ws-cleanup: consistency (lower-case tags, WAVE channel order, loops = play count, Err messages, caps)

- Audio tags keys are lower case everywhere (Types.Tags): FLAC no longer returns TITLE / ARTIST (the raw fields stay
  in meta.source.comments; also for Vorbis and Opus); Vorbis / Opus / FLAC read and write tags through
  codecs/VorbisComment (TRACKNUMBER -> track, DISCNUMBER -> disc, DESCRIPTION -> comment); MP3 albumArtist ->
  albumartist and year -> date (ID3 TYER / TDRC, ID3v1); RIFF INFO / CAF / MP4 freeform names are lower-cased (MP4
  writes iTunSMPB / iTunNORM back in their usual spelling; m4a reads tags.itunsmpb).
- Channel order: Vorbis (and Opus mapping family 1) decode to WAVE order like FLAC / WAV / AAC (both used to return
  the Vorbis order); the Vorbis encoder takes WAVE order and writes Vorbis order. Pcm.WAVE_FROM_VORBIS / Pcm.reorder;
  Vorbis.packetDecoder gives pd.order. Tests reorder oggdec's / opusdec's raw (Vorbis-order) references.
- img.loops is the play count in GIF, APNG and WebP (they already agreed; Types / WebP docs said "loop count");
  tests/api round-trips loops 0 / 1 / 3 through all three.
- Err: messages without the format name (png / midi encoders said "png encode: ..."); codecs/Bzip2 and codecs/Zstd
  check arguments through Bytes.span.
- caps: mp3 encodeLayers = { 2, 3 }, opus encodeChannels = 2.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 11:01:22 -05:00
1 parent 8158acf3d5
commit fb2dd98db2
27 files changed
+164 -170

No files matched your search

