Joren 6b0460a646 Use 1 MiB reads and add scan --shuffle for multi-disk arrays
- raise symphonia's MediaSourceStream buffer from the 64 KiB default to
  1 MiB; direct I/O on the FUSE share measures ~45 MB/s at 4 KiB,
  ~90 MB/s at 64 KiB, and ~119 MB/s at 1 MiB
- add scan --shuffle: seeded randomization of analysis order so
  concurrent workers read from different library regions instead of
  seek-thrashing the disk that happens to hold the current walk-order
  range
- thread the flag through scan::run and the integration tests
- document both changes in the README
2026-11-25 21:13:06 +01:00

sonic-rs

Fast, local sonic analysis for large music libraries.

sonic-rs decodes audio, computes Essentia-compatible log-mel spectrograms, runs Essentia's Discogs EfficientNet-B0 style classifier discogs-effnet-bsdynamic-1 through ONNX Runtime, stores one 1,280-d embedding and 400 style probabilities per track in SQLite, and builds an arroy approximate nearest-neighbour index. It can then generate:

  • Nearest Neighbour Radio — tracks close to a seed track, with artist diversity dampening and duplicate-edition filtering.
  • Smooth Transitions / Sonic Adventures — a Dijkstra route over a k-NN graph using squared cosine distance.
  • Mood / Genre Clusters — k-means playlists named by rebalanced-lift Discogs sub-styles.

Everything runs locally. No cloud service, no Plex dependency, no C++ Essentia runtime.


Quick start

1. Build

cargo build --release

The binary is target/release/sonic-rs.

2. Download the model (once)

Essentia publishes a ready-made ONNX export for the dynamic-batch variant, so no TensorFlow or tf2onnx conversion is needed:

python3 -m pip install onnx onnxruntime
python3 scripts/export_onnx.py

This downloads the model and metadata, writes the 400 Discogs style labels, checks the tensor contract, and runs a small smoke inference:

models/discogs-effnet-bsdynamic-1.onnx
models/discogs-effnet-bsdynamic-1.json
models/discogs-effnet-bsdynamic-1.labels.txt

3. Scan a library

target/release/sonic-rs scan ~/Music \
    --db data/music.db \
    --model models/discogs-effnet-bsdynamic-1.onnx \
    --jobs 8 \
    --exclude Full/QOBUZ_MONITOR

The first pass is CPU-bound. Later passes skip unchanged files based on path + mtime + size + model. --jobs N / -j N caps the rayon worker threads; omit it to use every core.

4. Generate playlists

# Exact path or case-insensitive title/path substring
target/release/sonic-rs similar "Lovers at Dusk" \
    --limit 25 --out data/lovers.m3u --db data/music.db

# Smooth route; --steps counts tracks including start and end
target/release/sonic-rs adventure "GISELLE" "Lovers at Dusk" \
    --steps 15 --out data/route.m3u --db data/music.db

# 15 clusters with Discogs sub-style names
target/release/sonic-rs cluster --clusters 15 \
    --out-dir data/playlists --db data/music.db \
    --labels models/discogs-effnet-bsdynamic-1.json

Add --relative-to <dir> to similar, adventure, or cluster to write relative paths into the .m3u files.

5. Refresh the index without re-scanning

The index is built from mean-centered copies of the stored embeddings, so it can be rebuilt in seconds with zero audio decoding:

target/release/sonic-rs rebuild-index --db data/music.db

Command reference

scan

sonic-rs scan <MUSIC_DIR> [--db <DB>] [--model <ONNX>] [--jobs <N>]
             [--exclude <DIR>]... [--seed <N>]
  • Recursively walks the library.
  • --jobs N / -j N caps the rayon worker threads (default: every core).
  • --exclude DIR (repeatable) skips an entire subtree; relative paths resolve against MUSIC_DIR. Files under an excluded path are pruned from the database, so they disappear from the index and playlists too.
  • --shuffle randomizes analysis order (seeded by --seed). On a multi-disk array this spreads concurrent workers across disks instead of thrashing the one disk that happens to hold the current walk-order region.
  • Logs discovery counts and a progress line every 50 processed tracks when stderr is not a terminal (e.g. under tee or nohup); interactive runs get a bar.
  • Considers only flac, mp3, m4a, aac, ogg, opus, and wav (case-insensitive). Cover art, .cue, .log, and other files are ignored.
  • Decodes, downmixes, resamples, computes log-mel patches, runs ONNX inference, and pools each track.
  • Analyzes in 128-track batches and upserts each batch, so peak memory stays bounded instead of holding the whole library's embeddings in RAM.
  • Removes rows for files that no longer exist.
  • Rebuilds the mean-centered arroy index deterministically.

