mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-29 02:32:51 +01:00
Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1bd65ea707 | ||
|
|
2afba4557c | ||
|
|
aaa7537d50 | ||
|
|
632d2dc3c4 | ||
|
|
5d4df2aa52 | ||
|
|
8d0817b39e | ||
|
|
f55b8f06e4 | ||
|
|
5d1bfcf7f1 | ||
|
|
2a40106ea5 | ||
|
|
4799eaef17 | ||
|
|
717685f621 | ||
|
|
832dbed341 | ||
|
|
352aa3e956 | ||
|
|
1b1ed7e2b3 | ||
|
|
341f12e275 | ||
|
|
af02b1fc1c | ||
|
|
fe91a46bae | ||
|
|
9df73ddcd2 | ||
|
|
063463efdd | ||
|
|
2fcf6e7070 | ||
|
|
f5e7202f3f | ||
|
|
4fdb2b7ce1 | ||
|
|
65fbc775ce | ||
|
|
b57dd74445 | ||
|
|
31287bdeb7 | ||
|
|
210c1ab135 | ||
|
|
e211fd180a | ||
|
|
5d059c7604 | ||
|
|
667068c2f1 | ||
|
|
75cb0c8138 | ||
|
|
068e4da08b | ||
|
|
1a28ad6102 | ||
|
|
dd82fa99bb | ||
|
|
fae91e8772 | ||
|
|
68128a123e | ||
|
|
23a5cd72f4 | ||
|
|
17c177e34e |
No files matched your search
@@ -51,3 +51,6 @@ backend/dist/
|
|||||||
# ---- Stem engine (PyInstaller onedir build) ----
|
# ---- Stem engine (PyInstaller onedir build) ----
|
||||||
engine/build/
|
engine/build/
|
||||||
engine/dist/
|
engine/dist/
|
||||||
|
|
||||||
|
# ---- Rubber Band build (frontend/rubberband/build.sh downloads + compiles here) ----
|
||||||
|
frontend/rubberband/upstream/
|
||||||
@@ -53,6 +53,13 @@ Two independent apps that talk over HTTP:
|
|||||||
inserts among the CURRENT entries (a drop between a table's rows);
|
inserts among the CURRENT entries (a drop between a table's rows);
|
||||||
folder add (`playlist_index`) and device import (`into_playlist_index`)
|
folder add (`playlist_index`) and device import (`into_playlist_index`)
|
||||||
take the same.
|
take the same.
|
||||||
|
`POST /api/playlists/{id}/remove` (`dry_run` counts, changes nothing)
|
||||||
|
drops EVERY occurrence of the given tracks, other entries kept as they
|
||||||
|
are — the track menu's **Remove ▸ From playlist ▸** (decided 2026-10-22,
|
||||||
|
[the discussion](.claude/discussions/discuss-playlist-subtraction-2026-10-22.md)):
|
||||||
|
tracks picked anywhere leave a playlist that is not open, so "A minus B"
|
||||||
|
is open B, select all, remove from A. Lists every `can_reorder`
|
||||||
|
playlist but the open one; the confirm says how many it holds, even 0.
|
||||||
- `capabilities.py` — `Capabilities`: what the loaded library can persist, so
|
- `capabilities.py` — `Capabilities`: what the loaded library can persist, so
|
||||||
the UI can gate controls instead of branching on the platform.
|
the UI can gate controls instead of branching on the platform.
|
||||||
- `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over
|
- `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over
|
||||||
@@ -299,6 +306,34 @@ Two independent apps that talk over HTTP:
|
|||||||
cached. The header itself is read by `core/mp3_gapless.py`, which skips
|
cached. The header itself is read by `core/mp3_gapless.py`, which skips
|
||||||
the ID3v2 tag first — a check that did not once misread every real MP3
|
the ID3v2 tag first — a check that did not once misread every real MP3
|
||||||
as header-less.
|
as header-less.
|
||||||
|
- `file_block.py` — **Traktor's own block INSIDE the audio file**, and
|
||||||
|
removing it from copies (measured in Traktor 4.5, 2026-10-24: 2MUCH /
|
||||||
|
Alone (Vip)). Traktor writes a `DMRT` chunk tree (reversed 4CCs; chunk =
|
||||||
|
name + u32 size + u32 child count + payload) into every file it tags:
|
||||||
|
MP4 `ilst` atom `NITR` (mutagen: `_failed_atoms`, or a parsed key), ID3
|
||||||
|
`PRIV` owner `TRAKTOR4` (MP3/AIFF/WAV), Vorbis `traktor4` (FLAC). It
|
||||||
|
holds `HBPM` (float32 BPM), `CUEP` (cues), `AUID` (= the NML AUDIO_ID
|
||||||
|
after a 4-byte length), `TRN3` transients, tags. **An entry with no
|
||||||
|
MODIFIED_DATE — every entry Konduktor creates — makes Traktor re-read
|
||||||
|
the file and take `HBPM` over the NML's BPM, LOCK or not** (anchor
|
||||||
|
kept; it then stamps MODIFIED_DATE/TIME = the file's mtime, UTC
|
||||||
|
seconds). So a grid fixed after Traktor last wrote the block reverted on
|
||||||
|
every export/push. Measured alternatives: AUDIO_ID added — no effect;
|
||||||
|
MODIFIED_DATE later than the file — grid kept but Traktor skips the
|
||||||
|
file entirely, cover art lost. Block removed (no date, no AUDIO_ID) —
|
||||||
|
grid, lock, cues AND art right, a stale `tmpo` ignored, and Traktor
|
||||||
|
writes a fresh, correct block on deck load. Hence the TraktorExporter's
|
||||||
|
`prepare_copy` and the adapter's optional `prepare_copied_audio`
|
||||||
|
(importer copies only): ONLY a copy Konduktor wrote is touched, never a
|
||||||
|
file referenced in place or an upload. The runners
|
||||||
|
(`exporter.prepare_copy` / `prepare_kept`, also used by `local_push`)
|
||||||
|
record `prepared` per copy in the manifest / push ledger, so a KEPT copy
|
||||||
|
from an older export, or one a new Traktor target joins, is cleaned IN
|
||||||
|
PLACE rather than copied again. Not covered: a Traktor collection
|
||||||
|
edited directly — a tag write at Save makes the file newer than the
|
||||||
|
entry, which by the same rule should make Traktor re-read it
|
||||||
|
(untested). Flexible grids are a separate rule: Traktor rounds every
|
||||||
|
segment to a whole number of beats on load, whatever the file says.
|
||||||
- `adapters/rekordbox/` — **track metadata, playlists and hot cues writable;
|
- `adapters/rekordbox/` — **track metadata, playlists and hot cues writable;
|
||||||
the beatgrid still read-only** (milestones 2 and 3a). Also home to
|
the beatgrid still read-only** (milestones 2 and 3a). Also home to
|
||||||
`anlz_writer.py`, which BUILDS analysis files from nothing — Pioneer's format,
|
`anlz_writer.py`, which BUILDS analysis files from nothing — Pioneer's format,
|
||||||
@@ -912,6 +947,47 @@ Two independent apps that talk over HTTP:
|
|||||||
`set_auto_gain` after `add_tracks` (kit G1: an AUDIO_ID-less entry keeps
|
`set_auto_gain` after `add_tracks` (kit G1: an AUDIO_ID-less entry keeps
|
||||||
PERCEIVED_DB through Traktor's first analysis), the Rekordbox Library
|
PERCEIVED_DB through Traktor's first analysis), the Rekordbox Library
|
||||||
through its replay store's `set_auto_gain`. No stick target has one.
|
through its replay store's `set_auto_gain`. No stick target has one.
|
||||||
|
- `local_push.py` — **push an export set into THIS computer's Traktor /
|
||||||
|
rekordbox** (decided 2026-10-20, [the discussion](.claude/discussions/discuss-export-to-local-library-2026-10-20.md)):
|
||||||
|
a set's `kind` is `folder` (an export, as before) or `computer`, whose
|
||||||
|
`mode` is `merge` (default) or `overwrite`; targets ⊆ `PLATFORMS`, no
|
||||||
|
destination. Which library each app uses, the SHARED audio folder and its
|
||||||
|
level are this computer's PREFS (`localLibraries` {platform: path|null =
|
||||||
|
detected}, `localAudioRoot` (default platformdirs Music + `Konduktor`),
|
||||||
|
`localNormalise`, `localLevel`), never the set's (a remote's sets live on
|
||||||
|
its server). Audio lands at `<root>/<source path minus its anchor>` — not
|
||||||
|
`common_dir_prefix`, which moves when a set changes — so a track is ONE
|
||||||
|
file and ONE entry whatever sets hold it; hence one level for the folder.
|
||||||
|
**Merge** opens the library standalone (`registry.open_library`), adds
|
||||||
|
new tracks (`add_tracks`; a file the library already holds maps to its
|
||||||
|
id), brings changed ones up to date — the SOURCE wins — through
|
||||||
|
`set_track_metadata` / `set_key` / `set_track_color` / `set_auto_gain` /
|
||||||
|
`audio_changed` and the protocol's **`replace_cues`** (clear, then the
|
||||||
|
add path's own placement), removes what left the set unless another set
|
||||||
|
holds it or rekordbox refuses (History, Sampler, …: kept + reported,
|
||||||
|
retried), and rebuilds the set's playlists in ONE folder named after it
|
||||||
|
(suffixed `(Konduktor)` beside a user folder of that name; skipped when
|
||||||
|
its hash is unchanged). **Overwrite** runs the platform's export writer
|
||||||
|
into app-data and swaps the files in (rekordbox: `master.db`, the XML,
|
||||||
|
`share/` merged, stale `-wal`/`-shm` deleted); the other sets pushed
|
||||||
|
there are forgotten and their files deleted. The ledger
|
||||||
|
(`app_data/local_push/ledger.json`): per library (`library_id`) and set,
|
||||||
|
source id → local id, copy `rel`, prep hash; per audio root, the export
|
||||||
|
manifest's copy records (`exporter._record`). A copy no set holds is
|
||||||
|
deleted after the push. Refused while the app runs (`core/apps_running.py`,
|
||||||
|
psutil: `rekordbox` exactly, `traktor*` — macOS `Traktor Pro 4`; re-checked
|
||||||
|
before each save), for the library open in Konduktor, and cloud-synced
|
||||||
|
rekordbox. A target library NOT on this computer (`not_found`) is
|
||||||
|
SKIPPED, not a block (`TargetPlan.skipped`): a remote's sets are shared
|
||||||
|
by every computer opening it, so the set dialog lets it be ticked or
|
||||||
|
unticked anywhere; only none found blocks (`no_library_here`). Backup first: Traktor a version-history baseline + a commit per
|
||||||
|
push, rekordbox `master.db` + XML copied to `app_data/local_push/backups`
|
||||||
|
(10 kept). New copies are placed before the library is written; a copy
|
||||||
|
REPLACING a file a library plays waits as `*.konduktor-partial` until a
|
||||||
|
save. Routes `GET /api/local-libraries`, `POST /api/exports/{id}/push/preview`
|
||||||
|
and `/push` (job `local-push`); `/preview` and `/run` 400 a computer set.
|
||||||
|
UI: `ExportDialog`'s Where (folder / This computer, at creation only),
|
||||||
|
`PushRunDialog`, Settings → Local libraries (`LocalLibrariesSettings`).
|
||||||
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
|
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
|
||||||
dir). Last-opened collection (global AND per-platform), library column
|
dir). Last-opened collection (global AND per-platform), library column
|
||||||
layout, prep-deck zoom, import destination. Best-effort, but **every
|
layout, prep-deck zoom, import destination. Best-effort, but **every
|
||||||
@@ -1059,8 +1135,9 @@ Two independent apps that talk over HTTP:
|
|||||||
picker used to be a one-way door with `forcePicker` never set, so changing
|
picker used to be a one-way door with `forcePicker` never set, so changing
|
||||||
library meant restarting; switching confirms first when there are unsaved
|
library meant restarting; switching confirms first when there are unsaved
|
||||||
edits, since the adapter holds them in a native model that opening another
|
edits, since the adapter holds them in a native model that opening another
|
||||||
library replaces — plus the playlist tree. **Creating is right-click
|
library replaces — plus the playlist tree. **Creating is right-click,
|
||||||
only**: a folder's menu offers New Playlist / New Folder inside it, empty
|
or the Playlists header's +** (the top-level menu under the button; with
|
||||||
|
no folders, straight to a new playlist): a folder's menu offers New Playlist / New Folder inside it, empty
|
||||||
space below the rows creates at the top level, and the new node is named
|
space below the rows creates at the top level, and the new node is named
|
||||||
in place (Esc or an empty name creates nothing). Rename/Delete are on the
|
in place (Esc or an empty name creates nothing). Rename/Delete are on the
|
||||||
same menu and the row's hover buttons, which share one set of actions.
|
same menu and the row's hover buttons, which share one set of actions.
|
||||||
@@ -1097,7 +1174,7 @@ Two independent apps that talk over HTTP:
|
|||||||
/ Try again (`backend_restart`). The shell has no timeout of its own. Before
|
/ 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
|
ready it answers quit requests itself — nothing can be unsaved — and stops
|
||||||
at ready so it never races `QuitGuard`), `SaveBar` (+ "Discard changes…" when
|
at ready so it never races `QuitGuard`), `SaveBar` (+ "Discard changes…" when
|
||||||
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),
|
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 `lib/deckKeys.ts` / `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)) — and its own panel, `PerformanceSettings` ("Performance mode…", decided 2026-11-03), whose values sit in the same `APP_SETTING_DEFAULTS`: `perfStems` (default on: a stem track loaded INTO performance mode plays its stems, else its mix; read at load, never reloads a deck), `keylockDefault` (on), `autoFocusDeck` (on: any press on a deck focuses it; off: only its A/B badge, a button), `useAutoGain` (on: a channel's gain starts at the track's auto gain; off: 0 dB), `eqKill` (off = -26 dB), `crossfaderSharpness` (0..1, 0 = smooth, default 0.5: a slider beside `CrossfaderCurveGraph`, which draws both channels' curves and where the crossfader is; dragging it moves the mixer at once and saves through the debounced prefs writer), and the Filter FX: `fxFilterRange` (the Filter alone) and `fxEffectRange` (under an effect), each full / musical / gentle, `fxFilterResonance`, `fxReverbSize`, `fxDelayBeats`, `fxCrusherDrive`, `fxFlangerBeats` (the mixer's per-channel PRM knob was removed). PrepStrip copies them into `mixerState`. 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
|
`TrackTable` (**the one track list** — All Tracks, playlists, exports and
|
||||||
devices. TanStack Table + **virtualized** grid; per-row play button,
|
devices. TanStack Table + **virtualized** grid; per-row play button,
|
||||||
configurable columns, header sorting, inline double-click editing, and
|
configurable columns, header sorting, inline double-click editing, and
|
||||||
@@ -1230,8 +1307,9 @@ Two independent apps that talk over HTTP:
|
|||||||
newest non-draft, non-prerelease `v…` tag — NOT `/releases/latest`, since the
|
newest non-draft, non-prerelease `v…` tag — NOT `/releases/latest`, since the
|
||||||
stem engine publishes `engine-v*` releases in the same repo — and,
|
stem engine publishes `engine-v*` releases in the same repo — and,
|
||||||
if its tag's **semver part** is newer than `__APP_VERSION__` — build-number
|
if its tag's **semver part** is newer than `__APP_VERSION__` — build-number
|
||||||
`-b<N>` bumps don't count — shows an update dialog with the release's
|
`-b<N>` bumps don't count — shows an update dialog with the "What's
|
||||||
"What's Changed" bullets; "Skip this version" persists
|
Changed" bullets of EVERY release newer than the running version (paged,
|
||||||
|
one section per release, newest first); "Skip this version" persists
|
||||||
`skippedUpdateVersion` to userprefs via `/api/prefs`; check failures are
|
`skippedUpdateVersion` to userprefs via `/api/prefs`; check failures are
|
||||||
silent. **In the desktop app, Update installs it** (decided 2026-10-16,
|
silent. **In the desktop app, Update installs it** (decided 2026-10-16,
|
||||||
[the discussion](.claude/discussions/discuss-self-update-2026-10-16.md)):
|
[the discussion](.claude/discussions/discuss-self-update-2026-10-16.md)):
|
||||||
@@ -1256,11 +1334,10 @@ Two independent apps that talk over HTTP:
|
|||||||
- **Stem playback** (decided 2026-09-30): a stem FILE always loads its four
|
- **Stem playback** (decided 2026-09-30): a stem FILE always loads its four
|
||||||
stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays
|
stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays
|
||||||
their SUM, as Traktor's stem deck does — the mix stream is never decoded,
|
their SUM, as Traktor's stem deck does — the mix stream is never decoded,
|
||||||
which also saves a full-length buffer. `PlaybackEngine.load` takes several
|
which also saves a full-length buffer. The deck's worklet (`lib/audio/`)
|
||||||
buffers: one source + gain each, all started at ONE scheduled context
|
takes several stems and reads them all at ONE position, so they stay
|
||||||
time (so they stay sample-locked through seeks and loops), mute/solo as
|
sample-locked through seeks, loops and scratch (which hears what is
|
||||||
ramped gains, never a restart. `ScratchEngine.loadStems` keeps ONE summed
|
audible); mute/solo are ramped gains, never a restart.
|
||||||
copy of the audible stems (not four), re-summed in slices on a mute change.
|
|
||||||
`analyzeStems` returns the overview's three-band columns (of the sum) plus
|
`analyzeStems` returns the overview's three-band columns (of the sum) plus
|
||||||
one amplitude lane per stem, each normalised to its own 99.5th percentile
|
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).
|
but never below 5% of the loudest (a silent stem stays silent).
|
||||||
@@ -1269,10 +1346,65 @@ Two independent apps that talk over HTTP:
|
|||||||
Q W E R mute stems 1-4, Shift+ solos. **Solo is not a mode**: it SETS the
|
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
|
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
|
it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is
|
||||||
the cost: ~140 MB per stem for 6 minutes, i.e. the same four buffers as
|
the cost: ~127 MB of stereo PCM per stem for 6 minutes in the worklet,
|
||||||
the file holds streams, and no more.
|
plus a half-size mono copy each on the main thread for the raw waveform —
|
||||||
- **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it,
|
~6 stereo-track units for a stem track (it was 5: four buffers plus a
|
||||||
in three rows. **Header**: cover, title/artist · album · genre, a Read-only
|
summed scratch copy), 1.5 for a plain track (it was 2).
|
||||||
|
- **Prep strip** (DJ deck across the top of the window), in three rows.
|
||||||
|
**The deck is `components/deck/`** (split out 2026-11-02 for performance
|
||||||
|
mode's second deck): `useDeck` holds everything a deck DOES — engine,
|
||||||
|
transport, CUE, hotcues, memory cues, loops, grid editing, stems,
|
||||||
|
analysis — and takes its capabilities as a PARAMETER (each deck may hold
|
||||||
|
a different library's track), returning a `Deck` that `DeckHeader`,
|
||||||
|
`DeckMainWave` / `DeckOverview`, `DeckControls` and `DeckOverlays` (its
|
||||||
|
menus and dialogs, under the deck's own `CapabilitiesContext`) render.
|
||||||
|
`PrepStrip` lays one deck out and owns what decks SHARE: the main view's
|
||||||
|
zoom + raw toggle (`DeckView`, persisted) and the keyboard —
|
||||||
|
`lib/deckKeys.ts`, ONE window listener routing each key to the focused
|
||||||
|
deck (Alt/Option = the other deck, in performance mode; a key-up goes to
|
||||||
|
the deck its key-down went to). A deck's `persist` (loop size, cue bank)
|
||||||
|
is deck A's; `leadsAmbient` (cover colours) the focused deck's.
|
||||||
|
**Performance mode** (P, or the Performance button at the RIGHT of the
|
||||||
|
track list's toolbar — `deck/PerformanceButton`, the toolbar's `trailing`;
|
||||||
|
decided
|
||||||
|
2026-11-02, [the discussion](.claude/discussions/discuss-performance-mode-2026-11-02.md)):
|
||||||
|
deck B appears — the two headers side by side (`compact`, each led by its
|
||||||
|
letter, lit when focused), the two main waveforms STACKED at the one zoom
|
||||||
|
past one playhead line (each lane a drop target for its own deck, ringed
|
||||||
|
while focused), the overviews side by side, then each deck's controls
|
||||||
|
`stacked` (pads and the mode switches on a second row; the tempo group
|
||||||
|
folds below 44rem) and a TEMPO row (`DeckTempo`: KEY, SYNC, MASTER, the
|
||||||
|
phase meter, the pitch fader with its ±8/16/50 range, the tempo as heard),
|
||||||
|
each beside its overview, the MIXER between them. The pitch fader is the
|
||||||
|
deck's SPEED (`useDeck`'s `rate`, applied only while `tempoActive` — the
|
||||||
|
prep deck always plays at the file's tempo); the header's BPM stays the
|
||||||
|
GRID's. SYNC (`lib/sync.ts`, tested): a follower takes the MASTER's tempo
|
||||||
|
at the nearer octave (½/1/2), widening its range if it must, and while both
|
||||||
|
play its beats are re-aligned by a seek whenever they drift past 3% of a
|
||||||
|
beat (checked every 150 ms, at once when the follower starts); a flexible
|
||||||
|
grid follows the segment under the playhead; moving the follower's pitch by
|
||||||
|
hand releases it; SYNC on the master hands the master over. DRAGGING THE
|
||||||
|
PHASE METER bends the deck's speed while held (right faster, left slower,
|
||||||
|
squared up to ±5% at 80 px, Shift ×¼ — `sync.bendFor`; `useDeck.bend`
|
||||||
|
multiplies `rate`, so the readout and a follower see it), springing back
|
||||||
|
on release; bending a synced follower releases its SYNC. Measured in
|
||||||
|
the app: 175 synced to 125 lands at 125.00 within 0.005 beat and follows
|
||||||
|
the master's pitch. Leaving performance mode releases SYNC. App holds `decks: {A, B}`
|
||||||
|
(`DeckSlot`: track, origin, playRequest, cuesRefresh), `focusedDeck` and
|
||||||
|
`performance`; the focus moves on any press on a deck (or only its A/B
|
||||||
|
badge, with the `autoFocusDeck` setting off); a load, Enter, a row's play button and a drop on the strip
|
||||||
|
go to the FOCUSED deck (A outside the mode), "Load to Deck A/B" to either,
|
||||||
|
and the table lights the focused deck's row. Entering with B empty focuses
|
||||||
|
B. **Past the edges** (decided 2026-11-03): in performance mode a beat
|
||||||
|
jump or loop move may land BEFORE the track — the engine's lead-in
|
||||||
|
(`setLeadIn`, up to 32 s): silence until the track starts, on the beat,
|
||||||
|
ELAPSED counting up from −; SYNC may align into it — and a loop may reach
|
||||||
|
past the END (it loops silence). A jump past the end still stops the
|
||||||
|
deck there, as the end of a track does. Prep mode keeps both edges hard;
|
||||||
|
leaving performance mode in the lead-in snaps to 0.
|
||||||
|
B's `useDeck` stays MOUNTED while hidden — leaving pauses it, coming
|
||||||
|
back finds it as it was; a library switch empties both decks. Not
|
||||||
|
persisted. **Header**: cover, title/artist · album · genre, a Read-only
|
||||||
badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` —
|
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
|
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**:
|
Set grid on a track with no BPM opens the readout to ask rather than failing), SNAP, Analyze, Auto hotcues. **Waveforms**:
|
||||||
@@ -1283,13 +1415,14 @@ Two independent apps that talk over HTTP:
|
|||||||
`OverviewWaveform`, which frames the main view's visible range around the
|
`OverviewWaveform`, which frames the main view's visible range around the
|
||||||
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then
|
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then
|
||||||
(where `cues.memory_cues`) the **Hot / Mem** switch (`ModeSwitch`, the same component as BEAT / MAN), then
|
(where `cues.memory_cues`) the **Hot / Mem** switch (`ModeSwitch`, the same component as BEAT / MAN), then
|
||||||
`HotcueBar`, `MemoryCueStrip` (Mem) OR — in **Grid mode** — `GridEditStrip`, then `TempoControls`
|
`HotcueBar`, `MemoryCueStrip` (Mem) OR — in **Grid mode** — `GridEditStrip`, then the
|
||||||
(±0.01 / ±0.25, ÷2 ×2, tap, lock) and the Grid toggle. The row is a
|
**CUES / GRID** switch (also a `ModeSwitch`) and `TempoControls`
|
||||||
|
(±0.01 / ±0.25, ÷2 ×2, tap, lock). A two-option `ModeSwitch` flips on a
|
||||||
|
click anywhere on it. The row is a
|
||||||
**container** and gives way in stages instead of overlapping: each pad
|
**container** and gives way in stages instead of overlapping: each pad
|
||||||
queries its own width and drops its name below 4rem (the bank never goes
|
queries its own width and drops its name below 4rem (the bank never goes
|
||||||
below `PAD_MIN` per pad), then the tempo group folds into `TempoFold`'s
|
below `PAD_MIN` per pad), then the tempo group folds into `TempoFold`'s
|
||||||
portalled popover, then Grid keeps only its icon. The two row breakpoints
|
portalled popover. That breakpoint is a measured width — move them if controls are added to the row. Every grid control acts
|
||||||
are measured widths — move them if controls are added to the row. Every grid control acts
|
|
||||||
on the marker **governing the playhead**, since a beatgrid is a marker list
|
on the marker **governing the playhead**, since a beatgrid is a marker list
|
||||||
and there is no separate marker selection; see "Beatgrid" below.
|
and there is no separate marker selection; see "Beatgrid" below.
|
||||||
- **One size for loops AND beat jump** (`beatSize`, 1/32–32, persisted as
|
- **One size for loops AND beat jump** (`beatSize`, 1/32–32, persisted as
|
||||||
@@ -1305,7 +1438,7 @@ Two independent apps that talk over HTTP:
|
|||||||
outline (`drawLoop(…, idle)`), so the toggle shows what it would restore.
|
outline (`drawLoop(…, idle)`), so the toggle shows what it would restore.
|
||||||
**‹ › (and ←/→) MOVE an engaged loop by its own length**, Traktor-style,
|
**‹ › (and ←/→) MOVE an engaged loop by its own length**, Traktor-style,
|
||||||
and only jump the playhead when no loop is engaged. The move sets the new
|
and only jump the playhead when no loop is engaged. The move sets the new
|
||||||
loop BEFORE seeking: `PlaybackEngine.seek` honours the loop in force, so
|
loop BEFORE seeking: the deck's seek honours the loop in force, so
|
||||||
seeking first wraps the playhead back into the old loop.
|
seeking first wraps the playhead back into the old loop.
|
||||||
- **Memory cues** (decided 2026-10-16, [the discussion](.claude/discussions/discuss-memory-cues-2026-10-16.md)):
|
- **Memory cues** (decided 2026-10-16, [the discussion](.claude/discussions/discuss-memory-cues-2026-10-16.md)):
|
||||||
Mem mode replaces the pads with `MemoryCueStrip` — chips in TIME order,
|
Mem mode replaces the pads with `MemoryCueStrip` — chips in TIME order,
|
||||||
@@ -1327,8 +1460,8 @@ Two independent apps that talk over HTTP:
|
|||||||
type dropdown or delete button. Rename re-sets the slot with its own start/type/length plus the
|
type dropdown or delete button. Rename re-sets the slot with its own start/type/length plus the
|
||||||
new name, since `set_cue` replaces a slot. A non-editable cue gets the
|
new name, since `set_cue` replaces a slot. A non-editable cue gets the
|
||||||
same menu disabled, not no menu.
|
same menu disabled, not no menu.
|
||||||
Prep libs live in `src/lib/`: `playbackEngine.ts` (Web Audio, seamless loops),
|
Prep libs live in `src/lib/`: `audio/` (the deck's worklet engine:
|
||||||
`scratchEngine.ts` (drag-to-scratch), `waveform.ts` (frequency-colored
|
playback, loops, scratch, varispeed, keylock), `waveform.ts` (frequency-colored
|
||||||
analysis + paint), `beatgrid.ts` (the marker-list beat math — every
|
analysis + paint), `beatgrid.ts` (the marker-list beat math — every
|
||||||
beat/bar/snap/jump calculation goes through it), `cues.ts` (draw
|
beat/bar/snap/jump calculation goes through it), `cues.ts` (draw
|
||||||
cues/loop/beatgrid/cue-point). See "Prep engine" below.
|
cues/loop/beatgrid/cue-point). See "Prep engine" below.
|
||||||
@@ -1369,6 +1502,67 @@ Two independent apps that talk over HTTP:
|
|||||||
Unmeasured: what Traktor leaves after "None" (Konduktor removes the attribute).
|
Unmeasured: what Traktor leaves after "None" (Konduktor removes the attribute).
|
||||||
Carried but deliberately unused until a second adapter
|
Carried but deliberately unused until a second adapter
|
||||||
exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`.
|
exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`.
|
||||||
|
- **`lib/midi/` — MIDI controllers** (decided 2026-11-03,
|
||||||
|
[the discussion](.claude/discussions/discuss-midi-controllers-2026-11-03.md)):
|
||||||
|
MIDI only (no HID), ANY controller, mapped by LEARNING — no shipped
|
||||||
|
mappings — and input only (no LEDs). **Transport**: WKWebView has no Web
|
||||||
|
MIDI, so the shell reads ports with `midir` (`src-tauri/src/midi.rs`:
|
||||||
|
`midi_ports` / `midi_open` / `midi_close`; system messages ignored at the
|
||||||
|
driver; a sender thread per port drains its queue into ONE `Channel`
|
||||||
|
batch, so idle = no delay and a flood coalesces). Measured (2026-11-03,
|
||||||
|
`src-tauri/examples/midi_flood.rs`, a CoreMIDI virtual source): 0 drops
|
||||||
|
or reorders at 250-4000 msg/s, ~1 ms spread. A JS `Channel` cannot be
|
||||||
|
reused once its Rust side is dropped — every open makes a fresh one.
|
||||||
|
`transport.ts` hides that and Web MIDI (`./dev.sh` in Chrome) behind one
|
||||||
|
interface; `useMidi` (mounted in App) polls ports every 1.5 s (midir has
|
||||||
|
no hot-plug events) and keeps mappings in userprefs `midiMappings`.
|
||||||
|
**Model**: `messages.ts` (bytes → note / CC / pitch bend; `SourceKey`
|
||||||
|
`cc:1:33`), `encoding.ts` (button, abs 7/14-bit — CC n + n+32 or pitch
|
||||||
|
bend, a knob's centre exactly 0 — three relative schemes, and ABSOLUTE-
|
||||||
|
position jogs that wrap; `detectEncoding` guesses from what a control sent
|
||||||
|
while learning: relative REPEATS and jitters inside its zones, absolute
|
||||||
|
progresses), `actions.ts` (the vocabulary: deck buttons = the deck keys'
|
||||||
|
actions, plus pitch, jog, jog touch, fast scrub, load, SYNC, MASTER, keylock,
|
||||||
|
loops; mixer; browse / tree; performance mode; `shiftDefault` = the
|
||||||
|
keyboard's Shift meaning), `mapping.ts` (per controller, keyed by SOURCE;
|
||||||
|
each control a normal + a FREE Shift binding; learning REPLACES an
|
||||||
|
action's control in that layer and fills an empty Shift layer with the
|
||||||
|
default). **Encoders on button actions** (beat jump, loop size — common
|
||||||
|
on controllers): learning a button action by TURNING an encoder binds
|
||||||
|
that DIRECTION, a virtual source `cc:1:20+` / `cc:1:20-` (↻ / ↺); each
|
||||||
|
tick fires the action once (up to 8 per message), both directions share
|
||||||
|
the encoder's encoding and decoder, and a plain binding on the same
|
||||||
|
encoder wins only where it has an action for the layer. A CC learned for
|
||||||
|
a button waits 400 ms: one message, or any 0, = a button; several
|
||||||
|
non-zero = a turn (so a two's-complement encoder's 127s are not a press).
|
||||||
|
**`router.ts`**: Shift is a learned control — up to TWO per controller
|
||||||
|
(`Mapping.shifts`, many have one per deck; either held = the Shift layer;
|
||||||
|
the old single `shift` field still loads) (an unbound Shift
|
||||||
|
binding falls back to normal); deck B and the mixer act only in
|
||||||
|
performance mode; positions JUMP (no soft takeover — "the controller
|
||||||
|
always wins"); a held control releases where it was pressed; Learn sees
|
||||||
|
every message first (buttons on the first press — a CC button waits
|
||||||
|
250 ms for a note, since a touch jog sends both; positions after 12
|
||||||
|
messages or 800 ms; notes ignored for a jog; Shift held = the Shift
|
||||||
|
layer). Targets are registered by whoever is mounted (`targets.ts`,
|
||||||
|
cleanup clears only its OWN values: a new view registers before the old
|
||||||
|
one unmounts): PrepStrip's `DeckMidi` per deck (a hardware pitch move and
|
||||||
|
a jog NUDGE release SYNC), App's `load` (the table's highlighted row,
|
||||||
|
loaded PAUSED), TrackTable's `browse` (= ↑/↓), Sidebar's `tree` (Shift +
|
||||||
|
browse: All Tracks + the visible tree; a playlist opens as reached, a
|
||||||
|
folder opens on press). **Jog** (`useDeck`): touch = scratch through the
|
||||||
|
waveform-drag path, target sent straight to the worklet; no touch =
|
||||||
|
nudge (a per-frame bend, also in prep mode) while playing; while paused
|
||||||
|
a turn SCRATCHES too (decided 2026-11-05: grabbed on the first tick,
|
||||||
|
released `JOG_SCRATCH_IDLE_MS` after the last, so a jog without a touch
|
||||||
|
sensor still cues by ear); fast scrub stays a seek; scale `JOG_SEC_PER_TICK` × the mapping's sensitivity. **UI**:
|
||||||
|
Settings ▸ MIDI Controllers… (`MidiSettings`: per controller, Shift, jog
|
||||||
|
sensitivity / fast scrub, every action × Normal / Shift with Learn,
|
||||||
|
encoding + Reversed per binding, Import / Export as
|
||||||
|
`.konduktor-midi.json` through `/api/midi/import|export` — never
|
||||||
|
overwrites) and **Learn on screen** (`MidiLearnOverlay`: controls carry
|
||||||
|
`data-midi-action`; a click ARMS instead of acting). A new on-screen
|
||||||
|
control with a MIDI action should carry the attribute.
|
||||||
- `lib/trackColumns.tsx` — single source of truth for the library table's
|
- `lib/trackColumns.tsx` — single source of truth for the library table's
|
||||||
columns (defs, default widths/visibility/order, the Columns-menu list, the
|
columns (defs, default widths/visibility/order, the Columns-menu list, the
|
||||||
inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation).
|
inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation).
|
||||||
@@ -1403,6 +1597,10 @@ Two independent apps that talk over HTTP:
|
|||||||
```bash
|
```bash
|
||||||
./dev.sh # start both servers (see README for one-time setup)
|
./dev.sh # start both servers (see README for one-time setup)
|
||||||
.\dev.ps1 # the same on Windows (BUILDING-WINDOWS.md)
|
.\dev.ps1 # the same on Windows (BUILDING-WINDOWS.md)
|
||||||
|
./build.sh # desktop app on macOS: sidecar + .app/.dmg
|
||||||
|
# (--skip-sidecar reuses the staged one; other
|
||||||
|
# args go to `tauri build`)
|
||||||
|
.\build.ps1 # the same on Windows
|
||||||
|
|
||||||
# Backend
|
# Backend
|
||||||
cd backend && source .venv/bin/activate
|
cd backend && source .venv/bin/activate
|
||||||
@@ -1420,7 +1618,10 @@ docker build -f server/Dockerfile -t konduktor-server . # from the repo root
|
|||||||
cd frontend
|
cd frontend
|
||||||
npm run dev # dev server (proxies /api -> :8000)
|
npm run dev # dev server (proxies /api -> :8000)
|
||||||
npm run build # tsc -b && vite build — run this to typecheck
|
npm run build # tsc -b && vite build — run this to typecheck
|
||||||
npm run test # vitest — unit tests for src/lib/beatgrid.ts
|
npm run test # vitest — unit tests (src/lib/**/*.test.ts)
|
||||||
|
|
||||||
|
# MIDI without hardware (macOS): a virtual source flooding CC 33 on ch 1
|
||||||
|
cd frontend/src-tauri && cargo run --example midi_flood -- <Hz> <count> <delay s>
|
||||||
```
|
```
|
||||||
|
|
||||||
**Tests:** `cd backend && ./run_tests.sh` (runs against a temp copy of the real
|
**Tests:** `cd backend && ./run_tests.sh` (runs against a temp copy of the real
|
||||||
@@ -1475,7 +1676,8 @@ serialization path.** It enforces:
|
|||||||
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
|
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
|
||||||
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched;
|
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched;
|
||||||
plus the drag-and-drop routes: `/add`'s three `duplicates` modes (`ask`
|
plus the drag-and-drop routes: `/add`'s three `duplicates` modes (`ask`
|
||||||
changes nothing and counts) and `/api/playlists/move` (path id answered,
|
changes nothing and counts), `/remove` (every copy, order kept, `dry_run`
|
||||||
|
counts and changes nothing, 404 unknown) and `/api/playlists/move` (path id answered,
|
||||||
400 into itself, 404 unknown).
|
400 into itself, 404 unknown).
|
||||||
- `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated
|
- `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated
|
||||||
MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset
|
MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset
|
||||||
@@ -1725,6 +1927,30 @@ serialization path.** It enforces:
|
|||||||
none; a levelled copy has its own waveform-cache key; and a file that
|
none; a levelled copy has its own waveform-cache key; and a file that
|
||||||
cannot be levelled (as HE-AAC) is copied unchanged at gain 0 without
|
cannot be levelled (as HE-AAC) is copied unchanged at gain 0 without
|
||||||
failing the export.
|
failing the export.
|
||||||
|
- `test_local_push.py` — pushing into this computer's DJ apps, through the
|
||||||
|
routes: a temp copy of the real collection as the SOURCE (generated MP3s) and
|
||||||
|
ANOTHER as the laptop's collection. A merge removes no line of the user's
|
||||||
|
but the entry / subnode counts; the set's folder holds its tree; cues + a
|
||||||
|
locked grid cross; history commits; an unchanged re-push copies and saves
|
||||||
|
nothing; an edited cue / title reaches the entry (only those two updated);
|
||||||
|
a re-levelled copy is swapped in with FILESIZE following; a user folder with
|
||||||
|
the set's name is left alone; a shared track is one entry and survives one
|
||||||
|
set's removal; a running app 409s; the open library is never a target; a
|
||||||
|
copy failure leaves the collection and folder untouched; overwrite leaves
|
||||||
|
only that set and deletes the other's files. On a temp copy of the local
|
||||||
|
rekordbox library (skipped when absent): merge, backup, a refused removal
|
||||||
|
kept and reported then retried, overwrite with a stale WAL.
|
||||||
|
- `test_traktor_file_block.py` — Traktor's block inside the file, on
|
||||||
|
GENERATED MP3 / M4A / FLAC carrying one that says 175 while the library's
|
||||||
|
grid says 176, with collections built from the empty Traktor skeleton:
|
||||||
|
each format's block removed with everything else kept (audio
|
||||||
|
sample-identical, a foreign PRIV frame, the cover, the ID3 version), a file
|
||||||
|
without one never rewritten; an export's copies lose it while the sources
|
||||||
|
keep it, the manifest records `prepared`, a re-export rewrites nothing, a
|
||||||
|
kept copy from an older export is cleaned in place (same inode), a target
|
||||||
|
without the hook (Rekordbox Export) leaves it and adding Traktor cleans the
|
||||||
|
kept copies; a local push's shared copies and an import's copies lose it,
|
||||||
|
a file added in place is never touched.
|
||||||
- `test_auto_hotcues.py` — Auto Hotcues in three layers: `structure.analyse`
|
- `test_auto_hotcues.py` — Auto Hotcues in three layers: `structure.analyse`
|
||||||
on SYNTHETIC audio with known sections (the intro with a kick is not a drop;
|
on SYNTHETIC audio with known sections (the intro with a kick is not a drop;
|
||||||
no breakdown after the last drop), `plan`'s outcomes and beat-counted offsets
|
no breakdown after the last drop), `plan`'s outcomes and beat-counted offsets
|
||||||
@@ -1797,6 +2023,11 @@ serialization path.** It enforces:
|
|||||||
last-collection and path-mapping helpers lose nothing either; an unreadable
|
last-collection and path-mapping helpers lose nothing either; an unreadable
|
||||||
file is moved aside, not overwritten. Against the old unlocked code it fails
|
file is moved aside, not overwritten. Against the old unlocked code it fails
|
||||||
on the first trial.
|
on the first trial.
|
||||||
|
- `test_midi_mappings.py` — a MIDI mapping to and from a file: never
|
||||||
|
overwrites (`-2`), a name cannot leave the folder, import refuses non-JSON,
|
||||||
|
non-objects, other versions and oversized files, and `/api/fs/list`'s
|
||||||
|
`suffix` lists only mapping files. (The mapping logic itself is the
|
||||||
|
frontend's: `src/lib/midi/*.test.ts`.)
|
||||||
- `test_exports.py` — export sets against a temp copy of the real collection.
|
- `test_exports.py` — export sets against a temp copy of the real collection.
|
||||||
Pins the things that would fail SILENTLY: a live reference picks up a playlist
|
Pins the things that would fail SILENTLY: a live reference picks up a playlist
|
||||||
edited AFTER curation; contents dedupe across playlists and loose tracks; a
|
edited AFTER curation; contents dedupe across playlists and loose tracks; a
|
||||||
@@ -2028,6 +2259,18 @@ frontend at `http://localhost:5173`.
|
|||||||
`ConfirmDialog` by the `ConfirmHost` mounted once in `main.tsx`. `tone` is
|
`ConfirmDialog` by the `ConfirmHost` mounted once in `main.tsx`. `tone` is
|
||||||
`danger` (default, pink) or `primary`. Components that already hold dialog
|
`danger` (default, pink) or `primary`. Components that already hold dialog
|
||||||
state may still render `ConfirmDialog` directly.
|
state may still render `ConfirmDialog` directly.
|
||||||
|
- **Every dialog is a `<Modal>`** (`components/Modal.tsx`; decided 2026-11-02):
|
||||||
|
the portal, backdrop, `aria-modal`, Esc and outside click in ONE place —
|
||||||
|
never a hand-rolled backdrop or a per-dialog Esc listener. `onDismiss` is
|
||||||
|
what the dialog's Cancel / Close (or Hide, while a job runs) does, `null`
|
||||||
|
while that is unavailable (busy): Esc and the backdrop then do nothing. An
|
||||||
|
outside click closes only when the press AND the release are both on the
|
||||||
|
backdrop — a plain `onClick` fires on the common ancestor, so a text
|
||||||
|
selection dragged out of the dialog closed it. Esc reaches only the TOP
|
||||||
|
modal (by opening order) and never while a menu is open. `layer="nested"`
|
||||||
|
= `z-[60]` (a dialog opened from a dialog, QuitGuard). The one exception is
|
||||||
|
`RelocateDialog`'s `backdropDismiss={false}` (Esc only: "Not now" lasts
|
||||||
|
until the library is reopened).
|
||||||
|
|
||||||
## Theme — "dark liquid glass"
|
## Theme — "dark liquid glass"
|
||||||
|
|
||||||
@@ -2052,7 +2295,7 @@ easy to break:
|
|||||||
opened far from the cursor. `.glass`'s blur and tint therefore live on its
|
opened far from the cursor. `.glass`'s blur and tint therefore live on its
|
||||||
`::after` (z-index -1 under `isolation: isolate`), not on the panel.
|
`::after` (z-index -1 under `isolation: isolate`), not on the panel.
|
||||||
- **Every overlay renders through `createPortal(…, document.body)`** — all
|
- **Every overlay renders through `createPortal(…, document.body)`** — all
|
||||||
dialogs, `ContextMenu` and `Toast`. Each `.glass` panel is a stacking context
|
dialogs (via `Modal`), `ContextMenu` and `Toast`. Each `.glass` panel is a stacking context
|
||||||
(`isolation`), so an overlay rendered INSIDE one can never rise above a
|
(`isolation`), so an overlay rendered INSIDE one can never rise above a
|
||||||
neighbouring panel, whatever its z-index: New Export (from the sidebar) sat
|
neighbouring panel, whatever its z-index: New Export (from the sidebar) sat
|
||||||
behind the library, and the deck's Auto Hotcues dialog behind both. One
|
behind the library, and the deck's Auto Hotcues dialog behind both. One
|
||||||
@@ -2124,7 +2367,8 @@ that number and nothing else — everything derives from it:
|
|||||||
`tauri.conf.json` `plugins.updater.pubkey`. **Losing the private key means
|
`tauri.conf.json` `plugins.updater.pubkey`. **Losing the private key means
|
||||||
installed copies can never update themselves again** — it is backed up
|
installed copies can never update themselves again** — it is backed up
|
||||||
outside the repo. A local build without it passes
|
outside the repo. A local build without it passes
|
||||||
`--config src-tauri/tauri.unsigned.conf.json` (`build.ps1` does so itself).
|
`--config src-tauri/tauri.unsigned.conf.json` (`build.sh` / `build.ps1` do
|
||||||
|
so themselves).
|
||||||
- **NOT a source**: `src-tauri/Cargo.toml` `version` is inert Rust crate metadata
|
- **NOT a source**: `src-tauri/Cargo.toml` `version` is inert Rust crate metadata
|
||||||
(Tauri uses the config's `../package.json`); don't treat it as the app version.
|
(Tauri uses the config's `../package.json`); don't treat it as the app version.
|
||||||
|
|
||||||
@@ -2524,6 +2768,18 @@ that number and nothing else — everything derives from it:
|
|||||||
laptop. One computer at a time, with takeover. See "Remote libraries" under
|
laptop. One computer at a time, with takeover. See "Remote libraries" under
|
||||||
Architecture. Not yet: verified on a real TrueNAS (the image is published by
|
Architecture. Not yet: verified on a real TrueNAS (the image is published by
|
||||||
CI's `server-image` job), a web UI served by the server (decided: not now).
|
CI's `server-image` job), a web UI served by the server (decided: not now).
|
||||||
|
- ✅ **Performance mode** (2026-11-03) — a second deck and a mixer to try
|
||||||
|
transitions: stacked waveforms, 3-band isolator, per-channel Filter FX,
|
||||||
|
crossfader, limiter, pitch with Rubber Band keylock, SYNC with a tempo
|
||||||
|
master, a phase meter you can drag to bend. See `lib/audio/`,
|
||||||
|
`components/deck/`, `components/mixer/` and "Prep strip" / "Prep engine";
|
||||||
|
[the discussion](.claude/discussions/discuss-performance-mode-2026-11-02.md).
|
||||||
|
Not yet: headphone cue (decided: not needed), recording the mix.
|
||||||
|
- 🟡 **MIDI controllers** (2026-11-03) — any MIDI controller, mapped by
|
||||||
|
learning, for prep (deck A) and performance mode; see `lib/midi/` under
|
||||||
|
Architecture. Built and unit-tested; not yet checked on real hardware
|
||||||
|
(scratch feel, jog scale) nor on Windows. Not planned for v1: HID
|
||||||
|
controllers, LED output, soft takeover, deck layers.
|
||||||
- ⬜ Serato adapter
|
- ⬜ Serato adapter
|
||||||
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
|
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
|
||||||
|
|
||||||
@@ -2595,19 +2851,102 @@ diff — no COLLECTION splicing needed.
|
|||||||
The prep strip plays every track through the **Web Audio API** (a plain
|
The prep strip plays every track through the **Web Audio API** (a plain
|
||||||
`<audio>` element can't do reverse/arbitrary-rate scratch or seamless loops).
|
`<audio>` element can't do reverse/arbitrary-rate scratch or seamless loops).
|
||||||
|
|
||||||
- `playbackEngine.ts` — an `AudioBufferSourceNode` with a `startOffset`/
|
- **`lib/audio/` — one AudioWorklet per deck** (2026-11-02, the first step of
|
||||||
`startedAt` position model; `getPosition()` reads the AudioContext clock
|
performance mode; [the discussion](.claude/discussions/discuss-performance-mode-2026-11-02.md)).
|
||||||
(high-res → smooth playhead). Seamless loops via native `loopStart`/`loopEnd`;
|
`deckCore.ts` renders a deck block by block: transport, seamless loops, the
|
||||||
`setLoop()` re-anchors position so enabling/disabling a loop doesn't desync.
|
stems in lockstep (ONE position for all), mute/solo as ramped gains,
|
||||||
- `scratchEngine.ts` — a persistent (idle-silent) `ScriptProcessorNode` that,
|
varispeed (cubic interpolation) and scratch (a release coasts and the deck
|
||||||
while dragging the main waveform, plays PCM at a position gliding toward the
|
PLAYS ON BY ITSELF, so there is no gap). **Scratch is rebuilt for sound**
|
||||||
cursor, then coasts with inertia on release.
|
(2026-11-05): the hand's position arrives in STEPS (mouse ~60 Hz, a jog up
|
||||||
- **CRITICAL gotcha**: playing an `AudioBuffer` "acquires the content" in
|
to one per block, bunched by the main thread), and chasing each step with a
|
||||||
Firefox and **detaches** any `getChannelData()` views held elsewhere. The
|
one-pole made the speed swing ±67-83% at that rate — buzzing, with a click
|
||||||
scratch engine therefore **copies** the PCM in `load()` (never holds the
|
each time it caught up (a hard mute at rest). Now the steps are joined into
|
||||||
playback buffer's views). Playback and scratch also run on **separate
|
a line played `handDelay` behind the newest (adapted to their spacing,
|
||||||
`AudioContext`s** — sharing one goes silent after a source has played.
|
6-30 ms), followed by a critically damped spring (`SCRATCH_HZ` 45), so the
|
||||||
- `waveform.ts` — decodes once (buffer reused by both engines, no re-decode),
|
speed is continuous; volume follows speed; above 1x the source is averaged
|
||||||
|
over the span each frame covers (anti-aliasing); targets are RELATIVE to
|
||||||
|
the position given at the grab (`scratchBegin` / `scratchRegrab(sec)`), so a
|
||||||
|
stale main-thread position cannot jump it, and grabbing a playing deck
|
||||||
|
brakes from its speed. Measured (`deckCore.test.ts` "scratch sound"): speed
|
||||||
|
ripple 0 for even steps, 3% for jittery bursts; lag 13.5 ms (a jog every
|
||||||
|
block) to ~30 ms (mouse). `deckProcessor.worklet.ts` wraps it (`?worker&url`, bundled
|
||||||
|
self-contained); `deckEngine.ts` is the main thread's handle, with the old
|
||||||
|
PlaybackEngine's surface: commands are async, so it answers from a model
|
||||||
|
(last report + context clock, `position.ts`) that each command updates at
|
||||||
|
once, and a GENERATION drops reports older than the latest positional
|
||||||
|
command. `context.ts` is the app's ONE AudioContext (never closed; a deck
|
||||||
|
disconnects its own nodes) with a master bus. It replaced an
|
||||||
|
AudioBufferSourceNode for playback plus a ScriptProcessorNode on a SECOND
|
||||||
|
AudioContext for scratch (sharing one went silent in Firefox once a source
|
||||||
|
had played), which left nowhere for a mixer to sit.
|
||||||
|
**Keylock** = Rubber Band R2 in the worklet (`stretcher.ts`,
|
||||||
|
`rubberband.wasm` built by `frontend/rubberband/build.sh` — see its README
|
||||||
|
for why it is OUR build: licence). One stereo stretcher per stem; R3 does not
|
||||||
|
fit 8 on one render thread (measured). After any seek the deck plays
|
||||||
|
varispeed AT ONCE, primes the stretchers over `WARM_QUANTA` blocks aimed at
|
||||||
|
where the playhead will be, and crossfades when aligned — priming 4 stems in
|
||||||
|
one block would be a dropout per hotcue. Aligned within ±3 ms, no drift over
|
||||||
|
a minute (`deckCore.test.ts`, which drives the real `.wasm` in Node). At
|
||||||
|
rate 1 the stretcher is bypassed.
|
||||||
|
**The mixer** (`lib/audio/mixer.ts`, performance mode phase 4): each deck's
|
||||||
|
engine plays into its CHANNEL (`DeckEngine.create(mixer().input(ch))`):
|
||||||
|
GAIN (the state's `trim`: the track's `auto_gain_db` — unless the
|
||||||
|
`useAutoGain` setting is off — + the knob, ±12 dB) →
|
||||||
|
a 3-band ISOLATOR
|
||||||
|
(LR4 crossovers at 250 Hz / 2.5 kHz, the low band through a 2.5 kHz
|
||||||
|
all-pass, so the bands sum flat — measured 0.0000 dB; Web Audio's
|
||||||
|
lowpass/highpass Q is in DB, Butterworth = -3.01, its allpass Q linear) →
|
||||||
|
fader → FILTER FX, POST-fader (decided 2026-11-05: pulling the fader down
|
||||||
|
stops feeding the reverb / delay and their tails ring out rather than
|
||||||
|
being cut with it) (`FilterFx`, decided 2026-11-03 after Traktor's mixer: the
|
||||||
|
FILTER knob always filters — 4-pole, low-pass left / high-pass right, over
|
||||||
|
a RANGE: FULL (to 20 Hz / 20 kHz: a 100 Hz bass -56 dB at full left,
|
||||||
|
measured; one 12 dB stage left it at -28), MUSICAL (150 Hz / 8 kHz) or
|
||||||
|
GENTLE (500 Hz / 2 kHz) — one setting for the Filter alone (default full),
|
||||||
|
another under an effect (default musical: swept to silence the filter
|
||||||
|
would starve the effect; `mixerState.rangeFor`) — and the channel's chosen
|
||||||
|
effect rides with it,
|
||||||
|
fed the FILTERED signal, growing with the knob: Reverb, Delay (sends whose
|
||||||
|
tails ring out — echo- and wash-outs), Bit crusher (replaces the filtered
|
||||||
|
signal), Flanger (a 0.7–7 ms delay swept by a beat-synced LFO, with
|
||||||
|
feedback that deepens with the knob; replaced the Phaser 2026-11-03), or
|
||||||
|
Filter alone. THE MORE FILTER, THE BIGGER THE EFFECT (decided
|
||||||
|
2026-11-03): the delay's length and the flanger's speed step by two at
|
||||||
|
each quarter of the knob (`mixerMath.knobStep` — the settings are the
|
||||||
|
SHORTEST delay and SLOWEST sweep, up to ×8, every step a musical length;
|
||||||
|
measured: the flanger sweeps every 2 / 0.5 / 0.25 s at 15 / 60 / 95% of
|
||||||
|
the knob, 4-beat setting at 120 BPM),
|
||||||
|
and the reverb blends from a short convolver (the setting) into one
|
||||||
|
`REVERB_GROWTH` (3) times as long — two convolvers, since swapping one's
|
||||||
|
impulse cuts its tail (measured: 6 s after a burst -75 dB at 20% of the
|
||||||
|
knob, -54 at 60%). Resonance fades over the last stretch of the sweep (no
|
||||||
|
boom at 20 Hz). Each effect's one parameter is an APP SETTING, not a knob —
|
||||||
|
`mixerState.fx`; all built once and switched by gains) →
|
||||||
|
crossfader (`xfadeGains(x, sharpness)`: each channel fades on a
|
||||||
|
quarter-cosine over the last `xfadeWidth` of the travel — the whole of it
|
||||||
|
at 0, constant power, -3 dB in the middle; 4% at 1, a cut; no dip in the
|
||||||
|
middle above ~0.52) → bus → limiter
|
||||||
|
(DynamicsCompressor at -1.5 dBFS 20:1 — Web Audio adds an automatic
|
||||||
|
MAKE-UP gain, +0.57 dB at -1/20:1, which let two loud decks peak at +0.3
|
||||||
|
dBFS until a gain after it took it back off) → speakers. Channel meters are
|
||||||
|
after the fader and FX, before the crossfader. OUTSIDE performance mode the mixer
|
||||||
|
is BYPASSED (A straight through, B silent, no limiter): prep listening is
|
||||||
|
unchanged. Controls live in `mixerState.ts` (an external store, not
|
||||||
|
persisted; a MIDI mapping would write the same setters); the curves in
|
||||||
|
`mixerMath.ts` (tested). `components/mixer/`: `MixerPanel` (26rem; per
|
||||||
|
channel a 2×2 block — GAIN HI / MID LOW, 40 px knobs — and toward the fader
|
||||||
|
the effect picker over a 48 px FILTER knob, mirrored on B; meters written from
|
||||||
|
one rAF loop, never through React state) and `Controls` (`Knob`,
|
||||||
|
`Fader`: drag, Shift = fine, wheel, double-click resets; not focusable, so
|
||||||
|
the deck keys never land on them). The graph itself was measured offline in
|
||||||
|
Chrome (tones in, levels out) — flat EQ, kills, crossfader, fader, trim,
|
||||||
|
filter and limiter all at their expected values.
|
||||||
|
**The PCM is TRANSFERRED to the worklet** (`waveform.DecodedAudio`, copied
|
||||||
|
out of the AudioBuffer once); the main thread keeps only a mono downmix for
|
||||||
|
the raw waveform. (The Firefox detach gotcha — playing an AudioBuffer
|
||||||
|
detaches `getChannelData()` views — no longer bites: nothing plays an
|
||||||
|
AudioBuffer now.)
|
||||||
|
- `waveform.ts` — decodes once (the PCM goes to the deck's worklet, no re-decode),
|
||||||
splits into 3 bands via `OfflineAudioContext` biquads, and paints them as
|
splits into 3 bands via `OfflineAudioContext` biquads, and paints them as
|
||||||
**three layers**, not one blended colour per column: bass (orange) first and
|
**three layers**, not one blended colour per column: bass (orange) first and
|
||||||
tallest, then mids (violet) and highs (cyan) with a `screen` blend — no green,
|
tallest, then mids (violet) and highs (cyan) with a `screen` blend — no green,
|
||||||
|
|||||||
@@ -608,3 +608,8 @@ class OneLibraryAdapter:
|
|||||||
|
|
||||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||||
raise Unsupported("OneLibrary has no beatgrid lock")
|
raise Unsupported("OneLibrary has no beatgrid lock")
|
||||||
|
|
||||||
|
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues:
|
||||||
|
# Only a DJ app's library on this computer is pushed into; a stick is
|
||||||
|
# filled by an export.
|
||||||
|
raise Unsupported("A OneLibrary drive is filled by an export, not a push")
|
||||||
@@ -21,7 +21,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
|
from ...core.adapter import InvalidCommand, NotFound, Unsupported, local_audio_facts
|
||||||
from ...core.capabilities import Capabilities
|
from ...core.capabilities import Capabilities
|
||||||
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
|
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
|
||||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||||
@@ -460,6 +460,30 @@ class RekordboxAdapter:
|
|||||||
self._store.delete_grid(track_id)
|
self._store.delete_grid(track_id)
|
||||||
return self._refresh_cues(track_id)
|
return self._refresh_cues(track_id)
|
||||||
|
|
||||||
|
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues:
|
||||||
|
"""Clear the track's cues and grid, then place `cues` as `add_tracks`
|
||||||
|
does (`_place_imported_cues`). Rekordbox has no grid lock, so
|
||||||
|
`grid_locked` is not carried; a cue on the reserved `Kind=4` (shown,
|
||||||
|
not editable) is left where it is."""
|
||||||
|
self._require_writable("Replacing cues")
|
||||||
|
current = self.track_cues(track_id)
|
||||||
|
if current is None:
|
||||||
|
raise NotFound(f"Track not found: {track_id}")
|
||||||
|
for cue in current.cues:
|
||||||
|
if not cue.editable:
|
||||||
|
continue
|
||||||
|
if cue.role == "hotcue" and cue.slot is not None:
|
||||||
|
self._store.delete_cue(track_id, cue.slot)
|
||||||
|
elif cue.id:
|
||||||
|
self._store.delete_memory_cue(track_id, cue.id)
|
||||||
|
markers = list(cues.grid_markers or [])
|
||||||
|
if markers:
|
||||||
|
self._store.replace_grid(track_id, self._markers_from(markers))
|
||||||
|
elif current.grid_markers:
|
||||||
|
self._store.delete_grid(track_id)
|
||||||
|
self._place_imported_cues(track_id, cues)
|
||||||
|
return self._refresh_cues(track_id)
|
||||||
|
|
||||||
# ---- save -------------------------------------------------------------
|
# ---- save -------------------------------------------------------------
|
||||||
@property
|
@property
|
||||||
def dirty(self) -> bool:
|
def dirty(self) -> bool:
|
||||||
|
|||||||
@@ -280,6 +280,11 @@ class RemoteAdapter:
|
|||||||
def set_grid_lock(self, track_id, locked):
|
def set_grid_lock(self, track_id, locked):
|
||||||
return self._call("set_grid_lock", track_id=track_id, locked=locked)
|
return self._call("set_grid_lock", track_id=track_id, locked=locked)
|
||||||
|
|
||||||
|
def replace_cues(self, track_id, cues):
|
||||||
|
# Never travels (`remote_protocol.EXCLUDED`): a push targets a library
|
||||||
|
# on THIS computer.
|
||||||
|
raise Unsupported("A library held by a server is not a push target")
|
||||||
|
|
||||||
# ---- adding tracks ------------------------------------------------------------------
|
# ---- adding tracks ------------------------------------------------------------------
|
||||||
def upload_audio(self, source: Path, folder: str, name: str, *, progress=None) -> Path:
|
def upload_audio(self, source: Path, folder: str, name: str, *, progress=None) -> Path:
|
||||||
"""Send `source` into `folder` on the server; the path it landed at (a
|
"""Send `source` into `folder` on the server; the path it landed at (a
|
||||||
|
|||||||
@@ -459,6 +459,39 @@ class TraktorAdapter:
|
|||||||
self._store.set_lock(track_id, locked)
|
self._store.set_lock(track_id, locked)
|
||||||
return self._refresh(track_id)
|
return self._refresh(track_id)
|
||||||
|
|
||||||
|
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues:
|
||||||
|
"""Clear the entry's prep, then replay `cues` exactly as `add_tracks`
|
||||||
|
does (`_apply_imported_cues`), so an updated entry and a new one cannot
|
||||||
|
differ. `delete_grid` takes the paired companion cues with it."""
|
||||||
|
current = self.track_cues(track_id)
|
||||||
|
if current is None:
|
||||||
|
raise NotFound(f"Track not found: {track_id}")
|
||||||
|
with _translate():
|
||||||
|
if current.grid_markers:
|
||||||
|
self._store.delete_grid(track_id)
|
||||||
|
# One at a time, re-reading between: a memory cue's id is derived
|
||||||
|
# from its content and its rank among cues at the same START, so a
|
||||||
|
# deletion can renumber the next one.
|
||||||
|
for _ in range(len(self.track_cues(track_id).cues)):
|
||||||
|
self._refresh(track_id)
|
||||||
|
left = self.track_cues(track_id).cues
|
||||||
|
cue = next((c for c in left if c.slot is not None or c.id), None)
|
||||||
|
if cue is None:
|
||||||
|
break
|
||||||
|
if cue.slot is not None:
|
||||||
|
self._store.delete_hotcue(track_id, cue.slot)
|
||||||
|
else:
|
||||||
|
self._store.delete_memory_cue(track_id, cue.id)
|
||||||
|
if current.grid_locked and not cues.grid_locked:
|
||||||
|
self._store.set_lock(track_id, False)
|
||||||
|
self._refresh(track_id)
|
||||||
|
if current.grid_locked and cues.grid_locked:
|
||||||
|
# Already locked: `_apply_imported_cues` would lock it again and
|
||||||
|
# move LOCK_MODIFICATION_TIME for nothing.
|
||||||
|
cues = cues.model_copy(update={"grid_locked": False})
|
||||||
|
self._apply_imported_cues(track_id, cues)
|
||||||
|
return self._refresh(track_id)
|
||||||
|
|
||||||
# ---- audio / paths ----------------------------------------------------
|
# ---- audio / paths ----------------------------------------------------
|
||||||
def audio_path(self, track_id: str):
|
def audio_path(self, track_id: str):
|
||||||
return self._store.audio_path(track_id)
|
return self._store.audio_path(track_id)
|
||||||
@@ -479,6 +512,15 @@ class TraktorAdapter:
|
|||||||
track uploaded there is stored as that computer would have stored it."""
|
track uploaded there is stored as that computer would have stored it."""
|
||||||
self._store.set_write_stored_paths(enabled)
|
self._store.set_write_stored_paths(enabled)
|
||||||
|
|
||||||
|
def prepare_copied_audio(self, path: Path) -> bool:
|
||||||
|
"""OPTIONAL: ready a file the importer just COPIED for this library —
|
||||||
|
Traktor's own block removed (`file_block`), which Traktor would
|
||||||
|
otherwise restore over the entry's grid. Never called for a file
|
||||||
|
added in place."""
|
||||||
|
from . import file_block
|
||||||
|
|
||||||
|
return file_block.strip(path)
|
||||||
|
|
||||||
def unresolved_path_groups(self) -> list[PathGroup]:
|
def unresolved_path_groups(self) -> list[PathGroup]:
|
||||||
return self._store.unresolved_path_groups()
|
return self._store.unresolved_path_groups()
|
||||||
|
|
||||||
|
|||||||
@@ -35,8 +35,9 @@ import logging
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from ...core.adapter import NewTrack
|
from ...core.adapter import NewTrack
|
||||||
from ...core.export import ExportPayload, WrittenLibrary
|
from ...core.export import OTHER_PLAYLIST, ExportPayload, WrittenLibrary, write_playlist_tree
|
||||||
from .adapter import TraktorAdapter
|
from .adapter import TraktorAdapter
|
||||||
|
from . import file_block
|
||||||
from .capabilities import capabilities_for
|
from .capabilities import capabilities_for
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
@@ -56,11 +57,6 @@ SKELETON = (
|
|||||||
"</INDEXING>\n</NML>\n"
|
"</INDEXING>\n</NML>\n"
|
||||||
)
|
)
|
||||||
|
|
||||||
#: Loose tracks — added individually rather than through a playlist — would
|
|
||||||
#: otherwise be reachable only by search in the exported library.
|
|
||||||
OTHER_PLAYLIST = "Other"
|
|
||||||
|
|
||||||
|
|
||||||
class TraktorExporter:
|
class TraktorExporter:
|
||||||
platform = "traktor"
|
platform = "traktor"
|
||||||
menu_order = 20
|
menu_order = 20
|
||||||
@@ -73,6 +69,12 @@ class TraktorExporter:
|
|||||||
#: analysis, which overwrites only ANALYZED_DB).
|
#: analysis, which overwrites only ANALYZED_DB).
|
||||||
writes_auto_gain = True
|
writes_auto_gain = True
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def prepare_copy(path: Path) -> bool:
|
||||||
|
"""Remove Traktor's own block from a copy (`file_block`): left in, it
|
||||||
|
is restored over this entry's grid when Traktor opens the collection."""
|
||||||
|
return file_block.strip(path)
|
||||||
|
|
||||||
def capabilities(self):
|
def capabilities(self):
|
||||||
"""What a Traktor library can hold — answered with no library to read.
|
"""What a Traktor library can hold — answered with no library to read.
|
||||||
|
|
||||||
@@ -119,35 +121,5 @@ class TraktorExporter:
|
|||||||
"""Recreate the tree — at the top level, or with `payload.root_folder`
|
"""Recreate the tree — at the top level, or with `payload.root_folder`
|
||||||
under one folder named after the export (None = the top level)."""
|
under one folder named after the export (None = the top level)."""
|
||||||
root = adapter.create_folder(payload.name) if payload.root_folder else None
|
root = adapter.create_folder(payload.name) if payload.root_folder else None
|
||||||
folders: dict[tuple[str, ...], str | None] = {(): root}
|
write_playlist_tree(adapter, payload.playlists, [t.source_id for t in payload.tracks],
|
||||||
|
moved, root)
|
||||||
for playlist in payload.playlists:
|
|
||||||
parent = self._folder_for(adapter, folders, tuple(playlist.folders), root)
|
|
||||||
node_id = adapter.create_playlist(playlist.name, parent)
|
|
||||||
entries = [moved[t] for t in playlist.track_ids if t in moved]
|
|
||||||
if entries:
|
|
||||||
adapter.set_playlist_entries(node_id, entries)
|
|
||||||
|
|
||||||
loose = self._loose(payload, moved)
|
|
||||||
if loose:
|
|
||||||
node_id = adapter.create_playlist(OTHER_PLAYLIST, root)
|
|
||||||
adapter.set_playlist_entries(node_id, loose)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str | None) -> str | None:
|
|
||||||
"""Create (once) the folder chain a playlist sits under, and return it."""
|
|
||||||
for depth in range(1, len(path) + 1):
|
|
||||||
branch = path[:depth]
|
|
||||||
if branch not in folders:
|
|
||||||
folders[branch] = adapter.create_folder(branch[-1], folders[branch[:-1]])
|
|
||||||
return folders.get(path, root)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _loose(payload: ExportPayload, moved: dict) -> list[str]:
|
|
||||||
"""Tracks no exported playlist accounts for, in payload order."""
|
|
||||||
in_playlists = {t for p in payload.playlists for t in p.track_ids}
|
|
||||||
return [
|
|
||||||
moved[t.source_id]
|
|
||||||
for t in payload.tracks
|
|
||||||
if t.source_id not in in_playlists and t.source_id in moved
|
|
||||||
]
|
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"""Traktor's own block INSIDE an audio file, and removing it from a copy.
|
||||||
|
|
||||||
|
Traktor writes a binary block of its analysis into every file it tags — the
|
||||||
|
same `DMRT` chunk tree in each format, stored where the format allows:
|
||||||
|
|
||||||
|
- MP4 (`.m4a`, stem files): the `ilst` atom `NITR`
|
||||||
|
- ID3 (MP3, AIFF, WAV): a `PRIV` frame owned by `TRAKTOR4`
|
||||||
|
- Vorbis comments (FLAC, Ogg): the field `traktor4`
|
||||||
|
|
||||||
|
It holds a BPM (`HBPM`), the cues (`CUEP`), the audio id, transients, tags.
|
||||||
|
Measured in Traktor 4.5 (2026-10-24, 2MUCH / Alone (Vip)): on an entry it did
|
||||||
|
not write itself — no MODIFIED_DATE, as every entry Konduktor creates — Traktor
|
||||||
|
re-reads the file and takes the block's BPM over the collection's, LOCK or not,
|
||||||
|
keeping the anchor. A grid fixed after Traktor last wrote the block (in
|
||||||
|
Konduktor, or in Traktor without a tag write) is reverted on every export.
|
||||||
|
|
||||||
|
Giving the entry a MODIFIED_DATE later than the file stops that, but Traktor
|
||||||
|
then skips the file altogether, cover art included. Giving it the block's
|
||||||
|
AUDIO_ID changes nothing. Removing the block from the copy does both: Traktor
|
||||||
|
imports the file as new — art, file facts and analysis from the file; BPM,
|
||||||
|
grid, lock and cues from the entry — and writes a fresh, correct block itself
|
||||||
|
when the track is first loaded. A stale `TBPM`/`tmpo` tag is ignored.
|
||||||
|
|
||||||
|
Only ever applied to a COPY Konduktor wrote. A file the user's library
|
||||||
|
references in place is the user's, and is never touched.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
#: The ID3 PRIV owner and the Vorbis field name Traktor writes the block under.
|
||||||
|
_PRIV_OWNER = "TRAKTOR4"
|
||||||
|
_VORBIS_FIELD = "traktor4"
|
||||||
|
#: The MP4 atom. mutagen keeps it among the atoms it could not parse — or, in
|
||||||
|
#: some files, parses it into an ordinary key; both are checked.
|
||||||
|
_MP4_ATOM = "NITR"
|
||||||
|
|
||||||
|
|
||||||
|
def has_block(path: Path) -> bool:
|
||||||
|
"""Whether the file carries Traktor's block. False for anything unreadable."""
|
||||||
|
audio = _open(path)
|
||||||
|
return audio is not None and bool(_remove(audio, dry_run=True))
|
||||||
|
|
||||||
|
|
||||||
|
def strip(path: Path) -> bool:
|
||||||
|
"""Remove Traktor's block from `path`, in place; True if it held one.
|
||||||
|
|
||||||
|
Everything else in the file is kept: other tags, cover, the stem box, the
|
||||||
|
audio. A file without a block is not rewritten at all. A file that cannot
|
||||||
|
be read or written is left as it is — a copy that still carries the block
|
||||||
|
is the old behaviour, never a failed export — and the reason is logged.
|
||||||
|
"""
|
||||||
|
audio = _open(path)
|
||||||
|
if audio is None or not _remove(audio, dry_run=False):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
version = getattr(audio.tags, "version", None)
|
||||||
|
if version is not None and _is_id3(audio):
|
||||||
|
# Keep the file's own ID3 version: nothing else in it is changing.
|
||||||
|
audio.save(v2_version=3 if version[1] == 3 else 4)
|
||||||
|
else:
|
||||||
|
audio.save()
|
||||||
|
except Exception as ex: # noqa: BLE001 — see the docstring
|
||||||
|
log.warning("could not remove Traktor's block from %s: %s", path, ex)
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _open(path: Path):
|
||||||
|
try:
|
||||||
|
import mutagen
|
||||||
|
|
||||||
|
audio = mutagen.File(path)
|
||||||
|
except Exception as ex: # noqa: BLE001 — an unreadable file has no block we can see
|
||||||
|
log.debug("cannot read tags of %s: %s", path, ex)
|
||||||
|
return None
|
||||||
|
if audio is None or audio.tags is None:
|
||||||
|
return None
|
||||||
|
return audio
|
||||||
|
|
||||||
|
|
||||||
|
def _is_id3(audio) -> bool:
|
||||||
|
from mutagen.id3 import ID3
|
||||||
|
|
||||||
|
return isinstance(audio.tags, ID3)
|
||||||
|
|
||||||
|
|
||||||
|
def _remove(audio, *, dry_run: bool) -> int:
|
||||||
|
"""How many block entries `audio`'s tags hold, removing them unless
|
||||||
|
`dry_run`. Never saves."""
|
||||||
|
from mutagen.mp4 import MP4Tags
|
||||||
|
|
||||||
|
tags = audio.tags
|
||||||
|
found = 0
|
||||||
|
if isinstance(tags, MP4Tags):
|
||||||
|
failed = getattr(tags, "_failed_atoms", {})
|
||||||
|
if _MP4_ATOM in failed:
|
||||||
|
found += 1
|
||||||
|
if not dry_run:
|
||||||
|
del failed[_MP4_ATOM]
|
||||||
|
if _MP4_ATOM in tags:
|
||||||
|
found += 1
|
||||||
|
if not dry_run:
|
||||||
|
del tags[_MP4_ATOM]
|
||||||
|
elif _is_id3(audio):
|
||||||
|
keys = [k for k, frame in tags.items()
|
||||||
|
if k.startswith("PRIV:") and getattr(frame, "owner", None) == _PRIV_OWNER]
|
||||||
|
found += len(keys)
|
||||||
|
if not dry_run:
|
||||||
|
for k in keys:
|
||||||
|
del tags[k]
|
||||||
|
elif hasattr(tags, "keys"): # Vorbis comments: case-insensitive field names
|
||||||
|
keys = [k for k in tags.keys() if k.lower() == _VORBIS_FIELD]
|
||||||
|
found += len(keys)
|
||||||
|
if not dry_run:
|
||||||
|
for k in keys:
|
||||||
|
del tags[k]
|
||||||
|
return found
|
||||||
@@ -349,6 +349,12 @@ class LibraryAdapter(Protocol):
|
|||||||
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues: ...
|
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues: ...
|
||||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
|
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
|
||||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
|
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
|
||||||
|
# Make a track's prep EXACTLY `cues` — its hot cues, memory cues, grid and
|
||||||
|
# lock — placed as `add_tracks` would place them on a new entry (a taken or
|
||||||
|
# out-of-bank pad moves, else becomes a memory cue). What was there goes
|
||||||
|
# first, grid companions included. A push into a DJ app's library uses it
|
||||||
|
# to bring a track it added earlier up to date with the source.
|
||||||
|
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues: ...
|
||||||
|
|
||||||
# ---- commands: memory cues --------------------------------------------
|
# ---- commands: memory cues --------------------------------------------
|
||||||
# Cues on no pad, addressed by `CuePoint.id`. Gated on `cues.memory_cues`.
|
# Cues on no pad, addressed by `CuePoint.id`. Gated on `cues.memory_cues`.
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""Is a DJ app running on this computer right now?
|
||||||
|
|
||||||
|
Asked before a push writes into the app's own library, which must not happen
|
||||||
|
under a running app: Traktor writes `collection.nml` back when it QUITS, so a
|
||||||
|
push made while it runs is silently undone, and rekordbox holds `master.db`
|
||||||
|
open. Answered from the process list (`psutil`), by executable name:
|
||||||
|
|
||||||
|
* rekordbox — exactly `rekordbox` (pyrekordbox's own test, minus `.exe`). Its
|
||||||
|
helpers (`rekordboxAgent`, `rb_http_server`, `edb_streamd`) are other names,
|
||||||
|
and `rekordboxAgent` runs whenever rekordbox is installed, so a prefix test
|
||||||
|
would refuse forever.
|
||||||
|
* Traktor — any name starting with `traktor`: the macOS executable is
|
||||||
|
`Traktor Pro 4` (read from the 4.5 bundle, 2026-10-20); the Windows one is
|
||||||
|
not measured, and a prefix covers `Traktor.exe` and `Traktor Pro 4.exe`
|
||||||
|
alike. Konduktor's own processes start with `konduktor`, not `traktor`.
|
||||||
|
|
||||||
|
A process list that cannot be read answers "not running": this is a guard
|
||||||
|
against a mistake, and refusing every push on a locked-down machine would make
|
||||||
|
the feature unusable rather than safe.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _names() -> list[str]:
|
||||||
|
try:
|
||||||
|
import psutil
|
||||||
|
except ImportError: # the server image does not ship it, and never pushes
|
||||||
|
return []
|
||||||
|
out = []
|
||||||
|
try:
|
||||||
|
for proc in psutil.process_iter(["name"]):
|
||||||
|
name = proc.info.get("name")
|
||||||
|
if name:
|
||||||
|
out.append(os.path.splitext(name)[0].lower())
|
||||||
|
except Exception as ex: # noqa: BLE001 — see the module docstring
|
||||||
|
log.warning("could not read the process list: %s", ex)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _matches(platform: str, name: str) -> bool:
|
||||||
|
if platform == "traktor":
|
||||||
|
return name.startswith("traktor")
|
||||||
|
if platform == "rekordbox":
|
||||||
|
return name == "rekordbox"
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def running(platforms: list[str]) -> set[str]:
|
||||||
|
"""Which of `platforms` (platform ids) have their app running now."""
|
||||||
|
names = _names()
|
||||||
|
return {p for p in platforms if any(_matches(p, n) for n in names)}
|
||||||
@@ -119,6 +119,40 @@ class ExportPayload:
|
|||||||
default=lambda message, step=None, of=None: None, repr=False)
|
default=lambda message, step=None, of=None: None, repr=False)
|
||||||
|
|
||||||
|
|
||||||
|
#: The playlist an export's LOOSE tracks (in no exported playlist) land in.
|
||||||
|
OTHER_PLAYLIST = "Other"
|
||||||
|
|
||||||
|
|
||||||
|
def write_playlist_tree(adapter, playlists: list[ExportPlaylist], track_ids: list[str],
|
||||||
|
moved: dict[str, str], root: str | None) -> None:
|
||||||
|
"""Recreate `playlists` under `root` (None = the top level) through the
|
||||||
|
generic playlist commands: each folder chain once, each playlist with the
|
||||||
|
entries `moved` maps its SOURCE ids to, and the tracks of `track_ids` no
|
||||||
|
playlist accounts for in an "Other" playlist. Shared by the Traktor writer
|
||||||
|
and the push into a DJ app's library, which builds the same tree inside
|
||||||
|
the set's own folder."""
|
||||||
|
folders: dict[tuple[str, ...], str | None] = {(): root}
|
||||||
|
|
||||||
|
def folder_for(path: tuple[str, ...]) -> str | None:
|
||||||
|
for depth in range(1, len(path) + 1):
|
||||||
|
branch = path[:depth]
|
||||||
|
if branch not in folders:
|
||||||
|
folders[branch] = adapter.create_folder(branch[-1], folders[branch[:-1]])
|
||||||
|
return folders.get(path, root)
|
||||||
|
|
||||||
|
for playlist in playlists:
|
||||||
|
node_id = adapter.create_playlist(playlist.name, folder_for(tuple(playlist.folders)))
|
||||||
|
entries = [moved[t] for t in playlist.track_ids if t in moved]
|
||||||
|
if entries:
|
||||||
|
adapter.set_playlist_entries(node_id, entries)
|
||||||
|
|
||||||
|
in_playlists = {t for p in playlists for t in p.track_ids}
|
||||||
|
loose = [moved[t] for t in track_ids if t not in in_playlists and t in moved]
|
||||||
|
if loose:
|
||||||
|
node_id = adapter.create_playlist(OTHER_PLAYLIST, root)
|
||||||
|
adapter.set_playlist_entries(node_id, loose)
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class WrittenLibrary:
|
class WrittenLibrary:
|
||||||
"""What an exporter put on disk.
|
"""What an exporter put on disk.
|
||||||
@@ -158,6 +192,14 @@ class LibraryExporter(Protocol):
|
|||||||
#: destination, so this is a warning the UI raises, not a refusal: the other
|
#: destination, so this is a warning the UI raises, not a refusal: the other
|
||||||
#: targets in the same export are still perfectly valid in any folder.
|
#: targets in the same export are still perfectly valid in any folder.
|
||||||
drive_root: bool = False
|
drive_root: bool = False
|
||||||
|
#: Optional, and not a protocol member so a target needs nothing to opt
|
||||||
|
#: out: `prepare_copy(path) -> bool` readies one audio COPY for this
|
||||||
|
#: library, in place, before its size is recorded or a library refers to
|
||||||
|
#: it, returning True if it changed the file. Called once per copy and
|
||||||
|
#: target (the runner records which targets have prepared it, so a kept
|
||||||
|
#: copy is prepared when a target joins the set). Traktor's removes its
|
||||||
|
#: own block from the file (`adapters/traktor/file_block.py`). Never
|
||||||
|
#: called on a file a library references in place.
|
||||||
|
|
||||||
def capabilities(self) -> Capabilities:
|
def capabilities(self) -> Capabilities:
|
||||||
"""What this target can represent — STATIC, with no library to read."""
|
"""What this target can represent — STATIC, with no library to read."""
|
||||||
|
|||||||
@@ -126,6 +126,9 @@ class PlannedTrack:
|
|||||||
level_outcome: str | None = None
|
level_outcome: str | None = None
|
||||||
#: The run needs this source's loudness (it normalises, or writes auto gain).
|
#: The run needs this source's loudness (it normalises, or writes auto gain).
|
||||||
needs_loudness: bool = False
|
needs_loudness: bool = False
|
||||||
|
#: The targets whose `prepare_copy` the copy has been through (sorted
|
||||||
|
#: platforms; recorded in the manifest, missing = none).
|
||||||
|
prepared: tuple[str, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -321,9 +324,43 @@ def _record(planned: PlannedTrack, copy: Path) -> dict:
|
|||||||
# The level the copy was written at: a copy kept by a later export must
|
# The level the copy was written at: a copy kept by a later export must
|
||||||
# be at the level THAT export wants (missing = 0, every older manifest).
|
# be at the level THAT export wants (missing = 0, every older manifest).
|
||||||
"gain_db": planned.gain_db,
|
"gain_db": planned.gain_db,
|
||||||
|
# The targets that have prepared the copy (`prepare_copy`): a kept copy
|
||||||
|
# is prepared for any target not listed (missing = none, every older
|
||||||
|
# manifest — which is how existing exports lose Traktor's block).
|
||||||
|
"prepared": list(planned.prepared),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_copy(path: Path, exporters, done=()) -> tuple[str, ...]:
|
||||||
|
"""Run each target's optional `prepare_copy` on one copy, in place,
|
||||||
|
skipping the targets in `done` (already prepared it). Returns every target
|
||||||
|
that now has — `done` included, so a target leaving the set does not make
|
||||||
|
a later one prepare the copy twice."""
|
||||||
|
ready = set(done)
|
||||||
|
for exporter in exporters:
|
||||||
|
hook = getattr(exporter, "prepare_copy", None)
|
||||||
|
if hook is None or exporter.platform in ready:
|
||||||
|
continue
|
||||||
|
hook(path)
|
||||||
|
ready.add(exporter.platform)
|
||||||
|
return tuple(sorted(ready))
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_kept(path: Path, planned: PlannedTrack, record: dict, exporters) -> dict:
|
||||||
|
"""Prepare a KEPT copy for any target that has not yet (an export made
|
||||||
|
before a target's `prepare_copy` existed, or a target new to the set), and
|
||||||
|
the record that now describes it — the copy's size and mtime as they are
|
||||||
|
after, so a rollback's manifest still matches the file."""
|
||||||
|
done = record.get("prepared")
|
||||||
|
done = tuple(done) if isinstance(done, list) else ()
|
||||||
|
planned.prepared = prepare_copy(path, exporters, done)
|
||||||
|
if planned.prepared == tuple(sorted(done)):
|
||||||
|
return record
|
||||||
|
st = path.stat()
|
||||||
|
return {**record, "copy_size": st.st_size, "copy_mtime_ns": st.st_mtime_ns,
|
||||||
|
"prepared": list(planned.prepared)}
|
||||||
|
|
||||||
|
|
||||||
def _previous_copies(destination: Path) -> dict[str, tuple[Path, dict]]:
|
def _previous_copies(destination: Path) -> dict[str, tuple[Path, dict]]:
|
||||||
"""The last export's copies, by SOURCE path — not by where they sit, since
|
"""The last export's copies, by SOURCE path — not by where they sit, since
|
||||||
adding a track from another folder moves the shared root and with it every
|
adding a track from another folder moves the shared root and with it every
|
||||||
@@ -599,6 +636,10 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
|
|||||||
if reused:
|
if reused:
|
||||||
handle.progress(message=f"Keeping {len(reused)} unchanged track{'' if len(reused) == 1 else 's'}…")
|
handle.progress(message=f"Keeping {len(reused)} unchanged track{'' if len(reused) == 1 else 's'}…")
|
||||||
_move_kept(destination, reused, kept)
|
_move_kept(destination, reused, kept)
|
||||||
|
for planned in reused:
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
path = Path(planned.destination)
|
||||||
|
kept[path] = prepare_kept(path, planned, kept[path], exporters)
|
||||||
|
|
||||||
payload_tracks: list[ExportTrack] = []
|
payload_tracks: list[ExportTrack] = []
|
||||||
for planned in items:
|
for planned in items:
|
||||||
@@ -617,30 +658,8 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
|
|||||||
done += n
|
done += n
|
||||||
handle.progress(done=done)
|
handle.progress(done=done)
|
||||||
|
|
||||||
# The file to READ: on this machine that is the source itself;
|
write_copy(adapter, planned, partial, handle, advance)
|
||||||
# on a library held by a server, a downloaded copy of it.
|
planned.prepared = prepare_copy(partial, exporters)
|
||||||
local = adapter.audio_path(planned.track_id) or planned.source_path
|
|
||||||
levelled = False
|
|
||||||
if planned.gain_db:
|
|
||||||
from .core import level_edit
|
|
||||||
|
|
||||||
handle.progress(message=f"Normalising {planned.title} ({planned.gain_db:+.1f} dB)")
|
|
||||||
try:
|
|
||||||
level_edit.apply(local, partial, planned.gain_db)
|
|
||||||
handle.raise_if_cancelled()
|
|
||||||
# A copy carried to a gig must be the source at the
|
|
||||||
# gain, nothing else: decode both and compare.
|
|
||||||
level_edit.verify(local, partial, planned.gain_db)
|
|
||||||
levelled = True
|
|
||||||
advance(planned.size)
|
|
||||||
except level_edit.LevelEditError as ex:
|
|
||||||
# Only the file says some things (HE-AAC in an .m4a):
|
|
||||||
# such a copy goes as it is, never fails the export.
|
|
||||||
log.warning("copying %s unlevelled: %s", planned.title, ex)
|
|
||||||
partial.unlink(missing_ok=True)
|
|
||||||
planned.gain_db, planned.level_outcome = 0.0, "unsupported"
|
|
||||||
if not levelled:
|
|
||||||
copy_file(local, partial, handle, advance)
|
|
||||||
os.replace(partial, target)
|
os.replace(partial, target)
|
||||||
payload_tracks.append(
|
payload_tracks.append(
|
||||||
ExportTrack(
|
ExportTrack(
|
||||||
@@ -748,6 +767,33 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def write_copy(adapter, planned: PlannedTrack, partial: Path, handle: JobHandle, advance) -> None:
|
||||||
|
"""Write one copy of `planned`'s source to `partial`: at its planned gain
|
||||||
|
(decode-verified), else byte for byte. A file that cannot be levelled
|
||||||
|
(HE-AAC in an .m4a — only the file says so) is copied as it is and its
|
||||||
|
plan says so (`gain_db` 0, outcome "unsupported"); never a failure."""
|
||||||
|
# The file to READ: on this machine that is the source itself; on a
|
||||||
|
# library held by a server, a downloaded copy of it.
|
||||||
|
local = adapter.audio_path(planned.track_id) or planned.source_path
|
||||||
|
if planned.gain_db:
|
||||||
|
from .core import level_edit
|
||||||
|
|
||||||
|
handle.progress(message=f"Normalising {planned.title} ({planned.gain_db:+.1f} dB)")
|
||||||
|
try:
|
||||||
|
level_edit.apply(local, partial, planned.gain_db)
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
# A copy carried to a gig must be the source at the gain, nothing
|
||||||
|
# else: decode both and compare.
|
||||||
|
level_edit.verify(local, partial, planned.gain_db)
|
||||||
|
advance(planned.size)
|
||||||
|
return
|
||||||
|
except level_edit.LevelEditError as ex:
|
||||||
|
log.warning("copying %s unlevelled: %s", planned.title, ex)
|
||||||
|
partial.unlink(missing_ok=True)
|
||||||
|
planned.gain_db, planned.level_outcome = 0.0, "unsupported"
|
||||||
|
copy_file(local, partial, handle, advance)
|
||||||
|
|
||||||
|
|
||||||
def _move_kept(destination: Path, reused: list[PlannedTrack], kept: dict[Path, dict]) -> None:
|
def _move_kept(destination: Path, reused: list[PlannedTrack], kept: dict[Path, dict]) -> None:
|
||||||
"""Rename each kept copy to where this export puts it — instant on one drive.
|
"""Rename each kept copy to where this export puts it — instant on one drive.
|
||||||
|
|
||||||
@@ -794,11 +840,13 @@ def _fingerprint(planned: PlannedTrack) -> str:
|
|||||||
return fingerprint(source, planned.size, planned.mtime_ns)
|
return fingerprint(source, planned.size, planned.mtime_ns)
|
||||||
|
|
||||||
|
|
||||||
def _measure_missing(adapter, built: ExportPlan, handle: JobHandle, *, store, level: Level | None) -> None:
|
def _measure_missing(adapter, built: ExportPlan, handle: JobHandle, *, store, level: Level | None,
|
||||||
|
previous: dict[str, tuple[Path, dict]] | None = None) -> None:
|
||||||
"""Measure the sources the run needs a loudness for and has none, store
|
"""Measure the sources the run needs a loudness for and has none, store
|
||||||
each, then settle their copies' levels and which previous copies can be
|
each, then settle their copies' levels and which previous copies can be
|
||||||
kept. Before anything at the destination changes, so a cancel here
|
kept (`previous`: the copies on record, by source path — by default the
|
||||||
leaves the previous export as it was."""
|
destination's manifest). Before anything at the destination changes, so a
|
||||||
|
cancel here leaves the previous export as it was."""
|
||||||
todo = [t for t in built.exportable if t.needs_loudness and t.loudness is None]
|
todo = [t for t in built.exportable if t.needs_loudness and t.loudness is None]
|
||||||
if not todo or store is None:
|
if not todo or store is None:
|
||||||
return
|
return
|
||||||
@@ -821,7 +869,7 @@ def _measure_missing(adapter, built: ExportPlan, handle: JobHandle, *, store, le
|
|||||||
store.put(fact, values)
|
store.put(fact, values)
|
||||||
if level is not None:
|
if level is not None:
|
||||||
set_level(planned, level)
|
set_level(planned, level)
|
||||||
assign_reuse(built, _previous_copies(Path(built.destination)))
|
assign_reuse(built, previous if previous is not None else _previous_copies(Path(built.destination)))
|
||||||
|
|
||||||
|
|
||||||
def _cover(adapter, track_id: str):
|
def _cover(adapter, track_id: str):
|
||||||
|
|||||||
@@ -44,6 +44,10 @@ from . import paths
|
|||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
#: A set's `kind` and a "computer" set's `mode` (see `ExportSet`).
|
||||||
|
KINDS = ("folder", "computer")
|
||||||
|
MODES = ("merge", "overwrite")
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class ExportSet:
|
class ExportSet:
|
||||||
@@ -56,6 +60,16 @@ class ExportSet:
|
|||||||
|
|
||||||
id: str
|
id: str
|
||||||
name: str
|
name: str
|
||||||
|
#: Where the set goes. "folder": a folder or drive the export writes a
|
||||||
|
#: library into (`destination`). "computer": PUSHED into the DJ apps'
|
||||||
|
#: own libraries on this computer (`local_push.py`) — `targets` names the
|
||||||
|
#: apps, `destination` is unused, and which file each app's library is
|
||||||
|
#: lives in this computer's prefs, not here (a remote library's sets are
|
||||||
|
#: kept on its server, but the paths belong to whichever laptop pushes).
|
||||||
|
kind: str = "folder"
|
||||||
|
#: A "computer" set's push: "merge" adds and updates only what this set
|
||||||
|
#: put there; "overwrite" replaces the whole library with this set.
|
||||||
|
mode: str = "merge"
|
||||||
#: Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
|
#: Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
|
||||||
#: empty; ordered as the user ticked them, which is the order they are written.
|
#: empty; ordered as the user ticked them, which is the order they are written.
|
||||||
targets: list[str] = field(default_factory=lambda: ["traktor"])
|
targets: list[str] = field(default_factory=lambda: ["traktor"])
|
||||||
@@ -194,6 +208,8 @@ def _load(library_id: str) -> dict[str, ExportSet]:
|
|||||||
out[set_id] = ExportSet(
|
out[set_id] = ExportSet(
|
||||||
id=set_id,
|
id=set_id,
|
||||||
name=values.get("name") or "Untitled",
|
name=values.get("name") or "Untitled",
|
||||||
|
kind=values.get("kind") if values.get("kind") in KINDS else "folder",
|
||||||
|
mode=values.get("mode") if values.get("mode") in MODES else "merge",
|
||||||
targets=_targets(values),
|
targets=_targets(values),
|
||||||
destination=values.get("destination") or "",
|
destination=values.get("destination") or "",
|
||||||
playlist_ids=list(values.get("playlist_ids") or []),
|
playlist_ids=list(values.get("playlist_ids") or []),
|
||||||
@@ -251,6 +267,8 @@ def destination_conflict(library_id: str, destination: str, *, ignore: str | Non
|
|||||||
if not target:
|
if not target:
|
||||||
return None
|
return None
|
||||||
for existing in _load(library_id).values():
|
for existing in _load(library_id).values():
|
||||||
|
if existing.kind != "folder":
|
||||||
|
continue # a push has no destination folder to clear
|
||||||
if existing.id != ignore and _normalise(existing.destination) == target:
|
if existing.id != ignore and _normalise(existing.destination) == target:
|
||||||
return existing.name
|
return existing.name
|
||||||
return None
|
return None
|
||||||
@@ -266,12 +284,15 @@ def _normalise(destination: str) -> str:
|
|||||||
# ---- writing -----------------------------------------------------------------
|
# ---- writing -----------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def create(library_id: str, *, name: str, targets: list[str], destination: str) -> ExportSet:
|
def create(library_id: str, *, name: str, targets: list[str], destination: str,
|
||||||
|
kind: str = "folder", mode: str = "merge") -> ExportSet:
|
||||||
sets = _load(library_id)
|
sets = _load(library_id)
|
||||||
now = time.time()
|
now = time.time()
|
||||||
created = ExportSet(
|
created = ExportSet(
|
||||||
id=uuid.uuid4().hex,
|
id=uuid.uuid4().hex,
|
||||||
name=name.strip() or "Untitled",
|
name=name.strip() or "Untitled",
|
||||||
|
kind=kind if kind in KINDS else "folder",
|
||||||
|
mode=mode if mode in MODES else "merge",
|
||||||
targets=list(dict.fromkeys(targets)),
|
targets=list(dict.fromkeys(targets)),
|
||||||
destination=destination,
|
destination=destination,
|
||||||
created=now,
|
created=now,
|
||||||
@@ -292,6 +313,10 @@ def update(library_id: str, set_id: str, **fields) -> ExportSet | None:
|
|||||||
for key in ("name", "destination"):
|
for key in ("name", "destination"):
|
||||||
if key in fields and fields[key] is not None:
|
if key in fields and fields[key] is not None:
|
||||||
setattr(found, key, fields[key])
|
setattr(found, key, fields[key])
|
||||||
|
if fields.get("kind") in KINDS:
|
||||||
|
found.kind = fields["kind"]
|
||||||
|
if fields.get("mode") in MODES:
|
||||||
|
found.mode = fields["mode"]
|
||||||
if fields.get("targets"):
|
if fields.get("targets"):
|
||||||
found.targets = list(dict.fromkeys(fields["targets"]))
|
found.targets = list(dict.fromkeys(fields["targets"]))
|
||||||
for key in ("lock_grids", "normalise", "auto_gain"):
|
for key in ("lock_grids", "normalise", "auto_gain"):
|
||||||
|
|||||||
@@ -347,6 +347,10 @@ def run(
|
|||||||
# a folder on the server, instead of copied here. Nothing can be left in
|
# a folder on the server, instead of copied here. Nothing can be left in
|
||||||
# place — the server cannot see this computer's files.
|
# place — the server cannot see this computer's files.
|
||||||
uploads = not places and uploads_audio(dest)
|
uploads = not places and uploads_audio(dest)
|
||||||
|
# The library's optional readying of a file copied FOR it (Traktor: its
|
||||||
|
# own block removed from the copy). Only copies made here: never a file
|
||||||
|
# added in place, nor an upload (written on the server).
|
||||||
|
prepare = getattr(dest, "prepare_copied_audio", None)
|
||||||
if uploads and reference and not getattr(source, "on_library_host", False):
|
if uploads and reference and not getattr(source, "on_library_host", False):
|
||||||
raise ValueError("A remote library cannot reference files on this computer")
|
raise ValueError("A remote library cannot reference files on this computer")
|
||||||
if not reference and not places and not uploads:
|
if not reference and not places and not uploads:
|
||||||
@@ -404,6 +408,8 @@ def run(
|
|||||||
handle.progress(message=f"Copying {planned.title}")
|
handle.progress(message=f"Copying {planned.title}")
|
||||||
created.append(target) # registered BEFORE the write, so a cancel
|
created.append(target) # registered BEFORE the write, so a cancel
|
||||||
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
|
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
|
||||||
|
if prepare is not None:
|
||||||
|
prepare(target)
|
||||||
copied.append((planned, target))
|
copied.append((planned, target))
|
||||||
|
|
||||||
handle.raise_if_cancelled()
|
handle.raise_if_cancelled()
|
||||||
|
|||||||
@@ -0,0 +1,979 @@
|
|||||||
|
"""Pushing an export set into the DJ apps' own libraries on THIS computer.
|
||||||
|
|
||||||
|
An export set of kind "computer" is not written into a folder: its tracks and
|
||||||
|
playlists go straight into the Traktor collection and/or rekordbox library this
|
||||||
|
computer's DJ apps use — the collection a DJ keeps on a server, prepared there,
|
||||||
|
and pushed to the laptop that plays the gig. Decided 2026-10-20
|
||||||
|
(`.claude/discussions/discuss-export-to-local-library-2026-10-20.md`).
|
||||||
|
|
||||||
|
## Two modes, chosen on the set
|
||||||
|
|
||||||
|
**Merge** (the default) adds and updates ONLY what this set put there: the
|
||||||
|
user's own tracks and playlists are never touched, and several sets can push
|
||||||
|
into one library side by side. Each push brings the set's tracks up to date
|
||||||
|
from the source (the source wins: a cue added on the laptop to a pushed track
|
||||||
|
is replaced), rebuilds the set's playlists inside ONE folder named after the
|
||||||
|
set, and removes from the library what left the set — unless another set still
|
||||||
|
holds it, or rekordbox refuses (a track in its History, Sampler, …), in which
|
||||||
|
case it stays, is reported, and the next push tries again.
|
||||||
|
|
||||||
|
**Overwrite** replaces the whole library with this set: the export writers
|
||||||
|
build a fresh one in app-data and it is swapped in, as a user would swap an
|
||||||
|
exported `collection.nml` / `master.db` by hand. Every other set that had been
|
||||||
|
pushed into that library is gone from it afterwards.
|
||||||
|
|
||||||
|
## One shared audio folder
|
||||||
|
|
||||||
|
Every pushed file lives under one folder (default `~/Music/Konduktor`), at its
|
||||||
|
SOURCE path minus the anchor — stable across sets and pushes, so a track in
|
||||||
|
two sets is one file and one entry in the DJ app. (`common_dir_prefix`, which
|
||||||
|
an export mirrors from, moves whenever a set changes; in a shared folder that
|
||||||
|
would leave the same track at two paths.) Being shared, the files can have only
|
||||||
|
one level, so Normalise lives with the folder in the app's settings, not on a
|
||||||
|
set. A file is deleted when no set in any library still holds it.
|
||||||
|
|
||||||
|
## What Konduktor remembers
|
||||||
|
|
||||||
|
A ledger in app-data (`local_push/ledger.json`, Konduktor's own data, never
|
||||||
|
written into a library): per library (by `library_id`) and set, which local
|
||||||
|
track each source track became, the copy it uses, a hash of the prep last
|
||||||
|
pushed (an unchanged track costs nothing on a re-push), and the set's folder;
|
||||||
|
per audio folder, the facts of each copy (the export manifest's record), so an
|
||||||
|
unchanged file is never copied again.
|
||||||
|
|
||||||
|
## Safety
|
||||||
|
|
||||||
|
A push refuses while the DJ app runs (Traktor writes its collection back on
|
||||||
|
quit, undoing the push; rekordbox holds its database open), checked again
|
||||||
|
just before each save. It never writes the library open in Konduktor itself,
|
||||||
|
nor a cloud-synced rekordbox library. Before writing, a Traktor collection
|
||||||
|
gets a version-history baseline and each push is committed to it (restored by
|
||||||
|
opening that collection in Konduktor); a rekordbox library is copied to
|
||||||
|
app-data, the last 10 kept. Audio is copied FIRST and the library written
|
||||||
|
LAST: a cancel before any save leaves every library untouched and removes the
|
||||||
|
files this run placed. A copy that REPLACES a file a library already plays
|
||||||
|
waits under a temporary name until a library has been saved.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from . import __version__, exports, history, library_id, paths, prefs
|
||||||
|
from .core import apps_running, registry
|
||||||
|
from .core import export as core_export
|
||||||
|
from .core.adapter import AudioChange, NewTrack, Unsupported
|
||||||
|
from .core.analysis_cache import AnalysisCache
|
||||||
|
from .core.export import ExportPayload, ExportPlaylist, ExportTrack, write_playlist_tree
|
||||||
|
from .core.level_plan import shifted
|
||||||
|
from .exporter import (
|
||||||
|
PARTIAL_SUFFIX,
|
||||||
|
ExportPlan,
|
||||||
|
Level,
|
||||||
|
PlannedTrack,
|
||||||
|
_cover,
|
||||||
|
_fingerprint,
|
||||||
|
_folder_paths,
|
||||||
|
_locked,
|
||||||
|
_measure_missing,
|
||||||
|
_record,
|
||||||
|
assign_reuse,
|
||||||
|
prepare_copy,
|
||||||
|
prepare_kept,
|
||||||
|
set_level,
|
||||||
|
write_copy,
|
||||||
|
)
|
||||||
|
from .importer import SPACE_HEADROOM, _existing_files, _key, free_bytes
|
||||||
|
from .jobs import JobHandle
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
#: The DJ apps a set can be pushed into, in the order they are offered.
|
||||||
|
PLATFORMS = ("traktor", "rekordbox")
|
||||||
|
JOB_KIND = "local-push"
|
||||||
|
_BACKUPS_KEPT = 10
|
||||||
|
|
||||||
|
#: Why a library cannot be pushed into. Facts; the UI words them.
|
||||||
|
NOT_FOUND = "not_found"
|
||||||
|
OPEN_IN_KONDUKTOR = "open_in_konduktor"
|
||||||
|
CLOUD_SYNCED = "cloud_synced"
|
||||||
|
UNREADABLE = "unreadable"
|
||||||
|
#: Why a push cannot run.
|
||||||
|
BLOCKED_NO_TARGET = "no_target"
|
||||||
|
#: Every library the set names is missing on THIS computer.
|
||||||
|
BLOCKED_NONE_HERE = "no_library_here"
|
||||||
|
BLOCKED_EMPTY = "nothing_to_push"
|
||||||
|
BLOCKED_UNAVAILABLE = "target_unavailable"
|
||||||
|
BLOCKED_RUNNING = "app_running"
|
||||||
|
|
||||||
|
_LOCK = threading.RLock()
|
||||||
|
|
||||||
|
|
||||||
|
class PushRefused(Exception):
|
||||||
|
"""A push that must not go ahead (a DJ app started, a library became
|
||||||
|
unwritable). The message is for the user."""
|
||||||
|
|
||||||
|
|
||||||
|
# ---- where things are ---------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _local_dir() -> Path:
|
||||||
|
return paths.app_data_dir() / "local_push"
|
||||||
|
|
||||||
|
|
||||||
|
def audio_root() -> Path:
|
||||||
|
"""The shared folder pushed audio lives in: the setting, else the user's
|
||||||
|
Music folder (platformdirs — hardcoding `~/Music` is wrong somewhere on
|
||||||
|
every OS) + `Konduktor`."""
|
||||||
|
raw = prefs.load_prefs().get("localAudioRoot")
|
||||||
|
if isinstance(raw, str) and raw.strip():
|
||||||
|
return Path(raw).expanduser()
|
||||||
|
import platformdirs
|
||||||
|
|
||||||
|
return Path(platformdirs.user_music_dir()) / "Konduktor"
|
||||||
|
|
||||||
|
|
||||||
|
def level() -> Level | None:
|
||||||
|
"""The shared folder's Normalise level, or None when it is off. The
|
||||||
|
measure / target / ceiling default to Normalize's app settings."""
|
||||||
|
p = prefs.load_prefs()
|
||||||
|
if not p.get("localNormalise"):
|
||||||
|
return None
|
||||||
|
raw = p.get("localLevel") if isinstance(p.get("localLevel"), dict) else {}
|
||||||
|
try:
|
||||||
|
measure = raw.get("measure", p.get("levelMeasure", "lufs"))
|
||||||
|
return Level(measure=measure if measure in ("lufs", "rms") else "lufs",
|
||||||
|
target=float(raw.get("target", p.get("levelTarget", -9.0))),
|
||||||
|
ceiling=float(raw.get("ceiling", p.get("levelCeiling", -1.0))))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return Level()
|
||||||
|
|
||||||
|
|
||||||
|
def _override(platform: str) -> Path | None:
|
||||||
|
raw = prefs.load_prefs().get("localLibraries")
|
||||||
|
value = raw.get(platform) if isinstance(raw, dict) else None
|
||||||
|
return Path(value).expanduser() if isinstance(value, str) and value.strip() else None
|
||||||
|
|
||||||
|
|
||||||
|
def library_path(platform: str) -> tuple[Path | None, bool]:
|
||||||
|
"""(the library a push into `platform` writes, whether it was DETECTED).
|
||||||
|
The setting wins; else the platform's own detection, best first (Traktor:
|
||||||
|
the newest `Traktor x.y` folder)."""
|
||||||
|
chosen = _override(platform)
|
||||||
|
if chosen is not None:
|
||||||
|
return chosen, False
|
||||||
|
for found in registry.detect_for(platform):
|
||||||
|
raw = found.get("path") if isinstance(found, dict) else getattr(found, "path", None)
|
||||||
|
if raw and Path(raw).is_file():
|
||||||
|
return Path(raw), True
|
||||||
|
return None, True
|
||||||
|
|
||||||
|
|
||||||
|
def _same(a: Path | None, b: Path | None) -> bool:
|
||||||
|
if a is None or b is None:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return Path(a).resolve() == Path(b).resolve()
|
||||||
|
except OSError:
|
||||||
|
return str(a) == str(b)
|
||||||
|
|
||||||
|
|
||||||
|
# Opening a library to ask whether it can be written costs a parse; the answer
|
||||||
|
# only changes with the file, so it is kept per path + mtime. Only a platform
|
||||||
|
# whose library can be read-only is opened for it: rekordbox (cloud sync). A
|
||||||
|
# Traktor collection is always writable, and parsing 8,000 entries to hear so
|
||||||
|
# would hold up the dialog that asks.
|
||||||
|
_MAY_BE_READ_ONLY = {"rekordbox"}
|
||||||
|
_WRITABLE: dict[tuple[str, int], str | None] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _unwritable(path: Path, platform: str) -> str | None:
|
||||||
|
"""Why `platform`'s library at `path` cannot be written, or None."""
|
||||||
|
try:
|
||||||
|
stamp = (str(path), path.stat().st_mtime_ns)
|
||||||
|
except OSError:
|
||||||
|
return NOT_FOUND
|
||||||
|
if stamp in _WRITABLE:
|
||||||
|
return _WRITABLE[stamp]
|
||||||
|
reason: str | None
|
||||||
|
adapter = None
|
||||||
|
try:
|
||||||
|
driver = registry.driver_for(path) # the cheap probe: is it that format at all?
|
||||||
|
if driver.platform != platform:
|
||||||
|
reason = UNREADABLE # e.g. a master.db chosen as the Traktor collection
|
||||||
|
elif driver.platform not in _MAY_BE_READ_ONLY:
|
||||||
|
reason = None
|
||||||
|
else:
|
||||||
|
adapter = driver.open(path)
|
||||||
|
caps = adapter.capabilities()
|
||||||
|
if caps.writable:
|
||||||
|
reason = None
|
||||||
|
else:
|
||||||
|
reason = CLOUD_SYNCED if caps.readonly_cause == "cloud_synced" else UNREADABLE
|
||||||
|
except Exception as ex: # noqa: BLE001 — anything that will not open is not a target
|
||||||
|
log.warning("cannot open %s to push into: %s", path, ex)
|
||||||
|
reason = UNREADABLE
|
||||||
|
finally:
|
||||||
|
_close(adapter)
|
||||||
|
_WRITABLE[stamp] = reason
|
||||||
|
return reason
|
||||||
|
|
||||||
|
|
||||||
|
def _close(adapter) -> None:
|
||||||
|
close = getattr(adapter, "close", None)
|
||||||
|
if close is not None:
|
||||||
|
try:
|
||||||
|
close()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
log.warning("closing a pushed-into library failed", exc_info=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _display_name(platform: str) -> str:
|
||||||
|
try:
|
||||||
|
return registry.driver_by_platform(platform).display_name
|
||||||
|
except registry.LibraryNotSupported:
|
||||||
|
return platform
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LocalLibrary:
|
||||||
|
"""One DJ app's library on this computer, as a push target."""
|
||||||
|
|
||||||
|
platform: str
|
||||||
|
name: str
|
||||||
|
path: str | None
|
||||||
|
detected: bool
|
||||||
|
#: Why it cannot be pushed into (`NOT_FOUND`, `OPEN_IN_KONDUKTOR`,
|
||||||
|
#: `CLOUD_SYNCED`, `UNREADABLE`), or None.
|
||||||
|
blocked: str | None = None
|
||||||
|
running: bool = False
|
||||||
|
|
||||||
|
def as_dict(self) -> dict:
|
||||||
|
return dict(self.__dict__)
|
||||||
|
|
||||||
|
|
||||||
|
def local_libraries(open_path: Path | None, platforms=PLATFORMS) -> list[LocalLibrary]:
|
||||||
|
"""The push targets this computer has, each with why it cannot be used."""
|
||||||
|
running = apps_running.running(list(platforms))
|
||||||
|
out = []
|
||||||
|
for platform in platforms:
|
||||||
|
path, detected = library_path(platform)
|
||||||
|
lib = LocalLibrary(platform=platform, name=_display_name(platform),
|
||||||
|
path=str(path) if path else None, detected=detected,
|
||||||
|
running=platform in running)
|
||||||
|
if path is None or not path.is_file():
|
||||||
|
lib.blocked = NOT_FOUND
|
||||||
|
elif _same(path, open_path):
|
||||||
|
# Its edits are the open session's; a push would race them.
|
||||||
|
lib.blocked = OPEN_IN_KONDUKTOR
|
||||||
|
else:
|
||||||
|
lib.blocked = _unwritable(path, platform)
|
||||||
|
out.append(lib)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---- the ledger ----------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _ledger_path() -> Path:
|
||||||
|
return _local_dir() / "ledger.json"
|
||||||
|
|
||||||
|
|
||||||
|
def _read_ledger() -> dict:
|
||||||
|
data = paths.read_json(_ledger_path(), {})
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
data = {}
|
||||||
|
data.setdefault("libraries", {})
|
||||||
|
data.setdefault("audio", {})
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def _write_ledger(doc: dict) -> None:
|
||||||
|
paths.write_json(_ledger_path(), doc)
|
||||||
|
|
||||||
|
|
||||||
|
def _rel_for(source: Path) -> str:
|
||||||
|
"""Where `source` sits under the shared folder: its whole path minus the
|
||||||
|
anchor (`/Volumes/Music/a.mp3` -> `Volumes/Music/a.mp3`, `D:\\x.mp3` ->
|
||||||
|
`D/x.mp3`). Never collides, and never moves when a set changes."""
|
||||||
|
text = str(source).replace("\\", "/")
|
||||||
|
if len(text) >= 2 and text[1] == ":":
|
||||||
|
text = text[0] + text[2:]
|
||||||
|
return text.lstrip("/")
|
||||||
|
|
||||||
|
|
||||||
|
def _owned(doc: dict) -> set[str]:
|
||||||
|
"""Every copy (by `rel`) some set in some library still holds."""
|
||||||
|
out = set()
|
||||||
|
for lib in doc["libraries"].values():
|
||||||
|
for entry in (lib.get("sets") or {}).values():
|
||||||
|
for rec in (entry.get("tracks") or {}).values():
|
||||||
|
if rec.get("rel"):
|
||||||
|
out.add(rec["rel"])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---- planning -------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class TargetPlan:
|
||||||
|
platform: str
|
||||||
|
name: str
|
||||||
|
path: str | None
|
||||||
|
blocked: str | None = None
|
||||||
|
running: bool = False
|
||||||
|
#: Tracks this set has not pushed into this library before.
|
||||||
|
add: int = 0
|
||||||
|
#: Tracks it has: kept as they are, or brought up to date where changed.
|
||||||
|
already: int = 0
|
||||||
|
#: Tracks that left the set since the last push (removed from the library
|
||||||
|
#: unless another set holds them, or rekordbox refuses).
|
||||||
|
remove: int = 0
|
||||||
|
#: Overwrite: the other sets pushed into this library, which it removes.
|
||||||
|
wipes_sets: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def skipped(self) -> bool:
|
||||||
|
"""Not on this computer, so passed over rather than blocking: a set's
|
||||||
|
targets are shared by every computer that opens the library (a
|
||||||
|
remote's sets live on its server), and one with only Traktor must
|
||||||
|
still push a Traktor + rekordbox set."""
|
||||||
|
return self.blocked == NOT_FOUND
|
||||||
|
|
||||||
|
def as_dict(self) -> dict:
|
||||||
|
return {**self.__dict__, "skipped": self.skipped}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PushPlan:
|
||||||
|
#: The audio, planned as an export into the shared folder: one
|
||||||
|
#: `PlannedTrack` per track, `destination` = its copy there, `reuse` set
|
||||||
|
#: where the copy on record is still good.
|
||||||
|
audio: ExportPlan
|
||||||
|
playlists: list[ExportPlaylist]
|
||||||
|
targets: list[TargetPlan]
|
||||||
|
mode: str = "merge"
|
||||||
|
blocked: str | None = None
|
||||||
|
#: The copies on record before this push, by source path (for `reuse`).
|
||||||
|
previous: dict = field(default_factory=dict)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def tracks(self) -> list[PlannedTrack]:
|
||||||
|
return self.audio.tracks
|
||||||
|
|
||||||
|
@property
|
||||||
|
def active(self) -> list[TargetPlan]:
|
||||||
|
"""The targets this push writes: every one found on this computer."""
|
||||||
|
return [t for t in self.targets if not t.skipped]
|
||||||
|
|
||||||
|
def as_dict(self) -> dict:
|
||||||
|
audio = self.audio
|
||||||
|
free = free_bytes(audio.destination) if audio.destination else None
|
||||||
|
need = audio.total_bytes
|
||||||
|
counts: dict[str, int] = {}
|
||||||
|
for t in audio.exportable:
|
||||||
|
if t.level_outcome:
|
||||||
|
counts[t.level_outcome] = counts.get(t.level_outcome, 0) + 1
|
||||||
|
return {
|
||||||
|
"mode": self.mode,
|
||||||
|
"tracks": len(audio.tracks),
|
||||||
|
"pushable": len(audio.exportable),
|
||||||
|
"unchanged": audio.unchanged,
|
||||||
|
"missing": [t.title for t in audio.tracks if t.missing],
|
||||||
|
"playlists": [p.name for p in self.playlists],
|
||||||
|
"total_bytes": need,
|
||||||
|
"audio_root": str(audio.destination),
|
||||||
|
"free_bytes": free,
|
||||||
|
"enough_space": None if free is None else free >= need + SPACE_HEADROOM,
|
||||||
|
"normalised": sum(1 for t in audio.exportable if t.gain_db),
|
||||||
|
"level_counts": counts,
|
||||||
|
"to_measure": sum(1 for t in audio.exportable if t.needs_loudness and t.loudness is None),
|
||||||
|
"targets": [t.as_dict() for t in self.targets],
|
||||||
|
"blocked": self.blocked,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def plan(adapter, export_set, *, store=None, level: Level | None = None,
|
||||||
|
auto_gain: bool = False, open_path: Path | None = None) -> PushPlan:
|
||||||
|
"""What a push of `export_set` would do now. Reads only — neither the
|
||||||
|
target libraries (their state is the ledger's, checked again by the run)
|
||||||
|
nor any audio file."""
|
||||||
|
root = audio_root()
|
||||||
|
built = ExportPlan(destination=root)
|
||||||
|
doc = _read_ledger()
|
||||||
|
records = doc["audio"].get(str(root)) or {}
|
||||||
|
previous = {r["source"]: (root / rel, r) for rel, r in records.items()
|
||||||
|
if isinstance(r, dict) and isinstance(r.get("source"), str)}
|
||||||
|
|
||||||
|
resolved = exports.resolve(adapter, export_set)
|
||||||
|
tracks = [t for t in (adapter.track(i) for i in resolved.track_ids) if t is not None]
|
||||||
|
facts = adapter.audio_facts([t.id for t in tracks])
|
||||||
|
wants_loudness = store is not None and (level is not None or auto_gain)
|
||||||
|
entries = store.get([f.key for f in facts.values() if f is not None]) if wants_loudness else {}
|
||||||
|
for track in tracks:
|
||||||
|
fact = facts.get(track.id)
|
||||||
|
source = Path(fact.key) if fact is not None else None
|
||||||
|
planned = PlannedTrack(
|
||||||
|
track_id=track.id,
|
||||||
|
title=track.title or (source.name if source else track.id),
|
||||||
|
source_path=source,
|
||||||
|
destination=(root / _rel_for(source)) if source else None,
|
||||||
|
size=fact.size if fact else 0,
|
||||||
|
mtime_ns=fact.mtime_ns if fact else 0,
|
||||||
|
missing=fact is None,
|
||||||
|
needs_loudness=fact is not None and wants_loudness,
|
||||||
|
)
|
||||||
|
if planned.needs_loudness:
|
||||||
|
entry = entries.get(fact.key)
|
||||||
|
planned.loudness = entry.values if entry is not None and not entry.stale(fact) else None
|
||||||
|
if fact is not None and level is not None:
|
||||||
|
set_level(planned, level)
|
||||||
|
built.tracks.append(planned)
|
||||||
|
assign_reuse(built, previous)
|
||||||
|
|
||||||
|
folders = _folder_paths(adapter)
|
||||||
|
playlists = [ExportPlaylist(name=p.name, track_ids=list(p.track_ids), folders=folders.get(p.id, []))
|
||||||
|
for p in resolved.playlists if not p.missing and p.track_ids]
|
||||||
|
|
||||||
|
pushable = {t.track_id for t in built.exportable}
|
||||||
|
targets = []
|
||||||
|
known = {lib.platform: lib for lib in local_libraries(open_path, [
|
||||||
|
t for t in export_set.targets if t in PLATFORMS])}
|
||||||
|
for platform in export_set.targets:
|
||||||
|
lib = known.get(platform)
|
||||||
|
if lib is None:
|
||||||
|
targets.append(TargetPlan(platform=platform, name=_display_name(platform), path=None,
|
||||||
|
blocked=NOT_FOUND))
|
||||||
|
continue
|
||||||
|
target = TargetPlan(platform=platform, name=lib.name, path=lib.path,
|
||||||
|
blocked=lib.blocked, running=lib.running)
|
||||||
|
lid = library_id.read_sidecar(Path(lib.path)) if lib.path else None
|
||||||
|
sets = (doc["libraries"].get(lid) or {}).get("sets") or {} if lid else {}
|
||||||
|
mine = (sets.get(export_set.id) or {}).get("tracks") or {}
|
||||||
|
target.add = sum(1 for t in pushable if t not in mine)
|
||||||
|
target.already = sum(1 for t in pushable if t in mine)
|
||||||
|
target.remove = sum(1 for t in mine if t not in pushable)
|
||||||
|
if export_set.mode == "overwrite":
|
||||||
|
target.wipes_sets = sorted(s.get("name") or "Untitled"
|
||||||
|
for sid, s in sets.items() if sid != export_set.id)
|
||||||
|
targets.append(target)
|
||||||
|
|
||||||
|
out = PushPlan(audio=built, playlists=playlists, targets=targets, mode=export_set.mode,
|
||||||
|
previous=previous)
|
||||||
|
if not targets:
|
||||||
|
out.blocked = BLOCKED_NO_TARGET
|
||||||
|
elif not out.active:
|
||||||
|
out.blocked = BLOCKED_NONE_HERE
|
||||||
|
elif not built.exportable:
|
||||||
|
out.blocked = BLOCKED_EMPTY
|
||||||
|
elif any(t.blocked for t in out.active):
|
||||||
|
out.blocked = BLOCKED_UNAVAILABLE
|
||||||
|
elif any(t.running for t in out.active):
|
||||||
|
out.blocked = BLOCKED_RUNNING
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---- running --------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _partial(target: Path) -> Path:
|
||||||
|
return target.with_name(target.name + PARTIAL_SUFFIX)
|
||||||
|
|
||||||
|
|
||||||
|
def _jsonable(value):
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
dump = getattr(value, "model_dump", None)
|
||||||
|
if dump is not None:
|
||||||
|
return dump()
|
||||||
|
if hasattr(value, "__dict__"):
|
||||||
|
return dict(value.__dict__)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
_PREP_FIELDS = ("title", "artist", "album", "genre", "label", "remixer", "producer", "mix",
|
||||||
|
"comment", "comment2", "release_date", "rating", "key_wheel", "key_mode", "color")
|
||||||
|
_METADATA_FIELDS = ("title", "artist", "album", "genre", "label", "remixer", "producer", "mix",
|
||||||
|
"comment", "comment2", "release_date", "rating")
|
||||||
|
|
||||||
|
|
||||||
|
def _prep_hash(item: ExportTrack) -> str:
|
||||||
|
"""What a re-push compares: the track's own fields, its cues and grid
|
||||||
|
(lock included) and the auto gain it would get — not the file, whose
|
||||||
|
copy is checked by its own facts."""
|
||||||
|
blob = {
|
||||||
|
"track": {k: getattr(item.track, k, None) for k in _PREP_FIELDS},
|
||||||
|
"cues": _jsonable(item.cues),
|
||||||
|
"loudness": _jsonable(item.loudness),
|
||||||
|
"gain_db": round(item.gain_db, 4),
|
||||||
|
}
|
||||||
|
return hashlib.sha256(json.dumps(blob, sort_keys=True, default=str).encode()).hexdigest()[:24]
|
||||||
|
|
||||||
|
|
||||||
|
def _checkpoint(handle: JobHandle):
|
||||||
|
def checkpoint(message: str, step: int | None = None, of: int | None = None) -> None:
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
if step is not None and of:
|
||||||
|
handle.progress(done=step - 1, total=of, unit="tracks", message=message)
|
||||||
|
else:
|
||||||
|
handle.progress(message=message)
|
||||||
|
return checkpoint
|
||||||
|
|
||||||
|
|
||||||
|
def _refuse_if_running(platform: str) -> None:
|
||||||
|
if apps_running.running([platform]):
|
||||||
|
raise PushRefused(f"{_display_name(platform)} is running — quit it, then push again")
|
||||||
|
|
||||||
|
|
||||||
|
def run(adapter, export_set, built: PushPlan, handle: JobHandle, *, lock_grids: bool = True,
|
||||||
|
store=None, level: Level | None = None, auto_gain: bool = False) -> dict:
|
||||||
|
"""Copy what changed into the shared folder, then push into each target.
|
||||||
|
See the module docstring for the order and what a cancel leaves."""
|
||||||
|
if built.blocked:
|
||||||
|
raise PushRefused(f"This push cannot run: {built.blocked}")
|
||||||
|
for target in built.active:
|
||||||
|
_refuse_if_running(target.platform)
|
||||||
|
|
||||||
|
root = Path(built.audio.destination)
|
||||||
|
created: list[Path] = [] # new files this run placed (rolled back)
|
||||||
|
waiting: list[tuple[Path, Path]] = [] # (partial, file) replacing a file in use
|
||||||
|
written: set[str] = set() # source ids whose copy this run wrote
|
||||||
|
saved = False
|
||||||
|
done = 0
|
||||||
|
try:
|
||||||
|
_measure_missing(adapter, built.audio, handle, store=store, level=level,
|
||||||
|
previous=built.previous)
|
||||||
|
items = built.audio.exportable
|
||||||
|
# The targets' writers, for `prepare_copy` (Traktor's removes its own
|
||||||
|
# block from the file, which it would restore over the pushed grid).
|
||||||
|
writers = [w for w in (core_export.for_platform(t.platform) for t in built.active) if w]
|
||||||
|
handle.progress(done=0, total=built.audio.total_bytes, unit="bytes", message="Copying…")
|
||||||
|
for planned in items:
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
if planned.reuse is not None:
|
||||||
|
# Kept: prepared for any target that has not yet. In place —
|
||||||
|
# no target app is running (refused above), and a library
|
||||||
|
# already holding the file re-reads its tags on its own.
|
||||||
|
old = built.previous.get(str(planned.source_path))
|
||||||
|
prepare_kept(planned.reuse, planned, old[1] if old else {}, writers)
|
||||||
|
continue
|
||||||
|
target = Path(planned.destination)
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
partial = _partial(target)
|
||||||
|
created.append(partial)
|
||||||
|
|
||||||
|
def advance(n: int) -> None:
|
||||||
|
nonlocal done
|
||||||
|
done += n
|
||||||
|
handle.progress(done=done)
|
||||||
|
|
||||||
|
handle.progress(message=f"Copying {planned.title}")
|
||||||
|
write_copy(adapter, planned, partial, handle, advance)
|
||||||
|
planned.prepared = prepare_copy(partial, writers)
|
||||||
|
written.add(planned.track_id)
|
||||||
|
if target.exists():
|
||||||
|
# A library may be playing this file: it is replaced only
|
||||||
|
# once a library has been saved to match.
|
||||||
|
waiting.append((partial, target))
|
||||||
|
else:
|
||||||
|
os.replace(partial, target)
|
||||||
|
created.remove(partial)
|
||||||
|
created.append(target)
|
||||||
|
|
||||||
|
cache = AnalysisCache(_local_dir() / "analysis")
|
||||||
|
payload_tracks = []
|
||||||
|
for planned in items:
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
payload_tracks.append(ExportTrack(
|
||||||
|
track=adapter.track(planned.track_id),
|
||||||
|
destination=Path(planned.destination),
|
||||||
|
cues=_locked(adapter.track_cues(planned.track_id), lock_grids),
|
||||||
|
art=_cover(adapter, planned.track_id),
|
||||||
|
fingerprint=_fingerprint(planned),
|
||||||
|
analysis_cache=cache,
|
||||||
|
loudness=(shifted(planned.loudness, planned.gain_db)
|
||||||
|
if auto_gain and planned.loudness is not None else None),
|
||||||
|
gain_db=planned.gain_db,
|
||||||
|
))
|
||||||
|
payload = ExportPayload(name=export_set.name, root_folder=True, tracks=payload_tracks,
|
||||||
|
playlists=built.playlists, checkpoint=_checkpoint(handle))
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for target in built.active:
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
handle.progress(done=0, total=0, unit="tracks",
|
||||||
|
message=f"Pushing into {target.name}…")
|
||||||
|
push = _overwrite if export_set.mode == "overwrite" else _merge
|
||||||
|
results.append(push(target, export_set, payload, handle,
|
||||||
|
planned={t.track_id: t for t in items}, written=written,
|
||||||
|
waiting=waiting, previous=built.previous))
|
||||||
|
saved = True
|
||||||
|
# The library now plays the new files: the waiting ones go in.
|
||||||
|
for partial, final in waiting:
|
||||||
|
os.replace(partial, final)
|
||||||
|
waiting.clear()
|
||||||
|
|
||||||
|
with _LOCK:
|
||||||
|
doc = _read_ledger()
|
||||||
|
records = doc["audio"].setdefault(str(root), {})
|
||||||
|
for planned in items:
|
||||||
|
records[_rel_for(planned.source_path)] = _record(planned, Path(planned.destination))
|
||||||
|
removed = _prune_audio(doc, root)
|
||||||
|
_write_ledger(doc)
|
||||||
|
return {
|
||||||
|
"tracks": len(items),
|
||||||
|
"copied": len(written),
|
||||||
|
"unchanged": built.audio.unchanged,
|
||||||
|
"normalised": sum(1 for t in items if t.gain_db),
|
||||||
|
"skipped": len(built.audio.tracks) - len(items),
|
||||||
|
"deleted_files": removed,
|
||||||
|
"audio_root": str(root),
|
||||||
|
"targets": results,
|
||||||
|
"skipped_targets": [t.name for t in built.targets if t.skipped],
|
||||||
|
}
|
||||||
|
except BaseException:
|
||||||
|
for partial, _final in waiting:
|
||||||
|
partial.unlink(missing_ok=True)
|
||||||
|
if not saved:
|
||||||
|
# No library refers to anything this run placed.
|
||||||
|
for path in created:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def _prune_audio(doc: dict, root: Path) -> int:
|
||||||
|
"""Delete the shared folder's copies no set holds any more."""
|
||||||
|
records = doc["audio"].get(str(root)) or {}
|
||||||
|
owned = _owned(doc)
|
||||||
|
gone = [rel for rel in records if rel not in owned]
|
||||||
|
for rel in gone:
|
||||||
|
path = root / rel
|
||||||
|
try:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
except OSError as ex:
|
||||||
|
log.warning("could not delete %s: %s", path, ex)
|
||||||
|
continue
|
||||||
|
records.pop(rel, None)
|
||||||
|
_prune_empty(path.parent, root)
|
||||||
|
return len(gone)
|
||||||
|
|
||||||
|
|
||||||
|
def _prune_empty(folder: Path, root: Path) -> None:
|
||||||
|
while folder != root and root in folder.parents:
|
||||||
|
try:
|
||||||
|
folder.rmdir()
|
||||||
|
except OSError:
|
||||||
|
return
|
||||||
|
folder = folder.parent
|
||||||
|
|
||||||
|
|
||||||
|
# ---- one library: merge ------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _backup(platform: str, path: Path) -> None:
|
||||||
|
"""Before a push writes `path`. Traktor: a version-history baseline (the
|
||||||
|
push itself is committed after). rekordbox, which Konduktor does not
|
||||||
|
version (a library is more than one file): the database, its WAL and the
|
||||||
|
playlist XML copied to app-data, the last 10 kept."""
|
||||||
|
if platform == "traktor":
|
||||||
|
history.ensure_baseline(path)
|
||||||
|
return
|
||||||
|
base = _local_dir() / "backups" / platform
|
||||||
|
dest = base / time.strftime("%Y%m%d-%H%M%S")
|
||||||
|
n = 1
|
||||||
|
while dest.exists():
|
||||||
|
n += 1
|
||||||
|
dest = base / f"{time.strftime('%Y%m%d-%H%M%S')}-{n}"
|
||||||
|
dest.mkdir(parents=True)
|
||||||
|
for p in (path, path.with_name(path.name + "-wal"), path.with_name("masterPlaylists6.xml")):
|
||||||
|
if p.is_file():
|
||||||
|
shutil.copy2(p, dest / p.name)
|
||||||
|
for old in sorted(d for d in base.iterdir() if d.is_dir())[:-_BACKUPS_KEPT]:
|
||||||
|
shutil.rmtree(old, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _commit(platform: str, path: Path, data: bytes | None, summary: str) -> None:
|
||||||
|
if platform == "traktor" and data is not None:
|
||||||
|
history.commit(path, data, summary, __version__)
|
||||||
|
|
||||||
|
|
||||||
|
def _folder_name(adapter, wanted: str, own: str | None) -> str:
|
||||||
|
"""The set's folder name: `wanted`, unless a top-level node the user owns
|
||||||
|
already has it — Traktor's `create_folder` would hand back THEIR folder,
|
||||||
|
and the next push would delete it."""
|
||||||
|
taken = {n.name for n in adapter.playlist_tree() if n.id != own}
|
||||||
|
name, n = wanted, 1
|
||||||
|
while name in taken:
|
||||||
|
name = f"{wanted} (Konduktor)" if n == 1 else f"{wanted} (Konduktor {n})"
|
||||||
|
n += 1
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def _tree_hash(name: str, payload: ExportPayload, moved: dict[str, str]) -> str:
|
||||||
|
blob = [name, [[p.name, p.folders, [moved.get(t) for t in p.track_ids]] for p in payload.playlists],
|
||||||
|
[moved.get(t.source_id) for t in payload.tracks]]
|
||||||
|
return hashlib.sha256(json.dumps(blob).encode()).hexdigest()[:24]
|
||||||
|
|
||||||
|
|
||||||
|
def _node_ids(nodes) -> set[str]:
|
||||||
|
out = set()
|
||||||
|
for n in nodes or []:
|
||||||
|
out.add(n.id)
|
||||||
|
out |= _node_ids(getattr(n, "children", None))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _update(target, local_id: str, item: ExportTrack, *, audio_change: AudioChange | None) -> None:
|
||||||
|
"""Bring a track this set pushed earlier up to date with the source."""
|
||||||
|
caps = target.capabilities().tracks
|
||||||
|
now = target.track(local_id)
|
||||||
|
fields = {}
|
||||||
|
for k in _METADATA_FIELDS:
|
||||||
|
if k in caps.editable_fields:
|
||||||
|
value = getattr(item.track, k, None)
|
||||||
|
if (getattr(now, k, None) or None) != (value or None):
|
||||||
|
fields[k] = value if value is not None else ("" if k != "rating" else 0)
|
||||||
|
if fields:
|
||||||
|
target.set_track_metadata(local_id, fields)
|
||||||
|
if caps.key_writable and item.track.key_wheel and item.track.key_mode and (
|
||||||
|
(now.key_wheel, now.key_mode) != (item.track.key_wheel, item.track.key_mode)):
|
||||||
|
target.set_key(local_id, item.track.key_wheel, item.track.key_mode)
|
||||||
|
if caps.colors and now.color != item.track.color:
|
||||||
|
target.set_track_color(local_id, item.track.color)
|
||||||
|
if audio_change is not None and caps.normalizable:
|
||||||
|
target.audio_changed(local_id, audio_change)
|
||||||
|
if item.loudness is not None and caps.auto_gain:
|
||||||
|
target.set_auto_gain(local_id, item.loudness)
|
||||||
|
if item.cues is not None:
|
||||||
|
target.replace_cues(local_id, item.cues)
|
||||||
|
|
||||||
|
|
||||||
|
def _audio_change(target, item: ExportTrack, planned: PlannedTrack, previous: dict,
|
||||||
|
waiting: list) -> AudioChange:
|
||||||
|
"""What a copy written this run means to a library already playing it:
|
||||||
|
its size, the level change, and — for a platform that draws waveforms
|
||||||
|
from the file (rekordbox) — the new audio measured at its time base."""
|
||||||
|
final = item.destination
|
||||||
|
path = next((p for p, f in waiting if f == final), final)
|
||||||
|
old = previous.get(str(planned.source_path))
|
||||||
|
before = float((old[1] if old else {}).get("gain_db") or 0.0)
|
||||||
|
measured = None
|
||||||
|
lead = getattr(target, "analysis_lead", None)
|
||||||
|
if lead is not None:
|
||||||
|
from .core import waveform
|
||||||
|
|
||||||
|
try:
|
||||||
|
measured = waveform.analyse(path, lead=lead(final))
|
||||||
|
except Exception as ex: # noqa: BLE001 — the old waveform stays drawn
|
||||||
|
log.warning("could not measure %s for its waveform: %s", path, ex)
|
||||||
|
return AudioChange(gain_db=item.gain_db - before, size=path.stat().st_size, measured=measured)
|
||||||
|
|
||||||
|
|
||||||
|
def _merge(tp: TargetPlan, export_set, payload: ExportPayload, handle: JobHandle, *,
|
||||||
|
planned: dict[str, PlannedTrack], written: set[str], waiting: list,
|
||||||
|
previous: dict) -> dict:
|
||||||
|
path = Path(tp.path)
|
||||||
|
lid = library_id.for_path(path, platform=tp.platform, label=tp.name)
|
||||||
|
with _LOCK:
|
||||||
|
doc = _read_ledger()
|
||||||
|
lib = doc["libraries"].get(lid) or {}
|
||||||
|
sets = lib.get("sets") or {}
|
||||||
|
mine = sets.get(export_set.id) or {}
|
||||||
|
tracks: dict[str, dict] = dict(mine.get("tracks") or {})
|
||||||
|
others = {rec.get("local_id") for sid, s in sets.items() if sid != export_set.id
|
||||||
|
for rec in (s.get("tracks") or {}).values()}
|
||||||
|
|
||||||
|
_backup(tp.platform, path)
|
||||||
|
target = registry.open_library(path)
|
||||||
|
try:
|
||||||
|
caps = target.capabilities()
|
||||||
|
if not caps.writable:
|
||||||
|
raise PushRefused(f"{tp.name} cannot be written: {caps.readonly_cause}")
|
||||||
|
held = _existing_files(target)
|
||||||
|
moved: dict[str, str] = {}
|
||||||
|
new_items: list[ExportTrack] = []
|
||||||
|
updates: list[tuple[ExportTrack, str]] = []
|
||||||
|
for item in payload.tracks:
|
||||||
|
sid = item.source_id
|
||||||
|
rec = tracks.get(sid)
|
||||||
|
local = rec.get("local_id") if rec and rec.get("local_id") else None
|
||||||
|
if local is not None and target.track(local) is None:
|
||||||
|
local = None # removed in the DJ app since: add it again
|
||||||
|
if local is None:
|
||||||
|
# Already in the library at that path (another set's, or a
|
||||||
|
# ledger that was lost): the same file is the same track — a
|
||||||
|
# second entry would be a corrupt Traktor collection.
|
||||||
|
local = held.get(_key(item.destination))
|
||||||
|
if local is None:
|
||||||
|
new_items.append(item)
|
||||||
|
continue
|
||||||
|
moved[sid] = local
|
||||||
|
if rec is None or rec.get("prep") != _prep_hash(item) or sid in written:
|
||||||
|
updates.append((item, local))
|
||||||
|
|
||||||
|
added = target.add_tracks(
|
||||||
|
[NewTrack(track=i.track, audio_path=i.destination, cues=i.cues, art=i.art)
|
||||||
|
for i in new_items], checkpoint=payload.checkpoint) if new_items else []
|
||||||
|
for item, local in zip(new_items, added):
|
||||||
|
moved[item.source_id] = local
|
||||||
|
if item.loudness is not None and caps.tracks.auto_gain:
|
||||||
|
target.set_auto_gain(local, item.loudness)
|
||||||
|
for n, (item, local) in enumerate(updates, start=1):
|
||||||
|
payload.checkpoint(f"Updating {item.track.title or item.destination.name}", step=n,
|
||||||
|
of=len(updates))
|
||||||
|
change = (_audio_change(target, item, planned[item.source_id], previous, waiting)
|
||||||
|
if item.source_id in written else None)
|
||||||
|
_update(target, local, item, audio_change=change)
|
||||||
|
|
||||||
|
# What left the set.
|
||||||
|
present = {i.source_id for i in payload.tracks}
|
||||||
|
kept: list[str] = []
|
||||||
|
removed = 0
|
||||||
|
for sid in [s for s in tracks if s not in present]:
|
||||||
|
rec = tracks[sid]
|
||||||
|
local = rec.get("local_id")
|
||||||
|
if not local or local in others or target.track(local) is None:
|
||||||
|
tracks.pop(sid)
|
||||||
|
continue
|
||||||
|
title = target.track(local).title or local
|
||||||
|
try:
|
||||||
|
target.remove_tracks([local])
|
||||||
|
removed += 1
|
||||||
|
tracks.pop(sid)
|
||||||
|
except Unsupported as ex:
|
||||||
|
# rekordbox: a track in its History, Sampler, … — kept, and
|
||||||
|
# the next push tries again.
|
||||||
|
kept.append(title)
|
||||||
|
rec["kept"] = str(ex)
|
||||||
|
for item in payload.tracks:
|
||||||
|
local = moved.get(item.source_id)
|
||||||
|
if local is not None:
|
||||||
|
tracks[item.source_id] = {
|
||||||
|
"local_id": local, "rel": _rel_for(planned[item.source_id].source_path),
|
||||||
|
"prep": _prep_hash(item)}
|
||||||
|
|
||||||
|
# The set's folder, rebuilt when anything in it would change.
|
||||||
|
existing = _node_ids(target.playlist_tree())
|
||||||
|
folder = mine.get("folder_id") if mine.get("folder_id") in existing else None
|
||||||
|
tree = _tree_hash(export_set.name, payload, moved)
|
||||||
|
if folder is None or mine.get("tree") != tree or mine.get("folder_name") != export_set.name:
|
||||||
|
if folder is not None:
|
||||||
|
target.delete_playlist(folder)
|
||||||
|
name = _folder_name(target, export_set.name, None)
|
||||||
|
folder = target.create_folder(name)
|
||||||
|
write_playlist_tree(target, payload.playlists, [t.source_id for t in payload.tracks],
|
||||||
|
moved, folder)
|
||||||
|
folder_name = export_set.name
|
||||||
|
else:
|
||||||
|
folder_name = mine.get("folder_name")
|
||||||
|
|
||||||
|
if target.dirty:
|
||||||
|
_refuse_if_running(tp.platform)
|
||||||
|
handle.progress(message=f"Saving {tp.name}…")
|
||||||
|
outcome = target.save()
|
||||||
|
_commit(tp.platform, path, getattr(outcome, "snapshot", None),
|
||||||
|
f"Pushed “{export_set.name}” from Konduktor")
|
||||||
|
with _LOCK:
|
||||||
|
doc = _read_ledger()
|
||||||
|
lib = doc["libraries"].setdefault(lid, {})
|
||||||
|
lib.update({"platform": tp.platform, "path": str(path)})
|
||||||
|
lib.setdefault("sets", {})[export_set.id] = {
|
||||||
|
"name": export_set.name, "folder_id": folder, "folder_name": folder_name,
|
||||||
|
"tree": tree, "tracks": tracks, "pushed": time.time(),
|
||||||
|
}
|
||||||
|
_write_ledger(doc)
|
||||||
|
return {"platform": tp.platform, "name": tp.name, "added": len(new_items),
|
||||||
|
"updated": len(updates), "removed": removed, "kept": kept}
|
||||||
|
finally:
|
||||||
|
_close(target)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- one library: overwrite ----------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _replace_file(source: Path, final: Path) -> None:
|
||||||
|
"""Put `source` at `final` atomically: copied beside it, then renamed."""
|
||||||
|
partial = final.with_name(final.name + PARTIAL_SUFFIX)
|
||||||
|
shutil.copy2(source, partial)
|
||||||
|
os.replace(partial, final)
|
||||||
|
|
||||||
|
|
||||||
|
def _overwrite(tp: TargetPlan, export_set, payload: ExportPayload, handle: JobHandle, *,
|
||||||
|
planned: dict[str, PlannedTrack], written: set[str], waiting: list,
|
||||||
|
previous: dict) -> dict:
|
||||||
|
"""Replace the library with this set: the platform's export writer builds
|
||||||
|
a fresh one in app-data (the playlists in a folder named after the set,
|
||||||
|
as a merge puts them), and its files are swapped in."""
|
||||||
|
path = Path(tp.path)
|
||||||
|
lid = library_id.for_path(path, platform=tp.platform, label=tp.name)
|
||||||
|
writer = core_export.for_platform(tp.platform)
|
||||||
|
if writer is None:
|
||||||
|
raise PushRefused(f"Konduktor cannot write a {tp.name} library")
|
||||||
|
# The old library goes, so nothing still plays the files being replaced —
|
||||||
|
# and the writer measures and sizes each file as it now is.
|
||||||
|
for partial, final in waiting:
|
||||||
|
os.replace(partial, final)
|
||||||
|
waiting.clear()
|
||||||
|
work_root = _local_dir() / "work"
|
||||||
|
work_root.mkdir(parents=True, exist_ok=True)
|
||||||
|
work = Path(tempfile.mkdtemp(dir=work_root))
|
||||||
|
try:
|
||||||
|
result = writer.write(payload, work)
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
_refuse_if_running(tp.platform)
|
||||||
|
handle.progress(message=f"Replacing the {tp.name} library…")
|
||||||
|
_backup(tp.platform, path)
|
||||||
|
if tp.platform == "traktor":
|
||||||
|
_replace_file(result.library, path)
|
||||||
|
_commit(tp.platform, path, path.read_bytes(), f"Replaced by “{export_set.name}” from Konduktor")
|
||||||
|
else:
|
||||||
|
# rekordbox: the database, its playlist XML and the analysis files
|
||||||
|
# under `share/` beside it (new UUID paths, so nothing collides).
|
||||||
|
# A WAL left by the old database would be replayed into the new one.
|
||||||
|
for suffix in ("-wal", "-shm"):
|
||||||
|
path.with_name(path.name + suffix).unlink(missing_ok=True)
|
||||||
|
_replace_file(result.library, path)
|
||||||
|
xml = work / "masterPlaylists6.xml"
|
||||||
|
if xml.is_file():
|
||||||
|
_replace_file(xml, path.with_name(xml.name))
|
||||||
|
share = work / "share"
|
||||||
|
if share.is_dir():
|
||||||
|
shutil.copytree(share, path.parent / "share", dirs_exist_ok=True)
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(work, ignore_errors=True)
|
||||||
|
|
||||||
|
# Record what the new library holds, so a later merge push of this set
|
||||||
|
# finds its tracks and folder.
|
||||||
|
target = registry.open_library(path)
|
||||||
|
try:
|
||||||
|
held = _existing_files(target)
|
||||||
|
tracks = {}
|
||||||
|
for item in payload.tracks:
|
||||||
|
local = held.get(_key(item.destination))
|
||||||
|
if local is not None:
|
||||||
|
tracks[item.source_id] = {"local_id": local,
|
||||||
|
"rel": _rel_for(planned[item.source_id].source_path),
|
||||||
|
"prep": _prep_hash(item)}
|
||||||
|
folder = next((n.id for n in target.playlist_tree() if n.name == export_set.name), None)
|
||||||
|
moved = {sid: rec["local_id"] for sid, rec in tracks.items()}
|
||||||
|
finally:
|
||||||
|
_close(target)
|
||||||
|
with _LOCK:
|
||||||
|
doc = _read_ledger()
|
||||||
|
doc["libraries"][lid] = {"platform": tp.platform, "path": str(path), "sets": {
|
||||||
|
export_set.id: {"name": export_set.name, "folder_id": folder,
|
||||||
|
"folder_name": export_set.name,
|
||||||
|
"tree": _tree_hash(export_set.name, payload, moved),
|
||||||
|
"tracks": tracks, "pushed": time.time()}}}
|
||||||
|
_write_ledger(doc)
|
||||||
|
return {"platform": tp.platform, "name": tp.name, "added": len(tracks), "updated": 0,
|
||||||
|
"removed": 0, "kept": [], "replaced": True, "wiped_sets": tp.wipes_sets}
|
||||||
+180
-15
@@ -6,6 +6,7 @@ in the environment auto-loads that file on startup (used by dev and tests).
|
|||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
@@ -16,7 +17,7 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
|
|||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import FileResponse, JSONResponse
|
from fastapi.responses import FileResponse, JSONResponse
|
||||||
|
|
||||||
from . import __version__, exporter, exports, loudness_store, prefs
|
from . import __version__, exporter, exports, local_push, loudness_store, paths, prefs
|
||||||
from .app_state import STATE
|
from .app_state import STATE
|
||||||
from .core import auto_hotcues as ah
|
from .core import auto_hotcues as ah
|
||||||
from .core import grid_detect, key_detect, loudness, structure
|
from .core import grid_detect, key_detect, loudness, structure
|
||||||
@@ -38,6 +39,7 @@ from .core.capabilities import Capabilities
|
|||||||
from .jobs import JOBS, Job, JobBusy
|
from .jobs import JOBS, Job, JobBusy
|
||||||
from .core.pathmap import PathMapping
|
from .core.pathmap import PathMapping
|
||||||
from .schemas import (
|
from .schemas import (
|
||||||
|
MidiExportRequest,
|
||||||
Relocation,
|
Relocation,
|
||||||
RelocationApplied,
|
RelocationApplied,
|
||||||
RelocationApply,
|
RelocationApply,
|
||||||
@@ -74,6 +76,8 @@ from .schemas import (
|
|||||||
ExportSetMembers,
|
ExportSetMembers,
|
||||||
ExportSetOut,
|
ExportSetOut,
|
||||||
ExportPreview,
|
ExportPreview,
|
||||||
|
LocalLibrariesOut,
|
||||||
|
PushPreview,
|
||||||
Drive,
|
Drive,
|
||||||
DroppedFiles,
|
DroppedFiles,
|
||||||
DroppedPaths,
|
DroppedPaths,
|
||||||
@@ -102,6 +106,7 @@ from .schemas import (
|
|||||||
RenamePlaylist,
|
RenamePlaylist,
|
||||||
SaveResult,
|
SaveResult,
|
||||||
AddEntries,
|
AddEntries,
|
||||||
|
RemoveEntries,
|
||||||
MovePlaylist,
|
MovePlaylist,
|
||||||
SetEntries,
|
SetEntries,
|
||||||
SourceCandidate,
|
SourceCandidate,
|
||||||
@@ -316,7 +321,7 @@ def delete_remote(remote_id: str) -> dict:
|
|||||||
def _running_batch() -> str | None:
|
def _running_batch() -> str | None:
|
||||||
"""The kind of batch running here, for the heartbeat: another computer
|
"""The kind of batch running here, for the heartbeat: another computer
|
||||||
asking to take over is told what it would cancel."""
|
asking to take over is told what it would cancel."""
|
||||||
for kind in BATCH_JOBS + ("import", "export"):
|
for kind in BATCH_JOBS + ("import", "export", local_push.JOB_KIND):
|
||||||
if JOBS.active(kind):
|
if JOBS.active(kind):
|
||||||
return kind
|
return kind
|
||||||
return None
|
return None
|
||||||
@@ -579,13 +584,14 @@ def fs_places(platform: str | None = None) -> list[FsPlace]:
|
|||||||
|
|
||||||
|
|
||||||
@app.get("/api/fs/list", response_model=FsListing)
|
@app.get("/api/fs/list", response_model=FsListing)
|
||||||
def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
|
def fs_list(path: str | None = None, platform: str | None = None, suffix: str | None = None) -> FsListing:
|
||||||
"""List directories and openable library files for the in-app file browser.
|
"""List directories and openable library files for the in-app file browser.
|
||||||
|
|
||||||
`platform` narrows the files to that platform's own: a Traktor browse that
|
`platform` narrows the files to that platform's own: a Traktor browse that
|
||||||
also listed `master.db` would be offering a file the chosen adapter cannot
|
also listed `master.db` would be offering a file the chosen adapter cannot
|
||||||
open. A platform whose library is a directory contributes no suffixes at
|
open. A platform whose library is a directory contributes no suffixes at
|
||||||
all, so its browse shows folders only.
|
all, so its browse shows folders only. `suffix` instead lists files whose
|
||||||
|
NAME ends with it (a MIDI mapping's `.konduktor-midi.json`).
|
||||||
"""
|
"""
|
||||||
base = Path(path).expanduser() if path else Path.home()
|
base = Path(path).expanduser() if path else Path.home()
|
||||||
if not base.exists() or not base.is_dir():
|
if not base.exists() or not base.is_dir():
|
||||||
@@ -601,7 +607,7 @@ def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
|
|||||||
try:
|
try:
|
||||||
if entry.is_dir():
|
if entry.is_dir():
|
||||||
dirs.append(FsEntry(name=entry.name, path=str(entry)))
|
dirs.append(FsEntry(name=entry.name, path=str(entry)))
|
||||||
elif entry.suffix.lower() in suffixes:
|
elif entry.name.lower().endswith(suffix.lower()) if suffix else entry.suffix.lower() in suffixes:
|
||||||
files.append(FsEntry(name=entry.name, path=str(entry)))
|
files.append(FsEntry(name=entry.name, path=str(entry)))
|
||||||
except OSError:
|
except OSError:
|
||||||
continue
|
continue
|
||||||
@@ -613,6 +619,53 @@ def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- MIDI controller mappings ---------------------------------------------------
|
||||||
|
#
|
||||||
|
# A mapping lives in userprefs (`midiMappings`, written by the UI like any pref);
|
||||||
|
# these two only move one to and from a FILE, so mappings can be shared. The
|
||||||
|
# content is the UI's to validate (lib/midi/mapping.sanitizeMapping): here it
|
||||||
|
# only has to be a small JSON object of the right version.
|
||||||
|
|
||||||
|
MIDI_MAPPING_SUFFIX = ".konduktor-midi.json"
|
||||||
|
_MIDI_MAPPING_MAX_BYTES = 1_000_000
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/midi/export")
|
||||||
|
def midi_export(req: MidiExportRequest) -> dict:
|
||||||
|
"""Write a mapping into `dir` as `<name>.konduktor-midi.json`. Never
|
||||||
|
overwrites: an existing file gets a `-2`, `-3`… beside it."""
|
||||||
|
folder = Path(req.dir).expanduser()
|
||||||
|
if not folder.is_dir():
|
||||||
|
raise HTTPException(400, f"Not a folder: {req.dir}")
|
||||||
|
if req.mapping.get("version") != 1:
|
||||||
|
raise HTTPException(400, "Not a MIDI mapping")
|
||||||
|
stem = "".join("_" if c in '/\\:*?"<>|' else c for c in req.name).strip(" .") or "MIDI mapping"
|
||||||
|
target = folder / f"{stem}{MIDI_MAPPING_SUFFIX}"
|
||||||
|
n = 2
|
||||||
|
while target.exists():
|
||||||
|
target = folder / f"{stem}-{n}{MIDI_MAPPING_SUFFIX}"
|
||||||
|
n += 1
|
||||||
|
paths.write_json(target, req.mapping)
|
||||||
|
return {"path": str(target)}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/midi/import")
|
||||||
|
def midi_import(path: str) -> dict:
|
||||||
|
"""Read a mapping file (size-capped; must be a version-1 JSON object)."""
|
||||||
|
file = Path(path).expanduser()
|
||||||
|
if not file.is_file():
|
||||||
|
raise HTTPException(404, f"No such file: {path}")
|
||||||
|
if file.stat().st_size > _MIDI_MAPPING_MAX_BYTES:
|
||||||
|
raise HTTPException(400, "That file is too large to be a MIDI mapping")
|
||||||
|
try:
|
||||||
|
data = json.loads(file.read_text(encoding="utf-8"))
|
||||||
|
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||||
|
raise HTTPException(400, "That file is not a MIDI mapping") from None
|
||||||
|
if not isinstance(data, dict) or data.get("version") != 1:
|
||||||
|
raise HTTPException(400, "That file is not a MIDI mapping")
|
||||||
|
return {"mapping": data}
|
||||||
|
|
||||||
|
|
||||||
# ---- export sets -------------------------------------------------------------
|
# ---- export sets -------------------------------------------------------------
|
||||||
#
|
#
|
||||||
# Curation, not library data: a set is Konduktor's own record of what to export,
|
# Curation, not library data: a set is Konduktor's own record of what to export,
|
||||||
@@ -642,30 +695,33 @@ def list_exports() -> list[ExportSetOut]:
|
|||||||
|
|
||||||
@app.post("/api/exports", response_model=ExportSetOut)
|
@app.post("/api/exports", response_model=ExportSetOut)
|
||||||
def create_export(body: CreateExportSet) -> ExportSetOut:
|
def create_export(body: CreateExportSet) -> ExportSetOut:
|
||||||
if not body.destination.strip():
|
if body.kind == "folder" and not body.destination.strip():
|
||||||
raise HTTPException(400, "An export needs a destination folder")
|
raise HTTPException(400, "An export needs a destination folder")
|
||||||
# Only platforms that can actually be WRITTEN may be targets. Gating here as
|
# Only platforms that can actually be WRITTEN may be targets. Gating here as
|
||||||
# well as in the UI, because a set persists: one created against a target
|
# well as in the UI, because a set persists: one created against a target
|
||||||
# that later stops being supported would otherwise fail at export time.
|
# that later stops being supported would otherwise fail at export time.
|
||||||
_check_targets(body.targets)
|
_check_targets(body.targets, kind=body.kind)
|
||||||
created = exports.create(
|
created = exports.create(
|
||||||
_require_library_id(),
|
_require_library_id(),
|
||||||
name=body.name,
|
name=body.name,
|
||||||
targets=body.targets,
|
targets=body.targets,
|
||||||
destination=body.destination,
|
destination=body.destination if body.kind == "folder" else "",
|
||||||
|
kind=body.kind,
|
||||||
|
mode=body.mode,
|
||||||
)
|
)
|
||||||
return ExportSetOut(**created.as_dict())
|
return ExportSetOut(**created.as_dict())
|
||||||
|
|
||||||
|
|
||||||
@app.patch("/api/exports/{set_id}", response_model=ExportSetOut)
|
@app.patch("/api/exports/{set_id}", response_model=ExportSetOut)
|
||||||
def update_export(set_id: str, body: UpdateExportSet) -> ExportSetOut:
|
def update_export(set_id: str, body: UpdateExportSet) -> ExportSetOut:
|
||||||
_require_set(set_id)
|
found = _require_set(set_id)
|
||||||
if body.targets is not None:
|
if body.targets is not None:
|
||||||
_check_targets(body.targets)
|
_check_targets(body.targets, kind=found.kind)
|
||||||
updated = exports.update(
|
updated = exports.update(
|
||||||
_require_library_id(),
|
_require_library_id(),
|
||||||
set_id,
|
set_id,
|
||||||
name=body.name,
|
name=body.name,
|
||||||
|
mode=body.mode,
|
||||||
targets=body.targets,
|
targets=body.targets,
|
||||||
destination=body.destination,
|
destination=body.destination,
|
||||||
lock_grids=body.lock_grids,
|
lock_grids=body.lock_grids,
|
||||||
@@ -724,7 +780,7 @@ def export_contents(set_id: str) -> ExportContents:
|
|||||||
dangling=resolved.dangling_track_ids,
|
dangling=resolved.dangling_track_ids,
|
||||||
destination_conflict=exports.destination_conflict(
|
destination_conflict=exports.destination_conflict(
|
||||||
_require_library_id(), found.destination, ignore=set_id
|
_require_library_id(), found.destination, ignore=set_id
|
||||||
),
|
) if found.kind == "folder" else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -800,7 +856,7 @@ def _export_options(found, body: RunExport | None) -> dict:
|
|||||||
def preview_export(set_id: str, body: RunExport | None = None) -> ExportPreview:
|
def preview_export(set_id: str, body: RunExport | None = None) -> ExportPreview:
|
||||||
"""What this export would do, right now, with the run dialog's options as
|
"""What this export would do, right now, with the run dialog's options as
|
||||||
ticked. Never cached — the set is live."""
|
ticked. Never cached — the set is live."""
|
||||||
found = _require_set(set_id)
|
found = _require_folder_set(set_id)
|
||||||
built = exporter.plan(require_adapter(), found, **_export_options(found, body))
|
built = exporter.plan(require_adapter(), found, **_export_options(found, body))
|
||||||
return ExportPreview(**built.as_dict(exporter.space_for(built)))
|
return ExportPreview(**built.as_dict(exporter.space_for(built)))
|
||||||
|
|
||||||
@@ -816,7 +872,7 @@ def run_export(set_id: str, body: RunExport | None = None) -> JobStatus:
|
|||||||
The dialog's options arrive with the click and are remembered on the set,
|
The dialog's options arrive with the click and are remembered on the set,
|
||||||
so the next export of the same stick starts from the same answer.
|
so the next export of the same stick starts from the same answer.
|
||||||
"""
|
"""
|
||||||
found = _require_set(set_id)
|
found = _require_folder_set(set_id)
|
||||||
if body is not None:
|
if body is not None:
|
||||||
changes = {k: v for k, v in (("lock_grids", body.lock_grids), ("normalise", body.normalise),
|
changes = {k: v for k, v in (("lock_grids", body.lock_grids), ("normalise", body.normalise),
|
||||||
("auto_gain", body.auto_gain)) if v is not None}
|
("auto_gain", body.auto_gain)) if v is not None}
|
||||||
@@ -836,6 +892,80 @@ def run_export(set_id: str, body: RunExport | None = None) -> JobStatus:
|
|||||||
return JobStatus(**job.as_dict())
|
return JobStatus(**job.as_dict())
|
||||||
|
|
||||||
|
|
||||||
|
# ---- pushing into this computer's DJ apps (`local_push.py`) -----------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _local_level_out(level) -> dict | None:
|
||||||
|
return {"measure": level.measure, "target": level.target, "ceiling": level.ceiling} if level else None
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/local-libraries", response_model=LocalLibrariesOut)
|
||||||
|
def local_libraries() -> LocalLibrariesOut:
|
||||||
|
"""The DJ apps' libraries on this computer a "computer" set pushes into,
|
||||||
|
each with why it cannot be used, plus the shared audio folder and its
|
||||||
|
level. Changed through `/api/prefs` (`localLibraries`, `localAudioRoot`,
|
||||||
|
`localNormalise`, `localLevel`)."""
|
||||||
|
import platformdirs
|
||||||
|
|
||||||
|
return LocalLibrariesOut(
|
||||||
|
libraries=[lib.as_dict() for lib in local_push.local_libraries(STATE.path)],
|
||||||
|
audio_root=str(local_push.audio_root()),
|
||||||
|
audio_root_default=str(Path(platformdirs.user_music_dir()) / "Konduktor"),
|
||||||
|
level=_local_level_out(local_push.level()),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_computer_set(set_id: str):
|
||||||
|
found = _require_set(set_id)
|
||||||
|
if found.kind != "computer":
|
||||||
|
raise HTTPException(400, "This set is exported into a folder, not pushed")
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _push_options(found) -> dict:
|
||||||
|
"""The push's options: the set's lock and auto gain (as the run dialog
|
||||||
|
left them), the shared folder's level (the app setting, not the set's)."""
|
||||||
|
return {"store": STATE.loudness, "level": local_push.level(), "auto_gain": bool(found.auto_gain)}
|
||||||
|
|
||||||
|
|
||||||
|
def _remember_run_options(found, body: RunExport | None):
|
||||||
|
if body is None:
|
||||||
|
return found
|
||||||
|
changes = {k: v for k, v in (("lock_grids", body.lock_grids), ("auto_gain", body.auto_gain))
|
||||||
|
if v is not None}
|
||||||
|
return exports.update(_require_library_id(), found.id, **changes) if changes else found
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/exports/{set_id}/push/preview", response_model=PushPreview)
|
||||||
|
def preview_push(set_id: str, body: RunExport | None = None) -> PushPreview:
|
||||||
|
"""What pushing this set would do now, with the dialog's ticks."""
|
||||||
|
found = _require_computer_set(set_id)
|
||||||
|
if body is not None and body.auto_gain is not None:
|
||||||
|
found.auto_gain = body.auto_gain # a look, not a change: not saved
|
||||||
|
built = local_push.plan(require_adapter(), found, open_path=STATE.path, **_push_options(found))
|
||||||
|
return PushPreview(**built.as_dict())
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/exports/{set_id}/push", response_model=JobStatus)
|
||||||
|
def run_push(set_id: str, body: RunExport | None = None) -> JobStatus:
|
||||||
|
"""Start the push on a background thread; poll `/api/jobs/{id}`. Planned
|
||||||
|
again here (a playlist may have changed since the preview, or Traktor been
|
||||||
|
started); the dialog's ticks are remembered on the set."""
|
||||||
|
found = _remember_run_options(_require_computer_set(set_id), body)
|
||||||
|
adapter = require_adapter()
|
||||||
|
options = _push_options(found)
|
||||||
|
built = local_push.plan(adapter, found, open_path=STATE.path, **options)
|
||||||
|
if built.blocked:
|
||||||
|
raise HTTPException(409, built.blocked)
|
||||||
|
try:
|
||||||
|
job = JOBS.submit(local_push.JOB_KIND, lambda handle: local_push.run(
|
||||||
|
adapter, found, built, handle, lock_grids=found.lock_grids, **options),
|
||||||
|
exclusive_with=(local_push.JOB_KIND,))
|
||||||
|
except JobBusy:
|
||||||
|
raise HTTPException(409, "A push is already running")
|
||||||
|
return JobStatus(**job.as_dict())
|
||||||
|
|
||||||
|
|
||||||
def _export_targets() -> set[str]:
|
def _export_targets() -> set[str]:
|
||||||
"""Platforms Konduktor can write a NEW library for.
|
"""Platforms Konduktor can write a NEW library for.
|
||||||
|
|
||||||
@@ -847,14 +977,27 @@ def _export_targets() -> set[str]:
|
|||||||
return core_export.targets()
|
return core_export.targets()
|
||||||
|
|
||||||
|
|
||||||
def _check_targets(targets: list[str]) -> None:
|
def _require_folder_set(set_id: str):
|
||||||
|
found = _require_set(set_id)
|
||||||
|
if found.kind != "folder":
|
||||||
|
raise HTTPException(400, "This set is pushed into this computer's DJ apps, not exported")
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _check_targets(targets: list[str], *, kind: str = "folder") -> None:
|
||||||
"""Refuse a set with no targets, or one naming a platform with no exporter.
|
"""Refuse a set with no targets, or one naming a platform with no exporter.
|
||||||
|
|
||||||
Checked when the set is saved: a target that later stops being supported
|
Checked when the set is saved: a target that later stops being supported
|
||||||
would otherwise fail at export time.
|
would otherwise fail at export time. A "computer" set pushes into the DJ
|
||||||
|
apps a computer runs, which are `local_push.PLATFORMS`.
|
||||||
"""
|
"""
|
||||||
if not targets:
|
if not targets:
|
||||||
raise HTTPException(400, "An export needs at least one platform to export for")
|
raise HTTPException(400, "An export needs at least one platform to export for")
|
||||||
|
if kind == "computer":
|
||||||
|
unsupported = [t for t in targets if t not in local_push.PLATFORMS]
|
||||||
|
if unsupported:
|
||||||
|
raise HTTPException(422, f"Konduktor cannot push into {', '.join(unsupported)}")
|
||||||
|
return
|
||||||
unsupported = [t for t in targets if t not in _export_targets()]
|
unsupported = [t for t in targets if t not in _export_targets()]
|
||||||
if unsupported:
|
if unsupported:
|
||||||
raise HTTPException(422, f"Konduktor cannot export to {', '.join(unsupported)} yet")
|
raise HTTPException(422, f"Konduktor cannot export to {', '.join(unsupported)} yet")
|
||||||
@@ -1381,6 +1524,28 @@ def add_entries(playlist_uuid: str, body: AddEntries) -> dict:
|
|||||||
"duplicates": len(dupes), "count": n}
|
"duplicates": len(dupes), "count": n}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/playlists/{playlist_uuid}/remove")
|
||||||
|
def remove_entries(playlist_uuid: str, body: RemoveEntries) -> dict:
|
||||||
|
"""Remove tracks from a playlist — EVERY occurrence of each — without the
|
||||||
|
caller holding its entry list (the track menu's Remove ▸ From playlist).
|
||||||
|
Other entries keep their order, including ones whose track is missing
|
||||||
|
from the collection. `tracks` = how many of the given tracks it held,
|
||||||
|
`removed` = entries dropped (more, where a track was there twice)."""
|
||||||
|
a = require_adapter()
|
||||||
|
current = a.playlist_entries(playlist_uuid)
|
||||||
|
if current is None:
|
||||||
|
raise HTTPException(404, f"Playlist not found: {playlist_uuid}")
|
||||||
|
gone = set(body.track_ids)
|
||||||
|
kept = [t for t in current if t not in gone]
|
||||||
|
held = len(gone & set(current))
|
||||||
|
removed = len(current) - len(kept)
|
||||||
|
n = len(current)
|
||||||
|
if removed and not body.dry_run:
|
||||||
|
n = a.set_playlist_entries(playlist_uuid, kept)
|
||||||
|
return {"status": "counted" if body.dry_run else "removed", "id": playlist_uuid,
|
||||||
|
"tracks": held, "removed": removed, "count": n}
|
||||||
|
|
||||||
|
|
||||||
@app.patch("/api/tracks")
|
@app.patch("/api/tracks")
|
||||||
def edit_track(body: EditTrack) -> dict:
|
def edit_track(body: EditTrack) -> dict:
|
||||||
"""Edit a single track's safe metadata fields (in-memory; persisted on save)."""
|
"""Edit a single track's safe metadata fields (in-memory; persisted on save)."""
|
||||||
|
|||||||
@@ -109,6 +109,7 @@ EXCLUDED: dict[str, str] = {
|
|||||||
"set_cover_art": "PUT /v1/art — bytes",
|
"set_cover_art": "PUT /v1/art — bytes",
|
||||||
"apply_stem_swaps": "the server applies stem swaps itself (POST /v1/stems/publish)",
|
"apply_stem_swaps": "the server applies stem swaps itself (POST /v1/stems/publish)",
|
||||||
"audio_changed": "the server applies a Normalize itself, at its own end step (POST /v1/gain/publish)",
|
"audio_changed": "the server applies a Normalize itself, at its own end step (POST /v1/gain/publish)",
|
||||||
|
"replace_cues": "a push targets a DJ app's library on THIS computer, never one a server holds",
|
||||||
"set_path_mapping": "the server's path mapping is its own configuration",
|
"set_path_mapping": "the server's path mapping is its own configuration",
|
||||||
"set_session_mappings": "the missing-files check searches THIS computer's drives",
|
"set_session_mappings": "the missing-files check searches THIS computer's drives",
|
||||||
"unresolved_path_groups": "the missing-files check searches THIS computer's drives",
|
"unresolved_path_groups": "the missing-files check searches THIS computer's drives",
|
||||||
|
|||||||
@@ -32,6 +32,12 @@ class AddEntries(BaseModel):
|
|||||||
index: int | None = None
|
index: int | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class RemoveEntries(BaseModel):
|
||||||
|
track_ids: list[str]
|
||||||
|
# Count what would go and change nothing — the confirm dialog's numbers.
|
||||||
|
dry_run: bool = False
|
||||||
|
|
||||||
|
|
||||||
class MovePlaylist(BaseModel):
|
class MovePlaylist(BaseModel):
|
||||||
node_id: str
|
node_id: str
|
||||||
parent_id: str | None = None # None = the top level
|
parent_id: str | None = None # None = the top level
|
||||||
@@ -402,6 +408,10 @@ class CollectionOptions(BaseModel):
|
|||||||
class ExportSetOut(BaseModel):
|
class ExportSetOut(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
name: str
|
name: str
|
||||||
|
#: "folder": exported into `destination`; "computer": pushed into the DJ
|
||||||
|
#: apps' own libraries on this computer (`local_push.py`), `mode` saying how.
|
||||||
|
kind: Literal["folder", "computer"] = "folder"
|
||||||
|
mode: Literal["merge", "overwrite"] = "merge"
|
||||||
targets: list[str] # platform ids of the export TARGETS, never empty
|
targets: list[str] # platform ids of the export TARGETS, never empty
|
||||||
destination: str
|
destination: str
|
||||||
playlist_ids: list[str] = []
|
playlist_ids: list[str] = []
|
||||||
@@ -416,8 +426,10 @@ class ExportSetOut(BaseModel):
|
|||||||
|
|
||||||
class CreateExportSet(BaseModel):
|
class CreateExportSet(BaseModel):
|
||||||
name: str
|
name: str
|
||||||
|
kind: Literal["folder", "computer"] = "folder"
|
||||||
|
mode: Literal["merge", "overwrite"] = "merge"
|
||||||
targets: list[str] = ["traktor"]
|
targets: list[str] = ["traktor"]
|
||||||
destination: str
|
destination: str = "" # a "computer" set has none
|
||||||
|
|
||||||
|
|
||||||
class ExportLevel(BaseModel):
|
class ExportLevel(BaseModel):
|
||||||
@@ -429,6 +441,7 @@ class ExportLevel(BaseModel):
|
|||||||
|
|
||||||
class UpdateExportSet(BaseModel):
|
class UpdateExportSet(BaseModel):
|
||||||
name: str | None = None
|
name: str | None = None
|
||||||
|
mode: Literal["merge", "overwrite"] | None = None
|
||||||
targets: list[str] | None = None
|
targets: list[str] | None = None
|
||||||
destination: str | None = None
|
destination: str | None = None
|
||||||
lock_grids: bool | None = None
|
lock_grids: bool | None = None
|
||||||
@@ -502,6 +515,71 @@ class ExportPreview(BaseModel):
|
|||||||
level_counts: dict[str, int] = {}
|
level_counts: dict[str, int] = {}
|
||||||
|
|
||||||
|
|
||||||
|
# ---- pushing into this computer's DJ apps (`local_push.py`) -------------------
|
||||||
|
|
||||||
|
|
||||||
|
class LocalLibraryOut(BaseModel):
|
||||||
|
"""One DJ app's library on this computer, as a push target."""
|
||||||
|
|
||||||
|
platform: str
|
||||||
|
name: str
|
||||||
|
path: str | None = None
|
||||||
|
#: Found by the platform's own detection (False: the user's setting).
|
||||||
|
detected: bool = True
|
||||||
|
#: A FACT: `not_found`, `open_in_konduktor`, `cloud_synced`, `unreadable`.
|
||||||
|
blocked: str | None = None
|
||||||
|
running: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class LocalLibrariesOut(BaseModel):
|
||||||
|
libraries: list[LocalLibraryOut] = []
|
||||||
|
#: The shared folder pushed audio lives in, and where it is by default.
|
||||||
|
audio_root: str
|
||||||
|
audio_root_default: str
|
||||||
|
#: The shared folder's Normalise level (None: off).
|
||||||
|
level: ExportLevel | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class PushTargetOut(BaseModel):
|
||||||
|
platform: str
|
||||||
|
name: str
|
||||||
|
path: str | None = None
|
||||||
|
blocked: str | None = None
|
||||||
|
#: Not on this computer (`blocked` = not_found): passed over by the push
|
||||||
|
#: instead of blocking it.
|
||||||
|
skipped: bool = False
|
||||||
|
running: bool = False
|
||||||
|
add: int = 0
|
||||||
|
already: int = 0
|
||||||
|
remove: int = 0
|
||||||
|
#: Overwrite: the other sets pushed into this library, which it removes.
|
||||||
|
wipes_sets: list[str] = []
|
||||||
|
|
||||||
|
|
||||||
|
class PushPreview(BaseModel):
|
||||||
|
"""What a push would do now. Computed fresh; never stored."""
|
||||||
|
|
||||||
|
mode: Literal["merge", "overwrite"] = "merge"
|
||||||
|
tracks: int = 0
|
||||||
|
pushable: int = 0
|
||||||
|
#: Copies in the shared folder kept rather than copied again.
|
||||||
|
unchanged: int = 0
|
||||||
|
missing: list[str] = []
|
||||||
|
playlists: list[str] = []
|
||||||
|
total_bytes: int = 0
|
||||||
|
audio_root: str
|
||||||
|
free_bytes: int | None = None
|
||||||
|
enough_space: bool | None = None
|
||||||
|
normalised: int = 0
|
||||||
|
to_measure: int = 0
|
||||||
|
level_counts: dict[str, int] = {}
|
||||||
|
targets: list[PushTargetOut] = []
|
||||||
|
#: A FACT: `no_target`, `no_library_here` (none of the set's libraries
|
||||||
|
#: is on this computer), `nothing_to_push`, `target_unavailable`,
|
||||||
|
#: `app_running`, or null when it can run.
|
||||||
|
blocked: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class FsPlace(BaseModel):
|
class FsPlace(BaseModel):
|
||||||
"""A shortcut in the file browser's sidebar.
|
"""A shortcut in the file browser's sidebar.
|
||||||
|
|
||||||
@@ -740,3 +818,11 @@ class NormalizeRequest(BaseModel):
|
|||||||
measure: Literal["lufs", "rms"] = "lufs"
|
measure: Literal["lufs", "rms"] = "lufs"
|
||||||
target: float = -9.0
|
target: float = -9.0
|
||||||
ceiling: float = -1.0
|
ceiling: float = -1.0
|
||||||
|
|
||||||
|
|
||||||
|
class MidiExportRequest(BaseModel):
|
||||||
|
"""A controller mapping written to a file (`/api/midi/export`). Its shape
|
||||||
|
is the UI's (`lib/midi/mapping.ts`); only the version is checked here."""
|
||||||
|
dir: str
|
||||||
|
name: str
|
||||||
|
mapping: dict
|
||||||
@@ -12,6 +12,9 @@ python-multipart>=0.0.9 # multipart form parsing for cover-art upload
|
|||||||
# app-data dir. Both bundle cleanly into the frozen sidecar.
|
# app-data dir. Both bundle cleanly into the frozen sidecar.
|
||||||
dulwich>=0.22
|
dulwich>=0.22
|
||||||
platformdirs>=4.0
|
platformdirs>=4.0
|
||||||
|
# Is Traktor / rekordbox running? (core/apps_running.py — a push refuses while
|
||||||
|
# one is). Came only through pyrekordbox before; imported directly now.
|
||||||
|
psutil>=5.9
|
||||||
# Auto Hotcues: structural segmentation (McFee/Ellis Laplacian). Pure-Python,
|
# Auto Hotcues: structural segmentation (McFee/Ellis Laplacian). Pure-Python,
|
||||||
# ~150MB; numba/llvmlite ship Python 3.14 wheels (verified). No torch/native build.
|
# ~150MB; numba/llvmlite ship Python 3.14 wheels (verified). No torch/native build.
|
||||||
librosa>=0.11
|
librosa>=0.11
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
|||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
|
|
||||||
fail=0
|
fail=0
|
||||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_aac_gain.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py test_remote_normalize.py; do
|
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_aac_gain.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_midi_mappings.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_local_push.py test_traktor_file_block.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py test_remote_normalize.py; do
|
||||||
echo "──────────────────────────────────────────"
|
echo "──────────────────────────────────────────"
|
||||||
echo "▶ $t"
|
echo "▶ $t"
|
||||||
echo "──────────────────────────────────────────"
|
echo "──────────────────────────────────────────"
|
||||||
|
|||||||
@@ -150,6 +150,20 @@ check("paths are compared normalised, not as strings",
|
|||||||
exports.destination_conflict(LIB, str(work / "out") + "/./", ignore=s3.id) == "Ibiza")
|
exports.destination_conflict(LIB, str(work / "out") + "/./", ignore=s3.id) == "Ibiza")
|
||||||
exports.delete(LIB, s3.id)
|
exports.delete(LIB, s3.id)
|
||||||
|
|
||||||
|
print("== a set pushed into this computer's DJ apps ==")
|
||||||
|
check("a set saved before kinds existed loads as a folder export, merge",
|
||||||
|
(exports.get(LIB, s1.id).kind, exports.get(LIB, s1.id).mode) == ("folder", "merge"))
|
||||||
|
s4 = exports.create(LIB, name="Laptop", targets=["traktor"], destination="", kind="computer",
|
||||||
|
mode="overwrite")
|
||||||
|
check("kind and mode persist", (exports.get(LIB, s4.id).kind, exports.get(LIB, s4.id).mode)
|
||||||
|
== ("computer", "overwrite"))
|
||||||
|
exports.update(LIB, s4.id, mode="merge", kind="nonsense")
|
||||||
|
check("mode changes; an unknown kind is ignored",
|
||||||
|
(exports.get(LIB, s4.id).kind, exports.get(LIB, s4.id).mode) == ("computer", "merge"))
|
||||||
|
check("a computer set has no destination to clash over",
|
||||||
|
exports.destination_conflict(LIB, "", ignore=s1.id) is None)
|
||||||
|
exports.delete(LIB, s4.id)
|
||||||
|
|
||||||
print("== following track ids that change under a path remap ==")
|
print("== following track ids that change under a path remap ==")
|
||||||
exports.retarget(LIB, {all_tracks[0]: "Macintosh HD/:Moved/:one.mp3"})
|
exports.retarget(LIB, {all_tracks[0]: "Macintosh HD/:Moved/:one.mp3"})
|
||||||
check("a renamed id is followed",
|
check("a renamed id is followed",
|
||||||
|
|||||||
@@ -0,0 +1,437 @@
|
|||||||
|
"""Pushing an export set into this computer's Traktor / rekordbox library
|
||||||
|
(`local_push.py`), through the routes.
|
||||||
|
|
||||||
|
The source library is a temp copy of the real collection pointed at GENERATED
|
||||||
|
audio; the "local" Traktor collection pushed into is ANOTHER temp copy of the
|
||||||
|
real one — the user's own 8,485 entries — and the shared audio folder is a temp
|
||||||
|
folder. Prefs and app-data are redirected, and whether a DJ app is running is
|
||||||
|
faked (a real Traktor may be open on the machine running this).
|
||||||
|
|
||||||
|
What would fail SILENTLY, and matter at a gig:
|
||||||
|
|
||||||
|
* a merge touches nothing of the user's own: existing entries and playlists
|
||||||
|
render byte-identically, only new ENTRYs and the set's folder appear;
|
||||||
|
* a re-push of an unchanged set copies and writes nothing;
|
||||||
|
* the source wins: an edited cue or title reaches the pushed entry, and a
|
||||||
|
re-levelled copy is swapped in with the entry's size following;
|
||||||
|
* removal follows the set, but never takes a track another set holds, and a
|
||||||
|
rekordbox refusal keeps the track and reports it;
|
||||||
|
* the set's folder never takes over a folder of the user's with its name;
|
||||||
|
* overwrite leaves only this set, deleting the other sets' files;
|
||||||
|
* a running DJ app, the open library, and a failure mid-copy all leave the
|
||||||
|
library as it was.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import difflib
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
import warnings
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
warnings.filterwarnings("ignore")
|
||||||
|
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-push-appdata-")
|
||||||
|
os.environ.pop("KONDUKTOR_NML", None)
|
||||||
|
|
||||||
|
import av # noqa: E402
|
||||||
|
import numpy as np # noqa: E402
|
||||||
|
from fastapi.testclient import TestClient # noqa: E402
|
||||||
|
|
||||||
|
import konduktor.main as main # noqa: E402
|
||||||
|
from konduktor import history, local_push, paths, prefs # noqa: E402
|
||||||
|
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
||||||
|
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
|
||||||
|
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
|
||||||
|
from konduktor.core import apps_running # noqa: E402
|
||||||
|
|
||||||
|
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||||
|
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-push-"))
|
||||||
|
AUDIO = ROOT / "Music" / "Konduktor"
|
||||||
|
failed = False
|
||||||
|
|
||||||
|
|
||||||
|
def check(label, cond, detail=""):
|
||||||
|
global failed
|
||||||
|
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||||
|
if not cond:
|
||||||
|
failed = True
|
||||||
|
|
||||||
|
|
||||||
|
def make_mp3(path: Path, seed: int) -> Path:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
sr = 44100
|
||||||
|
t = np.arange(sr * 8) / sr
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
beat = (np.sin(2 * np.pi * 2 * t) > 0.6).astype(float)
|
||||||
|
x = np.vstack([0.3 * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.2 * rng.standard_normal(t.size))
|
||||||
|
for _ in range(2)]).astype(np.float32)
|
||||||
|
with av.open(str(path), "w", format="mp3") as c:
|
||||||
|
s = c.add_stream("libmp3lame", rate=sr, layout="stereo")
|
||||||
|
s.bit_rate = 192_000
|
||||||
|
for o in range(0, x.shape[1], 1152):
|
||||||
|
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout="stereo")
|
||||||
|
f.sample_rate, f.pts = sr, o
|
||||||
|
for p in s.encode(f):
|
||||||
|
c.mux(p)
|
||||||
|
for p in s.encode(None):
|
||||||
|
c.mux(p)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def source_library(n=5):
|
||||||
|
d = ROOT / "source"
|
||||||
|
d.mkdir(parents=True)
|
||||||
|
work = d / "collection.nml"
|
||||||
|
shutil.copy2(REAL, work)
|
||||||
|
st = TraktorStore(work)
|
||||||
|
entries = [e for e in st._nml.collection.entry if e.location and e.stems is None]
|
||||||
|
ids, files = [], []
|
||||||
|
for i, e in enumerate(entries[:n]):
|
||||||
|
path = make_mp3(d / "Music" / f"track{i}.mp3", seed=i)
|
||||||
|
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
|
||||||
|
e.cue_v2 = []
|
||||||
|
e.title = f"Track {i}"
|
||||||
|
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
|
||||||
|
ids.append(st._key_of(e))
|
||||||
|
files.append(path)
|
||||||
|
st.save()
|
||||||
|
return work, ids, files
|
||||||
|
|
||||||
|
|
||||||
|
def sha(p: Path) -> str:
|
||||||
|
return hashlib.sha256(p.read_bytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def wait(c, jid, timeout=300):
|
||||||
|
end = time.time() + timeout
|
||||||
|
while time.time() < end:
|
||||||
|
j = c.get(f"/api/jobs/{jid}").json()
|
||||||
|
if j["state"] != "running":
|
||||||
|
return j
|
||||||
|
time.sleep(0.05)
|
||||||
|
raise AssertionError("job did not finish")
|
||||||
|
|
||||||
|
|
||||||
|
def copy_of(source: Path) -> Path:
|
||||||
|
return AUDIO / local_push._rel_for(source)
|
||||||
|
|
||||||
|
|
||||||
|
def pushed(target: Path) -> dict[str, object]:
|
||||||
|
"""The target's entries that live in the shared audio folder, by file name."""
|
||||||
|
st = TraktorStore(target)
|
||||||
|
out = {}
|
||||||
|
for e in st._nml.collection.entry:
|
||||||
|
path = st.audio_path(st._key_of(e)) if e.location else None
|
||||||
|
if path and AUDIO in Path(path).parents:
|
||||||
|
out[Path(path).name] = e
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def top_level(target: Path) -> dict[str, object]:
|
||||||
|
ad = TraktorAdapter(target)
|
||||||
|
return {n.name: n for n in ad.playlist_tree()}
|
||||||
|
|
||||||
|
|
||||||
|
def removed_lines(before: str, after: str) -> list[str]:
|
||||||
|
return [l for l in difflib.unified_diff(before.splitlines(), after.splitlines(), lineterm="", n=0)
|
||||||
|
if l.startswith("-") and not l.startswith("---")]
|
||||||
|
|
||||||
|
|
||||||
|
src, ids, files = source_library()
|
||||||
|
target = ROOT / "laptop" / "Traktor 4.5.0" / "collection.nml"
|
||||||
|
target.parent.mkdir(parents=True)
|
||||||
|
shutil.copy2(REAL, target)
|
||||||
|
|
||||||
|
RUNNING: set[str] = set()
|
||||||
|
apps_running.running = lambda platforms: {p for p in platforms if p in RUNNING}
|
||||||
|
prefs.update_prefs({"localLibraries": {"traktor": str(target), "rekordbox": str(ROOT / "none" / "master.db")},
|
||||||
|
"localAudioRoot": str(AUDIO), "localNormalise": False})
|
||||||
|
|
||||||
|
with TestClient(main.app) as c:
|
||||||
|
r = c.post("/api/library/open", json={"path": str(src)})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
adapter = main.STATE.adapter
|
||||||
|
|
||||||
|
print("== the local libraries ==")
|
||||||
|
libs = {l["platform"]: l for l in c.get("/api/local-libraries").json()["libraries"]}
|
||||||
|
check("Traktor is the configured collection, usable", libs["traktor"]["path"] == str(target)
|
||||||
|
and libs["traktor"]["blocked"] is None and not libs["traktor"]["detected"], str(libs["traktor"]))
|
||||||
|
check("a rekordbox library that is not there is not_found", libs["rekordbox"]["blocked"] == "not_found")
|
||||||
|
|
||||||
|
print("== a computer set ==")
|
||||||
|
r = c.post("/api/exports", json={"name": "Gig", "kind": "computer", "targets": ["onelibrary"]})
|
||||||
|
check("a stick format is not a push target", r.status_code == 422, r.text)
|
||||||
|
gig = c.post("/api/exports", json={"name": "Gig", "kind": "computer", "targets": ["traktor"]}).json()
|
||||||
|
check("created with no destination, mode merge", gig["kind"] == "computer" and gig["mode"] == "merge"
|
||||||
|
and gig["destination"] == "", str(gig))
|
||||||
|
pl = c.post("/api/playlists", json={"name": "Peak"}).json()["id"]
|
||||||
|
c.put(f"/api/playlists/{pl}/entries", json={"track_ids": ids[:2]})
|
||||||
|
c.post(f"/api/exports/{gig['id']}/add", json={"playlist_ids": [pl], "track_ids": [ids[2]]})
|
||||||
|
adapter.set_cue(ids[0], slot=0, start_sec=1.0, cue_type="cue", name="Drop")
|
||||||
|
adapter.replace_grid(ids[0], [(0.5, 120.0)])
|
||||||
|
check("an export route refuses a computer set",
|
||||||
|
c.post(f"/api/exports/{gig['id']}/preview", json={}).status_code == 400)
|
||||||
|
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
t = pv["targets"][0]
|
||||||
|
check("the preview: three to add, nothing blocked", pv["blocked"] is None and pv["pushable"] == 3
|
||||||
|
and (t["add"], t["already"], t["remove"]) == (3, 0, 0), str(pv))
|
||||||
|
|
||||||
|
print("== the first push merges ==")
|
||||||
|
before = target.read_text()
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
check("the push runs", j["state"] == "done", str(j.get("error")))
|
||||||
|
check("each copy is its source, byte for byte",
|
||||||
|
all(copy_of(f).is_file() and sha(copy_of(f)) == sha(f) for f in files[:3]))
|
||||||
|
after = target.read_text()
|
||||||
|
gone = removed_lines(before, after)
|
||||||
|
check("nothing of the user's changed: only the entry count and the root folder's count",
|
||||||
|
all("<COLLECTION ENTRIES=" in l or "SUBNODES COUNT=" in l for l in gone), "\n".join(gone[:5]))
|
||||||
|
entries = pushed(target)
|
||||||
|
check("three entries in the shared folder", set(entries) == {"track0.mp3", "track1.mp3", "track2.mp3"},
|
||||||
|
str(list(entries)))
|
||||||
|
tree = top_level(target)
|
||||||
|
folder = tree.get("Gig")
|
||||||
|
names = {n.name for n in folder.children} if folder else set()
|
||||||
|
check("the set's folder holds its playlist and Other", names == {"Peak", "Other"}, str(names))
|
||||||
|
tk = TraktorAdapter(target)
|
||||||
|
tid = next(t.id for t in tk.tracks if t.title == "Track 0")
|
||||||
|
cues = tk.track_cues(tid)
|
||||||
|
check("the cue and grid crossed, the grid locked",
|
||||||
|
any(c_.slot == 0 and c_.name == "Drop" for c_ in cues.cues) and len(cues.grid_markers) == 1
|
||||||
|
and cues.grid_locked, str(cues))
|
||||||
|
check("the push is in the collection's version history",
|
||||||
|
len(history.list_history(target)) >= 2, str(history.list_history(target)))
|
||||||
|
|
||||||
|
print("== an unchanged re-push writes nothing ==")
|
||||||
|
stamp = target.stat().st_mtime_ns
|
||||||
|
inodes = {f.name: copy_of(f).stat().st_ino for f in files[:3]}
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
check("the preview: three already there", (pv["targets"][0]["add"], pv["targets"][0]["already"]) == (0, 3)
|
||||||
|
and pv["unchanged"] == 3, str(pv))
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
check("nothing copied", j["state"] == "done" and j["result"]["copied"] == 0, str(j.get("result")))
|
||||||
|
check("…the same files, and the collection not saved",
|
||||||
|
{f.name: copy_of(f).stat().st_ino for f in files[:3]} == inodes and target.stat().st_mtime_ns == stamp)
|
||||||
|
|
||||||
|
print("== the source wins ==")
|
||||||
|
adapter.set_cue(ids[0], slot=1, start_sec=2.0, cue_type="cue", name="Break")
|
||||||
|
adapter.set_track_metadata(ids[1], {"title": "Track 1 (edit)"})
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
tk = TraktorAdapter(target)
|
||||||
|
cues = tk.track_cues(tid)
|
||||||
|
check("the new cue reached the pushed entry, the old one kept, no duplicates",
|
||||||
|
j["state"] == "done" and sorted((c_.slot, c_.name) for c_ in cues.cues if c_.slot is not None)
|
||||||
|
== [(0, "Drop"), (1, "Break")], str(cues.cues))
|
||||||
|
check("the new title too", any(t.title == "Track 1 (edit)" for t in tk.tracks))
|
||||||
|
check("…and only those two were updated", j["result"]["targets"][0]["updated"] == 2, str(j["result"]))
|
||||||
|
|
||||||
|
print("== a re-levelled copy is swapped in ==")
|
||||||
|
prefs.update_prefs({"localNormalise": True, "localLevel": {"measure": "lufs", "target": -6.0, "ceiling": -0.5}})
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
check("the push runs", j["state"] == "done", str(j.get("error")))
|
||||||
|
changed = [f for f in files[:3] if sha(copy_of(f)) != sha(f)]
|
||||||
|
check("the copies changed level", j["result"]["normalised"] > 0 and changed, str(j.get("result")))
|
||||||
|
entries = pushed(target)
|
||||||
|
check("each entry's FILESIZE follows its new copy",
|
||||||
|
all(entries[f.name].info.filesize == round(copy_of(f).stat().st_size / 1024) for f in files[:3]))
|
||||||
|
check("no temporary file left", not list(AUDIO.rglob("*.konduktor-partial")))
|
||||||
|
prefs.update_prefs({"localNormalise": False})
|
||||||
|
wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
check("Normalise off: the source's own bytes back", all(sha(copy_of(f)) == sha(f) for f in files[:3]))
|
||||||
|
|
||||||
|
print("== a second set, sharing a track ==")
|
||||||
|
warm = c.post("/api/exports", json={"name": "Warmup", "kind": "computer", "targets": ["traktor"]}).json()
|
||||||
|
c.post(f"/api/exports/{warm['id']}/add", json={"track_ids": [ids[2], ids[3]]})
|
||||||
|
tk = TraktorAdapter(target)
|
||||||
|
tk.create_folder("Warmup") # the user's own folder, with the set's name
|
||||||
|
tk.save()
|
||||||
|
j = wait(c, c.post(f"/api/exports/{warm['id']}/push", json={}).json()["id"])
|
||||||
|
tree = top_level(target)
|
||||||
|
check("a user's folder with the set's name is left alone; the set's is suffixed",
|
||||||
|
j["state"] == "done" and "Warmup" in tree and "Warmup (Konduktor)" in tree
|
||||||
|
and not tree["Warmup"].children, str(list(tree)))
|
||||||
|
check("the shared track is one entry", sum(1 for n in pushed(target) if n == "track2.mp3") == 1
|
||||||
|
and len(pushed(target)) == 4, str(list(pushed(target))))
|
||||||
|
|
||||||
|
print("== removal follows the set ==")
|
||||||
|
c.post(f"/api/exports/{gig['id']}/remove", json={"track_ids": [ids[2]]})
|
||||||
|
c.put(f"/api/playlists/{pl}/entries", json={"track_ids": ids[:1]})
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
check("the preview counts two to remove", pv["targets"][0]["remove"] == 2, str(pv["targets"]))
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
names = set(pushed(target))
|
||||||
|
check("track1 left the collection, track2 stays (Warmup holds it)",
|
||||||
|
j["state"] == "done" and "track1.mp3" not in names and "track2.mp3" in names, str(names))
|
||||||
|
check("track1's copy deleted, track2's kept",
|
||||||
|
not copy_of(files[1]).exists() and copy_of(files[2]).exists())
|
||||||
|
check("one removal reported", j["result"]["targets"][0]["removed"] == 1, str(j["result"]))
|
||||||
|
|
||||||
|
print("== a library missing on this computer is skipped, not a block ==")
|
||||||
|
# The set's targets are shared by every computer opening the library;
|
||||||
|
# this one has no rekordbox (its pref points at nothing).
|
||||||
|
c.patch(f"/api/exports/{gig['id']}", json={"targets": ["traktor", "rekordbox"]})
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
by = {t["platform"]: t for t in pv["targets"]}
|
||||||
|
check("the preview runs, rekordbox skipped", pv["blocked"] is None and by["rekordbox"]["skipped"]
|
||||||
|
and by["rekordbox"]["blocked"] == "not_found" and not by["traktor"]["skipped"], str(pv))
|
||||||
|
RUNNING.add("rekordbox")
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
check("a skipped library's app running blocks nothing", pv["blocked"] is None, str(pv))
|
||||||
|
RUNNING.clear()
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
check("the push runs into Traktor alone and names the skipped one", j["state"] == "done"
|
||||||
|
and [t["name"] for t in j["result"]["targets"]] == ["Traktor"]
|
||||||
|
and j["result"]["skipped_targets"] == ["Rekordbox"], str(j.get("error") or j["result"]))
|
||||||
|
c.patch(f"/api/exports/{gig['id']}", json={"targets": ["rekordbox"]})
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
check("none of its libraries here blocks it", pv["blocked"] == "no_library_here", str(pv))
|
||||||
|
check("…and the run is refused", c.post(f"/api/exports/{gig['id']}/push", json={}).status_code == 409)
|
||||||
|
c.patch(f"/api/exports/{gig['id']}", json={"targets": ["traktor"]})
|
||||||
|
|
||||||
|
print("== refusals ==")
|
||||||
|
RUNNING.add("traktor")
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
check("Traktor running blocks the push", pv["blocked"] == "app_running" and pv["targets"][0]["running"], str(pv))
|
||||||
|
check("…and the run is refused", c.post(f"/api/exports/{gig['id']}/push", json={}).status_code == 409)
|
||||||
|
RUNNING.clear()
|
||||||
|
prefs.update_prefs({"localLibraries": {"traktor": str(src)}})
|
||||||
|
libs = {l["platform"]: l for l in c.get("/api/local-libraries").json()["libraries"]}
|
||||||
|
check("the library open in Konduktor is never a target", libs["traktor"]["blocked"] == "open_in_konduktor",
|
||||||
|
str(libs["traktor"]))
|
||||||
|
wrong = ROOT / "not-a-collection.nml"
|
||||||
|
wrong.write_text("hello")
|
||||||
|
prefs.update_prefs({"localLibraries": {"traktor": str(wrong)}})
|
||||||
|
libs = {l["platform"]: l for l in c.get("/api/local-libraries").json()["libraries"]}
|
||||||
|
check("a file that is not a Traktor collection is unreadable", libs["traktor"]["blocked"] == "unreadable",
|
||||||
|
str(libs["traktor"]))
|
||||||
|
prefs.update_prefs({"localLibraries": {"traktor": str(target), "rekordbox": str(ROOT / "none" / "master.db")}})
|
||||||
|
|
||||||
|
print("== a failure mid-copy leaves the library and the folder as they were ==")
|
||||||
|
c.post(f"/api/exports/{gig['id']}/add", json={"track_ids": [ids[4]]})
|
||||||
|
real_write = local_push.write_copy
|
||||||
|
|
||||||
|
def broken(adapter_, planned, partial, handle, advance):
|
||||||
|
partial.write_bytes(b"half")
|
||||||
|
raise OSError("disk unplugged")
|
||||||
|
|
||||||
|
local_push.write_copy = broken
|
||||||
|
before = target.read_bytes()
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
local_push.write_copy = real_write
|
||||||
|
check("the push fails", j["state"] == "failed", str(j))
|
||||||
|
check("…the collection untouched, no file placed",
|
||||||
|
target.read_bytes() == before and not copy_of(files[4]).exists()
|
||||||
|
and not list(AUDIO.rglob("*.konduktor-partial")))
|
||||||
|
|
||||||
|
print("== overwrite ==")
|
||||||
|
c.patch(f"/api/exports/{warm['id']}", json={"mode": "overwrite"})
|
||||||
|
pv = c.post(f"/api/exports/{warm['id']}/push/preview", json={}).json()
|
||||||
|
check("the preview names the set it removes", pv["targets"][0]["wipes_sets"] == ["Gig"], str(pv["targets"]))
|
||||||
|
j = wait(c, c.post(f"/api/exports/{warm['id']}/push", json={}).json()["id"])
|
||||||
|
check("the overwrite runs", j["state"] == "done", str(j.get("error")))
|
||||||
|
st = TraktorStore(target)
|
||||||
|
check("the collection holds only Warmup's two tracks", len(st._nml.collection.entry) == 2
|
||||||
|
and set(pushed(target)) == {"track2.mp3", "track3.mp3"}, str(len(st._nml.collection.entry)))
|
||||||
|
tree = top_level(target)
|
||||||
|
check("…in its folder", set(tree) == {"Warmup"}, str(list(tree)))
|
||||||
|
check("Gig's own file is deleted, Warmup's kept",
|
||||||
|
not copy_of(files[0]).exists() and copy_of(files[2]).exists() and copy_of(files[3]).exists())
|
||||||
|
check("the replaced collection is in the version history",
|
||||||
|
len(history.list_history(target)) >= 3)
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
check("Gig is forgotten there: every track to add again",
|
||||||
|
pv["targets"][0]["already"] == 0 and pv["targets"][0]["add"] == pv["pushable"], str(pv["targets"]))
|
||||||
|
c.patch(f"/api/exports/{warm['id']}", json={"mode": "merge"})
|
||||||
|
pv = c.post(f"/api/exports/{warm['id']}/push/preview", json={}).json()
|
||||||
|
check("a merge after the overwrite finds Warmup's tracks", pv["targets"][0]["already"] == 2, str(pv["targets"]))
|
||||||
|
|
||||||
|
# ---- rekordbox, when installed --------------------------------------------------
|
||||||
|
from konduktor.adapters.rekordbox import discovery as rb_discovery
|
||||||
|
|
||||||
|
found = rb_discovery.detect_libraries()
|
||||||
|
if not found:
|
||||||
|
print("== rekordbox: not installed here, skipped ==")
|
||||||
|
else:
|
||||||
|
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter
|
||||||
|
from konduktor.core.adapter import Unsupported
|
||||||
|
|
||||||
|
print("== rekordbox: merge ==")
|
||||||
|
rb_dir = ROOT / "rekordbox"
|
||||||
|
rb_dir.mkdir()
|
||||||
|
real_db = Path(found[0]["path"])
|
||||||
|
for name in ("master.db", "masterPlaylists6.xml"):
|
||||||
|
if (real_db.parent / name).is_file():
|
||||||
|
shutil.copy2(real_db.parent / name, rb_dir / name)
|
||||||
|
rb = rb_dir / "master.db"
|
||||||
|
probe = RekordboxAdapter(rb)
|
||||||
|
synced, count = probe.capabilities().readonly_cause == "cloud_synced", len(probe.tracks)
|
||||||
|
probe.close()
|
||||||
|
if synced:
|
||||||
|
print(" (the local rekordbox library is cloud-synced: checking it is refused)")
|
||||||
|
prefs.update_prefs({"localLibraries": {"traktor": str(target), "rekordbox": str(rb)}})
|
||||||
|
rbset = c.post("/api/exports", json={"name": "RB Gig", "kind": "computer", "targets": ["rekordbox"]}).json()
|
||||||
|
c.post(f"/api/exports/{rbset['id']}/add", json={"track_ids": ids[:2]})
|
||||||
|
pv = c.post(f"/api/exports/{rbset['id']}/push/preview", json={}).json()
|
||||||
|
if synced:
|
||||||
|
check("a cloud-synced library is refused", pv["blocked"] == "target_unavailable"
|
||||||
|
and pv["targets"][0]["blocked"] == "cloud_synced", str(pv))
|
||||||
|
else:
|
||||||
|
j = wait(c, c.post(f"/api/exports/{rbset['id']}/push", json={}).json()["id"])
|
||||||
|
check("the push runs", j["state"] == "done", str(j.get("error")))
|
||||||
|
ad = RekordboxAdapter(rb)
|
||||||
|
mine = [t for t in ad.tracks if t.filepath and str(AUDIO) in t.filepath]
|
||||||
|
tree = {n.name: n for n in ad.playlist_tree()}
|
||||||
|
tid = next((t.id for t in mine if t.title == "Track 0"), None)
|
||||||
|
cues = ad.track_cues(tid) if tid else None
|
||||||
|
ad.close()
|
||||||
|
check("two tracks added beside the user's", len(mine) == 2, str([t.title for t in mine]))
|
||||||
|
check("the set's folder", "RB Gig" in tree, str(list(tree)))
|
||||||
|
check("the cues crossed", cues is not None and any(c_.slot == 0 for c_ in cues.cues), str(cues))
|
||||||
|
backups = list((paths.app_data_dir() / "local_push" / "backups" / "rekordbox").iterdir())
|
||||||
|
check("the library was backed up first", backups and (backups[0] / "master.db").is_file())
|
||||||
|
|
||||||
|
print("== rekordbox: a track it will not remove is kept and reported ==")
|
||||||
|
real_remove = RekordboxAdapter.remove_tracks
|
||||||
|
|
||||||
|
def refuse(self, track_ids):
|
||||||
|
raise Unsupported("“Track 1” is in a History list in Rekordbox")
|
||||||
|
|
||||||
|
RekordboxAdapter.remove_tracks = refuse
|
||||||
|
c.post(f"/api/exports/{rbset['id']}/remove", json={"track_ids": [ids[1]]})
|
||||||
|
j = wait(c, c.post(f"/api/exports/{rbset['id']}/push", json={}).json()["id"])
|
||||||
|
RekordboxAdapter.remove_tracks = real_remove
|
||||||
|
res = j.get("result") or {}
|
||||||
|
check("the push still completes, reporting the kept track",
|
||||||
|
j["state"] == "done" and res["targets"][0]["kept"], str(j.get("error") or res))
|
||||||
|
check("…whose file stays", copy_of(files[1]).exists())
|
||||||
|
j = wait(c, c.post(f"/api/exports/{rbset['id']}/push", json={}).json()["id"])
|
||||||
|
ad = RekordboxAdapter(rb)
|
||||||
|
left = [t for t in ad.tracks if t.filepath and str(AUDIO) in t.filepath]
|
||||||
|
ad.close()
|
||||||
|
check("the next push removes it", j["state"] == "done" and len(left) == 1, str([t.title for t in left]))
|
||||||
|
|
||||||
|
print("== rekordbox: overwrite ==")
|
||||||
|
(rb_dir / "master.db-wal").write_bytes(b"stale")
|
||||||
|
c.patch(f"/api/exports/{rbset['id']}", json={"mode": "overwrite"})
|
||||||
|
j = wait(c, c.post(f"/api/exports/{rbset['id']}/push", json={}).json()["id"])
|
||||||
|
check("the overwrite runs", j["state"] == "done", str(j.get("error")))
|
||||||
|
ad = RekordboxAdapter(rb)
|
||||||
|
titles = [t.title for t in ad.tracks]
|
||||||
|
tree = [n.name for n in ad.playlist_tree()]
|
||||||
|
ad.close()
|
||||||
|
check("the library holds only the set", titles == ["Track 0"], f"{count} -> {titles}")
|
||||||
|
check("…in its folder", tree == ["RB Gig"], str(tree))
|
||||||
|
check("the stale WAL is gone", not (rb_dir / "master.db-wal").exists())
|
||||||
|
|
||||||
|
print("== the ledger and sets survive as plain data ==")
|
||||||
|
sets = {s["name"]: s for s in c.get("/api/exports").json()}
|
||||||
|
check("kind and mode persist", sets["Warmup"]["kind"] == "computer" and sets["Warmup"]["mode"] == "merge")
|
||||||
|
|
||||||
|
shutil.rmtree(ROOT, ignore_errors=True)
|
||||||
|
print()
|
||||||
|
print("RESULT:", "SOME FAILED" if failed else "ALL PASSED")
|
||||||
|
raise SystemExit(1 if failed else 0)
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""MIDI controller mappings moved to and from FILES (`/api/midi/export`,
|
||||||
|
`/api/midi/import`) — the only backend part of controller support; the
|
||||||
|
mapping itself lives in userprefs and is validated by the UI.
|
||||||
|
|
||||||
|
Pins what would hurt silently: an export never overwrites a file (a shared
|
||||||
|
mapping saved twice must not replace the first), the name cannot steer the
|
||||||
|
file outside the chosen folder, and import refuses anything that is not a
|
||||||
|
small version-1 JSON object rather than handing the UI garbage. The file
|
||||||
|
browser's `suffix` filter lists the mapping files.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from konduktor import prefs
|
||||||
|
|
||||||
|
_TMP = tempfile.TemporaryDirectory()
|
||||||
|
prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json"
|
||||||
|
prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json"
|
||||||
|
|
||||||
|
from konduktor.main import fs_list, midi_export, midi_import # noqa: E402
|
||||||
|
from konduktor.schemas import MidiExportRequest # noqa: E402
|
||||||
|
|
||||||
|
failed = False
|
||||||
|
|
||||||
|
|
||||||
|
def check(label, cond, detail=""):
|
||||||
|
global failed
|
||||||
|
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||||
|
if not cond:
|
||||||
|
failed = True
|
||||||
|
|
||||||
|
|
||||||
|
def refused(fn, status):
|
||||||
|
try:
|
||||||
|
fn()
|
||||||
|
except HTTPException as e:
|
||||||
|
return e.status_code == status
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
folder = Path(_TMP.name) / "maps"
|
||||||
|
folder.mkdir()
|
||||||
|
mapping = {"version": 1, "shift": "note:1:63", "bindings": {"note:1:11": {"encoding": "button", "normal": "deck.A.play"}}}
|
||||||
|
|
||||||
|
print("export")
|
||||||
|
first = Path(midi_export(MidiExportRequest(dir=str(folder), name="DDJ-400", mapping=mapping))["path"])
|
||||||
|
check("written as <name>.konduktor-midi.json", first.name == "DDJ-400.konduktor-midi.json")
|
||||||
|
check("holds the mapping", json.loads(first.read_text()) == mapping)
|
||||||
|
second = Path(midi_export(MidiExportRequest(dir=str(folder), name="DDJ-400", mapping={"version": 1}))["path"])
|
||||||
|
check("never overwrites: a second export is -2", second.name == "DDJ-400-2.konduktor-midi.json")
|
||||||
|
check("the first file is untouched", json.loads(first.read_text()) == mapping)
|
||||||
|
sneaky = Path(midi_export(MidiExportRequest(dir=str(folder), name="../../escape", mapping=mapping))["path"])
|
||||||
|
check("a name cannot leave the folder", sneaky.parent == folder, str(sneaky))
|
||||||
|
check("a missing folder is refused", refused(lambda: midi_export(MidiExportRequest(dir=str(folder / "nope"), name="x", mapping=mapping)), 400))
|
||||||
|
check("a non-mapping is refused", refused(lambda: midi_export(MidiExportRequest(dir=str(folder), name="x", mapping={"version": 9})), 400))
|
||||||
|
|
||||||
|
print("import")
|
||||||
|
check("reads back what was exported", midi_import(str(first))["mapping"] == mapping)
|
||||||
|
bad = folder / "bad.konduktor-midi.json"
|
||||||
|
bad.write_text("{not json")
|
||||||
|
check("invalid JSON refused", refused(lambda: midi_import(str(bad)), 400))
|
||||||
|
bad.write_text(json.dumps([1, 2]))
|
||||||
|
check("not an object refused", refused(lambda: midi_import(str(bad)), 400))
|
||||||
|
bad.write_text(json.dumps({"version": 2}))
|
||||||
|
check("wrong version refused", refused(lambda: midi_import(str(bad)), 400))
|
||||||
|
big = folder / "big.konduktor-midi.json"
|
||||||
|
big.write_text(json.dumps({"version": 1, "pad": "x" * 1_100_000}))
|
||||||
|
check("an oversized file refused", refused(lambda: midi_import(str(big)), 400))
|
||||||
|
check("a missing file is 404", refused(lambda: midi_import(str(folder / "absent.json")), 404))
|
||||||
|
|
||||||
|
print("file browser")
|
||||||
|
(folder / "notes.json").write_text("{}")
|
||||||
|
listed = {f.name for f in fs_list(path=str(folder), suffix=".konduktor-midi.json").files}
|
||||||
|
check("the suffix lists mapping files only", "notes.json" not in listed and first.name in listed, str(listed))
|
||||||
|
|
||||||
|
sys.exit(1 if failed else 0)
|
||||||
@@ -204,6 +204,25 @@ check("an index past the end appends", after[-1] == more[1])
|
|||||||
check("capabilities say Traktor holds duplicates",
|
check("capabilities say Traktor holds duplicates",
|
||||||
client.get("/api/capabilities").json()["playlists"]["duplicates"] is True)
|
client.get("/api/capabilities").json()["playlists"]["duplicates"] is True)
|
||||||
|
|
||||||
|
before = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()]
|
||||||
|
outsider = next(t["id"] for t in client.get("/api/tracks", params={"limit": 50}).json()["items"]
|
||||||
|
if t["id"] not in before)
|
||||||
|
picked = [first[0], rest[0], outsider] # first[0] is in there twice
|
||||||
|
r = client.post(f"/api/playlists/{target}/remove",
|
||||||
|
json={"track_ids": picked, "dry_run": True}).json()
|
||||||
|
check("a dry-run remove counts tracks held and entries (both copies) and changes nothing",
|
||||||
|
r["tracks"] == 2 and r["removed"] == 3
|
||||||
|
and [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()] == before)
|
||||||
|
r = client.post(f"/api/playlists/{target}/remove", json={"track_ids": picked}).json()
|
||||||
|
after = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()]
|
||||||
|
check("remove drops every copy and keeps the rest in order",
|
||||||
|
r["removed"] == 3 and r["count"] == len(before) - 3
|
||||||
|
and after == [t for t in before if t not in picked])
|
||||||
|
r = client.post(f"/api/playlists/{target}/remove", json={"track_ids": [outsider]}).json()
|
||||||
|
check("removing tracks it does not hold changes nothing", r["removed"] == 0 and r["count"] == len(after))
|
||||||
|
check("remove from an unknown playlist is a 404",
|
||||||
|
client.post("/api/playlists/nope/remove", json={"track_ids": picked}).status_code == 404)
|
||||||
|
|
||||||
box = client.post("/api/playlists/folders", json={"name": "Konduktor Drop Box"}).json()["id"]
|
box = client.post("/api/playlists/folders", json={"name": "Konduktor Drop Box"}).json()["id"]
|
||||||
r = client.post("/api/playlists/move", json={"node_id": target, "parent_id": box, "index": 0})
|
r = client.post("/api/playlists/move", json={"node_id": target, "parent_id": box, "index": 0})
|
||||||
check("move answers the playlist's id", r.status_code == 200 and r.json()["id"] == target)
|
check("move answers the playlist's id", r.status_code == 200 and r.json()["id"] == target)
|
||||||
|
|||||||
@@ -263,6 +263,34 @@ with tempfile.TemporaryDirectory() as d:
|
|||||||
check("set_analysed_grid pairs the marker with a companion",
|
check("set_analysed_grid pairs the marker with a companion",
|
||||||
cues.grid_markers[0].companion is not None)
|
cues.grid_markers[0].companion is not None)
|
||||||
|
|
||||||
|
# ---- replace_cues: a pushed track brought up to date ------------------------
|
||||||
|
print("== replace_cues makes the prep exactly the given one ==")
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
from konduktor.core.model import CuePoint, GridMarker, TrackCues # noqa: E402
|
||||||
|
|
||||||
|
work = Path(d) / "collection.nml"
|
||||||
|
shutil.copy2(REAL, work)
|
||||||
|
adapter = TraktorAdapter(work)
|
||||||
|
# A real entry carrying a grid WITH its white companion, hot cues and a lock.
|
||||||
|
tid = next(t.id for t in adapter.tracks
|
||||||
|
if t.grid_marker_count == 1 and t.hotcue_count >= 2
|
||||||
|
and adapter.track_cues(t.id).grid_markers[0].companion is not None)
|
||||||
|
want = TrackCues(
|
||||||
|
grid_markers=[GridMarker(start=0.25, bpm=124.0)], grid_locked=False,
|
||||||
|
cues=[CuePoint(start=4.0, length=0.0, slot=2, name="Drop"),
|
||||||
|
CuePoint(start=8.0, length=2.0, slot=3, type="loop"),
|
||||||
|
CuePoint(start=12.0, length=0.0, role="memory", name="Mem")])
|
||||||
|
got = adapter.replace_cues(tid, want)
|
||||||
|
check("the grid is exactly the new one, no companion invented",
|
||||||
|
[(m.start, m.bpm, m.companion) for m in got.grid_markers] == [(0.25, 124.0, None)],
|
||||||
|
str(got.grid_markers))
|
||||||
|
check("only the given cues remain, on their pads, the memory cue as one",
|
||||||
|
sorted((c.slot, c.role, c.name) for c in got.cues if c.slot is not None) == [(2, "hotcue", "Drop"), (3, "hotcue", None)]
|
||||||
|
and [c.name for c in got.cues if c.role == "memory"] == ["Mem"], str(got.cues))
|
||||||
|
again = adapter.replace_cues(tid, want)
|
||||||
|
check("replacing with the same prep is stable",
|
||||||
|
[(c.slot, c.start, c.role) for c in again.cues] == [(c.slot, c.start, c.role) for c in got.cues])
|
||||||
|
|
||||||
# ---- remap rebuilds the index (track ids change) --------------------------
|
# ---- remap rebuilds the index (track ids change) --------------------------
|
||||||
print("== a path remap rebuilds the projection, because track ids change ==")
|
print("== a path remap rebuilds the projection, because track ids change ==")
|
||||||
with tempfile.TemporaryDirectory() as d:
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
|||||||
@@ -0,0 +1,353 @@
|
|||||||
|
"""Traktor's own block inside an audio file — removed from every copy made for a
|
||||||
|
Traktor library, so Traktor cannot restore its stale grid over the entry's.
|
||||||
|
|
||||||
|
Measured in Traktor 4.5 (2026-10-24, see `adapters/traktor/file_block.py`): an
|
||||||
|
entry Konduktor wrote has no MODIFIED_DATE, so Traktor re-reads the file and
|
||||||
|
takes the block's BPM (`HBPM`) over the collection's, LOCK or not. With the
|
||||||
|
block removed from the copy, the entry's grid, lock, cues — and the art, which
|
||||||
|
Traktor still imports from the file's ordinary tags — all survive.
|
||||||
|
|
||||||
|
Self-contained: generated audio in each format carrying a block that says 175
|
||||||
|
while the library's grid says 176, and collections built from Konduktor's own
|
||||||
|
empty Traktor skeleton. Pins:
|
||||||
|
- `file_block`: each format's block found and removed, everything else in
|
||||||
|
the file kept (audio sample-identical, other tags, a foreign PRIV frame),
|
||||||
|
a file without one never rewritten, a garbage file refused quietly;
|
||||||
|
- export: every copy for a Traktor target loses the block, the SOURCE keeps
|
||||||
|
it, the manifest records `prepared`, a re-export rewrites nothing, a copy
|
||||||
|
kept from an export made before this (no `prepared`) is cleaned IN PLACE
|
||||||
|
rather than copied again, a target without the hook leaves the block, and
|
||||||
|
adding Traktor to such a set cleans the kept copies;
|
||||||
|
- local push: the shared folder's copies lose it, the ledger records it;
|
||||||
|
- import: a copied file loses it, a file added in place is never touched.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import struct
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fileblock-appdata-")
|
||||||
|
os.environ.pop("KONDUKTOR_NML", None)
|
||||||
|
|
||||||
|
import av # noqa: E402
|
||||||
|
import numpy as np # noqa: E402
|
||||||
|
import soundfile as sf # noqa: E402
|
||||||
|
from mutagen import File as MutagenFile # noqa: E402
|
||||||
|
from mutagen.flac import FLAC # noqa: E402
|
||||||
|
from mutagen.id3 import APIC, ID3, PRIV, TIT2 # noqa: E402
|
||||||
|
from mutagen.mp4 import MP4, MP4Cover # noqa: E402
|
||||||
|
|
||||||
|
from konduktor import exporter, exports, importer, local_push, prefs # noqa: E402
|
||||||
|
from konduktor.adapters.traktor import file_block # noqa: E402
|
||||||
|
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
||||||
|
from konduktor.adapters.traktor.export import SKELETON # noqa: E402
|
||||||
|
from konduktor.app_state import STATE # noqa: E402
|
||||||
|
from konduktor.core import apps_running, pyav # noqa: E402
|
||||||
|
from konduktor.core import export as core_export # noqa: E402
|
||||||
|
from konduktor.core.export import ExportPayload, ExportTrack # noqa: E402
|
||||||
|
from konduktor.core.model import GridMarker, Track, TrackCues # noqa: E402
|
||||||
|
from konduktor.exporter import _read_manifest as read_manifest # noqa: E402
|
||||||
|
from konduktor.jobs import JOBS # noqa: E402
|
||||||
|
|
||||||
|
failed = False
|
||||||
|
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-fileblock-"))
|
||||||
|
def _jpeg() -> bytes:
|
||||||
|
import io
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
Image.new("RGB", (8, 8), (200, 40, 90)).save(buf, "JPEG")
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
JPEG = _jpeg() # a real (tiny) cover, so the exporters read it
|
||||||
|
|
||||||
|
|
||||||
|
def check(label, cond, detail=""):
|
||||||
|
global failed
|
||||||
|
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||||
|
if not cond:
|
||||||
|
failed = True
|
||||||
|
|
||||||
|
|
||||||
|
# ---- generated audio, each carrying a block that says 175 BPM ------------------------
|
||||||
|
|
||||||
|
def block(bpm: float) -> bytes:
|
||||||
|
"""A minimal `DMRT` tree as Traktor writes it: reversed 4CCs, each chunk
|
||||||
|
= name + payload size + child count + payload."""
|
||||||
|
def chunk(name: str, payload: bytes, children: int = 0) -> bytes:
|
||||||
|
return name[::-1].encode() + struct.pack("<II", len(payload), children) + payload
|
||||||
|
data = chunk("DATA", chunk("HBPM", struct.pack("<f", bpm)), 1)
|
||||||
|
hdr = chunk("HDR ", chunk("VRSN", struct.pack("<I", 7)), 1)
|
||||||
|
return chunk("DMRT", hdr + data, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def music(seconds=6, sr=44100, seed=0):
|
||||||
|
t = np.arange(int(sr * seconds)) / sr
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
beat = (np.sin(2 * np.pi * 2 * t) > 0.6).astype(float)
|
||||||
|
return np.vstack([0.3 * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.2 * rng.standard_normal(t.size))
|
||||||
|
for _ in range(2)]).astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
def encode(path: Path, fmt: str, codec: str, frame: int, seed: int):
|
||||||
|
x = music(seed=seed)
|
||||||
|
with av.open(str(path), "w", format=fmt) as c:
|
||||||
|
s = c.add_stream(codec, rate=44100, layout="stereo")
|
||||||
|
s.bit_rate = 192_000
|
||||||
|
for o in range(0, x.shape[1], frame):
|
||||||
|
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + frame]), format="fltp", layout="stereo")
|
||||||
|
f.sample_rate, f.pts = 44100, o
|
||||||
|
for p in s.encode(f):
|
||||||
|
c.mux(p)
|
||||||
|
for p in s.encode(None):
|
||||||
|
c.mux(p)
|
||||||
|
|
||||||
|
|
||||||
|
def make(path: Path, seed: int, *, with_block: bool = True) -> Path:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
ext = path.suffix
|
||||||
|
if ext == ".mp3":
|
||||||
|
encode(path, "mp3", "libmp3lame", 1152, seed)
|
||||||
|
tags = ID3()
|
||||||
|
tags.add(TIT2(encoding=3, text=path.stem))
|
||||||
|
tags.add(APIC(encoding=3, mime="image/jpeg", type=3, desc="", data=JPEG))
|
||||||
|
tags.add(PRIV(owner="SomeOtherApp", data=b"keep me"))
|
||||||
|
if with_block:
|
||||||
|
tags.add(PRIV(owner="TRAKTOR4", data=block(175.0)))
|
||||||
|
tags.save(path, v2_version=3)
|
||||||
|
elif ext == ".m4a":
|
||||||
|
encode(path, "ipod", "aac", 1024, seed)
|
||||||
|
m = MP4(path)
|
||||||
|
if m.tags is None:
|
||||||
|
m.add_tags()
|
||||||
|
m.tags["\xa9nam"] = [path.stem]
|
||||||
|
m.tags["covr"] = [MP4Cover(JPEG, imageformat=MP4Cover.FORMAT_JPEG)]
|
||||||
|
m.save()
|
||||||
|
if with_block:
|
||||||
|
m = MP4(path)
|
||||||
|
# As Traktor writes it: an atom mutagen cannot parse, kept raw.
|
||||||
|
m.tags._failed_atoms["NITR"] = [b"\x00\x00\x00\x08NTKB" + b"\x00" * 4 + block(175.0)]
|
||||||
|
m.save()
|
||||||
|
elif ext == ".flac":
|
||||||
|
sf.write(str(path), music(seed=seed).T, 44100, subtype="PCM_16")
|
||||||
|
f = FLAC(path)
|
||||||
|
f["title"] = path.stem
|
||||||
|
if with_block:
|
||||||
|
f["traktor4"] = base64.b64encode(block(175.0)).decode()
|
||||||
|
f.save()
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def pcm(path: Path) -> list[np.ndarray]:
|
||||||
|
out = []
|
||||||
|
with pyav.open_input(str(path)) as c:
|
||||||
|
for s in c.streams.audio:
|
||||||
|
c.seek(0)
|
||||||
|
out.append(np.concatenate([f.to_ndarray().ravel() for f in c.decode(s)]))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def tag_keys(path: Path) -> set[str]:
|
||||||
|
tags = MutagenFile(path).tags
|
||||||
|
return set(tags.keys()) | set(getattr(tags, "_failed_atoms", {}))
|
||||||
|
|
||||||
|
|
||||||
|
print("== file_block on each format ==")
|
||||||
|
unit = ROOT / "unit"
|
||||||
|
for name in ("a.mp3", "b.m4a", "c.flac"):
|
||||||
|
src = make(unit / "src" / name, seed=1)
|
||||||
|
copy = unit / "copy" / (name + ".konduktor-partial") # as the runners strip it
|
||||||
|
copy.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(src, copy)
|
||||||
|
before = tag_keys(copy)
|
||||||
|
check(f"{name}: the block is found", file_block.has_block(copy))
|
||||||
|
check(f"{name}: strip reports it removed one", file_block.strip(copy) is True)
|
||||||
|
check(f"{name}: none is left", not file_block.has_block(copy))
|
||||||
|
lost = before - tag_keys(copy)
|
||||||
|
check(f"{name}: only the block is gone from the tags",
|
||||||
|
len(lost) == 1 and ("TRAKTOR4" in next(iter(lost)) or next(iter(lost)) in ("NITR", "traktor4")),
|
||||||
|
str(lost))
|
||||||
|
check(f"{name}: the audio is sample-identical",
|
||||||
|
all(np.array_equal(a, b) for a, b in zip(pcm(src), pcm(copy))))
|
||||||
|
data, mtime = copy.read_bytes(), copy.stat().st_mtime_ns
|
||||||
|
check(f"{name}: a second strip changes nothing, and does not rewrite the file",
|
||||||
|
file_block.strip(copy) is False and copy.read_bytes() == data and copy.stat().st_mtime_ns == mtime)
|
||||||
|
mp3 = unit / "copy" / "a.mp3.konduktor-partial"
|
||||||
|
id3 = ID3(mp3)
|
||||||
|
check("mp3: a foreign PRIV frame and the cover stay", "PRIV:SomeOtherApp:keep me" in id3 and id3.getall("APIC"))
|
||||||
|
check("mp3: the file keeps its ID3 version (2.3)", id3.version[:2] == (2, 3))
|
||||||
|
check("m4a: the cover stays", "covr" in MP4(unit / "copy" / "b.m4a.konduktor-partial").tags)
|
||||||
|
clean = make(unit / "clean.mp3", seed=2, with_block=False)
|
||||||
|
data, mtime = clean.read_bytes(), clean.stat().st_mtime_ns
|
||||||
|
check("a file without a block is never rewritten",
|
||||||
|
file_block.strip(clean) is False and clean.read_bytes() == data and clean.stat().st_mtime_ns == mtime)
|
||||||
|
junk = unit / "junk.mp3"
|
||||||
|
junk.write_bytes(b"ID3" + b"\xff" * 64)
|
||||||
|
check("an unreadable file is refused quietly", file_block.strip(junk) is False and not file_block.has_block(junk))
|
||||||
|
|
||||||
|
|
||||||
|
# ---- a source library whose grids (176) disagree with the files' blocks (175) ---------
|
||||||
|
|
||||||
|
lib_root = ROOT / "MyMusic"
|
||||||
|
files = [make(lib_root / "DnB" / n, seed=i) for i, n in enumerate(("one.mp3", "two.m4a", "three.flac"))]
|
||||||
|
files.append(make(lib_root / "DnB" / "plain.mp3", seed=9, with_block=False))
|
||||||
|
seed = []
|
||||||
|
for i, path in enumerate(files):
|
||||||
|
track = Track(id=f"seed{i}", title=path.stem, artist="Test")
|
||||||
|
cues = TrackCues(grid_markers=[GridMarker(start=0.25, bpm=176.0)], grid_locked=True)
|
||||||
|
seed.append(ExportTrack(track=track, destination=path, cues=cues))
|
||||||
|
core_export.for_platform("traktor").write(
|
||||||
|
ExportPayload(name="Source", tracks=seed, playlists=[], root_folder=True), lib_root)
|
||||||
|
source_bytes = {p: p.read_bytes() for p in files}
|
||||||
|
STATE.open(lib_root / "collection.nml")
|
||||||
|
ad = STATE.adapter
|
||||||
|
LIB = STATE.library_id
|
||||||
|
ids = [t.id for t in ad.tracks]
|
||||||
|
check("the source library holds the four tracks", len(ids) == 4, str(ids))
|
||||||
|
|
||||||
|
|
||||||
|
def run_job(kind, fn):
|
||||||
|
job = JOBS.submit(kind, fn)
|
||||||
|
while not job.finished:
|
||||||
|
time.sleep(0.02)
|
||||||
|
assert job.error is None, job.error
|
||||||
|
return job.result
|
||||||
|
|
||||||
|
|
||||||
|
def copies(dest: Path) -> dict[str, Path]:
|
||||||
|
return {p.name: p for p in (dest / "Contents").rglob("*") if p.is_file() and not p.name.startswith(".")}
|
||||||
|
|
||||||
|
|
||||||
|
def records(dest: Path) -> dict[str, dict]:
|
||||||
|
return {Path(rel).name: r for rel, r in (read_manifest(dest).get("audio") or {}).items()}
|
||||||
|
|
||||||
|
|
||||||
|
def bpms(nml: Path) -> dict[str, float]:
|
||||||
|
a = TraktorAdapter(nml)
|
||||||
|
return {Path(a.audio_path(t.id)).name: a.track_cues(t.id).grid_markers[0].bpm for t in a.tracks}
|
||||||
|
|
||||||
|
|
||||||
|
print("== an export to Traktor ==")
|
||||||
|
dest = ROOT / "GIG"
|
||||||
|
gig = exports.create(LIB, name="GIG", targets=["traktor"], destination=str(dest))
|
||||||
|
exports.add(LIB, gig.id, track_ids=ids)
|
||||||
|
gig = exports.get(LIB, gig.id)
|
||||||
|
run_job("export", lambda h: exporter.run(ad, gig, exporter.plan(ad, gig), h))
|
||||||
|
out = copies(dest)
|
||||||
|
check("every track was copied", set(out) == {p.name for p in files}, str(sorted(out)))
|
||||||
|
check("no copy carries Traktor's block", not any(file_block.has_block(p) for p in out.values()))
|
||||||
|
check("the SOURCE files are untouched", all(p.read_bytes() == b for p, b in source_bytes.items()))
|
||||||
|
check("a file that had no block is copied byte for byte", out["plain.mp3"].read_bytes() == source_bytes[files[3]])
|
||||||
|
check("the covers are still in the copies",
|
||||||
|
ID3(out["one.mp3"]).getall("APIC") and "covr" in MP4(out["two.m4a"]).tags)
|
||||||
|
recs = records(dest)
|
||||||
|
check("the manifest records each copy as prepared for Traktor",
|
||||||
|
all(r.get("prepared") == ["traktor"] for r in recs.values()), str(recs))
|
||||||
|
check("and records the copy's size as it is now (after the strip)",
|
||||||
|
all(r["copy_size"] == out[n].stat().st_size for n, r in recs.items()))
|
||||||
|
check("the exported grids are the library's (176)", all(abs(b - 176.0) < 0.01 for b in bpms(dest / "collection.nml").values()))
|
||||||
|
|
||||||
|
print("== a re-export rewrites nothing ==")
|
||||||
|
stamp = {n: (p.stat().st_ino, p.stat().st_mtime_ns) for n, p in out.items()}
|
||||||
|
run_job("export", lambda h: exporter.run(ad, gig, exporter.plan(ad, gig), h))
|
||||||
|
check("every copy kept as it was (same inode, same mtime)",
|
||||||
|
{n: (p.stat().st_ino, p.stat().st_mtime_ns) for n, p in copies(dest).items()} == stamp)
|
||||||
|
|
||||||
|
print("== a copy kept from an export made before this fix is cleaned in place ==")
|
||||||
|
# Put the block back into one copy and drop `prepared`, as an older export's
|
||||||
|
# manifest and stick would be — the record matching the file, so it is kept.
|
||||||
|
old_copy = copies(dest)["one.mp3"]
|
||||||
|
tags = ID3(old_copy)
|
||||||
|
tags.add(PRIV(owner="TRAKTOR4", data=block(175.0)))
|
||||||
|
tags.save(old_copy, v2_version=3)
|
||||||
|
manifest = read_manifest(dest)
|
||||||
|
for rel, r in manifest["audio"].items():
|
||||||
|
r.pop("prepared", None)
|
||||||
|
if Path(rel).name == "one.mp3":
|
||||||
|
st = old_copy.stat()
|
||||||
|
r["copy_size"], r["copy_mtime_ns"] = st.st_size, st.st_mtime_ns
|
||||||
|
exporter.manifest_path(dest).write_text(json.dumps(manifest))
|
||||||
|
inode = old_copy.stat().st_ino
|
||||||
|
again = exporter.plan(ad, gig)
|
||||||
|
check("the old copy is planned as KEPT, not copied again",
|
||||||
|
next(t for t in again.exportable if t.destination.name == "one.mp3").reuse is not None)
|
||||||
|
run_job("export", lambda h: exporter.run(ad, gig, again, h))
|
||||||
|
cleaned = copies(dest)["one.mp3"]
|
||||||
|
check("its block is gone", not file_block.has_block(cleaned))
|
||||||
|
check("in place: the same file, not a new copy", cleaned.stat().st_ino == inode)
|
||||||
|
check("every record says prepared again", all(r.get("prepared") == ["traktor"] for r in records(dest).values()))
|
||||||
|
check("and the next export keeps it as it is",
|
||||||
|
next(t for t in exporter.plan(ad, gig).exportable if t.destination.name == "one.mp3").reuse is not None)
|
||||||
|
|
||||||
|
print("== a target without the hook leaves the block; adding Traktor cleans the kept copies ==")
|
||||||
|
pdest = ROOT / "PIONEER"
|
||||||
|
pio = exports.create(LIB, name="PIONEER", targets=["rekordbox_export"], destination=str(pdest))
|
||||||
|
exports.add(LIB, pio.id, track_ids=ids)
|
||||||
|
pio = exports.get(LIB, pio.id)
|
||||||
|
run_job("export", lambda h: exporter.run(ad, pio, exporter.plan(ad, pio), h))
|
||||||
|
pout = copies(pdest)
|
||||||
|
check("a Rekordbox Export's copies keep Traktor's block (none of its business)",
|
||||||
|
file_block.has_block(pout["one.mp3"]) and file_block.has_block(pout["two.m4a"]))
|
||||||
|
check("and are recorded as prepared by nobody", all(r.get("prepared") == [] for r in records(pdest).values()))
|
||||||
|
inodes = {n: p.stat().st_ino for n, p in pout.items()}
|
||||||
|
pio = exports.update(LIB, pio.id, targets=["rekordbox_export", "traktor"])
|
||||||
|
run_job("export", lambda h: exporter.run(ad, pio, exporter.plan(ad, pio), h))
|
||||||
|
pout = copies(pdest)
|
||||||
|
check("with Traktor added, no copy carries the block", not any(file_block.has_block(p) for p in pout.values()))
|
||||||
|
check("cleaned in place, none copied again", {n: p.stat().st_ino for n, p in pout.items()} == inodes)
|
||||||
|
check("recorded as prepared for Traktor", all(r.get("prepared") == ["traktor"] for r in records(pdest).values()))
|
||||||
|
|
||||||
|
print("== a local push into this computer's Traktor ==")
|
||||||
|
laptop = ROOT / "laptop" / "collection.nml"
|
||||||
|
laptop.parent.mkdir(parents=True)
|
||||||
|
laptop.write_text(SKELETON, encoding="utf-8")
|
||||||
|
AUDIO = ROOT / "LocalAudio"
|
||||||
|
apps_running.running = lambda platforms: set()
|
||||||
|
prefs.update_prefs({"localLibraries": {"traktor": str(laptop), "rekordbox": str(ROOT / "none" / "master.db")},
|
||||||
|
"localAudioRoot": str(AUDIO), "localNormalise": False})
|
||||||
|
push = exports.create(LIB, name="Push", targets=["traktor"], destination="", kind="computer", mode="merge")
|
||||||
|
exports.add(LIB, push.id, track_ids=ids)
|
||||||
|
push = exports.get(LIB, push.id)
|
||||||
|
built = local_push.plan(ad, push)
|
||||||
|
check("the push can run", built.blocked is None, str(built.blocked))
|
||||||
|
run_job("local-push", lambda h: local_push.run(ad, push, built, h))
|
||||||
|
pushed = {p.name: p for p in AUDIO.rglob("*") if p.is_file() and p.suffix in (".mp3", ".m4a", ".flac")}
|
||||||
|
check("every track's copy is in the shared folder", set(pushed) == {p.name for p in files}, str(sorted(pushed)))
|
||||||
|
check("none of them carries Traktor's block", not any(file_block.has_block(p) for p in pushed.values()))
|
||||||
|
ledger = local_push._read_ledger()["audio"][str(AUDIO)]
|
||||||
|
check("the ledger records them as prepared for Traktor",
|
||||||
|
all(r.get("prepared") == ["traktor"] for r in ledger.values()), str(ledger))
|
||||||
|
check("the laptop's collection has the library's grids (176)",
|
||||||
|
all(abs(b - 176.0) < 0.01 for b in bpms(laptop).values()), str(bpms(laptop)))
|
||||||
|
check("the SOURCE files are still untouched", all(p.read_bytes() == b for p, b in source_bytes.items()))
|
||||||
|
|
||||||
|
print("== an import into a Traktor collection ==")
|
||||||
|
into = ROOT / "into" / "collection.nml"
|
||||||
|
into.parent.mkdir(parents=True)
|
||||||
|
into.write_text(SKELETON, encoding="utf-8")
|
||||||
|
dest_ad = TraktorAdapter(into)
|
||||||
|
folder = ROOT / "into" / "Imported"
|
||||||
|
run_job("import", lambda h: importer.run(ad, dest_ad, importer.plan(ad, dest_ad, folder, track_ids=ids[:2]), h))
|
||||||
|
imported = [p for p in folder.rglob("*") if p.is_file()]
|
||||||
|
check("the copied files arrived", len(imported) == 2, str(imported))
|
||||||
|
check("and carry no block", imported and not any(file_block.has_block(p) for p in imported))
|
||||||
|
ref = ROOT / "ref" / "collection.nml"
|
||||||
|
ref.parent.mkdir(parents=True)
|
||||||
|
ref.write_text(SKELETON, encoding="utf-8")
|
||||||
|
ref_ad = TraktorAdapter(ref)
|
||||||
|
run_job("import", lambda h: importer.run(ad, ref_ad, importer.plan(ad, ref_ad, None, track_ids=ids[:2]), h,
|
||||||
|
reference=True))
|
||||||
|
check("a file added IN PLACE is never touched", all(p.read_bytes() == b for p, b in source_bytes.items()))
|
||||||
|
check("so it keeps its block (it is the user's file)", file_block.has_block(files[0]))
|
||||||
|
|
||||||
|
shutil.rmtree(ROOT, ignore_errors=True)
|
||||||
|
print("\nALL PASS" if not failed else "\nSOME CHECKS FAILED")
|
||||||
|
raise SystemExit(1 if failed else 0)
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Build the Konduktor desktop app on macOS: freeze + stage the backend sidecar,
|
||||||
|
# then build the Tauri app (.app + .dmg). The macOS twin of build.ps1.
|
||||||
|
# One-time setup:
|
||||||
|
# python3 -m venv backend/.venv
|
||||||
|
# backend/.venv/bin/pip install -r backend/requirements.txt -r backend/requirements-build.txt
|
||||||
|
# (cd frontend && npm install)
|
||||||
|
# a Rust toolchain from https://rustup.rs
|
||||||
|
#
|
||||||
|
# ./build.sh # sidecar + app (release bundles)
|
||||||
|
# ./build.sh --skip-sidecar # frontend-only change: reuse the staged sidecar
|
||||||
|
# ./build.sh --debug # anything else is passed on to `tauri build`
|
||||||
|
set -euo pipefail
|
||||||
|
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
|
||||||
|
SKIP_SIDECAR=0
|
||||||
|
TAURI_ARGS=()
|
||||||
|
for arg in "$@"; do
|
||||||
|
case "$arg" in
|
||||||
|
--skip-sidecar) SKIP_SIDECAR=1 ;;
|
||||||
|
*) TAURI_ARGS+=("$arg") ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
die() { echo "error: $*" >&2; exit 1; }
|
||||||
|
|
||||||
|
[ -x "$ROOT/backend/.venv/bin/python" ] || die "No backend venv at backend/.venv - see the one-time setup at the top of build.sh."
|
||||||
|
[ -d "$ROOT/frontend/node_modules" ] || die "No frontend/node_modules - run \`npm install\` in frontend first."
|
||||||
|
STAGED="$ROOT/frontend/src-tauri/binaries/konduktor-sidecar/konduktor-sidecar"
|
||||||
|
|
||||||
|
# rustup adds ~/.cargo/bin to PATH only in shells started AFTER the install -
|
||||||
|
# look there before giving up, rather than failing after the sidecar build.
|
||||||
|
if ! command -v cargo >/dev/null 2>&1; then
|
||||||
|
[ -x "$HOME/.cargo/bin/cargo" ] || die "No Rust toolchain (cargo) - install it from https://rustup.rs."
|
||||||
|
export PATH="$HOME/.cargo/bin:$PATH"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Bundles newer than this marker are this run's (release or --debug profile).
|
||||||
|
MARKER="$(mktemp)"
|
||||||
|
trap 'rm -f "$MARKER"' EXIT
|
||||||
|
|
||||||
|
if [ "$SKIP_SIDECAR" = 1 ]; then
|
||||||
|
[ -x "$STAGED" ] || die "No staged sidecar to reuse - run without --skip-sidecar first."
|
||||||
|
echo "==> Reusing the staged sidecar (--skip-sidecar)"
|
||||||
|
else
|
||||||
|
echo "==> 1/2 Freezing the backend sidecar"
|
||||||
|
PY="$ROOT/backend/.venv/bin/python" "$ROOT/backend/build_sidecar.sh"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Updater packages are signed with the release key (CI's secret). Without it,
|
||||||
|
# build the app and .dmg alone rather than fail at the signing step.
|
||||||
|
if [ -z "${TAURI_SIGNING_PRIVATE_KEY:-}" ]; then
|
||||||
|
TAURI_ARGS=(--config src-tauri/tauri.unsigned.conf.json ${TAURI_ARGS[@]+"${TAURI_ARGS[@]}"})
|
||||||
|
fi
|
||||||
|
|
||||||
|
# A failed .dmg step leaves its read-write image behind (`rw.<pid>.*.dmg`,
|
||||||
|
# hundreds of MB each); clear old ones.
|
||||||
|
find "$ROOT/frontend/src-tauri/target" -path '*/bundle/macos/rw.*.dmg' -delete 2>/dev/null || true
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "==> 2/2 Building the app (tauri build ${TAURI_ARGS[*]+${TAURI_ARGS[*]}})"
|
||||||
|
LOG="$(mktemp)"
|
||||||
|
trap 'rm -f "$MARKER" "$LOG"' EXIT
|
||||||
|
if ! (cd "$ROOT/frontend" && npx tauri build ${TAURI_ARGS[@]+"${TAURI_ARGS[@]}"}) 2>&1 | tee "$LOG"; then
|
||||||
|
# The .dmg step mounts a fresh image and has Finder lay it out, which fails
|
||||||
|
# now and then (measured: the same build passed on a rerun). The .app is
|
||||||
|
# already built by then, so retry just the .dmg once before giving up.
|
||||||
|
grep -q 'bundle_dmg.sh' "$LOG" || exit 1
|
||||||
|
echo ""
|
||||||
|
echo "==> The .dmg step failed; retrying it once"
|
||||||
|
(cd "$ROOT/frontend" && npx tauri build ${TAURI_ARGS[@]+"${TAURI_ARGS[@]}"} --bundles dmg)
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
BUILT="$(find "$ROOT/frontend/src-tauri/target" -path '*/bundle/*' \( -name '*.dmg' -o -name '*.app' \) \
|
||||||
|
-newer "$MARKER" -prune 2>/dev/null || true)"
|
||||||
|
if [ -n "$BUILT" ]; then
|
||||||
|
echo "Built:"
|
||||||
|
echo "$BUILT" | sed 's/^/ /'
|
||||||
|
else
|
||||||
|
echo "Done (nothing bundled - see frontend/src-tauri/target/)."
|
||||||
|
fi
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "frontend",
|
"name": "frontend",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.3.3",
|
"version": "0.3.6",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Rubber Band (keylock)
|
||||||
|
|
||||||
|
`src/lib/audio/rubberband.wasm` is the [Rubber Band Library](https://breakfastquay.com/rubberband/)
|
||||||
|
3.3.0 compiled to WebAssembly with Konduktor's own glue (`glue.c`). The deck's
|
||||||
|
audio worklet uses it for keylock: tempo changes without a pitch change. It
|
||||||
|
runs the R2 ("faster") engine in real-time mode.
|
||||||
|
|
||||||
|
**Licence.** Rubber Band is GPL-2.0-or-later. Every upstream source file says
|
||||||
|
"either version 2 of the License, or (at your option) any later version", and
|
||||||
|
its bundled `src/ext` code (KissFFT, Speex resampler, getopt, pommier) is
|
||||||
|
permissive. That is what allows it to combine with Konduktor's AGPL-3.0, via
|
||||||
|
GPLv3 §13. Do NOT replace it with a prebuilt npm package:
|
||||||
|
`rubberband-wasm`'s glue is labelled "GPLv2" without "or later", and
|
||||||
|
`@echogarden/rubberband-wasm` is GPL-2.0-only. Neither can be combined with
|
||||||
|
AGPL-3.0.
|
||||||
|
|
||||||
|
**Corresponding source** for the `.wasm`: `build.sh` plus `glue.c` plus the
|
||||||
|
upstream release it downloads, which is pinned by version and SHA-256.
|
||||||
|
|
||||||
|
**Rebuilding** is needed only when bumping Rubber Band or changing the glue:
|
||||||
|
run `./build.sh`, which needs `emcc` on PATH (`brew install emscripten`). The
|
||||||
|
`.wasm` is checked in, so neither `npm run dev` nor a release build needs
|
||||||
|
emscripten.
|
||||||
|
|
||||||
|
**Measured** (2026-11-02, Apple M3 Pro, stereo 44.1 kHz, 128-frame quanta):
|
||||||
|
about 40-55x realtime in both JavaScriptCore (WKWebView) and V8 (WebView2).
|
||||||
|
p99 is about 0.17 ms per quantum against a 2.9 ms budget, so 8 stretchers
|
||||||
|
(2 stem decks) fit on the one audio render thread. The R3 ("finer") engine is
|
||||||
|
about 11x realtime and does not fit at 8. `-msimd128` measured no faster than
|
||||||
|
the `-Oz` npm build.
|
||||||
Executable
+48
@@ -0,0 +1,48 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Builds src/lib/audio/rubberband.wasm — the Rubber Band Library compiled to
|
||||||
|
# WebAssembly with Konduktor's own glue (glue.c) — for the deck's keylock.
|
||||||
|
#
|
||||||
|
# The .wasm is checked in, so dev and release builds need no emscripten; rerun
|
||||||
|
# this only when bumping Rubber Band or changing the glue. Needs emcc on PATH
|
||||||
|
# (macOS: `brew install emscripten`).
|
||||||
|
#
|
||||||
|
# Upstream is pinned by version AND SHA-256. Rubber Band is GPL-2.0-or-later
|
||||||
|
# ("either version 2 of the License, or (at your option) any later version"),
|
||||||
|
# which is what lets it combine with Konduktor's AGPL-3.0 — do NOT swap in a
|
||||||
|
# prebuilt npm package: their glue is labelled GPL-2.0(-only).
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
|
||||||
|
VERSION=3.3.0
|
||||||
|
SHA256=d9ef89e2b8ef9f85b13ac3c2faec30e20acf2c9f3a9c8c45ce637f2bc95e576c
|
||||||
|
TARBALL="upstream/rubberband-${VERSION}.tar.bz2"
|
||||||
|
SRC="upstream/rubberband-${VERSION}"
|
||||||
|
OUT=../src/lib/audio/rubberband.wasm
|
||||||
|
|
||||||
|
mkdir -p upstream
|
||||||
|
if [ ! -f "$TARBALL" ]; then
|
||||||
|
curl -fsSL -o "$TARBALL" "https://breakfastquay.com/files/releases/rubberband-${VERSION}.tar.bz2"
|
||||||
|
fi
|
||||||
|
echo "${SHA256} ${TARBALL}" | shasum -a 256 -c -
|
||||||
|
rm -rf "$SRC"
|
||||||
|
tar xjf "$TARBALL" -C upstream
|
||||||
|
|
||||||
|
# -O3 + SIMD for speed on the audio thread (every deck's stretchers share one
|
||||||
|
# render thread). Single-threaded: RubberBandSingle.cpp sets NO_THREADING.
|
||||||
|
FLAGS=(-O3 -flto -msimd128 -fno-rtti -I"$SRC/rubberband")
|
||||||
|
|
||||||
|
# Rubber Band is C++, the glue C: compile each with its own driver, link as C++.
|
||||||
|
OBJ=upstream/obj
|
||||||
|
mkdir -p "$OBJ"
|
||||||
|
em++ "${FLAGS[@]}" -c "$SRC/single/RubberBandSingle.cpp" -o "$OBJ/rubberband.o"
|
||||||
|
emcc "${FLAGS[@]}" -c glue.c -o "$OBJ/glue.o"
|
||||||
|
em++ "${FLAGS[@]}" "$OBJ/rubberband.o" "$OBJ/glue.o" \
|
||||||
|
-sSTANDALONE_WASM=1 \
|
||||||
|
-sALLOW_MEMORY_GROWTH=1 \
|
||||||
|
-sFILESYSTEM=0 \
|
||||||
|
-sASSERTIONS=0 \
|
||||||
|
-sERROR_ON_UNDEFINED_SYMBOLS=1 \
|
||||||
|
--no-entry \
|
||||||
|
-o "$OUT"
|
||||||
|
|
||||||
|
echo "wrote $OUT ($(wc -c < "$OUT" | tr -d ' ') bytes)"
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/*
|
||||||
|
* Konduktor's WebAssembly interface to the Rubber Band Library, used by the
|
||||||
|
* deck's keylock (time-stretch without a pitch change). Part of Konduktor,
|
||||||
|
* licensed under the GNU AGPL-3.0 (see LICENSE at the repository root).
|
||||||
|
*
|
||||||
|
* Plain exports of the C API the deck worklet calls, plus malloc/free so it
|
||||||
|
* can place its sample buffers in the module's memory. Rubber Band itself is
|
||||||
|
* GPL-2.0-or-later (see README.md here).
|
||||||
|
*/
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <emscripten.h>
|
||||||
|
#include <rubberband-c.h>
|
||||||
|
|
||||||
|
#define EXPORT EMSCRIPTEN_KEEPALIVE
|
||||||
|
|
||||||
|
EXPORT void *kd_malloc(size_t size) { return malloc(size); }
|
||||||
|
EXPORT void kd_free(void *ptr) { free(ptr); }
|
||||||
|
|
||||||
|
EXPORT RubberBandState kd_new(unsigned int sample_rate, unsigned int channels,
|
||||||
|
RubberBandOptions options, double time_ratio,
|
||||||
|
double pitch_scale) {
|
||||||
|
return rubberband_new(sample_rate, channels, options, time_ratio, pitch_scale);
|
||||||
|
}
|
||||||
|
EXPORT void kd_delete(RubberBandState s) { rubberband_delete(s); }
|
||||||
|
EXPORT void kd_reset(RubberBandState s) { rubberband_reset(s); }
|
||||||
|
|
||||||
|
EXPORT void kd_set_time_ratio(RubberBandState s, double r) { rubberband_set_time_ratio(s, r); }
|
||||||
|
EXPORT void kd_set_pitch_scale(RubberBandState s, double p) { rubberband_set_pitch_scale(s, p); }
|
||||||
|
EXPORT void kd_set_max_process_size(RubberBandState s, unsigned int n) {
|
||||||
|
rubberband_set_max_process_size(s, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
EXPORT unsigned int kd_get_preferred_start_pad(RubberBandState s) {
|
||||||
|
return rubberband_get_preferred_start_pad(s);
|
||||||
|
}
|
||||||
|
EXPORT unsigned int kd_get_start_delay(RubberBandState s) { return rubberband_get_start_delay(s); }
|
||||||
|
EXPORT unsigned int kd_get_samples_required(RubberBandState s) {
|
||||||
|
return rubberband_get_samples_required(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
EXPORT void kd_process(RubberBandState s, const float *const *input, unsigned int samples,
|
||||||
|
int final) {
|
||||||
|
rubberband_process(s, input, samples, final);
|
||||||
|
}
|
||||||
|
EXPORT int kd_available(RubberBandState s) { return rubberband_available(s); }
|
||||||
|
EXPORT unsigned int kd_retrieve(RubberBandState s, float *const *output, unsigned int samples) {
|
||||||
|
return rubberband_retrieve(s, output, samples);
|
||||||
|
}
|
||||||
Generated
+130
-3
@@ -43,6 +43,38 @@ dependencies = [
|
|||||||
"alloc-no-stdlib",
|
"alloc-no-stdlib",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "alsa"
|
||||||
|
version = "0.12.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d3f93573e7ddb15145d27c58c0fa0a452faad9f5452ac17ed4554ea035ea9b71"
|
||||||
|
dependencies = [
|
||||||
|
"alsa-sys",
|
||||||
|
"bitflags 2.13.0",
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "alsa-sys"
|
||||||
|
version = "0.6.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f0320138053ef93099f168102c37b46ac0b9c53affc56ef7696633ad5477e2be"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"libc",
|
||||||
|
"pkg-config",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "android-build"
|
||||||
|
version = "0.1.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f9fc9904ad2ad097c3c1cfe2eacaaf0fc24710936fa9ed941cb310b7c6ed2ab7"
|
||||||
|
dependencies = [
|
||||||
|
"windows-sys 0.52.0",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "android_log-sys"
|
name = "android_log-sys"
|
||||||
version = "0.3.2"
|
version = "0.3.2"
|
||||||
@@ -80,6 +112,7 @@ name = "app"
|
|||||||
version = "0.1.1"
|
version = "0.1.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"log",
|
"log",
|
||||||
|
"midir",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri",
|
"tauri",
|
||||||
@@ -516,6 +549,27 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "coremidi"
|
||||||
|
version = "0.9.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a57ede822fdaf19280cf1320a5a5d3a522c75c910d01750af1e8122b6ad2595b"
|
||||||
|
dependencies = [
|
||||||
|
"block2",
|
||||||
|
"core-foundation 0.10.1",
|
||||||
|
"core-foundation-sys",
|
||||||
|
"coremidi-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "coremidi-sys"
|
||||||
|
version = "3.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1a2b8c2cefa9a8f712213c5a1383ffe428efc8f1a1fd1e2f757be94daf7e256a"
|
||||||
|
dependencies = [
|
||||||
|
"core-foundation-sys",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cpufeatures"
|
name = "cpufeatures"
|
||||||
version = "0.2.17"
|
version = "0.2.17"
|
||||||
@@ -739,6 +793,16 @@ dependencies = [
|
|||||||
"winapi",
|
"winapi",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "dlopen2"
|
||||||
|
version = "0.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "60768c353d76ba6dd1b6332a5dbbdd3bc2dddadc2935f4cc6a9d0f17ca8ecb6a"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dlopen2_derive"
|
name = "dlopen2_derive"
|
||||||
version = "0.4.3"
|
version = "0.4.3"
|
||||||
@@ -1706,6 +1770,15 @@ version = "1.0.18"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "java-locator"
|
||||||
|
version = "0.1.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "09c46c1fe465c59b1474e665e85e1256c3893dd00927b8d55f63b09044c1e64f"
|
||||||
|
dependencies = [
|
||||||
|
"glob",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "javascriptcore-rs"
|
name = "javascriptcore-rs"
|
||||||
version = "1.1.2"
|
version = "1.1.2"
|
||||||
@@ -1738,7 +1811,9 @@ dependencies = [
|
|||||||
"cesu8",
|
"cesu8",
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"combine",
|
"combine",
|
||||||
|
"java-locator",
|
||||||
"jni-sys 0.3.1",
|
"jni-sys 0.3.1",
|
||||||
|
"libloading",
|
||||||
"log",
|
"log",
|
||||||
"thiserror 1.0.69",
|
"thiserror 1.0.69",
|
||||||
"walkdir",
|
"walkdir",
|
||||||
@@ -1775,6 +1850,21 @@ dependencies = [
|
|||||||
"syn 2.0.118",
|
"syn 2.0.118",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "jni-min-helper"
|
||||||
|
version = "0.3.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "913370a00ba1851b0f3369b49d0f3e745da2d20d3f15ecc296a64234ccda45f7"
|
||||||
|
dependencies = [
|
||||||
|
"android-build",
|
||||||
|
"dlopen2 0.9.0",
|
||||||
|
"jni 0.21.1",
|
||||||
|
"libc",
|
||||||
|
"log",
|
||||||
|
"ndk-context",
|
||||||
|
"process_path",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "jni-sys"
|
name = "jni-sys"
|
||||||
version = "0.3.1"
|
version = "0.3.1"
|
||||||
@@ -1873,9 +1963,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libc"
|
name = "libc"
|
||||||
version = "0.2.186"
|
version = "0.2.191"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libdbus-sys"
|
name = "libdbus-sys"
|
||||||
@@ -1961,6 +2051,27 @@ dependencies = [
|
|||||||
"autocfg",
|
"autocfg",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "midir"
|
||||||
|
version = "0.11.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fea58b9250a667b032ff61fb1bf77aed74873152563f5cd613016dce4c821832"
|
||||||
|
dependencies = [
|
||||||
|
"alsa",
|
||||||
|
"cc",
|
||||||
|
"coremidi",
|
||||||
|
"jni 0.21.1",
|
||||||
|
"jni-min-helper",
|
||||||
|
"js-sys",
|
||||||
|
"libc",
|
||||||
|
"log",
|
||||||
|
"ndk-context",
|
||||||
|
"parking_lot",
|
||||||
|
"wasm-bindgen",
|
||||||
|
"web-sys",
|
||||||
|
"windows",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mime"
|
name = "mime"
|
||||||
version = "0.3.17"
|
version = "0.3.17"
|
||||||
@@ -2030,6 +2141,12 @@ dependencies = [
|
|||||||
"thiserror 1.0.69",
|
"thiserror 1.0.69",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ndk-context"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ndk-sys"
|
name = "ndk-sys"
|
||||||
version = "0.6.0+11769913"
|
version = "0.6.0+11769913"
|
||||||
@@ -2602,6 +2719,16 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "process_path"
|
||||||
|
version = "0.1.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f676f11eb0b3e2ea0fbaee218fa6b806689e2297b8c8adc5bf73df465c4f6171"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"winapi",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ptr_meta"
|
name = "ptr_meta"
|
||||||
version = "0.1.4"
|
version = "0.1.4"
|
||||||
@@ -3568,7 +3695,7 @@ dependencies = [
|
|||||||
"crossbeam-channel",
|
"crossbeam-channel",
|
||||||
"dbus",
|
"dbus",
|
||||||
"dispatch2",
|
"dispatch2",
|
||||||
"dlopen2",
|
"dlopen2 0.8.2",
|
||||||
"dpi",
|
"dpi",
|
||||||
"gdkwayland-sys",
|
"gdkwayland-sys",
|
||||||
"gdkx11-sys",
|
"gdkx11-sys",
|
||||||
|
|||||||
@@ -31,4 +31,6 @@ tokio = { version = "1", features = ["time"] } # timeout on the port handshake
|
|||||||
# One-click update (UpdateDialog.tsx). No `zip` feature: it only unpacks
|
# One-click update (UpdateDialog.tsx). No `zip` feature: it only unpacks
|
||||||
# v1-style zipped Windows installers (we ship the bare NSIS setup.exe), and
|
# v1-style zipped Windows installers (we ship the bare NSIS setup.exe), and
|
||||||
# every zip 4.x it would need is yanked.
|
# every zip 4.x it would need is yanked.
|
||||||
|
# MIDI controller input (src/midi.rs): CoreMIDI on macOS, WinMM on Windows.
|
||||||
|
midir = "0.11"
|
||||||
tauri-plugin-updater = { version = "2.12", default-features = false, features = ["rustls-tls", "system-proxy"] }
|
tauri-plugin-updater = { version = "2.12", default-features = false, features = ["rustls-tls", "system-proxy"] }
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
// MIDI transport spike (macOS): a virtual CoreMIDI source named
|
||||||
|
// "Konduktor Flood" that sends a jog-like CC stream at a fixed rate, so the
|
||||||
|
// shell's MIDI path can be measured without hardware.
|
||||||
|
//
|
||||||
|
// cargo run --example midi_flood -- <rate Hz> <count> <start delay s>
|
||||||
|
//
|
||||||
|
// Each message is CC 33 on channel 1 with a 7-bit counter as its value, so
|
||||||
|
// the receiver can check for drops and reordering.
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
fn main() {
|
||||||
|
use midir::os::unix::VirtualOutput;
|
||||||
|
use midir::MidiOutput;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
let args: Vec<String> = std::env::args().collect();
|
||||||
|
let rate: f64 = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(1000.0);
|
||||||
|
let count: u32 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(5000);
|
||||||
|
let delay: f64 = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(3.0);
|
||||||
|
|
||||||
|
let out = MidiOutput::new("Konduktor Flood").expect("MIDI client");
|
||||||
|
let mut conn = out.create_virtual("Konduktor Flood").expect("virtual source");
|
||||||
|
std::thread::sleep(Duration::from_secs_f64(delay));
|
||||||
|
|
||||||
|
let start = Instant::now();
|
||||||
|
let step = Duration::from_secs_f64(1.0 / rate);
|
||||||
|
for i in 0..count {
|
||||||
|
let due = start + step * i;
|
||||||
|
while Instant::now() < due {
|
||||||
|
let left = due - Instant::now();
|
||||||
|
if left > Duration::from_micros(300) {
|
||||||
|
std::thread::sleep(left - Duration::from_micros(200));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
conn.send(&[0xB0, 33, (i % 128) as u8]).expect("send");
|
||||||
|
}
|
||||||
|
eprintln!("sent {count} at {rate} Hz in {:.3} s", start.elapsed().as_secs_f64());
|
||||||
|
std::thread::sleep(Duration::from_secs(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "macos"))]
|
||||||
|
fn main() {
|
||||||
|
eprintln!("midi_flood needs CoreMIDI virtual ports (macOS).");
|
||||||
|
}
|
||||||
@@ -37,6 +37,12 @@
|
|||||||
// runs. Cancel in the Save / Discard prompt keeps the update staged, so the
|
// runs. Cancel in the Save / Discard prompt keeps the update staged, so the
|
||||||
// next ordinary quit installs it (without relaunching). A failed install is
|
// next ordinary quit installs it (without relaunching). A failed install is
|
||||||
// written to `failed.json` for the next launch's dialog to report.
|
// written to `failed.json` for the next launch's dialog to report.
|
||||||
|
//
|
||||||
|
// MIDI controllers (midi.rs): WKWebView has no Web MIDI, so the shell lists
|
||||||
|
// and opens the input ports itself and streams their messages to the page
|
||||||
|
// (`midi_ports` / `midi_open` / `midi_close`); everything else is the page's.
|
||||||
|
mod midi;
|
||||||
|
|
||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||||
@@ -459,6 +465,7 @@ pub fn run() {
|
|||||||
.manage(Staged(Mutex::new(None)))
|
.manage(Staged(Mutex::new(None)))
|
||||||
.manage(Backend { status: Mutex::new(BackendStatus::Starting), generation: AtomicU64::new(0) })
|
.manage(Backend { status: Mutex::new(BackendStatus::Starting), generation: AtomicU64::new(0) })
|
||||||
.manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) })
|
.manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) })
|
||||||
|
.manage(midi::MidiInputs::default())
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
backend_status,
|
backend_status,
|
||||||
backend_restart,
|
backend_restart,
|
||||||
@@ -467,7 +474,10 @@ pub fn run() {
|
|||||||
quit_now,
|
quit_now,
|
||||||
update_download,
|
update_download,
|
||||||
update_restart,
|
update_restart,
|
||||||
update_take_failure
|
update_take_failure,
|
||||||
|
midi::midi_ports,
|
||||||
|
midi::midi_open,
|
||||||
|
midi::midi_close
|
||||||
])
|
])
|
||||||
.on_window_event(|window, event| {
|
.on_window_event(|window, event| {
|
||||||
if let WindowEvent::CloseRequested { api, .. } = event {
|
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
// MIDI INPUT for controller mapping (decided 2026-11-03,
|
||||||
|
// .claude/discussions/discuss-midi-controllers-2026-11-03.md).
|
||||||
|
//
|
||||||
|
// WKWebView has no Web MIDI, so the shell reads the ports itself with midir
|
||||||
|
// (CoreMIDI on macOS, WinMM on Windows) and streams each port's messages to the
|
||||||
|
// page over a `Channel` — the frontend does all parsing, mapping and learning
|
||||||
|
// (lib/midi/). Input only: nothing is ever sent to a controller.
|
||||||
|
//
|
||||||
|
// Batching without a timer: the driver's callback queues each message on an
|
||||||
|
// mpsc; one sender thread per port blocks on it, then drains whatever else has
|
||||||
|
// queued and sends that as ONE batch. Idle, a message goes out the moment it
|
||||||
|
// arrives; under a jog wheel's flood, messages coalesce instead of queueing up
|
||||||
|
// one IPC call each. System messages (SysEx, MIDI clock, active sensing) are
|
||||||
|
// ignored at the driver: a 24-ppqn clock from a mixer would flood the page.
|
||||||
|
//
|
||||||
|
// `wall_us` is the wall clock (µs since the Unix epoch) when the driver handed
|
||||||
|
// the message over, so the page can measure transport latency against its own
|
||||||
|
// `Date.now()`.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::mpsc;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use midir::{Ignore, MidiInput, MidiInputConnection, MidiInputPort};
|
||||||
|
use serde::Serialize;
|
||||||
|
use tauri::ipc::Channel;
|
||||||
|
use tauri::State;
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize)]
|
||||||
|
pub struct MidiPacket {
|
||||||
|
pub wall_us: u64,
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open connections by port name. Dropping one closes the port and ends its
|
||||||
|
/// sender thread (the callback's mpsc sender goes with it).
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct MidiInputs(Mutex<HashMap<String, MidiInputConnection<()>>>);
|
||||||
|
|
||||||
|
fn client() -> Result<MidiInput, String> {
|
||||||
|
let mut input = MidiInput::new("Konduktor").map_err(|e| e.to_string())?;
|
||||||
|
input.ignore(Ignore::All);
|
||||||
|
Ok(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every input port with a unique name: two identical controllers are
|
||||||
|
/// "X" and "X #2", in the order the OS lists them.
|
||||||
|
fn named_ports(input: &MidiInput) -> Vec<(String, MidiInputPort)> {
|
||||||
|
let mut seen: HashMap<String, usize> = HashMap::new();
|
||||||
|
input
|
||||||
|
.ports()
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|p| {
|
||||||
|
let base = input.port_name(&p).ok()?;
|
||||||
|
let n = seen.entry(base.clone()).or_insert(0);
|
||||||
|
*n += 1;
|
||||||
|
let name = if *n == 1 { base } else { format!("{base} #{n}") };
|
||||||
|
Some((name, p))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now_us() -> u64 {
|
||||||
|
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_micros() as u64).unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn midi_ports() -> Result<Vec<String>, String> {
|
||||||
|
Ok(named_ports(&client()?).into_iter().map(|(name, _)| name).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open `port` and stream its messages to `on_message`. Opening a port that is
|
||||||
|
/// already open replaces the old connection (a page reload re-opens).
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn midi_open(
|
||||||
|
inputs: State<'_, MidiInputs>,
|
||||||
|
port: String,
|
||||||
|
on_message: Channel<Vec<MidiPacket>>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let input = client()?;
|
||||||
|
let found = named_ports(&input)
|
||||||
|
.into_iter()
|
||||||
|
.find(|(name, _)| *name == port)
|
||||||
|
.map(|(_, p)| p)
|
||||||
|
.ok_or_else(|| format!("MIDI port not found: {port}"))?;
|
||||||
|
|
||||||
|
let (tx, rx) = mpsc::channel::<MidiPacket>();
|
||||||
|
std::thread::Builder::new()
|
||||||
|
.name(format!("midi:{port}"))
|
||||||
|
.spawn(move || {
|
||||||
|
while let Ok(first) = rx.recv() {
|
||||||
|
let mut batch = vec![first];
|
||||||
|
while let Ok(more) = rx.try_recv() {
|
||||||
|
batch.push(more);
|
||||||
|
}
|
||||||
|
if on_message.send(batch).is_err() {
|
||||||
|
break; // the page went away
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let conn = input
|
||||||
|
.connect(
|
||||||
|
&found,
|
||||||
|
"Konduktor input",
|
||||||
|
move |_stamp, bytes, _| {
|
||||||
|
let _ = tx.send(MidiPacket { wall_us: now_us(), bytes: bytes.to_vec() });
|
||||||
|
},
|
||||||
|
(),
|
||||||
|
)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
inputs.0.lock().unwrap().insert(port, conn);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn midi_close(inputs: State<'_, MidiInputs>, port: String) {
|
||||||
|
if let Some(conn) = inputs.0.lock().unwrap().remove(&port) {
|
||||||
|
conn.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
+202
-58
@@ -32,7 +32,8 @@ import { ConfirmDialog, type ConfirmRequest } from './components/ConfirmDialog'
|
|||||||
import { PathMappingDialog } from './components/PathMappingDialog'
|
import { PathMappingDialog } from './components/PathMappingDialog'
|
||||||
import { RelocateDialog } from './components/RelocateDialog'
|
import { RelocateDialog } from './components/RelocateDialog'
|
||||||
import { HistoryPanel } from './components/HistoryPanel'
|
import { HistoryPanel } from './components/HistoryPanel'
|
||||||
import { PrepStrip } from './components/PrepStrip'
|
import { EMPTY_SLOT, PrepStrip, type DeckDrop, type DeckId, type DeckSlot } from './components/PrepStrip'
|
||||||
|
import { PerformanceButton } from './components/deck/PerformanceButton'
|
||||||
import { ImportDialog } from './components/ImportDialog'
|
import { ImportDialog } from './components/ImportDialog'
|
||||||
import { AddFilesDialog, type AddTarget, type ForeignOrigin } from './components/AddFilesDialog'
|
import { AddFilesDialog, type AddTarget, type ForeignOrigin } from './components/AddFilesDialog'
|
||||||
import { ConvertStemsDialog } from './components/ConvertStemsDialog'
|
import { ConvertStemsDialog } from './components/ConvertStemsDialog'
|
||||||
@@ -40,6 +41,8 @@ import { StemReportDialog } from './components/StemReportDialog'
|
|||||||
import { SetPositionDialog } from './components/SetPositionDialog'
|
import { SetPositionDialog } from './components/SetPositionDialog'
|
||||||
import { Icon } from './lib/icons'
|
import { Icon } from './lib/icons'
|
||||||
import { usePrefsWriter } from './lib/prefs'
|
import { usePrefsWriter } from './lib/prefs'
|
||||||
|
import { useMidi } from './lib/midi/useMidi'
|
||||||
|
import { midiTargets, useMidiTargets } from './lib/midi/targets'
|
||||||
|
|
||||||
function applyFilters(tracks: Track[], f: Filters): Track[] {
|
function applyFilters(tracks: Track[], f: Filters): Track[] {
|
||||||
const q = f.search.trim().toLowerCase()
|
const q = f.search.trim().toLowerCase()
|
||||||
@@ -61,6 +64,14 @@ function applyFilters(tracks: Track[], f: Filters): Track[] {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** `f` over both decks; the same object back when neither slot changed, so a
|
||||||
|
* no-op update does not re-render. */
|
||||||
|
function mapDecks(d: Record<DeckId, DeckSlot>, f: (s: DeckSlot) => DeckSlot): Record<DeckId, DeckSlot> {
|
||||||
|
const A = f(d.A)
|
||||||
|
const B = f(d.B)
|
||||||
|
return A === d.A && B === d.B ? d : { A, B }
|
||||||
|
}
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const qc = useQueryClient()
|
const qc = useQueryClient()
|
||||||
const [source, setSource] = useState<Source>({ kind: 'all' })
|
const [source, setSource] = useState<Source>({ kind: 'all' })
|
||||||
@@ -77,12 +88,20 @@ export default function App() {
|
|||||||
const [editing, setEditing] = useState<Track | null>(null)
|
const [editing, setEditing] = useState<Track | null>(null)
|
||||||
const [showPaths, setShowPaths] = useState(false)
|
const [showPaths, setShowPaths] = useState(false)
|
||||||
const [showHistory, setShowHistory] = useState(false)
|
const [showHistory, setShowHistory] = useState(false)
|
||||||
const [prepTrack, setPrepTrack] = useState<Track | null>(null)
|
// The decks: A always, B in performance mode (decided 2026-11-02). Each slot
|
||||||
const [deckPlaying, setDeckPlaying] = useState(false)
|
// is its track, which library that came from — not the view's: browsing to a
|
||||||
// Which library the DECK's track came from — not the view's. Browsing to a
|
|
||||||
// playlist while a device or folder track is loaded must not switch the deck
|
// playlist while a device or folder track is loaded must not switch the deck
|
||||||
// to endpoints that do not know that track.
|
// to endpoints that do not know that track — and two counters App bumps.
|
||||||
const [prepOrigin, setPrepOrigin] = useState<TrackOrigin>('collection')
|
const [decks, setDecks] = useState<Record<DeckId, DeckSlot>>({ A: EMPTY_SLOT, B: EMPTY_SLOT })
|
||||||
|
const [deckPlaying, setDeckPlaying] = useState<Record<DeckId, boolean>>({ A: false, B: false })
|
||||||
|
const [performance, setPerformance] = useState(false)
|
||||||
|
const [focusedDeck, setFocusedDeck] = useState<DeckId>('A')
|
||||||
|
// Where a load goes — the focused deck in performance mode, else A — and the
|
||||||
|
// deck the library's rows light up for. A ref too, for the load callbacks.
|
||||||
|
const targetDeck: DeckId = performance ? focusedDeck : 'A'
|
||||||
|
const targetDeckRef = useRef<DeckId>('A')
|
||||||
|
targetDeckRef.current = targetDeck
|
||||||
|
const prepTrack = decks[targetDeck].track
|
||||||
// The view's origin, read by the load callbacks below (defined before it).
|
// The view's origin, read by the load callbacks below (defined before it).
|
||||||
const viewOriginRef = useRef<TrackOrigin>('collection')
|
const viewOriginRef = useRef<TrackOrigin>('collection')
|
||||||
// The browsed folder's rows that ARE collection tracks: collection id → the
|
// The browsed folder's rows that ARE collection tracks: collection id → the
|
||||||
@@ -94,7 +113,6 @@ export default function App() {
|
|||||||
// How many dropped items are being read (a dropped folder is searched all
|
// 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.
|
// the way down, which can take a while): shown until the dialog opens.
|
||||||
const [readingDrop, setReadingDrop] = useState(0)
|
const [readingDrop, setReadingDrop] = useState(0)
|
||||||
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
|
|
||||||
const [importing, setImporting] = useState(false)
|
const [importing, setImporting] = useState(false)
|
||||||
// Device tracks dropped on a collection playlist / export: Import, with
|
// Device tracks dropped on a collection playlist / export: Import, with
|
||||||
// just those tracks and that target.
|
// just those tracks and that target.
|
||||||
@@ -119,23 +137,48 @@ export default function App() {
|
|||||||
const [stemReport, setStemReport] = useState<StemBatchResult | null>(null)
|
const [stemReport, setStemReport] = useState<StemBatchResult | null>(null)
|
||||||
const [engineJob, setEngineJob] = useState<string | null>(null)
|
const [engineJob, setEngineJob] = useState<string | null>(null)
|
||||||
const [batchCancelling, setBatchCancelling] = useState(false)
|
const [batchCancelling, setBatchCancelling] = useState(false)
|
||||||
const [cuesRefresh, setCuesRefresh] = useState(0) // bump → deck re-reads its cues
|
|
||||||
// Every Remove ▸ action (and the playlist Delete key) confirms first.
|
// Every Remove ▸ action (and the playlist Delete key) confirms first.
|
||||||
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
|
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
|
||||||
|
|
||||||
const loadTrack = useCallback((t: Track, origin: TrackOrigin = viewOriginRef.current) => {
|
const loadTrack = useCallback(
|
||||||
setPrepTrack(t)
|
(t: Track, origin: TrackOrigin = viewOriginRef.current, deck: DeckId = targetDeckRef.current) => {
|
||||||
// A folder row the collection holds IS the collection track, so the deck
|
// A folder row the collection holds IS the collection track, so the deck
|
||||||
// loads it as one: its cues and grid, and editable (decided 2026-10-10).
|
// loads it as one: its cues and grid, and editable (decided 2026-10-10).
|
||||||
setPrepOrigin(origin === 'folder' && folderFilesRef.current[t.id] ? 'collection' : origin)
|
const o = origin === 'folder' && folderFilesRef.current[t.id] ? 'collection' : origin
|
||||||
}, [])
|
setDecks((d) => ({ ...d, [deck]: { ...d[deck], track: t, origin: o } }))
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
)
|
||||||
const playTrack = useCallback(
|
const playTrack = useCallback(
|
||||||
(t: Track) => {
|
(t: Track) => {
|
||||||
loadTrack(t)
|
const deck = targetDeckRef.current
|
||||||
setPlayRequest((n) => n + 1)
|
loadTrack(t, undefined, deck)
|
||||||
|
setDecks((d) => ({ ...d, [deck]: { ...d[deck], playRequest: d[deck].playRequest + 1 } }))
|
||||||
},
|
},
|
||||||
[loadTrack],
|
[loadTrack],
|
||||||
)
|
)
|
||||||
|
// Every deck holding one of `ids`: re-read its cues (an outside edit wrote
|
||||||
|
// them), or unload it (the track left the collection).
|
||||||
|
const bumpDeckCues = useCallback((ids: string[]) => {
|
||||||
|
setDecks((d) => mapDecks(d, (s) => (s.track && ids.includes(s.track.id) ? { ...s, cuesRefresh: s.cuesRefresh + 1 } : s)))
|
||||||
|
}, [])
|
||||||
|
const unloadDecks = useCallback((ids: string[]) => {
|
||||||
|
setDecks((d) => mapDecks(d, (s) => (s.track && ids.includes(s.track.id) ? { ...s, track: null } : s)))
|
||||||
|
}, [])
|
||||||
|
const onDeckPlaying = useCallback((id: DeckId, playing: boolean) => {
|
||||||
|
setDeckPlaying((s) => (s[id] === playing ? s : { ...s, [id]: playing }))
|
||||||
|
}, [])
|
||||||
|
// Entering performance mode with deck B empty focuses B, so the next load
|
||||||
|
// goes there and deck A keeps playing what it has.
|
||||||
|
const decksRef = useRef(decks)
|
||||||
|
decksRef.current = decks
|
||||||
|
const performanceRef = useRef(performance)
|
||||||
|
performanceRef.current = performance
|
||||||
|
const togglePerformance = useCallback(() => {
|
||||||
|
const entering = !performanceRef.current
|
||||||
|
if (entering && !decksRef.current.B.track) setFocusedDeck('B')
|
||||||
|
setPerformance(entering)
|
||||||
|
}, [])
|
||||||
|
|
||||||
// ---- configurable library columns (persisted to userprefs.json) ----
|
// ---- configurable library columns (persisted to userprefs.json) ----
|
||||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(DEFAULT_COLUMN_VISIBILITY)
|
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(DEFAULT_COLUMN_VISIBILITY)
|
||||||
@@ -220,6 +263,16 @@ export default function App() {
|
|||||||
}, [])
|
}, [])
|
||||||
const onError = useCallback((msg: string) => notify('error', msg), [notify])
|
const onError = useCallback((msg: string) => notify('error', msg), [notify])
|
||||||
|
|
||||||
|
// MIDI controllers (lib/midi): found as they are plugged in; a controller's
|
||||||
|
// load buttons take the track list's highlighted row, loaded paused.
|
||||||
|
useMidi(notify)
|
||||||
|
useMidiTargets({
|
||||||
|
load: (deck) => {
|
||||||
|
const t = midiTargets.lead?.()
|
||||||
|
if (t) loadTrack(t, undefined, deck)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
// Inline single-field edit from a double-clicked table cell. Only offered when
|
// Inline single-field edit from a double-clicked table cell. Only offered when
|
||||||
// the library can take an edit: passing `undefined` makes those cells inert
|
// the library can take an edit: passing `undefined` makes those cells inert
|
||||||
// rather than firing a request the adapter will refuse. Defaults to false, so
|
// rather than firing a request the adapter will refuse. Defaults to false, so
|
||||||
@@ -324,7 +377,7 @@ export default function App() {
|
|||||||
const deviceCaps = useQuery({
|
const deviceCaps = useQuery({
|
||||||
queryKey: ['source-capabilities'],
|
queryKey: ['source-capabilities'],
|
||||||
queryFn: api.sourceCapabilities,
|
queryFn: api.sourceCapabilities,
|
||||||
enabled: viewingDevice || prepOrigin === 'device',
|
enabled: viewingDevice || decks.A.origin === 'device' || decks.B.origin === 'device',
|
||||||
staleTime: Infinity,
|
staleTime: Infinity,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -368,6 +421,13 @@ export default function App() {
|
|||||||
nodes.flatMap((n) => [...(n.can_add_tracks ? [n] : []), ...walk(n.children)])
|
nodes.flatMap((n) => [...(n.can_add_tracks ? [n] : []), ...walk(n.children)])
|
||||||
return walk(playlists.data ?? [])
|
return walk(playlists.data ?? [])
|
||||||
}, [playlists.data])
|
}, [playlists.data])
|
||||||
|
// Every playlist Remove ▸ From playlist can take tracks out of: the same
|
||||||
|
// gate as removing from the open one (its entry list is rewritten).
|
||||||
|
const removablePlaylists = useMemo(() => {
|
||||||
|
const walk = (nodes: PlaylistNode[]): PlaylistNode[] =>
|
||||||
|
nodes.flatMap((n) => [...(n.can_reorder ? [n] : []), ...walk(n.children)])
|
||||||
|
return canEdit ? walk(playlists.data ?? []) : []
|
||||||
|
}, [playlists.data, canEdit])
|
||||||
|
|
||||||
// Export membership. Both are no-ops on the library itself, so neither dirties
|
// Export membership. Both are no-ops on the library itself, so neither dirties
|
||||||
// it nor touches version history — an export set is Konduktor's own data.
|
// it nor touches version history — an export set is Konduktor's own data.
|
||||||
@@ -467,7 +527,7 @@ export default function App() {
|
|||||||
)
|
)
|
||||||
// One dropped audio file on the deck: loaded to listen to, added to nothing.
|
// One dropped audio file on the deck: loaded to listen to, added to nothing.
|
||||||
const loadDropped = useCallback(
|
const loadDropped = useCallback(
|
||||||
async (path: string) => {
|
async (path: string, deck: DeckId = targetDeckRef.current) => {
|
||||||
const r = await readDrop([path])
|
const r = await readDrop([path])
|
||||||
if (!r) return
|
if (!r) return
|
||||||
const t = r.tracks[0]
|
const t = r.tracks[0]
|
||||||
@@ -475,7 +535,7 @@ export default function App() {
|
|||||||
onError('That is not an audio file this library can hold.')
|
onError('That is not an audio file this library can hold.')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
loadTrack(t, r.files[t.id] ? 'collection' : 'folder')
|
loadTrack(t, r.files[t.id] ? 'collection' : 'folder', deck)
|
||||||
},
|
},
|
||||||
[readDrop, loadTrack, onError],
|
[readDrop, loadTrack, onError],
|
||||||
)
|
)
|
||||||
@@ -496,14 +556,25 @@ export default function App() {
|
|||||||
const audioFormats = capabilities.data?.tracks.audio_formats
|
const audioFormats = capabilities.data?.tracks.audio_formats
|
||||||
const isAudioPath = (path: string) =>
|
const isAudioPath = (path: string) =>
|
||||||
path.lastIndexOf('.') > 0 && !!audioFormats?.includes(path.slice(path.lastIndexOf('.')).toLowerCase())
|
path.lastIndexOf('.') > 0 && !!audioFormats?.includes(path.slice(path.lastIndexOf('.')).toLowerCase())
|
||||||
const [deckDropRef, deckOver] = useDropTarget<true>({
|
// A track (the row grabbed) or one audio file, dropped on a deck: loaded
|
||||||
|
// paused. In performance mode each waveform lane is a target for its own
|
||||||
|
// deck; anywhere else on the strip loads the focused one.
|
||||||
|
const deckDrop: DeckDrop = {
|
||||||
hint: (p) =>
|
hint: (p) =>
|
||||||
p.kind === 'tracks' || (p.kind === 'files' && p.paths.length === 1 && isAudioPath(p.paths[0])) ? true : null,
|
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'),
|
label: (p, deck) => {
|
||||||
onDrop: (p) => {
|
const into = performance ? `deck ${deck}` : 'the deck'
|
||||||
if (p.kind === 'tracks') loadTrack(p.lead, p.origin)
|
return p.kind === 'tracks' && p.ids.length > 1 ? `Load “${p.lead.title || 'Untitled'}” into ${into}` : `Load into ${into}`
|
||||||
else if (p.kind === 'files') void loadDropped(p.paths[0])
|
|
||||||
},
|
},
|
||||||
|
onDrop: (p, deck) => {
|
||||||
|
if (p.kind === 'tracks') loadTrack(p.lead, p.origin, deck)
|
||||||
|
else if (p.kind === 'files') void loadDropped(p.paths[0], deck)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
const [deckDropRef, deckOver] = useDropTarget<true>({
|
||||||
|
hint: deckDrop.hint,
|
||||||
|
label: (p) => deckDrop.label(p, targetDeck),
|
||||||
|
onDrop: (p) => deckDrop.onDrop(p, targetDeck),
|
||||||
})
|
})
|
||||||
// Files dropped anywhere no other target takes them: the collection. A
|
// Files dropped anywhere no other target takes them: the collection. A
|
||||||
// library that cannot add tracks still takes the drop, to say why not —
|
// library that cannot add tracks still takes the drop, to say why not —
|
||||||
@@ -562,8 +633,8 @@ export default function App() {
|
|||||||
// tracks and edit as such, and a loose row asks to be added first
|
// tracks and edit as such, and a loose row asks to be added first
|
||||||
// (`folderMayEdit`) rather than rendering inert.
|
// (`folderMayEdit`) rather than rendering inert.
|
||||||
const viewCaps = viewingFolder ? capabilities.data! : capsFor(viewOriginRef.current)
|
const viewCaps = viewingFolder ? capabilities.data! : capsFor(viewOriginRef.current)
|
||||||
// The deck follows its TRACK's library, not the view's.
|
// A deck follows its TRACK's library, not the view's.
|
||||||
const deckCaps = capsFor(prepOrigin)
|
const deckCaps = { A: capsFor(decks.A.origin), B: capsFor(decks.B.origin) }
|
||||||
|
|
||||||
const deviceLabel = openDevice.data?.label ?? 'device'
|
const deviceLabel = openDevice.data?.label ?? 'device'
|
||||||
// One name for whatever is on screen, so the header and the status bar cannot
|
// One name for whatever is on screen, so the header and the status bar cannot
|
||||||
@@ -621,14 +692,16 @@ export default function App() {
|
|||||||
// PrepStrip keys its audio on the id, so a new object for the same id
|
// PrepStrip keys its audio on the id, so a new object for the same id
|
||||||
// reloads nothing.
|
// reloads nothing.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!prepTrack) return
|
setDecks((d) =>
|
||||||
const fresh = tracks.find((t) => t.id === prepTrack.id)
|
mapDecks(d, (s) => {
|
||||||
if (!fresh) return
|
if (!s.track) return s
|
||||||
const origin =
|
const fresh = tracks.find((t) => t.id === s.track!.id)
|
||||||
viewOriginRef.current === 'folder' && folderFilesRef.current[fresh.id] ? 'collection' : viewOriginRef.current
|
if (!fresh) return s
|
||||||
if (origin === prepOrigin && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh)
|
const origin =
|
||||||
// Only a refetch of the list matters; prepTrack is read, not tracked.
|
viewOriginRef.current === 'folder' && folderFilesRef.current[fresh.id] ? 'collection' : viewOriginRef.current
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
return origin === s.origin && JSON.stringify(fresh) !== JSON.stringify(s.track) ? { ...s, track: fresh } : s
|
||||||
|
}),
|
||||||
|
)
|
||||||
}, [tracks])
|
}, [tracks])
|
||||||
|
|
||||||
const loading = viewingFolder
|
const loading = viewingFolder
|
||||||
@@ -824,7 +897,7 @@ export default function App() {
|
|||||||
const f = failures[0]
|
const f = failures[0]
|
||||||
parts.push(`${failures.length} failed (${f.title}: ${f.reason}${failures.length > 1 ? ', …' : ''})`)
|
parts.push(`${failures.length} failed (${f.title}: ${f.reason}${failures.length > 1 ? ', …' : ''})`)
|
||||||
}
|
}
|
||||||
if (prepTrack && touched.includes(prepTrack.id)) setCuesRefresh((n) => n + 1)
|
bumpDeckCues(touched)
|
||||||
notify(failures.length && touched.length === 0 ? 'error' : 'success', parts.filter(Boolean).join(' · '))
|
notify(failures.length && touched.length === 0 ? 'error' : 'success', parts.filter(Boolean).join(' · '))
|
||||||
// Only the job's finish matters here; prepTrack is read, not tracked.
|
// Only the job's finish matters here; prepTrack is read, not tracked.
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
@@ -835,9 +908,8 @@ export default function App() {
|
|||||||
setSource({ kind: 'all' })
|
setSource({ kind: 'all' })
|
||||||
setSelected(new Set())
|
setSelected(new Set())
|
||||||
setBatchJob(null) // the backend cancels it; its result is for the old library
|
setBatchJob(null) // the backend cancels it; its result is for the old library
|
||||||
// The deck starts empty: its track belongs to the old library.
|
// The decks start empty: their tracks belong to the old library.
|
||||||
setPrepTrack(null)
|
setDecks({ A: EMPTY_SLOT, B: EMPTY_SLOT })
|
||||||
setPlayRequest(0)
|
|
||||||
setFilters(emptyFilters)
|
setFilters(emptyFilters)
|
||||||
setSorting([])
|
setSorting([])
|
||||||
qc.invalidateQueries() // refetch everything for the newly-opened collection
|
qc.invalidateQueries() // refetch everything for the newly-opened collection
|
||||||
@@ -877,10 +949,13 @@ export default function App() {
|
|||||||
// A repointed track's id IS its location, so it changed: follow it with the
|
// A repointed track's id IS its location, so it changed: follow it with the
|
||||||
// deck and the selection instead of leaving them on an id that is gone.
|
// deck and the selection instead of leaving them on an id that is gone.
|
||||||
const renamed = r.renamed
|
const renamed = r.renamed
|
||||||
if (prepTrack && renamed[prepTrack.id]) {
|
setDecks((d) =>
|
||||||
setPrepTrack({ ...prepTrack, id: renamed[prepTrack.id], media_kind: 'stem' })
|
mapDecks(d, (s) =>
|
||||||
setCuesRefresh((n) => n + 1)
|
s.track && renamed[s.track.id]
|
||||||
}
|
? { ...s, track: { ...s.track, id: renamed[s.track.id], media_kind: 'stem' }, cuesRefresh: s.cuesRefresh + 1 }
|
||||||
|
: s,
|
||||||
|
),
|
||||||
|
)
|
||||||
setSelected((sel) => new Set([...sel].map((id) => renamed[id] ?? id)))
|
setSelected((sel) => new Set([...sel].map((id) => renamed[id] ?? id)))
|
||||||
const n = r.converted.length
|
const n = r.converted.length
|
||||||
const parts = [
|
const parts = [
|
||||||
@@ -1067,7 +1142,7 @@ export default function App() {
|
|||||||
qc.invalidateQueries({ queryKey: ['playlists'] })
|
qc.invalidateQueries({ queryKey: ['playlists'] })
|
||||||
qc.invalidateQueries({ queryKey: ['export-contents'] })
|
qc.invalidateQueries({ queryKey: ['export-contents'] })
|
||||||
qc.invalidateQueries({ queryKey: ['facets'] })
|
qc.invalidateQueries({ queryKey: ['facets'] })
|
||||||
if (cuesChanged && prepTrack && ids.includes(prepTrack.id)) setCuesRefresh((n) => n + 1)
|
if (cuesChanged) bumpDeckCues(ids)
|
||||||
}
|
}
|
||||||
const guard = async (fn: () => Promise<void>) => {
|
const guard = async (fn: () => Promise<void>) => {
|
||||||
try {
|
try {
|
||||||
@@ -1094,6 +1169,50 @@ export default function App() {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Remove ▸ From playlist ▸ <name>: tracks picked anywhere leave a playlist
|
||||||
|
// that is not open — every copy of each. Counted first, so the dialog says
|
||||||
|
// how many of the selection it actually holds (and still answers at 0).
|
||||||
|
const confirmRemoveFromOther = async (p: PlaylistNode, ids: string[]) => {
|
||||||
|
let r
|
||||||
|
try {
|
||||||
|
r = await api.removeEntries(p.id, ids, true)
|
||||||
|
} catch (e) {
|
||||||
|
onError((e as Error).message)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const name = <span className="text-text">{p.name}</span>
|
||||||
|
const held = r.tracks
|
||||||
|
setConfirmReq({
|
||||||
|
title: 'Remove from playlist',
|
||||||
|
body: !held ? (
|
||||||
|
<p>
|
||||||
|
{ids.length === 1 ? <>{trackNoun(ids)} is not</> : <>None of these {ids.length} tracks are</>} in {name}.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p>
|
||||||
|
Remove {held === ids.length ? trackNoun(ids) : `${held} of the ${ids.length} selected tracks`} from {name}?
|
||||||
|
The {held === 1 ? 'track stays' : 'tracks stay'} in the collection.
|
||||||
|
</p>
|
||||||
|
{held < ids.length && (
|
||||||
|
<p className="text-faint">The other {nTracks(ids.length - held)} {ids.length - held === 1 ? 'is' : 'are'} not in it.</p>
|
||||||
|
)}
|
||||||
|
{r.removed > held && <p className="text-faint">Some are in it more than once; every copy goes.</p>}
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
confirmLabel: held ? `Remove ${nTracks(held)}` : 'Remove',
|
||||||
|
confirmDisabled: !held,
|
||||||
|
onConfirm: () =>
|
||||||
|
guard(async () => {
|
||||||
|
const done = await api.removeEntries(p.id, ids)
|
||||||
|
qc.invalidateQueries({ queryKey: ['playlist', p.id] })
|
||||||
|
qc.invalidateQueries({ queryKey: ['playlists'] })
|
||||||
|
qc.invalidateQueries({ queryKey: ['state'] })
|
||||||
|
notify('success', `Removed ${nTracks(done.tracks)} from ${p.name}`)
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const confirmRemoveFromExport = (exportId: string, ids: string[]) => {
|
const confirmRemoveFromExport = (exportId: string, ids: string[]) => {
|
||||||
const name = exportSets.data?.find((x) => x.id === exportId)?.name ?? 'this export'
|
const name = exportSets.data?.find((x) => x.id === exportId)?.name ?? 'this export'
|
||||||
setConfirmReq({
|
setConfirmReq({
|
||||||
@@ -1177,7 +1296,7 @@ export default function App() {
|
|||||||
guard(async () => {
|
guard(async () => {
|
||||||
const r = await api.removeTracks(ids)
|
const r = await api.removeTracks(ids)
|
||||||
setSelected(new Set())
|
setSelected(new Set())
|
||||||
if (prepTrack && ids.includes(prepTrack.id)) setPrepTrack(null)
|
unloadDecks(ids)
|
||||||
afterBulk(ids, false)
|
afterBulk(ids, false)
|
||||||
notify('success', `Removed ${nTracks(r.removed)} from the collection`)
|
notify('success', `Removed ${nTracks(r.removed)} from the collection`)
|
||||||
}),
|
}),
|
||||||
@@ -1231,6 +1350,22 @@ export default function App() {
|
|||||||
...(playlistEditable
|
...(playlistEditable
|
||||||
? [{ label: 'From this playlist…', onClick: () => confirmRemoveFromPlaylist(ids) }]
|
? [{ label: 'From this playlist…', onClick: () => confirmRemoveFromPlaylist(ids) }]
|
||||||
: []),
|
: []),
|
||||||
|
// Any other editable playlist — "A minus B" is: open B, select all, here A.
|
||||||
|
...(() => {
|
||||||
|
// A device's ids mean nothing to the collection's playlists.
|
||||||
|
if (viewingDevice) return []
|
||||||
|
const lists = removablePlaylists.filter((p) => !(source.kind === 'playlist' && p.id === source.id))
|
||||||
|
return lists.length
|
||||||
|
? [{
|
||||||
|
label: 'From playlist',
|
||||||
|
submenu: lists.map((p) => ({
|
||||||
|
label: p.name,
|
||||||
|
hint: String(p.count),
|
||||||
|
onClick: () => void confirmRemoveFromOther(p, ids),
|
||||||
|
})),
|
||||||
|
}]
|
||||||
|
: []
|
||||||
|
})(),
|
||||||
// Only on the export's ROOT view. Inside a referenced playlist there is
|
// Only on the export's ROOT view. Inside a referenced playlist there is
|
||||||
// nothing to remove: the reference is live, and per-track removal would
|
// nothing to remove: the reference is live, and per-track removal would
|
||||||
// need an exclusion list — hidden state deciding what a future export
|
// need an exclusion list — hidden state deciding what a future export
|
||||||
@@ -1322,7 +1457,12 @@ export default function App() {
|
|||||||
items={[
|
items={[
|
||||||
// Single-track actions are hidden, not disabled, for a multi-selection.
|
// Single-track actions are hidden, not disabled, for a multi-selection.
|
||||||
...(menu.ids.length === 1
|
...(menu.ids.length === 1
|
||||||
? [{ label: 'Load to Deck', onClick: () => loadTrack(menu.track) }]
|
? performance
|
||||||
|
? (['A', 'B'] as const).map((d) => ({
|
||||||
|
label: `Load to Deck ${d}`,
|
||||||
|
onClick: () => loadTrack(menu.track, undefined, d),
|
||||||
|
}))
|
||||||
|
: [{ label: 'Load to Deck', onClick: () => loadTrack(menu.track) }]
|
||||||
: []),
|
: []),
|
||||||
// Offering "Edit Tags…" on a read-only library would open a dialog
|
// Offering "Edit Tags…" on a read-only library would open a dialog
|
||||||
// whose every save is refused, so it is not offered at all.
|
// whose every save is refused, so it is not offered at all.
|
||||||
@@ -1619,19 +1759,22 @@ export default function App() {
|
|||||||
{deckOver && (
|
{deckOver && (
|
||||||
<div aria-hidden className="pointer-events-none absolute inset-0 z-10 rounded-[22px] ring-2 ring-accent" />
|
<div aria-hidden className="pointer-events-none absolute inset-0 z-10 rounded-[22px] ring-2 ring-accent" />
|
||||||
)}
|
)}
|
||||||
<CapabilitiesContext.Provider value={deckCaps}>
|
<CapabilitiesContext.Provider value={deckCaps[targetDeck]}>
|
||||||
<PrepStrip
|
<PrepStrip
|
||||||
track={prepTrack}
|
decks={decks}
|
||||||
playRequest={playRequest}
|
caps={deckCaps}
|
||||||
|
performance={performance}
|
||||||
|
onTogglePerformance={togglePerformance}
|
||||||
|
focused={focusedDeck}
|
||||||
|
onFocus={setFocusedDeck}
|
||||||
|
drop={deckDrop}
|
||||||
onError={onError}
|
onError={onError}
|
||||||
onNotify={notify}
|
onNotify={notify}
|
||||||
origin={prepOrigin}
|
onPlayingChange={onDeckPlaying}
|
||||||
cuesRefresh={cuesRefresh}
|
|
||||||
onPlayingChange={setDeckPlaying}
|
|
||||||
// As the context menu's: a library that would refuse the save is
|
// As the context menu's: a library that would refuse the save is
|
||||||
// not offered the dialog, and a deck track outside the collection
|
// 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.
|
// (a device's, a loose file's) is not the collection's to edit.
|
||||||
onEditTags={canEdit && prepOrigin === 'collection' ? setEditing : undefined}
|
onEditTags={canEdit ? setEditing : undefined}
|
||||||
/>
|
/>
|
||||||
</CapabilitiesContext.Provider>
|
</CapabilitiesContext.Provider>
|
||||||
</div>
|
</div>
|
||||||
@@ -1648,7 +1791,7 @@ export default function App() {
|
|||||||
onDone={(msg) => notify('success', msg)}
|
onDone={(msg) => notify('success', msg)}
|
||||||
onAddForeign={addForeign}
|
onAddForeign={addForeign}
|
||||||
onOpenPathMapping={() => setShowPaths(true)}
|
onOpenPathMapping={() => setShowPaths(true)}
|
||||||
onDiscarded={() => afterBulk(prepTrack ? [prepTrack.id] : [], true)}
|
onDiscarded={() => afterBulk([decks.A.track?.id, decks.B.track?.id].filter((x): x is string => !!x), true)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<CapabilitiesContext.Provider value={viewCaps}>
|
<CapabilitiesContext.Provider value={viewCaps}>
|
||||||
@@ -1657,6 +1800,7 @@ export default function App() {
|
|||||||
<Toolbar
|
<Toolbar
|
||||||
filters={filters}
|
filters={filters}
|
||||||
onChange={setFilters}
|
onChange={setFilters}
|
||||||
|
trailing={<PerformanceButton on={performance} onToggle={togglePerformance} />}
|
||||||
/>
|
/>
|
||||||
{(!isAll || viewForeign) && (
|
{(!isAll || viewForeign) && (
|
||||||
<div className="flex items-center gap-3 border-b border-line px-4 py-2">
|
<div className="flex items-center gap-3 border-b border-line px-4 py-2">
|
||||||
@@ -1796,7 +1940,7 @@ export default function App() {
|
|||||||
onPlay={playTrack}
|
onPlay={playTrack}
|
||||||
onEditField={canEdit ? editField : undefined}
|
onEditField={canEdit ? editField : undefined}
|
||||||
activeTrackId={prepTrack?.id ?? null}
|
activeTrackId={prepTrack?.id ?? null}
|
||||||
activePlaying={deckPlaying}
|
activePlaying={deckPlaying[targetDeck]}
|
||||||
columnVisibility={columnVisibility}
|
columnVisibility={columnVisibility}
|
||||||
columnOrder={columnOrder}
|
columnOrder={columnOrder}
|
||||||
columnSizing={columnSizing}
|
columnSizing={columnSizing}
|
||||||
@@ -1838,7 +1982,7 @@ export default function App() {
|
|||||||
onEditField={canEdit ? folderEditField : undefined}
|
onEditField={canEdit ? folderEditField : undefined}
|
||||||
mayEdit={folderMayEdit}
|
mayEdit={folderMayEdit}
|
||||||
activeTrackId={prepTrack?.id ?? null}
|
activeTrackId={prepTrack?.id ?? null}
|
||||||
activePlaying={deckPlaying}
|
activePlaying={deckPlaying[targetDeck]}
|
||||||
columnVisibility={columnVisibility}
|
columnVisibility={columnVisibility}
|
||||||
columnOrder={columnOrder}
|
columnOrder={columnOrder}
|
||||||
columnSizing={columnSizing}
|
columnSizing={columnSizing}
|
||||||
@@ -1873,7 +2017,7 @@ export default function App() {
|
|||||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||||
onPlay={playTrack}
|
onPlay={playTrack}
|
||||||
activeTrackId={prepTrack?.id ?? null}
|
activeTrackId={prepTrack?.id ?? null}
|
||||||
activePlaying={deckPlaying}
|
activePlaying={deckPlaying[targetDeck]}
|
||||||
columnVisibility={columnVisibility}
|
columnVisibility={columnVisibility}
|
||||||
columnOrder={columnOrder}
|
columnOrder={columnOrder}
|
||||||
columnSizing={columnSizing}
|
columnSizing={columnSizing}
|
||||||
@@ -1898,7 +2042,7 @@ export default function App() {
|
|||||||
onPlay={playTrack}
|
onPlay={playTrack}
|
||||||
onEditField={canEdit ? editField : undefined}
|
onEditField={canEdit ? editField : undefined}
|
||||||
activeTrackId={prepTrack?.id ?? null}
|
activeTrackId={prepTrack?.id ?? null}
|
||||||
activePlaying={deckPlaying}
|
activePlaying={deckPlaying[targetDeck]}
|
||||||
columnVisibility={columnVisibility}
|
columnVisibility={columnVisibility}
|
||||||
columnOrder={columnOrder}
|
columnOrder={columnOrder}
|
||||||
columnSizing={columnSizing}
|
columnSizing={columnSizing}
|
||||||
@@ -1951,7 +2095,7 @@ export default function App() {
|
|||||||
onPlay={playTrack}
|
onPlay={playTrack}
|
||||||
onEditField={canEdit ? editField : undefined}
|
onEditField={canEdit ? editField : undefined}
|
||||||
activeTrackId={prepTrack?.id ?? null}
|
activeTrackId={prepTrack?.id ?? null}
|
||||||
activePlaying={deckPlaying}
|
activePlaying={deckPlaying[targetDeck]}
|
||||||
columnVisibility={columnVisibility}
|
columnVisibility={columnVisibility}
|
||||||
columnOrder={columnOrder}
|
columnOrder={columnOrder}
|
||||||
columnSizing={columnSizing}
|
columnSizing={columnSizing}
|
||||||
|
|||||||
+97
-5
@@ -828,6 +828,13 @@ export interface SourceStatus {
|
|||||||
export interface ExportSet {
|
export interface ExportSet {
|
||||||
id: string
|
id: string
|
||||||
name: string
|
name: string
|
||||||
|
/** 'folder': exported into `destination`. 'computer': PUSHED into the DJ
|
||||||
|
* apps' own libraries on this computer (`targets` names the apps, there is
|
||||||
|
* no destination), `mode` saying how. */
|
||||||
|
kind: 'folder' | 'computer'
|
||||||
|
/** A push: 'merge' adds and updates only what this set put there;
|
||||||
|
* 'overwrite' replaces the whole library with this set. */
|
||||||
|
mode: 'merge' | 'overwrite'
|
||||||
/** Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
|
/** Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
|
||||||
* empty. They share one destination and ONE copy of the audio. */
|
* empty. They share one destination and ONE copy of the audio. */
|
||||||
targets: string[]
|
targets: string[]
|
||||||
@@ -896,6 +903,66 @@ export interface ExportPreview {
|
|||||||
to_measure: number
|
to_measure: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One DJ app's library on this computer, as a push target. */
|
||||||
|
export interface LocalLibrary {
|
||||||
|
platform: string
|
||||||
|
name: string
|
||||||
|
path: string | null
|
||||||
|
/** Found by the platform's own detection (false: the user's setting). */
|
||||||
|
detected: boolean
|
||||||
|
/** A FACT; the UI words it. */
|
||||||
|
blocked: 'not_found' | 'open_in_konduktor' | 'cloud_synced' | 'unreadable' | null
|
||||||
|
running: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LocalLibraries {
|
||||||
|
libraries: LocalLibrary[]
|
||||||
|
/** The shared folder pushed audio lives in, and its default. */
|
||||||
|
audio_root: string
|
||||||
|
audio_root_default: string
|
||||||
|
/** The shared folder's Normalise level; null = off. */
|
||||||
|
level: NormalizeOptions | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PushTarget {
|
||||||
|
platform: string
|
||||||
|
name: string
|
||||||
|
path: string | null
|
||||||
|
blocked: LocalLibrary['blocked']
|
||||||
|
/** Not on this computer: the push passes it over instead of blocking. */
|
||||||
|
skipped: boolean
|
||||||
|
running: boolean
|
||||||
|
/** Tracks this set has not pushed here before. */
|
||||||
|
add: number
|
||||||
|
/** Tracks it has: kept, or brought up to date where changed. */
|
||||||
|
already: number
|
||||||
|
/** Tracks that left the set since the last push. */
|
||||||
|
remove: number
|
||||||
|
/** Overwrite: the other sets pushed here, which it removes. */
|
||||||
|
wipes_sets: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a push would do now. Computed fresh every time. */
|
||||||
|
export interface PushPreview {
|
||||||
|
mode: 'merge' | 'overwrite'
|
||||||
|
tracks: number
|
||||||
|
pushable: number
|
||||||
|
/** Copies in the shared folder kept rather than copied again. */
|
||||||
|
unchanged: number
|
||||||
|
missing: string[]
|
||||||
|
playlists: string[]
|
||||||
|
total_bytes: number
|
||||||
|
audio_root: string
|
||||||
|
free_bytes: number | null
|
||||||
|
enough_space: boolean | null
|
||||||
|
normalised: number
|
||||||
|
level_counts: Record<string, number>
|
||||||
|
to_measure: number
|
||||||
|
targets: PushTarget[]
|
||||||
|
/** A FACT, not a sentence. Null when the push can run. */
|
||||||
|
blocked: 'no_target' | 'no_library_here' | 'nothing_to_push' | 'target_unavailable' | 'app_running' | null
|
||||||
|
}
|
||||||
|
|
||||||
/** The run dialog's options; each is remembered on the set. Omitted = the
|
/** The run dialog's options; each is remembered on the set. Omitted = the
|
||||||
* set's own answer. */
|
* set's own answer. */
|
||||||
export interface ExportRunOptions {
|
export interface ExportRunOptions {
|
||||||
@@ -1073,8 +1140,12 @@ export const api = {
|
|||||||
// shortcuts and the browsable files are only meaningful inside that answer.
|
// shortcuts and the browsable files are only meaningful inside that answer.
|
||||||
collectionOptions: (platform?: string) =>
|
collectionOptions: (platform?: string) =>
|
||||||
getJSON<CollectionOptions>(`/api/library/options${qs({ platform })}`),
|
getJSON<CollectionOptions>(`/api/library/options${qs({ platform })}`),
|
||||||
listDir: (path?: string, platform?: string) =>
|
listDir: (path?: string, platform?: string, suffix?: string) =>
|
||||||
getJSON<FsListing>(`/api/fs/list${qs({ path, platform })}`),
|
getJSON<FsListing>(`/api/fs/list${qs({ path, platform, suffix })}`),
|
||||||
|
/** A MIDI controller mapping to / from a file (lib/midi/mapping.ts). */
|
||||||
|
midiExport: (dir: string, name: string, mapping: unknown) =>
|
||||||
|
send<{ path: string }>('POST', '/api/midi/export', { dir, name, mapping }),
|
||||||
|
midiImport: (path: string) => getJSON<{ mapping: unknown }>(`/api/midi/import${qs({ path })}`),
|
||||||
/** Folders on the machine that HOLDS the library (a remote's server),
|
/** Folders on the machine that HOLDS the library (a remote's server),
|
||||||
* confined to its content folder — `home` is that folder. */
|
* confined to its content folder — `home` is that folder. */
|
||||||
libraryListDir: (path?: string) => getJSON<FsListing>(`/api/library/fs/list${qs({ path })}`),
|
libraryListDir: (path?: string) => getJSON<FsListing>(`/api/library/fs/list${qs({ path })}`),
|
||||||
@@ -1098,11 +1169,16 @@ export const api = {
|
|||||||
// All scoped to the LOADED library on the server, by its stable id, so
|
// All scoped to the LOADED library on the server, by its stable id, so
|
||||||
// nothing here has to carry which collection it means.
|
// nothing here has to carry which collection it means.
|
||||||
exports: () => getJSON<ExportSet[]>('/api/exports'),
|
exports: () => getJSON<ExportSet[]>('/api/exports'),
|
||||||
createExport: (body: { name: string; targets: string[]; destination: string }) =>
|
createExport: (body: {
|
||||||
send<ExportSet>('POST', '/api/exports', body),
|
name: string
|
||||||
|
targets: string[]
|
||||||
|
destination: string
|
||||||
|
kind?: ExportSet['kind']
|
||||||
|
mode?: ExportSet['mode']
|
||||||
|
}) => send<ExportSet>('POST', '/api/exports', body),
|
||||||
updateExport: (
|
updateExport: (
|
||||||
id: string,
|
id: string,
|
||||||
body: Partial<Pick<ExportSet, 'name' | 'targets' | 'destination' | 'lock_grids'>>,
|
body: Partial<Pick<ExportSet, 'name' | 'targets' | 'destination' | 'lock_grids' | 'mode'>>,
|
||||||
) =>
|
) =>
|
||||||
send<ExportSet>('PATCH', `/api/exports/${encodeURIComponent(id)}`, body),
|
send<ExportSet>('PATCH', `/api/exports/${encodeURIComponent(id)}`, body),
|
||||||
deleteExport: (id: string) =>
|
deleteExport: (id: string) =>
|
||||||
@@ -1138,6 +1214,14 @@ export const api = {
|
|||||||
// The run dialog's options travel with the click; the set remembers them.
|
// The run dialog's options travel with the click; the set remembers them.
|
||||||
runExport: (id: string, body: ExportRunOptions = {}) =>
|
runExport: (id: string, body: ExportRunOptions = {}) =>
|
||||||
send<JobStatus>('POST', `/api/exports/${encodeURIComponent(id)}/run`, body),
|
send<JobStatus>('POST', `/api/exports/${encodeURIComponent(id)}/run`, body),
|
||||||
|
// A "computer" set: pushed into this computer's Traktor / rekordbox. Only
|
||||||
|
// lock_grids and auto_gain apply — Normalise is the shared folder's, set in
|
||||||
|
// Settings → Local libraries (`localNormalise` / `localLevel` prefs).
|
||||||
|
localLibraries: () => getJSON<LocalLibraries>('/api/local-libraries'),
|
||||||
|
pushPreview: (id: string, body: ExportRunOptions = {}) =>
|
||||||
|
send<PushPreview>('POST', `/api/exports/${encodeURIComponent(id)}/push/preview`, body),
|
||||||
|
runPush: (id: string, body: ExportRunOptions = {}) =>
|
||||||
|
send<JobStatus>('POST', `/api/exports/${encodeURIComponent(id)}/push`, body),
|
||||||
|
|
||||||
// ---- path remapping (per-collection OS-path prefix translation) ----
|
// ---- path remapping (per-collection OS-path prefix translation) ----
|
||||||
getPathMapping: () => getJSON<PathMapping>('/api/library/path-mapping'),
|
getPathMapping: () => getJSON<PathMapping>('/api/library/path-mapping'),
|
||||||
@@ -1192,6 +1276,14 @@ export const api = {
|
|||||||
`/api/playlists/${encodeURIComponent(nodeId)}/add`,
|
`/api/playlists/${encodeURIComponent(nodeId)}/add`,
|
||||||
{ track_ids: trackIds, duplicates, index },
|
{ track_ids: trackIds, duplicates, index },
|
||||||
),
|
),
|
||||||
|
/** Remove every occurrence of these tracks. `dryRun` changes nothing and
|
||||||
|
* counts: `tracks` = how many of them it holds, `removed` = entries. */
|
||||||
|
removeEntries: (nodeId: string, trackIds: string[], dryRun = false) =>
|
||||||
|
send<{ status: 'removed' | 'counted'; tracks: number; removed: number; count: number }>(
|
||||||
|
'POST',
|
||||||
|
`/api/playlists/${encodeURIComponent(nodeId)}/remove`,
|
||||||
|
{ track_ids: trackIds, dry_run: dryRun },
|
||||||
|
),
|
||||||
/** Move a tree node to `index` among `parentId`'s children (null = top
|
/** Move a tree node to `index` among `parentId`'s children (null = top
|
||||||
* level), counted without it. Answers its id AFTER the move. */
|
* level), counted without it. Answers its id AFTER the move. */
|
||||||
movePlaylist: (nodeId: string, parentId: string | null, index: number) =>
|
movePlaylist: (nodeId: string, parentId: string | null, index: number) =>
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus, type TrackOrigin } from '../api'
|
import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus, type TrackOrigin } from '../api'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
import { placedAudioSummary } from '../lib/platformCopy'
|
import { placedAudioSummary } from '../lib/platformCopy'
|
||||||
import { FolderPicker } from './FolderPicker'
|
import { FolderPicker } from './FolderPicker'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add browsed files to the collection — and, optionally, to a playlist or export.
|
* Add browsed files to the collection — and, optionally, to a playlist or export.
|
||||||
@@ -253,7 +253,7 @@ export function AddFilesDialog({ trackIds, target: requested, note, onClose, onD
|
|||||||
</label>
|
</label>
|
||||||
)
|
)
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<>
|
<>
|
||||||
{browsing && (
|
{browsing && (
|
||||||
<FolderPicker
|
<FolderPicker
|
||||||
@@ -267,10 +267,7 @@ export function AddFilesDialog({ trackIds, target: requested, note, onClose, onD
|
|||||||
onClose={() => setBrowsing(false)}
|
onClose={() => setBrowsing(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div
|
<Modal onDismiss={onClose} padding="p-4">
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-[3px]"
|
|
||||||
>
|
|
||||||
<div className="w-full max-w-lg glass-overlay">
|
<div className="w-full max-w-lg glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-3">
|
<div className="border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">{title}</h2>
|
<h2 className="text-sm font-semibold text-text">{title}</h2>
|
||||||
@@ -461,9 +458,8 @@ export function AddFilesDialog({ trackIds, target: requested, note, onClose, onD
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</>,
|
</>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useState, type ReactNode } from 'react'
|
import { useEffect, useState, type ReactNode } from 'react'
|
||||||
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type AnalyzeOptions, type AnalyzePreview, type TrackOrigin } from '../api'
|
import { api, type AnalyzeOptions, type AnalyzePreview, type TrackOrigin } from '../api'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
/** The selected tracks. */
|
/** The selected tracks. */
|
||||||
@@ -100,12 +100,6 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, gainWhy, preset, o
|
|||||||
const nothingTicked = !!what && !(what.bpm || what.grid || what.key || what.loudness || what.gain)
|
const nothingTicked = !!what && !(what.bpm || what.grid || what.key || what.loudness || what.gain)
|
||||||
const count = nothingTicked ? 0 : (p?.tracks_to_analyze ?? 0)
|
const count = nothingTicked ? 0 : (p?.tracks_to_analyze ?? 0)
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && onClose()
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [busy, onClose])
|
|
||||||
|
|
||||||
const run = async () => {
|
const run = async () => {
|
||||||
if (!opts || busy || count === 0) return
|
if (!opts || busy || count === 0) return
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
@@ -186,13 +180,9 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, gainWhy, preset, o
|
|||||||
if (p.grid_locked) gridLines.push(<div key="lk" className="text-faint">{plural(p.grid_locked, 'locked grid')} — skipped</div>)
|
if (p.grid_locked) gridLines.push(<div key="lk" className="text-faint">{plural(p.grid_locked, 'locked grid')} — skipped</div>)
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={busy ? null : onClose}>
|
||||||
aria-modal="true"
|
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={() => !busy && onClose()}
|
|
||||||
>
|
|
||||||
<div className="w-full max-w-sm overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Analyze</div>
|
<div className="text-[15px] font-semibold tracking-tight">Analyze</div>
|
||||||
<div className="text-xs text-muted">{plural(ids.length, 'track')} selected</div>
|
<div className="text-xs text-muted">{plural(ids.length, 'track')} selected</div>
|
||||||
@@ -265,7 +255,6 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, gainWhy, preset, o
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Settings → Konduktor: preferences about the app itself rather than about a
|
* Settings → Konduktor: preferences about the app itself rather than about a
|
||||||
@@ -21,6 +21,32 @@ export const APP_SETTING_DEFAULTS = {
|
|||||||
levelMeasure: 'lufs' as 'lufs' | 'rms',
|
levelMeasure: 'lufs' as 'lufs' | 'rms',
|
||||||
levelTarget: -9,
|
levelTarget: -9,
|
||||||
levelCeiling: -1,
|
levelCeiling: -1,
|
||||||
|
// Performance mode (decided 2026-11-02 / -03) — its own panel,
|
||||||
|
// PerformanceSettings.tsx.
|
||||||
|
/** Stem tracks load as stems into a performance deck (else their mix: one
|
||||||
|
* time-stretcher instead of four). Read when a track loads. */
|
||||||
|
perfStems: true,
|
||||||
|
/** A deck's keylock starts on. */
|
||||||
|
keylockDefault: true,
|
||||||
|
/** Any press on a deck focuses it (else only its A/B badge). */
|
||||||
|
autoFocusDeck: true,
|
||||||
|
/** A channel's gain starts at the track's auto gain (else 0 dB). */
|
||||||
|
useAutoGain: true,
|
||||||
|
/** EQ full left kills the band (else -26 dB, DJM-style). */
|
||||||
|
eqKill: false,
|
||||||
|
/** The crossfader curve: 0 smooth (constant power) .. 1 sharp (a cut).
|
||||||
|
* Default halfway: both channels full across the middle, fading over the
|
||||||
|
* outer half of the travel each (decided 2026-11-03). */
|
||||||
|
crossfaderSharpness: 0.5,
|
||||||
|
/** Filter FX: the filter's range and resonance, and each effect's one
|
||||||
|
* parameter (the mixer has no knob for them). */
|
||||||
|
fxFilterRange: 'full' as 'full' | 'musical' | 'gentle',
|
||||||
|
fxEffectRange: 'musical' as 'full' | 'musical' | 'gentle',
|
||||||
|
fxFilterResonance: 0.3,
|
||||||
|
fxReverbSize: 2,
|
||||||
|
fxDelayBeats: 0.25,
|
||||||
|
fxCrusherDrive: 2,
|
||||||
|
fxFlangerBeats: 4,
|
||||||
}
|
}
|
||||||
|
|
||||||
type AppSettingKey = keyof typeof APP_SETTING_DEFAULTS
|
type AppSettingKey = keyof typeof APP_SETTING_DEFAULTS
|
||||||
@@ -42,12 +68,6 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
|
|||||||
const levelCeiling = useAppSetting('levelCeiling')
|
const levelCeiling = useAppSetting('levelCeiling')
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [onClose])
|
|
||||||
|
|
||||||
const set = async (patch: Partial<typeof APP_SETTING_DEFAULTS>) => {
|
const set = async (patch: Partial<typeof APP_SETTING_DEFAULTS>) => {
|
||||||
setError(null)
|
setError(null)
|
||||||
try {
|
try {
|
||||||
@@ -57,13 +77,9 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true"
|
<div className="flex w-full max-w-md flex-col overflow-hidden glass-overlay">
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6 backdrop-blur-[3px]"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div className="flex w-full max-w-md flex-col overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="flex items-center justify-between border-b border-line px-5 py-3">
|
<div className="flex items-center justify-between border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">Konduktor settings</h2>
|
<h2 className="text-sm font-semibold text-text">Konduktor settings</h2>
|
||||||
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
|
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
|
||||||
@@ -166,8 +182,44 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Check({ checked, onChange, title, text }: {
|
||||||
|
checked: boolean; onChange: (v: boolean) => void; title: string; text?: string
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<label className="flex cursor-pointer items-start gap-2.5">
|
||||||
|
<input type="checkbox" className="mt-0.5" checked={checked} onChange={(e) => onChange(e.target.checked)} />
|
||||||
|
<span className="min-w-0">
|
||||||
|
<span className="block text-sm text-text">{title}</span>
|
||||||
|
{text && <span className="block text-xs text-faint">{text}</span>}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A setting picked from a list. A stored value not in the list (an older
|
||||||
|
* build's) shows as the list's first entry until changed. */
|
||||||
|
export function Choice({ title, value, options, onChange }: {
|
||||||
|
title: string; value: string; options: [string, string][]; onChange: (v: string) => void
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<label className="flex items-center justify-between gap-4">
|
||||||
|
<span className="text-sm text-text">{title}</span>
|
||||||
|
<select
|
||||||
|
className="shrink-0 rounded-lg well px-2 py-1 text-sm text-text outline-none"
|
||||||
|
value={options.some(([v]) => v === value) ? value : options[0][0]}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
>
|
||||||
|
{options.map(([v, label]) => (
|
||||||
|
<option key={v} value={v}>
|
||||||
|
{label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import {
|
import {
|
||||||
@@ -10,6 +9,7 @@ import {
|
|||||||
type Track,
|
type Track,
|
||||||
} from '../api'
|
} from '../api'
|
||||||
import { formatDuration } from '../lib/format'
|
import { formatDuration } from '../lib/format'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Auto Hotcues: bind each hotcue slot to a structural event plus an offset in
|
* Auto Hotcues: bind each hotcue slot to a structural event plus an offset in
|
||||||
@@ -109,14 +109,6 @@ export function AutoCueDialog(props: Props) {
|
|||||||
if (rows === null && (prefs.data || prefs.isError)) setRows(loadTemplate(prefs.data, slotCount))
|
if (rows === null && (prefs.data || prefs.isError)) setRows(loadTemplate(prefs.data, slotCount))
|
||||||
}, [prefs.data, prefs.isError, rows, slotCount])
|
}, [prefs.data, prefs.isError, rows, slotCount])
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => {
|
|
||||||
if (e.key === 'Escape' && !busy) onClose()
|
|
||||||
}
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [busy, onClose])
|
|
||||||
|
|
||||||
const setRow = (i: number, patch: Partial<Row>) =>
|
const setRow = (i: number, patch: Partial<Row>) =>
|
||||||
setRows((rs) => rs && rs.map((r, j) => (j === i ? { ...r, ...patch } : r)))
|
setRows((rs) => rs && rs.map((r, j) => (j === i ? { ...r, ...patch } : r)))
|
||||||
const nudge = (i: number, by: number) =>
|
const nudge = (i: number, by: number) =>
|
||||||
@@ -152,11 +144,10 @@ export function AutoCueDialog(props: Props) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6" onClick={() => !busy && onClose()}>
|
<Modal onDismiss={busy ? null : onClose}>
|
||||||
<div
|
<div
|
||||||
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay"
|
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Auto Hotcues</div>
|
<div className="text-[15px] font-semibold tracking-tight">Auto Hotcues</div>
|
||||||
@@ -294,7 +285,6 @@ export function AutoCueDialog(props: Props) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useState, type ReactNode } from 'react'
|
import { useEffect, useState, type ReactNode } from 'react'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
export interface ConfirmRequest {
|
export interface ConfirmRequest {
|
||||||
title: string
|
title: string
|
||||||
@@ -14,6 +14,9 @@ export interface ConfirmRequest {
|
|||||||
* (e.g. "Add them again" next to "Add 6 new"). Enter still means confirm. */
|
* (e.g. "Add them again" next to "Add 6 new"). Enter still means confirm. */
|
||||||
altLabel?: string
|
altLabel?: string
|
||||||
onAlt?: () => void
|
onAlt?: () => void
|
||||||
|
/** Nothing to confirm (e.g. none of the tracks are there): the dialog
|
||||||
|
* still answers, with the confirm button — and Enter — off. */
|
||||||
|
confirmDisabled?: boolean
|
||||||
onConfirm: () => Promise<void> | void
|
onConfirm: () => Promise<void> | void
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,11 +26,11 @@ interface Props extends ConfirmRequest {
|
|||||||
|
|
||||||
/** A yes/no confirmation for destructive actions. Enter confirms and Esc
|
/** A yes/no confirmation for destructive actions. Enter confirms and Esc
|
||||||
* cancels, so a confirmed Delete key stays a two-keystroke action. */
|
* cancels, so a confirmed Delete key stays a two-keystroke action. */
|
||||||
export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altLabel, onAlt, onConfirm, onClose }: Props) {
|
export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altLabel, onAlt, confirmDisabled, onConfirm, onClose }: Props) {
|
||||||
const [busy, setBusy] = useState(false)
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
||||||
const confirm = async () => {
|
const confirm = async () => {
|
||||||
if (busy) return
|
if (busy || confirmDisabled) return
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
try {
|
try {
|
||||||
await onConfirm()
|
await onConfirm()
|
||||||
@@ -39,7 +42,6 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altL
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onKey = (e: KeyboardEvent) => {
|
const onKey = (e: KeyboardEvent) => {
|
||||||
if (e.key === 'Escape' && !busy) onClose()
|
|
||||||
// A focused button handles its own Enter — otherwise tabbing to Cancel
|
// A focused button handles its own Enter — otherwise tabbing to Cancel
|
||||||
// and pressing Enter would run the destructive action.
|
// and pressing Enter would run the destructive action.
|
||||||
if (e.key === 'Enter' && !(e.target instanceof HTMLButtonElement)) {
|
if (e.key === 'Enter' && !(e.target instanceof HTMLButtonElement)) {
|
||||||
@@ -51,16 +53,9 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altL
|
|||||||
return () => window.removeEventListener('keydown', onKey)
|
return () => window.removeEventListener('keydown', onKey)
|
||||||
})
|
})
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={busy ? null : onClose}>
|
||||||
aria-modal="true"
|
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={() => !busy && onClose()}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="w-full max-w-sm overflow-hidden glass-overlay"
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
|
||||||
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
||||||
{title}
|
{title}
|
||||||
</div>
|
</div>
|
||||||
@@ -87,7 +82,7 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altL
|
|||||||
)}
|
)}
|
||||||
<button
|
<button
|
||||||
onClick={() => void confirm()}
|
onClick={() => void confirm()}
|
||||||
disabled={busy}
|
disabled={busy || confirmDisabled}
|
||||||
className={`rounded-full px-4 py-1.5 text-sm font-semibold disabled:opacity-50 ${
|
className={`rounded-full px-4 py-1.5 text-sm font-semibold disabled:opacity-50 ${
|
||||||
tone === 'primary'
|
tone === 'primary'
|
||||||
? 'btn-primary'
|
? 'btn-primary'
|
||||||
@@ -98,7 +93,6 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altL
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -31,6 +31,8 @@ interface Props {
|
|||||||
y: number
|
y: number
|
||||||
items: MenuItem[]
|
items: MenuItem[]
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
|
/** The panel's minimum width (px); 0 lets a short list fit its labels. */
|
||||||
|
minWidth?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
const SUBMENU_WIDTH = 240
|
const SUBMENU_WIDTH = 240
|
||||||
@@ -40,7 +42,7 @@ const SUBMENU_MAX_HEIGHT = 288
|
|||||||
const MENU_MAX_HEIGHT = 400
|
const MENU_MAX_HEIGHT = 400
|
||||||
|
|
||||||
// Lightweight fixed-position menu. Closes on outside click, scroll, or Escape.
|
// Lightweight fixed-position menu. Closes on outside click, scroll, or Escape.
|
||||||
export function ContextMenu({ x, y, items, onClose }: Props) {
|
export function ContextMenu({ x, y, items, onClose, minWidth = 160 }: Props) {
|
||||||
const rootRef = useRef<HTMLDivElement>(null)
|
const rootRef = useRef<HTMLDivElement>(null)
|
||||||
// Read through a ref so the listeners are attached ONCE. Callers pass an
|
// Read through a ref so the listeners are attached ONCE. Callers pass an
|
||||||
// inline `onClose`; if the effect depended on it, a click that re-renders the
|
// inline `onClose`; if the effect depended on it, a click that re-renders the
|
||||||
@@ -102,8 +104,7 @@ export function ContextMenu({ x, y, items, onClose }: Props) {
|
|||||||
<MenuPanel
|
<MenuPanel
|
||||||
items={items}
|
items={items}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
className="min-w-[160px]"
|
style={{ ...vertical, minWidth, left: Math.min(x, window.innerWidth - 180) }}
|
||||||
style={{ ...vertical, left: Math.min(x, window.innerWidth - 180) }}
|
|
||||||
/>
|
/>
|
||||||
</div>,
|
</div>,
|
||||||
document.body,
|
document.body,
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useMemo, useState, type ReactNode } from 'react'
|
import { useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import {
|
import {
|
||||||
@@ -12,6 +11,7 @@ import {
|
|||||||
import { FolderPicker } from './FolderPicker'
|
import { FolderPicker } from './FolderPicker'
|
||||||
import { useServerFolder } from './AddFilesDialog'
|
import { useServerFolder } from './AddFilesDialog'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert to Stems — one dialog (decided, see the stem-conversion discussion
|
* Convert to Stems — one dialog (decided, see the stem-conversion discussion
|
||||||
@@ -224,7 +224,7 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
|
|||||||
)
|
)
|
||||||
|
|
||||||
const count = trackIds.length
|
const count = trackIds.length
|
||||||
return createPortal(
|
return (
|
||||||
<>
|
<>
|
||||||
{browsing && opts && (
|
{browsing && opts && (
|
||||||
<FolderPicker
|
<FolderPicker
|
||||||
@@ -239,11 +239,7 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
|
|||||||
onClose={() => setBrowsing(false)}
|
onClose={() => setBrowsing(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div
|
<Modal onDismiss={starting ? null : onClose} padding="p-4">
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-[3px]"
|
|
||||||
onKeyDown={(e) => e.key === 'Escape' && !starting && onClose()}
|
|
||||||
>
|
|
||||||
<div className="flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden glass-overlay">
|
<div className="flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-3">
|
<div className="border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">
|
<h2 className="text-sm font-semibold text-text">
|
||||||
@@ -477,8 +473,7 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</>,
|
</>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useRef, useState } from 'react'
|
import { useRef, useState } from 'react'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type Track } from '../api'
|
import { api, type Track } from '../api'
|
||||||
@@ -7,6 +6,7 @@ import { useCaps } from '../lib/capabilities'
|
|||||||
import { RatingStars } from './RatingStars'
|
import { RatingStars } from './RatingStars'
|
||||||
import { writeHint } from '../lib/platformCopy'
|
import { writeHint } from '../lib/platformCopy'
|
||||||
import { invalidateTrackLists } from '../lib/trackQueries'
|
import { invalidateTrackLists } from '../lib/trackQueries'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
track: Track
|
track: Track
|
||||||
@@ -96,14 +96,10 @@ export function EditTagsDialog({ track, onClose, onApplied, onError }: Props) {
|
|||||||
apply.mutate()
|
apply.mutate()
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="flex max-h-[85vh] w-full max-w-lg flex-col overflow-hidden glass-overlay"
|
className="flex max-h-[85vh] w-full max-w-lg flex-col overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Edit Tags</div>
|
<div className="text-[15px] font-semibold tracking-tight">Edit Tags</div>
|
||||||
@@ -240,7 +236,6 @@ export function EditTagsDialog({ track, onClose, onApplied, onError }: Props) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { api, type ExportSet } from '../api'
|
import { api, type ExportSet, type LocalLibrary } from '../api'
|
||||||
|
import { localLibraryProblem } from '../lib/platformCopy'
|
||||||
import { FolderPicker } from './FolderPicker'
|
import { FolderPicker } from './FolderPicker'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create or edit an export: its name, its target platforms and where it lands.
|
* Create or edit an export: its name, its target platforms and where it lands.
|
||||||
@@ -15,6 +16,13 @@ import { FolderPicker } from './FolderPicker'
|
|||||||
* detail deferred to export time. A Traktor `<LOCATION>` is a volume name plus
|
* detail deferred to export time. A Traktor `<LOCATION>` is a volume name plus
|
||||||
* a volume-relative path — both derived from where the export is written — so
|
* a volume-relative path — both derived from where the export is written — so
|
||||||
* the library file genuinely cannot be built until the destination is known.
|
* the library file genuinely cannot be built until the destination is known.
|
||||||
|
*
|
||||||
|
* Or the set goes to THIS COMPUTER: pushed straight into the Traktor collection
|
||||||
|
* and/or rekordbox library its DJ apps use (`local_push.py`), merging beside
|
||||||
|
* the user's own tracks or replacing the library. No destination is asked —
|
||||||
|
* which library each app uses, and the shared audio folder, are this
|
||||||
|
* computer's settings. The kind is chosen once, at creation: a push leaves
|
||||||
|
* records of what it put where, which a change of kind would orphan.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -29,6 +37,15 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
const [name, setName] = useState(editing?.name ?? '')
|
const [name, setName] = useState(editing?.name ?? '')
|
||||||
const [chosen, setChosen] = useState<string[]>(editing?.targets ?? ['traktor'])
|
const [chosen, setChosen] = useState<string[]>(editing?.targets ?? ['traktor'])
|
||||||
const [destination, setDestination] = useState(editing?.destination ?? '')
|
const [destination, setDestination] = useState(editing?.destination ?? '')
|
||||||
|
const [kind, setKind] = useState<ExportSet['kind']>(editing?.kind ?? 'folder')
|
||||||
|
const [mode, setMode] = useState<ExportSet['mode']>(editing?.mode ?? 'merge')
|
||||||
|
const computer = kind === 'computer'
|
||||||
|
// A push's targets: this computer's DJ apps, each with why it cannot be used.
|
||||||
|
const locals = useQuery({
|
||||||
|
queryKey: ['local-libraries'],
|
||||||
|
queryFn: api.localLibraries,
|
||||||
|
enabled: computer,
|
||||||
|
})
|
||||||
const [browsing, setBrowsing] = useState(false)
|
const [browsing, setBrowsing] = useState(false)
|
||||||
const [busy, setBusy] = useState(false)
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
||||||
@@ -68,15 +85,32 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
on ? [...prev.filter((t) => t !== platform), platform] : prev.filter((t) => t !== platform),
|
on ? [...prev.filter((t) => t !== platform), platform] : prev.filter((t) => t !== platform),
|
||||||
)
|
)
|
||||||
|
|
||||||
const valid = name.trim() !== '' && destination.trim() !== '' && chosen.length > 0
|
// A set's targets are shared by every computer that opens this library (a
|
||||||
|
// remote's sets live on its server), so a library missing HERE can still be
|
||||||
|
// ticked or unticked — the push skips it on this computer. Anything else
|
||||||
|
// wrong with a library here can always be unticked, never newly ticked.
|
||||||
|
const lockedOut = (lib: LocalLibrary) =>
|
||||||
|
!!lib.blocked && lib.blocked !== 'not_found' && !chosen.includes(lib.platform)
|
||||||
|
const valid = computer
|
||||||
|
? name.trim() !== '' && chosen.length > 0
|
||||||
|
: name.trim() !== '' && destination.trim() !== '' && chosen.length > 0
|
||||||
|
|
||||||
|
const chooseKind = (next: ExportSet['kind']) => {
|
||||||
|
setKind(next)
|
||||||
|
// The two kinds offer different platforms: start from the obvious one.
|
||||||
|
setChosen(['traktor'])
|
||||||
|
}
|
||||||
|
|
||||||
const save = async () => {
|
const save = async () => {
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
try {
|
try {
|
||||||
const body = { name: name.trim(), targets: chosen, destination: destination.trim() }
|
|
||||||
const saved = editing
|
const saved = editing
|
||||||
? await api.updateExport(editing.id, body)
|
? await api.updateExport(editing.id, computer
|
||||||
: await api.createExport(body)
|
? { name: name.trim(), targets: chosen, mode }
|
||||||
|
: { name: name.trim(), targets: chosen, destination: destination.trim() })
|
||||||
|
: await api.createExport(computer
|
||||||
|
? { name: name.trim(), targets: chosen, destination: '', kind, mode }
|
||||||
|
: { name: name.trim(), targets: chosen, destination: destination.trim() })
|
||||||
onSaved(saved, !editing)
|
onSaved(saved, !editing)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
onError((e as Error).message)
|
onError((e as Error).message)
|
||||||
@@ -85,7 +119,7 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<>
|
<>
|
||||||
{browsing && (
|
{browsing && (
|
||||||
<FolderPicker
|
<FolderPicker
|
||||||
@@ -94,11 +128,11 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
onClose={() => setBrowsing(false)}
|
onClose={() => setBrowsing(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-4">
|
<Modal onDismiss={onClose} padding="p-4">
|
||||||
<div className="w-full max-w-lg glass-overlay">
|
<div className="w-full max-w-lg glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-3">
|
<div className="border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">
|
<h2 className="text-sm font-semibold text-text">
|
||||||
{editing ? `Edit “${editing.name}”` : 'New export'}
|
{editing ? `Edit “${editing.name}”` : computer ? 'New push to this computer' : 'New export'}
|
||||||
</h2>
|
</h2>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -117,6 +151,101 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{!editing && (
|
||||||
|
<div>
|
||||||
|
<span className="mb-1 block text-xs text-muted">Where</span>
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
{([
|
||||||
|
['folder', 'A folder or drive', 'Writes a library and a copy of the audio there — a USB stick for the gig.'],
|
||||||
|
['computer', 'This computer', 'Pushes into the Traktor or rekordbox you DJ with here.'],
|
||||||
|
] as const).map(([value, title, detail]) => (
|
||||||
|
<button
|
||||||
|
key={value}
|
||||||
|
onClick={() => chooseKind(value)}
|
||||||
|
aria-pressed={kind === value}
|
||||||
|
className={`rounded-lg px-3 py-2 text-left ${
|
||||||
|
kind === value ? 'is-selected well' : 'btn-glass'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="block text-sm text-text">{title}</span>
|
||||||
|
<span className="mt-0.5 block text-[11px] leading-snug text-faint">{detail}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{computer ? (
|
||||||
|
<>
|
||||||
|
<div>
|
||||||
|
<span className="mb-1 block text-xs text-muted">Into</span>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{(locals.data?.libraries ?? []).map((lib) => {
|
||||||
|
const missing = lib.blocked === 'not_found'
|
||||||
|
const problem = missing
|
||||||
|
? `${localLibraryProblem(lib)} — skipped when pushing from this computer`
|
||||||
|
: localLibraryProblem(lib)
|
||||||
|
const disabled = lockedOut(lib)
|
||||||
|
return (
|
||||||
|
<label
|
||||||
|
key={lib.platform}
|
||||||
|
className={`flex items-start gap-2 rounded-md px-2 py-1.5 ${
|
||||||
|
disabled ? 'cursor-not-allowed' : 'cursor-pointer hover:bg-ink-850'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
disabled={disabled}
|
||||||
|
checked={chosen.includes(lib.platform)}
|
||||||
|
onChange={(e) => toggle(lib.platform, e.target.checked)}
|
||||||
|
className="mt-0.5 accent-accent"
|
||||||
|
/>
|
||||||
|
<span className="min-w-0 flex-1">
|
||||||
|
<span className={problem ? 'text-faint' : 'text-text'}>{lib.name}</span>
|
||||||
|
<span
|
||||||
|
title={lib.path ?? undefined}
|
||||||
|
className="block truncate text-[11px] text-faint"
|
||||||
|
>
|
||||||
|
{problem ?? lib.path}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-[11px] text-faint">
|
||||||
|
The audio is copied to{' '}
|
||||||
|
<span className="font-mono">{locals.data?.audio_root ?? '…'}</span>, shared by
|
||||||
|
every push. Change either in Settings → Local libraries.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<span className="mb-1 block text-xs text-muted">How</span>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{([
|
||||||
|
['merge', 'Merge', 'Adds and updates this set’s tracks, in a folder named after it. Your own tracks and playlists are never touched.'],
|
||||||
|
['overwrite', 'Overwrite', 'Replaces the WHOLE library with this set. Everything else in it — your own tracks, playlists and other pushes — is removed.'],
|
||||||
|
] as const).map(([value, title, detail]) => (
|
||||||
|
<label key={value} className="flex cursor-pointer items-start gap-2 rounded-md px-2 py-1.5 hover:bg-ink-850">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="push-mode"
|
||||||
|
checked={mode === value}
|
||||||
|
onChange={() => setMode(value)}
|
||||||
|
className="mt-0.5 accent-accent"
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
<span className={value === 'overwrite' ? 'text-pink' : 'text-text'}>{title}</span>
|
||||||
|
<span className="block text-[11px] leading-snug text-faint">{detail}</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
<div>
|
<div>
|
||||||
<span className="mb-1 block text-xs text-muted">For</span>
|
<span className="mb-1 block text-xs text-muted">For</span>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
@@ -187,6 +316,8 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
|
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
|
||||||
@@ -205,8 +336,7 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</>,
|
</>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type ExportPreview, type ExportRunOptions, type ExportSet, type JobStatus, type NormalizeOptions } from '../api'
|
import { api, type ExportPreview, type ExportRunOptions, type ExportSet, type JobStatus, type NormalizeOptions } from '../api'
|
||||||
import { FolderPicker } from './FolderPicker'
|
import { FolderPicker } from './FolderPicker'
|
||||||
import { LevelInput, useAppSetting } from './AppSettings'
|
import { LevelInput, useAppSetting } from './AppSettings'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run an export: confirm what is about to happen, then watch it happen.
|
* Run an export: confirm what is about to happen, then watch it happen.
|
||||||
@@ -175,7 +175,7 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) {
|
|||||||
: null
|
: null
|
||||||
const blocked = p?.blocked ?? null
|
const blocked = p?.blocked ?? null
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<>
|
<>
|
||||||
{browsing && (
|
{browsing && (
|
||||||
<FolderPicker
|
<FolderPicker
|
||||||
@@ -184,7 +184,7 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) {
|
|||||||
onClose={() => setBrowsing(false)}
|
onClose={() => setBrowsing(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-4">
|
<Modal onDismiss={onClose} padding="p-4">
|
||||||
<div className="w-full max-w-lg glass-overlay">
|
<div className="w-full max-w-lg glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-3">
|
<div className="border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">Export “{set.name}”</h2>
|
<h2 className="text-sm font-semibold text-text">Export “{set.name}”</h2>
|
||||||
@@ -472,9 +472,8 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</>,
|
</>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import type { AddTarget, ForeignOrigin } from './AddFilesDialog'
|
|||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
import { ExportDialog } from './ExportDialog'
|
import { ExportDialog } from './ExportDialog'
|
||||||
import { ExportRunDialog } from './ExportRunDialog'
|
import { ExportRunDialog } from './ExportRunDialog'
|
||||||
|
import { PushRunDialog } from './PushRunDialog'
|
||||||
import type { Source } from './Sidebar'
|
import type { Source } from './Sidebar'
|
||||||
import { askConfirm } from '../lib/confirm'
|
import { askConfirm } from '../lib/confirm'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
@@ -74,7 +75,16 @@ export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{running && (
|
{running?.kind === 'computer' && (
|
||||||
|
<PushRunDialog
|
||||||
|
set={running}
|
||||||
|
onClose={() => setRunning(null)}
|
||||||
|
onDone={onDone}
|
||||||
|
onError={onError}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{running && running.kind !== 'computer' && (
|
||||||
<ExportRunDialog
|
<ExportRunDialog
|
||||||
set={running}
|
set={running}
|
||||||
onClose={() => setRunning(null)}
|
onClose={() => setRunning(null)}
|
||||||
@@ -118,7 +128,9 @@ export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign
|
|||||||
if (
|
if (
|
||||||
await askConfirm({
|
await askConfirm({
|
||||||
title: `Delete the export “${set.name}”?`,
|
title: `Delete the export “${set.name}”?`,
|
||||||
body: 'Nothing already exported is removed — the files in its folder stay where they are.',
|
body: set.kind === 'computer'
|
||||||
|
? 'Nothing already pushed is removed — its tracks and playlists stay in your DJ apps.'
|
||||||
|
: 'Nothing already exported is removed — the files in its folder stay where they are.',
|
||||||
confirmLabel: 'Delete export',
|
confirmLabel: 'Delete export',
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
@@ -257,8 +269,17 @@ function ExportRow({
|
|||||||
onClick={() => onSelect({ kind: 'export', id: set.id, name: set.name })}
|
onClick={() => onSelect({ kind: 'export', id: set.id, name: set.name })}
|
||||||
className="flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left text-sm"
|
className="flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left text-sm"
|
||||||
>
|
>
|
||||||
<span className="flex w-4 shrink-0 justify-center text-gold"><Icon name="export" size={14} /></span>
|
{/* A push into this computer's DJ apps reads differently from a
|
||||||
<span className="flex-1 truncate" title={set.destination}>
|
folder export at a glance: the target is this machine. */}
|
||||||
|
<span className="flex w-4 shrink-0 justify-center text-gold">
|
||||||
|
<Icon name={set.kind === 'computer' ? 'desktop' : 'export'} size={14} />
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className="flex-1 truncate"
|
||||||
|
title={set.kind === 'computer'
|
||||||
|
? `Pushed into this computer’s ${set.targets.join(' and ')} (${set.mode})`
|
||||||
|
: set.destination}
|
||||||
|
>
|
||||||
{set.name}
|
{set.name}
|
||||||
</span>
|
</span>
|
||||||
<span className="shrink-0 text-[10px] tabular-nums text-faint">
|
<span className="shrink-0 text-[10px] tabular-nums text-faint">
|
||||||
@@ -266,7 +287,7 @@ function ExportRow({
|
|||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
title="Edit name, platforms and destination"
|
title={set.kind === 'computer' ? 'Edit name, apps and how it pushes' : 'Edit name, platforms and destination'}
|
||||||
onClick={onEdit}
|
onClick={onEdit}
|
||||||
className="shrink-0 px-1 text-xs text-faint opacity-0 hover:text-text group-hover:opacity-100"
|
className="shrink-0 px-1 text-xs text-faint opacity-0 hover:text-text group-hover:opacity-100"
|
||||||
>
|
>
|
||||||
@@ -366,7 +387,7 @@ function ExportRow({
|
|||||||
style={{ marginLeft: 24 }}
|
style={{ marginLeft: 24 }}
|
||||||
className="mb-1 mt-1 rounded-full btn-primary px-2 py-1 text-xs font-semibold"
|
className="mb-1 mt-1 rounded-full btn-primary px-2 py-1 text-xs font-semibold"
|
||||||
>
|
>
|
||||||
Export {data.tracks} track{data.tracks === 1 ? '' : 's'}…
|
{set.kind === 'computer' ? 'Push' : 'Export'} {data.tracks} track{data.tracks === 1 ? '' : 's'}…
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -26,10 +26,10 @@ import { Icon, type IconName } from '../lib/icons'
|
|||||||
* the cache key. Passing it back up through a callback would mean an effect
|
* the cache key. Passing it back up through a callback would mean an effect
|
||||||
* firing on every navigation to tell the parent what it already asked for.
|
* firing on every navigation to tell the parent what it already asked for.
|
||||||
*/
|
*/
|
||||||
export function useFsListing(path: string | undefined, platform?: string, listing: Listing = 'host') {
|
export function useFsListing(path: string | undefined, platform?: string, listing: Listing = 'host', suffix?: string) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['fs', listing, path ?? '~', platform ?? null],
|
queryKey: ['fs', listing, path ?? '~', platform ?? null, suffix ?? null],
|
||||||
queryFn: () => (listing === 'library' ? api.libraryListDir(path) : api.listDir(path, platform)),
|
queryFn: () => (listing === 'library' ? api.libraryListDir(path) : api.listDir(path, platform, suffix)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,10 +65,12 @@ interface Props {
|
|||||||
footer?: ReactNode
|
footer?: ReactNode
|
||||||
/** Whose folders are browsed (see `Listing`). Default: this computer's. */
|
/** Whose folders are browsed (see `Listing`). Default: this computer's. */
|
||||||
listing?: Listing
|
listing?: Listing
|
||||||
|
/** Instead of a platform's files, those whose name ends with this. */
|
||||||
|
suffix?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer, listing: whose = 'host' }: Props) {
|
export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer, listing: whose = 'host', suffix }: Props) {
|
||||||
const listing = useFsListing(path, platform, whose)
|
const listing = useFsListing(path, platform, whose, suffix)
|
||||||
const places = useQuery({
|
const places = useQuery({
|
||||||
queryKey: ['fs-places', platform ?? null],
|
queryKey: ['fs-places', platform ?? null],
|
||||||
queryFn: () => api.places(platform),
|
queryFn: () => api.places(platform),
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { FileBrowser, useFsListing, type Listing } from './FileBrowser'
|
import { FileBrowser, useFsListing, type Listing } from './FileBrowser'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pick a FOLDER, by browsing.
|
* Pick a FOLDER, by browsing.
|
||||||
@@ -33,8 +33,8 @@ export function FolderPicker({ value, onChange, onClose, listing = 'host' }: Pro
|
|||||||
onClose()
|
onClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div aria-modal="true" className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-4">
|
<Modal onDismiss={onClose} layer="nested" padding="p-4">
|
||||||
<div className="flex h-[70vh] w-full max-w-2xl flex-col overflow-hidden glass-overlay">
|
<div className="flex h-[70vh] w-full max-w-2xl flex-col overflow-hidden glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-3">
|
<div className="border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">Choose a folder</h2>
|
<h2 className="text-sm font-semibold text-text">Choose a folder</h2>
|
||||||
@@ -84,7 +84,6 @@ export function FolderPicker({ value, onChange, onClose, listing = 'host' }: Pro
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type HistoryEntry } from '../api'
|
import { api, type HistoryEntry } from '../api'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
import { restoreWarning } from '../lib/platformCopy'
|
import { restoreWarning } from '../lib/platformCopy'
|
||||||
import type { ToastMsg } from './Toast'
|
import type { ToastMsg } from './Toast'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
@@ -79,14 +79,10 @@ export function HistoryPanel({ onClose, onNotify, onError }: Props) {
|
|||||||
|
|
||||||
const entries = history.data ?? []
|
const entries = history.data ?? []
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay"
|
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Version History</div>
|
<div className="text-[15px] font-semibold tracking-tight">Version History</div>
|
||||||
@@ -208,7 +204,6 @@ export function HistoryPanel({ onClose, onNotify, onError }: Props) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,8 @@ import { Icon } from '../lib/icons'
|
|||||||
import { RenameField } from './RenameField'
|
import { RenameField } from './RenameField'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
|
/** The deck's MIDI action prefix (`deck.A`), for on-screen learning. */
|
||||||
|
midi?: string
|
||||||
cues: CuePoint[]
|
cues: CuePoint[]
|
||||||
/** Bank size, from capabilities — not every platform has eight. */
|
/** Bank size, from capabilities — not every platform has eight. */
|
||||||
slotCount: number
|
slotCount: number
|
||||||
@@ -42,6 +44,7 @@ const READONLY_LABELS: Record<string, string> = {
|
|||||||
* than surfacing the refusal as an error.
|
* than surfacing the refusal as an error.
|
||||||
*/
|
*/
|
||||||
export function HotcueBar({
|
export function HotcueBar({
|
||||||
|
midi,
|
||||||
cues,
|
cues,
|
||||||
slotCount,
|
slotCount,
|
||||||
slotLabel,
|
slotLabel,
|
||||||
@@ -74,6 +77,7 @@ export function HotcueBar({
|
|||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={slot}
|
key={slot}
|
||||||
|
data-midi-action={midi && `${midi}.hotcue.${slot + 1}`}
|
||||||
onContextMenu={(e) => {
|
onContextMenu={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
onSlotMenu(slot, e.clientX, e.clientY)
|
onSlotMenu(slot, e.clientX, e.clientY)
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type ImportPreview, type JobStatus } from '../api'
|
import { api, type ImportPreview, type JobStatus } from '../api'
|
||||||
@@ -7,6 +6,7 @@ import { placedAudioSummary } from '../lib/platformCopy'
|
|||||||
import type { AddTarget } from './AddFilesDialog'
|
import type { AddTarget } from './AddFilesDialog'
|
||||||
import { FolderPicker } from './FolderPicker'
|
import { FolderPicker } from './FolderPicker'
|
||||||
import { useServerImportFolder, usePlaylistToggle } from './AddFilesDialog'
|
import { useServerImportFolder, usePlaylistToggle } from './AddFilesDialog'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Import a browsed device into the loaded collection.
|
* Import a browsed device into the loaded collection.
|
||||||
@@ -173,7 +173,7 @@ export function ImportDialog({ playlistId, trackIds, target: requested, deviceLa
|
|||||||
const finished = job != null && job.state !== 'running'
|
const finished = job != null && job.state !== 'running'
|
||||||
const pct = job && job.total > 0 ? Math.min(100, (job.done / job.total) * 100) : null
|
const pct = job && job.total > 0 ? Math.min(100, (job.done / job.total) * 100) : null
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<>
|
<>
|
||||||
{browsing && (
|
{browsing && (
|
||||||
<FolderPicker
|
<FolderPicker
|
||||||
@@ -187,7 +187,7 @@ export function ImportDialog({ playlistId, trackIds, target: requested, deviceLa
|
|||||||
onClose={() => setBrowsing(false)}
|
onClose={() => setBrowsing(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-4">
|
<Modal onDismiss={onClose} padding="p-4">
|
||||||
<div className="w-full max-w-lg glass-overlay">
|
<div className="w-full max-w-lg glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-3">
|
<div className="border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">
|
<h2 className="text-sm font-semibold text-text">
|
||||||
@@ -373,8 +373,7 @@ export function ImportDialog({ playlistId, trackIds, target: requested, deviceLa
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</>,
|
</>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { api, type NormalizeOptions } from '../api'
|
||||||
|
import { localLibraryProblem } from '../lib/platformCopy'
|
||||||
|
import { FolderPicker } from './FolderPicker'
|
||||||
|
import { LevelInput, useAppSetting } from './AppSettings'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings → Local libraries: where a "This computer" set is pushed.
|
||||||
|
*
|
||||||
|
* This computer's, not the set's: a remote library's sets are kept on its
|
||||||
|
* server, but which Traktor collection and rekordbox library a laptop DJs from,
|
||||||
|
* and where their audio goes, belong to the laptop. So they are prefs —
|
||||||
|
* `localLibraries` ({platform: path | null}, null = detected), `localAudioRoot`,
|
||||||
|
* `localNormalise` and `localLevel`.
|
||||||
|
*
|
||||||
|
* The audio folder is SHARED by every push, so a file has one level: Normalise
|
||||||
|
* lives here rather than on a set. A library is chosen by its FOLDER (the
|
||||||
|
* `Traktor 4.x` folder, rekordbox's), the file in it being the platform's own.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const LIBRARY_FILE: Record<string, string> = { traktor: 'collection.nml', rekordbox: 'master.db' }
|
||||||
|
|
||||||
|
export function LocalLibrariesSettings({ onClose }: { onClose: () => void }) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
const locals = useQuery({ queryKey: ['local-libraries'], queryFn: api.localLibraries })
|
||||||
|
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
|
||||||
|
const defaultMeasure = useAppSetting('levelMeasure')
|
||||||
|
const defaultTarget = useAppSetting('levelTarget')
|
||||||
|
const defaultCeiling = useAppSetting('levelCeiling')
|
||||||
|
const [picking, setPicking] = useState<string | null>(null) // a platform, or 'audio'
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const p = prefs.data ?? {}
|
||||||
|
const overrides = (p.localLibraries as Record<string, string | null> | undefined) ?? {}
|
||||||
|
const normalise = p.localNormalise === true
|
||||||
|
const stored = p.localLevel as Partial<NormalizeOptions> | undefined
|
||||||
|
const level: NormalizeOptions = {
|
||||||
|
measure: stored?.measure ?? defaultMeasure,
|
||||||
|
target: stored?.target ?? defaultTarget,
|
||||||
|
ceiling: stored?.ceiling ?? defaultCeiling,
|
||||||
|
}
|
||||||
|
|
||||||
|
const patch = async (body: Record<string, unknown>) => {
|
||||||
|
setError(null)
|
||||||
|
try {
|
||||||
|
qc.setQueryData(['prefs'], await api.patchPrefs(body))
|
||||||
|
qc.invalidateQueries({ queryKey: ['local-libraries'] })
|
||||||
|
qc.invalidateQueries({ queryKey: ['push-preview'] })
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const choose = (folder: string) => {
|
||||||
|
if (picking === 'audio') {
|
||||||
|
patch({ localAudioRoot: folder })
|
||||||
|
} else if (picking) {
|
||||||
|
const sep = folder.includes('\\') && !folder.includes('/') ? '\\' : '/'
|
||||||
|
patch({ localLibraries: { ...overrides, [picking]: `${folder.replace(/[\\/]+$/, '')}${sep}${LIBRARY_FILE[picking]}` } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const d = locals.data
|
||||||
|
const pickerValue =
|
||||||
|
picking === 'audio'
|
||||||
|
? d?.audio_root ?? ''
|
||||||
|
: (d?.libraries.find((l) => l.platform === picking)?.path ?? '').replace(/[\\/][^\\/]*$/, '')
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{picking && (
|
||||||
|
<FolderPicker value={pickerValue} onChange={choose} onClose={() => setPicking(null)} />
|
||||||
|
)}
|
||||||
|
<Modal onDismiss={onClose}>
|
||||||
|
<div className="flex max-h-full w-full max-w-lg flex-col overflow-hidden glass-overlay">
|
||||||
|
<div className="flex items-center justify-between border-b border-line px-5 py-3">
|
||||||
|
<h2 className="text-sm font-semibold text-text">Local libraries</h2>
|
||||||
|
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="min-h-0 space-y-5 overflow-y-auto px-5 py-4 text-sm">
|
||||||
|
<p className="text-muted">
|
||||||
|
Where an export set made for <span className="text-text">This computer</span> is pushed:
|
||||||
|
the DJ apps you play from here, and one folder for their audio.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<section className="space-y-2">
|
||||||
|
<h3 className="text-[11px] uppercase tracking-wider text-faint">DJ apps</h3>
|
||||||
|
{(d?.libraries ?? []).map((lib) => {
|
||||||
|
const problem = lib.blocked === 'open_in_konduktor' ? null : localLibraryProblem(lib)
|
||||||
|
return (
|
||||||
|
<div key={lib.platform} className="rounded-md well px-3 py-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-text">{lib.name}</span>
|
||||||
|
<span className="text-[11px] text-faint">{lib.detected ? 'found automatically' : 'chosen'}</span>
|
||||||
|
<span className="ml-auto flex gap-1">
|
||||||
|
{!lib.detected && (
|
||||||
|
<button
|
||||||
|
onClick={() => patch({ localLibraries: { ...overrides, [lib.platform]: null } })}
|
||||||
|
className="btn-glass rounded-full px-2.5 py-0.5 text-xs text-muted hover:text-text"
|
||||||
|
>
|
||||||
|
Find automatically
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
onClick={() => setPicking(lib.platform)}
|
||||||
|
className="btn-glass rounded-full px-2.5 py-0.5 text-xs text-muted hover:text-text"
|
||||||
|
>
|
||||||
|
Change…
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div title={lib.path ?? undefined} className="mt-0.5 truncate font-mono text-[11px] text-faint">
|
||||||
|
{lib.path ?? '—'}
|
||||||
|
</div>
|
||||||
|
{problem && <div className="mt-0.5 text-[11px] text-pink">{problem}</div>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="space-y-2">
|
||||||
|
<h3 className="text-[11px] uppercase tracking-wider text-faint">Audio folder</h3>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span title={d?.audio_root} dir="rtl"
|
||||||
|
className="min-w-0 flex-1 truncate rounded-md well px-2 py-1.5 text-left font-mono text-xs text-text">
|
||||||
|
{d?.audio_root ?? '…'}
|
||||||
|
</span>
|
||||||
|
{d && d.audio_root !== d.audio_root_default && (
|
||||||
|
<button onClick={() => patch({ localAudioRoot: null })}
|
||||||
|
className="shrink-0 btn-glass rounded-full px-2.5 py-1 text-xs text-muted hover:text-text">
|
||||||
|
Reset
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button onClick={() => setPicking('audio')}
|
||||||
|
className="shrink-0 btn-glass rounded-full px-2.5 py-1 text-xs text-muted hover:text-text">
|
||||||
|
Change…
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="text-[11px] text-faint">
|
||||||
|
Every push copies its tracks here, once each, however many sets or apps use them. A
|
||||||
|
file no push uses any more is deleted. Changing the folder copies everything again
|
||||||
|
on the next push.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="space-y-2">
|
||||||
|
<h3 className="text-[11px] uppercase tracking-wider text-faint">Level</h3>
|
||||||
|
<label className="flex cursor-pointer items-start gap-2.5">
|
||||||
|
<input type="checkbox" className="mt-0.5" checked={normalise}
|
||||||
|
onChange={(e) => patch({ localNormalise: e.target.checked })} />
|
||||||
|
<span>
|
||||||
|
<span className="block text-text">Normalise audio</span>
|
||||||
|
<span className="block text-xs text-faint">
|
||||||
|
Brings the copies to one level. Your own files are never changed.
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
{normalise && (
|
||||||
|
<div className="ml-6 space-y-1.5 text-xs">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<span className="text-muted">Level by</span>
|
||||||
|
<select
|
||||||
|
className="rounded-lg well px-2 py-1 text-xs text-text outline-none"
|
||||||
|
value={level.measure}
|
||||||
|
onChange={(e) => patch({ localLevel: { ...level, measure: e.target.value } })}
|
||||||
|
>
|
||||||
|
<option value="lufs">LUFS</option>
|
||||||
|
<option value="rms">RMS (loudest sections)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<span className="text-muted">Target</span>
|
||||||
|
<LevelInput value={level.target} unit={level.measure === 'lufs' ? 'LUFS' : 'dB'} min={-30} max={0}
|
||||||
|
onCommit={(v) => patch({ localLevel: { ...level, target: v } })} />
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<span className="text-muted" title="A raise stops here, so nothing clips">Peak ceiling</span>
|
||||||
|
<LevelInput value={level.ceiling} unit="dBTP" min={-12} max={0}
|
||||||
|
onCommit={(v) => patch({ localLevel: { ...level, ceiling: v } })} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
{error && <div className="text-xs text-pink">{error}</div>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -12,6 +12,9 @@ export function sizeLabel(size: number): string {
|
|||||||
export type LoopMode = 'beat' | 'manual'
|
export type LoopMode = 'beat' | 'manual'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
|
/** The deck's MIDI action prefix (`deck.A`): its controls carry
|
||||||
|
* `data-midi-action` for on-screen learning (lib/midi). */
|
||||||
|
midi?: string
|
||||||
mode: LoopMode
|
mode: LoopMode
|
||||||
onMode: (mode: LoopMode) => void
|
onMode: (mode: LoopMode) => void
|
||||||
hasGrid: boolean // beat loops and jumps are sized in beats; inert without a grid
|
hasGrid: boolean // beat loops and jumps are sized in beats; inert without a grid
|
||||||
@@ -67,6 +70,7 @@ const CLUSTER = 'well flex h-10 w-[8.5rem] shrink-0 items-center gap-0.5 rounded
|
|||||||
* Presentational: PrepStrip owns every piece of state and does the seeking.
|
* Presentational: PrepStrip owns every piece of state and does the seeking.
|
||||||
*/
|
*/
|
||||||
export function LoopControls({
|
export function LoopControls({
|
||||||
|
midi,
|
||||||
mode,
|
mode,
|
||||||
onMode,
|
onMode,
|
||||||
hasGrid,
|
hasGrid,
|
||||||
@@ -85,6 +89,7 @@ export function LoopControls({
|
|||||||
onToggleLoop,
|
onToggleLoop,
|
||||||
onMove,
|
onMove,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
|
const m = (op: string) => (midi ? `${midi}.${op}` : undefined)
|
||||||
const atMin = size <= LOOP_SIZES[0]
|
const atMin = size <= LOOP_SIZES[0]
|
||||||
const atMax = size >= LOOP_SIZES[LOOP_SIZES.length - 1]
|
const atMax = size >= LOOP_SIZES[LOOP_SIZES.length - 1]
|
||||||
const what = loopActive ? 'Move the loop' : `Jump ${sizeLabel(size)} beat${size === 1 ? '' : 's'}`
|
const what = loopActive ? 'Move the loop' : `Jump ${sizeLabel(size)} beat${size === 1 ? '' : 's'}`
|
||||||
@@ -107,6 +112,7 @@ export function LoopControls({
|
|||||||
<div role="group" aria-label="Loop size" className={`${CLUSTER} font-mono`}>
|
<div role="group" aria-label="Loop size" className={`${CLUSTER} font-mono`}>
|
||||||
<button
|
<button
|
||||||
onClick={onSmaller}
|
onClick={onSmaller}
|
||||||
|
data-midi-action={m('sizeDown')}
|
||||||
disabled={atMin}
|
disabled={atMin}
|
||||||
title="Halve the size (Cmd/Ctrl+↓)"
|
title="Halve the size (Cmd/Ctrl+↓)"
|
||||||
className={`${KEY} h-[34px] w-7 text-[15px] text-muted hover:bg-ink-800 hover:text-text`}
|
className={`${KEY} h-[34px] w-7 text-[15px] text-muted hover:bg-ink-800 hover:text-text`}
|
||||||
@@ -115,6 +121,7 @@ export function LoopControls({
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={onToggleSize}
|
onClick={onToggleSize}
|
||||||
|
data-midi-action={m('sizeLoop')}
|
||||||
disabled={!hasGrid || !ready}
|
disabled={!hasGrid || !ready}
|
||||||
title={hasGrid ? `${sizeLabel(size)}-beat loop — click to switch on or off` : 'No beatgrid'}
|
title={hasGrid ? `${sizeLabel(size)}-beat loop — click to switch on or off` : 'No beatgrid'}
|
||||||
className={`${KEY} h-[34px] min-w-0 flex-1 px-2 text-sm font-semibold ${
|
className={`${KEY} h-[34px] min-w-0 flex-1 px-2 text-sm font-semibold ${
|
||||||
@@ -125,6 +132,7 @@ export function LoopControls({
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={onBigger}
|
onClick={onBigger}
|
||||||
|
data-midi-action={m('sizeUp')}
|
||||||
disabled={atMax}
|
disabled={atMax}
|
||||||
title="Double the size (Cmd/Ctrl+↑)"
|
title="Double the size (Cmd/Ctrl+↑)"
|
||||||
className={`${KEY} h-[34px] w-7 text-[15px] text-muted hover:bg-ink-800 hover:text-text`}
|
className={`${KEY} h-[34px] w-7 text-[15px] text-muted hover:bg-ink-800 hover:text-text`}
|
||||||
@@ -136,6 +144,7 @@ export function LoopControls({
|
|||||||
<div role="group" aria-label="Manual loop" className={`${CLUSTER} text-xs font-semibold`}>
|
<div role="group" aria-label="Manual loop" className={`${CLUSTER} text-xs font-semibold`}>
|
||||||
<button
|
<button
|
||||||
onClick={onLoopIn}
|
onClick={onLoopIn}
|
||||||
|
data-midi-action={m('loopIn')}
|
||||||
disabled={!ready}
|
disabled={!ready}
|
||||||
aria-pressed={inArmed || manualSet}
|
aria-pressed={inArmed || manualSet}
|
||||||
title={inArmed ? 'Loop in is set — now press OUT (or IN again to move it)' : 'Loop in at the playhead'}
|
title={inArmed ? 'Loop in is set — now press OUT (or IN again to move it)' : 'Loop in at the playhead'}
|
||||||
@@ -145,6 +154,7 @@ export function LoopControls({
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={onLoopOut}
|
onClick={onLoopOut}
|
||||||
|
data-midi-action={m('loopOut')}
|
||||||
disabled={!ready || (!inArmed && !manualSet)}
|
disabled={!ready || (!inArmed && !manualSet)}
|
||||||
aria-pressed={manualSet && !inArmed}
|
aria-pressed={manualSet && !inArmed}
|
||||||
title={
|
title={
|
||||||
@@ -160,6 +170,7 @@ export function LoopControls({
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={onToggleLoop}
|
onClick={onToggleLoop}
|
||||||
|
data-midi-action={m('loopToggle')}
|
||||||
disabled={!canToggle}
|
disabled={!canToggle}
|
||||||
title={loopActive ? 'Switch the loop off' : 'Switch the loop on'}
|
title={loopActive ? 'Switch the loop off' : 'Switch the loop on'}
|
||||||
aria-pressed={loopActive}
|
aria-pressed={loopActive}
|
||||||
@@ -173,6 +184,7 @@ export function LoopControls({
|
|||||||
<div role="group" aria-label="Jump or move loop" className="glass-group flex h-10 items-center rounded-xl">
|
<div role="group" aria-label="Jump or move loop" className="glass-group flex h-10 items-center rounded-xl">
|
||||||
<button
|
<button
|
||||||
onClick={() => onMove(-1)}
|
onClick={() => onMove(-1)}
|
||||||
|
data-midi-action={m('jumpBack')}
|
||||||
disabled={!canMove}
|
disabled={!canMove}
|
||||||
title={`${what} back (←)`}
|
title={`${what} back (←)`}
|
||||||
className={`${HALF} rounded-l-xl`}
|
className={`${HALF} rounded-l-xl`}
|
||||||
@@ -181,6 +193,7 @@ export function LoopControls({
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => onMove(1)}
|
onClick={() => onMove(1)}
|
||||||
|
data-midi-action={m('jumpFwd')}
|
||||||
disabled={!canMove}
|
disabled={!canMove}
|
||||||
title={`${what} forward (→)`}
|
title={`${what} forward (→)`}
|
||||||
className={`${HALF} rounded-r-xl`}
|
className={`${HALF} rounded-r-xl`}
|
||||||
|
|||||||
@@ -34,7 +34,8 @@ interface Props {
|
|||||||
secPerView: number
|
secPerView: number
|
||||||
onZoomChange: (secPerView: number) => void
|
onZoomChange: (secPerView: number) => void
|
||||||
onSeek: (t: number) => void
|
onSeek: (t: number) => void
|
||||||
onScratchStart: () => void
|
/** Grab at `from` (s): later moves are relative to it. */
|
||||||
|
onScratchStart: (from: number) => void
|
||||||
onScratchMove: (t: number) => void
|
onScratchMove: (t: number) => void
|
||||||
onScratchEnd: (t: number) => void
|
onScratchEnd: (t: number) => void
|
||||||
/** A stem track: one lane per stem instead of the three-band mix view. */
|
/** A stem track: one lane per stem instead of the three-band mix view. */
|
||||||
@@ -236,11 +237,15 @@ export function MainWaveform({
|
|||||||
const rect = e.currentTarget.getBoundingClientRect()
|
const rect = e.currentTarget.getBoundingClientRect()
|
||||||
const dx = e.clientX - d.startX
|
const dx = e.clientX - d.startX
|
||||||
if (!d.moved && Math.abs(dx) > DRAG_THRESHOLD) {
|
if (!d.moved && Math.abs(dx) > DRAG_THRESHOLD) {
|
||||||
|
// Measure from HERE and NOW: a playing deck has moved on since the
|
||||||
|
// press, and the threshold's pixels would be a jump.
|
||||||
d.moved = true
|
d.moved = true
|
||||||
onScratchStart()
|
d.startX = e.clientX
|
||||||
|
d.startTime = currentTime
|
||||||
|
onScratchStart(currentTime)
|
||||||
}
|
}
|
||||||
if (d.moved) {
|
if (d.moved) {
|
||||||
const t = Math.min(duration, Math.max(0, d.startTime - (dx / rect.width) * secPerView))
|
const t = Math.min(duration, Math.max(0, d.startTime - ((e.clientX - d.startX) / rect.width) * secPerView))
|
||||||
d.lastT = t
|
d.lastT = t
|
||||||
onScratchMove(t)
|
onScratchMove(t)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { useEffect } from 'react'
|
||||||
|
import { createPortal } from 'react-dom'
|
||||||
|
import { actionDef } from '../lib/midi/actions'
|
||||||
|
import { armLearn, getMidiState, setOnScreenLearn, useMidiState } from '../lib/midi/store'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* On-screen MIDI learning (Settings ▸ MIDI Controllers… ▸ Learn on screen):
|
||||||
|
* every control that has a MIDI action (`data-midi-action`) is ringed;
|
||||||
|
* clicking one ARMS it instead of using it, and the next control moved on a
|
||||||
|
* controller is bound to it — into the Shift layer if the controller's Shift
|
||||||
|
* is held. Mapped controls show solid, the armed one glows, and Done or Esc
|
||||||
|
* leaves. Mounted once (main.tsx); renders nothing until switched on.
|
||||||
|
*/
|
||||||
|
export function MidiLearnOverlay() {
|
||||||
|
const onScreen = useMidiState((s) => s.onScreen)
|
||||||
|
const armed = useMidiState((s) => s.armed)
|
||||||
|
const mappings = useMidiState((s) => s.mappings)
|
||||||
|
const ports = useMidiState((s) => s.ports)
|
||||||
|
const learned = useMidiState((s) => s.learned)
|
||||||
|
|
||||||
|
// Clicks on a learnable control arm it; nothing else changes. Pointer and
|
||||||
|
// mouse events are stopped in the capture phase so the control never acts
|
||||||
|
// (knobs and faders start their drags on pointerdown).
|
||||||
|
useEffect(() => {
|
||||||
|
if (!onScreen) return
|
||||||
|
const target = (e: Event) => (e.target as Element | null)?.closest?.('[data-midi-action]') as HTMLElement | null
|
||||||
|
const stop = (e: Event) => {
|
||||||
|
const el = target(e)
|
||||||
|
if (!el) return
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
if (e.type !== 'pointerdown') return
|
||||||
|
const action = el.dataset.midiAction!
|
||||||
|
const a = getMidiState().armed
|
||||||
|
armLearn(a && 'layer' in a && a.action === action ? null : { action, layer: 'normal' })
|
||||||
|
}
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (e.key !== 'Escape') return
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
if (getMidiState().armed) armLearn(null)
|
||||||
|
else setOnScreenLearn(false)
|
||||||
|
}
|
||||||
|
const kinds = ['pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick', 'contextmenu']
|
||||||
|
for (const k of kinds) window.addEventListener(k, stop, true)
|
||||||
|
window.addEventListener('keydown', onKey, true)
|
||||||
|
document.body.classList.add('midi-learn')
|
||||||
|
return () => {
|
||||||
|
for (const k of kinds) window.removeEventListener(k, stop, true)
|
||||||
|
window.removeEventListener('keydown', onKey, true)
|
||||||
|
document.body.classList.remove('midi-learn')
|
||||||
|
}
|
||||||
|
}, [onScreen])
|
||||||
|
|
||||||
|
// Mark the controls: mapped (on a connected controller), armed, just learned.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!onScreen) return
|
||||||
|
const mapped = new Set<string>()
|
||||||
|
for (const p of ports) {
|
||||||
|
for (const b of Object.values(mappings[p]?.bindings ?? {})) {
|
||||||
|
if (b.normal) mapped.add(b.normal)
|
||||||
|
if (b.shift) mapped.add(b.shift)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const armedId = armed && 'layer' in armed ? armed.action : null
|
||||||
|
const flash = learned && performance.now() - learned.at < 1500 ? learned.action : null
|
||||||
|
for (const el of document.querySelectorAll<HTMLElement>('[data-midi-action]')) {
|
||||||
|
const id = el.dataset.midiAction!
|
||||||
|
el.toggleAttribute('data-midi-mapped', mapped.has(id))
|
||||||
|
el.toggleAttribute('data-midi-armed', id === armedId)
|
||||||
|
el.toggleAttribute('data-midi-learned', id === flash)
|
||||||
|
}
|
||||||
|
// The "just learned" flash fades on its own.
|
||||||
|
const fade = flash ? setTimeout(() => document.querySelector('[data-midi-learned]')?.removeAttribute('data-midi-learned'), 1500) : 0
|
||||||
|
return () => {
|
||||||
|
clearTimeout(fade)
|
||||||
|
for (const el of document.querySelectorAll('[data-midi-action]')) {
|
||||||
|
el.removeAttribute('data-midi-mapped')
|
||||||
|
el.removeAttribute('data-midi-armed')
|
||||||
|
el.removeAttribute('data-midi-learned')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [onScreen, armed, mappings, ports, learned])
|
||||||
|
|
||||||
|
if (!onScreen) return null
|
||||||
|
const armedLabel = armed && 'layer' in armed ? actionDef(armed.action)?.label : null
|
||||||
|
return createPortal(
|
||||||
|
<div className="pointer-events-none fixed inset-x-0 top-3 z-[80] flex justify-center">
|
||||||
|
<div className="pointer-events-auto flex items-center gap-3 glass-overlay rounded-full px-4 py-2 text-sm text-text">
|
||||||
|
<span className="h-2 w-2 animate-pulse rounded-full bg-accent" />
|
||||||
|
{ports.length === 0 ? (
|
||||||
|
<span>MIDI learn — plug in a controller</span>
|
||||||
|
) : armedLabel ? (
|
||||||
|
<span>
|
||||||
|
<span className="font-semibold">{armedLabel}</span>: move a control on your controller — an encoder a few clicks in
|
||||||
|
this action's direction (hold its Shift for the Shift layer)
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span>MIDI learn — click a control, then move it on your controller</span>
|
||||||
|
)}
|
||||||
|
<button onClick={() => setOnScreenLearn(false)} className="rounded-full btn-primary px-3 py-1 text-xs font-semibold">
|
||||||
|
Done
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,397 @@
|
|||||||
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { ACTION_GROUPS, ACTIONS, type ActionDef } from '../lib/midi/actions'
|
||||||
|
import { ENCODING_LABELS, ENCODINGS } from '../lib/midi/encoding'
|
||||||
|
import {
|
||||||
|
DEFAULT_JOG_SENSITIVITY,
|
||||||
|
DEFAULT_SCRUB_SPEED,
|
||||||
|
bindShift,
|
||||||
|
emptyMapping,
|
||||||
|
sanitizeMapping,
|
||||||
|
setBinding,
|
||||||
|
sourcesFor,
|
||||||
|
unbind,
|
||||||
|
type Layer,
|
||||||
|
type Mapping,
|
||||||
|
} from '../lib/midi/mapping'
|
||||||
|
import { describeSource, splitSource, type SourceKey } from '../lib/midi/messages'
|
||||||
|
import { armLearn, replaceMappings, setOnScreenLearn, updateMapping, useMidiState, type LearnTarget } from '../lib/midi/store'
|
||||||
|
import { askConfirm } from '../lib/confirm'
|
||||||
|
import { ContextMenu, type MenuItem } from './ContextMenu'
|
||||||
|
import { FileBrowser } from './FileBrowser'
|
||||||
|
import { FolderPicker } from './FolderPicker'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
|
const section = 'text-[11px] font-semibold uppercase tracking-wider text-faint'
|
||||||
|
const MAPPING_SUFFIX = '.konduktor-midi.json'
|
||||||
|
|
||||||
|
const which = (t: LearnTarget) => ('layer' in t ? t.layer : t.slot)
|
||||||
|
const sameTarget = (a: LearnTarget | null, b: LearnTarget) => a != null && a.action === b.action && which(a) === which(b)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings ▸ MIDI Controllers… (decided 2026-11-03): every controller is
|
||||||
|
* mapped by LEARNING — press Learn beside an action (or "Learn on screen" and
|
||||||
|
* click the control), then move the control. Each control has a normal and a
|
||||||
|
* free Shift binding; Shift itself is a learned control. Mappings are per
|
||||||
|
* controller, kept in userprefs, and shareable as files.
|
||||||
|
*/
|
||||||
|
export function MidiSettings({ onClose }: { onClose: () => void }) {
|
||||||
|
const available = useMidiState((s) => s.available)
|
||||||
|
const blocked = useMidiState((s) => s.blocked)
|
||||||
|
const ports = useMidiState((s) => s.ports)
|
||||||
|
const mappings = useMidiState((s) => s.mappings)
|
||||||
|
const armed = useMidiState((s) => s.armed)
|
||||||
|
const activity = useMidiState((s) => s.activity)
|
||||||
|
const learned = useMidiState((s) => s.learned)
|
||||||
|
const known = useMemo(() => [...new Set([...ports, ...Object.keys(mappings)])], [ports, mappings])
|
||||||
|
const [selected, setSelected] = useState<string | null>(null)
|
||||||
|
const port = selected && known.includes(selected) ? selected : (known[0] ?? null)
|
||||||
|
const mapping: Mapping = (port && mappings[port]) || emptyMapping()
|
||||||
|
const [filter, setFilter] = useState('')
|
||||||
|
const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)
|
||||||
|
const [exporting, setExporting] = useState(false)
|
||||||
|
const [importing, setImporting] = useState(false)
|
||||||
|
const [note, setNote] = useState<{ error: boolean; text: string } | null>(null)
|
||||||
|
|
||||||
|
// What was just learned shows under its own controller.
|
||||||
|
useEffect(() => {
|
||||||
|
if (learned) setSelected(learned.port)
|
||||||
|
}, [learned])
|
||||||
|
// Closing the dialog stops waiting for a control.
|
||||||
|
useEffect(() => () => armLearn(null), [])
|
||||||
|
|
||||||
|
const learn = (t: LearnTarget) => armLearn(sameTarget(armed, t) ? null : t)
|
||||||
|
const edit = (fn: (m: Mapping) => Mapping) => port && updateMapping(port, fn)
|
||||||
|
|
||||||
|
const bindingMenu = (e: React.MouseEvent, src: SourceKey, action: ActionDef, layer: Layer) => {
|
||||||
|
const b = mapping.bindings[src]
|
||||||
|
if (!b) return
|
||||||
|
const r = e.currentTarget.getBoundingClientRect()
|
||||||
|
const items: MenuItem[] = [{ heading: describeSource(src) }]
|
||||||
|
if (splitSource(src).dir) {
|
||||||
|
// An encoder turned for a button action: how it counts its clicks.
|
||||||
|
items.push(
|
||||||
|
{
|
||||||
|
label: 'Encoding',
|
||||||
|
submenu: ENCODINGS.filter((x) => x !== 'button' && x !== 'abs7' && x !== 'abs14').map((x) => ({
|
||||||
|
label: ENCODING_LABELS[x],
|
||||||
|
hint: x === b.encoding ? '✓' : undefined,
|
||||||
|
onClick: () => edit((m) => setBinding(m, src, { encoding: x })),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{ separator: true },
|
||||||
|
)
|
||||||
|
} else if (action.kind !== 'button' && action.kind !== 'hold') {
|
||||||
|
items.push(
|
||||||
|
{
|
||||||
|
label: 'Encoding',
|
||||||
|
submenu: ENCODINGS.filter((x) => x !== 'button').map((x) => ({
|
||||||
|
label: ENCODING_LABELS[x],
|
||||||
|
hint: x === b.encoding ? '✓' : undefined,
|
||||||
|
onClick: () => edit((m) => setBinding(m, src, { encoding: x })),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{ label: 'Reversed', checked: !!b.invert, onToggle: () => edit((m) => setBinding(m, src, { invert: !b.invert || undefined })) },
|
||||||
|
{ separator: true },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
items.push(
|
||||||
|
{ label: 'Learn again', onClick: () => learn({ action: action.id, layer }) },
|
||||||
|
{ label: 'Clear', danger: true, onClick: () => edit((m) => unbind(m, action.id, layer)) },
|
||||||
|
)
|
||||||
|
setMenu({ x: r.left, y: r.bottom + 4, items })
|
||||||
|
}
|
||||||
|
|
||||||
|
const cell = (action: ActionDef, layer: Layer) => {
|
||||||
|
const t: LearnTarget = { action: action.id, layer }
|
||||||
|
if (sameTarget(armed, t)) {
|
||||||
|
return (
|
||||||
|
<button onClick={() => armLearn(null)} className="w-full animate-pulse rounded-md bg-accent/25 px-2 py-1 text-left text-[11px] text-text ring-1 ring-accent">
|
||||||
|
Move a control…
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const sources = sourcesFor(mapping, action.id, layer)
|
||||||
|
if (sources.length === 0) {
|
||||||
|
return (
|
||||||
|
<button onClick={() => learn(t)} className="w-full rounded-md px-2 py-1 text-left text-[11px] text-faint hover:bg-ink-800 hover:text-text">
|
||||||
|
Learn
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap gap-1">
|
||||||
|
{sources.map((src) => {
|
||||||
|
const enc = mapping.bindings[src]?.encoding
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={src}
|
||||||
|
onClick={(e) => bindingMenu(e, src, action, layer)}
|
||||||
|
title={enc && enc !== 'button' ? ENCODING_LABELS[enc] : undefined}
|
||||||
|
className="rounded-md bg-ink-800 px-2 py-1 font-mono text-[10.5px] text-text hover:bg-ink-700"
|
||||||
|
>
|
||||||
|
{describeSource(src)}
|
||||||
|
{mapping.bindings[src]?.invert ? ' ⇄' : ''}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const needle = filter.trim().toLowerCase()
|
||||||
|
const shown = ACTIONS.filter((a) => !needle || a.label.toLowerCase().includes(needle) || a.group.toLowerCase().includes(needle))
|
||||||
|
|
||||||
|
const forget = async () => {
|
||||||
|
if (!port) return
|
||||||
|
const ok = await askConfirm({
|
||||||
|
title: `Forget ${port}'s mapping?`,
|
||||||
|
body: 'Every learned control on this controller is cleared.',
|
||||||
|
confirmLabel: 'Forget',
|
||||||
|
})
|
||||||
|
if (!ok) return
|
||||||
|
const next = { ...mappings }
|
||||||
|
delete next[port]
|
||||||
|
replaceMappings(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
const doExport = async (dir: string) => {
|
||||||
|
if (!port) return
|
||||||
|
try {
|
||||||
|
const { path } = await api.midiExport(dir, port, mapping)
|
||||||
|
setNote({ error: false, text: `Saved ${path}` })
|
||||||
|
} catch (e) {
|
||||||
|
setNote({ error: true, text: (e as Error).message })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const doImport = async (path: string) => {
|
||||||
|
setImporting(false)
|
||||||
|
if (!port) return
|
||||||
|
try {
|
||||||
|
const m = sanitizeMapping((await api.midiImport(path)).mapping)
|
||||||
|
if (!m) throw new Error('That file is not a MIDI mapping')
|
||||||
|
if (Object.keys(mapping.bindings).length > 0 || mapping.shifts.some(Boolean)) {
|
||||||
|
const ok = await askConfirm({
|
||||||
|
title: `Replace ${port}'s mapping?`,
|
||||||
|
body: 'The imported mapping replaces every control learned on this controller.',
|
||||||
|
confirmLabel: 'Replace',
|
||||||
|
})
|
||||||
|
if (!ok) return
|
||||||
|
}
|
||||||
|
updateMapping(port, () => m)
|
||||||
|
setNote({ error: false, text: `Imported ${Object.keys(m.bindings).length} controls` })
|
||||||
|
} catch (e) {
|
||||||
|
setNote({ error: true, text: (e as Error).message })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal onDismiss={armed ? () => armLearn(null) : onClose}>
|
||||||
|
<div className="flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden glass-overlay">
|
||||||
|
<div className="flex items-center justify-between border-b border-line px-5 py-3">
|
||||||
|
<h2 className="text-sm font-semibold text-text">MIDI Controllers</h2>
|
||||||
|
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!available ? (
|
||||||
|
<div className="px-5 py-6 text-sm text-muted">
|
||||||
|
MIDI is not available here. The desktop app reads controllers itself; in a browser, use Chrome.
|
||||||
|
</div>
|
||||||
|
) : blocked && known.length === 0 ? (
|
||||||
|
<div className="space-y-1 px-5 py-6 text-sm text-muted">
|
||||||
|
<p>The browser refused access to MIDI devices.</p>
|
||||||
|
<p className="text-xs text-faint">
|
||||||
|
Allow it from the site settings (the icon left of the address: MIDI devices → Allow). Konduktor asks again on
|
||||||
|
its own. ({blocked})
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : known.length === 0 ? (
|
||||||
|
<div className="px-5 py-6 text-sm text-muted">Plug in a MIDI controller — it shows up here within a couple of seconds.</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="space-y-3 border-b border-line px-5 py-3 text-sm">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<select
|
||||||
|
value={port ?? ''}
|
||||||
|
onChange={(e) => setSelected(e.target.value)}
|
||||||
|
className="min-w-0 max-w-[16rem] rounded-lg well px-2 py-1 text-sm text-text outline-none"
|
||||||
|
>
|
||||||
|
{known.map((p) => (
|
||||||
|
<option key={p} value={p}>
|
||||||
|
{p}
|
||||||
|
{ports.includes(p) ? '' : ' (not connected)'}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<span className="min-w-0 flex-1 truncate font-mono text-[11px] text-faint">
|
||||||
|
{activity
|
||||||
|
? `${activity.port}: ${describeSource(activity.source)} → ${activity.value}`
|
||||||
|
: 'Move a control to see it here'}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setOnScreenLearn(true)
|
||||||
|
onClose()
|
||||||
|
}}
|
||||||
|
className="btn-glass rounded-full px-3 py-1 text-xs text-text"
|
||||||
|
title="Click a control on screen, then move it on your controller"
|
||||||
|
>
|
||||||
|
Learn on screen
|
||||||
|
</button>
|
||||||
|
<button onClick={() => setImporting(true)} className="btn-glass rounded-full px-3 py-1 text-xs text-muted hover:text-text">
|
||||||
|
Import…
|
||||||
|
</button>
|
||||||
|
<button onClick={() => setExporting(true)} className="btn-glass rounded-full px-3 py-1 text-xs text-muted hover:text-text">
|
||||||
|
Export…
|
||||||
|
</button>
|
||||||
|
{mappings[port ?? ''] && (
|
||||||
|
<button onClick={() => void forget()} className="rounded-full px-2 py-1 text-xs text-faint hover:text-pink">
|
||||||
|
Forget
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{note && <div className={`text-xs ${note.error ? 'text-pink' : 'text-faint'}`}>{note.text}</div>}
|
||||||
|
<div className="grid grid-cols-[auto_1fr] items-center gap-x-4 gap-y-2">
|
||||||
|
{([0, 1] as const).map((slot) => {
|
||||||
|
const src = mapping.shifts[slot]
|
||||||
|
const t: LearnTarget = { action: 'shift', slot }
|
||||||
|
return (
|
||||||
|
<div key={slot} className="contents">
|
||||||
|
<span className="text-text">{slot === 0 ? 'Shift button' : 'Second Shift'}</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{sameTarget(armed, t) ? (
|
||||||
|
<button onClick={() => armLearn(null)} className="animate-pulse rounded-md bg-accent/25 px-2 py-1 text-[11px] text-text ring-1 ring-accent">
|
||||||
|
Press the controller's Shift…
|
||||||
|
</button>
|
||||||
|
) : src ? (
|
||||||
|
<>
|
||||||
|
<span className="rounded-md bg-ink-800 px-2 py-1 font-mono text-[10.5px] text-text">{describeSource(src)}</span>
|
||||||
|
<button onClick={() => learn(t)} className="text-[11px] text-faint hover:text-text">
|
||||||
|
Learn again
|
||||||
|
</button>
|
||||||
|
<button onClick={() => edit((m) => bindShift(m, null, slot))} className="text-[11px] text-faint hover:text-pink">
|
||||||
|
Clear
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<button onClick={() => learn(t)} className="rounded-md px-2 py-1 text-[11px] text-faint hover:bg-ink-800 hover:text-text">
|
||||||
|
Learn
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<span className="text-[11px] text-faint">
|
||||||
|
{slot === 0
|
||||||
|
? 'Hold it while moving a control to learn its Shift action.'
|
||||||
|
: 'Optional — many controllers have one per deck. Either one gives the Shift layer.'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
<span className="text-text">Jog sensitivity</span>
|
||||||
|
<Slider
|
||||||
|
value={mapping.jogSensitivity}
|
||||||
|
min={0.05}
|
||||||
|
max={4}
|
||||||
|
step={0.05}
|
||||||
|
reset={DEFAULT_JOG_SENSITIVITY}
|
||||||
|
format={(v) => `×${v.toFixed(2)}`}
|
||||||
|
onChange={(v) => edit((m) => ({ ...m, jogSensitivity: v }))}
|
||||||
|
/>
|
||||||
|
<span className="text-text">Fast scrub</span>
|
||||||
|
<Slider
|
||||||
|
value={mapping.scrubSpeed}
|
||||||
|
min={2}
|
||||||
|
max={32}
|
||||||
|
step={1}
|
||||||
|
reset={DEFAULT_SCRUB_SPEED}
|
||||||
|
format={(v) => `×${v} a jog`}
|
||||||
|
onChange={(v) => edit((m) => ({ ...m, scrubSpeed: v }))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 border-b border-line px-5 py-2">
|
||||||
|
<input
|
||||||
|
value={filter}
|
||||||
|
onChange={(e) => setFilter(e.target.value)}
|
||||||
|
placeholder="Find an action…"
|
||||||
|
className="w-56 rounded-md well px-2 py-1 text-xs text-text outline-none focus:ring-1 focus:ring-accent"
|
||||||
|
/>
|
||||||
|
<span className="min-w-0 flex-1 truncate text-[11px] text-faint" title="A button action can be an encoder turned one way: learn it by turning a few clicks in that direction (↻ / ↺).">
|
||||||
|
Buttons: press it, or turn an encoder a few clicks in this action's direction.
|
||||||
|
</span>
|
||||||
|
<span className="w-36 text-[11px] font-semibold uppercase tracking-wider text-faint">Control</span>
|
||||||
|
<span className="w-36 text-[11px] font-semibold uppercase tracking-wider text-faint">With Shift</span>
|
||||||
|
</div>
|
||||||
|
<div className="min-h-0 flex-1 overflow-y-auto px-5 pb-4">
|
||||||
|
{ACTION_GROUPS.map((g) => {
|
||||||
|
const rows = shown.filter((a) => a.group === g)
|
||||||
|
if (rows.length === 0) return null
|
||||||
|
return (
|
||||||
|
<section key={g} className="pt-3">
|
||||||
|
<h3 className={`${section} pb-1`}>
|
||||||
|
{g}
|
||||||
|
{g === 'Deck B' || g === 'Mixer' ? <span className="ml-2 normal-case tracking-normal">— performance mode only</span> : null}
|
||||||
|
</h3>
|
||||||
|
{rows.map((a) => (
|
||||||
|
<div key={a.id} className="flex items-center gap-3 border-b border-line/40 py-1">
|
||||||
|
<span className="min-w-0 flex-1 truncate text-sm text-text">{a.label}</span>
|
||||||
|
<div className="w-36 shrink-0">{cell(a, 'normal')}</div>
|
||||||
|
<div className="w-36 shrink-0">{cell(a, 'shift')}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{menu && <ContextMenu {...menu} onClose={() => setMenu(null)} />}
|
||||||
|
{exporting && <FolderPicker value="" onChange={(dir) => void doExport(dir)} onClose={() => setExporting(false)} />}
|
||||||
|
{importing && <ImportPicker onPick={(p) => void doImport(p)} onClose={() => setImporting(false)} />}
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Slider({ value, min, max, step, reset, format, onChange }: {
|
||||||
|
value: number; min: number; max: number; step: number; reset: number; format: (v: number) => string; onChange: (v: number) => void
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min={min}
|
||||||
|
max={max}
|
||||||
|
step={step}
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => onChange(Number(e.target.value))}
|
||||||
|
onDoubleClick={() => onChange(reset)}
|
||||||
|
className="w-48"
|
||||||
|
/>
|
||||||
|
<span className="font-mono text-[11px] text-muted">{format(value)}</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pick a `.konduktor-midi.json` file. */
|
||||||
|
function ImportPicker({ onPick, onClose }: { onPick: (path: string) => void; onClose: () => void }) {
|
||||||
|
const [dir, setDir] = useState<string | undefined>(undefined)
|
||||||
|
return (
|
||||||
|
<Modal onDismiss={onClose} layer="nested" padding="p-4">
|
||||||
|
<div className="flex h-[70vh] w-full max-w-2xl flex-col overflow-hidden glass-overlay">
|
||||||
|
<div className="border-b border-line px-5 py-3">
|
||||||
|
<h2 className="text-sm font-semibold text-text">Import a MIDI mapping</h2>
|
||||||
|
</div>
|
||||||
|
<FileBrowser mode="file" suffix={MAPPING_SUFFIX} path={dir} onNavigate={setDir} onPickFile={onPick} />
|
||||||
|
<div className="flex justify-end border-t border-line px-5 py-3">
|
||||||
|
<button onClick={onClose} className="btn-glass rounded-full px-3 py-1.5 text-sm text-muted hover:text-text">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import { createPortal } from 'react-dom'
|
||||||
|
import { useEffect, useRef, useState, type AriaRole, type ReactNode } from 'react'
|
||||||
|
|
||||||
|
// Open modals by opening order (taken at first render, so a dialog opened
|
||||||
|
// from another always ranks above it). Esc is answered by the top one only.
|
||||||
|
const open = new Set<number>()
|
||||||
|
let opened = 0
|
||||||
|
|
||||||
|
const menuOpen = () => document.querySelector('[role="menu"]') != null
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
/** What Esc and a click on the backdrop do: the dialog's Cancel / Close.
|
||||||
|
* `null` while that is not available (a run in progress), so neither
|
||||||
|
* can close the dialog when its own Cancel could not. */
|
||||||
|
onDismiss: (() => void) | null
|
||||||
|
/** `false`: Esc only. For a dialog whose dismissal decides something a
|
||||||
|
* stray click should not (RelocateDialog). */
|
||||||
|
backdropDismiss?: boolean
|
||||||
|
/** `nested` for a dialog opened from a dialog or above every other one. */
|
||||||
|
layer?: 'dialog' | 'nested'
|
||||||
|
/** The backdrop's padding (default `p-6`). */
|
||||||
|
padding?: string
|
||||||
|
role?: AriaRole
|
||||||
|
'aria-label'?: string
|
||||||
|
'aria-labelledby'?: string
|
||||||
|
children: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The ONE modal container: portal, dimmed backdrop, Esc and outside click.
|
||||||
|
*
|
||||||
|
* An outside click closes only when the press AND the release are both on
|
||||||
|
* the backdrop. A `click` alone fires on the nearest common ancestor, so a
|
||||||
|
* text selection started inside the dialog and released outside it used to
|
||||||
|
* land on the backdrop and close the dialog. */
|
||||||
|
export function Modal({
|
||||||
|
onDismiss,
|
||||||
|
backdropDismiss = true,
|
||||||
|
layer = 'dialog',
|
||||||
|
padding = 'p-6',
|
||||||
|
role,
|
||||||
|
children,
|
||||||
|
...aria
|
||||||
|
}: Props) {
|
||||||
|
const [id] = useState(() => ++opened)
|
||||||
|
const dismissRef = useRef(onDismiss)
|
||||||
|
dismissRef.current = onDismiss
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
open.add(id)
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (e.key !== 'Escape' || e.defaultPrevented) return
|
||||||
|
if (id !== Math.max(...open)) return
|
||||||
|
// A menu over the dialog closes itself on Esc; the dialog stays.
|
||||||
|
if (menuOpen()) return
|
||||||
|
const dismiss = dismissRef.current
|
||||||
|
if (!dismiss) return
|
||||||
|
e.preventDefault()
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
window.addEventListener('keydown', onKey)
|
||||||
|
return () => {
|
||||||
|
open.delete(id)
|
||||||
|
window.removeEventListener('keydown', onKey)
|
||||||
|
}
|
||||||
|
}, [id])
|
||||||
|
|
||||||
|
const pressed = useRef(false)
|
||||||
|
const released = useRef(false)
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div
|
||||||
|
aria-modal="true"
|
||||||
|
role={role}
|
||||||
|
{...aria}
|
||||||
|
className={`fixed inset-0 ${layer === 'nested' ? 'z-[60]' : 'z-50'} flex items-center justify-center bg-black/40 backdrop-blur-[3px] ${padding}`}
|
||||||
|
// React bubbles events through portals, so a nested dialog's or menu's
|
||||||
|
// pointer events reach here too; `target === currentTarget` keeps only
|
||||||
|
// the ones on THIS backdrop.
|
||||||
|
onPointerDown={(e) => {
|
||||||
|
// A press that closes an open menu closes only the menu.
|
||||||
|
pressed.current = e.target === e.currentTarget && e.button === 0 && !menuOpen()
|
||||||
|
released.current = false
|
||||||
|
}}
|
||||||
|
onPointerUp={(e) => {
|
||||||
|
released.current = e.target === e.currentTarget
|
||||||
|
}}
|
||||||
|
onClick={(e) => {
|
||||||
|
const outside = pressed.current && released.current && e.target === e.currentTarget
|
||||||
|
pressed.current = released.current = false
|
||||||
|
if (outside && backdropDismiss) dismissRef.current?.()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,30 +1,38 @@
|
|||||||
/**
|
/**
|
||||||
* The deck's two-way mode switch: two small stacked tabs in a well, the chosen
|
* The deck's two-way mode switch: two small stacked tabs in a well, the chosen
|
||||||
* one lit. BEAT / MAN (loops) and HOT / MEM (the cue bank) are both this.
|
* one lit. BEAT / MAN (loops) and HOT / MEM (the cue bank) are both this.
|
||||||
|
* With exactly two options a click anywhere on it flips to the other one;
|
||||||
|
* with more, each tab selects itself.
|
||||||
*/
|
*/
|
||||||
export function ModeSwitch<T extends string>({
|
export function ModeSwitch<T extends string>({
|
||||||
label,
|
label,
|
||||||
value,
|
value,
|
||||||
options,
|
options,
|
||||||
|
disabled = false,
|
||||||
onChange,
|
onChange,
|
||||||
}: {
|
}: {
|
||||||
/** Names the group for assistive tech ("Loop mode", "Cue bank"). */
|
/** Names the group for assistive tech ("Loop mode", "Cue bank"). */
|
||||||
label: string
|
label: string
|
||||||
value: T
|
value: T
|
||||||
options: { value: T; text: string; title: string }[]
|
options: { value: T; text: string; title: string }[]
|
||||||
|
disabled?: boolean
|
||||||
onChange: (value: T) => void
|
onChange: (value: T) => void
|
||||||
}) {
|
}) {
|
||||||
|
const other =
|
||||||
|
options.length === 2 && !disabled ? options.find((o) => o.value !== value) : undefined
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
role="group"
|
role="group"
|
||||||
aria-label={label}
|
aria-label={label}
|
||||||
className="well flex h-10 shrink-0 flex-col justify-center gap-0.5 rounded-[10px] p-0.5"
|
onClick={other ? () => onChange(other.value) : undefined}
|
||||||
|
className={`well ${other ? 'cursor-pointer ' : ''}${disabled ? 'opacity-40 ' : ''}flex h-10 shrink-0 flex-col justify-center gap-0.5 rounded-[10px] p-0.5`}
|
||||||
>
|
>
|
||||||
{options.map((o) => (
|
{options.map((o) => (
|
||||||
<button
|
<button
|
||||||
key={o.value}
|
key={o.value}
|
||||||
onClick={() => onChange(o.value)}
|
onClick={other ? undefined : () => onChange(o.value)}
|
||||||
title={o.title}
|
title={o.title}
|
||||||
|
disabled={disabled}
|
||||||
aria-pressed={value === o.value}
|
aria-pressed={value === o.value}
|
||||||
className={`h-[17px] rounded-[7px] px-[7px] text-[9px] font-bold tracking-[0.08em] transition-colors ${
|
className={`h-[17px] rounded-[7px] px-[7px] text-[9px] font-bold tracking-[0.08em] transition-colors ${
|
||||||
value === o.value ? 'btn-primary' : 'text-faint hover:text-text'
|
value === o.value ? 'btn-primary' : 'text-faint hover:text-text'
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useMemo, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import { keepPreviousData, useQuery } from '@tanstack/react-query'
|
import { keepPreviousData, useQuery } from '@tanstack/react-query'
|
||||||
import { api, type NormalizeOptions, type NormalizePreview, type NormalizeRow } from '../api'
|
import { api, type NormalizeOptions, type NormalizePreview, type NormalizeRow } from '../api'
|
||||||
import { LevelInput, useAppSetting } from './AppSettings'
|
import { LevelInput, useAppSetting } from './AppSettings'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
ids: string[]
|
ids: string[]
|
||||||
@@ -58,12 +58,6 @@ export function NormalizeDialog({ ids, onRun, onClose, onError }: Props) {
|
|||||||
const p: NormalizePreview | undefined = preview.data
|
const p: NormalizePreview | undefined = preview.data
|
||||||
const count = p?.tracks_to_process ?? 0
|
const count = p?.tracks_to_process ?? 0
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && onClose()
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [busy, onClose])
|
|
||||||
|
|
||||||
const summary = useMemo(() => {
|
const summary = useMemo(() => {
|
||||||
if (!p) return []
|
if (!p) return []
|
||||||
const rows = p.rows
|
const rows = p.rows
|
||||||
@@ -105,13 +99,9 @@ export function NormalizeDialog({ ids, onRun, onClose, onError }: Props) {
|
|||||||
|
|
||||||
const measureUnit = opts?.measure === 'rms' ? 'dB' : 'LUFS'
|
const measureUnit = opts?.measure === 'rms' ? 'dB' : 'LUFS'
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={busy ? null : onClose}>
|
||||||
aria-modal="true"
|
<div className="flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden glass-overlay">
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={() => !busy && onClose()}
|
|
||||||
>
|
|
||||||
<div className="flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Normalize</div>
|
<div className="text-[15px] font-semibold tracking-tight">Normalize</div>
|
||||||
<div className="text-xs text-muted">
|
<div className="text-xs text-muted">
|
||||||
@@ -198,7 +188,6 @@ export function NormalizeDialog({ ids, onRun, onClose, onError }: Props) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type RemapPreview } from '../api'
|
import { api, type RemapPreview } from '../api'
|
||||||
import type { ToastMsg } from './Toast'
|
import type { ToastMsg } from './Toast'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
import { invalidateTrackLists } from '../lib/trackQueries'
|
import { invalidateTrackLists } from '../lib/trackQueries'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
@@ -107,14 +107,10 @@ export function PathMappingDialog({ onClose, onNotify, onError }: Props) {
|
|||||||
const collides = (preview?.collisions ?? 0) > 0
|
const collides = (preview?.collisions ?? 0) > 0
|
||||||
const canCommit = !!from.trim() && !!to.trim() && !collides
|
const canCommit = !!from.trim() && !!to.trim() && !collides
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay"
|
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Path Remapping</div>
|
<div className="text-[15px] font-semibold tracking-tight">Path Remapping</div>
|
||||||
@@ -264,8 +260,7 @@ export function PathMappingDialog({ onClose, onNotify, onError }: Props) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,231 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { setMixer } from '../lib/audio/mixerState'
|
||||||
|
import { usePrefsWriter } from '../lib/prefs'
|
||||||
|
import { APP_SETTING_DEFAULTS, Check, Choice, useAppSetting } from './AppSettings'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
import { Fader } from './mixer/Controls'
|
||||||
|
import { CrossfaderCurveGraph } from './mixer/CrossfaderCurve'
|
||||||
|
|
||||||
|
/** How far the filter sweeps (`mixerMath.FILTER_RANGES`). */
|
||||||
|
const RANGES: [string, string][] = [
|
||||||
|
['full', 'Full - 20 Hz / 20 kHz'],
|
||||||
|
['musical', 'Musical - 150 Hz / 8 kHz'],
|
||||||
|
['gentle', 'Gentle - 500 Hz / 2 kHz'],
|
||||||
|
]
|
||||||
|
type Range = 'full' | 'musical' | 'gentle'
|
||||||
|
|
||||||
|
/** Resonance amounts offered (0..1 of the effect's maximum). */
|
||||||
|
const LEVELS: [string, string][] = [
|
||||||
|
['0', 'None'],
|
||||||
|
['0.3', 'Gentle'],
|
||||||
|
['0.6', 'Medium'],
|
||||||
|
['1', 'Strong'],
|
||||||
|
]
|
||||||
|
|
||||||
|
const section = 'text-[11px] font-semibold uppercase tracking-wider text-faint'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings ▸ Performance mode… (its own panel, decided 2026-11-03): the decks,
|
||||||
|
* the mixer and the Filter FX. Values live in the app
|
||||||
|
* settings (userprefs.json, `APP_SETTING_DEFAULTS`); PrepStrip copies the
|
||||||
|
* mixer's into `mixerState`.
|
||||||
|
*/
|
||||||
|
export function PerformanceSettings({ onClose }: { onClose: () => void }) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
const writePrefs = usePrefsWriter()
|
||||||
|
const perfStems = useAppSetting('perfStems')
|
||||||
|
const keylockDefault = useAppSetting('keylockDefault')
|
||||||
|
const autoFocusDeck = useAppSetting('autoFocusDeck')
|
||||||
|
const useAutoGain = useAppSetting('useAutoGain')
|
||||||
|
const eqKill = useAppSetting('eqKill')
|
||||||
|
const sharpnessSetting = useAppSetting('crossfaderSharpness')
|
||||||
|
const fxFilterRange = useAppSetting('fxFilterRange')
|
||||||
|
const fxEffectRange = useAppSetting('fxEffectRange')
|
||||||
|
const fxFilterResonance = useAppSetting('fxFilterResonance')
|
||||||
|
const fxReverbSize = useAppSetting('fxReverbSize')
|
||||||
|
const fxDelayBeats = useAppSetting('fxDelayBeats')
|
||||||
|
const fxCrusherDrive = useAppSetting('fxCrusherDrive')
|
||||||
|
const fxFlangerBeats = useAppSetting('fxFlangerBeats')
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
|
// The curve moves with the slider at once — mixer included, so it can be
|
||||||
|
// heard while dragging — and is saved through the debounced prefs writer.
|
||||||
|
const [sharpness, setSharpness] = useState(sharpnessSetting)
|
||||||
|
useEffect(() => setSharpness(sharpnessSetting), [sharpnessSetting])
|
||||||
|
const changeSharpness = (v: number) => {
|
||||||
|
const s = Math.round(v * 100) / 100
|
||||||
|
setSharpness(s)
|
||||||
|
setMixer({ sharpness: s })
|
||||||
|
writePrefs({ crossfaderSharpness: s })
|
||||||
|
}
|
||||||
|
|
||||||
|
const set = async (patch: Partial<typeof APP_SETTING_DEFAULTS>) => {
|
||||||
|
setError(null)
|
||||||
|
try {
|
||||||
|
qc.setQueryData(['prefs'], await api.patchPrefs(patch))
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const curveName =
|
||||||
|
sharpness === 0 ? 'Smooth' : sharpness === 1 ? 'Sharp' : sharpness < 0.52 ? 'Blend' : 'Cut'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal onDismiss={onClose}>
|
||||||
|
<div className="flex w-full max-w-md flex-col overflow-hidden glass-overlay">
|
||||||
|
<div className="flex items-center justify-between border-b border-line px-5 py-3">
|
||||||
|
<h2 className="text-sm font-semibold text-text">Performance mode</h2>
|
||||||
|
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="max-h-[70vh] space-y-4 overflow-y-auto px-5 py-4 text-sm">
|
||||||
|
<section className="space-y-2">
|
||||||
|
<h3 className={section}>Decks</h3>
|
||||||
|
<Check
|
||||||
|
checked={perfStems}
|
||||||
|
onChange={(v) => void set({ perfStems: v })}
|
||||||
|
title="Load stem tracks as stems"
|
||||||
|
text="Off plays the mix: lighter on older computers."
|
||||||
|
/>
|
||||||
|
<Check
|
||||||
|
checked={keylockDefault}
|
||||||
|
onChange={(v) => void set({ keylockDefault: v })}
|
||||||
|
title="Keylock on by default"
|
||||||
|
/>
|
||||||
|
<Check
|
||||||
|
checked={autoFocusDeck}
|
||||||
|
onChange={(v) => void set({ autoFocusDeck: v })}
|
||||||
|
title="Click a deck to focus it"
|
||||||
|
text="Off: only its A/B badge does."
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
<section className="space-y-2">
|
||||||
|
<h3 className={section}>Mixer</h3>
|
||||||
|
<Check
|
||||||
|
checked={useAutoGain}
|
||||||
|
onChange={(v) => void set({ useAutoGain: v })}
|
||||||
|
title="Use auto gain"
|
||||||
|
text="Off: every channel starts at 0 dB."
|
||||||
|
/>
|
||||||
|
<Choice
|
||||||
|
title="EQ full left"
|
||||||
|
value={eqKill ? 'kill' : 'cut'}
|
||||||
|
options={[
|
||||||
|
['cut', 'Cut to −26 dB'],
|
||||||
|
['kill', 'Kill (silence)'],
|
||||||
|
]}
|
||||||
|
onChange={(v) => void set({ eqKill: v === 'kill' })}
|
||||||
|
/>
|
||||||
|
<div className="space-y-1.5 pt-1">
|
||||||
|
<div className="flex items-baseline justify-between">
|
||||||
|
<span className="text-sm text-text">Crossfader curve</span>
|
||||||
|
<span className="font-mono text-xs text-muted">
|
||||||
|
{curveName} · {Math.round(sharpness * 100)}%
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<CrossfaderCurveGraph sharpness={sharpness} />
|
||||||
|
<div className="min-w-0 flex-1 space-y-1">
|
||||||
|
<Fader
|
||||||
|
orientation="horizontal"
|
||||||
|
value={sharpness}
|
||||||
|
min={0}
|
||||||
|
max={1}
|
||||||
|
defaultValue={APP_SETTING_DEFAULTS.crossfaderSharpness}
|
||||||
|
onChange={changeSharpness}
|
||||||
|
label="Crossfader curve sharpness"
|
||||||
|
describe={(v) =>
|
||||||
|
`${Math.round(v * 100)}% sharp — double-click to reset to ${Math.round(APP_SETTING_DEFAULTS.crossfaderSharpness * 100)}%`
|
||||||
|
}
|
||||||
|
className="w-full"
|
||||||
|
/>
|
||||||
|
<div className="flex justify-between text-[10px] uppercase tracking-wider text-faint">
|
||||||
|
<span>Smooth</span>
|
||||||
|
<span>Sharp</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section className="space-y-2">
|
||||||
|
<h3 className={section}>Filter FX</h3>
|
||||||
|
<span className="block text-xs text-faint">Effects grow as the filter opens.</span>
|
||||||
|
<Choice
|
||||||
|
title="Filter range (Filter alone)"
|
||||||
|
value={fxFilterRange}
|
||||||
|
options={RANGES}
|
||||||
|
onChange={(v) => void set({ fxFilterRange: v as Range })}
|
||||||
|
/>
|
||||||
|
<Choice
|
||||||
|
title="Filter range (with an effect)"
|
||||||
|
value={fxEffectRange}
|
||||||
|
options={RANGES}
|
||||||
|
onChange={(v) => void set({ fxEffectRange: v as Range })}
|
||||||
|
/>
|
||||||
|
<Choice
|
||||||
|
title="Filter resonance"
|
||||||
|
value={String(fxFilterResonance)}
|
||||||
|
options={LEVELS}
|
||||||
|
onChange={(v) => void set({ fxFilterResonance: Number(v) })}
|
||||||
|
/>
|
||||||
|
<Choice
|
||||||
|
title="Reverb size (shortest)"
|
||||||
|
value={String(fxReverbSize)}
|
||||||
|
options={[
|
||||||
|
['1', 'Small (1 → 3 s)'],
|
||||||
|
['2', 'Medium (2 → 6 s)'],
|
||||||
|
['3', 'Large (3 → 9 s)'],
|
||||||
|
['4', 'Huge (4 → 12 s)'],
|
||||||
|
]}
|
||||||
|
onChange={(v) => void set({ fxReverbSize: Number(v) })}
|
||||||
|
/>
|
||||||
|
<Choice
|
||||||
|
title="Delay length (shortest)"
|
||||||
|
value={String(fxDelayBeats)}
|
||||||
|
options={[
|
||||||
|
['0.125', '1/8 beat'],
|
||||||
|
['0.25', '1/4 beat'],
|
||||||
|
['0.5', '1/2 beat'],
|
||||||
|
['0.75', '3/4 beat'],
|
||||||
|
['1', '1 beat'],
|
||||||
|
]}
|
||||||
|
onChange={(v) => void set({ fxDelayBeats: Number(v) })}
|
||||||
|
/>
|
||||||
|
<Choice
|
||||||
|
title="Bit crusher drive"
|
||||||
|
value={String(fxCrusherDrive)}
|
||||||
|
options={[
|
||||||
|
['1', 'Clean (×1)'],
|
||||||
|
['2', 'Warm (×2)'],
|
||||||
|
['4', 'Hot (×4)'],
|
||||||
|
]}
|
||||||
|
onChange={(v) => void set({ fxCrusherDrive: Number(v) })}
|
||||||
|
/>
|
||||||
|
<Choice
|
||||||
|
title="Flanger sweep (slowest)"
|
||||||
|
value={String(fxFlangerBeats)}
|
||||||
|
options={[
|
||||||
|
['1', 'Every beat'],
|
||||||
|
['2', 'Every 2 beats'],
|
||||||
|
['4', 'Every 4 beats'],
|
||||||
|
['8', 'Every 8 beats'],
|
||||||
|
['16', 'Every 16 beats'],
|
||||||
|
]}
|
||||||
|
onChange={(v) => void set({ fxFlangerBeats: Number(v) })}
|
||||||
|
/>
|
||||||
|
</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">
|
||||||
|
<button onClick={onClose} className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold">
|
||||||
|
Done
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
+414
-1808
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,382 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { api, type ExportRunOptions, type ExportSet, type JobStatus, type PushPreview, type PushTarget } from '../api'
|
||||||
|
import { askConfirm } from '../lib/confirm'
|
||||||
|
import { localLibraryProblem } from '../lib/platformCopy'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Push a "computer" set into this computer's Traktor / rekordbox: confirm what
|
||||||
|
* is about to happen, then watch it happen. The sibling of `ExportRunDialog`,
|
||||||
|
* with the same rule — the preview takes the same body as the run, and is
|
||||||
|
* fetched fresh every time, never cached: the set's references are live.
|
||||||
|
*
|
||||||
|
* A running DJ app BLOCKS the push (Traktor writes its collection back when it
|
||||||
|
* quits, undoing it), and the preview re-checks every two seconds while it does,
|
||||||
|
* so quitting the app is all it takes. Overwrite is confirmed once more, naming
|
||||||
|
* the other pushes it removes. Normalise is not here: the pushed files are
|
||||||
|
* shared by every set, so their level is a setting (Settings → Local libraries).
|
||||||
|
*
|
||||||
|
* A library the set names that is not on THIS computer is skipped, not a block:
|
||||||
|
* a set's targets are shared by every computer that opens the library.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const POLL_MS = 300
|
||||||
|
|
||||||
|
function gb(bytes: number): string {
|
||||||
|
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`
|
||||||
|
if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(0)} MB`
|
||||||
|
return `${(bytes / 1e3).toFixed(0)} kB`
|
||||||
|
}
|
||||||
|
|
||||||
|
const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
set: ExportSet
|
||||||
|
onClose: () => void
|
||||||
|
onDone: (msg: string) => void
|
||||||
|
onError: (msg: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TargetResult {
|
||||||
|
name: string
|
||||||
|
added: number
|
||||||
|
updated: number
|
||||||
|
removed: number
|
||||||
|
kept: string[]
|
||||||
|
replaced?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PushRunDialog({ set, onClose, onDone, onError }: Props) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
const [job, setJob] = useState<JobStatus | null>(null)
|
||||||
|
const [starting, setStarting] = useState(false)
|
||||||
|
// Remembered on the set, sent with the click, as an export's are.
|
||||||
|
const [lockGrids, setLockGrids] = useState(set.lock_grids ?? true)
|
||||||
|
const [autoGain, setAutoGain] = useState(set.auto_gain ?? true)
|
||||||
|
const pollRef = useRef<number | null>(null)
|
||||||
|
const options: ExportRunOptions = { lock_grids: lockGrids, auto_gain: autoGain }
|
||||||
|
const overwrite = set.mode === 'overwrite'
|
||||||
|
|
||||||
|
const preview = useQuery<PushPreview>({
|
||||||
|
queryKey: ['push-preview', set.id, options],
|
||||||
|
queryFn: () => api.pushPreview(set.id, options),
|
||||||
|
enabled: !job,
|
||||||
|
staleTime: 0,
|
||||||
|
gcTime: 0,
|
||||||
|
// Quitting the DJ app is the fix for the commonest block: notice it.
|
||||||
|
refetchInterval: (q) => (q.state.data?.blocked === 'app_running' ? 2000 : false),
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!job || job.state !== 'running') return
|
||||||
|
pollRef.current = window.setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const next = await api.job(job.id)
|
||||||
|
setJob(next)
|
||||||
|
if (next.state !== 'running') {
|
||||||
|
if (pollRef.current) window.clearInterval(pollRef.current)
|
||||||
|
if (next.state === 'done') {
|
||||||
|
qc.invalidateQueries({ queryKey: ['local-libraries'] })
|
||||||
|
onDone(doneMessage(set.name, next.result))
|
||||||
|
} else if (next.state === 'failed') {
|
||||||
|
onError(next.error || 'Push failed')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
onError((e as Error).message)
|
||||||
|
if (pollRef.current) window.clearInterval(pollRef.current)
|
||||||
|
}
|
||||||
|
}, POLL_MS)
|
||||||
|
return () => {
|
||||||
|
if (pollRef.current) window.clearInterval(pollRef.current)
|
||||||
|
}
|
||||||
|
}, [job, qc, set.name, onDone, onError])
|
||||||
|
|
||||||
|
const p = preview.data
|
||||||
|
const blocked = p?.blocked ?? null
|
||||||
|
const active = p?.targets.filter((t) => !t.skipped) ?? []
|
||||||
|
|
||||||
|
const start = async () => {
|
||||||
|
if (overwrite && p) {
|
||||||
|
const wiped = active.flatMap((t) => t.wipes_sets)
|
||||||
|
const ok = await askConfirm({
|
||||||
|
title: `Replace ${active.map((t) => t.name).join(' and ')}’s library?`,
|
||||||
|
body:
|
||||||
|
`Everything in it is replaced by “${set.name}” — your own tracks and playlists too` +
|
||||||
|
(wiped.length ? `, and the pushes of ${wiped.map((n) => `“${n}”`).join(', ')}` : '') +
|
||||||
|
'. A backup is kept, but the DJ app will only show this set.',
|
||||||
|
confirmLabel: 'Replace',
|
||||||
|
})
|
||||||
|
if (!ok) return
|
||||||
|
}
|
||||||
|
setStarting(true)
|
||||||
|
try {
|
||||||
|
setJob(await api.runPush(set.id, options))
|
||||||
|
qc.invalidateQueries({ queryKey: ['exports'] })
|
||||||
|
} catch (e) {
|
||||||
|
onError((e as Error).message)
|
||||||
|
} finally {
|
||||||
|
setStarting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const cancel = async () => {
|
||||||
|
if (!job) return
|
||||||
|
try {
|
||||||
|
await api.cancelJob(job.id)
|
||||||
|
} catch (e) {
|
||||||
|
onError((e as Error).message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const running = job?.state === 'running'
|
||||||
|
const finished = job != null && job.state !== 'running'
|
||||||
|
const pct =
|
||||||
|
job?.state === 'done' ? 100 : job && job.total > 0 ? Math.min(100, (job.done / job.total) * 100) : null
|
||||||
|
const results = ((job?.result as { targets?: TargetResult[] } | null)?.targets ?? [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal onDismiss={onClose} padding="p-4">
|
||||||
|
<div className="w-full max-w-lg glass-overlay">
|
||||||
|
<div className="border-b border-line px-5 py-3">
|
||||||
|
<h2 className="text-sm font-semibold text-text">
|
||||||
|
{overwrite ? 'Replace with' : 'Push'} “{set.name}”
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4 px-5 py-4 text-sm">
|
||||||
|
{!job && (
|
||||||
|
<>
|
||||||
|
{preview.isLoading && <div className="text-faint">Checking…</div>}
|
||||||
|
{preview.isError && <div className="text-pink">{(preview.error as Error).message}</div>}
|
||||||
|
|
||||||
|
{p && (
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
{p.targets.map((t) => (
|
||||||
|
<TargetLine key={t.platform} target={t} overwrite={overwrite} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{p && blocked !== 'nothing_to_push' && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="text-text">
|
||||||
|
{plural(p.pushable, 'track')}
|
||||||
|
{p.playlists.length > 0 && ` · ${plural(p.playlists.length, 'playlist')}`}
|
||||||
|
<span className="text-muted">
|
||||||
|
{p.unchanged > 0 && ` · ${p.unchanged} already copied`} · {gb(p.total_bytes)} to copy
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-faint">
|
||||||
|
Into <span className="font-mono">{p.audio_root}</span>
|
||||||
|
{p.free_bytes != null && (
|
||||||
|
<span className={p.enough_space === false ? 'text-pink' : ''}>
|
||||||
|
{' '}· {gb(p.free_bytes)} free{p.enough_space === false && ' — not enough space'}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{p.missing.length > 0 && (
|
||||||
|
<div className="rounded well px-3 py-2 text-xs text-pink">
|
||||||
|
{plural(p.missing.length, 'track')} will be skipped — the audio file is not on this disk:
|
||||||
|
<div className="mt-1 text-faint">{p.missing.slice(0, 4).join(', ')}</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{overwrite && active.some((t) => t.wipes_sets.length) && (
|
||||||
|
<div className="rounded well px-3 py-2 text-xs text-gold">
|
||||||
|
Also removes what{' '}
|
||||||
|
{[...new Set(active.flatMap((t) => t.wipes_sets))].map((n) => `“${n}”`).join(', ')}{' '}
|
||||||
|
pushed there, and deletes its files.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{active.some((t) => t.platform === 'traktor') && (
|
||||||
|
<label className="flex cursor-pointer items-start gap-2.5">
|
||||||
|
<input type="checkbox" className="mt-0.5" checked={lockGrids}
|
||||||
|
onChange={(e) => setLockGrids(e.target.checked)} />
|
||||||
|
<span className="min-w-0">
|
||||||
|
<span className="block text-sm text-text">Lock beatgrids</span>
|
||||||
|
<span className="block text-xs text-faint">
|
||||||
|
Stops Traktor re-analysing the tracks when they’re loaded, which can change the
|
||||||
|
BPM or move the grid.
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<label className="flex cursor-pointer items-start gap-2.5">
|
||||||
|
<input type="checkbox" className="mt-0.5" checked={autoGain}
|
||||||
|
onChange={(e) => setAutoGain(e.target.checked)} />
|
||||||
|
<span className="min-w-0">
|
||||||
|
<span className="block text-sm text-text">Auto gain</span>
|
||||||
|
<span className="block text-xs text-faint">
|
||||||
|
Sets each track’s auto gain from its loudness, so tracks load at matching levels.
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<div className="text-xs text-faint">
|
||||||
|
{p.normalised > 0
|
||||||
|
? `${plural(p.normalised, 'copy', 'copies')} brought to the shared level. `
|
||||||
|
: ''}
|
||||||
|
Normalising is set for all pushes in Settings → Local libraries.
|
||||||
|
</div>
|
||||||
|
{p.to_measure > 0 && (
|
||||||
|
<div className="text-xs text-faint">
|
||||||
|
{plural(p.to_measure, 'track')} measured first (about a second each).
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{blocked === 'app_running' && (
|
||||||
|
<div className="rounded border border-pink/40 bg-well px-3 py-2 text-xs text-pink">
|
||||||
|
Quit {active.filter((t) => t.running).map((t) => t.name).join(' and ')} to push —
|
||||||
|
it would overwrite the push when it next saves its library.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{blocked === 'target_unavailable' && (
|
||||||
|
<div className="rounded border border-pink/40 bg-well px-3 py-2 text-xs text-pink">
|
||||||
|
Konduktor can’t push into every library this set is for. Check Settings → Local
|
||||||
|
libraries, or edit the set.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{blocked === 'no_library_here' && p && (
|
||||||
|
<div className="rounded border border-pink/40 bg-well px-3 py-2 text-xs text-pink">
|
||||||
|
{p.targets.map((t) => t.name).join(' and ')}{' '}
|
||||||
|
{p.targets.length === 1 ? 'isn’t' : 'aren’t'} on this computer, so there’s nothing to
|
||||||
|
push into. Set {p.targets.length === 1 ? 'its' : 'their'} location in Settings → Local
|
||||||
|
libraries, or edit the set.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{blocked === 'nothing_to_push' && p && (
|
||||||
|
<div className={`rounded well px-3 py-2 text-xs ${p.tracks ? 'text-pink' : 'text-muted'}`}>
|
||||||
|
{p.tracks === 0
|
||||||
|
? 'There’s nothing to push yet — add some tracks or a playlist.'
|
||||||
|
: `None of the ${plural(p.tracks, 'track')} can be pushed — their audio files are not on this disk.`}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{job && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="text-text">{job.state === 'done' ? 'Pushed.' : job.message || 'Working…'}</div>
|
||||||
|
<div className="h-2 overflow-hidden rounded-full bg-well">
|
||||||
|
<div
|
||||||
|
className={`h-full transition-[width] duration-200 ${job.state === 'failed' ? 'bg-pink' : 'bg-accent'} ${
|
||||||
|
pct == null ? 'w-1/3 animate-pulse' : ''
|
||||||
|
}`}
|
||||||
|
style={pct == null ? undefined : { width: `${pct}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{pct != null && running && job.unit === 'bytes' && (
|
||||||
|
<div className="text-xs text-faint">{gb(job.done)} of {gb(job.total)}</div>
|
||||||
|
)}
|
||||||
|
{job.state === 'cancelled' && (
|
||||||
|
<div className="text-xs text-muted">
|
||||||
|
Cancelled. A library already saved keeps the push; any other was left as it was.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{job.state === 'failed' && <div className="text-xs text-pink">{job.error}</div>}
|
||||||
|
{job.state === 'done' &&
|
||||||
|
results.map((r) => (
|
||||||
|
<div key={r.name} className="space-y-0.5 text-xs">
|
||||||
|
<div className="text-mint">{resultLine(r)}</div>
|
||||||
|
{r.kept.length > 0 && (
|
||||||
|
<div className="text-gold">
|
||||||
|
Left in {r.name}: {r.kept.slice(0, 4).join(', ')}
|
||||||
|
{r.kept.length > 4 && ` and ${r.kept.length - 4} more`} — {r.name} still lists
|
||||||
|
them in its History, Sampler or another list, so they stay. The next push tries
|
||||||
|
again.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
|
||||||
|
{running ? (
|
||||||
|
<>
|
||||||
|
<button onClick={cancel} className="btn-glass rounded-full px-3 py-1.5 text-sm text-muted hover:text-text">
|
||||||
|
Cancel push
|
||||||
|
</button>
|
||||||
|
<button onClick={onClose} className="rounded-md px-3 py-1.5 text-sm text-faint hover:text-text"
|
||||||
|
title="The push keeps running">
|
||||||
|
Hide
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<button onClick={onClose} className="btn-glass rounded-full px-3 py-1.5 text-sm text-muted hover:text-text">
|
||||||
|
{finished ? 'Close' : 'Cancel'}
|
||||||
|
</button>
|
||||||
|
{!finished && (
|
||||||
|
<button
|
||||||
|
disabled={starting || preview.isFetching || !p || !!blocked || p.enough_space === false}
|
||||||
|
onClick={start}
|
||||||
|
className="rounded-full btn-primary px-3 py-1.5 text-sm font-semibold disabled:opacity-40"
|
||||||
|
>
|
||||||
|
{starting ? 'Starting…' : overwrite ? 'Replace' : `Push ${p && !blocked ? p.pushable : ''}`.trim()}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TargetLine({ target, overwrite }: { target: PushTarget; overwrite: boolean }) {
|
||||||
|
if (target.skipped) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-md well px-3 py-2">
|
||||||
|
<div className="flex items-baseline gap-2">
|
||||||
|
<span className="text-faint">{target.name}</span>
|
||||||
|
<span className="ml-auto text-xs text-faint">not on this computer — skipped</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const problem = localLibraryProblem({ ...target, detected: true })
|
||||||
|
const counts = overwrite
|
||||||
|
? 'replaced by this set'
|
||||||
|
: [
|
||||||
|
target.add && `${target.add} to add`,
|
||||||
|
target.already && `${target.already} already there`,
|
||||||
|
target.remove && `${target.remove} to remove`,
|
||||||
|
].filter(Boolean).join(' · ') || 'nothing to change'
|
||||||
|
return (
|
||||||
|
<div className="rounded-md well px-3 py-2">
|
||||||
|
<div className="flex items-baseline gap-2">
|
||||||
|
<span className="text-text">{target.name}</span>
|
||||||
|
<span className={`ml-auto text-xs ${problem || target.running ? 'text-pink' : 'text-muted'}`}>
|
||||||
|
{problem ?? (target.running ? 'running' : counts)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{target.path && (
|
||||||
|
<div title={target.path} dir="rtl" className="truncate text-left font-mono text-[11px] text-faint">
|
||||||
|
{target.path}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function resultLine(r: TargetResult): string {
|
||||||
|
if (r.replaced) return `${r.name}: replaced — ${plural(r.added, 'track')}`
|
||||||
|
const parts = [
|
||||||
|
r.added && `${r.added} added`,
|
||||||
|
r.updated && `${r.updated} updated`,
|
||||||
|
r.removed && `${r.removed} removed`,
|
||||||
|
].filter(Boolean)
|
||||||
|
return `${r.name}: ${parts.length ? parts.join(', ') : 'already up to date'}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function doneMessage(name: string, result: Record<string, unknown> | null): string {
|
||||||
|
const r = result as { targets?: TargetResult[]; skipped_targets?: string[] } | null
|
||||||
|
const targets = (r?.targets ?? []).map((t) => t.name)
|
||||||
|
const skipped = r?.skipped_targets ?? []
|
||||||
|
return `Pushed “${name}” into ${targets.join(' and ') || 'this computer'}` +
|
||||||
|
(skipped.length ? ` (${skipped.join(' and ')} skipped — not on this computer)` : '')
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
import { flushPrefs } from '../lib/prefs'
|
import { flushPrefs } from '../lib/prefs'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ask before quitting with unsaved changes: Save · Discard · Cancel.
|
* Ask before quitting with unsaved changes: Save · Discard · Cancel.
|
||||||
@@ -99,21 +99,9 @@ export function QuitGuard() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!asking) return
|
|
||||||
const onKey = (e: KeyboardEvent) => {
|
|
||||||
if (e.key === 'Escape' && !busy) void cancel()
|
|
||||||
}
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!asking) return null
|
if (!asking) return null
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={busy ? null : () => void cancel()} layer="nested">
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
>
|
|
||||||
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
||||||
Save changes before quitting?
|
Save changes before quitting?
|
||||||
@@ -147,7 +135,6 @@ export function QuitGuard() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { createPortal } from 'react-dom'
|
import { useState } from 'react'
|
||||||
import { useEffect, useState } from 'react'
|
|
||||||
import { api, type PathMapping, type RelocationVolume } from '../api'
|
import { api, type PathMapping, type RelocationVolume } from '../api'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
volumes: RelocationVolume[]
|
volumes: RelocationVolume[]
|
||||||
@@ -51,21 +51,12 @@ export function RelocateDialog({ volumes, onAnswered, onOpenManual, onError }: P
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && answer([])
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
})
|
|
||||||
|
|
||||||
const set = (root: string, to: string | null) => setChoice((c) => ({ ...c, [root]: to }))
|
const set = (root: string, to: string | null) => setChoice((c) => ({ ...c, [root]: to }))
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
// No close on a backdrop click: dismissing lasts until the library is
|
// Esc is "Not now", but a backdrop click is not: dismissing lasts until
|
||||||
// reopened, which is too much for a stray click to decide.
|
// the library is reopened, which is too much for a stray click to decide.
|
||||||
<div
|
<Modal onDismiss={busy ? null : () => void answer([])} backdropDismiss={false}>
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
>
|
|
||||||
<div className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay">
|
<div className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Tracks not found</div>
|
<div className="text-[15px] font-semibold tracking-tight">Tracks not found</div>
|
||||||
@@ -116,8 +107,7 @@ export function RelocateDialog({ volumes, onAnswered, onOpenManual, onError }: P
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { createPortal } from 'react-dom'
|
import { useState } from 'react'
|
||||||
import { useEffect, useState } from 'react'
|
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
import { size } from './ConvertStemsDialog'
|
import { size } from './ConvertStemsDialog'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Settings → Remote audio: this computer's copies of a remote library's audio.
|
* Settings → Remote audio: this computer's copies of a remote library's audio.
|
||||||
@@ -21,12 +21,6 @@ export function RemoteCacheSettings({ onClose }: { onClose: () => void }) {
|
|||||||
const [busy, setBusy] = useState(false)
|
const [busy, setBusy] = useState(false)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [onClose])
|
|
||||||
|
|
||||||
const u = usage.data
|
const u = usage.data
|
||||||
const capGb = u ? Math.round(u.cap / 1024 ** 3) : null
|
const capGb = u ? Math.round(u.cap / 1024 ** 3) : null
|
||||||
|
|
||||||
@@ -54,13 +48,9 @@ export function RemoteCacheSettings({ onClose }: { onClose: () => void }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true"
|
<div className="flex w-full max-w-md flex-col overflow-hidden glass-overlay">
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6 backdrop-blur-[3px]"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div className="flex w-full max-w-md flex-col overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="flex items-center justify-between border-b border-line px-5 py-3">
|
<div className="flex items-center justify-between border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">Remote audio</h2>
|
<h2 className="text-sm font-semibold text-text">Remote audio</h2>
|
||||||
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
|
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
|
||||||
@@ -107,7 +97,6 @@ export function RemoteCacheSettings({ onClose }: { onClose: () => void }) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import { useState, type ReactNode } from 'react'
|
import { useState, type ReactNode } from 'react'
|
||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import {
|
import {
|
||||||
api,
|
api,
|
||||||
@@ -14,6 +13,7 @@ import {
|
|||||||
import { askConfirm } from '../lib/confirm'
|
import { askConfirm } from '../lib/confirm'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
import { remoteHolder } from '../lib/platformCopy'
|
import { remoteHolder } from '../lib/platformCopy'
|
||||||
|
import { Modal } from './Modal'
|
||||||
import { OptionCard } from './OptionCard'
|
import { OptionCard } from './OptionCard'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -329,12 +329,8 @@ function PendingEditsDialog({
|
|||||||
setBusy(false)
|
setBusy(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={busy ? null : () => void choose('later')}>
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6 backdrop-blur-[3px]"
|
|
||||||
onKeyDown={(e) => e.key === 'Escape' && !busy && void choose('later')}
|
|
||||||
>
|
|
||||||
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
||||||
Unsaved edits from {edits.machine || 'another computer'}
|
Unsaved edits from {edits.machine || 'another computer'}
|
||||||
@@ -369,7 +365,6 @@ function PendingEditsDialog({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||||
import type { SortingState } from '@tanstack/react-table'
|
import type { SortingState } from '@tanstack/react-table'
|
||||||
import { maxPosition, moveToPosition } from '../lib/playlistOrder'
|
import { maxPosition, moveToPosition } from '../lib/playlistOrder'
|
||||||
import { COLUMN_MENU } from '../lib/trackColumns'
|
import { COLUMN_MENU } from '../lib/trackColumns'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
/** The playlist's full entry order — never the sorted or filtered view, so
|
/** The playlist's full entry order — never the sorted or filtered view, so
|
||||||
@@ -50,14 +50,6 @@ export function SetPositionDialog({ order, ids, sorting, onMove, onClose }: Prop
|
|||||||
onClose()
|
onClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => {
|
|
||||||
if (e.key === 'Escape') onClose()
|
|
||||||
}
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [onClose])
|
|
||||||
|
|
||||||
const option = (value: 'playlist' | 'sorted', label: string, detail: ReactNode) => (
|
const option = (value: 'playlist' | 'sorted', label: string, detail: ReactNode) => (
|
||||||
<label
|
<label
|
||||||
className={`flex cursor-pointer gap-3 rounded-lg px-3 py-2 ${
|
className={`flex cursor-pointer gap-3 rounded-lg px-3 py-2 ${
|
||||||
@@ -80,15 +72,10 @@ export function SetPositionDialog({ order, ids, sorting, onMove, onClose }: Prop
|
|||||||
|
|
||||||
const span = (p: number) => (count > 1 ? `#${p}–${p + count - 1}` : `#${p}`)
|
const span = (p: number) => (count > 1 ? `#${p}–${p + count - 1}` : `#${p}`)
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<form
|
<form
|
||||||
className="w-full max-w-sm overflow-hidden glass-overlay"
|
className="w-full max-w-sm overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
onSubmit={(e) => {
|
onSubmit={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
submit()
|
submit()
|
||||||
@@ -152,7 +139,6 @@ export function SetPositionDialog({ order, ids, sorting, onMove, onClose }: Prop
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,9 @@ import { useQuery } from '@tanstack/react-query'
|
|||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
import { AppSettings } from './AppSettings'
|
import { AppSettings } from './AppSettings'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
|
import { LocalLibrariesSettings } from './LocalLibrariesSettings'
|
||||||
|
import { MidiSettings } from './MidiSettings'
|
||||||
|
import { PerformanceSettings } from './PerformanceSettings'
|
||||||
import { RemoteCacheSettings } from './RemoteCacheSettings'
|
import { RemoteCacheSettings } from './RemoteCacheSettings'
|
||||||
import { ShortcutsDialog } from './ShortcutsDialog'
|
import { ShortcutsDialog } from './ShortcutsDialog'
|
||||||
import { StemsSettings } from './StemsSettings'
|
import { StemsSettings } from './StemsSettings'
|
||||||
@@ -14,7 +17,7 @@ interface Props {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Overflow menu for low-frequency settings: the app's own (Konduktor
|
/** Overflow menu for low-frequency settings: the app's own (Konduktor
|
||||||
* settings), path remapping, Stems and the shortcut list. The dialogs are owned
|
* settings), path remapping, Stems, Performance mode and the shortcut list. The dialogs are owned
|
||||||
* here, since nothing else opens them. */
|
* here, since nothing else opens them. */
|
||||||
export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
|
export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
@@ -22,6 +25,9 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
|
|||||||
const [showStems, setShowStems] = useState(false)
|
const [showStems, setShowStems] = useState(false)
|
||||||
const [showCache, setShowCache] = useState(false)
|
const [showCache, setShowCache] = useState(false)
|
||||||
const [showApp, setShowApp] = useState(false)
|
const [showApp, setShowApp] = useState(false)
|
||||||
|
const [showLocal, setShowLocal] = useState(false)
|
||||||
|
const [showPerformance, setShowPerformance] = useState(false)
|
||||||
|
const [showMidi, setShowMidi] = useState(false)
|
||||||
const ref = useRef<HTMLDivElement>(null)
|
const ref = useRef<HTMLDivElement>(null)
|
||||||
// Path remapping is a library on THIS computer's business; a remote's
|
// Path remapping is a library on THIS computer's business; a remote's
|
||||||
// mapping is its server's configuration.
|
// mapping is its server's configuration.
|
||||||
@@ -123,6 +129,16 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
|
|||||||
<span className="text-[11px] text-faint">This computer's copies of the server's tracks</span>
|
<span className="text-[11px] text-faint">This computer's copies of the server's tracks</span>
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setShowLocal(true)
|
||||||
|
setOpen(false)
|
||||||
|
}}
|
||||||
|
className={item}
|
||||||
|
>
|
||||||
|
<span className="text-sm text-text">Local libraries…</span>
|
||||||
|
<span className="text-[11px] text-faint">The Traktor and rekordbox a set is pushed into</span>
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setShowStems(true)
|
setShowStems(true)
|
||||||
@@ -133,6 +149,26 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
|
|||||||
<span className="text-sm text-text">Stems…</span>
|
<span className="text-sm text-text">Stems…</span>
|
||||||
<span className="text-[11px] text-faint">The stem engine, device and conversion defaults</span>
|
<span className="text-[11px] text-faint">The stem engine, device and conversion defaults</span>
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setShowPerformance(true)
|
||||||
|
setOpen(false)
|
||||||
|
}}
|
||||||
|
className={item}
|
||||||
|
>
|
||||||
|
<span className="text-sm text-text">Performance mode…</span>
|
||||||
|
<span className="text-[11px] text-faint">The second deck, the mixer and its effects</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setShowMidi(true)
|
||||||
|
setOpen(false)
|
||||||
|
}}
|
||||||
|
className={item}
|
||||||
|
>
|
||||||
|
<span className="text-sm text-text">MIDI Controllers…</span>
|
||||||
|
<span className="text-[11px] text-faint">Map a controller by moving its controls</span>
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setShowShortcuts(true)
|
setShowShortcuts(true)
|
||||||
@@ -149,6 +185,9 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
|
|||||||
{showStems && <StemsSettings onClose={() => setShowStems(false)} />}
|
{showStems && <StemsSettings onClose={() => setShowStems(false)} />}
|
||||||
{showCache && <RemoteCacheSettings onClose={() => setShowCache(false)} />}
|
{showCache && <RemoteCacheSettings onClose={() => setShowCache(false)} />}
|
||||||
{showApp && <AppSettings onClose={() => setShowApp(false)} />}
|
{showApp && <AppSettings onClose={() => setShowApp(false)} />}
|
||||||
|
{showLocal && <LocalLibrariesSettings onClose={() => setShowLocal(false)} />}
|
||||||
|
{showPerformance && <PerformanceSettings onClose={() => setShowPerformance(false)} />}
|
||||||
|
{showMidi && <MidiSettings onClose={() => setShowMidi(false)} />}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'
|
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
@@ -24,6 +23,7 @@ import {
|
|||||||
type Layer,
|
type Layer,
|
||||||
type MouseGesture,
|
type MouseGesture,
|
||||||
} from '../lib/shortcuts'
|
} from '../lib/shortcuts'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
@@ -55,7 +55,7 @@ export function ShortcutsDialog({ onClose }: Props) {
|
|||||||
const [pressed, setPressed] = useState<string | null>(null)
|
const [pressed, setPressed] = useState<string | null>(null)
|
||||||
const [query, setQuery] = useState('')
|
const [query, setQuery] = useState('')
|
||||||
const [areas, setAreas] = useState<ReadonlySet<Area>>(new Set(ALL_AREAS))
|
const [areas, setAreas] = useState<ReadonlySet<Area>>(new Set(ALL_AREAS))
|
||||||
const layer: Layer = held.has('mod') ? 'mod' : held.has('shift') ? 'shift' : sticky
|
const layer: Layer = held.has('mod') ? 'mod' : held.has('alt') ? 'alt' : held.has('shift') ? 'shift' : sticky
|
||||||
const q = query.trim().toLowerCase()
|
const q = query.trim().toLowerCase()
|
||||||
|
|
||||||
// ---- fit: one key unit from the width the map has ----
|
// ---- fit: one key unit from the width the map has ----
|
||||||
@@ -162,15 +162,10 @@ export function ShortcutsDialog({ onClose }: Props) {
|
|||||||
onPick: pickLayer,
|
onPick: pickLayer,
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="flex max-h-full w-full max-w-[960px] 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 flex-wrap items-center gap-3 border-b border-line py-3.5 pl-5 pr-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>
|
<div className="text-[15px] font-semibold tracking-tight">Keyboard Shortcuts</div>
|
||||||
@@ -309,8 +304,7 @@ export function ShortcutsDialog({ onClose }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -430,8 +424,8 @@ function Caption({
|
|||||||
<>
|
<>
|
||||||
<span className="text-text">Point at a key, or press it, to see what it does.</span>
|
<span className="text-text">Point at a key, or press it, to see what it does.</span>
|
||||||
<span className="text-xs">
|
<span className="text-xs">
|
||||||
Hold <Kbd>{MODIFIER_KEY.shift}</Kbd> or <Kbd>{MODIFIER_KEY.mod}</Kbd>, or pick one above, to see what each
|
Hold <Kbd>{MODIFIER_KEY.shift}</Kbd>, <Kbd>{MODIFIER_KEY.mod}</Kbd> or <Kbd>{MODIFIER_KEY.alt}</Kbd>, or pick
|
||||||
modifier changes.
|
one above, to see what each modifier changes.
|
||||||
</span>
|
</span>
|
||||||
<span className="text-xs">
|
<span className="text-xs">
|
||||||
{padRange(slots)} are this library's {slots} hotcue pads; Q W E R are the stems of a stem track.
|
{padRange(slots)} are this library's {slots} hotcue pads; Q W E R are the stems of a stem track.
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ import { PlatformIcon } from '../lib/platformIcons'
|
|||||||
import { addTracksToPlaylist } from '../lib/addTracks'
|
import { addTracksToPlaylist } from '../lib/addTracks'
|
||||||
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload, type TracksOrFiles } from '../lib/drag'
|
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload, type TracksOrFiles } from '../lib/drag'
|
||||||
import { findNode, idsAfter, nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
|
import { findNode, idsAfter, nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
|
||||||
|
import { useMidiTargets } from '../lib/midi/targets'
|
||||||
|
|
||||||
|
/** All Tracks' place in a controller's walk of the tree (no node has this id). */
|
||||||
|
const ALL_ROW = 'konduktor:all-tracks'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Which view the main table is showing.
|
* Which view the main table is showing.
|
||||||
@@ -104,6 +108,8 @@ interface RowActions {
|
|||||||
/** Whether a folder is open, and opening / closing it. */
|
/** Whether a folder is open, and opening / closing it. */
|
||||||
isOpen: (node: PlaylistNode) => boolean
|
isOpen: (node: PlaylistNode) => boolean
|
||||||
setOpen: (node: PlaylistNode, open: boolean) => void
|
setOpen: (node: PlaylistNode, open: boolean) => void
|
||||||
|
/** Where a controller's playlist browsing stands (lib/midi), when not on the open playlist. */
|
||||||
|
isCursor: (node: PlaylistNode) => boolean
|
||||||
onContextMenu: (e: React.MouseEvent, node: PlaylistNode) => void
|
onContextMenu: (e: React.MouseEvent, node: PlaylistNode) => void
|
||||||
onRename: (node: PlaylistNode, name: string, parentId: string | null) => void
|
onRename: (node: PlaylistNode, name: string, parentId: string | null) => void
|
||||||
onDelete: (node: PlaylistNode) => void
|
onDelete: (node: PlaylistNode) => void
|
||||||
@@ -300,6 +306,7 @@ function NodeRow({
|
|||||||
<div
|
<div
|
||||||
ref={dropRef}
|
ref={dropRef}
|
||||||
data-node-row
|
data-node-row
|
||||||
|
data-node-id={node.id}
|
||||||
onPointerDown={startDrag}
|
onPointerDown={startDrag}
|
||||||
onContextMenu={(e) => actions.onContextMenu(e, node)}
|
onContextMenu={(e) => actions.onContextMenu(e, node)}
|
||||||
className={`group relative flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${
|
className={`group relative flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${
|
||||||
@@ -307,7 +314,9 @@ function NodeRow({
|
|||||||
? 'bg-accent-soft/40 text-text ring-1 ring-accent'
|
? 'bg-accent-soft/40 text-text ring-1 ring-accent'
|
||||||
: selected
|
: selected
|
||||||
? 'is-selected font-medium text-text'
|
? 'is-selected font-medium text-text'
|
||||||
: 'text-muted hover:bg-ink-800 hover:text-text'
|
: actions.isCursor(node)
|
||||||
|
? 'bg-ink-800 text-text ring-1 ring-accent/60'
|
||||||
|
: 'text-muted hover:bg-ink-800 hover:text-text'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{line && (
|
{line && (
|
||||||
@@ -485,6 +494,45 @@ export function Sidebar({
|
|||||||
useEffect(() => setOpenOverrides({}), [library?.path, expandByDefault])
|
useEffect(() => setOpenOverrides({}), [library?.path, expandByDefault])
|
||||||
const setFolderOpen = (id: string, open: boolean) =>
|
const setFolderOpen = (id: string, open: boolean) =>
|
||||||
setOpenOverrides((o) => ({ ...o, [id]: open }))
|
setOpenOverrides((o) => ({ ...o, [id]: open }))
|
||||||
|
const isOpen = (node: PlaylistNode) => openOverrides[node.id] ?? expandByDefault
|
||||||
|
|
||||||
|
// A controller's Shift + browse walks All Tracks and the visible playlist
|
||||||
|
// tree (decided 2026-11-03): a playlist opens as it is reached, a folder is
|
||||||
|
// only highlighted (the cursor) and opens / closes on the encoder's press.
|
||||||
|
const [treeCursor, setTreeCursor] = useState<string | null>(null)
|
||||||
|
useEffect(() => setTreeCursor(null), [source])
|
||||||
|
const visibleRows = (): { id: string; node: PlaylistNode | null }[] => {
|
||||||
|
const out: { id: string; node: PlaylistNode | null }[] = [{ id: ALL_ROW, node: null }]
|
||||||
|
const walk = (nodes: PlaylistNode[]) => {
|
||||||
|
for (const n of nodes) {
|
||||||
|
out.push({ id: n.id, node: n })
|
||||||
|
if (n.kind === 'folder' && isOpen(n)) walk(n.children)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(playlists ?? [])
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
useMidiTargets({
|
||||||
|
tree: {
|
||||||
|
step: (ticks) => {
|
||||||
|
const rows = visibleRows()
|
||||||
|
const at = treeCursor ?? (source.kind === 'all' ? ALL_ROW : source.kind === 'playlist' ? source.id : null)
|
||||||
|
const i = rows.findIndex((r) => r.id === at)
|
||||||
|
const next = rows[Math.max(0, Math.min(rows.length - 1, i < 0 ? 0 : i + ticks))]
|
||||||
|
if (!next) return
|
||||||
|
if (!next.node) onSelect({ kind: 'all' })
|
||||||
|
else if (next.node.kind !== 'folder' && next.node.selectable) {
|
||||||
|
onSelect({ kind: 'playlist', id: next.node.id, name: next.node.name })
|
||||||
|
}
|
||||||
|
setTreeCursor(next.id)
|
||||||
|
document.querySelector(`[data-node-id="${CSS.escape(next.id)}"]`)?.scrollIntoView({ block: 'nearest' })
|
||||||
|
},
|
||||||
|
press: () => {
|
||||||
|
const node = treeCursor ? findNode(playlists ?? [], treeCursor) : null
|
||||||
|
if (node?.kind === 'folder') setFolderOpen(node.id, !isOpen(node))
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
// A folder's id — and so every id under it — may change when it is renamed
|
// A folder's id — and so every id under it — may change when it is renamed
|
||||||
// or moved (a platform addressing folders by path), so open state follows
|
// or moved (a platform addressing folders by path), so open state follows
|
||||||
// the subtree to its new ids. Reads the tree as refetched after the edit.
|
// the subtree to its new ids. Reads the tree as refetched after the edit.
|
||||||
@@ -631,8 +679,9 @@ export function Sidebar({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const actions: RowActions = {
|
const actions: RowActions = {
|
||||||
isOpen: (node) => openOverrides[node.id] ?? expandByDefault,
|
isOpen,
|
||||||
setOpen: (node, open) => setFolderOpen(node.id, open),
|
setOpen: (node, open) => setFolderOpen(node.id, open),
|
||||||
|
isCursor: (node) => treeCursor === node.id,
|
||||||
onContextMenu: (e, node) => openMenu(e, nodeItems(node)),
|
onContextMenu: (e, node) => openMenu(e, nodeItems(node)),
|
||||||
onRename: (node, name, parentId) => rename.mutate({ node, name, parentId }),
|
onRename: (node, name, parentId) => rename.mutate({ node, name, parentId }),
|
||||||
onDelete: confirmDelete,
|
onDelete: confirmDelete,
|
||||||
@@ -760,6 +809,7 @@ export function Sidebar({
|
|||||||
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto">
|
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto">
|
||||||
<div className="shrink-0 px-2 pt-3">
|
<div className="shrink-0 px-2 pt-3">
|
||||||
<button
|
<button
|
||||||
|
data-node-id={ALL_ROW}
|
||||||
onClick={() => onSelect({ kind: 'all' })}
|
onClick={() => onSelect({ kind: 'all' })}
|
||||||
className={`flex w-full items-center gap-2 rounded-[10px] px-2 py-1.5 text-left text-sm transition-colors ${
|
className={`flex w-full items-center gap-2 rounded-[10px] px-2 py-1.5 text-left text-sm transition-colors ${
|
||||||
source.kind === 'all'
|
source.kind === 'all'
|
||||||
@@ -774,10 +824,26 @@ export function Sidebar({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-3 shrink-0 px-4">
|
<div className="mt-3 flex shrink-0 items-center justify-between px-4">
|
||||||
<span className="text-[11px] font-semibold uppercase tracking-wider text-faint">
|
<span className="text-[11px] font-semibold uppercase tracking-wider text-faint">
|
||||||
Playlists
|
Playlists
|
||||||
</span>
|
</span>
|
||||||
|
{/* The same choices as right-clicking below the rows: straight to a
|
||||||
|
new playlist where there is nothing else to create, else the
|
||||||
|
menu, opened under the button. */}
|
||||||
|
{canCreate && (
|
||||||
|
<button
|
||||||
|
title={foldersSupported ? 'New playlist or folder' : 'New playlist'}
|
||||||
|
onClick={(e) => {
|
||||||
|
if (!foldersSupported) return startDraft('playlist', null)
|
||||||
|
const r = e.currentTarget.getBoundingClientRect()
|
||||||
|
setMenu({ x: r.left, y: r.bottom + 4, items: createItems(null) })
|
||||||
|
}}
|
||||||
|
className="rounded px-1 text-sm text-faint hover:text-text"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Right-click here (below the rows) creates at the top level; rows
|
{/* Right-click here (below the rows) creates at the top level; rows
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect } from 'react'
|
|
||||||
import type { StemBatchResult } from '../api'
|
import type { StemBatchResult } from '../api'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Details behind a finished conversion's toast: every track that was
|
* The Details behind a finished conversion's toast: every track that was
|
||||||
@@ -8,24 +7,14 @@ import type { StemBatchResult } from '../api'
|
|||||||
* into a toast).
|
* into a toast).
|
||||||
*/
|
*/
|
||||||
export function StemReportDialog({ result, onClose }: { result: StemBatchResult; onClose: () => void }) {
|
export function StemReportDialog({ result, onClose }: { result: StemBatchResult; onClose: () => void }) {
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [onClose])
|
|
||||||
|
|
||||||
const rows = [
|
const rows = [
|
||||||
...result.failed.map((s) => ({ ...s, failed: true })),
|
...result.failed.map((s) => ({ ...s, failed: true })),
|
||||||
...result.skipped.map((s) => ({ ...s, failed: false })),
|
...result.skipped.map((s) => ({ ...s, failed: false })),
|
||||||
]
|
]
|
||||||
const n = result.converted.length
|
const n = result.converted.length
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose} padding="p-4">
|
||||||
aria-modal="true"
|
<div className="flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden glass-overlay">
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-[3px]"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div className="flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="border-b border-line px-5 py-3 text-sm font-semibold text-text">
|
<div className="border-b border-line px-5 py-3 text-sm font-semibold text-text">
|
||||||
{n} converted to stems · {result.skipped.length} skipped · {result.failed.length} failed
|
{n} converted to stems · {result.skipped.length} skipped · {result.failed.length} failed
|
||||||
</div>
|
</div>
|
||||||
@@ -49,7 +38,6 @@ export function StemReportDialog({ result, onClose }: { result: StemBatchResult;
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type StemTarget } from '../api'
|
import { api, type StemTarget } from '../api'
|
||||||
import { askConfirm } from '../lib/confirm'
|
import { askConfirm } from '../lib/confirm'
|
||||||
import { FolderPicker } from './FolderPicker'
|
import { FolderPicker } from './FolderPicker'
|
||||||
import { size } from './ConvertStemsDialog'
|
import { size } from './ConvertStemsDialog'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Settings → Stems (decided contents): the engine (status, download, install
|
* Settings → Stems (decided contents): the engine (status, download, install
|
||||||
@@ -40,12 +40,6 @@ export function StemsSettings({ onClose }: Props) {
|
|||||||
}
|
}
|
||||||
}, [install.data, qc])
|
}, [install.data, qc])
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !picking && onClose()
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [onClose, picking])
|
|
||||||
|
|
||||||
const act = async (fn: () => Promise<unknown>) => {
|
const act = async (fn: () => Promise<unknown>) => {
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
setError(null)
|
setError(null)
|
||||||
@@ -72,7 +66,7 @@ export function StemsSettings({ onClose }: Props) {
|
|||||||
const targetLabel = (t: StemTarget) =>
|
const targetLabel = (t: StemTarget) =>
|
||||||
t === 'macos-arm64' ? 'Apple silicon (GPU)' : t === 'windows-x64-cuda' ? 'NVIDIA GPU' : 'processor only'
|
t === 'macos-arm64' ? 'Apple silicon (GPU)' : t === 'windows-x64-cuda' ? 'NVIDIA GPU' : 'processor only'
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<>
|
<>
|
||||||
{picking && (
|
{picking && (
|
||||||
<FolderPicker
|
<FolderPicker
|
||||||
@@ -81,14 +75,9 @@ export function StemsSettings({ onClose }: Props) {
|
|||||||
onClose={() => setPicking(null)}
|
onClose={() => setPicking(null)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6 backdrop-blur-[3px]"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="flex max-h-[85vh] w-full max-w-lg flex-col overflow-hidden glass-overlay"
|
className="flex max-h-[85vh] w-full max-w-lg flex-col overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-between border-b border-line px-5 py-3">
|
<div className="flex items-center justify-between border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">Stems</h2>
|
<h2 className="text-sm font-semibold text-text">Stems</h2>
|
||||||
@@ -241,8 +230,7 @@ export function StemsSettings({ onClose }: Props) {
|
|||||||
{error && <div className="text-xs text-pink">{error}</div>}
|
{error && <div className="text-xs text-pink">{error}</div>}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</>,
|
</>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useRef } from 'react'
|
import { useRef, type ReactNode } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
@@ -27,6 +27,8 @@ export const emptyFilters: Filters = {
|
|||||||
interface Props {
|
interface Props {
|
||||||
filters: Filters
|
filters: Filters
|
||||||
onChange: (f: Filters) => void
|
onChange: (f: Filters) => void
|
||||||
|
/** At the far right, after Clear filters (the Performance button). */
|
||||||
|
trailing?: ReactNode
|
||||||
}
|
}
|
||||||
|
|
||||||
const selectCls =
|
const selectCls =
|
||||||
@@ -35,6 +37,7 @@ const selectCls =
|
|||||||
export function Toolbar({
|
export function Toolbar({
|
||||||
filters,
|
filters,
|
||||||
onChange,
|
onChange,
|
||||||
|
trailing,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const caps = useCaps()
|
const caps = useCaps()
|
||||||
const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets })
|
const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets })
|
||||||
@@ -60,7 +63,7 @@ export function Toolbar({
|
|||||||
onChange={(e) => set({ search: e.target.value })}
|
onChange={(e) => set({ search: e.target.value })}
|
||||||
ref={searchRef}
|
ref={searchRef}
|
||||||
placeholder="Artist, title, album, comment…"
|
placeholder="Artist, title, album, comment…"
|
||||||
className="well w-72 rounded-full py-1.5 pl-9 pr-8 text-sm text-text outline-none placeholder:text-faint focus:ring-1 focus:ring-accent"
|
className="well w-64 rounded-full py-1.5 pl-9 pr-8 text-sm text-text outline-none placeholder:text-faint focus:ring-1 focus:ring-accent"
|
||||||
/>
|
/>
|
||||||
{filters.search && (
|
{filters.search && (
|
||||||
<button
|
<button
|
||||||
@@ -81,7 +84,10 @@ export function Toolbar({
|
|||||||
<select
|
<select
|
||||||
value={filters.genre}
|
value={filters.genre}
|
||||||
onChange={(e) => set({ genre: e.target.value })}
|
onChange={(e) => set({ genre: e.target.value })}
|
||||||
className={selectCls}
|
// A select is as wide as its longest option — one long genre name
|
||||||
|
// made it ~300 px and wrapped the toolbar. The chosen one shows in full
|
||||||
|
// in the open list.
|
||||||
|
className={`${selectCls} max-w-44`}
|
||||||
>
|
>
|
||||||
<option value="">All genres</option>
|
<option value="">All genres</option>
|
||||||
{facets?.genres.map((g) => (
|
{facets?.genres.map((g) => (
|
||||||
@@ -152,6 +158,7 @@ export function Toolbar({
|
|||||||
Clear filters
|
Clear filters
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{trailing}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { createPortal } from 'react-dom'
|
import { useState, type ReactNode } from 'react'
|
||||||
import { useEffect, useState, type ReactNode } from 'react'
|
|
||||||
import type { Track } from '../api'
|
import type { Track } from '../api'
|
||||||
import { formatBpm, formatDuration, keyColor } from '../lib/format'
|
import { formatBpm, formatDuration, keyColor } from '../lib/format'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
import { RatingStars } from './RatingStars'
|
import { RatingStars } from './RatingStars'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
track: Track
|
track: Track
|
||||||
@@ -27,12 +27,6 @@ export function TrackInfoDialog({ track, artUrl, onClose, onEditTags }: Props) {
|
|||||||
const [artFailed, setArtFailed] = useState(false)
|
const [artFailed, setArtFailed] = useState(false)
|
||||||
const showArt = artUrl != null && !artFailed
|
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 =
|
const grid =
|
||||||
track.grid_marker_count === 0
|
track.grid_marker_count === 0
|
||||||
? null
|
? null
|
||||||
@@ -60,17 +54,10 @@ export function TrackInfoDialog({ track, artUrl, onClose, onEditTags }: Props) {
|
|||||||
] as [string, ReactNode][]
|
] as [string, ReactNode][]
|
||||||
).filter(([, v]) => v != null && v !== '')
|
).filter(([, v]) => v != null && v !== '')
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose} padding="p-4" role="dialog" aria-label={track.title ?? 'Track info'}>
|
||||||
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
|
<div
|
||||||
className="track-info-pop glass-overlay flex max-h-[90vh] w-full max-w-[860px] flex-col overflow-hidden sm:flex-row"
|
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
|
{/* 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
|
art's own colours. `filter` on this leaf is safe — nothing can open
|
||||||
@@ -166,8 +153,7 @@ export function TrackInfoDialog({ track, artUrl, onClose, onEditTags }: Props) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
|
import { useMidiTargets } from '../lib/midi/targets'
|
||||||
import {
|
import {
|
||||||
DndContext,
|
DndContext,
|
||||||
PointerSensor,
|
PointerSensor,
|
||||||
@@ -542,11 +543,16 @@ export function TrackTable({
|
|||||||
}
|
}
|
||||||
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return
|
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
|
moveLead(e.key === 'ArrowDown' ? 1 : -1, e.shiftKey)
|
||||||
|
}
|
||||||
|
/** Move the highlight `step` rows (Shift: extend the selection) — ↑/↓, and
|
||||||
|
* a controller's browse encoder. */
|
||||||
|
const moveLead = (step: number, extend: boolean) => {
|
||||||
|
if (!selection || rows.length === 0) return
|
||||||
const lead = indexOf(leadRef.current)
|
const lead = indexOf(leadRef.current)
|
||||||
const step = e.key === 'ArrowDown' ? 1 : -1
|
|
||||||
const next = lead < 0 ? 0 : Math.max(0, Math.min(rows.length - 1, lead + step))
|
const next = lead < 0 ? 0 : Math.max(0, Math.min(rows.length - 1, lead + step))
|
||||||
const anchor = indexOf(anchorRef.current)
|
const anchor = indexOf(anchorRef.current)
|
||||||
if (e.shiftKey && anchor >= 0) {
|
if (extend && anchor >= 0) {
|
||||||
leadRef.current = rows[next].original.id
|
leadRef.current = rows[next].original.id
|
||||||
selection.onChange(new Set(rangeIds(anchor, next)))
|
selection.onChange(new Set(rangeIds(anchor, next)))
|
||||||
} else {
|
} else {
|
||||||
@@ -554,6 +560,15 @@ export function TrackTable({
|
|||||||
}
|
}
|
||||||
virtualizer.scrollToIndex(next)
|
virtualizer.scrollToIndex(next)
|
||||||
}
|
}
|
||||||
|
// A controller's browse encoder moves the highlight as ↑/↓ do, and its load
|
||||||
|
// buttons take the highlighted row (lib/midi).
|
||||||
|
useMidiTargets({
|
||||||
|
browse: selection && onPlay ? (ticks) => moveLead(ticks, false) : null,
|
||||||
|
lead: () => {
|
||||||
|
const i = indexOf(leadRef.current)
|
||||||
|
return i >= 0 && selection?.selected.has(rows[i].original.id) ? rows[i].original : null
|
||||||
|
},
|
||||||
|
})
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onKey = (e: KeyboardEvent) => keysRef.current(e)
|
const onKey = (e: KeyboardEvent) => keysRef.current(e)
|
||||||
window.addEventListener('keydown', onKey)
|
window.addEventListener('keydown', onKey)
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Startup update check against GitHub Releases.
|
* Startup update check against GitHub Releases.
|
||||||
*
|
*
|
||||||
* Compares the running version (`__APP_VERSION__`, baked from package.json at
|
* Compares the running version (`__APP_VERSION__`, baked from package.json at
|
||||||
* build time) with the latest release's tag (`v<version>-b<N>` — only the
|
* build time) with release tags (`v<version>-b<N>` — only the semver part
|
||||||
* semver part counts, so a new build of the same version is NOT an update).
|
* counts, so a new build of the same version is NOT an update). The dialog
|
||||||
|
* lists the notes of EVERY release newer than the running one, not just the
|
||||||
|
* latest's.
|
||||||
* Failures are silent: an update check must never nag about itself.
|
* Failures are silent: an update check must never nag about itself.
|
||||||
* "Skip this version" persists `skippedUpdateVersion` to userprefs.json via
|
* "Skip this version" persists `skippedUpdateVersion` to userprefs.json via
|
||||||
* the prefs API, keyed by the semver part, so a later version re-triggers.
|
* the prefs API, keyed by the semver part, so a later version re-triggers.
|
||||||
@@ -36,22 +38,39 @@ interface GithubRelease {
|
|||||||
prerelease?: boolean
|
prerelease?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MAX_PAGES = 5
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The newest APP release. Not `/releases/latest`: that is whichever release
|
* Every APP release newer than the running version, newest first — the first
|
||||||
* GitHub flags "latest", and the same repo also publishes the stem engine on
|
* is the one offered, and all of their notes are shown, so someone several
|
||||||
* its own `engine-v*` channel — one flagged latest by mistake would make this
|
* versions behind sees everything they are getting. Not `/releases/latest`:
|
||||||
* check go quiet (its tag does not parse as an app version) with no error. So
|
* that is whichever release GitHub flags "latest", and the same repo also
|
||||||
* list recent releases (newest first) and take the first app tag.
|
* publishes the stem engine on its own `engine-v*` channel — one flagged
|
||||||
|
* latest by mistake would make this check go quiet (its tag does not parse as
|
||||||
|
* an app version) with no error. So list releases (newest first) and keep the
|
||||||
|
* app tags, paging until one is not newer than the running version.
|
||||||
*/
|
*/
|
||||||
async function fetchLatestRelease(): Promise<GithubRelease> {
|
async function fetchNewerReleases(): Promise<GithubRelease[]> {
|
||||||
const res = await fetch(`https://api.github.com/repos/${REPO}/releases?per_page=30`, {
|
const current = parseVersion(__APP_VERSION__)
|
||||||
headers: { Accept: 'application/vnd.github+json' },
|
if (!current) return []
|
||||||
})
|
const newer: GithubRelease[] = []
|
||||||
if (!res.ok) throw new Error(`GitHub responded ${res.status}`)
|
for (let page = 1; page <= MAX_PAGES; page++) {
|
||||||
const releases: GithubRelease[] = await res.json()
|
const res = await fetch(
|
||||||
const app = releases.find((r) => !r.draft && !r.prerelease && /^v\d/.test(r.tag_name))
|
`https://api.github.com/repos/${REPO}/releases?per_page=100&page=${page}`,
|
||||||
if (!app) throw new Error('No app release found')
|
{ headers: { Accept: 'application/vnd.github+json' } },
|
||||||
return app
|
)
|
||||||
|
if (!res.ok) throw new Error(`GitHub responded ${res.status}`)
|
||||||
|
const releases: GithubRelease[] = await res.json()
|
||||||
|
for (const r of releases) {
|
||||||
|
if (r.draft || r.prerelease) continue
|
||||||
|
const v = parseVersion(r.tag_name)
|
||||||
|
if (!v || !r.tag_name.startsWith('v')) continue
|
||||||
|
if (!isNewer(v, current)) return newer
|
||||||
|
newer.push(r)
|
||||||
|
}
|
||||||
|
if (releases.length < 100) break
|
||||||
|
}
|
||||||
|
return newer
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The semver triple at the start of a version/tag string ("v0.1.2-b7" → [0,1,2]). */
|
/** The semver triple at the start of a version/tag string ("v0.1.2-b7" → [0,1,2]). */
|
||||||
@@ -163,9 +182,9 @@ export function UpdateCheck() {
|
|||||||
const [skipVersion, setSkipVersion] = useState(false)
|
const [skipVersion, setSkipVersion] = useState(false)
|
||||||
const [phase, setPhase] = useState<Phase>({ kind: 'offer' })
|
const [phase, setPhase] = useState<Phase>({ kind: 'offer' })
|
||||||
|
|
||||||
const release = useQuery({
|
const releases = useQuery({
|
||||||
queryKey: ['latestRelease'],
|
queryKey: ['newerReleases'],
|
||||||
queryFn: fetchLatestRelease,
|
queryFn: fetchNewerReleases,
|
||||||
staleTime: Infinity,
|
staleTime: Infinity,
|
||||||
retry: false,
|
retry: false,
|
||||||
})
|
})
|
||||||
@@ -195,11 +214,10 @@ export function UpdateCheck() {
|
|||||||
}
|
}
|
||||||
}, [phase.kind])
|
}, [phase.kind])
|
||||||
|
|
||||||
const latest = release.data
|
const newer = releases.data ?? []
|
||||||
const latestVer = latest ? parseVersion(latest.tag_name) : null
|
const latest = newer[0]
|
||||||
const currentVer = parseVersion(__APP_VERSION__)
|
const latestSemver = latest ? parseVersion(latest.tag_name)?.join('.') : undefined
|
||||||
const latestSemver = latestVer?.join('.')
|
const updateAvailable = !!latest
|
||||||
const updateAvailable = !!(latestVer && currentVer && isNewer(latestVer, currentVer))
|
|
||||||
const skipped = !!latestSemver && prefs.data?.skippedUpdateVersion === latestSemver
|
const skipped = !!latestSemver && prefs.data?.skippedUpdateVersion === latestSemver
|
||||||
const failedBefore = lastFailure.data ?? null
|
const failedBefore = lastFailure.data ?? null
|
||||||
const releasePage = latest?.html_url ?? `https://github.com/${REPO}/releases`
|
const releasePage = latest?.html_url ?? `https://github.com/${REPO}/releases`
|
||||||
@@ -262,16 +280,15 @@ export function UpdateCheck() {
|
|||||||
? "Update didn't install"
|
? "Update didn't install"
|
||||||
: 'Update available'
|
: 'Update available'
|
||||||
|
|
||||||
const changes = latest ? whatsChanged(latest.body) : []
|
// One section per release the user is skipping past, newest first; a heading
|
||||||
|
// only when there is more than one, so a one-step update reads as before.
|
||||||
|
const sections = newer.map((r) => ({ tag: r.tag_name, changes: whatsChanged(r.body) }))
|
||||||
|
const grouped = sections.length > 1
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={busy ? null : close}>
|
||||||
aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={close}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="flex max-h-[80vh] w-full max-w-md flex-col overflow-hidden glass-overlay"
|
className="flex max-h-[80vh] w-full max-w-md flex-col overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">{title}</div>
|
<div className="text-[15px] font-semibold tracking-tight">{title}</div>
|
||||||
@@ -312,21 +329,32 @@ export function UpdateCheck() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<div className="mb-2 text-xs font-medium text-muted">What's changed</div>
|
<div className="mb-2 text-xs font-medium text-muted">
|
||||||
{changes.length ? (
|
What's changed{grouped ? ` since v${__APP_VERSION__}` : ''}
|
||||||
<ul className="space-y-1.5">
|
</div>
|
||||||
{changes.map((line, i) => (
|
<div className="space-y-4">
|
||||||
<li key={i} className="flex gap-2 text-sm text-text">
|
{sections.map((s) => (
|
||||||
<span className="text-faint">•</span>
|
<section key={s.tag}>
|
||||||
<span className="min-w-0 break-words">
|
{grouped && (
|
||||||
<ChangelogLine text={line} />
|
<div className="mb-1.5 text-xs font-semibold text-accent">{s.tag}</div>
|
||||||
</span>
|
)}
|
||||||
</li>
|
{s.changes.length ? (
|
||||||
))}
|
<ul className="space-y-1.5">
|
||||||
</ul>
|
{s.changes.map((line, i) => (
|
||||||
) : (
|
<li key={i} className="flex gap-2 text-sm text-text">
|
||||||
<div className="text-sm text-faint">No release notes.</div>
|
<span className="text-faint">•</span>
|
||||||
)}
|
<span className="min-w-0 break-words">
|
||||||
|
<ChangelogLine text={line} />
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
) : (
|
||||||
|
<div className="text-sm text-faint">No release notes.</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -386,7 +414,6 @@ export function UpdateCheck() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
import { Icon } from '../../lib/icons'
|
||||||
|
import { GridEditStrip, TempoControls, TempoFold } from '../GridControls'
|
||||||
|
import { HotcueBar } from '../HotcueBar'
|
||||||
|
import { LoopControls } from '../LoopControls'
|
||||||
|
import { MemoryCueStrip } from '../MemoryCueStrip'
|
||||||
|
import { ModeSwitch } from '../ModeSwitch'
|
||||||
|
import type { Deck } from './useDeck'
|
||||||
|
|
||||||
|
const DIVIDER = <span aria-hidden className="h-7 w-px shrink-0 bg-line" />
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The deck's controls row: transport · loop/jump · pads or grid · tempo.
|
||||||
|
*
|
||||||
|
* A container, so the row gives way in stages as it narrows instead of the
|
||||||
|
* pads sliding under the tempo group: the pads drop their names first (each pad
|
||||||
|
* queries its own width, see HotcueBar), then below 77rem the tempo group folds
|
||||||
|
* into one BPM button. That is the row's measured width just before the pad
|
||||||
|
* bank would hit its minimum (with a lockable grid's extra Lock button, and the
|
||||||
|
* Hot / Mem toggle's ~3rem with its gap), so move it with the controls.
|
||||||
|
*
|
||||||
|
* `stacked` (beside the mixer, in performance mode) puts the pads — or the grid
|
||||||
|
* or memory strip — on a second row with the two mode switches, and folds the
|
||||||
|
* tempo group below 44rem (measured in the app: transport + loops + the tempo
|
||||||
|
* group need ~42rem).
|
||||||
|
*/
|
||||||
|
export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?: boolean }) {
|
||||||
|
const {
|
||||||
|
caps,
|
||||||
|
track,
|
||||||
|
toggle,
|
||||||
|
ready,
|
||||||
|
previewing,
|
||||||
|
playing,
|
||||||
|
onCuePress,
|
||||||
|
onCueRelease,
|
||||||
|
cueHeld,
|
||||||
|
loopMode,
|
||||||
|
setLoopMode,
|
||||||
|
grid,
|
||||||
|
beatSize,
|
||||||
|
stepSize,
|
||||||
|
loopActive,
|
||||||
|
activeBeats,
|
||||||
|
toggleSizeLoop,
|
||||||
|
loopRegion,
|
||||||
|
loopInPoint,
|
||||||
|
loopIn,
|
||||||
|
loopOut,
|
||||||
|
toggleLoop,
|
||||||
|
moveOrJump,
|
||||||
|
gridMode,
|
||||||
|
setGridMode,
|
||||||
|
bankMode,
|
||||||
|
setBankMode,
|
||||||
|
setPadMenu,
|
||||||
|
setMemoryMenu,
|
||||||
|
setRenamingSlot,
|
||||||
|
setRenamingMemory,
|
||||||
|
activeMarkerIndex,
|
||||||
|
markerCount,
|
||||||
|
activeMarker,
|
||||||
|
atMarker,
|
||||||
|
beforeFirstMarker,
|
||||||
|
originalGridRef,
|
||||||
|
prevMarker,
|
||||||
|
nextMarker,
|
||||||
|
nudgeGrid,
|
||||||
|
nudgeGridBeats,
|
||||||
|
addMarkerHere,
|
||||||
|
deleteMarkerHere,
|
||||||
|
deleteGrid,
|
||||||
|
resetGrid,
|
||||||
|
showMemory,
|
||||||
|
cueData,
|
||||||
|
cuePoint,
|
||||||
|
callMemoryCue,
|
||||||
|
addMemoryCue,
|
||||||
|
memoryAddRefusal,
|
||||||
|
renamingMemory,
|
||||||
|
renameMemoryCue,
|
||||||
|
slotCount,
|
||||||
|
slotLabel,
|
||||||
|
selectedSlot,
|
||||||
|
setSelectedSlot,
|
||||||
|
onSlotPress,
|
||||||
|
onSlotRelease,
|
||||||
|
hotcueAt,
|
||||||
|
renamingSlot,
|
||||||
|
renameSlot,
|
||||||
|
tempoProps,
|
||||||
|
channel,
|
||||||
|
} = deck
|
||||||
|
// On-screen MIDI learning (lib/midi): controls carry their action.
|
||||||
|
const midi = `deck.${channel}`
|
||||||
|
const transport = (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
onClick={toggle}
|
||||||
|
data-midi-action={`${midi}.play`}
|
||||||
|
disabled={!ready}
|
||||||
|
className={
|
||||||
|
'flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 disabled:cursor-not-allowed disabled:opacity-40 ' +
|
||||||
|
(previewing
|
||||||
|
? 'bg-gradient-to-b from-white to-gold text-ink-950 shadow-[0_0_0_4px_rgb(255_200_97/0.22),0_8px_24px_-4px_var(--color-gold)]'
|
||||||
|
: playing
|
||||||
|
? 'btn-primary shadow-[0_0_0_4px_color-mix(in_oklab,var(--color-accent)_22%,transparent),0_8px_24px_-4px_var(--color-accent)]'
|
||||||
|
: 'btn-glass text-text')
|
||||||
|
}
|
||||||
|
title={playing ? 'Pause (Space)' : 'Play (Space)'}
|
||||||
|
>
|
||||||
|
<Icon name={playing ? 'pause' : 'play'} size={16} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
data-midi-action={`${midi}.cue`}
|
||||||
|
onPointerDown={(e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.currentTarget.setPointerCapture(e.pointerId)
|
||||||
|
onCuePress()
|
||||||
|
}}
|
||||||
|
onPointerUp={onCueRelease}
|
||||||
|
onPointerCancel={onCueRelease}
|
||||||
|
disabled={!ready}
|
||||||
|
aria-pressed={cueHeld}
|
||||||
|
className={`flex h-10 w-14 shrink-0 items-center justify-center rounded-xl font-mono text-[13px] font-semibold tracking-wider transition-[background-color,box-shadow,transform,color] duration-75 disabled:cursor-not-allowed disabled:opacity-40 ${
|
||||||
|
cueHeld
|
||||||
|
? // Held: lit like a pressed controller button — brighter fill,
|
||||||
|
// solid gold rim, a glow, and a slight press-in.
|
||||||
|
'scale-[0.96] bg-gold/35 text-[#fff1cc] shadow-[inset_0_1px_0_rgb(255_255_255/0.3),inset_0_0_0_1px_rgb(255_200_97/0.9),0_0_20px_-2px_rgb(255_200_97/0.75)]'
|
||||||
|
: 'bg-gold/10 text-gold shadow-[inset_0_1px_0_rgb(255_255_255/0.12),inset_0_0_0_1px_rgb(255_200_97/0.4)] hover:bg-gold/15'
|
||||||
|
}`}
|
||||||
|
title="Cue — set the cue point (paused), hold to preview from it, or jump back to it (playing) (C)"
|
||||||
|
>
|
||||||
|
CUE
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
const loopControls = (
|
||||||
|
<LoopControls
|
||||||
|
midi={midi}
|
||||||
|
mode={loopMode}
|
||||||
|
onMode={setLoopMode}
|
||||||
|
hasGrid={grid != null}
|
||||||
|
ready={ready}
|
||||||
|
size={beatSize}
|
||||||
|
onSmaller={() => stepSize(-1)}
|
||||||
|
onBigger={() => stepSize(1)}
|
||||||
|
loopActive={loopActive}
|
||||||
|
sizeLit={loopActive && activeBeats === beatSize}
|
||||||
|
onToggleSize={toggleSizeLoop}
|
||||||
|
canToggle={loopRegion != null}
|
||||||
|
inArmed={loopInPoint != null}
|
||||||
|
manualSet={loopRegion != null && activeBeats == null}
|
||||||
|
onLoopIn={loopIn}
|
||||||
|
onLoopOut={loopOut}
|
||||||
|
onToggleLoop={toggleLoop}
|
||||||
|
onMove={moveOrJump}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
const bankSwitch = caps.cues.memory_cues && !gridMode && (
|
||||||
|
<ModeSwitch
|
||||||
|
label="Cue bank"
|
||||||
|
value={bankMode}
|
||||||
|
options={[
|
||||||
|
{ value: 'hot', text: 'HOT', title: 'Hot cues: the pads' },
|
||||||
|
{ value: 'memory', text: 'MEM', title: 'Memory cues: call one to make it the CUE point' },
|
||||||
|
]}
|
||||||
|
onChange={(m) => {
|
||||||
|
setBankMode(m)
|
||||||
|
setPadMenu(null)
|
||||||
|
setMemoryMenu(null)
|
||||||
|
setRenamingSlot(null)
|
||||||
|
setRenamingMemory(null)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
const strip = gridMode ? (
|
||||||
|
<GridEditStrip
|
||||||
|
markerIndex={activeMarkerIndex}
|
||||||
|
markerCount={markerCount}
|
||||||
|
markerStart={activeMarker?.start ?? null}
|
||||||
|
atMarker={atMarker}
|
||||||
|
beforeFirst={beforeFirstMarker}
|
||||||
|
canReset={originalGridRef.current != null}
|
||||||
|
onPrevMarker={prevMarker}
|
||||||
|
onNextMarker={nextMarker}
|
||||||
|
onNudgeMarker={nudgeGrid}
|
||||||
|
onNudgeMarkerBeats={nudgeGridBeats}
|
||||||
|
onAddMarker={addMarkerHere}
|
||||||
|
onDeleteMarker={deleteMarkerHere}
|
||||||
|
onDeleteGrid={deleteGrid}
|
||||||
|
onReset={resetGrid}
|
||||||
|
/>
|
||||||
|
) : showMemory ? (
|
||||||
|
<MemoryCueStrip
|
||||||
|
cues={cueData?.cues ?? []}
|
||||||
|
cuePoint={cuePoint}
|
||||||
|
onCall={callMemoryCue}
|
||||||
|
onMenu={(cue, x, y) => setMemoryMenu({ cue, x, y })}
|
||||||
|
onAdd={() => void addMemoryCue()}
|
||||||
|
addRefusal={memoryAddRefusal}
|
||||||
|
renamingId={renamingMemory}
|
||||||
|
onRenameCommit={renameMemoryCue}
|
||||||
|
onRenameCancel={() => setRenamingMemory(null)}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<HotcueBar
|
||||||
|
midi={midi}
|
||||||
|
cues={cueData?.cues ?? []}
|
||||||
|
slotCount={slotCount}
|
||||||
|
slotLabel={slotLabel}
|
||||||
|
selectedSlot={selectedSlot}
|
||||||
|
onSlotPress={onSlotPress}
|
||||||
|
onSlotRelease={onSlotRelease}
|
||||||
|
onSlotMenu={(slot, x, y) => {
|
||||||
|
setSelectedSlot(slot)
|
||||||
|
if (hotcueAt(slot)) setPadMenu({ slot, x, y })
|
||||||
|
}}
|
||||||
|
renamingSlot={renamingSlot}
|
||||||
|
onRenameCommit={renameSlot}
|
||||||
|
onRenameCancel={() => setRenamingSlot(null)}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
const modeSwitch = (
|
||||||
|
<ModeSwitch
|
||||||
|
label="Deck mode"
|
||||||
|
value={gridMode ? 'grid' : 'cues'}
|
||||||
|
options={[
|
||||||
|
{ value: 'cues', text: 'CUES', title: 'Cues: the hotcue pads or memory cues' },
|
||||||
|
{ value: 'grid', text: 'GRID', title: 'Edit the beatgrid: markers, phase, reset' },
|
||||||
|
]}
|
||||||
|
disabled={!track}
|
||||||
|
onChange={(m) => {
|
||||||
|
setGridMode(m === 'grid')
|
||||||
|
setPadMenu(null)
|
||||||
|
setRenamingSlot(null)
|
||||||
|
setMemoryMenu(null)
|
||||||
|
setRenamingMemory(null)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
|
||||||
|
if (stacked) {
|
||||||
|
return (
|
||||||
|
<div className="@container flex min-w-0 flex-1 flex-col gap-2">
|
||||||
|
<div className="flex h-11 shrink-0 items-center gap-3">
|
||||||
|
{transport}
|
||||||
|
{DIVIDER}
|
||||||
|
{loopControls}
|
||||||
|
<span className="flex-1" />
|
||||||
|
<TempoControls {...tempoProps} className="@max-[44rem]:hidden" />
|
||||||
|
<TempoFold locked={tempoProps.locked} className="hidden @max-[44rem]:flex">
|
||||||
|
<TempoControls {...tempoProps} />
|
||||||
|
</TempoFold>
|
||||||
|
</div>
|
||||||
|
<div className="flex h-11 shrink-0 items-center gap-2">
|
||||||
|
{modeSwitch}
|
||||||
|
{bankSwitch}
|
||||||
|
{strip}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="@container flex h-11 shrink-0 items-center gap-3">
|
||||||
|
{transport}
|
||||||
|
{DIVIDER}
|
||||||
|
{loopControls}
|
||||||
|
{DIVIDER}
|
||||||
|
{bankSwitch}
|
||||||
|
{strip}
|
||||||
|
{DIVIDER}
|
||||||
|
{modeSwitch}
|
||||||
|
<TempoControls {...tempoProps} className="@max-[77rem]:hidden" />
|
||||||
|
<TempoFold locked={tempoProps.locked} className="hidden @max-[77rem]:flex">
|
||||||
|
<TempoControls {...tempoProps} />
|
||||||
|
</TempoFold>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
import { useState, type ReactNode } from 'react'
|
||||||
|
import { api } from '../../api'
|
||||||
|
import { keyColor } from '../../lib/format'
|
||||||
|
import { Icon } from '../../lib/icons'
|
||||||
|
import { readOnlyNotice, readOnlyShort } from '../../lib/platformCopy'
|
||||||
|
import { useAppSetting } from '../AppSettings'
|
||||||
|
import { BpmReadout } from '../GridControls'
|
||||||
|
import type { Deck } from './useDeck'
|
||||||
|
|
||||||
|
/** 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.
|
||||||
|
* Before the track (performance mode's lead-in) it counts up to it: −00:01.5. */
|
||||||
|
function fmtTime(secs: number, places: number): string {
|
||||||
|
if (!isFinite(secs)) secs = 0
|
||||||
|
if (secs < 0) return `−${fmtTime(-secs, places)}`
|
||||||
|
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}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The deck's header: the track, its readouts, the analysis actions — and
|
||||||
|
* `actions`, anything the layout adds after them. `compact` (half-width, in
|
||||||
|
* performance mode) tightens the readouts and drops the action buttons'
|
||||||
|
* words; `badge` leads the row (the deck's letter). */
|
||||||
|
export function DeckHeader({
|
||||||
|
deck,
|
||||||
|
actions,
|
||||||
|
compact = false,
|
||||||
|
badge,
|
||||||
|
}: {
|
||||||
|
deck: Deck
|
||||||
|
actions?: ReactNode
|
||||||
|
compact?: boolean
|
||||||
|
badge?: ReactNode
|
||||||
|
}) {
|
||||||
|
const {
|
||||||
|
caps,
|
||||||
|
track,
|
||||||
|
origin,
|
||||||
|
subtitle,
|
||||||
|
setInfoOpen,
|
||||||
|
current,
|
||||||
|
duration,
|
||||||
|
activeMarker,
|
||||||
|
canEditGrid,
|
||||||
|
commitBpm,
|
||||||
|
gridAnchorRef,
|
||||||
|
playheadNow,
|
||||||
|
bpmEntryRequest,
|
||||||
|
snap,
|
||||||
|
setSnap,
|
||||||
|
runAnalyzeGrid,
|
||||||
|
gridBusy,
|
||||||
|
openAutoHotcues,
|
||||||
|
canAutoCue,
|
||||||
|
} = deck
|
||||||
|
const timeDecimals = useAppSetting('timeReadoutDecimals')
|
||||||
|
const cell = `flex flex-col justify-center gap-px ${compact ? 'px-2.5' : 'px-4'}`
|
||||||
|
const action = `btn-glass flex h-9 shrink-0 items-center justify-center gap-2 rounded-full text-[13px] font-medium disabled:opacity-40 ${
|
||||||
|
compact ? 'w-9' : 'px-3.5'
|
||||||
|
}`
|
||||||
|
return (
|
||||||
|
<div className={`flex h-12 min-w-0 shrink-0 items-center ${compact ? 'gap-2' : 'gap-3'}`}>
|
||||||
|
{badge}
|
||||||
|
<CoverThumb
|
||||||
|
trackId={track && origin === 'collection' ? track.id : null}
|
||||||
|
onOpen={track ? () => setInfoOpen(true) : undefined}
|
||||||
|
/>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
{track ? (
|
||||||
|
<>
|
||||||
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
|
<span
|
||||||
|
className={`truncate font-semibold tracking-tight text-text ${compact ? 'text-[15px]' : 'text-[17px]'}`}
|
||||||
|
title={track.title ?? ''}
|
||||||
|
>
|
||||||
|
{track.title ?? 'Untitled'}
|
||||||
|
</span>
|
||||||
|
{/* The deck stays usable for listening on a read-only library,
|
||||||
|
so say which it is rather than leaving the edit controls
|
||||||
|
looking live. The controls report the reason when pressed. */}
|
||||||
|
{readOnlyShort(caps) && (
|
||||||
|
<span
|
||||||
|
className="shrink-0 rounded-md bg-ink-800 px-1.5 py-0.5 text-[10px] uppercase tracking-wider text-muted"
|
||||||
|
title={readOnlyNotice(caps) ?? ''}
|
||||||
|
>
|
||||||
|
{readOnlyShort(caps)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className={`truncate text-muted ${compact ? 'text-[12px]' : 'text-[13px]'}`} title={subtitle}>
|
||||||
|
{subtitle}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="text-xs uppercase tracking-wider text-faint">No track loaded</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="well flex h-11 shrink-0 items-stretch rounded-xl">
|
||||||
|
<div className={cell}>
|
||||||
|
<span className="text-[10px] tracking-[0.08em] text-faint">ELAPSED</span>
|
||||||
|
<span className={`font-mono font-medium ${compact ? 'text-[15px]' : 'text-[17px]'}`}>{fmtTime(current, timeDecimals)}</span>
|
||||||
|
</div>
|
||||||
|
<span aria-hidden className="my-2 w-px bg-line" />
|
||||||
|
<div className={cell}>
|
||||||
|
<span className="text-[10px] tracking-[0.08em] text-faint">REMAIN</span>
|
||||||
|
<span className={`font-mono font-medium ${compact ? 'text-[15px]' : 'text-[17px]'}`}>−{fmtTime(Math.max(0, duration - Math.max(0, current)), timeDecimals)}</span>
|
||||||
|
</div>
|
||||||
|
<span aria-hidden className="my-2 w-px bg-line" />
|
||||||
|
<div className={cell}>
|
||||||
|
<span className="text-[10px] tracking-[0.08em] text-faint">KEY</span>
|
||||||
|
<span
|
||||||
|
className={`font-mono font-semibold ${compact ? 'text-[15px]' : 'text-[17px]'}`}
|
||||||
|
style={{ color: keyColor(track?.key_wheel ?? null) }}
|
||||||
|
>
|
||||||
|
{track?.key || '—'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span aria-hidden className="my-2 w-px bg-line" />
|
||||||
|
<BpmReadout
|
||||||
|
bpm={activeMarker?.bpm ?? null}
|
||||||
|
editable={canEditGrid}
|
||||||
|
onSetBpm={(bpm) => commitBpm(bpm, gridAnchorRef.current ?? playheadNow())}
|
||||||
|
onClose={() => (gridAnchorRef.current = null)}
|
||||||
|
openRequest={bpmEntryRequest}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => setSnap((v) => !v)}
|
||||||
|
aria-pressed={snap}
|
||||||
|
title="Snap cues and loops to the nearest beat"
|
||||||
|
className={`h-9 shrink-0 rounded-full px-3.5 text-xs font-semibold tracking-[0.08em] ${
|
||||||
|
snap ? 'is-selected text-text' : 'btn-glass text-muted'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
SNAP
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={runAnalyzeGrid}
|
||||||
|
disabled={!track || gridBusy}
|
||||||
|
title={canEditGrid
|
||||||
|
? 'Detect BPM and first beat, then set the grid + hotcue 1 (fix the octave with ÷2 / ×2); measure loudness'
|
||||||
|
: 'Measure loudness (this track’s grid cannot be edited here)'}
|
||||||
|
aria-label="Analyze"
|
||||||
|
className={action}
|
||||||
|
>
|
||||||
|
<Icon name="wave" size={16} />
|
||||||
|
{!compact && (gridBusy ? 'Analyzing…' : 'Analyze')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={openAutoHotcues}
|
||||||
|
disabled={!track || !canAutoCue}
|
||||||
|
title={
|
||||||
|
canAutoCue
|
||||||
|
? "Place hotcues on the track's drops, breakdowns and other sections"
|
||||||
|
: 'Set a beatgrid first'
|
||||||
|
}
|
||||||
|
aria-label="Auto hotcues"
|
||||||
|
className={action}
|
||||||
|
>
|
||||||
|
<Icon name="sparkle" size={16} />
|
||||||
|
{!compact && 'Auto hotcues'}
|
||||||
|
</button>
|
||||||
|
{actions}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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, onOpen }: { trackId: string | null; onOpen?: () => void }) {
|
||||||
|
const [failed, setFailed] = useState<string | null>(null)
|
||||||
|
const showArt = trackId != null && failed !== trackId
|
||||||
|
return (
|
||||||
|
<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 && (
|
||||||
|
<img
|
||||||
|
key={trackId}
|
||||||
|
src={api.artUrl(trackId)}
|
||||||
|
alt=""
|
||||||
|
className="absolute inset-0 h-full w-full object-cover"
|
||||||
|
onError={() => setFailed(trackId)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { api } from '../../api'
|
||||||
|
import { CapabilitiesContext } from '../../lib/capabilities'
|
||||||
|
import { AutoCueDialog } from '../AutoCueDialog'
|
||||||
|
import { ContextMenu } from '../ContextMenu'
|
||||||
|
import { TrackInfoDialog } from '../TrackInfoDialog'
|
||||||
|
import type { Deck } from './useDeck'
|
||||||
|
|
||||||
|
/** The deck's menus and dialogs (all portalled, so where this renders does not
|
||||||
|
* matter). Under the deck's OWN capabilities: the track-info dialog reads
|
||||||
|
* them from context. */
|
||||||
|
export function DeckOverlays({ deck }: { deck: Deck }) {
|
||||||
|
const {
|
||||||
|
caps,
|
||||||
|
track,
|
||||||
|
origin,
|
||||||
|
onError,
|
||||||
|
onEditTags,
|
||||||
|
memoryMenu,
|
||||||
|
setMemoryMenu,
|
||||||
|
memoryMenuItems,
|
||||||
|
padMenu,
|
||||||
|
setPadMenu,
|
||||||
|
padMenuItems,
|
||||||
|
infoOpen,
|
||||||
|
setInfoOpen,
|
||||||
|
autoOpen,
|
||||||
|
setAutoOpen,
|
||||||
|
slotCount,
|
||||||
|
slotLabel,
|
||||||
|
existingHotcues,
|
||||||
|
autoHotcuesDone,
|
||||||
|
} = deck
|
||||||
|
return (
|
||||||
|
<CapabilitiesContext.Provider value={caps}>
|
||||||
|
{memoryMenu && (
|
||||||
|
<ContextMenu
|
||||||
|
key={`m:${memoryMenu.cue.id}:${memoryMenu.x}:${memoryMenu.y}`}
|
||||||
|
x={memoryMenu.x}
|
||||||
|
y={memoryMenu.y}
|
||||||
|
items={memoryMenuItems(memoryMenu.cue)}
|
||||||
|
onClose={() => setMemoryMenu(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{padMenu && (
|
||||||
|
<ContextMenu
|
||||||
|
key={`${padMenu.slot}:${padMenu.x}:${padMenu.y}`}
|
||||||
|
x={padMenu.x}
|
||||||
|
y={padMenu.y}
|
||||||
|
items={padMenuItems(padMenu.slot)}
|
||||||
|
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}
|
||||||
|
slotCount={slotCount}
|
||||||
|
slotLabel={slotLabel}
|
||||||
|
existing={existingHotcues}
|
||||||
|
onClose={() => setAutoOpen(false)}
|
||||||
|
onDone={autoHotcuesDone}
|
||||||
|
onError={(msg) => onError?.(msg)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</CapabilitiesContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
import { useEffect, useRef } from 'react'
|
||||||
|
import { bendFor, PITCH_RANGES } from '../../lib/sync'
|
||||||
|
import { Fader } from '../mixer/Controls'
|
||||||
|
import type { Deck } from './useDeck'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
deck: Deck
|
||||||
|
/** This deck is the tempo master (the one SYNC follows). */
|
||||||
|
master: boolean
|
||||||
|
synced: boolean
|
||||||
|
/** Why SYNC cannot engage (no grid on a deck), else null. */
|
||||||
|
syncBlocked: string | null
|
||||||
|
onSync: () => void
|
||||||
|
onMaster: () => void
|
||||||
|
/** Moving the pitch fader — or bending — by hand takes the deck out of SYNC. */
|
||||||
|
onManualPitch: () => void
|
||||||
|
/** This deck's beats against the other deck's, in beats (-0.5..0.5); null
|
||||||
|
* when either has no grid or is not playing. Read every frame. */
|
||||||
|
phase: () => number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
const lit = 'is-selected text-text'
|
||||||
|
const unlit = 'btn-glass text-muted'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A deck's tempo row in performance mode (decided 2026-11-02): keylock, SYNC,
|
||||||
|
* MASTER, the phase meter, the pitch fader with its range, and the tempo as
|
||||||
|
* heard. The pitch fader is the deck's SPEED — the grid's BPM is still edited
|
||||||
|
* in the header and Grid mode.
|
||||||
|
*/
|
||||||
|
export function DeckTempo({ deck, master, synced, syncBlocked, onSync, onMaster, onManualPitch, phase }: Props) {
|
||||||
|
const { pitch, setPitch, pitchRange, changeRange, rate, setBend, keylock, setKeylock, keylockAvailable, activeMarker, track } = deck
|
||||||
|
const bpm = activeMarker ? activeMarker.bpm * rate : null
|
||||||
|
const pct = pitch * pitchRange * 100
|
||||||
|
const nextRange = PITCH_RANGES[(PITCH_RANGES.indexOf(pitchRange) + 1) % PITCH_RANGES.length]
|
||||||
|
return (
|
||||||
|
<div className="flex h-9 shrink-0 items-center gap-2">
|
||||||
|
<button
|
||||||
|
data-midi-action={`deck.${deck.channel}.keylock`}
|
||||||
|
onClick={() => setKeylock(!keylock)}
|
||||||
|
disabled={!keylockAvailable}
|
||||||
|
aria-pressed={keylock}
|
||||||
|
title={
|
||||||
|
keylockAvailable
|
||||||
|
? keylock
|
||||||
|
? 'Keylock on: a tempo change keeps the pitch'
|
||||||
|
: 'Keylock off: the pitch moves with the tempo, like a turntable'
|
||||||
|
: 'Keylock is unavailable (the time-stretcher did not load)'
|
||||||
|
}
|
||||||
|
className={`h-8 shrink-0 rounded-full px-3 text-[11px] font-semibold tracking-[0.08em] disabled:opacity-40 ${keylock ? lit : unlit}`}
|
||||||
|
>
|
||||||
|
KEY
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
data-midi-action={`deck.${deck.channel}.sync`}
|
||||||
|
onClick={onSync}
|
||||||
|
disabled={!track || (!synced && syncBlocked != null)}
|
||||||
|
aria-pressed={synced}
|
||||||
|
title={syncBlocked ?? (synced ? 'Synced: following the master’s tempo and beats — click to release' : 'Match the master’s tempo and line the beats up')}
|
||||||
|
className={`h-8 shrink-0 rounded-full px-3 text-[11px] font-semibold tracking-[0.08em] disabled:opacity-40 ${synced ? lit : unlit}`}
|
||||||
|
>
|
||||||
|
SYNC
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
data-midi-action={`deck.${deck.channel}.master`}
|
||||||
|
onClick={onMaster}
|
||||||
|
disabled={!track}
|
||||||
|
aria-pressed={master}
|
||||||
|
title={master ? 'Tempo master: a synced deck follows this one' : 'Make this deck the tempo master'}
|
||||||
|
className={`h-8 shrink-0 rounded-full px-3 text-[11px] font-semibold tracking-[0.08em] disabled:opacity-40 ${
|
||||||
|
master ? 'bg-gold/20 text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.6)]' : unlit
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
MASTER
|
||||||
|
</button>
|
||||||
|
<PhaseMeter
|
||||||
|
phase={phase}
|
||||||
|
disabled={!track}
|
||||||
|
onBend={(b) => {
|
||||||
|
if (b !== 1) onManualPitch()
|
||||||
|
setBend(b)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Fader
|
||||||
|
midi={`deck.${deck.channel}.pitch`}
|
||||||
|
orientation="horizontal"
|
||||||
|
value={pitch}
|
||||||
|
min={-1}
|
||||||
|
max={1}
|
||||||
|
defaultValue={0}
|
||||||
|
onChange={(v) => {
|
||||||
|
setPitch(Math.abs(v) < 0.01 ? 0 : v)
|
||||||
|
onManualPitch()
|
||||||
|
}}
|
||||||
|
label="Pitch"
|
||||||
|
describe={() => `Pitch ${fmtPct(pct)} (range ±${Math.round(pitchRange * 100)}%) — double-click to reset`}
|
||||||
|
className="min-w-16 flex-1"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={() => changeRange(nextRange)}
|
||||||
|
title={`Pitch range ±${Math.round(pitchRange * 100)}% — click for ±${Math.round(nextRange * 100)}%`}
|
||||||
|
className="btn-glass h-8 w-11 shrink-0 rounded-full font-mono text-[11px] text-muted"
|
||||||
|
>
|
||||||
|
±{Math.round(pitchRange * 100)}
|
||||||
|
</button>
|
||||||
|
<div className="well flex h-8 w-[6.5rem] shrink-0 flex-col items-end justify-center rounded-lg px-2 leading-none">
|
||||||
|
<span className="font-mono text-[13px] font-medium text-text">{bpm ? bpm.toFixed(2) : '—'}</span>
|
||||||
|
<span className={`font-mono text-[10px] ${pct === 0 ? 'text-faint' : 'text-muted'}`}>{fmtPct(pct)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fmtPct = (p: number) => `${p > 0 ? '+' : p < 0 ? '−' : '±'}${Math.abs(p).toFixed(2)}%`
|
||||||
|
|
||||||
|
/** Where this deck's beats fall against the other deck's: centre = in phase,
|
||||||
|
* right = ahead. Drawn every frame straight to the DOM. DRAG it to bend the
|
||||||
|
* deck's speed — right faster, left slower — and let go to spring back, the
|
||||||
|
* way a DJ nudges a platter to bring the beats together. */
|
||||||
|
function PhaseMeter({
|
||||||
|
phase,
|
||||||
|
onBend,
|
||||||
|
disabled,
|
||||||
|
}: {
|
||||||
|
phase: () => number | null
|
||||||
|
onBend: (bend: number) => void
|
||||||
|
disabled: boolean
|
||||||
|
}) {
|
||||||
|
const markRef = useRef<HTMLSpanElement>(null)
|
||||||
|
const dragX = useRef<number | null>(null)
|
||||||
|
const release = () => {
|
||||||
|
if (dragX.current == null) return
|
||||||
|
dragX.current = null
|
||||||
|
onBend(1)
|
||||||
|
}
|
||||||
|
const read = useRef(phase)
|
||||||
|
read.current = phase
|
||||||
|
useEffect(() => {
|
||||||
|
let raf = 0
|
||||||
|
const tick = () => {
|
||||||
|
const el = markRef.current
|
||||||
|
const p = read.current()
|
||||||
|
if (el) {
|
||||||
|
el.style.opacity = p == null ? '0' : '1'
|
||||||
|
if (p != null) {
|
||||||
|
el.style.left = `${(p + 0.5) * 100}%`
|
||||||
|
el.style.background = Math.abs(p) < 0.03 ? 'var(--color-mint)' : 'var(--color-gold)'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raf = requestAnimationFrame(tick)
|
||||||
|
}
|
||||||
|
raf = requestAnimationFrame(tick)
|
||||||
|
return () => cancelAnimationFrame(raf)
|
||||||
|
}, [])
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
onPointerDown={(e) => {
|
||||||
|
if (disabled || e.button !== 0) return
|
||||||
|
e.preventDefault()
|
||||||
|
e.currentTarget.setPointerCapture(e.pointerId)
|
||||||
|
dragX.current = e.clientX
|
||||||
|
}}
|
||||||
|
onPointerMove={(e) => dragX.current != null && onBend(bendFor(e.clientX - dragX.current, e.shiftKey))}
|
||||||
|
onPointerUp={release}
|
||||||
|
onPointerCancel={release}
|
||||||
|
onLostPointerCapture={release}
|
||||||
|
className={`well relative h-3 w-20 shrink-0 touch-none overflow-hidden rounded-full ${disabled ? '' : 'cursor-ew-resize'}`}
|
||||||
|
title="Phase: where this deck's beats fall against the other deck's (centre = together). Drag to bend the speed — right faster, left slower (Shift: finer)"
|
||||||
|
>
|
||||||
|
<span aria-hidden className="absolute inset-y-0.5 left-1/2 w-px bg-white/25" />
|
||||||
|
<span ref={markRef} className="absolute inset-y-0 w-1.5 -translate-x-1/2 rounded-full opacity-0" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { MainWaveform } from '../MainWaveform'
|
||||||
|
import { OverviewWaveform } from '../OverviewWaveform'
|
||||||
|
import type { Deck } from './useDeck'
|
||||||
|
|
||||||
|
/** The main view's zoom and raw/bars toggle — shared by every deck's lane
|
||||||
|
* (so beats line up between them), owned by the deck area. */
|
||||||
|
export interface DeckView {
|
||||||
|
secPerView: number
|
||||||
|
setSecPerView: (sec: number) => void
|
||||||
|
rawWave: boolean
|
||||||
|
setRawWave: (raw: boolean) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The scrolling main waveform, in its well — or what stands in for it: no
|
||||||
|
* track, a load error, the analysis running. */
|
||||||
|
export function DeckMainWave({ deck, view, empty = 'Load a track to prep it' }: { deck: Deck; view: DeckView; empty?: string }) {
|
||||||
|
const {
|
||||||
|
track,
|
||||||
|
waveStatus,
|
||||||
|
showWaves,
|
||||||
|
cols,
|
||||||
|
raw,
|
||||||
|
current,
|
||||||
|
duration,
|
||||||
|
cueData,
|
||||||
|
cuePoint,
|
||||||
|
grid,
|
||||||
|
activeMarkerIndex,
|
||||||
|
gridMode,
|
||||||
|
activeLoop,
|
||||||
|
loopActive,
|
||||||
|
loopRegion,
|
||||||
|
loopInPoint,
|
||||||
|
seekManual,
|
||||||
|
onScratchStart,
|
||||||
|
onScratchMove,
|
||||||
|
onScratchEnd,
|
||||||
|
lanes,
|
||||||
|
toggleStem,
|
||||||
|
} = deck
|
||||||
|
if (!track) {
|
||||||
|
return (
|
||||||
|
<div className="well flex min-h-0 flex-1 items-center justify-center rounded-2xl text-xs text-faint">
|
||||||
|
{empty}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (waveStatus === 'error') {
|
||||||
|
return (
|
||||||
|
<div className="well flex min-h-0 flex-1 items-center justify-center rounded-2xl text-xs text-pink">
|
||||||
|
Could not load audio — file may be missing or an unsupported format.
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="well relative min-h-0 flex-1 overflow-hidden rounded-2xl">
|
||||||
|
{showWaves && cols ? (
|
||||||
|
<MainWaveform
|
||||||
|
cols={cols}
|
||||||
|
raw={raw}
|
||||||
|
rawMode={view.rawWave}
|
||||||
|
onRawModeChange={view.setRawWave}
|
||||||
|
currentTime={current}
|
||||||
|
duration={duration}
|
||||||
|
cues={cueData?.cues ?? []}
|
||||||
|
cuePoint={cuePoint}
|
||||||
|
grid={grid}
|
||||||
|
activeMarker={activeMarkerIndex}
|
||||||
|
emphasizeGrid={gridMode}
|
||||||
|
loop={activeLoop}
|
||||||
|
idleLoop={!loopActive ? loopRegion : null}
|
||||||
|
loopIn={loopInPoint}
|
||||||
|
secPerView={view.secPerView}
|
||||||
|
onZoomChange={view.setSecPerView}
|
||||||
|
onSeek={seekManual}
|
||||||
|
onScratchStart={onScratchStart}
|
||||||
|
onScratchMove={onScratchMove}
|
||||||
|
onScratchEnd={onScratchEnd}
|
||||||
|
lanes={lanes}
|
||||||
|
onStemToggle={toggleStem}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="flex h-full items-center justify-center text-xs text-faint">
|
||||||
|
Analysing waveform…
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The whole-track overview, framing the main view's range. Nothing without a
|
||||||
|
* playable track (the main well says why). */
|
||||||
|
export function DeckOverview({ deck, view }: { deck: Deck; view: DeckView }) {
|
||||||
|
const { track, waveStatus, showWaves, cols, current, duration, cueData, cuePoint, activeLoop, seekManual } = deck
|
||||||
|
if (!track || waveStatus === 'error') return null
|
||||||
|
return (
|
||||||
|
<div className="well h-7 shrink-0 overflow-hidden rounded-[9px]">
|
||||||
|
{showWaves && cols && (
|
||||||
|
<OverviewWaveform
|
||||||
|
cols={cols}
|
||||||
|
currentTime={current}
|
||||||
|
duration={duration}
|
||||||
|
cues={cueData?.cues ?? []}
|
||||||
|
cuePoint={cuePoint}
|
||||||
|
loop={activeLoop}
|
||||||
|
secPerView={view.secPerView}
|
||||||
|
onSeek={seekManual}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { Icon } from '../../lib/icons'
|
||||||
|
|
||||||
|
/** Performance mode on / off — at the right of the track list's toolbar
|
||||||
|
* (decided 2026-11-03), lit while on. P does the same. */
|
||||||
|
export function PerformanceButton({ on, onToggle }: { on: boolean; onToggle: () => void }) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
data-midi-action="app.performance"
|
||||||
|
onClick={onToggle}
|
||||||
|
aria-pressed={on}
|
||||||
|
aria-label="Performance mode"
|
||||||
|
title={on ? 'Leave performance mode (P)' : 'Performance mode — a second deck and a mixer, to try transitions (P)'}
|
||||||
|
className={`flex shrink-0 items-center gap-2 rounded-full px-3.5 py-1.5 text-sm font-medium ${
|
||||||
|
on ? 'is-selected text-text' : 'btn-glass text-text'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Icon name="decks" size={16} />
|
||||||
|
Performance
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,177 @@
|
|||||||
|
// The mixer's controls: a rotary knob and a fader. Mouse-driven — drag (Shift
|
||||||
|
// for fine), scroll, double-click to reset — and NOT focusable, so the deck's
|
||||||
|
// keys (←/→, Space) never land on them by accident.
|
||||||
|
|
||||||
|
import { useRef, type PointerEvent, type WheelEvent } from 'react'
|
||||||
|
|
||||||
|
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))
|
||||||
|
|
||||||
|
/** Pixels of drag for the whole travel (Shift: five times finer). */
|
||||||
|
const DRAG_PX = 150
|
||||||
|
|
||||||
|
interface KnobProps {
|
||||||
|
value: number
|
||||||
|
min: number
|
||||||
|
max: number
|
||||||
|
/** Reset value (double-click); also where the arc starts on a bipolar knob. */
|
||||||
|
defaultValue: number
|
||||||
|
/** The arc grows from the centre (EQ, colour) rather than from the left. */
|
||||||
|
bipolar?: boolean
|
||||||
|
onChange: (v: number) => void
|
||||||
|
label: string
|
||||||
|
/** The tooltip, for the value it would show. */
|
||||||
|
describe: (v: number) => string
|
||||||
|
color?: string
|
||||||
|
size?: number
|
||||||
|
/** Its MIDI action, for on-screen learning (lib/midi). */
|
||||||
|
midi?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A point on the knob's circle at angle `deg` (0 = straight up). */
|
||||||
|
function polar(r: number, deg: number, c: number): [number, number] {
|
||||||
|
const rad = ((deg - 90) * Math.PI) / 180
|
||||||
|
return [c + r * Math.cos(rad), c + r * Math.sin(rad)]
|
||||||
|
}
|
||||||
|
|
||||||
|
function arc(r: number, from: number, to: number, c: number): string {
|
||||||
|
if (Math.abs(to - from) < 0.5) return ''
|
||||||
|
const [a, b] = from < to ? [from, to] : [to, from]
|
||||||
|
const [x1, y1] = polar(r, a, c)
|
||||||
|
const [x2, y2] = polar(r, b, c)
|
||||||
|
return `M ${x1} ${y1} A ${r} ${r} 0 ${b - a > 180 ? 1 : 0} 1 ${x2} ${y2}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Knob({
|
||||||
|
midi,
|
||||||
|
value,
|
||||||
|
min,
|
||||||
|
max,
|
||||||
|
defaultValue,
|
||||||
|
bipolar = false,
|
||||||
|
onChange,
|
||||||
|
label,
|
||||||
|
describe,
|
||||||
|
color = 'var(--color-accent)',
|
||||||
|
size = 26,
|
||||||
|
}: KnobProps) {
|
||||||
|
const drag = useRef<{ y: number; v: number } | null>(null)
|
||||||
|
const range = max - min
|
||||||
|
const angle = -135 + ((clamp(value, min, max) - min) / range) * 270
|
||||||
|
const start = bipolar ? -135 + ((defaultValue - min) / range) * 270 : -135
|
||||||
|
const c = size / 2
|
||||||
|
const stroke = size >= 36 ? 3.5 : 2.5
|
||||||
|
const r = c - stroke
|
||||||
|
const [px, py] = polar(r - stroke - 2, angle, c)
|
||||||
|
|
||||||
|
const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {
|
||||||
|
if (e.button !== 0) return
|
||||||
|
e.preventDefault()
|
||||||
|
e.currentTarget.setPointerCapture(e.pointerId)
|
||||||
|
drag.current = { y: e.clientY, v: value }
|
||||||
|
}
|
||||||
|
const onPointerMove = (e: PointerEvent<HTMLDivElement>) => {
|
||||||
|
const d = drag.current
|
||||||
|
if (!d) return
|
||||||
|
const px = e.shiftKey ? DRAG_PX * 5 : DRAG_PX
|
||||||
|
onChange(clamp(d.v + ((d.y - e.clientY) / px) * range, min, max))
|
||||||
|
}
|
||||||
|
const onWheel = (e: WheelEvent<HTMLDivElement>) => {
|
||||||
|
onChange(clamp(value - (e.deltaY / (e.shiftKey ? 2000 : 400)) * range, min, max))
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center gap-0.5" title={describe(value)} data-midi-action={midi}>
|
||||||
|
<div
|
||||||
|
role="slider"
|
||||||
|
aria-label={label}
|
||||||
|
aria-valuemin={min}
|
||||||
|
aria-valuemax={max}
|
||||||
|
aria-valuenow={value}
|
||||||
|
onPointerDown={onPointerDown}
|
||||||
|
onPointerMove={onPointerMove}
|
||||||
|
onPointerUp={() => (drag.current = null)}
|
||||||
|
onPointerCancel={() => (drag.current = null)}
|
||||||
|
onDoubleClick={() => onChange(defaultValue)}
|
||||||
|
onWheel={onWheel}
|
||||||
|
className="cursor-ns-resize touch-none select-none"
|
||||||
|
style={{ width: size, height: size }}
|
||||||
|
>
|
||||||
|
<svg width={size} height={size}>
|
||||||
|
<circle cx={c} cy={c} r={r} fill="rgb(0 0 0 / 0.36)" stroke="rgb(255 255 255 / 0.08)" />
|
||||||
|
<path d={arc(r, -135, 135, c)} fill="none" stroke="rgb(255 255 255 / 0.1)" strokeWidth={stroke} strokeLinecap="round" />
|
||||||
|
<path
|
||||||
|
d={arc(r, start, angle, c)}
|
||||||
|
fill="none"
|
||||||
|
stroke={color}
|
||||||
|
strokeWidth={stroke}
|
||||||
|
strokeLinecap="round"
|
||||||
|
style={{ filter: `drop-shadow(0 0 3px ${color})` }}
|
||||||
|
/>
|
||||||
|
<line x1={c} y1={c} x2={px} y2={py} stroke="var(--color-text)" strokeWidth={size >= 36 ? 2.5 : 2} strokeLinecap="round" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<span
|
||||||
|
className={`font-semibold uppercase leading-none tracking-[0.08em] text-faint ${size >= 36 ? 'text-[9.5px]' : 'text-[8.5px]'}`}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FaderProps {
|
||||||
|
value: number
|
||||||
|
min: number
|
||||||
|
max: number
|
||||||
|
defaultValue: number
|
||||||
|
onChange: (v: number) => void
|
||||||
|
orientation: 'vertical' | 'horizontal'
|
||||||
|
label: string
|
||||||
|
describe: (v: number) => string
|
||||||
|
className?: string
|
||||||
|
/** Its MIDI action, for on-screen learning (lib/midi). */
|
||||||
|
midi?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A fader: grab anywhere on it and the cap follows the pointer. */
|
||||||
|
export function Fader({ value, min, max, defaultValue, onChange, orientation, label, describe, className = '', midi }: FaderProps) {
|
||||||
|
const vertical = orientation === 'vertical'
|
||||||
|
const t = (clamp(value, min, max) - min) / (max - min)
|
||||||
|
const set = (e: PointerEvent<HTMLDivElement>) => {
|
||||||
|
const box = e.currentTarget.getBoundingClientRect()
|
||||||
|
const f = vertical ? 1 - (e.clientY - box.top) / box.height : (e.clientX - box.left) / box.width
|
||||||
|
onChange(min + clamp(f, 0, 1) * (max - min))
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="slider"
|
||||||
|
data-midi-action={midi}
|
||||||
|
aria-label={label}
|
||||||
|
aria-orientation={orientation}
|
||||||
|
aria-valuemin={min}
|
||||||
|
aria-valuemax={max}
|
||||||
|
aria-valuenow={value}
|
||||||
|
title={describe(value)}
|
||||||
|
onPointerDown={(e) => {
|
||||||
|
if (e.button !== 0) return
|
||||||
|
e.preventDefault()
|
||||||
|
e.currentTarget.setPointerCapture(e.pointerId)
|
||||||
|
set(e)
|
||||||
|
}}
|
||||||
|
onPointerMove={(e) => e.currentTarget.hasPointerCapture(e.pointerId) && set(e)}
|
||||||
|
onDoubleClick={() => onChange(defaultValue)}
|
||||||
|
className={`relative touch-none select-none ${vertical ? 'w-6 cursor-ns-resize' : 'h-6 cursor-ew-resize'} ${className}`}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={`well absolute rounded-full ${vertical ? 'inset-y-1.5 left-1/2 w-1.5 -translate-x-1/2' : 'inset-x-1.5 top-1/2 h-1.5 -translate-y-1/2'}`}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className={`btn-glass pointer-events-none absolute rounded-md ${
|
||||||
|
vertical ? 'left-0 h-3 w-6 -translate-y-1/2' : 'top-0 h-6 w-3 -translate-x-1/2'
|
||||||
|
}`}
|
||||||
|
style={vertical ? { top: `calc(0.375rem + ${(1 - t) * 100}% - ${(1 - t) * 0.75}rem)` } : { left: `calc(0.375rem + ${t * 100}% - ${t * 0.75}rem)` }}
|
||||||
|
>
|
||||||
|
<span className={`absolute bg-text/80 ${vertical ? 'inset-x-1 top-1/2 h-px' : 'inset-y-1 left-1/2 w-px'}`} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { xfadeGains } from '../../lib/audio/mixerMath'
|
||||||
|
import { useMixer } from '../../lib/audio/mixerState'
|
||||||
|
|
||||||
|
const W = 200
|
||||||
|
const H = 72
|
||||||
|
const PAD = 6
|
||||||
|
const STEPS = 120
|
||||||
|
|
||||||
|
/** The crossfader's two gain curves at `sharpness`: A falling left to right,
|
||||||
|
* B rising, over the whole travel, with where the crossfader is now. */
|
||||||
|
export function CrossfaderCurveGraph({ sharpness }: { sharpness: number }) {
|
||||||
|
const position = useMixer((m) => m.crossfader)
|
||||||
|
const x = (t: number) => PAD + t * (W - 2 * PAD)
|
||||||
|
const y = (g: number) => H - PAD - g * (H - 2 * PAD)
|
||||||
|
const line = (ch: 0 | 1) =>
|
||||||
|
Array.from({ length: STEPS + 1 }, (_, i) => {
|
||||||
|
const t = i / STEPS
|
||||||
|
const g = xfadeGains(t * 2 - 1, sharpness)[ch]
|
||||||
|
return `${i ? 'L' : 'M'}${x(t).toFixed(1)} ${y(g).toFixed(1)}`
|
||||||
|
}).join(' ')
|
||||||
|
const at = (position + 1) / 2
|
||||||
|
return (
|
||||||
|
<svg
|
||||||
|
width={W}
|
||||||
|
height={H}
|
||||||
|
viewBox={`0 0 ${W} ${H}`}
|
||||||
|
className="well shrink-0 rounded-lg"
|
||||||
|
role="img"
|
||||||
|
aria-label={`Crossfader curve, ${Math.round(sharpness * 100)}% sharp`}
|
||||||
|
>
|
||||||
|
{/* full level, the -3 dB line, the centre */}
|
||||||
|
<line x1={PAD} x2={W - PAD} y1={y(1)} y2={y(1)} stroke="rgb(255 255 255 / 0.08)" />
|
||||||
|
<line x1={PAD} x2={W - PAD} y1={y(Math.SQRT1_2)} y2={y(Math.SQRT1_2)} stroke="rgb(255 255 255 / 0.06)" strokeDasharray="2 3" />
|
||||||
|
<line x1={x(0.5)} x2={x(0.5)} y1={PAD} y2={H - PAD} stroke="rgb(255 255 255 / 0.08)" />
|
||||||
|
<path d={line(0)} fill="none" stroke="var(--color-accent)" strokeWidth={2} strokeLinejoin="round" />
|
||||||
|
<path d={line(1)} fill="none" stroke="var(--color-gold)" strokeWidth={2} strokeLinejoin="round" />
|
||||||
|
<line x1={x(at)} x2={x(at)} y1={PAD} y2={H - PAD} stroke="var(--color-text)" strokeOpacity={0.5} />
|
||||||
|
<text x={PAD + 2} y={H - PAD - 3} fontSize={9} fill="var(--color-accent)" fontWeight={600}>A</text>
|
||||||
|
<text x={W - PAD - 8} y={H - PAD - 3} fontSize={9} fill="var(--color-gold)" fontWeight={600}>B</text>
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
import { useEffect, useRef, useState, type RefObject } from 'react'
|
||||||
|
import { mixer } from '../../lib/audio/mixer'
|
||||||
|
import { delayBeatsAt, faderGain, filterSweep, eqGain, gainToDb, REVERB_GROWTH, sweepBeatsAt, TRIM_RANGE_DB, EQ_CUT_DB } from '../../lib/audio/mixerMath'
|
||||||
|
import {
|
||||||
|
FX_LABELS,
|
||||||
|
FX_SHORT,
|
||||||
|
FX_TYPES,
|
||||||
|
rangeFor,
|
||||||
|
setChannel,
|
||||||
|
setMixer,
|
||||||
|
useMixer,
|
||||||
|
type Channel,
|
||||||
|
type FxSettings,
|
||||||
|
type FxType,
|
||||||
|
} from '../../lib/audio/mixerState'
|
||||||
|
import { Icon } from '../../lib/icons'
|
||||||
|
import { ContextMenu } from '../ContextMenu'
|
||||||
|
import { Fader, Knob } from './Controls'
|
||||||
|
|
||||||
|
/** The meters' scale (dBFS). */
|
||||||
|
const METER_FLOOR = -48
|
||||||
|
const METER_TOP = 3
|
||||||
|
|
||||||
|
/** Knob sizes (px): as large as the column allows — the EQ block is two
|
||||||
|
* across, the FILTER knob beside it larger. */
|
||||||
|
const EQ_KNOB = 40
|
||||||
|
const FILTER_KNOB = 48
|
||||||
|
|
||||||
|
const fmtDb = (db: number, places = 1) =>
|
||||||
|
!isFinite(db) ? '−∞ dB' : `${db > 0 ? '+' : db < 0 ? '−' : ''}${Math.abs(db).toFixed(places)} dB`
|
||||||
|
|
||||||
|
/** The FILTER knob's tooltip: where the filter is, and what rides with it. */
|
||||||
|
function describeFx(fx: FxType, c: number, set: FxSettings): string {
|
||||||
|
if (Math.abs(c) < 0.02) return `Filter${fx === 'filter' ? '' : ` + ${FX_LABELS[fx]}`}: off (turn left or right)`
|
||||||
|
const s = filterSweep(c, rangeFor(fx, set))!
|
||||||
|
const hz = s.freq >= 1000 ? `${(s.freq / 1000).toFixed(1)} kHz` : `${Math.round(s.freq)} Hz`
|
||||||
|
const filter = `${s.type === 'lowpass' ? 'low-pass' : 'high-pass'} at ${hz}`
|
||||||
|
const a = `${Math.round(Math.abs(c) * 100)}%`
|
||||||
|
switch (fx) {
|
||||||
|
case 'filter':
|
||||||
|
return `Filter: ${filter} · resonance ${Math.round(set.filterResonance * 100)}%`
|
||||||
|
case 'reverb':
|
||||||
|
return `Reverb ${a} (${set.reverbSize}–${set.reverbSize * REVERB_GROWTH} s, longer as it opens) + ${filter}`
|
||||||
|
case 'delay':
|
||||||
|
return `Delay ${a} (${beatsLabel(delayBeatsAt(set.delayBeats, Math.abs(c)))}) + ${filter}`
|
||||||
|
case 'crusher':
|
||||||
|
return `Bit crusher ${a} (drive ×${set.crusherDrive}) + ${filter}`
|
||||||
|
case 'flanger':
|
||||||
|
return `Flanger ${a} (a sweep every ${beatsLabel(sweepBeatsAt(set.flangerBeats, Math.abs(c)))}) + ${filter}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function beatsLabel(b: number): string {
|
||||||
|
const fractions: Record<number, string> = { 0.125: '1/8', 0.25: '1/4', 0.5: '1/2', 0.75: '3/4' }
|
||||||
|
return `${fractions[b] ?? b} beat${b > 1 ? 's' : ''}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The mixer, between the decks in performance mode (decided 2026-11-02): per
|
||||||
|
* channel GAIN (on top of the track's auto gain), HI / MID / LOW, the FILTER
|
||||||
|
* knob with the effect that rides with it (its picker above; each effect's one
|
||||||
|
* parameter is an app setting, in Settings ▸ Performance mode…), a fader and
|
||||||
|
* its meter; between
|
||||||
|
* them the master meter and the limiter's light; the crossfader beneath. The
|
||||||
|
* values live in `mixerState` and the audio in `mixer.ts`.
|
||||||
|
*/
|
||||||
|
export function MixerPanel({
|
||||||
|
autoGain,
|
||||||
|
autoGainOn,
|
||||||
|
}: {
|
||||||
|
autoGain: Record<Channel, number | null>
|
||||||
|
/** The `useAutoGain` setting: off, the gain ignores the track's. */
|
||||||
|
autoGainOn: boolean
|
||||||
|
}) {
|
||||||
|
const meterRefs = {
|
||||||
|
A: useRef<HTMLDivElement>(null),
|
||||||
|
B: useRef<HTMLDivElement>(null),
|
||||||
|
master: useRef<HTMLDivElement>(null),
|
||||||
|
}
|
||||||
|
const limitRef = useRef<HTMLSpanElement>(null)
|
||||||
|
|
||||||
|
// One frame loop for every meter, writing the DOM directly — sixty React
|
||||||
|
// renders a second for three bars would be waste.
|
||||||
|
useEffect(() => {
|
||||||
|
let raf = 0
|
||||||
|
const held = { A: METER_FLOOR, B: METER_FLOOR, master: METER_FLOOR }
|
||||||
|
let limitUntil = 0
|
||||||
|
const tick = (now: number) => {
|
||||||
|
const lv = mixer().levels()
|
||||||
|
for (const k of ['A', 'B', 'master'] as const) {
|
||||||
|
const db = Math.max(METER_FLOOR, lv[k])
|
||||||
|
held[k] = db >= held[k] ? db : Math.max(db, held[k] - 0.6) // fall back ~36 dB/s
|
||||||
|
const el = meterRefs[k].current
|
||||||
|
if (el) {
|
||||||
|
el.style.height = `${((held[k] - METER_FLOOR) / (METER_TOP - METER_FLOOR)) * 100}%`
|
||||||
|
el.style.background =
|
||||||
|
held[k] > -1 ? 'var(--color-pink)' : held[k] > -9 ? 'var(--color-gold)' : 'var(--color-mint)'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Only while the master carries sound: on silence, Chrome's compressor
|
||||||
|
// reports a phantom reduction (14 dB, decaying over ~2 s, measured just
|
||||||
|
// after performance mode opens) that limits nothing.
|
||||||
|
if (lv.limiting > 0.5 && lv.master > -60) limitUntil = now + 600
|
||||||
|
if (limitRef.current) limitRef.current.dataset.on = String(now < limitUntil)
|
||||||
|
raf = requestAnimationFrame(tick)
|
||||||
|
}
|
||||||
|
raf = requestAnimationFrame(tick)
|
||||||
|
return () => cancelAnimationFrame(raf)
|
||||||
|
// The refs are stable.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const crossfader = useMixer((s) => s.crossfader)
|
||||||
|
const sharpness = useMixer((s) => s.sharpness)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="well flex w-[26rem] shrink-0 flex-col gap-1.5 rounded-2xl px-2.5 pb-1.5 pt-2.5">
|
||||||
|
<div className="flex min-h-0 flex-1 items-stretch gap-2">
|
||||||
|
<Strip ch="A" autoGain={autoGainOn ? autoGain.A : undefined} meterRef={meterRefs.A} />
|
||||||
|
<div className="flex w-3 flex-col items-center gap-1" title="Master — after the limiter">
|
||||||
|
<MeterBar fillRef={meterRefs.master} />
|
||||||
|
<span
|
||||||
|
ref={limitRef}
|
||||||
|
data-on="false"
|
||||||
|
title="The limiter is holding the master below clipping"
|
||||||
|
className="text-[7.5px] font-bold leading-none tracking-[0.04em] text-faint/50 data-[on=true]:text-pink data-[on=true]:[text-shadow:0_0_6px_var(--color-pink)]"
|
||||||
|
>
|
||||||
|
LIM
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<Strip ch="B" autoGain={autoGainOn ? autoGain.B : undefined} meterRef={meterRefs.B} mirrored />
|
||||||
|
</div>
|
||||||
|
<div className="flex h-6 shrink-0 items-center justify-center gap-2 px-1">
|
||||||
|
<span className="font-mono text-[11px] font-semibold text-muted">A</span>
|
||||||
|
<Fader
|
||||||
|
midi="mixer.crossfader"
|
||||||
|
orientation="horizontal"
|
||||||
|
value={crossfader}
|
||||||
|
min={-1}
|
||||||
|
max={1}
|
||||||
|
defaultValue={0}
|
||||||
|
onChange={(v) => setMixer({ crossfader: Math.abs(v) < 0.03 ? 0 : v })}
|
||||||
|
label="Crossfader"
|
||||||
|
describe={(v) =>
|
||||||
|
`Crossfader (curve ${Math.round(sharpness * 100)}% sharp — Settings ▸ Performance mode…) — ${
|
||||||
|
Math.abs(v) < 0.03 ? 'centre' : v < 0 ? `toward A ${Math.round(-v * 100)}%` : `toward B ${Math.round(v * 100)}%`
|
||||||
|
}`
|
||||||
|
}
|
||||||
|
className="w-1/2"
|
||||||
|
/>
|
||||||
|
<span className="font-mono text-[11px] font-semibold text-muted">B</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MeterBar({ fillRef }: { fillRef: RefObject<HTMLDivElement | null> }) {
|
||||||
|
return (
|
||||||
|
<div className="relative w-1.5 flex-1 overflow-hidden rounded-full bg-black/40">
|
||||||
|
<div ref={fillRef} className="absolute inset-x-0 bottom-0 h-0 rounded-full transition-[background-color] duration-150" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One channel: its knobs, then (toward the middle) its fader and meter. */
|
||||||
|
function Strip({
|
||||||
|
ch,
|
||||||
|
autoGain,
|
||||||
|
meterRef,
|
||||||
|
mirrored = false,
|
||||||
|
}: {
|
||||||
|
ch: Channel
|
||||||
|
/** The track's auto gain; null = it has none, undefined = the setting is off. */
|
||||||
|
autoGain: number | null | undefined
|
||||||
|
meterRef: RefObject<HTMLDivElement | null>
|
||||||
|
mirrored?: boolean
|
||||||
|
}) {
|
||||||
|
const s = useMixer((m) => m[ch])
|
||||||
|
const eqKill = useMixer((m) => m.eqKill)
|
||||||
|
const fxSettings = useMixer((m) => m.fx)
|
||||||
|
const [fxMenu, setFxMenu] = useState<{ x: number; y: number } | null>(null)
|
||||||
|
const set = (patch: Parameters<typeof setChannel>[1]) => setChannel(ch, patch)
|
||||||
|
const describeEq = (band: string) => (v: number) => {
|
||||||
|
const g = eqGain(v, eqKill)
|
||||||
|
return `${band} ${Math.abs(v) < 0.01 ? 'flat' : g === 0 ? 'killed' : fmtDb(gainToDb(g))}${
|
||||||
|
v < 0 ? ` (full left: ${eqKill ? 'kill' : `${EQ_CUT_DB} dB`})` : ''
|
||||||
|
}`
|
||||||
|
}
|
||||||
|
const eq = (band: 'high' | 'mid' | 'low', label: string, name: string) => (
|
||||||
|
<Knob
|
||||||
|
midi={`mixer.${ch}.${band}`}
|
||||||
|
value={s[band]}
|
||||||
|
min={-1}
|
||||||
|
max={1}
|
||||||
|
defaultValue={0}
|
||||||
|
bipolar
|
||||||
|
size={EQ_KNOB}
|
||||||
|
onChange={(v) => set({ [band]: Math.abs(v) < 0.03 ? 0 : v })}
|
||||||
|
label={label}
|
||||||
|
describe={describeEq(name)}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
// GAIN (the state's `trim`: on top of the track's auto gain) and the EQ as a
|
||||||
|
// 2×2 block; beside it, toward the fader, the Filter FX: the effect's picker
|
||||||
|
// above a larger FILTER knob (decided 2026-11-03).
|
||||||
|
const knobs = (
|
||||||
|
<div className={`flex items-center gap-2 self-center ${mirrored ? 'flex-row-reverse' : ''}`}>
|
||||||
|
<div className="grid grid-cols-2 gap-x-1.5 gap-y-1.5">
|
||||||
|
<Knob
|
||||||
|
midi={`mixer.${ch}.gain`}
|
||||||
|
value={s.trim}
|
||||||
|
min={-TRIM_RANGE_DB}
|
||||||
|
max={TRIM_RANGE_DB}
|
||||||
|
defaultValue={0}
|
||||||
|
bipolar
|
||||||
|
size={EQ_KNOB}
|
||||||
|
color="var(--color-text)"
|
||||||
|
onChange={(v) => set({ trim: Math.abs(v) < 0.3 ? 0 : v })}
|
||||||
|
label="Gain"
|
||||||
|
describe={(v) =>
|
||||||
|
`Gain ${fmtDb(v)}${
|
||||||
|
autoGain === undefined
|
||||||
|
? ' (auto gain off)'
|
||||||
|
: autoGain != null
|
||||||
|
? ` on the track's auto gain (${fmtDb(autoGain)})`
|
||||||
|
: ' (this track has no auto gain)'
|
||||||
|
}`
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{eq('high', 'Hi', 'High')}
|
||||||
|
{eq('mid', 'Mid', 'Mid')}
|
||||||
|
{eq('low', 'Low', 'Low')}
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col items-center gap-2" style={{ width: FILTER_KNOB }}>
|
||||||
|
<button
|
||||||
|
data-midi-action={`mixer.${ch}.fxNext`}
|
||||||
|
onClick={(e) => {
|
||||||
|
const r = e.currentTarget.getBoundingClientRect()
|
||||||
|
setFxMenu({ x: r.left, y: r.bottom + 4 })
|
||||||
|
}}
|
||||||
|
title={s.fx === 'filter' ? 'Filter FX: the filter alone — pick an effect to ride with it' : `Filter FX: ${FX_LABELS[s.fx]} rides with the FILTER knob`}
|
||||||
|
className="btn-glass flex h-6 w-full items-center justify-center gap-px rounded-md text-[9.5px] font-semibold uppercase tracking-[0.04em] text-text"
|
||||||
|
>
|
||||||
|
{FX_SHORT[s.fx]}
|
||||||
|
<Icon name="chevronDown" size={9} />
|
||||||
|
</button>
|
||||||
|
<Knob
|
||||||
|
midi={`mixer.${ch}.filter`}
|
||||||
|
value={s.color}
|
||||||
|
min={-1}
|
||||||
|
max={1}
|
||||||
|
defaultValue={0}
|
||||||
|
bipolar
|
||||||
|
size={FILTER_KNOB}
|
||||||
|
color="var(--color-gold)"
|
||||||
|
onChange={(v) => set({ color: Math.abs(v) < 0.02 ? 0 : v })}
|
||||||
|
label="Filter"
|
||||||
|
describe={(v) => describeFx(s.fx, v, fxSettings)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
const fader = (
|
||||||
|
<div className="flex flex-col items-center gap-0.5">
|
||||||
|
<Fader
|
||||||
|
midi={`mixer.${ch}.fader`}
|
||||||
|
orientation="vertical"
|
||||||
|
value={s.fader}
|
||||||
|
min={0}
|
||||||
|
max={1}
|
||||||
|
defaultValue={1}
|
||||||
|
onChange={(v) => set({ fader: v })}
|
||||||
|
label={`Channel ${ch} fader`}
|
||||||
|
describe={(v) => `Channel ${ch}: ${fmtDb(gainToDb(faderGain(v)))}`}
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<span className="font-mono text-[10px] font-semibold leading-none text-muted">{ch}</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
const meter = (
|
||||||
|
<div className="flex flex-col pb-3" title={`Channel ${ch} level (after its fader and FX)`}>
|
||||||
|
<MeterBar fillRef={meterRef} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
<div className={`flex min-w-0 flex-1 items-stretch gap-1.5 ${mirrored ? 'flex-row-reverse' : ''}`}>
|
||||||
|
{knobs}
|
||||||
|
{fader}
|
||||||
|
{meter}
|
||||||
|
{fxMenu && (
|
||||||
|
<ContextMenu
|
||||||
|
x={fxMenu.x}
|
||||||
|
y={fxMenu.y}
|
||||||
|
minWidth={0}
|
||||||
|
onClose={() => setFxMenu(null)}
|
||||||
|
items={[
|
||||||
|
...FX_TYPES.map((t) => ({
|
||||||
|
label: FX_LABELS[t],
|
||||||
|
hint: t === s.fx ? '✓' : undefined,
|
||||||
|
onClick: () => set({ fx: t }),
|
||||||
|
})),
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -324,3 +324,31 @@ option {
|
|||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.ambient-wash { animation: none !important; }
|
.ambient-wash { animation: none !important; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---- On-screen MIDI learning (MidiLearnOverlay.tsx) --------------------- */
|
||||||
|
/* Outlines, not borders or shadows: they sit outside the control and change
|
||||||
|
no layout, and the controls' own shadows (lit buttons) stay as they are. */
|
||||||
|
body.midi-learn [data-midi-action] {
|
||||||
|
outline: 1px dashed color-mix(in oklab, var(--color-accent) 70%, transparent);
|
||||||
|
outline-offset: 2px;
|
||||||
|
cursor: crosshair;
|
||||||
|
}
|
||||||
|
body.midi-learn [data-midi-action][data-midi-mapped] {
|
||||||
|
outline-style: solid;
|
||||||
|
}
|
||||||
|
body.midi-learn [data-midi-action][data-midi-armed] {
|
||||||
|
outline: 2px solid var(--color-accent);
|
||||||
|
outline-offset: 3px;
|
||||||
|
animation: midi-armed 0.9s ease-in-out infinite alternate;
|
||||||
|
}
|
||||||
|
body.midi-learn [data-midi-action][data-midi-learned] {
|
||||||
|
outline: 2px solid var(--color-mint);
|
||||||
|
outline-offset: 3px;
|
||||||
|
}
|
||||||
|
@keyframes midi-armed {
|
||||||
|
from { outline-color: var(--color-accent); }
|
||||||
|
to { outline-color: color-mix(in oklab, var(--color-accent) 30%, transparent); }
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
body.midi-learn [data-midi-action][data-midi-armed] { animation: none; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
// The app's ONE AudioContext. Every deck plays into it, so the decks can be
|
||||||
|
// mixed (and limited) before the speakers — two contexts cannot be connected.
|
||||||
|
// Never closed: a deck that goes away disconnects its own nodes. The route to
|
||||||
|
// the speakers is the mixer's (mixer.ts).
|
||||||
|
|
||||||
|
import deckWorkletUrl from './deckProcessor.worklet.ts?worker&url'
|
||||||
|
import rubberbandUrl from './rubberband.wasm?url'
|
||||||
|
|
||||||
|
let ctx: AudioContext | null = null
|
||||||
|
let worklet: Promise<ArrayBuffer | null> | null = null
|
||||||
|
|
||||||
|
export function audioContext(): AudioContext {
|
||||||
|
if (!ctx) {
|
||||||
|
const AC: typeof AudioContext =
|
||||||
|
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
|
||||||
|
ctx = new AC({ latencyHint: 'interactive' })
|
||||||
|
}
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resume on a user gesture (autoplay policy). */
|
||||||
|
export function resumeAudio(): void {
|
||||||
|
void audioContext().resume()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register the deck processor (once per context) and fetch Rubber Band's
|
||||||
|
* module bytes for keylock. Resolves to null bytes when the module cannot be
|
||||||
|
* fetched — the decks then play without keylock rather than not at all.
|
||||||
|
*/
|
||||||
|
export function loadDeckWorklet(): Promise<ArrayBuffer | null> {
|
||||||
|
if (!worklet) {
|
||||||
|
const c = audioContext()
|
||||||
|
const bytes = fetch(rubberbandUrl)
|
||||||
|
.then((r) => (r.ok ? r.arrayBuffer() : null))
|
||||||
|
.catch(() => null)
|
||||||
|
worklet = c.audioWorklet.addModule(deckWorkletUrl).then(() => bytes)
|
||||||
|
worklet.catch(() => {
|
||||||
|
worklet = null
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return worklet
|
||||||
|
}
|
||||||
@@ -0,0 +1,458 @@
|
|||||||
|
/// <reference types="node" />
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { DeckCore, QUANTUM, WARM_QUANTA, type DeckSource } from './deckCore'
|
||||||
|
import { extrapolate } from './position'
|
||||||
|
import { RubberBand } from './stretcher'
|
||||||
|
|
||||||
|
const SR = 44100
|
||||||
|
const rb = () => new RubberBand(new WebAssembly.Module(readFileSync(new URL('./rubberband.wasm', import.meta.url))))
|
||||||
|
|
||||||
|
/** A mono track whose every sample is distinct: sample i = i / len. */
|
||||||
|
function ramp(len: number): DeckSource {
|
||||||
|
const ch = new Float32Array(len)
|
||||||
|
for (let i = 0; i < len; i++) ch[i] = i / len
|
||||||
|
return { stems: [[ch]], length: len, sampleRate: SR }
|
||||||
|
}
|
||||||
|
|
||||||
|
function sine(freq: number, seconds: number, clicksEvery?: number): Float32Array {
|
||||||
|
const len = Math.round(seconds * SR)
|
||||||
|
const ch = new Float32Array(len)
|
||||||
|
for (let i = 0; i < len; i++) ch[i] = 0.5 * Math.sin((2 * Math.PI * freq * i) / SR)
|
||||||
|
if (clicksEvery) for (let i = 0; i < len; i += clicksEvery) ch[i] = 1
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render `blocks` blocks; returns the left channel. */
|
||||||
|
function run(core: DeckCore, blocks: number): Float32Array {
|
||||||
|
const out = new Float32Array(blocks * QUANTUM)
|
||||||
|
const l = new Float32Array(QUANTUM)
|
||||||
|
const r = new Float32Array(QUANTUM)
|
||||||
|
for (let b = 0; b < blocks; b++) {
|
||||||
|
core.render(l, r)
|
||||||
|
out.set(l, b * QUANTUM)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Frequency by counting upward zero crossings. */
|
||||||
|
function pitch(x: Float32Array): number {
|
||||||
|
let n = 0
|
||||||
|
for (let i = 1; i < x.length; i++) if (x[i - 1] < 0 && x[i] >= 0) n++
|
||||||
|
return (n * SR) / x.length
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('DeckCore transport', () => {
|
||||||
|
it('plays the source sample for sample at rate 1', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
const src = ramp(SR)
|
||||||
|
core.load(src)
|
||||||
|
core.play()
|
||||||
|
const out = run(core, 20)
|
||||||
|
for (let i = 0; i < out.length; i++) expect(out[i]).toBeCloseTo(src.stems[0][0][i], 6)
|
||||||
|
expect(core.positionSec).toBeCloseTo((20 * QUANTUM) / SR, 9)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is silent and still while paused, and resumes where it stopped', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(ramp(SR))
|
||||||
|
core.play()
|
||||||
|
run(core, 4)
|
||||||
|
core.pause()
|
||||||
|
const at = core.positionSec
|
||||||
|
expect(run(core, 4).every((v) => v === 0)).toBe(true)
|
||||||
|
expect(core.positionSec).toBe(at)
|
||||||
|
core.play()
|
||||||
|
expect(run(core, 1)[0]).toBeCloseTo((4 * QUANTUM) / SR, 6)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('loops seamlessly between whole-sample bounds', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
const src = ramp(SR)
|
||||||
|
core.load(src)
|
||||||
|
const start = 1000
|
||||||
|
const end = 1300
|
||||||
|
core.seek(start / SR)
|
||||||
|
core.setLoop(start / SR, end / SR, true)
|
||||||
|
core.play()
|
||||||
|
const out = run(core, 10)
|
||||||
|
for (let i = 0; i < out.length; i++) {
|
||||||
|
expect(out[i]).toBeCloseTo(src.stems[0][0][start + (i % (end - start))], 6)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('jumps into a loop engaged behind the playhead', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(ramp(SR))
|
||||||
|
core.seek(0.5)
|
||||||
|
core.setLoop(0.1, 0.2, true)
|
||||||
|
expect(core.positionSec).toBeCloseTo(0.1, 9)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('varispeed: rate 2 reads every other sample', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
const src = ramp(SR)
|
||||||
|
core.load(src)
|
||||||
|
core.setRate(2)
|
||||||
|
core.play()
|
||||||
|
const out = run(core, 5)
|
||||||
|
for (let i = 0; i < out.length; i++) expect(out[i]).toBeCloseTo(src.stems[0][0][2 * i], 5)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reports the end of the track once and stops', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(ramp(QUANTUM * 3 + 10))
|
||||||
|
core.play()
|
||||||
|
const events: string[] = []
|
||||||
|
for (let b = 0; b < 6; b++) {
|
||||||
|
run(core, 1)
|
||||||
|
events.push(...core.events)
|
||||||
|
}
|
||||||
|
expect(events).toEqual(['ended'])
|
||||||
|
expect(core.playing).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('plays stems in lockstep, and a mute ramps one out', () => {
|
||||||
|
const a = sine(220, 1)
|
||||||
|
const b = sine(330, 1)
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load({ stems: [[a], [b]], length: a.length, sampleRate: SR })
|
||||||
|
core.play()
|
||||||
|
const both = run(core, 4)
|
||||||
|
for (let i = 0; i < both.length; i++) expect(both[i]).toBeCloseTo(a[i] + b[i], 5)
|
||||||
|
core.setGains([1, 0])
|
||||||
|
run(core, 40) // the 4 ms ramp settles
|
||||||
|
const at = Math.round(core.positionSec * SR)
|
||||||
|
const solo = run(core, 4)
|
||||||
|
for (let i = 0; i < solo.length; i++) expect(solo[i]).toBeCloseTo(a[at + i], 4)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('DeckCore lead-in (performance mode)', () => {
|
||||||
|
it('a seek before the track plays silence, then the track exactly on time', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
const src = ramp(SR)
|
||||||
|
core.load(src)
|
||||||
|
core.setLeadIn(true)
|
||||||
|
const lead = 2 * QUANTUM + 37
|
||||||
|
core.seek(-lead / SR)
|
||||||
|
expect(core.positionSec).toBeCloseTo(-lead / SR, 9)
|
||||||
|
core.play()
|
||||||
|
const out = run(core, 6)
|
||||||
|
for (let i = 0; i < lead - 2; i++) expect(out[i]).toBeCloseTo(0, 6)
|
||||||
|
for (let i = lead + 2; i < out.length; i++) expect(out[i]).toBeCloseTo(src.stems[0][0][i - lead], 6)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('without lead-in a seek stops at the start; turning it off brings the playhead back', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(ramp(SR))
|
||||||
|
core.seek(-0.5)
|
||||||
|
expect(core.positionSec).toBe(0)
|
||||||
|
core.setLeadIn(true)
|
||||||
|
core.seek(-0.5)
|
||||||
|
expect(core.positionSec).toBeCloseTo(-0.5, 9)
|
||||||
|
core.setLeadIn(false)
|
||||||
|
expect(core.positionSec).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a loop past the end loops silence and keeps playing; released, the deck stops', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
const len = QUANTUM * 4
|
||||||
|
core.load(ramp(len))
|
||||||
|
core.setLeadIn(true)
|
||||||
|
core.setLoop((len - 100) / SR, (len + 200) / SR, true)
|
||||||
|
core.seek((len - 100) / SR)
|
||||||
|
core.play()
|
||||||
|
const events: string[] = []
|
||||||
|
for (let b = 0; b < 20; b++) {
|
||||||
|
run(core, 1)
|
||||||
|
events.push(...core.events)
|
||||||
|
}
|
||||||
|
expect(events).toEqual([])
|
||||||
|
expect(core.playing).toBe(true)
|
||||||
|
core.setLoop((len - 100) / SR, (len + 200) / SR, false)
|
||||||
|
for (let b = 0; b < 5; b++) {
|
||||||
|
run(core, 1)
|
||||||
|
events.push(...core.events)
|
||||||
|
}
|
||||||
|
expect(events).toEqual(['ended'])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('DeckCore scratch', () => {
|
||||||
|
it('follows the drag, then coasts back to playing speed and plays on by itself', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(ramp(SR * 4))
|
||||||
|
core.play()
|
||||||
|
run(core, 10)
|
||||||
|
core.scratchBegin(1)
|
||||||
|
expect(core.scratching).toBe(true)
|
||||||
|
core.scratchTarget(1.2)
|
||||||
|
run(core, 200)
|
||||||
|
expect(core.positionSec).toBeGreaterThan(1.1)
|
||||||
|
core.scratchRelease(true)
|
||||||
|
const events: string[] = []
|
||||||
|
for (let b = 0; b < 2000 && !events.length; b++) {
|
||||||
|
run(core, 1)
|
||||||
|
events.push(...core.events)
|
||||||
|
}
|
||||||
|
expect(events).toEqual(['scratchDone'])
|
||||||
|
expect(core.playing).toBe(true)
|
||||||
|
const before = core.positionSec
|
||||||
|
run(core, 10)
|
||||||
|
expect(core.positionSec - before).toBeCloseTo((10 * QUANTUM) / SR, 6)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a re-grab that arrives after the coast settled grabs afresh (and echoes its id)', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(ramp(SR * 4))
|
||||||
|
core.scratchBegin(1, 7)
|
||||||
|
core.scratchTarget(1.1)
|
||||||
|
run(core, 50)
|
||||||
|
core.scratchRelease(false)
|
||||||
|
for (let b = 0; b < 3000 && core.scratching; b++) run(core, 1)
|
||||||
|
expect(core.scratching).toBe(false)
|
||||||
|
expect(core.scratchId).toBe(7)
|
||||||
|
// The caller has not heard scratchDone yet and thinks it is still coasting.
|
||||||
|
const p = core.positionSec
|
||||||
|
core.scratchRegrab(p, 8)
|
||||||
|
expect(core.scratching).toBe(true)
|
||||||
|
expect(core.scratchId).toBe(8)
|
||||||
|
core.scratchTarget(p + 0.2)
|
||||||
|
run(core, 200)
|
||||||
|
expect(core.positionSec).toBeGreaterThan(p + 0.15)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a release without resume settles paused', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(ramp(SR * 4))
|
||||||
|
core.scratchBegin(1)
|
||||||
|
core.scratchTarget(1.5)
|
||||||
|
run(core, 100)
|
||||||
|
core.scratchRelease(false)
|
||||||
|
for (let b = 0; b < 3000 && core.scratching; b++) run(core, 1)
|
||||||
|
expect(core.scratching).toBe(false)
|
||||||
|
expect(core.playing).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('DeckCore scratch sound', () => {
|
||||||
|
const tone = (freq: number): DeckSource => {
|
||||||
|
const ch = sine(freq, 20)
|
||||||
|
return { stems: [[ch]], length: ch.length, sampleRate: SR }
|
||||||
|
}
|
||||||
|
/** Drag at `speed`, the hand's position arriving after each of `gaps`
|
||||||
|
* (blocks, cycled) — as a mouse or a jog delivers it, in steps. Returns
|
||||||
|
* the speed after every block and the output. */
|
||||||
|
function drag(core: DeckCore, speed: number, gaps: number[], blocks: number) {
|
||||||
|
const start = core.positionSec
|
||||||
|
const speeds: number[] = []
|
||||||
|
const out = new Float32Array(blocks * QUANTUM)
|
||||||
|
const l = new Float32Array(QUANTUM)
|
||||||
|
const r = new Float32Array(QUANTUM)
|
||||||
|
let next = gaps[0]
|
||||||
|
for (let b = 0, g = 0; b < blocks; b++) {
|
||||||
|
if (b === next) {
|
||||||
|
core.scratchTarget(start + (speed * b * QUANTUM) / SR)
|
||||||
|
next += gaps[++g % gaps.length]
|
||||||
|
}
|
||||||
|
core.render(l, r)
|
||||||
|
out.set(l, b * QUANTUM)
|
||||||
|
speeds.push(core.speed)
|
||||||
|
}
|
||||||
|
return { speeds, out }
|
||||||
|
}
|
||||||
|
const worst = (xs: number[], ref: number) => Math.max(...xs.map((x) => Math.abs(x - ref)))
|
||||||
|
const maxStep = (x: Float32Array) => {
|
||||||
|
let m = 0
|
||||||
|
for (let i = 1; i < x.length; i++) m = Math.max(m, Math.abs(x[i] - x[i - 1]))
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
it('a steady hand moving in mouse-rate steps plays at a steady speed', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(tone(440))
|
||||||
|
core.scratchBegin(1)
|
||||||
|
const { speeds } = drag(core, 1, [6], 700) // a position every 17 ms
|
||||||
|
expect(worst(speeds.slice(200), 1)).toBeLessThan(0.03)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('and in jittery bursts, as a busy main thread delivers a jog', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(tone(440))
|
||||||
|
core.scratchBegin(1)
|
||||||
|
const { speeds } = drag(core, 1, [1, 1, 4, 1, 7, 2, 1, 3, 5, 1], 700)
|
||||||
|
expect(worst(speeds.slice(200), 1)).toBeLessThan(0.1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('stopping the hand fades out — no click at rest', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(tone(440))
|
||||||
|
core.scratchBegin(1)
|
||||||
|
const moving = drag(core, 1, [6], 200)
|
||||||
|
const resting = run(core, 100)
|
||||||
|
// A 0.5 amplitude 440 Hz sine at 1x moves at most 0.031 a sample.
|
||||||
|
expect(maxStep(moving.out)).toBeLessThan(0.05)
|
||||||
|
expect(maxStep(resting)).toBeLessThan(0.05)
|
||||||
|
expect(Math.max(...resting.slice(-QUANTUM).map(Math.abs))).toBeLessThan(1e-3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('grabbing a playing deck neither jumps nor clicks, whatever position the caller had', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(tone(440))
|
||||||
|
core.play()
|
||||||
|
const before = run(core, 20)
|
||||||
|
const p = core.positionSec
|
||||||
|
core.scratchBegin(p + 0.04) // a stale main-thread estimate
|
||||||
|
core.scratchTarget(p + 0.04) // the hand has not moved
|
||||||
|
const after = run(core, 20)
|
||||||
|
expect(Math.abs(core.positionSec - p)).toBeLessThan(0.01)
|
||||||
|
const joined = new Float32Array(before.length + after.length)
|
||||||
|
joined.set(before)
|
||||||
|
joined.set(after, before.length)
|
||||||
|
expect(maxStep(joined)).toBeLessThan(0.05)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a fast scratch does not fold highs back down as noise', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(tone(15000))
|
||||||
|
core.scratchBegin(1)
|
||||||
|
const { out } = drag(core, 3, [1], 300) // 3x: 45 kHz, far past Nyquist
|
||||||
|
const tail = out.slice(150 * QUANTUM)
|
||||||
|
const rms = Math.sqrt(tail.reduce((a, x) => a + x * x, 0) / tail.length)
|
||||||
|
expect(rms).toBeLessThan(0.05) // the tone itself is 0.35 RMS
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('DeckCore keylock', () => {
|
||||||
|
it('keeps the pitch while the tempo changes; plain varispeed does not', () => {
|
||||||
|
const tone = sine(440, 6)
|
||||||
|
const src: DeckSource = { stems: [[tone]], length: tone.length, sampleRate: SR }
|
||||||
|
|
||||||
|
const plain = new DeckCore(SR, rb())
|
||||||
|
plain.load(src)
|
||||||
|
plain.setRate(1.1)
|
||||||
|
plain.play()
|
||||||
|
expect(pitch(run(plain, 300).subarray(50 * QUANTUM))).toBeCloseTo(484, -1)
|
||||||
|
|
||||||
|
const locked = new DeckCore(SR, rb())
|
||||||
|
locked.load(src)
|
||||||
|
locked.setKeylock(true)
|
||||||
|
locked.setRate(1.1)
|
||||||
|
locked.play()
|
||||||
|
const out = run(locked, 300)
|
||||||
|
expect(locked.stretching).toBe(true)
|
||||||
|
expect(pitch(out.subarray(50 * QUANTUM))).toBeCloseTo(440, -1)
|
||||||
|
// The tempo still changed: the playhead ran at 1.1x.
|
||||||
|
expect(locked.positionSec).toBeCloseTo((1.1 * 300 * QUANTUM) / SR, 6)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers a seek at once (varispeed while priming), then hands over to the stretcher', () => {
|
||||||
|
const tone = sine(440, 6)
|
||||||
|
const core = new DeckCore(SR, rb())
|
||||||
|
core.load({ stems: [[tone]], length: tone.length, sampleRate: SR })
|
||||||
|
core.setKeylock(true)
|
||||||
|
core.setRate(0.94)
|
||||||
|
core.play()
|
||||||
|
run(core, 100)
|
||||||
|
core.seek(3)
|
||||||
|
const first = run(core, 1)
|
||||||
|
expect(Math.max(...first.map(Math.abs))).toBeGreaterThan(0.3) // sound in the very first block
|
||||||
|
expect(core.stretching).toBe(false)
|
||||||
|
run(core, WARM_QUANTA + 4)
|
||||||
|
expect(core.stretching).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('stretched output stays aligned with the playhead', () => {
|
||||||
|
// A click every 0.5 s of SOURCE; at 1.05x with keylock each should be heard
|
||||||
|
// where the playhead says it is, within a few ms.
|
||||||
|
const every = SR / 2
|
||||||
|
const tone = sine(110, 8, every).map((v, i) => (i % every === 0 ? 1 : v * 0.1))
|
||||||
|
const core = new DeckCore(SR, rb())
|
||||||
|
core.load({ stems: [[tone]], length: tone.length, sampleRate: SR })
|
||||||
|
core.setKeylock(true)
|
||||||
|
core.setRate(1.05)
|
||||||
|
core.play()
|
||||||
|
const blocks = 1200
|
||||||
|
const out = new Float32Array(blocks * QUANTUM)
|
||||||
|
const posAt = new Float64Array(blocks)
|
||||||
|
const l = new Float32Array(QUANTUM)
|
||||||
|
const r = new Float32Array(QUANTUM)
|
||||||
|
for (let b = 0; b < blocks; b++) {
|
||||||
|
posAt[b] = core.positionSec
|
||||||
|
core.render(l, r)
|
||||||
|
out.set(l, b * QUANTUM)
|
||||||
|
}
|
||||||
|
// Expected output frame of the click at source second s: the block whose
|
||||||
|
// playhead passes s, plus the fraction within it.
|
||||||
|
const errors: number[] = []
|
||||||
|
for (let s = 1; s < 3; s += 0.5) {
|
||||||
|
const b = posAt.findIndex((p) => p > s) - 1
|
||||||
|
const expected = b * QUANTUM + ((s - posAt[b]) * SR) / 1.05
|
||||||
|
let best = 0
|
||||||
|
let at = 0
|
||||||
|
for (let i = Math.round(expected - 2000); i < expected + 2000; i++) {
|
||||||
|
if (Math.abs(out[i]) > best) {
|
||||||
|
best = Math.abs(out[i])
|
||||||
|
at = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
errors.push(((at - expected) / SR) * 1000)
|
||||||
|
}
|
||||||
|
for (const e of errors) expect(Math.abs(e)).toBeLessThan(6)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('every stem gets its own stretcher and a mute stays instant', () => {
|
||||||
|
const a = sine(220, 4)
|
||||||
|
const b = sine(660, 4)
|
||||||
|
const core = new DeckCore(SR, rb())
|
||||||
|
core.load({ stems: [[a], [b]], length: a.length, sampleRate: SR })
|
||||||
|
core.setKeylock(true)
|
||||||
|
core.setRate(1.08)
|
||||||
|
core.play()
|
||||||
|
run(core, 60)
|
||||||
|
expect(core.stretching).toBe(true)
|
||||||
|
core.setGains([1, 0])
|
||||||
|
run(core, 40)
|
||||||
|
expect(pitch(run(core, 200))).toBeCloseTo(220, -1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('back at rate 1 the stretcher is bypassed', () => {
|
||||||
|
const tone = sine(440, 4)
|
||||||
|
const core = new DeckCore(SR, rb())
|
||||||
|
core.load({ stems: [[tone]], length: tone.length, sampleRate: SR })
|
||||||
|
core.setKeylock(true)
|
||||||
|
core.setRate(1.05)
|
||||||
|
core.play()
|
||||||
|
run(core, 60)
|
||||||
|
expect(core.stretching).toBe(true)
|
||||||
|
core.setRate(1)
|
||||||
|
run(core, 2)
|
||||||
|
expect(core.stretching).toBe(false)
|
||||||
|
const at = Math.round(core.positionSec * SR)
|
||||||
|
const out = run(core, 4)
|
||||||
|
for (let i = 0; i < out.length; i++) expect(out[i]).toBeCloseTo(tone[at + i], 5)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('extrapolate', () => {
|
||||||
|
const noLoop = { start: 0, end: 0, on: false }
|
||||||
|
it('holds still while paused', () => {
|
||||||
|
expect(extrapolate({ pos: 5, time: 1, speed: 1, playing: false, scratching: false }, 3, noLoop, 100)).toBe(5)
|
||||||
|
})
|
||||||
|
it('advances by the speed and clamps at the end', () => {
|
||||||
|
const m = { pos: 5, time: 1, speed: 1.1, playing: true, scratching: false }
|
||||||
|
expect(extrapolate(m, 3, noLoop, 100)).toBeCloseTo(7.2, 9)
|
||||||
|
expect(extrapolate(m, 300, noLoop, 100)).toBe(100)
|
||||||
|
})
|
||||||
|
it('wraps inside an engaged loop', () => {
|
||||||
|
const m = { pos: 9, time: 0, speed: 1, playing: true, scratching: false }
|
||||||
|
expect(extrapolate(m, 2.5, { start: 8, end: 10, on: true }, 100)).toBeCloseTo(9.5, 9)
|
||||||
|
})
|
||||||
|
it('runs on before the track and past its end inside a loop that reaches there', () => {
|
||||||
|
const lead = { pos: -1, time: 0, speed: 1, playing: true, scratching: false }
|
||||||
|
expect(extrapolate(lead, 0.4, { start: 0, end: 0, on: false }, 100)).toBeCloseTo(-0.6, 9)
|
||||||
|
const out = { pos: 99.5, time: 0, speed: 1, playing: true, scratching: false }
|
||||||
|
expect(extrapolate(out, 1, { start: 99, end: 101, on: true }, 100)).toBeCloseTo(100.5, 9)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,804 @@
|
|||||||
|
// One deck's audio, rendered a block at a time: the body of the deck's
|
||||||
|
// AudioWorklet (`deckProcessor.worklet.ts`), kept free of worklet globals so it
|
||||||
|
// can be driven directly in tests.
|
||||||
|
//
|
||||||
|
// ONE chain does everything the deck plays: transport, seamless loops, the
|
||||||
|
// stems in lockstep (one position for all of them), mute/solo as ramped gains,
|
||||||
|
// varispeed (the pitch fader), keylock and scratch. It replaced an
|
||||||
|
// AudioBufferSourceNode for playback plus a ScriptProcessorNode on a SECOND
|
||||||
|
// AudioContext for scratch: those two could not share a context (the scratch
|
||||||
|
// node went silent once a source had played), so there was no single place a
|
||||||
|
// mixer could sit.
|
||||||
|
//
|
||||||
|
// Positions are SOURCE samples (the decoded audio's own rate); a step of
|
||||||
|
// `rate * srcRate / ctxRate` source samples per output frame plays at `rate`.
|
||||||
|
//
|
||||||
|
// KEYLOCK runs the stems through Rubber Band (R2, real time) whenever the rate
|
||||||
|
// is not 1. A stretcher has to be primed before its output lines up with the
|
||||||
|
// playhead, and priming four stems at once would blow one block's budget — a
|
||||||
|
// dropout on every hotcue. So after a seek (or play, loop jump, scratch
|
||||||
|
// hand-back, rate change while priming) the deck plays the plain varispeed path
|
||||||
|
// at once, primes the stretchers over the next blocks aimed at where the
|
||||||
|
// playhead WILL be, and crossfades over one block when the stretched output is
|
||||||
|
// aligned. Near rate 1 those few ms of varispeed are inaudible.
|
||||||
|
|
||||||
|
import { MAX_BLOCK, type RubberBand, Stretcher } from './stretcher'
|
||||||
|
|
||||||
|
/** An AudioWorklet's block length. */
|
||||||
|
export const QUANTUM = 128
|
||||||
|
|
||||||
|
export interface DeckSource {
|
||||||
|
/** Per stem (a plain track is one), per channel (1 or 2). */
|
||||||
|
stems: Float32Array[][]
|
||||||
|
/** Frames, the same for every stem. */
|
||||||
|
length: number
|
||||||
|
sampleRate: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DeckEvent = 'ended' | 'scratchDone'
|
||||||
|
|
||||||
|
type Mode = 'stopped' | 'playing' | 'drag' | 'inertia'
|
||||||
|
type StretchState = 'off' | 'warming' | 'on'
|
||||||
|
|
||||||
|
// Scratch. The hand's position arrives in STEPS (a mouse move, a jog message:
|
||||||
|
// 60 Hz to 1 kHz, bunched by the main thread), and chasing each step made the
|
||||||
|
// speed lurch at that rate — a buzzing, distorted scratch with a click each
|
||||||
|
// time it caught up. So the steps are first joined into a line, played a
|
||||||
|
// little BEHIND the newest (`delay`, adapted to how far apart they arrive), and
|
||||||
|
// the platter follows that line through a critically damped spring: its speed
|
||||||
|
// is continuous. Volume follows speed (no hard mute at rest), and above 1x the
|
||||||
|
// source is averaged over the span each output frame covers (anti-aliasing).
|
||||||
|
const RATE_CAP = 12 // max source samples per output frame (pitch ceiling)
|
||||||
|
const INERTIA_FRICTION = 0.9998 // per-frame easing toward the target velocity (~0.4 s)
|
||||||
|
const SETTLE_EPS = 0.02 // |velocity - target| below this = settled
|
||||||
|
/** The platter's spring (Hz): higher follows the hand tighter, lower smooths more. */
|
||||||
|
const SCRATCH_HZ = 45
|
||||||
|
/** Hand-line delay (s): at least a block or two, at most this. */
|
||||||
|
const HAND_DELAY_MIN = 0.006
|
||||||
|
const HAND_DELAY_MAX = 0.03
|
||||||
|
const HAND_DELAY_START = 0.012
|
||||||
|
/** Two hand positions further apart than this (s) = the hand paused. */
|
||||||
|
const HAND_PAUSE = 0.06
|
||||||
|
/** How fast the delay may change: 3% of playing time (inaudible). */
|
||||||
|
const HAND_DELAY_SLEW = 0.03
|
||||||
|
/** Speed (source samples per frame) at which a scratch is at full volume. */
|
||||||
|
const SCRATCH_FULL_SPEED = 0.05
|
||||||
|
/** The volume's follow time (s). */
|
||||||
|
const SCRATCH_ENV_TAU = 0.003
|
||||||
|
/** Hand positions kept (a 1 kHz jog over the longest delay is ~30). */
|
||||||
|
const HAND_POINTS = 256
|
||||||
|
|
||||||
|
/** Blocks of varispeed while the stretchers prime (~29 ms at 44.1 kHz). */
|
||||||
|
export const WARM_QUANTA = 10
|
||||||
|
/** Input frames fed per stem per block while priming — keeps a 4-stem prime
|
||||||
|
* well inside a block's budget beside the other deck. */
|
||||||
|
const WARM_BUDGET = 384
|
||||||
|
/** Stem mute/solo ramp (s). */
|
||||||
|
const GAIN_TAU = 0.004
|
||||||
|
/** The furthest a lead-in reaches before the track (s). */
|
||||||
|
const LEAD_IN_SEC = 32
|
||||||
|
|
||||||
|
export class DeckCore {
|
||||||
|
private stems: Float32Array[][] = []
|
||||||
|
private len = 0
|
||||||
|
private srcRate = 44100
|
||||||
|
|
||||||
|
private mode: Mode = 'stopped'
|
||||||
|
/** Playhead, in source samples. */
|
||||||
|
private pos = 0
|
||||||
|
private rate = 1
|
||||||
|
private keylock = false
|
||||||
|
/** Performance mode: the playhead may sit BEFORE the track (silence until
|
||||||
|
* it starts, on the beat) — a beat jump or loop move past the start. */
|
||||||
|
private leadIn = false
|
||||||
|
|
||||||
|
private loopOn = false
|
||||||
|
private loopStart = 0
|
||||||
|
private loopEnd = 0
|
||||||
|
private loopLen = 0
|
||||||
|
/** loopLen rounded, for whole-sample index maps. */
|
||||||
|
private loopLenI = 0
|
||||||
|
|
||||||
|
private gainTarget: number[] = []
|
||||||
|
private gainNow: number[] = []
|
||||||
|
private readonly gainCoef: number
|
||||||
|
/** Per stem, this block's per-frame gains (shared by both paths in a crossfade). */
|
||||||
|
private gainBuf: Float32Array[] = []
|
||||||
|
|
||||||
|
// Scratch (source samples, and source samples per output frame).
|
||||||
|
private velocity = 0
|
||||||
|
private targetVelocity = 0
|
||||||
|
private resume = false
|
||||||
|
/** The caller's id for the current grab, echoed with its scratchDone. */
|
||||||
|
scratchId = 0
|
||||||
|
/** Output frames rendered so far: the hand positions' clock. */
|
||||||
|
private clock = 0
|
||||||
|
/** The hand's positions (clock frame, source sample), oldest first, a ring. */
|
||||||
|
private readonly handT = new Float64Array(HAND_POINTS)
|
||||||
|
private readonly handX = new Float64Array(HAND_POINTS)
|
||||||
|
private handHead = 0
|
||||||
|
private handLen = 0
|
||||||
|
/** Was the newest hand point sent (not a hold point added here)? */
|
||||||
|
private handLastReal = false
|
||||||
|
/** How far behind the clock the hand line is played (frames). */
|
||||||
|
private handDelay: number
|
||||||
|
/** Recent largest gap between hand positions (frames). */
|
||||||
|
private handGap = 0
|
||||||
|
/** The core's playhead minus the caller's position at the grab (samples):
|
||||||
|
* targets are relative, so a stale main-thread position cannot jump it. */
|
||||||
|
private handOffset = 0
|
||||||
|
/** Scratch volume, following speed. */
|
||||||
|
private env = 0
|
||||||
|
private readonly springW: number
|
||||||
|
private readonly envCoef: number
|
||||||
|
|
||||||
|
// Keylock.
|
||||||
|
private stretchers: Stretcher[] = []
|
||||||
|
private sState: StretchState = 'off'
|
||||||
|
private needRewarm = false
|
||||||
|
private warmRate = 0
|
||||||
|
/** Next pre-roll frame to feed while priming (may be < 0: silence). */
|
||||||
|
private feedPos = 0
|
||||||
|
private primeLeft = 0
|
||||||
|
private discardLeft = 0
|
||||||
|
/** Per stem: next source frame to feed (loop-wrapped). */
|
||||||
|
private readPtr: number[] = []
|
||||||
|
/** Source position of the stretchers' next output frame, while priming. */
|
||||||
|
private outPos = 0
|
||||||
|
|
||||||
|
private readonly inTmp = [new Float32Array(MAX_BLOCK), new Float32Array(MAX_BLOCK)]
|
||||||
|
private readonly dropTmp = [new Float32Array(MAX_BLOCK), new Float32Array(MAX_BLOCK)]
|
||||||
|
private outTmp: Float32Array[][] = []
|
||||||
|
private readonly xL = new Float32Array(QUANTUM)
|
||||||
|
private readonly xR = new Float32Array(QUANTUM)
|
||||||
|
|
||||||
|
/** Things that happened during the last render, for the processor to report. */
|
||||||
|
readonly events: DeckEvent[] = []
|
||||||
|
|
||||||
|
readonly ctxRate: number
|
||||||
|
private readonly rb: RubberBand | null
|
||||||
|
|
||||||
|
constructor(ctxRate: number, rb: RubberBand | null) {
|
||||||
|
this.ctxRate = ctxRate
|
||||||
|
this.rb = rb
|
||||||
|
this.gainCoef = Math.exp(-1 / (GAIN_TAU * ctxRate))
|
||||||
|
this.springW = (2 * Math.PI * SCRATCH_HZ) / ctxRate
|
||||||
|
this.envCoef = 1 - Math.exp(-1 / (SCRATCH_ENV_TAU * ctxRate))
|
||||||
|
this.handDelay = HAND_DELAY_START * ctxRate
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- state -----------------------------------------------------------
|
||||||
|
|
||||||
|
get loaded(): boolean {
|
||||||
|
return this.len > 0
|
||||||
|
}
|
||||||
|
get positionSec(): number {
|
||||||
|
return this.pos / this.srcRate
|
||||||
|
}
|
||||||
|
get playing(): boolean {
|
||||||
|
return this.mode === 'playing'
|
||||||
|
}
|
||||||
|
get scratching(): boolean {
|
||||||
|
return this.mode === 'drag' || this.mode === 'inertia'
|
||||||
|
}
|
||||||
|
/** Track seconds per second right now. */
|
||||||
|
get speed(): number {
|
||||||
|
if (this.mode === 'playing') return this.rate
|
||||||
|
if (this.scratching) return (this.velocity * this.ctxRate) / this.srcRate
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
/** Is keylock's stretched output what is heard? (tests) */
|
||||||
|
get stretching(): boolean {
|
||||||
|
return this.sState === 'on'
|
||||||
|
}
|
||||||
|
private get step(): number {
|
||||||
|
return (this.rate * this.srcRate) / this.ctxRate
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- commands --------------------------------------------------------
|
||||||
|
|
||||||
|
load(src: DeckSource): void {
|
||||||
|
this.disposeStretchers()
|
||||||
|
this.stems = src.stems
|
||||||
|
this.len = src.length
|
||||||
|
this.srcRate = src.sampleRate
|
||||||
|
this.mode = 'stopped'
|
||||||
|
this.pos = 0
|
||||||
|
this.loopOn = false
|
||||||
|
this.gainTarget = src.stems.map(() => 1)
|
||||||
|
this.gainNow = src.stems.map(() => 1)
|
||||||
|
this.gainBuf = src.stems.map(() => new Float32Array(QUANTUM))
|
||||||
|
this.outTmp = src.stems.map(() => [new Float32Array(QUANTUM), new Float32Array(QUANTUM)])
|
||||||
|
this.readPtr = src.stems.map(() => 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
play(): void {
|
||||||
|
if (!this.len) return
|
||||||
|
if (this.pos >= this.len - 0.01 * this.srcRate) this.pos = 0 // restart from the top at the end
|
||||||
|
this.mode = 'playing'
|
||||||
|
this.needRewarm = true
|
||||||
|
}
|
||||||
|
|
||||||
|
pause(): void {
|
||||||
|
if (this.mode === 'playing') this.mode = 'stopped'
|
||||||
|
this.sState = 'off'
|
||||||
|
}
|
||||||
|
|
||||||
|
seek(sec: number): void {
|
||||||
|
this.pos = Math.max(this.minPos, Math.min(sec * this.srcRate, this.maxPos))
|
||||||
|
this.needRewarm = true
|
||||||
|
}
|
||||||
|
|
||||||
|
setLeadIn(on: boolean): void {
|
||||||
|
this.leadIn = on
|
||||||
|
if (!on && this.pos < 0) {
|
||||||
|
this.pos = 0
|
||||||
|
this.needRewarm = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How far before the track the playhead may go (with lead-in), in source
|
||||||
|
* samples: far beyond any beat jump (32 beats at 60 BPM). */
|
||||||
|
private get minPos(): number {
|
||||||
|
return this.leadIn ? -LEAD_IN_SEC * this.srcRate : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The end, or an engaged loop's end where it reaches past the track. */
|
||||||
|
private get maxPos(): number {
|
||||||
|
return this.loopOn ? Math.max(this.len, this.loopEnd) : this.len
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoop(startSec: number, endSec: number, enabled: boolean): void {
|
||||||
|
const wasOn = this.loopOn
|
||||||
|
this.loopStart = startSec * this.srcRate
|
||||||
|
this.loopEnd = endSec * this.srcRate
|
||||||
|
this.loopLen = this.loopEnd - this.loopStart
|
||||||
|
this.loopLenI = Math.max(1, Math.round(this.loopLen))
|
||||||
|
this.loopOn = enabled && this.loopLen > 0
|
||||||
|
// Already past the new end: jump into it (as an AudioBufferSourceNode did).
|
||||||
|
if (this.loopOn && this.pos >= this.loopEnd) {
|
||||||
|
this.pos = this.loopStart
|
||||||
|
this.needRewarm = true
|
||||||
|
}
|
||||||
|
if (this.sState !== 'off') {
|
||||||
|
// The stretchers were fed AHEAD of the playhead. Re-prime if that input
|
||||||
|
// no longer matches the new loop: fed past the new end, or wrapped by a
|
||||||
|
// loop that is now gone.
|
||||||
|
const wrapped = this.readPtr.some((r) => r < this.pos)
|
||||||
|
if (this.loopOn ? wrapped || this.readPtr.some((r) => r >= this.loopEnd) : wasOn && wrapped) {
|
||||||
|
this.needRewarm = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setGains(levels: number[]): void {
|
||||||
|
this.gainTarget = this.stems.map((_, i) => levels[i] ?? 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
setRate(rate: number): void {
|
||||||
|
this.rate = Math.max(0.05, rate)
|
||||||
|
if (this.sState === 'on') for (const s of this.stretchers) s.setRatios(1 / this.step, this.pitchScale)
|
||||||
|
}
|
||||||
|
|
||||||
|
setKeylock(on: boolean): void {
|
||||||
|
this.keylock = on
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Grab the platter. `sec` is where the CALLER thinks the playhead is: later
|
||||||
|
* targets move relative to it. Grabbing a playing deck starts from its own
|
||||||
|
* speed, so the stop is a quick brake rather than a click. */
|
||||||
|
scratchBegin(sec: number, id = this.scratchId + 1): void {
|
||||||
|
if (!this.len) return
|
||||||
|
this.scratchId = id
|
||||||
|
const p = sec * this.srcRate
|
||||||
|
if (this.mode === 'playing') {
|
||||||
|
this.velocity = this.step
|
||||||
|
this.env = 1
|
||||||
|
} else if (!this.scratching) {
|
||||||
|
this.velocity = 0
|
||||||
|
this.env = 0
|
||||||
|
}
|
||||||
|
// The caller's position is an estimate; trust our own unless far off.
|
||||||
|
if (Math.abs(p - this.pos) > 0.25 * this.srcRate || this.pos < 0) {
|
||||||
|
this.pos = Math.max(0, Math.min(p, this.len - 1))
|
||||||
|
}
|
||||||
|
this.mode = 'drag'
|
||||||
|
this.sState = 'off'
|
||||||
|
this.grabHand(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Re-grab while the platter is still coasting: resume dragging from here.
|
||||||
|
* If the coast has already settled (its scratchDone still on its way to
|
||||||
|
* the caller), this is a fresh grab — ignoring it would leave the caller
|
||||||
|
* dragging a deck that no longer listens. */
|
||||||
|
scratchRegrab(sec?: number, id = this.scratchId + 1): void {
|
||||||
|
if (!this.len) return
|
||||||
|
if (!this.scratching) {
|
||||||
|
this.scratchBegin(sec ?? this.positionSec, id)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.scratchId = id
|
||||||
|
this.mode = 'drag'
|
||||||
|
this.grabHand(sec == null ? this.pos : sec * this.srcRate)
|
||||||
|
}
|
||||||
|
|
||||||
|
scratchTarget(sec: number): void {
|
||||||
|
if (!this.handLen) return
|
||||||
|
const x = Math.max(0, Math.min(this.len - 1, sec * this.srcRate + this.handOffset))
|
||||||
|
const now = this.clock
|
||||||
|
const last = (this.handHead + this.handLen - 1) % HAND_POINTS
|
||||||
|
const lt = this.handT[last]
|
||||||
|
// Several in one block: the newest wins (they share an arrival time).
|
||||||
|
if (now <= lt) {
|
||||||
|
this.handX[last] = x
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const gap = now - lt
|
||||||
|
if (this.handLastReal && gap < HAND_PAUSE * this.ctxRate) this.handGap = Math.max(gap, this.handGap * 0.97)
|
||||||
|
// The line already reached the last point and is holding it: start the
|
||||||
|
// move from where it is now, so the step is spread over the delay.
|
||||||
|
if (lt < now - this.handDelay) this.pushHand(now - this.handDelay, this.handX[last])
|
||||||
|
this.pushHand(now, x)
|
||||||
|
this.handLastReal = true
|
||||||
|
}
|
||||||
|
|
||||||
|
private grabHand(callerPos: number): void {
|
||||||
|
this.handOffset = this.pos - callerPos
|
||||||
|
this.handHead = 0
|
||||||
|
this.handLen = 0
|
||||||
|
this.handGap = 0
|
||||||
|
this.pushHand(this.clock - this.handDelay, this.pos)
|
||||||
|
this.handLastReal = false
|
||||||
|
}
|
||||||
|
|
||||||
|
private pushHand(t: number, x: number): void {
|
||||||
|
if (this.handLen === HAND_POINTS) {
|
||||||
|
this.handHead = (this.handHead + 1) % HAND_POINTS
|
||||||
|
this.handLen--
|
||||||
|
}
|
||||||
|
const i = (this.handHead + this.handLen) % HAND_POINTS
|
||||||
|
this.handT[i] = t
|
||||||
|
this.handX[i] = x
|
||||||
|
this.handLen++
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The hand line at clock frame `t` (points before it are dropped). */
|
||||||
|
private handAt(t: number): number {
|
||||||
|
while (this.handLen > 1 && this.handT[(this.handHead + 1) % HAND_POINTS] <= t) {
|
||||||
|
this.handHead = (this.handHead + 1) % HAND_POINTS
|
||||||
|
this.handLen--
|
||||||
|
}
|
||||||
|
const a = this.handHead
|
||||||
|
if (this.handLen < 2 || t <= this.handT[a]) return this.handX[a]
|
||||||
|
const b = (a + 1) % HAND_POINTS
|
||||||
|
return this.handX[a] + ((this.handX[b] - this.handX[a]) * (t - this.handT[a])) / (this.handT[b] - this.handT[a])
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Release the platter: coast toward playing speed (resume) or a stop. The
|
||||||
|
* deck then plays on (or stays paused) BY ITSELF — no hand-back round trip,
|
||||||
|
* so there is no gap between the coast and the music. */
|
||||||
|
scratchRelease(resume: boolean): void {
|
||||||
|
if (!this.scratching) return
|
||||||
|
this.resume = resume
|
||||||
|
this.targetVelocity = resume ? this.step : 0
|
||||||
|
this.mode = 'inertia'
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
this.disposeStretchers()
|
||||||
|
this.stems = []
|
||||||
|
this.len = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- rendering ---------------------------------------------------------
|
||||||
|
|
||||||
|
/** Render one block into `outL` / `outR` (QUANTUM frames). */
|
||||||
|
render(outL: Float32Array, outR: Float32Array): void {
|
||||||
|
const n = outL.length
|
||||||
|
const base = this.clock
|
||||||
|
this.clock += n
|
||||||
|
this.events.length = 0
|
||||||
|
if (!this.len || this.mode === 'stopped') {
|
||||||
|
outL.fill(0)
|
||||||
|
outR.fill(0)
|
||||||
|
this.advanceGains(n)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.advanceGains(n)
|
||||||
|
if (this.scratching) {
|
||||||
|
this.renderScratch(outL, outR, n, base)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const wantStretch = this.keylock && this.rb != null && Math.abs(this.rate - 1) > 1e-6
|
||||||
|
if (!wantStretch) {
|
||||||
|
this.needRewarm = false
|
||||||
|
if (this.sState === 'on') {
|
||||||
|
// Leave the stretched path: crossfade it out over this block.
|
||||||
|
this.renderStretched(this.xL, this.xR, n)
|
||||||
|
this.renderDirect(outL, outR, n)
|
||||||
|
crossfade(this.xL, this.xR, outL, outR, n)
|
||||||
|
} else {
|
||||||
|
this.renderDirect(outL, outR, n)
|
||||||
|
}
|
||||||
|
this.sState = 'off'
|
||||||
|
} else {
|
||||||
|
if (this.needRewarm || this.sState === 'off' || (this.sState === 'warming' && this.rate !== this.warmRate)) {
|
||||||
|
this.startWarm()
|
||||||
|
}
|
||||||
|
this.needRewarm = false
|
||||||
|
if (this.sState === 'warming') {
|
||||||
|
if (this.warmStep()) {
|
||||||
|
this.renderStretched(this.xL, this.xR, n)
|
||||||
|
this.renderDirect(outL, outR, n)
|
||||||
|
crossfade(outL, outR, this.xL, this.xR, n)
|
||||||
|
outL.set(this.xL)
|
||||||
|
outR.set(this.xR)
|
||||||
|
this.sState = 'on'
|
||||||
|
} else {
|
||||||
|
this.renderDirect(outL, outR, n)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.renderStretched(outL, outR, n)
|
||||||
|
this.pos = this.wrap(this.pos + this.step * n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.loopOn && this.pos >= this.len) {
|
||||||
|
this.pos = this.len
|
||||||
|
this.mode = 'stopped'
|
||||||
|
this.sState = 'off'
|
||||||
|
this.events.push('ended')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private advanceGains(n: number): void {
|
||||||
|
const a = this.gainCoef
|
||||||
|
for (let s = 0; s < this.gainBuf.length; s++) {
|
||||||
|
const buf = this.gainBuf[s]
|
||||||
|
const t = this.gainTarget[s]
|
||||||
|
let g = this.gainNow[s]
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
g = t + (g - t) * a
|
||||||
|
buf[i] = g
|
||||||
|
}
|
||||||
|
this.gainNow[s] = g
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private wrap(p: number): number {
|
||||||
|
if (this.loopOn && p >= this.loopEnd) p = this.loopStart + ((p - this.loopStart) % this.loopLen)
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sample k of channel `ch`; past a loop's end reads from its start. */
|
||||||
|
private at(ch: Float32Array, k: number, looped: boolean): number {
|
||||||
|
if (looped && k >= this.loopEnd) k -= this.loopLenI
|
||||||
|
return k >= 0 && k < this.len ? ch[k] : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cubic (Hermite) read at fractional position p. */
|
||||||
|
private read(ch: Float32Array, p: number, looped: boolean): number {
|
||||||
|
const i = Math.floor(p)
|
||||||
|
const f = p - i
|
||||||
|
const xm1 = this.at(ch, i - 1, looped)
|
||||||
|
const x0 = this.at(ch, i, looped)
|
||||||
|
const x1 = this.at(ch, i + 1, looped)
|
||||||
|
const x2 = this.at(ch, i + 2, looped)
|
||||||
|
const c1 = 0.5 * (x1 - xm1)
|
||||||
|
const c2 = xm1 - 2.5 * x0 + 2 * x1 - 0.5 * x2
|
||||||
|
const c3 = 0.5 * (x2 - xm1) + 1.5 * (x0 - x1)
|
||||||
|
return ((c3 * f + c2) * f + c1) * f + x0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mix every stem at position p, frame i of the block. */
|
||||||
|
private frame(p: number, i: number, looped: boolean, outL: Float32Array, outR: Float32Array): void {
|
||||||
|
let l = 0
|
||||||
|
let r = 0
|
||||||
|
for (let s = 0; s < this.stems.length; s++) {
|
||||||
|
const g = this.gainBuf[s][i]
|
||||||
|
if (g < 1e-5) continue
|
||||||
|
const chs = this.stems[s]
|
||||||
|
const vl = this.read(chs[0], p, looped)
|
||||||
|
l += vl * g
|
||||||
|
r += (chs.length > 1 ? this.read(chs[1], p, looped) : vl) * g
|
||||||
|
}
|
||||||
|
outL[i] = l
|
||||||
|
outR[i] = r
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The varispeed path; advances the playhead. */
|
||||||
|
private renderDirect(outL: Float32Array, outR: Float32Array, n: number): void {
|
||||||
|
const step = this.step
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
if (!this.loopOn && this.pos >= this.len) {
|
||||||
|
outL[i] = 0
|
||||||
|
outR[i] = 0
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
this.frame(this.pos, i, this.loopOn, outL, outR)
|
||||||
|
this.pos += step
|
||||||
|
if (this.loopOn && this.pos >= this.loopEnd) this.pos -= this.loopLen
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private renderScratch(outL: Float32Array, outR: Float32Array, n: number, base: number): void {
|
||||||
|
const w = this.springW
|
||||||
|
const w2 = w * w
|
||||||
|
const sr = this.ctxRate
|
||||||
|
const wantDelay = Math.max(HAND_DELAY_MIN * sr, Math.min(HAND_DELAY_MAX * sr, this.handGap * 1.2 + QUANTUM))
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
if (!this.scratching) {
|
||||||
|
// Settled mid-block: the rest of it plays (or stays silent) normally.
|
||||||
|
if (this.mode === 'playing') {
|
||||||
|
this.frame(this.pos, i, false, outL, outR)
|
||||||
|
this.pos += this.step
|
||||||
|
} else {
|
||||||
|
outL[i] = 0
|
||||||
|
outR[i] = 0
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Read, then advance — as the playing path does, so a grab or a settle
|
||||||
|
// neither skips nor repeats a sample.
|
||||||
|
const speed = Math.abs(this.velocity)
|
||||||
|
this.env += ((speed >= SCRATCH_FULL_SPEED ? 1 : speed / SCRATCH_FULL_SPEED) - this.env) * this.envCoef
|
||||||
|
this.scratchFrame(this.pos, this.velocity, i, outL, outR)
|
||||||
|
outL[i] *= this.env
|
||||||
|
outR[i] *= this.env
|
||||||
|
if (this.mode === 'drag') {
|
||||||
|
const d = wantDelay - this.handDelay
|
||||||
|
this.handDelay += d > HAND_DELAY_SLEW ? HAND_DELAY_SLEW : d < -HAND_DELAY_SLEW ? -HAND_DELAY_SLEW : d
|
||||||
|
const target = this.handAt(base + i - this.handDelay)
|
||||||
|
// Critically damped spring (semi-implicit Euler: stable at this w).
|
||||||
|
let v = this.velocity + w2 * (target - this.pos) - 2 * w * this.velocity
|
||||||
|
if (v > RATE_CAP) v = RATE_CAP
|
||||||
|
else if (v < -RATE_CAP) v = -RATE_CAP
|
||||||
|
this.velocity = v
|
||||||
|
this.pos += v
|
||||||
|
} else {
|
||||||
|
this.velocity = this.targetVelocity + (this.velocity - this.targetVelocity) * INERTIA_FRICTION
|
||||||
|
if (!this.resume && Math.abs(this.velocity) < SETTLE_EPS) this.velocity = 0
|
||||||
|
this.pos += this.velocity
|
||||||
|
if (this.resume && Math.abs(this.velocity - this.targetVelocity) < SETTLE_EPS) this.settle()
|
||||||
|
// A paused release stops once it has faded out.
|
||||||
|
else if (!this.resume && this.velocity === 0 && this.env < 1e-3) this.settle()
|
||||||
|
}
|
||||||
|
// Clamp to the track; hitting an edge kills momentum.
|
||||||
|
if (this.pos < 0) {
|
||||||
|
this.pos = 0
|
||||||
|
this.velocity = 0
|
||||||
|
if (this.mode === 'inertia') this.settle()
|
||||||
|
} else if (this.pos > this.len - 1) {
|
||||||
|
this.pos = this.len - 1
|
||||||
|
this.velocity = 0
|
||||||
|
if (this.mode === 'inertia') this.settle()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mix every stem at p for a platter moving v samples a frame: above 1x,
|
||||||
|
* the span it covered is averaged (blended in from 1x to 2x), so highs
|
||||||
|
* played past the Nyquist frequency do not fold back down as noise. */
|
||||||
|
private scratchFrame(p: number, v: number, i: number, outL: Float32Array, outR: Float32Array): void {
|
||||||
|
const av = Math.abs(v)
|
||||||
|
const box = av <= 1 ? 0 : av >= 2 ? 1 : av - 1
|
||||||
|
if (box === 0) {
|
||||||
|
this.frame(p, i, false, outL, outR)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const a = v > 0 ? p - v : p
|
||||||
|
const k = Math.ceil(av)
|
||||||
|
let l = 0
|
||||||
|
let r = 0
|
||||||
|
for (let s = 0; s < this.stems.length; s++) {
|
||||||
|
const g = this.gainBuf[s][i]
|
||||||
|
if (g < 1e-5) continue
|
||||||
|
const chs = this.stems[s]
|
||||||
|
const c0 = chs[0]
|
||||||
|
const c1 = chs.length > 1 ? chs[1] : null
|
||||||
|
const sl = this.span(c0, a, av, k)
|
||||||
|
const vl = box < 1 ? (1 - box) * this.read(c0, p, false) + box * sl : sl
|
||||||
|
l += vl * g
|
||||||
|
if (c1) {
|
||||||
|
const sr = this.span(c1, a, av, k)
|
||||||
|
r += (box < 1 ? (1 - box) * this.read(c1, p, false) + box * sr : sr) * g
|
||||||
|
} else r += vl * g
|
||||||
|
}
|
||||||
|
outL[i] = l
|
||||||
|
outR[i] = r
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mean of `ch` over [a, a + len] (trapezoid over k linear-read steps). */
|
||||||
|
private span(ch: Float32Array, a: number, len: number, k: number): number {
|
||||||
|
let sum = 0
|
||||||
|
for (let j = 0; j <= k; j++) {
|
||||||
|
const q = a + (len * j) / k
|
||||||
|
const qi = Math.floor(q)
|
||||||
|
const f = q - qi
|
||||||
|
const x = this.at(ch, qi, false) * (1 - f) + this.at(ch, qi + 1, false) * f
|
||||||
|
sum += j === 0 || j === k ? 0.5 * x : x
|
||||||
|
}
|
||||||
|
return sum / k
|
||||||
|
}
|
||||||
|
|
||||||
|
private settle(): void {
|
||||||
|
this.mode = this.resume ? 'playing' : 'stopped'
|
||||||
|
this.velocity = 0
|
||||||
|
this.needRewarm = true
|
||||||
|
this.events.push('scratchDone')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- keylock -------------------------------------------------------------
|
||||||
|
|
||||||
|
private get pitchScale(): number {
|
||||||
|
return this.srcRate / this.ctxRate
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureStretchers(): void {
|
||||||
|
if (this.stretchers.length === this.stems.length || !this.rb) return
|
||||||
|
this.disposeStretchers()
|
||||||
|
this.stretchers = this.stems.map(() => new Stretcher(this.rb!, this.srcRate, 2))
|
||||||
|
}
|
||||||
|
|
||||||
|
private disposeStretchers(): void {
|
||||||
|
for (const s of this.stretchers) s.dispose()
|
||||||
|
this.stretchers = []
|
||||||
|
this.sState = 'off'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Aim the stretchers at where the playhead will be WARM_QUANTA blocks from
|
||||||
|
* now, and start priming them. */
|
||||||
|
private startWarm(): void {
|
||||||
|
this.ensureStretchers()
|
||||||
|
const step = this.step
|
||||||
|
for (const s of this.stretchers) {
|
||||||
|
s.reset()
|
||||||
|
s.setRatios(1 / step, this.pitchScale)
|
||||||
|
}
|
||||||
|
const s0 = this.stretchers[0]
|
||||||
|
const q = Math.round(this.wrap(this.pos + WARM_QUANTA * QUANTUM * step))
|
||||||
|
this.primeLeft = s0.startPad
|
||||||
|
this.feedPos = q - this.primeLeft
|
||||||
|
this.discardLeft = s0.startDelay
|
||||||
|
this.readPtr = this.stems.map(() => q)
|
||||||
|
this.outPos = q
|
||||||
|
this.warmRate = this.rate
|
||||||
|
this.sState = 'warming'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One block's priming work. True when the stretched output is aligned with
|
||||||
|
* the playhead and a block of it is ready. */
|
||||||
|
private warmStep(): boolean {
|
||||||
|
const s0 = this.stretchers[0]
|
||||||
|
let budget = WARM_BUDGET
|
||||||
|
for (let guard = 0; guard < 64; guard++) {
|
||||||
|
if (this.primeLeft > 0) {
|
||||||
|
if (budget <= 0) return false
|
||||||
|
const k = Math.min(this.primeLeft, budget, MAX_BLOCK)
|
||||||
|
this.feedPreroll(k)
|
||||||
|
this.primeLeft -= k
|
||||||
|
budget -= k
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const avail = s0.available
|
||||||
|
if (this.discardLeft > 0) {
|
||||||
|
if (avail > 0) {
|
||||||
|
this.drop(Math.min(avail, this.discardLeft, MAX_BLOCK))
|
||||||
|
this.discardLeft -= Math.min(avail, this.discardLeft, MAX_BLOCK)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Primed: the next output frame plays source position `outPos`.
|
||||||
|
const lag = this.lagFrames()
|
||||||
|
if (lag > 0) {
|
||||||
|
// The playhead has passed it (priming ran long): skip ahead.
|
||||||
|
if (avail > 0) {
|
||||||
|
const k = Math.min(avail, lag, MAX_BLOCK)
|
||||||
|
this.drop(k)
|
||||||
|
this.outPos = this.wrap(this.outPos + k * this.step)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
} else if (lag < 0) {
|
||||||
|
return false // primed early: wait for the playhead to arrive
|
||||||
|
} else if (avail >= QUANTUM) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (budget <= 0) return false
|
||||||
|
const k = Math.min(Math.max(s0.required, 1), budget, MAX_BLOCK)
|
||||||
|
this.feedLooped(k)
|
||||||
|
budget -= k
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whole output frames from `outPos` forward to the playhead (negative =
|
||||||
|
* `outPos` is still ahead). Modulo the loop when one is engaged. */
|
||||||
|
private lagFrames(): number {
|
||||||
|
const step = this.step
|
||||||
|
let d = this.pos - this.outPos
|
||||||
|
if (this.loopOn && this.loopLen > 0) {
|
||||||
|
d = ((d % this.loopLen) + this.loopLen) % this.loopLen
|
||||||
|
if (d > this.loopLen / 2) d -= this.loopLen
|
||||||
|
}
|
||||||
|
return Math.abs(d) < step ? 0 : Math.round(d / step)
|
||||||
|
}
|
||||||
|
|
||||||
|
private drop(k: number): void {
|
||||||
|
for (const s of this.stretchers) s.retrieve(this.dropTmp, k)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pre-roll before the start point: straight, zeros outside the track. */
|
||||||
|
private feedPreroll(k: number): void {
|
||||||
|
const [tl, tr] = this.inTmp
|
||||||
|
for (let s = 0; s < this.stems.length; s++) {
|
||||||
|
const chs = this.stems[s]
|
||||||
|
for (let j = 0; j < k; j++) {
|
||||||
|
const idx = this.feedPos + j
|
||||||
|
const ok = idx >= 0 && idx < this.len
|
||||||
|
tl[j] = ok ? chs[0][idx] : 0
|
||||||
|
tr[j] = ok ? chs[chs.length > 1 ? 1 : 0][idx] : 0
|
||||||
|
}
|
||||||
|
this.stretchers[s].process(this.inTmp, k)
|
||||||
|
}
|
||||||
|
this.feedPos += k
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Feed stem s `k` frames from its read pointer, wrapping at the loop. */
|
||||||
|
private feedStem(s: number, k: number): void {
|
||||||
|
const [tl, tr] = this.inTmp
|
||||||
|
const chs = this.stems[s]
|
||||||
|
const right = chs[chs.length > 1 ? 1 : 0]
|
||||||
|
let idx = this.readPtr[s]
|
||||||
|
for (let j = 0; j < k; j++) {
|
||||||
|
if (this.loopOn && idx >= this.loopEnd) idx -= this.loopLenI
|
||||||
|
const ok = idx >= 0 && idx < this.len
|
||||||
|
tl[j] = ok ? chs[0][idx] : 0
|
||||||
|
tr[j] = ok ? right[idx] : 0
|
||||||
|
idx++
|
||||||
|
}
|
||||||
|
if (this.loopOn && idx >= this.loopEnd) idx -= this.loopLenI
|
||||||
|
this.readPtr[s] = idx
|
||||||
|
this.stretchers[s].process(this.inTmp, k)
|
||||||
|
}
|
||||||
|
|
||||||
|
private feedLooped(k: number): void {
|
||||||
|
for (let s = 0; s < this.stems.length; s++) this.feedStem(s, k)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The stretched path: a block from every stretcher, mixed with the gains.
|
||||||
|
* Leaves the playhead alone (the caller advances it). */
|
||||||
|
private renderStretched(outL: Float32Array, outR: Float32Array, n: number): void {
|
||||||
|
outL.fill(0)
|
||||||
|
outR.fill(0)
|
||||||
|
for (let s = 0; s < this.stretchers.length; s++) {
|
||||||
|
const st = this.stretchers[s]
|
||||||
|
for (let guard = 0; st.available < n && guard < 32; guard++) {
|
||||||
|
this.feedStem(s, Math.min(Math.max(st.required, 1), MAX_BLOCK))
|
||||||
|
}
|
||||||
|
const buf = this.outTmp[s]
|
||||||
|
const got = st.retrieve(buf, n)
|
||||||
|
const g = this.gainBuf[s]
|
||||||
|
for (let i = 0; i < got; i++) {
|
||||||
|
outL[i] += buf[0][i] * g[i]
|
||||||
|
outR[i] += buf[1][i] * g[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `to` = `from` fading out + `to` fading in, linearly over the block. */
|
||||||
|
function crossfade(
|
||||||
|
fromL: Float32Array,
|
||||||
|
fromR: Float32Array,
|
||||||
|
toL: Float32Array,
|
||||||
|
toR: Float32Array,
|
||||||
|
n: number,
|
||||||
|
): void {
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const t = (i + 0.5) / n
|
||||||
|
toL[i] = fromL[i] * (1 - t) + toL[i] * t
|
||||||
|
toR[i] = fromR[i] * (1 - t) + toR[i] * t
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
// The main thread's handle on one deck's audio worklet (`deckCore.ts` does the
|
||||||
|
// work). Same surface as the PlaybackEngine it replaced, plus rate, keylock
|
||||||
|
// and scratch, which used to be a separate engine on a separate AudioContext.
|
||||||
|
//
|
||||||
|
// The worklet runs on the audio thread, so every command is asynchronous. The
|
||||||
|
// engine therefore answers from its own model of the deck — the last report,
|
||||||
|
// extrapolated by the context clock, and updated at once by each command — so
|
||||||
|
// `getPosition()` right after `seek(t)` is `t`, as callers expect. Each
|
||||||
|
// position-changing command bumps a generation; a report from before it is
|
||||||
|
// ignored, so a stale position can never snap the playhead back.
|
||||||
|
|
||||||
|
import type { DecodedAudio } from '../waveform'
|
||||||
|
import { audioContext, loadDeckWorklet, resumeAudio } from './context'
|
||||||
|
import type { DeckCommand, DeckInbound, DeckOutbound } from './deckProcessor.worklet'
|
||||||
|
import { extrapolate, type Loop, type Model } from './position'
|
||||||
|
|
||||||
|
/** As `deckCore`'s: the furthest a lead-in reaches before the track (s). */
|
||||||
|
const LEAD_IN_SEC = 32
|
||||||
|
|
||||||
|
export class DeckEngine {
|
||||||
|
readonly output: GainNode
|
||||||
|
private readonly ctx: AudioContext
|
||||||
|
private readonly node: AudioWorkletNode
|
||||||
|
private gen = 0
|
||||||
|
private m: Model = { pos: 0, time: 0, speed: 0, playing: false, scratching: false }
|
||||||
|
private loop: Loop = { start: 0, end: 0, on: false }
|
||||||
|
private rate = 1
|
||||||
|
private leadIn = false
|
||||||
|
private _duration = 0
|
||||||
|
private _keylockAvailable = false
|
||||||
|
private onEnded: (() => void) | null = null
|
||||||
|
private onScratchDone: ((playing: boolean) => void) | null = null
|
||||||
|
/** The latest grab's id: a scratchDone for an earlier one is superseded. */
|
||||||
|
private scratchSeq = 0
|
||||||
|
|
||||||
|
/** The worklet module loads asynchronously, once per app. `destination` is
|
||||||
|
* where the deck plays into: its mixer channel. */
|
||||||
|
static async create(destination: AudioNode): Promise<DeckEngine> {
|
||||||
|
const wasm = await loadDeckWorklet()
|
||||||
|
return new DeckEngine(wasm, destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
private constructor(wasm: ArrayBuffer | null, destination: AudioNode) {
|
||||||
|
this.ctx = audioContext()
|
||||||
|
this.node = new AudioWorkletNode(this.ctx, 'konduktor-deck', {
|
||||||
|
numberOfInputs: 0,
|
||||||
|
numberOfOutputs: 1,
|
||||||
|
outputChannelCount: [2],
|
||||||
|
processorOptions: { wasm },
|
||||||
|
})
|
||||||
|
this.output = this.ctx.createGain()
|
||||||
|
this.node.connect(this.output)
|
||||||
|
this.output.connect(destination)
|
||||||
|
this.node.port.onmessage = (e: MessageEvent<DeckOutbound>) => this.receive(e.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
private receive(msg: DeckOutbound): void {
|
||||||
|
if (msg.type === 'error') {
|
||||||
|
console.warn(msg.message)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (msg.type === 'event' && msg.event === 'scratchDone') {
|
||||||
|
// NOT filtered by generation: a command sent while the coast settled (a
|
||||||
|
// pitch fader's trickle of rate changes) would drop it, leaving the deck
|
||||||
|
// "scratching" for good — every later grab a re-grab the audio thread
|
||||||
|
// ignores. Only a newer grab supersedes it.
|
||||||
|
if (msg.scratch !== this.scratchSeq) return
|
||||||
|
const current = msg.gen === this.gen
|
||||||
|
const playing = current ? msg.playing : this.m.playing
|
||||||
|
this.m = current
|
||||||
|
? { ...this.m, pos: msg.pos, time: this.ctx.currentTime, speed: playing ? this.rate : 0, playing, scratching: false }
|
||||||
|
: { ...this.m, scratching: false }
|
||||||
|
this.onScratchDone?.(playing)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (msg.gen !== this.gen) return // a report from before the latest command
|
||||||
|
if (msg.type === 'state') {
|
||||||
|
this._keylockAvailable = msg.keylockAvailable
|
||||||
|
this.m = { pos: msg.pos, time: msg.time, speed: msg.speed, playing: msg.playing, scratching: msg.scratching }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.m = { ...this.m, pos: msg.pos, time: this.ctx.currentTime, speed: msg.playing ? this.rate : 0, playing: msg.playing, scratching: false }
|
||||||
|
this.onEnded?.()
|
||||||
|
}
|
||||||
|
|
||||||
|
private send(cmd: DeckCommand, positional = true): void {
|
||||||
|
if (positional) this.gen++
|
||||||
|
const m: DeckInbound = { type: 'cmd', gen: this.gen, cmd }
|
||||||
|
this.node.port.postMessage(m)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Re-take the model at "now" before a change, so the change starts from
|
||||||
|
* the true position. */
|
||||||
|
private reanchor(): void {
|
||||||
|
this.m = { ...this.m, pos: this.getPosition(), time: this.ctx.currentTime }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- loading ------------------------------------------------------------
|
||||||
|
|
||||||
|
/** One track, or several stems played in lockstep. The PCM is TRANSFERRED to
|
||||||
|
* the audio thread: the caller must not use these arrays afterwards. */
|
||||||
|
load(audio: DecodedAudio | DecodedAudio[]): void {
|
||||||
|
const list = Array.isArray(audio) ? audio : [audio]
|
||||||
|
const length = Math.min(...list.map((a) => a.length))
|
||||||
|
const sampleRate = list[0].sampleRate
|
||||||
|
const stems = list.map((a) => a.channels)
|
||||||
|
const transfer = [...new Set(stems.flat().map((c) => c.buffer as ArrayBuffer))]
|
||||||
|
this.gen++
|
||||||
|
const m: DeckInbound = { type: 'load', gen: this.gen, source: { stems, length, sampleRate } }
|
||||||
|
this.node.port.postMessage(m, transfer)
|
||||||
|
this._duration = length / sampleRate
|
||||||
|
this.m = { pos: 0, time: this.ctx.currentTime, speed: 0, playing: false, scratching: false }
|
||||||
|
this.loop = { start: 0, end: 0, on: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
setOnEnded(cb: () => void): void {
|
||||||
|
this.onEnded = cb
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Called when a scratch's coast settles; the deck is then playing (if the
|
||||||
|
* release asked to resume) or paused — it hands itself back. */
|
||||||
|
setOnScratchDone(cb: (playing: boolean) => void): void {
|
||||||
|
this.onScratchDone = cb
|
||||||
|
}
|
||||||
|
|
||||||
|
get ready(): boolean {
|
||||||
|
return this._duration > 0
|
||||||
|
}
|
||||||
|
get duration(): number {
|
||||||
|
return this._duration
|
||||||
|
}
|
||||||
|
get playing(): boolean {
|
||||||
|
return this.m.playing
|
||||||
|
}
|
||||||
|
get scratching(): boolean {
|
||||||
|
return this.m.scratching
|
||||||
|
}
|
||||||
|
get loopEnabled(): boolean {
|
||||||
|
return this.loop.on
|
||||||
|
}
|
||||||
|
/** Rubber Band loaded in the worklet (known after its first report). */
|
||||||
|
get keylockAvailable(): boolean {
|
||||||
|
return this._keylockAvailable
|
||||||
|
}
|
||||||
|
|
||||||
|
getPosition(): number {
|
||||||
|
return extrapolate(this.m, this.ctx.currentTime, this.loop, this._duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- transport ------------------------------------------------------------
|
||||||
|
|
||||||
|
play(): void {
|
||||||
|
if (!this.ready || this.m.playing) return
|
||||||
|
resumeAudio()
|
||||||
|
let pos = this.m.pos
|
||||||
|
if (pos >= this._duration - 0.01) pos = 0 // restart from the top at the end
|
||||||
|
this.m = { pos, time: this.ctx.currentTime, speed: this.rate, playing: true, scratching: false }
|
||||||
|
this.send({ op: 'play' })
|
||||||
|
}
|
||||||
|
|
||||||
|
pause(): void {
|
||||||
|
if (!this.m.playing) return
|
||||||
|
this.m = { ...this.m, pos: this.getPosition(), time: this.ctx.currentTime, speed: 0, playing: false }
|
||||||
|
this.send({ op: 'pause' })
|
||||||
|
}
|
||||||
|
|
||||||
|
seek(t: number): void {
|
||||||
|
const end = this.loop.on ? Math.max(this._duration, this.loop.end) : this._duration
|
||||||
|
const sec = Math.max(this.leadIn ? -LEAD_IN_SEC : 0, Math.min(t, end))
|
||||||
|
this.m = { ...this.m, pos: sec, time: this.ctx.currentTime }
|
||||||
|
this.send({ op: 'seek', sec })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Set the loop region and whether it is active. Bounds apply live if playing. */
|
||||||
|
setLoop(start: number, end: number, enabled: boolean): void {
|
||||||
|
this.reanchor()
|
||||||
|
this.loop = { start, end, on: enabled && end > start }
|
||||||
|
if (this.loop.on && this.m.pos >= end) this.m = { ...this.m, pos: start }
|
||||||
|
this.send({ op: 'loop', start, end, on: enabled })
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoopEnabled(enabled: boolean): void {
|
||||||
|
this.setLoop(this.loop.start, this.loop.end, enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Per-stem levels (0 = muted) — the stems' mute/solo. Ramped, not stepped. */
|
||||||
|
setGains(levels: number[]): void {
|
||||||
|
this.send({ op: 'gains', levels }, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Playback speed (1 = the file's own tempo): the pitch fader. */
|
||||||
|
setRate(rate: number): void {
|
||||||
|
this.reanchor()
|
||||||
|
this.rate = rate
|
||||||
|
if (this.m.playing) this.m = { ...this.m, speed: rate }
|
||||||
|
this.send({ op: 'rate', rate })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Performance mode: a seek may land before the track (silence until it
|
||||||
|
* starts) — and a loop may reach past its end. */
|
||||||
|
setLeadIn(on: boolean): void {
|
||||||
|
this.leadIn = on
|
||||||
|
if (!on && this.m.pos < 0) this.m = { ...this.m, pos: 0, time: this.ctx.currentTime }
|
||||||
|
this.send({ op: 'leadIn', on })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keylock: keep the pitch while the rate changes. */
|
||||||
|
setKeylock(on: boolean): void {
|
||||||
|
this.send({ op: 'keylock', on }, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- scratch ----------------------------------------------------------------
|
||||||
|
|
||||||
|
scratchBegin(sec: number): void {
|
||||||
|
resumeAudio()
|
||||||
|
this.m = { pos: sec, time: this.ctx.currentTime, speed: 0, playing: false, scratching: true }
|
||||||
|
this.send({ op: 'scratchBegin', sec, id: ++this.scratchSeq })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Re-grab while the platter is still coasting; later targets move
|
||||||
|
* relative to `sec`. */
|
||||||
|
scratchRegrab(sec: number): void {
|
||||||
|
this.send({ op: 'scratchRegrab', sec, id: ++this.scratchSeq }, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
scratchTarget(sec: number): void {
|
||||||
|
this.send({ op: 'scratchTarget', sec }, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Release the platter: coast to playing speed (resume) or to a stop. */
|
||||||
|
scratchRelease(resume: boolean): void {
|
||||||
|
this.send({ op: 'scratchRelease', resume }, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
const m: DeckInbound = { type: 'dispose' }
|
||||||
|
this.node.port.postMessage(m)
|
||||||
|
this.node.disconnect()
|
||||||
|
this.output.disconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
// The deck's AudioWorkletProcessor: a thin shell around DeckCore (see there).
|
||||||
|
// Loaded once per AudioContext by `context.ts` (`?worker&url`, so Vite bundles
|
||||||
|
// its imports). Commands arrive on the port and apply before the next block;
|
||||||
|
// the playhead is reported at the START of a block, stamped with that block's
|
||||||
|
// context time, so the main thread can extrapolate it smoothly.
|
||||||
|
|
||||||
|
import { DeckCore, type DeckSource } from './deckCore'
|
||||||
|
import { RubberBand } from './stretcher'
|
||||||
|
|
||||||
|
// AudioWorkletGlobalScope — not in TypeScript's DOM lib.
|
||||||
|
declare const sampleRate: number
|
||||||
|
declare const currentTime: number
|
||||||
|
declare function registerProcessor(name: string, ctor: unknown): void
|
||||||
|
declare class AudioWorkletProcessor {
|
||||||
|
readonly port: MessagePort
|
||||||
|
constructor(options?: unknown)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Report the playhead every this many blocks (~5.8 ms at 44.1 kHz), and
|
||||||
|
* always on the block after a command. */
|
||||||
|
const REPORT_EVERY = 2
|
||||||
|
|
||||||
|
export type DeckCommand =
|
||||||
|
| { op: 'play' }
|
||||||
|
| { op: 'pause' }
|
||||||
|
| { op: 'seek'; sec: number }
|
||||||
|
| { op: 'loop'; start: number; end: number; on: boolean }
|
||||||
|
| { op: 'gains'; levels: number[] }
|
||||||
|
| { op: 'rate'; rate: number }
|
||||||
|
| { op: 'keylock'; on: boolean }
|
||||||
|
| { op: 'leadIn'; on: boolean }
|
||||||
|
| { op: 'scratchBegin'; sec: number; id: number }
|
||||||
|
| { op: 'scratchRegrab'; sec: number; id: number }
|
||||||
|
| { op: 'scratchTarget'; sec: number }
|
||||||
|
| { op: 'scratchRelease'; resume: boolean }
|
||||||
|
|
||||||
|
export type DeckInbound =
|
||||||
|
| { type: 'load'; gen: number; source: DeckSource }
|
||||||
|
| { type: 'cmd'; gen: number; cmd: DeckCommand }
|
||||||
|
| { type: 'dispose' }
|
||||||
|
|
||||||
|
export interface DeckReport {
|
||||||
|
type: 'state'
|
||||||
|
/** The last position-changing command applied. */
|
||||||
|
gen: number
|
||||||
|
/** Context time of the block this position starts. */
|
||||||
|
time: number
|
||||||
|
pos: number
|
||||||
|
speed: number
|
||||||
|
playing: boolean
|
||||||
|
scratching: boolean
|
||||||
|
keylockAvailable: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DeckOutbound =
|
||||||
|
| DeckReport
|
||||||
|
| {
|
||||||
|
type: 'event'
|
||||||
|
event: 'ended' | 'scratchDone'
|
||||||
|
gen: number
|
||||||
|
/** The grab (`scratchBegin` / `scratchRegrab` id) a scratchDone ends. */
|
||||||
|
scratch: number
|
||||||
|
pos: number
|
||||||
|
playing: boolean
|
||||||
|
}
|
||||||
|
| { type: 'error'; message: string }
|
||||||
|
|
||||||
|
class DeckProcessor extends AudioWorkletProcessor {
|
||||||
|
private readonly core: DeckCore
|
||||||
|
private readonly rbOk: boolean
|
||||||
|
private gen = 0
|
||||||
|
private tick = 0
|
||||||
|
private dirty = true
|
||||||
|
private alive = true
|
||||||
|
|
||||||
|
constructor(options: { processorOptions?: { wasm?: ArrayBuffer | null } }) {
|
||||||
|
super()
|
||||||
|
let rb: RubberBand | null = null
|
||||||
|
const wasm = options.processorOptions?.wasm
|
||||||
|
if (wasm) {
|
||||||
|
try {
|
||||||
|
rb = new RubberBand(new WebAssembly.Module(wasm))
|
||||||
|
} catch (e) {
|
||||||
|
this.port.postMessage({ type: 'error', message: `keylock unavailable: ${e}` })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.rbOk = rb != null
|
||||||
|
this.core = new DeckCore(sampleRate, rb)
|
||||||
|
this.port.onmessage = (e: MessageEvent<DeckInbound>) => this.receive(e.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
private receive(m: DeckInbound): void {
|
||||||
|
if (m.type === 'dispose') {
|
||||||
|
this.core.dispose()
|
||||||
|
this.alive = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.gen = m.gen
|
||||||
|
this.dirty = true
|
||||||
|
if (m.type === 'load') {
|
||||||
|
this.core.load(m.source)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const c = m.cmd
|
||||||
|
const core = this.core
|
||||||
|
switch (c.op) {
|
||||||
|
case 'play':
|
||||||
|
return core.play()
|
||||||
|
case 'pause':
|
||||||
|
return core.pause()
|
||||||
|
case 'seek':
|
||||||
|
return core.seek(c.sec)
|
||||||
|
case 'loop':
|
||||||
|
return core.setLoop(c.start, c.end, c.on)
|
||||||
|
case 'gains':
|
||||||
|
return core.setGains(c.levels)
|
||||||
|
case 'rate':
|
||||||
|
return core.setRate(c.rate)
|
||||||
|
case 'keylock':
|
||||||
|
return core.setKeylock(c.on)
|
||||||
|
case 'leadIn':
|
||||||
|
return core.setLeadIn(c.on)
|
||||||
|
case 'scratchBegin':
|
||||||
|
return core.scratchBegin(c.sec, c.id)
|
||||||
|
case 'scratchRegrab':
|
||||||
|
return core.scratchRegrab(c.sec, c.id)
|
||||||
|
case 'scratchTarget':
|
||||||
|
return core.scratchTarget(c.sec)
|
||||||
|
case 'scratchRelease':
|
||||||
|
return core.scratchRelease(c.resume)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
process(_inputs: Float32Array[][], outputs: Float32Array[][]): boolean {
|
||||||
|
if (!this.alive) return false
|
||||||
|
const out = outputs[0]
|
||||||
|
if (this.dirty || ++this.tick >= REPORT_EVERY) {
|
||||||
|
this.tick = 0
|
||||||
|
this.dirty = false
|
||||||
|
const core = this.core
|
||||||
|
const report: DeckReport = {
|
||||||
|
type: 'state',
|
||||||
|
gen: this.gen,
|
||||||
|
time: currentTime,
|
||||||
|
pos: core.positionSec,
|
||||||
|
speed: core.speed,
|
||||||
|
playing: core.playing,
|
||||||
|
scratching: core.scratching,
|
||||||
|
keylockAvailable: this.rbOk,
|
||||||
|
}
|
||||||
|
this.port.postMessage(report)
|
||||||
|
}
|
||||||
|
this.core.render(out[0], out[1] ?? out[0])
|
||||||
|
for (const event of this.core.events) {
|
||||||
|
this.port.postMessage({
|
||||||
|
type: 'event',
|
||||||
|
event,
|
||||||
|
gen: this.gen,
|
||||||
|
scratch: this.core.scratchId,
|
||||||
|
pos: this.core.positionSec,
|
||||||
|
playing: this.core.playing,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
registerProcessor('konduktor-deck', DeckProcessor)
|
||||||
@@ -0,0 +1,479 @@
|
|||||||
|
// The mixer's audio graph (performance mode, decided 2026-11-02). Both decks
|
||||||
|
// play into it; it follows the controls in `mixerState.ts`.
|
||||||
|
//
|
||||||
|
// deck → gain → 3-band isolator → fader → filter FX ─┬→ crossfader → bus
|
||||||
|
// └→ meter
|
||||||
|
//
|
||||||
|
// The filter FX is POST-fader, so pulling the fader down stops feeding the
|
||||||
|
// reverb / delay and their tails ring out instead of being cut with it.
|
||||||
|
// bus → limiter → master meter → speakers
|
||||||
|
//
|
||||||
|
// GAIN (`trim` in the state) starts at the track's own auto gain (the DJ app's, `Track.auto_gain_db`;
|
||||||
|
// none = 0 dB) plus the knob. The ISOLATOR splits at 250 Hz / 2.5 kHz with
|
||||||
|
// Linkwitz-Riley (LR4) crossovers, the low band through an all-pass matching
|
||||||
|
// the upper crossover, so the three bands sum back to flat — measured to 0.0001
|
||||||
|
// dB — and a band can be cut to silence (`eqKill`). Web Audio's lowpass /
|
||||||
|
// highpass Q is in dB (Butterworth = -3.01) while its allpass Q is linear.
|
||||||
|
// The LIMITER is a DynamicsCompressor set as one (-1.5 dBFS, 20:1, 1 ms), and
|
||||||
|
// `levels().limiting` is its gain reduction. Web Audio's compressor adds an
|
||||||
|
// automatic MAKE-UP gain — (1 / its gain at 0 dBFS)^0.6, +0.57 dB at -1 / 20:1
|
||||||
|
// — which raised everything in circuit and let two loud decks peak at +0.3
|
||||||
|
// dBFS (measured); a gain after it takes exactly that back off.
|
||||||
|
//
|
||||||
|
// Outside performance mode the mixer is BYPASSED: deck A goes straight to the
|
||||||
|
// speakers, as the prep deck always has, deck B is silent, and the limiter is
|
||||||
|
// out of the path — so prep listening is unchanged.
|
||||||
|
|
||||||
|
import { audioContext } from './context'
|
||||||
|
import {
|
||||||
|
beatSeconds,
|
||||||
|
dbToGain,
|
||||||
|
eqGain,
|
||||||
|
EQ_HIGH_HZ,
|
||||||
|
EQ_LOW_HZ,
|
||||||
|
delayBeatsAt,
|
||||||
|
faderGain,
|
||||||
|
filterSweep,
|
||||||
|
sweepBeatsAt,
|
||||||
|
REVERB_GROWTH,
|
||||||
|
FX_CENTRE,
|
||||||
|
TRIM_RANGE_DB,
|
||||||
|
xfadeGains,
|
||||||
|
} from './mixerMath'
|
||||||
|
import { getMixerState, rangeFor, subscribeMixer, type Channel, type ChannelState, type FxSettings, type FxType } from './mixerState'
|
||||||
|
|
||||||
|
/** Butterworth Q in Web Audio's lowpass/highpass units (dB). */
|
||||||
|
const BUTTERWORTH_DB = 20 * Math.log10(Math.SQRT1_2)
|
||||||
|
const LIMIT_DB = -1.5
|
||||||
|
const LIMIT_RATIO = 20
|
||||||
|
/** The compressor's automatic make-up gain (Web Audio spec: the inverse of its
|
||||||
|
* gain at 0 dBFS, to the power 0.6), in dB. */
|
||||||
|
const MAKEUP_DB = -0.6 * (LIMIT_DB + (0 - LIMIT_DB) / LIMIT_RATIO)
|
||||||
|
|
||||||
|
/** The flanger's delay sweeps between these (s). */
|
||||||
|
const FLANGE_MIN = 0.0007
|
||||||
|
const FLANGE_MAX = 0.007
|
||||||
|
|
||||||
|
/** The longest delay (s): 8 × a 1-beat setting at 120 BPM. */
|
||||||
|
const MAX_DELAY_S = 4
|
||||||
|
|
||||||
|
/** Parameter smoothing (s): fast enough to feel direct, slow enough not to click. */
|
||||||
|
const GLIDE = 0.012
|
||||||
|
|
||||||
|
function ramp(param: AudioParam, value: number, ctx: AudioContext, tau = GLIDE): void {
|
||||||
|
param.setTargetAtTime(value, ctx.currentTime, tau)
|
||||||
|
}
|
||||||
|
|
||||||
|
function biquad(ctx: AudioContext, type: BiquadFilterType, freq: number, q: number): BiquadFilterNode {
|
||||||
|
const f = ctx.createBiquadFilter()
|
||||||
|
f.type = type
|
||||||
|
f.frequency.value = freq
|
||||||
|
f.Q.value = q
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Two cascaded Butterworth sections: one LR4 half. */
|
||||||
|
function lr4(ctx: AudioContext, type: 'lowpass' | 'highpass', freq: number): [BiquadFilterNode, BiquadFilterNode] {
|
||||||
|
const a = biquad(ctx, type, freq, BUTTERWORTH_DB)
|
||||||
|
const b = biquad(ctx, type, freq, BUTTERWORTH_DB)
|
||||||
|
a.connect(b)
|
||||||
|
return [a, b]
|
||||||
|
}
|
||||||
|
|
||||||
|
function noiseBuffer(ctx: AudioContext, seconds: number): AudioBuffer {
|
||||||
|
const buf = ctx.createBuffer(2, Math.round(ctx.sampleRate * seconds), ctx.sampleRate)
|
||||||
|
for (let c = 0; c < 2; c++) {
|
||||||
|
const d = buf.getChannelData(c)
|
||||||
|
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1
|
||||||
|
}
|
||||||
|
return buf
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A reverb impulse: stereo noise decaying 60 dB over `seconds`. */
|
||||||
|
function impulse(ctx: AudioContext, seconds: number): AudioBuffer {
|
||||||
|
const buf = noiseBuffer(ctx, seconds)
|
||||||
|
const k = -6.9 / (seconds * ctx.sampleRate)
|
||||||
|
for (let c = 0; c < 2; c++) {
|
||||||
|
const d = buf.getChannelData(c)
|
||||||
|
for (let i = 0; i < d.length; i++) d[i] *= Math.exp(k * i)
|
||||||
|
}
|
||||||
|
return buf
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A bit-crusher's transfer curve at `bits` of resolution. */
|
||||||
|
function crushCurve(bits: number): Float32Array<ArrayBuffer> {
|
||||||
|
const n = 2048
|
||||||
|
const steps = 2 ** bits / 2
|
||||||
|
const curve = new Float32Array(n)
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const x = (i / (n - 1)) * 2 - 1
|
||||||
|
curve[i] = Math.round(x * steps) / steps
|
||||||
|
}
|
||||||
|
return curve
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One channel's FILTER FX (decided 2026-11-03, after Traktor's mixer): ONE
|
||||||
|
* knob, -1..1, out of the path at the centre. It always FILTERS — low-pass
|
||||||
|
* left, high-pass right; over the `filterRange` setting for the Filter alone,
|
||||||
|
* the musical range under an effect (`rangeFor`) — and the channel's
|
||||||
|
* chosen effect rides with it, fed the FILTERED signal, its amount growing
|
||||||
|
* with the knob — and the more filter, the longer the reverb and delay and
|
||||||
|
* the faster the flanger: Reverb and Delay are sends whose tails ring out
|
||||||
|
* after the knob returns (echo- and wash-outs); Bit crusher replaces the
|
||||||
|
* filtered signal with a crushed copy; Flanger mixes it with a few-ms delay
|
||||||
|
* swept by a beat-synced LFO, with feedback.
|
||||||
|
* `filter` is the filter alone. Everything is built
|
||||||
|
* once and switched by gains, so a change never clicks. Each effect's one
|
||||||
|
* parameter is an app setting (`FxSettings`).
|
||||||
|
*/
|
||||||
|
class FilterFx {
|
||||||
|
readonly input: GainNode
|
||||||
|
readonly output: GainNode
|
||||||
|
private readonly ctx: AudioContext
|
||||||
|
private readonly dry: GainNode
|
||||||
|
/** Two stages, 24 dB/octave: the first Butterworth, the second carrying the
|
||||||
|
* resonance. One 12 dB stage left a 100 Hz bass only 28 dB down at the end
|
||||||
|
* of a full-range low-pass (measured) — not the near-silence asked for. */
|
||||||
|
private readonly filterIn: BiquadFilterNode
|
||||||
|
private readonly filter: BiquadFilterNode
|
||||||
|
/** The filtered music itself (every effect but Bit crusher keeps it). */
|
||||||
|
private readonly filtered: GainNode
|
||||||
|
// Reverb: sends into a SHORT and a LONG convolver; the knob blends from one
|
||||||
|
// into the other (re-generating one impulse instead would cut its tail).
|
||||||
|
private readonly reverbShort: GainNode
|
||||||
|
private readonly reverbLong: GainNode
|
||||||
|
private readonly convShort: ConvolverNode
|
||||||
|
private readonly convLong: ConvolverNode
|
||||||
|
private reverbSize = -1
|
||||||
|
// Delay: a send into a delay with filtered feedback.
|
||||||
|
private readonly delaySend: GainNode
|
||||||
|
private readonly delay: DelayNode
|
||||||
|
private readonly delayTone: BiquadFilterNode
|
||||||
|
private readonly feedback: GainNode
|
||||||
|
// Bit crusher.
|
||||||
|
private readonly crushDrive: GainNode
|
||||||
|
private readonly shaper: WaveShaperNode
|
||||||
|
private readonly crushWet: GainNode
|
||||||
|
private crushBits = -1
|
||||||
|
// Flanger: a few-ms delay swept by one LFO, with feedback.
|
||||||
|
private readonly lfo: OscillatorNode
|
||||||
|
private readonly flange: DelayNode
|
||||||
|
private readonly flangeFeedback: GainNode
|
||||||
|
private readonly flangerWet: GainNode
|
||||||
|
|
||||||
|
constructor(ctx: AudioContext) {
|
||||||
|
this.ctx = ctx
|
||||||
|
this.input = ctx.createGain()
|
||||||
|
this.output = ctx.createGain()
|
||||||
|
this.dry = ctx.createGain()
|
||||||
|
this.input.connect(this.dry).connect(this.output)
|
||||||
|
|
||||||
|
this.filterIn = biquad(ctx, 'lowpass', 20000, BUTTERWORTH_DB)
|
||||||
|
this.filter = biquad(ctx, 'lowpass', 20000, 0)
|
||||||
|
this.input.connect(this.filterIn).connect(this.filter)
|
||||||
|
this.filtered = ctx.createGain()
|
||||||
|
this.filtered.gain.value = 0
|
||||||
|
this.filter.connect(this.filtered).connect(this.output)
|
||||||
|
|
||||||
|
this.reverbShort = ctx.createGain()
|
||||||
|
this.reverbShort.gain.value = 0
|
||||||
|
this.reverbLong = ctx.createGain()
|
||||||
|
this.reverbLong.gain.value = 0
|
||||||
|
this.convShort = ctx.createConvolver()
|
||||||
|
this.convLong = ctx.createConvolver()
|
||||||
|
this.filter.connect(this.reverbShort).connect(this.convShort).connect(this.output)
|
||||||
|
this.filter.connect(this.reverbLong).connect(this.convLong).connect(this.output)
|
||||||
|
|
||||||
|
this.delaySend = ctx.createGain()
|
||||||
|
this.delaySend.gain.value = 0
|
||||||
|
this.delay = ctx.createDelay(MAX_DELAY_S + 0.1)
|
||||||
|
this.delayTone = biquad(ctx, 'lowpass', 2500, 0)
|
||||||
|
this.feedback = ctx.createGain()
|
||||||
|
this.feedback.gain.value = 0.45
|
||||||
|
this.filter.connect(this.delaySend).connect(this.delay)
|
||||||
|
this.delay.connect(this.delayTone).connect(this.feedback).connect(this.delay)
|
||||||
|
this.delay.connect(this.output)
|
||||||
|
|
||||||
|
this.crushDrive = ctx.createGain()
|
||||||
|
this.shaper = ctx.createWaveShaper()
|
||||||
|
this.crushWet = ctx.createGain()
|
||||||
|
this.crushWet.gain.value = 0
|
||||||
|
this.filter.connect(this.crushDrive).connect(this.shaper).connect(this.crushWet).connect(this.output)
|
||||||
|
|
||||||
|
// A delay swept between FLANGE_MIN and FLANGE_MAX by the LFO, fed back
|
||||||
|
// into itself; mixed with the filtered music its comb notches sweep.
|
||||||
|
this.lfo = ctx.createOscillator()
|
||||||
|
this.lfo.frequency.value = 0.5
|
||||||
|
this.flange = ctx.createDelay(0.05)
|
||||||
|
this.flange.delayTime.value = (FLANGE_MIN + FLANGE_MAX) / 2
|
||||||
|
const depth = ctx.createGain()
|
||||||
|
depth.gain.value = (FLANGE_MAX - FLANGE_MIN) / 2
|
||||||
|
this.lfo.connect(depth).connect(this.flange.delayTime)
|
||||||
|
this.flangeFeedback = ctx.createGain()
|
||||||
|
this.flangeFeedback.gain.value = 0
|
||||||
|
this.flangerWet = ctx.createGain()
|
||||||
|
this.flangerWet.gain.value = 0
|
||||||
|
this.filter.connect(this.flange)
|
||||||
|
this.flange.connect(this.flangeFeedback).connect(this.flange)
|
||||||
|
this.flange.connect(this.flangerWet).connect(this.output)
|
||||||
|
this.lfo.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
apply(type: FxType, knob: number, fx: FxSettings, bpm: number): void {
|
||||||
|
const ctx = this.ctx
|
||||||
|
const a = Math.min(1, Math.abs(knob))
|
||||||
|
const on = a >= FX_CENTRE
|
||||||
|
// The filtered path replaces the dry one over the first few percent of
|
||||||
|
// the knob, so leaving the centre never jumps.
|
||||||
|
const take = on ? Math.min(1, a / 0.06) : 0
|
||||||
|
const sweep = filterSweep(knob, rangeFor(type, fx))
|
||||||
|
if (sweep) {
|
||||||
|
if (this.filter.type !== sweep.type) {
|
||||||
|
this.filterIn.type = sweep.type
|
||||||
|
this.filter.type = sweep.type
|
||||||
|
}
|
||||||
|
ramp(this.filterIn.frequency, sweep.freq, ctx)
|
||||||
|
ramp(this.filter.frequency, sweep.freq, ctx)
|
||||||
|
// Resonance fades over the last stretch: a resonant peak at 20 Hz (or
|
||||||
|
// 20 kHz) at the end of a full sweep would be a boom (or a whistle).
|
||||||
|
ramp(this.filter.Q, fx.filterResonance * 15 * (1 - a ** 4), ctx)
|
||||||
|
}
|
||||||
|
ramp(this.dry.gain, 1 - take, ctx)
|
||||||
|
|
||||||
|
// How much of the filtered music stays: all of it, but half under the
|
||||||
|
// flanger (whose notches come from mixing the two) and none under the
|
||||||
|
// crusher (which replaces it).
|
||||||
|
const flanging = type === 'flanger' && on
|
||||||
|
const mix = flanging ? Math.min(1, a / 0.25) : 0
|
||||||
|
const crushing = type === 'crusher' && on
|
||||||
|
ramp(this.filtered.gain, crushing ? 0 : take * (1 - 0.5 * mix), ctx)
|
||||||
|
ramp(this.flangerWet.gain, take * 0.5 * mix, ctx)
|
||||||
|
// The sweep speeds up and the feedback (the "jet") deepens as it opens.
|
||||||
|
ramp(this.flangeFeedback.gain, flanging ? 0.3 + 0.5 * a : 0, ctx, 0.05)
|
||||||
|
if (type === 'flanger') ramp(this.lfo.frequency, 1 / beatSeconds(sweepBeatsAt(fx.flangerBeats, a), bpm), ctx, 0.05)
|
||||||
|
|
||||||
|
// Reverb: the send grows with the knob, and moves from the short reverb
|
||||||
|
// into the long one — the more filter, the longer the tail.
|
||||||
|
const reverbing = type === 'reverb' && on
|
||||||
|
ramp(this.reverbShort.gain, reverbing ? a * (1 - a) : 0, ctx)
|
||||||
|
ramp(this.reverbLong.gain, reverbing ? a * a : 0, ctx)
|
||||||
|
if (type === 'reverb') {
|
||||||
|
const size = Math.round(Math.max(0.3, Math.min(6, fx.reverbSize)) * 10) / 10
|
||||||
|
if (size !== this.reverbSize) {
|
||||||
|
this.reverbSize = size
|
||||||
|
this.convShort.buffer = impulse(ctx, size)
|
||||||
|
this.convLong.buffer = impulse(ctx, Math.min(12, size * REVERB_GROWTH))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delay: send, feedback AND length grow with the knob (the length in
|
||||||
|
// doubling steps, `delayBeatsAt`); the repeats darken (left) or thin
|
||||||
|
// (right) as they go round.
|
||||||
|
const delaying = type === 'delay' && on
|
||||||
|
ramp(this.delaySend.gain, delaying ? a * 0.8 : 0, ctx)
|
||||||
|
ramp(this.feedback.gain, delaying ? 0.35 + 0.5 * a : 0.45, ctx, 0.05)
|
||||||
|
if (type === 'delay') {
|
||||||
|
ramp(this.delay.delayTime, Math.min(MAX_DELAY_S, beatSeconds(delayBeatsAt(fx.delayBeats, a), bpm)), ctx, 0.05)
|
||||||
|
const tone = knob < 0 ? 'lowpass' : 'highpass'
|
||||||
|
if (this.delayTone.type !== tone) this.delayTone.type = tone
|
||||||
|
ramp(this.delayTone.frequency, knob < 0 ? 2500 : 600, ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bit crusher: fewer bits as the knob opens (16 → 3), driven by the setting.
|
||||||
|
if (crushing) {
|
||||||
|
const bits = Math.round(16 - a * 13)
|
||||||
|
if (bits !== this.crushBits) {
|
||||||
|
this.crushBits = bits
|
||||||
|
this.shaper.curve = crushCurve(bits)
|
||||||
|
}
|
||||||
|
ramp(this.crushDrive.gain, fx.crusherDrive, ctx)
|
||||||
|
}
|
||||||
|
ramp(this.crushWet.gain, crushing ? take / Math.max(1, fx.crusherDrive) ** 0.5 : 0, ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Strip {
|
||||||
|
readonly input: GainNode
|
||||||
|
readonly meter: AnalyserNode
|
||||||
|
private readonly ctx: AudioContext
|
||||||
|
private readonly trim: GainNode
|
||||||
|
private readonly bands: [GainNode, GainNode, GainNode]
|
||||||
|
private readonly fx: FilterFx
|
||||||
|
private readonly fader: GainNode
|
||||||
|
private readonly xfade: GainNode
|
||||||
|
/** In circuit (performance mode) vs straight through (prep). */
|
||||||
|
private readonly wetGate: GainNode
|
||||||
|
private readonly dryGate: GainNode
|
||||||
|
autoGainDb = 0
|
||||||
|
bpm = 0
|
||||||
|
|
||||||
|
constructor(ctx: AudioContext, bus: AudioNode) {
|
||||||
|
this.ctx = ctx
|
||||||
|
this.input = ctx.createGain()
|
||||||
|
this.trim = ctx.createGain()
|
||||||
|
this.input.connect(this.trim)
|
||||||
|
|
||||||
|
// Isolator: low = LR4 low-pass @250 then an all-pass @2.5k (the phase the
|
||||||
|
// other bands get from their LR4 pair there); mid = high-pass @250 then
|
||||||
|
// low-pass @2.5k; high = high-pass @250 then high-pass @2.5k.
|
||||||
|
const eqOut = ctx.createGain()
|
||||||
|
const [lpA, lpB] = lr4(ctx, 'lowpass', EQ_LOW_HZ)
|
||||||
|
const [hpA, hpB] = lr4(ctx, 'highpass', EQ_LOW_HZ)
|
||||||
|
const ap = biquad(ctx, 'allpass', EQ_HIGH_HZ, Math.SQRT1_2)
|
||||||
|
const [mlA, mlB] = lr4(ctx, 'lowpass', EQ_HIGH_HZ)
|
||||||
|
const [mhA, mhB] = lr4(ctx, 'highpass', EQ_HIGH_HZ)
|
||||||
|
this.bands = [ctx.createGain(), ctx.createGain(), ctx.createGain()]
|
||||||
|
this.trim.connect(lpA)
|
||||||
|
this.trim.connect(hpA)
|
||||||
|
lpB.connect(ap).connect(this.bands[0]).connect(eqOut)
|
||||||
|
hpB.connect(mlA)
|
||||||
|
hpB.connect(mhA)
|
||||||
|
mlB.connect(this.bands[1]).connect(eqOut)
|
||||||
|
mhB.connect(this.bands[2]).connect(eqOut)
|
||||||
|
|
||||||
|
this.fader = ctx.createGain()
|
||||||
|
eqOut.connect(this.fader)
|
||||||
|
this.fx = new FilterFx(ctx)
|
||||||
|
this.fader.connect(this.fx.input)
|
||||||
|
this.meter = ctx.createAnalyser()
|
||||||
|
this.meter.fftSize = 512
|
||||||
|
this.fx.output.connect(this.meter)
|
||||||
|
this.xfade = ctx.createGain()
|
||||||
|
this.wetGate = ctx.createGain()
|
||||||
|
this.fx.output.connect(this.xfade).connect(this.wetGate).connect(bus)
|
||||||
|
this.dryGate = ctx.createGain()
|
||||||
|
this.input.connect(this.dryGate).connect(bus)
|
||||||
|
}
|
||||||
|
|
||||||
|
apply(s: ChannelState, xfade: number, eqKill: boolean, fx: FxSettings): void {
|
||||||
|
const ctx = this.ctx
|
||||||
|
const trimDb = this.autoGainDb + Math.max(-TRIM_RANGE_DB, Math.min(TRIM_RANGE_DB, s.trim))
|
||||||
|
ramp(this.trim.gain, dbToGain(trimDb), ctx)
|
||||||
|
ramp(this.bands[0].gain, eqGain(s.low, eqKill), ctx)
|
||||||
|
ramp(this.bands[1].gain, eqGain(s.mid, eqKill), ctx)
|
||||||
|
ramp(this.bands[2].gain, eqGain(s.high, eqKill), ctx)
|
||||||
|
this.fx.apply(s.fx, s.color, fx, this.bpm)
|
||||||
|
ramp(this.fader.gain, faderGain(s.fader), ctx)
|
||||||
|
ramp(this.xfade.gain, xfade, ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
route(inCircuit: boolean, audible: boolean): void {
|
||||||
|
ramp(this.wetGate.gain, audible && inCircuit ? 1 : 0, this.ctx, 0.01)
|
||||||
|
ramp(this.dryGate.gain, audible && !inCircuit ? 1 : 0, this.ctx, 0.01)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MixerLevels {
|
||||||
|
/** Peak dBFS: each channel after its fader and FX, and the master after the limiter. */
|
||||||
|
A: number
|
||||||
|
B: number
|
||||||
|
master: number
|
||||||
|
/** The limiter's gain reduction now (dB, >= 0). */
|
||||||
|
limiting: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Mixer {
|
||||||
|
private readonly ctx: AudioContext
|
||||||
|
private readonly strips: Record<Channel, Strip>
|
||||||
|
private readonly limiter: DynamicsCompressorNode
|
||||||
|
private readonly limWet: GainNode
|
||||||
|
private readonly limDry: GainNode
|
||||||
|
private readonly masterMeter: AnalyserNode
|
||||||
|
private readonly buf = new Float32Array(512)
|
||||||
|
private active = false
|
||||||
|
|
||||||
|
constructor(ctx: AudioContext) {
|
||||||
|
this.ctx = ctx
|
||||||
|
const bus = ctx.createGain()
|
||||||
|
this.limiter = ctx.createDynamicsCompressor()
|
||||||
|
this.limiter.threshold.value = LIMIT_DB
|
||||||
|
this.limiter.knee.value = 0
|
||||||
|
this.limiter.ratio.value = LIMIT_RATIO
|
||||||
|
this.limiter.attack.value = 0.001
|
||||||
|
this.limiter.release.value = 0.15
|
||||||
|
const unMakeup = ctx.createGain()
|
||||||
|
unMakeup.gain.value = dbToGain(-MAKEUP_DB)
|
||||||
|
const out = ctx.createGain()
|
||||||
|
this.limWet = ctx.createGain()
|
||||||
|
this.limDry = ctx.createGain()
|
||||||
|
bus.connect(this.limiter).connect(unMakeup).connect(this.limWet).connect(out)
|
||||||
|
bus.connect(this.limDry).connect(out)
|
||||||
|
this.masterMeter = ctx.createAnalyser()
|
||||||
|
this.masterMeter.fftSize = 512
|
||||||
|
out.connect(this.masterMeter)
|
||||||
|
out.connect(ctx.destination)
|
||||||
|
this.strips = { A: new Strip(ctx, bus), B: new Strip(ctx, bus) }
|
||||||
|
this.setActive(false)
|
||||||
|
subscribeMixer(() => this.apply())
|
||||||
|
this.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where deck `ch` plays into. */
|
||||||
|
input(ch: Channel): AudioNode {
|
||||||
|
return this.strips[ch].input
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Performance mode: both channels through the mixer and the limiter. Off:
|
||||||
|
* deck A straight to the speakers, deck B silent. */
|
||||||
|
setActive(on: boolean): void {
|
||||||
|
this.active = on
|
||||||
|
this.strips.A.route(on, true)
|
||||||
|
this.strips.B.route(on, on)
|
||||||
|
ramp(this.limWet.gain, on ? 1 : 0, this.ctx, 0.01)
|
||||||
|
ramp(this.limDry.gain, on ? 0 : 1, this.ctx, 0.01)
|
||||||
|
}
|
||||||
|
|
||||||
|
get isActive(): boolean {
|
||||||
|
return this.active
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The loaded track's own auto gain (dB; 0 when it has none). */
|
||||||
|
setAutoGain(ch: Channel, db: number): void {
|
||||||
|
this.strips[ch].autoGainDb = db
|
||||||
|
this.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The deck's tempo now — Echo's beat. */
|
||||||
|
setTempo(ch: Channel, bpm: number): void {
|
||||||
|
if (this.strips[ch].bpm === bpm) return
|
||||||
|
this.strips[ch].bpm = bpm
|
||||||
|
this.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
private apply(): void {
|
||||||
|
const s = getMixerState()
|
||||||
|
const [ga, gb] = xfadeGains(s.crossfader, s.sharpness)
|
||||||
|
this.strips.A.apply(s.A, ga, s.eqKill, s.fx)
|
||||||
|
this.strips.B.apply(s.B, gb, s.eqKill, s.fx)
|
||||||
|
}
|
||||||
|
|
||||||
|
private peak(meter: AnalyserNode): number {
|
||||||
|
meter.getFloatTimeDomainData(this.buf)
|
||||||
|
let p = 0
|
||||||
|
for (let i = 0; i < this.buf.length; i++) {
|
||||||
|
const v = Math.abs(this.buf[i])
|
||||||
|
if (v > p) p = v
|
||||||
|
}
|
||||||
|
return p > 0 ? 20 * Math.log10(p) : -Infinity
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read the meters (call once per frame). */
|
||||||
|
levels(): MixerLevels {
|
||||||
|
return {
|
||||||
|
A: this.peak(this.strips.A.meter),
|
||||||
|
B: this.peak(this.strips.B.meter),
|
||||||
|
master: this.peak(this.masterMeter),
|
||||||
|
limiting: Math.max(0, -this.limiter.reduction),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let instance: Mixer | null = null
|
||||||
|
|
||||||
|
/** The app's mixer, built on its AudioContext the first time it is asked for. */
|
||||||
|
export function mixer(): Mixer {
|
||||||
|
if (!instance) instance = new Mixer(audioContext())
|
||||||
|
return instance
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { beatSeconds, delayBeatsAt, eqGain, sweepBeatsAt, faderGain, filterSweep, gainToDb, xfadeGains } from './mixerMath'
|
||||||
|
|
||||||
|
describe('eqGain', () => {
|
||||||
|
it('is flat at the centre, +6 dB at full right', () => {
|
||||||
|
expect(eqGain(0, false)).toBe(1)
|
||||||
|
expect(gainToDb(eqGain(1, false))).toBeCloseTo(6, 6)
|
||||||
|
expect(gainToDb(eqGain(0.5, true))).toBeCloseTo(3, 6)
|
||||||
|
})
|
||||||
|
it('cuts to -26 dB, DJM-style', () => {
|
||||||
|
expect(gainToDb(eqGain(-1, false))).toBeCloseTo(-26, 6)
|
||||||
|
expect(gainToDb(eqGain(-0.5, false))).toBeCloseTo(-13, 6)
|
||||||
|
})
|
||||||
|
it('kills to silence over the last fifth, continuously', () => {
|
||||||
|
expect(eqGain(-1, true)).toBe(0)
|
||||||
|
expect(eqGain(-0.8, true)).toBeCloseTo(eqGain(-0.8, false), 9)
|
||||||
|
expect(eqGain(-0.5, true)).toBe(eqGain(-0.5, false))
|
||||||
|
let prev = Infinity
|
||||||
|
for (let v = -0.7; v >= -1; v -= 0.01) {
|
||||||
|
const g = eqGain(v, true)
|
||||||
|
expect(g).toBeLessThanOrEqual(prev)
|
||||||
|
prev = g
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('xfadeGains', () => {
|
||||||
|
it('sharpness 0: constant power, -3 dB each at the centre', () => {
|
||||||
|
for (const x of [-1, -0.4, 0, 0.3, 1]) {
|
||||||
|
const [a, b] = xfadeGains(x, 0)
|
||||||
|
expect(a * a + b * b).toBeCloseTo(1, 9)
|
||||||
|
}
|
||||||
|
expect(gainToDb(xfadeGains(0, 0)[0])).toBeCloseTo(-3.01, 2)
|
||||||
|
expect(xfadeGains(-1, 0)).toEqual([1, expect.closeTo(0, 9)])
|
||||||
|
})
|
||||||
|
it('sharpness 1: both full until the last 4%, then a cut', () => {
|
||||||
|
expect(xfadeGains(0, 1)).toEqual([1, 1])
|
||||||
|
expect(xfadeGains(0.9, 1)).toEqual([1, 1])
|
||||||
|
expect(xfadeGains(1, 1)).toEqual([expect.closeTo(0, 9), 1])
|
||||||
|
expect(xfadeGains(-0.96, 1)[1]).toBeCloseTo(Math.SQRT1_2, 9) // halfway through its fade
|
||||||
|
})
|
||||||
|
it('in between: the centre rises from -3 dB to full, and every curve falls monotonically', () => {
|
||||||
|
let centre = 0
|
||||||
|
for (let s = 0; s <= 1; s += 0.1) {
|
||||||
|
const c = xfadeGains(0, s)[0]
|
||||||
|
expect(c).toBeGreaterThanOrEqual(centre - 1e-12)
|
||||||
|
centre = c
|
||||||
|
let prev = Infinity
|
||||||
|
for (let x = -1; x <= 1; x += 0.05) {
|
||||||
|
const [a, b] = xfadeGains(x, s)
|
||||||
|
expect(a).toBeLessThanOrEqual(prev + 1e-12)
|
||||||
|
expect(b).toBeCloseTo(xfadeGains(-x, s)[0], 9) // mirror images
|
||||||
|
prev = a
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(xfadeGains(0, 0.6)[0]).toBe(1) // past ~0.52 the fades no longer reach the middle: no dip
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('faderGain', () => {
|
||||||
|
it('runs 0 → 1 on an audio taper', () => {
|
||||||
|
expect(faderGain(0)).toBe(0)
|
||||||
|
expect(faderGain(1)).toBe(1)
|
||||||
|
expect(gainToDb(faderGain(0.7071))).toBeCloseTo(-6.02, 1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('filterSweep', () => {
|
||||||
|
it('is bypassed at the centre', () => {
|
||||||
|
expect(filterSweep(0)).toBeNull()
|
||||||
|
expect(filterSweep(0.01)).toBeNull()
|
||||||
|
})
|
||||||
|
it('full range (the default): low-pass to 20 Hz, high-pass to 20 kHz, on a log scale', () => {
|
||||||
|
expect(filterSweep(-1)).toEqual({ type: 'lowpass', freq: expect.closeTo(20, 6) })
|
||||||
|
expect(filterSweep(1)).toEqual({ type: 'highpass', freq: expect.closeTo(20000, 6) })
|
||||||
|
expect(filterSweep(-0.5)!.freq).toBeCloseTo(Math.sqrt(20000 * 20), 3)
|
||||||
|
expect(filterSweep(0.03)!.freq).toBeCloseTo(20 * 1000 ** 0.03, 6) // starts at the bottom
|
||||||
|
})
|
||||||
|
it('gentle range: stops at 500 Hz / 2 kHz', () => {
|
||||||
|
expect(filterSweep(-1, 'gentle')).toEqual({ type: 'lowpass', freq: expect.closeTo(500, 6) })
|
||||||
|
expect(filterSweep(1, 'gentle')).toEqual({ type: 'highpass', freq: expect.closeTo(2000, 6) })
|
||||||
|
})
|
||||||
|
it('musical range: stops at 150 Hz / 8 kHz', () => {
|
||||||
|
expect(filterSweep(-1, 'musical')).toEqual({ type: 'lowpass', freq: expect.closeTo(150, 6) })
|
||||||
|
expect(filterSweep(1, 'musical')).toEqual({ type: 'highpass', freq: expect.closeTo(8000, 6) })
|
||||||
|
expect(filterSweep(-0.5, 'musical')!.freq).toBeCloseTo(Math.sqrt(20000 * 150), 3)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('sweepBeatsAt', () => {
|
||||||
|
it('starts at the slowest sweep and halves at each quarter of the knob', () => {
|
||||||
|
expect(sweepBeatsAt(4, 0.05)).toBe(4)
|
||||||
|
expect(sweepBeatsAt(4, 0.3)).toBe(2)
|
||||||
|
expect(sweepBeatsAt(4, 0.6)).toBe(1)
|
||||||
|
expect(sweepBeatsAt(4, 0.8)).toBe(0.5)
|
||||||
|
expect(sweepBeatsAt(4, 1)).toBe(0.5)
|
||||||
|
expect(sweepBeatsAt(8, 1)).toBe(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('delayBeatsAt', () => {
|
||||||
|
it('starts at the shortest echo and doubles at each quarter of the knob', () => {
|
||||||
|
expect(delayBeatsAt(0.25, 0.1)).toBe(0.25)
|
||||||
|
expect(delayBeatsAt(0.25, 0.4)).toBe(0.5)
|
||||||
|
expect(delayBeatsAt(0.25, 0.7)).toBe(1)
|
||||||
|
expect(delayBeatsAt(0.25, 1)).toBe(2)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('beatSeconds', () => {
|
||||||
|
it('is a length in beats at the deck’s tempo', () => {
|
||||||
|
expect(beatSeconds(1, 120)).toBeCloseTo(0.5, 9)
|
||||||
|
expect(beatSeconds(0.5, 128)).toBeCloseTo(60 / 128 / 2, 9)
|
||||||
|
expect(beatSeconds(4, 0)).toBeCloseTo(2, 9) // unknown tempo: 120
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
// The mixer's control curves: how a knob or fader position becomes a gain or a
|
||||||
|
// filter setting. Pure, so they are tested on their own (mixerMath.test.ts);
|
||||||
|
// `mixer.ts` applies them to the audio graph.
|
||||||
|
|
||||||
|
export const dbToGain = (db: number): number => 10 ** (db / 20)
|
||||||
|
export const gainToDb = (g: number): number => (g > 0 ? 20 * Math.log10(g) : -Infinity)
|
||||||
|
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))
|
||||||
|
|
||||||
|
/** An EQ band's boost at full right. */
|
||||||
|
export const EQ_BOOST_DB = 6
|
||||||
|
/** An EQ band's cut at full left, DJM-style (the alternative is a full kill). */
|
||||||
|
export const EQ_CUT_DB = -26
|
||||||
|
/** The isolator's crossovers (Hz) — where the deck's waveform splits its bands. */
|
||||||
|
export const EQ_LOW_HZ = 250
|
||||||
|
export const EQ_HIGH_HZ = 2500
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An EQ knob (-1..1, centre = flat) as a linear gain. Right boosts to +6 dB.
|
||||||
|
* Left cuts in dB to -26 dB; with `kill`, the last fifth of the travel fades
|
||||||
|
* on from there to silence, so the band can disappear entirely.
|
||||||
|
*/
|
||||||
|
export function eqGain(v: number, kill: boolean): number {
|
||||||
|
v = clamp(v, -1, 1)
|
||||||
|
if (v >= 0) return dbToGain(EQ_BOOST_DB * v)
|
||||||
|
const g = dbToGain(-EQ_CUT_DB * v)
|
||||||
|
if (!kill || v > -0.8) return g
|
||||||
|
return g * ((1 + v) / 0.2)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The trim knob's range either side of the track's auto gain (dB). */
|
||||||
|
export const TRIM_RANGE_DB = 12
|
||||||
|
|
||||||
|
/** A channel fader (0..1) as a gain: an audio taper, -6 dB at ~0.7. */
|
||||||
|
export const faderGain = (f: number): number => clamp(f, 0, 1) ** 2
|
||||||
|
|
||||||
|
/** The narrowest fade a fully sharp crossfader leaves (of its whole travel). */
|
||||||
|
export const XF_MIN_WIDTH = 0.04
|
||||||
|
|
||||||
|
/** How much of the travel a channel takes to fade out, at `sharpness` 0..1. */
|
||||||
|
export const xfadeWidth = (sharpness: number): number => 1 - clamp(sharpness, 0, 1) * (1 - XF_MIN_WIDTH)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The crossfader (-1 = all A, 1 = all B) as the two channels' gains, at a
|
||||||
|
* SHARPNESS from 0 to 1 (decided 2026-11-03: fully adjustable). Each channel
|
||||||
|
* fades on a quarter-cosine over the last `xfadeWidth` of the travel toward the
|
||||||
|
* other side and is at full level before it. At 0 that is the whole travel —
|
||||||
|
* constant power, both at -3 dB in the middle, for blends; turned up, both stay
|
||||||
|
* full across a widening middle (no dip), until at 1 a channel cuts over the
|
||||||
|
* last 4%, for cuts and scratching.
|
||||||
|
*/
|
||||||
|
export function xfadeGains(x: number, sharpness: number): [number, number] {
|
||||||
|
const t = (clamp(x, -1, 1) + 1) / 2 // 0 = all A
|
||||||
|
const w = xfadeWidth(sharpness)
|
||||||
|
const fade = (u: number) => Math.cos((Math.PI / 2) * clamp((u - (1 - w)) / w, 0, 1))
|
||||||
|
return [fade(t), fade(1 - t)]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The colour knob's dead centre: inside it, the effect is out of the path. */
|
||||||
|
export const FX_CENTRE = 0.02
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How far the FILTER knob sweeps (settings, decided 2026-11-03): `full` runs
|
||||||
|
* the low-pass down to 20 Hz and the high-pass up to 20 kHz, so either end is
|
||||||
|
* near silence; `musical` stops at 150 Hz / 8 kHz, where the track is thinned
|
||||||
|
* but still there; `gentle` at 500 Hz / 2 kHz, where it stays clearly heard.
|
||||||
|
*/
|
||||||
|
export type FilterRange = 'full' | 'musical' | 'gentle'
|
||||||
|
export const FILTER_RANGES: Record<FilterRange, { low: number; high: number }> = {
|
||||||
|
full: { low: 20, high: 20000 },
|
||||||
|
musical: { low: 150, high: 8000 },
|
||||||
|
gentle: { low: 500, high: 2000 },
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The filter at knob `c` (-1..1): left a low-pass falling from 20 kHz, right a
|
||||||
|
* high-pass rising from 20 Hz, to the range's ends, on a log scale so the
|
||||||
|
* sweep sounds even. Null at the centre (bypassed).
|
||||||
|
*/
|
||||||
|
export function filterSweep(
|
||||||
|
c: number,
|
||||||
|
range: FilterRange = 'full',
|
||||||
|
): { type: 'lowpass' | 'highpass'; freq: number } | null {
|
||||||
|
c = clamp(c, -1, 1)
|
||||||
|
if (Math.abs(c) < FX_CENTRE) return null
|
||||||
|
const a = Math.abs(c)
|
||||||
|
const end = FILTER_RANGES[range]
|
||||||
|
return c < 0
|
||||||
|
? { type: 'lowpass', freq: 20000 * (end.low / 20000) ** a }
|
||||||
|
: { type: 'highpass', freq: 20 * (end.high / 20) ** a }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Filter FX grow as the knob opens (decided 2026-11-03), in STEPS of two
|
||||||
|
* at each further quarter of its travel, so every length stays a musical one
|
||||||
|
* of the tempo: 0 near the centre, 3 in the last quarter.
|
||||||
|
*/
|
||||||
|
export const knobStep = (a: number): number => Math.min(3, Math.floor(clamp(a, 0, 1) * 4))
|
||||||
|
|
||||||
|
/** The flanger's sweep (beats): `slowest` (the setting), then ½, ¼, ⅛ of it —
|
||||||
|
* faster as the filter opens. */
|
||||||
|
export const sweepBeatsAt = (slowest: number, a: number): number => slowest / 2 ** knobStep(a)
|
||||||
|
|
||||||
|
/** The delay's length (beats): `shortest` (the setting), then ×2, ×4, ×8 —
|
||||||
|
* longer as the filter opens. */
|
||||||
|
export const delayBeatsAt = (shortest: number, a: number): number => shortest * 2 ** knobStep(a)
|
||||||
|
|
||||||
|
/** The long reverb is this many times the set (short) one; the knob blends
|
||||||
|
* from the short into the long as it opens. */
|
||||||
|
export const REVERB_GROWTH = 3
|
||||||
|
|
||||||
|
/** Seconds for `beats` at `bpm` (120 when the tempo is unknown) — the delay's
|
||||||
|
* length, the flanger's sweep. */
|
||||||
|
export function beatSeconds(beats: number, bpm: number): number {
|
||||||
|
return (beats * 60) / (bpm > 0 ? bpm : 120)
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { DEFAULT_FX, FX_TYPES, rangeFor } from './mixerState'
|
||||||
|
|
||||||
|
describe('rangeFor', () => {
|
||||||
|
it('the Filter alone follows its setting, an effect the other', () => {
|
||||||
|
const fx = { ...DEFAULT_FX, filterRange: 'full' as const, effectRange: 'gentle' as const }
|
||||||
|
expect(rangeFor('filter', fx)).toBe('full')
|
||||||
|
for (const t of FX_TYPES.filter((x) => x !== 'filter')) expect(rangeFor(t, fx)).toBe('gentle')
|
||||||
|
})
|
||||||
|
it('defaults: Full alone, Musical with an effect', () => {
|
||||||
|
expect(rangeFor('filter', DEFAULT_FX)).toBe('full')
|
||||||
|
expect(rangeFor('reverb', DEFAULT_FX)).toBe('musical')
|
||||||
|
})
|
||||||
|
})
|
||||||
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user