|
| 1 | +"""Nothing X "Advanced equaliser profile" share codec. |
| 2 | +
|
| 3 | +A shared profile (the content of a Nothing X EQ QR code) is gzip + base64 of: |
| 4 | +
|
| 5 | + 0x00 | band_bytes_len(1) | bands | 0x01 | name_len(1) | name (ASCII) |
| 6 | +
|
| 7 | +Each band is three little-endian float32 values: gain (dB), frequency (Hz), Q. |
| 8 | +This lets us import and export Nothing-X-compatible profiles. |
| 9 | +
|
| 10 | +Decoded and verified against real Nothing X QR samples. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import base64 |
| 16 | +import gzip |
| 17 | +import struct |
| 18 | +from dataclasses import dataclass |
| 19 | + |
| 20 | +_BAND_SIZE = 12 |
| 21 | + |
| 22 | + |
| 23 | +@dataclass(frozen=True) |
| 24 | +class EqBand: |
| 25 | + gain: float |
| 26 | + frequency: float |
| 27 | + q: float |
| 28 | + |
| 29 | + |
| 30 | +@dataclass(frozen=True) |
| 31 | +class AdvancedEqProfile: |
| 32 | + name: str |
| 33 | + bands: list[EqBand] |
| 34 | + |
| 35 | + |
| 36 | +def decode_binary(raw: bytes) -> AdvancedEqProfile: |
| 37 | + band_len = raw[1] |
| 38 | + count = band_len // _BAND_SIZE |
| 39 | + bands = [] |
| 40 | + offset = 2 |
| 41 | + for _ in range(count): |
| 42 | + gain, frequency, q = struct.unpack_from("<3f", raw, offset) |
| 43 | + bands.append(EqBand(gain, frequency, q)) |
| 44 | + offset += _BAND_SIZE |
| 45 | + name_len = raw[offset + 1] |
| 46 | + name = raw[offset + 2 : offset + 2 + name_len].decode("ascii", errors="replace") |
| 47 | + return AdvancedEqProfile(name=name, bands=bands) |
| 48 | + |
| 49 | + |
| 50 | +def encode_binary(profile: AdvancedEqProfile) -> bytes: |
| 51 | + body = bytes([0x00, len(profile.bands) * _BAND_SIZE]) |
| 52 | + for band in profile.bands: |
| 53 | + body += struct.pack("<3f", band.gain, band.frequency, band.q) |
| 54 | + name = profile.name.encode("ascii", errors="replace") |
| 55 | + body += bytes([0x01, len(name)]) + name |
| 56 | + return body |
| 57 | + |
| 58 | + |
| 59 | +def decode_profile(code: str) -> AdvancedEqProfile: |
| 60 | + raw = gzip.decompress(base64.b64decode(code)) |
| 61 | + return decode_binary(raw) |
| 62 | + |
| 63 | + |
| 64 | +def encode_profile(profile: AdvancedEqProfile) -> str: |
| 65 | + raw = encode_binary(profile) |
| 66 | + return base64.b64encode(gzip.compress(raw)).decode("ascii") |
0 commit comments