similar

sonic-rs similar <TRACK|TITLE-SUBSTRING> [--limit 25] --out <FILE> --db <DB>
                 [--relative-to <DIR>]

The argument is resolved as:

  1. exact path,
  2. canonicalized/absolute path,
  3. case-insensitive substring of path or title.

If several tracks match, the top candidates are printed and the command asks for a more specific query.

Candidates are deduplicated by normalized (artist, title) with the seed's key pre-inserted, so duplicate rips, deluxe editions, and compilation copies never repeat. Empty titles are exempt from title dedup.

adventure

sonic-rs adventure <START> <END> [--steps 15] --out <FILE> --db <DB>
                   [--relative-to <DIR>]

Routes over a 15-nearest-neighbour graph. The shortest path minimizes the sum of squared cosine distances. --steps is the maximum number of tracks in the route (start and end included).

cluster

sonic-rs cluster [--clusters 8] [--out-dir ./playlists] --db <DB>
                 [--labels models/discogs-effnet-bsdynamic-1.json]
                 [--relative-to <DIR>]

Runs k-means over the stored embeddings. If labels are available, filenames use the top three Discogs sub-styles (the ParentGenre--- prefix is stripped):

cluster_01_synth-pop-boogie-city-pop.m3u
cluster_02_ambient-instrumental-electronic.m3u

Filenames are scored by the rebalanced lift described below, so dominant sub-styles name the cluster instead of one stray prediction. Each playlist is also deduplicated by normalized (artist, title); members are ordered nearest-to-centroid first, so the retained edition is the most representative one.

Without labels, files are named cluster_01.m3u, cluster_02.m3u, etc.

rebuild-index

sonic-rs rebuild-index [--db sonic.db]

Reopens the SQLite database, re-reads the stored f32 embeddings, applies the library mean-centering, and rebuilds <db-stem>.mdb/. No audio files are touched, so this is the fast path after changing the centering, the tree count, or the build seed. Prints the number of indexed tracks.


How it works

audio file
   │
   ▼
symphonia decode ──► mono downmix ──► rubato FFT resampler ──► 16 kHz mono f32
   │
   ▼
512/256 framing ──► normalized Hann ──► 512-pt power FFT
   │
   ▼
96 Slaney mel bands (0–8 kHz, unit_tri) ──► log10(10000·E + 1)
   │
   ▼
128×96 patches (~2 s) ──► EffNetDiscogs ONNX
   │                            ├── 1,280-d embedding
   │                            └── 400 style probabilities
   ▼
trimmed-mean pooling ──► L2 normalize embedding
   │
   ▼
SQLite raw blobs ──► mean-center + L2 (at load) ──► arroy/LMDB cosine index
   │
   ├── similar   (k-NN + artist diversity + title dedup)
   ├── adventure (k-NN graph + Dijkstra)
   └── cluster   (k-means++/Lloyd on the same centered space)

1. Audio decoding and resampling

  • Symphonia decodes FLAC, MP3, AAC/M4A, Ogg Vorbis, and WAV.
  • Reads use a 1 MiB buffer instead of symphonia's 64 KiB default: on FUSE (shfs) and spinning disks the larger reads roughly double throughput.
  • Samples are converted to interleaved f32.
  • Channels are averaged before resampling: x_{\text{mono}}[n] = \frac{1}{C}\sum_{c=1}^{C} x_c[n].
  • rubato's FFT resampler converts to exactly 16,000 Hz. 16 kHz input is returned unchanged. The resampler delay is trimmed, the tail is flushed with process_partial, and the output is truncated/padded to the exact rational length.
  • Recoverable packet/frame decode errors are skipped; one damaged frame does not discard the track.

2. Framing and the STFT

For N = 512 samples per frame (32 ms) and hop H = 256 (16 ms), Essentia's FrameCutter-compatible frame count is:


