mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Begun implementing playback
This commit is contained in:
1 parent
279e5ac34f
commit
fa7375d0e9
9 files changed
+712
-49
No files matched your search
@@ -7,19 +7,27 @@ Guidance for working in this repo. Read before making changes.
|
|||||||
**Konduktor** — a library-management and track-preparation tool for **Native
|
**Konduktor** — a library-management and track-preparation tool for **Native
|
||||||
Instruments Traktor** (Pro 4 / NML v20), built on the `traktor-nml-utils`
|
Instruments Traktor** (Pro 4 / NML v20), built on the `traktor-nml-utils`
|
||||||
library. The user is a DJ; the goal is a polished, multiplatform web app for
|
library. The user is a DJ; the goal is a polished, multiplatform web app for
|
||||||
browsing the collection and editing playlists, later possibly wrapped in Tauri.
|
browsing the collection, editing playlists, and preparing tracks (metadata,
|
||||||
|
cover art; later audio/cue prep) — a lightweight alternative to heavy Traktor,
|
||||||
|
later possibly wrapped in Tauri and given a mobile version.
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
Two independent apps that talk over HTTP:
|
Two independent apps that talk over HTTP:
|
||||||
|
|
||||||
- **`backend/`** — Python + FastAPI. Parses `collection.nml` via
|
- **`backend/`** — Python + FastAPI. Parses `collection.nml` via
|
||||||
`traktor-nml-utils` and serves a query API. Entry point:
|
`traktor-nml-utils` and serves a query + edit API. Entry point:
|
||||||
[backend/konduktor/main.py](backend/konduktor/main.py).
|
[backend/konduktor/main.py](backend/konduktor/main.py).
|
||||||
- `collection_service.py` — loads the NML once into memory, flattens ENTRYs
|
- `collection_service.py` — the **read** model: loads the NML, flattens ENTRYs
|
||||||
into `Track` objects, indexes them by primary key, and builds the playlist
|
into `Track` objects, indexes them by primary key. All query logic
|
||||||
tree. All query logic (filter/sort/facets/stats) lives here.
|
(filter/sort/facets/stats) lives here. `replace_track()` refreshes one
|
||||||
- `schemas.py` — Pydantic response models.
|
projection after an edit (bridges the read model and the edit store).
|
||||||
|
- `playlist_store.py` (`PlaylistStore`) — the **edit** model: owns the parsed
|
||||||
|
dataclass NML and applies all edits (playlists AND track metadata AND cover
|
||||||
|
art), then renders + saves. See "Write path" below.
|
||||||
|
- `file_tags.py` — reads/writes embedded audio-file tags & cover art (mutagen)
|
||||||
|
and resolves Traktor `LOCATION`s to OS paths. Best-effort.
|
||||||
|
- `schemas.py` — Pydantic response/request models.
|
||||||
- `main.py` — FastAPI routes (all under `/api`). Holds an `AppState` with the
|
- `main.py` — FastAPI routes (all under `/api`). Holds an `AppState` with the
|
||||||
currently-loaded collection; it starts **unloaded** and the collection is
|
currently-loaded collection; it starts **unloaded** and the collection is
|
||||||
chosen at runtime via `POST /api/collection/open` (data routes 409 until
|
chosen at runtime via `POST /api/collection/open` (data routes 409 until
|
||||||
@@ -29,11 +37,16 @@ Two independent apps that talk over HTTP:
|
|||||||
explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx).
|
explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx).
|
||||||
- `api.ts` — typed client + all API types (keep in sync with backend
|
- `api.ts` — typed client + all API types (keep in sync with backend
|
||||||
`schemas.py`).
|
`schemas.py`).
|
||||||
- `components/` — `Sidebar` (playlist tree), `Toolbar` (search/filters),
|
- `components/` — `CollectionPicker` (startup file-browser gate), `Sidebar`
|
||||||
`TrackTable` (TanStack Table + Virtual grid), `StatusBar`, `RatingStars`.
|
(playlist tree + create/rename/delete), `SaveBar`, `Toolbar`
|
||||||
|
(search/filters), `TrackTable` (TanStack Table + Virtual grid),
|
||||||
|
`PlaylistEditor` (dnd-kit reorder), `SelectionBar` (bulk add-to-playlist),
|
||||||
|
`ContextMenu` + `EditTagsDialog` (right-click → metadata + album-art edit),
|
||||||
|
`StatusBar`, `RatingStars`, `Toast`.
|
||||||
- Data flow: the whole library is fetched once (`/api/tracks?limit=20000`);
|
- Data flow: the whole library is fetched once (`/api/tracks?limit=20000`);
|
||||||
filtering and sorting happen **client-side** for instant interaction.
|
filtering and sorting happen **client-side** for instant interaction. Edits
|
||||||
Styling is Tailwind v4 with design tokens in `src/index.css`.
|
apply in-memory (server holds them) and the sidebar **Save to Traktor**
|
||||||
|
button flushes to disk. Styling is Tailwind v4 with tokens in `src/index.css`.
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
@@ -54,9 +67,10 @@ npm run build # tsc -b && vite build — run this to typecheck
|
|||||||
**Tests:** `cd backend && ./run_tests.sh` (runs against a temp copy of the real
|
**Tests:** `cd backend && ./run_tests.sh` (runs against a temp copy of the real
|
||||||
collection). **ALWAYS run this before changing anything in the save /
|
collection). **ALWAYS run this before changing anything in the save /
|
||||||
serialization path.** It enforces:
|
serialization path.** It enforces:
|
||||||
- `test_save_fidelity.py` — a no-op save is byte-identical, and an edit changes
|
- `test_save_fidelity.py` — a no-op save is byte-identical; a playlist edit
|
||||||
only the edited playlist's block (this is the guard that catches serialization
|
changes only that playlist's block; and a **track-metadata edit changes only
|
||||||
regressions like the lxml reformatting bug).
|
that `<ENTRY>`** (Invariant C). The guard that catches serialization
|
||||||
|
regressions like the lxml reformatting bug.
|
||||||
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
|
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
|
||||||
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched.
|
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched.
|
||||||
|
|
||||||
@@ -69,14 +83,15 @@ frontend at `http://localhost:5173`.
|
|||||||
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 the
|
||||||
GitHub `master` (v4.0.0). Do not "simplify" this to a plain PyPI pin.
|
GitHub `master` (v4.0.0). Do not "simplify" this to a plain PyPI pin.
|
||||||
2. **Never write to the user's `collection.nml`.** It is real, irreplaceable
|
2. **The collection is real, irreplaceable data — protect it.** Every save
|
||||||
data (8,485 tracks). The app is read-only today. Phase 3 writes must operate
|
writes a timestamped `.bak` first (into a `backups/` folder next to the
|
||||||
on a copy and **back up first**.
|
collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the
|
||||||
3. **Saving is lossy.** The library's `save()` re-serializes the entire file
|
user to close Traktor before saving (it overwrites `collection.nml` on exit).
|
||||||
(reflows whitespace, `124.000000`→`124.0`, reorders attributes) and does
|
3. **Never re-serialize with lxml.** lxml reformats the whole file (collapses
|
||||||
**not** update count attributes (e.g. `PLAYLIST ENTRIES`). For Phase 3, prefer
|
empty tags, drops float precision) → thousands of noise lines. The ONLY safe
|
||||||
**surgical edits** to just the `PLAYLISTS` node (e.g. via lxml), recompute
|
render is the library's own pipeline (see "Write path"), which reproduces
|
||||||
counts, and back up — do not round-trip the whole 14 MB collection.
|
Traktor's byte-exact layout so a no-op save is byte-identical and only edited
|
||||||
|
objects diff. `test_save_fidelity.py` enforces this.
|
||||||
|
|
||||||
## Data model notes
|
## Data model notes
|
||||||
|
|
||||||
@@ -87,8 +102,8 @@ frontend at `http://localhost:5173`.
|
|||||||
- **Key** is Traktor's display key string, e.g. `"10m"` (Open Key notation).
|
- **Key** is Traktor's display key string, e.g. `"10m"` (Open Key notation).
|
||||||
- **Playlist tree**: recurse `nml.playlists.node.subnodes.node`. A node's `.type`
|
- **Playlist tree**: recurse `nml.playlists.node.subnodes.node`. A node's `.type`
|
||||||
is `FOLDER`, `PLAYLIST`, or `SMARTLIST`. Smart playlists are rule-based and
|
is `FOLDER`, `PLAYLIST`, or `SMARTLIST`. Smart playlists are rule-based and
|
||||||
have no static entry list. Synthetic ids (`pl-N`/`fld-N`/`sl-N`) are assigned
|
have no static entry list. `PlaylistNode.id` is the playlist's stable `UUID`;
|
||||||
at load and map to entries in `CollectionService._playlist_entries`.
|
folders use a synthetic path id `fld:<name>/<name>`, smart playlists `sl:<path>`.
|
||||||
- Model classes use single-capital names: `Entrytype`, `Primarykeytype`,
|
- Model classes use single-capital names: `Entrytype`, `Primarykeytype`,
|
||||||
`CueV2Type`. `Entrytype` is shared by collection entries and playlist entries.
|
`CueV2Type`. `Entrytype` is shared by collection entries and playlist entries.
|
||||||
|
|
||||||
@@ -107,29 +122,44 @@ frontend at `http://localhost:5173`.
|
|||||||
- ✅ Phase 1 — backend core + read-only API
|
- ✅ Phase 1 — backend core + read-only API
|
||||||
- ✅ Phase 2 — track explorer UI
|
- ✅ Phase 2 — track explorer UI
|
||||||
- ✅ Phase 3 — playlist editing/creation + safe (backup-first, surgical) saves
|
- ✅ Phase 3 — playlist editing/creation + safe (backup-first, surgical) saves
|
||||||
- ⬜ Phase 4 — polish + optional Tauri desktop packaging
|
- ✅ Runtime collection picker (in-app file browser)
|
||||||
|
- ✅ Track metadata editing (right-click → Edit Tags) + embedded file-tag & cover-art writing
|
||||||
|
- ⬜ Track prep — audio playback / cue-point & loop editing (Tier 2; needs audio engine)
|
||||||
|
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
|
||||||
|
|
||||||
## Phase 3 write path (playlists)
|
## Write path (playlists + track metadata)
|
||||||
|
|
||||||
- `playlist_store.py` (`PlaylistStore`) edits the **traktor-nml-utils dataclass
|
`PlaylistStore` edits the **traktor-nml-utils dataclass model** in memory and,
|
||||||
model** in memory (create/rename/delete/set-entries). On `save()` it renders
|
on `save()`, renders the WHOLE model and writes it (backup-first, into a
|
||||||
the model, extracts only the freshly rendered `<PLAYLISTS>…</PLAYLISTS>` span,
|
`backups/` folder next to the collection). Whole-file render is proven
|
||||||
and splices it into the original file bytes — COLLECTION stays byte-identical,
|
byte-identical for unedited content, so only the objects you actually changed
|
||||||
and a timestamped `.bak` is written first (into a `backups/` folder next to
|
diff — no COLLECTION splicing needed.
|
||||||
the collection).
|
|
||||||
- **Minimal-diff is load-bearing — do NOT re-serialize with lxml.** lxml
|
- **The render MUST use the library's pipeline** (do NOT use lxml — see gotcha 3):
|
||||||
reformats the whole PLAYLISTS section (~2500 changed lines). The render MUST
|
`XmlSerializer().render(nml)` → `restore_traktor_float_format(s, nml)` →
|
||||||
use the library's pipeline: `XmlSerializer().render(nml)` →
|
`format_traktor_layout(s)` (both funcs imported from `traktor_nml_utils`).
|
||||||
`restore_traktor_float_format(s, nml)` → `format_traktor_layout(s)` (both
|
`_render()` in `playlist_store.py` is the single place this happens.
|
||||||
imported from `traktor_nml_utils`). That reproduces Traktor's exact layout, so
|
- **Playlists**: keyed by stable `UUID`; folders by synthetic path id
|
||||||
unedited playlists stay byte-identical and only edited entries diff (verified:
|
|
||||||
a 13-track reorder changes exactly 24 lines).
|
|
||||||
- Playlists are keyed by their stable `UUID`; folders by synthetic path id
|
|
||||||
(`fld:<name>/<name>`). PRIMARYKEY `TYPE` is `STEM` if the track has a STEMS
|
(`fld:<name>/<name>`). PRIMARYKEY `TYPE` is `STEM` if the track has a STEMS
|
||||||
child (`CollectionService.stem_keys`, resolved via `entries_for`), else
|
child (`CollectionService.stem_keys`, resolved via `entries_for`), else `TRACK`.
|
||||||
`TRACK`.
|
- **Track metadata**: `set_track_metadata(track_id, fields)` edits only the SAFE
|
||||||
|
set — title, artist, album, genre, label, remixer, producer, mix,
|
||||||
|
release_date, comment, rating (0–5 stars → `RANKING = stars*51`). Path, BPM and
|
||||||
|
key are intentionally NOT editable (path = identity; BPM/key are audio/grid).
|
||||||
|
- **Embedded file tags + cover art**: on save, for each edited track,
|
||||||
|
`_sync_file_tags()` writes the changed fields (and staged cover art) into the
|
||||||
|
audio file via `file_tags` (mutagen; ID3/MP4/FLAC/AIFF, WAV skipped) —
|
||||||
|
best-effort (reports `file-not-found` if the drive isn't mounted, `.nml` still
|
||||||
|
saves). Frame/atom-level writes preserve everything else (verified: cover art,
|
||||||
|
BPM, key, and Traktor STEM atoms all survive). `.nml` is the source of truth;
|
||||||
|
Traktor caches its own cover thumbnail so it may need a manual "Import Cover
|
||||||
|
Art" to show replaced art.
|
||||||
|
- Reads come from `CollectionService`; after a metadata edit the endpoint calls
|
||||||
|
`service.replace_track()` so the change shows immediately (the two models
|
||||||
|
aren't yet consolidated).
|
||||||
- `POST /api/save` always writes (backup-first); no write gate. Endpoints:
|
- `POST /api/save` always writes (backup-first); no write gate. Endpoints:
|
||||||
`POST/PATCH/DELETE /api/playlists[...]`, `PUT .../entries` (replace),
|
`POST/PATCH/DELETE /api/playlists[...]`, `PUT .../entries` (replace),
|
||||||
`POST .../add` (append), `POST /api/save`.
|
`POST .../add` (append); `PATCH /api/tracks` (metadata); `GET/PUT /api/tracks/art`
|
||||||
- Test: `backend/test_phase3.py` (runs against a temp copy; asserts surgical +
|
(cover art); `POST /api/save`.
|
||||||
backup + Traktor-valid). Run: `python test_phase3.py` in the backend venv.
|
- Tests: `backend/run_tests.sh` → `test_save_fidelity.py` + `test_phase3.py`
|
||||||
|
(both run against a temp copy). Run before touching the save/serialization path.
|
||||||
@@ -11,6 +11,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadFile
|
from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadFile
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
|
||||||
from .collection_service import CollectionService
|
from .collection_service import CollectionService
|
||||||
from .playlist_store import PlaylistError, PlaylistStore
|
from .playlist_store import PlaylistError, PlaylistStore
|
||||||
@@ -299,6 +300,34 @@ def track_art(track_id: str) -> Response:
|
|||||||
return Response(content=data, media_type=mime, headers={"Cache-Control": "no-store"})
|
return Response(content=data, media_type=mime, headers={"Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
|
||||||
|
_AUDIO_MIME = {
|
||||||
|
".mp3": "audio/mpeg",
|
||||||
|
".m4a": "audio/mp4",
|
||||||
|
".mp4": "audio/mp4",
|
||||||
|
".aac": "audio/aac",
|
||||||
|
".flac": "audio/flac",
|
||||||
|
".wav": "audio/wav",
|
||||||
|
".aif": "audio/aiff",
|
||||||
|
".aiff": "audio/aiff",
|
||||||
|
".ogg": "audio/ogg",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/tracks/audio")
|
||||||
|
def track_audio(track_id: str) -> FileResponse:
|
||||||
|
"""Stream a track's audio file for playback (supports HTTP Range/seeking)."""
|
||||||
|
path = require_store().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}")
|
||||||
|
# .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
|
||||||
|
# the download (FileResponse adds ETag/Last-Modified for revalidation).
|
||||||
|
return FileResponse(path, media_type=mime)
|
||||||
|
|
||||||
|
|
||||||
@app.put("/api/tracks/art")
|
@app.put("/api/tracks/art")
|
||||||
async def set_track_art(track_id: str = Form(...), file: UploadFile = File(...)) -> dict:
|
async def set_track_art(track_id: str = Form(...), file: UploadFile = File(...)) -> dict:
|
||||||
"""Stage replacement cover art for a track (written to the file on save)."""
|
"""Stage replacement cover art for a track (written to the file on save)."""
|
||||||
|
|||||||
@@ -286,6 +286,17 @@ class PlaylistStore:
|
|||||||
loc = entry.location
|
loc = entry.location
|
||||||
return file_tags.read_cover(file_tags.resolve_path(loc.volume, loc.dir, loc.file))
|
return file_tags.read_cover(file_tags.resolve_path(loc.volume, loc.dir, loc.file))
|
||||||
|
|
||||||
|
def audio_path(self, track_id: str) -> "Path | None":
|
||||||
|
"""Resolve a track's audio file to an OS path (for playback streaming)."""
|
||||||
|
from . import file_tags
|
||||||
|
|
||||||
|
with self._lock:
|
||||||
|
entry = self._entry_by_key.get(track_id)
|
||||||
|
if entry is None or entry.location is None:
|
||||||
|
return None
|
||||||
|
loc = entry.location
|
||||||
|
return file_tags.resolve_path(loc.volume, loc.dir, loc.file)
|
||||||
|
|
||||||
def _entry_field_value(self, entry: Entrytype, field: str):
|
def _entry_field_value(self, entry: Entrytype, field: str):
|
||||||
"""Read a single editable field's current value from the model, in the
|
"""Read a single editable field's current value from the model, in the
|
||||||
shape file_tags expects (rating as 0–5 stars)."""
|
shape file_tags expects (rating as 0–5 stars)."""
|
||||||
|
|||||||
+16
-5
@@ -12,6 +12,7 @@ import { Toast, type ToastMsg } from './components/Toast'
|
|||||||
import { CollectionPicker } from './components/CollectionPicker'
|
import { CollectionPicker } from './components/CollectionPicker'
|
||||||
import { ContextMenu } from './components/ContextMenu'
|
import { ContextMenu } from './components/ContextMenu'
|
||||||
import { EditTagsDialog } from './components/EditTagsDialog'
|
import { EditTagsDialog } from './components/EditTagsDialog'
|
||||||
|
import { PrepStrip } from './components/PrepStrip'
|
||||||
|
|
||||||
function applyFilters(tracks: Track[], f: Filters): Track[] {
|
function applyFilters(tracks: Track[], f: Filters): Track[] {
|
||||||
const q = f.search.trim().toLowerCase()
|
const q = f.search.trim().toLowerCase()
|
||||||
@@ -43,6 +44,7 @@ export default function App() {
|
|||||||
const [forcePicker, setForcePicker] = useState(false)
|
const [forcePicker, setForcePicker] = useState(false)
|
||||||
const [menu, setMenu] = useState<{ track: Track; x: number; y: number } | null>(null)
|
const [menu, setMenu] = useState<{ track: Track; x: number; y: number } | null>(null)
|
||||||
const [editing, setEditing] = useState<Track | null>(null)
|
const [editing, setEditing] = useState<Track | null>(null)
|
||||||
|
const [prepTrack, setPrepTrack] = useState<Track | null>(null)
|
||||||
|
|
||||||
const notify = useCallback((kind: ToastMsg['kind'], text: string) => {
|
const notify = useCallback((kind: ToastMsg['kind'], text: string) => {
|
||||||
setToast({ id: Date.now(), kind, text })
|
setToast({ id: Date.now(), kind, text })
|
||||||
@@ -119,13 +121,16 @@ export default function App() {
|
|||||||
)
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-screen w-screen overflow-hidden bg-ink-950">
|
<div className="flex h-screen w-screen flex-col overflow-hidden bg-ink-950">
|
||||||
<Toast toast={toast} onClose={() => setToast(null)} />
|
<Toast toast={toast} onClose={() => setToast(null)} />
|
||||||
{menu && (
|
{menu && (
|
||||||
<ContextMenu
|
<ContextMenu
|
||||||
x={menu.x}
|
x={menu.x}
|
||||||
y={menu.y}
|
y={menu.y}
|
||||||
items={[{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }]}
|
items={[
|
||||||
|
{ label: 'Load to Deck', onClick: () => setPrepTrack(menu.track) },
|
||||||
|
{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) },
|
||||||
|
]}
|
||||||
onClose={() => setMenu(null)}
|
onClose={() => setMenu(null)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -137,9 +142,14 @@ export default function App() {
|
|||||||
onError={onError}
|
onError={onError}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<Sidebar source={source} onSelect={selectSource} onError={onError} />
|
|
||||||
|
|
||||||
<main className="relative flex min-w-0 flex-1 flex-col">
|
{/* Prep strip spans the top of the window; the library sits below it. */}
|
||||||
|
<PrepStrip track={prepTrack} onError={onError} />
|
||||||
|
|
||||||
|
<div className="flex min-h-0 flex-1 overflow-hidden">
|
||||||
|
<Sidebar source={source} onSelect={selectSource} onError={onError} />
|
||||||
|
|
||||||
|
<main className="relative flex min-w-0 flex-1 flex-col">
|
||||||
{isAll ? (
|
{isAll ? (
|
||||||
<Toolbar filters={filters} onChange={setFilters} />
|
<Toolbar filters={filters} onChange={setFilters} />
|
||||||
) : (
|
) : (
|
||||||
@@ -203,7 +213,8 @@ export default function App() {
|
|||||||
collectionName={collection.data?.path?.split('/').pop() ?? null}
|
collectionName={collection.data?.path?.split('/').pop() ?? null}
|
||||||
onChangeCollection={() => setForcePicker(true)}
|
onChangeCollection={() => setForcePicker(true)}
|
||||||
/>
|
/>
|
||||||
</main>
|
</main>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -200,6 +200,7 @@ export const api = {
|
|||||||
editTrack: (trackId: string, fields: Record<string, string | number | null>) =>
|
editTrack: (trackId: string, fields: Record<string, string | number | null>) =>
|
||||||
send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }),
|
send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }),
|
||||||
artUrl: (trackId: string) => `/api/tracks/art?track_id=${encodeURIComponent(trackId)}`,
|
artUrl: (trackId: string) => `/api/tracks/art?track_id=${encodeURIComponent(trackId)}`,
|
||||||
|
audioUrl: (trackId: string) => `/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`,
|
||||||
uploadArt: async (trackId: string, file: File) => {
|
uploadArt: async (trackId: string, file: File) => {
|
||||||
const fd = new FormData()
|
const fd = new FormData()
|
||||||
fd.append('track_id', trackId)
|
fd.append('track_id', trackId)
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
import { paintWave, type WaveColumn } from '../lib/waveform'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
cols: WaveColumn[]
|
||||||
|
currentTime: number
|
||||||
|
duration: number
|
||||||
|
onSeek: (t: number) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const MIN_SEC = 2 // most zoomed-in (seconds across the view)
|
||||||
|
const MAX_SEC = 64 // most zoomed-out
|
||||||
|
const DEFAULT_SEC = 16
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Traktor-style scrolling main waveform: the playhead is fixed at the centre and
|
||||||
|
* the waveform scrolls beneath it. Shows a time window [t - sec/2, t + sec/2];
|
||||||
|
* the zoom buttons change that window width. Repaints every frame (driven by the
|
||||||
|
* parent's rAF-updated currentTime).
|
||||||
|
*/
|
||||||
|
export function MainWaveform({ cols, currentTime, duration, onSeek }: Props) {
|
||||||
|
const wrapRef = useRef<HTMLDivElement>(null)
|
||||||
|
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||||
|
const [secPerView, setSecPerView] = useState(DEFAULT_SEC)
|
||||||
|
|
||||||
|
// Draw closes over the latest props/state; a ref lets the ResizeObserver call
|
||||||
|
// the current version without re-subscribing.
|
||||||
|
const draw = () => {
|
||||||
|
const canvas = canvasRef.current
|
||||||
|
const wrap = wrapRef.current
|
||||||
|
if (!canvas || !wrap) return
|
||||||
|
const dpr = window.devicePixelRatio || 1
|
||||||
|
const w = Math.max(1, Math.floor(wrap.clientWidth * dpr))
|
||||||
|
const h = Math.max(1, Math.floor(wrap.clientHeight * dpr))
|
||||||
|
if (canvas.width !== w) canvas.width = w
|
||||||
|
if (canvas.height !== h) canvas.height = h
|
||||||
|
const ctx = canvas.getContext('2d')!
|
||||||
|
ctx.clearRect(0, 0, w, h)
|
||||||
|
|
||||||
|
if (cols.length && duration > 0) {
|
||||||
|
const half = secPerView / 2
|
||||||
|
const startFrac = (currentTime - half) / duration
|
||||||
|
const endFrac = (currentTime + half) / duration
|
||||||
|
paintWave(ctx, cols, w, h, startFrac, endFrac)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fixed centre playhead.
|
||||||
|
const cx = Math.floor(w / 2)
|
||||||
|
ctx.fillStyle = '#e6e9ef'
|
||||||
|
ctx.fillRect(cx, 0, Math.max(1, Math.round(dpr)), h)
|
||||||
|
}
|
||||||
|
|
||||||
|
const drawRef = useRef(draw)
|
||||||
|
drawRef.current = draw
|
||||||
|
|
||||||
|
// Redraw after every render (covers currentTime advancing, zoom, new track).
|
||||||
|
useEffect(() => {
|
||||||
|
draw()
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const wrap = wrapRef.current
|
||||||
|
if (!wrap) return
|
||||||
|
const ro = new ResizeObserver(() => drawRef.current())
|
||||||
|
ro.observe(wrap)
|
||||||
|
return () => ro.disconnect()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
// Click to seek: map horizontal offset from centre to a time delta.
|
||||||
|
const seek = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||||
|
if (!duration) return
|
||||||
|
const rect = e.currentTarget.getBoundingClientRect()
|
||||||
|
const ratioFromCenter = (e.clientX - rect.left) / rect.width - 0.5
|
||||||
|
const t = currentTime + ratioFromCenter * secPerView
|
||||||
|
onSeek(Math.min(duration, Math.max(0, t)))
|
||||||
|
}
|
||||||
|
|
||||||
|
const zoomIn = () => setSecPerView((s) => Math.max(MIN_SEC, s / 2))
|
||||||
|
const zoomOut = () => setSecPerView((s) => Math.min(MAX_SEC, s * 2))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={wrapRef} onClick={seek} className="relative h-full w-full cursor-pointer">
|
||||||
|
<canvas ref={canvasRef} className="block h-full w-full" />
|
||||||
|
|
||||||
|
{/* Zoom controls (Traktor-style +/-) */}
|
||||||
|
<div className="absolute right-2 top-2 flex flex-col gap-1">
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
zoomIn()
|
||||||
|
}}
|
||||||
|
disabled={secPerView <= MIN_SEC}
|
||||||
|
className="flex h-6 w-6 items-center justify-center rounded border border-line bg-ink-950/70 text-sm text-text hover:border-accent disabled:opacity-30"
|
||||||
|
title="Zoom in"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
zoomOut()
|
||||||
|
}}
|
||||||
|
disabled={secPerView >= MAX_SEC}
|
||||||
|
className="flex h-6 w-6 items-center justify-center rounded border border-line bg-ink-950/70 text-sm text-text hover:border-accent disabled:opacity-30"
|
||||||
|
title="Zoom out"
|
||||||
|
>
|
||||||
|
−
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import { useCallback, useEffect, useRef } from 'react'
|
||||||
|
import { paintWave, type WaveColumn } from '../lib/waveform'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
cols: WaveColumn[]
|
||||||
|
currentTime: number
|
||||||
|
duration: number
|
||||||
|
onSeek: (t: number) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whole-track overview waveform: static coloured waveform (cached to an
|
||||||
|
* offscreen canvas) with a moving playhead + dimmed played region. Click to
|
||||||
|
* seek anywhere in the track.
|
||||||
|
*/
|
||||||
|
export function OverviewWaveform({ cols, currentTime, duration, onSeek }: Props) {
|
||||||
|
const wrapRef = useRef<HTMLDivElement>(null)
|
||||||
|
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||||
|
const cacheRef = useRef<HTMLCanvasElement | null>(null)
|
||||||
|
const timeRef = useRef(0)
|
||||||
|
const durRef = useRef(0)
|
||||||
|
|
||||||
|
const renderCache = useCallback(() => {
|
||||||
|
const canvas = canvasRef.current
|
||||||
|
if (!canvas || canvas.width === 0) return
|
||||||
|
let cache = cacheRef.current
|
||||||
|
if (!cache) {
|
||||||
|
cache = document.createElement('canvas')
|
||||||
|
cacheRef.current = cache
|
||||||
|
}
|
||||||
|
cache.width = canvas.width
|
||||||
|
cache.height = canvas.height
|
||||||
|
const ctx = cache.getContext('2d')!
|
||||||
|
ctx.clearRect(0, 0, cache.width, cache.height)
|
||||||
|
paintWave(ctx, cols, cache.width, cache.height, 0, 1)
|
||||||
|
}, [cols])
|
||||||
|
|
||||||
|
const draw = useCallback(() => {
|
||||||
|
const canvas = canvasRef.current
|
||||||
|
const cache = cacheRef.current
|
||||||
|
if (!canvas) return
|
||||||
|
const ctx = canvas.getContext('2d')!
|
||||||
|
const w = canvas.width
|
||||||
|
const h = canvas.height
|
||||||
|
ctx.clearRect(0, 0, w, h)
|
||||||
|
if (cache) ctx.drawImage(cache, 0, 0)
|
||||||
|
const dur = durRef.current
|
||||||
|
if (dur > 0) {
|
||||||
|
const px = Math.round((timeRef.current / dur) * w)
|
||||||
|
ctx.fillStyle = 'rgba(10,11,15,0.55)'
|
||||||
|
ctx.fillRect(0, 0, px, h)
|
||||||
|
ctx.fillStyle = '#e6e9ef'
|
||||||
|
ctx.fillRect(px, 0, 1, h)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const resize = useCallback(() => {
|
||||||
|
const canvas = canvasRef.current
|
||||||
|
const wrap = wrapRef.current
|
||||||
|
if (!canvas || !wrap) return
|
||||||
|
const dpr = window.devicePixelRatio || 1
|
||||||
|
canvas.width = Math.max(1, Math.floor(wrap.clientWidth * dpr))
|
||||||
|
canvas.height = Math.max(1, Math.floor(wrap.clientHeight * dpr))
|
||||||
|
renderCache()
|
||||||
|
draw()
|
||||||
|
}, [renderCache, draw])
|
||||||
|
|
||||||
|
// Rebuild the cache when the columns change (new track) or on resize.
|
||||||
|
useEffect(() => {
|
||||||
|
resize()
|
||||||
|
}, [resize])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const wrap = wrapRef.current
|
||||||
|
if (!wrap) return
|
||||||
|
const ro = new ResizeObserver(() => resize())
|
||||||
|
ro.observe(wrap)
|
||||||
|
return () => ro.disconnect()
|
||||||
|
}, [resize])
|
||||||
|
|
||||||
|
// Move the playhead as playback advances.
|
||||||
|
useEffect(() => {
|
||||||
|
timeRef.current = currentTime
|
||||||
|
durRef.current = duration
|
||||||
|
draw()
|
||||||
|
}, [currentTime, duration, draw])
|
||||||
|
|
||||||
|
const seek = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||||
|
if (!duration) return
|
||||||
|
const rect = e.currentTarget.getBoundingClientRect()
|
||||||
|
const ratio = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width))
|
||||||
|
onSeek(ratio * duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={wrapRef} onClick={seek} className="h-full w-full cursor-pointer">
|
||||||
|
<canvas ref={canvasRef} className="block h-full w-full" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
import { api, type Track } from '../api'
|
||||||
|
import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
|
||||||
|
import { MainWaveform } from './MainWaveform'
|
||||||
|
import { OverviewWaveform } from './OverviewWaveform'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
/** The track currently loaded into the prep deck, if any. */
|
||||||
|
track: Track | null
|
||||||
|
onError?: (msg: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmt(secs: number): string {
|
||||||
|
if (!isFinite(secs) || secs < 0) return '0:00'
|
||||||
|
const m = Math.floor(secs / 60)
|
||||||
|
const s = Math.floor(secs % 60)
|
||||||
|
return `${m}:${s.toString().padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The DJ-style "prep strip" across the top of the window: transport controls on
|
||||||
|
* the left, waveforms on the right (a scrolling zoomable main view above a
|
||||||
|
* whole-track overview). Playback is driven by a single hidden <audio> element
|
||||||
|
* streamed from the backend (range-enabled, so seeking works). The frequency-
|
||||||
|
* coloured waveform is analysed once here and shared by both views.
|
||||||
|
*/
|
||||||
|
export function PrepStrip({ track, onError }: Props) {
|
||||||
|
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||||
|
const [playing, setPlaying] = useState(false)
|
||||||
|
const [current, setCurrent] = useState(0)
|
||||||
|
const [duration, setDuration] = useState(0)
|
||||||
|
const [loadError, setLoadError] = useState(false)
|
||||||
|
const [cols, setCols] = useState<WaveColumn[] | null>(null)
|
||||||
|
const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading')
|
||||||
|
|
||||||
|
const trackId = track?.id ?? null
|
||||||
|
|
||||||
|
// When the loaded track changes, reset transport state. The <audio> src is
|
||||||
|
// bound declaratively below, so changing trackId swaps the source.
|
||||||
|
useEffect(() => {
|
||||||
|
setPlaying(false)
|
||||||
|
setCurrent(0)
|
||||||
|
setDuration(0)
|
||||||
|
setLoadError(false)
|
||||||
|
}, [trackId])
|
||||||
|
|
||||||
|
// Analyse the waveform once per track; both waveform views share the result.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!trackId) {
|
||||||
|
setCols(null)
|
||||||
|
setWaveStatus('loading')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let cancelled = false
|
||||||
|
setCols(null)
|
||||||
|
setWaveStatus('loading')
|
||||||
|
analyzeWaveform(api.audioUrl(trackId))
|
||||||
|
.then((c) => {
|
||||||
|
if (cancelled) return
|
||||||
|
setCols(c)
|
||||||
|
setWaveStatus('ready')
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!cancelled) setWaveStatus('error')
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
|
}, [trackId])
|
||||||
|
|
||||||
|
const toggle = () => {
|
||||||
|
const el = audioRef.current
|
||||||
|
if (!el || !track) return
|
||||||
|
if (el.paused) {
|
||||||
|
el.play().catch(() => {
|
||||||
|
setLoadError(true)
|
||||||
|
setPlaying(false)
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
el.pause()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Smoothly advance the playhead/time while playing (timeupdate is only ~4Hz).
|
||||||
|
useEffect(() => {
|
||||||
|
if (!playing) return
|
||||||
|
let raf = 0
|
||||||
|
const tick = () => {
|
||||||
|
const el = audioRef.current
|
||||||
|
if (el) setCurrent(el.currentTime)
|
||||||
|
raf = requestAnimationFrame(tick)
|
||||||
|
}
|
||||||
|
raf = requestAnimationFrame(tick)
|
||||||
|
return () => cancelAnimationFrame(raf)
|
||||||
|
}, [playing])
|
||||||
|
|
||||||
|
const seek = (t: number) => {
|
||||||
|
const el = audioRef.current
|
||||||
|
if (!el) return
|
||||||
|
el.currentTime = t
|
||||||
|
setCurrent(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
const showWaves = track && !loadError && cols && waveStatus === 'ready'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-52 shrink-0 items-stretch gap-px border-b border-line bg-ink-950">
|
||||||
|
{/* Controls */}
|
||||||
|
<div className="flex w-72 shrink-0 flex-col justify-between bg-ink-900 px-4 py-3">
|
||||||
|
<div className="min-w-0">
|
||||||
|
{track ? (
|
||||||
|
<>
|
||||||
|
<div className="truncate text-sm font-semibold text-text" title={track.title ?? ''}>
|
||||||
|
{track.title ?? 'Untitled'}
|
||||||
|
</div>
|
||||||
|
<div className="truncate text-xs text-muted" title={track.artist ?? ''}>
|
||||||
|
{track.artist ?? 'Unknown artist'}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="text-xs uppercase tracking-wider text-faint">No track loaded</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<button
|
||||||
|
onClick={toggle}
|
||||||
|
disabled={!track || loadError}
|
||||||
|
className="flex h-9 w-9 items-center justify-center rounded-full border border-line bg-ink-850 text-text hover:border-accent disabled:opacity-40 disabled:hover:border-line"
|
||||||
|
title={playing ? 'Pause' : 'Play'}
|
||||||
|
>
|
||||||
|
{playing ? '❚❚' : '▶'}
|
||||||
|
</button>
|
||||||
|
<div className="tabular-nums text-xs text-faint">
|
||||||
|
{fmt(current)} / {fmt(duration)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Waveforms: scrolling main view above a whole-track overview. */}
|
||||||
|
<div className="relative flex min-w-0 flex-1 flex-col bg-ink-900">
|
||||||
|
{!track ? (
|
||||||
|
<div className="flex flex-1 items-center justify-center text-xs text-faint">
|
||||||
|
Load a track to prep it
|
||||||
|
</div>
|
||||||
|
) : loadError ? (
|
||||||
|
<div className="flex flex-1 items-center justify-center text-xs text-pink">
|
||||||
|
Could not load audio — file may be missing or unsupported by the browser.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="relative min-h-0 flex-1">
|
||||||
|
{showWaves ? (
|
||||||
|
<MainWaveform
|
||||||
|
cols={cols}
|
||||||
|
currentTime={current}
|
||||||
|
duration={duration}
|
||||||
|
onSeek={seek}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="flex h-full items-center justify-center text-xs text-faint">
|
||||||
|
{waveStatus === 'error' ? 'Waveform unavailable' : 'Analysing waveform…'}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="h-10 shrink-0 border-t border-line">
|
||||||
|
{showWaves && (
|
||||||
|
<OverviewWaveform
|
||||||
|
cols={cols}
|
||||||
|
currentTime={current}
|
||||||
|
duration={duration}
|
||||||
|
onSeek={seek}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{track && (
|
||||||
|
<audio
|
||||||
|
ref={audioRef}
|
||||||
|
src={api.audioUrl(track.id)}
|
||||||
|
onPlay={() => setPlaying(true)}
|
||||||
|
onPause={() => setPlaying(false)}
|
||||||
|
onEnded={() => setPlaying(false)}
|
||||||
|
onTimeUpdate={(e) => setCurrent(e.currentTarget.currentTime)}
|
||||||
|
onLoadedMetadata={(e) => setDuration(e.currentTarget.duration)}
|
||||||
|
onError={() => {
|
||||||
|
setLoadError(true)
|
||||||
|
onError?.('Could not load audio for this track')
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
// Frequency-colored waveform analysis (Traktor "Spectrum" theme).
|
||||||
|
//
|
||||||
|
// The audio is downmixed to mono and split into three frequency bands with
|
||||||
|
// native BiquadFilters (via OfflineAudioContext — fast, off the main thread).
|
||||||
|
// Per output column we keep each band's RMS energy plus the amplitude peak.
|
||||||
|
// Colour = balance of the three bands (bass→red, mids→green, highs→blue);
|
||||||
|
// height = amplitude. This mirrors how Traktor's Spectrum waveform reads.
|
||||||
|
|
||||||
|
export interface WaveColumn {
|
||||||
|
peak: number // 0..1 amplitude (column height)
|
||||||
|
r: number // 0..1 colour channels (already contrast-boosted)
|
||||||
|
g: number
|
||||||
|
b: number
|
||||||
|
}
|
||||||
|
|
||||||
|
// Band crossover choices. Independent filters, so band energies don't strictly
|
||||||
|
// partition — that's fine, colour is normalised per column.
|
||||||
|
const LOW_HZ = 250
|
||||||
|
const MID_HZ = 1200
|
||||||
|
const MID_Q = 0.6
|
||||||
|
const HIGH_HZ = 5000
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paint a slice of the analysed columns across a canvas: source columns in the
|
||||||
|
* fractional range [startFrac, endFrac) (of the whole track) are mapped across
|
||||||
|
* the full canvas width, aggregating multiple columns per pixel (max peak,
|
||||||
|
* averaged colour). Fractions outside [0,1] paint blank — used by the scrolling
|
||||||
|
* main view so the lead-in/lead-out past the track edges stays empty.
|
||||||
|
*/
|
||||||
|
export function paintWave(
|
||||||
|
ctx: CanvasRenderingContext2D,
|
||||||
|
cols: WaveColumn[],
|
||||||
|
w: number,
|
||||||
|
h: number,
|
||||||
|
startFrac: number,
|
||||||
|
endFrac: number,
|
||||||
|
): void {
|
||||||
|
const n = cols.length
|
||||||
|
if (n === 0 || w === 0 || h === 0) return
|
||||||
|
const mid = h / 2
|
||||||
|
const span = (endFrac - startFrac) * n
|
||||||
|
for (let x = 0; x < w; x++) {
|
||||||
|
const c0 = startFrac * n + (x / w) * span
|
||||||
|
const c1 = startFrac * n + ((x + 1) / w) * span
|
||||||
|
const i0 = Math.floor(c0)
|
||||||
|
const i1 = Math.max(i0 + 1, Math.ceil(c1))
|
||||||
|
let peak = 0
|
||||||
|
let r = 0
|
||||||
|
let g = 0
|
||||||
|
let b = 0
|
||||||
|
let count = 0
|
||||||
|
for (let i = i0; i < i1; i++) {
|
||||||
|
if (i < 0 || i >= n) continue
|
||||||
|
const col = cols[i]
|
||||||
|
if (col.peak > peak) peak = col.peak
|
||||||
|
r += col.r
|
||||||
|
g += col.g
|
||||||
|
b += col.b
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
if (count === 0) continue // outside the track → blank pixel
|
||||||
|
r /= count
|
||||||
|
g /= count
|
||||||
|
b /= count
|
||||||
|
const half = Math.max(0.5, peak * (mid - 1))
|
||||||
|
ctx.fillStyle = `rgb(${(r * 255) | 0},${(g * 255) | 0},${(b * 255) | 0})`
|
||||||
|
ctx.fillRect(x, mid - half, 1, half * 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function analyzeWaveform(url: string, buckets?: number): Promise<WaveColumn[]> {
|
||||||
|
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)
|
||||||
|
} finally {
|
||||||
|
void ctx.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
const len = audio.length
|
||||||
|
const sr = audio.sampleRate
|
||||||
|
const chs = audio.numberOfChannels
|
||||||
|
|
||||||
|
// 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)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
const scale = buckets / len
|
||||||
|
const lowE = new Float64Array(buckets)
|
||||||
|
const midE = new Float64Array(buckets)
|
||||||
|
const highE = new Float64Array(buckets)
|
||||||
|
const peak = new Float64Array(buckets)
|
||||||
|
const cnt = new Float64Array(buckets)
|
||||||
|
|
||||||
|
// Amplitude peak + sample count per column (from the mono mix).
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
const b = (i * scale) | 0
|
||||||
|
const a = Math.abs(mono[i])
|
||||||
|
if (a > peak[b]) peak[b] = a
|
||||||
|
cnt[b]++
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render one band through a native filter, accumulate its energy, then let the
|
||||||
|
// rendered buffer be GC'd before the next band (keeps peak memory to ~2 copies).
|
||||||
|
const accumBand = async (
|
||||||
|
target: Float64Array,
|
||||||
|
type: BiquadFilterType,
|
||||||
|
freq: number,
|
||||||
|
q?: number,
|
||||||
|
) => {
|
||||||
|
const off = new OfflineAudioContext(1, len, sr)
|
||||||
|
const buf = off.createBuffer(1, len, sr)
|
||||||
|
buf.copyToChannel(mono, 0)
|
||||||
|
const src = off.createBufferSource()
|
||||||
|
src.buffer = buf
|
||||||
|
const filter = off.createBiquadFilter()
|
||||||
|
filter.type = type
|
||||||
|
filter.frequency.value = freq
|
||||||
|
if (q != null) filter.Q.value = q
|
||||||
|
src.connect(filter)
|
||||||
|
filter.connect(off.destination)
|
||||||
|
src.start()
|
||||||
|
const rendered = await off.startRendering()
|
||||||
|
const data = rendered.getChannelData(0)
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
const b = (i * scale) | 0
|
||||||
|
target[b] += data[i] * data[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await accumBand(lowE, 'lowpass', LOW_HZ)
|
||||||
|
await accumBand(midE, 'bandpass', MID_HZ, MID_Q)
|
||||||
|
await accumBand(highE, 'highpass', HIGH_HZ)
|
||||||
|
|
||||||
|
let maxPeak = 1e-6
|
||||||
|
for (let b = 0; b < buckets; b++) if (peak[b] > maxPeak) maxPeak = peak[b]
|
||||||
|
|
||||||
|
const cols: WaveColumn[] = new Array(buckets)
|
||||||
|
for (let b = 0; b < buckets; b++) {
|
||||||
|
const n = cnt[b] || 1
|
||||||
|
const l = Math.sqrt(lowE[b] / n)
|
||||||
|
const m = Math.sqrt(midE[b] / n)
|
||||||
|
const h = Math.sqrt(highE[b] / n)
|
||||||
|
// Normalise to the dominant band so colours stay vivid (brightness is not
|
||||||
|
// tied to loudness — amplitude is shown by height, like Traktor). Gamma
|
||||||
|
// sharpens the separation between bands.
|
||||||
|
const mx = Math.max(l, m, h, 1e-9)
|
||||||
|
cols[b] = {
|
||||||
|
peak: peak[b] / maxPeak,
|
||||||
|
r: Math.pow(l / mx, 1.3),
|
||||||
|
g: Math.pow(m / mx, 1.3),
|
||||||
|
b: Math.pow(h / mx, 1.3),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cols
|
||||||
|
}
|
||||||
Reference in new issue
Block a user