#!/usr/bin/env python3 """ xoverlab.py - adjust the sound of Klipsch The Fives by patching the official firmware update files. * DSP image (DSPTFV02.bin / DSPTFV03.bin, ADAU145x SigmaDSP, 8.24 format): - sub-out crossover: sub low-pass + speaker high-passes (stock 80 Hz) - sub-out level and polarity - woofer/tweeter crossover (stock ~2.35 kHz) and tweeter level - Klipsch's tonal EQ (peaking filters) and the fixed bass boost * MCU firmware (MCUTFV02/03.bin, FIVESMCU.bin): - dynamic bass curve (boost vs. volume step), maximum boost and range UNOFFICIAL. Flashing a modified image can brick the speaker or damage drivers. Use at your own risk. How the DSP patch works * Biquads are stored as 5 big-endian 8.24 words: B2 B1 B0 A2 A1 (SigmaStudio order, feedback coefficients already negated). * Low-/high-pass sections use the RBJ form with a passband gain; peaking sections use the RBJ peaking form. Both are verified bit-exact (round-trip self-test) against the file before anything is changed. * Sections are found by type and position, not fixed offsets. * Only the targeted sections and the image checksum change. Sample rate: the DSP is assumed to run at 96 kHz (--fs). At 96 kHz the sub crossover is the standard 80 Hz, matching the older ADAU1701-class image. Usage python3 xoverlab.py info DSPTFV03.bin python3 xoverlab.py patch DSPTFV03.bin -o out/DSPTFV03.bin --sub-xover 120 python3 xoverlab.py patch DSPTFV03.bin -o out/DSPTFV03.bin --sub-level -3 --tweeter-level -1.5 python3 xoverlab.py patch DSPTFV03.bin -o out/DSPTFV03.bin --sub-invert python3 xoverlab.py patch DSPTFV03.bin -o out/DSPTFV03.bin --eq 0x045c:0 --bass-boost 4 python3 xoverlab.py patch DSPTFV03.bin -o out/DSPTFV03.bin --eq-flat python3 xoverlab.py patch DSPTFV03.bin -o out/DSPTFV03.bin --scale 1.10 Dynamic bass (patches the MCU file, not the DSP file): python3 xoverlab.py dynbass MCUTFV03.bin --knee 24 --rate 1.0 # preview python3 xoverlab.py dynbass MCUTFV03.bin --knee 24 --rate 1.0 -o out/MCUTFV03.bin # "more dynamic, less fixed": DSP --bass-boost 0 together with python3 xoverlab.py dynbass MCUTFV03.bin --dyn-max 24 --i-reduced-fixed-boost -o out/MCUTFV03.bin """ import argparse import math import os import struct import sys Q24 = 1 << 24 LSB_TOL = 3 # allowed rounding difference (in LSBs) for the self-test DEFAULT_FS = 96000 # safety limits for level / EQ edits SUB_LEVEL_RANGE = (-12.0, 6.0) TWEETER_LEVEL_RANGE = (-6.0, 3.0) EQ_GAIN_RANGE = (-15.0, 6.0) EQ_Q_RANGE = (0.3, 10.0) EQ_FREQ_RANGE = (20.0, 20000.0) # ---------------------------------------------------------------- fixed point def to_float(word): return struct.unpack(">i", word)[0] / Q24 def to_word(x): v = int(round(x * Q24)) if not -(1 << 31) <= v < (1 << 31): raise ValueError("coefficient %r out of 8.24 range" % x) return struct.pack(">i", v) def read_slot(data, off): return [to_float(data[off + 4 * k: off + 4 * k + 4]) for k in range(5)] def raw_ints(data, off): return [struct.unpack(">i", data[off + 4 * k: off + 4 * k + 4])[0] for k in range(5)] # ------------------------------------------------------------------- checksum def words_sum(data, end): return sum(struct.unpack(">I", data[i:i + 4])[0] for i in range(0, end, 4)) & 0xFFFFFFFF def find_checksum(data): """Offset of the word equal to the 32-bit sum of all words before the word preceding it (layout: ...data | 4-byte field | checksum). Must be unique.""" hits = [] prefix = [0] for i in range(0, len(data) - 3, 4): prefix.append((prefix[-1] + struct.unpack(">I", data[i:i + 4])[0]) & 0xFFFFFFFF) for pos in range(8, len(data) - 3, 4): val = struct.unpack(">I", data[pos:pos + 4])[0] if val and val == prefix[(pos - 4) // 4]: hits.append(pos) return hits # -------------------------------------------------------------------- filters def decode(slot): """Classify a slot as a 2nd-order LP/HP. Returns dict or None. Tolerances allow a few LSB of quantisation (low-frequency low-passes have numerator coefficients of only ~100 LSB). gain is linear and may be negative (inverted polarity).""" B2, B1, B0, A2, A1 = slot if not (-1 < A2 < 0 and 0 < A1 < 2) or B0 == 0: return None alpha = (1 + A2) / (1 - A2) c = A1 * (1 + alpha) / 2 if not -1 < c < 1: return None w0 = math.acos(c) q = math.sin(w0) / (2 * alpha) lsb = 3.0 / Q24 if abs(B0 - B2) > max(1e-5 * abs(B0), lsb): return None tol = max(3e-4 * abs(B0), 2 * lsb) if abs(B1 - 2 * B0) < tol: kind = "LP" gain = B0 * (1 + alpha) / ((1 - c) / 2) elif abs(B1 + 2 * B0) < tol: kind = "HP" gain = B0 * (1 + alpha) / ((1 + c) / 2) else: return None return {"kind": kind, "w0": w0, "q": q, "gain": gain} def decode_peak(slot): """Classify a slot as an RBJ peaking EQ. Returns dict (gain in dB) or None.""" B2, B1, B0, A2, A1 = slot if not (-1 < A2 < 0 and 0 < A1 < 2): return None if abs(B1 + A1) > 4.0 / Q24: # peaking: b1 == a1 (a1 stored negated) return None beta = (1 + A2) / (1 - A2) # alpha / A c = A1 * (1 + beta) / 2 if not -1 < c < 1: return None alpha_a = B0 * (1 + beta) - 1 # alpha * A if alpha_a <= 0: return None A = math.sqrt(alpha_a / beta) w0 = math.acos(c) alpha = beta * A return {"kind": "PK", "w0": w0, "q": math.sin(w0) / (2 * alpha), "gain_db": 40 * math.log10(A)} def design(kind, w0, q, gain): """RBJ 2nd-order LP/HP with linear passband gain -> [B2,B1,B0,A2,A1].""" c, s = math.cos(w0), math.sin(w0) alpha = s / (2 * q) a0 = 1 + alpha if kind == "LP": b0 = (1 - c) / 2 * gain b1 = (1 - c) * gain else: b0 = (1 + c) / 2 * gain b1 = -(1 + c) * gain b2 = b0 A1 = 2 * c / a0 A2 = -(1 - alpha) / a0 return [b2 / a0, b1 / a0, b0 / a0, A2, A1] def design_peak(w0, q, gain_db): """RBJ peaking EQ -> [B2,B1,B0,A2,A1].""" A = 10 ** (gain_db / 40) c = math.cos(w0) alpha = math.sin(w0) / (2 * q) a0 = 1 + alpha / A return [(1 - alpha * A) / a0, -2 * c / a0, (1 + alpha * A) / a0, -(1 - alpha / A) / a0, 2 * c / a0] IDENTITY = [0.0, 0.0, 1.0, 0.0, 0.0] # pass-through biquad (B2 B1 B0 A2 A1) HP_Q_STOCK_MAX = 0.75 # speaker high-pass Q may only go down from ~0.71 without consent HP_Q_RANGE = (0.5, 1.0) SUB_Q_RANGE = (0.5, 0.9) EXPERT_LIMITS = { # same values as Limits.expert in the macOS app "SUB_LEVEL_RANGE": (-24.0, 12.0), "TWEETER_LEVEL_RANGE": (-12.0, 6.0), "EQ_GAIN_RANGE": (-24.0, 12.0), "EQ_Q_RANGE": (0.2, 16.0), "HP_Q_RANGE": (0.4, 1.5), "SUB_Q_RANGE": (0.4, 1.4), "FIXED_BOOST_MAX": 18.0, "FIXED_FREQ_RANGE": (15.0, 200.0), "FIXED_Q_RANGE": (0.2, 4.0), "DYN_MAX_LIMIT": 36.0, "DYN_FREQ_RANGE": {"shelf": (15.0, 250.0), "peak": (15.0, 300.0)}, "DYN_Q_RANGE": {"shelf": (0.3, 2.0), "peak": (0.2, 5.0)}, "RATE_RANGE": (0.5, 10.0), "XOVER_SCALE_RANGE": (0.25, 4.0), "ALWAYS_HP_MAX": 300.0, } RATE_RANGE = (0.5, 4.0) XOVER_SCALE_RANGE = (0.5, 2.0) ALWAYS_HP_MAX = 160.0 # Hz at 96 kHz def apply_expert_limits(): """Loosen all user limits (hard checks - coefficient range and stability - stay).""" globals().update(EXPERT_LIMITS) def is_stable(slot): """Both poles inside the unit circle (y = ... + A1*y1 + A2*y2).""" A2, A1 = slot[3], slot[4] return abs(A2) < 1 - 1e-9 and abs(A1) < 1 - A2 - 1e-12 def design_any(d): if d["kind"] == "ID": return list(IDENTITY) if d["kind"] == "PK": return design_peak(d["w0"], d["q"], d["gain_db"]) return design(d["kind"], d["w0"], d["q"], d["gain"]) def decode_any(slot, kind): if kind == "ID": return {"kind": "ID", "w0": 1.0, "q": 0.0, "gain": 1.0} if slot == IDENTITY else None return decode_peak(slot) if kind == "PK" else decode(slot) def encode(slot): return b"".join(to_word(x) for x in slot) def fnorm(d): """Frequency expressed at 48 kHz: used for sample-rate independent thresholds.""" return d["w0"] * 48000 / (2 * math.pi) BASS_REGION_END = 0x0800 # bass-management filters live below this offset (v02 and v03) EQ_REGION_START = 0x0400 # Klipsch's tonal EQ lives above this offset def find_sections(data, limit): """Return dict of section groups: sub_lp sub-out low-pass (2 sections) main_hp speaker high-pass, active when a sub is plugged in or Dynamic Bass is on (before sub_lp) always_hp woofer protection high-pass, always in the path (after sub_lp, e.g. 0x07B0) woofer_lp woofer low-pass of the woofer/tweeter crossover tweeter_hp tweeter high-pass of the woofer/tweeter crossover bass_boost fixed bass-boost peaking filter of the Dynamic-Bass block (just before main_hp) eq Klipsch's tonal EQ peaking filters (non-flat) Bass and tweeter high-passes are separated by position, because a raised bass high-pass can reach the frequency range of a lowered tweeter high-pass.""" found, peaks = [], [] for off in range(0, limit - 19, 4): slot = read_slot(data, off) d = decode(slot) if d: found.append((off, d)) continue p = decode_peak(slot) if p and abs(p["gain_db"]) >= 0.05: peaks.append((off, p)) groups = {"sub_lp": [], "main_hp": [], "always_hp": [], "woofer_lp": [], "tweeter_hp": [], "bass_boost": [], "eq": []} bass_hp = [] for off, d in found: fn = fnorm(d) if d["kind"] == "LP" and fn >= 300: groups["woofer_lp"].append((off, d)) elif d["kind"] == "LP" and fn < 150: # stock 40 (x2 limit = 80) at 48 kHz terms groups["sub_lp"].append((off, d)) elif d["kind"] == "HP" and off >= BASS_REGION_END and 90 < fn < 8000: groups["tweeter_hp"].append((off, d)) elif d["kind"] == "HP" and off < BASS_REGION_END and fn < 150: bass_hp.append((off, d)) if groups["sub_lp"]: first_lp = groups["sub_lp"][0][0] last_lp = groups["sub_lp"][-1][0] for off, d in bass_hp: if first_lp - 0x40 <= off < first_lp: groups["main_hp"].append((off, d)) elif off > last_lp: groups["always_hp"].append((off, d)) main_off = groups["main_hp"][0][0] if groups["main_hp"] else None for off, p in peaks: if main_off is not None and off == main_off - 20: groups["bass_boost"].append((off, p)) elif off >= EQ_REGION_START: groups["eq"].append((off, p)) return groups GROUP_INFO = { # name: (label, expected count) "sub_lp": ("Sub-out low-pass", 2), "main_hp": ("Speaker high-pass (sub connected / DB)", 1), "always_hp": ("Woofer protection HP (always on)", 1), "woofer_lp": ("Woofer low-pass", 2), "tweeter_hp": ("Tweeter high-pass", 2), "bass_boost": ("Fixed bass boost (Dynamic Bass)", 1), "eq": ("Factory tonal EQ", None), } GROUP_ORDER = ("sub_lp", "main_hp", "always_hp", "woofer_lp", "tweeter_hp", "bass_boost", "eq") XOVER_GROUPS = ("sub_lp", "main_hp", "always_hp", "woofer_lp", "tweeter_hp") # ----------------------------------------------------------------------- main def load(path): with open(path, "rb") as fh: data = bytearray(fh.read()) if data[:1] != b"\xaa" or len(data) < 0x1000: sys.exit("error: %s does not look like a DSPTFVxx (ADAU145x) image. " "FIVESDSP files (a different DSP chip) are not supported." % path) cs = find_checksum(data) if len(cs) != 1: sys.exit("error: could not locate a unique valid checksum (found %d). " "Refusing to touch this file." % len(cs)) return data, cs[0] def hz(d, fs): return d["w0"] * fs / (2 * math.pi) def level_text(d): """Gain/polarity text for any section.""" if d["kind"] == "ID": return "pass-through" if d["kind"] == "PK": return "gain=%+.2f dB" % d["gain_db"] g = d["gain"] return "gain=%+.2f dB%s" % (20 * math.log10(abs(g)), " INVERTED" if g < 0 else "") def describe(off, d, fs): kind = {"LP": "low-pass ", "HP": "high-pass", "PK": "peaking "}[d["kind"]] return "@0x%04x %s fc=%8.1f Hz Q=%.3f %s" % (off, kind, hz(d, fs), d["q"], level_text(d)) def self_test(data, sections): for off, d in sections: regen = [struct.unpack(">i", to_word(x))[0] for x in design_any(d)] orig = raw_ints(data, off) err = max(abs(a - b) for a, b in zip(regen, orig)) if err > LSB_TOL: sys.exit("error: self-test failed at 0x%04x (max diff %d LSB). The filter " "model does not match this file; refusing to patch." % (off, err)) def all_sections(groups): return [s for g in groups.values() for s in g] def cmd_info(a): data, cs = load(a.file) groups = find_sections(data, cs) print("file : %s (%d bytes)" % (a.file, len(data))) print("checksum : 0x%08x at 0x%04x (valid)" % (struct.unpack(">I", data[cs:cs + 4])[0], cs)) print("fs assumed: %d Hz" % a.fs) for name in GROUP_ORDER: label, _ = GROUP_INFO[name] print("\n%s sections:" % label) for off, d in groups[name]: print(" " + describe(off, d, a.fs)) if not groups[name]: print(" (none found)") self_test(data, all_sections(groups)) print("\nself-test : OK (sections regenerate bit-exact within %d LSB)" % LSB_TOL) def ref_hz(sections, fs): return max(hz(d, fs) for _, d in sections) def parse_eq(spec, fs): """'0x045c:GAIN[:FREQ[:Q]]' -> (offset, gain_db, freq or None, q or None).""" parts = spec.split(":") if not 2 <= len(parts) <= 4: sys.exit("error: --eq expects OFFSET:GAIN[:FREQ[:Q]], e.g. 0x045c:-1.5") try: off = int(parts[0], 16) gain = float(parts[1]) freq = float(parts[2]) if len(parts) > 2 and parts[2] else None q = float(parts[3]) if len(parts) > 3 and parts[3] else None except ValueError: sys.exit("error: could not parse --eq %s" % spec) return off, gain, freq, q def cmd_patch(a): if a.expert: apply_expert_limits() data, cs = load(a.file) groups = find_sections(data, cs) self_test(data, all_sections(groups)) # ---- crossover frequency scale factors per group k = {} if a.scale: k["woofer_lp"] = k["tweeter_hp"] = a.scale if a.xover: k["woofer_lp"] = k["tweeter_hp"] = a.xover / ref_hz(groups["woofer_lp"], a.fs) if a.lp: k["woofer_lp"] = a.lp / ref_hz(groups["woofer_lp"], a.fs) if a.hp: k["tweeter_hp"] = a.hp / ref_hz(groups["tweeter_hp"], a.fs) if groups["sub_lp"]: sub_ref = ref_hz(groups["sub_lp"], a.fs) if a.sub_xover: k["sub_lp"] = k["main_hp"] = a.sub_xover / sub_ref if a.sub_lp: k["sub_lp"] = a.sub_lp / sub_ref if a.main_hp: k["main_hp"] = a.main_hp / sub_ref elif a.sub_xover or a.sub_lp or a.main_hp: sys.exit("error: no sub-out crossover found in this image") always_target = None if a.speaker_hp_always or a.always_hp: if not groups["always_hp"] or not groups["main_hp"]: sys.exit("error: no always-on speaker high-pass found in this image") if a.always_hp: always_target = a.always_hp else: # follow the (new) main speaker high-pass frequency always_target = ref_hz(groups["main_hp"], a.fs) * min(2.0, max(0.5, k.get("main_hp", 1.0))) # Values within 0.5% of a limit are clamped to it (stock sub filter is 79.98 Hz, so # "160 Hz" is x2.0005); this matches the macOS app, which clamps to 0.5...2.0. lo, hi = XOVER_SCALE_RANGE k = {g: (min(hi, max(lo, v)) if lo * 0.995 <= v <= hi * 1.005 else v) for g, v in k.items()} if always_target is not None: k["always_hp"] = always_target / ref_hz(groups["always_hp"], a.fs) k = {g: v for g, v in k.items() if abs(v - 1) > 1e-9} # structure and safety checks for crossover changes for g in k: label, expected = GROUP_INFO[g] if len(groups[g]) != expected and not a.force: sys.exit("error: found %d %s sections (expected %d). Use --force only if you have " "checked `info` output." % (len(groups[g]), label.lower(), expected)) if g == "always_hp": new_hz = ref_hz(groups[g], a.fs) * k[g] max_hz = ALWAYS_HP_MAX * a.fs / DEFAULT_FS if new_hz > max_hz * 1.005: sys.exit("error: always-on speaker high-pass %.0f Hz is above the %.0f Hz limit" % (new_hz, max_hz)) if k[g] < 0.999 and not a.i_accept_woofer_risk: sys.exit("error: lowering the always-on speaker high-pass below stock sends more deep " "bass to the woofer. Add --i-accept-woofer-risk to override.") if k[g] < XOVER_SCALE_RANGE[0]: sys.exit("error: always-on speaker high-pass change x%.2f is below x%.2f" % (k[g], XOVER_SCALE_RANGE[0])) elif not XOVER_SCALE_RANGE[0] <= k[g] <= XOVER_SCALE_RANGE[1]: sys.exit("error: %s change x%.2f outside the allowed %.2f-%.1f range" % (label.lower(), k[g], XOVER_SCALE_RANGE[0], XOVER_SCALE_RANGE[1])) if k.get("tweeter_hp", 1) < 0.85 and not a.i_accept_tweeter_risk: sys.exit("error: lowering the tweeter high-pass by more than 15%% (x%.2f) risks " "tweeter damage. Add --i-accept-tweeter-risk to override." % k["tweeter_hp"]) if k.get("main_hp", 1) < 0.85 and not a.i_accept_woofer_risk: sys.exit("error: lowering the main-speaker high-pass by more than 15%% (x%.2f) sends " "more deep bass to the 4.5\" woofer (more excursion/distortion). Add " "--i-accept-woofer-risk to override." % k["main_hp"]) # ---- per-section edits: offset -> (label, original, new) edits = {} def edit(off, label, orig): if off not in edits: edits[off] = [label, orig, dict(orig)] return edits[off][2] for g in XOVER_GROUPS: if g in k: for off, d in groups[g]: n = edit(off, GROUP_INFO[g][0], d) n["w0"] = d["w0"] * k[g] def need(group, what): if len(groups[group]) != (GROUP_INFO[group][1] or len(groups[group])) or not groups[group]: sys.exit("error: cannot apply %s: expected %s %s section(s), found %d" % (what, GROUP_INFO[group][1], GROUP_INFO[group][0].lower(), len(groups[group]))) if a.sub_level is not None: lo, hi = SUB_LEVEL_RANGE if not lo <= a.sub_level <= hi: sys.exit("error: --sub-level must be %+.0f..%+.0f dB" % (lo, hi)) need("sub_lp", "--sub-level") off, d = groups["sub_lp"][0] n = edit(off, GROUP_INFO["sub_lp"][0], d) n["gain"] = n["gain"] * 10 ** (a.sub_level / 20) if a.sub_invert: need("sub_lp", "--sub-invert") off, d = groups["sub_lp"][0] n = edit(off, GROUP_INFO["sub_lp"][0], d) n["gain"] = -n["gain"] # ---- Q and slope of the sub-out crossover if a.sub_q is not None: if not SUB_Q_RANGE[0] <= a.sub_q <= SUB_Q_RANGE[1]: sys.exit("error: --sub-q must be %.1f..%.1f" % SUB_Q_RANGE) need("sub_lp", "--sub-q") for off, d in groups["sub_lp"]: edit(off, GROUP_INFO["sub_lp"][0], d)["q"] = a.sub_q if a.sub_slope == 12: need("sub_lp", "--sub-slope") off, d = groups["sub_lp"][1] edit(off, GROUP_INFO["sub_lp"][0], d)["kind"] = "ID" for opt, group in (("main_hp_q", "main_hp"), ("always_hp_q", "always_hp")): q = getattr(a, opt) if q is None: continue if not HP_Q_RANGE[0] <= q <= HP_Q_RANGE[1]: sys.exit("error: --%s must be %.1f..%.1f" % (opt.replace("_", "-"), HP_Q_RANGE[0], HP_Q_RANGE[1])) if q > HP_Q_STOCK_MAX and not a.i_accept_woofer_risk: sys.exit("error: a speaker high-pass Q above %.2f adds a bump (more woofer excursion) just above " "the crossover. Add --i-accept-woofer-risk to override." % HP_Q_STOCK_MAX) need(group, "--" + opt.replace("_", "-")) off, d = groups[group][0] edit(off, GROUP_INFO[group][0], d)["q"] = q if a.tweeter_level is not None: lo, hi = TWEETER_LEVEL_RANGE if not lo <= a.tweeter_level <= hi: sys.exit("error: --tweeter-level must be %+.0f..%+.0f dB" % (lo, hi)) need("tweeter_hp", "--tweeter-level") off, d = max(groups["tweeter_hp"], key=lambda s: s[1]["w0"]) n = edit(off, GROUP_INFO["tweeter_hp"][0], d) n["gain"] = n["gain"] * 10 ** (a.tweeter_level / 20) if a.bass_boost is not None or a.bass_boost_freq is not None or a.bass_boost_q is not None: need("bass_boost", "--bass-boost") off, d = groups["bass_boost"][0] n = edit(off, GROUP_INFO["bass_boost"][0], d) if a.bass_boost is not None: if not 0 <= a.bass_boost <= FIXED_BOOST_MAX: sys.exit("error: --bass-boost must be 0..%.0f dB" % FIXED_BOOST_MAX) if a.bass_boost > d["gain_db"] + 0.01 and not a.i_accept_woofer_risk: sys.exit("error: --bass-boost above stock (%.1f dB) adds deep bass (more woofer excursion). " "Add --i-accept-woofer-risk to override." % d["gain_db"]) n["gain_db"] = a.bass_boost if a.bass_boost_freq is not None: if not FIXED_FREQ_RANGE[0] <= a.bass_boost_freq <= FIXED_FREQ_RANGE[1]: sys.exit("error: --bass-boost-freq must be %.0f..%.0f Hz" % FIXED_FREQ_RANGE) n["w0"] = 2 * math.pi * a.bass_boost_freq / a.fs if a.bass_boost_q is not None: if not FIXED_Q_RANGE[0] <= a.bass_boost_q <= FIXED_Q_RANGE[1]: sys.exit("error: --bass-boost-q must be %.1f..%.1f" % FIXED_Q_RANGE) n["q"] = a.bass_boost_q eq_by_off = dict(groups["eq"]) if a.eq_flat: for off, d in groups["eq"]: edit(off, GROUP_INFO["eq"][0], d)["gain_db"] = 0.0 for spec in a.eq or []: off, gain, freq, q = parse_eq(spec, a.fs) if off not in eq_by_off: sys.exit("error: 0x%04x is not one of the EQ filters listed by `info`" % off) lo, hi = EQ_GAIN_RANGE if not lo <= gain <= hi: sys.exit("error: EQ gain must be %+.0f..%+.0f dB" % (lo, hi)) n = edit(off, GROUP_INFO["eq"][0], eq_by_off[off]) n["gain_db"] = gain if freq is not None: if not EQ_FREQ_RANGE[0] <= freq <= min(EQ_FREQ_RANGE[1], 0.45 * a.fs): sys.exit("error: EQ frequency must be %.0f..%.0f Hz" % EQ_FREQ_RANGE) n["w0"] = 2 * math.pi * freq / a.fs if q is not None: if not EQ_Q_RANGE[0] <= q <= EQ_Q_RANGE[1]: sys.exit("error: EQ Q must be %.1f..%.1f" % EQ_Q_RANGE) n["q"] = q if not edits: sys.exit("error: nothing to do; see --help for the available changes") # ---- apply out = bytearray(data) print("Changes (fs assumed %d Hz):" % a.fs) for off in sorted(edits): label, d, n = edits[off] if n["kind"] != "ID" and not 0 < n["w0"] < math.pi * 0.45: sys.exit("error: new frequency out of range at 0x%04x" % off) out[off:off + 20] = encode(design_any(n)) if n["kind"] != "ID" and not is_stable(read_slot(out, off)): sys.exit("error: the filter at 0x%04x would be unstable with these settings; nothing written" % off) chk = decode_any(read_slot(out, off), n["kind"]) if chk is None or chk["kind"] != n["kind"]: sys.exit("internal error: patched section at 0x%04x does not decode" % off) if n["kind"] == "ID": print(" %-38s @0x%04x %8.1f Hz Q %.3f %s -> pass-through (section disabled)" % ( label, off, hz(d, a.fs), d["q"], level_text(d))) else: print(" %-38s @0x%04x %8.1f Hz Q %.3f %s -> %8.1f Hz Q %.3f %s" % ( label, off, hz(d, a.fs), d["q"], level_text(d), hz(chk, a.fs), chk["q"], level_text(chk))) new_cs = words_sum(out, cs - 4) out[cs:cs + 4] = struct.pack(">I", new_cs) if find_checksum(out) != [cs]: sys.exit("internal error: checksum verification failed; nothing written") diff = [i for i in range(len(data)) if data[i] != out[i]] allowed = set(range(cs, cs + 4)) for off in edits: allowed.update(range(off, off + 20)) if not set(diff) <= allowed: sys.exit("internal error: bytes changed outside target sections; nothing written") if os.path.abspath(a.output) == os.path.abspath(a.file): sys.exit("error: refusing to overwrite the input file") os.makedirs(os.path.dirname(os.path.abspath(a.output)), exist_ok=True) with open(a.output, "wb") as fh: fh.write(out) print("\nchecksum : 0x%08x -> 0x%08x" % (struct.unpack(">I", data[cs:cs + 4])[0], new_cs)) print("written : %s (%d bytes changed)" % (a.output, len(diff))) print("Keep the original file name (e.g. DSPTFV03.bin) when copying to the update USB stick.") # ------------------------------------------------------------ dynamic bass # The MCU firmware holds # * a 61-byte table: volume step (0..60) -> dynamic-bass index (0..40), and # * 41 pre-computed RBJ low-shelf filters (50 Hz at 96 kHz, Q 1/sqrt(2)), index i = +0.5*i dB # (0 to +20 dB), which the MCU writes into the DSP (slot 0x0188). Verified bit-exact. # Stock curve: +20 dB up to step 20, then -0.5 dB per volume step, 0 dB at step 60. # While Dynamic Bass is on, the DSP adds a fixed peaking boost (+8 dB at 40 Hz, Q 0.5). DB_STEPS = 61 DB_MAXIDX = 40 DB_STOCK_MAX_DB = 20.0 DB_STOCK = bytes([40] * 21 + list(range(39, -1, -1))) SHELF_F0_NORM = 50.0 / 96000.0 # corner frequency / sample rate (stock) SHELF_Q = 1 / math.sqrt(2) # stock DYN_MAX_LIMIT = 28.0 # ceiling for the dynamic boost (dB); above 20 needs consent or a lower fixed boost DYN_FREQ_RANGE = {"shelf": (30.0, 120.0), "peak": (25.0, 150.0)} # Hz at 96 kHz DYN_Q_RANGE = {"shelf": (0.5, 1.0), "peak": (0.4, 2.0)} FIXED_BOOST_MAX = 12.0 # fixed (DSP) bass boost ceiling (stock +8 dB) FIXED_FREQ_RANGE = (25.0, 120.0) FIXED_Q_RANGE = (0.3, 2.0) def design_low_shelf(w0, q, gain_db): """RBJ low shelf -> [B2,B1,B0,A2,A1].""" A = 10 ** (gain_db / 40) c = math.cos(w0) r = 2 * math.sqrt(A) * math.sin(w0) / (2 * q) b0 = A * ((A + 1) - (A - 1) * c + r) b1 = 2 * A * ((A - 1) - (A + 1) * c) b2 = A * ((A + 1) - (A - 1) * c - r) a0 = (A + 1) + (A - 1) * c + r a1 = -2 * ((A - 1) + (A + 1) * c) a2 = (A + 1) + (A - 1) * c - r return [b2 / a0, b1 / a0, b0 / a0, -a2 / a0, -a1 / a0] def boost_table_bytes(max_db, kind="shelf", f0_norm=SHELF_F0_NORM, q=SHELF_Q): """41 boost filters, entry i = i/40 * max_db. Stock: low shelf, 50 Hz @ 96 kHz, Q 1/sqrt2, 20 dB. kind 'peak' uses RBJ peaking filters at f0 instead (boosts around f0 only).""" w0 = 2 * math.pi * f0_norm design_fn = design_low_shelf if kind == "shelf" else (lambda w, qq, g: design_peak(w, qq, g)) return b"".join(encode(design_fn(w0, q, max_db * i / DB_MAXIDX)) for i in range(DB_MAXIDX + 1)) # Tone controls (MCU): the MCU writes one filter per knob position into the DSP. # bass : 16 RBJ low shelves, 200 Hz @ 96 kHz, Q 1/sqrt2, gain (i - 9) dB -> position 9 = 0 dB (DSP 0x0344) # mid : 17 RBJ peaks, 1 kHz, Q 0.5, gain (i - 10) dB; position 10 stored as pass-through (DSP 0x036C) # treble: 17 RBJ high shelves, 4 kHz, Q 1/sqrt2, gain (i - 10) dB; position 10 stored as a # 0 dB peak (DSP 0x0358) # All three regenerate bit-exact. BASS_ZERO, MID_ZERO, TREBLE_ZERO = 9, 10, 10 BASS_STEPS, MID_STEPS, TREBLE_STEPS = 16, 17, 17 def design_high_shelf(w0, q, gain_db): """RBJ high shelf -> [B2,B1,B0,A2,A1].""" A = 10 ** (gain_db / 40) c = math.cos(w0) r = 2 * math.sqrt(A) * math.sin(w0) / (2 * q) b0 = A * ((A + 1) + (A - 1) * c + r) b1 = -2 * A * ((A - 1) + (A + 1) * c) b2 = A * ((A + 1) + (A - 1) * c - r) a0 = (A + 1) - (A - 1) * c + r a1 = 2 * ((A - 1) - (A + 1) * c) a2 = (A + 1) - (A - 1) * c - r return [b2 / a0, b1 / a0, b0 / a0, -a2 / a0, -a1 / a0] def bass_tone_bytes(): w0 = 2 * math.pi * 200.0 / 96000.0 return b"".join(encode(design_low_shelf(w0, SHELF_Q, float(i - BASS_ZERO))) for i in range(BASS_STEPS)) def mid_tone_bytes(): w0 = 2 * math.pi * 1000.0 / 96000.0 return b"".join(encode(IDENTITY if i == MID_ZERO else design_peak(w0, 0.5, float(i - MID_ZERO))) for i in range(MID_STEPS)) def treble_tone_bytes(): w0 = 2 * math.pi * 4000.0 / 96000.0 return b"".join(encode(design_peak(w0, SHELF_Q, 0.0) if i == TREBLE_ZERO else design_high_shelf(w0, SHELF_Q, float(i - TREBLE_ZERO))) for i in range(TREBLE_STEPS)) def parse_band(spec, what): """'F:G[:Q]' (Hz at 96 kHz, dB, Q) -> (f, g, q).""" parts = spec.split(":") try: f, g = float(parts[0]), float(parts[1]) q = float(parts[2]) if len(parts) > 2 else 4.0 except (ValueError, IndexError): sys.exit("error: %s expects FREQ:GAIN[:Q], e.g. 194:-7:6.5" % what) if not EQ_FREQ_RANGE[0] <= f <= EQ_FREQ_RANGE[1]: sys.exit("error: %s frequency must be %.0f..%.0f Hz" % ((what,) + EQ_FREQ_RANGE)) if not EQ_GAIN_RANGE[0] <= g <= EQ_GAIN_RANGE[1]: sys.exit("error: %s gain must be %+.0f..%+.0f dB" % ((what,) + EQ_GAIN_RANGE)) if not EQ_Q_RANGE[0] <= q <= EQ_Q_RANGE[1]: sys.exit("error: %s Q must be %.1f..%.1f" % ((what,) + EQ_Q_RANGE)) return f, g, q def find_all(data, needle): hits = [] i = data.find(needle) while i != -1: hits.append(i) i = data.find(needle, i + 1) return hits def find_dynbass(data): return find_all(data, DB_STOCK) def build_curve(knee, rate, stock, max_boost=None, db_per_index=0.5): """Stock values up to `knee`; above it the boost falls `rate` dB per volume step from the value at the knee. Optionally capped at `max_boost` dB. Never exceeds the stock index anywhere.""" cap = DB_MAXIDX if max_boost is None else int(round(max_boost / db_per_index)) out = [] start = stock[knee] * db_per_index for s in range(DB_STEPS): if s <= knee: v = stock[s] else: v = int(round(max(0.0, start - rate * (s - knee)) / db_per_index)) v = min(v, stock[s]) out.append(max(0, min(DB_MAXIDX, cap, v))) return bytes(out) def cmd_dynbass(a): if a.expert: apply_expert_limits() with open(a.file, "rb") as fh: data = bytearray(fh.read()) if len(data) < 0x8000 or struct.unpack("> 24 != 0x08: sys.exit("error: %s does not look like an MCU firmware file (MCUTFVxx / FIVESMCU)" % a.file) hits = find_dynbass(data) if len(hits) != 1: sys.exit("error: stock dynamic-bass table found %d times (need exactly 1). Use an " "unmodified original MCU file." % len(hits)) off = hits[0] stock = list(DB_STOCK) dyn_max = DB_STOCK_MAX_DB if a.dyn_max is None else a.dyn_max kind = a.dyn_type f0 = a.dyn_freq if a.dyn_freq is not None else (50.0 if kind == "shelf" else 50.0) q = a.dyn_q if a.dyn_q is not None else (SHELF_Q if kind == "shelf" else 0.7) lo, hi = DYN_FREQ_RANGE[kind] if not lo <= f0 <= hi: sys.exit("error: --dyn-freq for a %s must be %.0f..%.0f Hz" % (kind, lo, hi)) lo, hi = DYN_Q_RANGE[kind] if not lo - 1e-9 <= q <= hi: sys.exit("error: --dyn-q for a %s must be %.1f..%.1f" % (kind, lo, hi)) shape_stock = kind == "shelf" and abs(f0 - 50.0) < 1e-9 and abs(q - SHELF_Q) < 1e-9 if not 0 <= a.knee < DB_STEPS - 1: sys.exit("error: --knee must be 0..59") if not RATE_RANGE[0] <= a.rate <= RATE_RANGE[1]: sys.exit("error: --rate must be %.1f..%.1f dB per volume step (stock is 0.5)" % RATE_RANGE) if not 0 < dyn_max <= DYN_MAX_LIMIT: sys.exit("error: --dyn-max must be 0..%.0f dB (stock 20)" % DYN_MAX_LIMIT) if dyn_max > DB_STOCK_MAX_DB + 1e-9 and not (a.i_reduced_fixed_boost or a.i_accept_woofer_risk): sys.exit("error: --dyn-max above 20 dB adds bass at low volume (more woofer excursion). Either reduce the " "fixed boost in the DSP file and add --i-reduced-fixed-boost, or add --i-accept-woofer-risk.") if a.max_boost is not None and not 0 <= a.max_boost <= dyn_max: sys.exit("error: --max-boost must be 0..%.1f dB" % dyn_max) dbpi = dyn_max / DB_MAXIDX new = build_curve(a.knee, a.rate, stock, a.max_boost, dbpi) # extra correction bands via the tone-control tables tone_edits = [] if a.band1 or a.band2 or a.band3: bt = find_all(data, bass_tone_bytes()) mt = find_all(data, mid_tone_bytes()) tt = find_all(data, treble_tone_bytes()) if len(bt) != 1 or len(mt) != 1 or len(tt) != 1: sys.exit("error: stock tone-control tables not found (need an unmodified MCUTFV02/03 file)") for spec, t_off, zero, steps, label in ((a.band1, bt[0], BASS_ZERO, BASS_STEPS, "--band1 (bass control)"), (a.band2, mt[0], MID_ZERO, MID_STEPS, "--band2 (mid control)"), (a.band3, tt[0], TREBLE_ZERO, TREBLE_STEPS, "--band3 (treble control)")): if not spec: continue bf, bg, bq = parse_band(spec, label) entry = encode(design_peak(2 * math.pi * bf / 96000.0, bq, bg)) if not is_stable([to_float(entry[4 * j:4 * j + 4]) for j in range(5)]): sys.exit("error: %s would be unstable" % label) positions = range(steps) if a.tone_mode == "all" else [zero] tone_edits.append((label, t_off, [(t_off + 20 * i, entry) for i in positions], bf, bg, bq)) boost_off = None if abs(dyn_max - DB_STOCK_MAX_DB) > 1e-9 or not shape_stock: bh = find_all(data, boost_table_bytes(DB_STOCK_MAX_DB)) if len(bh) != 1: sys.exit("error: stock low-shelf boost table found %d times (need exactly 1); --dyn-max is only " "supported for MCUTFV02/03 (8.24 format)." % len(bh)) boost_off = bh[0] print("dynamic-bass table at 0x%05x in %s%s" % (off, a.file, "" if boost_off is None else "; boost filters at 0x%05x: %s %.0f Hz Q %.2f, 0..%+.1f dB" % (boost_off, kind, f0, q, dyn_max))) print(" step | stock shelf | new shelf | bass at woofer vs step 20 (stock -> new)") for s in range(DB_STEPS): old_db, new_db = stock[s] * 0.5, new[s] * dbpi rel_old = (s - 20) + old_db - DB_STOCK_MAX_DB rel_new = (s - 20) + new_db - DB_STOCK_MAX_DB mark = " *" if abs(new_db - old_db) > 1e-9 else "" if s % 2 == 0 or mark: print(" %2d | %+5.1f dB | %+5.1f dB | %+5.1f -> %+5.1f dB%s" % (s, old_db, new_db, rel_old, rel_new, mark)) print("(low-shelf gain below ~50 Hz; the fixed +8 dB @ 40 Hz peaking boost in the DSP comes on top. " "Last column assumes ~1 dB per volume step, shelf part only)") for label, t_off, writes, bf, bg, bq in tone_edits: print("%s at 0x%05x: peak %.0f Hz %+.1f dB Q %.2f at %s" % (label, t_off, bf, bg, bq, "every knob position (control disabled)" if a.tone_mode == "all" else "knob position 0")) if a.output is None: print("\npreview only - add -o OUTPUT to write a file") return if os.path.abspath(a.output) == os.path.abspath(a.file): sys.exit("error: refusing to overwrite the input file") out = bytearray(data) out[off:off + DB_STEPS] = new allowed = set(range(off, off + DB_STEPS)) for _label, _t_off, writes, *_rest in tone_edits: for pos, entry in writes: out[pos:pos + 20] = entry allowed.update(range(pos, pos + 20)) if boost_off is not None: table = boost_table_bytes(dyn_max, kind, f0 / 96000.0, q) for i in range(DB_MAXIDX + 1): if not is_stable([to_float(table[20 * i + 4 * j: 20 * i + 4 * j + 4]) for j in range(5)]): sys.exit("error: dynamic boost filter %d would be unstable; nothing written" % i) out[boost_off:boost_off + len(table)] = table allowed.update(range(boost_off, boost_off + len(table))) diff = [i for i in range(len(data)) if data[i] != out[i]] if any(i not in allowed for i in diff): sys.exit("internal error: bytes changed outside the dynamic-bass / tone tables; nothing written") if not diff: sys.exit("error: these settings equal stock; nothing written") os.makedirs(os.path.dirname(os.path.abspath(a.output)), exist_ok=True) with open(a.output, "wb") as fh: fh.write(out) print("\nwritten : %s (%d bytes changed, all inside the dynamic-bass / tone tables)" % (a.output, len(diff))) print("Keep the original file name (e.g. MCUTFV03.bin) when copying to the update USB stick.") def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--expert", action="store_true", help="much looser limits (same as the app's Expert mode); coefficient range and filter " "stability are always checked") p.add_argument("--fs", type=int, default=DEFAULT_FS, help="DSP sample rate to assume (default 96000; 48000 halves all frequencies)") sub = p.add_subparsers(dest="cmd", required=True) i = sub.add_parser("info", help="show crossover/EQ sections and validate a DSP image") i.add_argument("file") i.set_defaults(func=cmd_info) t = sub.add_parser("patch", help="write a patched DSP image") t.add_argument("file") t.add_argument("-o", "--output", required=True) s = t.add_argument_group("sub-out crossover (stock 80 Hz)") s.add_argument("--sub-xover", type=float, help="move sub low-pass AND speaker high-pass to this Hz") s.add_argument("--sub-lp", type=float, help="subwoofer-out low-pass frequency in Hz") s.add_argument("--main-hp", type=float, help="speaker high-pass (Dynamic Bass path) frequency in Hz") s.add_argument("--speaker-hp-always", action="store_true", help="also raise the always-on woofer protection high-pass (stock 50 Hz) to the speaker " "high-pass frequency. NOT recommended: the speaker high-pass already applies whenever " "a sub is plugged in; this makes the speakers thin without a sub and the woofer slope " "steeper with one") s.add_argument("--always-hp", type=float, help="set the always-on speaker high-pass to this Hz directly") s.add_argument("--i-accept-woofer-risk", action="store_true", help="allow lowering a speaker high-pass (main by >15%%, always-on below stock)") sq = t.add_argument_group("slope and Q of the sub-out crossover") sq.add_argument("--sub-q", type=float, help="Q of the sub-out low-pass sections (stock 0.71, %.1f..%.1f)" % SUB_Q_RANGE) sq.add_argument("--sub-slope", type=int, choices=(12, 24), help="sub-out low-pass slope in dB/octave (stock 24; 12 disables the second section)") sq.add_argument("--main-hp-q", type=float, help="Q of the speaker high-pass (sub connected / DB), stock 0.71; lower = softer knee") sq.add_argument("--always-hp-q", type=float, help="Q of the always-on woofer protection high-pass (stock 0.73)") lv = t.add_argument_group("levels and polarity") lv.add_argument("--sub-level", type=float, metavar="DB", help="sub-out level change in dB (%+.0f..%+.0f)" % SUB_LEVEL_RANGE) lv.add_argument("--sub-invert", action="store_true", help="invert sub-out polarity (180 degrees)") lv.add_argument("--tweeter-level", type=float, metavar="DB", help="tweeter level change in dB (%+.0f..%+.0f)" % TWEETER_LEVEL_RANGE) eq = t.add_argument_group("tonal EQ and bass boost") eq.add_argument("--eq", action="append", metavar="OFFSET:GAIN[:FREQ[:Q]]", help="change one of Klipsch's EQ filters (offsets from `info`); gain %+.0f..%+.0f dB, " "e.g. 0x045c:0 or 0x0a94:1.5:1900:2; repeatable" % EQ_GAIN_RANGE) eq.add_argument("--eq-flat", action="store_true", help="set all of Klipsch's EQ filters to 0 dB") eq.add_argument("--bass-boost", type=float, metavar="DB", help="fixed bass boost of the Dynamic Bass mode (stock +8 dB at 40 Hz; 0..%.0f, above stock " "needs --i-accept-woofer-risk)" % FIXED_BOOST_MAX) eq.add_argument("--bass-boost-freq", type=float, metavar="HZ", help="centre frequency of the fixed boost (stock 40 Hz)") eq.add_argument("--bass-boost-q", type=float, help="Q of the fixed boost (stock 0.5)") w = t.add_argument_group("woofer/tweeter crossover") g = w.add_mutually_exclusive_group() g.add_argument("--scale", type=float, help="move woofer/tweeter crossover by this factor (e.g. 1.1)") g.add_argument("--xover", type=float, help="move woofer/tweeter crossover so the woofer LP lands at this Hz") w.add_argument("--lp", type=float, help="woofer low-pass frequency in Hz") w.add_argument("--hp", type=float, help="main (highest) tweeter high-pass frequency in Hz; " "the other tweeter HP section is scaled by the same ratio") w.add_argument("--i-accept-tweeter-risk", action="store_true") t.add_argument("--force", action="store_true") t.set_defaults(func=cmd_patch) b = sub.add_parser("dynbass", help="change the dynamic bass curve (patches the MCU file)") b.add_argument("file", help="original MCUTFV02.bin / MCUTFV03.bin / FIVESMCU.bin") b.add_argument("-o", "--output", help="write patched file here (omit for preview)") b.add_argument("--knee", type=int, default=20, help="volume step (0-60) above which the new, faster roll-off starts (stock: 20)") b.add_argument("--rate", type=float, default=0.5, help="boost reduction in dB per volume step above the knee (stock 0.5; " "1.0 keeps the deep-bass level at the woofer constant)") b.add_argument("--max-boost", type=float, metavar="DB", help="cap the dynamic boost at this many dB at every volume") b.add_argument("--dyn-max", type=float, metavar="DB", help="rescale the 41 low-shelf boost filters to 0..DB (stock 20, max %.0f). " "Above 20 only together with a reduced fixed boost (DSP --bass-boost)" % DYN_MAX_LIMIT) b.add_argument("--dyn-type", choices=("shelf", "peak"), default="shelf", help="shape of the dynamic boost: low shelf (stock, keeps rising towards the deepest bass) or " "peak (boosts around --dyn-freq only)") b.add_argument("--dyn-freq", type=float, metavar="HZ", help="corner (shelf) or centre (peak) frequency at 96 kHz; stock shelf 50 Hz") b.add_argument("--dyn-q", type=float, help="Q of the dynamic boost (stock shelf 0.707; peak default 0.7)") b.add_argument("--band1", metavar="F:G[:Q]", help="extra correction band replacing the BASS tone control (peak, Hz at 96 kHz), e.g. 194:-7:6.5") b.add_argument("--band2", metavar="F:G[:Q]", help="extra correction band replacing the MID tone control, e.g. 271:-4:9") b.add_argument("--band3", metavar="F:G[:Q]", help="extra correction band replacing the TREBLE tone control") b.add_argument("--tone-mode", choices=("zero", "all"), default="zero", help="zero: band active when that tone control is at 0 (other positions keep the normal control); " "all: band at every position (that control stops working, band can't be lost)") b.add_argument("--i-reduced-fixed-boost", action="store_true", help="confirm you reduce the DSP's fixed boost when using --dyn-max above 20") b.add_argument("--i-accept-woofer-risk", action="store_true", help="allow --dyn-max above 20 without reducing the fixed boost") b.set_defaults(func=cmd_dynbass) a = p.parse_args() a.func(a) if __name__ == "__main__": main()