F = \left\lfloor \frac{L - 0.5N}{H} \right\rfloor + 1,
\quad L \ge 0.5N

where L is the number of mono samples. The final partial frame is zero-padded. For exactly 3.000 s at 16 kHz, L = 48{,}000 and F = 187.

The Hann window and Essentia normalization are:


w[n] = 0.5 - 0.5\cos\!\left(\frac{2\pi n}{N-1}\right),
\qquad
\tilde w[n] = \frac{2\,w[n]}{\sum_{m=0}^{N-1} w[m]}.

The 512-point FFT and power spectrum are:


X[k] = \sum_{n=0}^{N-1} x[n]\tilde w[n]e^{-i2\pi kn/N},
\qquad
P[k] = |X[k]|^2,\quad k=0,\ldots,256.

No FFT normalization is applied: this matches Plex/Essentia's absolute energy scale, which matters because the next step is logarithmic, not relative.

3. Slaney mel filterbank

The mel scale is the piecewise Slaney scale used by Essentia's warpingFormula=slaneyMel:


m(f)=
\begin{cases}
\dfrac{3}{200}f, & f < 1000,\\[6pt]
15 + \dfrac{\ln(f/1000)}{\ln(6.4)/27}, & f \ge 1000.
\end{cases}

The inverse is:


f(m)=
\begin{cases}
\dfrac{200}{3}m, & m < 15,\\[6pt]
1000\exp\!\left((m-15)\dfrac{\ln 6.4}{27}\right), & m \ge 15.
\end{cases}

For 96 bands between 0 and 8000 Hz, 98 edges are spaced uniformly in mel:


e_i = f\!\left(m(0) + i\frac{m(8000)-m(0)}{97}\right),
\quad i=0,\ldots,97.

Band i is the triangle (e_i, e_{i+1}, e_{i+2}). With linear weighting, the weight of FFT bin k at frequency f_k is:


c_i(k)=
\begin{cases}
\dfrac{f_k-e_i}{e_{i+1}-e_i}, & f_k < e_{i+1},\\[8pt]
\dfrac{e_{i+2}-f_k}{e_{i+2}-e_{i+1}}, & f_k \ge e_{i+1}.
\end{cases}

Only bins in


\left\lceil \frac{e_i}{\Delta f}\right\rceil
\le k \le
\left\lfloor \frac{e_{i+2}}{\Delta f}\right\rfloor,
\qquad
\Delta f = \frac{8000}{256} = 31.25\text{ Hz}

are visited. The unit_tri normalization divides every coefficient by the theoretical triangle area:


\text{area}_i = \frac{(e_{i+1}-e_i) + (e_{i+2}-e_{i+1})}{2}.

So the continuous triangle area is 1. The band energy is:


E_i = \sum_k P[k]\,c_i(k),

and the log compression is:


L_i = \log_{10}\!\left(10000\,E_i + 1\right).

A patch is 128 consecutive frames (2.048 s):


M \in \mathbb{R}^{128 \times 96}.

4. EffNetDiscogs inference

The model is Essentia's discogs-effnet-bsdynamic-1: an EfficientNet-B0 trained on the Discogs-4M dataset for 400 music styles. Essentia publishes a ready-made ONNX export with a dynamic batch dimension:

tensor name shape
input melspectrogram [batch, 128, 96]
embedding embeddings [batch, 1280]
styles activations [batch, 400]

The 1,280-d output is the globally pooled feature vector that feeds the 400-way classifier; activations are independent sigmoid style probabilities. Essentia's own TensorflowPredictEffnetDiscogs uses TensorflowInputMusiCNN for feature extraction, so the log-mel frontend above is unchanged from the MusiCNN model — only the patch length differs.

Patches are sent to ONNX Runtime in batches of 32. The model is validated at load time; input/output tensors are discovered by shape, so renamed nodes do not matter.

5. Track pooling

For a track with P complete patches, let M_j be patch $j$'s log-mel matrix. The patch energy is:


s_j = \frac{1}{128\cdot96}\sum_{a,b} M_j[a,b].

The quietest \lfloor 0.10P \rfloor patches are dropped (always keeping at least one). Let K be the kept set. The embedding and tag vectors are averaged:


