mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-29 10:32:51 +01:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87cbd3720e | ||
|
|
591f2bc791 | ||
|
|
ebe30c1128 | ||
|
|
cd1914216f |
No files matched your search
@@ -33,6 +33,18 @@ npm install
|
|||||||
cd ..
|
cd ..
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Develop (no build)
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\dev.ps1 # backend on :8000 + Vite on :5173, both reloading; Ctrl-C stops both
|
||||||
|
```
|
||||||
|
|
||||||
|
Then open <http://localhost:5173> in a browser. This is `dev.sh` for Windows.
|
||||||
|
It runs the Python source, not the frozen sidecar, so it cannot show
|
||||||
|
desktop-shell behaviour (startup screen, quit prompt, WebView2). For that, use
|
||||||
|
`npx tauri dev` in `frontend` — but note it still spawns the FROZEN sidecar from
|
||||||
|
`src-tauri\binaries\`, so backend changes need `build_sidecar.ps1` first.
|
||||||
|
|
||||||
## Build
|
## Build
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -1098,6 +1105,7 @@ Two independent apps that talk over HTTP:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
./dev.sh # start both servers (see README for one-time setup)
|
./dev.sh # start both servers (see README for one-time setup)
|
||||||
|
.\dev.ps1 # the same on Windows (BUILDING-WINDOWS.md)
|
||||||
|
|
||||||
# Backend
|
# Backend
|
||||||
cd backend && source .venv/bin/activate
|
cd backend && source .venv/bin/activate
|
||||||
@@ -1170,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-
|
||||||
|
|||||||
@@ -16,7 +16,12 @@ Set-Location $Root
|
|||||||
$Py = Join-Path $Root ".venv\Scripts\python.exe"
|
$Py = Join-Path $Root ".venv\Scripts\python.exe"
|
||||||
if (-not (Test-Path $Py)) { $Py = "python" }
|
if (-not (Test-Path $Py)) { $Py = "python" }
|
||||||
|
|
||||||
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
|
# PyInstaller logs to stderr. Windows PowerShell 5.1 (unlike pwsh 7) turns a
|
||||||
|
# native command's stderr into an error record, which "Stop" makes fatal on the
|
||||||
|
# first INFO line — so relax it for this call and judge by the exit code.
|
||||||
|
$ErrorActionPreference = "Continue"
|
||||||
|
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec 2>&1 | ForEach-Object { "$_" }
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" }
|
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" }
|
||||||
Write-Host "Built: $Root\dist\konduktor-sidecar\"
|
Write-Host "Built: $Root\dist\konduktor-sidecar\"
|
||||||
|
|
||||||
|
|||||||
@@ -235,8 +235,8 @@ def detect_grid(
|
|||||||
if bpm is not None and not (20.0 <= bpm <= 400.0):
|
if bpm is not None and not (20.0 <= bpm <= 400.0):
|
||||||
raise ValueError(f"Not a usable BPM: {bpm}")
|
raise ValueError(f"Not a usable BPM: {bpm}")
|
||||||
if y is None:
|
if y is None:
|
||||||
import librosa
|
from . import waveform
|
||||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
y, sr = waveform.load(audio_path, sr=sr)
|
||||||
y = np.asarray(y, dtype=np.float32)
|
y = np.asarray(y, dtype=np.float32)
|
||||||
duration = len(y) / sr
|
duration = len(y) / sr
|
||||||
if duration < 1.5:
|
if duration < 1.5:
|
||||||
|
|||||||
@@ -178,7 +178,7 @@ def with_detected_key(track, y: np.ndarray | None, sr: int):
|
|||||||
|
|
||||||
|
|
||||||
def detect_key(audio_path: str) -> KeyResult | None:
|
def detect_key(audio_path: str) -> KeyResult | None:
|
||||||
import librosa
|
from . import waveform
|
||||||
|
|
||||||
y, sr = librosa.load(audio_path, sr=SR, mono=True)
|
y, sr = waveform.load(audio_path, sr=SR)
|
||||||
return detect_key_samples(y, sr)
|
return detect_key_samples(y, sr)
|
||||||
@@ -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)):
|
|
||||||
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 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)
|
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)
|
||||||
|
|||||||
@@ -273,8 +273,8 @@ def analyse(
|
|||||||
if not markers:
|
if not markers:
|
||||||
raise ValueError("Set a beatgrid first")
|
raise ValueError("Set a beatgrid first")
|
||||||
if y is None:
|
if y is None:
|
||||||
import librosa
|
from . import waveform
|
||||||
y, _ = librosa.load(audio_path, sr=_SR, mono=True)
|
y, _ = waveform.load(audio_path, sr=_SR)
|
||||||
y = np.asarray(y, dtype=np.float32)
|
y = np.asarray(y, dtype=np.float32)
|
||||||
duration = len(y) / _SR
|
duration = len(y) / _SR
|
||||||
beats, bar0 = grid_beats(markers, duration)
|
beats, bar0 = grid_beats(markers, duration)
|
||||||
|
|||||||
@@ -84,8 +84,8 @@ class Analysis:
|
|||||||
return self.columns.duration
|
return self.columns.duration
|
||||||
|
|
||||||
|
|
||||||
def _decode_pyav(path: Path) -> np.ndarray:
|
def _decode_pyav(path: Path, sr: int = SR) -> np.ndarray:
|
||||||
"""Mono float32 at `SR`, via PyAV — FFmpeg's decoders, bundled in its wheel.
|
"""Mono float32 at `sr`, via PyAV — FFmpeg's decoders, bundled in its wheel.
|
||||||
|
|
||||||
The reason it is first: it decodes AAC (every Traktor `.stem.m4a`) on EVERY
|
The reason it is first: it decodes AAC (every Traktor `.stem.m4a`) on EVERY
|
||||||
OS, where librosa needs CoreAudio (macOS only) or a system ffmpeg. Measured
|
OS, where librosa needs CoreAudio (macOS only) or a system ffmpeg. Measured
|
||||||
@@ -98,7 +98,7 @@ def _decode_pyav(path: Path) -> np.ndarray:
|
|||||||
|
|
||||||
with pyav.open_input(path) as container:
|
with pyav.open_input(path) as container:
|
||||||
stream = container.streams.audio[0]
|
stream = container.streams.audio[0]
|
||||||
resampler = av.AudioResampler(format="flt", layout="mono", rate=SR)
|
resampler = av.AudioResampler(format="flt", layout="mono", rate=sr)
|
||||||
chunks = []
|
chunks = []
|
||||||
for frame in container.decode(stream):
|
for frame in container.decode(stream):
|
||||||
for out in resampler.resample(frame):
|
for out in resampler.resample(frame):
|
||||||
@@ -122,16 +122,24 @@ def even_slices(n: int, k: int) -> list[slice]:
|
|||||||
return [slice(int(a), int(max(b, a + 1)) if n else 0) for a, b in zip(edges[:-1], edges[1:])]
|
return [slice(int(a), int(max(b, a + 1)) if n else 0) for a, b in zip(edges[:-1], edges[1:])]
|
||||||
|
|
||||||
|
|
||||||
def _decode(path: Path) -> np.ndarray | None:
|
def load(path: Path | str, sr: int = SR) -> tuple[np.ndarray, int]:
|
||||||
|
"""Mono float32 at `sr` as `(y, sr)` — `librosa.load`'s shape, raising as it
|
||||||
|
does. EVERY analysis decode goes through here, never `librosa.load` itself:
|
||||||
|
librosa reads AAC only through CoreAudio or a system ffmpeg, so on Windows
|
||||||
|
a `.stem.m4a` failed with "Format not recognised"."""
|
||||||
try:
|
try:
|
||||||
return _decode_pyav(path)
|
return _decode_pyav(Path(path), sr), sr
|
||||||
except Exception as ex: # PyAV missing, or a file FFmpeg cannot open
|
except Exception as ex: # PyAV missing, or a file FFmpeg cannot open
|
||||||
log.debug("PyAV could not decode %s (%s); trying librosa", path, ex)
|
log.debug("PyAV could not decode %s (%s); trying librosa", path, ex)
|
||||||
try:
|
import librosa
|
||||||
import librosa
|
|
||||||
|
|
||||||
y, _ = librosa.load(str(path), sr=SR, mono=True)
|
y, _ = librosa.load(str(path), sr=sr, mono=True)
|
||||||
return y
|
return y, sr
|
||||||
|
|
||||||
|
|
||||||
|
def _decode(path: Path) -> np.ndarray | None:
|
||||||
|
try:
|
||||||
|
return load(path)[0]
|
||||||
except Exception as ex: # any decoder failure: no waveform, not a failed export
|
except Exception as ex: # any decoder failure: no waveform, not a failed export
|
||||||
log.warning("could not decode %s for a waveform: %s", path, ex)
|
log.warning("could not decode %s for a waveform: %s", path, ex)
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -120,8 +120,12 @@ app.add_middleware(
|
|||||||
"http://localhost:5173",
|
"http://localhost:5173",
|
||||||
"http://127.0.0.1:5173",
|
"http://127.0.0.1:5173",
|
||||||
# Packaged desktop app: the webview's origin when Tauri loads the built
|
# Packaged desktop app: the webview's origin when Tauri loads the built
|
||||||
# frontend (macOS uses tauri://, Windows/Linux use https://tauri.localhost).
|
# frontend. macOS uses tauri://; Windows/Linux default to
|
||||||
|
# https://tauri.localhost, but lib.rs forces the http scheme
|
||||||
|
# (use_https_scheme(false)) so the sidecar is not mixed content —
|
||||||
|
# without the http origin here, the Windows app reaches no API at all.
|
||||||
"tauri://localhost",
|
"tauri://localhost",
|
||||||
|
"http://tauri.localhost",
|
||||||
"https://tauri.localhost",
|
"https://tauri.localhost",
|
||||||
],
|
],
|
||||||
allow_methods=["*"],
|
allow_methods=["*"],
|
||||||
@@ -1662,10 +1666,10 @@ def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview:
|
|||||||
|
|
||||||
def _decode_for_analysis(path: Path):
|
def _decode_for_analysis(path: Path):
|
||||||
"""Mono samples at the rate BOTH detectors work at (they share one decode)."""
|
"""Mono samples at the rate BOTH detectors work at (they share one decode)."""
|
||||||
import librosa
|
from .core import waveform
|
||||||
|
|
||||||
assert grid_detect._SR == key_detect.SR, "grid and key detection must share a sample rate"
|
assert grid_detect._SR == key_detect.SR, "grid and key detection must share a sample rate"
|
||||||
return librosa.load(str(path), sr=key_detect.SR, mono=True)
|
return waveform.load(path, sr=key_detect.SR)
|
||||||
|
|
||||||
|
|
||||||
def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None:
|
def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None:
|
||||||
|
|||||||
@@ -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])
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
+26
-4
@@ -28,16 +28,38 @@ def _watch_parent_and_exit() -> None:
|
|||||||
shut down, so the backend can never be orphaned (the Rust-side kill-on-exit
|
shut down, so the backend can never be orphaned (the Rust-side kill-on-exit
|
||||||
only covers the graceful path). When run standalone from a terminal, stdin is
|
only covers the graceful path). When run standalone from a terminal, stdin is
|
||||||
a TTY and this blocks harmlessly forever.
|
a TTY and this blocks harmlessly forever.
|
||||||
|
|
||||||
|
NOT on Windows: there a read left pending on the stdin pipe stalls loading
|
||||||
|
scipy's OpenBLAS DLL in any other thread, forever — so the first analysis
|
||||||
|
hung the packaged app (dev runs no watcher). Measured 2026-10-12 with plain
|
||||||
|
Python, through the CRT and through kernel32.ReadFile alike. Windows waits
|
||||||
|
on the parent PROCESS instead, which also covers a crash.
|
||||||
"""
|
"""
|
||||||
try:
|
if sys.platform == "win32":
|
||||||
while sys.stdin.buffer.read(1):
|
_wait_for_parent_process()
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
while sys.stdin.buffer.read(1):
|
||||||
|
pass
|
||||||
|
except Exception:
|
||||||
pass
|
pass
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
_release_remote()
|
_release_remote()
|
||||||
os._exit(0)
|
os._exit(0)
|
||||||
|
|
||||||
|
|
||||||
|
def _wait_for_parent_process() -> None:
|
||||||
|
"""Block until the process that started us exits (Windows only)."""
|
||||||
|
import ctypes
|
||||||
|
|
||||||
|
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||||
|
kernel32.OpenProcess.restype = ctypes.c_void_p
|
||||||
|
kernel32.WaitForSingleObject.argtypes = (ctypes.c_void_p, ctypes.c_uint32)
|
||||||
|
synchronize, infinite = 0x00100000, 0xFFFFFFFF
|
||||||
|
handle = kernel32.OpenProcess(synchronize, False, os.getppid())
|
||||||
|
if handle: # None: the parent is already gone
|
||||||
|
kernel32.WaitForSingleObject(handle, infinite)
|
||||||
|
|
||||||
|
|
||||||
def _release_remote() -> None:
|
def _release_remote() -> None:
|
||||||
"""Hand back a remote library's session on the way out, so the next
|
"""Hand back a remote library's session on the way out, so the next
|
||||||
computer opens it at once instead of waiting out the lease (or being asked
|
computer opens it at once instead of waiting out the lease (or being asked
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Start both Konduktor servers (backend + frontend) together - the Windows
|
||||||
|
# counterpart of dev.sh. Ctrl-C stops both. First run? See one-time setup in
|
||||||
|
# BUILDING-WINDOWS.md (the backend venv and `npm install`).
|
||||||
|
#
|
||||||
|
# .\dev.ps1
|
||||||
|
# (if scripts are blocked: powershell -ExecutionPolicy Bypass -File .\dev.ps1)
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
$Root = $PSScriptRoot
|
||||||
|
|
||||||
|
$Py = Join-Path $Root "backend\.venv\Scripts\python.exe"
|
||||||
|
if (-not (Test-Path $Py)) { throw "No backend venv at backend\.venv - see BUILDING-WINDOWS.md for setup." }
|
||||||
|
# Vite through node, not `npm run dev`: npm is a .cmd batch file, and Ctrl-C in a
|
||||||
|
# shared console makes cmd ask "Terminate batch job (Y/N)?" instead of exiting.
|
||||||
|
$Vite = Join-Path $Root "frontend\node_modules\vite\bin\vite.js"
|
||||||
|
if (-not (Test-Path $Vite)) { throw "No frontend\node_modules - run ``npm install`` in frontend first." }
|
||||||
|
|
||||||
|
# Backend (FastAPI on :8000)
|
||||||
|
$Backend = Start-Process -FilePath $Py -NoNewWindow -PassThru `
|
||||||
|
-ArgumentList "-m", "uvicorn", "konduktor.main:app", "--reload", "--port", "8000", "--app-dir", "`"$Root\backend`""
|
||||||
|
|
||||||
|
# Frontend (Vite on :5173, proxies /api -> :8000)
|
||||||
|
$Frontend = Start-Process -FilePath "node" -NoNewWindow -PassThru `
|
||||||
|
-WorkingDirectory (Join-Path $Root "frontend") -ArgumentList "`"$Vite`""
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Konduktor is starting..."
|
||||||
|
Write-Host " -> App: http://localhost:5173"
|
||||||
|
Write-Host " -> API docs: http://localhost:8000/docs"
|
||||||
|
Write-Host " (Ctrl-C to stop both)"
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
try {
|
||||||
|
# If either one dies, stop the other rather than leave half a dev setup.
|
||||||
|
while (-not $Backend.HasExited -and -not $Frontend.HasExited) { Start-Sleep -Milliseconds 500 }
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
# Kill the whole tree: uvicorn --reload runs the server in a child process,
|
||||||
|
# which would otherwise keep :8000 bound after the reloader has gone.
|
||||||
|
foreach ($p in $Backend, $Frontend) {
|
||||||
|
if ($p -and -not $p.HasExited) { & taskkill /PID $p.Id /T /F 2>&1 | Out-Null }
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user