# M4A / AAC / ALAC / CAF fixtures (tools/fixtures.py). Reference tools through nix: ffmpeg (AAC + ALAC encoders and # decoders, the CAF muxer), fdkaac (Fraunhofer's encoder: plain and HE-AAC), MP4Box (-info on our files). # tests/gen/m4a_alac.luau ALAC in M4A / CAF from ffmpeg: { name, data, container, channels, rate, bits, frames, # crc } where crc is the CRC-32 of the source integers as little-endian int32 # tests/gen/m4a_aac.luau AAC from ffmpeg / faac (M4A, ADTS, CAF): { name, data, container, channels, rate, frames, # ref } with ref = ffmpeg's float decode (f32le) of the file # tests/gen/m4a_he.luau HE-AAC / HE-AACv2 from fdkaac: { name, data, rate (the SBR output rate), ps } # tests/gen/m4a_ours.luau our writers' files (tools/fixtures/_m4a_encode.luau over tests/audio/_encode_cases.luau) # checked by ffmpeg: { name, crc (of our bytes), ffmpeg (decodes bit-exactly), frames, # tags (ffprobe's view), mp4box (MP4Box -info exit status 0) } import importlib.util, json, math, os, shutil, struct, subprocess, tempfile, zlib # the shared signal module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) _spec = importlib.util.spec_from_file_location("_m4a_signal", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_m4a_signal.py")) _sig = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(_sig) signal, pack, wav = _sig.signal, _sig.pack, _sig.wav INPUTS = ["src/Rosetta/audio/m4a", "src/Rosetta/audio/caf", "src/Rosetta/codecs/audio/Alac", "src/Rosetta/containers/IsoBmff", "tests/audio/_signal.luau", "tests/audio/_encode_cases.luau", "tools/fixtures/_m4a_encode.luau", "tools/fixtures/_m4a_signal.py"] PKGS = ["ffmpeg", "fdk-aac-encoder", "gpac"] def run(ctx, cmd, cwd): return ctx.nix(PKGS, ["sh", "-c", "cd '%s' && %s" % (cwd, cmd)]) def crc_ints(ints): return zlib.crc32(struct.pack("<%di" % len(ints), *ints)) def music(frames, channels, rate, seed): """a float test signal for the lossy codecs: tones with vibrato, a chord, noise bursts and clicks (transients)""" rng = __import__("random").Random(seed) out = [] for i in range(frames): t = i / rate for c in range(channels): v = 0.25 * math.sin(2 * math.pi * (220 * (c + 1)) * t + 3 * math.sin(2 * math.pi * 5 * t)) v += 0.12 * math.sin(2 * math.pi * 660 * t) + 0.08 * math.sin(2 * math.pi * 1320.5 * t + c) v += 0.05 * math.sin(2 * math.pi * (5000 + 300 * c) * t) if (i // (rate // 8)) % 3 == 1: v += 0.15 * (rng.random() * 2 - 1) if i % (rate // 3) < 40: v += 0.6 * (1 - (i % (rate // 3)) / 40) * (1 if (i // 7) % 2 else -1) out.append(max(-32768, min(32767, int(round(v * 20000))))) return out def adts_to_caf(adts): frames, p = [], 0 while p + 7 <= len(adts): b1, b2, b3, b4, b5 = adts[p + 1], adts[p + 2], adts[p + 3], adts[p + 4], adts[p + 5] hs = 7 if b1 & 1 else 9 size = ((b3 & 3) << 11) | (b4 << 3) | (b5 >> 5) frames.append(adts[p + hs:p + size]) sfi, ch, aot = (b2 >> 2) & 15, ((b2 & 1) << 2) | (b3 >> 6), (b2 >> 6) + 1 p += size rate = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350][sfi] asc = struct.pack(">H", (aot << 11) | (sfi << 7) | (ch << 3)) dsi = b"\x05" + bytes([len(asc)]) + asc dcd = b"\x04" + bytes([13 + len(dsi)]) + bytes([0x40, 0x15, 0, 0, 0]) + struct.pack(">II", 0, 0) + dsi esd = b"\x03" + bytes([3 + len(dcd) + 3]) + b"\x00\x00\x00" + dcd + b"\x06\x01\x02" def ber(n): out = [n & 127] n >>= 7 while n: out.insert(0, 128 | (n & 127)) n >>= 7 return bytes(out) def chunk(t, body): return t + struct.pack(">q", len(body)) + body desc = struct.pack(">d4sIIIII", rate, b"aac ", 2, 0, 1024, ch, 0) pakt = struct.pack(">qqii", len(frames), len(frames) * 1024, 0, 0) + b"".join(ber(len(f)) for f in frames) data = b"\x00\x00\x00\x00" + b"".join(frames) return b"caff\x00\x01\x00\x00" + chunk(b"desc", desc) + chunk(b"kuki", b"\x00\x00\x00\x00" + esd) + chunk(b"pakt", pakt) + chunk(b"data", data) def generate(ctx): d = tempfile.mkdtemp(prefix="m4a-fx-") try: # --- ALAC from ffmpeg: lossless, the decode must equal the source integers alac = [] for name, frames, ch, rate, bits, container in ( ("alac16_stereo.m4a", 10000, 2, 44100, 16, "m4a"), ("alac16_mono.m4a", 4097, 1, 8000, 16, "m4a"), ("alac24_stereo.m4a", 6000, 2, 96000, 24, "m4a"), ("alac16_6ch.m4a", 5000, 6, 48000, 16, "m4a"), ("alac16_stereo.caf", 9000, 2, 44100, 16, "caf"), ): ints = signal(frames, ch, bits, 11 + frames) with open(os.path.join(d, "in.wav"), "wb") as f: f.write(wav(ints, ch, rate, bits)) fmt = "-sample_fmt s32p" if bits == 24 else "" run(ctx, "ffmpeg -v error -y -i in.wav -c:a alac %s %s" % (fmt, name), d) with open(os.path.join(d, name), "rb") as f: data = f.read() alac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate, "bits": bits, "frames": frames, "crc": crc_ints(ints)}) ctx.emit("m4a_alac", alac) # --- AAC from ffmpeg / faac: our decode against ffmpeg's float decode aac = [] specs = ( # name, frames, channels, rate, encoder command (in.wav -> name) ("aac_stereo_128k.m4a", 60000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 128k -aac_pns 0 %s"), ("aac_mono_22k.m4a", 30000, 1, 22050, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 48k %s"), ("aac_51_48k.m4a", 30000, 6, 48000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 256k %s"), ("aac_tools_40k.m4a", 50000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 40k -aac_pns 1 -aac_is 1 -aac_ms 1 -aac_tns 1 %s"), ("aac_8k_mono.m4a", 12000, 1, 8000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 16k %s"), ("aac_96k.m4a", 30000, 2, 96000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 192k %s"), ("aac_stereo.aac", 40000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -aac_pns 0 -f adts %s"), ("fdk_stereo.aac", 40000, 2, 44100, "fdkaac -S -b 96000 -f 2 -o %s in.wav"), ("fdk_mono_32k.aac", 20000, 1, 32000, "fdkaac -S -b 48000 -f 2 -o %s in.wav"), ("fdk_stereo.m4a", 40000, 2, 48000, "fdkaac -S -b 128000 -o %s in.wav"), ("aac_stereo.caf", 30000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -f adts %s.adts"), ) for name, frames, ch, rate, cmd in specs: ints = music(frames, ch, rate, frames + ch) with open(os.path.join(d, "in.wav"), "wb") as f: f.write(wav(ints, ch, rate, 16)) run(ctx, cmd % name, d) if name.endswith(".caf"): # ffmpeg cannot write AAC in CAF: wrap its ADTS frames ourselves (desc, kuki esds, pakt, data) with open(os.path.join(d, name + ".adts"), "rb") as f: adts = f.read() with open(os.path.join(d, name), "wb") as f: f.write(adts_to_caf(adts)) with open(os.path.join(d, name), "rb") as f: data = f.read() ref = run(ctx, "ffmpeg -v error -i %s -f f32le -c:a pcm_f32le -" % name, d) container = "caf" if name.endswith(".caf") else ("adts" if name.endswith(".aac") else "m4a") aac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate, "frames": len(ref) // (4 * ch), "ref": ref}) ctx.emit("m4a_aac", aac) # HE-AAC (SBR) and HE-AACv2 (SBR + PS) from fdkaac: we decode the AAC-LC core at the core rate he = [] for name, frames, ch, rate, prof, br in (("he_aac.m4a", 48000, 2, 44100, 5, 48000), ("he_aac_v2.m4a", 48000, 2, 44100, 29, 32000), ("he_aac.aac", 48000, 2, 44100, 5, 48000)): ints = music(frames, ch, rate, 99) with open(os.path.join(d, "in.wav"), "wb") as f: f.write(wav(ints, ch, rate, 16)) run(ctx, "fdkaac -S -p %d -b %d %s -o %s in.wav" % (prof, br, "-f 2" if name.endswith(".aac") else "", name), d) with open(os.path.join(d, name), "rb") as f: he.append({"name": name, "data": f.read(), "rate": rate, "ps": prof == 29}) ctx.emit("m4a_he", he) # --- our writers, checked by ffmpeg / ffprobe / MP4Box luau = os.environ.get("LUAU") or shutil.which("luau") if luau: out = subprocess.run([luau, "tools/fixtures/_m4a_encode.luau"], capture_output=True, check=True, cwd=ctx.root).stdout else: out = ctx.nix("luau", ["luau", os.path.join(ctx.root, "tools/fixtures/_m4a_encode.luau")]) ours = [] meta = { # name -> frames, channels, bits, seed (tests/audio/_encode_cases.luau) "ours_alac16_stereo": (4096 * 3 + 1234, 2, 16, 1), "ours_alac16_mono": (5000, 1, 16, 2), "ours_alac24_stereo": (9000, 2, 24, 3), "ours_alac16_6ch": (4500, 6, 16, 4), "ours_alac20_stereo": (3000, 2, 20, 5), "ours_caf_alac16": (7000, 2, 16, 6), "ours_caf_pcm16": (3000, 2, 16, 7), "ours_caf_pcm24": (2000, 1, 24, 8), } for line in out.decode().split("\n"): if not line.strip(): continue name, hx = line.split(" ", 1) if hx.startswith("ERROR"): raise RuntimeError("m4a fixtures: our encoder failed on %s: %s" % (name, hx)) data = bytes.fromhex(hx) ext = "caf" if "caf" in name else "m4a" path = name + "." + ext with open(os.path.join(d, path), "wb") as f: f.write(data) frames, ch, bits, seed = meta[name] ints = signal(frames, ch, bits, seed) wide = bits > 16 want = pack([v << (32 - bits) for v in ints] if wide else ints, 32 if wide else 16) got = run(ctx, "ffmpeg -v error -i %s -f %s -" % (path, "s32le" if wide else "s16le"), d) fbytes = (4 if wide else 2) * ch # ffmpeg's CAF reader drops the pakt remainder from a partial last ALAC packet (also on its own files): # accept its output when it is an exact prefix of ours ok = got == want or (ext == "caf" and len(got) > 0 and want.startswith(got)) probe = json.loads(run(ctx, "ffprobe -v error -show_format -show_streams -of json %s" % path, d)) tags = {k.lower(): v for k, v in probe["format"].get("tags", {}).items()} mp4box = True if ext == "m4a": try: run(ctx, "MP4Box -info %s >/dev/null 2>&1" % path, d) except subprocess.CalledProcessError: mp4box = False ours.append({"name": name, "crc": zlib.crc32(data), "ffmpeg": ok, "frames": len(got) // fbytes, "tags": tags, "mp4box": mp4box, "codec": probe["streams"][0]["codec_name"]}) ctx.emit("m4a_ours", ours) finally: shutil.rmtree(d, ignore_errors=True)