merge ws/cm-codecs

This commit is contained in:
4DBug committed 2026-11-01 01:27:54 -06:00
commit c12d5b12bf
202 files changed
+1390 -4762

No files matched your search

+69 -69
View File
@@ -183,89 +183,89 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- **audio**
- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the
- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in rosetta; the IMA and
- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
- codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28
- codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and
- codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim,
- codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats
- codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
- codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list,
- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it:
- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped
- codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT
- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): AudioSpecificConfig, ADTS, raw_data_block.
- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: syncinfo / BSI, CRC check and decoder.
- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap).
- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder.
- codecs/audio/Ape: the Monkey's Audio codec (.ape), file versions 3.95 and later.
- codecs/audio/ApeTag: APEv1 / APEv2 tags -> Types.Tags.
- codecs/audio/Flac: FLAC frames without the container (frame header, subframes, CRC-8 / CRC-16) and the frame encoder.
- codecs/audio/Hively: the AHX / HivelyTracker engine (loader, replayer, waveform tables, render glue).
- codecs/audio/Mdct: MDCT / IMDCT for any N divisible by 4, DCT-IV, and the sine / KBD / Vorbis windows.
- codecs/audio/MidiRender: the MIDI tempo map, event timeline and the Decoder that plays a Midi through SoundFont.
- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it.
- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8.
- codecs/audio/Opus: the Opus codec (RFC 6716) without its container.
- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale
- codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or
- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
- codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part
- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders
- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description
- codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup),
- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags.
- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec
- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA).
- codecs/audio/Resample: sample-rate conversion by band-limited (Kaiser-windowed sinc) polyphase interpolation.
- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them.
- codecs/audio/Stream: the streaming Types.Decoder over a packetised codec (gapless trim, seeking with pre-roll).
- codecs/audio/Tracker: the shared tracker engine behind music/mod, s3m, xm and it, and the formats mapped onto them.
- codecs/audio/Tta: the TTA1 (True Audio) lossless codec.
- codecs/audio/Vorbis: the Vorbis I decoder without its container.
- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value"; Vorbis, Opus, FLAC) <-> Types.Tags.
- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska).
- **compress**
- codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ
- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder
- codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo:
- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
- codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes,
- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF
- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft
- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code
- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content
- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
- codecs/compress/Brotli: Brotli (RFC 7932) decompression, with the large-window extension.
- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x).
- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with zlib (RFC 1950) and gzip (RFC 1952).
- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987).
- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md), decode and the reference "fast" encoder.
- codecs/compress/Lzh: the LHA family of LZSS decoders (lh1, lh4-lh7, lhx, lzs, lz5, ARJ 1-4, Zoo 2).
- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container.
- codecs/compress/Lzw: LZW decoder and encoder, from the GIF89a spec (appendix F) and TIFF 6.0 section 13 (new code).
- codecs/compress/Lzx: the LZX decoder for Microsoft Cabinet folders (windows of 2^15 .. 2^21 bytes).
- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD RLE, IFF ByteRun1).
- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 + adaptive arithmetic coder) for Cabinet folders.
- codecs/compress/UnixCompress: the LZW of Unix compress (.Z: magic 1F 9D, a flags byte: max width 9..16, block mode).
- codecs/compress/Xxh32: XXH32 for the LZ4 frame checksums, from the xxHash specification (Yann Collet, BSD-2).
- codecs/compress/Zstd: Zstandard decompression (RFC 8878), written from the specification; no dictionaries.
- **entropy**
- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders.
- codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt):
- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order).
- codecs/entropy/RangeCoder: the RFC 6716 range coder used by Opus, a port of libopus celt/entdec.c + entenc.c.
- **font**
- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike
- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
- codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a
- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT) and their 1-bit rows.
- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177), the outlines of .otf fonts.
- codecs/font/GlyphNames: PostScript glyph names -> Unicode (AGL specification) and Adobe StandardEncoding.
- codecs/font/TrueType: the sfnt container (.ttf, .otf with CFF outlines, .ttc collections) as the standard Font value.
- **image**
- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...):
- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
- codecs/image/Bcn: BC1-BC7 block-compressed textures with the D3D11 rules.
- codecs/image/Blend: rgba8 layer compositing (straight alpha) with the W3C Compositing and Blending Level 1 modes.
- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
- codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar
- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H,
- codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP,
- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers
- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...):
- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
- codecs/image/Etc: ETC1 / ETC2 / EAC block texture decoding (Khronos Data Format Specification 1.3, section 21).
- codecs/image/Half: IEEE 754 binary16 <-> number (round to nearest even, overflow to infinity). New in rosetta.
- codecs/image/Jpeg: the JPEG codec (ITU T.81), bit-exact with libjpeg-turbo's djpeg and byte-identical with cjpeg.
- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB.
- codecs/image/Quantize: palette quantization of rgba8 pixels (median cut or octree, Floyd-Steinberg dithering).
- codecs/image/Raster: an antialiased scanline rasterizer (nonzero / even-odd) for line and Bézier paths, plus a stroker.
- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats. New in rosetta.
- codecs/image/Texture: one entry point over the texture pixel codecs (Bcn, Etc, Texel). New in rosetta.
- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only.
- codecs/image/Vp8L: WebP lossless (VP8L, RFC 9649 section 3).
- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8, BT.601 / BT.709, limited or full range.
- **model**
- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7).
- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16
- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
- codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers.
- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF).
- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code.
- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map
- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl,
- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each
- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for
- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML,
- codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code.
- codecs/model/Rbx: the Roblox instance tree and property values shared by model/rbxm and model/rbxmx.
- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...). New code.
- codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 animations. New code.
- codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d.
- **text**
- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt,
- codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is
- codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL,
- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ...
- codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT").
- codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting.
- codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding.
- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize. New code.
- **video**
- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs.
- codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int.
- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the
- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau, bit-exact with ffmpeg.
- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders.
- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder
- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), the old name and API over codecs/video/Mpeg2.
- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile).
- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska
- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg and Matroska (V_THEORA).
- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta.
+18 -40
View File
@@ -1,12 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE /
-- FIL / END elements, ics_info with window grouping, section data, scalefactors (with noise energies and intensity
-- positions), pulse data, TNS, the eleven spectral codebooks with escapes, dequantisation, M/S and intensity stereo,
-- perceptual noise substitution (FFmpeg's LCG so the noise matches it), the filterbank (sine / KBD windows, the four
-- window sequences, IMDCT through codecs/audio/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook
-- and otherwise skipped. Written from the standard; no third-party code. Never throws: returns nil, message.
-- codecs/audio/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4).
-- Written from the standard; no third-party code. PNS uses FFmpeg's LCG so the noise matches it.
local Mdct = require("@rosetta/codecs/audio/Mdct")
local Tables = require("@rosetta/codecs/audio/Aac/Tables")
@@ -18,14 +14,13 @@ local Decode = {}
local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3
local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15
-- ------------------------------------------------------------------------------------------------ bit reader
-- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields)
local B: buffer = buffer.create(16)
local BP = 0 -- bit position
local BL = 0 -- bit limit
local BP = 0
local BL = 0
local OVER = false
local function getBits(n: number): number -- 1 .. 25
local function getBits(n: number): number
local p = BP
BP = p + n
if p > BL then
@@ -49,7 +44,6 @@ local function getLong(n: number): number
return getBits(n)
end
-- ------------------------------------------------------------------------------------------------ Huffman
local PEEK = 10
type Book = { tab: { number }, map: { [number]: number }, maxLen: number }
@@ -78,14 +72,12 @@ for i = 1, 11 do
SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i])
end
-- the next symbol of a book, -1 for an invalid code
local function huff(bk: Book): number
local e = bk.tab[peekBits(PEEK) + 1]
if e > 0 then
BP += band(e, 31)
return rshift(e, 5)
end
-- a code longer than PEEK bits
local code = getBits(PEEK)
local map = bk.map
for l = PEEK + 1, bk.maxLen do
@@ -98,7 +90,6 @@ local function huff(bk: Book): number
return -1
end
-- per codebook: dimension, unsigned, modulus, offset
local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 }
local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true }
local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 }
@@ -110,7 +101,6 @@ for i = 0, 8191 do
POW43[i + 1] = i ^ (4 / 3)
end
-- ------------------------------------------------------------------------------------------------ windows
local SINE_LONG = Mdct.window("sine", 2048) :: { number }
local KBD_LONG = Mdct.window("kbd", 2048, 4) :: { number }
local SINE_SHORT = Mdct.window("sine", 256) :: { number }
@@ -118,37 +108,34 @@ local KBD_SHORT = Mdct.window("kbd", 256, 6) :: { number }
local PLAN_LONG = Mdct.new(2048) :: Mdct.Plan
local PLAN_SHORT = Mdct.new(256) :: Mdct.Plan
-- ------------------------------------------------------------------------------------------------ state
export type Channel = {
spec: { number }, -- 1024 dequantised coefficients (8 x 128 for short windows)
overlap: { number }, -- 1024 samples carried to the next frame
spec: { number },
overlap: { number },
prevShape: number,
-- this frame's ics
windowSequence: number,
windowShape: number,
maxSfb: number,
numGroups: number,
groupLen: { number },
bandType: { number }, -- [g * maxSfb + sfb + 1]
bandType: { number },
sf: { number },
-- tns
tnsFilters: { { { number } } }, -- per window: { length, order, direction, coefs ... } flattened per filter
tnsFilters: { { { number } } },
}
export type State = {
sfIndex: number,
channels: number, -- configured channels (0: as found)
channels: number,
frameLength: number,
ch: { Channel },
pcm: { number }, -- interleaved output floats
random: number, -- PNS generator state
time: { number }, -- 2048 IMDCT scratch
frame: { number }, -- 2048 windowed frame scratch
short: { number }, -- 256 scratch
pcm: { number },
random: number,
time: { number },
frame: { number },
short: { number },
onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?,
extensions: number, -- extension payloads seen (SBR / PS / ...)
sbr: boolean, -- an SBR payload was seen
map: { number }?, -- element channel order -> output channel (1-based)
extensions: number,
sbr: boolean,
map: { number }?,
}
local function newChannel(): Channel
@@ -168,7 +155,6 @@ local function newChannel(): Channel
end
Decode.newChannel = newChannel
-- ------------------------------------------------------------------------------------------------ ics
local function icsInfo(st: State, c: Channel): string?
if getBits(1) ~= 0 then
return "reserved ics bit set"
@@ -394,7 +380,6 @@ local function applyTns(st: State, c: Channel)
end
end
-- the spectral data of one channel, dequantised into c.spec (also pulses, noise, intensity zeros)
local function spectralData(st: State, c: Channel, pulses: { number }?): string?
local short = c.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
@@ -530,7 +515,6 @@ local function spectralData(st: State, c: Channel, pulses: { number }?): string?
win += glen
end
if pulses then
-- long window: add the pulses to the quantised values, then dequantise every band
for i = 1, #pulses, 2 do
local pos = pulses[i] + 1
if pos <= 1024 then
@@ -609,7 +593,6 @@ local function ics(st: State, c: Channel, commonWindow: boolean): string?
return spectralData(st, c, pulses)
end
-- ------------------------------------------------------------------------------------------------ stereo
local function msStereo(st: State, l: Channel, r: Channel, mask: { number })
local short = l.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
@@ -663,7 +646,6 @@ local function intensity(st: State, l: Channel, r: Channel, mask: { number }, ms
end
end
-- ------------------------------------------------------------------------------------------------ filterbank
local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number)
local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape
local spec, overlap = c.spec, c.overlap
@@ -688,7 +670,6 @@ local function filterbank(st: State, c: Channel, out: { number }, stride: number
else
local t = st.time
Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048)
-- left half
if seq == LONG_STOP then
local rise = if prev == 1 then KBD_SHORT else SINE_SHORT
for n = 1, 448 do
@@ -706,7 +687,6 @@ local function filterbank(st: State, c: Channel, out: { number }, stride: number
frame[n] = t[n] * rise[n]
end
end
-- right half
if seq == LONG_START then
local fall = if shape == 1 then KBD_SHORT else SINE_SHORT
for n = 1025, 1472 do
@@ -734,8 +714,6 @@ local function filterbank(st: State, c: Channel, out: { number }, stride: number
c.prevShape = shape
end
-- ------------------------------------------------------------------------------------------------ frame
-- frame(st, buf, off, len) -> channels decoded | nil, message. Output: st.pcm, 1024 frames interleaved.
function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?)
if buffer.len(B) < len + 16 then
B = buffer.create(len + 256)
+3 -4
View File
@@ -1,8 +1,7 @@
--!strict
-- codecs/audio/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven
-- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128
-- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code;
-- see licenses/NOTICE.md). Generated; do not edit.
-- codecs/audio/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): Huffman codebooks, scalefactor
-- band offsets, TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code; see
-- licenses/NOTICE.md). Generated; do not edit.
local Tables = {}
Tables.SF_CODES = {
+10 -29
View File
@@ -1,20 +1,7 @@
--!strict
-- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
-- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding
-- (codecs/audio/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it.
-- Written from the standard (tables: codecs/audio/Aac/Tables); no third-party code.
-- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD
-- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads)
-- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a
-- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain
-- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED).
--
-- local Aac = require("@rosetta/codecs/audio/Aac")
-- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels }
-- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats)
-- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... }
--
-- Never throws: bad data returns nil, Err.
-- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): AudioSpecificConfig, ADTS, raw_data_block.
-- Written from the standard; no third-party code. HE-AAC decodes its AAC-LC core at the core rate. Not supported: Main
-- prediction, LTP, SSR, coupling channels, 960-sample frames, ER / USAC (UNSUPPORTED).
local Err = require("@rosetta/core/Err")
local Bits = require("@rosetta/core/Bits")
local Decode = require("@rosetta/codecs/audio/Aac/Decode")
@@ -35,12 +22,12 @@ local CONFIG_MAP: { [number]: { number } } = {
export type Config = {
objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled)
sfIndex: number,
sampleRate: number, -- the core rate
sampleRate: number,
channelConfig: number,
channels: number,
sbr: boolean, -- SBR signalled (explicitly or backward-compatibly)
sbr: boolean,
ps: boolean,
extensionRate: number?, -- the SBR output rate
extensionRate: number?,
frameLength: number,
}
@@ -72,7 +59,7 @@ local function frequency(br: Bits.BitReader): (number, number)
return i, Aac.RATES[i + 1] or 0
end
-- pce(br) -> channels (program_config_element)
-- program_config_element
local function pce(br: Bits.BitReader): number
br:read(4 + 2 + 4)
local front, side, back = br:read(4), br:read(4), br:read(4)
@@ -98,7 +85,6 @@ local function pce(br: Bits.BitReader): number
return channels
end
-- config(asc) -> Config | nil, Err: parse an AudioSpecificConfig
function Aac.config(asc: buffer): (Config?, Err.Err?)
if type(asc) ~= "buffer" or buffer.len(asc) < 2 then
return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes")
@@ -182,7 +168,6 @@ function Aac.config(asc: buffer): (Config?, Err.Err?)
}, nil
end
-- asc(objectType, sfIndex, channelConfig) -> a 2-byte AudioSpecificConfig
function Aac.asc(aot: number, sfIndex: number, channelConfig: number): buffer
local b = buffer.create(2)
local v = aot * 2048 + sfIndex * 128 + channelConfig * 8
@@ -193,7 +178,7 @@ end
export type Adts = {
headerSize: number, -- 7, or 9 with a CRC
frameSize: number, -- the whole frame, header included
frameSize: number,
objectType: number,
sfIndex: number,
sampleRate: number,
@@ -202,7 +187,6 @@ export type Adts = {
protected: boolean,
}
-- adts(buf, offset, limit) -> Adts | nil (not a valid header at offset)
function Aac.adts(b: buffer, o: number, limit: number): Adts?
if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then
return nil
@@ -233,14 +217,13 @@ function Aac.adts(b: buffer, o: number, limit: number): Adts?
}
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Decoder = {
config: Config,
channels: number,
sampleRate: number,
frameLength: number,
pcm: { number }, -- the last frame: 1024 * channels interleaved floats (-1 .. 1), WAV channel order
sbr: boolean, -- SBR payloads seen in the stream (implicit signalling) or signalled
pcm: { number },
sbr: boolean,
onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?,
decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
reset: (self: Decoder) -> (),
@@ -263,7 +246,6 @@ local function decode(self: Decoder, buf: buffer, offset: number?, length: numbe
self.sbr = true
end
if chans == 0 then
-- an empty frame (only fill elements): silence
for i = 1, 1024 * self.channels do
st.pcm[i] = 0
end
@@ -284,7 +266,6 @@ local function reset(self: Decoder)
end
end
-- decoder(asc | { objectType?, sfIndex, channels }) -> Decoder | nil, Err
function Aac.decoder(asc: any): (Decoder?, Err.Err?)
local cfg: Config
if type(asc) == "buffer" then
+12 -45
View File
@@ -1,12 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Ac3/Decode: one AC-3 syncframe (6 audio blocks of 256 samples) -> PCM. Written from ATSC A/52:2018
-- (section 5.3 syntax, 7.1 exponents, 7.2 parametric bit allocation with delta bit allocation, 7.3 mantissas with
-- grouping and dither, 7.4 coupling with phase flags, 7.5 rematrixing, 7.7.1 dynamic range, 7.9 the 512 / 2 x 256
-- inverse transforms with block switching) on codecs/audio/Mdct; no third-party code. The bit reader is module state
-- over a frame the caller pads by PAD bytes; every section stops when the position passes the frame. No error /
-- assert: failures return nil, "message".
-- codecs/audio/Ac3/Decode: one AC-3 syncframe (6 audio blocks of 256 samples) -> PCM.
-- Written from ATSC A/52:2018 (5.3 syntax, 7.1 exponents, 7.2 bit allocation, 7.3 mantissas, 7.4 coupling, 7.5
-- rematrixing, 7.7.1 dynamic range, 7.9 transforms); no third-party code. The caller pads the frame by PAD bytes.
local T = require("@rosetta/codecs/audio/Ac3/Tables")
local Mdct = require("@rosetta/codecs/audio/Mdct")
@@ -22,7 +19,6 @@ local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 }
local SLOWDEC, FASTDEC, SLOWGAIN, DBPBTAB, FLOORTAB, FASTGAIN = T.SLOWDEC, T.FASTDEC, T.SLOWGAIN, T.DBPBTAB, T.FLOORTAB, T.FASTGAIN
local BNDTAB, BNDSZ, MASKTAB, LATAB, HTH, BAPTAB = T.BNDTAB, T.BNDSZ, T.MASKTAB, T.LATAB, T.HTH, T.BAPTAB
-- 2^-e for the exponents 0 .. 24
local POW2 = table.create(32, 0)
for e = 0, 31 do
POW2[e + 1] = 2 ^ -e
@@ -43,7 +39,6 @@ local WINDOW = Mdct.window("kbd", 512, 5) :: { number }
local PLAN512 = Mdct.new(512) :: Mdct.Plan
local PLAN256 = Mdct.new(256) :: Mdct.Plan
-- ------------------------------------------------------------------------------------------------ bit reader
local B: buffer = buffer.create(0)
local P = 0
@@ -61,17 +56,14 @@ local function bits(n: number): number
return v
end
-- ------------------------------------------------------------------------------------------------ state
export type State = {
-- the frame header
fscod: number,
acmod: number,
lfeon: boolean,
nfchans: number,
channels: number, -- output channels
map: { number }, -- output index of slots 1 .. 6
drc: number, -- the dynamic range scale (0 = off)
-- per channel slot (1 .. 7)
channels: number,
map: { number },
drc: number,
exp: { { number } },
bap: { { number } },
coef: { { number } },
@@ -86,19 +78,17 @@ export type State = {
dbaOffst: { { number } },
dbaLen: { { number } },
dbaBa: { { number } },
-- coupling
cplinu: boolean,
chincpl: { boolean },
phsflginu: boolean,
cplbegf: number,
cplendf: number,
cplbndstrc: { boolean }, -- [sbnd + 1], sbnd = 0 .. 17 (absolute sub-band)
cplco: { { number } }, -- [ch][sbnd + 1]
phsflg: { boolean }, -- [sbnd + 1]
cplco: { { number } },
phsflg: { boolean },
cplfleak: number,
cplsleak: number,
rematflg: { boolean },
-- bit allocation parameters
sdcycod: number,
fdcycod: number,
sgaincod: number,
@@ -106,15 +96,14 @@ export type State = {
floorcod: number,
csnroffst: number,
dynrng: { number }, -- gain for Ch1 / Ch2
seed: number, -- dither generator
-- scratch
seed: number,
psd: { number },
bndpsd: { number },
excite: { number },
mask: { number },
y: { number },
pcm: { number },
blocks: { number }, -- the bit offset of each audio block in the last frame (for tools)
blocks: { number },
}
local function arrays(n: number, size: number, v: any): { any }
@@ -177,7 +166,6 @@ function Decode.state(): State
}
end
-- reset(st): forget the overlap (before a seek)
function Decode.reset(st: State)
for _, d in st.delay do
for i = 1, 256 do
@@ -186,9 +174,7 @@ function Decode.reset(st: State)
end
end
-- ------------------------------------------------------------------------------------------------ exponents
-- read ngrps grouped exponents (7 bits = 3 deltas each) after absexp into e[first + 1 ..] (bins first ..), grpsize
-- bins per delta; false when an exponent leaves 0 .. 24
-- grouped exponents: 7 bits = 3 deltas each after absexp, grpsize bins per delta; each exponent stays in 0 .. 24
local function exponents(e: { number }, absexp: number, ngrps: number, grpsize: number, first: number): boolean
local prev = absexp
local k = first + 1
@@ -215,7 +201,6 @@ local function exponents(e: { number }, absexp: number, ngrps: number, grpsize:
return true
end
-- ------------------------------------------------------------------------------------------------ bit allocation
local function logadd(a: number, b: number): number
local c = a - b
local adr = min(rshift(if c >= 0 then c else -c, 1), 255)
@@ -357,7 +342,6 @@ local function allocate(st: State, ch: number, start: number, stop: number, fgai
until stop <= lastbin
end
-- ------------------------------------------------------------------------------------------------ mantissas
-- grouped mantissa state (bap 1, 2, 4 share groups across channels within a block)
local G1, G2, G4 = table.create(3, 0), table.create(3, 0), table.create(2, 0)
local n1, n2, n4 = 0, 0, 0
@@ -368,7 +352,6 @@ local function dither(st: State): number
return (s / 2147483648 - 1) * 0.707
end
-- the mantissas of bins [start, stop) of slot ch into out[], scaled by their exponents (bap 0: dither when asked)
local function mantissas(st: State, ch: number, start: number, stop: number, out: { number }, dith: boolean)
local e, bap = st.exp[ch], st.bap[ch]
for bin = start, stop - 1 do
@@ -426,7 +409,6 @@ local function mantissas(st: State, ch: number, start: number, stop: number, out
end
end
-- ------------------------------------------------------------------------------------------------ audio block
local function readDba(st: State, ch: number)
local nseg = bits(3) + 1
local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch]
@@ -463,7 +445,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string?
st.dynrng[i] = 1
end
end
-- coupling strategy
if bits(1) == 1 then
st.cplinu = bits(1) == 1
if st.cplinu then
@@ -527,7 +508,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string?
end
end
end
-- rematrixing
if acmod == 2 then
if bits(1) == 1 then
local n = if not cplinu or cplbegf > 2 then 4 elseif cplbegf > 0 then 3 else 2
@@ -540,7 +520,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string?
end
end
end
-- exponent strategies
local chexpstr = st.chexpstr
chexpstr[CPL] = if cplinu then bits(2) else 0
for ch = 1, nf do
@@ -572,7 +551,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string?
end
end
endmant[LFE] = 7
-- exponents
if cplinu and chexpstr[CPL] ~= 0 then
local abs = bits(4) * 2
local grp = EXPGRP[chexpstr[CPL]]
@@ -610,7 +588,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string?
if P > limit then
return nil, "truncated block"
end
-- bit allocation parameters
if bits(1) == 1 then
st.sdcycod, st.fdcycod, st.sgaincod, st.dbpbcod, st.floorcod = bits(2), bits(2), bits(2), bits(2), bits(3)
elseif blk == 0 then
@@ -635,7 +612,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string?
st.cplfleak, st.cplsleak = bits(3), bits(3)
end
end
-- delta bit allocation
if bits(1) == 1 then
local modes = table.create(7, 0)
if cplinu then
@@ -664,14 +640,12 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string?
st.dbaOn[ch] = false
end
end
-- skip field
if bits(1) == 1 then
P += bits(9) * 8
end
if P > limit then
return nil, "truncated block"
end
-- bit allocation
local zero = st.csnroffst == 0
if zero then
for ch = 1, nf do
@@ -702,7 +676,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string?
if st.lfeon then
alloc(LFE, 0, 7, true)
end
-- mantissas
n1, n2, n4 = 0, 0, 0
local gotCpl = false
local coef = st.coef
@@ -774,13 +747,11 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string?
return true, nil
end
-- ------------------------------------------------------------------------------------------------ transform
-- the inverse transform of slot ch (long or two short), windowed, overlap-added into out[base + i * step]
local function synth(st: State, ch: number, short: boolean, gain: number, out: { number }, base: number, step: number)
local x, y, d, w = st.coef[ch], st.y, st.delay[ch], WINDOW
if short then
-- two 256-point transforms of the interleaved coefficients, phases alpha = -1 (n0 = 0) and +1 (n0 = N / 2)
local z = st.psd -- 256 scratch
local z = st.psd
Mdct.inverse(PLAN256, x, 1, 2, z, 1, -2 * gain)
for n = 0, 63 do
y[n + 1] = -z[n + 193]
@@ -806,7 +777,6 @@ local function synth(st: State, ch: number, short: boolean, gain: number, out: {
end
end
-- ------------------------------------------------------------------------------------------------ frame
-- the output index of each slot (1 .. 5 full bandwidth, 6 LFE) in WAVE order: L R C LFE surrounds
local ORDER: { [number]: { number } } = {
[0] = { 1, 2 },
@@ -820,8 +790,6 @@ local ORDER: { [number]: { number } } = {
}
local HAS_C = { [0] = false, true, false, true, false, true, false, true }
-- frame(st, buf, len, drc) -> 1536 | nil, message: decodes the syncframe at buf[0 .. len) (padded by PAD bytes)
-- into st.pcm (1536 * st.channels interleaved floats, WAVE order). drc: the dynamic range scale (0 = off, 1 = full).
function Decode.frame(st: State, buf: buffer, len: number, drc: number): (number?, string?)
if len < 8 or buffer.len(buf) < len + Decode.PAD then
return nil, "truncated frame"
@@ -875,7 +843,6 @@ function Decode.frame(st: State, buf: buffer, len: number, drc: number): (number
local nf = NFCHANS[acmod]
local channels = nf + (if lfeon then 1 else 0)
if st.acmod ~= acmod or st.lfeon ~= lfeon then
-- a new channel layout: build the output map and forget the overlap
local order = ORDER[acmod]
local map = table.create(6, 0)
local nfront = if HAS_C[acmod] then 3 elseif acmod == 1 then 1 else 2
+5 -8
View File
@@ -1,9 +1,6 @@
--!strict
-- codecs/audio/Ac3/Tables: the AC-3 constant tables, transcribed from ATSC A/52:2018 (Digital Audio Compression
-- Standard) section 7.2.3 (bit allocation: slowdec, fastdec, slowgain, dbpbtab, floortab, fastgain, bndtab / bndsz,
-- latab, hth, baptab) and section 5.4 (frame sizes). masktab is derived from bndtab / bndsz, the transform window
-- (Table 7.33) is the Kaiser-Bessel-derived window with alpha 5 (codecs/audio/Mdct), which Table 7.33 rounds to five
-- decimals. No third-party code.
-- codecs/audio/Ac3/Tables: transcribed from ATSC A/52:2018 section 7.2.3 (bit allocation tables) and section 5.4 (frame
-- sizes); masktab is derived from bndtab / bndsz. No third-party code.
local T = {}
T.SLOWDEC = { 0x0f, 0x11, 0x13, 0x15 }
@@ -13,7 +10,7 @@ T.DBPBTAB = { 0x000, 0x700, 0x900, 0xb00 }
T.FLOORTAB = { 0x2f0, 0x2b0, 0x270, 0x230, 0x1f0, 0x170, 0x0f0, 0xf800 }
T.FASTGAIN = { 0x080, 0x100, 0x180, 0x200, 0x280, 0x300, 0x380, 0x400 }
-- the 50 bit allocation bands: first bin and width (Table 7.12)
-- bit allocation bands: first bin and width (Table 7.12)
T.BNDTAB = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 31, 34, 37, 40, 43, 46, 49, 55, 61, 67, 73, 79, 85, 97, 109, 121, 133, 157, 181, 205, 229,
@@ -22,7 +19,7 @@ T.BNDSZ = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 24, 24, 24, 24, 24,
}
-- masktab[bin + 1]: the band of each bin (Table 7.13; bins 253 .. 255 map to 0)
-- masktab (Table 7.13; bins 253 .. 255 map to 0)
T.MASKTAB = table.create(256, 0)
for b = 1, 50 do
for k = T.BNDTAB[b], T.BNDTAB[b] + T.BNDSZ[b] - 1 do
@@ -50,7 +47,7 @@ T.LATAB = {
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
}
-- hearing threshold per band (Table 7.15): HTH[fscod + 1][band + 1]
-- hearing threshold (Table 7.15): HTH[fscod + 1][band + 1]
T.HTH = {
{
0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0,
+9 -24
View File
@@ -1,17 +1,6 @@
--!strict
-- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the
-- decoder (codecs/audio/Ac3/Decode). Written from ATSC A/52:2018; no third-party code. A codec (layer 3): audio/ac3
-- (raw .ac3 files) builds on it, and the AC-3 tracks of MKV / MP4 / MPEG-TS / AVI reach it through
-- containers/AudioWrap.
-- Supports: every acmod (1+1, 1/0 .. 3/2) with or without LFE, 32 / 44.1 / 48 kHz, all bit rates, coupling with phase
-- flags, rematrixing, block switching, delta bit allocation, dither, dynamic range control (off by default,
-- `drc` = 0 .. 1 scales it). Output: every channel in WAVE order (L R C LFE surrounds), no downmix. Not supported:
-- E-AC-3 (bsid 11 .. 16) and the reduced-rate bsid 9 / 10 streams (UNSUPPORTED).
--
-- local h = Ac3.header(buf, offset, limit) -- { sampleRate, frameSize, channels, acmod, lfeon, bsid, bitrate }
-- local dec = Ac3.decoder({ drc = 0 }) -- dec:decode(buf, offset, length) -> 1536, dec.pcm (interleaved)
--
-- Never throws: bad data returns nil, Err.
-- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: syncinfo / BSI, CRC check and decoder.
-- Written from ATSC A/52:2018; no third-party code. E-AC-3 (bsid 11 .. 16) and bsid 9 / 10 are UNSUPPORTED.
local Err = require("@rosetta/core/Err")
local T = require("@rosetta/codecs/audio/Ac3/Tables")
local Decode = require("@rosetta/codecs/audio/Ac3/Decode")
@@ -23,16 +12,14 @@ local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 }
export type Header = {
sampleRate: number,
frameSize: number, -- bytes
bitrate: number, -- bits per second
frameSize: number,
bitrate: number,
channels: number,
acmod: number,
lfeon: boolean,
bsid: number,
}
-- header(buf, o, limit) -> Header | nil (not an AC-3 / E-AC-3 syncframe header at o). E-AC-3 headers (bsid > 10)
-- come back with frameSize from their own frmsiz field so a scanner can step over them.
function Ac3.header(b: buffer, o: number, limit: number): Header?
if o < 0 or o + 8 > limit or o + 8 > buffer.len(b) then
return nil
@@ -90,8 +77,7 @@ function Ac3.header(b: buffer, o: number, limit: number): Header?
}
end
-- the CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): a syncframe checks when the CRC of
-- everything after the sync word is 0
-- CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): 0 over everything after the sync word
local CRC = table.create(256, 0)
for i = 0, 255 do
local c = i * 256
@@ -109,17 +95,16 @@ function Ac3.crc(b: buffer, o: number, n: number): number
return c
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Options = {
drc: number?, -- dynamic range control: 0 = off (default, like ffmpeg -drc_scale 0), 1 = as the stream says
crc: boolean?, -- check crc2 (default true): a mismatch is Err.CHECKSUM
drc: number?, -- 0 = off (default, as ffmpeg -drc_scale 0), 1 = as the stream says
crc: boolean?,
}
export type Decoder = {
pcm: { number }, -- the last frame: 1536 * channels interleaved floats, WAVE order
pcm: { number },
channels: number,
sampleRate: number,
blocks: { number }, -- the bit offset of each audio block in the last frame (tools: stream editing, analysis)
blocks: { number },
decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
reset: (self: Decoder) -> (),
}
+16 -44
View File
@@ -1,26 +1,6 @@
--!strict
-- codecs/audio/Adpcm/Decoder: the streaming Decoder (Types.Decoder) over an ADPCM stream cut into packets, for the
-- formats whose state carries from packet to packet (ADX, VAG, BRSTM, raw IMA): codecs/audio/Stream.packets plus
-- exact seeking. The codec state (one buffer the packet decoder advances) is snapshotted at every packet start it
-- passes; a seek restores the snapshot, else the format's own state for that packet (BRSTM's ADPC history), else
-- decodes forward from the nearest earlier snapshot. New in rosetta.
--
-- local dec, err = Decoder.packets(dec, { -- dec: the Decoder table (sampleRate, channels, frames, ...)
-- count = n, packetFrames = 4096, -- packets of packetFrames frames (the last may be shorter)
-- frames = total, -- output frames
-- state = st, -- the codec state buffer decode advances
-- decode = function(i, out) return frames end, -- packet i (1-based) as interleaved f32 into out from 0
-- restore = function(i) return false end, -- optional: set st for packet i, true if it could
-- })
--
-- The layouts the formats share, each returning the Decoder (dec gets read / seek / position) | nil, Err:
-- Decoder.interleaved(dec, spec) psx / adx / dsp frames (or s16 / s8 PCM), channels interleaved every
-- spec.interleave bytes (VAG, ADX, BRSTM / BCSTM / BFSTM, raw PS-ADPCM)
-- Decoder.nibbles(dec, spec) an IMA nibble stream, channels interleaved by nibble (raw IMA, KVAG)
-- Decoder.blocks(dec, spec) self-contained blocks: "ms" / "ima_wav" (blockAlign bytes), "ima_qt" (34 bytes
-- per channel), raw or inside AIFF-C / CAF
--
-- Never throws (decode failures end the stream and land in dec.error, see codecs/audio/Stream).
-- codecs/audio/Adpcm/Decoder: the streaming Types.Decoder over packetised ADPCM (ADX, VAG, BRSTM, raw IMA) with exact seeking.
-- New in rosetta.
local Err = require("@rosetta/core/Err")
local Stream = require("@rosetta/codecs/audio/Stream")
local Adpcm = require("@rosetta/codecs/audio/Adpcm")
@@ -58,7 +38,6 @@ function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?)
if snaps[i] then
buffer.copy(st, 0, snaps[i])
elseif restore and restore(i) then
-- the format set the state (BRSTM's seek table)
else
local j = i - 1
while j > 1 and not snaps[j] do
@@ -95,11 +74,9 @@ function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?)
})
end
-- ------------------------------------------------------------------------------------------------ layouts
local FRAME: { [string]: number } = { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame
local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame
-- PCM samples of one channel into every ds-th float of dst from float d
local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, d: number, ds: number)
if kind == "s8" then
for k = 0, n - 1 do
@@ -118,22 +95,21 @@ local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer,
end
export type InterleavedSpec = {
kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", -- ADPCM frames, or PCM samples laid out the same way
kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8",
buf: buffer,
offset: number, -- the first row
size: number, -- data bytes (rows past it are cut; a truncated file decodes its whole frames)
interleave: number, -- bytes per channel per row (a multiple of the frame size; mono: any multiple)
offset: number,
size: number,
interleave: number,
lastInterleave: number?, -- bytes per channel in the last row (BRSTM's padded last block), default interleave
frames: number?, -- frames to output (default: what the data holds)
c1: number?, -- adx: the predictor (Adpcm.adxCoefs)
frames: number?,
c1: number?,
c2: number?,
v3: boolean?, -- adx: version 3 rounding
v3: boolean?,
coefs: buffer?, -- dsp: 16 i32 per channel
hist: { number }?, -- initial history, h1 / h2 per channel (default 0)
hist: { number }?,
restore: ((row: number, st: buffer) -> boolean)?, -- the exact history at the start of a row (BRSTM ADPC)
}
-- interleaved(dec, spec) -> Decoder | nil, Err
function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?)
local ch = dec.channels
local kind = spec.kind
@@ -145,9 +121,8 @@ function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?)
end
local buf, base, size = spec.buf, spec.offset, spec.size
local rowBytes = il * ch
-- rows: the full ones, then the last (which may be shorter, and may be cut by a truncated file)
local rows = math.max(1, math.ceil(size / rowBytes))
local function rowFrames(r: number): number -- the frames row r (0-based) holds whole in every channel
local function rowFrames(r: number): number
local width = if r == rows - 1 then last else il
-- channel c sits at c * width in the row: the last channel is the one a cut file shortens
local per = math.clamp(size - r * rowBytes - (ch - 1) * width, 0, width)
@@ -211,12 +186,12 @@ end
export type NibbleSpec = {
buf: buffer,
offset: number,
size: number, -- bytes
size: number,
hi: boolean?, -- the high nibble first (DVI / KVAG); default low first
frames: number?, -- default: every whole frame of nibbles
frames: number?,
}
-- nibbles(dec, spec): an IMA stream starting from predictor 0, step index 0, channel c in nibbles c, c + ch, ...
-- IMA from predictor 0, step index 0; channel c in nibbles c, c + ch, ...
function Decoder.nibbles(dec: any, spec: NibbleSpec): (any, Err.Err?)
local ch = dec.channels
local buf, base = spec.buf, spec.offset
@@ -246,12 +221,11 @@ export type BlockSpec = {
buf: buffer,
offset: number,
size: number,
blockAlign: number?, -- ms / ima_wav: bytes per block
frames: number?, -- default: what the blocks hold
blockAlign: number?,
frames: number?,
coefs: { number }?, -- ms: coefficient pairs, flat (default the 7 standard pairs)
}
-- blockFrames(kind, blockAlign, ch) -> frames per block, or nil when the block cannot hold the headers
function Decoder.blockFrames(kind: string, ba: number, ch: number): number?
if kind == "ima_qt" then
return 64
@@ -261,7 +235,6 @@ function Decoder.blockFrames(kind: string, ba: number, ch: number): number?
return if ba >= 4 * ch then (ba - 4 * ch) * 2 // ch + 1 else nil
end
-- blocks(dec, spec): self-contained ADPCM blocks (no state across blocks); a truncated last block decodes what it has
function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?)
local ch = dec.channels
local kind = spec.kind
@@ -278,7 +251,6 @@ function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?)
local rest = size - full * ba
local total = full * spb
if kind ~= "ima_qt" and rest > 0 then
-- a partial last block: the frames it holds whole
if kind == "ms" then
total += if rest >= 7 * ch then math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) else 0
elseif rest >= 4 * ch then
+23 -89
View File
@@ -1,31 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in rosetta; the IMA and
-- MS block decoders moved here from audio/wav/Codecs (wav-luau, same author). ADX coefficients, PS-ADPCM and Nintendo
-- DSP decoding follow vgmstream r2117 (ISC licence, licenses/vgmstream-LICENSE.txt) so the output is bit-exact with it:
-- the ADX scale + 1 and the version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024
-- rounding. Codec kernels only: the formats (wav, aiff, caf, adx, vag, brstm, adpcm, ...) walk the layouts.
--
-- Decoders write f32 (sample / 32768) to dst at float index d, every ds floats (interleaving), and keep their running
-- state in a caller-owned buffer `st` at byte offset `so` (i32 pairs: IMA pred / step index, the others hist1 / hist2),
-- so a decoder can stop between calls and snapshot the state for seeking (codecs/audio/Adpcm/Decoder).
--
-- Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) -- IMA nibbles: count samples, nibble q0, q0+qs, ...
-- Adpcm.imaQt(src, p, st, so, dst, d, ds) -- Apple ima4: one 34-byte packet -> 64 samples
-- Adpcm.imaWav(src, off, avail, ch, spb, dst, d) -> frames -- Microsoft IMA block (WAV / AVI)
-- Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, st) -> frames -- MS ADPCM block
-- Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) -- CRI ADX: 18-byte frames, 32 samples
-- Adpcm.adxCoefs(cutoff, rate) -> c1, c2
-- Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) -- Sony PS-ADPCM (VAG): 16-byte frames, 28 samples
-- Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) -- Nintendo DSP: 8-byte frames, 14 samples
-- Adpcm.modplug(src, p, count, dst, d) -- ModPlug ADPCM (XM / MOD samples)
-- Adpcm.swfFrames(src, p, n, ch) -> frames -- Flash (SWF / FLV) ADPCM: one packet's length
-- Adpcm.swf(src, p, n, ch, dst, d) -> frames -- Flash ADPCM: one packet of n bytes
-- encoders: imaEncode, imaWavEncode, msEncode, adxEncode, psxEncode, dspEncode (see each)
--
-- Every function reads only the bytes its arguments describe: the caller checks the ranges (byte counts per call are
-- documented on each). Never throws.
-- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap).
-- ADX, PS-ADPCM and Nintendo DSP decoding follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt) bit-exactly: the
-- ADX scale + 1 and version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024 rounding.
local readu8, readi16, readu16, readi32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readi32
local writef32, readf32, writei32, writeu8, writeu16 = buffer.writef32, buffer.readf32, buffer.writei32, buffer.writeu8, buffer.writeu16
local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift
@@ -33,7 +11,6 @@ local floor = math.floor
local Adpcm = {}
-- ------------------------------------------------------------------------------------------------ IMA
local IMA_STEP = {
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060,
@@ -67,9 +44,7 @@ for i = 0, 88 do
end
Adpcm.IMA_STEP = IMA_STEP
-- ima: `count` samples of one channel from a nibble stream at byte p: nibble q0, q0 + qs, q0 + 2 qs, ... (nibble q is
-- in byte p + q // 2, the low half first unless hi). State: st[so] predictor, st[so + 4] step index. Reads bytes
-- p .. p + (q0 + (count - 1) * qs) // 2.
-- IMA nibble q is in byte p + q // 2, the low half first unless hi
function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number, hi: boolean, st: buffer, so: number,
dst: buffer, d: number, ds: number)
local pred = readi32(st, so)
@@ -106,10 +81,8 @@ function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number
writei32(st, so + 4, index)
end
-- imaQt: one Apple ima4 packet (34 bytes at p: a big-endian header, the predictor's top 9 bits and the 7-bit step
-- index, then 64 nibbles low first) -> 64 samples. Apple's decoders keep the running full-precision predictor while
-- the header agrees with it (the same step index, the predictor within 127): st carries it from packet to packet
-- (zeros before the first).
-- Apple ima4: 34 bytes: a big-endian header (the predictor's top 9 bits, 7-bit step index), 64 nibbles low first;
-- Apple's decoders keep the full-precision predictor while the header agrees (same step index, within 127)
function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer, d: number, ds: number)
local h = readu8(src, p) * 256 + readu8(src, p + 1)
local pred = band(h, 0xFF80)
@@ -124,10 +97,8 @@ function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer
Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds)
end
-- imaWav: one Microsoft IMA ADPCM block (WAV / AVI) at src[off]: per channel a 4-byte header (s16 predictor = the
-- first sample, u8 step index, pad), then groups of 4 bytes (8 nibbles, low first) per channel in turn. avail: the
-- bytes present (a truncated last block decodes the whole groups it has). Writes interleaved frames to dst from float
-- index d; returns the frame count (<= spb).
-- Microsoft IMA block: per channel s16 predictor (= the first sample), u8 step index, pad; then 4-byte groups
-- (8 nibbles, low first) per channel in turn
function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number): number
if avail < 4 * ch then
return 0
@@ -170,15 +141,12 @@ function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb:
return frames
end
-- ------------------------------------------------------------------------------------------------ MS ADPCM
local MS_ADAPT = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 }
Adpcm.MS_COEF1 = { 256, 512, 0, 192, 240, 460, 392 }
Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 }
-- msBlock: one MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for
-- every channel in turn), then nibbles high first, channels interleaved per nibble. coefs: i32 pairs (coef1, coef2) x
-- ncoef (256 = 1.0). state: 20 * ch bytes of scratch. avail: the bytes present. Writes interleaved frames to dst from
-- float index d; returns the frame count (<= spb).
-- MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for every channel
-- in turn), then nibbles high first, channels interleaved per nibble; coefficients 256 = 1.0
function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number,
coefs: buffer, ncoef: number, state: buffer): number
local hdr = 7 * ch
@@ -233,15 +201,14 @@ function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb:
return frames
end
-- ------------------------------------------------------------------------------------------------ CRI ADX
local F32 = buffer.create(4)
local function f32(x: number): number
writef32(F32, 0, x)
return readf32(F32, 0)
end
-- adxCoefs(cutoff, rate) -> coef1, coef2 (fixed point, 12 fractional bits): the 2-pole high-pass predictor from the
-- header's cutoff frequency, in single precision as CRI's decoders (and vgmstream) compute it
-- coef1, coef2 (12 fractional bits): the 2-pole high-pass predictor from the header's cutoff, in single precision as
-- CRI's decoders (and vgmstream) compute it
function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number)
if rate <= 0 then
return 0, 0
@@ -257,9 +224,8 @@ function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number)
return c1, c2
end
-- adx: nframes 18-byte frames of one channel (s16 big-endian scale, 32 nibbles high first), pstride bytes apart from
-- p. v3: the version 3 rounding (each product shifted on its own). A scale of 0x8001 (CRI's end marker) decodes as
-- silence. Reads p .. p + (nframes - 1) * pstride + 17; writes 32 * nframes samples.
-- ADX frame: s16 big-endian scale, 32 nibbles high first. v3 shifts each product on its own; scale 0x8001 (CRI's end
-- marker) decodes as silence
function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: number, c2: number, v3: boolean,
st: buffer, so: number, dst: buffer, d: number, ds: number)
local h1, h2 = readi32(st, so), readi32(st, so + 4)
@@ -302,7 +268,6 @@ function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1:
writei32(st, so + 4, h2)
end
-- ------------------------------------------------------------------------------------------------ PS-ADPCM
local PSX1 = { 0, 60, 115, 98, 122 }
local PSX2 = { 0, 0, -52, -55, -60 }
@@ -317,9 +282,8 @@ local function psxPred(f: number, h1: number, h2: number): number
return if v >= 0 then floor(v) else -floor(-v)
end
-- psx: nframes 16-byte frames of one channel (filter << 4 | shift, flags, 28 nibbles low first), pstride bytes apart
-- from p. Filters past 4 decode as 0 and shifts past 12 as 9 (as vgmstream); a frame with flags 7 is silence. The
-- history keeps the unclipped value. Reads p .. p + (nframes - 1) * pstride + 15; writes 28 * nframes samples.
-- PS-ADPCM frame: filter << 4 | shift, flags, 28 nibbles low first. Filters past 4 decode as 0 and shifts past 12 as 9
-- (as vgmstream); flags 7 is silence; the history keeps the unclipped value
function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: buffer, so: number, dst: buffer,
d: number, ds: number)
local h1, h2 = readi32(st, so), readi32(st, so + 4)
@@ -364,10 +328,8 @@ function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st:
writei32(st, so + 4, h2)
end
-- ------------------------------------------------------------------------------------------------ Nintendo DSP
-- dsp: count samples of one channel from 8-byte frames at p (predictor << 4 | scale shift, 14 nibbles high first).
-- coefs: 16 i32 at byte co (8 pairs, 11 fractional bits); a predictor index past 7 uses pair 7. Reads p ..
-- p + ceil(count / 14) * 8 - 1.
-- DSP frame: predictor << 4 | scale shift, 14 nibbles high first; coefs 8 pairs, 11 fractional bits; a predictor
-- index past 7 uses pair 7
function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: number, st: buffer, so: number,
dst: buffer, d: number, ds: number)
local h1, h2 = readi32(st, so), readi32(st, so + 4)
@@ -405,8 +367,6 @@ function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: num
writei32(st, so + 4, h2)
end
-- ------------------------------------------------------------------------------------------------ encoders
-- the nearest s16 to x * 32768 (NaN -> 0)
local function toS16(x: number): number
local v = floor(x * 32768 + 0.5)
if v ~= v then
@@ -420,7 +380,6 @@ local function toS16(x: number): number
end
Adpcm.toS16 = toS16
-- the IMA nibble for x from (pred, index): the one whose decoded value lands nearest (greedy, all 16 tried)
local function imaNibble(x: number, pred: number, index: number): number
local base = index * 8 + 1
local best, bestErr = 0, math.huge
@@ -440,9 +399,6 @@ local function imaNibble(x: number, pred: number, index: number): number
return best
end
-- imaEncode: count samples of one channel, f32 at float index xi every xs floats of x, into nibbles q0, q0 + qs, ...
-- of out at byte p (the other half of each byte is kept). State as Adpcm.ima. Writes bytes p ..
-- p + (q0 + (count - 1) * qs) // 2.
function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer,
p: number, q0: number, qs: number, hi: boolean)
local pred = readi32(st, so)
@@ -468,9 +424,7 @@ function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: b
writei32(st, so + 4, index)
end
-- imaWavEncode: one Microsoft IMA block of spb frames (spb = 1 + 8k) from interleaved f32 x at frame xf (frames
-- available: n; the rest is padded with the last sample) to out[off] (4 * ch + (spb - 1) / 2 * ch bytes). st: 8 * ch
-- bytes carrying the step index from block to block.
-- Microsoft IMA block: spb = 1 + 8k frames, 4 * ch + (spb - 1) / 2 * ch bytes
function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: number, st: buffer, out: buffer, off: number)
local groups = (spb - 1) // 8
for c = 0, ch - 1 do
@@ -504,8 +458,6 @@ function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: n
end
end
-- one MS ADPCM channel run for the encoder: the nibbles for samples 2 .. n - 1 with predictor (c1, c2) and the first
-- delta; returns the squared error and the nibbles in nibs (when given)
local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0: number, nibs: { number }?): number
local s1, s2 = xs[2], xs[1]
local idelta = delta0
@@ -528,9 +480,7 @@ local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0
return err
end
-- msEncode: one MS ADPCM block of spb frames (standard 7 coefficient pairs) from interleaved f32 x at frame xf
-- (frames available: n; the rest is padded with silence) to out[off] (7 * ch + (spb - 2) * ch / 2 bytes). Each channel
-- takes the predictor with the least error.
-- MS ADPCM block (standard 7 coefficient pairs): 7 * ch + (spb - 2) * ch / 2 bytes
function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: number, out: buffer, off: number)
local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2
local xs = table.create(spb, 0)
@@ -540,7 +490,6 @@ function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: numbe
for i = 1, spb do
xs[i] = if i <= n then toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) else 0
end
-- the first delta from the first steps
local sum = 0
for i = 3, math.min(spb, 10) do
sum += math.abs(xs[i] - xs[i - 1])
@@ -568,8 +517,6 @@ function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: numbe
end
end
-- one ADX frame for the encoder: the squared error of encoding xs[1..32] with scale from (h1, h2) (v4 rounding), and
-- the nibbles in nibs when given; returns the error and the new history
local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h1: number, h2: number, nibs: { number }?): (number, number, number)
local err = 0
for k = 1, 32 do
@@ -588,9 +535,8 @@ local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h
return err, h1, h2
end
-- adxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 32) ADX frames
-- ADX v4 rounding; the scale is stored minus one as CRI's decoders add it back
-- (v4 rounding, the scale stored minus one as CRI's decoders add it back) at out[p], pstride bytes apart; the frame
-- past count is padded with silence. State as Adpcm.adx.
function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: number, c2: number, st: buffer, so: number,
out: buffer, p: number, pstride: number)
local h1, h2 = readi32(st, so), readi32(st, so + 4)
@@ -607,7 +553,6 @@ function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: n
b = a
a = s
end
-- the scale that covers the open-loop residual peak, and a few around it, closed loop
local base = math.max(1, (peak + 6) // 7)
local best, bestErr = base, math.huge
for _, m in { 1, 0.75, 1.25, 0.5, 1.6 } do
@@ -630,9 +575,6 @@ function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: n
writei32(st, so + 4, h2)
end
-- psxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 28) PS-ADPCM
-- frames at out[p], pstride bytes apart, flags byte 0 (the caller sets loop / end flags); every filter and shift is
-- tried per frame against Adpcm.psx's decoding, the least squared error wins. State as Adpcm.psx.
function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer,
p: number, pstride: number)
local h1, h2 = readi32(st, so), readi32(st, so + 4)
@@ -667,7 +609,6 @@ function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: b
end
end
end
-- the winner again, for its nibbles and history
local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15)
local mul = 2 ^ (20 - shift)
for k = 1, 28 do
@@ -688,10 +629,8 @@ function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: b
writei32(st, so + 4, h2)
end
-- ------------------------------------------------------------------------------------------------ ModPlug
-- modplug: ModPlug / OpenMPT ADPCM samples (XM / MOD sample data marked 0xAD): a table of 16 signed byte deltas at
-- p, then count nibbles (low first) at p + 16, each adding its table delta to a running signed byte (wrapping).
-- Writes count f32 (value / 128) to dst from float index d. Reads p .. p + 16 + ceil(count / 2) - 1.
-- ModPlug / OpenMPT ADPCM (sample data marked 0xAD): 16 signed byte deltas, then nibbles low first, each adding its
-- delta to a wrapping signed byte; value / 128
function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: number)
local tab = table.create(16, 0)
for k = 0, 15 do
@@ -706,7 +645,6 @@ function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: nu
end
end
-- ------------------------------------------------------------------------------------------------ Flash ADPCM
-- The SWF / FLV ADPCM (SoundFormat 1, Adobe's SWF specification, "ADPCM compression"): an MSB-first bit stream of
-- 2 bits (code size - 2), then blocks of 4096 frames: per channel a signed 16-bit first sample and a 6-bit step
-- index, then 4095 frames of `bits`-bit codes, channels interleaved. A code is IMA generalised to 2..5 bits: sign in
@@ -719,7 +657,6 @@ local SWF_INDEX: { { number } } = {
{ -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 },
}
-- swfFrames: the frame count of one Flash ADPCM packet (n bytes at p, n >= 1)
function Adpcm.swfFrames(src: buffer, p: number, n: number, ch: number): number
if n < 1 or ch < 1 then
return 0
@@ -737,7 +674,6 @@ function Adpcm.swfFrames(src: buffer, p: number, n: number, ch: number): number
return frames
end
-- the k-bit (k <= 16) MSB-first value at bit position pos of src[p ..]; bytes at or past e read as 0
local function msb(src: buffer, p: number, e: number, pos: number, k: number): number
local q = p + rshift(pos, 3)
local v = readu8(src, q) * 65536
@@ -750,8 +686,6 @@ local function msb(src: buffer, p: number, e: number, pos: number, k: number): n
return band(rshift(v, 24 - band(pos, 7) - k), lshift(1, k) - 1)
end
-- swf: one Flash ADPCM packet (n bytes at p, ch channels) -> interleaved f32 frames to dst from float index d; returns
-- the frame count (Adpcm.swfFrames). Reads p .. p + n - 1 only.
function Adpcm.swf(src: buffer, p: number, n: number, ch: number, dst: buffer, d: number): number
local frames = Adpcm.swfFrames(src, p, n, ch)
if frames == 0 then
+5 -15
View File
@@ -1,10 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice
-- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes,
-- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple
-- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message.
-- codecs/audio/Alac/Decode: the ALAC frame decoder (SCE / CPE / LFE / DSE / FIL / END elements).
-- Written from the ALAC format as published by Apple (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code).
local readu32, readu8 = buffer.readu32, buffer.readu8
local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot
local floor = math.floor
@@ -20,10 +18,10 @@ export type State = {
channels: number,
maxRun: number,
scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked)
pred: { { number } }, -- per element channel (0, 1): residuals / predictor output
pred: { { number } },
mix: { { number } },
shift: { number },
out: { number }, -- interleaved output samples (integers), frames * channels
out: { number },
}
local POW = table.create(64, 0)
@@ -31,7 +29,6 @@ for i = 0, 63 do
POW[i + 1] = 2 ^ i
end
-- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25.
local function bitsAt(b: buffer, pos: number, n: number): number
local w = byteswap(readu32(b, rshift(pos, 3)))
return rshift(lshift(w, band(pos, 7)), 32 - n)
@@ -72,7 +69,6 @@ local function scalar(b: buffer, pos: number, k: number, m: number, bps: number)
return x, pos + k - 1
end
-- residuals: n values into out[1..n]; returns the new bit position or -1
local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number
local history = st.mb
local kb = st.kb
@@ -126,7 +122,6 @@ local function rice(b: buffer, pos: number, limit: number, out: { number }, n: n
return pos
end
-- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place
local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number)
out[1] = err[1]
if n <= 1 then
@@ -180,8 +175,6 @@ local function predict(err: { number }, out: { number }, n: number, bps: number,
end
end
-- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the
-- ALAC element order.
function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?)
if len <= 0 then
return nil, "empty packet"
@@ -196,7 +189,7 @@ function Decode.frame(st: State, buf: buffer, off: number, len: number): (number
local limit = len * 8
local pos = 0
local channels = st.channels
local ch = 0 -- next output channel
local ch = 0
local frames = -1
local out = st.out
while true do
@@ -331,7 +324,6 @@ function Decode.frame(st: State, buf: buffer, off: number, len: number): (number
end
shift = 0
end
-- unmix + shifted bytes -> interleaved output
local sm = POW[shift + 1]
if nch == 2 then
local den = POW[mixBits + 1]
@@ -394,7 +386,6 @@ function Decode.frame(st: State, buf: buffer, off: number, len: number): (number
return 0, nil
end
if ch < channels then
-- missing channels: silence
for i = 1, frames do
for c = ch + 1, channels do
out[(i - 1) * channels + c] = 0
@@ -404,7 +395,6 @@ function Decode.frame(st: State, buf: buffer, off: number, len: number): (number
return frames, nil
end
-- the scratch state for a configuration
function Decode.state(cfg: any): State
local n = cfg.frameLength
return {
+5 -22
View File
@@ -1,11 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of
-- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation,
-- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the
-- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit
-- input. Written for this library from the ALAC format; no third-party code. Never throws.
-- codecs/audio/Alac/Encode: an ALAC frame encoder (mixBits 2, LPC orders 4 / 8 with denShift 9, escape frames).
-- Written from the ALAC format; no third-party code.
local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz
local readu8, writeu8 = buffer.readu8, buffer.writeu8
local floor, abs = math.floor, math.abs
@@ -27,16 +24,15 @@ export type State = {
mb: number,
kb: number,
channels: number,
out: buffer, -- packet scratch
pos: number, -- bit position in out
cap: number, -- bits available
out: buffer,
pos: number,
cap: number,
u: { number },
v: { number },
err: { number },
work: { number },
}
-- ------------------------------------------------------------------------------------------------ bit writer
local function put(st: State, v: number, n: number)
local pos = st.pos
if pos + n > st.cap then
@@ -66,7 +62,6 @@ local function putBig(st: State, v: number, n: number)
end
end
-- ------------------------------------------------------------------------------------------------ rice code
local function signExtend(v: number, bits: number): number
local m = POW[bits + 1]
v = v % m
@@ -76,7 +71,6 @@ local function signExtend(v: number, bits: number): number
return v
end
-- the bits of one scalar (no writing)
local function scalarBits(x: number, k: number, m: number, bps: number): number
local pre = if k == 1 then x else floor(x / m)
if pre >= 9 then
@@ -96,7 +90,6 @@ local function scalar(st: State, x: number, k: number, m: number, bps: number)
putBig(st, x, bps)
return
end
-- pre ones and a zero
put(st, POW[pre + 2] - 2, pre + 1)
if k ~= 1 then
local r = x - pre * m
@@ -108,7 +101,6 @@ local function scalar(st: State, x: number, k: number, m: number, bps: number)
end
end
-- code the residuals e[1..n] (write = false: just count the bits)
local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number
local history = st.mb
local kb = st.kb
@@ -162,7 +154,6 @@ local function rice(st: State, e: { number }, n: number, bps: number, mult: numb
return bits
end
-- ------------------------------------------------------------------------------------------------ prediction
-- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder)
local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number)
e[1] = x[1]
@@ -201,7 +192,6 @@ local function residuals(x: { number }, e: { number }, n: number, bps: number, c
end
end
-- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised
local function lpc(x: { number }, n: number, order: number, work: { number }): { number }
local ac = table.create(order + 1, 0)
for i = 1, n do
@@ -248,7 +238,6 @@ local function lpc(x: { number }, n: number, order: number, work: { number }): {
return coefs
end
-- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits
local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number)
local mult = floor(st.pb * PB_FACTOR / 4)
local bestOrder, bestCoefs, bestBits = 0, {}, math.huge
@@ -274,9 +263,6 @@ local function analyse(st: State, x: { number }, n: number, bps: number): (numbe
return bestOrder, bestCoefs, bestBits
end
-- ------------------------------------------------------------------------------------------------ frame
-- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index
-- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts
function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer
local channels, depth = st.channels, st.bitDepth
local n = frames
@@ -299,7 +285,6 @@ function Encode.frame(st: State, samples: { number }, first: number, frames: num
local bps = depth + nch - 1
local mixRes = 0
if nch == 2 then
-- the mix with the smallest first-difference energy
local best = math.huge
for res = 0, 4 do
local cost = 0
@@ -334,7 +319,6 @@ function Encode.frame(st: State, samples: { number }, first: number, frames: num
u[i] = samples[first + (i - 1) * channels + a - 1]
end
end
-- header
put(st, if nch == 2 then 1 else 0, 3)
put(st, 0, 4)
put(st, 0, 12)
@@ -376,7 +360,6 @@ function Encode.frame(st: State, samples: { number }, first: number, frames: num
end
end
if not compressed then
-- uncompressed frame
buffer.fill(st.out, 0, 0)
st.pos = 0
ch = 1
+12 -31
View File
@@ -1,18 +1,7 @@
--!strict
-- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
-- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice
-- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 /
-- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels).
--
-- local Alac = require("@rosetta/codecs/audio/Alac")
-- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped)
-- local dec = Alac.decoder(cfg)
-- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order)
-- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 })
-- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096)
-- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled
--
-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG.
-- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder.
-- Written from the ALAC format as Apple published it; no third-party code. ALAC stores C L R ... for 3+ channels; the
-- API uses WAV order.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Decode = require("@rosetta/codecs/audio/Alac/Decode")
@@ -21,20 +10,19 @@ local Encode = require("@rosetta/codecs/audio/Alac/Encode")
local Alac = {}
export type Config = {
frameLength: number, -- samples per packet (4096)
frameLength: number,
compatibleVersion: number,
bitDepth: number,
pb: number, -- 40
mb: number, -- 10
kb: number, -- 14
pb: number,
mb: number,
kb: number,
channels: number,
maxRun: number, -- 255
maxRun: number,
maxFrameBytes: number,
avgBitRate: number,
sampleRate: number,
}
-- ALAC channel k (1-based) -> WAV channel (1-based), per channel count
local TO_WAV: { { number } } = {
{ 1 },
{ 1, 2 },
@@ -45,7 +33,6 @@ local TO_WAV: { { number } } = {
{ 3, 1, 2, 5, 6, 7, 4 },
{ 3, 7, 8, 1, 2, 5, 6, 4 },
}
-- the element layout (channels per element) the encoder writes
local ELEMENTS: { { number } } = {
{ 1 },
{ 2 },
@@ -58,7 +45,6 @@ local ELEMENTS: { { number } } = {
}
Alac.TO_WAV = TO_WAV
-- config(buf, offset?, length?) -> Config | nil, Err
function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, Err.Err?)
local r = Bytes.reader(buf, offset, length)
-- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie
@@ -104,7 +90,6 @@ function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, E
return c, nil
end
-- cookie(cfg) -> the 24-byte ALACSpecificConfig
function Alac.cookie(c: Config): buffer
local w = Bytes.writer(24)
w:u32be(c.frameLength)
@@ -121,10 +106,9 @@ function Alac.cookie(c: Config): buffer
return w:finish()
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Decoder = {
config: Config,
pcm: { number }, -- the last packet's samples, interleaved, WAV order (integers of config.bitDepth bits)
pcm: { number },
decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
state: Decode.State,
}
@@ -157,7 +141,6 @@ local function decode(self: Decoder, buf: buffer, offset: number?, length: numbe
return frames, nil
end
-- decoder(cfg) -> Decoder
function Alac.decoder(cfg: Config): Decoder
return {
config = cfg,
@@ -167,7 +150,6 @@ function Alac.decoder(cfg: Config): Decoder
}
end
-- ------------------------------------------------------------------------------------------------ encoder
export type Encoder = {
config: Config,
encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?),
@@ -200,12 +182,11 @@ end
export type EncoderOptions = {
sampleRate: number,
channels: number, -- 1 .. 8
bitDepth: number?, -- 16 (default), 20 or 24
frameLength: number?, -- default 4096
channels: number,
bitDepth: number?,
frameLength: number?,
}
-- encoder(opts) -> Encoder | nil, Err
function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?)
if type(opts) ~= "table" then
return nil, Err.new(Err.ARG, "encoder: expected options")
+10 -29
View File
@@ -1,12 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Ape/Decode: one Monkey's Audio frame -> samples. Ported from the Monkey's Audio SDK 13.28 (Matthew T.
-- Ashland, BSD 3-clause, licenses/monkeys-audio-LICENSE.txt): UnBitArray.cpp (the range coder and its value model,
-- 3.99+) and Old/UnBitArrayOld.cpp (CUnBitArray3891To3989, the 3.95 - 3.98 model), NNFilter / NNFilterCommon.h (the
-- neural-net filters of the normal .. insane levels), NewPredictor.cpp (CPredictorDecompress3950toCurrent, its int32
-- and int64 flavours), ScaledFirstOrderFilter.h, Prepare.cpp (Unprepare: X / Y -> channels), APEDecompressCore.cpp
-- (special frames, the frame CRC) and FloatTransform.cpp. Never throws: returns nil, message.
-- codecs/audio/Ape/Decode: one Monkey's Audio frame -> samples.
-- Ported from the Monkey's Audio SDK 13.28 (Matthew T. Ashland, BSD 3-clause, licenses/monkeys-audio-LICENSE.txt):
-- UnBitArray.cpp, Old/UnBitArrayOld.cpp, NNFilter.h, NewPredictor.cpp, Prepare.cpp, APEDecompressCore.cpp, FloatTransform.cpp.
local Crc32 = require("@rosetta/core/Crc32")
local readu8, readu32, writeu32, byteswap = buffer.readu8, buffer.readu32, buffer.writeu32, bit32.byteswap
@@ -62,8 +59,8 @@ export type State = {
bits: number,
channels: number,
filters: { Filter }, -- per level, applied last to first on decode (as m_spNNFilter2, 1, 0)
V: { { number } }, -- per channel: the frame's values through the stages
S: buffer, -- the frame bytes, word-swapped (+ PAD zeros)
V: { { number } },
S: buffer,
crcbuf: buffer,
scratch: buffer,
lastX: number,
@@ -78,7 +75,6 @@ local FILTERS: { [number]: { number } } = { -- level -> { order, shift, ... } in
[5000] = { 1280, 15, 256, 13, 16, 11 },
}
-- state(version, level, bits, channels) -> State | nil, message
function Decode.state(version: number, level: number, bits: number, channels: number): (State?, string?)
local spec = FILTERS[level]
if not spec then
@@ -114,7 +110,6 @@ function Decode.state(version: number, level: number, bits: number, channels: nu
}, nil
end
-- ------------------------------------------------------------------------------------------------ entropy
-- the range coder as a record (the 3.95 - 3.98 model's RangeDecodeFastWithUpdate)
type Rc = { q: number, low: number, range: number, prev: number }
local function rcBits(rc: Rc, S: buffer, nb: number): number
@@ -136,8 +131,6 @@ local function rcBits(rc: Rc, S: buffer, nb: number): number
return r
end
-- values(st, q, n, order, old) -> q | nil, message: n blocks of range-coded values into st.V[c] for the channels of
-- `order` (decode order), from byte q of st.S (the range coder starts there)
local function values(st: State, q: number, lim: number, n: number, order: { number }, old: boolean): (number?, string?)
local S = st.S
local V = st.V
@@ -298,13 +291,11 @@ local function values(st: State, q: number, lim: number, n: number, order: { num
return q, nil
end
-- ------------------------------------------------------------------------------------------------ NN filters
-- ((v >> s) & m) ~= 0 for an int64 v (s given as 2^s)
local function negBit(v: number, p2: number, m: number): boolean
return band((v // p2) % TWO32, m) ~= 0
end
-- the int16 dot product of the weights and the inputs from byte b (span bytes)
local function dot16(M: buffer, I: buffer, b: number, span: number): number
local dot = 0
for k = 0, span - 16, 16 do
@@ -332,8 +323,7 @@ local function dotAdapt16(M: buffer, I: buffer, D: buffer, b: number, span: numb
return dot
end
-- one CNNFilter over n values of v, in place (DecompressGeneric). The weights, inputs and deltas live in buffers of
-- the C types (int16 for 8 - 24-bit files, int32 for 32-bit ones: `wide`), so the weights wrap as the C shorts do
-- one CNNFilter (DecompressGeneric); weights in the C types (int16 up to 24-bit files, int32 for 32-bit) wrap as C does
local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean, wide: boolean)
local order, M, I, D = f.order, f.M, f.I, f.D
local es = if wide then 4 else 2
@@ -342,7 +332,7 @@ local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean,
buffer.fill(M, 0, 0, order * es)
buffer.fill(I, 0, 0, (order + 1) * es)
buffer.fill(D, 0, 0, (order + 1) * es)
local p = order -- the current element (0-based); its history is p - order .. p - 1
local p = order
local total = 512 + order
local avg = 0
local span = order * 2
@@ -421,7 +411,6 @@ local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean,
end
end
-- ------------------------------------------------------------------------------------------------ predictor
-- the adapt sign of a 32-bit file's int64 prediction value: ((v >> 30) & 2) - 1, or 0
local function adaptWide(v: number): number
if v == 0 then
@@ -430,8 +419,7 @@ local function adaptWide(v: number): number
return if (v // 1073741824) % 4 >= 2 then 1 else -1
end
-- predict(st, a, b?, n) : CPredictorDecompress3950toCurrent over channel a's values (nB = channel b's outputs of the
-- block, or 0), single-channel form; stereo uses predictStereo
-- CPredictorDecompress3950toCurrent, single-channel form
local function predictOne(st: State, v: { number }, n: number)
local wide = st.bits >= 32
local lastA, prevA0, A1, A2, A3 = 0, 0, 0, 0, 0
@@ -489,7 +477,6 @@ local function predictStereo(st: State, X: { number }, Y: { number }, n: number)
local xStage = 0
local lastX = 0
for t = 1, n do
-- Y
local nA = Y[t]
local A0 = yLast
yA3 = yA2
@@ -539,7 +526,6 @@ local function predictStereo(st: State, X: { number }, Y: { number }, n: number)
yStage = wrap32(cur + (yStage * 31) // 32)
yLast = cur
local yv = yStage
-- X
nA = X[t]
A0 = xLast
xA3 = xA2
@@ -592,10 +578,6 @@ local function predictStereo(st: State, X: { number }, Y: { number }, n: number)
end
end
-- ------------------------------------------------------------------------------------------------ frame
-- frame(st, buf, at, rem, stop, n, P, float) -> n | nil, message: the frame whose words start at byte `at` (its first
-- byte at at + rem), reading at most up to `stop`; n blocks into P (interleaved integers, or floats when float); cut:
-- the data ends at `stop` before the frame does (a running-over decode is then "truncated", else corrupt)
function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: number, n: number, P: { number }, float: boolean, cut: boolean): (number?, string?)
local C, bits = st.channels, st.bits
local len = math.max(0, stop - at)
@@ -636,10 +618,9 @@ function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: num
end
stored %= TWO31
end
-- the values
local V = st.V
local order: { number }
local mode -- "silence", "pseudo", "stereo", "mono", "multi"
local mode
if C == 1 then
if band(special, 1) ~= 0 then
mode = "silence"
@@ -694,7 +675,7 @@ function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: num
cb = buffer.create(n * C * bps + 1024)
st.crcbuf = cb
end
local paired: { [number]: boolean } = {} -- first channel (0-based) of an X / Y pair
local paired: { [number]: boolean } = {}
if C == 2 and mode == "stereo" then
paired[0] = true
elseif C == 4 and (bits == 16 or bits == 24) then
+7 -23
View File
@@ -1,19 +1,7 @@
--!strict
-- codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28
-- (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): APEHeader.cpp (the descriptor /
-- header / seek table, and the pre-3.98 header), APEInfo / APEDecompress.cpp (frame bytes and alignment); the frame
-- decoder is codecs/audio/Ape/Decode. Supports file versions 3.95 and later (3.99+ as the current encoder writes; the
-- 3.95 - 3.98 range coder model is ported but has no reference fixture), every compression level (fast, normal, high,
-- extra high, insane), 8 / 16 / 24 / 32-bit integer and 32-bit float, 1 - 32 channels, special frames (silence,
-- pseudo stereo) and the frame CRC. Not supported: versions before 3.95 (UNSUPPORTED), the "interim" 24-bit
-- re-decode for files of the 32-bit era before 8.50, big-endian / signed 8-bit source flags (the samples are returned
-- as numbers either way).
--
-- local info, err = Ape.info(buf, base, limit) -- header facts + the frame table
-- local dec = Ape.decoder(info)
-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved; integers, or floats)
--
-- Never throws: bad data returns nil, Err.
-- codecs/audio/Ape: the Monkey's Audio codec (.ape), file versions 3.95 and later.
-- Ported from the Monkey's Audio SDK 13.28 (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt):
-- APEHeader.cpp, APEInfo / APEDecompress.cpp. Not supported: pre-3.95 (UNSUPPORTED), the pre-8.50 "interim" 24-bit re-decode.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Decode = require("@rosetta/codecs/audio/Ape/Decode")
@@ -22,7 +10,7 @@ local Ape = {}
export type Info = {
version: number, -- file version * 1000 (3990)
programVersion: number, -- 13280 (0 when not stored)
programVersion: number,
level: number, -- 1000 (fast) .. 5000 (insane)
flags: number,
channels: number,
@@ -33,16 +21,15 @@ export type Info = {
finalFrameBlocks: number,
totalFrames: number,
totalBlocks: number,
frameStart: { number }, -- byte offset of each frame
frameStart: { number },
firstFrame: number, -- byte offset of frame 1 (the word alignment origin)
dataEnd: number, -- the end of the frame data
limit: number, -- the end of the file data (frames past it are truncated)
dataEnd: number,
limit: number,
md5: string?,
}
local FLAG_8, FLAG_24, FLAG_PEAK, FLAG_SEEKN, FLAG_WAVHDR, FLAG_FLOAT = 1, 8, 4, 16, 32, 4096
-- find(buf, base, limit) -> the offset of "MAC " / "MACF" (after an ID3v2 tag) | nil
function Ape.find(buf: buffer, base: number, limit: number): number?
local at = base
if limit - at >= 10 and buffer.readstring(buf, at, 3) == "ID3" then
@@ -70,7 +57,6 @@ function Ape.find(buf: buffer, base: number, limit: number): number?
return if k then at + k - 1 else nil
end
-- info(buf, base, limit) -> Info | nil, Err
function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?)
local at = Ape.find(buf, base, limit)
if not at then
@@ -184,7 +170,6 @@ function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?)
return info :: Info, nil
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Decoder = {
info: Info,
pcm: { number },
@@ -212,7 +197,6 @@ local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?)
return n2, nil
end
-- decoder(info) -> Decoder | nil, Err
function Ape.decoder(info: Info): (Decoder?, Err.Err?)
local st, msg = Decode.state(info.version, info.level, info.bitsPerSample, info.channels)
if not st then
+3 -18
View File
@@ -1,17 +1,7 @@
--!strict
-- codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and
-- some MP3s) -> Types.Tags. Written from the APEv2 specification (wiki.hydrogenaud.io "APEv2 specification"); no
-- third-party code. A tag sits at the end of the file (before an optional ID3v1 tag) as items + a 32-byte footer
-- "APETAGEX", with an optional 32-byte header in front (APEv2). Item keys become lower case tag keys (Year -> date,
-- Track -> track, Album Artist -> albumartist, Disc -> disc, Comment -> comment); text values holding several
-- values (NUL separated) are joined with "; "; binary items (cover art) and external links stay in info.items.
-- Never throws.
--
-- local tags, info = ApeTag.find(buf, start, limit) -- the tag ending at limit (or before an ID3v1 tag there)
-- -- tags: { title = ..., artist = ... } | nil (no tag / malformed)
-- -- info: { start = first byte (the header when present), stop = past the footer, version = 1000 | 2000,
-- -- items = { { key = "Title", value = "...", kind = "text" | "binary" | "link" } } }
-- local tags, info = ApeTag.parse(buf, footer, start) -- the tag whose footer is at byte `footer` (>= start)
-- codecs/audio/ApeTag: APEv1 / APEv2 tags -> Types.Tags.
-- From the APEv2 specification (wiki.hydrogenaud.io); no third-party code. Items + a 32-byte "APETAGEX" footer, optional
-- 32-byte header (APEv2), before an optional ID3v1 tag.
local ApeTag = {}
export type Item = { key: string, value: string, kind: string }
@@ -27,14 +17,11 @@ local TO_TAG: { [string]: string } = {
}
local KINDS = { [0] = "text", "binary", "link", "text" }
-- tagKey(itemKey) -> the Types.Tags key
function ApeTag.tagKey(key: string): string
local k = string.lower(key)
return TO_TAG[k] or k
end
-- parse(buf, footer, start?) -> tags, info | nil: the tag whose 32-byte footer starts at byte `footer`; the items
-- must lie at or after `start` (default 0)
function ApeTag.parse(buf: buffer, footer: number, start: number?): ({ [string]: string }?, Info?)
local lo = start or 0
local n = buffer.len(buf)
@@ -89,8 +76,6 @@ function ApeTag.parse(buf: buffer, footer: number, start: number?): ({ [string]:
return tags, { start = first, stop = footer + 32, version = version, items = items }
end
-- find(buf, start, limit) -> tags, info | nil: the tag at the end of [start, limit), or just before a 128-byte
-- ID3v1 tag ("TAG") there
function ApeTag.find(buf: buffer, start: number, limit: number): ({ [string]: string }?, Info?)
if limit > buffer.len(buf) then
limit = buffer.len(buf)
+11 -52
View File
@@ -1,15 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Flac/Encode: the FLAC encoder (RFC 9639). New code, written from the RFC; the presets mirror libFLAC's -0 .. -8
-- (block size 1152 / 4096, max LPC order 0 / 6 / 8 / 12, Rice partition order 3 .. 6, independent / adaptive /
-- exhaustive stereo decorrelation). Subframes: CONSTANT, VERBATIM, FIXED (order 0..4, chosen by the residual sum),
-- LPC (Levinson-Durbin on the tukey(0.5)-windowed autocorrelation, error-feedback coefficient quantization with
-- libFLAC's precision table, the order estimated from the prediction error or searched exhaustively at -8), wasted
-- bits; Rice / Rice2 partitions with the partition order and parameters searched per subframe. Frames carry CRC-8 /
-- CRC-16; STREAMINFO carries the sizes, total samples and the MD5 of the PCM; VORBIS_COMMENT from the tags; an optional
-- SEEKTABLE. Streams: input blocks are pulled from a codecs/audio/Pcm Source, so a Decoder is encoded without decoding it
-- whole. Never throws: bad options are rejected by audio/flac before calling in.
-- codecs/audio/Flac/Encode: the FLAC encoder (RFC 9639), written from the RFC.
-- The presets mirror libFLAC's -0 .. -8; QLP precision follows libFLAC's table.
local Bits = require("@rosetta/core/Bits")
local Md5 = require("@rosetta/core/Md5")
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
@@ -25,8 +18,6 @@ for i = 0, 63 do
POW[i + 1] = 2 ^ i
end
-- ------------------------------------------------------------------------------------------------ CRCs
-- (the decoder's tables: codecs/audio/Flac/Frame; (b, offset, count) here)
local function crc8(b: buffer, o: number, n: number): number
return Frame.crc8(b, o, o + n)
end
@@ -35,7 +26,6 @@ local function crc16(b: buffer, o: number, n: number): number
end
Encode.crc8, Encode.crc16 = crc8, crc16
-- ------------------------------------------------------------------------------------------------ bit writer (MSB first)
type W = Bits.RawWriter
local function ensure(w: W, n: number)
@@ -74,12 +64,11 @@ local function putUtf8(w: W, v: number)
end
end
-- ------------------------------------------------------------------------------------------------ presets
export type Config = {
blockSize: number,
maxLpcOrder: number,
maxPartitionOrder: number,
stereo: string, -- "independent" | "adaptive" | "exhaustive"
stereo: string,
exhaustiveOrder: boolean,
}
local PRESETS: { Config } = {
@@ -95,22 +84,20 @@ local PRESETS: { Config } = {
}
Encode.PRESETS = PRESETS
-- ------------------------------------------------------------------------------------------------ analysis
-- a subframe plan for one channel signal
type Plan = {
kind: number, -- 0 constant, 1 verbatim, 2 fixed, 3 lpc
bits: number, -- estimated size in bits (with the subframe header)
kind: number,
bits: number,
order: number,
wasted: number,
bps: number, -- sample size after removing wasted bits
res: { number }, -- residual (fixed / lpc), indices 1..n
bps: number,
res: { number },
porder: number,
params: { number },
method: number, -- 0 Rice (4-bit params), 1 Rice2 (5-bit)
qlp: { number },
shift: number,
precision: number,
x: { number }, -- the (shifted) samples
x: { number },
}
local function newPlan(n: number): Plan
@@ -131,7 +118,6 @@ local function newPlan(n: number): Plan
}
end
-- scratch per encoder
type Scratch = {
sums: { number },
counts: { number },
@@ -147,9 +133,7 @@ type Scratch = {
qlp: { number },
}
-- rice(res, n, order, maxP, plan?) -> bits, porder, method (fills scratch.bestKs with the parameters)
local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP: number): (number, number, number)
-- the finest usable partition order
local p = maxP
while p > 0 and (n % POW[p + 1] ~= 0 or n // POW[p + 1] <= order) do
p -= 1
@@ -157,7 +141,6 @@ local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP
local sums, counts = sc.sums, sc.counts
local parts = POW[p + 1]
local ps = n // parts
-- sums of zig-zag values at the finest order
for j = 0, parts - 1 do
local s = 0
local a = if j == 0 then order + 1 else j * ps + 1
@@ -206,7 +189,6 @@ local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP
if q == 0 then
break
end
-- merge pairs into the next coarser order
for j = 1, np // 2 do
sums[j] = sums[2 * j - 1] + sums[2 * j]
counts[j] = counts[2 * j - 1] + counts[2 * j]
@@ -224,7 +206,6 @@ local function keepRice(sc: Scratch, plan: Plan, porder: number, method: number)
end
end
-- fixed predictor residuals
local function fixedResidual(x: { number }, n: number, order: number, res: { number })
for i = 1, order do
res[i] = 0
@@ -310,7 +291,6 @@ local function qlpPrecision(bps: number, n: number): number
return 13
end
-- quantize coefficients lp[1..order] to precision bits: qlp[1..order], shift | nil
local function quantize(lp: { number }, order: number, precision: number, qlp: { number }): number?
local cmax = 0
for i = 1, order do
@@ -372,7 +352,6 @@ local function lpcResidual(x: { number }, n: number, order: number, qlp: { numbe
end
end
-- Levinson-Durbin: sc.lpc[o][1..o] and sc.err[o] for o = 1 .. maxOrder; returns the highest usable order
local function levinson(sc: Scratch, maxOrder: number): number
local r = sc.autoc
local e = r[1]
@@ -407,10 +386,8 @@ local function levinson(sc: Scratch, maxOrder: number): number
return maxOrder
end
-- choose the subframe for signal x (n samples, bps bits) into plan (reusing its arrays)
local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps: number, plan: Plan)
local x = plan.x
-- constant?
local first = src[1]
local constant = true
for i = 1, n do
@@ -424,7 +401,6 @@ local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps
plan.res[1] = first
return
end
-- wasted bits: the common trailing zeros
local wasted = 0
do
local w = 0
@@ -451,9 +427,7 @@ local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps
local b = bps - wasted
local hdr = 8 + wasted
plan.wasted, plan.bps = wasted, b
-- verbatim
plan.kind, plan.bits = 1, hdr + n * b
-- fixed
local fo = bestFixedOrder(x, n)
if n > fo then
local tmp = sc.tmpRes
@@ -466,10 +440,8 @@ local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps
keepRice(sc, plan, po, me)
end
end
-- lpc
local maxOrder = math.min(cfg.maxLpcOrder, n - 1, 32)
if maxOrder > 0 then
-- windowed autocorrelation
local win = sc.win
if sc.winN ~= n then
-- tukey(0.5)
@@ -542,7 +514,6 @@ local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps
end
end
-- ------------------------------------------------------------------------------------------------ writing
local function writeResidual(w: W, plan: Plan, n: number)
local method = plan.method
put(w, method, 2)
@@ -649,7 +620,6 @@ local function blockCode(n: number): (number, number) -- code, extra bits (0, 8,
return 7, 16
end
-- ------------------------------------------------------------------------------------------------ encoder
export type Source = {
sampleRate: number,
channels: number,
@@ -662,18 +632,16 @@ export type Options = {
level: number,
bits: number,
blockSize: number?,
seekInterval: number, -- seconds between seek points (0 = no SEEKTABLE)
padding: number, -- bytes of PADDING
seekInterval: number,
padding: number,
vendor: string,
}
-- encode(src, opts) -> buffer | nil, message
function Encode.encode(src: Source, opts: Options): (buffer?, string?)
local cfg = PRESETS[opts.level + 1]
local ch, rate, bps = src.channels, src.sampleRate, opts.bits
local bs = opts.blockSize or cfg.blockSize
local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 }
-- metadata
put(w, 0x664C6143, 32) -- "fLaC"
put(w, 0, 1)
put(w, 0, 7)
@@ -682,7 +650,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
for _ = 1, 34 do
put(w, 0, 8)
end
-- seek table placeholders (when the length is known)
local seekPoints = 0
local seekAt = 0
local interval = floor(opts.seekInterval * rate)
@@ -692,14 +659,12 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
seekPoints = 0
end
end
-- vorbis comment
local comments = VorbisComment.fields(src.tags)
local vendor = opts.vendor
local vcLen = 4 + #vendor + 4
for _, c in comments do
vcLen += 4 + #c
end
-- SEEKTABLE
if seekPoints > 0 then
put(w, 0, 1)
put(w, 3, 7)
@@ -747,7 +712,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
end
end
local audioStart = w.pos
-- frames
local md5 = Md5.new()
local mbytes = (bps + 7) // 8
local mbuf = buffer.create(bs * ch * mbytes)
@@ -794,7 +758,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
local tmp: buffer? = nil
local pendingBuf: buffer? = nil
local pendingN, pendingOff = 0, 0
-- read exactly bs frames (fewer only at the end)
local function readBlock(): (buffer?, number)
local out = buffer.create(bs * ch * 4)
local got = 0
@@ -841,7 +804,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
end
end
md5:update(mbuf, 0, mo)
-- channel decorrelation
local assign = ch - 1
local chosen: { Plan } = {}
if ch == 2 and cfg.stereo ~= "independent" then
@@ -900,14 +862,12 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
chosen[c] = plans[4 + c]
end
end
-- the frame
local need = n * ch * 4 + 64
for _, p in chosen do
need += (p.bits // 8) + 8
end
ensure(w, need)
local start = w.pos
-- seek points: the first frame at or after each multiple of the interval
while seekIdx < seekPoints and total >= seekNext do
local at = seekAt + seekIdx * 18
local sn, off = total, start - audioStart
@@ -957,7 +917,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
if src.err then
return nil, tostring(src.err)
end
-- unused seek points stay placeholders; STREAMINFO
local out = buffer.create(w.pos)
buffer.copy(out, 0, w.buf, 0, w.pos)
local si = Encode.streaminfo(bs, if frameNo > 0 then minFrame else 0, maxFrame, rate, ch, bps, total, md5:digest())
@@ -965,7 +924,7 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
return out, nil
end
-- streaminfo(...) -> the 34-byte STREAMINFO body
-- STREAMINFO: 34 bytes
function Encode.streaminfo(bs: number, minFrame: number, maxFrame: number, rate: number, ch: number, bps: number, total: number, md5: string): buffer
local w: W = { buf = buffer.create(64), pos = 0, acc = 0, cnt = 0 }
put(w, bs, 16)
+5 -20
View File
@@ -1,13 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Flac/Frame: FLAC frames: header parsing (CRC-8), the sync search, subframes (constant, verbatim, fixed, LPC, wasted bits),
-- residuals (Rice / Rice2 partitions, escapes), stereo decorrelation and the CRC-16 check.
--
-- The input buffer must have at least PAD zero bytes after the data end (`len`): the bit reader reads 32-bit
-- words without bounds checks and instead compares its position with the data end once per sample. Nothing here
-- throws: bad data gives nil, err.
-- Absorbed from flac-luau 7083d0d (same author, no third-party code).
-- codecs/audio/Flac/Frame: FLAC frames: header (CRC-8), sync search, subframes, residuals, decorrelation, CRC-16.
-- Absorbed from flac-luau 7083d0d (no third-party code). The input needs PAD zero bytes after `len`: the bit reader
-- reads 32-bit words unchecked and compares its position with the data end once per sample.
local readu8, readu32 = buffer.readu8, buffer.readu32
local band, bxor, lshift, rshift, countlz, byteswap = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift,
bit32.countlz, bit32.byteswap
@@ -62,7 +58,7 @@ local RATE = { [1] = 88200, [2] = 176400, [3] = 192000, [4] = 8000, [5] = 16000,
local BITS = { [1] = 8, [2] = 12, [4] = 16, [5] = 20, [6] = 24, [7] = 32 }
export type Header = {
offset: number, -- byte offset of the sync code
offset: number,
size: number, -- header bytes, CRC-8 included
blockSize: number,
sampleRate: number,
@@ -73,8 +69,6 @@ export type Header = {
number: number,
}
-- Parse the frame header at pos (data ends at len; the buffer is padded). si gives the STREAMINFO defaults
-- (sampleRate, bitsPerSample) for the "from STREAMINFO" codes. Returns nil when it is not a valid header.
function Frame.header(b: buffer, pos: number, len: number, si: any): Header?
if pos < 0 or pos + 6 > len then
return nil
@@ -155,7 +149,6 @@ function Frame.header(b: buffer, pos: number, len: number, si: any): Header?
if not bs or not bps or bps < 4 or bps > 32 or p + 1 > len then
return nil
end
-- CRC-8 over the header
if crc8(b, pos, p) ~= readu8(b, p) then
return nil
end
@@ -172,7 +165,6 @@ function Frame.header(b: buffer, pos: number, len: number, si: any): Header?
}
end
-- The first valid header at an offset in [pos, limit)
function Frame.find(b: buffer, pos: number, limit: number, len: number, si: any): Header?
local lim = math.min(limit, len - 6)
if pos < 0 then
@@ -193,7 +185,6 @@ function Frame.find(b: buffer, pos: number, limit: number, len: number, si: any)
return nil
end
-- Bit reading for the header parts of subframes: n <= 32 bits at bit position p (unsigned)
local function bits(b: buffer, p: number, n: number): number
if n == 0 then
return 0
@@ -213,7 +204,6 @@ local function sbits(b: buffer, p: number, n: number): number
return v
end
-- Residual coding: fills s[order + 1 .. n] with residuals. Returns the new bit position, or -1.
local function residual(b: buffer, p: number, lim: number, s: { number }, n: number, order: number): number
local method = bits(b, p, 2)
if method > 1 then
@@ -258,7 +248,6 @@ local function residual(b: buffer, p: number, lim: number, s: { number }, n: num
end
end
elseif k <= 24 then
-- the hot loop: unary quotient + k-bit remainder, zigzag
local pk = POW2[k + 1]
local rk = 32 - k
for j = i, stop do
@@ -280,7 +269,6 @@ local function residual(b: buffer, p: number, lim: number, s: { number }, n: num
p += k
end
else
-- a long run of zeros
q = 32 - sh
p += q
while true do
@@ -448,7 +436,6 @@ local function lpc(s: { number }, n: number, cf: { number }, order: number, shif
end
end
-- One subframe into s[1..n]. Returns the new bit position, or -1.
local function subframe(b: buffer, p: number, lim: number, s: { number }, n: number, bps: number, cf: { number }): number
if p > lim then
return -1
@@ -558,8 +545,6 @@ local function subframe(b: buffer, p: number, lim: number, s: { number }, n: num
return p
end
-- Decode the frame whose header h was parsed (data ends at len). chans[c] are tables of at least h.blockSize
-- numbers; they receive the samples. Returns the byte offset after the frame, or nil, err.
function Frame.decode(b: buffer, len: number, h: Header, chans: { { number } }, cf: { number }, checkCrc: boolean): (number?, string?)
local n = h.blockSize
local lim = len * 8
@@ -575,7 +560,7 @@ function Frame.decode(b: buffer, len: number, h: Header, chans: { { number } },
return nil, "bad subframe"
end
end
local e = rshift(p + 7, 3) -- byte align
local e = rshift(p + 7, 3)
if e + 2 > len then
return nil, "truncated frame"
end
+2 -4
View File
@@ -1,8 +1,6 @@
--!strict
-- codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim,
-- fixed, LPC, Rice residuals, stereo decorrelation) with CRC-8 / CRC-16 (Frame), and the frame encoder (Encode).
-- Absorbed from flac-luau 7083d0d (same author); the encoder is new. Native FLAC / Ogg FLAC streams, metadata and
-- seeking are audio/flac.
-- codecs/audio/Flac: FLAC frames without the container (frame header, subframes, CRC-8 / CRC-16) and the frame encoder.
-- Absorbed from flac-luau 7083d0d; the encoder is new.
local Flac = {
Frame = require("@rosetta/codecs/audio/Flac/Frame"),
Encode = require("@rosetta/codecs/audio/Flac/Encode"),
+13 -15
View File
@@ -1,8 +1,7 @@
--!strict
-- codecs/audio/Hively/Load: AHX ("THX\0".."THX\2") and HivelyTracker ("HVL\0", "HVL\1") module files -> the replayer's
-- Tune. Ported from hvl2wav's replay.c 1.9 loaders (hvl_load_ahx / hvl_reset; BSD-3-Clause, (c) 2006-2018 Pete Gordon;
-- licenses/hivelytracker-LICENSE.txt), with bounds checks the C code does not have. Errors are returned as
-- (nil, message, kind) for core/Err.from.
-- codecs/audio/Hively/Load: AHX ("THX\0".."THX\2") and HivelyTracker ("HVL\0", "HVL\1") module files -> Tune.
-- Ported from hvl2wav replay.c 1.9 (hvl_load_ahx / hvl_reset; BSD-3-Clause, (c) 2006-2018 Pete Gordon;
-- licenses/hivelytracker-LICENSE.txt), with bounds checks the C code does not have.
local Load = {}
local readu8, readi8 = buffer.readu8, buffer.readi8
@@ -27,23 +26,23 @@ export type Instrument = {
plist: { speed: number, length: number, entries: { PlistEntry } },
}
export type Tune = {
format: string, -- "ahx" | "hvl"
version: number, -- the 4th byte: AHX 0..2, HVL 0..1
format: string,
version: number,
title: string,
channels: number, -- 4 (AHX), 4..16 (HVL)
channels: number,
positionNr: number,
restart: number,
speedMultiplier: number, -- 1..4 player calls per 50 Hz frame
trackLength: number, -- rows per track, 1..64
trackNr: number, -- the highest track number stored
speedMultiplier: number,
trackLength: number,
trackNr: number,
instrumentNr: number,
subsongs: { number }, -- first positions of subsongs 1..n
subsongs: { number },
positions: buffer, -- positionNr * 16 * 2 bytes: per channel track (u8), transpose (i8)
tracks: buffer, -- 257 * 64 * 6 bytes: per track row note, instrument, fx, param, fxb, paramb
instruments: { Instrument }, -- 1-based, as numbered in the file
instruments: { Instrument },
mixgain: number, -- (percent * 256) / 100, HVL only (AHX: set by the stereo separation at render time)
stereo: number, -- HVL: the default stereo separation 0..4
emptyTrack0: boolean, -- track 0 is not stored (always empty)
stereo: number,
emptyTrack0: boolean,
}
local function cstring(b: buffer, p: number, limit: number, max: number): (string, number)
@@ -54,7 +53,6 @@ local function cstring(b: buffer, p: number, limit: number, max: number): (strin
return buffer.readstring(b, p, e - p), e
end
-- parse(b, base, limit) -> Tune | nil, message, kind
function Load.parse(b: buffer, base: number, limit: number): (Tune?, string?, string?)
local size = limit - base
if size < 14 then
+5 -19
View File
@@ -1,10 +1,8 @@
--!strict
--!native
-- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer: positions and tracks (two effect columns in HVL), the
-- instrument engine (ADSR, vibrato, the PList performance list, square modulation, the resonant filter sweep, hard cut,
-- ring modulation and panning for HVL) and the integer mixer, all as hvl2wav's replay.c 1.9 computes them so the output
-- matches hvl2wav sample for sample. Ported from HivelyTracker (BSD-3-Clause, (c) 2006-2018 Pete Gordon;
-- licenses/hivelytracker-LICENSE.txt). Where the C code reads outside its arrays on bad data this port clamps instead.
-- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer and integer mixer, as hvl2wav's replay.c 1.9 computes them.
-- Ported from HivelyTracker (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt). Where the C
-- code reads outside its arrays on bad data this port clamps instead.
local Tables = require("@rosetta/codecs/audio/Hively/Tables")
local Load = require("@rosetta/codecs/audio/Hively/Load")
@@ -102,7 +100,6 @@ local function newVoice(i: number): Voice
}
end
-- new(tune, freq, stereo, subsong) -> State | nil (subsong out of range). stereo: AHX separation 0..4 (HVL: the file's)
function Player.new(tune: Load.Tune, freq: number, stereo: number, subsong: number): State?
if subsong < 0 or subsong > #tune.subsongs then
return nil
@@ -130,7 +127,6 @@ function Player.new(tune: Load.Tune, freq: number, stereo: number, subsong: numb
return st
end
-- ------------------------------------------------------------------------------------------------ steps
local function setPan(st: State, v: Voice, p: number)
v.pan = p
v.panMultLeft, v.panMultRight = st.panL[p], st.panR[p]
@@ -370,7 +366,6 @@ local function processStep(st: State, v: Voice)
stepfx3(st, v, fxb, fxbp)
end
-- ------------------------------------------------------------------------------------------------ frames
local function plistCommand(st: State, v: Voice, fx: number, param: number)
if fx == 0 then
if param > 0 and param < 0x40 then
@@ -537,7 +532,6 @@ local function processFrame(st: State, v: Voice)
end
end
-- ADSR envelope
if v.aFrames ~= 0 then
v.adsrVolume += v.aVolume
v.aFrames -= 1
@@ -560,10 +554,8 @@ local function processFrame(st: State, v: Voice)
end
end
-- volume slide
v.noteMaxVolume = math.clamp(v.noteMaxVolume + v.volumeSlideUp - v.volumeSlideDown, 0, 0x40)
-- portamento
if v.periodSlideOn then
if v.periodSlideWithLimit then
local d0 = v.periodSlidePeriod - v.periodSlideLimit
@@ -588,7 +580,6 @@ local function processFrame(st: State, v: Voice)
end
end
-- vibrato
if v.vibratoDepth ~= 0 then
if v.vibratoDelay <= 0 then
v.vibratoPeriod = (VIB[v.vibratoCurrent] * v.vibratoDepth) // 128
@@ -599,7 +590,6 @@ local function processFrame(st: State, v: Voice)
end
end
-- PList
local pl = v.perfList
if pl then
if v.instrument and v.perfCurrent < v.instrument.plist.length then
@@ -636,7 +626,6 @@ local function processFrame(st: State, v: Voice)
end
end
-- perf portamento
if v.periodPerfSlideOn then
v.periodPerfSlidePeriod = s16(v.periodPerfSlidePeriod - v.periodPerfSlideSpeed)
if v.periodPerfSlidePeriod ~= 0 then
@@ -754,7 +743,6 @@ local function processFrame(st: State, v: Voice)
end
end
-- ring modulation period
if v.ringAudioOff >= 0 then
local rp = v.ringBasePeriod
if v.ringFixedPeriod == 0 then
@@ -772,7 +760,6 @@ local function processFrame(st: State, v: Voice)
v.ringAudioPeriod = math.clamp(rp, 0x71, 0xd60)
end
-- the period
local ap = v.instrPeriod
if v.fixedNote == 0 then
if v.overrideTranspose ~= 1000 then
@@ -794,7 +781,6 @@ local function processFrame(st: State, v: Voice)
v.audioVolume = s16(vol)
end
-- fill the 0x280-byte voice buffer with repeats of the 4 << waveLength cycle at (src, off)
local function fillCycles(dst: buffer, src: buffer, off: number, len: number)
if off < 0 or off + len > buffer.len(src) then
buffer.fill(dst, 0, 0, 0x281)
@@ -830,7 +816,7 @@ local function setAudio(st: State, v: Voice)
end
end
-- irq(st, audio): one player call (hvl_play_irq); audio = false skips the audio side (duration scans)
-- hvl_play_irq (audio = false skips the audio side)
function Player.irq(st: State, audio: boolean)
local tune = st.tune
local nch = st.channels
@@ -888,7 +874,7 @@ function Player.irq(st: State, audio: boolean)
end
end
-- mix(st, out, at, n): n stereo frames of f32 into out at frame `at` (hvl_mixchunk: integer mixing, s16 clipping, / 32768)
-- hvl_mixchunk: integer mixing, s16 clipping, / 32768
function Player.mix(st: State, out: buffer, at: number, n: number)
local nch = st.channels
local voices = st.voices
+3 -7
View File
@@ -1,15 +1,12 @@
--!strict
--!native
-- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's tables: the waveform block (triangle and sawtooth at
-- six lengths, 32 square pulse widths, white noise, and the 31 low-pass and 31 high-pass filtered copies of all of
-- them, generated as hvl_replay.c does), the sine panning tables, the vibrato sine and the Amiga period table. Ported
-- from HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt)
-- as hvl2wav builds on 64-bit Linux (`long` is 64-bit there: the noise generator's shifts do not wrap at 32 bits).
-- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's waveform, panning, vibrato and period tables.
-- Ported from hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt) as
-- built on 64-bit Linux (`long` is 64-bit: the noise generator's shifts do not wrap at 32 bits).
local Tables = {}
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
-- the offsets inside `waves` (bytes)
local FILTER_SET = 0xfc + 0xfc + 0x80 * 0x1f + 0x80 + 3 * 0x280 -- 6520: one filtered copy of every waveform
local WHITENOISELEN = 0x280 * 3
local WO_LOWPASSES = 0
@@ -184,7 +181,6 @@ end
local cache: { waves: buffer, panL: { number }, panR: { number } }? = nil
-- get() -> { waves (int8 buffer), panL, panR (0-based, 256 entries) }: built once, shared read only
function Tables.get(): { waves: buffer, panL: { number }, panR: { number } }
if cache then
return cache
+9 -24
View File
@@ -1,17 +1,8 @@
--!strict
-- codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats
-- (Load), the replayer with its waveform generator (Tables: triangle / sawtooth / square / noise and the 31 + 31
-- filtered copies) and integer mixer (Player), and the render glue to a Types.Decoder (stereo f32). A port of
-- HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt):
-- at hvl2wav's settings the output equals hvl2wav's 16-bit samples / 32768, sample for sample.
--
-- local Hively = require("@rosetta/codecs/audio/Hively")
-- local tune, err = Hively.parse(buf, 0, buffer.len(buf)) -- the replayer's Tune
-- local song = Hively.module(tune) -- a Types.Module-shaped value with render()
-- local dec = Hively.decoder(tune, { sampleRate = 44100 }) -- a Types.Decoder
--
-- Not supported: hvl2wav's -a auto gain; a speed multiplier of 4 at 44.1 kHz renders 880 samples per 50 Hz frame
-- (hvl2wav pads each frame to 882 with stale samples).
-- codecs/audio/Hively: the AHX / HivelyTracker engine (loader, replayer, waveform tables, render glue).
-- A port of hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt); at
-- hvl2wav's settings the output equals its 16-bit samples / 32768. hvl2wav pads a 44.1 kHz speed-multiplier-4 frame to
-- 882 samples with stale data; this renders 880.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Load = require("@rosetta/codecs/audio/Hively/Load")
@@ -22,14 +13,13 @@ local Hively = {}
export type Tune = Load.Tune
export type RenderOptions = {
sampleRate: number?, -- default 44100 (the replayer runs at any rate: 8000..192000)
subsong: number?, -- 0 = the main song (default), 1..n the subsongs
stereo: number?, -- AHX stereo separation 0..4 (0 mono, 4 = 100 % Amiga L R R L); default 0 as hvl2wav. HVL: the file's
loop: boolean?, -- keep playing past the song end (frames / duration still give one pass)
sampleRate: number?,
subsong: number?,
stereo: number?, -- AHX stereo separation 0..4 (4 = 100 % Amiga L R R L); default 0 as hvl2wav
loop: boolean?,
maxDuration: number?, -- seconds, default 600 (hvl2wav's 10 minute limit)
}
-- parse(b, base?, limit?) -> Tune | nil, Err
function Hively.parse(b: buffer, base: number?, limit: number?): (Tune?, Err.Err?)
local tune, msg, kind = Load.parse(b, base or 0, limit or buffer.len(b))
if not tune then
@@ -51,7 +41,6 @@ local function settings(tune: Tune, opts: RenderOptions?): (number?, number, num
return rate, sub, tonumber(o.stereo) or 0, nil
end
-- frameCount(tune, opts?) -> 50 Hz frames until the song end (as hvl2wav stops), capped by maxDuration
function Hively.frameCount(tune: Tune, opts: RenderOptions?): number
local rate, sub, stereo = settings(tune, opts)
local st = rate and Player.new(tune, rate :: number, stereo, sub)
@@ -69,7 +58,6 @@ function Hively.frameCount(tune: Tune, opts: RenderOptions?): number
return n
end
-- decoder(tune, opts?) -> Types.Decoder | nil, Err
function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
local rate, sub, stereo, err = settings(tune, opts)
if not rate then
@@ -84,7 +72,7 @@ function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err.
local loop = opts ~= nil and opts.loop == true
local st = Player.new(tune, sr, stereo, sub) :: Player.State
local fbuf = buffer.create(perFrame * 8)
local fpos, ffill = 0, 0 -- read position / filled frames inside fbuf
local fpos, ffill = 0, 0
local pos = 0
local function nextFrame()
@@ -147,8 +135,6 @@ function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err.
return (dec :: any) :: Types.Decoder, nil
end
-- module(tune) -> a Types.Module-shaped value (kind "music"): tracks as patterns (rows * 6 bytes: note, instrument,
-- fx, param, fxb, paramb), positions, instruments with their play lists, and render(opts) -> Decoder
function Hively.module(tune: Tune): Types.Module
local patterns = {}
for t = 0, tune.trackNr do
@@ -198,7 +184,6 @@ function Hively.module(tune: Tune): Types.Module
if dec then
return dec
end
-- the Types contract returns a Decoder: a failed render is an empty one carrying the Err
local empty: any = Pcm.audioDecoder(Types.Audio.new(44100, 2, 0))
empty.err = derr
return empty
+4 -8
View File
@@ -1,10 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for
-- other primes), self-sorting Stockham passes ping-ponging between the data and a scratch array (the FFTPACK /
-- pocketfft pass structure, written from the textbook decimation-in-frequency derivation; no third-party code).
-- Data are separate real / imaginary arrays, 1-based. Never throws.
-- codecs/audio/Mdct/Fft: mixed-radix complex FFT (radix 4, 2, 3, 5, generic odd), self-sorting Stockham passes (the
-- FFTPACK / pocketfft pass structure, written from the textbook derivation; no third-party code).
local Fft = {}
export type Plan = {
@@ -16,13 +14,12 @@ export type Plan = {
-- per pass, generic odd radix: exp(-2 pi i k / p) for k = 0 .. p - 1
rr: { { number } },
ri: { { number } },
sre: { number }, -- scratch
sre: { number },
sim: { number },
}
local cos, sin, pi = math.cos, math.sin, math.pi
-- new(n) -> Plan | nil (n < 1 or not an integer)
function Fft.new(n: number): Plan?
if type(n) ~= "number" or n < 1 or n % 1 ~= 0 or n > 2 ^ 24 then
return nil
@@ -189,8 +186,7 @@ local function pass(p: number, ido: number, l1: number, ar: { number }, ai: { nu
end
end
-- forward(plan, re, im): in-place forward DFT X[k] = sum x[j] exp(-2 pi i j k / n) of re[1..n], im[1..n].
-- The inverse (without the 1 / n) is forward(plan, im, re).
-- X[k] = sum x[j] exp(-2 pi i j k / n), in place; the inverse (without 1 / n) is forward(plan, im, re)
function Fft.forward(plan: Plan, re: { number }, im: { number })
local n = plan.n
local ar, ai, br, bi = re, im, plan.sre, plan.sim
+13 -34
View File
@@ -1,28 +1,14 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
-- complex FFT (codecs/audio/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the
-- DCT-IV, a plain FFT and the sine / KBD / Vorbis windows. Shared by AAC, Vorbis and Opus (decoders and encoders).
-- Written from the textbook definitions (MDCT = DCT-IV of the folded input; DCT-IV through a half-size complex FFT
-- with pre / post twiddles); no third-party code.
-- codecs/audio/Mdct: MDCT / IMDCT for any N divisible by 4, DCT-IV, and the sine / KBD / Vorbis windows.
-- Through an N / 4-point complex FFT; written from the textbook definitions, no third-party code.
--
-- X[k] = sum_{j=0}^{N-1} x[j] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) forward, k = 0 .. N/2 - 1
-- y[j] = sum_{k=0}^{N/2-1} X[k] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) inverse, j = 0 .. N - 1
--
-- Both are unnormalised (times `scale`, default 1): windowed forward + inverse + overlap-add with a Princen-Bradley
-- window gives the input times N / 4 (AAC: the spec IMDCT is inverse(..., 2 / N), its MDCT has a factor 2). Arrays
-- are Luau arrays; `xi` / `yi` are the 1-based index of element 0, coefficient arrays may be strided (CELT
-- interleaves its short blocks).
--
-- local Mdct = require("@rosetta/codecs/audio/Mdct")
-- local plan = Mdct.new(2048) -- nil when N is not a multiple of 4
-- Mdct.forward(plan, x, 1, X, 1) -- 2048 samples -> 1024 coefficients
-- Mdct.inverse(plan, X, 1, 1, y, 1, 2 / 2048) -- 1024 coefficients -> 2048 samples
-- local w = Mdct.window("sine", 2048) -- or "kbd" (alpha), "vorbis": N values
--
-- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller
-- sizes them).
-- Unnormalised: forward + inverse + overlap-add with a Princen-Bradley window gives the input times N / 4 (the AAC spec
-- IMDCT is inverse(..., 2 / N)).
local Fft = require("@rosetta/codecs/audio/Mdct/Fft")
local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt
@@ -31,17 +17,16 @@ local Mdct = {}
Mdct.Fft = Fft
export type Plan = {
n: number, -- window length N
m: number, -- coefficients N / 2
fft: Fft.Plan, -- N / 4 points
n: number,
m: number,
fft: Fft.Plan,
twc: { number }, -- cos / sin (pi (p + 1/8) / M), p = 0 .. N/4 - 1
tws: { number },
re: { number }, -- scratch
re: { number },
im: { number },
c: { number }, -- DCT-IV output scratch (M)
c: { number },
}
-- new(N) -> Plan | nil
function Mdct.new(n: number): Plan?
if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then
return nil
@@ -69,7 +54,6 @@ function Mdct.new(n: number): Plan?
}
end
-- the DCT-IV of the M values u (already in plan.re / plan.im as the pre-twiddled pairs) into out[oi + k * os]
local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, scale: number)
local q, m = plan.n // 4, plan.m
local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws
@@ -82,8 +66,7 @@ local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, sca
end
end
-- dct4(plan, u, ui, us, out, oi, os, scale?): C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)) for the
-- plan's M = N / 2 (its own inverse up to 2 / M)
-- C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)), M = N / 2 (its own inverse up to 2 / M)
function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { number }, oi: number, os: number, scale: number?)
local q, m = plan.n // 4, plan.m
local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws
@@ -96,10 +79,9 @@ function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { num
dct4Post(plan, out, oi, os, scale or 1)
end
-- forward(plan, x, xi, X, Xi, Xs?, scale?): N samples x[xi ..] -> N / 2 coefficients X[Xi + k * Xs]
function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi: number, os: number?, scale: number?)
local q, m = plan.n // 4, plan.m
local h = m // 2 -- N / 4
local h = m // 2
local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws
-- fold: u[j] = -x[3M/2 - 1 - j] - x[3M/2 + j] (j < M/2), x[j - M/2] - x[3M/2 - 1 - j] (j >= M/2)
local b3 = xi + 3 * h
@@ -125,7 +107,6 @@ function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi
dct4Post(plan, out, oi, os or 1, scale or 1)
end
-- inverse(plan, X, Xi, Xs?, y, yi, scale?): N / 2 coefficients X[Xi + k * Xs] -> N samples y[yi ..] (no window)
function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: { number }, yi: number, scale: number?)
local m = plan.m
local h = m // 2
@@ -140,7 +121,6 @@ function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: {
end
end
-- ------------------------------------------------------------------------------------------------ windows
local function besselI0(x: number): number
local sum, term = 1, 1
local k = 1
@@ -156,8 +136,8 @@ local function besselI0(x: number): number
end
Mdct.besselI0 = besselI0
-- window(kind, N, alpha?) -> N values: "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (alpha: AAC uses 4
-- for long, 6 for short windows); "vorbis" sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1.
-- "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (AAC: alpha 4 long, 6 short); "vorbis"
-- sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1.
function Mdct.window(kind: string, n: number, alpha: number?): { number }?
if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then
return nil
@@ -195,7 +175,6 @@ function Mdct.window(kind: string, n: number, alpha: number?): { number }?
return w
end
-- fft(n) -> an Fft plan (Fft.forward(plan, re, im) transforms in place)
function Mdct.fft(n: number): Fft.Plan?
return Fft.new(n)
end
+11 -26
View File
@@ -1,9 +1,7 @@
--!strict
-- codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list,
-- and the audio Decoder that plays a Midi through codecs/audio/SoundFont's synth (a SoundFont bank, or the built-in
-- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order).
-- Format 2: each track is its own song with its own tempo map, played one after another. Shared by every format that
-- decodes to a Types.Midi (music/midi, mus, xmi, hmp): attach() adds the meta summary and the render method.
-- codecs/audio/MidiRender: the MIDI tempo map, event timeline and the Decoder that plays a Midi through SoundFont.
-- Lengths as python mido computes them. Format 0 / 1: one tempo map from every track, tracks merged (ties keep track
-- order); format 2: each track is its own song, played one after another.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local SoundFont = require("@rosetta/codecs/audio/SoundFont")
@@ -23,7 +21,6 @@ local function tempoOf(ev: any): number?
return nil
end
-- tempoMap(midi, track?) -> TempoMap: from every track (format 0 / 1) or from one track (format 2)
function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap
local changes: { { number } } = {}
for ti, t in midi.tracks do
@@ -62,7 +59,6 @@ function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap
return map
end
-- seconds(map, tick) -> seconds (PPQ through the tempo map; SMPTE divisions are fixed time)
function Render.seconds(map: TempoMap, tick: number): number
local div = map.division
if div < 0 then
@@ -74,7 +70,6 @@ function Render.seconds(map: TempoMap, tick: number): number
return tick / ((if fps == 29 then 29.97 else fps) * tpf)
end
local ticks = map.ticks
-- binary search for the last change at or before tick
local lo, hi = 1, #ticks
while lo < hi do
local mid = (lo + hi + 1) // 2
@@ -87,7 +82,6 @@ function Render.seconds(map: TempoMap, tick: number): number
return map.secs[lo] + (tick - ticks[lo]) * map.us[lo] * 1e-6 / div
end
-- length(midi) -> seconds to the last event (format 2: the tracks one after another)
function Render.length(midi: Types.Midi): number
if #midi.tracks == 0 then
return 0
@@ -116,7 +110,6 @@ end
export type Timeline = { time: { number }, status: { number }, d1: { number }, d2: { number }, length: number }
-- timeline(midi) -> the channel messages in play order with their times in seconds
function Render.timeline(midi: Types.Midi): Timeline
local items: { { any } } = {}
local offset = 0
@@ -162,14 +155,13 @@ function Render.timeline(midi: Types.Midi): Timeline
end
export type RenderOptions = {
sampleRate: number?, -- default 44100
soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/audio/SoundFont.parse) or SF2 bytes (buffer / string); default the built-in waveforms
gain: number?, -- linear output gain, default 0.5
tail: number?, -- seconds rendered after the last event (release tails), default 1
maxVoices: number?, -- default 256
sampleRate: number?,
soundfont: any?,
gain: number?,
tail: number?,
maxVoices: number?,
}
-- decoder(midi, opts?) -> Types.Decoder | nil, Err
function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
if type(midi) ~= "table" or type(midi.tracks) ~= "table" or type(midi.division) ~= "number" or midi.division == 0 then
return nil, Err.new(Err.ARG, "render: needs a Midi value")
@@ -267,19 +259,16 @@ function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?
return (dec :: any) :: Types.Decoder, nil
end
-- tempoBytes(division, ticksPerSecond) -> the 3 data bytes of a tempo meta event making each tick last
-- 1 / ticksPerSecond seconds at that division (for formats with a fixed tick rate: MUS, XMIDI, HMP / HMI)
-- tempo meta making each tick last 1 / ticksPerSecond s at that division (MUS, XMIDI, HMP / HMI)
function Render.tempoBytes(division: number, ticksPerSecond: number): { number }
local us = math.clamp(math.floor(division * 1e6 / ticksPerSecond + 0.5), 1, 0xFFFFFF)
return { us // 65536, (us // 256) % 256, us % 256 }
end
-- ------------------------------------------------------------------------------------------------ durations
export type PendingOff = { tick: number, onTick: number, ev: Types.MidiEvent }
-- merge(events, offs) -> one tick-ordered event list: for formats that store a duration with each note (XMIDI, HMI).
-- events are in file order (ticks never decrease); offs are the generated note-offs. At equal ticks an off whose note
-- started earlier goes before the file's events, an off of a zero-length note after them.
-- XMIDI / HMI note durations: at equal ticks an off whose note started earlier goes before the file's events,
-- an off of a zero-length note after them
function Render.merge(events: { Types.MidiEvent }, offs: { PendingOff }): { Types.MidiEvent }
for i, o in offs do
(o :: any).seq = i
@@ -305,11 +294,9 @@ function Render.merge(events: { Types.MidiEvent }, offs: { PendingOff }): { Type
return out
end
-- ------------------------------------------------------------------------------------------------ attach
local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder
local dec, err = Render.decoder(self, opts)
if not dec then
-- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err)
local empty: any = {
sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err,
read = function(_self: any, _n: number, out: buffer?): (buffer, number)
@@ -325,7 +312,6 @@ local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder
return dec
end
-- summarize(midi): meta.tempos / timeSignatures / keySignatures / length from the events
function Render.summarize(midi: Types.Midi)
local tempos, sigs, keys = {}, {}, {}
local map = Render.tempoMap(midi)
@@ -349,7 +335,6 @@ function Render.summarize(midi: Types.Midi)
midi.meta.length = Render.length(midi)
end
-- attach(midi, source): what every MIDI-like decoder does last: the meta summary, meta.source and the render method
function Render.attach(midi: Types.Midi, source: { [string]: any })
Render.summarize(midi)
midi.meta.source = source
+3 -9
View File
@@ -1,13 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Mpa/Analysis: the MPEG audio polyphase analysis filterbank (ISO/IEC 11172-3 section C.1.3, figure C.4): 32
-- input samples -> one sample in each of the 32 subbands, with the standard's 512-tap window C = D / 32 (D from
-- codecs/audio/Mpa/EncTables) and the matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). Shared by the layer II and layer III
-- encoders. New code from the standard's flow chart. Never throws.
--
-- local st = Analysis.new()
-- Analysis.run(st, samples, start, out, outStart) -- samples[start .. start + 31] -> out[outStart .. outStart + 31]
-- codecs/audio/Mpa/Analysis: the polyphase analysis filterbank (ISO/IEC 11172-3 C.1.3, figure C.4): window C = D / 32,
-- matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64).
local E = require("@rosetta/codecs/audio/Mpa/EncTables")
local Analysis = {}
@@ -16,7 +11,7 @@ local C = table.create(512, 0)
for i = 1, 512 do
C[i] = E.D[i] / 32
end
local M = table.create(32 * 64, 0) -- M[k * 64 + i + 1]
local M = table.create(32 * 64, 0)
for k = 0, 31 do
for i = 0, 63 do
M[k * 64 + i + 1] = math.cos((2 * k + 1) * (i - 16) * math.pi / 64)
@@ -29,7 +24,6 @@ function Analysis.new(): State
return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) }
end
-- run(st, s, si, out, oi): s[si .. si + 31] (oldest first) -> out[oi .. oi + 31] (subbands 0 .. 31)
function Analysis.run(st: State, s: { number }, si: number, out: { number }, oi: number)
-- the window X is kept twice (x[p] and x[p + 512]) so X[i] = x[off + i + 1] without a modulo
local x = st.x
+14 -50
View File
@@ -1,11 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Mpa/Core: a line-by-line port of minimp3's mp3dec_decode_frame (https://github.com/lieff/minimp3,
-- CC0) for layers I, II and III, using its scalar (non-SIMD) code paths and float output.
-- State that must survive between frames (MDCT overlap, polyphase history, bit reservoir) lives in a per-stream
-- state from Core.newState(); everything else is module scratch, so decoding is synchronous and allocation free.
-- All buffer accesses stay in bounds by construction (padded scratch, bounded loops): native code must not throw.
-- codecs/audio/Mpa/Core: a line-by-line port of minimp3's mp3dec_decode_frame (https://github.com/lieff/minimp3, CC0)
-- for layers I, II and III, using its scalar (non-SIMD) code paths and float output.
local T = require("@rosetta/codecs/audio/Mpa/Tables")
local band, bor, lshift, rshift, arshift, bswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.arshift, bit32.byteswap
@@ -18,7 +15,6 @@ local MAX_BITRESERVOIR_BYTES = 511
local MAX_FRAME = 2304 + 8 -- largest frame (free format) incl. padding, rounded up
local SCALE = 1 / 32768
----------------------------------------------------------------------------------------------------------------
-- tables (floats rounded to f32 like the C arrays)
local F32 = bcreate(4)
@@ -111,19 +107,16 @@ for i = 0, 239 do
WINT[i + 1] = f32(T.g_win[i])
end
----------------------------------------------------------------------------------------------------------------
-- scratch
local FRAME = bcreate(MAX_FRAME + 64) -- the current frame, copied (bit reader reads up to 4 bytes ahead)
local MAIN = bcreate(MAX_BITRESERVOIR_BYTES + MAX_FRAME + 4096) -- layer III main data (reservoir + frame)
local MAIN = bcreate(MAX_BITRESERVOIR_BYTES + MAX_FRAME + 4096)
local GRBUF = bcreate(576 * 2 * 4) -- [ch][576] f32
local SCF = bcreate(40 * 4) -- layer III scalefactor gains, f32
local SYN = bcreate((18 + 15) * 64 * 4) -- synthesis lines / reorder scratch, f32
local SCF = bcreate(40 * 4)
local SYN = bcreate((18 + 15) * 64 * 4)
local IST = bcreate(2 * 39 + 8) -- ist_pos[2][39], u8
local ISCF = bcreate(48) -- integer scalefactors, u8
local ISCF = bcreate(48)
local TMP = bcreate(18 * 4 * 2) -- imdct scratch: co[9] si[9] / short block copy[18]
local L12SCF = bcreate(192 * 4) -- L12 scalefactors [band*2 + ch][3], f32
local BA = bcreate(64) -- L12 bit allocation
local BA = bcreate(64)
local SCFCOD = bcreate(64)
-- layer III side info, per granule x channel (0..3)
@@ -140,19 +133,16 @@ end
local MAXB = { [0] = -1, -1, -1 }
local SCFSIZE = { [0] = 0, 0, 0, 0 }
-- per-stream state of the frame being decoded (set by decodeFrame)
local OVL: buffer = bcreate(4) -- mdct_overlap[2][9*32]
local QMF: buffer = bcreate(4) -- qmf_state[15*2*32]
local PCM: buffer = bcreate(4)
----------------------------------------------------------------------------------------------------------------
-- bit reader (bs_t): position and limit in bits
-- bit reader (bs_t)
local bsBuf: buffer = FRAME
local bsPos = 0
local bsLimit = 0
-- n <= 25
local function getBits(n: number): number
local pos = bsPos
bsPos = pos + n
@@ -163,7 +153,6 @@ local function getBits(n: number): number
return rshift(w, 32 - n)
end
----------------------------------------------------------------------------------------------------------------
-- layer III side info (L3_read_side_info): fills GR_*, returns main_data_begin or -1
local function readSideInfo(h1: number, h2: number, h3: number): number
@@ -254,9 +243,6 @@ local function readSideInfo(h1: number, h2: number, h3: number): number
return mdb
end
----------------------------------------------------------------------------------------------------------------
-- layer III scalefactors
local function ldexpQ2(y: number, e: number): number
repeat
local s = if e < 120 then e else 120
@@ -346,7 +332,6 @@ local function decodeScalefactors(h1: number, h3: number, istOff: number, gr: nu
end
end
----------------------------------------------------------------------------------------------------------------
-- layer III Huffman decoding (L3_huffman) into GRBUF[dst ..], reads MAIN through a 32-bit cache
local function huffman(dst: number, gr: number, limit: number)
@@ -495,9 +480,6 @@ local function huffman(dst: number, gr: number, limit: number)
bsPos = limit
end
----------------------------------------------------------------------------------------------------------------
-- layer III stereo
-- L3_midside_stereo on GRBUF[left .. left + n) and its right channel at + 576
local function midside(left: number, n: number)
for i = left * 4, (left + n - 1) * 4, 4 do
@@ -576,9 +558,6 @@ local function intensityStereo(h1: number, h3: number, gr: number)
end
end
----------------------------------------------------------------------------------------------------------------
-- layer III reorder, antialias, IMDCT
local function reorder(g: number, sfb: number)
local src, dst = g, 0
while true do
@@ -842,7 +821,7 @@ local function dctII(g: number, n: number)
t2_7 = d + c
t3_7 = (d - c) * 5.10114861
end
do -- row 0
do
local x0, x1, x2, x3, x4, x5, x6, x7 = t0_0, t0_1, t0_2, t0_3, t0_4, t0_5, t0_6, t0_7
local xt = x0 - x7
x0 += x7
@@ -874,7 +853,7 @@ local function dctII(g: number, n: number)
t0_6 = (x4 - x3) * 1.30656302
t0_7 = (xt - x7) * 2.56291556
end
do -- row 1
do
local x0, x1, x2, x3, x4, x5, x6, x7 = t1_0, t1_1, t1_2, t1_3, t1_4, t1_5, t1_6, t1_7
local xt = x0 - x7
x0 += x7
@@ -906,7 +885,7 @@ local function dctII(g: number, n: number)
t1_6 = (x4 - x3) * 1.30656302
t1_7 = (xt - x7) * 2.56291556
end
do -- row 2
do
local x0, x1, x2, x3, x4, x5, x6, x7 = t2_0, t2_1, t2_2, t2_3, t2_4, t2_5, t2_6, t2_7
local xt = x0 - x7
x0 += x7
@@ -938,7 +917,7 @@ local function dctII(g: number, n: number)
t2_6 = (x4 - x3) * 1.30656302
t2_7 = (xt - x7) * 2.56291556
end
do -- row 3
do
local x0, x1, x2, x3, x4, x5, x6, x7 = t3_0, t3_1, t3_2, t3_3, t3_4, t3_5, t3_6, t3_7
local xt = x0 - x7
x0 += x7
@@ -1101,7 +1080,6 @@ local function l3Decode(h1: number, h2: number, h3: number, grBase: number, nch:
end
end
----------------------------------------------------------------------------------------------------------------
-- polyphase synthesis (mp3d_DCT_II, mp3d_synth, mp3d_synth_granule)
@@ -1129,8 +1107,7 @@ local function synthPair(dst: number, nch: number, z: number)
wf(PCM, (dst + 16 * nch) * 4, a * SCALE)
end
-- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel. xl = GRBUF float index of the left
-- channel's slot, dstl = PCM float index, lins = SYN float index
-- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel
local function synth(xl: number, dstl: number, nch: number, lins: number)
local xr = xl + 576 * (nch - 1)
local dstr = dstl + (nch - 1)
@@ -1256,9 +1233,6 @@ local function synthGranule(nbands: number, nch: number, pcm: number)
end
end
----------------------------------------------------------------------------------------------------------------
-- layers I and II
local ALLOC_L1 = { 76, 4, 32 }
local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 }
local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 }
@@ -1371,9 +1345,6 @@ local function l12ApplyScf(scfOff: number)
end
end
----------------------------------------------------------------------------------------------------------------
-- API
local Core = {}
Core.MAX_FRAME = MAX_FRAME
@@ -1406,7 +1377,6 @@ end
Core.lastChannels = 0
-- pcm holds n mono samples: spread them to n interleaved stereo pairs (in place)
function Core.upmix(pcm: buffer, n: number)
if buffer.len(pcm) < n * 8 then
return
@@ -1418,9 +1388,6 @@ function Core.upmix(pcm: buffer, n: number)
end
end
-- Decodes the frame b[off, off + size) (a whole frame found by the index, header included) into pcm
-- (interleaved f32, frame samples x channels) and returns the samples per channel (0 = no output: an
-- unfilled bit reservoir, or corrupt data). Core.lastChannels = the frame's channel count.
function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm: buffer): number
if size < 4 or size > MAX_FRAME or off < 0 or off + size > buffer.len(b) then
st.needReset = true
@@ -1485,7 +1452,6 @@ function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm:
bsBuf = FRAME
return if success then spf else 0
end
-- layers I / II
local kbps = 2 * HALFRATE[(if band(h1, 8) ~= 0 then 45 else 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)]
l12ReadScaleInfo(h1, h2, h3, kbps)
bfill(GRBUF, 0, 0)
@@ -1509,8 +1475,6 @@ function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm:
return spf
end
-- Layer III side info of the frame b[off, off + size): main_data_begin (-1 = corrupt), the sum of its
-- part2_3 lengths in bits, and the main data bytes in the frame. Used by the stream index.
function Core.probeL3(b: buffer, off: number, size: number): (number, number, number)
local n = min(size, 64)
if size < 4 or off + n > buffer.len(b) then
@@ -1534,7 +1498,7 @@ function Core.probeL3(b: buffer, off: number, size: number): (number, number, nu
return mdb, sum, (bsLimit - bsPos) // 8
end
-- Layer I / II: false when the frame b[off, off + size) needs more bits than it has (minimp3 then drops it).
-- Layer I / II: minimp3 drops a frame that needs more bits than it has
function Core.probeL12(b: buffer, off: number, size: number): boolean
if size < 4 or size > MAX_FRAME or off + size > buffer.len(b) then
return false
+3 -5
View File
@@ -1,9 +1,7 @@
--!strict
-- codecs/audio/Mpa/EncTables: tables for the MPEG audio encoders, from PDMP3 (public domain / unlicense, by Krister
-- Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt), which transcribes ISO/IEC 11172-3: the synthesis window D
-- (the analysis window is C = D / 32) and the layer III Huffman code trees (the encoders derive codeword tables from
-- them). Trees use the standard's decoder layout: an entry with a high byte is a node (high byte: left offset, low
-- byte: right offset), otherwise a leaf (x << 4 | y; count1 tables: v w x y bits).
-- codecs/audio/Mpa/EncTables: the synthesis window D and the layer III Huffman trees of ISO/IEC 11172-3, from PDMP3
-- (public domain / unlicense, Krister Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt). Tree entries with a
-- high byte are nodes (high byte: left offset, low byte: right offset), else leaves (x << 4 | y; count1: v w x y bits).
local E = {}
E.D = {
0.000000000, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000030518,
+6 -17
View File
@@ -1,13 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Mpa/Encode2: an MPEG audio layer II (MP2) encoder: constant bit rate, MPEG-1 (32 / 44.1 / 48 kHz) and MPEG-2
-- low sampling frequencies (16 / 22.05 / 24 kHz), mono or stereo. New code written from ISO/IEC 11172-3 (2.4.2.3,
-- C.1.5.2): the polyphase analysis (codecs/audio/Mpa/Analysis), one scalefactor per 12-sample part (scfsi 0: all three are
-- sent), the standard bit allocation tables (in minimp3's compact form, CC0: licenses/minimp3-CC0.txt, as the decoder
-- in this folder reads them), a greedy allocation that always gives the next step to the band with the most noise
-- (signal level minus the quantizer's SNR; no psychoacoustic model), uniform midtread quantization and grouping of
-- 3 / 5 / 9-level samples. Never throws.
-- codecs/audio/Mpa/Encode2: an MPEG audio layer II CBR encoder, written from ISO/IEC 11172-3 (2.4.2.3, C.1.5.2).
-- Bit allocation tables in minimp3's compact form (CC0, licenses/minimp3-CC0.txt); greedy allocation by noise (signal
-- level minus the quantizer's SNR), no psychoacoustic model.
local Bits = require("@rosetta/core/Bits")
local T = require("@rosetta/codecs/audio/Mpa/Tables")
local Analysis = require("@rosetta/codecs/audio/Mpa/Analysis")
@@ -35,7 +31,6 @@ local function levels(ba: number): number
end
return POW[ba + 1] - 1
end
-- bits for the 3 samples of one granule
local function tripleBits(ba: number): number
if ba >= 17 then
return if ba == 17 then 5 elseif ba == 18 then 7 else 10
@@ -100,7 +95,6 @@ export type Source = {
}
export type Options = { bitrate: number, mode: string, prefix: buffer? }
-- encode(src, opts) -> buffer | nil, message
function Encode2.encode(src: Source, opts: Options): (buffer?, string?)
local rate = src.sampleRate
local info = RATES[rate]
@@ -117,7 +111,6 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?)
if not brIndex then
return nil, "unsupported bit rate"
end
-- the allocation table (the decoder's choice from the header)
local alloc, nbands
if not mpeg1 then
alloc, nbands = ALLOC_L2M2, 30
@@ -168,8 +161,8 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?)
-- subband samples: sb[c][band * 36 + t + 1], t = 0 .. 35
local sbs = { table.create(32 * 36, 0), table.create(32 * 36, 0) }
local sub = table.create(32, 0)
local scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) } -- scalefactor index per band and part
local bal = { table.create(32, 0), table.create(32, 0) } -- allocation step (0 = none) per band
local scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) }
local bal = { table.create(32, 0), table.create(32, 0) }
local slot = 144000 * kbps
local rest = 0
local tmp: buffer? = nil
@@ -249,7 +242,6 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?)
end
end
end
-- the frame size and the bits left for scalefactors and samples
local frameBytes = slot // rate
rest += slot % rate
local padding = 0
@@ -262,8 +254,7 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?)
for b = 1, nbands do
avail -= bandBits[b] * nch
end
-- greedy allocation: the band with the most noise gets its next step while it fits
local level = { table.create(nbands, 0), table.create(nbands, 0) } -- signal level (dB) per band
local level = { table.create(nbands, 0), table.create(nbands, 0) }
for c = 1, nch do
local sc = scf[c]
for b = 1, nbands do
@@ -298,7 +289,6 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?)
bal[bestC][bestB] += 1
avail -= bestCost
end
-- write the frame
if w.pos + frameBytes + 64 > buffer.len(w.buf) then
local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes)
buffer.copy(nb, 0, w.buf, 0, w.pos)
@@ -318,7 +308,6 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?)
put(w, 0, 1)
put(w, 1, 1)
put(w, 0, 2)
-- bit allocation
for b = 1, nbands do
for c = 1, nch do
local st = bal[c][b]
+12 -38
View File
@@ -1,13 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Mpa/Encode3: an MPEG audio layer III encoder in the spirit of shine: constant bit rate, long blocks only,
-- global-gain rate control (no psychoacoustic model, scalefactors all zero), no bit reservoir (main_data_begin = 0),
-- MPEG-1 (32 / 44.1 / 48 kHz, two granules), MPEG-2 (16 / 22.05 / 24 kHz) and MPEG-2.5 (8 / 11.025 / 12 kHz), mono,
-- stereo or joint (mid / side) stereo. New code written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code): the
-- analysis filterbank (codecs/audio/Mpa/Analysis), the 36-point MDCT with the sine window, the alias-reduction butterflies,
-- the x^(3/4) quantizer, big_values / count1 partitioning with per-region Huffman table choice; the Huffman codes are
-- derived from the standard's decoder trees (codecs/audio/Mpa/EncTables, from PDMP3, public domain). Never throws.
-- codecs/audio/Mpa/Encode3: an MPEG audio layer III CBR encoder in the spirit of shine (long blocks, global-gain rate
-- control, no bit reservoir). Written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code); Huffman codes derived
-- from the standard's decoder trees (codecs/audio/Mpa/EncTables, from PDMP3, public domain).
local Bits = require("@rosetta/core/Bits")
local E = require("@rosetta/codecs/audio/Mpa/EncTables")
local T = require("@rosetta/codecs/audio/Mpa/Tables")
@@ -23,7 +19,6 @@ for i = 0, 39 do
POW[i + 1] = 2 ^ i
end
-- ------------------------------------------------------------------------------------------------ Huffman codes
-- CODE[t][x * 16 + y + 1], LEN[t][...] for the pair tables 1..31 (16..23 and 24..31 share a tree); count1 tables A
-- (32) and B (33) indexed by v * 8 + w * 4 + x * 2 + y + 1
local CODE: { [number]: { number } } = {}
@@ -75,7 +70,6 @@ for t = 1, 33 do
end
end
local LINBITS = E.LINBITS
-- the tables that hold values up to m (m <= 15), smallest first
local SMALL: { [number]: { number } } = {}
for m = 0, 15 do
local list = {}
@@ -87,13 +81,11 @@ for m = 0, 15 do
SMALL[m] = list
end
-- ------------------------------------------------------------------------------------------------ bit writer
type W = Bits.RawWriter
local put = Bits.msbPut
Encode3.put = put
-- ------------------------------------------------------------------------------------------------ constants
local RATES = {
-- rate -> version bits (3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5), sample rate index, scalefactor band group (g_scf_long)
[44100] = { 3, 0, 5 },
@@ -118,7 +110,6 @@ for k = 0, 17 do
MDCT[k * 36 + i + 1] = math.sin(pi / 36 * (i + 0.5)) * cos(pi / 72 * (2 * i + 19) * (2 * k + 1)) / 9
end
end
-- alias reduction coefficients
local CI = { -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037 }
local CS, CA = table.create(8, 0), table.create(8, 0)
for i = 1, 8 do
@@ -126,16 +117,15 @@ for i = 1, 8 do
CS[i], CA[i] = 1 / s, CI[i] / s
end
-- ------------------------------------------------------------------------------------------------ Huffman planning
type Plan = {
bits: number,
bigValues: number, -- pairs
count1: number, -- quadruples
tables: { number }, -- 3 region tables
bigValues: number,
count1: number,
tables: { number },
region0: number,
region1: number,
c1table: number, -- 0 = A (table 32), 1 = B (33)
addr1: number, -- coefficient index where region 1 starts
addr1: number,
addr2: number,
}
@@ -143,7 +133,6 @@ local function newPlan(): Plan
return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 }
end
-- bits of the pairs ix[a .. b) with table t (ix 1-based: ix[i + 1] is coefficient i)
local function pairBits(ix: { number }, a: number, b: number, t: number): number
if t == 0 then
return 0
@@ -173,7 +162,6 @@ local function pairBits(ix: { number }, a: number, b: number, t: number): number
return bits
end
-- the best table for the pairs ix[a .. b): table, bits
local function chooseTable(ix: { number }, a: number, b: number): (number, number)
if b <= a then
return 0, 0
@@ -214,7 +202,6 @@ local function chooseTable(ix: { number }, a: number, b: number): (number, numbe
return best, bestBits
end
-- plan the Huffman coding of ix (576 values, max <= 8206) into p; bounds = scalefactor band starts (1-based list)
local function plan(ix: { number }, bounds: { number }, p: Plan)
local i = 576
while i > 1 and ix[i] == 0 and ix[i - 1] == 0 do
@@ -228,7 +215,6 @@ local function plan(ix: { number }, bounds: { number }, p: Plan)
end
local bv = i -- big_values * 2 coefficients
p.bigValues, p.count1 = bv // 2, c1
-- count1 bits, table A vs B
local ba, bb = 0, 0
local lensA = LEN[32]
for q = 0, c1 - 1 do
@@ -309,9 +295,8 @@ local function writeHuffman(w: W, ix: { number }, sign: { boolean }, p: Plan)
end
end
-- ------------------------------------------------------------------------------------------------ quantization
type Unit = {
xr: { number }, -- 576 MDCT coefficients
xr: { number },
xa: { number }, -- |xr|^(3/4)
ix: { number },
sign: { boolean },
@@ -344,7 +329,6 @@ local function quantize(u: Unit, g: number): boolean
return true
end
-- the finest global gain whose Huffman size fits budget bits
local function rateLoop(u: Unit, budget: number, bounds: { number })
local xr, xa, sign = u.xr, u.xa, u.sign
local maxa = 0
@@ -366,7 +350,6 @@ local function rateLoop(u: Unit, budget: number, bounds: { number })
u.gain = 0
return
end
-- the gain where the largest value quantizes to 0: an upper bound
local lo, hi = 0, 255
local best = -1
while lo <= hi do
@@ -397,7 +380,6 @@ local function rateLoop(u: Unit, budget: number, bounds: { number })
u.gain = best
end
-- ------------------------------------------------------------------------------------------------ encoder
export type Source = {
sampleRate: number,
channels: number,
@@ -406,12 +388,11 @@ export type Source = {
err: any,
}
export type Options = {
bitrate: number, -- kbps, valid for the version
mode: string, -- "stereo" | "joint" | "mono"
prefix: buffer?, -- bytes written before the first frame (an ID3v2 tag)
bitrate: number,
mode: string,
prefix: buffer?,
}
-- encode(src, opts) -> buffer | nil, message
function Encode3.encode(src: Source, opts: Options): (buffer?, string?)
local rate = src.sampleRate
local info = RATES[rate]
@@ -433,7 +414,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?)
end
local sideBytes = if mpeg1 then (if nch == 1 then 17 else 32) else (if nch == 1 then 9 else 17)
local slotNum = (if mpeg1 then 144000 else 72000) * kbps -- frame bytes * rate
-- scalefactor band starts (long blocks)
local bounds = { 0 }
do
local acc = 0
@@ -453,7 +433,7 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?)
w.pos = need
end
local ana = { Analysis.new(), Analysis.new() }
local prev = { table.create(576, 0), table.create(576, 0) } -- previous granule's subband samples [sb * 18 + k + 1]
local prev = { table.create(576, 0), table.create(576, 0) }
local cur = { table.create(576, 0), table.create(576, 0) }
local units = {}
for g = 1, 2 do
@@ -469,7 +449,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?)
local srcDone = false
local flushed = false
while true do
-- one frame of input (zero padded at the end; one more silent frame flushes the filterbank delay)
local got = 0
while got < spf and not srcDone do
if pendN == 0 then
@@ -513,7 +492,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?)
s[i] = 0
end
end
-- analysis + MDCT per granule and channel
for g = 1, granules do
for c = 1, nch do
local cu, pv = cur[c], prev[c]
@@ -564,7 +542,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?)
end
end
end
-- the frame size
local frameBytes = slotNum // rate
rest += slotNum % rate
local padding = 0
@@ -586,7 +563,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?)
done += 1
end
end
-- header
if w.pos + frameBytes + 64 > buffer.len(w.buf) then
local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes)
buffer.copy(nb, 0, w.buf, 0, w.pos)
@@ -606,7 +582,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?)
put(w, 0, 1)
put(w, 1, 1) -- original
put(w, 0, 2)
-- side info
if mpeg1 then
put(w, 0, 9) -- main_data_begin
put(w, 0, if nch == 1 then 5 else 3)
@@ -638,7 +613,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?)
put(w, p.c1table, 1)
end
end
-- main data
for g = 1, granules do
for c = 1, nch do
local u = units[g][c]
+5 -6
View File
@@ -1,9 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Mpa/Header: MPEG audio frame headers (minimp3's hdr_* macros and functions), frame sync (mp3d_find_frame /
-- mp3d_match_frame). Every function reads 4 header bytes at a byte offset of a buffer; callers keep offset + 4
-- inside the buffer. Never throws.
-- codecs/audio/Mpa/Header: MPEG audio frame headers and frame sync, after minimp3's hdr_* and mp3d_find_frame /
-- mp3d_match_frame (CC0, licenses/minimp3-CC0.txt).
local T = require("@rosetta/codecs/audio/Mpa/Tables")
local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift
@@ -30,7 +29,7 @@ function H.valid(b: buffer, o: number): boolean
end
local valid = H.valid
-- hdr_compare: h2 is a valid header of the same version / layer / sample rate / free-format-ness as h1
-- hdr_compare
function H.compare(b: buffer, o1: number, o2: number): boolean
if not valid(b, o2) then
return false
@@ -73,7 +72,7 @@ function H.frameSamples(h1: number): number
end
local frameSamples = H.frameSamples
-- hdr_frame_bytes (without padding); free format = 0 -> freeSize
-- hdr_frame_bytes (without padding)
function H.frameBytes(b: buffer, o: number, freeSize: number): number
local h1, h2 = ru8(b, o + 1), ru8(b, o + 2)
local hz = sampleRate(h1, h2)
@@ -108,7 +107,7 @@ local function matchFrame(b: buffer, o: number, n: number, fb: number): boolean
return true
end
-- mp3d_find_frame over b[base, base + n): returns (skip, frame bytes incl. padding or 0, free format size)
-- mp3d_find_frame
function H.findFrame(b: buffer, base: number, n: number, ffb: number): (number, number, number)
for i = 0, n - 5 do
local o = base + i
+3 -4
View File
@@ -1,8 +1,7 @@
--!strict
-- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it:
-- frame headers (Header), the decoder core (Core: a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt,
-- absorbed from mp3-luau c755bbf) with its tables, and the layer III / layer II encoders (Encode3, Encode2: shine-style
-- CBR, new) with their analysis tables. ID3 tags, Xing / LAME gapless info, the frame index and seeking are audio/mp3.
-- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it.
-- Core is a port of minimp3 by lieff (CC0, licenses/minimp3-CC0.txt), absorbed from mp3-luau c755bbf; the layer II / III
-- encoders are new.
local Mpa = {
Header = require("@rosetta/codecs/audio/Mpa/Header"),
Core = require("@rosetta/codecs/audio/Mpa/Core"),
+14 -34
View File
@@ -1,13 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel): the bitstream (band
-- resolutions, scalefactor indices, quantised subband samples, with SV8's canonical Huffman / enumerative codes),
-- requantisation (M/S or L/R) and the 32-band polyphase synthesis. A line-by-line port of libmpcdec's mpc_decoder.c,
-- requant.c and synth_filter.c (musepack_src_r475, BSD-3-Clause, (c) The Musepack Development Team,
-- licenses/libmpcdec-BSD.txt) in double precision float. The bit reader is module state (decoding is synchronous) over
-- a buffer the caller pads by at least PAD bytes past `limit`: the band loops stop as soon as the position passes the
-- limit, so every read stays inside the buffer. No error / assert: failures return nil, "message".
-- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel).
-- A line-by-line port of libmpcdec's mpc_decoder.c, requant.c and synth_filter.c (musepack_src_r475, BSD-3-Clause, (c) The
-- Musepack Development Team, licenses/libmpcdec-BSD.txt). The caller pads the buffer by PAD bytes past `limit`.
local T = require("@rosetta/codecs/audio/Musepack/Tables")
local readu32, bswap, extract, band, bor, rshift, lshift, bnot, bxor =
@@ -19,7 +15,6 @@ Decode.PAD = 8192
Decode.DELAY = 481 -- MPC_DECODER_SYNTH_DELAY
Decode.FRAME = 1152
-- ------------------------------------------------------------------------------------------------ tables
local L = T.lut
local HDR, SCFI7, DSCF7 = L(T.HuffHdr), L(T.HuffSCFI), L(T.HuffDSCF)
local Q7: { { T.Lut } } = {
@@ -83,9 +78,8 @@ for i, v in T.DI do
DW[i] = f32(v / 65536)
end
-- ------------------------------------------------------------------------------------------------ bit reader
local B: buffer = buffer.create(0)
local P = 0 -- bit position
local P = 0
local function bits(n: number): number
if n <= 0 then
@@ -106,7 +100,6 @@ local function peek16(): number
return extract(w, 16 - band(P, 7), 16)
end
-- a table-driven Huffman symbol (plain or canonical)
local function huff(t: T.Lut): number
local code = peek16()
local k = rshift(code, 8) + 1
@@ -176,7 +169,6 @@ for i = 0, 255 do
PARITY[i + 1] = p
end
-- ------------------------------------------------------------------------------------------------ synthesis
-- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing
-- through Byeong Gi Lee's fast DCT)
local function newV(Y: { number }, y: number, V: { number }, o: number)
@@ -392,26 +384,25 @@ local function newV(Y: { number }, y: number, V: { number }, o: number)
V[o + 96 - i] = V[o + i]
end
end
-- ------------------------------------------------------------------------------------------------ state
export type State = {
version: number, -- 7 | 8
maxBand: number, -- the highest band index (0 .. 31)
version: number,
maxBand: number,
ms: boolean,
channels: number,
resL: { number }, -- [band + 1]
resL: { number },
resR: { number },
scfL: { number }, -- [band * 3 + m + 1]
scfL: { number },
scfR: { number },
scfiL: { number },
scfiR: { number },
dscfL: { boolean },
dscfR: { boolean },
msf: { boolean },
qL: { number }, -- [band * 36 + k + 1]
qL: { number },
qR: { number },
yL: { number }, -- [n * 32 + band + 1], n = 0 .. 35
yL: { number },
yR: { number },
vL: { number }, -- synthesis history, 2304 + 960
vL: { number },
vR: { number },
r1: number,
r2: number,
@@ -446,9 +437,7 @@ function Decode.state(version: number, maxBand: number, ms: boolean, channels: n
return st
end
-- reset(st, scf): forget the history (before a seek); scf = the scalefactor indices to assume (libmpcdec: 0 at the
-- start of the stream, 0x01010101 in the middle of an SV7 stream). The noise generator restarts too, so a seek
-- decodes like libmpcdec seeking in a freshly opened stream.
-- libmpcdec assumes scf 0 at the stream start, 0x01010101 mid-SV7; the noise generator restarts, as in a fresh stream
function Decode.reset(st: State, scf: number)
for i = 1, 99 do
st.scfL[i] = scf
@@ -479,8 +468,7 @@ local function noise(st: State, q: { number }, o: number)
st.r1, st.r2 = r1, r2
end
-- ------------------------------------------------------------------------------------------------ SV7
-- mpc_decoder_read_bitstream_sv7 -> true | nil, message
-- mpc_decoder_read_bitstream_sv7
local function readSv7(st: State, limit: number): (boolean?, string?)
local resL, resR, msf = st.resL, st.resR, st.msf
local maxUsed = 0
@@ -607,7 +595,6 @@ local function readSv7(st: State, limit: number): (boolean?, string?)
return true, nil
end
-- ------------------------------------------------------------------------------------------------ SV8
local function readSv8(st: State, key: boolean, limit: number): (boolean?, string?)
local resL, resR, msf = st.resL, st.resR, st.msf
local maxBand = st.maxBand
@@ -802,7 +789,6 @@ local function readSv8(st: State, key: boolean, limit: number): (boolean?, strin
return true, nil
end
-- ------------------------------------------------------------------------------------------------ requantisation
local function requant(st: State)
local resL, resR, msf = st.resL, st.resR, st.msf
local scfL, scfR, qL, qR, yL, yR = st.scfL, st.scfR, st.qL, st.qR, st.yL, st.yR
@@ -833,7 +819,7 @@ local function requant(st: State)
end
-- mpc_synthese_filter_float for one channel: 36 x 32 subband samples -> 1152 samples at out[base + i * step]
-- mpc_synthese_filter_float
local function synth(V: { number }, Y: { number }, out: { number }, base: number, step: number)
table.move(V, 1, 960, 2305)
local o = 2304 + 1
@@ -854,10 +840,6 @@ local function synth(V: { number }, Y: { number }, out: { number }, base: number
end
end
-- ------------------------------------------------------------------------------------------------ frames
-- frame(st, buf, bitPos, limitBits, key, out, base) -> the bit position after the frame | nil, message: decodes one
-- frame from buf (padded by PAD bytes past limitBits / 8) into out[base ..] (1152 * channels interleaved floats).
-- key: an SV8 key frame (the first of a block). bitPos < 0 decodes a silent frame (the synthesis tail).
function Decode.frame(st: State, buf: buffer, bitPos: number, limitBits: number, key: boolean, out: { number }, base: number): (number?, string?)
if bitPos >= 0 then
if rshift(limitBits, 3) + Decode.PAD > buffer.len(buf) or bitPos > limitBits then
@@ -889,8 +871,6 @@ function Decode.frame(st: State, buf: buffer, bitPos: number, limitBits: number,
return if bitPos >= 0 then pos else bitPos, nil
end
-- bitsAt(buf, bitPos, n) -> n (1 .. 24) bits at bitPos (frame headers: the SV7 frame size); the caller keeps
-- bitPos / 8 + 4 inside buf
function Decode.bitsAt(buf: buffer, bitPos: number, n: number): number
local w = bswap(readu32(buf, rshift(bitPos, 3)))
return extract(w, 32 - band(bitPos, 7) - n, n)
@@ -1,10 +1,8 @@
--!strict
-- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, the synthesis window and the requantisation
-- constants. Ported from libmpcdec (musepack_src_r475: huffman.c, synth_filter.c, requant.c, mpc_bits_reader.c;
-- BSD-3-Clause, (c) The Musepack Development Team, licenses/libmpcdec-BSD.txt); the tables are transcribed by script.
-- Each Huffman table is a flat { code, length, value, ... } list sorted by descending left-aligned 16-bit code;
-- canonical (SV8) tables map value - (code >> (16 - length)) through their symbol list. lut(table, sym?) builds the
-- 8-bit first-level lookup the decoder uses.
-- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, synthesis window and requantisation constants.
-- Ported from libmpcdec (musepack_src_r475: huffman.c, synth_filter.c, requant.c, mpc_bits_reader.c; BSD-3-Clause,
-- (c) The Musepack Development Team, licenses/libmpcdec-BSD.txt). Huffman tables: flat { code, length, value, ... }
-- sorted by descending left-aligned 16-bit code; canonical (SV8) tables map value - (code >> (16 - length)).
local T = {}
T.HuffHdr = {
@@ -332,15 +330,14 @@ do
end
export type Lut = {
len: { number }, -- 256 entries: code length when the 8-bit prefix decides the symbol, else 0
val: { number }, -- the symbol, or the 1-based table entry to scan from
len: { number },
val: { number },
codes: { number },
lens: { number },
vals: { number },
sym: { number }?,
}
-- lut(table, sym?) -> Lut
function T.lut(tab: { number }, sym: { number }?): Lut
local codes, lens, vals = {}, {}, {}
for i = 1, #tab, 3 do
+7 -23
View File
@@ -1,17 +1,7 @@
--!strict
-- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped
-- header, SV8's key / size packets: SH with its CRC, RG, EI, AP, SE), the frame / audio packet index, and the
-- decoder (codecs/audio/Musepack/Decode: subband bitstream, requantisation, polyphase synthesis). A port of libmpcdec
-- (musepack_src_r475: mpc_demux.c, streaminfo.c, mpc_decoder.c; BSD-3-Clause, (c) The Musepack Development Team,
-- licenses/libmpcdec-BSD.txt), gapless like libmpcdec (the 481-sample synthesis delay and SV8's leading silence are
-- dropped, the length is exact). Not supported: SV4 - SV6 (UNSUPPORTED), the SV8 seek table (the packets are indexed
-- instead), chapters.
--
-- local s, err = Musepack.open(buf, start, limit) -- start: the "MP+" / "MPCK" magic (after an ID3v2 tag)
-- -- s: { version, sampleRate, channels, frames, maxBand, ms, profile, encoder, gapless, gain, ... } plus the
-- -- codecs/audio/Stream spec: count, start(i), decode(i), pcm(), reset(), skip, stop, preroll
--
-- Never throws: bad data returns nil, Err.
-- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8.
-- A port of libmpcdec (musepack_src_r475: mpc_demux.c, streaminfo.c, mpc_decoder.c; BSD-3-Clause, (c) The Musepack
-- Development Team, licenses/libmpcdec-BSD.txt), gapless like libmpcdec. SV4 - SV6 are UNSUPPORTED.
local Err = require("@rosetta/core/Err")
local Crc32 = require("@rosetta/core/Crc32")
local Decode = require("@rosetta/codecs/audio/Musepack/Decode")
@@ -26,7 +16,7 @@ export type Stream = {
version: number,
sampleRate: number,
channels: number,
frames: number, -- output sample frames (gapless)
frames: number,
maxBand: number,
ms: boolean,
profile: number, -- SV7: the profile index (7 telephone .. 13 braindead); SV8: the quality (0 .. 15.875)
@@ -35,8 +25,7 @@ export type Stream = {
pns: boolean?,
gain: { titleGain: number, titlePeak: number, albumGain: number, albumPeak: number }?,
blockFrames: number, -- frames per packet (SV7: 1; SV8: 2^block_pwr)
bytes: number, -- the stream's size in bytes (for the bitrate)
-- the codecs/audio/Stream spec
bytes: number,
count: number,
start: (i: number) -> number,
decode: (i: number) -> (number?, Err.Err?),
@@ -47,7 +36,6 @@ export type Stream = {
preroll: number,
}
-- ------------------------------------------------------------------------------------------------ SV7
-- SV7 reads the stream as little-endian 32-bit words, most significant bit first: swap them into a padded copy
local function swapped(buf: buffer, p: number, limit: number): buffer
local n = limit - p
@@ -106,7 +94,7 @@ local function sv7(buf: buffer, start: number, limit: number): (Stream?, Err.Err
local size = at(s, pos, 20)
local stop = pos + 20 + size + (if i == frames then 11 else 0)
if stop > totalBits then
break -- a truncated last frame
break
end
offs[i], sizes[i] = pos + 20, size
pos = stop
@@ -170,7 +158,6 @@ local function sv7(buf: buffer, start: number, limit: number): (Stream?, Err.Err
return out, nil
end
-- ------------------------------------------------------------------------------------------------ SV8
-- a packet size: 7 bits per byte, most significant first, bit 7 = more
local function varint(buf: buffer, p: number, limit: number): (number, number)
local v = 0
@@ -205,7 +192,7 @@ local function sv8(buf: buffer, start: number, limit: number): (Stream?, Err.Err
local stop = p + size
if stop > limit then
if key == "AP" then
break -- a truncated last packet
break
end
return nil, Err.new(Err.TRUNCATED, key .. " packet", p)
end
@@ -329,8 +316,6 @@ local function sv8(buf: buffer, start: number, limit: number): (Stream?, Err.Err
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- magic(buf, p, limit) -> 7 | 8 | 0 (other: "MP+" with another version is 7's family, reported by open)
function Musepack.magic(buf: buffer, p: number, limit: number): number
if p + 4 > limit then
return 0
@@ -345,7 +330,6 @@ function Musepack.magic(buf: buffer, p: number, limit: number): number
return 0
end
-- open(buf, start, limit) -> Stream | nil, Err
function Musepack.open(buf: buffer, start: number, limit: number): (Stream?, Err.Err?)
local v = Musepack.magic(buf, start, limit)
if v == 8 then
+5 -24
View File
@@ -1,12 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Opus/Celt: CELT decoder (RFC 6716 section 4.3), a port of the libopus float decoder: celt/celt_decoder.c, bands.c, vq.c,
-- cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c (comb filter). Only the standard 48 kHz / 960-sample mode is
-- needed by Opus. Packet loss concealment is the noise-based variant only (no pitch PLC).
--
-- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch
-- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it.
-- codecs/audio/Opus/Celt: CELT decoder (RFC 6716 section 4.3), 48 kHz / 960-sample mode, noise-based PLC only.
-- A port of the libopus float decoder (celt_decoder.c, bands.c, vq.c, cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c;
-- BSD, licenses/libopus-BSD.txt). The C code's band pointers are 0-based offsets into one table W.
local RD = require("@rosetta/codecs/entropy/RangeCoder/Decoder")
local Mdct = require("@rosetta/codecs/audio/Opus/Mdct")
local T = require("@rosetta/codecs/audio/Opus/CeltTables")
@@ -102,7 +99,6 @@ for n = 1, UK - 1 do
end
end
-- shared workspace (decoding is not re-entrant)
local NORM_BASE = 1920
local W = table.create(4096, 0)
local TMP = table.create(256, 0)
@@ -164,7 +160,6 @@ local function bitexactLog2tan(isin: number, icos: number): number
return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932)
end
-- ---------------------------------------------------------------------------------------------------------------
-- energy (quant_bands.c, laplace.c)
local function laplaceDecode(dec: RD.Dec, fs: number, decay: number): number
@@ -278,7 +273,6 @@ local function unquantEnergyFinalise(st: any, start: number, endb: number, fineQ
end
end
-- ---------------------------------------------------------------------------------------------------------------
-- bit allocation (rate.c)
local function bits2pulses(bandI: number, LM: number, bits: number): number
@@ -315,7 +309,7 @@ local function getPulses(i: number): number
return lshift(8 + band(i, 7), rshift(i, 3) - 1)
end
-- clt_compute_allocation + interp_bits2pulses (decoder side). Returns codedBands, balance, intensity, dualStereo.
-- clt_compute_allocation + interp_bits2pulses (decoder side)
local function computeAllocation(start: number, endb: number, offsets: { number }, cap: { number }, allocTrim: number,
total: number, pulses: { number }, ebits: { number }, finePriority: { number }, C: number, LM: number, ec: RD.Dec)
total = imax(total, 0)
@@ -544,7 +538,6 @@ local function computeAllocation(start: number, endb: number, offsets: { number
return codedBands, balance, intensity, dualStereo
end
-- ---------------------------------------------------------------------------------------------------------------
-- PVQ (cwrs.c, vq.c)
local function cwrsi(n: number, k: number, i: number, iy: { number }): number
@@ -605,7 +598,6 @@ local function cwrsi(n: number, k: number, i: number, iy: { number }): number
end
n -= 1
end
-- n == 2
p = 2 * k + 1
local neg = i >= p
if neg then
@@ -619,7 +611,6 @@ local function cwrsi(n: number, k: number, i: number, iy: { number }): number
val = if neg then k - k0 else k0 - k
iy[idx] = val
yy += val * val
-- n == 1
val = if i ~= 0 then -k else k
iy[idx + 1] = val
yy += val * val
@@ -717,7 +708,6 @@ local function algUnquant(X: number, N: number, K: number, spread: number, B: nu
return mask
end
-- ---------------------------------------------------------------------------------------------------------------
-- bands (bands.c)
type Ctx = {
@@ -819,7 +809,6 @@ local function computeQn(N: number, b: number, offset: number, pulseCap: number,
return lshift(rshift(qn + 1, 1), 1)
end
-- returns b, fill, inv, imid, iside, delta, itheta, qalloc
local function computeTheta(N: number, b: number, B: number, B0: number, LM: number, stereo: boolean, fill: number)
local i = ctx.i
local ec = ctx.ec
@@ -1328,9 +1317,6 @@ local function antiCollapse(st: any, C: number, size: number, LM: number, start:
end
end
-- ---------------------------------------------------------------------------------------------------------------
-- synthesis
local function denormaliseBands(X: number, freq: { number }, logE: { number }, eoff: number, start: number, endb: number, M: number, silence: boolean)
local N = M * SHORT_MDCT
local bound = M * EB[endb + 1]
@@ -1486,9 +1472,6 @@ local function deemphasis(st: any, CC: number, N: number, pcm: { number }, pbase
end
end
-- ---------------------------------------------------------------------------------------------------------------
-- decoder state
local function resetState(st: any)
st.rng = 0
st.error = 0
@@ -1596,8 +1579,7 @@ local function decodeLost(st: any, N: number, LM: number)
st.last_frame_type = FRAME_PLC_NOISE
end
-- celt_decode_with_ec. pcm[pbase + j * channels + c]; frameSize at 48 kHz. dec may be nil (a new range decoder over
-- buf[off, off + len)). buf == nil or len <= 1 conceals. Returns the samples per channel, or < 0 on error.
-- celt_decode_with_ec (buf nil or len <= 1 conceals)
function Celt.decode(st: any, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number,
dec: RD.Dec?, accum: boolean): number
local CC = st.channels
@@ -1766,7 +1748,6 @@ function Celt.decode(st: any, buf: buffer?, off: number, len: number, pcm: { num
pulses, fineQuant, finePriority, C, LM, ec)
unquantFineEnergy(st, start, endb, fineQuant, ec, C)
-- shift the decoder memory by one frame
for c = 1, CC do
table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1)
end
+8 -23
View File
@@ -1,12 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms frames (LM 3), full band, constant
-- bit rate, long MDCTs only (no transient detection), no pitch pre-filter, normal spreading, default allocation trim,
-- mono, or stereo as mid / side per band (the angle, intensity when it has no bits; dual L / R stereo on request). The bitstream side is a port of the libopus 1.6 encoder paths
-- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that
-- mirror codecs/audio/Opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/audio/Mdct.
-- Never throws.
-- codecs/audio/Opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms, full band, CBR, long MDCTs only.
-- The bitstream side is a port of the libopus 1.6 encoder paths (celt_encoder.c, quant_bands.c, laplace.c, rate.c,
-- bands.c, vq.c, cwrs.c; BSD, licenses/libopus-BSD.txt); the analysis is simplified.
local RE = require("@rosetta/codecs/entropy/RangeCoder/Encoder")
local T = require("@rosetta/codecs/audio/Opus/CeltTables")
local Mdct = require("@rosetta/codecs/audio/Mdct")
@@ -67,7 +64,6 @@ local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 }
local SPREAD_NORMAL = 2
local SPREAD_FACTOR = { 15, 10, 5 }
-- the MDCT window (the decoder's) and plan
local WINDOW = table.create(OVERLAP, 0)
for i = 0, OVERLAP - 1 do
local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP)
@@ -116,7 +112,6 @@ local function bitexactLog2tan(isin: number, icos: number): number
return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932)
end
-- ------------------------------------------------------------------------------------------------ energy
-- ec_laplace_encode: returns the value actually coded (clamped in the flat tail)
local function laplaceEncode(enc: RE.Enc, value: number, fs: number, decay: number): number
local fl = 0
@@ -153,23 +148,22 @@ end
export type State = {
channels: number,
oldBandE: { number }, -- the decoder's view (2 * 21)
oldBandE: { number },
preMem: { number },
inMem: { { number } }, -- the last OVERLAP pre-emphasised samples per channel
inMem: { { number } },
frames: number,
X: { { number } }, -- per channel 960 normalised coefficients
X: { { number } },
bandLogE: { number },
bandE: { number }, -- linear band amplitudes (intensity stereo weights)
bandE: { number },
error: { number },
work: { number },
tmp: { number },
iy: { number },
remaining: number,
spread: number,
dual: boolean, -- stereo: L / R coded independently (default false: mid / side)
dual: boolean,
}
-- new(channels) -> State
function CeltEncoder.new(channels: number): State
local inMem = {}
local X = {}
@@ -302,7 +296,6 @@ local function quantEnergyFinalise(st: State, fineQuant: { number }, finePriorit
end
end
-- ------------------------------------------------------------------------------------------------ allocation
local function bits2pulses(bandI: number, lm: number, bits: number): number
local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1]
local lo, hi = 0, CACHE_BITS[base + 1]
@@ -566,7 +559,6 @@ local function computeAllocation(offsets: { number }, cap: { number }, allocTrim
return codedBands, balance, intensity, dualStereo
end
-- ------------------------------------------------------------------------------------------------ PVQ
-- icwrs: the index of the pulse vector iy[1..n]
local function icwrs(n: number, iy: { number }): number
local j = n -- 1-based position of _y[n - 1]
@@ -700,7 +692,6 @@ local SCRATCH_A = table.create(256, 0)
local ROT = table.create(256, 0)
local function algQuant(st: State, X: { number }, xo: number, n: number, K: number, enc: RE.Enc)
-- rotate a copy (the original band stays for nothing else, but keep it intact)
for j = 1, n do
ROT[j] = X[xo + j]
end
@@ -710,7 +701,6 @@ local function algQuant(st: State, X: { number }, xo: number, n: number, K: numb
encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1))
end
-- ------------------------------------------------------------------------------------------------ bands
local function computeQn(n: number, b: number, offset: number, pulseCap: number): number
local N2 = 2 * n - 1
local qb = tdiv(b + N2 * offset, N2)
@@ -929,14 +919,10 @@ local function quantAllBands(st: State, C: number, pulses: { number }, dualStere
end
end
-- ------------------------------------------------------------------------------------------------ frame
-- encodeFrame(st, pcm, base, stride, nbBytes) -> buffer: one CELT frame of nbBytes from 960 samples per channel
-- (pcm[base + k * stride + c], floats -1 .. 1, interleaved)
function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, stride: number, nbBytes: number): buffer
local C = st.channels
local work, tmp = st.work, st.tmp
local silent = true
-- pre-emphasis, the windowed 1920-sample MDCT input, band energies, normalisation
for c = 1, C do
local inMem = st.inMem[c]
local m = st.preMem[c]
@@ -988,7 +974,6 @@ function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, strid
local enc = RE.new(nbBytes)
local totalBits = nbBytes * 8
local oldE = st.oldBandE
-- silence
if silent then
encBitLogp(enc, true, 15)
enc.nbits_total += totalBits - tell(enc)
@@ -1,5 +1,5 @@
--!strict
-- codecs/audio/Opus/CeltTables: Generated from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, see licenses/). 1-based arrays.
-- codecs/audio/Opus/CeltTables: from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, licenses/).
return {
logN400 = {
0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36,
+4 -12
View File
@@ -1,9 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching
-- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the
-- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays.
-- codecs/audio/Opus/Decoder: the Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c).
-- SILK / hybrid / CELT mode switching, redundant CELT frames of mode transitions, cross-fades, PLC, multistream.
local RD = require("@rosetta/codecs/entropy/RangeCoder/Decoder")
local Packet = require("@rosetta/codecs/audio/Opus/Packet")
local Celt = require("@rosetta/codecs/audio/Opus/Celt")
@@ -153,7 +152,6 @@ local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pc
end
frameSize = audiosize
-- SILK
if mode ~= MODE_CELT then
local tooSmall = frameSize < F10
local sarr, sbase = pcm, pbase
@@ -289,8 +287,7 @@ local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pc
return audiosize
end
-- opus_decode_native: decodes one packet (buf == nil or len == 0: conceal frameSize samples). pcm[pbase + i * ch + c].
-- Returns the samples per channel (or < 0 on error) and the packet's size (self-delimited packets).
-- opus_decode_native (buf nil or len 0: conceal frameSize samples)
function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, selfDelimited: boolean?): (number, number)
local ch = st.channels
if buf == nil or len == 0 then
@@ -337,7 +334,6 @@ function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm:
return nb, packetOffset
end
-- ---------------------------------------------------------------------------------------------------------------
-- multistream (channel mapping families 0 / 1 / 255)
export type MS = {
@@ -370,7 +366,6 @@ function Decoder.resetMultistream(ms: MS)
end
end
-- copies channel `sc` of src (stride sstride) into every output channel mapped to stream channel index `id`
local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride: number, pcm: { number }, pbase: number, n: number)
local nch = ms.channels
for c = 0, nch - 1 do
@@ -386,7 +381,7 @@ local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride:
end
end
-- opus_multistream_decode_native (float). Returns the samples per channel, or < 0 on error.
-- opus_multistream_decode_native
function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number
local doPlc = buf == nil or len == 0
frameSize = min(frameSize, 5760)
@@ -428,7 +423,6 @@ function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: numbe
return frameSize
end
-- writes src[base + 1 .. base + count] * gain to out as f32 from byte offset o
function Decoder.writeF32(src: { number }, base: number, count: number, gain: number, out: buffer, o: number)
local writef32 = buffer.writef32
if gain == 1 then
@@ -444,8 +438,6 @@ function Decoder.writeF32(src: { number }, base: number, count: number, gain: nu
end
end
-- Stereo downmix of n frames of srcCh-channel audio (src[base + 1 ..], interleaved): matrix[c * 2 + 1 / + 2] are the
-- left / right weights of channel c. Writes f32 to out from byte offset o.
function Decoder.writeDownmix(src: { number }, base: number, n: number, srcCh: number, matrix: { number }, gain: number, out: buffer, o: number)
local writef32 = buffer.writef32
local p = base
+6 -17
View File
@@ -1,19 +1,15 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the
-- kiss_fft stages used by libopus: radix 5, 3, 4 and 2). The 48 kHz mode uses N = 1920 >> shift for
-- shift = 0..3 (FFT sizes 480, 240, 120, 60). Arrays are Luau tables of numbers, 1-based.
-- Why not codecs/audio/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a
-- DCT-IV, of which CELT keeps the middle N / 2, so routing the decoder through it made CELT decoding 2-3x slower
-- (luau: 25 -> 54-76 ms for 3 s of 32 kbps stereo) and changed the output bits (same SNR against opusdec). This
-- fused libopus port (pre-rotation, a kiss_fft with fixed factors, post-rotation, TDAC) stays private.
-- codecs/audio/Opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over the kiss_fft radix 5 / 3 / 4 / 2 stages.
-- N = 1920 >> shift (FFT sizes 480 .. 60). Kept apart from codecs/audio/Mdct: CELT keeps only the middle N / 2 of the
-- full IMDCT, so the shared transform was 2-3x slower and changed the output bits.
local Mdct = {}
local sin, cos, pi = math.sin, math.cos, math.pi
type Plan = {
n: number, -- FFT size (N / 4)
n: number,
factors: { number },
bitrev: { number },
twr: { number },
@@ -82,13 +78,11 @@ local function bfly2(fr: { number }, fi: { number }, N: number)
local tw = 0.7071067812
local p = 1
for _ = 1, N do
-- k = 0
local tr, ti = fr[p + 4], fi[p + 4]
fr[p + 4] = fr[p] - tr
fi[p + 4] = fi[p] - ti
fr[p] += tr
fi[p] += ti
-- k = 1
local a, b = fr[p + 5], fi[p + 5]
tr = (a + b) * tw
ti = (b - a) * tw
@@ -96,14 +90,12 @@ local function bfly2(fr: { number }, fi: { number }, N: number)
fi[p + 5] = fi[p + 1] - ti
fr[p + 1] += tr
fi[p + 1] += ti
-- k = 2
tr = fi[p + 6]
ti = -fr[p + 6]
fr[p + 6] = fr[p + 2] - tr
fi[p + 6] = fi[p + 2] - ti
fr[p + 2] += tr
fi[p + 2] += ti
-- k = 3
a, b = fr[p + 7], fi[p + 7]
tr = (b - a) * tw
ti = -(b + a) * tw
@@ -265,7 +257,7 @@ local function bfly5(fr: { number }, fi: { number }, fstride: number, twr: { num
end
end
-- in-place forward FFT of bit-reversed input (opus_fft_impl)
-- opus_fft_impl (bit-reversed input)
local function fftImpl(pl: Plan)
local factors = pl.factors
local fr, fi, twr, twi = pl.fr, pl.fi, pl.twr, pl.twi
@@ -295,9 +287,7 @@ local function fftImpl(pl: Plan)
end
end
-- clt_mdct_backward: input coefficients inp[inBase + k*stride] (k = 0 .. N/2-1, inBase is the 1-based index of
-- coefficient 0), output written to out[outBase .. outBase + N/2 + overlap/2) with TDAC windowing of the first
-- `overlap` samples (out[outBase] is sample 0).
-- clt_mdct_backward
function Mdct.backward(inp: { number }, inBase: number, out: { number }, outBase: number, window: { number }, overlap: number, shift: number, stride: number)
local pl = plans[shift + 1]
local N4 = pl.n
@@ -319,7 +309,6 @@ function Mdct.backward(inp: { number }, inBase: number, out: { number }, outBase
xp2 -= 2 * stride
end
fftImpl(pl)
-- post-rotate
local h = outBase + (overlap // 2)
for k = 0, N4 - 1 do
local re = fi[k + 1]
+1 -5
View File
@@ -46,7 +46,6 @@ function Packet.channels(toc: number): number
return if band(toc, 4) ~= 0 then 2 else 1
end
-- samples per frame at rate Fs
function Packet.samplesPerFrame(toc: number, Fs: number): number
if band(toc, 0x80) ~= 0 then
local a = band(rshift(toc, 3), 3)
@@ -62,7 +61,6 @@ function Packet.samplesPerFrame(toc: number, Fs: number): number
end
end
-- total samples of a packet at 48 kHz, or -1 if invalid
function Packet.samples(buf: buffer, off: number, len: number): number
if len < 1 then
return -1
@@ -100,9 +98,7 @@ local function parseSize(buf: buffer, p: number, len: number): (number, number)
return 2, 4 * readu8(buf, p + 1) + b0
end
-- Splits a packet (opus_packet_parse_impl). Fills offsets[i] / sizes[i] (1-based, absolute buffer offsets) and
-- returns the frame count, the TOC byte and the packet's total size including padding (self-delimited packets, as in
-- multistream, carry an explicit size for the last frame). The count is -1 for an invalid packet.
-- opus_packet_parse_impl; self-delimited packets (multistream) carry an explicit size for the last frame
function Packet.parse(buf: buffer, off: number, len: number, offsets: { number }, sizes: { number }, selfDelimited: boolean?): (number, number, number)
if len < 1 then
return -1, 0, 0
+3 -39
View File
@@ -1,19 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Opus/Silk: SILK decoder: a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what it calls:
-- decode_frame, decode_indices, decode_pulses, shell_coder, code_signs, decode_parameters, gain_quant, NLSF_*,
-- LPC_fit, LPC_inv_pred_gain, decode_core, stereo_*, CNG, PLC, resampler_private_up2_HQ / IIR_FIR). BSD, see
-- licenses/.
--
-- local st = Silk.new(apiChannels)
-- local ret, n = Silk.decode(st, ctrl, lostFlag, firstFrame, ec, out, outBase)
-- ctrl = { nChannelsAPI, nChannelsInternal, API_sampleRate, internalSampleRate, payloadSize_ms }
-- decodes one 10 / 20 ms SILK frame and writes n samples per channel (at API_sampleRate) to the Luau array
-- `out`, interleaved by nChannelsAPI: out[outBase + i * nChannelsAPI + c], scaled int16 / 32768.
--
-- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values
-- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact.
-- codecs/audio/Opus/Silk: SILK decoder, a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what
-- it calls; BSD, licenses/). C int32 / int16 values are Luau numbers; int32 x int32 products are split to stay below 2^53.
local RD = require("@rosetta/codecs/entropy/RangeCoder/Decoder")
local T = require("@rosetta/codecs/audio/Opus/SilkTables")
@@ -24,7 +13,7 @@ local floor = math.floor
local Silk = {}
local P2 = table.create(64, 0) -- P2[s] = 2^s (1-based by s: P2[s] for s >= 1, P2_0 = 1)
local P2 = table.create(64, 0)
for s = 1, 63 do
P2[s] = 2 ^ s
end
@@ -35,8 +24,6 @@ local function p2(s: number): number
return P2[s]
end
-- C helpers -----------------------------------------------------------------------------------------------------
local function s16(x: number): number
x = x % 65536
if x >= 32768 then
@@ -252,8 +239,6 @@ local function sumSqrShift(x: { number }, xo: number, len: number): (number, num
return nrg, shft
end
-- LPC helpers ---------------------------------------------------------------------------------------------------
-- silk_bwexpander (int16 coefficients), ar 1-based
local function bwexpander(ar: { number }, d: number, chirp_Q16: number)
local chirp_minus_one_Q16 = chirp_Q16 - 65536
@@ -451,8 +436,6 @@ local function lpcAnalysisFilter(out: { number }, oo: number, inp: { number }, i
end
end
-- NLSF ----------------------------------------------------------------------------------------------------------
local CB_NB_MB = {
nVectors = 32,
order = 10,
@@ -604,8 +587,6 @@ local function nlsfDecode(pNLSF_Q15: { number }, NLSFIndices: { number }, CB: an
nlsfStabilize(pNLSF_Q15, CB.deltaMin_Q15, order)
end
-- Resampler (decoder side: 8 / 12 / 16 kHz up to the API rate) ----------------------------------------------------
local RES_COPY, RES_UP2, RES_IIR_FIR = 0, 1, 2
local up2_hq_0 = { 1746, 14986, 39083 - 65536 }
local up2_hq_1 = { 6854, 25769, 55542 - 65536 }
@@ -733,7 +714,6 @@ local function up2HQ(S: { number }, out: { number }, oo: number, inp: { number }
S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5
end
-- returns the next output index
local function iirFirInterpol(out: { number }, oo: number, buf: { number }, max_index_Q16: number, incr: number): number
local index_Q16 = 0
while index_Q16 < max_index_Q16 do
@@ -814,8 +794,6 @@ local function resampler(S: any, out: { number }, inp: { number }, io: number, i
end
end
-- Decoder state -------------------------------------------------------------------------------------------------
local function newChannel(): any
return {
prev_gain_Q16 = 65536,
@@ -943,8 +921,6 @@ local function decoderSetFs(ch: any, fs_kHz: number, fs_API_Hz: number): number
return ret
end
-- Bitstream: indices and pulses ---------------------------------------------------------------------------------
local LTP_gain_iCDF = { T.LTP_gain_iCDF_0, T.LTP_gain_iCDF_1, T.LTP_gain_iCDF_2 }
local LTP_vq_Q7 = { T.LTP_gain_vq_0, T.LTP_gain_vq_1, T.LTP_gain_vq_2 }
local LBRR_flags_iCDF = { T.LBRR_flags_2_iCDF, T.LBRR_flags_3_iCDF }
@@ -1115,8 +1091,6 @@ local function decodePulses(d: any, pulses: { number }, signalType: number, quan
end
end
-- Parameters ----------------------------------------------------------------------------------------------------
local pNLSF_Q15 = table.create(16, 0)
local pNLSF0_Q15 = table.create(16, 0)
@@ -1214,8 +1188,6 @@ local function decodeParameters(ch: any, ctrl: any, condCoding: number)
end
end
-- Core synthesis ------------------------------------------------------------------------------------------------
local sLTP = table.create(320, 0)
local sLTP_Q15 = table.create(640, 0)
local res_Q14 = table.create(80, 0)
@@ -1381,8 +1353,6 @@ local function decodeCore(ch: any, ctrl: any, xq: { number }, xo: number, pulses
end
end
-- PLC / CNG -----------------------------------------------------------------------------------------------------
local HARM_ATT_Q15 = { 32440, 31130 }
local PLC_RAND_ATTENUATE_V_Q15 = { 31130, 26214 }
local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 }
@@ -1708,8 +1678,6 @@ local function cng(ch: any, ctrl: any, frame: { number }, fo: number, length: nu
end
end
-- Frame decode --------------------------------------------------------------------------------------------------
-- silk_decode_frame: writes frame_length samples to out[fo ..]
local function decodeFrame(ch: any, d: any, out: { number }, fo: number, lostFlag: number, condCoding: number): number
local L = ch.frame_length
@@ -1760,8 +1728,6 @@ local function decodeFrame(ch: any, d: any, out: { number }, fo: number, lostFla
return L
end
-- Stereo --------------------------------------------------------------------------------------------------------
local function stereoDecodePred(d: any, pred_Q13: { number })
local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8)
local ix02 = n // 5
@@ -1818,8 +1784,6 @@ local function stereoMSToLR(state: any, x1: { number }, x2: { number }, pred_Q13
end
end
-- API -----------------------------------------------------------------------------------------------------------
export type State = any
function Silk.new(apiChannels: number): State
+2 -5
View File
@@ -1,9 +1,6 @@
--!strict
-- codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT
-- decoders and the multistream / hybrid decoder that drives them (Decoder), the CELT encoder (CeltEncoder) and the
-- CELT inverse MDCT (Mdct, a fused libopus port: see its header for why it is not codecs/audio/Mdct). A port of the
-- libopus 1.6 decoder (BSD: licenses/libopus-BSD.txt), absorbed from opus-luau dd2b4e5; the encoder is new. Ogg Opus
-- (OpusHead, OpusTags, granules, seeking) is audio/opus.
-- codecs/audio/Opus: the Opus codec (RFC 6716) without its container.
-- A port of the libopus 1.6 decoder (BSD, licenses/libopus-BSD.txt), absorbed from opus-luau dd2b4e5; the CELT encoder is new.
local Opus = {
Packet = require("@rosetta/codecs/audio/Opus/Packet"),
Decoder = require("@rosetta/codecs/audio/Opus/Decoder"),
+4 -17
View File
@@ -1,12 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/audio/Pcm). Integers map to
-- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the
-- classic Sun g711.c algorithm, written from the spec).
--
-- Formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw (u8: offset binary).
-- Never throws: callers check ranges (Convert.SIZE[fmt] * count bytes) before calling.
-- codecs/audio/Pcm/Convert: raw sample formats <-> interleaved f32.
-- Integers map to v / 2^(bits-1) (as ffmpeg does). G.711 A-law / mu-law per ITU-T G.711 (the classic Sun g711.c
-- algorithm, written from the spec).
local Convert = {}
local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32
@@ -32,7 +29,6 @@ local SIZE: { [string]: number } = {
ulaw = 1,
}
Convert.SIZE = SIZE
-- the integer bit depth of each format (float: 32 / 64; G.711: 16 after expansion)
Convert.BITS = {
u8 = 8,
s8 = 8,
@@ -50,11 +46,9 @@ Convert.BITS = {
ulaw = 16,
}
-- ------------------------------------------------------------------------------------------------ G.711
local ALAW = table.create(256, 0) -- code -> linear s16
local ALAW = table.create(256, 0)
local ULAW = table.create(256, 0)
for code = 0, 255 do
-- A-law
local a = bit32.bxor(code, 0x55)
local t = bit32.band(a, 0x0F) * 16
local seg = bit32.rshift(bit32.band(a, 0x70), 4)
@@ -66,7 +60,6 @@ for code = 0, 255 do
t = (t + 0x108) * 2 ^ (seg - 1)
end
ALAW[code + 1] = if bit32.band(a, 0x80) ~= 0 then t else -t
-- mu-law
local u = bit32.bxor(code, 0xFF)
local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4)
ULAW[code + 1] = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84
@@ -83,7 +76,6 @@ local function segment(v: number, ends: { number }): number
return 8
end
-- linear s16 -> A-law code
local function alawEncode(pcm: number): number
local mask
local v = floor(pcm / 8) -- 13-bit magnitude domain
@@ -108,7 +100,6 @@ local function alawEncode(pcm: number): number
return bit32.bxor(aval, mask)
end
-- linear s16 -> mu-law code
local function ulawEncode(pcm: number): number
local v = floor(pcm / 4) -- 14-bit
local mask
@@ -136,8 +127,6 @@ Convert.ulawEncode = ulawEncode
Convert.ALAW = ALAW
Convert.ULAW = ULAW
-- ------------------------------------------------------------------------------------------------ decode
-- decode(src, so, fmt, count, dst, do_) -> true | false (unknown fmt): count samples at src[so] -> f32 at dst[do_]
function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean
if fmt == "s16le" then
for i = 0, count - 1 do
@@ -216,7 +205,6 @@ function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst
return true
end
-- ------------------------------------------------------------------------------------------------ encode
local function q(x: number, s: number): number
local v = floor(x * s + 0.5)
if v ~= v then
@@ -230,7 +218,6 @@ local function q(x: number, s: number): number
return v
end
-- encode(src, so, count, fmt, dst, do_) -> true | false: count f32 samples at src[so] -> fmt at dst[do_]
function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean
if fmt == "s16le" then
for i = 0, count - 1 do
+2 -35
View File
@@ -1,21 +1,5 @@
--!strict
-- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
-- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one
-- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au,
-- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder.
--
-- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else
-- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read
-- local audio = Pcm.collect(src) -- read everything into a Types.Audio
-- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder
-- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio
-- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer
-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/audio/Pcm/Convert)
-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767]
-- local x = Pcm.fromInt(s16, 16) -- s / 32768
--
-- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw.
-- Never throws (a decoder's read that throws is caught and ends the stream).
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
@@ -41,11 +25,10 @@ Pcm.WAVE_FROM_VORBIS = {
export type Source = {
sampleRate: number,
channels: number,
frames: number, -- total frames, 0 = unknown (a streaming decoder without an index)
frames: number,
tags: Types.Tags,
-- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end)
read: (self: Source, n: number, out: buffer?) -> (buffer, number),
err: Err.Err?, -- set when the underlying decoder failed mid-stream
err: Err.Err?,
}
local function audioRead(self: any, n: number, out: buffer?): (buffer, number)
@@ -86,7 +69,6 @@ local function decoderRead(self: any, n: number, out: buffer?): (buffer, number)
return b, got
end
-- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read)
function Pcm.source(v: any): (Source?, Err.Err?)
if type(v) ~= "table" then
return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder")
@@ -109,7 +91,6 @@ function Pcm.source(v: any): (Source?, Err.Err?)
return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder")
end
-- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames)
function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?)
local ch = src.channels
local cap = math.max(src.frames, 4096)
@@ -117,7 +98,6 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?)
local total = 0
local limit = maxFrames or 2 ^ 31
local tmp: buffer? = nil
-- a known length: one read straight into the result (decoders write into a big enough out buffer: no copy)
if src.frames > 0 and src.frames <= limit then
local b, n = src:read(src.frames, data)
if n > 0 then
@@ -160,9 +140,6 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?)
return a, nil
end
-- drain(dec, source?, maxFrames?) -> Types.Audio | nil, Err: a format's decode() through its open(): every frame of
-- the Decoder (dec.frames is only a hint: short or long streams keep what decodes), dec.tags, meta.source = source
-- (default dec.source). A decoder that recorded a failure in dec.error (an Err) fails the drain.
function Pcm.drain(dec: any, source: { [string]: any }?, maxFrames: number?): (Types.Audio?, Err.Err?)
local src, err = Pcm.source(dec)
if not src then
@@ -180,9 +157,6 @@ function Pcm.drain(dec: any, source: { [string]: any }?, maxFrames: number?): (T
return a, nil
end
-- ------------------------------------------------------------------------------------------------ decoders
-- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming
-- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf)
function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: number, sampleRate: number, fmt: string, tags: Types.Tags?): (Types.Decoder?, Err.Err?)
local size = Convert.SIZE[fmt]
if not size then
@@ -221,14 +195,12 @@ function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: n
return dec :: any, nil
end
-- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples)
function Pcm.audioDecoder(a: Types.Audio): Types.Decoder
local d = Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) :: any
d.bitrate = a.sampleRate * a.channels * 32
return d
end
-- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples
function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?)
local size = Convert.SIZE[fmt]
if not size then
@@ -254,9 +226,6 @@ function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Er
return total, nil
end
-- ------------------------------------------------------------------------------------------------ conversions
-- reorder(buf, offset, frames, channels, map): in place, frame by frame, channel i of the result = channel map[i]
-- (1-based) of the input; for converting between channel orders (Pcm.WAVE_FROM_VORBIS)
function Pcm.reorder(buf: buffer, offset: number, frames: number, channels: number, map: { number })
local tmp = table.create(channels, 0)
local readf32, writef32 = buffer.readf32, buffer.writef32
@@ -271,7 +240,6 @@ function Pcm.reorder(buf: buffer, offset: number, frames: number, channels: numb
end
end
-- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0)
function Pcm.toInt(x: number, bits: number): number
local s = 2 ^ (bits - 1)
local v = math.floor(x * s + 0.5)
@@ -286,7 +254,6 @@ function Pcm.toInt(x: number, bits: number): number
return v
end
-- fromInt(v, bits) -> v / 2^(bits-1)
function Pcm.fromInt(v: number, bits: number): number
return v / 2 ^ (bits - 1)
end
+4 -21
View File
@@ -1,18 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale
-- factor and 20 3-bit residuals over a 4-tap sign-sign LMS predictor. Ported from qoa.h (phoboslab/qoa, Dominic
-- Szablewski, MIT: licenses/qoa-LICENSE.txt): the tables, the predictor, the decoder and the encoder's brute-force
-- scale factor search, so encoding is byte-for-byte qoa.h's (including its 32-bit wrap in the reciprocal division).
-- The 64-bit slices are handled as two 32-bit halves.
--
-- local info = Qoa.frameInfo(buf, p, avail) -- { channels, rate, samples, size } | nil, message
-- local n, msg = Qoa.decodeFrame(buf, p, avail, dst, d) -- one frame -> interleaved f32 at float index d
-- local size = Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) -- n frames of f32 at frame xf -> bytes at out[p]
-- local lms = Qoa.newLms(ch) -- the encoder state (history 0, weights 0, 0, -1, 2)
--
-- Never throws: decodeFrame checks the frame against avail before reading; encodeFrame needs Qoa.frameSize bytes.
-- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA).
-- Ported from qoa.h (phoboslab/qoa, Dominic Szablewski, MIT: licenses/qoa-LICENSE.txt); encoding is byte-for-byte
-- qoa.h's, including its 32-bit wrap in the reciprocal division.
local readu8, readu32, readf32, writef32, writeu32 = buffer.readu8, buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32
local readi32, writei32 = buffer.readi32, buffer.writei32
local band, rshift, bor, lshift, byteswap = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.byteswap
@@ -55,14 +46,12 @@ local function s16(v: number): number
return if v >= 32768 then v - 65536 else v
end
-- frameSize(channels, slices) -> bytes
function Qoa.frameSize(ch: number, slices: number): number
return 8 + 16 * ch + 8 * slices * ch
end
export type FrameInfo = { channels: number, rate: number, samples: number, size: number }
-- frameInfo(buf, p, avail) -> the frame header's facts, checked against avail and the slice count | nil, message
function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?)
if avail < 8 then
return nil, "truncated frame header"
@@ -86,8 +75,6 @@ function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string
return { channels = ch, rate = rate, samples = samples, size = size }, nil
end
-- decodeFrame(buf, p, avail, dst, d) -> samples per channel, frame bytes | nil, message: one frame (its own LMS state
-- in the header) as interleaved f32 into dst from float index d (dst holds samples * channels floats there)
function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: number): (number?, number | string)
local info, msg = Qoa.frameInfo(b, p, avail)
if not info then
@@ -140,8 +127,7 @@ function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: nu
return samples, info.size
end
-- ------------------------------------------------------------------------------------------------ encoder
-- newLms(ch) -> the encoder's LMS state: 8 i32 per channel (history 0..3, weights 0..3), weights 0, 0, -1, 2 (<< 13)
-- LMS state: 8 i32 per channel (history 0..3, weights 0..3); initial weights 0, 0, -1, 2 (<< 13)
function Qoa.newLms(ch: number): buffer
local st = buffer.create(32 * ch)
for c = 0, ch - 1 do
@@ -151,7 +137,6 @@ function Qoa.newLms(ch: number): buffer
return st
end
-- the nearest s16 to x * 32768 (NaN -> 0)
local function toS16(x: number): number
local v = floor(x * 32768 + 0.5)
if v ~= v then
@@ -177,8 +162,6 @@ local function qdiv(v: number, sf: number): number
return n + sv - sn
end
-- encodeFrame(x, xf, n, ch, rate, lms, out, p) -> bytes written: frames xf .. xf + n - 1 (n <= 5120) of interleaved f32 x
-- as one QOA frame at out[p] (Qoa.frameSize(ch, ceil(n / 20)) bytes); lms carries the encoder state between frames
function Qoa.encodeFrame(x: buffer, xf: number, n: number, ch: number, rate: number, lms: buffer, out: buffer, p: number): number
local slices = (n + 19) // 20
local size = Qoa.frameSize(ch, slices)
+16 -36
View File
@@ -1,44 +1,32 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or
-- whole-buffer, any channel count, interleaved f32 (the Types.Audio / Decoder layout). Used by the Opus, MP3 and MP2
-- encoders (their input rates are fixed) and ops/AudioOps.resample. New in rosetta (the textbook polyphase
-- filter; the kernel is the one the Opus encoder carried).
-- codecs/audio/Resample: sample-rate conversion by band-limited (Kaiser-windowed sinc) polyphase interpolation.
-- New in rosetta.
--
-- The filter is a polyphase table: exact phases when to / gcd(from, to) <= 4096 (44100 <-> 48000: 160 phases),
-- else 4096 phases with linear interpolation between them. Each phase is normalised to unit DC gain. The cutoff is a
-- fraction (opts.cutoff, default 0.97) of the lower Nyquist frequency; quality picks the taps per side at the cutoff:
-- fraction (default 0.97) of the lower Nyquist frequency.
--
-- quality zero crossings per side Kaiser beta stop band
-- "low" 8 6 ~ -60 dB
-- "medium" 16 (default) 8 ~ -80 dB
-- "high" 32 10 ~ -100 dB
--
-- Output frame j sits at input time j * from / to (no delay: the filter is centred, the input is zero outside its
-- range); a stream of n input frames gives floor(n * to / from + 0.5) output frames.
--
-- local out, frames = Resample.buffer(samples, frames, channels, 44100, 48000, { quality = "high" })
-- local rs = Resample.new(44100, 48000, 2) -- nil, message for bad rates
-- local b, n = rs:process(chunk, chunkFrames) -- the output frames this input completes
-- local b2, n2 = rs:flush() -- the rest (the input end padded with zeros)
-- local src2 = Resample.source(pcmSource, 48000) -- a codecs/audio/Pcm Source at the new rate
--
-- Never throws: bad arguments return nil, message (the api turns them into Err.ARG).
-- Output frame j sits at input time j * from / to (centred filter, zero outside the input); n input frames give
-- floor(n * to / from + 0.5) output frames.
local Resample = {}
export type Options = {
quality: ("low" | "medium" | "high")?, -- default "medium"
cutoff: number?, -- pass band edge as a fraction of the lower Nyquist frequency, 0.5 .. 1 (default 0.97)
quality: ("low" | "medium" | "high")?,
cutoff: number?,
}
export type Resampler = {
from: number,
to: number,
channels: number,
-- process(src, frames, out?) -> interleaved f32 buffer, output frames (out is reused when big enough)
process: (self: Resampler, src: buffer, frames: number, out: buffer?) -> (buffer, number),
-- flush(out?) -> the remaining output frames; the resampler is finished afterwards
flush: (self: Resampler, out: buffer?) -> (buffer, number),
}
@@ -69,15 +57,14 @@ local function gcd(a: number, b: number): number
end
type Filter = {
taps: number, -- per phase
half: number, -- taps on the left of the centre (taps = 2 * half)
taps: number,
half: number,
phases: number,
exact: boolean,
h: { number }, -- phase p, tap k: h[p * taps + k + 1]
}
-- filter(ratio, phases, exact, opts) -> the polyphase table. Phase p is the kernel for an output at fraction
-- p / phases past an input sample; tap k multiplies input (floor(t) - half + 1 + k).
-- phase p: an output p / phases past an input sample; tap k multiplies input floor(t) - half + 1 + k
local function makeFilter(ratio: number, phases: number, exact: boolean, zc: number, beta: number, cut: number): Filter
local cutoff = cut * min(1, ratio)
local width = zc / cutoff -- in input samples, each side
@@ -111,7 +98,6 @@ local function makeFilter(ratio: number, phases: number, exact: boolean, zc: num
return { taps = taps, half = half, phases = phases, exact = exact, h = h }
end
-- the stream state: the input history as an interleaved Lua array; hist[1] is frame `base` (absolute)
type State = {
from: number,
to: number,
@@ -121,15 +107,14 @@ type State = {
L: number, -- to / g
hist: { number },
histFrames: number,
base: number, -- the absolute input frame of hist[1]
inFrames: number, -- absolute input frames received
outPos: number, -- next output frame (absolute)
base: number,
inFrames: number,
outPos: number,
done: boolean,
process: any,
flush: any,
}
-- run(st, lastInput) -> buffer, frames: every output frame whose taps end at or before lastInput (absolute, exclusive)
local function run(st: State, limitOut: number, out: buffer?): (buffer, number)
local f = st.f
local taps, half, h = f.taps, f.half, f.h
@@ -159,8 +144,8 @@ local function run(st: State, limitOut: number, out: buffer?): (buffer, number)
for j = j0, jmax - 1 do
local num = j * M
local ip = num // L -- floor(t)
local first = ip - half + 1 -- absolute input frame of tap 0
local rel = first - base -- frame index in hist
local first = ip - half + 1
local rel = first - base
local kLo = if rel < 0 then -rel else 0
local kHi = taps - 1
if rel + kHi >= histFrames then
@@ -199,7 +184,6 @@ local function run(st: State, limitOut: number, out: buffer?): (buffer, number)
end
end
st.outPos = jmax
-- drop history no future output needs (keep from the next output's first tap)
local keepFrom = (jmax * M) // L - half + 1
local drop = keepFrom - base
if drop > 0 then
@@ -243,7 +227,6 @@ local function flush(self: State, out: buffer?): (buffer, number)
return run(self, total, out)
end
-- new(from, to, channels, opts?) -> Resampler | nil, message
function Resample.new(from: number, to: number, channels: number, opts: Options?): (Resampler?, string?)
if type(from) ~= "number" or type(to) ~= "number" or from ~= from or to ~= to or from <= 0 or to <= 0 or from > 2 ^ 24 or to > 2 ^ 24 then
return nil, "bad sample rates"
@@ -287,7 +270,6 @@ function Resample.new(from: number, to: number, channels: number, opts: Options?
return st :: any, nil
end
-- buffer(src, frames, channels, from, to, opts?) -> interleaved f32 buffer, frames | nil, message
function Resample.buffer(src: buffer, frames: number, channels: number, from: number, to: number, opts: Options?): (buffer?, number | string)
local rs, err = Resample.new(from, to, channels, opts)
if not rs then
@@ -322,8 +304,6 @@ function Resample.buffer(src: buffer, frames: number, channels: number, from: nu
return out, got
end
-- source(src, to, opts?) -> a pull source ({ sampleRate, channels, frames, tags, read, err }, the codecs/audio/Pcm Source
-- shape) reading src (any such source: Pcm.source(audioOrDecoder)) at the rate `to` | nil, message
function Resample.source(src: any, to: number, opts: Options?): (any, string?)
if type(src) ~= "table" or type(src.read) ~= "function" then
return nil, "needs a source"
@@ -333,7 +313,7 @@ function Resample.source(src: any, to: number, opts: Options?): (any, string?)
return nil, err
end
local ch = src.channels
local pending = buffer.create(0) -- produced but not yet returned
local pending = buffer.create(0)
local pendingFrames, pendingPos = 0, 0
local ended = false
local out = {
@@ -1,10 +1,6 @@
--!strict
-- codecs/audio/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont
-- (the same shape Parse returns, so the same synth plays it): single-cycle sine / triangle / square / saw waves and a
-- looped noise sample, one preset per GM family of 8 programs (piano, chromatic percussion, organ, guitar, bass,
-- strings, ensemble, brass, reed, pipe, lead, pad, synth fx, ethnic, percussive, sound fx) with family envelopes,
-- filters and vibrato, plus a drum kit on bank 128 (pitch-swept sine kicks and toms, filtered noise snares, hats with
-- an exclusive class, cymbals). Written for this library (no third-party code).
-- codecs/audio/SoundFont/Fallback: the built-in General MIDI set (generated waveforms per GM family, drum kit on bank 128).
-- No third-party code.
local Parse = require("@rosetta/codecs/audio/SoundFont/Parse")
local Fallback = {}
@@ -19,7 +15,6 @@ end
local cached: any = nil
-- build() -> a SoundFont value (kind "soundfont"); built once, shared (the synth never writes to it)
function Fallback.build(): any
if cached then
return cached
@@ -72,7 +67,6 @@ function Fallback.build(): any
return r
end
-- the 16 GM families: wave + envelope / filter / vibrato
local families: { { any } } = {
{ "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } },
{ "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } },
@@ -97,9 +91,7 @@ function Fallback.build(): any
table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } })
end
-- the drum kit (bank 128, every program): one region per key
local kit = {}
-- fields.semis: the pitch (semitones from the sample's natural pitch) at keytrack 0
local function drum(lo: number, hi: number, wave: string, fields: { [string]: number })
local r = region(wave, fields)
r.lokey, r.hikey = lo, hi
+8 -20
View File
@@ -1,19 +1,13 @@
--!strict
-- codecs/audio/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24
-- when present) as one f32 buffer, and the pdta "hydra" (phdr pbag pmod pgen inst ibag imod igen shdr), flattened
-- into playable regions per preset: the instrument global zone, the preset global zone and the preset zone's
-- generators merged the way TinySoundFont (tsf.h v0.9, MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt)
-- does (tsf_load_presets / tsf_region_operator / tsf_region_envtosecs), with every index and sample offset clamped
-- so the synth never reads outside the sample buffer.
-- Differences from tsf.h: initialAttenuation is cB * 0.04 dB (FluidSynth's EMU-compatible scale; tsf uses 0.01);
-- SF3 (Ogg samples) is not supported; modulators (pmod / imod) are read but not applied (as in tsf.h).
-- Never throws: a bad file returns nil, Err.
-- codecs/audio/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader, zones merged into regions as TinySoundFont does.
-- After tsf.h v0.9 (MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt) tsf_load_presets /
-- tsf_region_operator / tsf_region_envtosecs. Unlike tsf.h, initialAttenuation is cB * 0.04 dB (FluidSynth's
-- EMU-compatible scale; tsf uses 0.01).
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Parse = {}
-- a region (one sample zone of a preset), in "absolute" form: envelope / LFO times in seconds, sustain as a level
export type Region = { [string]: number }
export type Preset = { name: string, preset: number, bank: number, regions: { Region } }
@@ -23,7 +17,7 @@ export type SoundFont = {
info: { [string]: string },
samples: buffer, -- f32 mono, sampleCount + 1 floats (a zero pad sample past the end)
sampleCount: number,
presets: { Preset }, -- sorted by bank, then preset number
presets: { Preset },
sampleHeaders: { { [string]: any } },
instruments: { { name: string, zones: number } },
meta: { [string]: any },
@@ -84,7 +78,6 @@ local GEN: { [number]: { any } } = {
[57] = { "group", "group" },
[58] = { "keycenter", "key" },
}
-- the merged fields: value generators once each (several ops share a field), then the four address fields
local MERGE: { { any } } = {}
do
local seen: { [string]: boolean } = {}
@@ -106,7 +99,7 @@ local FIELDS = {
"sampleIndex",
}
-- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's)
-- tsf_region_clear (relative: a preset zone, all zero so values add to the instrument's)
local function clear(relative: boolean): Region
local r: Region = {}
for _, f in FIELDS do
@@ -136,7 +129,6 @@ local function copy(r: Region): Region
return c
end
-- the region defaults in absolute form (seconds, levels): what Fallback builds its regions from
function Parse.defaultRegion(): Region
local r = clear(false)
r.keycenter = 60
@@ -220,7 +212,6 @@ local function envToSecs(r: Region, p: string, sustainIsGain: boolean)
r[p .. "Sustain"] = sus
end
-- ------------------------------------------------------------------------------------------------ RIFF
type Hydra = { [string]: { { number } } }
-- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte)
@@ -244,7 +235,6 @@ local INFO_NAMES = {
export type Options = { maxRegions: number?, maxSamples: number? }
-- parse(r, opts?) -> SoundFont | nil, Err
function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
local maxRegions = opts and opts.maxRegions or 1000000
local maxSamples = opts and opts.maxSamples or 2 ^ 28
@@ -301,7 +291,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
local rec = {}
for _, w in layout do
if w == 20 then
table.insert(rec, 0) -- the name is read separately
table.insert(rec, 0)
sub:skip(20)
elseif w == 4 then
table.insert(rec, sub:u32le())
@@ -338,7 +328,6 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records")
end
end
-- samples
local sr = smpl :: Bytes.Reader
local count = sr:remaining() // 2
if count > maxSamples then
@@ -363,14 +352,13 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
end
sm24 = s24
end
-- presets (tsf_load_presets)
-- tsf_load_presets
local phdr, pbag, pgen = hydra.phdr, hydra.pbag, hydra.pgen
local inst, ibag, igen, shdr = hydra.inst, hydra.ibag, hydra.igen, hydra.shdr
local phdrNames, instNames, shdrNames = (hydra :: any).phdrNames, (hydra :: any).instNames, (hydra :: any).shdrNames
local nInst = #inst - 1 -- the last record of each list is the terminal one
local nShdr = #shdr - 1
local function range(list: { { number } }, i: number, field: number, limit: number): (number, number)
-- [list[i][field], list[i + 1][field]) clamped to [1, limit] (1-based record indexes)
local a = list[i][field] + 1
local b = if list[i + 1] then list[i + 1][field] + 1 else a
return math.max(1, a), math.min(b, limit + 1)
+11 -35
View File
@@ -1,16 +1,8 @@
--!strict
--!native
-- codecs/audio/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9,
-- MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta; licenses/TinySoundFont-LICENSE.txt):
-- voices with the DAHDSR volume envelope (exponential decay / release), the modulation envelope to pitch and filter
-- cutoff, the modulation and vibrato LFOs (triangle) to pitch / filter / volume, a resonant biquad low-pass, linear
-- interpolation, loop modes (none / continuous / until release), 3 dB pan law, exclusive classes; channels with
-- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume,
-- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not
-- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer.
-- Differences from tsf.h: the envelope gain is ramped across each 64-sample block (tsf.h steps it); a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only.
-- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback,
-- the sample buffer has a zero pad sample, the output range is checked before mixing).
-- codecs/audio/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels.
-- A port of TinySoundFont (tsf.h v0.9, MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta;
-- licenses/TinySoundFont-LICENSE.txt). Unlike tsf.h, the envelope gain is ramped across each 64-sample block.
local Synth = {}
local readf32, writef32, blen = buffer.readf32, buffer.writef32, buffer.len
@@ -39,12 +31,12 @@ type Env = {
}
type Lfo = { untilStart: number, level: number, delta: number }
export type Voice = {
preset: number, -- 1-based preset index, -1 = idle
preset: number,
key: number,
channel: number,
held: boolean, -- note off while sustain was down
held: boolean,
region: { [string]: number },
pitchIn: number, -- timecents
pitchIn: number,
pitchOut: number,
pos: number,
gainDB: number,
@@ -83,14 +75,14 @@ export type Channel = {
}
export type State = {
presets: { { regions: { { [string]: number } }, preset: number, bank: number } },
lookup: { [number]: number }, -- bank * 128 + preset -> preset index
lookup: { [number]: number },
samples: buffer,
rate: number,
gainDB: number,
voices: { Voice },
maxVoices: number,
playIndex: number,
channels: { Channel }, -- [1..16] = MIDI channels 0..15
channels: { Channel },
}
local function tc2s(tc: number): number
@@ -106,7 +98,6 @@ local function gain2db(g: number): number
return if g <= 0.00001 then -100 else 20 * math.log10(g)
end
-- ------------------------------------------------------------------------------------------------ envelope
local function releaseSamples(e: Env, rate: number): number
return floor((if e.release <= 0 then FASTRELEASE else e.release) * rate)
end
@@ -216,7 +207,6 @@ local function newEnv(): Env
return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 }
end
-- ------------------------------------------------------------------------------------------------ filter / lfo
local function lowpassSetup(v: Voice, fc: number)
-- the biquad from earlevel.com (as tsf.h)
local k = tan(PI * fc)
@@ -249,7 +239,6 @@ local function lfoProcess(l: Lfo, n: number)
end
end
-- ------------------------------------------------------------------------------------------------ voices
local function calcPitch(v: Voice, shift: number, rate: number)
local r = v.region
local note = v.key + r.transpose + r.tune / 100
@@ -276,7 +265,7 @@ local function voiceEnd(s: State, v: Voice)
nextSegment(v.amp, SUSTAIN, s.rate)
nextSegment(v.mod, SUSTAIN, s.rate)
if v.region.loopMode == LOOP_SUSTAIN then
v.loopEnd = v.loopStart -- keep playing, stop looping
v.loopEnd = v.loopStart
end
end
@@ -303,8 +292,6 @@ local function newChannel(): Channel
}
end
-- new(sf, sampleRate, opts) -> State. sf: { presets, samples } (Parse.parse or Fallback.build).
-- opts.gain: output gain (linear, default 0.5); opts.maxVoices (default 256)
function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State
local lookup: { [number]: number } = {}
for i, p in sf.presets do
@@ -337,7 +324,6 @@ local function presetIndex(s: State, bank: number, preset: number): number
return s.lookup[bank * 128 + preset] or -1
end
-- noteOn(s, channel, key, velocity 0..127)
function Synth.noteOn(s: State, ch: number, key: number, velocity: number)
local c = s.channels[ch + 1]
if not c then
@@ -427,7 +413,6 @@ function Synth.noteOn(s: State, ch: number, key: number, velocity: number)
end
end
-- noteOff(s, channel, key): ends the oldest matching note (all its regions); held while sustain is down
function Synth.noteOff(s: State, ch: number, key: number)
local c = s.channels[ch + 1]
if not c then
@@ -518,7 +503,7 @@ local function setSustain(s: State, ch: number, c: Channel, on: boolean)
end
end
-- program(s, channel, program): bank select + program change (channel 9: drums, bank 128)
-- channel 9: drums (bank 128)
function Synth.program(s: State, ch: number, program: number)
local c = s.channels[ch + 1]
if not c then
@@ -548,7 +533,6 @@ function Synth.program(s: State, ch: number, program: number)
end
end
-- pitchBend(s, channel, 0..16383)
function Synth.pitchBend(s: State, ch: number, value: number)
local c = s.channels[ch + 1]
if not c or c.pitchWheel == value then
@@ -558,7 +542,6 @@ function Synth.pitchBend(s: State, ch: number, value: number)
applyPitch(s, ch, c)
end
-- control(s, channel, controller, value 0..127)
function Synth.control(s: State, ch: number, cc: number, value: number)
local c = s.channels[ch + 1]
if not c then
@@ -640,7 +623,6 @@ function Synth.control(s: State, ch: number, cc: number, value: number)
end
end
-- midi(s, status, d1, d2): one channel message
function Synth.midi(s: State, status: number, d1: number, d2: number)
local kind, ch = status // 16, status % 16
if kind == 9 then
@@ -656,7 +638,6 @@ function Synth.midi(s: State, status: number, d1: number, d2: number)
end
end
-- reset(s): all voices off, channels back to their defaults
function Synth.reset(s: State)
for _, v in s.voices do
v.preset = -1
@@ -669,7 +650,6 @@ function Synth.reset(s: State)
end
end
-- active(s) -> the number of sounding voices
function Synth.active(s: State): number
local n = 0
for _, v in s.voices do
@@ -680,7 +660,6 @@ function Synth.active(s: State): number
return n
end
-- ------------------------------------------------------------------------------------------------ render
local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number)
local region = v.region
local input = s.samples
@@ -772,8 +751,6 @@ local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSa
v.lpActive, v.z1, v.z2 = lpActive, z1, z2
end
-- render(s, out, frame, n): mixes n stereo frames into out (interleaved f32) starting at frame; out-of-range
-- requests are clipped to the buffer
function Synth.render(s: State, out: buffer, frame: number, n: number)
local room = blen(out) // 8 - frame
if frame < 0 or room <= 0 then
@@ -785,8 +762,7 @@ function Synth.render(s: State, out: buffer, frame: number, n: number)
if n <= 0 then
return
end
-- the sample buffer must hold every region's range + the pad sample (Parse / Fallback guarantee it; checked here
-- once so a hand-made SoundFont cannot index outside it)
-- the sample buffer must hold every region's range + the pad sample (checked once against hand-made SoundFonts)
local count = blen(s.samples) // 4 - 1
for _, v in s.voices do
if v.preset ~= -1 then
+2 -19
View File
@@ -1,17 +1,6 @@
--!strict
-- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
-- music/sf2 (the file format) and music/midi (rendering). The synth is a port of TinySoundFont (tsf.h v0.9, MIT,
-- (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt); see Parse / Synth for what is covered.
-- Without a bank, fallback() is a generated General MIDI set of simple waveforms (sine / triangle / square / saw /
-- noise) with a drum kit.
--
-- local SoundFont = require("@rosetta/codecs/audio/SoundFont")
-- local sf, err = SoundFont.parse(buf) -- buffer | string | core/Bytes Reader -> SoundFont | nil, Err
-- local sf = SoundFont.fallback() -- the built-in waveform set
-- local s = SoundFont.synth(sf, 44100, { gain = 0.5 }) -- a synth State; SoundFont.Synth.midi(s, 0x90, 60, 100)
-- SoundFont.Synth.render(s, out, frame, n) -- mix n stereo f32 frames into out at frame
--
-- Never throws: bad data returns nil, Err.
-- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them.
-- The synth is a port of TinySoundFont (tsf.h v0.9, MIT, (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt).
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Parse = require("@rosetta/codecs/audio/SoundFont/Parse")
@@ -26,13 +15,10 @@ export type State = Synth.State
SoundFont.Synth = Synth
SoundFont.defaultRegion = Parse.defaultRegion
-- sniff(r) -> true when r starts with RIFF....sfbk
function SoundFont.sniff(r: Bytes.Reader): boolean
return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk"
end
-- parse(src, opts?) -> SoundFont | nil, Err. src: buffer | string | Reader. opts.maxRegions (default 10^6),
-- opts.maxSamples (default 2^28)
function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?)
local r: Bytes.Reader
if type(src) == "string" then
@@ -51,17 +37,14 @@ function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?)
return sf, err
end
-- fallback() -> the built-in General MIDI waveform set
function SoundFont.fallback(): SoundFont
return Fallback.build()
end
-- isSoundFont(v) -> true for a parsed / fallback SoundFont value
function SoundFont.isSoundFont(v: any): boolean
return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table"
end
-- synth(sf?, sampleRate?, opts?) -> State. opts.gain (linear, default 0.5), opts.maxVoices (default 256)
function SoundFont.synth(sf: SoundFont?, sampleRate: number?, opts: { gain: number?, maxVoices: number? }?): State
return Synth.new(sf or Fallback.build(), sampleRate or 44100, opts and opts.gain, opts and opts.maxVoices)
end
+10 -32
View File
@@ -1,25 +1,6 @@
--!strict
-- codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part
-- every packet-based audio format repeated: decode packets in order into a pending float block, return frames in
-- read()-sized pieces, drop the encoder priming at the start and the padding at the end (gapless), and seek by
-- finding the packet holding the target (with codec pre-roll) and dropping up to it. AAC (ADTS), CAF and M4A use it;
-- formats with their own seeking (Opus granule bisection, FLAC, MP3, Vorbis) keep their streams. New in rosetta
-- (the loop the three formats carried).
--
-- local dec, err = Stream.packets(dec, { -- dec: the Decoder table with its fields (sampleRate, channels,
-- count = n, -- frames, duration, bitrate, tags, ...); read / seek / position
-- start = function(i) return ... end, -- are added. start(i): packet i's first frame (absolute, before
-- decode = function(i) return n, err end,-- trimming); decode(i) -> frames | nil, Err, the samples in pcm()
-- pcm = function() return floats end, -- (interleaved, 1-based; or a buffer of f32) until the next decode
-- reset = function() end, -- forget codec state (before a seek)
-- skip = priming, stop = lastFrame, -- output = absolute frames [skip, stop)
-- preroll = 1, -- packets decoded before the one holding a seek target (AAC: 1)
-- scale = 1 / 32768, -- optional: read() writes pcm() values * scale (default 1)
-- ints = true, -- optional: pcm() holds integers; adds dec:readInt(n, out?), the
-- }) -- same frames as read() as i32 (bit-exact checks)
--
-- A decode failure ends the stream and is kept in dec.error (Pcm.drain reports it); a failing first packet is
-- returned by packets() as the open error. Never throws.
-- codecs/audio/Stream: the streaming Types.Decoder over a packetised codec (gapless trim, seeking with pre-roll).
-- New in rosetta.
local Err = require("@rosetta/core/Err")
local Stream = {}
@@ -28,17 +9,16 @@ export type Spec = {
count: number,
start: (i: number) -> number,
decode: (i: number) -> (number?, Err.Err?),
pcm: () -> { number } | buffer, -- a buffer: interleaved f32 from byte 0
pcm: () -> { number } | buffer,
reset: () -> (),
skip: number?, -- default 0
stop: number?, -- default start(count + 1)
preroll: number?, -- default 0
skip: number?,
stop: number?,
preroll: number?,
cumulative: boolean?, -- frames after a packet = frames before + its output (default: start(i) + its output)
scale: number?, -- read() writes pcm() values times this (default 1)
ints: boolean?, -- pcm() values are integers: dec:readInt(n, out?) returns them as i32
scale: number?,
ints: boolean?,
}
-- packets(dec, spec) -> dec (with read / seek / position) | nil, Err (the first packet failed)
function Stream.packets(dec: any, spec: Spec): (any, Err.Err?)
local sr, ch = dec.sampleRate, dec.channels
local count = spec.count
@@ -48,7 +28,7 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?)
local preroll = spec.preroll or 0
local decodeP, pcmOf, startOf = spec.decode, spec.pcm, spec.start
local nextPacket = 1
local decoded = 0 -- absolute frame after the packets decoded so far
local decoded = 0
local pendPos, pendN = 0, 0
local dropUntil = skip
local pos = 0
@@ -144,8 +124,7 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?)
function dec.seek(_self: any, seconds: number)
local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0
local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip -- absolute frame
-- the last packet starting at or before the target, minus the codec's pre-roll
local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip
local lo, hi, found = 1, count, 1
while lo <= hi do
local mid = (lo + hi) // 2
@@ -171,7 +150,6 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?)
return pos / sr
end
-- prime: surface a broken first packet as an open error
if count > 0 and frames > 0 and not fill() and failed then
return nil, failed
end
+9 -24
View File
@@ -1,10 +1,7 @@
--!strict
-- codecs/audio/Tracker/Load: helpers shared by the tracker loaders that map another format's effects onto one of the
-- engine's families (music/mtm, 669, stm, ult, okt, med, ptm, far). Effects are first named the way OpenMPT's loaders
-- name them ("portaup", "volslide", "modex", ...), then written in the family's own cell coding: S3M / IT letter
-- codes (A = 1) with the IT volume column, or MOD / XM numbers. Ported from OpenMPT's ModCommand helpers
-- (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, CPattern::WriteEffect; BSD licence,
-- licenses/openmpt-LICENSE.txt), reduced to what the engine plays.
-- codecs/audio/Tracker/Load: helpers mapping other tracker formats' effects onto the engine's S3M / IT or MOD / XM families.
-- Ported from OpenMPT's ModCommand helpers (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight,
-- CPattern::WriteEffect; BSD licence, licenses/openmpt-LICENSE.txt).
local Err = require("@rosetta/core/Err")
local Player = require("@rosetta/codecs/audio/Tracker/Player")
local Pcm = require("@rosetta/codecs/audio/Tracker/Pcm")
@@ -14,7 +11,6 @@ local Load = {}
local EXT = Player.EXT
-- the S3M / IT letter code of each effect name (engine extension effects included)
local IT: { [string]: number } = {
speed = 1,
jump = 2,
@@ -67,7 +63,7 @@ end
local GLOBAL = { jump = true, ["break"] = true, speed = true, tempo = true, globalvol = true, globalvolslide = true }
-- isGlobal(name, param) -> the effect acts on the whole song (OpenMPT's IsGlobalCommand)
-- OpenMPT's IsGlobalCommand
function Load.isGlobal(name: string?, param: number): boolean
if name == nil then
return false
@@ -84,7 +80,7 @@ function Load.isGlobal(name: string?, param: number): boolean
return false
end
-- modCommand(cmd, param) -> name?, param: a MOD / XM effect number (0..F, XM letters 16..) by name (ConvertModCommand)
-- OpenMPT's ConvertModCommand
local MODFX: { [number]: string } = {
[0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [5] = "toneportavol",
[6] = "vibratovol", [7] = "tremolo", [8] = "panning8", [9] = "offset", [10] = "volslide", [11] = "jump",
@@ -104,8 +100,7 @@ function Load.modCommand(cmd: number, param: number): (string?, number)
return n, param
end
-- itVolume(name, param, force) -> the IT volume-column byte + 1 (the engine's coding) for an effect that fits there,
-- or nil (OpenMPT's ConvertToVolCommand; force: fit it with some loss of precision)
-- OpenMPT's ConvertToVolCommand (force: fit with some loss of precision)
function Load.itVolume(name: string?, param: number, force: boolean): number?
if name == "volume" then
return math.min(param, 64) + 1
@@ -159,8 +154,6 @@ function Load.itVolume(name: string?, param: number, force: boolean): number?
return nil
end
-- itEffect(name, param) -> effect code, param in S3M / IT coding (0, 0 for none or an effect the family lacks; MOD's
-- extended E commands become their S3M equivalents)
function Load.itEffect(name: string?, param: number): (number, number)
if name == nil then
return 0, 0
@@ -191,9 +184,7 @@ function Load.itEffect(name: string?, param: number): (number, number)
return code, param
end
-- fillTwo(name1, param1, name2, param2, lowResOffset?) -> volume byte (engine IT coding, 0 none), effect name, param,
-- lost name?, lost param: two effects of one cell into the IT volume column and the effect column, keeping the
-- heavier one when both cannot fit (OpenMPT's FillInTwoCommands)
-- OpenMPT's FillInTwoCommands
function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number, string?, number, string?, number)
if e1 ~= nil and e1 == e2 then
e2 = nil -- the same effect twice: keep one (most are absolute; slides are kept once too, a simplification)
@@ -215,10 +206,7 @@ function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number
return 0, e2, p2, e1, p1
end
-- writeEffect(m, pattern (0-based), row, fx, param, retry?, channel?, multiple?) -> true when written: puts an effect
-- into a free effect slot of the row (any channel, or the given 1-based one); none free: the next row (retry "next") or
-- the previous one ("prev"). The same effect already on the row counts as written unless multiple (OpenMPT's
-- CPattern::WriteEffect).
-- OpenMPT's CPattern::WriteEffect
function Load.writeEffect(m: any, pattern: number, row: number, fx: number, param: number, retry: string?, channel: number?, multiple: boolean?): boolean
local p = m.patterns[pattern + 1]
if not p then
@@ -261,9 +249,6 @@ function Load.writeEffect(m: any, pattern: number, row: number, fx: number, para
return false
end
-- readSample(buf, offset, frames, spec, sample, budget) -> true | nil, Err: decodes raw PCM (codecs/audio/Tracker/Pcm
-- spec) at the absolute buffer offset into the sample (data, length, bits, channels). A short file keeps the frames
-- that are there (end = the buffer's length, or spec.limit). budget = { left = f32 bytes still allowed } (maxBytes).
function Load.readSample(buf: buffer, offset: number, frames: number, spec: any, s: any, budget: { left: number }): (boolean?, Err.Err?)
local nch = spec.channels or 1
local bps = spec.bits // 8
@@ -282,7 +267,7 @@ function Load.readSample(buf: buffer, offset: number, frames: number, spec: any,
return true, nil
end
-- bcd(n) -> n as the two decimal digits S3M / MOD pattern breaks store (0..99)
-- S3M / MOD pattern breaks store the row as two decimal digits
function Load.bcd(n: number): number
n = math.clamp(math.floor(n), 0, 99)
return (n // 10) * 16 + n % 10
+2 -8
View File
@@ -1,17 +1,12 @@
--!strict
--!native
-- codecs/audio/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample
-- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole
-- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code).
--
-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/audio/Tracker)
-- validates the sample buffers' sizes.
-- codecs/audio/Tracker/Mixer: tracker voice mixing (loops, IT sustain loops, IT two-pole resonant filter, click ramps).
-- No third-party code.
local floor, ceil, min = math.floor, math.ceil, math.min
local readf32, writef32 = buffer.readf32, buffer.writef32
local Mixer = {}
-- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance)
local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number)
local data: buffer = v.data
local nch = v.nch
@@ -161,7 +156,6 @@ local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: bo
local _ = ramp
end
-- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions
function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean)
for _, v in st.voices do
if v.active and v.data then
+4 -10
View File
@@ -1,9 +1,7 @@
--!strict
--!native
-- codecs/audio/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned,
-- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back.
--
-- Never throws: reads past the source are refused up front (decode returns nil).
-- codecs/audio/Tracker/Pcm: raw 8 / 16-bit tracker sample data (signed / unsigned, XM / IT 2.15 delta coding,
-- interleaved or planar stereo) <-> f32.
local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16
local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16
local floor = math.floor
@@ -11,20 +9,18 @@ local floor = math.floor
local Pcm = {}
export type Spec = {
bits: number, -- 8 | 16
bits: number,
signed: boolean,
delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag)
channels: number?, -- 1 (default) | 2
channels: number?,
planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved
bigEndian: boolean?,
}
-- bytes(frames, spec) -> the size of the raw data
function Pcm.bytes(frames: number, spec: Spec): number
return frames * (spec.channels or 1) * (spec.bits // 8)
end
-- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short
function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer?
local nch = spec.channels or 1
local bps = spec.bits // 8
@@ -76,7 +72,6 @@ function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffe
return out
end
-- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar)
function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer
local nch = spec.channels or 1
local bps = spec.bits // 8
@@ -118,7 +113,6 @@ function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer
return out
end
-- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16
function Pcm.bitsNeeded(samples: buffer): number
for i = 0, buffer.len(samples) // 4 - 1 do
local x = readf32(samples, i * 4) * 128
+13 -53
View File
@@ -1,14 +1,8 @@
--!strict
--!native
-- codecs/audio/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders,
-- speed / tempo, every effect of the four formats (interpreted per format family: ProTracker / FastTracker 2 numeric
-- effects, ScreamTracker 3 / Impulse Tracker letter effects), instruments with volume / panning / pitch envelopes,
-- fadeout and auto-vibrato, IT new note actions (background voices), duplicate checks and resonant filters, and song
-- end / loop detection. Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes,
-- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/audio/Tracker/Mixer.
--
-- Never throws: the module is validated by codecs/audio/Tracker before a player is made, and every table lookup here is
-- guarded.
-- codecs/audio/Tracker/Player: the tracker sequencer for the MOD, S3M, XM and IT effect families.
-- Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes, ST3 TECH.DOC, ITTECH.TXT);
-- no third-party code.
local Tables = require("@rosetta/codecs/audio/Tracker/Tables")
local wave64, autoWave = Tables.wave64, Tables.autoWave
@@ -23,8 +17,6 @@ local MOD, S3M, XM, IT = 1, 2, 3, 4
Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT
local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT }
-- engine extension effects: format-specific commands of the other tracker formats, in any family (see
-- codecs/audio/Tracker)
local EXT = {
NOTE_SLIDE_UP = 0x40,
NOTE_SLIDE_DOWN = 0x41,
@@ -37,9 +29,8 @@ local EXT = {
}
Player.EXT = EXT
local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions
local BG_VOICES = 64
-- ------------------------------------------------------------------------------------------------ state
local function newVoice(): any
return {
active = false,
@@ -100,8 +91,8 @@ local function newVoice(): any
tremorMute = false,
surround = false,
rampN = 0,
owner = 0, -- the channel whose foreground voice this is (0: free or background)
order = 0, -- allocation age
owner = 0,
order = 0,
}
end
@@ -126,7 +117,6 @@ local function newChannel(i: number, pan: number, vol: number): any
fx = 0,
param = 0,
vcmd = 0,
-- memories
mPortaUp = 0,
mPortaDn = 0,
mFineUp = 0,
@@ -186,15 +176,14 @@ local function newChannel(i: number, pan: number, vol: number): any
muted = false,
triggered = false,
autoPorta = 0, -- auto portamento (EXT 0x44 / 0x45): period units per tick, + down
autoTone = false, -- flags.autoTonePorta: the tone portamento keeps running
autoTone = false,
hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669)
slideCount = 0, -- note slides: ticks to the next step
slideCount = 0,
mNoteSlide = 0,
tonePortaRow = false,
}
end
-- new(module, opts) -> player state (module validated by the caller)
function Player.new(m: any, sampleRate: number, opts: any): any
local fmt = FAMILY[m.engine or m.format] or MOD
local flags = m.flags
@@ -213,8 +202,8 @@ function Player.new(m: any, sampleRate: number, opts: any): any
compatG = m.flags.compatGxx or false,
fastSlides = flags.fastSlides or false,
amigaLimits = flags.amigaLimits or false,
ptPeriods = ptPeriods, -- ProTracker periods (integer table periods, PAL clock)
hz = flags.periods == "hz", -- periods are frequencies in Hz
ptPeriods = ptPeriods,
hz = flags.periods == "hz",
hzScale = if type(flags.hzSlide) == "number" then flags.hzSlide else 1,
hzTone = if type(flags.hzTonePorta) == "number" then flags.hzTonePorta else 1,
fastPortas = flags.fastPortas or false,
@@ -286,8 +275,6 @@ function Player.masterGain(m: any, fmt: number): number
return 2 / clamp(m.channels, 2, 8)
end
-- ------------------------------------------------------------------------------------------------ orders and rows
-- startOrder(st, ord, row): resolve skip markers / the end of the order list; sets st.pat or st.ended
function Player.startOrder(st: any, ord: number, row: number)
local m = st.m
local order = m.order
@@ -357,8 +344,6 @@ local function advanceRow(st: any)
end
end
-- ------------------------------------------------------------------------------------------------ pitch
-- the period of a note for a sample (see codecs/audio/Tracker for the two period spaces)
local function notePeriod(st: any, note: number, smp: any, ft: number?): (number, number)
local base, ref, tr
if st.fmt == MOD or st.fmt == XM then
@@ -412,8 +397,7 @@ local function clampPeriod(st: any, c: any)
end
end
-- slide(st, c, units): a pitch slide in period units (positive: down; 4 per effect unit); in Hz mode the frequency
-- moves units * hzSlide Hz the other way
-- pitch slides in period units (positive: down; 4 per effect unit); in Hz mode the frequency moves units * hzSlide Hz the other way
local function slide(st: any, c: any, units: number)
if st.hz then
c.period -= units * st.hzScale
@@ -423,7 +407,6 @@ local function slide(st: any, c: any, units: number)
clampPeriod(st, c)
end
-- ------------------------------------------------------------------------------------------------ voices
local function allocVoice(st: any): any
local best, bestScore = nil, math.huge
for _, v in st.voices do
@@ -441,7 +424,6 @@ local function allocVoice(st: any): any
best.active = false
return best
end
-- every voice is busy in the foreground (more channels than voices): reuse an inactive one anyway
for _, v in st.voices do
if not v.active then
local c = st.chans[v.owner]
@@ -451,7 +433,7 @@ local function allocVoice(st: any): any
return v
end
end
return st.voices[1] -- unreachable: there are more voices than channels
return st.voices[1]
end
local function keyOff(st: any, v: any)
@@ -492,7 +474,6 @@ local function cutVoice(v: any)
end
end
-- start(st, c, smp, smpIdx, ins, insIdx, note, period, base, offset): a fresh voice for channel c
local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: any)
local v = c.voice
if v == nil or v.bg then
@@ -541,7 +522,6 @@ end
-- IT new note actions on the channel's current voice (and duplicate checks on all its voices)
local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: number, smpIdx: number)
-- duplicate check: voices of this channel playing the same instrument
if ins and ins.dct and ins.dct > 0 then
for _, u in st.voices do
if u.active and u.chan == c.idx and u.insIdx == insIdx then
@@ -582,7 +562,6 @@ local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: nu
end
end
-- ------------------------------------------------------------------------------------------------ triggering
local function isPorta(st: any, fx: number, vcmd: number): boolean
local f = st.fmt
if f == MOD then
@@ -594,7 +573,6 @@ local function isPorta(st: any, fx: number, vcmd: number): boolean
return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203)
end
-- the sample and real note for an instrument number + note
local function resolve(st: any, insIdx: number, note: number): (any, number, any, number)
local m = st.m
if st.insMode then
@@ -668,7 +646,6 @@ local function sampleOffset(st: any, c: any, v: any)
end
end
-- trigger(st, c, note, insIdx, vcmd): the note / instrument / volume column part of a cell
local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: number)
local f = st.fmt
local m = st.m
@@ -802,7 +779,6 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb
end
end
-- ------------------------------------------------------------------------------------------------ effect helpers
local function volSlideMod(c: any, param: number)
local x, y = param // 16, param % 16
if x > 0 then
@@ -858,8 +834,7 @@ local function retrigVolume(c: any, x: number)
c.vol = clamp(c.vol, 0, 64)
end
-- S3M / IT D-style slide of a value: returns the new value (fine parts only on tick 0, normal parts on other ticks;
-- fast: normal parts on tick 0 too)
-- S3M / IT D-style slide: fine parts only on tick 0, normal parts on other ticks (fast: normal parts on tick 0 too)
local function dSlide(value: number, param: number, tick: number, fast: boolean, hi: number): number
local x, y = param // 16, param % 16
if y == 0xF and x > 0 then
@@ -884,7 +859,6 @@ local function dSlide(value: number, param: number, tick: number, fast: boolean,
return value
end
-- ------------------------------------------------------------------------------------------------ MOD / XM effects
local function fxModXm(st: any, c: any, tick: number)
local fx, param = c.fx, c.param
local xm = st.fmt == XM
@@ -1198,7 +1172,6 @@ local function volColXm(st: any, c: any, tick: number)
end
end
-- ------------------------------------------------------------------------------------------------ S3M / IT effects
-- the parameter after memory: IT keeps one memory per effect group, ST3 one memory for most effects
local function mem(st: any, c: any, field: string, param: number): number
if st.fmt == S3M then
@@ -1606,8 +1579,6 @@ local function volColIt(st: any, c: any, tick: number)
end
end
-- ------------------------------------------------------------------------------------------------ extension effects
-- the engine extension effects (EXT, codes 0x40..) and the auto slides, in any family
local function fxExt(st: any, c: any, tick: number)
local fx, param = c.fx, c.param
if fx >= EXT.NOTE_SLIDE_UP and fx <= EXT.NOTE_SLIDE_DOWN_RETRIG then
@@ -1666,7 +1637,6 @@ local function fxExt(st: any, c: any, tick: number)
end
end
-- ------------------------------------------------------------------------------------------------ rows and ticks
local function noteDelayOf(st: any, fx: number, param: number): number
if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then
return param % 16
@@ -1764,7 +1734,6 @@ local function processRow(st: any)
end
local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean): (number, number, boolean)
-- returns value, next position, ended
local ticks, values = env.ticks, env.values
local n = #ticks
if n == 0 then
@@ -1805,7 +1774,6 @@ local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean
return value, nextPos, ended
end
-- per-tick voice update: envelopes, fadeout, auto-vibrato, final frequency, gains and filter
local function updateVoice(st: any, v: any)
local ins = v.ins
local it = st.fmt == IT
@@ -1876,7 +1844,6 @@ local function updateVoice(st: any, v: any)
end
v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256
end
-- frequency
local P = v.periodOut + avDelta
local freq
if st.hz then
@@ -1890,7 +1857,6 @@ local function updateVoice(st: any, v: any)
freq *= 2 ^ (envPitch / 24)
end
v.inc = freq / st.sr
-- volume
local smp = v.smp
local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128
-- channel, sample and instrument global volumes (64 / 64 / 128 unless an IT file, or another format's loader,
@@ -1899,7 +1865,6 @@ local function updateVoice(st: any, v: any)
if v.tremorMute then
vol = 0
end
-- panning
local pan = v.pan
if it and ins and (ins.pps or 0) ~= 0 then
pan = clamp(pan + ((v.patNote or v.note) - (ins.ppc or 60) - 1) * ins.pps / 2, 0, 256)
@@ -1921,7 +1886,6 @@ local function updateVoice(st: any, v: any)
v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256
end
v.rampN = st.ramp
-- IT resonant filter
local cutoff = v.cutoff
if filterEnv ~= nil or cutoff < 127 or v.reso > 0 then
local cc = cutoff
@@ -1946,7 +1910,6 @@ local function updateVoice(st: any, v: any)
end
end
-- tick(st) -> frames to mix for this tick (0 when the song ended)
function Player.tick(st: any): number
if st.ended then
return 0
@@ -1959,7 +1922,6 @@ function Player.tick(st: any): number
return 0
end
if st.visited[key] then
-- looping on: forget the song so far, keep playing
table.clear(st.visited)
end
st.fineDelay = 0
@@ -1983,7 +1945,6 @@ function Player.tick(st: any): number
if st.ended then
return 0
end
-- channel -> foreground voice
for i = 1, st.nch do
local c = st.chans[i]
local v = c.voice
@@ -2009,7 +1970,6 @@ function Player.tick(st: any): number
end
-- frames for this tick: 2.5 / tempo seconds, truncated per tick (as OpenMPT does)
local frames = floor(st.sr * 2.5 / max(1, st.tempo))
-- advance
st.tick += 1
if st.tick >= st.speed + st.fineDelay then
st.tick = 0
+5 -17
View File
@@ -1,15 +1,12 @@
--!strict
--!native
-- codecs/audio/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the
-- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M
-- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker
-- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT).
-- codecs/audio/Tracker/Tables: tracker lookup tables, from the public format documents (ProTracker 2.3 effect docs,
-- FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT).
local Tables = {}
-- the ProTracker half-sine (32 steps, 0..255)
local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 }
-- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic)
local RANDOM: { number } = {}
do
local s = 12345
@@ -31,8 +28,6 @@ function Tables.wave64(kind: number, pos: number): number
return if p >= 32 then -v else v
end
-- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up.
-- IT: 0 sine, 1 ramp down, 2 square, 3 random.
local SINE256: { number } = {}
for i = 0, 255 do
SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5)
@@ -59,9 +54,7 @@ function Tables.autoWave(kind: number, pos: number, it: boolean): number
return SINE256[p + 1]
end
-- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers:
-- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at
-- its base rate (8363 Hz).
-- ProTracker periods, finetune 0, C-0 .. B-4; note 1 = C-0 (FT2 numbering), C-2 (428) = note 49 plays at 8363 Hz
local PERIODS = {
3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812,
1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906,
@@ -73,12 +66,10 @@ local PERIODS = {
Tables.PERIODS = PERIODS
Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1)
-- periodToNote(period) -> note (1..120), 0 for period 0
function Tables.periodToNote(period: number): number
if period <= 0 then
return 0
end
-- exact match first, then the nearest note on a log scale
for i = 1, #PERIODS do
if PERIODS[i] == period then
return i + Tables.PERIOD_FIRST_NOTE - 1
@@ -88,7 +79,6 @@ function Tables.periodToNote(period: number): number
return math.clamp(n, 1, 120)
end
-- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends
function Tables.noteToPeriod(note: number): number
local i = note - Tables.PERIOD_FIRST_NOTE + 1
if i >= 1 and i <= #PERIODS then
@@ -104,14 +94,12 @@ Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 }
Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 }
Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 }
-- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate
-- (FT2 / ST3 period units, 4x ProTracker's)
-- frequency = AMIGA / period; period 1712 plays an 8363 Hz sample at its base rate (FT2 / ST3 units, 4x ProTracker's)
Tables.AMIGA = 8363 * 1712
-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz)
Tables.AMIGA_PAL = 7093789.2 / 2 * 4
-- st2Tempo(byte) -> speed, tempo: a Scream Tracker 2 tempo byte (high nibble ticks per row, low nibble a fine factor)
-- as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at its 23863 Hz mixing rate, as a fractional BPM)
-- Scream Tracker 2 tempo byte as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at 23863 Hz, as a fractional BPM)
local ST2_FACTOR = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 }
function Tables.st2Tempo(byte: number): (number, number)
local hi, lo = byte // 16, byte % 16
+18 -90
View File
@@ -1,67 +1,18 @@
--!strict
-- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders
-- that map other trackers onto those four effect families (music/mtm, 669, stm, ult, okt, med, ptm, far; helpers in
-- codecs/audio/Tracker/Load). The loaders read their files into one Module structure (below); render(module, opts) plays any of them through the standard audio
-- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM
-- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests.
-- codecs/audio/Tracker: the shared tracker engine behind music/mod, s3m, xm and it, and the formats mapped onto them.
-- Written from the format documents (ProTracker 2.3, the XM spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp /
-- OpenMPT were used only as reference players for tests.
--
-- local Tracker = require("@rosetta/codecs/audio/Tracker")
-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder
-- local seconds = Tracker.duration(module) -- one pass, song loops detected
-- Pattern cells are 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 = C-0; C-4 = 49
-- plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5 speed), 253 note fade, 254 note cut,
-- 255 key off. MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored; S3M / IT effects 1..26 (A = 1),
-- S3M volume 0 = none else volume + 1, IT volume byte + 1 (0 = none). Extension effects (Tracker.EXT): 0x40 / 0x41 note
-- slide up / down, 0x42 / 0x43 with retrigger (param = ticks per step << 4 | semitones), 0x44 / 0x45 auto portamento
-- up / down (669), 0x46 frequency adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED).
--
-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file):
-- format the file format ("mod", "s3m", "xm", "it", "mtm", "669", ...): what the module was read from
-- engine "mod" | "s3m" | "xm" | "it": the effect family the engine plays (default: format, so the four
-- families need no engine field). Other formats map their effects onto one family (music/mtm: "xm",
-- music/669: "s3m", ...) and set the quirks they need in flags.
-- preamp optional 0..256: the output gain as OpenMPT's sample pre-amp (gain = preamp / 128); default per family
-- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s)
-- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume)
-- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index)
-- linear linear frequency slides (XM / IT flag) or Amiga periods
-- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column
-- is a sample number (MOD, S3M, IT sample mode)
-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides: also on tick 0; any family),
-- amigaLimits (MOD), and the quirks of the other formats (any family):
-- periods = "amiga" (ProTracker period table + PAL clock, as MOD) | "hz" (periods are frequencies in
-- Hz: 669, FAR; slides move hzSlide Hz per unit, tone portamento hzSlide * hzTonePorta),
-- fastPortas (slides on tick 0 too), autoTonePorta (a tone portamento keeps running on later rows),
-- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo),
-- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels),
-- envRowHold (MED: envelopes do not advance on a row's first tick) }
-- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width,
-- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool }
-- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels
-- cells of 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 =
-- C-0; C-4 = 49 plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5
-- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the
-- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored;
-- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1
-- (0 = none). Engine extension effects (any family, for the other formats): Tracker.EXT (0x40 note
-- slide up, 0x41 down, 0x42 / 0x43 the same with retrigger: param = ticks per step << 4 | semitones;
-- 0x44 / 0x45 auto portamento up / down (669: every tick until another effect), 0x46 frequency
-- adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED)).
-- Tracker.cell / Tracker.setCell read and write cells.
-- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16,
-- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong),
-- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil),
-- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth /
-- vibRate (IT auto-vibrato) }
-- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note },
-- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut,
-- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off,
-- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre),
-- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) }
-- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart,
-- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) }
--
-- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), frequency = base * 2^(-P/768).
-- Amiga: P = 1712 * 8363 / base * 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add
-- 4 per effect unit in both). MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT:
-- base = c5speed, ref 61.
--
-- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects
-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation.
-- Pitch: linear P = (ref - note) * 64 - transpose, frequency = base * 2^(-P/768). Amiga: P = 1712 * 8363 / base *
-- 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add 4 per effect unit in both).
-- MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT: base = c5speed, ref 61.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Player = require("@rosetta/codecs/audio/Tracker/Player")
@@ -86,38 +37,32 @@ export type Envelope = {
susEnd: number,
carry: boolean?,
filter: boolean?,
raw: any?, -- format-specific fields kept for a faithful re-save (XM)
raw: any?,
}
export type Pattern = { rows: number, data: buffer }
export type RenderOptions = {
sampleRate: number?, -- default 44100
interpolation: ("linear" | "none")?, -- default "linear"
stereoSeparation: number?, -- 0..200 % (default 100: the panning as stored; 200 doubles every distance from centre)
loop: boolean?, -- keep playing past the song's end (frames / duration still give one pass); default false
maxDuration: number?, -- seconds; the render stops there (default 3600)
sampleRate: number?,
interpolation: ("linear" | "none")?,
stereoSeparation: number?,
loop: boolean?,
maxDuration: number?,
}
local CELL = 5
-- engine extension effects (see the Module notes above)
Tracker.EXT = Player.EXT
-- st2Tempo(byte) -> speed, tempo (BPM): a Scream Tracker 2 tempo byte
Tracker.st2Tempo = Tables.st2Tempo
local FAMILIES = { mod = true, s3m = true, xm = true, it = true }
-- family(module) -> "mod" | "s3m" | "xm" | "it" | nil: the effect family a module plays as
function Tracker.family(m: any): string?
local f = m.engine or m.format
return if type(f) == "string" and FAMILIES[f] then f else nil
end
-- ------------------------------------------------------------------------------------------------ constructors
-- newModule(format, channels, engine?) -> an empty Module (no patterns / samples) with the defaults of the effect family
-- (engine, default format)
function Tracker.newModule(format: string, channels: number, engine: string?): any
local fam = engine or format
local m = {
@@ -156,12 +101,10 @@ function Tracker.newModule(format: string, channels: number, engine: string?): a
return m
end
-- newPattern(rows, channels) -> an empty Pattern
function Tracker.newPattern(rows: number, channels: number): Pattern
return { rows = rows, data = buffer.create(rows * channels * CELL) }
end
-- newSample() -> an empty Sample
function Tracker.newSample(name: string?): any
return {
name = name or "",
@@ -192,7 +135,6 @@ function Tracker.newEnvelope(): Envelope
return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 }
end
-- newInstrument() -> an Instrument mapping every note to sample 0 (none)
function Tracker.newInstrument(name: string?): any
local sm, nm = table.create(120, 0), table.create(120, 0)
for i = 1, 120 do
@@ -222,8 +164,6 @@ function Tracker.newInstrument(name: string?): any
}
end
-- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based,
-- channel 1-based); nil when out of range
function Tracker.cell(m: any, pattern: number, row: number, channel: number): (number?, number, number, number, number)
local p = m.patterns[pattern + 1]
if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then
@@ -234,7 +174,6 @@ function Tracker.cell(m: any, pattern: number, row: number, channel: number): (n
return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4)
end
-- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range)
function Tracker.setCell(m: any, pattern: number, row: number, channel: number, note: number, ins: number, vol: number, fx: number, param: number): boolean
local p = m.patterns[pattern + 1]
if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then
@@ -250,7 +189,6 @@ function Tracker.setCell(m: any, pattern: number, row: number, channel: number,
return true
end
-- ------------------------------------------------------------------------------------------------ validation
local function num(v: any, lo: number, hi: number): boolean
return type(v) == "number" and v == v and v >= lo and v <= hi
end
@@ -312,8 +250,6 @@ local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number,
return s, e, t
end
-- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and
-- numbers into range (in place)
function Tracker.validate(m: any): (boolean?, Err.Err?)
if type(m) ~= "table" then
return nil, Err.new(Err.ARG, "not a module")
@@ -420,11 +356,9 @@ function Tracker.validate(m: any): (boolean?, Err.Err?)
return true, nil
end
-- ------------------------------------------------------------------------------------------------ rendering
local Decoder = {}
Decoder.__index = Decoder
-- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err
function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?)
local ok, err = Tracker.validate(m)
if not ok then
@@ -451,7 +385,6 @@ local function newPlayer(self: any)
self.pos = 0
end
-- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err
function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
local o: RenderOptions = opts or {}
local sr = o.sampleRate or 44100
@@ -482,13 +415,11 @@ function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?
return self :: any, nil
end
-- the Module method: module:render(opts)
function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder
local dec = Tracker.render(self, opts)
return dec :: any
end
-- run(self, out?, n) -> frames produced (out nil: advance without mixing)
local function run(self: any, out: buffer?, n: number): number
local st = self.st
local done = 0
@@ -515,7 +446,6 @@ local function run(self: any, out: buffer?, n: number): number
return done
end
-- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the end)
function Decoder.read(self: any, n: number, out: buffer?): (buffer, number)
n = math.max(0, math.floor(tonumber(n) or 0))
local o = out
@@ -528,7 +458,6 @@ function Decoder.read(self: any, n: number, out: buffer?): (buffer, number)
return o :: buffer, got
end
-- seek(seconds): replays the song silently up to the position (sample positions included)
function Decoder.seek(self: any, seconds: number)
local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate))
newPlayer(self)
@@ -539,7 +468,6 @@ function Decoder.seek(self: any, seconds: number)
break
end
end
-- the gains ramp in from silence after a seek
for _, v in self.st.voices do
v.gl, v.gr = 0, 0
end
+7 -16
View File
@@ -1,10 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Tta/Decode: one TTA1 frame -> samples. Written from the TTA1 format description (the True Audio
-- format notes: adaptive Rice codes with two running sums per channel, the order-8 sign-LMS "hybrid" filter, the
-- first-order fixed predictor, inter-channel decorrelation, a CRC-32 per frame); no libtta / ffmpeg code. Checked
-- bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). Never throws: returns nil, message.
-- codecs/audio/Tta/Decode: one TTA1 frame -> samples, from the TTA1 format description; no libtta / ffmpeg code.
-- Bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py).
local Crc32 = require("@rosetta/core/Crc32")
local readu8, readu32 = buffer.readu8, buffer.readu32
@@ -16,11 +14,10 @@ local Decode = {}
local TWO31, TWO32 = 2147483648, 4294967296
local INV31 = 1 / TWO31
local PAD = 16
local P2: { number } = table.create(40, 0) -- P2[k + 1] = 2^k
local P2: { number } = table.create(40, 0)
for i = 0, 39 do
P2[i + 1] = 2 ^ i
end
-- ONES[b + 1]: the trailing 1 bits of the byte b
local ONES: { number } = table.create(256, 0)
for b = 0, 255 do
local n, v = 0, b
@@ -31,7 +28,6 @@ for b = 0, 255 do
ONES[b + 1] = n
end
-- longUnary(S, pos, lim) -> the count of 1 bits from pos, the position after the 0 | nil (past lim)
local function longUnary(S: buffer, pos: number, lim: number): (number?, number)
local unary = 0
while pos <= lim do
@@ -48,9 +44,8 @@ end
export type State = {
channels: number,
bytes: number, -- 1 .. 3
S: buffer, -- the frame's bits (+ PAD zeros)
-- per channel: rice k0, k1, sum0, sum1; filter error, Q (weights), X (steps), L (delay line) x 8; the last value
bytes: number,
S: buffer,
R: { number },
Q: { number },
X: { number },
@@ -75,8 +70,6 @@ function Decode.state(channels: number, bytes: number): State
}
end
-- frame(st, buf, o, len, n, P) -> n | nil, message: the frame of len bytes at o (its CRC-32 last) holding n samples per
-- channel, into P (interleaved integers)
function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, P: { number }): (number?, string?)
if len < 4 then
return nil, "truncated frame"
@@ -105,15 +98,14 @@ function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number,
Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0
end
end
local pos = 0 -- bit position
local pos = 0
local lim = dlen * 8
local c = 0 -- the channel of the sample at idx
local c = 0
for idx = 1, n * C do
do
if pos > lim then
return nil, "truncated frame"
end
-- the unary prefix: 1 bits up to a 0 (a run past one byte goes to longUnary)
local unary
local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7))
local ones = ONES[band(w, 255) + 1]
@@ -222,7 +214,6 @@ function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number,
L[fb + 6] = n6
L[fb + 7] = n7
L[fb + 8] = value
-- the fixed predictor
value += (last[c + 1] * (pk - 1)) // pk
last[c + 1] = value
cur[c + 1] = value
+5 -16
View File
@@ -1,15 +1,7 @@
--!strict
-- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description
-- (the 22-byte header with its CRC-32, the seek table of frame sizes with its CRC-32, frames of 256 / 245 seconds);
-- no libtta / ffmpeg code (those are LGPL). The frame decoder is codecs/audio/Tta/Decode. Supports format 1 (plain
-- PCM), 8 / 16 / 24 bits, any channel count, the header / seek table / frame CRCs. Not supported: format 2
-- (password-protected: UNSUPPORTED), TTA2.
--
-- local info, err = Tta.info(buf, at, limit) -- the header at `at` (after any ID3v2 tag) + the frame table
-- local dec = Tta.decoder(info)
-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved integers)
--
-- Never throws: bad data returns nil, Err.
-- codecs/audio/Tta: the TTA1 (True Audio) lossless codec.
-- From the TTA1 format description (22-byte header and seek table with CRC-32s, frames of 256 / 245 seconds); no libtta /
-- ffmpeg code (LGPL). Format 2 (password) is UNSUPPORTED.
local Err = require("@rosetta/core/Err")
local Crc32 = require("@rosetta/core/Crc32")
local Decode = require("@rosetta/codecs/audio/Tta/Decode")
@@ -21,14 +13,13 @@ export type Info = {
channels: number,
bitsPerSample: number,
sampleRate: number,
samples: number, -- per channel
samples: number,
frameLength: number, -- samples per frame (256 * rate / 245)
frames: number,
offsets: { number }, -- each frame's byte offset
offsets: { number },
sizes: { number },
}
-- info(buf, at, limit) -> Info | nil, Err: the TTA1 header at byte `at`
function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?)
if at + 22 > limit then
return nil, Err.new(Err.TRUNCATED, "truncated header")
@@ -86,7 +77,6 @@ function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?)
return info, nil
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Decoder = {
info: Info,
pcm: { number },
@@ -112,7 +102,6 @@ local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?)
return got, nil
end
-- decoder(info, limit) -> Decoder (limit: the end of the file data)
function Tta.decoder(info: Info, limit: number): Decoder
return {
info = info,
+12 -24
View File
@@ -1,14 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3):
-- reading a codebook from the setup header (ordered / sparse length lists, lookup types 1 and 2, float32_unpack),
-- the codeword assignment, and Huffman / VQ decoding. Ported from stb_vorbis 1.22 (public domain / MIT; see
-- licenses/stb_vorbis-LICENSE.txt): compute_codewords' lowest-free-leaf assignment, lookup1_values; the decode side
-- is a fast table (up to 10 bits) plus a binary tree for longer codes instead of stb's sorted binary search.
--
-- Never throws. Reading past the packet end gives zero bits and sets br.eop (the spec's end-of-packet condition);
-- an invalid codeword also sets eop and decodes to -1.
-- codecs/audio/Vorbis/Codebook: the Vorbis LSB-first bit reader and codebooks (Vorbis I spec sections 2 and 3).
-- Ported from stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). Reading past the packet end gives
-- zero bits and sets eop (the spec's end-of-packet condition); an invalid codeword also sets eop and decodes to -1.
local Codebook = {}
local readu8 = buffer.readu8
@@ -19,22 +14,20 @@ for i = 0, 40 do
POW[i + 1] = 2 ^ i
end
-- ------------------------------------------------------------------------------------------------ bit reader
export type Br = {
buf: buffer,
pos: number, -- next byte to load
pos: number,
limit: number,
acc: number, -- loaded, unread bits (LSB first)
acc: number,
cnt: number,
pad: number, -- how many of the top bits of acc are past the end of the packet
eop: boolean, -- read past the end of the packet
pad: number,
eop: boolean,
}
function Codebook.reader(buf: buffer, offset: number, size: number): Br
return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false }
end
-- bits(br, n) -> the next n (0..32) bits as an unsigned number
local function bits(br: Br, n: number): number
if n == 0 then
return 0
@@ -66,7 +59,7 @@ local function bits(br: Br, n: number): number
end
Codebook.bits = bits
-- ilog(x): the number of bits needed to hold x (0 for x <= 0)
-- ilog (spec 9.2.1)
local function ilog(x: number): number
local n = 0
while x > 0 do
@@ -86,7 +79,6 @@ local function float32Unpack(x: number): number
return if sign then -v else v
end
-- ------------------------------------------------------------------------------------------------ codebooks
export type Book = {
dims: number,
entries: number,
@@ -95,9 +87,9 @@ export type Book = {
fastSym: { number }, -- symbol, or the tree node to continue from
c0: { number }, -- tree: child for bit 0 / 1: > 0 node, < 0 leaf (-symbol - 1), 0 none
c1: { number },
lookup: number, -- 0, 1, 2
vq: { number }?, -- entries * dims values (lookup 1 / 2, expanded)
used: number, -- entries with a codeword
lookup: number,
vq: { number }?,
used: number,
}
local MAX_ENTRIES = 2 ^ 20
@@ -152,7 +144,6 @@ local function build(book: Book, lengths: { number }): string?
available[y + 1] = code + POW[33 - y] + 1
end
end
-- walk the MSB-first code into the tree
local node = 1
for d = 1, len do
local bit = floor(code / POW[33 - d]) % 2
@@ -189,7 +180,6 @@ local function build(book: Book, lengths: { number }): string?
end
end
book.used = used
-- the fast table: every fastBits-bit prefix (read LSB first) walked down the tree
local fb = math.clamp(maxLen, 1, 10)
book.fastBits = fb
local size = POW[fb + 1]
@@ -205,7 +195,7 @@ local function build(book: Book, lengths: { number }): string?
fl[idx + 1], fs[idx + 1] = d, -child - 1
break
elseif child == 0 then
break -- invalid (-1)
break
end
node = child
if d == fb then
@@ -217,7 +207,6 @@ local function build(book: Book, lengths: { number }): string?
return nil
end
-- read(br) -> Book | nil, message: one codebook from the setup header
function Codebook.read(br: Br): (Book?, string?)
if bits(br, 24) ~= 0x564342 then
return nil, "bad codebook sync"
@@ -337,7 +326,6 @@ function Codebook.read(br: Br): (Book?, string?)
return book, nil
end
-- decode(br, book) -> entry number | -1 (end of packet / invalid codeword: br.eop is set)
local function decode(br: Br, book: Book): number
local fb = book.fastBits
local acc, cnt = br.acc, br.cnt
+11 -33
View File
@@ -1,18 +1,10 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1
-- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/audio/Mdct), windowing and overlap-add.
-- Floors, residues and coupling are ported from stb_vorbis 1.22 vorbis_decode_packet_rest / decode_residue /
-- do_floor / draw_line (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). The overlap follows libvorbis:
-- each packet after the first returns the n_prev/4 + n_cur/4 samples between the centres of the two windows, so
-- granule positions count exactly the samples returned (the first packet returns none).
--
-- local st = Packet.new(ident, setup)
-- local n = Packet.decode(st, buf, offset, size) -- frames now in st.out[ch][1 .. n]; -1 = not an audio packet
-- Packet.reset(st) -- forget the overlap (after a seek / a gap)
-- local bs = Packet.blocksize(st, buf, offset, size) -- the packet's block size (0 = not audio), header bits only
-- Never throws: a damaged packet decodes as far as its bits go (the spec's end-of-packet rule) or returns -1.
-- codecs/audio/Vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8).
-- Floors, residues and coupling ported from stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). The
-- overlap follows libvorbis: each packet after the first returns the n_prev/4 + n_cur/4 samples between the two window
-- centres, so granule positions count exactly the samples returned (the first packet returns none).
local Codebook = require("@rosetta/codecs/audio/Vorbis/Codebook")
local Setup = require("@rosetta/codecs/audio/Vorbis/Setup")
local Tables = require("@rosetta/codecs/audio/Vorbis/Tables")
@@ -31,16 +23,16 @@ export type State = {
n1: number,
setup: Setup.Setup,
plans: { [number]: Mdct.Plan },
slopes: { [number]: { number } }, -- rising half-window of overlap length L (= blocksize / 2)
spec: { { number } }, -- per channel: n/2 spectral values (residue, then times the floor)
frame: { { number } }, -- per channel: n windowed time samples
tail: { { number } }, -- per channel: the previous frame from its centre on
slopes: { [number]: { number } },
spec: { { number } },
frame: { { number } },
tail: { { number } },
tailLen: number,
prevN: number, -- the previous block size, 0 = no previous frame
out: { { number } }, -- per channel: the returned samples
prevN: number,
out: { { number } },
finalY: { { number } },
step2: { number },
inter: { number }, -- residue type 2 interleaved scratch
inter: { number },
zero: { boolean },
reallyZero: { boolean },
partClass: { { { number } } },
@@ -101,7 +93,6 @@ function Packet.reset(st: State)
st.tailLen = 0
end
-- blocksize(st, buf, off, size) -> the block size of an audio packet (0 if not audio)
function Packet.blocksize(st: State, b: buffer, off: number, size: number): number
if size < 1 then
return 0
@@ -118,7 +109,6 @@ function Packet.blocksize(st: State, b: buffer, off: number, size: number): numb
return if mode.blockflag == 1 then st.n1 else st.n0
end
-- ------------------------------------------------------------------------------------------------ floor 1
local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number
local dy = y1 - y0
local adx = x1 - x0
@@ -155,7 +145,6 @@ local function drawLine(out: { number }, x0: number, y0: number, x1: number, y1:
end
end
-- decode the floor of one channel into finalY (-1 = unused point); false = this channel is silent
local function floorDecode(st: State, br: Codebook.Br, g: Setup.Floor1, finalY: { number }): boolean
if bits(br, 1) == 0 then
return false
@@ -259,8 +248,6 @@ local function floorCurve(g: Setup.Floor1, finalY: { number }, target: { number
end
end
-- ------------------------------------------------------------------------------------------------ residue
-- add the vectors of one partition to target at offset (0-based) .. offset + psize (bounded by limit)
local function partition(br: Codebook.Br, book: Codebook.Book, target: { number }, offset: number, psize: number, rtype: number, limit: number): boolean
local vq = book.vq
if not vq then
@@ -304,7 +291,6 @@ local function partition(br: Codebook.Br, book: Codebook.Book, target: { number
return true
end
-- decode residue r for the channels `targets` (nil = do not decode) of length n2 each
local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { { number } | false }, ch: number, n2: number)
local books = st.setup.books
local rtype = r.type
@@ -374,7 +360,6 @@ local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: {
classSet += 1
end
end
-- de-interleave into the channels that are decoded
for j = 1, ch do
local t = targets[j]
if t then
@@ -428,8 +413,6 @@ local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: {
end
end
-- ------------------------------------------------------------------------------------------------ packet
-- decode(st, buf, off, size) -> frames returned in st.out (0 for the first packet), -1 for a non-audio / bad packet
function Packet.decode(st: State, b: buffer, off: number, size: number): number
if size < 1 then
return -1
@@ -471,7 +454,6 @@ function Packet.decode(st: State, b: buffer, off: number, size: number): number
local map = setup.mappings[mode.mapping + 1]
local ch = st.channels
local spec, zero, reallyZero = st.spec, st.zero, st.reallyZero
-- floors
for c = 1, ch do
local s = map.mux[c] + 1
local g = setup.floors[map.submapFloor[s] + 1]
@@ -486,7 +468,6 @@ function Packet.decode(st: State, b: buffer, off: number, size: number): number
zero[m], zero[a] = false, false
end
end
-- residues, per submap
for i = 1, map.submaps do
local targets: { { number } | false } = {}
local k = 0
@@ -498,7 +479,6 @@ function Packet.decode(st: State, b: buffer, off: number, size: number): number
end
residue(st, br, setup.residues[map.submapResidue[i] + 1], targets, k, n2)
end
-- inverse coupling
for i = map.couplingSteps, 1, -1 do
local m, a = spec[map.magnitude[i] + 1], spec[map.angle[i] + 1]
for j = 1, n2 do
@@ -520,7 +500,6 @@ function Packet.decode(st: State, b: buffer, off: number, size: number): number
m[j], a[j] = m2, a2
end
end
-- floor curves, IMDCT, windows
local plan = st.plans[n]
local lslope = st.slopes[leftEnd - leftStart]
local rslope = st.slopes[rightEnd - rightStart]
@@ -570,7 +549,6 @@ function Packet.decode(st: State, b: buffer, off: number, size: number): number
end
end
end
-- the new tail: this frame from its centre to the end of its window
local tl = rightEnd - n2
for c = 1, ch do
local tail, fr = st.tail[c], st.frame[c]
+13 -23
View File
@@ -1,10 +1,8 @@
--!strict
--!native
-- codecs/audio/Vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2): identification (channels, rate,
-- bitrates, blocksizes), comment (vendor + user comments -> tags) and setup (codebooks, floors, residues, mappings,
-- modes). Ported from stb_vorbis 1.22 start_decoder (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt).
-- Floor 0 is rejected as unsupported, as stb_vorbis does (no encoder has produced it since 2000).
-- Never throws: every parser returns nil, message on bad data.
-- codecs/audio/Vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2).
-- Ported from stb_vorbis 1.22 start_decoder (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). Floor 0 is
-- rejected as unsupported, as stb_vorbis does.
local Codebook = require("@rosetta/codecs/audio/Vorbis/Codebook")
local Setup = {}
@@ -24,16 +22,16 @@ export type Ident = {
export type Floor1 = {
partitions: number,
partitionClass: { number }, -- 1-based list of class numbers (0-based values)
classDims: { number }, -- [class + 1]
partitionClass: { number },
classDims: { number },
classSubs: { number },
classMaster: { number },
subBooks: { { number } }, -- [class + 1][sub + 1] = book (0-based) or -1
subBooks: { { number } },
multiplier: number,
xlist: { number }, -- [j + 1]
xlist: { number },
values: number,
sorted: { number }, -- point indices (0-based) by increasing x
low: { number }, -- neighbours, [j + 1] (0-based indices)
sorted: { number },
low: { number },
high: { number },
}
@@ -44,16 +42,16 @@ export type Residue = {
partSize: number,
classifications: number,
classbook: number,
books: { { number } }, -- [class + 1][pass + 1] = book or -1
classdata: { { number } }, -- [classbook entry + 1][k + 1] = class
books: { { number } },
classdata: { { number } },
}
export type Mapping = {
submaps: number,
couplingSteps: number,
magnitude: { number }, -- [step + 1] channel (0-based)
magnitude: { number },
angle: { number },
mux: { number }, -- [channel + 1] submap (0-based)
mux: { number },
submapFloor: { number },
submapResidue: { number },
}
@@ -75,7 +73,6 @@ local function isVorbis(b: buffer, o: number, n: number, kind: number): boolean
end
Setup.isVorbis = isVorbis
-- ident(buf, offset, size) -> Ident | nil, message
function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?)
if not isVorbis(b, o, n, 1) then
return nil, "not a Vorbis identification header"
@@ -111,7 +108,6 @@ function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?)
nil
end
-- comment(buf, offset, size) -> vendor, { "KEY=value" } | nil, message
function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?)
if not isVorbis(b, o, n, 3) then
return nil, nil
@@ -148,14 +144,12 @@ function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?)
return vendor, list
end
-- setup(buf, offset, size, ident) -> Setup | nil, message
function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, string?)
if not isVorbis(b, o, n, 5) then
return nil, "not a Vorbis setup header"
end
local br = Codebook.reader(b, o + 7, n - 7)
local channels = id.channels
-- codebooks
local books: { Codebook.Book } = {}
local nbooks = bits(br, 8) + 1
for i = 1, nbooks do
@@ -172,7 +166,6 @@ function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, strin
return nil, "bad time domain transform"
end
end
-- floors
local floors: { Floor1 } = {}
local maxValues = 0
local nfloors = bits(br, 6) + 1
@@ -272,7 +265,6 @@ function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, strin
maxValues = values
end
end
-- residues
local residues: { Residue } = {}
local nres = bits(br, 6) + 1
for i = 1, nres do
@@ -341,7 +333,6 @@ function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, strin
classdata = classdata,
}
end
-- mappings
local mappings: { Mapping } = {}
local nmaps = bits(br, 6) + 1
local chBits = ilog(channels - 1)
@@ -396,7 +387,6 @@ function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, strin
submapResidue = sr,
}
end
-- modes
local modes: { Mode } = {}
local nmodes = bits(br, 6) + 1
for i = 1, nmodes do
+2 -2
View File
@@ -1,6 +1,6 @@
--!strict
-- codecs/audio/Vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification, section 10.1, as in stb_vorbis 1.22,
-- public domain / MIT, licenses/stb_vorbis-LICENSE.txt). 256 values, index = floor value (1-based here).
-- codecs/audio/Vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification section 10.1, as in stb_vorbis 1.22,
-- public domain / MIT, licenses/stb_vorbis-LICENSE.txt).
return table.freeze({
1.0649863e-07, 1.1341951e-07, 1.2079015e-07, 1.2863978e-07, 1.3699951e-07, 1.4590251e-07, 1.5538408e-07, 1.6548181e-07,
1.7623575e-07, 1.8768855e-07, 1.9988561e-07, 2.1287530e-07, 2.2670913e-07, 2.4144197e-07, 2.5713223e-07, 2.7384213e-07,
+2 -4
View File
@@ -1,8 +1,6 @@
--!strict
-- codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup),
-- codebooks (Codebook), audio packets to PCM (Packet: floors 0 / 1, residues 0 / 1 / 2, coupling, the IMDCT through
-- codecs/audio/Mdct) and the shared tables. A Luau port of stb_vorbis 1.22 (public domain / MIT,
-- licenses/stb_vorbis-LICENSE.txt). Ogg Vorbis (pages, granules, seeking) and the encoder are audio/vorbis.
-- codecs/audio/Vorbis: the Vorbis I decoder without its container.
-- A Luau port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt).
local Vorbis = {
Setup = require("@rosetta/codecs/audio/Vorbis/Setup"),
Codebook = require("@rosetta/codecs/audio/Vorbis/Codebook"),
+2 -14
View File
@@ -1,32 +1,21 @@
--!strict
-- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags.
-- Tag keys are lower case everywhere in rosetta (the same names ID3 / MP4 / RIFF INFO map to): title, artist,
-- album, albumartist, date, genre, track, tracktotal, disc, disctotal, comment, composer, ...; TRACKNUMBER becomes
-- track, DISCNUMBER disc, DESCRIPTION comment, other fields their lower-cased name. Repeated fields are joined with
-- "; " in tags; the raw fields stay available (decoders put them in meta.source.comments). Shared so the three
-- formats read and write tags the same way. Never throws.
--
-- local tags, raw = VorbisComment.tags({ "TITLE=x", "TRACKNUMBER=3" }) -- { title = "x", track = "3" }, raw list
-- local fields = VorbisComment.fields(tags) -- sorted { "TITLE=x", "TRACKNUMBER=3" }
-- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value"; Vorbis, Opus, FLAC) <-> Types.Tags.
local VorbisComment = {}
export type Field = { key: string, value: string } -- key as written (upper-cased), value
export type Field = { key: string, value: string }
local TO_TAG: { [string]: string } = { tracknumber = "track", discnumber = "disc", description = "comment" }
local TO_FIELD: { [string]: string } = { track = "TRACKNUMBER", disc = "DISCNUMBER" }
-- tagKey(fieldName) -> the Types.Tags key
function VorbisComment.tagKey(name: string): string
local k = string.lower(name)
return TO_TAG[k] or k
end
-- fieldName(tagKey) -> the Vorbis comment field name
function VorbisComment.fieldName(key: string): string
return TO_FIELD[key] or string.upper(key)
end
-- tags(list of "KEY=value") -> Types.Tags, { Field } (entries without "=" are skipped)
function VorbisComment.tags(comments: { string }): ({ [string]: string }, { Field })
local tags: { [string]: string } = {}
local raw: { Field } = {}
@@ -43,7 +32,6 @@ function VorbisComment.tags(comments: { string }): ({ [string]: string }, { Fiel
return tags, raw
end
-- fields(tags) -> "KEY=value" strings in key order (string keys and values only)
function VorbisComment.fields(tags: { [any]: any }): { string }
local keys = {}
for k, v in tags do
+11 -41
View File
@@ -1,13 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/WavPack/Block: one WavPack 4 / 5 block (one mono or stereo stream of a frame) -> samples. Ported from
-- WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt): unpack.c (the decorrelation passes, joint
-- stereo, the hybrid lossy and hybrid lossless (+ wvc) paths with noise shaping and cross decorrelation, fixup_samples),
-- read_words.c (the median-adaptive entropy decoder: get_words_lossless, get_word, read_code), unpack_floats.c,
-- decorr_utils.c / entropy_utils.c (the metadata) and open_utils.c (metadata parsing, the block checksum). The block
-- CRC (and the wvx CRC) is checked. Not ported: DSD blocks (UNSUPPORTED), pre-4.0 streams, the lossy "mute" heuristics.
-- Never throws: returns nil, message.
-- codecs/audio/WavPack/Block: one WavPack 4 / 5 block (one mono or stereo stream of a frame) -> samples.
-- Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt): unpack.c, read_words.c,
-- unpack_floats.c, decorr_utils.c / entropy_utils.c, open_utils.c. DSD blocks are UNSUPPORTED.
local Tables = require("@rosetta/codecs/audio/WavPack/Tables")
local readu8, readi8, readu16, readi16, readu32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32
@@ -19,11 +15,10 @@ local sign, clamp = math.sign, math.clamp
local Block = {}
local TWO32 = 4294967296
local P2: { number } = table.create(34, 0) -- P2[k + 1] = 2^k
local P2: { number } = table.create(34, 0)
for i = 0, 33 do
P2[i + 1] = 2 ^ i
end
-- ONES[b + 1]: the number of trailing 1 bits of the byte b
local ONES: { number } = table.create(256, 0)
for b = 0, 255 do
local n, v = 0, b
@@ -34,18 +29,15 @@ for b = 0, 255 do
ONES[b + 1] = n
end
-- header flags
local MONO_FLAG, HYBRID, JOINT, CROSS, SHAPE, FLOAT, INT32 = 4, 8, 0x10, 0x20, 0x40, 0x80, 0x100
local HBITRATE, HBALANCE, NEW_SHAPING, FALSE_STEREO, DSD = 0x200, 0x400, 0x20000000, 0x40000000, 0x80000000
local FLOAT_SHIFT_ONES, FLOAT_SHIFT_SAME, FLOAT_SHIFT_SENT, FLOAT_ZEROS_SENT, FLOAT_NEG_ZEROS = 1, 2, 4, 8, 0x10
local PAD = 64 -- zero bytes after each copied bitstream: reads past the end stay in the buffer
local MAX_SAMPLES = 2 ^ 20 -- per block
local MAX_SAMPLES = 2 ^ 20
local D2, D1 = 17, 9 -- the first data index of the work table (stereo / mono): 8 frames of history in front
-- ------------------------------------------------------------------------------------------------ metadata
export type Meta = { [number]: number } -- id -> offset; id + 256 -> byte length
-- meta(buf, p, size) -> Meta | nil, message: the metadata sub-blocks of the block at p (header included in size)
function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?)
local m: Meta = {}
local q, stop = p + 32, p + size
@@ -80,7 +72,6 @@ function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?)
return m, nil
end
-- checksum(buf, p, size, m) -> true | false: the ID_BLOCK_CHECKSUM (when there is one) matches
function Block.checksum(buf: buffer, p: number, m: Meta): boolean
local o = m[0x2F]
if not o then
@@ -102,7 +93,6 @@ function Block.checksum(buf: buffer, p: number, m: Meta): boolean
return readu16(buf, o) == band(csum, 0xFFFF)
end
-- ------------------------------------------------------------------------------------------------ state
export type Reader = { b: buffer, p: number, e: number, n: number }
export type State = { [string]: any }
@@ -130,7 +120,6 @@ function Block.state(): State
}
end
-- open a bitstream: the bytes [o, o + len) copied with PAD zero bytes after them
local function openReader(R: Reader, buf: buffer, o: number, len: number)
if buffer.len(R.b) < len + PAD then
R.b = buffer.create(len + PAD + 1024)
@@ -143,8 +132,6 @@ local function openReader(R: Reader, buf: buffer, o: number, len: number)
R.n = len + PAD
end
-- ------------------------------------------------------------------------------------------------ bit reading
-- bits(R, n) -> the next n (<= 32) bits, LSB first
local function bits(R: Reader, n: number): number
if n <= 0 then
return 0
@@ -152,7 +139,7 @@ local function bits(R: Reader, n: number): number
local p = R.p
local byte = rshift(p, 3)
if byte + 8 > R.n then
R.p = R.e + 1 -- overrun: the caller's end check fails
R.p = R.e + 1
return 0
end
local b = R.b
@@ -170,8 +157,6 @@ local function bit(R: Reader): number
return bits(R, 1)
end
-- trailing(R, max) -> the number of 1 bits from the read position (up to max; a byte at a time), consumed with the 0
-- after them when fewer than max
local function trailing(R: Reader, max: number): number
local c = 0
while c < max do
@@ -193,7 +178,6 @@ local function trailing(R: Reader, max: number): number
c += 8
R.p = p + 8
end
-- (max reached inside a run of 8: give back the extra ones)
R.p -= c - max
return max
end
@@ -210,7 +194,7 @@ local function gamma(R: Reader): number?
return bits(R, c - 1) + P2[c]
end
-- readCode(R, maxcode) -> 0 .. maxcode (read_code)
-- read_code
local function readCode(R: Reader, maxcode: number): number
if maxcode < 2 then
return if maxcode == 1 then bits(R, 1) else 0
@@ -240,16 +224,13 @@ local function onesCount(R: Reader): number?
return c
end
-- ------------------------------------------------------------------------------------------------ lossless entropy
-- wordsLossless(st, n, stereo) -> true | nil: n samples (n * 2 when stereo) into st.W from the data index (the hot
-- loop of get_words_lossless, with the bit reader in locals)
-- get_words_lossless
local function wordsLossless(st: State, count: number, d: number): boolean
local R: Reader = st.R1
local b, pos, lim = R.b, R.p, R.e
local W = st.W
local med = st.med
local stereo = d == D2
-- (a0, a1, a2): the current channel's medians, (c0, c1, c2) the other's; swapped every sample when stereo
local a0, a1, a2, c0, c1, c2 = med[4], med[5], med[6], med[1], med[2], med[3]
if not stereo then
a0, a1, a2, c0, c1, c2 = med[1], med[2], med[3], 0, 0, 0
@@ -408,7 +389,6 @@ local function wordsLossless(st: State, count: number, d: number): boolean
return pos <= lim
end
-- ------------------------------------------------------------------------------------------------ hybrid entropy
local function updateErrorLimit(st: State, flags: number, mono: boolean)
local bacc, bdelta, slow, limit = st.bacc, st.bdelta, st.slow, st.limit
bacc[1] = (bacc[1] + bdelta[1]) % TWO32
@@ -448,7 +428,7 @@ local function updateErrorLimit(st: State, flags: number, mono: boolean)
end
end
-- getWord(st, chan, flags, mono) -> value, correction | nil (get_word; chan 0 / 1)
-- get_word
local function getWord(st: State, chan: number, flags: number, mono: boolean): (number?, number)
local R: Reader = st.R1
local med = st.med
@@ -564,7 +544,6 @@ local function getWord(st: State, chan: number, flags: number, mono: boolean): (
return if sign == 1 then -mid - 1 else mid, correction
end
-- ------------------------------------------------------------------------------------------------ decorrelation
-- the decorrelation passes over the whole block (stereo, from W[D2]): unpack.c decorr_stereo_pass
local function passesStereo(st: State, n: number)
local W = st.W
@@ -679,7 +658,6 @@ local function passesMono(st: State, n: number)
end
end
-- ------------------------------------------------------------------------------------------------ hybrid lossless
local function shaped(st: State, c: number, flags: number, correction: number): number
-- returns the value to subtract (temp) and updates the error state (noise shaping, unpack.c)
local sacc, sdelta, err = st.sacc, st.sdelta, st.err
@@ -872,7 +850,6 @@ local function hybridStereo(st: State, n: number, flags: number): boolean
return true
end
-- ------------------------------------------------------------------------------------------------ metadata -> state
local function readMeta(st: State, buf: buffer, m: Meta, flags: number, version: number): string?
local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0
local o = m[2]
@@ -1058,8 +1035,7 @@ local function readMeta(st: State, buf: buffer, m: Meta, flags: number, version:
return nil
end
-- ------------------------------------------------------------------------------------------------ fixup + output
-- the float conversion of one value (float_values; R = the wvx stream or nil)
-- float_values (R = the wvx stream or nil)
local function floatValue(st: State, v: number, R: Reader?): number
local fflags, exp = st.fflags, st.fmaxexp
local mant, e, sign = 0, 0, 0
@@ -1160,7 +1136,7 @@ local function floatValue(st: State, v: number, R: Reader?): number
return readf32(sc, 0)
end
-- emit: fixup_samples + false stereo + interleave into P (stride C, first channel c0 0-based)
-- fixup_samples + false stereo + interleave
local function emit(st: State, flags: number, n: number, d: number, P: { number }, c0: number, C: number, lossy: boolean)
local W = st.W
local s = if d == D2 then 2 else 1
@@ -1263,7 +1239,6 @@ local function emit(st: State, flags: number, n: number, d: number, P: { number
end
end
end
-- interleave
if s == 2 then
if c0 == 0 and C == 2 then
for k = 0, count - 1 do
@@ -1296,9 +1271,6 @@ local function emit(st: State, flags: number, n: number, d: number, P: { number
end
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(st, buf, p, size, P, c0, C, cbuf?, cp?, csize?) -> channels written (1 / 2) | nil, message: the block at p
-- (header included in size) into P (interleaved, stride C, from channel c0), with its correction block if given
function Block.decode(st: State, buf: buffer, p: number, size: number, P: { number }, c0: number, C: number, cbuf: buffer?, cp: number?, csize: number?): (number?, string?)
local version = readu16(buf, p + 8)
local n = readu32(buf, p + 20)
@@ -1332,7 +1304,6 @@ function Block.decode(st: State, buf: buffer, p: number, size: number, P: { numb
cm, cb, hasC = cmeta, cbuf, true
crcWant = readu32(cbuf, cp + 28)
end
-- reset
st.nterms = 0
local sA, sB, wA, wB = st.sA, st.sB, st.wA, st.wB
for k = 1, 128 do
@@ -1368,7 +1339,6 @@ function Block.decode(st: State, buf: buffer, p: number, size: number, P: { numb
if n == 0 then
return out, nil
end
-- bitstreams
local o = m[0xA]
if not o or m[0xA + 256] == 0 or m[0xA + 256] % 2 == 1 then
return nil, "no audio bitstream"
+2 -6
View File
@@ -1,13 +1,12 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/WavPack/Tables: the WavPack log2 / exp2 tables and the conversions built on them (wp_log2, wp_exp2s,
-- restore_weight). Ported from WavPack 5.9.0 entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt).
-- codecs/audio/WavPack/Tables: the log2 / exp2 tables, wp_log2, wp_exp2s, restore_weight. Ported from WavPack 5.9.0
-- entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt).
local band, rshift, lshift, countlz = bit32.band, bit32.rshift, bit32.lshift, bit32.countlz
local Tables = {}
-- LOG2[x + 1], EXP2[x + 1] for x = 0 .. 255
local LOG2: { number } = {
0, 1, 3, 4, 6, 7, 9, 10, 11, 13, 14, 16, 17, 18, 20, 21, 22, 24, 25, 26, 28, 29, 30, 32, 33, 34, 36, 37, 38, 40, 41, 42,
44, 45, 46, 47, 49, 50, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 77, 78, 79, 80, 81,
@@ -29,7 +28,6 @@ local EXP2: { number } = {
214, 215, 216, 217, 219, 220, 221, 222, 224, 225, 226, 228, 229, 230, 232, 233, 234, 236, 237, 238, 240, 241, 242, 244, 245, 246, 248, 249, 250, 252, 253, 255,
}
-- exp2s(log) -> the int32 the signed log stands for (wp_exp2s)
function Tables.exp2s(lg: number): number
if lg < 0 then
local v = Tables.exp2s(-lg)
@@ -42,7 +40,6 @@ function Tables.exp2s(lg: number): number
return if r >= 2147483648 then r - 4294967296 else r
end
-- log2(v) -> wp_log2 of the uint32 v
function Tables.log2(v: number): number
v = (v + rshift(v, 9)) % 4294967296
if v < 256 then
@@ -53,7 +50,6 @@ function Tables.log2(v: number): number
return dbits * 256 + LOG2[band(rshift(v, dbits - 9), 255) + 1]
end
-- restoreWeight(signed byte) -> the decorrelation weight (restore_weight)
function Tables.restoreWeight(w: number): number
local r = w * 8
if r > 0 then
+7 -25
View File
@@ -1,18 +1,7 @@
--!strict
-- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec
-- (layer 3). Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt); the hot code is in
-- codecs/audio/WavPack/Block. Lossless and hybrid (lossy, and lossless with the .wvc correction blocks), integer 8 - 32
-- bit (with the extended int32 modes) and 32-bit float, mono / stereo / multichannel (one block per mono or stereo
-- stream, INITIAL .. FINAL), every decorrelation pass (terms 1 - 8, 17, 18, -1 .. -3), joint stereo, cross
-- decorrelation, noise shaping, block CRCs and block checksums. Not supported: DSD, pre-4.0 streams (version < 0x402).
--
-- local h, err = WavPack.header(buf, at, limit) -- the 32-byte block header at `at` (nil, message if none)
-- local info, err = WavPack.info(buf, at, limit) -- stream facts from the first audio block (channels, rate, ...)
-- local dec = WavPack.decoder(info.channels)
-- local frames, err = dec:frame(buf, blocks, cbuf?, cblocks?) -- blocks = { offset, ... } of one frame (+ wvc)
-- -- dec.pcm: interleaved samples (integers in the container range, or float values), WAV channel order
--
-- Never throws: bad data returns nil, Err.
-- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska).
-- Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). Not supported: DSD, pre-4.0
-- streams (version < 0x402).
local Err = require("@rosetta/core/Err")
local Block = require("@rosetta/codecs/audio/WavPack/Block")
@@ -32,7 +21,6 @@ local RATES = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 4410
WavPack.MONO, WavPack.HYBRID, WavPack.FLOAT, WavPack.INITIAL, WavPack.FINAL = 4, 8, 0x80, 0x800, 0x1000
WavPack.DSD = 0x80000000
-- header(buf, at, limit?) -> Header | nil, message: a valid "wvpk" block header at byte `at` whose block ends by limit
function WavPack.header(buf: buffer, at: number, limit: number?): (Header?, string?)
local lim = math.min(limit or buffer.len(buf), buffer.len(buf))
if at < 0 or at + 32 > lim then
@@ -70,15 +58,14 @@ export type Info = {
channels: number,
channelMask: number,
sampleRate: number,
bitsPerSample: number, -- the source depth (container bytes * 8 - shift)
bytesPerSample: number, -- the container: 1 .. 4
bitsPerSample: number,
bytesPerSample: number,
float: boolean,
hybrid: boolean,
md5: string?, -- 32 hex digits when stored
md5: string?,
version: number,
}
-- info(buf, at, limit?) -> Info | nil, Err: the facts of the stream whose first audio block is at `at`
function WavPack.info(buf: buffer, at: number, limit: number?): (Info?, Err.Err?)
local h, herr = WavPack.header(buf, at, limit)
if not h then
@@ -146,7 +133,6 @@ function WavPack.info(buf: buffer, at: number, limit: number?): (Info?, Err.Err?
return info, nil
end
-- md5(buf, at, limit?) -> 32 hex digits | nil: an ID_MD5_CHECKSUM in the block at `at`
function WavPack.md5(buf: buffer, at: number, limit: number?): string?
local h = WavPack.header(buf, at, limit)
if not h then
@@ -167,16 +153,13 @@ function WavPack.md5(buf: buffer, at: number, limit: number?): string?
return table.concat(hex)
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Decoder = {
channels: number,
pcm: { number }, -- the last frame's samples, interleaved (integers in the container range, or floats)
pcm: { number },
frame: (self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?) -> (number?, Err.Err?),
state: Block.State,
}
-- frame(buf, blocks, cbuf?, cblocks?) -> frames | nil, Err: decode one frame (the blocks of one sample range, one per
-- mono / stereo stream, in channel order) into dec.pcm; cblocks are the matching .wvc blocks (hybrid lossless)
local function frame(self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?): (number?, Err.Err?)
local C = self.channels
local n = -1
@@ -222,7 +205,6 @@ local function frame(self: Decoder, buf: buffer, blocks: { number }, cbuf: buffe
return n, nil
end
-- decoder(channels) -> Decoder
function WavPack.decoder(channels: number): Decoder
return {
channels = channels,
+8 -37
View File
@@ -1,18 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder over a whole in-memory stream. Written from the RFC, with the
-- reference decoder (google/brotli c/dec/decode.c, MIT) as the authority on edge cases (simple prefix code alphabet
-- widths, repeat codes, padding checks, the large-window extension). Supports every meta-block kind (compressed,
-- uncompressed, metadata), block types / counts, the four literal context modes, context maps with RLE and inverse
-- move-to-front, NPOSTFIX / NDIRECT distances, the static dictionary with all 121 transforms, window sizes 10..24 and
-- large windows (10..30). The whole output is kept, so the window is only used to tell copies from dictionary words.
--
-- Bits are read LSB first into a bit buffer of up to 32 bits. Prefix codes decode through tables indexed by the next
-- 8 bits; entries are symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits.
--
-- Nothing here throws: every buffer access is checked or in range by construction (the output buffer is sized for each
-- meta-block before it is decoded); bad data returns nil, message.
-- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder, with the large-window extension (windows 10..30).
-- Written from the RFC, with google/brotli c/dec/decode.c (MIT) as the authority on edge cases.
-- Prefix table entry: symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits (8-bit primary).
local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
local bcreate, bcopy, blen, bfill = buffer.create, buffer.copy, buffer.len, buffer.fill
@@ -27,7 +18,6 @@ export type Static = {
transforms: { number }, -- 121 x (prefix id, type, suffix id)
}
-- ------------------------------------------------------------------------------------------------ constants
local CL_ORDER = { 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
local CLP_LEN = { 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4 }
local CLP_VAL = { 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5 }
@@ -54,7 +44,6 @@ end
local NTRANSFORMS = 121
local MAX_ALLOWED_DISTANCE = 0x7FFFFFFC
-- 8-bit reversal
local REV8 = bcreate(256)
for i = 0, 255 do
local r, v = 0, i
@@ -65,19 +54,15 @@ for i = 0, 255 do
writeu8(REV8, i, r)
end
local function reverse(code: number, len: number): number
-- len <= 15
local r = readu8(REV8, band(code, 255)) * 256 + readu8(REV8, band(rshift(code, 8), 255))
return rshift(r, 16 - len)
end
-- ------------------------------------------------------------------------------------------------ prefix tables
local count = table.create(16, 0)
local nextc = table.create(16, 0)
local subBits = table.create(256, 0)
local subOff = table.create(256, 0)
-- tableSize(lens, n) -> the entries build() will write (256 + subtables), or -1 for an over-subscribed set.
-- Also leaves count / nextc / subBits ready for build().
local function prepare(lens: buffer, n: number): number
for l = 1, 16 do
count[l] = 0
@@ -135,7 +120,6 @@ local function prepare(lens: buffer, n: number): number
return size
end
-- build(lens, n, T, at): the table prepared by prepare() at entry offset `at` of T (T must have room)
local function build(lens: buffer, n: number, T: buffer, at: number)
local single = -1
local used = 0
@@ -188,8 +172,7 @@ local function build(lens: buffer, n: number, T: buffer, at: number)
end
end
-- the largest distance alphabet whose distances stay under MAX_ALLOWED_DISTANCE (large windows); after the reference
-- decoder's BrotliCalculateDistanceCodeLimit
-- largest distance alphabet under MAX_ALLOWED_DISTANCE, as the reference's BrotliCalculateDistanceCodeLimit
local function distanceLimit(maxDistance: number, npostfix: number, ndirect: number): number
if maxDistance <= ndirect then
return maxDistance + 16
@@ -213,8 +196,6 @@ local function distanceLimit(maxDistance: number, npostfix: number, ndirect: num
return bor(lshift(group, npostfix), postfix) + ndirect + 16 + 1
end
-- ------------------------------------------------------------------------------------------------ decoder
-- decompress(src, off, len, maxBytes, S, largeWindow) -> out, n, consumedEnd | nil, message
function Decode.decompress(src: buffer, off: number, len: number, maxBytes: number, S: Static, largeWindow: boolean): (buffer?, any, number?)
local lim = off + len
local ip = off
@@ -251,7 +232,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
return (ip - lim) * 8 > bc
end
-- prefix tables of the current meta-block: T (u32 entries), tpos entries used
local T = bcreate(4096 * 4)
local tpos = 0
local LENS = bcreate(1128)
@@ -273,7 +253,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
return rshift(e, 5)
end
-- install(n) -> base: the table for LENS[0 .. n - 1] appended to T, or -1
local function install(n: number): number
local size = prepare(LENS, n)
if size < 0 then
@@ -291,7 +270,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
return base
end
-- readCode(alphabetMax, limit) -> table base | -1 (corrupt)
local function readCode(alphabetMax: number, limit: number): number
bfill(LENS, 0, 0, limit)
local hskip = bits(2)
@@ -447,7 +425,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
return BL_OFF[code + 1] + bits(BL_BITS[code + 1])
end
-- readContextMap(size) -> ntrees, map buffer | -1
local function readContextMap(size: number): (number, buffer)
local ntrees = varLen8() + 1
local map = bcreate(size)
@@ -475,7 +452,7 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
if i + reps > size then
return -1, map
end
i += reps -- zeros (map is zero-filled)
i += reps
end
if overrun() then
return -1, map
@@ -499,7 +476,7 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
return ntrees, map
end
-- ------------------------------------------------------------------ stream header
-- RFC 7932 9.1: stream header
fill()
local wbits
local large = false
@@ -545,7 +522,7 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
local d0, d1, d2, d3 = 4, 11, 15, 16
while true do
-- ---------------------------------------------------------------- meta-block header
-- RFC 7932 9.2: meta-block header
if overrun() then
return nil, "truncated stream"
end
@@ -626,7 +603,7 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
continue
end
-- ---------------------------------------------------------------- compressed meta-block
-- RFC 7932 9.3: compressed meta-block data
tpos = 0
-- block types / counts: 1 = literals, 2 = commands, 3 = distances
local nbtL, nbtI, nbtD = 1, 1, 1
@@ -673,7 +650,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
if ntreesD < 0 then
return nil, "bad distance context map"
end
-- the tree groups
local litBase = table.create(ntreesL, 0)
for i = 1, ntreesL do
local b = readCode(256, 256)
@@ -703,7 +679,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
if overrun() then
return nil, "truncated meta-block header"
end
-- context map slices resolved to table bases
local litMap = table.create(64 * nbtL, 0)
for i = 0, 64 * nbtL - 1 do
litMap[i + 1] = litBase[readu8(cmapL, i) + 1]
@@ -713,7 +688,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
distMap[i + 1] = distBase[readu8(cmapD, i) + 1]
end
-- block state: current type, previous type
local typeL, prevL = 0, 1
local typeI, prevI = 0, 1
local typeD, prevD = 0, 1
@@ -727,7 +701,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
if ip > lim + 4 then
return nil, "truncated stream"
end
-- command block switch
if cntI == 0 then
local t = decodeSym(btTreeI)
if t == 1 then
@@ -759,7 +732,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
if ce > 0 then
cpyLen += bits(ce)
end
-- literals
if insLen > remaining then
return nil, "insert past the meta-block end"
end
@@ -815,7 +787,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
break
end
end
-- distance
local dist
local push = true
if cell < 2 then
+5 -21
View File
@@ -1,16 +1,7 @@
--!strict
-- codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
-- from the RFC (decoder in codecs/compress/Brotli/Decode); the static dictionary, context table and word transforms come from
-- google/brotli (MIT, licenses/brotli-LICENSE.txt) through codecs/compress/Brotli/Static (tools/brotli_static.py).
-- Supports every RFC 7932 stream (window sizes 10..24, metadata / uncompressed / compressed meta-blocks, the static
-- dictionary with all 121 transforms) and the large-window extension (opts.largeWindow). Not supported: compression,
-- shared / compound dictionaries (draft "shared brotli").
--
-- local Brotli = require("@rosetta/codecs/compress/Brotli")
-- local out, consumedEnd = Brotli.decompress(buf) -- buffer | string
-- local out, err = Brotli.decompress(buf, offset, length, { maxBytes = 2^24 })
--
-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / LIMIT / UNSUPPORTED / ARG).
-- codecs/compress/Brotli: Brotli (RFC 7932) decompression, with the large-window extension.
-- The static dictionary, context table and word transforms come from google/brotli (MIT, licenses/brotli-LICENSE.txt)
-- through codecs/compress/Brotli/Static (tools/brotli_static.py).
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Crc32 = require("@rosetta/core/Crc32")
@@ -22,11 +13,10 @@ local StaticData = require("@rosetta/codecs/compress/Brotli/Static")
local Brotli = {}
export type Options = {
maxBytes: number?, -- refuse output larger than this (default 2^30)
largeWindow: boolean?, -- accept the large-window extension (windows up to 2^30; default true)
maxBytes: number?,
largeWindow: boolean?,
}
-- ------------------------------------------------------------------------------------------------ static data
-- the tables are base64 text (trusted, generated by tools/brotli_static.py)
local function unbase64(s: string): buffer
return Base64.decode(s) or buffer.create(0)
@@ -34,7 +24,6 @@ end
local static: Decode.Static? = nil
-- tables() -> the decoded static data (inflated once, on first use)
local function tables(): (Decode.Static?, Err.Err?)
if static then
return static, nil
@@ -57,16 +46,11 @@ local function tables(): (Decode.Static?, Err.Err?)
return static, nil
end
-- dictionary() -> the 122784-byte RFC 7932 static dictionary (for tests and encoders)
function Brotli.dictionary(): buffer?
local s = tables()
return if s then s.dictionary else nil
end
-- ------------------------------------------------------------------------------------------------ decompress
-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. consumedEnd: the input offset just past
-- the stream (trailing bytes are ignored).
function Brotli.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
local b, o, l, aerr = Bytes.span("Brotli.decompress", buf, offset, length)
if not b then
+9 -23
View File
@@ -1,16 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Bzip2/Decode: bzip2 stream decoder (Julian Seward's format, as documented by the bzip2 1.0.x sources and
-- Joe Tsai's "bzip2 format specification"). Written from the format description; no third-party code.
-- Per block: MSB-first bit reader on a local 32-bit bit buffer, Huffman groups (10-bit lookup + canonical fallback for
-- codes up to 20 bits), MTF + RUNA/RUNB, inverse BWT through one u32 vector (byte in the low 8 bits, next index
-- above), RLE1 undo with the block CRC (CRC-32/BZIP2, MSB first) computed on the way out; the combined stream CRC is
-- checked at the end-of-stream marker. Concatenated streams are decoded one after the other.
-- Not supported: randomised blocks (written only by bzip2 0.9.0 and older).
--
-- Never throws: every buffer access is in range by construction; failures return nil, message, kind
-- ("truncated" | "corrupt" | "checksum" | "limit" | "unsupported").
-- codecs/compress/Bzip2/Decode: bzip2 stream decoder (bzip2 1.0.x sources, Joe Tsai's "bzip2 format specification").
-- Huffman groups, MTF + RUNA/RUNB, inverse BWT, RLE1; block CRC-32/BZIP2 (MSB first) and the combined stream CRC.
-- Written from the format description; no third-party code.
local Crc32 = require("@rosetta/core/Crc32")
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32
@@ -27,25 +20,23 @@ for i = 0, 32 do
MASK[i + 1] = if i == 32 then 0xFFFFFFFF else 2 ^ i - 1
end
local PBITS = 10 -- primary lookup width
local PBITS = 10
local PSIZE = 1024
local MAXGROUPS = 6
local MAXALPHA = 258
local MAXLEN = 20
-- scratch tables, reused across calls (single-threaded)
local LOOK = bcreate(MAXGROUPS * PSIZE * 4) -- per group: sym * 32 + len (len <= PBITS), 0 = longer code / none
local LOOK = bcreate(MAXGROUPS * PSIZE * 4)
local LENS = bcreate(MAXGROUPS * MAXALPHA)
local PERM = table.create(MAXGROUPS * MAXALPHA, 0) -- per group: symbols in canonical order
local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- first code of each length
local PERM = table.create(MAXGROUPS * MAXALPHA, 0)
local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0)
local COUNT = table.create(MAXGROUPS * (MAXLEN + 1), 0)
local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- index into PERM of the first symbol of each length
local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0)
local MAXL = table.create(MAXGROUPS, 0)
local CFTAB = table.create(257, 0)
local MTF = table.create(256, 0)
local SEQ = table.create(256, 0)
-- build group g's tables from LENS[g*MAXALPHA .. + n): false when over-subscribed
local function buildGroup(g: number, n: number): boolean
local lbase = g * MAXALPHA
local cbase = g * (MAXLEN + 1)
@@ -74,7 +65,6 @@ local function buildGroup(g: number, n: number): boolean
end
code *= 2
end
-- perm + lookup
local pbase = g * MAXALPHA
local tbase = g * PSIZE * 4
bfill(LOOK, tbase, 0, PSIZE * 4)
@@ -106,11 +96,10 @@ local function grow(out: buffer, op: number, need: number): buffer
return nb
end
-- decode(b, o, e, maxBytes) -> out, n, consumedEnd | nil, message, kind
function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buffer?, any, any)
local out = bcreate(math.min(math.max(65536, (e - o) * 4), maxBytes + 1))
local op = 0
local p = o -- next input byte (may run past e: zeros are fed, and the overrun is detected)
local p = o
local bb, bc = 0, 0
local tt: buffer? = nil
local ttSize = 0
@@ -377,7 +366,6 @@ function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buff
bc -= band(ent, 31)
sym = rshift(ent, 5)
else
-- a code longer than PBITS: canonical search
local v = band(rshift(bb, bc - gmax), MASK[gmax + 1])
sym = -1
for l = PBITS + 1, gmax do
@@ -442,7 +430,6 @@ function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buff
return nil, "bad BWT origin pointer", "corrupt"
end
-- inverse BWT: T[pos] |= i << 8 at each byte's sorted position
local sum = 0
for i = 0, 255 do
local c = CFTAB[i + 1]
@@ -456,7 +443,6 @@ function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buff
writeu32(T, k * 4, bor(readu32(T, k * 4), lshift(i, 8)))
end
-- walk, undo RLE1, CRC
if op + nblock + 4096 > blen(out) then
out = grow(out, op, op + nblock + 4096)
end
+3 -13
View File
@@ -1,14 +1,6 @@
--!strict
-- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
-- (layer 3): archive/bz2 and tar.bz2 build on it. Written from the format description (no third-party code).
-- Supports: block sizes 1..9, every Huffman group layout, block and stream CRCs, concatenated streams (as bzip2 -d).
-- Not supported: randomised blocks (bzip2 0.9.0 and older; Err.UNSUPPORTED), compression.
--
-- local Bzip2 = require("@rosetta/codecs/compress/Bzip2")
-- local out, consumedEnd = Bzip2.decompress(buf) -- | nil, Err
-- local out = Bzip2.decompress(buf, offset, length, { maxBytes = 2^24 })
--
-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / LIMIT / ARG).
-- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x).
-- Written from the format description (no third-party code); randomised blocks (bzip2 0.9.0 and older) are unsupported.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Decode = require("@rosetta/codecs/compress/Bzip2/Decode")
@@ -16,10 +8,9 @@ local Decode = require("@rosetta/codecs/compress/Bzip2/Decode")
local Bzip2 = {}
export type Options = {
maxBytes: number?, -- refuse output larger than this (default 2^30)
maxBytes: number?,
}
-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err
function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
local b, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length)
if not b then
@@ -41,7 +32,6 @@ function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?
return res, consumed
end
-- crc(buf, offset?, length?) -> the CRC-32/BZIP2 of a range (the block CRC bzip2 stores)
function Bzip2.crc(buf: buffer, offset: number?, length: number?): number
local CT = Decode.crcTable
local o = offset or 0
@@ -1,11 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth
-- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (codecs/entropy/Huffman
-- length-limited codes). Level 0 = stored blocks only.
--
-- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments).
-- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor: hash-chain LZ77 over a 32 KB window, then per
-- block the cheapest of stored / fixed / dynamic Huffman, as zlib's levels.
local Huffman = require("@rosetta/codecs/entropy/Huffman")
local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16
@@ -15,11 +12,10 @@ local floor = math.floor
local WSIZE = 32768
local HSIZE = 65536
local MAXMATCH = 258
local BLOCKSYMS = 16384 -- symbols per block
local BLOCKSYMS = 16384
-- per level (zlib's configuration_table): GOOD = a match this long quarters the chain for the lazy search, LAZY = no
-- lazy search after a match this long, NICE = stop searching at this length, CHAIN = max chain steps. Levels 1-3 are
-- greedy (no lazy matching).
-- zlib's configuration_table: GOOD quarters the chain for the lazy search, LAZY = no lazy search after a match this
-- long, NICE = stop searching at this length, CHAIN = max chain steps; levels 1-3 are greedy.
local GOOD = { 4, 4, 4, 4, 8, 8, 8, 32, 32 }
local LAZY = { 0, 0, 0, 4, 16, 16, 32, 128, 258 }
local NICE = { 8, 16, 32, 16, 32, 128, 128, 258, 258 }
@@ -66,14 +62,12 @@ end
local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }
-- fixed codes
local FIXLEN = table.create(288, 0)
for i = 1, 288 do
FIXLEN[i] = if i <= 144 then 8 elseif i <= 256 then 9 elseif i <= 280 then 7 else 8
end
local FIXDLEN = table.create(30, 5)
-- reversed (LSB-first) canonical codes for lengths
local function revCodes(lens: { number }): { number }
local codes = Huffman.codes(lens)
for i, l in lens do
@@ -91,7 +85,6 @@ for i = 0, 32 do
POW[i + 1] = 2 ^ i
end
-- ------------------------------------------------------------------------------------------------ bit output
type Out = { buf: buffer, op: number, acc: number, cnt: number }
local function ensure(o: Out, n: number)
@@ -102,7 +95,6 @@ local function ensure(o: Out, n: number)
end
end
-- put(v, n): n <= 24 bits, LSB first
local function put(o: Out, v: number, n: number)
local acc = o.acc + v * POW[o.cnt + 1]
local cnt = o.cnt + n
@@ -127,8 +119,6 @@ local function alignOut(o: Out)
end
end
-- ------------------------------------------------------------------------------------------------ blocks
-- syms: L[i] = literal 0..255 or 256 + match length; D[i] = distance (0 for literals)
local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean)
local p = s
repeat
@@ -209,7 +199,7 @@ local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D
for i = 1, hdist do
all[hlit + i] = dlen[i]
end
local cs, cx = {}, {} -- symbol, extra value
local cs, cx = {}, {}
local cf = table.create(19, 0)
local i = 1
local total = hlit + hdist
@@ -252,7 +242,6 @@ local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D
while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do
hclen -= 1
end
-- costs in bits
local dyn = 17 + 3 * hclen + extra
for k = 1, 19 do
dyn += cf[k] * clen[k]
@@ -299,7 +288,6 @@ local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D
emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen)
end
-- ------------------------------------------------------------------------------------------------ LZ77
local Compress = {}
function Compress.raw(src: buffer, off: number, len: number, level: number): buffer
@@ -336,7 +324,6 @@ function Compress.raw(src: buffer, off: number, len: number, level: number): buf
prev[p % WSIZE + 1] = head[h]
head[h] = p
end
-- longest match at p among earlier positions: len (0 if < 3), dist
local function find(p: number, steps: number): (number, number)
local maxLen = math.min(MAXMATCH, e - p)
if maxLen < 3 then
@@ -360,7 +347,7 @@ function Compress.raw(src: buffer, off: number, len: number, level: number): buf
end
local nc = prev[c % WSIZE + 1]
if nc >= c then
break -- the slot was reused by a newer position: the chain ends here
break
end
c = nc
steps -= 1
@@ -377,7 +364,7 @@ function Compress.raw(src: buffer, off: number, len: number, level: number): buf
end
local p = off
local stop3 = e - 3 -- positions with 3 bytes ahead can be hashed
local stop3 = e - 3
while p < e do
local mlen, mdist = 0, 0
if p <= stop3 then
@@ -386,7 +373,6 @@ function Compress.raw(src: buffer, off: number, len: number, level: number): buf
if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then
local l2, d2 = find(p + 1, if mlen >= good then maxChain // 4 else maxChain)
if l2 > mlen then
-- a literal now, the longer match from p + 1
nsym += 1
L[nsym] = readu8(src, p)
D[nsym] = 0
@@ -2,15 +2,7 @@
--!native
--!optimize 2
-- codecs/compress/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks.
-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to codecs/entropy/Huffman, whose
-- entries are symbol * 32 + length (5 length bits instead of 4).
--
-- Bits are read LSB first into a 32-bit bit buffer (refilled 4 bytes at a time with one readu32 while the input
-- lasts). Huffman codes decode through a codecs/entropy/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer
-- code's primary slot links to a subtable, so a symbol is one or two table reads.
--
-- Nothing in this module throws on any input: every buffer read and write is bounds-checked, and corrupt data
-- returns nil, message. (Native code must never throw: it crashes Roblox Studio.)
-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author).
local Huffman = require("@rosetta/codecs/entropy/Huffman")
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
@@ -20,7 +12,7 @@ local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buf
local LITBITS, DISTBITS, CLBITS = 10, 8, 7
local LITMASK, DISTMASK, CLMASK = 1023, 255, 127
-- length codes 257..285 and distance codes 0..29: base value, extra bits
-- RFC 1951 3.2.5: length codes 257..285 and distance codes 0..29: base value, extra bits
local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }
local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }
local DBASE = {
@@ -28,15 +20,13 @@ local DBASE = {
6145, 8193, 12289, 16385, 24577,
}
local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }
-- the order code-length code lengths are sent in
-- RFC 1951 3.2.7: the order the code-length code lengths are sent in
local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }
-- table capacities (entries): primary + one subtable per code longer than the primary width, worst case
local LITCAP = Huffman.capacity(288, LITBITS, 15)
local DISTCAP = Huffman.capacity(32, DISTBITS, 15)
local CLCAP = Huffman.capacity(19, CLBITS, 7)
-- fixed Huffman tables
local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
local FLITS: number, FDISTS: number
do
@@ -53,7 +43,6 @@ end
local Inflate = {}
-- Grow out (capacity cap) to hold at least need bytes. Returns the new buffer and capacity.
local function grow(out: buffer, op: number, need: number): (buffer, number)
local cap = math.max(blen(out) * 2, need, 1024)
local nb = bcreate(cap)
@@ -61,12 +50,6 @@ local function grow(out: buffer, op: number, need: number): (buffer, number)
return nb, cap
end
-- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in
-- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and
-- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing).
-- dict: a preset dictionary (the data before the stream, e.g. MSZIP's previous block): out starts with a copy of it,
-- distances may reach into it, and outLen includes it (cap does not).
-- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message.
function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?)
local op = 0
if dict then
@@ -267,7 +250,6 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
end
local lsmask = lshift(1, lsub) - 1
local dsmask = lshift(1, dsub) - 1
-- the symbol loop
while true do
if bitcnt < 15 then
if pos + 4 <= endpos then
@@ -324,7 +306,6 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
if sym > 29 then
return nil, "invalid literal/length code"
end
-- up to 5 length extra bits + a 15-bit distance code
if bitcnt < 20 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
@@ -414,8 +395,7 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
local s = op - dist
if dist >= len then
if len <= 16 and op + 16 <= cap then
-- straight-line 16-byte copy (the bytes past len are rewritten later): no inner loop, which
-- keeps LuaJIT's traces simple; chunks read only bytes before op or already copied ones
-- straight-line 16-byte copy for simple LuaJIT traces; it reads only bytes before op or already copied ones
writeu32(out, op, readu32(out, s))
writeu32(out, op + 4, readu32(out, s + 4))
writeu32(out, op + 8, readu32(out, s + 8))
@@ -432,7 +412,6 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
bfill(out, op, readu8(out, s), len)
op += len
else
-- overlapping: the pattern of period dist, copied in growing non-overlapping chunks
local rem = len
while rem > 0 do
local k = math.min(op - s, rem)
+5 -37
View File
@@ -1,19 +1,6 @@
--!strict
-- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
-- A codec (layer 1), not a format: png, zip, gzip, woff, tiff, ... build on it. Absorbed from deflate-luau 1.0.0
-- (same author; no third-party code); the compressor is new.
--
-- local Deflate = require("@rosetta/codecs/compress/Deflate")
-- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err
-- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known
-- local out, err = Deflate.inflate(buf, off, len, size, dict) -- with a preset dictionary
-- local out, err = Deflate.mszip(buf, { { offset, length, size }, ... }) -- MSZIP blocks ("CK" + deflate, chained)
-- local out, err = Deflate.zlib(buf) -- checks the Adler-32
-- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members
-- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip
-- local head = Deflate.peek(buf, nil, nil, 512) -- the first 512 inflated bytes of gzip / zlib / raw
--
-- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG).
-- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with zlib (RFC 1950) and gzip (RFC 1952).
-- Absorbed from deflate-luau 1.0.0 (same author; no third-party code); the compressor is new.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Crc32 = require("@rosetta/core/Crc32")
@@ -42,11 +29,6 @@ local function inflateErr(msg: string, at: number?): Err.Err
return Err.new(code, "inflate: " .. msg, at)
end
-- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate.
-- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream
-- that inflates to a different size is an error. consumedEnd is the input offset just past the final block.
-- dict: a preset dictionary (up to 32 KB of data before the stream, as MSZIP's previous block): back references may
-- reach into it; the result holds only the new bytes.
function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?, dict: buffer?): (buffer?, any)
local b, o, l, aerr = args("Deflate.inflate", buf, offset, length)
if not b then
@@ -82,7 +64,6 @@ function Deflate.inflate(buf: buffer | string, offset: number?, length: number?,
return shrink(out, n), consumed
end
-- zlib(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err
function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any)
local b, o, l, aerr = args("Deflate.zlib", buf, offset, length)
if not b then
@@ -116,7 +97,6 @@ function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, ex
return out, consumed + 4
end
-- gzipBody(b, p, e) -> the offset of a gzip member's deflate data (past FEXTRA / FNAME / FCOMMENT / FHCRC) | nil, Err
local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?)
local flg = buffer.readu8(b, p + 3)
if flg >= 0x20 then
@@ -146,8 +126,6 @@ local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?)
return q, nil
end
-- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is
-- not another gzip member (zero padding, garbage) is ignored, as gzip -d does.
function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length)
if not b then
@@ -194,7 +172,6 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?):
table.insert(parts, out)
total += buffer.len(out)
p = consumed + 8
-- skip zero padding
local z = p
while z < e and buffer.readu8(b, z) == 0 do
z += 1
@@ -215,9 +192,6 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?):
return res, nil
end
-- peek(buf, offset?, length?, n) -> buffer | nil, Err: the first n bytes (fewer when the stream is shorter, or up to
-- 258 fewer at a match boundary) a gzip member, zlib stream or raw deflate stream inflates to, without inflating
-- the rest or checking checksums: for sniffing compressed files cheaply.
function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n: number): (buffer?, Err.Err?)
local b, o, l, aerr = args("Deflate.peek", buf, offset, length)
if not b then
@@ -248,7 +222,7 @@ function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n:
end
export type CompressOptions = {
level: number?, -- 0 (stored) .. 9 (best); default 6
level: number?,
}
local function level(opts: CompressOptions?): number?
@@ -259,7 +233,6 @@ local function level(opts: CompressOptions?): number?
return lv
end
-- compress(buf, opts?) -> raw deflate buffer | nil, Err
function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
@@ -269,7 +242,6 @@ function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer
return Compress.raw(b, 0, buffer.len(b), lv), nil
end
-- zlibCompress(buf, opts?) -> zlib stream | nil, Err
function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
@@ -290,7 +262,6 @@ function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (bu
return out, nil
end
-- gzip(buf, opts?) -> gzip member (no name, mtime 0) | nil, Err
function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
@@ -309,10 +280,8 @@ function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, E
return out, nil
end
-- mszip(buf, blocks) -> buffer | nil, Err: MSZIP data (Microsoft's blocked deflate, as in CAB folders and DirectX .x
-- files): blocks = { { offset, length, size } }, each buf[offset, offset + length) = "CK" + a raw deflate stream that
-- inflates to exactly size bytes using the previous block's output (up to 32 KB) as its dictionary. Returns the
-- blocks' output concatenated.
-- MSZIP (CAB folders, DirectX .x): each block is "CK" + a raw deflate stream using the previous block's output (up to
-- 32 KB) as its dictionary.
function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number, size: number } }): (buffer?, Err.Err?)
local total = 0
for _, b in blocks do
@@ -343,7 +312,6 @@ function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number,
return out, nil
end
-- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of)
Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number
local b = toBuffer(buf) or buffer.create(0)
return Crc32.of(b, offset, length, crc)
+3 -13
View File
@@ -1,17 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ
-- archive sectors, old installers, some game data files). A codec (layer 3). Written after the format as documented
-- by Mark Adler's blast.c (zlib licence, licenses/blast-LICENSE.txt): the same constant code tables (run-length
-- coded Huffman code lengths, length bases / extra bits), the bit order (LSB first, Huffman codes inverted); the
-- decoder itself is new code.
-- Supports: literal coding off (raw bytes) and on (Huffman coded), 1 / 2 / 4 KB dictionaries, the end code; stops
-- early at maxOut bytes (MPQ sectors whose stream has no end code).
--
-- local out, err = Explode.decompress(buf, offset?, length?, maxOut?) -- buffer | nil, Err
--
-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / ARG / LIMIT).
-- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987).
-- Code tables and bit order (LSB first, Huffman codes inverted) after Mark Adler's blast.c (zlib licence:
-- licenses/blast-LICENSE.txt); the decoder is new code.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
@@ -33,7 +25,6 @@ local EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 }
type Code = { count: { number }, symbol: { number } }
-- canonical code from run-length coded lengths
local function construct(rep: { number }): Code
local lengths: { number } = {}
for _, b in rep do
@@ -64,7 +55,6 @@ local LIT = construct(LITLEN)
local LEN = construct(LENLEN)
local DIST = construct(DISTLEN)
-- decompress(buf, offset?, length?, maxOut?) -> buffer | nil, Err
function Explode.decompress(buf: buffer | string, offset: number?, length: number?, maxOut: number?): (buffer?, Err.Err?)
local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length)
if not b then
+3 -27
View File
@@ -1,26 +1,14 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder
-- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies,
-- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws.
--
-- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err
-- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err
-- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks)
-- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room
-- Lz4.bound(n) -- worst-case block size for n bytes
--
-- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default
-- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or
-- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from.
-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md), decode and the reference "fast" encoder.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Lz4 = {}
export type Options = {
maxBytes: number?, -- refuse output larger than this when outSize is not given (default 2^28)
maxBytes: number?,
}
local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32
@@ -34,7 +22,6 @@ local MAX_OFFSET = 65535
local HASH_BITS = 13
local HASH_SIZE = 2 ^ HASH_BITS
-- ------------------------------------------------------------------------------------------------ decode
function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?)
local lo = histStart or d
if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then
@@ -107,7 +94,6 @@ function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: n
buffer.fill(dst, d, readu8(dst, s), ml)
d += ml
else
-- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time
local n = ml
while n > 0 do
local c = d - s
@@ -122,8 +108,6 @@ function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: n
end
end
-- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be
-- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes.
function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?)
local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length)
if not b then
@@ -163,13 +147,10 @@ function Lz4.decompress(src: buffer | string, offset: number?, length: number?,
end
end
-- ------------------------------------------------------------------------------------------------ encode
-- bound(n) -> the largest block n input bytes can produce
function Lz4.bound(n: number): number
return n + n // 255 + 16
end
-- writes a length's 255-run extension at o; returns the next offset
local function extend(dst: buffer, o: number, n: number): number
while n >= 255 do
writeu8(dst, o, 255)
@@ -180,7 +161,7 @@ local function extend(dst: buffer, o: number, n: number): number
return o + 1
end
-- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles
-- Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles
local function hash(v: number): number
local vl, vh = band(v, 0xFFFF), rshift(v, 16)
local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536
@@ -189,7 +170,6 @@ end
local hashTable: { number } = table.create(HASH_SIZE, -1e9)
-- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n))
function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number
local op = d
local anchor = p
@@ -209,7 +189,6 @@ function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: numbe
local ref = ht[h]
ht[h] = ip
if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then
-- back over equal bytes before the match (into the pending literals)
while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do
ip -= 1
ref -= 1
@@ -247,7 +226,6 @@ function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: numbe
ip = a
anchor = ip
skip = 64
-- index the position just before the next one (better ratio at no cost)
if ip - 2 >= p and ip - 2 < mflimit then
local w = readu32(src, ip - 2)
ht[hash(w)] = ip - 2
@@ -258,7 +236,6 @@ function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: numbe
end
end
end
-- the last literals
local lit = iend - anchor
local tok = op
op += 1
@@ -275,7 +252,6 @@ function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: numbe
return op - d
end
-- compress(src, offset?, length?) -> buffer (one block) | nil, Err
function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length)
if not b then
+6 -30
View File
@@ -1,23 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo:
-- lh4 / lh5 / lh6 / lh7 / lhx static Huffman blocks (code-length "temp" table, 510 literal / length codes, offset
-- bit-length codes); also ARJ methods 1..3 (= "lh6") and Zoo method 2 (= "lh5")
-- lh1 adaptive Huffman (LHarc 1.x: 314 codes, grouped frequency tree) with fixed-length
-- offset prefixes, 4 KB window
-- lzs / lz5 LArc's plain LZSS (2 KB / 4 KB windows, flag bits / flag bytes)
-- arj4 ARJ method 4 (unary-prefixed lengths and offsets, no Huffman)
-- Every method decodes into a buffer of the known output size; the windows start filled as the original tools fill
-- them (spaces; lz5's pattern), and offsets before the start of the output read that fill.
-- Ported from lhasa 0.6.0 (Simon Howard, ISC licence: licenses/lhasa-LICENSE.txt): lh_new_decoder.c, lh1_decoder.c,
-- lzs_decoder.c, lz5_decoder.c; the static Huffman tables are canonical codes built with codecs/entropy/Huffman instead
-- of lhasa's trees. ARJ method 4 is written from the ARJ technical notes (unarj's decode_f description).
--
-- local out, err = Lzh.decode(src, off, len, outSize, "lh5") -- buffer | nil, message
--
-- Never throws: bad codes / truncated input return nil, message (truncated input: "truncated ..." after the bytes
-- decoded so far would be useless, so nothing partial is returned). Not supported: pm0 / pm1 / pm2 (PMarc), lk7.
-- codecs/compress/Lzh: the LHA family of LZSS decoders (lh1, lh4-lh7, lhx, lzs, lz5, ARJ 1-4, Zoo 2).
-- Ported from lhasa 0.6.0 (Simon Howard, ISC: licenses/lhasa-LICENSE.txt); ARJ method 4 from the ARJ technical notes.
-- Windows start filled as the original tools fill them (spaces; lz5's pattern); offsets before the output read it.
local Huffman = require("@rosetta/codecs/entropy/Huffman")
local Lzh = {}
@@ -26,9 +12,6 @@ local readu8, writeu8, readu32 = buffer.readu8, buffer.writeu8, buffer.readu32
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
local floor = math.floor
-- ------------------------------------------------------------------------------------------------ bit reader
-- an MSB-first bit reader over src[pos, limit): acc holds cnt bits (cnt <= 32); past the end, zero bits are read and
-- over counts them
type Reader = { src: buffer, pos: number, limit: number, acc: number, cnt: number, over: number }
local function reader(src: buffer, off: number, len: number): Reader
@@ -73,7 +56,6 @@ local function bits(r: Reader, n: number): number
return v
end
-- ------------------------------------------------------------------------------------------------ static Huffman
type Table = { tab: buffer, P: number, S: number, single: number }
local function newTable(nsym: number, P: number): Table
@@ -145,7 +127,7 @@ local function readLengths(r: Reader, t: Table, nbits: number, maxN: number, spe
writeu8(lens, i, l)
if i == special then
local z = bits(r, 2)
i += z -- zeros (already zero)
i += z
end
i += 1
end
@@ -235,7 +217,6 @@ local function decodeNew(src: buffer, off: number, len: number, out: buffer, n:
return nil
end
-- ------------------------------------------------------------------------------------------------ lh1
local NUM_CODES = 314
local NUM_NODES = NUM_CODES * 2 - 1
local REORDER = 32 * 1024
@@ -261,7 +242,6 @@ end
local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: number): string?
local r = reader(src, off, len)
-- node arrays (0-based indexes stored at [i + 1])
local leaf = table.create(NUM_NODES, false)
local child = table.create(NUM_NODES, 0)
local parent = table.create(NUM_NODES, 0)
@@ -401,7 +381,7 @@ local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n:
end
end
local code = child[ni + 1]
-- increment_for_code
-- lhasa's increment_for_code
if freq[1] >= REORDER then
reconstruct()
end
@@ -438,8 +418,7 @@ local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n:
return nil
end
-- ------------------------------------------------------------------------------------------------ LArc lzs / lz5
-- the ring of a 2 KB / 4 KB window (positions are absolute ring positions, not distances)
-- LArc lzs / lz5: a 2 KB / 4 KB ring (absolute ring positions, not distances)
local function decodeLzs(src: buffer, off: number, len: number, out: buffer, n: number): string?
local r = reader(src, off, len)
local ring = buffer.create(2048)
@@ -549,7 +528,6 @@ local function decodeLz5(src: buffer, off: number, len: number, out: buffer, n:
return nil
end
-- ------------------------------------------------------------------------------------------------ ARJ method 4
local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n: number): string?
local r = reader(src, off, len)
local function prefixed(start: number, stop: number): number
@@ -591,10 +569,8 @@ local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n:
return nil
end
-- ------------------------------------------------------------------------------------------------ api
Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" }
-- decode(src, off, len, outSize, method) -> buffer | nil, message
function Lzh.decode(src: buffer, off: number, len: number, outSize: number, method: string): (buffer?, string?)
if off < 0 or len < 0 or off > buffer.len(src) or outSize < 0 or outSize ~= outSize then
return nil, "bad arguments"
+2 -3
View File
@@ -1,8 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit
-- value is kept as two u32 halves (hi, lo). Written from the xz file format specification. Never throws.
-- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), xz check type 4.
-- Written from the xz file format specification; the 64-bit value is kept as two u32 halves (hi, lo).
local band, bxor, rshift, lshift, bor = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift, bit32.bor
local readu8 = buffer.readu8
@@ -23,7 +23,6 @@ end
local Crc64 = {}
-- of(buf, offset, length) -> hi, lo
function Crc64.of(b: buffer, o: number, n: number): (number, number)
local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF
for i = o, o + n - 1 do
+8 -29
View File
@@ -1,17 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z).
-- Written from the LZMA specification and its reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain); the
-- structure (probability model layout, state transitions, distance / length decoding) follows that document.
--
-- The output buffer is also the dictionary: everything decoded stays in memory, so a match may reach back to the last
-- dictionary reset (st.dictStart). A decoder state (new) carries the probabilities, the LZ state, the four rep
-- distances, a pending match remainder (st.remLen) and the range coder across calls, so LZMA2 can feed it chunk by
-- chunk. run() decodes until st.op reaches outEnd, an end marker, or an error.
--
-- Never throws: every input read is bounds-checked (a read past the end counts in `over` and fails the call as
-- "truncated"), every output write is preceded by a capacity check, and errors return nil, message.
-- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by LZMA (.lzma, 7z) and LZMA2.
-- Follows the LZMA specification's reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain): probability layout,
-- state transitions, distance / length decoding.
local readu8, readu16, writeu8, writeu16 = buffer.readu8, buffer.readu16, buffer.writeu8, buffer.writeu16
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
local rshift, band = bit32.rshift, bit32.band
@@ -37,8 +29,8 @@ local Decode = {}
export type State = {
out: buffer,
cap: number,
op: number, -- bytes decoded so far (the next write offset)
dictStart: number, -- the last dictionary reset: matches may not reach before it
op: number,
dictStart: number,
maxBytes: number,
probs: buffer,
nprobs: number,
@@ -50,12 +42,11 @@ export type State = {
rep1: number,
rep2: number,
rep3: number,
remLen: number, -- a match cut by outEnd, finished by the next run
remLen: number,
range: number,
code: number,
}
-- new(cap, maxBytes) -> a decoder state with an empty output buffer of capacity cap
function Decode.new(cap: number, maxBytes: number): State
local c = math.max(64, math.min(cap, maxBytes))
return {
@@ -80,7 +71,6 @@ function Decode.new(cap: number, maxBytes: number): State
}
end
-- setProps(st, lc, lp, pb) -> ok, message?: new literal / position parameters (resets the probabilities)
function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolean, string?)
if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then
return false, "bad lc / lp / pb"
@@ -95,7 +85,6 @@ function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolea
return true, nil
end
-- resetState(st): probabilities to 1/2, LZ state and reps to 0
function Decode.resetState(st: State)
local p = st.probs
for i = 0, st.nprobs - 1 do
@@ -106,13 +95,11 @@ function Decode.resetState(st: State)
st.remLen = 0
end
-- resetDict(st): matches may no longer reach before the current position
function Decode.resetDict(st: State)
st.dictStart = st.op
st.remLen = 0
end
-- rcInit(st, buf, ip, iend) -> next ip | nil, message: the 5 range coder init bytes
function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?, string?)
if ip + 5 > iend then
return nil, "truncated range coder init"
@@ -128,7 +115,6 @@ function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?
return ip + 5, nil
end
-- ensure(st, need) -> ok: grow the output to hold need bytes (bounded by maxBytes)
local function ensure(st: State, need: number): boolean
if need <= st.cap then
return true
@@ -145,7 +131,6 @@ local function ensure(st: State, need: number): boolean
end
Decode.ensure = ensure
-- copy(st, n, b, ip): append n stored bytes (LZMA2 uncompressed chunks); the caller checked the input range
function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, string?)
if not ensure(st, st.op + n) then
return false, "limit: output over maxBytes"
@@ -155,14 +140,12 @@ function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, str
return true, nil
end
-- the range decoder state while run() executes (module upvalues: the helpers below are created once, so LuaJIT
-- traces stay valid across calls; run() is not re-entrant, and never yields)
-- module upvalues, so LuaJIT traces stay valid across calls (run() is not re-entrant)
local EMPTY = bcreate(2)
local probs: buffer = EMPTY
local inb: buffer = EMPTY
local range, code, ip, iend, over = 0, 0, 0, 0, 0
-- decode one bit with the probability at index i
local function bit(i: number): number
local p = i * 2
local prob = readu16(probs, p)
@@ -244,8 +227,6 @@ local function length(base: number, posState: number): number
return 16 + tree(base + 258, 8)
end
-- run(st, buf, ip, iend, outEnd) -> status, ip | nil, message. status: "full" (st.op reached outEnd) or "eos" (end
-- marker). The range coder must have been initialised (rcInit).
function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any)
probs = st.probs
inb = inb0
@@ -268,7 +249,6 @@ function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd:
local status: string? = nil
local msg: string? = nil
-- a pending match from the previous call
local remLen = st.remLen
if remLen > 0 then
local n = math.min(remLen, outEnd - op)
@@ -469,7 +449,7 @@ function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd:
st.state = state
st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3
st.remLen = remLen
probs, inb = EMPTY, EMPTY -- do not keep the caller's buffers alive
probs, inb = EMPTY, EMPTY
if msg then
return nil, msg
end
@@ -479,7 +459,6 @@ function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd:
return status, ip
end
-- finish(st) -> a buffer of exactly the decoded bytes
function Decode.finish(st: State): buffer
if st.cap == st.op then
return st.out
@@ -1,10 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole
-- decoded buffer range. Written from the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin,
-- public domain): x86, ARM, ARM-Thumb, PowerPC, SPARC, ARM64 and delta. Not supported: IA-64, RISC-V.
-- Never throws: every access is inside [o, o + n).
-- codecs/compress/Lzma/Filters: the xz / 7z branch-call-jump (BCJ) and delta decoding filters, in place.
-- From the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin, public domain).
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local band, bor, bxor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.bxor, bit32.rshift, bit32.lshift, bit32.byteswap
@@ -19,7 +17,6 @@ local function msbyte(b: number): boolean
return b == 0 or b == 0xFF
end
-- x86(b, o, n, start): BCJ x86 decode; start = the stream position of b[o] (the filter's start offset)
function Filters.x86(b: buffer, o: number, n: number, start: number)
if n <= 4 then
return
@@ -167,7 +164,7 @@ function Filters.arm64(b: buffer, o: number, n: number, start: number)
end
end
-- delta(b, o, n, dist): b[i] += b[i - dist] (1 <= dist <= 256)
-- delta filter: b[i] += b[i - dist] (1 <= dist <= 256)
function Filters.delta(b: buffer, o: number, n: number, dist: number)
for i = dist, n - 1 do
writeu8(b, o + i, band(readu8(b, o + i) + readu8(b, o + i - dist), 255))
+6 -35
View File
@@ -1,21 +1,7 @@
--!strict
-- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
-- archive/xz, archive/7z (and anything else holding LZMA data) build on it. Decode only.
-- Written from the LZMA specification (LzmaSpec.cpp, Igor Pavlov, public domain) and the xz file format specification
-- 1.2 (Lasse Collin / Igor Pavlov, public domain); the BCJ filters follow xz-embedded (public domain).
--
-- local Lzma = require("@rosetta/codecs/compress/Lzma")
-- local out, e = Lzma.lzma(buf, off, len, props, unpackSize?, opts?) -- raw LZMA; props = 5-byte buffer / string
-- -- or { lc, lp, pb, dictSize }
-- local out, e = Lzma.lzma2(buf, off, len, dictSize?, unpackSize?, opts?) -- raw LZMA2 chunks
-- local out, e = Lzma.alone(buf, off?, len?, opts?) -- a .lzma file (13-byte header)
-- local out, e = Lzma.xz(buf, off?, len?, opts?) -- a .xz file (all streams concatenated)
-- Lzma.filter(id, buf, off, len, props?) -- BCJ / delta decode in place (7z)
--
-- Each returns buffer, consumedEnd (the input offset just past what was decoded) | nil, Err. opts.maxBytes (default
-- 2^30) bounds the output (Err.LIMIT). xz: every stream, block, index and footer is parsed and checked; check types
-- none / CRC-32 / CRC-64 are verified, SHA-256 is skipped (not verified). xz filters: LZMA2, delta, x86, PowerPC,
-- ARM, ARM-Thumb, SPARC, ARM64; IA-64 and RISC-V are Err.UNSUPPORTED. Never throws.
-- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container.
-- From LzmaSpec.cpp (Igor Pavlov) and the xz file format specification 1.2 (Lasse Collin / Igor Pavlov), both public
-- domain; the BCJ filters follow xz-embedded (public domain).
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Crc32 = require("@rosetta/core/Crc32")
@@ -30,7 +16,7 @@ local Lzma = {}
local DEFAULT_MAX = 2 ^ 30
export type Options = {
maxBytes: number?, -- refuse output larger than this (default 2^30)
maxBytes: number?,
}
export type Props = { lc: number, lp: number, pb: number, dictSize: number? }
@@ -42,7 +28,6 @@ local function maxOf(opts: Options?): number
return if type(m) == "number" and m >= 0 then m else DEFAULT_MAX
end
-- a decoder message -> Err
local function fail(msg: any, at: number?): Err.Err
local s = tostring(msg)
local code = Err.CORRUPT
@@ -54,7 +39,6 @@ local function fail(msg: any, at: number?): Err.Err
return Err.new(code, s, at)
end
-- props byte -> lc, lp, pb | nil
local function propsByte(d: number): (number?, number, number)
if d >= 225 then
return nil, 0, 0
@@ -63,8 +47,6 @@ local function propsByte(d: number): (number?, number, number)
end
Lzma.propsByte = propsByte
-- ------------------------------------------------------------------------------------------------ LZMA
-- decodeLzma(st, b, o, e, unpackSize?) -> consumedEnd | nil, Err: one raw LZMA stream into st (props set)
local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unpackSize: number?): (number?, Err.Err?)
local ip, ierr = Decode.rcInit(st, b, o, e)
if not ip then
@@ -87,7 +69,6 @@ local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unp
return res :: number, nil
end
-- lzma(buf, offset, length, props, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err
function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props: any, unpackSize: number?, opts: Options?): (buffer?, any)
local b, o, l, aerr = args("Lzma.lzma", buf, offset, length)
if not b then
@@ -125,7 +106,7 @@ function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props
return Decode.finish(st), consumed
end
-- alone(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: a .lzma file (props, dict size, u64 size)
-- .lzma file: props byte, dict size, u64 unpacked size
function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
local b, o, l, aerr = args("Lzma.alone", buf, offset, length)
if not b then
@@ -145,8 +126,6 @@ function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts
return Lzma.lzma(b, o + 13, l - 13, buffer.fromstring(buffer.readstring(b, o, 1)), size, opts)
end
-- ------------------------------------------------------------------------------------------------ LZMA2
-- decodeLzma2(st, b, o, e) -> consumedEnd | nil, Err: LZMA2 chunks up to the end-of-stream byte
local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?)
local p = o
local needDict, needProps = true, true
@@ -234,7 +213,6 @@ local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): (
end
end
-- lzma2(buf, offset?, length?, dictSize?, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err
function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dictSize: number?, unpackSize: number?, opts: Options?): (buffer?, any)
local b, o, l, aerr = args("Lzma.lzma2", buf, offset, length)
if not b then
@@ -252,7 +230,6 @@ function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dic
return Decode.finish(st), consumed
end
-- ------------------------------------------------------------------------------------------------ filters
-- filter ids (xz numbering; 7z's method ids map onto these in archive/7z)
Lzma.FILTER = table.freeze({
delta = 0x03,
@@ -275,8 +252,7 @@ local BCJ: { [number]: (buffer, number, number, number) -> () } = {
[0x0A] = Filters.arm64,
}
-- filter(id, buf, offset, length, props?) -> true | nil, Err: decode a BCJ / delta filter in place. props: the
-- filter's property bytes (a string or buffer: BCJ start offset u32le, delta distance - 1)
-- filter properties: BCJ start offset u32le, delta distance - 1
function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): (boolean?, Err.Err?)
local pb = toBuffer(props)
local plen = if pb then buffer.len(pb) else 0
@@ -301,11 +277,9 @@ function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?):
return true, nil
end
-- ------------------------------------------------------------------------------------------------ xz
local XZ_MAGIC = "\253" .. "7zXZ\0"
local CHECK_SIZE = { [0] = 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 }
-- vli(b, p, e) -> value, next | nil
local function vli(b: buffer, p: number, e: number): (number?, number)
local v, mul = 0, 1
for i = 0, 8 do
@@ -330,7 +304,6 @@ local function crc(b: buffer, o: number, n: number): number
return Crc32.raw(b, o, n)
end
-- one xz stream at o -> next offset | nil, Err (blocks appended to st)
local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?)
if o + 12 > e then
return nil, Err.new(Err.TRUNCATED, "truncated xz stream header", o)
@@ -521,7 +494,6 @@ local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (num
return q + 12, nil
end
-- xz(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: every stream (and stream padding) in the range
function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
local b, o, l, aerr = args("Lzma.xz", buf, offset, length)
if not b then
@@ -558,7 +530,6 @@ function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: O
return Decode.finish(st), p
end
-- isXz(buf, offset?) -> true when the bytes start an xz stream
function Lzma.isXz(b: buffer, o: number?): boolean
local off = o or 0
return off + 6 <= buffer.len(b) and buffer.readstring(b, off, 6) == XZ_MAGIC
+12 -35
View File
@@ -1,25 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
-- image/tiff build on it. New code (no port), written from the GIF89a spec (appendix F) and TIFF 6.0 section 13.
-- gif LSB-first codes, a minimum code size 1..11 (2..8 in GIF), clear = 2^min, EOI = clear + 1, the code width
-- grows when the next free code reaches 2^width (max 12 bits; a full table stays frozen until a clear).
-- tiff MSB-first codes, 8-bit symbols, clear = 256, EOI = 257, "early change": the width grows one code
-- earlier (next free code = 2^width - 1). Old-style (pre-6.0, LSB-first, no early change) TIFF LZW is
-- detected by its first bytes (0x00 then an odd byte) and decoded too.
-- zoo the gif layout with 8-bit symbols and codes up to 13 bits (Zoo archives' method 1; decode only).
--
-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "gif", minCodeSize) -- bytes written
-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "tiff")
-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "zoo")
-- local codes = Lzw.encode(data, off, len, "gif", minCodeSize) -- buffer
-- local codes = Lzw.encode(data, off, len, "tiff")
--
-- decode writes at most maxOut bytes at out[outOff ..] and returns how many it wrote; it stops at EOI, at the end of
-- the input or when out is full. err is nil for a clean stream, "truncated" when the input ended without EOI, or
-- "corrupt" for an impossible code (everything decoded up to it is kept). Never throws; the caller checks that
-- [outOff, outOff + maxOut) lies inside out and [off, off + len) inside src (decode clamps both anyway).
-- codecs/compress/Lzw: LZW decoder and encoder, from the GIF89a spec (appendix F) and TIFF 6.0 section 13 (new code).
-- gif: LSB-first, clear = 2^min, EOI = clear + 1, width grows when the next code reaches 2^width (max 12, then frozen).
-- tiff: MSB-first, clear = 256, EOI = 257, early change (at 2^width - 1). zoo (method 1): gif layout, up to 13 bits.
local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
local blen = buffer.len
@@ -29,14 +13,11 @@ local Lzw = {}
local MAX_CODES = 4096 -- 12-bit codes (GIF, TIFF)
local TABLE = 8192 -- the tables hold 13-bit codes (Zoo)
-- per-call tables (allocated once: decode / encode are not re-entrant across coroutines, but never yield)
local prefix = buffer.create(TABLE * 2) -- u16: the code this entry extends
local suffix = buffer.create(TABLE) -- u8: its last byte
local first = buffer.create(TABLE) -- u8: its first byte
local length = buffer.create(TABLE * 2) -- u16: its length
local prefix = buffer.create(TABLE * 2)
local suffix = buffer.create(TABLE)
local first = buffer.create(TABLE)
local length = buffer.create(TABLE * 2)
-- ------------------------------------------------------------------------------------------------ decode
-- writes the string of code c (length l) ending at out[o + l - 1]; clipped to [o, lim)
local function emit(out: buffer, o: number, c: number, l: number, lim: number)
local p = o + l - 1
if p < lim then
@@ -67,7 +48,7 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff:
return 0, "corrupt"
end
local msb = variant == "tiff"
local early = 0 -- 1 for TIFF's early change
local early = 0
local min = minCodeSize or 8
local maxCodes, maxBits = MAX_CODES, 12
if variant == "zoo" then
@@ -101,7 +82,6 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff:
local p = off
local acc, nb = 0, 0
while true do
-- refill (at most 13 + 7 bits held: below 2^21)
while nb < size do
if p >= e then
return o - outOff, "truncated"
@@ -133,7 +113,7 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff:
return o - outOff, nil
else
if o >= lim then
return o - outOff, nil -- full: the rest (normally just EOI) is ignored
return o - outOff, nil
end
if prev < 0 then
if c >= clear then
@@ -178,13 +158,10 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff:
end
end
-- ------------------------------------------------------------------------------------------------ encode
local HASH = 8192 -- open addressing over (prefix << 8 | byte) keys: a power of two above 4096 entries
local hkey = buffer.create(HASH * 4) -- i32 key + 1 (0 = empty)
local hval = buffer.create(HASH * 2) -- u16 code
local HASH = 8192
local hkey = buffer.create(HASH * 4)
local hval = buffer.create(HASH * 2)
-- encode(data, off, len, variant, minCodeSize?) -> the code stream (GIF: without the sub-block framing). Symbols in
-- data must be below 2^minCodeSize (GIF; larger ones are masked) or bytes (TIFF).
function Lzw.encode(data: buffer, off: number, len: number, variant: string, minCodeSize: number?): buffer
local msb = variant == "tiff"
local min = if msb then 8 else math.clamp(minCodeSize or 8, 1, 11)
+6 -23
View File
@@ -1,19 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes,
-- verbatim, aligned offset and uncompressed blocks (block sizes of 24 bits, blocks spanning frames), the main and
-- length trees sent as deltas of the previous block's code lengths through a 20-symbol pre-tree (runs 17 / 18 / 19),
-- the three repeated offsets R0..R2, the Intel E8 call translation header (applied to the first 32768 frames, on the
-- output only), and the stream cut into frames of 32768 output bytes, each 16-bit aligned at its end; trees, offsets
-- and the window persist across the frames (the CFDATA blocks) of a folder. Written from the specification
-- (Microsoft's LZX data format documentation in the Cabinet SDK and the LZX sections of [MS-PATCH]); no code from
-- libmspack. Not supported: LZX DELTA reference data and reset intervals (CHM / WIM variants).
--
-- local out, err = Lzx.decode(src, offset, length, outSize, windowBits) -- buffer | nil, message
--
-- src[offset, offset + length) is the folder's compressed data (the CFDATA payloads concatenated), outSize its exact
-- uncompressed size. Never throws: bad or truncated data returns nil, message.
-- codecs/compress/Lzx: the LZX decoder for Microsoft Cabinet folders (windows of 2^15 .. 2^21 bytes).
-- Written from Microsoft's LZX data format documentation (Cabinet SDK) and [MS-PATCH]; no code from libmspack.
-- Frames of 32768 output bytes, 16-bit aligned at their ends; trees, R0..R2 and the window persist across a folder.
local Huffman = require("@rosetta/codecs/entropy/Huffman")
local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
@@ -43,9 +33,7 @@ do
end
local SLOTS: { [number]: number } = { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 }
-- ------------------------------------------------------------------------------------------------ bit reader
-- 16-bit little-endian words read most significant bit first; bb holds cnt bits left aligned (cnt <= 32). Past the
-- end, zero words are read and over counts their bits.
-- 16-bit little-endian words, read most significant bit first
type State = { src: buffer, pos: number, stop: number, bb: number, cnt: number, over: number }
local function refill(s: State)
@@ -67,7 +55,6 @@ local function refill(s: State)
end
end
-- bits(s, n) -> the next n (1..17) bits
local function bits(s: State, n: number): number
if s.cnt < n then
refill(s)
@@ -78,7 +65,6 @@ local function bits(s: State, n: number): number
return v
end
-- sym(s, tab, P, S) -> the next symbol of an MSB Huffman table, -1 for an invalid code
local function sym(s: State, tab: buffer, P: number, S: number): number
if s.cnt < 16 then
refill(s)
@@ -100,7 +86,7 @@ local function sym(s: State, tab: buffer, P: number, S: number): number
return rshift(e, 5)
end
-- readLens: the code lengths lens[first, last) as deltas of their previous values, through a fresh pre-tree
-- code lengths as deltas of their previous values, through a fresh 20-symbol pre-tree (runs 17 / 18 / 19)
local function readLens(s: State, lens: buffer, first: number, last: number, pre: buffer, preLens: buffer): boolean
for i = 0, 19 do
writeu8(preLens, i, bits(s, 4))
@@ -145,8 +131,7 @@ local function readLens(s: State, lens: buffer, first: number, last: number, pre
return true
end
-- ------------------------------------------------------------------------------------------------ decode
-- E8 translation of the decoded output, frame by frame (absolute call targets back to relative)
-- E8 translation, frame by frame: absolute call targets back to relative
local function translate(out: buffer, n: number, size: number)
local base = 0
local frame = 0
@@ -199,7 +184,6 @@ function Lzx.decode(src: buffer, offset: number, length: number, outSize: number
local frameEnd = math.min(op + FRAME, outSize)
while op < frameEnd do
if bremain == 0 then
-- a new block
if btype == 3 and band(bsize, 1) == 1 then
s.pos += 1
end
@@ -283,7 +267,6 @@ function Lzx.decode(src: buffer, offset: number, length: number, outSize: number
local aligned = btype == 2
local start = op
while op < runEnd do
-- refill to at least 17 bits
while cnt <= 16 do
local w = 0
if pos + 2 <= stop then
+2 -9
View File
@@ -1,18 +1,12 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF
-- ByteRun1, ...): a header byte n < 128 copies n + 1 literal bytes, n > 128 repeats the next byte 257 - n times,
-- 128 is a no-op. Decode and encode; moved here from image/tiff (TIFF and PSD both carried a decoder). Never throws.
--
-- local written, srcEnd, clean = PackBits.decode(src, p, limit, dst, d, n) -- up to n bytes into dst at d
-- local packed = PackBits.encode(src, offset, length) -- a buffer (one row at a time)
-- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD RLE, IFF ByteRun1).
-- Header byte n < 128 copies n + 1 literal bytes, n > 128 repeats the next byte 257 - n times, 128 is a no-op.
local PackBits = {}
local readu8, writeu8 = buffer.readu8, buffer.writeu8
-- decode(src, p, limit, dst, d, n) -> bytes written (<= n), the source offset after the codes used, clean (false when
-- the source ran out before n bytes or a run overflowed n: lenient callers keep what was written, strict ones fail)
function PackBits.decode(src: buffer, p: number, limit: number, dst: buffer, d: number, n: number): (number, number, boolean)
local o, lim = d, d + n
local clean = true
@@ -56,7 +50,6 @@ function PackBits.decode(src: buffer, p: number, limit: number, dst: buffer, d:
return o - d, p, clean
end
-- encode(src, offset, length) -> buffer: runs of 3+ equal bytes as repeats, the rest as literals (at most 128 each)
function PackBits.encode(src: buffer, off: number, len: number): buffer
local out = buffer.create(len + (len + 127) // 128 + 8)
local o = 0
+4 -20
View File
@@ -1,20 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft
-- Cabinet folders use it: windows of 2^10 .. 2^21 bytes; a 16-bit arithmetic decoder (H / L / C registers with
-- underflow handling) over a most-significant-bit-first byte stream; eight adaptive frequency models (the
-- 7-symbol selector, four 64-symbol literal models, the offset models for matches of 3, 4 and 5..259 bytes and the
-- 27-symbol length model) whose cumulative frequencies grow by 8 per symbol and are rescaled above 3800 (halved, and
-- every 50th time rebuilt from the frequencies and re-sorted); position and length footers read as raw bits from the
-- same stream. Each CFDATA block is one frame (at most 32768 output bytes) that restarts the arithmetic coder; the
-- models and the window persist across the frames of a folder. Written from the public descriptions of the format
-- (the Quantum notes by Matthew Russotto and the cabinet documentation); no code from libmspack.
--
-- local out, err = Quantum.decode(src, blocks, outSize, windowBits) -- buffer | nil, message
--
-- blocks = { { at, len, size } }: each block's compressed bytes src[at, at + len) and its output size; outSize is
-- their total. Never throws: bad or truncated data returns nil, message.
-- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 + adaptive arithmetic coder) for Cabinet folders.
-- Written from Matthew Russotto's Quantum notes and the cabinet documentation; no code from libmspack. Frequencies grow
-- by 8 and rescale above 3800 (halved; every 50th time rebuilt and re-sorted); each CFDATA frame restarts the coder.
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
local readu8, writeu8 = buffer.readu8, buffer.writeu8
@@ -45,8 +34,7 @@ do
end
end
-- ------------------------------------------------------------------------------------------------ models
-- an adaptive model: symbols sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0)
-- model: sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0)
type Model = { n: number, sym: { number }, cum: { number }, shifts: number }
local function model(first: number, n: number): Model
@@ -92,8 +80,6 @@ local function rescale(m: Model)
end
end
-- ------------------------------------------------------------------------------------------------ decode
-- the coder and bit reader of one frame
type Coder = { src: buffer, pos: number, stop: number, acc: number, cnt: number, over: number, H: number, L: number, C: number, bad: boolean }
local function bit(c: Coder): number
@@ -112,7 +98,6 @@ local function bit(c: Coder): number
return band(rshift(c.acc, c.cnt), 1)
end
-- raw(c, n) -> the next n (0..19) bits, most significant first
local function raw(c: Coder, n: number): number
local v = 0
for _ = 1, n do
@@ -127,7 +112,6 @@ local function symbol(c: Coder, m: Model): number
local range = H - L + 1
local total = cum[1]
if range <= 0 or C < L or C > H then
-- only corrupt registers get here (the decoder keeps L <= C <= H)
c.bad = true
return 0
end
+13 -30
View File
@@ -1,24 +1,16 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code
-- width 9..16 and the block mode bit), decode and encode. A codec (layer 3): archive/z builds on it. Codes are
-- LSB-first, 9 bits wide at the start; the width grows when the next free code passes 2^width - 1 (up to the
-- maximum), and in block mode code 256 clears the table. compress writes codes in groups of eight: when the width
-- changes or a CLEAR is read, the rest of the current group (counted from the previous change) is skipped. The encoder
-- reproduces ncompress 5.0 bit for bit: greedy longest match, a full table frozen until the compression ratio checked
-- every 10000 input bytes drops, then a CLEAR. Written from the ncompress sources (public domain, The Unlicense: read
-- for the format and the encoder's ratio check; licenses/ncompress-UNLICENSE.txt). Never throws.
--
-- local out, err = UnixCompress.decompress(buf, offset?, length?, { maxBytes = 2^28 }) -- a whole .Z file
-- local z = UnixCompress.compress(buf, offset?, length?, { maxBits = 16 }) -- -> a .Z file
-- codecs/compress/UnixCompress: the LZW of Unix compress (.Z: magic 1F 9D, a flags byte: max width 9..16, block mode).
-- From the ncompress sources (public domain: licenses/ncompress-UNLICENSE.txt); the encoder matches ncompress 5.0.
-- LSB-first codes from 9 bits; block mode code 256 clears; a width change or CLEAR skips the rest of the 8-code group.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local UnixCompress = {}
export type DecodeOptions = { maxBytes: number? } -- refuse output larger than this (default 2^30)
export type EncodeOptions = { maxBits: number? } -- 9..16, default 16
export type DecodeOptions = { maxBytes: number? }
export type EncodeOptions = { maxBits: number? }
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
@@ -27,14 +19,11 @@ local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
local MAXCODES = 65536
local CHECK_GAP = 10000
-- decoder tables (per call state lives in locals; the tables are reused: decode never yields)
local prefix = bcreate(MAXCODES * 4) -- u32: the code an entry extends
local suffix = bcreate(MAXCODES) -- u8: its last byte
local first = bcreate(MAXCODES) -- u8: its first byte
local length = bcreate(MAXCODES * 4) -- u32: its length
local prefix = bcreate(MAXCODES * 4)
local suffix = bcreate(MAXCODES)
local first = bcreate(MAXCODES)
local length = bcreate(MAXCODES * 4)
-- ------------------------------------------------------------------------------------------------ decode
-- decompress(buf, offset?, length?, opts?) -> buffer | nil, Err
function UnixCompress.decompress(buf: buffer | string, offset: number?, len: number?, opts: DecodeOptions?): (buffer?, Err.Err?)
local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len)
if not b then
@@ -68,8 +57,8 @@ function UnixCompress.decompress(buf: buffer | string, offset: number?, len: num
local op = 0
local totalBits = (n - 3) * 8
local base = o + 3
local pos = 0 -- bit position from the first code
local gbase = 0 -- where the current group sequence starts
local pos = 0
local gbase = 0
local nbits = 9
local mask = 511
local maxcode = 511
@@ -85,7 +74,6 @@ function UnixCompress.decompress(buf: buffer | string, offset: number?, len: num
mask = lshift(1, nbits) - 1
continue
end
-- the code: up to 23 bits from three bytes
local q = base + rshift(pos, 3)
local acc = readu8(b, q)
if q + 1 < o + n then
@@ -157,12 +145,10 @@ function UnixCompress.decompress(buf: buffer | string, offset: number?, len: num
return res, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local HSIZE = 1 * 131072 -- open addressing over (prefix << 8 | byte) + 1 keys: twice the 65536 entries
local HSIZE = 1 * 131072
local hkey = bcreate(HSIZE * 4)
local hval = bcreate(HSIZE * 4)
-- compress(buf, offset?, length?, opts?) -> a .Z file (block mode) | nil, Err
function UnixCompress.compress(buf: buffer | string, offset: number?, len: number?, opts: EncodeOptions?): (buffer?, Err.Err?)
local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len)
if not b then
@@ -172,7 +158,6 @@ function UnixCompress.compress(buf: buffer | string, offset: number?, len: numbe
if type(maxbits) ~= "number" or maxbits < 9 or maxbits > 16 or maxbits % 1 ~= 0 then
return nil, Err.new(Err.ARG, "maxBits must be 9..16")
end
-- at most 17 bits per input byte, plus group padding (< one group per width change / clear)
local cap = 3 + n * 2 + 64
local out = bcreate(cap)
writeu8(out, 0, 0x1F)
@@ -180,7 +165,7 @@ function UnixCompress.compress(buf: buffer | string, offset: number?, len: numbe
writeu8(out, 2, bor(maxbits, 0x80))
local outbits = 24
local boff = 24
local acc, nb = 0, 0 -- pending bits not yet written (below 2^24)
local acc, nb = 0, 0
local nbits = 9
local extcode = 513
local maxmax = lshift(1, maxbits)
@@ -290,7 +275,6 @@ function UnixCompress.compress(buf: buffer | string, offset: number?, len: numbe
checks(i - o)
end
if rshift(outbits, 3) + 8 > cap then
-- grow (rare: only incompressible input passes 2 bytes per byte)
local ncap = cap * 2
local nbuf = bcreate(ncap)
bcopy(nbuf, 0, out, 0, cap)
@@ -310,7 +294,6 @@ function UnixCompress.compress(buf: buffer | string, offset: number?, len: numbe
return res, nil
end
-- isCompress(buf, offset?) -> true when the bytes at offset start a .Z file
function UnixCompress.isCompress(b: buffer, o: number?): boolean
local p = o or 0
return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D
+2 -7
View File
@@ -1,11 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content
-- checksums. 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double.
-- From the xxHash specification (Yann Collet, BSD-2); no code copied. Never throws (the range is clamped to the buffer).
--
-- local h = Xxh32.hash(buf, offset?, length?, seed?) -- a number in 0 .. 2^32 - 1
-- codecs/compress/Xxh32: XXH32 for the LZ4 frame checksums, from the xxHash specification (Yann Collet, BSD-2).
-- 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double.
local Xxh32 = {}
local bxor, bor, lshift, rshift = bit32.bxor, bit32.bor, bit32.lshift, bit32.rshift
@@ -14,7 +11,6 @@ local readu8, readu32 = buffer.readu8, buffer.readu32
local T32 = 4294967296
local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1
-- a * b mod 2^32 (a, b below 2^32)
local function mul(a: number, b: number): number
local a0 = a % 65536
local a1 = (a - a0) / 65536
@@ -29,7 +25,6 @@ local function round(acc: number, lane: number): number
return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1)
end
-- hash(buf, offset?, length?, seed?) -> XXH32
function Xxh32.hash(b: buffer, offset: number?, length: number?, seed: number?): number
local n0 = buffer.len(b)
local o = math.clamp(offset or 0, 0, n0)
+4 -28
View File
@@ -1,16 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the
-- BSD reference implementation). Frames (any number, concatenated), skippable frames, raw / RLE / compressed blocks,
-- Huffman literals (1 or 4 streams, new or repeated table), FSE sequence tables (predefined / RLE / compressed /
-- repeat), repeat offsets, the XXH64 content checksum. Not supported: dictionaries (a non-zero dictionary ID).
--
-- The whole output lives in one buffer, so the window is the output itself (offsets are checked against the frame's
-- start). Backward bitstreams are read through bit offsets: bits [o - n, o) of a stream come from one readu32 at
-- byte (o - n) / 8, bits before the stream start read as zeros.
--
-- Nothing here throws on any input: every read is bounds-checked; failures return nil, code, message, offset.
-- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no reference code).
-- Backward bitstreams: bits [o - n, o) come from one readu32 at byte (o - n) / 8; bits before the stream read as zeros.
local Xxh64 = require("@rosetta/codecs/compress/Zstd/Xxh64")
local band, lshift, rshift = bit32.band, bit32.lshift, bit32.rshift
@@ -22,7 +14,6 @@ local BLOCK_MAX = 131072
local Decode = {}
-- ------------------------------------------------------------------------------------------------ tables
-- literal length / match length codes: baseline, extra bits (index = code + 1)
local LL_BASE = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 }
local LL_BITS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }
@@ -41,7 +32,6 @@ local ML_DEFAULT = {
}
local OF_DEFAULT = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1 }
-- highest set bit of 1..2048
local HB = table.create(2048, 0)
do
local v = 0
@@ -53,8 +43,6 @@ do
end
end
-- ------------------------------------------------------------------------------------------------ bit readers
-- backward stream starting at byte s: bits [o - n, o) (n <= 25), bits below 0 are zeros
local function peek(b: buffer, s: number, o: number, n: number): number
if n <= 0 then
return 0
@@ -82,7 +70,6 @@ local function peek(b: buffer, s: number, o: number, n: number): number
return lshift(peek(b, s, o, o), -lo)
end
-- the bit length of a backward stream [s, e) (up to its end marker), or -1 when the last byte is 0 / it is empty
local function streamBits(b: buffer, s: number, e: number): number
if e <= s then
return -1
@@ -94,7 +81,6 @@ local function streamBits(b: buffer, s: number, e: number): number
return (e - 1 - s) * 8 + HB[last]
end
-- forward stream: n (<= 24) bits at bit position bp from byte p; bytes at or past e read as zeros
local function getF(b: buffer, p: number, e: number, bp: number, n: number): number
local byte = p + rshift(bp, 3)
local v = 0
@@ -108,11 +94,10 @@ local function getF(b: buffer, p: number, e: number, bp: number, n: number): num
return band(rshift(v, band(bp, 7)), lshift(1, n) - 1)
end
-- ------------------------------------------------------------------------------------------------ FSE
-- FSE decoding table entries (u32): symbol | nbBits << 8 | newStateBase << 16
local symTmp = bcreate(512)
-- build(norm, nsym, al, t) -> true | nil, message. norm: { [symbol + 1] = normalized count (-1 = "less than 1") }
-- normalized counts: { [symbol + 1] = count }, -1 = "less than 1" probability
local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): (boolean?, string?)
local size = lshift(1, al)
local high = size - 1
@@ -166,7 +151,6 @@ local function buildFse(norm: { number }, nsym: number, al: number, t: buffer):
return true, nil
end
-- ncount(b, p, e, maxSym, maxAL, norm) -> al, bytesUsed, nsym | nil, message: an FSE table description
local function ncount(b: buffer, p: number, e: number, maxSym: number, maxAL: number, norm: { number }): (number?, any, number?)
if p >= e then
return nil, "truncated FSE table"
@@ -251,8 +235,7 @@ local function predefined(dist: { number }, al: number): buffer
end
local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, 6), predefined(OF_DEFAULT, 5)
-- ------------------------------------------------------------------------------------------------ Huffman
-- hufTable(b, p, e, st) -> bytesUsed | nil, message: a Huffman tree description into st.huf (u16: sym | nbBits << 8)
-- Huffman table entry (u16): sym | nbBits << 8
local weights = bcreate(256)
local wfse = bcreate(64 * 4)
local function hufTable(b: buffer, p: number, e: number, st: any): (number?, string?)
@@ -380,7 +363,6 @@ local function hufTable(b: buffer, p: number, e: number, st: any): (number?, str
return used, nil
end
-- one Huffman stream [s, e) -> cnt literals at lit[dp] | nil, message
local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number, lit: buffer, dp: number, cnt: number): string?
local off = streamBits(b, s, e)
if off < 0 then
@@ -411,8 +393,6 @@ local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number,
return nil
end
-- ------------------------------------------------------------------------------------------------ frames
-- grow st.out to hold need bytes (doubling, capped at st.maxBytes): true | false (over the limit)
local function grow(st: any, need: number): boolean
if need > st.maxBytes then
return false
@@ -424,7 +404,6 @@ local function grow(st: any, need: number): boolean
return true
end
-- a compressed block [p, e): nil (ok) | code, message
local function block(b: buffer, p: number, e: number, st: any): (string?, string?)
-- literals section
local b0 = readu8(b, p)
@@ -759,7 +738,6 @@ local function block(b: buffer, p: number, e: number, st: any): (string?, string
bfill(out, op, readu8(out, from), ml)
op += ml
else
-- overlapping: copy in chunks of `offset` bytes (each chunk's source precedes its destination)
local left = ml
while left > 0 do
local n = if left < offset then left else offset
@@ -790,7 +768,6 @@ local function block(b: buffer, p: number, e: number, st: any): (string?, string
return nil, nil
end
-- decompress(b, start, stop, maxBytes, verify) -> out, length, consumedEnd | nil, code, message, offset
function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: number, verify: boolean): (buffer?, any, any, any)
local st: any = {
out = bcreate(math.min(maxBytes, math.max(4096, (stop - start) * 3))),
@@ -903,7 +880,6 @@ function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: num
st.rep1, st.rep2, st.rep3 = 1, 4, 8
st.hufBits = nil
table.clear(st.tabs)
-- blocks
local last = false
repeat
if pos + 3 > stop then
+3 -8
View File
@@ -1,10 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have
-- no 64-bit integers). 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is
-- exact below 2^53. From the xxHash specification (Yann Collet, BSD-2); no code copied. zstd stores the low 32 bits
-- of the hash as the frame content checksum. Never throws (the caller passes an in-range buffer slice).
-- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) on 32-bit halves, from the xxHash specification (Yann Collet, BSD-2).
-- 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is exact below 2^53.
local bor, bxor, lshift, rshift = bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
local readu8, readu32 = buffer.readu8, buffer.readu32
@@ -16,7 +14,6 @@ local P3H, P3L = 0x165667B1, 0x9E3779F9
local P4H, P4L = 0x85EBCA77, 0xC2B2AE63
local P5H, P5L = 0x27D4EB2F, 0x165667C5
-- (ah, al) * (bh, bl) mod 2^64
local function mul(ah: number, al: number, bh: number, bl: number): (number, number)
local a0 = al % 65536
local a1 = (al - a0) / 65536
@@ -41,7 +38,6 @@ local function add(ah: number, al: number, bh: number, bl: number): (number, num
return h % T32, l
end
-- rotl by r in 1..31
local function rotl(h: number, l: number, r: number): (number, number)
return bor(lshift(h, r), rshift(l, 32 - r)), bor(lshift(l, r), rshift(h, 32 - r))
end
@@ -49,7 +45,7 @@ end
local P1L0, P1L1 = P1L % 65536, P1L // 65536
local P2L0, P2L1 = P2L % 65536, P2L // 65536
-- acc = rotl(acc + input * P2, 31) * P1, with both products written out (the hot path: 4 per 32 input bytes)
-- round: acc = rotl(acc + input * P2, 31) * P1
local function round(ah: number, al: number, ih: number, il: number): (number, number)
local a0 = il % 65536
local a1 = (il - a0) / 65536
@@ -87,7 +83,6 @@ end
local Xxh64 = {}
-- hash(b, offset, length) -> hi, lo (the 64-bit hash as two unsigned 32-bit halves)
function Xxh64.hash(b: buffer, offset: number, length: number): (number, number)
local p = offset
local e = offset + length
+4 -17
View File
@@ -1,15 +1,5 @@
--!strict
-- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
-- data build on it. Written from the specification. Supports every frame feature a dictionary-less stream uses:
-- concatenated and skippable frames, raw / RLE / compressed blocks, Huffman literals (1 / 4 streams, repeated tables),
-- predefined / RLE / compressed / repeated FSE tables, repeat offsets, the XXH64 content checksum (verified).
-- Not supported: dictionaries (Err.UNSUPPORTED), compression.
--
-- local Zstd = require("@rosetta/codecs/compress/Zstd")
-- local out, err = Zstd.decompress(buf) -- -> buffer, consumedEnd | nil, Err
-- local out, err = Zstd.decompress(buf, off, len, { maxBytes = 2^24, verify = false })
--
-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / UNSUPPORTED / LIMIT / ARG).
-- codecs/compress/Zstd: Zstandard decompression (RFC 8878), written from the specification; no dictionaries.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Decode = require("@rosetta/codecs/compress/Zstd/Decode")
@@ -17,14 +7,13 @@ local Decode = require("@rosetta/codecs/compress/Zstd/Decode")
local Zstd = {}
export type Options = {
maxBytes: number?, -- refuse output larger than this (default 2^30)
verify: boolean?, -- check the content checksum when a frame has one (default true)
maxBytes: number?,
verify: boolean?,
}
-- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F)
Zstd.MAGIC = "\40\181\47\253"
-- isFrame(buf, offset?) -> true when a zstd (or skippable) frame starts there
function Zstd.isFrame(buf: buffer, offset: number?): boolean
local o = offset or 0
if type(buf) ~= "buffer" or o < 0 or o + 4 > buffer.len(buf) then
@@ -34,8 +23,7 @@ function Zstd.isFrame(buf: buffer, offset: number?): boolean
return m == 0xFD2FB528 or bit32.band(m, 0xFFFFFFF0) == 0x184D2A50
end
-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. Every frame in the range is decoded
-- and the outputs concatenated; data after the last frame that is not a frame is an error (as zstd -d does).
-- data after the last frame that is not a frame is an error, as zstd -d does
function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
local b, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length)
if not b then
@@ -58,7 +46,6 @@ function Zstd.decompress(buf: buffer | string, offset: number?, length: number?,
return out, consumed
end
-- xxh64(buf, offset?, length?) -> hi, lo: the XXH64 hash (seed 0) as two unsigned 32-bit halves
function Zstd.xxh64(buf: buffer, offset: number?, length: number?): (number, number)
local o = math.clamp(offset or 0, 0, buffer.len(buf))
local l = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o)
+8 -34
View File
@@ -1,18 +1,10 @@
--!strict
--!native
-- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders.
--
-- Decoding tables (built by buildLsb / buildMsb) are u32 buffers, indexed by the next P bits of the stream:
-- entry = symbol * 32 + length a code of `length` <= P bits
-- entry = offset * 32 (length 0) a link: index offset + the following S bits (subtable of 2^S entries)
-- entry = 0 no code (incomplete code set): the stream is corrupt
-- so a symbol is one or two table reads. LSB tables (DEFLATE, VP8L) are indexed by bit-reversed codes, MSB tables
-- (JPEG, MPEG) by the code itself. Code lengths are 1..MAXLEN (16), symbols < 2^27.
-- The hot loops (codecs/compress/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a
-- core/Bits reader.
--
-- Encoding: lengths(freqs, maxLen) -> length-limited code lengths; codes(lengths) -> canonical code values.
-- Never throws: bad code sets return -1 / nil.
-- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order).
-- Decoding table entry (u32, indexed by the next P bits; LSB tables by bit-reversed codes, MSB tables by the code):
-- symbol * 32 + length a code of length <= P bits
-- offset * 32 a link: index offset + the following S bits (subtable of 2^S entries)
-- 0 no code (incomplete code set)
local Bits = require("@rosetta/core/Bits")
local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
@@ -24,7 +16,6 @@ local MAXLEN = 16
local Huffman = {}
Huffman.MAXLEN = MAXLEN
-- 8-bit reversal
local REV = table.create(256, 0)
for i = 0, 255 do
local r, v = 0, i
@@ -35,13 +26,11 @@ for i = 0, 255 do
REV[i + 1] = r
end
-- reverse(code, len) -> the low len bits of code reversed (len <= 16)
local function reverse(code: number, len: number): number
return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len)
end
Huffman.reverse = reverse
-- capacity(nsym, P, maxLen) -> the table entries (u32) needed for nsym symbols, primary width P, codes up to maxLen
function Huffman.capacity(nsym: number, P: number, maxLen: number): number
return 2 ^ P + (if maxLen > P then nsym * 2 ^ (maxLen - P) else 0)
end
@@ -90,7 +79,6 @@ local function build(lens: buffer, off: number, n: number, tab: buffer, P: numbe
local entry = s * 32 + l
if l <= P then
if msb then
-- the code is the top l bits of the P-bit index: fill every completion of the low bits
local first = lshift(c, P - l)
local last = first + lshift(1, P - l) - 1
for i = first, last do
@@ -124,7 +112,7 @@ local function build(lens: buffer, off: number, n: number, tab: buffer, P: numbe
else
sub = rshift(e, 5)
end
local k = l - P -- bits of the code in the subtable index
local k = l - P
if msb then
local first = lshift(rest, S - k)
for i = first, first + lshift(1, S - k) - 1 do
@@ -144,19 +132,14 @@ local function build(lens: buffer, off: number, n: number, tab: buffer, P: numbe
return S
end
-- buildLsb(lens, off, n, tab, P) -> S: a table for the code lengths lens[off .. off + n - 1] (u8), indexed by the next
-- P bits LSB-first (bit-reversed codes). S = the subtable width (0 when no code is longer than P), -1 = an
-- over-subscribed or invalid code set. tab must hold capacity(n, P, maxLen) u32 entries.
function Huffman.buildLsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number
return build(lens, off, n, tab, P, false)
end
-- buildMsb(lens, off, n, tab, P) -> S: the same, indexed by the next P bits MSB-first
function Huffman.buildMsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number
return build(lens, off, n, tab, P, true)
end
-- decodeLsb(br, tab, P, S) -> symbol, or -1 for an invalid code (br: a core/Bits LSB reader)
function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number
local e = readu32(tab, br:peek(P) * 4)
local l = band(e, 31)
@@ -175,7 +158,6 @@ function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number
return rshift(e, 5)
end
-- decodeMsb(br, tab, P, S) -> symbol, or -1 (br: a core/Bits MSB reader)
function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number
local e = readu32(tab, br:peek(P) * 4)
local l = band(e, 31)
@@ -194,8 +176,6 @@ function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number
return rshift(e, 5)
end
-- codes(lengths) -> canonical code values (MSB-first, as written by an MSB writer; reverse() them for LSB streams).
-- lengths: { number } indexed 1..n (symbol + 1), 0 = unused.
function Huffman.codes(lengths: { number }): { number }
local cnt = table.create(MAXLEN + 1, 0)
for _, l in lengths do
@@ -219,12 +199,9 @@ function Huffman.codes(lengths: { number }): { number }
return out
end
-- lengths(freqs, maxLen) -> code lengths ({ number }, same indexing as freqs), at most maxLen bits, optimal without
-- the limit; over the limit, the JPEG Annex K.3 adjustment. A single used symbol gets length 1.
function Huffman.lengths(freqs: { number }, maxLen: number): { number }
local n = #freqs
local out = table.create(n, 0)
-- leaves sorted by frequency (ties by symbol, for determinism)
local syms = {}
for i = 1, n do
if freqs[i] > 0 then
@@ -244,14 +221,13 @@ function Huffman.lengths(freqs: { number }, maxLen: number): { number }
end
return a < b
end)
-- two-queue Huffman: leaves (sorted) and internal nodes (created in increasing weight order)
local m = #syms
local weight = table.create(2 * m, 0)
local parent = table.create(2 * m, 0)
for i = 1, m do
weight[i] = freqs[syms[i]]
end
local li, ni, nn = 1, m + 1, m + 1 -- next leaf, next internal node to take, next free node
local li, ni, nn = 1, m + 1, m + 1
local function take(): number
if li <= m and (ni >= nn or weight[li] <= weight[ni]) then
li += 1
@@ -268,12 +244,11 @@ function Huffman.lengths(freqs: { number }, maxLen: number): { number }
parent[b] = nn
nn += 1
end
-- depths: the root is nn - 1
local depth = table.create(2 * m, 0)
for i = nn - 2, 1, -1 do
depth[i] = depth[parent[i]] + 1
end
-- count codes per length; limit (JPEG K.3: move pairs from the deepest level up)
-- length limiting: JPEG Annex K.3 (move pairs from the deepest level up)
local bl = table.create(m + maxLen + 2, 0)
local deepest = 0
for i = 1, m do
@@ -292,7 +267,6 @@ function Huffman.lengths(freqs: { number }, maxLen: number): { number }
bl[j] -= 1
end
end
-- the longest codes go to the least frequent symbols (syms is sorted ascending)
local k = 1
for l = math.min(deepest, maxLen), 1, -1 do
for _ = 1, bl[l] do
@@ -1,10 +1,9 @@
--!strict
--!native
--!optimize 2
-- codecs/entropy/RangeCoder/Decoder: the Opus range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus
-- frame from a `buffer` slice [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice
-- backwards.
-- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52.
-- codecs/entropy/RangeCoder/Decoder: the Opus range decoder (RFC 6716 4.1), a port of libopus celt/entdec.c (BSD:
-- licenses/libopus-BSD.txt). Raw bits (ec_dec_bits) are read from the end of the frame backwards.
-- All values stay below 2^32, so floor division on plain numbers is exact.
local RangeDecoder = {}
export type Dec = {
@@ -54,7 +53,7 @@ local function normalize(d: Dec)
else
rem = 0
end
sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA) -- (sym << 8 | rem) >> 1
sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA)
val = band(val * 256 + band(SYM_MAX, bit32.bnot(sym)), CODE_TOP - 1)
end
d.rng, d.val, d.rem = rng, val, rem
@@ -87,7 +86,6 @@ function RangeDecoder.new(buf: buffer, base: number, storage: number): Dec
return d
end
-- ec_decode: the cumulative frequency of the next symbol, for a total of ft
function RangeDecoder.decode(d: Dec, ft: number): number
local ext = d.rng // ft
d.ext = ext
@@ -129,7 +127,6 @@ function RangeDecoder.bitLogp(d: Dec, logp: number): boolean
return ret
end
-- ec_dec_icdf over a Luau array (1-based) starting at index `off` (icdf[off] is entry 0)
function RangeDecoder.icdf(d: Dec, icdf: { number }, off: number, ftb: number): number
local s = d.rng
local v = d.val
@@ -1,10 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/entropy/RangeCoder/Encoder: the Opus range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD:
-- licenses/libopus-BSD.txt), the mirror of codecs/entropy/RangeCoder/Decoder. Writes one fixed-size frame: the range-coded
-- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain
-- numbers. Never throws: running out of room sets `error`.
-- codecs/entropy/RangeCoder/Encoder: the Opus range encoder (RFC 6716 5.1), a port of libopus celt/entenc.c (BSD:
-- licenses/libopus-BSD.txt). Range-coded symbols from the front of the frame, raw bits (ec_enc_bits) from the back.
local RangeEncoder = {}
export type Enc = {
@@ -37,7 +35,6 @@ local function ilog(x: number): number
end
RangeEncoder.ilog = ilog
-- new(storage) -> Enc over a fresh zeroed buffer of storage bytes
function RangeEncoder.new(storage: number): Enc
return {
buf = buffer.create(math.max(storage, 1)),
@@ -101,7 +98,6 @@ local function normalize(e: Enc)
end
end
-- encode(fl, fh, ft): the symbol [fl, fh) of ft
function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number)
local r = floor(e.rng / ft)
if fl > 0 then
@@ -113,7 +109,6 @@ function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number)
normalize(e)
end
-- encodeBin(fl, fh, bits): ft = 2^bits
function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number)
local ft = 2 ^ bits
local r = floor(e.rng / ft)
@@ -126,7 +121,6 @@ function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number)
normalize(e)
end
-- bitLogp(v, logp): a bit whose probability of being 1 is 2^-logp
function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number)
local r = e.rng
local s = floor(r / 2 ^ logp)
@@ -140,7 +134,6 @@ function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number)
normalize(e)
end
-- icdf(s, icdf, ftb): symbol s (0-based) of an inverse CDF table (1-based Luau array) with 2^ftb total
function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number)
local r = floor(e.rng / 2 ^ ftb)
if s > 0 then
@@ -152,7 +145,6 @@ function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number)
normalize(e)
end
-- bits(fl, n): n raw bits (n <= 25), written from the end of the frame
function RangeEncoder.bits(e: Enc, fl: number, n: number)
local window = e.end_window
local used = e.nend_bits
@@ -170,7 +162,6 @@ function RangeEncoder.bits(e: Enc, fl: number, n: number)
e.nbits_total += n
end
-- uint(fl, ft): fl uniformly in [0, ft), ft up to 2^32
function RangeEncoder.uint(e: Enc, fl: number, ft: number)
ft -= 1
local ftb = ilog(ft)
@@ -202,7 +193,6 @@ function RangeEncoder.tellFrac(e: Enc): number
return nbits - (l * 8 + b)
end
-- done(): flush; the frame is e.buf (storage bytes)
function RangeEncoder.done(e: Enc)
local l = 32 - ilog(e.rng)
local msk = floor((CODE_TOP - 1) / 2 ^ l)
@@ -1,10 +1,6 @@
--!strict
-- codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt):
-- symbols range-coded from the front of a frame, raw bits from its back. Opus (CELT and SILK) uses it; LZMA, VP8 and
-- CABAC have their own (different) binary coders. Moved here from audio/opus by the cleanup pass (same code).
--
-- local RD = require("@rosetta/codecs/entropy/RangeCoder/Decoder") -- RD.new(buf, base, size), RD.icdf / bits / uint ...
-- local RE = require("@rosetta/codecs/entropy/RangeCoder/Encoder") -- RE.new(size), RE.icdf / bits / uint, RE.done
-- codecs/entropy/RangeCoder: the RFC 6716 range coder used by Opus, a port of libopus celt/entdec.c + entenc.c.
-- BSD: licenses/libopus-BSD.txt.
local RangeCoder = {
Decoder = require("@rosetta/codecs/entropy/RangeCoder/Decoder"),
Encoder = require("@rosetta/codecs/entropy/RangeCoder/Encoder"),
+5 -26
View File
@@ -1,18 +1,6 @@
--!strict
-- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike
-- (one pixel size, glyphs as u8 bitmaps, 0 = off / 255 = on) wrapped as a Types.Font whose units are pixels
-- (unitsPerEm = the pixel size), glyphIndex / advance / kern work, outline is nil, and rasterize(g) returns the glyph's
-- bitmap as an alpha8 Image (img.meta.left / top / advance, as codecs/font/TrueType does; the px argument is ignored,
-- img.meta.scale = px / size tells the caller how much to scale). Also: the strike of any Font (its own bitmap, or an
-- outline font rasterized at a pixel size and thresholded), which the bitmap font encoders write, and the bit-row
-- packing every bitmap font format shares. New code.
--
-- local font = Bitmap.font(strike, { family = "Fixed" }, { source = { format = "bdf" } })
-- local strike, err = Bitmap.strike(anyFont, { px = 16, chars = "abc" }) -- font.bitmap, or rasterized
-- local pixels = Bitmap.unpack(buf, off, w, h, stride) -- MSB-first 1-bit rows -> u8 0 / 255
-- local bytes = Bitmap.pack(pixels, w, h, stride) -- u8 -> MSB-first rows (buffer)
--
-- Never throws: rasterize of a bad glyph index returns nil; unpack reads only inside the buffer (missing bits are 0).
-- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT) and their 1-bit rows.
-- Bit rows are MSB = left pixel unless lsbFirst; a pixel >= 128 is on.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
@@ -20,9 +8,6 @@ local Bitmap = {}
local readu8, writeu8 = buffer.readu8, buffer.writeu8
-- ------------------------------------------------------------------------------------------------ bits
-- unpack(buf, off, w, h, stride, lsbFirst?) -> u8 pixels (w * h, 0 / 255) from 1-bit rows of stride bytes (MSB = left
-- pixel unless lsbFirst); bytes past the end of buf read as 0
function Bitmap.unpack(b: buffer, off: number, w: number, h: number, stride: number, lsbFirst: boolean?): buffer
local out = buffer.create(math.max(0, w * h))
local n = buffer.len(b)
@@ -42,7 +27,6 @@ function Bitmap.unpack(b: buffer, off: number, w: number, h: number, stride: num
return out
end
-- pack(pixels, w, h, stride?, lsbFirst?) -> 1-bit rows (stride bytes each, default ceil(w / 8)); a pixel >= 128 is on
function Bitmap.pack(px: buffer, w: number, h: number, stride: number?, lsbFirst: boolean?): buffer
local s = stride or math.ceil(w / 8)
local out = buffer.create(math.max(0, s * h))
@@ -60,7 +44,6 @@ function Bitmap.pack(px: buffer, w: number, h: number, stride: number?, lsbFirst
return out
end
-- ------------------------------------------------------------------------------------------------ font
local Face = {}
Face.__index = Face
@@ -81,7 +64,6 @@ function Face.outline(_self: any, _g: number): { any }?
return nil
end
-- rasterize(g, px?) -> the glyph as an alpha8 Image (px is ignored: meta.scale = px / size)
function Face.rasterize(self: any, g: number, px: number?): Types.Image?
local gl: Types.BitmapGlyph? = self.bitmap.glyphs[g + 1]
if not gl or gl.width < 0 or gl.height < 0 then
@@ -100,7 +82,6 @@ function Face.rasterize(self: any, g: number, px: number?): Types.Image?
return img
end
-- font(strike, info?, meta?) -> a Types.Font over the strike (font.bitmap = strike)
function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta: { [string]: any }?): any
local index: { [number]: number } = {}
for i, gl in strike.glyphs do
@@ -136,11 +117,10 @@ function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta:
return f
end
-- ------------------------------------------------------------------------------------------------ strike
export type StrikeOptions = {
px: number?, -- pixel size for outline fonts (default 16)
chars: (string | { number })?, -- code points for outline fonts (default 32..126)
threshold: number?, -- coverage 0..255 at or above which a pixel is on (default 128)
px: number?,
chars: (string | { number })?,
threshold: number?,
}
local function codepoints(chars: (string | { number })?): { number }
@@ -160,7 +140,6 @@ local function codepoints(chars: (string | { number })?): { number }
return out
end
-- strike(font, opts?) -> the font's BitmapStrike: font.bitmap, else the outline font rasterized at opts.px
function Bitmap.strike(font: any, opts: StrikeOptions?): (Types.BitmapStrike?, Err.Err?)
if type(font) ~= "table" or font.kind ~= "font" then
return nil, Err.new(Err.ARG, "expected a Font")
+10 -28
View File
@@ -1,17 +1,7 @@
--!strict
-- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
-- with a "CFF " table (.otf). Parses the header, the INDEXes, the Top / Private DICTs (name-keyed and CID-keyed
-- fonts with FDArray / FDSelect formats 0 and 3), local and global subroutines, and runs charstrings to path commands
-- (moveTo / lineTo / cubicTo / close, font units, y up). The charstring interpreter is ported from stb_truetype 1.26
-- (public domain / MIT; Dougall Johnson's Type 2 support) through imgui-luau's imstb_truetype.lua, bounds-checked,
-- with fixes: flex1's last delta, an operation budget against subroutine bombs, and the arithmetic / storage
-- operators (TN #5177 4.4: and or not abs add sub div neg eq drop put get ifelse random mul sqrt dup exch index roll).
-- Not supported: CFF2 (variable fonts), seac accented glyphs in endchar (deprecated in OpenType), hinting.
--
-- local cff, err = Cff.parse(buf, offset, length)
-- local cmds, err = Cff.outline(cff, glyphIndex)
--
-- Never throws: malformed data returns nil, message.
-- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177), the outlines of .otf fonts.
-- Charstrings ported from stb_truetype 1.26 (public domain / MIT) via imgui-luau's imstb_truetype.lua, plus
-- flex1's last delta, an operation budget, and the TN #5177 4.4 arithmetic / storage operators.
local Cff = {}
local readu8 = buffer.readu8
@@ -38,15 +28,14 @@ export type Font = {
limit: number,
charStrings: Index,
gsubrs: Index,
subrs: Index?, -- name-keyed fonts
fdSubrs: { Index? }?, -- CID-keyed fonts: per font dict
fdSelect: number?, -- absolute offset of FDSelect
subrs: Index?,
fdSubrs: { Index? }?,
fdSelect: number?,
numGlyphs: number,
cid: boolean,
fontMatrix: { number }?,
}
-- INDEX at absolute offset p (within [base, limit)) -> Index | nil
local function index(b: buffer, p: number, limit: number): Index?
if p + 2 > limit then
return nil
@@ -71,7 +60,6 @@ local function index(b: buffer, p: number, limit: number): Index?
return { count = count, offSize = offSize, offsets = offsets, data = data, next = data + last }
end
-- item(idx, i) -> absolute start, length (nil when out of range / corrupt)
local function item(b: buffer, idx: Index, i: number): (number?, number)
if i < 0 or i >= idx.count then
return nil, 0
@@ -85,7 +73,7 @@ local function item(b: buffer, idx: Index, i: number): (number?, number)
end
Cff.item = item
-- DICT at [p, p + n) -> { [op] = { operands } } (two-byte ops are 1200 + second byte)
-- DICT operators: two-byte ops (12 x) are keyed 1200 + x
local function dict(b: buffer, p: number, n: number): { [number]: { number } }
local out: { [number]: { number } } = {}
local ops: { number } = {}
@@ -171,7 +159,6 @@ local function privateSubrs(b: buffer, base: number, limit: number, d: { [number
return index(b, ps + s[1], limit)
end
-- parse(buf, offset, length) -> Font | nil, message
function Cff.parse(b: buffer, offset: number, length: number): (Font?, string?)
local base, limit = offset, math.min(offset + length, blen(b))
if limit - base < 4 then
@@ -256,7 +243,6 @@ local function bias(count: number): number
return if count < 1240 then 107 elseif count < 33900 then 1131 else 32768
end
-- the local subrs of glyph g (CID fonts: through FDSelect)
local function localSubrs(f: Font, g: number): Index?
if not f.cid then
return f.subrs
@@ -286,7 +272,6 @@ end
local BUDGET = 200000 -- operators per glyph (subroutine bombs)
-- outline(f, g) -> path commands | nil, message
function Cff.outline(f: Font, g: number): ({ any }?, string?)
local b = f.buf
local p, len = item(b, f.charStrings, g)
@@ -295,14 +280,14 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?)
end
local e = p + len
local cmds: { any } = {}
local s: { number } = table.create(48, 0) -- operand stack, 1-based; sp = count
local s: { number } = table.create(48, 0)
local sp = 0
local trans = table.create(32, 0) :: { number }
local x, y = 0, 0
local open = false
local maskbits = 0
local inHeader = true
local stack: { { number } } = {} -- return addresses { p, e }
local stack: { { number } } = {}
local subrs: Index? = nil
local haveSubrs = false
local ops = 0
@@ -334,13 +319,12 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?)
x, y = x2 + dx3, y2 + dy3
table.insert(cmds, { op = "cubicTo", x1, y1, x2, y2, x, y })
end
local function S(i: number): number -- operand i (0-based), 0 past the stack
local function S(i: number): number
return s[i + 1] or 0
end
while true do
if p >= e then
-- the end of a subroutine without return, or of the charstring without endchar
if #stack > 0 then
local r = table.remove(stack) :: { number }
p, e = r[1], r[2]
@@ -535,12 +519,10 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?)
curveTo(S(0), S(1), S(2), S(3), S(4), S(5))
curveTo(S(6), S(7), S(8), S(9), dx6, dy6)
else
-- arithmetic and storage operators: they leave results on the stack
clear = false
local top = sp
local a, c = S(top - 2), S(top - 1)
local function set(n: number, v: number)
-- pop n operands, push v
sp = math.max(0, sp - n)
sp += 1
s[sp] = v
+3 -9
View File
@@ -1,12 +1,7 @@
--!strict
-- codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a
-- cmap, PCF / BDF glyph names): the Adobe Glyph List For New Fonts (AGLFN 1.7, Adobe, BSD-3-Clause:
-- licenses/agl-LICENSE.txt; the f-ligatures and dotlessj added), the uniXXXX / uXXXX[XX] conventions and
-- name.suffix variants ("a.sc" -> a) per the AGL specification; and Adobe StandardEncoding (code -> glyph name).
-- Generated once from fontTools.agl / fontTools.encodings.StandardEncoding.
--
-- GlyphNames.unicode("Aacute") -> 0xC1 GlyphNames.unicode("uni20AC") -> 0x20AC (nil when unknown)
-- GlyphNames.STANDARD[65] -> "A" (StandardEncoding, codes 0..255; nil for .notdef)
-- codecs/font/GlyphNames: PostScript glyph names -> Unicode (AGL specification) and Adobe StandardEncoding.
-- Data: the Adobe Glyph List For New Fonts (AGLFN 1.7, BSD-3-Clause: licenses/agl-LICENSE.txt; the f-ligatures and
-- dotlessj added) and StandardEncoding, generated from fontTools.agl / fontTools.encodings.StandardEncoding.
local GlyphNames = {}
-- AGLFN: "name hex" pairs
@@ -126,7 +121,6 @@ do
end
GlyphNames.STANDARD = STANDARD
-- unicode(name) -> the code point of a glyph name (the first one for ligature names like "f_i"), or nil
function GlyphNames.unicode(name: string): number?
local base = string.match(name, "^([^%.]+)") or name
local t = byName or load()
+6 -19
View File
@@ -1,12 +1,7 @@
--!strict
-- codecs/font/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and
-- off-curve points, with the implied on-curve midpoints) and composite glyphs (offsets or point matching, scale /
-- x-y scale / 2x2 transforms, SCALED_COMPONENT_OFFSET, nesting up to 8 levels). Ported from stb_truetype 1.26
-- (public domain / MIT, Sean Barrett) through imgui-luau's imstb_truetype.lua, made bounds-checked, with point
-- matching and the FreeType component transform (stb scales the offsets of transformed components; FreeType and the
-- spec do not). No hinting.
--
-- Never throws: every read is range-checked (out of range reads as 0) and malformed glyphs return nil, message.
-- codecs/font/TrueType/Glyf: TrueType glyph outlines from the glyf / loca tables, simple and composite.
-- Ported from stb_truetype 1.26 (public domain / MIT, Sean Barrett) via imgui-luau's imstb_truetype.lua; component
-- offsets follow FreeType and the spec (stb also scales the offsets of transformed components).
local Glyf = {}
local readu8, readi8 = buffer.readu8, buffer.readi8
@@ -35,7 +30,7 @@ end
export type Face = {
buf: buffer,
glyf: number, -- absolute offset of the glyf table
glyf: number,
glyfLen: number,
loca: number,
locaLen: number,
@@ -44,7 +39,6 @@ export type Face = {
[string]: any,
}
-- (start, length) of glyph g in the glyf table, or nil for an empty glyph / bad index
function Glyf.range(f: Face, g: number): (number?, number)
if g < 0 or g >= f.numGlyphs or g % 1 ~= 0 then
return nil, 0
@@ -67,7 +61,6 @@ function Glyf.range(f: Face, g: number): (number?, number)
return f.glyf + a, z - a
end
-- bounds(f, g) -> xMin, yMin, xMax, yMax from the glyph header (nil for empty glyphs)
function Glyf.bounds(f: Face, g: number): (number?, number, number, number)
local o, n = Glyf.range(f, g)
if not o or n < 10 then
@@ -77,7 +70,6 @@ function Glyf.bounds(f: Face, g: number): (number?, number, number, number)
return i16(b, o + 2), i16(b, o + 4), i16(b, o + 6), i16(b, o + 8)
end
-- contours: { { xs, ys, on } } point lists in font units
type Contour = { x: { number }, y: { number }, on: { boolean } }
local MAX_POINTS = 65536
@@ -108,7 +100,6 @@ local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour
if p > e then
return nil, "instructions past the end"
end
-- flags
local flags = table.create(n, 0)
local i = 1
while i <= n do
@@ -134,7 +125,6 @@ local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour
end
end
end
-- coordinates
local xs = table.create(n, 0)
local x = 0
for k = 1, n do
@@ -247,7 +237,6 @@ local function composite(f: Face, o: number, len: number, depth: number): ({ Con
if not child then
return nil, err
end
-- transform the child's points
local tc = table.create(#child) :: { Contour }
for i, c in child do
local nx, ny = table.create(#c.x) :: { number }, table.create(#c.x) :: { number }
@@ -308,7 +297,7 @@ contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?)
end
local o, len = Glyf.range(f, g)
if not o then
return {}, nil -- empty glyph (space)
return {}, nil
end
if len < 10 then
return nil, "glyph header past the end"
@@ -320,7 +309,6 @@ contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?)
return composite(f, o, len, depth)
end
-- outline(f, g) -> path commands (codecs/image/Raster format, font units, y up) | nil, message
function Glyf.outline(f: Face, g: number): ({ any }?, string?)
local cs, err = contours(f, g, 0)
if not cs then
@@ -365,7 +353,7 @@ function Glyf.outline(f: Face, g: number): ({ any }?, string?)
local k = (s + i - 1) % n + 1
local x, y, isOn = xs[k], ys[k], on[k]
if i == n then
x, y, isOn = sx, sy, true -- back to the start
x, y, isOn = sx, sy, true
end
if isOn then
if off then
@@ -387,7 +375,6 @@ function Glyf.outline(f: Face, g: number): ({ any }?, string?)
return cmds, nil
end
-- points(f, g) -> the number of points and contours (for tests)
function Glyf.counts(f: Face, g: number): (number, number)
local cs = contours(f, g, 0)
if not cs then
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff. Show more