mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Compare commits
55
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d10b11f8eb | ||
|
|
79a8a843c5 | ||
|
|
0204a322ff | ||
|
|
05051e7056 | ||
|
|
b5dabbc8a0 | ||
|
|
86bbb7b961 | ||
|
|
d474c662db | ||
|
|
a0df683fee | ||
|
|
3385b794e9 | ||
|
|
2c352b76a1 | ||
|
|
40630ff78e | ||
|
|
966f3fe8c5 | ||
|
|
a03b9056a9 | ||
|
|
26b556d975 | ||
|
|
c87444bda5 | ||
|
|
7ba71981c8 | ||
|
|
89c7dade25 | ||
|
|
b154df430a | ||
|
|
e5c7b67626 | ||
|
|
9f79f5a849 | ||
|
|
c8b86100f0 | ||
|
|
0fac84cb73 | ||
|
|
71ee877784 | ||
|
|
920146f2c0 | ||
|
|
ba7b662b93 | ||
|
|
e5fb0f0dbb | ||
|
|
e8a53eee07 | ||
|
|
36a6df4d3b | ||
|
|
72a52d3291 | ||
|
|
c3571fd054 | ||
|
|
b5b3dd04c3 | ||
|
|
4e9472c14a | ||
|
|
957525393b | ||
|
|
bdc62f2c1b | ||
|
|
7960a5a68f | ||
|
|
c5280a95f2 | ||
|
|
e73fa05e1f | ||
|
|
775e94168c | ||
|
|
2784879872 | ||
|
|
702e5d86a6 | ||
|
|
d7f8768d4c | ||
|
|
5c193e0ab7 | ||
|
|
badf12b991 | ||
|
|
ecc0e4c8df | ||
|
|
ae03a93f98 | ||
|
|
c560876c02 | ||
|
|
e805635383 | ||
|
|
27471a82cd | ||
|
|
28b705173e | ||
|
|
681add852a | ||
|
|
376569ec75 | ||
|
|
b5b0fa91fe | ||
|
|
34b18893ef | ||
|
|
2c02019bb2 | ||
|
|
08c53e1150 |
No files matched your search
@@ -55,10 +55,11 @@ jobs:
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
# --- Step 1: freeze the FastAPI backend into a single-file sidecar ---
|
||||
# --- Step 1: freeze the FastAPI backend into a onedir sidecar folder ---
|
||||
# build_sidecar.* stages it as
|
||||
# frontend/src-tauri/binaries/konduktor-sidecar-<triple>[.exe]
|
||||
# which tauri.conf.json's externalBin bundles into the app.
|
||||
# frontend/src-tauri/binaries/konduktor-sidecar/
|
||||
# which tauri.macos.conf.json (bundle.macOS.files, keeps its symlinks) /
|
||||
# tauri.windows.conf.json (bundle.resources) put in the app as `sidecar/`.
|
||||
- name: Install backend deps
|
||||
working-directory: backend
|
||||
run: |
|
||||
@@ -114,6 +115,52 @@ jobs:
|
||||
if-no-files-found: error
|
||||
path: installer/*
|
||||
|
||||
# The Konduktor SERVER image (server/Dockerfile): a remote library's half,
|
||||
# pushed to GHCR with the same version as the desktop app, so a TrueNAS app
|
||||
# can name the tag that matches the app it is opened from.
|
||||
server-image:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write # push to ghcr.io
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Resolve version and image name
|
||||
id: meta
|
||||
run: |
|
||||
echo "version=$(jq -r .version frontend/package.json)" >> "$GITHUB_OUTPUT"
|
||||
# GHCR names must be lower-case; the owner may not be.
|
||||
echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/konduktor-server" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Log in to GHCR
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Set up Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
env:
|
||||
DOCKER_BUILD_RECORD_UPLOAD: false # no .dockerbuild artifact in the run
|
||||
with:
|
||||
context: .
|
||||
file: server/Dockerfile
|
||||
platforms: linux/amd64
|
||||
push: true
|
||||
tags: |
|
||||
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}-b${{ github.run_number }}
|
||||
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}
|
||||
${{ steps.meta.outputs.image }}:latest
|
||||
labels: |
|
||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||
org.opencontainers.image.version=${{ steps.meta.outputs.version }}
|
||||
|
||||
# Gather both platforms' installers and publish them as a single new Release.
|
||||
# Runs once, after both builds succeed, so the two matrix jobs never race to
|
||||
# create the same tag/release.
|
||||
@@ -136,6 +183,9 @@ jobs:
|
||||
- name: Download installers from both builds
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
# Only the installers: the run also holds server-image's Docker build
|
||||
# record, which is not a release asset (and once failed to download).
|
||||
pattern: konduktor-*
|
||||
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
|
||||
|
||||
- name: Publish release
|
||||
|
||||
+3
-2
@@ -39,7 +39,7 @@ cd ..
|
||||
# 1) Freeze + stage the backend sidecar (from the activated backend venv)
|
||||
cd backend
|
||||
.\.venv\Scripts\Activate.ps1 # if not already active
|
||||
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar-<triple>.exe
|
||||
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder)
|
||||
cd ..
|
||||
|
||||
# 2) Build the app
|
||||
@@ -56,7 +56,8 @@ frontend\src-tauri\target\release\bundle\msi\Konduktor_0.1.0_x64_en-US.msi
|
||||
frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_x64-setup.exe
|
||||
```
|
||||
|
||||
Either one installs the app (bundling the sidecar `.exe` alongside it).
|
||||
Either one installs the app, with the sidecar folder in its `sidecar\` resource
|
||||
folder (`tauri.windows.conf.json`).
|
||||
|
||||
## Rebuilding after changes
|
||||
|
||||
|
||||
@@ -1,213 +1,141 @@
|
||||
# Konduktor
|
||||
<p align="center">
|
||||
<img src="design/konduktor-icon.svg" width="96" alt="Konduktor icon">
|
||||
</p>
|
||||
|
||||
**A fast, modern home for your Traktor collection.**
|
||||
<h1 align="center">Konduktor</h1>
|
||||
|
||||
Konduktor is a lightweight desktop-style app for DJs who run **Native
|
||||
Instruments Traktor** (Pro 4 / NML v20). It opens your existing
|
||||
`collection.nml`, gives you a beautiful dark library to explore, and lets you
|
||||
build playlists and prep tracks — without launching the whole heavyweight
|
||||
Traktor app just to tidy up your tags or drop a few cue points.
|
||||
<p align="center">
|
||||
<b>Prep your tracks and run your DJ libraries in one fast app.</b><br>
|
||||
Traktor, Rekordbox, or the USB stick in your pocket.
|
||||
</p>
|
||||
|
||||
Your collection stays exactly where it is. Konduktor reads and writes the same
|
||||
file Traktor uses, so everything you do shows up next time you open Traktor.
|
||||
<p align="center">
|
||||
<a href="https://github.com/MrPatben8/konduktor/releases"><b>Download for macOS & Windows</b></a>
|
||||
</p>
|
||||
|
||||

|
||||
|
||||
Konduktor opens the library you already have, in the format it already uses.
|
||||
You can tidy tags, build playlists, set grids and cues, and pack a USB stick
|
||||
for the gig without launching your full DJ software. When you open your DJ
|
||||
software again, everything you changed is there.
|
||||
|
||||
---
|
||||
|
||||
## Why you'll like it
|
||||
## One app for every library
|
||||
|
||||
- **Instant, searchable library.** Your whole collection loads into a snappy,
|
||||
virtualized grid. Search, filter by genre / key / BPM / rating, and sort by
|
||||
any column — all instant, no waiting.
|
||||
- **Make it yours.** Show only the columns you care about, drag them into the
|
||||
order you like, and resize them to fit. Your layout is remembered.
|
||||
- **Edit tags without the ceremony.** Double-click any field to fix a title or
|
||||
genre on the spot, click the stars to rate a track, or right-click for a full
|
||||
tag + cover-art editor. Great for quick one-off fixes.
|
||||
- **Playlists, the easy way.** Create, rename, and delete playlists, then
|
||||
drag-and-drop to reorder or add tracks.
|
||||
- **A real prep deck.** Load any track into the deck at the top and:
|
||||
- play it with a **frequency-colored waveform** (Traktor-style Spectrum look),
|
||||
scrolling under a fixed playhead with zoom in/out
|
||||
- scratch it by dragging the waveform
|
||||
- see and adjust the **beatgrid** and BPM
|
||||
- set, jump to, and delete **hotcues** (with a color-coded 8-slot bar)
|
||||
- build **loops** in fixed beat sizes, tied into the hotcue system
|
||||
- use keyboard shortcuts: **Space** to play/pause, **1–8** to fire hotcues,
|
||||
**Shift+1–8** to clear them
|
||||
- **Your data is safe.** Every save makes a timestamped backup first, and only
|
||||
ever touches the parts you changed — the rest of the file stays byte-for-byte
|
||||
identical.
|
||||
<img src="docs/screenshots/platforms.png" align="right" width="420" alt="Choosing a platform: Rekordbox, Traktor, OneLibrary or Remote">
|
||||
|
||||
- **Traktor** collections.
|
||||
- **Rekordbox** libraries.
|
||||
- **OneLibrary** USB sticks, the format CDJs read. Plug one in to browse it,
|
||||
preview tracks off it, import them, or edit the stick directly.
|
||||
- **Remote** libraries: keep your whole library and music on a home server and
|
||||
open it from any laptop ([set up a server](docs/REMOTE-SERVER.md)).
|
||||
- **Any folder or drive**: browse loose audio files, preview them, and add
|
||||
them to your library.
|
||||
|
||||
Your library is never converted into a Konduktor database. Saves write back to
|
||||
the original file and change only what you edited.
|
||||
|
||||
<br clear="right">
|
||||
|
||||
## A real prep deck
|
||||
|
||||

|
||||
|
||||
- A scrolling waveform, coloured by frequency, with zoom, scratching and an
|
||||
overview of the whole track.
|
||||
- Eight hotcue pads with names, types and colours, plus beat loops, beat jump
|
||||
and tap tempo.
|
||||
- **Beatgrid editing**, including grids with tempo changes. Nudge, retempo,
|
||||
halve or double without opening your DJ software.
|
||||
- Keyboard shortcuts for the whole deck: Space to play, 1–8 for hotcues,
|
||||
arrow keys to jump or move a loop.
|
||||
|
||||
## Stems, built in
|
||||
|
||||

|
||||
|
||||
**Play stem files as stems.** Load a stem file and the deck splits into
|
||||
drums, bass, synths and vocals, each drawn in its own lane. Click a lane's
|
||||
button to mute it, Alt/Option-click to solo it, or use Q W E R.
|
||||
|
||||
**Convert to Stems.** In a Traktor collection, right-click any tracks and
|
||||
choose Convert to Stems. They come back as standard Traktor stem files with their tags, cover art, cues and
|
||||
beatgrid intact.
|
||||
|
||||
- The separation runs on your own computer, so your music isn't sent to an
|
||||
online service.
|
||||
- Replace the originals, or save the stems to a folder and add them as new
|
||||
tracks.
|
||||
- Convert a whole playlist in one go.
|
||||
|
||||
## Let it do the boring parts
|
||||
|
||||
| Auto Hotcues | Analyze |
|
||||
|:---:|:---:|
|
||||
|  |  |
|
||||
| Pick an event for each pad (first beat, build, drop, breakdown, outro). Konduktor finds them in the track and places the cues. Run it on one track or a whole playlist. | Detects tempo, beatgrid and musical key, for one track or hundreds. |
|
||||
|
||||
## Export to USB for CDJs, or other platforms
|
||||
|
||||
<img src="docs/screenshots/export.png" align="right" width="380" alt="An export set for OneLibrary, Traktor and Rekordbox">
|
||||
|
||||
Make an **export** in the sidebar, drag playlists onto it, and press Export.
|
||||
One stick can carry a Traktor collection, a OneLibrary library for current
|
||||
CDJs and a Rekordbox Device Library for older players, all sharing **one copy
|
||||
of the audio**.
|
||||
|
||||
- Hotcues, memory cues, loops, grids, keys and cover art are converted for
|
||||
each platform.
|
||||
- Playlists stay linked: edit a playlist, re-export, and the stick catches up.
|
||||
- Re-exports copy only what changed, so updating a stick is quick.
|
||||
- Konduktor only ever clears a folder that it wrote itself.
|
||||
|
||||
<br clear="right">
|
||||
|
||||
## Your library is safe
|
||||
|
||||
- **Saves are surgical.** A Traktor save changes only the entries you edited.
|
||||
The rest of the file stays byte-for-byte identical.
|
||||
- **Backups and history.** Every Traktor save makes a backup first and is kept
|
||||
in a version history that you can restore from in the app.
|
||||
- **Nothing is written until you press Save.** Discard changes throws away
|
||||
everything you did since your last save.
|
||||
- Tag edits are also written into the audio files themselves, so other apps
|
||||
see them too.
|
||||
|
||||
## And also
|
||||
|
||||
- A fast library with search, filters, sorting and columns you can rearrange,
|
||||
even with thousands of tracks.
|
||||
- Edit tags inline or in a full tag and cover-art editor.
|
||||
- Drag and drop tracks onto playlists, exports or the deck, and drag playlists
|
||||
to reorganise them.
|
||||
- If you open a Traktor collection on a different computer or drive,
|
||||
Konduktor finds the missing files for you.
|
||||
|
||||
---
|
||||
|
||||
## Getting started
|
||||
## Get Konduktor
|
||||
|
||||
Konduktor runs as two small local servers (a Python backend and a web
|
||||
frontend). Do the one-time setup, then start them — the same steps work on
|
||||
macOS, Linux, and Windows.
|
||||
Download the latest build from
|
||||
[**Releases**](https://github.com/MrPatben8/konduktor/releases):
|
||||
a `.dmg` for macOS (Apple Silicon) and a `-setup.exe` for Windows.
|
||||
|
||||
### 1. Install (once)
|
||||
> **First launch:** builds aren't notarised yet, so your OS will warn you the
|
||||
> first time.
|
||||
> **macOS:** right-click the app, choose **Open**, then **Open** again. If it
|
||||
> still refuses, run `xattr -cr /Applications/Konduktor.app` once.
|
||||
> **Windows:** click **More info → Run anyway**.
|
||||
|
||||
**Backend** — needs Python 3.11+. Create a virtual environment and install the
|
||||
dependencies:
|
||||
> **Using Traktor?** Close it before saving in Konduktor. Traktor rewrites
|
||||
> `collection.nml` when it quits, which would overwrite your changes.
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python3 -m venv .venv # Windows: python -m venv .venv
|
||||
```
|
||||
Want to run it from source or build it yourself? See
|
||||
[docs/BUILDING.md](docs/BUILDING.md).
|
||||
|
||||
Activate it, then install:
|
||||
## License
|
||||
|
||||
```bash
|
||||
source .venv/bin/activate # Windows (PowerShell): .\.venv\Scripts\Activate.ps1
|
||||
pip install -r requirements.txt
|
||||
cd ..
|
||||
```
|
||||
|
||||
**Frontend** — needs Node 18+ (same on every platform):
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
cd ..
|
||||
```
|
||||
|
||||
### 2. Run it (development)
|
||||
|
||||
Konduktor runs as two local servers (backend on `:8000`, frontend on `:5173`).
|
||||
|
||||
**macOS / Linux** — one command starts both:
|
||||
|
||||
```bash
|
||||
./dev.sh
|
||||
```
|
||||
|
||||
**Windows** — start each server in its own terminal:
|
||||
|
||||
```powershell
|
||||
# Terminal 1 — backend
|
||||
cd backend; .\.venv\Scripts\Activate.ps1; uvicorn konduktor.main:app --reload --port 8000
|
||||
|
||||
# Terminal 2 — frontend
|
||||
cd frontend; npm run dev
|
||||
```
|
||||
|
||||
Either way, open **http://localhost:5173** in your browser (`Ctrl-C` stops a
|
||||
server). This is the fastest way to try Konduktor or hack on it — the frontend
|
||||
hot-reloads as you edit. To package a real double-clickable app instead, see
|
||||
[Build a standalone app](#build-a-standalone-app-production) below.
|
||||
|
||||
### 3. Open your collection
|
||||
|
||||
On launch, Konduktor offers to:
|
||||
|
||||
- **Automatically** open the collection from your latest installed Traktor,
|
||||
- reopen the **last collection** you used, or
|
||||
- **browse** for a `collection.nml` yourself.
|
||||
|
||||
That's it — you're in.
|
||||
|
||||
---
|
||||
|
||||
## Build a standalone app (production)
|
||||
|
||||
Prefer a real double-clickable app over running the dev servers? Konduktor
|
||||
packages into a native desktop app (via **Tauri**) that bundles the Python
|
||||
backend as a sidecar — no terminal, no servers to start by hand.
|
||||
|
||||
### Extra prerequisites
|
||||
|
||||
On top of the Python 3.11+ and Node 18+ from above:
|
||||
|
||||
- **Rust** — install from <https://rustup.rs> (the app shell is Tauri/Rust).
|
||||
- **PyInstaller** — into the backend venv:
|
||||
`pip install -r backend/requirements-build.txt`
|
||||
- **Windows only:** also the MSVC C++ build tools and the WebView2 runtime — see
|
||||
[BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the one-time toolchain setup.
|
||||
|
||||
The build is a two-step recipe on both platforms: **freeze the backend into a
|
||||
sidecar binary**, then **build the app**. The only difference is which sidecar
|
||||
script you run — `.sh` on macOS/Linux, `.ps1` on Windows. Each build runs on its
|
||||
own OS (the app can't be cross-compiled).
|
||||
|
||||
### macOS / Linux
|
||||
|
||||
```bash
|
||||
# 1) Freeze the backend into a sidecar binary (from the activated backend venv)
|
||||
cd backend && source .venv/bin/activate && ./build_sidecar.sh && cd ..
|
||||
|
||||
# 2) Build the app
|
||||
cd frontend && npx tauri build
|
||||
```
|
||||
|
||||
The installer lands at
|
||||
`frontend/src-tauri/target/release/bundle/dmg/Konduktor_<version>_aarch64.dmg`
|
||||
(with the `.app` beside it).
|
||||
|
||||
### Windows
|
||||
|
||||
```powershell
|
||||
# 1) Freeze the backend into a sidecar binary (from the activated backend venv)
|
||||
cd backend; .\.venv\Scripts\Activate.ps1; .\build_sidecar.ps1; cd ..
|
||||
|
||||
# 2) Build the app
|
||||
cd frontend; npx tauri build
|
||||
```
|
||||
|
||||
The installers land in `frontend\src-tauri\target\release\bundle\` (an `.msi` and
|
||||
an NSIS `-setup.exe`). See [BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the full
|
||||
walkthrough and Windows-specific notes.
|
||||
|
||||
> **First launch — getting past the OS security prompt.** Builds are
|
||||
> **ad-hoc signed, not notarized** (no paid Apple/Windows developer cert yet), so
|
||||
> the OS flags them the first time. This is expected — the app isn't damaged.
|
||||
>
|
||||
> - **macOS:** right-click the app → **Open** → **Open** (or System Settings →
|
||||
> Privacy & Security → **Open Anyway** after the first blocked attempt). If it
|
||||
> still refuses — common for a `.dmg` downloaded via a browser, which macOS
|
||||
> quarantines — clear the quarantine flag once from Terminal:
|
||||
> ```bash
|
||||
> xattr -cr /Applications/Konduktor.app
|
||||
> ```
|
||||
> - **Windows:** click **More info → Run anyway** past SmartScreen.
|
||||
>
|
||||
> The macOS `.dmg` is Apple-Silicon (`aarch64`) only.
|
||||
|
||||
> **Faster local builds:** `npx tauri build --debug --bundles app` skips the
|
||||
> optimizer and the installer, giving you a runnable app in seconds — handy while
|
||||
> iterating.
|
||||
|
||||
### Rebuilding after changes
|
||||
|
||||
Changed **backend** Python? Re-run the sidecar script for your OS
|
||||
(`./build_sidecar.sh` or `.\build_sidecar.ps1`), then `npx tauri build`.
|
||||
Frontend-only change? Just `npx tauri build` — it rebuilds the web app for you.
|
||||
|
||||
---
|
||||
|
||||
## Saving back to Traktor
|
||||
|
||||
Playlist edits, tag changes, and prep tweaks all apply live in the app. When
|
||||
you're happy, hit **Save to Traktor** to write them to `collection.nml`.
|
||||
|
||||
> ⚠️ **Close Traktor before saving.** Traktor rewrites `collection.nml` when it
|
||||
> quits, so if it's open it will overwrite your changes. Konduktor always writes
|
||||
> a backup first (into a `backups/` folder next to your collection), but closing
|
||||
> Traktor first is the safe habit.
|
||||
|
||||
Want to experiment risk-free? Point Konduktor at a *copy* of your collection and
|
||||
play around.
|
||||
|
||||
---
|
||||
|
||||
## Good to know
|
||||
|
||||
- Konduktor is built on [`traktor-nml-utils`](https://github.com/MrPatben8/traktor-nml-utils)
|
||||
and speaks Traktor's real file format — no import/export, no separate database.
|
||||
- Run it in your browser from source, or package it into a native desktop app
|
||||
(macOS `.dmg` / Windows `.msi`) that bundles the backend — see
|
||||
[Build a standalone app](#build-a-standalone-app-production). A mobile version
|
||||
is on the horizon.
|
||||
- Under the hood: **FastAPI** (Python) backend + **React / TypeScript / Vite**
|
||||
frontend. Curious about internals or contributing? See
|
||||
[CLAUDE.md](CLAUDE.md) for the architecture and conventions.
|
||||
[AGPL-3.0](LICENSE)
|
||||
@@ -6,6 +6,8 @@ compare rather than a pass/fail. Every open is read-only — nothing is saved.
|
||||
python bench_grid_detect.py # the local Rekordbox library
|
||||
python bench_grid_detect.py path/to/collection.nml path/to/master.db
|
||||
python bench_grid_detect.py --legacy # score the old librosa beat_track
|
||||
python bench_grid_detect.py --hold bpm # Grid alone: phase, given the right BPM
|
||||
python bench_grid_detect.py --hold anchor # BPM alone: tempo, given the right anchor
|
||||
|
||||
The reference is each track's own grid, and only single-marker grids are used:
|
||||
a multi-marker grid is either a real tempo change (which a constant-tempo
|
||||
@@ -102,6 +104,9 @@ def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("libraries", nargs="*", type=Path)
|
||||
ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector")
|
||||
ap.add_argument("--hold", choices=("bpm", "anchor"),
|
||||
help="score one half alone: hold the REFERENCE's BPM (the Analyze dialog's "
|
||||
"'Grid' tick — phase is all that is scored) or its anchor ('BPM')")
|
||||
args = ap.parse_args()
|
||||
|
||||
libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"]
|
||||
@@ -119,7 +124,8 @@ def main() -> int:
|
||||
for name, audio, r0, rb in refs:
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
res = detect(str(audio))
|
||||
hold = {"bpm": {"bpm": rb}, "anchor": {"anchor": r0}}.get(args.hold, {})
|
||||
res = detect(str(audio), **hold)
|
||||
except Exception as ex: # a failure is a data point, not a crash
|
||||
print(f" FAIL {name[:48]:48} {ex}")
|
||||
rows.append(None)
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Benchmark key detection (`core/key_detect.py`).
|
||||
|
||||
NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to
|
||||
compare rather than a pass/fail.
|
||||
|
||||
python bench_key_detect.py --giantsteps DATA/gs # hand-annotated EDM
|
||||
python bench_key_detect.py ~/Music # files with a key TAG
|
||||
|
||||
GiantSteps (604 Beatport previews, keys corrected by hand) is ground truth
|
||||
and the number to quote; the model never trained on it (see
|
||||
`train_key_model.py`). A folder's key tags were written by some other
|
||||
analyser — usually Traktor, sometimes Mixed In Key or a store — so that score
|
||||
is AGREEMENT with it, not accuracy. Copies of one song (a stem file beside its
|
||||
source) count once, by title.
|
||||
|
||||
Errors are classed the MIREX way, because they are not equally wrong for a
|
||||
DJ: a FIFTH (one step round the Camelot wheel) or the RELATIVE key (same
|
||||
number, other letter) still mixes harmonically; PARALLEL (same tonic, other
|
||||
mode) and OTHER do not. MIREX's weighted score is 1 / 0.5 / 0.3 / 0.2 / 0.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import warnings
|
||||
from collections import Counter
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
from konduktor.core import key_detect, musical_key # noqa: E402
|
||||
|
||||
WEIGHT = {"exact": 1.0, "fifth": 0.5, "relative": 0.3, "parallel": 0.2, "other": 0.0}
|
||||
AUDIO = {".mp3", ".m4a", ".mp4", ".flac", ".aif", ".aiff", ".wav", ".ogg"}
|
||||
|
||||
|
||||
def relation(det: tuple[int, str], ref: tuple[int, str]) -> str:
|
||||
"""How a detected (wheel, mode) relates to the reference."""
|
||||
(dw, dm), (rw, rm) = det, ref
|
||||
if (dw, dm) == (rw, rm):
|
||||
return "exact"
|
||||
if dw == rw:
|
||||
return "relative"
|
||||
if dm == rm and (dw - rw) % 12 in (1, 11):
|
||||
return "fifth"
|
||||
if dm != rm:
|
||||
major, minor = (dw, rw) if dm == "major" else (rw, dw)
|
||||
if (major - minor) % 12 == 3: # C major 8B vs C minor 5A
|
||||
return "parallel"
|
||||
return "other"
|
||||
|
||||
|
||||
def parse_any(text: str) -> tuple[int, str] | None:
|
||||
"""Open Key, Camelot or a named key ("Abm", "F# minor", "Gmin")."""
|
||||
w, m = musical_key.parse(text)
|
||||
return (w, m) if w else None
|
||||
|
||||
|
||||
def _tag_key(path: Path) -> tuple[str, str] | None:
|
||||
import mutagen
|
||||
|
||||
try:
|
||||
f = mutagen.File(path)
|
||||
except Exception:
|
||||
return None
|
||||
if not f or not f.tags:
|
||||
return None
|
||||
t = f.tags
|
||||
|
||||
def has(name: str) -> bool:
|
||||
try:
|
||||
return name in t
|
||||
except ValueError: # a Vorbis comment refuses an MP4-style atom name
|
||||
return False
|
||||
|
||||
key = title = None
|
||||
for name in ("TKEY", "----:com.apple.iTunes:initialkey", "initialkey", "INITIALKEY"):
|
||||
if has(name):
|
||||
v = t[name]
|
||||
v = v.text[0] if hasattr(v, "text") else v[0]
|
||||
key = v.decode() if isinstance(v, bytes) else str(v)
|
||||
break
|
||||
for name in ("TIT2", "\xa9nam", "title", "TITLE"):
|
||||
if has(name):
|
||||
v = t[name]
|
||||
title = str(v.text[0] if hasattr(v, "text") else v[0])
|
||||
break
|
||||
return (key, title or path.stem) if key else None
|
||||
|
||||
|
||||
def folder_refs(roots: list[Path]) -> list[tuple[Path, tuple[int, str], str]]:
|
||||
seen, out = set(), []
|
||||
for root in roots:
|
||||
for dp, dirs, files in os.walk(root):
|
||||
dirs[:] = sorted(d for d in dirs if not d.startswith("."))
|
||||
for name in sorted(files):
|
||||
p = Path(dp) / name
|
||||
if p.suffix.lower() not in AUDIO or name.startswith("."):
|
||||
continue
|
||||
tagged = _tag_key(p)
|
||||
if not tagged or not (ref := parse_any(tagged[0])):
|
||||
continue
|
||||
title = re.sub(r"\.stem$", "", tagged[1].strip().lower())
|
||||
if title not in seen:
|
||||
seen.add(title)
|
||||
out.append((p, ref, tagged[1]))
|
||||
return out
|
||||
|
||||
|
||||
def giantsteps_refs(gs: Path) -> list[tuple[Path, tuple[int, str], str]]:
|
||||
out = []
|
||||
for f in sorted((gs / "annotations/key").glob("*.key")):
|
||||
audio = gs / "audio" / f"{f.stem}.mp3"
|
||||
ref = parse_any(f.read_text()) # "C minor"
|
||||
if audio.exists() and ref:
|
||||
out.append((audio, ref, f.stem))
|
||||
return out
|
||||
|
||||
|
||||
def _detect(path: Path):
|
||||
warnings.filterwarnings("ignore")
|
||||
try:
|
||||
r = key_detect.detect_key(str(path))
|
||||
except Exception as ex: # an undecodable file is reported, not fatal
|
||||
return None, str(ex)
|
||||
return (r.wheel, r.mode, r.name, r.confidence) if r else None, None
|
||||
|
||||
|
||||
def run(refs, label: str, verbose: bool) -> None:
|
||||
with ProcessPoolExecutor() as ex:
|
||||
results = list(ex.map(_detect, [p for p, _, _ in refs], chunksize=2))
|
||||
rels, misses = [], []
|
||||
for (path, ref, title), (det, err) in zip(refs, results):
|
||||
if det is None:
|
||||
print(f" could not analyse {title}: {err or 'silent / too short'}")
|
||||
continue
|
||||
rel = relation(det[:2], ref)
|
||||
rels.append(rel)
|
||||
if rel != "exact":
|
||||
misses.append((title, ref, det, rel))
|
||||
n = len(rels)
|
||||
if not n:
|
||||
print(f"{label}: nothing to score")
|
||||
return
|
||||
c = Counter(rels)
|
||||
print(f"\n{label}: {n} tracks")
|
||||
for k in WEIGHT:
|
||||
print(f" {k:9s} {c[k]:4d} {100 * c[k] / n:5.1f}%")
|
||||
print(f" MIREX weighted score {sum(WEIGHT[r] for r in rels) / n:.3f}")
|
||||
print(f" harmonically mixable (exact + fifth + relative) {100 * (c['exact'] + c['fifth'] + c['relative']) / n:.1f}%")
|
||||
if verbose:
|
||||
for title, ref, det, rel in misses:
|
||||
print(f" {rel:9s} ref {ref[0]}{'A' if ref[1] == 'minor' else 'B'} "
|
||||
f"got {det[0]}{'A' if det[1] == 'minor' else 'B'} ({det[2]}, p={det[3]:.2f}) {title[:60]}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("folders", nargs="*", type=Path, help="folders of audio files carrying a key tag")
|
||||
ap.add_argument("--giantsteps", type=Path, help="a downloaded giantsteps-key-dataset clone")
|
||||
ap.add_argument("-v", "--verbose", action="store_true", help="list every miss")
|
||||
a = ap.parse_args()
|
||||
if not a.folders and not a.giantsteps:
|
||||
ap.error("give --giantsteps and/or folders")
|
||||
if a.giantsteps:
|
||||
run(giantsteps_refs(a.giantsteps), "GiantSteps key (hand-annotated)", a.verbose)
|
||||
if a.folders:
|
||||
run(folder_refs(a.folders), "Key tags (agreement with another analyser)", a.verbose)
|
||||
sys.exit(0)
|
||||
@@ -1,6 +1,7 @@
|
||||
# Build the frozen backend sidecar on Windows (PyInstaller) and stage it for
|
||||
# Tauri as binaries\konduktor-sidecar-<target-triple>.exe.
|
||||
# Output: backend\dist\konduktor-sidecar.exe + frontend\src-tauri\binaries\...
|
||||
# Build the frozen backend sidecar on Windows (a PyInstaller onedir folder) and
|
||||
# stage it for Tauri as frontend\src-tauri\binaries\konduktor-sidecar\, which
|
||||
# tauri.conf.json bundles as a resource folder (`sidecar\` in the app).
|
||||
# Output: backend\dist\konduktor-sidecar\ + frontend\src-tauri\binaries\konduktor-sidecar\
|
||||
#
|
||||
# Run from a PowerShell prompt with the backend venv's Python on PATH, e.g.:
|
||||
# cd backend
|
||||
@@ -16,12 +17,13 @@ $Py = Join-Path $Root ".venv\Scripts\python.exe"
|
||||
if (-not (Test-Path $Py)) { $Py = "python" }
|
||||
|
||||
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
|
||||
Write-Host "Built: $Root\dist\konduktor-sidecar.exe"
|
||||
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" }
|
||||
Write-Host "Built: $Root\dist\konduktor-sidecar\"
|
||||
|
||||
# Stage for Tauri: name with the host target triple + .exe so the shell plugin
|
||||
# resolves it. (rustc must be on PATH.)
|
||||
$Triple = (& rustc -vV | Select-String '^host: ').ToString().Replace('host: ', '').Trim()
|
||||
# Stage for Tauri, replacing the whole folder so no file from an older build survives.
|
||||
$Dest = Join-Path $Root "..\frontend\src-tauri\binaries"
|
||||
New-Item -ItemType Directory -Force -Path $Dest | Out-Null
|
||||
Copy-Item "$Root\dist\konduktor-sidecar.exe" (Join-Path $Dest "konduktor-sidecar-$Triple.exe") -Force
|
||||
Write-Host "Staged: $Dest\konduktor-sidecar-$Triple.exe"
|
||||
$Staged = Join-Path $Dest "konduktor-sidecar"
|
||||
if (Test-Path $Staged) { Remove-Item -Recurse -Force $Staged }
|
||||
Copy-Item -Recurse "$Root\dist\konduktor-sidecar" $Staged
|
||||
Write-Host "Staged: $Staged\"
|
||||
+19
-23
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the frozen backend sidecar (single-file binary) with PyInstaller and
|
||||
# stage it for Tauri as binaries/konduktor-sidecar-<target-triple>.
|
||||
# Output: backend/dist/konduktor-sidecar + frontend/src-tauri/binaries/…
|
||||
# Build the frozen backend sidecar (a onedir folder) with PyInstaller and stage
|
||||
# it for Tauri as frontend/src-tauri/binaries/konduktor-sidecar/, which
|
||||
# tauri.conf.json bundles as a resource folder (`sidecar/` in the app).
|
||||
# Output: backend/dist/konduktor-sidecar/ + frontend/src-tauri/binaries/konduktor-sidecar/
|
||||
#
|
||||
# One-time: pip install -r requirements-build.txt (into the backend venv).
|
||||
set -euo pipefail
|
||||
@@ -9,25 +10,20 @@ ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||
cd "$ROOT"
|
||||
PY="${PY:-.venv/bin/python}"
|
||||
"$PY" -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
|
||||
echo "Built: $ROOT/dist/konduktor-sidecar"
|
||||
echo "Built: $ROOT/dist/konduktor-sidecar/"
|
||||
|
||||
# NOTE: do NOT re-codesign this binary. PyInstaller already ad-hoc signs the
|
||||
# one-file bootloader AND its packed libraries (Python.framework, etc.) with a
|
||||
# matching identity. Re-signing only the outer bootloader (e.g. `codesign -s -`)
|
||||
# desyncs the Team IDs, so at runtime dlopen of the extracted Python framework
|
||||
# fails with "different Team IDs" and the sidecar dies on launch (which makes
|
||||
# the Tauri app panic: "backend sidecar did not report a port"). The app bundle
|
||||
# is ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
|
||||
# which seals this binary without re-signing it.
|
||||
# NOTE: do NOT re-codesign anything in this folder. PyInstaller already ad-hoc
|
||||
# signs the executable AND its collected libraries (Python, the .so/.dylib
|
||||
# files) with a matching identity. Re-signing only some of them desyncs the
|
||||
# Team IDs, so dlopen fails with "different Team IDs" and the sidecar dies on
|
||||
# launch (the app then shows "Konduktor couldn't start"). The app bundle is
|
||||
# ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
|
||||
# which seals this folder as a resource without re-signing it.
|
||||
|
||||
# Stage for Tauri: the sidecar must be named with the host target triple so the
|
||||
# shell plugin can resolve it in both dev and bundle. (rustc must be on PATH.)
|
||||
if command -v rustc >/dev/null 2>&1; then
|
||||
TRIPLE="$(rustc -vV | sed -n 's/host: //p')"
|
||||
DEST="$ROOT/../frontend/src-tauri/binaries"
|
||||
mkdir -p "$DEST"
|
||||
cp "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar-$TRIPLE"
|
||||
echo "Staged: $DEST/konduktor-sidecar-$TRIPLE"
|
||||
else
|
||||
echo "warning: rustc not found — skipped staging the Tauri sidecar binary" >&2
|
||||
fi
|
||||
# Stage for Tauri. Replace the whole folder so no file from an older build
|
||||
# survives; `cp -R` keeps PyInstaller's symlinks as symlinks.
|
||||
DEST="$ROOT/../frontend/src-tauri/binaries"
|
||||
mkdir -p "$DEST"
|
||||
rm -rf "$DEST/konduktor-sidecar"
|
||||
cp -R "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar"
|
||||
echo "Staged: $DEST/konduktor-sidecar/"
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,32 @@
|
||||
# Goober: a rekordbox-written stick, before and after rekordbox edited it
|
||||
|
||||
The stick Ben keeps for measuring the Pioneer formats, as rekordbox 7 left it:
|
||||
11 tracks, 2 playlists, **both** libraries (`exportLibrary.db` and the legacy
|
||||
`export.pdb` + `exportExt.pdb`). `test_onelibrary_anlz.py`,
|
||||
`test_onelibrary_pdb.py` and `test_onelibrary_tracks.py` run against copies of it.
|
||||
|
||||
## What is here
|
||||
|
||||
- `PIONEER/rekordbox/` holds the three databases, **untouched**: bytes rekordbox
|
||||
wrote (snapshot `s0`, 2026-10-01).
|
||||
- `PIONEER/USBANLZ/` holds every track's `.DAT` and `.EXT`, trimmed by dropping
|
||||
whole tags: only `PPTH`, `PQTZ`, `PCOB`, `PCO2` and `PQT2` are kept, byte for
|
||||
byte. The waveforms are gone, and so are the `.2EX` files.
|
||||
- `after/` holds the same tags after **rekordbox 7 itself** edited the stick
|
||||
(snapshot `s1`, one edit per track):
|
||||
- `black-bloc-recoloured.EXT`: pad C recoloured to `0x2D` `#FF0045`.
|
||||
- `wtf-87bpm.DAT` / `.EXT`: "Result – WTF" changed from 174 to 87 BPM.
|
||||
- `demo2-pad-e-added.EXT`: a hot cue added on pad E of "Demo Track 2".
|
||||
|
||||
There is no audio. The adapter resolves paths and never needs the files, so the
|
||||
time base falls back to rekordbox's MP3 default, the same offset for reading and
|
||||
writing.
|
||||
|
||||
## Why
|
||||
|
||||
Konduktor's edits are pinned against what rekordbox wrote for the SAME edit, not
|
||||
against Konduktor's own reader. A recolour and a grid edit must reproduce
|
||||
rekordbox's bytes exactly (colour bytes, the blanked `PQT2`, loop beats cleared).
|
||||
The pdb tests prove that an in-place edit of a rekordbox-written `export.pdb`
|
||||
leaves everything else as rekordbox wrote it. The full diff of the measurement is
|
||||
in `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -56,3 +56,16 @@ implementation — open and write to it.
|
||||
|
||||
Not loaded by the tests; kept as documentation, and as the starting point if
|
||||
Konduktor ever needs to create a drive from nothing.
|
||||
|
||||
## rekordbox-edited/
|
||||
|
||||
Analysis files from a SECOND stick (Goober), after rekordbox 7 itself edited it
|
||||
(2026-10-01): a hot cue added on pad E of `demo-track-2`, and a memory cue added on
|
||||
the start of `nemean`'s memory loop. Trimmed the same way as above, by dropping
|
||||
whole tags: only `PPTH`, `PCOB` and `PCO2` are kept, byte for byte.
|
||||
|
||||
They exist for one property: rekordbox writes **compact** cue entries when it
|
||||
edits (48 bytes for that hot cue, 44 with no colour for the memory cue; an export
|
||||
writes 88). pyrekordbox's parser raises on the 44-byte form, which once made the
|
||||
reader drop the whole `.EXT`, losing pads D-H and every colour. See
|
||||
`adapters/rekordbox/anlz_file.py`.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,6 +1,14 @@
|
||||
# PyInstaller spec for the Konduktor backend sidecar (Step 1 of the standalone
|
||||
# build). Produces a single-file binary that serves the FastAPI API on a free
|
||||
# loopback port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
|
||||
# build). Produces a ONEDIR build — dist/konduktor-sidecar/ holding the
|
||||
# executable plus `_internal/` — that serves the FastAPI API on a free loopback
|
||||
# port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
|
||||
#
|
||||
# Onedir, NOT onefile: a onefile binary unpacks ~300 MB (1,000+ files, ~390
|
||||
# native libraries) into a NEW temp folder on every launch, and macOS checks
|
||||
# every library it has not seen before (XProtect / syspolicyd) as it is
|
||||
# dlopen()ed, keyed per file — so every launch paid ~10 s before the window
|
||||
# appeared (measured 2026-10-12: the same libraries took 95 s fresh, 1 s once
|
||||
# seen). Installed as a folder inside the app, they are checked once.
|
||||
#
|
||||
# The tricky bits this handles:
|
||||
# - uvicorn imports its loop/protocol backends dynamically → collect_submodules
|
||||
@@ -10,7 +18,7 @@
|
||||
# - python-multipart is imported as `multipart` by starlette → hidden import
|
||||
# - dulwich (version-history backups) imports git backends dynamically →
|
||||
# collect_submodules('dulwich')
|
||||
from PyInstaller.utils.hooks import collect_submodules, collect_all
|
||||
from PyInstaller.utils.hooks import collect_all, collect_submodules, copy_metadata
|
||||
|
||||
hiddenimports = []
|
||||
datas = []
|
||||
@@ -31,6 +39,12 @@ for pkg in ("uvloop", "httptools", "websockets", "av"):
|
||||
# Imported by name, not statically discoverable.
|
||||
hiddenimports += ["multipart", "anyio"]
|
||||
|
||||
# A remote library's password lives in the OS keychain through `keyring`, which
|
||||
# finds its backends (macOS Keychain, Windows Credential Manager) by entry point
|
||||
# — so both the modules AND the package metadata that names them must ship.
|
||||
hiddenimports += collect_submodules("keyring")
|
||||
datas += copy_metadata("keyring")
|
||||
|
||||
# Bundle the canonical version file so konduktor.__version__ can read it at
|
||||
# runtime from sys._MEIPASS (frontend/package.json is the single source of the
|
||||
# app version — see konduktor/__init__.py). Path is relative to this spec.
|
||||
@@ -48,6 +62,14 @@ datas += [
|
||||
("fixtures/rekordbox/device/export.pdb", "fixtures/rekordbox/device"),
|
||||
("fixtures/rekordbox/device/exportExt.pdb", "fixtures/rekordbox/device"),
|
||||
]
|
||||
# Which stem engine this build needs, and the pinned weights (read at import by
|
||||
# konduktor/stems/engine_manager.py).
|
||||
datas += [
|
||||
("konduktor/stems/engine.json", "konduktor/stems"),
|
||||
("konduktor/stems/weights.json", "konduktor/stems"),
|
||||
]
|
||||
# The key-detection network's weights (konduktor/core/key_detect.py).
|
||||
datas += [("konduktor/core/key_model.npz", "konduktor/core")]
|
||||
|
||||
a = Analysis(
|
||||
["sidecar.py"],
|
||||
@@ -68,9 +90,8 @@ pyz = PYZ(a.pure)
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
[],
|
||||
exclude_binaries=True,
|
||||
name="konduktor-sidecar",
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
@@ -83,3 +104,12 @@ exe = EXE(
|
||||
codesign_identity=None,
|
||||
entitlements_file=None,
|
||||
)
|
||||
|
||||
coll = COLLECT(
|
||||
exe,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
strip=False,
|
||||
upx=False,
|
||||
name="konduktor-sidecar",
|
||||
)
|
||||
@@ -5,28 +5,30 @@ Mirrors `adapters.rekordbox.adapter`. It holds:
|
||||
* a ``OneLibraryStore`` — the retained NATIVE model (the open drive),
|
||||
* a ``TrackIndex`` — the generic READ projection built from it.
|
||||
|
||||
**Read-only.** Every command is refused and `capabilities.writable` is False with
|
||||
cause `platform_incomplete`, so the UI never offers an edit in the first place;
|
||||
the raises here are the backstop, not the mechanism.
|
||||
**Editable when opened as THE library**, with parity with the Rekordbox adapter
|
||||
as the goal (decisions: `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`).
|
||||
Opened `read_only` — as the sidebar's Devices do, beside the loaded library — it
|
||||
reports `writable=False` with cause `browsing`, and every command is refused.
|
||||
|
||||
That scope is deliberate rather than provisional. The purpose of this adapter is
|
||||
to make a OneLibrary drive a readable SOURCE — the half an import into another
|
||||
library needs — and every genuinely unknown part of the format sits on the write
|
||||
side: the `cue` table's eight MPEG frame/offset columns, whose values a player
|
||||
needs to seek accurately in a VBR file; the waveform tags a CDJ draws from; and
|
||||
the update counters a drive uses to reconcile edits made on hardware. None of
|
||||
those has to be guessed at to read a drive, and none of them should be guessed at
|
||||
at all.
|
||||
What a write must look like was MEASURED by diffing a stick before and after
|
||||
rekordbox 7 edited it, rather than guessed: the update counters a drive carries
|
||||
do NOT move, and the `cue` table stays empty. Landing in steps — track metadata,
|
||||
playlists, hot cues and the beatgrid so far; adding and removing tracks next —
|
||||
and every command not written yet is refused, with its capability flag False so
|
||||
the UI never offers it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import Unsupported
|
||||
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import HotcueChip, PlaylistNode, Track, TrackCues
|
||||
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||
from ...core.query import TrackIndex
|
||||
from ..rekordbox import palette
|
||||
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
|
||||
from ...exporter import MANIFEST_NAME
|
||||
from . import capabilities as caps
|
||||
from . import projection
|
||||
from .store import OneLibraryStore
|
||||
@@ -42,23 +44,28 @@ ATTRIBUTE_SMART = 4
|
||||
class OneLibraryAdapter:
|
||||
platform = "onelibrary"
|
||||
|
||||
def __init__(self, path: Path):
|
||||
def __init__(self, path: Path, *, read_only: bool = False):
|
||||
self.path = Path(path)
|
||||
self._store = OneLibraryStore(self.path)
|
||||
self.read_only = read_only
|
||||
self._store = OneLibraryStore(self.path, read_only=read_only)
|
||||
self._index = TrackIndex()
|
||||
self._rebuild()
|
||||
|
||||
# ---- projection maintenance -----------------------------------------
|
||||
def _rebuild(self) -> None:
|
||||
self._index.rebuild(
|
||||
[
|
||||
projection.to_track(row, self._drive_path(row))
|
||||
for row in self._store.iter_content()
|
||||
]
|
||||
)
|
||||
from ...core.stem_file import is_stem_file
|
||||
|
||||
tracks = []
|
||||
for row in self._store.iter_content():
|
||||
path = self._drive_path(row)
|
||||
tracks.append(projection.to_track(
|
||||
row, path, stem=bool(path) and is_stem_file(path)))
|
||||
self._index.rebuild(tracks)
|
||||
|
||||
def _drive_path(self, row) -> str | None:
|
||||
resolved = self._store.layout.resolve(getattr(row, "path", None))
|
||||
# Through the store: an added track plays from its incoming copy until
|
||||
# Save puts it in place.
|
||||
resolved = self._store.resolve_audio(getattr(row, "path", None))
|
||||
return str(resolved) if resolved is not None else None
|
||||
|
||||
def close(self) -> None:
|
||||
@@ -70,14 +77,27 @@ class OneLibraryAdapter:
|
||||
self._store.close()
|
||||
|
||||
def reload(self) -> None:
|
||||
self._store._load()
|
||||
"""Re-read the drive, DISCARDING unsaved edits."""
|
||||
self._store.discard()
|
||||
self._rebuild()
|
||||
|
||||
def _refresh(self, track_id: str) -> None:
|
||||
"""Re-project one track after a command, so the UI cannot go stale."""
|
||||
from ...core.stem_file import is_stem_file
|
||||
|
||||
row = self._store.content(track_id)
|
||||
path = self._drive_path(row)
|
||||
self._index.replace(projection.to_track(row, path, stem=bool(path) and is_stem_file(path)))
|
||||
|
||||
# ---- identity --------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities:
|
||||
return caps.capabilities_for(
|
||||
device_name=self._store.device_name,
|
||||
version=self._store.db_version,
|
||||
read_only=self.read_only,
|
||||
editable_fields=sorted(OneLibraryStore.EDITABLE_FIELDS),
|
||||
# A drive an export set wrote carries the export's manifest at its root.
|
||||
managed_by_export=(self._store.layout.root / MANIFEST_NAME).is_file(),
|
||||
)
|
||||
|
||||
# ---- read ------------------------------------------------------------
|
||||
@@ -144,7 +164,9 @@ class OneLibraryAdapter:
|
||||
rather than an absence, and treating 0 as a real id would orphan every
|
||||
top-level playlist.
|
||||
"""
|
||||
rows = self._store.playlists()
|
||||
rows = sorted(self._store.playlists(),
|
||||
key=lambda r: (int(getattr(r, "sequenceNo", 0) or 0), int(r.playlist_id)))
|
||||
writable = not self.read_only
|
||||
nodes: dict[str, PlaylistNode] = {}
|
||||
parents: dict[str, str] = {}
|
||||
|
||||
@@ -164,13 +186,14 @@ class OneLibraryAdapter:
|
||||
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
|
||||
children=[],
|
||||
selectable=kind == "playlist",
|
||||
# Read-only: every per-node flag is False, and
|
||||
# Opened read-only, every flag is False and
|
||||
# `capabilities.writable` tells the UI why, once.
|
||||
can_add_tracks=False,
|
||||
can_reorder=False,
|
||||
can_rename=False,
|
||||
can_delete=False,
|
||||
can_add_tracks=writable and kind == "playlist",
|
||||
can_reorder=writable and kind == "playlist",
|
||||
can_rename=writable,
|
||||
can_delete=writable,
|
||||
can_contain_children=kind == "folder",
|
||||
can_move=writable,
|
||||
)
|
||||
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
|
||||
parents[node_id] = "root" if parent in ("0", "", "None") else parent
|
||||
@@ -201,6 +224,9 @@ class OneLibraryAdapter:
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
"""Ignored: a drive's paths are relative to wherever it is mounted.
|
||||
|
||||
@@ -236,32 +262,147 @@ class OneLibraryAdapter:
|
||||
# ---- save -------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return False
|
||||
return self._store.dirty
|
||||
|
||||
def save(self):
|
||||
raise Unsupported(self._readonly_reason("Saving"))
|
||||
self._require_writable("Saving")
|
||||
outcome = self._store.save()
|
||||
# Save MOVES files (an added track's audio leaves its incoming copy), so
|
||||
# the projection is rebuilt from what is now on the drive.
|
||||
self._rebuild()
|
||||
return outcome
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
|
||||
|
||||
# ---- commands: all refused -------------------------------------------
|
||||
# ---- commands -----------------------------------------------------------
|
||||
def _readonly_reason(self, what: str) -> str:
|
||||
if self.read_only:
|
||||
return (f"{what} is not possible while the drive is open for browsing. "
|
||||
"Open it for editing to change it.")
|
||||
return f"{what} is not supported yet for OneLibrary drives."
|
||||
|
||||
def _refuse(self, what: str):
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def add_tracks(self, items: list) -> list[str]:
|
||||
self._refuse("Adding tracks")
|
||||
def _require_writable(self, what: str) -> None:
|
||||
"""Every write passes through here, so a command added later cannot
|
||||
forget that a browsing drive is read-only."""
|
||||
if self.read_only:
|
||||
self._refuse(what)
|
||||
|
||||
# ---- audio placement (`tracks.places_audio`) ----------------------------
|
||||
def audio_home(self) -> Path:
|
||||
return self._store.audio_home()
|
||||
|
||||
def place_audio(self, source: Path, track) -> Path | None:
|
||||
self._require_writable("Adding tracks")
|
||||
return self._store.place_audio(source, track)
|
||||
|
||||
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
|
||||
"""Add tracks, each arriving ready to prep — as the Rekordbox adapter does.
|
||||
|
||||
A drive keeps the beatgrid, cues and waveforms in per-track analysis
|
||||
files, and rekordbox shows neither grid nor cues without them, so every
|
||||
file is decoded ONCE here and its `.DAT`/`.EXT`/`.2EX` built by the
|
||||
OneLibrary exporter's own writer — the files rekordbox 7 was verified
|
||||
to read. A file with no grid of its own gets Konduktor's.
|
||||
|
||||
Two phases, as in Rekordbox: FIRST the slow, cancellable part (decoding,
|
||||
grid detection, building the analysis and artwork bytes) before the
|
||||
library is touched; THEN the rows, with hot cues replayed through the
|
||||
ordinary `set_cue` so they keep its conventions. Memory cues — and a hot
|
||||
cue with no free pad — cross as memory cues, written with the files.
|
||||
`audio_path` is where `place_audio` said to copy it (or the file itself,
|
||||
already on the stick); Save moves copies into place.
|
||||
"""
|
||||
from ...core import audio_tags, grid_detect, key_detect, waveform
|
||||
from ...core.export import ExportTrack
|
||||
from ..rekordbox import artwork, timebase
|
||||
from .export import OneLibraryExporter
|
||||
|
||||
self._require_writable("Adding tracks")
|
||||
exporter = OneLibraryExporter()
|
||||
prepared = []
|
||||
total = len(items)
|
||||
for n, item in enumerate(items, start=1):
|
||||
audio = Path(item.audio_path)
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})", step=n, of=total)
|
||||
if not audio.is_file():
|
||||
raise InvalidCommand(f"No audio file at {audio}")
|
||||
try:
|
||||
rel = self._store.drive_relative(self._store.final_of(audio))
|
||||
except ValueError:
|
||||
raise InvalidCommand(f"{audio} is not on this drive") from None
|
||||
samples = waveform.decode(audio)
|
||||
measured = waveform.analyse_samples(samples, lead=timebase.offset(audio))
|
||||
markers = list(item.cues.grid_markers) if item.cues else []
|
||||
if not markers and samples is not None:
|
||||
try:
|
||||
found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR)
|
||||
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
|
||||
except ValueError:
|
||||
pass # no pulse to fit (a one-shot, silence): no grid
|
||||
hot, memory, taken = [], [], set()
|
||||
for cue in sorted((item.cues.cues if item.cues else []), key=lambda c: c.start):
|
||||
if (cue.role == "hotcue" and cue.slot is not None
|
||||
and 0 <= cue.slot < caps.HOTCUE_SLOTS and cue.slot not in taken):
|
||||
hot.append(cue)
|
||||
taken.add(cue.slot)
|
||||
else:
|
||||
memory.append(cue.model_copy(update={"role": "memory", "slot": None}))
|
||||
# A file with no key of its own gets one, as it gets a grid.
|
||||
track = key_detect.with_detected_key(item.track, samples, waveform.SR)
|
||||
export_track = ExportTrack(track=track, destination=audio,
|
||||
cues=TrackCues(grid_markers=markers, cues=memory))
|
||||
# Decoded once above; the writer must not decode it again.
|
||||
export_track.waveform = lambda *, lead=0.0, m=measured: m
|
||||
art = item.art or audio_tags.read_cover(audio)
|
||||
jpegs = artwork.pioneer_jpegs(art[0]) if art else None
|
||||
length = track.length or (int(measured.duration) if measured else None)
|
||||
prepared.append((item, track, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
|
||||
markers, hot, length))
|
||||
|
||||
added: list[str] = []
|
||||
for item, track, audio, rel, anlz, jpegs, markers, hot, length in prepared:
|
||||
track_id = self._store.add_track(
|
||||
audio, track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
|
||||
jpegs=jpegs, bpm=markers[0].bpm if markers else track.bpm, length=length)
|
||||
for cue in hot:
|
||||
self._store.set_cue(track_id, slot=cue.slot, start_sec=cue.start,
|
||||
cue_type="loop" if cue.length else "cue",
|
||||
length_sec=cue.length or 0.0, name=cue.name)
|
||||
code, _rgb = palette.code_for(cue.color)
|
||||
if cue.color and code:
|
||||
self._store.set_cue_color(track_id, cue.slot, code)
|
||||
added.append(track_id)
|
||||
self._rebuild()
|
||||
return added
|
||||
|
||||
def remove_tracks(self, track_ids: list[str]) -> int:
|
||||
self._refuse("Removing tracks")
|
||||
"""Remove tracks — and, on a stick, their audio and analysis files at Save
|
||||
(decision 3: a stick's audio belongs to its library)."""
|
||||
self._require_writable("Removing tracks")
|
||||
n = self._store.remove_tracks(track_ids)
|
||||
if n:
|
||||
self._rebuild()
|
||||
return n
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
self._refuse("Converting tracks to stems")
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
|
||||
self._refuse("Editing track metadata")
|
||||
self._require_writable("Editing track metadata")
|
||||
self._store.set_track_metadata(track_id, fields)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
|
||||
self._require_writable("Setting the key")
|
||||
self._store.set_key(track_id, wheel, mode)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
self._refuse("Editing cover art")
|
||||
@@ -270,52 +411,130 @@ class OneLibraryAdapter:
|
||||
return self._store.cover_art(track_id)
|
||||
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._refuse("Creating playlists")
|
||||
self._require_writable("Creating playlists")
|
||||
return self._store.create_playlist(name, parent_id)
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._refuse("Creating playlist folders")
|
||||
self._require_writable("Creating playlist folders")
|
||||
return self._store.create_folder(name, parent_id)
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
self._refuse("Renaming playlists")
|
||||
self._require_writable("Renaming playlists")
|
||||
self._store.rename_playlist(node_id, name)
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
self._refuse("Deleting playlists")
|
||||
self._require_writable("Deleting playlists")
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
self._require_writable("Moving playlists")
|
||||
return self._store.move_playlist(node_id, parent_id, index)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
self._refuse("Editing playlists")
|
||||
self._require_writable("Editing playlists")
|
||||
return self._store.set_playlist_entries(node_id, track_ids)
|
||||
|
||||
def set_cue(self, track_id: str, **kw) -> TrackCues:
|
||||
self._refuse("Editing cues")
|
||||
def _refresh_cues(self, track_id: str) -> TrackCues:
|
||||
"""Re-project a track AND return its fresh cues — every cue/grid command
|
||||
ends here, so a route can never serve a stale projection."""
|
||||
self._refresh(track_id)
|
||||
return self.track_cues(track_id) or TrackCues()
|
||||
|
||||
def _check_cue_type(self, cue_type: str) -> None:
|
||||
if cue_type not in WRITABLE_CUE_TYPES:
|
||||
raise Unsupported(f"OneLibrary has no cue type {cue_type!r}")
|
||||
|
||||
def set_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
slot: int,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
role: str = "hotcue",
|
||||
name: str | None = None,
|
||||
) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
if role != "hotcue":
|
||||
# Preserved-but-uneditable, exactly as in the Rekordbox adapter.
|
||||
raise Unsupported(
|
||||
"Memory cues are shown but cannot be edited — only hot cues are writable"
|
||||
)
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.set_cue(track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
|
||||
length_sec=length_sec, name=name)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
|
||||
self._refuse("Editing cues")
|
||||
self._require_writable("Editing cues")
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.set_cue_type(track_id, slot, cue_type)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
code = None
|
||||
if color is not None:
|
||||
code = palette.swatch_code(color)
|
||||
if code is None:
|
||||
raise InvalidCommand(f"{color!r} is not one of rekordbox's hot cue colours")
|
||||
self._store.set_cue_color(track_id, slot, code)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
self._refuse("Deleting cues")
|
||||
self._require_writable("Deleting cues")
|
||||
self._store.delete_cue(track_id, slot)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
|
||||
self._refuse("Placing cues")
|
||||
self._require_writable("Placing cues")
|
||||
for cue in cues:
|
||||
self._check_cue_type(getattr(cue, "type", "cue"))
|
||||
self._store.place_cues(track_id, cues, overwrite=overwrite)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
# ---- commands: beatgrid -----------------------------------------------
|
||||
@staticmethod
|
||||
def _markers_from(markers: list) -> list:
|
||||
"""Accept either GridMarkers or the (start, bpm) tuples routes send."""
|
||||
return [m if isinstance(m, GridMarker) else GridMarker(start=float(m[0]), bpm=float(m[1]))
|
||||
for m in markers]
|
||||
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.add_grid_marker(track_id, start_sec, bpm)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.move_grid_marker(track_id, index, start_sec)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.set_grid_marker_bpm(track_id, index, bpm)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.delete_grid_marker(track_id, index)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.replace_grid(track_id, self._markers_from(markers))
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
"""An analysis result, as rekordbox's analyser would write it: nothing is
|
||||
paired with a marker (the companion cue is Traktor's), so a replace."""
|
||||
return self.replace_grid(track_id, markers)
|
||||
|
||||
def delete_grid(self, track_id: str) -> TrackCues:
|
||||
self._refuse("Deleting the beatgrid")
|
||||
self._require_writable("Deleting the beatgrid")
|
||||
self._store.delete_grid(track_id)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||
raise Unsupported("OneLibrary has no beatgrid lock")
|
||||
@@ -28,7 +28,8 @@ __all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from
|
||||
|
||||
|
||||
def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
|
||||
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag.
|
||||
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag
|
||||
(an `anlz_file.AnlzFile`).
|
||||
|
||||
Returns None when the file has no `PQTZ` — which is a real state, not an
|
||||
error: rekordbox analyses one-shot samples too, and gives them an analysis
|
||||
@@ -39,7 +40,7 @@ def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
|
||||
for tag in getattr(anlz, "tags", []):
|
||||
if tag.type != "PQTZ":
|
||||
continue
|
||||
entries = getattr(getattr(tag.struct, "content", None), "entries", None)
|
||||
entries = tag.entries
|
||||
if not entries:
|
||||
return None
|
||||
times: list[float] = []
|
||||
|
||||
@@ -1,25 +1,27 @@
|
||||
"""What a OneLibrary drive can persist: nothing, for now.
|
||||
"""What a OneLibrary drive can persist.
|
||||
|
||||
`writable` is False with cause `platform_incomplete`. That is the distinction the
|
||||
capability system exists to draw — this is a ROADMAP GAP, not a refusal. A
|
||||
cloud-synced Rekordbox library is refused permanently to protect the user's other
|
||||
machines; a OneLibrary drive simply has no write path yet, and the UI must word
|
||||
those two very differently.
|
||||
Opened as THE library, a drive is writable, and the per-feature flags say which
|
||||
edits have landed: track metadata, playlists, hot cues, the grid, and adding
|
||||
and removing tracks, so the UI never offers an edit the adapter
|
||||
would refuse. Opened `read_only` — the sidebar's Devices, browsing beside the
|
||||
loaded library — `writable` is False with cause `browsing`, which the UI words
|
||||
as "open it for editing", not as a missing feature.
|
||||
|
||||
The per-feature flags below still report what the FORMAT supports rather than
|
||||
being blanked to false, because that is what `writable=False` is for: the UI can
|
||||
show a drive's cues and grid honestly, and say once, in one place, that the whole
|
||||
library is read-only. Blanking them would claim OneLibrary has no hot cues.
|
||||
With `writable=False` the per-feature flags still report what the FORMAT
|
||||
supports rather than being blanked, because that is what the library-level flag
|
||||
is for: the UI can show a drive's cues and grid honestly and say once, in one
|
||||
place, that the library is read-only. Blanking them would claim OneLibrary has no
|
||||
hot cues.
|
||||
|
||||
Two answers are worth recording now, while the evidence is in front of us, since
|
||||
getting them wrong later would be a silent data bug rather than a missing
|
||||
feature:
|
||||
|
||||
* cue colour is **free RGB**, not a palette index. The `PCO2` tag stores three
|
||||
bytes per cue, and the reference drive held #4D00FF, #33FF00, #00C4FF and
|
||||
#FF8C00. This differs from the desktop Rekordbox adapter, which reports
|
||||
"palette" because `djmdCue` stores an index into a built-in table — the same
|
||||
vendor, two genuinely different representations.
|
||||
* cue colour is a **palette**, like master.db's. `PCO2` stores a palette CODE
|
||||
and an RGB per cue, and rekordbox DRAWS from the code (an export writing only
|
||||
RGB had every cue in rekordbox's defaults) — so a pick is one of rekordbox's
|
||||
16 swatches and both are written. (This was first read as "free RGB" off the
|
||||
RGB bytes alone; the code byte beside them is what decides.)
|
||||
* a loop is a cue with an out-point, so ``loops="cue_type"`` — the same answer
|
||||
as Traktor and Rekordbox, and NOT the `separate_bank` the original
|
||||
multi-platform plan assumed.
|
||||
@@ -34,44 +36,59 @@ from ...core.capabilities import (
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from ..rekordbox import palette
|
||||
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
|
||||
|
||||
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
|
||||
# so the bank really is 1..8 (see `cues.py`).
|
||||
HOTCUE_SLOTS = 8
|
||||
|
||||
|
||||
def capabilities_for(device_name: str | None = None, version: str | None = None) -> Capabilities:
|
||||
def capabilities_for(
|
||||
device_name: str | None = None,
|
||||
version: str | None = None,
|
||||
*,
|
||||
read_only: bool = False,
|
||||
editable_fields: list[str] | None = None,
|
||||
managed_by_export: bool = False,
|
||||
) -> Capabilities:
|
||||
return Capabilities(
|
||||
platform="onelibrary",
|
||||
version=version,
|
||||
# A roadmap gap, not a protective refusal — the UI words the two
|
||||
# differently, which is the whole reason `readonly_cause` exists.
|
||||
writable=False,
|
||||
readonly_cause="platform_incomplete",
|
||||
writable=not read_only,
|
||||
readonly_cause="browsing" if read_only else None,
|
||||
cues=CueCapabilities(
|
||||
editable=False,
|
||||
editable=True,
|
||||
hotcue_slots=HOTCUE_SLOTS,
|
||||
slot_labels="letter",
|
||||
# OneLibrary carries memory cues, as Rekordbox does. They are
|
||||
# projected and preserved; nothing here is editable anyway.
|
||||
# OneLibrary carries memory cues, as Rekordbox does: projected and
|
||||
# preserved, NOT editable (the two-platform rule, as in Rekordbox).
|
||||
memory_cues=True,
|
||||
max_memory_cues=None,
|
||||
types=["cue", "loop"],
|
||||
color="free", # PCO2 stores RGB per cue, not a palette index
|
||||
palette=[],
|
||||
types=WRITABLE_CUE_TYPES,
|
||||
color="palette",
|
||||
palette=[palette.hex_for(code) for code in palette.SWATCHES],
|
||||
named=True, # PCO2 carries a per-cue comment
|
||||
loops="cue_type",
|
||||
),
|
||||
# The grid is the ANLZ `PQTZ` tag, per beat, and multi-tempo grids do
|
||||
# survive an export — so the format is flexible even though Konduktor
|
||||
# does not write it here.
|
||||
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
|
||||
# The grid is the ANLZ `PQTZ` tag, per beat; multi-tempo grids survive.
|
||||
# No per-track grid lock exists in the format.
|
||||
grid=GridCapabilities(editable=True, flexible=True, lockable=False),
|
||||
tracks=TrackCapabilities(
|
||||
rating_max=5, # stored 0-5 directly, as in master.db
|
||||
editable_fields=[],
|
||||
media_kinds=["audio"],
|
||||
# `artwork` gates EDITING, and a drive is read-only here. Reading
|
||||
# works: `store.cover_art` follows `content.image_id` -> `image.path`.
|
||||
# The Rekordbox adapter's set: `producer`/`mix` have no column.
|
||||
editable_fields=sorted(editable_fields or []),
|
||||
media_kinds=["audio", "stem"],
|
||||
# A stick's audio belongs to its library: added files are copied onto
|
||||
# it (laid out as rekordbox does) and a removed track's file goes
|
||||
# with it, at Save — so the library, not the user, places the audio.
|
||||
addable=not read_only,
|
||||
removable=not read_only,
|
||||
key_writable=not read_only,
|
||||
places_audio=True,
|
||||
# `artwork` gates EDITING, which Rekordbox does not do yet either
|
||||
# (parity). Reading works: `store.cover_art` follows
|
||||
# `content.image_id` -> `image.path`.
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
@@ -80,13 +97,18 @@ def capabilities_for(device_name: str | None = None, version: str | None = None)
|
||||
# A drive carries no smart playlists: rekordbox resolves them to
|
||||
# static lists on export, because a CDJ cannot evaluate rules.
|
||||
smart="none",
|
||||
reorder=False,
|
||||
reorder=True,
|
||||
),
|
||||
save=SaveCapabilities(
|
||||
app_name="OneLibrary",
|
||||
library_label=device_name or "exportLibrary.db",
|
||||
# Nothing is written, so nothing can be overwritten by another app.
|
||||
# Named for the DRIVE ("Save to Goober"): a person has several
|
||||
# sticks, and "Save to OneLibrary" would not say which.
|
||||
app_name=device_name or "OneLibrary",
|
||||
library_label="exportLibrary.db",
|
||||
# Another app writing the drive between open and save is CAUGHT,
|
||||
# not risked: the store fingerprints the database at open and
|
||||
# refuses to save over a change it did not make.
|
||||
overwrite_risk="none",
|
||||
managed_by_export=managed_by_export,
|
||||
# A drive is a database plus N analysis files plus the audio itself,
|
||||
# so there is no single blob that IS the library — the same reason
|
||||
# Rekordbox libraries are not versioned.
|
||||
|
||||
@@ -37,6 +37,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
|
||||
from ...core.model import CuePoint
|
||||
from ..rekordbox import palette
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -47,14 +48,13 @@ NO_LOOP = 0xFFFFFFFF
|
||||
# `hot_cue` for a cue that sits in no pad bank, i.e. a memory cue.
|
||||
MEMORY_SLOT = 0
|
||||
|
||||
# PCO2/PCOB entry kinds. The value is the same in both tags; PCOB exposes it as
|
||||
# a construct enum and PCO2 as a plain int, so both are normalised to an int.
|
||||
# PCO2/PCOB entry kinds. The value is the same in both tags.
|
||||
ENTRY_CUE = 1
|
||||
ENTRY_LOOP = 2
|
||||
|
||||
|
||||
def _entry_kind(value) -> int:
|
||||
"""PCOB gives an enum, PCO2 an int — one number out of either."""
|
||||
"""An entry's kind as an int, defaulting to a point cue if unreadable."""
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
@@ -68,8 +68,17 @@ def _color(entry) -> str | None:
|
||||
real black in principle, but rekordbox uses it as "unset" and shows such a
|
||||
cue in the default colour, so it is reported as no colour rather than as
|
||||
black. Memory cues in the reference export are exactly this case.
|
||||
|
||||
rekordbox DRAWS a cue from its palette CODE (`rekordbox.palette`), so a known
|
||||
code is reported as that swatch; a cue with code 0 and an RGB (older
|
||||
exports, the reference fixture) is reported by its RGB.
|
||||
"""
|
||||
swatch = palette.hex_for(getattr(entry, "color_code", None))
|
||||
if swatch is not None:
|
||||
return swatch
|
||||
try:
|
||||
# None on an entry too short to carry a colour: every PCPT, and the
|
||||
# compact 44-byte PCP2 rekordbox writes for a memory cue it added.
|
||||
r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
return None
|
||||
@@ -78,7 +87,7 @@ def _color(entry) -> str | None:
|
||||
return f"#{r:02X}{g:02X}{b:02X}"
|
||||
|
||||
|
||||
def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
|
||||
def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | None:
|
||||
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
|
||||
try:
|
||||
hot_cue = int(entry.hot_cue)
|
||||
@@ -111,11 +120,11 @@ def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
|
||||
length=length,
|
||||
slot=slot,
|
||||
color=_color(entry) if with_color else None,
|
||||
# A OneLibrary drive is read-only in Konduktor, so no cue accepts a
|
||||
# command. `capabilities.writable` is what the UI actually gates on;
|
||||
# this keeps the per-cue answer consistent with it.
|
||||
editable=False,
|
||||
readonly_reason="platform_managed",
|
||||
# Hot cues are editable on a drive opened for editing (the caller says
|
||||
# so). MEMORY cues never are — preserved-but-uneditable, as in the
|
||||
# Rekordbox adapter (the two-platform rule).
|
||||
editable=editable and role == "hotcue",
|
||||
readonly_reason=None if editable and role == "hotcue" else "platform_managed",
|
||||
grid_marker=None,
|
||||
)
|
||||
|
||||
@@ -130,15 +139,14 @@ def _entries(anlz, tag_type: str) -> list:
|
||||
"""
|
||||
out: list = []
|
||||
for tag in getattr(anlz, "tags", []):
|
||||
if tag.type != tag_type:
|
||||
continue
|
||||
content = getattr(tag.struct, "content", None)
|
||||
out.extend(getattr(content, "entries", None) or [])
|
||||
if tag.type == tag_type:
|
||||
out.extend(tag.entries)
|
||||
return out
|
||||
|
||||
|
||||
def cues_from_anlz(dat, ext) -> list[CuePoint]:
|
||||
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`.
|
||||
def cues_from_anlz(dat, ext, *, editable: bool = False) -> list[CuePoint]:
|
||||
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`
|
||||
(`rekordbox.anlz_file.AnlzFile`s).
|
||||
|
||||
Either may be None — a drive can carry a `.DAT` with no `.EXT` — and a track
|
||||
with no cues at all yields an empty list rather than an error.
|
||||
@@ -153,14 +161,14 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
|
||||
for f in files:
|
||||
pco2.extend(_entries(f, "PCO2"))
|
||||
if pco2:
|
||||
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True)) is not None]
|
||||
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True, editable=editable)) is not None]
|
||||
else:
|
||||
# Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the
|
||||
# .EXT the rest, so either alone is an incomplete bank.
|
||||
pcob: list = []
|
||||
for f in files:
|
||||
pcob.extend(_entries(f, "PCOB"))
|
||||
cues = [c for e in pcob if (c := _to_cue(e, with_color=False)) is not None]
|
||||
cues = [c for e in pcob if (c := _to_cue(e, with_color=False, editable=editable)) is not None]
|
||||
|
||||
return _dedupe(cues)
|
||||
|
||||
@@ -168,18 +176,23 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
|
||||
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
|
||||
"""Collapse the same cue appearing in more than one tag or file.
|
||||
|
||||
Identity is (role, slot, start) rather than the whole cue: the same pad can
|
||||
be described by both `PCOB` and `PCO2`, and by both files, and those copies
|
||||
agree on position while differing in how much detail they carry. The first
|
||||
one wins, which — given PCO2 is read first — is the richest.
|
||||
Identity is (role, slot, start, type, length) rather than the whole cue:
|
||||
the same pad can be described by both `PCOB` and `PCO2`, and by both files,
|
||||
and those copies agree on all five while differing in how much detail they
|
||||
carry (colour, comment). The first one wins, which — given PCO2 is read
|
||||
first — is the richest.
|
||||
|
||||
Type and length are part of it because two MEMORY cues may share a position:
|
||||
rekordbox happily stores a memory cue on the start of a memory loop (seen on
|
||||
Goober), and keying on position alone silently dropped the loop.
|
||||
|
||||
Ordered by position, then by slot, so the projection is stable across reads
|
||||
regardless of the order the tags happened to store.
|
||||
"""
|
||||
seen: set[tuple[str, int | None, int]] = set()
|
||||
seen: set[tuple] = set()
|
||||
out: list[CuePoint] = []
|
||||
for c in cues:
|
||||
key = (c.role, c.slot, round(c.start * 1000))
|
||||
key = (c.role, c.slot, round(c.start * 1000), c.type, round(c.length * 1000))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Keeping a stick's legacy Device Library (`export.pdb`) in step with its OneLibrary.
|
||||
|
||||
Most rekordbox sticks carry BOTH: `exportLibrary.db` (OneLibrary, newer players)
|
||||
and `export.pdb` (the Device Library, older players and rekordbox's own "Device
|
||||
Library" view). Cues and the grid live in the analysis files both share, so they
|
||||
follow an edit by themselves; titles and playlists live in each database
|
||||
separately. **rekordbox itself lets them drift**: measured on Goober
|
||||
(2026-10-01), its edits updated the pdb's track metadata but not a new playlist
|
||||
or a reorder. Konduktor rebuilds the pdb at Save instead (decision 2 of the
|
||||
editing discussion), so a stick never shows different playlists depending on
|
||||
which player reads it.
|
||||
|
||||
**Ids are mirrored, not assigned.** rekordbox exports both libraries from the
|
||||
same ids — pdb track id = `content_id`, the artist/album/genre/label/key ids, the
|
||||
playlist ids, playlist `sort` = `sequenceNo`, entries `(sequenceNo, content_id,
|
||||
playlist_id)`, artwork id = `image_id` — all checked on Goober. So the OneLibrary
|
||||
database IS the answer for every row the pdb shares with it.
|
||||
|
||||
**An edit, not a regeneration.** The stick's own `export.pdb` is edited in place
|
||||
(`pdb.PdbEditor`): only the tracks, the lookup tables (artist, album, genre,
|
||||
label, key), artwork and the playlist tree and entries are candidates, a table is rewritten only if one of its rows changed,
|
||||
and an unchanged row keeps rekordbox's bytes. A changed TRACK row is the old row
|
||||
with the edited fields overwritten, so everything the pdb holds that OneLibrary
|
||||
does not — the phrase-analysis strings, the `masterDbId` halves, play counts,
|
||||
dates — survives. History, colours, menus and `exportExt.pdb` are never touched.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import struct
|
||||
from pathlib import Path
|
||||
|
||||
from ..rekordbox import pdb
|
||||
|
||||
#: Tables this rebuild owns. Everything else in the file is left as it is.
|
||||
_OWNED = (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES, pdb.LABELS, pdb.KEYS,
|
||||
pdb.ARTWORK, pdb.PLAYLIST_TREE, pdb.PLAYLIST_ENTRIES)
|
||||
|
||||
|
||||
def _lookup_name(table: int, row: bytes) -> str:
|
||||
if table == pdb.ARTISTS:
|
||||
sub, _shift, _rid, _b, ofs = struct.unpack_from("<HHIBB", row, 0)
|
||||
if sub == 0x64:
|
||||
ofs = struct.unpack_from("<H", row, 10)[0]
|
||||
return pdb.read_dsql(row, ofs)
|
||||
if table == pdb.ALBUMS:
|
||||
sub, _shift, _u, _artist, _rid, _u3, _b, ofs = struct.unpack_from("<HHIIIIBB", row, 0)
|
||||
return pdb.read_dsql(row, ofs)
|
||||
if table == pdb.KEYS:
|
||||
return pdb.read_dsql(row, 8)
|
||||
return pdb.read_dsql(row, 4)
|
||||
|
||||
|
||||
def _pdb_art_path(path: str | None) -> str:
|
||||
"""OneLibrary's `image.path` names the `b<n>` file; export.pdb's artwork row
|
||||
the byte-identical `a<n>` beside it (as on Goober, and as rekordbox writes)."""
|
||||
return re.sub(r"/b(\d+)(\.jpg)$", r"/a\1\2", path or "")
|
||||
|
||||
|
||||
def _tree_value(row: bytes) -> tuple:
|
||||
parent, _u, sort, rid, folder = struct.unpack_from("<5I", row, 0)
|
||||
return parent, sort, rid, bool(folder), pdb.read_dsql(row, 20)
|
||||
|
||||
|
||||
def _merge(old: list[bytes], new: dict, table: int, same) -> list[bytes] | None:
|
||||
"""The table's rows: old ORDER kept, an unchanged row's old BYTES kept, new
|
||||
rows appended by id. None when nothing changed (the table is not rewritten).
|
||||
|
||||
`new` maps row id -> (value, encode()); `same(old_row, value)` says whether
|
||||
an old row already says `value`.
|
||||
"""
|
||||
out, changed, seen = [], False, set()
|
||||
for row in old:
|
||||
rid = pdb.row_id(table, row)
|
||||
if rid not in new:
|
||||
changed = True # removed
|
||||
continue
|
||||
seen.add(rid)
|
||||
value, encode = new[rid]
|
||||
if same(row, value):
|
||||
out.append(row)
|
||||
else:
|
||||
out.append(encode())
|
||||
changed = True
|
||||
for rid in sorted((r for r in new if r not in seen), key=str):
|
||||
out.append(new[rid][1]())
|
||||
changed = True
|
||||
return out if changed else None
|
||||
|
||||
|
||||
def rebuild(existing: bytes, session) -> bytes | None:
|
||||
"""`export.pdb` edited to match the OneLibrary database open in `session`
|
||||
(the working copy, edits committed); None if it already matches."""
|
||||
from sqlalchemy import text
|
||||
|
||||
tables: dict[int, list[bytes]] = {}
|
||||
|
||||
# ---- lookups ----------------------------------------------------------------
|
||||
for table, sql, build in (
|
||||
(pdb.ARTISTS, "SELECT artist_id, name FROM artist", pdb.artist_row),
|
||||
# rekordbox's export leaves an album's artist 0 (see `pdb.album_row`).
|
||||
(pdb.ALBUMS, "SELECT album_id, name FROM album", pdb.album_row),
|
||||
(pdb.GENRES, "SELECT genre_id, name FROM genre", pdb.id_string_row),
|
||||
(pdb.LABELS, "SELECT label_id, name FROM label", pdb.id_string_row),
|
||||
(pdb.KEYS, "SELECT key_id, name FROM key", pdb.key_row),
|
||||
):
|
||||
want = {int(i): (name or "", (lambda i=i, n=name, b=build: b(int(i), n or "")))
|
||||
for i, name in session.execute(text(sql))}
|
||||
merged = _merge(pdb.table_rows(existing, table), want, table,
|
||||
lambda row, value, t=table: _lookup_name(t, row) == value)
|
||||
if merged is not None:
|
||||
tables[table] = merged
|
||||
|
||||
want = {int(i): (_pdb_art_path(path), (lambda i=i, p=path: pdb.id_string_row(int(i), _pdb_art_path(p))))
|
||||
for i, path in session.execute(text("SELECT image_id, path FROM image"))}
|
||||
merged = _merge(pdb.table_rows(existing, pdb.ARTWORK), want, pdb.ARTWORK,
|
||||
lambda row, value: pdb.read_dsql(row, 4) == value)
|
||||
if merged is not None:
|
||||
tables[pdb.ARTWORK] = merged
|
||||
|
||||
# ---- tracks -----------------------------------------------------------------
|
||||
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
|
||||
want = {}
|
||||
for (cid, title, artist, remixer, album, genre, label, rating, bpm, year, released,
|
||||
comment, *fresh) in session.execute(text(
|
||||
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, "
|
||||
"label_id, rating, bpmx100, releaseYear, releaseDate, djComment, "
|
||||
"path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, "
|
||||
"analysisDataFilePath, dateAdded, key_id, image_id FROM content")):
|
||||
cid = int(cid)
|
||||
if cid in old_tracks:
|
||||
fields, strings = pdb.track_fields(old_tracks[cid])
|
||||
else:
|
||||
fields, strings = _fresh_track(cid, *fresh)
|
||||
fields = {**fields, "artist_id": artist or 0, "remixer_id": remixer or 0,
|
||||
"album_id": album or 0, "genre_id": genre or 0, "label_id": label or 0,
|
||||
"rating": max(0, min(5, int(rating or 0))), "tempo": int(bpm or 0),
|
||||
"year": int(year or 0)}
|
||||
strings = {**strings, "title": title or "", "comment": comment or "",
|
||||
"release_date": released or ""}
|
||||
want[cid] = ((fields, strings),
|
||||
(lambda f=fields, s=strings: pdb.track_row(f, s)))
|
||||
merged = _merge(list(old_tracks.values()), want, pdb.TRACKS,
|
||||
lambda row, value: _same_track(pdb.track_fields(row), value))
|
||||
if merged is not None:
|
||||
tables[pdb.TRACKS] = merged
|
||||
|
||||
# ---- playlists ----------------------------------------------------------------
|
||||
want = {int(pid): ((int(parent or 0), int(seq or 0), int(pid), int(attr or 0) == 1, name or ""),
|
||||
(lambda p=pid, par=parent, s=seq, n=name, a=attr:
|
||||
pdb.playlist_tree_row(int(p), int(par or 0), int(s or 0), n or "",
|
||||
folder=int(a or 0) == 1)))
|
||||
for pid, parent, seq, name, attr in session.execute(text(
|
||||
"SELECT playlist_id, playlist_id_parent, sequenceNo, name, attribute FROM playlist"))}
|
||||
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_TREE), want, pdb.PLAYLIST_TREE,
|
||||
lambda row, value: _tree_value(row) == value)
|
||||
if merged is not None:
|
||||
tables[pdb.PLAYLIST_TREE] = merged
|
||||
|
||||
want = {}
|
||||
for pid, cid, seq in session.execute(text(
|
||||
"SELECT playlist_id, content_id, sequenceNo FROM playlist_content "
|
||||
"ORDER BY playlist_id, sequenceNo")):
|
||||
key = (int(seq), int(cid), int(pid))
|
||||
want[key] = (key, (lambda k=key: pdb.playlist_entry_row(*k)))
|
||||
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_ENTRIES), want, pdb.PLAYLIST_ENTRIES,
|
||||
lambda row, value: True)
|
||||
if merged is not None:
|
||||
tables[pdb.PLAYLIST_ENTRIES] = merged
|
||||
|
||||
if not tables:
|
||||
return None
|
||||
editor = pdb.PdbEditor(existing)
|
||||
for table in _OWNED:
|
||||
if table in tables:
|
||||
editor.refill(table, tables[table])
|
||||
return editor.render()
|
||||
|
||||
|
||||
def _same_track(old: tuple[dict, dict], new: tuple[dict, dict]) -> bool:
|
||||
"""Equal in every field that means something: `index_shift` is the row's slot
|
||||
in its page, re-stamped whenever a page is written."""
|
||||
(of, os_), (nf, ns) = old, new
|
||||
return ({k: v for k, v in of.items() if k != "index_shift"}
|
||||
== {k: v for k, v in nf.items() if k != "index_shift"} and os_ == ns)
|
||||
|
||||
|
||||
def _fresh_track(cid: int, path, file_name, file_size, file_type, bitrate, bit_depth,
|
||||
sample_rate, length, analysis, date_added, key_id, image_id) -> tuple[dict, dict]:
|
||||
"""A track the pdb has never listed (one added to the stick by Konduktor), in
|
||||
the shape `device_export` writes one — the values a rekordbox device export
|
||||
was measured to carry (see that module)."""
|
||||
from ..rekordbox.device_export import ANALYSED, BITMASK
|
||||
|
||||
added = str(date_added or "")[:10]
|
||||
fields = {
|
||||
"subtype": 0x24, "bitmask": BITMASK, "sample_rate": int(sample_rate or 0),
|
||||
"file_size": int(file_size or 0), "u2": cid + 0x600, "artwork_id": int(image_id or 0),
|
||||
"key_id": int(key_id or 0), "bitrate": int(bitrate or 0), "id": cid,
|
||||
"sample_depth": int(bit_depth or 0), "duration": min(int(length or 0), 0xFFFF),
|
||||
"u5": ANALYSED, "u6": int(file_type or 0), "u7": 3,
|
||||
}
|
||||
strings = {
|
||||
"kuvo_public": "ON", "autoload_hotcues": "ON", "date_added": added,
|
||||
"analyze_path": analysis or "", "analyze_date": added,
|
||||
"filename": file_name or Path(str(path or "")).name, "file_path": path or "",
|
||||
}
|
||||
return fields, strings
|
||||
@@ -49,7 +49,7 @@ class OneLibraryDriver:
|
||||
def _has_onelibrary_schema(path: Path) -> bool:
|
||||
try:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.devicelib_plus.database import BLOB
|
||||
from pyrekordbox.onelibrary.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
except ImportError: # pragma: no cover — dependency missing
|
||||
return False
|
||||
@@ -73,8 +73,8 @@ class OneLibraryDriver:
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> OneLibraryAdapter:
|
||||
return OneLibraryAdapter(path)
|
||||
def open(self, path: Path, *, read_only: bool = False) -> OneLibraryAdapter:
|
||||
return OneLibraryAdapter(path, read_only=read_only)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
return discovery.detect_libraries()
|
||||
|
||||
@@ -121,7 +121,7 @@ class OneLibraryExporter:
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.devicelib_plus.database import BLOB
|
||||
from pyrekordbox.onelibrary.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
|
||||
root = Path(destination)
|
||||
@@ -265,21 +265,21 @@ class OneLibraryExporter:
|
||||
n = counter["next"]
|
||||
folder = root / "PIONEER" / "Artwork" / "00001"
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
small, medium = jpegs
|
||||
files = []
|
||||
for letter in ("a", "b"):
|
||||
for suffix, data in (("", small), ("_m", medium)):
|
||||
path = folder / f"{letter}{n}{suffix}.jpg"
|
||||
path.write_bytes(data)
|
||||
files.append(path)
|
||||
for rel, data in art_files(n, jpegs):
|
||||
path = root / rel.lstrip("/")
|
||||
path.write_bytes(data)
|
||||
files.append(path)
|
||||
con.execute("INSERT INTO image (image_id, path) VALUES (?, ?)",
|
||||
(n, f"/PIONEER/Artwork/00001/b{n}.jpg"))
|
||||
return n, files
|
||||
|
||||
# ---- the analysis files --------------------------------------------------
|
||||
|
||||
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
|
||||
"""The `.DAT`, `.EXT` and `.2EX`, as rekordbox 7 writes them.
|
||||
def anlz_files(self, item: ExportTrack, rel: str) -> list[tuple[str, bytes]]:
|
||||
"""The `.DAT`, `.EXT` and `.2EX` as `(suffix, bytes)`, as rekordbox 7 writes
|
||||
them — built, not written, so a library adding a track to a stick can hold
|
||||
them until Save (`OneLibraryStore.add_track`).
|
||||
|
||||
All three, and every cue list, even for a track with no cues: rekordbox
|
||||
never produces a track without them, and `PCO2` — the complete list,
|
||||
@@ -318,9 +318,18 @@ class OneLibraryExporter:
|
||||
tags += previews
|
||||
tags += W.cue_tags(cues, extended=False)
|
||||
ext = [W.path_tag(rel), *ext_waves[:1], *W.cue_tags(cues, extended=True), *ext_waves[1:]]
|
||||
written = [W.write_anlz(dat, tags), W.write_anlz(dat.with_suffix(".EXT"), ext)]
|
||||
files = [(".DAT", W.anlz_bytes(tags)), (".EXT", W.anlz_bytes(ext))]
|
||||
if two_ex:
|
||||
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(rel), *two_ex]))
|
||||
files.append((".2EX", W.anlz_bytes([W.path_tag(rel), *two_ex])))
|
||||
return files
|
||||
|
||||
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
|
||||
written = []
|
||||
for suffix, data in self.anlz_files(item, rel):
|
||||
path = dat.with_suffix(suffix)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
written.append(path)
|
||||
return written
|
||||
|
||||
@staticmethod
|
||||
@@ -372,7 +381,8 @@ class OneLibraryExporter:
|
||||
# ---- playlists -----------------------------------------------------------
|
||||
|
||||
def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None:
|
||||
"""One folder named after the export, with the tree preserved under it.
|
||||
"""The tree preserved — at the top level (parent NULL), or with
|
||||
`payload.root_folder` under one folder named after the export.
|
||||
|
||||
`playlist` is a flat table with `playlist_id_parent`, so folders and
|
||||
playlists are the same row kind told apart by `attribute` (1 = folder).
|
||||
@@ -388,8 +398,8 @@ class OneLibraryExporter:
|
||||
)
|
||||
return next_id[0]
|
||||
|
||||
root = add(payload.name, None, folder=True)
|
||||
folders: dict[tuple[str, ...], int] = {(): root}
|
||||
root = add(payload.name, None, folder=True) if payload.root_folder else None
|
||||
folders: dict[tuple[str, ...], int | None] = {(): root}
|
||||
|
||||
for playlist in payload.playlists:
|
||||
parent = root
|
||||
@@ -418,12 +428,23 @@ class OneLibraryExporter:
|
||||
)
|
||||
|
||||
|
||||
#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them.
|
||||
#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player.
|
||||
#: rekordbox's `fileType` codes. `.stem.m4a` (a Traktor STEM) is an M4A to a
|
||||
#: Pioneer player. `pyrekordbox.onelibrary.FileType` now also lists MP4 = 3 (the
|
||||
#: `.mp4` container) and ALAC = 6 (an ALAC `.m4a`); neither is measured here, so
|
||||
#: both still write 4.
|
||||
_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
|
||||
".aif": 12, ".aiff": 12}
|
||||
|
||||
|
||||
def art_files(n: int, jpegs: tuple[bytes, bytes]) -> list[tuple[str, bytes]]:
|
||||
"""Image `n`'s four files as `(drive-relative path, bytes)`: `a<n>`/`b<n>`
|
||||
and their `_m`, byte-identical pairs, in `Artwork/00001/` (see `_write_art`).
|
||||
`image.path` names the `b` file; `export.pdb`'s artwork table the `a` one."""
|
||||
small, medium = jpegs
|
||||
return [(f"/PIONEER/Artwork/00001/{letter}{n}{suffix}.jpg", data)
|
||||
for letter in ("a", "b") for suffix, data in (("", small), ("_m", medium))]
|
||||
|
||||
|
||||
def _file_type(path: Path) -> int:
|
||||
return _FILE_TYPES.get(path.suffix.lower(), 1)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""OneLibrary rows -> the generic projection.
|
||||
|
||||
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` /
|
||||
The only place a ``pyrekordbox.onelibrary`` ORM object becomes a generic `Track` /
|
||||
`TrackCues`. Everything above this file sees generic types exclusively.
|
||||
|
||||
Field conventions are read off a real rekordbox 7 export rather than guessed:
|
||||
@@ -54,7 +54,7 @@ def _bpm(row) -> float | None:
|
||||
return round(int(raw) / 100.0, 2)
|
||||
|
||||
|
||||
def to_track(row, drive_path: str | None = None) -> Track:
|
||||
def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track:
|
||||
"""Project one ``Content`` row.
|
||||
|
||||
**The three count fields are approximations here**, and deliberately so. Cues
|
||||
@@ -104,7 +104,8 @@ def to_track(row, drive_path: str | None = None) -> Track:
|
||||
hotcue_count=0,
|
||||
grid_marker_count=1 if (bpm and has_analysis) else 0,
|
||||
grid_locked=False, # OneLibrary has no grid lock
|
||||
media_kind="audio",
|
||||
# What the FILE is, as the deck plays it — see the Rekordbox projection.
|
||||
media_kind="stem" if stem else "audio",
|
||||
)
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -21,13 +21,14 @@ from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import Unsupported
|
||||
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||
from ...core.query import TrackIndex
|
||||
from . import capabilities as caps
|
||||
from . import projection
|
||||
from . import palette, projection, timebase
|
||||
from ...core import add_analysis
|
||||
from .store import RekordboxStore
|
||||
|
||||
|
||||
@@ -46,7 +47,8 @@ class RekordboxAdapter:
|
||||
kinds = self._store.cue_kinds()
|
||||
self._index.rebuild(
|
||||
[
|
||||
projection.to_track(row, kinds.get(str(row.ID), ()))
|
||||
projection.to_track(row, kinds.get(str(row.ID), ()),
|
||||
stem=self._store.is_stem(str(row.ID)))
|
||||
for row in self._store.iter_content()
|
||||
]
|
||||
)
|
||||
@@ -68,7 +70,8 @@ class RekordboxAdapter:
|
||||
"""
|
||||
kinds = self._store.cue_kinds()
|
||||
row = self._store.content(track_id)
|
||||
self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ())))
|
||||
self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ()),
|
||||
stem=self._store.is_stem(str(row.ID))))
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the database connection.
|
||||
@@ -169,6 +172,7 @@ class RekordboxAdapter:
|
||||
can_rename=writable,
|
||||
can_delete=writable,
|
||||
can_contain_children=kind == "folder",
|
||||
can_move=writable,
|
||||
)
|
||||
parent = str(r.ParentID or "root")
|
||||
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
|
||||
@@ -200,8 +204,13 @@ class RekordboxAdapter:
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
# The FILE decides a track's media kind, and the mapping moves files.
|
||||
self._rebuild()
|
||||
|
||||
def unresolved_path_groups(self) -> list:
|
||||
"""Not checked yet: the open-time missing-files check is Traktor-only
|
||||
@@ -211,6 +220,10 @@ class RekordboxAdapter:
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
return None
|
||||
|
||||
def set_write_stored_paths(self, enabled: bool) -> None:
|
||||
"""OPTIONAL: see `TraktorAdapter.set_write_stored_paths`."""
|
||||
self._store.set_write_stored_paths(enabled)
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
paths = self._store.all_audio_paths()
|
||||
primary = common_dir_prefix(paths)
|
||||
@@ -241,6 +254,12 @@ class RekordboxAdapter:
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
|
||||
self._require_writable("Setting the key")
|
||||
self._store.set_key(track_id, wheel, mode)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
# ---- commands: playlists ----------------------------------------------
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._require_writable("Creating playlists")
|
||||
@@ -258,6 +277,10 @@ class RekordboxAdapter:
|
||||
self._require_writable("Deleting playlists")
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
self._require_writable("Moving playlists")
|
||||
return self._store.move_playlist(node_id, parent_id, index)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
self._require_writable("Editing playlists")
|
||||
return self._store.set_playlist_entries(node_id, track_ids)
|
||||
@@ -299,6 +322,18 @@ class RekordboxAdapter:
|
||||
self._store.set_cue_type(track_id, slot, cue_type)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
code = None
|
||||
if color is not None:
|
||||
code = palette.swatch_code(color)
|
||||
if code is None:
|
||||
raise InvalidCommand(
|
||||
f"{color!r} is not one of Rekordbox's hot cue colours"
|
||||
)
|
||||
self._store.set_cue_color(track_id, slot, code)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
self._require_writable("Deleting cues")
|
||||
self._store.delete_cue(track_id, slot)
|
||||
@@ -366,6 +401,12 @@ class RekordboxAdapter:
|
||||
def dirty(self) -> bool:
|
||||
return self._store.dirty
|
||||
|
||||
def edit_summary(self) -> str:
|
||||
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
|
||||
tracks; added 6 hotcues") — what a server tells the next computer to
|
||||
open the library about the edits it is inheriting."""
|
||||
return self._store._journal.summary()
|
||||
|
||||
def save(self):
|
||||
self._require_writable("Saving")
|
||||
return self._store.save()
|
||||
@@ -400,19 +441,108 @@ class RekordboxAdapter:
|
||||
if self._cloud_synced:
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def add_tracks(self, items: list) -> list[str]:
|
||||
# Not a refusal in principle — Rekordbox could receive imported
|
||||
# tracks — but adding one means a djmdContent row, its lookup-table
|
||||
# foreign keys, a USN, and an ANLZ file built from scratch, which
|
||||
# is unexplored (see the export handoff). Traktor is the only
|
||||
# import target for now.
|
||||
self._refuse("Adding tracks")
|
||||
def analysis_lead(self, audio: Path) -> float:
|
||||
"""The time-base lead `add_tracks` measures a file's waveform with —
|
||||
rekordbox's clock against the decoded audio, read from the file's
|
||||
header (`timebase.py`). OPTIONAL on the protocol: a platform that does
|
||||
not analyse what it adds has none, and whoever prepares an analysis
|
||||
for this one (a client of a server-held library) asks for it."""
|
||||
return timebase.offset(Path(audio))
|
||||
|
||||
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
|
||||
"""Add tracks that came from somewhere else, with their prep.
|
||||
|
||||
Rekordbox keeps the beatgrid AND the waveforms in per-track analysis
|
||||
files, and shows neither grid nor cues for a track without them — so
|
||||
unlike Traktor, which re-analyses on load, every file is decoded here.
|
||||
A file that brings no grid gets one from Konduktor's own detector
|
||||
(decided 2026-10-01: a track should arrive ready to prep).
|
||||
|
||||
Two phases, and the split is the point. FIRST every file is decoded and
|
||||
analysed, which is slow and may be cancelled through `checkpoint` —
|
||||
before the library is touched, so a cancel leaves it as it was. THEN
|
||||
each row is added and its grid and cues replayed through the ordinary
|
||||
store commands (`replace_grid`, `set_cue`), so an added track inherits
|
||||
their conventions and tests rather than growing a second copy.
|
||||
|
||||
Nothing is lost on the way in: Rekordbox has memory cues and coloured
|
||||
cues, so both cross as themselves. A hot cue whose pad is out of the
|
||||
bank or already taken becomes a memory cue at the same position rather
|
||||
than being dropped.
|
||||
"""
|
||||
from ...core import audio_tags
|
||||
|
||||
self._require_writable("Adding tracks")
|
||||
held = set(self._store.all_audio_paths())
|
||||
prepared = []
|
||||
total = len(items)
|
||||
for n, item in enumerate(items, start=1):
|
||||
audio = Path(item.audio_path)
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})",
|
||||
step=n, of=total)
|
||||
if not audio.is_file():
|
||||
raise InvalidCommand(f"No audio file at {audio}")
|
||||
if str(audio) in held:
|
||||
raise InvalidCommand(f"The library already holds {audio}")
|
||||
held.add(str(audio))
|
||||
markers = list(item.cues.grid_markers) if item.cues else []
|
||||
if item.analysis is not None:
|
||||
# Measured by whoever added it — a library held by a server is
|
||||
# never asked to decode audio (see `PreparedAnalysis`).
|
||||
analysed = item.analysis
|
||||
if not markers:
|
||||
markers = list(analysed.markers)
|
||||
else:
|
||||
analysed = add_analysis.prepare(audio, lead=self.analysis_lead(audio),
|
||||
detect=not markers,
|
||||
detect_key=item.track.key_wheel is None)
|
||||
markers = markers or list(analysed.markers)
|
||||
measured = analysed.measured
|
||||
# A file with no key of its own gets one, as it gets a grid
|
||||
# (decided: arrive ready to prep). Rekordbox's own add analyses one.
|
||||
track = add_analysis.with_key(item.track, analysed.key)
|
||||
art = item.art or audio_tags.read_cover(audio)
|
||||
prepared.append((item, track, audio, measured, markers, art[0] if art else None))
|
||||
|
||||
added: list[str] = []
|
||||
for item, track, audio, measured, markers, art in prepared:
|
||||
track_id = self._store.add_track(
|
||||
audio, track, measured=measured, with_grid=bool(markers), art=art)
|
||||
self._index.add(projection.to_track(self._store.content(track_id), (),
|
||||
stem=self._store.is_stem(track_id)))
|
||||
if markers:
|
||||
self._store.replace_grid(track_id, markers)
|
||||
if item.cues is not None:
|
||||
self._place_imported_cues(track_id, item.cues)
|
||||
self._refresh(track_id)
|
||||
added.append(track_id)
|
||||
return added
|
||||
|
||||
def _place_imported_cues(self, track_id: str, cues) -> None:
|
||||
"""Hot cues on their own pads; memory cues — and a hot cue with no
|
||||
free pad — as memory cues. Colour as the nearest palette swatch."""
|
||||
taken: set[int] = set()
|
||||
for cue in sorted(cues.cues or [], key=lambda c: c.start):
|
||||
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
|
||||
code, _rgb = palette.code_for(cue.color)
|
||||
common = dict(start_sec=cue.start, cue_type=cue_type,
|
||||
length_sec=getattr(cue, "length", 0.0) or 0.0,
|
||||
name=getattr(cue, "name", None), color_code=code or None)
|
||||
slot = cue.slot if cue.role == "hotcue" else None
|
||||
if slot is not None and 0 <= slot < caps.HOTCUE_SLOTS and slot not in taken:
|
||||
self._store.set_cue(track_id, slot=slot, **common)
|
||||
taken.add(slot)
|
||||
else:
|
||||
self._store.add_memory_cue(track_id, **common)
|
||||
|
||||
def remove_tracks(self, track_ids: list[str]) -> int:
|
||||
# Same shape as adding: a track is a djmdContent row plus its cues,
|
||||
# playlist rows, contentCue/contentFile mirrors and ANLZ files, and
|
||||
# which of those Rekordbox expects to be deleted together is unmeasured.
|
||||
self._refuse("Removing tracks")
|
||||
# What goes with a track was measured in Rekordbox 7 — see the store.
|
||||
self._require_writable("Removing tracks")
|
||||
n = self._store.remove_tracks(track_ids)
|
||||
if n:
|
||||
self._rebuild()
|
||||
return n
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
# Rekordbox does not play native-instruments stem files as stems.
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
"""Reading an ANLZ analysis file at the TAG level, by hand.
|
||||
|
||||
The writer half is `anlz_writer`; this is its reader. Like the writer it lives
|
||||
here because the format is Pioneer's, not one product's.
|
||||
|
||||
**Why not `pyrekordbox`'s parser.** It decodes a cue entry with a FIXED layout,
|
||||
and rekordbox does not write one. An exported entry is 88 bytes, but when
|
||||
rekordbox 7 EDITS a stick it writes compact ones (measured on Goober,
|
||||
2026-10-01): a hot cue added in rekordbox was a 48-byte `PCP2` (colour, no
|
||||
padding), and a memory cue a 44-byte one (no colour bytes at all). pyrekordbox
|
||||
raises `PaddingError` on the 44-byte form, the whole `.EXT` fails to parse, and
|
||||
a reader that falls back to the `.DAT` silently loses pads D-H and every colour.
|
||||
So every entry here is read at its own `len_entry`, and a field the entry is too
|
||||
short to hold is simply absent.
|
||||
|
||||
A file is also split into its RAW tags, kept byte for byte. Editing a stick
|
||||
replaces one or two tags of a file rekordbox wrote; everything else (the
|
||||
waveforms, `PVBR`, tags nobody has decoded) must go back exactly as it was, and
|
||||
re-serialising through a parser is how bytes get lost.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
#: `PMAI` · len_header · len_file · …
|
||||
FILE_MAGIC = b"PMAI"
|
||||
NO_LOOP = 0xFFFFFFFF
|
||||
|
||||
#: The cue-list kinds in `PCOB`/`PCO2`'s own header.
|
||||
LIST_MEMORY = 0
|
||||
LIST_HOT = 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class Tag:
|
||||
"""One tag, raw. `data` is the WHOLE tag: magic, both lengths, and body."""
|
||||
|
||||
type: str
|
||||
data: bytes
|
||||
_entries: list | None = field(default=None, repr=False, compare=False)
|
||||
|
||||
@property
|
||||
def len_header(self) -> int:
|
||||
return struct.unpack_from(">I", self.data, 4)[0]
|
||||
|
||||
@property
|
||||
def list_kind(self) -> int | None:
|
||||
"""`PCOB`/`PCO2`: whether this is the hot cue or the memory list."""
|
||||
if self.type in ("PCOB", "PCO2") and len(self.data) >= 16:
|
||||
return struct.unpack_from(">I", self.data, 12)[0]
|
||||
return None
|
||||
|
||||
@property
|
||||
def entries(self) -> list:
|
||||
"""The tag's decoded entries (cues, or beats for `PQTZ`); [] otherwise."""
|
||||
if self._entries is None:
|
||||
decode = _DECODERS.get(self.type)
|
||||
self._entries = decode(self.data) if decode else []
|
||||
return self._entries
|
||||
|
||||
|
||||
@dataclass
|
||||
class AnlzFile:
|
||||
"""An analysis file split into its header and raw tags."""
|
||||
|
||||
header: bytes
|
||||
tags: list[Tag]
|
||||
|
||||
def to_bytes(self) -> bytes:
|
||||
"""Reassemble, fixing only the header's file length."""
|
||||
body = b"".join(t.data for t in self.tags)
|
||||
head = bytearray(self.header)
|
||||
struct.pack_into(">I", head, 8, len(head) + len(body))
|
||||
return bytes(head) + body
|
||||
|
||||
def copy(self) -> "AnlzFile":
|
||||
return AnlzFile(self.header, [Tag(t.type, t.data) for t in self.tags])
|
||||
|
||||
def find(self, kind: str, list_kind: int | None = None) -> int | None:
|
||||
"""Index of the first `kind` tag (of that cue-list kind, if given)."""
|
||||
for i, t in enumerate(self.tags):
|
||||
if t.type == kind and (list_kind is None or t.list_kind == list_kind):
|
||||
return i
|
||||
return None
|
||||
|
||||
def put(self, kind: str, data: bytes, *, list_kind: int | None = None,
|
||||
after: tuple[str, ...] = ()) -> None:
|
||||
"""Replace the `kind` tag IN PLACE, keeping every other tag where it is.
|
||||
|
||||
A file without one gets it inserted after the last tag named in
|
||||
`after` (rekordbox's order), else at the end.
|
||||
"""
|
||||
tag = Tag(kind, data)
|
||||
i = self.find(kind, list_kind)
|
||||
if i is not None:
|
||||
self.tags[i] = tag
|
||||
return
|
||||
at = max((j for j, t in enumerate(self.tags) if t.type in after), default=len(self.tags) - 1)
|
||||
self.tags.insert(at + 1, tag)
|
||||
|
||||
|
||||
class AnlzError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def parse(data: bytes) -> AnlzFile:
|
||||
"""Split a file into its tags. Raises `AnlzError` on a malformed file.
|
||||
|
||||
Lengths are trusted only as far as the file reaches: a tag claiming more
|
||||
bytes than remain ends the walk with an error rather than a short read.
|
||||
"""
|
||||
if len(data) < 12 or data[:4] != FILE_MAGIC:
|
||||
raise AnlzError("not an ANLZ file")
|
||||
len_header = struct.unpack_from(">I", data, 4)[0]
|
||||
if not 12 <= len_header <= len(data):
|
||||
raise AnlzError(f"bad file header length {len_header}")
|
||||
tags: list[Tag] = []
|
||||
off = len_header
|
||||
while off < len(data):
|
||||
if off + 12 > len(data):
|
||||
raise AnlzError(f"truncated tag at {off}")
|
||||
kind = data[off:off + 4].decode("latin-1")
|
||||
len_tag = struct.unpack_from(">I", data, off + 8)[0]
|
||||
if len_tag < 12 or off + len_tag > len(data):
|
||||
raise AnlzError(f"bad length {len_tag} for {kind} at {off}")
|
||||
tags.append(Tag(kind, data[off:off + len_tag]))
|
||||
off += len_tag
|
||||
return AnlzFile(header=data[:len_header], tags=tags)
|
||||
|
||||
|
||||
def parse_file(path) -> AnlzFile:
|
||||
with open(path, "rb") as f:
|
||||
return parse(f.read())
|
||||
|
||||
|
||||
# ---- cue entries ------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class CueEntry:
|
||||
"""One `PCPT` or `PCP2` entry. Attribute names follow pyrekordbox's, which
|
||||
is what `onelibrary.cues` was written against.
|
||||
|
||||
`color_code` / RGB are None when the entry is too short to carry them (every
|
||||
`PCPT`, and rekordbox's compact 44-byte `PCP2`).
|
||||
"""
|
||||
|
||||
hot_cue: int
|
||||
type: int
|
||||
time: int
|
||||
loop_time: int
|
||||
comment: str = ""
|
||||
loop_numerator: int = 0
|
||||
loop_denominator: int = 0
|
||||
color_code: int | None = None
|
||||
color_red: int | None = None
|
||||
color_green: int | None = None
|
||||
color_blue: int | None = None
|
||||
len_entry: int = 0
|
||||
|
||||
|
||||
def raw_entries(tag: Tag) -> list[bytes]:
|
||||
"""A `PCOB`/`PCO2` tag's entries as their own bytes, each at its own length —
|
||||
so an entry Konduktor does not change goes back exactly as rekordbox wrote it."""
|
||||
if tag.type == "PCOB":
|
||||
count, first, magic = struct.unpack_from(">H", tag.data, 18)[0], 24, b"PCPT"
|
||||
elif tag.type == "PCO2":
|
||||
count, first, magic = struct.unpack_from(">H", tag.data, 16)[0], 20, b"PCP2"
|
||||
else:
|
||||
return []
|
||||
return [tag.data[off:off + n] for off, n in _walk(tag.data, first, magic, count)]
|
||||
|
||||
|
||||
def decode_entry(entry: bytes) -> CueEntry:
|
||||
"""One raw `PCPT` or `PCP2` entry, decoded."""
|
||||
if entry[:4] == b"PCPT":
|
||||
return _pcob(struct.pack(">4sIIIHHi", b"PCOB", 24, 24 + len(entry), 0, 0, 1, -1) + entry)[0]
|
||||
return _pco2(struct.pack(">4sIIIHH", b"PCO2", 20, 20 + len(entry), 0, 1, 0) + entry)[0]
|
||||
|
||||
|
||||
def entry_hot_cue(entry: bytes) -> int:
|
||||
"""A PCPT/PCP2 entry's `hot_cue`: its pad, 1-based; 0 for a memory cue."""
|
||||
return struct.unpack_from(">I", entry, 12)[0]
|
||||
|
||||
|
||||
def entry_with_colour(entry: bytes, code: int, rgb: tuple[int, int, int]) -> bytes | None:
|
||||
"""A `PCP2` entry with ONLY its colour bytes changed — what rekordbox itself
|
||||
does to recolour a cue (measured: those 4 bytes and nothing else). None if
|
||||
the entry is too short to carry a colour (rekordbox's 44-byte form)."""
|
||||
if len(entry) < 44:
|
||||
return None
|
||||
len_comment = struct.unpack_from(">I", entry, 40)[0]
|
||||
at = 44 + len_comment
|
||||
if at + 4 > len(entry):
|
||||
return None
|
||||
return entry[:at] + bytes([code & 0xFF, *rgb]) + entry[at + 4:]
|
||||
|
||||
|
||||
def entry_without_loop_beats(entry: bytes) -> bytes:
|
||||
"""A `PCP2` entry with its loop length in beats cleared to 0/0 — what
|
||||
rekordbox does to every loop when the grid changes (measured: 32/1 -> 0/0),
|
||||
rather than recomputing it."""
|
||||
if len(entry) < 40 or entry[36:40] == b"\0\0\0\0":
|
||||
return entry
|
||||
return entry[:36] + bytes(4) + entry[40:]
|
||||
|
||||
|
||||
def _walk(data: bytes, first: int, magic: bytes, count: int):
|
||||
"""(offset, len_entry) for each entry, trusting each entry's own length."""
|
||||
off = first
|
||||
for _ in range(count):
|
||||
if off + 12 > len(data) or data[off:off + 4] != magic:
|
||||
return
|
||||
len_entry = struct.unpack_from(">I", data, off + 8)[0]
|
||||
if len_entry < 12 or off + len_entry > len(data):
|
||||
return
|
||||
yield off, len_entry
|
||||
off += len_entry
|
||||
|
||||
|
||||
def _pcob(data: bytes) -> list[CueEntry]:
|
||||
# tag prefix(12) · I list kind · H 0 · H count · i last
|
||||
count = struct.unpack_from(">H", data, 18)[0]
|
||||
out = []
|
||||
for off, n in _walk(data, 24, b"PCPT", count):
|
||||
if n < 44:
|
||||
continue
|
||||
# 4s · I len_header · I len_entry · I hot_cue · I status · I 0x10000 ·
|
||||
# H order_first · H order_last · B kind · x · H 1000 · I time · I loop
|
||||
hot_cue, = struct.unpack_from(">I", data, off + 12)
|
||||
kind = data[off + 28]
|
||||
time, loop = struct.unpack_from(">II", data, off + 32)
|
||||
out.append(CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n))
|
||||
return out
|
||||
|
||||
|
||||
def _pco2(data: bytes) -> list[CueEntry]:
|
||||
# tag prefix(12) · I list kind · H count · H 0
|
||||
count = struct.unpack_from(">H", data, 16)[0]
|
||||
out = []
|
||||
for off, n in _walk(data, 20, b"PCP2", count):
|
||||
if n < 28:
|
||||
continue
|
||||
hot_cue, = struct.unpack_from(">I", data, off + 12)
|
||||
kind = data[off + 16]
|
||||
time, loop = struct.unpack_from(">II", data, off + 20)
|
||||
e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n)
|
||||
if n >= 44:
|
||||
e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36)
|
||||
colour_at = off + 44 + len_comment
|
||||
if len_comment and colour_at <= off + n:
|
||||
e.comment = data[off + 44:colour_at].decode("utf-16-be", "replace").rstrip("\x00")
|
||||
if colour_at + 4 <= off + n:
|
||||
e.color_code, e.color_red, e.color_green, e.color_blue = data[colour_at:colour_at + 4]
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
# ---- the beatgrid -----------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class Beat:
|
||||
beat: int # 1-4, position in the bar
|
||||
tempo: int # BPM x 100
|
||||
time: int # ms
|
||||
|
||||
|
||||
def _pqtz(data: bytes) -> list[Beat]:
|
||||
# tag prefix(12) · I 0 · I 0x80000 · I count, then 8-byte entries
|
||||
count = struct.unpack_from(">I", data, 20)[0]
|
||||
first = struct.unpack_from(">I", data, 4)[0]
|
||||
out = []
|
||||
for i in range(count):
|
||||
off = first + 8 * i
|
||||
if off + 8 > len(data):
|
||||
break
|
||||
beat, tempo, time = struct.unpack_from(">HHI", data, off)
|
||||
out.append(Beat(beat=beat, tempo=tempo, time=time))
|
||||
return out
|
||||
|
||||
|
||||
_DECODERS = {"PCOB": _pcob, "PCO2": _pco2, "PQTZ": _pqtz}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AnlzError", "AnlzFile", "Beat", "CueEntry", "LIST_HOT", "LIST_MEMORY",
|
||||
"NO_LOOP", "Tag", "decode_entry", "entry_hot_cue", "entry_with_colour", "entry_without_loop_beats",
|
||||
"parse", "parse_file", "raw_entries",
|
||||
]
|
||||
@@ -313,30 +313,38 @@ def flat_preview_tags() -> list[bytes]:
|
||||
return preview_tags([0.0] * 400, [0.0] * 400)
|
||||
|
||||
|
||||
def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
|
||||
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0) -> bytes:
|
||||
def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
|
||||
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0,
|
||||
comment: str | None = None) -> bytes:
|
||||
"""One `PCP2` entry, byte-for-byte as rekordbox 7 writes it.
|
||||
|
||||
Two constants in here are rekordbox's, not the documented struct's: the
|
||||
`1000` after the kind (the struct calls it padding) and the `1` after the
|
||||
colour id. Both appear in every entry of a real export; zeros there were a
|
||||
guess, and pyrekordbox's parser would never notice one.
|
||||
|
||||
A `comment` (the cue's name) is UTF-16BE with a terminating NUL, and
|
||||
`len_comment` counts the terminator — crate-digger's layout, which both
|
||||
Konduktor's reader and pyrekordbox's agree with. No reference cue carries
|
||||
one, so that detail is documented rather than measured. The entry stays the
|
||||
exported 88 bytes unless the name needs more.
|
||||
"""
|
||||
comment = b""
|
||||
comment_bytes = (comment.encode("utf-16-be") + b"\0\0") if comment else b""
|
||||
red, green, blue = rgb or (0, 0, 0)
|
||||
length = max(PCP2_ENTRY_LEN, 48 + len(comment_bytes))
|
||||
return struct.pack(
|
||||
">4sIIIBxHIIBB6xHHI",
|
||||
b"PCP2", 16, PCP2_ENTRY_LEN, hot_cue, kind, 1000,
|
||||
b"PCP2", 16, length, hot_cue, kind, 1000,
|
||||
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
|
||||
0, 1, beats or 0, 1 if beats else 0, len(comment),
|
||||
0, 1, beats or 0, 1 if beats else 0, len(comment_bytes),
|
||||
# The colour is the palette CODE, then RGB: rekordbox draws from the code
|
||||
# (`palette`); a code of 0 draws its default colour whatever the RGB says.
|
||||
) + comment + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
|
||||
PCP2_ENTRY_LEN - 48 - len(comment)
|
||||
) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
|
||||
length - 48 - len(comment_bytes)
|
||||
)
|
||||
|
||||
|
||||
def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
|
||||
def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
|
||||
"""One `PCPT` entry, byte-for-byte as rekordbox 7 writes it.
|
||||
|
||||
`len_header` is **28**, not 12: a reader that trusts it finds the body 16
|
||||
@@ -353,28 +361,54 @@ def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -
|
||||
) + bytes(16)
|
||||
|
||||
|
||||
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
|
||||
blob = b"".join(
|
||||
_pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"])
|
||||
for c in chosen
|
||||
)
|
||||
def pcob_tag(cue_type: int, entries: list[bytes]) -> bytes:
|
||||
"""A `PCOB` around already-built `PCPT` entries (rekordbox's own, untouched,
|
||||
or new ones from `pcpt_entry`)."""
|
||||
# cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong
|
||||
# shifts every following field and the reader sees garbage. The last field
|
||||
# is -1 on a hot-cue list and (count - 1) on a memory list, as rekordbox
|
||||
# writes it.
|
||||
last = -1 if cue_type == 1 else len(chosen) - 1
|
||||
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(chosen), last) + blob)
|
||||
# writes it (an export, and rekordbox's own edits, alike).
|
||||
last = -1 if cue_type == 1 else len(entries) - 1
|
||||
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(entries), last) + b"".join(entries))
|
||||
|
||||
|
||||
def pco2_tag(cue_type: int, entries: list[bytes]) -> bytes:
|
||||
"""A `PCO2` around already-built `PCP2` entries."""
|
||||
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(entries), 0) + b"".join(entries))
|
||||
|
||||
|
||||
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
|
||||
return pcob_tag(cue_type, [
|
||||
pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"])
|
||||
for c in chosen
|
||||
])
|
||||
|
||||
|
||||
def _pco2(cue_type: int, chosen: list[dict]) -> bytes:
|
||||
blob = b"".join(
|
||||
_pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
|
||||
code=c.get("code", 0))
|
||||
return pco2_tag(cue_type, [
|
||||
pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
|
||||
code=c.get("code", 0), comment=c.get("comment"))
|
||||
for c in chosen
|
||||
)
|
||||
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(chosen), 0) + blob)
|
||||
])
|
||||
|
||||
|
||||
#: `PQT2` as rekordbox 7 leaves it after a grid edit: header kept, every count
|
||||
#: and the beat list gone (56 bytes, the `len_header`). MEASURED on Goober
|
||||
#: (2026-10-01): rekordbox does not recompute this "extended" grid when the grid
|
||||
#: changes, it blanks it, and a CDJ then works from `PQTZ`.
|
||||
_PQT2_HEADER = 56
|
||||
|
||||
|
||||
def blank_pqt2(tag: bytes) -> bytes:
|
||||
"""The blanked form of an existing `PQT2` tag, exactly as rekordbox writes it.
|
||||
|
||||
Bytes 12-24 (rekordbox's constants, `00000000 01000002 00000000` on every
|
||||
file seen) are KEPT; the counts and first/last-beat fields after them are
|
||||
zeroed, and the beat entries dropped.
|
||||
"""
|
||||
return tag[:8] + struct.pack(">I", _PQT2_HEADER) + tag[12:24] + bytes(_PQT2_HEADER - 24)
|
||||
|
||||
|
||||
def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
|
||||
@@ -404,13 +438,18 @@ def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
|
||||
_FILE_HEADER_LEN = 28
|
||||
|
||||
|
||||
def write_anlz(path: Path, tags: list[bytes]) -> Path:
|
||||
"""Assemble and write an ANLZ file from built tag bytes."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
def anlz_bytes(tags: list[bytes]) -> bytes:
|
||||
"""Assemble an ANLZ file from built tag bytes."""
|
||||
body = b"".join(tags)
|
||||
header = struct.pack(
|
||||
">4sIIIIII", b"PMAI", _FILE_HEADER_LEN, _FILE_HEADER_LEN + len(body),
|
||||
FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3, 0,
|
||||
)
|
||||
path.write_bytes(header + body)
|
||||
return header + body
|
||||
|
||||
|
||||
def write_anlz(path: Path, tags: list[bytes]) -> Path:
|
||||
"""Assemble and write an ANLZ file from built tag bytes."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(anlz_bytes(tags))
|
||||
return path
|
||||
@@ -30,6 +30,7 @@ from ...core.capabilities import (
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from . import palette
|
||||
from .cue_types import WRITABLE_CUE_TYPES
|
||||
|
||||
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
|
||||
@@ -68,8 +69,10 @@ def capabilities_for(
|
||||
max_memory_cues=None, # unlimited
|
||||
# Both cue types write; Rekordbox has no fade/load types.
|
||||
types=WRITABLE_CUE_TYPES,
|
||||
# A hot cue's colour is one of rekordbox's 16 swatches (all
|
||||
# measured, see `palette`), offered in rekordbox's own order.
|
||||
color="palette",
|
||||
palette=[], # TODO milestone 2: the built-in cue colour table
|
||||
palette=[palette.hex_for(code) for code in palette.SWATCHES],
|
||||
named=True, # djmdCue.Comment
|
||||
loops="cue_type",
|
||||
),
|
||||
@@ -83,7 +86,12 @@ def capabilities_for(
|
||||
# column (its Composer is a different field), so they are absent
|
||||
# rather than mapped onto something approximate.
|
||||
editable_fields=sorted(editable_fields or []),
|
||||
media_kinds=["audio"],
|
||||
# A stem file is held (and played by Rekordbox as its mix);
|
||||
# Konduktor's deck plays its stems.
|
||||
media_kinds=["audio", "stem"],
|
||||
removable=True,
|
||||
addable=True,
|
||||
key_writable=True,
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
|
||||
@@ -198,8 +198,9 @@ class RekordboxDeviceExporter:
|
||||
|
||||
@staticmethod
|
||||
def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]:
|
||||
"""The tree under one folder named after the export, as the other
|
||||
targets build it. `sort_order` is a node's position among its siblings."""
|
||||
"""The tree as the other targets build it — at the top level (parent
|
||||
0), or with `payload.root_folder` under one folder named after the
|
||||
export. `sort_order` is a node's position among its siblings."""
|
||||
tree: list[bytes] = []
|
||||
entries: list[bytes] = []
|
||||
next_id = [0]
|
||||
@@ -220,7 +221,7 @@ class RekordboxDeviceExporter:
|
||||
index += 1
|
||||
entries.append(pdb.playlist_entry_row(index, track_id, playlist_id))
|
||||
|
||||
root = add(payload.name, 0, folder=True)
|
||||
root = add(payload.name, 0, folder=True) if payload.root_folder else 0
|
||||
folders: dict[tuple[str, ...], int] = {(): root}
|
||||
for playlist in payload.playlists:
|
||||
parent = root
|
||||
|
||||
@@ -63,7 +63,7 @@ class RekordboxDriver:
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> RekordboxAdapter:
|
||||
def open(self, path: Path, *, read_only: bool = False) -> RekordboxAdapter:
|
||||
return RekordboxAdapter(path)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
|
||||
@@ -58,8 +58,7 @@ from sqlalchemy import text
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from ...core.cue_colors import effective_color
|
||||
from . import anlz_writer as W
|
||||
from . import artwork, palette
|
||||
from . import new_content, palette
|
||||
from . import timebase
|
||||
from .beatgrid import beats_from_markers
|
||||
from .capabilities import capabilities_for
|
||||
@@ -82,15 +81,8 @@ SEED = _FIXTURES / "seed.sql"
|
||||
#: Rekordbox counts cue positions in frames at 150 fps, not milliseconds.
|
||||
FRAMES_PER_SECOND = 150
|
||||
|
||||
#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving
|
||||
#: five tracks of a Konduktor-written library different values and loading it
|
||||
#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?"
|
||||
#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here,
|
||||
#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's
|
||||
#: MP3/M4A tracks carry — adds two more bits that draw an extra badge, most
|
||||
#: likely claiming phrase/vocal analysis this exporter does not write. So the
|
||||
#: value that claims only what is written: 0x2C060E.
|
||||
CONTENT_LINK = 2885134
|
||||
#: `djmdContent.ContentLink` — see `new_content`, where its bits are measured.
|
||||
CONTENT_LINK = new_content.CONTENT_LINK
|
||||
|
||||
#: Rekordbox's playlist side file, beside master.db. It lists every playlist
|
||||
#: node with a `Timestamp` matching the row's `updated_at` (ms); a playlist the
|
||||
@@ -133,7 +125,7 @@ class RekordboxExporter:
|
||||
)
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
# `masterdb`'s OWN key blob. `devicelib_plus` has a different one — a
|
||||
# `masterdb`'s OWN key blob. `onelibrary` has a different one — a
|
||||
# OneLibrary drive uses a universal key shared across vendors, and
|
||||
# master.db does not. Mixing them up produces a database Rekordbox
|
||||
# cannot open, and pyrekordbox rejects the wrong one outright.
|
||||
@@ -319,27 +311,7 @@ class RekordboxExporter:
|
||||
|
||||
@staticmethod
|
||||
def _lookup(db, kind: str, name: str | None):
|
||||
"""Find-or-create a lookup row, returning its id.
|
||||
|
||||
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
|
||||
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
|
||||
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
|
||||
"""
|
||||
if not name:
|
||||
return None
|
||||
if kind == "key":
|
||||
found = db.get_key(ScaleName=name).first()
|
||||
if found is not None:
|
||||
return found.ID
|
||||
return _insert_key(db, name)
|
||||
found = {"artist": db.get_artist, "album": db.get_album,
|
||||
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
|
||||
if found is not None:
|
||||
return found.ID
|
||||
created = {"artist": db.add_artist, "album": db.add_album,
|
||||
"genre": db.add_genre, "label": db.add_label}[kind](name)
|
||||
db.flush()
|
||||
return created.ID
|
||||
return new_content.lookup(db, kind, name)
|
||||
|
||||
# ---- analysis ---------------------------------------------------------------
|
||||
|
||||
@@ -350,24 +322,15 @@ class RekordboxExporter:
|
||||
and the file on disk have to agree — so the same derivation is used here
|
||||
rather than a path of our own choosing.
|
||||
"""
|
||||
track_uuid = str(content.UUID)
|
||||
# Rekordbox derives these two levels from the track's UUID, and the
|
||||
# column and the file have to agree — so the same derivation is used.
|
||||
rel = f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
|
||||
rel = new_content.anlz_rel(str(content.UUID))
|
||||
content.AnalysisDataPath = rel
|
||||
content.Analysed = 105 # what a rekordbox-analysed track carries
|
||||
content.AnalysisUpdated = 1
|
||||
db.flush()
|
||||
|
||||
# The same three files as a rekordbox-analysed track. The `.DAT` needs
|
||||
# PVBR and the preview waveforms before rekordbox shows a grid at all
|
||||
# (measured on a OneLibrary stick; the same Pioneer file here); the
|
||||
# `.EXT`/`.2EX` carry the drawn waveforms. Cue lists are present but
|
||||
# EMPTY — master.db keeps cues in djmdCue.
|
||||
off = timebase.offset(item.destination)
|
||||
measured = item.waveform(lead=off)
|
||||
path = str(item.destination)
|
||||
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(item.destination))]
|
||||
beats = None
|
||||
markers = item.cues.grid_markers if item.cues else []
|
||||
if markers:
|
||||
duration = ((measured.duration if measured else 0.0)
|
||||
@@ -377,26 +340,18 @@ class RekordboxExporter:
|
||||
# Onto rekordbox's clock (~25 ms behind on MP3/AAC — `timebase`).
|
||||
# The cues need no such line: they are replayed through
|
||||
# `set_cue`, which applies the same offset itself.
|
||||
tags.append(W.beatgrid_tag(
|
||||
[(n, bpm, timebase.to_pioneer(t, off)) for n, bpm, t in zip(nums, bpms, times)]))
|
||||
if measured:
|
||||
tags += W.preview_tags(measured.columns.rms, measured.columns.brightness)
|
||||
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
|
||||
else:
|
||||
tags += W.flat_preview_tags()
|
||||
ext_waves, two_ex = [], []
|
||||
tags += W.cue_tags([], extended=False)
|
||||
beats = [(n, bpm, timebase.to_pioneer(t, off))
|
||||
for n, bpm, t in zip(nums, bpms, times)]
|
||||
# AnalysisDataPath is rooted at a `share` directory BESIDE master.db,
|
||||
# not at the library root — the read path joins it that way, and writing
|
||||
# it anywhere else produces a track whose grid silently reads as empty.
|
||||
dat = root / "share" / rel.lstrip("/")
|
||||
written = [
|
||||
W.write_anlz(dat, tags),
|
||||
W.write_anlz(dat.with_suffix(".EXT"), [W.path_tag(path), *ext_waves[:1],
|
||||
*W.cue_tags([], extended=True), *ext_waves[1:]]),
|
||||
]
|
||||
if two_ex:
|
||||
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(path), *two_ex]))
|
||||
written = []
|
||||
for suffix, data in new_content.anlz_files(item.destination, measured, beats).items():
|
||||
target = dat.with_suffix(suffix)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(data)
|
||||
written.append(target)
|
||||
return written
|
||||
|
||||
# ---- artwork ------------------------------------------------------------------
|
||||
@@ -412,17 +367,14 @@ class RekordboxExporter:
|
||||
rooted at `share/` like `AnalysisDataPath`. All measured on a real
|
||||
Rekordbox 7 library.
|
||||
"""
|
||||
if not item.art:
|
||||
files = new_content.artwork_files(item.art[0] if item.art else None)
|
||||
if files is None:
|
||||
return []
|
||||
jpegs = artwork.library_jpegs(item.art[0])
|
||||
if jpegs is None:
|
||||
return []
|
||||
track_uuid = str(content.UUID)
|
||||
rel = f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}"
|
||||
rel = new_content.artwork_rel(str(content.UUID))
|
||||
folder = root / "share" / rel.lstrip("/")
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
written = []
|
||||
for name, data in zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs):
|
||||
for name, data in files.items():
|
||||
(folder / name).write_bytes(data)
|
||||
written.append(folder / name)
|
||||
content.ImagePath = f"{rel}/artwork.jpg"
|
||||
@@ -431,9 +383,12 @@ class RekordboxExporter:
|
||||
# ---- playlists ---------------------------------------------------------------
|
||||
|
||||
def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None:
|
||||
"""The tree, under one folder named after the export."""
|
||||
root = db.create_playlist_folder(payload.name)
|
||||
db.flush()
|
||||
"""The tree — at the top level, or with `payload.root_folder` under one
|
||||
folder named after the export (None = the top level)."""
|
||||
root = None
|
||||
if payload.root_folder:
|
||||
root = db.create_playlist_folder(payload.name)
|
||||
db.flush()
|
||||
folders: dict[tuple[str, ...], object] = {(): root}
|
||||
|
||||
for playlist in payload.playlists:
|
||||
@@ -462,20 +417,3 @@ class RekordboxExporter:
|
||||
db.add_to_playlist(playlist, content)
|
||||
db.flush()
|
||||
|
||||
|
||||
def _insert_key(db, name: str) -> str:
|
||||
"""A `djmdKey` row. Raw SQL for the same reason the registry row is: the
|
||||
ORM's DateTime binder raises on the NULLs a real row carries."""
|
||||
from pyrekordbox.masterdb import models
|
||||
|
||||
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
|
||||
seq = (db.query(models.DjmdKey).count() or 0) + 1
|
||||
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
|
||||
db.session.execute(
|
||||
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
|
||||
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
|
||||
{"id": key_id, "name": name, "seq": seq,
|
||||
"uuid": str(uuidlib.uuid4()), "now": now},
|
||||
)
|
||||
db.flush()
|
||||
return key_id
|
||||
@@ -0,0 +1,138 @@
|
||||
"""A NEW track's rows and files in a `master.db` library.
|
||||
|
||||
Shared by the two places a track is created rather than edited: the Rekordbox
|
||||
Library exporter (a `master.db` from nothing) and `RekordboxStore.add_tracks`
|
||||
(a track added to the user's own library). One definition, because a track
|
||||
row, its lookups and its analysis files are the same thing in both, and two
|
||||
copies would drift.
|
||||
|
||||
What a track Rekordbox itself adds looks like was MEASURED (two files dragged
|
||||
into Rekordbox 7.2's collection, 2026-10-01, every row and file diffed): a
|
||||
`djmdContent` row, three ANLZ files plus a `.3EX`, the embedded cover as three
|
||||
JPEGs, one `contentFile` row per file (its `Hash` the file's MD5), and its own
|
||||
analysis results — key, mixer gain, phrases — which nothing here can produce.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid as uuidlib
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from . import anlz_writer as W
|
||||
from . import artwork
|
||||
|
||||
#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving
|
||||
#: five tracks of a Konduktor-written library different values and loading it
|
||||
#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?"
|
||||
#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here,
|
||||
#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's
|
||||
#: MP3/M4A tracks carry, and what Rekordbox writes for a track it analyses
|
||||
#: itself — adds two more bits that draw an extra badge, most likely claiming
|
||||
#: phrase/vocal analysis Konduktor does not write. So the value that claims
|
||||
#: only what is written: 0x2C060E.
|
||||
CONTENT_LINK = 2885134
|
||||
|
||||
|
||||
def anlz_rel(track_uuid: str) -> str:
|
||||
"""`djmdContent.AnalysisDataPath` for a track. Rekordbox derives it from
|
||||
the track's UUID, and the column and the file have to agree."""
|
||||
return f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
|
||||
|
||||
|
||||
def artwork_rel(track_uuid: str) -> str:
|
||||
"""The track's artwork FOLDER — the same UUID split as its analysis."""
|
||||
return f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}"
|
||||
|
||||
|
||||
def anlz_files(audio: Path, measured, beats: list | None) -> dict[str, bytes]:
|
||||
"""The analysis files for a track, by suffix: `.DAT`, `.EXT`, `.2EX`.
|
||||
|
||||
The same files as a rekordbox-analysed track. The `.DAT` needs PVBR and the
|
||||
preview waveforms before rekordbox shows a grid at all (measured on a
|
||||
OneLibrary stick; the same Pioneer file here); the `.EXT`/`.2EX` carry the
|
||||
drawn waveforms. Cue lists are present but EMPTY — master.db keeps cues in
|
||||
djmdCue. `measured` is `waveform.analyse`'s result (None: flat previews).
|
||||
`beats` is `(beat-in-bar, bpm, seconds)` ON REKORDBOX'S CLOCK; None writes
|
||||
no `PQTZ`, and `[]` an empty one for `write_pqtz` to fill later.
|
||||
"""
|
||||
path = str(audio)
|
||||
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(audio))]
|
||||
if beats is not None:
|
||||
tags.append(W.beatgrid_tag(beats))
|
||||
if measured:
|
||||
tags += W.preview_tags(measured.columns.rms, measured.columns.brightness)
|
||||
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
|
||||
else:
|
||||
tags += W.flat_preview_tags()
|
||||
ext_waves, two_ex = [], []
|
||||
tags += W.cue_tags([], extended=False)
|
||||
out = {
|
||||
".DAT": W.anlz_bytes(tags),
|
||||
".EXT": W.anlz_bytes([W.path_tag(path), *ext_waves[:1],
|
||||
*W.cue_tags([], extended=True), *ext_waves[1:]]),
|
||||
}
|
||||
if two_ex:
|
||||
out[".2EX"] = W.anlz_bytes([W.path_tag(path), *two_ex])
|
||||
return out
|
||||
|
||||
|
||||
def artwork_files(art: bytes | None) -> dict[str, bytes] | None:
|
||||
"""The cover as a rekordbox-managed track carries it, by file name.
|
||||
|
||||
`artwork.jpg` (the cover, fit to 800 px), `artwork_m.jpg` (240) and
|
||||
`artwork_s.jpg` (80), the last two letterboxed square; `djmdContent.
|
||||
ImagePath` names `artwork.jpg`. All measured on a real Rekordbox 7 library.
|
||||
None when there is no art or it cannot be read.
|
||||
"""
|
||||
if not art:
|
||||
return None
|
||||
jpegs = artwork.library_jpegs(art)
|
||||
if jpegs is None:
|
||||
return None
|
||||
return dict(zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs))
|
||||
|
||||
|
||||
def lookup(db, kind: str, name: str | None):
|
||||
"""Find-or-create a lookup row, returning its id.
|
||||
|
||||
Lookups are foreign keys; pyrekordbox's `add_*` RAISES on an existing name,
|
||||
so every one is find-or-create — the same rule the in-place adapter follows.
|
||||
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
|
||||
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
|
||||
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
|
||||
"""
|
||||
if not name:
|
||||
return None
|
||||
if kind == "key":
|
||||
found = db.get_key(ScaleName=name).first()
|
||||
if found is not None:
|
||||
return found.ID
|
||||
return insert_key(db, name)
|
||||
found = {"artist": db.get_artist, "album": db.get_album,
|
||||
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
|
||||
if found is not None:
|
||||
return found.ID
|
||||
created = {"artist": db.add_artist, "album": db.add_album,
|
||||
"genre": db.add_genre, "label": db.add_label}[kind](name)
|
||||
db.flush()
|
||||
return created.ID
|
||||
|
||||
|
||||
def insert_key(db, name: str) -> str:
|
||||
"""A `djmdKey` row. Raw SQL: the ORM's DateTime binder raises on the NULLs
|
||||
a real row carries."""
|
||||
from pyrekordbox.masterdb import models
|
||||
|
||||
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
|
||||
seq = (db.query(models.DjmdKey).count() or 0) + 1
|
||||
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
|
||||
db.session.execute(
|
||||
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
|
||||
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
|
||||
{"id": key_id, "name": name, "seq": seq,
|
||||
"uuid": str(uuidlib.uuid4()), "now": now},
|
||||
)
|
||||
db.flush()
|
||||
return key_id
|
||||
@@ -9,8 +9,9 @@ The table was MEASURED, not recalled: 16 hot cues coloured through rekordbox 7's
|
||||
own palette, one colour per pad, exported to a stick, and read back. Rekordbox
|
||||
writes the palette's exact RGB beside each code.
|
||||
|
||||
* One palette colour went unmeasured — the teal-green between 0x0E and 0x16
|
||||
(probably code 0x12); a cue that should be it maps to its nearest neighbour.
|
||||
* The teal-green between 0x0E and 0x16 was missed by that measurement, and
|
||||
found later: it is **0x13 = #00FF30**, which rekordbox 7 wrote itself as the
|
||||
DEFAULT colour of a hot cue added on a stick (Goober, 2026-10-01).
|
||||
* 0x2B (#FF0017) was observed on a real export though it is not one of the 16
|
||||
swatches; it is kept so such a colour survives a round trip exactly.
|
||||
* **The palette has no white or grey.** A colourless (white/grey) cue — above
|
||||
@@ -32,6 +33,7 @@ PALETTE: dict[int, tuple[int, int, int]] = {
|
||||
0x05: (0x00, 0x70, 0xFF), # light blue
|
||||
0x09: (0x00, 0xE0, 0xFF), # cyan
|
||||
0x0E: (0x00, 0xFF, 0xA3), # teal
|
||||
0x13: (0x00, 0xFF, 0x30), # teal-green (rekordbox's default for a new hot cue)
|
||||
0x16: (0x1A, 0xFF, 0x00), # green
|
||||
0x1A: (0x80, 0xFF, 0x00), # lime
|
||||
0x1E: (0xE6, 0xFF, 0x00), # yellow-lime
|
||||
@@ -91,3 +93,27 @@ def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]:
|
||||
return min(d, 1 - d)
|
||||
best = min((c for c in PALETTE if c != 0x2B), key=hue_gap)
|
||||
return best, PALETTE[best]
|
||||
|
||||
|
||||
#: The swatches a user can pick, in rekordbox's own order — what
|
||||
#: `capabilities.cues.palette` offers: all 16. 0x2B is not a swatch at all (see
|
||||
#: the module note).
|
||||
SWATCHES: list[int] = [code for code in PALETTE if code != 0x2B]
|
||||
|
||||
|
||||
def hex_for(code: int | None) -> str | None:
|
||||
"""`#RRGGBB` for a stored palette code; None for uncoloured or unknown.
|
||||
|
||||
An unknown code projects as no colour rather than a guessed one; it is
|
||||
still kept on the row, since editing a cue's position, type or name never
|
||||
rewrites its colour.
|
||||
"""
|
||||
rgb = PALETTE.get(code) if code else None
|
||||
return None if rgb is None else f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
|
||||
|
||||
|
||||
def swatch_code(color: str) -> int | None:
|
||||
"""The code of an EXACT palette colour, else None — for a user's pick, which
|
||||
must be a swatch, unlike `code_for`'s nearest-hue mapping for exports."""
|
||||
rgb = _parse(color)
|
||||
return next((code for code, value in PALETTE.items() if value == rgb), None)
|
||||
@@ -430,3 +430,166 @@ __all__ = [
|
||||
"album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row",
|
||||
"playlist_tree_row", "read", "read_dsql", "template", "track_row",
|
||||
]
|
||||
|
||||
|
||||
# ---- editing an existing library -----------------------------------------------
|
||||
#
|
||||
# Editing a stick rekordbox wrote, rather than writing one from the template:
|
||||
# only the tables whose rows change are rewritten, and inside them a row that
|
||||
# does not change keeps rekordbox's own bytes. Every other table — history,
|
||||
# colours, menus, artwork — stays byte-identical, and so does exportExt.pdb.
|
||||
|
||||
|
||||
def _chain(buf: bytes, first: int, last: int) -> list[int]:
|
||||
"""A table's page chain, header page first."""
|
||||
pages, p = [first], first
|
||||
while p != last and len(pages) < 100000:
|
||||
p = struct.unpack_from("<I", buf, p * PAGE + 12)[0]
|
||||
pages.append(p)
|
||||
return pages
|
||||
|
||||
|
||||
def table_rows(buf: bytes, table: int) -> list[bytes]:
|
||||
"""Every present row of `table`, in page order, as its own bytes (padding
|
||||
included) — a row's extent is up to the next row's heap offset, or the end
|
||||
of the page's used heap."""
|
||||
n_tables = struct.unpack_from("<I", buf, 8)[0]
|
||||
for i in range(n_tables):
|
||||
t, _empty, first, last = struct.unpack_from("<4I", buf, 28 + 16 * i)
|
||||
if t != table:
|
||||
continue
|
||||
out = []
|
||||
for p in _chain(buf, first, last)[1:]:
|
||||
o = p * PAGE
|
||||
if buf[o + 0x1B] & _HEADER_PAGE:
|
||||
continue
|
||||
n = (buf[o + 0x19] >> 5) | (buf[o + 0x1A] << 3)
|
||||
used = struct.unpack_from("<H", buf, o + 0x1E)[0]
|
||||
offs, present = [], []
|
||||
# As `_rows` reads them: every bit of every group, since a page
|
||||
# rekordbox has edited holds more row slots than its small count.
|
||||
for g in range((n + 15) // 16):
|
||||
base = o + PAGE - g * _GROUP
|
||||
mask = struct.unpack_from("<H", buf, base - 4)[0]
|
||||
for r in range(16):
|
||||
if mask & (1 << r):
|
||||
offs.append(struct.unpack_from("<H", buf, base - 6 - 2 * r)[0])
|
||||
present.append(True)
|
||||
ends = sorted(set(offs)) + [used]
|
||||
for off, ok in zip(offs, present):
|
||||
if ok:
|
||||
end = next(e for e in ends if e > off)
|
||||
row = bytes(buf[o + _HEADER + off:o + _HEADER + end])
|
||||
if table == TRACKS:
|
||||
row = row[:track_extent(row)]
|
||||
out.append(row)
|
||||
return out
|
||||
return []
|
||||
|
||||
|
||||
def _dsql_len(buf: bytes, off: int) -> int:
|
||||
head = buf[off]
|
||||
return (head >> 1) if head & 1 else struct.unpack_from("<H", buf, off + 1)[0]
|
||||
|
||||
|
||||
def track_extent(row: bytes) -> int:
|
||||
"""Where a track row really ends: past its last string, 4-aligned.
|
||||
|
||||
NOT the next row's offset: rekordbox reuses its heap, and the bytes between
|
||||
a row and the next can be a stale tail of an older, longer string (seen on
|
||||
Goober: `...mp3` followed by `ing.stem.m4a`)."""
|
||||
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", row, _TRACK_FIXED)
|
||||
end = max(o + _dsql_len(row, o) for o in offs)
|
||||
return end + (-end % 4)
|
||||
|
||||
|
||||
def track_fields(row: bytes) -> tuple[dict, dict]:
|
||||
"""A raw track row as (`fields`, `strings`) — what `track_row` takes back."""
|
||||
fields = dict(zip([n for n, _ in _TRACK_FIELDS], struct.unpack_from(_TRACK_FMT, row, 0)))
|
||||
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", row, _TRACK_FIXED)
|
||||
return fields, {name: read_dsql(row, o) for name, o in zip(TRACK_STRINGS, offs)}
|
||||
|
||||
|
||||
def row_id(table: int, row: bytes) -> int | tuple:
|
||||
"""A row's identity within its table (the triple, for playlist entries)."""
|
||||
if table == TRACKS:
|
||||
return track_fields(row)[0]["id"]
|
||||
if table == ARTISTS:
|
||||
return struct.unpack_from("<I", row, 4)[0]
|
||||
if table == ALBUMS:
|
||||
return struct.unpack_from("<I", row, 12)[0]
|
||||
if table == PLAYLIST_TREE:
|
||||
return struct.unpack_from("<I", row, 12)[0]
|
||||
if table == PLAYLIST_ENTRIES:
|
||||
return struct.unpack_from("<3I", row, 0)
|
||||
return struct.unpack_from("<I", row, 0)[0]
|
||||
|
||||
|
||||
class PdbEditor(PdbWriter):
|
||||
"""`PdbWriter` over an EXISTING library: `refill` replaces one table's rows.
|
||||
|
||||
The table keeps its pages — overwritten in place, more taken from the
|
||||
next-unused counter if needed, any left over unlinked and blanked (a blank
|
||||
reserved page inside the file is a state rekordbox's own template has) —
|
||||
and keeps its empty candidate. `render` leaves the header's
|
||||
pages-with-room field as it was: rekordbox did not touch it when it edited
|
||||
Goober, and it is the least understood field in the file.
|
||||
"""
|
||||
|
||||
def __init__(self, existing: bytes):
|
||||
super().__init__(existing)
|
||||
self._room_field = struct.unpack_from("<I", self.buf, 16)[0]
|
||||
self._blank: set[int] = set()
|
||||
|
||||
def refill(self, table: int, rows: list[bytes]) -> None:
|
||||
slot, candidate, first, last = self.tables[table]
|
||||
old = _chain(bytes(self.buf), first, last)[1:]
|
||||
if candidate in old:
|
||||
old.remove(candidate)
|
||||
chunks = _chunk(rows) if rows else []
|
||||
indices = old[:len(chunks)] + [self._alloc() for _ in chunks[len(old):]]
|
||||
for p in old[len(chunks):]:
|
||||
self._blank.add(p)
|
||||
shift_at = _INDEX_SHIFT_AT if table in (TRACKS, ARTISTS, ALBUMS) else None
|
||||
indexed = table in _INDEXED
|
||||
for i, chunk in enumerate(chunks):
|
||||
nxt = indices[i + 1] if i + 1 < len(indices) else candidate
|
||||
fill = None
|
||||
if indexed:
|
||||
fill = (len(chunk) + 1, 0) if i + 1 == len(chunks) else (_NONE, _NONE)
|
||||
self.sequence += 1
|
||||
self.pages[indices[i]] = _data_page(indices[i], table, nxt, chunk, self.sequence,
|
||||
shift_at=shift_at, fill=fill)
|
||||
self._reindex(first, indices, indexed=indexed)
|
||||
self.tables[table] = [slot, candidate, first, indices[-1] if indices else first]
|
||||
if not indices:
|
||||
# No rows: the header page points straight at the candidate again.
|
||||
struct.pack_into("<I", self.buf, first * PAGE + 12, candidate)
|
||||
|
||||
def _reindex(self, header_page: int, data_pages: list[int], *, indexed: bool) -> None:
|
||||
o = header_page * PAGE
|
||||
struct.pack_into("<I", self.buf, o + 12, data_pages[0] if data_pages else
|
||||
struct.unpack_from("<I", self.buf, o + 12)[0])
|
||||
if indexed:
|
||||
# Clear the old entries first: a table that shrank must not keep
|
||||
# listing pages it no longer has.
|
||||
count = struct.unpack_from("<H", self.buf, o + _HEADER + 16)[0]
|
||||
for k in range(max(count, len(data_pages))):
|
||||
struct.pack_into("<I", self.buf, o + _HEADER + 20 + 4 * k, 0x1FFFFFF8)
|
||||
if data_pages:
|
||||
pages_with_room = self.pages_with_room
|
||||
self._index(header_page, data_pages, indexed=indexed)
|
||||
self.pages_with_room = pages_with_room
|
||||
else:
|
||||
struct.pack_into("<I", self.buf, o + _HEADER + 4, 0x03FFFFFF)
|
||||
if indexed:
|
||||
struct.pack_into("<HH", self.buf, o + _HEADER + 16, 0, 0x1FFF)
|
||||
struct.pack_into("<HH", self.buf, o + 0x20, _NONE, _NONE)
|
||||
struct.pack_into("<H", self.buf, o + 0x26, 0)
|
||||
|
||||
def render(self) -> bytes:
|
||||
out = bytearray(super().render())
|
||||
struct.pack_into("<I", out, 16, self._room_field)
|
||||
for p in self._blank - set(self.pages):
|
||||
out[p * PAGE:(p + 1) * PAGE] = bytes(PAGE)
|
||||
return bytes(out)
|
||||
@@ -5,65 +5,32 @@ The only place a ``pyrekordbox`` ORM object becomes a generic `Track` /
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from ...core import musical_key
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid, timebase
|
||||
from . import beatgrid, palette, timebase
|
||||
from .cue_types import cue_type, role_and_slot
|
||||
|
||||
# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or
|
||||
# Open Key notation. Parsing that is platform knowledge and belongs here.
|
||||
_KEY_RE = re.compile(r"^([A-G])([#b]?)(m?)$", re.I)
|
||||
|
||||
# Camelot wheel position for each pitch class, per mode.
|
||||
_CAMELOT_MINOR = {
|
||||
"A": 8, "E": 9, "B": 10, "F#": 11, "Gb": 11, "C#": 12, "Db": 12,
|
||||
"G#": 1, "Ab": 1, "D#": 2, "Eb": 2, "A#": 3, "Bb": 3,
|
||||
"F": 4, "C": 5, "G": 6, "D": 7,
|
||||
}
|
||||
_CAMELOT_MAJOR = {
|
||||
"C": 8, "G": 9, "D": 10, "A": 11, "E": 12, "B": 1, "F#": 2, "Gb": 2,
|
||||
"C#": 3, "Db": 3, "G#": 4, "Ab": 4, "D#": 5, "Eb": 5, "A#": 6, "Bb": 6,
|
||||
"F": 7,
|
||||
}
|
||||
|
||||
|
||||
# Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also
|
||||
# holds whatever text a track's key TAG carried when it was imported, so a real
|
||||
# stick has "12A" beside "Abm". Parsing therefore accepts every notation.
|
||||
def parse_key(key: str | None) -> tuple[int | None, str | None]:
|
||||
"""(Camelot wheel position 1-12, mode) for a Rekordbox key name."""
|
||||
if not key:
|
||||
return None, None
|
||||
m = _KEY_RE.match(key.strip())
|
||||
if not m:
|
||||
return None, None
|
||||
letter, accidental, minor = m.group(1).upper(), m.group(2), m.group(3)
|
||||
pitch = letter + (accidental.replace("B", "b") if accidental else "")
|
||||
table = _CAMELOT_MINOR if minor else _CAMELOT_MAJOR
|
||||
n = table.get(pitch)
|
||||
return (n, "minor" if minor else "major") if n else (None, None)
|
||||
"""(Camelot wheel position 1-12, mode) for a key name in any notation."""
|
||||
return musical_key.parse(key)
|
||||
|
||||
|
||||
# The inverse, for EXPORT. A track arriving from Traktor carries `key` as
|
||||
# The inverse, for writing. A track arriving from Traktor carries `key` as
|
||||
# Traktor's own display string ("10m") and `key_wheel`/`key_mode` as the parsed
|
||||
# position — so writing the string verbatim into a Pioneer library would show
|
||||
# "10m" where the deck expects "Abm". Rendering from the wheel is the only
|
||||
# correct crossing. Shared with the OneLibrary exporter: same vendor, same
|
||||
# notation, and two tables would drift.
|
||||
_MINOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MINOR.items()))}
|
||||
_MAJOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MAJOR.items()))}
|
||||
|
||||
|
||||
# "10m" where the deck expects "Cm". Rendering from the wheel is the only
|
||||
# correct crossing. Shared by the adapter and both Pioneer exporters.
|
||||
def render_key(wheel: int | None, mode: str | None) -> str | None:
|
||||
"""A Pioneer-style key name ("Abm", "F") for a Camelot position + mode.
|
||||
"""A Pioneer key name ("Abm", "F") for a Camelot position + mode, spelt as
|
||||
rekordbox spells its own (flats; see `core/musical_key`).
|
||||
|
||||
Returns None when the position is unknown, which is honest: a made-up key is
|
||||
worse than a blank one, and Pioneer software shows blanks without complaint.
|
||||
"""
|
||||
if not wheel or not (1 <= wheel <= 12):
|
||||
return None
|
||||
if mode == "minor":
|
||||
name = _MINOR_NAMES.get(wheel)
|
||||
return f"{name}m" if name else None
|
||||
return _MAJOR_NAMES.get(wheel)
|
||||
return musical_key.render(wheel, mode, "musical")
|
||||
|
||||
|
||||
def _iso_date(value) -> str | None:
|
||||
@@ -97,10 +64,10 @@ def _name_of(related) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def to_track(row, cue_kinds=()) -> Track:
|
||||
def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
|
||||
"""Project one ``DjmdContent`` row.
|
||||
|
||||
`cue_kinds` is this track's ``(Kind, OutMsec)`` pairs from the store's single
|
||||
`cue_kinds` is this track's ``(Kind, OutMsec, ColorTableIndex)`` from the store's single
|
||||
query — passed in rather than read off the row, which would be a per-track
|
||||
round trip. "Is this a hot cue, and on which pad?" is `role_and_slot`, the
|
||||
same definition `to_track_cues` uses, so the table's count and dots agree
|
||||
@@ -118,12 +85,11 @@ def to_track(row, cue_kinds=()) -> Track:
|
||||
BPM are precisely the 22 with no grid.
|
||||
"""
|
||||
chips: list[HotcueChip] = []
|
||||
for kind, out_msec in cue_kinds:
|
||||
for kind, out_msec, color_code in cue_kinds:
|
||||
role, slot = role_and_slot(kind)
|
||||
if role == "hotcue" and slot is not None:
|
||||
# Rekordbox's colour is a palette index nobody has decoded yet (see
|
||||
# `_cue_color`), so no colour is claimed and the UI uses the type's.
|
||||
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec), color=None))
|
||||
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec),
|
||||
color=palette.hex_for(color_code)))
|
||||
chips.sort(key=lambda chip: chip.slot)
|
||||
key_name = _name_of(getattr(row, "Key", None))
|
||||
wheel, mode = parse_key(key_name)
|
||||
@@ -157,7 +123,10 @@ def to_track(row, cue_kinds=()) -> Track:
|
||||
hotcues=chips,
|
||||
grid_marker_count=1 if (_bpm(row) and getattr(row, "AnalysisDataPath", None)) else 0,
|
||||
grid_locked=False, # Rekordbox has no per-track grid lock
|
||||
media_kind="audio",
|
||||
# What the FILE is (`store.is_stem`): Rekordbox itself plays a stem
|
||||
# file's mix, but Konduktor's deck plays its stems, and the Type column
|
||||
# must not disagree with the deck.
|
||||
media_kind="stem" if stem else "audio",
|
||||
)
|
||||
|
||||
|
||||
@@ -210,11 +179,6 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
|
||||
|
||||
|
||||
def _cue_color(row) -> str | None:
|
||||
"""Rekordbox stores a PALETTE INDEX, not an RGB value.
|
||||
|
||||
The generic model carries ``#RRGGBB``, and the built-in palette that index
|
||||
refers to is not yet known, so no colour is claimed rather than a wrong one
|
||||
being invented. `capabilities.cues.color` already says "palette", so the UI
|
||||
knows not to offer a free colour picker.
|
||||
"""
|
||||
return None
|
||||
"""Rekordbox stores a PALETTE CODE (`ColorTableIndex`), not an RGB value;
|
||||
`Color` is -1 on a coloured cue. A loop's uncoloured convention is code 0."""
|
||||
return palette.hex_for(getattr(row, "ColorTableIndex", None))
|
||||
@@ -37,15 +37,52 @@ from sqlalchemy import func, select, text
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome
|
||||
from ...core.adapter import (
|
||||
InvalidCommand,
|
||||
LibraryNotSupported,
|
||||
NotFound,
|
||||
SaveOutcome,
|
||||
Unsupported,
|
||||
)
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.pathmap import PathMapping
|
||||
from ...core.grid_edit import ReplaceGridCommands
|
||||
from ...core.pathmap import PathMapping, stored_form
|
||||
from . import timebase
|
||||
from .cue_types import beat_loop_size, kind_for, role_and_slot
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _file_facts(audio: Path) -> dict:
|
||||
"""What Rekordbox reads off the file itself for a new track's row."""
|
||||
from datetime import date
|
||||
|
||||
out: dict = {}
|
||||
try:
|
||||
st = audio.stat()
|
||||
born = getattr(st, "st_birthtime", None) or st.st_mtime
|
||||
out["created"] = date.fromtimestamp(born)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
import mutagen
|
||||
|
||||
info = mutagen.File(str(audio)).info
|
||||
out["length"] = int(round(info.length)) if info.length else None
|
||||
if getattr(info, "bitrate", None):
|
||||
out["bitrate"] = int(round(info.bitrate / 1000)) # kbps, as Rekordbox stores it
|
||||
if getattr(info, "sample_rate", None):
|
||||
out["sample_rate"] = int(info.sample_rate)
|
||||
if getattr(info, "bits_per_sample", None):
|
||||
out["bit_depth"] = int(info.bits_per_sample)
|
||||
except Exception: # noqa: BLE001 — facts are a nicety; the row stands without them
|
||||
log.debug("could not read %s", audio, exc_info=True)
|
||||
return out
|
||||
|
||||
# Where a track's analysis files live, as `contentFile.Path` spells it.
|
||||
_ANLZ_ROOT = "/PIONEER/USBANLZ/"
|
||||
|
||||
|
||||
@contextmanager
|
||||
def rekordbox_probe_suppressed():
|
||||
"""Stop `pyrekordbox.commit()` refusing because a Rekordbox process exists.
|
||||
@@ -74,17 +111,25 @@ def _iso_stamp(value) -> str:
|
||||
return str(value)
|
||||
|
||||
|
||||
class RekordboxStore:
|
||||
class RekordboxStore(ReplaceGridCommands):
|
||||
"""One open Rekordbox library."""
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = Path(path)
|
||||
self._mapping = PathMapping()
|
||||
# Write an added file in the library's STORED form (`pathmap.stored_form`).
|
||||
self._write_stored_paths = False
|
||||
self._grid_cache: dict[str, tuple[list[float], list[float], list[int]] | None] = {}
|
||||
self._journal = EditJournal()
|
||||
# Grid edits buffered until save(): ANLZ files are written to disk, so
|
||||
# applying them at command time would break the save contract.
|
||||
self._pending_grids: dict[str, tuple[list, list, list]] = {}
|
||||
# Analysis/artwork files of removed tracks, `share`-relative, deleted
|
||||
# by save() AFTER the commit — a failed commit must leave them in place.
|
||||
self._pending_file_removals: set[str] = set()
|
||||
# Files of ADDED tracks, `share`-relative path -> bytes, written by
|
||||
# save() BEFORE the commit (and removed again if it fails).
|
||||
self._pending_new_files: dict[str, bytes] = {}
|
||||
self._load()
|
||||
|
||||
# ---- open ------------------------------------------------------------
|
||||
@@ -98,6 +143,7 @@ class RekordboxStore:
|
||||
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
|
||||
raise LibraryNotSupported(f"Could not open Rekordbox library: {ex}") from ex
|
||||
self._grid_cache.clear()
|
||||
self._stem_cache: dict[str, bool] = {}
|
||||
self._content_cache: list | None = None
|
||||
self._by_id: dict[str, object] | None = None
|
||||
|
||||
@@ -117,6 +163,8 @@ class RekordboxStore:
|
||||
self.close()
|
||||
self._journal = EditJournal()
|
||||
self._pending_grids.clear()
|
||||
self._pending_file_removals.clear()
|
||||
self._pending_new_files.clear()
|
||||
self._load()
|
||||
|
||||
def close(self) -> None:
|
||||
@@ -210,8 +258,9 @@ class RekordboxStore:
|
||||
raise NotFound(f"No track {track_id!r}")
|
||||
return row
|
||||
|
||||
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None]]]:
|
||||
"""``{track_id: [(Kind, OutMsec), ...]}`` for every live cue, in one query.
|
||||
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None, int | None]]]:
|
||||
"""``{track_id: [(Kind, OutMsec, ColorTableIndex), ...]}`` for every live
|
||||
cue, in one query.
|
||||
|
||||
Just enough per cue for the library table's count and hotcue dots,
|
||||
without a per-track round trip. What a ``Kind`` means is decided in the
|
||||
@@ -220,12 +269,13 @@ class RekordboxStore:
|
||||
"""
|
||||
t = self._tables
|
||||
rows = self._db.session.execute(
|
||||
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec)
|
||||
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec,
|
||||
t.DjmdCue.ColorTableIndex)
|
||||
.where(t.DjmdCue.rb_local_deleted == 0)
|
||||
).all()
|
||||
out: dict[str, list[tuple[int | None, int | None]]] = {}
|
||||
for content_id, kind, out_msec in rows:
|
||||
out.setdefault(str(content_id), []).append((kind, out_msec))
|
||||
out: dict[str, list[tuple[int | None, int | None, int | None]]] = {}
|
||||
for content_id, kind, out_msec, color_code in rows:
|
||||
out.setdefault(str(content_id), []).append((kind, out_msec, color_code))
|
||||
return out
|
||||
|
||||
def cues(self, track_id: str) -> list:
|
||||
@@ -327,6 +377,28 @@ class RekordboxStore:
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._mapping = mapping or PathMapping()
|
||||
|
||||
def set_write_stored_paths(self, enabled: bool) -> None:
|
||||
self._write_stored_paths = bool(enabled)
|
||||
|
||||
def _stored(self, audio: Path) -> Path:
|
||||
if not self._write_stored_paths:
|
||||
return Path(audio)
|
||||
return stored_form(Path(audio), [self._mapping])
|
||||
|
||||
def is_stem(self, track_id: str) -> bool:
|
||||
"""Whether the track's FILE is a native-instruments stem file — read
|
||||
from its contents (only `.m4a`/`.mp4` are opened, ~0.7 ms each), and
|
||||
cached per path, since the projection asks for every track at open."""
|
||||
from ...core.stem_file import is_stem_file
|
||||
|
||||
path = self.audio_path(track_id)
|
||||
if path is None:
|
||||
return False
|
||||
key = str(path)
|
||||
if key not in self._stem_cache:
|
||||
self._stem_cache[key] = is_stem_file(path)
|
||||
return self._stem_cache[key]
|
||||
|
||||
@property
|
||||
def path_mapping(self) -> PathMapping:
|
||||
return self._mapping
|
||||
@@ -444,6 +516,46 @@ class RekordboxStore:
|
||||
self._db.flush()
|
||||
self._db.session.expire(row)
|
||||
|
||||
# ---- writes: musical key ---------------------------------------------
|
||||
def _key_id(self, wheel: int | None, mode: str | None) -> str | None:
|
||||
"""The `djmdKey` row for a key, found by what it MEANS, not its text.
|
||||
|
||||
A library's key table holds rekordbox's own names ("Abm") and whatever
|
||||
key tags imported ("12A"), so matching on a rendered name would add a
|
||||
second row for a key the library already has. Only a key it has never
|
||||
seen gets a row — created as rekordbox creates its own (measured on the
|
||||
local library, which rekordbox fills lazily as it analyses): named in
|
||||
its spelling, `Seq` NULL, and through the ORM so `commit()` stamps the
|
||||
row's `rb_local_usn` like any other change. (The exporters' raw insert
|
||||
would leave it unstamped.)"""
|
||||
from .projection import parse_key, render_key
|
||||
|
||||
if wheel is None or mode is None:
|
||||
return None
|
||||
for k in self._db.query(self._tables.DjmdKey).all():
|
||||
if parse_key(k.ScaleName) == (wheel, mode):
|
||||
return str(k.ID)
|
||||
row = self._tables.DjmdKey(
|
||||
ID=str(uuid.uuid4().int % 2_147_483_647),
|
||||
ScaleName=render_key(wheel, mode),
|
||||
UUID=str(uuid.uuid4()),
|
||||
)
|
||||
self._db.add(row)
|
||||
self._db.flush()
|
||||
return str(row.ID)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> None:
|
||||
if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"):
|
||||
raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}")
|
||||
row = self.content(track_id)
|
||||
before = row.KeyID
|
||||
row.KeyID = self._key_id(wheel, mode)
|
||||
self._journal.record("track", "set", track_id, "key", before, row.KeyID)
|
||||
# A foreign key, like artist: flush + expire, or the re-projection
|
||||
# reads the old key back through the cached relationship.
|
||||
self._db.flush()
|
||||
self._db.session.expire(row)
|
||||
|
||||
# ---- writes: playlists ------------------------------------------------
|
||||
def _playlist(self, node_id: str):
|
||||
t = self._tables
|
||||
@@ -496,6 +608,79 @@ class RekordboxStore:
|
||||
self._db.delete_playlist(row)
|
||||
self._journal.record("playlist", "delete", name)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
"""Move a node to `index` among `parent_id`'s visible children.
|
||||
|
||||
Not pyrekordbox's `move_playlist`: its `parent=None` means "keep the
|
||||
parent", so nothing can be moved to the top level with it. The same
|
||||
writes are made here — `ParentID`, the moved row's `updated_at`, and
|
||||
`Seq` renumbered from 1 in both parents (only rows whose `Seq` changes
|
||||
are touched) — plus `masterPlaylists6.xml`'s `ParentId`, which
|
||||
pyrekordbox's version leaves stale. Rekordbox's hidden working lists
|
||||
share the table and the numbering, so `index` is placed relative to
|
||||
the VISIBLE siblings and the hidden ones keep their order around it."""
|
||||
import datetime
|
||||
|
||||
from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS
|
||||
|
||||
t = self._tables
|
||||
row = self._playlist(node_id)
|
||||
dest = self._playlist(parent_id) if parent_id else None
|
||||
if dest is not None and int(dest.Attribute or 0) != int(t.PlaylistType.FOLDER):
|
||||
raise InvalidCommand("A playlist can only be moved into a folder")
|
||||
ancestor = dest
|
||||
while ancestor is not None:
|
||||
if str(ancestor.ID) == str(row.ID):
|
||||
raise InvalidCommand("A folder cannot be moved into itself")
|
||||
up = str(ancestor.ParentID or "root")
|
||||
ancestor = None if up in ("root", "0", "") else self._playlist(up)
|
||||
|
||||
def children(key: str) -> list:
|
||||
return (
|
||||
self._db.session.query(t.DjmdPlaylist)
|
||||
.filter(t.DjmdPlaylist.ParentID == key)
|
||||
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
|
||||
.order_by(t.DjmdPlaylist.Seq)
|
||||
.all()
|
||||
)
|
||||
|
||||
old_key = str(row.ParentID or "root")
|
||||
new_key = str(dest.ID) if dest is not None else "root"
|
||||
siblings = [c for c in children(new_key) if str(c.ID) != str(row.ID)]
|
||||
visible = [c for c in siblings if str(c.ID) not in SPECIAL_PLAYLIST_IDS]
|
||||
index = max(0, min(int(index), len(visible)))
|
||||
if index < len(visible):
|
||||
at = siblings.index(visible[index])
|
||||
else:
|
||||
at = siblings.index(visible[-1]) + 1 if visible else len(siblings)
|
||||
order = siblings[:at] + [row] + siblings[at:]
|
||||
if old_key == new_key and [str(c.ID) for c in order] == [
|
||||
str(c.ID) for c in children(new_key)
|
||||
]:
|
||||
return str(row.ID)
|
||||
|
||||
row.ParentID = new_key
|
||||
with self._db.registry.disabled():
|
||||
row.updated_at = datetime.datetime.now()
|
||||
for n, c in enumerate(order, start=1):
|
||||
if c.Seq != n:
|
||||
c.Seq = n
|
||||
if old_key != new_key:
|
||||
for n, c in enumerate(
|
||||
(c for c in children(old_key) if str(c.ID) != str(row.ID)), start=1
|
||||
):
|
||||
if c.Seq != n:
|
||||
c.Seq = n
|
||||
xml = getattr(self._db, "playlist_xml", None)
|
||||
if xml is not None:
|
||||
try:
|
||||
xml.update(row.ID, parent_id=new_key)
|
||||
except ValueError:
|
||||
pass # a playlist the XML never listed: nothing to keep in step
|
||||
self._db.flush()
|
||||
self._journal.record("playlist", "move", row.Name)
|
||||
return str(row.ID)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents, in the given order.
|
||||
|
||||
@@ -517,13 +702,278 @@ class RekordboxStore:
|
||||
.filter(t.DjmdSongPlaylist.PlaylistID == str(node_id))
|
||||
.all()
|
||||
)
|
||||
# NOT `remove_from_playlist`: it commits, which wrote an unsaved edit
|
||||
# to disk (beyond Discard's reach) and raised while Rekordbox ran.
|
||||
# The list is rebuilt from 1 below, so no renumbering is needed.
|
||||
for song in existing:
|
||||
self._db.remove_from_playlist(playlist, song)
|
||||
self._db.delete(song)
|
||||
self._db.flush()
|
||||
for n, track_id in enumerate(track_ids, start=1):
|
||||
self._db.add_to_playlist(playlist, str(track_id), track_no=n)
|
||||
self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids))
|
||||
return len(track_ids)
|
||||
|
||||
# ---- writes: adding tracks ---------------------------------------------
|
||||
#
|
||||
# MEASURED, by dragging two files into Rekordbox 7.2's collection and
|
||||
# diffing (2026-10-01): see `new_content`. Rekordbox fills the row from the
|
||||
# FILE (size, sample rate, bit rate, and `DateCreated` from the file's
|
||||
# creation date), stamps it with this library's device, and lists every
|
||||
# file it writes for the track in `contentFile` with the file's MD5.
|
||||
def add_track(self, audio: Path, track, *, measured, with_grid: bool,
|
||||
art: bytes | None) -> str:
|
||||
"""Add one track's row, return its id. Its analysis files and artwork
|
||||
are held until save(); its grid and cues are the caller's to replay
|
||||
through the ordinary commands. `with_grid` reserves an empty `PQTZ`
|
||||
in the `.DAT` for `replace_grid` to fill."""
|
||||
from . import new_content
|
||||
|
||||
audio = Path(audio)
|
||||
if not audio.is_file():
|
||||
raise InvalidCommand(f"No audio file at {audio}")
|
||||
t = self._tables
|
||||
stored = self._stored(audio)
|
||||
for form in {str(audio), str(stored)}:
|
||||
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=form).count():
|
||||
raise InvalidCommand(f"The library already holds {audio}")
|
||||
facts = _file_facts(audio)
|
||||
content = self._db.add_content(
|
||||
str(audio),
|
||||
Title=track.title or audio.stem,
|
||||
Length=facts.get("length") or track.length,
|
||||
BitRate=facts.get("bitrate") or (int(track.bitrate / 1000) if track.bitrate else None),
|
||||
SampleRate=facts.get("sample_rate"),
|
||||
BitDepth=facts.get("bit_depth", 16),
|
||||
Rating=track.rating or 0,
|
||||
Commnt=track.comment or "",
|
||||
ReleaseDate=track.release_date or "",
|
||||
)
|
||||
year = str(track.release_date or "")[:4]
|
||||
if year.isdigit():
|
||||
content.ReleaseYear = int(year)
|
||||
if facts.get("created"):
|
||||
content.DateCreated = facts["created"]
|
||||
content.ArtistID = new_content.lookup(self._db, "artist", track.artist)
|
||||
content.AlbumID = new_content.lookup(self._db, "album", track.album)
|
||||
content.GenreID = new_content.lookup(self._db, "genre", track.genre)
|
||||
content.LabelID = new_content.lookup(self._db, "label", track.label)
|
||||
# From the wheel, never the source's text: its notation is not
|
||||
# Rekordbox's ("10m" is "Cm" here), and a row it already has is reused.
|
||||
content.KeyID = self._key_id(track.key_wheel, track.key_mode)
|
||||
content.ContentLink = new_content.CONTENT_LINK
|
||||
if stored != audio:
|
||||
# pyrekordbox reads the file where it IS; the row names it as the
|
||||
# library stores every other path (the server's mapping, inverted).
|
||||
content.FolderPath = str(stored)
|
||||
|
||||
track_uuid = str(content.UUID)
|
||||
rel = new_content.anlz_rel(track_uuid)
|
||||
content.AnalysisDataPath = rel
|
||||
content.Analysed = 105 # what a rekordbox-analysed track carries
|
||||
content.AnalysisUpdated = 1
|
||||
files = new_content.anlz_files(audio, measured, [] if with_grid else None)
|
||||
for suffix, data in files.items():
|
||||
self._pending_new_files[str(Path(rel).with_suffix(suffix))] = data
|
||||
art_files = new_content.artwork_files(art)
|
||||
if art_files:
|
||||
folder = new_content.artwork_rel(track_uuid)
|
||||
for name, data in art_files.items():
|
||||
self._pending_new_files[f"{folder}/{name}"] = data
|
||||
content.ImagePath = f"{folder}/artwork.jpg"
|
||||
self._db.flush()
|
||||
|
||||
track_id = str(content.ID)
|
||||
if self._content_cache is not None and self._by_id is not None:
|
||||
self._content_cache.append(content)
|
||||
self._by_id[track_id] = content
|
||||
self._grid_cache.pop(track_id, None)
|
||||
self._journal.record("track", "add", track_id)
|
||||
return track_id
|
||||
|
||||
def _write_new_files(self) -> list[Path]:
|
||||
"""Write added tracks' files; return what was written."""
|
||||
share = self.path.parent / "share"
|
||||
written: list[Path] = []
|
||||
try:
|
||||
for rel, data in self._pending_new_files.items():
|
||||
path = share / rel.lstrip("/")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
written.append(path) # before the write: a partial file is cleaned too
|
||||
path.write_bytes(data)
|
||||
except BaseException:
|
||||
for path in written:
|
||||
path.unlink(missing_ok=True)
|
||||
raise
|
||||
return written
|
||||
|
||||
def _add_content_files(self, written: list[Path]) -> None:
|
||||
"""One `contentFile` row per file an added track carries, as Rekordbox
|
||||
writes them: `Hash` is the file's MD5, and its `_m`/`_s` artwork sizes
|
||||
are not listed."""
|
||||
import hashlib
|
||||
from urllib.parse import quote
|
||||
|
||||
t = self._tables
|
||||
share = self.path.parent / "share"
|
||||
by_folder = {}
|
||||
for row in self.iter_content():
|
||||
for rel in (row.AnalysisDataPath, row.ImagePath):
|
||||
if rel:
|
||||
by_folder[str(Path(rel).parent)] = row
|
||||
for path in written:
|
||||
if path.name in ("artwork_m.jpg", "artwork_s.jpg"):
|
||||
continue
|
||||
rel = "/" + path.relative_to(share).as_posix()
|
||||
row = by_folder.get(str(Path(rel).parent))
|
||||
if row is None:
|
||||
continue
|
||||
self._db.add(t.ContentFile(
|
||||
ID=f"{row.UUID}_{quote(rel, safe='')}",
|
||||
ContentID=str(row.ID),
|
||||
Path=rel,
|
||||
Hash=hashlib.md5(path.read_bytes()).hexdigest(),
|
||||
Size=path.stat().st_size,
|
||||
rb_local_path=str(path),
|
||||
UUID=str(uuid.uuid4()),
|
||||
created_at=datetime.now(),
|
||||
updated_at=datetime.now(),
|
||||
))
|
||||
self._db.flush()
|
||||
|
||||
# ---- writes: removing tracks -------------------------------------------
|
||||
#
|
||||
# MEASURED, by removing a track in Rekordbox 7.2 and diffing every row and
|
||||
# every file under `share/` (Demo Track 2, 2026-10-01): Rekordbox DELETES
|
||||
# the rows — it does not set `rb_local_deleted` — from these tables, leaves
|
||||
# the playlist row itself alone, and deletes the files `contentFile` lists
|
||||
# (there, the four ANLZ files) together with their emptied folders. That
|
||||
# track had no artwork, and an Artwork folder holds `_m`/`_s` sizes that
|
||||
# `contentFile` does not list, so artwork is left in place: an orphaned
|
||||
# image is harmless, a guessed deletion is not.
|
||||
_REMOVED_WITH_TRACK = ("DjmdCue", "ContentCue", "ContentFile", "DjmdMixerParam",
|
||||
"DjmdSongPlaylist")
|
||||
# Also keyed by ContentID, but empty in the measured library, so what
|
||||
# Rekordbox does with them is unknown. A track that appears in one is
|
||||
# refused rather than guessed at.
|
||||
_UNMEASURED_LINKS = {
|
||||
"djmdSongHistory": "a History list",
|
||||
"djmdSongSampler": "the Sampler",
|
||||
"djmdSongTagList": "the Tag List",
|
||||
"djmdSongMyTag": "My Tag",
|
||||
"djmdSongHotCueBanklist": "a Hot Cue Bank List",
|
||||
"djmdSongRelatedTracks": "Related Tracks",
|
||||
"djmdSongRequestList": "a request list",
|
||||
"djmdActiveCensor": "an Active Censor",
|
||||
"contentActiveCensor": "an Active Censor",
|
||||
"djmdCloudExportSongPlaylist": "a cloud export",
|
||||
}
|
||||
|
||||
def _unmeasured_links(self, ids: list[str]) -> list[tuple[str, str]]:
|
||||
"""``(track_id, where)`` for each track named by an unmeasured table."""
|
||||
params = {f"i{n}": tid for n, tid in enumerate(ids)}
|
||||
marks = ", ".join(f":{k}" for k in params)
|
||||
found: list[tuple[str, str]] = []
|
||||
for table, where in self._UNMEASURED_LINKS.items():
|
||||
try:
|
||||
rows = self._db.session.execute(
|
||||
text(f'SELECT DISTINCT ContentID FROM "{table}" '
|
||||
f"WHERE ContentID IN ({marks})"), params
|
||||
).all()
|
||||
except Exception: # noqa: BLE001 — table absent in this schema version
|
||||
continue
|
||||
found += [(str(r[0]), where) for r in rows]
|
||||
return found
|
||||
|
||||
def remove_tracks(self, track_ids: list[str]) -> int:
|
||||
"""Remove tracks from the library and every playlist; return how many.
|
||||
|
||||
Validated as a whole first, so a refused batch changes nothing. The
|
||||
audio files are never touched; the analysis files go at save().
|
||||
"""
|
||||
t = self._tables
|
||||
self.iter_content()
|
||||
assert self._by_id is not None
|
||||
ids = [str(tid) for tid in dict.fromkeys(track_ids) if str(tid) in self._by_id]
|
||||
if not ids:
|
||||
return 0
|
||||
blocked = self._unmeasured_links(ids)
|
||||
if blocked:
|
||||
tid, where = blocked[0]
|
||||
title = self._by_id[tid].Title or tid
|
||||
more = f" (and {len(blocked) - 1} more)" if len(blocked) > 1 else ""
|
||||
raise Unsupported(
|
||||
f"“{title}” is in {where} in Rekordbox{more}, and Konduktor does not "
|
||||
"yet know how Rekordbox removes a track from there. Remove it in "
|
||||
"Rekordbox instead — nothing was changed."
|
||||
)
|
||||
|
||||
playlists: set[str] = set()
|
||||
for tid in ids:
|
||||
for name in self._REMOVED_WITH_TRACK:
|
||||
table = getattr(t, name)
|
||||
for row in self._db.session.query(table).filter(table.ContentID == tid):
|
||||
if name == "ContentFile" and str(row.Path or "").startswith(_ANLZ_ROOT):
|
||||
self._pending_file_removals.add(str(row.Path))
|
||||
elif name == "DjmdSongPlaylist":
|
||||
playlists.add(str(row.PlaylistID))
|
||||
self._db.delete(row)
|
||||
self._db.delete(self._by_id[tid])
|
||||
self._pending_grids.pop(tid, None)
|
||||
self._grid_cache.pop(tid, None)
|
||||
self._journal.record("track", "remove", tid)
|
||||
self._db.flush()
|
||||
for playlist_id in playlists:
|
||||
self._renumber(playlist_id)
|
||||
self._content_cache = None
|
||||
self._by_id = None
|
||||
return len(ids)
|
||||
|
||||
def _renumber(self, playlist_id: str) -> None:
|
||||
"""Close the gaps removed entries left in a playlist's `TrackNo`s, as
|
||||
`pyrekordbox.remove_from_playlist` does — one 'move' for the registry,
|
||||
not an update per row."""
|
||||
t = self._tables
|
||||
moved = []
|
||||
now = datetime.now()
|
||||
rows = (
|
||||
self._db.session.query(t.DjmdSongPlaylist)
|
||||
.filter(t.DjmdSongPlaylist.PlaylistID == playlist_id)
|
||||
.order_by(t.DjmdSongPlaylist.TrackNo)
|
||||
)
|
||||
with self._db.registry.disabled():
|
||||
for n, row in enumerate(rows, start=1):
|
||||
if row.TrackNo != n:
|
||||
row.TrackNo = n
|
||||
row.updated_at = now
|
||||
moved.append(row)
|
||||
if moved:
|
||||
self._db.registry.on_move(moved)
|
||||
|
||||
def _delete_removed_files(self) -> None:
|
||||
"""Delete removed tracks' analysis/artwork files, then their emptied
|
||||
folders. Called after the commit; a file another track still lists is
|
||||
kept, and a failure only leaves an orphan behind, so it is logged."""
|
||||
t = self._tables
|
||||
share = (self.path.parent / "share").resolve()
|
||||
still_listed = {str(p) for (p,) in self._db.session.query(t.ContentFile.Path)}
|
||||
for rel in sorted(self._pending_file_removals - still_listed):
|
||||
parts = Path(rel.lstrip("/\\")).parts
|
||||
path = (share / Path(*parts)).resolve()
|
||||
# Folders below e.g. `PIONEER/USBANLZ` are the track's own; that
|
||||
# level and above are Rekordbox's and stay even when emptied.
|
||||
keep = (share / Path(*parts[:2])).resolve()
|
||||
if len(parts) < 3 or keep not in path.parents:
|
||||
continue
|
||||
try:
|
||||
path.unlink(missing_ok=True)
|
||||
folder = path.parent
|
||||
while folder != keep and not any(folder.iterdir()):
|
||||
folder.rmdir()
|
||||
folder = folder.parent
|
||||
except OSError as ex:
|
||||
log.warning("Could not delete %s: %s", path, ex)
|
||||
self._pending_file_removals.clear()
|
||||
|
||||
# ---- save --------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
@@ -546,9 +996,20 @@ class RekordboxStore:
|
||||
"""
|
||||
summary = self._journal.summary()
|
||||
# Files first: if an analysis file cannot be written, nothing should have
|
||||
# been committed to the database either.
|
||||
self._flush_grids()
|
||||
self._commit()
|
||||
# been committed to the database either. An added track's files go
|
||||
# before the grids, which write into them, and their `contentFile`
|
||||
# rows after, which hash what was finally written.
|
||||
written = self._write_new_files()
|
||||
try:
|
||||
self._flush_grids()
|
||||
self._add_content_files(written)
|
||||
self._commit()
|
||||
except BaseException:
|
||||
for path in written:
|
||||
path.unlink(missing_ok=True)
|
||||
raise
|
||||
self._pending_new_files.clear()
|
||||
self._delete_removed_files()
|
||||
self._journal.clear()
|
||||
# Reads go through the same session, so nothing needs re-projecting from
|
||||
# scratch — but the grid cache is keyed by track and survives a save.
|
||||
@@ -669,13 +1130,17 @@ class RekordboxStore:
|
||||
) -> None:
|
||||
"""Create or replace the cue in `slot`. A loop is a cue with a length.
|
||||
|
||||
`color_code` is a rekordbox palette code (`palette.PALETTE`); None or 0
|
||||
writes the uncoloured convention, which is what every edit through the
|
||||
adapter does — only the exporter passes a colour.
|
||||
`color_code` is a rekordbox palette code (`palette.PALETTE`). None KEEPS
|
||||
the colour of the cue already in the slot — the colour belongs to the
|
||||
pad, so a rename, a type change or an Auto Hotcues Replace leaves it as
|
||||
the user set it — and a new cue is uncoloured. Only `set_cue_color`
|
||||
clears one.
|
||||
"""
|
||||
if int(slot) < 0:
|
||||
raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}")
|
||||
existing = self._cue_row(track_id, slot)
|
||||
if color_code is None and existing is not None:
|
||||
color_code = existing.ColorTableIndex or None
|
||||
self._write_cue(
|
||||
track_id, existing, kind=kind_for("hotcue", slot), start_sec=start_sec,
|
||||
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
|
||||
@@ -748,26 +1213,44 @@ class RekordboxStore:
|
||||
cue.BeatLoopSize = beat_loop_size(beats) if beats else None
|
||||
cue.ActiveLoop = 0
|
||||
cue.CueMicrosec = 0
|
||||
cue.Color = 255
|
||||
cue.ColorTableIndex = 0
|
||||
else:
|
||||
cue.BeatLoopSize = None
|
||||
cue.ActiveLoop = None
|
||||
cue.CueMicrosec = None
|
||||
cue.Color = -1
|
||||
cue.ColorTableIndex = None
|
||||
if color_code:
|
||||
# A palette-coloured cue, as the real library stores one: the code in
|
||||
# ColorTableIndex (22 = green), Color -1. How rekordbox stores a
|
||||
# COLOURED LOOP is not in the reference library; the same column is
|
||||
# assumed and is what the smoke test checks.
|
||||
cue.ColorTableIndex = int(color_code)
|
||||
cue.Color = -1
|
||||
self._apply_color(cue, color_code, is_loop)
|
||||
cue.Comment = name or None
|
||||
|
||||
self._db.flush()
|
||||
self._sync_content_cue(track_id)
|
||||
|
||||
@staticmethod
|
||||
def _apply_color(cue, color_code: int | None, is_loop: bool) -> None:
|
||||
"""A row's two colour columns — the one definition of both conventions."""
|
||||
if color_code:
|
||||
# A palette-coloured cue, as the real library stores one: the code in
|
||||
# ColorTableIndex (22 = green), Color -1. Coloured loops store the
|
||||
# same; verified in Rekordbox 7 through the master.db export.
|
||||
cue.ColorTableIndex = int(color_code)
|
||||
cue.Color = -1
|
||||
elif is_loop:
|
||||
# What Rekordbox writes on the loops and auto-cues it creates.
|
||||
cue.Color = 255
|
||||
cue.ColorTableIndex = 0
|
||||
else:
|
||||
cue.Color = -1
|
||||
cue.ColorTableIndex = None
|
||||
|
||||
def set_cue_color(self, track_id: str, slot: int, color_code: int | None) -> None:
|
||||
"""Recolour the cue in `slot`; None makes it uncoloured. Touches only the
|
||||
colour columns, so the position does not take a time-base round trip."""
|
||||
cue = self._cue_row(track_id, slot)
|
||||
if cue is None:
|
||||
raise NotFound(f"No cue in slot {slot}")
|
||||
self._apply_color(cue, color_code, (cue.OutMsec or 0) > 0)
|
||||
self._db.flush()
|
||||
self._sync_content_cue(track_id)
|
||||
self._journal.record("cue", "modify", track_id, f"slot:{slot}")
|
||||
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> None:
|
||||
cue = self._cue_row(track_id, slot)
|
||||
if cue is None:
|
||||
@@ -930,53 +1413,6 @@ class RekordboxStore:
|
||||
row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0
|
||||
self._journal.record("grid", "replace" if ordered else "delete", track_id)
|
||||
|
||||
def delete_grid(self, track_id: str) -> None:
|
||||
self.replace_grid(track_id, [])
|
||||
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
|
||||
from ...core.model import GridMarker
|
||||
|
||||
markers = self.current_markers(track_id)
|
||||
if bpm is None:
|
||||
# Inherit the tempo governing this point, like Traktor's add does.
|
||||
governing = [m for m in markers if m.start <= start_sec]
|
||||
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
|
||||
if not bpm:
|
||||
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
|
||||
if any(abs(m.start - start_sec) < 0.001 for m in markers):
|
||||
raise InvalidCommand("There is already a marker here")
|
||||
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
|
||||
markers = self.current_markers(track_id)
|
||||
if not 0 <= index < len(markers):
|
||||
raise NotFound(f"No grid marker {index}")
|
||||
return markers, index
|
||||
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
# Clamp between neighbours so the list cannot reorder under the caller.
|
||||
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
|
||||
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
|
||||
target = max(low, float(start_sec))
|
||||
if high is not None:
|
||||
target = min(target, high)
|
||||
markers[i] = markers[i].model_copy(update={"start": target})
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
if bpm <= 0:
|
||||
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
|
||||
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
del markers[i]
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def _flush_grids(self) -> None:
|
||||
"""Write buffered grids into their ANLZ files. Called by save().
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Remote libraries: a library held by a Konduktor server, opened from here.
|
||||
|
||||
NOT a registered driver: a remote is not a file `can_open` could probe, and it
|
||||
is chosen from the picker's own "Remote" step, by the saved remote's id. What
|
||||
opening one returns is everything `AppState.open_remote` installs — the
|
||||
adapter, the services that keep history and export sets on the server, and the
|
||||
session that keeps this computer's hold on it.
|
||||
|
||||
Imports no platform adapter (`test_layering.py`): what platform the server
|
||||
holds is the server's business, and reaches this side only as capabilities.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from ... import exports
|
||||
from . import config
|
||||
from .adapter import RemoteAdapter
|
||||
from .client import AuthFailed, InUse, RemoteClient, SessionLost, Unreachable, VersionMismatch
|
||||
from .services import RemotePending, RemoteServices, RemoteSetStore
|
||||
from .session import RemoteSession
|
||||
|
||||
__all__ = [
|
||||
"AuthFailed", "InUse", "Opened", "RemoteAdapter", "SessionLost", "Unreachable",
|
||||
"VersionMismatch", "handshake", "open_remote",
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Opened:
|
||||
remote: config.Remote
|
||||
path: Path
|
||||
adapter: RemoteAdapter
|
||||
services: RemoteServices
|
||||
session: RemoteSession
|
||||
library_id: str
|
||||
pending: object | None
|
||||
#: Edits another computer left unsaved: {machine, summary}, or None.
|
||||
pending_edits: dict | None
|
||||
|
||||
|
||||
def open_remote(remote: config.Remote, *, takeover: bool = False, batch_probe=None,
|
||||
password: str | None = None, cache=None) -> Opened:
|
||||
"""Connect, take the session, and mirror the library. Raises `InUse` when
|
||||
another computer holds it (and `takeover` is not set), `AuthFailed`,
|
||||
`VersionMismatch` or `Unreachable` — all before anything is installed."""
|
||||
secret = password if password is not None else config.password(remote.id)
|
||||
if not secret:
|
||||
raise AuthFailed("No password is saved for this remote — edit it to enter one")
|
||||
client = RemoteClient(remote, secret)
|
||||
try:
|
||||
client_id = config.client_id()
|
||||
hello = client.hello(client_id)
|
||||
machine = config.machine_name()
|
||||
acquired = client.acquire(client_id, machine, takeover=takeover)
|
||||
session = RemoteSession(client, batch_probe=batch_probe, identity=(client_id, machine))
|
||||
adapter = RemoteAdapter(client, session, hello, cache=cache)
|
||||
session.on_reacquired = adapter.refresh
|
||||
except Exception:
|
||||
client.release()
|
||||
client.close()
|
||||
raise
|
||||
# The server's id for the library, namespaced: this computer's export-set
|
||||
# store for it is the SERVER (`RemoteSetStore`), and nothing this computer
|
||||
# keeps under the server's own id may be mistaken for it.
|
||||
library_id = f"remote:{hello['library_id']}"
|
||||
exports.use_store(library_id, RemoteSetStore(client))
|
||||
session.start()
|
||||
return Opened(
|
||||
remote=remote, path=Path(hello.get("path") or remote.name), adapter=adapter,
|
||||
services=RemoteServices(client), session=session, library_id=library_id,
|
||||
pending=RemotePending(client), pending_edits=acquired.get("pending_edits"),
|
||||
)
|
||||
|
||||
|
||||
def handshake(remote: config.Remote, password: str) -> list[dict]:
|
||||
"""Try each of the remote's addresses on its own: what a Save of the
|
||||
remote's settings reports. Each result is {address, url, ok, error, kind},
|
||||
`kind` one of ok / unreachable / auth / version / other."""
|
||||
results = []
|
||||
for label, url in remote.addresses():
|
||||
single = config.Remote(id=remote.id, name=remote.name, host=url, username=remote.username)
|
||||
client = RemoteClient(single, password, timeout=8.0)
|
||||
try:
|
||||
info = client.hello()
|
||||
results.append({"address": label, "url": url, "ok": True, "error": None, "kind": "ok",
|
||||
"name": info.get("name"), "platform": info.get("platform")})
|
||||
except Unreachable as ex:
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "unreachable"})
|
||||
except AuthFailed as ex:
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "auth"})
|
||||
except VersionMismatch as ex:
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "version"})
|
||||
except Exception as ex: # noqa: BLE001 — anything else is that address's answer
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "other"})
|
||||
finally:
|
||||
client.close()
|
||||
return results
|
||||
@@ -0,0 +1,514 @@
|
||||
"""`RemoteAdapter`: a library held by a Konduktor server, as a `LibraryAdapter`.
|
||||
|
||||
Everything above the adapter layer — routes, export, import, batches, the UI —
|
||||
works on a remote library unchanged, because this IS the adapter: the server
|
||||
holds the native model (`konduktor.server`), and every command travels to it
|
||||
over `remote_protocol`.
|
||||
|
||||
* **The projection is mirrored here.** The server's tracks are fetched once
|
||||
into a local `TrackIndex`, and each command's answer carries the tracks it
|
||||
changed — so filtering, sorting, facets and stats are as instant as on a
|
||||
local library, and use the SAME query code (`core/query.py`). Every answer
|
||||
carries the server's revision; a gap (an answer out of order, a reconnect)
|
||||
re-fetches the whole projection rather than guessing.
|
||||
* **`audio_path` downloads.** It must return a readable file on THIS
|
||||
computer, so it fetches the track into the shared cache (`cache.py`).
|
||||
Anything that only needs to know WHICH file a track is asks `audio_facts`,
|
||||
which never downloads.
|
||||
* **Read-only when the session is not ours** — taken over, or the server out
|
||||
of reach — through `capabilities()`, so the UI gates itself as it does for
|
||||
any read-only library. A command the server refuses for that reason (423)
|
||||
turns the session `taken_over` on the spot, not at the next heartbeat.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from ... import remote_protocol as rp
|
||||
from ...core.adapter import (
|
||||
AudioFacts,
|
||||
FileTagResult,
|
||||
NotFound,
|
||||
SaveOutcome,
|
||||
Unavailable,
|
||||
Unsupported,
|
||||
)
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.query import TrackIndex
|
||||
from .cache import RemoteAudioCache, StaleFacts
|
||||
from .cache import shared as shared_cache
|
||||
from .client import RemoteClient, SessionLost
|
||||
from .folder import ServerFile, ServerFiles
|
||||
from .session import RemoteSession
|
||||
|
||||
_NOT_HERE = "A remote library's paths are the server's configuration"
|
||||
|
||||
|
||||
class RemoteAdapter:
|
||||
def __init__(self, client: RemoteClient, session: RemoteSession, hello: dict, *,
|
||||
cache: RemoteAudioCache | None = None):
|
||||
self.platform = hello["platform"]
|
||||
self.path = Path(hello.get("path") or "")
|
||||
self.hello = hello
|
||||
self.client = client
|
||||
self.session = session
|
||||
self.cache = cache or shared_cache()
|
||||
self._index = TrackIndex()
|
||||
self._lock = threading.RLock()
|
||||
self._rev: int | None = None
|
||||
self._caps: tuple[int, Capabilities] | None = None
|
||||
self._facts: dict[str, AudioFacts] = {}
|
||||
#: Server path of an upload → (the local file it came from, its analysis lead).
|
||||
self._uploads: dict[str, tuple[Path, float | None]] = {}
|
||||
#: Content-folder files a listing returned, by their server path.
|
||||
self._listed: dict[str, ServerFile] = {}
|
||||
#: `str(Path(p))` → `p` for every server path this side has turned into
|
||||
#: a `Path` (an upload's target, a listed file): on Windows that
|
||||
#: conversion rewrites the separators, and the server must get its own
|
||||
#: spelling back.
|
||||
self._server_paths: dict[str, str] = {}
|
||||
self._dirty = bool(hello.get("dirty"))
|
||||
self._load()
|
||||
|
||||
# ---- following the server ---------------------------------------------------
|
||||
def _load(self) -> None:
|
||||
envelope = self.client.rpc("tracks")
|
||||
with self._lock:
|
||||
self._index.rebuild(list(envelope["result"]))
|
||||
self._rev = envelope["rev"]
|
||||
self._facts.clear()
|
||||
self._caps = None
|
||||
|
||||
def _apply(self, envelope: dict) -> None:
|
||||
"""Fold a command's answer into the mirror — or re-fetch on any gap."""
|
||||
with self._lock:
|
||||
rev = envelope.get("rev")
|
||||
if envelope.get("reset") or self._rev is None or rev != self._rev + 1:
|
||||
in_order = False
|
||||
else:
|
||||
in_order = True
|
||||
from ...core.model import Track
|
||||
|
||||
removed = set(envelope.get("removed") or [])
|
||||
if removed:
|
||||
self._index.rebuild([t for t in self._index.tracks if t.id not in removed])
|
||||
for raw in envelope.get("changed") or []:
|
||||
track = Track.model_validate(raw)
|
||||
self._index.add(track)
|
||||
self._facts.pop(track.id, None)
|
||||
for track_id in removed:
|
||||
self._facts.pop(track_id, None)
|
||||
self._rev = rev
|
||||
if not in_order:
|
||||
self._load()
|
||||
|
||||
def _call(self, method: str, /, **args):
|
||||
try:
|
||||
envelope = self.client.rpc(method, **args)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
if rp.RPC[method].mutating:
|
||||
self.session.reached()
|
||||
self._apply(envelope)
|
||||
return envelope["result"]
|
||||
|
||||
def refresh(self) -> None:
|
||||
"""Re-read everything from the server (after a restore, a reconnect)."""
|
||||
self._load()
|
||||
|
||||
# ---- identity -----------------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities:
|
||||
with self._lock:
|
||||
cached = self._caps
|
||||
if cached is None or cached[0] != self._rev:
|
||||
try:
|
||||
caps = self._call("capabilities")
|
||||
except Unavailable:
|
||||
# Out of reach: the last answer, read-only (below) — the UI
|
||||
# must still render, and gate every edit.
|
||||
if cached is None:
|
||||
raise
|
||||
caps = cached[1]
|
||||
else:
|
||||
with self._lock:
|
||||
self._caps = (self._rev, caps)
|
||||
else:
|
||||
caps = cached[1]
|
||||
if self.session.writable:
|
||||
return caps
|
||||
return caps.model_copy(update={"writable": False, "readonly_cause": self.session.readonly_cause})
|
||||
|
||||
def reload(self) -> None:
|
||||
# The server is what holds (and drops) the edits — `AppState.discard`
|
||||
# asks it to discard first; this is the mirror following.
|
||||
self._load()
|
||||
|
||||
# ---- read projection (the mirror) -------------------------------------------
|
||||
@property
|
||||
def tracks(self):
|
||||
return self._index.tracks
|
||||
|
||||
def track(self, track_id: str):
|
||||
return self._index.get(track_id)
|
||||
|
||||
def query_tracks(self, **kw):
|
||||
return self._index.query_tracks(**kw)
|
||||
|
||||
def facets(self):
|
||||
return self._index.facets()
|
||||
|
||||
def stats(self, playlist_count: int):
|
||||
return self._index.stats(playlist_count)
|
||||
|
||||
# ---- read projection (the server) -------------------------------------------
|
||||
def playlist_tree(self):
|
||||
return self._call("playlist_tree")
|
||||
|
||||
def playlist_count(self) -> int:
|
||||
return self._call("playlist_count")
|
||||
|
||||
def playlist_entries(self, node_id: str):
|
||||
return self._call("playlist_entries", node_id=node_id)
|
||||
|
||||
def playlist_tracks(self, node_id: str):
|
||||
entries = self.playlist_entries(node_id)
|
||||
if entries is None:
|
||||
return None
|
||||
return [t for k in entries if (t := self._index.get(k)) is not None]
|
||||
|
||||
def track_cues(self, track_id: str):
|
||||
return self._call("track_cues", track_id=track_id)
|
||||
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
try:
|
||||
self._dirty = self._call("dirty")
|
||||
except Unavailable:
|
||||
pass # out of reach: what it was
|
||||
return self._dirty
|
||||
|
||||
# ---- commands -------------------------------------------------------------------
|
||||
def create_playlist(self, name, parent_id=None):
|
||||
return self._call("create_playlist", name=name, parent_id=parent_id)
|
||||
|
||||
def create_folder(self, name, parent_id=None):
|
||||
return self._call("create_folder", name=name, parent_id=parent_id)
|
||||
|
||||
def rename_playlist(self, node_id, name):
|
||||
return self._call("rename_playlist", node_id=node_id, name=name)
|
||||
|
||||
def delete_playlist(self, node_id):
|
||||
return self._call("delete_playlist", node_id=node_id)
|
||||
|
||||
def move_playlist(self, node_id, parent_id, index):
|
||||
return self._call("move_playlist", node_id=node_id, parent_id=parent_id, index=index)
|
||||
|
||||
def set_playlist_entries(self, node_id, track_ids):
|
||||
return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids))
|
||||
|
||||
def remove_tracks(self, track_ids):
|
||||
return self._call("remove_tracks", track_ids=list(track_ids))
|
||||
|
||||
def set_track_metadata(self, track_id, fields):
|
||||
return self._call("set_track_metadata", track_id=track_id, fields=fields)
|
||||
|
||||
def set_key(self, track_id, wheel, mode):
|
||||
return self._call("set_key", track_id=track_id, wheel=wheel, mode=mode)
|
||||
|
||||
def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None):
|
||||
return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec,
|
||||
cue_type=cue_type, length_sec=length_sec, role=role, name=name)
|
||||
|
||||
def set_cue_type(self, track_id, slot, cue_type):
|
||||
return self._call("set_cue_type", track_id=track_id, slot=slot, cue_type=cue_type)
|
||||
|
||||
def set_cue_color(self, track_id, slot, color):
|
||||
return self._call("set_cue_color", track_id=track_id, slot=slot, color=color)
|
||||
|
||||
def delete_cue(self, track_id, slot):
|
||||
return self._call("delete_cue", track_id=track_id, slot=slot)
|
||||
|
||||
def place_cues(self, track_id, cues, *, overwrite=False):
|
||||
return self._call("place_cues", track_id=track_id, cues=list(cues), overwrite=overwrite)
|
||||
|
||||
def add_grid_marker(self, track_id, start_sec, bpm=None):
|
||||
return self._call("add_grid_marker", track_id=track_id, start_sec=start_sec, bpm=bpm)
|
||||
|
||||
def move_grid_marker(self, track_id, index, start_sec):
|
||||
return self._call("move_grid_marker", track_id=track_id, index=index, start_sec=start_sec)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id, index, bpm):
|
||||
return self._call("set_grid_marker_bpm", track_id=track_id, index=index, bpm=bpm)
|
||||
|
||||
def delete_grid_marker(self, track_id, index):
|
||||
return self._call("delete_grid_marker", track_id=track_id, index=index)
|
||||
|
||||
def replace_grid(self, track_id, markers):
|
||||
return self._call("replace_grid", track_id=track_id, markers=_pairs(markers))
|
||||
|
||||
def set_analysed_grid(self, track_id, markers):
|
||||
return self._call("set_analysed_grid", track_id=track_id, markers=_pairs(markers))
|
||||
|
||||
def delete_grid(self, track_id):
|
||||
return self._call("delete_grid", track_id=track_id)
|
||||
|
||||
def set_grid_lock(self, track_id, locked):
|
||||
return self._call("set_grid_lock", track_id=track_id, locked=locked)
|
||||
|
||||
# ---- adding tracks ------------------------------------------------------------------
|
||||
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
|
||||
taken name gets `-2`…, as a local copy does). What a local import's
|
||||
file copy becomes when the library's destination is the server's."""
|
||||
try:
|
||||
landed = self.client.upload(Path(source), folder, name, progress=progress)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead"))
|
||||
self._server_paths[str(Path(landed["path"]))] = landed["path"]
|
||||
return Path(landed["path"])
|
||||
|
||||
def free_space(self, path: str) -> int:
|
||||
"""Free space on the SERVER's disk at `path` (an import's destination)."""
|
||||
return self.client.fs_space(path)
|
||||
|
||||
def delete_upload(self, path) -> None:
|
||||
"""Undo `upload_audio` (a cancelled or failed import)."""
|
||||
key = self._server_key(path)
|
||||
self._uploads.pop(key, None)
|
||||
self.client.delete_upload(key)
|
||||
|
||||
def _server_key(self, path) -> str:
|
||||
text = str(path)
|
||||
return self._server_paths.get(text, text)
|
||||
|
||||
def add_tracks(self, items, *, checkpoint=None):
|
||||
"""Add uploaded files. Where the platform analyses what it adds (the
|
||||
server said so with an analysis lead), the analysis is done HERE, on
|
||||
the copy this computer uploaded — the server never decodes audio."""
|
||||
from ...core import add_analysis
|
||||
|
||||
wire = []
|
||||
total = len(items)
|
||||
keys = [self._server_key(item.audio_path) for item in items]
|
||||
# Files already in the content folder (added in place): the server says
|
||||
# whether the platform analyses, and only then is the file fetched.
|
||||
in_place = [k for k, item in zip(keys, items)
|
||||
if item.analysis is None and k not in self._uploads and k in self._listed]
|
||||
leads = self.client.folder_leads(in_place) if in_place else {}
|
||||
for n, (item, key) in enumerate(zip(items, keys), start=1):
|
||||
source, lead = self._uploads.get(key, (None, None))
|
||||
analysis = item.analysis
|
||||
if analysis is None and source is None and leads.get(key) is not None:
|
||||
lead = leads[key]
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Downloading {item.track.title or Path(key).name} ({n}/{total})", step=n, of=total)
|
||||
source = self.folder_audio(key)
|
||||
if analysis is None and lead is not None and source is not None:
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total)
|
||||
has_grid = bool(item.cues and item.cues.grid_markers)
|
||||
analysis = add_analysis.prepare(source, lead=lead, detect=not has_grid,
|
||||
detect_key=item.track.key_wheel is None)
|
||||
art = rp.WireArt(data=base64.b64encode(item.art[0]).decode("ascii"), mime=item.art[1]) \
|
||||
if item.art else None
|
||||
wire.append(rp.WireNewTrack(track=item.track, audio_path=key, cues=item.cues, art=art,
|
||||
analysis=rp.pack_analysis(analysis)))
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Adding {total} track{'' if total == 1 else 's'} on the server",
|
||||
step=total, of=total)
|
||||
try:
|
||||
envelope = self.client.rpc("add_tracks", items=wire, timeout=None)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._apply(envelope)
|
||||
for key in keys:
|
||||
self._uploads.pop(key, None)
|
||||
return envelope["result"]
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
raise Unsupported("A remote library's stem files are swapped in on the server")
|
||||
|
||||
# ---- Convert to Stems (the library side lives on the server) ---------------------
|
||||
# `stems/remote_convert.py` drives these: the server plans and swaps, this
|
||||
# computer separates. See the server's stem routes for why.
|
||||
def stems_plan(self, body: dict) -> dict:
|
||||
return self.client.stems_plan(body)
|
||||
|
||||
def stage_stem(self, track_id: str, target: str, local: Path, *, bit_rate: int,
|
||||
duration: float, progress=None) -> dict:
|
||||
import hashlib
|
||||
|
||||
digest = hashlib.sha256()
|
||||
with open(local, "rb") as f:
|
||||
while chunk := f.read(1 << 20):
|
||||
digest.update(chunk)
|
||||
try:
|
||||
return self.client.stems_stage(track_id, target, local, sha256=digest.hexdigest(),
|
||||
bit_rate=bit_rate, duration=duration, progress=progress)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
|
||||
def abandon_stems(self, targets: list[str]) -> None:
|
||||
self.client.stems_abandon(targets)
|
||||
|
||||
def publish_stems(self, items: list[dict], options: dict) -> dict:
|
||||
try:
|
||||
result = self.client.stems_publish(items, options)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._load() # ids changed (repoint) or entries were added
|
||||
return result
|
||||
|
||||
# ---- metadata / art ------------------------------------------------------------------
|
||||
def set_cover_art(self, track_id, data, mime):
|
||||
try:
|
||||
envelope = self.client.put_art(track_id, data, mime)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._apply({**envelope, "removed": [], "reset": False})
|
||||
|
||||
def cover_art(self, track_id):
|
||||
return self.client.art(track_id)
|
||||
|
||||
# ---- audio ------------------------------------------------------------------------------
|
||||
def audio_facts(self, track_ids):
|
||||
wanted = list(dict.fromkeys(track_ids))
|
||||
with self._lock:
|
||||
missing = [t for t in wanted if t not in self._facts]
|
||||
if missing:
|
||||
found = {}
|
||||
for start in range(0, len(missing), 2000):
|
||||
found.update(self._call("audio_facts", track_ids=missing[start:start + 2000]))
|
||||
with self._lock:
|
||||
self._facts.update(found)
|
||||
with self._lock:
|
||||
return {t: self._facts[t] for t in wanted if t in self._facts}
|
||||
|
||||
def audio_path(self, track_id, *, progress=None):
|
||||
"""A local copy of the track's audio, downloaded if this computer has
|
||||
none of this version. None when the server has no file for it."""
|
||||
for attempt in range(2):
|
||||
facts = self.audio_facts([track_id]).get(track_id)
|
||||
if facts is None:
|
||||
return None
|
||||
cached = self.cache.get(facts)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
return self.cache.fetch(
|
||||
facts, lambda partial: self.client.download(track_id, partial, progress=progress))
|
||||
except StaleFacts:
|
||||
with self._lock:
|
||||
self._facts.pop(track_id, None)
|
||||
if attempt:
|
||||
raise
|
||||
return None
|
||||
|
||||
def cached_audio(self, track_id) -> Path | None:
|
||||
"""The local copy if there already is one — never downloads."""
|
||||
facts = self.audio_facts([track_id]).get(track_id)
|
||||
return self.cache.get(facts) if facts else None
|
||||
|
||||
# ---- the content folder, browsed --------------------------------------------------
|
||||
def folder_listing(self, path: str | None) -> ServerFiles:
|
||||
"""The audio directly inside a content folder (None: the folder itself),
|
||||
as the server lists it — and remembered, so a file can then be played
|
||||
or added by its path."""
|
||||
listing = ServerFiles.from_wire(self, self.client.folder_tracks(path))
|
||||
with self._lock:
|
||||
self._listed = {k: f for k, f in self._listed.items() if f.folder != listing.path}
|
||||
self._listed.update(listing.files)
|
||||
self._server_paths.update({str(Path(k)): k for k in listing.files})
|
||||
return listing
|
||||
|
||||
def listed_files(self, paths) -> ServerFiles | None:
|
||||
"""The listed files among `paths` as one source (they may come from
|
||||
several folders); None when none of them was listed."""
|
||||
with self._lock:
|
||||
found = [self._listed[p] for p in paths if p in self._listed]
|
||||
return ServerFiles(self, found[0].folder, found) if found else None
|
||||
|
||||
def folder_audio(self, path: str, *, progress=None) -> Path:
|
||||
"""A local copy of a listed file, downloaded into the shared cache —
|
||||
keyed by the same facts as a library track's, so a file that is both
|
||||
downloads once."""
|
||||
for attempt in range(2):
|
||||
with self._lock:
|
||||
found = self._listed.get(path)
|
||||
if found is None:
|
||||
raise NotFound("File not found — browse to its folder first")
|
||||
cached = self.cache.get(found.facts)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
return self.cache.fetch(
|
||||
found.facts, lambda partial: self.client.folder_download(path, partial, progress=progress))
|
||||
except StaleFacts:
|
||||
if attempt:
|
||||
raise
|
||||
self.folder_listing(found.folder) # changed on the server: re-read it
|
||||
raise NotFound(path)
|
||||
|
||||
# ---- paths: the server's business ------------------------------------------------
|
||||
def set_path_mapping(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def set_session_mappings(self, mappings):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def unresolved_path_groups(self):
|
||||
return []
|
||||
|
||||
def path_prefix_suggestions(self):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def remap_preview(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def remap_locations(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
# ---- save ----------------------------------------------------------------------------
|
||||
def save(self):
|
||||
try:
|
||||
result = self.client.save()
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
outcome = SaveOutcome(
|
||||
summary=result.get("summary") or "",
|
||||
snapshot=None,
|
||||
tag_results=[FileTagResult(**r) for r in result.get("tag_results") or []],
|
||||
)
|
||||
# Versioned on the server; `RemoteServices.commit_save` hands it on.
|
||||
outcome.commit = result.get("commit")
|
||||
self._load()
|
||||
return outcome
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
raise Unsupported("A remote library's version history is kept on the server")
|
||||
|
||||
def close(self) -> None:
|
||||
self.session.stop()
|
||||
self.client.release()
|
||||
self.client.close()
|
||||
|
||||
|
||||
def _pairs(markers) -> list[tuple[float, float]]:
|
||||
out = []
|
||||
for m in markers:
|
||||
if hasattr(m, "start"):
|
||||
out.append((float(m.start), float(m.bpm)))
|
||||
else:
|
||||
start, bpm = m
|
||||
out.append((float(start), float(bpm)))
|
||||
return out
|
||||
@@ -0,0 +1,194 @@
|
||||
"""This computer's copies of a remote library's audio.
|
||||
|
||||
Everything that needs a track's audio as a FILE runs here, not on the server —
|
||||
the deck's decode, grid and cue analysis, stem separation and extraction, an
|
||||
export's copy onto a stick. One cache serves them all, so a track analysed and
|
||||
then exported downloads once.
|
||||
|
||||
* **Keyed by what the server says the file IS** — its path there, size and
|
||||
mtime (`AudioFacts`) — never by when it was fetched: an edited file (Save
|
||||
writes tags into it) is a new entry, and the same file fetched again after
|
||||
an eviction, or by another computer exporting the same set, is recognised.
|
||||
* **A partial, renamed into place**, so a cut connection never leaves a
|
||||
truncated file under a real entry's name, and a download whose size does
|
||||
not match the facts is refused rather than kept.
|
||||
* **Least recently used, under a cap** (`remoteCacheBytes` in prefs). The
|
||||
entry just written and anything touched in the last few minutes are never
|
||||
the ones evicted: they are being played or copied right now.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from ... import paths, prefs
|
||||
from ...core.adapter import AudioFacts, Unavailable
|
||||
|
||||
DEFAULT_CAP = 10 * 1024 ** 3
|
||||
_RECENT = 300.0 # seconds: an entry touched this recently is in use
|
||||
_PART = ".part"
|
||||
|
||||
|
||||
class StaleFacts(Unavailable):
|
||||
"""The server's file changed between asking about it and downloading it."""
|
||||
|
||||
|
||||
def cache_root() -> Path:
|
||||
return paths.app_data_dir() / "remote-cache"
|
||||
|
||||
|
||||
def cap_bytes() -> int:
|
||||
try:
|
||||
value = int(prefs.load_prefs().get("remoteCacheBytes") or DEFAULT_CAP)
|
||||
except (TypeError, ValueError):
|
||||
value = DEFAULT_CAP
|
||||
return max(value, 256 * 1024 ** 2)
|
||||
|
||||
|
||||
class RemoteAudioCache:
|
||||
def __init__(self, root: Path | None = None, *, cap=None, clock=time.time):
|
||||
self.root = Path(root) if root is not None else cache_root()
|
||||
self._cap = cap if cap is not None else cap_bytes
|
||||
self._clock = clock
|
||||
self._locks: dict[str, threading.Lock] = {}
|
||||
self._guard = threading.Lock()
|
||||
#: Recent download speeds (bytes/s), newest last — for time estimates.
|
||||
self._speeds: list[float] = []
|
||||
|
||||
# ---- naming ----------------------------------------------------------------
|
||||
@staticmethod
|
||||
def key(facts: AudioFacts) -> str:
|
||||
text = f"{facts.key}|{facts.size}|{facts.mtime_ns}"
|
||||
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:32]
|
||||
|
||||
def path_for(self, facts: AudioFacts) -> Path:
|
||||
# The original's suffix, so a MIME type and a decoder's guess still work.
|
||||
suffix = Path(facts.key.replace("\\", "/")).suffix.lower()
|
||||
return self.root / f"{self.key(facts)}{suffix}"
|
||||
|
||||
def _lock_for(self, key: str) -> threading.Lock:
|
||||
with self._guard:
|
||||
return self._locks.setdefault(key, threading.Lock())
|
||||
|
||||
# ---- use -------------------------------------------------------------------
|
||||
def get(self, facts: AudioFacts) -> Path | None:
|
||||
path = self.path_for(facts)
|
||||
if path.is_file():
|
||||
self._touch(path)
|
||||
return path
|
||||
return None
|
||||
|
||||
def fetch(self, facts: AudioFacts, download) -> Path:
|
||||
"""The cached copy, downloading it first if needed. `download(partial)`
|
||||
writes the file and returns the server's `{size, mtime_ns}` for it."""
|
||||
path = self.path_for(facts)
|
||||
with self._lock_for(path.name):
|
||||
if path.is_file():
|
||||
self._touch(path)
|
||||
return path
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
partial = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}{_PART}")
|
||||
started = time.monotonic()
|
||||
try:
|
||||
meta = download(partial) or {}
|
||||
got = partial.stat().st_size
|
||||
if got != facts.size or (meta.get("size") and meta["size"] != facts.size):
|
||||
raise StaleFacts(f"{Path(facts.key).name} changed on the server while downloading")
|
||||
os.replace(partial, path)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
elapsed = max(time.monotonic() - started, 1e-3)
|
||||
if facts.size > 1 << 20:
|
||||
self._speeds = (self._speeds + [facts.size / elapsed])[-8:]
|
||||
self._touch(path)
|
||||
self.prune(keep={path})
|
||||
return path
|
||||
|
||||
def speed(self) -> float | None:
|
||||
"""A recent download speed in bytes/s, or None before the first."""
|
||||
if not self._speeds:
|
||||
return None
|
||||
ordered = sorted(self._speeds)
|
||||
return ordered[len(ordered) // 2]
|
||||
|
||||
def _touch(self, path: Path) -> None:
|
||||
now = self._clock()
|
||||
try:
|
||||
os.utime(path, (now, now))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# ---- housekeeping ------------------------------------------------------------
|
||||
def _entries(self) -> list[tuple[float, int, Path]]:
|
||||
out = []
|
||||
if not self.root.is_dir():
|
||||
return out
|
||||
for p in self.root.iterdir():
|
||||
if p.name.endswith(_PART) or not p.is_file():
|
||||
continue
|
||||
try:
|
||||
st = p.stat()
|
||||
except OSError:
|
||||
continue
|
||||
out.append((st.st_mtime, st.st_size, p))
|
||||
return out
|
||||
|
||||
def prune(self, keep: set[Path] | None = None) -> int:
|
||||
"""Evict least-recently-used entries until under the cap. Returns bytes freed."""
|
||||
cap = self._cap() if callable(self._cap) else self._cap
|
||||
entries = sorted(self._entries())
|
||||
total = sum(size for _, size, _ in entries)
|
||||
freed = 0
|
||||
now = self._clock()
|
||||
for used, size, p in entries:
|
||||
if total <= cap:
|
||||
break
|
||||
if (keep and p in keep) or now - used < _RECENT:
|
||||
continue
|
||||
try:
|
||||
p.unlink()
|
||||
except OSError:
|
||||
continue # held open (Windows): next time
|
||||
total -= size
|
||||
freed += size
|
||||
return freed
|
||||
|
||||
def usage(self) -> dict:
|
||||
entries = self._entries()
|
||||
cap = self._cap() if callable(self._cap) else self._cap
|
||||
return {"bytes": sum(s for _, s, _ in entries), "files": len(entries), "cap": cap,
|
||||
"free": _free(self.root)}
|
||||
|
||||
def clear(self) -> int:
|
||||
freed = 0
|
||||
for _, size, p in self._entries():
|
||||
try:
|
||||
p.unlink()
|
||||
freed += size
|
||||
except OSError:
|
||||
pass
|
||||
return freed
|
||||
|
||||
|
||||
def _free(folder: Path) -> int:
|
||||
probe = folder
|
||||
while not probe.exists() and probe != probe.parent:
|
||||
probe = probe.parent
|
||||
try:
|
||||
return shutil.disk_usage(probe).free
|
||||
except OSError:
|
||||
return 0
|
||||
|
||||
|
||||
_shared: RemoteAudioCache | None = None
|
||||
|
||||
|
||||
def shared() -> RemoteAudioCache:
|
||||
global _shared
|
||||
if _shared is None:
|
||||
_shared = RemoteAudioCache()
|
||||
return _shared
|
||||
@@ -0,0 +1,325 @@
|
||||
"""Talking to a Konduktor server: addresses, sign-in, and the error vocabulary.
|
||||
|
||||
Every request tries the address that last worked, then the others in the
|
||||
remote's order (primary, then fallback) — so a laptop that leaves the house
|
||||
moves from the LAN address to the VPN one without being asked, and back again.
|
||||
Only a CONNECT failure moves on: the request never reached that server, so
|
||||
sending it to the other one cannot apply it twice. A request that reached a
|
||||
server and then failed is that server's answer.
|
||||
|
||||
The server's refusals come back as the adapter's own error classes (the same
|
||||
status codes `main.py` maps them from), so a route on this computer reports a
|
||||
remote library's refusal exactly as it would a local one's.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from ... import remote_protocol as rp
|
||||
from ...core.adapter import (
|
||||
AdapterError,
|
||||
InvalidCommand,
|
||||
LibraryNotSupported,
|
||||
NotFound,
|
||||
Unavailable,
|
||||
Unsupported,
|
||||
)
|
||||
from .config import Remote
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_CONNECT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout)
|
||||
|
||||
|
||||
class Unreachable(Unavailable):
|
||||
"""No address of the remote answered."""
|
||||
|
||||
|
||||
class AuthFailed(LibraryNotSupported):
|
||||
"""The server refused the username or password."""
|
||||
|
||||
|
||||
class VersionMismatch(LibraryNotSupported):
|
||||
def __init__(self, update: str, server_version: str):
|
||||
side = "Konduktor on this computer" if update == "app" else "the Konduktor server"
|
||||
super().__init__(
|
||||
f"This server speaks a different version of Konduktor's protocol "
|
||||
f"(server {server_version}): update {side}."
|
||||
)
|
||||
self.update = update
|
||||
|
||||
|
||||
class InUse(AdapterError):
|
||||
"""Another computer holds the session: `holder` = {machine, since, batch}."""
|
||||
|
||||
def __init__(self, holder: dict):
|
||||
super().__init__(f"In use by {holder.get('machine') or 'another computer'}")
|
||||
self.holder = holder
|
||||
|
||||
|
||||
class SessionLost(Unavailable):
|
||||
"""This computer no longer holds the session (another one took over)."""
|
||||
|
||||
def __init__(self, holder: dict | None):
|
||||
who = (holder or {}).get("machine")
|
||||
super().__init__(
|
||||
f"{who} has taken over this library — it is read-only here" if who
|
||||
else "This computer no longer holds the library's session"
|
||||
)
|
||||
self.holder = holder
|
||||
|
||||
|
||||
def _detail(response: httpx.Response):
|
||||
try:
|
||||
return response.json().get("detail")
|
||||
except Exception: # noqa: BLE001
|
||||
return response.text[:300]
|
||||
|
||||
|
||||
class RemoteClient:
|
||||
def __init__(self, remote: Remote, password: str, *, timeout: float = 30.0):
|
||||
self.remote = remote
|
||||
self._addresses = remote.addresses()
|
||||
self._active: int | None = None
|
||||
self.token: str | None = None
|
||||
self._lock = threading.Lock()
|
||||
self._http = httpx.Client(
|
||||
auth=(remote.username, password),
|
||||
timeout=httpx.Timeout(timeout, connect=4.0),
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
self._http.close()
|
||||
|
||||
@property
|
||||
def via(self) -> str | None:
|
||||
"""Which address is in use: "primary" / "fallback" (None until one answers)."""
|
||||
return None if self._active is None else self._addresses[self._active][0]
|
||||
|
||||
# ---- transport ----------------------------------------------------------------
|
||||
def _order(self) -> list[int]:
|
||||
everything = list(range(len(self._addresses)))
|
||||
if self._active is None:
|
||||
return everything
|
||||
return [self._active] + [i for i in everything if i != self._active]
|
||||
|
||||
def request(self, method: str, path: str, *, retry: bool = True, session: bool = True,
|
||||
**kw) -> httpx.Response:
|
||||
headers = dict(kw.pop("headers", None) or {})
|
||||
if session and self.token:
|
||||
headers[rp.SESSION_HEADER] = self.token
|
||||
order = self._order() if retry else ([self._active] if self._active is not None else [0])
|
||||
last: Exception | None = None
|
||||
for i in order:
|
||||
base = self._addresses[i][1]
|
||||
try:
|
||||
response = self._http.request(method, base + path, headers=headers, **kw)
|
||||
except _CONNECT_ERRORS as ex:
|
||||
last = ex
|
||||
continue
|
||||
except httpx.TimeoutException as ex:
|
||||
self._active = i
|
||||
raise Unreachable(f"The server at {base} stopped answering") from ex
|
||||
except httpx.TransportError as ex:
|
||||
last = ex
|
||||
continue
|
||||
self._active = i
|
||||
return self.check(response)
|
||||
names = " or ".join(b for _, b in (self._addresses[i] for i in order))
|
||||
raise Unreachable(f"Cannot reach the server at {names}") from last
|
||||
|
||||
def stream(self, method: str, path: str, **kw):
|
||||
"""A streaming request on the address in use (a download)."""
|
||||
headers = dict(kw.pop("headers", None) or {})
|
||||
if self.token:
|
||||
headers[rp.SESSION_HEADER] = self.token
|
||||
# Pick the address first with a cheap call, so the stream itself is not
|
||||
# the request that discovers the primary is gone.
|
||||
if self._active is None:
|
||||
self.request("GET", "/v1/hello", session=False)
|
||||
base = self._addresses[self._active][1]
|
||||
return self._http.stream(method, base + path, headers=headers, **kw)
|
||||
|
||||
@staticmethod
|
||||
def check(response: httpx.Response) -> httpx.Response:
|
||||
status = response.status_code
|
||||
if status < 400:
|
||||
return response
|
||||
detail = _detail(response)
|
||||
if status == 401:
|
||||
raise AuthFailed("The server refused the username or password")
|
||||
if status == 423:
|
||||
raise SessionLost((detail or {}).get("holder") if isinstance(detail, dict) else None)
|
||||
if status == 409 and isinstance(detail, dict) and detail.get("code") == "in_use":
|
||||
raise InUse(detail)
|
||||
text = detail if isinstance(detail, str) else (detail or {}).get("message", str(detail))
|
||||
cls = {404: NotFound, 400: InvalidCommand, 422: Unsupported, 503: Unavailable}.get(status)
|
||||
if cls is not None:
|
||||
raise cls(text)
|
||||
raise AdapterError(f"The server answered {status}: {text}")
|
||||
|
||||
# ---- handshake + session ----------------------------------------------------------
|
||||
def hello(self, client_id: str | None = None) -> dict:
|
||||
info = self.request("GET", "/v1/hello", params={"client_id": client_id} if client_id else None,
|
||||
session=False).json()
|
||||
server_version = tuple(info.get("api_version") or (0, 0))
|
||||
update = rp.compatible(rp.API_VERSION, (int(server_version[0]), int(server_version[1])))
|
||||
if update:
|
||||
raise VersionMismatch(update, info.get("app_version") or ".".join(map(str, server_version)))
|
||||
return info
|
||||
|
||||
def acquire(self, client_id: str, machine: str, *, takeover: bool = False) -> dict:
|
||||
body = self.request("POST", "/v1/session/acquire", session=False,
|
||||
json={"client_id": client_id, "machine": machine, "takeover": takeover}).json()
|
||||
self.token = body["token"]
|
||||
return body
|
||||
|
||||
def heartbeat(self, batch: str | None) -> dict:
|
||||
return self.request("POST", "/v1/session/heartbeat", json={"batch": batch}).json()
|
||||
|
||||
def release(self, *, timeout: float | None = None) -> None:
|
||||
if not self.token:
|
||||
return
|
||||
try:
|
||||
kw = {"timeout": timeout} if timeout is not None else {}
|
||||
self.request("POST", "/v1/session/release", retry=False, **kw)
|
||||
except AdapterError:
|
||||
pass
|
||||
self.token = None
|
||||
|
||||
# ---- the protocol -------------------------------------------------------------------
|
||||
def rpc(self, method: str, /, *, timeout=..., **args) -> dict:
|
||||
"""Call one protocol method; the envelope `{result, rev, changed, removed, reset}`
|
||||
with `result` already deserialised."""
|
||||
kw = {} if timeout is ... else {"timeout": timeout}
|
||||
body = self.request("POST", f"/v1/rpc/{method}", json={"args": rp.dump_args(method, args)}, **kw).json()
|
||||
body["result"] = rp.load_result(method, body.get("result"))
|
||||
return body
|
||||
|
||||
# ---- bytes -----------------------------------------------------------------------------
|
||||
def download(self, track_id: str, target: Path, *, progress=None) -> dict:
|
||||
"""Stream a track's audio into `target`; its server-side size and mtime."""
|
||||
with self.stream("GET", "/v1/audio", params={"track_id": track_id}, timeout=None) as response:
|
||||
if response.status_code >= 400:
|
||||
response.read()
|
||||
self.check(response)
|
||||
with open(target, "wb") as out:
|
||||
for chunk in response.iter_bytes(1 << 20):
|
||||
out.write(chunk)
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
return {
|
||||
"size": int(response.headers.get("X-Konduktor-Size") or 0),
|
||||
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
|
||||
}
|
||||
|
||||
def upload(self, source: Path, folder: str, name: str, *, progress=None) -> dict:
|
||||
def body():
|
||||
with open(source, "rb") as f:
|
||||
while chunk := f.read(1 << 20):
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
yield chunk
|
||||
|
||||
return self.request("POST", "/v1/upload", params={"dir": folder, "name": name},
|
||||
content=body(), retry=False, timeout=None).json()
|
||||
|
||||
def delete_upload(self, path: str) -> None:
|
||||
self.request("DELETE", "/v1/upload", params={"path": path})
|
||||
|
||||
def art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
try:
|
||||
r = self.request("GET", "/v1/art", params={"track_id": track_id})
|
||||
except NotFound:
|
||||
return None
|
||||
return r.content, r.headers.get("content-type", "image/jpeg").split(";")[0]
|
||||
|
||||
def put_art(self, track_id: str, data: bytes, mime: str) -> dict:
|
||||
return self.request("PUT", "/v1/art", params={"track_id": track_id, "mime": mime},
|
||||
content=data).json()
|
||||
|
||||
def fs_list(self, path: str | None) -> dict:
|
||||
return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json()
|
||||
|
||||
def folder_tracks(self, path: str | None) -> dict:
|
||||
return self.request("GET", "/v1/folder/tracks", params={"path": path} if path else None,
|
||||
timeout=None).json()
|
||||
|
||||
def folder_leads(self, paths: list[str]) -> dict[str, float | None]:
|
||||
return self.request("POST", "/v1/folder/leads", json={"paths": paths}).json()["leads"]
|
||||
|
||||
def folder_download(self, path: str, target: Path, *, progress=None) -> dict:
|
||||
"""Stream a listed content-folder file into `target` (as `download`)."""
|
||||
with self.stream("GET", "/v1/folder/audio", params={"path": path}, timeout=None) as response:
|
||||
if response.status_code >= 400:
|
||||
response.read()
|
||||
self.check(response)
|
||||
with open(target, "wb") as out:
|
||||
for chunk in response.iter_bytes(1 << 20):
|
||||
out.write(chunk)
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
return {
|
||||
"size": int(response.headers.get("X-Konduktor-Size") or 0),
|
||||
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
|
||||
}
|
||||
|
||||
def fs_space(self, path: str | None) -> int:
|
||||
return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"])
|
||||
|
||||
# ---- Convert to Stems ----------------------------------------------------------------
|
||||
def stems_plan(self, body: dict) -> dict:
|
||||
return self.request("POST", "/v1/stems/plan", json=body, timeout=None).json()
|
||||
|
||||
def stems_stage(self, track_id: str, target: str, source: Path, *, sha256: str,
|
||||
bit_rate: int, duration: float, progress=None) -> dict:
|
||||
def body():
|
||||
with open(source, "rb") as f:
|
||||
while chunk := f.read(1 << 20):
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
yield chunk
|
||||
|
||||
return self.request(
|
||||
"PUT", "/v1/stems/stage",
|
||||
params={"track_id": track_id, "target": target, "sha256": sha256,
|
||||
"bit_rate": bit_rate, "duration": duration},
|
||||
content=body(), retry=False, timeout=None,
|
||||
).json()
|
||||
|
||||
def stems_abandon(self, targets: list[str]) -> None:
|
||||
self.request("POST", "/v1/stems/abandon", json={"targets": targets})
|
||||
|
||||
def stems_publish(self, items: list[dict], options: dict) -> dict:
|
||||
return self.request("POST", "/v1/stems/publish", json={"items": items, "options": options},
|
||||
timeout=None).json()
|
||||
|
||||
def stems_pending(self) -> dict:
|
||||
return self.request("GET", "/v1/stems/pending").json()
|
||||
|
||||
# ---- save / history / export sets -------------------------------------------------
|
||||
def save(self) -> dict:
|
||||
return self.request("POST", "/v1/save", timeout=None).json()
|
||||
|
||||
def discard(self) -> dict:
|
||||
return self.request("POST", "/v1/discard", timeout=None).json()
|
||||
|
||||
def history(self) -> list[dict]:
|
||||
return self.request("GET", "/v1/history").json()
|
||||
|
||||
def restore(self, commit_id: str) -> dict:
|
||||
return self.request("POST", f"/v1/history/{commit_id}/restore", timeout=None).json()
|
||||
|
||||
def clear_history(self) -> None:
|
||||
self.request("DELETE", "/v1/history")
|
||||
|
||||
def export_sets(self) -> dict:
|
||||
return self.request("GET", "/v1/export-sets").json()
|
||||
|
||||
def put_export_sets(self, doc: dict) -> None:
|
||||
self.request("PUT", "/v1/export-sets", json=doc)
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Saved remotes: the servers this computer knows how to reach.
|
||||
|
||||
A remote is where a Konduktor server is (an address, an optional port, and a
|
||||
fallback address — typically the LAN address first and a VPN one second) and
|
||||
who to sign in as. Everything but the password is a plain preference
|
||||
(`userprefs.json`, key `remotes`); the password lives in the OS keychain
|
||||
(macOS Keychain, Windows Credential Manager) through `keyring`, never in a JSON
|
||||
file beside the app's other data.
|
||||
|
||||
This computer also has a stable `client_id`, which is how a server tells "the
|
||||
same laptop back from sleep" (renew its session silently) from "another
|
||||
computer" (offer a takeover).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
from ... import prefs
|
||||
|
||||
DEFAULT_PORT = 8765
|
||||
_PREFS_KEY = "remotes"
|
||||
_CLIENT_KEY = "remoteClientId"
|
||||
_KEYRING_SERVICE = "Konduktor"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Remote:
|
||||
id: str
|
||||
name: str
|
||||
host: str
|
||||
port: int | None = None
|
||||
fallback_host: str | None = None
|
||||
fallback_port: int | None = None
|
||||
username: str = ""
|
||||
|
||||
def addresses(self) -> list[tuple[str, str]]:
|
||||
"""`(label, base url)`, primary first — the order every connect tries.
|
||||
|
||||
Each address keeps its OWN port. The fallback once borrowed the
|
||||
primary's, so a reverse-proxied fallback (`konduktor.example.net`,
|
||||
served on 443) was tried at `:8765` because the LAN address named it.
|
||||
"""
|
||||
out = [("primary", _base(self.host, self.port))]
|
||||
if self.fallback_host:
|
||||
out.append(("fallback", _base(self.fallback_host, self.fallback_port)))
|
||||
return out
|
||||
|
||||
def public(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def _base(host: str, port: int | None) -> str:
|
||||
"""An address as typed → a base URL. A full URL (`https://…`, the way to
|
||||
reach a server behind the user's own reverse proxy) is taken exactly as
|
||||
given, port and all; anything else is plain HTTP on its port, else 8765."""
|
||||
host = host.strip()
|
||||
if host.startswith("http://") or host.startswith("https://"):
|
||||
return host.rstrip("/")
|
||||
bare, inline = split_host(host)
|
||||
if inline is not None:
|
||||
host, port = bare, port or inline
|
||||
if ":" in host and not host.startswith("["):
|
||||
host = f"[{host}]" # an IPv6 literal
|
||||
return f"http://{host}:{port or DEFAULT_PORT}"
|
||||
|
||||
|
||||
def split_host(text: str) -> tuple[str, int | None]:
|
||||
"""`"nas.local:9000"` → `("nas.local", 9000)`; a bare host keeps no port."""
|
||||
text = (text or "").strip()
|
||||
if text.startswith("http://") or text.startswith("https://"):
|
||||
return text, None
|
||||
if text.count(":") == 1:
|
||||
host, _, port = text.partition(":")
|
||||
if port.isdigit():
|
||||
return host, int(port)
|
||||
return text, None
|
||||
|
||||
|
||||
# ---- the list ------------------------------------------------------------------
|
||||
|
||||
|
||||
def remotes() -> list[Remote]:
|
||||
raw = prefs.load_prefs().get(_PREFS_KEY) or []
|
||||
out = []
|
||||
for item in raw if isinstance(raw, list) else []:
|
||||
try:
|
||||
out.append(Remote(**{k: item.get(k) for k in Remote.__dataclass_fields__ if k in item}))
|
||||
except TypeError:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def get(remote_id: str) -> Remote | None:
|
||||
return next((r for r in remotes() if r.id == remote_id), None)
|
||||
|
||||
|
||||
def save(remote: Remote) -> Remote:
|
||||
items = [r for r in remotes() if r.id != remote.id] + [remote]
|
||||
prefs.update_prefs({_PREFS_KEY: [r.public() for r in items]})
|
||||
return remote
|
||||
|
||||
|
||||
def delete(remote_id: str) -> bool:
|
||||
before = remotes()
|
||||
items = [r for r in before if r.id != remote_id]
|
||||
prefs.update_prefs({_PREFS_KEY: [r.public() for r in items]})
|
||||
forget_password(remote_id)
|
||||
return len(items) != len(before)
|
||||
|
||||
|
||||
def new_id() -> str:
|
||||
return uuid.uuid4().hex[:12]
|
||||
|
||||
|
||||
# ---- this computer ---------------------------------------------------------------
|
||||
|
||||
|
||||
def client_id() -> str:
|
||||
current = prefs.load_prefs().get(_CLIENT_KEY)
|
||||
if isinstance(current, str) and current:
|
||||
return current
|
||||
fresh = uuid.uuid4().hex
|
||||
prefs.update_prefs({_CLIENT_KEY: fresh})
|
||||
return fresh
|
||||
|
||||
|
||||
def machine_name() -> str:
|
||||
"""What another computer is told holds the library ("Ben's MacBook")."""
|
||||
try:
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
if sys.platform == "darwin":
|
||||
name = subprocess.run(["scutil", "--get", "ComputerName"], capture_output=True,
|
||||
text=True, timeout=2).stdout.strip()
|
||||
if name:
|
||||
return name
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
name = socket.gethostname()
|
||||
return name[:-6] if name.endswith(".local") else name
|
||||
|
||||
|
||||
# ---- the password ------------------------------------------------------------------
|
||||
# A seam for tests (and any machine without a keychain): `use_password_store`.
|
||||
|
||||
|
||||
class _Keyring:
|
||||
def get(self, account: str) -> str | None:
|
||||
import keyring
|
||||
|
||||
return keyring.get_password(_KEYRING_SERVICE, account)
|
||||
|
||||
def set(self, account: str, password: str) -> None:
|
||||
import keyring
|
||||
|
||||
keyring.set_password(_KEYRING_SERVICE, account, password)
|
||||
|
||||
def delete(self, account: str) -> None:
|
||||
import keyring
|
||||
from keyring.errors import PasswordDeleteError
|
||||
|
||||
try:
|
||||
keyring.delete_password(_KEYRING_SERVICE, account)
|
||||
except PasswordDeleteError:
|
||||
pass
|
||||
|
||||
|
||||
_store = _Keyring()
|
||||
|
||||
|
||||
def use_password_store(store) -> None:
|
||||
"""Replace the keychain (`get`/`set`/`delete` by account) — tests only."""
|
||||
global _store
|
||||
_store = store if store is not None else _Keyring()
|
||||
|
||||
|
||||
def _account(remote_id: str) -> str:
|
||||
return f"remote:{remote_id}"
|
||||
|
||||
|
||||
def password(remote_id: str) -> str | None:
|
||||
try:
|
||||
return _store.get(_account(remote_id))
|
||||
except Exception: # noqa: BLE001 — a locked keychain reads as "no password"
|
||||
return None
|
||||
|
||||
|
||||
def set_password(remote_id: str, value: str) -> None:
|
||||
_store.set(_account(remote_id), value)
|
||||
|
||||
|
||||
def forget_password(remote_id: str) -> None:
|
||||
try:
|
||||
_store.delete(_account(remote_id))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
@@ -0,0 +1,102 @@
|
||||
"""The server's content folder, browsed from this computer like a drive.
|
||||
|
||||
The sidebar's Files trees read folders on THIS computer (`core/folder.py`). On a
|
||||
remote library the music lives in the server's content folder, which this
|
||||
computer cannot see — so the server lists it (`/v1/folder/tracks`: tags, file
|
||||
facts, and which files the library already holds) and this module holds the
|
||||
answer as a read-only SOURCE, the shape the table, the deck and the importer
|
||||
already read.
|
||||
|
||||
Adding one of these files never uploads anything: it is already where the
|
||||
library can reach it, so it is added IN PLACE (`on_library_host`), and the
|
||||
importer skips both the copy and the copy-or-reference question.
|
||||
|
||||
Ids are the file's path ON THE SERVER — a string, never a `Path` on this side
|
||||
until the importer needs one, because a server path is not a path here (on a
|
||||
Windows laptop `Path("/music/x.mp3")` is `\\music\\x.mp3`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import AudioFacts
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServerFile:
|
||||
folder: str
|
||||
track: Track
|
||||
facts: AudioFacts
|
||||
#: The library's id for this file, when it already points at it.
|
||||
held: str | None = None
|
||||
|
||||
|
||||
class ServerFiles:
|
||||
"""Files in the content folder, as the read half of a source."""
|
||||
|
||||
#: The importer's cue that these are already on the machine holding the
|
||||
#: library: added where they are, neither copied nor uploaded.
|
||||
on_library_host = True
|
||||
|
||||
def __init__(self, adapter, path: str, files: list[ServerFile]):
|
||||
self.adapter = adapter
|
||||
self.path = path
|
||||
self._files = {f.track.id: f for f in files}
|
||||
|
||||
@classmethod
|
||||
def from_wire(cls, adapter, body: dict) -> "ServerFiles":
|
||||
folder = body["path"]
|
||||
facts = body.get("files") or {}
|
||||
held = body.get("held") or {}
|
||||
files = []
|
||||
for raw in body.get("tracks") or []:
|
||||
track = Track.model_validate(raw)
|
||||
fact = facts.get(track.id)
|
||||
if fact is None:
|
||||
continue
|
||||
files.append(ServerFile(
|
||||
folder=folder, track=track,
|
||||
facts=AudioFacts(key=track.id, size=int(fact["size"]), mtime_ns=int(fact["mtime_ns"])),
|
||||
held=held.get(track.id),
|
||||
))
|
||||
return cls(adapter, folder, files)
|
||||
|
||||
@property
|
||||
def files(self) -> dict[str, ServerFile]:
|
||||
return self._files
|
||||
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return [f.track for f in self._files.values()]
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
found = self._files.get(track_id)
|
||||
return found.track if found else None
|
||||
|
||||
def held(self, track_id: str) -> str | None:
|
||||
found = self._files.get(track_id)
|
||||
return found.held if found else None
|
||||
|
||||
def size(self, track_id: str) -> int:
|
||||
found = self._files.get(track_id)
|
||||
return found.facts.size if found else 0
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
return TrackCues(cues=[], grid_markers=[]) if track_id in self._files else None
|
||||
|
||||
def audio_facts(self, track_ids) -> dict[str, AudioFacts]:
|
||||
return {t: self._files[t].facts for t in track_ids if t in self._files}
|
||||
|
||||
def audio_path(self, track_id: str, *, progress=None) -> Path | None:
|
||||
"""A local copy (downloaded into the shared cache, like a library track)."""
|
||||
if track_id not in self._files:
|
||||
return None
|
||||
return self.adapter.folder_audio(track_id, progress=progress)
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return []
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
return None
|
||||
@@ -0,0 +1,85 @@
|
||||
"""A remote library's app-level bookkeeping — kept on the server, beside it.
|
||||
|
||||
Version history, export sets and the stems ledger belong with the library, not
|
||||
with whichever computer opened it: they are what every computer that opens it
|
||||
should see. So for a remote library these are calls to the server, and this
|
||||
computer's app-data holds none of them (`services.py` is the local half).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.adapter import NotFound
|
||||
from ...history import HistoryEntry
|
||||
from .client import RemoteClient
|
||||
|
||||
|
||||
class RemoteServices:
|
||||
remote = True
|
||||
|
||||
def __init__(self, client: RemoteClient):
|
||||
self.client = client
|
||||
|
||||
def baseline(self) -> None:
|
||||
pass # the server records its own "as I found it" version when it opens
|
||||
|
||||
def commit_save(self, adapter, outcome) -> str | None:
|
||||
# The server versioned the save itself; its commit rides on the outcome.
|
||||
return getattr(outcome, "commit", None)
|
||||
|
||||
def history(self) -> list[HistoryEntry]:
|
||||
return [HistoryEntry(**e) for e in self.client.history()]
|
||||
|
||||
def restore(self, commit_id: str) -> bool:
|
||||
try:
|
||||
self.client.restore(commit_id)
|
||||
except NotFound:
|
||||
return False
|
||||
return True
|
||||
|
||||
def clear_history(self) -> None:
|
||||
self.client.clear_history()
|
||||
|
||||
def discard(self) -> None:
|
||||
self.client.discard()
|
||||
|
||||
|
||||
class RemoteSetStore:
|
||||
"""`exports.use_store`'s store for a remote library: its sets, on the server."""
|
||||
|
||||
def __init__(self, client: RemoteClient):
|
||||
self.client = client
|
||||
|
||||
def read(self) -> dict:
|
||||
return self.client.export_sets()
|
||||
|
||||
def write(self, doc: dict) -> None:
|
||||
self.client.put_export_sets(doc)
|
||||
|
||||
|
||||
class RemotePending:
|
||||
"""`AppState.pending` for a remote library: the SERVER keeps the ledger of
|
||||
converted tracks awaiting Save (and commits, restores and recovers it
|
||||
itself), so on this computer there is nothing to commit or restore — only
|
||||
the server's summary to report, and its "blocking" to honour."""
|
||||
|
||||
items: list = []
|
||||
|
||||
def __init__(self, client: RemoteClient):
|
||||
self.client = client
|
||||
|
||||
def summary(self) -> dict:
|
||||
try:
|
||||
return self.client.stems_pending()
|
||||
except Exception: # noqa: BLE001 — out of reach: nothing known to be pending
|
||||
return {"tracks": 0, "parked": 0, "bytes": 0}
|
||||
|
||||
def blocking(self) -> bool:
|
||||
return bool(self.summary().get("tracks"))
|
||||
|
||||
def swapped(self) -> list:
|
||||
return []
|
||||
|
||||
def restore(self) -> int:
|
||||
return 0
|
||||
|
||||
def commit(self) -> dict:
|
||||
return {}
|
||||
@@ -0,0 +1,159 @@
|
||||
"""This computer's hold on a remote library's session.
|
||||
|
||||
The server lets ONE computer edit at a time (`server/session.py`); this keeps
|
||||
this computer's hold alive with a heartbeat every `HEARTBEAT_SECONDS`, and is
|
||||
the one place that knows how this computer stands:
|
||||
|
||||
connected — holding the session; edits go through
|
||||
reconnecting — a heartbeat failed to reach the server; edits still try
|
||||
(each request walks the addresses again)
|
||||
offline — several in a row failed; read-only until one gets through
|
||||
taken_over — another computer took the session; read-only, for good
|
||||
|
||||
Coming back from `reconnecting` or `offline` needs no new sign-in: the server
|
||||
renews a lapsed lease for the computer that held it, as long as nobody else
|
||||
has taken it meanwhile — and says so (423) if somebody has.
|
||||
|
||||
The heartbeat names the batch running here, so a computer asking to take over
|
||||
is told what it would cancel. Being taken over cancels it (`on_change`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from ...core.adapter import Unavailable
|
||||
from ...remote_protocol import HEARTBEAT_SECONDS
|
||||
from .client import RemoteClient, SessionLost
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: Missed heartbeats in a row before `reconnecting` becomes `offline`.
|
||||
OFFLINE_AFTER = 3
|
||||
|
||||
|
||||
class RemoteSession:
|
||||
def __init__(self, client: RemoteClient, *, batch_probe=None, interval: float = HEARTBEAT_SECONDS,
|
||||
identity: tuple[str, str] | None = None):
|
||||
self.client = client
|
||||
self.interval = interval
|
||||
self._batch_probe = batch_probe or (lambda: None)
|
||||
#: (client_id, machine) — to take the session back when the server has
|
||||
#: forgotten it (a restart) and nobody else holds it.
|
||||
self.identity = identity
|
||||
self.state = "connected"
|
||||
self.machine: str | None = None # who took it over
|
||||
#: The last thing worth telling the user that is not a state ("the
|
||||
#: server restarted"), with a counter so the UI shows each once.
|
||||
self.notice: str | None = None
|
||||
self.notices = 0
|
||||
#: Called after the session was taken back: the library must be re-read.
|
||||
self.on_reacquired = None
|
||||
self._failures = 0
|
||||
self._listeners: list = []
|
||||
self._stop = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# ---- facts ---------------------------------------------------------------------
|
||||
@property
|
||||
def writable(self) -> bool:
|
||||
return self.state in ("connected", "reconnecting")
|
||||
|
||||
@property
|
||||
def readonly_cause(self) -> str | None:
|
||||
return {"taken_over": "taken_over", "offline": "offline"}.get(self.state)
|
||||
|
||||
def describe(self) -> dict:
|
||||
return {"state": self.state, "via": self.client.via if self.state != "offline" else None,
|
||||
"machine": self.machine, "notice": self.notice, "notices": self.notices}
|
||||
|
||||
def on_change(self, listener) -> None:
|
||||
"""`listener(state)` after every change of state (from the heartbeat thread)."""
|
||||
self._listeners.append(listener)
|
||||
|
||||
# ---- running -------------------------------------------------------------------
|
||||
def start(self) -> None:
|
||||
if self._thread is None:
|
||||
self._thread = threading.Thread(target=self._run, name="konduktor-remote-heartbeat",
|
||||
daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stop.set()
|
||||
|
||||
def _run(self) -> None:
|
||||
while not self._stop.wait(self.interval):
|
||||
if self.state == "taken_over":
|
||||
return
|
||||
self.beat()
|
||||
|
||||
def beat(self) -> None:
|
||||
try:
|
||||
self.client.heartbeat(self._batch_probe())
|
||||
except SessionLost as ex:
|
||||
self.lost(ex.holder)
|
||||
return
|
||||
except Unavailable:
|
||||
self._failures += 1
|
||||
self._set("offline" if self._failures >= OFFLINE_AFTER else "reconnecting")
|
||||
return
|
||||
except Exception: # noqa: BLE001 — a bad answer is a missed beat, not a crash
|
||||
log.exception("heartbeat failed")
|
||||
self._failures += 1
|
||||
self._set("offline" if self._failures >= OFFLINE_AFTER else "reconnecting")
|
||||
return
|
||||
self._failures = 0
|
||||
self._set("connected")
|
||||
|
||||
def _take_back(self) -> bool:
|
||||
"""The server no longer knows this computer's token and nobody holds the
|
||||
session — it restarted (unsaved edits went with it, an accepted loss).
|
||||
Take the session back without asking, unless the library now holds
|
||||
someone ELSE's unsaved edits: those deserve the Save / Discard question
|
||||
that reopening asks, so then this stays read-only."""
|
||||
if self.identity is None:
|
||||
return False
|
||||
try:
|
||||
got = self.client.acquire(*self.identity)
|
||||
except Exception: # noqa: BLE001 — someone got there first, or no server
|
||||
return False
|
||||
if got.get("pending_edits"):
|
||||
self.client.release()
|
||||
return False
|
||||
if self.on_reacquired is not None:
|
||||
try:
|
||||
self.on_reacquired()
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("re-reading the library after a reconnect failed")
|
||||
self.notice = "The server restarted — any edits not yet saved there were lost"
|
||||
self.notices += 1
|
||||
self._failures = 0
|
||||
self._set("connected")
|
||||
return True
|
||||
|
||||
def lost(self, holder: dict | None) -> None:
|
||||
"""Another computer holds the session — from a heartbeat, or a command
|
||||
the server refused with 423. Nobody holding it means the server forgot
|
||||
this computer's token (a restart): take it back if that is safe."""
|
||||
if holder is None and self.state != "taken_over" and self._take_back():
|
||||
return
|
||||
self.machine = (holder or {}).get("machine")
|
||||
self._set("taken_over")
|
||||
|
||||
def reached(self) -> None:
|
||||
"""A request got through: whatever the heartbeat last saw, the server is there."""
|
||||
if self.state in ("reconnecting", "offline"):
|
||||
self._failures = 0
|
||||
self._set("connected")
|
||||
|
||||
def _set(self, state: str) -> None:
|
||||
with self._lock:
|
||||
if state == self.state:
|
||||
return
|
||||
self.state = state
|
||||
for listener in list(self._listeners):
|
||||
try:
|
||||
listener(state)
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("remote session listener failed")
|
||||
@@ -15,7 +15,7 @@ from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from ...core.adapter import InvalidCommand, NotFound, Unsupported
|
||||
from ...core.adapter import InvalidCommand, NotFound, Unsupported, local_audio_facts
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping
|
||||
@@ -131,6 +131,10 @@ class TraktorAdapter:
|
||||
with _translate():
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
with _translate():
|
||||
return self._store.move_playlist(node_id, parent_id, index)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents. The adapter resolves each id to its
|
||||
native entry kind, so callers never see Traktor's STEM/TRACK split."""
|
||||
@@ -146,6 +150,12 @@ class TraktorAdapter:
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
|
||||
with _translate():
|
||||
self._store.set_key(track_id, wheel, mode)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
with _translate():
|
||||
self._store.set_track_art(track_id, data, mime)
|
||||
@@ -173,7 +183,7 @@ class TraktorAdapter:
|
||||
return result
|
||||
|
||||
# ---- adding tracks ----------------------------------------------------
|
||||
def add_tracks(self, items: list) -> list[str]:
|
||||
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
|
||||
"""Add tracks that came from somewhere else, with their prep.
|
||||
|
||||
Two steps, and the split is the point. The store creates a bare ENTRY —
|
||||
@@ -195,6 +205,7 @@ class TraktorAdapter:
|
||||
type, so a free RGB value has nowhere to go.
|
||||
|
||||
Returns the new track ids, in the order the items were given.
|
||||
`checkpoint` is unused: nothing here is slow (Traktor analyses on load).
|
||||
"""
|
||||
added: list[str] = []
|
||||
for item in items:
|
||||
@@ -298,6 +309,10 @@ class TraktorAdapter:
|
||||
self._store.set_hotcue_type(track_id, slot, self._native_cue_type(cue_type))
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
|
||||
# Traktor colours a cue by its type (capabilities.cues.color = "none").
|
||||
raise Unsupported("Traktor colours cues by their type")
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.delete_hotcue(track_id, slot)
|
||||
@@ -372,12 +387,22 @@ class TraktorAdapter:
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
self._store.set_session_mappings(mappings)
|
||||
|
||||
def set_write_stored_paths(self, enabled: bool) -> None:
|
||||
"""OPTIONAL: write a file added through the path mapping in the
|
||||
library's STORED form (see `pathmap.stored_form`). A Konduktor server
|
||||
holding a collection made on another computer turns this on, so a
|
||||
track uploaded there is stored as that computer would have stored it."""
|
||||
self._store.set_write_stored_paths(enabled)
|
||||
|
||||
def unresolved_path_groups(self) -> list[PathGroup]:
|
||||
return self._store.unresolved_path_groups()
|
||||
|
||||
@@ -400,6 +425,12 @@ class TraktorAdapter:
|
||||
def dirty(self) -> bool:
|
||||
return self._store.dirty
|
||||
|
||||
def edit_summary(self) -> str:
|
||||
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
|
||||
tracks; added 6 hotcues") — what a server tells the next computer to
|
||||
open the library about the edits it is inheriting."""
|
||||
return self._store._edit_summary()
|
||||
|
||||
def save(self):
|
||||
outcome = self._store.save()
|
||||
self._rebuild() # save() re-parses, so every object identity changed
|
||||
|
||||
@@ -49,7 +49,9 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
# Traktor has no memory cues — every cue occupies a bank slot.
|
||||
memory_cues=False,
|
||||
types=CUE_TYPES,
|
||||
color="free",
|
||||
# Traktor colours a cue by its TYPE; the only COLOR it stores is a
|
||||
# grid marker's white companion, so there is nothing to pick.
|
||||
color="none",
|
||||
named=True,
|
||||
# A saved loop is a cue TYPE in Traktor, not a separate bank.
|
||||
loops="cue_type",
|
||||
@@ -60,7 +62,9 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
editable_fields=sorted(editable_fields),
|
||||
media_kinds=["audio", "stem"],
|
||||
removable=True,
|
||||
addable=True,
|
||||
stem_convertible=True,
|
||||
key_writable=True,
|
||||
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
|
||||
# but only on Windows, and a file added on one OS must play on both.
|
||||
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
|
||||
@@ -70,7 +74,12 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
"need a manual Import Cover Art to show up."
|
||||
),
|
||||
),
|
||||
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
|
||||
playlists=PlaylistCapabilities(
|
||||
folders=True, smart="read_only", reorder=True,
|
||||
# A playlist's entries are a plain list of PRIMARYKEYs, and Traktor
|
||||
# itself adds a track twice when asked.
|
||||
duplicates=True,
|
||||
),
|
||||
save=SaveCapabilities(
|
||||
app_name="Traktor",
|
||||
library_label="collection.nml",
|
||||
|
||||
@@ -25,7 +25,7 @@ class TraktorDriver:
|
||||
return False
|
||||
return b"<NML" in head and b"VERSION=" in head
|
||||
|
||||
def open(self, path: Path) -> TraktorAdapter:
|
||||
def open(self, path: Path, *, read_only: bool = False) -> TraktorAdapter:
|
||||
return TraktorAdapter(path)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
|
||||
@@ -106,14 +106,10 @@ class TraktorExporter:
|
||||
return WrittenLibrary(library=library)
|
||||
|
||||
def _write_playlists(self, adapter, payload: ExportPayload, moved: dict) -> None:
|
||||
"""Recreate the tree under one folder named after the export.
|
||||
|
||||
Nested under the export's own name for the same reason import nests a
|
||||
drive's playlists under the drive's name: a collection swapped onto
|
||||
another machine should say where its playlists came from.
|
||||
"""
|
||||
root = adapter.create_folder(payload.name)
|
||||
folders: dict[tuple[str, ...], str] = {(): root}
|
||||
"""Recreate the tree — at the top level, or with `payload.root_folder`
|
||||
under one folder named after the export (None = the top level)."""
|
||||
root = adapter.create_folder(payload.name) if payload.root_folder else None
|
||||
folders: dict[tuple[str, ...], str | None] = {(): root}
|
||||
|
||||
for playlist in payload.playlists:
|
||||
parent = self._folder_for(adapter, folders, tuple(playlist.folders), root)
|
||||
@@ -128,7 +124,7 @@ class TraktorExporter:
|
||||
adapter.set_playlist_entries(node_id, loose)
|
||||
|
||||
@staticmethod
|
||||
def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str) -> str:
|
||||
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]
|
||||
|
||||
@@ -7,15 +7,14 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from ...core import musical_key
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid, timebase
|
||||
from .cue_types import NATIVE_TO_CUE_TYPE
|
||||
|
||||
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
|
||||
# depending on a user preference — so the library can contain either. Parsing
|
||||
# notation is platform knowledge and belongs here, not in the UI.
|
||||
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
|
||||
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
|
||||
# depending on a user preference, and INFO@KEY also holds whatever a file's key
|
||||
# tag said ("Gm", "Amin") — so every notation is parsed (`core/musical_key`).
|
||||
_DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$")
|
||||
# "YYYY", "YYYY-MM" or "YYYY-MM-DD", optionally followed by a time (a
|
||||
# timestamp's date part is the date).
|
||||
@@ -23,23 +22,42 @@ _ISO_DATE = re.compile(r"^(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:[T ].*)?$")
|
||||
|
||||
|
||||
def parse_key(key: str | None) -> tuple[int | None, str | None]:
|
||||
"""(Camelot wheel position 1-12, mode) for a Traktor display key.
|
||||
"""(Camelot wheel position 1-12, mode) for a Traktor key string."""
|
||||
return musical_key.parse(key)
|
||||
|
||||
Open Key numbers the wheel seven semitones round from Camelot, so
|
||||
Open Key 1 == Camelot 8 (both are C major / A minor).
|
||||
"""
|
||||
if not key:
|
||||
|
||||
def musical_key_value(wheel: int, mode: str) -> int:
|
||||
"""`<MUSICAL_KEY VALUE>`: the tonic's pitch class (C = 0), plus 12 for minor
|
||||
— read off the real collection, where 12 pairs with "10m" (C minor) and 21
|
||||
with "1m" (A minor) on every entry carrying both."""
|
||||
return musical_key.pitch_class_of(wheel, mode) + (12 if mode == "minor" else 0)
|
||||
|
||||
|
||||
def _from_musical_key(value: int | None) -> tuple[int | None, str | None]:
|
||||
if value is None or not 0 <= value <= 23:
|
||||
return None, None
|
||||
k = key.strip()
|
||||
if m := _CAMELOT.match(k):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return n, "minor" if m.group(2).lower() == "a" else "major"
|
||||
if m := _OPEN_KEY.match(k):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major"
|
||||
return None, None
|
||||
mode = "minor" if value >= 12 else "major"
|
||||
return musical_key.wheel_of(value % 12, mode), mode
|
||||
|
||||
|
||||
def entry_key(e) -> tuple[str | None, int | None, str | None]:
|
||||
"""(display string, wheel, mode) for an ENTRY.
|
||||
|
||||
INFO@KEY is the text Traktor shows and writes to the file's tag; the
|
||||
analysed key itself is `<MUSICAL_KEY>`. 1,354 of the real collection's
|
||||
8,485 entries carry only the latter — analysed, with every value 0-23
|
||||
present, just never given a text — and Traktor shows a key for them, so
|
||||
they fall back to it, rendered in Open Key (Traktor's own default).
|
||||
"""
|
||||
info = e.info
|
||||
text = info.key if info else None
|
||||
wheel, mode = parse_key(text)
|
||||
if wheel is None:
|
||||
mk = e.musical_key.value_attribute if e.musical_key is not None else None
|
||||
wheel, mode = _from_musical_key(mk)
|
||||
if wheel is not None and not text:
|
||||
text = musical_key.render(wheel, mode, "open_key")
|
||||
return text, wheel, mode
|
||||
|
||||
|
||||
def iso_date(value: str | None) -> str | None:
|
||||
@@ -122,7 +140,7 @@ def to_track(e) -> Track:
|
||||
),
|
||||
key=lambda chip: chip.slot,
|
||||
)
|
||||
wheel, mode = parse_key(info.key if info else None)
|
||||
key_text, wheel, mode = entry_key(e)
|
||||
return Track(
|
||||
id=primary_key(loc) if loc else (e.title or ""),
|
||||
artist=e.artist,
|
||||
@@ -137,7 +155,7 @@ def to_track(e) -> Track:
|
||||
# Traktor's "Comment 2" is stored in INFO@RATING (stars are RANKING).
|
||||
comment2=info.rating if info else None,
|
||||
bpm=beatgrid.effective_bpm(e),
|
||||
key=info.key if info else None,
|
||||
key=key_text,
|
||||
key_wheel=wheel,
|
||||
key_mode=mode,
|
||||
rating=_rating_stars(info.ranking if info else None),
|
||||
|
||||
@@ -22,7 +22,6 @@ import copy
|
||||
import math
|
||||
import threading
|
||||
import uuid as uuidlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from traktor_nml_utils import (
|
||||
@@ -36,6 +35,7 @@ from traktor_nml_utils.models.collection import (
|
||||
Entrytype,
|
||||
GridType,
|
||||
Infotype,
|
||||
MusicalKeytype,
|
||||
Locationtype,
|
||||
Nodetype,
|
||||
Playlisttype,
|
||||
@@ -46,16 +46,17 @@ from traktor_nml_utils.models.collection import (
|
||||
)
|
||||
from xsdata.formats.dataclass.serializers import XmlSerializer
|
||||
|
||||
from ...core.adapter import InvalidCommand, SaveOutcome, StemSwapResult
|
||||
from ...core.adapter import FileTagResult, InvalidCommand, SaveOutcome, StemSwapResult
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.pathmap import common_dir_prefix
|
||||
from ...core.pathmap import PathMapping
|
||||
from ...core.pathmap import PathMapping, stored_form
|
||||
from ...core.relocate import PathGroup
|
||||
from ...core.stem_file import NML_STEMS_JSON
|
||||
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
|
||||
from ...schemas import PlaylistNode
|
||||
from . import beatgrid, timebase
|
||||
from .locations import os_path_to_location, resolve_path
|
||||
from .projection import iso_date, traktor_date
|
||||
from ...core import musical_key
|
||||
from .projection import iso_date, musical_key_value, traktor_date
|
||||
|
||||
# Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under
|
||||
# this email is what makes the stars show up in Traktor itself.
|
||||
@@ -71,15 +72,6 @@ class PlaylistError(InvalidCommand):
|
||||
"""
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileTagResult:
|
||||
track_id: str
|
||||
file: str
|
||||
ok: bool
|
||||
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
|
||||
detail: str = ""
|
||||
|
||||
|
||||
class TraktorStore:
|
||||
def __init__(self, nml_path: Path):
|
||||
self.nml_path = Path(nml_path)
|
||||
@@ -87,6 +79,9 @@ class TraktorStore:
|
||||
self.dirty = False
|
||||
# Active OS-path prefix remapping (empty = identity). Survives _load().
|
||||
self._path_mapping = PathMapping()
|
||||
# Write a file added through a mapping in the library's STORED form
|
||||
# (`pathmap.stored_form`) — a Konduktor server sets this.
|
||||
self._write_stored_paths = False
|
||||
# Mappings the user confirmed in the open-time missing-files check.
|
||||
# Session-only: never saved, re-derived on every open.
|
||||
self._session_mappings: list[PathMapping] = []
|
||||
@@ -109,6 +104,7 @@ class TraktorStore:
|
||||
self._journal = EditJournal()
|
||||
# track_id -> (image_bytes, mime) of staged replacement cover art
|
||||
self._track_art: dict[str, tuple[bytes, str]] = {}
|
||||
self._notation: str | None = None
|
||||
self.dirty = False
|
||||
|
||||
def _note(
|
||||
@@ -164,11 +160,13 @@ class TraktorStore:
|
||||
can_reorder=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
can_move=True,
|
||||
)
|
||||
if ntype == "SMARTLIST" or node.smartplaylist is not None:
|
||||
# Rule-based, so it has no static entry list to show or edit.
|
||||
return PlaylistNode(
|
||||
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart"
|
||||
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart",
|
||||
can_move=True,
|
||||
)
|
||||
path = parent_path + [name]
|
||||
return PlaylistNode(
|
||||
@@ -179,6 +177,7 @@ class TraktorStore:
|
||||
can_contain_children=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
can_move=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -352,6 +351,79 @@ class TraktorStore:
|
||||
self._note("playlist-delete", node.name)
|
||||
self.dirty = True
|
||||
|
||||
def _find_node(self, node_id: str) -> Nodetype:
|
||||
"""Any node by its id: a playlist's UUID, a folder's `fld:` path or a
|
||||
smart playlist's `sl:` path (its folder path plus its own name)."""
|
||||
if node_id.startswith("fld:"):
|
||||
return self._find_folder(node_id)
|
||||
if node_id.startswith("sl:"):
|
||||
*folders, name = node_id[len("sl:"):].split("/")
|
||||
parent = self._find_folder("fld:" + "/".join(folders) if folders else None)
|
||||
match = next(
|
||||
(c for c in self._children(parent)
|
||||
if (c.type == "SMARTLIST" or c.smartplaylist is not None) and c.name == name),
|
||||
None,
|
||||
)
|
||||
if match is None:
|
||||
raise PlaylistError(f"Smart playlist not found: {node_id}")
|
||||
return match
|
||||
node = self._find_playlist_node(node_id)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {node_id}")
|
||||
return node
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
"""Move a node to `index` among `parent_id`'s children (counted without
|
||||
it) and return its id afterwards — a folder's and a smart playlist's id
|
||||
is their path of names, so moving one changes it (and its subtree's).
|
||||
|
||||
A folder or smart playlist landing beside a namesake of its own kind is
|
||||
refused, as rename refuses it: the two paths would be one, and one of
|
||||
them unaddressable. Playlists are UUIDs, so their names may repeat."""
|
||||
with self._lock:
|
||||
node = self._find_node(node_id)
|
||||
if node is self._root():
|
||||
raise PlaylistError("Cannot move the root folder")
|
||||
dest = self._find_folder(parent_id)
|
||||
if dest is node or any(n is dest for n in self._iter_nodes(node)):
|
||||
raise PlaylistError("A folder cannot be moved into itself")
|
||||
is_folder = node.playlist is None and node.smartplaylist is None and (
|
||||
node.type or "FOLDER") == "FOLDER"
|
||||
is_smart = node.type == "SMARTLIST" or node.smartplaylist is not None
|
||||
if is_folder or is_smart:
|
||||
kind = "folder" if is_folder else "smart playlist"
|
||||
for c in self._children(dest):
|
||||
same_kind = (
|
||||
(c.type or "FOLDER") == "FOLDER" and c.playlist is None
|
||||
and c.smartplaylist is None
|
||||
) if is_folder else (c.type == "SMARTLIST" or c.smartplaylist is not None)
|
||||
if c is not node and same_kind and c.name == node.name:
|
||||
raise PlaylistError(f'There is already a {kind} called "{node.name}" there')
|
||||
source = self._find_parent_of(node)
|
||||
if source is None:
|
||||
raise PlaylistError("Cannot move a top-level node")
|
||||
siblings = [c for c in self._children(dest) if c is not node]
|
||||
index = max(0, min(int(index), len(siblings)))
|
||||
if source is dest and self._children(dest).index(node) == index:
|
||||
return self._node_id(node, parent_id) # already there
|
||||
source.subnodes.node.remove(node)
|
||||
source.subnodes.count = len(source.subnodes.node)
|
||||
if dest.subnodes is None:
|
||||
dest.subnodes = Subnodestype(node=[], count=0)
|
||||
dest.subnodes.node.insert(index, node)
|
||||
dest.subnodes.count = len(dest.subnodes.node)
|
||||
self._note("playlist-move", node.name)
|
||||
self.dirty = True
|
||||
return self._node_id(node, parent_id)
|
||||
|
||||
def _node_id(self, node: Nodetype, parent_id: str | None) -> str:
|
||||
"""The id `_to_model` gives `node` inside the folder `parent_id`."""
|
||||
if node.playlist is not None:
|
||||
return node.playlist.uuid
|
||||
prefix = parent_id[len("fld:"):] if parent_id and parent_id.startswith("fld:") else ""
|
||||
tag = "sl:" if (node.type == "SMARTLIST" or node.smartplaylist is not None) else "fld:"
|
||||
return tag + "/".join(p for p in (prefix, node.name or "(unnamed)") if p)
|
||||
|
||||
def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
@@ -409,6 +481,69 @@ class TraktorStore:
|
||||
self._journal.record("track", "set", track_id, k)
|
||||
self.dirty = True
|
||||
|
||||
# ---- musical key ----------------------------------------------------
|
||||
def _collection_notation(self) -> str | None:
|
||||
"""The notation this collection's INFO@KEY values are written in — a
|
||||
Traktor preference (Open Key / Camelot / musical) the NML does not
|
||||
record, so it is read off the keys themselves; the majority wins. None
|
||||
when the collection holds no keys — never cached, since adding entries
|
||||
to an empty collection (an export) is exactly when it changes. Once
|
||||
known it is kept for the session: every key Konduktor writes is in it,
|
||||
so it can only move if one could out-vote thousands."""
|
||||
from collections import Counter
|
||||
|
||||
if self._notation is not None:
|
||||
return self._notation
|
||||
seen = Counter(
|
||||
musical_key.notation_of(e.info.key)
|
||||
for e in self._nml.collection.entry
|
||||
if e.info is not None and e.info.key
|
||||
)
|
||||
seen.pop(None, None)
|
||||
self._notation = seen.most_common(1)[0][0] if seen else None
|
||||
return self._notation
|
||||
|
||||
def key_notation(self) -> str:
|
||||
"""`_collection_notation`, or Open Key (Traktor's default) when there
|
||||
are no keys to go by. A key in another notation would display fine but
|
||||
read as foreign beside its neighbours."""
|
||||
return self._collection_notation() or "open_key"
|
||||
|
||||
def _added_key_text(self, track) -> str | None:
|
||||
"""INFO@KEY for an entry `add_entry` creates: rendered from the wheel in
|
||||
this collection's notation, never copied — a Pioneer source says "Abm",
|
||||
which reads as foreign beside "9m". A collection with no keys yet (an
|
||||
export's fresh skeleton) takes a Traktor-native source's own notation,
|
||||
so Traktor -> Traktor keeps the user's (the export decision). Text that
|
||||
names no key is kept as it was: dropping it would lose information."""
|
||||
text = getattr(track, "key", None) or None
|
||||
wheel, mode = getattr(track, "key_wheel", None), getattr(track, "key_mode", None)
|
||||
if not (wheel and mode):
|
||||
return text
|
||||
notation = self._collection_notation()
|
||||
if notation is None:
|
||||
own = musical_key.notation_of(text)
|
||||
notation = own if own in ("open_key", "camelot") else "open_key"
|
||||
return musical_key.render(wheel, mode, notation)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> None:
|
||||
"""Set a track's key as Traktor's analysis writes one: the display
|
||||
text in INFO@KEY (in the collection's notation; also what reaches the
|
||||
file's tag at Save) AND the analysed value in `<MUSICAL_KEY>`."""
|
||||
if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"):
|
||||
raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}")
|
||||
with self._lock:
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None:
|
||||
raise PlaylistError(f"Track not found: {track_id}")
|
||||
if entry.info is None:
|
||||
entry.info = Infotype()
|
||||
before = entry.info.key
|
||||
entry.info.key = musical_key.render(wheel, mode, self.key_notation())
|
||||
entry.musical_key = MusicalKeytype(value_attribute=musical_key_value(wheel, mode))
|
||||
self._journal.record("track", "set", track_id, "key", before, entry.info.key)
|
||||
self.dirty = True
|
||||
|
||||
# ---- adding tracks --------------------------------------------------
|
||||
def add_entry(self, track, audio_path: Path) -> str:
|
||||
"""Append a brand-new ENTRY for `audio_path` and return its track id.
|
||||
@@ -429,9 +564,16 @@ class TraktorStore:
|
||||
and ``loudness``. Both are outputs of Traktor's own analysis and cannot
|
||||
be computed here; Traktor re-analyses a track that has none. Writing a
|
||||
plausible-looking fingerprint would be inventing data.
|
||||
|
||||
A stem FILE gets ``<STEMS>``, rendered from its own ``stem`` box as
|
||||
Traktor renders it: that element is what makes the entry a stem track
|
||||
(its playlist keys ``TYPE="STEM"``, the Type column), and without it a
|
||||
stem file added here read as plain audio.
|
||||
"""
|
||||
# Read before the lock: it opens the file.
|
||||
stems = nml_stems_for(audio_path)
|
||||
with self._lock:
|
||||
volume, dir_, file = os_path_to_location(Path(audio_path))
|
||||
volume, dir_, file = os_path_to_location(self._stored(Path(audio_path)))
|
||||
key = f"{volume}{dir_}{file}"
|
||||
if key in self._entry_by_key:
|
||||
raise PlaylistError(
|
||||
@@ -446,7 +588,7 @@ class TraktorStore:
|
||||
remixer=getattr(track, "remixer", None) or None,
|
||||
producer=getattr(track, "producer", None) or None,
|
||||
mix=getattr(track, "mix", None) or None,
|
||||
key=getattr(track, "key", None) or None,
|
||||
key=self._added_key_text(track),
|
||||
bitrate=getattr(track, "bitrate", None) or None,
|
||||
playcount=getattr(track, "playcount", None) or None,
|
||||
# The generic model carries ISO dates; Traktor writes "YYYY/M/D".
|
||||
@@ -472,7 +614,14 @@ class TraktorStore:
|
||||
# projected BPM so a track with no grid still shows a tempo;
|
||||
# `replace_grid` overwrites it from the markers when they land.
|
||||
tempo=Tempotype(bpm=float(bpm)) if bpm else None,
|
||||
# The analysed key, as Traktor's own analysis stores it.
|
||||
musical_key=(
|
||||
MusicalKeytype(value_attribute=musical_key_value(track.key_wheel, track.key_mode))
|
||||
if getattr(track, "key_wheel", None) and getattr(track, "key_mode", None)
|
||||
else None
|
||||
),
|
||||
cue_v2=[],
|
||||
stems=Stemstype(stems=stems) if stems else None,
|
||||
)
|
||||
self._nml.collection.entry.append(entry)
|
||||
self._entry_by_key[key] = entry
|
||||
@@ -990,6 +1139,15 @@ class TraktorStore:
|
||||
with self._lock:
|
||||
self._path_mapping = mapping
|
||||
|
||||
def set_write_stored_paths(self, enabled: bool) -> None:
|
||||
self._write_stored_paths = bool(enabled)
|
||||
|
||||
def _stored(self, os_path: Path) -> Path:
|
||||
"""Where a NEW entry points, as the collection stores paths."""
|
||||
if not self._write_stored_paths:
|
||||
return Path(os_path)
|
||||
return stored_form(Path(os_path), [self._path_mapping, *self._session_mappings])
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
"""Set the mappings confirmed for this session (applied at resolve time)."""
|
||||
with self._lock:
|
||||
@@ -1285,7 +1443,7 @@ class TraktorStore:
|
||||
if swap.mode not in ("repoint", "add"):
|
||||
raise PlaylistError(f"Unknown stem swap mode: {swap.mode}")
|
||||
seen_ids.add(swap.track_id)
|
||||
loc = os_path_to_location(Path(swap.stem_path))
|
||||
loc = os_path_to_location(self._stored(Path(swap.stem_path)))
|
||||
new_key = "".join(x or "" for x in loc)
|
||||
if new_key in self._entry_by_key or new_key in new_keys:
|
||||
raise PlaylistError(
|
||||
|
||||
+111
-24
@@ -28,11 +28,12 @@ import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
|
||||
from . import adapters, library_id, prefs # noqa: F401 — registers adapters
|
||||
from .core import registry
|
||||
from .core.adapter import LibraryAdapter
|
||||
from .core.pathmap import PathMapping
|
||||
from .relocation import RelocationCheck
|
||||
from .services import LibraryServices, LocalServices
|
||||
|
||||
|
||||
class AppState:
|
||||
@@ -57,6 +58,22 @@ class AppState:
|
||||
# the middle of another would commit a half-applied state; reentrant so
|
||||
# one of them may call another.
|
||||
self.mutation = threading.RLock()
|
||||
# Converted-to-stem tracks awaiting Save or Discard (see stems/pending.py),
|
||||
# and what the last open's crash recovery did about any left over.
|
||||
self.pending = None
|
||||
self.recovery: dict | None = None
|
||||
# Where this library's history (and, for a remote, its export sets and
|
||||
# ledger) are kept — see `services.py`.
|
||||
self.services: LibraryServices | None = None
|
||||
# The open remote's connection (`adapters/remote/session.py`), or None
|
||||
# for a library on this computer.
|
||||
self.remote = None
|
||||
# …and the saved remote it was opened through (`adapters/remote/config.py`).
|
||||
self.remote_config = None
|
||||
# Called with the adapter at the end of every open (and so after a
|
||||
# restore, which reopens): how a Konduktor SERVER re-applies the path
|
||||
# mapping its configuration names, which lives in no prefs file.
|
||||
self.open_hooks: list = []
|
||||
|
||||
@property
|
||||
def loaded(self) -> bool:
|
||||
@@ -75,7 +92,7 @@ class AppState:
|
||||
rests on, and an adapter is the thing that knows whether it is true —
|
||||
so it is asserted here rather than assumed everywhere else.
|
||||
"""
|
||||
adapter = registry.open_library(path)
|
||||
adapter = registry.open_library(path, read_only=True)
|
||||
if adapter.capabilities().writable:
|
||||
if hasattr(adapter, "close"):
|
||||
try:
|
||||
@@ -83,7 +100,7 @@ class AppState:
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
raise ValueError(
|
||||
f"{path} is a writable library; only read-only sources "
|
||||
f"{path} cannot be opened read-only; only a library that can "
|
||||
"(such as a OneLibrary drive) can be opened as a source"
|
||||
)
|
||||
self.close_source()
|
||||
@@ -116,21 +133,13 @@ class AppState:
|
||||
# write-ahead log beside a file another process replaces is how a SQLite
|
||||
# library gets corrupted. Only close once the new one has parsed, so a
|
||||
# failed open leaves the current library intact.
|
||||
previous = self.adapter
|
||||
if previous is not None and hasattr(previous, "close"):
|
||||
try:
|
||||
previous.close()
|
||||
except Exception: # noqa: BLE001 — a failed close must not block the open
|
||||
pass
|
||||
self._release_previous()
|
||||
# Apply this library's saved OS-path remapping (per-machine, keyed by the
|
||||
# library's local path) so runtime translation is live on open.
|
||||
saved = prefs.get_path_mapping(str(path))
|
||||
if saved:
|
||||
adapter.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
|
||||
self.path, self.adapter = path, adapter
|
||||
# Started after the saved mapping is applied, so a volume that mapping
|
||||
# already fixes is not asked about.
|
||||
self.relocation = RelocationCheck(adapter)
|
||||
caps = adapter.capabilities()
|
||||
# No sidecar beside a removable library: writing to a user's USB stick to
|
||||
# satisfy Konduktor's own bookkeeping is not a trade worth making. Those
|
||||
@@ -144,9 +153,67 @@ class AppState:
|
||||
label=Path(str(path)).name,
|
||||
sidecar=not getattr(driver, "removable", False),
|
||||
)
|
||||
# Version history: record an "as I found it" baseline (deduped, so
|
||||
# re-opening an unchanged library is a no-op). Best-effort.
|
||||
history.ensure_baseline(path)
|
||||
# A crash may have left converted tracks mid-lifecycle: settle them from
|
||||
# what the SAVED library says, BEFORE the missing-files check — a parked
|
||||
# original is exactly what that check would report as missing.
|
||||
from .stems.pending import Pending
|
||||
|
||||
self.pending = Pending(self.library_id)
|
||||
self.recovery = None
|
||||
if self.pending.items:
|
||||
self.recovery = self.pending.recover(lambda item: adapter.track(item["new_id"]) is not None)
|
||||
# Started after the saved mapping is applied, so a volume that mapping
|
||||
# already fixes is not asked about.
|
||||
self.relocation = RelocationCheck(adapter)
|
||||
self.services = LocalServices(path)
|
||||
self.services.baseline()
|
||||
for hook in self.open_hooks:
|
||||
hook(adapter)
|
||||
|
||||
def _release_previous(self) -> None:
|
||||
previous = self.adapter
|
||||
# Leaving a library discards its unsaved edits (the UI has confirmed), so
|
||||
# a stem conversion's parked originals go back under their own names.
|
||||
if self.pending is not None and self.pending.items:
|
||||
self.pending.restore()
|
||||
if previous is not None and hasattr(previous, "close"):
|
||||
try:
|
||||
previous.close()
|
||||
except Exception: # noqa: BLE001 — a failed close must not block the open
|
||||
pass
|
||||
if self.remote is not None and self.library_id:
|
||||
# A remote library's export sets were the server's; stop asking it.
|
||||
from . import exports
|
||||
|
||||
exports.use_store(self.library_id, None)
|
||||
self.adapter = None
|
||||
self.remote = None
|
||||
self.remote_config = None
|
||||
|
||||
def open_remote(self, opened) -> None:
|
||||
"""Make an already-connected remote library THE library.
|
||||
|
||||
`opened` is what `adapters.remote.open_remote` returns: the adapter, its
|
||||
services and session, and the server's identity for the library. The
|
||||
connection (handshake, version check, session) is made BEFORE this, so
|
||||
a refusal leaves the current library intact, as a failed parse does.
|
||||
"""
|
||||
with self.mutation:
|
||||
self._release_previous()
|
||||
self.path = opened.path
|
||||
self.adapter = opened.adapter
|
||||
self.services = opened.services
|
||||
self.remote = opened.session
|
||||
self.remote_config = opened.remote
|
||||
# The server's id for the library: export sets are keyed by it, and
|
||||
# they live on the server too, so every computer sees the same ones.
|
||||
self.library_id = opened.library_id
|
||||
# The server keeps its own ledger of converted tracks; nothing of a
|
||||
# remote library's lives in this computer's.
|
||||
self.pending = opened.pending
|
||||
self.recovery = None
|
||||
# A remote library's files are not on this computer's drives.
|
||||
self.relocation = None
|
||||
|
||||
def save(self):
|
||||
"""Write the library, then record the saved bytes in version history.
|
||||
@@ -161,15 +228,16 @@ class AppState:
|
||||
|
||||
def _save(self):
|
||||
outcome = self.adapter.save()
|
||||
# Not every platform is versioned. A library that is more than one file
|
||||
# has no single blob that IS the library, and it says so through its
|
||||
# capabilities rather than this module knowing which platforms those are.
|
||||
versioned = self.adapter.capabilities().save.history
|
||||
commit = None
|
||||
if versioned and outcome.snapshot is not None:
|
||||
commit = history.commit(
|
||||
self.path, outcome.snapshot, outcome.summary, __version__
|
||||
)
|
||||
commit = self.services.commit_save(self.adapter, outcome)
|
||||
# The swap is now on disk: what it replaced can go. After the library
|
||||
# write, so a failed save deletes nothing; here rather than in the save
|
||||
# route, because import and path remap save too.
|
||||
if self.pending is not None and self.pending.swapped():
|
||||
renames = self.pending.commit()
|
||||
if renames and self.library_id:
|
||||
from . import exports
|
||||
|
||||
exports.retarget(self.library_id, renames)
|
||||
return outcome, commit
|
||||
|
||||
def discard(self) -> None:
|
||||
@@ -181,8 +249,27 @@ class AppState:
|
||||
"""
|
||||
assert self.adapter is not None
|
||||
with self.mutation:
|
||||
if self.pending is not None and self.pending.items:
|
||||
self.pending.restore()
|
||||
if self.services is not None and self.services.remote:
|
||||
# The server holds the edits; it is what drops them.
|
||||
self.services.discard()
|
||||
self.adapter.reload()
|
||||
|
||||
def restore_version(self, commit_id: str) -> bool:
|
||||
"""Write a past version back as a new save and re-read the library.
|
||||
False when the version is unknown."""
|
||||
assert self.adapter is not None and self.services is not None
|
||||
with self.mutation:
|
||||
if not self.services.restore(commit_id):
|
||||
return False
|
||||
if self.services.remote:
|
||||
# The server reopened its own library; follow it.
|
||||
self.adapter.reload()
|
||||
else:
|
||||
self._open(self.path) # rebuild read + edit models from the restored file
|
||||
return True
|
||||
|
||||
|
||||
STATE = AppState()
|
||||
|
||||
|
||||
@@ -28,6 +28,21 @@ from .pathmap import PathMapping
|
||||
from .relocate import PathGroup
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileTagResult:
|
||||
"""One audio-file tag write a save made — the `SaveOutcome.tag_results` item.
|
||||
|
||||
Promoted from the Traktor store when OneLibrary became the second platform
|
||||
that writes edited fields into the audio files themselves.
|
||||
"""
|
||||
|
||||
track_id: str
|
||||
file: str
|
||||
ok: bool
|
||||
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
|
||||
detail: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class SaveOutcome:
|
||||
"""What a save produced, in terms every platform can answer.
|
||||
@@ -50,6 +65,60 @@ class SaveOutcome:
|
||||
tag_results: list = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AudioFacts:
|
||||
"""One track's audio file as its library's host sees it — WITHOUT reading it.
|
||||
|
||||
`key` is the file's path on the machine that holds it (a string, because on
|
||||
a remote library that is not this machine), `size` and `mtime_ns` its stat.
|
||||
Together they name one version of one file: what an export's manifest
|
||||
records, what the analysis cache keys on, and how a downloaded copy is
|
||||
recognised. Callers that only need a file's IDENTITY ask for these rather
|
||||
than `audio_path`, which on a remote library means downloading it.
|
||||
"""
|
||||
|
||||
key: str
|
||||
size: int
|
||||
mtime_ns: int
|
||||
|
||||
|
||||
def local_audio_facts(adapter, track_ids) -> dict[str, AudioFacts]:
|
||||
"""`audio_facts` for a library whose files are on this machine: stat each
|
||||
`audio_path`. A track whose file is missing is left out."""
|
||||
out: dict[str, AudioFacts] = {}
|
||||
for track_id in track_ids:
|
||||
try:
|
||||
path = adapter.audio_path(track_id)
|
||||
if path is None:
|
||||
continue
|
||||
st = Path(path).stat()
|
||||
except (OSError, AdapterError):
|
||||
continue
|
||||
if not Path(path).is_file():
|
||||
continue
|
||||
out[track_id] = AudioFacts(key=str(path), size=st.st_size, mtime_ns=st.st_mtime_ns)
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class PreparedAnalysis:
|
||||
"""What adding a track would otherwise decode the file to learn.
|
||||
|
||||
A platform that must ANALYSE what it adds (Rekordbox: the waveform and grid
|
||||
live in its ANLZ files) decodes each file in `add_tracks`. When the library
|
||||
lives on a server that never decodes audio, the client does that work on
|
||||
its own copy and the result travels with the track. `measured` is a
|
||||
`core.waveform.Analysis` measured with the file's own time-base lead,
|
||||
`markers` the detected grid (empty: none found) and `key` the detected
|
||||
`core.key_detect.KeyResult` (None: not asked for, or none found). Absent,
|
||||
the adapter decodes as before.
|
||||
"""
|
||||
|
||||
measured: object
|
||||
markers: list = field(default_factory=list)
|
||||
key: object | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class NewTrack:
|
||||
"""A track to ADD to a library, described generically.
|
||||
@@ -73,6 +142,14 @@ class NewTrack:
|
||||
track: Track
|
||||
audio_path: Path
|
||||
cues: TrackCues | None = None
|
||||
# The cover as the SOURCE library shows it — `(bytes, mime)` from its
|
||||
# `cover_art` — since a library's art is not always embedded in the file.
|
||||
# For a platform that keeps its own copy of the art (Rekordbox); one that
|
||||
# reads the file's tags (Traktor) ignores it.
|
||||
art: tuple[bytes, str] | None = None
|
||||
# Precomputed analysis for a platform that would otherwise decode the file
|
||||
# (see `PreparedAnalysis`); ignored by one that does not analyse.
|
||||
analysis: PreparedAnalysis | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -133,6 +210,11 @@ class Unsupported(AdapterError):
|
||||
"""The platform cannot represent this edit at all."""
|
||||
|
||||
|
||||
class Unavailable(AdapterError):
|
||||
"""The library's host cannot be reached, or no longer lets this computer
|
||||
write (a library held by a server, taken over by another computer)."""
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class LibraryAdapter(Protocol):
|
||||
"""One open library. Stateful; exactly one is loaded at a time."""
|
||||
@@ -152,6 +234,7 @@ class LibraryAdapter(Protocol):
|
||||
def facets(self) -> Facets: ...
|
||||
def stats(self, playlist_count: int) -> Stats: ...
|
||||
def playlist_tree(self) -> list[PlaylistNode]: ...
|
||||
def playlist_count(self) -> int: ...
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None: ...
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None: ...
|
||||
def track_cues(self, track_id: str) -> TrackCues | None: ...
|
||||
@@ -164,6 +247,12 @@ class LibraryAdapter(Protocol):
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str: ...
|
||||
def rename_playlist(self, node_id: str, name: str) -> None: ...
|
||||
def delete_playlist(self, node_id: str) -> None: ...
|
||||
# Move a node (playlist, folder or smart playlist) to `index` among
|
||||
# `parent_id`'s children (None = the top level), counted with the moved
|
||||
# node left out. Returns the node's id AFTER the move: an id is opaque, and
|
||||
# on a platform that addresses a folder by its path it changes. A folder
|
||||
# cannot go into itself or a descendant (InvalidCommand).
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: ...
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ...
|
||||
|
||||
# ---- commands: adding tracks ----------------------------------------
|
||||
@@ -173,12 +262,25 @@ class LibraryAdapter(Protocol):
|
||||
# fidelity guarantee hold. A new entry has no parsed original, so the rule
|
||||
# becomes "an added entry must not perturb any existing one" — which is
|
||||
# what `test_save_fidelity.py` checks rather than taking on trust.
|
||||
def add_tracks(self, items: list["NewTrack"]) -> list[str]: ...
|
||||
#
|
||||
# `checkpoint(message, step, of)` is called before each slow step (a
|
||||
# platform that must ANALYSE what it adds, like Rekordbox, decodes every
|
||||
# file) and may raise to cancel; it is only ever called before the library
|
||||
# is touched, so a cancel leaves it as it was. Gated on
|
||||
# `capabilities().tracks.addable`.
|
||||
def add_tracks(self, items: list["NewTrack"], *, checkpoint=None) -> list[str]: ...
|
||||
# OPTIONAL, where `capabilities().tracks.places_audio`: the library decides
|
||||
# where added audio goes. `place_audio(source, track)` returns the path the
|
||||
# importer must COPY `source` to (which becomes `NewTrack.audio_path`), or
|
||||
# None when the file is already where the library can use it in place;
|
||||
# `audio_home()` is where that audio lands, for the free-space check.
|
||||
# (A protocol member would make every adapter implement them.)
|
||||
|
||||
# Remove tracks from the library — and so from every playlist, since an
|
||||
# entry naming a track the library no longer has is a dangling reference.
|
||||
# Never touches audio files. Returns how many were removed; gated on
|
||||
# `capabilities().tracks.removable`.
|
||||
# Never touches audio files, except where `tracks.places_audio` (a stick's
|
||||
# audio belongs to its library): there the file goes too, at Save. Returns
|
||||
# how many were removed; gated on `capabilities().tracks.removable`.
|
||||
def remove_tracks(self, track_ids: list[str]) -> int: ...
|
||||
|
||||
# Swap converted stem files into the library (see `StemSwap`), all at once:
|
||||
@@ -190,6 +292,10 @@ class LibraryAdapter(Protocol):
|
||||
|
||||
# ---- commands: track metadata / art ---------------------------------
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ...
|
||||
# The musical key, as a Camelot wheel position (1-12) + mode — what key
|
||||
# analysis writes. Each platform renders it in its own notation (and its own
|
||||
# analysed-key field, where it has one). Gated on `tracks.key_writable`.
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None: ...
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ...
|
||||
|
||||
@@ -206,6 +312,9 @@ class LibraryAdapter(Protocol):
|
||||
name: str | None = None,
|
||||
) -> TrackCues: ...
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues: ...
|
||||
# `color` is "#RRGGBB" from `capabilities().cues.palette`, or None for the
|
||||
# platform's uncoloured cue. Any other cue command keeps a slot's colour.
|
||||
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 place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
|
||||
|
||||
@@ -220,7 +329,12 @@ class LibraryAdapter(Protocol):
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: ...
|
||||
|
||||
# ---- audio / paths ---------------------------------------------------
|
||||
# A READABLE file on this machine — which, for a library held by a server,
|
||||
# means downloading it. Anything that only needs to know WHICH file a track
|
||||
# is (an export plan, "is this already in the library?") asks `audio_facts`
|
||||
# instead, which never reads the file and never downloads.
|
||||
def audio_path(self, track_id: str) -> Path | None: ...
|
||||
def audio_facts(self, track_ids: list[str]) -> dict[str, AudioFacts]: ...
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None: ...
|
||||
# The open-time missing-files check (`core/relocate.py`): the stored volumes
|
||||
# in which NO track resolves, and the mappings the user confirmed for them —
|
||||
@@ -260,7 +374,11 @@ class LibraryDriver(Protocol):
|
||||
selects: str
|
||||
|
||||
def can_open(self, path: Path) -> bool: ...
|
||||
def open(self, path: Path) -> LibraryAdapter: ...
|
||||
# `read_only` opens a library only to READ it, alongside the loaded one (the
|
||||
# sidebar's Devices). An adapter that honours it reports `writable=False`
|
||||
# with cause `browsing`; one that ignores it still reports writable, and the
|
||||
# caller — `AppState.open_source` — refuses it, so ignoring is safe.
|
||||
def open(self, path: Path, *, read_only: bool = False) -> LibraryAdapter: ...
|
||||
# OPTIONAL. What to call an opened library on screen. Only the adapter can
|
||||
# answer for a platform where one library has more than one valid path —
|
||||
# the filename is otherwise assumed, and that assumption is wrong for a
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""The analysis a platform that ANALYSES what it adds needs for one new track.
|
||||
|
||||
Rekordbox draws a new track's waveform and grid from its ANLZ files, so adding a
|
||||
track means decoding it once: the waveform measured on the platform's own clock
|
||||
(`lead`, read from the file's header by that platform) plus a detected grid and
|
||||
key when the track brings none. One definition, used both by the adapter (a library on
|
||||
this computer) and by the client of a library held by a server — which never
|
||||
decodes audio, so the client measures its own copy and sends the result
|
||||
(`PreparedAnalysis`) with the track.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from .adapter import PreparedAnalysis
|
||||
from .model import GridMarker
|
||||
|
||||
|
||||
def prepare(path: Path, *, lead: float, detect: bool = True,
|
||||
detect_key: bool = False) -> PreparedAnalysis:
|
||||
"""Decode `path` once: its waveform at `lead`, and (with `detect`) a grid,
|
||||
(with `detect_key`) a key."""
|
||||
from . import grid_detect, waveform
|
||||
|
||||
samples = waveform.decode(Path(path))
|
||||
measured = waveform.analyse_samples(samples, lead=lead)
|
||||
markers: list[GridMarker] = []
|
||||
if detect and samples is not None:
|
||||
try:
|
||||
found = grid_detect.detect_grid(str(path), y=samples, sr=waveform.SR)
|
||||
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
|
||||
except ValueError:
|
||||
pass # no pulse to fit (a one-shot, silence): no grid
|
||||
key = None
|
||||
if detect_key and samples is not None:
|
||||
from . import key_detect
|
||||
|
||||
try:
|
||||
key = key_detect.detect_key_samples(samples, waveform.SR)
|
||||
except Exception: # noqa: BLE001 - a missing key is not worth failing an add over
|
||||
logging.getLogger(__name__).warning("key detection failed", exc_info=True)
|
||||
return PreparedAnalysis(measured=measured, markers=markers, key=key)
|
||||
|
||||
|
||||
def with_key(track, key):
|
||||
"""`track` (a generic `Track`) with the detected `key` if it has none of its
|
||||
own. A key the track already carries (its tags, its source library) is
|
||||
never second-guessed."""
|
||||
if key is None or getattr(track, "key_wheel", None) is not None:
|
||||
return track
|
||||
return track.model_copy(update={"key": key.name, "key_wheel": key.wheel, "key_mode": key.mode})
|
||||
@@ -22,7 +22,10 @@ DEFAULT_POPM_EMAIL = "no@email"
|
||||
# The safe, editable metadata we sync to files (the adapter's editable field set).
|
||||
# rating is 0–5 stars.
|
||||
TagMeta = dict # keys: title, artist, album, genre, label, remixer, producer,
|
||||
# comment, mix, release_date, rating
|
||||
# comment, mix, release_date, rating, key
|
||||
# `key` is written as the library holds it ("9m", "Abm") into the frame DJ
|
||||
# software reads: ID3 TKEY, MP4/FLAC `initialkey` — where Traktor writes its
|
||||
# own (every key-tagged file on the dev machine has it there).
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -170,6 +173,7 @@ def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None
|
||||
TDRC,
|
||||
TIT2,
|
||||
TIT3,
|
||||
TKEY,
|
||||
TPE1,
|
||||
TPE4,
|
||||
TPUB,
|
||||
@@ -185,6 +189,7 @@ def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None
|
||||
"remixer": TPE4,
|
||||
"mix": TIT3,
|
||||
"release_date": TDRC,
|
||||
"key": TKEY,
|
||||
}
|
||||
for field, frame in simple.items():
|
||||
if field in meta:
|
||||
@@ -262,7 +267,8 @@ def _write_mp4(path: Path, meta: TagMeta) -> None:
|
||||
else:
|
||||
t[atom] = [val]
|
||||
# No standard MP4 atoms for these — use iTunes-style freeform atoms.
|
||||
freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX"}
|
||||
freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX",
|
||||
"key": "initialkey"}
|
||||
for field, name in freeform.items():
|
||||
if field in meta:
|
||||
key = f"----:com.apple.iTunes:{name}"
|
||||
@@ -297,6 +303,7 @@ def _write_flac(path: Path, meta: TagMeta) -> None:
|
||||
"comment": "comment",
|
||||
"mix": "mixname",
|
||||
"release_date": "date",
|
||||
"key": "initialkey",
|
||||
}
|
||||
for field, vc in mapping.items():
|
||||
if field in meta:
|
||||
|
||||
@@ -22,7 +22,15 @@ from pydantic import BaseModel
|
||||
# permanent refusal protecting their other machines.
|
||||
# `not_in_library` is a folder of loose files being browsed: nothing there is a
|
||||
# library to write to, and the way to edit one is to add it to the collection.
|
||||
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library"]
|
||||
# `browsing` is an editable library opened only to READ alongside the loaded one
|
||||
# (a OneLibrary stick in the sidebar's Devices): the way to edit it is to open it
|
||||
# as THE library, which one SaveBar and one dirty state can then follow.
|
||||
# `taken_over` is a library held by a server that another computer has taken
|
||||
# over; `offline` one whose server cannot be reached. Both are temporary, and
|
||||
# both mean "nothing you do here can be saved" until the session is back.
|
||||
ReadonlyCause = Literal[
|
||||
"platform_incomplete", "cloud_synced", "not_in_library", "browsing", "taken_over", "offline",
|
||||
]
|
||||
|
||||
CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
|
||||
CueRole = Literal["hotcue", "memory"]
|
||||
@@ -61,23 +69,53 @@ class TrackCapabilities(BaseModel):
|
||||
editable_fields: list[str] = []
|
||||
media_kinds: list[MediaKind] = ["audio"]
|
||||
# Tracks can be removed from the library (and so from its playlists). The
|
||||
# audio file is never touched either way.
|
||||
# audio file is never touched — except where `places_audio`: a library that
|
||||
# owns where its audio lives (a stick) deletes it with the track, at Save.
|
||||
removable: bool = False
|
||||
# Tracks can be added to the library (`add_tracks`): an import from a
|
||||
# device, or browsed files added to the collection.
|
||||
addable: bool = False
|
||||
# The LIBRARY decides where added audio goes (`place_audio`), so the user is
|
||||
# neither asked "copy or leave in place?" nor for a destination: a OneLibrary
|
||||
# stick can only point at files on itself, and lays them out as rekordbox
|
||||
# does. False: the user chooses, as for a desktop collection.
|
||||
places_audio: bool = False
|
||||
# Tracks can be converted to native-instruments STEM files, which this
|
||||
# platform plays as stems (`apply_stem_swaps`).
|
||||
stem_convertible: bool = False
|
||||
# The musical key can be set (`set_key`) — what key analysis writes. Not
|
||||
# in `editable_fields`: a key is a wheel position, not free text.
|
||||
key_writable: bool = False
|
||||
# The audio files this library can hold, as lower-case suffixes. What a
|
||||
# browsed folder offers to add — a file the library would refuse, or that
|
||||
# the DJ app cannot play, is not worth listing as addable.
|
||||
audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"]
|
||||
artwork: bool = False
|
||||
artwork_note: str | None = None
|
||||
# Whose filesystem an import destination is on. "host": this computer's,
|
||||
# browsed with the ordinary file browser. "library": the machine that holds
|
||||
# the library (a server), whose folders are listed through the library —
|
||||
# added audio is UPLOADED there.
|
||||
audio_destination: Literal["host", "library"] = "host"
|
||||
# Whether added files can be left where they are ("reference") rather than
|
||||
# copied. False where the library cannot see this computer's files at all.
|
||||
reference: bool = True
|
||||
|
||||
|
||||
class PlaylistCapabilities(BaseModel):
|
||||
folders: bool = False
|
||||
smart: Literal["none", "read_only"] = "none"
|
||||
reorder: bool = False
|
||||
# A playlist can hold the same track more than once. Where it cannot, a
|
||||
# drop of tracks already there skips them rather than asking.
|
||||
duplicates: bool = False
|
||||
|
||||
|
||||
class PathCapabilities(BaseModel):
|
||||
# Path mapping, path rewriting and the open-time missing-files check apply.
|
||||
# False for a library held by a server: its mapping is the server's own
|
||||
# configuration, and this computer's drives are not where its files are.
|
||||
remappable: bool = True
|
||||
|
||||
|
||||
class SaveCapabilities(BaseModel):
|
||||
@@ -92,6 +130,9 @@ class SaveCapabilities(BaseModel):
|
||||
library_label: str
|
||||
overwrite_risk: Literal["none", "on_exit", "while_running"] = "none"
|
||||
history: bool = True
|
||||
# The library was written by one of Konduktor's EXPORT sets, whose next run
|
||||
# replaces it — so an edit made here directly is undone by the next export.
|
||||
managed_by_export: bool = False
|
||||
|
||||
|
||||
class Capabilities(BaseModel):
|
||||
@@ -111,4 +152,5 @@ class Capabilities(BaseModel):
|
||||
grid: GridCapabilities = GridCapabilities()
|
||||
tracks: TrackCapabilities = TrackCapabilities()
|
||||
playlists: PlaylistCapabilities = PlaylistCapabilities()
|
||||
paths: PathCapabilities = PathCapabilities()
|
||||
save: SaveCapabilities
|
||||
@@ -94,8 +94,14 @@ class ExportPayload:
|
||||
|
||||
tracks: list[ExportTrack] = field(default_factory=list)
|
||||
playlists: list[ExportPlaylist] = field(default_factory=list)
|
||||
#: The export's name, used for the folder its playlists are nested under.
|
||||
#: The export's name, used for the folder its playlists are nested under
|
||||
#: when `root_folder` is set.
|
||||
name: str = "Export"
|
||||
#: Nest the whole playlist tree (and "Other") in one folder named `name`.
|
||||
#: Off — the default, a Konduktor setting — the playlists sit at the
|
||||
#: library's top level: an export is a library of its own, so a folder
|
||||
#: saying where it came from is one more click at the gig.
|
||||
root_folder: bool = False
|
||||
#: Called by a writer before each slow step (e.g. decoding a track for its
|
||||
#: waveform) with a message for the status bar, and — for a per-track loop —
|
||||
#: `step` of `of`, which drives the progress bar. RAISES when the user has
|
||||
|
||||
@@ -31,6 +31,7 @@ from pathlib import Path
|
||||
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
|
||||
from .model import PlaylistNode, Track, TrackCues
|
||||
from .places import is_hidden
|
||||
from .stem_file import is_stem_file
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -59,7 +60,8 @@ def _bpm(tags) -> float | None:
|
||||
|
||||
def read_track(path: Path) -> Track:
|
||||
"""Project one audio file. Never raises: an unreadable tag is an untitled track."""
|
||||
track = Track(id=str(path), title=path.stem, filepath=str(path))
|
||||
track = Track(id=str(path), title=path.stem, filepath=str(path),
|
||||
media_kind="stem" if is_stem_file(path) else "audio")
|
||||
try:
|
||||
import mutagen
|
||||
|
||||
@@ -112,7 +114,7 @@ def capabilities_for(folder: Path) -> Capabilities:
|
||||
platform="folder",
|
||||
writable=False,
|
||||
readonly_cause="not_in_library",
|
||||
tracks=TrackCapabilities(editable_fields=[], artwork=False),
|
||||
tracks=TrackCapabilities(editable_fields=[], artwork=False, media_kinds=["audio", "stem"]),
|
||||
save=SaveCapabilities(
|
||||
app_name="Files",
|
||||
library_label=folder.name or str(folder),
|
||||
@@ -148,6 +150,11 @@ class FolderSource:
|
||||
def audio_path(self, track_id: str) -> Path | None:
|
||||
return Path(track_id) if track_id in self._by_id else None
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
from .adapter import local_audio_facts
|
||||
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return []
|
||||
|
||||
|
||||
@@ -213,12 +213,27 @@ def detect_grid(
|
||||
*,
|
||||
y: np.ndarray | None = None,
|
||||
sr: int = _SR,
|
||||
bpm: float | None = None,
|
||||
anchor: float | None = None,
|
||||
) -> GridResult:
|
||||
"""Detect a track's constant tempo and first beat.
|
||||
|
||||
``y``/``sr`` let a caller (or a test) pass decoded mono audio directly.
|
||||
Raises ``ValueError`` when there is no pulse to fit (silence, a one-shot).
|
||||
|
||||
Either half can be held fixed — the Analyze dialog's BPM and Grid ticks:
|
||||
- ``bpm`` given ("Grid" alone): that tempo is KEPT — no search, no
|
||||
round-BPM snap — and only where its beats fall is found. For a BPM the
|
||||
user trusts (typed, or a store's) and a grid that sits off the beat.
|
||||
- ``anchor`` given ("BPM" alone): the tempo is detected and the anchor
|
||||
returned as given, so the grid's downbeat stays where the user put it.
|
||||
``drift_ms`` is then measured against THAT anchor: large means the kept
|
||||
anchor does not sit on the detected beat.
|
||||
"""
|
||||
if bpm is not None and anchor is not None:
|
||||
raise ValueError("Hold the BPM or the anchor, not both — there would be nothing to detect")
|
||||
if bpm is not None and not (20.0 <= bpm <= 400.0):
|
||||
raise ValueError(f"Not a usable BPM: {bpm}")
|
||||
if y is None:
|
||||
import librosa
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
@@ -227,10 +242,42 @@ def detect_grid(
|
||||
if duration < 1.5:
|
||||
raise ValueError("Track is too short to detect a tempo")
|
||||
|
||||
lo, hi = bpm_range
|
||||
low = _onset(_band_env(y, sr, 30.0, 150.0))
|
||||
mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3))
|
||||
attack = _onset(_band_env(y, sr, _ATTACK_LO_HZ, _ATTACK_HI_HZ, smooth_ms=3))
|
||||
|
||||
if bpm is not None:
|
||||
period = 60.0 / bpm
|
||||
if not np.isfinite(attack).all() or attack.max() <= 0:
|
||||
raise ValueError("No onsets found")
|
||||
phase = _phase(low, attack, period)
|
||||
return GridResult(
|
||||
bpm=float(bpm),
|
||||
anchor=round(_first_beat(low + attack, phase, period), 4),
|
||||
duration=duration,
|
||||
drift_ms=round(_drift(attack, bpm, phase) * 1000.0, 1),
|
||||
)
|
||||
|
||||
found_bpm, phase, drift = _detect_tempo(y, sr, low, attack, bpm_range, duration)
|
||||
period = 60.0 / found_bpm
|
||||
if anchor is not None:
|
||||
return GridResult(
|
||||
bpm=round(found_bpm, 4),
|
||||
anchor=float(anchor),
|
||||
duration=duration,
|
||||
drift_ms=round(_drift(attack, found_bpm, float(anchor) % period) * 1000.0, 1),
|
||||
)
|
||||
return GridResult(
|
||||
bpm=round(found_bpm, 4),
|
||||
anchor=round(_first_beat(low + attack, phase, period), 4),
|
||||
duration=duration,
|
||||
drift_ms=round(drift * 1000.0, 1),
|
||||
)
|
||||
|
||||
|
||||
def _detect_tempo(y, sr, low, attack, bpm_range, duration) -> tuple[float, float, float]:
|
||||
"""(bpm, phase, drift) — the tempo search, octave rule and round snap."""
|
||||
lo, hi = bpm_range
|
||||
mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3))
|
||||
full = _onset(_band_env(y, sr, None, None, smooth_ms=3))
|
||||
o_tempo = low + mid + 0.5 * full
|
||||
if not np.isfinite(o_tempo).all() or o_tempo.max() <= 0:
|
||||
@@ -260,15 +307,7 @@ def detect_grid(
|
||||
bpm, _ = _refine(o_t, bpm, 0.02, 0.001)
|
||||
phase = _phase(low, attack, 60.0 / bpm)
|
||||
drift = _drift(attack, bpm, phase)
|
||||
bpm, phase, drift = _snap_round(low, attack, bpm, phase, drift, duration)
|
||||
|
||||
period = 60.0 / bpm
|
||||
return GridResult(
|
||||
bpm=round(bpm, 4),
|
||||
anchor=round(_first_beat(low + attack, phase, period), 4),
|
||||
duration=duration,
|
||||
drift_ms=round(drift * 1000.0, 1),
|
||||
)
|
||||
return _snap_round(low, attack, bpm, phase, drift, duration)
|
||||
|
||||
|
||||
def _peaks(f: np.ndarray, k: int, min_sep: int) -> list[int]:
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Marker-level beatgrid commands, for a store whose one primitive is "replace".
|
||||
|
||||
A platform that stores the grid as a flat list of beats (Rekordbox's `PQTZ`, and
|
||||
so OneLibrary's) has no native "move this marker": every marker-level command is
|
||||
a read-modify-replace of the generic marker list. Promoted here when OneLibrary
|
||||
became the second store needing exactly that, so "where does a moved marker
|
||||
clamp" cannot mean two things. (Traktor's store has markers natively and keeps
|
||||
its own, companion-cue-aware versions.)
|
||||
|
||||
A store using it provides `current_markers(track_id)` and
|
||||
`replace_grid(track_id, markers)`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .adapter import InvalidCommand, NotFound
|
||||
from .model import GridMarker
|
||||
|
||||
|
||||
class ReplaceGridCommands:
|
||||
def current_markers(self, track_id: str) -> list[GridMarker]: # pragma: no cover
|
||||
raise NotImplementedError
|
||||
|
||||
def replace_grid(self, track_id: str, markers: list[GridMarker]) -> None: # pragma: no cover
|
||||
raise NotImplementedError
|
||||
|
||||
def delete_grid(self, track_id: str) -> None:
|
||||
self.replace_grid(track_id, [])
|
||||
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
|
||||
markers = self.current_markers(track_id)
|
||||
if bpm is None:
|
||||
# Inherit the tempo governing this point, like Traktor's add does.
|
||||
governing = [m for m in markers if m.start <= start_sec]
|
||||
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
|
||||
if not bpm:
|
||||
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
|
||||
if any(abs(m.start - start_sec) < 0.001 for m in markers):
|
||||
raise InvalidCommand("There is already a marker here")
|
||||
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
|
||||
markers = self.current_markers(track_id)
|
||||
if not 0 <= index < len(markers):
|
||||
raise NotFound(f"No grid marker {index}")
|
||||
return markers, index
|
||||
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
# Clamp between neighbours so the list cannot reorder under the caller.
|
||||
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
|
||||
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
|
||||
target = max(low, float(start_sec))
|
||||
if high is not None:
|
||||
target = min(target, high)
|
||||
markers[i] = markers[i].model_copy(update={"start": target})
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
if bpm <= 0:
|
||||
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
|
||||
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
del markers[i]
|
||||
self.replace_grid(track_id, markers)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""What an analysis does to one track's grid, given the BPM / Grid ticks.
|
||||
|
||||
One pure function, so the batch, the dialog's counts and the tests cannot come
|
||||
to mean different things. Decided with the user (2026-10-04, see
|
||||
`.claude/discussions/discuss-key-analysis-2026-10-04.md`):
|
||||
|
||||
- BPM + Grid: a full analysis. A track that already has a grid is replaced
|
||||
only when the user ticked "Replace" — a grid may hold hand edits.
|
||||
- BPM alone: re-detect the tempo, KEEP the anchor (the first marker).
|
||||
- Grid alone: KEEP the BPM, find only where the beats fall.
|
||||
- With one tick, adjusting the existing grid is the point, so "Replace" does
|
||||
not apply; a track with nothing to keep (no grid / no BPM) is analysed in
|
||||
full rather than skipped — one tick never leaves a track worse off.
|
||||
- A multi-marker (flexible) grid is skipped by BPM alone and Grid alone: its
|
||||
tempo changes are exactly what one constant tempo would flatten.
|
||||
- A locked grid is skipped whatever is ticked.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal, Sequence
|
||||
|
||||
Action = Literal["none", "full", "bpm", "phase", "skip"]
|
||||
SkipReason = Literal["locked", "existing", "flexible"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GridStep:
|
||||
action: Action
|
||||
reason: SkipReason | None = None
|
||||
hold_bpm: float | None = None # "phase": the tempo kept
|
||||
hold_anchor: float | None = None # "bpm": the anchor kept (seconds)
|
||||
|
||||
|
||||
def plan_grid(
|
||||
*,
|
||||
bpm: bool,
|
||||
grid: bool,
|
||||
markers: Sequence, # the track's grid markers (`.start`, `.bpm`), any order
|
||||
track_bpm: float | None,
|
||||
locked: bool,
|
||||
replace_existing: bool,
|
||||
) -> GridStep:
|
||||
if not (bpm or grid):
|
||||
return GridStep("none")
|
||||
if locked:
|
||||
return GridStep("skip", "locked")
|
||||
ordered = sorted(markers, key=lambda m: m.start)
|
||||
if bpm and grid:
|
||||
if ordered and not replace_existing:
|
||||
return GridStep("skip", "existing")
|
||||
return GridStep("full")
|
||||
if len(ordered) > 1:
|
||||
return GridStep("skip", "flexible")
|
||||
if bpm: # BPM alone
|
||||
if not ordered:
|
||||
return GridStep("full")
|
||||
return GridStep("bpm", hold_anchor=float(ordered[0].start))
|
||||
# Grid alone
|
||||
held = float(ordered[0].bpm) if ordered else (float(track_bpm) if track_bpm else None)
|
||||
if not held or held <= 0:
|
||||
return GridStep("full")
|
||||
return GridStep("phase", hold_bpm=held)
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Musical key detection: a small convolutional network, run in numpy.
|
||||
|
||||
Why a network and not key profiles. The classic method — fold the spectrum
|
||||
into a 12-bin chroma vector and correlate it with a major / minor template —
|
||||
was benchmarked first on GiantSteps (604 Beatport previews, keys corrected by
|
||||
hand), over Krumhansl, Temperley, Sha'ath (KeyFinder) and Faraldo's EDM
|
||||
templates and every combination of octave range, compression and harmonic
|
||||
filtering tried: the best got 49.5% exactly right. A template sees only how
|
||||
much of each pitch class there is; a network also sees WHERE in pitch it is
|
||||
(the bass line, the pad, the lead) and learns from data what states a key.
|
||||
|
||||
The model follows Korzeniowski & Widmer, "End-to-end musical key estimation
|
||||
using a convolutional neural network" (EUSIPCO 2017): five 5x5 convolutions,
|
||||
then a per-frame dense layer over the whole pitch axis — a key is NOT
|
||||
pitch-invariant, so nothing pools over frequency — then 24 logits averaged
|
||||
over the track. ~76 k weights per network; `key_model.npz` holds an ensemble
|
||||
of three (logits averaged), trained by `backend/train_key_model.py` on the
|
||||
SEPARATE GiantSteps MTG dataset. torch is used only to train: the backend
|
||||
never imports it.
|
||||
|
||||
Measured (`bench_key_detect.py`, 2026-10-04): GiantSteps 69.4% exact, 83.4%
|
||||
harmonically mixable (exact, a fifth, or the relative key), MIREX 0.758 —
|
||||
about the published figure for this design. Against the key tags of 47 local
|
||||
files (Traktor's analysis, not ground truth) it agrees on 62%, 77% mixable.
|
||||
`confidence` tracks correctness (82% exact above 0.7, ~40% below 0.4) but even
|
||||
a low one is ten times better than chance, so a key is always returned for
|
||||
music; only silence and clips under 5 s get None.
|
||||
|
||||
Cost on a 6.7-minute track: CQT 0.1 s, the three networks 0.5 s — beside the
|
||||
decode, which the grid analysis shares.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import numpy as np
|
||||
|
||||
from . import musical_key
|
||||
|
||||
SR = 22050
|
||||
HOP = 4096 # ~5.4 frames/s: key is a slow property
|
||||
BINS_PER_OCTAVE = 36 # three per semitone, so a detuned track still lands in one
|
||||
FMIN_NOTE = "C1"
|
||||
OCTAVES = 7 # C1..C8: the input window plus room to pitch-shift it
|
||||
# The network's input: C2..C7 (65 Hz - 2.1 kHz), where bass lines, pads and
|
||||
# leads state the key. The octave either side is only there so training can
|
||||
# shift the window by up to six semitones.
|
||||
WINDOW = (36, 216)
|
||||
|
||||
_MODEL = Path(__file__).with_name("key_model.npz")
|
||||
_TIME_CHUNK = 256 # frames per im2col block: bounds memory to tens of MB
|
||||
|
||||
PITCH_NAMES = musical_key.SPELLING
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class KeyResult:
|
||||
pitch_class: int # tonic, 0 = C
|
||||
mode: Literal["major", "minor"]
|
||||
wheel: int # Camelot position 1-12, the generic model's key
|
||||
confidence: float # the network's probability for this key, 0-1
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return PITCH_NAMES[self.pitch_class] + ("m" if self.mode == "minor" else "")
|
||||
|
||||
|
||||
def camelot_wheel(pitch_class: int, mode: str) -> int:
|
||||
"""Camelot position: C major = 8B, A minor = 8A; one step = a fifth."""
|
||||
return musical_key.wheel_of(pitch_class, mode)
|
||||
|
||||
|
||||
def features(y: np.ndarray, sr: int = SR) -> np.ndarray:
|
||||
"""Log-magnitude constant-Q spectrogram, (OCTAVES * 36, frames), float32.
|
||||
|
||||
Normalised to the track's own loudest bin, so a quiet master and a loud
|
||||
one give the same picture. Training calls this same function."""
|
||||
import librosa
|
||||
|
||||
if sr != SR:
|
||||
y = librosa.resample(y, orig_sr=sr, target_sr=SR)
|
||||
C = np.abs(librosa.cqt(
|
||||
y, sr=SR, hop_length=HOP, fmin=librosa.note_to_hz(FMIN_NOTE),
|
||||
n_bins=OCTAVES * BINS_PER_OCTAVE, bins_per_octave=BINS_PER_OCTAVE, tuning=0.0,
|
||||
))
|
||||
peak = float(C.max()) or 1.0
|
||||
return np.log1p(1000.0 * C / peak).astype(np.float32)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _members() -> list[dict[str, np.ndarray]]:
|
||||
"""The ensemble: `key_model.npz` holds N networks as `m<i>.<param>`, plus
|
||||
`pool` (frequency bins averaged before the dense layer; 1 = none)."""
|
||||
with np.load(_MODEL) as z:
|
||||
flat = {k: z[k] for k in z.files}
|
||||
pool = int(flat.pop("pool"))
|
||||
members: dict[int, dict[str, np.ndarray]] = {}
|
||||
for k, v in flat.items():
|
||||
i, name = k.split(".", 1)
|
||||
members.setdefault(int(i[1:]), {})[name] = v.astype(np.float32)
|
||||
for m in members.values():
|
||||
m["pool"] = np.array(pool)
|
||||
return [members[i] for i in sorted(members)]
|
||||
|
||||
|
||||
def _elu(x: np.ndarray) -> np.ndarray:
|
||||
return np.where(x > 0, x, np.expm1(np.minimum(x, 0)))
|
||||
|
||||
|
||||
def _conv5(x: np.ndarray, w: np.ndarray, b: np.ndarray) -> np.ndarray:
|
||||
"""'same' 5x5 convolution (cross-correlation, as torch's Conv2d).
|
||||
x: (cin, F, T), w: (cout, cin, 5, 5) -> (cout, F, T)."""
|
||||
cin, f, t = x.shape
|
||||
xp = np.pad(x, ((0, 0), (2, 2), (2, 2)))
|
||||
out = np.empty((w.shape[0], f, t), np.float32)
|
||||
for t0 in range(0, t, _TIME_CHUNK):
|
||||
t1 = min(t, t0 + _TIME_CHUNK)
|
||||
view = np.lib.stride_tricks.sliding_window_view(xp[:, :, t0:t1 + 4], (5, 5), axis=(1, 2))
|
||||
out[:, :, t0:t1] = np.tensordot(w, view, axes=([1, 2, 3], [0, 3, 4]))
|
||||
return out + b[:, None, None]
|
||||
|
||||
|
||||
def _network(x: np.ndarray, w: dict[str, np.ndarray]) -> np.ndarray:
|
||||
"""One member's 24 logits, averaged over time. x: (1, F, T)."""
|
||||
n = sum(1 for k in w if k.startswith("conv") and k.endswith(".weight"))
|
||||
for i in range(n):
|
||||
x = _elu(_conv5(x, w[f"conv{i}.weight"], w[f"conv{i}.bias"]))
|
||||
pool = int(w["pool"]) # average within a semitone
|
||||
if pool > 1:
|
||||
f = x.shape[1] // pool * pool
|
||||
x = x[:, :f].reshape(x.shape[0], f // pool, pool, -1).mean(axis=2)
|
||||
dw = w["dense.weight"][..., 0] # (hid, ch, F)
|
||||
h = _elu(np.tensordot(dw, x, axes=([1, 2], [0, 1])) + w["dense.bias"][:, None])
|
||||
out = w["out.weight"][:, :, 0, 0] @ h + w["out.bias"][:, None] # (24, T)
|
||||
return out.mean(axis=1)
|
||||
|
||||
|
||||
def logits(spec: np.ndarray) -> np.ndarray:
|
||||
"""The ensemble's 24 logits — major C..B, then minor C..B — for a
|
||||
`features()` spectrogram: each member's, averaged."""
|
||||
x = spec[WINDOW[0]:WINDOW[1]][None]
|
||||
return np.mean([_network(x, w) for w in _members()], axis=0)
|
||||
|
||||
|
||||
def detect_key_samples(y: np.ndarray, sr: int) -> KeyResult | None:
|
||||
"""The key of decoded mono audio, or None for silence / too short to say."""
|
||||
if y.size < sr * 5 or not np.any(y):
|
||||
return None
|
||||
z = logits(features(y, sr)).astype(np.float64)
|
||||
p = np.exp(z - z.max())
|
||||
p /= p.sum()
|
||||
k = int(np.argmax(p))
|
||||
pc, mode = k % 12, ("minor" if k >= 12 else "major")
|
||||
return KeyResult(pc, mode, camelot_wheel(pc, mode), float(p[k]))
|
||||
|
||||
|
||||
def with_detected_key(track, y: np.ndarray | None, sr: int):
|
||||
"""`track` (a generic `Track`) with a detected key if it has none of its
|
||||
own — for a file being ADDED, which is decoded anyway. A key the track
|
||||
already carries (its tags, its source library) is never second-guessed,
|
||||
and a detection failure leaves the track as it was: a missing key is not
|
||||
worth failing an add over."""
|
||||
if getattr(track, "key_wheel", None) is not None or y is None:
|
||||
return track
|
||||
try:
|
||||
found = detect_key_samples(y, sr)
|
||||
except Exception: # noqa: BLE001
|
||||
import logging
|
||||
|
||||
logging.getLogger(__name__).warning("key detection failed", exc_info=True)
|
||||
return track
|
||||
if found is None:
|
||||
return track
|
||||
return track.model_copy(update={"key": found.name, "key_wheel": found.wheel, "key_mode": found.mode})
|
||||
|
||||
|
||||
def detect_key(audio_path: str) -> KeyResult | None:
|
||||
import librosa
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=SR, mono=True)
|
||||
return detect_key_samples(y, sr)
|
||||
Binary file not shown.
@@ -130,6 +130,9 @@ class PlaylistNode(BaseModel):
|
||||
can_rename: bool = False
|
||||
can_delete: bool = False
|
||||
can_contain_children: bool = False # a valid parent for a new playlist
|
||||
# Can be dragged elsewhere in the tree (`move_playlist`): reordered among
|
||||
# its siblings or moved into another folder.
|
||||
can_move: bool = False
|
||||
|
||||
|
||||
PlaylistNode.model_rebuild()
|
||||
@@ -194,6 +197,9 @@ class LibraryInfo(BaseModel):
|
||||
path: str
|
||||
display_name: str # short label for the status bar
|
||||
version: str | None = None
|
||||
# Set when the library is held by a server: {id, name, via} of the saved
|
||||
# remote it was opened through. None for a library on this computer.
|
||||
remote: dict | None = None
|
||||
|
||||
|
||||
class PlatformOption(BaseModel):
|
||||
@@ -208,7 +214,7 @@ class PlatformOption(BaseModel):
|
||||
platform: str
|
||||
name: str
|
||||
library_label: str
|
||||
selects: Literal["file", "directory"] = "file"
|
||||
selects: Literal["file", "directory", "remote"] = "file"
|
||||
installed: bool = False
|
||||
#: How many libraries this platform has right now; `installed` is `found > 0`.
|
||||
found: int = 0
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Musical keys: the generic form and the notations DJ software writes.
|
||||
|
||||
The generic model carries a key as a Camelot wheel position (1-12) plus a mode
|
||||
(`Track.key_wheel` / `key_mode`); one step round the wheel is a fifth, and the
|
||||
minor key on a number is the relative of the major one. Each platform STORES a
|
||||
key in its own notation, and a library also holds whatever another tool put
|
||||
there — a rekordbox stick's key table carries "12A" beside "Abm" when tracks
|
||||
arrived with Camelot tags. So parsing accepts every notation, and rendering is
|
||||
always explicit about which one it writes.
|
||||
|
||||
Notations:
|
||||
- "camelot": 8A / 8B (Mixed In Key's wheel; A = minor)
|
||||
- "open_key": 1m / 1d (Traktor's default; Open Key 1 = Camelot 8)
|
||||
- "musical": Am / C, with rekordbox's spelling: flats for Db Eb Ab Bb, and
|
||||
F# — measured from the key rows rekordbox 7 itself created (Abm, Dbm, Ebm,
|
||||
Eb; the six-sharp key was not among them).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Literal
|
||||
|
||||
Mode = Literal["major", "minor"]
|
||||
Notation = Literal["camelot", "open_key", "musical"]
|
||||
|
||||
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
|
||||
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
|
||||
_MUSICAL = re.compile(r"^([A-G])\s*([#b♯♭]?)\s*(m|min|minor|maj|major)?$", re.I)
|
||||
|
||||
_PITCH = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
|
||||
SPELLING = ("C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B")
|
||||
|
||||
|
||||
def wheel_of(pitch_class: int, mode: Mode) -> int:
|
||||
"""Camelot position of a tonic: C major = 8B, A minor = 8A."""
|
||||
return (((7 * pitch_class) % 12 + (7 if mode == "major" else 4)) % 12) + 1
|
||||
|
||||
|
||||
def pitch_class_of(wheel: int, mode: Mode) -> int:
|
||||
"""The tonic (0 = C) at a Camelot position — `wheel_of`'s inverse."""
|
||||
return (7 * ((wheel - 1) - (7 if mode == "major" else 4))) % 12
|
||||
|
||||
|
||||
def parse(text: str | None) -> tuple[int | None, Mode | None]:
|
||||
"""(wheel, mode) for a key in any notation; (None, None) if unreadable.
|
||||
|
||||
A bare number-and-letter is ambiguous only in principle: Camelot uses A/B
|
||||
and Open Key m/d, so the letter says which."""
|
||||
if not text:
|
||||
return None, None
|
||||
s = text.strip()
|
||||
if m := _CAMELOT.match(s):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return n, "minor" if m.group(2).lower() == "a" else "major"
|
||||
return None, None
|
||||
if m := _OPEN_KEY.match(s):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major"
|
||||
return None, None
|
||||
if m := _MUSICAL.match(s):
|
||||
letter, accidental, quality = m.group(1).upper(), m.group(2), (m.group(3) or "")
|
||||
pc = _PITCH[letter] + {"#": 1, "♯": 1, "b": -1, "♭": -1}.get(accidental, 0)
|
||||
# "m" alone is minor; "maj"/"major" major; "min"/"minor" minor.
|
||||
q = quality.lower()
|
||||
mode: Mode = "minor" if q in ("m", "min", "minor") else "major"
|
||||
return wheel_of(pc % 12, mode), mode
|
||||
return None, None
|
||||
|
||||
|
||||
def render(wheel: int | None, mode: str | None, notation: Notation) -> str | None:
|
||||
"""A key in `notation`, or None when the position is unknown — a made-up
|
||||
key is worse than a blank one."""
|
||||
if not wheel or not (1 <= wheel <= 12) or mode not in ("major", "minor"):
|
||||
return None
|
||||
if notation == "camelot":
|
||||
return f"{wheel}{'A' if mode == 'minor' else 'B'}"
|
||||
if notation == "open_key":
|
||||
return f"{((wheel + 4) % 12) + 1}{'m' if mode == 'minor' else 'd'}"
|
||||
return SPELLING[pitch_class_of(wheel, mode)] + ("m" if mode == "minor" else "")
|
||||
|
||||
|
||||
def notation_of(text: str | None) -> Notation | None:
|
||||
"""Which notation a stored key string is written in."""
|
||||
if not text:
|
||||
return None
|
||||
s = text.strip()
|
||||
if _CAMELOT.match(s):
|
||||
return "camelot"
|
||||
if _OPEN_KEY.match(s):
|
||||
return "open_key"
|
||||
if _MUSICAL.match(s):
|
||||
return "musical"
|
||||
return None
|
||||
@@ -54,6 +54,10 @@ class PathMapping:
|
||||
return True
|
||||
return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/")
|
||||
|
||||
def inverted(self) -> "PathMapping":
|
||||
"""The mapping back: a path HERE → the form the library stores."""
|
||||
return PathMapping(self.to_prefix, self.from_prefix)
|
||||
|
||||
def apply(self, os_path: Path) -> Path:
|
||||
"""Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the
|
||||
path unchanged when it doesn't match (non-matching tracks untouched)."""
|
||||
@@ -81,3 +85,21 @@ def common_dir_prefix(paths: list[str]) -> str:
|
||||
else:
|
||||
break
|
||||
return "/".join(common)
|
||||
|
||||
|
||||
def stored_form(os_path: Path, mappings) -> Path:
|
||||
"""`os_path` as the library STORES its paths, when it sits under where one
|
||||
of `mappings` points (the first that does).
|
||||
|
||||
A library opened through a mapping (a server holding a collection made on
|
||||
another computer) stores every path in the other computer's form. A file
|
||||
added through that mapping is written in the same form, so the library
|
||||
keeps ONE convention — and still opens, mapping and all, where it was made.
|
||||
"""
|
||||
for mapping in mappings:
|
||||
if mapping is None or mapping.empty:
|
||||
continue
|
||||
back = mapping.inverted()
|
||||
if back.matches(os_path):
|
||||
return back.apply(os_path)
|
||||
return os_path
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Opening a file for reading with PyAV, on every PyAV version the app ships.
|
||||
|
||||
A file whose tags are not valid UTF-8 must still open: it is still audio.
|
||||
PyAV 18 decodes tags strictly by default and raises UnicodeDecodeError at open
|
||||
unless given `metadata_errors="ignore"`; PyAV 19 REMOVED that keyword (passing
|
||||
it is a TypeError) and opens such a file as it is, the bad bytes as surrogates.
|
||||
Measured on both with a generated M4A and MP3 whose title is invalid UTF-8.
|
||||
|
||||
The keyword once went straight into `av.open`, which worked on the dev venv's
|
||||
18.1 while CI's fresh install took 19.0.1: every stem file then failed to open
|
||||
in the released app, and the deck played stem tracks as the mix. Every read
|
||||
goes through `open_input`, so the difference lives in one place.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@cache
|
||||
def _takes_metadata_errors() -> bool:
|
||||
import av
|
||||
|
||||
return int(av.__version__.split(".")[0]) < 19
|
||||
|
||||
|
||||
def open_input(path: Path | str):
|
||||
"""`av.open(path)` for reading, tolerant of tags that are not UTF-8."""
|
||||
import av
|
||||
|
||||
if _takes_metadata_errors():
|
||||
return av.open(str(path), metadata_errors="ignore")
|
||||
return av.open(str(path))
|
||||
@@ -105,6 +105,8 @@ class TrackIndex:
|
||||
if (t.artist and ql in t.artist.lower())
|
||||
or (t.title and ql in t.title.lower())
|
||||
or (t.album and ql in t.album.lower())
|
||||
or (t.comment and ql in t.comment.lower())
|
||||
or (t.comment2 and ql in t.comment2.lower())
|
||||
]
|
||||
if genre:
|
||||
items = [t for t in items if t.genre == genre]
|
||||
|
||||
@@ -44,8 +44,8 @@ def driver_for(path: Path) -> LibraryDriver:
|
||||
raise LibraryNotSupported(f"No DJ library Konduktor recognises at {path}")
|
||||
|
||||
|
||||
def open_library(path: Path):
|
||||
return driver_for(path).open(path)
|
||||
def open_library(path: Path, *, read_only: bool = False):
|
||||
return driver_for(path).open(path, read_only=read_only)
|
||||
|
||||
|
||||
def describe(path: Path) -> dict:
|
||||
|
||||
@@ -36,6 +36,7 @@ Things that were measured and are easy to get wrong:
|
||||
from __future__ import annotations
|
||||
|
||||
import fractions
|
||||
import json
|
||||
import struct
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
@@ -44,7 +45,7 @@ from typing import Callable
|
||||
|
||||
import numpy as np
|
||||
|
||||
from . import mp4_edit, tag_copy
|
||||
from . import mp4_edit, pyav, tag_copy
|
||||
|
||||
SR = 44100
|
||||
FRAME = 1024 # AAC-LC frame size, for both encoders
|
||||
@@ -131,7 +132,7 @@ def decode(path: Path | str) -> Source:
|
||||
"""Decode the first audio stream to stereo float32 at 44.1 kHz."""
|
||||
import av
|
||||
|
||||
with av.open(str(path), metadata_errors="ignore") as container:
|
||||
with pyav.open_input(path) as container:
|
||||
stream = container.streams.audio[0]
|
||||
codec = stream.codec_context.name
|
||||
bit_rate = stream.bit_rate or container.bit_rate or None
|
||||
@@ -347,8 +348,130 @@ def is_stem_file(path: Path | str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def stem_layout(path: Path | str) -> list[dict] | None:
|
||||
"""The stems a file carries, for PLAYBACK: `[{"name", "color"}]` in stream
|
||||
order (stream k+1 is stem k), or None when the file is not a playable stem
|
||||
file — no `stem` box, a box that does not parse, or fewer audio streams than
|
||||
it names. Read from the FILE, never from the library's `<STEMS>`: 105 plain
|
||||
MP3 entries in the real collection carry that element."""
|
||||
import json
|
||||
|
||||
path = Path(path)
|
||||
try:
|
||||
raw = read_stem_box(path)
|
||||
if raw is None:
|
||||
return None # not a stem file: nothing to count, no decoder needed
|
||||
stems = json.loads(raw).get("stems") or []
|
||||
streams = _audio_stream_count(path)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
if not stems or streams < 1 + len(stems):
|
||||
return None
|
||||
return [{"name": str(s.get("name") or f"Stem {i + 1}"), "color": str(s.get("color") or "#FFFFFF")}
|
||||
for i, s in enumerate(stems)]
|
||||
|
||||
|
||||
def _audio_stream_count(path: Path) -> int:
|
||||
"""How many audio streams an MP4 holds. Through PyAV where it is installed;
|
||||
otherwise (the Konduktor SERVER ships without it — it never decodes) by
|
||||
counting the `trak`s whose handler is `soun`, which is what PyAV counts."""
|
||||
try:
|
||||
import av
|
||||
except ImportError:
|
||||
av = None
|
||||
if av is not None:
|
||||
try:
|
||||
with pyav.open_input(path) as c:
|
||||
return len(c.streams.audio)
|
||||
except av.FFmpegError as ex:
|
||||
raise ValueError(str(ex))
|
||||
size = path.stat().st_size
|
||||
count = 0
|
||||
with open(path, "rb") as f:
|
||||
moov = _find(f, 0, size, b"moov")
|
||||
if moov is None:
|
||||
return 0
|
||||
for kind, body, end in mp4_edit._boxes(f, moov[1], moov[2]):
|
||||
if kind != b"trak":
|
||||
continue
|
||||
mdia = _find(f, body, end, b"mdia")
|
||||
hdlr = _find(f, mdia[1], mdia[2], b"hdlr") if mdia else None
|
||||
if hdlr is None:
|
||||
continue
|
||||
f.seek(hdlr[1] + 8) # version/flags (4) + pre_defined (4), then the type
|
||||
if f.read(4) == b"soun":
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def _traktor_json(v) -> str:
|
||||
if isinstance(v, bool):
|
||||
return "true" if v else "false"
|
||||
if isinstance(v, float):
|
||||
return str(int(v)) if v.is_integer() else "%.16g" % v
|
||||
if isinstance(v, (int, str)) or v is None:
|
||||
return json.dumps(v, ensure_ascii=False)
|
||||
if isinstance(v, list):
|
||||
return "[" + ",".join(_traktor_json(x) for x in v) + "]"
|
||||
if isinstance(v, dict):
|
||||
return "{" + ",".join(f"{json.dumps(k, ensure_ascii=False)}:{_traktor_json(v[k])}"
|
||||
for k in sorted(v)) + "}"
|
||||
raise TypeError(f"not JSON: {v!r}")
|
||||
|
||||
|
||||
def traktor_stems_json(box: bytes) -> str:
|
||||
"""A `stem` box payload as Traktor writes it into `<STEMS STEMS="…">`: keys
|
||||
sorted, no spaces, a whole float as an integer, any other to 16 significant
|
||||
digits. Measured: it reproduces Traktor's value for every stem file on this
|
||||
machine, and re-renders each of the 3,678 `<STEMS>` in the user's big
|
||||
collection unchanged — but all of those carry ONE layout (NI's defaults),
|
||||
so a box with other values is the same rule extrapolated. Raises ValueError
|
||||
on a box that is not JSON."""
|
||||
return _traktor_json(json.loads(box))
|
||||
|
||||
|
||||
def nml_stems_for(path: Path | str) -> str | None:
|
||||
"""The `<STEMS>` value a library entry for this file should carry, or None
|
||||
when it is not a playable stem file (the test `stem_layout` applies)."""
|
||||
if stem_layout(path) is None:
|
||||
return None
|
||||
try:
|
||||
return traktor_stems_json(read_stem_box(path))
|
||||
except (OSError, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def extract_stream(path: Path | str, stream: int, fp) -> None:
|
||||
"""Copy audio stream `stream` (0 = the mix, 1-4 the stems) into its own MP4,
|
||||
written to the file object `fp` — packets COPIED, never re-encoded.
|
||||
|
||||
A browser decodes only an MP4's first audio stream, so this is how the deck
|
||||
gets at the stems. Measured bit-identical to decoding the stream in place,
|
||||
with the edit list (and so the priming: 1024 for FFmpeg's encoder, 2112 for
|
||||
Apple's) carried across — on Konduktor's files and commercial ones alike, so
|
||||
every stem stays sample-locked to the mix and to the cue timeline.
|
||||
"""
|
||||
import av
|
||||
|
||||
with pyav.open_input(path) as inp:
|
||||
if not 0 <= stream < len(inp.streams.audio):
|
||||
raise StemFileError(f"The file has no audio stream {stream}")
|
||||
ist = inp.streams.audio[stream]
|
||||
out = av.open(fp, "w", format="ipod")
|
||||
try:
|
||||
ost = out.add_stream_from_template(ist)
|
||||
for pkt in inp.demux(ist):
|
||||
if pkt.dts is None:
|
||||
continue # the demuxer's end-of-stream flush packet
|
||||
pkt.stream = ost
|
||||
out.mux(pkt)
|
||||
finally:
|
||||
out.close()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DEMUCS_ORDER", "NML_STEMS_JSON", "SR", "STEM_BOX_JSON", "STEM_NAMES", "Source",
|
||||
"StemFileError", "Written", "add_stem_box", "build", "choose_bitrate", "decode",
|
||||
"default_encoder", "is_stem_file", "read_stem_box", "stem_target_name", "verify",
|
||||
"default_encoder", "extract_stream", "is_stem_file", "nml_stems_for", "read_stem_box", "stem_layout",
|
||||
"stem_target_name", "traktor_stems_json", "verify",
|
||||
]
|
||||
@@ -94,7 +94,9 @@ def _decode_pyav(path: Path) -> np.ndarray:
|
||||
"""
|
||||
import av
|
||||
|
||||
with av.open(str(path)) as container:
|
||||
from . import pyav
|
||||
|
||||
with pyav.open_input(path) as container:
|
||||
stream = container.streams.audio[0]
|
||||
resampler = av.AudioResampler(format="flt", layout="mono", rate=SR)
|
||||
chunks = []
|
||||
@@ -173,7 +175,18 @@ def _frames(y: np.ndarray, lead: float) -> Frames:
|
||||
|
||||
def analyse(path: Path, *, n_columns: int = 400, lead: float = 0.0) -> Analysis | None:
|
||||
"""Decode `path` once and measure both resolutions; None if undecodable."""
|
||||
y = _decode(path)
|
||||
return analyse_samples(decode(path), n_columns=n_columns, lead=lead)
|
||||
|
||||
|
||||
def decode(path: Path) -> np.ndarray | None:
|
||||
"""Mono float32 at `SR` — the same samples `analyse` measures, for a caller
|
||||
that needs them for something else too (grid detection runs at `SR`)."""
|
||||
return _decode(path)
|
||||
|
||||
|
||||
def analyse_samples(y: np.ndarray | None, *, n_columns: int = 400,
|
||||
lead: float = 0.0) -> Analysis | None:
|
||||
"""`analyse` on samples already decoded by `decode`."""
|
||||
if y is None or len(y) < max(n_columns, N_FFT):
|
||||
return None
|
||||
return Analysis(columns=_columns(y, n_columns), frames=_frames(y, lead))
|
||||
|
||||
@@ -341,11 +341,15 @@ def plan(adapter, export_set) -> ExportPlan:
|
||||
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]
|
||||
|
||||
# The source is the adapter's `audio_path`, never `Track.filepath`: that is
|
||||
# a DISPLAY path, which on Traktor omits the volume and ignores the active
|
||||
# The source is the adapter's file, never `Track.filepath`: that is a
|
||||
# DISPLAY path, which on Traktor omits the volume and ignores the active
|
||||
# path mapping — so every track off the boot volume (or on a remapped
|
||||
# Windows drive) read as missing and the export was "empty".
|
||||
sources = {t.id: adapter.audio_path(t.id) for t in tracks}
|
||||
# Windows drive) read as missing and the export was "empty". Its FACTS,
|
||||
# not `audio_path`: planning must not read a file, and on a library held
|
||||
# by a server reading one means downloading it. `run` fetches each file
|
||||
# only when it copies it.
|
||||
facts = adapter.audio_facts([t.id for t in tracks])
|
||||
sources = {tid: Path(f.key) for tid, f in facts.items()}
|
||||
|
||||
# Mirror relative to the deepest shared folder, so the export carries the
|
||||
# user's structure without carrying their home directory.
|
||||
@@ -355,16 +359,10 @@ def plan(adapter, export_set) -> ExportPlan:
|
||||
previous = _previous_copies(destination)
|
||||
claimed: set[Path] = set()
|
||||
for track in tracks:
|
||||
source = sources[track.id]
|
||||
exists = False
|
||||
size = mtime_ns = 0
|
||||
try:
|
||||
exists = bool(source and source.is_file())
|
||||
if exists:
|
||||
st = source.stat()
|
||||
size, mtime_ns = st.st_size, st.st_mtime_ns
|
||||
except OSError:
|
||||
exists = False
|
||||
source = sources.get(track.id)
|
||||
fact = facts.get(track.id)
|
||||
exists = fact is not None
|
||||
size, mtime_ns = (fact.size, fact.mtime_ns) if fact else (0, 0)
|
||||
planned = PlannedTrack(
|
||||
track_id=track.id,
|
||||
title=track.title or (source.name if source else track.id),
|
||||
@@ -435,9 +433,13 @@ def _folder_paths(adapter) -> dict[str, list[str]]:
|
||||
# ---- running -----------------------------------------------------------------
|
||||
|
||||
|
||||
def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
|
||||
root_folder: bool = False) -> dict:
|
||||
"""Copy what changed, then write every target's library over the audio.
|
||||
|
||||
`root_folder` nests the playlists in a folder named after the export (the
|
||||
"Put exported playlists in a folder" setting); otherwise they sit at the top.
|
||||
|
||||
Rolls back EVERYTHING this run wrote on cancel or on any failure —
|
||||
including the libraries of targets that had already been written when a
|
||||
later one failed. What it KEPT from the previous export stays, and the
|
||||
@@ -519,7 +521,10 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
done += n
|
||||
handle.progress(done=done)
|
||||
|
||||
copy_file(planned.source_path, partial, handle, advance)
|
||||
# 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
|
||||
copy_file(local, partial, handle, advance)
|
||||
os.replace(partial, target)
|
||||
payload_tracks.append(
|
||||
ExportTrack(
|
||||
@@ -544,6 +549,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
|
||||
payload = ExportPayload(
|
||||
name=export_set.name,
|
||||
root_folder=root_folder,
|
||||
tracks=payload_tracks,
|
||||
playlists=built.playlists,
|
||||
checkpoint=checkpoint,
|
||||
|
||||
Loaded 100 of 231 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user