formats-luau foundation: build (darklua + token passes) for Roblox and LuaJIT, compat prelude, core, Types, host adapters, API + registry, lint, tests on both runtimes; absorb deflate (codecs/Deflate + new compressor) and png (image/png + new encoder)

This commit is contained in:
4DBug committed 2026-10-31 08:18:01 -05:00
commit cdcb5b0b77
226 files changed
+8409

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
--!strict
-- Registry: GENERATED by tools/gen_registry.py from the format folders - do not edit.
-- One entry per format: the contract metadata (copied from its init.luau) and load(), which requires the format
-- module on first use (a static require, as Roblox needs). Order: category, then name.
export type Entry = {
name: string,
category: string,
path: string,
extensions: { string },
mime: { string },
deps: { string },
caps: { [string]: any },
load: () -> any,
}
local list: { Entry } = {
{
name = "png",
category = "image",
path = "image/png",
extensions = { "png", "apng" },
mime = { "image/png", "image/apng" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" },
caps = { decode = true, encode = true, animation = false, alpha = true, depths = { 1, 2, 4, 8, 16 } },
load = function()
return require("@formats/image/png")
end,
},
}
return list
+475
View File
@@ -0,0 +1,475 @@
--!strict
-- Types: the standard value types every format of a category decodes to and encodes from, plus small constructors.
-- A PNG and a WebP both load as an Image; a WAV and an MP3 both open as an audio Decoder. Every top-level value has a
-- `kind` field ("image", "audio", "scene", ...) so F.save knows the category without a format name.
--
-- local T = require("@formats/Types")
-- local img = T.Image.new(64, 32) -- rgba8, zero-filled
-- local snd = T.Audio.new(44100, 2, 44100) -- 1 s of silent stereo f32
--
-- Shared enums are plain strings. Buffers are tightly packed, rows top to bottom, interleaved channels.
local Err = require("@formats/core/Err")
local Types = {}
export type Err = Err.Err
-- ------------------------------------------------------------------------------------------------ Image
-- pixel formats: bytes per pixel. rgba8 is the default every decoder produces unless opts.native asks to keep the
-- source layout. yuv420p: Y plane (w*h) then U and V planes (ceil(w/2) * ceil(h/2) each).
export type PixelFormat = "rgba8" | "rgba16" | "rgbaf32" | "rgb8" | "gray8" | "gray16" | "graya8" | "alpha8" | "yuv420p"
local BPP: { [string]: number } = {
rgba8 = 4,
rgba16 = 8,
rgbaf32 = 16,
rgb8 = 3,
gray8 = 1,
gray16 = 2,
graya8 = 2,
alpha8 = 1,
}
Types.BPP = table.freeze(BPP)
export type ImageMeta = {
colorSpace: string?, -- "srgb" (default), "linear", "display-p3", ...
gamma: number?,
icc: buffer?, -- the raw ICC profile
exif: buffer?, -- the raw EXIF block (TIFF header onwards)
dpi: { x: number, y: number }?,
palette: { { number } }?, -- { r, g, b, a } 0..255 per entry, for palette sources
text: { [string]: string }?, -- tEXt / comments
source: { format: string, bitDepth: number?, colorType: string?, [string]: any }?,
[string]: any,
}
-- one frame of an animation (GIF, APNG, WebP): the image is the frame's own rectangle, composited at x, y
export type Frame = {
image: Image,
delay: number, -- seconds
x: number,
y: number,
dispose: "none" | "background" | "previous",
blend: "source" | "over",
}
export type Image = {
kind: "image",
width: number,
height: number,
format: PixelFormat,
pixels: buffer,
frames: { Frame }?, -- animations: frame 1 is also width x height pixels (the composited first frame)
loops: number, -- 0 = forever
meta: ImageMeta,
}
local Image = {}
-- new(width, height, format?) -> a zero-filled Image (format defaults to rgba8)
function Image.new(width: number, height: number, format: PixelFormat?): Image
local f: PixelFormat = format or "rgba8"
local size
if f == "yuv420p" then
local cw, ch = (width + 1) // 2, (height + 1) // 2
size = width * height + 2 * cw * ch
else
size = width * height * (BPP[f] or 4)
end
return {
kind = "image",
width = width,
height = height,
format = f,
pixels = buffer.create(size),
frames = nil,
loops = 0,
meta = {},
}
end
-- bpp(format) -> bytes per pixel (nil for planar formats)
function Image.bpp(format: string): number?
return BPP[format]
end
Types.Image = Image
-- ------------------------------------------------------------------------------------------------ Audio
export type Tags = { [string]: string } -- title, artist, album, date, genre, track, comment, ...
-- the streaming decoder every audio format's open() returns (the shape the absorbed wav/mp3/flac/ogg/opus share)
export type Decoder = {
sampleRate: number,
channels: number,
frames: number, -- total sample frames (estimate for VBR streams without an index), 0 = unknown
duration: number, -- seconds
bitrate: number, -- bits per second (average)
tags: Tags,
-- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end); out (if given) is reused when big enough
read: (self: any, n: number, out: buffer?) -> (buffer, number),
seek: (self: any, seconds: number) -> (),
position: (self: any) -> number, -- seconds
}
-- a fully decoded sound (F.load / F.audio.load)
export type Audio = {
kind: "audio",
sampleRate: number,
channels: number,
frames: number,
samples: buffer, -- interleaved f32, frames * channels * 4 bytes
tags: Tags,
meta: { source: { format: string, [string]: any }?, [string]: any },
}
local Audio = {}
function Audio.new(sampleRate: number, channels: number, frames: number): Audio
return {
kind = "audio",
sampleRate = sampleRate,
channels = channels,
frames = frames,
samples = buffer.create(frames * channels * 4),
tags = {},
meta = {},
}
end
Types.Audio = Audio
-- ------------------------------------------------------------------------------------------------ Music (trackers, MIDI)
export type Module = {
kind: "music",
title: string,
format: string, -- "mod", "s3m", "xm", "it", "mid"
channels: number,
patterns: { any },
order: { number },
instruments: { any },
samples: { any },
render: (self: any, opts: any?) -> Decoder, -- every music file is also audio
meta: { [string]: any },
}
export type MidiEvent = { tick: number, type: string, channel: number?, data: { number }?, meta: any? }
export type Midi = {
kind: "midi",
format: number, -- SMF 0 / 1 / 2
division: number, -- ticks per quarter note (or SMPTE, negative)
tracks: { { events: { MidiEvent }, name: string? } },
meta: { [string]: any },
}
local Midi = {}
function Midi.new(division: number?): Midi
return { kind = "midi", format = 1, division = division or 480, tracks = {}, meta = {} }
end
Types.Midi = Midi
-- ------------------------------------------------------------------------------------------------ Video
export type Track = {
id: number,
kind: "video" | "audio" | "subtitle" | "data",
codec: string, -- "h264", "vp8", "mpeg1", "mjpeg", "aac", "mp3", "opus", ...
timescale: number, -- ticks per second for pts / duration
duration: number?, -- seconds
width: number?,
height: number?,
sampleRate: number?,
channels: number?,
config: buffer?, -- codec configuration (avcC, CodecPrivate, ...)
[string]: any,
}
export type Packet = { track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer }
export type Demuxer = {
tracks: { Track },
duration: number,
-- packets(trackId?) -> iterator of Packets in file order (one track, or all)
packets: (self: any, track: number?) -> () -> Packet?,
seek: ((self: any, seconds: number) -> ())?,
}
export type VideoFrame = { image: Image, pts: number, duration: number }
export type VideoDecoder = {
width: number,
height: number,
frameRate: number,
duration: number,
nextFrame: (self: any) -> (VideoFrame?, Err?), -- nil, nil at the end
toRGBA: (self: any, frame: VideoFrame) -> Image,
seek: ((self: any, seconds: number) -> ())?,
audio: Decoder?, -- the first audio track, decoded
demuxer: Demuxer?,
}
-- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped)
export type Accessor = {
data: buffer, -- tightly packed
type: "f32" | "u8" | "u16" | "u32" | "i8" | "i16" | "unorm8" | "unorm16" | "snorm8" | "snorm16",
components: number, -- 1 (SCALAR) .. 4 (VEC4), 16 (MAT4)
count: number,
}
export type Primitive = {
attributes: { [string]: Accessor }, -- POSITION, NORMAL, TANGENT, TEXCOORD_0, COLOR_0, JOINTS_0, WEIGHTS_0
indices: Accessor?,
mode: "triangles" | "lines" | "points" | "triangle_strip" | "triangle_fan" | "line_strip",
material: number?, -- index into scene.materials (1-based)
}
export type Mesh = { name: string?, primitives: { Primitive } }
export type Texture = { image: Image?, uri: string?, sampler: { wrapS: string?, wrapT: string?, filter: string? }? }
export type TextureRef = { texture: number, texCoord: number?, transform: { offset: { number }?, scale: { number }?, rotation: number? }? }
export type Material = {
name: string?,
baseColor: { number }, -- r, g, b, a linear 0..1
baseColorTexture: TextureRef?,
metallic: number,
roughness: number,
metallicRoughnessTexture: TextureRef?,
normalTexture: TextureRef?,
occlusionTexture: TextureRef?,
emissive: { number },
emissiveTexture: TextureRef?,
alphaMode: "opaque" | "mask" | "blend",
alphaCutoff: number,
doubleSided: boolean,
extras: { [string]: any }?, -- classic Phong (OBJ / FBX): ambient, diffuse, specular, shininess, ...
}
export type Node = {
name: string?,
children: { number }, -- node indices (1-based)
mesh: number?,
camera: number?,
light: number?,
skin: number?,
translation: { number }?, -- TRS, or matrix (column-major 4x4), not both
rotation: { number }?, -- quaternion x, y, z, w
scale: { number }?,
matrix: { number }?,
extras: { [string]: any }?,
}
export type Camera = { type: "perspective" | "orthographic", yfov: number?, aspect: number?, xmag: number?, ymag: number?, znear: number, zfar: number? }
export type Light = { type: "directional" | "point" | "spot", color: { number }, intensity: number, range: number?, innerCone: number?, outerCone: number? }
export type Skin = { joints: { number }, inverseBindMatrices: Accessor?, skeleton: number? }
export type Channel = { node: number, path: "translation" | "rotation" | "scale" | "weights", input: Accessor, output: Accessor, interpolation: "LINEAR" | "STEP" | "CUBICSPLINE" }
export type Animation = { name: string?, channels: { Channel } }
export type Scene = {
kind: "scene",
nodes: { Node },
roots: { number }, -- top-level node indices
meshes: { Mesh },
materials: { Material },
textures: { Texture },
cameras: { Camera },
lights: { Light },
skins: { Skin },
animations: { Animation },
meta: { up: "y" | "z"?, unit: number?, source: { format: string, [string]: any }?, [string]: any },
}
local Scene = {}
function Scene.new(): Scene
return {
kind = "scene",
nodes = {},
roots = {},
meshes = {},
materials = {},
textures = {},
cameras = {},
lights = {},
skins = {},
animations = {},
meta = {},
}
end
function Scene.accessor(data: buffer, type: any, components: number, count: number): Accessor
return { data = data, type = type, components = components, count = count }
end
function Scene.material(name: string?): Material
return {
name = name,
baseColor = { 1, 1, 1, 1 },
metallic = 1,
roughness = 1,
emissive = { 0, 0, 0 },
alphaMode = "opaque",
alphaCutoff = 0.5,
doubleSided = false,
}
end
-- one-node scene around a single primitive (mesh-only formats: STL, OBJ, PLY, OFF)
function Scene.fromPrimitive(prim: Primitive, name: string?): Scene
local s = Scene.new()
s.meshes[1] = { name = name, primitives = { prim } }
s.nodes[1] = { name = name, children = {}, mesh = 1 }
s.roots[1] = 1
return s
end
Types.Scene = Scene
-- ------------------------------------------------------------------------------------------------ Cad
-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Formats.plugins.brep)
export type StepEntity = { id: number, type: string, args: { any } }
export type Cad = {
kind: "cad",
schema: string, -- "AP203", "AP214", "AP242", ...
header: { [string]: any },
entities: { [number]: StepEntity },
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ Font
export type Font = {
kind: "font",
info: { family: string?, style: string?, fullName: string?, [string]: any },
unitsPerEm: number,
ascent: number,
descent: number,
lineGap: number,
glyphIndex: (self: any, codepoint: number) -> number, -- 0 = .notdef
advance: (self: any, glyph: number) -> number, -- font units
kern: (self: any, a: number, b: number) -> number,
outline: (self: any, glyph: number) -> { { op: string, [number]: number } }?, -- moveTo / lineTo / quadTo / cubicTo
rasterize: (self: any, glyph: number, px: number) -> Image?, -- alpha8
pages: { Image }?, -- bitmap fonts (BMFont)
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ Archive
export type ArchiveEntry = { name: string, size: number, compressedSize: number?, method: string?, mtime: number?, dir: boolean }
export type Archive = {
kind: "archive",
format: string,
list: (self: any) -> { ArchiveEntry },
read: (self: any, name: string) -> (buffer?, Err?),
add: (self: any, name: string, data: buffer | string, opts: any?) -> (),
write: (self: any, opts: any?) -> (buffer?, Err?),
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ Data
-- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a
-- table). XML decodes to XmlNode trees.
local nullMeta = { __tostring = function()
return "null"
end }
Types.null = table.freeze(setmetatable({}, nullMeta))
export type XmlNode = { name: string, attrs: { [string]: string }, children: { XmlNode | string }, parent: XmlNode? }
-- ------------------------------------------------------------------------------------------------ Vector
export type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any }
export type VectorPath = {
d: { { op: string, [number]: number } }, -- absolute M / L / C / Q / Z commands
fill: Paint?,
fillRule: "nonzero" | "evenodd",
stroke: Paint?,
strokeWidth: number,
transform: { number }?, -- a, b, c, d, e, f
opacity: number,
}
export type Vector = {
kind: "vector",
width: number,
height: number,
viewBox: { number }, -- x, y, w, h
paths: { VectorPath },
meta: { [string]: any },
}
local Vector = {}
function Vector.new(width: number, height: number): Vector
return { kind = "vector", width = width, height = height, viewBox = { 0, 0, width, height }, paths = {}, meta = {} }
end
Types.Vector = Vector
-- ------------------------------------------------------------------------------------------------ Layered (PSD, Aseprite)
export type Layer = { name: string, image: Image, x: number, y: number, opacity: number, blend: string, visible: boolean }
export type Layered = {
kind: "layered",
width: number,
height: number,
layers: { Layer }, -- bottom to top
frames: { { layers: { Layer }, delay: number } }?,
meta: { [string]: any },
}
local Layered = {}
function Layered.new(width: number, height: number): Layered
return { kind = "layered", width = width, height = height, layers = {}, frames = nil, meta = {} }
end
Types.Layered = Layered
-- ------------------------------------------------------------------------------------------------ TileMap (Tiled)
export type Tileset = { name: string, firstGid: number, tileWidth: number, tileHeight: number, columns: number, count: number, image: Image?, source: string? }
export type TileLayer = { name: string, type: "tiles" | "objects" | "image" | "group", width: number?, height: number?, data: { number }?, objects: { any }?, visible: boolean, opacity: number, properties: { [string]: any } }
export type TileMap = {
kind: "tilemap",
width: number,
height: number,
tileWidth: number,
tileHeight: number,
orientation: string,
tilesets: { Tileset },
layers: { TileLayer },
properties: { [string]: any },
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ Subtitles
export type Cue = { start: number, stop: number, text: string, style: string?, id: string?, [string]: any } -- seconds
export type Subtitles = { kind: "subtitles", cues: { Cue }, styles: { [string]: any }, meta: { [string]: any } }
local Subtitles = {}
function Subtitles.new(): Subtitles
return { kind = "subtitles", cues = {}, styles = {}, meta = {} }
end
Types.Subtitles = Subtitles
-- ------------------------------------------------------------------------------------------------ Playlist
-- the playlist-luau shape
export type PlaylistEntry = {
url: string,
title: string?,
duration: number?,
playable: boolean,
reason: string?,
bandwidth: number?,
codecs: string?,
attributes: { [string]: string }?,
byteRange: { length: number, offset: number? }?,
}
export type Playlist = {
kind: "playlist",
format: string, -- "m3u", "pls", "hls", "xspf"
entries: { PlaylistEntry },
warnings: { string },
title: string?,
hls: { [string]: any }?,
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ the format contract
-- what every format folder's init.luau returns (checked by tools/lint.sh CONTRACT; see docs/STYLE.md)
export type Caps = { decode: boolean, encode: boolean, [string]: any }
export type Format = {
name: string,
category: string,
extensions: { string },
mime: { string },
deps: { string },
sniff: (r: any) -> number, -- confidence 0..1 from the first bytes (a core/Bytes Reader); must not consume / throw
decode: ((r: any, opts: any?) -> (any, Err?))?,
encode: ((value: any, opts: any?) -> (buffer?, Err?))?,
open: ((r: any, opts: any?) -> (any, Err?))?, -- streaming categories (audio / video)
caps: Caps,
}
-- the categories, in the order F.formats() lists them; kind = the `kind` of the values they decode to
Types.CATEGORIES = table.freeze({
image = "image",
audio = "audio",
video = "video",
model = "scene",
cad = "cad",
font = "font",
archive = "archive",
data = "data",
vector = "vector",
layered = "layered",
subtitle = "subtitles",
music = "music",
playlist = "playlist",
})
return Types
+432
View File
@@ -0,0 +1,432 @@
--!strict
--!native
--!optimize 2
-- codecs/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth
-- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (core/Huffman
-- length-limited codes). Level 0 = stored blocks only.
--
-- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments).
local Huffman = require("@formats/core/Huffman")
local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
local floor = math.floor
local WSIZE = 32768
local HSIZE = 65536
local MAXMATCH = 258
local BLOCKSYMS = 16384 -- symbols per block
-- per level (zlib's configuration_table): GOOD = a match this long quarters the chain for the lazy search, LAZY = no
-- lazy search after a match this long, NICE = stop searching at this length, CHAIN = max chain steps. Levels 1-3 are
-- greedy (no lazy matching).
local GOOD = { 4, 4, 4, 4, 8, 8, 8, 32, 32 }
local LAZY = { 0, 0, 0, 4, 16, 16, 32, 128, 258 }
local NICE = { 8, 16, 32, 16, 32, 128, 128, 258, 258 }
local CHAIN = { 4, 8, 32, 16, 32, 128, 256, 1024, 4096 }
-- length 3..258 -> code 257..285 (index len), its extra bits and base
local LCODE, LEXTRA, LBASEOF = table.create(259, 0), table.create(259, 0), table.create(259, 0)
local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }
local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }
for c = 1, 29 do
local base = LBASE[c]
local top = if c == 29 then 258 elseif c == 28 then 257 else LBASE[c + 1] - 1
for len = base, top do
LCODE[len] = 256 + c
LEXTRA[len] = LEXT[c]
LBASEOF[len] = base
end
end
local DBASE = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097,
6145, 8193, 12289, 16385, 24577,
}
local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }
-- distance -> code (0..29): direct for 1..256, by (d - 1) // 128 above
local DSMALL, DLARGE = table.create(257, 0), table.create(257, 0)
for c = 1, 30 do
local base = DBASE[c]
local top = if c == 30 then 32768 else DBASE[c + 1] - 1
for d = base, math.min(top, 256) do
DSMALL[d] = c - 1
end
if top > 256 then
for k = math.max(base, 257), top, 128 do
DLARGE[(k - 1) // 128 + 1] = c - 1
end
end
end
local function dcode(d: number): number
if d <= 256 then
return DSMALL[d]
end
return DLARGE[(d - 1) // 128 + 1]
end
local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }
-- fixed codes
local FIXLEN = table.create(288, 0)
for i = 1, 288 do
FIXLEN[i] = if i <= 144 then 8 elseif i <= 256 then 9 elseif i <= 280 then 7 else 8
end
local FIXDLEN = table.create(30, 5)
-- reversed (LSB-first) canonical codes for lengths
local function revCodes(lens: { number }): { number }
local codes = Huffman.codes(lens)
for i, l in lens do
if l > 0 then
codes[i] = Huffman.reverse(codes[i], l)
end
end
return codes
end
local FIXCODE = revCodes(FIXLEN)
local FIXDCODE = revCodes(FIXDLEN)
local POW = table.create(33, 0)
for i = 0, 32 do
POW[i + 1] = 2 ^ i
end
-- ------------------------------------------------------------------------------------------------ bit output
type Out = { buf: buffer, op: number, acc: number, cnt: number }
local function ensure(o: Out, n: number)
if o.op + n > blen(o.buf) then
local nb = bcreate(math.max(blen(o.buf) * 2, o.op + n))
bcopy(nb, 0, o.buf, 0, o.op)
o.buf = nb
end
end
-- put(v, n): n <= 24 bits, LSB first
local function put(o: Out, v: number, n: number)
local acc = o.acc + v * POW[o.cnt + 1]
local cnt = o.cnt + n
if cnt >= 8 then
ensure(o, 4)
local buf, op = o.buf, o.op
while cnt >= 8 do
local byte = acc % 256
writeu8(buf, op, byte)
op += 1
acc = (acc - byte) / 256
cnt -= 8
end
o.op = op
end
o.acc, o.cnt = acc, cnt
end
local function alignOut(o: Out)
if o.cnt > 0 then
put(o, 0, 8 - o.cnt)
end
end
-- ------------------------------------------------------------------------------------------------ blocks
-- syms: L[i] = literal 0..255 or 256 + match length; D[i] = distance (0 for literals)
local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean)
local p = s
repeat
local n = math.min(65535, e - p)
local last = final and p + n >= e
put(o, if last then 1 else 0, 3)
alignOut(o)
ensure(o, 4 + n)
writeu16(o.buf, o.op, n)
writeu16(o.buf, o.op + 2, 65535 - n)
bcopy(o.buf, o.op + 4, src, p, n)
o.op += 4 + n
p += n
until p >= e
end
local function emitSymbols(o: Out, L: { number }, D: { number }, nsym: number, lcode: { number }, llen: { number }, dcodes: { number }, dlen: { number })
for i = 1, nsym do
local l = L[i]
if l < 256 then
put(o, lcode[l + 1], llen[l + 1])
else
local len = l - 256
local c = LCODE[len]
put(o, lcode[c + 1], llen[c + 1])
local xb = LEXTRA[len]
if xb > 0 then
put(o, len - LBASEOF[len], xb)
end
local d = D[i]
local dc = dcode(d)
put(o, dcodes[dc + 1], dlen[dc + 1])
xb = DEXT[dc + 1]
if xb > 0 then
put(o, d - DBASE[dc + 1], xb)
end
end
end
put(o, lcode[257], llen[257]) -- end of block
end
local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D: { number }, nsym: number, final: boolean)
local lf = table.create(286, 0)
local df = table.create(30, 0)
local extra = 0
for i = 1, nsym do
local l = L[i]
if l < 256 then
lf[l + 1] += 1
else
local len = l - 256
lf[LCODE[len] + 1] += 1
extra += LEXTRA[len]
local dc = dcode(D[i])
df[dc + 1] += 1
extra += DEXT[dc + 1]
end
end
lf[257] = 1
local llen = Huffman.lengths(lf, 15)
local dlen = Huffman.lengths(df, 15)
local hlit = 286
while hlit > 257 and llen[hlit] == 0 do
hlit -= 1
end
local hdist = 30
while hdist > 1 and dlen[hdist] == 0 do
hdist -= 1
end
if dlen[1] == 0 and hdist == 1 then
dlen[1] = 1 -- at least one distance code (a lone 1-bit code, as zlib writes)
end
-- code-length symbols: RLE of the hlit + hdist lengths
local all = table.create(hlit + hdist, 0)
for i = 1, hlit do
all[i] = llen[i]
end
for i = 1, hdist do
all[hlit + i] = dlen[i]
end
local cs, cx = {}, {} -- symbol, extra value
local cf = table.create(19, 0)
local i = 1
local total = hlit + hdist
while i <= total do
local v = all[i]
local run = 1
while i + run <= total and all[i + run] == v do
run += 1
end
if v == 0 and run >= 3 then
local r = math.min(run, 138)
if r >= 11 then
table.insert(cs, 18)
table.insert(cx, r - 11)
cf[19] += 1
else
table.insert(cs, 17)
table.insert(cx, r - 3)
cf[18] += 1
end
i += r
elseif v ~= 0 and run >= 4 then
table.insert(cs, v)
table.insert(cx, 0)
cf[v + 1] += 1
local r = math.min(run - 1, 6)
table.insert(cs, 16)
table.insert(cx, r - 3)
cf[17] += 1
i += 1 + r
else
table.insert(cs, v)
table.insert(cx, 0)
cf[v + 1] += 1
i += 1
end
end
local clen = Huffman.lengths(cf, 7)
local hclen = 19
while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do
hclen -= 1
end
-- costs in bits
local dyn = 17 + 3 * hclen + extra
for k = 1, 19 do
dyn += cf[k] * clen[k]
end
dyn += cf[17] * 2 + cf[18] * 3 + cf[19] * 7
local fix = 3 + extra
for k = 1, 286 do
dyn += lf[k] * llen[k]
fix += lf[k] * FIXLEN[k]
end
for k = 1, 30 do
dyn += df[k] * dlen[k]
fix += df[k] * 5
end
local stored = (e - s) * 8 + 40 * (floor((e - s) / 65535) + 1) + 7
if stored <= dyn and stored <= fix then
storedBlock(o, src, s, e, final)
return
end
if fix <= dyn then
put(o, if final then 3 else 2, 3)
emitSymbols(o, L, D, nsym, FIXCODE, FIXLEN, FIXDCODE, FIXDLEN)
return
end
put(o, if final then 5 else 4, 3)
put(o, hlit - 257, 5)
put(o, hdist - 1, 5)
put(o, hclen - 4, 4)
for k = 1, hclen do
put(o, clen[CLORDER[k] + 1], 3)
end
local ccode = revCodes(clen)
for k = 1, #cs do
local c = cs[k]
put(o, ccode[c + 1], clen[c + 1])
if c == 16 then
put(o, cx[k], 2)
elseif c == 17 then
put(o, cx[k], 3)
elseif c == 18 then
put(o, cx[k], 7)
end
end
emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen)
end
-- ------------------------------------------------------------------------------------------------ LZ77
local Compress = {}
function Compress.raw(src: buffer, off: number, len: number, level: number): buffer
local o: Out = { buf = bcreate(math.max(64, len // 2 + 64)), op = 0, acc = 0, cnt = 0 }
local e = off + len
if level == 0 or len == 0 then
if len == 0 then
put(o, 3, 3) -- one empty fixed block
put(o, 0, 7)
else
storedBlock(o, src, off, e, true)
end
alignOut(o)
local out = bcreate(o.op)
bcopy(out, 0, o.buf, 0, o.op)
return out
end
local maxChain = CHAIN[level]
local nice = NICE[level]
local good = GOOD[level]
local lazyMax = LAZY[level]
local head = table.create(HSIZE, -1)
local prev = table.create(WSIZE, -1)
local L = table.create(BLOCKSYMS, 0)
local D = table.create(BLOCKSYMS, 0)
local nsym = 0
local blockStart = off
local function hash(p: number): number
return ((readu8(src, p) * 251 + readu8(src, p + 1)) * 251 + readu8(src, p + 2)) % HSIZE
end
local function insert(p: number)
local h = hash(p) + 1
prev[p % WSIZE + 1] = head[h]
head[h] = p
end
-- longest match at p among earlier positions: len (0 if < 3), dist
local function find(p: number, steps: number): (number, number)
local maxLen = math.min(MAXMATCH, e - p)
if maxLen < 3 then
return 0, 0
end
local best, bestDist = 2, 0
local c = head[hash(p) + 1]
local limit = p - WSIZE
while c >= 0 and c > limit and steps > 0 do
if readu8(src, c + best) == readu8(src, p + best) and readu8(src, c) == readu8(src, p) then
local k = 1
while k < maxLen and readu8(src, c + k) == readu8(src, p + k) do
k += 1
end
if k > best then
best, bestDist = k, p - c
if k >= nice or k >= maxLen then
break
end
end
end
local nc = prev[c % WSIZE + 1]
if nc >= c then
break -- the slot was reused by a newer position: the chain ends here
end
c = nc
steps -= 1
end
if best < 3 then
return 0, 0
end
return best, bestDist
end
local function flush(upto: number, final: boolean)
block(o, src, blockStart, upto, L, D, nsym, final)
nsym = 0
blockStart = upto
end
local p = off
local stop3 = e - 3 -- positions with 3 bytes ahead can be hashed
while p < e do
local mlen, mdist = 0, 0
if p <= stop3 then
mlen, mdist = find(p, maxChain)
insert(p)
if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then
local l2, d2 = find(p + 1, if mlen >= good then maxChain // 4 else maxChain)
if l2 > mlen then
-- a literal now, the longer match from p + 1
nsym += 1
L[nsym] = readu8(src, p)
D[nsym] = 0
p += 1
insert(p)
mlen, mdist = l2, d2
end
end
end
if mlen >= 3 then
nsym += 1
L[nsym] = 256 + mlen
D[nsym] = mdist
local q = p + 1
local qe = math.min(p + mlen, stop3 + 1)
while q < qe do
insert(q)
q += 1
end
p += mlen
else
nsym += 1
L[nsym] = readu8(src, p)
D[nsym] = 0
p += 1
end
if nsym >= BLOCKSYMS - 2 then
flush(p, p >= e)
end
end
if nsym > 0 or blockStart < e then
flush(e, true)
elseif blockStart == e and o.op == 0 and o.cnt == 0 then
put(o, 3, 3)
put(o, 0, 7)
end
alignOut(o)
local out = bcreate(o.op)
bcopy(out, 0, o.buf, 0, o.op)
return out
end
return Compress
+435
View File
@@ -0,0 +1,435 @@
--!strict
--!native
--!optimize 2
-- codecs/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks.
-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to core/Huffman, whose
-- entries are symbol * 32 + length (5 length bits instead of 4).
--
-- Bits are read LSB first into a 32-bit bit buffer (refilled 4 bytes at a time with one readu32 while the input
-- lasts). Huffman codes decode through a core/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer
-- code's primary slot links to a subtable, so a symbol is one or two table reads.
--
-- Nothing in this module throws on any input: every buffer read and write is bounds-checked, and corrupt data
-- returns nil, message. (Native code must never throw: it crashes Roblox Studio.)
local Huffman = require("@formats/core/Huffman")
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len
local LITBITS, DISTBITS, CLBITS = 10, 8, 7
local LITMASK, DISTMASK, CLMASK = 1023, 255, 127
-- length codes 257..285 and distance codes 0..29: base value, extra bits
local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }
local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }
local DBASE = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097,
6145, 8193, 12289, 16385, 24577,
}
local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }
-- the order code-length code lengths are sent in
local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }
-- table capacities (entries): primary + one subtable per code longer than the primary width, worst case
local LITCAP = Huffman.capacity(288, LITBITS, 15)
local DISTCAP = Huffman.capacity(32, DISTBITS, 15)
local CLCAP = Huffman.capacity(19, CLBITS, 7)
-- fixed Huffman tables
local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
local FLITS, FDISTS
do
local l = bcreate(288)
bfill(l, 0, 8, 144)
bfill(l, 144, 9, 112)
bfill(l, 256, 7, 24)
bfill(l, 280, 8, 8)
FLITS = Huffman.buildLsb(l, 0, 288, FLIT, LITBITS)
local d = bcreate(30)
bfill(d, 0, 5, 30)
FDISTS = Huffman.buildLsb(d, 0, 30, FDIST, DISTBITS)
end
local Inflate = {}
-- Grow out (capacity cap) to hold at least need bytes. Returns the new buffer and capacity.
local function grow(out: buffer, op: number, need: number): (buffer, number)
local cap = math.max(blen(out) * 2, need, 1024)
local nb = bcreate(cap)
bcopy(nb, 0, out, 0, op)
return nb, cap
end
-- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in
-- cap bytes (an error otherwise), false = grow as needed.
-- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message.
function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean): (buffer?, any, number?)
local out = bcreate(cap)
local op = 0
local pos = start
local bitbuf, bitcnt, over = 0, 0, 0
local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
local clt = bcreate(CLCAP * 4)
local lens = bcreate(320)
local final = 0
repeat
-- block header (3 bits); also up to 14 bits of a dynamic header
if bitcnt < 17 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
final = band(bitbuf, 1)
local btype = band(rshift(bitbuf, 1), 3)
bitbuf = rshift(bitbuf, 3)
bitcnt -= 3
if btype == 0 then
-- stored: skip to the byte boundary, give back the whole bytes still in the bit buffer
local k = band(bitcnt, 7)
bitcnt -= k
local real = rshift(bitcnt, 3) - over
if real < 0 then
return nil, "truncated input"
end
pos -= real
bitbuf, bitcnt, over = 0, 0, 0
if pos + 4 > endpos then
return nil, "truncated input"
end
local n = readu16(src, pos)
if n ~= bxor(readu16(src, pos + 2), 0xFFFF) then
return nil, "stored block length mismatch"
end
pos += 4
if pos + n > endpos then
return nil, "truncated input"
end
if op + n > cap then
if exact then
return nil, "output larger than expected"
end
out, cap = grow(out, op, op + n)
end
bcopy(out, op, src, pos, n)
op += n
pos += n
continue
end
local lsub, dsub
if btype == 1 then
lt, dt = FLIT, FDIST
lsub, dsub = FLITS, FDISTS
elseif btype == 2 then
if lt == FLIT then
lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
end
local hlit = band(bitbuf, 31) + 257
local hdist = band(rshift(bitbuf, 5), 31) + 1
local hclen = band(rshift(bitbuf, 10), 15) + 4
bitbuf = rshift(bitbuf, 14)
bitcnt -= 14
if hlit > 286 or hdist > 30 then
return nil, "too many length or distance symbols"
end
bfill(lens, 0, 0, 19)
for i = 1, hclen do
if bitcnt < 3 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
writeu8(lens, CLORDER[i], band(bitbuf, 7))
bitbuf = rshift(bitbuf, 3)
bitcnt -= 3
end
if Huffman.buildLsb(lens, 0, 19, clt, CLBITS) < 0 then
return nil, "invalid code lengths set"
end
local total = hlit + hdist
local i = 0
while i < total do
if bitcnt < 14 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
local e = readu32(clt, band(bitbuf, CLMASK) * 4)
local l = band(e, 31)
if l == 0 then
return nil, "invalid code lengths set"
end
bitbuf = rshift(bitbuf, l)
bitcnt -= l
local sym = rshift(e, 5)
if sym < 16 then
writeu8(lens, i, sym)
i += 1
else
local rep, val
if sym == 16 then
if i == 0 then
return nil, "repeat with no first length"
end
val = readu8(lens, i - 1)
rep = 3 + band(bitbuf, 3)
bitbuf = rshift(bitbuf, 2)
bitcnt -= 2
elseif sym == 17 then
val = 0
rep = 3 + band(bitbuf, 7)
bitbuf = rshift(bitbuf, 3)
bitcnt -= 3
else
val = 0
rep = 11 + band(bitbuf, 127)
bitbuf = rshift(bitbuf, 7)
bitcnt -= 7
end
if i + rep > total then
return nil, "too many code lengths"
end
bfill(lens, i, val, rep)
i += rep
end
end
if readu8(lens, 256) == 0 then
return nil, "missing end-of-block code"
end
lsub = Huffman.buildLsb(lens, 0, hlit, lt, LITBITS)
dsub = Huffman.buildLsb(lens, hlit, hdist, dt, DISTBITS)
if lsub < 0 or dsub < 0 then
return nil, "invalid literal/length or distance code set"
end
else
return nil, "invalid block type"
end
local lsmask = lshift(1, lsub) - 1
local dsmask = lshift(1, dsub) - 1
-- the symbol loop
while true do
if bitcnt < 15 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
local e = readu32(lt, band(bitbuf, LITMASK) * 4)
local l = band(e, 31)
if l == 0 then
if e == 0 then
return nil, "invalid literal/length code"
end
e = readu32(lt, (rshift(e, 5) + band(rshift(bitbuf, LITBITS), lsmask)) * 4)
l = band(e, 31)
if l == 0 then
return nil, "invalid literal/length code"
end
end
bitbuf = rshift(bitbuf, l)
bitcnt -= l
local sym = rshift(e, 5)
if sym < 256 then
if op >= cap then
if exact then
return nil, "output larger than expected"
end
out, cap = grow(out, op, op + 1)
end
writeu8(out, op, sym)
op += 1
elseif sym == 256 then
break
else
sym -= 256
if sym > 29 then
return nil, "invalid literal/length code"
end
-- up to 5 length extra bits + a 15-bit distance code
if bitcnt < 20 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
local len = LBASE[sym]
local xb = LEXT[sym]
if xb > 0 then
len += band(bitbuf, lshift(1, xb) - 1)
bitbuf = rshift(bitbuf, xb)
bitcnt -= xb
end
e = readu32(dt, band(bitbuf, DISTMASK) * 4)
l = band(e, 31)
if l == 0 then
if e == 0 then
return nil, "invalid distance code"
end
e = readu32(dt, (rshift(e, 5) + band(rshift(bitbuf, DISTBITS), dsmask)) * 4)
l = band(e, 31)
if l == 0 then
return nil, "invalid distance code"
end
end
bitbuf = rshift(bitbuf, l)
bitcnt -= l
local dsym = rshift(e, 5) + 1
if dsym > 30 then
return nil, "invalid distance code"
end
local dist = DBASE[dsym]
xb = DEXT[dsym]
if xb > 0 then
if bitcnt < 13 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
dist += band(bitbuf, lshift(1, xb) - 1)
bitbuf = rshift(bitbuf, xb)
bitcnt -= xb
end
if dist > op then
return nil, "invalid distance too far back"
end
if op + len > cap then
if exact then
return nil, "output larger than expected"
end
out, cap = grow(out, op, op + len)
end
local s = op - dist
if dist >= len then
if len <= 16 and op + 16 <= cap then
-- straight-line 16-byte copy (the bytes past len are rewritten later): no inner loop, which
-- keeps LuaJIT's traces simple; chunks read only bytes before op or already copied ones
writeu32(out, op, readu32(out, s))
writeu32(out, op + 4, readu32(out, s + 4))
writeu32(out, op + 8, readu32(out, s + 8))
writeu32(out, op + 12, readu32(out, s + 12))
elseif len <= 16 then
for k = 0, len - 1 do
writeu8(out, op + k, readu8(out, s + k))
end
else
bcopy(out, op, out, s, len)
end
op += len
elseif dist == 1 then
bfill(out, op, readu8(out, s), len)
op += len
else
-- overlapping: the pattern of period dist, copied in growing non-overlapping chunks
local rem = len
while rem > 0 do
local k = math.min(op - s, rem)
bcopy(out, op, out, s, k)
op += k
rem -= k
end
end
end
end
until final == 1
local consumed = pos + over - rshift(bitcnt, 3)
if consumed > endpos then
return nil, "truncated input"
end
return out, op, consumed
end
return Inflate
+301
View File
@@ -0,0 +1,301 @@
--!strict
-- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
-- A codec (layer 1), not a format: png, zip, gzip, woff, tiff, ... build on it. Absorbed from deflate-luau 1.0.0
-- (same author; no third-party code); the compressor is new.
--
-- local Deflate = require("@formats/codecs/Deflate")
-- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err
-- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known
-- local out, err = Deflate.zlib(buf) -- checks the Adler-32
-- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members
-- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip
--
-- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG).
local Err = require("@formats/core/Err")
local Crc32 = require("@formats/core/Crc32")
local Adler32 = require("@formats/core/Adler32")
local Inflate = require("@formats/codecs/Deflate/Inflate")
local Compress = require("@formats/codecs/Deflate/Compress")
local Deflate = {}
Deflate.version = "1.1.0"
local function toBuffer(b: any): buffer?
if type(b) == "string" then
return buffer.fromstring(b)
end
if type(b) ~= "buffer" then
return nil
end
return b
end
-- (offset, length) clamped to the buffer; nil for non-numbers / negative / fractional / out-of-range offsets
local function range(b: buffer, off: number?, len: number?): (number?, number)
local n = buffer.len(b)
local o = off or 0
if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
return nil, 0
end
local l = len or (n - o)
if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
return nil, 0
end
if o + l > n then
l = n - o
end
return o, l
end
local function args(what: string, buf: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?)
local b = toBuffer(buf)
if not b then
return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(buf))
end
local o, l = range(b, offset, length)
if not o then
return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length))
end
return b, o, l, nil
end
local function shrink(out: buffer, n: number): buffer
if buffer.len(out) == n then
return out
end
local b = buffer.create(n)
buffer.copy(b, 0, out, 0, n)
return b
end
local function inflateErr(msg: string, at: number?): Err.Err
local code = if string.find(msg, "truncated", 1, true) then Err.TRUNCATED else Err.CORRUPT
return Err.new(code, "inflate: " .. msg, at)
end
-- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate.
-- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream
-- that inflates to a different size is an error. consumedEnd is the input offset just past the final block.
function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any)
local b, o, l, aerr = args("Deflate.inflate", buf, offset, length)
if not b then
return nil, aerr
end
local exact = expectedSize ~= nil
local cap
if exact then
if type(expectedSize) ~= "number" or expectedSize < 0 or expectedSize % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Deflate.inflate: bad expectedSize " .. tostring(expectedSize))
end
cap = expectedSize
else
cap = math.max(1024, l * 4)
end
local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact)
if not out then
return nil, inflateErr(tostring(n), o)
end
if exact and n ~= expectedSize then
return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize :: number))
end
return shrink(out, n), consumed
end
-- zlib(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err
function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any)
local b, o, l, aerr = args("Deflate.zlib", buf, offset, length)
if not b then
return nil, aerr
end
if l < 6 then
return nil, Err.new(Err.TRUNCATED, "zlib: truncated header", o)
end
local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1)
if cmf % 16 ~= 8 or cmf // 16 > 7 then
return nil, Err.new(Err.CORRUPT, "zlib: not a deflate stream (CMF " .. cmf .. ")", o)
end
if (cmf * 256 + flg) % 31 ~= 0 then
return nil, Err.new(Err.CORRUPT, "zlib: header check failed", o)
end
if bit32.band(flg, 0x20) ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "zlib: preset dictionaries are not supported", o)
end
local out, consumed = Deflate.inflate(b, o + 2, l - 2, expectedSize)
if not out then
return nil, consumed
end
if consumed + 4 > o + l then
return nil, Err.new(Err.TRUNCATED, "zlib: missing Adler-32", consumed)
end
local want = bit32.byteswap(buffer.readu32(b, consumed))
local got = Adler32.raw(out, 0, buffer.len(out))
if got ~= want then
return nil, Err.new(Err.CHECKSUM, string.format("zlib: Adler-32 mismatch (%08x, expected %08x)", got, want), consumed)
end
return out, consumed + 4
end
-- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is
-- not another gzip member (zero padding, garbage) is ignored, as gzip -d does.
function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length)
if not b then
return nil, aerr
end
local e = o + l
local parts, total = {}, 0
local p = o
repeat
if p + 18 > e then
if #parts > 0 then
break
end
return nil, Err.new(Err.TRUNCATED, "gzip: truncated member", p)
end
if buffer.readu8(b, p) ~= 0x1f or buffer.readu8(b, p + 1) ~= 0x8b then
if #parts > 0 then
break -- trailing garbage after a member: ignored, as gzip -d does
end
return nil, Err.new(Err.CORRUPT, "gzip: bad magic", p)
end
if buffer.readu8(b, p + 2) ~= 8 then
return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2)
end
local flg = buffer.readu8(b, p + 3)
if flg >= 0x20 then
return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3)
end
local q = p + 10
if bit32.band(flg, 4) ~= 0 then -- FEXTRA
if q + 2 > e then
return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q)
end
q += 2 + buffer.readu16(b, q)
end
for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated
if bit32.band(flg, bit) ~= 0 then
while q < e and buffer.readu8(b, q) ~= 0 do
q += 1
end
q += 1
end
end
if bit32.band(flg, 2) ~= 0 then -- FHCRC
q += 2
end
if q >= e then
return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q)
end
local out, consumed = Deflate.inflate(b, q, e - q)
if not out then
return nil, consumed
end
if consumed + 8 > e then
return nil, Err.new(Err.TRUNCATED, "gzip: missing trailer", consumed)
end
local want, isize = buffer.readu32(b, consumed), buffer.readu32(b, consumed + 4)
local got = Crc32.raw(out, 0, buffer.len(out))
if got ~= want then
return nil, Err.new(Err.CHECKSUM, string.format("gzip: CRC-32 mismatch (%08x, expected %08x)", got, want), consumed)
end
if buffer.len(out) % 4294967296 ~= isize then
return nil, Err.new(Err.CORRUPT, "gzip: length mismatch", consumed + 4)
end
table.insert(parts, out)
total += buffer.len(out)
p = consumed + 8
-- skip zero padding
local z = p
while z < e and buffer.readu8(b, z) == 0 do
z += 1
end
if z == e then
break
end
until p >= e
if #parts == 1 then
return parts[1], nil
end
local res = buffer.create(total)
local w = 0
for _, part in parts do
buffer.copy(res, w, part)
w += buffer.len(part)
end
return res, nil
end
export type CompressOptions = {
level: number?, -- 0 (stored) .. 9 (best); default 6
}
local function level(opts: CompressOptions?): number?
local lv = if opts and opts.level ~= nil then opts.level else 6
if type(lv) ~= "number" or lv < 0 or lv > 9 or lv % 1 ~= 0 then
return nil
end
return lv
end
-- compress(buf, opts?) -> raw deflate buffer | nil, Err
function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
if not b or not lv then
return nil, Err.new(Err.ARG, "Deflate.compress: expected a buffer or a string and opts.level 0..9")
end
return Compress.raw(b, 0, buffer.len(b), lv), nil
end
-- zlibCompress(buf, opts?) -> zlib stream | nil, Err
function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
if not b or not lv then
return nil, Err.new(Err.ARG, "Deflate.zlibCompress: expected a buffer or a string and opts.level 0..9")
end
local raw = Compress.raw(b, 0, buffer.len(b), lv)
local n = buffer.len(raw)
local out = buffer.create(n + 6)
local flevel = if lv < 2 then 0 elseif lv < 6 then 1 elseif lv == 6 then 2 else 3
local cmf = 0x78
local flg = flevel * 64
flg += 31 - (cmf * 256 + flg) % 31
buffer.writeu8(out, 0, cmf)
buffer.writeu8(out, 1, flg)
buffer.copy(out, 2, raw, 0, n)
buffer.writeu32(out, n + 2, bit32.byteswap(Adler32.raw(b, 0, buffer.len(b))))
return out, nil
end
-- gzip(buf, opts?) -> gzip member (no name, mtime 0) | nil, Err
function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
if not b or not lv then
return nil, Err.new(Err.ARG, "Deflate.gzip: expected a buffer or a string and opts.level 0..9")
end
local raw = Compress.raw(b, 0, buffer.len(b), lv)
local n = buffer.len(raw)
local out = buffer.create(n + 18)
buffer.writestring(out, 0, "\31\139\8\0\0\0\0\0")
buffer.writeu8(out, 8, if lv >= 9 then 2 elseif lv <= 1 then 4 else 0)
buffer.writeu8(out, 9, 255)
buffer.copy(out, 10, raw, 0, n)
buffer.writeu32(out, n + 10, Crc32.raw(b, 0, buffer.len(b)))
buffer.writeu32(out, n + 14, buffer.len(b) % 4294967296)
return out, nil
end
-- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of)
Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number
local b = toBuffer(buf) or buffer.create(0)
return Crc32.of(b, offset, length, crc)
end
Deflate.adler32 = function(buf: buffer | string, offset: number?, length: number?, adler: number?): number
local b = toBuffer(buf) or buffer.create(0)
return Adler32.of(b, offset, length, adler)
end
return Deflate
+50
View File
@@ -0,0 +1,50 @@
--!strict
--!native
-- core/Adler32: Adler-32 (RFC 1950, the zlib checksum). Absorbed from deflate-luau src/Deflate/Checksum.luau (same author;
-- no third-party code). Never throws: the range is clamped.
--
-- Adler32.of(buf, offset?, length?, adler?) -> u32 (starts at 1; pass a previous result to continue it)
-- Adler32.string(s, adler?) -> u32
local readu8 = buffer.readu8
-- Adler-32 of buf[off, off + len), continuing adler (default 1)
local function adler32(buf: buffer, off: number, len: number, adler: number?): number
local a0 = adler or 1
local a, b = a0 % 65536, a0 // 65536
local i, e = off, off + len
while i < e do
-- 5552 is zlib's NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32. Doubles hold far
-- more, but keeping the sums small keeps them exact and cheap.
local stop = math.min(e, i + 5552)
while i < stop do
a += readu8(buf, i)
b += a
i += 1
end
a %= 65521
b %= 65521
end
return b * 65536 + a
end
-- clamp (offset, length) to the buffer
local function range(buf: buffer, offset: number?, length: number?): (number, number)
local n = buffer.len(buf)
local o = math.clamp(offset or 0, 0, n)
return o, math.clamp(length or (n - o), 0, n - o)
end
local Adler32 = {}
function Adler32.of(buf: buffer, offset: number?, length: number?, adler: number?): number
local o, l = range(buf, offset, length)
return adler32(buf, o, l, adler)
end
function Adler32.string(s: string, adler: number?): number
return adler32(buffer.fromstring(s), 0, #s, adler)
end
Adler32.raw = adler32
return Adler32
+287
View File
@@ -0,0 +1,287 @@
--!strict
--!native
-- core/Bits: bit readers and writers, LSB-first (DEFLATE, GIF LZW, VP8L, ...) and MSB-first (JPEG entropy data
-- without the 0xFF00 unstuffing, MPEG, H.264, FLAC, ...). Up to 32 bits per read / write.
--
-- Plain arithmetic on an accumulator of at most 31 bits (no bit32 calls), exact on doubles, cheap on both runtimes.
-- These are the generic, convenient readers: a codec's innermost loop usually keeps its own local bit buffer (see
-- codecs/Deflate/Inflate) and uses these for headers.
--
-- Never throws: reading past the end returns zero bits and sets the sticky `err` (Err.TRUNCATED).
--
-- local br = Bits.lsbReader(buf, offset?, length?) -- or Bits.msbReader
-- local v = br:read(5); if br.err then return nil, br.err end
-- local bw = Bits.msbWriter(); bw:write(0b101, 3); local out = bw:finish()
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local readu8, blen = buffer.readu8, buffer.len
local floor = math.floor
-- 2^n for n = 0..32
local POW = table.create(33, 0)
for i = 0, 32 do
POW[i + 1] = 2 ^ i
end
local Bits = {}
Bits.POW = POW
-- ------------------------------------------------------------------------------------------------ readers
export type BitReader = {
buf: buffer,
pos: number, -- next byte to load
limit: number,
acc: number, -- loaded, unread bits
cnt: number, -- how many
err: Err.Err?,
read: (BitReader, number) -> number,
peek: (BitReader, number) -> number,
skip: (BitReader, number) -> (),
align: (BitReader) -> (),
bytePos: (BitReader) -> number,
bitsLeft: (BitReader) -> number,
}
local function overrun(self: any)
if not self.err then
self.err = Err.new(Err.TRUNCATED, "bit stream ends early", self.limit)
end
end
-- LSB-first: the first bit of the stream is bit 0 of the first byte; a field's first bit is its least significant
local Lsb = {}
Lsb.__index = Lsb
local function lsbFill(self: any, n: number)
local acc, cnt, pos = self.acc, self.cnt, self.pos
while cnt < n do
if pos < self.limit then
acc += readu8(self.buf, pos) * POW[cnt + 1]
pos += 1
else
overrun(self)
end
cnt += 8
end
self.acc, self.cnt, self.pos = acc, cnt, pos
end
function Lsb.read(self: any, n: number): number
if n > 24 then
local lo = Lsb.read(self, 16)
return lo + Lsb.read(self, n - 16) * 65536
end
if self.cnt < n then
lsbFill(self, n)
end
local m = POW[n + 1]
local v = self.acc % m
self.acc = (self.acc - v) / m
self.cnt -= n
return v
end
function Lsb.peek(self: any, n: number): number
if self.cnt < n then
local acc, cnt, pos = self.acc, self.cnt, self.pos
while cnt < n do -- no error for peeking past the end: the bits are zeros
if pos < self.limit then
acc += readu8(self.buf, pos) * POW[cnt + 1]
pos += 1
end
cnt += 8
end
-- keep the loaded bytes only when they are all real (zero padding past the end is not data)
if (pos - self.pos) * 8 == cnt - self.cnt then
self.acc, self.cnt, self.pos = acc, cnt, pos
end
return acc % POW[n + 1]
end
return self.acc % POW[n + 1]
end
function Lsb.skip(self: any, n: number)
while n > 24 do
Lsb.read(self, 24)
n -= 24
end
Lsb.read(self, n)
end
-- align(): drop the bits up to the next byte boundary
function Lsb.align(self: any)
local k = self.cnt % 8
if k > 0 then
Lsb.read(self, k)
end
end
-- bytePos(): the offset of the first byte not yet (even partly) consumed
function Lsb.bytePos(self: any): number
return self.pos - floor(self.cnt / 8)
end
function Lsb.bitsLeft(self: any): number
return (self.limit - self.pos) * 8 + self.cnt
end
-- MSB-first: the first bit of the stream is bit 7 of the first byte; a field's first bit is its most significant
local Msb = {}
Msb.__index = Msb
local function msbFill(self: any, n: number)
local acc, cnt, pos = self.acc, self.cnt, self.pos
while cnt < n do
if pos < self.limit then
acc = acc * 256 + readu8(self.buf, pos)
pos += 1
else
acc *= 256
overrun(self)
end
cnt += 8
end
self.acc, self.cnt, self.pos = acc, cnt, pos
end
function Msb.read(self: any, n: number): number
if n > 24 then
local hi = Msb.read(self, n - 16)
return hi * 65536 + Msb.read(self, 16)
end
if self.cnt < n then
msbFill(self, n)
end
local sh = POW[self.cnt - n + 1]
local v = floor(self.acc / sh)
self.acc -= v * sh
self.cnt -= n
return v
end
function Msb.peek(self: any, n: number): number
local acc, cnt, pos = self.acc, self.cnt, self.pos
while cnt < n do
if pos < self.limit then
acc = acc * 256 + readu8(self.buf, pos)
pos += 1
else
acc *= 256
end
cnt += 8
end
-- keep the loaded bytes only when they are all real (zero padding past the end is not data)
if (pos - self.pos) * 8 == cnt - self.cnt then
self.acc, self.cnt, self.pos = acc, cnt, pos
end
return floor(acc / POW[cnt - n + 1])
end
function Msb.skip(self: any, n: number)
while n > 24 do
Msb.read(self, 24)
n -= 24
end
Msb.read(self, n)
end
function Msb.align(self: any)
local k = self.cnt % 8
if k > 0 then
Msb.read(self, k)
end
end
Msb.bytePos = Lsb.bytePos
Msb.bitsLeft = Lsb.bitsLeft
local function reader(meta: any, buf: buffer, offset: number?, length: number?): BitReader
local n = blen(buf)
local o = math.clamp(offset or 0, 0, n)
local l = math.clamp(length or (n - o), 0, n - o)
return setmetatable({ buf = buf, pos = o, limit = o + l, acc = 0, cnt = 0, err = nil }, meta) :: any
end
-- lsbReader(buf, offset?, length?) / msbReader(buf, offset?, length?) -> BitReader
function Bits.lsbReader(buf: buffer, offset: number?, length: number?): BitReader
return reader(Lsb, buf, offset, length)
end
function Bits.msbReader(buf: buffer, offset: number?, length: number?): BitReader
return reader(Msb, buf, offset, length)
end
-- ------------------------------------------------------------------------------------------------ writers
export type BitWriter = {
out: Bytes.Writer, -- the bytes so far (whole bytes only)
acc: number,
cnt: number,
write: (BitWriter, number, number) -> (),
align: (BitWriter) -> (),
finish: (BitWriter) -> buffer,
}
local LsbW = {}
LsbW.__index = LsbW
function LsbW.write(self: any, v: number, n: number)
if n > 24 then
local lo = v % 65536
LsbW.write(self, lo, 16)
LsbW.write(self, (v - lo) / 65536, n - 16)
return
end
local acc = self.acc + (v % POW[n + 1]) * POW[self.cnt + 1]
local cnt = self.cnt + n
local out = self.out
while cnt >= 8 do
local byte = acc % 256
out:u8(byte)
acc = (acc - byte) / 256
cnt -= 8
end
self.acc, self.cnt = acc, cnt
end
-- align(): pad with zero bits to a byte boundary
function LsbW.align(self: any)
if self.cnt > 0 then
self.out:u8(self.acc)
self.acc, self.cnt = 0, 0
end
end
function LsbW.finish(self: any): buffer
LsbW.align(self)
return self.out:finish()
end
local MsbW = {}
MsbW.__index = MsbW
function MsbW.write(self: any, v: number, n: number)
if n > 24 then
local lo = v % 65536
MsbW.write(self, (v - lo) / 65536, n - 16)
MsbW.write(self, lo, 16)
return
end
local acc = self.acc * POW[n + 1] + (v % POW[n + 1])
local cnt = self.cnt + n
local out = self.out
while cnt >= 8 do
local sh = POW[cnt - 8 + 1]
local byte = floor(acc / sh)
out:u8(byte)
acc -= byte * sh
cnt -= 8
end
self.acc, self.cnt = acc, cnt
end
function MsbW.align(self: any)
if self.cnt > 0 then
self.out:u8(self.acc * POW[8 - self.cnt + 1])
self.acc, self.cnt = 0, 0
end
end
function MsbW.finish(self: any): buffer
MsbW.align(self)
return self.out:finish()
end
-- lsbWriter(capacity?) / msbWriter(capacity?) -> BitWriter
function Bits.lsbWriter(capacity: number?): BitWriter
return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) :: any
end
function Bits.msbWriter(capacity: number?): BitWriter
return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, MsbW) :: any
end
return Bits
+537
View File
@@ -0,0 +1,537 @@
--!strict
--!native
-- core/Bytes: a cursor Reader over a buffer range and a growable Writer. Little / big endian integers up to u64 (as a
-- double: exact to 2^53), f16 / f32 / f64, C strings, fixed strings, and zero-copy sub-readers.
--
-- Never throws. A read past the end (or a failed seek) sets the reader's sticky `err` (Err.TRUNCATED), moves the cursor
-- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads:
--
-- local r = Bytes.reader(buf) -- or Bytes.reader(buf, offset, length)
-- local magic, w, h = r:string(4), r:u32be(), r:u32be()
-- if r.err then return nil, r.err end
-- if magic ~= "abcd" then return r:fail(Err.CORRUPT, "bad magic") end
--
-- local w = Bytes.writer() -- or Bytes.writer(initialCapacity)
-- w:string("abcd"); w:u32be(width); local out = w:finish()
local Err = require("@formats/core/Err")
local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32
local readf32, readf64, readstring = buffer.readf32, buffer.readf64, buffer.readstring
local writeu8, writeu16, writeu32, writef32, writef64, writestring = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32, buffer.writef64, buffer.writestring
local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len
local byteswap = bit32.byteswap
local TWO32 = 4294967296
local scratch = bcreate(8) -- reinterpret casts for big-endian floats
local Bytes = {}
-- ------------------------------------------------------------------------------------------------ Reader
local Reader = {}
Reader.__index = Reader
export type Reader = typeof(setmetatable(
{} :: {
buf: buffer,
pos: number, -- absolute offset of the next byte in buf
base: number, -- absolute offset of the reader's first byte
limit: number, -- absolute offset just past the reader's last byte
err: Err.Err?, -- sticky: the first failure
},
Reader
))
-- reader(buf, offset?, length?) -> Reader over buf[offset, offset + length), clamped to the buffer
function Bytes.reader(buf: buffer, offset: number?, length: number?): Reader
local n = blen(buf)
local o = math.clamp(offset or 0, 0, n)
local l = math.clamp(length or (n - o), 0, n - o)
return setmetatable({ buf = buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader)
end
-- fail(code, message) -> nil, Err: records the first error (at the cursor) and returns it, for `return r:fail(...)`
function Reader.fail(self: Reader, code: string, message: string): (nil, Err.Err)
if not self.err then
self.err = Err.new(code, message, self.pos)
end
return nil, self.err :: Err.Err
end
-- need(n) -> true when n more bytes are available; otherwise records TRUNCATED and moves to the end
function Reader.need(self: Reader, n: number): boolean
if self.pos + n <= self.limit and n >= 0 then
return true
end
if not self.err then
self.err = Err.new(Err.TRUNCATED, string.format("need %d bytes, %d left", n, self.limit - self.pos), self.pos)
end
self.pos = self.limit
return false
end
function Reader.tell(self: Reader): number
return self.pos - self.base
end
function Reader.size(self: Reader): number
return self.limit - self.base
end
function Reader.remaining(self: Reader): number
return self.limit - self.pos
end
function Reader.eof(self: Reader): boolean
return self.pos >= self.limit
end
-- seek(offset) -> boolean: offset relative to the reader's start; out of range records TRUNCATED
function Reader.seek(self: Reader, offset: number): boolean
if offset < 0 or self.base + offset > self.limit then
self.pos = self.limit
if not self.err then
self.err = Err.new(Err.TRUNCATED, "seek to " .. offset .. " past the end", self.base + offset)
end
return false
end
self.pos = self.base + offset
return true
end
function Reader.skip(self: Reader, n: number): boolean
if self:need(n) then
self.pos += n
return true
end
return false
end
-- align(n): skip to the next multiple of n (relative to the reader's start)
function Reader.align(self: Reader, n: number): boolean
local r = (self.pos - self.base) % n
if r == 0 then
return true
end
return self:skip(n - r)
end
-- integers
function Reader.u8(self: Reader): number
local p = self.pos
if p + 1 > self.limit then
self:need(1)
return 0
end
self.pos = p + 1
return readu8(self.buf, p)
end
function Reader.i8(self: Reader): number
local p = self.pos
if p + 1 > self.limit then
self:need(1)
return 0
end
self.pos = p + 1
return readi8(self.buf, p)
end
function Reader.u16le(self: Reader): number
local p = self.pos
if p + 2 > self.limit then
self:need(2)
return 0
end
self.pos = p + 2
return readu16(self.buf, p)
end
function Reader.u16be(self: Reader): number
local p = self.pos
if p + 2 > self.limit then
self:need(2)
return 0
end
self.pos = p + 2
return readu8(self.buf, p) * 256 + readu8(self.buf, p + 1)
end
function Reader.i16le(self: Reader): number
local p = self.pos
if p + 2 > self.limit then
self:need(2)
return 0
end
self.pos = p + 2
return readi16(self.buf, p)
end
function Reader.i16be(self: Reader): number
local v = self:u16be()
return if v >= 32768 then v - 65536 else v
end
function Reader.u24le(self: Reader): number
local p = self.pos
if p + 3 > self.limit then
self:need(3)
return 0
end
self.pos = p + 3
return readu16(self.buf, p) + readu8(self.buf, p + 2) * 65536
end
function Reader.u24be(self: Reader): number
local p = self.pos
if p + 3 > self.limit then
self:need(3)
return 0
end
self.pos = p + 3
return readu8(self.buf, p) * 65536 + readu8(self.buf, p + 1) * 256 + readu8(self.buf, p + 2)
end
function Reader.u32le(self: Reader): number
local p = self.pos
if p + 4 > self.limit then
self:need(4)
return 0
end
self.pos = p + 4
return readu32(self.buf, p)
end
function Reader.u32be(self: Reader): number
local p = self.pos
if p + 4 > self.limit then
self:need(4)
return 0
end
self.pos = p + 4
return byteswap(readu32(self.buf, p))
end
function Reader.i32le(self: Reader): number
local p = self.pos
if p + 4 > self.limit then
self:need(4)
return 0
end
self.pos = p + 4
return readi32(self.buf, p)
end
function Reader.i32be(self: Reader): number
local v = self:u32be()
return if v >= 2147483648 then v - TWO32 else v
end
-- 64-bit integers as doubles (exact below 2^53)
function Reader.u64le(self: Reader): number
local lo = self:u32le()
return lo + self:u32le() * TWO32
end
function Reader.u64be(self: Reader): number
local hi = self:u32be()
return hi * TWO32 + self:u32be()
end
function Reader.i64le(self: Reader): number
local lo = self:u32le()
return lo + self:i32le() * TWO32
end
function Reader.i64be(self: Reader): number
local hi = self:i32be()
return hi * TWO32 + self:u32be()
end
-- floats
local function half(h: number): number
local s = if h >= 32768 then -1 else 1
local e = bit32.band(bit32.rshift(h, 10), 31)
local m = bit32.band(h, 1023)
if e == 0 then
return s * m * 2 ^ -24
elseif e == 31 then
return if m == 0 then s * math.huge else 0 / 0
end
return s * (1 + m / 1024) * 2 ^ (e - 15)
end
Bytes.half = half
function Reader.f16le(self: Reader): number
return half(self:u16le())
end
function Reader.f16be(self: Reader): number
return half(self:u16be())
end
function Reader.f32le(self: Reader): number
local p = self.pos
if p + 4 > self.limit then
self:need(4)
return 0
end
self.pos = p + 4
return readf32(self.buf, p)
end
function Reader.f32be(self: Reader): number
local v = self:u32be()
writeu32(scratch, 0, v)
return readf32(scratch, 0)
end
function Reader.f64le(self: Reader): number
local p = self.pos
if p + 8 > self.limit then
self:need(8)
return 0
end
self.pos = p + 8
return readf64(self.buf, p)
end
function Reader.f64be(self: Reader): number
local hi = self:u32be()
local lo = self:u32be()
writeu32(scratch, 0, lo)
writeu32(scratch, 4, hi)
return readf64(scratch, 0)
end
-- strings
function Reader.string(self: Reader, n: number): string
local p = self.pos
if n < 0 or p + n > self.limit then
self:need(n)
return ""
end
self.pos = p + n
return readstring(self.buf, p, n)
end
-- fixed(n): an n-byte field, cut at the first NUL
function Reader.fixed(self: Reader, n: number): string
local s = self:string(n)
local z = string.find(s, "\0", 1, true)
return if z then string.sub(s, 1, z - 1) else s
end
-- cstring(max?): bytes up to a NUL (consumed, not returned); no NUL before the end (or max bytes) records TRUNCATED
function Reader.cstring(self: Reader, max: number?): string
local p = self.pos
local e = if max then math.min(self.limit, p + max) else self.limit
local q = p
local buf = self.buf
while q < e and readu8(buf, q) ~= 0 do
q += 1
end
if q >= e then
self.pos = e
self:need(1)
return readstring(buf, p, e - p)
end
self.pos = q + 1
return readstring(buf, p, q - p)
end
-- match(s) -> true (and skips s) when the next bytes are s; otherwise false, nothing consumed, no error
function Reader.match(self: Reader, s: string): boolean
local p, n = self.pos, #s
if p + n > self.limit or readstring(self.buf, p, n) ~= s then
return false
end
self.pos = p + n
return true
end
-- peek(n, at?) -> up to n bytes as a string at the cursor (+ at), without consuming; short at the end, never an error
function Reader.peek(self: Reader, n: number, at: number?): string
local p = self.pos + (at or 0)
if p < self.base or p >= self.limit then
return ""
end
return readstring(self.buf, p, math.min(n, self.limit - p))
end
-- peekU8(at?) -> the byte at the cursor (+ at), or -1 past the end
function Reader.peekU8(self: Reader, at: number?): number
local p = self.pos + (at or 0)
if p < self.base or p >= self.limit then
return -1
end
return readu8(self.buf, p)
end
-- bytes(n) -> a new buffer with a copy of the next n bytes
function Reader.bytes(self: Reader, n: number): buffer
local p = self.pos
if n < 0 or p + n > self.limit then
self:need(n)
return bcreate(0)
end
local b = bcreate(n)
bcopy(b, 0, self.buf, p, n)
self.pos = p + n
return b
end
-- slice(n) -> a Reader over the next n bytes (no copy); the parent skips them. Short data: a reader over what is
-- left, and the parent records TRUNCATED.
function Reader.slice(self: Reader, n: number): Reader
local p = self.pos
local l = math.max(0, math.min(n, self.limit - p))
if l < n then
self:need(n)
else
self.pos = p + n
end
return setmetatable({ buf = self.buf, pos = p, base = p, limit = p + l, err = nil :: Err.Err? }, Reader)
end
-- sub(offset, length?) -> a Reader over [offset, offset + length) relative to this reader's start (clamped), without
-- moving the cursor
function Reader.sub(self: Reader, offset: number, length: number?): Reader
local o = math.clamp(self.base + offset, self.base, self.limit)
local l = math.clamp(length or (self.limit - o), 0, self.limit - o)
return setmetatable({ buf = self.buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader)
end
-- ------------------------------------------------------------------------------------------------ Writer
local Writer = {}
Writer.__index = Writer
export type Writer = typeof(setmetatable(
{} :: {
buf: buffer,
pos: number, -- bytes written (the next write offset)
},
Writer
))
-- writer(capacity?) -> Writer
function Bytes.writer(capacity: number?): Writer
return setmetatable({ buf = bcreate(math.max(16, capacity or 256)), pos = 0 }, Writer)
end
-- reserve(n): make room for n more bytes; returns the write offset (for direct buffer.write* into w.buf)
function Writer.reserve(self: Writer, n: number): number
local p = self.pos
local cap = blen(self.buf)
if p + n > cap then
local nb = bcreate(math.max(cap * 2, p + n))
bcopy(nb, 0, self.buf, 0, p)
self.buf = nb
end
return p
end
function Writer.tell(self: Writer): number
return self.pos
end
function Writer.u8(self: Writer, v: number)
local p = self:reserve(1)
writeu8(self.buf, p, v)
self.pos = p + 1
end
function Writer.u16le(self: Writer, v: number)
local p = self:reserve(2)
writeu16(self.buf, p, v)
self.pos = p + 2
end
function Writer.u16be(self: Writer, v: number)
local p = self:reserve(2)
writeu8(self.buf, p, bit32.rshift(v, 8))
writeu8(self.buf, p + 1, v)
self.pos = p + 2
end
function Writer.u24le(self: Writer, v: number)
local p = self:reserve(3)
writeu16(self.buf, p, v)
writeu8(self.buf, p + 2, bit32.rshift(v, 16))
self.pos = p + 3
end
function Writer.u24be(self: Writer, v: number)
local p = self:reserve(3)
writeu8(self.buf, p, bit32.rshift(v, 16))
writeu8(self.buf, p + 1, bit32.rshift(v, 8))
writeu8(self.buf, p + 2, v)
self.pos = p + 3
end
function Writer.u32le(self: Writer, v: number)
local p = self:reserve(4)
writeu32(self.buf, p, v)
self.pos = p + 4
end
function Writer.u32be(self: Writer, v: number)
local p = self:reserve(4)
writeu32(self.buf, p, byteswap(v % TWO32))
self.pos = p + 4
end
Writer.i8 = Writer.u8
Writer.i16le = Writer.u16le
Writer.i16be = Writer.u16be
Writer.i32le = Writer.u32le
Writer.i32be = Writer.u32be
function Writer.u64le(self: Writer, v: number)
self:u32le(v % TWO32)
self:u32le(math.floor(v / TWO32) % TWO32)
end
function Writer.u64be(self: Writer, v: number)
self:u32be(math.floor(v / TWO32) % TWO32)
self:u32be(v % TWO32)
end
Writer.i64le = Writer.u64le
Writer.i64be = Writer.u64be
function Writer.f32le(self: Writer, v: number)
local p = self:reserve(4)
writef32(self.buf, p, v)
self.pos = p + 4
end
function Writer.f32be(self: Writer, v: number)
writef32(scratch, 0, v)
self:u32be(readu32(scratch, 0))
end
function Writer.f64le(self: Writer, v: number)
local p = self:reserve(8)
writef64(self.buf, p, v)
self.pos = p + 8
end
function Writer.f64be(self: Writer, v: number)
writef64(scratch, 0, v)
self:u32be(readu32(scratch, 4))
self:u32be(readu32(scratch, 0))
end
function Writer.string(self: Writer, s: string)
local n = #s
local p = self:reserve(n)
writestring(self.buf, p, s)
self.pos = p + n
end
-- cstring(s): s and a NUL
function Writer.cstring(self: Writer, s: string)
self:string(s)
self:u8(0)
end
-- bytes(b, offset?, length?): copy a buffer range
function Writer.bytes(self: Writer, b: buffer, offset: number?, length: number?)
local o = offset or 0
local n = length or (blen(b) - o)
local p = self:reserve(n)
bcopy(self.buf, p, b, o, n)
self.pos = p + n
end
function Writer.fill(self: Writer, v: number, n: number)
local p = self:reserve(n)
bfill(self.buf, p, v, n)
self.pos = p + n
end
-- patch fields written earlier (lengths, CRCs) at an absolute offset < pos
function Writer.setU32le(self: Writer, at: number, v: number)
writeu32(self.buf, at, v)
end
function Writer.setU32be(self: Writer, at: number, v: number)
writeu32(self.buf, at, byteswap(v % TWO32))
end
function Writer.setU16le(self: Writer, at: number, v: number)
writeu16(self.buf, at, v)
end
function Writer.setU8(self: Writer, at: number, v: number)
writeu8(self.buf, at, v)
end
-- finish() -> a buffer of exactly the written bytes (the writer can keep going)
function Writer.finish(self: Writer): buffer
local b = bcreate(self.pos)
bcopy(b, 0, self.buf, 0, self.pos)
return b
end
Bytes.Reader = Reader
Bytes.Writer = Writer
return Bytes
+98
View File
@@ -0,0 +1,98 @@
--!strict
--!native
-- core/Crc32: CRC-32 (IEEE 802.3, the zlib / gzip / zip / PNG polynomial 0xEDB88320, reflected), slice-by-8.
-- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author;
-- no third-party code). Never throws: the range is clamped.
--
-- Crc32.of(buf, offset?, length?, crc?) -> u32 (pass a previous result as crc to continue it)
-- Crc32.string(s, crc?) -> u32
local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift
local readu8, readu32 = buffer.readu8, buffer.readu32
local T0, T1, T2, T3 = table.create(256, 0), table.create(256, 0), table.create(256, 0), table.create(256, 0)
local T4, T5, T6, T7 = table.create(256, 0), table.create(256, 0), table.create(256, 0), table.create(256, 0)
for n = 0, 255 do
local c = n
for _ = 1, 8 do
if band(c, 1) ~= 0 then
c = bxor(0xEDB88320, rshift(c, 1))
else
c = rshift(c, 1)
end
end
T0[n + 1] = c
end
for n = 0, 255 do
local c = T0[n + 1]
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T1[n + 1] = c
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T2[n + 1] = c
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T3[n + 1] = c
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T4[n + 1] = c
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T5[n + 1] = c
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T6[n + 1] = c
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T7[n + 1] = c
end
-- CRC-32 of buf[off, off + len), continuing crc (default 0 = a new CRC). Values are finished CRCs (the inversion
-- happens inside), so crc(b, crc(a)) == the CRC of a .. b.
local function crc32(buf: buffer, off: number, len: number, crc: number?): number
local c = bxor(crc or 0, 0xFFFFFFFF)
local i, e = off, off + len
local e8 = e - 8
while i <= e8 do
c = bxor(c, readu32(buf, i))
local d = readu32(buf, i + 4)
c = bxor(
T7[band(c, 255) + 1],
T6[band(rshift(c, 8), 255) + 1],
T5[band(rshift(c, 16), 255) + 1],
T4[rshift(c, 24) + 1],
T3[band(d, 255) + 1],
T2[band(rshift(d, 8), 255) + 1],
T1[band(rshift(d, 16), 255) + 1],
T0[rshift(d, 24) + 1]
)
i += 8
end
local e4 = e - 4
while i <= e4 do
c = bxor(c, readu32(buf, i))
c = bxor(T3[band(c, 255) + 1], T2[band(rshift(c, 8), 255) + 1], T1[band(rshift(c, 16), 255) + 1], T0[rshift(c, 24) + 1])
i += 4
end
while i < e do
c = bxor(T0[band(bxor(c, readu8(buf, i)), 255) + 1], rshift(c, 8))
i += 1
end
return bxor(c, 0xFFFFFFFF)
end
-- clamp (offset, length) to the buffer
local function range(buf: buffer, offset: number?, length: number?): (number, number)
local n = buffer.len(buf)
local o = math.clamp(offset or 0, 0, n)
return o, math.clamp(length or (n - o), 0, n - o)
end
local Crc32 = {}
function Crc32.of(buf: buffer, offset: number?, length: number?, crc: number?): number
local o, l = range(buf, offset, length)
return crc32(buf, o, l, crc)
end
function Crc32.string(s: string, crc: number?): number
return crc32(buffer.fromstring(s), 0, #s, crc)
end
-- raw(buf, off, len, crc?): no clamping, for callers that already checked the range (hot paths)
Crc32.raw = crc32
return Crc32
+58
View File
@@ -0,0 +1,58 @@
--!strict
-- core/Err: the error values every decoder / encoder returns (`nil, err`; nothing in the library throws on bad data).
-- An Err is a table { code, message, offset?, format? } that prints as "png: CORRUPT at 0x1234: bad filter type 7".
-- Never throws: --!native modules may require it.
--
-- return nil, Err.new(Err.TRUNCATED, "IDAT runs past the end", r.pos)
-- if err.code == Err.UNSUPPORTED then ... end
local Err = {}
-- codes
Err.TRUNCATED = "TRUNCATED" -- the data ends early
Err.CORRUPT = "CORRUPT" -- the data is malformed (bad magic inside, bad table, out-of-range field)
Err.CHECKSUM = "CHECKSUM" -- a CRC / Adler / hash mismatch
Err.UNSUPPORTED = "UNSUPPORTED" -- valid data using a feature this library does not implement, or no encoder
Err.UNKNOWN_FORMAT = "UNKNOWN_FORMAT" -- no format recognised the data / name
Err.LIMIT = "LIMIT" -- over a size limit (opts.maxPixels, opts.maxBytes, ...)
Err.ARG = "ARG" -- a bad argument (wrong type, out-of-range option)
Err.IO = "IO" -- reading or writing a file failed, or the host has no file system
export type Err = {
code: string,
message: string,
offset: number?,
format: string?,
}
local Meta = {}
Meta.__tostring = function(e: Err): string
local s = if e.format then e.format .. ": " .. e.code else e.code
if e.offset then
s ..= string.format(" at 0x%x", e.offset)
end
return s .. ": " .. e.message
end
-- new(code, message, offset?) -> Err
function Err.new(code: string, message: string, offset: number?): Err
return setmetatable({ code = code, message = message, offset = offset, format = nil :: string? }, Meta) :: any
end
-- is(v) -> true when v is an Err
function Err.is(v: any): boolean
return type(v) == "table" and getmetatable(v) == Meta
end
-- wrap(e, format) -> e with its format set (when not set yet); a string becomes a CORRUPT Err. Used by the API to
-- tag errors with the format name.
function Err.wrap(e: any, format: string?): Err
if not Err.is(e) then
e = Err.new(Err.CORRUPT, tostring(e))
end
if e.format == nil then
e.format = format
end
return e
end
return table.freeze(Err)
+306
View File
@@ -0,0 +1,306 @@
--!strict
--!native
-- core/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders.
--
-- Decoding tables (built by buildLsb / buildMsb) are u32 buffers, indexed by the next P bits of the stream:
-- entry = symbol * 32 + length a code of `length` <= P bits
-- entry = offset * 32 (length 0) a link: index offset + the following S bits (subtable of 2^S entries)
-- entry = 0 no code (incomplete code set): the stream is corrupt
-- so a symbol is one or two table reads. LSB tables (DEFLATE, VP8L) are indexed by bit-reversed codes, MSB tables
-- (JPEG, MPEG) by the code itself. Code lengths are 1..MAXLEN (16), symbols < 2^27.
-- The hot loops (codecs/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a
-- core/Bits reader.
--
-- Encoding: lengths(freqs, maxLen) -> length-limited code lengths; codes(lengths) -> canonical code values.
-- Never throws: bad code sets return -1 / nil.
local Bits = require("@formats/core/Bits")
local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
local bfill = buffer.fill
local MAXLEN = 16
local Huffman = {}
Huffman.MAXLEN = MAXLEN
-- 8-bit reversal
local REV = table.create(256, 0)
for i = 0, 255 do
local r, v = 0, i
for _ = 1, 8 do
r = r * 2 + v % 2
v = v // 2
end
REV[i + 1] = r
end
-- reverse(code, len) -> the low len bits of code reversed (len <= 16)
local function reverse(code: number, len: number): number
return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len)
end
Huffman.reverse = reverse
-- capacity(nsym, P, maxLen) -> the table entries (u32) needed for nsym symbols, primary width P, codes up to maxLen
function Huffman.capacity(nsym: number, P: number, maxLen: number): number
return 2 ^ P + (if maxLen > P then nsym * 2 ^ (maxLen - P) else 0)
end
local count = table.create(MAXLEN + 1, 0)
local nextc = table.create(MAXLEN + 1, 0)
local function build(lens: buffer, off: number, n: number, tab: buffer, P: number, msb: boolean): number
for i = 1, MAXLEN + 1 do
count[i] = 0
end
for s = 0, n - 1 do
local l = readu8(lens, off + s)
if l > MAXLEN then
return -1
end
count[l + 1] += 1
end
count[1] = 0
local left = 1
local maxLen = 0
for l = 1, MAXLEN do
left = left * 2 - count[l + 1]
if left < 0 then
return -1
end
if count[l + 1] > 0 then
maxLen = l
end
end
local code = 0
for l = 1, MAXLEN do
code = (code + count[l]) * 2
nextc[l] = code
end
local psize = lshift(1, P)
bfill(tab, 0, 0, psize * 4)
local S = if maxLen > P then maxLen - P else 0
local ssize = lshift(1, S)
local nextSub = psize
for s = 0, n - 1 do
local l = readu8(lens, off + s)
if l > 0 then
local c = nextc[l]
nextc[l] = c + 1
local entry = s * 32 + l
if l <= P then
if msb then
-- the code is the top l bits of the P-bit index: fill every completion of the low bits
local first = lshift(c, P - l)
local last = first + lshift(1, P - l) - 1
for i = first, last do
writeu32(tab, i * 4, entry)
end
else
local step = lshift(1, l)
local i = reverse(c, l)
while i < psize do
writeu32(tab, i * 4, entry)
i += step
end
end
else
local pre, rest
if msb then
pre = rshift(c, l - P)
rest = band(c, lshift(1, l - P) - 1)
else
local rev = reverse(c, l)
pre = band(rev, psize - 1)
rest = rshift(rev, P)
end
local e = readu32(tab, pre * 4)
local sub
if e == 0 then
sub = nextSub
nextSub += ssize
bfill(tab, sub * 4, 0, ssize * 4)
writeu32(tab, pre * 4, sub * 32)
else
sub = rshift(e, 5)
end
local k = l - P -- bits of the code in the subtable index
if msb then
local first = lshift(rest, S - k)
for i = first, first + lshift(1, S - k) - 1 do
writeu32(tab, (sub + i) * 4, entry)
end
else
local step = lshift(1, k)
local i = rest
while i < ssize do
writeu32(tab, (sub + i) * 4, entry)
i += step
end
end
end
end
end
return S
end
-- buildLsb(lens, off, n, tab, P) -> S: a table for the code lengths lens[off .. off + n - 1] (u8), indexed by the next
-- P bits LSB-first (bit-reversed codes). S = the subtable width (0 when no code is longer than P), -1 = an
-- over-subscribed or invalid code set. tab must hold capacity(n, P, maxLen) u32 entries.
function Huffman.buildLsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number
return build(lens, off, n, tab, P, false)
end
-- buildMsb(lens, off, n, tab, P) -> S: the same, indexed by the next P bits MSB-first
function Huffman.buildMsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number
return build(lens, off, n, tab, P, true)
end
-- decodeLsb(br, tab, P, S) -> symbol, or -1 for an invalid code (br: a core/Bits LSB reader)
function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number
local e = readu32(tab, br:peek(P) * 4)
local l = band(e, 31)
if l == 0 then
if e == 0 then
return -1
end
local idx = br:peek(P + S)
e = readu32(tab, (rshift(e, 5) + rshift(idx, P)) * 4)
l = band(e, 31)
if l == 0 then
return -1
end
end
br:skip(l)
return rshift(e, 5)
end
-- decodeMsb(br, tab, P, S) -> symbol, or -1 (br: a core/Bits MSB reader)
function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number
local e = readu32(tab, br:peek(P) * 4)
local l = band(e, 31)
if l == 0 then
if e == 0 then
return -1
end
local idx = br:peek(P + S)
e = readu32(tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4)
l = band(e, 31)
if l == 0 then
return -1
end
end
br:skip(l)
return rshift(e, 5)
end
-- codes(lengths) -> canonical code values (MSB-first, as written by an MSB writer; reverse() them for LSB streams).
-- lengths: { number } indexed 1..n (symbol + 1), 0 = unused.
function Huffman.codes(lengths: { number }): { number }
local cnt = table.create(MAXLEN + 1, 0)
for _, l in lengths do
if l > 0 then
cnt[l + 1] += 1
end
end
local nxt = table.create(MAXLEN + 1, 0)
local code = 0
for l = 1, MAXLEN do
code = (code + cnt[l]) * 2
nxt[l + 1] = code
end
local out = table.create(#lengths, 0)
for i, l in lengths do
if l > 0 then
out[i] = nxt[l + 1]
nxt[l + 1] += 1
end
end
return out
end
-- lengths(freqs, maxLen) -> code lengths ({ number }, same indexing as freqs), at most maxLen bits, optimal without
-- the limit; over the limit, the JPEG Annex K.3 adjustment. A single used symbol gets length 1.
function Huffman.lengths(freqs: { number }, maxLen: number): { number }
local n = #freqs
local out = table.create(n, 0)
-- leaves sorted by frequency (ties by symbol, for determinism)
local syms = {}
for i = 1, n do
if freqs[i] > 0 then
table.insert(syms, i)
end
end
if #syms == 0 then
return out
end
if #syms == 1 then
out[syms[1]] = 1
return out
end
table.sort(syms, function(a: number, b: number): boolean
if freqs[a] ~= freqs[b] then
return freqs[a] < freqs[b]
end
return a < b
end)
-- two-queue Huffman: leaves (sorted) and internal nodes (created in increasing weight order)
local m = #syms
local weight = table.create(2 * m, 0)
local parent = table.create(2 * m, 0)
for i = 1, m do
weight[i] = freqs[syms[i]]
end
local li, ni, nn = 1, m + 1, m + 1 -- next leaf, next internal node to take, next free node
local function take(): number
if li <= m and (ni >= nn or weight[li] <= weight[ni]) then
li += 1
return li - 1
end
ni += 1
return ni - 1
end
for _ = 1, m - 1 do
local a = take()
local b = take()
weight[nn] = weight[a] + weight[b]
parent[a] = nn
parent[b] = nn
nn += 1
end
-- depths: the root is nn - 1
local depth = table.create(2 * m, 0)
for i = nn - 2, 1, -1 do
depth[i] = depth[parent[i]] + 1
end
-- count codes per length; limit (JPEG K.3: move pairs from the deepest level up)
local bl = table.create(m + maxLen + 2, 0)
local deepest = 0
for i = 1, m do
bl[depth[i]] += 1
deepest = math.max(deepest, depth[i])
end
for l = deepest, maxLen + 1, -1 do
while bl[l] > 0 do
local j = l - 2
while j > 0 and bl[j] == 0 do
j -= 1
end
bl[l] -= 2
bl[l - 1] += 1
bl[j + 1] += 2
bl[j] -= 1
end
end
-- the longest codes go to the least frequent symbols (syms is sorted ascending)
local k = 1
for l = math.min(deepest, maxLen), 1, -1 do
for _ = 1, bl[l] do
out[syms[k]] = l
k += 1
end
end
return out
end
return Huffman
+62
View File
@@ -0,0 +1,62 @@
--!strict
-- core/Input: turns what the caller passed (a buffer, a string of bytes, or a file path) into a buffer, reading files
-- through the host adapter the API passes in (core never requires host itself).
--
-- local buf, err, name = Input.resolve(src, opts, host)
--
-- A string is a path when opts.path is true, or when the host has a file system and the string looks like a path
-- (under 4 KB, no NUL / newline) and the file exists; otherwise it is the data itself (opts.data = true forces that).
-- name: the path (for the extension fallback) or opts.name. Never throws.
local Err = require("@formats/core/Err")
local Input = {}
export type HostLike = {
hasFiles: boolean,
readFile: (path: string) -> (buffer?, Err.Err?),
exists: (path: string) -> boolean,
}
-- looksLikePath(s) -> true for short strings without NUL / newline bytes
function Input.looksLikePath(s: string): boolean
return #s > 0 and #s < 4096 and not string.find(s, "\0", 1, true) and not string.find(s, "[\n\r]")
end
-- resolve(src, opts?, host?) -> buffer, nil, name? | nil, Err
function Input.resolve(src: any, opts: any?, host: HostLike?): (buffer?, Err.Err?, string?)
local o = opts or {}
local t = type(src)
if t == "buffer" then
return src, nil, o.name
elseif t == "string" then
local isPath = false
if o.path == true then
isPath = true
elseif o.data ~= true and host and host.hasFiles and Input.looksLikePath(src) then
isPath = host.exists(src)
end
if isPath then
if not host then
return nil, Err.new(Err.IO, "no host to read " .. src), nil
end
local b, err = host.readFile(src)
if not b then
return nil, err, nil
end
return b, nil, src
end
return buffer.fromstring(src), nil, o.name
end
return nil, Err.new(Err.ARG, "expected a buffer, a string or a path, got " .. typeof(src)), nil
end
-- extension(name) -> the lower-case extension without the dot ("png"), or nil
function Input.extension(name: string?): string?
if not name then
return nil
end
local ext = string.match(name, "%.([%w_]+)$")
return if ext then string.lower(ext) else nil
end
return Input
+149
View File
@@ -0,0 +1,149 @@
--!strict
-- host/Love: LÖVE 11+. Files through love.filesystem (the game folder and the save directory), falling back to io for
-- paths outside them; converts the standard types to LÖVE objects:
-- host.toImageData(img) -> love ImageData (rgba8)
-- host.fromImageData(imageData) -> Image (rgba8)
-- host.toSoundData(audio) -> love SoundData (an Audio, or a Decoder decoded to the end; 16-bit)
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Host = {}
Host.name = "love"
Host.hasFiles = true
local function love(): any
return (_G :: any).love
end
local function io(): any
return (_G :: any).io
end
-- the FFI, when the build runs on LuaJIT (always, under LÖVE); called through _G so the build leaves it alone
local function ffi(): any
local req = (_G :: any).require
local ok, m = pcall(req, "ffi")
return if ok then m else nil
end
function Host.readFile(path: string): (buffer?, Err.Err?)
local fs = love().filesystem
if fs.getInfo(path, "file") then
local s, msg = fs.read(path)
if type(s) ~= "string" then
return nil, Err.new(Err.IO, "cannot read " .. path .. ": " .. tostring(msg))
end
return buffer.fromstring(s)
end
local f, msg = io().open(path, "rb")
if not f then
return nil, Err.new(Err.IO, "cannot open " .. path .. ": " .. tostring(msg))
end
local s = f:read("*a")
f:close()
return buffer.fromstring(s)
end
-- writeFile: relative paths go to the save directory (love.filesystem.write), absolute ones through io
function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?)
local s = buffer.tostring(data)
if string.sub(path, 1, 1) ~= "/" and not string.find(path, "^%a:[/\\]") then
local ok, msg = love().filesystem.write(path, s)
if not ok then
return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(msg))
end
return true
end
local f, msg = io().open(path, "wb")
if not f then
return false, Err.new(Err.IO, "cannot create " .. path .. ": " .. tostring(msg))
end
f:write(s)
f:close()
return true
end
function Host.exists(path: string): boolean
if love().filesystem.getInfo(path, "file") then
return true
end
local f = io().open(path, "rb")
if f then
f:close()
return true
end
return false
end
-- toImageData(img) -> ImageData | nil, Err
function Host.toImageData(img: any): (any, Err.Err?)
if img.format ~= "rgba8" then
return nil, Err.new(Err.ARG, "toImageData: needs rgba8 pixels, got " .. tostring(img.format))
end
local n = img.width * img.height * 4
local F = ffi()
local B = buffer :: any
if F and B.toffi then
local id = love().image.newImageData(img.width, img.height, "rgba8")
F.copy(id:getFFIPointer(), B.toffi(img.pixels), n)
return id
end
local bytes = love().data.newByteData(buffer.readstring(img.pixels, 0, n))
return love().image.newImageData(img.width, img.height, "rgba8", bytes)
end
-- fromImageData(imageData) -> Image (rgba8 copy)
function Host.fromImageData(id: any): Types.Image
local w, h = id:getDimensions()
local img = Types.Image.new(w, h, "rgba8")
local F = ffi()
local B = buffer :: any
if F and B.toffi and id:getFormat() == "rgba8" then
F.copy(B.toffi(img.pixels), id:getFFIPointer(), w * h * 4)
return img
end
local s = id:getString()
buffer.writestring(img.pixels, 0, s, math.min(#s, w * h * 4))
return img
end
-- toSoundData(audio) -> SoundData (16-bit). audio: an Audio, or a Decoder (decoded to the end).
function Host.toSoundData(a: any): (any, Err.Err?)
local samples, frames, channels, rate = a.samples, a.frames, a.channels, a.sampleRate
if samples == nil then
-- a Decoder: read everything
local parts, total = {}, 0
while true do
local out, n = a:read(65536)
if n == 0 then
break
end
local copy = buffer.create(n * channels * 4)
buffer.copy(copy, 0, out, 0, n * channels * 4)
table.insert(parts, copy)
total += n
end
samples = buffer.create(total * channels * 4)
local o = 0
for _, p in parts do
buffer.copy(samples, o, p)
o += buffer.len(p)
end
frames = total
end
local sd = love().sound.newSoundData(math.max(frames, 1), rate, 16, channels)
local count = frames * channels
local F = ffi()
if F then
local p = F.cast("int16_t*", sd:getFFIPointer())
for i = 0, count - 1 do
local v = math.clamp(buffer.readf32(samples, i * 4), -1, 1)
p[i] = math.floor(v * 32767 + 0.5)
end
else
for i = 0, count - 1 do
sd:setSample(i, math.clamp(buffer.readf32(samples, i * 4), -1, 1))
end
end
return sd
end
return Host
+48
View File
@@ -0,0 +1,48 @@
--!strict
-- host/LuaJIT: plain LuaJIT (or any Lua with io): files through io.open.
local Err = require("@formats/core/Err")
local Host = {}
Host.name = "luajit"
Host.hasFiles = true
local function io(): any
return (_G :: any).io
end
function Host.readFile(path: string): (buffer?, Err.Err?)
local f, msg = io().open(path, "rb")
if not f then
return nil, Err.new(Err.IO, "cannot open " .. path .. ": " .. tostring(msg))
end
local s = f:read("*a")
f:close()
if type(s) ~= "string" then
return nil, Err.new(Err.IO, "cannot read " .. path)
end
return buffer.fromstring(s), nil
end
function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?)
local f, msg = io().open(path, "wb")
if not f then
return false, Err.new(Err.IO, "cannot create " .. path .. ": " .. tostring(msg))
end
local ok, werr = f:write(buffer.tostring(data))
f:close()
if not ok then
return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(werr))
end
return true, nil
end
function Host.exists(path: string): boolean
local f = io().open(path, "rb")
if f then
f:close()
return true
end
return false
end
return Host
+21
View File
@@ -0,0 +1,21 @@
--!strict
-- host/Luau: the Luau CLI (and any embedding without io): no file system. Sources are buffers or strings.
local Err = require("@formats/core/Err")
local Host = {}
Host.name = "luau"
Host.hasFiles = false
function Host.readFile(path: string): (buffer?, Err.Err?)
return nil, Err.new(Err.IO, "no file system on this host (luau): pass a buffer or a string, not the path " .. path)
end
function Host.writeFile(path: string, _data: buffer): (boolean, Err.Err?)
return false, Err.new(Err.IO, "no file system on this host (luau): cannot write " .. path)
end
function Host.exists(_path: string): boolean
return false
end
return Host
+40
View File
@@ -0,0 +1,40 @@
--!strict
-- host/Roblox: no file system (sources are buffers or strings, e.g. from HttpService or an asset); converts the
-- standard types to engine objects:
-- host.toEditableImage(img) -> EditableImage (rgba8; other formats are converted by the caller first)
local Err = require("@formats/core/Err")
local Host = {}
Host.name = "roblox"
Host.hasFiles = false
function Host.readFile(path: string): (buffer?, Err.Err?)
return nil, Err.new(Err.IO, "Roblox has no file system: pass a buffer or a string, not the path " .. path)
end
function Host.writeFile(path: string, _data: buffer): (boolean, Err.Err?)
return false, Err.new(Err.IO, "Roblox has no file system: cannot write " .. path .. " (use F.save(value) for a buffer)")
end
function Host.exists(_path: string): boolean
return false
end
-- toEditableImage(img) -> EditableImage | nil, Err. img.format must be "rgba8".
function Host.toEditableImage(img: any): (any, Err.Err?)
if img.format ~= "rgba8" then
return nil, Err.new(Err.ARG, "toEditableImage: needs rgba8 pixels, got " .. tostring(img.format))
end
local AssetService = (game :: any):GetService("AssetService")
local size = Vector2.new(img.width, img.height)
local ok, ei = pcall(function()
return AssetService:CreateEditableImage({ Size = size })
end)
if not ok or not ei then
return nil, Err.new(Err.IO, "CreateEditableImage failed: " .. tostring(ei))
end
ei:WritePixelsBuffer(Vector2.zero, size, img.pixels)
return ei
end
return Host
+43
View File
@@ -0,0 +1,43 @@
--!strict
-- host: the runtime adapter, detected once at load time. Roblox (no file system; toEditableImage), LÖVE
-- (love.filesystem + io; toImageData / toSoundData), plain LuaJIT (io), the Luau CLI (no file system).
--
-- local host = require("@formats/host")
-- print(host.name) -- "roblox" | "love" | "luajit" | "luau"
-- local buf, err = host.readFile("a.png") -- every host has readFile / writeFile / exists (failing with Err.IO
-- -- where there is no file system)
local Err = require("@formats/core/Err")
export type Host = {
name: string,
hasFiles: boolean,
readFile: (path: string) -> (buffer?, Err.Err?),
writeFile: (path: string, data: buffer) -> (boolean, Err.Err?),
exists: (path: string) -> boolean,
[string]: any,
}
local G = _G :: any
local name
if typeof(game) == "Instance" then
name = "roblox"
elseif G.love ~= nil and type(G.love) == "table" and G.love.filesystem ~= nil then
name = "love"
elseif G.jit ~= nil or G.io ~= nil then
name = "luajit"
else
name = "luau"
end
local host: Host
if name == "roblox" then
host = require("@formats/host/Roblox")
elseif name == "love" then
host = require("@formats/host/Love")
elseif name == "luajit" then
host = require("@formats/host/LuaJIT")
else
host = require("@formats/host/Luau")
end
local _ = Err
return host
+253
View File
@@ -0,0 +1,253 @@
--!strict
--!native
--!optimize 2
-- image/png/Decode: the PNG pixel stage. Undo the per-row filters (none / sub / up / average / Paeth) in place in the
-- inflated image data, then expand every colour type and bit depth to RGBA8, for one image or the 7 Adam7 passes.
-- Absorbed from png-luau src/Png/Decode.luau (same author).
--
-- The caller (init) has validated the header and checked that the data holds at least the expected number of
-- bytes, so every index here is in range. A bad filter type returns false, message: nothing in this module throws.
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local bcopy = buffer.copy
local Decode = {}
-- Adam7: x0, y0, dx, dy per pass
local PASSES = {
{ 0, 0, 8, 8 },
{ 4, 0, 8, 8 },
{ 0, 4, 4, 8 },
{ 2, 0, 4, 4 },
{ 0, 2, 2, 4 },
{ 1, 0, 2, 2 },
{ 0, 1, 1, 2 },
}
Decode.PASSES = PASSES
local CHANNELS = { [0] = 1, [2] = 3, [3] = 1, [4] = 2, [6] = 4 }
Decode.CHANNELS = CHANNELS
-- bytes per row (without the filter byte) for a pass width
function Decode.rowBytes(pw: number, channels: number, depth: number): number
return (pw * channels * depth + 7) // 8
end
-- Unfilter ph rows of rb bytes starting at raw[p] (each row: a filter byte, then rb bytes). bpp: bytes per
-- complete pixel (at least 1). Returns true, or false + the bad filter type.
local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number): (boolean, number)
local stride = rb + 1
for r = 0, ph - 1 do
local f = readu8(raw, p)
local cur = p + 1
if f == 0 then
-- none
elseif f == 1 then
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp))
end
elseif f == 2 then
if r > 0 then
local i = cur
local e4 = cur + rb - 4
while i <= e4 do
-- four bytes at once: add without carries between the byte lanes
local x, y = readu32(raw, i), readu32(raw, i - stride)
local lo = band(x, 0x7F7F7F7F) + band(y, 0x7F7F7F7F)
writeu32(raw, i, bit32.bxor(lo, band(bit32.bxor(x, y), 0x80808080)))
i += 4
end
while i < cur + rb do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride))
i += 1
end
end
elseif f == 3 then
if r > 0 then
for i = cur, cur + bpp - 1 do
writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - stride), 1))
end
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp) + readu8(raw, i - stride), 1))
end
else
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp), 1))
end
end
elseif f == 4 then
if r > 0 then
-- the first pixel: a = c = 0, so Paeth picks b
for i = cur, cur + bpp - 1 do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride))
end
for i = cur + bpp, cur + rb - 1 do
local a = readu8(raw, i - bpp)
local b = readu8(raw, i - stride)
local c = readu8(raw, i - stride - bpp)
local pa = math.abs(b - c)
local pb = math.abs(a - c)
local pc = math.abs(a + b - c - c)
local v
if pa <= pb and pa <= pc then
v = a
elseif pb <= pc then
v = b
else
v = c
end
writeu8(raw, i, readu8(raw, i) + v)
end
else
-- no previous row: Paeth is sub
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp))
end
end
else
return false, f
end
p += stride
end
return true, 0
end
-- Expand one unfiltered row (pw pixels at raw[ro]) to RGBA8 at out[oo], oo stepping by ostep bytes.
-- pal: 256 RGBA8 entries (index -> u32 little-endian RGBA). tr: the tRNS key for grey / RGB (-1 if none),
-- as a sample value (grey) or r * 2^32 + g * 2^16 + b (RGB), at the image's bit depth.
local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: number, ostep: number, ct: number, depth: number, pal: buffer, tr: number)
if ct == 6 then
if depth == 8 then
if ostep == 4 then
bcopy(out, oo, raw, ro, pw * 4)
else
for x = 0, pw - 1 do
writeu32(out, oo + x * ostep, readu32(raw, ro + x * 4))
end
end
else
for x = 0, pw - 1 do
local s = ro + x * 8
local o = oo + x * ostep
writeu8(out, o, readu8(raw, s))
writeu8(out, o + 1, readu8(raw, s + 2))
writeu8(out, o + 2, readu8(raw, s + 4))
writeu8(out, o + 3, readu8(raw, s + 6))
end
end
elseif ct == 2 then
if depth == 8 then
for x = 0, pw - 1 do
local s = ro + x * 3
local r, g, b = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2)
local a = 255
if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then
a = 0
end
writeu32(out, oo + x * ostep, r + g * 256 + b * 65536 + a * 16777216)
end
else
for x = 0, pw - 1 do
local s = ro + x * 6
local r = readu8(raw, s) * 256 + readu8(raw, s + 1)
local g = readu8(raw, s + 2) * 256 + readu8(raw, s + 3)
local b = readu8(raw, s + 4) * 256 + readu8(raw, s + 5)
local a = 255
if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then
a = 0
end
writeu32(out, oo + x * ostep, rshift(r, 8) + band(g, 0xFF00) + lshift(rshift(b, 8), 16) + a * 16777216)
end
end
elseif ct == 3 then
if depth == 8 then
for x = 0, pw - 1 do
writeu32(out, oo + x * ostep, readu32(pal, readu8(raw, ro + x) * 4))
end
else
local per = 8 // depth
local mask = lshift(1, depth) - 1
for x = 0, pw - 1 do
local byte = readu8(raw, ro + x // per)
local idx = band(rshift(byte, 8 - depth - (x % per) * depth), mask)
writeu32(out, oo + x * ostep, readu32(pal, idx * 4))
end
end
elseif ct == 0 then
if depth == 8 then
for x = 0, pw - 1 do
local v = readu8(raw, ro + x)
local a = if v == tr then 0 else 255
writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216)
end
elseif depth == 16 then
for x = 0, pw - 1 do
local hi = readu8(raw, ro + x * 2)
local v = hi * 256 + readu8(raw, ro + x * 2 + 1)
local a = if v == tr then 0 else 255
writeu32(out, oo + x * ostep, hi * 0x10101 + a * 16777216)
end
else
local per = 8 // depth
local mask = lshift(1, depth) - 1
local scale = 255 // mask
for x = 0, pw - 1 do
local byte = readu8(raw, ro + x // per)
local v = band(rshift(byte, 8 - depth - (x % per) * depth), mask)
local a = if v == tr then 0 else 255
writeu32(out, oo + x * ostep, v * scale * 0x10101 + a * 16777216)
end
end
else -- ct == 4: grey + alpha
if depth == 8 then
for x = 0, pw - 1 do
local v, a = readu8(raw, ro + x * 2), readu8(raw, ro + x * 2 + 1)
writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216)
end
else
for x = 0, pw - 1 do
local v, a = readu8(raw, ro + x * 4), readu8(raw, ro + x * 4 + 2)
writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216)
end
end
end
end
-- Decode the inflated data raw (at least the expected size) of a w x h image to out (w * h * 4 bytes, RGBA8).
-- Returns true, or false + message.
function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): (boolean, string?)
local channels = CHANNELS[ct]
local bpp = math.max(1, (channels * depth) // 8)
local p = 0
if interlace == 0 then
local rb = Decode.rowBytes(w, channels, depth)
local ok, f = unfilter(raw, 0, h, rb, bpp)
if not ok then
return false, "bad filter type " .. f
end
for y = 0, h - 1 do
convert(raw, y * (rb + 1) + 1, w, out, y * w * 4, 4, ct, depth, pal, tr)
end
return true, nil
end
for _, pass in PASSES do
local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4]
local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0
local ph = if h > y0 then (h - y0 + dy - 1) // dy else 0
if pw > 0 and ph > 0 then
local rb = Decode.rowBytes(pw, channels, depth)
local ok, f = unfilter(raw, p, ph, rb, bpp)
if not ok then
return false, "bad filter type " .. f
end
for r = 0, ph - 1 do
local y = y0 + r * dy
convert(raw, p + r * (rb + 1) + 1, pw, out, (y * w + x0) * 4, dx * 4, ct, depth, pal, tr)
end
p += ph * (rb + 1)
end
end
return true, nil
end
return Decode
+162
View File
@@ -0,0 +1,162 @@
--!strict
--!native
--!optimize 2
-- image/png/Encode: the PNG encoder's pixel stage. Picks the smallest lossless colour type for rgba8 pixels and
-- writes the filtered scanlines (a filter byte + the row), choosing each row's filter by the minimum sum of absolute
-- signed residuals (the libpng heuristic). Nothing here throws: the caller (init) validated the image.
local readu8, writeu8 = buffer.readu8, buffer.writeu8
local bcreate, bcopy = buffer.create, buffer.copy
local Encode = {}
local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 }
-- pickColorType(px, w, h) -> "rgba" | "rgb" | "graya" | "gray"
function Encode.pickColorType(px: buffer, w: number, h: number): string
local opaque, gray = true, true
for i = 0, w * h - 1 do
local o = i * 4
local r, g, b, a = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2), readu8(px, o + 3)
if a ~= 255 then
opaque = false
end
if r ~= g or g ~= b then
gray = false
end
if not opaque and not gray then
return "rgba"
end
end
if gray then
return if opaque then "gray" else "graya"
end
return "rgb"
end
-- convert rgba8 to the colour type's packed rows (no filter bytes)
local function pack(px: buffer, w: number, h: number, ct: number): buffer
local ch = CHANNELS[ct]
if ch == 4 then
return px
end
local out = bcreate(w * h * ch)
local n = w * h
if ct == 2 then
for i = 0, n - 1 do
bcopy(out, i * 3, px, i * 4, 3)
end
elseif ct == 0 then
for i = 0, n - 1 do
writeu8(out, i, readu8(px, i * 4))
end
else -- graya
for i = 0, n - 1 do
writeu8(out, i * 2, readu8(px, i * 4))
writeu8(out, i * 2 + 1, readu8(px, i * 4 + 3))
end
end
return out
end
local function paeth(a: number, b: number, c: number): number
local pa = math.abs(b - c)
local pb = math.abs(a - c)
local pc = math.abs(a + b - c - c)
if pa <= pb and pa <= pc then
return a
elseif pb <= pc then
return b
end
return c
end
-- the five filter costs (sums of |signed residual|) of the row at s (rb bytes; previous row at s - rb unless first);
-- the arithmetic is inlined: this runs for every byte
local function costs(src: buffer, s: number, rb: number, bpp: number, first: boolean): (number, number, number, number, number)
local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0
local p = s - rb
for i = 0, rb - 1 do
local x = readu8(src, s + i)
local a = if i >= bpp then readu8(src, s + i - bpp) else 0
local b, c = 0, 0
if not first then
b = readu8(src, p + i)
if i >= bpp then
c = readu8(src, p + i - bpp)
end
end
local d = if x < 128 then x else 256 - x
c0 += d
d = (x - a) % 256
c1 += if d < 128 then d else 256 - d
d = (x - b) % 256
c2 += if d < 128 then d else 256 - d
d = (x - (a + b) // 2) % 256
c3 += if d < 128 then d else 256 - d
local pa, pb, pc = math.abs(b - c), math.abs(a - c), math.abs(a + b - c - c)
local pr = if pa <= pb and pa <= pc then a elseif pb <= pc then b else c
d = (x - pr) % 256
c4 += if d < 128 then d else 256 - d
end
return c0, c1, c2, c3, c4
end
-- write the row at s filtered with f to out[o + 1 ..] (out[o] = f)
local function apply(src: buffer, s: number, rb: number, bpp: number, first: boolean, f: number, out: buffer, o: number)
writeu8(out, o, f)
o += 1
if f == 0 or (f == 2 and first) then
bcopy(out, o, src, s, rb)
return
end
local p = s - rb
for i = 0, rb - 1 do
local x = readu8(src, s + i)
local a = if i >= bpp then readu8(src, s + i - bpp) else 0
local pred
if f == 1 then
pred = a
elseif f == 2 then
pred = readu8(src, p + i)
elseif f == 3 then
pred = (a + (if first then 0 else readu8(src, p + i))) // 2
elseif first then
pred = a
else
local c = if i >= bpp then readu8(src, p + i - bpp) else 0
pred = paeth(a, readu8(src, p + i), c)
end
writeu8(out, o + i, x - pred)
end
end
-- filter(px, w, h, ct) -> the filtered scanlines (h * (1 + rowBytes)); each row's filter: the minimum sum of
-- |signed residuals| (the libpng heuristic)
function Encode.filter(px: buffer, w: number, h: number, ct: number): buffer
local ch = CHANNELS[ct]
local src = pack(px, w, h, ct)
local rb = w * ch
local out = bcreate(h * (rb + 1))
for y = 0, h - 1 do
local s = y * rb
local first = y == 0
local c0, c1, c2, c3, c4 = costs(src, s, rb, ch, first)
local best, bc = 0, c0
if c1 < bc then
best, bc = 1, c1
end
if c2 < bc then
best, bc = 2, c2
end
if c3 < bc then
best, bc = 3, c3
end
if c4 < bc then
best = 4
end
apply(src, s, rb, ch, first, best, out, y * (rb + 1))
end
return out
end
return Encode
+306
View File
@@ -0,0 +1,306 @@
--!strict
-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.). Absorbed from png-luau 1.0.0 (same author) + a new encoder.
-- Supports: decode of every colour type (grey, RGB, palette, grey + alpha, RGBA) at every bit depth (1, 2, 4, 8, 16),
-- PLTE / tRNS transparency, the five filters, Adam7, tEXt; encode of rgba8 to RGBA / RGB / grey / grey + alpha
-- (chosen automatically) with adaptive filters. Decodes to rgba8 (16-bit samples keep their high byte).
-- Not supported: APNG animation (the default image is decoded), colour management (gAMA / cHRM / sRGB / iCCP are
-- ignored; iCCP is kept raw-compressed in meta.iccCompressed), palette / 16-bit / interlaced output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Deflate = require("@formats/codecs/Deflate")
local Types = require("@formats/Types")
local Decode = require("@formats/image/png/Decode")
local Encode = require("@formats/image/png/Encode")
-- ------------------------------------------------------------------------------------------------ contract
local Png = {
name = "png",
category = "image",
extensions = { "png", "apng" },
mime = { "image/png", "image/apng" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" },
caps = { decode = true, encode = true, animation = false, alpha = true, depths = { 1, 2, 4, 8, 16 } },
}
export type DecodeOptions = {
checkCrc: boolean?, -- verify every chunk's CRC-32 (default false)
maxPixels: number?, -- refuse larger images (default 2^26 = 64 Mpixel, a 256 MB RGBA buffer)
}
export type EncodeOptions = {
level: number?, -- deflate level 0..9 (default 6)
colorType: ("auto" | "rgba" | "rgb" | "gray" | "graya")?, -- default "auto": the smallest lossless one
}
-- ------------------------------------------------------------------------------------------------ constants
local SIGNATURE = "\137PNG\r\n\26\n"
local VALID = {
[0] = { [1] = true, [2] = true, [4] = true, [8] = true, [16] = true },
[2] = { [8] = true, [16] = true },
[3] = { [1] = true, [2] = true, [4] = true, [8] = true },
[4] = { [8] = true, [16] = true },
[6] = { [8] = true, [16] = true },
}
local COLOR_NAMES = { [0] = "gray", [2] = "rgb", [3] = "palette", [4] = "graya", [6] = "rgba" }
local readu8, readu32 = buffer.readu8, buffer.readu32
local function be32(b: buffer, o: number): number
return bit32.byteswap(readu32(b, o))
end
-- ------------------------------------------------------------------------------------------------ sniff
function Png.sniff(r: Bytes.Reader): number
return if r:peek(8) == SIGNATURE then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Header = { width: number, height: number, bitDepth: number, colorType: number, interlace: number }
-- the IHDR at r's start: Header | nil, Err
local function header(r: Bytes.Reader): (Header?, Err.Err?)
local b, o, n = r.buf, r.base, r.limit - r.base
if n < 8 or readu8(b, o) ~= 137 or buffer.readstring(b, o, 8) ~= SIGNATURE then
return nil, Err.new(Err.CORRUPT, "bad signature", o)
end
if n < 33 or buffer.readstring(b, o + 12, 4) ~= "IHDR" or be32(b, o + 8) ~= 13 then
return nil, Err.new(Err.CORRUPT, "missing IHDR", o + 8)
end
local h = {
width = be32(b, o + 16),
height = be32(b, o + 20),
bitDepth = readu8(b, o + 24),
colorType = readu8(b, o + 25),
interlace = readu8(b, o + 28),
}
if h.width == 0 or h.height == 0 or h.width >= 2 ^ 31 or h.height >= 2 ^ 31 then
return nil, Err.new(Err.CORRUPT, "bad image size", o + 16)
end
local depths = VALID[h.colorType]
if not depths then
return nil, Err.new(Err.CORRUPT, "bad colour type " .. h.colorType, o + 25)
end
if not depths[h.bitDepth] then
return nil, Err.new(Err.CORRUPT, string.format("bad bit depth %d for colour type %d", h.bitDepth, h.colorType), o + 24)
end
if readu8(b, o + 26) ~= 0 or readu8(b, o + 27) ~= 0 or h.interlace > 1 then
return nil, Err.new(Err.UNSUPPORTED, "unknown compression, filter or interlace method", o + 26)
end
return h, nil
end
-- info(r) -> { width, height, bitDepth, colorType, interlace } | nil, Err (reads only the header)
function Png.info(r: Bytes.Reader): (Header?, Err.Err?)
return header(r)
end
function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local checkCrc = opts and opts.checkCrc or false
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local h, herr = header(r)
if not h then
return nil, herr
end
local w, ht, depth, ct = h.width, h.height, h.bitDepth, h.colorType
if w * ht > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels))
end
local b, n = r.buf, r.limit
-- chunks
local pal = buffer.create(1024)
for i = 0, 255 do
buffer.writeu32(pal, i * 4, 0xFF000000) -- out-of-range indexes: opaque black
end
local palCount = 0
local tr = -1
local idat: { { number } } = {}
local idatLen = 0
local text: { [string]: string } = {}
local iccCompressed: buffer? = nil
local p = r.base + 8
local first = true
while p + 12 <= n do
local len = be32(b, p)
local typ = buffer.readstring(b, p + 4, 4)
if len > n - p - 12 then
return nil, Err.new(Err.TRUNCATED, "chunk " .. typ .. " runs past the end", p)
end
local d = p + 8
if checkCrc then
local want = be32(b, d + len)
if Crc32.raw(b, p + 4, len + 4) ~= want then
return nil, Err.new(Err.CHECKSUM, "CRC mismatch in chunk " .. typ, d + len)
end
end
if first and typ ~= "IHDR" then
return nil, Err.new(Err.CORRUPT, "IHDR is not the first chunk", p)
end
first = false
if typ == "PLTE" then
if len % 3 ~= 0 or len > 768 or len == 0 then
return nil, Err.new(Err.CORRUPT, "bad PLTE length", p)
end
palCount = len // 3
for i = 0, palCount - 1 do
local q = d + i * 3
buffer.writeu32(pal, i * 4, readu8(b, q) + readu8(b, q + 1) * 256 + readu8(b, q + 2) * 65536 + 0xFF000000)
end
elseif typ == "tRNS" then
if ct == 3 then
for i = 0, math.min(len, 256) - 1 do
buffer.writeu8(pal, i * 4 + 3, readu8(b, d + i))
end
elseif ct == 0 and len >= 2 then
tr = readu8(b, d) * 256 + readu8(b, d + 1)
elseif ct == 2 and len >= 6 then
local function u16(q: number): number
return readu8(b, d + q) * 256 + readu8(b, d + q + 1)
end
tr = u16(0) * 4294967296 + u16(2) * 65536 + u16(4)
end
elseif typ == "IDAT" then
table.insert(idat, { d, len })
idatLen += len
elseif typ == "tEXt" then
local s = buffer.readstring(b, d, len)
local z = string.find(s, "\0", 1, true)
if z then
text[string.sub(s, 1, z - 1)] = string.sub(s, z + 1)
end
elseif typ == "iCCP" then
local cb = buffer.create(len)
buffer.copy(cb, 0, b, d, len)
iccCompressed = cb
elseif typ == "IEND" then
break -- a missing IEND is tolerated (truncated tail after the data)
elseif bit32.band(readu8(b, p + 4), 0x20) == 0 and typ ~= "IHDR" then
return nil, Err.new(Err.UNSUPPORTED, "unknown critical chunk " .. typ, p)
end
p = d + len + 4
end
if #idat == 0 then
return nil, Err.new(Err.TRUNCATED, "no image data", p)
end
if ct == 3 and palCount == 0 then
return nil, Err.new(Err.CORRUPT, "palette image without PLTE")
end
-- the inflated size: every (pass) row has a filter byte
local channels = Decode.CHANNELS[ct]
local expected = 0
if h.interlace == 0 then
expected = ht * (Decode.rowBytes(w, channels, depth) + 1)
else
for _, pass in Decode.PASSES do
local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4]
local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0
local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0
if pw > 0 and ph > 0 then
expected += ph * (Decode.rowBytes(pw, channels, depth) + 1)
end
end
end
local z: buffer
if #idat == 1 then
z = b
else
z = buffer.create(idatLen)
local w0 = 0
for _, c in idat do
buffer.copy(z, w0, b, c[1], c[2])
w0 += c[2]
end
end
local zo, zl = if #idat == 1 then idat[1][1] else 0, idatLen
local raw, zerr = Deflate.zlib(z, zo, zl, expected)
if not raw then
-- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows
local loose = Deflate.zlib(z, zo, zl)
if not loose or buffer.len(loose) < expected then
return nil, zerr
end
raw = loose
end
local img = Types.Image.new(w, ht, "rgba8")
local ok, derr = Decode.run(raw :: buffer, w, ht, depth, ct, h.interlace, pal, tr, img.pixels)
if not ok then
return nil, Err.new(Err.CORRUPT, tostring(derr))
end
if ct == 3 then
local palette: { { number } } = {}
for i = 0, palCount - 1 do
palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) }
end
img.meta.palette = palette
end
if next(text) then
img.meta.text = text
end
img.meta.iccCompressed = iccCompressed
img.meta.source = { format = "png", bitDepth = depth, colorType = COLOR_NAMES[ct], interlace = h.interlace }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 }
function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "png encode: needs an rgba8 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 or buffer.len(img.pixels) < w * h * 4 then
return nil, Err.new(Err.ARG, "png encode: bad image size or pixel buffer")
end
local level = opts and opts.level or 6
if type(level) ~= "number" or level < 0 or level > 9 then
return nil, Err.new(Err.ARG, "png encode: level must be 0..9")
end
local want = opts and opts.colorType or "auto"
local ctName: string = want
if want == "auto" then
ctName = Encode.pickColorType(img.pixels, w, h)
end
local ct = CT_CODES[ctName]
if ct == nil then
return nil, Err.new(Err.ARG, "png encode: unknown colorType " .. tostring(want))
end
local raw = Encode.filter(img.pixels, w, h, ct)
local z = Deflate.zlibCompress(raw, { level = level }) :: buffer
local out = Bytes.writer(buffer.len(z) + 128)
local function chunk(typ: string, data: buffer?)
local len = if data then buffer.len(data) else 0
out:u32be(len)
local start = out:tell()
out:string(typ)
if data then
out:bytes(data)
end
out:u32be(Crc32.raw(out.buf, start, len + 4))
end
out:string(SIGNATURE)
local ihdr = Bytes.writer(13)
ihdr:u32be(w)
ihdr:u32be(h)
ihdr:u8(8)
ihdr:u8(ct)
ihdr:u8(0)
ihdr:u8(0)
ihdr:u8(0)
chunk("IHDR", ihdr:finish())
if img.meta and img.meta.text then
for k, v in img.meta.text do
local t = Bytes.writer()
t:string(k)
t:u8(0)
t:string(v)
chunk("tEXt", t:finish())
end
end
chunk("IDAT", z)
chunk("IEND", nil)
return out:finish(), nil
end
return Png
+378
View File
@@ -0,0 +1,378 @@
--!strict
-- Formats: read, write and convert file formats in pure Luau, on Roblox and on LuaJIT / LÖVE (through tools/build.py).
-- Every format of a category maps onto one standard type (src/Formats/Types.luau): a PNG and a WebP both load as an
-- Image. Formats are found through the generated Registry: by content (each format's sniff), then by extension.
--
-- local F = require(Formats) -- Roblox: the ModuleScript; LuaJIT: require("formats"); luau: "@formats"
-- local img, err = F.load(src, opts?) -- src: buffer | string | path (hosts with files); err: core/Err
-- local img = F.image.load(src) -- the same, restricted to one category (F.audio, F.model, ...)
-- local dec = F.audio.open(src) -- streaming decoders (audio / video)
-- local buf = F.save(img, nil, { format = "png" }) -- a buffer; without format: the source format
-- F.save(img, "out.png") -- a file (the format from the extension), on hosts with files
-- local s = F.saveString(img, { format = "png" })
-- local buf = F.convert(src, "png", opts?) -- load + save
-- F.formats() -- the capability list (also docs/FORMATS.md)
--
-- Never throws on bad data or bad arguments: every function returns nil, Err (Err.code, Err.message, tostring(err)).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Input = require("@formats/core/Input")
local Types = require("@formats/Types")
local Registry = require("@formats/Registry")
local host = require("@formats/host")
local F = {}
F.version = "0.1.0"
F.Err = Err
F.Types = Types
F.Bytes = Bytes
F.null = Types.null
F.host = host
F.plugins = {} :: { [string]: any } -- injected optional dependencies (plugins.brep for cad/step)
-- value.kind -> category
local KIND_CATEGORY: { [string]: string } = {
image = "image",
audio = "audio",
scene = "model",
cad = "cad",
font = "font",
archive = "archive",
vector = "vector",
tilemap = "vector",
layered = "layered",
subtitles = "subtitle",
music = "music",
midi = "music",
playlist = "playlist",
}
-- ------------------------------------------------------------------------------------------------ registry access
local loaded: { [string]: any } = {}
local function module(entry: Registry.Entry): (any, Err.Err?)
local m = loaded[entry.path]
if m then
return m
end
local ok, res = pcall(entry.load)
if not ok then
return nil, Err.new(Err.UNSUPPORTED, "format " .. entry.name .. " failed to load: " .. tostring(res))
end
loaded[entry.path] = res
return res
end
local function inCategory(entry: Registry.Entry, category: string?): boolean
return category == nil or entry.category == category
end
-- find(nameOrExt, category?) -> the entry whose name, then whose extension, matches
local function find(key: string, category: string?): Registry.Entry?
local k = string.lower(key)
for _, e in Registry do
if e.name == k and inCategory(e, category) then
return e
end
end
for _, e in Registry do
if inCategory(e, category) and table.find(e.extensions, k) then
return e
end
end
return nil
end
-- detect(buf, name?, category?, format?) -> entry | nil, Err: opts.format, else the best sniff, else the extension
local function detect(buf: buffer, name: string?, category: string?, format: string?): (Registry.Entry?, Err.Err?)
if format then
local e = find(format, category)
if not e then
return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. format .. (if category then " in " .. category else ""))
end
return e
end
local ext = Input.extension(name)
local best: Registry.Entry? = nil
local bestScore = 0
for _, e in Registry do
if inCategory(e, category) and (e.caps.decode or e.caps.open) then
local m = module(e)
if m and m.sniff then
local ok, score = pcall(m.sniff, Bytes.reader(buf))
if ok and type(score) == "number" and score > 0 then
if ext and table.find(e.extensions, ext) then
score += 0.01 -- ties go to the extension
end
if score > bestScore then
best, bestScore = e, score
end
end
end
end
end
if best then
return best
end
if ext then
local e = find(ext, category)
if e then
return e
end
end
return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. (if name then " (" .. name .. ")" else "") .. (if category then " for " .. category else ""))
end
local function tag(value: any, formatName: string)
if type(value) == "table" then
local meta = value.meta
if type(meta) == "table" then
if meta.source == nil then
meta.source = { format = formatName }
elseif type(meta.source) == "table" and meta.source.format == nil then
meta.source.format = formatName
end
end
end
end
-- full decode through a streaming decoder (audio formats with open but no decode)
local function drain(dec: any): any
local channels = dec.channels
local parts, total = {}, 0
while true do
local out, n = dec:read(65536)
if not out or n == 0 then
break
end
local copy = buffer.create(n * channels * 4)
buffer.copy(copy, 0, out, 0, n * channels * 4)
table.insert(parts, copy)
total += n
end
local a = Types.Audio.new(dec.sampleRate, channels, total)
local o = 0
for _, p in parts do
buffer.copy(a.samples, o, p)
o += buffer.len(p)
end
a.tags = dec.tags or {}
return a
end
-- ------------------------------------------------------------------------------------------------ API
export type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options
-- load(src, opts?) -> value | nil, Err
function F.load(src: any, opts: Options?): (any, Err.Err?)
local o = opts or {}
local buf, ierr, name = Input.resolve(src, o, host)
if not buf then
return nil, ierr
end
local entry, derr = detect(buf, name, o.category, o.format)
if not entry then
return nil, derr
end
local m, merr = module(entry)
if not m then
return nil, merr
end
local value, err
if m.decode then
local ok, v, e = pcall(m.decode, Bytes.reader(buf), o)
if not ok then
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name)
end
value, err = v, e
elseif m.open then
local ok, dec, e = pcall(m.open, Bytes.reader(buf), o)
if not ok then
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name)
end
if dec then
value = drain(dec)
end
err = e
else
return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no decoder"), entry.name)
end
if value == nil then
return nil, Err.wrap(err or Err.new(Err.CORRUPT, "decode failed"), entry.name)
end
tag(value, entry.name)
return value
end
-- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err
function F.open(src: any, opts: Options?): (any, Err.Err?)
local o = opts or {}
local buf, ierr, name = Input.resolve(src, o, host)
if not buf then
return nil, ierr
end
local entry, derr = detect(buf, name, o.category, o.format)
if not entry then
return nil, derr
end
local m, merr = module(entry)
if not m then
return nil, merr
end
if not m.open then
return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no streaming decoder (use load)"), entry.name)
end
local ok, dec, e = pcall(m.open, Bytes.reader(buf), o)
if not ok then
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name)
end
if dec == nil then
return nil, Err.wrap(e or Err.new(Err.CORRUPT, "open failed"), entry.name)
end
return dec
end
-- the writable format for a value: opts.format, the destination's extension, or the source format
local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?)
local category = o.category
if category == nil and type(value) == "table" and type(value.kind) == "string" then
category = KIND_CATEGORY[value.kind]
end
local key = o.format or Input.extension(dest)
if key == nil and type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" then
key = value.meta.source.format
end
if key == nil then
return nil, nil, Err.new(Err.ARG, "save: no format (pass opts.format or a destination with an extension)")
end
local entry = find(key, category)
if not entry then
return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. (if category then " for " .. category else ""))
end
local m, merr = module(entry)
if not m then
return nil, nil, merr
end
if not m.encode then
local alt = nil
for _, e in Registry do
if e.category == entry.category and e.caps.encode then
alt = e.name
break
end
end
return nil, nil, Err.wrap(Err.new(Err.UNSUPPORTED, "read-only format" .. (if alt then "; try " .. alt else "")), entry.name)
end
return entry, m, nil
end
-- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err
function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
local o = opts or {}
local entry, m, err = encoderFor(value, dest, o)
if not entry then
return nil, err
end
local ok, buf, e = pcall(m.encode, value, o)
if not ok then
return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name)
end
if buf == nil then
return nil, Err.wrap(e or Err.new(Err.ARG, "encode failed"), entry.name)
end
if dest then
local wok, werr = host.writeFile(dest, buf)
if not wok then
return nil, werr
end
return true
end
return buf
end
-- saveString(value, opts?) -> string | nil, Err
function F.saveString(value: any, opts: Options?): (string?, Err.Err?)
local buf, err = F.save(value, nil, opts)
if not buf then
return nil, err
end
return buffer.tostring(buf)
end
-- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save.
function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?)
local o = opts or {}
local value, err = F.load(src, o)
if value == nil then
return nil, err
end
local so = table.clone(o)
so.format = format
so.category = nil
return F.save(value, o.out, so)
end
-- detect(src, opts?) -> format name | nil, Err
function F.detect(src: any, opts: Options?): (string?, Err.Err?)
local o = opts or {}
local buf, ierr, name = Input.resolve(src, o, host)
if not buf then
return nil, ierr
end
local entry, err = detect(buf, name, o.category, o.format)
if not entry then
return nil, err
end
return entry.name
end
export type FormatInfo = { name: string, category: string, extensions: { string }, mime: { string }, caps: { [string]: any } }
-- formats(category?) -> { FormatInfo } (no format module is loaded)
function F.formats(category: string?): { FormatInfo }
local out = {}
for _, e in Registry do
if inCategory(e, category) then
table.insert(out, { name = e.name, category = e.category, extensions = e.extensions, mime = e.mime, caps = e.caps })
end
end
return out
end
-- format(name) -> the format module itself (its contract table: sniff / decode / encode / extras such as png.info)
function F.format(name: string): (any, Err.Err?)
local e = find(name)
if not e then
return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. name)
end
return module(e)
end
-- ------------------------------------------------------------------------------------------------ category facades
-- F.image.load / save / open / formats, F.audio..., F.model... : the same calls restricted to one category
local function with(opts: Options?, category: string): Options
local o = if opts then table.clone(opts) else {}
o.category = category
return o
end
for category in Types.CATEGORIES do
local cat: string = category
F[cat] = {
load = function(src: any, opts: Options?): (any, Err.Err?)
return F.load(src, with(opts, cat))
end,
open = function(src: any, opts: Options?): (any, Err.Err?)
return F.open(src, with(opts, cat))
end,
save = function(value: any, dest: string?, opts: Options?): (any, Err.Err?)
return F.save(value, dest, with(opts, cat))
end,
formats = function(): { FormatInfo }
return F.formats(cat)
end,
}
end
F.data.null = Types.null
return F