Pararellized STEM aac encoding

This commit is contained in:
patben8 committed 2026-10-13 10:45:52 +02:00
1 parent ebe30c1128
commit 591f2bc791
5 files changed
+186 -35

No files matched your search

+12 -2
View File
@@ -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 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, streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0,
muxed IN LOCKSTEP, plus a `moov/udta/stem` JSON box appended in place 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 the backend never imports torch; the engine (below) supplies it, the
tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB, 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 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 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 five streams with only the mix enabled, no shift (cross-correlation), the
bitrate rule (256 floor, lossless 320), every tag + cover; `verify` refuses a 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 - `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 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- reads back at the same decoded second while its START moves by the 2257-
+82 -15
View File
@@ -37,8 +37,10 @@ from __future__ import annotations
import fractions import fractions
import json import json
import queue
import struct import struct
import sys import sys
import threading
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Callable 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) 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, def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
checkpoint: Callable[[], None] | None) -> None: checkpoint: Callable[[], None] | None,
"""Mux five AAC streams IN LOCKSTEP — one frame of each in turn — so the progress: Callable[[float], None] | None = None) -> None:
muxer never buffers a whole stream (which it would if they came one after """Encode the AAC streams on one thread EACH and mux them on this one, IN
another).""" 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 import av
n = tracks[0].shape[1] n = tracks[0].shape[1]
tb = fractions.Fraction(1, SR) tb = fractions.Fraction(1, SR)
offsets = range(0, n, FRAME)
stop = threading.Event()
threads: list[threading.Thread] = []
container = av.open(fp, "w", format="ipod") container = av.open(fp, "w", format="ipod")
try: try:
streams = [] streams = []
@@ -169,21 +192,63 @@ def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
if k: if k:
s.disposition = 0 # present, not enabled: a plain player plays the mix s.disposition = 0 # present, not enabled: a plain player plays the mix
streams.append(s) streams.append(s)
for i, offset in enumerate(range(0, n, FRAME)): for s in streams:
if checkpoint is not None and i % 512 == 0: s.codec_context.open(strict=False)
checkpoint() container.start_encoding()
for s, x in zip(streams, tracks): 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( frame = av.AudioFrame.from_ndarray(
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32), np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
format="fltp", layout="stereo", format="fltp", layout="stereo",
) )
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
for packet in s.encode(frame): if not put(q, s.encode(frame)):
container.mux(packet) return
for s in streams: put(q, s.encode(None))
for packet in 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) 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: 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() container.close()
@@ -302,14 +367,16 @@ Separate = Callable[[np.ndarray], list[np.ndarray]]
def build(source_path: Path | str, target: Path | str, separate: Separate, *, 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`. """Convert `source_path` into a stem file at `target`.
`separate(pcm)` gets the stereo 44.1 kHz mix and must return the four stems `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 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 writes a `*.konduktor-partial` and renames it once the batch commits — since
nothing here infers a format from the suffix. `checkpoint()` is called between 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) target = Path(target)
tick = checkpoint or (lambda: None) 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) bit_rate = choose_bitrate(source)
with open(target, "wb") as fp: with open(target, "wb") as fp:
_encode(fp, [source.pcm, *stems], bit_rate=bit_rate, _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) add_stem_box(target)
tags = tag_copy.copy_tags(source_path, target) tags = tag_copy.copy_tags(source_path, target)
verify(target, source) verify(target, source)
+29 -14
View File
@@ -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 _WORK_BYTES_PER_SECOND = 5 * 2 * 4 * sf.SR
#: Shares of ONE track's conversion time, for the status bar's within-track #: Shares of ONE track's conversion time (decode, separate; encoding + verifying
#: progress (measured on the M3 Pro: decode ~1 s, separate ~50 s, encode + #: take the rest), for the status bar's within-track progress, by AAC encoder.
#: verify ~4 s for a 4-minute track). #: Measured: `aac_at` on the M3 Pro (4-minute track: decode ~1 s, separate
_DECODE_SHARE = 0.03 #: ~50 s, encode + verify ~4 s); `aac` on an i7-9750H + RTX 2070 (5-minute
_SEPARATE_SHARE = 0.90 #: 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): 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}" work = work_root() / f"batch-{id(handle):x}"
finished: list[tuple[Planned, dict, sf.Written]] = [] finished: list[tuple[Planned, dict, sf.Written]] = []
needs_engine = any(p.reuse is None for p in items) needs_engine = any(p.reuse is None for p in items)
encoder = sf.default_encoder()
if needs_engine and not mgr.ready(): if needs_engine and not mgr.ready():
raise ConvertError("The stem engine is not installed") 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)}) "stem": str(item.target), "state": "converting", "facts": source_facts(item.source)})
item.target.parent.mkdir(parents=True, exist_ok=True) item.target.parent.mkdir(parents=True, exist_ok=True)
# Of a TRACK's time, separation is nearly all (~90 % on MPS); # Of a TRACK's time, separation is nearly all; decoding before it
# decoding before it and encoding + verifying after share the rest. # and encoding + verifying after share the rest.
decode_share, separate_share = track_shares(encoder)
def on_progress(f: float) -> None: 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} %") handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %")
def separate(pcm): def separate(pcm):
handle.progress(fraction=_DECODE_SHARE, status=f"separating {_DECODE_SHARE * 100:.0f} %") 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) return 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(status="decoding 0 %") handle.progress(status="decoding 0 %")
try: 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): except (_Cancel, EngineCancelled):
partial.unlink(missing_ok=True) partial.unlink(missing_ok=True)
pending.drop([pitem]) pending.drop([pitem])
+3 -4
View File
@@ -153,13 +153,12 @@ def run(handle, adapter, planned: RemotePlan, opts: convert.Options, *, still_cu
def separate(pcm): def separate(pcm):
handle.progress(fraction=0.05, status="separating 5 %") handle.progress(fraction=0.05, status="separating 5 %")
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled) return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
handle.progress(fraction=0.85, status="encoding 85 %")
return stems
partial = work / f"{n}.stem.m4a" partial = work / f"{n}.stem.m4a"
try: 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): except (convert._Cancel, EngineCancelled):
partial.unlink(missing_ok=True) partial.unlink(missing_ok=True)
raise raise
+60
View File
@@ -262,11 +262,71 @@ def stop_in_encode():
raise Stop() raise Stop()
def encoder_threads():
import threading
return [t.name for t in threading.enumerate() if t.name.startswith("stem-encode-")]
try: try:
sf.build(MP3, tmp / "cancelled.partial", fake_separate, encoder="aac", checkpoint=stop_in_encode) 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") check("a checkpoint that raises stops the build", False, "it finished")
except Stop: except Stop:
check("a checkpoint that raises stops the build", True) 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") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)