\bar e = \frac{1}{|K|}\sum_{j\in K} e_j,
\qquad
\bar t = \frac{1}{|K|}\sum_{j\in K} t_j.

The embedding is L2-normalized:


\hat e = \frac{\bar e}{\lVert \bar e\rVert_2}.

Styles remain mean probabilities so cluster names and thresholds stay interpretable. Tracks shorter than one complete 128-frame patch (~2.1 s) are skipped with a warning.

6. Mean-centering (zero-mean hypersphere)

Raw EffNetDiscogs embeddings share a large "average music" component, so every pair of tracks looks similar by cosine and nearest neighbours drift towards genre prototypes instead of genuinely matching tracks. Left uncentered, the 1,280-d baseline dominates the distance.

Let v_1,\ldots,v_N \in \mathbb{R}^{1280} be the stored (L2-normalized) track embeddings. The library mean and the indexed vector are:


\mu = \frac{1}{N}\sum_{i=1}^{N} v_i,
\qquad
\hat v_i = \frac{v_i - \mu}{\lVert v_i - \mu\rVert_2 + 10^{-12}}.

Cosine similarity on the centered vectors equals the Pearson correlation of the raw embeddings:


\cos(\hat v_i, \hat v_j) = \operatorname{corr}(v_i, v_j),

which removes the shared baseline and maximizes the contribution of what actually differs between tracks. The same \hat v_i is used for the arroy index and for k-means, so similar, adventure and cluster all live on the same zero-mean hypersphere.

The transformation is applied at load time only: SQLite stores the raw blobs, \mu is persisted as meta.center_mean, and rebuild-index refreshes <db-stem>.mdb/ without re-scanning any audio. A single-track library (or any set that collapses to zero after centering) stays as zero vectors rather than amplifying floating-point noise. An empty rebuild removes meta.center_mean so vector queries fail with a clear "rebuild the index" message instead of a dimension mismatch.

7. Storage

SQLite stores:

meta(key, value)          -- model_id, embedding_dim, schema_version, center_mean
tracks(
  id, path, mtime_ns, size, title, artist, album, duration_s,
  embedding BLOB, tags BLOB, model, updated_at
)

Embeddings and tags are little-endian f32 blobs and are always the raw pooled vectors (uncentered). meta.model_id and meta.embedding_dim are checked on open; a mismatch clears cached tracks so a model upgrade forces a clean rescan. meta.center_mean holds the 1,280-d library mean written by the most recent index rebuild.

The scan cache is keyed by canonical path and compares mtime_ns, size, and the model id. prune_missing removes rows whose files disappeared.

8. Vector index

The index lives in an LMDB directory at <db-stem>.mdb/:

  • map_size = 16 GiB (virtual address space; the file grows on demand)
  • max_dbs = 4
  • arroy Cosine distance
  • 10 trees
  • StdRng::seed_from_u64(seed) (default 42)
  • rebuilt from ORDER BY id ASC, with IDs cast to u32
  • vectors mean-centered and L2-normalized before insertion; queries by item use the stored centered vector, and arbitrary query vectors are centered with meta.center_mean

arroy's cosine distance is:


d_{\cos}(u,v) = \frac{1-\cos(u,v)}{2} \in [0,1].

Annoy's angular distance is:


d_{\text{ang}}(u,v) = \sqrt{2-2\cos(u,v)} = 2\sqrt{d_{\cos}(u,v)}.

It is a monotonic transform of d_{\cos}, so nearest-neighbour ordering is identical.

9. Similar radio

similar asks arroy for a pool of neighbours, excludes the seed, and applies artist-diversity dampening:


\text{score}(t) = d(t)\left(1 + 0.35\,n_{\text{artist}}(t)\right),

where n_{\text{artist}} is how many tracks by that artist have already been selected. A fourth consecutive track by the same artist is strongly discouraged.

Before scoring, candidates are deduplicated by the normalized key


(\text{artist},\ \text{title}) = (\operatorname{trim}\circ\operatorname{lower},\
\operatorname{trim}\circ\operatorname{lower}),

with the seed's key pre-inserted. Duplicate rips, deluxe editions, and the same song on a compilation therefore never appear twice in one playlist. Tracks with an empty title produce no key and are only excluded by identity, so untitled tracks are not collapsed together. The result is written as a UTF-8 .m3u playlist.

