"""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' 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() 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) print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0)