From 9840aade8594729b835e84f33d146dd85385da37 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Thu, 19 Nov 2026 10:37:49 -0500 Subject: [PATCH] speaker tuning: collect the BuzzKill matrix only on request until speakerguardd reads it Since #119 the Python collector adds a `buzzkill_quadrature` record (and buzzkill-quadrature.bin) to every bundle whose AudioDSP holds the matrix, which is every macOS build seen so far. speakerguardd v2 parses a schema-2 manifest with deny_unknown_fields and no release reads the record yet (speakerguardd#138 adds the reader), so every release up to 1.0.0alpha.1-42 refuses such a bundle: "not a schema-2 manifest: unknown field `buzzkill_quadrature`". aurora-speaker-upgrade --collection then refuses the switch, and a Mac whose kernel has only the v2 interface, given the bundle with install-linux.sh, keeps its speakers at the kernel's floor. Seen on a J713 (AID37) and an M4 Mac mini (J773g, AID36). The native installer does not collect the matrix, so its bundles are not affected. Collect the matrix only when asked (collect/collect-linux --buzzkill-matrix, AudioTuningFWCollection(buzzkill=True)), as the native installer does, until a speakerguardd release reads it; then flip COLLECT_BUZZKILL. A bundle that already carries it is still verified and read. install-linux.sh installs such a bundle without the matrix by default (without_buzzkill: the bundle exactly as collected without it) and says so; --keep-buzzkill-matrix keeps it. Signed-off-by: Diljit Singh --- asahi_firmware/audio_tuning.py | 61 +++++++++++++++++++------- tests/test_audio_tuning.py | 39 ++++++++++++++-- tests/test_speaker_tuning_tool.py | 43 ++++++++++++++++-- tools/speaker-tuning/README.md | 11 +++++ tools/speaker-tuning/speaker_tuning.py | 45 ++++++++++++++----- 5 files changed, 166 insertions(+), 33 deletions(-) diff --git a/asahi_firmware/audio_tuning.py b/asahi_firmware/audio_tuning.py index 90bc6c1b..939f884d 100644 --- a/asahi_firmware/audio_tuning.py +++ b/asahi_firmware/audio_tuning.py @@ -66,6 +66,16 @@ LATTICE = "lsm2-mask-lattice.bin" # The BuzzKill detector's quadrature matrix (buzzkill_matrix), as its 80 bytes. BUZZKILL = "buzzkill-quadrature.bin" +BUZZKILL_KEY = "buzzkill_quadrature" +# Whether a new bundle carries that matrix. speakerguardd v2 reads a schema-2 +# manifest strictly: a key it does not know refuses the whole bundle, and the +# speakers stay at the kernel's floor. No speakerguardd release reads +# `buzzkill_quadrature` yet (speakerguardd#138 adds the reader); every one up +# to 1.0.0alpha.1-42 refuses a bundle that has it. So, until a release reads +# it, the matrix is collected only on request (rigs, the parity gate), as the +# native installer does. A bundle that already carries it is still verified +# and read; `without_buzzkill` gives the same bundle without it. +COLLECT_BUZZKILL = False # Where it is read: the AudioDSP component of the running macOS. AUDIODSP_PATH = "/" + lsm2_lattice.AUDIODSP @@ -422,10 +432,27 @@ def manifest(aid, acoustic, files, spts, build, selection=None, speaker=None, # present when it was read; without it the voicing compiler refuses # Buzz boxes. if buzzkill is not None: - doc["buzzkill_quadrature"] = buzzkill_record(buzzkill) + doc[BUZZKILL_KEY] = buzzkill_record(buzzkill) return doc +def encode_manifest(doc): + return json.dumps(doc, indent=2, sort_keys=True).encode("utf-8") + + +def without_buzzkill(bundle): + """The bundle as the collector writes it without the BuzzKill matrix: + no matrix file and no `buzzkill_quadrature` record; every other file and + manifest entry unchanged. A bundle without the matrix is returned as is.""" + doc = json.loads(bundle[MANIFEST]) + if BUZZKILL not in bundle and BUZZKILL_KEY not in doc: + return bundle + doc.pop(BUZZKILL_KEY, None) + out = {rel: data for rel, data in bundle.items() if rel != BUZZKILL} + out[MANIFEST] = encode_manifest(doc) + return out + + def tree(acoustic, files, spts, build, selection=None, source_count=None, speaker=None, shared=None, loudness=None, source=DATABASE, lattice=None, board=None, unit=None, fill=None, buzzkill=None): @@ -488,10 +515,9 @@ def tree(acoustic, files, spts, build, selection=None, source_count=None, speake out[lsm2_fill.NAME] = fill if buzzkill is not None: out[BUZZKILL] = bytes(buzzkill) - out[MANIFEST] = json.dumps(manifest(aid, acoustic, files, spts, build, selection, speaker, - shared, loudness, source, bytes(lattice), board, unit, fill, - None if buzzkill is None else bytes(buzzkill)), - indent=2, sort_keys=True).encode("utf-8") + out[MANIFEST] = encode_manifest(manifest(aid, acoustic, files, spts, build, selection, speaker, + shared, loudness, source, bytes(lattice), board, unit, + fill, None if buzzkill is None else bytes(buzzkill))) return out @@ -588,11 +614,14 @@ class AudioTuningFWCollection(object): extracted fallback archive (path = the directory holding audio-tuning/).""" def __init__(self, path=None, tunings_root=TUNINGS_ROOT, run=subprocess.run, audiodsp=None, - offline=None, force_lsm2_fill=False): + offline=None, force_lsm2_fill=False, buzzkill=None): """offline: an OfflineMac, to collect from a mounted macOS system - volume and the Mac's ADT (Linux) instead of the running macOS.""" + volume and the Mac's ADT (Linux) instead of the running macOS. + buzzkill: also collect the BuzzKill quadrature matrix (default + COLLECT_BUZZKILL); a re-collection (path) keeps what the bundle has.""" self.fwfiles = [] self.bundle = {} + self.collect_buzzkill = COLLECT_BUZZKILL if buzzkill is None else bool(buzzkill) try: if offline is not None: self.load(offline.tunings_root, None, offline.audiodsp, offline) @@ -684,13 +713,15 @@ def load(self, tunings_root, run, audiodsp=AUDIODSP_PATH, offline=None, force_ls except Exception as e: log.warning(f"lsm2 fill not collected: {e}; short presets remain muted; " "collect again on this Mac's running macOS") - # The BuzzKill matrix the same way; without one the bundle still - # serves every Mac whose graph has no Buzz box. - try: - buzzkill = buzzkill_matrix.read(audiodsp) - except ValueError as e: - log.warning(f"Speaker tuning collected without the BuzzKill quadrature matrix: {e}") - buzzkill = None + # The BuzzKill matrix the same way, when asked (COLLECT_BUZZKILL); + # without one the bundle still serves every Mac whose graph has no + # Buzz box. + buzzkill = None + if getattr(self, "collect_buzzkill", COLLECT_BUZZKILL): + try: + buzzkill = buzzkill_matrix.read(audiodsp) + except ValueError as e: + log.warning(f"Speaker tuning collected without the BuzzKill quadrature matrix: {e}") self._publish(tree(acoustic, files, props[1], build, selection, count, speaker, shared, loudness, source, lattice, board, unit, fill, buzzkill)) log.info(f" Collected speaker tuning AID{acoustic} ({len(files)} files" @@ -797,7 +828,7 @@ def update(self, path): or not unit or fill.get("unit_id") != unit): raise ValueError("malformed lsm2 fill record") records = records + [fill] - buzzkill = meta.get("buzzkill_quadrature") + buzzkill = meta.get(BUZZKILL_KEY) if buzzkill is not None: if not isinstance(buzzkill, dict) or buzzkill.get("path") != BUZZKILL \ or buzzkill.get("version") != buzzkill_matrix.VERSION \ diff --git a/tests/test_audio_tuning.py b/tests/test_audio_tuning.py index 22f9e5b5..46265445 100644 --- a/tests/test_audio_tuning.py +++ b/tests/test_audio_tuning.py @@ -728,14 +728,45 @@ def test_a_bundle_collected_before_the_lattice_still_verifies_with_a_warning(sel class BuzzKillMatrixTest(unittest.TestCase): - """The BuzzKill quadrature matrix: carried when the component has one, - otherwise the bundle is still written without it.""" + """The BuzzKill quadrature matrix: collected on request and carried when + the component has one, otherwise the bundle is still written without + it. Not collected by default until a speakerguardd release reads it.""" - def collect_with(self, root, component): + def collect_with(self, root, component, buzzkill=True): path = root / "component" path.write_bytes(component) return AudioTuningFWCollection(tunings_root=str(root), run=fake_run(AID35), - audiodsp=str(path)) + audiodsp=str(path), buzzkill=buzzkill) + + def test_not_collected_by_default(self): + # No released speakerguardd reads the record, and every one refuses + # a manifest that has it (speakerguardd#138). + self.assertFalse(audio_tuning.COLLECT_BUZZKILL) + with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + tunings(root) + with self.assertNoLogs("asahi_firmware.audio_tuning", "WARNING"): + col = self.collect_with(root, self.component(), buzzkill=None) + self.assertTrue(col.bundle) + self.assertNotIn("buzzkill-quadrature.bin", col.bundle) + self.assertNotIn("buzzkill_quadrature", json.loads(col.bundle["manifest.json"])) + + def test_without_buzzkill_is_the_bundle_collected_without_it(self): + with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + tunings(root) + carried = self.collect_with(root, self.component()).bundle + plain = self.collect_with(root, self.component(), buzzkill=False).bundle + self.assertIn("buzzkill-quadrature.bin", carried) + self.assertEqual(audio_tuning.without_buzzkill(carried), plain) + self.assertIs(audio_tuning.without_buzzkill(plain), plain) + # Still a complete bundle that reads back unchanged. + out = pathlib.Path(tmp) / "out" + col = AudioTuningFWCollection.__new__(AudioTuningFWCollection) + col.fwfiles, col.bundle = [], {} + col._publish(audio_tuning.without_buzzkill(carried)) + self.assertTrue(col.write_fallback(str(out))) + self.assertEqual(AudioTuningFWCollection(str(out)).bundle, plain) def component(self, matrix_const=None): from test_buzzkill_matrix import const diff --git a/tests/test_speaker_tuning_tool.py b/tests/test_speaker_tuning_tool.py index 22ec1872..fbcdf1f0 100644 --- a/tests/test_speaker_tuning_tool.py +++ b/tests/test_speaker_tuning_tool.py @@ -84,11 +84,19 @@ def tunings(root, acoustic=35, salt=b""): (root / "DeviceDSPDatabase.plist").write_bytes(plistlib.dumps(db)) -def bundle_dir(base, acoustic=35, salt=b"", spts=bytes(range(16)), root=None): - """A verified audio-tuning/ under base; returns base.""" +def bundle_dir(base, acoustic=35, salt=b"", spts=bytes(range(16)), root=None, buzzkill=False): + """A verified audio-tuning/ under base; returns base. buzzkill: collect + from a component that also has a BuzzKill matrix, with the matrix.""" src = base / "tunings" tunings(src, acoustic, salt) - col = AudioTuningFWCollection(tunings_root=str(src), run=fake_run(acoustic, spts, root=root)) + audiodsp = None + if buzzkill: + from test_buzzkill_matrix import const + audiodsp = base / "AudioDSP-buzzkill" + audiodsp.write_bytes(thin(padded(synthetic_lattice()) + const())) + col = AudioTuningFWCollection(tunings_root=str(src), run=fake_run(acoustic, spts, root=root), + audiodsp=None if audiodsp is None else str(audiodsp), + buzzkill=buzzkill) assert col.bundle out = base / "bundle" out.mkdir() @@ -540,6 +548,35 @@ def test_newer_bundle_replaces_the_old_one(self): with st.opened_bundle(src) as (bundle, _): self.assertEqual(raw, bundle) + def test_a_bundle_with_the_buzzkill_matrix_installs_without_it(self): + # A collection made while the collector wrote the matrix by default: + # no released speakerguardd reads it, and every one refuses it. + src = bundle_dir(self.tmp, buzzkill=True) + with st.opened_bundle(src) as (bundle, _): + self.assertIn(audio_tuning.BUZZKILL, bundle) + plain = audio_tuning.without_buzzkill(bundle) + result, text = self.install(src) + self.assertEqual(result, "installed", text) + self.assertIn("installed without it", text) + raw, _ = st.raw_tuning(self.esp / "asahi" / "all_firmware.tar.gz") + self.assertEqual(raw, plain) + manifest = st.parse_manifest((self.esp / "vendorfw" / "manifest.txt").read_text()) + self.assertNotIn("apple/audio-tuning/" + audio_tuning.BUZZKILL, manifest) + self.assertNotIn(audio_tuning.BUZZKILL_KEY, + json.loads(raw[audio_tuning.MANIFEST])) + result, text = self.install(src) + self.assertEqual(result, "identical", text) + + def test_keep_buzzkill_matrix_installs_it(self): + src = bundle_dir(self.tmp, buzzkill=True) + result, text = self.install(src, buzzkill=True) + self.assertEqual(result, "installed", text) + self.assertNotIn("installed without it", text) + raw, _ = st.raw_tuning(self.esp / "asahi" / "all_firmware.tar.gz") + with st.opened_bundle(src) as (bundle, _): + self.assertEqual(raw, bundle) + self.assertIn(audio_tuning.BUZZKILL, raw) + def test_verify_running_bundle(self): src = bundle_dir(self.tmp) self.install(src) diff --git a/tools/speaker-tuning/README.md b/tools/speaker-tuning/README.md index 5ab88cdf..2df24076 100644 --- a/tools/speaker-tuning/README.md +++ b/tools/speaker-tuning/README.md @@ -26,6 +26,13 @@ component (see If it does not find exactly one valid table, it writes nothing and exits with an error. +The BuzzKill detector's quadrature matrix (also in AudioDSP) is collected +only with `--buzzkill-matrix`, for rigs. No speakerguardd release reads it +yet, and every release up to 1.0.0alpha.1-42 refuses a bundle that carries +it (`unknown field buzzkill_quadrature`), which leaves the speakers at the +kernel's floor. It becomes the default once a release reads it +(speakerguardd#138). + It reads both tuning layouts: the shared `DeviceDSPDatabase.plist` up to macOS 26, and the per-Mac `AID/DSP/DSPDatabase.plist` of macOS 27, and prints which one it used. @@ -128,6 +135,10 @@ since boot (it should be 0). - A bundle collected before the collector read the lsm2 masker lattice still installs; the Neo's lsm2 protection then gives no masking credit. Collect it again to add the lattice. +- A tarball collected between 2026-11-13 and this change carries the BuzzKill + matrix by default. `install-linux.sh` installs it without the matrix + (it says so), so speakerguardd accepts it; `--keep-buzzkill-matrix` keeps + it for a speakerguardd that reads it. - Collect again after a macOS update that changes the tuning. A newer bundle for the same AID replaces the old one. - The tarball and the backups hold this Mac's own calibration. Keep them on diff --git a/tools/speaker-tuning/speaker_tuning.py b/tools/speaker-tuning/speaker_tuning.py index 7d4e5047..05e8e339 100755 --- a/tools/speaker-tuning/speaker_tuning.py +++ b/tools/speaker-tuning/speaker_tuning.py @@ -67,6 +67,7 @@ def summary(bundle): "shared": len(meta.get("shared_files") or []), "loudness": meta.get("loudness_manager") is not None, "lattice": meta.get("lsm2_mask_lattice") is not None, + "buzzkill": meta.get(audio_tuning.BUZZKILL_KEY) is not None, } @@ -78,7 +79,8 @@ def describe(bundle): return (f"{s['aid']}, {s['files']} tuning files{extra}, calibration " f"{'present' if s['calibration'] else 'absent'}, speaker ID {spid}, " f"macOS {s['macos_build']}, lsm2 masker lattice " - f"{'present' if s['lattice'] else 'absent (collect again on macOS)'}") + f"{'present' if s['lattice'] else 'absent (collect again on macOS)'}" + + (", BuzzKill matrix" if s["buzzkill"] else "")) def verified(path): @@ -161,12 +163,13 @@ def write_collection(bundle, info, out): def collect(out=None, tunings_root=audio_tuning.TUNINGS_ROOT, run=subprocess.run, offline=None, - force_lsm2_fill=False): + force_lsm2_fill=False, buzzkill=None): """Collect this Mac's bundle and write the tarball. Returns its path. offline: an audio_tuning.OfflineMac (collect-linux) instead of the - running macOS.""" + running macOS. buzzkill: also collect the BuzzKill quadrature matrix + (default audio_tuning.COLLECT_BUZZKILL).""" col = AudioTuningFWCollection(tunings_root=tunings_root, run=run, offline=offline, - force_lsm2_fill=force_lsm2_fill) + force_lsm2_fill=force_lsm2_fill, buzzkill=buzzkill) if not col.bundle: raise Refused("this Mac's speaker tuning was not collected (see the messages above)") if force_lsm2_fill and audio_tuning.lsm2_fill.NAME not in col.bundle \ @@ -219,7 +222,7 @@ def dt_speaker_id(path=DT_SPEAKER_ID): return int.from_bytes(raw, "big") if len(raw) == 4 else None -def collect_linux(macos_root, adt_path=None, out=None): +def collect_linux(macos_root, adt_path=None, out=None, buzzkill=None): """Collect this Mac's bundle on Linux: its ADT and its own macOS system volume, mounted read-only at macos_root. The same bundle as collect on that macOS, except the speaker ID when the boot chain does not export it.""" @@ -237,7 +240,7 @@ def collect_linux(macos_root, adt_path=None, out=None): if out is None: name = f"aurora-speaker-tuning-{(offline.target() or 'mac').lower()}-linux.tar.gz" out = pathlib.Path.home() / name - return collect(out, offline=offline) + return collect(out, offline=offline, buzzkill=buzzkill) # ---------------------------------------------------------------- bundle input @@ -695,9 +698,12 @@ def read_compatible(path=DT_COMPATIBLE): def install(source, esp, dry_run=False, backup_root=BACKUP_ROOT, any_mac=False, - compatible=None, out=print, swap=exchange, rebuild=None, unit=None): + compatible=None, out=print, swap=exchange, rebuild=None, unit=None, buzzkill=None): """Returns "identical" (nothing to do), "dry-run" or "installed", or - raises Refused. The ESP is left as it was on any failure.""" + raises Refused. The ESP is left as it was on any failure. + buzzkill: keep a BuzzKill quadrature matrix the bundle carries (default + audio_tuning.COLLECT_BUZZKILL); otherwise it is installed without it.""" + keep_buzzkill = audio_tuning.COLLECT_BUZZKILL if buzzkill is None else bool(buzzkill) esp = pathlib.Path(esp) asahi, vendorfw = esp / "asahi", esp / "vendorfw" all_fw = asahi / "all_firmware.tar.gz" @@ -724,6 +730,10 @@ def install(source, esp, dry_run=False, backup_root=BACKUP_ROOT, any_mac=False, kernel = kernelcache(asahi) with opened_bundle(source) as (bundle, info): + if not keep_buzzkill and summary(bundle)["buzzkill"]: + bundle = audio_tuning.without_buzzkill(bundle) + out("The bundle carries the BuzzKill quadrature matrix, which no speakerguardd release " + "reads yet (and every one refuses): it is installed without it.") out(f"Bundle: {describe(bundle)}") if info is not None: out(f"Collected on: {info.get('target')} ({info.get('model')})") @@ -908,6 +918,9 @@ def main(argv=None): c = sub.add_parser("collect", help="on macOS: write this Mac's speaker tuning tarball") c.add_argument("--lsm2-fill-readback", action="store_true", help="also collect private parameter readback for full lsm2 presets (dry-run verification)") + buzz_help = ("also collect the BuzzKill quadrature matrix (rigs; no speakerguardd release reads it " + "yet, and every one refuses a bundle that has it)") + c.add_argument("--buzzkill-matrix", action="store_true", default=None, help=buzz_help) c.add_argument("-o", "--output", help="tarball path (default ~/aurora-speaker-tuning--AID.tar.gz)") cl = sub.add_parser("collect-linux", @@ -916,6 +929,7 @@ def main(argv=None): help="the macOS system volume, mounted read-only (e.g. apfs-fuse -o ro)") cl.add_argument("--adt", help="ADT blob (default: the \"adt\" MTD partition aura exposes)") cl.add_argument("-o", "--output", required=True, help="tarball path") + cl.add_argument("--buzzkill-matrix", action="store_true", default=None, help=buzz_help) i = sub.add_parser("install", help="on Linux: add a bundle to the ESP firmware") i.add_argument("bundle", help="tarball from collect-macos.sh, or a directory holding audio-tuning/") i.add_argument("-n", "--dry-run", action="store_true", help="check and rebuild, change nothing") @@ -923,6 +937,9 @@ def main(argv=None): i.add_argument("--backup-dir", default=BACKUP_ROOT, help=f"backup root (default {BACKUP_ROOT})") i.add_argument("--any-mac", action="store_true", help="skip the check that the bundle came from this model and AID") + i.add_argument("--keep-buzzkill-matrix", action="store_true", default=None, + help="keep a BuzzKill quadrature matrix the bundle carries (by default it is left out: " + "no speakerguardd release reads it yet, and every one refuses a bundle that has it)") v = sub.add_parser("verify", help="on Linux, after the reboot: check the unpacked bundle") v.add_argument("--esp", help="system ESP mount point") args = ap.parse_args(argv) @@ -931,9 +948,11 @@ def main(argv=None): if args.cmd == "collect": if sys.platform != "darwin": raise Refused("collect runs on the Mac's own macOS (on Linux: collect-linux)") - path, bundle, info = collect(args.output, force_lsm2_fill=args.lsm2_fill_readback) + path, bundle, info = collect(args.output, force_lsm2_fill=args.lsm2_fill_readback, + buzzkill=args.buzzkill_matrix) else: - path, bundle, info = collect_linux(args.macos_root, args.adt, args.output) + path, bundle, info = collect_linux(args.macos_root, args.adt, args.output, + buzzkill=args.buzzkill_matrix) s = summary(bundle) print(f"AID: {s['aid']}") print(f"Files: {s['files']} tuning files ({len(bundle)} in the bundle)") @@ -941,6 +960,9 @@ def main(argv=None): print(f"Speaker ID: {'unknown' if s['speaker_id'] is None else s['speaker_id']}") print(f"DSP database: {s['database_source']}") print("lsm2 masker lattice: read from AudioDSP (one per slice, identical)") + if s["buzzkill"]: + print("BuzzKill quadrature matrix: read from AudioDSP (only a speakerguardd that reads it " + "accepts this bundle)") if s["shared"] or s["loudness"]: print(f"Shared files: {s['shared']}, loudness manager: " f"{'yes' if s['loudness'] else 'no'}") @@ -964,7 +986,8 @@ def main(argv=None): with locked(), system_esp(args.esp) as esp: result = install(args.bundle, esp, dry_run=args.dry_run, backup_root=args.backup_dir, any_mac=args.any_mac, - compatible=read_compatible(), unit=read_unit()) + compatible=read_compatible(), unit=read_unit(), + buzzkill=args.keep_buzzkill_matrix) if result == "installed": print("Next: reboot, then check the unpacked bundle with") print(" sudo tools/speaker-tuning/install-linux.sh --verify")