10. Sonic adventure

Build an undirected graph G=(V,E) where each track is connected to its k=15 nearest neighbours. The edge weight is:


w(u,v) = d_{\cos}(u,v)^2.

Squaring penalizes long jumps and rewards several small, smooth transitions. Dijkstra minimizes:


\sum_{(u,v)\in\text{path}} w(u,v).

The route is capped at --steps tracks (start and end included).

11. Mood / genre clusters

k-means runs on the same mean-centered, L2-normalized vectors as the index (the mean is recomputed from SQLite on every run), so a cluster boundary means the same thing as an arroy neighbour region. k-means++ selects initial centroids with probability proportional to the squared distance to the nearest existing centroid:


\Pr(x) = \frac{D(x)^2}{\sum_{x'} D(x')^2}.

Lloyd's algorithm then alternates:


\text{assign}(x)=\arg\min_c \lVert x-\mu_c\rVert_2^2,
\qquad
\mu_c = \frac{1}{|S_c|}\sum_{x\in S_c}x.

Because track embeddings are L2-normalized, Euclidean distance squared is equivalent to cosine distance:


\lVert x-y\rVert_2^2 = 2-2\cos(x,y).

Cluster playlist names use a rebalanced relative lift over the whole library:


\text{score}_{c,i} =
\sqrt{\mu_{c,i}}\;\frac{\mu_{c,i}}{\text{global}_i + 0.05},

where \mu_{c,i} is the cluster's mean probability for style i and \text{global}_i is the library mean. Discogs has 400 styles with a very long tail: the square-root factor dampens styles that fire on only a few patches, and the +0.05 floor caps the lift of ultra-rare styles whose global mean is near zero. Dominant styles therefore name the cluster.

Labels are formatted as ParentGenre---SubStyle; the parent is stripped and the top three distinct sub-styles become a sanitized filename suffix. Because the same sub-style can exist under several parents (e.g. Gospel under both Funk / Soul and Folk, World, & Country), duplicates are removed before the three are chosen.


Performance

Release build, 20-core Linux, /home/joren/Music/Musica (2,411 tracks, 82 GB, FLAC/M4A/WAV), full re-embed at --jobs 8 under nice -n 19 ionice -c 3:

discovered: 2,411
analyzed:   2,411
skipped:    0
pruned:     0
indexed:    2,411
warnings:   0

wall:       19m 34s
throughput: 2.05 tracks/sec (123 tracks/min)
db:         data/musica.db (19 MB)
index:      data/musica.mdb/ (42 MB)

The first pass is dominated by FLAC decoding, FFT/mel work, and per-patch ONNX inference. Incremental rescans are much faster: unchanged files are skipped and only the index is rebuilt. A full rebuild from the stored 1,280-d embeddings (rebuild-index) takes ~60 ms for 2,411 tracks — no audio is decoded.

Large libraries

Per-track CPU cost measured on a 32-core host is roughly 1 CPU-second per track (decode + 128-frame log-mel + EfficientNet-B0 inference); the nice 19 reference run above is deliberately throttled, so its wall time is not representative of dedicated hardware. A 429k-track library is therefore about 120 core-hours: ~6 hours at 20 workers, ~15 hours at 8 workers, before any storage bottleneck. Reading 18 TB is usually the real limit — roughly 10–25 hours at 200–500 MB/s — so expect ~12–30 hours end to end on a fast local share, longer on a single HDD or a busy network link.

The implementation is sized for this: LMDB reserves 16 GiB of address space (the file grows on demand), scanning writes every 128 tracks so RAM stays bounded and progress is committed frequently, and incremental rescans only walk the tree and rebuild the index. Budget ~12 GB of disk for the SQLite database, WAL, and index at that scale.

Effect of mean-centering

On the same library, raw EffNetDiscogs embeddings share a sizeable baseline; mean-centering widens the discrimination among the seed's nearest neighbours:

seed "Lovers at Dusk" vs its 25 nearest neighbours
raw       cos 0.7822 – 0.9350  (mean 0.8382)
centered  cos 0.5146 – 0.8456  (mean 0.6307)

Project layout