+5 -3
View File
@@ -22,8 +22,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| audio | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` | | audio | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` |
| audio | flac | .flac .oga | yes | yes | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | | audio | flac | .flac .oga | yes | yes | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` |
| audio | m4a | .m4a .m4b .m4r | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` | | audio | m4a | .m4a .m4b .m4r | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` |
| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, encodeLayers: 2, 3, channels: 2 | `tests/audio/mp3.luau` |
| audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt" | `tests/audio/opus.luau` | | audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt", encodeChannels: 2 | `tests/audio/opus.luau` |
| audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | | audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` |
| audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` |
| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
@@ -86,7 +86,6 @@ Codecs (layer 1, shared by formats; not loadable on their own):
- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program - codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). - codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
- codecs/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs
- codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable - codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
- codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written - codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec - codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
@@ -102,13 +101,16 @@ Codecs (layer 1, shared by formats; not loadable on their own):
- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from - codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from
- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. - codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
- codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette - codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
- codecs/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt):
- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine - codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
- codecs/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or
- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by - codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
- codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is - codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is
- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read - codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
- codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed - codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
- codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, - codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL,
- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. - codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau.
- codecs/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags.
- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the - codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
- codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): - codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... - codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ...
+11 -11
View File
@@ -200,7 +200,7 @@ local list: { Entry } = {
path = "audio/flac", path = "audio/flac",
extensions = { "flac", "oga" }, extensions = { "flac", "oga" },
mime = { "audio/flac", "audio/x-flac" }, mime = { "audio/flac", "audio/x-flac" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
load = function() load = function()
return require("@formats/audio/flac") return require("@formats/audio/flac")
@@ -224,8 +224,8 @@ local list: { Entry } = {
path = "audio/mp3", path = "audio/mp3",
extensions = { "mp3", "mp2", "mp1", "mpga" }, extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm", "codecs/Resample" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 },
load = function() load = function()
return require("@formats/audio/mp3") return require("@formats/audio/mp3")
end, end,
@@ -236,8 +236,8 @@ local list: { Entry } = {
path = "audio/opus", path = "audio/opus",
extensions = { "opus" }, extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" }, mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/RangeCoder/Decoder", "codecs/RangeCoder/Encoder", "codecs/Pcm", "codecs/Resample", "codecs/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 },
load = function() load = function()
return require("@formats/audio/opus") return require("@formats/audio/opus")
end, end,
@@ -260,7 +260,7 @@ local list: { Entry } = {
path = "audio/vorbis", path = "audio/vorbis",
extensions = { "ogg", "oga" }, extensions = { "ogg", "oga" },
mime = { "audio/ogg", "audio/vorbis" }, mime = { "audio/ogg", "audio/vorbis" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm", "codecs/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 },
load = function() load = function()
return require("@formats/audio/vorbis") return require("@formats/audio/vorbis")
@@ -368,7 +368,7 @@ local list: { Entry } = {
path = "model/dae", path = "model/dae",
extensions = { "dae", "zae" }, extensions = { "dae", "zae" },
mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" }, mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Base64", "containers/Zip" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Base64", "containers/Zip" },
caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true }, caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true },
load = function() load = function()
return require("@formats/model/dae") return require("@formats/model/dae")
@@ -392,7 +392,7 @@ local list: { Entry } = {
path = "model/gltf", path = "model/gltf",
extensions = { "gltf", "glb" }, extensions = { "gltf", "glb" },
mime = { "model/gltf+json", "model/gltf-binary" }, mime = { "model/gltf+json", "model/gltf-binary" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Base64" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64" },
caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true },
load = function() load = function()
return require("@formats/model/gltf") return require("@formats/model/gltf")
@@ -692,7 +692,7 @@ local list: { Entry } = {
path = "data/plist", path = "data/plist",
extensions = { "plist" }, extensions = { "plist" },
mime = { "application/x-plist", "application/x-bplist" }, mime = { "application/x-plist", "application/x-bplist" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Json" }, deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/Xml", "codecs/Json" },
caps = { decode = true, encode = true, binary = "read", ordered = true }, caps = { decode = true, encode = true, binary = "read", ordered = true },
load = function() load = function()
return require("@formats/data/plist") return require("@formats/data/plist")
@@ -704,7 +704,7 @@ local list: { Entry } = {
path = "data/toml", path = "data/toml",
extensions = { "toml" }, extensions = { "toml" },
mime = { "application/toml" }, mime = { "application/toml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Text" },
caps = { decode = true, encode = true, ordered = true, dates = true }, caps = { decode = true, encode = true, ordered = true, dates = true },
load = function() load = function()
return require("@formats/data/toml") return require("@formats/data/toml")
@@ -728,7 +728,7 @@ local list: { Entry } = {
path = "data/yaml", path = "data/yaml",
extensions = { "yaml", "yml" }, extensions = { "yaml", "yml" },
mime = { "application/yaml", "application/x-yaml", "text/yaml" }, mime = { "application/yaml", "application/x-yaml", "text/yaml" },
deps = { "core/Err", "core/Bytes", "Types" }, deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/Text" },
caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true }, caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true },
load = function() load = function()
return require("@formats/data/yaml") return require("@formats/data/yaml")
+2 -1
View File
@@ -59,7 +59,8 @@ export type Image = {
format: PixelFormat, format: PixelFormat,
pixels: buffer, pixels: buffer,
frames: { Frame }?, -- animations: frame 1 is also width x height pixels (the composited first frame) frames: { Frame }?, -- animations: frame 1 is also width x height pixels (the composited first frame)
loops: number, -- 0 = forever loops: number, -- play count: how many times the animation plays, 0 = forever (GIF stores repeats: plays - 1; APNG
-- num_plays and the WebP ANIM loop count are play counts)
meta: ImageMeta, meta: ImageMeta,
} }
+1 -1
View File
@@ -222,7 +222,7 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?)
if c.err then if c.err then
break break
end end
p.tags[INFO_TAGS[string.lower(k)] or k] = v p.tags[INFO_TAGS[string.lower(k)] or string.lower(k)] = v
end end
end end
r.pos = stop r.pos = stop
+6 -40
View File
@@ -11,6 +11,8 @@
-- SEEKTABLE. Streams: input blocks are pulled from a codecs/Pcm Source, so a Decoder is encoded without decoding it -- SEEKTABLE. Streams: input blocks are pulled from a codecs/Pcm Source, so a Decoder is encoded without decoding it
-- whole. Never throws: bad options are rejected by audio/flac before calling in. -- whole. Never throws: bad options are rejected by audio/flac before calling in.
local Md5 = require("@formats/core/Md5") local Md5 = require("@formats/core/Md5")
local VorbisComment = require("@formats/codecs/VorbisComment")
local Frame = require("@formats/audio/flac/Frame")
local Encode = {} local Encode = {}
@@ -23,33 +25,12 @@ for i = 0, 63 do
end end
-- ------------------------------------------------------------------------------------------------ CRCs -- ------------------------------------------------------------------------------------------------ CRCs
local CRC8 = table.create(256, 0) -- (the decoder's tables: audio/flac/Frame; (b, offset, count) here)
local CRC16 = table.create(256, 0)
for i = 0, 255 do
local c = i
for _ = 1, 8 do
c = if c >= 128 then bit32.bxor((c * 2) % 256, 0x07) else c * 2
end
CRC8[i + 1] = c
local d = i * 256
for _ = 1, 8 do
d = if d >= 32768 then bit32.bxor((d * 2) % 65536, 0x8005) else d * 2
end
CRC16[i + 1] = d
end
local function crc8(b: buffer, o: number, n: number): number local function crc8(b: buffer, o: number, n: number): number
local c = 0 return Frame.crc8(b, o, o + n)
for i = o, o + n - 1 do
c = CRC8[bit32.bxor(c, buffer.readu8(b, i)) + 1]
end
return c
end end
local function crc16(b: buffer, o: number, n: number): number local function crc16(b: buffer, o: number, n: number): number
local c = 0 return Frame.crc16(b, o, o + n)
for i = o, o + n - 1 do
c = bit32.bxor((c * 256) % 65536, CRC16[bit32.bxor(c // 256, buffer.readu8(b, i)) + 1])
end
return c
end end
Encode.crc8, Encode.crc16 = crc8, crc16 Encode.crc8, Encode.crc16 = crc8, crc16
@@ -702,8 +683,6 @@ export type Options = {
vendor: string, vendor: string,
} }
local TAG_NAMES = { track = "TRACKNUMBER" }
-- encode(src, opts) -> buffer | nil, message -- encode(src, opts) -> buffer | nil, message
function Encode.encode(src: Source, opts: Options): (buffer?, string?) function Encode.encode(src: Source, opts: Options): (buffer?, string?)
local cfg = PRESETS[opts.level + 1] local cfg = PRESETS[opts.level + 1]
@@ -730,20 +709,7 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
end end
end end
-- vorbis comment -- vorbis comment
local comments = {} local comments = VorbisComment.fields(src.tags)
local keys = {}
for k in src.tags do
if type(k) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
for _, k in keys do
local v = src.tags[k]
if type(v) == "string" then
table.insert(comments, (TAG_NAMES[k] or string.upper(k)) .. "=" .. v)
end
end
local vendor = opts.vendor local vendor = opts.vendor
local vcLen = 4 + #vendor + 4 local vcLen = 4 + #vendor + 4
for _, c in comments do for _, c in comments do
+5 -2
View File
@@ -4,6 +4,8 @@
-- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is -- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is
-- left in place); every other block is skipped. Nothing throws: bad data gives nil, err. -- left in place); every other block is skipped. Nothing throws: bad data gives nil, err.
-- Absorbed from flac-luau 7083d0d (same author, no third-party code). -- Absorbed from flac-luau 7083d0d (same author, no third-party code).
local VorbisComment = require("@formats/codecs/VorbisComment")
local readu8, readu32 = buffer.readu8, buffer.readu32 local readu8, readu32 = buffer.readu8, buffer.readu32
local Meta = {} local Meta = {}
@@ -102,8 +104,9 @@ local function vorbisComment(b: buffer, p: number, e: number, info: Info): boole
p += l p += l
local eq = string.find(s, "=", 1, true) local eq = string.find(s, "=", 1, true)
if eq then if eq then
local key, value = string.upper(string.sub(s, 1, eq - 1)), string.sub(s, eq + 1) local name, value = string.sub(s, 1, eq - 1), string.sub(s, eq + 1)
table.insert(info.comments, { key = key, value = value }) table.insert(info.comments, { key = string.upper(name), value = value })
local key = VorbisComment.tagKey(name)
local old = info.tags[key] local old = info.tags[key]
info.tags[key] = if old then old .. "; " .. value else value info.tags[key] = if old then old .. "; " .. value else value
end end
+2 -2
View File
@@ -29,7 +29,7 @@ local Flac = {
category = "audio", category = "audio",
extensions = { "flac", "oga" }, extensions = { "flac", "oga" },
mime = { "audio/flac", "audio/x-flac" }, mime = { "audio/flac", "audio/x-flac" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
} }
@@ -115,7 +115,7 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er
o += n o += n
end end
a.tags = d.tags a.tags = d.tags
a.meta.source = { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures } a.meta.source = { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures, comments = d.comments }
return a, nil return a, nil
end end
+1 -1
View File
@@ -167,7 +167,7 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
end end
local tags, pictures = IsoBmff.tags(r, movie) local tags, pictures = IsoBmff.tags(r, movie)
-- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 <priming> <padding> <samples> ..." (hex) -- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 <priming> <padding> <samples> ..." (hex)
local smpb = tags.iTunSMPB local smpb = tags.itunsmpb
if gapless and not t.edits and smpb then if gapless and not t.edits and smpb then
local f = {} local f = {}
for w in string.gmatch(smpb, "%x+") do for w in string.gmatch(smpb, "%x+") do
+4 -4
View File
@@ -35,8 +35,8 @@ local FIELDS = {
TIT2 = "title", TT2 = "title", TIT2 = "title", TT2 = "title",
TPE1 = "artist", TP1 = "artist", TPE1 = "artist", TP1 = "artist",
TALB = "album", TAL = "album", TALB = "album", TAL = "album",
TPE2 = "albumArtist", TP2 = "albumArtist", TPE2 = "albumartist", TP2 = "albumartist",
TYER = "year", TYE = "year", TDRC = "year", TYER = "date", TYE = "date", TDRC = "date",
TRCK = "track", TRK = "track", TRCK = "track", TRK = "track",
TPOS = "disc", TPA = "disc", TPOS = "disc", TPA = "disc",
TCON = "genre", TCO = "genre", TCON = "genre", TCO = "genre",
@@ -257,7 +257,7 @@ local function v1String(b: buffer, o: number, n: number): string
end end
-- Parses tags and returns (tags, audio start, audio end) for the buffer b. -- Parses tags and returns (tags, audio start, audio end) for the buffer b.
-- tags = { title?, artist?, album?, albumArtist?, year?, track?, disc?, genre?, composer?, comment?, -- tags = { title?, artist?, album?, albumartist?, date?, track?, disc?, genre?, composer?, comment?,
-- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? } -- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? }
function Tags.parse(b: buffer): (any, number, number) function Tags.parse(b: buffer): (any, number, number)
local len = buffer.len(b) local len = buffer.len(b)
@@ -277,7 +277,7 @@ function Tags.parse(b: buffer): (any, number, number)
title = v1String(b, o + 3, 30), title = v1String(b, o + 3, 30),
artist = v1String(b, o + 33, 30), artist = v1String(b, o + 33, 30),
album = v1String(b, o + 63, 30), album = v1String(b, o + 63, 30),
year = v1String(b, o + 93, 4), date = v1String(b, o + 93, 4),
} }
if ru8(b, o + 125) == 0 and ru8(b, o + 126) ~= 0 then if ru8(b, o + 125) == 0 and ru8(b, o + 126) ~= 0 then
v1.comment = v1String(b, o + 97, 28) v1.comment = v1String(b, o + 97, 28)
+1 -1
View File
@@ -33,7 +33,7 @@ local Mp3 = {
extensions = { "mp3", "mp2", "mp1", "mpga" }, extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm", "codecs/Resample" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm", "codecs/Resample" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 },
} }
-- ------------------------------------------------------------------------------------------------ types -- ------------------------------------------------------------------------------------------------ types
+1 -1
View File
@@ -38,7 +38,7 @@ local Opus = {
extensions = { "opus" }, extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" }, mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/RangeCoder/Decoder", "codecs/RangeCoder/Encoder", "codecs/Pcm", "codecs/Resample", "codecs/VorbisComment" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/RangeCoder/Decoder", "codecs/RangeCoder/Encoder", "codecs/Pcm", "codecs/Resample", "codecs/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 },
} }
-- ------------------------------------------------------------------------------------------------ types -- ------------------------------------------------------------------------------------------------ types
+14 -12
View File
@@ -11,6 +11,8 @@
-- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact -- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact
-- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws. -- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws.
local Mdct = require("@formats/codecs/Mdct") local Mdct = require("@formats/codecs/Mdct")
local Pcm = require("@formats/codecs/Pcm")
local VorbisComment = require("@formats/codecs/VorbisComment")
local Ogg = require("@formats/containers/Ogg") local Ogg = require("@formats/containers/Ogg")
local Tables = require("@formats/audio/vorbis/Tables") local Tables = require("@formats/audio/vorbis/Tables")
@@ -448,17 +450,9 @@ local function commentHeader(vendor: string, tags: { [string]: string }): buffer
putString(w, "vorbis") putString(w, "vorbis")
put(w, #vendor, 32) put(w, #vendor, 32)
putString(w, vendor) putString(w, vendor)
local keys = {} local fields = VorbisComment.fields(tags)
for k, v in tags do put(w, #fields, 32)
if type(k) == "string" and type(v) == "string" then for _, s in fields do
table.insert(keys, k)
end
end
table.sort(keys)
put(w, #keys, 32)
for _, k in keys do
local name = if k == "track" then "TRACKNUMBER" else string.upper(k)
local s = name .. "=" .. tags[k]
put(w, #s, 32) put(w, #s, 32)
putString(w, s) putString(w, s)
end end
@@ -614,6 +608,14 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
for c = 1, ch do for c = 1, ch do
frame[c] = table.create(N, 0) frame[c] = table.create(N, 0)
end end
-- the input is in WAVE channel order; input channel c goes to Vorbis channel order[c]
local order = Pcm.WAVE_FROM_VORBIS[ch] or {}
if #order ~= ch then
order = table.create(ch, 0)
for c = 1, ch do
order[c] = c
end
end
local blk = table.create(N, 0) local blk = table.create(N, 0)
local X = table.create(ch) local X = table.create(ch)
local R = table.create(ch) local R = table.create(ch)
@@ -658,7 +660,7 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
for i = 0, take - 1 do for i = 0, take - 1 do
local base = (pendOff + i) * ch * 4 local base = (pendOff + i) * ch * 4
for c = 1, ch do for c = 1, ch do
frame[c][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4) frame[order[c]][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4)
end end
end end
got += take got += take
+28 -24
View File
@@ -19,6 +19,7 @@ local Setup = require("@formats/audio/vorbis/Setup")
local Packet = require("@formats/audio/vorbis/Packet") local Packet = require("@formats/audio/vorbis/Packet")
local Encode = require("@formats/audio/vorbis/Encode") local Encode = require("@formats/audio/vorbis/Encode")
local Pcm = require("@formats/codecs/Pcm") local Pcm = require("@formats/codecs/Pcm")
local VorbisComment = require("@formats/codecs/VorbisComment")
-- ------------------------------------------------------------------------------------------------ contract -- ------------------------------------------------------------------------------------------------ contract
local Vorbis = { local Vorbis = {
@@ -26,7 +27,7 @@ local Vorbis = {
category = "audio", category = "audio",
extensions = { "ogg", "oga" }, extensions = { "ogg", "oga" },
mime = { "audio/ogg", "audio/vorbis" }, mime = { "audio/ogg", "audio/vorbis" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm", "codecs/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 },
} }
@@ -40,38 +41,36 @@ export type EncodeOptions = {
} }
-- ------------------------------------------------------------------------------------------------ constants -- ------------------------------------------------------------------------------------------------ constants
local TAG_KEYS = { tracknumber = "track", description = "comment" } -- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/Pcm; identity past 8 channels)
local function waveOrder(ch: number): { number }
local function tagsOf(comments: { string }): Types.Tags local m = Pcm.WAVE_FROM_VORBIS[ch]
local tags: Types.Tags = {} if m then
for _, s in comments do return m
local eq = string.find(s, "=", 1, true)
if eq then
local k = string.lower(string.sub(s, 1, eq - 1))
local v = string.sub(s, eq + 1)
k = TAG_KEYS[k] or k
tags[k] = if tags[k] then tags[k] .. "; " .. v else v
end
end end
return tags local id = table.create(ch, 0)
for c = 1, ch do
id[c] = c
end
return id
end end
-- the three headers -> ident, setup, vendor, tags | nil, Err -- the three headers -> ident, setup, vendor, tags, raw comment fields | nil, Err
local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, Err.Err?) local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, { VorbisComment.Field }?, Err.Err?)
local id, ierr = Setup.ident(h1.data, h1.offset, h1.size) local id, ierr = Setup.ident(h1.data, h1.offset, h1.size)
if not id then if not id then
return nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header") return nil, nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header")
end end
local vendor, comments = Setup.comment(h2.data, h2.offset, h2.size) local vendor, comments = Setup.comment(h2.data, h2.offset, h2.size)
if not vendor then if not vendor then
return nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header") return nil, nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header")
end end
local setup, serr = Setup.setup(h3.data, h3.offset, h3.size, id) local setup, serr = Setup.setup(h3.data, h3.offset, h3.size, id)
if not setup then if not setup then
local code = if serr == "floor 0" then Err.UNSUPPORTED else Err.CORRUPT local code = if serr == "floor 0" then Err.UNSUPPORTED else Err.CORRUPT
return nil, nil, nil, nil, Err.new(code, serr or "bad setup header") return nil, nil, nil, nil, nil, Err.new(code, serr or "bad setup header")
end end
return id, setup, vendor, tagsOf(comments or {}), nil local tags, raw = VorbisComment.tags(comments or {})
return id, setup, vendor, tags, raw, nil
end end
-- ------------------------------------------------------------------------------------------------ sniff -- ------------------------------------------------------------------------------------------------ sniff
@@ -244,8 +243,9 @@ function Stream.read(self: any, n: number, out: buffer?): (buffer, number)
end end
local arrays, first, last = q[1], q[2], q[3] local arrays, first, last = q[1], q[2], q[3]
local take = math.min(n - got, last - first + 1) local take = math.min(n - got, last - first + 1)
local order = self.order
for c = 1, ch do for c = 1, ch do
local a = arrays[c] local a = arrays[order[c]]
local o = got * ch * 4 + (c - 1) * 4 local o = got * ch * 4 + (c - 1) * 4
for i = first, first + take - 1 do for i = first, first + take - 1 do
writef32(b, o, a[i]) writef32(b, o, a[i])
@@ -373,7 +373,7 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
if h3 == nil then if h3 == nil then
return nil, Err.new(Err.TRUNCATED, "missing setup header") return nil, Err.new(Err.TRUNCATED, "missing setup header")
end end
local id, setup, vendor, tags, herr = headers(h1, h2copy, h3) local id, setup, vendor, tags, raw, herr = headers(h1, h2copy, h3)
if not id then if not id then
return nil, herr return nil, herr
end end
@@ -420,10 +420,13 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
tags = tags, tags = tags,
vendor = vendor, vendor = vendor,
ident = id, ident = id,
-- WAVE channel order out (codecs/Pcm): output channel c is Vorbis channel order[c]
order = waveOrder(id.channels),
source = { source = {
format = "vorbis", format = "vorbis",
codec = "vorbis", codec = "vorbis",
vendor = vendor, vendor = vendor,
comments = raw,
blocksizes = { id.blocksize0, id.blocksize1 }, blocksizes = { id.blocksize0, id.blocksize1 },
nominalBitrate = id.bitrateNominal, nominalBitrate = id.bitrateNominal,
}, },
@@ -456,7 +459,7 @@ function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err
local function pk(b: buffer): any local function pk(b: buffer): any
return { data = b, offset = 0, size = buffer.len(b) } return { data = b, offset = 0, size = buffer.len(b) }
end end
local id, setup, vendor, tags, err = headers(pk(h1), pk(h2), pk(h3)) local id, setup, vendor, tags, _, err = headers(pk(h1), pk(h2), pk(h3))
if not id then if not id then
return nil, err return nil, err
end end
@@ -469,7 +472,8 @@ function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err
channels = id.channels, channels = id.channels,
vendor = vendor, vendor = vendor,
tags = tags, tags = tags,
out = st.out, out = st.out, -- per Vorbis channel; WAVE-order channel c is out[order[c]]
order = waveOrder(id.channels),
decode = function(_self: any, b: buffer, offset: number, size: number): number decode = function(_self: any, b: buffer, offset: number, size: number): number
if offset < 0 or size < 0 or offset + size > buffer.len(b) then if offset < 0 or size < 0 or offset + size > buffer.len(b) then
return -1 return -1
+3 -2
View File
@@ -304,7 +304,8 @@ local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean):
table.sort(keys) table.sort(keys)
for _, k in keys do for _, k in keys do
local v = tags[k] local v = tags[k]
local id = TAG_IDS[k] or (if #k == 4 and string.upper(k) == k then k else nil) -- other RIFF INFO ids come back as their lower-cased id ("ixyz") and are written as such
local id = TAG_IDS[k] or (if string.match(string.lower(k), "^i[%l%d][%l%d][%l%d]$") then string.upper(k) else nil)
if id and type(v) == "string" and v ~= "" then if id and type(v) == "string" and v ~= "" then
table.insert(items, { id, v }) table.insert(items, { id, v })
end end
@@ -383,7 +384,7 @@ function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?)
if sc.avail > 0 then if sc.avail > 0 then
local v = trimTag(buffer.readstring(buf, sc.offset, sc.avail)) local v = trimTag(buffer.readstring(buf, sc.offset, sc.avail))
if v ~= "" then if v ~= "" then
tags[name or sc.id] = v tags[name or string.lower(sc.id)] = v
end end
end end
end end
+4 -17
View File
@@ -10,6 +10,7 @@
-- --
-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / LIMIT / ARG). -- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / LIMIT / ARG).
local Err = require("@formats/core/Err") local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Decode = require("@formats/codecs/Bzip2/Decode") local Decode = require("@formats/codecs/Bzip2/Decode")
local Bzip2 = {} local Bzip2 = {}
@@ -28,24 +29,10 @@ local KINDS = {
-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err -- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err
function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
local b: buffer local b, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length)
if type(buf) == "string" then if not b then
b = buffer.fromstring(buf) return nil, aerr
elseif type(buf) == "buffer" then
b = buf
else
return nil, Err.new(Err.ARG, "Bzip2.decompress: expected a buffer or a string, got " .. typeof(buf))
end end
local n = buffer.len(b)
local o = offset or 0
if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Bzip2.decompress: bad offset " .. tostring(offset))
end
local l = length or (n - o)
if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Bzip2.decompress: bad length " .. tostring(length))
end
l = math.min(l, n - o)
local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30 local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30
if type(maxBytes) ~= "number" or maxBytes < 0 then if type(maxBytes) ~= "number" or maxBytes < 0 then
return nil, Err.new(Err.ARG, "Bzip2.decompress: bad maxBytes") return nil, Err.new(Err.ARG, "Bzip2.decompress: bad maxBytes")
+4 -17
View File
@@ -11,6 +11,7 @@
-- --
-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / UNSUPPORTED / LIMIT / ARG). -- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / UNSUPPORTED / LIMIT / ARG).
local Err = require("@formats/core/Err") local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Decode = require("@formats/codecs/Zstd/Decode") local Decode = require("@formats/codecs/Zstd/Decode")
local Zstd = {} local Zstd = {}
@@ -44,24 +45,10 @@ end
-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. Every frame in the range is decoded -- 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). -- and the outputs concatenated; 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) function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
local b: buffer local b, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length)
if type(buf) == "string" then if not b then
b = buffer.fromstring(buf) return nil, aerr
elseif type(buf) == "buffer" then
b = buf
else
return nil, Err.new(Err.ARG, "Zstd.decompress: expected a buffer or a string, got " .. typeof(buf))
end end
local n = buffer.len(b)
local o = offset or 0
if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Zstd.decompress: bad offset " .. tostring(offset))
end
local l = length or (n - o)
if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Zstd.decompress: bad length " .. tostring(length))
end
l = math.min(l, n - o)
local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30 local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30
if type(maxBytes) ~= "number" or maxBytes < 0 then if type(maxBytes) ~= "number" or maxBytes < 0 then
return nil, Err.new(Err.ARG, "Zstd.decompress: bad maxBytes " .. tostring(maxBytes)) return nil, Err.new(Err.ARG, "Zstd.decompress: bad maxBytes " .. tostring(maxBytes))
+4 -2
View File
@@ -312,6 +312,8 @@ for atom, name in TAG do
end end
Meta.TAG = TAG Meta.TAG = TAG
Meta.TAG_ATOM = TAG_ATOM Meta.TAG_ATOM = TAG_ATOM
-- freeform (----) names: tags keys are lower case; these keep their usual spelling when written back
local FREEFORM: { [string]: string } = { itunsmpb = "iTunSMPB", itunnorm = "iTunNORM", itunes_cddb_ids = "iTunes_CDDB_IDs" }
-- the ID3v1 genres gnre indexes (1-based in gnre) -- the ID3v1 genres gnre indexes (1-based in gnre)
local GENRES = { local GENRES = {
@@ -384,7 +386,7 @@ function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture
table.insert(pics, { mime = mime, data = data }) table.insert(pics, { mime = mime, data = data })
elseif kind == 1 or kind == 0 then elseif kind == 1 or kind == 0 then
local s = readstring(b, p, n) local s = readstring(b, p, n)
local key = freeName or TAG[typ] or typ local key = if freeName then string.lower(freeName) else TAG[typ] or string.lower(typ)
if typ == "\169gen" or not tags[key] then if typ == "\169gen" or not tags[key] then
tags[key] = s tags[key] = s
end end
@@ -487,7 +489,7 @@ function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: {
end) end)
box(w, "name", function() box(w, "name", function()
w:u32be(0) w:u32be(0)
w:string(k) w:string(FREEFORM[k] or k)
end) end)
dataBox(w, 1, v) dataBox(w, 1, v)
end) end)
+5 -5
View File
@@ -413,7 +413,7 @@ local function animationFrames(img: Types.Image, opts: EncodeOptions?): ({ Types
return nil, nil return nil, nil
end end
if frames ~= nil and type(frames) ~= "table" then if frames ~= nil and type(frames) ~= "table" then
return nil, Err.new(Err.ARG, "png encode: frames must be a list") return nil, Err.new(Err.ARG, "frames must be a list")
end end
if frames == nil or #frames == 0 then if frames == nil or #frames == 0 then
if mode then if mode then
@@ -445,12 +445,12 @@ end
function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if not validImage(img) then if not validImage(img) then
return nil, Err.new(Err.ARG, "png encode: needs an rgba8 Image") return nil, Err.new(Err.ARG, "needs an rgba8 Image")
end end
local w, h = img.width, img.height local w, h = img.width, img.height
local level = opts and opts.level or 6 local level = opts and opts.level or 6
if type(level) ~= "number" or level < 0 or level > 9 then if type(level) ~= "number" or level < 0 or level > 9 then
return nil, Err.new(Err.ARG, "png encode: level must be 0..9") return nil, Err.new(Err.ARG, "level must be 0..9")
end end
local frames, ferr = animationFrames(img, opts) local frames, ferr = animationFrames(img, opts)
if ferr then if ferr then
@@ -458,7 +458,7 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
end end
local loops = img.loops or 0 local loops = img.loops or 0
if frames and (type(loops) ~= "number" or loops < 0 or loops > 4294967295 or loops % 1 ~= 0) then if frames and (type(loops) ~= "number" or loops < 0 or loops > 4294967295 or loops % 1 ~= 0) then
return nil, Err.new(Err.ARG, "png encode: loops must be an integer 0..2^32-1") return nil, Err.new(Err.ARG, "loops must be an integer 0..2^32-1")
end end
local want = opts and opts.colorType or "auto" local want = opts and opts.colorType or "auto"
local ctName: string = want local ctName: string = want
@@ -480,7 +480,7 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
end end
local ct = CT_CODES[ctName] local ct = CT_CODES[ctName]
if ct == nil then if ct == nil then
return nil, Err.new(Err.ARG, "png encode: unknown colorType " .. tostring(want)) return nil, Err.new(Err.ARG, "unknown colorType " .. tostring(want))
end end
local function zdata(im: Types.Image): buffer local function zdata(im: Types.Image): buffer
return Deflate.zlibCompress(Encode.filter(im.pixels, im.width, im.height, ct), { level = level }) :: buffer return Deflate.zlibCompress(Encode.filter(im.pixels, im.width, im.height, ct), { level = level }) :: buffer
+1 -1
View File
@@ -49,7 +49,7 @@ export type EncodeOptions = {
lossless: boolean?, -- must be true or nil (lossy encoding is not supported) lossless: boolean?, -- must be true or nil (lossy encoding is not supported)
effort: number?, -- 0..9, default 5: VP8L encoder effort (more = smaller, slower) effort: number?, -- 0..9, default 5: VP8L encoder effort (more = smaller, slower)
exact: boolean?, -- keep the RGB of fully transparent pixels (default false: they may be changed) exact: boolean?, -- keep the RGB of fully transparent pixels (default false: they may be changed)
loops: number?, -- animations: loop count (default img.loops; 0 = forever) loops: number?, -- animations: play count (default img.loops; 0 = forever)
background: { number }?, -- animations: ANIM background colour { r, g, b, a } (default meta.background or 0) background: { number }?, -- animations: ANIM background colour { r, g, b, a } (default meta.background or 0)
} }
+8 -8
View File
@@ -269,22 +269,22 @@ end
-- write(midi, opts?) -> buffer | nil, Err -- write(midi, opts?) -> buffer | nil, Err
function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?)
if type(midi) ~= "table" or type(midi.tracks) ~= "table" then if type(midi) ~= "table" or type(midi.tracks) ~= "table" then
return nil, Err.new(Err.ARG, "midi encode: needs a Midi value with tracks") return nil, Err.new(Err.ARG, "needs a Midi value with tracks")
end end
local running = not (opts and opts.runningStatus == false) local running = not (opts and opts.runningStatus == false)
local format = midi.format or 1 local format = midi.format or 1
local division = midi.division or 480 local division = midi.division or 480
if type(format) ~= "number" or format < 0 or format > 2 or format % 1 ~= 0 then if type(format) ~= "number" or format < 0 or format > 2 or format % 1 ~= 0 then
return nil, Err.new(Err.ARG, "midi encode: format must be 0, 1 or 2") return nil, Err.new(Err.ARG, "format must be 0, 1 or 2")
end end
if type(division) ~= "number" or division == 0 or division < -32768 or division > 32767 or division % 1 ~= 0 then if type(division) ~= "number" or division == 0 or division < -32768 or division > 32767 or division % 1 ~= 0 then
return nil, Err.new(Err.ARG, "midi encode: division must be a non-zero 16-bit integer") return nil, Err.new(Err.ARG, "division must be a non-zero 16-bit integer")
end end
if format == 0 and #midi.tracks ~= 1 then if format == 0 and #midi.tracks ~= 1 then
return nil, Err.new(Err.ARG, "midi encode: format 0 needs exactly one track") return nil, Err.new(Err.ARG, "format 0 needs exactly one track")
end end
if #midi.tracks > 65535 then if #midi.tracks > 65535 then
return nil, Err.new(Err.ARG, "midi encode: too many tracks") return nil, Err.new(Err.ARG, "too many tracks")
end end
local w = Bytes.writer(1024) local w = Bytes.writer(1024)
w:string("MThd") w:string("MThd")
@@ -295,7 +295,7 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?)
for ti, track in midi.tracks do for ti, track in midi.tracks do
local events = if type(track) == "table" then track.events else nil local events = if type(track) == "table" then track.events else nil
if type(events) ~= "table" then if type(events) ~= "table" then
return nil, Err.new(Err.ARG, "midi encode: track " .. ti .. " has no events list") return nil, Err.new(Err.ARG, "track " .. ti .. " has no events list")
end end
-- stable order by tick -- stable order by tick
local sorted = true local sorted = true
@@ -338,7 +338,7 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?)
end end
local delta = ev.tick - prev local delta = ev.tick - prev
if delta > 0x0FFFFFFF then if delta > 0x0FFFFFFF then
return nil, Err.new(Err.ARG, "midi encode: a delta time over 0x0FFFFFFF ticks") return nil, Err.new(Err.ARG, "a delta time over 0x0FFFFFFF ticks")
end end
local base = TYPE_STATUS[t] local base = TYPE_STATUS[t]
if base then if base then
@@ -378,7 +378,7 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?)
w:u8(if t == "sysex" then 0xF0 else 0xF7) w:u8(if t == "sysex" then 0xF0 else 0xF7)
end end
if #d > 0x0FFFFFFF then if #d > 0x0FFFFFFF then
return nil, Err.new(Err.ARG, "midi encode: event data too long") return nil, Err.new(Err.ARG, "event data too long")
end end
vlq(w, #d) vlq(w, #d)
for _, c in d do for _, c in d do
+24
View File
@@ -129,4 +129,28 @@ do
t:check(F.data.null == F.null, "F.data.null") t:check(F.data.null == F.null, "F.data.null")
end end
-- img.loops is a play count in every animated format (GIF stores repeats; APNG / WebP store plays)
do
local function anim(loops: number): any
local img = image(8, 8)
img.frames = {}
for k = 1, 2 do
local fr = image(8, 8)
buffer.writeu8(fr.pixels, 0, k)
table.insert(img.frames, { image = fr, delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" })
end
img.loops = loops
return img
end
for _, fmt in { "gif", "png", "webp" } do
for _, loops in { 0, 1, 3 } do
local saved, err = F.save(anim(loops), nil, { format = fmt, lossless = true })
t:check(saved, fmt .. " loops " .. loops .. ": " .. tostring(err))
local back = saved and F.load(saved)
t:check(back and back.frames and #back.frames == 2, fmt .. " loops " .. loops .. ": animated")
t:eq(back and back.loops, loops, fmt .. ": loops " .. loops .. " round trip")
end
end
end
t:done() t:done()
+3 -2
View File
@@ -4,6 +4,7 @@
-- Reader; tags and pictures; the length from the last frame; sniff; the api; damaged frames skipped; the fuzz pass. -- Reader; tags and pictures; the length from the last frame; sniff; the api; damaged frames skipped; the fuzz pass.
-- Ported from flac-luau tests/flac.luau. Fixtures: tools/fixtures/flac.py. -- Ported from flac-luau tests/flac.luau. Fixtures: tools/fixtures/flac.py.
local T = require("@tests/T") local T = require("@tests/T")
local VorbisComment = require("@formats/codecs/VorbisComment")
local Flac = require("@formats/audio/flac") local Flac = require("@formats/audio/flac")
local Bytes = require("@formats/core/Bytes") local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32") local Crc32 = require("@formats/core/Crc32")
@@ -92,8 +93,8 @@ for _, fx in Cases do
t:check(math.abs(pos - fx.frames / 3) <= 1, name .. ": seek seconds") t:check(math.abs(pos - fx.frames / 3) <= 1, name .. ": seek seconds")
dec:seek(dec.duration + 5) dec:seek(dec.duration + 5)
t:eq(select(2, dec:read(10)), 0, name .. ": read past the end") t:eq(select(2, dec:read(10)), 0, name .. ": read past the end")
for key, v in fx.tags or {} do for key, v in fx.tags or {} do -- (tags keys are lower case: codecs/VorbisComment)
t:eq(dec.tags[key], v, name .. ": tag " .. key) t:eq(dec.tags[VorbisComment.tagKey(key)], v, name .. ": tag " .. key)
end end
t:eq(Flac.sniff(Bytes.reader(buffer.fromstring(fx.data))), 1, name .. ": sniff") t:eq(Flac.sniff(Bytes.reader(buffer.fromstring(fx.data))), 1, name .. ": sniff")
end end
+3 -3
View File
@@ -80,9 +80,9 @@ do
t:eq(back.meta.source.bitDepth, 8, "bit depth from meta.source") t:eq(back.meta.source.bitDepth, 8, "bit depth from meta.source")
-- (the absorbed FLAC decoder keeps Vorbis comment keys upper case) -- (the absorbed FLAC decoder keeps Vorbis comment keys upper case)
local tags = back.tags :: any local tags = back.tags :: any
t:eq(tags.title or tags.TITLE, "Tïtle", "title") t:eq(tags.title, "Tïtle", "title")
t:eq(tags.artist or tags.ARTIST, "Artist", "artist") t:eq(tags.artist, "Artist", "artist")
t:eq(tags.track or tags.TRACKNUMBER, "3", "track number") t:eq(tags.track, "3", "track number")
local empty = Flac.encode(Types.Audio.new(44100, 2, 0)) :: buffer local empty = Flac.encode(Types.Audio.new(44100, 2, 0)) :: buffer
local e0 = Flac.decode(Bytes.reader(empty)) local e0 = Flac.decode(Bytes.reader(empty))
t:check(e0 and e0.frames == 0, "empty audio") t:check(e0 and e0.frames == 0, "empty audio")
+3 -3
View File
@@ -344,7 +344,7 @@ do
eq(tg.title, "Test Title", "fixture title") eq(tg.title, "Test Title", "fixture title")
eq(tg.artist, "Some Artist", "fixture artist") eq(tg.artist, "Some Artist", "fixture artist")
eq(tg.album, "An Album", "fixture album") eq(tg.album, "An Album", "fixture album")
eq(tg.year, "2001", "fixture year") eq(tg.date, "2001", "fixture year")
eq(tg.track, "7", "fixture track") eq(tg.track, "7", "fixture track")
eq(tg.genre, "Rock", "fixture genre") eq(tg.genre, "Rock", "fixture genre")
eq(tg.comment, "hello", "fixture comment") eq(tg.comment, "hello", "fixture comment")
@@ -405,7 +405,7 @@ do
eq(dec.tags.title, "Ünïcödé ★ title", "v2.4 title") eq(dec.tags.title, "Ünïcödé ★ title", "v2.4 title")
eq(dec.tags.artist, "One / Two", "v2.4 multi-value") eq(dec.tags.artist, "One / Two", "v2.4 multi-value")
eq(dec.tags.genre, "Rock", "v2.4 genre") eq(dec.tags.genre, "Rock", "v2.4 genre")
eq(dec.tags.year, "1999-05-01", "v2.4 TDRC") eq(dec.tags.date, "1999-05-01", "v2.4 TDRC")
eq(dec.tags.comment, "a comment", "v2.4 COMM") eq(dec.tags.comment, "a comment", "v2.4 COMM")
sameAudio(dec, "v2.4") sameAudio(dec, "v2.4")
t:check(Mp3.sniff(Bytes.reader(withAudio(tag))) >= 0.7, "sniff behind an ID3v2 tag") t:check(Mp3.sniff(Bytes.reader(withAudio(tag))) >= 0.7, "sniff behind an ID3v2 tag")
@@ -453,7 +453,7 @@ do
eq(dec.tags.title, "V1 Title", "v1 title") eq(dec.tags.title, "V1 Title", "v1 title")
eq(dec.tags.artist, "V1 Artist", "v1 artist") eq(dec.tags.artist, "V1 Artist", "v1 artist")
eq(dec.tags.album, "V1 Album", "v1 album") eq(dec.tags.album, "V1 Album", "v1 album")
eq(dec.tags.year, "1987", "v1 year") eq(dec.tags.date, "1987", "v1 year")
eq(dec.tags.comment, "v1 comment", "v1 comment") eq(dec.tags.comment, "v1 comment", "v1 comment")
eq(dec.tags.track, "9", "v1.1 track") eq(dec.tags.track, "9", "v1.1 track")
eq(dec.tags.genre, "Rock", "v1 genre") eq(dec.tags.genre, "Rock", "v1 genre")
+12
View File
@@ -7,6 +7,7 @@ local Vorbis = require("@formats/audio/vorbis")
local Bytes = require("@formats/core/Bytes") local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err") local Err = require("@formats/core/Err")
local Types = require("@formats/Types") local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Ogg = require("@formats/containers/Ogg") local Ogg = require("@formats/containers/Ogg")
local Cases = require("@tests/gen/vorbis_cases") local Cases = require("@tests/gen/vorbis_cases")
@@ -57,6 +58,17 @@ for _, c in Cases do
t:eq(a.frames, c.inputFrames, c.name .. ": frames = the encoder's input") t:eq(a.frames, c.inputFrames, c.name .. ": frames = the encoder's input")
local ref16 = buffer.fromstring(c.ref16) local ref16 = buffer.fromstring(c.ref16)
local n = c.frames * c.channels local n = c.frames * c.channels
-- oggdec -R keeps the Vorbis channel order; the decoder returns WAVE order (codecs/Pcm)
local order = Pcm.WAVE_FROM_VORBIS[c.channels]
if c.channels > 2 and order then
local w = buffer.create(buffer.len(ref16))
for f = 0, c.frames - 1 do
for ch = 1, c.channels do
buffer.writei16(w, (f * c.channels + ch - 1) * 2, buffer.readi16(ref16, (f * c.channels + order[ch] - 1) * 2))
end
end
ref16 = w
end
local d = maxDiff16(a.samples, 0, ref16, 0, n) local d = maxDiff16(a.samples, 0, ref16, 0, n)
t:check(d <= 1, string.format("%s: within 1 LSB of oggdec (max %d)", c.name, d)) t:check(d <= 1, string.format("%s: within 1 LSB of oggdec (max %d)", c.name, d))
if c.ffRef then if c.ffRef then
+2 -2
View File
@@ -182,7 +182,7 @@ end
do -- tags do -- tags
local info = "INFO" .. "INAM" .. u32(3) .. "abc\0" .. "IART" .. u32(6) .. "xy\0\0\0\0" .. "IXYZ" .. u32(2) .. "zz" .. "ITRK" .. u32(2) .. "7\0" local info = "INFO" .. "INAM" .. u32(3) .. "abc\0" .. "IART" .. u32(6) .. "xy\0\0\0\0" .. "IXYZ" .. u32(2) .. "zz" .. "ITRK" .. u32(2) .. "7\0"
local dec = open(riff(fmt(1, 1, 8000, 8), chunk("LIST", info), chunk("data", "\128\128\128"))) local dec = open(riff(fmt(1, 1, 8000, 8), chunk("LIST", info), chunk("data", "\128\128\128")))
t:check(dec and dec.tags.title == "abc" and dec.tags.artist == "xy" and dec.tags.IXYZ == "zz" and dec.tags.track == "7", "tags") t:check(dec and dec.tags.title == "abc" and dec.tags.artist == "xy" and dec.tags.ixyz == "zz" and dec.tags.track == "7", "tags")
t:check(dec and dec.frames == 3, "8-bit odd data") t:check(dec and dec.frames == 3, "8-bit odd data")
end end
do -- 8-bit, A-law and mu-law values do -- 8-bit, A-law and mu-law values
@@ -251,7 +251,7 @@ do
-- tags -- tags
a.tags = { title = "Hello", artist = "Someone", IXYZ = "kept", comment = "" } a.tags = { title = "Hello", artist = "Someone", IXYZ = "kept", comment = "" }
local tg = Wav.decode(Bytes.reader(Wav.encode(a, { sampleFormat = "u8" }) :: buffer)) :: any local tg = Wav.decode(Bytes.reader(Wav.encode(a, { sampleFormat = "u8" }) :: buffer)) :: any
t:check(tg.tags.title == "Hello" and tg.tags.artist == "Someone" and tg.tags.IXYZ == "kept" and tg.tags.comment == nil, "tag round trip") t:check(tg.tags.title == "Hello" and tg.tags.artist == "Someone" and tg.tags.ixyz == "kept" and tg.tags.comment == nil, "tag round trip")
-- encodeParts, and RF64 chosen automatically past the threshold -- encodeParts, and RF64 chosen automatically past the threshold
local big = Types.Audio.new(44100, 2, 3000) local big = Types.Audio.new(44100, 2, 3000)
for i = 0, 3000 * 2 - 1 do for i = 0, 3000 * 2 - 1 do
+7 -5
View File
@@ -18,11 +18,12 @@ INPUTS = ["src/Formats/audio/vorbis", "src/Formats/codecs", "src/Formats/contain
WAVE_FROM_VORBIS6 = [0, 2, 1, 4, 5, 3] # vorbis channel k is WAVE channel WAVE_FROM_VORBIS6[k] WAVE_FROM_VORBIS6 = [0, 2, 1, 4, 5, 3] # vorbis channel k is WAVE channel WAVE_FROM_VORBIS6[k]
def reorder(x): def to_wave(x):
"""6-channel samples in Vorbis order -> WAVE order"""
out = [0.0] * len(x) out = [0.0] * len(x)
for i in range(0, len(x) - 5, 6): for i in range(0, len(x) - 5, 6):
for k in range(6): for k in range(6):
out[i + k] = x[i + WAVE_FROM_VORBIS6[k]] out[i + WAVE_FROM_VORBIS6[k]] = x[i + k]
return out return out
@@ -59,11 +60,12 @@ def generate(ctx):
problems = "\n".join(l for l in info.split("\n") if re.search(r"(?i)warning|error", l)) problems = "\n".join(l for l in info.split("\n") if re.search(r"(?i)warning|error", l))
raw = A.tool(ctx, "vorbis-tools", ["oggdec", "-Q", "-R", "-o", "{out}", "{in}"], data, "ogg", "raw") raw = A.tool(ctx, "vorbis-tools", ["oggdec", "-Q", "-R", "-o", "{out}", "{in}"], data, "ogg", "raw")
od = [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw) - 1, 2)] od = [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw) - 1, 2)]
osnr, _ = A.snr(samples, od, ch) # (oggdec -R keeps the Vorbis channel order) if ch == 6: # the input is in WAVE order (FL FR FC LFE RL RR); oggdec -R keeps the Vorbis order (FL FC FR RL RR LFE)
od = to_wave(od)
osnr, _ = A.snr(samples, od, ch)
ffe = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], data, "ogg").decode(errors="replace") ffe = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], data, "ogg").decode(errors="replace")
_, fch, ff = A.ffdecode(ctx, data, ext="ogg") _, fch, ff = A.ffdecode(ctx, data, ext="ogg")
if ch == 6: # ffmpeg reorders to WAVE order (FL FR FC LFE RL RR); Vorbis order is FL FC FR RL RR LFE # (ffmpeg decodes to WAVE order, like our decoder)
ff = reorder(ff)
fsnr, _ = A.snr(samples, ff, ch) if fch == ch else (-99.0, 0) fsnr, _ = A.snr(samples, ff, ch) if fch == ch else (-99.0, 0)
e = {"name": name, "sig": sigmod, "quality": q, "rate": rate, "channels": ch, "frames": frames, "ogginfo": problems, e = {"name": name, "sig": sigmod, "quality": q, "rate": rate, "channels": ch, "frames": frames, "ogginfo": problems,
"oggdecFrames": len(od) // ch, "oggdecSnr": osnr, "ffFrames": len(ff) // max(1, fch), "ffSnr": fsnr, "oggdecFrames": len(od) // ch, "oggdecSnr": osnr, "ffFrames": len(ff) // max(1, fch), "ffSnr": fsnr,