diff --git a/docs/FORMATS.md b/docs/FORMATS.md index d17d956..c68c2af 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -17,6 +17,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` | | image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` | | audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.luau` | +| audio | ac3 | .ac3 .a52 | yes | - | codecs: "ac3", channels: 6, streaming: true, lossy: true | `tests/audio/ac3.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 | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 2b94be5..9450fdd 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -158,6 +158,18 @@ local list: { Entry } = { return require("@formats/audio/aac") end, }, + { + name = "ac3", + category = "audio", + path = "audio/ac3", + extensions = { "ac3", "a52" }, + mime = { "audio/ac3", "audio/x-ac3" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, + caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, + load = function() + return require("@formats/audio/ac3") + end, + }, { name = "aiff", category = "audio", diff --git a/src/Formats/audio/ac3/init.luau b/src/Formats/audio/ac3/init.luau new file mode 100644 index 0000000..4f69ea9 --- /dev/null +++ b/src/Formats/audio/ac3/init.luau @@ -0,0 +1,146 @@ +--!strict +-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) elementary streams, the .ac3 files of DVD / broadcast rips, through +-- codecs/audio/Ac3 (written from the A/52 specification). Supports: every channel layout (1+1, 1/0 .. 3/2, LFE) +-- output in WAVE order without downmixing, 32 / 44.1 / 48 kHz, every bit rate, coupling, rematrixing, block +-- switching, delta bit allocation, the CRC check, resync over garbage, a truncated last frame (dropped), streaming and +-- exact seeking (one frame of pre-roll for the overlap). Dynamic range control is off by default (`drc` = 0 .. 1). +-- Not supported: writing, E-AC-3 / Dolby Digital Plus (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Stream = require("@formats/codecs/audio/Stream") +local Ac3 = require("@formats/codecs/audio/Ac3") + +-- ------------------------------------------------------------------------------------------------ contract +local Ac3Format = { + name = "ac3", + category = "audio", + extensions = { "ac3", "a52" }, + mime = { "audio/ac3", "audio/x-ac3" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, + caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFrames: number?, -- refuse streams with more syncframes (default 2^22) + drc: number?, -- dynamic range control scale: 0 = off (default), 1 = full + crc: boolean?, -- check every syncframe's CRC (default true; a bad frame ends the stream with Err.CHECKSUM) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ac3Format.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + local h = Ac3.header(b, p, limit) + if not h or h.bsid > 10 then + return 0 + end + local h2 = Ac3.header(b, p + h.frameSize, limit) + if h2 and h2.sampleRate == h.sampleRate then + return 0.9 + end + return if p + h.frameSize >= limit then 0.6 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the syncframe index (resyncing over garbage: a header counts when the next one follows it, or the data ends) +local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Ac3.Header?, Err.Err?) + local b, limit = r.buf, r.limit + local p = r.base + local offs, sizes = {}, {} + local first: Ac3.Header? = nil + while p + 8 <= limit do + local h = Ac3.header(b, p, limit) + if h and first and (h.sampleRate ~= first.sampleRate or h.bsid > 10) then + h = nil + end + if h and not first and p + h.frameSize + 8 <= limit then + local h2 = Ac3.header(b, p + h.frameSize, limit) + if not h2 then + h = nil -- a false sync word + end + end + if not h then + p += 1 + continue + end + if not first then + first = h + if h.bsid > 10 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "E-AC-3 (Dolby Digital Plus)", p) + elseif h.bsid > 8 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "reduced sample rate AC-3 (bsid " .. h.bsid .. ")", p) + end + end + if p + h.frameSize > limit then + break -- a truncated last frame + end + table.insert(offs, p) + table.insert(sizes, h.frameSize) + if #offs > maxFrames then + return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") + end + p += h.frameSize + end + return offs, sizes, first, nil +end + +function Ac3Format.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) + if ierr then + return nil, ierr + end + if not first or #offs == 0 then + return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", r.base) + end + local h = first :: Ac3.Header + local d = Ac3.decoder({ drc = o.drc, crc = o.crc }) + local buf = r.buf + local n = #offs + local out = { + sampleRate = h.sampleRate, + channels = h.channels, + frames = n * 1536, + duration = n * 1536 / h.sampleRate, + bitrate = h.bitrate, + tags = {}, + codec = "ac3", + acmod = h.acmod, + lfe = h.lfeon, + } + return Stream.packets(out, { + count = n, + start = function(i: number): number + return (i - 1) * 1536 + end, + decode = function(i: number): (number?, Err.Err?) + local frames, err = d:decode(buf, offs[i], sizes[i]) + if frames and d.channels ~= h.channels then + return nil, Err.new(Err.UNSUPPORTED, "channel layout change inside the stream", offs[i]) + end + return frames, err + end, + pcm = function(): { number } + return d.pcm + end, + reset = function() + d:reset() + end, + preroll = 1, + }) +end + +function Ac3Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Ac3Format.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "ac3", codec = "ac3", acmod = d.acmod, lfe = d.lfe, bitrate = d.bitrate }) +end + +return Ac3Format diff --git a/src/Formats/codecs/audio/Ac3/Decode.luau b/src/Formats/codecs/audio/Ac3/Decode.luau new file mode 100644 index 0000000..830de4a --- /dev/null +++ b/src/Formats/codecs/audio/Ac3/Decode.luau @@ -0,0 +1,916 @@ +--!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". +local T = require("@formats/codecs/audio/Ac3/Tables") +local Mdct = require("@formats/codecs/audio/Mdct") + +local readu32, bswap, extract, band, rshift = buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.rshift +local max, min = math.max, math.min + +local Decode = {} +Decode.PAD = 2048 + +local CPL, LFE = 7, 6 -- channel slots: 1 .. 5 full bandwidth, 6 LFE, 7 the coupling channel +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 +end +-- symmetric quantiser values (Tables 7.19 - 7.23): Q1[code + 1] etc. +local function levels(n: number): { number } + local t = {} + for c = 0, n - 1 do + t[c + 1] = (2 * c - (n - 1)) / n + end + return t +end +local Q1, Q2, Q3, Q4, Q5 = levels(3), levels(5), levels(7), levels(11), levels(15) +-- bits of the asymmetric quantisers (bap 6 .. 15) +local QBITS = { [6] = 5, [7] = 6, [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 14, [15] = 16 } + +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 + +local function bits(n: number): number + if n <= 0 then + return 0 + end + if n > 24 then + local hi = bits(n - 16) + return hi * 65536 + bits(16) + end + local w = bswap(readu32(B, rshift(P, 3))) + local v = extract(w, 32 - band(P, 7) - n, n) + P += n + 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) + exp: { { number } }, + bap: { { number } }, + coef: { { number } }, + delay: { { number } }, + endmant: { number }, + chexpstr: { number }, + blksw: { boolean }, + dithflag: { boolean }, + fsnroffst: { number }, + fgaincod: { number }, + dbaOn: { boolean }, + 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] + cplfleak: number, + cplsleak: number, + rematflg: { boolean }, + -- bit allocation parameters + sdcycod: number, + fdcycod: number, + sgaincod: number, + dbpbcod: number, + floorcod: number, + csnroffst: number, + dynrng: { number }, -- gain for Ch1 / Ch2 + seed: number, -- dither generator + -- scratch + 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) +} + +local function arrays(n: number, size: number, v: any): { any } + local t = {} + for i = 1, n do + t[i] = table.create(size, v) + end + return t +end + +function Decode.state(): State + return { + fscod = 0, + acmod = 2, + lfeon = false, + nfchans = 2, + channels = 2, + map = { 1, 2, 3, 4, 5, 6 }, + drc = 0, + exp = arrays(7, 264, 0), + bap = arrays(7, 264, 0), + coef = arrays(7, 256, 0), + delay = arrays(6, 256, 0), + endmant = table.create(7, 0), + chexpstr = table.create(7, 0), + blksw = table.create(7, false), + dithflag = table.create(7, false), + fsnroffst = table.create(7, 0), + fgaincod = table.create(7, 0), + dbaOn = table.create(7, false), + dbaOffst = arrays(7, 8, 0), + dbaLen = arrays(7, 8, 0), + dbaBa = arrays(7, 8, 0), + cplinu = false, + chincpl = table.create(7, false), + phsflginu = false, + cplbegf = 0, + cplendf = 0, + cplbndstrc = table.create(18, false), + cplco = arrays(5, 18, 0), + phsflg = table.create(18, false), + cplfleak = 0, + cplsleak = 0, + rematflg = table.create(4, false), + sdcycod = 0, + fdcycod = 0, + sgaincod = 0, + dbpbcod = 0, + floorcod = 0, + csnroffst = 0, + dynrng = { 1, 1 }, + seed = 1, + psd = table.create(256, 0), + bndpsd = table.create(50, 0), + excite = table.create(50, 0), + mask = table.create(50, 0), + y = table.create(512, 0), + pcm = table.create(1536 * 2, 0), + blocks = table.create(6, 0), + } +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 + d[i] = 0 + end + 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 +local function exponents(e: { number }, absexp: number, ngrps: number, grpsize: number, first: number): boolean + local prev = absexp + local k = first + 1 + for _ = 1, ngrps do + local g = bits(7) + if g >= 125 then + return false + end + local d1 = g // 25 + local d2 = (g % 25) // 5 + local d3 = g % 5 + for m = 1, 3 do + local d = if m == 1 then d1 elseif m == 2 then d2 else d3 + prev += d - 2 + if prev < 0 or prev > 24 then + return false + end + for _ = 1, grpsize do + e[k] = prev + k += 1 + end + end + end + 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) + return if c >= 0 then a + LATAB[adr + 1] else b + LATAB[adr + 1] +end + +local function lowcomp(a: number, b0: number, b1: number, bin: number): number + if bin < 7 then + if b0 + 256 == b1 then + a = 384 + elseif b0 > b1 then + a = max(0, a - 64) + end + elseif bin < 20 then + if b0 + 256 == b1 then + a = 320 + elseif b0 > b1 then + a = max(0, a - 64) + end + else + a = max(0, a - 128) + end + return a +end + +-- section 7.2.2: the bap of bins [start, stop) of channel slot ch +local function allocate(st: State, ch: number, start: number, stop: number, fgain: number, snroffset: number, isLfe: boolean) + local e, bap = st.exp[ch], st.bap[ch] + local psd, bndpsd, excite, mask = st.psd, st.bndpsd, st.excite, st.mask + local sdecay, fdecay = SLOWDEC[st.sdcycod + 1], FASTDEC[st.fdcycod + 1] + local sgain, dbknee, floor = SLOWGAIN[st.sgaincod + 1], DBPBTAB[st.dbpbcod + 1], FLOORTAB[st.floorcod + 1] + if floor >= 0x8000 then + floor -= 0x10000 -- 0xf800: a negative 16-bit value + end + for bin = start, stop - 1 do + psd[bin + 1] = 3072 - e[bin + 1] * 128 + end + -- PSD integration + local j = start + local k = MASKTAB[start + 1] + local lastbin + repeat + lastbin = min(BNDTAB[k + 1] + BNDSZ[k + 1], stop) + local v = psd[j + 1] + j += 1 + while j < lastbin do + v = logadd(v, psd[j + 1]) + j += 1 + end + bndpsd[k + 1] = v + k += 1 + until stop <= lastbin + -- excitation + local bndstrt = MASKTAB[start + 1] + local bndend = MASKTAB[stop] + 1 + local fastleak, slowleak = 0, 0 + local begin + if bndstrt == 0 then + local lc = 0 + lc = lowcomp(lc, bndpsd[1], bndpsd[2], 0) + excite[1] = bndpsd[1] - fgain - lc + lc = lowcomp(lc, bndpsd[2], bndpsd[3], 1) + excite[2] = bndpsd[2] - fgain - lc + begin = 7 + for bin = 2, 6 do + local last = isLfe and bin == 6 + if not last then + lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) + end + fastleak = bndpsd[bin + 1] - fgain + slowleak = bndpsd[bin + 1] - sgain + excite[bin + 1] = fastleak - lc + if not last and bndpsd[bin + 1] <= bndpsd[bin + 2] then + begin = bin + 1 + break + end + end + for bin = begin, min(bndend, 22) - 1 do + if not (isLfe and bin == 6) then + lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) + end + fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) + slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) + excite[bin + 1] = max(fastleak - lc, slowleak) + end + begin = 22 + else + begin = bndstrt + fastleak = st.cplfleak * 256 + 768 + slowleak = st.cplsleak * 256 + 768 + end + for bin = begin, bndend - 1 do + fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) + slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) + excite[bin + 1] = max(fastleak, slowleak) + end + -- masking curve + local hth = HTH[st.fscod + 1] + for bin = bndstrt, bndend - 1 do + local x = excite[bin + 1] + local p = bndpsd[bin + 1] + if p < dbknee then + x += (dbknee - p) // 4 + end + mask[bin + 1] = max(x, hth[bin + 1]) + end + -- delta bit allocation + if st.dbaOn[ch] then + local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] + local b = 0 + for seg = 1, #offs do + b += offs[seg] + local ba = bas[seg] + local delta = if ba >= 4 then (ba - 3) * 128 else (ba - 4) * 128 + for _ = 1, lens[seg] do + if b < 50 then + mask[b + 1] += delta + end + b += 1 + end + end + end + -- bit allocation pointers + local i = start + j = MASKTAB[start + 1] + repeat + lastbin = min(BNDTAB[j + 1] + BNDSZ[j + 1], stop) + local m = mask[j + 1] - snroffset - floor + if m < 0 then + m = 0 + end + m = band(m, 0x1fe0) + floor + while i < lastbin do + local adr = (psd[i + 1] - m) // 32 + bap[i + 1] = BAPTAB[min(63, max(0, adr)) + 1] + i += 1 + end + j += 1 + 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 + +local function dither(st: State): number + local s = (st.seed * 1664525 + 1013904223) % 4294967296 + st.seed = s + 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 + local b = bap[bin + 1] + local v + if b == 0 then + v = if dith then dither(st) else 0 + elseif b == 1 then + if n1 == 0 then + local g = bits(5) + if g > 26 then + g = 26 + end + G1[1], G1[2], G1[3] = Q1[g // 9 + 1], Q1[(g % 9) // 3 + 1], Q1[g % 3 + 1] + n1 = 3 + end + v = G1[4 - n1] + n1 -= 1 + elseif b == 2 then + if n2 == 0 then + local g = bits(7) + if g > 124 then + g = 124 + end + G2[1], G2[2], G2[3] = Q2[g // 25 + 1], Q2[(g % 25) // 5 + 1], Q2[g % 5 + 1] + n2 = 3 + end + v = G2[4 - n2] + n2 -= 1 + elseif b == 3 then + v = Q3[min(bits(3), 6) + 1] + elseif b == 4 then + if n4 == 0 then + local g = bits(7) + if g > 120 then + g = 120 + end + G4[1], G4[2] = Q4[g // 11 + 1], Q4[g % 11 + 1] + n4 = 2 + end + v = G4[3 - n4] + n4 -= 1 + elseif b == 5 then + v = Q5[min(bits(4), 14) + 1] + else + local nb = QBITS[b] + local m = bits(nb) + local half = 2 ^ (nb - 1) + if m >= half then + m -= 2 * half + end + v = m / half + end + out[bin + 1] = v * POW2[e[bin + 1] + 1] + 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] + table.clear(offs) + table.clear(lens) + table.clear(bas) + for seg = 1, nseg do + offs[seg] = bits(5) + lens[seg] = bits(4) + bas[seg] = bits(3) + end +end + +local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D25 / D45) + +local function audblk(st: State, blk: number, limit: number): (boolean?, string?) + local nf, acmod = st.nfchans, st.acmod + for ch = 1, nf do + st.blksw[ch] = bits(1) == 1 + end + for ch = 1, nf do + st.dithflag[ch] = bits(1) == 1 + end + for i = 1, if acmod == 0 then 2 else 1 do + if bits(1) == 1 then + local v = bits(8) + local x = rshift(v, 5) + if x >= 4 then + x -= 8 + end + local g = 2 ^ (x + 1) * (32 + band(v, 31)) / 64 + st.dynrng[i] = if st.drc == 1 then g else g ^ st.drc + elseif blk == 0 then + st.dynrng[i] = 1 + end + end + -- coupling strategy + if bits(1) == 1 then + st.cplinu = bits(1) == 1 + if st.cplinu then + if acmod < 2 then + return nil, "coupling in a mono / dual mono stream" + end + for ch = 1, nf do + st.chincpl[ch] = bits(1) == 1 + end + st.phsflginu = if acmod == 2 then bits(1) == 1 else false + st.cplbegf = bits(4) + st.cplendf = bits(4) + if st.cplendf + 3 <= st.cplbegf then + return nil, "bad coupling range" + end + st.cplbndstrc[st.cplbegf + 1] = false + for sbnd = st.cplbegf + 1, st.cplendf + 2 do + st.cplbndstrc[sbnd + 1] = bits(1) == 1 + end + else + for ch = 1, nf do + st.chincpl[ch] = false + end + st.phsflginu = false + end + elseif blk == 0 then + return nil, "no coupling strategy in block 0" + end + local cplinu = st.cplinu + local cplbegf, cplendf = st.cplbegf, st.cplendf + local cplstrt = 37 + 12 * cplbegf + local cplend = 37 + 12 * (cplendf + 3) + -- coupling coordinates (per sub-band, duplicated over each coupling band) + if cplinu then + local anyNew = false + for ch = 1, nf do + if st.chincpl[ch] then + if bits(1) == 1 then + anyNew = true + local mstr = bits(2) * 3 + local co = st.cplco[ch] + local v = 0 + for sbnd = cplbegf, cplendf + 2 do + if not st.cplbndstrc[sbnd + 1] then + local ex, mant = bits(4), bits(4) + local m = if ex == 15 then mant / 16 else (mant + 16) / 32 + v = m * 2 ^ -(ex + mstr) + end + co[sbnd + 1] = v + end + end + end + end + if acmod == 2 and st.phsflginu and anyNew then + local f = false + for sbnd = cplbegf, cplendf + 2 do + if not st.cplbndstrc[sbnd + 1] then + f = bits(1) == 1 + end + st.phsflg[sbnd + 1] = f + 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 + for r = 1, 4 do + st.rematflg[r] = if r <= n then bits(1) == 1 else false + end + elseif blk == 0 then + for r = 1, 4 do + st.rematflg[r] = false + end + end + end + -- exponent strategies + local chexpstr = st.chexpstr + chexpstr[CPL] = if cplinu then bits(2) else 0 + for ch = 1, nf do + chexpstr[ch] = bits(2) + end + chexpstr[LFE] = if st.lfeon then bits(1) else 0 + if blk == 0 then + for ch = 1, nf do + if chexpstr[ch] == 0 then + return nil, "exponent reuse in block 0" + end + end + if (cplinu and chexpstr[CPL] == 0) or (st.lfeon and chexpstr[LFE] == 0) then + return nil, "exponent reuse in block 0" + end + end + local endmant = st.endmant + for ch = 1, nf do + if chexpstr[ch] ~= 0 then + if st.chincpl[ch] then + endmant[ch] = cplstrt + else + local bw = bits(6) + if bw > 60 then + return nil, "bad channel bandwidth code" + end + endmant[ch] = 37 + 3 * (bw + 12) + end + end + end + endmant[LFE] = 7 + -- exponents + if cplinu and chexpstr[CPL] ~= 0 then + local abs = bits(4) * 2 + local grp = EXPGRP[chexpstr[CPL]] + if not exponents(st.exp[CPL], abs, (cplend - cplstrt) // grp, grp // 3, cplstrt) then + return nil, "bad coupling exponents" + end + end + for ch = 1, nf do + local s = chexpstr[ch] + if s ~= 0 then + local grp = EXPGRP[s] + local ngrps + if s == 1 then + ngrps = (endmant[ch] - 1) // 3 + elseif s == 2 then + ngrps = (endmant[ch] - 1 + 3) // 6 + else + ngrps = (endmant[ch] - 1 + 9) // 12 + end + local e = st.exp[ch] + e[1] = bits(4) + if not exponents(e, e[1], ngrps, grp // 3, 1) then + return nil, "bad exponents" + end + bits(2) -- gainrng + end + end + if st.lfeon and chexpstr[LFE] ~= 0 then + local e = st.exp[LFE] + e[1] = bits(4) + if not exponents(e, e[1], 2, 1, 1) then + return nil, "bad LFE exponents" + end + end + 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 + return nil, "no bit allocation parameters in block 0" + end + if bits(1) == 1 then + st.csnroffst = bits(6) + if cplinu then + st.fsnroffst[CPL], st.fgaincod[CPL] = bits(4), bits(3) + end + for ch = 1, nf do + st.fsnroffst[ch], st.fgaincod[ch] = bits(4), bits(3) + end + if st.lfeon then + st.fsnroffst[LFE], st.fgaincod[LFE] = bits(4), bits(3) + end + elseif blk == 0 then + return nil, "no SNR offsets in block 0" + end + if cplinu then + if bits(1) == 1 then + 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 + modes[CPL] = bits(2) + end + for ch = 1, nf do + modes[ch] = bits(2) + end + if cplinu and modes[CPL] == 1 then + readDba(st, CPL) + end + for ch = 1, nf do + if modes[ch] == 1 then + readDba(st, ch) + end + end + for _, ch in { 1, 2, 3, 4, 5, CPL } do + if modes[ch] == 1 then + st.dbaOn[ch] = true + elseif modes[ch] == 2 or modes[ch] == 3 then + st.dbaOn[ch] = false + end + end + elseif blk == 0 then + for ch = 1, 7 do + 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 + if st.fsnroffst[ch] ~= 0 then + zero = false + end + end + if (cplinu and st.fsnroffst[CPL] ~= 0) or (st.lfeon and st.fsnroffst[LFE] ~= 0) then + zero = false + end + end + local function alloc(ch: number, start: number, stop: number, isLfe: boolean) + if zero then + for i = start + 1, stop do + st.bap[ch][i] = 0 + end + else + local snr = ((st.csnroffst - 15) * 16 + st.fsnroffst[ch]) * 4 + allocate(st, ch, start, stop, FASTGAIN[st.fgaincod[ch] + 1], snr, isLfe) + end + end + if cplinu then + alloc(CPL, cplstrt, cplend, false) + end + for ch = 1, nf do + alloc(ch, 0, endmant[ch], false) + end + if st.lfeon then + alloc(LFE, 0, 7, true) + end + -- mantissas + n1, n2, n4 = 0, 0, 0 + local gotCpl = false + local coef = st.coef + for ch = 1, nf do + local c = coef[ch] + mantissas(st, ch, 0, endmant[ch], c, st.dithflag[ch]) + for i = endmant[ch] + 1, 256 do + c[i] = 0 + end + if cplinu and st.chincpl[ch] and not gotCpl then + mantissas(st, CPL, cplstrt, cplend, coef[CPL], false) + gotCpl = true + end + if P > limit then + return nil, "truncated block" + end + end + if st.lfeon then + local c = coef[LFE] + mantissas(st, LFE, 0, 7, c, false) + for i = 8, 256 do + c[i] = 0 + end + end + if P > limit then + return nil, "truncated block" + end + -- decoupling (section 7.4): dither the coupling channel's zero-bit mantissas per channel + if cplinu then + local cc, cbap, cexp = coef[CPL], st.bap[CPL], st.exp[CPL] + for ch = 1, nf do + if st.chincpl[ch] then + local c, co = coef[ch], st.cplco[ch] + local dith = st.dithflag[ch] + local flip = acmod == 2 and ch == 2 and st.phsflginu + for sbnd = cplbegf, cplendf + 2 do + local f = co[sbnd + 1] * 8 + if flip and st.phsflg[sbnd + 1] then + f = -f + end + for k = 37 + 12 * sbnd + 1, 37 + 12 * sbnd + 12 do + local v = cc[k] + if cbap[k] == 0 then + v = if dith then dither(st) * POW2[cexp[k] + 1] else 0 + end + c[k] = v * f + end + end + for k = cplend + 1, 256 do + c[k] = 0 + end + end + end + end + -- rematrixing (section 7.5) + if acmod == 2 then + local stop = if cplinu then cplstrt else min(endmant[1], endmant[2]) + local l, r = coef[1], coef[2] + local edges = { 13, 25, 37, 61, 253 } + for rb = 1, 4 do + if st.rematflg[rb] then + for k = edges[rb] + 1, min(edges[rb + 1], stop) do + local a, b = l[k], r[k] + l[k], r[k] = a + b, a - b + end + end + end + end + 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 + Mdct.inverse(PLAN256, x, 1, 2, z, 1, -2 * gain) + for n = 0, 63 do + y[n + 1] = -z[n + 193] + end + for n = 64, 255 do + y[n + 1] = z[n - 63] + end + Mdct.inverse(PLAN256, x, 2, 2, z, 1, -2 * gain) + for n = 0, 191 do + y[257 + n] = z[n + 65] + end + for n = 192, 255 do + y[257 + n] = -z[n - 191] + end + else + Mdct.inverse(PLAN512, x, 1, 1, y, 1, -2 * gain) + end + local p = base + for n = 1, 256 do + out[p] = y[n] * w[n] + d[n] + d[n] = y[n + 256] * w[n + 256] + p += step + 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 }, + { 1 }, + { 1, 2 }, + { 1, 3, 2 }, + { 1, 2, 3 }, + { 1, 3, 2, 4 }, + { 1, 2, 3, 4 }, + { 1, 3, 2, 4, 5 }, +} +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" + end + B, P = buf, 32 + local fscod = bits(2) + bits(6) + local bsid = bits(5) + if bsid > 8 then + B = buffer.create(0) + return nil, "unsupported: bsid " .. bsid .. (if bsid > 10 then " (E-AC-3)" else " (reduced sample rate)") + end + if fscod == 3 then + B = buffer.create(0) + return nil, "bad sample rate code" + end + bits(3) -- bsmod + local acmod = bits(3) + if band(acmod, 1) == 1 and acmod ~= 1 then + bits(2) + end + if band(acmod, 4) ~= 0 then + bits(2) + end + if acmod == 2 then + bits(2) + end + local lfeon = bits(1) == 1 + for _ = 1, if acmod == 0 then 2 else 1 do + bits(5) + if bits(1) == 1 then + bits(8) + end + if bits(1) == 1 then + bits(8) + end + if bits(1) == 1 then + bits(7) + end + end + bits(2) + if bits(1) == 1 then + bits(14) + end + if bits(1) == 1 then + bits(14) + end + if bits(1) == 1 then + P += (bits(6) + 1) * 8 + end + 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 + for ch = 1, nf do + local o = order[ch] + map[ch] = if lfeon and o > nfront then o + 1 else o + end + if lfeon then + map[LFE] = nfront + 1 + end + st.map = map + st.pcm = table.create(1536 * channels, 0) + Decode.reset(st) + end + st.fscod, st.acmod, st.lfeon, st.nfchans, st.channels, st.drc = fscod, acmod, lfeon, nf, channels, drc + local pcm = st.pcm + local limit = len * 8 - 16 -- crc2 + for blk = 0, 5 do + st.blocks[blk + 1] = P + local ok, err = audblk(st, blk, limit) + if not ok then + B = buffer.create(0) + return nil, err + end + local base = blk * 256 * channels + for ch = 1, nf do + local g = st.dynrng[if acmod == 0 and ch == 2 then 2 else 1] + synth(st, ch, st.blksw[ch], g, pcm, base + st.map[ch], channels) + end + if lfeon then + synth(st, LFE, false, st.dynrng[1], pcm, base + st.map[LFE], channels) + end + end + B = buffer.create(0) + return 1536, nil +end + +return Decode diff --git a/src/Formats/codecs/audio/Ac3/Tables.luau b/src/Formats/codecs/audio/Ac3/Tables.luau new file mode 100644 index 0000000..3eec9e3 --- /dev/null +++ b/src/Formats/codecs/audio/Ac3/Tables.luau @@ -0,0 +1,102 @@ +--!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. +local T = {} + +T.SLOWDEC = { 0x0f, 0x11, 0x13, 0x15 } +T.FASTDEC = { 0x3f, 0x53, 0x67, 0x7b } +T.SLOWGAIN = { 0x540, 0x4d8, 0x478, 0x410 } +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) +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, +} +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) +T.MASKTAB = table.create(256, 0) +for b = 1, 50 do + for k = T.BNDTAB[b], T.BNDTAB[b] + T.BNDSZ[b] - 1 do + T.MASKTAB[k + 1] = b - 1 + end +end + +-- log-addition table (Table 7.14) +T.LATAB = { + 0x0040, 0x003f, 0x003e, 0x003d, 0x003c, 0x003b, 0x003a, 0x0039, 0x0038, 0x0037, 0x0036, 0x0035, 0x0034, 0x0034, 0x0033, 0x0032, + 0x0031, 0x0030, 0x002f, 0x002f, 0x002e, 0x002d, 0x002c, 0x002c, 0x002b, 0x002a, 0x0029, 0x0029, 0x0028, 0x0027, 0x0026, 0x0026, + 0x0025, 0x0024, 0x0024, 0x0023, 0x0023, 0x0022, 0x0021, 0x0021, 0x0020, 0x0020, 0x001f, 0x001e, 0x001e, 0x001d, 0x001d, 0x001c, + 0x001c, 0x001b, 0x001b, 0x001a, 0x001a, 0x0019, 0x0019, 0x0018, 0x0018, 0x0017, 0x0017, 0x0016, 0x0016, 0x0015, 0x0015, 0x0015, + 0x0014, 0x0014, 0x0013, 0x0013, 0x0013, 0x0012, 0x0012, 0x0012, 0x0011, 0x0011, 0x0011, 0x0010, 0x0010, 0x0010, 0x000f, 0x000f, + 0x000f, 0x000e, 0x000e, 0x000e, 0x000d, 0x000d, 0x000d, 0x000d, 0x000c, 0x000c, 0x000c, 0x000c, 0x000b, 0x000b, 0x000b, 0x000b, + 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x0009, 0x0009, 0x0009, 0x0009, 0x0009, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, + 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0005, 0x0005, + 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, + 0x0004, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0002, + 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, + 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 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] +T.HTH = { + { + 0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, + 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0370, 0x0370, + 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, + 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, 0x0340, 0x0390, 0x03e0, 0x0420, + 0x0460, 0x0490, 0x04a0, 0x0460, 0x0440, 0x0440, 0x0520, 0x0800, 0x0840, 0x0840, + }, + { + 0x04f0, 0x04f0, 0x0460, 0x0410, 0x03e0, 0x03d0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, + 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, + 0x0370, 0x0370, 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0320, 0x0310, + 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0320, 0x0350, 0x0390, 0x03e0, + 0x0420, 0x0450, 0x04a0, 0x0490, 0x0460, 0x0440, 0x0480, 0x0630, 0x0840, 0x0840, + }, + { + 0x0580, 0x0580, 0x04b0, 0x0450, 0x0420, 0x03f0, 0x03e0, 0x03d0, 0x03c0, 0x03b0, + 0x03b0, 0x03b0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, + 0x0390, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, 0x0370, 0x0360, 0x0350, + 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, + 0x0330, 0x0350, 0x03c0, 0x0410, 0x0470, 0x04a0, 0x0460, 0x0440, 0x0450, 0x04e0, + }, +} + +-- bit allocation pointers (Table 7.16) +T.BAPTAB = { + 0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, + 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, +} + +-- words per syncframe (Table 5.18) for frmsizecod // 2 (the nominal bit rate in kbps) and fscod: 48 kHz = 2 x rate, +-- 32 kHz = 3 x rate, 44.1 kHz = floor(rate x 1536000 / 705600) + (frmsizecod & 1) +T.BITRATES = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640 } +T.RATES = { 48000, 44100, 32000 } + +function T.frameWords(fscod: number, frmsizecod: number): number + local kbps = T.BITRATES[frmsizecod // 2 + 1] + if not kbps or fscod > 2 then + return 0 + end + if fscod == 0 then + return 2 * kbps + elseif fscod == 2 then + return 3 * kbps + end + return kbps * 1536000 // 705600 + frmsizecod % 2 +end + +return T diff --git a/src/Formats/codecs/audio/Ac3/init.luau b/src/Formats/codecs/audio/Ac3/init.luau new file mode 100644 index 0000000..16bf136 --- /dev/null +++ b/src/Formats/codecs/audio/Ac3/init.luau @@ -0,0 +1,172 @@ +--!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. +local Err = require("@formats/core/Err") +local T = require("@formats/codecs/audio/Ac3/Tables") +local Decode = require("@formats/codecs/audio/Ac3/Decode") + +local Ac3 = {} + +local readu8 = buffer.readu8 +local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } + +export type Header = { + sampleRate: number, + frameSize: number, -- bytes + bitrate: number, -- bits per second + 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 + end + if readu8(b, o) ~= 0x0B or readu8(b, o + 1) ~= 0x77 then + return nil + end + local bsid = bit32.rshift(readu8(b, o + 5), 3) + if bsid > 10 then + if bsid > 16 then + return nil + end + -- E-AC-3: strmtyp(2) substreamid(3) frmsiz(11) fscod(2) ... + local words = bit32.band(readu8(b, o + 2), 7) * 256 + readu8(b, o + 3) + 1 + local fs = bit32.rshift(readu8(b, o + 4), 6) + return { + sampleRate = if fs < 3 then T.RATES[fs + 1] else 0, + frameSize = words * 2, + bitrate = 0, + channels = 0, + acmod = bit32.band(bit32.rshift(readu8(b, o + 4), 1), 7), + lfeon = false, + bsid = bsid, + } + end + local b4 = readu8(b, o + 4) + local fscod, frmsizecod = bit32.rshift(b4, 6), bit32.band(b4, 63) + local words = T.frameWords(fscod, frmsizecod) + if words == 0 then + return nil + end + local acmod = bit32.rshift(readu8(b, o + 6), 5) + -- lfeon: after acmod and the optional cmixlev / surmixlev / dsurmod fields + local skip = 0 + if bit32.band(acmod, 1) == 1 and acmod ~= 1 then + skip += 2 + end + if bit32.band(acmod, 4) ~= 0 then + skip += 2 + end + if acmod == 2 then + skip += 2 + end + local w = readu8(b, o + 6) * 256 + readu8(b, o + 7) + local lfeon = bit32.extract(w, 12 - skip, 1) == 1 + local shift = if bsid > 8 then bsid - 8 else 0 + return { + sampleRate = T.RATES[fscod + 1] // 2 ^ shift, + frameSize = words * 2, + bitrate = T.BITRATES[frmsizecod // 2 + 1] * 1000 // 2 ^ shift, + channels = NFCHANS[acmod] + (if lfeon then 1 else 0), + acmod = acmod, + lfeon = lfeon, + bsid = bsid, + } +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 +local CRC = table.create(256, 0) +for i = 0, 255 do + local c = i * 256 + for _ = 1, 8 do + c = if c >= 0x8000 then bit32.bxor(bit32.band(c * 2, 0xFFFF), 0x8005) else c * 2 + end + CRC[i + 1] = c +end + +function Ac3.crc(b: buffer, o: number, n: number): number + local c = 0 + for i = o, o + n - 1 do + c = bit32.bxor(bit32.band(c * 256, 0xFFFF), CRC[bit32.bxor(bit32.rshift(c, 8), readu8(b, i)) + 1]) + end + 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 +} + +export type Decoder = { + pcm: { number }, -- the last frame: 1536 * channels interleaved floats, WAVE order + channels: number, + sampleRate: number, + blocks: { number }, -- the bit offset of each audio block in the last frame (tools: stream editing, analysis) + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + reset: (self: Decoder) -> (), +} + +function Ac3.decoder(opts: Options?): Decoder + local o: Options = opts or {} + local drc = math.max(0, o.drc or 0) + local checkCrc = o.crc ~= false + local st = Decode.state() + local scratch = buffer.create(3840 + Decode.PAD) + local dec: Decoder + dec = { + pcm = st.pcm, + channels = 0, + sampleRate = 0, + blocks = st.blocks, + decode = function(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local off = offset or 0 + if type(buf) ~= "buffer" or off < 0 or off >= buffer.len(buf) then + return nil, Err.new(Err.ARG, "frame range out of the buffer") + end + local h = Ac3.header(buf, off, buffer.len(buf)) + if not h then + return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", off) + end + local n = h.frameSize + if length and length < n or off + n > buffer.len(buf) then + return nil, Err.new(Err.TRUNCATED, "truncated syncframe", off) + end + if checkCrc and Ac3.crc(buf, off + 2, n - 2) ~= 0 then + return nil, Err.new(Err.CHECKSUM, "syncframe CRC", off) + end + buffer.copy(scratch, 0, buf, off, n) + local frames, msg = Decode.frame(st, scratch, n, drc) + if not frames then + return nil, Err.from(msg, off) + end + self.pcm = st.pcm + self.channels = st.channels + self.sampleRate = h.sampleRate + return frames, nil + end, + reset = function(_self: Decoder) + Decode.reset(st) + end, + } + return dec +end + +return Ac3 diff --git a/src/Formats/containers/AudioWrap.luau b/src/Formats/containers/AudioWrap.luau index ac51aee..4a0f3da 100644 --- a/src/Formats/containers/AudioWrap.luau +++ b/src/Formats/containers/AudioWrap.luau @@ -8,7 +8,8 @@ -- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames; -- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations); -- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout); --- aac -> ADTS (from the AudioSpecificConfig) for audio/aac. +-- aac -> ADTS (from the AudioSpecificConfig) for audio/aac; +-- ac3 -> the syncframes back to back (format "ac3"; E-AC-3 tracks stay UNSUPPORTED). -- -- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format }) local Err = require("@formats/core/Err") @@ -407,6 +408,9 @@ function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Er if codec == "mp3" or codec == "mp2" or codec == "mp1" then return concat(packets), "mp3", nil end + if codec == "ac3" then + return concat(packets), "ac3", nil + end if codec == "flac" then local c = track.config local prefix: buffer? = nil diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 5774bf3..927a7d4 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -278,7 +278,7 @@ end -- -- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets -- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / --- FLAC as they are), opened through F.open with that format. +-- FLAC / AC-3 as they are), opened through F.open with that format. local function openAudio(demuxer: any, track: any): (any, Err.Err?) local buf, fmt, err = AudioWrap.wrap(demuxer, track) if not buf then diff --git a/tests/audio/ac3.luau b/tests/audio/ac3.luau new file mode 100644 index 0000000..6f00ebd --- /dev/null +++ b/tests/audio/ac3.luau @@ -0,0 +1,153 @@ +-- audio/ac3 tests: AC-3 streams from ffmpeg (every acmod with and without LFE, coupling incl. cplbegf 0, rematrixing, +-- 32 / 44.1 / 48 kHz) and aften (block switching, 1+1 dual mono, dynamic range profiles, the alternate BSI) against +-- ffmpeg's float decode, or liba52's for block-switched streams (SNR, max difference; dithflags cleared in the +-- fixture step so both sides decode the same numbers); dynamic range on; the encoders' dithered originals; AC-3 tracks +-- of MKV / MP4 / MPEG-TS through the api's audio hook; exact seeking; resync and truncation; error codes (E-AC-3, +-- CRC); the fuzz no-throw pass. Fixtures: tools/fixtures/ac3.py. +local T = require("@tests/T") +local F = require("@formats") +local Ac3F = require("@formats/audio/ac3") +local Ac3 = require("@formats/codecs/audio/Ac3") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/ac3_cases") +local Tracks = require("@tests/gen/ac3_tracks") + +local t = T.suite("ac3") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- SNR (dB) and the largest difference of interleaved f32 `got` against the f32le reference `ref` +local function compare(got: buffer, ref: string, count: number): (number, number) + local rb = buffer.fromstring(ref) + local n = math.min(count, #ref // 4, buffer.len(got) // 4) + local sig, err, maxd = 0, 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(got, i * 4) - r + sig += r * r + err += d * d + maxd = math.max(maxd, math.abs(d)) + end + return if err == 0 then math.huge else 10 * math.log10(sig / err), maxd +end + +t:eq(Ac3F.name, "ac3", "name") +t:check(Ac3F.caps.decode and not Ac3F.caps.encode and Ac3F.encode == nil, "caps: decode only") + +local byName = {} +for _, c in Fx do + byName[c.name] = c + local r = reader(c.data) + t:check(Ac3F.sniff(r) >= 0.9, c.name .. ": sniff") + local a, err = Ac3F.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + if not a then + continue + end + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + -- liba52's 6-channel output is 16-bit + local min = if c.refTool == "a52dec" and c.channels > 2 then 80 else 95 + local s, maxd = compare(a.samples, c.ref, a.frames * a.channels) + t:check(s > min, string.format("%s: SNR %.1f dB vs %s", c.name, s, c.refTool)) + t:note("%s: %d ch %d Hz, %d frames: SNR %.1f dB, max diff %.1e vs %s", c.name, a.channels, a.sampleRate, a.frames, s, maxd, c.refTool) + if c.refDrc then + local d = Ac3F.decode(r, { drc = 1 }) :: any + local sd = compare(d.samples, c.refDrc, d.frames * d.channels) + t:check(sd > min, string.format("%s: dynamic range on: SNR %.1f dB vs %s", c.name, sd, c.refTool)) + local off = compare(d.samples, c.ref, d.frames * d.channels) + t:check(off < 40, c.name .. ": the dynamic range gains change the output") + end + if c.dithered then + -- the encoder's own stream (dithflag set): our dither against the reference's undithered decode + local dd = Ac3F.decode(reader(c.dithered)) :: any + local sd = compare(dd.samples, c.ref, dd.frames * dd.channels) + t:check(dd and sd > 10, string.format("%s: dithered original decodes (SNR %.1f dB, the dither noise)", c.name, sd)) + end +end + +-- AC-3 tracks of video containers, through the api's audio hook (containers/AudioWrap -> audio/ac3) +for _, c in Tracks do + local v, err = F.video.open(buffer.fromstring(c.data)) + t:check(v, c.name .. ": open: " .. tostring(err)) + if not v then + continue + end + t:check(v.audio, c.name .. ": audio track opens: " .. tostring(v.audioError)) + if v.audio then + local a = assert(F.ops.audio.toAudio(v.audio)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": audio format") + local s = compare(a.samples, c.ref, a.frames * a.channels) + t:check(s > 95, string.format("%s: AC-3 track SNR %.1f dB vs ffmpeg", c.name, s)) + t:note("%s: AC-3 track, %d ch, %d frames, SNR %.1f dB", c.name, a.channels, a.frames, s) + end +end + +-- streaming + exact seeking (one frame of pre-roll for the overlap) +do + local c = byName["5.1_448"] + local whole = Ac3F.decode(reader(c.data)) :: any + local dec = Ac3F.open(reader(c.data)) :: any + local _ = dec:read(3000) + for _, at in { 0.1, 0.0, 0.0517 } do + dec:seek(at) + local b, n = dec:read(700) + local f0 = math.floor(at * c.rate + 0.5) + local maxd = 0 + for i = 0, n * 6 - 1 do + maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * 6 + i) * 4))) + end + t:check(n == 700 and maxd < 1e-6, string.format("seek %.4f s (max diff %g)", at, maxd)) + end +end + +-- resync over garbage, a truncated last frame, the raw codec API +do + local c = byName.stereo_44k + local a = Ac3F.decode(reader("\0\11\119garbage" .. c.data)) :: any + t:check(a and a.frames == c.frames, "garbage in front: same frames") + local h = Ac3.header(buffer.fromstring(c.data), 0, #c.data) :: Ac3.Header + t:check(h.sampleRate == 44100 and h.channels == 2 and h.acmod == 2 and h.bitrate == 192000, "header fields") + local cut = Ac3F.decode(reader(string.sub(c.data, 1, #c.data - 10))) :: any + t:check(cut and cut.frames == c.frames - 1536, "truncated last frame dropped") + local d = Ac3.decoder() + local n = d:decode(buffer.fromstring(c.data), 0, h.frameSize) + t:check(n == 1536 and d.channels == 2 and #d.pcm == 1536 * 2, "decoder: one syncframe") +end + +-- errors +do + local c = byName.stereo_44k.data + t:eq(Ac3F.sniff(reader("RIFF....WAVE")), 0, "sniff a WAV") + local _, e = Ac3F.decode(reader(string.rep("\0", 100))) + t:check(e and e.code == Err.CORRUPT, "no frames: " .. tostring(e)) + -- an E-AC-3 header: bsid 16, frmsiz 255 (512 bytes), then the same again + local eac3 = "\11\119\0\255\128\128" .. string.rep("\0", 506) + _, e = Ac3F.decode(reader(eac3 .. eac3)) + t:check(e and e.code == Err.UNSUPPORTED, "E-AC-3: " .. tostring(e)) + -- a flipped bit in the middle of the first frame: the CRC catches it + local bad = string.sub(c, 1, 300) .. string.char(bit32.bxor(string.byte(c, 301), 4)) .. string.sub(c, 302) + _, e = Ac3F.decode(reader(bad)) + t:check(e and e.code == Err.CHECKSUM, "CRC: " .. tostring(e)) + _, e = Ac3F.decode(reader(c), { maxFrames = 2 }) + t:check(e and e.code == Err.LIMIT, "maxFrames: " .. tostring(e)) +end + +-- fuzz (without the CRC check, so mutations reach the decoder) +do + local samples = {} + for _, c in Fx do + table.insert(samples, string.sub(c.data, 1, 4000)) + end + t:fuzz("decode", function(b: buffer) + return Ac3F.decode(Bytes.reader(b), { crc = false }) + end, samples, { mutations = 25 }) + t:fuzz("decode (crc)", function(b: buffer) + return Ac3F.decode(Bytes.reader(b)) + end, samples, { mutations = 4, garbage = 20 }) +end + +t:done() diff --git a/tools/fixtures/ac3.py b/tools/fixtures/ac3.py new file mode 100644 index 0000000..f7cba37 --- /dev/null +++ b/tools/fixtures/ac3.py @@ -0,0 +1,233 @@ +# AC-3 fixtures (tools/fixtures.py). Encoders: ffmpeg (every channel layout, coupling, rematrixing, 32 / 44.1 / +# 48 kHz) and aften (block switching, dual mono 1+1, dynamic range profiles, the alternate bit stream syntax). +# References: ffmpeg's float decode with -drc_scale 0 (dynamic range off, our default), except for block-switched +# streams: ffmpeg (as packaged) mis-decodes the first of the two short transforms, so those use liba52's a52dec +# (-r -a: no dynamic range, no level adjustment; float for stereo, 16-bit wav6 for more channels), which agrees with +# the A/52 transform equations. AC-3 tracks in Matroska / MP4 / MPEG-TS (remuxed by ffmpeg) for the api's audio hook. +# +# Both encoders set dithflag, and decoders draw their own random dither for the zero-bit mantissas, so two correct +# decoders differ by about the coding noise. The reference streams therefore have their dithflags cleared (the bit +# positions come from our decoder's dec.blocks, the CRCs are recomputed): the reference and we decode the same +# numbers. `dithered` keeps the encoder's original stream for a few cases. +# tests/gen/ac3_cases.luau { name, data, channels, rate, frames, ref (f32le, WAVE order), refTool, refDrc?, +# dithered? } +# tests/gen/ac3_tracks.luau { name, data (the container), channels, rate, ref (ffmpeg's decode of the AC-3) } +import importlib.util, math, os, random, shutil, struct, subprocess, tempfile + +_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 = ["tools/fixtures/_audio.py", "src/Formats/codecs/audio/Ac3"] +SECONDS = 0.15 +DITHERED = ("stereo_44k", "aften_5.1_blksw") +NFCHANS = [2, 1, 2, 3, 3, 4, 4, 5] + + +def _lit(b): + return '"' + "".join("\\x%02x" % x for x in b) + '"' + + + +def crc16(data, crc=0): + """A/52 section 7.10.1: x^16 + x^15 + x^2 + 1, MSB first, zero start""" + for b in data: + crc ^= b << 8 + for _ in range(8): + crc = ((crc << 1) ^ 0x8005) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF + return crc + + +def fix_crcs(f): + """recompute crc1 (the CRC of the first 5/8 of the frame after the sync word is 0) and crc2 (all of it)""" + words = len(f) // 2 + n58 = ((words >> 1) + (words >> 3)) * 2 + # crc1 is the first word of the span: solve the linear map W -> crc(W || 0...) for crc(W || rest) == 0 + rest = crc16(bytes(2) + bytes(f[4:n58])) + basis = [crc16(bytes([(1 << i) >> 8, (1 << i) & 255]) + bytes(n58 - 4)) for i in range(16)] + rows = [(basis[i], 1 << i) for i in range(16)] + pivots = {} + for v, m in rows: + for bit in range(15, -1, -1): + if not v >> bit & 1: + continue + if bit in pivots: + pv, pm = pivots[bit] + v, m = v ^ pv, m ^ pm + else: + pivots[bit] = (v, m) + break + w, target = 0, rest + for bit in range(15, -1, -1): + if target >> bit & 1: + pv, pm = pivots[bit] + target ^= pv + w ^= pm + f[2], f[3] = w >> 8, w & 255 + assert crc16(bytes(f[2:n58])) == 0 + c2 = crc16(bytes(f[2:-2])) + f[-2], f[-1] = c2 >> 8, c2 & 255 + assert crc16(bytes(f[2:])) == 0 + + +def undither(ctx, data): + """clear every dithflag (after the blksw flags at each audio block's start) and fix the CRCs""" + code = """ +local Ac3 = require("@formats/codecs/audio/Ac3") +local b = buffer.fromstring(%s) +local dec = Ac3.decoder() +local o, n = 0, buffer.len(b) +while o + 8 <= n do + local h = Ac3.header(b, o, n) + if not h then break end + assert(dec:decode(b, o, h.frameSize)) + print(o, h.frameSize, h.acmod, table.concat(dec.blocks, " ")) + o += h.frameSize +end +""" % _lit(data) + out = bytearray(data) + for line in A.luau(ctx, code).decode().strip().split("\n"): + v = [int(x) for x in line.split()] + o, size, acmod, blocks = v[0], v[1], v[2], v[3:] + nf = NFCHANS[acmod] + f = out[o:o + size] + for p in blocks: + for k in range(nf): + bit = p + nf + k + f[bit >> 3] &= ~(0x80 >> (bit & 7)) & 255 + fix_crcs(f) + out[o:o + size] = f + return bytes(out) + +# Both encoders set dithflag, and decoders draw their own random dither for the zero-bit mantissas, so two correct +# decoders differ by about the coding noise. The reference streams therefore have their dithflags cleared (the bit +# positions come from our decoder's dec.blocks, the CRCs are recomputed): ffmpeg and we then decode the same numbers. +# `dithered` keeps the encoder's original stream for a few cases. +# +# name, encoder, layout (ffmpeg) or (acmod, lfe) (aften), rate, kbps, extra options +CASES = [ + ("mono_48k", "ffmpeg", "mono", 48000, 96, []), + ("stereo_44k", "ffmpeg", "stereo", 44100, 192, []), + ("stereo_cpl_48k", "ffmpeg", "stereo", 48000, 96, ["-channel_coupling", "1", "-cpl_start_band", "1"]), + ("stereo_cpl0_48k", "ffmpeg", "stereo", 48000, 64, ["-channel_coupling", "1", "-cpl_start_band", "0"]), + ("stereo_32k", "ffmpeg", "stereo", 32000, 64, []), + ("3.0_48k", "ffmpeg", "3.0", 48000, 256, []), + ("2.1_48k", "ffmpeg", "2.1", 48000, 192, []), + ("3.0back_48k", "ffmpeg", "3.0(back)", 48000, 192, []), + ("4.0_48k", "ffmpeg", "4.0", 48000, 256, []), + ("4.1_44k", "ffmpeg", "4.1", 44100, 320, []), + ("quad_side_48k", "ffmpeg", "quad(side)", 48000, 256, []), + ("5.0_side_32k", "ffmpeg", "5.0(side)", 32000, 320, []), + ("5.1_448", "ffmpeg", "5.1(side)", 48000, 448, []), + ("5.1_cpl_256", "ffmpeg", "5.1(side)", 48000, 256, ["-channel_coupling", "1"]), + ("aften_blksw_stereo", "aften", (2, 0), 48000, 192, ["-s", "1"]), + ("aften_dualmono", "aften", (0, 0), 48000, 128, []), + ("aften_5.1_blksw", "aften", (7, 1), 48000, 384, ["-s", "1"]), + ("aften_5.1_drc", "aften", (7, 1), 48000, 384, ["-dynrng", "1"]), + ("aften_xbsi_2.2", "aften", (6, 0), 44100, 256, ["-xbsi1", "1", "-xbsi2", "1", "-s", "1"]), +] +CHANNELS = {"mono": 1, "stereo": 2, "3.0": 3, "2.1": 3, "3.0(back)": 3, "4.0": 4, "4.1": 5, "quad(side)": 4, + "5.0(side)": 5, "5.1(side)": 6} +ACMOD_CH = {0: 2, 1: 1, 2: 2, 3: 3, 4: 3, 5: 4, 6: 4, 7: 5} + + +def signal(frames, ch, rate, seed): + """per-channel tones with vibrato, noise bursts and clicks (transients for block switching)""" + rng = random.Random(seed) + out = [0.0] * (frames * ch) + for c in range(ch): + f = 110.0 * (c + 2) * (1.0 + 0.07 * c) + for i in range(frames): + t = i / rate + v = 0.2 * math.sin(2 * math.pi * f * t + 2 * math.sin(2 * math.pi * 4 * t)) + v += 0.06 * math.sin(2 * math.pi * (2500 + 700 * c) * t) + if (i // (rate // 10) + c) % 4 == 1: + v += 0.12 * (rng.random() * 2 - 1) + k = i % (rate // 7) + if k < 60: + v += 0.5 * (1 - k / 60) * (1 if (i // 5) % 2 else -1) + out[i * ch + c] = v + return out + + +def raw(samples): + return struct.pack("<%df" % len(samples), *samples) + + +def a52dec(run, d, name, ch): + """liba52's decode: float (planar per 256-sample block) for stereo, 16-bit wav6 otherwise -> f32le, WAVE order""" + flags = "-a -r" + if ch == 2: + raw_ = run("a52dec -o float %s %s 2>/dev/null" % (flags, name)) + v = struct.unpack("<%df" % (len(raw_) // 4), raw_) + out = [0.0] * len(v) + for b in range(len(v) // 512): + for i in range(256): + out[(b * 256 + i) * 2] = v[b * 512 + i] + out[(b * 256 + i) * 2 + 1] = v[b * 512 + 256 + i] + return raw(out) + wav = run("a52dec -o wav6 %s %s 2>/dev/null" % (flags, name)) + p = wav.index(b"data") + 8 + pcm = struct.unpack("<%dh" % ((len(wav) - p) // 2), wav[p:p + (len(wav) - p) // 2 * 2]) + return raw([x / 32768 for x in pcm]) + + +def generate(ctx): + d = tempfile.mkdtemp(prefix="fmt-ac3-") + cases, tracks = [], [] + try: + def run(cmd): + return ctx.nix(["ffmpeg", "aften", "a52dec"], ["sh", "-c", "cd '%s' && %s" % (d, cmd)]) + + for name, enc, layout, rate, kbps, extra in CASES: + ch = CHANNELS[layout] if enc == "ffmpeg" else ACMOD_CH[layout[0]] + layout[1] + frames = int(rate * SECONDS) + sig = signal(frames, ch, rate, len(name)) + with open(os.path.join(d, name + ".raw"), "wb") as f: + f.write(raw(sig)) + out = name + ".ac3" + if enc == "ffmpeg": + run("ffmpeg -v error -y -f f32le -ar %d -ch_layout '%s' -i %s.raw -c:a ac3 -b:a %dk %s %s" + % (rate, layout, name, kbps, " ".join(extra), out)) + else: + with open(os.path.join(d, name + ".wav"), "wb") as f: + f.write(A.wav(sig, rate, ch)) + run("aften -v 0 -threads 1 -b %d -acmod %d -lfe %d %s %s.wav %s" % (kbps, layout[0], layout[1], " ".join(extra), name, out)) + with open(os.path.join(d, out), "rb") as f: + orig = f.read() + data = undither(ctx, orig) + with open(os.path.join(d, "u_" + out), "wb") as f: + f.write(data) + c = {"name": name, "data": data, "channels": ch, "rate": rate} + if "-s" in extra: + c["ref"], c["refTool"] = a52dec(run, d, "u_" + out, ch), "a52dec" + else: + c["ref"], c["refTool"] = run("ffmpeg -v error -drc_scale 0 -i u_%s -f f32le -" % out), "ffmpeg" + if "-dynrng" in extra: + c["refDrc"] = run("ffmpeg -v error -drc_scale 1 -i u_%s -f f32le -" % out) + c["frames"] = len(c["ref"]) // (4 * ch) + if name in DITHERED: + c["dithered"] = orig + cases.append(c) + # AC-3 tracks in containers: the (undithered) AC-3 remuxed with a tiny Motion-JPEG / MPEG-1 picture track + sig = signal(int(48000 * 0.3), 6, 48000, 7) + with open(os.path.join(d, "t.raw"), "wb") as f: + f.write(raw(sig)) + for name, video, layout in (("ac3.mkv", "-c:v mjpeg -pix_fmt yuvj420p", "5.1(side)"), + ("ac3.mp4", "-c:v mjpeg -pix_fmt yuvj420p", "stereo"), ("ac3.ts", "-c:v mpeg1video", "stereo")): + run("ffmpeg -v error -y -f f32le -ar 48000 -ch_layout '5.1(side)' -i t.raw -af aformat=channel_layouts='%s' " + "-c:a ac3 -b:a 192k t.ac3" % layout) + with open(os.path.join(d, "t.ac3"), "rb") as f: + es = undither(ctx, f.read()) + with open(os.path.join(d, "u.ac3"), "wb") as f: + f.write(es) + run("ffmpeg -v error -y -f lavfi -i testsrc=size=64x48:rate=25:duration=0.3 -i u.ac3 %s -c:a copy -shortest %s" + % (video, name)) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + ref = run("ffmpeg -v error -drc_scale 0 -i u.ac3 -f f32le -") + tracks.append({"name": name, "data": data, "channels": CHANNELS[layout], "rate": 48000, "ref": ref}) + finally: + shutil.rmtree(d, ignore_errors=True) + ctx.emit("ac3_cases", cases) + ctx.emit("ac3_tracks", tracks)