src/
├── main.rs       CLI dispatch and flexible track lookup
├── audio.rs      symphonia decode, mono downmix, rubato resample
├── mel.rs        Slaney mel filterbank
├── dsp.rs        framing, Hann, FFT, log-mel, 128×96 patches
├── model.rs      ONNX session, pooling, mean-centering, L2
├── db.rs         SQLite schema, upserts, cache, pruning, center mean
├── index.rs      arroy/LMDB cosine index over centered vectors
├── scan.rs       walkdir + rayon + indicatif scan
├── playlist.rs   .m3u writer + artist diversity + dedup
├── graph.rs      k-NN graph + Dijkstra
└── cluster.rs    k-means++/Lloyd + label naming
scripts/
└── export_onnx.py
models/
├── discogs-effnet-bsdynamic-1.json        # 400 style labels (tracked)
├── discogs-effnet-bsdynamic-1.labels.txt  # convenience label list (tracked)
└── discogs-effnet-bsdynamic-1.onnx        # downloaded, gitignored

Model download details

scripts/export_onnx.py:

  1. Downloads the official ONNX export https://essentia.upf.edu/models/feature-extractors/discogs-effnet/discogs-effnet-bsdynamic-1.onnx and its .json metadata.
  2. Writes the 400 Discogs style labels to models/discogs-effnet-bsdynamic-1.labels.txt.
  3. Reads the declared schema from the JSON and locates the [batch, 128, 96] input, the [batch, 1280] embedding output, and the [batch, 400] style output by shape — no node names are guessed.
  4. Verifies the ONNX contract with onnx and runs a small onnxruntime inference to prove the graph executes.

No TensorFlow or tf2onnx installation is required. The ONNX model is intentionally not committed (.gitignore); the small JSON/label files are.

Because MODEL_ID and EMBEDDING_DIM are checked when the database opens, an existing msd-musicnn-1 database is invalidated automatically on the next scan: old rows and meta.center_mean are cleared, then the library is re-embedded. No manual migration is needed.


Testing

cargo test
cargo clippy --all-targets -- -D warnings
cargo fmt --check

Coverage includes:

  • Slaney mel geometry, unit_tri areas, DC/tone band placement
  • exact 128×96 patch dimensions from synthetic sine waves
  • Hann normalization and Essentia frame counts
  • stereo 44.1 kHz → 16 kHz mono WAV fixtures, frequency preservation
  • full decode → DSP → model embedding path
  • trimmed-mean pooling, 1,280-d embeddings, 400-d sigmoid styles, L2
  • mean-centering: zero-mean/unit-norm output and increased angular separation
  • SQLite upsert/prune/model invalidation and stored center_mean
  • arroy build + brute-force top-5 accuracy in centered space
  • empty rebuild clears the stored mean
  • incremental scan/prune integration
  • .m3u absolute/relative paths
  • artist-diversity selection and duplicate (artist, title) filtering
  • per-cluster duplicate edition filtering (nearest-to-centroid kept)
  • Discogs ParentGenre---SubStyle stripping and rebalanced tag ranking
  • Dijkstra route selection
  • k-means separation and sub-style naming

Limitations and notes

  • Style-level similarity, not a full timbre embedding. The 400 sigmoid style probabilities are averaged over 2-second patches, so tracks with similar style profiles are considered sonically similar even if their instrumentation or rhythm differs.
  • Temporal structure is averaged away. Intros, drops, and outros contribute to one vector per track.
  • Short tracks are skipped if they contain less than one complete 128-frame patch (~2.1 s).
  • Opus filtering is present, but Symphonia 0.6 does not bundle an Opus decoder; Opus files will be skipped with a warning unless a decoder is added.
  • CPU only by default. ONNX Runtime uses CPU; each rayon worker loads its own session with one intra-op thread to avoid oversubscription.
  • Approximate index. arroy is an approximate nearest-neighbour index; increasing trees/search-k improves recall at a cost of build/query time.
  • Style taxonomy comes from discogs-effnet-bsdynamic-1, not from the user's metadata or genre tags.

License

MIT. See LICENSE.

S
Description
No description provided
Readme MIT
285 KiB
0 Stars 1 Watchers 0 Forks
Languages
Rust 95.2%
Python 4.8%