Compare commits

...
20 Commits
Author SHA1 Message Date
patben8 83b0978b14 Merge pull request #10 from MrPatben8/dev
Implemented Raw Waveform View
2026-10-15 17:51:59 +02:00
patben8 0ced274f73 Bumped version number 2026-10-15 17:48:40 +02:00
patben8 fc4e7804b3 Changed how patchnotes are compiled 2026-10-15 17:48:17 +02:00
patben8 77b063ba0e Implemented time readout accuracy setting 2026-10-15 17:42:26 +02:00
patben8 16c3552be6 Changed option keyboard shortcuts to use command instead 2026-10-15 16:36:10 +02:00
patben8 32cfb034e2 Implemented better shortcut menu 2026-10-15 16:30:34 +02:00
patben8 b70798a0fe Implemented track info dialog popup 2026-10-15 15:46:39 +02:00
patben8 4c51f57fe9 Improved context menu positioning when near the bottom of the window 2026-10-15 14:22:40 +02:00
patben8 7b2d6de411 Implemented new set playlist position mode 2026-10-15 10:48:14 +02:00
patben8 8230722105 Implemented raw waveform mode 2026-10-15 10:26:41 +02:00
patben8 1464b1e211 Merge pull request #9 from MrPatben8/dev
Fixed issues on Windows, Implemented drag & drop importing, Improved STEM encoding speed
2026-10-13 17:47:09 +02:00
patben8 10f175b206 Bumped version number 2026-10-13 17:43:20 +02:00
patben8 a65ef959b2 Implemented drag to import 2026-10-13 17:42:24 +02:00
patben8 87cbd3720e Fixed STEM analysis not working on Windows 2026-10-13 10:59:22 +02:00
patben8 591f2bc791 Pararellized STEM aac encoding 2026-10-13 10:45:52 +02:00
patben8 ebe30c1128 Fixed analysis not working on windows 2026-10-12 23:49:19 +02:00
patben8 cd1914216f Fixed library options not appearing in windows 2026-10-12 23:26:33 +02:00
patben8 d10b11f8eb Merge pull request #8 from MrPatben8/dev
Fixed Rekordbox exports
2026-10-12 19:12:41 +02:00
patben8 79a8a843c5 Bumped version number 2026-10-12 19:12:09 +02:00
patben8 0204a322ff Fixed and pinned rekordbox exports 2026-10-12 19:10:20 +02:00
59 changed files with 3328 additions and 425 deletions

No files matched your search

