Files
rosetta/src/Formats/image/jpeg/init.luau
T

150 lines
6.7 KiB
Luau

--!strict
-- 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
-- reduced IDCTs), EXIF orientation reported in meta.orientation and applied with opts.orient. Truncated or corrupt
-- scans decode as far as they go (meta.truncated = true).
-- 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, EXIF / ICC / comment segments from meta;
-- byte-identical to cjpeg for the same settings.
-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, ICC colour management, 12-bit
-- or CMYK encoding.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Codec = require("@formats/codecs/Jpeg")
-- ------------------------------------------------------------------------------------------------ contract
local Jpeg = {
name = "jpeg",
category = "image",
extensions = { "jpg", "jpeg", "jpe", "jfif" },
mime = { "image/jpeg" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" },
caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
}
-- ------------------------------------------------------------------------------------------------ types
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)
native: boolean?, -- grey files decode to gray8 (default false: rgba8)
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")
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)
meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true)
}
export type Info = Codec.Info
-- ------------------------------------------------------------------------------------------------ sniff
function Jpeg.sniff(r: Bytes.Reader): number
local s = r:peek(3)
return if s == "\255\216\255" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- info(r) -> Info | nil, Err (reads the headers up to the frame header)
function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?)
return Codec.info(r.buf, r.base, r.limit - r.base)
end
function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
if opts ~= nil and type(opts) ~= "table" then
return nil, Err.new(Err.ARG, "options must be a table")
end
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
-- 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 = {}
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
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
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,
})
end
return Jpeg