Added support for flexible beatgrids

This commit is contained in:
patben8 committed 2026-09-17 15:14:07 +02:00
1 parent 3f51444e2a
commit dd97f27ac7
20 files changed
+2176 -346

No files matched your search

+45 -10
View File
@@ -114,11 +114,41 @@ def detect_grid(audio_path: str, sr: int = _SR) -> tuple[float, float]:
return bpm, first_beat
def _segment_for(t: float, markers: list[tuple[float, float]]) -> tuple[float, float]:
"""The ``(start, bpm)`` of the beatgrid segment containing ``t``.
Times before the first marker use the first segment, extrapolated backwards
— the same convention the deck draws with.
"""
seg = markers[0]
for m in markers:
if m[0] <= t:
seg = m
else:
break
return seg
def snap_to_phrase(
t: float, markers: list[tuple[float, float]], phrase_bars: int = 16
) -> float:
"""Snap ``t`` to the nearest phrase boundary OF ITS OWN SEGMENT.
Snapping is deliberately segment-local rather than a running phrase count
across the whole track: a flexible grid exists precisely because the tempo
drifted, so carrying a phrase count across a marker seam would propagate the
very error the marker was placed to correct. With a single marker this is
exactly the old ``anchor + round((t - anchor) / phrase) * phrase``.
"""
anchor, bpm = _segment_for(t, markers)
phrase = phrase_bars * 4 * (60.0 / bpm)
return anchor + round((t - anchor) / phrase) * phrase
def select_hotcues(
boundaries: list[tuple[float, float]],
*,
bpm: float,
anchor: float,
markers: list[tuple[float, float]],
duration: float,
free_slots: list[int],
existing_times: list[float],
@@ -127,21 +157,26 @@ def select_hotcues(
) -> list[dict]:
"""Turn raw boundaries into hotcue specs, phrase-snapped to the beatgrid.
Snaps each boundary to the nearest ``phrase_bars``-bar grid point (which
also merges near-duplicates), drops any coinciding with an existing hotcue,
caps to the free slots (down-sampling evenly if there are too many), and
assigns positional names. Returns dicts with slot/start/name/type/length.
``markers`` is the beatgrid as ``[(start_sec, bpm), ...]`` ordered by start —
a constant-tempo track is simply a one-element list.
Snaps each boundary to the nearest ``phrase_bars``-bar grid point of its own
tempo segment (which also merges near-duplicates), drops any coinciding with
an existing hotcue, caps to the free slots (down-sampling evenly if there
are too many), and assigns positional names. Returns dicts with
slot/start/name/type/length.
"""
if not boundaries or not free_slots or bpm <= 0:
if not boundaries or not free_slots or not markers or markers[0][1] <= 0:
return []
beat = 60.0 / bpm
phrase = phrase_bars * 4 * beat # seconds per phrase
# Tolerance for "same place as an existing cue" and the end clamp. Marker
# BPMs differ by well under 1% in practice, so the first is representative.
beat = 60.0 / markers[0][1]
# Snap to phrase grid; dedupe (keep the strongest energy seen at each point).
snapped: dict[float, float] = {}
for t, energy in boundaries:
p = anchor + round((t - anchor) / phrase) * phrase
p = snap_to_phrase(t, markers, phrase_bars)
p = max(0.0, min(p, duration - beat))
snapped[p] = max(snapped.get(p, 0.0), energy)
+117
View File
@@ -0,0 +1,117 @@
"""The beatgrid model: an ORDERED LIST of grid markers.
A Traktor beatgrid is not "a BPM and an anchor" — it is a list of `CUE_V2
TYPE="4"` markers, each carrying its own `<GRID BPM>` child. Marker *i*'s tempo
governs from its position until marker *i+1*. Traktor has stored grids this way
since 3.4 (flexible beatgrids); a constant-tempo track is simply a list of
length one, which is why this model is right for every track rather than a
special case for flexible ones.
`<TEMPO BPM>` mirrors the FIRST marker by START.
Verified against the 8485-entry reference collection:
* markers per entry: {1: 7966, 0: 517, 2: 2}
* TEMPO.bpm == markers[0].grid.bpm in 7968/7968 entries with both
* CUE_V2 is ascending by START in 8485/8485 entries
* 53 entries have a TEMPO but no marker -> deleting a grid must KEEP TEMPO
Two rules that are easy to get wrong:
1. **Marker NAME is not a discriminator.** In the reference collection TYPE=4
markers are named "AutoGrid" x7888, "n.n." x64, "Beat Marker" x14 and
"Unnamed" x4. Identify a marker by having a `<GRID>` child, and order the
list by START — never by name, never by document order.
2. **Companion cues are conventional, not structural.** Traktor usually writes a
white TYPE=0 cue alongside each grid marker, at the same position, occupying
a real hotcue slot. 7910 of 7970 markers have one; 60 do not, and one track
has a companion on its first marker but not its second. So we follow them
where they exist, keep them in sync, and NEVER invent one.
This module is pure and imports nothing else from the package, so it can be the
single shared definition used by the store, the API projection and the read
model — which previously each had their own and disagreed about BPM.
"""
from __future__ import annotations
from traktor_nml_utils.models.collection import CueV2Type, Entrytype
# How close a cue must sit to a marker to be considered its companion. Traktor
# writes them at the identical START; 71 markers in the reference collection are
# a fraction of a millisecond off, which this absorbs.
COMPANION_EPS_MS = 1.0
# Companions are always white. This test is LOAD-BEARING: 49 uncoloured cues and
# 18 LOOPS also sit within 1 ms of a marker in the reference collection. Drop the
# colour check and the marker commands would start dragging and deleting the
# user's own loops.
COMPANION_COLOR = "#FFFFFF"
def grid_markers(entry: Entrytype) -> list[CueV2Type]:
"""Every grid marker on `entry`, ordered by START.
Sorting is not cosmetic: the first marker by START is the one `<TEMPO BPM>`
mirrors, and marker indices are the identity used by the edit commands.
"""
markers = [c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is not None]
markers.sort(key=lambda c: c.start or 0.0)
return markers
def first_marker(entry: Entrytype) -> CueV2Type | None:
"""The marker `<TEMPO BPM>` mirrors, or None when the track has no grid."""
markers = grid_markers(entry)
return markers[0] if markers else None
def effective_bpm(entry: Entrytype) -> float | None:
"""The tempo the grid actually starts at.
Prefers the first marker's `<GRID BPM>` and falls back to `<TEMPO BPM>` so
the 53 gridless-but-tempo'd entries still report a BPM. Routing both the
library table and the prep deck through this makes them structurally
incapable of disagreeing.
"""
marker = first_marker(entry)
if marker is not None and marker.grid is not None and marker.grid.bpm:
return marker.grid.bpm
return entry.tempo.bpm if entry.tempo else None
def companions(entry: Entrytype) -> dict[int, CueV2Type]:
"""Map marker index -> the companion cue paired with it, where one exists.
Greedy nearest-unclaimed matching, so two markers close together can never
both claim the same cue.
"""
markers = grid_markers(entry)
if not markers:
return {}
pool = [
c
for c in (entry.cue_v2 or [])
if getattr(c, "grid", None) is None
and c.type == 0
and c.color == COMPANION_COLOR
and c.hotcue is not None
and c.hotcue >= 0
]
out: dict[int, CueV2Type] = {}
claimed: set[int] = set()
for i, m in enumerate(markers):
m_start = m.start or 0.0
best = min(
(c for c in pool if id(c) not in claimed),
key=lambda c: abs((c.start or 0.0) - m_start),
default=None,
)
if best is not None and abs((best.start or 0.0) - m_start) <= COMPANION_EPS_MS:
out[i] = best
claimed.add(id(best))
return out
def is_companion(entry: Entrytype, cue: CueV2Type) -> bool:
"""True when `cue` is some grid marker's companion on this entry."""
return any(c is cue for c in companions(entry).values())
+6 -3
View File
@@ -11,6 +11,8 @@ from pathlib import Path
from traktor_nml_utils import TraktorCollection
from . import beatgrid
from .schemas import (
Facets,
GenreCount,
@@ -80,7 +82,7 @@ class CollectionService:
hotcues = sum(
1 for c in cues if c.hotcue is not None and c.hotcue >= 0
)
has_grid = any(getattr(c, "grid", None) is not None for c in cues)
markers = beatgrid.grid_markers(e)
return Track(
id=_primary_key(loc) if loc else (e.title or ""),
artist=e.artist,
@@ -92,7 +94,7 @@ class CollectionService:
producer=info.producer if info else None,
mix=info.mix if info else None,
comment=info.comment if info else None,
bpm=e.tempo.bpm if e.tempo else None,
bpm=beatgrid.effective_bpm(e),
key=info.key if info else None,
rating=_rating_stars(info.ranking if info else None),
playcount=info.playcount if info else None,
@@ -104,7 +106,8 @@ class CollectionService:
filepath=_display_path(loc) if loc else None,
cue_count=len(cues),
hotcue_count=hotcues,
has_grid=has_grid,
has_grid=bool(markers),
grid_markers=len(markers),
is_stem=getattr(e, "stems", None) is not None,
)
+88 -34
View File
@@ -13,7 +13,7 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from . import __version__
from . import __version__, beatgrid
from . import auto_hotcues as ah
from . import history, prefs
from .collection_service import CollectionService
@@ -35,7 +35,10 @@ from .schemas import (
FileTagOutcome,
FsEntry,
FsListing,
GridEdit,
AddGridMarker,
GridMarker,
GridMarkerEdit,
ReplaceGrid,
HistoryEntry,
OpenCollection,
PathMappingInfo,
@@ -452,30 +455,40 @@ def track_audio(track_id: str) -> FileResponse:
def _build_track_cues(entry) -> TrackCues:
grid_anchor: float | None = None
grid_bpm: float | None = None
cues: list[CuePoint] = []
for c in entry.cue_v2 or []:
grid = getattr(c, "grid", None)
start_sec = (c.start or 0.0) / 1000.0 # Traktor stores cue START in ms
if grid is not None:
if grid_anchor is None:
grid_anchor = start_sec
grid_bpm = grid.bpm
continue # grid markers are represented by the beatgrid, not as cues
cues.append(
CuePoint(
name=c.name,
type=c.type if c.type is not None else 0,
start=start_sec,
length=(c.len or 0.0) / 1000.0,
hotcue=c.hotcue if c.hotcue is not None else -1,
color=c.color,
)
"""Project an ENTRY's beatgrid + cues.
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,
because they occupy real hotcue slots, and each is tagged with the marker it
belongs to so the UI can show it as beatgrid-owned rather than editable.
"""
markers = beatgrid.grid_markers(entry)
comps = beatgrid.companions(entry)
marker_of = {id(c): i for i, c in comps.items()}
grid_markers = [
GridMarker(
start=(m.start or 0.0) / 1000.0, # Traktor stores START in ms
bpm=m.grid.bpm if m.grid and m.grid.bpm else 0.0,
name=m.name,
companion=comps[i].hotcue if i in comps else None,
)
bpm = grid_bpm if grid_bpm is not None else (entry.tempo.bpm if entry.tempo else None)
for i, m in enumerate(markers)
]
cues = [
CuePoint(
name=c.name,
type=c.type if c.type is not None else 0,
start=(c.start or 0.0) / 1000.0,
length=(c.len or 0.0) / 1000.0,
hotcue=c.hotcue if c.hotcue is not None else -1,
color=c.color,
grid_marker=marker_of.get(id(c)),
)
for c in (entry.cue_v2 or [])
if getattr(c, "grid", None) is None
]
return TrackCues(
bpm=bpm, grid_anchor=grid_anchor, locked=bool(entry.lock), cues=cues
grid_markers=grid_markers, locked=bool(entry.lock), cues=cues
)
@@ -525,7 +538,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
if entry is None:
raise HTTPException(404, "Track not found")
cues = _build_track_cues(entry)
if not cues.bpm or cues.bpm <= 0 or cues.grid_anchor is None:
if not cues.grid_markers:
raise HTTPException(400, "Set a beatgrid before using Auto Hotcues")
path = store.audio_path(body.track_id)
if path is None or not path.exists():
@@ -541,8 +554,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
existing_times = [c.start for c in cues.cues if c.hotcue is not None and c.hotcue >= 0]
specs = ah.select_hotcues(
boundaries,
bpm=cues.bpm,
anchor=cues.grid_anchor,
markers=[(m.start, m.bpm) for m in cues.grid_markers],
duration=duration,
free_slots=free,
existing_times=existing_times,
@@ -573,8 +585,10 @@ def auto_grid(body: AutoGridRequest) -> TrackCues:
except Exception as ex: # analysis is best-effort; never 500 the UI
raise HTTPException(400, f"Analysis failed: {ex}")
try:
store.set_grid(body.track_id, bpm=bpm, anchor_sec=first_beat)
store.set_hotcue(body.track_id, 0, first_beat, 0) # hotcue 1 = slot 0
store.replace_grid(body.track_id, [(first_beat, bpm)])
# Traktor pairs its own grid markers with a white beat-1 cue; mirror
# that, but never over an existing hotcue (the old code clobbered slot 0).
store.place_grid_companion(body.track_id, 0, prefer_slot=0)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id)
@@ -600,11 +614,51 @@ def delete_hotcue(track_id: str, slot: int) -> TrackCues:
return _sync_cue_edit(track_id)
@app.patch("/api/tracks/grid", response_model=TrackCues)
def edit_grid(body: GridEdit) -> TrackCues:
"""Set the beatgrid BPM and/or move the grid marker (beat 1)."""
@app.post("/api/tracks/grid/marker", response_model=TrackCues)
def add_grid_marker(body: AddGridMarker) -> TrackCues:
"""Add a beatgrid marker. Omitting `bpm` inherits the governing tempo."""
try:
require_store().set_grid(body.track_id, body.bpm, body.anchor)
require_store().add_grid_marker(body.track_id, body.start, body.bpm)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id)
@app.patch("/api/tracks/grid/marker", response_model=TrackCues)
def edit_grid_marker(body: GridMarkerEdit) -> TrackCues:
"""Retempo and/or move one grid marker.
BPM is applied before the move: a tempo change can never reorder markers, so
`index` is still valid for the move afterwards.
"""
store = require_store()
try:
if body.bpm is not None:
store.set_grid_marker_bpm(body.track_id, body.index, body.bpm)
if body.start is not None:
store.move_grid_marker(body.track_id, body.index, body.start)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id)
@app.delete("/api/tracks/grid/marker", response_model=TrackCues)
def remove_grid_marker(track_id: str, index: int) -> TrackCues:
"""Delete one grid marker (and its companion cue)."""
try:
require_store().delete_grid_marker(track_id, index)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(track_id)
@app.put("/api/tracks/grid", response_model=TrackCues)
def replace_grid(body: ReplaceGrid) -> TrackCues:
"""Replace the whole beatgrid (the deck's Reset). `markers: []` clears it."""
try:
require_store().replace_grid(
body.track_id, [(m.start, m.bpm) for m in body.markers]
)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id)
@@ -612,7 +666,7 @@ def edit_grid(body: GridEdit) -> TrackCues:
@app.delete("/api/tracks/grid", response_model=TrackCues)
def remove_grid(track_id: str) -> TrackCues:
"""Delete the track's grid marker(s)."""
"""Delete every grid marker and its companion cue. <TEMPO> is kept."""
try:
require_store().delete_grid(track_id)
except PlaylistError as ex:
+293 -49
View File
@@ -42,7 +42,7 @@ from traktor_nml_utils.models.collection import (
)
from xsdata.formats.dataclass.serializers import XmlSerializer
from . import __version__, history
from . import __version__, beatgrid, history
from .path_mapping import PathMapping
from .schemas import PlaylistNode
@@ -295,6 +295,21 @@ class PlaylistStore:
raise PlaylistError(f"Track not found: {track_id}")
return entry
@staticmethod
def _reject_if_companion(entry: Entrytype, slot: int) -> None:
"""Refuse to touch a slot held by a grid marker's companion cue.
Traktor pairs most grid markers with a white cue in a real hotcue slot.
Overwriting, retyping or deleting one desyncs it from its marker, so the
beatgrid commands own these slots — move or delete the marker instead.
"""
cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None)
if cue is not None and beatgrid.is_companion(entry, cue):
raise PlaylistError(
f"Hotcue {slot + 1} belongs to a beatgrid marker — "
"move or delete the marker instead"
)
def set_hotcue(
self,
track_id: str,
@@ -314,6 +329,7 @@ class PlaylistStore:
raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock:
entry = self._entry_or_raise(track_id)
self._reject_if_companion(entry, slot)
start_ms = max(0.0, start_sec * 1000.0) # Traktor stores START/LEN in ms
len_ms = max(0.0, length_sec * 1000.0)
existing = next(
@@ -356,8 +372,13 @@ class PlaylistStore:
occupied = {
c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0
}
# Companion slots belong to the beatgrid — never fill them, even
# with overwrite=True (occupied alone only guards them while False).
protected = {
c.hotcue for c in beatgrid.companions(entry).values() if c.hotcue is not None
}
for spec in specs:
if not overwrite and spec.slot in occupied:
if spec.slot in protected or (not overwrite and spec.slot in occupied):
continue
self.set_hotcue(
track_id,
@@ -374,6 +395,7 @@ class PlaylistStore:
raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock:
entry = self._entry_or_raise(track_id)
self._reject_if_companion(entry, slot)
cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None)
if cue is None:
raise PlaylistError(f"Hotcue {slot} is not set")
@@ -384,6 +406,7 @@ class PlaylistStore:
def delete_hotcue(self, track_id: str, slot: int) -> None:
with self._lock:
entry = self._entry_or_raise(track_id)
self._reject_if_companion(entry, slot)
before = entry.cue_v2 or []
entry.cue_v2 = [c for c in before if c.hotcue != slot]
if len(entry.cue_v2) != len(before): # only count an actual removal
@@ -391,61 +414,279 @@ class PlaylistStore:
self.dirty = True
# ---- beatgrid -----------------------------------------------------
# A beatgrid is an ORDERED LIST of markers (see beatgrid.py); a constant
# grid is a list of length one. Markers are addressed by their index in that
# start-ordered list. CUE_V2 has no id attribute and save() reparses the
# whole file, so any synthetic id would have to be rebuilt by position
# anyway — the index IS the identity.
_MARKER_MIN_GAP_MS = 1.0
@staticmethod
def _grid_marker(entry: Entrytype) -> CueV2Type | None:
return next(
(c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is not None), None
)
"""The first grid marker BY START — the one <TEMPO BPM> mirrors."""
return beatgrid.first_marker(entry)
def set_grid(
self, track_id: str, bpm: float | None = None, anchor_sec: float | None = None
) -> None:
"""Set the beatgrid tempo (TEMPO + grid marker BPM) and/or move the grid
marker (beat 1). Creates a grid marker if the track has none."""
@staticmethod
def _sync_tempo(entry: Entrytype) -> None:
"""Mirror <TEMPO BPM> from the first marker (7968/7968 in the reference
collection). Called last by every grid mutator, so a move that changes
which marker is first re-mirrors for free.
With no markers left, TEMPO is LEFT ALONE: Traktor keeps the analysed
BPM on gridless tracks (53 such entries exist in the reference file).
"""
marker = beatgrid.first_marker(entry)
if marker is None or marker.grid is None or not marker.grid.bpm:
return
if entry.tempo is None:
entry.tempo = Tempotype(bpm=marker.grid.bpm, bpm_quality=100.0)
else:
entry.tempo.bpm = marker.grid.bpm
@staticmethod
def _sort_cues(entry: Entrytype) -> None:
"""Keep CUE_V2 ascending by START — true for 8485/8485 reference
entries, so an inserted marker must not become the one exception.
Stable, so a marker stays ahead of a companion at an identical START.
"""
if entry.cue_v2:
entry.cue_v2.sort(key=lambda c: c.start or 0.0)
def _markers_or_raise(
self, entry: Entrytype, index: int
) -> tuple[list[CueV2Type], CueV2Type]:
markers = beatgrid.grid_markers(entry)
if not markers:
raise PlaylistError("Track has no beatgrid")
if not 0 <= index < len(markers):
raise PlaylistError(
f"Grid marker {index} out of range (track has {len(markers)})"
)
return markers, markers[index]
def _drop_grid(self, entry: Entrytype) -> None:
"""Remove every marker AND every companion. No _note — callers do that."""
doomed = {id(m) for m in beatgrid.grid_markers(entry)}
doomed |= {id(c) for c in beatgrid.companions(entry).values()}
entry.cue_v2 = [c for c in (entry.cue_v2 or []) if id(c) not in doomed]
def add_grid_marker(
self,
track_id: str,
start_sec: float,
bpm: float | None = None,
name: str | None = None,
) -> int:
"""Add a beatgrid marker at `start_sec`; returns its index.
With `bpm` unset the marker INHERITS the tempo of the section it lands
in, so splitting a section is musically a no-op until it's retempoed.
Creates no companion cue — Traktor tolerates markers without one, and
inventing them would silently consume the user's hotcue slots.
"""
if bpm is not None and bpm <= 0:
raise PlaylistError(f"BPM must be positive: {bpm}")
with self._lock:
entry = self._entry_or_raise(track_id)
marker = self._grid_marker(entry)
if bpm is not None:
if bpm <= 0:
raise PlaylistError(f"BPM must be positive: {bpm}")
if entry.tempo is None:
entry.tempo = Tempotype(bpm=bpm, bpm_quality=100.0)
else:
entry.tempo.bpm = bpm
if marker is not None and marker.grid is not None:
marker.grid.bpm = bpm
if anchor_sec is not None:
start_ms = max(0.0, anchor_sec * 1000.0)
if marker is not None:
marker.start = start_ms
else:
grid_bpm = bpm if bpm is not None else (entry.tempo.bpm if entry.tempo else None)
if grid_bpm is None:
raise PlaylistError("No BPM available to create a beatgrid")
if entry.cue_v2 is None:
entry.cue_v2 = []
entry.cue_v2.append(
CueV2Type(
name="AutoGrid",
displ_order=0,
type=4,
start=start_ms,
len=0.0,
repeats=-1,
hotcue=-1,
color=None,
grid=GridType(bpm=grid_bpm),
)
)
self._note("grid", "edit", track_id)
start_ms = max(0.0, start_sec * 1000.0)
markers = beatgrid.grid_markers(entry)
for m in markers:
if abs((m.start or 0.0) - start_ms) < self._MARKER_MIN_GAP_MS:
raise PlaylistError("A grid marker already exists at that position")
if bpm is None:
bpm = self._bpm_governing(entry, start_ms)
if bpm is None:
raise PlaylistError("No BPM available to create a beatgrid")
if entry.cue_v2 is None:
entry.cue_v2 = []
entry.cue_v2.append(
CueV2Type(
name=name or ("AutoGrid" if not markers else "n.n."),
displ_order=0,
type=4,
start=start_ms,
len=0.0,
repeats=-1,
hotcue=-1,
color=None,
grid=GridType(bpm=bpm),
)
)
self._sort_cues(entry)
self._sync_tempo(entry)
self._note("grid", "marker-add", track_id)
self.dirty = True
return next(
i
for i, m in enumerate(beatgrid.grid_markers(entry))
if abs((m.start or 0.0) - start_ms) < 1e-9
)
@staticmethod
def _bpm_governing(entry: Entrytype, start_ms: float) -> float | None:
"""The tempo in force at `start_ms`: the last marker at or before it,
else the first marker (extrapolated backwards), else <TEMPO BPM>."""
markers = beatgrid.grid_markers(entry)
if not markers:
return entry.tempo.bpm if entry.tempo else None
governing = markers[0]
for m in markers:
if (m.start or 0.0) <= start_ms:
governing = m
else:
break
return governing.grid.bpm if governing.grid else None
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
"""Move marker `index`, DRAGGING ITS COMPANION with it.
The new position is CLAMPED between the neighbouring markers rather than
allowed to reorder them, so an index can never go stale mid-edit. Phase
nudges are +/-1 and +/-10 ms, so this is no practical constraint;
restructuring a grid is add-then-delete.
"""
with self._lock:
entry = self._entry_or_raise(track_id)
markers, marker = self._markers_or_raise(entry, index)
start_ms = max(0.0, start_sec * 1000.0)
if index > 0:
lo = (markers[index - 1].start or 0.0) + self._MARKER_MIN_GAP_MS
start_ms = max(start_ms, lo)
if index < len(markers) - 1:
hi = (markers[index + 1].start or 0.0) - self._MARKER_MIN_GAP_MS
start_ms = min(start_ms, hi)
companion = beatgrid.companions(entry).get(index)
marker.start = start_ms
if companion is not None:
# Copy the float — never recompute from seconds. A 1-ULP drift
# here would change the rendered bytes and break byte-reverts.
companion.start = marker.start
self._sync_tempo(entry)
self._note("grid", "marker-move", track_id)
self.dirty = True
def delete_grid(self, track_id: str) -> None:
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
"""Set marker `index`'s tempo (governs until the next marker)."""
if bpm <= 0:
raise PlaylistError(f"BPM must be positive: {bpm}")
with self._lock:
entry = self._entry_or_raise(track_id)
entry.cue_v2 = [
c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is None
]
_, marker = self._markers_or_raise(entry, index)
if marker.grid is None:
marker.grid = GridType(bpm=bpm)
else:
marker.grid.bpm = bpm
self._sync_tempo(entry)
self._note("grid", "marker-bpm", track_id)
self.dirty = True
def delete_grid_marker(self, track_id: str, index: int) -> None:
"""Remove marker `index` and its companion (freeing that hotcue slot)."""
with self._lock:
entry = self._entry_or_raise(track_id)
markers, marker = self._markers_or_raise(entry, index)
companion = beatgrid.companions(entry).get(index)
doomed = {id(marker)} | ({id(companion)} if companion is not None else set())
entry.cue_v2 = [c for c in (entry.cue_v2 or []) if id(c) not in doomed]
self._sync_tempo(entry)
# Removing the last marker IS deleting the grid — report it as one.
self._note(
"grid", "delete" if len(markers) == 1 else "marker-delete", track_id
)
self.dirty = True
def replace_grid(
self, track_id: str, markers: list[tuple[float, float]]
) -> None:
"""Throw the grid away and rebuild it from `markers` [(start_sec, bpm)].
Serves both Auto Grid (a single marker) and the deck's Reset (restore
the list as loaded) as one atomic, single-event command. Companions of
the old grid go with it; none are created.
"""
for start_sec, bpm in markers:
if bpm <= 0:
raise PlaylistError(f"BPM must be positive: {bpm}")
with self._lock:
entry = self._entry_or_raise(track_id)
self._drop_grid(entry)
if entry.cue_v2 is None:
entry.cue_v2 = []
for i, (start_sec, bpm) in enumerate(
sorted(markers, key=lambda m: m[0])
):
entry.cue_v2.append(
CueV2Type(
name="AutoGrid" if i == 0 else "n.n.",
displ_order=0,
type=4,
start=max(0.0, start_sec * 1000.0),
len=0.0,
repeats=-1,
hotcue=-1,
color=None,
grid=GridType(bpm=bpm),
)
)
self._sort_cues(entry)
self._sync_tempo(entry)
self._note("grid", "replace", track_id)
self.dirty = True
def place_grid_companion(
self, track_id: str, index: int, *, prefer_slot: int = 0
) -> int | None:
"""Give marker `index` the white beat-1 hotcue Traktor writes beside its
own markers: `prefer_slot` when free, else the lowest free slot.
Returns the slot used, or None when the bank is full or the marker
already has a companion. NEVER overwrites. This is the ONLY place
Konduktor creates a companion — grid edits never do — because it is a
deliberate, user-invoked feature (Auto Grid), not a side effect.
"""
with self._lock:
entry = self._entry_or_raise(track_id)
_, marker = self._markers_or_raise(entry, index)
if index in beatgrid.companions(entry):
return None
used = {
c.hotcue
for c in (entry.cue_v2 or [])
if c.hotcue is not None and c.hotcue >= 0
}
slot = next(
(s for s in [prefer_slot, *range(8)] if 0 <= s <= 7 and s not in used),
None,
)
if slot is None:
return None
entry.cue_v2.append(
CueV2Type(
name=marker.name or "AutoGrid",
displ_order=0,
type=0,
start=marker.start, # copy the float, not start_sec * 1000
len=0.0,
repeats=-1,
hotcue=slot,
color=beatgrid.COMPANION_COLOR,
grid=None,
)
)
self._sort_cues(entry)
self._note("grid", "marker-add", track_id)
self.dirty = True
return slot
def delete_grid(self, track_id: str) -> None:
"""Remove EVERY grid marker AND EVERY companion; <TEMPO> is kept.
Dropping companions is the debris fix: the old code stripped markers
only, leaving orphan white cues squatting in hotcue slots.
"""
with self._lock:
entry = self._entry_or_raise(track_id)
self._drop_grid(entry)
self._note("grid", "delete", track_id)
self.dirty = True
@@ -698,7 +939,10 @@ class PlaylistStore:
elif detail == "delete":
hc_del += 1
elif cat == "grid":
(grid_edit if detail == "edit" else grid_del).add(tid or "")
# "delete" is the ONLY deletion detail. Everything else — including
# details added later — counts as an edit, because mis-labelling an
# edit as a deletion in the history summary is the damaging direction.
(grid_del if detail == "delete" else grid_edit).add(tid or "")
elif cat == "lock":
(lock_on if detail == "on" else lock_off).add(tid or "")
+33 -6
View File
@@ -30,6 +30,7 @@ class Track(BaseModel):
cue_count: int = 0
hotcue_count: int = 0
has_grid: bool = False
grid_markers: int = 0 # >1 = a flexible (multi-tempo) beatgrid
is_stem: bool = False # a Stem file (<STEMS> child) vs a normal audio track
@@ -132,19 +133,45 @@ class CuePoint(BaseModel):
length: float # seconds (>0 for loops)
hotcue: int # -1 if not assigned to a hotcue slot
color: str | None = None # "#RRGGBB" if set
# Index of the grid marker this cue is the companion of, if any. Such a cue
# holds a real hotcue slot but belongs to the beatgrid and is not editable.
grid_marker: int | None = None
class GridMarker(BaseModel):
"""One beatgrid marker. Its position in the list IS its index/identity."""
start: float # seconds
bpm: float # governs from this marker until the next one
name: str | None = None # Traktor's label — display only, NOT a discriminator
companion: int | None = None # hotcue slot of the paired white cue, if any
class TrackCues(BaseModel):
bpm: float | None = None # beatgrid BPM (from the grid marker; falls back to tempo)
grid_anchor: float | None = None # seconds — first grid marker (beat 1 of the grid)
# THE beatgrid, ordered by start. Empty = no grid; one marker = constant
# tempo. There is deliberately no scalar bpm/anchor here: a single "the BPM"
# is what made flexible grids render and edit wrongly.
grid_markers: list[GridMarker] = []
locked: bool = False # Traktor LOCK flag
cues: list[CuePoint] = [] # cue/loop markers (grid markers excluded)
cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded)
class GridEdit(BaseModel):
class AddGridMarker(BaseModel):
track_id: str
bpm: float | None = None # set the beatgrid tempo
anchor: float | None = None # set the grid marker (beat 1) position, in seconds
start: float # seconds
bpm: float | None = None # unset = inherit the tempo governing that position
class GridMarkerEdit(BaseModel):
track_id: str
index: int # into the start-ordered marker list
start: float | None = None # move it (clamped between its neighbours)
bpm: float | None = None # retempo the section it opens
class ReplaceGrid(BaseModel):
track_id: str
markers: list[GridMarker] = [] # [] is equivalent to deleting the grid
class SetLock(BaseModel):
+225 -33
View File
@@ -31,7 +31,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fidelity-a
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
from konduktor.collection_service import CollectionService # noqa: E402
from konduktor.playlist_store import PlaylistStore # noqa: E402
from konduktor.playlist_store import PlaylistError, PlaylistStore # noqa: E402
failed = False
@@ -232,24 +232,42 @@ with tempfile.TemporaryDirectory() as d:
check("create+delete round-trips to the original bytes", work.read_bytes() == original)
# ---- Invariant E: a beatgrid edit is fully localized -------------------
print("== E. grid/bpm edit touches only that track's ENTRY ==")
print("== E. grid marker edit touches only that track's ENTRY ==")
from konduktor import beatgrid as bg # noqa: E402
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
store = PlaylistStore(work)
# first entry that has both a tempo and a grid marker
entry = next(
e
for e in store._nml.collection.entry
if e.tempo and store._grid_marker(e) is not None
)
loc = entry.location
track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
orig_bpm = entry.tempo.bpm
store.set_grid(track_id, bpm=orig_bpm / 2, anchor_sec=1.5)
def _key(e):
loc = e.location
return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" if loc else ""
# An entry with a tempo and exactly ONE marker whose companion (if any) sits
# at an EXACTLY equal START. That predicate is load-bearing: a companion a
# fraction of a ms off would be normalised to exact by the first move, so the
# byte-revert below would fail through no fault of the code.
def _clean_single(e):
ms = bg.grid_markers(e)
if not (e.tempo and len(ms) == 1):
return False
comp = bg.companions(e).get(0)
return comp is None or comp.start == ms[0].start
entry = next(e for e in store._nml.collection.entry if _clean_single(e))
loc = entry.location
track_id = _key(entry)
orig_bpm = entry.tempo.bpm
orig_anchor_ms = bg.grid_markers(entry)[0].start
comp_slot = (
bg.companions(entry)[0].hotcue if 0 in bg.companions(entry) else None
)
store.set_grid_marker_bpm(track_id, 0, orig_bpm / 2)
store.move_grid_marker(track_id, 0, 1.5)
store.save()
edited = work.read_bytes()
@@ -272,30 +290,28 @@ with tempfile.TemporaryDirectory() as d:
from traktor_nml_utils import TraktorCollection
reparsed = TraktorCollection(path=work)
e0 = next(
e
for e in reparsed.nml.collection.entry
if e.location
and f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}" == track_id
)
e0 = next(e for e in reparsed.nml.collection.entry if e.location and _key(e) == track_id)
markers = bg.grid_markers(e0)
m = store._grid_marker(e0)
check("tempo BPM halved + persisted", abs(e0.tempo.bpm - orig_bpm / 2) < 1e-3)
check("grid marker BPM matches tempo", m is not None and abs(m.grid.bpm - orig_bpm / 2) < 1e-3)
check("grid anchor moved to 1.5s (1500 ms)", m is not None and abs(m.start - 1500.0) < 1)
# A move must reposition the grid, never fork it into a flexible one.
check("still exactly one grid marker", len(markers) == 1, str(len(markers)))
# _grid_marker is the first marker BY START, not by document order.
check("_grid_marker == first marker by start", m is markers[0])
if comp_slot is not None:
comp = bg.companions(e0).get(0)
check("companion dragged along with its marker",
comp is not None and abs(comp.start - 1500.0) < 1, str(comp.start if comp else None))
check("companion kept its hotcue slot", comp is not None and comp.hotcue == comp_slot)
# Reverting BPM + anchor to the original values round-trips to the file.
orig_anchor_ms = store._grid_marker(
next(
e
for e in TraktorCollection(path=REAL).nml.collection.entry
if e.location
and f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}" == track_id
)
).start
# Reverting BPM + position round-trips to the original bytes.
store2 = PlaylistStore(work)
store2.set_grid(track_id, bpm=orig_bpm, anchor_sec=orig_anchor_ms / 1000.0)
store2.set_grid_marker_bpm(track_id, 0, orig_bpm)
store2.move_grid_marker(track_id, 0, orig_anchor_ms / 1000.0)
store2.save()
check("revert BPM + anchor round-trips to original bytes", work.read_bytes() == original)
check("revert BPM + position round-trips to original bytes", work.read_bytes() == original)
# ---- Invariant F: batch place_hotcues (Auto Hotcues) -------------------
print("== F. place_hotcues fills empty slots only, names round-trip, localized ==")
@@ -365,12 +381,13 @@ with tempfile.TemporaryDirectory() as d:
print("== G. select_hotcues: phrase-snap, empty-slots, names, existing-cue avoidance ==")
from konduktor import auto_hotcues as ah # noqa: E402
# 128 BPM => beat 0.46875s, 16-bar phrase = 30.0s exactly; anchor 0.0.
# 128 BPM => beat 0.46875s, 16-bar phrase = 30.0s exactly; marker at 0.0.
BPM, ANCHOR, DUR = 128.0, 0.0, 300.0
GRID = [(ANCHOR, BPM)] # a constant grid is a one-marker list
# Raw boundaries near (but not exactly on) phrase multiples + a fragmented pair.
raw = [(0.3, 0.2), (29.4, 0.5), (30.6, 0.55), (61.0, 0.9), (150.0, 0.3), (270.2, 0.25)]
specs = ah.select_hotcues(
raw, bpm=BPM, anchor=ANCHOR, duration=DUR,
raw, markers=GRID, duration=DUR,
free_slots=[2, 3, 4, 5, 6, 7], existing_times=[], max_cues=8,
)
starts = [s["start"] for s in specs]
@@ -383,13 +400,27 @@ check("names are unique (ordinal de-dupe)", len({s["name"] for s in specs}) == l
# A hotcue already sitting on the 60s phrase must not get a duplicate.
specs2 = ah.select_hotcues(
raw, bpm=BPM, anchor=ANCHOR, duration=DUR,
raw, markers=GRID, duration=DUR,
free_slots=[0, 1, 2, 3, 4, 5, 6, 7], existing_times=[60.0], max_cues=8,
)
check("boundary colliding with an existing hotcue is dropped", 60.0 not in [s["start"] for s in specs2], str([s["start"] for s in specs2]))
# No free slots => nothing placed.
check("no free slots => empty result", ah.select_hotcues(raw, bpm=BPM, anchor=ANCHOR, duration=DUR, free_slots=[], existing_times=[], max_cues=8) == [])
check("no free slots => empty result", ah.select_hotcues(raw, markers=GRID, duration=DUR, free_slots=[], existing_times=[], max_cues=8) == [])
# Flexible grid: each segment snaps to ITS OWN phrase length. Segment 2 starts
# at 120s at 120 BPM => 16-bar phrase = 32.0s, so points there land on 120+k*32.
FLEX = [(0.0, 128.0), (120.0, 120.0)]
flex_specs = ah.select_hotcues(
[(29.4, 0.5), (61.0, 0.9), (152.5, 0.4), (215.0, 0.3)],
markers=FLEX, duration=DUR, free_slots=[0, 1, 2, 3, 4, 5, 6, 7],
existing_times=[], max_cues=8,
)
flex_starts = [s_["start"] for s_ in flex_specs]
check("flexible grid: pre-seam points snap to the 30s phrase",
all(abs(round(t / 30.0) * 30.0 - t) < 0.01 for t in flex_starts if t < 120.0), str(flex_starts))
check("flexible grid: post-seam points snap to that segment's 32s phrase",
all(abs(120.0 + round((t - 120.0) / 32.0) * 32.0 - t) < 0.01 for t in flex_starts if t >= 120.0), str(flex_starts))
# ---- Invariant H: path write-back is localized + round-trips -----------
print("== H. remap_locations rewrites LOCATIONs (+ playlist keys), localized, round-trips ==")
@@ -517,5 +548,166 @@ with tempfile.TemporaryDirectory() as d:
check("H2: new playlist PRIMARYKEY present", new_key in all_pl_keys)
# ---- Invariant I: flexible (multi-marker) beatgrids round-trip ---------
print("== I. flexible beatgrid: add/move/delete markers, localized + reversible ==")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
def _key(e):
loc = e.location
return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" if loc else ""
def entry_span(data: bytes, file_name: str):
marker = f'FILE="{file_name}"'.encode()
i = data.find(marker)
st = data.rfind(b"<ENTRY ", 0, i)
en = data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
return st, en
# Synthesize the flexible grid rather than relying on the handful of real
# ones: those are the user's own data and could change at any time.
store = PlaylistStore(work)
entry = next(
e for e in store._nml.collection.entry
if e.tempo and len(bg.grid_markers(e)) == 1
and (bg.companions(e).get(0) is None or bg.companions(e)[0].start == bg.grid_markers(e)[0].start)
)
loc = entry.location
track_id = _key(entry)
_m0 = bg.grid_markers(entry)[0]
m0_start, m0_bpm = _m0.start, _m0.grid.bpm
orig_tempo = entry.tempo.bpm
store.add_grid_marker(track_id, (m0_start + 60_000.0) / 1000.0, bpm=m0_bpm * 0.99)
store.save()
two = work.read_bytes()
reparsed = TraktorCollection(path=work)
e1 = next(e for e in reparsed.nml.collection.entry if e.location and _key(e) == track_id)
ms = bg.grid_markers(e1)
check("I: second marker added", len(ms) == 2, str(len(ms)))
check("I: markers ascending by START", ms[0].start < ms[1].start)
check("I: second marker kept its own BPM", abs(ms[1].grid.bpm - m0_bpm * 0.99) < 1e-3)
check("I: TEMPO still mirrors the FIRST marker", abs(e1.tempo.bpm - orig_tempo) < 1e-6,
f"{e1.tempo.bpm} vs {orig_tempo}")
check("I: CUE_V2 still ascending by START",
all((c.start or 0) <= (ms_ .start or 0) for c, ms_ in zip(e1.cue_v2, e1.cue_v2[1:])))
check("I: new GRID BPM rendered at 6 decimals",
f'<GRID BPM="{m0_bpm * 0.99:.6f}">'.encode() in two)
os_, oe = entry_span(original, loc.file)
es_, ee = entry_span(two, loc.file)
check("I: adding a marker is confined to that ENTRY",
original[:os_] + b"@@" + original[oe:] == two[:es_] + b"@@" + two[ee:])
# Removing it must return the file to its original bytes exactly.
store2 = PlaylistStore(work)
store2.delete_grid_marker(track_id, 1)
store2.save()
check("I: deleting the added marker round-trips to original bytes",
work.read_bytes() == original)
# Moves clamp between neighbours rather than reordering the list.
store3 = PlaylistStore(work)
store3.add_grid_marker(track_id, (m0_start + 60_000.0) / 1000.0, bpm=m0_bpm * 0.99)
store3.move_grid_marker(track_id, 0, (m0_start + 120_000.0) / 1000.0)
e3 = store3.model_entry(track_id)
ms3 = bg.grid_markers(e3)
check("I: move clamps below the next marker", ms3[0].start < ms3[1].start)
check("I: move never changes the marker count", len(ms3) == 2)
# delete_grid takes the companions with it and keeps TEMPO.
store3.delete_grid(track_id)
e3 = store3.model_entry(track_id)
whites = [c for c in (e3.cue_v2 or []) if c.color == "#FFFFFF" and getattr(c, "grid", None) is None]
check("I: delete_grid removes every marker", len(bg.grid_markers(e3)) == 0)
check("I: delete_grid leaves no companion debris", not whites, str(len(whites)))
check("I: delete_grid keeps TEMPO", e3.tempo is not None and e3.tempo.bpm == orig_tempo)
# ---- Invariant J: companion cues are protected from hotcue edits -------
print("== J. grid companion cues cannot be clobbered by hotcue commands ==")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
store = PlaylistStore(work)
entry = next(
e for e in store._nml.collection.entry if bg.companions(e).get(0) is not None
)
track_id = f"{entry.location.volume or ''}{entry.location.dir or ''}{entry.location.file or ''}"
slot = bg.companions(entry)[0].hotcue
for label, fn in [
("set_hotcue", lambda: store.set_hotcue(track_id, slot, 5.0, 0)),
("set_hotcue_type", lambda: store.set_hotcue_type(track_id, slot, 1)),
("delete_hotcue", lambda: store.delete_hotcue(track_id, slot)),
]:
try:
fn()
check(f"J: {label} refuses a companion slot", False, "no error raised")
except PlaylistError:
check(f"J: {label} refuses a companion slot", True)
check("J: refusals leave the store clean", store.dirty is False)
store.save()
check("J: save after refusals is byte-identical", work.read_bytes() == original)
# The guard must be narrow: a free slot in the same track still works.
used = {c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0}
free = next(s_ for s_ in range(8) if s_ not in used)
store.set_hotcue(track_id, free, 12.0, 0)
check("J: a non-companion slot is still editable", store.dirty is True)
# Auto Hotcues must skip companion slots even when told to overwrite.
store2 = PlaylistStore(work)
spec = type("S", (), {"slot": slot, "start": 42.0, "name": "X", "type": 0, "length": 0.0})()
store2.place_hotcues(track_id, [spec], overwrite=True)
e2 = store2.model_entry(track_id)
comp = bg.companions(e2).get(0)
check("J: place_hotcues(overwrite) skips a companion slot",
comp is not None and abs(comp.start - 42_000.0) > 1)
# Deleting the grid releases the slot it was holding.
store2.delete_grid(track_id)
e2 = store2.model_entry(track_id)
check("J: delete_grid frees the companion's hotcue slot",
not any(c.hotcue == slot for c in (e2.cue_v2 or [])))
# ---- Invariant K: real flexible grids project correctly (read-only) ----
print("== K. genuine Traktor flexible grids read correctly ==")
_real = TraktorCollection(path=REAL).nml.collection.entry
_flex = [e for e in _real if len(bg.grid_markers(e)) > 1]
if not _flex:
print(" [SKIP] no flexible-grid entries in the reference collection")
else:
import konduktor.main as _m
ok_order = ok_tempo = ok_proj = ok_comp = True
for e in _flex:
ms = bg.grid_markers(e)
ok_order &= all(ms[i].start < ms[i + 1].start for i in range(len(ms) - 1))
if e.tempo and e.tempo.bpm:
ok_tempo &= abs(e.tempo.bpm - ms[0].grid.bpm) < 1e-6
tc = _m._build_track_cues(e)
ok_proj &= len(tc.grid_markers) == len(ms) and all(
abs(g.bpm - m.grid.bpm) < 1e-9 and abs(g.start - (m.start or 0) / 1000.0) < 1e-9
for g, m in zip(tc.grid_markers, ms)
)
# A marker with no companion must project None, not raise.
comps = bg.companions(e)
ok_comp &= all(
(tc.grid_markers[i].companion is None) == (i not in comps) for i in range(len(ms))
)
print(f" ({len(_flex)} flexible entr{'y' if len(_flex) == 1 else 'ies'} checked)")
check("K: markers strictly ascending by START", ok_order)
check("K: TEMPO mirrors the first marker", ok_tempo)
check("K: every marker projects with its own BPM + position", ok_proj)
check("K: a marker without a companion projects None", ok_comp)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)