286 lines
11 KiB
Luau
286 lines
11 KiB
Luau
--!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.
|
|
-- 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 Decode = require("@formats/image/jpeg/Decode")
|
|
local Encode = require("@formats/image/jpeg/Encode")
|
|
|
|
-- ------------------------------------------------------------------------------------------------ contract
|
|
local Jpeg = {
|
|
name = "jpeg",
|
|
category = "image",
|
|
extensions = { "jpg", "jpeg", "jpe", "jfif" },
|
|
mime = { "image/jpeg" },
|
|
deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" },
|
|
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 = {
|
|
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 }
|
|
|
|
-- ------------------------------------------------------------------------------------------------ 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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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 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,
|
|
density = density,
|
|
})
|
|
return out, nil
|
|
end
|
|
|
|
return Jpeg
|