#!/usr/bin/env python3 """Offline regression test for MSM8905/MSM8909 audio quality fixes (patch 0015, PipeWire downmix, gain staging).""" import os import re import shutil import subprocess import sys import tempfile BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PATCH_0015 = os.path.join( BASE_DIR, "patches/kernel/0015-msm8909-wcd-digital-interpolator-cajon-analog.patch" ) BUILD_KERNEL = os.path.join(BASE_DIR, "scripts/build-kernel-audio.sh") SXMO_AUDIO = os.path.join(BASE_DIR, "overlay/rootfs/usr/bin/sxmo_audio.sh") SOUNDMONITOR_C = os.path.join( BASE_DIR, "src/bananarchy-daemons/bananarchy-soundmonitor.c" ) SXMO_RING = os.path.join( BASE_DIR, "overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_ring.sh" ) CALLSCREEN_CPP = os.path.join(BASE_DIR, "src/dwm-plugins/callscreen_plugin.cpp") FILES_CPP = os.path.join(BASE_DIR, "src/dwm-plugins/files_plugin.cpp") RINGTONES_CPP = os.path.join(BASE_DIR, "src/dwm-plugins/ringtones_plugin.cpp") XDRAWER_CPP = os.path.join(BASE_DIR, "src/xdrawer/xdrawer.cpp") WP_S16LE_PATHS = [ "overlay/rootfs/etc/wireplumber/wireplumber.conf.d/msm8916-s16le.conf", "overlay/rootfs/usr/share/wireplumber/wireplumber.conf.d/msm8916-s16le.conf", "overlay/rootfs/etc/skel/.config/wireplumber/wireplumber.conf.d/msm8916-s16le.conf", "overlay/rootfs/home/user/.config/wireplumber/wireplumber.conf.d/msm8916-s16le.conf", ] WP_BT_PATHS = [ "overlay/rootfs/etc/wireplumber/wireplumber.conf.d/50-bluetooth.conf", "overlay/rootfs/usr/share/wireplumber/wireplumber.conf.d/50-bluetooth.conf", "overlay/rootfs/etc/skel/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf", "overlay/rootfs/home/user/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf", ] WP_CREATE_ITEM_LUA = ( "overlay/rootfs/usr/share/wireplumber/scripts/node/create-item.lua" ) PW_STREAM_DROPINS = [ "overlay/rootfs/etc/pipewire/client.conf.d/10-bananarchy-audio.conf", "overlay/rootfs/etc/pipewire/pipewire-pulse.conf.d/10-bananarchy-audio.conf", ] UCM_FILES = { "overlay/rootfs/usr/share/alsa/ucm2/codecs/msm8916-wcd/Speaker.conf": ("RX3 Digital Volume", 84), "overlay/rootfs/usr/share/alsa/ucm2/codecs/msm8916-wcd/Headphones.conf": ("RX1 Digital Volume", 84), "overlay/rootfs/usr/share/alsa/ucm2/codecs/msm8916-wcd/Earpiece.conf": ("RX1 Digital Volume", 84), } def read_text(path): with open(path, "r", encoding="utf-8") as handle: return handle.read() def fail(msg): sys.stderr.write(f"[fail] {msg}\n") return 1 def run_c_codec_harness(): gcc = shutil.which("gcc") if not gcc: print("[skip] host gcc unavailable; skipping C codec register verification") return c_src = r""" #include #include #include #define GENMASK(h, l) (((~0U) - (1U << (l)) + 1) & (~0U >> (31 - (h)))) #define BIT(n) (1U << (n)) #define RXn_B5_CTL_INTERP_FS_RATE_MASK GENMASK(7, 5) #define RXn_B5_CTL_INTERP_FS_RATE_SHIFT 5 #define RXn_B5_CTL_INTERP_HALFBAND_EN BIT(3) #define TXn_CLK_FS_CTL_FS_RATE_MASK GENMASK(2, 0) #define SPKR_DRV_CTL_DEF_MASK 0xEFU #define SPKR_DRV_CLASSD_PA_EN_MASK BIT(7) #define SPKR_DRV_CLASSD_PA_EN_ENABLE BIT(7) #define SPKR_DRV_CAL_EN BIT(6) #define SPKR_DRV_SETTLE_EN BIT(5) #define SPKR_DRV_FW_EN BIT(3) #define SPKR_DRV_BOOST_SET BIT(2) #define SPKR_DRV_CMFB_SET BIT(1) #define SPKR_DRV_GAIN_SET BIT(0) #define SPKR_DRV_CTL_NO_BOOST_VAL (SPKR_DRV_CAL_EN | SPKR_DRV_SETTLE_EN | \ SPKR_DRV_FW_EN | SPKR_DRV_GAIN_SET) #define SPKR_DRV_CTL_DEF_VAL (SPKR_DRV_CLASSD_PA_EN_ENABLE | SPKR_DRV_CAL_EN | \ SPKR_DRV_SETTLE_EN | SPKR_DRV_FW_EN | \ SPKR_DRV_BOOST_SET | SPKR_DRV_CMFB_SET | \ SPKR_DRV_GAIN_SET) static uint32_t update_bits(uint32_t cur, uint32_t mask, uint32_t val) { return (cur & ~mask) | (val & mask); } static uint32_t compute_rx_b5(uint32_t cur_b5, unsigned int rate) { uint32_t rx_fs = 3; if (rate == 8000) rx_fs = 0; else if (rate == 16000) rx_fs = 1; else if (rate == 32000) rx_fs = 2; else if (rate == 48000) rx_fs = 3; return update_bits(cur_b5, RXn_B5_CTL_INTERP_FS_RATE_MASK | RXn_B5_CTL_INTERP_HALFBAND_EN, (rx_fs << RXn_B5_CTL_INTERP_FS_RATE_SHIFT) | RXn_B5_CTL_INTERP_HALFBAND_EN); } int main(void) { /* 1. Verify B5_CTL updates fs rate and halfband while preserving DCB switch (BIT 2). */ if (compute_rx_b5(0x00, 48000) != 0x68 || compute_rx_b5(0x04, 48000) != 0x6C || compute_rx_b5(0x6C, 8000) != 0x0C || compute_rx_b5(0x08, 16000) != 0x28 || compute_rx_b5(0x08, 32000) != 0x48) { fprintf(stderr, "RXn_B5_CTL rate transition mismatch\n"); return 1; } /* 2. Verify TXn_CLK_FS_CTL lower 3 bits update without clobbering reserved bits. */ if (update_bits(0x03, TXn_CLK_FS_CTL_FS_RATE_MASK, 0) != 0x00 || update_bits(0x00, TXn_CLK_FS_CTL_FS_RATE_MASK, 3) != 0x03) { fprintf(stderr, "TXn_CLK_FS_CTL update mismatch\n"); return 2; } /* 3. Verify CAJON speaker PA clears BOOST_SET & CMFB_SET (0xE9 vs 0xEF). */ uint32_t drv = 0x29; /* after DAPM sets CAL_EN -> 0x69 */ drv = update_bits(drv, SPKR_DRV_CTL_DEF_MASK & ~SPKR_DRV_CLASSD_PA_EN_MASK, SPKR_DRV_CTL_NO_BOOST_VAL); if (drv != 0x69) { fprintf(stderr, "CAJON pre-PA DRV_CTL expected 0x69, got 0x%x\n", drv); return 3; } drv = update_bits(drv, SPKR_DRV_CLASSD_PA_EN_MASK, SPKR_DRV_CLASSD_PA_EN_ENABLE); if (drv != 0xE9 || (drv & (SPKR_DRV_BOOST_SET | SPKR_DRV_CMFB_SET)) != 0) { fprintf(stderr, "CAJON active DRV_CTL expected 0xE9 without boost bits, got 0x%x\n", drv); return 4; } /* 4. Verify s2 wakeup preserves SPK DAC Switch bit 7 while restoring CAJON 0x03. */ uint32_t spkr_dac_ctl = 0x80; /* SPK DAC Switch ON before standby */ spkr_dac_ctl = update_bits(spkr_dac_ctl, 0x7FU, 0x03U); if (spkr_dac_ctl != 0x83U) { fprintf(stderr, "s2 restore clobbered SPK DAC Switch: 0x%x\n", spkr_dac_ctl); return 5; } return 0; } """ with tempfile.TemporaryDirectory(prefix="ba_audio_q_") as td: src = os.path.join(td, "test_audio_q.c") exe = os.path.join(td, "test_audio_q") with open(src, "w", encoding="utf-8") as handle: handle.write(c_src) subprocess.run([gcc, "-Wall", "-Wextra", "-Werror", "-O2", src, "-o", exe], check=True) subprocess.run([exe], check=True) def check_patch_0015(): if not os.path.isfile(PATCH_0015): return fail("missing patches/kernel/0015-msm8909-wcd-digital-interpolator-cajon-analog.patch") txt = read_text(PATCH_0015) required = [ "msm8916_wcd_digital_reg_defaults", "{ LPASS_CDC_CLK_RX_RESET_CTL, 0x00 }", "{ LPASS_CDC_RX1_B5_CTL, 0x00 }", "{ LPASS_CDC_RX2_B5_CTL, 0x00 }", "{ LPASS_CDC_RX3_B5_CTL, 0x00 }", "{ LPASS_CDC_TX1_CLK_FS_CTL, 0x00 }", "{ LPASS_CDC_TX2_CLK_FS_CTL, 0x00 }", "{ LPASS_CDC_CLK_OTHR_CTL, 0x00 }", "msm8916_wcd_digital_force_sync_ctl", "regmap_write_bits", ".use_pmdown_time\t= 0,", "RXn_B5_CTL_INTERP_FS_RATE_MASK", "TXn_CLK_FS_CTL_FS_RATE_MASK", "digital_cdc_clk_freq", "AFE_PORT_ID_PRIMARY_MI2S_RX", "q6core_query_versions_locked", "core->adsp_version != Q6_ADSP_VERSION_UNKNOWN", "wcd_reg_defaults_cajon_2_0", "wcd_reg_defaults_conga", "pm8916_wcd_is_pm8909", "CDC_D_PERPH_SUBTYPE_CONGA", "{CDC_A_RX_COM_OCP_CTL, 0x12}", "{CDC_A_NCP_FBCTRL, 0x28}", "{CDC_A_NCP_FBCTRL, 0xA8}", "{CDC_A_NCP_VCTRL, 0xA4}", "{CDC_A_RX_HPH_BIAS_PA, 0xFA}", "{CDC_A_SPKR_ANA_BIAS_SET, 0x41}", "{CDC_A_SPKR_DRV_CTL, 0x69}", "SPKR_DRV_CTL_NO_BOOST_VAL", "CDC_A_PERPH_SUBTYPE_CAJON", "pm8916_wcd_analog_enable_hphl_dac", "pm8916_wcd_analog_enable_hphr_dac", "pm8916_wcd_analog_enable_hph_pa", "pm8916_wcd_analog_apply_defaults(component, true);", "snd_soc_component_write(component, CDC_D_PERPH_RESET_CTL4, 0x00);", "snd_soc_component_write(component, CDC_A_PERPH_RESET_CTL4, 0x00);", "ARRAY_SIZE(msm8916_wcd_digital_reg_defaults)", "CDC_A_MBHC_RESULT_2_SWCH_LEVEL_REMOVE", "pm8916_mbhc_plug_present", "DIG_CLK_CTL_D_MBHC_CLK_EN", "CDC_A_MASTER_BIAS_CTL, 0x30", "snd_soc_jack_report(jack, initial_report, hs_jack_mask);", "phys_ins != waiting_ins", ] for tok in required: if tok not in txt: return fail(f"0015 patch missing required token: {tok}") analog_diff = txt.split("diff --git a/sound/soc/codecs/msm8916-wcd-digital.c")[0] if "+ snd_soc_component_write(component, CDC_A_MASTER_BIAS_CTL, 0x00);" in analog_diff: return fail("0015 must not zero CDC_A_MASTER_BIAS_CTL on s2 idle gating") if "+\t{CDC_A_RX_COM_OCP_CTL, 0xD1}" in analog_diff: return fail("0015 must use 0x12 (350 mA) RX_COM_OCP_CTL default, not 0xD1") if ".volatile_reg" in txt: return fail("0015 patch must not set .volatile_reg on msm8916_codec_regmap_config") m = re.search( r"msm8916_wcd_digital_reg_defaults\[\]\s*=\s*\{(.*?)\n\+\};", txt, re.S, ) if not m: return fail("0015 patch missing msm8916_wcd_digital_reg_defaults block") default_entries = re.findall(r"\{\s*(LPASS_CDC_[A-Z0-9_]+),\s*(0x[0-9a-fA-F]+)\s*\}", m.group(1)) if len(default_entries) != 97: return fail(f"0015 msm8916_wcd_digital_reg_defaults expected 97 registers, got {len(default_entries)}") if any(val != "0x00" for _, val in default_entries): return fail("0015 msm8916_wcd_digital_reg_defaults entries must use 0x00 hardware reset defaults") build_txt = read_text(BUILD_KERNEL) if build_txt.count("0015-msm8909-wcd-digital-interpolator-cajon-analog.patch") != 2: return fail("scripts/build-kernel-audio.sh must apply 0015 in both kcache and tarball paths") return 0 def check_wireplumber(): s16_ref = None for rel in WP_S16LE_PATHS: path = os.path.join(BASE_DIR, rel) if not os.path.isfile(path): return fail(f"missing {rel}") raw = read_text(path) if s16_ref is None: s16_ref = raw elif raw != s16_ref: return fail(f"wireplumber msm8916-s16le.conf drifted in {rel}") for tok in ( 'audio.format = "S16LE"', "audio.rate = 48000", 'dither.method = "triangular"', "~alsa_output.platform-7702000.*.HiFi__Speaker__sink", "~alsa_output.platform-sound.*.HiFi__Speaker__sink", "~alsa_output.platform-7702000.*.HiFi__Earpiece__sink", "~alsa_output.platform-sound.*.HiFi__Earpiece__sink", "item.features.mono = true", "channelmix.normalize = true", ): if tok not in s16_ref: return fail(f"msm8916-s16le.conf missing {tok}") for forbidden in ("AUX0", "channelmix.upmix = false"): if forbidden in s16_ref: return fail(f"msm8916-s16le.conf must not contain unpositioned/no-upmix token {forbidden}") create_item_path = os.path.join(BASE_DIR, WP_CREATE_ITEM_LUA) if not os.path.isfile(create_item_path): return fail(f"missing {WP_CREATE_ITEM_LUA}") create_item_txt = read_text(create_item_path) for tok in ( 'Settings.get_boolean ("node.features.audio.mono")', 'cutils.parseBool (properties ["item.features.mono"])', ): if tok not in create_item_txt: return fail(f"{WP_CREATE_ITEM_LUA} missing {tok}") pw_ref = None for rel in PW_STREAM_DROPINS: path = os.path.join(BASE_DIR, rel) if not os.path.isfile(path): return fail(f"missing {rel}") raw = read_text(path) if pw_ref is None: pw_ref = raw elif raw != pw_ref: return fail(f"PipeWire stream drop-in drifted in {rel}") for tok in ("channelmix.normalize = true", 'dither.method = "triangular"'): if tok not in pw_ref: return fail(f"PipeWire stream drop-in missing {tok}") bt_ref = None for rel in WP_BT_PATHS: path = os.path.join(BASE_DIR, rel) raw = read_text(path) if bt_ref is None: bt_ref = raw elif raw != bt_ref: return fail(f"wireplumber 50-bluetooth.conf drifted in {rel}") if "bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ]" not in bt_ref: return fail("50-bluetooth.conf lost bluez5.roles invariant") return 0 def check_gain_staging(): for rel, (ctl_name, max_vol) in UCM_FILES.items(): txt = read_text(os.path.join(BASE_DIR, rel)) matches = re.findall(rf'{re.escape(ctl_name)}\x27\s+(\d+)', txt) if not matches: return fail(f"{rel} missing {ctl_name}") for m in matches: if int(m) > max_vol: return fail(f"{rel} {ctl_name}={m} exceeds 0 dB unity ceiling ({max_vol})") audio_txt = read_text(SXMO_AUDIO) if "bananarchy_set_sink_volume" not in audio_txt or \ "bananarchy_sync_internal_pw_vol" not in audio_txt or \ "[ -d /proc/asound/card0 ]" not in audio_txt or \ "@DEFAULT_AUDIO_SINK@" not in audio_txt or \ 'pactl list short sinks 2>/dev/null | grep -Fq "$sink_name"' not in audio_txt: return fail("sxmo_audio.sh missing PipeWire unity sync guard, @DEFAULT_AUDIO_SINK@, or sink wait") soundmon_txt = read_text(SOUNDMONITOR_C) for tok in ( "has_internal_sink", "internal_synced", "drain_jack_events", "last_hp_plugged", "iface=CARD,name='Headphone Jack'", "iface=CARD,name='Mic Jack'", ): if tok not in soundmon_txt: return fail(f"bananarchy-soundmonitor.c missing {tok}") gcc = shutil.which("gcc") if gcc: with tempfile.TemporaryDirectory(prefix="ba_soundmon_") as td: exe = os.path.join(td, "bananarchy-soundmonitor") bld = subprocess.run( [ gcc, "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror", "-I", os.path.dirname(SOUNDMONITOR_C), SOUNDMONITOR_C, "-o", exe, ], capture_output=True, text=True, ) if bld.returncode != 0: return fail(f"host gcc build of bananarchy-soundmonitor.c failed:\n{bld.stderr}") with tempfile.TemporaryDirectory(prefix="ba_audio_dev_") as td: tmp_dir = os.path.join(td, "tmp") cfg_dir = os.path.join(td, "cfg") bin_dir = os.path.join(td, "bin") os.makedirs(tmp_dir, exist_ok=True) os.makedirs(cfg_dir, exist_ok=True) os.makedirs(bin_dir, exist_ok=True) mock_pactl = os.path.join(bin_dir, "pactl") with open(mock_pactl, "w", encoding="utf-8") as handle: handle.write("#!/bin/sh\nexit 0\n") os.chmod(mock_pactl, 0o755) patched_sh = os.path.join(td, "sxmo_audio.sh") with open(patched_sh, "w", encoding="utf-8") as handle: handle.write(audio_txt.replace("/tmp/", tmp_dir + "/")) env = dict(os.environ) env["XDG_CONFIG_HOME"] = td env["CFG_DIR"] = cfg_dir env["PATH"] = bin_dir + ":" + env.get("PATH", "") # Rewrite CFG_DIR to cfg_dir explicitly via a symlink sxmo -> cfg_dir. os.symlink(cfg_dir, os.path.join(td, "sxmo")) with open(os.path.join(cfg_dir, "audio_out_device"), "w", encoding="utf-8") as handle: handle.write("Headphones\n") with open(os.path.join(cfg_dir, "audio_in_device"), "w", encoding="utf-8") as handle: handle.write("Headset\n") with open(os.path.join(tmp_dir, "sxmo_jack_plugged"), "w", encoding="utf-8") as handle: handle.write("0\n") r_out = subprocess.run(["sh", patched_sh, "device", "get"], env=env, capture_output=True, text=True, check=True) r_in = subprocess.run(["sh", patched_sh, "device", "getinput"], env=env, capture_output=True, text=True, check=True) if r_out.stdout.strip() != "Speaker" or r_in.stdout.strip() != "Mic1": return fail(f"unplugged boot fallback failed: out={r_out.stdout!r} in={r_in.stdout!r}") for p in ("sxmo_audio_out_device", "sxmo_audio_in_device"): fp = os.path.join(tmp_dir, p) if os.path.exists(fp): os.unlink(fp) with open(os.path.join(tmp_dir, "sxmo_jack_plugged"), "w", encoding="utf-8") as handle: handle.write("1\n") r_out2 = subprocess.run(["sh", patched_sh, "device", "get"], env=env, capture_output=True, text=True, check=True) r_in2 = subprocess.run(["sh", patched_sh, "device", "getinput"], env=env, capture_output=True, text=True, check=True) if r_out2.stdout.strip() != "Headphones" or r_in2.stdout.strip() != "Headset": return fail(f"plugged boot preservation failed: out={r_out2.stdout!r} in={r_in2.stdout!r}") probe_script = r""" set -eu . "%s" >/dev/null 2>&1 || true """ % SXMO_AUDIO # Extract pct_to_hw_out + dependencies and evaluate edge percentages with sh res = subprocess.run( [ "sh", "-eu", "-c", f""" eval "$(sed -n '/^normalize_out_dev()/,/^}}/p; /^clamp_pct()/,/^}}/p; /^pct_to_hw_out()/,/^}}/p' '{SXMO_AUDIO}')" for dev in Speaker Headphones Earpiece; do v0="$(pct_to_hw_out "$dev" 0)" v1="$(pct_to_hw_out "$dev" 1)" v85="$(pct_to_hw_out "$dev" 85)" v100="$(pct_to_hw_out "$dev" 100)" printf '%s %s %s %s %s\n' "$dev" "$v0" "$v1" "$v85" "$v100" done """, ], capture_output=True, text=True, check=True, ) expected = { "Speaker": (0, 52, 79, 84), "Earpiece": (0, 52, 79, 84), "Headphones": (0, 51, 78, 83), } for line in res.stdout.strip().splitlines(): dev, v0, v1, v85, v100 = line.split() got = (int(v0), int(v1), int(v85), int(v100)) if got != expected[dev]: return fail(f"sxmo_audio.sh pct_to_hw_out {dev} expected {expected[dev]}, got {got}") ring_txt = read_text(SXMO_RING) if "ring_rx3=$(( 52 +" not in ring_txt or "ring_hp=$(( 51 +" not in ring_txt: return fail("sxmo_hook_ring.sh volume curve out of sync with unity ceiling") for path, label, needles in [ (CALLSCREEN_CPP, "callscreen_plugin.cpp", ["51 + (c * 32 + 50) / 100", "52 + (c * 32 + 50) / 100"]), (FILES_CPP, "files_plugin.cpp", ["52 + (rvol * 32 + 50) / 100", "51 + (rvol * 32 + 50) / 100"]), (RINGTONES_CPP, "ringtones_plugin.cpp", ["52 + (rvol * 32 + 50) / 100", "51 + (rvol * 32 + 50) / 100"]), (XDRAWER_CPP, "xdrawer.cpp", ["rx1 >= 83", "rx3 >= 84", "51 + std::lround", "52 + std::lround"]), ]: txt = read_text(path) for n in needles: if n not in txt: return fail(f"{label} missing synced gain staging expression: {n}") return 0 def main(): for fn in (check_patch_0015, check_wireplumber, check_gain_staging): rc = fn() if rc != 0: return rc run_c_codec_harness() print("[ok] 0015 WCD digital 48 kHz interpolator, CAJON analog codec, WirePlumber item.features.mono downmix, and <= 0 dB gain staging passed") return 0 if __name__ == "__main__": sys.exit(main())