merge ws/cm-formats

This commit is contained in:
4DBug committed 2026-11-01 01:32:04 -06:00
commit 54c55c1615
283 files changed
+1622 -4508

No files matched your search

+1 -6
View File
@@ -1,8 +1,5 @@
--!strict
-- archive/7z/Header: the 7z header parser (7zFormat.txt from the LZMA SDK / 7-Zip, Igor Pavlov, public domain):
-- streams info (pack info, folders with their coders and bind pairs, substreams), files info (names, empty streams /
-- files, anti items, times, attributes). Not --!native: a parse failure raises an Err value that parse() catches and
-- returns; any other error is a bug and propagates (the tests' fuzz pass sees it).
-- archive/7z/Header: the 7z header parser (7zFormat.txt, LZMA SDK, Igor Pavlov, public domain): streams, files info.
local Text = require("@rosetta/codecs/text/Text")
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
@@ -505,8 +502,6 @@ local function header(r: Bytes.Reader): Parsed
return p
end
-- parse(buf, offset, length) -> Parsed | nil, Err. An encoded header returns { encoded = streams } for the caller to
-- decode and parse again.
function Header.parse(b: buffer, o: number, n: number): (Parsed?, Err.Err?)
local r = Bytes.reader(b, o, n)
local ok, res = pcall(function(): Parsed
+5 -13
View File
@@ -1,12 +1,7 @@
--!strict
-- archive/7z: 7z archives (7zFormat.txt from the LZMA SDK, Igor Pavlov, public domain), read as an Archive whose
-- entries decode lazily (a folder is decoded once on first read, then sliced). Supports: plain and encoded (compressed)
-- headers, solid and non-solid folders, coder chains of copy / LZMA / LZMA2 / Deflate / BZip2 /
-- Zstd (7-Zip-zstd's plain frames; untested: stock 7-Zip cannot write it) with BCJ (x86, PowerPC, ARM,
-- ARM-Thumb, SPARC, ARM64) and delta filters, empty files and directories, anti items (skipped), UTF-16 names, mtimes,
-- Windows / Unix attributes, folder and file CRC-32s (verified on read).
-- Not supported (Err.UNSUPPORTED naming the method, on read of the affected entries): PPMd, BCJ2, Deflate64, other
-- plug-in codecs (Brotli, LZ4, ...), AES encryption, multi-volume archives, external header references; writing.
-- archive/7z: 7z (7zFormat.txt, LZMA SDK, public domain). Supports: encoded headers, solid folders, copy / LZMA /
-- LZMA2 / Deflate / BZip2 / Zstd (7-Zip-zstd frames) with BCJ and delta filters, anti items (skipped), CRC-32s.
-- Not supported: PPMd, BCJ2, Deflate64, other plug-in codecs, AES, multi-volume, external header references, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -31,8 +26,8 @@ local SevenZip = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse a folder (solid block) or header that decodes to more than this (default 2^30)
checkCrc: boolean?, -- verify CRC-32s on read (default true)
maxBytes: number?, -- default 2^30, per folder or header
checkCrc: boolean?, -- default true
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -99,7 +94,6 @@ local function packStart(ctx: Ctx, s: Header.Streams, index: number): number
end
local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buffer?, Err.Err?)
-- coder -> first in / out stream index
local inBase, outBase = {}, {}
local ni, no = 0, 0
for i, c in f.coders do
@@ -130,7 +124,6 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf
if size > ctx.maxBytes then
return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size))
end
-- the coder's input: another coder's output, or a packed stream
local inIdx = inBase[ci]
local src: buffer, so: number, sl: number
local bound = nil
@@ -292,7 +285,6 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?
local s: Header.Streams = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} }
a.meta.folders = #s.folders
a.meta.solid = false
-- folder caches and the substream -> folder map
local cache: { [number]: buffer } = {}
local subFolder: { number }, subOffset: { number } = {}, {}
do
+3 -11
View File
@@ -1,14 +1,7 @@
--!strict
-- archive/adf: Amiga disk images (.adf: 880 KB double density, 1.76 MB high density, and other sizes holding an
-- AmigaDOS volume without a partition table) read as an Archive: the boot block's DOS type (OFS / FFS, international,
-- directory cache: meta.fs / meta.intl / meta.dircache), the root block (volume name, dates), directories through
-- their 72-slot hash tables and hash chains, files through their header and extension block tables (FFS) or the
-- OFS data block chain, soft links (entry.link) and hard links (entry.hardlink = the path linked to; a hard-linked
-- file reads its target's data). Protection bits (entry.protect, AmigaDOS order: bit 0 = delete forbidden ...),
-- comments (entry.comment) and dates (days / minutes / ticks since 1978-01-01, as unix seconds) are mapped; names are
-- ISO-8859-1. Header block checksums are verified (Err.CHECKSUM). Written from the AmigaDOS file system description
-- (the ADF-FAQ by Laurent Clévy). Not supported: writing, long-name file systems (DOS\6 / DOS\7), RDB hard-disk
-- images (use the partition contents), dircache blocks (not needed to read).
-- archive/adf: Amiga disk images (AmigaDOS OFS / FFS, intl, dircache; ADF-FAQ by Laurent Clévy): 72-slot hash tables,
-- extension blocks / OFS chains, soft and hard links, protection bits, comments, dates since 1978-01-01, ISO-8859-1
-- names, header checksums. Not supported: writing, DOS\6 / DOS\7, RDB hard-disk images, dircache blocks.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -89,7 +82,6 @@ local function date(d: Disk, blk: number, off: number): number
return (u32(d, blk, off) * 86400 + u32(d, blk, off + 4) * 60 + u32(d, blk, off + 8) // 50) + EPOCH
end
-- the data blocks of a file header (FFS: the header and extension tables; OFS uses the same tables)
local function dataBlocks(d: Disk, hdr: number, maxBlocks: number): ({ number }?, string?)
local out = {}
local blk = hdr
+6 -12
View File
@@ -1,13 +1,7 @@
--!strict
-- archive/applesingle: AppleSingle (magic 0x00051600) and AppleDouble (0x00051607) files, versions 1 and 2 (RFC 1740):
-- the entry table with the data fork (1), resource fork (2), real name (3), comment (4), file dates (8, version 2:
-- seconds since 2000-01-01; version 1's file info (7) as Mac dates) and Finder info (9: type, creator, flags).
-- Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a resource fork the
-- entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / comment); the name is the real name
-- entry, else the file name without the "._" AppleDouble prefix (opts.name), else "data". An AppleDouble file holds
-- no data fork: only its resource fork entry is listed, and meta.double = true. Writes version 2 AppleSingle (or AppleDouble with
-- opts.double) from any Archive's first Mac file or a buffer. Written from RFC 1740. Not supported: icon, ProDOS /
-- MS-DOS / AFP info entries (kept in meta.entries as id + length).
-- archive/applesingle: AppleSingle (0x00051600) / AppleDouble (0x00051607) v1 and v2 (RFC 1740): data fork (1),
-- resource fork (2), real name (3), comment (4), dates (8; v1 file info 7), Finder info (9), as containers/MacFile.
-- Supports: read, write v2. Not supported: icon, ProDOS / MS-DOS / AFP info entries (kept in meta.entries).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,10 +19,10 @@ local AppleSingle = {
caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } },
}
export type DecodeOptions = { name: string?, maxBytes: number? } -- name: the file name (the api passes it)
export type DecodeOptions = { name: string?, maxBytes: number? }
export type EncodeOptions = {
double: boolean?, -- write AppleDouble (no data fork) instead of AppleSingle (default false)
name: string?, -- the name of a buffer / string value (default "data")
double: boolean?, -- default false
name: string?,
}
-- ------------------------------------------------------------------------------------------------ constants
+6 -15
View File
@@ -1,13 +1,7 @@
--!strict
-- archive/ar: Unix ar archives ("!<arch>\n"): System V / GNU (names ending in "/", the "//" long-name table, the "/"
-- and "/SYM64/" symbol tables) and BSD (inline "#1/<len>" names, the "__.SYMDEF" symbol table), read into the standard
-- Archive value and written (opts.variant "gnu", the default, or "bsd") from any Archive value. Symbol tables are not
-- entries: their symbols land in meta.symbols ({ name, member }). Debian packages (.deb) are ar archives: their
-- meta.payload names the data.tar.* member (the api loads a .deb as that data tar, meta.outer = this archive) and
-- meta.control holds the fields of the control file in control.tar / .gz / .xz / .zst / .bz2 / .lzma (decompressed
-- with codecs/compress/*, read with containers/Tar). Written from the ar(5) manual pages (GNU binutils, FreeBSD) and
-- deb(5) (dpkg); no code ported. Not supported: thin archives ("!<thin>"), writing symbol tables (a re-written
-- library needs ranlib), writing .deb control data (any entries write as a plain ar).
-- archive/ar: Unix ar ("!<arch>\n"; ar(5), deb(5); no code ported): System V / GNU ("//" names, "/" and "/SYM64/"
-- symbols) and BSD ("#1/<len>", "__.SYMDEF"); .deb payload and control fields. Supports: read, write gnu / bsd.
-- Not supported: thin archives ("!<thin>"), writing symbol tables or .deb control data.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -31,10 +25,10 @@ local Ar = {
export type DecodeOptions = {
maxEntries: number?, -- default 1e6
maxBytes: number?, -- .deb: the largest control.tar to decompress (default 2^26)
maxBytes: number?, -- .deb control.tar limit (default 2^26)
}
export type EncodeOptions = {
variant: ("gnu" | "bsd")?, -- default: the source archive's ("bsd" for a .deb: plain names), else "gnu"
variant: ("gnu" | "bsd")?, -- default: the source's ("bsd" for a .deb), else "gnu"
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -134,7 +128,6 @@ local function controlFields(s: string): { [string]: string }
return out
end
-- control.tar[.ext] -> the control file's fields, or nil
local function debControl(b: buffer, o: number, n: number, name: string, maxBytes: number): { [string]: string }?
local ext = string.match(name, "^control%.tar%.?(%w*)$")
local raw: buffer?
@@ -183,7 +176,7 @@ function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local variant = "gnu"
local longNames: string? = nil
local symbols: { { name: string, offset: number } }? = nil
local offsets: { [number]: string } = {} -- header offset (from the start) -> member name
local offsets: { [number]: string } = {}
local count = 0
local p = base + 8
while p < e do
@@ -281,7 +274,6 @@ function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
a.meta.symbols = out
end
a.meta.source = { format = "ar", variant = variant }
-- Debian packages
local list = a._entries
if list[1] and list[1].name == "debian-binary" then
a.meta.source.variant = "deb"
@@ -400,7 +392,6 @@ function Ar.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty ar Archive: a:add(name, data, { mtime, mode }); a:write({ variant = "bsd" })
function Ar.new(): any
local a = Archive.new("ar", encode)
a.meta.source = { format = "ar", variant = "gnu" }
+4 -8
View File
@@ -1,11 +1,7 @@
--!strict
-- archive/arj: ARJ archives (Robert Jung) read into an Archive: the main header (archive name, comment, host OS,
-- dates) and every local header (CRC-32 checked), files stored (method 0), compressed with methods 1..3 (the LHA-style
-- static Huffman LZSS of codecs/compress/Lzh, "lh6" tables) or 4 (codecs/compress/Lzh "arj4"), directories (file type
-- 3), DOS times (read as UTC), file modes, comments; each file's CRC-32 is verified when read (Err.CHECKSUM).
-- Written from the ARJ technical information (arj's technote.txt). Not supported: garbled (encrypted) files,
-- multi-volume archives (entries continued to / from another volume), chapters, writing (Err.UNSUPPORTED for those
-- entries / calls).
-- archive/arj: ARJ (Robert Jung; arj's technote.txt): headers CRC-32 checked, methods 0 stored, 1..3 Lzh "lh6", 4 Lzh
-- "arj4", directories (file type 3), DOS times as UTC; file CRC-32 verified. Not supported: garbled (encrypted) files,
-- multi-volume archives, chapters, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,7 +21,7 @@ local Arj = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse an entry larger than this (default 2^30)
maxBytes: number?, -- default 2^30
maxEntries: number?, -- default 65536
}
+4 -11
View File
@@ -1,11 +1,7 @@
--!strict
-- archive/binhex: BinHex 4.0 (.hqx) files: the 6-bit text encoding, the RLE90 run-length layer, the header (name,
-- type / creator, Finder flags) and the data and resource forks, each with its CRC-16/XMODEM (verified:
-- Err.CHECKSUM). Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a
-- resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags); writes any Archive's first Mac file
-- (or a buffer) back, 64 characters a line, as BinHex 4.0 tools do. Written from the BinHex 4.0 definition (Peter
-- Lewis' / RFC 1741 notes). Not supported: BinHex 2 / 3 / 5 (BinHex 5 is MacBinary inside BinHex 4: unwrap it with
-- archive/macbinary), several files in one .hqx (only the first is read).
-- archive/binhex: BinHex 4.0 (.hqx; RFC 1741 notes): 6-bit text, RLE90, header and forks each with CRC-16/XMODEM, as
-- containers/MacFile; writes 64 characters a line, as BinHex 4.0 tools do. Not supported: BinHex 2 / 3 / 5, several
-- files in one .hqx (the first is read).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,7 +21,7 @@ local Binhex = {
}
export type DecodeOptions = { maxBytes: number? } -- default 2^30
export type EncodeOptions = { name: string? } -- the name of a buffer / string value (default "data")
export type EncodeOptions = { name: string? }
-- ------------------------------------------------------------------------------------------------ constants
local ALPHABET = "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr"
@@ -46,7 +42,6 @@ function Binhex.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the 6-bit characters between the colons -> bytes, then RLE90 expanded (nil, message on bad input)
local function unhex(text: string, maxBytes: number): (buffer?, string?)
local banner = string.find(text, BANNER, 1, true)
if not banner then
@@ -190,7 +185,6 @@ function Binhex.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
body:u16be(Crc16.ccitt(part, 0, buffer.len(part)))
end
local src = body:finish()
-- RLE90
local rle = Bytes.writer(buffer.len(src) + 16)
local n = buffer.len(src)
local i = 0
@@ -244,7 +238,6 @@ function Binhex.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty BinHex Archive: a:add(name, data, { macType, macCreator }); add "name.rsrc" for a resource fork
function Binhex.new(): any
local a = Archive.new("binhex", encoder)
a.meta.source = { format = "binhex" }
+4 -7
View File
@@ -1,9 +1,6 @@
--!strict
-- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (meta.stream: the api unwraps a .tar.br to the tar
-- inside). Decoding through codecs/compress/Brotli. The entry is named after opts.name without ".br" (else "data").
-- Supports: read (eager decompression). Not supported: write (no Brotli compressor). Brotli has no magic number:
-- sniff accepts only data that decodes cleanly (the whole stream for small files, a 64 KB prefix for big ones), at a
-- low confidence, so the extension decides between candidates.
-- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (codecs/compress/Brotli). Supports: read.
-- Not supported: write. No magic number: sniff accepts only data that decodes cleanly, at a low confidence.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -22,8 +19,8 @@ local Br = {
}
export type DecodeOptions = {
name: string?, -- the file name (the api passes it): the entry is named after it
maxBytes: number?, -- refuse output larger than this (default 2^30)
name: string?,
maxBytes: number?, -- default 2^30
}
-- ------------------------------------------------------------------------------------------------ constants
+4 -6
View File
@@ -1,8 +1,6 @@
--!strict
-- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/compress/Bzip2; concatenated
-- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"),
-- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). New in rosetta. Not supported:
-- writing (codecs/compress/Bzip2 has no compressor), randomised blocks (bzip2 0.9.0 and older).
-- archive/bz2: a .bz2 file as a single-stream archive of one entry (codecs/compress/Bzip2). Supports: read,
-- concatenated streams joined as bzip2 -d does. Not supported: writing, randomised blocks (bzip2 0.9.0 and older).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -21,8 +19,8 @@ local Bz2 = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger output (default 2^30)
name: string?, -- the file name (the api passes it): names the entry
maxBytes: number?, -- default 2^30
name: string?,
}
-- ------------------------------------------------------------------------------------------------ sniff
+2 -5
View File
@@ -1,16 +1,14 @@
--!strict
--!native
--!optimize 2
-- archive/cab/Sum: the cabinet data block checksum (the XOR of the data's little-endian 32-bit words, the last 1..3
-- bytes packed most significant first, then the block's cbData / cbUncomp word). Written from the CAB format
-- description ([MS-CAB] 2.4, CFDATA.csum).
-- archive/cab/Sum: the CFDATA.csum checksum ([MS-CAB] 2.4): XOR of LE u32 words, the last 1..3 bytes packed most
-- significant first, then the cbData / cbUncomp word.
local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len
local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift
local Sum = {}
-- of(buf, off, len, seed) -> the checksum of buf[off, off + len) continuing from seed (0 for a new sum)
function Sum.of(buf: buffer, off: number, len: number, seed: number): number
if off < 0 or len <= 0 or off + len > blen(buf) then
return seed
@@ -34,7 +32,6 @@ function Sum.of(buf: buffer, off: number, len: number, seed: number): number
return bxor(s, tail)
end
-- block(buf, dataAt, cbData, cbUncomp) -> the csum field of a CFDATA block with these sizes over buf[dataAt, +cbData)
function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number
return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536)
end
+8 -24
View File
@@ -1,14 +1,7 @@
--!strict
-- archive/cab: Microsoft Cabinet files (MSCF 1.3) read into an Archive: the header with its reserve areas and
-- cabinet set fields, folders (CFFOLDER) compressed with none, MSZIP (each CFDATA block "CK" + raw deflate whose
-- dictionary carries over from the block before), LZX (codecs/compress/Lzx, windows 2^15..2^21) or Quantum
-- (codecs/compress/Quantum, windows 2^10..2^21), the files (CFFILE) with their MS-DOS attributes, DOS times (local
-- time without a zone, read as UTC) and the UTF-8 name flag; every data block's checksum is verified (Err.CHECKSUM)
-- when a file of its folder is read. A folder is decompressed once per read and kept for the next file of the same
-- folder. Writes one folder, stored or MSZIP (independent 32 KB deflate blocks), from any Archive. Written from the
-- Microsoft Cabinet format specification ([MS-CAB]). Not supported: files continued from / to another cabinet of a
-- set (Err.UNSUPPORTED for those entries, and for the first folder of a cabinet continued from a previous one),
-- signed / self-extracting stubs before the header.
-- archive/cab: Microsoft Cabinet (MSCF 1.3, [MS-CAB]): folders none / MSZIP ("CK" + raw deflate, dictionary carried
-- over between blocks) / LZX (2^15..2^21) / Quantum (2^10..2^21), DOS times as UTC, checksums verified; writes one
-- stored or MSZIP folder. Not supported: files spanning cabinets of a set, signed / self-extracting stubs.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -30,14 +23,14 @@ local Cab = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse a folder that decompresses to more than this (default 2^30)
maxBytes: number?, -- default 2^30
maxEntries: number?, -- default 65535
verify: boolean?, -- check the data block checksums (default true)
verify: boolean?, -- default true
}
export type EncodeOptions = {
compression: ("mszip" | "none")?, -- default "mszip"
level: number?, -- deflate level 0..9 (default 6)
setId: number?, -- the cabinet set id (default 0)
level: number?, -- 0..9 (default 6)
setId: number?, -- default 0
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -63,8 +56,7 @@ type Folder = {
}
type Block = { at: number, len: number, size: number }
-- the CFDATA blocks of a folder (checksums checked), their total output and whether the folder runs into the next
-- cabinet (a block with cbUncomp 0)
-- a block with cbUncomp 0 runs into the next cabinet
local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: boolean, maxBytes: number): ({ Block }?, any, boolean?)
local list: { Block } = {}
local p = f.dataAt
@@ -95,7 +87,6 @@ local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: b
return list, total, false
end
-- the decompressed data of a folder's blocks
local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: number): (buffer?, Err.Err?)
local method = bit32.band(typ, 15)
local out = buffer.create(total)
@@ -191,7 +182,6 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
flags = flags,
reserve = { header = headerReserve, folder = folderReserve, data = dataReserve },
}
-- folders
local folders: { Folder } = {}
local methods = {}
for i = 1, cFolders do
@@ -216,7 +206,6 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
if cFiles > maxEntries then
return nil, Err.new(Err.LIMIT, "more than maxEntries files")
end
-- the folder cache: the last decompressed folder
local cachedIndex, cachedData, cachedRuns = 0, nil :: buffer?, false
local function folderData(f: Folder): (buffer?, Err.Err?, boolean?)
if cachedIndex == f.index then
@@ -233,7 +222,6 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
cachedIndex, cachedData, cachedRuns = f.index, data, runs == true
return data, nil, runs
end
-- files
local fr = r:sub(coffFiles)
for _ = 1, cFiles do
local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le()
@@ -306,7 +294,6 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(archive, opts?) -> a cabinet with one folder holding every file (directories are implied by the names)
function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local compression = o.compression or "mszip"
@@ -334,7 +321,6 @@ function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if total > 0x7FFF8000 then
return nil, Err.new(Err.ARG, "more than 2 GB of data")
end
-- the folder data, in 32 KB blocks
local folder = buffer.create(total)
local p = 0
for _, f in files do
@@ -369,7 +355,6 @@ function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
s += n
end
local blob = data:finish()
-- names and the file table
local table_ = Bytes.writer(64 + #files * 32)
local offset = 0
for _, f in files do
@@ -417,7 +402,6 @@ function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty cab Archive: a:add(name, data, { mtime }); a:write({ compression = "none" | "mszip" })
function Cab.new(): any
local a = Archive.new("cab", encode)
a.meta.source = { format = "cab" }
+5 -11
View File
@@ -1,10 +1,6 @@
--!strict
-- archive/cpio: cpio archives (newc, crc, odc, old binary in both byte orders; see containers/Cpio) read into the
-- standard Archive value (entries read lazily: a copy of the stored bytes) and written as newc (default), crc or odc
-- from any Archive value (a tar, a zip, ...: list() + read()). Entries carry the cpio fields: type (tar letters),
-- mode (permission bits; the type is in type), uid, gid, nlink, ino, devmajor / devminor, rdevmajor / rdevminor,
-- link (symlinks), hardlink (the first link of a hard link group; every link reads the data). Tar hard links ("1")
-- written as cpio share an inode with their target. Not supported: tar-only fields (uname, gname: dropped).
-- archive/cpio: cpio (newc, crc, odc, old binary in both byte orders; containers/Cpio). Supports: read (lazy), write as
-- newc / crc / odc; tar hard links ("1") share an inode with their target. Not supported: uname / gname (dropped).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,12 +20,12 @@ local CpioFormat = {
export type DecodeOptions = {
maxEntries: number?, -- default 1e6
verify: boolean?, -- crc archives: check the data sums (default true)
verify: boolean?, -- default true
}
export type EncodeOptions = {
variant: ("newc" | "crc" | "odc")?, -- default: the source archive's (old binary: newc), else "newc"
format: string?, -- "newc", "crc" or "odc" here too; any other value (the api's "cpio") means the variant default
block: number?, -- pad to a multiple of this many bytes (default 512, as GNU cpio; 1 = none)
format: string?, -- any other value (the api's "cpio") means the variant default
block: number?, -- default 512, as GNU cpio; 1 = none
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -153,7 +149,6 @@ function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Er
rdevminor = num(e.rdevminor),
})
end
-- opts.format may also be the api's format name ("cpio"): the variant default then
local o: any = opts or {}
local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source
local own = if src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") then src.variant else "newc"
@@ -162,7 +157,6 @@ function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Er
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty cpio Archive: a:add(name, data, { mtime, mode, dir }); a:write()
function CpioFormat.new(): any
local a = Archive.new("cpio", encode)
a.meta.source = { format = "cpio" }
+5 -17
View File
@@ -1,14 +1,7 @@
--!strict
-- archive/d64: Commodore disk images as an Archive: D64 (1541: 35 / 40 / 42 tracks, with or without the error-info
-- block), D71 (1571: 70 tracks, double sided) and D81 (1581: 80 tracks of 40 sectors). The BAM / header (disk name and
-- id in meta.disk / meta.id), the directory chain, and every file's sector chain; PRG / SEQ / USR / REL files are
-- entries (entry.type, entry.blocks, entry.locked, entry.closed; REL files read their data chain, the side sectors are
-- skipped), deleted entries are skipped, unclosed ("splat") files are flagged closed = false. Names are PETSCII
-- translated as VICE's c1541 does (0x41..0x5A -> a..z, 0xC1..0xDA and 0x61..0x7A -> A..Z, other bytes to U+E0xx so the
-- name survives a round trip); entry.rawName keeps the 16 bytes. Writes D64 (35 tracks) / D71 / D81 images from any
-- Archive (files as PRG, or entry.type), allocating sectors near the directory track with interleave 10 as CBM DOS
-- does (not the same sectors as a real drive). Written from the 1541 / 1571 / 1581 DOS documentation (Peter Schepers'
-- disk format notes). Not supported: GEOS VLIR files (read as their first chain), 1581 partitions (CBM type) contents.
-- archive/d64: Commodore D64 (1541: 35 / 40 / 42 tracks, error block), D71, D81 (Peter Schepers' notes); PETSCII names
-- as VICE's c1541 (0x41..0x5A -> a..z, 0xC1..0xDA / 0x61..0x7A -> A..Z, else U+E0xx); writes with interleave 10 as
-- CBM DOS (not a real drive's sectors). Not supported: GEOS VLIR files (first chain), 1581 partition contents.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -28,8 +21,8 @@ local D64 = {
export type DecodeOptions = { maxEntries: number? } -- default 4096
export type EncodeOptions = {
variant: ("d64" | "d71" | "d81")?, -- default: the variant read, else "d64"
disk: string?, -- disk name (default "rosetta" / the name read)
id: string?, -- two-character disk id (default "fl")
disk: string?, -- default "rosetta" / the name read
id: string?, -- default "fl"
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -129,7 +122,6 @@ local function encoder(a: any, o: any?): (buffer?, Err.Err?)
return D64.encode(a, o)
end
-- the bytes of a sector chain starting at (t, s); nil, message when it leaves the disk or loops
local function chain(b: buffer, base: number, geo: Geometry, t: number, s: number): (buffer?, string?)
local w = Bytes.writer()
local seen: { [number]: boolean } = {}
@@ -174,7 +166,6 @@ function D64.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
a.meta.tracks = geo.tracks
a.meta.errorInfo = r:size() ~= geo.total
a.meta.source = { format = "d64", variant = geo.kind, tracks = geo.tracks }
-- the directory chain
local t, s = buffer.readu8(b, hdr), buffer.readu8(b, hdr + 1)
local seen: { [number]: boolean } = {}
local count = 0
@@ -236,7 +227,6 @@ end
-- ------------------------------------------------------------------------------------------------ encode
-- BAM layout per variant: where each track's free count + bitmap lives
local function bamEntry(geo: Geometry, img: buffer, t: number): (number, number, number)
-- returns (offset of the free count, offset of the bitmap, bitmap bytes)
local dir = geo.offsets[geo.dirTrack]
if geo.kind == "d81" then
local side = if t <= 40 then 1 else 2
@@ -286,7 +276,6 @@ function D64.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local function pad16(s: string): string
return s .. string.rep("\160", 16 - #s)
end
-- header / BAM
local firstDir
if variant == "d81" then
buffer.writestring(img, dir, "\40\3\68\0")
@@ -413,7 +402,6 @@ function D64.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new(variant?) -> an empty disk: a:add(name, data); a:write({ disk = "name", id = "ab" })
function D64.new(variant: string?): any
local a = Archive.new("d64", encoder)
a.meta.variant = variant or "d64"
+6 -10
View File
@@ -1,10 +1,7 @@
--!strict
-- archive/fat: FAT12 / FAT16 / FAT32 disk images (floppy images, and hard-disk images with an MBR partition table: the
-- first FAT partition, or opts.partition) as an Archive, through containers/Fat: VFAT long names, NT lower-case 8.3
-- names, directories (entries ending in "/"), file dates (DOS local time read as UTC), attributes (entry.attr) and the
-- 8.3 name (entry.shortName); files read lazily. meta.fat = 12 / 16 / 32, meta.label, meta.oem. Writes FAT12 floppy
-- images (1.44 MB by default; 360 / 720 / 1200 / 2880 KB with opts.size) from any Archive, with long names where a
-- name is not a plain 8.3 name; mtools and fsck.fat read them. Not supported: writing FAT16 / FAT32, exFAT, boot code.
-- archive/fat: FAT12 / FAT16 / FAT32 images (floppy, or the first FAT partition of an MBR) through containers/Fat.
-- Supports: VFAT long names, NT lower-case 8.3, DOS dates as UTC; writes FAT12 floppies (360..2880 KB) that mtools and
-- fsck.fat read. Not supported: writing FAT16 / FAT32, exFAT, boot code.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -23,12 +20,12 @@ local FatFormat = {
}
export type DecodeOptions = {
partition: number?, -- MBR partition 1..4 (default: the first FAT partition, or the image itself)
partition: number?, -- 1..4 (default: the first FAT partition, or the image itself)
maxEntries: number?, -- default 65536
}
export type EncodeOptions = {
size: number?, -- floppy size in KB: 360 / 720 / 1200 / 1440 / 2880 (default 1440)
label: string?, -- volume label
size: number?, -- KB: 360 / 720 / 1200 / 1440 / 2880 (default 1440)
label: string?,
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -114,7 +111,6 @@ function FatFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty floppy: a:add("dir/file.txt", data, { mtime }); a:write({ size = 1440, label = "DISK" })
function FatFormat.new(): any
local a = Archive.new("fat", encoder)
a.meta.source = { format = "fat" }
+4 -7
View File
@@ -1,9 +1,7 @@
--!strict
-- archive/grp: Build engine GRP archives (Duke Nukem 3D, Shadow Warrior, Blood: "KenSilverman", a u32 file count,
-- 16-byte entries of a 12-byte name and a u32 size, then the files back to back), read into the standard Archive
-- (entries read lazily) and written from any Archive value (names upper-cased to 8.3 by the caller's choice: they
-- are stored as given, at most 12 bytes). Written from Ken Silverman's GRP description (kenbuild); no code taken.
-- Not supported: the "GRP 2" / RFF / SSI variants.
-- archive/grp: Build engine GRP ("KenSilverman", u32 count, 16-byte entries: 12-byte name + u32 size, then the data),
-- from Ken Silverman's description; no code taken. Supports: read (lazy), write (names stored as given, at most 12
-- bytes). Not supported: the "GRP 2" / RFF / SSI variants.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -23,7 +21,7 @@ local Grp = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = { maxEntries: number? } -- default 1e6
export type EncodeOptions = { upper: boolean? } -- upper-case the names (Build looks them up case-insensitively; default false)
export type EncodeOptions = { upper: boolean? } -- Build looks names up case-insensitively; default false
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "KenSilverman"
@@ -105,7 +103,6 @@ function Grp.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty GRP Archive: a:add(name, data); a:write()
function Grp.new(): any
local a = Archive.new("grp", encode)
a.meta.source = { format = "grp" }
+6 -10
View File
@@ -1,9 +1,7 @@
--!strict
-- archive/gzip: gzip files (RFC 1952) as a single-stream Archive: one entry, named after the header's FNAME (else the
-- file name without .gz, else "data"), with the header's MTIME; concatenated members decode as one stream, as gzip -d
-- does. Writing: an Archive with one entry (or a buffer / string) becomes one member with FNAME and MTIME; an Archive
-- with several entries is written as a tar inside the gzip (a .tar.gz). The api unwraps a .tar.gz / .tgz on load (the
-- inner tar, meta.compression = "gzip"). Deflate is codecs/compress/Deflate. Not supported: FHCRC verification.
-- archive/gzip: gzip (RFC 1952) as a single-stream archive of one entry (FNAME, MTIME; codecs/compress/Deflate).
-- Supports: concatenated members as one stream (as gzip -d); write (several entries: a .tar.gz).
-- Not supported: FHCRC verification.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -23,11 +21,11 @@ local Gzip = {
caps = { decode = true, encode = true, stream = true },
}
export type DecodeOptions = { name: string? } -- the file name (the api passes it): names the entry without FNAME
export type DecodeOptions = { name: string? }
export type EncodeOptions = {
level: number?, -- 0..9, default 6
name: string?, -- FNAME (default: the entry's name; none for a buffer)
mtime: number?, -- MTIME (default: the entry's mtime, else 0)
name: string?, -- default: the entry's name; none for a buffer
mtime: number?, -- default: the entry's mtime, else 0
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -36,7 +34,6 @@ function Gzip.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- header(r) -> { name, comment, mtime, os } of the first member (nil fields when absent)
local function header(b: buffer, o: number, e: number): { [string]: any }
local h: { [string]: any } = {}
if o + 10 > e then
@@ -171,7 +168,6 @@ function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new(data?, name?) -> a gzip Archive holding one entry (add() replaces / adds; several entries write a .tar.gz)
function Gzip.new(data: (buffer | string)?, name: string?): any
local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?)
return Gzip.encode(arc, o)
+4 -9
View File
@@ -1,12 +1,7 @@
--!strict
-- archive/iso: ISO 9660 CD / DVD images (.iso) read into the standard Archive value through containers/Iso9660:
-- plain ISO 9660 names, Joliet and Rock Ridge (names, modes, owners, times, symlinks, relocated deep directories;
-- Rock Ridge is used when present, else Joliet, else the plain names: opts.prefer picks another), multi-extent files.
-- Directories are dir entries; file data reads lazily (a copy of the extents). meta.iso holds the volume facts
-- (volumeId, systemId, publisher, blockSize, blocks, created, joliet level, rockRidge, tree) and meta.boot the El
-- Torito boot catalog (platform, bootable, media, load segment, sector count, image LBA) when there is one.
-- Not supported: writing, UDF, interleaved files (read: Err.UNSUPPORTED), zisofs-compressed files (read: the stored
-- bytes), multi-session images (the first session).
-- archive/iso: ISO 9660 images through containers/Iso9660. Supports: plain names, Joliet, Rock Ridge (RR, else Joliet,
-- else plain), multi-extent files, El Torito boot catalog (meta.boot). Not supported: writing, UDF, interleaved files
-- (UNSUPPORTED), zisofs (stored bytes), multi-session images (the first session).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,7 +20,7 @@ local Iso = {
}
export type DecodeOptions = {
prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain)
prefer: ("rockridge" | "joliet" | "iso9660")?, -- default: Rock Ridge, else Joliet, else plain
maxEntries: number?, -- default 1e6
}
+6 -17
View File
@@ -1,14 +1,7 @@
--!strict
-- archive/lha: LHA / LZH archives (and LArc .lzs) read into an Archive: header levels 0, 1, 2 and 3 with their
-- extended headers (file and directory names, Unix permissions / uid / gid / user and group names / mtime, MS-DOS
-- attributes, Windows timestamps, comments), methods lh0 / lz4 (stored), lhd (directory), lh1, lh4, lh5, lh6, lh7,
-- lhx, lzs and lz5 through codecs/compress/Lzh; every file's CRC-16 (ARC) is verified (Err.CHECKSUM) when read.
-- Unix LHA symlinks ("name|target") become link entries; all-capital names from MS-DOS-like systems read in lower
-- case (as lhasa and LHa do). Level 0 / 1 MS-DOS times are read as UTC. Writes header
-- level 2 archives with stored (lh0) data from any Archive. Written from the LHA header documentation (Haruyasu
-- Yoshizaki's LHa notes, lhasa's lha_file_header.c as a reference, ISC). Not supported: pm0 / pm1 / pm2 (PMarc),
-- compression when writing, multi-volume archives, self-extracting stubs (the archive must start at offset 0 or
-- at the first header found in the first 64 KB).
-- archive/lha: LHA / LZH (and LArc .lzs; Yoshizaki's LHa notes, lhasa's lha_file_header.c, ISC): header levels 0-3,
-- methods lh0 / lz4 / lhd / lh1 / lh4-lh7 / lhx / lzs / lz5, CRC-16 (ARC), "name|target" symlinks; writes level 2,
-- stored. Not supported: PMarc pm0-pm2, compression when writing, multi-volume, stubs beyond the first 64 KB.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -28,7 +21,7 @@ local Lha = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse an entry larger than this (default 2^30)
maxBytes: number?, -- default 2^30
maxEntries: number?, -- default 65536
}
export type EncodeOptions = {}
@@ -58,7 +51,7 @@ function Lha.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- a path with "/" separators, without a leading "/" and without "." / ".." components (as lhasa collapses them)
-- "." / ".." collapsed as lhasa does
local function path(s: string): string
s = string.gsub(s, "[\\\255]", "/")
local parts = {}
@@ -90,7 +83,6 @@ type Header = {
dataAt: number,
}
-- the extended headers from offset p (size field width w), until a zero size; returns the end offset
local function extended(r: Bytes.Reader, p: number, w: number, first: number, h: Header, limit: number): (number?, string?)
local size = first
local guard = 0
@@ -138,7 +130,6 @@ local OS = { [0x4D] = "msdos", [0x55] = "unix", [0x32] = "os2", [0x39] = "os9",
[0x48] = "human68k", [0x43] = "cpm", [0x46] = "flex", [0x6D] = "mac", [0x77] = "windows95", [0x57] = "windowsnt",
[0x52] = "runser", [0x54] = "townsos", [0x58] = "xosk", [0x41] = "amiga", [0x61] = "atari", [0x4A] = "java" }
-- one header at p -> Header (h.dataAt: where the data starts), or nil at the end marker
local function header(r: Bytes.Reader, p: number): (Header?, string?)
local limit = r:size()
if p >= limit or r:sub(p, 1):u8() == 0 then
@@ -241,7 +232,6 @@ function Lha.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local maxBytes = o.maxBytes or 2 ^ 30
local maxEntries = o.maxEntries or 65536
local p = 0
-- a self-extracting stub: find the first header
if not isHeader(r:peek(22)) then
local head = r:peek(65536)
local at = nil
@@ -383,7 +373,7 @@ function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
dirPart, base = full .. "/", ""
end
local h = Bytes.writer()
h:u16le(0) -- total size, patched
h:u16le(0)
h:string(if e.dir then "-lhd-" else "-lh0-")
h:u32le(buffer.len(data))
h:u32le(buffer.len(data))
@@ -424,7 +414,6 @@ function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty LHA Archive: a:add(name, data, { mtime, mode }); a:write() (level 2 headers, stored data)
function Lha.new(): any
local a = Archive.new("lha", encoder)
a.meta.source = { format = "lha" }
+7 -18
View File
@@ -1,13 +1,7 @@
--!strict
-- archive/lz4: LZ4 frame files (.lz4: lz4 doc/lz4_Frame_format.md 1.6.x) as a single-stream Archive: one entry (the
-- decompressed data), named after the file without .lz4 (.tlz4 -> .tar), else "data"; meta.stream = true, so the api
-- unwraps a .tar.lz4. Reading: concatenated frames, skippable frames (magic 0x184D2A50..5F, skipped), the legacy
-- frame (magic 0x184C2102, 8 MB blocks), independent and linked blocks, block sizes 64 KB .. 4 MB, uncompressed
-- blocks, the header checksum, block checksums and the content checksum (XXH32, codecs/compress/Xxh32: verified
-- unless opts.verify = false), the content size (checked). Writing: one frame of independent blocks
-- (codecs/compress/Lz4), with opts for the block size, block checksums, the content checksum and the content size;
-- several entries are written as a tar inside. Written from the specification; no code ported. Not supported:
-- dictionaries (frames with a dictionary ID: Err.UNSUPPORTED), writing linked blocks or legacy frames.
-- archive/lz4: LZ4 frames (lz4_Frame_format.md 1.6.x) as a single-stream archive. Supports: concatenated, skippable
-- (0x184D2A50..5F) and legacy (0x184C2102, 8 MB blocks) frames, linked blocks, 64 KB .. 4 MB, XXH32 checksums; writes
-- one frame of independent blocks. Not supported: dictionaries, writing linked blocks or legacy frames.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -27,15 +21,15 @@ local Lz4Format = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse output larger than this (default 2^30)
verify: boolean?, -- check the block / content checksums (default true; the header checksum is always checked)
name: string?, -- the file name (the api passes it): names the entry
maxBytes: number?, -- default 2^30
verify: boolean?, -- default true; the header checksum is always checked
name: string?,
}
export type EncodeOptions = {
blockSize: number?, -- 65536, 262144, 1048576 or 4194304 (default 4 MB, as the lz4 tool)
blockChecksum: boolean?, -- default false
contentChecksum: boolean?, -- default true
contentSize: boolean?, -- store the content size (default false)
contentSize: boolean?, -- default false
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -71,7 +65,6 @@ end
type Out = { buf: buffer, n: number, max: number }
-- room for k more bytes in the output (doubling, up to max) | false
local function room(out: Out, k: number): boolean
local need = out.n + k
if need > out.max then
@@ -85,7 +78,6 @@ local function room(out: Out, k: number): boolean
return true
end
-- one LZ4 frame at p -> the input offset after it | nil, Err
local function frame(b: buffer, p: number, e: number, out: Out, verify: boolean): (number?, Err.Err?)
if p + 7 > e then
return nil, Err.new(Err.TRUNCATED, "frame header past the end", p)
@@ -210,7 +202,6 @@ local function legacy(b: buffer, p: number, e: number, out: Out): (number?, Err.
return q, nil
end
-- decompress(buf, offset?, length?, opts?) -> the data of every frame | nil, Err
function Lz4Format.decompress(src: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (buffer?, Err.Err?)
local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length)
if not b then
@@ -280,7 +271,6 @@ function Lz4Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?
end
-- ------------------------------------------------------------------------------------------------ encode
-- compress(data, opts?) -> one LZ4 frame | nil, Err
function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffer?, Err.Err?)
local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil)
if not b then
@@ -341,7 +331,6 @@ function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffe
return w:finish(), nil
end
-- encode(value, opts?): a buffer / string, an Archive's one file, or a tar of the Archive's entries, as one frame
function Lz4Format.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local data, err = Archive.streamData(value)
if not data then
+4 -9
View File
@@ -1,11 +1,7 @@
--!strict
-- archive/macbinary: MacBinary I, II and III files (a 128-byte header with the name, type / creator, Finder flags,
-- dates and fork lengths, then the data and resource forks padded to 128 bytes, then the Get Info comment). II / III
-- headers carry a CRC-16/XMODEM (verified: Err.CHECKSUM), III the 'mBIN' signature; MacBinary I is recognised by its
-- zero bytes and sane lengths. Decodes to an Archive in the containers/MacFile convention (the data fork is the entry
-- `name`, a resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime /
-- comment); writes MacBinary III (readable as II) from any Archive's first Mac file or a buffer. Written from the
-- MacBinary II / III specifications (Yves Lempereur et al.). Not supported: the secondary header's content (skipped).
-- archive/macbinary: MacBinary I / II / III (128-byte header, forks padded to 128, Get Info comment; II / III
-- CRC-16/XMODEM, III 'mBIN'), from the MacBinary II / III specs (Lempereur et al.), as containers/MacFile.
-- Supports: read, write III. Not supported: the secondary header's content (skipped).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,10 +21,9 @@ local MacBinary = {
}
export type DecodeOptions = { maxBytes: number? } -- default 2^30
export type EncodeOptions = { name: string? } -- the name of a buffer / string value (default "data")
export type EncodeOptions = { name: string? }
-- ------------------------------------------------------------------------------------------------ sniff
-- version(b, o, len) -> "III" / "II" / "I" / nil: which MacBinary header sits at o
local function version(b: buffer, o: number, len: number): string?
if len < 128 then
return nil
+5 -7
View File
@@ -1,9 +1,7 @@
--!strict
--!native
-- archive/mpq/Crypt: the MPQ encryption table, the name hash (types 0 = table index, 1 / 2 = name check, 3 = file
-- key) and block decryption in place. Written from the MPQ format description (Justin Olbrantz / Jean-Francois
-- Roy, "The MoPaQ Archive Format"; StormLib's documentation); no code taken. All arithmetic is mod 2^32 and every
-- value handed to bit32 is an integer in 0..2^32 - 1 (both runtimes agree).
-- archive/mpq/Crypt: the MPQ encryption table, name hash (0 = table index, 1 / 2 = name check, 3 = file key) and
-- block decryption, from "The MoPaQ Archive Format" (Olbrantz / Roy) and StormLib's docs; no code taken. Mod 2^32.
local readu32, writeu32 = buffer.readu32, buffer.writeu32
local bxor, band, bor, lshift, rshift, bnot = bit32.bxor, bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.bnot
@@ -26,7 +24,7 @@ do
end
end
-- hash(name, kind) -> u32: ASCII upper case, '/' as '\'
-- name hash: ASCII upper case, '/' as '\'
function Crypt.hash(name: string, kind: number): number
local s1, s2 = 0x7FED7FED, 0xEEEEEEEE
local base = kind * 0x100
@@ -43,7 +41,7 @@ function Crypt.hash(name: string, kind: number): number
return s1
end
-- decrypt(buf, at, n, key): n bytes (whole u32s; a trailing partial word is left as is) at buf[at..] in place
-- whole u32s; a trailing partial word is left as is
function Crypt.decrypt(buf: buffer, at: number, n: number, key: number)
local s2 = 0xEEEEEEEE
local k = key % TWO32
@@ -57,7 +55,7 @@ function Crypt.decrypt(buf: buffer, at: number, n: number, key: number)
end
end
-- base name of an archived path (the file key uses it)
-- the file key uses the base name
function Crypt.baseName(name: string): string
return string.match(name, "([^\\/]*)$") or name
end
+5 -20
View File
@@ -1,16 +1,7 @@
--!strict
-- archive/mpq: Blizzard MPQ archives (MoPaQ: Diablo, StarCraft, Warcraft II / III, WoW, StarCraft II), read into the
-- standard Archive. Supports: header versions 1-4 with the classic hash and block tables (encrypted, found at offset
-- 0, at any 512-byte boundary (prefixed archives / installers) or through the "MPQ\x1B" user data header), the hi-block
-- table (files past 4 GB), names from "(listfile)" (plus opts.names), unnamed files as "File00000123.xxx" (block
-- index), encrypted files (key from the name, MPQ_FILE_FIX_KEY), sector offset tables, single-unit files, imploded
-- files (codecs/compress/Explode), compressed sectors: zlib (codecs/compress/Deflate), PKWARE DCL implode, bzip2
-- (codecs/compress/Bzip2), LZMA (codecs/compress/Lzma), sparse, and combinations; deleted and delete-marker blocks
-- are skipped. Written from the MPQ format description (Justin Olbrantz / Jean-Francois Roy, "The MoPaQ Archive
-- Format", and StormLib's documentation); no code taken.
-- Not supported (Err.UNSUPPORTED on read): Huffman and IMA ADPCM sectors (WAVE files), patch files, the HET / BET
-- tables of archives without classic tables, encrypted files whose name is unknown, compressed hash / block tables,
-- writing.
-- archive/mpq: Blizzard MPQ ("The MoPaQ Archive Format", Olbrantz / Roy; StormLib docs; no code taken). Supports:
-- header v1-4, hash / block / hi-block tables, prefixed archives, (listfile), encrypted files, imploded and zlib /
-- PKWARE / bzip2 / LZMA / sparse sectors. Not supported: Huffman / ADPCM sectors, patch files, HET / BET, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -34,9 +25,9 @@ local Mpq = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
names: { string }?, -- extra file names to look up (beside the archive's own "(listfile)")
names: { string }?,
maxEntries: number?, -- default 1e6
maxBytes: number?, -- the largest file read (default 2^30)
maxBytes: number?, -- default 2^30
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -85,7 +76,6 @@ local function unsparse(b: buffer, at: number, n: number, want: number): (buffer
return out, nil
end
-- one compressed sector (mask byte first) -> want bytes
local function decompress(b: buffer, at: number, n: number, want: number): (buffer?, Err.Err?)
if n < 1 then
return nil, Err.new(Err.CORRUPT, "empty compressed sector")
@@ -151,7 +141,6 @@ end
type Block = { offset: number, csize: number, size: number, flags: number }
-- read a file's bytes (the archive buffer, the absolute block offset, the file name for the key)
local function readFile(b: buffer, limit: number, blk: Block, at: number, name: string?, sectorSize: number, maxBytes: number): (buffer?, Err.Err?)
local flags = blk.flags
if band(flags, FLAG_PATCH) ~= 0 then
@@ -250,7 +239,6 @@ local function encode(_archive: any, _opts: any?): (buffer?, Err.Err?)
return nil, Err.new(Err.UNSUPPORTED, "MPQ archives are read-only")
end
-- the header: its absolute offset in r (0, a 512-byte boundary, or behind "MPQ\x1B") | nil
local function findHeader(r: Bytes.Reader): number?
local size = r.limit - r.base
local p = 0
@@ -328,7 +316,6 @@ function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 30
local mask = hashCount - 1
local pow2 = band(hashCount, mask) == 0
-- lookup(name) -> block index (1-based) | nil
local function lookup(name: string): number?
local h0, h1, h2 = Crypt.hash(name, 0), Crypt.hash(name, 1), Crypt.hash(name, 2)
local start = if pow2 then band(h0, mask) else h0 % hashCount
@@ -352,7 +339,6 @@ function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local blk = blocks[bi]
return readFile(r.buf, r.limit, blk, r.base + h + blk.offset, name, sectorSize, maxBytes)
end
-- names: (listfile) and opts.names
local names: { string } = {}
for _, internal in { "(attributes)", "(signature)", "(user data)" } do
table.insert(names, internal)
@@ -413,7 +399,6 @@ function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- hash(name, kind) -> the MPQ name hash (kind 0 = table index, 1 / 2 = name checks, 3 = file key)
Mpq.hash = Crypt.hash
return Mpq
+3 -6
View File
@@ -1,9 +1,7 @@
--!strict
-- archive/pak: Quake / Quake II / Half-Life PAK archives ("PACK": 56-byte names, 64-byte directory entries) and the
-- SiN variant ("SPAK": 120-byte names), read into the standard Archive (entries read lazily: a copy of the stored
-- bytes) and written from any Archive value. Written from the format description in the Quake source release
-- (common.c: dpackheader_t / dpackfile_t) and the Quake specs; no code taken.
-- Not supported: Daikatana's compressed PAK entries.
-- archive/pak: Quake / Quake II / Half-Life PAK ("PACK": 56-byte names, 64-byte entries) and SiN ("SPAK": 120-byte
-- names), from Quake's common.c (dpackheader_t / dpackfile_t) and the Quake specs; no code taken. Supports: read
-- (lazy), write. Not supported: Daikatana's compressed entries.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -125,7 +123,6 @@ function Pak.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new(variant?) -> an empty PAK Archive: a:add(name, data); a:write()
function Pak.new(variant: ("quake" | "sin")?): any
local a = Archive.new("pak", encode)
a.meta.source = { format = "pak", variant = variant or "quake" }
+4 -15
View File
@@ -1,13 +1,7 @@
--!strict
-- archive/rpm: RPM packages (format v3 / v4), read into the standard Archive value. The 96-byte lead, the signature
-- header (padded to 8 bytes) and the main header are parsed (every tag into meta.rpm.tags; the common ones by name in
-- meta.rpm); the file list comes from the header (dirnames / basenames / dirindexes, or the old filenames tag, with
-- sizes / long sizes, modes, mtimes, link targets, owners) and lists without touching the payload. The payload
-- (gzip / bzip2 / xz / lzma / zstd or none, through codecs/compress/*) is decompressed on the first read and parsed
-- as a cpio archive (containers/Cpio); entry names drop the leading "./" and "/". Ghost files (%ghost) are not
-- listed (they are not in the payload). Written from the RPM file format documentation (rpm.org, the LSB package
-- format chapter); no code ported. Not supported: writing, signature / digest verification, the "stripped cpio"
-- payload of packages with files over 4 GiB (Err.UNSUPPORTED on read), delta rpms.
-- archive/rpm: RPM v3 / v4 (rpm.org, LSB package format; no code ported): 96-byte lead, signature header (8-byte
-- aligned), main header; the payload (gzip / bzip2 / xz / lzma / zstd / none) is cpio; %ghost files not listed.
-- Not supported: writing, signature / digest checks, "stripped cpio" (files over 4 GiB), delta rpms.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -30,7 +24,7 @@ local Rpm = {
}
export type DecodeOptions = {
maxBytes: number?, -- the largest decompressed payload (default 2^30)
maxBytes: number?, -- default 2^30
maxEntries: number?, -- default 1e6
}
@@ -39,7 +33,6 @@ local LEAD_MAGIC = "\237\171\238\219"
local HEADER_MAGIC = "\142\173\232\1"
local RPMFILE_GHOST = 64
-- the tags meta.rpm names
local NAMES: { [number]: string } = {
[1000] = "name",
[1001] = "version",
@@ -73,7 +66,6 @@ function Rpm.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- a header structure at p -> { [tag] = value }, end offset | nil, Err
local function header(b: buffer, p: number, e: number): (any, any)
if p + 16 > e then
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
@@ -146,7 +138,6 @@ local function header(b: buffer, p: number, e: number): (any, any)
return tags, se
end
-- the file list of the header: { name, size, mode, mtime, link, user, group, flags }
local function files(tags: { [number]: any }): { any }
local names: { string } = {}
local bn, dn, di = tags[1117], tags[1118], tags[1116]
@@ -181,7 +172,6 @@ local function strip(name: string): string
return (string.gsub(name, "^%.?/+", ""))
end
-- the payload: decompressed, then its cpio entries by stripped name
local function payload(b: buffer, p: number, e: number, compressor: string?, o: DecodeOptions): (any, Err.Err?)
local n = e - p
local opts: any = { maxBytes = o.maxBytes or 2 ^ 30 }
@@ -313,7 +303,6 @@ function Rpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- cpio(r, opts?) -> the decompressed payload (a cpio archive, as rpm2cpio prints it) | nil, Err
function Rpm.cpio(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?)
local a, err = Rpm.decode(r, opts)
if not a then
+2 -6
View File
@@ -1,9 +1,6 @@
--!strict
-- archive/tar: tar archives (ustar, pax, GNU long names; see containers/Tar), read into the standard Archive value
-- (entries read lazily: a copy of the stored bytes) and written from any Archive value (a tar, a zip, a 7z: list() +
-- read()). Compressed tars (.tar.gz / .tgz / .tar.zst / .tar.xz / .tar.bz2 / .tar.br) load through the api, which
-- unwraps the single-stream archive and sniffs again (meta.compression names the outer format).
-- Not supported: sparse files, multi-volume archives.
-- archive/tar: tar archives (ustar, pax, GNU long names; containers/Tar). Supports: read (lazy), write from any
-- Archive. Not supported: sparse files, multi-volume archives.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -110,7 +107,6 @@ function TarFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty tar Archive: a:add(name, data, { mtime, mode, dir }); a:write()
function TarFormat.new(): any
local a = Archive.new("tar", encode)
a.meta.source = { format = "tar" }
+6 -14
View File
@@ -1,11 +1,7 @@
--!strict
-- archive/uu: uuencoded, xxencoded and GNU "begin-base64" text as an Archive: every "begin <mode> <name>" block of a
-- text (mail, news, shar parts: the text around the blocks is ignored) is one entry (entry.mode = the octal mode);
-- one block makes a single-stream archive (meta.stream: the api unwraps a uuencoded .tar.gz). The variant of each
-- block (uu / xx / base64) is detected from its characters and line lengths and kept in entry.variant and
-- meta.source.variant. Written from the POSIX uuencode description and the xxencode alphabet; written as GNU sharutils
-- does (45 bytes a line, "`" for zero, base64 lines of 60 characters + "===="). Not supported: multi-part postings
-- split over several files (concatenate the parts first), yEnc (archive/yenc), BinHex (archive/binhex).
-- archive/uu: uuencode (POSIX), xxencode and GNU "begin-base64" blocks, one entry each (variant detected per block);
-- written as GNU sharutils does (45 bytes a line, "`" for zero; base64 60 characters + "===="). Not supported: postings
-- split over several files, yEnc (archive/yenc), BinHex (archive/binhex).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -23,11 +19,11 @@ local Uu = {
caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } },
}
export type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30
export type DecodeOptions = { maxBytes: number?, name: string? } -- default 2^30
export type EncodeOptions = {
variant: ("uu" | "xx" | "base64")?, -- default "uu"
mode: number?, -- file mode when the entry has none (default 0o644)
name: string?, -- the name of a buffer / string value (default "data")
mode: number?, -- default 0o644
name: string?,
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -50,7 +46,6 @@ function Uu.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the value of character c in a variant, or nil
local function value(c: number, xx: boolean): number?
if xx then
return XX_VALUE[c]
@@ -61,7 +56,6 @@ local function value(c: number, xx: boolean): number?
return nil
end
-- does a data line fit the variant: every character valid and the length matching the count character
local function fits(line: string, xx: boolean): boolean
local n = value(string.byte(line, 1) or 0, xx)
if not n then
@@ -79,7 +73,6 @@ local function fits(line: string, xx: boolean): boolean
return true
end
-- decode the uu / xx lines of a block into a buffer (nil, message on a bad line)
local function decodeLines(lines: { string }, xx: boolean, maxBytes: number): (buffer?, string?)
local total = 0
for _, l in lines do
@@ -266,7 +259,6 @@ function Uu.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty uu Archive: a:add(name, data, { mode }); a:write({ variant })
function Uu.new(): any
local a = Archive.new("uu", encoder)
a.meta.source = { format = "uu" }
+6 -14
View File
@@ -1,13 +1,7 @@
--!strict
-- archive/vpk: Valve VPK archives (Source / Source 2: version 1 and 2 directory files, "pak01_dir.vpk"), read into the
-- standard Archive and written from any Archive value. Reading: the extension / path / name tree, preload bytes
-- (stored in the tree) followed by the data, data embedded in the directory file (archive index 0x7fff) or in the
-- numbered part files "<name>_NNN.vpk", found through opts.resolve(fileName) / opts.files[fileName] (the name comes
-- from opts.name, "x_dir.vpk" -> "x_000.vpk", default "pak01"); each entry's CRC-32 is checked on read; version 2's
-- MD5 section is kept in meta. Writing: one self-contained directory file (every entry embedded, no preload),
-- version 2 by default with its tree / chunk / file MD5s (version = 1 for the older header). Written from the
-- Valve Developer Community VPK file format page; no code taken.
-- Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives.
-- archive/vpk: Valve VPK v1 / v2 directory files (Valve Developer Community page; no code taken): preload bytes,
-- embedded (index 0x7fff) or part-file data ("<name>_NNN.vpk"), CRC-32 checked; writes one self-contained v2 file
-- with its MD5s. Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -29,10 +23,10 @@ local Vpk = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
verify: boolean?, -- check each entry's CRC-32 on read (default true)
resolve: ((name: string) -> (buffer | string)?)?, -- the part files ("pak01_000.vpk", ...)
verify: boolean?, -- default true
resolve: ((name: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
name: string?, -- the directory file's name ("pak01_dir.vpk"), for the part file names
name: string?, -- "pak01_dir.vpk" -> "pak01_000.vpk"
maxEntries: number?, -- default 1e6
}
export type EncodeOptions = { version: number? } -- 1 or 2 (default: the source's, else 2)
@@ -55,7 +49,6 @@ local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
return Vpk.encode(archive, opts)
end
-- the part file `index` as a buffer (cached per archive)
local function partLoader(opts: DecodeOptions?): (number) -> (buffer?, Err.Err?)
local cache: { [number]: buffer } = {}
local prefix = "pak01"
@@ -307,7 +300,6 @@ function Vpk.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new(version?) -> an empty VPK Archive (version 2 by default): a:add(name, data); a:write()
function Vpk.new(version: number?): any
local a = Archive.new("vpk", encode)
a.meta.source = { format = "vpk", version = version or 2 }
+5 -18
View File
@@ -1,12 +1,7 @@
--!strict
-- archive/wad/Map: a Doom / Heretic / Hexen map (the binary lumps after a map marker: THINGS, LINEDEFS, SIDEDEFS,
-- VERTEXES, SECTORS; Hexen format when BEHAVIOR is present) parsed into plain tables (Map.parse) and built into a
-- Scene (Map.scene): sector floors and ceilings (sector outlines chained from the linedefs, triangulated with
-- codecs/model/Polygon), walls (one-sided middles; lower / upper walls and masked middles of two-sided lines, the
-- sky hack between two sky ceilings) with the vanilla texture alignment (x / y offsets, upper / lower unpegged), one
-- primitive per flat / wall texture, things as child nodes standing on their sector's floor. Units are map units, z
-- up. Written from the Unofficial Doom Specs and the Hexen specs; no code taken. UDMF (TEXTMAP) maps are not
-- supported.
-- archive/wad/Map: Doom / Heretic / Hexen binary map lumps (Hexen when BEHAVIOR is present) to tables and a Scene, with
-- vanilla texture alignment (offsets, unpegged) and the sky hack; z up, map units. From the Unofficial Doom Specs and
-- the Hexen specs; no code taken. Not supported: UDMF (TEXTMAP).
local Types = require("@rosetta/Types")
local Polygon = require("@rosetta/codecs/model/Polygon")
@@ -29,7 +24,6 @@ export type MapData = {
vertices: { number }, -- x1, y1, x2, y2, ...
sectors: { Sector },
}
-- texture sizes / images by kind ("flat" | "texture") and name: what the WAD knows
export type Textures = {
size: (kind: string, name: string) -> (number?, number?),
image: ((kind: string, name: string) -> Types.Image?)?,
@@ -46,7 +40,6 @@ local function side(v: number): number?
return if v == 0xFFFF then nil else v + 1
end
-- parse(lumps, hexen) -> MapData | nil, message: lumps = { THINGS, LINEDEFS, SIDEDEFS, VERTEXES, SECTORS } (Lump)
function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string?)
for _, k in { "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" } do
if not lumps[k] then
@@ -144,9 +137,8 @@ function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string
end
-- ------------------------------------------------------------------------------------------------ sector outlines
-- loops(m) -> loops[sector] = { { vertex ids } }: each sector's edges (front sides v1 -> v2, back sides v2 -> v1;
-- lines with the sector on both sides left out) chained into closed loops, taking the sharpest right turn at forks;
-- chains that do not close are dropped
-- sector loops: front sides v1 -> v2, back sides v2 -> v1, lines with the sector on both sides left out; the sharpest
-- right turn at forks; unclosed chains dropped
local function loops(m: MapData): { [number]: { { number } } }
local edges: { [number]: { { number } } } = {}
local nv = #m.vertices // 2
@@ -247,7 +239,6 @@ type Batch = { kind: string, name: string, pos: { number }, nrm: { number }, uv:
local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4
-- scene(m, tex, name) -> Scene
function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene
local batches: { [string]: Batch } = {}
local order: { string } = {}
@@ -269,7 +260,6 @@ function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene
end
local V = m.vertices
local nv = #V // 2
-- floors and ceilings
local secLoops = loops(m)
for sec, ls in secLoops do
local s = m.sectors[sec]
@@ -301,7 +291,6 @@ function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene
end
end
end
-- walls
local function quad(tname: string, x1: number, y1: number, x2: number, y2: number, zb: number, zt: number, xoff: number, len: number, texTop: number, yoff: number)
if tname == "-" or tname == "" or zt <= zb then
return
@@ -363,7 +352,6 @@ function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene
end
end
end
-- the scene
local scene = Scene.new()
scene.meta.up = "z"
local mesh: Types.Mesh = { name = name, primitives = {} }
@@ -410,7 +398,6 @@ function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene
table.insert(scene.meshes, mesh)
scene.nodes[1] = { name = name, children = {}, mesh = 1 }
scene.roots[1] = 1
-- things, on the floor of the sector under them
for i, th in m.things do
local z = th.z or 0
for sec, ls in secLoops do
+3 -12
View File
@@ -1,16 +1,12 @@
--!strict
--!native
-- archive/wad/Picture: Doom graphics lumps to rgba8 through a u32 palette (Pixels.palette of PLAYPAL): the column
-- "picture" format of patches, sprites and menu graphics (width, height, left / top offsets, column offsets, posts of
-- topdelta / length / pad / pixels / pad; DeePsea tall patches: a topdelta not above the previous one is relative)
-- and raw flats (64 x 64, 64 x 128, 128 x 128, 256 x 256, Heretic's 64 x 65 / 64 x 200 and any w x 64 strip).
-- Transparent picture pixels are 0 (alpha 0). Written from the Unofficial Doom Specs and the Doom source release's
-- r_data.c description; no code taken. Never throws: every read is checked against the lump's end.
-- archive/wad/Picture: Doom picture lumps (column posts: topdelta / length / pad / pixels / pad; DeePsea tall patches:
-- a topdelta not above the previous is relative) and raw flats to rgba8, from the Unofficial Doom Specs and r_data.c;
-- no code taken. Transparent pixels are 0.
local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32
local Picture = {}
-- valid(b, at, n) -> width, height, left, top when the lump looks like a picture (every column offset inside it)
function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number)
if n < 8 then
return nil, 0, 0, 0
@@ -28,7 +24,6 @@ function Picture.header(b: buffer, at: number, n: number): (number?, number, num
return w, h, readi16(b, at + 4), readi16(b, at + 6)
end
-- decode(b, at, n, pal, out) -> true | false, message: the picture's pixels into out (w * h * 4 bytes, zeroed)
function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?)
local stop = at + n
for x = 0, w - 1 do
@@ -63,7 +58,6 @@ function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buff
return true, nil
end
-- flatSize(n) -> width, height of a raw flat of n bytes (nil when no shape fits)
function Picture.flatSize(n: number): (number?, number)
if n == 4096 then
return 64, 64
@@ -84,15 +78,12 @@ function Picture.flatSize(n: number): (number?, number)
return nil, 0
end
-- flat(b, at, w, h, pal, out): raw indexes, row by row
function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer)
for i = 0, w * h - 1 do
writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4))
end
end
-- blit(src, sw, sh, dst, dw, dh, ox, oy): the non-transparent pixels of an rgba8 image onto another at (ox, oy),
-- clipped (composite wall textures from patches)
function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number)
local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1
for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do
+11 -37
View File
@@ -1,20 +1,7 @@
--!strict
-- archive/wad: Doom-engine WAD files (IWAD / PWAD: Doom, Heretic, Hexen, Strife, Freedoom, ...), read into the
-- standard Archive and written from any Archive value, plus the lumps as game data:
-- Wad.lumps(a) every lump in file order with its namespace (sprites / patches / flats / ...) and map
-- Wad.palette(a, i?) PLAYPAL palette i (default 0) as a u32 palette buffer
-- Wad.image(a, name) a flat, patch, sprite or graphic (the column picture format) as an rgba8 Image
-- (meta.offset = { left, top } for pictures; transparent pixels alpha 0)
-- Wad.texture(a, name) a wall texture composed from its patches (TEXTURE1 / TEXTURE2 + PNAMES)
-- Wad.maps(a) Wad.mapData(a, name) Wad.map(a, name, opts)
-- the maps; their things / linedefs / sidedefs / vertices / sectors as tables; a Scene
-- (floors, ceilings and walls per texture, things as nodes: archive/wad/Map)
-- Entry names: the lump names, except lumps of a map, named "<map>/<lump>" ("MAP01/THINGS"), and later lumps
-- repeating an earlier name, named "<name>~<n>" (n = 2, 3, ...), so every entry is unique; writing strips both again
-- (the last path component, without its "~n", upper-cased, at most 8 bytes). Written from the Unofficial Doom
-- Specs (Matthew Fell) and the Doom source release's w_wad.c / r_data.c description; no code taken.
-- Not supported: UDMF (TEXTMAP) map geometry (its lumps are listed and readable), Strife's TEXTURE format variant,
-- big-endian (Jaguar) WADs, compressed Jaguar lumps.
-- archive/wad: Doom-engine WADs (IWAD / PWAD; Unofficial Doom Specs, w_wad.c / r_data.c; no code taken), plus lumps,
-- palettes, pictures, wall textures and maps. Entry names: "<map>/<lump>", repeats "<name>~<n>". Not supported: UDMF
-- geometry (lumps listed), Strife's TEXTURE variant, big-endian (Jaguar) WADs, compressed Jaguar lumps.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -39,18 +26,18 @@ local Wad = {
export type DecodeOptions = { maxEntries: number? } -- default 1e6
export type EncodeOptions = { type: ("IWAD" | "PWAD")? } -- default: the source's, else "PWAD"
export type Lump = {
name: string, -- the lump name as stored (upper case)
entry: string, -- the Archive entry name
index: number, -- 1-based position in the directory
name: string,
entry: string,
index: number,
offset: number,
size: number,
namespace: string?, -- "sprites" | "patches" | "flats" | "colormaps" | "textures" (between *_START / *_END markers)
map: string?, -- the map this lump belongs to
namespace: string?, -- between *_START / *_END markers
map: string?,
marker: boolean?, -- a zero-size marker (F_START, MAP01, ...)
}
export type MapOptions = {
textures: boolean?, -- build texture images (flats / composed wall textures) into scene.textures (default true)
palette: number?, -- PLAYPAL palette index (default 0)
textures: boolean?, -- default true
palette: number?, -- default 0
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -139,7 +126,6 @@ function Wad.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
if isMapMarker then
map, udmf = name, nextName == "TEXTMAP"
end
-- namespaces
local marker: boolean = false
local pre = string.match(name, "^(%w+)_START$")
local post = string.match(name, "^(%w+)_END$")
@@ -215,7 +201,7 @@ local function info(a: any): any
return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil
end
-- the last lump named name (PWAD order: later lumps override), preferring namespace ns when given
-- the last lump named name (PWAD order: later lumps override)
local function find(w: any, name: string, ns: string?): Lump?
local up = string.upper(name)
local best: Lump? = nil
@@ -238,20 +224,17 @@ local function find(w: any, name: string, ns: string?): Lump?
return best
end
-- new(type?) -> an empty WAD Archive ("PWAD" by default): a:add(name, data); a:write()
function Wad.new(kind: ("IWAD" | "PWAD")?): any
local a = Archive.new("wad", encode)
a.meta.source = { format = "wad", type = kind or "PWAD" }
return a
end
-- lumps(a) -> { Lump } in directory order (nil when a is not a decoded WAD)
function Wad.lumps(a: any): { Lump }?
local w = info(a)
return w and w.lumps
end
-- palette(a, index?) -> a 256-entry u32 palette (Pixels layout) from PLAYPAL | nil, Err
function Wad.palette(a: any, index: number?): (buffer?, Err.Err?)
local w = info(a)
if not w then
@@ -265,8 +248,6 @@ function Wad.palette(a: any, index: number?): (buffer?, Err.Err?)
return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil
end
-- image(a, name, opts?) -> an rgba8 Image of a flat (in the flats namespace) or a picture (patch, sprite, graphic)
-- | nil, Err. opts.palette: the PLAYPAL index (default 0); opts.kind: "flat" | "picture" to force the decoding.
function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? }?): (Types.Image?, Err.Err?)
local w = info(a)
if not w then
@@ -307,7 +288,6 @@ function Wad.image(a: any, name: string, opts: { palette: number?, kind: string?
return img, nil
end
-- the texture definitions (TEXTURE1 + TEXTURE2 with PNAMES): name -> { width, height, patches = { { x, y, patch } } }
local function textureDefs(w: any): { [string]: any }
if w.textures then
return w.textures
@@ -359,7 +339,6 @@ local function textureDefs(w: any): { [string]: any }
return defs
end
-- texture(a, name, opts?) -> the composed rgba8 Image of a wall texture | nil, Err (opts.palette)
function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types.Image?, Err.Err?)
local w = info(a)
if not w then
@@ -383,7 +362,6 @@ function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types.
return img, nil
end
-- maps(a) -> { map names } in file order
function Wad.maps(a: any): { string }
local w = info(a)
local out: { string } = {}
@@ -399,7 +377,6 @@ function Wad.maps(a: any): { string }
return out
end
-- mapData(a, name) -> Map.MapData (things, linedefs, sidedefs, vertices, sectors as tables, 1-based references)
function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?)
local w = info(a)
if not w then
@@ -425,9 +402,6 @@ function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?)
return m, nil
end
-- map(a, name, opts?) -> a Scene of the map (z up, map units): one primitive per flat / wall texture (materials and
-- textures named after them; texture.image when opts.textures ~= false and the WAD holds it), things as child nodes
-- (extras.thing = { type, angle, flags, ... }); meta.source.map = the MapData
function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?)
local m, err = Wad.mapData(a, name)
if not m then
+4 -7
View File
@@ -1,10 +1,7 @@
--!strict
-- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") files, read as single-stream archives holding one
-- entry (the decompressed data). Built on codecs/compress/Lzma. Supports: concatenated streams, stream padding, every block
-- layout, checks none / CRC-32 / CRC-64 (verified; SHA-256 is not verified), filters LZMA2, delta and the BCJ filters
-- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") as single-stream archives (codecs/compress/Lzma).
-- Supports: concatenated streams, padding, checks none / CRC-32 / CRC-64 (SHA-256 unverified), LZMA2, delta, BCJ
-- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters.
-- The entry is named after the file (opts.name without .xz / .lzma; .txz -> .tar), else "data". meta.stream = true:
-- the api unwraps an inner archive (a .tar.xz loads as the tar).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,8 +21,8 @@ local Xz = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse output larger than this (default 2^30)
name: string?, -- the file name (the api passes it): names the entry
maxBytes: number?, -- default 2^30
name: string?,
}
-- ------------------------------------------------------------------------------------------------ constants
+6 -13
View File
@@ -1,11 +1,7 @@
--!strict
-- archive/yenc: yEnc-encoded binaries (yEnc 1.3: =ybegin / =ypart / =yend, byte + 42 with "=" escapes) as an Archive:
-- every =ybegin block is a file; the parts of a multi-part file found in the same text are joined at their =ypart
-- begin offsets. The part CRC (pcrc32) and, once all parts are there, the file CRC (crc32) and size are verified
-- (Err.CHECKSUM / Err.CORRUPT); missing parts leave a short file with meta.incomplete listing it. One file makes a
-- single-stream archive (meta.stream). Written from the yEnc 1.3 draft (Jürgen Helbing); writing produces one
-- single-part block per file with 128-character lines, escaping NUL, LF, CR, "=" and a leading / trailing TAB, space
-- or ".", as uuenview / yencode do. Not supported: joining parts spread over several files (concatenate them first).
-- archive/yenc: yEnc 1.3 (=ybegin / =ypart / =yend, byte + 42, "=" escapes; Jürgen Helbing's draft): parts in one text
-- joined, pcrc32 / crc32 / size verified; writes one 128-character-line part per file, escaping NUL, LF, CR, "=" and a
-- leading / trailing TAB, space or ".", as uuenview / yencode do. Not supported: parts spread over several files.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -23,10 +19,10 @@ local Yenc = {
caps = { decode = true, encode = true, multipart = true },
}
export type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30
export type DecodeOptions = { maxBytes: number?, name: string? } -- default 2^30
export type EncodeOptions = {
line: number?, -- characters per line (default 128)
name: string?, -- the name of a buffer / string value (default "data")
line: number?, -- default 128
name: string?,
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -53,7 +49,6 @@ local function fields(line: string): { [string]: string }
return f
end
-- decode the data lines [i, j) of src into out at o; returns the new o (stops at the end of out)
local function decodeData(src: buffer, i: number, j: number, out: buffer, o: number): number
local lim = buffer.len(out)
local esc = false
@@ -78,7 +73,6 @@ local function decodeData(src: buffer, i: number, j: number, out: buffer, o: num
return o
end
-- count the decoded bytes of the data lines [i, j)
local function countData(src: buffer, i: number, j: number): number
local n, esc = 0, false
for p = i, j - 1 do
@@ -267,7 +261,6 @@ function Yenc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty yEnc Archive: a:add(name, data); a:write({ line })
function Yenc.new(): any
local a = Archive.new("yenc", encoder)
a.meta.source = { format = "yenc" }
+5 -9
View File
@@ -1,9 +1,7 @@
--!strict
-- archive/z: Unix compress files (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream Archive: one
-- entry, named after the file without .Z (.taz / .tZ -> .tar), else "data"; meta.stream = true, so the api unwraps a
-- .tar.Z into the tar. Writing: an Archive with one file entry (or a buffer / string) becomes that file compressed,
-- byte for byte what ncompress writes; an Archive with several entries is written as a tar inside (a .tar.Z). The LZW is
-- codecs/compress/UnixCompress. Not supported: pack (.z, 1F 1E) and compact (1F FF) files.
-- archive/z: Unix compress (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream archive of one
-- entry (codecs/compress/UnixCompress). Supports: read; write byte for byte as ncompress (several entries: a .tar.Z).
-- Not supported: pack (.z, 1F 1E) and compact (1F FF) files.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -22,8 +20,8 @@ local Z = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse output larger than this (default 2^30)
name: string?, -- the file name (the api passes it): names the entry
maxBytes: number?, -- default 2^30
name: string?,
}
export type EncodeOptions = {
maxBits: number?, -- 9..16 (compress -b), default 16
@@ -39,7 +37,6 @@ function Z.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the entry name: the file name without .Z; .taz / .tz name a tar
local function entryName(opts: DecodeOptions): string
local name = Archive.streamName(opts, { "z" })
local stem, ext = string.match(name, "^(.+)%.(%w+)$")
@@ -84,7 +81,6 @@ function Z.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new(data?, name?) -> a .Z Archive holding one entry
function Z.new(data: (buffer | string)?, name: string?): any
local a = Archive.new("z", encode)
a.meta.stream = true
+4 -25
View File
@@ -1,18 +1,7 @@
--!strict
-- archive/zip: ZIP archives as the standard Archive (Types.Archive: list / read / add / write) on containers/Zip.
-- Absorbed from zip-luau 121d4b0 (same author, no third-party code; the reader, now containers/Zip) plus a new
-- writer. Supports: reading stored and deflated entries (CRC-checked), ZIP64, data descriptors, archive comments,
-- prefixed archives (self-extractors), UTF-8 names, case-insensitive / basename lookup; writing stored and deflated
-- entries (codecs/compress/Deflate), unchanged entries copied without recompressing, ZIP64 when needed.
-- Not supported: encryption (traditional PKWARE or AES), compression methods other than store / deflate (bzip2,
-- LZMA, zstd entries are listed but not readable), multi-disk archives.
--
-- local a = Zip.decode(Bytes.reader(buf)) -- or F.archive.load(buf)
-- for _, e in a:list() do print(e.name, e.size, e.method) end
-- local data = a:read("dir/file.txt")
-- a:add("new.txt", "hello", { level = 9 }) -- or { method = "store", mtime = os.time() }
-- local out = a:write({ comment = "made here" }) -- or Zip.encode(a) / F.save(a, nil, { format = "zip" })
-- local b = Zip.create() -- an empty archive
-- archive/zip: ZIP archives on containers/Zip, absorbed from zip-luau 121d4b0 (same author) plus a new writer.
-- Supports: stored / deflated entries (CRC-checked), ZIP64, data descriptors, comments, self-extractors, UTF-8 names;
-- writing, unchanged entries copied. Not supported: encryption, methods other than store / deflate, multi-disk.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -32,7 +21,7 @@ local Zip = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
verify: boolean?, -- check every entry's CRC-32 on read (default true)
verify: boolean?, -- default true
}
export type AddOptions = Container.AddOptions
export type WriteOptions = Container.FinishOptions
@@ -78,7 +67,6 @@ function Zip.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Archive | nil, Err
function Zip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?)
local zip, err = Container.open(r)
if not zip then
@@ -87,14 +75,11 @@ function Zip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err
return new(zip, not (opts and opts.verify == false)), nil
end
-- create() -> an empty Archive
function Zip.create(): Types.Archive
return new(nil, true)
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(archive, opts?) -> buffer | nil, Err. archive: an Archive (any format's: its entries are read and written
-- here), or a plain table { [name] = buffer | string }.
function Zip.encode(value: any, opts: WriteOptions?): (buffer?, Err.Err?)
if type(value) ~= "table" then
return nil, Err.new(Err.ARG, "encode: needs an Archive or a { name = data } table")
@@ -132,9 +117,7 @@ function Zip.encode(value: any, opts: WriteOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- the Archive methods (Types.Archive)
-- list() -> { ArchiveEntry } in archive order (+ crc32, comment)
function Archive.list(self: any): { Types.ArchiveEntry }
local out = {}
for _, name in self._order do
@@ -165,7 +148,6 @@ function Archive.list(self: any): { Types.ArchiveEntry }
return out
end
-- read(name) -> buffer | nil, Err: an exact name, else the reader's case-insensitive / basename lookup
function Archive.read(self: any, name: string): (buffer?, Err.Err?)
if type(name) ~= "string" then
return nil, Err.new(Err.ARG, "read: name must be a string")
@@ -188,7 +170,6 @@ function Archive.read(self: any, name: string): (buffer?, Err.Err?)
return nil, Err.new(Err.ARG, "no entry " .. name)
end
-- add(name, data, opts?): add or replace an entry (data: buffer or string; nil for a directory "name/")
function Archive.add(self: any, name: string, data: any, opts: AddOptions?)
local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0)
if self._items[name] == nil then
@@ -197,7 +178,6 @@ function Archive.add(self: any, name: string, data: any, opts: AddOptions?)
self._items[name] = { data = b, opts = opts or {} }
end
-- remove(name) -> true when there was such an entry
function Archive.remove(self: any, name: string): boolean
if self._items[name] == nil then
return false
@@ -210,7 +190,6 @@ function Archive.remove(self: any, name: string): boolean
return true
end
-- write(opts?) -> buffer | nil, Err: the archive with every change; unchanged entries are copied as they are
function Archive.write(self: any, opts: WriteOptions?): (buffer?, Err.Err?)
local w = Container.writer()
for _, name in self._order do
+4 -7
View File
@@ -1,10 +1,7 @@
--!strict
-- archive/zoo: Zoo archives (Rahul Dhesi's zoo 1.x / 2.x) read into an Archive: the archive header, the chain of
-- directory entries (type 1, and type 2 with long names, directory names, Unix-style attributes and version numbers),
-- deleted entries skipped, entries stored (method 0), LZW-compressed (method 1: codecs/compress/Lzw "zoo", 13-bit
-- codes) or lzh-compressed (method 2: codecs/compress/Lzh "lh5"); every file's CRC-16 (ARC) is verified when read
-- (Err.CHECKSUM). MS-DOS dates read as UTC. Written from zoo 2.10's file format description (zoo.h / ar.h). Not
-- supported: writing, file generations beyond keeping the newest (older versions of a name get ";<version>").
-- archive/zoo: Zoo 1.x / 2.x (zoo 2.10's zoo.h / ar.h): directory entries type 1 and 2, methods 0 stored, 1 LZW
-- (13-bit), 2 lh5; CRC-16 (ARC) verified; MS-DOS dates as UTC. Not supported: writing, file generations beyond the
-- newest (older versions of a name get ";<version>").
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,7 +22,7 @@ local Zoo = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse an entry larger than this (default 2^30)
maxBytes: number?, -- default 2^30
maxEntries: number?, -- default 65536
}
+5 -6
View File
@@ -1,7 +1,6 @@
--!strict
-- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded
-- through codecs/compress/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else
-- "data". The api unwraps it when the entry is itself an archive (.tar.zst loads as the tar). Read-only.
-- archive/zst: a Zstandard file (.zst, RFC 8878) as a single-stream archive of one entry (codecs/compress/Zstd).
-- Supports: read; the entry is named after the file without its extension (".tzst" -> ".tar"), else "data".
-- Not supported: dictionaries, writing.
-- ------------------------------------------------------------------------------------------------ requires
@@ -21,9 +20,9 @@ local Zst = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse a decompressed size over this (default 2^30)
verify: boolean?, -- check the content checksum (default true)
name: string?, -- the file name, for the entry name (the api passes it)
maxBytes: number?, -- default 2^30
verify: boolean?, -- default true
name: string?,
}
-- ------------------------------------------------------------------------------------------------ sniff
+7 -12
View File
@@ -1,8 +1,7 @@
--!strict
-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams
-- write. Supports: reading AAC-LC through codecs/audio/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected
-- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by
-- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM.
-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3). Supports: AAC-LC via codecs/audio/Aac (1-8
-- channels, every rate), CRC-protected headers, a leading ID3v2 tag, resync, seeking by frame; HE-AAC plays its
-- AAC-LC core. Not supported: writing, ADIF, LATM.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,13 +23,12 @@ local AacFormat = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- refuse streams with more ADTS frames (default 2^22)
maxFrames: number?, -- default 2^22
}
-- ------------------------------------------------------------------------------------------------ constants
local readu8 = buffer.readu8
-- the size of an ID3v2 tag at p (0 if none)
local function id3Size(b: buffer, p: number, limit: number): number
if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then
return 0
@@ -43,7 +41,6 @@ local function id3Size(b: buffer, p: number, limit: number): number
return 10 + s + footer
end
-- a few ID3v2.3 / 2.4 text frames -> tags
local ID3_TAGS: { [string]: string } = {
TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track",
COMM = "comment", TCOM = "composer", TPE2 = "albumartist",
@@ -94,7 +91,6 @@ function AacFormat.sniff(r: Bytes.Reader): number
if not h then
return 0
end
-- a second header right after the first makes it certain
local h2 = Aac.adts(b, p + h.frameSize, limit)
if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then
return 0.9
@@ -103,7 +99,6 @@ function AacFormat.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the frame index: offsets of every ADTS frame (resyncing over garbage)
local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Aac.Adts?, Err.Err?)
local b, limit = r.buf, r.limit
local p = r.base + id3Size(b, r.base, limit)
@@ -112,14 +107,14 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number
while p + 7 <= limit do
local h = Aac.adts(b, p, limit)
if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then
h = nil -- a false sync inside the data
h = nil
end
if not h then
p += 1
continue
end
if p + h.frameSize > limit then
break -- a truncated last frame
break
end
if not first then
first = h
@@ -178,7 +173,7 @@ function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?,
tags = tags,
codec = "aac",
}
-- 1024 frames per ADTS frame; one frame of pre-roll for the overlap when seeking
-- 1024 samples per ADTS frame; one frame of pre-roll for the overlap
return Stream.packets(out, {
count = nframes,
start = function(i: number): number
+10 -13
View File
@@ -1,10 +1,7 @@
--!strict
-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) elementary streams, the .ac3 files of DVD / broadcast rips, through
-- codecs/audio/Ac3 (written from the A/52 specification). Supports: every channel layout (1+1, 1/0 .. 3/2, LFE)
-- output in WAVE order without downmixing, 32 / 44.1 / 48 kHz, every bit rate, coupling, rematrixing, block
-- switching, delta bit allocation, the CRC check, resync over garbage, a truncated last frame (dropped), streaming and
-- exact seeking (one frame of pre-roll for the overlap). Dynamic range control is off by default (`drc` = 0 .. 1).
-- Not supported: writing, E-AC-3 / Dolby Digital Plus (UNSUPPORTED), bsid 9 / 10 reduced-rate streams.
-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) via codecs/audio/Ac3. Supports: every channel layout (WAVE order, no
-- downmix), 32 / 44.1 / 48 kHz, every bit rate, the CRC check, resync, exact seeking; drc 0 .. 1, off by default.
-- Not supported: writing, E-AC-3 (UNSUPPORTED), bsid 9 / 10 reduced-rate streams.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -26,13 +23,13 @@ local Ac3Format = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- refuse streams with more syncframes (default 2^22)
drc: number?, -- dynamic range control scale: 0 = off (default), 1 = full
crc: boolean?, -- check every syncframe's CRC (default true; a bad frame ends the stream with Err.CHECKSUM)
maxFrames: number?, -- default 2^22
drc: number?, -- 0 = off (default), 1 = full
crc: boolean?, -- default true; a bad frame ends the stream with Err.CHECKSUM
}
-- ------------------------------------------------------------------------------------------------ sniff
-- (E-AC-3 streams sniff too, so loading one says UNSUPPORTED instead of an unknown format)
-- E-AC-3 sniffs too, so it reports UNSUPPORTED rather than an unknown format
function Ac3Format.sniff(r: Bytes.Reader): number
local b, p, limit = r.buf, r.pos, r.limit
local h = Ac3.header(b, p, limit)
@@ -47,7 +44,7 @@ function Ac3Format.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the syncframe index (resyncing over garbage: a header counts when the next one follows it, or the data ends)
-- a header counts when the next one follows it, or the data ends
local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Ac3.Header?, Err.Err?)
local b, limit = r.buf, r.limit
local p = r.base
@@ -61,7 +58,7 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number
if h and not first and p + h.frameSize + 8 <= limit then
local h2 = Ac3.header(b, p + h.frameSize, limit)
if not h2 then
h = nil -- a false sync word
h = nil
end
end
if not h then
@@ -77,7 +74,7 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number
end
end
if p + h.frameSize > limit then
break -- a truncated last frame
break
end
table.insert(offs, p)
table.insert(sizes, h.frameSize)
+9 -21
View File
@@ -1,20 +1,8 @@
--!strict
-- audio/adpcm: headerless ADPCM streams (.adpcm / .ima / .vox-style dumps), over codecs/audio/Adpcm. New in
-- rosetta. A raw stream has no header, so nothing identifies it: sniff is always 0, F.detect only finds it by
-- extension, and the layout comes from the options (codec, sampleRate, channels, blockAlign). vgmstream plays such
-- files only through a .txth description and ffmpeg not at all (its adpcm_* codecs need a container), so the codecs
-- here are the layouts those containers use:
-- "ima" IMA nibbles from predictor 0 / step index 0, channels interleaved by nibble, the high nibble first
-- (DVI order, as KVAG / adpcm_ima_ssi); lowFirst = true for the other order
-- "ima_wav" Microsoft IMA blocks (the WAV / AVI data chunk), blockAlign bytes each (default 1024)
-- "ms" Microsoft ADPCM blocks with the 7 standard coefficient pairs (default blockAlign 1024)
-- "ima_qt" Apple ima4 packets (34 bytes per channel, 64 frames), as in AIFF-C / CAF / QuickTime
-- "psx" Sony PS-ADPCM frames (16 bytes, 28 samples), channels interleaved every `interleave` bytes (default 16)
-- Encode: "ima", "ima_wav" and "ms" (from an Audio or a Decoder). Not supported: raw DSP / ADX (their coefficients
-- live in a header: see audio/brstm and audio/adx).
--
-- local a = Adpcm.decode(Bytes.reader(buf), { codec = "ms", sampleRate = 22050, channels = 2, blockAlign = 512 })
-- local raw = Adpcm.encode(a, { codec = "ima" })
-- audio/adpcm: headerless ADPCM (.adpcm / .ima / .vox) via codecs/audio/Adpcm; sniff is 0, the layout comes from opts.
-- "ima": DVI nibbles, high first; "ima_wav": MS IMA blocks; "ms": MS ADPCM, 7 standard coefficient pairs; "ima_qt":
-- Apple ima4 (34-byte packets, 64 frames); "psx": PS-ADPCM (16-byte frames, 28 samples). Encode: ima, ima_wav, ms.
-- Not supported: raw DSP / ADX (their coefficients live in a header).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -40,10 +28,10 @@ export type Options = {
codec: Codec?, -- default "ima"
sampleRate: number?, -- default 22050 (decode)
channels: number?, -- default 1 (decode)
blockAlign: number?, -- ima_wav / ms: bytes per block (default 1024 when decoding; 256 * channels when encoding)
lowFirst: boolean?, -- ima: the low nibble first
interleave: number?, -- psx: bytes per channel before the next channel (default 16)
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
blockAlign: number?, -- ima_wav / ms; default 1024 decoding, 256 * channels encoding
lowFirst: boolean?,
interleave: number?, -- psx: bytes per channel (default 16)
maxFrames: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -51,7 +39,7 @@ local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = tru
-- ------------------------------------------------------------------------------------------------ sniff
function Raw.sniff(_r: Bytes.Reader): number
return 0 -- no header: found by extension or opts.format only
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
+6 -14
View File
@@ -1,15 +1,7 @@
--!strict
-- audio/adx: CRI ADX (.adx), the game-audio ADPCM of Sega / CRI Middleware, over codecs/audio/Adpcm. New in
-- rosetta; the header layout and the decoder details follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt),
-- whose output it matches bit for bit (the scale + 1 of CRI's decoders, the version 3 rounding; ffmpeg's ADX decoder
-- differs slightly on both). Supports: encoding type 3 (the standard predictor from the header's high-pass cutoff),
-- versions 3, 4 and 5, 1-8 channels, the initial history of version 4, loop points (dec.loop and
-- meta.source.loop = { start, stop } in frames, stop exclusive). Encode (Audio or Decoder): version 4, 1-8 channels,
-- loop points from opts.loop. Not supported: encrypted ADX (versions 0x0408 / 0x0409, keys needed), the fixed (2) and
-- exponential (4) encoding types, AHX.
--
-- local dec = Adx.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, version, cutoff)
-- local file = Adx.encode(audio, { loop = { start = 44100, stop = 441000 } })
-- audio/adx: CRI ADX via codecs/audio/Adpcm; header and decoder follow vgmstream r2117 (ISC,
-- licenses/vgmstream-LICENSE.txt), bit-exact with it. Supports: encoding type 3, versions 3-5, 1-8 channels, loop
-- points; encode as version 4. Not supported: encrypted ADX (0x0408 / 0x0409), encoding types 2 and 4, AHX.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -32,11 +24,11 @@ local Adx = {
-- ------------------------------------------------------------------------------------------------ types
export type Loop = { start: number, stop: number }
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
maxFrames: number?, -- default 2^28
}
export type EncodeOptions = {
loop: Loop?, -- loop points in frames (stop exclusive); default: the source's meta.source.loop / loop, else none
cutoff: number?, -- the predictor's high-pass cutoff in Hz (default 500, as CRI's encoders)
loop: Loop?, -- frames, stop exclusive; default the source's meta.source.loop
cutoff: number?, -- Hz, default 500 (as CRI's encoders)
}
-- ------------------------------------------------------------------------------------------------ constants
+11 -22
View File
@@ -1,11 +1,7 @@
--!strict
-- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs.
-- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw
-- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated
-- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 /
-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. AIFF-C ima4 (Apple IMA ADPCM, codecs/audio/Adpcm;
-- COMM counts packets of 64 frames) decodes too. Not supported: the other compressed AIFF-C codecs (MAC3 / MAC6,
-- Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk.
-- audio/aiff: AIFF / AIFF-C (Apple AIFF 1.3, AIFF-C draft 1991). Supports: PCM 1-32 bits; AIFF-C NONE / twos /
-- sowt / raw / in24 / in32 / fl32 / fl64 / ulaw / alaw / ima4; text chunks as tags; truncated SSND; encode 8-32 bit,
-- sowt, fl32, fl64, ulaw, alaw. Not supported: other compressed AIFF-C codecs, MARK / INST, the ID3 chunk.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -26,13 +22,12 @@ local Aiff = {
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
maxFrames: number?, -- default 2^28
}
export type EncodeOptions = {
sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16"
littleEndian: boolean?, -- 16-bit samples as AIFF-C "sowt" (default false: big endian; readers such as ffmpeg only
-- take 16-bit sowt, so other formats return Err.ARG)
aifc: boolean?, -- always write AIFF-C (default: only when the sample format needs it)
littleEndian: boolean?, -- 16-bit only, as AIFF-C "sowt" (ffmpeg reads no other sowt); default false
aifc: boolean?, -- default: only when the sample format needs it
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -40,7 +35,6 @@ local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANN
local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } }
local AIFC_VERSION = 0xA2805140
-- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian)
local function ext80(b: buffer, o: number): number
local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1)
local hi = bit32.byteswap(buffer.readu32(b, o + 2))
@@ -56,7 +50,6 @@ local function ext80(b: buffer, o: number): number
return if se >= 0x8000 then -v else v
end
-- the 10 bytes of x (> 0) as an 80-bit extended float
local function writeExt80(w: Bytes.Writer, x: number)
if x <= 0 or x ~= x then
w:fill(0, 10)
@@ -69,7 +62,7 @@ local function writeExt80(w: Bytes.Writer, x: number)
while x < 2 ^ e do
e -= 1
end
local m = x * 2 ^ (63 - e) -- in [2^63, 2^64)
local m = x * 2 ^ (63 - e)
local hi = math.floor(m / 4294967296)
local lo = m - hi * 4294967296
w:u16be(e + 16383)
@@ -77,7 +70,6 @@ local function writeExt80(w: Bytes.Writer, x: number)
w:u32be(math.floor(lo))
end
-- the sample format of a COMM chunk: Pcm format name | nil, message
local function sampleFormat(comp: string, bits: number): (string?, string?)
if comp == "NONE" or comp == "twos" or comp == "" then
if bits >= 1 and bits <= 8 then
@@ -118,7 +110,7 @@ local function sampleFormat(comp: string, bits: number): (string?, string?)
elseif comp == "alaw" or comp == "ALAW" then
return "alaw", nil
elseif comp == "ima4" then
return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks
return "ima4", nil
end
return nil, "compression " .. string.format("%q", comp)
end
@@ -142,12 +134,11 @@ type Info = {
compression: string,
aifc: boolean,
dataOffset: number, -- absolute in r.buf
dataSize: number, -- bytes of sample data present
dataSize: number,
truncated: boolean,
tags: Types.Tags,
}
-- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples)
local function parse(r: Bytes.Reader): (Info?, Err.Err?)
local b = r.buf
local base, limit = r.base, r.limit
@@ -165,7 +156,7 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
local ssnd: number? = nil
local ssndLen = 0
local tags: Types.Tags = {}
-- (walked to the end of the data: a FORM size that undercounts still reads the last chunk's body)
-- a FORM size that undercounts still reads the last chunk's body
for _, c in Chunks.walk(b, base + 12, limit, Chunks.IFF) do
local id, len, d, avail, p = c.id, c.declared, c.offset, c.avail, c.start
if p + 8 > formEnd then
@@ -250,7 +241,6 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
return fi, nil
end
-- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err
function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?)
return parse(r)
end
@@ -300,14 +290,13 @@ function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local aifc = o.aifc or comp ~= "NONE"
local w = Bytes.writer(65536)
w:string("FORM")
w:u32be(0) -- patched
w:u32be(0)
w:string(if aifc then "AIFC" else "AIFF")
if aifc then
w:string("FVER")
w:u32be(4)
w:u32be(AIFC_VERSION)
end
-- text chunks from the tags
for _, pair in TEXT_ORDER do
local id, key = pair[1], pair[2]
local s = src.tags[key]
+4 -12
View File
@@ -1,13 +1,7 @@
--!strict
-- audio/ape: Monkey's Audio (.ape) files around codecs/audio/Ape: the header in front (after an optional ID3v2 tag),
-- the frames (each independent: sample-accurate seeking through the seek table), APEv2 tags at the end
-- (codecs/audio/ApeTag). Written from the Monkey's Audio SDK 13.28 (BSD 3-clause, licenses/monkeys-audio-LICENSE.txt).
-- Supports file versions 3.95 and later, every compression level, 8 - 32-bit integer and 32-bit float, 1 - 32
-- channels (as the source WAV ordered them). Not supported: files before 3.95, encoding.
--
-- local dec = Ape.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, level, version, float, md5
-- local i32, n = dec:readInt(4096) -- integer files: the samples as `mac -d` writes them
-- local audio = Ape.decode(Bytes.reader(buf)) -- Types.Audio
-- audio/ape: Monkey's Audio (.ape) via codecs/audio/Ape and ApeTag, from the Monkey's Audio SDK 13.28 (BSD 3-clause,
-- licenses/monkeys-audio-LICENSE.txt). Supports: versions 3.95+, every level, 8-32-bit integer and 32-bit float, 1-32
-- channels, an ID3v2 prefix, seeking by the seek table. Not supported: files before 3.95, encoding.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -30,7 +24,7 @@ local Ape = {
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
maxFrames: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -59,7 +53,6 @@ function Ape.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Ape.open(r, opts)
if not dec then
@@ -74,7 +67,6 @@ function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err
function Ape.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
if type(r) == "buffer" then
r = Bytes.reader(r :: any)
+5 -7
View File
@@ -1,9 +1,7 @@
--!strict
-- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description.
-- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear),
-- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file);
-- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit).
-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED).
-- audio/au: Sun / NeXT audio (.au / .snd), big endian. Supports: encodings 1 (mu-law), 2-5 (8-32-bit linear), 6 / 7
-- (float), 27 (A-law), data size 0xFFFFFFFF (to the end), the annotation as tags.comment; encode to any of them.
-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -22,7 +20,7 @@ local Au = {
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
maxFrames: number?, -- default 2^28
}
export type EncodeOptions = {
sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16"
@@ -90,7 +88,7 @@ function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local w = Bytes.writer(65536)
w:string(".snd")
w:u32be(24 + alen)
w:u32be(0xFFFFFFFF) -- patched
w:u32be(0xFFFFFFFF)
w:u32be(spec[1])
w:u32be(src.sampleRate)
w:u32be(src.channels)
+5 -14
View File
@@ -1,13 +1,7 @@
--!strict
-- audio/brstm: Nintendo's streamed audio: BRSTM (Wii, "RSTM", big-endian), BCSTM (3DS, "CSTM", little-endian) and
-- BFSTM (Wii U big-endian / Switch little-endian, "FSTM"), over codecs/audio/Adpcm. New in rosetta; the layouts
-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: DSP
-- ADPCM (with the header's initial history; seeks into blocks not yet played use the ADPC / SEEK history table), PCM16
-- and PCM8, 1-255 channels in block-interleaved layout, the loop start (dec.loop and meta.source.loop = { start, stop }
-- in frames, stop exclusive). Read only. Not supported: BCSTM IMA ADPCM, BRSTM version 0.1 (beta), BFSTM regions
-- (the whole stream plays), the track table (channels are not grouped).
--
-- local dec = Brstm.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, container, codec)
-- audio/brstm: Nintendo BRSTM (Wii, "RSTM", BE), BCSTM (3DS, "CSTM", LE), BFSTM (Wii U BE / Switch LE, "FSTM"); layouts
-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), bit-exact. Supports: DSP ADPCM, PCM16 / PCM8, 1-255
-- channels, loop points. Read only. Not supported: BCSTM IMA ADPCM, BRSTM 0.1, BFSTM regions, the track table.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -28,7 +22,7 @@ local Brstm = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
maxFrames: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -44,7 +38,6 @@ function Brstm.sniff(r: Bytes.Reader): number
return if bom == "\254\255" or bom == "\255\254" then 1 else 0
end
-- variant(r) -> "brstm" / "bcstm" / "bfstm": the flavour, for F.detect
function Brstm.variant(r: Bytes.Reader): string?
local m = r:peek(4)
return if m == "RSTM" then "brstm" elseif m == "CSTM" then "bcstm" elseif m == "FSTM" then "bfstm" else nil
@@ -65,8 +58,6 @@ function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err
end
-- ------------------------------------------------------------------------------------------------ open
-- a reader of the whole file in its byte order: u8 / u16 / u32 / i16 / i32 at absolute offsets (relative to the file
-- start); a read out of range records the error in .err and returns 0
local function view(r: Bytes.Reader, be: boolean)
local v = { err = nil :: string? }
local size = r.limit - r.base
@@ -109,7 +100,7 @@ type Layout = {
frames: number,
blockSize: number,
lastPadded: number,
data: number, -- the first block (absolute in the file)
data: number, -- absolute
adp: { number }, -- each channel's DSP info offset (coefficients, then gain, ps, yn1, yn2)
hist: number?, -- the per-block history table: (yn1, yn2) per channel per block
histEntries: number,
+5 -13
View File
@@ -1,10 +1,7 @@
--!strict
-- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear
-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/audio/Alac), AAC-LC (codecs/audio/Aac,
-- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown
-- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 /
-- 24-bit) with info tags. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported:
-- other compressed formats (UNSUPPORTED).
-- audio/caf: Apple Core Audio Format (CAF 1.0 spec). Supports: linear PCM (8-32-bit integer, 32 / 64-bit float, either
-- endian), ALAC, AAC-LC (kuki esds), mu-law, A-law, IMA4; pakt trimming, data size -1, info tags, seeking; encode PCM
-- (16 / 24-bit BE, 32-bit float) and ALAC (16 / 20 / 24-bit). Not supported: other compressed formats.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -29,7 +26,7 @@ local Caf = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPackets: number?, -- packet table limit (default 2^24)
maxPackets: number?, -- default 2^24
}
export type EncodeOptions = {
codec: ("pcm" | "alac")?, -- default "alac"
@@ -48,7 +45,6 @@ for k, v in INFO_TAGS do
TAG_INFO[v] = k
end
-- mu-law / A-law -> linear 16-bit
local ULAW, ALAW = table.create(256, 0), table.create(256, 0)
for i = 0, 255 do
local u = 255 - i
@@ -76,7 +72,7 @@ end
type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number }
type Parsed = {
desc: Desc,
dataStart: number, -- absolute offset of the audio data
dataStart: number, -- absolute
dataEnd: number,
cookie: buffer?,
packets: { number }?, -- sizes (pakt)
@@ -236,7 +232,6 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?)
return p, nil
end
-- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err
type Source = {
channels: number,
rate: number,
@@ -333,7 +328,6 @@ local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?)
}
return src, nil
end
-- packetised codecs
local sizes = p.packets
if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none
if d.bytesPerPacket > 0 then
@@ -505,7 +499,6 @@ local function chunk(w: Bytes.Writer, typ: string, size: number)
w:i64be(size)
end
-- encode(audio | decoder, opts?) -> buffer | nil, Err
function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
@@ -523,7 +516,6 @@ function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if ch < 1 or ch > 64 or sr <= 0 then
return nil, Err.new(Err.ARG, "bad sample rate / channels")
end
-- the source frames
local isAudio = value.kind == "audio" and type(value.samples) == "buffer"
if not isAudio and type(value.read) ~= "function" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
+3 -6
View File
@@ -1,9 +1,7 @@
--!strict
--!native
--!optimize 2
-- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is
-- left in place); every other block is skipped. Nothing throws: bad data gives nil, err.
-- Absorbed from flac-luau 7083d0d (same author, no third-party code).
-- audio/flac/Meta: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE blocks; absorbed from flac-luau 7083d0d.
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
local readu8, readu32 = buffer.readu8, buffer.readu32
@@ -51,7 +49,7 @@ export type Info = {
seekTable: { SeekPoint },
vendor: string,
tags: { [string]: string }, -- upper-case keys; repeated keys are joined with "; "
comments: { { key: string, value: string } }, -- every comment in order
comments: { { key: string, value: string } },
pictures: { Picture },
firstFrame: number, -- byte offset just after the last metadata block
}
@@ -150,7 +148,6 @@ local function picture(b: buffer, p: number, e: number): Picture?
return pic
end
-- Parse the metadata blocks that follow "fLaC" at pos (data ends at len)
function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?)
if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then
return nil, "Flac: no fLaC marker"
@@ -195,7 +192,7 @@ function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?)
end
end
elseif typ == 4 then
vorbisComment(b, p, e, info) -- a broken comment block leaves what was read
vorbisComment(b, p, e, info)
elseif typ == 6 then
local pic = picture(b, p, e)
if pic then
+4 -19
View File
@@ -1,11 +1,7 @@
--!strict
--!native
--!optimize 2
-- audio/flac/Stream: the streaming FLAC decoder (native FLAC with an optional ID3v2 tag in front, and Ogg FLAC through
-- containers/Ogg): stream setup, read / readInt with resync past corrupt frames, sample-accurate seeking (seek table,
-- byte bisection by sync search, then a frame walk), length from the last frame when STREAMINFO has none. Absorbed
-- from flac-luau 7083d0d (same author, no third-party code; the Ogg demuxer is now a direct require instead of an
-- injected module). Nothing throws: open returns nil, message, code.
-- audio/flac/Stream: streaming FLAC decoder (native and Ogg FLAC); absorbed from flac-luau 7083d0d (same author).
local Bytes = require("@rosetta/core/Bytes")
local Ogg = require("@rosetta/containers/Ogg")
local Frame = require("@rosetta/codecs/audio/Flac/Frame")
@@ -41,12 +37,10 @@ export type Decoder = {
local Dec = {}
Dec.__index = Dec
-- the sample number of a frame
local function sampleOf(self: any, h: Header): number
return if h.variable then h.number else h.number * self._nominal
end
-- a header that also matches the stream (guards the sync search against false syncs)
local function plausible(self: any, h: Header): boolean
if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then
return false
@@ -80,7 +74,6 @@ local function ensure(self: any, n: number)
end
end
-- Decode the frame at or after pos (resyncing past corrupt data). Sets the current frame; false at the end.
local function decodeAt(self: any, pos: number): boolean
local b, len = self._b, self._len
while true do
@@ -114,7 +107,7 @@ local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?):
local ch = self.channels
local want = math.floor(tonumber(maxFrames) or 0)
if not (want >= 0) then
want = 0 -- negative or NaN
want = 0
end
want = math.min(want, 2 ^ 26 // ch) -- keeps the output buffer under 256 MB
local reuse = dst ~= nil and type(dst) == "buffer" and buffer.len(dst) >= want * ch * 4
@@ -159,29 +152,23 @@ local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?):
return out, got
end
-- Up to maxFrames sample frames as interleaved f32 (sample / 2^(bps-1)); 0 frames = end of stream. out (if given) is
-- reused when big enough.
function Dec.read(self: any, maxFrames: number, out: buffer?): (buffer, number)
return pull(self, maxFrames, false, out)
end
-- The same as interleaved i32 integer samples (bit-exact, right-aligned)
function Dec.readInt(self: any, maxFrames: number, out: buffer?): (buffer, number)
return pull(self, maxFrames, true, out)
end
-- seconds, sample frame of the next frame read() returns
function Dec.position(self: any): (number, number)
local s = self._fs + self._cur
return s / self.sampleRate, s
end
-- Seek so the next read starts exactly at sample frame t. Uses the seek table to bracket t, bisects byte offsets
-- by sync search, then walks frame headers forward. Returns false if the stream has no frame there.
function Dec.seekSample(self: any, t: number): boolean
t = math.floor(tonumber(t) or 0)
if not (t >= 0) then
t = 0 -- negative or NaN
t = 0
end
if self.frames > 0 and t >= self.frames then
self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0
@@ -228,7 +215,7 @@ function Dec.seekSample(self: any, t: number): boolean
self._cur = t - self._fs
return true
elseif self._fs > t then
return false -- a hole in the stream: we are at the next frame
return false
end
pos = self._pos
else
@@ -244,7 +231,6 @@ function Dec.seek(self: any, seconds: number): boolean
return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5))
end
-- Find the total length from the last frame (when STREAMINFO does not give it)
local function scanLength(self: any): number
local len = self._len
local step = math.max(65536, 2 * self._si.maxFrameSize)
@@ -284,7 +270,6 @@ local function skipId3(b: buffer, base: number, len: number): number
return p
end
-- opts.crc16 = false skips the per-frame CRC-16 check
function Stream.open(buf: buffer, base: number, srcLen: number, opts: { crc16: boolean? }?): (Decoder?, string?, string?)
local b, len, container
if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then
+6 -21
View File
@@ -1,19 +1,7 @@
--!strict
-- audio/flac: FLAC (RFC 9639), native and in Ogg (the Ogg FLAC mapping). Absorbed from flac-luau 7083d0d (same author,
-- no third-party code); the Ogg demuxer is now a direct require of containers/Ogg instead of an injected module.
-- Supports: every subframe type (constant, verbatim, fixed, LPC up to order 32, wasted bits), Rice / Rice2 residuals
-- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame
-- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in
-- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when
-- STREAMINFO has none. Encode (codecs/audio/Flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels
-- 0-8 like libFLAC's presets, 4-24 bits, 1-8 channels, MD5, VORBIS_COMMENT, SEEKTABLE. Not supported: MD5
-- verification on decode, chained Ogg streams, Ogg FLAC output.
-- The codec itself is codecs/audio/Flac; this folder maps it onto the file (container, tags, seeking, writing).
--
-- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...)
-- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end
-- local i32, n = dec:readInt(4096) -- bit-exact integer samples
-- local audio = Flac.decode(Bytes.reader(buf)) -- Types.Audio
-- audio/flac: FLAC (RFC 9639), native and Ogg FLAC; absorbed from flac-luau 7083d0d (same author). Supports: every
-- subframe type, Rice / Rice2, 4-32 bits, 1-8 channels, CRC-16 resync, seeking, an ID3v2 prefix, the main metadata
-- blocks; encode levels 0-8 (libFLAC presets), 4-24 bits. Not supported: MD5 check on decode, chained Ogg, Ogg output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -37,12 +25,12 @@ local Flac = {
-- ------------------------------------------------------------------------------------------------ types
export type Decoder = Stream.Decoder
export type OpenOptions = {
crc16: boolean?, -- check every frame's CRC-16 (default true; a bad frame is skipped by resyncing)
maxFrames: number?, -- decode(): refuse streams longer than this many sample frames (default 2^28)
crc16: boolean?, -- default true; a bad frame is skipped by resyncing
maxFrames: number?, -- default 2^28
}
export type EncodeOptions = {
level: number?, -- 0..8 like libFLAC's -0 .. -8 (default 5)
bits: number?, -- bits per sample 4..24 (default: the source's meta.source.bitDepth / bitsPerSample if 4..24, else 16)
bits: number?, -- 4..24; default the source's bit depth if 4..24, else 16
blockSize: number?, -- 16..65535 (default: the level's, 1152 or 4096)
seekInterval: number?, -- seconds between SEEKTABLE points when the length is known (default 10; 0 = none)
padding: number?, -- bytes of PADDING after the metadata (default 0)
@@ -79,7 +67,6 @@ function Flac.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Flac.open(r, opts)
if not dec then
@@ -94,7 +81,6 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audioOrDecoder, opts?) -> FLAC file buffer | nil, Err
function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
@@ -139,7 +125,6 @@ function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err
function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?)
if type(r) == "buffer" then
r = Bytes.reader(r :: any)
+5 -13
View File
@@ -1,9 +1,7 @@
--!strict
-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading
-- AAC-LC (codecs/audio/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/audio/Alac) tracks, gapless
-- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures);
-- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs
-- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files.
-- audio/m4a: MPEG-4 audio (M4A / M4B / MP4 / MOV audio tracks) via containers/IsoBmff. Supports: AAC-LC (HE-AAC plays
-- its core), ALAC, edit-list gapless trimming, seeking, iTunes tags and cover art; encode ALAC (16 / 20 / 24-bit, 1-8
-- channels). Not supported: writing AAC, other codecs in MP4 (UNSUPPORTED), encrypted files.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -29,13 +27,13 @@ local M4a = {
export type DecodeOptions = {
track: number?, -- the track id to play (default: the first AAC / ALAC track)
gapless: boolean?, -- apply the edit list (default true)
maxSamples: number?, -- sample table limit (default 2^25)
maxSamples: number?, -- default 2^25
}
export type EncodeOptions = {
bitDepth: number?, -- 16 (default), 20 or 24
frameLength: number?, -- samples per packet, default 4096
tags: Types.Tags?, -- default: the audio's tags
pictures: { { mime: string, data: buffer } }?, -- cover art (default: audio.meta.pictures)
pictures: { { mime: string, data: buffer } }?, -- default: audio.meta.pictures
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -57,7 +55,6 @@ function M4a.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats
type PacketDecoder = {
channels: number,
sampleRate: number,
@@ -121,7 +118,6 @@ local function packetDecoder(t: IsoBmff.Track): (PacketDecoder?, Err.Err?)
return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4")
end
-- open(r, opts?) -> Types.Decoder | nil, Err
function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local o: DecodeOptions = opts or {}
local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples })
@@ -155,7 +151,6 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
end
local p = pd :: PacketDecoder
local channels, sr = p.channels, p.sampleRate
-- media ticks -> sample frames
local tickScale = sr / t.timescale
local gapless = o.gapless ~= false
local skip = if gapless then math.floor(t.skip * tickScale + 0.5) else 0
@@ -219,7 +214,6 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
})
end
-- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures)
function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = M4a.open(r, opts)
if not dec then
@@ -234,7 +228,6 @@ function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A
function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
@@ -254,7 +247,6 @@ function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local ints = table.create(fl * ch, 0)
local floor = math.floor
local readf32 = buffer.readf32
-- frames from an Audio buffer or a streaming Decoder
local src: buffer, srcFrames = nil :: any, 0
local isAudio = value.kind == "audio" and type(value.samples) == "buffer"
if isAudio then
+1 -6
View File
@@ -1,10 +1,7 @@
--!strict
--!native
--!optimize 2
-- audio/mp3/Index: the frame index of a stream, built once on open. It follows minimp3_ex's mp3dec_load_buf frame by frame
-- (same sync, resync and Xing / LAME handling), and simulates the layer III bit reservoir from the side info, so
-- it knows in advance which frames give output and where each one's samples land. That makes the total length
-- exact and seeking sample-accurate. Never throws.
-- audio/mp3/Index: the frame index as minimp3_ex's mp3dec_load_buf walks it, simulating the layer III bit reservoir.
local Header = require("@rosetta/codecs/audio/Mpa/Header")
local Core = require("@rosetta/codecs/audio/Mpa/Core")
@@ -29,7 +26,6 @@ export type Index = {
main: buffer, -- u16 layer III main data bytes per frame (0 for layers I / II)
outTotal: number, -- samples (per channel) of a continuous decode, delay not cut
bytes: number, -- audio bytes in indexed frames
-- format of the first frame
sampleRate: number,
channels: number, -- the most channels of any frame
layer: number,
@@ -89,7 +85,6 @@ function Index.build(b: buffer, start: number, stop: number): Index?
pos += i
end
if fs < 4 or fs > Core.MAX_FRAME then
-- cannot happen with a well-formed header, but never index an impossible frame
prev = -1
pos += max(fs, 1)
continue
+2 -14
View File
@@ -1,7 +1,6 @@
--!strict
--!optimize 2
-- audio/mp3/Stream: the streaming Decoder (Types.Decoder) over a frame index: gapless (LAME delay / padding), exact
-- length, sample-accurate seeking. From mp3-luau's Mp3.open / Decoder (same author). Never throws.
-- audio/mp3/Stream: streaming Decoder over the frame index (gapless, exact seeking); from mp3-luau (same author).
local Core = require("@rosetta/codecs/audio/Mpa/Core")
local Index = require("@rosetta/audio/mp3/Index")
@@ -44,7 +43,6 @@ export type Decoder = typeof(setmetatable(
Decoder
))
-- new(b, idx, tags, id3) -> Decoder over the whole buffer b, with its frame index (Index.build)
function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): Decoder
local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels
-- gapless: minimp3_ex cuts delay samples off the start and caps the length at the Xing / LAME count
@@ -92,7 +90,6 @@ function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any):
end
-- decodes frames until one has samples inside [minAbs, endAbs); false at the end
local function fill(self: Decoder): boolean
local idx = self._idx
local n = idx.n
@@ -127,9 +124,6 @@ local function fill(self: Decoder): boolean
return false
end
-- Reads up to maxFrames sample frames: (buffer of interleaved f32, frames read); 0 frames = end of stream.
-- With out (a buffer of at least maxFrames * channels * 4 bytes) the samples go there and out is returned; a
-- smaller out is ignored.
function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, number)
local ch = self.channels
local want = tonumber(maxFrames) or 4096
@@ -138,7 +132,7 @@ function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer,
end
want = floor(max(0, min(want, self.frames - self._pos)))
if out and buffer.len(out) < want * ch * 4 then
out = nil -- too small: a new buffer (Types.Decoder: out is reused when big enough)
out = nil
end
local dst = out or buffer.create(want * ch * 4)
local got = 0
@@ -163,8 +157,6 @@ function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer,
return dst, got
end
-- Seeks to a time in seconds (clamped to the stream). Sample-accurate: decoding restarts a few frames earlier
-- (enough to refill the bit reservoir and the filter history) and the output before the target is dropped.
function Decoder.seek(self: Decoder, seconds: number)
local hz = self.sampleRate
local target = floor((tonumber(seconds) or 0) * hz + 0.5)
@@ -172,7 +164,6 @@ function Decoder.seek(self: Decoder, seconds: number)
self:seekFrame(target)
end
-- Seeks to a sample frame (0 .. frames).
function Decoder.seekFrame(self: Decoder, target: number)
target = tonumber(target) or 0
if target ~= target then
@@ -190,7 +181,6 @@ function Decoder.seekFrame(self: Decoder, target: number)
self._cur = n
return
end
-- last frame starting at or before abs
local lo, hi = 0, n - 1
while lo < hi do
local mid = (lo + hi + 1) // 2
@@ -218,12 +208,10 @@ function Decoder.seekFrame(self: Decoder, target: number)
self._cur = s
end
-- Current position: (seconds, sample frame)
function Decoder.position(self: Decoder): (number, number)
return self._pos / self.sampleRate, self._pos
end
-- Decodes everything from the current position to the end: (buffer of interleaved f32, frames)
function Decoder.readAll(self: Decoder): (buffer, number)
return self:read(max(0, self.frames - self._pos))
end
+1 -8
View File
@@ -1,8 +1,6 @@
--!strict
--!optimize 2
-- audio/mp3/Tags: ID3 tags: ID3v2.2 / 2.3 / 2.4 at the start (text frames, COMM, unsynchronisation, extended header) and ID3v1 /
-- ID3v1.1 at the end; APEv2 tags are only skipped. Also finds the byte range that holds the audio, the same way
-- minimp3_ex does (mp3dec_skip_id3). Text is returned as UTF-8. Never throws: malformed tags are cut short.
-- audio/mp3/Tags: ID3v2.2-2.4 and ID3v1 / 1.1 tags (APEv2 skipped); the audio range as minimp3_ex's mp3dec_skip_id3.
local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift
local ru8 = buffer.readu8
@@ -97,7 +95,6 @@ local function decodeText(b: buffer, i: number, j: number, enc: number): string
return table.concat(out)
end
-- trim trailing NULs / spaces, join multi-value NUL separators with " / "
local function clean(s: string): string
s = string.gsub(s, "[%z%s]+$", "")
s = string.gsub(s, "%z+", " / ")
@@ -166,7 +163,6 @@ local function setField(tags: any, id: string, text: string)
end
end
-- parse an ID3v2 tag at b[o ..] (o .. o + size within the buffer) into tags
local function parseV2(b: buffer, o: number, size: number, tags: any)
local ver = ru8(b, o + 3)
local flags = ru8(b, o + 5)
@@ -258,9 +254,6 @@ local function v1String(b: buffer, o: number, n: number): string
return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", ""))
end
-- Parses tags and returns (tags, audio start, audio end) for the buffer b.
-- tags = { title?, artist?, album?, albumartist?, date?, track?, disc?, genre?, composer?, comment?,
-- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? }
function Tags.parse(b: buffer): (any, number, number)
local len = buffer.len(b)
local tags: any = { raw = {} }
+5 -25
View File
@@ -1,18 +1,7 @@
--!strict
-- audio/mp3: MPEG audio (ISO/IEC 11172-3, 13818-3; MPEG-2.5), layers I, II and III. Absorbed from mp3-luau c755bbf
-- (same author; a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt). Supports: decode of MPEG-1 / 2 / 2.5
-- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing /
-- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync
-- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped).
-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, codecs/audio/Mpa/Encode3 + Encode2): layer III
-- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from
-- the tags; input at rates the layer cannot hold is resampled (codecs/audio/Resample). Not supported: MPEG-2 multichannel
-- extension, CRC checks, VBR / Xing output.
-- The codec itself is codecs/audio/Mpa; this folder maps it onto the file (container, tags, seeking, writing).
--
-- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay,
-- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll())
-- local audio = Mp3.decode(Bytes.reader(buf)) -- a Types.Audio (the whole file)
-- audio/mp3: MPEG audio layers I-III (ISO/IEC 11172-3, 13818-3, MPEG-2.5); absorbed from mp3-luau c755bbf, a port of
-- minimp3 by lieff (CC0: licenses/minimp3-CC0.txt). Supports: every mode, CBR / VBR / free format, Xing / LAME gapless,
-- exact seeking, ID3v2 / ID3v1 tags; encode layers III / II (CBR). Not supported: MPEG-2 multichannel, CRC, VBR output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -39,7 +28,7 @@ local Mp3 = {
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31)
maxFrames: number?, -- default 2^31
}
export type Decoder = Stream.Decoder
export type EncodeOptions = {
@@ -58,7 +47,6 @@ export type EncodeOptions = {
local MAX_FRAMES = 2 ^ 31
-- ------------------------------------------------------------------------------------------------ sniff
-- an ID3v2 tag and / or a valid frame header at the start, more when the next frame chains on
function Mp3.sniff(r: Bytes.Reader): number
local b, p, lim = r.buf, r.pos, r.limit
local id3 = false
@@ -87,7 +75,6 @@ function Mp3.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts) -> Types.Audio (the whole stream, through open)
function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Mp3.open(r, opts)
if not dec then
@@ -113,7 +100,6 @@ local ID3_FRAMES = {
{ "composer", "TCOM" },
}
-- an ID3v2.4 tag (UTF-8 text frames + a COMM frame) | nil when there is nothing to write
local function id3Tag(tags: { [string]: any }): buffer?
local w = Bytes.writer(256)
local seen: { [string]: boolean } = {}
@@ -162,7 +148,6 @@ local function id3Tag(tags: { [string]: any }): buffer?
return out:finish()
end
-- encode(audioOrDecoder, opts?) -> an MP3 (layer III) or MP2 (layer II) file | nil, Err
function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
@@ -174,8 +159,6 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
return nil, Err.new(Err.ARG, "layer must be 2 or 3")
end
local Enc = if layer == 3 then Encode3 else Encode2
-- the output rate: opts.sampleRate, else the input's when the layer has it, else the nearest rate above it (else
-- the highest); other input rates go through codecs/audio/Resample
local rate = o.sampleRate or src.sampleRate
if o.sampleRate and not Enc.RATES[o.sampleRate] then
return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz", layer, tostring(o.sampleRate)))
@@ -209,7 +192,6 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if layer == 2 and mode == "joint" then
mode = "stereo"
end
-- bitrate: bit/s, or kbit/s below 1000; the encoder works in kbit/s
local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96))
if type(bitrate) == "number" and bitrate >= 1000 then
bitrate /= 1000
@@ -234,7 +216,6 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ open
-- the string-valued tag fields (title, artist, album, albumartist, date, track, disc, genre, composer, comment)
local function stringTags(t: any): { [string]: string }
local out: { [string]: string } = {}
for k, v in t do
@@ -245,7 +226,6 @@ local function stringTags(t: any): { [string]: string }
return out
end
-- open(r, opts) -> the streaming Decoder (Types.Decoder) | nil, Err
function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?)
local b = r.buf
if r.base ~= 0 or r.limit ~= buffer.len(b) then
@@ -273,6 +253,6 @@ function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
Mp3.Tags = Tags -- Tags.parse(buf) -> (tags, audio start, audio end)
Mp3.Tags = Tags
return Mp3
+4 -8
View File
@@ -1,10 +1,7 @@
--!strict
-- audio/mpc: Musepack (.mpc / .mp+ / .mpp), stream versions 7 and 8, through codecs/audio/Musepack (a libmpcdec
-- port). Supports: SV7 (mppenc 1.x) and SV8 (mpcenc 1.30) streams, mono / stereo, every rate (32 / 37.8 / 44.1 /
-- 48 kHz), gapless length (the synthesis delay, SV8 leading silence and the last frame's length are honoured), seeking
-- (SV8: by audio packet, exact; SV7: by frame with 32 frames of pre-roll, as libmpcdec), APEv2 tags
-- (codecs/audio/ApeTag), a leading ID3v2 tag (skipped), ReplayGain values in meta (not applied). Not supported:
-- writing, SV4 - SV6 (UNSUPPORTED), chapters.
-- audio/mpc: Musepack (.mpc / .mp+ / .mpp) SV7 and SV8 via codecs/audio/Musepack (a libmpcdec port). Supports: mono /
-- stereo, 32-48 kHz, gapless length, seeking (SV8 exact; SV7 with 32 frames of pre-roll, as libmpcdec), APEv2 tags,
-- an ID3v2 prefix, ReplayGain in meta. Not supported: writing, SV4-SV6 (UNSUPPORTED), chapters.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -27,11 +24,10 @@ local Mpc = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- Err.LIMIT past this many output sample frames (default 2^31)
maxFrames: number?, -- default 2^31
}
-- ------------------------------------------------------------------------------------------------ constants
-- the size of an ID3v2 tag at p (0 if none)
local function id3v2(b: buffer, p: number, limit: number): number
if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then
return 0
+2 -10
View File
@@ -1,9 +1,5 @@
--!strict
-- audio/opus/Encode: Ogg Opus writing (RFC 7845) around codecs/audio/Opus/CeltEncoder: CELT-only packets (TOC config 31:
-- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor +
-- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at
-- other rates is resampled to 48 kHz (codecs/audio/Resample); the input is a Types.Audio or a Decoder (codecs/audio/Pcm). New in
-- rosetta.
-- audio/opus/Encode: Ogg Opus writing (RFC 7845), CELT only (TOC config 31: full band, 20 ms, code 0), family 0.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Ogg = require("@rosetta/containers/Ogg")
@@ -24,7 +20,6 @@ export type Options = {
local floor = math.floor
-- encode(audio | decoder, opts) -> buffer | nil, Err
function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
local o: Options = opts or {}
local src, serr = Pcm.source(value)
@@ -41,12 +36,11 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
end
local bitrate = o.bitrate or 64000 * ch
if type(bitrate) == "number" and bitrate > 0 and bitrate < 1000 then
bitrate *= 1000 -- kbit/s
bitrate *= 1000
end
if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then
return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000")
end
-- the whole input at 48 kHz (codecs/audio/Resample for other rates), then as floats
if rate ~= 48000 then
local rs, rerr = Resample.source(src, 48000)
if not rs then
@@ -68,7 +62,6 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
local FRAME = CeltEncoder.FRAME
local preSkip = CeltEncoder.DELAY
local packets = (n48 + preSkip + FRAME - 1) // FRAME
-- zero padding to whole frames
for i = n48 * ch + 1, packets * FRAME * ch do
pcm[i] = 0
end
@@ -100,7 +93,6 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
tw:string(field)
end
s:packet(tw:finish(), 0, { flush = true })
-- audio
local toc = 31 * 8 + (if ch == 2 then 4 else 0)
for p = 0, packets - 1 do
local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes)
+6 -32
View File
@@ -1,22 +1,7 @@
--!strict
-- audio/opus: Ogg Opus (RFC 6716 codec, RFC 7845 encapsulation). Absorbed from opus-luau dd2b4e5 (same author; a
-- port of the libopus 1.6 decoder, BSD: licenses/libopus-BSD.txt): the range decoder, CELT (float), SILK
-- (bit-exact fixed point), hybrid, mode transitions, PLC, multistream (mapping families 0, 1, 255).
-- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix,
-- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms
-- pre-roll), damaged files (concealment). Output is always 48 kHz f32.
-- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant
-- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags.
-- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics
-- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only).
-- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an
-- optional output buffer; decode() fully decodes to an Audio.
-- The codec itself is codecs/audio/Opus; this folder maps it onto the file (container, tags, seeking, writing).
--
-- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ...
-- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio
-- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets
-- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only)
-- audio/opus: Ogg Opus (RFC 6716, RFC 7845); absorbed from opus-luau dd2b4e5, a port of the libopus 1.6 decoder (BSD:
-- licenses/libopus-BSD.txt). Supports: every mode / bandwidth / frame size, mapping families 0 / 1 / 255, seeking, PLC;
-- encode CELT only (20 ms, full band, CBR). Not supported: SILK / hybrid encoding, mapping family 3, chained streams.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -75,7 +60,7 @@ export type Head = {
mapping: { number },
}
-- OpusHead (RFC 7845 section 5.1). Returns the header or nil, message.
-- OpusHead (RFC 7845 section 5.1)
local function parseHead(b: buffer, off: number, size: number): (Head?, string?)
if size < 19 or buffer.readstring(b, off, 8) ~= "OpusHead" then
return nil, "not an OpusHead packet"
@@ -127,8 +112,7 @@ local function parseHead(b: buffer, off: number, size: number): (Head?, string?)
return head, nil
end
-- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/audio/VorbisComment: lower-case keys, repeated fields joined
-- with "; "), the raw fields
-- OpusTags (RFC 7845 section 5.2)
local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }, { VorbisComment.Field })
if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then
return "", {}, {}
@@ -173,7 +157,6 @@ Opus.parseTags = parseTags
Opus.SAMPLE_RATE = SAMPLE_RATE
-- ------------------------------------------------------------------------------------------------ sniff
-- 1 when the file starts with an Ogg page whose first packet is an OpusHead
function Opus.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "OggS" then
return 0
@@ -186,7 +169,6 @@ function Opus.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Audio | nil, Err: the whole stream (48 kHz f32)
function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Opus.open(r, opts)
if not dec then
@@ -196,7 +178,6 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode)
function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?)
return Encode.encode(value, opts)
end
@@ -205,7 +186,6 @@ end
local Stream = {}
Stream.__index = Stream
-- Decodes the next packet into the pending buffer. Returns false at the end of the stream.
local function decodeNext(self: any): boolean
local p = self.demux:nextPacket(self.serial)
if p == nil then
@@ -239,8 +219,6 @@ local function decodeNext(self: any): boolean
return true
end
-- dec:read(maxFrames, out?) -> buffer of interleaved f32 samples, frames read (0 at the end of the stream). out (if
-- given and big enough) is filled instead of a new buffer.
function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, number)
local ch = self.channels
local mf = if type(maxFrames) == "number" and maxFrames == maxFrames then maxFrames else 0
@@ -255,7 +233,6 @@ function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, numb
break
end
end
-- skip decoded samples before the next wanted one (pre-skip, seek pre-roll)
local s = self.pendStart + self.pendPos
if s < self.next then
self.pendPos = math.min(self.pendLen, self.pendPos + (self.next - s))
@@ -280,17 +257,15 @@ function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, numb
buffer.copy(trimmed, 0, out, 0, got * ch * 4)
out = trimmed
end
self.endSample = self.next -- the stream ended early (truncated file)
self.endSample = self.next
end
return out, got
end
-- current playback position in seconds
function Stream.position(self: any): number
return (self.next - self.preSkip) / SAMPLE_RATE
end
-- seek to a time in seconds (clamped to the stream): granule bisection with 80 ms pre-roll
function Stream.seek(self: any, seconds: number)
local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0
local p = math.floor(math.max(0, math.min(sec, 1e12)) * SAMPLE_RATE + 0.5)
@@ -315,7 +290,6 @@ function Stream.seek(self: any, seconds: number)
self.next = target
end
-- open(r, opts?) -> Decoder | nil, Err (r: a core/Bytes Reader, or a buffer)
function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?)
local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil)
if not demux then
+4 -11
View File
@@ -1,13 +1,7 @@
--!strict
-- audio/qoa: QOA, "Quite OK Audio" (.qoa), over codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). New in
-- rosetta. Decode / open: static files and streaming files (total 0 in the header), 1-255 channels (WAVE order
-- for 1-8, as the spec lays them out), any rate up to 16777215 Hz, frame-accurate seeking (every frame carries its
-- own predictor state), a truncated file decodes its whole frames. Encode (Audio or Decoder, streamed frame by frame):
-- byte-for-byte what qoa.h's qoa_encode writes, 1-8 channels (qoa.h's limit). Not supported: frames whose channel
-- count or rate change mid-stream (Err.UNSUPPORTED).
--
-- local dec = Qoa.open(Bytes.reader(buf)) -- Types.Decoder
-- local file = Qoa.encode(audio)
-- audio/qoa: QOA "Quite OK Audio" via codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). Supports: static and
-- streaming files, 1-255 channels, rates up to 16777215 Hz, frame-accurate seeking; encode byte-for-byte as qoa_encode,
-- 1-8 channels. Not supported: channel count or rate changes mid-stream.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -29,7 +23,7 @@ local Qoa = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this many sample frames (default 2^28)
maxFrames: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -122,7 +116,6 @@ function Qoa.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?)
return nil, h.err
end
local buf = r.buf
-- the frame index: offsets, first frames
local offs, starts = {}, {}
local p, total = r.base + 8, 0
local ch, rate = 0, 0
+4 -11
View File
@@ -1,11 +1,7 @@
--!strict
-- audio/tta: True Audio (.tta, TTA1) files around codecs/audio/Tta: an optional ID3v2 tag in front (skipped), the
-- header and seek table, independent frames (sample-accurate seeking), APEv2 tags at the end (codecs/audio/ApeTag).
-- Written from the TTA1 format description; no libtta / ffmpeg code. Supports 8 / 16 / 24 bits, any channel count.
-- Not supported: password-protected files (Err.UNSUPPORTED), TTA2, ID3v2 tag contents, encoding.
--
-- local dec = Tta.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, readInt
-- local audio = Tta.decode(Bytes.reader(buf)) -- Types.Audio
-- audio/tta: True Audio (.tta, TTA1) via codecs/audio/Tta, from the TTA1 format description. Supports: 8 / 16 / 24
-- bits, any channel count, seeking by the seek table, APEv2 tags, an ID3v2 prefix. Not supported: password-protected
-- files, TTA2, ID3v2 contents, encoding.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -28,11 +24,10 @@ local Tta = {
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
maxFrames: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ sniff
-- the size of an ID3v2 tag at the reader's start (0 when none)
local function id3Size(r: Bytes.Reader): number
if r:peek(3) ~= "ID3" then
return 0
@@ -54,7 +49,6 @@ function Tta.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Tta.open(r, opts)
if not dec then
@@ -69,7 +63,6 @@ function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err
function Tta.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
if type(r) == "buffer" then
r = Bytes.reader(r :: any)
+5 -15
View File
@@ -1,16 +1,7 @@
--!strict
-- audio/vag: Sony VAG (PlayStation SPU PS-ADPCM, .vag), and Simon & Schuster / Hyperscan KVAG (IMA ADPCM, the same
-- extension), over codecs/audio/Adpcm. New in rosetta; the header variants and the PS-ADPCM decoding follow
-- vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: "VAGp" mono
-- (versions 0, 2, 3, 4, 6, 0x20; the name field as tags.title; loop points from the frame flags, as dec.loop and
-- meta.source.loop = { start, stop } in frames, stop exclusive), "VAGi" stereo (interleaved blocks), "KVAG" mono /
-- stereo IMA. The output starts with the blank frame Sony's tools put first (28 silent samples), as vgmstream plays it.
-- Encode (Audio or Decoder): mono to VAGp, stereo to VAGi (2048-byte interleave), loop points from opts.loop (frame
-- aligned: 28 samples). Not supported: HEVAG (VAGp versions 0x00020001 / 0x00030000, Vita / PS4), the many game
-- specific variants vgmstream knows (pGAV, VAG1 / VAG2, Jak, ...).
--
-- local dec = Vag.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, variant)
-- local file = Vag.encode(audio, { loop = { start = 0, stop = audio.frames } })
-- audio/vag: Sony VAG (PS-ADPCM: VAGp mono, VAGi stereo) and KVAG (IMA); layouts follow vgmstream r2117 (ISC,
-- licenses/vgmstream-LICENSE.txt), bit-exact, Sony's leading blank frame included. Supports: loop points; encode VAGp /
-- VAGi. Not supported: HEVAG (0x00020001 / 0x00030000), game-specific variants (pGAV, VAG1 / VAG2, Jak, ...).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -33,7 +24,7 @@ local Vag = {
-- ------------------------------------------------------------------------------------------------ types
export type Loop = { start: number, stop: number }
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
maxFrames: number?, -- default 2^28
}
export type EncodeOptions = {
loop: Loop?, -- loop points in frames of the input (stop exclusive), rounded out to 28-sample frames; default: the
@@ -144,8 +135,7 @@ function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ open
-- the loop from the PS-ADPCM frame flags of channel 0 (vgmstream's reading: the first start flag 6, the first end
-- flag 3), or nil
-- vgmstream's loop reading: channel 0's first start flag 6 and first end flag 3
local function findLoop(buf: buffer, p: number, frames: number, il: number, ch: number): Loop?
local ls, le = -1, -1
for k = 0, frames - 1 do
+6 -11
View File
@@ -1,11 +1,7 @@
--!strict
-- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description.
-- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence),
-- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit
-- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played
-- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version
-- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM
-- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used).
-- audio/voc: Creative Voice File (.voc), from Creative's format description. Supports: block types 1, 2, 3, 5, 8, 9
-- (8 / 16-bit, A-law, mu-law); markers and repeats played once, as ffmpeg; truncated files; encode version 1.20 type 9
-- blocks. Not supported: Creative ADPCM, channel count changes mid-file (the first block's rate is used).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,7 +20,7 @@ local Voc = {
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
maxFrames: number?, -- default 2^28
}
export type EncodeOptions = {
sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16"
@@ -73,7 +69,6 @@ function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E
local truncated = false
local tags: Types.Tags = {}
local p = base + hsize
-- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames)
local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err?
if channels == 0 then
channels, rate = ch, sr
@@ -177,7 +172,7 @@ function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E
local n = s.frames * channels
if s.fmt then
Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o)
end -- silence: the buffer is already zero
end
o += n * 4
end
a.tags = tags
@@ -238,7 +233,7 @@ function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
blockAt = w:tell()
blockFrames = 0
w:u8(9)
w:u24le(0) -- patched
w:u24le(0)
w:u32le(src.sampleRate)
w:u8(spec[3])
w:u8(src.channels)
+6 -22
View File
@@ -1,15 +1,8 @@
--!strict
--!native
--!optimize 2
-- audio/vorbis/Encode: a basic but valid Vorbis I encoder in Ogg. New code written from the Vorbis I specification
-- (no libvorbis code). Design: long blocks only (2048 samples; blocksize 0 is declared as 256 but never used), the
-- Vorbis window, the MDCT (codecs/audio/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a
-- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality-
-- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer
-- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then
-- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian
-- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact
-- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws.
-- audio/vorbis/Encode: Vorbis I encoder in Ogg, from the Vorbis I spec (no libvorbis code): long blocks only (2048),
-- one floor 1 per channel (30 posts), square-polar coupling, residue type 2, a fixed codebook set with Laplacian lengths.
local Mdct = require("@rosetta/codecs/audio/Mdct")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
@@ -99,7 +92,6 @@ type Book = {
values: number, -- lookup1 values per dimension
}
-- Huffman code lengths for weights w[1..n] (all > 0), at most 24 bits long (weights are floored to keep it so)
local function huffmanLengths(w: { number }): { number }
local n = #w
local total = 0
@@ -112,7 +104,6 @@ local function huffmanLengths(w: { number }): { number }
return lens
end
local minw = total * 2 ^ -20
-- nodes: leaves 1..n then internal; a simple O(n^2)-free approach with two sorted queues
local order = table.create(n, 0)
for i = 1, n do
order[i] = i
@@ -128,8 +119,8 @@ local function huffmanLengths(w: { number }): { number }
end
return a < b
end)
local q1, h1 = order, 1 -- leaves, ascending
local q2, h2, t2 = table.create(n, 0), 1, 0 -- internal nodes, created in ascending weight order
local q1, h1 = order, 1
local q2, h2, t2 = table.create(n, 0), 1, 0
local nextId = n
local function pop(): number
local a = if h1 <= n then q1[h1] else nil
@@ -161,7 +152,7 @@ local function huffmanLengths(w: { number }): { number }
return lens
end
-- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes
-- the spec's codeword assignment (lowest free leaf, in entry order)
local function assign(lens: { number }): { number }
local codes = table.create(#lens, 0)
local available = table.create(33, 0)
@@ -208,7 +199,6 @@ local function makeBook(dims: number, entries: number, weight: (number) -> numbe
return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values }
end
-- a VQ book of `dims` dimensions over integer values -h .. h times `scale`, Laplacian weights exp(-|v| / s)
local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book
local values = 2 * h + 1
local entries = values ^ dims
@@ -302,7 +292,6 @@ do
table.insert(xs, x)
end
table.sort(xs)
-- bisection order over the sorted list
local queue = { { 1, #xs } }
local qh = 1
while qh <= #queue do
@@ -424,7 +413,7 @@ local function floorVal(Y: { number }, j: number): number
end
end
end
return 0 -- unreachable for t in range; fall back to the prediction
return 0
end
-- ------------------------------------------------------------------------------------------------ headers
@@ -559,7 +548,6 @@ export type Options = {
serial: number,
}
-- the residue of one partition: vectors of each pass for class c
local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number)
local b = CLASS_BOOKS[c][pass]
if b < 0 then
@@ -639,7 +627,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
local k = 0
local lastWanted = -1 -- the last packet index needed (known once the input ends)
while true do
-- shift in the next 1024 input samples (zeros past the end)
for c = 1, ch do
local fr = frame[c]
table.move(fr, N2 + 1, N, 1)
@@ -678,8 +665,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
lastWanted = (total + N2 - 1) // N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024))
end
-- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024)
-- (frame k holds input [(k - 1) * 1024, (k + 1) * 1024): the shift above moved the window by 1024)
-- MDCT per channel
local energy = 0
for c = 1, ch do
local fr = frame[c]
@@ -821,7 +806,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
return mux:finish(), nil
end
-- the codebooks (tests check the Huffman lengths are a valid prefix code)
Encode.BOOKS = BOOKS
return Encode
+4 -22
View File
@@ -1,15 +1,7 @@
--!strict
-- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau
-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/audio/Mdct,
-- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last
-- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position).
-- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2,
-- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level
-- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Encode (audio/vorbis/Encode, new code): a basic
-- Ogg Vorbis encoder from an Audio or a streamed Decoder (long blocks, floor 1, coupled residue 2, a fixed codebook
-- set, quality -1 .. 10). Not supported: floor 0 (Err.UNSUPPORTED, as in stb_vorbis; no encoder has produced it since
-- 2000), chained streams (the first logical Vorbis stream is decoded), short blocks in the encoder.
-- The codec itself is codecs/audio/Vorbis; this folder maps it onto the file (container, tags, seeking, writing).
-- audio/vorbis: Ogg Vorbis (Vorbis I spec; RFC 5215); the decoder is a port of stb_vorbis 1.22 (public domain / MIT,
-- licenses/stb_vorbis-LICENSE.txt) with libvorbis' sample-exact trimming and seeking. Supports: 1-255 channels,
-- floor 1, residues 0-2, packetDecoder for Matroska / MP4; an encoder. Not supported: floor 0, chained streams.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -42,7 +34,6 @@ export type EncodeOptions = {
}
-- ------------------------------------------------------------------------------------------------ constants
-- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/audio/Pcm; identity past 8 channels)
local function waveOrder(ch: number): { number }
local m = Pcm.WAVE_FROM_VORBIS[ch]
if m then
@@ -55,7 +46,6 @@ local function waveOrder(ch: number): { number }
return id
end
-- the three headers -> ident, setup, vendor, tags, raw comment fields | nil, Err
local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, { VorbisComment.Field }?, Err.Err?)
local id, ierr = Setup.ident(h1.data, h1.offset, h1.size)
if not id then
@@ -98,7 +88,6 @@ function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err
function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
@@ -130,7 +119,6 @@ end
local Stream = {}
Stream.__index = Stream
-- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi)
local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number)
local lo = math.max(g0, self.startG, self.skipTo)
if hi > g0 + count then
@@ -152,7 +140,6 @@ local function copyOut(self: any, count: number): { { number } }
return t
end
-- decode packets until something is queued; false at the end of the stream
local function decodeMore(self: any): boolean
local reader, st = self.reader, self.st
while not self.ended do
@@ -251,7 +238,6 @@ function Stream.position(self: any): number
return (self.next - self.startG) / self.sampleRate
end
-- back to the first audio packet
local function restart(self: any)
local r = self.reader
r:rewind()
@@ -430,11 +416,7 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three
-- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet.
-- local pd = Vorbis.packetDecoder(h1, h2, h3)
-- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n]
-- pd:reset() -- after a seek
-- raw Vorbis packets: Matroska / WebM / MP4 carry the three headers in their codec private data
function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err?)
local function pk(b: buffer): any
return { data = b, offset = 0, size = buffer.len(b) }
+2 -11
View File
@@ -1,10 +1,7 @@
--!strict
--!native
--!optimize 2
-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). The
-- ADPCM block decoders moved to codecs/audio/Adpcm.
-- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau)
-- only calls them with ranges it has checked against the source length and the output size.
-- audio/wav/Codecs: PCM / float / G.711 sample loops into interleaved f32 and back; absorbed from wav-luau fd9a909.
local readu8, readi8, readu16, readi16, readu32, readi32 =
buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32
local readf32, readf64, writef32, writeu32 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writeu32
@@ -13,8 +10,7 @@ local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, b
local Codecs = {}
-- Integer PCM: count samples of `bytes` bytes each (1 = unsigned 8-bit, 2 / 3 / 4 = signed), little- or big-endian,
-- from src[off] to dst (f32) starting at sample index d.
-- integer PCM: 1 byte = unsigned, 2 / 3 / 4 bytes = signed
function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean)
local o = d * 4
if bytes == 1 then
@@ -64,7 +60,6 @@ function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: num
end
end
-- IEEE float, 4 or 8 bytes. tmp: an 8-byte scratch buffer for byte-swapping big-endian values.
function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean,
tmp: buffer)
local o = d * 4
@@ -95,7 +90,6 @@ function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: n
end
end
-- 8-bit companded (A-law / mu-law) through a 256-entry f32 table
function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: number, tbl: buffer)
local o = d * 4
for i = 0, count - 1 do
@@ -103,13 +97,10 @@ function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: num
end
end
-- copy frames from a block cache into the output: count f32 values
function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number)
buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4)
end
-- Encoder: count f32 samples from src (sample index s) to dst[off] as `kind` ("u8", "s16", "s24", "s32", "f32"),
-- little-endian, rounding to nearest and clamping to the integer range. Ranges are checked by the caller.
function Codecs.quantize(src: buffer, s: number, dst: buffer, off: number, count: number, kind: string)
local so = s * 4
if kind == "f32" then
+5 -29
View File
@@ -1,18 +1,8 @@
--!strict
--!optimize 2
-- audio/wav: WAVE in RIFF / RIFX (big-endian) / RF64 / BW64. Absorbed from wav-luau fd9a909 (same author, no
-- third-party code; the streaming decoder) on the shared containers/Riff, plus a new encoder.
-- Decode: PCM 8 / 16 / 24 / 32 bit, IEEE float 32 / 64, A-law, mu-law, IMA ADPCM, MS ADPCM, WAVE_FORMAT_EXTENSIBLE
-- wrapping any of them; odd-sized chunks with or without the pad byte; LIST/INFO tags; a data size of 0 or 0xFFFFFFFF
-- (streamed output) or past the end means "up to the end of the file" (a truncated file decodes what it has).
-- Encode: PCM u8 / s16 / s24 / s32 and float32 from an Audio or a streaming Decoder, WAVE_FORMAT_EXTENSIBLE when
-- there are more than 2 channels, more than 16 bits or over 48 kHz (as ffmpeg), fact for float, LIST/INFO tags,
-- RF64 (ds64) automatically past 4 GiB (Wav.encodeParts streams files over the 1 GiB buffer limit) or on request.
-- Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output.
--
-- local dec = Wav.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(4096) -> f32 buffer, frames
-- local audio = Wav.decode(Bytes.reader(buf)) -- Types.Audio
-- local file = Wav.encode(audio, { sampleFormat = "s24" })
-- audio/wav: WAVE in RIFF / RIFX / RF64 / BW64; absorbed from wav-luau fd9a909 (same author). Supports: PCM 8-32 bit,
-- float 32 / 64, A-law, mu-law, IMA / MS ADPCM, EXTENSIBLE, LIST/INFO tags, data size 0 / 0xFFFFFFFF (to the end);
-- encode PCM and f32, EXTENSIBLE and RF64 as ffmpeg. Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -36,14 +26,14 @@ local Wav = {
-- ------------------------------------------------------------------------------------------------ types
export type Tags = { [string]: string }
export type OpenOptions = {
maxBytes: number?, -- unused (the file is already in memory); kept for symmetry
maxBytes: number?,
}
export type EncodeOptions = {
sampleFormat: ("u8" | "s16" | "s24" | "s32" | "f32")?, -- default "s16"
rf64: (boolean | "auto")?, -- default "auto": RF64 only when the file passes 4 GiB
extensible: boolean?, -- force (true) or forbid (false) WAVE_FORMAT_EXTENSIBLE; default as ffmpeg
channelMask: number?, -- the EXTENSIBLE speaker mask (default: ffmpeg's default layout for the channel count)
tags: Tags?, -- default: the Audio's tags (title, artist, album, comment, date, genre, track, ...)
tags: Tags?, -- default: the Audio's tags
rf64Threshold: number?, -- testing: the RIFF size past which "auto" switches to RF64 (default 0xFFFFFFFF)
}
@@ -144,7 +134,6 @@ export type Decoder = typeof(setmetatable(
))
local function trimTag(s: string): string
-- strip trailing NULs / spaces
local e = #s
while e > 0 do
local c = string.byte(s, e)
@@ -166,7 +155,6 @@ function Wav.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole file
function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Wav.open(r, opts)
if not dec then
@@ -191,7 +179,6 @@ local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTY
local TAG_IDS = { title = "INAM", artist = "IART", album = "IPRD", comment = "ICMT", date = "ICRD", genre = "IGNR", track = "ITRK", encoder = "ISFT", copyright = "ICOP", engineer = "IENG", subject = "ISBJ", keywords = "IKEY" }
local BLOCK = 65536 -- frames per data piece when streaming a Decoder
-- the body of the encoder: { buffer } pieces of the file | nil, Err
local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): (any, Err.Err?)
if type(value) ~= "table" then
return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder")
@@ -312,19 +299,15 @@ local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean):
return w:finish({ parts = asParts })
end
-- encode(audio or decoder, opts?) -> buffer | nil, Err
function Wav.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
return encodeParts(value, opts, false)
end
-- encodeParts(audio or decoder, opts?) -> { buffer } | nil, Err: the file as pieces to write one after the other
-- (header, sample blocks, ...), without the 1 GiB single-buffer limit; RF64 past 4 GiB
function Wav.encodeParts(value: any, opts: EncodeOptions?): ({ buffer }?, Err.Err?)
return encodeParts(value, opts, true)
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err: the streaming decoder (Types.Decoder) over the file in r's range
function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?)
if type(r) == "buffer" or type(r) == "string" then
r = Bytes.reader(if type(r) == "string" then buffer.fromstring(r) else r :: any)
@@ -550,8 +533,6 @@ function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- Decodes up to maxFrames frames from the current position. Returns a buffer of interleaved f32 samples
-- (frames * channels values; `out` is reused when given and large enough) and the frame count (0 = end).
function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, number)
local ch = self.channels
local req = math.floor(tonumber(maxFrames) or 0)
@@ -581,7 +562,6 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer,
self._pos += want
return dst, want
end
-- block formats: decode a block into the cache, copy out of it
local spb, ba = self._spb, self.blockAlign
local cache = self._cache :: buffer
local done = 0
@@ -612,7 +592,6 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer,
return dst, done
end
-- Moves to a time in seconds (clamped to the stream).
function Decoder.seek(self: Decoder, seconds: number)
local f = math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)
if f ~= f then
@@ -621,7 +600,6 @@ function Decoder.seek(self: Decoder, seconds: number)
self._pos = math.clamp(f, 0, self.frames)
end
-- Moves to a frame index (clamped).
function Decoder.seekFrame(self: Decoder, frame: number)
local f = math.floor(tonumber(frame) or 0)
if f ~= f then
@@ -630,12 +608,10 @@ function Decoder.seekFrame(self: Decoder, frame: number)
self._pos = math.clamp(f, 0, self.frames)
end
-- Current position in seconds.
function Decoder.position(self: Decoder): number
return self._pos / self.sampleRate
end
-- Current position in frames.
function Decoder.tell(self: Decoder): number
return self._pos
end
+6 -20
View File
@@ -1,17 +1,7 @@
--!strict
-- audio/wavpack: WavPack (.wv) files: the block sequence around codecs/audio/WavPack, APEv2 tags, the .wvc correction
-- file of hybrid lossless files. Written from the WavPack 5 file format document (David Bryant) and the WavPack 5.9.0
-- library's file handling (open_utils.c; BSD 3-clause, licenses/wavpack-LICENSE.txt).
-- Supports: lossless and hybrid streams, integer 8 - 32 bit and 32-bit float, 1 - 4096 channels (WAV order, as the
-- encoder stores them), non-standard sample rates, the correction file (opts.correction, else opts.resolve("<name>c")
-- on hosts with files) which makes a hybrid file lossless, garbage between blocks (resync), sample-accurate seeking
-- (every block is independent), APEv2 tags at the end (codecs/audio/ApeTag). Without a correction file a hybrid file
-- decodes lossy (as wvunpack does). Not supported: DSD (Err.UNSUPPORTED), WavPack 1 - 3 files, encoding.
--
-- local dec = WavPack.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, float, hybrid, lossless, ...
-- local f32, n = dec:read(4096)
-- local i32, n = dec:readInt(4096) -- integer streams: the samples as wvunpack writes them
-- local audio = WavPack.decode(Bytes.reader(buf)) -- Types.Audio
-- audio/wavpack: WavPack (.wv) via codecs/audio/WavPack, from the WavPack 5 file format document and WavPack 5.9.0's
-- open_utils.c (BSD 3-clause, licenses/wavpack-LICENSE.txt). Supports: lossless and hybrid (lossy without the .wvc, as
-- wvunpack), 8-32-bit integer and float, 1-4096 channels, seeking, APEv2. Not supported: DSD, WavPack 1-3, encoding.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -35,9 +25,9 @@ local WavPack = {
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
correction: (buffer | string)?, -- the .wvc file of a hybrid file (default: opts.resolve(name .. "c") when given)
resolve: ((uri: string) -> buffer?)?, -- sibling files (the api passes it for paths)
name: string?, -- the file name (the api passes it)
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
resolve: ((uri: string) -> buffer?)?,
name: string?,
maxFrames: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -50,7 +40,6 @@ function WavPack.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
function WavPack.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = WavPack.open(r, opts)
if not dec then
@@ -67,7 +56,6 @@ end
-- ------------------------------------------------------------------------------------------------ open
type Index = { offsets: { { number } }, starts: { number }, samples: { number }, total: number, first: number, md5: string? }
-- index(buf, base, limit) -> the frames (block offsets per frame) of a .wv / .wvc block sequence
local function index(buf: buffer, base: number, limit: number): (Index?, string?)
local at = base
local idx: Index = { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 }
@@ -142,7 +130,6 @@ local function correctionFile(opts: OpenOptions?): buffer?
return nil
end
-- open(r, opts?) -> Decoder | nil, Err
function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
if type(r) == "buffer" then
r = Bytes.reader(r :: any)
@@ -167,7 +154,6 @@ function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err
local count = #idx.offsets
local last = idx.starts[count] + idx.samples[count]
local frames = if idx.total >= 0 then math.min(idx.total, last) else last
-- the correction file: its frames by start sample
local cbuf = if info.hybrid then correctionFile(opts) else nil
local cfor: { [number]: { number } } = {}
if cbuf then
+6 -21
View File
@@ -1,16 +1,7 @@
--!strict
-- cad/step/Brep: the injected B-rep plug-in (Rosetta.plugins.brep; rosetta never requires a kernel). Normalises
-- the plug-in table, calls it under pcall (kernels throw on bad geometry) and turns its tessellated meshes into a
-- Scene. Interpreted on purpose: the plug-in's errors unwind through here.
--
-- The interface (every function may throw; results are checked):
-- read(text: string, opts) -> { bodies = { Body }, stats = { ... }? } STEP text -> B-rep bodies (body.name?,
-- body.color? = Color3 | { r, g, b } | { 1, 2, 3 })
-- write(bodies: { Body }, opts) -> string bodies -> STEP text
-- tessellate(body: Body, opts) -> { positions = { vector | {x, y, z} }, normals = { ... }?, indices = { 1-based
-- triples }, faceOf = { [triangle] = Face (face.color?) }? }
-- or brep-luau's modules as they are: { Step = , StepBrep = , StepWrite = , Tess = } (adapted here: read =
-- StepBrep.read(Step.parse(text)), write = StepWrite.write with options.colors from body.color, tessellate = Tess.body).
-- cad/step/Brep: the injected B-rep plug-in (Rosetta.plugins.brep; never required by rosetta), called under pcall.
-- Interface (each may throw): read(text, opts) -> { bodies, stats? }; write(bodies, opts) -> text;
-- tessellate(body, opts) -> { positions, normals?, indices (1-based triples), faceOf? }; or brep-luau's modules as-is.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
@@ -30,7 +21,7 @@ local function rgbOf(c: any): (number?, number?, number?)
if type(c) == "table" then
return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3]
end
return (c :: any).R, (c :: any).G, (c :: any).B -- Color3
return (c :: any).R, (c :: any).G, (c :: any).B
end)
if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then
return r, g, b
@@ -38,7 +29,6 @@ local function rgbOf(c: any): (number?, number?, number?)
return nil, nil, nil
end
-- plugin(p) -> the normalised interface, or nil + the reason
function Brep.plugin(p: any): (Plugin?, string?)
if type(p) ~= "table" then
return nil, "needs the B-rep plug-in (Rosetta.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })"
@@ -82,7 +72,6 @@ function Brep.plugin(p: any): (Plugin?, string?)
return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules"
end
-- find(opts) -> the plug-in from opts.brep or opts.plugins.brep
function Brep.find(opts: any): (Plugin?, Err.Err?)
local p = nil
if type(opts) == "table" then
@@ -98,7 +87,6 @@ function Brep.find(opts: any): (Plugin?, Err.Err?)
return plug, nil
end
-- read(plug, text, opts) -> bodies, result | nil, Err
function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err.Err?)
local ok, res = pcall(plug.read, text, opts)
if not ok then
@@ -110,7 +98,6 @@ function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err
return res.bodies, res, nil
end
-- write(plug, bodies, opts) -> text | nil, Err
function Brep.write(plug: Plugin, bodies: { any }, opts: any): (string?, Err.Err?)
local w = plug.write
if not w then
@@ -130,7 +117,7 @@ local function xyz(p: any): (number, number, number)
if type(p) == "table" then
return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0
end
return (p :: any).X, (p :: any).Y, (p :: any).Z -- vector / Vector3
return (p :: any).X, (p :: any).Y, (p :: any).Z
end
local function linear(c: number): number
@@ -138,8 +125,7 @@ local function linear(c: number): number
return if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4
end
-- scene(plug, bodies, opts) -> Scene: one node + mesh per body, one primitive per face colour (materials shared by
-- colour; baseColor = the STEP colour converted from sRGB to linear, extras.color = the colour as written)
-- baseColor = the STEP colour converted from sRGB to linear; extras.color = the colour as written
function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Err.Err?)
local tess = plug.tessellate
if not tess then
@@ -196,7 +182,6 @@ function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Er
end
end
local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil)
-- triangles grouped by colour, in first-seen order
local groups: { { mat: number, tris: { number } } } = {}
local byMat: { [number]: { mat: number, tris: { number } } } = {}
local faceOf = if type(mesh.faceOf) == "table" then mesh.faceOf else {}
+3 -21
View File
@@ -1,15 +1,7 @@
--!strict
--!native
-- cad/step/Parse: ISO 10303-21 (STEP physical file, editions 1-3) text -> header + entity instances. A single pass
-- over the text: comments, the HEADER section, any number of DATA sections (edition 3 `DATA('name', ('schema'));`),
-- ANCHOR / REFERENCE / SIGNATURE sections kept as raw text, simple and complex (external mapping) instances, every
-- parameter kind (integer, real, string with its \S\ \X\ \X2\ \X4\ escapes decoded to UTF-8, enumeration, binary,
-- entity reference, $, *, list, typed parameter). Never throws: failures return nil, message, offset.
--
-- Values: numbers; strings; { enum = "T" }; { ref = 12 }; { binary = "0FF" }; { typed = "LENGTH_MEASURE", value = v };
-- lists as arrays; NULL / DERIVED sentinels (from the caller). A real literal with an integral value (`0.`, `1.E2`)
-- is recorded in the metatable of the list (or typed table) holding it (`__reals = { [index | "value"] = true }`), so
-- the writer prints it back as a real; integral numbers without that mark are written as integers.
-- cad/step/Parse: ISO 10303-21 text -> header + entity instances, one pass; never throws (nil, message, offset).
-- An integral real (`0.`, `1.E2`) is marked in its holder's metatable (`__reals = { [index | "value"] = true }`).
local Parse = {}
local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor
@@ -32,7 +24,6 @@ local function fail(ctx: Ctx, msg: string, at: number): nil
return nil
end
-- the next position that is not white space or inside a /* comment */ (n + 1 at the end; an open comment -> error)
local function skip(ctx: Ctx, i: number): number
local s, n = ctx.s, ctx.n
while i <= n do
@@ -60,7 +51,6 @@ local function isWord(c: number): boolean
return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57)
end
-- keyword at i ([!]A-Z_ A-Z0-9_*) -> word, next; nil when there is none
local function keyword(ctx: Ctx, i: number): (string?, number)
local s, n = ctx.s, ctx.n
local j = i
@@ -77,7 +67,6 @@ local function keyword(ctx: Ctx, i: number): (string?, number)
return string.upper(ssub(s, i, j - 1)), j
end
-- UTF-8 of a code point
local function utf8char(cp: number): string
if cp < 0x80 then
return schar(cp)
@@ -100,9 +89,7 @@ local function hexAt(s: string, i: number, k: number): number?
return tonumber(h, 16)
end
-- the text between the quotes of a string literal -> its value ('' -> ', \\ -> \, \S\c, \X\hh, \X2\..\X0\, \X4\..\X0\,
-- \P?\ page switches ignored: every page reads as ISO 8859-1). Bytes >= 0x80 written raw (common, though not allowed)
-- pass through.
-- Part 21 escapes: '' \\ \S\c \X\hh \X2\..\X0\ \X4\..\X0\; \P?\ ignored (ISO 8859-1); raw bytes >= 0x80 pass through
function Parse.unescape(raw: string): string
if not sfind(raw, "[\\']") then
return raw
@@ -185,11 +172,9 @@ local function markReal(t: { [any]: any }, key: any)
mt.__reals[key] = true
end
-- one parameter at i -> value, next, integralReal (nil value + ctx.err on failure)
local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean)
local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number)
-- i is just past "("
local s = ctx.s
local out = {}
i = skip(ctx, i)
@@ -309,7 +294,6 @@ value = function(ctx: Ctx, i: number, depth: number): (any, number, boolean)
end
Parse.value = value
-- the simple record at i: NAME(params) -> type, args, next
local function record(ctx: Ctx, i: number): (string?, { any }?, number)
local word, j = keyword(ctx, i)
if not word then
@@ -326,7 +310,6 @@ local function record(ctx: Ctx, i: number): (string?, { any }?, number)
return word, args, k
end
-- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil
local function expect(ctx: Ctx, i: number, ch: number, what: string): number?
i = skip(ctx, i)
if sbyte(ctx.s, i) ~= ch then
@@ -353,7 +336,6 @@ export type Result = {
terminated: boolean,
}
-- parse(s, opts) -> Result | nil, message, offset (1-based position in s)
function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?)
local ctx: Ctx = { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived }
local res: Result = {
+2 -8
View File
@@ -1,16 +1,13 @@
--!strict
--!native
-- cad/step/Write: header + entity instances -> ISO 10303-21 text. Values as cad/step/Parse produces them; strings
-- re-escaped (' -> '', \ -> \\, UTF-8 outside printable ASCII -> \X2\..\X0\ / \X4\..\X0\, control bytes and invalid
-- UTF-8 -> \X\hh), reals printed with the fewest digits (15..17) that read back to the same double. Never throws:
-- failures return nil, message.
-- cad/step/Write: header + entity instances -> ISO 10303-21 text (escaped strings, shortest round-trip reals).
local Write = {}
local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge
local MAX_DEPTH = 100
-- the shortest %g form that reads back exactly, in Part 21 syntax (a '.' always, upper-case E)
-- Part 21 real: a '.' always, upper-case E
function Write.real(v: number): string?
if v ~= v or v == huge or v == -huge then
return nil
@@ -45,7 +42,6 @@ local function hex(v: number, k: number): string
return table.concat(out)
end
-- a string's Part 21 literal (with the quotes)
function Write.str(s: string): string
if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \
return "'" .. s .. "'"
@@ -72,7 +68,6 @@ function Write.str(s: string): string
end
i += 1
else
-- a UTF-8 sequence -> code point
local cp: number? = nil
local len = 1
if c >= 0xC2 and c < 0xE0 then
@@ -235,7 +230,6 @@ value = function(ctx: Ctx, v: any, real: boolean, depth: number): boolean
end
Write.value = value
-- record(ctx, type, args) -> appends TYPE(args)
function Write.record(ctx: Ctx, t: any, args: any): boolean
if not isName(t) then
ctx.err = "bad entity type " .. tostring(t)
+11 -41
View File
@@ -1,24 +1,7 @@
--!strict
-- cad/step: STEP physical files (ISO 10303-21 editions 1-3, "Part 21": AP203 / AP214 / AP242 and any other schema).
-- New code. Reads and writes the entity graph (Types.Cad) fully in-library: the header (FILE_DESCRIPTION / FILE_NAME /
-- FILE_SCHEMA + any other header entity), every DATA section (edition 3 named sections: entity.section), simple and
-- complex instances (type "COMPLEX", parts = { { type, args } }), every parameter kind: integers and reals (numbers;
-- integral reals such as `0.` keep their real-ness through a metatable mark, see Parse), strings (escapes decoded to
-- UTF-8: \S\ \X\ \X2\ \X4\, '' and \\), { enum = "T" } (.T. / .F. booleans too), { ref = id }, { binary = "0FF" },
-- { typed = "LENGTH_MEASURE", value = v }, lists, Step.NULL ($) and Step.DERIVED (*), comments; ANCHOR / REFERENCE /
-- SIGNATURE sections kept as raw text (meta.source.extra) and written back. parse -> write -> parse gives the same
-- entities. Writes one instance per line in id order, strings escaped as Part 21 requires (\X2\ for non-ASCII).
--
-- B-rep bodies and tessellation come from an injected kernel, never required by rosetta:
-- F.plugins.brep = { read = fn(text, opts) -> { bodies, stats? }, write = fn(bodies, opts) -> text,
-- tessellate = fn(body, opts) -> { positions, normals?, indices (1-based), faceOf? } }
-- or brep-luau's modules as they are: F.plugins.brep = { Step = , StepBrep = , StepWrite = , Tess = }
-- (the full contract is in cad/step/Brep). Step.toBodies(cad, opts) / Step.fromBodies(bodies, opts) /
-- Step.tessellate(cad | bodies, opts) take it from opts.brep or opts.plugins.brep; F.cad.toBodies / fromBodies /
-- tessellate pass F.plugins. Tessellated scenes: one node + mesh per body, one primitive per face colour, z up,
-- millimetres (meta.unit = 0.001).
-- Not supported: STEP-XML (ISO 10303-28), compressed .stpZ, edition 3 value instances (#NAME, @constants: CORRUPT),
-- code pages other than ISO 8859-1 in \S\ escapes (\P?\ is ignored).
-- cad/step: STEP physical files (ISO 10303-21 eds 1-3; AP203 / AP214 / AP242 / any schema). Supports: header, DATA
-- sections, simple and complex instances, every parameter kind, ANCHOR / REFERENCE / SIGNATURE kept raw; B-rep via the
-- injected plug-in (cad/step/Brep). Not supported: STEP-XML (10303-28), .stpZ, ed. 3 value instances, \P?\ code pages.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -41,19 +24,19 @@ local Step = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 2^30)
maxEntities: number?, -- refuse more instances (default 2^24)
maxBytes: number?, -- default 2^30
maxEntities: number?, -- default 2^24
}
export type EncodeOptions = {
schema: string?, -- "AP203" | "AP214" | "AP242" | a schema name: overrides the header's FILE_SCHEMA
name: string?, -- FILE_NAME name (default: the header's, else "model")
timestamp: string?, -- FILE_NAME time_stamp when the header has none (default "1970-01-01T00:00:00")
crlf: boolean?, -- CRLF line ends (default LF)
schema: string?, -- overrides the header's FILE_SCHEMA
name: string?, -- default: the header's, else "model"
timestamp: string?, -- default "1970-01-01T00:00:00"
crlf: boolean?,
}
export type BrepOptions = {
brep: any?, -- the plug-in (else opts.plugins.brep)
brep: any?,
plugins: { [string]: any }?,
chord: number?, -- tessellation sag in millimetres (default 0.05); opts.tess = the kernel's own options instead
chord: number?, -- millimetres (default 0.05)
tess: { [string]: any }?,
}
@@ -68,7 +51,6 @@ local SCHEMAS = {
}
Step.SCHEMAS = SCHEMAS
-- a FILE_SCHEMA name -> "AP203" | "AP214" | "AP242" | the name itself
local function schemaOf(name: string): string
local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name)
if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then
@@ -203,7 +185,6 @@ function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?)
end
end
end
-- entities by section, in id order
local ids = {}
for id, e in cad.entities do
if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then
@@ -257,7 +238,6 @@ function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- get(cad, id | { ref = id }) -> the entity
function Step.get(cad: Types.Cad, id: any): Types.StepEntity?
if type(id) == "table" then
id = id.ref
@@ -265,7 +245,6 @@ function Step.get(cad: Types.Cad, id: any): Types.StepEntity?
return cad.entities[id]
end
-- ids(cad) -> the instance ids in ascending order
function Step.ids(cad: Types.Cad): { number }
local out = {}
for id in cad.entities do
@@ -275,7 +254,6 @@ function Step.ids(cad: Types.Cad): { number }
return out
end
-- byType(cad, "ADVANCED_FACE") -> the ids of the instances of that type (complex ones with such a part too), ascending
function Step.byType(cad: Types.Cad, name: string): { number }
local n = string.upper(name)
local out = {}
@@ -295,7 +273,6 @@ function Step.byType(cad: Types.Cad, name: string): { number }
return out
end
-- part(entity, "TYPE") -> the args of that type (the entity's own, or one part of a complex instance)
function Step.part(e: Types.StepEntity?, name: string): { any }?
if not e then
return nil
@@ -313,7 +290,6 @@ function Step.part(e: Types.StepEntity?, name: string): { any }?
return nil
end
-- add(cad, type, args) -> id: a new instance after the highest id
function Step.add(cad: Types.Cad, type: string, args: { any }): number
local top = 0
for id in cad.entities do
@@ -327,7 +303,6 @@ function Step.add(cad: Types.Cad, type: string, args: { any }): number
return id
end
-- real(list, index) -> list: marks list[index] as a real (an integral value is then written `3.`, not `3`)
function Step.real(t: { [any]: any }, key: any): { [any]: any }
local mt: any = getmetatable(t)
if not mt then
@@ -338,12 +313,10 @@ function Step.real(t: { [any]: any }, key: any): { [any]: any }
return t
end
-- new(schema?) -> an empty Cad ("AP214" by default)
function Step.new(schema: string?): Types.Cad
return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } }
end
-- plugin(p) -> the normalised B-rep plug-in interface (see cad/step/Brep) | nil, reason
Step.plugin = Brep.plugin
local function textOf(cad: Types.Cad): (string?, Err.Err?)
@@ -354,7 +327,6 @@ local function textOf(cad: Types.Cad): (string?, Err.Err?)
return buffer.tostring(buf), nil
end
-- toBodies(cad, opts) -> bodies, result (the plug-in's read result: stats, warnings, ...) | nil, Err
function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any)
local plug, perr = Brep.find(opts)
if not plug then
@@ -371,7 +343,6 @@ function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any)
return bodies, res
end
-- fromBodies(bodies, opts) -> Cad (the plug-in writes STEP text, parsed here) | nil, Err
function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err.Err?)
if type(bodies) ~= "table" then
return nil, Err.new(Err.ARG, "needs a list of bodies")
@@ -387,7 +358,6 @@ function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err.
return Step.decode(Bytes.reader(buffer.fromstring(text)))
end
-- tessellate(cad | bodies, opts) -> Scene (one node + mesh per body, z up, millimetres) | nil, Err
function Step.tessellate(value: any, opts: BrepOptions?): (Types.Scene?, Err.Err?)
local plug, perr = Brep.find(opts)
if not plug then
+14 -22
View File
@@ -1,7 +1,6 @@
--!strict
--!native
-- data/cbor/Codec: the CBOR (RFC 8949) decoder and encoder behind data/cbor. Never throws: errors return nil,
-- message, offset.
-- data/cbor/Codec: CBOR (RFC 8949) decoder and encoder; never throws (errors return nil, message, offset).
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
@@ -16,14 +15,13 @@ end }
local SimpleMeta = { __tostring = function(s: any): string
return "cbor.simple(" .. s.value .. ")"
end }
-- tagged(tag, value) -> { tag, value }: a tag this library does not interpret
function Codec.tagged(tag: number, value: any): { tag: number, value: any }
return setmetatable({ tag = tag, value = value }, TaggedMeta) :: any
end
function Codec.isTagged(v: any): boolean
return type(v) == "table" and getmetatable(v) == TaggedMeta
end
-- simple(n) -> an unassigned simple value (0..19, 32..255)
-- unassigned simple values: 0..19, 32..255
function Codec.simple(n: number): { value: number }
return setmetatable({ value = n }, SimpleMeta) :: any
end
@@ -34,7 +32,6 @@ Codec.undefined = table.freeze(setmetatable({}, { __tostring = function()
return "undefined"
end }))
-- decimal text of a big-endian unsigned byte string (any length)
local function bigText(s: string): string
local limbs = {} -- base 1e7, little-endian
for i = 1, #s do
@@ -58,7 +55,6 @@ local function bigText(s: string): string
end
return table.concat(out)
end
-- text + 1 for a decimal string
local function incText(s: string): string
local digits: { number } = table.create(#s) :: { number }
for i = 1, #s do
@@ -81,18 +77,18 @@ local function incText(s: string): string
end
export type DecodeOptions = {
bigInts: ("number" | "string")?, -- integers / bignums past 2^53: "string" keeps exact decimal text
null: any?, -- the value for null (default Types.null)
undefined: any?, -- the value for undefined (default Codec.undefined)
bigInts: ("number" | "string")?,
null: any?, -- default Types.null
undefined: any?, -- default Codec.undefined
maxDepth: number?, -- default 512
dates: boolean?, -- tags 0 / 1 as Types.Date (default true)
dates: boolean?, -- default true
}
type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: number, dates: boolean }
local BREAK = {} -- the 0xFF stop code, inside indefinite items
local BREAK = {} -- 0xFF break stop code
-- the argument of a head: number (or nil, "text" for u64 past 2^53 when big), nil means indefinite (ai 31)
-- additional information 31: indefinite length
local function arg(st: St, ai: number): (number?, string?, string?)
local r = st.r
if ai < 24 then
@@ -169,7 +165,7 @@ local function tag(st: St, t: number, v: any): (any, string?)
n = n * 256 + string.byte(s, i)
end
if n >= 9007199254740992 then
-- exact text; as a number, read back from that text (correctly rounded, unlike the running sum)
-- read back from the exact text: correctly rounded, unlike the running sum
local text = bigText(s)
if t == 3 then
text = incText(text)
@@ -347,7 +343,6 @@ function item(st: St, depth: number): (any, string?)
if v == BREAK then
return nil, "unexpected break"
end
-- bignum content arrives as a buffer: hand the tag its bytes
if (n == 2 or n == 3) and type(v) == "buffer" then
return tag(st, n, buffer.tostring(v))
end
@@ -355,7 +350,6 @@ function item(st: St, depth: number): (any, string?)
end
end
-- decode(r, opts) -> value | nil, message, offset (one item; r is left after it)
function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?)
local o: DecodeOptions = opts or {}
local st: St = {
@@ -378,10 +372,10 @@ end
-- ------------------------------------------------------------------------------------------------ encode
export type EncodeOptions = {
compactFloats: boolean?, -- floats in the shortest of half / single / double that keeps the value (default false)
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
emptyTable: ("array" | "map")?, -- a plain empty table (default "array")
dates: ("string" | "epoch")?, -- Types.Date as tag 0 text (default) or tag 1 seconds
compactFloats: boolean?, -- default false
sortKeys: boolean?, -- default true
emptyTable: ("array" | "map")?, -- default "array"
dates: ("string" | "epoch")?, -- tag 0 text (default) or tag 1 epoch seconds
maxDepth: number?, -- default 512 (also catches cycles)
}
@@ -410,7 +404,6 @@ local function head(w: Bytes.Writer, major: number, n: number)
end
end
-- the half-float bits of x when x is exactly representable, else nil
local function toHalf(x: number): number?
if x ~= x then
return 0x7E00
@@ -423,7 +416,7 @@ local function toHalf(x: number): number?
if a == 0 then
return sign
end
local m, e = math.frexp(a) -- a = m * 2^e, 0.5 <= m < 1
local m, e = math.frexp(a)
local exp = e - 1 + 15
if exp >= 31 then
return nil
@@ -554,7 +547,6 @@ local function enc(st: ESt, v: any, depth: number): boolean
return true
end
-- encode(v, opts) -> buffer | nil, message
function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?)
local o: EncodeOptions = opts or {}
local st: ESt = {
+8 -11
View File
@@ -1,10 +1,7 @@
--!strict
-- data/cbor: CBOR (RFC 8949). New code. Supports: every major type, indefinite-length strings / arrays / maps, half /
-- single / double floats, tags (0 / 1 date-times as Types.Date, 2 / 3 bignums as numbers or exact decimal text,
-- 55799 self-describe stripped, others kept as Cbor.tagged(tag, value)), simple values (Cbor.simple(n),
-- Cbor.undefined), byte strings as buffers, maps as Types.object (key order kept; keys of any type), sequences
-- (RFC 8742, opts.all). Encode: preferred (shortest) integer and length heads, float64 unless opts.compactFloats,
-- definite lengths. Not supported: other semantic tags (decimal fractions, bigfloats, ...) stay tagged values.
-- data/cbor: CBOR (RFC 8949), new code. Supports: every major type, indefinite lengths, half / single / double
-- floats, tags 0 / 1 (Types.Date), 2 / 3 (bignums), 55799 (stripped), others as Cbor.tagged; simple values; sequences
-- (RFC 8742). Encode: shortest heads, definite lengths. Not supported: other semantic tags (kept as tagged values).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -22,11 +19,11 @@ local Cbor = {
}
export type DecodeOptions = Codec.DecodeOptions & {
all: boolean?, -- a CBOR sequence: every item into an array (default false: exactly one item)
all: boolean?, -- default false
}
export type EncodeOptions = Codec.EncodeOptions & {
all: boolean?, -- the value is an array of items, written as a sequence
selfDescribe: boolean?, -- prefix the 55799 self-describe tag (d9 d9 f7)
all: boolean?,
selfDescribe: boolean?, -- 55799 tag prefix (d9 d9 f7)
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -91,9 +88,9 @@ function Cbor.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
Cbor.tagged = Codec.tagged -- tagged(tag, value) -> a value written as that tag
Cbor.tagged = Codec.tagged
Cbor.isTagged = Codec.isTagged
Cbor.simple = Codec.simple -- simple(n) -> a simple value
Cbor.simple = Codec.simple
Cbor.isSimple = Codec.isSimple
Cbor.undefined = Codec.undefined
+13 -18
View File
@@ -1,10 +1,7 @@
--!strict
-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv module). New code. Supports: any
-- one-byte delimiter (opts.delimiter, or "auto" to pick , ; tab |), quoted fields with doubled quotes and embedded
-- line breaks, CRLF / LF / CR line ends, a header row (opts.header: rows become Types.object keyed by the column
-- names, in column order), number conversion by option; encode from arrays of arrays or of keyed rows, quoting only
-- where needed (like Python's QUOTE_MINIMAL) or always. Blank lines are skipped. Not supported: escape characters
-- other than the doubled quote, multi-byte delimiters.
-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv), new code. Supports: one-byte or
-- "auto" delimiter, quoted fields with "" and line breaks, CRLF / LF / CR, header rows, numbers by option; encode
-- quotes minimally (QUOTE_MINIMAL) or always. Not supported: other escapes, multi-byte delimiters.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,19 +21,19 @@ local Csv = {
}
export type DecodeOptions = {
delimiter: string?, -- one byte (default ","; "auto" guesses from the first line among , ; tab |)
quote: string?, -- the quote byte (default '"')
header: boolean?, -- the first row names the columns: rows become Types.object (default false: arrays)
numbers: boolean?, -- fields that are numbers become numbers (default false: every field is a string)
maxRows: number?, -- refuse more rows (default unlimited)
delimiter: string?, -- default ","; "auto": one of , ; tab |
quote: string?, -- default '"'
header: boolean?, -- default false
numbers: boolean?, -- default false
maxRows: number?, -- default unlimited
}
export type EncodeOptions = {
delimiter: string?, -- default ","
quote: string?, -- default '"'
newline: string?, -- the row terminator (default "\r\n", as RFC 4180 and Python's csv)
quoteAll: boolean?, -- quote every field (default false: only those that need it)
columns: { string }?, -- keyed rows: the column order (default: the keys of the rows in first-seen order)
header: boolean?, -- keyed rows: write the header row (default true)
newline: string?, -- default "\r\n" (RFC 4180)
quoteAll: boolean?, -- default false
columns: { string }?, -- default: keys in first-seen order
header: boolean?, -- default true
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -80,7 +77,6 @@ local function guess(s: string, q: string): string
return best
end
-- rows(s, opts) -> { { string } } | nil, Err
function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?)
local o: DecodeOptions = opts or {}
local q = o.quote or '"'
@@ -98,7 +94,7 @@ function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?)
local row: { string } = {}
local n = #s
local i = 1
local rowEmpty = true -- the current line has no field text yet (blank lines are skipped)
local rowEmpty = true
while true do
local c = byte(s, i)
local field: string
@@ -141,7 +137,6 @@ function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?)
rowEmpty = false
i += 1
else
-- end of the row: CRLF / LF / CR / end of data
if c == 13 and byte(s, i + 1) == 10 then
i += 2
elseif c ~= nil then
+8 -13
View File
@@ -1,11 +1,7 @@
--!strict
-- data/ini: INI / config files, read the way Python's configparser does (interpolation off, key case kept). New code.
-- Supports: [sections] (name = everything between the first '[' and the last ']'), key = value and key: value,
-- ; and # comment lines (indented too), indented continuation lines (joined with "\n"), keys before any section (at
-- the top level), duplicate keys / sections (the last value wins, sections merge), inline comments, keys without a
-- value and typed values by option. Decodes to a Types.object of sections (each a Types.object of strings), top-level
-- keys beside them. Encode writes configparser's layout ("key = value", a blank line after each section, nested
-- tables as dotted section names). Not supported: interpolation, the DEFAULT section's inheritance, escapes.
-- data/ini: INI files read the way Python's configparser does (interpolation off, key case kept), new code. Supports:
-- [sections], key = / key:, ; and # comments, continuation lines, top-level keys, duplicates (last wins), inline
-- comments, keys without values, typed values by option. Not supported: interpolation, DEFAULT inheritance, escapes.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,10 +21,10 @@ local Ini = {
}
export type DecodeOptions = {
inlineComments: boolean?, -- strip " ;..." / " #..." after values (default false, like configparser)
allowNoValue: boolean?, -- a line with a key and no delimiter is the key with value true (default false: an error)
types: boolean?, -- values that are numbers / true / false / yes / no / on / off become numbers / booleans
strict: boolean?, -- a duplicate section or key is an error (default false: last wins / merge)
inlineComments: boolean?, -- default false (configparser)
allowNoValue: boolean?, -- default false
types: boolean?,
strict: boolean?, -- default false
}
export type EncodeOptions = {
delimiter: string?, -- default " = "
@@ -92,9 +88,8 @@ function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
if trimmed == "" then
lastKey = nil
elseif string.match(trimmed, "^[;#]") then
-- a comment line (configparser: also when indented); it does not end a continuation
-- configparser: comment lines may be indented and do not end a continuation
elseif lastKey and indent > lastIndent then
-- continuation of the previous value
local v = trimmed
if o.inlineComments then
v = string.match(v, "^(.-)%s+[;#]") or v
+4 -5
View File
@@ -1,7 +1,6 @@
--!strict
-- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/text/Json (which see for the value mapping and options).
-- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or
-- pretty. JSON Lines through codecs/text/Json.lines. Not supported: JSON5 / comments / trailing commas.
-- data/json: JSON (RFC 8259) over codecs/text/Json. Supports: decode to Luau values, compact / pretty encode, JSON
-- Lines. Not supported: JSON5 / comments / trailing commas.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -20,10 +19,10 @@ local JsonFormat = {
}
export type DecodeOptions = Json.DecodeOptions & {
lines: boolean?, -- JSON Lines: decode every value into an array (default false: one value)
lines: boolean?, -- default false
}
export type EncodeOptions = Json.EncodeOptions & {
lines: boolean?, -- JSON Lines: the value must be an array, written one compact value per line
lines: boolean?,
}
-- ------------------------------------------------------------------------------------------------ sniff
+11 -17
View File
@@ -1,7 +1,6 @@
--!strict
--!native
-- data/msgpack/Codec: the MessagePack decoder and encoder behind data/msgpack (msgpack spec, 2017 revision with
-- str8 / bin / ext and the timestamp extension). Never throws: errors return nil, message, offset.
-- data/msgpack/Codec: MessagePack (2017 spec: str8 / bin / ext, timestamp ext -1) decoder and encoder; never throws.
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
@@ -9,7 +8,7 @@ local Codec = {}
local TWO32 = 4294967296
-- an extension value: { type = -128..127, data = buffer }
-- ext type: -128..127
local ExtMeta = { __tostring = function(e: any): string
return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)"
end }
@@ -20,13 +19,11 @@ function Codec.isExt(v: any): boolean
return type(v) == "table" and getmetatable(v) == ExtMeta
end
-- decimal text of hi * 2^32 + lo (hi, lo unsigned 32-bit), exact
local function u64text(hi: number, lo: number): string
if hi == 0 then
return string.format("%d", lo)
end
local digits = {}
-- long division by 10 on four 16-bit limbs
local l = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 }
while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do
local rem = 0
@@ -42,11 +39,11 @@ end
Codec.u64text = u64text
export type DecodeOptions = {
bigInts: ("number" | "string")?, -- 64-bit integers past 2^53: "string" keeps the exact decimal text
null: any?, -- the value for nil (default Types.null)
maxDepth: number?, -- nesting limit (default 512)
timestamps: boolean?, -- ext -1 as a Types.Date (default true)
ordered: boolean?, -- maps as Types.object with key order (default true)
bigInts: ("number" | "string")?,
null: any?, -- default Types.null
maxDepth: number?, -- default 512
timestamps: boolean?, -- default true
ordered: boolean?, -- default true
}
type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: boolean, ordered: boolean }
@@ -55,7 +52,6 @@ local function int64(st: St, signed: boolean): any
local r = st.r
local hi, lo = r:u32be(), r:u32be()
if signed and hi >= 0x80000000 then
-- negative: two's complement
local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo
if nlo == TWO32 then
nlo = 0
@@ -239,7 +235,6 @@ function value(st: St, depth: number): (any, string?)
return nil, string.format("reserved type byte 0x%02x", b)
end
-- decode(r, opts) -> value, nil | nil, message, offset (one value; r is left after it)
function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?)
local o: DecodeOptions = opts or {}
local st: St = {
@@ -259,11 +254,11 @@ end
-- ------------------------------------------------------------------------------------------------ encode
export type EncodeOptions = {
float32: boolean?, -- non-integer numbers as float32 (default false: float64)
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
emptyTable: ("array" | "map")?, -- a plain empty table (default "array")
float32: boolean?, -- default false
sortKeys: boolean?, -- default true
emptyTable: ("array" | "map")?, -- default "array"
maxDepth: number?, -- default 512 (also catches cycles)
stringsAsBin: boolean?, -- strings as bin (default false: str)
stringsAsBin: boolean?, -- default false
}
type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, maxDepth: number, bin: boolean, err: string? }
@@ -425,7 +420,6 @@ local function enc(st: ESt, v: any, depth: number): boolean
return true
end
-- encode(v, opts) -> buffer | nil, message
function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?)
local o: EncodeOptions = opts or {}
local st: ESt = {
+5 -8
View File
@@ -1,9 +1,7 @@
--!strict
-- data/msgpack: MessagePack (msgpack spec, str8 / bin / ext revision). New code. Supports: every type, the
-- timestamp extension (-1) as Types.Date, other extensions as Msgpack.ext(type, data), bin as buffers, maps as
-- Types.object (key order kept; keys of any type), 64-bit integers past 2^53 as exact decimal strings by option, a
-- stream of concatenated values (opts.all). Encode picks the smallest integer / length forms (float64 for
-- non-integers unless opts.float32). Not supported: nothing in the spec.
-- data/msgpack: MessagePack (str8 / bin / ext revision), new code. Supports: every type, timestamps (ext -1) as
-- Types.Date, other ext as Msgpack.ext, exact 64-bit integers by option, concatenated streams; encode picks the
-- smallest forms. Not supported: none.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -21,10 +19,10 @@ local Msgpack = {
}
export type DecodeOptions = Codec.DecodeOptions & {
all: boolean?, -- decode every concatenated value into an array (default false: exactly one value)
all: boolean?, -- default false
}
export type EncodeOptions = Codec.EncodeOptions & {
all: boolean?, -- the value is an array of values, written one after another
all: boolean?,
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -83,7 +81,6 @@ function Msgpack.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- ext(type, data) -> an extension value { type, data } that encodes as ext; isExt(v)
Msgpack.ext = Codec.ext
Msgpack.isExt = Codec.isExt
+4 -7
View File
@@ -1,10 +1,7 @@
--!strict
-- data/nbt: Minecraft NBT files (.nbt structures, level.dat / playerdata .dat, servers.dat, Bedrock .mcstructure and
-- level.dat), a thin format over codecs/text/Nbt (which see for the value mapping). Supports: Java big-endian and
-- Bedrock little-endian NBT (the level.dat 8-byte header too; network varint NBT with opts.varint), gzip / zlib /
-- uncompressed, every tag type, exact round trips (Nbt.info(value) remembers the root name, edition, compression
-- and header; encode writes it back the same way unless opts say otherwise). Text SNBT: data/snbt.
-- Not supported: nothing in the format.
-- data/nbt: Minecraft NBT files over codecs/text/Nbt. Supports: Java big-endian and Bedrock little-endian NBT
-- (level.dat header, varint by option), gzip / zlib / raw, every tag, exact round trips (Nbt.info).
-- Not supported: none.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -54,7 +51,7 @@ function NbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
NbtFormat.info = Nbt.info -- how a decoded value was stored: { name, endian, compression, header?, varint? }
NbtFormat.info = Nbt.info
NbtFormat.Nbt = Nbt
return NbtFormat
+1 -7
View File
@@ -1,10 +1,6 @@
--!strict
--!native
-- data/plist/Binary: the binary property list reader ("bplist00", CoreFoundation's format as documented in
-- CFBinaryPList.c and implemented by Python's plistlib). Objects: null / bool / fill, ints (1, 2, 4, 8 bytes; 16-byte
-- ints are read from their low 8 bytes), reals (4 / 8 bytes), dates, data, ASCII / UTF-16BE / UTF-8 strings, UIDs,
-- arrays, sets (as arrays), dicts (Types.object, key order kept). Shared references decode to the same table; cycles
-- are errors. Never throws: errors return nil, message.
-- data/plist/Binary: binary plist reader ("bplist00", CFBinaryPList.c / Python's plistlib); 16-byte ints: low 8 bytes.
local Types = require("@rosetta/Types")
local Binary = {}
@@ -44,7 +40,6 @@ end
export type Options = { bigInts: ("number" | "string")?, maxDepth: number? }
-- decode(buf, base, len, opts) -> value | nil, message
function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?)
if len < 40 then
return nil, "truncated: shorter than header + trailer"
@@ -130,7 +125,6 @@ function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (a
if h >= 0x80000000 and nib == 3 then
v = (h - TWO32) * TWO32 + l
elseif opts and opts.bigInts == "string" and h >= 0x200000 then
-- exact decimal text of h * 2^32 + l
local digits = {}
local limbs = { h // 65536, h % 65536, l // 65536, l % 65536 }
while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do
+6 -8
View File
@@ -1,9 +1,7 @@
--!strict
-- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/text/Xml; the write is
-- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict ->
-- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data ->
-- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past
-- 2^63. Note: Luau has one number type, so a real with an integral value is written back as <integer>.
-- data/plist: Apple property lists, new code. Supports: XML read / write (byte-identical to Python's plistlib),
-- binary "bplist00" read, UIDs as Plist.uid. Not supported: binary write, OpenStep text, integers past 2^63; integral
-- reals write back as <integer>.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,11 +23,11 @@ local Plist = {
}
export type DecodeOptions = {
bigInts: ("number" | "string")?, -- integers past 2^53: "string" keeps exact decimal text
bigInts: ("number" | "string")?,
maxDepth: number?, -- default 512
}
export type EncodeOptions = {
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
sortKeys: boolean?, -- default true
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -300,7 +298,7 @@ function Plist.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
Plist.uid = Binary.uid -- uid(n) -> a UID value (binary plists, NSKeyedArchiver)
Plist.uid = Binary.uid
Plist.isUid = Binary.isUid
return Plist
+3 -5
View File
@@ -1,7 +1,5 @@
--!strict
-- data/snbt: stringified NBT text (Minecraft commands, datapacks, .snbt structure files), a thin format over
-- codecs/text/Nbt (which see for the value mapping and grammar). Supports: parse to the same typed values data/nbt
-- gives (convert between the two freely), print compact (Minecraft's form) or indented (opts.indent).
-- data/snbt: stringified NBT over codecs/text/Nbt. Supports: parse to data/nbt's values, compact or indented print.
-- Not supported: the 1.21.5 bool(...) / uuid(...) operations.
-- ------------------------------------------------------------------------------------------------ requires
@@ -22,8 +20,8 @@ local SnbtFormat = {
export type DecodeOptions = { maxDepth: number? }
export type EncodeOptions = {
indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact)
quote: string?, -- '"' (default) or "'"
indent: (number | string)?, -- default: compact
quote: string?, -- default '"'
}
-- ------------------------------------------------------------------------------------------------ sniff
+2 -11
View File
@@ -1,8 +1,5 @@
--!strict
-- data/toml/Decode: the TOML 1.0.0 parser behind data/toml. Tables (and inline tables) are Types.object values with
-- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control
-- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and
-- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based).
-- data/toml/Decode: TOML 1.0.0 parser with the 1.0 validity rules; never throws (nil, message, 0-based offset).
local Text = require("@rosetta/codecs/text/Text")
local Types = require("@rosetta/Types")
@@ -11,7 +8,7 @@ local Decode = {}
local byte, sub, find, match, gsub, char = string.byte, string.sub, string.find, string.match, string.gsub, string.char
export type Options = {
bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their digits (default "number")
bigInts: ("number" | "string")?, -- default "number"
}
local utf8char = Text.utf8char
@@ -32,7 +29,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
return nil
end
-- input checks: BOM, UTF-8, control characters, bare CR
if sub(s, 1, 3) == "\239\187\191" then
s = sub(s, 4)
end
@@ -80,7 +76,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
local function ws(i: number): number
return match(s, "^[ \t]*()", i) :: any
end
-- whitespace, newlines and comments (inside arrays)
local function wsnl(i: number): number
while true do
i = match(s, "^[ \t\n]*()", i) :: any
@@ -114,7 +109,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
return fail("bad escape", p)
end
-- strings: value, next | nil
local function basic(i: number): (string?, number)
local parts = {}
local j = i + 1
@@ -204,7 +198,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
return sub(s, j, e - 1) .. string.rep("'", extra), q
end
-- a (dotted) key: { parts }, next | nil
local function key(i: number): ({ string }?, number)
local keys: { string } = {}
while true do
@@ -242,7 +235,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
end
end
-- numbers and datetimes
local function number(i: number): (any, number)
local tok = match(s, "^[%+%-]?[%w_%.]+", i)
if not tok then
@@ -556,7 +548,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
end
ni += 1
end
-- walk to the parent
local t = root
for j = 1, #keys - 1 do
local k = keys[j]
+3 -10
View File
@@ -1,9 +1,5 @@
--!strict
-- data/toml/Encode: the TOML 1.0.0 writer behind data/toml. A table's plain values come first, then its sub-tables
-- as [a.b] sections and arrays of tables as [[a.b]]; keys in Types.object order (plain tables: sorted); strings as
-- basic strings with escapes; numbers as integers when integral (|x| < 2^63) else round-trip float text; Types.Date
-- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil,
-- message.
-- data/toml/Encode: TOML 1.0.0 writer: plain values, then [a.b] sections and [[a.b]] arrays of tables; never throws.
local Types = require("@rosetta/Types")
local Json = require("@rosetta/codecs/text/Json")
@@ -12,8 +8,8 @@ local Encode = {}
local format, gsub, find = string.format, string.gsub, string.find
export type Options = {
inline: boolean?, -- write every sub-table as an inline table (default false: [sections])
indent: (number | string)?, -- indent keys of nested sections (default none)
inline: boolean?, -- default false
indent: (number | string)?, -- default none
}
local ESC: { [string]: string } = { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\t"] = "\\t", ["\n"] = "\\n", ["\f"] = "\\f", ["\r"] = "\\r", ["\127"] = "\\u007F" }
@@ -36,7 +32,6 @@ local function keyText(k: string): string
return quote(k)
end
-- isMap(t): a table written as a TOML table (Types.object, or keys other than 1..n); empty plain tables are arrays
local function isMap(t: { [any]: any }): boolean
if Types.isObject(t) then
return true
@@ -56,7 +51,6 @@ local function isDate(v: any): boolean
return Types.Date.is(v)
end
-- an array of tables: non-empty, every element a map
local function isAot(v: any): boolean
if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then
return false
@@ -196,7 +190,6 @@ local function section(st: State, t: any, path: string, out: { string }, inlineA
return true
end
-- encode(t, opts) -> text | nil, message
function Encode.encode(t: any, opts: Options?): (string?, string?)
if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then
return nil, "the top level must be a table with string keys"
+4 -9
View File
@@ -1,11 +1,7 @@
--!strict
-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0). New code. Supports: decode of the whole 1.0 grammar (tables,
-- inline tables, arrays of tables, dotted keys, every string kind, integers in every base with the 64-bit range
-- check, floats incl. inf / nan, booleans, offset / local datetimes, local dates and times) with the validity rules
-- (redefinitions, UTF-8, control characters, number grammar), tested against toml-test; encode from plain tables /
-- Types.object (key order kept) / Types.Date. Tables decode to Types.object values (key order kept), datetimes to
-- Types.Date. Not supported: TOML 1.1 additions; the integer / float distinction is lost (Luau numbers: integral
-- values are written as integers).
-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0), new code, tested against toml-test. Supports: the whole 1.0
-- grammar and validity rules; tables as Types.object, datetimes as Types.Date. Not supported: TOML 1.1; the integer /
-- float distinction (integral values write as integers).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -27,8 +23,7 @@ export type DecodeOptions = Decode.Options
export type EncodeOptions = Encode.Options
-- ------------------------------------------------------------------------------------------------ sniff
-- text that starts (after comments / blank lines) with a [table] header or a key = value line; INI looks the same,
-- so this stays low and the extension decides
-- INI looks the same: a [table] or key = value start scores low and the extension decides
function Toml.sniff(r: Bytes.Reader): number
local head = r:peek(512)
if string.find(head, "%z") then
+2 -3
View File
@@ -1,7 +1,6 @@
--!strict
-- data/xml: XML 1.0 files, a thin wrapper over codecs/text/Xml (which see for the node shape and options). Supports:
-- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not
-- supported: external entities / DTDs, validation.
-- data/xml: XML 1.0 over codecs/text/Xml. Supports: decode to a "#document" XmlNode tree, encode a document or an
-- element. Not supported: external entities / DTDs, validation.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
+6 -17
View File
@@ -1,9 +1,5 @@
--!strict
-- data/yaml/Emit: the YAML writer behind data/yaml. Block style; empty collections as [] / {}; strings plain when
-- they read back as the same string (core schema, and not a YAML 1.1 boolean like "yes"), literal block scalars
-- for multi-line text, double-quoted otherwise; numbers with the shortest round-trip text, .inf / .nan; buffers as
-- !!binary; dates as their RFC 3339 text; tables referenced twice get an anchor and aliases. Never throws: bad
-- values (cycles, functions, collection keys) return nil, message.
-- data/yaml/Emit: YAML block-style writer; plain scalars only when they read back the same (core schema, no 1.1 bools).
local Types = require("@rosetta/Types")
local Base64 = require("@rosetta/core/Base64")
local Parse = require("@rosetta/data/yaml/Parse")
@@ -11,11 +7,11 @@ local Parse = require("@rosetta/data/yaml/Parse")
local Emit = {}
export type Options = {
indent: number?, -- spaces per level (default 2)
all: boolean?, -- the value is an array of documents, written with "---" separators
explicitStart: boolean?, -- start the (first) document with "---" (default false)
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keys keep their order)
null: any?, -- the value written as null besides Types.null
indent: number?, -- default 2
all: boolean?,
explicitStart: boolean?, -- default false
sortKeys: boolean?, -- default true
null: any?,
}
local format, byte, find, gsub = string.format, string.byte, string.find, string.gsub
@@ -96,7 +92,6 @@ local function plainOk(s: string): boolean
return true
end
-- a string as a scalar on a line at indentation ind (for block scalars)
local function str(s: string, ind: string, key: boolean): string
if plainOk(s) then
return s
@@ -126,7 +121,6 @@ local keyLess = Types.keyLess
type St = { out: { string }, step: number, sort: boolean, null: any, refs: { [any]: number }, anchors: { [any]: string }, nextId: number, err: string? }
-- count references to tables (anchors for those seen twice); false on a cycle
local function count(st: St, v: any, onStack: { [any]: boolean }): boolean
if type(v) ~= "table" or v == Types.null or v == st.null or Types.Date.is(v) then
return true
@@ -150,7 +144,6 @@ local function count(st: St, v: any, onStack: { [any]: boolean }): boolean
return true
end
-- scalar text for a non-collection value, or nil
local function scalar(st: St, v: any, ind: string, key: boolean): string?
local tv = type(v)
if v == nil or v == Types.null or (st.null ~= nil and v == st.null) then
@@ -171,7 +164,6 @@ end
local write: (st: St, v: any, depth: number) -> string?
-- the text of v as a node whose first line follows "key:" / "- " (it starts with a space or a newline)
function write(st: St, v: any, depth: number): string?
local ind = string.rep(" ", st.step * (depth + 1))
local s = scalar(st, v, ind, false)
@@ -244,19 +236,16 @@ local function document(st: St, v: any): string?
if not t then
return nil
end
-- the top level: drop the separator write() put before the first line
if string.sub(t, 1, 1) == "\n" then
return string.sub(t, 2)
end
local body = string.sub(t, 2)
if string.sub(body, 1, 1) == "&" then
-- "&id001\n- a": an anchored top-level collection
return body
end
return body
end
-- encode(v, opts) -> text | nil, message
function Emit.encode(v: any, opts: Options?): (string?, string?)
local o: Options = opts or {}
local st: St = {
+13 -44
View File
@@ -1,11 +1,5 @@
--!strict
-- data/yaml/Parse: the YAML 1.2 parser behind data/yaml. Recursive descent over the text (line breaks normalized):
-- block mappings / sequences (compact forms included), flow collections, plain / single / double-quoted scalars with
-- line folding, literal / folded block scalars (indentation and chomping indicators), anchors and aliases (shared
-- references, with an expansion-size limit), tags (core types + !!binary, !!timestamp; others UNSUPPORTED unless
-- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core
-- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a
-- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it.
-- data/yaml/Parse: YAML 1.2 recursive-descent parser; raises { yamlErr } tables caught by run(), never throws past it.
local Text = require("@rosetta/codecs/text/Text")
local Types = require("@rosetta/Types")
local Base64 = require("@rosetta/core/Base64")
@@ -15,11 +9,11 @@ local Parse = {}
local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char
export type Options = {
all: boolean?, -- every document as an array (default false: the first document; none -> Types.null)
tags: ("error" | "ignore")?, -- unknown tags: an UNSUPPORTED error (default) or resolved as if untagged
maxAliasNodes: number?, -- the total size of aliased nodes (default 1e6): the billion laughs guard
maxDepth: number?, -- nesting limit (default 500)
null: any?, -- the value for null (default Types.null)
all: boolean?, -- default false
tags: ("error" | "ignore")?, -- default "error"
maxAliasNodes: number?, -- default 1e6 (billion laughs guard)
maxDepth: number?, -- default 500
null: any?, -- default Types.null
}
type St = {
@@ -54,7 +48,7 @@ local function col(s: string, p: number): number
return p - q
end
local function isWsEnd(c: number?): boolean -- space, tab, newline or the end
local function isWsEnd(c: number?): boolean
return c == nil or c == 32 or c == 9 or c == 10
end
@@ -66,7 +60,6 @@ local function docMarker(s: string, p: number): boolean
return (m == "---" or m == "...") and isWsEnd(byte(s, p + 3))
end
-- skip spaces, tabs, comments and line breaks: the next content position (n + 1 at the end)
local function skip(s: string, p: number): number
local n = #s
while p <= n do
@@ -86,7 +79,6 @@ local function skip(s: string, p: number): number
return p
end
-- the number of leading spaces on p's line, and whether a tab comes before p on it
local function lineIndent(s: string, p: number): (number, boolean)
local q = p
while q > 1 and byte(s, q - 1) ~= 10 do
@@ -105,7 +97,6 @@ local function noTabs(s: string, p: number, ind: number?)
end
end
-- skip spaces / tabs on the line
local function skipLine(s: string, p: number): number
return match(s, "^[ \t]*()", p) :: any
end
@@ -120,7 +111,6 @@ end
local utf8char = Text.utf8char
-- ------------------------------------------------------------------------------------------------ resolution
-- the core schema: a plain scalar's value
function Parse.resolve(t: string, nullv: any): any
if t == "" or t == "~" or t == "null" or t == "Null" or t == "NULL" then
return nullv
@@ -168,7 +158,6 @@ local function base64(t: string): buffer?
return (Base64.decode(t))
end
-- a scalar's value given its tag (nil = untagged, "!" = non-specific)
local function scalarValue(st: St, raw: string, plain: boolean, tag: string?, p: number): any
if tag == nil then
return if plain then Parse.resolve(raw, st.null) else raw
@@ -237,7 +226,6 @@ local function collectionTag(st: St, tag: string?, kind: string, p: number)
end
end
-- expansion size of a value (nodes), memoized
local function size(st: St, v: any): number
if type(v) ~= "table" or v == st.null then
return 1
@@ -257,7 +245,6 @@ end
-- ------------------------------------------------------------------------------------------------ properties
type Props = { anchor: string?, tag: string?, at: number }
-- anchors / tags at p -> props?, the position after them (and the spaces after them)
local function properties(st: St, p: number): (Props?, number)
local s = st.s
local props: Props? = nil
@@ -348,8 +335,7 @@ local function alias(st: St, p: number): (any, number)
end
-- ------------------------------------------------------------------------------------------------ scalars
-- fold the line break(s) at p (p at a '\n'): the text they become and the position of the next line's content.
-- Lines holding only spaces / tabs count as empty.
-- line folding: lines holding only spaces / tabs count as empty
local function fold(s: string, p: number): (string, number)
local empties = 0
local q = p + 1
@@ -385,7 +371,6 @@ local ESC: { [number]: string } = {
[80] = "\226\128\169",
}
-- a quoted scalar at p ('"' or "'") -> text, the position after the closing quote
local function quoted(st: St, p: number, ind: number): (string, number)
local s = st.s
local dq = byte(s, p) == 34
@@ -456,15 +441,13 @@ local function quoted(st: St, p: number, ind: number): (string, number)
end
end
-- a plain scalar at p -> text, the position after it. ind: continuation lines must be indented deeper than ind
-- (block context); flow: the flow-context rules (stops at , [ ] { }).
-- plain scalar: continuation lines indented deeper than ind (block context); flow context stops at , [ ] { }
local function plain(st: St, p: number, ind: number, flow: boolean): (string, number)
local s = st.s
local parts: { string } = {}
local i = p
local lastEnd = p
while true do
-- one line's worth
local j = i
local stopAt = nil
while true do
@@ -492,7 +475,6 @@ local function plain(st: St, p: number, ind: number, flow: boolean): (string, nu
if stopAt or byte(s, j) == nil then
return table.concat(parts), lastEnd
end
-- a continuation line?
local f, q = fold(s, j)
local r = skipLine(s, q)
local c = byte(s, r)
@@ -507,7 +489,6 @@ local function plain(st: St, p: number, ind: number, flow: boolean): (string, nu
end
end
-- a block scalar at p ('|' or '>'); ind = the parent's indentation -> text, the position after it
local function blockScalar(st: St, p: number, ind: number): (string, number)
local s = st.s
local folded = byte(s, p) == 62
@@ -529,7 +510,7 @@ local function blockScalar(st: St, p: number, ind: number): (string, number)
end
local nl = find(s, "\n", q, true)
local lines: { string } = {}
local trailing = 0 -- empty lines after the last content line
local trailing = 0
if not nl then
return "", #s + 1
end
@@ -568,7 +549,6 @@ local function blockScalar(st: St, p: number, ind: number): (string, number)
indent = ind + 1
end
end
-- the lines
local r = ls
local pendingEmpty = 0
local endPos = ls
@@ -625,7 +605,7 @@ local function blockScalar(st: St, p: number, ind: number): (string, number)
empties = 0
end
end
trailing += empties -- empty lines after the last content line (or all of them)
trailing += empties
body = table.concat(out)
end
if not folded then
@@ -666,7 +646,6 @@ local function enter(st: St, p: number)
end
end
-- a flow node at p (after skip) -> value, next, wasEmpty
local function flowNode(st: St, p: number, ind: number): (any, number, boolean)
local s = st.s
local props, q = properties(st, p)
@@ -688,7 +667,6 @@ local function flowNode(st: St, p: number, ind: number): (any, number, boolean)
local t, r = quoted(st, q, ind)
return finish(st, props, scalarValue(st, t, false, props and props.tag, q)), r, false
elseif c == nil or c == 44 or c == 93 or c == 125 or (c == 58 and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125)) then
-- an empty node
return finish(st, props, scalarValue(st, "", true, props and props.tag, q)), (if props then q else p), true
elseif c == 35 or c == 38 or c == 33 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 then
corrupt("unexpected character in a flow collection", q)
@@ -819,7 +797,7 @@ end
-- ------------------------------------------------------------------------------------------------ block
local blockNode: (st: St, ind: number, p: number, inline: boolean, mapParent: boolean) -> (any, number)
-- an implicit key at p (on one line, followed by ':' and a space / the end of the line) -> key, position after ':'
-- implicit key: on one line, followed by ':' and a space or the end of the line
local function implicitKey(st: St, p: number): (any, number?)
local s = st.s
local c = byte(s, p)
@@ -847,7 +825,6 @@ local function implicitKey(st: St, p: number): (any, number?)
end
return nil, nil
elseif c == 91 or c == 123 then
-- a flow collection used as a key?
local e = find(s, "\n", p, true) or #s + 1
local line = sub(s, p, e - 1)
if match(line, "[%]}]%s*:%s") or match(line, "[%]}]%s*:$") then
@@ -892,7 +869,7 @@ local function readKey(st: St, p: number, props: Props?): (any, number)
end
k, q = alias(st, p)
q = skipLine(s, q)
q += 1 -- the ':'
q += 1
elseif c == 34 or c == 39 then
local t, r = quoted(st, p, -1)
if find(sub(s, p, r - 1), "\n", 1, true) then
@@ -912,7 +889,6 @@ local function readKey(st: St, p: number, props: Props?): (any, number)
return checkKey(st, k, p), q
end
-- a node on the lines after p's line (content deeper than ind; or a sequence at ind when seqAt) -> value, next | null
local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapParent: boolean): (any, number)
local s = st.s
local r = skip(s, p)
@@ -926,7 +902,6 @@ local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapP
return st.null, p
end
-- the value after a ':' (at p, just past it) of a mapping at column mc
local function mapValue(st: St, mc: number, p: number, explicit: boolean): (any, number)
local s = st.s
local r = skipLine(s, p)
@@ -1044,7 +1019,6 @@ local function blockSeq(st: St, sc: number, p: number): (any, number)
return t, q
end
-- the node at q after its properties (props may be nil); start = where the properties began
local function afterProps(st: St, ind: number, start: number, q: number, props: Props?, inline: boolean, mapParent: boolean): (any, number)
local s = st.s
local tag = props and props.tag
@@ -1111,9 +1085,6 @@ local function afterProps(st: St, ind: number, start: number, q: number, props:
return finish(st, props, scalarValue(st, text, true, tag, q)), e
end
-- a block node at p (content; col(p) > ind, or == ind for a sequence that is a mapping's value). inline: on the
-- same line as its mapping key (no new block collection may start). mapParent: a sequence at the parent's
-- indentation may follow properties that end their line.
function blockNode(st: St, ind: number, p: number, inline: boolean, mapParent: boolean): (any, number)
local s = st.s
local props, q = properties(st, p)
@@ -1253,7 +1224,6 @@ local function stream(st: St): { any }
p = q
else
if explicit and not find(sub(s, p, q), "\n", 1, true) then
-- content on the "---" line
local ok, _, q2 = pcall(properties, st, q)
local c = byte(s, q2)
if ok and c ~= 124 and c ~= 62 and not endOfLine(s, q2) and implicitKey(st, q2) ~= nil then
@@ -1282,7 +1252,6 @@ local function stream(st: St): { any }
return docs
end
-- run(text, opts) -> docs | nil, code, message, offset
function Parse.run(text: string, opts: Options?): (any, any, any, any)
local o: Options = opts or {}
local s = text
+3 -9
View File
@@ -1,11 +1,7 @@
--!strict
-- data/yaml: YAML 1.2 (core schema), new code. Supports: block and flow styles, compact nested collections, plain /
-- quoted / literal / folded scalars (indentation and chomping indicators), comments, anchors and aliases (decoded as
-- shared references; an expansion-size limit guards against alias bombs), tags !!str !!int !!float !!bool !!null
-- !!map !!seq !!binary (-> buffer) !!timestamp (-> Types.Date) and verbatim / %TAG forms, multi-document streams.
-- Maps decode to Types.object (key order kept), null to Types.null. Writes block style (anchors for shared tables).
-- Not supported (Err.UNSUPPORTED): complex keys "? ", collections as keys, other tags unless opts.tags = "ignore";
-- merge keys "<<" stay ordinary keys; YAML 1.1 types (yes / no, sexagesimal, ...) are strings.
-- data/yaml: YAML 1.2 (core schema), new code. Supports: block / flow styles, every scalar style, anchors and aliases
-- (shared, alias-bomb limit), core tags + !!binary / !!timestamp, %TAG, multi-document streams; writes block style.
-- Not supported (Err.UNSUPPORTED): complex keys, collections as keys; merge keys stay keys; YAML 1.1 types are strings.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -47,7 +43,6 @@ function Yaml.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> the first document (Types.null when there is none) | every document (opts.all) | nil, Err
function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local docs, code, msg, at = Parse.run(text, opts)
@@ -65,7 +60,6 @@ function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(value, opts?) -> buffer | nil, Err (opts.all: value is an array of documents)
function Yaml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local s, err = Emit.encode(value, opts)
if not s then
+6 -14
View File
@@ -1,13 +1,7 @@
--!strict
-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0) bitmap fonts, read and written, as the
-- standard Font with a bitmap strike (codecs/font/Bitmap): FONT / SIZE / FONTBOUNDINGBOX, the properties (all kept in
-- meta.properties; FONT_ASCENT / FONT_DESCENT / PIXEL_SIZE / DEFAULT_CHAR / FAMILY_NAME / WEIGHT_NAME / SLANT used),
-- glyphs with STARTCHAR names, ENCODING (-1 for unencoded, "-1 n" non-standard codes), DWIDTH / BBX (falling back to
-- the font's) and hex BITMAP rows. Code points: ENCODING is the Unicode code point for CHARSET_REGISTRY ISO10646, for
-- ISO8859-1 and for fonts without a registry; fonts in other charsets keep their glyphs unmapped (glyph names and
-- meta.encodings keep the codes). Writing takes any Font (Bitmap.strike: a bitmap font as it is, an outline font
-- rasterized at opts.px) and writes Unicode (ISO10646-1) BDF 2.1. Written from Adobe's BDF 2.1 specification.
-- Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR are read and ignored).
-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0), read and written, from Adobe's BDF 2.1
-- spec. ENCODING is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets stay unmapped. Writes
-- Unicode (ISO10646-1) BDF 2.1 from any Font. Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR ignored).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -27,9 +21,9 @@ local Bdf = {
export type DecodeOptions = { maxGlyphs: number? } -- default 1114112
export type EncodeOptions = {
px: number?, -- pixel size for outline fonts (default 16)
chars: (string | { number })?, -- code points for outline fonts (default printable ASCII)
name: string?, -- the FONT (XLFD) name (default built from the font's family / style)
px: number?, -- default 16
chars: (string | { number })?, -- default printable ASCII
name: string?, -- XLFD; default built from the family / style
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -223,7 +217,6 @@ function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local bold = string.find(string.lower(tostring(info.style or "")), "bold") ~= nil
local italic = string.find(string.lower(tostring(info.style or "")), "italic") ~= nil
local px = strike.size
-- the font bounding box
local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
for _, g in strike.glyphs do
if g.width > 0 and g.height > 0 then
@@ -244,7 +237,6 @@ function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
string.format("SIZE %d 75 75", px),
string.format("FONTBOUNDINGBOX %d %d %d %d", x1 - x0, y1 - y0, x0, y0),
}
-- the default glyph: the strike's default, else glyph 0
local defaultIndex = (strike.default or 0) + 1
local props: { { any } } = {
{ "FAMILY_NAME", quote(family) },
+3 -9
View File
@@ -1,10 +1,5 @@
--!strict
-- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one
-- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation
-- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the
-- descriptor has no nesting that matters, no text content).
--
-- Never throws on bad input: parse functions return nil, message.
-- font/bmfont/Parse: BMFont text / XML / binary v3 descriptors (angelcode.com/products/bmfont/doc/file_format.html).
local Bytes = require("@rosetta/core/Bytes")
local Parse = {}
@@ -24,12 +19,12 @@ export type Char = {
export type Desc = {
info: { [string]: any }, -- face, size, bold, italic, charset, unicode, stretchH, smooth, aa, padding {4}, spacing {2}, outline
common: { [string]: any }, -- lineHeight, base, scaleW, scaleH, pages, packed, alphaChnl, redChnl, greenChnl, blueChnl
pages: { string }, -- file names, by page id (1-based: page id 0 is pages[1])
pages: { string }, -- by page id: page id 0 is pages[1]
chars: { Char },
kernings: { { number } }, -- { first, second, amount }
}
local LIMIT = 1000000 -- chars / kernings
local LIMIT = 1000000
local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" }
local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" }
@@ -54,7 +49,6 @@ local function new(): Desc
return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} }
end
-- one tag's attributes (already split into key -> string) into the description
local function apply(d: Desc, tag: string, a: { [string]: string }): string?
if tag == "info" then
d.info.face = a.face or ""
+15 -30
View File
@@ -1,11 +1,7 @@
--!strict
-- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and
-- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize
-- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are
-- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the
-- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf /
-- woff) into a packed bitmap font with its pages. Written from the BMFont documentation.
-- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha).
-- font/bmfont: AngelCode BMFont descriptors (.fnt: text, XML, binary version 3), read and written, from the BMFont
-- documentation. Pages are image files (meta.pageFiles), loaded lazily; Bmfont.bake renders an outline Font to pages.
-- Not supported: packed multi-channel glyphs (read as alpha).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,25 +20,24 @@ local Bmfont = {
}
export type DecodeOptions = {
pages: { Types.Image }?, -- the page images, if the caller has them already (page id 0 first)
loadPage: ((file: string, page: number) -> any)?, -- loader for lazy pages: file -> Image (the api passes one)
pages: { Types.Image }?, -- page id 0 first
loadPage: ((file: string, page: number) -> any)?,
}
export type EncodeOptions = {
variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text"
px: number?, -- fonts without a BMFont description are baked first (see bake)
px: number?,
chars: (string | { number })?,
file: string?, -- baking: the page file name prefix (default: opts.name without its extension, else "font")
name: string?, -- the destination's file name (set by the api)
files: { [string]: any }?, -- the page images are written here, encoded by opts.encodeImage (the api passes
-- both): files[page file name] = PNG bytes, for the baked pages or a BMFont's loaded pages
file: string?, -- default: opts.name without its extension, else "font"
name: string?,
files: { [string]: any }?,
encodeImage: ((img: any, format: string) -> (buffer?, any))?,
}
export type BakeOptions = {
px: number?, -- pixels per em (default 32)
chars: (string | { number })?, -- code points to include (default printable ASCII 32..126)
pageSize: number?, -- page width = height (default: the smallest power of two that fits, up to 4096)
padding: number?, -- empty pixels around each glyph (default 1)
file: string?, -- page file name prefix (default "font"): pages are <file>_<n>.png
px: number?, -- default 32
chars: (string | { number })?, -- default printable ASCII 32..126
pageSize: number?, -- default: the smallest power of two that fits, up to 4096
padding: number?, -- default 1
file: string?, -- default "font"; pages are <file>_<n>.png
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -61,7 +56,6 @@ function Bmfont.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the Font value
local Face = {}
Face.__index = Face
@@ -80,10 +74,9 @@ function Face.kern(self: any, a: number, b: number): number
return self._kern[ca.id * 2097152 + cb.id] or 0
end
function Face.outline(_self: any, _g: number): { any }?
return nil -- bitmap font
return nil
end
-- loadPages(loader?) -> true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil
function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?)
local load = loader or self.meta.pageLoader
if type(load) ~= "function" then
@@ -103,8 +96,6 @@ end
local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8
-- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size;
-- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available.
function Face.rasterize(self: any, g: number, px: number?): Types.Image?
local c = self._chars[g]
if not c then
@@ -141,7 +132,6 @@ function Face.rasterize(self: any, g: number, px: number?): Types.Image?
return img
end
-- the Font value of a description
local function face(d: Parse.Desc, variant: string): any
local f: any = setmetatable({
kind = "font",
@@ -244,7 +234,6 @@ function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local d = type(font.meta) == "table" and font.meta.bmfont or nil
local pages = font.pages
if d == nil then
-- page names: opts.file, else the destination's base name (the api passes opts.name), else "font"
local file = opts and opts.file
if file == nil and opts and type(opts.name) == "string" then
file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$")
@@ -262,7 +251,6 @@ function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if not validDesc(d) then
return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont")
end
-- the page images into opts.files, under the names the descriptor gives them
local files = opts and opts.files
local encodeImage = opts and opts.encodeImage
if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then
@@ -310,9 +298,6 @@ local function codepoints(chars: any): { number }
return out
end
-- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are
-- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are
-- kept (rounded to pixels).
function Bmfont.bake(font: any, opts: BakeOptions?): (any, Err.Err?)
if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then
return nil, Err.new(Err.ARG, "bake: expected an outline Font")
+5 -8
View File
@@ -1,10 +1,7 @@
--!strict
-- font/eot: Embedded OpenType (.eot; versions 0x00010000, 0x00020001 and 0x00020002): the EOT header (PANOSE, charset,
-- weight, fsType, Unicode / code page ranges, family / style / version / full names, the root string, EUDC data) and
-- the font data inside, XOR-0x50 obfuscated or not, read as the standard Font through codecs/font/TrueType (meta.eot
-- holds the header fields, meta.fontData the TrueType bytes). Writes EOT 2.1 around TrueType bytes (a buffer / string,
-- or a Font read from an EOT), filling the header from the font's OS/2, head and name tables. Written from the W3C
-- EOT submission (2008). Not supported: MicroType Express compressed fonts (flag 0x4: Err.UNSUPPORTED), signatures.
-- font/eot: Embedded OpenType (versions 0x00010000, 0x00020001, 0x00020002; W3C EOT submission, 2008): the header
-- and the font data (XOR-0x50 obfuscated or not) through codecs/font/TrueType; writes EOT 2.1 around TrueType bytes.
-- Not supported: MicroType Express compression (flag 0x4: Err.UNSUPPORTED), signatures.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,8 +21,8 @@ local Eot = {
export type DecodeOptions = {}
export type EncodeOptions = {
xor: boolean?, -- obfuscate the font data with XOR 0x50 (default false)
rootString: string?, -- the URLs allowed to use the font (default "")
xor: boolean?, -- XOR 0x50; default false
rootString: string?, -- default ""
}
-- ------------------------------------------------------------------------------------------------ constants
+4 -11
View File
@@ -1,10 +1,6 @@
--!strict
-- font/fon: Windows raster fonts: bare .fnt resources (versions 2.0 and 3.0: the header, the character table and the
-- column-major glyph bitmaps) and .fon files holding them as RT_FONT resources of a 16-bit NE executable (or a PE
-- one), as the standard Font with a bitmap strike (codecs/font/Bitmap). A .fon usually holds several sizes: the first
-- (or the one closest to opts.size pixels) is the Font, every strike's Font is in meta.strikes. Code points: ANSI
-- charset fonts map through Windows-1252, other charsets keep their byte codes below 0x80 only (meta.charset).
-- Written from Microsoft's "Windows 3.0 font file format" (KB65123) and the NE / PE resource table layouts.
-- font/fon: Windows raster fonts: .fnt resources (versions 2.0 / 3.0) and .fon NE / PE executables holding them as
-- RT_FONT, from Microsoft's KB65123 and the NE / PE resource layouts; ANSI charset maps through Windows-1252.
-- Not supported: vector FNT (Err.UNSUPPORTED), writing.
-- ------------------------------------------------------------------------------------------------ requires
@@ -24,7 +20,7 @@ local Fon = {
caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } },
}
export type DecodeOptions = { size: number? } -- pick the strike closest to this pixel height (default: the first)
export type DecodeOptions = { size: number? } -- default: the first strike
-- ------------------------------------------------------------------------------------------------ sniff
local function isFnt(h: string): boolean
@@ -50,7 +46,6 @@ function Fon.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- one FNT resource -> Font
local function fnt(r: Bytes.Reader): (any, Err.Err?)
local version = r:u16le()
local total = r:u32le()
@@ -145,7 +140,6 @@ local function fnt(r: Bytes.Reader): (any, Err.Err?)
}), nil
end
-- the RT_FONT resources of an NE executable: { { offset, length } }
local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?)
local rt = r:sub(ne + 0x24, 2):u16le()
local t = r:sub(ne + rt)
@@ -175,7 +169,7 @@ local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?)
return out, nil
end
-- the RT_FONT (8) resources of a PE executable: { { offset, length } }
-- RT_FONT: resource type 8
local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?)
local h = r:sub(pe + 4, 20)
h:skip(2)
@@ -190,7 +184,6 @@ local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?)
if opt.err or rsrcRva == 0 then
return {}, nil
end
-- the section holding the resources
local secs = r:sub(pe + 24 + optSize, nsec * 40)
local base, rva0 = -1, 0
for _ = 1, nsec do
+5 -12
View File
@@ -1,13 +1,7 @@
--!strict
-- font/hershey: Hershey vector fonts in the JHF text layout (James Hurt's distribution of the Hershey glyphs: per glyph
-- a 5-column id, a 3-column vertex count, the left / right extents and the vertices as character pairs offset by "R",
-- " R" lifting the pen; records continue over 72-column lines) as the standard Font: outlines are open stroke paths
-- (moveTo / lineTo, no close; meta.strokes = true), rasterize strokes them through codecs/image/Raster
-- (opts.strokeWidth, default 2 units). Units are Hershey units (unitsPerEm 32, y up, baseline at the Hershey y = 9 of
-- the Roman fonts: ascent 21, descent 7 for capitals / descenders). Code points: opts.map = "ascii" (default: glyph i
-- of the file is code point 32 + i, as the romans / futural / ... .jhf files are laid out) or "id" (the Hershey glyph
-- number is the code point). Written from the JHF layout notes of the Hershey font distribution. Not supported:
-- writing, the Hershey "occidental" index files (.hmp), filled rendering.
-- font/hershey: Hershey vector fonts, JHF layout (5-column id, 3-column vertex count, extents, vertices as character
-- pairs offset by "R", " R" lifts the pen; records continue over 72-column lines). Units: unitsPerEm 32, y up.
-- Not supported: writing, .hmp index files, filled rendering.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -26,8 +20,8 @@ local Hershey = {
}
export type DecodeOptions = {
map: ("ascii" | "id")?, -- how glyphs map to code points (default "ascii")
strokeWidth: number?, -- stroke width in font units for rasterize (default 2)
map: ("ascii" | "id")?, -- default "ascii"
strokeWidth: number?, -- font units; default 2
maxGlyphs: number?, -- default 65536
}
@@ -93,7 +87,6 @@ function Face.outline(self: any, g: number): { any }?
return out
end
-- rasterize(g, px) -> alpha8 Image of the stroked glyph (img.meta.left / top / advance in pixels)
function Face.rasterize(self: any, g: number, px: number): Types.Image?
local gl = self._glyphs[g + 1]
if not gl or type(px) ~= "number" or not (px > 0) or px > 4096 then
+2 -14
View File
@@ -1,11 +1,6 @@
--!strict
-- font/pcf: X11 Portable Compiled Format bitmap fonts (.pcf; .pcf.gz loads through the api's gzip unwrap) as the
-- standard Font with a bitmap strike (codecs/font/Bitmap): the table of contents, PROPERTIES (meta.properties),
-- ACCELERATORS / BDF_ACCELERATORS (font ascent / descent), METRICS (compressed and not), BITMAPS in any glyph pad
-- (1 / 2 / 4 / 8), scan unit and bit / byte order, BDF_ENCODINGS (one- and two-byte), SWIDTHS and GLYPH_NAMES.
-- Code points as font/bdf: the encoding is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets
-- keep glyphs unmapped (meta.encodings). Written from the PCF description in libXfont / FreeType's pcf driver
-- documentation (no code copied). Not supported: writing (write BDF and compile it with bdftopcf), INK_METRICS.
-- font/pcf: X11 Portable Compiled Format bitmap fonts, from the PCF description in libXfont / FreeType's pcf driver
-- docs (no code copied); code points as font/bdf. Not supported: writing, INK_METRICS.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -38,7 +33,6 @@ end
-- ------------------------------------------------------------------------------------------------ decode
type Table = { format: number, size: number, offset: number }
-- a reader positioned after a table's format word, with the integer readers for its byte order
type TR = { r: Bytes.Reader, format: number, big: boolean }
local function open(r: Bytes.Reader, t: Table?): TR?
@@ -91,7 +85,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
if r.err then
return nil, r.err
end
-- properties
local props: { [string]: any } = {}
local pt = open(r, tables[PROPERTIES])
if pt then
@@ -122,14 +115,12 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
return nil, Err.new(Err.TRUNCATED, "properties table")
end
end
-- accelerators: ascent / descent
local ascent: number?, descent: number? = nil, nil
local at = open(r, tables[BDF_ACCELERATORS] or tables[ACCELERATORS])
if at then
at.r:skip(8)
ascent, descent = i32(at), i32(at)
end
-- metrics
local mt = open(r, tables[METRICS])
if not mt then
return nil, Err.new(Err.CORRUPT, "no METRICS table")
@@ -152,7 +143,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
if mt.r.err then
return nil, Err.new(Err.TRUNCATED, "metrics table")
end
-- bitmaps
local bt = open(r, tables[BITMAPS])
if not bt then
return nil, Err.new(Err.CORRUPT, "no BITMAPS table")
@@ -202,7 +192,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local px = Bitmap.unpack(bits, offsets[k], w, h, stride)
glyphs[k] = { width = w, height = h, left = m[1], top = m[4], advance = m[3], pixels = px }
end
-- encodings
local encodings: { [number]: number } = {}
local default: number? = nil
local et = open(r, tables[BDF_ENCODINGS])
@@ -233,7 +222,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
end
end
end
-- glyph names
local nt = open(r, tables[GLYPH_NAMES])
if nt then
local n = u32(nt)
+8 -18
View File
@@ -1,14 +1,7 @@
--!strict
-- font/psf: Linux console fonts, PC Screen Font versions 1 (magic 36 04: 8 pixels wide, 256 or 512 glyphs, UCS-2
-- Unicode table with FFFF / FFFE) and 2 (magic 72 B5 4A 86: any width, UTF-8 Unicode table with FF / FE), read and
-- written, as the standard Font with a bitmap strike (codecs/font/Bitmap). Every code point of a glyph's table entry
-- maps to it (strike.map; combining sequences after FE / FFFE are kept in meta.sequences); fonts without a table map
-- glyph i to code point i (meta.unicode = false). Console cells have no baseline: the strike's ascent is the cell
-- height (descent 0) and every glyph fills its cell. .psf.gz / .psfu.gz load through the api's gzip unwrap. Writing:
-- PSF 2 by default (opts.version = 1 for PSF 1: 8-pixel cells, 256 or 512 glyphs) from any Font through
-- Bitmap.strike, glyphs placed in a cell of the strike's widest advance and ascent + descent; a PSF read before keeps
-- its Unicode table (meta.unicodeTable) and its table / no-table choice. Written from the kbd
-- project's psf documentation (Andries Brouwer).
-- font/psf: Linux console fonts (kbd project's psf docs, Andries Brouwer): PSF 1 (magic 36 04, UCS-2 table, FFFF /
-- FFFE) and PSF 2 (magic 72 B5 4A 86, UTF-8 table, FF / FE), read and written (PSF 2 by default); the ascent is the
-- cell height.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -28,10 +21,10 @@ local Psf = {
export type DecodeOptions = { maxGlyphs: number? } -- default 65536
export type EncodeOptions = {
version: number?, -- 1 or 2 (default 2)
px: number?, -- pixel size for outline fonts (default 16)
chars: (string | { number })?, -- code points for outline fonts (default printable ASCII)
unicode: boolean?, -- write the Unicode table (default true)
version: number?, -- 1 or 2; default 2
px: number?, -- default 16
chars: (string | { number })?, -- default printable ASCII
unicode: boolean?, -- default true
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -103,7 +96,7 @@ function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
end
local map: { [number]: number } = {}
local sequences = {}
local unicodeTable: { { any } } = {} -- per glyph: code points and { sequence } tables, in file order
local unicodeTable: { { any } } = {}
if hasTable then
local t = r:sub(glyphAt + count * size)
for i = 0, count - 1 do
@@ -141,7 +134,6 @@ function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
inSeq = true
continue
end
-- UTF-8
local n = if b < 0x80 then 0 elseif b >= 0xF0 then 3 elseif b >= 0xE0 then 2 elseif b >= 0xC0 then 1 else -1
if n < 0 then
return nil, Err.new(Err.CORRUPT, "bad UTF-8 in the Unicode table")
@@ -208,7 +200,6 @@ function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if n == 0 then
return nil, Err.new(Err.ARG, "no glyphs")
end
-- the cell
local width = 0
for _, g in glyphs do
width = math.max(width, g.advance, g.left + g.width)
@@ -241,7 +232,6 @@ function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
buffer.copy(cells, (i - 1) * size, Bitmap.pack(cell, width, height, stride))
end
-- the Unicode table: each glyph's code point and the extra mappings onto it
local cps: { { number } } = {}
for i = 1, count do
cps[i] = {}
+4 -7
View File
@@ -1,9 +1,7 @@
--!strict
-- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the
-- standard Font (Types.Font) by codecs/font/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table,
-- GPOS pair kerning) and rasterize(glyph, px) through codecs/image/Raster. Ported from stb_truetype 1.26 (public domain /
-- MIT) via imgui-luau's imstb_truetype.lua; see codecs/font/TrueType. opts.index picks the font of a collection.
-- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing.
-- font/ttf: TrueType / OpenType (glyf or CFF) fonts and collections via codecs/font/TrueType, ported from stb_truetype
-- 1.26 (public domain / MIT) via imgui-luau's imstb_truetype.lua. Not supported: hinting, variable fonts, bitmap /
-- colour glyphs, GSUB, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -21,7 +19,7 @@ local Ttf = {
}
export type DecodeOptions = {
index: number?, -- the font of a collection (default 0)
index: number?, -- default 0
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -44,7 +42,6 @@ function Ttf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- count(r) -> the number of fonts in the file (1 unless a collection)
function Ttf.count(r: Bytes.Reader): number
return TrueType.count(r.buf, r.base)
end
+2 -9
View File
@@ -1,15 +1,8 @@
--!strict
-- font/type1/Charstring: the Type 1 charstring interpreter (Adobe Type 1 Font Format, chapter 6 and 8): decrypted
-- charstrings to path commands (moveTo / lineTo / cubicTo / close, font units, y up) plus the advance and side
-- bearing. hsbw / sbw, the r/h/v moveto, lineto and curveto operators, closepath, callsubr / return, div,
-- callothersubr / pop with the standard OtherSubrs (0..2: flex, emitted as its two curves; 3: hint replacement;
-- others pass their arguments back), setcurrentpoint, seac (the base and accent glyphs from StandardEncoding codes,
-- through a callback), endchar; hints (hstem / vstem / hstem3 / vstem3 / dotsection) are ignored. New code from the
-- specification. Never throws: malformed charstrings return nil, message (an operation budget stops subroutine loops).
-- font/type1/Charstring: Type 1 charstring interpreter (Adobe Type 1 Font Format, chapters 6 and 8); hints ignored.
local Charstring = {}
export type Result = { cmds: { any }, advance: number, sbx: number }
-- fonts: subrs (decrypted subroutines), lenIV handled by the caller; seac(code) -> the base / accent Result
export type Context = { subrs: { buffer }, seac: ((code: number) -> Result?)? }
local readu8 = buffer.readu8
@@ -18,7 +11,7 @@ function Charstring.run(cs: buffer, ctx: Context): (Result?, string?)
local cmds: { any } = {}
local stack: { number } = {}
local sp = 0
local ps: { number } = {} -- the PostScript stack callothersubr / pop use
local ps: { number } = {}
local x, y = 0, 0
local advance, sbx = 0, 0
local open = false
+3 -14
View File
@@ -1,12 +1,7 @@
--!strict
-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA (hex eexec section), as the
-- standard Font: the cleartext dictionary (FontName, FamilyName, FullName, Weight, ItalicAngle, FontMatrix, FontBBox,
-- Encoding: StandardEncoding or the font's own array), eexec decryption (r = 55665), the Private dictionary (lenIV,
-- Subrs, CharStrings with RD / -| binary strings, charstring decryption r = 4330) and the Type 1 charstring
-- interpreter (font/type1/Charstring: flex, hint replacement, seac) to outlines; code points from the encoding's glyph
-- names through codecs/font/GlyphNames (AGLFN, uniXXXX), plus every other glyph name the AGL knows; rasterize through
-- codecs/image/Raster. Written from Adobe's "Adobe Type 1 Font Format" (1990). Not supported: hinting, Multiple
-- Master and CID-keyed (Type 9 / 11) fonts, writing.
-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA, from Adobe's "Adobe Type 1 Font
-- Format" (1990): eexec (r = 55665) and charstring (r = 4330) decryption, code points via codecs/font/GlyphNames.
-- Not supported: hinting, Multiple Master and CID-keyed (Type 9 / 11) fonts, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -41,7 +36,6 @@ function Type1.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the cleartext and the (still encrypted) binary eexec section of a PFB or PFA
local function sections(r: Bytes.Reader): (string?, buffer?, string?)
local b = r.buf
local n = r:size()
@@ -204,7 +198,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4)
local ptext = buffer.tostring(priv)
local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4
-- Subrs
local subrs: { buffer } = {}
local function charstring(p: number, len: number): buffer?
local raw = binaryAt(priv, p, len)
@@ -241,7 +234,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
p = e + n
end
end
-- CharStrings
local names: { string } = {}
local charstrings: { buffer } = {}
local byName: { [string]: number } = {}
@@ -252,7 +244,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
break
end
local e = e0 :: number
-- stop at the end of the dictionary
if string.find(string.sub(ptext, p, s), "%send%s") then
break
end
@@ -281,7 +272,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1]
byName[names[1]], byName[names[nd + 1]] = 0, nd
end
-- the encoding
local encoding: { [number]: string } = {}
if string.find(clear, "/Encoding%s+StandardEncoding") then
for code, gname in GlyphNames.STANDARD do
@@ -306,7 +296,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
cmap[cp] = k - 1
end
end
-- font matrix / bbox
local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]")
local scale = 0.001
if fm then
+3 -5
View File
@@ -1,7 +1,6 @@
--!strict
-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding
-- rebuilds the sfnt and reads it through codecs/font/TrueType (TrueType or CFF outlines, see font/ttf); the extended
-- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing.
-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): zlib-compressed sfnt tables, rebuilt and read through
-- codecs/font/TrueType; the metadata XML goes to meta.woffMetadata. Not supported: writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -20,7 +19,7 @@ local Woff = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28)
maxBytes: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -29,7 +28,6 @@ function Woff.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- sfnt(r, opts?) -> the rebuilt sfnt font file (a buffer) | nil, Err
function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, string?)
local maxBytes = (opts and opts.maxBytes) or 2 ^ 28
local base = r.base
+1 -11
View File
@@ -1,10 +1,5 @@
--!strict
-- font/woff2/Rebuild: rebuilds the sfnt of a WOFF2 file (W3C WOFF2 Recommendation, 2024 edition): the table
-- directory, the Brotli stream, the transformed glyf / loca tables (section 5: nContour, nPoints, flag, glyph,
-- composite, bbox and instruction streams, triplet-encoded coordinates, the overlap bitmap) and the transformed hmtx
-- (section 6: side bearings from the glyph bounds). Written from the spec. Not supported: collections (ttcf flavor).
--
-- Never throws: malformed data returns nil, message.
-- font/woff2/Rebuild: the sfnt of a WOFF2 file (W3C WOFF2, 2024 edition: section 5 glyf / loca, section 6 hmtx).
local Bytes = require("@rosetta/core/Bytes")
local Brotli = require("@rosetta/codecs/compress/Brotli")
@@ -40,7 +35,6 @@ local function base128(r: Bytes.Reader): number?
return nil
end
-- a cursor over a stream inside the decompressed block
type Stream = { buf: buffer, p: number, e: number, bad: boolean }
local function stream(b: buffer, p: number, n: number): Stream
return { buf = b, p = p, e = p + n, bad = false }
@@ -77,7 +71,6 @@ local function withSign(flag: number, v: number): number
return if band(flag, 1) ~= 0 then v else -v
end
-- the glyf transform -> glyf bytes (a Writer), loca offsets, per-glyph xMin (for hmtx), numGlyphs, indexFormat
local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, string?)
local h = stream(b, p, n)
su16(h) -- reserved
@@ -132,7 +125,6 @@ local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, s
return nil, "empty glyph with a bounding box"
end
elseif nc > 0 then
-- simple glyph
local ends = table.create(nc, 0)
local total = 0
for c = 1, nc do
@@ -363,7 +355,6 @@ local function hmtx(b: buffer, p: number, n: number, numGlyphs: number, numH: nu
return out:finish(), nil
end
-- sfnt(r, maxBytes) -> sfnt buffer | nil, message, code ("truncated" / "corrupt" / "unsupported" / "limit")
function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, string?)
if not r:match("wOF2") then
return nil, "bad signature", "corrupt"
@@ -433,7 +424,6 @@ function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, str
if buffer.len(data) < streamTotal then
return nil, "decompressed stream shorter than the tables", "corrupt"
end
-- the tables, glyf / loca / hmtx rebuilt
local byTag: { [string]: any } = {}
for _, e in dir do
byTag[e.tag] = e
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff. Show more