"""The stem writer (`core/stem_file.py`) on GENERATED sources with a FAKE engine. The separation is a callback, so everything Konduktor itself does — decode, encode five streams, the `stem` box, tags, verification — is tested here with no torch installed. What would fail SILENTLY is what this pins: * the two stem JSON literals are exactly the bytes the user's commercial files and Traktor's collection hold (skipped when those files are not on the machine), and hold the same float32 values; * a mono source is not converted 3 dB quieter, and resampling does not move time — both would shift or change every converted track; * the finished file starts on the source's first sample (cue positions carry over unchanged in the decoded time base), with every tag and the cover; * `verify` refuses a shifted, truncated or box-less file. """ from __future__ import annotations import fractions import html import json import os import re import struct import sys import tempfile import warnings from pathlib import Path warnings.filterwarnings("ignore") os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-stemfile-appdata-") import av # noqa: E402 import numpy as np # noqa: E402 from konduktor.core import stem_file as sf # noqa: E402 from konduktor.core import tag_copy # 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, x: np.ndarray, sr: int, layout="stereo", bit_rate=None): with av.open(str(path), "w", format=fmt) as c: s = c.add_stream(codec, rate=sr, layout=layout) if bit_rate: s.bit_rate = bit_rate n = x.shape[1] for o in range(0, n, 1152): f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout=layout) f.sample_rate, f.pts = sr, o for p in s.encode(f): c.mux(p) for p in s.encode(None): c.mux(p) def music(n, sr, seed=1): """Noise bursts on a beat: something every encoder and the correlator can grip.""" rng = np.random.default_rng(seed) x = np.zeros((2, n), np.float32) for start in range(int(0.5 * sr), n - sr // 10, sr // 2): burst = rng.uniform(-0.6, 0.6, (2, sr // 20)).astype(np.float32) x[:, start:start + burst.shape[1]] += burst * np.linspace(1, 0, burst.shape[1]) return x def fake_separate(pcm): """Four 'stems' in DEMUCS_ORDER: scaled copies, so each stream is distinct.""" return [pcm * g for g in (0.5, 0.25, -0.2, 0.1)] tmp = Path(tempfile.mkdtemp(prefix="konduktor-stemfile-")) print("== 1. the stem JSON literals ==") box, nml = json.loads(sf.STEM_BOX_JSON), json.loads(sf.NML_STEMS_JSON) def f32(o): if isinstance(o, float): return struct.unpack("f", struct.pack("f", o))[0] if isinstance(o, dict): return {k: f32(v) for k, v in o.items()} if isinstance(o, list): return [f32(v) for v in o] return o check("the box and the NML value hold the same float32 values", f32(box) == f32(nml)) check("names and colours are Drums/Bass/Synths/Vox, as on every stem in the collection", [s["name"] for s in box["stems"]] == list(sf.STEM_NAMES)) check("mastering DSP is written disabled", not box["mastering_dsp"]["compressor"]["enabled"] and not box["mastering_dsp"]["limiter"]["enabled"]) commercial = sorted(Path.home().glob("Music/Library/*.stem.m4a")) if commercial: check(f"the box is byte-identical to {len(commercial)} commercial stem files", all(sf.read_stem_box(p) == sf.STEM_BOX_JSON for p in commercial)) else: print(" (skipped: no commercial stem files on this machine)") real_nml = Path.home() / "Downloads/collection_latest.nml" if real_nml.is_file(): values = {html.unescape(v) for v in re.findall(r'` when added: # rendered from its own box by Traktor's rule. check("Traktor's rendering rule turns the box literal into the NML literal", sf.traktor_stems_json(sf.STEM_BOX_JSON) == sf.NML_STEMS_JSON) check("…and keeps other names, colours and values (keys sorted, whole floats as integers)", sf.traktor_stems_json(b'{"version": 1, "stems": [{"name": "Kick \\u00e9", "color": "#010203"}], ' b'"x": {"b": 2.5, "a": 3.0, "c": true}}') == '{"stems":[{"color":"#010203","name":"Kick é"}],"version":1,"x":{"a":3,"b":2.5,"c":true}}') nml_stem_entries = {} for n in (real_nml, Path.home() / "Downloads/collection.nml"): if n.is_file(): for file, value in re.findall(r'FILE="([^"]+)"(?:(?!).)*? Track.stem.m4a", sf.stem_target_name("Track.mp3") == "Track.stem.m4a") print("== 4. verify refuses what is wrong ==") source = sf.decode(MP3) def raw_file(name, master): path = tmp / name with open(path, "wb") as fp: sf._encode(fp, [master, *fake_separate(master)], bit_rate=256_000, encoder="aac", checkpoint=None) sf.add_stem_box(path) return path def refused(path, src_obj=source): try: sf.verify(path, src_obj) return None except sf.StemFileError as ex: return str(ex) shifted = np.roll(source.pcm, 5, axis=1) check("a mix shifted by 5 samples is refused", refused(raw_file("shift.m4a", shifted)) is not None) check("a truncated mix is refused", refused(raw_file("short.m4a", source.pcm[:, : source.samples - 5000])) is not None) good = raw_file("good.m4a", source.pcm) check("the same file unshifted passes", refused(good) is None, refused(good) or "") nobox = tmp / "nobox.m4a" with open(nobox, "wb") as fp: sf._encode(fp, [source.pcm, *fake_separate(source.pcm)], bit_rate=256_000, encoder="aac", checkpoint=None) check("a file without the stem box is refused", "box" in (refused(nobox) or ""), refused(nobox) or "") print("== 5. cancel ==") class Stop(Exception): pass calls = {"n": 0} def stop_in_encode(): calls["n"] += 1 if calls["n"] > 3: raise Stop() def encoder_threads(): import threading return [t.name for t in threading.enumerate() if t.name.startswith("stem-encode-")] try: sf.build(MP3, tmp / "cancelled.partial", fake_separate, encoder="aac", checkpoint=stop_in_encode) check("a checkpoint that raises stops the build", False, "it finished") except Stop: check("a checkpoint that raises stops the build", True) check("…and no encoder thread outlives it", not encoder_threads(), str(encoder_threads())) print("== 6. the encode runs on one thread per stream ==") def encode_single_threaded(fp, tracks, *, bit_rate, encoder): """The encode as it was before it was threaded: the reference for the bytes.""" tb = fractions.Fraction(1, SR) c = av.open(fp, "w", format="ipod") try: streams = [] for k in range(len(tracks)): s = c.add_stream(encoder, rate=SR, layout="stereo") s.bit_rate = bit_rate if k: s.disposition = 0 streams.append(s) for offset in range(0, tracks[0].shape[1], sf.FRAME): for s, x in zip(streams, tracks): f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, offset:offset + sf.FRAME]), format="fltp", layout="stereo") f.sample_rate, f.pts, f.time_base = SR, offset, tb for p in s.encode(f): c.mux(p) for s in streams: for p in s.encode(None): c.mux(p) finally: c.close() source = sf.decode(MP3) # A length that is not a whole number of frames, and stems that differ from the mix. five = [np.ascontiguousarray(t[:, :-333]) for t in (source.pcm, *fake_separate(source.pcm))] for enc in encoders: ref, par = tmp / f"ref.{enc}.m4a", tmp / f"par.{enc}.m4a" with open(ref, "wb") as fp: encode_single_threaded(fp, five, bit_rate=320_000, encoder=enc) seen = [] with open(par, "wb") as fp: sf._encode(fp, five, bit_rate=320_000, encoder=enc, checkpoint=None, progress=seen.append) check(f"{enc}: the threaded encode is byte-identical to the single-threaded one", ref.read_bytes() == par.read_bytes(), f"{ref.stat().st_size} vs {par.stat().st_size} bytes") check(f"{enc}: progress runs 0 -> 1, never backwards", len(seen) >= 3 and seen[0] == 0 and seen[-1] == 1.0 and seen == sorted(seen), str(seen)) try: with open(tmp / "broken.m4a", "wb") as fp: # A mono array in a stereo stream: that stream's thread fails on its first frame. sf._encode(fp, [five[0], five[1][:1], *five[2:]], bit_rate=320_000, encoder="aac", checkpoint=None) check("a failing encoder thread fails the encode", False, "it finished") except Exception as ex: # noqa: BLE001 check("a failing encoder thread fails the encode, with its own error", not isinstance(ex, Stop), repr(ex)) check("…and no encoder thread outlives it", not encoder_threads(), str(encoder_threads())) print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0)