# 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 / AVI (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, 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/Rosetta/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("@rosetta/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) # 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"), ("ac3.avi", "-c:v mjpeg -pix_fmt yuvj420p", "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)