mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented STEM playback
This commit is contained in:
1 parent
ae03a93f98
commit
ecc0e4c8df
13 files changed
+775
-61
No files matched your search
@@ -381,6 +381,17 @@ Two independent apps that talk over HTTP:
|
||||
relocation, import, folder add, history restore and reload answer 409
|
||||
(`_require_no_pending_stems`): each would save or drop the swap.
|
||||
`/api/state` reports `pending_stems`, `stem_job`, `stem_recovery`.
|
||||
**`stream_cache.py` — stem PLAYBACK.** A browser decodes only an MP4's
|
||||
FIRST audio stream (the mix), so each stem is served as a file of its own:
|
||||
the three audio routes (collection / `source` / `folder`) take
|
||||
`?stem=0..3`, and `/api/…/tracks/stems` report `[{name, color}]` read from
|
||||
the FILE (`stem_file.stem_layout`: the box, and enough streams — never the
|
||||
library's `<STEMS>`, which plain MP3s carry). `stem_file.extract_stream`
|
||||
COPIES packets into an `ipod` MP4 — measured bit-identical to decoding the
|
||||
stream in place, edit list and priming (1024 / 2112) intact, on commercial
|
||||
stems too, so stems stay sample-locked to the mix and the cues. Cached in
|
||||
app-data keyed by path + size + mtime, LRU under 2 GB, written partial →
|
||||
rename; ~0.1 s per stem uncached.
|
||||
- `app_state.py` — the one loaded library, and the **version-history commit**.
|
||||
**`discard()`** (`POST /api/discard`, SaveBar's "Discard changes…", the
|
||||
quit prompt's Discard) drops every unsaved edit through the adapter's own
|
||||
@@ -645,6 +656,24 @@ Two independent apps that talk over HTTP:
|
||||
browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open`
|
||||
outside Tauri; "Skip this version" persists `skippedUpdateVersion` to
|
||||
userprefs via `/api/prefs`; all failures are silent).
|
||||
- **Stem playback** (decided 2026-09-30): a stem FILE always loads its four
|
||||
stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays
|
||||
their SUM, as Traktor's stem deck does — the mix stream is never decoded,
|
||||
which also saves a full-length buffer. `PlaybackEngine.load` takes several
|
||||
buffers: one source + gain each, all started at ONE scheduled context
|
||||
time (so they stay sample-locked through seeks and loops), mute/solo as
|
||||
ramped gains, never a restart. `ScratchEngine.loadStems` keeps ONE summed
|
||||
copy of the audible stems (not four), re-summed in slices on a mute change.
|
||||
`analyzeStems` returns the overview's three-band columns (of the sum) plus
|
||||
one amplitude lane per stem, each normalised to its own 99.5th percentile
|
||||
but never below 5% of the loudest (a silent stem stays silent).
|
||||
`MainWaveform` draws the lanes in the file's own colours with a mute
|
||||
button at each lane's left edge (click = mute, Alt/Option-click = solo);
|
||||
Q W E R mute stems 1-4, Shift+ solos. **Solo is not a mode**: it SETS the
|
||||
mutes (every other stem muted), so each stem stays freely mutable after
|
||||
it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is
|
||||
the cost: ~140 MB per stem for 6 minutes, i.e. the same four buffers as
|
||||
the file holds streams, and no more.
|
||||
- **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it,
|
||||
in three rows. **Header**: cover, title/artist · album · genre, a Read-only
|
||||
badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` —
|
||||
@@ -809,6 +838,12 @@ serialization path.** It enforces:
|
||||
one bad track fails alone; destination+add mirrors into a new playlist;
|
||||
crash recovery restores (or finishes a committed save) and a re-run REUSES
|
||||
the kept stem files without calling the engine.
|
||||
- `test_stem_playback.py` — stem playback's backend half on a generated stem
|
||||
file (fake stems = distinct scalings of the mix): the layout is read from
|
||||
the FILE (an MP3 whose entry carries `<STEMS>` has none); each served stem
|
||||
is its own MP4, bit-identical to that stream in place and the RIGHT stem;
|
||||
out-of-range / non-stem requests 404; the cache reuses, follows an edited
|
||||
file, evicts LRU but never what it just wrote; the folder origin serves too.
|
||||
- `test_traktor_adapter.py` — the **generic layer**: one parse per open, the
|
||||
projection refreshing after every command family, cue-type translation,
|
||||
capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity`
|
||||
|
||||
@@ -347,8 +347,62 @@ def is_stem_file(path: Path | str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def stem_layout(path: Path | str) -> list[dict] | None:
|
||||
"""The stems a file carries, for PLAYBACK: `[{"name", "color"}]` in stream
|
||||
order (stream k+1 is stem k), or None when the file is not a playable stem
|
||||
file — no `stem` box, a box that does not parse, or fewer audio streams than
|
||||
it names. Read from the FILE, never from the library's `<STEMS>`: 105 plain
|
||||
MP3 entries in the real collection carry that element."""
|
||||
import json
|
||||
|
||||
import av
|
||||
|
||||
path = Path(path)
|
||||
try:
|
||||
raw = read_stem_box(path)
|
||||
if raw is None:
|
||||
return None
|
||||
stems = json.loads(raw).get("stems") or []
|
||||
with av.open(str(path), metadata_errors="ignore") as c:
|
||||
streams = len(c.streams.audio)
|
||||
except (OSError, ValueError, av.FFmpegError):
|
||||
return None
|
||||
if not stems or streams < 1 + len(stems):
|
||||
return None
|
||||
return [{"name": str(s.get("name") or f"Stem {i + 1}"), "color": str(s.get("color") or "#FFFFFF")}
|
||||
for i, s in enumerate(stems)]
|
||||
|
||||
|
||||
def extract_stream(path: Path | str, stream: int, fp) -> None:
|
||||
"""Copy audio stream `stream` (0 = the mix, 1-4 the stems) into its own MP4,
|
||||
written to the file object `fp` — packets COPIED, never re-encoded.
|
||||
|
||||
A browser decodes only an MP4's first audio stream, so this is how the deck
|
||||
gets at the stems. Measured bit-identical to decoding the stream in place,
|
||||
with the edit list (and so the priming: 1024 for FFmpeg's encoder, 2112 for
|
||||
Apple's) carried across — on Konduktor's files and commercial ones alike, so
|
||||
every stem stays sample-locked to the mix and to the cue timeline.
|
||||
"""
|
||||
import av
|
||||
|
||||
with av.open(str(path), metadata_errors="ignore") as inp:
|
||||
if not 0 <= stream < len(inp.streams.audio):
|
||||
raise StemFileError(f"The file has no audio stream {stream}")
|
||||
ist = inp.streams.audio[stream]
|
||||
out = av.open(fp, "w", format="ipod")
|
||||
try:
|
||||
ost = out.add_stream_from_template(ist)
|
||||
for pkt in inp.demux(ist):
|
||||
if pkt.dts is None:
|
||||
continue # the demuxer's end-of-stream flush packet
|
||||
pkt.stream = ost
|
||||
out.mux(pkt)
|
||||
finally:
|
||||
out.close()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DEMUCS_ORDER", "NML_STEMS_JSON", "SR", "STEM_BOX_JSON", "STEM_NAMES", "Source",
|
||||
"StemFileError", "Written", "add_stem_box", "build", "choose_bitrate", "decode",
|
||||
"default_encoder", "is_stem_file", "read_stem_box", "stem_target_name", "verify",
|
||||
"default_encoder", "extract_stream", "is_stem_file", "read_stem_box", "stem_layout", "stem_target_name", "verify",
|
||||
]
|
||||
@@ -1080,14 +1080,47 @@ _AUDIO_MIME = {
|
||||
}
|
||||
|
||||
|
||||
def _stem_audio(path: Path, stem: int) -> FileResponse:
|
||||
"""One stem of a stem file as a file of its own (see stems/stream_cache.py):
|
||||
a browser only ever decodes an MP4's first stream, which is the mix."""
|
||||
from .core import stem_file
|
||||
from .stems import stream_cache
|
||||
|
||||
layout = stem_file.stem_layout(path)
|
||||
if layout is None or not 0 <= stem < len(layout):
|
||||
raise HTTPException(404, "That file has no such stem")
|
||||
try:
|
||||
return FileResponse(stream_cache.stem_file_for(path, stem), media_type="audio/mp4")
|
||||
except (stem_file.StemFileError, OSError) as ex:
|
||||
raise HTTPException(500, f"Could not read the stem: {ex}")
|
||||
|
||||
|
||||
def _stem_layout_of(path: Path | None) -> dict:
|
||||
from .core import stem_file
|
||||
|
||||
if path is None or not path.exists():
|
||||
raise HTTPException(404, "Audio file not found")
|
||||
return {"stems": stem_file.stem_layout(path) or []}
|
||||
|
||||
|
||||
@app.get("/api/tracks/stems")
|
||||
def track_stems(track_id: str) -> dict:
|
||||
"""The stems a track's FILE carries for playback — `[{name, color}]`, empty
|
||||
for anything that is not a stem file (whatever the library says)."""
|
||||
return _stem_layout_of(require_adapter().audio_path(track_id))
|
||||
|
||||
|
||||
@app.get("/api/tracks/audio")
|
||||
def track_audio(track_id: str) -> FileResponse:
|
||||
"""Stream a track's audio file for playback (supports HTTP Range/seeking)."""
|
||||
def track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
"""Stream a track's audio file for playback (supports HTTP Range/seeking);
|
||||
with `stem`, that stem of a stem file (0-based) instead."""
|
||||
path = require_adapter().audio_path(track_id)
|
||||
if path is None:
|
||||
raise HTTPException(404, "Track not found")
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"Audio file not found: {path}")
|
||||
if stem is not None:
|
||||
return _stem_audio(path, stem)
|
||||
# .stem.m4a and other MP4s serve as audio/mp4; browsers play the first track.
|
||||
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
|
||||
# Cacheable so the waveform's decode-fetch and the <audio> element can share
|
||||
@@ -1705,7 +1738,7 @@ def source_track_cues(track_id: str) -> TrackCues:
|
||||
|
||||
|
||||
@app.get("/api/source/tracks/audio")
|
||||
def source_track_audio(track_id: str) -> FileResponse:
|
||||
def source_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
"""Stream a track's audio straight off the source drive.
|
||||
|
||||
So the deck can audition a track BEFORE importing it, which is most of the
|
||||
@@ -1717,10 +1750,17 @@ def source_track_audio(track_id: str) -> FileResponse:
|
||||
raise HTTPException(404, "Track not found")
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"Audio file not found: {path}")
|
||||
if stem is not None:
|
||||
return _stem_audio(path, stem)
|
||||
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
|
||||
return FileResponse(path, media_type=mime)
|
||||
|
||||
|
||||
@app.get("/api/source/tracks/stems")
|
||||
def source_track_stems(track_id: str) -> dict:
|
||||
return _stem_layout_of(require_source().audio_path(track_id))
|
||||
|
||||
|
||||
# ---- drives and folders -----------------------------------------------
|
||||
#
|
||||
# The sidebar's Devices and Local Storage trees. Browsing a folder is READ-ONLY
|
||||
@@ -1820,14 +1860,21 @@ def folder_track_cues(track_id: str) -> TrackCues:
|
||||
|
||||
|
||||
@app.get("/api/folder/tracks/audio")
|
||||
def folder_track_audio(track_id: str) -> FileResponse:
|
||||
def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
path = _folder_track(track_id).audio_path(track_id)
|
||||
if path is None or not path.is_file():
|
||||
raise HTTPException(404, "Audio file not found")
|
||||
if stem is not None:
|
||||
return _stem_audio(path, stem)
|
||||
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
|
||||
return FileResponse(path, media_type=mime)
|
||||
|
||||
|
||||
@app.get("/api/folder/tracks/stems")
|
||||
def folder_track_stems(track_id: str) -> dict:
|
||||
return _stem_layout_of(_folder_track(track_id).audio_path(track_id))
|
||||
|
||||
|
||||
def _folder_add_plan(body: FolderAddRequest):
|
||||
dest = require_adapter()
|
||||
tracks = []
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""The deck's stem audio: one stream of a stem file, as a file of its own.
|
||||
|
||||
A browser decodes only the FIRST audio stream of an MP4, so the deck cannot get
|
||||
at a stem file's stems from the file itself. Each is copied out (packets, not
|
||||
re-encoded — `stem_file.extract_stream`) into a small cache in app-data, keyed
|
||||
by the source's path, size and mtime, so an edited or replaced file is never
|
||||
served stale and loading the same track twice costs nothing the second time.
|
||||
|
||||
The cache is bounded (`LIMIT` bytes, least recently used first) — a stem is
|
||||
2-10 MB, so the limit holds a few hundred tracks' worth. Files are written as a
|
||||
partial then renamed, so two requests racing for the same stem, or a crash
|
||||
mid-write, can never serve a truncated file.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from .. import paths
|
||||
from ..core import stem_file
|
||||
|
||||
LIMIT = 2 * 1024 ** 3
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def root() -> Path:
|
||||
d = paths.app_data_dir() / "stems" / "playback"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def _key(path: Path, stream: int) -> str:
|
||||
st = path.stat()
|
||||
raw = f"{path.resolve()}\0{st.st_size}\0{st.st_mtime_ns}\0{stream}".encode()
|
||||
return hashlib.sha256(raw).hexdigest()[:32]
|
||||
|
||||
|
||||
def stem_file_for(path: Path, stem: int) -> Path:
|
||||
"""The cached single-stream file for stem `stem` (0-based: stream stem+1)."""
|
||||
path = Path(path)
|
||||
stream = stem + 1
|
||||
target = root() / f"{_key(path, stream)}.m4a"
|
||||
if target.exists():
|
||||
os.utime(target) # most recently used
|
||||
return target
|
||||
partial = target.with_name(f"{target.name}.{os.getpid()}.{threading.get_ident()}.part")
|
||||
try:
|
||||
with open(partial, "wb") as fp:
|
||||
stem_file.extract_stream(path, stream, fp)
|
||||
os.replace(partial, target)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
_prune(keep=target)
|
||||
return target
|
||||
|
||||
|
||||
def _prune(keep: Path) -> None:
|
||||
with _lock:
|
||||
files = []
|
||||
for p in root().glob("*.m4a"):
|
||||
try:
|
||||
st = p.stat()
|
||||
except OSError:
|
||||
continue
|
||||
files.append((st.st_mtime, st.st_size, p))
|
||||
total = sum(size for _, size, _ in files)
|
||||
for _, size, p in sorted(files):
|
||||
if total <= LIMIT:
|
||||
break
|
||||
if p == keep:
|
||||
continue
|
||||
p.unlink(missing_ok=True)
|
||||
total -= size
|
||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||
source .venv/bin/activate
|
||||
|
||||
fail=0
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Stem playback on the deck — the backend half: a stem file's stems served one
|
||||
by one, because a browser decodes only an MP4's first audio stream (the mix).
|
||||
|
||||
Pins what would fail silently:
|
||||
* a served stem is BIT-IDENTICAL to decoding that stream in place, edit list
|
||||
and all — a stem shifted by its priming would flam against the others and
|
||||
sit off every cue;
|
||||
* "is this a stem file" is read from the FILE: an MP3 whose collection entry
|
||||
carries `<STEMS>` (105 real ones do) has no stems to play;
|
||||
* the cache follows the file (an edited file is not served stale) and stays
|
||||
within its limit without evicting what it just wrote;
|
||||
* all three origins (collection, device, folder) serve them.
|
||||
|
||||
Everything is generated: a stem file built with a FAKE separator whose four
|
||||
stems are distinct scalings of the mix, so each served stem can be told apart.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-stemplay-appdata-")
|
||||
|
||||
import av # noqa: E402
|
||||
import numpy as np # noqa: E402
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import konduktor.main as main # noqa: E402
|
||||
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
|
||||
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
|
||||
from konduktor.core import stem_file as sf # noqa: E402
|
||||
from konduktor.stems import stream_cache # noqa: E402
|
||||
from stem_test_support import make_mp3 # noqa: E402
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
def decode(path: Path, stream: int = 0) -> np.ndarray:
|
||||
with av.open(str(path)) as c:
|
||||
return np.concatenate([f.to_ndarray() for f in c.decode(c.streams.audio[stream])], axis=1)
|
||||
|
||||
|
||||
GAINS = (0.5, 0.25, -0.2, 0.1)
|
||||
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-stemplay-"))
|
||||
music = ROOT / "Music"
|
||||
music.mkdir()
|
||||
stem = music / "Tune.stem.m4a"
|
||||
sf.build(make_mp3(ROOT / "src.mp3", seconds=6), stem, lambda p: [p * g for g in GAINS])
|
||||
plain = make_mp3(music / "Plain.mp3", seed=7)
|
||||
tagged = make_mp3(music / "Tagged.mp3", seed=8) # its ENTRY will carry <STEMS>
|
||||
|
||||
print("== stem_file: what a file carries ==")
|
||||
layout = sf.stem_layout(stem)
|
||||
check("a stem file lists its four stems with names and colours, in stream order",
|
||||
[s["name"] for s in layout or []] == ["Drums", "Bass", "Synths", "Vox"]
|
||||
and all(s["color"].startswith("#") for s in layout), str(layout))
|
||||
check("a plain MP3 has none", sf.stem_layout(plain) is None)
|
||||
check("a missing file has none (no exception)", sf.stem_layout(ROOT / "nope.stem.m4a") is None)
|
||||
|
||||
print("== a temp collection pointing at them ==")
|
||||
work = ROOT / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
st = TraktorStore(work)
|
||||
entries = [e for e in st._nml.collection.entry if e.location][:3]
|
||||
ids = []
|
||||
for e, path in zip(entries, (stem, plain, tagged)):
|
||||
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
|
||||
ids.append(st._key_of(e))
|
||||
from traktor_nml_utils.models.collection import Stemstype # noqa: E402
|
||||
|
||||
entries[2].stems = Stemstype(stems=sf.NML_STEMS_JSON)
|
||||
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
|
||||
st.save()
|
||||
stem_id, plain_id, tagged_id = ids
|
||||
|
||||
with TestClient(main.app) as c:
|
||||
assert c.post("/api/library/open", json={"path": str(work)}).status_code == 200
|
||||
print("== the collection routes ==")
|
||||
r = c.get("/api/tracks/stems", params={"track_id": stem_id}).json()
|
||||
check("/api/tracks/stems lists the stem file's stems", r["stems"] == layout, str(r))
|
||||
check("…none for a plain MP3", c.get("/api/tracks/stems", params={"track_id": plain_id}).json()["stems"] == [])
|
||||
tagged_track = c.get("/api/tracks", params={"limit": 20000}).json()
|
||||
tagged_kind = next((t["media_kind"] for t in tagged_track["items"] if t["id"] == tagged_id), None) \
|
||||
if isinstance(tagged_track, dict) and "items" in tagged_track else None
|
||||
check("…and none for an MP3 the COLLECTION calls a stem track (decided by the file)",
|
||||
c.get("/api/tracks/stems", params={"track_id": tagged_id}).json()["stems"] == [],
|
||||
f"media_kind={tagged_kind}")
|
||||
|
||||
mix = decode(stem, 0)
|
||||
for k in range(4):
|
||||
r = c.get("/api/tracks/audio", params={"track_id": stem_id, "stem": k})
|
||||
ok = r.status_code == 200 and r.headers["content-type"].startswith("audio/mp4")
|
||||
got = ROOT / f"served-{k}.m4a"
|
||||
got.write_bytes(r.content if ok else b"")
|
||||
same = ok and np.array_equal(decode(got), decode(stem, k + 1))
|
||||
check(f"stem {k} is served as its own MP4, bit-identical to stream {k + 1} in place", same)
|
||||
if same:
|
||||
s = decode(got)
|
||||
n = min(s.shape[1], mix.shape[1])
|
||||
# The fake stems are the mix scaled: the right stream, not just A stream.
|
||||
ratio = float(np.dot(s[0, :n], mix[0, :n]) / np.dot(mix[0, :n], mix[0, :n]))
|
||||
check(f"…and it is stem {k} (gain {GAINS[k]:+.2f}, measured {ratio:+.2f}), same length as the mix",
|
||||
abs(ratio - GAINS[k]) < 0.05 and s.shape[1] == mix.shape[1], f"{ratio} {s.shape} {mix.shape}")
|
||||
check("the plain audio route still serves the whole file",
|
||||
c.get("/api/tracks/audio", params={"track_id": stem_id}).content == stem.read_bytes())
|
||||
check("a stem out of range is 404",
|
||||
c.get("/api/tracks/audio", params={"track_id": stem_id, "stem": 4}).status_code == 404)
|
||||
check("asking a plain MP3 for a stem is 404",
|
||||
c.get("/api/tracks/audio", params={"track_id": plain_id, "stem": 0}).status_code == 404)
|
||||
|
||||
print("== the cache ==")
|
||||
cached = stream_cache.stem_file_for(stem, 0)
|
||||
check("a second request reuses the cached file", stream_cache.stem_file_for(stem, 0) == cached)
|
||||
st_ = stem.stat()
|
||||
os.utime(stem, ns=(st_.st_atime_ns, st_.st_mtime_ns + 10_000_000_000))
|
||||
check("an edited source gets a fresh file, never the stale one", stream_cache.stem_file_for(stem, 0) != cached)
|
||||
before = sorted(stream_cache.root().glob("*.m4a"))
|
||||
stream_cache.LIMIT = 1 # everything is over the limit now
|
||||
newest = stream_cache.stem_file_for(stem, 3)
|
||||
after = sorted(stream_cache.root().glob("*.m4a"))
|
||||
check("over its limit the cache evicts the least recently used…", len(before) >= 2 and after == [newest],
|
||||
f"{len(before)} -> {[p.name for p in after]}")
|
||||
check("…but never the file it just wrote", newest.exists() and newest in after)
|
||||
check("no partial file is left behind", not list(stream_cache.root().glob("*.part")))
|
||||
stream_cache.LIMIT = 2 * 1024 ** 3
|
||||
|
||||
print("== the folder origin ==")
|
||||
listing = c.get("/api/folder/tracks", params={"path": str(music)})
|
||||
check("(setup) the folder lists", listing.status_code == 200, listing.text[:200])
|
||||
fid = str(stem)
|
||||
r = c.get("/api/folder/tracks/stems", params={"track_id": fid})
|
||||
check("a stem file browsed in a folder lists its stems", r.status_code == 200 and r.json()["stems"] == layout,
|
||||
r.text[:200])
|
||||
r = c.get("/api/folder/tracks/audio", params={"track_id": fid, "stem": 1})
|
||||
got = ROOT / "folder-1.m4a"
|
||||
got.write_bytes(r.content)
|
||||
check("…and serves them", r.status_code == 200 and np.array_equal(decode(got), decode(stem, 2)))
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -1008,6 +1008,27 @@ export function trackAudioUrl(origin: TrackOrigin, trackId: string): string {
|
||||
return api.audioUrl(trackId)
|
||||
}
|
||||
|
||||
/** One stem a stem file carries, in stream order (stem k = stream k+1). */
|
||||
export interface StemInfo {
|
||||
name: string
|
||||
/** "#RRGGBB", as the file names it. */
|
||||
color: string
|
||||
}
|
||||
|
||||
/** The stems the track's FILE carries — empty for anything that is not a
|
||||
* playable stem file, whatever the library says about it. */
|
||||
export async function trackStemsFor(origin: TrackOrigin, trackId: string): Promise<StemInfo[]> {
|
||||
const base = origin === 'device' ? '/api/source/tracks/stems' : origin === 'folder' ? '/api/folder/tracks/stems' : '/api/tracks/stems'
|
||||
const res = await getJSON<{ stems: StemInfo[] }>(`${base}?track_id=${encodeURIComponent(trackId)}`)
|
||||
return res.stems
|
||||
}
|
||||
|
||||
/** Stem `k` (0-based) of a stem file, served as a file of its own: a browser
|
||||
* decodes only an MP4's first audio stream, which is the mix. */
|
||||
export function trackStemUrl(origin: TrackOrigin, trackId: string, k: number): string {
|
||||
return `${trackAudioUrl(origin, trackId)}&stem=${k}`
|
||||
}
|
||||
|
||||
export function trackCuesFor(origin: TrackOrigin, trackId: string): Promise<TrackCues> {
|
||||
if (origin === 'device') return api.sourceTrackCues(trackId)
|
||||
if (origin === 'folder') return api.folderTrackCues(trackId)
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useRef } from 'react'
|
||||
import type { CuePoint } from '../api'
|
||||
import type { BeatGrid } from '../lib/beatgrid'
|
||||
import { drawBeatgrid, drawCuePoint, drawCues, drawLoop, drawLoopIn, drawPlayhead } from '../lib/cues'
|
||||
import { paintWave, type WaveColumn } from '../lib/waveform'
|
||||
import { paintLane, paintWave, type WaveColumn } from '../lib/waveform'
|
||||
|
||||
interface Props {
|
||||
cols: WaveColumn[]
|
||||
@@ -28,8 +28,26 @@ interface Props {
|
||||
onScratchStart: () => void
|
||||
onScratchMove: (t: number) => void
|
||||
onScratchEnd: (t: number) => void
|
||||
/** A stem track: one lane per stem instead of the three-band mix view. */
|
||||
lanes?: StemLane[] | null
|
||||
/** Click = mute toggle; Alt/Option-click = solo (mute all the others). */
|
||||
onStemToggle?: (index: number, solo: boolean) => void
|
||||
}
|
||||
|
||||
export interface StemLane {
|
||||
data: Float32Array
|
||||
name: string
|
||||
color: string
|
||||
/** Not muted. */
|
||||
audible: boolean
|
||||
/** The only stem playing (drawn with a ring). */
|
||||
solo: boolean
|
||||
/** Its keyboard shortcut, for the tooltip ("Q"). */
|
||||
shortcut: string
|
||||
}
|
||||
|
||||
const ALT = typeof navigator !== 'undefined' && /Mac/.test(navigator.platform) ? 'Option' : 'Alt'
|
||||
|
||||
const DRAG_THRESHOLD = 3 // px before a press becomes a scratch (vs a click-seek)
|
||||
|
||||
export const MIN_SEC = 2 // most zoomed-in (seconds across the view)
|
||||
@@ -60,6 +78,8 @@ export function MainWaveform({
|
||||
onScratchStart,
|
||||
onScratchMove,
|
||||
onScratchEnd,
|
||||
lanes = null,
|
||||
onStemToggle,
|
||||
}: Props) {
|
||||
const wrapRef = useRef<HTMLDivElement>(null)
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
@@ -90,10 +110,19 @@ export function MainWaveform({
|
||||
const endSec = currentTime + half
|
||||
// 2 px bars with a 1 px gap: the texture that makes the scrolling view
|
||||
// read as discrete energy rather than a smear.
|
||||
paintWave(ctx, cols, w, h, startSec / duration, endSec / duration, {
|
||||
bar: Math.max(1, Math.round(2 * dpr)),
|
||||
gap: Math.max(1, Math.round(dpr)),
|
||||
})
|
||||
const bars = { bar: Math.max(1, Math.round(2 * dpr)), gap: Math.max(1, Math.round(dpr)) }
|
||||
if (lanes && lanes.length) {
|
||||
// Stem lanes, Traktor-style: each stem its own strip in its own colour.
|
||||
const laneH = h / lanes.length
|
||||
lanes.forEach((lane, k) => {
|
||||
paintLane(ctx, lane.data, lane.color, w, k * laneH, laneH, startSec / duration, endSec / duration, bars,
|
||||
!lane.audible)
|
||||
})
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.06)'
|
||||
for (let k = 1; k < lanes.length; k++) ctx.fillRect(0, Math.round(k * laneH), w, Math.max(1, Math.round(dpr)))
|
||||
} else {
|
||||
paintWave(ctx, cols, w, h, startSec / duration, endSec / duration, bars)
|
||||
}
|
||||
|
||||
const timeToX = (t: number) => ((t - startSec) / secPerView) * w
|
||||
// Loop band (under the grid/cues), then beatgrid, then cue markers.
|
||||
@@ -208,6 +237,32 @@ export function MainWaveform({
|
||||
>
|
||||
<canvas ref={canvasRef} className="block h-full w-full" />
|
||||
|
||||
{/* One mute button per stem lane, at its left edge. stopPropagation on
|
||||
down, like the zoom buttons, so a click never starts a scratch. */}
|
||||
{lanes && lanes.length > 0 && (
|
||||
<div className="absolute inset-y-0 left-1.5 flex flex-col">
|
||||
{lanes.map((lane, k) => (
|
||||
<div key={k} className="flex flex-1 items-center">
|
||||
<button
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onClick={(e) => onStemToggle?.(k, e.altKey)}
|
||||
title={`${lane.name} — click to mute, ${ALT}-click to mute all the others (${lane.shortcut})`}
|
||||
aria-pressed={lane.audible}
|
||||
className={`flex h-5 min-w-5 items-center justify-center rounded-md px-1 font-mono text-[10px] font-semibold backdrop-blur-md transition-opacity ${
|
||||
lane.audible ? '' : 'opacity-40'
|
||||
} ${lane.solo ? 'ring-1 ring-white/80' : ''}`}
|
||||
style={{
|
||||
color: lane.audible ? '#0b0b0f' : lane.color,
|
||||
background: lane.audible ? lane.color : 'rgba(255,255,255,0.06)',
|
||||
}}
|
||||
>
|
||||
{lane.name.slice(0, 1).toUpperCase()}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Zoom controls (Traktor-style +/-). stopPropagation on down so tapping a
|
||||
button doesn't begin a scratch drag. */}
|
||||
<div className="absolute right-2 top-2 flex flex-col gap-1">
|
||||
|
||||
@@ -8,16 +8,19 @@ import {
|
||||
type GridMarker,
|
||||
type Track,
|
||||
type TrackCues,
|
||||
type StemInfo,
|
||||
type TrackOrigin,
|
||||
trackAudioUrl,
|
||||
trackCuesFor,
|
||||
trackStemsFor,
|
||||
trackStemUrl,
|
||||
} from '../api'
|
||||
import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid'
|
||||
import { slotLabeller, useCaps } from '../lib/capabilities'
|
||||
import { CUE_TYPE_LABELS, cueTypeColor } from '../lib/cues'
|
||||
import { keyColor } from '../lib/format'
|
||||
import { readOnlyShort, readOnlyNotice } from '../lib/platformCopy'
|
||||
import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
|
||||
import { analyzeStems, analyzeWaveform, type WaveColumn } from '../lib/waveform'
|
||||
import { setAmbientFromArt } from '../lib/ambient'
|
||||
import { Icon } from '../lib/icons'
|
||||
import { ScratchEngine } from '../lib/scratchEngine'
|
||||
@@ -28,9 +31,12 @@ import { ContextMenu, type MenuItem } from './ContextMenu'
|
||||
import { BpmReadout, GridEditStrip, TempoControls, TempoFold } from './GridControls'
|
||||
import { HotcueBar } from './HotcueBar'
|
||||
import { LoopControls, LOOP_SIZES, type LoopMode } from './LoopControls'
|
||||
import { MainWaveform, MIN_SEC, MAX_SEC, DEFAULT_SEC } from './MainWaveform'
|
||||
import { MainWaveform, MIN_SEC, MAX_SEC, DEFAULT_SEC, type StemLane } from './MainWaveform'
|
||||
import { OverviewWaveform } from './OverviewWaveform'
|
||||
|
||||
/** Keys that mute stems 1-4 (Shift = solo), by `KeyboardEvent.code`. */
|
||||
const STEM_KEYS = ['KeyQ', 'KeyW', 'KeyE', 'KeyR']
|
||||
|
||||
interface Props {
|
||||
/** The track currently loaded into the prep deck, if any. */
|
||||
track: Track | null
|
||||
@@ -107,6 +113,13 @@ export function PrepStrip({
|
||||
const [duration, setDuration] = useState(0)
|
||||
const [ready, setReady] = useState(false)
|
||||
const [cols, setCols] = useState<WaveColumn[] | null>(null)
|
||||
// A stem track: its stems (from the FILE), their lanes, and which are muted
|
||||
// — reset per track, as Traktor's stem deck does. There is no separate solo
|
||||
// state: solo is a shortcut that SETS the mutes, so every stem stays freely
|
||||
// mutable afterwards.
|
||||
const [stems, setStems] = useState<StemInfo[] | null>(null)
|
||||
const [stemLanes, setStemLanes] = useState<Float32Array[] | null>(null)
|
||||
const [stemMuted, setStemMuted] = useState<boolean[]>([])
|
||||
const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading')
|
||||
const [cueData, setCueData] = useState<TrackCues | null>(null)
|
||||
// The beatgrid, rebuilt whenever the cue data is replaced (every edit returns
|
||||
@@ -254,6 +267,7 @@ export function PrepStrip({
|
||||
previewRef.current = null
|
||||
setPreviewing(false)
|
||||
setCueHeld(false)
|
||||
setStemMuted([])
|
||||
}, [trackId])
|
||||
|
||||
// Recolour the whole app from this track's cover art. A device's art is not
|
||||
@@ -274,23 +288,40 @@ export function PrepStrip({
|
||||
}
|
||||
let cancelled = false
|
||||
setCols(null)
|
||||
setStems(null)
|
||||
setStemLanes(null)
|
||||
setWaveStatus('loading')
|
||||
analyzeWaveform(trackAudioUrl(origin, trackId))
|
||||
// A stem FILE loads its four stems and plays their sum (decided: always,
|
||||
// for every stem track); anything else loads as one buffer, as before.
|
||||
const load = trackStemsFor(origin, trackId)
|
||||
.catch(() => [] as StemInfo[])
|
||||
.then(async (found) => {
|
||||
if (found.length) {
|
||||
const res = await analyzeStems(found.map((_, k) => trackStemUrl(origin, trackId, k)))
|
||||
return { cols: res.cols, buffers: res.buffers, lanes: res.lanes, stems: found }
|
||||
}
|
||||
const res = await analyzeWaveform(trackAudioUrl(origin, trackId))
|
||||
return { cols: res.cols, buffers: [res.buffer], lanes: null, stems: null }
|
||||
})
|
||||
load
|
||||
.then((res) => {
|
||||
if (cancelled) return
|
||||
setCols(res.cols)
|
||||
setStems(res.stems)
|
||||
setStemLanes(res.lanes)
|
||||
setWaveStatus('ready')
|
||||
const ctx = getCtx()
|
||||
const sc = new ScratchEngine()
|
||||
sc.load(res.buffer)
|
||||
if (res.stems) sc.loadStems(res.buffers, res.buffers.map(() => 1))
|
||||
else sc.load(res.buffers[0])
|
||||
sc.attach(getScratchCtx()) // own context; warm up so the first scratch isn't silent
|
||||
scratchRef.current = sc
|
||||
if (!playbackRef.current) {
|
||||
playbackRef.current = new PlaybackEngine()
|
||||
playbackRef.current.setOnEnded(() => setPlaying(false))
|
||||
}
|
||||
playbackRef.current.load(ctx, res.buffer)
|
||||
setDuration(res.buffer.duration)
|
||||
playbackRef.current.load(ctx, res.stems ? res.buffers : res.buffers[0])
|
||||
setDuration(res.buffers[0].duration)
|
||||
setReady(true)
|
||||
loadedIdRef.current = trackId
|
||||
// A play was requested (library row button) → start now that it's ready.
|
||||
@@ -1046,6 +1077,43 @@ export function PrepStrip({
|
||||
// (Shift+↑/↓ is the track table's extend-selection).
|
||||
// Digits are read from e.code (layout-/Shift-independent) and a ref holds the
|
||||
// latest handlers so the listener attaches once and never goes stale.
|
||||
// ---- stems: mute / solo ------------------------------------------------------
|
||||
// What each stem plays at: a muted stem is 0. Both engines follow it (the
|
||||
// scratch engine re-sums).
|
||||
const stemLevels = useMemo(() => (stems ?? []).map((_, k) => (stemMuted[k] ? 0 : 1)), [stems, stemMuted])
|
||||
const stemLevelKey = stemLevels.join(',')
|
||||
useEffect(() => {
|
||||
if (!stems) return
|
||||
playbackRef.current?.setGains(stemLevels)
|
||||
scratchRef.current?.setLevels(stemLevels)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [stemLevelKey])
|
||||
// Solo = "mute every stem but this one". Soloing a stem that is already the
|
||||
// only one playing brings them all back (so solo twice undoes it).
|
||||
const toggleStem = (k: number, solo: boolean) => {
|
||||
if (!stems || k >= stems.length) return
|
||||
setStemMuted((m) => {
|
||||
if (!solo) return stems.map((_, i) => (i === k ? !m[i] : !!m[i]))
|
||||
const alone = stems.every((_, i) => (i === k ? !m[i] : !!m[i]))
|
||||
return stems.map((_, i) => (alone ? false : i !== k))
|
||||
})
|
||||
}
|
||||
// The ring on a lane button: that stem is the only one playing.
|
||||
const soloed = stemLevels.filter((l) => l > 0).length === 1 && stemLevels.length > 1
|
||||
? stemLevels.findIndex((l) => l > 0)
|
||||
: null
|
||||
const lanes: StemLane[] | null =
|
||||
stems && stemLanes
|
||||
? stems.map((st, k) => ({
|
||||
data: stemLanes[k],
|
||||
name: st.name,
|
||||
color: st.color,
|
||||
audible: stemLevels[k] > 0,
|
||||
solo: soloed === k,
|
||||
shortcut: STEM_KEYS[k] ? STEM_KEYS[k].slice(3) : '',
|
||||
}))
|
||||
: null
|
||||
|
||||
const shortcutsRef = useRef({
|
||||
toggle,
|
||||
onSlotPress,
|
||||
@@ -1058,6 +1126,7 @@ export function PrepStrip({
|
||||
prevMarker,
|
||||
nextMarker,
|
||||
slotCount,
|
||||
toggleStem,
|
||||
})
|
||||
shortcutsRef.current = {
|
||||
toggle,
|
||||
@@ -1071,6 +1140,7 @@ export function PrepStrip({
|
||||
prevMarker,
|
||||
nextMarker,
|
||||
slotCount,
|
||||
toggleStem,
|
||||
}
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
@@ -1097,6 +1167,14 @@ export function PrepStrip({
|
||||
shortcutsRef.current.onCuePress()
|
||||
return
|
||||
}
|
||||
// Q W E R: mute a stem; Shift+ solos it (a stem track only — elsewhere
|
||||
// there is nothing to toggle, and the keys stay free).
|
||||
const stemKey = STEM_KEYS.indexOf(e.code)
|
||||
if (stemKey >= 0) {
|
||||
e.preventDefault()
|
||||
shortcutsRef.current.toggleStem(stemKey, e.shiftKey)
|
||||
return
|
||||
}
|
||||
if (e.code === 'ArrowLeft') {
|
||||
e.preventDefault()
|
||||
if (e.shiftKey) shortcutsRef.current.prevMarker()
|
||||
@@ -1337,6 +1415,8 @@ export function PrepStrip({
|
||||
onScratchStart={onScratchStart}
|
||||
onScratchMove={onScratchMove}
|
||||
onScratchEnd={onScratchEnd}
|
||||
lanes={lanes}
|
||||
onStemToggle={toggleStem}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center text-xs text-faint">
|
||||
|
||||
@@ -10,6 +10,7 @@ interface Props {
|
||||
// says "Cmd/Ctrl" everywhere is harder to scan than one that names your key.
|
||||
const IS_MAC = /Mac|iPhone|iPad/.test(navigator.userAgent)
|
||||
const MOD = IS_MAC ? '⌘' : 'Ctrl'
|
||||
const ALT_KEY = IS_MAC ? '⌥' : 'Alt'
|
||||
|
||||
type Row = { keys: string[][]; action: string }
|
||||
type Section = { title: string; rows: Row[] }
|
||||
@@ -36,6 +37,9 @@ function sections(slots: number): Section[] {
|
||||
{ keys: [['Shift', '←'], ['Shift', '→']], action: 'Previous / next grid marker' },
|
||||
{ keys: [[pads]], action: 'Hotcue — set if empty, else jump (hold to preview)' },
|
||||
{ keys: [['Shift', pads]], action: 'Delete hotcue' },
|
||||
{ keys: [['Q'], ['W'], ['E'], ['R']], action: 'Stem track: mute / unmute stem 1–4' },
|
||||
{ keys: [['Shift', 'Q–R']], action: 'Stem track: solo — mute every other stem (again to unmute all)' },
|
||||
{ keys: [[ALT_KEY, 'Click', 'stem']], action: 'Solo a stem from its lane button' },
|
||||
{ keys: [['Drag waveform']], action: 'Scratch' },
|
||||
{ keys: [[MOD, 'Scroll']], action: 'Zoom the waveform' },
|
||||
{ keys: [['Right-click', 'pad']], action: 'Hotcue type, rename, delete' },
|
||||
|
||||
@@ -6,12 +6,20 @@
|
||||
// the AudioContext clock (high-resolution, so the playhead is smooth without any
|
||||
// wall-clock interpolation). Loop bounds can be changed on the live node, so
|
||||
// enabling a loop mid-playback is seamless.
|
||||
//
|
||||
// A STEM track loads four buffers instead of one. Each gets its own source and
|
||||
// gain, and every source is started at the SAME scheduled context time, so the
|
||||
// stems stay sample-locked through play, seek and loops — the deck plays their
|
||||
// sum, as Traktor's stem deck does. Muting is a gain change (ramped over a few
|
||||
// ms so it does not click), never a restart.
|
||||
|
||||
export class PlaybackEngine {
|
||||
private ctx: AudioContext | null = null
|
||||
private buffer: AudioBuffer | null = null
|
||||
private buffers: AudioBuffer[] = []
|
||||
private gain: GainNode | null = null
|
||||
private source: AudioBufferSourceNode | null = null
|
||||
/** One per buffer; a plain track has one of each. */
|
||||
private gains: GainNode[] = []
|
||||
private sources: AudioBufferSourceNode[] = []
|
||||
private startedAt = 0 // ctx time when the current source started
|
||||
private startOffset = 0 // buffer position (s) at that moment / paused position
|
||||
private _playing = false
|
||||
@@ -20,14 +28,21 @@ export class PlaybackEngine {
|
||||
private loopEnd = 0
|
||||
private onEnded: (() => void) | null = null
|
||||
|
||||
load(ctx: AudioContext, buffer: AudioBuffer): void {
|
||||
/** One buffer (a plain track) or several played in lockstep (the stems). */
|
||||
load(ctx: AudioContext, buffer: AudioBuffer | AudioBuffer[]): void {
|
||||
this.ctx = ctx
|
||||
this.buffer = buffer
|
||||
this.stopSource()
|
||||
this.buffers = Array.isArray(buffer) ? buffer : [buffer]
|
||||
if (!this.gain) {
|
||||
this.gain = ctx.createGain()
|
||||
this.gain.connect(ctx.destination)
|
||||
}
|
||||
this.stopSource()
|
||||
for (const g of this.gains) g.disconnect()
|
||||
this.gains = this.buffers.map(() => {
|
||||
const g = ctx.createGain()
|
||||
g.connect(this.gain!)
|
||||
return g
|
||||
})
|
||||
this._playing = false
|
||||
this.startOffset = 0
|
||||
this.loopOn = false
|
||||
@@ -37,9 +52,23 @@ export class PlaybackEngine {
|
||||
this.onEnded = cb
|
||||
}
|
||||
|
||||
private get buffer(): AudioBuffer | null {
|
||||
return this.buffers[0] ?? null
|
||||
}
|
||||
|
||||
get ready(): boolean {
|
||||
return !!this.buffer
|
||||
}
|
||||
|
||||
/** Per-buffer levels (0 = muted) — the stems' mute/solo. Ramped, not stepped. */
|
||||
setGains(levels: number[]): void {
|
||||
if (!this.ctx) return
|
||||
const now = this.ctx.currentTime
|
||||
this.gains.forEach((g, i) => {
|
||||
g.gain.cancelScheduledValues(now)
|
||||
g.gain.setTargetAtTime(levels[i] ?? 1, now, 0.004)
|
||||
})
|
||||
}
|
||||
get playing(): boolean {
|
||||
return this._playing
|
||||
}
|
||||
@@ -52,7 +81,8 @@ export class PlaybackEngine {
|
||||
|
||||
getPosition(): number {
|
||||
if (!this.buffer || !this.ctx || !this._playing) return this.startOffset
|
||||
let pos = this.startOffset + (this.ctx.currentTime - this.startedAt)
|
||||
// max(0, …): a scheduled start is a few ms in the future.
|
||||
let pos = this.startOffset + Math.max(0, this.ctx.currentTime - this.startedAt)
|
||||
if (this.loopOn && this.loopEnd > this.loopStart && pos >= this.loopEnd) {
|
||||
const len = this.loopEnd - this.loopStart
|
||||
pos = this.loopStart + ((pos - this.loopStart) % len)
|
||||
@@ -62,41 +92,48 @@ export class PlaybackEngine {
|
||||
|
||||
private startSource(offset: number): void {
|
||||
if (!this.ctx || !this.buffer || !this.gain) return
|
||||
const src = this.ctx.createBufferSource()
|
||||
src.buffer = this.buffer
|
||||
if (this.loopOn && this.loopEnd > this.loopStart) {
|
||||
src.loop = true
|
||||
src.loopStart = this.loopStart
|
||||
src.loopEnd = this.loopEnd
|
||||
}
|
||||
src.connect(this.gain)
|
||||
src.onended = () => {
|
||||
if (this.source === src) {
|
||||
const off = Math.max(0, Math.min(offset, this.buffer.duration - 0.001))
|
||||
// One shared start time, a hair ahead so every source can make it: that is
|
||||
// what keeps the stems sample-locked to each other.
|
||||
const when = this.ctx.currentTime + (this.buffers.length > 1 ? 0.01 : 0)
|
||||
const started = this.buffers.map((buf, i) => {
|
||||
const src = this.ctx!.createBufferSource()
|
||||
src.buffer = buf
|
||||
if (this.loopOn && this.loopEnd > this.loopStart) {
|
||||
src.loop = true
|
||||
src.loopStart = this.loopStart
|
||||
src.loopEnd = this.loopEnd
|
||||
}
|
||||
src.connect(this.gains[i] ?? this.gain!)
|
||||
src.start(when, off)
|
||||
return src
|
||||
})
|
||||
const first = started[0]
|
||||
first.onended = () => {
|
||||
if (this.sources[0] === first) {
|
||||
// Natural end (our own stops null out onended first).
|
||||
this._playing = false
|
||||
this.source = null
|
||||
this.stopSource()
|
||||
this.onEnded?.()
|
||||
}
|
||||
}
|
||||
const off = Math.max(0, Math.min(offset, this.buffer.duration - 0.001))
|
||||
src.start(0, off)
|
||||
this.source = src
|
||||
this.startedAt = this.ctx.currentTime
|
||||
this.sources = started
|
||||
this.startedAt = when
|
||||
this.startOffset = offset
|
||||
this._playing = true
|
||||
}
|
||||
|
||||
private stopSource(): void {
|
||||
if (this.source) {
|
||||
this.source.onended = null
|
||||
for (const src of this.sources) {
|
||||
src.onended = null
|
||||
try {
|
||||
this.source.stop()
|
||||
src.stop()
|
||||
} catch {
|
||||
/* already stopped */
|
||||
}
|
||||
this.source.disconnect()
|
||||
this.source = null
|
||||
src.disconnect()
|
||||
}
|
||||
this.sources = []
|
||||
}
|
||||
|
||||
play(): void {
|
||||
@@ -141,13 +178,13 @@ export class PlaybackEngine {
|
||||
this.loopStart = start
|
||||
this.loopEnd = end
|
||||
this.loopOn = enabled
|
||||
if (this.source) {
|
||||
for (const src of this.sources) {
|
||||
if (enabled && end > start) {
|
||||
this.source.loop = true
|
||||
this.source.loopStart = start
|
||||
this.source.loopEnd = end
|
||||
src.loop = true
|
||||
src.loopStart = start
|
||||
src.loopEnd = end
|
||||
} else {
|
||||
this.source.loop = false
|
||||
src.loop = false
|
||||
}
|
||||
}
|
||||
// If the playhead is already at/past the loop end, jump into it (the live
|
||||
|
||||
@@ -38,6 +38,8 @@ export class ScratchEngine {
|
||||
// COPY the PCM — do NOT hold getChannelData() views. When the playback engine
|
||||
// plays this same AudioBuffer, the browser (Firefox) "acquires the content"
|
||||
// and detaches those views to zero-length, which would silence the scratch.
|
||||
this.stems = []
|
||||
this.build++
|
||||
this.channels = []
|
||||
for (let c = 0; c < buffer.numberOfChannels; c++) {
|
||||
this.channels.push(new Float32Array(buffer.getChannelData(c)))
|
||||
@@ -46,6 +48,54 @@ export class ScratchEngine {
|
||||
this.sr = buffer.sampleRate
|
||||
}
|
||||
|
||||
// ---- stems: scratch what you hear -----------------------------------------
|
||||
private stems: AudioBuffer[] = []
|
||||
private build = 0 // generation: a newer mute change abandons an older rebuild
|
||||
|
||||
/** Load a stem track: ONE summed copy of the stems at `levels` (the deck's
|
||||
* mute/solo) — not four, which would quadruple the memory. copyFromChannel
|
||||
* rather than getChannelData, for the same detaching reason as `load`. */
|
||||
loadStems(buffers: AudioBuffer[], levels: number[]): void {
|
||||
this.stems = buffers
|
||||
const first = buffers[0]
|
||||
this.length = first.length
|
||||
this.sr = first.sampleRate
|
||||
this.channels = []
|
||||
for (let c = 0; c < first.numberOfChannels; c++) this.channels.push(new Float32Array(first.length))
|
||||
this.setLevels(levels)
|
||||
}
|
||||
|
||||
/** Re-sum for new mute/solo levels. In slices over a few frames, so a toggle
|
||||
* never stalls the page (a 6-minute track is tens of millions of samples);
|
||||
* until it finishes, a scratch hears the previous mix. */
|
||||
setLevels(levels: number[]): void {
|
||||
if (!this.stems.length) return
|
||||
const gen = ++this.build
|
||||
const n = this.length
|
||||
const next = this.channels.map(() => new Float32Array(n))
|
||||
const tmp = new Float32Array(1 << 18)
|
||||
let at = 0
|
||||
const step = () => {
|
||||
if (gen !== this.build) return
|
||||
const end = Math.min(n, at + tmp.length)
|
||||
const len = end - at
|
||||
const view: Float32Array<ArrayBuffer> = len === tmp.length ? tmp : tmp.subarray(0, len)
|
||||
this.stems.forEach((buf, s) => {
|
||||
const g = levels[s] ?? 1
|
||||
if (!g) return
|
||||
for (let c = 0; c < next.length; c++) {
|
||||
buf.copyFromChannel(view, Math.min(c, buf.numberOfChannels - 1), at)
|
||||
const dst = next[c]
|
||||
for (let i = 0; i < len; i++) dst[at + i] += view[i] * g
|
||||
}
|
||||
})
|
||||
at = end
|
||||
if (at < n) setTimeout(step, 0)
|
||||
else this.channels = next
|
||||
}
|
||||
step()
|
||||
}
|
||||
|
||||
get loaded(): boolean {
|
||||
return this.length > 0
|
||||
}
|
||||
|
||||
+116
-13
@@ -99,38 +99,98 @@ export interface WaveformAnalysis {
|
||||
buffer: AudioBuffer
|
||||
}
|
||||
|
||||
export async function analyzeWaveform(url: string, buckets?: number): Promise<WaveformAnalysis> {
|
||||
async function decodeUrl(url: string): Promise<AudioBuffer> {
|
||||
const resp = await fetch(url)
|
||||
if (!resp.ok) throw new Error(`audio fetch failed: ${resp.status}`)
|
||||
const arr = await resp.arrayBuffer()
|
||||
|
||||
const AC: typeof AudioContext =
|
||||
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
|
||||
const ctx = new AC()
|
||||
let audio: AudioBuffer
|
||||
try {
|
||||
audio = await ctx.decodeAudioData(arr)
|
||||
return await ctx.decodeAudioData(arr)
|
||||
} finally {
|
||||
void ctx.close()
|
||||
}
|
||||
}
|
||||
|
||||
const len = audio.length
|
||||
const sr = audio.sampleRate
|
||||
const chs = audio.numberOfChannels
|
||||
|
||||
function defaultBuckets(len: number, sr: number): number {
|
||||
// Resolution scales with track length (~140 columns/sec) so the zoomed-in
|
||||
// main waveform stays crisp; clamped so short/long tracks stay reasonable.
|
||||
if (buckets == null) {
|
||||
const seconds = len / sr
|
||||
buckets = Math.min(48000, Math.max(1600, Math.round(seconds * 140)))
|
||||
}
|
||||
return Math.min(48000, Math.max(1600, Math.round((len / sr) * 140)))
|
||||
}
|
||||
|
||||
export async function analyzeWaveform(url: string, buckets?: number): Promise<WaveformAnalysis> {
|
||||
const audio = await decodeUrl(url)
|
||||
const len = audio.length
|
||||
const chs = audio.numberOfChannels
|
||||
// Downmix to mono.
|
||||
const mono = new Float32Array(len)
|
||||
for (let c = 0; c < chs; c++) {
|
||||
const d = audio.getChannelData(c)
|
||||
for (let i = 0; i < len; i++) mono[i] += d[i] / chs
|
||||
}
|
||||
return { cols: await analyzeMono(mono, audio.sampleRate, buckets), buffer: audio }
|
||||
}
|
||||
|
||||
export interface StemAnalysis {
|
||||
/** The ordinary three-band columns, of the stems' SUM — the overview. */
|
||||
cols: WaveColumn[]
|
||||
/** Per stem, per column: amplitude 0..1 — the main view's lanes. */
|
||||
lanes: Float32Array[]
|
||||
buffers: AudioBuffer[]
|
||||
}
|
||||
|
||||
/**
|
||||
* A stem track: decode its stems (in parallel) and analyse them once. The mix
|
||||
* stream is never decoded — the deck plays the stems' sum, and one fewer
|
||||
* full-length buffer is ~140 MB less on a 6-minute track.
|
||||
*
|
||||
* Each lane is normalised to its OWN 99.5th percentile so a quiet vocal lane is
|
||||
* still readable, but never below 5% of the loudest stem's, so a near-silent
|
||||
* stem draws as near-silence rather than magnified noise.
|
||||
*/
|
||||
export async function analyzeStems(urls: string[], buckets?: number): Promise<StemAnalysis> {
|
||||
const buffers = await Promise.all(urls.map(decodeUrl))
|
||||
const len = Math.min(...buffers.map((b) => b.length))
|
||||
const sr = buffers[0].sampleRate
|
||||
const n = buckets ?? defaultBuckets(len, sr)
|
||||
const scale = n / len
|
||||
const mono = new Float32Array(len)
|
||||
const tmp = new Float32Array(len)
|
||||
const lanes = buffers.map((buf) => {
|
||||
const lane = new Float32Array(n)
|
||||
const chs = buf.numberOfChannels
|
||||
const monoStem = new Float32Array(len)
|
||||
for (let c = 0; c < chs; c++) {
|
||||
buf.copyFromChannel(tmp, c)
|
||||
for (let i = 0; i < len; i++) monoStem[i] += tmp[i] / chs
|
||||
}
|
||||
for (let i = 0; i < len; i++) {
|
||||
const v = monoStem[i]
|
||||
mono[i] += v
|
||||
const a = Math.abs(v)
|
||||
const b = (i * scale) | 0
|
||||
if (a > lane[b]) lane[b] = a
|
||||
}
|
||||
return lane
|
||||
})
|
||||
const ceilOf = (v: Float32Array) => {
|
||||
const sorted = Float32Array.from(v).sort()
|
||||
return sorted[Math.floor((sorted.length - 1) * 0.995)]
|
||||
}
|
||||
const ceilings = lanes.map(ceilOf)
|
||||
const loudest = Math.max(1e-6, ...ceilings)
|
||||
lanes.forEach((lane, k) => {
|
||||
const top = Math.max(ceilings[k], loudest * 0.05, 1e-6)
|
||||
for (let b = 0; b < lane.length; b++) lane[b] = Math.min(1, lane[b] / top)
|
||||
})
|
||||
return { cols: await analyzeMono(mono, sr, n), lanes, buffers }
|
||||
}
|
||||
|
||||
async function analyzeMono(mono: Float32Array<ArrayBuffer>, sr: number, buckets?: number): Promise<WaveColumn[]> {
|
||||
const len = mono.length
|
||||
|
||||
if (buckets == null) buckets = defaultBuckets(len, sr)
|
||||
|
||||
const scale = buckets / len
|
||||
const lowE = new Float64Array(buckets)
|
||||
@@ -214,5 +274,48 @@ export async function analyzeWaveform(url: string, buckets?: number): Promise<Wa
|
||||
high: curve(highR[b] / maxH, 1.05),
|
||||
}
|
||||
}
|
||||
return { cols, buffer: audio }
|
||||
return cols
|
||||
}
|
||||
|
||||
/**
|
||||
* Paint one stem LANE: the stem's amplitude as symmetric bars in its own
|
||||
* colour, across [y0, y0 + laneH). Same track-space binning as `paintWave`, so
|
||||
* lanes and the plain view scroll identically. A muted stem is drawn faint.
|
||||
*/
|
||||
export function paintLane(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
lane: Float32Array,
|
||||
color: string,
|
||||
w: number,
|
||||
y0: number,
|
||||
laneH: number,
|
||||
startFrac: number,
|
||||
endFrac: number,
|
||||
opts: PaintOptions,
|
||||
dim: boolean,
|
||||
): void {
|
||||
const n = lane.length
|
||||
if (n === 0 || w === 0 || laneH <= 0 || endFrac <= startFrac) return
|
||||
const mid = y0 + laneH / 2
|
||||
const reach = laneH / 2 - 1
|
||||
const colsPerPx = ((endFrac - startFrac) * n) / w
|
||||
const colsPerBar = (opts.bar + opts.gap) * colsPerPx
|
||||
const startCol = startFrac * n
|
||||
const k0 = Math.floor(Math.max(0, startCol) / colsPerBar)
|
||||
const k1 = Math.ceil(Math.min(n, endFrac * n) / colsPerBar)
|
||||
const prevAlpha = ctx.globalAlpha
|
||||
ctx.globalAlpha = dim ? 0.18 : 0.92
|
||||
ctx.fillStyle = color
|
||||
for (let k = k0; k < k1; k++) {
|
||||
const c0 = k * colsPerBar
|
||||
const i0 = Math.max(0, Math.floor(c0))
|
||||
const i1 = Math.min(n, Math.max(i0 + 1, Math.ceil(c0 + colsPerBar)))
|
||||
let v = 0
|
||||
for (let i = i0; i < i1; i++) if (lane[i] > v) v = lane[i]
|
||||
if (v <= 0) continue
|
||||
const x = (c0 - startCol) / colsPerPx
|
||||
const half = Math.max(0.5, v * reach)
|
||||
ctx.fillRect(x, mid - half, opts.bar, half * 2)
|
||||
}
|
||||
ctx.globalAlpha = prevAlpha
|
||||
}
|
||||
Reference in new issue
Block a user