388 lines
15 KiB
Luau
388 lines
15 KiB
Luau
--!strict
|
|
-- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
|
|
-- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and
|
|
-- arithmetic scan decoding, IDCTs through codecs/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder)
|
|
-- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's
|
|
-- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md.
|
|
--
|
|
-- local img, err = Jpeg.decode(buf, off?, len?, opts?) -- one JPEG -> rgba8 (or gray8 / yuv420p) Types.Image
|
|
-- local img = Jpeg.decode(frame, 0, n, { yuv = true }) -- video: yuv420p straight from the IDCT planes
|
|
-- local out, err = Jpeg.encode(img, opts?) -- rgba8 / rgb8 / gray8 / yuv420p Image -> buffer
|
|
-- local info, err = Jpeg.info(buf, off?, len?) -- the headers up to the frame header
|
|
--
|
|
-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit
|
|
-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt
|
|
-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8), EXIF orientation
|
|
-- (meta.orientation, applied with opts.orient). Truncated or corrupt scans decode as far as they go
|
|
-- (meta.truncated = true).
|
|
-- Motion-JPEG: frames without DHT segments use the T.81 annex K tables; the AVI1 APP0 segment is read (its field
|
|
-- polarity) and data after EOI is ignored. Two fields back to back (AVI1 interlaced: two JPEGs of half the frame
|
|
-- height, polarity 1 or 2, or opts.fields = true) are decoded and woven into one frame, the first field on the even
|
|
-- rows (top field first, as ffmpeg, which ignores the polarity value); a missing or different-sized second field
|
|
-- leaves the first field alone (meta.source.fields = 1).
|
|
-- opts.yuv: 8-bit YCbCr frames come out as yuv420p (full-range BT.601, meta.source.range = "full") without colour
|
|
-- conversion or upsampling: 4:2:0 (2x2 luma) as the planes are; 4:2:2 (2x1 luma, the usual Motion-JPEG camera
|
|
-- layout) with each pair of chroma rows averaged; 4:4:4 with 2 x 2 chroma averages; grey with chroma 128. Other
|
|
-- layouts (RGB, CMYK, 4:1:1, 4:4:0, 12-bit) and scaled decodes fall back to rgba8 (check img.format).
|
|
-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or
|
|
-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, extra APPn / COM segments
|
|
-- (opts.segments); yuv420p input is coded from its planes as they are (4:2:0, no colour conversion).
|
|
-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, 12-bit or CMYK encoding.
|
|
-- Never throws: bad data or arguments return nil, Err.
|
|
local Err = require("@formats/core/Err")
|
|
local Types = require("@formats/Types")
|
|
local Decode = require("@formats/codecs/Jpeg/Decode")
|
|
local Encode = require("@formats/codecs/Jpeg/Encode")
|
|
local Yuv = require("@formats/codecs/Jpeg/Yuv")
|
|
|
|
local Jpeg = {}
|
|
|
|
export type DecodeOptions = {
|
|
scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only)
|
|
orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only; rgba8 / gray8)
|
|
native: boolean?, -- grey files decode to gray8 (default false: rgba8)
|
|
yuv: boolean?, -- 8-bit YCbCr / grey frames decode to yuv420p (default false); see the header for the layouts
|
|
fields: boolean?, -- two JPEGs back to back are two fields of one frame (default: when the AVI1 segment says so)
|
|
maxPixels: number?, -- refuse larger images (default 2^26)
|
|
}
|
|
export type EncodeOptions = {
|
|
quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables
|
|
subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420"; yuv420p input is always 4:2:0)
|
|
progressive: boolean?, -- default false
|
|
optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises)
|
|
gray: boolean?, -- a one-component file (default: true for gray8 images)
|
|
restart: number?, -- restart interval in MCUs (default 0 = none)
|
|
jfif: boolean?, -- write the JFIF APP0 header (default true)
|
|
density: { unit: number, x: number, y: number }?, -- the JFIF density (default unit 0, 1 x 1)
|
|
segments: { { marker: number, data: buffer } }?, -- APPn / COM segments written after the JFIF header
|
|
}
|
|
|
|
export type Info = {
|
|
width: number,
|
|
height: number,
|
|
components: number,
|
|
progressive: boolean,
|
|
arithmetic: boolean,
|
|
precision: number,
|
|
colorSpace: string,
|
|
sampling: { { number } }, -- { h, v } per component
|
|
orientation: number,
|
|
adobe: number?,
|
|
jfif: boolean,
|
|
avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header
|
|
}
|
|
|
|
local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG }
|
|
|
|
local function range(buf: buffer, off: number?, len: number?): (number, number)
|
|
local n = buffer.len(buf)
|
|
local o = math.clamp(math.floor(tonumber(off) or 0), 0, n)
|
|
return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o)
|
|
end
|
|
|
|
-- the marker parser over [o, o + l): State | nil, Err
|
|
local function parse(buf: buffer, o: number, l: number, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?)
|
|
local ok, st, code, msg = pcall(Decode.parse, buf, o, o + l, opts, headerOnly)
|
|
if not ok then
|
|
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st))
|
|
end
|
|
if not st then
|
|
return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed", o)
|
|
end
|
|
return st, nil
|
|
end
|
|
|
|
local function samplingOf(f: any): { { number } }
|
|
local sampling = {}
|
|
for _, c in f.comps do
|
|
table.insert(sampling, { c.h, c.v })
|
|
end
|
|
return sampling
|
|
end
|
|
|
|
-- info(buf, off?, len?) -> Info | nil, Err (reads the headers up to the frame header)
|
|
function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?)
|
|
if type(buf) ~= "buffer" then
|
|
return nil, Err.new(Err.ARG, "expected a buffer")
|
|
end
|
|
local o, l = range(buf, off, len)
|
|
local st, err = parse(buf, o, l, nil, true)
|
|
if not st then
|
|
return nil, err
|
|
end
|
|
local f = st.frame
|
|
return {
|
|
width = f.width,
|
|
height = f.height,
|
|
components = #f.comps,
|
|
progressive = f.progressive,
|
|
arithmetic = f.arithmetic,
|
|
precision = f.precision,
|
|
colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif),
|
|
sampling = samplingOf(f),
|
|
orientation = st.orientation,
|
|
adobe = st.adobe,
|
|
jfif = st.jfif,
|
|
avi1 = st.avi1,
|
|
},
|
|
nil
|
|
end
|
|
|
|
-- the EXIF orientation applied to rgba8 pixels: buffer, width, height
|
|
local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number)
|
|
if o <= 1 or o > 8 then
|
|
return px, w, h
|
|
end
|
|
local swap = o >= 5
|
|
local ow, oh = if swap then h else w, if swap then w else h
|
|
local out = buffer.create(ow * oh * 4)
|
|
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
|
for y = 0, oh - 1 do
|
|
for x = 0, ow - 1 do
|
|
local col, row
|
|
if o == 2 then
|
|
col, row = w - 1 - x, y
|
|
elseif o == 3 then
|
|
col, row = w - 1 - x, h - 1 - y
|
|
elseif o == 4 then
|
|
col, row = x, h - 1 - y
|
|
elseif o == 5 then
|
|
col, row = y, x
|
|
elseif o == 6 then
|
|
col, row = y, h - 1 - x
|
|
elseif o == 7 then
|
|
col, row = w - 1 - y, h - 1 - x
|
|
else
|
|
col, row = w - 1 - y, x
|
|
end
|
|
writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4))
|
|
end
|
|
end
|
|
return out, ow, oh
|
|
end
|
|
|
|
-- one JPEG at [o, o + l): Image, State | nil, Err
|
|
local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions?): (Types.Image?, any)
|
|
local st, err = parse(buf, o, l, opts, false)
|
|
if not st then
|
|
return nil, err
|
|
end
|
|
local s = st :: Decode.State
|
|
local img = Types.Image.new(0, 0)
|
|
local space, mode = nil, nil
|
|
if opts and opts.yuv then
|
|
local ok, w, h, px, m = pcall(Decode.outputYuv, s)
|
|
if not ok then
|
|
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
|
|
end
|
|
if w then
|
|
img.width, img.height, img.pixels, img.format = w, h :: number, px :: buffer, "yuv420p"
|
|
mode = m
|
|
space = Decode.colorSpaceOf(s.frame, s.adobe, s.jfif)
|
|
end
|
|
end
|
|
if not mode then
|
|
local ok, w, h, px, sp = pcall(Decode.output, s)
|
|
if not ok then
|
|
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
|
|
end
|
|
if not w then
|
|
return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px), o)
|
|
end
|
|
space = sp
|
|
if opts and opts.orient then
|
|
px, w, h = orient(px, w, h, s.orientation)
|
|
end
|
|
img.width, img.height, img.pixels = w, h, px
|
|
if opts and opts.native and space == "gray" then
|
|
local g = buffer.create(w * h)
|
|
for i = 0, w * h - 1 do
|
|
buffer.writeu8(g, i, buffer.readu8(px, i * 4))
|
|
end
|
|
img.pixels, img.format = g, "gray8"
|
|
end
|
|
end
|
|
local f = s.frame
|
|
local meta = img.meta
|
|
meta.orientation = s.orientation
|
|
meta.oriented = (opts and opts.orient and not mode) or false
|
|
meta.exif = s.exif
|
|
meta.icc = s.icc
|
|
if #s.comments > 0 then
|
|
meta.text = { comment = table.concat(s.comments, "\n") }
|
|
end
|
|
if s.density and s.density.unit > 0 and s.density.x > 0 and s.density.y > 0 then
|
|
local k = if s.density.unit == 2 then 2.54 else 1
|
|
meta.dpi = { x = s.density.x * k, y = s.density.y * k }
|
|
end
|
|
meta.truncated = s.truncated
|
|
meta.source = {
|
|
format = "jpeg",
|
|
bitDepth = f.precision,
|
|
colorType = space,
|
|
components = #f.comps,
|
|
progressive = f.progressive,
|
|
arithmetic = f.arithmetic,
|
|
sampling = samplingOf(f),
|
|
scale = s.scale,
|
|
adobe = s.adobe,
|
|
jfif = s.jfif,
|
|
avi1 = s.avi1,
|
|
yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv)
|
|
range = if mode then "full" else nil,
|
|
fields = 1,
|
|
}
|
|
return img, s
|
|
end
|
|
|
|
-- the start of a second JPEG (FF D8 FF) at or after p, before e; -1 if none
|
|
local function nextSoi(buf: buffer, p: number, e: number): number
|
|
local readu8 = buffer.readu8
|
|
while p + 3 <= e do
|
|
if readu8(buf, p) == 0xFF and readu8(buf, p + 1) == 0xD8 and readu8(buf, p + 2) == 0xFF then
|
|
return p
|
|
end
|
|
p += 1
|
|
end
|
|
return -1
|
|
end
|
|
|
|
-- two fields (same size and format) -> one frame of twice the height, field a on the even rows
|
|
local function weave(a: Types.Image, b: Types.Image): Types.Image
|
|
local w, hf = a.width, a.height
|
|
local h = hf * 2
|
|
local out = Types.Image.new(w, h, a.format)
|
|
local dst = out.pixels
|
|
if a.format == "yuv420p" then
|
|
local cw, chf = (w + 1) // 2, (hf + 1) // 2
|
|
local ch = (h + 1) // 2 -- = hf
|
|
Yuv.weave(a.pixels, 0, b.pixels, 0, w, h, dst, 0)
|
|
for k = 0, 1 do
|
|
Yuv.weave(a.pixels, w * hf + k * cw * chf, b.pixels, w * hf + k * cw * chf, cw, ch, dst, w * h + k * cw * ch)
|
|
end
|
|
else
|
|
local bpp = Types.Image.bpp(a.format) or 4
|
|
Yuv.weave(a.pixels, 0, b.pixels, 0, w * bpp, h, dst, 0)
|
|
end
|
|
out.meta = a.meta
|
|
return out
|
|
end
|
|
|
|
-- decode(buf, off?, len?, opts?) -> Image | nil, Err: one JPEG (or one interlaced Motion-JPEG frame) in [off, off + len)
|
|
function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
|
if type(buf) ~= "buffer" then
|
|
return nil, Err.new(Err.ARG, "expected a buffer")
|
|
end
|
|
if opts ~= nil and type(opts) ~= "table" then
|
|
return nil, Err.new(Err.ARG, "options must be a table")
|
|
end
|
|
local o, l = range(buf, off, len)
|
|
local img, st = decodeOne(buf, o, l, opts)
|
|
if not img then
|
|
return nil, st
|
|
end
|
|
local s = st :: Decode.State
|
|
local wantFields = if opts and opts.fields ~= nil then opts.fields else (s.avi1 == 1 or s.avi1 == 2)
|
|
if wantFields and not (opts and opts.orient) then
|
|
local e = o + l
|
|
local p = nextSoi(buf, s.endPos, e)
|
|
if p >= 0 then
|
|
local o2 = table.clone(opts or {}) :: any
|
|
if o2.maxPixels then
|
|
o2.maxPixels = math.max(0, o2.maxPixels - img.width * img.height)
|
|
end
|
|
local b = decodeOne(buf, p, e - p, o2)
|
|
if b and b.width == img.width and b.height == img.height and b.format == img.format then
|
|
local truncated = img.meta.truncated or b.meta.truncated
|
|
img = weave(img, b)
|
|
img.meta.truncated = truncated
|
|
local source: any = img.meta.source
|
|
source.fields = 2
|
|
end
|
|
end
|
|
end
|
|
return img, nil
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ encode
|
|
local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 }
|
|
|
|
-- encode(img, opts?) -> buffer | nil, Err: an rgba8 / rgb8 / gray8 / yuv420p Image as a baseline or progressive JPEG
|
|
function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
|
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then
|
|
return nil, Err.new(Err.ARG, "needs an Image")
|
|
end
|
|
local bpp = BPP[img.format]
|
|
if not bpp then
|
|
return nil, Err.new(Err.ARG, "needs an rgba8, rgb8, gray8 or yuv420p Image (got " .. tostring(img.format) .. ")")
|
|
end
|
|
local w, h = img.width, img.height
|
|
local need = if bpp == 0 then w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) else w * h * bpp
|
|
if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < need then
|
|
return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
|
|
end
|
|
if opts ~= nil and type(opts) ~= "table" then
|
|
return nil, Err.new(Err.ARG, "options must be a table")
|
|
end
|
|
local o: any = opts or {}
|
|
local quality = o.quality or 90
|
|
if type(quality) ~= "number" or quality < 1 or quality > 100 then
|
|
return nil, Err.new(Err.ARG, "quality must be 1..100")
|
|
end
|
|
local sub = o.subsampling or "420"
|
|
if sub ~= "420" and sub ~= "422" and sub ~= "444" then
|
|
return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"")
|
|
end
|
|
if bpp == 0 then
|
|
sub = "420"
|
|
end
|
|
local restart = o.restart or 0
|
|
if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then
|
|
return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs")
|
|
end
|
|
local gray = o.gray
|
|
if gray == nil then
|
|
gray = img.format == "gray8"
|
|
end
|
|
local segments = {}
|
|
if o.segments ~= nil then
|
|
if type(o.segments) ~= "table" then
|
|
return nil, Err.new(Err.ARG, "segments must be a list of { marker, data }")
|
|
end
|
|
for _, sg in o.segments do
|
|
if type(sg) ~= "table" or type(sg.data) ~= "buffer" or buffer.len(sg.data) > 65533 or type(sg.marker) ~= "number" then
|
|
return nil, Err.new(Err.ARG, "bad segment (marker 0xE0..0xEF / 0xFE, at most 65533 bytes)")
|
|
end
|
|
if not ((sg.marker >= 0xE0 and sg.marker <= 0xEF) or sg.marker == 0xFE) then
|
|
return nil, Err.new(Err.ARG, "bad segment marker (0xE0..0xEF / 0xFE)")
|
|
end
|
|
table.insert(segments, sg)
|
|
end
|
|
end
|
|
local density = o.density
|
|
if density ~= nil then
|
|
if type(density) ~= "table" or type(density.unit) ~= "number" or type(density.x) ~= "number" or type(density.y) ~= "number" then
|
|
return nil, Err.new(Err.ARG, "bad density")
|
|
end
|
|
density = {
|
|
unit = math.clamp(math.floor(density.unit), 0, 2),
|
|
x = math.clamp(math.floor(density.x), 1, 65535),
|
|
y = math.clamp(math.floor(density.y), 1, 65535),
|
|
}
|
|
end
|
|
local out = Encode.run(img.pixels, w, h, bpp, {
|
|
quality = quality,
|
|
sampling = sub,
|
|
progressive = o.progressive == true,
|
|
optimize = o.optimize == true,
|
|
gray = gray,
|
|
restart = restart,
|
|
segments = segments,
|
|
jfif = o.jfif ~= false,
|
|
density = density,
|
|
})
|
|
return out, nil
|
|
end
|
|
|
|
return Jpeg
|