ws-video-codecs: codecs/Jpeg (the JPEG engine moved down from image/jpeg; byte-range API, yuv420p decode / encode, AVI1 fields); image/jpeg is a thin format over it

This commit is contained in:
4DBug committed 2026-10-31 09:28:38 -05:00
1 parent 646d18f056
commit 2ca0d1f10a
12 files changed
+653 -236

No files matched your search

+75 -211
View File
@@ -1,7 +1,10 @@
--!strict
-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81). Absorbed from jpeg-luau 1.0 (same author: the Huffman decoder, IDCTs,
-- upsampling and colour conversion, bit-exact with libjpeg-turbo's djpeg) and extended with arithmetic coding, meta
-- (EXIF, ICC, comments, density) and an encoder. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md.
-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/Jpeg (the engine, shared with the Motion-JPEG
-- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical
-- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the
-- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi
-- (JFIF density) are written from the Image on encode and read back on decode. Encode also takes yuv420p Images
-- (coded 4:2:0 from the planes as they are).
-- 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 through libjpeg's
@@ -17,8 +20,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Decode = require("@formats/image/jpeg/Decode")
local Encode = require("@formats/image/jpeg/Encode")
local Codec = require("@formats/codecs/Jpeg")
-- ------------------------------------------------------------------------------------------------ contract
local Jpeg = {
@@ -26,7 +28,7 @@ local Jpeg = {
category = "image",
extensions = { "jpg", "jpeg", "jpe", "jfif" },
mime = { "image/jpeg" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" },
caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
}
@@ -48,22 +50,7 @@ export type EncodeOptions = {
meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true)
}
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,
}
-- ------------------------------------------------------------------------------------------------ constants
local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG }
export type Info = Codec.Info
-- ------------------------------------------------------------------------------------------------ sniff
function Jpeg.sniff(r: Bytes.Reader): number
@@ -72,214 +59,91 @@ function Jpeg.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
local function parse(r: Bytes.Reader, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?)
local ok, st, code, msg = pcall(Decode.parse, r.buf, r.base, r.limit, 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")
end
return st, nil
end
-- info(r) -> Info | nil, Err (reads the headers up to the frame header)
function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?)
local st, err = parse(r, nil, true)
if not st then
return nil, err
end
local f = st.frame
local sampling = {}
for _, c in f.comps do
table.insert(sampling, { c.h, c.v })
end
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 = sampling,
orientation = st.orientation,
adobe = st.adobe,
jfif = st.jfif,
},
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
return Codec.info(r.buf, r.base, r.limit - r.base)
end
function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local st, err = parse(r, opts, false)
if not st then
return nil, err
if opts ~= nil and type(opts) ~= "table" then
return nil, Err.new(Err.ARG, "options must be a table")
end
local ok, w, h, px, space = pcall(Decode.output, st :: Decode.State)
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))
end
local orientation = st.orientation
if opts and opts.orient then
px, w, h = orient(px, w, h, orientation)
end
local img = Types.Image.new(1, 1)
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
local f = st.frame
local sampling = {}
for _, c in f.comps do
table.insert(sampling, { c.h, c.v })
end
img.meta.orientation = orientation
img.meta.oriented = (opts and opts.orient) or false
img.meta.exif = st.exif
img.meta.icc = st.icc
if #st.comments > 0 then
img.meta.text = { comment = table.concat(st.comments, "\n") }
end
if st.density and st.density.unit > 0 and st.density.x > 0 and st.density.y > 0 then
local k = if st.density.unit == 2 then 2.54 else 1
img.meta.dpi = { x = st.density.x * k, y = st.density.y * k }
end
img.meta.truncated = st.truncated
img.meta.source = {
format = "jpeg",
bitDepth = f.precision,
colorType = space,
components = #f.comps,
progressive = f.progressive,
arithmetic = f.arithmetic,
sampling = sampling,
scale = st.scale,
adobe = st.adobe,
jfif = st.jfif,
}
return img, nil
local o = opts or {} :: DecodeOptions
-- one image: no yuv output, no field weaving (two JPEGs back to back are an image and a preview, as in MPF)
return Codec.decode(r.buf, r.base, r.limit - r.base, {
scale = o.scale,
orient = o.orient,
native = o.native,
maxPixels = o.maxPixels,
fields = false,
})
end
-- ------------------------------------------------------------------------------------------------ encode
local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1 }
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 or gray8 Image (got " .. tostring(img.format) .. ")")
end
local w, h = img.width, img.height
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) < w * h * bpp then
return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
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
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
-- the APP1 / APP2 / COM segments and the JFIF density from img.meta
local function metaSegments(meta: any): ({ { marker: number, data: buffer } }, { unit: number, x: number, y: number }?)
local segments = {}
local meta = img.meta or {}
if o.meta ~= false then
if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then
local d = buffer.create(buffer.len(meta.exif) + 6)
buffer.writestring(d, 0, "Exif\0\0")
buffer.copy(d, 6, meta.exif)
table.insert(segments, { marker = 0xE1, data = d })
end
if type(meta.icc) == "buffer" then
local icc = meta.icc :: buffer
local n = buffer.len(icc)
local chunk = 65519
local count = math.max(1, math.ceil(n / chunk))
if count <= 255 then
for i = 1, count do
local a = (i - 1) * chunk
local l = math.min(chunk, n - a)
local d = buffer.create(l + 14)
buffer.writestring(d, 0, "ICC_PROFILE\0")
buffer.writeu8(d, 12, i)
buffer.writeu8(d, 13, count)
buffer.copy(d, 14, icc, a, l)
table.insert(segments, { marker = 0xE2, data = d })
end
if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then
local d = buffer.create(buffer.len(meta.exif) + 6)
buffer.writestring(d, 0, "Exif\0\0")
buffer.copy(d, 6, meta.exif)
table.insert(segments, { marker = 0xE1, data = d })
end
if type(meta.icc) == "buffer" then
local icc = meta.icc :: buffer
local n = buffer.len(icc)
local chunk = 65519
local count = math.max(1, math.ceil(n / chunk))
if count <= 255 then
for i = 1, count do
local a = (i - 1) * chunk
local l = math.min(chunk, n - a)
local d = buffer.create(l + 14)
buffer.writestring(d, 0, "ICC_PROFILE\0")
buffer.writeu8(d, 12, i)
buffer.writeu8(d, 13, count)
buffer.copy(d, 14, icc, a, l)
table.insert(segments, { marker = 0xE2, data = d })
end
end
local text = meta.text
if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then
table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) })
end
end
local text = meta.text
if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then
table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) })
end
local density = nil
if type(meta.dpi) == "table" and type(meta.dpi.x) == "number" and type(meta.dpi.y) == "number" then
density = { unit = 1, x = math.clamp(math.floor(meta.dpi.x + 0.5), 1, 65535), y = math.clamp(math.floor(meta.dpi.y + 0.5), 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,
return segments, density
end
function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" then
return nil, Err.new(Err.ARG, "needs an Image")
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 segments, density = {}, nil
if o.meta ~= false then
segments, density = metaSegments(img.meta or {})
elseif type(img.meta) == "table" then
local _
_, density = metaSegments({ dpi = img.meta.dpi })
end
return Codec.encode(img, {
quality = o.quality,
subsampling = o.subsampling,
progressive = o.progressive,
optimize = o.optimize,
gray = o.gray,
restart = o.restart,
jfif = o.jfif,
density = density,
segments = segments,
})
return out, nil
end
return Jpeg