+40 -1
View File
@@ -169,6 +169,7 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: write # required to create the tag + release
pull-requests: read # to read the merged PR's patch notes
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -188,12 +189,50 @@ jobs:
pattern: konduktor-*
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
# Release notes from the "Patch notes" section of the PR that merged this
# commit into main (dev → main merges carry many features in one PR, so
# its title alone says little). Written under "What's Changed", the
# heading the app's update dialog reads. No PR (a manual run, a direct
# push) or no such section → GitHub's generated notes, as before.
- name: Patch notes from the merged PR
id: notes
env:
GH_TOKEN: ${{ github.token }}
run: |
gh api "repos/${{ github.repository }}/commits/${{ github.sha }}/pulls" \
--jq '[.[] | select(.base.ref == "main" and .merged_at != null)][0].body // ""' \
> pr-body.md || : > pr-body.md
python3 - <<'EOF'
import os, re
body = open("pr-body.md", encoding="utf-8").read().replace("\r\n", "\n")
body = re.sub(r"<!--.*?-->", "", body, flags=re.S)
section, level = [], None
for line in body.split("\n"):
m = re.match(r"^(#{1,6})\s+(.*?)\s*#*\s*$", line)
if level is None:
if m and re.fullmatch(r"patch[\s-]?notes:?", m.group(2), re.I):
level = len(m.group(1))
elif m and len(m.group(1)) <= level:
break
else:
section.append(line)
notes = "\n".join(section).strip()
found = bool(notes)
if found:
with open("release-notes.md", "w", encoding="utf-8") as f:
f.write("## What's Changed\n\n" + notes + "\n")
with open(os.environ["GITHUB_OUTPUT"], "a") as out:
out.write(f"found={'true' if found else 'false'}\n")
print("Using the PR's patch notes." if found else "No patch notes section; using generated notes.")
EOF
- name: Publish release
uses: softprops/action-gh-release@v2
with:
tag_name: v${{ steps.version.outputs.version }}-b${{ github.run_number }}
name: Konduktor v${{ steps.version.outputs.version }}-b${{ github.run_number }}
target_commitish: ${{ github.sha }}
generate_release_notes: true # auto changelog from commits/PRs since last release
body_path: ${{ steps.notes.outputs.found == 'true' && 'release-notes.md' || '' }}
generate_release_notes: ${{ steps.notes.outputs.found != 'true' }}
fail_on_unmatched_files: true
files: artifacts/**/*
+100 -29
View File
@@ -1,21 +1,27 @@
# Building Konduktor for Windows
The desktop app can't be cross-compiled — a Windows build must be produced **on
Windows** (Tauri needs the MSVC toolchain + WebView2; PyInstaller must freeze the
backend into a Windows `.exe`). The macOS `.dmg` is built separately on a Mac.
The desktop app can't be cross-compiled. A Windows build must be produced **on
Windows**: Tauri needs the MSVC toolchain and WebView2, and PyInstaller must
freeze the backend into a Windows `.exe`. The macOS `.dmg` is built separately
on a Mac (see [docs/BUILDING.md](docs/BUILDING.md)).
This mirrors the macOS build exactly; only the toolchain install and the
sidecar-build command differ.
The recipe is the same as on macOS. Only the toolchain install and the
sidecar-build command differ. CI does exactly this on `windows-latest`
([.github/workflows/build.yml](.github/workflows/build.yml)), so if a local build
disagrees with CI, check that workflow first.
## One-time setup
1. **Rust** — install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
1. **Rust**: install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
toolchain). You also need the **MSVC C++ build tools**: install "Desktop
development with C++" from the Visual Studio Build Tools installer.
2. **WebView2 Runtime** — preinstalled on current Windows 10/11. If missing, get
the Evergreen runtime from Microsoft (Tauri's installer can also bootstrap it).
3. **Python 3.11–3.14** — <https://python.org> (tick "Add to PATH").
4. **Node 18+** — <https://nodejs.org>.
2. **WebView2 Runtime**: preinstalled on current Windows 10/11. If it's missing,
get the Evergreen runtime from Microsoft (Tauri's installer can also
bootstrap it).
3. **Python 3.11–3.14**: <https://python.org> (tick "Add to PATH"). CI builds
with **3.12**, the safest choice.
4. **Node 20.19+ or 22.12+**: <https://nodejs.org>. Vite 8 refuses older
versions, so Node 18 no longer works. CI uses Node 20.
Then, from the repo root:
@@ -33,50 +39,115 @@ npm install
cd ..
```
## Build
If PowerShell refuses to run `Activate.ps1` or `dev.ps1` ("running scripts is
disabled on this system"), either allow local scripts once with
`Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`, or run a script with
`powershell -ExecutionPolicy Bypass -File .\dev.ps1`.
## Develop (no build)
```powershell
.\dev.ps1 # backend on :8000 + Vite on :5173, both reloading; Ctrl-C stops both
```
Then open <http://localhost:5173> in a browser. `dev.ps1` is the Windows
counterpart of `dev.sh`. It needs the `backend\.venv` and `frontend\node_modules`
from the setup above. It runs the Python source, not the frozen sidecar, so it
can't show desktop-shell behaviour (startup screen, quit prompt, WebView2, file
drops from Explorer). For that, run `npx tauri dev` in `frontend`. Note that this
still spawns the **frozen** sidecar staged in `src-tauri\binaries\`, so backend
changes need `build_sidecar.ps1` first.
### Tests
`backend/run_tests.sh` expects a POSIX venv (`.venv/bin/activate`), so it won't
run as-is on Windows. Run a suite directly with the venv's Python instead:
```powershell
# 1) Freeze + stage the backend sidecar (from the activated backend venv)
cd backend
.\.venv\Scripts\Activate.ps1 # if not already active
.\.venv\Scripts\python.exe test_save_fidelity.py
```
## Build
One command does both steps and lists the installers it produced:
```powershell
.\build.ps1 # sidecar + app
.\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar
.\build.ps1 --debug # any other argument is passed on to `tauri build`
```
By hand, that is:
```powershell
# 1) Freeze + stage the backend sidecar
cd backend
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder)
cd ..
# 2) Build the app
# 2) Build the app (its beforeBuildCommand runs the Vite build)
cd frontend
npx tauri build
```
`build_sidecar.ps1` uses `backend\.venv\Scripts\python.exe` when it exists (else
whatever `python` resolves to), so the venv doesn't need to be activated. It
replaces the whole staged folder, so no file from an older build survives.
The sidecar is a PyInstaller **onedir** folder (`konduktor-sidecar.exe` plus
`_internal\`), not a single `.exe`. Don't switch it back to onefile; see
gotcha 4 in [CLAUDE.md](CLAUDE.md).
## Output
Installers land in:
```
frontend\src-tauri\target\release\bundle\msi\Konduktor_0.1.0_x64_en-US.msi
frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_x64-setup.exe
frontend\src-tauri\target\release\bundle\nsis\Konduktor_<version>_x64-setup.exe
frontend\src-tauri\target\release\bundle\msi\Konduktor_<version>_x64_en-US.msi
```
Either one installs the app, with the sidecar folder in its `sidecar\` resource
folder (`tauri.windows.conf.json`).
`<version>` is the `version` in [frontend/package.json](frontend/package.json),
the app's only version source. Either installer works. Releases ship only the
NSIS `-setup.exe`. Both put the sidecar folder in the app's `sidecar\` resource
folder (`tauri.windows.conf.json` → `bundle.resources`), where `lib.rs` spawns
`sidecar\konduktor-sidecar.exe`.
## Rebuilding after changes
Same as macOS: if you changed **backend** Python, re-run `build_sidecar.ps1`
first; then `npx tauri build`. Frontend-only changes just need `npx tauri build`
(its `beforeBuildCommand` rebuilds the web app).
If you changed **backend** Python, run `.\build.ps1` (or `build_sidecar.ps1`,
then `npx tauri build`). Frontend-only changes just need
`.\build.ps1 -SkipSidecar` (or `npx tauri build`).
## Not part of this build: the stem engine
Convert to Stems uses a separate program, `engine/` (torch + demucs), built and
released on its own channel by
[.github/workflows/engine.yml](.github/workflows/engine.yml) (`windows-x64-cpu`
and `windows-x64-cuda`). The app downloads it at runtime into a short
`%LOCALAPPDATA%\Konduktor\engine` path to stay under Windows' 260-character path
limit. You don't need it to build or run the app.
## Known Windows caveats
- **Unsigned build → SmartScreen.** We don't code-sign yet, so the first launch
shows a "Windows protected your PC" prompt. Click **More info → Run anyway**.
(Signing is a future step.)
- **Unsigned build → SmartScreen.** Builds aren't code-signed yet, so the first
launch shows a "Windows protected your PC" prompt. Click **More info → Run
anyway**.
- **Mixed content is already handled.** The webview is forced to the `http`
custom-protocol scheme (`use_https_scheme(false)` in `src-tauri/src/lib.rs`) so
it can fetch the sidecar at `http://127.0.0.1:<port>` without being blocked.
Leave that setting as-is.
- **Sidecar console window.** The sidecar is frozen as a console app (needed for
the `KONDUKTOR_PORT` stdout handshake). Tauri's shell plugin normally spawns it
without a visible window; if a console flashes on launch, tell me and we'll add
the `CREATE_NO_WINDOW` spawn flag.
- **The sidecar must be frozen on Windows** — a macOS-built sidecar won't run.
- **The sidecar is a console app, but no console appears.** It's frozen with
`console=True` because the shell reads the `KONDUKTOR_PORT=<n>` line from its
stdout. Tauri's shell plugin spawns it with `CREATE_NO_WINDOW`, so no window
flashes.
- **The sidecar doesn't watch stdin on Windows.** On macOS it exits when its
stdin closes. On Windows a pending stdin read stalled loading scipy's OpenBLAS
DLL, which hung the first analysis, so it waits on the parent process instead
(`backend/sidecar.py`). Keep this in mind before touching that watcher.
- **Decode audio through `waveform.load`, never `librosa.load`.** librosa reads
AAC only through CoreAudio or a system ffmpeg, so on Windows every `.m4a` /
`.stem.m4a` failed with "Format not recognised". PyAV bundles FFmpeg.
- **The sidecar must be frozen on Windows.** A macOS-built sidecar won't run.
`build_sidecar.ps1` handles this; just don't copy binaries between OSes.
+91 -20
View File
@@ -170,7 +170,14 @@ Two independent apps that talk over HTTP:
file** (Convert to Stems). An `ipod` MP4 with five AAC stereo 44.1 kHz
streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0,
muxed IN LOCKSTEP, plus a `moov/udta/stem` JSON box appended in place
(moov is last, so only two sizes change). The separation is a CALLBACK —
(moov is last, so only two sizes change). **Each stream encodes on its
own thread** (PyAV releases the GIL in FFmpeg; ~3x faster with `aac`,
104 → 35 s for a 5-minute track's real stems) while ONE thread muxes in
the single-threaded order, so the file is byte-identical; every codec is
opened and the header written before a worker starts, since the first
`mux()` would otherwise open codecs a worker is using. `aac_coder=fast`
was measured and rejected: 3-4x faster per stream, but it drops whole
8-20 kHz bands for moments (twoloop: never). The separation is a CALLBACK —
the backend never imports torch; the engine (below) supplies it, the
tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB,
so mono is duplicated by hand; resampling does not move time; both
@@ -863,7 +870,7 @@ Two independent apps that talk over HTTP:
too, so nested playlists are reachable). Tracks dropped on a playlist go
through `lib/addTracks.ts` — shared with the context menu's "Add to" —
which ASKS about duplicates where the platform can hold them (decided:
ask each time), and Option/Alt moves them out of the editable playlist
ask each time), and Cmd (Ctrl on Windows; `lib/modKey.ts`) moves them out of the editable playlist
they came from. A device's or Files folder's tracks open `ImportDialog`
(`trackIds` + `target`) / `AddFilesDialog` with the target filled in
(`onAddForeign`), so copy-vs-reference is still asked. Export rows take the
@@ -886,7 +893,7 @@ Two independent apps that talk over HTTP:
/ Try again (`backend_restart`). The shell has no timeout of its own. Before
ready it answers quit requests itself — nothing can be unsaved — and stops
at ready so it never races `QuitGuard`), `SaveBar` (+ "Discard changes…" when
dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder`. The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
dirty, and the settings gear beside it, whose menu (or `?` anywhere) opens `ShortcutsDialog` — a KEYBOARD MAP (decided 2026-10-15): keys lit in the colour of what they do, a caption explaining the key pointed at or pressed (pressing explains, it never acts: a capture-phase listener keeps the deck's and table's keys from firing), holding or picking ⇧ / Cmd-Ctrl relights it with that layer, mouse gestures listed beneath. It shrinks to fit the dialog and drops the words on the keys when too small. Its content is `lib/shortcuts.ts`, written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder` — and `timeReadoutDecimals` (0–3, default 1: the deck's ELAPSED / REMAIN, truncated, never rounded). The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
`TrackTable` (**the one track list** — All Tracks, playlists, exports and
devices. TanStack Table + **virtualized** grid; per-row play button,
configurable columns, header sorting, inline double-click editing, and
@@ -908,7 +915,7 @@ Two independent apps that talk over HTTP:
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.
Every table's rows are a DRAG SOURCE through `lib/drag.tsx` (a selected row
carries the selection, the payload's `lead` is the row grabbed, `dragFrom`
says whose ids they are and which editable playlist an Option-drag leaves);
says whose ids they are and which editable playlist a Cmd/Ctrl-drag leaves — a Cmd/Ctrl press arms a drag, and stays a toggle-click if it never moves);
the in-table reorder is just the table's own drop target.)
**`lib/drag.tsx` — drag and drop across the window** (decided 2026-10-06,
[the discussion](.claude/discussions/discuss-drag-and-drop-2026-10-06.md)):
@@ -927,6 +934,21 @@ Two independent apps that talk over HTTP:
could not be dropped on. Targets: playlist + export rows (Sidebar,
ExportsSection), the tree's zones, the table's reorder, and the DECK
(App), which loads the grabbed row paused, in its own origin.
**Files from Finder / Explorer** (decided 2026-10-13) ride the same store
as a `files` payload: `lib/fileDrop.ts` feeds Tauri's `onDragDropEvent`
(real paths; a plain browser has none, so no file drop there) through
`nativeDragStart`/`Move`/`End`, refused at enter while an `aria-modal`
dialog is open or no library is loaded. A playlist/export row opens
`AddFilesDialog` with its target, ONE audio file on the deck loads it to
listen to, anywhere else (App's root target, with a window overlay) adds
to the collection — or says why the library cannot. `POST
/api/folder/dropped` resolves the paths first (`FolderScanner.dropped`:
folders RECURSIVELY, capped at `MAX_DROPPED`; single files held apart
from the folder cache so a partial listing never hides a folder's other
files from the sidebar) and makes each file addable and playable through
the folder routes. Copy vs in place is asked as for a browsed folder; the
add preview counts external-drive files PER FILE (`removable_count` /
`removable_drives`, a drop can mix drives) and `in_destination`.
`ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where =
Replace the originals (its option STATES that Save deletes them, since
the choice is remembered and may be preselected) or Save to a folder; In
@@ -974,9 +996,12 @@ Two independent apps that talk over HTTP:
column chooser uses those; "Add to" lists
playlists + exports and acts on the whole selection; in an editable
playlist "Set Position…" (`SetPositionDialog`, `lib/playlistOrder.ts`)
moves the selection as ONE block in playlist order so its first track
lands at #N — allowed while sorted/filtered, unlike drag, because it
reorders the FULL entry list; "Remove ▸" holds
moves the selection as ONE block so its first track lands at #N —
allowed while sorted/filtered, unlike drag, because it reorders the FULL
entry list. While the table is sorted the dialog asks the block's Order:
"As sorted" (default; the menu's ids arrive in VIEW order, so the sort is
written into the playlist and survives clearing it) or playlist order;
"Remove ▸" holds
From this playlist / From this export / Grids / Hotcues / From collection,
each behind a `ConfirmDialog` — as is the playlist Delete key. Enter
confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog`
@@ -1004,7 +1029,7 @@ Two independent apps that talk over HTTP:
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);
button at each lane's left edge (click = mute, Cmd/Ctrl-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
@@ -1015,8 +1040,10 @@ Two independent apps that talk over HTTP:
badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` —
click to type an exact BPM; with no grid, a typed or tapped BPM CREATES one at the playhead, and
Set grid on a track with no BPM opens the readout to ask rather than failing), SNAP, Analyze, Auto hotcues. **Waveforms**:
`MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll, owned
by `PrepStrip` so it survives track switches and persists) over
`MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll,
0.25–64 s across, owned by `PrepStrip` so it survives track switches and
persists; a toggle under the zoom buttons draws the RAW signal instead
of bars — `lib/rawWave.ts`, below; persisted as `mainWaveRaw`) over
`OverviewWaveform`, which frames the main view's visible range around the
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then EITHER
`HotcueBar` OR — in **Grid mode** — `GridEditStrip`, then `TempoControls`
@@ -1098,6 +1125,7 @@ Two independent apps that talk over HTTP:
```bash
./dev.sh # start both servers (see README for one-time setup)
.\dev.ps1 # the same on Windows (BUILDING-WINDOWS.md)
# Backend
cd backend && source .venv/bin/activate
@@ -1170,7 +1198,10 @@ serialization path.** It enforces:
48 kHz resampling does not move time; MP3 and FLAC through both encoders give
five streams with only the mix enabled, no shift (cross-correlation), the
bitrate rule (256 floor, lossless 320), every tag + cover; `verify` refuses a
shifted, truncated or box-less file; a raising checkpoint cancels.
shifted, truncated or box-less file; a raising checkpoint cancels. The
threaded encode is byte-identical to a single-threaded reference (with each
encoder present), reports progress 0 → 1, and a cancel or a failing encoder
thread leaves no thread running.
- `test_stem_swap.py` — `apply_stem_swaps` on a temp copy of the real
collection with a generated MP3 (with header) and a real stem file: prep
reads back at the same decoded second while its START moves by the 2257-
@@ -1367,7 +1398,11 @@ serialization path.** It enforces:
scan did not find; **a file the collection already points at is never added
twice** (on Traktor that would be two ENTRYs sharing a primary key — a corrupt
collection) but still reaches the playlist/export it was headed for; "copy"
points the entry at the copy and "reference" at the original.
points the entry at the copy and "reference" at the original. And a DROP
(`/api/folder/dropped`): folders recursively minus hidden ones, dropped
non-audio counted as skipped, only what was dropped becomes streamable, the
folder's own listing stays whole, the cap, held files as their collection
track, and the preview's per-file external-drive count and `in_destination`.
- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it
replaced was invisible: `/api/library/options` flattened every driver's
detections and returned `[0]`, so a plugged-in USB stick could be offered as
@@ -1475,14 +1510,18 @@ frontend at `http://localhost:5173`.
1. **`traktor-nml-utils` MUST come from GitHub, not PyPI.** PyPI's `3.1.0` is
stale and **cannot parse Traktor Pro 4 (NML v20)** files — its strict parser
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.
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins a
GitHub commit (v4.0.0). Do not "simplify" this to a plain PyPI pin.
**`pyrekordbox` is now the same situation**: PyPI's latest (0.4.4) has no
`devicelib_plus`, which is the OneLibrary (`exportLibrary.db`) reader, so
`requirements.txt` pins the GitHub master. That upgrade renamed `db6` →
`masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`;
the Rekordbox adapter uses the new names. `db6` still works as a deprecated
alias and is **removed in 0.6.0**.
`onelibrary` module, which is the OneLibrary (`exportLibrary.db`) reader
(`OneLibrary` class; `devicelib_plus` / `DeviceLibraryPlus` before upstream's
rename), nor `masterdb` (formerly `db6`, now removed upstream; `tables` →
`models`, `BLOB` in `masterdb.database`).
**Both GitHub deps are pinned to a COMMIT, never bare master**: the
`devicelib_plus` → `onelibrary` rename reached CI's fresh install while dev
venvs kept the old commit, and a release shipped that could not export or
read OneLibrary while every local test passed. Move a pin on purpose, with
`./run_tests.sh`.
**PyAV: open files for reading through `core/pyav.open_input`, never
`av.open` directly.** PyAV 18 refuses a file with non-UTF-8 tags unless
given `metadata_errors="ignore"`; PyAV 19 removed that keyword. CI installs
@@ -1814,7 +1853,7 @@ that number and nothing else — everything derives from it:
deliberately NOT in the fixture, since they carry the machine's name and
UUIDs; those are generated fresh per export.
- **The two Pioneer key blobs are different.** `masterdb`'s key and
`devicelib_plus`'s are not the same string; mixing them up yields a database
`onelibrary`'s are not the same string; mixing them up yields a database
Rekordbox cannot open.
`adapters/onelibrary/export.py` writes a whole drive (`PIONEER/rekordbox/
exportLibrary.db` from the checked-in DDL, plus ANLZ under `PIONEER/USBANLZ/`,
@@ -2132,6 +2171,38 @@ The prep strip plays every track through the **Web Audio API** (a plain
full scale for whole sections, so a linear map draws a solid orange wall
instead of the kick pulse. The main view draws 2 px bars with a 1 px gap,
**binned in track space** so bars scroll rather than flicker.
- `rawWave.ts` — **the raw waveform** (decided 2026-10-15,
[the discussion](.claude/discussions/discuss-raw-waveform-2026-10-15.md)):
the bars' ~7 ms columns of unsigned band energy hide where a kick starts, so
the main view can draw the signal itself as a thin line, after Traktor at
full zoom. Its own toggle (under the zoom buttons), NOT tied to Grid mode —
tried first, changed after use.
**Shape exact, colour approximate**: the tint is the bar palette weighted by
the ~7 ms band columns, lerped, mixed in OKLab with the CHROMA restored
(`bandColour`) — a plain RGB mean of orange/violet/cyan lands near grey and
read as mud; chosen from five variants rendered on real tracks; the scale is fixed by the track's loudest
sample (no per-view gain, so nothing pumps while scrolling). Each pixel is a
min→max stroke stretched to touch its neighbour's, so it reads as an
envelope zoomed out and a line zoomed in with no switch-over. Data: min/max
per 32 samples summarised at load (~4 MB / 6 min) for wide views; below 128
samples a pixel, the visible window read straight from the `AudioBuffer`
(`copyFromChannel` — no full-length mono copy). Bins sit on a track-space
grid like the bars'. A stem track's lanes each draw their own raw line, in
the stem's colour, each at its own peak floored at 5% of the loudest.
Measured in WKWebView: 0.3 ms a frame at 0.25 s, ~5 ms at 64 s.
- `decodeAlign.ts` — **the deck's decode vs the grid's time base.** Positions
are in the backend's PyAV decode; the deck decodes with `decodeAudioData`.
Measured 2026-10-15 with click files: identical on every format and engine
EXCEPT a **header-less MP3 under WebKit** (the macOS app), decoded 529
samples (12 ms) EARLY — CoreAudio trims the decoder delay with no header to
say so; FFmpeg (and Chromium/WebView2) do not. Invisible under bars, a
12 ms miss on the raw line. The engine's offset is MEASURED once per session
by decoding a built-in 2.7 KB header-less MP3 (`decodeProbe.ts`, click at a
known FFmpeg sample), and a header-less MP3's buffer (`mp3HeaderFrame`, a
port of `core/mp3_gapless.parse` behind an is-it-an-MP3 gate) is padded by
it in `decodeUrl` — so playback, scratch and both waveforms move together.
Not measured: a header without a trusted encoder-delay field; Edge on a real
Windows machine (Chromium on macOS matched).
- `cues.ts` — canvas drawers for cue markers (type-colored), the active loop
band, the beatgrid (per-segment white beats/brighter downbeats, plus marker
lines — gold for the one governing the playhead, accent otherwise, with the
+6 -1
View File
@@ -16,7 +16,12 @@ Set-Location $Root
$Py = Join-Path $Root ".venv\Scripts\python.exe"
if (-not (Test-Path $Py)) { $Py = "python" }
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
# PyInstaller logs to stderr. Windows PowerShell 5.1 (unlike pwsh 7) turns a
# native command's stderr into an error record, which "Stop" makes fatal on the
# first INFO line — so relax it for this call and judge by the exit code.
$ErrorActionPreference = "Continue"
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec 2>&1 | ForEach-Object { "$_" }
$ErrorActionPreference = "Stop"
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" }
Write-Host "Built: $Root\dist\konduktor-sidecar\"
@@ -49,7 +49,7 @@ class OneLibraryDriver:
def _has_onelibrary_schema(path: Path) -> bool:
try:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
except ImportError: # pragma: no cover — dependency missing
return False
@@ -121,7 +121,7 @@ class OneLibraryExporter:
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
root = Path(destination)
@@ -428,8 +428,10 @@ class OneLibraryExporter:
)
#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them.
#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player.
#: rekordbox's `fileType` codes. `.stem.m4a` (a Traktor STEM) is an M4A to a
#: Pioneer player. `pyrekordbox.onelibrary.FileType` now also lists MP4 = 3 (the
#: `.mp4` container) and ALAC = 6 (an ALAC `.m4a`); neither is measured here, so
#: both still write 4.
_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
".aif": 12, ".aiff": 12}
@@ -1,6 +1,6 @@
"""OneLibrary rows -> the generic projection.
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` /
The only place a ``pyrekordbox.onelibrary`` ORM object becomes a generic `Track` /
`TrackCues`. Everything above this file sees generic types exclusively.
Field conventions are read off a real rekordbox 7 export rather than guessed:
+15 -15
View File
@@ -1,7 +1,7 @@
"""The retained native model for a OneLibrary drive.
Owns the drive's ``exportLibrary.db`` and the layout around it, and is the only
place a ``pyrekordbox.devicelib_plus`` row or an ANLZ tag is touched.
place a ``pyrekordbox.onelibrary`` row or an ANLZ tag is touched.
The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but
with a **different and universal key**: every OneLibrary drive from every vendor
@@ -170,10 +170,10 @@ class OneLibraryStore(ReplaceGridCommands):
def _load(self) -> None:
"""Copy the drive's database into app-data and open the copy."""
try:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
from pyrekordbox.onelibrary import OneLibrary
except ImportError as ex: # pragma: no cover — dependency missing
raise LibraryNotSupported(
"Reading OneLibrary drives needs pyrekordbox with devicelib_plus"
"Reading OneLibrary drives needs pyrekordbox with its onelibrary module"
) from ex
_clear_stale_work()
work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root()))
@@ -186,7 +186,7 @@ class OneLibraryStore(ReplaceGridCommands):
sidecar = self.path.with_name(self.path.name + suffix)
if sidecar.is_file() and sidecar.stat().st_size:
shutil.copyfile(sidecar, working.with_name(working.name + suffix))
db = DeviceLibraryPlus(str(working))
db = OneLibrary(str(working))
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
shutil.rmtree(work, ignore_errors=True)
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
@@ -206,7 +206,7 @@ class OneLibraryStore(ReplaceGridCommands):
"""Release the working copy and delete it.
The drive itself is never held open (see the module docstring); the copy
is, and `DeviceLibraryPlus.close()` only unregisters events, so the
is, and `OneLibrary.close()` only unregisters events, so the
session and engine are closed here explicitly.
"""
db, self._db = self._db, None
@@ -316,7 +316,7 @@ class OneLibraryStore(ReplaceGridCommands):
image_id = getattr(self.content(track_id), "image_id", None)
if not image_id:
return None
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none()
small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None
@@ -456,7 +456,7 @@ class OneLibraryStore(ReplaceGridCommands):
"""
if not name:
return None
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
model = getattr(models, model_name)
pk = f"{model.__tablename__}_id"
@@ -497,7 +497,7 @@ class OneLibraryStore(ReplaceGridCommands):
stick already has. A new key gets rekordbox's own spelling."""
if wheel is None or mode is None:
return None
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
from ..rekordbox.projection import parse_key, render_key
@@ -567,7 +567,7 @@ class OneLibraryStore(ReplaceGridCommands):
# ---- writes: playlists --------------------------------------------------
def _playlist(self, node_id: str):
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
try:
pid = int(node_id)
@@ -579,14 +579,14 @@ class OneLibraryStore(ReplaceGridCommands):
return row
def _siblings(self, parent_id: int, *, excluding: int | None = None) -> list:
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
rows = self._require_db().query(models.Playlist).filter_by(playlist_id_parent=parent_id).all()
rows = [r for r in rows if r.playlist_id != excluding]
return sorted(rows, key=lambda r: (int(r.sequenceNo or 0), int(r.playlist_id)))
def _create_node(self, name: str, parent_id: str | None, attribute: int) -> str:
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
name = (name or "").strip()
noun = "folder" if attribute == ATTRIBUTE_FOLDER else "playlist"
@@ -631,7 +631,7 @@ class OneLibraryStore(ReplaceGridCommands):
def delete_playlist(self, node_id: str) -> None:
"""Delete a playlist, or a folder WITH everything in it, and close the gap
its `sequenceNo` leaves among its siblings."""
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
db = self._require_db()
row = self._playlist(node_id)
@@ -693,7 +693,7 @@ class OneLibraryStore(ReplaceGridCommands):
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in order, numbered from 1 (measured)."""
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
db = self._require_db()
playlist = self._playlist(node_id)
@@ -1378,9 +1378,9 @@ class OneLibraryStore(ReplaceGridCommands):
return SaveOutcome(summary=summary, snapshot=None, tag_results=tag_results)
def _reopen_working(self, work: Path) -> None:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
from pyrekordbox.onelibrary import OneLibrary
self._db, self._work = DeviceLibraryPlus(str(work / self.path.name)), work
self._db, self._work = OneLibrary(str(work / self.path.name)), work
self._content_cache = None
self._by_id = None
@@ -125,7 +125,7 @@ class RekordboxExporter:
)
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
# `masterdb`'s OWN key blob. `devicelib_plus` has a different one — a
# `masterdb`'s OWN key blob. `onelibrary` has a different one — a
# OneLibrary drive uses a universal key shared across vendors, and
# master.db does not. Mixing them up produces a database Rekordbox
# cannot open, and pyrekordbox rejects the wrong one outright.
+102 -6
View File
@@ -14,7 +14,9 @@ This is opened by the folder routes and nothing else.
Three rules:
* **This folder only.** Subfolders are not scanned — the tree is how you get to
them — so a click on a drive root never walks the whole drive.
them — so a click on a drive root never walks the whole drive. A folder
DROPPED onto the window is the exception (`FolderScanner.dropped`): the user
asked for everything in it, so it recurses, capped at `MAX_DROPPED`.
* **A track id is the file's absolute path.** It is the one identity a loose
file has, and it is what the audio route checks a request against.
* **Tags are read once per folder state.** Reading tags opens every file, which
@@ -26,6 +28,7 @@ from __future__ import annotations
import logging
import os
import threading
from dataclasses import dataclass, field
from pathlib import Path
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
@@ -165,17 +168,88 @@ class FolderSource:
return capabilities_for(self.path)
# A drop of a whole drive must not read tags for hours: past this many audio
# files the rest are left out and the answer says so.
MAX_DROPPED = 20_000
@dataclass
class Dropped:
"""What a drop onto the window resolved to."""
tracks: list[Track] = field(default_factory=list)
# Dropped FILES that are not audio this library can hold (or are gone).
# Non-audio inside a dropped folder is not counted: an album folder's
# cover and cue sheet are not something the user asked to add.
skipped: int = 0
# More than MAX_DROPPED audio files: the rest were left out.
truncated: bool = False
class FolderScanner:
"""Scans folders on request, caching each until its contents change.
Also the gatekeeper for streaming: `source_for_file` answers only for a file
found by a scan, so the audio route cannot be used to read an arbitrary path
off the disk — only audio the user has browsed to.
found by a scan — or dropped onto the window by the user — so the audio
route cannot be used to read an arbitrary path off the disk, only audio the
user has browsed to or handed over.
"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {}
# Files dropped one by one: their folder was never scanned (and is not
# cached as if it had been — a partial listing would hide its other
# files from the sidebar), so each is held on its own.
self._files: dict[str, Track] = {}
def dropped(self, paths: list[str], formats: list[str], limit: int = MAX_DROPPED) -> Dropped:
"""Resolve paths dropped onto the window: folders RECURSIVELY (hidden
and OS-housekeeping folders left out, as the tree leaves them out),
files as themselves. Every audio file found becomes addable and
playable through the folder routes, exactly as if it had been browsed."""
wanted = {f.lower() for f in formats}
out = Dropped()
seen: set[str] = set()
def take(tracks: list[Track]) -> bool:
for t in tracks:
if t.id in seen:
continue
if len(out.tracks) >= limit:
out.truncated = True
return False
seen.add(t.id)
out.tracks.append(t)
return True
for raw in paths:
path = Path(raw).expanduser()
if path.is_dir():
for folder in _walk(path):
if not audio_files(folder, formats):
continue
if not take(self.scan(folder, formats).tracks):
return out
elif path.is_file() and path.suffix.lower() in wanted and not is_hidden(path):
track = self._file_track(path)
if not take([track]):
return out
else:
out.skipped += 1
return out
def _file_track(self, path: Path) -> Track:
key = str(path)
with self._lock:
hit = self._cache.get(str(path.parent))
known = hit[2].track(key) if hit is not None else None
if known is not None:
return known
track = read_track(path)
with self._lock:
self._files[key] = track
return track
def scan(self, folder: Path, formats: list[str]) -> FolderSource:
folder = Path(folder)
@@ -198,10 +272,32 @@ class FolderScanner:
folder = str(Path(track_id).parent)
with self._lock:
hit = self._cache.get(folder)
if hit is None or hit[2].track(track_id) is None:
return None
return hit[2]
loose = self._files.get(track_id)
if hit is not None and hit[2].track(track_id) is not None:
return hit[2]
if loose is not None:
return FolderSource(Path(folder), [loose])
return None
def clear(self) -> None:
with self._lock:
self._cache.clear()
self._files.clear()
def _walk(root: Path):
"""`root` and every visible folder under it, depth first, sorted by name."""
yield root
try:
with os.scandir(root) as it:
subs = []
for entry in it:
try:
if entry.is_dir(follow_symlinks=False) and not is_hidden(entry):
subs.append(Path(entry.path))
except OSError:
continue
except OSError:
return
for sub in sorted(subs, key=lambda p: p.name.lower()):
yield from _walk(sub)
+2 -2
View File
@@ -235,8 +235,8 @@ def detect_grid(
if bpm is not None and not (20.0 <= bpm <= 400.0):
raise ValueError(f"Not a usable BPM: {bpm}")
if y is None:
import librosa
y, sr = librosa.load(audio_path, sr=sr, mono=True)
from . import waveform
y, sr = waveform.load(audio_path, sr=sr)
y = np.asarray(y, dtype=np.float32)
duration = len(y) / sr
if duration < 1.5:
+2 -2
View File
@@ -178,7 +178,7 @@ def with_detected_key(track, y: np.ndarray | None, sr: int):
def detect_key(audio_path: str) -> KeyResult | None:
import librosa
from . import waveform
y, sr = librosa.load(audio_path, sr=SR, mono=True)
y, sr = waveform.load(audio_path, sr=SR)
return detect_key_samples(y, sr)
+86 -19
View File
@@ -37,8 +37,10 @@ from __future__ import annotations
import fractions
import json
import queue
import struct
import sys
import threading
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
@@ -151,15 +153,36 @@ def decode(path: Path | str) -> Source:
return Source(pcm=np.ascontiguousarray(pcm), codec=codec, bit_rate=bit_rate)
#: Encoded frames each stream's thread may run ahead of the muxer.
_ENCODE_QUEUE = 64
#: Frames between `checkpoint()` / `progress()` calls (~6 s of audio).
_ENCODE_TICK = 256
def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
checkpoint: Callable[[], None] | None) -> None:
"""Mux five AAC streams IN LOCKSTEP — one frame of each in turn — so the
muxer never buffers a whole stream (which it would if they came one after
another)."""
checkpoint: Callable[[], None] | None,
progress: Callable[[float], None] | None = None) -> None:
"""Encode the AAC streams on one thread EACH and mux them on this one, IN
LOCKSTEP — per frame stream 0..4, then each stream's flush — so the muxer
never buffers a whole stream (which it would if they came one after another).
The encoders are independent and PyAV releases the GIL inside FFmpeg, so
this is ~3x faster than one thread with FFmpeg's `aac` (a 5-minute track's
real stems: 104 s -> 35 s on a 6-core i7) — and since the mux order is the single-threaded
one, the file is byte-identical. Every codec is opened and the header written
HERE before any worker starts: the first `mux()` would otherwise open (and
read) codec contexts a worker may be opening or encoding with. After that
this thread never touches a codec, and a worker never touches the container.
`checkpoint()` and `progress(fraction)` are called from this thread only.
"""
import av
n = tracks[0].shape[1]
tb = fractions.Fraction(1, SR)
offsets = range(0, n, FRAME)
stop = threading.Event()
threads: list[threading.Thread] = []
container = av.open(fp, "w", format="ipod")
try:
streams = []
@@ -169,21 +192,63 @@ def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
if k:
s.disposition = 0 # present, not enabled: a plain player plays the mix
streams.append(s)
for i, offset in enumerate(range(0, n, FRAME)):
if checkpoint is not None and i % 512 == 0:
checkpoint()
for s, x in zip(streams, tracks):
frame = av.AudioFrame.from_ndarray(
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
format="fltp", layout="stereo",
)
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
for packet in s.encode(frame):
container.mux(packet)
for s in streams:
for packet in s.encode(None):
s.codec_context.open(strict=False)
container.start_encoding()
queues = [queue.Queue(maxsize=_ENCODE_QUEUE) for _ in tracks]
def put(q: queue.Queue, item) -> bool:
while not stop.is_set():
try:
q.put(item, timeout=0.1)
return True
except queue.Full:
pass
return False # the muxer gave up: stop encoding
def work(s, x: np.ndarray, q: queue.Queue) -> None:
try:
for offset in offsets:
frame = av.AudioFrame.from_ndarray(
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
format="fltp", layout="stereo",
)
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
if not put(q, s.encode(frame)):
return
put(q, s.encode(None))
except BaseException as ex: # noqa: BLE001 — re-raised by the muxer
put(q, ex)
def mux(q: queue.Queue) -> None:
packets = q.get()
if isinstance(packets, BaseException):
raise packets
for packet in packets:
container.mux(packet)
threads = [threading.Thread(target=work, args=(s, x, q), daemon=True, name=f"stem-encode-{k}")
for k, (s, x, q) in enumerate(zip(streams, tracks, queues))]
for t in threads:
t.start()
for i in range(len(offsets)):
if i % _ENCODE_TICK == 0:
if checkpoint is not None:
checkpoint()
if progress is not None:
progress(i / len(offsets))
for q in queues:
mux(q)
for q in queues:
mux(q) # each stream's flush
if progress is not None:
progress(1.0)
finally:
# A cancel or a failure: the workers stop at their next frame, and must
# have stopped before the container (and their codecs) are freed.
stop.set()
for t in threads:
t.join()
container.close()
@@ -302,14 +367,16 @@ Separate = Callable[[np.ndarray], list[np.ndarray]]
def build(source_path: Path | str, target: Path | str, separate: Separate, *,
encoder: str | None = None, checkpoint: Callable[[], None] | None = None) -> Written:
encoder: str | None = None, checkpoint: Callable[[], None] | None = None,
on_encode: Callable[[float], None] | None = None) -> Written:
"""Convert `source_path` into a stem file at `target`.
`separate(pcm)` gets the stereo 44.1 kHz mix and must return the four stems
in `DEMUCS_ORDER`, each the mix's shape. `target` may be any name — the batch
writes a `*.konduktor-partial` and renames it once the batch commits — since
nothing here infers a format from the suffix. `checkpoint()` is called between
phases and during the encode, and may raise to cancel.
phases and during the encode, and may raise to cancel. `on_encode(fraction)`
reports the encode's progress, 0 to 1 (verifying after it takes ~1 s).
"""
target = Path(target)
tick = checkpoint or (lambda: None)
@@ -322,7 +389,7 @@ def build(source_path: Path | str, target: Path | str, separate: Separate, *,
bit_rate = choose_bitrate(source)
with open(target, "wb") as fp:
_encode(fp, [source.pcm, *stems], bit_rate=bit_rate,
encoder=encoder or default_encoder(), checkpoint=checkpoint)
encoder=encoder or default_encoder(), checkpoint=checkpoint, progress=on_encode)
add_stem_box(target)
tags = tag_copy.copy_tags(source_path, target)
verify(target, source)
+2 -2
View File
@@ -273,8 +273,8 @@ def analyse(
if not markers:
raise ValueError("Set a beatgrid first")
if y is None:
import librosa
y, _ = librosa.load(audio_path, sr=_SR, mono=True)
from . import waveform
y, _ = waveform.load(audio_path, sr=_SR)
y = np.asarray(y, dtype=np.float32)
duration = len(y) / _SR
beats, bar0 = grid_beats(markers, duration)
+17 -9
View File
@@ -84,8 +84,8 @@ class Analysis:
return self.columns.duration
def _decode_pyav(path: Path) -> np.ndarray:
"""Mono float32 at `SR`, via PyAV — FFmpeg's decoders, bundled in its wheel.
def _decode_pyav(path: Path, sr: int = SR) -> np.ndarray:
"""Mono float32 at `sr`, via PyAV — FFmpeg's decoders, bundled in its wheel.
The reason it is first: it decodes AAC (every Traktor `.stem.m4a`) on EVERY
OS, where librosa needs CoreAudio (macOS only) or a system ffmpeg. Measured
@@ -98,7 +98,7 @@ def _decode_pyav(path: Path) -> np.ndarray:
with pyav.open_input(path) as container:
stream = container.streams.audio[0]
resampler = av.AudioResampler(format="flt", layout="mono", rate=SR)
resampler = av.AudioResampler(format="flt", layout="mono", rate=sr)
chunks = []
for frame in container.decode(stream):
for out in resampler.resample(frame):
@@ -122,16 +122,24 @@ def even_slices(n: int, k: int) -> list[slice]:
return [slice(int(a), int(max(b, a + 1)) if n else 0) for a, b in zip(edges[:-1], edges[1:])]
def _decode(path: Path) -> np.ndarray | None:
def load(path: Path | str, sr: int = SR) -> tuple[np.ndarray, int]:
"""Mono float32 at `sr` as `(y, sr)` — `librosa.load`'s shape, raising as it
does. EVERY analysis decode goes through here, never `librosa.load` itself:
librosa reads AAC only through CoreAudio or a system ffmpeg, so on Windows
a `.stem.m4a` failed with "Format not recognised"."""
try:
return _decode_pyav(path)
return _decode_pyav(Path(path), sr), sr
except Exception as ex: # PyAV missing, or a file FFmpeg cannot open
log.debug("PyAV could not decode %s (%s); trying librosa", path, ex)
try:
import librosa
import librosa
y, _ = librosa.load(str(path), sr=SR, mono=True)
return y
y, _ = librosa.load(str(path), sr=sr, mono=True)
return y, sr
def _decode(path: Path) -> np.ndarray | None:
try:
return load(path)[0]
except Exception as ex: # any decoder failure: no waveform, not a failed export
log.warning("could not decode %s for a waveform: %s", path, ex)
return None
+43 -5
View File
@@ -69,6 +69,8 @@ from .schemas import (
ExportSetOut,
ExportPreview,
Drive,
DroppedFiles,
DroppedPaths,
FolderAddRequest,
FolderTracks,
FsEntry,
@@ -120,8 +122,12 @@ app.add_middleware(
"http://localhost:5173",
"http://127.0.0.1:5173",
# Packaged desktop app: the webview's origin when Tauri loads the built
# frontend (macOS uses tauri://, Windows/Linux use https://tauri.localhost).
# frontend. macOS uses tauri://; Windows/Linux default to
# https://tauri.localhost, but lib.rs forces the http scheme
# (use_https_scheme(false)) so the sidecar is not mixed content —
# without the http origin here, the Windows app reaches no API at all.
"tauri://localhost",
"http://tauri.localhost",
"https://tauri.localhost",
],
allow_methods=["*"],
@@ -1662,10 +1668,10 @@ def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview:
def _decode_for_analysis(path: Path):
"""Mono samples at the rate BOTH detectors work at (they share one decode)."""
import librosa
from .core import waveform
assert grid_detect._SR == key_detect.SR, "grid and key detection must share a sample rate"
return librosa.load(str(path), sr=key_detect.SR, mono=True)
return waveform.load(path, sr=key_detect.SR)
def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None:
@@ -2317,6 +2323,18 @@ def folder_tracks(path: str) -> FolderTracks:
)
@app.post("/api/folder/dropped", response_model=DroppedFiles)
def folder_dropped(body: DroppedPaths) -> DroppedFiles:
"""Files and folders dropped onto the window. Folders are searched all the
way down; every audio file found is then addable and playable through the
folder routes, as if it had been browsed to in the sidebar."""
dest = require_adapter()
dropped = FOLDERS.dropped(body.paths, _formats())
held = importer._existing_files(dest)
rows, files = _folder_rows(dest, dropped.tracks, lambda t: held.get(importer._key(Path(t.id))))
return DroppedFiles(tracks=rows, files=files, skipped=dropped.skipped, truncated=dropped.truncated)
def _folder_track(track_id: str) -> FolderSource:
# Only a file a scan found. This is what keeps the audio route from being a
# way to read any path on the disk.
@@ -2443,8 +2461,28 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
elif body.mode == "reference":
# Nothing is copied, so there is no size to fit anywhere.
out.update(total_bytes=0, free_bytes=None, enough_space=None)
drive = _drive_of(Path(body.track_ids[0]), places.drives()) if body.track_ids else None
out["removable"] = drive is None or drive["kind"] == "external"
elif destination is not None:
# Copying a file that is already in the import folder makes a second
# copy beside it — legal, but rarely meant, so the dialog says so.
home = destination.resolve()
out["in_destination"] = sum(
1 for t in plan.importable
if t.source_path is not None and t.source_path.resolve().is_relative_to(home)
)
# Per FILE, not per request: a drop can mix the computer's own disk with a
# stick, and only the files on the stick go missing when it is unplugged.
drives = places.drives()
external: dict[str, int] = {}
for t in plan.importable:
if t.source_path is None:
continue
drive = _drive_of(t.source_path, drives)
if drive is None or drive["kind"] == "external":
name = drive["name"] if drive else str(t.source_path.anchor or t.source_path.parent)
external[name] = external.get(name, 0) + 1
out["removable"] = bool(external)
out["removable_count"] = sum(external.values())
out["removable_drives"] = sorted(external)
return out
+19
View File
@@ -549,6 +549,25 @@ class FolderTracks(BaseModel):
removable: bool
class DroppedPaths(BaseModel):
"""Files and folders dropped onto the window from Finder / Explorer."""
paths: list[str]
class DroppedFiles(BaseModel):
"""What a drop resolved to: the audio in it, as a folder lists its files."""
tracks: list[Track]
# As FolderTracks: rows the collection holds are its tracks, and this maps
# their collection id back to the file's folder id, which adding takes.
files: dict[str, str] = {}
# Dropped files that are not audio the library can hold, or are gone.
skipped: int = 0
# Too many files: only the first MAX_DROPPED are here.
truncated: bool = False
class FolderAddRequest(BaseModel):
"""Add browsed files to the collection, and optionally to a playlist/export.
+29 -14
View File
@@ -39,11 +39,25 @@ _BYTES_PER_SECOND = {256_000: 5 * 256_000 / 8 * 1.03, 320_000: 5 * 320_000 / 8 *
_WORK_BYTES_PER_SECOND = 5 * 2 * 4 * sf.SR
#: Shares of ONE track's conversion time, for the status bar's within-track
#: progress (measured on the M3 Pro: decode ~1 s, separate ~50 s, encode +
#: verify ~4 s for a 4-minute track).
_DECODE_SHARE = 0.03
_SEPARATE_SHARE = 0.90
#: Shares of ONE track's conversion time (decode, separate; encoding + verifying
#: take the rest), for the status bar's within-track progress, by AAC encoder.
#: Measured: `aac_at` on the M3 Pro (4-minute track: decode ~1 s, separate
#: ~50 s, encode + verify ~4 s); `aac` on an i7-9750H + RTX 2070 (5-minute
#: track: decode 0.5 s, separate ~102 s, encode ~38 s on five threads, verify ~1 s).
_SHARES = {"aac_at": (0.03, 0.90), "aac": (0.01, 0.71)}
def track_shares(encoder: str) -> tuple[float, float]:
return _SHARES.get(encoder, _SHARES["aac"])
def encode_reporter(handle, start: float, end: float = 0.99) -> Callable[[float], None]:
"""`on_encode` for `stem_file.build`: the encode runs from `start` to `end`
of the track, and the ~1 s of tags + verification after it reads as such."""
def report(f: float) -> None:
frac = start + f * (end - start)
handle.progress(fraction=frac, status=f"{'verifying' if f >= 1 else 'encoding'} {frac * 100:.0f} %")
return report
class ConvertError(Exception):
@@ -227,6 +241,7 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
work = work_root() / f"batch-{id(handle):x}"
finished: list[tuple[Planned, dict, sf.Written]] = []
needs_engine = any(p.reuse is None for p in items)
encoder = sf.default_encoder()
if needs_engine and not mgr.ready():
raise ConvertError("The stem engine is not installed")
@@ -258,22 +273,22 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
"stem": str(item.target), "state": "converting", "facts": source_facts(item.source)})
item.target.parent.mkdir(parents=True, exist_ok=True)
# Of a TRACK's time, separation is nearly all (~90 % on MPS);
# decoding before it and encoding + verifying after share the rest.
# Of a TRACK's time, separation is nearly all; decoding before it
# and encoding + verifying after share the rest.
decode_share, separate_share = track_shares(encoder)
def on_progress(f: float) -> None:
frac = _DECODE_SHARE + f * (_SEPARATE_SHARE)
frac = decode_share + f * separate_share
handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %")
def separate(pcm):
handle.progress(fraction=_DECODE_SHARE, status=f"separating {_DECODE_SHARE * 100:.0f} %")
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
done_at = _DECODE_SHARE + _SEPARATE_SHARE
handle.progress(fraction=done_at, status=f"encoding {done_at * 100:.0f} %")
return stems
handle.progress(fraction=decode_share, status=f"separating {decode_share * 100:.0f} %")
return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
handle.progress(status="decoding 0 %")
try:
written = sf.build(item.source, partial, separate, checkpoint=checkpoint)
written = sf.build(item.source, partial, separate, encoder=encoder, checkpoint=checkpoint,
on_encode=encode_reporter(handle, decode_share + separate_share))
except (_Cancel, EngineCancelled):
partial.unlink(missing_ok=True)
pending.drop([pitem])
+3 -4
View File
@@ -153,13 +153,12 @@ def run(handle, adapter, planned: RemotePlan, opts: convert.Options, *, still_cu
def separate(pcm):
handle.progress(fraction=0.05, status="separating 5 %")
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
handle.progress(fraction=0.85, status="encoding 85 %")
return stems
return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
partial = work / f"{n}.stem.m4a"
try:
written = sf.build(local, partial, separate, checkpoint=checkpoint)
written = sf.build(local, partial, separate, checkpoint=checkpoint,
on_encode=convert.encode_reporter(handle, 0.85, 0.9))
except (convert._Cancel, EngineCancelled):
partial.unlink(missing_ok=True)
raise
+2 -2
View File
@@ -14,5 +14,5 @@ Pillow>=11 # a Rekordbox add writes the cover's artwork files
dulwich>=0.22 # version history, beside the library
platformdirs>=4.0
# From GitHub, NOT PyPI — see requirements.txt for why.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@39a9c15f29d6b0ea2ce61cd7d548501eea38319d
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git@43137cb91f8297c768d2a8bdce5b27b2225f0a2d
+12 -9
View File
@@ -18,19 +18,22 @@ librosa>=0.11
scikit-learn>=1.5
# Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0),
# NOT the stale PyPI release (3.1.0), which cannot parse v4 files.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
#
# Both GitHub dependencies are PINNED TO A COMMIT. Unpinned, a fresh install
# (CI's release build) takes whatever master is that day while a dev venv keeps
# what it had: pyrekordbox renamed `devicelib_plus` to `onelibrary` upstream,
# every local test passed, and the released app could not export or read a
# OneLibrary stick. Move a pin deliberately, with ./run_tests.sh.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@39a9c15f29d6b0ea2ce61cd7d548501eea38319d
# Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis
# files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build.
#
# FROM GITHUB, NOT PyPI — the same situation as traktor-nml-utils above, and for
# the same kind of reason. PyPI's latest (0.4.4) has no `devicelib_plus`, which
# is the OneLibrary (`exportLibrary.db`) reader the OneLibrary adapter is built
# on; it exists only on master. Do not "simplify" this back to a version pin.
#
# The upgrade also renames `db6` to `masterdb`. `db6` still works as a
# deprecated alias and is removed in 0.6.0, so the Rekordbox adapter keeps
# running as-is — but that rename is the thing to fix before taking 0.6.
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
# the same kind of reason. PyPI's latest (0.4.4) has no `onelibrary` module
# (`exportLibrary.db`, which the OneLibrary adapter is built on; it was called
# `devicelib_plus` before the rename) and no `masterdb` (formerly `db6`, now
# removed). Do not "simplify" this back to a version pin.
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git@43137cb91f8297c768d2a8bdce5b27b2225f0a2d
# The stem engine and its weights are downloaded over HTTPS by the sidecar; a
# frozen Python on macOS has no system CA bundle of its own.
certifi>=2024.7
+26 -4
View File
@@ -28,16 +28,38 @@ def _watch_parent_and_exit() -> None:
shut down, so the backend can never be orphaned (the Rust-side kill-on-exit
only covers the graceful path). When run standalone from a terminal, stdin is
a TTY and this blocks harmlessly forever.
NOT on Windows: there a read left pending on the stdin pipe stalls loading
scipy's OpenBLAS DLL in any other thread, forever — so the first analysis
hung the packaged app (dev runs no watcher). Measured 2026-10-12 with plain
Python, through the CRT and through kernel32.ReadFile alike. Windows waits
on the parent PROCESS instead, which also covers a crash.
"""
try:
while sys.stdin.buffer.read(1):
if sys.platform == "win32":
_wait_for_parent_process()
else:
try:
while sys.stdin.buffer.read(1):
pass
except Exception:
pass
except Exception:
pass
_release_remote()
os._exit(0)
def _wait_for_parent_process() -> None:
"""Block until the process that started us exits (Windows only)."""
import ctypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.OpenProcess.restype = ctypes.c_void_p
kernel32.WaitForSingleObject.argtypes = (ctypes.c_void_p, ctypes.c_uint32)
synchronize, infinite = 0x00100000, 0xFFFFFFFF
handle = kernel32.OpenProcess(synchronize, False, os.getppid())
if handle: # None: the parent is already gone
kernel32.WaitForSingleObject(handle, infinite)
def _release_remote() -> None:
"""Hand back a remote library's session on the way out, so the next
computer opens it at once instead of waiting out the lease (or being asked
+1 -1
View File
@@ -504,7 +504,7 @@ print("\n== content.contentLink is what rekordbox writes ==")
# row's song-list preview plain blue and put a "?" beside CUE — exactly what
# every row of Konduktor's exports showed while it was NULL.
import sqlcipher3.dbapi2 as _sq # noqa: E402
from pyrekordbox.devicelib_plus.database import BLOB as _BLOB # noqa: E402
from pyrekordbox.onelibrary.database import BLOB as _BLOB # noqa: E402
from pyrekordbox.utils import deobfuscate as _deob # noqa: E402
_con = _sq.connect(str(art_written.library))
+76
View File
@@ -197,6 +197,82 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
c.post("/api/folder/add/preview",
json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404)
print("== a drop onto the window: folders all the way down, files as themselves ==")
drop = Path(tempfile.mkdtemp()) / "Dropped"
d_a = flac(drop / "Album" / "a.flac", title="Dropped A")
d_b = flac(drop / "Album" / "CD2" / "b.flac")
(drop / "Album" / "cover.jpg").write_bytes(b"not audio")
flac(drop / "Album" / ".cache" / "h.flac")
single = flac(drop / "Loose" / "single.flac", title="Single")
sibling = flac(drop / "Loose" / "sibling.flac")
(drop / "Loose" / "readme.txt").write_text("not audio")
r = c.post("/api/folder/dropped", json={"paths": [
str(drop / "Album"), str(single), str(drop / "Loose" / "readme.txt"),
str(drop / "gone.flac"), str(single), str(d_a),
]})
check("answers 200", r.status_code == 200, r.text[:300])
body = r.json()
ids = [t["id"] for t in body["tracks"]]
check("the folder's audio, subfolders included, then the file — each once",
ids == [str(d_a), str(d_b), str(single)], str(ids))
check("a hidden folder inside is left out", str(drop / "Album" / ".cache" / "h.flac") not in ids)
check("a dropped non-audio file and a missing one are counted as skipped",
body["skipped"] == 2, str(body["skipped"]))
check("non-audio INSIDE a dropped folder is not counted", body["skipped"] == 2)
check("tags are read", body["tracks"][0]["title"] == "Dropped A")
check("not truncated", body["truncated"] is False)
check("a dropped file streams",
c.get("/api/folder/tracks/audio", params={"track_id": str(single)}).status_code == 200)
check("so does one found inside a dropped folder",
c.get("/api/folder/tracks/audio", params={"track_id": str(d_b)}).status_code == 200)
check("but not its undropped sibling",
c.get("/api/folder/tracks/audio", params={"track_id": str(sibling)}).status_code == 404)
listed = [t["id"] for t in c.get("/api/folder/tracks", params={"path": str(drop / "Loose")}).json()["tracks"]]
check("browsing that folder afterwards still lists ALL of it",
listed == [str(sibling), str(single)], str(listed))
r = c.post("/api/folder/dropped", json={"paths": [str(drop / "Loose" / "readme.txt")]})
check("a non-audio file is never made streamable",
r.json()["tracks"] == [] and c.get("/api/folder/tracks/audio", params={
"track_id": str(drop / "Loose" / "readme.txt")}).status_code == 404)
capped = main.FOLDERS.dropped([str(drop / "Album")], main._formats(), limit=1)
check("past the cap the rest are left out, and it says so",
len(capped.tracks) == 1 and capped.truncated)
body = c.post("/api/folder/dropped", json={"paths": [str(one)]}).json()
check("a dropped file the collection holds IS its collection track",
[t["id"] for t in body["tracks"]] == [added] and body["files"] == {added: str(one)},
str(body))
req = {"track_ids": [str(d_b)], "mode": "copy", "destination": str(drop / "Album")}
p = c.post("/api/folder/add/preview", json=req).json()
check("copying into the folder they are already in is flagged", p.get("in_destination") == 1, str(p))
req["destination"] = str(Path(tempfile.mkdtemp()))
p = c.post("/api/folder/add/preview", json=req).json()
check("…and not elsewhere", p.get("in_destination") == 0, str(p))
real_drives = main.places.drives
main.places.drives = lambda: [
{"name": "Computer", "path": drop.anchor, "kind": "local"},
{"name": "Stick", "path": str(drop / "Album"), "kind": "external"},
]
try:
req = {"track_ids": [str(d_a), str(single)], "mode": "reference"}
p = c.post("/api/folder/add/preview", json=req).json()
check("the external-drive warning counts files per drive, not by the first",
p["removable"] is True and p["removable_count"] == 1 and p["removable_drives"] == ["Stick"],
str(p))
p = c.post("/api/folder/add/preview", json={"track_ids": [str(single), str(d_a)],
"mode": "reference"}).json()
check("…whichever file comes first", p["removable_count"] == 1, str(p))
finally:
main.places.drives = real_drives
n = len(a.tracks)
job = wait(c, c.post("/api/folder/add", json={"track_ids": [str(d_a), str(single)],
"mode": "reference"}).json())
check("dropped files are added like browsed ones", job["state"] == "done" and len(a.tracks) == n + 2,
str(job))
print("== Rekordbox: the same route adds to a master.db ==")
from konduktor.adapters.rekordbox import discovery as rb_discovery
+1 -1
View File
@@ -60,7 +60,7 @@ def dump(db: Path) -> dict:
"""Every row of every table; keyed by primary key, or by the whole row for
the link tables, which have none."""
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(db))
+1 -1
View File
@@ -65,7 +65,7 @@ def fingerprint(root: Path) -> str:
def rows(root: Path, sql: str):
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(root / "PIONEER" / "rekordbox" / "exportLibrary.db"))
+60
View File
@@ -262,11 +262,71 @@ def stop_in_encode():
raise Stop()
def encoder_threads():
import threading
return [t.name for t in threading.enumerate() if t.name.startswith("stem-encode-")]
try:
sf.build(MP3, tmp / "cancelled.partial", fake_separate, encoder="aac", checkpoint=stop_in_encode)
check("a checkpoint that raises stops the build", False, "it finished")
except Stop:
check("a checkpoint that raises stops the build", True)
check("…and no encoder thread outlives it", not encoder_threads(), str(encoder_threads()))
print("== 6. the encode runs on one thread per stream ==")
def encode_single_threaded(fp, tracks, *, bit_rate, encoder):
"""The encode as it was before it was threaded: the reference for the bytes."""
tb = fractions.Fraction(1, SR)
c = av.open(fp, "w", format="ipod")
try:
streams = []
for k in range(len(tracks)):
s = c.add_stream(encoder, rate=SR, layout="stereo")
s.bit_rate = bit_rate
if k:
s.disposition = 0
streams.append(s)
for offset in range(0, tracks[0].shape[1], sf.FRAME):
for s, x in zip(streams, tracks):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, offset:offset + sf.FRAME]),
format="fltp", layout="stereo")
f.sample_rate, f.pts, f.time_base = SR, offset, tb
for p in s.encode(f):
c.mux(p)
for s in streams:
for p in s.encode(None):
c.mux(p)
finally:
c.close()
source = sf.decode(MP3)
# A length that is not a whole number of frames, and stems that differ from the mix.
five = [np.ascontiguousarray(t[:, :-333]) for t in (source.pcm, *fake_separate(source.pcm))]
for enc in encoders:
ref, par = tmp / f"ref.{enc}.m4a", tmp / f"par.{enc}.m4a"
with open(ref, "wb") as fp:
encode_single_threaded(fp, five, bit_rate=320_000, encoder=enc)
seen = []
with open(par, "wb") as fp:
sf._encode(fp, five, bit_rate=320_000, encoder=enc, checkpoint=None, progress=seen.append)
check(f"{enc}: the threaded encode is byte-identical to the single-threaded one",
ref.read_bytes() == par.read_bytes(), f"{ref.stat().st_size} vs {par.stat().st_size} bytes")
check(f"{enc}: progress runs 0 -> 1, never backwards",
len(seen) >= 3 and seen[0] == 0 and seen[-1] == 1.0 and seen == sorted(seen), str(seen))
try:
with open(tmp / "broken.m4a", "wb") as fp:
# A mono array in a stereo stream: that stream's thread fails on its first frame.
sf._encode(fp, [five[0], five[1][:1], *five[2:]], bit_rate=320_000, encoder="aac", checkpoint=None)
check("a failing encoder thread fails the encode", False, "it finished")
except Exception as ex: # noqa: BLE001
check("a failing encoder thread fails the encode, with its own error", not isinstance(ex, Stop), repr(ex))
check("…and no encoder thread outlives it", not encoder_threads(), str(encoder_threads()))
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+69
View File
@@ -0,0 +1,69 @@
# Build the Konduktor desktop app on Windows: freeze + stage the backend sidecar,
# then build the Tauri installers. First run? See one-time setup in
# BUILDING-WINDOWS.md (the backend venv with requirements-build.txt, and
# `npm install`).
#
# .\build.ps1 # sidecar + app (release installers)
# .\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar
# .\build.ps1 --debug # anything else is passed on to `tauri build`
# (if scripts are blocked: powershell -ExecutionPolicy Bypass -File .\build.ps1)
param([switch]$SkipSidecar)
$ErrorActionPreference = "Stop"
$Root = $PSScriptRoot
$TauriArgs = $args
$Py = Join-Path $Root "backend\.venv\Scripts\python.exe"
if (-not (Test-Path $Py)) { throw "No backend venv at backend\.venv - see BUILDING-WINDOWS.md for setup." }
if (-not (Test-Path (Join-Path $Root "frontend\node_modules"))) { throw "No frontend\node_modules - run ``npm install`` in frontend first." }
$Staged = Join-Path $Root "frontend\src-tauri\binaries\konduktor-sidecar\konduktor-sidecar.exe"
# rustup puts cargo in %USERPROFILE%\.cargo\bin and adds it to PATH only for
# terminals opened AFTER the install - so find it there before giving up, rather
# than failing ten minutes in, after the sidecar build.
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
$CargoBin = Join-Path $env:USERPROFILE ".cargo\bin"
if (-not (Test-Path (Join-Path $CargoBin "cargo.exe"))) { throw "No Rust toolchain (cargo) - install it from https://rustup.rs, see BUILDING-WINDOWS.md." }
$env:PATH = "$CargoBin;$env:PATH"
}
$Started = Get-Date
# build_sidecar.ps1 changes directory itself, and a location change outlives the
# script it was made in - so put ours back whatever happens.
Push-Location $Root
try {
if ($SkipSidecar) {
if (-not (Test-Path $Staged)) { throw "No staged sidecar to reuse - run without -SkipSidecar first." }
Write-Host "==> Reusing the staged sidecar (-SkipSidecar)"
}
else {
Write-Host "==> 1/2 Freezing the backend sidecar"
& (Join-Path $Root "backend\build_sidecar.ps1")
}
Write-Host ""
Write-Host "==> 2/2 Building the app (tauri build $TauriArgs)"
Set-Location (Join-Path $Root "frontend")
# npx is a .cmd and cargo reports progress on stderr: relax "Stop" for the
# call (as build_sidecar.ps1 does for PyInstaller) and judge by exit code.
$ErrorActionPreference = "Continue"
& npx tauri build @TauriArgs
$code = $LASTEXITCODE
$ErrorActionPreference = "Stop"
if ($code -ne 0) { throw "tauri build failed ($code)" }
}
finally {
Pop-Location
}
# List what this run produced (release or --debug profile).
$Bundles = Join-Path $Root "frontend\src-tauri\target\*\bundle"
$Built = Get-ChildItem -Path "$Bundles\nsis\*-setup.exe", "$Bundles\msi\*.msi" -File -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -ge $Started }
Write-Host ""
if ($Built) {
Write-Host "Installers:"
$Built | ForEach-Object { Write-Host " $($_.FullName)" }
}
else {
Write-Host "Done (no installer bundled - see frontend\src-tauri\target\)."
}
+42
View File
@@ -0,0 +1,42 @@
# Start both Konduktor servers (backend + frontend) together - the Windows
# counterpart of dev.sh. Ctrl-C stops both. First run? See one-time setup in
# BUILDING-WINDOWS.md (the backend venv and `npm install`).
#
# .\dev.ps1
# (if scripts are blocked: powershell -ExecutionPolicy Bypass -File .\dev.ps1)
$ErrorActionPreference = "Stop"
$Root = $PSScriptRoot
$Py = Join-Path $Root "backend\.venv\Scripts\python.exe"
if (-not (Test-Path $Py)) { throw "No backend venv at backend\.venv - see BUILDING-WINDOWS.md for setup." }
# Vite through node, not `npm run dev`: npm is a .cmd batch file, and Ctrl-C in a
# shared console makes cmd ask "Terminate batch job (Y/N)?" instead of exiting.
$Vite = Join-Path $Root "frontend\node_modules\vite\bin\vite.js"
if (-not (Test-Path $Vite)) { throw "No frontend\node_modules - run ``npm install`` in frontend first." }
# Backend (FastAPI on :8000)
$Backend = Start-Process -FilePath $Py -NoNewWindow -PassThru `
-ArgumentList "-m", "uvicorn", "konduktor.main:app", "--reload", "--port", "8000", "--app-dir", "`"$Root\backend`""
# Frontend (Vite on :5173, proxies /api -> :8000)
$Frontend = Start-Process -FilePath "node" -NoNewWindow -PassThru `
-WorkingDirectory (Join-Path $Root "frontend") -ArgumentList "`"$Vite`""
Write-Host ""
Write-Host " Konduktor is starting..."
Write-Host " -> App: http://localhost:5173"
Write-Host " -> API docs: http://localhost:8000/docs"
Write-Host " (Ctrl-C to stop both)"
Write-Host ""
try {
# If either one dies, stop the other rather than leave half a dev setup.
while (-not $Backend.HasExited -and -not $Frontend.HasExited) { Start-Sleep -Milliseconds 500 }
}
finally {
# Kill the whole tree: uvicorn --reload runs the server in a child process,
# which would otherwise keep :8000 bound after the reloader has gone.
foreach ($p in $Backend, $Frontend) {
if ($p -and -not $p.HasExited) { & taskkill /PID $p.Id /T /F 2>&1 | Out-Null }
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "frontend",
"private": true,
"version": "0.2.5",
"version": "0.2.8",
"type": "module",
"scripts": {
"dev": "vite",
+154 -19
View File
@@ -1,11 +1,13 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table'
import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { removalNote, writeHint } from './lib/platformCopy'
import { readOnlyNotice, removalNote, writeHint } from './lib/platformCopy'
import { invalidateTrackLists } from './lib/trackQueries'
import { addTracksToPlaylist } from './lib/addTracks'
import { useDropTarget } from './lib/drag'
import { useDragPayload, useDropTarget } from './lib/drag'
import { useNativeFileDrop } from './lib/fileDrop'
import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
import { confirmDiscardUnsaved } from './lib/unsaved'
import { askConfirm } from './lib/confirm'
@@ -30,7 +32,7 @@ import { RelocateDialog } from './components/RelocateDialog'
import { HistoryPanel } from './components/HistoryPanel'
import { PrepStrip } from './components/PrepStrip'
import { ImportDialog } from './components/ImportDialog'
import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog'
import { AddFilesDialog, type AddTarget, type ForeignOrigin } from './components/AddFilesDialog'
import { ConvertStemsDialog } from './components/ConvertStemsDialog'
import { StemReportDialog } from './components/StemReportDialog'
import { SetPositionDialog } from './components/SetPositionDialog'
@@ -84,8 +86,12 @@ export default function App() {
// The browsed folder's rows that ARE collection tracks: collection id → the
// file's folder id. A ref, for the callbacks below that outlive a render.
const folderFilesRef = useRef<Record<string, string>>({})
// Browsed files being added to the collection (and maybe a playlist/export).
const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null)
// Browsed (or dropped) files being added to the collection (and maybe a
// playlist/export). `note` says what a drop left out.
const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null; note?: string | null } | null>(null)
// How many dropped items are being read (a dropped folder is searched all
// the way down, which can take a while): shown until the dialog opens.
const [readingDrop, setReadingDrop] = useState(0)
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
const [importing, setImporting] = useState(false)
// Device tracks dropped on a collection playlist / export: Import, with
@@ -377,9 +383,78 @@ export default function App() {
// export: they are not in the collection yet, so the drop opens the dialog
// that adds them — with that target filled in, and copy-vs-reference still
// asked (decided 2026-10-06).
// Files dragged in from Finder / Explorer (lib/fileDrop.ts). What is in them
// is read first — folders all the way down — and then they go where a
// browsed folder's files go: the add dialog, copy-vs-reference asked.
const readDrop = useCallback(
async (paths: string[]) => {
setReadingDrop(paths.length)
try {
return await api.folderDropped(paths)
} catch (e) {
onError((e as Error).message)
return null
} finally {
setReadingDrop(0)
}
},
[onError],
)
const dropFiles = useCallback(
async (paths: string[], target: AddTarget | null) => {
const r = await readDrop(paths)
if (!r) return
if (!r.tracks.length) {
onError(
paths.length === 1 && r.skipped
? 'That is not an audio file this library can hold.'
: 'No audio files this library can hold were found there.',
)
return
}
const notes: string[] = []
if (r.skipped)
notes.push(
r.skipped === 1
? '1 dropped item is not audio this library can hold and was left out.'
: `${r.skipped} dropped items are not audio this library can hold and were left out.`,
)
if (r.truncated) notes.push(`Only the first ${r.tracks.length.toLocaleString()} files are included.`)
// Files the collection holds are its tracks already: as with a folder's
// rows, nothing to add first — straight into the target, if there is one.
const held = r.tracks.filter((t) => r.files[t.id]).map((t) => t.id)
if (held.length === r.tracks.length) {
if (target?.kind === 'playlist') void addToPlaylist(target.id, held)
else if (target) void addToExport(target.id, held)
else
notify(
'success',
held.length === 1 ? 'Already in your collection' : `All ${held.length} are already in your collection`,
)
return
}
setAdding({ ids: r.tracks.map((t) => r.files[t.id] ?? t.id), target, note: notes.join(' ') || null })
},
[readDrop, addToPlaylist, addToExport, notify, onError],
)
// One dropped audio file on the deck: loaded to listen to, added to nothing.
const loadDropped = useCallback(
async (path: string) => {
const r = await readDrop([path])
if (!r) return
const t = r.tracks[0]
if (!t) {
onError('That is not an audio file this library can hold.')
return
}
loadTrack(t, r.files[t.id] ? 'collection' : 'folder')
},
[readDrop, loadTrack, onError],
)
const addForeign = useCallback(
(origin: TrackOrigin, ids: string[], target: AddTarget) => {
if (origin === 'folder') {
(origin: ForeignOrigin, ids: string[], target: AddTarget) => {
if (origin === 'dropped') void dropFiles(ids, target)
else if (origin === 'folder') {
const files = folderFilesRef.current
// Rows that are all collection tracks already: nothing to add first.
if (ids.every((id) => files[id])) {
@@ -388,13 +463,44 @@ export default function App() {
} else setAdding({ ids: ids.map((id) => files[id] ?? id), target })
} else if (origin === 'device') setImportDrop({ ids, target })
},
[addToPlaylist, addToExport],
[addToPlaylist, addToExport, dropFiles],
)
const audioFormats = capabilities.data?.tracks.audio_formats
const isAudioPath = (path: string) =>
path.lastIndexOf('.') > 0 && !!audioFormats?.includes(path.slice(path.lastIndexOf('.')).toLowerCase())
const [deckDropRef, deckOver] = useDropTarget<true>({
hint: (p) => (p.kind === 'tracks' ? true : null),
hint: (p) =>
p.kind === 'tracks' || (p.kind === 'files' && p.paths.length === 1 && isAudioPath(p.paths[0])) ? true : null,
label: (p) => (p.kind === 'tracks' && p.ids.length > 1 ? `Load “${p.lead.title || 'Untitled'}” into the deck` : 'Load into the deck'),
onDrop: (p) => p.kind === 'tracks' && loadTrack(p.lead, p.origin),
onDrop: (p) => {
if (p.kind === 'tracks') loadTrack(p.lead, p.origin)
else if (p.kind === 'files') void loadDropped(p.paths[0])
},
})
// Files dropped anywhere no other target takes them: the collection. A
// library that cannot add tracks still takes the drop, to say why not —
// silently ignoring it would read as the feature being broken.
const canAddFiles = (capabilities.data?.writable ?? false) && !!capabilities.data?.tracks.addable
const cannotAddFiles =
capabilities.data && !capabilities.data.writable
? (readOnlyNotice(capabilities.data) ?? 'This library is read-only.')
: 'Tracks cannot be added to this library.'
const [rootDropRef, rootOver] = useDropTarget<true>({
hint: (p) => (p.kind === 'files' ? true : null),
label: () => (canAddFiles ? 'Add to your collection…' : null),
onDrop: (p) => {
if (p.kind !== 'files') return
if (canAddFiles) void dropFiles(p.paths, null)
else notify('error', cannotAddFiles)
},
})
const draggingFiles = useDragPayload()?.kind === 'files'
useNativeFileDrop(loaded && !forcePicker, () =>
notify(
'warning',
'Dropping files works in the Konduktor app, not in a browser (it cannot tell the page where a file is). Browse to it under Files in the sidebar instead.',
),
)
const removeFromExport = useCallback(
async (id: string, ids: string[]) => {
try {
@@ -792,11 +898,16 @@ export default function App() {
// TrackTable retargets the selection to a right-clicked row outside it
// before calling this, but that state update has not landed yet — so the
// same rule is applied here to decide what the menu acts on.
const openMenu = (track: Track, x: number, y: number, selectable: boolean) =>
// same rule is applied here to decide what the menu acts on. The ids come
// in the order the view shows them (Set Position can keep that order); a
// selected track the view hides follows.
const openMenu = (track: Track, x: number, y: number, selectable: boolean, viewIds: string[]) =>
setMenu({
track,
ids: selectable && selected.has(track.id) ? [...selected] : [track.id],
ids:
selectable && selected.has(track.id)
? [...new Set([...viewIds.filter((id) => selected.has(id)), ...selected])]
: [track.id],
x,
y,
})
@@ -1066,8 +1177,26 @@ export default function App() {
<CapabilitiesContext.Provider value={capabilities.data!}>
{/* Floating glass panels with gaps between them: the ambient backdrop
(main.tsx) shows through the gutters as well as through the glass. */}
<div className="flex h-screen w-screen flex-col gap-3 overflow-hidden p-3">
<div ref={rootDropRef} className="flex h-screen w-screen flex-col gap-3 overflow-hidden p-3">
<Toast toast={toast} onClose={() => setToast(null)} />
{draggingFiles && rootOver &&
createPortal(
<div aria-hidden className="pointer-events-none fixed inset-0 z-[85] flex items-center justify-center">
<div className="absolute inset-1.5 rounded-[26px] ring-2 ring-accent" />
<div className="glass-overlay flex items-center gap-2.5 overflow-hidden rounded-2xl px-5 py-3 text-sm text-text shadow-lg">
<Icon name="music" size={15} className={canAddFiles ? 'text-accent' : 'text-pink'} />
{canAddFiles ? 'Drop to add to your collection' : cannotAddFiles}
</div>
</div>,
document.body,
)}
{readingDrop > 0 &&
createPortal(
<div className="glass-overlay pointer-events-none fixed bottom-14 left-1/2 z-[80] -translate-x-1/2 overflow-hidden rounded-full px-4 py-2 text-xs text-muted shadow-lg">
Looking for audio in {readingDrop === 1 ? 'the dropped item' : `${readingDrop} dropped items`}…
</div>,
document.body,
)}
{menu && (
<ContextMenu
// Remount per opening: a right-click on another row while a menu is
@@ -1197,6 +1326,7 @@ export default function App() {
<SetPositionDialog
order={tracks.map((t) => t.id)}
ids={positioning}
sorting={sorting}
onMove={reorderPlaylist}
onClose={() => setPositioning(null)}
/>
@@ -1280,6 +1410,7 @@ export default function App() {
<AddFilesDialog
trackIds={adding.ids}
target={adding.target}
note={adding.note}
onClose={() => setAdding(null)}
onDone={(msg) => {
setAdding(null)
@@ -1319,6 +1450,10 @@ export default function App() {
origin={prepOrigin}
cuesRefresh={cuesRefresh}
onPlayingChange={setDeckPlaying}
// As the context menu's: a library that would refuse the save is
// not offered the dialog, and a deck track outside the collection
// (a device's, a loose file's) is not the collection's to edit.
onEditTags={canEdit && prepOrigin === 'collection' ? setEditing : undefined}
/>
</CapabilitiesContext.Provider>
</div>
@@ -1478,7 +1613,7 @@ export default function App() {
sorting={sorting}
onSortingChange={setSorting}
selection={{ selected, onChange: setSelected }}
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
onRowContextMenu={(track, x, y, viewIds) => openMenu(track, x, y, true, viewIds)}
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
onPlay={playTrack}
onEditField={canEdit ? editField : undefined}
@@ -1519,7 +1654,7 @@ export default function App() {
selection={{ selected, onChange: setSelected }}
marked={{ ids: heldInFolder, title: 'Already in your collection' }}
dragFrom={{ origin: 'folder' }}
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
onRowContextMenu={(track, x, y, viewIds) => openMenu(track, x, y, true, viewIds)}
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
onPlay={playTrack}
onEditField={canEdit ? folderEditField : undefined}
@@ -1555,7 +1690,7 @@ export default function App() {
tracks={filtered}
sorting={sorting}
onSortingChange={setSorting}
onRowContextMenu={(track, x, y) => openMenu(track, x, y, false)}
onRowContextMenu={(track, x, y, viewIds) => openMenu(track, x, y, false, viewIds)}
dragFrom={{ origin: 'device' }}
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
onPlay={playTrack}
@@ -1580,7 +1715,7 @@ export default function App() {
sorting={sorting}
onSortingChange={setSorting}
selection={{ selected, onChange: setSelected }}
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
onRowContextMenu={(track, x, y, viewIds) => openMenu(track, x, y, true, viewIds)}
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
onPlay={playTrack}
onEditField={canEdit ? editField : undefined}
@@ -1622,7 +1757,7 @@ export default function App() {
origin: 'collection',
playlistId: playlistEditable && source.kind === 'playlist' ? source.id : undefined,
}}
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
onRowContextMenu={(track, x, y, viewIds) => openMenu(track, x, y, true, viewIds)}
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
onPlay={playTrack}
onEditField={canEdit ? editField : undefined}
+21
View File
@@ -514,7 +514,27 @@ export interface FolderAddRequest {
}
export interface FolderAddPreview extends ImportPreview {
/** Some of the files to add are on an external drive. */
removable: boolean
/** How many, and on which drives — per FILE, since a drop can mix drives. */
removable_count?: number
removable_drives?: string[]
/** Copy mode: files already inside the import folder (copying makes a
* second copy beside them). */
in_destination?: number
}
/** What files dropped onto the window from the OS resolved to: the audio in
* them (folders searched all the way down), listed as a folder lists its
* files — a file the collection holds is its collection track. */
export interface DroppedFiles {
tracks: Track[]
/** Collection id → the file's folder id (= its path), for held rows. */
files: Record<string, string>
/** Dropped files that are not audio this library can hold, or are gone. */
skipped: number
/** Too many files: only the first 20,000 are included. */
truncated: boolean
}
export type JobState = 'running' | 'done' | 'failed' | 'cancelled'
@@ -1177,6 +1197,7 @@ export const api = {
folderAddPreview: (body: FolderAddRequest) =>
send<FolderAddPreview>('POST', '/api/folder/add/preview', body),
folderAdd: (body: FolderAddRequest) => send<JobStatus>('POST', '/api/folder/add', body),
folderDropped: (paths: string[]) => send<DroppedFiles>('POST', '/api/folder/dropped', { paths }),
// ---- import ----
importPreview: (body: ImportRequest) => send<ImportPreview>('POST', '/api/import/preview', body),
/** Starts the job and returns immediately — poll `job()` for progress. */
+38 -7
View File
@@ -1,7 +1,7 @@
import { createPortal } from 'react-dom'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus } from '../api'
import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus, type TrackOrigin } from '../api'
import { useCaps } from '../lib/capabilities'
import { placedAudioSummary } from '../lib/platformCopy'
import { FolderPicker } from './FolderPicker'
@@ -25,6 +25,10 @@ import { FolderPicker } from './FolderPicker'
* library can reach them, so they are added in place, uploaded nowhere and
* nothing asked (decided 2026-10-10).
*
* Files dropped onto the window from the OS (`lib/fileDrop.ts`) arrive here
* too, so a drop asks exactly what the sidebar's Add to Collection asks. A
* drop can mix drives, so the external-drive warning counts files per drive.
*
* A playlist or export target still needs the files in the collection first —
* both hold collection track ids — so the dialog says so rather than doing it
* silently. Files the collection already holds are not added again, but still
@@ -45,15 +49,32 @@ export interface AddTarget {
name: string
}
/** Where tracks headed for the collection come from: another library's or a
* folder's track ids, or — `dropped` — paths dragged in from the OS. */
export type ForeignOrigin = TrackOrigin | 'dropped'
interface Props {
trackIds: string[]
target: AddTarget | null
/** A line about what was left out before the dialog (a drop's non-audio files). */
note?: string | null
onClose: () => void
onDone: (msg: string) => void
onError: (msg: string) => void
}
export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: Props) {
/** The leave-in-place warning, per drive: a drop can mix the computer's own
* disk with a stick, and only the stick's files go missing on unplug. */
function removableWarning(p: FolderAddPreview, newCount: number): string {
const count = p.removable_count ?? newCount
const drives = p.removable_drives ?? []
const where = drives.length === 1 ? `${drives[0]}, an external drive` : 'external drives'
const what = count >= newCount ? 'These files are' : `${count} of these files are`
const unplugged = drives.length === 1 ? 'it is' : 'they are'
return `${what} on ${where}. They will go missing from your collection whenever ${unplugged} unplugged.`
}
export function AddFilesDialog({ trackIds, target, note, onClose, onDone, onError }: Props) {
const qc = useQueryClient()
// The LIBRARY's capabilities (this dialog is mounted outside the browsed
// view's swapped context). A library that places its own audio — a stick —
@@ -177,9 +198,12 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
const newCount = p?.importable ?? 0
const shown = places ? 'placed' : mode
const libraryName = places ? caps.save.app_name : 'your collection'
// Every file is held already: nothing is copied or referenced, so there is
// nothing to ask — only the target to fill.
const nothingNew = !!p && newCount === 0 && p.existing.length > 0
const canAdd =
!starting && shown !== null && !!p && (newCount > 0 || (!!target && p.existing.length > 0)) &&
p.enough_space !== false
!starting && (shown !== null || nothingNew) && !!p &&
(newCount > 0 || (!!target && p.existing.length > 0)) && p.enough_space !== false
const title = target
? `Add ${n} track${n === 1 ? '' : 's'} to ${target.name}`
@@ -265,7 +289,9 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
</div>
)}
{!places && !uploads && !onServer && (
{note && <div className="text-xs text-muted">{note}</div>}
{!places && !uploads && !onServer && !nothingNew && (
<div className="space-y-1">
{option(
'copy',
@@ -296,9 +322,14 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
)}
{mode === 'reference' && p?.removable && (
<div className="rounded well px-3 py-2 text-xs text-gold">{removableWarning(p, newCount)}</div>
)}
{mode === 'copy' && !!p?.in_destination && (
<div className="rounded well px-3 py-2 text-xs text-gold">
These files are on an external drive. They will go missing from your
collection whenever the drive is unplugged.
{p.in_destination === newCount ? 'These files are' : `${p.in_destination} of these files are`}{' '}
already in your import folder. Copying makes a second copy beside{' '}
{p.in_destination === 1 ? 'it' : 'them'}.
</div>
)}
+25
View File
@@ -14,6 +14,8 @@ export const APP_SETTING_DEFAULTS = {
expandPlaylistFolders: false,
/** Read by the backend when an export runs (`main.run_export`). */
exportRootFolder: false,
/** Decimal places on the deck's ELAPSED / REMAIN readouts (0–3). */
timeReadoutDecimals: 1,
}
type AppSettingKey = keyof typeof APP_SETTING_DEFAULTS
@@ -29,6 +31,7 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
const qc = useQueryClient()
const expandFolders = useAppSetting('expandPlaylistFolders')
const exportRootFolder = useAppSetting('exportRootFolder')
const timeDecimals = useAppSetting('timeReadoutDecimals')
const [error, setError] = useState<string | null>(null)
useEffect(() => {
@@ -95,6 +98,28 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
</span>
</label>
</section>
<section className="space-y-2">
<h3 className="text-[11px] font-semibold uppercase tracking-wider text-faint">Deck</h3>
<label className="flex items-start justify-between gap-4">
<span className="min-w-0">
<span className="block text-sm text-text">Time readout precision</span>
<span className="block text-xs text-faint">
Decimal places on the Elapsed and Remain readouts. 1 shows tenths, 3 milliseconds.
</span>
</span>
<select
className="shrink-0 rounded-lg well px-2 py-1 text-sm text-text outline-none"
value={timeDecimals}
onChange={(e) => void set({ timeReadoutDecimals: Number(e.target.value) })}
>
{['00:00', '00:00.0', '00:00.00', '00:00.000'].map((sample, n) => (
<option key={n} value={n}>
{n} — {sample}
</option>
))}
</select>
</label>
</section>
{error && <div className="text-xs text-pink">{error}</div>}
</div>
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
+23 -9
View File
@@ -1,6 +1,6 @@
import { createPortal } from 'react-dom'
import type { ReactNode } from 'react'
import { useEffect, useRef, useState } from 'react'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { Icon } from '../lib/icons'
/** One row of a menu: an action, a submenu (`label ▸`), or a section heading. */
@@ -69,6 +69,27 @@ export function ContextMenu({ x, y, items, onClose }: Props) {
}
}, [])
// Opened near the bottom of the window, the menu moves UP so its bottom sits
// at the window's edge, and only scrolls once it cannot fit at its natural
// height at all. The first render places it at the cursor; this measures the
// list's full height before paint and repositions it.
const [vertical, setVertical] = useState<{ top: number; maxHeight: number }>(() => {
const top = Math.min(y, window.innerHeight - 100)
return { top, maxHeight: Math.min(MENU_MAX_HEIGHT, window.innerHeight - top - 8) }
})
useLayoutEffect(() => {
const panel = rootRef.current?.firstElementChild as HTMLElement | null
const list = panel?.firstElementChild as HTMLElement | null
if (!panel || !list) return
const natural = Math.min(
MENU_MAX_HEIGHT,
panel.offsetHeight - list.clientHeight + list.scrollHeight,
)
const top = Math.max(8, Math.min(y, window.innerHeight - 8 - natural))
const maxHeight = Math.min(MENU_MAX_HEIGHT, window.innerHeight - top - 8)
setVertical((v) => (v.top === top && v.maxHeight === maxHeight ? v : { top, maxHeight }))
}, [y, items])
return createPortal(
// `contents`: the panels are fixed-positioned, so this wrapper must take no
// part in layout. As an ordinary empty block it became one more item in
@@ -78,14 +99,7 @@ export function ContextMenu({ x, y, items, onClose }: Props) {
items={items}
onClose={onClose}
className="min-w-[160px]"
style={(() => {
const top = Math.min(y, window.innerHeight - 100)
return {
top,
left: Math.min(x, window.innerWidth - 180),
maxHeight: Math.min(MENU_MAX_HEIGHT, window.innerHeight - top - 8),
}
})()}
style={{ ...vertical, left: Math.min(x, window.innerWidth - 180) }}
/>
</div>,
document.body,
+12 -6
View File
@@ -1,7 +1,7 @@
import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type ExportSet, type TrackOrigin } from '../api'
import type { AddTarget } from './AddFilesDialog'
import { api, type ExportSet } from '../api'
import type { AddTarget, ForeignOrigin } from './AddFilesDialog'
import { useCaps } from '../lib/capabilities'
import { ExportDialog } from './ExportDialog'
import { ExportRunDialog } from './ExportRunDialog'
@@ -31,7 +31,7 @@ interface Props {
onSelect: (s: Source) => void
onDone: (msg: string) => void
onError: (msg: string) => void
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void
}
export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign }: Props) {
@@ -151,7 +151,7 @@ function ExportRow({
onDelete: () => void
onDone: (msg: string) => void
onError: (msg: string) => void
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void
}) {
const qc = useQueryClient()
// The COLLECTION's capabilities (the sidebar sits outside the browsed view's
@@ -196,14 +196,20 @@ function ExportRow({
const accepts = (p: DragPayload) =>
p.kind === 'tracks'
? p.origin === 'collection' || (caps.writable && caps.tracks.addable)
: playlistIdsUnder(p.node).length > 0
: p.kind === 'files'
? caps.writable && caps.tracks.addable
: playlistIdsUnder(p.node).length > 0
const [dropRef, over] = useDropTarget<true>({
hint: (p) => (accepts(p) ? true : null),
label: (p) =>
p.kind === 'tracks' && p.origin === 'device'
? `Import into export ${set.name}…`
: `Add to export ${set.name}${p.kind === 'tracks' && p.origin === 'folder' ? '…' : ''}`,
: `Add to export ${set.name}${(p.kind === 'tracks' && p.origin === 'folder') || p.kind === 'files' ? '…' : ''}`,
onDrop: async (p) => {
if (p.kind === 'files') {
onAddForeign('dropped', p.paths, { kind: 'export', id: set.id, name: set.name })
return
}
if (p.kind === 'tracks' && p.origin !== 'collection') {
onAddForeign(p.origin, p.ids, { kind: 'export', id: set.id, name: set.name })
return
+53 -10
View File
@@ -1,11 +1,20 @@
import { useEffect, useRef } from 'react'
import type { CuePoint } from '../api'
import type { BeatGrid } from '../lib/beatgrid'
import { Icon } from '../lib/icons'
import { hasMod, MOD_NAME } from '../lib/modKey'
import { drawBeatgrid, drawCuePoint, drawCues, drawLoop, drawLoopIn, drawPlayhead } from '../lib/cues'
import { laneScales, makeSpans, paintRaw, rawSpans, tintAt, type RawWave } from '../lib/rawWave'
import { paintLane, paintWave, type WaveColumn } from '../lib/waveform'
interface Props {
cols: WaveColumn[]
/** The samples, for the raw view. */
raw?: RawWave | null
/** Draw the raw signal as a thin line instead of bars (the toggle under
the zoom buttons; owned by the parent, which persists it). */
rawMode?: boolean
onRawModeChange?: (raw: boolean) => void
currentTime: number
duration: number
cues: CuePoint[]
@@ -30,12 +39,14 @@ interface Props {
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). */
/** Click = mute toggle; Cmd/Ctrl-click = solo (mute all the others). */
onStemToggle?: (index: number, solo: boolean) => void
}
export interface StemLane {
data: Float32Array
/** The stem's samples, for the raw view. */
raw?: RawWave | null
name: string
color: string
/** Not muted. */
@@ -46,11 +57,9 @@ export interface StemLane {
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)
export const MIN_SEC = 0.25 // most zoomed-in (seconds across the view): a kick's attack spans dozens of px
export const MAX_SEC = 64 // most zoomed-out
export const DEFAULT_SEC = 16
@@ -62,6 +71,9 @@ export const DEFAULT_SEC = 16
*/
export function MainWaveform({
cols,
raw = null,
rawMode = false,
onRawModeChange,
currentTime,
duration,
cues,
@@ -89,6 +101,7 @@ export function MainWaveform({
const dragRef = useRef<{ startX: number; startTime: number; lastT: number; moved: boolean } | null>(
null,
)
const spansRef = useRef(makeSpans())
// Draw closes over the latest props/state; a ref lets the ResizeObserver call
// the current version without re-subscribing.
@@ -111,7 +124,25 @@ export function MainWaveform({
// 2 px bars with a 1 px gap: the texture that makes the scrolling view
// read as discrete energy rather than a smear.
const bars = { bar: Math.max(1, Math.round(2 * dpr)), gap: Math.max(1, Math.round(dpr)) }
if (lanes && lanes.length) {
// The raw line's minimum stroke, so silence and flat stretches still read.
const thick = Math.max(1, 1.25 * dpr)
const spans = spansRef.current
if (rawMode && lanes && lanes.length && lanes.every((l) => l.raw)) {
const laneH = h / lanes.length
const scales = laneScales(lanes.map((l) => l.raw!.peak), laneH / 2 - thick)
lanes.forEach((lane, k) => {
rawSpans(lane.raw!, startSec, endSec, w, spans)
ctx.globalAlpha = lane.audible ? 0.92 : 0.18
paintRaw(ctx, spans, k * laneH, laneH, scales[k], thick, lane.color)
})
ctx.globalAlpha = 1
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 if (rawMode && !lanes?.length && raw) {
rawSpans(raw, startSec, endSec, w, spans)
const scale = (h / 2 - thick) / Math.max(raw.peak, 1e-6)
paintRaw(ctx, spans, 0, h, scale, thick, (t) => tintAt(cols, duration, t))
} else 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) => {
@@ -245,8 +276,8 @@ export function MainWaveform({
<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})`}
onClick={(e) => onStemToggle?.(k, hasMod(e))}
title={`${lane.name} — click to mute, ${MOD_NAME}-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'
@@ -263,9 +294,10 @@ export function MainWaveform({
</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">
{/* Zoom in · raw/bars · zoom out, centred on the waveform's height.
stopPropagation on down so tapping a button doesn't begin a scratch
drag. */}
<div className="absolute right-2 top-1/2 flex -translate-y-1/2 flex-col gap-1">
<button
onPointerDown={(e) => e.stopPropagation()}
onClick={zoomIn}
@@ -275,6 +307,17 @@ export function MainWaveform({
>
+
</button>
<button
onPointerDown={(e) => e.stopPropagation()}
onClick={() => onRawModeChange?.(!rawMode)}
aria-pressed={rawMode}
aria-label="Raw waveform"
className="btn-glass flex h-6 w-6 items-center justify-center rounded-lg text-text backdrop-blur-md"
title={rawMode ? 'Raw waveform — click for bars' : 'Bars — click for the raw waveform: the exact shape of every transient'}
>
{/* The icon shows the mode in force: bars, or the raw line. */}
<Icon name={rawMode ? 'sine' : 'wave'} size={14} />
</button>
<button
onPointerDown={(e) => e.stopPropagation()}
onClick={zoomOut}
+75 -20
View File
@@ -21,18 +21,21 @@ import { CUE_TYPE_LABELS, cueTypeColor } from '../lib/cues'
import { keyColor } from '../lib/format'
import { readOnlyShort, readOnlyNotice } from '../lib/platformCopy'
import { analyzeStems, analyzeWaveform, type WaveColumn } from '../lib/waveform'
import type { RawWave } from '../lib/rawWave'
import { setAmbientFromArt } from '../lib/ambient'
import { Icon } from '../lib/icons'
import { ScratchEngine } from '../lib/scratchEngine'
import { PlaybackEngine } from '../lib/playbackEngine'
import { invalidateTrackLists } from '../lib/trackQueries'
import { AutoCueDialog, eventLabel } from './AutoCueDialog'
import { TrackInfoDialog } from './TrackInfoDialog'
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, type StemLane } from './MainWaveform'
import { OverviewWaveform } from './OverviewWaveform'
import { useAppSetting } from './AppSettings'
import { usePrefsWriter } from '../lib/prefs'
/** Keys that mute stems 1-4 (Shift = solo), by `KeyboardEvent.code`. */
@@ -59,15 +62,24 @@ interface Props {
cuesRefresh?: number
/** Reports whether the deck is playing, so the library can light its row. */
onPlayingChange?: (playing: boolean) => void
/** Opens Edit Tags for the loaded track — passed only where the library
* will accept the edit, so the cover popup offers it only then. */
onEditTags?: (track: Track) => void
}
/** m:ss.t — the deck's readouts show tenths, as a CDJ does. */
function fmtTenths(secs: number): string {
/** mm:ss.f — tenths by default, as a CDJ does; `places` is the
* `timeReadoutDecimals` setting (0 drops the fraction). Truncates, never
* rounds, so the readout never shows a second before it has been reached. */
function fmtTime(secs: number, places: number): string {
if (!isFinite(secs) || secs < 0) secs = 0
const tenths = Math.floor(secs * 10)
const m = Math.floor(tenths / 600)
const s = Math.floor((tenths % 600) / 10)
return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}.${tenths % 10}`
const scale = 10 ** places
// The epsilon keeps e.g. 0.3 s from reading 0.299 at 3 places.
const units = Math.floor(secs * scale + 1e-6)
const whole = Math.floor(units / scale)
const m = Math.floor(whole / 60)
const s = whole % 60
const frac = places > 0 ? `.${(units % scale).toString().padStart(places, '0')}` : ''
return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}${frac}`
}
/**
@@ -102,6 +114,7 @@ export function PrepStrip({
origin = 'collection',
cuesRefresh = 0,
onPlayingChange,
onEditTags,
}: Props) {
const qc = useQueryClient()
const [playing, setPlaying] = useState(false)
@@ -111,9 +124,13 @@ export function PrepStrip({
// which the pointer's :active alone cannot, since the key never touches it.
const [cueHeld, setCueHeld] = useState(false)
const [current, setCurrent] = useState(0)
const timeDecimals = useAppSetting('timeReadoutDecimals')
const [duration, setDuration] = useState(0)
const [ready, setReady] = useState(false)
const [cols, setCols] = useState<WaveColumn[] | null>(null)
// The raw waveform's data: the mix's samples, or one per stem lane.
const [raw, setRaw] = useState<RawWave | null>(null)
const [stemRaws, setStemRaws] = useState<RawWave[] | 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
@@ -129,7 +146,9 @@ export function PrepStrip({
const [snap, setSnap] = useState(true)
const [selectedSlot, setSelectedSlot] = useState<number | null>(null)
const [cuePoint, setCuePoint] = useState(0) // floating "CUE" point (frontend-only)
const [infoOpen, setInfoOpen] = useState(false) // the cover's track-info popup
const [secPerView, setSecPerView] = useState(DEFAULT_SEC) // main-waveform zoom (persisted)
const [rawWave, setRawWave] = useState(false) // main waveform: raw line instead of bars (persisted)
// ONE size, in beats, for beat loops and beat jump alike (persisted).
const [beatSize, setBeatSize] = useState(4)
const [loopMode, setLoopMode] = useState<LoopMode>('beat')
@@ -164,7 +183,7 @@ export function PrepStrip({
const trackId = track?.id ?? null
// Main-waveform zoom persists to userprefs.json so it survives track switches
// Main-waveform zoom (and the raw/bars toggle) persists to userprefs.json so it survives track switches
// (MainWaveform unmounts during each load) and app restarts. Hydrate once from
// the shared ['prefs'] query, then persist changes through the shared,
// debounced prefs writer (as App's column layout does).
@@ -178,11 +197,12 @@ export function PrepStrip({
if (typeof z === 'number' && isFinite(z)) {
setSecPerView(Math.min(MAX_SEC, Math.max(MIN_SEC, z)))
}
if ((prefsQuery.data as { mainWaveRaw?: unknown }).mainWaveRaw === true) setRawWave(true)
}, [prefsQuery.data])
useEffect(() => {
if (!zoomHydratedRef.current) return // don't clobber saved prefs pre-hydration
writePrefs({ mainZoomSec: secPerView })
}, [secPerView, writePrefs])
writePrefs({ mainZoomSec: secPerView, mainWaveRaw: rawWave })
}, [secPerView, rawWave, writePrefs])
// The loop/jump size persists the same way (survives track switches +
// restarts). `beatJumpBeats` is its name from when only beat jump had a size;
@@ -271,11 +291,15 @@ export function PrepStrip({
scratchRef.current = null
if (!trackId) {
setCols(null)
setRaw(null)
setStemRaws(null)
setWaveStatus('loading')
return
}
let cancelled = false
setCols(null)
setRaw(null)
setStemRaws(null)
setStems(null)
setStemLanes(null)
setWaveStatus('loading')
@@ -286,15 +310,17 @@ export function PrepStrip({
.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 }
return { cols: res.cols, buffers: res.buffers, lanes: res.lanes, stems: found, raw: null, raws: res.raws }
}
const res = await analyzeWaveform(trackAudioUrl(origin, trackId))
return { cols: res.cols, buffers: [res.buffer], lanes: null, stems: null }
return { cols: res.cols, buffers: [res.buffer], lanes: null, stems: null, raw: res.raw, raws: null }
})
load
.then((res) => {
if (cancelled) return
setCols(res.cols)
setRaw(res.raw)
setStemRaws(res.raws)
setStems(res.stems)
setStemLanes(res.lanes)
setWaveStatus('ready')
@@ -917,7 +943,9 @@ export function PrepStrip({
const activeMarkerIndex = grid ? grid.markerIndexAt(current) : -1
const activeMarker = activeMarkerIndex >= 0 ? grid!.markers[activeMarkerIndex] : null
// ~4px of the current zoom, so "on the marker" stays usable at 2s and 64s/view.
const markerHitSec = Math.max(0.01, secPerView / 250)
// ~4 px of the view either side, so "at a marker" stays a marker-sized
// target at deep zoom instead of 4% of a 0.25 s view.
const markerHitSec = Math.max(0.001, secPerView / 250)
const atMarker = !!grid && grid.isOnMarker(current, markerHitSec)
const beforeFirstMarker = !!grid && current < grid.markers[0].start - GRID_EPS
@@ -1097,6 +1125,7 @@ export function PrepStrip({
stems && stemLanes
? stems.map((st, k) => ({
data: stemLanes[k],
raw: stemRaws?.[k] ?? null,
name: st.name,
color: st.color,
audible: stemLevels[k] > 0,
@@ -1282,7 +1311,10 @@ export function PrepStrip({
<div className="glass flex h-[19.75rem] shrink-0 flex-col gap-2 p-4">
{/* ---- Header: the track, its readouts, the analysis actions ---- */}
<div className="flex h-12 shrink-0 items-center gap-3">
<CoverThumb trackId={track && origin === 'collection' ? track.id : null} />
<CoverThumb
trackId={track && origin === 'collection' ? track.id : null}
onOpen={track ? () => setInfoOpen(true) : undefined}
/>
<div className="min-w-0 flex-1">
{track ? (
<>
@@ -1314,12 +1346,12 @@ export function PrepStrip({
<div className="well flex h-11 shrink-0 items-stretch rounded-xl">
<div className="flex flex-col justify-center gap-px px-4">
<span className="text-[10px] tracking-[0.08em] text-faint">ELAPSED</span>
<span className="font-mono text-[17px] font-medium">{fmtTenths(current)}</span>
<span className="font-mono text-[17px] font-medium">{fmtTime(current, timeDecimals)}</span>
</div>
<span aria-hidden className="my-2 w-px bg-line" />
<div className="flex flex-col justify-center gap-px px-4">
<span className="text-[10px] tracking-[0.08em] text-faint">REMAIN</span>
<span className="font-mono text-[17px] font-medium">−{fmtTenths(Math.max(0, duration - current))}</span>
<span className="font-mono text-[17px] font-medium">−{fmtTime(Math.max(0, duration - current), timeDecimals)}</span>
</div>
<span aria-hidden className="my-2 w-px bg-line" />
<div className="flex flex-col justify-center gap-px px-4">
@@ -1390,6 +1422,9 @@ export function PrepStrip({
{showWaves ? (
<MainWaveform
cols={cols}
raw={raw}
rawMode={rawWave}
onRawModeChange={setRawWave}
currentTime={current}
duration={duration}
cues={cueData?.cues ?? []}
@@ -1567,6 +1602,21 @@ export function PrepStrip({
onClose={() => setPadMenu(null)}
/>
)}
{infoOpen && track && (
<TrackInfoDialog
track={track}
artUrl={origin === 'collection' ? api.artUrl(track.id) : null}
onClose={() => setInfoOpen(false)}
onEditTags={
onEditTags
? () => {
setInfoOpen(false)
onEditTags(track)
}
: undefined
}
/>
)}
{autoOpen && track && (
<AutoCueDialog
track={track}
@@ -1585,14 +1635,19 @@ export function PrepStrip({
/**
* The loaded track's sleeve. Until it loads — and for a track with no art — a
* swatch of the ambient colours stands in, so the header never has a hole in it.
* With a track loaded it is a button that opens the track-info popup.
*/
function CoverThumb({ trackId }: { trackId: string | null }) {
function CoverThumb({ trackId, onOpen }: { trackId: string | null; onOpen?: () => void }) {
const [failed, setFailed] = useState<string | null>(null)
const showArt = trackId != null && failed !== trackId
return (
<div
aria-hidden
className="relative h-11 w-11 shrink-0 overflow-hidden rounded-xl shadow-[inset_0_1px_0_rgb(255_255_255/0.35),0_8px_24px_-6px_var(--amb-2)]"
<button
type="button"
onClick={onOpen}
disabled={!onOpen}
title={onOpen ? 'Track info' : undefined}
aria-label="Track info"
className="relative h-11 w-11 shrink-0 overflow-hidden rounded-xl shadow-[inset_0_1px_0_rgb(255_255_255/0.35),0_8px_24px_-6px_var(--amb-2)] transition-transform enabled:cursor-zoom-in enabled:hover:scale-105 enabled:active:scale-95 disabled:cursor-default"
style={{ background: 'linear-gradient(135deg, var(--amb-1), var(--amb-2) 55%, var(--amb-3))' }}
>
{showArt && (
@@ -1604,6 +1659,6 @@ function CoverThumb({ trackId }: { trackId: string | null }) {
onError={() => setFailed(trackId)}
/>
)}
</div>
</button>
)
}
+58 -6
View File
@@ -1,24 +1,41 @@
import { createPortal } from 'react-dom'
import { useEffect, useRef, useState } from 'react'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import type { SortingState } from '@tanstack/react-table'
import { maxPosition, moveToPosition } from '../lib/playlistOrder'
import { COLUMN_MENU } from '../lib/trackColumns'
interface Props {
/** The playlist's full entry order — never the sorted or filtered view, so
* the move is safe whatever the table is showing. */
order: string[]
/** The tracks to move; they keep their playlist order as one block. */
/** The tracks to move, in the order the table shows them. */
ids: string[]
/** The table's sort. While there is one, the block may keep that order
* instead of its playlist order — which writes the sort into the playlist. */
sorting: SortingState
onMove: (order: string[]) => void
onClose: () => void
}
/** "Set Position…": type where the first selected track should end up. */
export function SetPositionDialog({ order, ids, onMove, onClose }: Props) {
/** "Key" / "Key descending, then BPM" — the sort as the Order choice names it. */
function describeSort(sorting: SortingState): string {
const label = (id: string) => COLUMN_MENU.find((c) => c.id === id)?.label ?? id
return sorting.map((s) => `${label(s.id)}${s.desc ? ' descending' : ''}`).join(', then ')
}
/** "Set Position…": type where the first selected track should end up, and —
* while the table is sorted — whether the block keeps its playlist order or
* takes the sorted one. */
export function SetPositionDialog({ order, ids, sorting, onMove, onClose }: Props) {
const moving = new Set(ids)
const count = order.filter((id) => moving.has(id)).length
const max = maxPosition(order, moving)
const current = order.findIndex((id) => moving.has(id)) + 1
const [value, setValue] = useState(String(current))
// With one track there is no order to choose; unsorted, both are the same.
const canSort = sorting.length > 0 && count > 1
const [mode, setMode] = useState<'playlist' | 'sorted'>('sorted')
const sorted = canSort && mode === 'sorted'
const input = useRef<HTMLInputElement>(null)
useEffect(() => input.current?.select(), [])
@@ -28,7 +45,7 @@ export function SetPositionDialog({ order, ids, onMove, onClose }: Props) {
const submit = () => {
if (position === null) return
const next = moveToPosition(order, moving, position)
const next = moveToPosition(order, moving, position, sorted ? ids : undefined)
if (next.some((id, i) => id !== order[i])) onMove(next)
onClose()
}
@@ -41,6 +58,26 @@ export function SetPositionDialog({ order, ids, onMove, onClose }: Props) {
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const option = (value: 'playlist' | 'sorted', label: string, detail: ReactNode) => (
<label
className={`flex cursor-pointer gap-3 rounded-lg px-3 py-2 ${
mode === value ? 'is-selected' : 'hover:bg-ink-850'
}`}
>
<input
type="radio"
name="position-order"
checked={mode === value}
onChange={() => setMode(value)}
className="mt-0.5 accent-accent"
/>
<span className="min-w-0 flex-1">
<span className="block text-text">{label}</span>
<span className="block text-xs text-faint">{detail}</span>
</span>
</label>
)
const span = (p: number) => (count > 1 ? `#${p}–${p + count - 1}` : `#${p}`)
return createPortal(
@@ -79,9 +116,24 @@ export function SetPositionDialog({ order, ids, onMove, onClose }: Props) {
{position === null
? 'Type a position.'
: count > 1
? `Will occupy ${span(position)}`
? `Will occupy ${span(position)}${canSort ? '' : ', in the order they have in the playlist.'}`
: `Now ${span(current)} · will be ${span(position)}`}
</div>
{canSort && (
<div role="radiogroup" aria-label="Order" className="space-y-1">
<div className="text-xs uppercase tracking-wide text-faint">Order</div>
{option(
'sorted',
`As sorted: ${describeSort(sorting)}`,
'In the order shown here. The playlist keeps this order when you clear the sort.',
)}
{option(
'playlist',
'Playlist order',
'In the order they have in the playlist now, whatever the sort shows.',
)}
</div>
)}
</div>
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
<button
+20 -1
View File
@@ -38,6 +38,25 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
return () => document.removeEventListener('mousedown', onDoc)
}, [open])
// The `?` key opens the shortcut map from anywhere — unless typing, or
// something already holds the keyboard. Pressed as it is, no Shift: by its
// position (the US/UK "/ ?" key), and by the character on layouts that put
// `?` elsewhere (typed with Shift there).
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.metaKey || e.ctrlKey || e.altKey) return
if (!(e.code === 'Slash' && !e.shiftKey) && e.key !== '?') return
const t = e.target as HTMLElement | null
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable)) return
if (document.querySelector('[aria-modal="true"], [role="menu"]')) return
e.preventDefault()
setOpen(false)
setShowShortcuts(true)
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [])
const item =
'flex w-full flex-col items-start rounded-[10px] px-2.5 py-1.5 text-left hover:bg-ink-800'
@@ -122,7 +141,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
className={item}
>
<span className="text-sm text-text">View Shortcuts</span>
<span className="text-[11px] text-faint">Every keyboard shortcut in one list</span>
<span className="text-[11px] text-faint">Every keyboard shortcut, on a keyboard (?)</span>
</button>
</div>
)}
+514 -114
View File
@@ -1,112 +1,167 @@
import { createPortal } from 'react-dom'
import { useEffect } from 'react'
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'
import { useCaps } from '../lib/capabilities'
import { Icon } from '../lib/icons'
import {
ARROW_GAP,
ARROW_KEYS,
AREA_COLORS,
AREAS,
KEY_ROWS,
KEYBOARD_UNITS,
KEYS_BY_CODE,
LAYER_NAMES,
LAYERS,
MODIFIER_KEY,
MOUSE,
bindings,
modifierLayer,
padRange,
unusedNote,
type Area,
type Binding,
type KeyDef,
type Layer,
type MouseGesture,
} from '../lib/shortcuts'
interface Props {
onClose: () => void
}
// Cmd on macOS, Ctrl elsewhere — the handlers accept either, but a list that
// 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'
/** Key unit bounds, px. The map shrinks to fit the dialog; below LABEL_MIN the
* words on the keys go (the caption still explains each key), below SHORT_MIN
* the long modifier legends become symbols. */
const UNIT_MAX = 52
const UNIT_MIN = 20
const LABEL_MIN = 44
const SHORT_MIN = 38
type Row = { keys: string[][]; action: string }
type Section = { title: string; rows: Row[] }
const ALL_AREAS = Object.keys(AREAS) as Area[]
const matchText = (b: Binding) => `${b.text} ${b.label}`.toLowerCase()
const mouseText = (r: MouseGesture) => `${r.gesture} ${r.on ?? ''} ${r.text}`.toLowerCase()
/** Hotcue keys are digits in pad order, 0 being the tenth, so the list follows
* the loaded library's bank size rather than hard-coding eight. */
function hotcueKeys(slots: number): string {
const n = Math.min(slots, 10)
if (n <= 0) return '1'
if (n <= 9) return `1–${n}`
return '1–9, 0'
}
function sections(slots: number): Section[] {
const pads = hotcueKeys(slots)
return [
{
title: 'Deck',
rows: [
{ keys: [['Space']], action: 'Play / pause' },
{ keys: [['C']], action: 'CUE — jump back, set, or hold to preview' },
{ keys: [['←'], ['→']], action: 'Beat jump back / forward — or move the loop, while one plays' },
{ keys: [[MOD, '↓'], [MOD, '↑']], action: 'Halve / double the loop and jump size' },
{ 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' },
],
},
{
title: 'Track list',
rows: [
{ keys: [['Enter']], action: 'Load and play the highlighted track' },
{ keys: [['↑'], ['↓']], action: 'Move the selection' },
{ keys: [['Shift', '↑'], ['Shift', '↓']], action: 'Extend the selection' },
{ keys: [[MOD, 'A']], action: 'Select all' },
{ keys: [['Esc']], action: 'Clear the selection' },
{ keys: [['Delete']], action: 'Remove from this playlist' },
{ keys: [['Shift', 'Click']], action: 'Select a range' },
{ keys: [[MOD, 'Click']], action: 'Add to / remove from the selection' },
{ keys: [['Double-click']], action: 'Edit a cell' },
{ keys: [['Right-click']], action: 'Track menu (header: choose columns)' },
{ keys: [['Drag rows']], action: 'Onto a playlist or export to add, onto the deck to load, within a playlist to reorder' },
{ keys: [[ALT_KEY, 'Drag']], action: 'Move tracks to another playlist (out of this one)' },
{ keys: [['Esc']], action: 'While dragging: cancel the drag' },
],
},
{
title: 'Sidebar',
rows: [
{ keys: [['Right-click']], action: 'New playlist or folder, rename, delete' },
{ keys: [['Drag']], action: 'Rearrange playlists and folders; onto an export to add one' },
],
},
{
title: 'Fields & dialogs',
rows: [
{ keys: [['Enter']], action: 'Save the edit / confirm' },
{ keys: [['Esc']], action: 'Cancel / close' },
],
},
]
}
function Keys({ combo }: { combo: string[] }) {
return (
<span className="inline-flex items-center gap-0.5">
{combo.map((k, i) => (
<kbd
key={i}
className="min-w-[1.5rem] rounded border border-line bg-ink-800 px-1.5 py-0.5 text-center font-sans text-[11px] text-text"
>
{k}
</kbd>
))}
</span>
)
}
/** Every keyboard shortcut (and the mouse gestures that go with them), from the
* settings menu. Keep in step with the handlers in `PrepStrip` and `TrackTable`
* — this list is written out by hand, not derived from them. */
/** Every shortcut, drawn on a keyboard: a key lights in the colour of what it
* does, pointing at (or pressing) it explains it, and holding a modifier — or
* picking one above — relights the map with that layer. Mouse gestures are
* listed beneath. The content lives in `lib/shortcuts.ts`. */
export function ShortcutsDialog({ onClose }: Props) {
const slots = useCaps().cues.hotcue_slots
const binds = useMemo(() => bindings(slots), [slots])
const [sticky, setSticky] = useState<Layer>('base')
const [held, setHeld] = useState<ReadonlySet<Layer>>(new Set())
const [hover, setHover] = useState<string | null>(null)
const [pressed, setPressed] = useState<string | null>(null)
const [query, setQuery] = useState('')
const [areas, setAreas] = useState<ReadonlySet<Area>>(new Set(ALL_AREAS))
const layer: Layer = held.has('mod') ? 'mod' : held.has('shift') ? 'shift' : sticky
const q = query.trim().toLowerCase()
// ---- fit: one key unit from the width the map has ----
const fitRef = useRef<HTMLDivElement>(null)
const [unit, setUnit] = useState(UNIT_MAX)
useLayoutEffect(() => {
const el = fitRef.current
if (!el) return
const fit = () => {
const u = Math.floor(el.clientWidth / KEYBOARD_UNITS)
setUnit(Math.max(UNIT_MIN, Math.min(UNIT_MAX, u)))
}
fit()
const ro = new ResizeObserver(fit)
ro.observe(el)
return () => ro.disconnect()
}, [])
// ---- keyboard: pressing a key explains it rather than doing it ----
// Capture phase on window, so the deck's and the table's own listeners (which
// are on window too, bubbling) never see a key pressed in here.
const queryRef = useRef(query)
queryRef.current = query
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
let release: number | undefined
const onDown = (e: KeyboardEvent) => {
const inField = (e.target as HTMLElement | null)?.tagName === 'INPUT'
if (e.key === 'Escape') {
e.preventDefault()
e.stopPropagation()
if (inField && queryRef.current) setQuery('')
else onClose()
return
}
if (inField) return
const mod = modifierLayer(e.code)
if (mod) {
setHeld((h) => new Set(h).add(mod))
return
}
if (e.code === 'Tab' || !KEYS_BY_CODE[e.code]) return
e.stopPropagation()
// Space / Enter still press a focused control (a layer tab, a modifier key).
const t = e.target as HTMLElement | null
if ((e.code === 'Space' || e.code === 'Enter') && t?.tagName === 'BUTTON' && !t.dataset.mapKey) return
e.preventDefault()
setHover(e.code)
setPressed(e.code)
window.clearTimeout(release)
release = window.setTimeout(() => setPressed(null), 160)
}
const onUp = (e: KeyboardEvent) => {
const mod = modifierLayer(e.code)
if (mod) {
setHeld((h) => {
const next = new Set(h)
next.delete(mod)
return next
})
} else if (KEYS_BY_CODE[e.code] && (e.target as HTMLElement | null)?.tagName !== 'INPUT') {
e.stopPropagation() // the deck's keyup ends a held cue/hotcue preview
}
}
const onBlur = () => setHeld(new Set())
window.addEventListener('keydown', onDown, true)
window.addEventListener('keyup', onUp, true)
window.addEventListener('blur', onBlur)
return () => {
window.clearTimeout(release)
window.removeEventListener('keydown', onDown, true)
window.removeEventListener('keyup', onUp, true)
window.removeEventListener('blur', onBlur)
}
}, [onClose])
const visible = (l: Layer, code: string) => (binds[l][code] ?? []).filter((b) => areas.has(b.area))
const layerCount = (l: Layer) =>
Object.values(binds[l]).flat().filter((b) => areas.has(b.area) && (!q || matchText(b).includes(q))).length +
MOUSE.flatMap((c) => c.rows).filter((r) => (r.mod ?? 'base') === l && (!q || mouseText(r).includes(q))).length
const pickLayer = (l: Layer) => setSticky((s) => (s === l && l !== 'base' ? 'base' : l))
const toggleArea = (a: Area) =>
setAreas((cur) => {
const next = new Set(cur)
if (next.has(a) && next.size > 1) next.delete(a)
else next.add(a)
return next
})
const gap = Math.max(2, Math.round(unit / 10))
const keyProps = {
unit,
gap,
labels: unit >= LABEL_MIN,
short: unit < SHORT_MIN,
layer,
hover,
pressed,
q,
visible,
noted: (code: string) => !!unusedNote(code, slots),
bound: (code: string) => LAYERS.some((l) => binds[l][code]),
onHover: setHover,
onPick: pickLayer,
}
return createPortal(
<div
aria-modal="true"
@@ -114,42 +169,387 @@ export function ShortcutsDialog({ onClose }: Props) {
onClick={onClose}
>
<div
className="flex max-h-full w-full max-w-lg flex-col overflow-hidden glass-overlay"
className="flex max-h-full w-full max-w-[960px] flex-col overflow-hidden glass-overlay"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between border-b border-line px-5 py-4">
<div className="flex flex-wrap items-center gap-3 border-b border-line py-3.5 pl-5 pr-4">
<div className="text-[15px] font-semibold tracking-tight">Keyboard Shortcuts</div>
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search shortcuts"
aria-label="Search shortcuts"
className="well ml-auto w-64 min-w-0 rounded-[9px] border border-line px-2.5 py-1.5 text-[13px] text-text outline-none"
/>
<button
onClick={onClose}
aria-label="Close"
className="rounded px-1.5 text-muted hover:bg-ink-800 hover:text-text"
className="h-7 w-7 rounded-md text-lg leading-none text-muted hover:bg-ink-800 hover:text-text"
>
×
</button>
</div>
<div className="space-y-5 overflow-y-auto px-5 py-4">
{sections(slots).map((s) => (
<section key={s.title}>
<div className="mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-faint">
{s.title}
</div>
<div className="divide-y divide-line/60">
{s.rows.map((r, i) => (
<div key={i} className="flex items-center justify-between gap-4 py-1.5">
<span className="text-sm text-muted">{r.action}</span>
<span className="flex shrink-0 items-center gap-1.5">
{r.keys.map((combo, j) => (
<Keys key={j} combo={combo} />
))}
</span>
<div className="overflow-y-auto">
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2.5 px-5 pb-1 pt-3.5">
<div className="well inline-flex flex-wrap gap-0.5 rounded-[10px] p-[3px]">
{LAYERS.map((l) => (
<button
key={l}
onClick={() => setSticky(l)}
aria-pressed={l === layer}
className={`inline-flex items-baseline gap-1.5 rounded-[7px] px-2.5 py-1 text-xs font-medium ${
l === layer ? 'bg-ink-600 text-text' : 'text-muted hover:text-text'
}`}
>
{LAYER_NAMES[l]}
<span className="font-mono text-[10px] text-faint">{layerCount(l)}</span>
</button>
))}
</div>
<div className="flex flex-wrap gap-1.5">
{ALL_AREAS.map((a) => (
<button
key={a}
onClick={() => toggleArea(a)}
aria-pressed={areas.has(a)}
className={`inline-flex items-center gap-1.5 rounded-full border border-line py-0.5 pl-2 pr-2.5 text-[11.5px] font-medium text-muted ${
areas.has(a) ? '' : 'opacity-40'
}`}
>
<i
className="h-[7px] w-[7px] rounded-full"
style={{ background: AREA_COLORS[a], boxShadow: areas.has(a) ? `0 0 8px ${AREA_COLORS[a]}` : undefined }}
/>
{AREAS[a]}
</button>
))}
</div>
</div>
<div ref={fitRef} className="mx-5 mb-2.5 mt-4">
<div
className="mx-auto flex w-max items-end"
style={{ gap: unit * ARROW_GAP }}
onPointerLeave={() => setHover(null)}
>
<div className="flex flex-col" style={{ gap }}>
{KEY_ROWS.map((row, i) => (
<div key={i} className="flex" style={{ gap, marginBottom: i === 0 ? gap * 0.4 : 0 }}>
{row.map((k) => (
<Key key={k.code} def={k} fnRow={i === 0} {...keyProps} />
))}
</div>
))}
</div>
</section>
))}
<div className="grid" style={{ gap, gridTemplateColumns: `repeat(3, ${unit - gap}px)` }}>
{ARROW_KEYS.map((k, i) =>
k ? <Key key={k.code} def={k} fnRow={false} {...keyProps} /> : <span key={i} />,
)}
</div>
</div>
</div>
<div
aria-live="polite"
// A FIXED height, so the dialog does not resize under the pointer as
// it moves between keys: tall enough for the fullest key (three
// lines + "Also on this key"); search results scroll inside it.
className="well mx-5 flex h-32 shrink-0 flex-col gap-[7px] overflow-y-auto rounded-xl px-3.5 py-3 text-[13px] text-muted"
>
<Caption
hover={hover}
layer={layer}
q={q}
query={query}
slots={slots}
binds={binds}
areas={areas}
/>
</div>
<div className="px-5 pb-2 pt-5">
<div className="mb-2.5 text-[10px] font-semibold uppercase tracking-wider text-faint">Mouse</div>
<div className="grid grid-cols-[repeat(auto-fit,minmax(250px,1fr))] gap-x-7 gap-y-2">
{MOUSE.map((col) => (
<div key={col.title} className="min-w-0">
<div className="pb-1.5 text-xs font-semibold text-muted">{col.title}</div>
{col.rows.map((r, i) => {
const m = r.mod ?? 'base'
const hit = !q || mouseText(r).includes(q)
const lit = layer !== 'base' && m === layer && hit
const dim = (layer !== 'base' && m !== layer) || !hit
return (
<div
key={i}
className={`-mx-1.5 grid grid-cols-[minmax(8.5rem,auto)_1fr] items-baseline gap-2.5 rounded-md border-t px-1.5 py-1 text-[12.5px] transition-opacity ${
lit ? 'border-transparent bg-accent-soft text-text' : 'border-line text-muted'
} ${dim ? 'opacity-30' : ''}`}
>
<span className="inline-flex flex-wrap items-baseline gap-1">
{r.mod && <Kbd>{MODIFIER_KEY[r.mod]}</Kbd>}
<span className="inline-flex items-center gap-1 whitespace-nowrap rounded-full border border-dashed border-ink-600 py-px pl-1.5 pr-2 text-[11px] font-medium text-text">
<Icon name="mouse" size={11} strokeWidth={2} />
{r.gesture}
{r.on ? ` ${r.on}` : ''}
</span>
</span>
<span>{r.text}</span>
</div>
)
})}
</div>
))}
</div>
</div>
<div className="mt-2.5 border-t border-line px-5 py-3 text-xs text-faint">
Press the <Kbd>?</Kbd> key anywhere to open this list.
</div>
</div>
</div>
</div>,
document.body,
)
}
function Kbd({ children }: { children: ReactNode }) {
return (
<kbd className="min-w-[1.5em] rounded-[5px] border border-b-2 border-line bg-ink-800 px-1.5 py-px text-center font-mono text-[11px] text-text">
{children}
</kbd>
)
}
function Combo({ layer, code }: { layer: Layer; code: string }) {
const legend = KEYS_BY_CODE[code]?.legend ?? code
return (
<span className="inline-flex shrink-0 gap-[3px]">
{layer !== 'base' && <Kbd>{MODIFIER_KEY[layer]}</Kbd>}
<Kbd>{legend}</Kbd>
</span>
)
}
function Line({ layer, code, b, other }: { layer: Layer; code: string; b: Binding; other?: boolean }) {
return (
<div className={`flex flex-wrap items-baseline gap-2.5 ${other ? 'text-xs' : ''}`}>
<Combo layer={layer} code={code} />
<span className={`min-w-0 ${other ? 'text-muted' : 'text-text'}`}>{b.text}</span>
<span className="text-[9.5px] font-semibold uppercase tracking-wider" style={{ color: AREA_COLORS[b.area] }}>
{AREAS[b.area]}
</span>
</div>
)
}
const Sub = ({ children }: { children: ReactNode }) => (
<div className="mt-0.5 text-[10px] font-semibold uppercase tracking-wider text-faint">{children}</div>
)
function Caption({
hover,
layer,
q,
query,
slots,
binds,
areas,
}: {
hover: string | null
layer: Layer
q: string
query: string
slots: number
binds: ReturnType<typeof bindings>
areas: ReadonlySet<Area>
}) {
if (hover) {
const role = KEYS_BY_CODE[hover]?.role
if (role) {
const keys = Object.keys(binds[role]).length
const mouse = MOUSE.flatMap((c) => c.rows).filter((r) => r.mod === role).length
return (
<div className="flex flex-wrap items-baseline gap-2.5">
<Kbd>{MODIFIER_KEY[role]}</Kbd>
<span className="text-text">
Hold, or click, to light up what {LAYER_NAMES[role]} changes: {keys} key{keys === 1 ? '' : 's'} and{' '}
{mouse} mouse gesture{mouse === 1 ? '' : 's'}.
</span>
</div>
)
}
const here = binds[layer][hover] ?? []
const others = LAYERS.filter((l) => l !== layer && binds[l][hover])
return (
<>
{here.length ? (
here.map((b, i) => <Line key={i} layer={layer} code={hover} b={b} />)
) : (
<div className="flex flex-wrap items-baseline gap-2.5">
<Combo layer={layer} code={hover} />
<span>{unusedNote(hover, slots) ?? 'Does nothing in Konduktor.'}</span>
</div>
)}
{others.length > 0 && <Sub>Also on this key</Sub>}
{others.flatMap((l) => binds[l][hover].map((b, i) => <Line key={`${l}${i}`} layer={l} code={hover} b={b} other />))}
</>
)
}
if (q) {
const hits = LAYERS.flatMap((l) =>
Object.entries(binds[l]).flatMap(([code, bs]) =>
bs
.filter((b) => areas.has(b.area) && matchText(b).includes(q))
.map((b, i) => <Line key={`${l}${code}${i}`} layer={l} code={code} b={b} />),
),
)
const mouse = MOUSE.flatMap((c) => c.rows).filter((r) => mouseText(r).includes(q)).length
if (!hits.length && !mouse) return <span>No shortcut matches “{query.trim()}”.</span>
return (
<>
{hits}
{mouse > 0 && <Sub>{mouse} mouse gesture{mouse === 1 ? '' : 's'} below</Sub>}
</>
)
}
if (layer !== 'base') {
return (
<>
<span className="text-text">
Showing what {LAYER_NAMES[layer]} changes. The highlighted mouse gestures below use it too.
</span>
<span className="text-xs">Let go of the key, or pick “No modifier”, to go back.</span>
</>
)
}
return (
<>
<span className="text-text">Point at a key, or press it, to see what it does.</span>
<span className="text-xs">
Hold <Kbd>{MODIFIER_KEY.shift}</Kbd> or <Kbd>{MODIFIER_KEY.mod}</Kbd>, or pick one above, to see what each
modifier changes.
</span>
<span className="text-xs">
{padRange(slots)} are this library's {slots} hotcue pads; Q W E R are the stems of a stem track.
</span>
</>
)
}
interface KeyProps {
def: KeyDef
fnRow: boolean
unit: number
gap: number
labels: boolean
short: boolean
layer: Layer
hover: string | null
pressed: string | null
q: string
visible: (layer: Layer, code: string) => Binding[]
noted: (code: string) => boolean
bound: (code: string) => boolean
onHover: (code: string | null) => void
onPick: (layer: Layer) => void
}
function Key({ def, fnRow, unit, gap, labels, short, layer, hover, pressed, q, visible, noted, bound, onHover, onPick }: KeyProps) {
const { code, role } = def
const legend = short && def.short ? def.short : def.legend
const ents = role ? [] : visible(layer, code)
const first = ents[0]
const kc = first ? (first.color ?? AREA_COLORS[first.area]) : 'var(--color-faint)'
const on = role === layer
const miss = !!first && !!q && !ents.some((b) => matchText(b).includes(q))
const pad = first?.label === 'Pad' || first?.label === 'Delete'
const interactive = !!role || bound(code) || noted(code)
const inset = Math.max(2, Math.round(unit * 0.1))
const style: CSSProperties = {
width: (def.w ?? 1) * unit - gap,
height: fnRow ? Math.round(unit * 0.72) : unit - gap,
padding: `${Math.max(2, inset - 1)}px ${inset}px`,
borderRadius: pad ? Math.round(unit * 0.18) : Math.round(unit * 0.14),
borderColor: 'rgb(255 255 255 / 0.05)',
}
if (on) {
Object.assign(style, {
background: 'var(--color-accent)',
borderColor: 'transparent',
color: 'var(--color-ink-950)',
boxShadow: '0 0 22px -4px var(--color-accent)',
})
} else if (role) {
style.borderColor = 'rgb(255 255 255 / 0.12)'
} else if (first) {
Object.assign(style, {
background: pressed === code
? `color-mix(in oklab, ${kc} 45%, transparent)`
: `color-mix(in oklab, ${kc} ${pad ? 24 : 15}%, rgb(255 255 255 / 0.05))`,
borderColor: hover === code
? `color-mix(in oklab, ${kc} 85%, white)`
: `color-mix(in oklab, ${kc} 50%, transparent)`,
boxShadow: `0 0 18px -6px color-mix(in oklab, ${kc} 70%, transparent), inset 0 1px 0 rgb(255 255 255 / 0.1)`,
})
} else if (hover === code) {
style.borderColor = 'rgb(255 255 255 / 0.3)'
}
const legendSize = Math.max(8.5, Math.min(11, unit * 0.22)) - (role && !short ? 1 : 0)
const body = (
<>
<span
className={`whitespace-nowrap font-medium leading-none ${first || on ? (on ? '' : 'text-text') : ''}`}
style={{ fontSize: legendSize }}
>
{legend}
</span>
{labels && first && (
<span
className="max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-[9px] font-semibold leading-tight"
style={{ color: kc }}
>
{first.label}
</span>
)}
{ents.length > 1 && (
<span className="absolute right-1 top-1 flex gap-0.5">
{ents.map((b, i) => (
<i key={i} className="h-[5px] w-[5px] rounded-full" style={{ background: AREA_COLORS[b.area] }} />
))}
</span>
)}
</>
)
const className = `relative flex shrink-0 flex-col items-start justify-between border text-left transition-[background,border-color,opacity,transform,box-shadow] duration-150 ${
first || on ? '' : 'bg-ink-850'
} ${role && !on ? 'text-muted' : 'text-faint'} ${miss ? 'opacity-25' : ''} ${pressed === code ? 'scale-[0.96]' : ''}`
if (!interactive) {
return (
<span className={className} style={style} onPointerEnter={() => onHover(def.legend ? code : null)}>
{body}
</span>
)
}
return (
<button
type="button"
className={`${className} ${role ? 'cursor-pointer' : 'cursor-help'}`}
style={style}
aria-label={first ? `${def.legend}: ${first.text}` : def.legend}
aria-pressed={role ? on : undefined}
data-map-key={role ? undefined : code}
onPointerEnter={() => onHover(code)}
onFocus={() => onHover(code)}
onClick={() => role && onPick(role)}
>
{body}
</button>
)
}
+24 -19
View File
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type PlaylistKind, type PlaylistNode, type TrackOrigin } from '../api'
import type { AddTarget } from './AddFilesDialog'
import { api, type PlaylistKind, type PlaylistNode } from '../api'
import type { AddTarget, ForeignOrigin } from './AddFilesDialog'
import { useCaps } from '../lib/capabilities'
import { SaveBar } from './SaveBar'
import { confirmDiscardUnsaved } from '../lib/unsaved'
@@ -14,7 +14,7 @@ import { ContextMenu, type MenuItem } from './ContextMenu'
import { Icon, type IconName } from '../lib/icons'
import { PlatformIcon } from '../lib/platformIcons'
import { addTracksToPlaylist } from '../lib/addTracks'
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload } from '../lib/drag'
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload, type TracksOrFiles } from '../lib/drag'
import { findNode, idsAfter, nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
/**
@@ -55,9 +55,10 @@ interface Props {
/** Open a drive's library as THE library (Devices' "Open for editing…"). */
onOpenLibrary: (path: string) => void
onDone: (msg: string) => void
/** Tracks not in the collection yet (a device's, a folder's) dropped on a
* playlist or export: open the dialog that adds them, target filled in. */
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
/** Tracks not in the collection yet (a device's, a folder's — or files
* dropped from the OS, as paths) dropped on a playlist or export: open the
* dialog that adds them, target filled in. */
onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void
onOpenPathMapping: () => void
/** After unsaved edits were discarded (SaveBar). */
onDiscarded?: () => void
@@ -111,11 +112,11 @@ interface RowActions {
onPickExport: (e: React.MouseEvent<HTMLElement>, node: PlaylistNode) => void
onCommitDraft: (name: string) => void
onCancelDraft: () => void
/** Whether a drag of tracks may drop on this playlist. */
acceptsTracks: (node: PlaylistNode, p: Extract<DragPayload, { kind: 'tracks' }>) => boolean
/** Tracks dropped on a playlist; `alt` (Option) moves them out of the
/** Whether a drag of tracks (or of files from the OS) may drop on this playlist. */
acceptsTracks: (node: PlaylistNode, p: TracksOrFiles) => boolean
/** Tracks dropped on a playlist; `mod` (Cmd/Ctrl) moves them out of the
* playlist they came from. */
onDropTracks: (node: PlaylistNode, p: Extract<DragPayload, { kind: 'tracks' }>, alt: boolean) => void
onDropTracks: (node: PlaylistNode, p: TracksOrFiles, mod: boolean) => void
/** Whether a node may be dragged elsewhere in the tree. */
canMove: (node: PlaylistNode) => boolean
/** A node dropped in the tree: `index` among `parentId`'s children,
@@ -226,8 +227,8 @@ function NodeRow({
// drop TARGET for tracks. Whether it takes them is the node's own
// `can_add_tracks` plus the library being writable, decided by the sidebar.
const startDrag = usePressToDrag(() => (renaming ? null : { kind: 'node', node, parentId }))
const moves = (p: DragPayload, alt: boolean) =>
p.kind === 'tracks' && alt && !!p.fromPlaylist && p.fromPlaylist !== node.id
const moves = (p: DragPayload, mod: boolean) =>
p.kind === 'tracks' && mod && !!p.fromPlaylist && p.fromPlaylist !== node.id
// A node held over this row: which zone, and where that puts it. Never into
// itself or anything nested in it; a drop that would leave it exactly where
@@ -265,15 +266,15 @@ function NodeRow({
label: (p, h, at) => {
if (h.zone === 'tracks') {
if (p.kind === 'tracks' && p.origin === 'device') return `Import into ${node.name}…`
if (p.kind === 'tracks' && p.origin === 'folder') return `Add to ${node.name}…`
return `${moves(p, at.alt) ? 'Move' : 'Add'} to ${node.name}`
if ((p.kind === 'tracks' && p.origin === 'folder') || p.kind === 'files') return `Add to ${node.name}…`
return `${moves(p, at.mod) ? 'Move' : 'Add'} to ${node.name}`
}
if (h.zone === 'peek') return null
return h.zone === 'into' || h.zone === 'first' ? `Move into ${node.name}` : `Move ${h.zone} ${node.name}`
},
onDrop: (p, h, at) => {
if (p.kind === 'tracks') {
if (h.zone === 'tracks') actions.onDropTracks(node, p, at.alt)
if (p.kind !== 'node') {
if (h.zone === 'tracks') actions.onDropTracks(node, p, at.mod)
} else if ('parentId' in h) {
actions.onMoveNode(p.node, h.parentId, h.index, h.zone === 'into' && !expanded ? node : null)
}
@@ -664,7 +665,7 @@ export function Sidebar({
acceptsTracks: (node, p) =>
caps.writable &&
node.can_add_tracks &&
(p.origin === 'collection' ? p.fromPlaylist !== node.id : caps.tracks.addable),
(p.kind === 'tracks' && p.origin === 'collection' ? p.fromPlaylist !== node.id : caps.tracks.addable),
canMove: (node) => caps.writable && node.can_move,
onMoveNode: async (node, parentId, index, into) => {
try {
@@ -677,7 +678,11 @@ export function Sidebar({
onError((e as Error).message)
}
},
onDropTracks: async (node, p, alt) => {
onDropTracks: async (node, p, mod) => {
if (p.kind === 'files') {
onAddForeign('dropped', p.paths, { kind: 'playlist', id: node.id, name: node.name })
return
}
if (p.origin !== 'collection') {
onAddForeign(p.origin, p.ids, { kind: 'playlist', id: node.id, name: node.name })
return
@@ -688,7 +693,7 @@ export function Sidebar({
playlist: node,
ids: p.ids,
duplicatesAllowed: caps.playlists.duplicates,
moveFrom: alt ? p.fromPlaylist : undefined,
moveFrom: mod ? p.fromPlaylist : undefined,
})
if (msg) onDone(msg)
} catch (e) {
+183
View File
@@ -0,0 +1,183 @@
import { createPortal } from 'react-dom'
import { useEffect, useState, type ReactNode } from 'react'
import type { Track } from '../api'
import { formatBpm, formatDuration, keyColor } from '../lib/format'
import { useCaps } from '../lib/capabilities'
import { Icon } from '../lib/icons'
import { RatingStars } from './RatingStars'
interface Props {
track: Track
/** The cover's URL, or null where this track's library serves none (a
* device or a loose file) — the ambient swatch stands in, as in the deck. */
artUrl: string | null
onClose: () => void
/** Offered only where the library will accept the edit; closes this first. */
onEditTags?: () => void
}
/**
* The deck cover's popup: the art large, beside everything the library knows
* about the track. View-only apart from the one way out to Edit Tags. Rows with
* no value are left out rather than shown as dashes, so a sparse track reads
* as short rather than broken.
*/
export function TrackInfoDialog({ track, artUrl, onClose, onEditTags }: Props) {
const caps = useCaps()
const [artFailed, setArtFailed] = useState(false)
const showArt = artUrl != null && !artFailed
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const grid =
track.grid_marker_count === 0
? null
: `${track.grid_marker_count > 1 ? `Flexible · ${track.grid_marker_count} markers` : 'Constant tempo'}${
track.grid_locked ? ' · locked' : ''
}`
const details: [string, ReactNode][] = (
[
['Album', track.album],
['Label', track.label],
['Genre', track.genre],
['Remixer', track.remixer],
['Producer', track.producer],
['Mix', track.mix],
['Released', track.release_date],
['Added', track.import_date],
['Last played', track.last_played],
['Plays', track.playcount ? String(track.playcount) : null],
// The generic bitrate is bits per second.
['Bitrate', track.bitrate ? `${Math.round(track.bitrate / 1000)} kbps` : null],
['Grid', grid],
['Hotcues', track.hotcue_count ? String(track.hotcue_count) : null],
['Comment', track.comment],
['Comment 2', track.comment2],
] as [string, ReactNode][]
).filter(([, v]) => v != null && v !== '')
return createPortal(
<div
aria-modal="true"
role="dialog"
aria-label={track.title ?? 'Track info'}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 backdrop-blur-[3px]"
onClick={onClose}
>
<div
className="track-info-pop glass-overlay flex max-h-[90vh] w-full max-w-[860px] flex-col overflow-hidden sm:flex-row"
onClick={(e) => e.stopPropagation()}
>
{/* The sleeve, bled into the card behind everything: a soft wash of the
art's own colours. `filter` on this leaf is safe — nothing can open
inside it. */}
{showArt && (
<img
aria-hidden
src={artUrl}
alt=""
// Between the tint (::after, z -1, earlier) and the rim (::before).
style={{ zIndex: -1 }}
className="pointer-events-none absolute inset-0 h-full w-full scale-125 object-cover opacity-30 blur-3xl saturate-150"
/>
)}
<div className="relative flex shrink-0 flex-col items-center gap-4 p-6 sm:pr-3">
<div
className="relative aspect-square w-[min(340px,70vw)] overflow-hidden rounded-2xl shadow-[inset_0_1px_0_rgb(255_255_255/0.35),0_24px_60px_-12px_var(--amb-2)]"
style={{ background: 'linear-gradient(135deg, var(--amb-1), var(--amb-2) 55%, var(--amb-3))' }}
>
{showArt ? (
<img
src={artUrl}
alt={`Cover of ${track.title ?? 'this track'}`}
className="absolute inset-0 h-full w-full object-cover"
onError={() => setArtFailed(true)}
/>
) : (
<div className="absolute inset-0 flex items-center justify-center text-white/40">
<Icon name="music" size={72} strokeWidth={1.2} />
</div>
)}
</div>
{track.rating > 0 && <RatingStars value={track.rating} max={caps.tracks.rating_max} />}
</div>
<div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
<div className="min-h-0 flex-1 overflow-y-auto p-6 sm:pl-3">
<div className="flex items-start gap-3">
<div className="min-w-0 flex-1">
<h2 className="text-2xl font-semibold leading-tight tracking-tight text-text select-text">
{track.title ?? 'Untitled'}
</h2>
<div className="mt-1 text-[15px] text-muted select-text">{track.artist ?? 'Unknown artist'}</div>
</div>
<button
onClick={onClose}
aria-label="Close"
className="btn-glass -mr-2 -mt-2 flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted hover:text-text"
>
<Icon name="close" size={14} />
</button>
</div>
<div className="mt-5 flex flex-wrap gap-2">
<Stat label="KEY" value={track.key || '—'} color={keyColor(track.key_wheel)} />
<Stat label="BPM" value={formatBpm(track.bpm)} />
<Stat label="LENGTH" value={formatDuration(track.length)} />
{track.media_kind !== 'audio' && <Stat label="TYPE" value={track.media_kind.toUpperCase()} />}
</div>
{details.length > 0 && (
<dl className="mt-5 grid grid-cols-[auto_1fr] gap-x-5 gap-y-1.5 border-t border-line pt-4 text-[13px]">
{details.map(([label, value]) => (
<div key={label} className="contents">
<dt className="text-faint">{label}</dt>
<dd className="min-w-0 whitespace-pre-wrap break-words text-text select-text">{value}</dd>
</div>
))}
</dl>
)}
{track.filepath && (
<div
className="well mt-5 rounded-xl px-3 py-2 font-mono text-[11px] leading-relaxed text-muted break-all select-text"
title={track.filepath}
>
{track.filepath}
</div>
)}
</div>
{onEditTags && (
<div className="flex justify-end px-6 pb-6 sm:pl-3">
<button
onClick={onEditTags}
className="btn-glass flex h-9 items-center gap-2 rounded-full px-4 text-[13px] font-medium"
>
<Icon name="pencil" size={15} />
Edit Tags…
</button>
</div>
)}
</div>
</div>
</div>,
document.body,
)
}
function Stat({ label, value, color }: { label: string; value: string; color?: string }) {
return (
<div className="well flex flex-col gap-px rounded-xl px-4 py-2">
<span className="text-[10px] tracking-[0.08em] text-faint">{label}</span>
<span className="font-mono text-[17px] font-semibold" style={{ color }}>
{value}
</span>
</div>
)
}
+9 -5
View File
@@ -31,6 +31,7 @@ import {
import { CSS } from '@dnd-kit/utilities'
import type { Track, TrackOrigin } from '../api'
import { beginDrag, useDragPayload, useDropTarget } from '../lib/drag'
import { hasMod } from '../lib/modKey'
import { TRACK_COLUMNS } from '../lib/trackColumns'
/** Fields this platform can persist, for the table's per-cell edit gating.
@@ -73,11 +74,12 @@ interface Props {
* active: reordering a partial or re-sorted list would lose the real order. */
reorder?: { enabled: boolean; onReorder: (ids: string[]) => void }
/** Where dragged rows come from: whose ids they are, and the editable
* playlist they leave on an Option-drag (move). Defaults to the collection. */
* playlist they leave on a Cmd/Ctrl-drag (move). Defaults to the collection. */
dragFrom?: { origin: TrackOrigin; playlistId?: string }
/** Delete/Backspace removes the selected tracks from this view. */
onRemove?: (ids: string[]) => void
onRowContextMenu?: (track: Track, x: number, y: number) => void
/** `viewIds` is every row's id in the order shown (sorted, filtered). */
onRowContextMenu?: (track: Track, x: number, y: number, viewIds: string[]) => void
/** Right-click on the header row (the column chooser). */
onHeaderContextMenu?: (x: number, y: number) => void
onPlay?: (track: Track) => void
@@ -431,7 +433,7 @@ export function TrackTable({
fromPlaylist: from?.playlistId,
source: tableKey,
},
{ x: e.clientX, y: e.clientY, alt: e.altKey },
{ x: e.clientX, y: e.clientY, mod: hasMod(e) },
)
}
const release = () => (pressRef.current = null)
@@ -579,7 +581,9 @@ export function TrackTable({
if (selection && (e.shiftKey || e.metaKey || e.ctrlKey)) e.preventDefault()
}}
onPointerDown={(e) => {
if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return
// Cmd/Ctrl arms a drag too (it MOVES the tracks); without
// movement it stays a Cmd/Ctrl-click, which toggles the row.
if (e.button !== 0 || e.shiftKey || (!hasMod(e) && (e.metaKey || e.ctrlKey))) return
// Not from a control inside the row (play, stars, an edit field).
if ((e.target as HTMLElement).closest('button, input, textarea, select, a')) return
pressRef.current = { x: e.clientX, y: e.clientY, index: vr.index }
@@ -591,7 +595,7 @@ export function TrackTable({
// Right-clicking outside the selection retargets it, so the
// menu always acts on what is highlighted.
if (selection && !isSelected) selectOnly(vr.index)
onRowContextMenu(row.original, e.clientX, e.clientY)
onRowContextMenu(row.original, e.clientX, e.clientY, rows.map((r) => r.original.id))
}}
>
<span className="w-10 shrink-0 pr-2 text-right text-xs tabular-nums text-faint">
+12
View File
@@ -291,6 +291,18 @@ option {
}
}
/* ---- Track info popup (see TrackInfoDialog.tsx) ---------------------- */
.track-info-pop {
animation: track-info-pop 220ms cubic-bezier(0.2, 0.9, 0.3, 1.15);
}
@keyframes track-info-pop {
from { opacity: 0; transform: translateY(8px) scale(0.96); }
to { opacity: 1; transform: none; }
}
@media (prefers-reduced-motion: reduce) {
.track-info-pop { animation: none; }
}
/* ---- Ambient backdrop (see AmbientBackdrop.tsx) ------------------------ */
.ambient-wash {
position: absolute;
+1 -1
View File
@@ -13,7 +13,7 @@ const plural = (n: number) => `${n} track${n === 1 ? '' : 's'}`
* elsewhere they are skipped and the message says so. Nothing is asked when
* there are none.
*
* `moveFrom` is an Option-drag out of another (editable) playlist: once the
* `moveFrom` is a Cmd/Ctrl-drag out of another (editable) playlist: once the
* tracks are in the target they leave the source. Cancelling the duplicates
* question cancels the move too.
*
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it } from 'vitest'
import { alignShift, mp3HeaderFrame } from './decodeAlign'
import { PROBE_MP3_BASE64 } from './decodeProbe'
/** A stereo MPEG-1 Layer III frame header (128 kbps, 44.1 kHz) followed by
* `tag` where a Xing/Info tag would sit, padded to 64 bytes. */
function frame(tag = '') {
const b = new Uint8Array(64)
b.set([0xff, 0xfb, 0x90, 0x00])
for (let i = 0; i < tag.length; i++) b[4 + 32 + i] = tag.charCodeAt(i)
return b
}
function withId3(body: Uint8Array, size = 1000) {
const out = new Uint8Array(10 + size + body.length)
out.set([0x49, 0x44, 0x33, 4, 0, 0])
out.set([(size >> 21) & 127, (size >> 14) & 127, (size >> 7) & 127, size & 127], 6)
out.set(body, 10 + size)
return out
}
describe('mp3HeaderFrame', () => {
it('sees a Xing / Info header, after an ID3 tag too', () => {
expect(mp3HeaderFrame(frame('Xing'))).toBe(true)
expect(mp3HeaderFrame(withId3(frame('Info'), 200_000))).toBe(true)
})
it('sees an MP3 without one', () => {
expect(mp3HeaderFrame(frame())).toBe(false)
expect(mp3HeaderFrame(withId3(frame()))).toBe(false)
})
it('reads the built-in probe as header-less', () => {
const bytes = Uint8Array.from(atob(PROBE_MP3_BASE64), (c) => c.charCodeAt(0))
expect(mp3HeaderFrame(bytes)).toBe(false)
})
it('is not fooled by a frame sync inside another format', () => {
const m4a = new Uint8Array(96)
m4a.set([0, 0, 0, 0x20, 0x66, 0x74, 0x79, 0x70]) // ....ftyp
m4a.set(frame(), 16)
expect(mp3HeaderFrame(m4a)).toBeNull()
const flac = withId3(new Uint8Array([0x66, 0x4c, 0x61, 0x43, ...frame()])) // ID3 + fLaC
expect(mp3HeaderFrame(flac)).toBeNull()
})
})
describe('alignShift', () => {
it("prepends what this engine trimmed, only on a header-less MP3", () => {
// WebKit measured 529 samples early at 44.1 kHz.
const early = -529 / 44100
expect(alignShift(false, early, 44100)).toBe(529)
expect(alignShift(false, early, 48000)).toBe(Math.round(529 * 48000 / 44100))
expect(alignShift(true, early, 44100)).toBe(0)
expect(alignShift(null, early, 44100)).toBe(0)
expect(alignShift(false, 0, 44100)).toBe(0)
})
})
+128
View File
@@ -0,0 +1,128 @@
// The deck decodes audio in the BROWSER (decodeAudioData), while every stored
// position — grids, cues — is in the backend's decoded time base (PyAV/FFmpeg,
// `core/waveform.load`). Measured 2026-10-15 with click files: the two agree to
// the sample on every format EXCEPT a header-less MP3 under WebKit (the macOS
// app's WKWebView), which decodes 529 samples (12 ms) EARLY — CoreAudio trims
// the MP3 decoder delay even when no Xing/Info header says to, FFmpeg trims
// nothing. Chromium (WebView2) matches FFmpeg. Invisible under 7 ms bars, but
// the raw waveform would draw every beat line 12 ms off its kick.
//
// Rather than hard-code WebKit's number, this engine's offset is MEASURED once,
// by decoding a tiny built-in header-less MP3 (`decodeProbe.ts`) whose click
// FFmpeg places at a known sample, and a header-less MP3's decoded buffer is
// shifted by it — so playback, scratch and both waveforms share the grid's
// clock. An MP3 WITH a header was measured to agree on both engines and is
// never touched.
import { PROBE_MP3_BASE64, PROBE_ONSET, PROBE_RATE } from './decodeProbe'
/** How far past the ID3 tag to look for the first frame (junk, padding). */
const SCAN = 64 * 1024
interface Frame {
mpeg1: boolean
mono: boolean
}
/** A Layer III frame header at `i`, or null. The backend's
* `core/mp3_gapless._frame_header`, kept in step with it. */
function frameHeader(b: Uint8Array, i: number): Frame | null {
if (i + 4 > b.length || b[i] !== 0xff || (b[i + 1] & 0xe0) !== 0xe0) return null
const version = (b[i + 1] >> 3) & 3
const layer = (b[i + 1] >> 1) & 3
const bitrate = b[i + 2] >> 4
const rate = (b[i + 2] >> 2) & 3
if (version === 1 || layer !== 1 || bitrate === 0 || bitrate === 15 || rate === 3) return null
return { mpeg1: version === 3, mono: b[i + 3] >> 6 === 3 }
}
const ascii = (b: Uint8Array, i: number, n: number) => String.fromCharCode(...b.subarray(i, i + n))
/**
* Whether `bytes` is an MP3 whose first frame is a Xing / Info / VBRI header
* (true), an MP3 without one (false), or not an MP3 at all (null). The header
* test is the backend's `core/mp3_gapless.parse`; the "is it an MP3" gate is
* extra, because this sees every format the deck plays and a stray frame sync
* inside an M4A or FLAC must not count. An MP3 starts with an ID3v2 tag or with
* a frame — nothing else this app plays does (FLAC, RIFF, ftyp, FORM, OggS).
*/
export function mp3HeaderFrame(b: Uint8Array): boolean | null {
let start = 0
if (b.length >= 10 && b[0] === 0x49 && b[1] === 0x44 && b[2] === 0x33) {
const size = ((b[6] & 127) << 21) | ((b[7] & 127) << 14) | ((b[8] & 127) << 7) | (b[9] & 127)
start = 10 + size + (b[5] & 0x10 ? 10 : 0)
if (ascii(b, start, 4) === 'fLaC') return null // a FLAC carrying a (non-standard) ID3 tag
} else if (!frameHeader(b, 0)) {
return null
}
const end = Math.min(b.length - 4, start + SCAN)
for (let i = start; i < end; i++) {
const h = frameHeader(b, i)
if (!h) continue
const side = h.mpeg1 ? (h.mono ? 17 : 32) : h.mono ? 9 : 17
const tag = ascii(b, i + 4 + side, 4)
if (tag === 'Xing' || tag === 'Info') return true
return ascii(b, i + 36, 4) === 'VBRI'
}
return null
}
/** The first sample of the probe's click (a quarter of its peak), or -1. */
function clickOnset(buf: AudioBuffer): number {
const d = new Float32Array(buf.length)
buf.copyFromChannel(d, 0)
let peak = 0
for (let i = 0; i < d.length; i++) peak = Math.max(peak, Math.abs(d[i]))
if (peak <= 0) return -1
for (let i = 0; i < d.length; i++) if (Math.abs(d[i]) > peak * 0.25) return i
return -1
}
async function measure(): Promise<number> {
const bytes = Uint8Array.from(atob(PROBE_MP3_BASE64), (c) => c.charCodeAt(0))
const buf = await new OfflineAudioContext(1, 1, PROBE_RATE).decodeAudioData(bytes.buffer)
const onset = clickOnset(buf)
// An onset nowhere near the click means the probe did not decode sensibly;
// shifting by it would be worse than the 12 ms it exists to fix.
if (onset < 0 || Math.abs(onset - PROBE_ONSET) > 4096) return 0
return (onset - PROBE_ONSET) / PROBE_RATE
}
let offset: Promise<number> | null = null
/** Seconds by which this engine decodes a header-less MP3 AHEAD of FFmpeg
* (negative = its audio starts earlier). Measured once per session; 0 if the
* probe cannot be decoded. */
export function headerlessMp3Offset(): Promise<number> {
return (offset ??= measure().catch(() => 0))
}
/**
* Samples to PREPEND (negative: drop from the start) to a buffer this engine
* decoded, to put it in the backend's time base. `header` is
* `mp3HeaderFrame` of the file's bytes, read before decoding detaches them.
*/
export function alignShift(header: boolean | null, offsetSec: number, sampleRate: number): number {
return header === false ? Math.round(-offsetSec * sampleRate) || 0 : 0
}
/** `buffer`, decoded by this engine from a file whose `mp3HeaderFrame` is
* `header`, moved into the backend's time base (the same buffer if no move). */
export async function alignDecoded(buffer: AudioBuffer, header: boolean | null): Promise<AudioBuffer> {
if (header !== false) return buffer
const shift = alignShift(header, await headerlessMp3Offset(), buffer.sampleRate)
if (shift === 0) return buffer
const out = new AudioBuffer({
length: Math.max(1, buffer.length + shift),
numberOfChannels: buffer.numberOfChannels,
sampleRate: buffer.sampleRate,
})
// copyFromChannel, never getChannelData: see the detach gotcha in scratchEngine.
const tmp = new Float32Array(buffer.length)
for (let c = 0; c < buffer.numberOfChannels; c++) {
buffer.copyFromChannel(tmp, c)
if (shift > 0) out.copyToChannel(tmp, c, shift)
else out.copyToChannel(tmp.subarray(-shift), c, 0)
}
return out
}
+48
View File
@@ -0,0 +1,48 @@
// A 0.3 s mono 44.1 kHz MP3, 64 kbps, encoded by LAME (via FFmpeg) WITHOUT a
// Xing/Info header: silence with a 64-sample click at 0.1 s. FFmpeg decodes the
// click at sample PROBE_ONSET — 4410 + 1105 samples of start padding it does not
// trim, having no header to say how much. See decodeAlign.ts for its use.
export const PROBE_RATE = 44100
export const PROBE_ONSET = 5515
export const PROBE_MP3_BASE64 =
'SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYyLjEyLjEwMgAAAAAAAAAAAAAA//tQxAADwAABpAAAACAAADSAAAAETEFNRTMu' +
'MTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7UsRdg8AAAaQAAAAgAAA0gAAABFVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVKKKKKKKKKKKK/wgdhBp1G6J/rUrOW2H/vW0ArmeSx1nA' +
'Bvz47A8DIdw8/5YO8PZPH0bThO/80JBY9Meh+aUjp//Pzew4xQdy9kn//pM3PsNDizVDyVt///emf4ZFaJ2FDa5NVv///e+2' +
'MY972MpJd0tRpyR7////9nNzexlPfbGTJrUG12ih//tSxKGDwAABpAAAACAAADSAAAAElGgywARRdQUoCyGCWFuOpvQ2OnTR' +
'OlxYmJXK7DgEFJORBQDTkSM5RIlIiBoeCodWCrlgrLA0oGoKhsShosDTgaeJQ3yzvEUqCqw1ER4seWCvUHP/qBrlTvBpTEFN' +
'RTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+1LEoYPAAAGkAAAAIAAANIKAAARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVf/7UsT/gBEVjXM5lYAZYIlno55gAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVV//tSxKGDwAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVX/+1LEoYPAAAGkAAAAIAAANIAAAARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7UsSh' +
'g8AAAaQAAAAgAAA0gAAABFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVTEFN' +
'RTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//tSxKGDwAABpAAA' +
'ACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+1LEoYPAAAGkAAAAIAAANIAA' +
'AARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7UsShg8AAAaQAAAAgAAA0gAAABFVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//tSxKGDwAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+1LEoYPAAAGkAAAAIAAANIAAAARVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVQ=='
+94 -44
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'
import { createPortal } from 'react-dom'
import type { PlaylistNode, Track, TrackOrigin } from '../api'
import { Icon } from './icons'
import { hasMod, MOD_KEY } from './modKey'
/**
* Drag and drop across the whole window: track rows onto sidebar playlists,
@@ -18,6 +19,11 @@ import { Icon } from './icons'
* events for its own file drop on Windows, so HTML5 DnD silently dies in the
* packaged app.
*
* Files dragged in from Finder / Explorer ride the same store as a `files`
* payload: Tauri reports that drag (with real paths) instead of the webview,
* and `lib/fileDrop.ts` feeds it in through `nativeDragStart` / `Move` / `End`,
* so the same targets light up and the same ghost names what a drop would do.
*
* The state lives in a module-level store read through useSyncExternalStore
* with narrow selectors, so a pointer move re-renders only the target under it
* (and the ghost) — never the table.
@@ -33,18 +39,24 @@ export type DragPayload =
/** Which library the ids belong to — a device's or a folder's are not
* the collection's, so collection targets must not take them as such. */
origin: TrackOrigin
/** The editable playlist they were dragged out of, for Option = move. */
/** The editable playlist they were dragged out of, for Cmd/Ctrl = move. */
fromPlaylist?: string
/** Identity of the table that started the drag (its own reorder target). */
source: object
}
| { kind: 'node'; node: PlaylistNode; parentId: string | null }
/** Files and folders from the OS, as absolute paths. Not yet tracks: a
* target hands them to the drop resolver, which reads what is in them. */
| { kind: 'files'; paths: string[] }
/** What a playlist or export row takes: track rows, or files from the OS. */
export type TracksOrFiles = Exclude<DragPayload, { kind: 'node' }>
export interface DropPoint {
x: number
y: number
/** Option/Alt held: tracks dragged out of a playlist MOVE instead of copy. */
alt: boolean
/** Cmd (macOS) / Ctrl held: tracks dragged out of a playlist MOVE instead of copy. */
mod: boolean
}
export interface DropSpec<H> {
@@ -62,13 +74,13 @@ interface State {
payload: DragPayload | null
x: number
y: number
alt: boolean
mod: boolean
target: HTMLElement | null
hint: unknown
label: string | null
}
const IDLE: State = { payload: null, x: 0, y: 0, alt: false, target: null, hint: null, label: null }
const IDLE: State = { payload: null, x: 0, y: 0, mod: false, target: null, hint: null, label: null }
let state: State = IDLE
const listeners = new Set<() => void>()
const targets = new Map<HTMLElement, { current: DropSpec<unknown> }>()
@@ -96,9 +108,9 @@ function sameHint(a: unknown, b: unknown): boolean {
/** Find the innermost target under the pointer that accepts, and record its hint. */
function evaluate() {
const { payload, x, y, alt } = state
const { payload, x, y, mod } = state
if (!payload) return
const at = { x, y, alt }
const at = { x, y, mod }
let el = document.elementFromPoint(x, y) as HTMLElement | null
while (el) {
const spec = targets.get(el)
@@ -117,44 +129,26 @@ function evaluate() {
let detach: (() => void) | null = null
/** Start a drag. Call it once the press has moved past the source's threshold. */
export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: boolean }) {
/** End the drag in progress, dropping on the target under the pointer if `drop`. */
function finish(drop: boolean) {
const { payload: p, target, hint, x, y, mod } = state
detach?.()
if (!drop || !p || !target) return
const spec = targets.get(target)
try {
spec?.current.onDrop(p, hint, { x, y, mod })
} catch (err) {
console.error('drop failed', err)
}
}
/** Publish a new drag and start edge auto-scroll. Returns what undoes both. */
function open(payload: DragPayload, at: { x: number; y: number; mod: boolean }): () => void {
detach?.()
set({ ...IDLE, payload, ...at })
document.documentElement.classList.add('is-dragging')
window.getSelection()?.removeAllRanges()
const onMove = (e: PointerEvent) => {
// One notification per move: evaluate() publishes the position with the hint.
state = { ...state, x: e.clientX, y: e.clientY, alt: e.altKey }
evaluate()
}
const finish = (drop: boolean) => {
const { payload: p, target, hint, x, y, alt } = state
detach?.()
if (!drop || !p || !target) return
const spec = targets.get(target)
try {
spec?.current.onDrop(p, hint, { x, y, alt })
} catch (err) {
console.error('drop failed', err)
}
}
const onUp = () => finish(true)
const onCancel = () => finish(false)
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape' && e.type === 'keydown') {
// Before every other Esc handler: cancelling the drag is all Esc does.
e.preventDefault()
e.stopImmediatePropagation()
finish(false)
return
}
if (e.key === 'Alt' && state.alt !== (e.type === 'keydown')) {
set({ alt: e.type === 'keydown' })
evaluate()
}
}
// Hold near the edge of a `data-drag-scroll` element to scroll it. Its
// value is the height covered at the top (a sticky header). The edge is
// thinner than a row and must be HELD for a moment first: otherwise the
@@ -187,6 +181,37 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt:
}
raf = requestAnimationFrame(autoScroll)
return () => {
cancelAnimationFrame(raf)
document.documentElement.classList.remove('is-dragging')
set(IDLE)
}
}
/** Start a drag. Call it once the press has moved past the source's threshold. */
export function beginDrag(payload: DragPayload, at: { x: number; y: number; mod: boolean }) {
const close = open(payload, at)
const onMove = (e: PointerEvent) => {
// One notification per move: evaluate() publishes the position with the hint.
state = { ...state, x: e.clientX, y: e.clientY, mod: hasMod(e) }
evaluate()
}
const onUp = () => finish(true)
const onCancel = () => finish(false)
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape' && e.type === 'keydown') {
// Before every other Esc handler: cancelling the drag is all Esc does.
e.preventDefault()
e.stopImmediatePropagation()
finish(false)
return
}
if (e.key === MOD_KEY && state.mod !== (e.type === 'keydown')) {
set({ mod: e.type === 'keydown' })
evaluate()
}
}
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', onUp)
window.addEventListener('pointercancel', onCancel)
@@ -195,14 +220,12 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt:
window.addEventListener('blur', onCancel)
detach = () => {
detach = null
cancelAnimationFrame(raf)
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', onUp)
window.removeEventListener('pointercancel', onCancel)
window.removeEventListener('keydown', onKey, true)
window.removeEventListener('keyup', onKey, true)
window.removeEventListener('blur', onCancel)
document.documentElement.classList.remove('is-dragging')
// The pointerup that ended the drag is followed by a click on whatever
// is under it; that click is part of the drop, not a click of its own.
const swallow = (e: MouseEvent) => {
@@ -211,11 +234,34 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt:
}
window.addEventListener('click', swallow, true)
setTimeout(() => window.removeEventListener('click', swallow, true), 0)
set(IDLE)
close()
}
evaluate()
}
/** A drag the OS owns (files from Finder / Explorer): it enters the window… */
export function nativeDragStart(payload: DragPayload, at: { x: number; y: number }) {
const close = open(payload, { ...at, mod: false })
detach = () => {
detach = null
close()
}
evaluate()
}
/** …moves over it (window coordinates, CSS pixels)… */
export function nativeDragMove(at: { x: number; y: number }) {
if (!state.payload) return
state = { ...state, ...at }
evaluate()
}
/** …and is dropped (or leaves the window: `drop` false). */
export function nativeDragEnd(drop: boolean, at?: { x: number; y: number }) {
if (drop && at) nativeDragMove(at)
finish(drop)
}
/** A pointerdown handler that starts a drag once the press moves 6 px. A plain
* click never moves that far, so the element keeps its click; a press on a
* field inside it (a rename input) never drags. `make` is asked at the moment
@@ -231,7 +277,7 @@ export function usePressToDrag(make: () => DragPayload | null): (e: React.Pointe
if (Math.hypot(m.clientX - start.x, m.clientY - start.y) < 6) return
stop()
const payload = makeRef.current()
if (payload) beginDrag(payload, { x: m.clientX, y: m.clientY, alt: m.altKey })
if (payload) beginDrag(payload, { x: m.clientX, y: m.clientY, mod: hasMod(m) })
}
const stop = () => {
window.removeEventListener('pointermove', onMove)
@@ -273,6 +319,10 @@ export function useDropTarget<H>(spec: DropSpec<H>): [(el: HTMLElement | null) =
function describe(p: DragPayload): { icon: 'music' | 'playlist' | 'folder' | 'smart'; text: string } {
if (p.kind === 'node')
return { icon: p.node.kind === 'folder' ? 'folder' : p.node.kind === 'smart' ? 'smart' : 'playlist', text: p.node.name }
if (p.kind === 'files')
return p.paths.length === 1
? { icon: 'music', text: p.paths[0].split(/[\\/]/).filter(Boolean).pop() ?? p.paths[0] }
: { icon: 'music', text: `${p.paths.length} items` }
if (p.ids.length === 1) {
const t = p.tracks[0]
return { icon: 'music', text: t ? [t.artist, t.title].filter(Boolean).join(' – ') || 'Untitled' : '1 track' }
+84
View File
@@ -0,0 +1,84 @@
import { useEffect, useRef } from 'react'
import { nativeDragEnd, nativeDragMove, nativeDragStart } from './drag'
/**
* Files dragged in from Finder / Explorer, fed into the window's ONE drag
* store (`lib/drag.tsx`) as a `files` payload, so the targets that take track
* rows — playlists, exports, the deck — take files too, and anywhere else is
* "add to the collection" (App's own target).
*
* Tauri only: the shell's webview hands the OS drag to Tauri, which reports it
* with real paths — what adding a file IN PLACE needs. A plain browser gives a
* page `File` objects without paths, so in a browser a file drop is only
* CAUGHT — left alone, the browser navigates to the dropped file and the app
* is gone — and `onBrowserDrop` says why nothing happened.
*
* `enabled` false (no library open yet) and an open dialog both refuse the
* drag at its start, before anything is highlighted.
*/
export function useNativeFileDrop(enabled: boolean, onBrowserDrop: () => void) {
const enabledRef = useRef(enabled)
enabledRef.current = enabled
const onBrowserDropRef = useRef(onBrowserDrop)
onBrowserDropRef.current = onBrowserDrop
useEffect(() => {
if (!('__TAURI_INTERNALS__' in window)) {
// Only drags carrying files: the app's own drags are pointer events,
// and a text drag into a field must keep working.
const hasFiles = (e: DragEvent) => !!e.dataTransfer?.types.includes('Files')
const over = (e: DragEvent) => {
if (hasFiles(e)) e.preventDefault()
}
const drop = (e: DragEvent) => {
if (!hasFiles(e)) return
e.preventDefault()
onBrowserDropRef.current()
}
window.addEventListener('dragover', over)
window.addEventListener('drop', drop)
return () => {
window.removeEventListener('dragover', over)
window.removeEventListener('drop', drop)
}
}
let unlisten: (() => void) | undefined
let cancelled = false
let active = false
void (async () => {
const { getCurrentWebview } = await import('@tauri-apps/api/webview')
const off = await getCurrentWebview().onDragDropEvent(({ payload }) => {
// Tauri reports PHYSICAL pixels; the page works in CSS pixels.
const scale = window.devicePixelRatio || 1
const at = 'position' in payload ? { x: payload.position.x / scale, y: payload.position.y / scale } : null
switch (payload.type) {
case 'enter':
active =
enabledRef.current &&
payload.paths.length > 0 &&
!document.querySelector('[aria-modal="true"]')
if (active && at) nativeDragStart({ kind: 'files', paths: payload.paths }, at)
break
case 'over':
if (active && at) nativeDragMove(at)
break
case 'drop':
if (active) nativeDragEnd(true, at ?? undefined)
active = false
break
case 'leave':
if (active) nativeDragEnd(false)
active = false
break
}
})
if (cancelled) off()
else unlisten = off
})()
return () => {
cancelled = true
unlisten?.()
if (active) nativeDragEnd(false)
}
}, [])
}
+7
View File
@@ -25,6 +25,7 @@ const PATHS = {
),
sparkle: <path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8zM19 16l.7 1.8 1.8.7-1.8.7L19 21l-.7-1.8-1.8-.7 1.8-.7z" strokeLinejoin="round" />,
wave: <path d="M3 12h2M7 8v8M11 5v14M15 9v6M19 11v2" />,
sine: <path d="M2 12c2.5-8 5-8 7.5 0s5 8 7.5 0 3.5-5 5-3" strokeLinejoin="round" />,
folder: <path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" strokeLinejoin="round" />,
folderOpen: <path d="M3 7a2 2 0 0 1 2-2h4l2 2h6a2 2 0 0 1 2 2v1M3 7v10a2 2 0 0 0 2 2h12.5a2 2 0 0 0 1.9-1.4L21 12a1 1 0 0 0-1-1.3H8.5a2 2 0 0 0-1.9 1.4L4 19" strokeLinejoin="round" />,
playlist: <path d="M8 6h13M8 12h13M8 18h13M3.5 6h.01M3.5 12h.01M3.5 18h.01" />,
@@ -98,6 +99,12 @@ const PATHS = {
fadeOut: <path d="M3 5l18 14H3z" strokeLinejoin="round" />,
eject: <path d="M12 4l8 9H4zM4 18h16" strokeLinejoin="round" />,
grid: <path d="M5 3v18M10 3v18M15 3v18M20 3v18" />,
mouse: (
<>
<rect x="6" y="3" width="12" height="18" rx="6" />
<path d="M12 7v3" />
</>
),
} as const
export type IconName = keyof typeof PATHS
+15
View File
@@ -0,0 +1,15 @@
// The platform's command modifier: Cmd on macOS, Ctrl elsewhere. For mouse
// gestures it is exactly that key — on macOS, Ctrl+click is a right-click, so
// accepting either (as the keyboard shortcuts do) would start a drag under a
// context menu.
export const IS_MAC = /Mac|iPhone|iPad/.test(navigator.userAgent)
/** Whether the command modifier is held. */
export const hasMod = (e: { metaKey: boolean; ctrlKey: boolean }) => (IS_MAC ? e.metaKey : e.ctrlKey)
/** Its `KeyboardEvent.key`, for following it being pressed mid-gesture. */
export const MOD_KEY = IS_MAC ? 'Meta' : 'Control'
/** Its name in a tooltip ("Cmd-click"). */
export const MOD_NAME = IS_MAC ? 'Cmd' : 'Ctrl'
+19
View File
@@ -27,6 +27,25 @@ describe('moveToPosition', () => {
})
})
describe('moveToPosition with a view order', () => {
const sorted = (ids: string[], position: number, view: string[]) =>
moveToPosition(order, new Set(ids), position, view).join('')
it('moves the block in the order the view shows it', () => {
expect(sorted(['B', 'E', 'F'], 1, ['F', 'B', 'E'])).toBe('FBEACDG')
expect(sorted(['B', 'E', 'F'], 3, ['E', 'F', 'B'])).toBe('ACEFBDG')
})
it('ignores view ids that are not moving', () => {
expect(sorted(['B', 'D'], 1, ['G', 'D', 'A', 'B'])).toBe('DBACEFG')
})
it('keeps a twice-listed track together, and appends a track the view lacks', () => {
expect(moveToPosition(['A', 'B', 'A', 'C'], new Set(['A', 'C']), 1, ['C', 'A']).join('')).toBe('CAAB')
expect(sorted(['B', 'C'], 1, ['C'])).toBe('CBADEFG')
})
})
describe('maxPosition', () => {
it('leaves room for the block behind its first track', () => {
expect(maxPosition(order, new Set(['B']))).toBe(7)
+29 -7
View File
@@ -1,10 +1,17 @@
/** A playlist's entry order with `moving` lifted out as one block, kept in
* their PLAYLIST order, and put back so the block's first track lands at the
* 1-based `position` of the result. A position past the end puts the block
* last. A track listed twice in the playlist moves with both entries, since a
* selection is by track id. */
export function moveToPosition(order: string[], moving: ReadonlySet<string>, position: number): string[] {
const block = order.filter((id) => moving.has(id))
/** A playlist's entry order with `moving` lifted out as one block and put
* back so the block's first track lands at the 1-based `position` of the
* result. A position past the end puts the block last. The block keeps the
* tracks' PLAYLIST order, or with `blockOrder` (the ids as a sorted view
* shows them) that order instead — so a sort can be written into the
* playlist. A track listed twice in the playlist moves with both entries,
* since a selection is by track id; in `blockOrder` they stay together. */
export function moveToPosition(
order: string[],
moving: ReadonlySet<string>,
position: number,
blockOrder?: readonly string[],
): string[] {
const block = blockOrder ? orderBlock(order, moving, blockOrder) : order.filter((id) => moving.has(id))
const rest = order.filter((id) => !moving.has(id))
const at = Math.min(Math.max(Math.floor(position), 1) - 1, rest.length)
return [...rest.slice(0, at), ...block, ...rest.slice(at)]
@@ -15,3 +22,18 @@ export function moveToPosition(order: string[], moving: ReadonlySet<string>, pos
export function maxPosition(order: string[], moving: ReadonlySet<string>): number {
return order.length - order.filter((id) => moving.has(id)).length + 1
}
/** The moving entries in `blockOrder`'s order, each track's repeats together.
* A moving track `blockOrder` lacks (none should) follows in playlist order. */
function orderBlock(order: string[], moving: ReadonlySet<string>, blockOrder: readonly string[]): string[] {
const counts = new Map<string, number>()
for (const id of order) if (moving.has(id)) counts.set(id, (counts.get(id) ?? 0) + 1)
const block: string[] = []
for (const id of [...blockOrder, ...order]) {
const n = counts.get(id)
if (!n) continue
for (let i = 0; i < n; i++) block.push(id)
counts.delete(id)
}
return block
}
+143
View File
@@ -0,0 +1,143 @@
import { describe, expect, it } from 'vitest'
import { laneScales, makeSpans, rawSpans, rawWaveFromMono, RAW_BLOCK, tintAt } from './rawWave'
import type { WaveColumn } from './waveform'
const SR = 44100
/** `sec` of silence with a one-sample click of `amp` at sample `at`. */
function click(sec: number, at: number, amp = 0.8) {
const mono = new Float32Array(Math.round(sec * SR))
mono[at] = amp
return rawWaveFromMono(mono, SR)
}
/** The bin whose centre time is nearest `sec`. */
const binAt = (s: ReturnType<typeof makeSpans>, sec: number) => {
let best = 0
for (let k = 0; k < s.n; k++) if (Math.abs(s.t[k] - sec) < Math.abs(s.t[best] - sec)) best = k
return best
}
describe('rawWaveFromMono', () => {
it('summarises min/max per block and finds the peak', () => {
const mono = new Float32Array(RAW_BLOCK * 3)
mono[5] = 0.5
mono[RAW_BLOCK + 7] = -0.9
const raw = rawWaveFromMono(mono, SR)
expect(raw.min.length).toBe(3)
expect(raw.max[0]).toBeCloseTo(0.5)
expect(raw.min[1]).toBeCloseTo(-0.9)
expect(raw.peak).toBeCloseTo(0.9)
})
})
describe('rawSpans', () => {
// A 0.25 s view across 1200 px: ~9 samples a pixel — the SAMPLE path.
// A 16 s view: ~588 a pixel — the BLOCK path.
for (const [label, view] of [['deep zoom', 0.25], ['wide zoom', 16]] as const) {
it(`puts a click in the pixel that holds it (${label})`, () => {
const at = 2 * SR + 123
const raw = click(30, at)
const w = 1200
const start = at / SR - view / 2
const s = rawSpans(raw, start, start + view, w, makeSpans())
const k = binAt(s, at / SR)
expect(s.hi[k]).toBeCloseTo(0.8)
// Its pixel is where the playhead (the view's centre) is.
expect(Math.abs(Math.round(s.x0 + k) - w / 2)).toBeLessThanOrEqual(1)
// Far from it, silence.
expect(s.hi[k + 20]).toBe(0)
expect(s.hi[k - 20]).toBe(0)
})
}
it('leaves bins outside the track empty', () => {
const raw = click(1, 100)
const s = rawSpans(raw, -0.5, 0.5, 1000, makeSpans())
expect(Number.isNaN(s.lo[10])).toBe(true)
expect(Number.isNaN(s.lo[900])).toBe(false)
})
it('draws a sine as one continuous line at deep zoom', () => {
const mono = new Float32Array(SR)
for (let i = 0; i < mono.length; i++) mono[i] = Math.sin((2 * Math.PI * 60 * i) / SR) * 0.7
const s = rawSpans(rawWaveFromMono(mono, SR), 0.4, 0.65, 1200, makeSpans())
for (let k = 1; k < s.n; k++) {
// Each stroke overlaps the previous: no gap a line could fall through.
expect(s.lo[k]).toBeLessThanOrEqual(s.hi[k - 1] + 1e-6)
expect(s.hi[k]).toBeGreaterThanOrEqual(s.lo[k - 1] - 1e-6)
}
})
it('interpolates when a pixel is narrower than a sample', () => {
const mono = new Float32Array(SR)
for (let i = 0; i < mono.length; i++) mono[i] = i / mono.length
// 0.01 s across 4000 px: ~0.11 samples a pixel.
const s = rawSpans(rawWaveFromMono(mono, SR), 0.5, 0.51, 4000, makeSpans())
const k = 2000
expect(s.lo[k]).toBeCloseTo(s.t[k], 3)
})
it('agrees with itself across the block/sample switch-over', () => {
const mono = new Float32Array(10 * SR)
for (let i = 0; i < mono.length; i++) mono[i] = Math.sin(i * 0.001) * Math.sin(i * 0.37) * 0.9
const raw = rawWaveFromMono(mono, SR)
const w = 1000
// Just either side of 128 samples a pixel.
const sample = rawSpans(raw, 1, 1 + (127 * w) / SR, w, makeSpans())
const block = rawSpans(raw, 1, 1 + (129 * w) / SR, w, makeSpans())
// At the same time, the block path's extent contains the sample path's
// (it may smear by part of a block, never miss a peak).
for (const k of [100, 400, 700]) {
const j = binAt(block, sample.t[k])
const near = [j - 1, j, j + 1]
expect(Math.min(...near.map((i) => block.lo[i]))).toBeLessThanOrEqual(sample.lo[k] + 1e-6)
expect(Math.max(...near.map((i) => block.hi[i]))).toBeGreaterThanOrEqual(sample.hi[k] - 1e-6)
}
})
it('bins in track space, so scrolling does not regroup samples', () => {
const mono = new Float32Array(4 * SR)
for (let i = 0; i < mono.length; i++) mono[i] = Math.sin(i * 0.013) * Math.sin(i * 0.41)
const raw = rawWaveFromMono(mono, SR)
const w = 800
const view = 8 // wide: block path
const a = rawSpans(raw, 0.5, 0.5 + view, w, makeSpans())
const lo = Array.from(a.lo.subarray(0, a.n))
const shift = (view / w) * 0.37 // a fraction of a pixel
const b = rawSpans(raw, 0.5 + shift, 0.5 + shift + view, w, makeSpans())
expect(Array.from(b.lo.subarray(0, b.n))).toEqual(lo)
})
})
describe('laneScales', () => {
it('scales each stem by its own peak', () => {
const [a, b] = laneScales([1, 0.5], 100)
expect(a).toBeCloseTo(100)
expect(b).toBeCloseTo(200)
})
it('never magnifies a near-silent stem past 5% of the loudest', () => {
const [, quiet] = laneScales([1, 0.001], 100)
expect(quiet).toBeCloseTo(100 / 0.05)
})
})
describe('tintAt', () => {
const col = (low: number, mid: number, high: number): WaveColumn => ({ peak: 1, low, mid, high })
const rgb = (s: string) => s.slice(4, -1).split(',').map(Number)
const saturation = (s: string) => Math.max(...rgb(s)) - Math.min(...rgb(s))
it('keeps each band its bar colour', () => {
const [r, g, b] = rgb(tintAt([col(1, 0, 0)], 1, 0.5))
expect(r).toBeGreaterThan(g)
expect(g).toBeGreaterThan(b) // orange
const [r2, , b2] = rgb(tintAt([col(0, 0, 1)], 1, 0.5))
expect(b2).toBeGreaterThan(r2) // cyan
})
it('never greys out where bands mix', () => {
// A plain weighted mean of orange + violet + cyan spreads only 26-56 here.
for (const mix of [col(1, 1, 1), col(1, 0, 1), col(0.6, 1, 0.4)]) {
expect(saturation(tintAt([mix], 1, 0.5))).toBeGreaterThan(90)
}
})
})
+362
View File
@@ -0,0 +1,362 @@
// The RAW waveform: the main view's alternative to bars (the toggle under its
// zoom buttons, persisted as `mainWaveRaw`), after Traktor at full zoom — a thin
// signed line of the actual signal, its colour shifting with the frequency mix.
// The bars (`waveform.ts`) draw ~7 ms columns of unsigned band energy, which
// hides where a kick actually starts; this draws the samples.
//
// Decided (discussion 2026-10-15): the SHAPE is exact and the COLOUR is
// approximate — the tint comes from the bars' ~7 ms band columns, in the bars'
// palette blended in OKLab (`bandColour`), lerped between columns. The vertical scale is fixed by the track's
// loudest sample, so relative loudness is truthful and the height never pumps
// while scrolling.
//
// Two data paths, by how many samples one pixel covers:
// * many (wide zoom): min/max per RAW_BLOCK samples, summarised once at load
// (~4 MB for a 6-minute track) — a 64 s view reads ~90k block values;
// * few (deep zoom): the visible window read straight from the decoded
// AudioBuffer each frame. No full-length mono copy is kept; the playback
// engine holds the buffer anyway.
// Each pixel is a vertical stroke from the lowest to the highest sample in it,
// stretched to touch its neighbour's — zoomed out it reads as a filled
// envelope, zoomed in it narrows to one continuous line, with no switch-over.
import type { WaveColumn } from './waveform'
/** Samples per entry of the min/max summary. */
export const RAW_BLOCK = 32
/** Below this many samples per pixel, read samples instead of blocks: a pixel
* then spans at least 4 blocks, so block edges smear it by at most a quarter. */
const SAMPLE_PATH_BELOW = 4 * RAW_BLOCK
export interface RawWave {
sampleRate: number
/** Samples in the track. */
length: number
/** Min / max of the mono downmix per RAW_BLOCK samples. */
min: Float32Array
max: Float32Array
/** The loudest absolute sample — the fixed vertical scale. */
peak: number
/** Fill `dest` with the mono downmix from sample `start` (zeros outside). */
readMono: (start: number, dest: Float32Array) => void
}
/** A reader of an AudioBuffer's mono downmix. copyFromChannel copies, so this
* never holds a view the playback engine could detach (the Firefox gotcha). */
export function bufferReader(buffer: AudioBuffer): RawWave['readMono'] {
let tmp = new Float32Array(0)
const chs = buffer.numberOfChannels
return (start, dest) => {
dest.fill(0)
const from = Math.max(0, start)
const skip = from - start
const n = Math.min(dest.length - skip, buffer.length - from)
if (n <= 0) return
if (tmp.length < n) tmp = new Float32Array(n)
const view = tmp.subarray(0, n)
for (let c = 0; c < chs; c++) {
buffer.copyFromChannel(view, c, from)
for (let i = 0; i < n; i++) dest[skip + i] += view[i] / chs
}
}
}
/** Summarise a mono downmix. `readMono` defaults to reading `mono` itself
* (tests); the deck passes `bufferReader` so `mono` can be dropped. */
export function rawWaveFromMono(
mono: Float32Array,
sampleRate: number,
readMono?: RawWave['readMono'],
): RawWave {
const len = mono.length
const nb = Math.max(1, Math.ceil(len / RAW_BLOCK))
const min = new Float32Array(nb)
const max = new Float32Array(nb)
let peak = 0
for (let b = 0; b < nb; b++) {
let lo = Infinity
let hi = -Infinity
const end = Math.min(len, (b + 1) * RAW_BLOCK)
for (let i = b * RAW_BLOCK; i < end; i++) {
const v = mono[i]
if (v < lo) lo = v
if (v > hi) hi = v
}
if (lo === Infinity) lo = hi = 0
min[b] = lo
max[b] = hi
peak = Math.max(peak, -lo, hi)
}
return {
sampleRate,
length: len,
min,
max,
peak,
readMono:
readMono ??
((start, dest) => {
dest.fill(0)
for (let i = 0; i < dest.length; i++) {
const j = start + i
if (j >= 0 && j < len) dest[i] = mono[j]
}
}),
}
}
/** Reusable per-pixel output of `rawSpans`. */
export interface RawSpans {
lo: Float32Array
hi: Float32Array
/** Track time at each bin's centre (for the colour). */
t: Float64Array
/** Bins filled; bin k is drawn at device pixel `round(x0 + k)`. */
n: number
x0: number
scratch: Float32Array
}
export function makeSpans(): RawSpans {
return { lo: new Float32Array(0), hi: new Float32Array(0), t: new Float64Array(0), n: 0, x0: 0, scratch: new Float32Array(0) }
}
/**
* Per-pixel min/max of `raw` across a `w`-pixel view of [startSec, endSec).
* Bins sit on a TRACK-space grid (bin g covers [g, g+1) pixel widths of track
* time), so a scrolling view moves bins rather than regrouping samples under
* them — the same reason `paintWave` bins in track space: regrouping makes
* every peak shimmer as the playhead advances. Bins outside the track are NaN.
*/
export function rawSpans(raw: RawWave, startSec: number, endSec: number, w: number, out: RawSpans): RawSpans {
const secPerPx = (endSec - startSec) / w
const spp = secPerPx * raw.sampleRate // samples per pixel
const g0 = Math.floor(startSec / secPerPx)
const n = w + 2
if (out.lo.length < n) {
out.lo = new Float32Array(n)
out.hi = new Float32Array(n)
out.t = new Float64Array(n)
}
out.n = n
out.x0 = g0 - startSec / secPerPx
const { lo, hi, t } = out
for (let k = 0; k < n; k++) t[k] = (g0 + k + 0.5) * secPerPx
if (spp >= SAMPLE_PATH_BELOW) {
const nb = raw.min.length
for (let k = 0; k < n; k++) {
const s0 = (g0 + k) * spp
const s1 = s0 + spp
if (s1 <= 0 || s0 >= raw.length) {
lo[k] = hi[k] = NaN
continue
}
const b0 = Math.max(0, Math.floor(s0 / RAW_BLOCK))
const b1 = Math.min(nb, Math.max(b0 + 1, Math.ceil(s1 / RAW_BLOCK)))
let a = Infinity
let z = -Infinity
for (let b = b0; b < b1; b++) {
if (raw.min[b] < a) a = raw.min[b]
if (raw.max[b] > z) z = raw.max[b]
}
lo[k] = a
hi[k] = z
}
} else {
// One read covers the window, plus a sample each side for interpolation.
const first = Math.floor(g0 * spp) - 1
const count = Math.ceil(n * spp) + 3
if (out.scratch.length < count) out.scratch = new Float32Array(count)
const win = out.scratch.subarray(0, count)
raw.readMono(first, win)
for (let k = 0; k < n; k++) {
const s0 = (g0 + k) * spp
const s1 = s0 + spp
if (s1 <= 0 || s0 >= raw.length) {
lo[k] = hi[k] = NaN
continue
}
const i0 = Math.ceil(s0)
const i1 = Math.ceil(s1)
let a = Infinity
let z = -Infinity
for (let i = i0; i < i1; i++) {
const v = win[i - first]
if (v < a) a = v
if (v > z) z = v
}
if (a === Infinity) {
// Narrower than a sample: the line's value at the bin's centre.
const c = (s0 + s1) / 2
const i = Math.floor(c)
const f = c - i
a = z = win[i - first] * (1 - f) + win[i + 1 - first] * f
}
lo[k] = a
hi[k] = z
}
}
// Join each stroke to the previous one (by its ORIGINAL extent), so a steep
// edge stays a continuous line instead of a dotted one.
let pLo = NaN
let pHi = NaN
for (let k = 0; k < n; k++) {
const a = lo[k]
const z = hi[k]
if (a === a && pLo === pLo) {
if (a > pHi) lo[k] = pHi
if (z < pLo) hi[k] = pLo
}
pLo = a
pHi = z
}
return out
}
/** Pixels per unit amplitude for each stem lane: each stem at its own peak,
* but never below 5% of the loudest stem's — the same floor as the bar lanes,
* so a near-silent stem draws as near-silence, not magnified noise. */
export function laneScales(peaks: number[], halfHeight: number): number[] {
const loudest = Math.max(1e-6, ...peaks)
return peaks.map((p) => halfHeight / Math.max(p, loudest * 0.05, 1e-6))
}
// The bars' band colours (waveform.ts LAYERS), as RGB.
const BANDS = [
[255, 138, 61], // bass
[143, 107, 255], // mids
[94, 231, 255], // highs
]
// sRGB <-> OKLab (Björn Ottosson's matrices).
function toLab([r, g, b]: number[]): number[] {
const lin = (v: number) => ((v /= 255) <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)
const R = lin(r)
const G = lin(g)
const B = lin(b)
const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B)
const m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B)
const s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B)
return [
0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
]
}
function fromLab([L, A, B]: number[]): number[] {
const l = (L + 0.3963377774 * A + 0.2158037573 * B) ** 3
const m = (L - 0.1055613458 * A - 0.0638541728 * B) ** 3
const s = (L - 0.0894841775 * A - 1.291485548 * B) ** 3
const enc = (v: number) => {
v = Math.min(1, Math.max(0, v))
return 255 * (v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055)
}
return [
enc(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
enc(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
enc(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),
]
}
const BAND_LAB = BANDS.map(toLab)
const BAND_CHROMA = BAND_LAB.map(([, a, b]) => Math.hypot(a, b))
/**
* A column's colour from its band energies. Mixed in OKLab, then the CHROMA is
* put back to the bands' weighted chroma: a plain weighted mean of orange,
* violet and cyan lands near grey (they sit around the hue wheel), which read
* as mud on busy passages. Chosen 2026-10-15 from five candidates rendered on
* real tracks: orange + violet blends through pink (Traktor-like), highs stay
* cyan, and nothing greys out. Lifted a touch so it reads on the dark well.
*/
function bandColour(low: number, mid: number, high: number): number[] {
const w = [low, mid, high]
const sum = low + mid + high
if (sum < 1e-6) return BANDS[0]
const mix = [0, 1, 2].map((c) => BAND_LAB.reduce((acc, lab, b) => acc + lab[c] * w[b], 0) / sum)
const chroma = BAND_CHROMA.reduce((acc, ch, b) => acc + ch * w[b], 0) / sum
const k = chroma / Math.max(1e-6, Math.hypot(mix[1], mix[2]))
return fromLab([mix[0] + 0.04, mix[1] * k, mix[2] * k])
}
const columnRgb = new WeakMap<WaveColumn[], Float32Array>()
/** Each band column's colour (`bandColour`), computed once per analysis. */
function rgbOf(cols: WaveColumn[]): Float32Array {
let rgb = columnRgb.get(cols)
if (rgb) return rgb
rgb = new Float32Array(cols.length * 3)
for (let i = 0; i < cols.length; i++) rgb.set(bandColour(cols[i].low, cols[i].mid, cols[i].high), i * 3)
columnRgb.set(cols, rgb)
return rgb
}
const styles = new Map<number, string>()
/** The tint at track time `t`: lerped between the two nearest band columns,
* quantised to 32 levels a channel so a frame reuses a small set of strings. */
export function tintAt(cols: WaveColumn[], duration: number, t: number): string {
const rgb = rgbOf(cols)
const n = cols.length
const c = Math.min(n - 1, Math.max(0, (t / duration) * n - 0.5))
const i = Math.floor(c)
const j = Math.min(n - 1, i + 1)
const f = c - i
let key = 0
for (let ch = 0; ch < 3; ch++) {
const v = rgb[i * 3 + ch] * (1 - f) + rgb[j * 3 + ch] * f
key = (key << 5) | Math.min(31, Math.round(v / 8.226))
}
let s = styles.get(key)
if (!s) {
const r = ((key >> 10) & 31) * 8.226
const g = ((key >> 5) & 31) * 8.226
const b = (key & 31) * 8.226
s = `rgb(${r | 0},${g | 0},${b | 0})`
styles.set(key, s)
}
return s
}
/**
* Paint spans as a line centred in [y0, y0 + h). `scale` is pixels per unit
* amplitude; `thick` the minimum stroke (device px), so a flat stretch still
* reads as a line. `colour` is a fixed style or a per-bin function (by time).
*/
export function paintRaw(
ctx: CanvasRenderingContext2D,
s: RawSpans,
y0: number,
h: number,
scale: number,
thick: number,
colour: string | ((t: number) => string),
): void {
const mid = y0 + h / 2
const fixed = typeof colour === 'string'
if (fixed) ctx.fillStyle = colour
let current = ''
const wpx = Math.max(1, Math.round(thick * 0.8))
for (let k = 0; k < s.n; k++) {
const a = s.lo[k]
if (a !== a) continue
let top = mid - s.hi[k] * scale
let bot = mid - a * scale
if (bot - top < thick) {
const c = (top + bot) / 2
top = c - thick / 2
bot = c + thick / 2
}
if (!fixed) {
const style = colour(s.t[k])
if (style !== current) {
ctx.fillStyle = style
current = style
}
}
ctx.fillRect(Math.round(s.x0 + k), top, wpx, bot - top)
}
}
+250
View File
@@ -0,0 +1,250 @@
// What every shortcut does, for the keyboard map in `ShortcutsDialog`.
// Written out BY HAND, not derived from the handlers: keep it in step with
// `PrepStrip` (deck), `TrackTable` (track list) and `SettingsMenu` (`?`).
import { cueTypeColor, GRID_MARKER_ACTIVE_COLOR } from './cues'
import { IS_MAC } from './modKey'
/** A modifier layer of the keyboard. `mod` is Cmd on macOS, Ctrl elsewhere —
* the handlers accept either, but the map names your key. */
export type Layer = 'base' | 'shift' | 'mod'
export const LAYERS: Layer[] = ['base', 'shift', 'mod']
export const MODIFIER_KEY: Record<Exclude<Layer, 'base'>, string> = IS_MAC
? { shift: '⇧', mod: '⌘' }
: { shift: 'Shift', mod: 'Ctrl' }
export const LAYER_NAMES: Record<Layer, string> = IS_MAC
? { base: 'No modifier', shift: '⇧ Shift', mod: '⌘ Command' }
: { base: 'No modifier', shift: 'Shift', mod: 'Ctrl' }
/** Where a shortcut acts. The colour lights its key on the map. */
export type Area = 'deck' | 'list' | 'any'
export const AREAS: Record<Area, string> = { deck: 'Deck', list: 'Track list', any: 'Anywhere' }
export const AREA_COLORS: Record<Area, string> = {
deck: 'var(--color-accent)',
list: '#6fd6e8',
any: 'var(--color-text)',
}
export interface Binding {
area: Area
/** Printed on the key — a word or two; the key's own legend names it. */
label: string
/** The caption's full sentence. */
text: string
/** Overrides the area colour where the key has a colour of its own (pads, stems). */
color?: string
}
export type Bindings = Record<Layer, Record<string, Binding[]>>
/** A stem file's default layout (NI's), since the map cannot know the loaded track's. */
const STEMS: [string, string][] = [
['drums', '#009E73'],
['bass', '#D55E00'],
['synths', '#CC79A7'],
['vox', '#56B4E9'],
]
const STEM_CODES = ['KeyQ', 'KeyW', 'KeyE', 'KeyR']
/** The digit keys of a bank of `slots` pads: 1–9, then 0 for the tenth, as
* `PrepStrip`'s `slotForDigit` reads them. */
export function padCodes(slots: number): string[] {
return Array.from({ length: Math.min(slots, 10) }, (_, i) => (i === 9 ? 'Digit0' : `Digit${i + 1}`))
}
/** "1–8", or "1–9, 0" for a ten-pad bank. */
export function padRange(slots: number): string {
const n = Math.min(slots, 10)
if (n <= 1) return '1'
if (n <= 9) return `1–${n}`
return '1–9, 0'
}
export function bindings(slots: number): Bindings {
const b: Bindings = { base: {}, shift: {}, mod: {} }
const pad = cueTypeColor('cue')
padCodes(slots).forEach((code, i) => {
const n = i + 1
b.base[code] = [
{ area: 'deck', label: 'Pad', color: pad, text: `Hotcue ${n}: set it if the pad is empty, otherwise jump to it. Hold to preview.` },
]
b.shift[code] = [{ area: 'deck', label: 'Delete', color: 'var(--color-pink)', text: `Delete hotcue ${n}` }]
})
STEM_CODES.forEach((code, i) => {
const [name, color] = STEMS[i]
b.base[code] = [{ area: 'deck', label: 'Mute', color, text: `Stem tracks: mute or unmute stem ${i + 1} (usually ${name})` }]
b.shift[code] = [
{ area: 'deck', label: 'Solo', color, text: `Solo stem ${i + 1}: mute every other stem. Press again to unmute them all.` },
]
})
Object.assign(b.base, {
Space: [{ area: 'deck', label: 'Play / pause', text: 'Play / pause' }],
KeyC: [
{ area: 'deck', label: 'CUE', color: 'var(--color-gold)', text: 'CUE: jump back to the cue point, set it while paused, or hold to preview' },
],
ArrowLeft: [
{ area: 'deck', label: 'Jump −', text: 'Beat jump back by the loop size. While a loop plays, move the loop back by its length.' },
],
ArrowRight: [
{ area: 'deck', label: 'Jump +', text: 'Beat jump forward by the loop size. While a loop plays, move the loop forward by its length.' },
],
ArrowUp: [{ area: 'list', label: 'Up', text: 'Move the selection up one track' }],
ArrowDown: [{ area: 'list', label: 'Down', text: 'Move the selection down one track' }],
Enter: [
{ area: 'list', label: 'Load · OK', text: 'Load and play the highlighted track' },
{ area: 'any', label: 'OK', text: 'Save an edit, or confirm a dialog' },
],
Backspace: [
{
area: 'list',
label: 'Remove',
text: `Remove the selected tracks from this playlist${IS_MAC ? '' : ' (Delete works too)'}`,
},
],
Slash: [{ area: 'any', label: 'Help', text: 'Open this list of shortcuts' }],
Escape: [
{ area: 'list', label: 'Cancel', text: 'Clear the selection' },
{ area: 'any', label: 'Cancel', text: 'Cancel a drag or an edit, or close a dialog' },
],
} satisfies Record<string, Binding[]>)
Object.assign(b.shift, {
ArrowLeft: [{ area: 'deck', label: '◂ Grid', color: GRID_MARKER_ACTIVE_COLOR, text: 'Go to the previous grid marker' }],
ArrowRight: [{ area: 'deck', label: 'Grid ▸', color: GRID_MARKER_ACTIVE_COLOR, text: 'Go to the next grid marker' }],
ArrowUp: [{ area: 'list', label: 'Extend', text: 'Extend the selection up' }],
ArrowDown: [{ area: 'list', label: 'Extend', text: 'Extend the selection down' }],
} satisfies Record<string, Binding[]>)
Object.assign(b.mod, {
ArrowDown: [{ area: 'deck', label: 'Size ÷2', text: 'Halve the loop and beat-jump size (down to 1/32 beat)' }],
ArrowUp: [{ area: 'deck', label: 'Size ×2', text: 'Double the loop and beat-jump size (up to 32 beats)' }],
KeyA: [{ area: 'list', label: 'All', text: 'Select every track in the list' }],
} satisfies Record<string, Binding[]>)
return b
}
/** Why a digit past the bank does nothing — the bank follows the library. */
export function unusedNote(code: string, slots: number): string | null {
if (!/^Digit\d$/.test(code) || padCodes(slots).includes(code)) return null
return `Not used: this library has ${slots} hotcue pad${slots === 1 ? '' : 's'}.`
}
export interface MouseGesture {
mod?: Exclude<Layer, 'base'>
gesture: string
/** What is clicked or dragged, when it is not the column's whole area. */
on?: string
text: string
}
export const MOUSE: { title: string; rows: MouseGesture[] }[] = [
{
title: 'Deck',
rows: [
{ gesture: 'Drag', on: 'waveform', text: 'Scratch' },
{ mod: 'mod', gesture: 'Scroll', on: 'waveform', text: 'Zoom in and out' },
{ gesture: 'Click', on: 'stem button', text: 'Mute or unmute that stem' },
{ mod: 'mod', gesture: 'Click', on: 'stem button', text: 'Solo that stem' },
{ gesture: 'Right-click', on: 'pad', text: 'Hotcue type, colour, rename, delete' },
],
},
{
title: 'Track list',
rows: [
{ gesture: 'Click', text: 'Select a track' },
{ mod: 'shift', gesture: 'Click', text: 'Select a range' },
{ mod: 'mod', gesture: 'Click', text: 'Add to or remove from the selection' },
{ gesture: 'Double-click', on: 'cell', text: 'Edit it in place' },
{ gesture: 'Right-click', text: 'Track menu. On the header: choose columns' },
{ gesture: 'Drag', on: 'rows', text: 'Onto a playlist or export to add, onto the deck to load, within a playlist to reorder' },
{ mod: 'mod', gesture: 'Drag', on: 'rows', text: 'Move them out of this playlist into another' },
],
},
{
title: 'Sidebar',
rows: [
{ gesture: 'Right-click', text: 'New playlist or folder, rename, delete' },
{ gesture: 'Drag', on: 'playlist', text: 'Rearrange playlists and folders, or drop onto an export to add it' },
],
},
]
// ---- the keyboard drawn -----------------------------------------------------
export interface KeyDef {
code: string
legend: string
/** The legend when keys are too small for `legend`. */
short?: string
/** Width in key units. */
w?: number
/** A modifier key: holding or clicking it shows its layer. */
role?: Exclude<Layer, 'base'>
}
const key = (code: string, legend: string, w = 1, role?: KeyDef['role'], short?: string): KeyDef => ({
code,
legend,
w,
role,
short,
})
const chars = (s: string, prefix: string) => [...s].map((c) => key(prefix + c, c))
/** The main block, a row per list. Every row is 14.5 units wide. */
export const KEY_ROWS: KeyDef[][] = (() => {
const fn = [key('Escape', 'esc', 1.5)]
for (let i = 1; i <= 12; i++) fn.push(key(`F${i}`, `F${i}`))
fn.push(key('Power', ''))
const shift = IS_MAC ? 'shift ⇧' : 'Shift'
const shiftShort = IS_MAC ? '⇧' : 'Shift'
const bottom = IS_MAC
? [
key('Fn', 'fn'),
key('ControlLeft', 'control', 1.25, undefined, 'ctrl'),
key('AltLeft', 'option ⌥', 1.25, undefined, '⌥'),
key('MetaLeft', 'command ⌘', 1.5, 'mod', '⌘'),
key('Space', 'space', 6.75),
key('MetaRight', 'command ⌘', 1.5, 'mod', '⌘'),
key('AltRight', 'option ⌥', 1.25, undefined, '⌥'),
]
: [
key('ControlLeft', 'Ctrl', 1.25, 'mod'),
key('MetaLeft', 'Win', 1.25),
key('AltLeft', 'Alt', 1.25),
key('Space', 'space', 6.75),
key('AltRight', 'Alt', 1.25),
key('MetaRight', 'Win', 1.25),
key('ControlRight', 'Ctrl', 1.5, 'mod'),
]
return [
fn,
[key('Backquote', '`'), ...chars('1234567890', 'Digit'), key('Minus', '-'), key('Equal', '='),
key('Backspace', IS_MAC ? 'delete' : 'Backspace', 1.5, undefined, IS_MAC ? 'del' : 'Bksp')],
[key('Tab', 'tab', 1.5), ...chars('QWERTYUIOP', 'Key'), key('BracketLeft', '['), key('BracketRight', ']'), key('Backslash', '\\')],
[key('CapsLock', 'caps', 1.75), ...chars('ASDFGHJKL', 'Key'), key('Semicolon', ';'), key('Quote', "'"),
key('Enter', IS_MAC ? 'return' : 'Enter', 1.75)],
[key('ShiftLeft', shift, 2.25, 'shift', shiftShort), ...chars('ZXCVBNM', 'Key'), key('Comma', ','), key('Period', '.'),
key('Slash', '/ ?'), key('ShiftRight', shift, 2.25, 'shift', shiftShort)],
bottom,
]
})()
/** The inverted-T arrow cluster, 3 × 2, `null` for the gaps beside ↑. */
export const ARROW_KEYS: (KeyDef | null)[] = [
null, key('ArrowUp', '↑'), null,
key('ArrowLeft', '←'), key('ArrowDown', '↓'), key('ArrowRight', '→'),
]
/** The space between the main block and the arrows, in key units. */
export const ARROW_GAP = 0.36
/** The whole map's width in key units. */
export const KEYBOARD_UNITS = 14.5 + ARROW_GAP + 3
export const KEYS_BY_CODE: Record<string, KeyDef> = Object.fromEntries(
[...KEY_ROWS.flat(), ...ARROW_KEYS.filter((k): k is KeyDef => !!k)].map((k) => [k.code, k]),
)
/** The modifier layer a physical key holds, if it is one. */
export function modifierLayer(code: string): Exclude<Layer, 'base'> | null {
if (code === 'ShiftLeft' || code === 'ShiftRight') return 'shift'
const mod = IS_MAC ? ['MetaLeft', 'MetaRight'] : ['ControlLeft', 'ControlRight']
return mod.includes(code) ? 'mod' : null
}
+15 -3
View File
@@ -12,6 +12,9 @@
// and the structure of a track — where the bass drops out, where the highs
// build — is visible at a glance. Still no green, matching Traktor's palette.
import { alignDecoded, mp3HeaderFrame } from './decodeAlign'
import { bufferReader, rawWaveFromMono, type RawWave } from './rawWave'
export interface WaveColumn {
peak: number // 0..1 amplitude of the full mix
low: number // 0..1 band energies, each normalised to its own maximum
@@ -97,17 +100,21 @@ export interface WaveformAnalysis {
cols: WaveColumn[]
/** The decoded audio, retained for the scratch engine (reused, not re-decoded). */
buffer: AudioBuffer
/** The raw waveform of the same audio. */
raw: RawWave
}
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()
// Read BEFORE decoding: decodeAudioData detaches `arr`.
const header = mp3HeaderFrame(new Uint8Array(arr))
const AC: typeof AudioContext =
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
const ctx = new AC()
try {
return await ctx.decodeAudioData(arr)
return await alignDecoded(await ctx.decodeAudioData(arr), header)
} finally {
void ctx.close()
}
@@ -129,7 +136,8 @@ export async function analyzeWaveform(url: string, buckets?: number): Promise<Wa
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 }
const raw = rawWaveFromMono(mono, audio.sampleRate, bufferReader(audio))
return { cols: await analyzeMono(mono, audio.sampleRate, buckets), buffer: audio, raw }
}
export interface StemAnalysis {
@@ -138,6 +146,8 @@ export interface StemAnalysis {
/** Per stem, per column: amplitude 0..1 — the main view's lanes. */
lanes: Float32Array[]
buffers: AudioBuffer[]
/** Per stem: the raw waveform of its lane. */
raws: RawWave[]
}
/**
@@ -157,6 +167,7 @@ export async function analyzeStems(urls: string[], buckets?: number): Promise<St
const scale = n / len
const mono = new Float32Array(len)
const tmp = new Float32Array(len)
const raws: RawWave[] = []
const lanes = buffers.map((buf) => {
const lane = new Float32Array(n)
const chs = buf.numberOfChannels
@@ -172,6 +183,7 @@ export async function analyzeStems(urls: string[], buckets?: number): Promise<St
const b = (i * scale) | 0
if (a > lane[b]) lane[b] = a
}
raws.push(rawWaveFromMono(monoStem, sr, bufferReader(buf)))
return lane
})
const ceilOf = (v: Float32Array) => {
@@ -184,7 +196,7 @@ export async function analyzeStems(urls: string[], buckets?: number): Promise<St
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 }
return { cols: await analyzeMono(mono, sr, n), lanes, buffers, raws }
}
async function analyzeMono(mono: Float32Array<ArrayBuffer>, sr: number, buckets?: number): Promise<WaveColumn[]> {