ws-audio: FLAC encoder (audio/flac/Encode: levels 0-8 like libFLAC presets, fixed + LPC + Rice/Rice2 partition search, wasted bits, stereo decorrelation, MD5, VORBIS_COMMENT, SEEKTABLE, padding; streams from a Decoder) wired into audio/flac encode; core/Md5 (new core module, RFC 1321) + test; fixtures: flac -t + MD5 bit-exact on 76 encodes, sizes within 1.1% of libFLAC; bench lines
This commit is contained in:
1 parent
bdab71df77
commit
c74c93ae11
10 files changed
+1553
-6
No files matched your search
+1
-1
@@ -9,7 +9,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
|
||||
| audio | aiff | .aiff .aif .aifc .afc | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/aiff.luau` |
|
||||
| audio | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.luau` |
|
||||
| audio | flac | .flac .oga | 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 | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` |
|
||||
| audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` |
|
||||
| audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` |
|
||||
|
||||
@@ -68,8 +68,8 @@ local list: { Entry } = {
|
||||
path = "audio/flac",
|
||||
extensions = { "flac", "oga" },
|
||||
mime = { "audio/flac", "audio/x-flac" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
|
||||
caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
|
||||
load = function()
|
||||
return require("@formats/audio/flac")
|
||||
end,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,9 @@
|
||||
-- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame
|
||||
-- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in
|
||||
-- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when
|
||||
-- STREAMINFO has none. Not supported: encoding (ws-audio), MD5 verification, chained Ogg streams.
|
||||
-- STREAMINFO has none. Encode (audio/flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels
|
||||
-- 0-8 like libFLAC's presets, 4-24 bits, 1-8 channels, MD5, VORBIS_COMMENT, SEEKTABLE. Not supported: MD5
|
||||
-- verification on decode, chained Ogg streams, Ogg FLAC output.
|
||||
--
|
||||
-- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...)
|
||||
-- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end
|
||||
@@ -18,6 +20,8 @@ local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Ogg = require("@formats/containers/Ogg")
|
||||
local Stream = require("@formats/audio/flac/Stream")
|
||||
local Encode = require("@formats/audio/flac/Encode")
|
||||
local Pcm = require("@formats/codecs/Pcm")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Flac = {
|
||||
@@ -25,8 +29,8 @@ local Flac = {
|
||||
category = "audio",
|
||||
extensions = { "flac", "oga" },
|
||||
mime = { "audio/flac", "audio/x-flac" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
|
||||
caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
@@ -35,6 +39,13 @@ export type OpenOptions = {
|
||||
crc16: boolean?, -- check every frame's CRC-16 (default true; a bad frame is skipped by resyncing)
|
||||
maxFrames: number?, -- decode(): refuse streams longer than this many sample frames (default 2^28)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
level: number?, -- 0..8 like libFLAC's -0 .. -8 (default 5)
|
||||
bits: number?, -- bits per sample 4..24 (default: the source's meta.source.bitDepth / bitsPerSample if 4..24, else 16)
|
||||
blockSize: number?, -- 16..65535 (default: the level's, 1152 or 4096)
|
||||
seekInterval: number?, -- seconds between SEEKTABLE points when the length is known (default 10; 0 = none)
|
||||
padding: number?, -- bytes of PADDING after the metadata (default 0)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Flac.sniff(r: Bytes.Reader): number
|
||||
@@ -108,6 +119,51 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(audioOrDecoder, opts?) -> FLAC file buffer | nil, Err
|
||||
function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local src, serr = Pcm.source(value)
|
||||
if not src then
|
||||
return nil, serr
|
||||
end
|
||||
local o: EncodeOptions = opts or {}
|
||||
local level = o.level or 5
|
||||
if type(level) ~= "number" or level ~= math.floor(level) or level < 0 or level > 8 then
|
||||
return nil, Err.new(Err.ARG, "level must be 0..8")
|
||||
end
|
||||
local bits = o.bits
|
||||
if bits == nil then
|
||||
local v = value :: any
|
||||
local sb = (type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.bitDepth) or v.bitsPerSample
|
||||
bits = if type(sb) == "number" and sb >= 4 and sb <= 24 then sb else 16
|
||||
end
|
||||
if type(bits) ~= "number" or bits ~= math.floor(bits) or bits < 4 or bits > 24 then
|
||||
return nil, Err.new(Err.ARG, "bits must be 4..24")
|
||||
end
|
||||
local bs = o.blockSize
|
||||
if bs ~= nil and (type(bs) ~= "number" or bs ~= math.floor(bs) or bs < 16 or bs > 65535) then
|
||||
return nil, Err.new(Err.ARG, "blockSize must be 16..65535")
|
||||
end
|
||||
if src.channels > 8 then
|
||||
return nil, Err.new(Err.ARG, "FLAC holds at most 8 channels")
|
||||
end
|
||||
if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 20 then
|
||||
return nil, Err.new(Err.ARG, "the sample rate must be an integer below 2^20")
|
||||
end
|
||||
local out, msg = Encode.encode(src :: any, {
|
||||
level = level,
|
||||
bits = bits :: number,
|
||||
blockSize = bs,
|
||||
seekInterval = math.max(0, o.seekInterval or 10),
|
||||
padding = math.clamp(math.floor(o.padding or 0), 0, 0xFFFFFF),
|
||||
vendor = "formats-luau",
|
||||
})
|
||||
if not out then
|
||||
return nil, Err.new(Err.CORRUPT, tostring(msg))
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> Decoder | nil, Err
|
||||
function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?)
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- core/Md5: MD5 (RFC 1321), incremental. Written from the RFC. Used by the FLAC encoder (STREAMINFO's MD5 of the PCM);
|
||||
-- not for security.
|
||||
--
|
||||
-- local h = Md5.new()
|
||||
-- h:update(buf, offset?, length?) -- any number of times
|
||||
-- local digest = h:digest() -- 16-byte string (the state is finished; make a new one to hash again)
|
||||
-- Md5.hex(digest) / Md5.of(buf) -> hex string
|
||||
-- Never throws (ranges are clamped to the buffer).
|
||||
local Md5 = {}
|
||||
|
||||
local band, bor, bxor, bnot, lrotate = bit32.band, bit32.bor, bit32.bxor, bit32.bnot, bit32.lrotate
|
||||
local readu32, writeu32, writeu8 = buffer.readu32, buffer.writeu32, buffer.writeu8
|
||||
|
||||
local K = table.create(64, 0)
|
||||
for i = 0, 63 do
|
||||
K[i + 1] = math.floor(math.abs(math.sin(i + 1)) * 4294967296) % 4294967296
|
||||
end
|
||||
local S = {
|
||||
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
|
||||
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
|
||||
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
|
||||
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
|
||||
}
|
||||
local G = table.create(64, 0)
|
||||
for i = 0, 63 do
|
||||
if i < 16 then
|
||||
G[i + 1] = i
|
||||
elseif i < 32 then
|
||||
G[i + 1] = (5 * i + 1) % 16
|
||||
elseif i < 48 then
|
||||
G[i + 1] = (3 * i + 5) % 16
|
||||
else
|
||||
G[i + 1] = (7 * i) % 16
|
||||
end
|
||||
end
|
||||
|
||||
export type State = {
|
||||
a: number,
|
||||
b: number,
|
||||
c: number,
|
||||
d: number,
|
||||
block: buffer, -- 64-byte pending block
|
||||
fill: number,
|
||||
total: number, -- bytes hashed
|
||||
update: (self: State, buf: buffer, offset: number?, length: number?) -> (),
|
||||
digest: (self: State) -> string,
|
||||
}
|
||||
|
||||
local M = table.create(16, 0)
|
||||
|
||||
local function compress(st: State, blk: buffer, o: number)
|
||||
for i = 0, 15 do
|
||||
M[i + 1] = readu32(blk, o + i * 4)
|
||||
end
|
||||
local a, b, c, d = st.a, st.b, st.c, st.d
|
||||
for i = 0, 63 do
|
||||
local f
|
||||
if i < 16 then
|
||||
f = bor(band(b, c), band(bnot(b), d))
|
||||
elseif i < 32 then
|
||||
f = bor(band(d, b), band(bnot(d), c))
|
||||
elseif i < 48 then
|
||||
f = bxor(b, c, d)
|
||||
else
|
||||
f = bxor(c, bor(b, bnot(d)))
|
||||
end
|
||||
local tmp = d
|
||||
d = c
|
||||
c = b
|
||||
b = (b + lrotate((a + f + K[i + 1] + M[G[i + 1] + 1]) % 4294967296, S[i + 1])) % 4294967296
|
||||
a = tmp
|
||||
end
|
||||
st.a = (st.a + a) % 4294967296
|
||||
st.b = (st.b + b) % 4294967296
|
||||
st.c = (st.c + c) % 4294967296
|
||||
st.d = (st.d + d) % 4294967296
|
||||
end
|
||||
|
||||
local function update(self: State, buf: buffer, offset: number?, length: number?)
|
||||
local n = buffer.len(buf)
|
||||
local o = math.clamp(offset or 0, 0, n)
|
||||
local len = math.clamp(length or (n - o), 0, n - o)
|
||||
self.total += len
|
||||
local blk = self.block
|
||||
if self.fill > 0 then
|
||||
local take = math.min(64 - self.fill, len)
|
||||
buffer.copy(blk, self.fill, buf, o, take)
|
||||
self.fill += take
|
||||
o += take
|
||||
len -= take
|
||||
if self.fill == 64 then
|
||||
compress(self, blk, 0)
|
||||
self.fill = 0
|
||||
end
|
||||
end
|
||||
while len >= 64 do
|
||||
compress(self, buf, o)
|
||||
o += 64
|
||||
len -= 64
|
||||
end
|
||||
if len > 0 then
|
||||
buffer.copy(blk, 0, buf, o, len)
|
||||
self.fill = len
|
||||
end
|
||||
end
|
||||
|
||||
local function digest(self: State): string
|
||||
local bits = self.total * 8
|
||||
local blk = self.block
|
||||
local f = self.fill
|
||||
writeu8(blk, f, 0x80)
|
||||
f += 1
|
||||
if f > 56 then
|
||||
buffer.fill(blk, f, 0, 64 - f)
|
||||
compress(self, blk, 0)
|
||||
f = 0
|
||||
end
|
||||
buffer.fill(blk, f, 0, 56 - f)
|
||||
writeu32(blk, 56, bits % 4294967296)
|
||||
writeu32(blk, 60, math.floor(bits / 4294967296) % 4294967296)
|
||||
compress(self, blk, 0)
|
||||
self.fill = 0
|
||||
local out = buffer.create(16)
|
||||
writeu32(out, 0, self.a)
|
||||
writeu32(out, 4, self.b)
|
||||
writeu32(out, 8, self.c)
|
||||
writeu32(out, 12, self.d)
|
||||
return buffer.tostring(out)
|
||||
end
|
||||
|
||||
function Md5.new(): State
|
||||
return {
|
||||
a = 0x67452301,
|
||||
b = 0xEFCDAB89,
|
||||
c = 0x98BADCFE,
|
||||
d = 0x10325476,
|
||||
block = buffer.create(64),
|
||||
fill = 0,
|
||||
total = 0,
|
||||
update = update,
|
||||
digest = digest,
|
||||
}
|
||||
end
|
||||
|
||||
-- hex(digest) -> 32 lower-case hex digits
|
||||
function Md5.hex(d: string): string
|
||||
local out = table.create(#d)
|
||||
for i = 1, #d do
|
||||
out[i] = string.format("%02x", string.byte(d, i))
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
-- of(buf, offset?, length?) -> hex digest
|
||||
function Md5.of(buf: buffer, offset: number?, length: number?): string
|
||||
local h = Md5.new()
|
||||
h:update(buf, offset, length)
|
||||
return Md5.hex(h:digest())
|
||||
end
|
||||
|
||||
return Md5
|
||||
@@ -0,0 +1,109 @@
|
||||
-- audio/flac encoder tests: every fixture-step encode (levels 0-8, 1 / 2 / 6 channels, 8 / 12 / 16 / 20 / 24 bits,
|
||||
-- odd lengths and block sizes, odd rates, seek tables, padding) passed `flac -t` and carries the MD5 of the quantized
|
||||
-- input; sizes within 10% of libFLAC at the same level; each decodes bit-exactly through our own decoder; streaming
|
||||
-- from a Decoder gives the same bytes; tags; option errors. Fixtures: tools/fixtures/flac_enc.py.
|
||||
local T = require("@tests/T")
|
||||
local Flac = require("@formats/audio/flac")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/Pcm")
|
||||
local Enc = require("@tests/gen/flac_enc")
|
||||
local Sigs = require("@tests/gen/flac_enc_sigs")
|
||||
|
||||
local t = T.suite("flac_encode")
|
||||
|
||||
local sigCache: { [string]: any } = {}
|
||||
local function sig(name: string): Types.Audio
|
||||
local s = sigCache[name]
|
||||
if not s then
|
||||
local m = Sigs[name]
|
||||
s = Types.Audio.new(m.rate, m.channels, m.frames)
|
||||
buffer.writestring(s.samples, 0, m.data)
|
||||
sigCache[name] = s
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
t:check(Flac.caps.encode and Flac.encode ~= nil, "caps.encode")
|
||||
|
||||
local worst = 0
|
||||
for _, e in Enc do
|
||||
t:eq(e.flacTest, "", e.name .. ": flac -t")
|
||||
t:eq(e.md5, e.wantMd5, e.name .. ": STREAMINFO MD5 = MD5 of the quantized input")
|
||||
if e.refSize then
|
||||
local ratio = e.size / e.refSize
|
||||
worst = math.max(worst, ratio)
|
||||
t:check(ratio < 1.1, string.format("%s: %d bytes, libFLAC %d (%.3f)", e.name, e.size, e.refSize, ratio))
|
||||
end
|
||||
-- our decoder: bit-exact against the input quantized to e.bits
|
||||
local a = sig(e.sig)
|
||||
local back, err = Flac.decode(Bytes.reader(buffer.fromstring(e.data)))
|
||||
t:check(back, e.name .. ": our decoder: " .. tostring(err))
|
||||
t:check(back.frames == a.frames and back.channels == a.channels and back.sampleRate == a.sampleRate, e.name .. ": format")
|
||||
local s = 2 ^ (e.bits - 1)
|
||||
local exact = true
|
||||
for i = 0, a.frames * a.channels - 1 do
|
||||
local want = math.clamp(math.floor(buffer.readf32(a.samples, i * 4) * s + 0.5), -s, s - 1)
|
||||
if math.floor(buffer.readf32(back.samples, i * 4) * s + 0.5) ~= want then
|
||||
exact = false
|
||||
break
|
||||
end
|
||||
end
|
||||
t:check(exact, e.name .. ": bit-exact round trip")
|
||||
t:eq(back.meta.source.bitDepth, e.bits, e.name .. ": bits per sample")
|
||||
end
|
||||
t:note("%d encodes pass flac -t with the right MD5 and decode bit-exactly; worst size vs libFLAC %.3f", #Enc, worst)
|
||||
|
||||
-- streaming: a Decoder source gives the same bytes as the Audio
|
||||
do
|
||||
local a = sig("flacsig_music_2_7000_44100")
|
||||
local f1 = Flac.encode(a, { level = 5 }) :: buffer
|
||||
local f2 = Flac.encode(Pcm.audioDecoder(a), { level = 5 }) :: buffer
|
||||
t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source")
|
||||
-- a decoder of our own output re-encodes to the same stream (its bit depth carries over)
|
||||
local dec = Flac.open(Bytes.reader(f1)) :: any
|
||||
local f3 = Flac.encode(dec, { level = 5 }) :: buffer
|
||||
t:check(buffer.tostring(f3) == buffer.tostring(f1), "FLAC -> FLAC through the streaming decoder")
|
||||
end
|
||||
|
||||
-- tags, bit depth from the source
|
||||
do
|
||||
local a = Types.Audio.new(48000, 1, 3000)
|
||||
for i = 0, 2999 do
|
||||
buffer.writef32(a.samples, i * 4, math.floor(math.sin(i / 7) * 100) / 128)
|
||||
end
|
||||
a.tags = { title = "Tïtle", artist = "Artist", track = "3" }
|
||||
a.meta.source = { format = "wav", bitDepth = 8 }
|
||||
local f = Flac.encode(a) :: buffer
|
||||
local back = Flac.decode(Bytes.reader(f)) :: Types.Audio
|
||||
t:eq(back.meta.source.bitDepth, 8, "bit depth from meta.source")
|
||||
-- (the absorbed FLAC decoder keeps Vorbis comment keys upper case)
|
||||
local tags = back.tags :: any
|
||||
t:eq(tags.title or tags.TITLE, "Tïtle", "title")
|
||||
t:eq(tags.artist or tags.ARTIST, "Artist", "artist")
|
||||
t:eq(tags.track or tags.TRACKNUMBER, "3", "track number")
|
||||
local empty = Flac.encode(Types.Audio.new(44100, 2, 0)) :: buffer
|
||||
local e0 = Flac.decode(Bytes.reader(empty))
|
||||
t:check(e0 and e0.frames == 0, "empty audio")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local a = Types.Audio.new(44100, 2, 10)
|
||||
local function code(v: any, o: any): string?
|
||||
local _, e = Flac.encode(v, o)
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code({}, nil), Err.ARG, "junk value")
|
||||
t:eq(code(a, { level = 9 }), Err.ARG, "level 9")
|
||||
t:eq(code(a, { level = 2.5 }), Err.ARG, "level 2.5")
|
||||
t:eq(code(a, { bits = 32 }), Err.ARG, "32 bits")
|
||||
t:eq(code(a, { bits = 3 }), Err.ARG, "3 bits")
|
||||
t:eq(code(a, { blockSize = 8 }), Err.ARG, "block size 8")
|
||||
t:eq(code(Types.Audio.new(44100, 9, 1), nil), Err.ARG, "9 channels")
|
||||
t:eq(code(Types.Audio.new(44100.5, 1, 1), nil), Err.ARG, "fractional rate")
|
||||
end
|
||||
|
||||
-- (the decoder's fuzz pass is in tests/audio/flac.luau; the encoder takes no untrusted bytes)
|
||||
t:done()
|
||||
@@ -0,0 +1,30 @@
|
||||
-- core/Md5 tests: the RFC 1321 test suite, incremental updates at every split, sub-ranges, a long input.
|
||||
local T = require("@tests/T")
|
||||
local Md5 = require("@formats/core/Md5")
|
||||
|
||||
local t = T.suite("md5")
|
||||
local VECTORS = {
|
||||
{ "", "d41d8cd98f00b204e9800998ecf8427e" },
|
||||
{ "a", "0cc175b9c0f1b6a831c399e269772661" },
|
||||
{ "abc", "900150983cd24fb0d6963f7d28e17f72" },
|
||||
{ "message digest", "f96b697d7cb7938d525a2f31aaf161d0" },
|
||||
{ "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b" },
|
||||
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f" },
|
||||
{ string.rep("1234567890", 8), "57edf4a22be3c955ac49da2e2107b67a" },
|
||||
}
|
||||
for _, v in VECTORS do
|
||||
t:eq(Md5.of(buffer.fromstring(v[1])), v[2], "md5 of " .. string.format("%q", v[1]))
|
||||
end
|
||||
-- incremental: every split point of a 130-byte message, three pieces
|
||||
local msg = string.rep("The quick brown fox jumps over the lazy dog. ", 3)
|
||||
local want = Md5.of(buffer.fromstring(msg))
|
||||
for cut = 0, #msg, 7 do
|
||||
local h = Md5.new()
|
||||
h:update(buffer.fromstring(string.sub(msg, 1, cut)))
|
||||
h:update(buffer.fromstring(string.sub(msg, cut + 1, cut + 20)))
|
||||
h:update(buffer.fromstring(string.sub(msg, cut + 21)))
|
||||
t:eq(Md5.hex(h:digest()), want, "split at " .. cut)
|
||||
end
|
||||
t:eq(Md5.of(buffer.fromstring("xxabcyy"), 2, 3), "900150983cd24fb0d6963f7d28e17f72", "sub-range")
|
||||
t:eq(Md5.of(buffer.fromstring(string.rep("a", 1000000))), "7707d6ae4e027c70eea2a935c2296f21", "a million a's")
|
||||
t:done()
|
||||
@@ -125,3 +125,22 @@ do
|
||||
Wav.decode(Bytes.reader(file))
|
||||
end)
|
||||
end
|
||||
-- flac encode (ws-audio): 10 s of 44.1 kHz stereo 16-bit (a synthetic two-tone signal with noise)
|
||||
do
|
||||
local Fl = require("@formats/audio/flac")
|
||||
local n = 441000
|
||||
local a = Types.Audio.new(44100, 2, n)
|
||||
local seed = 1
|
||||
for i = 0, n - 1 do
|
||||
seed = (seed * 1103515245 + 12345) % 2147483648
|
||||
local noise = (seed / 2147483648 - 0.5) * 0.01
|
||||
buffer.writef32(a.samples, i * 8, math.floor((math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1 + noise) * 32768) / 32768)
|
||||
buffer.writef32(a.samples, i * 8 + 4, math.floor((math.sin(i * 0.017) * 0.3 + noise) * 32768) / 32768)
|
||||
end
|
||||
for _, level in { 0, 5, 8 } do
|
||||
local dt = bench("flac encode -" .. level .. " (10 s st 16)", 2, n * 4, function()
|
||||
Fl.encode(a, { level = level })
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.0fx real time", runtime, "", 10 / dt))
|
||||
end
|
||||
end
|
||||
@@ -272,3 +272,45 @@ def pcm_fixtures(ctx, fmt, made, encodes, sig_rate=22050, sig_frames=3000):
|
||||
"maxDiff": max_diff(sig, dec) if dch == ch else 99.0, "ffmpegErrors": errs.decode(errors="replace"),
|
||||
"bytes": len(out), "sameStreamed": out == streamed, "data": out})
|
||||
ctx.emit(fmt + "_enc", results)
|
||||
|
||||
|
||||
def encode_luau_many(ctx, module, jobs, sigmod):
|
||||
"""jobs = [(signal name, opts_lua)] over the emitted module sigmod = { [name] = { rate, channels, frames, data } }
|
||||
-> [bytes]: one Luau run encodes them all (length-prefixed on stdout)"""
|
||||
body = ['job("%s", %s)' % (name, opts) for name, opts in jobs]
|
||||
code = """
|
||||
local Types = require("@formats/Types")
|
||||
local M = require("@formats/%s")
|
||||
local S = require("@tests/gen/%s")
|
||||
local outs = {}
|
||||
local function job(name, opts)
|
||||
local s = S[name]
|
||||
local a = Types.Audio.new(s.rate, s.channels, s.frames)
|
||||
buffer.writestring(a.samples, 0, s.data)
|
||||
local out, err = M.encode(a, opts)
|
||||
if not out then error("encode failed: " .. tostring(err)) end
|
||||
local n = buffer.len(out)
|
||||
table.insert(outs, string.format("%%012d", n) .. buffer.tostring(out))
|
||||
end
|
||||
%s
|
||||
print(table.concat(outs))
|
||||
""" % (module, sigmod, "\n".join(body))
|
||||
raw = luau(ctx, code)
|
||||
res, p = [], 0
|
||||
while p < len(raw):
|
||||
n = int(raw[p:p + 12])
|
||||
res.append(raw[p + 12:p + 12 + n])
|
||||
p += 12 + n
|
||||
return res
|
||||
|
||||
|
||||
def shell_many(ctx, packages, files, script):
|
||||
"""write files {name: bytes} into a temp dir and run `sh -c script` there under nix; returns stdout"""
|
||||
d = tempfile.mkdtemp(prefix="fmt-audio-")
|
||||
try:
|
||||
for name, data in files.items():
|
||||
with open(os.path.join(d, name), "wb") as f:
|
||||
f.write(data)
|
||||
return ctx.nix(packages, ["sh", "-c", "cd '%s' && %s" % (d, script)])
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
@@ -0,0 +1,89 @@
|
||||
# FLAC encoder fixtures (tools/fixtures.py): our encoder runs in the fixture step (tools/fixtures/_audio.py
|
||||
# encode_luau_many) on test signals; every output must pass `flac -t` (which also checks the decoded PCM against the
|
||||
# STREAMINFO MD5), and that MD5 must equal the MD5 of the input quantized here, so the stream is bit-exact. The level
|
||||
# sweep is compared in size with `flac -<level>` (libFLAC 1.5, --no-padding --no-seektable).
|
||||
# tests/gen/flac_enc.luau { name, sig, opts, bits, channels, frames, flacTest, md5, wantMd5, size, refSize?, data }
|
||||
# tests/gen/flac_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } }: the inputs
|
||||
import hashlib, importlib.util, os
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py"))
|
||||
A = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(A)
|
||||
|
||||
INPUTS = ["src/Formats/audio/flac", "src/Formats/codecs/Pcm", "src/Formats/core/Md5.luau"]
|
||||
|
||||
|
||||
def pcm_bytes(samples, bits):
|
||||
s = 2 ** (bits - 1)
|
||||
nb = (bits + 7) // 8
|
||||
out = bytearray()
|
||||
for v in samples:
|
||||
q = max(-s, min(s - 1, int(__import__("math").floor(v * s + 0.5))))
|
||||
out += (q & ((1 << (8 * nb)) - 1)).to_bytes(nb, "little")
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
sigs = {}
|
||||
|
||||
def sig(kind, ch, frames, rate=44100):
|
||||
name = "flacsig_%s_%d_%d_%d" % (kind, ch, frames, rate)
|
||||
if name not in sigs:
|
||||
samples = A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=frames + ch))) # f32-rounded
|
||||
sigs[name] = (samples, rate, ch)
|
||||
return name
|
||||
|
||||
cases = [] # (name, sigmod, bits, opts_lua, ref_level)
|
||||
for level in range(9):
|
||||
cases.append(("L%d-music-st16" % level, sig("music", 2, 20000), 16, "{ level = %d, bits = 16 }" % level, level))
|
||||
cases.append(("L%d-noise-mono24" % level, sig("noise", 1, 9000), 24, "{ level = %d, bits = 24 }" % level, level))
|
||||
cases.append(("L%d-sweep-6ch8" % level, sig("sweep", 6, 5000, 48000), 8, "{ level = %d, bits = 8 }" % level, level))
|
||||
for kind in ("sine", "silence", "loud", "square"):
|
||||
for ch in (1, 2):
|
||||
for bits in (8, 16, 24):
|
||||
cases.append(("%s-%dch-%d" % (kind, ch, bits), sig(kind, ch, 4500), bits, "{ bits = %d }" % bits, None))
|
||||
for level in (0, 5, 8):
|
||||
for n in (1, 15, 100, 1153, 4097):
|
||||
cases.append(("L%d-len%d" % (level, n), sig("music", 2, n), 16, "{ level = %d }" % level, None))
|
||||
for bs in (192, 576, 1000, 4608, 16):
|
||||
cases.append(("bs%d" % bs, sig("music", 2, 7000), 16, "{ blockSize = %d }" % bs, None))
|
||||
cases.append(("bits12-22k", sig("music", 1, 6000, 22050), 12, "{ bits = 12 }", None))
|
||||
cases.append(("bits20-96k", sig("sweep", 2, 6000, 96000), 20, "{ bits = 20, level = 8 }", None))
|
||||
cases.append(("rate-11111", sig("sine", 2, 3000, 11111), 16, "nil", None))
|
||||
cases.append(("seek-1s", sig("music", 2, 30000), 16, "{ seekInterval = 0.25 }", None))
|
||||
cases.append(("padding", sig("sine", 1, 1000), 16, "{ padding = 100 }", None))
|
||||
|
||||
ctx.emit("flac_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()})
|
||||
outs = A.encode_luau_many(ctx, "audio/flac", [(c[1], c[3]) for c in cases], "flac_enc_sigs")
|
||||
files = {"c%03d.flac" % i: o for i, o in enumerate(outs)}
|
||||
script = 'for f in c*.flac; do r=$(flac -s -t "$f" 2>&1); echo "$f|$?|$(metaflac --show-md5sum "$f")|$(echo $r | tr "\\n" " ")"; done'
|
||||
report = A.shell_many(ctx, "flac", files, script).decode(errors="replace")
|
||||
rows = {}
|
||||
for line in report.strip().split("\n"):
|
||||
f, rc, md5, msg = line.split("|", 3)
|
||||
rows[f] = (int(rc), md5.strip(), msg.strip())
|
||||
# libFLAC reference sizes for the level sweep
|
||||
refs = {}
|
||||
wavs = {}
|
||||
for i, c in enumerate(cases):
|
||||
if c[4] is not None:
|
||||
samples, rate, ch = sigs[c[1]]
|
||||
wavs["r%03d.raw" % i] = pcm_bytes(samples, c[2])
|
||||
wavs["r%03d.arg" % i] = ("-%d --channels=%d --bps=%d --sample-rate=%d" % (c[4], ch, c[2], rate)).encode()
|
||||
script = ('for i in r*.raw; do rm -f out.flac; flac -s $(cat "${i%.raw}.arg") --force-raw-format --endian=little --sign=signed '
|
||||
'--no-padding --no-seektable -f -o out.flac "$i"; echo "$i $(stat -c %s out.flac)"; done')
|
||||
for line in A.shell_many(ctx, "flac", wavs, script).decode().strip().split("\n"):
|
||||
f, size = line.split()
|
||||
refs[int(f[1:4])] = int(size)
|
||||
emitted = []
|
||||
for i, (name, sigmod, bits, opts, lvl) in enumerate(cases):
|
||||
samples, rate, ch = sigs[sigmod]
|
||||
rc, md5, msg = rows["c%03d.flac" % i]
|
||||
want = hashlib.md5(pcm_bytes(samples, bits)).hexdigest()
|
||||
e = {"name": name, "sig": sigmod, "opts": opts, "bits": bits, "channels": ch, "frames": len(samples) // ch,
|
||||
"flacTest": "" if rc == 0 else (msg or "rc %d" % rc), "md5": md5, "wantMd5": want, "size": len(outs[i]),
|
||||
"data": outs[i]}
|
||||
if i in refs:
|
||||
e["refSize"] = refs[i]
|
||||
emitted.append(e)
|
||||
ctx.emit("flac_enc", emitted)
|
||||
Reference in new issue
Block a user