"""Multi-interval histogram blocks, mic on and mic off (issues #47, #49). Measured 2026-10-26: * A sub-minute histogram packs one minute of intervals per block: ``[00][segment][ctr LE][0a]`` (5 bytes), then one record per interval of BIG-endian peak / half-period pairs per channel, then ``0000`` and one more word, then a 7-byte trailer. A record is 20 bytes with the mic and 16 without (``4 * channels + 4``); the standard 32-byte block is the same thing with one record. * The last block is SHORT, not padded: it holds only the intervals recorded and ends in ``9c 06 00 42`` (K440L3AQ: 1,427 x 4 + 2 = 5,710, Blastware's count). * #47: BE9441's mic-off 2-second histogram (fixture) decoded to nothing. Read as above, its 22 intervals match Blastware's export: 66/66 peaks, 66/66 frequencies. * #49: the old reader took the mic-on records as little-endian from byte 6 -- the same bytes shifted by one, identical whenever the high bytes are zero. Across the 770 archive histograms with an export it disagreed with Blastware on exactly 1 of 10,715,315 intervals (K440KZP4.560H #4764). """ from __future__ import annotations import os import re import sys from pathlib import Path import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from minimateplus.histogram_codec import ( # noqa: E402 decode_histogram_body, decode_histogram_body_full, walk_multi_interval_blocks, ) FIX = Path(__file__).parent / "fixtures" / "histogram-mic-off-10-26-26" TERMINAL = b"\x9c\x06\x00\x42" def _body(path: Path) -> bytes: raw = path.read_bytes() return raw[raw.find(b"STRT") + 21:] def _ascii_rows(path: Path) -> list: return [line.split() for line in path.read_text(errors="replace").splitlines() if re.match(r"^\d\d:\d\d:\d\d\s", line)] def _block(records, *, ctr=0x0100, seg=0, mic=True, last=False) -> bytes: """One block: records are (T, Tf, V, Vf, L, Lf[, M, Mf]) tuples, BIG-endian.""" b = bytearray([0x00, seg, ctr & 0xFF, ctr >> 8, 0x0A]) for r in records: assert len(r) == (8 if mic else 6) for v in r: b += int(v).to_bytes(2, "big") b += (max(r[0], r[2], r[4]) ** 2).to_bytes(4, "big") # PVS², consistent as on real data b += b"\xfc\xf3\x00" + (TERMINAL if last else b"\x5a\x0a\x00\x00") return bytes(b) # -- #47: mic off ------------------------------------------------------------- def test_the_mic_off_histogram_matches_blastwares_export(): recs = decode_histogram_body_full(_body(FIX / "K441LTOK.QZ0")) rows = _ascii_rows(FIX / "K441LTOK_QZ0_ASCII.TXT") assert recs is not None and len(recs) == len(rows) == 22 num = 2048 / 2 # "Sample Rate : 2048 sps" for r, row in zip(recs, rows): for c, ch in enumerate("tvl"): assert r[f"{ch}_peak"] * 0.005 == pytest.approx(float(row[1 + 2 * c]), abs=1e-9) f, want = num / r[f"{ch}_halfp"], row[2 + 2 * c] if want.startswith(">"): assert f > 200 else: assert f == pytest.approx(float(want), rel=0.051) assert r["m_peak"] is None and r["m_halfp"] is None def test_a_mic_off_histogram_has_no_mic_channel(): ch = decode_histogram_body(_body(FIX / "K441LTOK.QZ0")) assert ch is not None assert [len(ch[c]) for c in ("Tran", "Vert", "Long", "MicL")] == [22, 22, 22, 0] assert max(ch["Vert"]) * 0.005 == pytest.approx(1.080) # Blastware's Vert PPV def test_mic_off_blocks_walk_in_sixteen_byte_records(): a = [(1, 2, 3, 4, 5, 6)] * 30 body = _block(a, mic=False) + _block([(7, 8, 9, 10, 11, 12)] * 3, ctr=0x0101, mic=False, last=True) + b"setup block follows" recs = walk_multi_interval_blocks(body) assert len(recs) == 33 assert (recs[30]["t_peak"], recs[30]["l_halfp"]) == (7, 12) # -- #49: mic on, big-endian from byte 5 --------------------------------------- def test_mic_on_records_are_big_endian(): # K440KZP4.560H #4764's shape: a mic peak >= 256 next to a Long half-period of 1. # Read little-endian from byte 6, that half-period came out 257 (~2 Hz, not >100). iv = [(10, 2, 11, 1, 10, 1, 0x0123, 4)] * 4 body = _block(iv) + _block(iv, ctr=0x0101, last=True) r = walk_multi_interval_blocks(body)[0] assert (r["l_halfp"], r["m_peak"], r["m_halfp"]) == (1, 0x0123, 4) def test_a_loud_first_interval_does_not_end_the_walk(): # byte 5 is the first record's Tran peak high byte, not a constant 0 iv = [(0x0150, 9, 1, 1, 1, 1, 1, 1)] + [(1, 1, 1, 1, 1, 1, 1, 1)] * 3 body = _block(iv) + _block(iv, ctr=0x0101) + _block(iv, ctr=0x0102, last=True) recs = walk_multi_interval_blocks(body) assert len(recs) == 12 and recs[8]["t_peak"] == 0x0150 # -- the last block is short, bounded by its terminal tail --------------------- def test_the_last_block_holds_only_its_intervals(): iv = [(1, 1, 2, 2, 3, 3, 4, 4)] tail = [(5, 5, 6, 6, 7, 7, 8, 8)] * 2 body = (_block(iv * 4) + _block(tail, ctr=0x0101, last=True) + bytes([0x00, 0x00, 0x01, 0x01, 0x0A]) + b"\x07" * 60) # setup data after it recs = walk_multi_interval_blocks(body) assert len(recs) == 6 assert recs[-1]["t_peak"] == 5 def test_a_single_short_block_decodes(): body = _block([(4, 9, 4, 9, 4, 9, 2, 2)] * 7, last=True) + b"\x00" * 40 recs = walk_multi_interval_blocks(body) assert len(recs) == 7 and recs[0]["m_peak"] == 2 def test_the_walk_crosses_a_segment_boundary(): # 256 blocks per segment: block_ctr restarts at 0x0100 and segment_id steps. iv = [(1, 1, 2, 2, 3, 3, 4, 4)] * 4 body = (_block(iv, ctr=0x01FE) + _block(iv, ctr=0x01FF) + _block(iv, ctr=0x0100, seg=1) + _block(iv, ctr=0x0101, seg=1, last=True)) recs = walk_multi_interval_blocks(body) assert len(recs) == 16 and recs[-1]["segment_id"] == 1