Compare commits

...
Author SHA1 Message Date
patben8 87cbd3720e Fixed STEM analysis not working on Windows 2026-10-13 10:59:22 +02:00
patben8 591f2bc791 Pararellized STEM aac encoding 2026-10-13 10:45:52 +02:00
patben8 ebe30c1128 Fixed analysis not working on windows 2026-10-12 23:49:19 +02:00
patben8 cd1914216f Fixed library options not appearing in windows 2026-10-12 23:26:33 +02:00
patben8 d10b11f8eb Merge pull request #8 from MrPatben8/dev
Fixed Rekordbox exports
2026-10-12 19:12:41 +02:00
patben8 79a8a843c5 Bumped version number 2026-10-12 19:12:09 +02:00
patben8 0204a322ff Fixed and pinned rekordbox exports 2026-10-12 19:10:20 +02:00
25 changed files with 360 additions and 106 deletions

No files matched your search

+12
View File
@@ -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
+25 -10
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
@@ -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-
@@ -1475,14 +1486,18 @@ frontend at `http://localhost:5173`.
1. **`traktor-nml-utils` MUST come from GitHub, not PyPI.** PyPI's `3.1.0` is 1. **`traktor-nml-utils` MUST come from GitHub, not PyPI.** PyPI's `3.1.0` is
stale and **cannot parse Traktor Pro 4 (NML v20)** files — its strict parser stale and **cannot parse Traktor Pro 4 (NML v20)** files — its strict parser
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins the dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins a
GitHub `master` (v4.0.0). Do not "simplify" this to a plain PyPI pin. GitHub commit (v4.0.0). Do not "simplify" this to a plain PyPI pin.
**`pyrekordbox` is now the same situation**: PyPI's latest (0.4.4) has no **`pyrekordbox` is now the same situation**: PyPI's latest (0.4.4) has no
`devicelib_plus`, which is the OneLibrary (`exportLibrary.db`) reader, so `onelibrary` module, which is the OneLibrary (`exportLibrary.db`) reader
`requirements.txt` pins the GitHub master. That upgrade renamed `db6` → (`OneLibrary` class; `devicelib_plus` / `DeviceLibraryPlus` before upstream's
`masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`; rename), nor `masterdb` (formerly `db6`, now removed upstream; `tables` →
the Rekordbox adapter uses the new names. `db6` still works as a deprecated `models`, `BLOB` in `masterdb.database`).
alias and is **removed in 0.6.0**. **Both GitHub deps are pinned to a COMMIT, never bare master**: the
`devicelib_plus` → `onelibrary` rename reached CI's fresh install while dev
venvs kept the old commit, and a release shipped that could not export or
read OneLibrary while every local test passed. Move a pin on purpose, with
`./run_tests.sh`.
**PyAV: open files for reading through `core/pyav.open_input`, never **PyAV: open files for reading through `core/pyav.open_input`, never
`av.open` directly.** PyAV 18 refuses a file with non-UTF-8 tags unless `av.open` directly.** PyAV 18 refuses a file with non-UTF-8 tags unless
given `metadata_errors="ignore"`; PyAV 19 removed that keyword. CI installs given `metadata_errors="ignore"`; PyAV 19 removed that keyword. CI installs
@@ -1814,7 +1829,7 @@ that number and nothing else — everything derives from it:
deliberately NOT in the fixture, since they carry the machine's name and deliberately NOT in the fixture, since they carry the machine's name and
UUIDs; those are generated fresh per export. UUIDs; those are generated fresh per export.
- **The two Pioneer key blobs are different.** `masterdb`'s key and - **The two Pioneer key blobs are different.** `masterdb`'s key and
`devicelib_plus`'s are not the same string; mixing them up yields a database `onelibrary`'s are not the same string; mixing them up yields a database
Rekordbox cannot open. Rekordbox cannot open.
`adapters/onelibrary/export.py` writes a whole drive (`PIONEER/rekordbox/ `adapters/onelibrary/export.py` writes a whole drive (`PIONEER/rekordbox/
exportLibrary.db` from the checked-in DDL, plus ANLZ under `PIONEER/USBANLZ/`, exportLibrary.db` from the checked-in DDL, plus ANLZ under `PIONEER/USBANLZ/`,
+6 -1
View File
@@ -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\"
@@ -49,7 +49,7 @@ class OneLibraryDriver:
def _has_onelibrary_schema(path: Path) -> bool: def _has_onelibrary_schema(path: Path) -> bool:
try: try:
import sqlcipher3.dbapi2 as sqlcipher import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate from pyrekordbox.utils import deobfuscate
except ImportError: # pragma: no cover — dependency missing except ImportError: # pragma: no cover — dependency missing
return False return False
@@ -121,7 +121,7 @@ class OneLibraryExporter:
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary: def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
import sqlcipher3.dbapi2 as sqlcipher import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate from pyrekordbox.utils import deobfuscate
root = Path(destination) root = Path(destination)
@@ -428,8 +428,10 @@ class OneLibraryExporter:
) )
#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them. #: rekordbox's `fileType` codes. `.stem.m4a` (a Traktor STEM) is an M4A to a
#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player. #: Pioneer player. `pyrekordbox.onelibrary.FileType` now also lists MP4 = 3 (the
#: `.mp4` container) and ALAC = 6 (an ALAC `.m4a`); neither is measured here, so
#: both still write 4.
_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11, _FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
".aif": 12, ".aiff": 12} ".aif": 12, ".aiff": 12}
@@ -1,6 +1,6 @@
"""OneLibrary rows -> the generic projection. """OneLibrary rows -> the generic projection.
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` / The only place a ``pyrekordbox.onelibrary`` ORM object becomes a generic `Track` /
`TrackCues`. Everything above this file sees generic types exclusively. `TrackCues`. Everything above this file sees generic types exclusively.
Field conventions are read off a real rekordbox 7 export rather than guessed: Field conventions are read off a real rekordbox 7 export rather than guessed:
+15 -15
View File
@@ -1,7 +1,7 @@
"""The retained native model for a OneLibrary drive. """The retained native model for a OneLibrary drive.
Owns the drive's ``exportLibrary.db`` and the layout around it, and is the only Owns the drive's ``exportLibrary.db`` and the layout around it, and is the only
place a ``pyrekordbox.devicelib_plus`` row or an ANLZ tag is touched. place a ``pyrekordbox.onelibrary`` row or an ANLZ tag is touched.
The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but
with a **different and universal key**: every OneLibrary drive from every vendor with a **different and universal key**: every OneLibrary drive from every vendor
@@ -170,10 +170,10 @@ class OneLibraryStore(ReplaceGridCommands):
def _load(self) -> None: def _load(self) -> None:
"""Copy the drive's database into app-data and open the copy.""" """Copy the drive's database into app-data and open the copy."""
try: try:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus from pyrekordbox.onelibrary import OneLibrary
except ImportError as ex: # pragma: no cover — dependency missing except ImportError as ex: # pragma: no cover — dependency missing
raise LibraryNotSupported( raise LibraryNotSupported(
"Reading OneLibrary drives needs pyrekordbox with devicelib_plus" "Reading OneLibrary drives needs pyrekordbox with its onelibrary module"
) from ex ) from ex
_clear_stale_work() _clear_stale_work()
work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root())) work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root()))
@@ -186,7 +186,7 @@ class OneLibraryStore(ReplaceGridCommands):
sidecar = self.path.with_name(self.path.name + suffix) sidecar = self.path.with_name(self.path.name + suffix)
if sidecar.is_file() and sidecar.stat().st_size: if sidecar.is_file() and sidecar.stat().st_size:
shutil.copyfile(sidecar, working.with_name(working.name + suffix)) shutil.copyfile(sidecar, working.with_name(working.name + suffix))
db = DeviceLibraryPlus(str(working)) db = OneLibrary(str(working))
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
shutil.rmtree(work, ignore_errors=True) shutil.rmtree(work, ignore_errors=True)
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
@@ -206,7 +206,7 @@ class OneLibraryStore(ReplaceGridCommands):
"""Release the working copy and delete it. """Release the working copy and delete it.
The drive itself is never held open (see the module docstring); the copy The drive itself is never held open (see the module docstring); the copy
is, and `DeviceLibraryPlus.close()` only unregisters events, so the is, and `OneLibrary.close()` only unregisters events, so the
session and engine are closed here explicitly. session and engine are closed here explicitly.
""" """
db, self._db = self._db, None db, self._db = self._db, None
@@ -316,7 +316,7 @@ class OneLibraryStore(ReplaceGridCommands):
image_id = getattr(self.content(track_id), "image_id", None) image_id = getattr(self.content(track_id), "image_id", None)
if not image_id: if not image_id:
return None return None
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none() row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none()
small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None
@@ -456,7 +456,7 @@ class OneLibraryStore(ReplaceGridCommands):
""" """
if not name: if not name:
return None return None
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
model = getattr(models, model_name) model = getattr(models, model_name)
pk = f"{model.__tablename__}_id" pk = f"{model.__tablename__}_id"
@@ -497,7 +497,7 @@ class OneLibraryStore(ReplaceGridCommands):
stick already has. A new key gets rekordbox's own spelling.""" stick already has. A new key gets rekordbox's own spelling."""
if wheel is None or mode is None: if wheel is None or mode is None:
return None return None
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
from ..rekordbox.projection import parse_key, render_key from ..rekordbox.projection import parse_key, render_key
@@ -567,7 +567,7 @@ class OneLibraryStore(ReplaceGridCommands):
# ---- writes: playlists -------------------------------------------------- # ---- writes: playlists --------------------------------------------------
def _playlist(self, node_id: str): def _playlist(self, node_id: str):
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
try: try:
pid = int(node_id) pid = int(node_id)
@@ -579,14 +579,14 @@ class OneLibraryStore(ReplaceGridCommands):
return row return row
def _siblings(self, parent_id: int, *, excluding: int | None = None) -> list: def _siblings(self, parent_id: int, *, excluding: int | None = None) -> list:
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
rows = self._require_db().query(models.Playlist).filter_by(playlist_id_parent=parent_id).all() rows = self._require_db().query(models.Playlist).filter_by(playlist_id_parent=parent_id).all()
rows = [r for r in rows if r.playlist_id != excluding] rows = [r for r in rows if r.playlist_id != excluding]
return sorted(rows, key=lambda r: (int(r.sequenceNo or 0), int(r.playlist_id))) return sorted(rows, key=lambda r: (int(r.sequenceNo or 0), int(r.playlist_id)))
def _create_node(self, name: str, parent_id: str | None, attribute: int) -> str: def _create_node(self, name: str, parent_id: str | None, attribute: int) -> str:
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
name = (name or "").strip() name = (name or "").strip()
noun = "folder" if attribute == ATTRIBUTE_FOLDER else "playlist" noun = "folder" if attribute == ATTRIBUTE_FOLDER else "playlist"
@@ -631,7 +631,7 @@ class OneLibraryStore(ReplaceGridCommands):
def delete_playlist(self, node_id: str) -> None: def delete_playlist(self, node_id: str) -> None:
"""Delete a playlist, or a folder WITH everything in it, and close the gap """Delete a playlist, or a folder WITH everything in it, and close the gap
its `sequenceNo` leaves among its siblings.""" its `sequenceNo` leaves among its siblings."""
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
db = self._require_db() db = self._require_db()
row = self._playlist(node_id) row = self._playlist(node_id)
@@ -693,7 +693,7 @@ class OneLibraryStore(ReplaceGridCommands):
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in order, numbered from 1 (measured).""" """Replace a playlist's contents, in order, numbered from 1 (measured)."""
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
db = self._require_db() db = self._require_db()
playlist = self._playlist(node_id) playlist = self._playlist(node_id)
@@ -1378,9 +1378,9 @@ class OneLibraryStore(ReplaceGridCommands):
return SaveOutcome(summary=summary, snapshot=None, tag_results=tag_results) return SaveOutcome(summary=summary, snapshot=None, tag_results=tag_results)
def _reopen_working(self, work: Path) -> None: def _reopen_working(self, work: Path) -> None:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus from pyrekordbox.onelibrary import OneLibrary
self._db, self._work = DeviceLibraryPlus(str(work / self.path.name)), work self._db, self._work = OneLibrary(str(work / self.path.name)), work
self._content_cache = None self._content_cache = None
self._by_id = None self._by_id = None
@@ -125,7 +125,7 @@ class RekordboxExporter:
) )
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary: def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
# `masterdb`'s OWN key blob. `devicelib_plus` has a different one — a # `masterdb`'s OWN key blob. `onelibrary` has a different one — a
# OneLibrary drive uses a universal key shared across vendors, and # OneLibrary drive uses a universal key shared across vendors, and
# master.db does not. Mixing them up produces a database Rekordbox # master.db does not. Mixing them up produces a database Rekordbox
# cannot open, and pyrekordbox rejects the wrong one outright. # cannot open, and pyrekordbox rejects the wrong one outright.
+2 -2
View File
@@ -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:
+2 -2
View File
@@ -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)
+86 -19
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)):
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)
+2 -2
View File
@@ -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)
+17 -9
View File
@@ -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
+7 -3
View File
@@ -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:
+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
+2 -2
View File
@@ -14,5 +14,5 @@ Pillow>=11 # a Rekordbox add writes the cover's artwork files
dulwich>=0.22 # version history, beside the library dulwich>=0.22 # version history, beside the library
platformdirs>=4.0 platformdirs>=4.0
# From GitHub, NOT PyPI — see requirements.txt for why. # From GitHub, NOT PyPI — see requirements.txt for why.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@39a9c15f29d6b0ea2ce61cd7d548501eea38319d
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git@43137cb91f8297c768d2a8bdce5b27b2225f0a2d
+12 -9
View File
@@ -18,19 +18,22 @@ librosa>=0.11
scikit-learn>=1.5 scikit-learn>=1.5
# Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0), # Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0),
# NOT the stale PyPI release (3.1.0), which cannot parse v4 files. # NOT the stale PyPI release (3.1.0), which cannot parse v4 files.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git #
# Both GitHub dependencies are PINNED TO A COMMIT. Unpinned, a fresh install
# (CI's release build) takes whatever master is that day while a dev venv keeps
# what it had: pyrekordbox renamed `devicelib_plus` to `onelibrary` upstream,
# every local test passed, and the released app could not export or read a
# OneLibrary stick. Move a pin deliberately, with ./run_tests.sh.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@39a9c15f29d6b0ea2ce61cd7d548501eea38319d
# Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis # Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis
# files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build. # files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build.
# #
# FROM GITHUB, NOT PyPI — the same situation as traktor-nml-utils above, and for # FROM GITHUB, NOT PyPI — the same situation as traktor-nml-utils above, and for
# the same kind of reason. PyPI's latest (0.4.4) has no `devicelib_plus`, which # the same kind of reason. PyPI's latest (0.4.4) has no `onelibrary` module
# is the OneLibrary (`exportLibrary.db`) reader the OneLibrary adapter is built # (`exportLibrary.db`, which the OneLibrary adapter is built on; it was called
# on; it exists only on master. Do not "simplify" this back to a version pin. # `devicelib_plus` before the rename) and no `masterdb` (formerly `db6`, now
# # removed). Do not "simplify" this back to a version pin.
# The upgrade also renames `db6` to `masterdb`. `db6` still works as a pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git@43137cb91f8297c768d2a8bdce5b27b2225f0a2d
# deprecated alias and is removed in 0.6.0, so the Rekordbox adapter keeps
# running as-is — but that rename is the thing to fix before taking 0.6.
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
# The stem engine and its weights are downloaded over HTTPS by the sidecar; a # The stem engine and its weights are downloaded over HTTPS by the sidecar; a
# frozen Python on macOS has no system CA bundle of its own. # frozen Python on macOS has no system CA bundle of its own.
certifi>=2024.7 certifi>=2024.7
+26 -4
View File
@@ -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
+1 -1
View File
@@ -504,7 +504,7 @@ print("\n== content.contentLink is what rekordbox writes ==")
# row's song-list preview plain blue and put a "?" beside CUE — exactly what # row's song-list preview plain blue and put a "?" beside CUE — exactly what
# every row of Konduktor's exports showed while it was NULL. # every row of Konduktor's exports showed while it was NULL.
import sqlcipher3.dbapi2 as _sq # noqa: E402 import sqlcipher3.dbapi2 as _sq # noqa: E402
from pyrekordbox.devicelib_plus.database import BLOB as _BLOB # noqa: E402 from pyrekordbox.onelibrary.database import BLOB as _BLOB # noqa: E402
from pyrekordbox.utils import deobfuscate as _deob # noqa: E402 from pyrekordbox.utils import deobfuscate as _deob # noqa: E402
_con = _sq.connect(str(art_written.library)) _con = _sq.connect(str(art_written.library))
+1 -1
View File
@@ -60,7 +60,7 @@ def dump(db: Path) -> dict:
"""Every row of every table; keyed by primary key, or by the whole row for """Every row of every table; keyed by primary key, or by the whole row for
the link tables, which have none.""" the link tables, which have none."""
import sqlcipher3.dbapi2 as sqlcipher import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(db)) con = sqlcipher.connect(str(db))
+1 -1
View File
@@ -65,7 +65,7 @@ def fingerprint(root: Path) -> str:
def rows(root: Path, sql: str): def rows(root: Path, sql: str):
import sqlcipher3.dbapi2 as sqlcipher import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(root / "PIONEER" / "rekordbox" / "exportLibrary.db")) con = sqlcipher.connect(str(root / "PIONEER" / "rekordbox" / "exportLibrary.db"))
+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)
+42
View File
@@ -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 }
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "frontend", "name": "frontend",
"private": true, "private": true,
"version": "0.2.5", "version": "0.2.6",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",