From b5b0fa91fea481e848ebe991e6ea7e3dfefe4c86 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Wed, 30 Sep 2026 13:18:56 +0200 Subject: [PATCH] Refined Rekordbox timing fix --- CLAUDE.md | 32 ++++-- .../konduktor/adapters/rekordbox/beatgrid.py | 12 +- backend/konduktor/adapters/rekordbox/store.py | 10 +- .../konduktor/adapters/rekordbox/timebase.py | 81 +++++++++---- backend/konduktor/core/mp4_edit.py | 106 ++++++++++++++++++ backend/test_timebase.py | 65 +++++++++++ 6 files changed, 267 insertions(+), 39 deletions(-) create mode 100644 backend/konduktor/core/mp4_edit.py diff --git a/CLAUDE.md b/CLAUDE.md index 201fe74..316e7c5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -102,11 +102,11 @@ Two independent apps that talk over HTTP: 1–8 kHz attack band, and which attack is the beat from whether a kick's low end follows it — each band alone lost a real track to an off-beat hat or a syncopated bassline. Positions are in the **decoded audio's** time - base (libsndfile = CoreAudio to the sample on MP3). **Rekordbox's grids sit - a constant ~25 ms later on lossy files** and at 0 on WAV — a platform - time-base difference, deliberately NOT corrected here. Traktor's differs - by a per-file rule instead (an MP3 with a header runs 2257 samples late), - corrected at the adapter boundary — see `adapters/traktor/timebase.py`. + base (libsndfile = CoreAudio to the sample on MP3). **Rekordbox's and + Traktor's clocks both differ from it, per FILE** (an MP3's header, an + M4A's edit list), and are deliberately NOT corrected here but at each + adapter boundary — `adapters/rekordbox/timebase.py`, + `adapters/traktor/timebase.py`. `backend/bench_grid_detect.py` scores it against any library's single-marker grids and reports that constant separately from detection error (29 Rekordbox references: old 1/29 BPMs, new 27/29). @@ -609,7 +609,10 @@ serialization path.** It enforces: write path adding it and the projection removing it, a grid anchored inside the header frame reading negative and round-tripping byte for byte, and — when kit 4 is on the machine — Traktor's own hand-placed cues reading back - onto the kick. + onto the kick. Then the same for rekordbox's clock: the per-file offsets + (MP3 header, header-less, 48 kHz, FFmpeg and Apple AAC priming, the + unreadable fallback), negative beats dropped with bar numbering kept, and + rekordbox's own hand-placed kit-4 cues read back from `master.db`. - `test_traktor_adapter.py` — the **generic layer**: one parse per open, the projection refreshing after every command family, cue-type translation, capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity` @@ -1066,9 +1069,20 @@ that number and nothing else — everything derives from it: first marker on the first DOWNBEAT — the generic first marker is bar 1 — and `beats_from_markers` writes the lead-in beats back, numbered as they were; before this every bar of such a track landed two beats early, on import to - Traktor as well as on export. **Rekordbox's clock runs 1105 samples (~25 ms) - behind the decoded audio on MP3/AAC** — the codec delay it does not trim; - measured +25.0 ms on 16 MP3s, +24.5 on 4 M4As, 0 on WAV. The generic model is + Traktor as well as on export. **Rekordbox's clock runs behind the decoded + audio by the start padding it does not trim, which depends on the FILE**: + an MP3 with a Xing/Info header 1105 samples (~25 ms; rekordbox skips the + header frame, unlike Traktor), a header-less MP3 0, an M4A its edit list's + priming (1024 from FFmpeg, 2112 from Apple — rekordbox ignores the edit + list), lossless 0. Measured with blinded cues in rekordbox 7 (kit 4, + 2026-09-30); it replaced a fixed 1105 that was 25 ms wrong on header-less + MP3s and 22 ms on Apple AAC. The file is read (`core/mp3_gapless.py`, + `core/mp4_edit.py`); one that cannot be read falls back to 1105. A position + before the decoded audio (a Traktor grid anchored in the header frame) + clamps to 0 on write, and `beats_from_markers` drops beats before 0 while + keeping the rest's bar numbering. The OneLibrary fixture's demo MP3s are + 12-byte stubs, so the fixture tests exercise only the fallback — + `test_timebase.py` covers the per-file rule. The generic model is the decoded time base, so `adapters/rekordbox/timebase.py` is applied at EVERY Pioneer boundary: both exporters add it, the OneLibrary reader and the Rekordbox adapter subtract it on read and add it on write (`set_cue`, diff --git a/backend/konduktor/adapters/rekordbox/beatgrid.py b/backend/konduktor/adapters/rekordbox/beatgrid.py index 642e1ea..1c32bac 100644 --- a/backend/konduktor/adapters/rekordbox/beatgrid.py +++ b/backend/konduktor/adapters/rekordbox/beatgrid.py @@ -99,9 +99,15 @@ def beats_from_markers( n = 1 # Guard against a zero/negative span producing an endless loop. while t < end - 1e-9 and step > 0: - beat_nums.append(n) - bpms.append(m.bpm) - times.append(t) + # A beat before the audio starts is skipped but still COUNTED, so the + # next one keeps its place in the bar. The generic model can hold one + # (a Traktor grid anchored inside an MP3's header frame reads + # negative); rekordbox stores no negative times, and clamping it to 0 + # would invent a beat there. + if t >= 0.0: + beat_nums.append(n) + bpms.append(m.bpm) + times.append(t) n = n % 4 + 1 t += step return beat_nums, bpms, times diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index 34b6d5c..6019ca3 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -324,11 +324,11 @@ class RekordboxStore: def time_offset(self, track_id: str) -> float: """Seconds rekordbox's clock runs behind the decoded audio for this - track (~25 ms on MP3/AAC, 0 lossless). Added on every position written, - subtracted on every position read — see `timebase`. Decided by the - stored FolderPath's format, so it holds even when the file is offline.""" - folder = getattr(self.content(track_id), "FolderPath", None) - return timebase.offset(str(folder) if folder else None) + track — per FILE (an MP3's header, an M4A's edit list; 0 lossless). + Added on every position written, subtracted on every position read — + see `timebase`. Read from the file as it resolves here (path mapping + applied); a file that is offline falls back to its format's default.""" + return timebase.offset(self.audio_path(track_id)) def cover_art(self, track_id: str) -> tuple[bytes, str] | None: """The art embedded in the audio file, else Rekordbox's own copy. diff --git a/backend/konduktor/adapters/rekordbox/timebase.py b/backend/konduktor/adapters/rekordbox/timebase.py index 17305ce..b85c007 100644 --- a/backend/konduktor/adapters/rekordbox/timebase.py +++ b/backend/konduktor/adapters/rekordbox/timebase.py @@ -1,36 +1,53 @@ """Pioneer's clock vs the decoded audio's — one rule, used at every boundary. -**On MP3 and AAC, rekordbox's time 0 is NOT the decoded audio's time 0.** It does -not trim the codec delay a decoder removes, so every position it stores — beats, -cues, loops — sits a constant 1105 samples (~25 ms at 44.1 kHz) LATER than the -same moment in the decoded audio. Lossless files have no such delay. +**rekordbox's time 0 is not always the decoded audio's time 0**, and by how much +depends on the FILE, not just its format. rekordbox does not trim the start +padding a gapless decoder removes, so every position it stores — beats, cues, +loops — sits LATER than the same moment in the decoded audio by exactly that +padding: -Measured, not assumed: Konduktor's grid detector (which works in the decoded -time base) against rekordbox's own grids for the local library gave a median of -+25.0 ms on 16 MP3s, +24.5 ms on 4 M4As and 0.0 ms on 7 WAVs. 1105 samples is the -classic MP3 codec delay (576 encoder + 529 decoder). + * **MP3 with a Xing/Info header**: the header's encoder delay + 529 decoder + delay — 1105 samples (~25 ms at 44.1 kHz) for LAME's usual 576. rekordbox + SKIPS the header frame (Traktor does not — see `adapters/traktor/timebase.py`), + it just does not trim. + * **MP3 without a header**: 0. No decoder knows the delay, so none trims it. + * **AAC / M4A** (incl. a Traktor `.stem.m4a`): the edit list's priming, which + rekordbox ignores — 1024 samples from FFmpeg's encoder, 2112 from Apple's. + * **Lossless**: 0. -The generic model is in the DECODED time base — it is what Konduktor's deck plays -and what the grid detector measures. (Traktor's clock differs from it too, by a -different rule: `adapters/traktor/timebase.py`.) So a -Pioneer adapter ADDS the offset on every write and SUBTRACTS it on every read. -Get it wrong and nothing fails: every cue and beat is simply 25 ms early in -rekordbox (as the first OneLibrary exports were), or late in Konduktor. +Measured 2026-09-30 in rekordbox 7 with kit 4 (see the stem-conversion discussion +log): blinded hotcues Konduktor wrote on a synthetic kick landed on it only at +these offsets, hot cues placed by hand read back at them to rekordbox's 1 ms +resolution, and rekordbox's own grids agree. It replaced a fixed 1105 samples +for every lossy file, fitted to a library of MP3s that all had headers and +FFmpeg-encoded M4As — right for those, 25 ms wrong on a header-less MP3 and +22 ms wrong on Apple-encoded AAC. -Suspected, not yet measured: on an MP3 WITHOUT a Xing/Info header the decoder -trims nothing either, so the offset there should be 0, not 1105 — the three -header-less MP3s imported from a stick are exactly the ones whose grids read -~25 ms off (`core/mp3_gapless.py` can tell them apart). +Derived, not measured: an MP3 header whose delay field a decoder does not trust +(no LAME/Lavf/Lavc tag, or VBRI) — nothing is trimmed, so 0. + +A file that cannot be READ (offline, or a path that does not resolve) falls back +to the old 1105 samples for a lossy suffix: the overwhelmingly common case, and +what every position written before this rule assumed. + +The generic model is in the DECODED time base — what Konduktor's deck plays and +the grid detector measures. So a Pioneer adapter ADDS the offset on every write +and SUBTRACTS it on every read. Get it wrong and nothing fails: every cue and +beat is simply early in rekordbox (as the first OneLibrary exports were), or +late in Konduktor. """ from __future__ import annotations from functools import lru_cache from pathlib import Path -#: The codec delay rekordbox does not trim. +from ...core import mp3_gapless, mp4_edit + +#: The fallback for a lossy file that cannot be read: MP3's classic codec delay. CODEC_DELAY_SAMPLES = 1105 -#: Formats that carry one. `.stem.m4a` (a Traktor STEM) is AAC. +#: Formats that carry a start padding. `.stem.m4a` (a Traktor STEM) is AAC. LOSSY = frozenset({".mp3", ".m4a", ".mp4", ".aac"}) +_MP4 = frozenset({".m4a", ".mp4"}) _DEFAULT_RATE = 44100 @@ -45,23 +62,43 @@ def _sample_rate(path: str) -> int: return _DEFAULT_RATE +def _measured(p: Path) -> float | None: + """The per-file offset, or None when the file cannot be read.""" + suffix = p.suffix.lower() + if suffix == ".mp3": + start = mp3_gapless.read(p) + if start is None: + return None + return start.trimmed / start.sample_rate if start.header_frame else 0.0 + if suffix in _MP4: + return mp4_edit.priming_seconds(p) + return None # raw ADTS .aac: nothing to read, keep the fallback + + def offset(path: Path | str | None) -> float: """Seconds to ADD to a decoded-audio time to get rekordbox's; 0 if lossless. A missing path (a track whose audio cannot be located) gets 0: there is no file to say which format it is, and guessing lossy would move a lossless - track's cues. + track's cues. A path to a lossy file that cannot be read gets the fallback. """ if not path: return 0.0 p = Path(path) if p.suffix.lower() not in LOSSY: return 0.0 + measured = _measured(p) + if measured is not None: + return measured return CODEC_DELAY_SAMPLES / _sample_rate(str(p)) def to_pioneer(seconds: float, off: float) -> float: - return seconds + off + """A decoded-audio time -> rekordbox's, never before its own time 0: the + generic model can hold a position before the decoded audio starts (a + Traktor grid anchored inside an MP3's header frame), which no Pioneer field + can store.""" + return max(0.0, seconds + off) def from_pioneer(seconds: float, off: float) -> float: diff --git a/backend/konduktor/core/mp4_edit.py b/backend/konduktor/core/mp4_edit.py new file mode 100644 index 0000000..3891f38 --- /dev/null +++ b/backend/konduktor/core/mp4_edit.py @@ -0,0 +1,106 @@ +"""The priming an MP4/M4A's edit list tells a decoder to skip. + +An AAC encoder emits `priming` samples of lead-in before the audio proper — +1024 from FFmpeg's `aac`, 2112 from Apple's — and records it as the +`media_time` of the audio track's edit list (`moov/trak/edts/elst`). A decoder +that honours the edit list (FFmpeg, CoreAudio, Traktor) starts the audio after +it; one that ignores it (rekordbox) plays the priming as audio. What a platform +does with it lives in that platform's `timebase`; this only reads the box. + +Only box headers are read and `mdat` is seeked past, so `moov` at the END of a +file (FFmpeg's default, and every commercial stem file) costs a few reads. +""" +from __future__ import annotations + +import os +import struct +from functools import lru_cache +from pathlib import Path + +_CONTAINERS = {b"moov", b"trak", b"mdia", b"edts"} + + +def _boxes(f, start: int, end: int): + """(type, payload offset, payload end) for each box in [start, end).""" + pos = start + while pos + 8 <= end: + f.seek(pos) + head = f.read(8) + if len(head) < 8: + return + size, kind = struct.unpack(">I4s", head) + body = pos + 8 + if size == 1: + size = struct.unpack(">Q", f.read(8))[0] + body = pos + 16 + elif size == 0: + size = end - pos + if size < 8: + return + yield kind, body, min(pos + size, end) + pos += size + + +def _audio_track_priming(f, trak_start: int, trak_end: int) -> tuple[int, int] | None: + """(media_time, media timescale) of one trak if it is audio, else None.""" + handler = timescale = None + media_time = 0 # no edit list: nothing to skip + for kind, body, end in _boxes(f, trak_start, trak_end): + if kind == b"mdia": + for k2, b2, e2 in _boxes(f, body, end): + f.seek(b2) + if k2 == b"hdlr": + handler = f.read(12)[8:12] + elif k2 == b"mdhd": + version = f.read(1)[0] + f.seek(b2 + (20 if version == 1 else 12)) + timescale = struct.unpack(">I", f.read(4))[0] + elif kind == b"edts": + for k2, b2, e2 in _boxes(f, body, end): + if k2 != b"elst": + continue + f.seek(b2) + version = f.read(1)[0] + f.read(3) + count = struct.unpack(">I", f.read(4))[0] + for _ in range(count): + if version == 1: + _dur, mt = struct.unpack(">Qq", f.read(16)) + else: + _dur, mt = struct.unpack(">Ii", f.read(8)) + f.read(4) # media rate + if mt >= 0: # -1 is an EMPTY edit (a delay), not a skip + media_time = mt + break + if handler != b"soun" or not timescale: + return None + return media_time, timescale + + +@lru_cache(maxsize=16384) +def _read_cached(path: str, size: int, mtime_ns: int) -> float | None: + with open(path, "rb") as f: + for kind, body, end in _boxes(f, 0, size): + if kind != b"moov": + continue + for k2, b2, e2 in _boxes(f, body, end): + if k2 == b"trak": + found = _audio_track_priming(f, b2, e2) + if found is not None: # the FIRST audio track: a stem's master + media_time, timescale = found + return media_time / timescale + return None + return None + + +def priming_seconds(path: Path | str | None) -> float | None: + """Seconds of priming the first audio track's edit list skips (0.0 when it + has no edit list); None when the file is missing or not a readable MP4. + Cached per (path, size, mtime), like `mp3_gapless.read`.""" + if not path: + return None + try: + st = os.stat(path) + return _read_cached(str(path), st.st_size, st.st_mtime_ns) + except (OSError, struct.error, IndexError): + return None diff --git a/backend/test_timebase.py b/backend/test_timebase.py index edfc839..b24b197 100644 --- a/backend/test_timebase.py +++ b/backend/test_timebase.py @@ -210,5 +210,70 @@ else: if not seen: print(" (skipped: no hand-placed pad-8 cues in kit 4)") +print("== 4. rekordbox's clock is per file too (Pioneer timebase) ==") +from konduktor.adapters.rekordbox import beatgrid as pioneer_grid # noqa: E402 +from konduktor.adapters.rekordbox import timebase as pioneer # noqa: E402 +from konduktor.core import mp4_edit # noqa: E402 +from konduktor.core.model import GridMarker # noqa: E402 + +(tmp / "xing-moved.mp3").rename(XING) # section 2 moved it away +AAC = tmp / "ffmpeg.m4a" +encode(AAC, "aac", "ipod", bit_rate=256_000) +check("an FFmpeg AAC's edit list primes 1024 samples", mp4_edit.priming_seconds(AAC) == 1024 / 44100, + str(mp4_edit.priming_seconds(AAC))) +check("MP3 with a header: the trimmed 1105 samples", abs(pioneer.offset(XING) - 1105 / 44100) < 1e-12) +check("MP3 at 48 kHz: 1105 SAMPLES", abs(pioneer.offset(MP3_48K) - 1105 / 48000) < 1e-12) +check("MP3 without a header: 0 (nothing is trimmed)", pioneer.offset(NOXING) == 0.0) +check("AAC: the edit list's priming (rekordbox ignores it)", pioneer.offset(AAC) == 1024 / 44100) +if "aac_at" in av.codecs_available: + APPLE = tmp / "apple.m4a" + encode(APPLE, "aac_at", "ipod", bit_rate=256_000) + check("Apple AAC: 2112 samples of priming", pioneer.offset(APPLE) == 2112 / 44100, str(pioneer.offset(APPLE))) +check("WAV: 0", pioneer.offset(WAV) == 0.0) +check("an unreadable MP3 keeps the old 1105-sample default", + abs(pioneer.offset(tmp / "offline.mp3") - 1105 / 44100) < 1e-12) +check("no path: 0", pioneer.offset(None) == 0.0) +check("a position before the decoded audio clamps to rekordbox's 0 on write", + pioneer.to_pioneer(-0.030, 1105 / 44100) == 0.0) + +# A Traktor grid anchored inside the header frame reads NEGATIVE; expanding it +# for a Pioneer export must drop the beats before 0 — and number the rest as +# if nothing had been dropped, or every bar would start on the wrong beat. +nums, _bpms, times = pioneer_grid.beats_from_markers([GridMarker(start=-0.030, bpm=120.0)], 3.0) +check("no beat before 0 is written", min(times) >= 0.0, str(times[:3])) +check("the first kept beat is beat 2 of the bar, 0.47 s in", + nums[0] == 2 and abs(times[0] - 0.47) < 1e-9, f"{nums[:4]} {times[:2]}") + +print("== 5. rekordbox's own hand-placed cues land on the kick (kit 4) ==") +MASTER = Path.home() / "Library/Pioneer/rekordbox/master.db" +if not (KIT.is_dir() and MASTER.is_file()): + print(" (skipped: kit 4 or the local rekordbox library is not on this machine)") +else: + from pyrekordbox.masterdb import MasterDatabase # noqa: E402 + + seen = 0 + db = MasterDatabase(MASTER) + try: + for c in db.get_cue(): + name = c.Content.FileNameL if c.Content else "" + if not name.startswith("K4-") or c.Kind != 9 or not (KIT / name).is_file(): + continue # pad H: the ones placed by hand + with av.open(str(KIT / name), metadata_errors="ignore") as con: + st = con.streams.audio[0] + sr = st.rate + y = np.concatenate([f.to_ndarray()[0] for f in con.decode(st)]).astype(np.float64) + a = int(8.9 * sr) + onset = (a + int(np.argmax(np.abs(y[a:a + int(0.2 * sr)]) > 0.05))) / sr + decoded = pioneer.from_pioneer(c.InMsec / 1000, pioneer.offset(KIT / name)) + err = (decoded - onset) * 1000 + seen += 1 + # rekordbox stores whole milliseconds, apparently truncated. + check(f"{name}: a cue placed in rekordbox reads back on the kick (±1.5 ms)", abs(err) < 1.5, + f"{err:+.2f} ms") + finally: + db.close() + if not seen: + print(" (skipped: no hand-placed pad-H cues in kit 4)") + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0)