Exports now strip Traktor song data blocks that overwrite BPM from collection

This commit is contained in:
patben8 committed 2026-10-26 09:42:19 +01:00
1 parent 210c1ab135
commit 31287bdeb7
10 files changed
+597 -1

No files matched your search

@@ -512,6 +512,15 @@ class TraktorAdapter:
track uploaded there is stored as that computer would have stored it."""
self._store.set_write_stored_paths(enabled)
def prepare_copied_audio(self, path: Path) -> bool:
"""OPTIONAL: ready a file the importer just COPIED for this library —
Traktor's own block removed (`file_block`), which Traktor would
otherwise restore over the entry's grid. Never called for a file
added in place."""
from . import file_block
return file_block.strip(path)
def unresolved_path_groups(self) -> list[PathGroup]:
return self._store.unresolved_path_groups()
@@ -37,6 +37,7 @@ from pathlib import Path
from ...core.adapter import NewTrack
from ...core.export import OTHER_PLAYLIST, ExportPayload, WrittenLibrary, write_playlist_tree
from .adapter import TraktorAdapter
from . import file_block
from .capabilities import capabilities_for
log = logging.getLogger(__name__)
@@ -68,6 +69,12 @@ class TraktorExporter:
#: analysis, which overwrites only ANALYZED_DB).
writes_auto_gain = True
@staticmethod
def prepare_copy(path: Path) -> bool:
"""Remove Traktor's own block from a copy (`file_block`): left in, it
is restored over this entry's grid when Traktor opens the collection."""
return file_block.strip(path)
def capabilities(self):
"""What a Traktor library can hold — answered with no library to read.
@@ -0,0 +1,121 @@
"""Traktor's own block INSIDE an audio file, and removing it from a copy.
Traktor writes a binary block of its analysis into every file it tags — the
same `DMRT` chunk tree in each format, stored where the format allows:
- MP4 (`.m4a`, stem files): the `ilst` atom `NITR`
- ID3 (MP3, AIFF, WAV): a `PRIV` frame owned by `TRAKTOR4`
- Vorbis comments (FLAC, Ogg): the field `traktor4`
It holds a BPM (`HBPM`), the cues (`CUEP`), the audio id, transients, tags.
Measured in Traktor 4.5 (2026-10-24, 2MUCH / Alone (Vip)): on an entry it did
not write itself — no MODIFIED_DATE, as every entry Konduktor creates — Traktor
re-reads the file and takes the block's BPM over the collection's, LOCK or not,
keeping the anchor. A grid fixed after Traktor last wrote the block (in
Konduktor, or in Traktor without a tag write) is reverted on every export.
Giving the entry a MODIFIED_DATE later than the file stops that, but Traktor
then skips the file altogether, cover art included. Giving it the block's
AUDIO_ID changes nothing. Removing the block from the copy does both: Traktor
imports the file as new — art, file facts and analysis from the file; BPM,
grid, lock and cues from the entry — and writes a fresh, correct block itself
when the track is first loaded. A stale `TBPM`/`tmpo` tag is ignored.
Only ever applied to a COPY Konduktor wrote. A file the user's library
references in place is the user's, and is never touched.
"""
from __future__ import annotations
import logging
from pathlib import Path
log = logging.getLogger(__name__)
#: The ID3 PRIV owner and the Vorbis field name Traktor writes the block under.
_PRIV_OWNER = "TRAKTOR4"
_VORBIS_FIELD = "traktor4"
#: The MP4 atom. mutagen keeps it among the atoms it could not parse — or, in
#: some files, parses it into an ordinary key; both are checked.
_MP4_ATOM = "NITR"
def has_block(path: Path) -> bool:
"""Whether the file carries Traktor's block. False for anything unreadable."""
audio = _open(path)
return audio is not None and bool(_remove(audio, dry_run=True))
def strip(path: Path) -> bool:
"""Remove Traktor's block from `path`, in place; True if it held one.
Everything else in the file is kept: other tags, cover, the stem box, the
audio. A file without a block is not rewritten at all. A file that cannot
be read or written is left as it is — a copy that still carries the block
is the old behaviour, never a failed export — and the reason is logged.
"""
audio = _open(path)
if audio is None or not _remove(audio, dry_run=False):
return False
try:
version = getattr(audio.tags, "version", None)
if version is not None and _is_id3(audio):
# Keep the file's own ID3 version: nothing else in it is changing.
audio.save(v2_version=3 if version[1] == 3 else 4)
else:
audio.save()
except Exception as ex: # noqa: BLE001 — see the docstring
log.warning("could not remove Traktor's block from %s: %s", path, ex)
return False
return True
def _open(path: Path):
try:
import mutagen
audio = mutagen.File(path)
except Exception as ex: # noqa: BLE001 — an unreadable file has no block we can see
log.debug("cannot read tags of %s: %s", path, ex)
return None
if audio is None or audio.tags is None:
return None
return audio
def _is_id3(audio) -> bool:
from mutagen.id3 import ID3
return isinstance(audio.tags, ID3)
def _remove(audio, *, dry_run: bool) -> int:
"""How many block entries `audio`'s tags hold, removing them unless
`dry_run`. Never saves."""
from mutagen.mp4 import MP4Tags
tags = audio.tags
found = 0
if isinstance(tags, MP4Tags):
failed = getattr(tags, "_failed_atoms", {})
if _MP4_ATOM in failed:
found += 1
if not dry_run:
del failed[_MP4_ATOM]
if _MP4_ATOM in tags:
found += 1
if not dry_run:
del tags[_MP4_ATOM]
elif _is_id3(audio):
keys = [k for k, frame in tags.items()
if k.startswith("PRIV:") and getattr(frame, "owner", None) == _PRIV_OWNER]
found += len(keys)
if not dry_run:
for k in keys:
del tags[k]
elif hasattr(tags, "keys"): # Vorbis comments: case-insensitive field names
keys = [k for k in tags.keys() if k.lower() == _VORBIS_FIELD]
found += len(keys)
if not dry_run:
for k in keys:
del tags[k]
return found
+8
View File
@@ -192,6 +192,14 @@ class LibraryExporter(Protocol):
#: destination, so this is a warning the UI raises, not a refusal: the other
#: targets in the same export are still perfectly valid in any folder.
drive_root: bool = False
#: Optional, and not a protocol member so a target needs nothing to opt
#: out: `prepare_copy(path) -> bool` readies one audio COPY for this
#: library, in place, before its size is recorded or a library refers to
#: it, returning True if it changed the file. Called once per copy and
#: target (the runner records which targets have prepared it, so a kept
#: copy is prepared when a target joins the set). Traktor's removes its
#: own block from the file (`adapters/traktor/file_block.py`). Never
#: called on a file a library references in place.
def capabilities(self) -> Capabilities:
"""What this target can represent — STATIC, with no library to read."""
+42
View File
@@ -126,6 +126,9 @@ class PlannedTrack:
level_outcome: str | None = None
#: The run needs this source's loudness (it normalises, or writes auto gain).
needs_loudness: bool = False
#: The targets whose `prepare_copy` the copy has been through (sorted
#: platforms; recorded in the manifest, missing = none).
prepared: tuple[str, ...] = ()
@dataclass(frozen=True)
@@ -321,9 +324,43 @@ def _record(planned: PlannedTrack, copy: Path) -> dict:
# The level the copy was written at: a copy kept by a later export must
# be at the level THAT export wants (missing = 0, every older manifest).
"gain_db": planned.gain_db,
# The targets that have prepared the copy (`prepare_copy`): a kept copy
# is prepared for any target not listed (missing = none, every older
# manifest — which is how existing exports lose Traktor's block).
"prepared": list(planned.prepared),
}
def prepare_copy(path: Path, exporters, done=()) -> tuple[str, ...]:
"""Run each target's optional `prepare_copy` on one copy, in place,
skipping the targets in `done` (already prepared it). Returns every target
that now has — `done` included, so a target leaving the set does not make
a later one prepare the copy twice."""
ready = set(done)
for exporter in exporters:
hook = getattr(exporter, "prepare_copy", None)
if hook is None or exporter.platform in ready:
continue
hook(path)
ready.add(exporter.platform)
return tuple(sorted(ready))
def prepare_kept(path: Path, planned: PlannedTrack, record: dict, exporters) -> dict:
"""Prepare a KEPT copy for any target that has not yet (an export made
before a target's `prepare_copy` existed, or a target new to the set), and
the record that now describes it — the copy's size and mtime as they are
after, so a rollback's manifest still matches the file."""
done = record.get("prepared")
done = tuple(done) if isinstance(done, list) else ()
planned.prepared = prepare_copy(path, exporters, done)
if planned.prepared == tuple(sorted(done)):
return record
st = path.stat()
return {**record, "copy_size": st.st_size, "copy_mtime_ns": st.st_mtime_ns,
"prepared": list(planned.prepared)}
def _previous_copies(destination: Path) -> dict[str, tuple[Path, dict]]:
"""The last export's copies, by SOURCE path — not by where they sit, since
adding a track from another folder moves the shared root and with it every
@@ -599,6 +636,10 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
if reused:
handle.progress(message=f"Keeping {len(reused)} unchanged track{'' if len(reused) == 1 else 's'}…")
_move_kept(destination, reused, kept)
for planned in reused:
handle.raise_if_cancelled()
path = Path(planned.destination)
kept[path] = prepare_kept(path, planned, kept[path], exporters)
payload_tracks: list[ExportTrack] = []
for planned in items:
@@ -618,6 +659,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
handle.progress(done=done)
write_copy(adapter, planned, partial, handle, advance)
planned.prepared = prepare_copy(partial, exporters)
os.replace(partial, target)
payload_tracks.append(
ExportTrack(
+6
View File
@@ -347,6 +347,10 @@ def run(
# a folder on the server, instead of copied here. Nothing can be left in
# place — the server cannot see this computer's files.
uploads = not places and uploads_audio(dest)
# The library's optional readying of a file copied FOR it (Traktor: its
# own block removed from the copy). Only copies made here: never a file
# added in place, nor an upload (written on the server).
prepare = getattr(dest, "prepare_copied_audio", None)
if uploads and reference and not getattr(source, "on_library_host", False):
raise ValueError("A remote library cannot reference files on this computer")
if not reference and not places and not uploads:
@@ -404,6 +408,8 @@ def run(
handle.progress(message=f"Copying {planned.title}")
created.append(target) # registered BEFORE the write, so a cancel
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
if prepare is not None:
prepare(target)
copied.append((planned, target))
handle.raise_if_cancelled()
+11
View File
@@ -86,6 +86,8 @@ from .exporter import (
_measure_missing,
_record,
assign_reuse,
prepare_copy,
prepare_kept,
set_level,
write_copy,
)
@@ -551,10 +553,18 @@ def run(adapter, export_set, built: PushPlan, handle: JobHandle, *, lock_grids:
_measure_missing(adapter, built.audio, handle, store=store, level=level,
previous=built.previous)
items = built.audio.exportable
# The targets' writers, for `prepare_copy` (Traktor's removes its own
# block from the file, which it would restore over the pushed grid).
writers = [w for w in (core_export.for_platform(t.platform) for t in built.active) if w]
handle.progress(done=0, total=built.audio.total_bytes, unit="bytes", message="Copying…")
for planned in items:
handle.raise_if_cancelled()
if planned.reuse is not None:
# Kept: prepared for any target that has not yet. In place —
# no target app is running (refused above), and a library
# already holding the file re-reads its tags on its own.
old = built.previous.get(str(planned.source_path))
prepare_kept(planned.reuse, planned, old[1] if old else {}, writers)
continue
target = Path(planned.destination)
target.parent.mkdir(parents=True, exist_ok=True)
@@ -568,6 +578,7 @@ def run(adapter, export_set, built: PushPlan, handle: JobHandle, *, lock_grids:
handle.progress(message=f"Copying {planned.title}")
write_copy(adapter, planned, partial, handle, advance)
planned.prepared = prepare_copy(partial, writers)
written.add(planned.track_id)
if target.exists():
# A library may be playing this file: it is replaced only