diff --git a/CLAUDE.md b/CLAUDE.md index c79cfea..e202b9e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -170,7 +170,14 @@ Two independent apps that talk over HTTP: file** (Convert to Stems). An `ipod` MP4 with five AAC stereo 44.1 kHz streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0, muxed IN LOCKSTEP, plus a `moov/udta/stem` JSON box appended in place - (moov is last, so only two sizes change). The separation is a CALLBACK — + (moov is last, so only two sizes change). **Each stream encodes on its + own thread** (PyAV releases the GIL in FFmpeg; ~3x faster with `aac`, + 104 → 35 s for a 5-minute track's real stems) while ONE thread muxes in + the single-threaded order, so the file is byte-identical; every codec is + opened and the header written before a worker starts, since the first + `mux()` would otherwise open codecs a worker is using. `aac_coder=fast` + was measured and rejected: 3-4x faster per stream, but it drops whole + 8-20 kHz bands for moments (twoloop: never). The separation is a CALLBACK — the backend never imports torch; the engine (below) supplies it, the tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB, so mono is duplicated by hand; resampling does not move time; both @@ -1171,7 +1178,10 @@ serialization path.** It enforces: 48 kHz resampling does not move time; MP3 and FLAC through both encoders give five streams with only the mix enabled, no shift (cross-correlation), the bitrate rule (256 floor, lossless 320), every tag + cover; `verify` refuses a - shifted, truncated or box-less file; a raising checkpoint cancels. + shifted, truncated or box-less file; a raising checkpoint cancels. The + threaded encode is byte-identical to a single-threaded reference (with each + encoder present), reports progress 0 → 1, and a cancel or a failing encoder + thread leaves no thread running. - `test_stem_swap.py` — `apply_stem_swaps` on a temp copy of the real collection with a generated MP3 (with header) and a real stem file: prep reads back at the same decoded second while its START moves by the 2257- diff --git a/backend/konduktor/core/stem_file.py b/backend/konduktor/core/stem_file.py index b17cc1e..68033e5 100644 --- a/backend/konduktor/core/stem_file.py +++ b/backend/konduktor/core/stem_file.py @@ -37,8 +37,10 @@ from __future__ import annotations import fractions import json +import queue import struct import sys +import threading from dataclasses import dataclass from pathlib import Path from typing import Callable @@ -151,15 +153,36 @@ def decode(path: Path | str) -> Source: return Source(pcm=np.ascontiguousarray(pcm), codec=codec, bit_rate=bit_rate) +#: Encoded frames each stream's thread may run ahead of the muxer. +_ENCODE_QUEUE = 64 +#: Frames between `checkpoint()` / `progress()` calls (~6 s of audio). +_ENCODE_TICK = 256 + + def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str, - checkpoint: Callable[[], None] | None) -> None: - """Mux five AAC streams IN LOCKSTEP — one frame of each in turn — so the - muxer never buffers a whole stream (which it would if they came one after - another).""" + checkpoint: Callable[[], None] | None, + progress: Callable[[float], None] | None = None) -> None: + """Encode the AAC streams on one thread EACH and mux them on this one, IN + LOCKSTEP — per frame stream 0..4, then each stream's flush — so the muxer + never buffers a whole stream (which it would if they came one after another). + + The encoders are independent and PyAV releases the GIL inside FFmpeg, so + this is ~3x faster than one thread with FFmpeg's `aac` (a 5-minute track's + real stems: 104 s -> 35 s on a 6-core i7) — and since the mux order is the single-threaded + one, the file is byte-identical. Every codec is opened and the header written + HERE before any worker starts: the first `mux()` would otherwise open (and + read) codec contexts a worker may be opening or encoding with. After that + this thread never touches a codec, and a worker never touches the container. + + `checkpoint()` and `progress(fraction)` are called from this thread only. + """ import av n = tracks[0].shape[1] tb = fractions.Fraction(1, SR) + offsets = range(0, n, FRAME) + stop = threading.Event() + threads: list[threading.Thread] = [] container = av.open(fp, "w", format="ipod") try: streams = [] @@ -169,21 +192,63 @@ def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str, if k: s.disposition = 0 # present, not enabled: a plain player plays the mix streams.append(s) - for i, offset in enumerate(range(0, n, FRAME)): - if checkpoint is not None and i % 512 == 0: - checkpoint() - for s, x in zip(streams, tracks): - frame = av.AudioFrame.from_ndarray( - np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32), - format="fltp", layout="stereo", - ) - frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb - for packet in s.encode(frame): - container.mux(packet) for s in streams: - for packet in s.encode(None): + s.codec_context.open(strict=False) + container.start_encoding() + queues = [queue.Queue(maxsize=_ENCODE_QUEUE) for _ in tracks] + + def put(q: queue.Queue, item) -> bool: + while not stop.is_set(): + try: + q.put(item, timeout=0.1) + return True + except queue.Full: + pass + return False # the muxer gave up: stop encoding + + def work(s, x: np.ndarray, q: queue.Queue) -> None: + try: + for offset in offsets: + frame = av.AudioFrame.from_ndarray( + np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32), + format="fltp", layout="stereo", + ) + frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb + if not put(q, s.encode(frame)): + return + put(q, s.encode(None)) + except BaseException as ex: # noqa: BLE001 — re-raised by the muxer + put(q, ex) + + def mux(q: queue.Queue) -> None: + packets = q.get() + if isinstance(packets, BaseException): + raise packets + for packet in packets: container.mux(packet) + + threads = [threading.Thread(target=work, args=(s, x, q), daemon=True, name=f"stem-encode-{k}") + for k, (s, x, q) in enumerate(zip(streams, tracks, queues))] + for t in threads: + t.start() + for i in range(len(offsets)): + if i % _ENCODE_TICK == 0: + if checkpoint is not None: + checkpoint() + if progress is not None: + progress(i / len(offsets)) + for q in queues: + mux(q) + for q in queues: + mux(q) # each stream's flush + if progress is not None: + progress(1.0) finally: + # A cancel or a failure: the workers stop at their next frame, and must + # have stopped before the container (and their codecs) are freed. + stop.set() + for t in threads: + t.join() container.close() @@ -302,14 +367,16 @@ Separate = Callable[[np.ndarray], list[np.ndarray]] def build(source_path: Path | str, target: Path | str, separate: Separate, *, - encoder: str | None = None, checkpoint: Callable[[], None] | None = None) -> Written: + encoder: str | None = None, checkpoint: Callable[[], None] | None = None, + on_encode: Callable[[float], None] | None = None) -> Written: """Convert `source_path` into a stem file at `target`. `separate(pcm)` gets the stereo 44.1 kHz mix and must return the four stems in `DEMUCS_ORDER`, each the mix's shape. `target` may be any name — the batch writes a `*.konduktor-partial` and renames it once the batch commits — since nothing here infers a format from the suffix. `checkpoint()` is called between - phases and during the encode, and may raise to cancel. + phases and during the encode, and may raise to cancel. `on_encode(fraction)` + reports the encode's progress, 0 to 1 (verifying after it takes ~1 s). """ target = Path(target) tick = checkpoint or (lambda: None) @@ -322,7 +389,7 @@ def build(source_path: Path | str, target: Path | str, separate: Separate, *, bit_rate = choose_bitrate(source) with open(target, "wb") as fp: _encode(fp, [source.pcm, *stems], bit_rate=bit_rate, - encoder=encoder or default_encoder(), checkpoint=checkpoint) + encoder=encoder or default_encoder(), checkpoint=checkpoint, progress=on_encode) add_stem_box(target) tags = tag_copy.copy_tags(source_path, target) verify(target, source) diff --git a/backend/konduktor/stems/convert.py b/backend/konduktor/stems/convert.py index b08d4ae..5f5acbe 100644 --- a/backend/konduktor/stems/convert.py +++ b/backend/konduktor/stems/convert.py @@ -39,11 +39,25 @@ _BYTES_PER_SECOND = {256_000: 5 * 256_000 / 8 * 1.03, 320_000: 5 * 320_000 / 8 * _WORK_BYTES_PER_SECOND = 5 * 2 * 4 * sf.SR -#: Shares of ONE track's conversion time, for the status bar's within-track -#: progress (measured on the M3 Pro: decode ~1 s, separate ~50 s, encode + -#: verify ~4 s for a 4-minute track). -_DECODE_SHARE = 0.03 -_SEPARATE_SHARE = 0.90 +#: Shares of ONE track's conversion time (decode, separate; encoding + verifying +#: take the rest), for the status bar's within-track progress, by AAC encoder. +#: Measured: `aac_at` on the M3 Pro (4-minute track: decode ~1 s, separate +#: ~50 s, encode + verify ~4 s); `aac` on an i7-9750H + RTX 2070 (5-minute +#: track: decode 0.5 s, separate ~102 s, encode ~38 s on five threads, verify ~1 s). +_SHARES = {"aac_at": (0.03, 0.90), "aac": (0.01, 0.71)} + + +def track_shares(encoder: str) -> tuple[float, float]: + return _SHARES.get(encoder, _SHARES["aac"]) + + +def encode_reporter(handle, start: float, end: float = 0.99) -> Callable[[float], None]: + """`on_encode` for `stem_file.build`: the encode runs from `start` to `end` + of the track, and the ~1 s of tags + verification after it reads as such.""" + def report(f: float) -> None: + frac = start + f * (end - start) + handle.progress(fraction=frac, status=f"{'verifying' if f >= 1 else 'encoding'} {frac * 100:.0f} %") + return report class ConvertError(Exception): @@ -227,6 +241,7 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *, work = work_root() / f"batch-{id(handle):x}" finished: list[tuple[Planned, dict, sf.Written]] = [] needs_engine = any(p.reuse is None for p in items) + encoder = sf.default_encoder() if needs_engine and not mgr.ready(): raise ConvertError("The stem engine is not installed") @@ -258,22 +273,22 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *, "stem": str(item.target), "state": "converting", "facts": source_facts(item.source)}) item.target.parent.mkdir(parents=True, exist_ok=True) - # Of a TRACK's time, separation is nearly all (~90 % on MPS); - # decoding before it and encoding + verifying after share the rest. + # Of a TRACK's time, separation is nearly all; decoding before it + # and encoding + verifying after share the rest. + decode_share, separate_share = track_shares(encoder) + def on_progress(f: float) -> None: - frac = _DECODE_SHARE + f * (_SEPARATE_SHARE) + frac = decode_share + f * separate_share handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %") def separate(pcm): - handle.progress(fraction=_DECODE_SHARE, status=f"separating {_DECODE_SHARE * 100:.0f} %") - stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled) - done_at = _DECODE_SHARE + _SEPARATE_SHARE - handle.progress(fraction=done_at, status=f"encoding {done_at * 100:.0f} %") - return stems + handle.progress(fraction=decode_share, status=f"separating {decode_share * 100:.0f} %") + return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled) handle.progress(status="decoding 0 %") try: - written = sf.build(item.source, partial, separate, checkpoint=checkpoint) + written = sf.build(item.source, partial, separate, encoder=encoder, checkpoint=checkpoint, + on_encode=encode_reporter(handle, decode_share + separate_share)) except (_Cancel, EngineCancelled): partial.unlink(missing_ok=True) pending.drop([pitem]) diff --git a/backend/konduktor/stems/remote_convert.py b/backend/konduktor/stems/remote_convert.py index 14b120c..98952b1 100644 --- a/backend/konduktor/stems/remote_convert.py +++ b/backend/konduktor/stems/remote_convert.py @@ -153,13 +153,12 @@ def run(handle, adapter, planned: RemotePlan, opts: convert.Options, *, still_cu def separate(pcm): handle.progress(fraction=0.05, status="separating 5 %") - stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled) - handle.progress(fraction=0.85, status="encoding 85 %") - return stems + return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled) partial = work / f"{n}.stem.m4a" try: - written = sf.build(local, partial, separate, checkpoint=checkpoint) + written = sf.build(local, partial, separate, checkpoint=checkpoint, + on_encode=convert.encode_reporter(handle, 0.85, 0.9)) except (convert._Cancel, EngineCancelled): partial.unlink(missing_ok=True) raise diff --git a/backend/test_stem_file.py b/backend/test_stem_file.py index c142641..dddee8f 100644 --- a/backend/test_stem_file.py +++ b/backend/test_stem_file.py @@ -262,11 +262,71 @@ def stop_in_encode(): 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)