Refined traktor timing fix

This commit is contained in:
patben8 committed 2026-09-30 11:18:10 +02:00
1 parent 2a4c403d43
commit d087310a9d
11 files changed
+489 -20

No files matched your search

+26 -2
View File
@@ -104,8 +104,10 @@ Two independent apps that talk over HTTP:
or a syncopated bassline. Positions are in the **decoded audio's** time or a syncopated bassline. Positions are in the **decoded audio's** time
base (libsndfile = CoreAudio to the sample on MP3). **Rekordbox's grids sit 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 a constant ~25 ms later on lossy files** and at 0 on WAV — a platform
time-base difference, deliberately NOT corrected here; Traktor's is time-base difference, deliberately NOT corrected here. Traktor's differs
unmeasured. `backend/bench_grid_detect.py` scores it against any library's 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`.
`backend/bench_grid_detect.py` scores it against any library's
single-marker grids and reports that constant separately from detection single-marker grids and reports that constant separately from detection
error (29 Rekordbox references: old 1/29 BPMs, new 27/29). error (29 Rekordbox references: old 1/29 BPMs, new 27/29).
- `places.py` — where a person keeps things on THIS computer: the user's own - `places.py` — where a person keeps things on THIS computer: the user's own
@@ -149,6 +151,21 @@ Two independent apps that talk over HTTP:
- `driver.py`/`discovery.py` — `can_open`, default-location detection, restore. - `driver.py`/`discovery.py` — `can_open`, default-location detection, restore.
- `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion - `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion
rules, LOCATION ↔ OS path conversion, and its capability set. rules, LOCATION ↔ OS path conversion, and its capability set.
- `timebase.py` — **Traktor's clock vs the decoded audio.** Traktor decodes
MP3 naively (ignores the LAME gapless fields, decodes the Xing/Info
header frame as audio), so on an MP3 WITH a header every stored position
sits `samples_per_frame + encoder_delay + 529` samples (2257 = ~51 ms at
44.1 kHz, 47 ms at 48 kHz) later than the decoded audio; header-less
MP3s and every other format are 0. Measured in Traktor 4.5 with blinded
cues in both directions (kit 4, in the stem-conversion discussion log).
The store ADDS it at its four seconds→START writes (`time_offset_ms`),
`projection.to_track_cues` SUBTRACTS it, and a read is **never clamped
at 0**: Traktor anchors grids inside the header frame, and clamping would
move them on the next write-back (`buildBeatGrid` keeps negative starts
for the same reason). A file that cannot be read gets 0 and is not
cached. The header itself is read by `core/mp3_gapless.py`, which skips
the ID3v2 tag first — a check that did not once misread every real MP3
as header-less.
- `adapters/rekordbox/` — **track metadata, playlists and hot cues writable; - `adapters/rekordbox/` — **track metadata, playlists and hot cues writable;
the beatgrid still read-only** (milestones 2 and 3a). Also home to the beatgrid still read-only** (milestones 2 and 3a). Also home to
`anlz_writer.py`, which BUILDS analysis files from nothing — Pioneer's format, `anlz_writer.py`, which BUILDS analysis files from nothing — Pioneer's format,
@@ -570,6 +587,13 @@ serialization path.** It enforces:
The guard that catches serialization regressions like the lxml reformatting bug. The guard that catches serialization regressions like the lxml reformatting bug.
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. Traktor-valid, backup-first, COLLECTION byte-identical, original untouched.
- `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated
MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset
in samples (2257 at 44.1 and 48 kHz, 0 header-less / WAV / missing), every
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.
- `test_traktor_adapter.py` — the **generic layer**: one parse per open, the - `test_traktor_adapter.py` — the **generic layer**: one parse per open, the
projection refreshing after every command family, cue-type translation, projection refreshing after every command family, cue-type translation,
capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity` capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity`
@@ -10,11 +10,17 @@ 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 +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). classic MP3 codec delay (576 encoder + 529 decoder).
The generic model is in the DECODED time base — it is what Konduktor's deck plays, The generic model is in the DECODED time base — it is what Konduktor's deck plays
what Traktor's positions line up with, and what the grid detector measures. So a 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. 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 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. rekordbox (as the first OneLibrary exports were), or late in Konduktor.
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).
""" """
from __future__ import annotations from __future__ import annotations
@@ -50,7 +50,7 @@ class TraktorAdapter:
if entry is None: if entry is None:
return TrackCues() return TrackCues()
self._index.replace(projection.to_track(entry)) self._index.replace(projection.to_track(entry))
return projection.to_track_cues(entry) return projection.to_track_cues(entry, self._store.time_offset_ms(entry))
# ---- read ------------------------------------------------------------ # ---- read ------------------------------------------------------------
@property @property
@@ -75,7 +75,9 @@ class TraktorAdapter:
def track_cues(self, track_id: str) -> TrackCues | None: def track_cues(self, track_id: str) -> TrackCues | None:
entry = self._store.model_entry(track_id) entry = self._store.model_entry(track_id)
return projection.to_track_cues(entry) if entry is not None else None if entry is None:
return None
return projection.to_track_cues(entry, self._store.time_offset_ms(entry))
# ---- transitional shims -------------------------------------------- # ---- transitional shims --------------------------------------------
# main.py still drives the store directly and calls replace_track after each # main.py still drives the store directly and calls replace_track after each
@@ -8,7 +8,7 @@ from __future__ import annotations
import re import re
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid from . import beatgrid, timebase
from .cue_types import NATIVE_TO_CUE_TYPE from .cue_types import NATIVE_TO_CUE_TYPE
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"), # Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
@@ -157,9 +157,13 @@ def to_track(e) -> Track:
) )
def to_track_cues(entry) -> TrackCues: def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
"""Project an ENTRY's beatgrid + cues. """Project an ENTRY's beatgrid + cues.
`offset_ms` is how far the entry's positions sit behind the decoded audio
(`TraktorStore.time_offset_ms`, see `timebase`); positions come out in the
decoded time base, unclamped.
The beatgrid is the FULL ordered marker list — a constant grid is a list of The beatgrid is the FULL ordered marker list — a constant grid is a list of
length one. Grid markers themselves are not cues; their companion cues are, length one. Grid markers themselves are not cues; their companion cues are,
because they occupy real hotcue slots. Each is tagged with the marker it sits because they occupy real hotcue slots. Each is tagged with the marker it sits
@@ -171,7 +175,7 @@ def to_track_cues(entry) -> TrackCues:
marker_of = {id(c): i for i, c in comps.items()} marker_of = {id(c): i for i, c in comps.items()}
grid_markers = [ grid_markers = [
GridMarker( GridMarker(
start=(m.start or 0.0) / 1000.0, # Traktor stores START in ms start=timebase.from_traktor_ms(m.start or 0.0, offset_ms), # START is ms
bpm=m.grid.bpm if m.grid and m.grid.bpm else 0.0, bpm=m.grid.bpm if m.grid and m.grid.bpm else 0.0,
name=m.name, name=m.name,
companion=comps[i].hotcue if i in comps else None, companion=comps[i].hotcue if i in comps else None,
@@ -192,7 +196,7 @@ def to_track_cues(entry) -> TrackCues:
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"), type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
# Every Traktor cue lives in the hotcue bank. # Every Traktor cue lives in the hotcue bank.
role="hotcue", role="hotcue",
start=(c.start or 0.0) / 1000.0, start=timebase.from_traktor_ms(c.start or 0.0, offset_ms),
length=(c.len or 0.0) / 1000.0, length=(c.len or 0.0) / 1000.0,
slot=slot, slot=slot,
color=c.color, color=c.color,
+14 -5
View File
@@ -49,7 +49,7 @@ from ...core.pathmap import common_dir_prefix
from ...core.pathmap import PathMapping from ...core.pathmap import PathMapping
from ...core.relocate import PathGroup from ...core.relocate import PathGroup
from ...schemas import PlaylistNode from ...schemas import PlaylistNode
from . import beatgrid from . import beatgrid, timebase
from .locations import os_path_to_location, resolve_path from .locations import os_path_to_location, resolve_path
from .projection import iso_date, traktor_date from .projection import iso_date, traktor_date
@@ -603,7 +603,9 @@ class TraktorStore:
raise PlaylistError(f"Unsupported cue type: {cue_type}") raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock: with self._lock:
entry = self._entry_or_raise(track_id) entry = self._entry_or_raise(track_id)
start_ms = max(0.0, start_sec * 1000.0) # Traktor stores START/LEN in ms # Traktor stores START/LEN in ms, on its own clock (see `timebase`).
# A length is a duration, so the offset does not apply to it.
start_ms = timebase.to_traktor_ms(start_sec, self.time_offset_ms(entry))
len_ms = max(0.0, length_sec * 1000.0) len_ms = max(0.0, length_sec * 1000.0)
existing = next( existing = next(
(c for c in (entry.cue_v2 or []) if c.hotcue == slot), None (c for c in (entry.cue_v2 or []) if c.hotcue == slot), None
@@ -758,7 +760,7 @@ class TraktorStore:
raise PlaylistError(f"BPM must be positive: {bpm}") raise PlaylistError(f"BPM must be positive: {bpm}")
with self._lock: with self._lock:
entry = self._entry_or_raise(track_id) entry = self._entry_or_raise(track_id)
start_ms = max(0.0, start_sec * 1000.0) start_ms = timebase.to_traktor_ms(start_sec, self.time_offset_ms(entry))
markers = beatgrid.grid_markers(entry) markers = beatgrid.grid_markers(entry)
for m in markers: for m in markers:
if abs((m.start or 0.0) - start_ms) < self._MARKER_MIN_GAP_MS: if abs((m.start or 0.0) - start_ms) < self._MARKER_MIN_GAP_MS:
@@ -818,7 +820,7 @@ class TraktorStore:
with self._lock: with self._lock:
entry = self._entry_or_raise(track_id) entry = self._entry_or_raise(track_id)
markers, marker = self._markers_or_raise(entry, index) markers, marker = self._markers_or_raise(entry, index)
start_ms = max(0.0, start_sec * 1000.0) start_ms = timebase.to_traktor_ms(start_sec, self.time_offset_ms(entry))
if index > 0: if index > 0:
lo = (markers[index - 1].start or 0.0) + self._MARKER_MIN_GAP_MS lo = (markers[index - 1].start or 0.0) + self._MARKER_MIN_GAP_MS
start_ms = max(start_ms, lo) start_ms = max(start_ms, lo)
@@ -882,6 +884,7 @@ class TraktorStore:
raise PlaylistError(f"BPM must be positive: {bpm}") raise PlaylistError(f"BPM must be positive: {bpm}")
with self._lock: with self._lock:
entry = self._entry_or_raise(track_id) entry = self._entry_or_raise(track_id)
off_ms = self.time_offset_ms(entry)
self._drop_grid(entry) self._drop_grid(entry)
if entry.cue_v2 is None: if entry.cue_v2 is None:
entry.cue_v2 = [] entry.cue_v2 = []
@@ -893,7 +896,7 @@ class TraktorStore:
name="AutoGrid" if i == 0 else "n.n.", name="AutoGrid" if i == 0 else "n.n.",
displ_order=0, displ_order=0,
type=4, type=4,
start=max(0.0, start_sec * 1000.0), start=timebase.to_traktor_ms(start_sec, off_ms),
len=0.0, len=0.0,
repeats=-1, repeats=-1,
hotcue=-1, hotcue=-1,
@@ -1052,6 +1055,12 @@ class TraktorStore:
path = self._resolve(entry.location) path = self._resolve(entry.location)
return file_tags.read_cover(path) if path else None return file_tags.read_cover(path) if path else None
def time_offset_ms(self, entry: Entrytype) -> float:
"""How far this entry's positions sit behind the decoded audio, in ms
(see `timebase`). Every seconds <-> START conversion goes through it:
the four writes here and `projection.to_track_cues` on the way out."""
return timebase.offset_ms(self._resolve(entry.location) if entry.location else None)
def audio_path(self, track_id: str) -> "Path | None": def audio_path(self, track_id: str) -> "Path | None":
"""Resolve a track's audio file to an OS path (for playback streaming).""" """Resolve a track's audio file to an OS path (for playback streaming)."""
with self._lock: with self._lock:
@@ -0,0 +1,70 @@
"""Traktor's clock vs the decoded audio's — one rule, used at every boundary.
**On an MP3 with a gapless header, Traktor's time 0 is NOT the decoded audio's
time 0.** Traktor decodes MP3 naively: it ignores the LAME gapless fields and
decodes the Xing/Info header frame as if it were audio. A gapless decoder skips
that frame and trims the encoder's start padding. So every position Traktor
stores — grid markers, cues, loops — sits
samples_per_frame + encoder_delay + 529 (= 2257 for LAME's usual 576)
samples LATER than the same moment in the decoded audio: ~51.2 ms at 44.1 kHz,
~47.0 ms at 48 kHz. The rule is in SAMPLES. An MP3 WITHOUT a header is decoded
the same way by both sides (nothing to skip, nothing to trim), so its offset is
0 — as is every other format: WAV, AIFF, FLAC and AAC (Traktor honours the MP4
edit list) line up to the sample.
Measured 2026-09-30 in Traktor 4.5 ("kit 4", see the stem-conversion discussion
log): hotcues Konduktor wrote on a synthetic kick, blinded, landed on it only
at this offset, and hotcues placed by hand in Traktor read back at it (+2255 at
44.1 kHz, +2242 at 48 kHz, header-less −6, WAV −4, AAC −13). Traktor's AutoGrid
agrees, and `bench_grid_detect.py` shows it on every Traktor-analysed MP3.
Derived, not measured: a header frame whose delay field a gapless decoder does
not trust (no LAME/Lavf/Lavc tag, or a VBRI tag) — the decoder then skips the
frame but trims nothing, so the offset is one frame.
The generic model is in the DECODED time base — what Konduktor's deck plays and
the grid detector measures. So the Traktor store ADDS the offset on every write
and the projection SUBTRACTS it on every read. A read is NOT clamped at 0: a
Traktor grid anchor can sit inside the header frame (a beat before the decoded
audio starts), and clamping it would move the grid on its next write-back.
Get it wrong and nothing fails: every MP3 cue and beat is simply ~51 ms early in
Traktor, or late in Konduktor — which is what every release before this did.
"""
from __future__ import annotations
from pathlib import Path
from ...core import mp3_gapless
def offset_samples(path: Path | str | None) -> tuple[int, int]:
"""(samples Traktor runs behind the decoded audio, sample rate).
(0, 0) for anything that is not an MP3 with a header frame — including a
file that cannot be read: with no header to go by, 0 is the answer that
cannot move a cue, since a position read at 0 is written back at 0.
"""
if not path or Path(path).suffix.lower() != ".mp3":
return 0, 0
start = mp3_gapless.read(path)
if start is None or not start.header_frame:
return 0, 0
return start.samples_per_frame + start.trimmed, start.sample_rate
def offset_ms(path: Path | str | None) -> float:
"""Milliseconds to ADD to a decoded-audio time to get Traktor's."""
samples, rate = offset_samples(path)
return samples * 1000.0 / rate if samples else 0.0
def to_traktor_ms(seconds: float, off_ms: float) -> float:
"""A decoded-audio time in seconds -> a Traktor START in ms (never < 0:
Traktor cannot store a position before its own time 0)."""
return max(0.0, seconds * 1000.0 + off_ms)
def from_traktor_ms(start_ms: float, off_ms: float) -> float:
"""A Traktor START in ms -> decoded-audio seconds. Deliberately unclamped."""
return (start_ms - off_ms) / 1000.0
+127
View File
@@ -0,0 +1,127 @@
"""What an MP3's first frame says about where its audio starts.
A gapless MP3 opens with a HEADER FRAME — a valid MPEG frame whose payload is a
`Xing` (VBR) or `Info` (CBR) tag instead of audio — often followed by a LAME
extension recording the encoder delay. A gapless decoder (FFmpeg, libsndfile's
mpg123, CoreAudio) skips that frame and trims `encoder delay + 529` samples of
start padding; a naive one decodes the frame as silence and trims nothing. Where
a platform's clock sits relative to Konduktor's decoded time base therefore
depends on these facts, per file — which is why they are read here, once, rather
than assumed per format.
Format knowledge, not platform knowledge: this reads bytes and says what is
there. What a platform DOES with them lives in that platform's `timebase`.
Two things are easy to get wrong, and both were got wrong once:
* the first frame comes AFTER the ID3v2 tag, which can be megabytes of cover
art — a check that only looks at the start of the file sees no header;
* the tag sits at a fixed offset after the side information, whose size
depends on the MPEG version and channel mode.
"""
from __future__ import annotations
import os
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
#: The mp3 decoder delay a gapless decoder trims on top of the encoder's.
DECODER_DELAY = 529
#: Encoder strings whose LAME-style delay field FFmpeg (and mpg123) honour.
_TRUSTED_ENCODERS = (b"LAME", b"Lavf", b"Lavc")
#: How far past the ID3 tag to look for the first frame (junk, padding).
_SCAN = 64 * 1024
_RATES = {3: (44100, 48000, 32000), 2: (22050, 24000, 16000), 0: (11025, 12000, 8000)}
@dataclass(frozen=True)
class Mp3Start:
sample_rate: int
#: Samples in one frame: 1152 for MPEG-1 Layer III, 576 for MPEG-2/2.5.
samples_per_frame: int
#: The first frame is a Xing/Info/VBRI tag, not audio.
header_frame: bool
#: Encoder delay from a LAME-style tag a gapless decoder trusts, else None.
encoder_delay: int | None
@property
def trimmed(self) -> int:
"""Samples of start padding a gapless decoder removes (0 without a
trusted delay field: it has nothing to trim by)."""
return 0 if self.encoder_delay is None else self.encoder_delay + DECODER_DELAY
def _id3_end(head: bytes) -> int:
if head[:3] != b"ID3" or len(head) < 10:
return 0
size = ((head[6] & 127) << 21) | ((head[7] & 127) << 14) | ((head[8] & 127) << 7) | (head[9] & 127)
footer = 10 if head[5] & 0x10 else 0
return 10 + size + footer
def _frame_header(b: bytes, i: int):
"""(version bits, sample rate, mono) if a Layer III frame header starts at i."""
if i + 4 > len(b) or b[i] != 0xFF or (b[i + 1] & 0xE0) != 0xE0:
return None
version = (b[i + 1] >> 3) & 3
layer = (b[i + 1] >> 1) & 3
bitrate = b[i + 2] >> 4
rate = (b[i + 2] >> 2) & 3
if version == 1 or layer != 1 or bitrate in (0, 15) or rate == 3:
return None
return version, _RATES[version][rate], (b[i + 3] >> 6) == 3
def parse(data: bytes, audio_start: int = 0) -> Mp3Start | None:
"""Read the first frame of `data`, whose audio starts at `audio_start`
(after any ID3v2 tag). None if no Layer III frame is found."""
for i in range(audio_start, min(len(data) - 4, audio_start + _SCAN)):
hdr = _frame_header(data, i)
if hdr is None:
continue
version, rate, mono = hdr
mpeg1 = version == 3
spf = 1152 if mpeg1 else 576
side = (17 if mono else 32) if mpeg1 else (9 if mono else 17)
x = i + 4 + side
tag = data[x:x + 4]
if tag in (b"Xing", b"Info"):
flags = int.from_bytes(data[x + 4:x + 8], "big")
lame = x + 8 + (4 if flags & 1 else 0) + (4 if flags & 2 else 0) \
+ (100 if flags & 4 else 0) + (4 if flags & 8 else 0)
delay = None
if data[lame:lame + 4] in _TRUSTED_ENCODERS and len(data) >= lame + 24:
d = data[lame + 21:lame + 24]
delay = (d[0] << 4) | (d[1] >> 4)
return Mp3Start(rate, spf, True, delay)
if data[i + 36:i + 40] == b"VBRI": # Fraunhofer's tag, always at 32 + 4
return Mp3Start(rate, spf, True, None)
return Mp3Start(rate, spf, False, None)
return None
@lru_cache(maxsize=16384)
def _read_cached(path: str, size: int, mtime_ns: int) -> Mp3Start | None:
with open(path, "rb") as f:
head = f.read(10)
start = _id3_end(head)
f.seek(start)
# Enough for the first frame and a scan past junk before it.
return parse(f.read(_SCAN + 2048), 0)
def read(path: Path | str | None) -> Mp3Start | None:
"""`parse` a file on disk; None when it is missing, unreadable or no MP3.
Cached per (path, size, mtime), so a file that appears later — a drive
plugged in mid-session — or is replaced is read afresh, and a missing one is
never remembered as headerless.
"""
if not path:
return None
try:
st = os.stat(path)
return _read_cached(str(path), st.st_size, st.st_mtime_ns)
except OSError:
return None
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate source .venv/bin/activate
fail=0 fail=0
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py; do for t in test_layering.py test_save_fidelity.py test_timebase.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py; do
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
echo "▶ $t" echo "▶ $t"
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
+214
View File
@@ -0,0 +1,214 @@
"""Traktor's MP3 time base — the offset between its clock and the decoded audio.
Nothing fails when this is wrong: every MP3 cue and beat is simply ~51 ms off,
which is what every release before `adapters/traktor/timebase.py` did. So this
pins the numbers rather than trusting them, in three layers:
1. `core.mp3_gapless` on GENERATED MP3s: the header frame is found AFTER an
ID3 tag holding a megabyte of art (the check that missed it once read only
the start of the file), and a header-less MP3 has none.
2. The Traktor store and projection on a skeleton collection pointing at those
files: a write adds the offset, a read subtracts it, a read is NOT clamped
(a grid anchored inside the header frame survives a Reset byte for byte),
and a file with nothing to go by — WAV, missing — gets 0.
3. Traktor's OWN data: the hotcues placed by hand in Traktor 4.5 on kit 4's
synthetic kick must read back onto that kick in the decoded audio. Skipped
cleanly when kit 4 or its collection is not on this machine.
"""
from __future__ import annotations
import os
import re
import sys
import tempfile
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-timebase-appdata-")
import av # noqa: E402
import numpy as np # noqa: E402
from konduktor.adapters.traktor import timebase # noqa: E402
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
from konduktor.adapters.traktor.export import SKELETON # noqa: E402
from konduktor.core import mp3_gapless # noqa: E402
from konduktor.core.adapter import NewTrack # noqa: E402
from konduktor.core.model import Track # noqa: E402
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def encode(path: Path, codec: str, fmt: str, sr: int = 44100, container_options=None, bit_rate=320_000):
"""Two seconds of a click at 1.0 s — enough for a header; content is irrelevant."""
n = 2 * sr
x = np.zeros((2, n), dtype=np.float32)
x[:, sr:sr + 64] = 0.8
with av.open(str(path), "w", format=fmt, options=container_options or {}) as c:
s = c.add_stream(codec, rate=sr, layout="stereo")
if bit_rate and codec != "pcm_s16le":
s.bit_rate = bit_rate
step = s.codec_context.frame_size or 1024
for i in range(0, n, step):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, i:i + step]), format="fltp", layout="stereo")
f.sample_rate, f.pts = sr, i
for p in s.encode(f):
c.mux(p)
for p in s.encode(None):
c.mux(p)
def add_big_id3(path: Path):
from mutagen.id3 import APIC, ID3, TIT2
tags = ID3()
tags.add(TIT2(encoding=3, text="timebase"))
tags.add(APIC(encoding=3, mime="image/jpeg", type=3, desc="", data=os.urandom(1_000_000)))
tags.save(str(path))
tmp = Path(tempfile.mkdtemp(prefix="konduktor-timebase-"))
XING = tmp / "xing.mp3"
NOXING = tmp / "noxing.mp3"
MP3_48K = tmp / "48k.mp3"
WAV = tmp / "plain.wav"
encode(XING, "libmp3lame", "mp3")
add_big_id3(XING)
encode(NOXING, "libmp3lame", "mp3", container_options={"write_xing": "0"})
encode(MP3_48K, "libmp3lame", "mp3", sr=48000)
encode(WAV, "pcm_s16le", "wav")
print("== 1. mp3_gapless reads the first frame ==")
x = mp3_gapless.read(XING)
check("the header frame is found after a 1 MB ID3 tag", x is not None and x.header_frame, str(x))
check("…with LAME's 576-sample encoder delay", x is not None and x.encoder_delay == 576, str(x))
check("…in an MPEG-1 frame of 1152 samples", x is not None and x.samples_per_frame == 1152 and x.sample_rate == 44100)
n = mp3_gapless.read(NOXING)
check("a header-less MP3 has no header frame", n is not None and not n.header_frame, str(n))
check("a missing file reads as None (and is not cached as header-less)",
mp3_gapless.read(tmp / "gone.mp3") is None)
print("== 1b. timebase.offset ==")
check("MP3 with a header: 2257 samples", timebase.offset_samples(XING) == (2257, 44100), str(timebase.offset_samples(XING)))
check("…which is 51.18 ms at 44.1 kHz", abs(timebase.offset_ms(XING) - 51.179138) < 1e-6, str(timebase.offset_ms(XING)))
check("48 kHz: the same 2257 SAMPLES, i.e. 47.02 ms",
timebase.offset_samples(MP3_48K) == (2257, 48000) and abs(timebase.offset_ms(MP3_48K) - 47.020833) < 1e-6,
str(timebase.offset_samples(MP3_48K)))
check("header-less MP3: 0", timebase.offset_ms(NOXING) == 0.0)
check("WAV: 0", timebase.offset_ms(WAV) == 0.0)
check("a missing MP3: 0", timebase.offset_ms(tmp / "gone.mp3") == 0.0)
print("== 2. the store adds it on write, the projection subtracts it on read ==")
lib = tmp / "collection.nml"
lib.write_text(SKELETON, encoding="utf-8")
ad = TraktorAdapter(lib)
ids = dict(zip(("xing", "noxing", "wav"), ad.add_tracks([
NewTrack(track=Track(id="", title=p.stem), audio_path=p, cues=None) for p in (XING, NOXING, WAV)
])))
OFF = 2257 / 44.1 # ms
def native(tid):
return ad.store.model_entry(tid)
def cue_start_ms(tid, slot):
return next(c.start for c in native(tid).cue_v2 if c.hotcue == slot)
def marker_starts_ms(tid):
return sorted(c.start for c in native(tid).cue_v2 if c.grid is not None)
for key, off in (("xing", OFF), ("noxing", 0.0), ("wav", 0.0)):
tid = ids[key]
tc = ad.set_cue(tid, slot=0, start_sec=1.0, cue_type="cue")
check(f"{key}: a cue at 1.000 s is stored at START {1000 + off:.6f}",
abs(cue_start_ms(tid, 0) - (1000 + off)) < 1e-9, str(cue_start_ms(tid, 0)))
check(f"{key}: …and reads back at 1.000 s", abs(tc.cues[0].start - 1.0) < 1e-12, str(tc.cues[0].start))
tid = ids["xing"]
tc = ad.replace_grid(tid, [(0.5, 120.0), (1.5, 126.0)])
check("replace_grid shifts every marker", marker_starts_ms(tid) == [500 + OFF, 1500 + OFF], str(marker_starts_ms(tid)))
check("…and the projection undoes it", [round(m.start, 9) for m in tc.grid_markers] == [0.5, 1.5])
tc = ad.move_grid_marker(tid, 0, 0.25)
check("move_grid_marker shifts", abs(marker_starts_ms(tid)[0] - (250 + OFF)) < 1e-9, str(marker_starts_ms(tid)))
tc = ad.add_grid_marker(tid, 1.0)
check("add_grid_marker shifts", abs(marker_starts_ms(tid)[1] - (1000 + OFF)) < 1e-9, str(marker_starts_ms(tid)))
tc = ad.set_analysed_grid(tid, [(0.75, 124.0)])
comp = tc.grid_markers[0].companion
check("the analysed grid's companion sits on its marker",
comp is not None and abs(cue_start_ms(tid, comp) - marker_starts_ms(tid)[0]) < 1e-9,
f"slot {comp}, markers {marker_starts_ms(tid)}")
# A grid Traktor anchored INSIDE the header frame (the real collection has an
# AutoGrid at 21 ms): in decoded time it lies before the audio starts. It must
# read as a negative position, and the deck's Reset — which sends the markers
# back exactly as it loaded them — must leave the bytes alone. (No companion:
# Reset's `replace_grid` drops the old grid's companions by design.)
ad.delete_grid(tid)
for c in list(ad.track_cues(tid).cues):
ad.delete_cue(tid, c.slot)
ad.replace_grid(tid, [(0.0, 172.0)])
ad.set_cue(tid, slot=3, start_sec=0.0, cue_type="cue")
for c in native(tid).cue_v2: # as Traktor wrote them, both inside the header frame
c.start = 20.979167 if c.grid is not None else 33.5
ad.store._sort_cues(native(tid)) # as a real file would be ordered
ad.store._sync_tempo(native(tid))
before = ad.snapshot()
tc = ad.track_cues(tid)
check("a Traktor anchor inside the header frame reads as negative, unclamped",
abs(tc.grid_markers[0].start - (20.979167 - OFF) / 1000) < 1e-12, str(tc.grid_markers[0].start))
check("…as does a cue there", abs(tc.cues[0].start - (33.5 - OFF) / 1000) < 1e-12, str(tc.cues[0].start))
ad.replace_grid(tid, [(m.start, m.bpm) for m in tc.grid_markers])
ad.set_cue(tid, slot=3, start_sec=tc.cues[0].start, cue_type="cue")
check("…and writing the loaded grid and cue straight back is byte-identical", ad.snapshot() == before)
ad.save()
re_ad = TraktorAdapter(lib)
check("positions survive a save and reopen",
abs(re_ad.track_cues(tid).grid_markers[0].start - (20.979167 - OFF) / 1000) < 1e-9)
(tmp / "xing.mp3").rename(tmp / "xing-moved.mp3")
gone = TraktorAdapter(lib).track_cues(tid)
check("with the file gone the offset is 0 (the raw START)",
abs(gone.grid_markers[0].start - 0.020979167) < 1e-12, str(gone.grid_markers[0].start))
print("== 3. Traktor's own hand-placed cues land on the kick (kit 4) ==")
KIT = Path.home() / "Music/Konduktor Stem Test/Kit 4"
NML = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml"
if not (KIT.is_dir() and NML.is_file()):
print(" (skipped: kit 4 or the local Traktor collection is not on this machine)")
else:
xml = NML.read_text(encoding="utf-8")
seen = 0
for m in re.finditer(r"<ENTRY [^>]*>.*?</ENTRY>", xml, re.S):
e = m.group(0)
if "Kit 4" not in e:
continue
name = re.search(r'FILE="([^"]*)"', e).group(1)
pad8 = re.search(r'<CUE_V2 [^>]*START="([^"]*)"[^>]*HOTCUE="7"', e)
if not pad8 or not (KIT / name).is_file():
continue
with av.open(str(KIT / name), metadata_errors="ignore") as c:
st = c.streams.audio[0]
sr = st.rate
y = np.concatenate([f.to_ndarray()[0] for f in c.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 = timebase.from_traktor_ms(float(pad8.group(1)), timebase.offset_ms(KIT / name))
err = (decoded - onset) * 1000
seen += 1
check(f"{name}: a cue placed in Traktor reads back on the kick (±1 ms)", abs(err) < 1.0, f"{err:+.2f} ms")
if not seen:
print(" (skipped: no hand-placed pad-8 cues in kit 4)")
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+10 -2
View File
@@ -29,12 +29,20 @@ describe('buildBeatGrid', () => {
expect(buildBeatGrid([{ start: Infinity, bpm: 120 }])).toBeNull() expect(buildBeatGrid([{ start: Infinity, bpm: 120 }])).toBeNull()
}) })
it('sorts unsorted input and clamps negative starts', () => { it('sorts unsorted input and keeps negative starts', () => {
const g = grid([ const g = grid([
{ start: 10, bpm: 60 }, { start: 10, bpm: 60 },
{ start: -5, bpm: 120 }, { start: -5, bpm: 120 },
]) ])
expect(g.markers.map((m) => m.start)).toEqual([0, 10]) expect(g.markers.map((m) => m.start)).toEqual([-5, 10])
})
it('a marker before the audio starts keeps its phase', () => {
// A Traktor MP3 grid anchored inside the header frame: 30 ms before the
// decoded audio. Clamping it to 0 would put every beat 30 ms late.
const g = grid([{ start: -0.03, bpm: 120 }])
expect(g.snapToBeat(0.5)).toBeCloseTo(0.47, 9)
expect(g.timeOfBeat(1)).toBeCloseTo(0.47, 9)
}) })
it('collapses markers at the same instant', () => { it('collapses markers at the same instant', () => {
+7 -2
View File
@@ -277,7 +277,8 @@ export class BeatGrid {
* *
* Tolerant by design: accepts `undefined` (so a frontend running against an * Tolerant by design: accepts `undefined` (so a frontend running against an
* older backend degrades to "no grid" rather than throwing), unsorted input, * older backend degrades to "no grid" rather than throwing), unsorted input,
* duplicate positions, negative starts, and non-finite or out-of-range BPMs. * duplicate positions and non-finite or out-of-range BPMs. Negative starts are
* kept as they are (see below).
*/ */
export function buildBeatGrid(markers?: readonly GridMarker[] | null): BeatGrid | null { export function buildBeatGrid(markers?: readonly GridMarker[] | null): BeatGrid | null {
if (!markers || markers.length === 0) return null if (!markers || markers.length === 0) return null
@@ -286,7 +287,11 @@ export function buildBeatGrid(markers?: readonly GridMarker[] | null): BeatGrid
if (!m || !Number.isFinite(m.bpm) || !Number.isFinite(m.start)) continue if (!m || !Number.isFinite(m.bpm) || !Number.isFinite(m.start)) continue
if (m.bpm <= 0) continue if (m.bpm <= 0) continue
clean.push({ clean.push({
start: Math.max(0, m.start), // NOT clamped at 0. A marker before the decoded audio's start is a real
// phase — Traktor anchors MP3 grids inside the header frame, ~51 ms
// before the audio Konduktor decodes — and clamping it would move every
// beat of the grid late by that much.
start: m.start,
bpm: Math.min(MAX_BPM, Math.max(MIN_BPM, m.bpm)), bpm: Math.min(MAX_BPM, Math.max(MIN_BPM, m.bpm)),
}) })
} }