Merge branch 'ws/cm-image' into ws/cm-codecs
This commit is contained in:
commit
84f3426217
30 files changed
+224
-770
No files matched your search
+13
-13
@@ -230,20 +230,20 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
|
||||
- codecs/font/GlyphNames: PostScript glyph names -> Unicode (AGL specification) and Adobe StandardEncoding.
|
||||
- codecs/font/TrueType: the sfnt container (.ttf, .otf with CFF outlines, .ttc collections) as the standard Font value.
|
||||
- **image**
|
||||
- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...):
|
||||
- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
|
||||
- codecs/image/Bcn: BC1-BC7 block-compressed textures with the D3D11 rules.
|
||||
- codecs/image/Blend: rgba8 layer compositing (straight alpha) with the W3C Compositing and Blending Level 1 modes.
|
||||
- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
|
||||
- codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar
|
||||
- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H,
|
||||
- codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
|
||||
- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP,
|
||||
- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
|
||||
- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
|
||||
- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers
|
||||
- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...):
|
||||
- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
|
||||
- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
|
||||
- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
|
||||
- codecs/image/Etc: ETC1 / ETC2 / EAC block texture decoding (Khronos Data Format Specification 1.3, section 21).
|
||||
- codecs/image/Half: IEEE 754 binary16 <-> number (round to nearest even, overflow to infinity). New in rosetta.
|
||||
- codecs/image/Jpeg: the JPEG codec (ITU T.81), bit-exact with libjpeg-turbo's djpeg and byte-identical with cjpeg.
|
||||
- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB.
|
||||
- codecs/image/Quantize: palette quantization of rgba8 pixels (median cut or octree, Floyd-Steinberg dithering).
|
||||
- codecs/image/Raster: an antialiased scanline rasterizer (nonzero / even-odd) for line and Bézier paths, plus a stroker.
|
||||
- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats. New in rosetta.
|
||||
- codecs/image/Texture: one entry point over the texture pixel codecs (Bcn, Etc, Texel). New in rosetta.
|
||||
- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only.
|
||||
- codecs/image/Vp8L: WebP lossless (VP8L, RFC 9649 section 3).
|
||||
- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8, BT.601 / BT.709, limited or full range.
|
||||
- **model**
|
||||
- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7).
|
||||
- codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers.
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Bcn/Decode: the BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC). Ported from Pillow's
|
||||
-- src/libImaging/BcnDecode.c (CC0, licenses/pillow-bcn-CC0.txt) and changed to follow the D3D11 functional spec where
|
||||
-- Pillow does not: BC6H interpolation rounds ((a * (64 - w) + b * w + 32) >> 6), BC6H keeps its float values (no 8-bit
|
||||
-- clamp), BC7's reserved mode 8 and BC6H's reserved modes decode to transparent / zero, BC4 / BC5 SNORM interpolate
|
||||
-- the signed values (-128 reads as -127). Each decoder writes one 4x4 block into a 64-byte (rgba8) or 256-byte
|
||||
-- (rgbaf32) scratch block; the caller clips it into the image. Never throws: the caller checks the source size.
|
||||
-- codecs/image/Bcn/Decode: BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC), ported from Pillow's BcnDecode.c
|
||||
-- (CC0, licenses/pillow-bcn-CC0.txt). Follows the D3D11 functional spec where Pillow does not: BC6H rounds
|
||||
-- (a * (64 - w) + b * w + 32) >> 6 and keeps floats, reserved modes decode to zero, SNORM -128 reads as -127.
|
||||
local Half = require("@rosetta/codecs/image/Half")
|
||||
|
||||
local Decode = {}
|
||||
@@ -15,8 +12,7 @@ local readu8, readu16, readu32, writeu8, writeu32, writef32 = buffer.readu8, buf
|
||||
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
|
||||
local HALF = Half.TABLE
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC1 / BC2 / BC3
|
||||
local pal = buffer.create(16) -- 4 rgba8 colours
|
||||
local pal = buffer.create(16)
|
||||
|
||||
local function c565(c: number): (number, number, number)
|
||||
local r = rshift(band(c, 0xF800), 8)
|
||||
@@ -25,7 +21,7 @@ local function c565(c: number): (number, number, number)
|
||||
return bor(r, rshift(r, 5)), bor(g, rshift(g, 6)), bor(b, rshift(b, 5))
|
||||
end
|
||||
|
||||
-- the BC1 colour block at p into blk (64 bytes); fourColour = BC2 / BC3 (always the 4-colour palette)
|
||||
-- BC2 / BC3 colour blocks always use the 4-colour palette
|
||||
local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean)
|
||||
local c0, c1 = readu16(src, p), readu16(src, p + 2)
|
||||
local r0, g0, b0 = c565(c0)
|
||||
@@ -45,7 +41,6 @@ local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean)
|
||||
end
|
||||
end
|
||||
|
||||
-- the 8 values of a BC3 alpha / BC4 block (unsigned) into vals
|
||||
local vals = table.create(8, 0)
|
||||
local function ramp8(a0: number, a1: number)
|
||||
vals[1], vals[2] = a0, a1
|
||||
@@ -78,7 +73,6 @@ local function ramp8s(u0: number, u1: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- one 8-byte BC3 alpha / BC4 block at p into byte `channel` of every blk pixel (and the next ones when spread)
|
||||
local function single(src: buffer, p: number, blk: buffer, channel: number, signed: boolean, spread: boolean)
|
||||
if signed then
|
||||
ramp8s(readu8(src, p), readu8(src, p + 1))
|
||||
@@ -138,7 +132,6 @@ function Decode.bc5s(src: buffer, p: number, blk: buffer)
|
||||
bc5(src, p, blk, true)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BPTC tables
|
||||
-- partition tables (BC7 Table.P2 1 bit per pixel, Table.P3 2 bits per pixel) and the anchor indices
|
||||
local SI2 = {
|
||||
0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000,
|
||||
@@ -182,7 +175,6 @@ local function subset(ns: number, part: number, i: number): number
|
||||
return 0
|
||||
end
|
||||
|
||||
-- the 128-bit block as four u32 words: bits(at, n) for n <= 16
|
||||
local w0, w1, w2, w3 = 0, 0, 0, 0
|
||||
local function load(src: buffer, p: number)
|
||||
w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12)
|
||||
@@ -202,7 +194,6 @@ local function bits(at: number, n: number): number
|
||||
return band(v, lshift(1, n) - 1)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC7
|
||||
-- ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2
|
||||
local MODES7 = {
|
||||
{ 3, 4, 0, 0, 4, 0, 1, 0, 3, 0 },
|
||||
@@ -341,7 +332,6 @@ function Decode.bc7(src: buffer, p: number, blk: buffer)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC6H
|
||||
-- ns, transformed, pb, epb, rb, gb, bb
|
||||
local MODES6 = {
|
||||
{ 2, 1, 5, 10, 5, 5, 5 },
|
||||
@@ -420,7 +410,6 @@ local function finish(v: number, signed: boolean): number
|
||||
return HALF[(v * 31) // 64]
|
||||
end
|
||||
|
||||
-- one BC6H block into blk as rgbaf32 (256 bytes, alpha 1)
|
||||
function Decode.bc6h(src: buffer, p: number, blk: buffer, signed: boolean)
|
||||
load(src, p)
|
||||
local m = band(w0, 31)
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders (new in rosetta; the approach follows stb_dxt by
|
||||
-- Fabian Giesen / Sean Barrett, public domain: the principal axis of the block's colours by power iteration, the
|
||||
-- extreme pixels along it as endpoints, then least-squares refinement of the endpoints for the chosen indices, keeping
|
||||
-- the best; single-colour blocks use exact endpoint tables). Indices are chosen against the palette exactly as
|
||||
-- Bcn/Decode rebuilds it. BC4 / BC5 channels try both the 8-value and the 6-value (+ 0 / 255) ramps. Never throws.
|
||||
-- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders, new in rosetta; the approach follows stb_dxt (Fabian
|
||||
-- Giesen / Sean Barrett, public domain): principal axis endpoints, least-squares refinement, exact single-colour tables.
|
||||
local Encode = {}
|
||||
|
||||
local readu8, writeu8, writeu16, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu16, buffer.writeu32
|
||||
@@ -18,7 +15,6 @@ local function exp6(v: number): number
|
||||
return bor(lshift(v, 2), rshift(v, 4))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ single colours
|
||||
-- OM[k][v + 1] = e0 * 256 + e1 (quantized) whose colour-2 value (4-colour: (2 e0 + e1) // 3; 3-colour: (e0 + e1)
|
||||
-- // 2) is closest to v; k = 1 / 2 for 5-bit (4 / 3 colour), 3 / 4 for 6-bit
|
||||
local OM: { { number } }? = nil
|
||||
@@ -56,7 +52,6 @@ local function singleTables(): { { number } }
|
||||
return t
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC1 colour
|
||||
local R, G, B, A = table.create(16, 0), table.create(16, 0), table.create(16, 0), table.create(16, 0)
|
||||
local USE = table.create(16, true)
|
||||
local PR, PG, PB = table.create(4, 0), table.create(4, 0), table.create(4, 0)
|
||||
@@ -77,7 +72,6 @@ local function palette(c0: number, c1: number, four: boolean)
|
||||
end
|
||||
end
|
||||
|
||||
-- indices for the palette into IDX (0-based); returns the squared error of the used pixels
|
||||
local function assign(four: boolean): number
|
||||
local n = if four then 4 else 3
|
||||
local total = 0
|
||||
@@ -108,11 +102,9 @@ local function q565(r: number, g: number, b: number): number
|
||||
return qr * 2048 + qg * 32 + qb
|
||||
end
|
||||
|
||||
-- the endpoint weights of index k (the e0 share)
|
||||
local W4 = { 1, 0, 2 / 3, 1 / 3 }
|
||||
local W3 = { 1, 0, 0.5, 0 }
|
||||
|
||||
-- least squares endpoints for the current IDX: c0, c1 or nil when degenerate
|
||||
local function refine(four: boolean): (number?, number?)
|
||||
local W = if four then W4 else W3
|
||||
local aa, bb, ab = 0, 0, 0
|
||||
@@ -142,8 +134,6 @@ local function refine(four: boolean): (number?, number?)
|
||||
return q565(r0, g0, b0), q565(r1, g1, b1)
|
||||
end
|
||||
|
||||
-- encodes R / G / B (USE marks the pixels that count) as a BC1 colour block at out[o]; four = 4-colour mode
|
||||
-- (opaque), else the 3-colour mode with index 3 for the unused (transparent) pixels
|
||||
local function colourBlock(out: buffer, o: number, four: boolean)
|
||||
local n, mr, mg, mb = 0, 0, 0, 0
|
||||
for i = 1, 16 do
|
||||
@@ -276,7 +266,6 @@ local function colourBlock(out: buffer, o: number, four: boolean)
|
||||
writeu32(out, o + 4, bitsv)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC4 channel
|
||||
local V = table.create(16, 0)
|
||||
local RAMP = table.create(8, 0)
|
||||
local SEL = table.create(16, 0)
|
||||
@@ -314,7 +303,6 @@ local function pick(): number
|
||||
return total
|
||||
end
|
||||
|
||||
-- encodes V[1..16] (0..255) as an 8-byte BC4 block at out[o]
|
||||
local function channelBlock(out: buffer, o: number)
|
||||
local lo, hi = 255, 0
|
||||
local lo2, hi2 = 255, 0
|
||||
@@ -380,8 +368,6 @@ local function channelBlock(out: buffer, o: number)
|
||||
writeu8(out, o + 7, rshift(hi24, 16))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ whole images
|
||||
-- the 4x4 block at bx, by of an rgba8 image into R / G / B / A (edge pixels repeat)
|
||||
local function gather(px: buffer, w: number, h: number, bx: number, by: number)
|
||||
for y = 0, 3 do
|
||||
local sy = math.min(by * 4 + y, h - 1)
|
||||
@@ -394,7 +380,6 @@ local function gather(px: buffer, w: number, h: number, bx: number, by: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- encode(kind, rgba8 pixels, w, h, alphaThreshold) -> the block data (kind = bc1 / bc3 / bc4 / bc5)
|
||||
function Encode.run(kind: string, px: buffer, w: number, h: number, threshold: number): buffer
|
||||
local bw, bh = (w + 3) // 4, (h + 3) // 4
|
||||
local bytes = if kind == "bc1" or kind == "bc4" then 8 else 16
|
||||
|
||||
@@ -1,26 +1,14 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...):
|
||||
-- decode of BC1 (DXT1, with the 3-colour + transparent mode), BC2 (DXT3), BC3 (DXT5), BC4 / BC5 (RGTC / ATI1 / ATI2,
|
||||
-- UNORM and SNORM), BC6H (UF16 / SF16, to rgbaf32) and BC7 (all 8 modes); encode of BC1 / BC3 / BC4 / BC5 (UNORM).
|
||||
-- Decoders ported from Pillow's BcnDecode.c (CC0) with the D3D11 rules; encoders new (stb_dxt-style). Never throws.
|
||||
--
|
||||
-- local px, err = Bcn.decode("bc7", buf, offset, w, h) -- rgba8 pixels (rgbaf32 for bc6h / bc6hs)
|
||||
-- local blocks = Bcn.encode("bc1", rgba8Pixels, w, h) -- the block data (row-major blocks)
|
||||
-- Bcn.size("bc3", w, h) -- bytes of a w x h image (whole 4x4 blocks)
|
||||
--
|
||||
-- Channels: BC4 decodes to grey (r = g = b, opaque), BC5 to red + green (blue 0, opaque); SNORM values are biased by
|
||||
-- 128 into rgba8 (-127 -> 1, 0 -> 128, 127 -> 255). BC1 / BC3 / BC5 encode reads R / G (BC4: R), BC1 alpha below
|
||||
-- opts.alphaThreshold (default 128) selects the transparent 3-colour mode.
|
||||
-- codecs/image/Bcn: BC1-BC7 block-compressed textures with the D3D11 rules.
|
||||
-- Decoders ported from Pillow's BcnDecode.c (CC0); encoders new (stb_dxt-style). SNORM is biased by 128 into rgba8.
|
||||
local Decode = require("@rosetta/codecs/image/Bcn/Decode")
|
||||
local Encode = require("@rosetta/codecs/image/Bcn/Encode")
|
||||
|
||||
local Bcn = {}
|
||||
|
||||
-- kind -> bytes per 4x4 block
|
||||
Bcn.BLOCK = table.freeze({ bc1 = 8, bc2 = 16, bc3 = 16, bc4 = 8, bc4s = 8, bc5 = 16, bc5s = 16, bc6h = 16, bc6hs = 16, bc7 = 16 }) :: { [string]: number }
|
||||
-- kinds that decode to rgbaf32
|
||||
Bcn.FLOAT = table.freeze({ bc6h = true, bc6hs = true }) :: { [string]: boolean }
|
||||
|
||||
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
||||
@@ -42,7 +30,6 @@ local BLOCKS: { [string]: (buffer, number, buffer) -> () } = {
|
||||
end,
|
||||
}
|
||||
|
||||
-- size(kind, w, h) -> bytes of the block data (nil for an unknown kind)
|
||||
function Bcn.size(kind: string, w: number, h: number): number?
|
||||
local b = Bcn.BLOCK[kind]
|
||||
if not b then
|
||||
@@ -51,8 +38,6 @@ function Bcn.size(kind: string, w: number, h: number): number?
|
||||
return ((w + 3) // 4) * ((h + 3) // 4) * b
|
||||
end
|
||||
|
||||
-- decode(kind, src, offset, w, h, out?, outOffset?) -> pixels (rgba8, or rgbaf32 for BC6H) | nil, message.
|
||||
-- out (optional) receives the pixels at outOffset (default 0) instead of a new buffer.
|
||||
function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?): (buffer?, string?)
|
||||
local fn = BLOCKS[kind]
|
||||
if not fn then
|
||||
@@ -103,10 +88,9 @@ function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: num
|
||||
end
|
||||
|
||||
export type EncodeOptions = {
|
||||
alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128; 0 = always opaque)
|
||||
alphaThreshold: number?,
|
||||
}
|
||||
|
||||
-- encode(kind, pixels, w, h, opts?) -> block data | nil, message. pixels: rgba8, w x h; kind = bc1 / bc3 / bc4 / bc5.
|
||||
function Bcn.encode(kind: string, px: buffer, w: number, h: number, opts: EncodeOptions?): (buffer?, string?)
|
||||
if kind ~= "bc1" and kind ~= "bc3" and kind ~= "bc4" and kind ~= "bc5" then
|
||||
return nil, "unsupported: no encoder for " .. tostring(kind)
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
|
||||
-- blend modes of the W3C Compositing and Blending Level 1 spec (the Photoshop / Aseprite set), opacity, a grey layer
|
||||
-- mask, clipping (source-atop: the backdrop keeps its alpha) and dissolve. Shared by ops/LayerOps (flatten) and the
|
||||
-- layered formats that must write a composite (layered/psd). Never throws: rectangles are clipped to both buffers.
|
||||
--
|
||||
-- Blend.composite(dst, dw, dh, src, sw, sh, x, y, opacity, "multiply", { clip = false, mask = m })
|
||||
-- Blend.MODES.multiply -> true
|
||||
--
|
||||
-- Mode names: normal dissolve darken multiply colorBurn linearBurn darkerColor lighten screen colorDodge linearDodge
|
||||
-- (= add) lighterColor overlay softLight hardLight vividLight linearLight pinLight hardMix difference exclusion
|
||||
-- subtract divide hue saturation color luminosity. Unknown names composite as normal.
|
||||
-- codecs/image/Blend: rgba8 layer compositing (straight alpha) with the W3C Compositing and Blending Level 1 modes.
|
||||
-- Clipping is source-atop (the backdrop keeps its alpha); unknown mode names composite as normal.
|
||||
local Blend = {}
|
||||
|
||||
local readu8, writeu8, readu32, writeu32, blen = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32, buffer.len
|
||||
@@ -164,9 +155,6 @@ local function setSat(r: number, g: number, b: number, s: number): (number, numb
|
||||
return (r - mn) * k, (g - mn) * k, (b - mn) * k
|
||||
end
|
||||
|
||||
-- composite(dst, dw, dh, src, sw, sh, x, y, opacity, mode, opts?): blends the sw x sh rgba8 src onto the dw x dh rgba8
|
||||
-- dst with its top-left at (x, y). opacity 0..1. opts.clip: keep the backdrop's alpha (clipping masks). opts.mask:
|
||||
-- { pixels: buffer (1 byte per pixel), width, height, x, y, default: 0..255 } in dst coordinates (outside it: default).
|
||||
local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: number, sh: number, x: number, y: number, opacity: number, mode: string?, opts: { clip: boolean?, mask: any? }?)
|
||||
x, y = floor(x), floor(y)
|
||||
if opacity <= 0 or dw <= 0 or dh <= 0 or sw <= 0 or sh <= 0 then
|
||||
@@ -216,7 +204,6 @@ local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: n
|
||||
if sa > 0 and not (clip and ba8 == 0) then
|
||||
local sr, sg, sb = readu8(src, so) / 255, readu8(src, so + 1) / 255, readu8(src, so + 2) / 255
|
||||
if ba8 == 0 then
|
||||
-- empty backdrop: the source as it is (alpha scaled)
|
||||
writeu32(dst, do_, readu32(src, so))
|
||||
writeu8(dst, do_ + 3, floor(sa * 255 + 0.5))
|
||||
else
|
||||
@@ -273,9 +260,6 @@ local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: n
|
||||
end
|
||||
end
|
||||
|
||||
-- lerp(dst, from, t, n, w?, mask?): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity);
|
||||
-- with a mask ({ pixels, width, height, x, y, default } as for composite, in the coordinates of a w-wide canvas) t is
|
||||
-- also scaled by the mask value of each pixel
|
||||
local function lerp(dst: buffer, from: buffer, t: number, n: number, w: number?, mask: any?)
|
||||
if blen(dst) < n * 4 or blen(from) < n * 4 then
|
||||
return
|
||||
@@ -312,7 +296,6 @@ end
|
||||
Blend.composite = composite
|
||||
Blend.lerp = lerp
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ layer trees
|
||||
local function isImage(v: any): boolean
|
||||
return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and buffer.len(v.pixels) >= v.width * v.height * 4
|
||||
end
|
||||
@@ -324,7 +307,7 @@ local function maskOf(l: any): any
|
||||
end
|
||||
local img = m.image
|
||||
local px = img.pixels
|
||||
if img.format == "rgba8" then -- use the red channel
|
||||
if img.format == "rgba8" then
|
||||
local n = img.width * img.height
|
||||
local g = buffer.create(n)
|
||||
for i = 0, n - 1 do
|
||||
@@ -349,7 +332,6 @@ local function compose(layers: { any }, canvas: buffer, w: number, h: number, hi
|
||||
end
|
||||
local opacity = (tonumber(l.opacity) or 1) * (tonumber(l.fillOpacity) or 1)
|
||||
local mode = if type(l.blend) == "string" then l.blend else "normal"
|
||||
-- the layer's own pixels, as an isolated w x h buffer
|
||||
local src: buffer? = nil
|
||||
if type(l.children) == "table" then
|
||||
if mode == "passThrough" then
|
||||
@@ -386,10 +368,6 @@ local function compose(layers: { any }, canvas: buffer, w: number, h: number, hi
|
||||
end
|
||||
end
|
||||
|
||||
-- flatten(layers, canvas, w, h, hidden): composites a Types.Layer tree (bottom to top) onto the w x h rgba8 canvas:
|
||||
-- blend modes, opacity x fillOpacity, groups (isolated, or "passThrough": blended straight onto the canvas, the group
|
||||
-- opacity and mask then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks.
|
||||
-- hidden = true includes invisible layers.
|
||||
function Blend.flatten(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean)
|
||||
if blen(canvas) >= w * h * 4 then
|
||||
compose(layers, canvas, w, h, hidden)
|
||||
|
||||
@@ -2,16 +2,8 @@
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
|
||||
-- Inverse: libjpeg's islow (jidctint.c: the Loeffler-Ligtenberg-Moschytz algorithm, 13-bit constants, two passes with
|
||||
-- PASS1_BITS of scaling between them), plus the reduced 4x4 / 2x2 / 1x1 IDCTs for scaled decodes (jidctred.c); the
|
||||
-- results match libjpeg-turbo's djpeg bit for bit. Absorbed from jpeg-luau 1.0 src/Jpeg/Idct.luau (same author).
|
||||
-- Forward: libjpeg's islow (jfdctint.c) with jcdctmgr.c's rounding quantiser, so an encoder built on it produces
|
||||
-- the same coefficients as cjpeg. Both are Luau translations of IJG code (licenses/libjpeg-turbo-LICENSE.md).
|
||||
-- Values are exact integers in doubles: no overflow even on corrupt coefficients; outputs are clamped to 0..maxv.
|
||||
--
|
||||
-- Dct.idctComponent(coef, q, bpl, bpc, size, plane, p1, center, maxv) -- every block of a component
|
||||
-- Dct.idctBlock(coef, off, q, plane, out, stride, p1, center, maxv) -- one 8x8 block (u16 samples)
|
||||
-- Dct.fdctQuantize(src, stride, x, y, w, h, div, coef, off) -- one block from u8 samples
|
||||
-- libjpeg's islow (jidctint.c / jfdctint.c), the reduced IDCTs (jidctred.c) and jcdctmgr.c's rounding quantiser, bit-exact
|
||||
-- with libjpeg-turbo. From jpeg-luau 1.0 (same author); IJG code: licenses/libjpeg-turbo-LICENSE.md.
|
||||
local readi16, readu16, writeu16, readu8, writei16 = buffer.readi16, buffer.readu16, buffer.writeu16, buffer.readu8, buffer.writei16
|
||||
local clamp = math.clamp
|
||||
|
||||
@@ -243,10 +235,7 @@ local function idct2(coef: buffer, off: number, q: buffer, plane: buffer, out: n
|
||||
end
|
||||
end
|
||||
|
||||
-- Inverse-transforms every block of a component: coef (i16, 64 per block, natural order) on a bpl x bpc block
|
||||
-- grid, quantisation table q (64 u16, natural order), into plane (u16 samples, (bpl * size) per row) at size x
|
||||
-- size samples per block. p1 is PASS1_BITS (2 for 8-bit, 1 for 12-bit), center the level shift, maxv the top.
|
||||
-- hook (optional): a cooperative yield point after every block row (pcall'ed: it can't throw through here).
|
||||
-- p1 = PASS1_BITS (2 for 8-bit, 1 for 12-bit)
|
||||
function Dct.idctComponent(coef: buffer, q: buffer, bpl: number, bpc: number, size: number, plane: buffer, p1: number, center: number, maxv: number, hook: (() -> ())?)
|
||||
local stride = bpl * size
|
||||
for by = 0, bpc - 1 do
|
||||
@@ -270,13 +259,10 @@ function Dct.idctComponent(coef: buffer, q: buffer, bpl: number, bpc: number, si
|
||||
end
|
||||
end
|
||||
|
||||
-- idctBlock(coef, off, q, plane, out, stride, p1, center, maxv): one 8x8 block, coef (i16, natural order) at byte
|
||||
-- offset off, dequantised by q (64 u16), into the u16 plane at sample index out with stride samples per row
|
||||
function Dct.idctBlock(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number)
|
||||
idct8(coef, off, q, plane, out, stride, p1, center, maxv)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ forward
|
||||
local fw = table.create(64, 0)
|
||||
|
||||
local function quant(coef: buffer, off: number, div: buffer, v: number, i: number)
|
||||
@@ -289,10 +275,7 @@ local function quant(coef: buffer, off: number, div: buffer, v: number, i: numbe
|
||||
end
|
||||
end
|
||||
|
||||
-- fdctQuantize(src, stride, x, y, w, h, div, coef, off): the 8x8 block of u8 samples at (x, y) in src (stride bytes
|
||||
-- per row; samples past w - 1 / h - 1 repeat the edge), level-shifted by 128, forward DCT (jfdctint.c islow), then
|
||||
-- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored, q = div (64 u16, natural order). Writes
|
||||
-- 64 i16 at coef[off] (natural order). The caller keeps x < w, y < h and the src range valid.
|
||||
-- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored
|
||||
function Dct.fdctQuantize(src: buffer, stride: number, x: number, y: number, w: number, h: number, div: buffer, coef: buffer, off: number)
|
||||
local lastX, lastY = w - 1, h - 1
|
||||
for r = 0, 7 do
|
||||
|
||||
@@ -1,17 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar
|
||||
-- modes), ETC2 RGBA (an EAC alpha block + ETC2 colour), ETC2 RGB A1 (punch-through alpha) and EAC R11 / RG11
|
||||
-- (unsigned and signed). Written from the Khronos Data Format Specification 1.3, section 21 (ETC1 / ETC2 / EAC); new
|
||||
-- in rosetta. Shared by the texture formats (KTX, PVR, ...). Never throws: the caller gets a message instead.
|
||||
--
|
||||
-- local px, err = Etc.decode("etc2_rgba", buf, offset, w, h) -- rgba8 pixels
|
||||
-- local px16 = Etc.decode("eac_rg11", buf, offset, w, h, nil, 0, true) -- rgba16 (EAC keeps its 11 bits)
|
||||
-- Etc.size("etc1", w, h) -- bytes of the block data
|
||||
--
|
||||
-- Kinds: etc1, etc2_rgb, etc2_rgba, etc2_rgba1, eac_r11, eac_r11s, eac_rg11, eac_rg11s. R11 decodes to grey (r = g = b),
|
||||
-- RG11 to red + green (blue 0); signed values are biased (-1 -> 1, 0 -> 128, +1 -> 255; rgba16: 0 / 32768 / 65535).
|
||||
-- codecs/image/Etc: ETC1 / ETC2 / EAC block texture decoding (Khronos Data Format Specification 1.3, section 21).
|
||||
-- New in rosetta. Signed EAC values are biased into rgba8 (-1 -> 1, 0 -> 128, +1 -> 255).
|
||||
local Etc = {}
|
||||
|
||||
Etc.BLOCK = table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 = 8, eac_r11 = 8, eac_r11s = 8, eac_rg11 = 16, eac_rg11s = 16 }) :: { [string]: number }
|
||||
@@ -19,7 +10,6 @@ Etc.BLOCK = table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 =
|
||||
local readu8, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32
|
||||
local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ tables
|
||||
local MOD = { -- the ETC1 intensity modifiers per table: index (msb * 2 + lsb) -> a, b, -a, -b
|
||||
{ 2, 8, -2, -8 },
|
||||
{ 5, 17, -5, -17 },
|
||||
@@ -57,9 +47,8 @@ local function rgb(r: number, g: number, b: number): number
|
||||
return clamp8(r) + clamp8(g) * 256 + clamp8(b) * 65536 + 0xFF000000
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ colour blocks
|
||||
-- blk: 16 u32 rgba8 pixels in raster order (y * 4 + x)
|
||||
local P = table.create(4, 0) -- T / H paint colours (rgba8 u32)
|
||||
local P = table.create(4, 0)
|
||||
|
||||
local function be32(src: buffer, p: number): number
|
||||
return byteswap(readu32(src, p))
|
||||
@@ -70,7 +59,7 @@ local function pix(lo: number, i: number): number
|
||||
return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1)
|
||||
end
|
||||
|
||||
-- ETC1 / ETC2 colour block at p into blk. etc2: T / H / planar modes; punch: the RGB A1 variant (bit 33 = opaque).
|
||||
-- ETC1 / ETC2 colour block; the RGB A1 variant: bit 33 = opaque
|
||||
local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch: boolean)
|
||||
local hi, lo = be32(src, p), be32(src, p + 4)
|
||||
local diffBit = band(rshift(hi, 1), 1)
|
||||
@@ -142,7 +131,6 @@ local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch:
|
||||
r2, g2, b2 = R2 * 8 + rshift(R2, 2), G2 * 8 + rshift(G2, 2), B2 * 8 + rshift(B2, 2)
|
||||
end
|
||||
if not r1 then
|
||||
-- T / H: the paint colours by index
|
||||
for i = 0, 15 do
|
||||
local x, y = rshift(i, 2), band(i, 3)
|
||||
local idx = pix(lo, i)
|
||||
@@ -175,10 +163,8 @@ local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch:
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ EAC
|
||||
local VALS = table.create(16, 0)
|
||||
|
||||
-- the 16 values of the EAC block at p into VALS (raster order): mode "alpha" (8-bit), "u11" / "s11" (11-bit)
|
||||
local function eac(src: buffer, p: number, mode: string)
|
||||
local base = readu8(src, p)
|
||||
local b1 = readu8(src, p + 1)
|
||||
@@ -211,7 +197,6 @@ local function eac(src: buffer, p: number, mode: string)
|
||||
end
|
||||
end
|
||||
|
||||
-- 11-bit values -> 8 / 16 bits
|
||||
local function to8(v: number, signed: boolean): number
|
||||
if signed then
|
||||
return math.floor(v * 127 / 1023 + 0.5) + 128
|
||||
@@ -225,15 +210,11 @@ local function to16(v: number, signed: boolean): number
|
||||
return v * 32 + rshift(v, 6)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- size(kind, w, h) -> bytes of the block data | nil for an unknown kind
|
||||
function Etc.size(kind: string, w: number, h: number): number?
|
||||
local b = Etc.BLOCK[kind]
|
||||
return if b then ((w + 3) // 4) * ((h + 3) // 4) * b else nil
|
||||
end
|
||||
|
||||
-- decode(kind, src, offset, w, h, out?, outOffset?, wide?) -> pixels | nil, message. rgba8, or rgba16 for the EAC
|
||||
-- kinds when wide is true.
|
||||
function Etc.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?, wide: boolean?): (buffer?, string?)
|
||||
local bytes = Etc.BLOCK[kind]
|
||||
if not bytes then
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H,
|
||||
-- OpenEXR HALF channels). New in rosetta. Never throws.
|
||||
--
|
||||
-- local f = Half.TABLE[h] -- the number of every half bit pattern 0..65535 (a 65536-entry table)
|
||||
-- local f = Half.toFloat(h) -- the same, computed
|
||||
-- local h = Half.fromFloat(f) -- round to nearest even; overflow -> infinity, NaN -> a quiet NaN
|
||||
-- codecs/image/Half: IEEE 754 binary16 <-> number (round to nearest even, overflow to infinity). New in rosetta.
|
||||
local Half = {}
|
||||
|
||||
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
|
||||
|
||||
-- toFloat(h) -> number (h a 16-bit pattern)
|
||||
local function toFloat(h: number): number
|
||||
local s = if h >= 32768 then -1 else 1
|
||||
local e = band(rshift(h, 10), 31)
|
||||
@@ -33,7 +27,6 @@ Half.TABLE = TABLE
|
||||
|
||||
local scratch = buffer.create(4)
|
||||
|
||||
-- fromFloat(f) -> the nearest half bit pattern (ties to even)
|
||||
function Half.fromFloat(f: number): number
|
||||
if f ~= f then
|
||||
return 0x7E00
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised
|
||||
-- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's
|
||||
-- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table.
|
||||
--
|
||||
-- It reads the destuffed scan data that Scan.destuff produces (0xFF 0x00 already removed, RSTn positions recorded);
|
||||
-- past the end of a restart segment it reads zero bytes, the convention libjpeg follows when the decoder runs into a
|
||||
-- marker (libjpeg's encoder also drops trailing zero bytes, so reading past the end is normal and not a sign of
|
||||
-- truncation: the caller flags a scan that runs into the end of the file instead). Statistics bins live in one buffer: DC tables at [t * 64], AC tables at [256 + t * 256], the fixed 0.5
|
||||
-- bin at [1280].
|
||||
-- codecs/image/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive).
|
||||
-- A Luau translation of libjpeg-turbo's jdarith.c / jaricom.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md); past the
|
||||
-- end of a restart segment it reads zero bytes, as libjpeg does. Bins: DC [t * 64], AC [256 + t * 256], fixed 0.5 [1280].
|
||||
local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16
|
||||
local band, bxor = bit32.band, bit32.bxor
|
||||
|
||||
@@ -50,7 +44,7 @@ do
|
||||
end
|
||||
end
|
||||
|
||||
local ZZ: buffer = buffer.create(80) -- set by Arith.init (Scan.ZIGZAG)
|
||||
local ZZ: buffer = buffer.create(80)
|
||||
|
||||
local STATS = 1281
|
||||
local POW2 = buffer.create(8)
|
||||
@@ -59,11 +53,10 @@ for i = 0, 7 do
|
||||
end
|
||||
local FIXED = 1280
|
||||
|
||||
-- decoder state (one scan at a time; never yields)
|
||||
local D: buffer = buffer.create(0)
|
||||
local P = 0 -- next byte
|
||||
local SEGEND = 0 -- reads at or past this return 0
|
||||
local OVER = 0 -- zero bytes supplied past the end
|
||||
local P = 0
|
||||
local SEGEND = 0
|
||||
local OVER = 0
|
||||
local C, A, CT = 0, 0, -16
|
||||
local st: buffer = buffer.create(STATS)
|
||||
|
||||
@@ -130,7 +123,7 @@ export type ArithComp = {
|
||||
v: number,
|
||||
bw: number,
|
||||
bh: number,
|
||||
dcTbl: number, -- 0..3
|
||||
dcTbl: number,
|
||||
acTbl: number,
|
||||
pred: number,
|
||||
ctx: number,
|
||||
@@ -141,16 +134,16 @@ export type ArithParams = {
|
||||
mcusX: number,
|
||||
mcusY: number,
|
||||
ri: number,
|
||||
mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine
|
||||
mode: number,
|
||||
ss: number,
|
||||
se: number,
|
||||
al: number,
|
||||
dcL: { number }, -- conditioning per table (DAC), 1-based by table + 1
|
||||
dcL: { number },
|
||||
dcU: { number },
|
||||
acK: { number },
|
||||
}
|
||||
|
||||
-- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24); returns the new predictor or nil on a bad code
|
||||
-- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24)
|
||||
local function dcDiff(c: ArithComp, L: number, U: number): number?
|
||||
local base = c.dcTbl * 64
|
||||
local s = base + c.ctx
|
||||
@@ -194,7 +187,7 @@ local function dcDiff(c: ArithComp, L: number, U: number): number?
|
||||
return band(c.pred + v, 0xFFFF)
|
||||
end
|
||||
|
||||
-- AC coefficients k = ss..se of one block (figure F.20); false on a bad code
|
||||
-- AC coefficients k = ss..se of one block (figure F.20)
|
||||
local function acFirst(coef: buffer, off: number, tbl: number, ss: number, se: number, K: number, mul: number): boolean
|
||||
local base = 256 + tbl * 256
|
||||
local k = ss
|
||||
@@ -292,7 +285,6 @@ function Arith.init(zigzag: buffer)
|
||||
ZZ = zigzag
|
||||
end
|
||||
|
||||
-- run(d, cleanLen, rst, nrst, P) -> truncated: decodes one scan (see Scan.run for the data layout)
|
||||
function Arith.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, Pm: ArithParams): boolean
|
||||
local comps = Pm.comps
|
||||
local nc = #comps
|
||||
|
||||
@@ -1,19 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never
|
||||
-- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's
|
||||
-- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md).
|
||||
--
|
||||
-- Upsampling follows libjpeg-turbo's jdsample.c, so the output matches djpeg's defaults:
|
||||
-- FULL the component is at output resolution
|
||||
-- H2V1 "fancy" triangle filter, 3/4 nearer + 1/4 further sample, alternating rounding (1, 2) / 4
|
||||
-- H2V2 fancy in both directions: vertical 3:1 column sums, then horizontal 3:1, rounding (8, 7) / 16
|
||||
-- H1V2 fancy vertical only, rounding 1 (upper row) / 2 (lower row)
|
||||
-- REPLICATE any other ratio (or no fancy upsampling): nearest sample, as int_upsample
|
||||
-- Edges replicate the last real sample (downW x downH), as libjpeg does with its context rows.
|
||||
-- Colour conversion is jdcolor.c's table-driven YCbCr -> RGB (16-bit fixed point), plus grey, RGB, CMYK and
|
||||
-- YCCK (Adobe inverted CMYK: R = C * K / 255).
|
||||
-- codecs/image/Jpeg/Color: chroma upsampling (libjpeg-turbo jdsample.c: fancy H2V1 / H2V2 / H1V2, else replicate) and
|
||||
-- colour conversion (jdcolor.c; YCCK = Adobe inverted CMYK), matching djpeg's defaults. From jpeg-luau 1.0, a Luau
|
||||
-- translation of libjpeg-turbo (IJG licence: licenses/libjpeg-turbo-LICENSE.md).
|
||||
local readu16, readi32, readu8, writeu16, writeu32 = buffer.readu16, buffer.readi32, buffer.readu8, buffer.writeu16, buffer.writeu32
|
||||
local clamp, min, max = math.clamp, math.min, math.max
|
||||
|
||||
@@ -31,20 +21,20 @@ Color.RGB = 2
|
||||
Color.CMYK = 3
|
||||
Color.YCCK = 4
|
||||
Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted
|
||||
Color.RAW = 6 -- no conversion: components 1..4 as R, G, B, A (opts.raw: BLP1's BGRA JPEGs, ...)
|
||||
Color.RAW = 6
|
||||
|
||||
export type Comp = {
|
||||
plane: buffer, -- u16 samples, stride per row
|
||||
plane: buffer,
|
||||
stride: number,
|
||||
rows: number, -- plane height
|
||||
downW: number, -- real samples across / down (the rest is block padding)
|
||||
rows: number,
|
||||
downW: number,
|
||||
downH: number,
|
||||
method: number,
|
||||
hIn: number,
|
||||
hOut: number,
|
||||
vIn: number,
|
||||
vOut: number,
|
||||
row: buffer, -- scratch row (u16, at least max(outW, 2 * downW) + 8 samples)
|
||||
row: buffer,
|
||||
}
|
||||
|
||||
export type Params = {
|
||||
@@ -54,13 +44,12 @@ export type Params = {
|
||||
outH: number,
|
||||
maxv: number,
|
||||
pixels: buffer,
|
||||
-- YCbCr tables (maxv + 1 i32 entries)
|
||||
crr: buffer,
|
||||
cbb: buffer,
|
||||
crg: buffer,
|
||||
cbg: buffer,
|
||||
toByte: buffer?, -- maxv + 1 u8 entries (12-bit), nil for 8-bit
|
||||
hook: (() -> ())?, -- a cooperative yield point every 8 rows (pcall'ed: it can't throw through here)
|
||||
toByte: buffer?,
|
||||
hook: (() -> ())?,
|
||||
}
|
||||
|
||||
-- jdcolor.c build_ycc_rgb_table
|
||||
@@ -81,7 +70,6 @@ function Color.tables(maxv: number): (buffer, buffer, buffer, buffer)
|
||||
return crr, cbb, crg, cbg
|
||||
end
|
||||
|
||||
-- fills c.row with output row y; returns the buffer and byte offset of the row's samples
|
||||
local function fetch(c: Comp, y: number, outW: number): (buffer, number)
|
||||
local method = c.method
|
||||
local plane, stride, row = c.plane, c.stride, c.row
|
||||
@@ -197,7 +185,6 @@ function Color.run(P: Params)
|
||||
continue
|
||||
end
|
||||
if space == 1 and not toByte then
|
||||
-- the common case: 8-bit YCbCr
|
||||
for x = 0, outW - 1 do
|
||||
local i = x * 2
|
||||
local yv, cb, cr = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i)
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/image/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan /
|
||||
-- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended:
|
||||
-- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM
|
||||
-- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a
|
||||
-- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows
|
||||
-- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/image/Jpeg/Decode for the video formats.
|
||||
-- codecs/image/Jpeg/Decode: the JPEG marker parser and output stage (it validates everything the native loops index).
|
||||
-- From jpeg-luau 1.0 (same author), extended with SOF9 / SOF10 / DAC, EXIF / ICC / AVI1 segments and yuv420p output;
|
||||
-- the IDCT size choice for scaled decodes follows libjpeg-turbo's jdmaster.c.
|
||||
local Scan = require("@rosetta/codecs/image/Jpeg/Scan")
|
||||
local Arith = require("@rosetta/codecs/image/Jpeg/Arith")
|
||||
local Color = require("@rosetta/codecs/image/Jpeg/Color")
|
||||
@@ -36,7 +33,7 @@ local function stdTable(class: string, slot: number): buffer?
|
||||
return stdBuilt[key]
|
||||
end
|
||||
|
||||
-- the EXIF TIFF block (after "Exif\0\0") and its orientation tag, from an APP1 segment at [p, e)
|
||||
-- the EXIF TIFF block (after "Exif\0\0") and its orientation tag
|
||||
local function exif(b: buffer, p: number, e: number): (number?, number?)
|
||||
if e - p < 14 or buffer.readstring(b, p, 6) ~= "Exif\0\0" then
|
||||
return nil, nil
|
||||
@@ -91,7 +88,7 @@ type Comp = {
|
||||
bw: number,
|
||||
bh: number,
|
||||
coef: buffer?,
|
||||
quant: buffer?, -- latched at the component's first scan
|
||||
quant: buffer?,
|
||||
dct: buffer?,
|
||||
act: buffer?,
|
||||
dcTbl: number,
|
||||
@@ -124,7 +121,6 @@ local SOF_REFUSED = {
|
||||
[0xCF] = "hierarchical arithmetic-coded",
|
||||
}
|
||||
|
||||
-- failures carry a code: "corrupt" | "unsupported" | "limit" | "truncated"
|
||||
local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, string?, string?)
|
||||
if e - p < 6 then
|
||||
return nil, "corrupt", "short SOF"
|
||||
@@ -228,15 +224,13 @@ export type State = {
|
||||
icc: buffer?,
|
||||
comments: { string },
|
||||
truncated: boolean,
|
||||
raw: boolean, -- opts.raw: no colour conversion
|
||||
raw: boolean,
|
||||
scale: number,
|
||||
avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back)
|
||||
endPos: number, -- the byte after the EOI marker (or the end of the data)
|
||||
hook: (() -> ())?, -- opts.yield: the cooperative yield point (scans, IDCT, colour conversion)
|
||||
endPos: number,
|
||||
hook: (() -> ())?,
|
||||
}
|
||||
|
||||
-- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with
|
||||
-- headerOnly it stops at the frame header, otherwise it decodes every scan into the components' coefficients.
|
||||
function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: boolean): (State?, string?, string?)
|
||||
if n - base < 4 or readu8(b, base) ~= 0xFF or readu8(b, base + 1) ~= 0xD8 then
|
||||
return nil, "corrupt", "not a JPEG file (no SOI marker)"
|
||||
@@ -587,7 +581,6 @@ end
|
||||
|
||||
local toByte12: buffer? = nil
|
||||
|
||||
-- output(st) -> width, height, rgba8 pixels, colour space | nil, code, message
|
||||
function Decode.output(st: State): (number?, any, any, string?)
|
||||
local f: Frame = st.frame
|
||||
local scale = st.scale
|
||||
@@ -642,7 +635,7 @@ function Decode.output(st: State): (number?, any, any, string?)
|
||||
vOut = vOut,
|
||||
row = buffer.create((math.max(outW, 2 * stride) + 8) * 2),
|
||||
})
|
||||
c.coef = nil -- free the coefficients early
|
||||
c.coef = nil
|
||||
end
|
||||
local space = colorSpaceOf(f, st.adobe, st.jfif)
|
||||
local spaceId = SPACE_IDS[space]
|
||||
@@ -682,14 +675,8 @@ function Decode.output(st: State): (number?, any, any, string?)
|
||||
return outW, outH, pixels, space
|
||||
end
|
||||
|
||||
-- outputYuv(st) -> width, height, yuv420p pixels, sampling | nil when the frame has no direct yuv420p form (the
|
||||
-- caller falls back to output). The IDCT output planes as they are, cropped to the image, without colour conversion
|
||||
-- or upsampling: 8-bit YCbCr whose chroma is sampled at half the luma rate both ways ("420", 2x2 / 1x1); half
|
||||
-- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma
|
||||
-- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: each 2 x 2 chroma block averaged, rounding to nearest); grey ("gray":
|
||||
-- chroma 128). Full scale only (opts.scale = 1).
|
||||
-- one IDCT plane at a time is live (each is cropped into the output before the next component): frame-sized planes
|
||||
-- (up to 4 MB) are kept between calls, so a stream of video frames does not allocate them per frame
|
||||
-- outputYuv: 4:2:0, 4:2:2 (chroma row pairs averaged, rounding up), 4:4:4 (2 x 2 averaged, rounding to nearest) or grey
|
||||
-- (chroma 128) straight from the IDCT planes; full scale only
|
||||
local scratch: buffer? = nil
|
||||
local function scratchPlane(n: number): buffer
|
||||
local sc = scratch
|
||||
@@ -734,7 +721,7 @@ function Decode.outputYuv(st: State): (number?, number?, buffer?, string?)
|
||||
end
|
||||
for _, c in comps do
|
||||
if c.coef and not c.quant then
|
||||
return nil, nil, nil, nil -- output() reports the missing table
|
||||
return nil, nil, nil, nil
|
||||
end
|
||||
end
|
||||
local w, h = f.width, f.height
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman
|
||||
-- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr
|
||||
-- 4:4:4 / 4:2:2 / 4:2:0, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG
|
||||
-- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/image/Jpeg/Encode. It follows libjpeg-turbo's
|
||||
-- encoder step for step so that its output is byte-identical to cjpeg's for the same settings: jccolor.c
|
||||
-- (fixed-point RGB -> YCbCr), jcsample.c (box downsampling with alternating rounding bias, right-edge replication),
|
||||
-- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/image/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs,
|
||||
-- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md.
|
||||
-- codecs/image/Jpeg/Encode: the JPEG encoder, baseline (SOF0) and progressive (SOF2, jpeg_simple_progression).
|
||||
-- Follows libjpeg-turbo step for step (jccolor.c, jcsample.c, jccoefct.c, jfdctint.c / jcdctmgr.c, jchuff.c, jcphuff.c)
|
||||
-- so its output is byte-identical to cjpeg's; Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md.
|
||||
local Dct = require("@rosetta/codecs/image/Dct")
|
||||
local Tables = require("@rosetta/codecs/image/Jpeg/Tables")
|
||||
|
||||
@@ -38,7 +33,6 @@ do
|
||||
end
|
||||
Encode.ZIGZAG = ZZ
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ output
|
||||
local OUT = buffer.create(0)
|
||||
local OP = 0
|
||||
local CAP = 0
|
||||
@@ -100,7 +94,6 @@ local function nbits(v: number): number
|
||||
return if v == 0 then 0 else 32 - countlz(v)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Huffman tables
|
||||
-- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl)
|
||||
export type Derived = { code: buffer, size: buffer }
|
||||
|
||||
@@ -222,7 +215,6 @@ local function optimal(freqIn: { number }): ({ number }, { number })
|
||||
end
|
||||
Encode.optimal = optimal
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ entropy coding state
|
||||
local dcTab: { Derived } = {}
|
||||
local acTab: { Derived } = {}
|
||||
local dcFreq: { { number } } = {}
|
||||
@@ -241,14 +233,14 @@ export type Comp = {
|
||||
h: number,
|
||||
v: number,
|
||||
tq: number,
|
||||
td: number, -- DC table slot
|
||||
ta: number, -- AC table slot
|
||||
bw: number, -- real blocks across / down
|
||||
td: number,
|
||||
ta: number,
|
||||
bw: number,
|
||||
bh: number,
|
||||
bpl: number, -- MCU-padded block grid
|
||||
bpl: number,
|
||||
bpc: number,
|
||||
coef: buffer, -- i16, 64 per block, natural order
|
||||
last: number, -- DC predictor
|
||||
coef: buffer,
|
||||
last: number,
|
||||
}
|
||||
|
||||
local function dcDiff(c: Comp, diff: number)
|
||||
@@ -379,7 +371,7 @@ local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: n
|
||||
end
|
||||
end
|
||||
local r = 0
|
||||
local br = 0 -- correction bits added in this block, at CORR[brStart + 1 ..]
|
||||
local br = 0
|
||||
local brStart = BE
|
||||
for k = ss, se do
|
||||
local t = absv[k + 1]
|
||||
@@ -425,10 +417,8 @@ local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: n
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ scans
|
||||
export type ScanSpec = { comps: { number }, ss: number, se: number, ah: number, al: number }
|
||||
|
||||
-- iterate the scan's MCUs (or blocks, for one component), calling fn(c, off) per block; restart markers when ri > 0
|
||||
local function walk(comps: { Comp }, mcusX: number, mcusY: number, ri: number, onRestart: (number) -> (), fn: (Comp, number) -> ())
|
||||
local nc = #comps
|
||||
local units, ux
|
||||
@@ -490,7 +480,6 @@ local function sos(comps: { Comp }, ss: number, se: number, ah: number, al: numb
|
||||
byte(ah * 16 + al)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ planes
|
||||
-- jccolor.c rgb_ycc_start tables (16-bit fixed point)
|
||||
local function fix(x: number): number
|
||||
return math.floor(x * 65536 + 0.5)
|
||||
@@ -500,7 +489,6 @@ local CBR, CBG, HALF = fix(0.16874), fix(0.33126), fix(0.5)
|
||||
local CRG, CRB = fix(0.41869), fix(0.08131)
|
||||
local OFF = 128 * 65536 + 32768 - 1
|
||||
|
||||
-- pixels (rgba8 / rgb8 / gray8) -> Y, Cb, Cr planes (w * h bytes each; Cb / Cr nil for grey output)
|
||||
local function planes(px: buffer, w: number, h: number, bpp: number, gray: boolean): (buffer, buffer?, buffer?)
|
||||
local n = w * h
|
||||
local Y = buffer.create(n)
|
||||
@@ -534,8 +522,7 @@ local function planes(px: buffer, w: number, h: number, bpp: number, gray: boole
|
||||
return Y, Cb, Cr
|
||||
end
|
||||
|
||||
-- jcsample.c: a full-resolution plane (w x h) -> the component's samples, (bw * 8) x ch, for factors hf x vf
|
||||
-- (1 or 2 each); full-resolution columns past w - 1 repeat the last one, rows past h - 1 the last row
|
||||
-- jcsample.c downsampling: columns past w - 1 repeat the last one, rows past h - 1 the last row
|
||||
local function downsample(src: buffer, w: number, h: number, hf: number, vf: number, outW: number, outH: number): buffer
|
||||
local out = buffer.create(outW * outH)
|
||||
for oy = 0, outH - 1 do
|
||||
@@ -562,22 +549,18 @@ local function downsample(src: buffer, w: number, h: number, hf: number, vf: num
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
export type Options = {
|
||||
quality: number, -- 1..100
|
||||
sampling: string, -- "444" | "422" | "420"
|
||||
quality: number,
|
||||
sampling: string,
|
||||
progressive: boolean,
|
||||
optimize: boolean, -- baseline: optimised Huffman tables (progressive always optimises)
|
||||
optimize: boolean,
|
||||
gray: boolean,
|
||||
restart: number, -- MCUs per restart interval (0 = none)
|
||||
segments: { { marker: number, data: buffer } }, -- APPn / COM segments after the JFIF header
|
||||
restart: number,
|
||||
segments: { { marker: number, data: buffer } },
|
||||
jfif: boolean,
|
||||
density: { unit: number, x: number, y: number }?,
|
||||
}
|
||||
|
||||
-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8), or bpp 0:
|
||||
-- yuv420p (w * h luma, then ceil(w / 2) * ceil(h / 2) Cb and Cr; opts.sampling must be "420" unless opts.gray). The
|
||||
-- caller validated sizes (1..65535), the buffer length and options.
|
||||
function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer
|
||||
OUT = buffer.create(math.max(1024, w * h // 2))
|
||||
CAP = buffer.len(OUT)
|
||||
@@ -619,7 +602,6 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options):
|
||||
qdiv[t] = b
|
||||
end
|
||||
|
||||
-- components and their quantised coefficients
|
||||
local comps: { Comp } = {}
|
||||
local srcs = if o.gray then { Y } else { Y, Cb :: buffer, Cr :: buffer }
|
||||
for i, src in srcs do
|
||||
@@ -668,7 +650,6 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options):
|
||||
comps[i] = c
|
||||
end
|
||||
|
||||
-- headers
|
||||
byte(0xFF)
|
||||
byte(0xD8)
|
||||
if o.jfif then
|
||||
@@ -845,7 +826,6 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options):
|
||||
walk(sComps, mcusX, mcusY, o.restart, onRestart, blockFn)
|
||||
emitEobrun()
|
||||
end
|
||||
-- gather statistics, then emit the optimal tables this scan uses
|
||||
if not (isDc and ah > 0) then
|
||||
GATHER = true
|
||||
for t = 1, ntab do
|
||||
|
||||
@@ -1,16 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from
|
||||
-- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header.
|
||||
--
|
||||
-- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF,
|
||||
-- records where each RSTn marker fell, and stops at any other marker. The clean buffer is followed by at least
|
||||
-- PAD zero bytes, so the bit reader can read 32 bits at any position up to PAD bytes past the end without a
|
||||
-- bounds check. `run` checks the position once per MCU, and no MCU (at most 10 blocks, enforced by the parser)
|
||||
-- can consume PAD bytes. So every buffer index stays in range, even on garbage data.
|
||||
--
|
||||
-- The bit reader keeps no state but a bit position: `peek` reads the big-endian 32-bit word that holds it.
|
||||
-- codecs/image/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients. From jpeg-luau 1.0 (same author).
|
||||
-- The clean scan data is followed by PAD zero bytes, so the 32-bit big-endian bit reader needs no bounds check.
|
||||
-- Huffman tables (built by `buildTable`) are buffers:
|
||||
-- [0, 1024) fast lookup by the next 9 bits: u16 (length << 8) | symbol, 0 = longer code
|
||||
-- [1024, 1096) maxcode[l], l = 0..17: u32, one past the last code of length l, left-aligned to 16 bits
|
||||
@@ -58,8 +50,7 @@ do
|
||||
end
|
||||
Scan.ZIGZAG = ZZ
|
||||
|
||||
-- Builds a Huffman table from the 16 code-length counts and the symbols (Luau arrays, 1-based). An
|
||||
-- over-subscribed table keeps the codes that fit; the rest decode as invalid.
|
||||
-- an over-subscribed table keeps the codes that fit; the rest decode as invalid
|
||||
function Scan.buildTable(counts: { number }, symbols: { number }): buffer
|
||||
local t = buffer.create(Scan.TABLE_SIZE)
|
||||
local code, k = 0, 0
|
||||
@@ -87,7 +78,6 @@ function Scan.buildTable(counts: { number }, symbols: { number }): buffer
|
||||
writeu8(t, T_VAL + i - 1, symbols[i])
|
||||
end
|
||||
writeu16(t, T_COUNT, k)
|
||||
-- fast lookups
|
||||
for i = 1, k do
|
||||
local l = sizes[i]
|
||||
if l <= 9 then
|
||||
@@ -110,9 +100,6 @@ function Scan.buildTable(counts: { number }, symbols: { number }): buffer
|
||||
return t
|
||||
end
|
||||
|
||||
-- Copies the entropy-coded data at src[pos..n) into dst (at least n - pos + PAD bytes): byte stuffing removed,
|
||||
-- RSTn offsets (in dst) stored in rst[1..]. Returns the source position of the marker that ended the scan (or n),
|
||||
-- the clean length, and the RST count. The PAD bytes after the clean data are zeroed.
|
||||
function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }): (number, number, number)
|
||||
local o, nr = 0, 0
|
||||
while pos < n do
|
||||
@@ -170,7 +157,6 @@ local function huff(d: buffer, pos: number, t: buffer): (number, number)
|
||||
return readu8(t, T_VAL + idx), pos + l
|
||||
end
|
||||
|
||||
-- the next s bits (1 <= s <= 16) as an unsigned number
|
||||
local function bits(d: buffer, pos: number, s: number): number
|
||||
return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s)
|
||||
end
|
||||
@@ -182,7 +168,6 @@ local function extend(v: number, s: number): number
|
||||
return v
|
||||
end
|
||||
|
||||
-- sequential (baseline / extended) block: returns pos, DC predictor
|
||||
local function blockSeq(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, act: buffer, pred: number): (number, number)
|
||||
local s
|
||||
s, pos = huff(d, pos, dct)
|
||||
@@ -354,11 +339,11 @@ local function blockAcRefine(d: buffer, pos: number, coef: buffer, off: number,
|
||||
end
|
||||
|
||||
export type ScanComp = {
|
||||
coef: buffer, -- i16 coefficients, 64 per block in natural order, blocks row-major on a bpl-wide grid
|
||||
coef: buffer,
|
||||
bpl: number,
|
||||
h: number,
|
||||
v: number,
|
||||
bw: number, -- blocks across / down the component itself (non-interleaved scans)
|
||||
bw: number,
|
||||
bh: number,
|
||||
dct: buffer?,
|
||||
act: buffer?,
|
||||
@@ -369,16 +354,14 @@ export type ScanParams = {
|
||||
comps: { ScanComp },
|
||||
mcusX: number,
|
||||
mcusY: number,
|
||||
ri: number, -- restart interval in MCUs (0 = none)
|
||||
mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine
|
||||
ri: number,
|
||||
mode: number,
|
||||
ss: number,
|
||||
se: number,
|
||||
al: number,
|
||||
hook: (() -> ())?, -- a cooperative yield point after every MCU row (pcall'ed: it can't throw through here)
|
||||
hook: (() -> ())?,
|
||||
}
|
||||
|
||||
-- Decodes one scan from the clean data d (cleanLen bytes, then PAD zeros). Returns the final bit position and
|
||||
-- whether the data ran out (or overran) before the last MCU.
|
||||
function Scan.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, P: ScanParams): (number, boolean)
|
||||
local comps = P.comps
|
||||
local nc = #comps
|
||||
|
||||
@@ -63,7 +63,6 @@ Tables.CHROMA = {
|
||||
99, 99, 99, 99, 99, 99, 99, 99,
|
||||
}
|
||||
|
||||
-- quant(base, quality) -> 64 values (natural order) for quality 1..100, clamped to 1..255 (baseline)
|
||||
function Tables.quant(base: { number }, quality: number): { number }
|
||||
local q = math.clamp(math.floor(quality), 1, 100)
|
||||
local scale = if q < 50 then 5000 // q else 200 - q * 2
|
||||
|
||||
@@ -1,23 +1,18 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16
|
||||
-- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4
|
||||
-- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG).
|
||||
-- The callers (codecs/image/Jpeg/Decode, codecs/image/Jpeg) size every buffer; each loop reads and writes inside those sizes.
|
||||
-- codecs/image/Jpeg/Yuv: the JPEG decoder's u16 IDCT planes -> u8 yuv420p; 4:2:2 / 4:4:4 chroma averaged to 4:2:0,
|
||||
-- the two fields of AVI1 interlaced Motion-JPEG woven.
|
||||
local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32
|
||||
|
||||
local Yuv = {}
|
||||
|
||||
-- crop(src, stride, w, h, dst, doff): the top-left w x h samples of a u16 plane (stride samples per row) into u8
|
||||
-- samples at dst[doff], w per row
|
||||
function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
|
||||
local quads = w // 4
|
||||
local rest = w - quads * 4
|
||||
for y = 0, h - 1 do
|
||||
local s = y * stride * 2
|
||||
local d = doff + y * w
|
||||
-- four samples (two u32 reads of two u16 samples, each 0..255) per u32 write
|
||||
for _ = 1, quads do
|
||||
local a, b = readu32(src, s), readu32(src, s + 4)
|
||||
writeu32(dst, d, a % 65536 + (a // 65536) * 256 + (b % 65536) * 65536 + (b // 65536) * 16777216)
|
||||
@@ -30,8 +25,6 @@ function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer
|
||||
end
|
||||
end
|
||||
|
||||
-- rows(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:2:2 chroma) -> u8 w x ceil(h / 2), each output
|
||||
-- row the rounded mean of two source rows (the last row alone when h is odd)
|
||||
function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
|
||||
local oh = (h + 1) // 2
|
||||
for y = 0, oh - 1 do
|
||||
@@ -44,8 +37,6 @@ function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer
|
||||
end
|
||||
end
|
||||
|
||||
-- box(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:4:4 chroma) -> u8 ceil(w / 2) x ceil(h / 2),
|
||||
-- each output sample the rounded mean of a 2 x 2 block (edges repeat the last row / column)
|
||||
function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
|
||||
local ow, oh = (w + 1) // 2, (h + 1) // 2
|
||||
for y = 0, oh - 1 do
|
||||
@@ -60,8 +51,6 @@ function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer,
|
||||
end
|
||||
end
|
||||
|
||||
-- weave(top, toff, bottom, boff, rowBytes, rows, dst, doff): interleave rows of two planes (field 1 on the even rows, field
|
||||
-- 2 on the odd rows) into rows output rows at dst[doff]; top holds ceil(rows / 2) rows, bottom floor(rows / 2)
|
||||
function Yuv.weave(top: buffer, toff: number, bottom: buffer, boff: number, rowBytes: number, rows: number, dst: buffer, doff: number)
|
||||
for y = 0, rows - 1 do
|
||||
local k = y // 2
|
||||
|
||||
@@ -1,34 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/image/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/image/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.
|
||||
-- codecs/image/Jpeg: the JPEG codec (ITU T.81), bit-exact with libjpeg-turbo's djpeg and byte-identical with cjpeg.
|
||||
-- From jpeg-luau 1.0 (same author); IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md. Motion-JPEG: frames without
|
||||
-- DHT use the T.81 annex K tables; AVI1 fields are woven top field first, as ffmpeg does (it ignores the polarity).
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Decode = require("@rosetta/codecs/image/Jpeg/Decode")
|
||||
@@ -38,28 +11,25 @@ local Yuv = require("@rosetta/codecs/image/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)
|
||||
raw: boolean?, -- no colour conversion: 3 / 4 components as R, G, B (, A) bytes (default false; BLP1 BGRA JPEGs)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
-- a cooperative yield point, run after every MCU row of a scan, every block row of the IDCT and every 8 output
|
||||
-- rows: e.g. a function that calls coroutine.yield() when a time budget is spent, so one image is decoded over
|
||||
-- several frames (decode then runs inside a coroutine). Errors in it are ignored.
|
||||
scale: number?,
|
||||
orient: boolean?,
|
||||
native: boolean?,
|
||||
yuv: boolean?,
|
||||
fields: boolean?,
|
||||
raw: boolean?,
|
||||
maxPixels: number?,
|
||||
yield: (() -> ())?,
|
||||
}
|
||||
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
|
||||
quality: number?,
|
||||
subsampling: ("420" | "422" | "444")?,
|
||||
progressive: boolean?,
|
||||
optimize: boolean?,
|
||||
gray: boolean?,
|
||||
restart: number?,
|
||||
jfif: boolean?,
|
||||
density: { unit: number, x: number, y: number }?,
|
||||
segments: { { marker: number, data: buffer } }?,
|
||||
}
|
||||
|
||||
export type Info = {
|
||||
@@ -70,11 +40,11 @@ export type Info = {
|
||||
arithmetic: boolean,
|
||||
precision: number,
|
||||
colorSpace: string,
|
||||
sampling: { { number } }, -- { h, v } per component
|
||||
sampling: { { number } },
|
||||
orientation: number,
|
||||
adobe: number?,
|
||||
jfif: boolean,
|
||||
avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header
|
||||
avi1: number?,
|
||||
}
|
||||
|
||||
local function range(buf: buffer, off: number?, len: number?): (number, number)
|
||||
@@ -83,7 +53,6 @@ local function range(buf: buffer, off: number?, len: number?): (number, number)
|
||||
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
|
||||
@@ -103,7 +72,6 @@ local function samplingOf(f: any): { { number } }
|
||||
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")
|
||||
@@ -131,7 +99,6 @@ function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?)
|
||||
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
|
||||
@@ -164,7 +131,6 @@ local function orient(px: buffer, w: number, h: number, o: number): (buffer, num
|
||||
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
|
||||
@@ -231,14 +197,14 @@ local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions?
|
||||
adobe = s.adobe,
|
||||
jfif = s.jfif,
|
||||
avi1 = s.avi1,
|
||||
yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv)
|
||||
yuv = mode,
|
||||
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
|
||||
-- the start of a second JPEG: FF D8 FF
|
||||
local function nextSoi(buf: buffer, p: number, e: number): number
|
||||
local readu8 = buffer.readu8
|
||||
while p + 3 <= e do
|
||||
@@ -250,7 +216,6 @@ local function nextSoi(buf: buffer, p: number, e: number): number
|
||||
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
|
||||
@@ -258,7 +223,7 @@ local function weave(a: Types.Image, b: Types.Image): Types.Image
|
||||
local dst = out.pixels
|
||||
if a.format == "yuv420p" then
|
||||
local cw, chf = (w + 1) // 2, (hf + 1) // 2
|
||||
local ch = (h + 1) // 2 -- = hf
|
||||
local ch = (h + 1) // 2
|
||||
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)
|
||||
@@ -271,7 +236,6 @@ local function weave(a: Types.Image, b: Types.Image): Types.Image
|
||||
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")
|
||||
@@ -307,10 +271,8 @@ function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOption
|
||||
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")
|
||||
|
||||
@@ -1,21 +1,13 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP,
|
||||
-- the DIBs inside ICO / CUR, ...): 1 / 2 / 4 / 8-bit indexes through a palette, BGR / BGRA, 5-5-5, bit-masked 16 /
|
||||
-- 24 / 32-bit pixels, RLE4 / RLE8, rows bottom-up or top-down; and the encoder direction (rgba8 -> BGR / BGRA /
|
||||
-- 8-bit indexes, bottom-up). Absorbed from bmp-luau b86aed6 (same author, no third-party code); the encoder loops
|
||||
-- are new. They never throw: the caller validates every size first and hands in a source buffer that holds every
|
||||
-- byte an uncompressed loop can read (a truncated file is copied into a zero-padded buffer); the RLE loop checks each
|
||||
-- read against its end offset. Output: rgba8, top-down rows, one u32 per pixel (bytes R, G, B, A).
|
||||
-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB.
|
||||
-- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8. From bmp-luau b86aed6 (same author); the encoder loops are new.
|
||||
local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8
|
||||
local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift
|
||||
|
||||
local Pixels = {}
|
||||
|
||||
-- palette(src, base, n, bgr?) -> a 256-entry u32 palette for indexed(): n RGB triples (BGR when bgr) at src[base..],
|
||||
-- opaque; entries past n (or past the end of src) are opaque black. The game formats' 768-byte palettes (PLAYPAL,
|
||||
-- Quake palette.lmp, Half-Life MDL / WAD3 / BSP 30 textures).
|
||||
function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): buffer
|
||||
local pal = buffer.create(1024)
|
||||
local m = if base >= 0 then math.clamp(math.min(n, (buffer.len(src) - base) // 3), 0, 256) else 0
|
||||
@@ -34,7 +26,6 @@ function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): bu
|
||||
return pal
|
||||
end
|
||||
|
||||
-- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal)
|
||||
function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number,
|
||||
topDown: boolean, pal: buffer)
|
||||
local mask = lshift(1, bpp) - 1
|
||||
@@ -88,7 +79,7 @@ function Pixels.bgr24(src: buffer, base: number, stride: number, dst: buffer, w:
|
||||
end
|
||||
end
|
||||
|
||||
-- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks). Returns the OR of every alpha byte.
|
||||
-- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks)
|
||||
function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number,
|
||||
topDown: boolean): number
|
||||
local aor = 0
|
||||
@@ -97,7 +88,6 @@ function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w
|
||||
local d = (if topDown then r else h - 1 - r) * w * 4
|
||||
for x = 0, w - 1 do
|
||||
local p = readu32(src, so + x * 4)
|
||||
-- swap R and B: B G R A -> R G B A
|
||||
writeu32(dst, d + x * 4, bor(band(p, 0xFF00FF00), band(rshift(p, 16), 0xFF), lshift(band(p, 0xFF), 16)))
|
||||
aor = bor(aor, p)
|
||||
end
|
||||
@@ -105,9 +95,6 @@ function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w
|
||||
return rshift(aor, 24)
|
||||
end
|
||||
|
||||
-- 16 / 24 / 32 bpp through bit masks. sh* = shift of each mask, m* = mask >> shift, t* = scale tables (u8, one entry
|
||||
-- per masked value). A channel without a mask has m = 0 and a 1-entry table (0 for colour, 255 for alpha).
|
||||
-- Returns the OR of every masked alpha value (before scaling).
|
||||
function Pixels.masked(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number,
|
||||
topDown: boolean, shr: number, mr: number, tr: buffer, shg: number, mg: number, tg: buffer, shb: number,
|
||||
mb: number, tb: buffer, sha: number, ma: number, ta: buffer): number
|
||||
@@ -138,16 +125,14 @@ function Pixels.masked(src: buffer, base: number, stride: number, bpp: number, d
|
||||
return aor
|
||||
end
|
||||
|
||||
-- Sets every alpha byte to 255 (32-bit images whose alpha channel is all zero are opaque).
|
||||
-- 32-bit images whose alpha channel is all zero are opaque
|
||||
function Pixels.opaque(dst: buffer, n: number)
|
||||
for i = 0, n - 1 do
|
||||
writeu8(dst, i * 4 + 3, 255)
|
||||
end
|
||||
end
|
||||
|
||||
-- RLE8 / RLE4 from src[pos, stop) into dst (pre-filled with transparent black; pixels the stream skips with a
|
||||
-- delta, an early end of line or an early end of bitmap stay transparent). Malformed or truncated data stops the
|
||||
-- decode and keeps what was drawn. Returns the number of pixels written.
|
||||
-- RLE8 / RLE4: pixels skipped by a delta or an early end of line / bitmap stay transparent
|
||||
function Pixels.rle(src: buffer, pos: number, stop: number, rle4: boolean, dst: buffer, w: number, h: number,
|
||||
topDown: boolean, pal: buffer): number
|
||||
local x, y = 0, 0
|
||||
@@ -221,7 +206,6 @@ function Pixels.rle(src: buffer, pos: number, stop: number, rle4: boolean, dst:
|
||||
return written
|
||||
end
|
||||
|
||||
-- Encoder: rgba8 (top-down) -> 24 bpp BGR rows, bottom-up, each padded to stride (dst is zero-filled)
|
||||
function Pixels.encode24(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number)
|
||||
for y = 0, h - 1 do
|
||||
local s = y * w * 4
|
||||
@@ -236,20 +220,17 @@ function Pixels.encode24(src: buffer, w: number, h: number, dst: buffer, base: n
|
||||
end
|
||||
end
|
||||
|
||||
-- rgba8 -> 32 bpp BGRA, bottom-up
|
||||
function Pixels.encode32(src: buffer, w: number, h: number, dst: buffer, base: number)
|
||||
for y = 0, h - 1 do
|
||||
local s = y * w * 4
|
||||
local d = base + (h - 1 - y) * w * 4
|
||||
for x = 0, w - 1 do
|
||||
local v = readu32(src, s + x * 4)
|
||||
-- R G B A (little-endian u32: R | G << 8 | B << 16 | A << 24) -> B G R A
|
||||
writeu32(dst, d + x * 4, bor(band(v, 0xFF00FF00), band(rshift(v, 16), 255), lshift(band(v, 255), 16)))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- rgba8 -> 8 bpp indexes through idx (a table colour -> index, colours as R | G << 8 | B << 16), bottom-up
|
||||
function Pixels.encode8(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number, idx: { [number]: number })
|
||||
for y = 0, h - 1 do
|
||||
local s = y * w * 4
|
||||
@@ -260,8 +241,6 @@ function Pixels.encode8(src: buffer, w: number, h: number, dst: buffer, base: nu
|
||||
end
|
||||
end
|
||||
|
||||
-- colours(src, n, max) -> the distinct RGB colours in first-appearance order (R | G << 8 | B << 16), whether any
|
||||
-- alpha is below 255; stops counting at max + 1 colours
|
||||
function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boolean)
|
||||
local seen: { [number]: boolean } = {}
|
||||
local list: { number } = {}
|
||||
|
||||
@@ -1,20 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
|
||||
-- writer) builds on it. New code: Heckbert's median cut and Gervautz-Purgathofer octree, both over a 5-bit-per-channel
|
||||
-- weighted histogram (palette colours are the exact means of the pixels they cover), nearest-colour mapping with
|
||||
-- optional Floyd-Steinberg error diffusion. Deterministic: the same palette and indexes on every runtime (no table
|
||||
-- iteration order is ever relied on).
|
||||
--
|
||||
-- local pal, exact = Quantize.palette(pixels, w, h, 256, { method = "mediancut" }) -- { {r, g, b, 255} }, boolean
|
||||
-- local idx = Quantize.map(pixels, w, h, pal, { dither = true, transparentIndex = 255 }) -- buffer of w * h u8
|
||||
--
|
||||
-- Pixels with alpha < 128 are "transparent": palette() ignores them, map() gives them opts.transparentIndex (0-based)
|
||||
-- when set (otherwise they map like opaque pixels). When the opaque pixels have at most maxColors distinct colours,
|
||||
-- palette() returns exactly those (in first-seen order) and exact = true, and map() is then lossless. The octree
|
||||
-- folds whole nodes, so it may return fewer than maxColors entries; below 8 colours median cut is used instead.
|
||||
-- Never throws: bad arguments give an empty palette / a zero-filled index buffer.
|
||||
-- codecs/image/Quantize: palette quantization of rgba8 pixels (median cut or octree, Floyd-Steinberg dithering).
|
||||
-- New in rosetta: Heckbert's median cut and the Gervautz-Purgathofer octree over a 5-bit-per-channel histogram;
|
||||
-- deterministic on every runtime (no table iteration order is relied on).
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64
|
||||
local floor = math.floor
|
||||
@@ -22,18 +11,17 @@ local blen = buffer.len
|
||||
|
||||
local Quantize = {}
|
||||
|
||||
export type Color = { number } -- { r, g, b, a } 0..255
|
||||
export type Color = { number }
|
||||
export type PaletteOptions = {
|
||||
method: ("mediancut" | "octree")?, -- default "mediancut"
|
||||
method: ("mediancut" | "octree")?,
|
||||
}
|
||||
export type MapOptions = {
|
||||
dither: boolean?, -- Floyd-Steinberg error diffusion (default false)
|
||||
transparentIndex: number?, -- 0-based index for pixels with alpha < 128 (default: none)
|
||||
dither: boolean?,
|
||||
transparentIndex: number?,
|
||||
}
|
||||
|
||||
local BINS = 32768 -- 5 bits per channel
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ helpers
|
||||
local function count(pixels: buffer, n: number): (buffer, buffer)
|
||||
-- per bin: u32 count; f64 sums of r, g, b
|
||||
local cnt = buffer.create(BINS * 4)
|
||||
@@ -68,7 +56,6 @@ local function mean(cnt: buffer, sums: buffer, bins: { number }, lo: number, hi:
|
||||
return { floor(r / n + 0.5), floor(g / n + 0.5), floor(b / n + 0.5), 255 }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ median cut
|
||||
local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color }
|
||||
local bins: { number } = {}
|
||||
for bin = 0, BINS - 1 do
|
||||
@@ -79,7 +66,6 @@ local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color
|
||||
if #bins == 0 then
|
||||
return {}
|
||||
end
|
||||
-- boxes: { lo, hi } ranges of the bins array
|
||||
local boxes: { { number } } = {}
|
||||
local function channel(bin: number, c: number): number
|
||||
if c == 0 then
|
||||
@@ -90,7 +76,6 @@ local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color
|
||||
return bin % 32
|
||||
end
|
||||
local function stats(box: { number }): (number, number, number)
|
||||
-- returns the widest channel, its range, the pixel count
|
||||
local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 }
|
||||
local n = 0
|
||||
for i = box[1], box[2] do
|
||||
@@ -164,11 +149,10 @@ local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color
|
||||
return pal
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ octree
|
||||
-- over the histogram bins: 5 levels (one bit of each channel per level). Nodes are array slots.
|
||||
-- octree over the histogram bins: 5 levels, one bit of each channel per level
|
||||
local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color }
|
||||
local child: { number } = {} -- node * 8 + k -> node (0 = none)
|
||||
local n: { number } = {} -- pixel count
|
||||
local n: { number } = {}
|
||||
local sr: { number }, sg: { number }, sb: { number } = {}, {}, {}
|
||||
local leaf: { boolean } = {}
|
||||
local level: { number } = {}
|
||||
@@ -177,7 +161,7 @@ local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color }
|
||||
for k = 1, 8 do
|
||||
child[k] = 0
|
||||
end
|
||||
local byLevel: { { number } } = { {}, {}, {}, {}, {} } -- inner nodes per level 0..4, creation order
|
||||
local byLevel: { { number } } = { {}, {}, {}, {}, {} }
|
||||
table.insert(byLevel[1], 1)
|
||||
local leaves = 0
|
||||
for bin = 0, BINS - 1 do
|
||||
@@ -215,7 +199,6 @@ local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color }
|
||||
end
|
||||
-- fold the deepest inner nodes (fewest pixels first, ties by creation order) until few enough leaves remain
|
||||
local function fold(node: number): number
|
||||
-- merges the children (all leaves) into node; returns how many leaves disappeared
|
||||
local merged = 0
|
||||
for k = 1, 8 do
|
||||
local slot = (node - 1) * 8 + k
|
||||
@@ -264,7 +247,6 @@ local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color }
|
||||
leaves -= fold(e[1])
|
||||
end
|
||||
end
|
||||
-- collect leaves depth first in child order
|
||||
local pal: { Color } = {}
|
||||
local function walk(node: number)
|
||||
if leaf[node] then
|
||||
@@ -289,15 +271,12 @@ local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color }
|
||||
return pal
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ palette
|
||||
-- palette(pixels, w, h, maxColors, opts?) -> palette, exact
|
||||
function Quantize.palette(pixels: buffer, w: number, h: number, maxColors: number, opts: PaletteOptions?): ({ Color }, boolean)
|
||||
if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 then
|
||||
return {}, false
|
||||
end
|
||||
local maxc = math.clamp(floor(tonumber(maxColors) or 256), 1, 65536)
|
||||
local npx = w * h
|
||||
-- exact colours, in first-seen order (stops counting past maxColors)
|
||||
local seen: { [number]: boolean } = {}
|
||||
local exact: { Color } = {}
|
||||
local over = false
|
||||
@@ -327,8 +306,6 @@ function Quantize.palette(pixels: buffer, w: number, h: number, maxColors: numbe
|
||||
return medianCut(cnt, sums, maxc), false
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ map
|
||||
-- map(pixels, w, h, palette, opts?) -> buffer of w * h palette indexes (0-based)
|
||||
function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, opts: MapOptions?): buffer
|
||||
if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 or type(palette) ~= "table" then
|
||||
return buffer.create(0)
|
||||
@@ -337,7 +314,6 @@ function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color },
|
||||
local out = buffer.create(npx)
|
||||
local dither = opts and opts.dither or false
|
||||
local tidx = opts and opts.transparentIndex
|
||||
-- the searchable entries (the transparent slot is excluded)
|
||||
local pr: { number }, pg: { number }, pb: { number }, pi: { number } = {}, {}, {}, {}
|
||||
for i, c in palette do
|
||||
if tidx == nil or i - 1 ~= tidx then
|
||||
@@ -362,7 +338,7 @@ function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color },
|
||||
end
|
||||
pr, pg, pb, pi = r2, g2, b2, i2
|
||||
end
|
||||
local startAt = table.create(256, np) -- the first entry with green >= g (1-based), np + 1 past the end
|
||||
local startAt = table.create(256, np)
|
||||
do
|
||||
local k = 1
|
||||
for g = 0, 255 do
|
||||
@@ -431,7 +407,6 @@ function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color },
|
||||
end
|
||||
return out
|
||||
end
|
||||
-- Floyd-Steinberg: error rows (f64 r, g, b per pixel, one extra pixel each side)
|
||||
local rowLen = (w + 2) * 24
|
||||
local cur, nxt = buffer.create(rowLen), buffer.create(rowLen)
|
||||
for y = 0, h - 1 do
|
||||
@@ -469,13 +444,12 @@ function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color },
|
||||
return out
|
||||
end
|
||||
|
||||
-- quantize(pixels, w, h, maxColors, opts?) -> indexes, palette, exact: palette() then map() (opts of both)
|
||||
function Quantize.quantize(pixels: buffer, w: number, h: number, maxColors: number, opts: any?): (buffer, { Color }, boolean)
|
||||
local pal, exact = Quantize.palette(pixels, w, h, maxColors, opts)
|
||||
local mo = opts
|
||||
if exact and opts and opts.dither then
|
||||
mo = table.clone(opts)
|
||||
mo.dither = false -- nothing to diffuse
|
||||
mo.dither = false
|
||||
end
|
||||
return Quantize.map(pixels, w, h, pal, mo), pal, exact
|
||||
end
|
||||
|
||||
@@ -1,29 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
|
||||
-- transform, with the nonzero and even-odd fill rules, plus a polygon stroker. Used by the fonts (glyph outlines) and
|
||||
-- by vector/svg. New code; the coverage accumulation is the signed-area method of font-rs (Raph Levien, Apache-2.0 /
|
||||
-- MIT, an algorithm description, no code copied) and of stb_truetype v2: every edge adds its exact signed area to an
|
||||
-- accumulation row; a running sum along the row gives the winding coverage of each pixel. The rules map the summed
|
||||
-- coverage a as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2.
|
||||
--
|
||||
-- local R = require("@rosetta/codecs/image/Raster")
|
||||
-- local p = R.path():moveTo(0, 0):lineTo(10, 0):quadTo(10, 10, 0, 10):close() -- or a plain command list:
|
||||
-- local cmds = { { op = "moveTo", 0, 0 }, { op = "lineTo", 10, 0 }, { op = "cubicTo", 12, 2, 12, 8, 10, 10 },
|
||||
-- { op = "close" } } -- (the Font:outline() format)
|
||||
-- local m = R.mask(cmds, { transform = { 2, 0, 0, 2, 5, 5 }, rule = "evenodd", clip = { 0, 0, 64, 64 } })
|
||||
-- -- m = { x, y, width, height, coverage: buffer (u8, width * height) } in device pixels, or nil when empty
|
||||
-- R.fill(img, cmds, { 255, 0, 0, 255 }, { transform = t }) -- composite onto an rgba8 Image (source over)
|
||||
-- R.fill(img, cmds, function(x, y) return r, g, b, a end) -- a paint function per covered pixel (gradients)
|
||||
-- local outline = R.stroke(cmds, { width = 2, join = "round", cap = "butt" }) -- a path to fill (nonzero)
|
||||
--
|
||||
-- Transforms are { a, b, c, d, e, f } (SVG matrix order): x' = a x + c y + e, y' = b x + d y + f. Coordinates are
|
||||
-- pixels with y down; a pixel (i, j) covers [i, i+1) x [j, j+1). Curves are flattened in device space to
|
||||
-- opts.tolerance (default 0.1 px). Subpaths are implicitly closed for filling.
|
||||
--
|
||||
-- Never throws: malformed commands (missing or non-number operands) are skipped, non-finite coordinates drop the
|
||||
-- edge, sizes are bounded by opts.maxPixels (default 2^26), so it is safe for native code and untrusted paths.
|
||||
-- codecs/image/Raster: an antialiased scanline rasterizer (nonzero / even-odd) for line and Bézier paths, plus a stroker.
|
||||
-- New code; the signed-area accumulation follows font-rs (Raph Levien, Apache-2.0 / MIT; algorithm only) and stb_truetype
|
||||
-- v2, and the summed coverage a maps as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2.
|
||||
local Raster = {}
|
||||
|
||||
local floor, ceil, min, max, abs, sqrt = math.floor, math.ceil, math.min, math.max, math.abs, math.sqrt
|
||||
@@ -35,20 +15,19 @@ export type Path = { Cmd }
|
||||
export type Transform = { number }
|
||||
export type Mask = { x: number, y: number, width: number, height: number, coverage: buffer }
|
||||
export type Options = {
|
||||
transform: Transform?, -- default identity
|
||||
rule: ("nonzero" | "evenodd")?, -- default "nonzero"
|
||||
clip: { number }?, -- { x0, y0, x1, y1 } device pixel bounds (integers); default: the path's bounds (fill: the image)
|
||||
tolerance: number?, -- curve flattening tolerance in device pixels (default 0.1)
|
||||
maxPixels: number?, -- largest mask (default 2^26)
|
||||
opacity: number?, -- fill: multiplies the coverage (0..1, default 1)
|
||||
transform: Transform?,
|
||||
rule: ("nonzero" | "evenodd")?,
|
||||
clip: { number }?,
|
||||
tolerance: number?,
|
||||
maxPixels: number?,
|
||||
opacity: number?,
|
||||
}
|
||||
|
||||
local LIMIT = 1e7 -- coordinates beyond this (device pixels) are treated as broken
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
-- transforms { a, b, c, d, e, f } in SVG matrix order: x' = a x + c y + e, y' = b x + d y + f
|
||||
Raster.IDENTITY = table.freeze({ 1, 0, 0, 1, 0, 0 })
|
||||
|
||||
-- multiply(m, n) -> m * n (apply n first, then m)
|
||||
function Raster.multiply(m: Transform, n: Transform): Transform
|
||||
return {
|
||||
m[1] * n[1] + m[3] * n[2],
|
||||
@@ -69,7 +48,6 @@ function Raster.rotate(radians: number): Transform
|
||||
local c, s = math.cos(radians), math.sin(radians)
|
||||
return { c, s, -s, c, 0, 0 }
|
||||
end
|
||||
-- invert(m) -> m^-1 | nil (singular)
|
||||
function Raster.invert(m: Transform): Transform?
|
||||
local det = m[1] * m[4] - m[2] * m[3]
|
||||
if det == 0 or det ~= det then
|
||||
@@ -79,18 +57,14 @@ function Raster.invert(m: Transform): Transform?
|
||||
local a, b, c, d = m[4] * id, -m[2] * id, -m[3] * id, m[1] * id
|
||||
return { a, b, c, d, -(a * m[5] + c * m[6]), -(b * m[5] + d * m[6]) }
|
||||
end
|
||||
-- apply(m, x, y) -> x', y'
|
||||
function Raster.apply(m: Transform, x: number, y: number): (number, number)
|
||||
return m[1] * x + m[3] * y + m[5], m[2] * x + m[4] * y + m[6]
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ path builder
|
||||
local Builder = {}
|
||||
Builder.__index = Builder
|
||||
export type Builder = typeof(setmetatable({} :: { cmds: Path }, Builder))
|
||||
|
||||
-- path() -> a Builder; every method returns the builder; builder.cmds is the command list (any API taking a path
|
||||
-- takes a builder too)
|
||||
function Raster.path(): Builder
|
||||
return setmetatable({ cmds = {} :: Path }, Builder)
|
||||
end
|
||||
@@ -114,7 +88,6 @@ function Builder.close(self: Builder): Builder
|
||||
table.insert(self.cmds, { op = "close" } :: Cmd)
|
||||
return self
|
||||
end
|
||||
-- rect(x, y, w, h), ellipse(cx, cy, rx, ry): closed subpaths
|
||||
function Builder.rect(self: Builder, x: number, y: number, w: number, h: number): Builder
|
||||
return self:moveTo(x, y):lineTo(x + w, y):lineTo(x + w, y + h):lineTo(x, y + h):close()
|
||||
end
|
||||
@@ -138,7 +111,6 @@ local function commands(path: any): Path?
|
||||
return path
|
||||
end
|
||||
|
||||
-- n numeric operands of a command, or nil
|
||||
local function operands(c: any, n: number): boolean
|
||||
if type(c) ~= "table" then
|
||||
return false
|
||||
@@ -152,9 +124,6 @@ local function operands(c: any, n: number): boolean
|
||||
return true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ flattening
|
||||
-- flatten(path, transform?, tolerance?) -> polylines: { { x1, y1, x2, y2, ... } } in device space, one per subpath
|
||||
-- (closed implicitly; the closing point is not repeated), and the bounds x0, y0, x1, y1 (nil when empty)
|
||||
local function flatten(path: any, transform: Transform?, tolerance: number?, minLen: number): ({ { number } }, number?, number?, number?, number?)
|
||||
local cmds = commands(path)
|
||||
local polys: { { number } } = {}
|
||||
@@ -171,8 +140,8 @@ local function flatten(path: any, transform: Transform?, tolerance: number?, min
|
||||
tol = 0.1
|
||||
end
|
||||
local cur: { number }? = nil
|
||||
local px, py = 0, 0 -- current point (device)
|
||||
local sx, sy = 0, 0 -- subpath start (device)
|
||||
local px, py = 0, 0
|
||||
local sx, sy = 0, 0
|
||||
local bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge
|
||||
local function point(x: number, y: number)
|
||||
local poly = cur :: { number }
|
||||
@@ -280,9 +249,7 @@ function Raster.flatten(path: any, transform: Transform?, tolerance: number?): (
|
||||
return flatten(path, transform, tolerance, 6)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ accumulation
|
||||
-- one edge (x0, y0) -> (x1, y1), already inside [0, W] horizontally, into acc (stride S, H rows): the signed area
|
||||
-- each pixel gains (font-rs's draw_line)
|
||||
-- the signed area each pixel gains from one edge (font-rs draw_line)
|
||||
local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x1: number, y1: number)
|
||||
if y0 == y1 then
|
||||
return
|
||||
@@ -362,9 +329,7 @@ local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x
|
||||
end
|
||||
end
|
||||
|
||||
-- an edge in mask coordinates, split where it crosses x = 0 and x = W (in its own order: the direction is the
|
||||
-- winding sign); the parts outside are pushed onto the border (their area lies outside the mask, their cover still
|
||||
-- applies to the row)
|
||||
-- edges split at x = 0 / x = W: the parts outside go onto the border, whose cover still applies to the row
|
||||
local function clampx(x: number, W: number): number
|
||||
return if x < 0 then 0 elseif x > W then W else x
|
||||
end
|
||||
@@ -376,7 +341,7 @@ local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0
|
||||
return
|
||||
end
|
||||
local dx = x1 - x0
|
||||
local ta, tb = 2, 2 -- parameters of the crossings with x = 0 and x = W (2 = none)
|
||||
local ta, tb = 2, 2
|
||||
if dx ~= 0 then
|
||||
local t0 = (0 - x0) / dx
|
||||
local tw = (W - x0) / dx
|
||||
@@ -405,8 +370,6 @@ local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0
|
||||
line(acc, S, H, clampx(px, W), py, clampx(x1, W), y1)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ masks
|
||||
-- mask(path, opts?) -> Mask | nil (empty, or over the size limit: then the second result is "limit")
|
||||
function Raster.mask(path: any, opts: Options?): (Mask?, string?)
|
||||
local o: Options = opts or {}
|
||||
local polys, bx0, by0, bx1, by1 = Raster.flatten(path, o.transform, o.tolerance)
|
||||
@@ -467,11 +430,6 @@ function Raster.mask(path: any, opts: Options?): (Mask?, string?)
|
||||
return { x = X0, y = Y0, width = W, height = H, coverage = cov }, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ filling
|
||||
-- fill(img, path, paint, opts?) -> true | false, message. img: an rgba8 Image ({ width, height, pixels }); paint: an
|
||||
-- { r, g, b, a } colour (0..255) or a function(x, y) -> r, g, b, a called per covered pixel (pixel centres in
|
||||
-- device space: x + 0.5, y + 0.5). Composites source-over onto the straight-alpha pixels. opts.clip defaults to the
|
||||
-- image; opts.opacity scales the coverage.
|
||||
function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, string?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then
|
||||
return false, "fill: expected an rgba8 image"
|
||||
@@ -536,14 +494,13 @@ function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean,
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ stroking
|
||||
export type StrokeOptions = {
|
||||
width: number?, -- default 1
|
||||
join: ("miter" | "round" | "bevel")?, -- default "miter"
|
||||
cap: ("butt" | "round" | "square")?, -- default "butt"
|
||||
miterLimit: number?, -- default 4 (SVG)
|
||||
tolerance: number?, -- flattening tolerance in path units (default 0.1); scale it down for magnified strokes
|
||||
closed: boolean?, -- treat every subpath as closed (default: only subpaths ending with "close")
|
||||
width: number?,
|
||||
join: ("miter" | "round" | "bevel")?,
|
||||
cap: ("butt" | "round" | "square")?,
|
||||
miterLimit: number?,
|
||||
tolerance: number?,
|
||||
closed: boolean?,
|
||||
}
|
||||
|
||||
-- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up
|
||||
@@ -586,8 +543,6 @@ local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: numb
|
||||
end
|
||||
end
|
||||
|
||||
-- stroke(path, opts?) -> Path: the outline of the stroke as pieces to fill with the nonzero rule (in the path's own
|
||||
-- coordinate space: transform it like the path). Dashes are the caller's job (split the path first).
|
||||
function Raster.stroke(path: any, opts: StrokeOptions?): Path
|
||||
local o: StrokeOptions = opts or {}
|
||||
local hw = (if type(o.width) == "number" and o.width > 0 then o.width else 1) / 2
|
||||
@@ -640,7 +595,6 @@ function Raster.stroke(path: any, opts: StrokeOptions?): Path
|
||||
end
|
||||
continue
|
||||
end
|
||||
-- drop repeated points
|
||||
local p: { number } = { pts[1], pts[2] }
|
||||
for i = 3, #pts - 1, 2 do
|
||||
if abs(pts[i] - p[#p - 1]) > 1e-9 or abs(pts[i + 1] - p[#p]) > 1e-9 then
|
||||
@@ -658,7 +612,6 @@ function Raster.stroke(path: any, opts: StrokeOptions?): Path
|
||||
continue
|
||||
end
|
||||
local segs = if closed then n else n - 1
|
||||
-- segment bodies
|
||||
local dirs: { number } = {}
|
||||
for s = 0, segs - 1 do
|
||||
local i, j = s, (s + 1) % n
|
||||
@@ -670,7 +623,6 @@ function Raster.stroke(path: any, opts: StrokeOptions?): Path
|
||||
local nx, ny = -uy * hw, ux * hw
|
||||
polygon(out, { x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny })
|
||||
end
|
||||
-- joins
|
||||
local function joinAt(k: number, s0: number, s1: number)
|
||||
local x, y = p[2 * k + 1], p[2 * k + 2]
|
||||
local ax, ay = dirs[2 * s0 + 1], dirs[2 * s0 + 2]
|
||||
@@ -697,7 +649,7 @@ function Raster.stroke(path: any, opts: StrokeOptions?): Path
|
||||
arcPoints(x, y, hw, a0, a0 + da, tol, d)
|
||||
polygon(out, d)
|
||||
else
|
||||
local cosT = ax * bx + ay * by -- angle between directions
|
||||
local cosT = ax * bx + ay * by
|
||||
local miter = if join == "miter" then 1 / sqrt(max(1e-12, (1 + cosT) / 2)) else math.huge
|
||||
if join == "miter" and miter <= miterLimit then
|
||||
local mx, my = n0x + n1x, n0y + n1y
|
||||
@@ -719,12 +671,11 @@ function Raster.stroke(path: any, opts: StrokeOptions?): Path
|
||||
for k = 1, n - 2 do
|
||||
joinAt(k, k - 1, k)
|
||||
end
|
||||
-- caps
|
||||
if cap ~= "butt" then
|
||||
for _, endInfo in { { 0, 0, -1 }, { n - 1, segs - 1, 1 } } do
|
||||
local k, s, sgn = endInfo[1], endInfo[2], endInfo[3]
|
||||
local x, y = p[2 * k + 1], p[2 * k + 2]
|
||||
local ux, uy = dirs[2 * s + 1] * sgn, dirs[2 * s + 2] * sgn -- pointing outwards
|
||||
local ux, uy = dirs[2 * s + 1] * sgn, dirs[2 * s + 2] * sgn
|
||||
local nx, ny = -uy * hw, ux * hw
|
||||
if cap == "square" then
|
||||
polygon(out, { x + nx, y + ny, x + nx + ux * hw, y + ny + uy * hw, x - nx + ux * hw, y - ny + uy * hw, x - nx, y - ny })
|
||||
|
||||
@@ -1,33 +1,20 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers
|
||||
-- (DDS's DXGI and legacy bit-mask formats, KTX's Vulkan / OpenGL formats, ...). New in rosetta. Formats are named
|
||||
-- lower case, channels from the lowest address / bit up (DXGI order): r8, rg8, rgb8, bgr8, rgba8, bgra8, bgrx8, a8,
|
||||
-- l8, la8, r16, rgba16, *s (snorm), *ui / *i (integers), *f (half / float: r16f ... rgba32f), and the packed ones:
|
||||
-- b5g6r5, r5g6b5, b5g5r5a1, a1b5g5r5, b4g4r4a4, a4b4g4r4, a4r4g4b4, rgb10a2, bgr10a2, r11g11b10f, rgb9e5; any other
|
||||
-- bit-mask layout through Texel.masked(bytes, rMask, gMask, bMask, aMask, luminance?). Never throws.
|
||||
--
|
||||
-- local px, fmt = Texel.decode("bgra8", buf, offset, w, h) -- rgba8 pixels
|
||||
-- local px, fmt = Texel.decode("rgba16f", buf, offset, w, h, true) -- native: rgbaf32 (float) / rgba16 (16-bit)
|
||||
-- local desc = Texel.masked(2, 0xF800, 0x07E0, 0x001F, 0) -- a descriptor, accepted by decode
|
||||
--
|
||||
-- Channels: one-channel formats (r*, l*) are grey (r = g = b), two-channel ones red + green; missing alpha is opaque.
|
||||
-- rgba8 output: unorm rescaled with rounding, snorm biased (8-bit: s + 128), floats clamped to 0..1, integers clamped
|
||||
-- to 0..255. Native output: rgba8 when every channel fits 8 bits unsigned, rgba16 for 9..16-bit unorm, else rgbaf32
|
||||
-- (snorm -> -1..1, integers as their values).
|
||||
-- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats. New in rosetta.
|
||||
-- Names list channels from the lowest address / bit up (DXGI order); snorm -> rgba8 is biased (8-bit: s + 128).
|
||||
local Half = require("@rosetta/codecs/image/Half")
|
||||
|
||||
local Texel = {}
|
||||
|
||||
export type Channel = { c: string, shift: number, bits: number } -- packed channels (c = r g b a l)
|
||||
export type Channel = { c: string, shift: number, bits: number }
|
||||
export type Desc = {
|
||||
bytes: number, -- per texel
|
||||
bytes: number,
|
||||
kind: "array" | "packed" | "r11g11b10f" | "rgb9e5" | "pair" | "ayuv",
|
||||
size: number?, -- array: bytes per component (1, 2, 4)
|
||||
type: string?, -- array: unorm / snorm / uint / sint / float
|
||||
order: string?, -- array: the components in memory (r g b a l x); pair: the 4 bytes of 2 pixels (yuyv, uyvy, rgbg, grgb)
|
||||
channels: { Channel }?, -- packed: unorm fields of a little-endian 16 / 32-bit word
|
||||
size: number?,
|
||||
type: string?,
|
||||
order: string?,
|
||||
channels: { Channel }?,
|
||||
}
|
||||
|
||||
local readu8, readu16, readu32, readi8, readi16, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readf32
|
||||
@@ -35,7 +22,6 @@ local writeu8, writeu16, writeu32, writef32 = buffer.writeu8, buffer.writeu16, b
|
||||
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
|
||||
local HALF = Half.TABLE
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ formats
|
||||
local FORMATS: { [string]: Desc } = {}
|
||||
local function array(name: string, size: number, typ: string, order: string)
|
||||
FORMATS[name] = { bytes = size * #order, kind = "array", size = size, type = typ, order = order }
|
||||
@@ -95,8 +81,6 @@ FORMATS.grgb = { bytes = 2, kind = "pair", order = "grgb" }
|
||||
FORMATS.ayuv = { bytes = 4, kind = "ayuv" }
|
||||
Texel.FORMATS = FORMATS
|
||||
|
||||
-- masked(bytes, r, g, b, a, luminance?) -> a packed descriptor from bit masks (DDS legacy pixel formats); luminance:
|
||||
-- the r mask is a luminance channel
|
||||
function Texel.masked(bytes: number, r: number, g: number, b: number, a: number, luminance: boolean?): Desc?
|
||||
if bytes < 1 or bytes > 4 then
|
||||
return nil
|
||||
@@ -122,7 +106,6 @@ function Texel.masked(bytes: number, r: number, g: number, b: number, a: number,
|
||||
return { bytes = bytes, kind = "packed", channels = ch }
|
||||
end
|
||||
|
||||
-- size(fmt, w, h) -> bytes (rows tightly packed) | nil
|
||||
function Texel.size(fmt: string | Desc, w: number, h: number): number?
|
||||
local d = if type(fmt) == "string" then FORMATS[fmt] else fmt
|
||||
if not d then
|
||||
@@ -131,8 +114,6 @@ function Texel.size(fmt: string | Desc, w: number, h: number): number?
|
||||
return if d.kind == "pair" then ((w + 1) // 2) * 4 * h else d.bytes * w * h
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ helpers
|
||||
-- the native output of a descriptor: rgba8 / rgba16 / rgbaf32
|
||||
local function nativeOf(d: Desc): string
|
||||
if d.kind == "array" then
|
||||
local t, s = d.type, d.size :: number
|
||||
@@ -170,7 +151,6 @@ local function uf10(v: number): number
|
||||
return (1 + m / 32) * 2 ^ (e - 15)
|
||||
end
|
||||
|
||||
-- one component at q of an array format -> a float (native meaning) and its rgba8 byte
|
||||
local function component(src: buffer, q: number, size: number, typ: string): (number, number)
|
||||
if typ == "unorm" then
|
||||
if size == 1 then
|
||||
@@ -204,7 +184,6 @@ local function component(src: buffer, q: number, size: number, typ: string): (nu
|
||||
return v, math.clamp(v, 0, 255)
|
||||
end
|
||||
|
||||
-- BT.601 limited-range Y'CbCr -> an rgba8 u32
|
||||
local function ycc(y: number, u: number, v: number, a: number): number
|
||||
local c, d, e = 1.164 * (y - 16), u - 128, v - 128
|
||||
local r = math.clamp(math.floor(c + 1.596 * e + 0.5), 0, 255)
|
||||
@@ -213,7 +192,6 @@ local function ycc(y: number, u: number, v: number, a: number): number
|
||||
return r + g * 256 + b * 65536 + a * 16777216
|
||||
end
|
||||
|
||||
-- the 4:2:2 pair formats and AYUV -> rgba8 (out is always rgba8: 8-bit sources)
|
||||
local function yuv(d: Desc, src: buffer, offset: number, w: number, h: number, pitch: number, dst: buffer): buffer
|
||||
local n = 0
|
||||
local order = d.order or ""
|
||||
@@ -243,9 +221,6 @@ local function yuv(d: Desc, src: buffer, offset: number, w: number, h: number, p
|
||||
return dst
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decode(fmt, src, offset, w, h, native?, rowPitch?) -> pixels, pixel format ("rgba8" / "rgba16" / "rgbaf32") | nil,
|
||||
-- message. rowPitch: bytes per source row (default tight).
|
||||
function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number, h: number, native: boolean?, rowPitch: number?): (buffer?, string)
|
||||
local d = if type(fmt) == "string" then FORMATS[fmt] else fmt
|
||||
if not d then
|
||||
@@ -266,7 +241,6 @@ function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number
|
||||
local n = 0
|
||||
if d.kind == "array" then
|
||||
local order, size, typ = d.order :: string, d.size :: number, d.type :: string
|
||||
-- fast paths
|
||||
if size == 1 and typ == "unorm" and out == "rgba8" and (order == "rgba" or order == "bgra" or order == "bgrx" or order == "rgbx") then
|
||||
local swap = order == "bgra" or order == "bgrx"
|
||||
local opaque = order == "bgrx" or order == "rgbx"
|
||||
@@ -287,7 +261,7 @@ function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number
|
||||
return dst, out
|
||||
end
|
||||
local nc = #order
|
||||
local map = table.create(nc, 0) -- component -> output channel 0..3, 4 = grey, -1 = skip
|
||||
local map = table.create(nc, 0)
|
||||
for i = 1, nc do
|
||||
local c = string.sub(order, i, i)
|
||||
map[i] = if c == "r" then (if nc == 1 then 4 else 0) elseif c == "g" then 1 elseif c == "b" then 2 elseif c == "a" then 3 elseif c == "l" then 4 else -1
|
||||
@@ -367,7 +341,6 @@ function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number
|
||||
if d.kind == "pair" or d.kind == "ayuv" then
|
||||
return yuv(d, src, offset, w, h, pitch, dst), out
|
||||
end
|
||||
-- shared-exponent / packed floats
|
||||
local nine = d.kind == "rgb9e5"
|
||||
for y = 0, h - 1 do
|
||||
local s = offset + y * pitch
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
--!strict
|
||||
-- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...):
|
||||
-- a format name is a BCn kind (codecs/image/Bcn), an ETC / EAC kind (codecs/image/Etc) or a texel format
|
||||
-- (codecs/image/Texel); decode / size dispatch on it, surfaces() assembles mip levels / faces / layers into one
|
||||
-- Types.Image, halve() makes the next mip level of an image for writers. New in rosetta. Never throws.
|
||||
--
|
||||
-- local px, pf = Texture.decode("bc7", buf, offset, w, h, native) -- pixels + their pixel format
|
||||
-- Texture.size("etc2_rgb", w, h) -- bytes of one surface
|
||||
-- local img = Texture.image(px, pf, w, h) -- a Types.Image around them
|
||||
-- local smaller = Texture.halve(img) -- box-filtered next mip level
|
||||
-- codecs/image/Texture: one entry point over the texture pixel codecs (Bcn, Etc, Texel). New in rosetta.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Bcn = require("@rosetta/codecs/image/Bcn")
|
||||
local Etc = require("@rosetta/codecs/image/Etc")
|
||||
@@ -16,7 +8,6 @@ local Half = require("@rosetta/codecs/image/Half")
|
||||
|
||||
local Texture = {}
|
||||
|
||||
-- known(name) -> "bcn" | "etc" | "texel" | nil
|
||||
function Texture.known(name: string): string?
|
||||
if Bcn.BLOCK[name] then
|
||||
return "bcn"
|
||||
@@ -28,12 +19,10 @@ function Texture.known(name: string): string?
|
||||
return nil
|
||||
end
|
||||
|
||||
-- size(name, w, h) -> bytes of a w x h surface | nil
|
||||
function Texture.size(name: string, w: number, h: number): number?
|
||||
return Bcn.size(name, w, h) or Etc.size(name, w, h) or Texel.size(name, w, h)
|
||||
end
|
||||
|
||||
-- block(name) -> block width, height, bytes (1, 1, texel bytes for texel formats) | nil
|
||||
function Texture.block(name: string): (number?, number?, number?)
|
||||
local b = Bcn.BLOCK[name] or Etc.BLOCK[name]
|
||||
if b then
|
||||
@@ -46,8 +35,6 @@ function Texture.block(name: string): (number?, number?, number?)
|
||||
return nil, nil, nil
|
||||
end
|
||||
|
||||
-- decode(name, src, offset, w, h, native?) -> pixels, pixel format | nil, message. Without native the result is
|
||||
-- rgba8 (BC6H and float texels clamped to 0..1); native keeps rgbaf32 (BC6H, floats) / rgba16 (EAC, 16-bit unorm).
|
||||
function Texture.decode(name: string, src: buffer, offset: number, w: number, h: number, native: boolean?): (buffer?, string)
|
||||
if Bcn.BLOCK[name] then
|
||||
local px, err = Bcn.decode(name, src, offset, w, h)
|
||||
@@ -79,7 +66,6 @@ function Texture.decode(name: string, src: buffer, offset: number, w: number, h:
|
||||
return Texel.decode(name, src, offset, w, h, native)
|
||||
end
|
||||
|
||||
-- image(pixels, pixel format, w, h) -> Types.Image
|
||||
function Texture.image(px: buffer, pf: string, w: number, h: number): Types.Image
|
||||
local img = Types.Image.new(0, 0, pf :: any)
|
||||
img.width, img.height, img.pixels = w, h, px
|
||||
@@ -88,8 +74,6 @@ end
|
||||
|
||||
export type Surface = { level: number, layer: number, face: number, slice: number, image: Types.Image }
|
||||
|
||||
-- assemble(surfaces, layout) -> the Image of the first surface with img.frames = every level-0 surface (faces /
|
||||
-- layers / depth slices in order, when more than one) and img.meta.mipmaps = the smaller levels of the first surface
|
||||
function Texture.assemble(list: { Surface }, layout: string): Types.Image?
|
||||
local first: Types.Image? = nil
|
||||
local frames: { Types.Frame } = {}
|
||||
@@ -117,8 +101,6 @@ function Texture.assemble(list: { Surface }, layout: string): Types.Image?
|
||||
return img
|
||||
end
|
||||
|
||||
-- halve(img) -> the next mip level (each dimension halved, at least 1; 2 x 2 box filter), same pixel format
|
||||
-- (rgba8 / rgba16 / rgbaf32)
|
||||
function Texture.halve(img: Types.Image): Types.Image
|
||||
local w, h = img.width, img.height
|
||||
local nw, nh = math.max(1, w // 2), math.max(1, h // 2)
|
||||
@@ -149,7 +131,6 @@ function Texture.halve(img: Types.Image): Types.Image
|
||||
return out
|
||||
end
|
||||
|
||||
-- toHalf(rgbaf32 pixels, n) -> rgba16f texels (for writers)
|
||||
function Texture.toHalf(px: buffer, n: number): buffer
|
||||
local out = buffer.create(n * 8)
|
||||
local from = Half.fromFloat
|
||||
|
||||
@@ -1,21 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Vp8/Decode: the VP8 frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter /
|
||||
-- quantizer headers, token probability updates, intra modes, residual tokens, the inverse WHT and DCT, intra
|
||||
-- prediction (16x16, 4x4, chroma), and the normal and simple loop filters: a port of libwebp 1.6 src/dec/vp8_dec.c,
|
||||
-- tree_dec.c, quant_dec.c, frame_dec.c, src/dsp/dec.c and src/utils/bit_reader* (BSD-3-Clause,
|
||||
-- licenses/libwebp-LICENSE.txt). Inter frames after libvpx 1.17 vp8/decoder/decodeframe.c, decodemv.c and
|
||||
-- vp8/common/findnearmv.c, vp8_loopfilter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt): reference updates and sign
|
||||
-- bias, the frame context saved around frames that do not refresh it, persistent segment maps and loop filter deltas,
|
||||
-- inter modes from the near vectors, motion vectors, split macroblocks, intra macroblocks in inter frames, per
|
||||
-- reference / mode loop filter levels; the prediction itself is codecs/image/Vp8/Predict. Bit-exact with libvpx / ffmpeg
|
||||
-- (and with libwebp on key frames). Where libvpx and ffmpeg disagree on streams no encoder writes (an intermediate
|
||||
-- clamp of segment filter levels, copying golden to altref and altref to golden in one frame), this follows ffmpeg.
|
||||
--
|
||||
-- The decoder state (Decode.new) keeps what persists between frames: the frame context, segment / filter headers, the
|
||||
-- segment map, the last / golden / altref frames. Never throws: bad data returns nil, "message" ("truncated: ..." when
|
||||
-- the data ends early).
|
||||
-- codecs/image/Vp8/Decode: the VP8 frame decoder (RFC 6386), key frames a port of libwebp 1.6 src/dec + src/dsp/dec.c
|
||||
-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt), inter frames after libvpx 1.17 vp8/decoder + vp8/common (BSD-3-Clause,
|
||||
-- licenses/libvpx-LICENSE.txt). Where libvpx and ffmpeg disagree on streams no encoder writes, this follows ffmpeg.
|
||||
local Tables = require("@rosetta/codecs/image/Vp8/Tables")
|
||||
local Predict = require("@rosetta/codecs/image/Vp8/Predict")
|
||||
|
||||
@@ -34,7 +22,6 @@ local CAT = { Tables.CAT3, Tables.CAT4, Tables.CAT5, Tables.CAT6 }
|
||||
|
||||
local Decode = {}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ boolean decoder
|
||||
-- libwebp's VP8BitReader: `range` is the range minus one (127..254), `value` holds the unread bits, `bits` is the
|
||||
-- position of the 8-bit window in `value` (< 0: load more). Bytes past the end read as zero once and set eof.
|
||||
type Br = { buf: buffer, pos: number, limit: number, value: number, bits: number, range: number, eof: boolean }
|
||||
@@ -76,8 +63,8 @@ local function newBr(buf: buffer, off: number, len: number): Br
|
||||
return br
|
||||
end
|
||||
|
||||
-- getBit without a branch on the decoded bit (one inlined copy per call site keeps LuaJIT's trace count down):
|
||||
-- bit = 1 when value >> bits > split, then range = bit ? range - split : split + 1, value -= bit * (split + 1) << bits
|
||||
-- branchless getBit: bit = value >> bits > split; range = bit ? range - split : split + 1;
|
||||
-- value -= bit * (split + 1) << bits
|
||||
local function getBit(br: Br, prob: number): number
|
||||
if br.bits < 0 then
|
||||
load(br)
|
||||
@@ -107,10 +94,8 @@ local function getSignedValue(br: Br, n: number): number
|
||||
return if getBit(br, 0x80) == 1 then -v else v
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ state
|
||||
export type Quant = { y1dc: number, y1ac: number, y2dc: number, y2ac: number, uvdc: number, uvac: number }
|
||||
|
||||
-- a decoded frame / reference: the macroblock aligned planes with a Predict.BORDER pixel border
|
||||
export type Ref = Predict.Planes & { extended: boolean }
|
||||
|
||||
export type State = {
|
||||
@@ -129,12 +114,12 @@ export type State = {
|
||||
refLfDelta: { number }, -- 4: intra, last, golden, altref
|
||||
modeLfDelta: { number }, -- 4: B_PRED, zero, nearest / near / new, split
|
||||
signBias: { number }, -- 4 (by reference frame + 1)
|
||||
segMap: { number }, -- the segment of every macroblock
|
||||
segMap: { number },
|
||||
width: number,
|
||||
height: number,
|
||||
mbw: number,
|
||||
mbh: number,
|
||||
hasKey: boolean, -- a key frame was decoded (inter frames need one)
|
||||
hasKey: boolean,
|
||||
last: Ref?,
|
||||
golden: Ref?,
|
||||
alt: Ref?,
|
||||
@@ -146,8 +131,8 @@ export type State = {
|
||||
miMvC: { number },
|
||||
miSubR: { number }, -- 16 per macroblock
|
||||
miSubC: { number },
|
||||
miN: number, -- the size of the mode info arrays (allocated by the first inter frame)
|
||||
pred: buffer?, -- the inter predictions of a row
|
||||
miN: number,
|
||||
pred: buffer?,
|
||||
}
|
||||
|
||||
function Decode.new(): State
|
||||
@@ -186,13 +171,11 @@ function Decode.new(): State
|
||||
}
|
||||
end
|
||||
|
||||
-- reset(state): drops the references; the next frame must be a key frame
|
||||
function Decode.reset(st: State)
|
||||
st.hasKey = false
|
||||
st.last, st.golden, st.alt = nil, nil, nil
|
||||
end
|
||||
|
||||
-- header(buf, off, len) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, msg
|
||||
function Decode.header(buf: buffer, off: number, len: number): (any, string?)
|
||||
if len < 3 then
|
||||
return nil, "truncated: frame tag"
|
||||
@@ -226,7 +209,6 @@ function Decode.header(buf: buffer, off: number, len: number): (any, string?)
|
||||
return h, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ residuals
|
||||
local function getLargeValue(br: Br, P: { number }, p: number): number
|
||||
local v
|
||||
if getBit(br, P[p + 4]) == 0 then
|
||||
@@ -257,9 +239,7 @@ local function getLargeValue(br: Br, P: { number }, p: number): number
|
||||
return v
|
||||
end
|
||||
|
||||
-- getCoeffs(br, P, t, ctx, dqDc, dqAc, n, out, o) -> the position of the last non-zero coefficient + 1. Writes the
|
||||
-- dequantized coefficients (int16, as libwebp stores them) into out at byte offset o, in raster order. The boolean
|
||||
-- decoder is inlined (the hot loop of lossy decoding); getLargeValue goes through br.
|
||||
-- coefficients are dequantized to int16 as libwebp stores them, in raster order
|
||||
local function getCoeffs(br: Br, P: { number }, t: number, ctx: number, dqDc: number, dqAc: number, n: number, out: buffer, o: number): number
|
||||
local tb = t * 8
|
||||
local p = ((tb + BANDS[n + 1]) * 3 + ctx) * 11
|
||||
@@ -432,7 +412,6 @@ local function transformWHT(inp: buffer, out: buffer, o: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ reconstruction
|
||||
-- the work buffer of libwebp (yuv_b): BPS = 32, Y at row 1 column 8, U and V below it side by side
|
||||
local BPS = 32
|
||||
local Y_OFF = BPS + 8
|
||||
@@ -772,13 +751,11 @@ local function checkMode(mbx: number, mby: number, mode: number): number
|
||||
return mode
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ loop filter
|
||||
-- the filters are libwebp's DoFilter2 / DoFilter4 / DoFilter6 inlined into their loops (VP8ksclip1 clamps to
|
||||
-- [-128, 127], VP8ksclip2 to [-16, 15], VP8kclip1 to [0, 255]). Arithmetic shifts of small signed values are
|
||||
-- logical shifts of the value plus a bias: (a + 4) >> 3 = rshift(a + 4 + 1024, 3) - 128 for a >= -1024.
|
||||
|
||||
-- simpleFilter(b, p, step, along, thresh): SimpleVFilter16 / SimpleHFilter16 (16 positions). A position whose filter
|
||||
-- value a is 0 changes nothing and is skipped before the mask (flat areas).
|
||||
-- SimpleVFilter16 / SimpleHFilter16; a position whose filter value a is 0 changes nothing (skipped before the mask)
|
||||
local function simpleFilter(b: buffer, p: number, step: number, along: number, thresh: number)
|
||||
local t2 = 2 * thresh + 1
|
||||
for _ = 1, 16 do
|
||||
@@ -807,7 +784,7 @@ local function simpleFilter(b: buffer, p: number, step: number, along: number, t
|
||||
end
|
||||
end
|
||||
|
||||
-- filterEdge(b, p, hs, vs, size, thresh, it, hevT): the macroblock edge filter (FilterLoop26)
|
||||
-- the macroblock edge filter (FilterLoop26)
|
||||
local function filterEdge(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number)
|
||||
local t2 = 2 * thresh + 1
|
||||
for _ = 1, size do
|
||||
@@ -866,8 +843,7 @@ local function filterEdge(b: buffer, p: number, hs: number, vs: number, size: nu
|
||||
end
|
||||
end
|
||||
|
||||
-- filterInner(b, p, hs, vs, size, thresh, it, hevT): the inner edge filter (FilterLoop24); nothing changes when
|
||||
-- q0 == p0 and p1 == q1
|
||||
-- the inner edge filter (FilterLoop24); nothing changes when q0 == p0 and p1 == q1
|
||||
local function filterInner(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number)
|
||||
local t2 = 2 * thresh + 1
|
||||
for _ = 1, size do
|
||||
@@ -914,7 +890,6 @@ local function filterInner(b: buffer, p: number, hs: number, vs: number, size: n
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ inter modes
|
||||
local MODE_CTX = Tables.MODE_CONTEXTS
|
||||
local SUB_MV_REF_PROB = Tables.SUB_MV_REF_PROB
|
||||
local SPLIT_OFFSET, SPLIT_FILL, SPLIT_COUNT = Tables.SPLIT_OFFSET, Tables.SPLIT_FILL, Tables.SPLIT_COUNT
|
||||
@@ -976,17 +951,16 @@ end
|
||||
|
||||
export type Rows = {
|
||||
i4: { boolean }, -- no Y2 block (B_PRED or SPLITMV)
|
||||
modes: { number }, -- 16 per macroblock: the 16x16 intra mode or the 4x4 ones
|
||||
modes: { number },
|
||||
uv: { number },
|
||||
ref: { number }, -- 0 intra, 1 last, 2 golden, 3 altref
|
||||
mode: { number }, -- 0..9 (see MODE_LF)
|
||||
mode: { number },
|
||||
part: { number }, -- SPLITMV partitioning (0 16x8, 1 8x16, 2 8x8, 3 4x4) or -1
|
||||
}
|
||||
|
||||
local nr, nc, cnt = table.create(4, 0), table.create(4, 0), table.create(4, 0)
|
||||
|
||||
-- readInterMb(st, br, probs, mi, mbx, mby, rows): the modes and motion vectors of one inter frame macroblock (libvpx
|
||||
-- read_mb_modes_mv with vp8_find_near_mvs); mi: its 1-based index in the mode info arrays
|
||||
-- libvpx read_mb_modes_mv with vp8_find_near_mvs
|
||||
local function readInterMb(st: State, br: Br, probIntra: number, probLast: number, probGf: number, mi: number, mbx: number, mby: number, rows: Rows)
|
||||
local miRef, miMode, miMvR, miMvC = st.miRef, st.miMode, st.miMvR, st.miMvC
|
||||
local x1 = mbx + 1
|
||||
@@ -1187,11 +1161,10 @@ local function readInterMb(st: State, br: Br, probIntra: number, probLast: numbe
|
||||
miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = ref, mode, mvr, mvc
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ frame
|
||||
export type Frame = {
|
||||
width: number,
|
||||
height: number,
|
||||
ref: Ref, -- the decoded planes (the decoder keeps them as a reference: copy them out, see cropTo)
|
||||
ref: Ref,
|
||||
header: any,
|
||||
}
|
||||
|
||||
@@ -1213,7 +1186,6 @@ local function newRef(mbw: number, mbh: number): Ref
|
||||
}
|
||||
end
|
||||
|
||||
-- a frame buffer no reference uses
|
||||
local function freeRef(st: State): Ref
|
||||
for _, r in st.pool do
|
||||
if r ~= st.last and r ~= st.golden and r ~= st.alt then
|
||||
@@ -1225,7 +1197,6 @@ local function freeRef(st: State): Ref
|
||||
return r
|
||||
end
|
||||
|
||||
-- cropTo(frame, dy, oy, du, ou, dv, ov): copies the visible planes out (luma stride width, chroma ceil(width / 2))
|
||||
function Decode.cropTo(f: Frame, dy: buffer, oy: number, du: buffer, ou: number, dv: buffer, ov: number)
|
||||
local r = f.ref
|
||||
local w, h = f.width, f.height
|
||||
@@ -1240,7 +1211,6 @@ function Decode.cropTo(f: Frame, dy: buffer, oy: number, du: buffer, ou: number,
|
||||
end
|
||||
end
|
||||
|
||||
-- decodeFrame(state, buf, off, len, maxPixels) -> Frame | nil, message: one key or inter frame of the stream
|
||||
function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, maxPixels: number): (Frame?, string?)
|
||||
local hdr, herr = Decode.header(buf, off, len)
|
||||
if not hdr then
|
||||
@@ -1502,7 +1472,6 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma
|
||||
end
|
||||
end
|
||||
|
||||
-- the frame buffer (macroblock aligned, with a border) and the references
|
||||
local cur = freeRef(st)
|
||||
cur.extended = false
|
||||
local Y, U, V, ys, uvs, yb, uvb = cur.Y, cur.U, cur.V, cur.ys, cur.uvs, cur.yb, cur.uvb
|
||||
@@ -1536,7 +1505,6 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma
|
||||
end
|
||||
local coeffs = bcreate(mbw * 768)
|
||||
local dcb = bcreate(32)
|
||||
-- per macroblock column / row state
|
||||
local intraT = table.create(mbw * 4, 0)
|
||||
local intraL = table.create(4, 0)
|
||||
local topNz = table.create(mbw, 0)
|
||||
@@ -1554,7 +1522,6 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma
|
||||
local mbSkip = table.create(mbw, 0)
|
||||
local mbNzY = table.create(mbw, 0)
|
||||
local mbNzUv = table.create(mbw, 0)
|
||||
-- filter info for the whole frame: limit, ilevel, inner, hev per macroblock
|
||||
local fLimit = table.create(mbw * mbh, 0)
|
||||
local fIlevel = table.create(mbw * mbh, 0)
|
||||
local fInner = table.create(mbw * mbh, 0)
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the
|
||||
-- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the
|
||||
-- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and
|
||||
-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels
|
||||
-- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the
|
||||
-- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a
|
||||
-- block whose taps leave it is first copied with clamped coordinates. Never throws.
|
||||
-- codecs/image/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18), after libvpx 1.17 vp8/common/reconinter.c and
|
||||
-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the edge pixels extended forever,
|
||||
-- which equals libvpx's 32 pixel border plus its motion vector clamping.
|
||||
local Tables = require("@rosetta/codecs/image/Vp8/Tables")
|
||||
|
||||
local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill
|
||||
@@ -20,14 +16,12 @@ local Predict = {}
|
||||
local BORDER = 32
|
||||
Predict.BORDER = BORDER
|
||||
|
||||
-- the work buffer stride (codecs/image/Vp8/Decode: BPS)
|
||||
local BPS = 32
|
||||
|
||||
local emu = bcreate(32 * 32) -- a block with its taps, edges replicated
|
||||
local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional filter
|
||||
local emu = bcreate(32 * 32)
|
||||
local tmp = bcreate(32 * 32)
|
||||
|
||||
-- the six-tap filter along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7). Each output reads
|
||||
-- its six pixels (a sliding window of locals is no faster in Luau and stops LuaJIT's register allocator).
|
||||
-- six-tap along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7)
|
||||
local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
|
||||
local k = f * 6
|
||||
local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6]
|
||||
@@ -42,7 +36,6 @@ local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number,
|
||||
end
|
||||
end
|
||||
|
||||
-- the six-tap filter along columns
|
||||
local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
|
||||
local k = f * 6
|
||||
local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6]
|
||||
@@ -83,9 +76,6 @@ local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number,
|
||||
end
|
||||
end
|
||||
|
||||
-- block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil): predicts the w x h block at plane pixel
|
||||
-- (x, y) moved by (mvx, mvy) eighth pixels into dst at d (stride BPS). base: the offset of plane pixel (0, 0); wmax,
|
||||
-- hmax: the last pixel column / row of the (macroblock aligned) plane.
|
||||
local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean)
|
||||
local fx, fy = band(mvx, 7), band(mvy, 7)
|
||||
local px, py = x + (mvx - fx) // 8, y + (mvy - fy) // 8
|
||||
@@ -163,17 +153,14 @@ export type Planes = {
|
||||
Y: buffer,
|
||||
U: buffer,
|
||||
V: buffer,
|
||||
ys: number, -- luma stride
|
||||
uvs: number, -- chroma stride
|
||||
yb: number, -- offset of luma pixel (0, 0)
|
||||
ys: number,
|
||||
uvs: number,
|
||||
yb: number,
|
||||
uvb: number,
|
||||
mbw: number,
|
||||
mbh: number,
|
||||
}
|
||||
|
||||
-- mb(ref, mbx, mby, mvr, mvc, split, subR, subC, sb, dst, yo, uo, vo, bil, full): the prediction of one inter
|
||||
-- macroblock into the work buffer (luma at yo, chroma at uo / vo). Not split: one vector (mvr, mvc) in eighth pixels;
|
||||
-- split: the 16 block vectors subR / subC[sb + 1 .. sb + 16] (part < 3: the four 8x8 quarters share them).
|
||||
function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean)
|
||||
local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb
|
||||
local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1
|
||||
@@ -236,9 +223,6 @@ function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: num
|
||||
end
|
||||
end
|
||||
|
||||
-- row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full): predicts the
|
||||
-- inter macroblocks of a row (ref[mbx + 1] > 0: refs[ref]) into pred, macroblock mbx at mbx * chunk + yo / uo / vo;
|
||||
-- mi0 + mbx + 1: the mode info index of macroblock mbx. A loop of its own (LuaJIT traces it apart from the decoder).
|
||||
function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }, part: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, miSubC: { number }, mi0: number, pred: buffer, chunk: number, yo: number, uo: number, vo: number, bil: boolean, full: boolean)
|
||||
for mbx = 0, mbw - 1 do
|
||||
local rf = ref[mbx + 1]
|
||||
@@ -250,7 +234,6 @@ function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }
|
||||
end
|
||||
end
|
||||
|
||||
-- extend(P, stride, base, w, h): fills the BORDER pixels around a w x h plane with its edge pixels
|
||||
local function extend(P: buffer, stride: number, base: number, w: number, h: number)
|
||||
for r = 0, h - 1 do
|
||||
local o = base + r * stride
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/image/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6
|
||||
-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables
|
||||
-- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from
|
||||
-- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c;
|
||||
-- BSD-3-Clause, licenses/libvpx-LICENSE.txt). Flat 1-based arrays.
|
||||
-- codecs/image/Vp8/Tables: the VP8 tables of RFC 6386 (sections 11.5, 13.4, 13.5, 14.1, 16-18), from libwebp 1.6 src/dec
|
||||
-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt) and libvpx 1.17 vp8/common (BSD-3-Clause, licenses/libvpx-LICENSE.txt).
|
||||
-- Flat 1-based arrays.
|
||||
local Tables = {}
|
||||
|
||||
-- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Vp8/Yuv: 4:2:0 Y'CbCr (BT.601, limited range) to rgba8 the way libwebp's decoder does it, bit-exact: the
|
||||
-- 14-bit fixed-point VP8YuvToRgb of src/dsp/yuv.h, with either the "fancy" upsampler (src/dsp/upsampling.c: a 9-3-3-1
|
||||
-- bilinear filter on the chroma, libwebp's default) or point sampling (dwebp -nofancy). A port of libwebp 1.6
|
||||
-- codecs/image/Vp8/Yuv: 4:2:0 BT.601 limited-range Y'CbCr -> rgba8, bit-exact with libwebp (src/dsp/yuv.h VP8YuvToRgb;
|
||||
-- src/dsp/upsampling.c "fancy" 9-3-3-1 upsampler, or point sampling as dwebp -nofancy). A port of libwebp 1.6
|
||||
-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt).
|
||||
local rshift = bit32.rshift
|
||||
local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
|
||||
@@ -19,12 +18,10 @@ local function clip(v: number): number
|
||||
return if v < 0 then 0 else 255
|
||||
end
|
||||
|
||||
-- (v * coeff) >> 8 for non-negative v
|
||||
local function mulHi(v: number, c: number): number
|
||||
return rshift(v * c, 8)
|
||||
end
|
||||
|
||||
-- rgba(y, u, v) -> the pixel as a little-endian u32 (bytes R G B 255)
|
||||
local function rgba(y: number, u: number, v: number): number
|
||||
local yy = mulHi(y, 19077)
|
||||
local r = clip(yy + mulHi(v, 26149) - 14234)
|
||||
@@ -34,8 +31,7 @@ local function rgba(y: number, u: number, v: number): number
|
||||
end
|
||||
Yuv.rgba = rgba
|
||||
|
||||
-- upsamplePair: libwebp UPSAMPLE_FUNC for one or two output rows. ty / by: offsets of the top / bottom luma rows
|
||||
-- (by < 0: no bottom row), tu / cu: offsets of the top / current chroma rows; dt / db: output row offsets.
|
||||
-- libwebp UPSAMPLE_FUNC for one or two output rows (by < 0: no bottom row)
|
||||
local function upsamplePair(Y: buffer, U: buffer, V: buffer, ty: number, by: number, tu: number, cu: number, out: buffer, dt: number, db: number, len: number)
|
||||
local last = rshift(len - 1, 1)
|
||||
local tlu, tlv = readu8(U, tu), readu8(V, tu)
|
||||
@@ -80,7 +76,6 @@ local function upsamplePair(Y: buffer, U: buffer, V: buffer, ty: number, by: num
|
||||
end
|
||||
end
|
||||
|
||||
-- toRgba(y, u, v, w, h, fancy, out?) -> rgba8 (alpha 255). Planes are tightly packed (chroma ceil(w / 2) wide).
|
||||
function Yuv.toRgba(Y: buffer, U: buffer, V: buffer, w: number, h: number, fancy: boolean, out: buffer?): buffer
|
||||
local o = out or bcreate(w * h * 4)
|
||||
local cw = (w + 1) // 2
|
||||
@@ -113,7 +108,6 @@ function Yuv.toRgba(Y: buffer, U: buffer, V: buffer, w: number, h: number, fancy
|
||||
return o
|
||||
end
|
||||
|
||||
-- setAlpha(rgba, a8, n): copy an alpha plane into the A bytes
|
||||
function Yuv.setAlpha(o: buffer, a: buffer, n: number)
|
||||
for i = 0, n - 1 do
|
||||
writeu8(o, i * 4 + 3, readu8(a, i))
|
||||
|
||||
@@ -1,25 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
|
||||
-- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause,
|
||||
-- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals
|
||||
-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause,
|
||||
-- licenses/libvpx-LICENSE.txt), bit-exact with libvpx / ffmpeg on the official test vectors and libvpx streams.
|
||||
-- Supports: key and inter frames of every version / profile (0: six-tap filters, normal loop filter; 1-2: bilinear;
|
||||
-- 3: bilinear with full pixel chroma; the loop filter type is the header's), last / golden / altref references with
|
||||
-- sign bias, hidden (altref) frames, token partitions, segments, loop filter deltas, probability context save /
|
||||
-- restore. Not supported: the horizontal / vertical scale bits (ignored, as libwebp and ffmpeg do), error
|
||||
-- concealment (a damaged frame returns an Err).
|
||||
-- Speed (one Zen 5 core): 640x480 inter frames ~190 fps under luau --codegen, ~220 fps under LuaJIT with the trace
|
||||
-- limits the host module sets (maxtrace=8000; with LuaJIT's default 1000 traces the decoder thrashes: ~70 fps).
|
||||
--
|
||||
-- local Vp8 = require("@rosetta/codecs/image/Vp8")
|
||||
-- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image
|
||||
-- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling)
|
||||
-- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames
|
||||
-- local img, err = dec:decodeFrame(buf, off, len) -- img.meta.source.show == false: a hidden frame
|
||||
-- dec:reset() -- after a seek: the next frame must be a key frame
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG).
|
||||
-- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only.
|
||||
-- Key frames ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), inter frames after libvpx 1.17
|
||||
-- (BSD-3-Clause, licenses/libvpx-LICENSE.txt); bit-exact with both. Scale bits are ignored, as libwebp and ffmpeg do.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Decode = require("@rosetta/codecs/image/Vp8/Decode")
|
||||
@@ -30,7 +12,7 @@ local Vp8 = {}
|
||||
local DEFAULT_MAX_PIXELS = 2 ^ 28
|
||||
|
||||
export type Options = {
|
||||
maxPixels: number?, -- default 2^28
|
||||
maxPixels: number?,
|
||||
}
|
||||
|
||||
local function fail(msg: string?, offset: number?): Err.Err
|
||||
@@ -51,7 +33,6 @@ local function range(buf: buffer, off: number?, len: number?): (number, number)
|
||||
return o, math.clamp(len or (n - o), 0, n - o)
|
||||
end
|
||||
|
||||
-- info(buf, off?, len?) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, Err
|
||||
function Vp8.info(buf: buffer, off: number?, len: number?): (any, Err.Err?)
|
||||
if type(buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "info: expected a buffer")
|
||||
@@ -69,14 +50,10 @@ DecoderMeta.__index = DecoderMeta
|
||||
|
||||
export type Decoder = typeof(setmetatable({} :: { state: Decode.State }, DecoderMeta))
|
||||
|
||||
-- newDecoder() -> Decoder: decodes successive frames of one stream
|
||||
function Vp8.newDecoder(): Decoder
|
||||
return setmetatable({ state = Decode.new() }, DecoderMeta)
|
||||
end
|
||||
|
||||
-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image (a fresh buffer) | nil, Err. Key and inter frames;
|
||||
-- meta.source = { format = "vp8", keyFrame, show (false: a hidden frame, decoded as a reference but not displayed),
|
||||
-- profile, width, height }. An inter frame before the first key frame (or after reset) returns CORRUPT.
|
||||
function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?)
|
||||
if type(buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer")
|
||||
@@ -95,17 +72,14 @@ function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len:
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- decoder:reset(): drops the reference frames (after a seek); the next frame must be a key frame
|
||||
function DecoderMeta.reset(self: Decoder)
|
||||
Decode.reset(self.state)
|
||||
end
|
||||
|
||||
-- decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err (one key frame)
|
||||
function Vp8.decodeFrame(buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?)
|
||||
return Vp8.newDecoder():decodeFrame(buf, off, len, opts)
|
||||
end
|
||||
|
||||
-- decodePlanes(buf, off?, len?, opts?) -> y, u, v, width, height | nil, Err: one key frame as separate planes
|
||||
function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options?): (buffer?, any, buffer?, number?, number?)
|
||||
if type(buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "decodePlanes: expected a buffer")
|
||||
@@ -121,15 +95,12 @@ function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options
|
||||
return y, u, v, f.width, f.height
|
||||
end
|
||||
|
||||
-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height
|
||||
function Vp8.planes(img: Types.Image): (number, number, number, number, number)
|
||||
local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2
|
||||
local ny = img.width * img.height
|
||||
return 0, ny, ny + cw * ch, cw, ch
|
||||
end
|
||||
|
||||
-- toRgba(yuvImage, fancy?) -> rgba8 Image. fancy (default true): libwebp's bilinear chroma upsampling; false: point
|
||||
-- sampling (dwebp -nofancy)
|
||||
function Vp8.toRgba(img: Types.Image, fancy: boolean?): (Types.Image?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "yuv420p" then
|
||||
return nil, Err.new(Err.ARG, "toRgba: needs a yuv420p Image")
|
||||
@@ -148,7 +119,6 @@ function Vp8.toRgba(img: Types.Image, fancy: boolean?): (Types.Image?, Err.Err?)
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- yuvToRgba(y, u, v, w, h, fancy?) -> rgba8 pixels from separate planes (alpha 255)
|
||||
function Vp8.yuvToRgba(y: buffer, u: buffer, v: buffer, w: number, h: number, fancy: boolean?): buffer
|
||||
return Yuv.toRgba(y, u, v, w, h, fancy ~= false)
|
||||
end
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes,
|
||||
-- LZ77 backward references with the 2-D distance map, the colour cache, and the four inverse transforms (predictor,
|
||||
-- cross colour, subtract green, colour indexing with pixel bundling). A port of libwebp 1.6 src/dec/vp8l_dec.c,
|
||||
-- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder, a port of libwebp 1.6 src/dec/vp8l_dec.c,
|
||||
-- src/utils/huffman_utils.c and src/dsp/lossless.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); bit-exact with it.
|
||||
--
|
||||
-- Pixels are ARGB u32 values (0xAARRGGBB) in a buffer, 4 bytes each, rows top to bottom. Never throws: every
|
||||
-- function returns nil, "message" (prefixed "truncated: " when the data ends early) on bad data.
|
||||
-- Pixels are ARGB u32 values (0xAARRGGBB).
|
||||
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
|
||||
local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8
|
||||
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
|
||||
@@ -35,9 +31,7 @@ local CODE_TO_PLANE = {
|
||||
-- distance map (x offset 8 - (v & 15), y offset v >> 4) as a plain distance for a row width: done per image
|
||||
Decode.CODE_TO_PLANE = CODE_TO_PLANE
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit reader
|
||||
-- LSB-first; bytes past the end read as zero and are counted in `over`: the stream is overrun when fewer bits are
|
||||
-- left in the buffer than phantom bits were added (bitcnt < over * 8).
|
||||
-- LSB-first; bytes past the end read as zero and count in `over`: the stream is overrun when bitcnt < over * 8
|
||||
export type State = {
|
||||
buf: buffer,
|
||||
pos: number,
|
||||
@@ -68,7 +62,6 @@ local function fill(d: State)
|
||||
d.bitbuf, d.bitcnt = bitbuf, bitcnt
|
||||
end
|
||||
|
||||
-- readBits(d, n) n <= 24
|
||||
local function readBits(d: State, n: number): number
|
||||
if d.bitcnt < n then
|
||||
fill(d)
|
||||
@@ -83,7 +76,6 @@ local function eos(d: State): boolean
|
||||
return d.bitcnt < d.over * 8
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ prefix codes
|
||||
local count = table.create(MAX_LEN + 1, 0)
|
||||
local offset = table.create(MAX_LEN + 2, 0)
|
||||
|
||||
@@ -112,8 +104,7 @@ local function nextKey(key: number, len: number): number
|
||||
return if step ~= 0 then band(key, step - 1) + step else key
|
||||
end
|
||||
|
||||
-- build(d, lens (0-based Lua array), n) -> table offset in d.tab, or -1 for an invalid code set (libwebp
|
||||
-- BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits)
|
||||
-- libwebp BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits; -1 when invalid
|
||||
local sorted = table.create(2400, 0)
|
||||
local function build(d: State, lens: { number }, n: number): number
|
||||
for l = 0, MAX_LEN do
|
||||
@@ -222,7 +213,6 @@ local function build(d: State, lens: { number }, n: number): number
|
||||
return root
|
||||
end
|
||||
|
||||
-- readSymbol(d, at) -> symbol (the reader is refilled to >= 15 bits first)
|
||||
local function readSymbol(d: State, at: number): number
|
||||
if d.bitcnt < MAX_LEN then
|
||||
fill(d)
|
||||
@@ -246,7 +236,6 @@ end
|
||||
local codeLengths = table.create(2400, 0)
|
||||
local clLens = table.create(19, 0)
|
||||
|
||||
-- readCode(d, alphabetSize) -> table offset, or -1
|
||||
local function readCode(d: State, size: number): number
|
||||
for i = 1, size do
|
||||
codeLengths[i] = 0
|
||||
@@ -325,7 +314,6 @@ local function readCode(d: State, size: number): number
|
||||
return build(d, codeLengths, size)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ pixel data
|
||||
local function subSample(size: number, bits: number): number
|
||||
return rshift(size + lshift(1, bits) - 1, bits)
|
||||
end
|
||||
@@ -340,7 +328,6 @@ local function cacheKey(argb: number, shift: number): number
|
||||
end
|
||||
Decode.cacheKey = cacheKey
|
||||
|
||||
-- decodeData: the entropy-coded pixels of one level into `data` (w * h u32)
|
||||
local function decodeData(d: State, data: buffer, w: number, h: number, cacheBits: number, groups: { number }, himg: buffer?, hbits: number, hxs: number): (boolean, string?)
|
||||
local total = w * h
|
||||
local cache: buffer? = if cacheBits > 0 then bcreate(lshift(1, cacheBits) * 4) else nil
|
||||
@@ -457,7 +444,6 @@ local function decodeData(d: State, data: buffer, w: number, h: number, cacheBit
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
local function addPixels(a: number, b: number): number
|
||||
return band(band(a, 0xff00ff00) + band(b, 0xff00ff00), 0xff00ff00) + band(band(a, 0x00ff00ff) + band(b, 0x00ff00ff), 0x00ff00ff)
|
||||
end
|
||||
@@ -510,7 +496,7 @@ local function clampedHalf(c0: number, c1: number, c2: number): number
|
||||
return a * 16777216 + r * 65536 + g * 256 + b
|
||||
end
|
||||
|
||||
-- predict(mode, L, T, TR, TL) -> the predicted pixel (libwebp VP8LPredictors; 14 and 15 are black)
|
||||
-- libwebp VP8LPredictors; modes 14 and 15 are black
|
||||
local function predict(mode: number, L: number, T: number, TR: number, TL: number): number
|
||||
if mode == 0 then
|
||||
return ARGB_BLACK
|
||||
@@ -618,7 +604,6 @@ local function inverseSubtractGreen(data: buffer, n: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- inverseColorIndexing(src (sw x h), w, h, bits, map (2^(8 >> bits) u32)) -> w x h
|
||||
local function inverseColorIndexing(src: buffer, sw: number, w: number, h: number, bits: number, map: buffer): buffer
|
||||
local out = bcreate(w * h * 4)
|
||||
if bits == 0 then
|
||||
@@ -646,12 +631,10 @@ local function inverseColorIndexing(src: buffer, sw: number, w: number, h: numbe
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ image stream
|
||||
type Transform = { kind: number, xsize: number, bits: number, data: buffer? }
|
||||
|
||||
local decodeStream: (d: State, xs: number, ys: number, level0: boolean) -> (buffer?, string?)
|
||||
|
||||
-- readCodes(d, xs, ys, cacheBits, level0) -> groups (5 table offsets each), huffman image, bits, image width
|
||||
local function readCodes(d: State, xs: number, ys: number, cacheBits: number, level0: boolean): ({ number }?, buffer?, number, number, string?)
|
||||
local himg: buffer? = nil
|
||||
local hbits, hxs = 0, 0
|
||||
@@ -808,7 +791,6 @@ local function newState(buf: buffer, off: number, len: number, maxPixels: number
|
||||
}
|
||||
end
|
||||
|
||||
-- header(buf, off, len) -> width, height, alphaHint | nil, message
|
||||
function Decode.header(buf: buffer, off: number, len: number): (number?, number, boolean, string?)
|
||||
if len < 5 then
|
||||
return nil, 0, false, "truncated: header"
|
||||
@@ -826,7 +808,6 @@ function Decode.header(buf: buffer, off: number, len: number): (number?, number,
|
||||
return w, h, alpha, nil
|
||||
end
|
||||
|
||||
-- argb(buf, off, len, maxPixels) -> ARGB pixels, width, height, alphaHint | nil, message
|
||||
function Decode.argb(buf: buffer, off: number, len: number, maxPixels: number): (buffer?, number, number, boolean, string?)
|
||||
local w, h, alpha, err = Decode.header(buf, off, len)
|
||||
if not w then
|
||||
@@ -843,13 +824,11 @@ function Decode.argb(buf: buffer, off: number, len: number, maxPixels: number):
|
||||
return data, w, h, alpha, nil
|
||||
end
|
||||
|
||||
-- stream(buf, off, len, w, h) -> ARGB pixels | nil, message: a headerless image stream (the ALPH chunk's payload)
|
||||
function Decode.stream(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, string?)
|
||||
local d = newState(buf, off, len, w * h)
|
||||
return decodeStream(d, w, h, true)
|
||||
end
|
||||
|
||||
-- toRgba(argb, n, out?, outOff?) -> rgba8 bytes
|
||||
function Decode.toRgba(argb: buffer, n: number, out: buffer?, outOff: number?): buffer
|
||||
local o = out or bcreate(n * 4)
|
||||
local base = outOff or 0
|
||||
@@ -861,7 +840,6 @@ function Decode.toRgba(argb: buffer, n: number, out: buffer?, outOff: number?):
|
||||
return o
|
||||
end
|
||||
|
||||
-- green(argb, n) -> the green channel as bytes (alpha planes)
|
||||
function Decode.green(argb: buffer, n: number): buffer
|
||||
local o = bcreate(n)
|
||||
for k = 0, n - 1 do
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from the specification (RFC 9649 section 3).
|
||||
-- Transforms: colour indexing with pixel bundling (<= 256 colours), else subtract green + predictor (per-tile mode
|
||||
-- chosen from a residual cost) + cross colour (per-tile least-squares multipliers). Entropy coding: LZ77 with hash
|
||||
-- chains, the left / up run candidates and the 2-D distance codes, a colour cache whose size is chosen by an entropy
|
||||
-- estimate, one prefix code group per image, code lengths limited to 15 bits (codecs/entropy/Huffman) and run-length coded.
|
||||
-- Never throws (the init module validates the arguments).
|
||||
-- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from RFC 9649 section 3.
|
||||
local Huffman = require("@rosetta/codecs/entropy/Huffman")
|
||||
|
||||
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
|
||||
@@ -39,14 +34,13 @@ for i, v in CODE_TO_PLANE do
|
||||
PLANE_TO_CODE[v + 1] = i
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit writer
|
||||
type W = { buf: buffer, pos: number, acc: number, cnt: number }
|
||||
|
||||
local function newWriter(cap: number): W
|
||||
return { buf = bcreate(math.max(64, cap)), pos = 0, acc = 0, cnt = 0 }
|
||||
end
|
||||
|
||||
-- put(w, v, n): the n <= 24 low bits of v, LSB first
|
||||
-- the n <= 24 low bits of v, LSB first
|
||||
local function put(w: W, v: number, n: number)
|
||||
local acc = w.acc + v * 2 ^ w.cnt
|
||||
local cnt = w.cnt + n
|
||||
@@ -80,7 +74,6 @@ local function finish(w: W): buffer
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ helpers
|
||||
local function subSample(size: number, bits: number): number
|
||||
return rshift(size + lshift(1, bits) - 1, bits)
|
||||
end
|
||||
@@ -92,7 +85,6 @@ local function mulHash(v: number): number
|
||||
return (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296
|
||||
end
|
||||
|
||||
-- prefix(v) -> code, extra bits, extra value of a length or distance code value v >= 1
|
||||
local function prefix(v: number): (number, number, number)
|
||||
local d = v - 1
|
||||
if d < 4 then
|
||||
@@ -109,7 +101,7 @@ local function prefix(v: number): (number, number, number)
|
||||
return 2 * hb + second, eb, band(d, lshift(1, eb) - 1)
|
||||
end
|
||||
|
||||
-- distCode(xs, dist) -> the distance code value (1..120 for the 2-D plane offsets, else dist + 120)
|
||||
-- distance code value: 1..120 for the 2-D plane offsets, else dist + 120
|
||||
local function distCode(xs: number, dist: number): number
|
||||
local yo = dist // xs
|
||||
local xo = dist - yo * xs
|
||||
@@ -143,7 +135,6 @@ local function half(x: number, y: number): number
|
||||
return clip255(x + (if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1)))
|
||||
end
|
||||
|
||||
-- predict(mode, L, T, TR, TL): the decoder's predictors (codecs/image/Vp8L/Decode)
|
||||
local function predict(mode: number, L: number, T: number, TR: number, TL: number): number
|
||||
if mode == 1 then
|
||||
return L
|
||||
@@ -188,7 +179,6 @@ local function predict(mode: number, L: number, T: number, TR: number, TL: numbe
|
||||
return ARGB_BLACK
|
||||
end
|
||||
|
||||
-- COST[v + 1]: an estimate of the bits of a residual byte v (small magnitudes, mod 256, are cheap)
|
||||
local COST = table.create(256, 0)
|
||||
for v = 0, 255 do
|
||||
local m = math.min(v, 256 - v)
|
||||
@@ -199,12 +189,10 @@ local function residualCost(r: number): number
|
||||
return COST[band(r, 255) + 1] + COST[band(rshift(r, 8), 255) + 1] + COST[band(rshift(r, 16), 255) + 1] + COST[rshift(r, 24) + 1]
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
local MODES_FAST = { 1, 2, 11 }
|
||||
local MODES_MID = { 0, 1, 2, 4, 5, 7, 10, 11, 12, 13 }
|
||||
local MODES_ALL = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }
|
||||
|
||||
-- predictorTransform(px, w, h, bits, effort) -> the modes sub-image; px becomes the residuals
|
||||
local function predictorTransform(px: buffer, w: number, h: number, bits: number, effort: number): buffer
|
||||
local tw, th = subSample(w, bits), subSample(h, bits)
|
||||
local modesImg = bcreate(tw * th * 4)
|
||||
@@ -267,8 +255,7 @@ local function clampM(v: number): number
|
||||
return if m < -128 then -128 elseif m > 127 then 127 else m
|
||||
end
|
||||
|
||||
-- crossColorTransform(px, w, h, bits) -> the multipliers sub-image; px is transformed in place. Per tile: the
|
||||
-- least-squares multipliers (r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32), kept when they lower the cost
|
||||
-- cross colour per tile: least-squares r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32, kept when they lower the cost
|
||||
local function crossColorTransform(px: buffer, w: number, h: number, bits: number): buffer
|
||||
local tw, th = subSample(w, bits), subSample(h, bits)
|
||||
local img = bcreate(tw * th * 4)
|
||||
@@ -342,7 +329,6 @@ local function crossColorTransform(px: buffer, w: number, h: number, bits: numbe
|
||||
return img
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ LZ77
|
||||
-- tokens: L[i] >= 0 is a literal ARGB pixel; L[i] < 0 is a copy of -L[i] pixels with the distance code value D[i]
|
||||
local HASH_BITS = 16
|
||||
|
||||
@@ -378,7 +364,6 @@ local function lz77(px: buffer, xs: number, n: number, effort: number): ({ numbe
|
||||
head[h] = i
|
||||
end
|
||||
end
|
||||
-- best(i) -> length, distance (0, 0 when no useful match)
|
||||
local function best(i: number): (number, number)
|
||||
local max = math.min(MAX_LENGTH, n - i)
|
||||
if max < 2 then
|
||||
@@ -482,7 +467,6 @@ local function lz77(px: buffer, xs: number, n: number, effort: number): ({ numbe
|
||||
return L, D
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ prefix codes
|
||||
local function entropy(h: { number }): number
|
||||
local total = 0
|
||||
for _, c in h do
|
||||
@@ -501,7 +485,6 @@ local function entropy(h: { number }): number
|
||||
return bits / log(2)
|
||||
end
|
||||
|
||||
-- chooseCache(px, L, effort) -> the colour cache bits (0..10) with the smallest estimated literal cost
|
||||
local function chooseCache(px: buffer, L: { number }, effort: number): number
|
||||
if effort < 2 then
|
||||
return 0
|
||||
@@ -565,7 +548,6 @@ end
|
||||
|
||||
type Code = { lens: { number }, codes: { number }, single: boolean }
|
||||
|
||||
-- buildCode(freqs, maxLen) -> code lengths, reversed (LSB-first) codes, single (<= 1 used symbol: 0 bits each)
|
||||
local function buildCode(freqs: { number }, maxLen: number): Code
|
||||
local lens = Huffman.lengths(freqs, maxLen)
|
||||
local used = 0
|
||||
@@ -609,7 +591,6 @@ local function zeroRun(tok: { number }, ext: { number }, run: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- writeCode(w, code, alphabetSize): the code lengths (a simple code when possible, else run-length coded)
|
||||
local function writeCode(w: W, c: Code, size: number)
|
||||
local syms: { number } = {}
|
||||
for s = 0, size - 1 do
|
||||
@@ -647,7 +628,7 @@ local function writeCode(w: W, c: Code, size: number)
|
||||
-- decoder's "previous" starts at 8), 17 zeros (3..10), 18 zeros (11..138)
|
||||
local tok: { number } = {}
|
||||
local ext: { number } = {}
|
||||
local keep = 0 -- tokens up to the last non-zero length
|
||||
local keep = 0
|
||||
local prev = 8
|
||||
local s = 1
|
||||
while s <= size do
|
||||
@@ -727,8 +708,7 @@ local function writeCode(w: W, c: Code, size: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ image data
|
||||
-- writeImage(w, px, xs, n, effort, level0): colour cache bits, [the meta-code bit], the five codes, the pixels
|
||||
-- colour cache bits, [the meta-code bit], the five codes, the pixels
|
||||
local function writeImage(w: W, px: buffer, xs: number, n: number, effort: number, level0: boolean)
|
||||
local L, D = lz77(px, xs, n, effort)
|
||||
local cacheBits = if level0 then chooseCache(px, L, effort) else 0
|
||||
@@ -815,8 +795,6 @@ local function writeImage(w: W, px: buffer, xs: number, n: number, effort: numbe
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- toArgb(rgba, n, exact) -> ARGB pixels, any alpha < 255. Without exact, fully transparent pixels become 0.
|
||||
local function toArgb(rgba: buffer, n: number, exact: boolean): (buffer, boolean)
|
||||
local px = bcreate(n * 4)
|
||||
local alpha = false
|
||||
@@ -835,7 +813,6 @@ local function toArgb(rgba: buffer, n: number, exact: boolean): (buffer, boolean
|
||||
return px, alpha
|
||||
end
|
||||
|
||||
-- palette(px, n) -> the sorted colours when there are at most 256, else nil
|
||||
local function palette(px: buffer, n: number): { number }?
|
||||
local seen: { [number]: boolean } = {}
|
||||
local list: { number } = {}
|
||||
@@ -855,7 +832,6 @@ end
|
||||
|
||||
type Config = { palette: { number }?, pbits: number, cc: boolean, ccbits: number }
|
||||
|
||||
-- stream(px, w, h, effort, cfg, bw): the transforms and the main image of one configuration (px is consumed)
|
||||
local function stream(px: buffer, w: number, h: number, effort: number, cfg: Config, bw: W)
|
||||
local n = w * h
|
||||
local xs = w
|
||||
@@ -923,8 +899,6 @@ local function stream(px: buffer, w: number, h: number, effort: number, cfg: Con
|
||||
writeImage(bw, px, xs, xs * h, effort, true)
|
||||
end
|
||||
|
||||
-- encode(rgba, w, h, effort, exact, alphaHint?, headerless) -> the VP8L bitstream (headerless: the image stream only,
|
||||
-- as an ALPH chunk stores it). Efforts 6+ try several transform configurations and keep the smallest.
|
||||
function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact: boolean, alphaHint: boolean?, headerless: boolean): buffer
|
||||
local n = w * h
|
||||
local px, usesAlpha = toArgb(rgba, n, exact)
|
||||
|
||||
@@ -1,17 +1,6 @@
|
||||
--!strict
|
||||
-- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
|
||||
-- image/webp uses it for VP8L frames and for compressed ALPH planes; other containers may carry it too.
|
||||
-- Decoder: a port of libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it. Encoder: new
|
||||
-- (subtract green, predictor and cross-colour transforms with per-tile mode search, colour indexing with pixel
|
||||
-- bundling for <= 256 colours, LZ77 with hash chains and the 2-D distance codes, a colour cache chosen by entropy,
|
||||
-- one prefix code group per image or meta codes for big images).
|
||||
--
|
||||
-- local Vp8L = require("@rosetta/codecs/image/Vp8L")
|
||||
-- local rgba, w, h, alpha = Vp8L.decode(buf, off, len) -- a VP8L bitstream (0x2f signature) -> rgba8
|
||||
-- local a8 = Vp8L.decodeAlpha(buf, off, len, w, h) -- a headerless stream's green channel (ALPH)
|
||||
-- local bits = Vp8L.encode(rgba, w, h, { effort = 4 }) -- rgba8 -> a VP8L bitstream
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / LIMIT / ARG).
|
||||
-- codecs/image/Vp8L: WebP lossless (VP8L, RFC 9649 section 3).
|
||||
-- Decoder ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it; encoder new.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Decode = require("@rosetta/codecs/image/Vp8L/Decode")
|
||||
local Encode = require("@rosetta/codecs/image/Vp8L/Encode")
|
||||
@@ -37,7 +26,6 @@ local function range(buf: buffer, off: number?, len: number?): (number, number)
|
||||
return o, math.clamp(len or (n - o), 0, n - o)
|
||||
end
|
||||
|
||||
-- info(buf, off?, len?) -> { width, height, alpha } | nil, Err: the 5-byte header
|
||||
function Vp8L.info(buf: buffer, off: number?, len: number?): ({ width: number, height: number, alpha: boolean }?, Err.Err?)
|
||||
local o, l = range(buf, off, len)
|
||||
local w, h, alpha, err = Decode.header(buf, o, l)
|
||||
@@ -47,7 +35,6 @@ function Vp8L.info(buf: buffer, off: number?, len: number?): ({ width: number, h
|
||||
return { width = w, height = h, alpha = alpha }, nil
|
||||
end
|
||||
|
||||
-- decodeArgb(buf, off?, len?, maxPixels?) -> ARGB u32 pixels (0xAARRGGBB), width, height, alphaHint | nil, Err
|
||||
function Vp8L.decodeArgb(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?)
|
||||
local o, l = range(buf, off, len)
|
||||
local px, w, h, alpha, err = Decode.argb(buf, o, l, maxPixels or DEFAULT_MAX_PIXELS)
|
||||
@@ -57,7 +44,6 @@ function Vp8L.decodeArgb(buf: buffer, off: number?, len: number?, maxPixels: num
|
||||
return px, w, h, alpha
|
||||
end
|
||||
|
||||
-- decode(buf, off?, len?, maxPixels?) -> rgba8 pixels, width, height, alphaHint | nil, Err
|
||||
function Vp8L.decode(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?)
|
||||
local px, w, h, alpha = Vp8L.decodeArgb(buf, off, len, maxPixels)
|
||||
if not px then
|
||||
@@ -66,7 +52,6 @@ function Vp8L.decode(buf: buffer, off: number?, len: number?, maxPixels: number?
|
||||
return Decode.toRgba(px, w * (h :: number)), w, h, alpha
|
||||
end
|
||||
|
||||
-- decodeAlpha(buf, off, len, width, height) -> width * height bytes (the green channel) | nil, Err
|
||||
function Vp8L.decodeAlpha(buf: buffer, off: number?, len: number?, width: number, height: number): (buffer?, Err.Err?)
|
||||
local o, l = range(buf, off, len)
|
||||
local px, err = Decode.stream(buf, o, l, width, height)
|
||||
@@ -76,16 +61,14 @@ function Vp8L.decodeAlpha(buf: buffer, off: number?, len: number?, width: number
|
||||
return Decode.green(px, width * height), nil
|
||||
end
|
||||
|
||||
-- toRgba(argb, n) -> rgba8 bytes of n ARGB pixels
|
||||
Vp8L.toRgba = Decode.toRgba
|
||||
|
||||
export type EncodeOptions = {
|
||||
effort: number?, -- 0..9, default 5: more = smaller and slower (0: no transforms, no LZ77 search)
|
||||
exact: boolean?, -- default false: keep the RGB of fully transparent pixels (otherwise they may be zeroed)
|
||||
alphaHint: boolean?, -- the header's "alpha is used" bit; default: any alpha < 255
|
||||
effort: number?,
|
||||
exact: boolean?,
|
||||
alphaHint: boolean?,
|
||||
}
|
||||
|
||||
-- encode(rgba, width, height, opts?) -> a VP8L bitstream (signature + header + image stream) | nil, Err
|
||||
function Vp8L.encode(rgba: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(rgba) ~= "buffer" or type(width) ~= "number" or type(height) ~= "number" then
|
||||
return nil, Err.new(Err.ARG, "encode: needs rgba8 pixels, width, height")
|
||||
@@ -104,7 +87,6 @@ function Vp8L.encode(rgba: buffer, width: number, height: number, opts: EncodeOp
|
||||
return Encode.encode(rgba, width, height, effort, o.exact == true, o.alphaHint, false), nil
|
||||
end
|
||||
|
||||
-- encodeAlpha(a8, width, height, opts?) -> a headerless stream of the plane in green (an ALPH payload)
|
||||
function Vp8L.encodeAlpha(a8: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(a8) ~= "buffer" or buffer.len(a8) < width * height then
|
||||
return nil, Err.new(Err.ARG, "encodeAlpha: plane too small")
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
|
||||
-- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range.
|
||||
-- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the
|
||||
-- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma
|
||||
-- (ffmpeg's default rgb -> yuv420p chroma siting is close to this).
|
||||
--
|
||||
-- Yuv.toRgba(planes, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 buffer (alpha 255)
|
||||
-- Yuv.fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p buffer (Y, then U, then V; ceil(w/2) x ceil(h/2))
|
||||
-- Yuv.imageToRgba(img) / Yuv.imageFromRgba(img, range?, matrix?) -> Types.Image
|
||||
-- Yuv.scale(src, w, h, dw, dh, out?) -> yuv420p buffer of dw x dh (each plane bilinear; for shrinking by up to 2x per
|
||||
-- axis, larger factors skip source samples); Yuv.imageScale(img, dw, dh) -> Types.Image (yuv420p in and out)
|
||||
-- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8, BT.601 / BT.709, limited or full range.
|
||||
-- yuv -> rgb: nearest chroma, swscale's default 16-bit coefficients (within about one level of ffmpeg -pix_fmt rgba);
|
||||
-- rgb -> yuv: each 2x2 block averaged for the chroma.
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
|
||||
@@ -55,14 +47,11 @@ local function coeffs(range: string?, matrix: string?): Coeffs
|
||||
return c
|
||||
end
|
||||
|
||||
-- CLIP[v + 1024] = clamp(v, 0, 255) for v in -1024..1279
|
||||
local CLIP = bcreate(2304)
|
||||
for i = 0, 2303 do
|
||||
writeu8(CLIP, i, math.clamp(i - 1024, 0, 255))
|
||||
end
|
||||
|
||||
-- toRgba(src, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 (w * h * 4) from planes in one buffer: Y at 0 with
|
||||
-- stride w, U at uo and V at vo with stride cw (ceil(w/2) rows of ceil(h/2))
|
||||
function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer
|
||||
local dst = out or bcreate(w * h * 4)
|
||||
local c = coeffs(range, matrix)
|
||||
@@ -94,7 +83,6 @@ function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, c
|
||||
return dst
|
||||
end
|
||||
|
||||
-- fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p
|
||||
function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: string?, out: buffer?): buffer
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local uo, vo = w * h, w * h + cw * ch
|
||||
@@ -109,7 +97,6 @@ function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix:
|
||||
local ysc = if full then 1 else 219 / 255
|
||||
local csc = if full then 1 else 224 / 255
|
||||
local yof = if full then 0.5 else 16.5
|
||||
-- fixed point x 65536
|
||||
local yr, yg, yb = floor(kr * ysc * 65536 + 0.5), floor(kg * ysc * 65536 + 0.5), floor(kb * ysc * 65536 + 0.5)
|
||||
local yoff = floor(yof * 65536)
|
||||
local ur = floor(-kr / (2 * (1 - kb)) * csc * 65536 + 0.5)
|
||||
@@ -142,7 +129,6 @@ function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix:
|
||||
return dst
|
||||
end
|
||||
|
||||
-- the range / matrix an Image's meta records (meta.yuv = { range, matrix }); limited BT.601 when absent
|
||||
local function info(img: Types.Image): (string, string)
|
||||
local m = img.meta
|
||||
local y = m and m.yuv
|
||||
@@ -157,13 +143,11 @@ local function info(img: Types.Image): (string, string)
|
||||
end
|
||||
Yuv.info = info
|
||||
|
||||
-- planes(w, h) -> uo, vo, cw, ch of a yuv420p buffer
|
||||
function Yuv.planes(w: number, h: number): (number, number, number, number)
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
return w * h, w * h + cw * ch, cw, ch
|
||||
end
|
||||
|
||||
-- FULL_Y / FULL_C: limited -> full range sample maps
|
||||
local FULL_Y = bcreate(256)
|
||||
local FULL_C = bcreate(256)
|
||||
for v = 0, 255 do
|
||||
@@ -171,7 +155,6 @@ for v = 0, 255 do
|
||||
writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255))
|
||||
end
|
||||
|
||||
-- toFullRange(img) -> a yuv420p Image in full range (a limited-range one remapped; a full-range one returned)
|
||||
function Yuv.toFullRange(img: Types.Image): Types.Image
|
||||
if img.format ~= "yuv420p" or info(img) == "full" then
|
||||
return img
|
||||
@@ -192,7 +175,6 @@ function Yuv.toFullRange(img: Types.Image): Types.Image
|
||||
return out
|
||||
end
|
||||
|
||||
-- imageToRgba(img) -> an rgba8 Image (yuv420p converted; rgba8 returned as is; nil for other formats)
|
||||
function Yuv.imageToRgba(img: Types.Image): Types.Image?
|
||||
if img.format == "rgba8" then
|
||||
return img
|
||||
@@ -209,7 +191,6 @@ function Yuv.imageToRgba(img: Types.Image): Types.Image?
|
||||
return out
|
||||
end
|
||||
|
||||
-- imageFromRgba(img, range?, matrix?) -> a yuv420p Image (meta.yuv records the range / matrix)
|
||||
function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image?
|
||||
if img.format == "yuv420p" then
|
||||
return img
|
||||
@@ -224,7 +205,6 @@ function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): T
|
||||
return out
|
||||
end
|
||||
|
||||
-- one plane (sw x sh bytes at so) -> (dw x dh at do), bilinear in 8-bit fixed point (source sample centres)
|
||||
local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst: buffer, d0: number, dw: number, dh: number)
|
||||
local fx, fy = sw / dw, sh / dh
|
||||
for y = 0, dh - 1 do
|
||||
@@ -258,8 +238,6 @@ local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst:
|
||||
end
|
||||
end
|
||||
|
||||
-- scale(src, w, h, dw, dh, out?) -> a yuv420p buffer of dw x dh (planes Y, U, V; chroma ceil(dw / 2) x ceil(dh / 2)).
|
||||
-- src must hold w x h yuv420p (checked: a short buffer or bad sizes return a zero-filled result of the right size).
|
||||
function Yuv.scale(src: buffer, w: number, h: number, width: number, height: number, out: buffer?): buffer
|
||||
local dw: number = math.max(1, floor(width))
|
||||
local dh: number = math.max(1, floor(height))
|
||||
|
||||
Reference in new issue
Block a user