diff --git a/CLAUDE.md b/CLAUDE.md index f714c86..19e4224 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1473,6 +1473,13 @@ frontend at `http://localhost:5173`. `masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`; the Rekordbox adapter uses the new names. `db6` still works as a deprecated alias and is **removed in 0.6.0**. + **PyAV: open files for reading through `core/pyav.open_input`, never + `av.open` directly.** PyAV 18 refuses a file with non-UTF-8 tags unless + given `metadata_errors="ignore"`; PyAV 19 removed that keyword. CI installs + fresh (it got 19) while a dev venv keeps what it had (18), so code passing + the keyword passed every local test and shipped a release whose deck played + every stem track as the mix. `requirements.txt` caps `av<20`: check + `pyav.py` before raising it. 2. **The collection is real, irreplaceable data — protect it.** Every save writes a timestamped `.bak` first (into a `backups/` folder next to the collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the diff --git a/backend/konduktor/core/pyav.py b/backend/konduktor/core/pyav.py new file mode 100644 index 0000000..b76dc7a --- /dev/null +++ b/backend/konduktor/core/pyav.py @@ -0,0 +1,33 @@ +"""Opening a file for reading with PyAV, on every PyAV version the app ships. + +A file whose tags are not valid UTF-8 must still open: it is still audio. +PyAV 18 decodes tags strictly by default and raises UnicodeDecodeError at open +unless given `metadata_errors="ignore"`; PyAV 19 REMOVED that keyword (passing +it is a TypeError) and opens such a file as it is, the bad bytes as surrogates. +Measured on both with a generated M4A and MP3 whose title is invalid UTF-8. + +The keyword once went straight into `av.open`, which worked on the dev venv's +18.1 while CI's fresh install took 19.0.1: every stem file then failed to open +in the released app, and the deck played stem tracks as the mix. Every read +goes through `open_input`, so the difference lives in one place. +""" +from __future__ import annotations + +from functools import cache +from pathlib import Path + + +@cache +def _takes_metadata_errors() -> bool: + import av + + return int(av.__version__.split(".")[0]) < 19 + + +def open_input(path: Path | str): + """`av.open(path)` for reading, tolerant of tags that are not UTF-8.""" + import av + + if _takes_metadata_errors(): + return av.open(str(path), metadata_errors="ignore") + return av.open(str(path)) diff --git a/backend/konduktor/core/stem_file.py b/backend/konduktor/core/stem_file.py index a044c4c..b17cc1e 100644 --- a/backend/konduktor/core/stem_file.py +++ b/backend/konduktor/core/stem_file.py @@ -45,7 +45,7 @@ from typing import Callable import numpy as np -from . import mp4_edit, tag_copy +from . import mp4_edit, pyav, tag_copy SR = 44100 FRAME = 1024 # AAC-LC frame size, for both encoders @@ -132,7 +132,7 @@ def decode(path: Path | str) -> Source: """Decode the first audio stream to stereo float32 at 44.1 kHz.""" import av - with av.open(str(path), metadata_errors="ignore") as container: + with pyav.open_input(path) as container: stream = container.streams.audio[0] codec = stream.codec_context.name bit_rate = stream.bit_rate or container.bit_rate or None @@ -381,7 +381,7 @@ def _audio_stream_count(path: Path) -> int: av = None if av is not None: try: - with av.open(str(path), metadata_errors="ignore") as c: + with pyav.open_input(path) as c: return len(c.streams.audio) except av.FFmpegError as ex: raise ValueError(str(ex)) @@ -453,7 +453,7 @@ def extract_stream(path: Path | str, stream: int, fp) -> None: """ import av - with av.open(str(path), metadata_errors="ignore") as inp: + with pyav.open_input(path) as inp: if not 0 <= stream < len(inp.streams.audio): raise StemFileError(f"The file has no audio stream {stream}") ist = inp.streams.audio[stream] diff --git a/backend/konduktor/core/waveform.py b/backend/konduktor/core/waveform.py index b38b04d..9c00067 100644 --- a/backend/konduktor/core/waveform.py +++ b/backend/konduktor/core/waveform.py @@ -94,7 +94,9 @@ def _decode_pyav(path: Path) -> np.ndarray: """ import av - with av.open(str(path)) as container: + from . import pyav + + with pyav.open_input(path) as container: stream = container.streams.audio[0] resampler = av.AudioResampler(format="flt", layout="mono", rate=SR) chunks = [] diff --git a/backend/requirements.txt b/backend/requirements.txt index 43f8fc3..f691eb3 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -4,7 +4,7 @@ fastapi>=0.115 uvicorn[standard]>=0.34 pydantic>=2.11 mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF) -av>=18.1 # PyAV: FFmpeg's decoders in the wheel — waveforms for export, AAC on every OS +av>=18.1,<20 # PyAV: FFmpeg's decoders in the wheel — waveforms for export, AAC on every OS. Before allowing a new major, check core/pyav.py (19 broke av.open) Pillow>=11 # cover art -> the 80/240 px JPEGs a Pioneer export carries python-multipart>=0.0.9 # multipart form parsing for cover-art upload # Version-history backups: a self-contained git impl (no system git needed; diff --git a/backend/test_stem_playback.py b/backend/test_stem_playback.py index 3fdf825..758ea7d 100644 --- a/backend/test_stem_playback.py +++ b/backend/test_stem_playback.py @@ -73,6 +73,27 @@ check("a stem file lists its four stems with names and colours, in stream order" check("a plain MP3 has none", sf.stem_layout(plain) is None) check("a missing file has none (no exception)", sf.stem_layout(ROOT / "nope.stem.m4a") is None) +print("== a stem file whose tags are not UTF-8 ==") +# PyAV 18 will not open such a file unless told to ignore the bad bytes, and +# PyAV 19 rejects the keyword that tells it (core/pyav.py). A release built on +# 19 while dev ran 18 played every stem track as the mix: the route 500'd. +from mutagen.mp4 import MP4 # noqa: E402 + +bad = ROOT / "BadTag.stem.m4a" +shutil.copy2(stem, bad) +m = MP4(bad) +m["\xa9nam"] = ["XéX"] +m.save() +raw = bad.read_bytes() +assert raw.count("XéX".encode()) == 1 +bad.write_bytes(raw.replace("XéX".encode(), b"X\xe9\xe9X")) # same length: no box sizes change +check(f"it still lists its stems (PyAV {av.__version__})", sf.stem_layout(bad) == layout, str(sf.stem_layout(bad))) +with open(ROOT / "bad-stem-1.m4a", "wb") as fp: + sf.extract_stream(bad, 1, fp) +check("…a stem still extracts, bit-identical to the stream in place", + np.array_equal(decode(ROOT / "bad-stem-1.m4a"), decode(stem, 1))) +check("…and it still decodes for conversion", sf.decode(bad).pcm.shape[1] > 0) + print("== a temp collection pointing at them ==") work = ROOT / "collection.nml" shutil.copy2(REAL, work) diff --git a/backend/test_timebase.py b/backend/test_timebase.py index b24b197..725a488 100644 --- a/backend/test_timebase.py +++ b/backend/test_timebase.py @@ -33,7 +33,7 @@ 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 import mp3_gapless, pyav # noqa: E402 from konduktor.core.adapter import NewTrack # noqa: E402 from konduktor.core.model import Track # noqa: E402 @@ -197,7 +197,7 @@ else: pad8 = re.search(r']*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: + with pyav.open_input(KIT / name) 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) @@ -258,7 +258,7 @@ else: name = c.Content.FileNameL if c.Content else "" if not name.startswith("K4-") or c.Kind != 9 or not (KIT / name).is_file(): continue # pad H: the ones placed by hand - with av.open(str(KIT / name), metadata_errors="ignore") as con: + with pyav.open_input(KIT / name) as con: st = con.streams.audio[0] sr = st.rate y = np.concatenate([f.to_ndarray()[0] for f in con.decode(st)]).astype(np.float64)