fix(histogram_codec): read multi-interval blocks big-endian from byte 5, mic on and off (#47, #49)

Measured 2026-10-26.  A sub-minute histogram block is [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 x channels + 4); the standard 32-byte block
is the same thing holding one record.  The last block is short, not padded: it
holds only the intervals recorded and ends on 9c 06 00 42.

#47: a mic-off histogram (16-byte records) decoded to nothing, so a Blastware
import carried no histogram data and SFM's download check would refuse it.
BE9441's K441LTOK.QZ0 (2 s, 22 intervals; fixture) now matches its Blastware
export on 66/66 peaks and 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 while every high byte is zero.  It also
required byte 5 to be 0 (the first record's Tran peak high byte) and read the
last block at full stride, trimming what it overran.

Regression over every DL2 histogram with a Blastware ASCII export (13,089
files, interval counts + every geo peak, frequency and mic dB): old reader
13,087 exact, new 13,089.  The two the old one got wrong were one interval each:
K440KZP4.560H #4764 (Long half-period 1 read as 257, mic peak 389 as 133) and
M462KZUD.6R0H #145 (mic peak 6 read as 262).

Walk: blocks follow by block_ctr + 1, or the next segment every 256 blocks; the
last block is bounded by its terminal tail; with no terminal tail the old
trimming rule remains as the fallback.  Mic-off records give m_peak None and an
empty MicL channel, as a mic-off waveform does.  Inferred, not yet seen in a
file: mic-off 1-minute (28-byte) and 15 s / 5 s mic-off strides.

Not fixed here, noted on #47: half_period_to_hz assumes 1024 sps (512/hp); the
2048-sps histogram's frequencies are 1024/hp.

Operational: a decoder change -- needs a TOOL_VERSION bump at release, then
backfill_sidecars.py + backfill_event_shape.py (~2 h on the NAS) to regenerate
stored histograms.  No schema change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-26 18:30:09 -04:00
1 parent 6690434ecf
commit dfc5aefef7
5 files changed
+410 -140

No files matched your search

+184 -134
View File
@@ -255,18 +255,25 @@ def walk_body(body: bytes) -> List[dict]:
def _walk_auto(body: bytes) -> List[dict]:
"""Pick the block model by signature strength, not by which returns first.
The multi-interval variant announces itself with consecutive block headers
at an exact ``12 + 20*n`` stride — far stronger evidence than a handful of
scattered standard-tail blocks, which a multi-interval body will also yield
by coincidence. Dispatching on "whichever decoder returns something"
handed 193 BE18193 files to the standard walker and produced peaks of
149 in/s against a 10 in/s full scale.
A multi-interval body announces itself with consecutive block headers at an
exact ``12 + record * n`` stride -- far stronger evidence than a handful of
scattered standard-tail blocks, which it will also yield by coincidence.
Dispatching on "whichever decoder returns something" handed 193 BE18193
files to the standard walker and produced peaks of 149 in/s against a
10 in/s full scale. A single short block (under a minute of intervals) has
no second header; it is tried after the standard walker, which a one-block
standard body satisfies with the same values.
"""
if detect_multi_interval_stride(body):
layout = detect_multi_interval_layout(body)
if layout and (_is_multi_header(body, _stride(*layout))
or layout[0] == 16):
recs = walk_multi_interval_blocks(body)
if recs:
return recs
return walk_body(body)
recs = walk_body(body)
if recs:
return recs
return walk_multi_interval_blocks(body) if layout else []
def decode_histogram_body(body: bytes) -> Optional[dict]:
@@ -291,7 +298,9 @@ def decode_histogram_body(body: bytes) -> Optional[dict]:
"Tran": [r["t_peak"] for r in records],
"Vert": [r["v_peak"] for r in records],
"Long": [r["l_peak"] for r in records],
"MicL": [r["m_peak"] for r in records],
# A mic-off histogram has no mic channel: an empty list, as a mic-off
# waveform's decode gives.
"MicL": [r["m_peak"] for r in records if r["m_peak"] is not None],
}
@@ -328,160 +337,201 @@ def geo_count_to_ins(count: int) -> float:
return count * _GEO_LSB_INS
# ── Multi-interval block variant (CONFIRMED 2026-08-26) ─────────────────────
# ── Multi-interval blocks (CONFIRMED 2026-08-26; re-read 2026-10-26) ─────────
#
# When the histogram interval is SHORTER than one minute, the device packs
# several intervals into a single block so that every block still covers
# exactly one minute of data:
# When the histogram interval is SHORTER than one minute, the device packs one
# minute of intervals into each block:
#
# interval size intervals/block stride
# 1 minute 1 32 <- the standard block above
# 15 seconds 4 92
# 2 seconds 30 612
# interval per block stride, mic on (20 B records) mic off (16 B)
# 1 minute 1 32 <- the standard block above 28 (inferred)
# 15 s 4 92 76 (inferred)
# 2 s 30 612 492 (inferred)
#
# stride = 12 + n_intervals * 20
# stride = 12 + per_block * record, record = 4 * channels + 4
#
# Block layout:
# Block layout (measured 2026-10-26, issues #47 and #49):
# [0] 0x00
# [1] segment_id (256 blocks per segment, same as the standard block)
# [2:4] block_ctr uint16 LE (0x0100.., resets each segment)
# [4] 0x0a marker
# [5] 0x00
# [6 ...] n x 20-byte interval records, each carrying 8 x uint16
# LITTLE-endian values:
# T_peak, T_halfperiod, V_peak, V_halfperiod,
# L_peak, L_halfperiod, M_peak, M_halfperiod
# then 2 more words; the first is 0x0000 on every real interval.
# [-6:] 6-byte block trailer
# [1] segment_id (256 blocks per segment, as in the standard block)
# [2:4] block_ctr uint16 LE
# [4] 0x0a
# [5 ...] one record per interval: per channel a BIG-endian uint16 peak and
# half-period (Tran, Vert, Long[, MicL]), then 0x0000, then one more
# word ("meta_var" keeps those 4 bytes)
# [-7:] trailer: 3 bytes, then the 4-byte tail -- 9c 06 00 42 on the
# stream's LAST block
#
# ⚠ ENDIANNESS: the standard 32-byte block is BIG-endian. This variant is
# LITTLE-endian. Do not share the accessor.
# The last block is SHORT, not padded: it holds only the intervals recorded and
# ends on 9c 06 00 42 (K440L3AQ.T70H: 1,427 x 4 + 2 = 5,710, Blastware's count;
# T193L0XM.CI0H: 30 + 21 = 51). Reading it at full stride ran into the setup
# data that follows, which is what the old "garbage slot" trimming cleaned up;
# that trimming survives only as the fallback for a stream with no 9c 06 00 42.
#
# These files previously decoded to nothing at all — 415 of them in the
# production snapshot, 216 on BE18193 (2 s intervals) and 199 on BE9440
# (15 s). Before that they were being accepted by the WAVEFORM codec, which
# returned garbage peaking up to 400x the device-reported PPV.
# ⚠ RETRACTED 2026-10-26: "8 x uint16 LITTLE-endian from byte 6, a 6-byte
# header with [5] == 0". That is the same bytes shifted by one: identical while
# every high byte is zero, which is why it matched Blastware on 10,715,314 of the
# 770 archive files' intervals -- and wrong on the 1 that was not (K440KZP4.560H
# #4764: a Long half-period of 1 read as 257, ">100 Hz" read as ~2 Hz). And
# byte 5 is the first record's Tran peak high byte, so a block whose first
# interval exceeded 1.275 in/s ended the old walk.
#
# Ground truth: BE9440/K440L3AQ.T70H (15 s intervals, 5,710 of them) decodes
# against its Blastware ASCII export with 17,130/17,130 geo peak counts,
# 22,840/22,840 frequencies and 5,710/5,710 mic dB(L) values matching exactly.
# Mic off (#47): BE9441's K441LTOK.QZ0 (2 s, 22 intervals, one short block)
# matches its Blastware export on 66/66 peaks and 66/66 frequencies. The mic-off
# strides above follow from the same layout; only the 2 s short block is
# measured.
#
# Ground truth, mic on: BE9440/K440L3AQ.T70H (15 s, 5,710 intervals) --
# 17,130 / 22,840 / 5,710 geo peaks, frequencies and mic dB(L), all exact.
_MULTI_HEADER_LEN = 6
_MULTI_RECORD_LEN = 20
_MULTI_TRAILER_LEN = 6
# At least 2 records: a 1-record block would have stride 12 + 20 = 32, which
# collides with the standard big-endian block and mis-decodes it.
_MULTI_MIN_RECORDS = 2
_MULTI_MAX_RECORDS = 64
_MULTI_HEADER_LEN = 5
_MULTI_TRAILER_LEN = 7
_MULTI_MAX_RECORDS = 64
_RECORD_LENS = (20, 16) # mic on (4 channels), mic off (3 channels)
# Geo full scale in 16-count units: 10.000 in/s / 0.005 = 2000. A peak above
# this is physically impossible and marks buffer garbage in a partial block.
# Geo full scale in 16-count units: 10.000 in/s / 0.005 = 2000. Used only by
# the fallback trim of a stream with no terminal tail.
_GEO_MAX_COUNTS = 2000
def _is_multi_header(body: bytes, off: int) -> bool:
return (off + _MULTI_HEADER_LEN <= len(body)
and body[off] == 0x00
and body[off + 4] == 0x0A
and body[off + 5] == 0x00)
and body[off + 4] == 0x0A)
def detect_multi_interval_stride(body: bytes) -> Optional[int]:
"""Block stride of a multi-interval histogram body, or None.
def _ctr(body: bytes, off: int) -> int:
return body[off + 2] | (body[off + 3] << 8)
Found by locating the second block header; validated against
``stride = 12 + n * 20`` and confirmed on a third block where present.
def _follows(body: bytes, off: int, nxt: int) -> bool:
"""A block header at ``nxt`` that continues the block at ``off``: block_ctr
one higher, or -- every 256 blocks -- the next segment (block_ctr restarts)."""
if not _is_multi_header(body, nxt):
return False
if body[nxt + 1] == body[off + 1]:
return (_ctr(body, nxt) - _ctr(body, off)) & 0xFFFF == 1
return body[nxt + 1] == (body[off + 1] + 1) & 0xFF
def _stride(rec: int, n: int) -> int:
return _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + rec * n
def _records_plausible(body: bytes, off: int, rec: int, m: int) -> bool:
"""Every record's zero word is 0000 -- what tells a 16-byte layout from a
20-byte one when both strides happen to fit (492 = 12 + 16x30 = 12 + 20x24)."""
z = rec - 4
for k in range(m):
q = off + _MULTI_HEADER_LEN + rec * k
if q + rec > len(body) or body[q + z] or body[q + z + 1]:
return False
return True
def detect_multi_interval_layout(body: bytes) -> Optional[Tuple[int, int]]:
"""``(record_len, per_block)`` of a multi-interval body, or None.
Found from the second block header (block_ctr one higher), confirmed on a
third when present; a single short block is found from its terminal tail.
"""
if not _is_multi_header(body, 0):
return None
lo = _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + _MULTI_RECORD_LEN * _MULTI_MIN_RECORDS
hi = _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + _MULTI_RECORD_LEN * _MULTI_MAX_RECORDS
for stride in range(lo, min(hi, len(body)) + 1, 2):
if (stride - 12) % _MULTI_RECORD_LEN:
continue
if not _is_multi_header(body, stride):
continue
# DECISIVE CHECK: consecutive blocks differ by exactly 1 in block_ctr.
# Without it this false-positives on ordinary standard-block bodies:
# those carry a header every 32 bytes, and 192 = 12 + 20*9 and
# 512 = 12 + 20*25 are both multiples of 32, so a stride "fits" while
# actually skipping 6 or 16 real blocks. Sampling a standard body at
# stride 192 handed 9,082 files to the wrong decoder and produced peaks
# of 149 in/s against a 10 in/s full scale.
def _ctr(o: int) -> int:
return body[o + 2] | (body[o + 3] << 8)
if (_ctr(stride) - _ctr(0)) & 0xFFFF != 1:
continue
# Confirm on a third block WHEN ONE IS ACTUALLY PRESENT. A body can
# be longer than two strides and still hold only two real blocks: a
# final *partial* block leaves trailing padding. E.g. 51 intervals at
# 2 s = one full 30-interval block + a 21-interval remainder, in a
# 2787-byte body — long enough to demand a third header at 1224 that
# does not exist. Requiring it unconditionally threw away the correct
# stride and the file decoded to nothing (BE18193 T193L0XM.CI0H).
# The block-counter check above is the decisive anti-false-positive
# test; this one is corroboration, so a missing third header means
# end-of-stream, not disqualification.
if (2 * stride + _MULTI_HEADER_LEN <= len(body)
and _is_multi_header(body, 2 * stride)):
if (_ctr(2 * stride) - _ctr(stride)) & 0xFFFF != 1:
for rec in _RECORD_LENS:
# A 20-byte record with one interval per block IS the standard 32-byte
# block, which walk_body reads; the mic-off one-minute block is not.
for n in range(2 if rec == 20 else 1, _MULTI_MAX_RECORDS + 1):
s = _stride(rec, n)
if s + _MULTI_HEADER_LEN > len(body):
break
if not _follows(body, 0, s):
continue
return stride
# The block-counter step is the decisive test: a standard body has a
# header every 32 bytes, and 192 = 12 + 20x9 skips 6 of them. A third
# block, when there is one, must follow too.
if (_is_multi_header(body, 2 * s) and not _follows(body, s, 2 * s)
and body[2 * s - 4:2 * s] != _BLOCK_TAIL_TERMINAL):
continue
if not _records_plausible(body, 0, rec, n):
continue
return rec, n
# One block only (a histogram shorter than a minute): bounded by its tail.
t = body.find(_BLOCK_TAIL_TERMINAL)
while t >= 0:
for rec in _RECORD_LENS:
span = t + 4 - _MULTI_HEADER_LEN - _MULTI_TRAILER_LEN
if span > 0 and span % rec == 0 and span // rec <= _MULTI_MAX_RECORDS \
and _records_plausible(body, 0, rec, span // rec):
return rec, span // rec
t = body.find(_BLOCK_TAIL_TERMINAL, t + 1)
return None
def detect_multi_interval_stride(body: bytes) -> Optional[int]:
"""Block stride of a multi-interval histogram body, or None."""
layout = detect_multi_interval_layout(body)
return _stride(*layout) if layout else None
def _decode_record(body: bytes, q: int, rec: int, off: int) -> dict:
def be16(p: int) -> int:
return (body[p] << 8) | body[p + 1]
mic = rec == 20
z = rec - 4
return {
"segment_id": body[off + 1],
"block_ctr": _ctr(body, off),
"t_peak": be16(q), "t_halfp": be16(q + 2),
"v_peak": be16(q + 4), "v_halfp": be16(q + 6),
"l_peak": be16(q + 8), "l_halfp": be16(q + 10),
"m_peak": be16(q + 12) if mic else None,
"m_halfp": be16(q + 14) if mic else None,
"meta_var": bytes(body[q + z:q + z + 4]),
"is_terminal": False,
}
def walk_multi_interval_blocks(body: bytes,
stride: Optional[int] = None) -> List[dict]:
"""Decode a multi-interval histogram body into per-interval records."""
if stride is None:
stride = detect_multi_interval_stride(body)
if not stride:
return []
n_per_block = (stride - _MULTI_HEADER_LEN - _MULTI_TRAILER_LEN) // _MULTI_RECORD_LEN
if n_per_block < 1:
return []
def u16le(p: int) -> int:
return body[p] | (body[p + 1] << 8)
"""Decode a multi-interval histogram body into per-interval records.
``stride`` is accepted for compatibility and ignored: the record size is
detected, and each block's own length is read from the stream.
"""
layout = detect_multi_interval_layout(body)
if not layout:
return []
rec, n = layout
s = _stride(rec, n)
out: List[dict] = []
for off in range(0, len(body) - stride + 1, stride):
if not _is_multi_header(body, off):
break # end of the block run; trailer follows
for k in range(n_per_block):
q = off + _MULTI_HEADER_LEN + _MULTI_RECORD_LEN * k
out.append({
"_tail0": u16le(q + 16),
"segment_id": body[off + 1],
"block_ctr": u16le(off + 2),
"t_peak": u16le(q), "t_halfp": u16le(q + 2),
"v_peak": u16le(q + 4), "v_halfp": u16le(q + 6),
"l_peak": u16le(q + 8), "l_halfp": u16le(q + 10),
"m_peak": u16le(q + 12), "m_halfp": u16le(q + 14),
"meta_var": bytes(body[q + 16:q + 20]),
"is_terminal": False,
})
# A session ending mid-block leaves the remaining slots of the FINAL block
# filled with whatever was in the buffer. Those decoded as peaks thousands
# of times the device-reported PPV, so they have to go — but only from the
# final block: a non-zero tail word occurs mid-file on real intervals, and
# trimming on that alone truncated four BE9440 files by up to 2,800
# intervals, while trimming purely from the end left garbage stranded
# behind one slot that happened to have a zero tail word.
#
# Within the final block, stop at the first slot that is not plausibly
# real: a non-zero tail word, or a geo peak above full scale. 16-count
# units put Normal-range full scale (10.000 in/s) at 2000 counts, so
# anything beyond that is physically impossible.
if out:
last_block_start = ((len(out) - 1) // n_per_block) * n_per_block
for i in range(last_block_start, len(out)):
r = out[i]
if (r["_tail0"] != 0
or max(r["t_peak"], r["v_peak"], r["l_peak"]) > _GEO_MAX_COUNTS):
del out[i:]
off = 0
while _is_multi_header(body, off):
# The last block ends on the terminal tail, after however many intervals
# it holds; any other block runs the full stride to the next header.
m = next((k for k in range(1, n + 1)
if body[off + _stride(rec, k) - 4:off + _stride(rec, k)] == _BLOCK_TAIL_TERMINAL),
None)
last = m is not None
if not last:
nxt = off + s
if not _follows(body, off, nxt):
# No terminal tail and no next block: the stream just stops. Read
# what fits and trim implausible slots (the pre-2026-10-26 rule).
m, last = min(n, (len(body) - off - _MULTI_HEADER_LEN) // rec), True
recs = [_decode_record(body, off + _MULTI_HEADER_LEN + rec * k, rec, off)
for k in range(max(m, 0))]
for k, r in enumerate(recs):
if (r["meta_var"][:2] != b"\x00\x00"
or max(r["t_peak"], r["v_peak"], r["l_peak"]) > _GEO_MAX_COUNTS):
del recs[k:]
break
out.extend(recs)
break
for r in out:
r.pop("_tail0", None)
m = n
for k in range(m):
r = _decode_record(body, off + _MULTI_HEADER_LEN + rec * k, rec, off)
r["is_terminal"] = last
out.append(r)
if last:
break
off += s
return out