From c095c7a7692cd47e69c50b22ea3ee45c89ce843d Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 14:35:09 +0000 Subject: [PATCH 01/25] Add a cue survey of how a playlist's cues meet the grid and phrases A dev example that reads a snapshot of the installed library and reports cue alignment to beats, bars and the 4-32 bar grid, which rekordbox phrase starts carry a cue, and the gaps between cues. Optionally dumps the grids, phrases and cues as JSON for evaluating cue placement. Bumps es-rekordbox-sdk for the PSSI reader, rustfmt and lint fixes. Co-Authored-By: Claude Opus 5.5 --- es-rekordbox-sdk | 2 +- native/crates/es-index/examples/cue_survey.rs | 450 ++++++++++++++++++ 2 files changed, 451 insertions(+), 1 deletion(-) create mode 100644 native/crates/es-index/examples/cue_survey.rs diff --git a/es-rekordbox-sdk b/es-rekordbox-sdk index eebc9b9..43f07d3 160000 --- a/es-rekordbox-sdk +++ b/es-rekordbox-sdk @@ -1 +1 @@ -Subproject commit eebc9b9ae1349f270fa522a9b54827e7187f26e2 +Subproject commit 43f07d348486688f86b4524e9d61b17f7dffdf11 diff --git a/native/crates/es-index/examples/cue_survey.rs b/native/crates/es-index/examples/cue_survey.rs new file mode 100644 index 0000000..8b2e193 --- /dev/null +++ b/native/crates/es-index/examples/cue_survey.rs @@ -0,0 +1,450 @@ +//! How a playlist's cues sit against the beat grid and rekordbox's phrases: what an automatic cue +//! placer would have to learn. Reads a snapshot of the installed library and changes nothing. +//! `cargo run --release -p es-index --example cue_survey -- "" [--json survey.json]` + +use std::cmp::Reverse; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::path::Path; + +use rb_anlz::decode::{self, Grid, Tags}; +use rb_anlz::phrase::{self, Mood, SongStructure}; +use rb_library::{Library, PlaylistKind, PlaylistNode, Track}; +use serde_json::json; + +type Beats = i64; +type Bars = i64; + +const BEATS_PER_BAR: Beats = 4; +const ON_BEAT_TOLERANCE_MS: i64 = 15; +const PHRASE_GRIDS: [Bars; 4] = [4, 8, 16, 32]; +const TOP_ANCHORS: usize = 10; +const TOP_BOUNDARIES: usize = 20; + +struct SurveyedTrack { + track: Track, + grid: Option, + structure: Option, + cues: Vec, +} + +struct Placement { + hot_slot: Option, + beat: usize, + on_beat: bool, + on_downbeat: bool, + beats_from_first_downbeat: Beats, + track_fraction: f64, + anchor: Option, +} + +struct PhraseAnchor { + name: String, + beats_after: Beats, +} + +fn main() -> Result<(), Box> { + let mut args = std::env::args().skip(1); + let wanted = args.next().ok_or("name a playlist or folder")?; + let json_path = match (args.next().as_deref(), args.next()) { + (Some("--json"), Some(path)) => Some(path), + _ => None, + }; + + let path = Library::installed_path().ok_or("no installed rekordbox library")?; + let lib = Library::open_snapshot(&path)?; + let share = path.with_file_name("share"); + let ids = playlist_track_ids(&lib, &wanted)?; + let tracks: Vec = + lib.tracks(Some(&ids))?.into_iter().map(|track| survey(&lib, &share, track)).collect::>()?; + + if let Some(path) = json_path { + std::fs::write(&path, serde_json::to_string_pretty(&tracks.iter().map(to_json).collect::>())?)?; + println!("wrote {path}"); + } + report(&tracks); + Ok(()) +} + +fn playlist_track_ids(lib: &Library, wanted: &str) -> Result, Box> { + let nodes = lib.playlists()?; + let matches: Vec<&PlaylistNode> = + nodes.iter().filter(|node| node.id == wanted || node.name.eq_ignore_ascii_case(wanted)).collect(); + let root = match matches.as_slice() { + [one] => *one, + [] => return Err(format!("no playlist or folder called {wanted}").into()), + many => { + let ids: Vec<_> = many.iter().map(|node| node.id.as_str()).collect(); + return Err(format!("{wanted} names several playlists; pass one id of {ids:?}").into()); + } + }; + let mut ids = Vec::new(); + let mut seen = HashSet::new(); + let mut pending = vec![root]; + while let Some(node) = pending.pop() { + if node.kind == PlaylistKind::Folder { + pending.extend(nodes.iter().filter(|child| child.parent_id == node.id)); + continue; + } + ids.extend(lib.playlist_track_ids(&node.id)?.into_iter().filter(|id| seen.insert(id.clone()))); + } + Ok(ids) +} + +fn survey(lib: &Library, share: &Path, track: Track) -> rb_library::Result { + let analysis = |suffix| { + let relative = track.analysis_path.as_deref()?; + Tags::read(&rb_anlz::file(share, relative, suffix)?).ok() + }; + let grid = analysis("DAT").as_ref().and_then(decode::beatgrid); + let structure = analysis("EXT").as_ref().and_then(phrase::song_structure); + let cues = es_index::detail::cues(lib, &track.id, None)?; + Ok(SurveyedTrack { track, grid, structure, cues }) +} + +fn hot_cue_letter(slot: i64) -> Option { + let index = match slot { + 1..=3 => slot - 1, + 5..=9 => slot - 2, + _ => return None, + }; + char::from_u32('A' as u32 + u32::try_from(index).ok()?) +} + +fn mood_name(mood: Mood) -> &'static str { + match mood { + Mood::High => "high", + Mood::Mid => "mid", + Mood::Low => "low", + } +} + +fn to_json(surveyed: &SurveyedTrack) -> serde_json::Value { + let track = &surveyed.track; + json!({ + "id": track.id, + "title": track.title, + "artist": track.artist, + "genre": track.genre, + "bpm": track.bpm_x100 as f64 / 100.0, + "lengthSeconds": track.length, + "grid": surveyed.grid.as_ref().map(|grid| json!({ "times": grid.times, "beats": grid.beats })), + "structure": surveyed.structure.as_ref().map(|structure| json!({ + "mood": mood_name(structure.mood), + "endBeat": structure.end_beat, + "phrases": structure.phrases.iter().map(|phrase| json!({ + "firstBeat": phrase.first_beat, + "label": phrase.to_string(), + "fillInBeat": phrase.fill_in_beat, + })).collect::>(), + })), + "cues": surveyed.cues.iter().map(|cue| json!({ + "hotSlot": hot_cue_letter(cue.slot).filter(|_| cue.kind == "hot").map(String::from), + "startMs": cue.start, + "endMs": cue.end, + })).collect::>(), + }) +} + +fn nearest_beat(grid: &Grid, ms: i64) -> usize { + let after = grid.times.partition_point(|&time| i64::from(time) < ms); + let distance = |index: usize| (i64::from(grid.times[index]) - ms).abs(); + match after { + 0 => 0, + index if index == grid.times.len() => index - 1, + index if distance(index - 1) <= distance(index) => index - 1, + index => index, + } +} + +/// Each phrase named by its kind and how many of that kind came before it, so "Chorus#2" is the +/// second chorus whatever rekordbox's variant number says. +fn phrase_boundaries(structure: &SongStructure) -> Vec<(Beats, String)> { + let mut seen: HashMap = HashMap::new(); + structure + .phrases + .iter() + .map(|phrase| { + let kind = phrase.kind.map_or_else(|| "?".to_owned(), |kind| format!("{kind:?}")); + let occurrence = seen.entry(kind.clone()).and_modify(|n| *n += 1).or_insert(1); + (Beats::from(phrase.first_beat) - 1, format!("{kind}#{occurrence}")) + }) + .collect() +} + +fn nearest_anchor(boundaries: &[(Beats, String)], beat: Beats) -> Option { + boundaries + .iter() + .min_by_key(|(start, _)| ((beat - start).abs(), beat > *start)) + .map(|(start, name)| PhraseAnchor { name: name.clone(), beats_after: beat - start }) +} + +fn placements(surveyed: &SurveyedTrack) -> Vec { + let Some(grid) = &surveyed.grid else { return Vec::new() }; + let first_downbeat = grid.beats.iter().position(|&beat| beat == 1).unwrap_or(0); + let boundaries = surveyed.structure.as_ref().map(phrase_boundaries).unwrap_or_default(); + let length_ms = (surveyed.track.length * 1000).max(1); + surveyed + .cues + .iter() + .map(|cue| { + let beat = nearest_beat(grid, cue.start); + let on_beat = (i64::from(grid.times[beat]) - cue.start).abs() <= ON_BEAT_TOLERANCE_MS; + let beat_number = Beats::try_from(beat).unwrap_or(Beats::MAX); + Placement { + hot_slot: hot_cue_letter(cue.slot).filter(|_| cue.kind == "hot"), + beat, + on_beat, + on_downbeat: on_beat && grid.beats[beat] == 1, + beats_from_first_downbeat: beat_number - Beats::try_from(first_downbeat).unwrap_or(0), + track_fraction: cue.start as f64 / length_ms as f64, + anchor: nearest_anchor(&boundaries, beat_number), + } + }) + .collect() +} + +fn percent(count: usize, total: usize) -> String { + if total == 0 { + return " - ".to_owned(); + } + format!("{:>4.0}%", 100.0 * count as f64 / total as f64) +} + +fn describe_offset(beats: Beats) -> String { + let (bars, beats) = (beats.div_euclid(BEATS_PER_BAR), beats.rem_euclid(BEATS_PER_BAR)); + match (bars, beats) { + (0, 0) => "start".to_owned(), + (bars, 0) => format!("{bars:+} bars"), + (bars, beats) => format!("{bars:+} bars {beats:+} beats"), + } +} + +fn tally(items: impl IntoIterator) -> Vec<(K, usize)> { + let mut counts: BTreeMap = BTreeMap::new(); + for item in items { + *counts.entry(item).or_default() += 1; + } + let mut sorted: Vec<_> = counts.into_iter().collect(); + sorted.sort_by_key(|(_, count)| Reverse(*count)); + sorted +} + +fn median(mut values: Vec) -> f64 { + values.sort_by(f64::total_cmp); + values.get(values.len() / 2).copied().unwrap_or(f64::NAN) +} + +fn report(tracks: &[SurveyedTrack]) { + let with_grid = tracks.iter().filter(|t| t.grid.is_some()).count(); + let with_structure: Vec<&SongStructure> = tracks.iter().filter_map(|t| t.structure.as_ref()).collect(); + let bpms: Vec = tracks.iter().map(|t| t.track.bpm_x100 as f64 / 100.0).filter(|bpm| *bpm > 0.0).collect(); + println!("\n== Library =="); + println!("tracks {} with grid {with_grid} with phrases {}", tracks.len(), with_structure.len()); + println!( + "bpm {:.0}-{:.0} (median {:.0})", + bpms.iter().copied().fold(f64::INFINITY, f64::min), + bpms.iter().copied().fold(0.0, f64::max), + median(bpms.clone()) + ); + println!("moods {:?}", tally(with_structure.iter().map(|s| mood_name(s.mood)))); + println!( + "hot cues per track {:?}", + tally(tracks.iter().map(|t| t.cues.iter().filter(|c| c.kind == "hot").count())) + ); + println!( + "memory cues per track {:?}", + tally(tracks.iter().map(|t| t.cues.iter().filter(|c| c.kind == "memory").count())) + ); + println!("loops {}", tracks.iter().flat_map(|t| &t.cues).filter(|c| c.end.is_some()).count()); + + let phrase_bars = with_structure.iter().flat_map(|structure| { + let starts: Vec = structure.phrases.iter().map(|p| Beats::from(p.first_beat)).collect(); + let ends = starts.iter().skip(1).copied().chain([Beats::from(structure.end_beat)]); + starts.iter().zip(ends).map(|(start, end)| (end - start) as f64 / BEATS_PER_BAR as f64).collect::>() + }); + let phrase_bars: Vec = phrase_bars.map(|bars| format!("{bars}")).collect(); + println!("rekordbox phrase lengths in bars {:?}", tally(phrase_bars)); + + let placed: Vec<(&SurveyedTrack, Vec)> = tracks.iter().map(|t| (t, placements(t))).collect(); + report_alignment(&placed); + report_phase(&placed); + report_coverage(&placed); + report_slots(&placed); + report_memory(&placed); + report_gaps(&placed); +} + +fn report_alignment(placed: &[(&SurveyedTrack, Vec)]) { + println!("\n== Alignment (share of cues) =="); + println!( + "{:<8} {:>5} {:>6} {:>9} {:>5} {:>5} {:>5} {:>5} {:>9} {:>11}", + "", "cues", "beat", "downbeat", "4bar", "8bar", "16bar", "32bar", "phrase", "phrase±1bar" + ); + for (name, hot) in [("hot", true), ("memory", false)] { + let cues: Vec<(&Placement, bool)> = placed + .iter() + .flat_map(|(track, places)| places.iter().map(move |p| (p, track.structure.is_some()))) + .filter(|(p, _)| p.hot_slot.is_some() == hot) + .collect(); + let on_grid = |bars: Bars| { + cues.iter() + .filter(|(p, _)| p.on_downbeat && p.beats_from_first_downbeat.rem_euclid(bars * BEATS_PER_BAR) == 0) + .count() + }; + let phrased: Vec<&Placement> = cues.iter().filter(|(_, has)| *has).map(|(p, _)| *p).collect(); + let near_phrase = |within: Beats| { + phrased + .iter() + .filter(|p| p.on_beat && p.anchor.as_ref().is_some_and(|a| a.beats_after.abs() <= within)) + .count() + }; + println!( + "{name:<8} {:>5} {:>6} {:>9} {:>5} {:>5} {:>5} {:>5} {:>9} {:>11}", + cues.len(), + percent(cues.iter().filter(|(p, _)| p.on_beat).count(), cues.len()), + percent(cues.iter().filter(|(p, _)| p.on_downbeat).count(), cues.len()), + percent(on_grid(PHRASE_GRIDS[0]), cues.len()), + percent(on_grid(PHRASE_GRIDS[1]), cues.len()), + percent(on_grid(PHRASE_GRIDS[2]), cues.len()), + percent(on_grid(PHRASE_GRIDS[3]), cues.len()), + percent(near_phrase(0), phrased.len()), + percent(near_phrase(BEATS_PER_BAR), phrased.len()), + ); + } + println!("(N-bar columns count bars from each track's first downbeat; phrase columns only cover tracks with rekordbox phrases)"); +} + +/// Whether counting bars from the first downbeat finds the phrase grid, or each track needs its +/// own phrase start: the best phase is an upper bound no single rule can beat. +fn report_phase(placed: &[(&SurveyedTrack, Vec)]) { + println!("\n== Phrase grid phase (downbeat cues on the grid) =="); + let downbeat_cues: Vec> = placed + .iter() + .map(|(_, places)| { + places.iter().filter(|p| p.on_downbeat).map(|p| p.beats_from_first_downbeat / BEATS_PER_BAR).collect() + }) + .collect(); + let total: usize = downbeat_cues.iter().map(Vec::len).sum(); + for bars in PHRASE_GRIDS { + let from_first_downbeat: usize = + downbeat_cues.iter().map(|cues| cues.iter().filter(|b| b.rem_euclid(bars) == 0).count()).sum(); + let best_phase: usize = downbeat_cues + .iter() + .map(|cues| { + (0..bars) + .map(|phase| cues.iter().filter(|b| (*b - phase).rem_euclid(bars) == 0).count()) + .max() + .unwrap_or(0) + }) + .sum(); + println!( + "{bars:>2} bars: from first downbeat {} best phase per track {}", + percent(from_first_downbeat, total), + percent(best_phase, total) + ); + } +} + +/// Which phrase starts the user cues, out of every one rekordbox found: the choice a cue placer +/// has to learn once it knows the sections. +fn report_coverage(placed: &[(&SurveyedTrack, Vec)]) { + println!("\n== Rekordbox phrase starts that carry a cue =="); + let mut by_anchor: BTreeMap = BTreeMap::new(); + let mut by_kind: BTreeMap = BTreeMap::new(); + let mut by_change: BTreeMap = BTreeMap::new(); + for (track, places) in placed { + let Some(structure) = &track.structure else { continue }; + let cued: HashSet = + places.iter().filter(|p| p.on_beat).filter_map(|p| Beats::try_from(p.beat).ok()).collect(); + let mut previous_kind = String::new(); + for (start, name) in phrase_boundaries(structure) { + let carries_cue = usize::from(cued.contains(&start)); + let kind = name.split('#').next().unwrap_or_default().to_owned(); + let change = if kind == previous_kind { "same kind continues" } else { "kind changes" }.to_owned(); + previous_kind.clone_from(&kind); + for (key, totals) in [(name, &mut by_anchor), (kind, &mut by_kind), (change, &mut by_change)] { + let (seen, cued) = totals.entry(key).or_default(); + *seen += 1; + *cued += carries_cue; + } + } + } + for (title, totals, limit) in [ + ("by change", by_change, usize::MAX), + ("by kind", by_kind, usize::MAX), + ("by occurrence", by_anchor, TOP_BOUNDARIES), + ] { + println!(" {title}:"); + let mut rows: Vec<_> = totals.into_iter().collect(); + rows.sort_by_key(|(_, (seen, _))| Reverse(*seen)); + for (name, (seen, cued)) in rows.into_iter().take(limit) { + println!(" {name:<10} {seen:>4} found {} cued", percent(cued, seen)); + } + } +} + +fn report_slots(placed: &[(&SurveyedTrack, Vec)]) { + println!("\n== Hot cue slots: nearest rekordbox phrase =="); + let mut by_slot: BTreeMap> = BTreeMap::new(); + for place in placed.iter().flat_map(|(_, places)| places) { + if let Some(slot) = place.hot_slot { + by_slot.entry(slot).or_default().push(place); + } + } + for (slot, places) in by_slot { + let position = median(places.iter().map(|p| p.track_fraction).collect()); + println!("{slot}: {} cues, median at {:.0}% of the track", places.len(), position * 100.0); + print_anchors(&places); + } +} + +fn print_anchors(places: &[&Placement]) { + let anchors = places + .iter() + .filter_map(|p| p.anchor.as_ref()) + .map(|a| format!("{} {}", a.name, describe_offset(a.beats_after))); + for (anchor, count) in tally(anchors).into_iter().take(TOP_ANCHORS) { + println!(" {count:>4} {anchor}"); + } +} + +fn report_memory(placed: &[(&SurveyedTrack, Vec)]) { + println!("\n== Memory cues =="); + let memory: Vec<&Placement> = + placed.iter().flat_map(|(_, places)| places).filter(|p| p.hot_slot.is_none()).collect(); + print_anchors(&memory); + if placed.iter().flat_map(|(_, places)| places).all(|p| p.hot_slot.is_none()) { + return; + } + let to_next_hot = placed.iter().flat_map(|(_, places)| { + let hot: Vec = places.iter().filter(|p| p.hot_slot.is_some()).map(|p| p.beat).collect(); + places.iter().filter(|p| p.hot_slot.is_none()).map(move |memory| { + hot.iter().filter(|&&beat| beat >= memory.beat).min().map_or_else( + || "no hot cue after".to_owned(), + |&beat| { + format!("{} before a hot cue", describe_offset(Beats::try_from(beat - memory.beat).unwrap_or(0))) + }, + ) + }) + }); + println!(" distance to the next hot cue:"); + for (distance, count) in tally(to_next_hot).into_iter().take(TOP_ANCHORS) { + println!(" {count:>4} {distance}"); + } +} + +fn report_gaps(placed: &[(&SurveyedTrack, Vec)]) { + println!("\n== Gaps between neighbouring cues, in bars =="); + let gaps = placed.iter().flat_map(|(_, places)| { + let mut beats: Vec = places.iter().map(|p| p.beat).collect(); + beats.sort_unstable(); + beats.dedup(); + beats + .windows(2) + .map(|pair| describe_offset(Beats::try_from(pair[1] - pair[0]).unwrap_or(0))) + .collect::>() + }); + for (gap, count) in tally(gaps).into_iter().take(10) { + println!(" {count:>4} {gap}"); + } +} From c38d1caa0fe85e6838ee5500c720e885ecbe9e89 Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 14:36:34 +0000 Subject: [PATCH 02/25] Format the native crates with rustfmt rustfmt.toml matches the app's 120-column Prettier width. Co-Authored-By: Claude Opus 5.5 --- native/crates/es-analyse/src/attack.rs | 28 +- native/crates/es-analyse/src/downbeat.rs | 26 +- native/crates/es-analyse/src/lib.rs | 38 +- native/crates/es-analyse/src/onset.rs | 16 +- native/crates/es-analyse/src/spectrum.rs | 58 +-- native/crates/es-analyse/src/tempo.rs | 46 +- native/crates/es-analyse/src/waveform.rs | 69 ++- native/crates/es-backup/src/lib.rs | 73 ++- native/crates/es-backup/src/tests.rs | 14 +- native/crates/es-convert/src/inspect.rs | 60 ++- native/crates/es-convert/src/lib.rs | 22 +- native/crates/es-deck/src/block.rs | 7 +- native/crates/es-deck/src/clock.rs | 22 +- native/crates/es-deck/src/deck.rs | 55 +-- native/crates/es-deck/src/fade.rs | 6 +- native/crates/es-deck/src/isolator.rs | 26 +- native/crates/es-deck/src/lib.rs | 121 +---- native/crates/es-deck/src/reader.rs | 41 +- native/crates/es-deck/src/scrub.rs | 81 +--- native/crates/es-deck/src/sink.rs | 119 ++--- native/crates/es-deck/src/smooth.rs | 5 +- native/crates/es-deck/src/sync.rs | 56 +-- native/crates/es-deck/src/tempo.rs | 44 +- native/crates/es-deck/tests/common/mod.rs | 17 +- native/crates/es-deck/tests/engine.rs | 82 +--- native/crates/es-deck/tests/key.rs | 15 +- native/crates/es-deck/tests/mix.rs | 36 +- native/crates/es-deck/tests/scrub.rs | 28 +- native/crates/es-deck/tests/sync.rs | 55 +-- native/crates/es-deck/tests/tempo.rs | 15 +- native/crates/es-deck/tests/timing.rs | 58 +-- native/crates/es-decode/src/lib.rs | 68 +-- native/crates/es-engine/src/analysis.rs | 41 +- native/crates/es-engine/src/browse.rs | 11 +- native/crates/es-engine/src/convert.rs | 23 +- native/crates/es-engine/src/device_import.rs | 142 +++++- native/crates/es-engine/src/import.rs | 6 +- native/crates/es-engine/src/lib.rs | 2 +- native/crates/es-engine/src/library.rs | 446 +++++------------- native/crates/es-engine/src/place.rs | 27 +- native/crates/es-engine/src/relocate.rs | 18 +- native/crates/es-engine/src/sync.rs | 98 ++-- native/crates/es-engine/tests/analysis.rs | 14 +- native/crates/es-engine/tests/convert.rs | 29 +- .../crates/es-engine/tests/device_import.rs | 55 ++- native/crates/es-engine/tests/import.rs | 2 +- native/crates/es-engine/tests/relocate.rs | 25 +- native/crates/es-engine/tests/sync.rs | 16 +- native/crates/es-index/examples/dump.rs | 3 +- native/crates/es-index/src/detail.rs | 25 +- native/crates/es-index/src/device.rs | 55 ++- native/crates/es-index/src/lib.rs | 6 +- native/crates/es-index/tests/rows.rs | 9 +- native/crates/es-node/src/lib.rs | 42 +- native/crates/es-node/src/library.rs | 101 ++-- native/crates/es-node/src/usb.rs | 55 ++- native/crates/es-node/src/usb_settings.rs | 24 +- native/crates/es-tags/src/lib.rs | 43 +- native/crates/es-tags/tests/write.rs | 5 +- native/crates/es-usb/src/convert.rs | 15 +- native/crates/es-usb/src/main.rs | 22 +- native/crates/es-wave/src/lib.rs | 137 +----- native/crates/es-wave/tests/parity.rs | 53 +-- native/rustfmt.toml | 2 + 64 files changed, 1255 insertions(+), 1704 deletions(-) create mode 100644 native/rustfmt.toml diff --git a/native/crates/es-analyse/src/attack.rs b/native/crates/es-analyse/src/attack.rs index ea24119..0a2b09c 100644 --- a/native/crates/es-analyse/src/attack.rs +++ b/native/crates/es-analyse/src/attack.rs @@ -45,19 +45,9 @@ impl Attacks { } db.push((10.0 * (energy / chunk.len() as f64 + 1e-10).log10()) as f32); } - let rise = (0..db.len()) - .map(|j| { - if j < RISE_SPAN { - 0.0 - } else { - (db[j] - db[j - RISE_SPAN]).max(0.0) - } - }) - .collect(); - Self { - rise, - step: block as f64 / sample_rate, - } + let rise = + (0..db.len()).map(|j| if j < RISE_SPAN { 0.0 } else { (db[j] - db[j - RISE_SPAN]).max(0.0) }).collect(); + Self { rise, step: block as f64 / sample_rate } } /// The start of the strongest transient within `reach` seconds of `time`. @@ -69,9 +59,10 @@ impl Attacks { if lo >= hi { return None; } - let (peak_at, peak) = (lo..=hi) - .map(|j| (j, self.rise[j])) - .fold((lo, 0.0f32), |best, cur| if cur.1 > best.1 { cur } else { best }); + let (peak_at, peak) = + (lo..=hi) + .map(|j| (j, self.rise[j])) + .fold((lo, 0.0f32), |best, cur| if cur.1 > best.1 { cur } else { best }); if peak < MIN_RISE_DB { return None; } @@ -83,9 +74,6 @@ impl Attacks { } // The rise at step j spans the RISE_SPAN steps before it, so the hit starts there. let start = onset.saturating_sub(RISE_SPAN - 1); - Some(Hit { - time: start as f64 * self.step + BEAT_AFTER_ONSET, - strength: peak, - }) + Some(Hit { time: start as f64 * self.step + BEAT_AFTER_ONSET, strength: peak }) } } diff --git a/native/crates/es-analyse/src/downbeat.rs b/native/crates/es-analyse/src/downbeat.rs index a61b3f7..89cd6ca 100644 --- a/native/crates/es-analyse/src/downbeat.rs +++ b/native/crates/es-analyse/src/downbeat.rs @@ -67,10 +67,8 @@ fn profiles(stft: &Stft, beats: &[f64], low_onset: &dyn Fn(f64) -> f64) -> Profi for f in f0..f1.min(stft.frames) { let frame = stft.frame(f); for b in 0..BANDS { - bands[b] += frame[edges[b]..edges[b + 1].max(edges[b] + 1)] - .iter() - .map(|&m| f64::from(m * m)) - .sum::(); + bands[b] += + frame[edges[b]..edges[b + 1].max(edges[b] + 1)].iter().map(|&m| f64::from(m * m)).sum::(); } for (bin, p) in pitch.iter().enumerate() { if let Some(pc) = p { @@ -123,9 +121,7 @@ fn novelty(p: &Profiles) -> Vec { } } } - let chord: Vec = (0..n) - .map(|b| if b == 0 { 0.0 } else { distance(&p.chroma[b], &p.chroma[b - 1]) }) - .collect(); + let chord: Vec = (0..n).map(|b| if b == 0 { 0.0 } else { distance(&p.chroma[b], &p.chroma[b - 1]) }).collect(); for (series, weight) in [(&chord, CHORD_WEIGHT), (&p.kick, KICK_WEIGHT)] { let mean = series.iter().sum::() / n.max(1) as f64; let sd = (series.iter().map(|r| (r - mean) * (r - mean)).sum::() / n.max(1) as f64).sqrt(); @@ -140,11 +136,7 @@ fn novelty(p: &Profiles) -> Vec { /// The first beat whose loudness reaches a fair share of the track's typical loudness. fn first_sounding(p: &Profiles) -> usize { - let loudness: Vec = p - .bands - .iter() - .map(|b| b.iter().map(|db| 10f64.powf(*db)).sum::().log10()) - .collect(); + let loudness: Vec = p.bands.iter().map(|b| b.iter().map(|db| 10f64.powf(*db)).sum::().log10()).collect(); let mut sorted = loudness.clone(); sorted.sort_by(f64::total_cmp); let typical = sorted[sorted.len() / 2]; @@ -165,16 +157,10 @@ pub fn first_downbeat(stft: &Stft, beats: &[f64], low_onset: &dyn Fn(f64) -> f64 // Most tracks start on a bar line, so the first beat with sound in it gets a head start. let spread = scores.iter().copied().fold(f64::MIN, f64::max) - scores.iter().copied().fold(f64::MAX, f64::min); scores[first_sounding(&p) % 4] += START_WEIGHT * spread; - scores - .iter() - .enumerate() - .fold((0, f64::MIN), |best, (i, &s)| if s > best.1 { (i, s) } else { best }) - .0 + scores.iter().enumerate().fold((0, f64::MIN), |best, (i, &s)| if s > best.1 { (i, s) } else { best }).0 } /// Beat numbers 1 to 4 for `count` beats, the first bar starting at `first`. pub fn numbers(count: usize, first: usize) -> Vec { - (0..count) - .map(|i| ((i + 4 - first % 4) % 4 + 1) as u8) - .collect() + (0..count).map(|i| ((i + 4 - first % 4) % 4 + 1) as u8).collect() } diff --git a/native/crates/es-analyse/src/lib.rs b/native/crates/es-analyse/src/lib.rs index 062ce2e..c7b3816 100644 --- a/native/crates/es-analyse/src/lib.rs +++ b/native/crates/es-analyse/src/lib.rs @@ -33,11 +33,7 @@ pub struct Options { impl Default for Options { fn default() -> Self { - Self { - tempo: TempoOptions::default(), - grid: true, - key: true, - } + Self { tempo: TempoOptions::default(), grid: true, key: true } } } @@ -90,13 +86,7 @@ pub fn analyse_samples(mono: &[f32], sample_rate: f64, options: &Options) -> Ana || options.key.then(|| key::analyse(mono, sample_rate)).flatten(), ); let (bpm, beats) = grid.unwrap_or_default(); - Analysis { - duration, - bpm, - beats, - key, - waveform: waveform::features(mono, sample_rate), - } + Analysis { duration, bpm, beats, key, waveform: waveform::features(mono, sample_rate) } } fn beatgrid(mono: &[f32], sample_rate: f64, duration: f64, opts: &TempoOptions) -> Option<(f64, Vec)> { @@ -106,19 +96,8 @@ fn beatgrid(mono: &[f32], sample_rate: f64, duration: f64, opts: &TempoOptions) ); let onset = onset::smooth(&onset::flux(&stft, ONSET_HZ.0, ONSET_HZ.1), 1); let low = onset::smooth(&onset::flux(&stft, KICK_HZ.0, KICK_HZ.1), 1); - let bands: Vec<_> = tempo::PHASE_BANDS - .iter() - .map(|&(a, b)| onset::smooth(&onset::flux(&stft, a, b), 1)) - .collect(); - let grid = tempo::estimate( - &tempo::Inputs { - bands: &bands, - onset: &onset, - attacks: &attacks, - duration, - }, - opts, - )?; + let bands: Vec<_> = tempo::PHASE_BANDS.iter().map(|&(a, b)| onset::smooth(&onset::flux(&stft, a, b), 1)).collect(); + let grid = tempo::estimate(&tempo::Inputs { bands: &bands, onset: &onset, attacks: &attacks, duration }, opts)?; let first = downbeat::first_downbeat(&stft, &grid.beats, &|t| f64::from(low.at_time(t))); let numbers = downbeat::numbers(grid.beats.len(), first); let beats = grid @@ -200,13 +179,8 @@ mod tests { fn dynamic_follows_a_tempo_change() { let mut audio = track(120.0, 48.0, 0.0, &[220.0]); audio.extend(track(128.0, 48.0, 0.0, &[220.0])); - let options = Options { - tempo: TempoOptions { - dynamic: true, - ..TempoOptions::default() - }, - ..Options::default() - }; + let options = + Options { tempo: TempoOptions { dynamic: true, ..TempoOptions::default() }, ..Options::default() }; let a = analyse_samples(&audio, RATE, &options); let tempos: Vec = a.beats.iter().map(|b| b.tempo_x100).collect(); assert_eq!(tempos.first(), Some(&12_000)); diff --git a/native/crates/es-analyse/src/onset.rs b/native/crates/es-analyse/src/onset.rs index b9284f9..e9cfd10 100644 --- a/native/crates/es-analyse/src/onset.rs +++ b/native/crates/es-analyse/src/onset.rs @@ -70,11 +70,7 @@ pub fn flux(stft: &Stft, lo_hz: f64, hi_hz: f64) -> Envelope { raw.push(sum); } let values = normalise(&subtract_local_mean(&raw, MEAN_REACH)); - Envelope { - values, - rate: stft.sample_rate / stft.hop as f64, - start: (stft.frame / 2) as f64 / stft.sample_rate, - } + Envelope { values, rate: stft.sample_rate / stft.hop as f64, start: (stft.frame / 2) as f64 / stft.sample_rate } } pub fn subtract_local_mean(raw: &[f32], reach: usize) -> Vec { @@ -104,9 +100,7 @@ pub fn normalise(values: &[f32]) -> Vec { /// Smooths with a small triangular kernel, so a grid point a frame off still finds its onset. pub fn smooth(env: &Envelope, reach: usize) -> Envelope { let n = env.values.len(); - let weights: Vec = (0..=reach * 2) - .map(|i| (reach + 1) as f32 - (i as f32 - reach as f32).abs()) - .collect(); + let weights: Vec = (0..=reach * 2).map(|i| (reach + 1) as f32 - (i as f32 - reach as f32).abs()).collect(); let total: f32 = weights.iter().sum(); let values = (0..n) .map(|i| { @@ -120,9 +114,5 @@ pub fn smooth(env: &Envelope, reach: usize) -> Envelope { sum / total }) .collect(); - Envelope { - values, - rate: env.rate, - start: env.start, - } + Envelope { values, rate: env.rate, start: env.start } } diff --git a/native/crates/es-analyse/src/spectrum.rs b/native/crates/es-analyse/src/spectrum.rs index 69fb5fa..7b04ae8 100644 --- a/native/crates/es-analyse/src/spectrum.rs +++ b/native/crates/es-analyse/src/spectrum.rs @@ -32,54 +32,36 @@ impl Stft { } pub fn hann(n: usize) -> Vec { - (0..n) - .map(|i| 0.5 - 0.5 * (2.0 * PI * i as f32 / n as f32).cos()) - .collect() + (0..n).map(|i| 0.5 - 0.5 * (2.0 * PI * i as f32 / n as f32).cos()).collect() } /// Magnitude spectra of `samples` in frames of `frame` every `hop` samples, Hann windowed. /// Frames run past the end with zeros, so the last samples are covered. pub fn stft(samples: &[f32], sample_rate: f64, frame: usize, hop: usize) -> Stft { - let frames = if samples.is_empty() { - 0 - } else { - samples.len().div_ceil(hop) - }; + let frames = if samples.is_empty() { 0 } else { samples.len().div_ceil(hop) }; let bins = frame / 2 + 1; let window = hann(frame); // A full-scale sine peaks at 1, whatever the frame size. let scale = 2.0 / window.iter().sum::(); let fft: Arc> = RealFftPlanner::::new().plan_fft_forward(frame); let mut mags = vec![0.0f32; frames * bins]; - mags.par_chunks_mut(bins * 64) - .enumerate() - .for_each(|(chunk, out)| { - let mut input = fft.make_input_vec(); - let mut spectrum = fft.make_output_vec(); - let mut scratch = fft.make_scratch_vec(); - for (j, row) in out.chunks_mut(bins).enumerate() { - let t = chunk * 64 + j; - let start = t * hop; - for (i, slot) in input.iter_mut().enumerate() { - *slot = samples.get(start + i).copied().unwrap_or(0.0) * window[i]; - } - if fft - .process_with_scratch(&mut input, &mut spectrum, &mut scratch) - .is_err() - { - continue; - } - for (m, c) in row.iter_mut().zip(&spectrum) { - *m = c.norm() * scale; - } + mags.par_chunks_mut(bins * 64).enumerate().for_each(|(chunk, out)| { + let mut input = fft.make_input_vec(); + let mut spectrum = fft.make_output_vec(); + let mut scratch = fft.make_scratch_vec(); + for (j, row) in out.chunks_mut(bins).enumerate() { + let t = chunk * 64 + j; + let start = t * hop; + for (i, slot) in input.iter_mut().enumerate() { + *slot = samples.get(start + i).copied().unwrap_or(0.0) * window[i]; } - }); - Stft { - frame, - hop, - sample_rate, - mags, - bins, - frames, - } + if fft.process_with_scratch(&mut input, &mut spectrum, &mut scratch).is_err() { + continue; + } + for (m, c) in row.iter_mut().zip(&spectrum) { + *m = c.norm() * scale; + } + } + }); + Stft { frame, hop, sample_rate, mags, bins, frames } } diff --git a/native/crates/es-analyse/src/tempo.rs b/native/crates/es-analyse/src/tempo.rs index c8399dc..89868bf 100644 --- a/native/crates/es-analyse/src/tempo.rs +++ b/native/crates/es-analyse/src/tempo.rs @@ -25,13 +25,7 @@ pub struct TempoOptions { impl Default for TempoOptions { fn default() -> Self { - Self { - min_bpm: 70.0, - max_bpm: 180.0, - dynamic: false, - high_precision: true, - round_bpm: true, - } + Self { min_bpm: 70.0, max_bpm: 180.0, dynamic: false, high_precision: true, round_bpm: true } } } @@ -58,7 +52,8 @@ const BEAT_AFTER_PEAK: f64 = 0.002; /// Hits further than this share of a period from the first fit are dropped before refitting. const OUTLIER_SHARE: f64 = 0.04; /// Bands whose onsets vote on whether a grid sits on the beat or the off-beat, in Hz. -pub const PHASE_BANDS: [(f64, f64); 5] = [(60.0, 120.0), (120.0, 250.0), (250.0, 1_000.0), (1_000.0, 4_000.0), (4_000.0, 16_000.0)]; +pub const PHASE_BANDS: [(f64, f64); 5] = + [(60.0, 120.0), (120.0, 250.0), (250.0, 1_000.0), (1_000.0, 4_000.0), (4_000.0, 16_000.0)]; /// Logistic weights for those votes, fitted to rekordbox's grids on a few hundred tracks: kick /// bodies and claps mark the beat, hats the off-beat. const OFFBEAT_WEIGHTS: [f64; 5] = [0.635, -1.409, -3.101, -2.652, 2.917]; @@ -139,9 +134,7 @@ fn autocorrelation(values: &[f32], max_lag: usize) -> Vec { return vec![0.0; max_lag + 1]; } let zero = out[0].max(1e-12); - (0..=max_lag.min(n - 1)) - .map(|lag| out[lag] / zero * n as f32 / (n - lag) as f32) - .collect() + (0..=max_lag.min(n - 1)).map(|lag| out[lag] / zero * n as f32 / (n - lag) as f32).collect() } fn interp(values: &[f32], x: f64) -> f64 { @@ -164,9 +157,7 @@ fn coarse_bpm(env: &Envelope, opts: &TempoOptions) -> Option { let acf = autocorrelation(&env.values, max_lag); let score = |bpm: f64| { let lag = 60.0 * env.rate / bpm; - let comb: f64 = (1..=ACF_MULTIPLES) - .map(|k| interp(&acf, lag * k as f64) / k as f64) - .sum(); + let comb: f64 = (1..=ACF_MULTIPLES).map(|k| interp(&acf, lag * k as f64) / k as f64).sum(); comb.max(0.0) * prior(bpm).powf(TIE_PRIOR) }; let lo = opts.min_bpm / 2.0; @@ -303,11 +294,7 @@ fn envelope_peak(env: &Envelope, time: f64) -> Option<(f64, f64)> { if at < 0 || best <= 0.0 { return None; } - let (a, b, c) = ( - f64::from(env.values[at as usize - 1]), - f64::from(best), - f64::from(env.values[at as usize + 1]), - ); + let (a, b, c) = (f64::from(env.values[at as usize - 1]), f64::from(best), f64::from(env.values[at as usize + 1])); let denom = a - 2.0 * b + c; let shift = if denom.abs() > 1e-12 { 0.5 * (a - c) / denom } else { 0.0 }; Some((env.time(at as f64 + shift.clamp(-0.5, 0.5)) + BEAT_AFTER_PEAK, b)) @@ -341,7 +328,14 @@ fn is_offbeat(inputs: &Inputs, period: f64, phase: f64, from: f64, to: f64) -> b } /// Fits one constant-tempo segment over `from..to`, starting from a rough period. -fn fit_segment(inputs: &Inputs, rough_period: f64, spread: f64, from: f64, to: f64, opts: &TempoOptions) -> Option { +fn fit_segment( + inputs: &Inputs, + rough_period: f64, + spread: f64, + from: f64, + to: f64, + opts: &TempoOptions, +) -> Option { let (period, mut phase, score) = comb_fit(inputs.onset, rough_period, spread, from, to); if score <= 0.0 { return None; @@ -356,10 +350,7 @@ fn fit_segment(inputs: &Inputs, rough_period: f64, spread: f64, from: f64, to: f for k in first..=last { let predicted = phase + k as f64 * period; let found = if opts.high_precision { - inputs - .attacks - .near(predicted, period * ATTACK_REACH) - .map(|hit| (hit.time, f64::from(hit.strength))) + inputs.attacks.near(predicted, period * ATTACK_REACH).map(|hit| (hit.time, f64::from(hit.strength))) } else { envelope_peak(inputs.onset, predicted) }; @@ -516,10 +507,5 @@ pub fn estimate(inputs: &Inputs, opts: &TempoOptions) -> Option { (to - s.from, s.bpm()) }) .fold((f64::MIN, bpm), |a, b| if b.0 > a.0 { b } else { a }); - Some(Grid { - bpm: longest.1, - segments, - beats, - tempos, - }) + Some(Grid { bpm: longest.1, segments, beats, tempos }) } diff --git a/native/crates/es-analyse/src/waveform.rs b/native/crates/es-analyse/src/waveform.rs index 6b12311..fb4f87f 100644 --- a/native/crates/es-analyse/src/waveform.rs +++ b/native/crates/es-analyse/src/waveform.rs @@ -38,12 +38,7 @@ impl Biquad { Pass::Low => ((1.0 - cos) / 2.0, 1.0 - cos), Pass::High => ((1.0 + cos) / 2.0, -(1.0 + cos)), }; - Self { - b: [b0 / a0, b1 / a0, b0 / a0], - a: [-2.0 * cos / a0, (1.0 - alpha) / a0], - x: [0.0; 2], - y: [0.0; 2], - } + Self { b: [b0 / a0, b1 / a0, b0 / a0], a: [-2.0 * cos / a0, (1.0 - alpha) / a0], x: [0.0; 2], y: [0.0; 2] } } fn run(&mut self, x: f64) -> f64 { @@ -69,41 +64,39 @@ pub fn features(mono: &[f32], sample_rate: f64) -> Vec { let parts = rayon::current_num_threads().max(1); let per_part = count.div_ceil(parts).max(1); let mut out = vec![0u8; count * LANES]; - out.par_chunks_mut(per_part * LANES) - .enumerate() - .for_each(|(part, chunk)| { - let first = part * per_part; - let mut low = Biquad::new(Pass::Low, sample_rate, LOW_HZ); - let mut mid_hp = Biquad::new(Pass::High, sample_rate, LOW_HZ); - let mut mid_lp = Biquad::new(Pass::Low, sample_rate, HIGH_HZ); - let mut high = Biquad::new(Pass::High, sample_rate, HIGH_HZ); - let start = (first as f64 * step).floor() as usize; - for &x in &mono[start.saturating_sub(warmup)..start.min(mono.len())] { + out.par_chunks_mut(per_part * LANES).enumerate().for_each(|(part, chunk)| { + let first = part * per_part; + let mut low = Biquad::new(Pass::Low, sample_rate, LOW_HZ); + let mut mid_hp = Biquad::new(Pass::High, sample_rate, LOW_HZ); + let mut mid_lp = Biquad::new(Pass::Low, sample_rate, HIGH_HZ); + let mut high = Biquad::new(Pass::High, sample_rate, HIGH_HZ); + let start = (first as f64 * step).floor() as usize; + for &x in &mono[start.saturating_sub(warmup)..start.min(mono.len())] { + let x = f64::from(x); + low.run(x); + mid_lp.run(mid_hp.run(x)); + high.run(x); + } + for (j, entry) in chunk.chunks_mut(LANES).enumerate() { + let k = first + j; + let a = ((k as f64 * step).floor() as usize).min(mono.len()); + let b = (((k + 1) as f64 * step).floor() as usize).min(mono.len()); + let mut peak = [0.0f64; 4]; + let mut energy = [0.0f64; 4]; + for &x in &mono[a..b] { let x = f64::from(x); - low.run(x); - mid_lp.run(mid_hp.run(x)); - high.run(x); - } - for (j, entry) in chunk.chunks_mut(LANES).enumerate() { - let k = first + j; - let a = ((k as f64 * step).floor() as usize).min(mono.len()); - let b = (((k + 1) as f64 * step).floor() as usize).min(mono.len()); - let mut peak = [0.0f64; 4]; - let mut energy = [0.0f64; 4]; - for &x in &mono[a..b] { - let x = f64::from(x); - let v = [x, low.run(x), mid_lp.run(mid_hp.run(x)), high.run(x)]; - for i in 0..4 { - peak[i] = peak[i].max(v[i].abs()); - energy[i] += v[i] * v[i]; - } - } - let n = (b - a).max(1) as f64; + let v = [x, low.run(x), mid_lp.run(mid_hp.run(x)), high.run(x)]; for i in 0..4 { - entry[i * 2] = quantise(peak[i]); - entry[i * 2 + 1] = quantise((energy[i] / n).sqrt() * std::f64::consts::SQRT_2); + peak[i] = peak[i].max(v[i].abs()); + energy[i] += v[i] * v[i]; } } - }); + let n = (b - a).max(1) as f64; + for i in 0..4 { + entry[i * 2] = quantise(peak[i]); + entry[i * 2 + 1] = quantise((energy[i] / n).sqrt() * std::f64::consts::SQRT_2); + } + } + }); out } diff --git a/native/crates/es-backup/src/lib.rs b/native/crates/es-backup/src/lib.rs index d8f94e8..8436be1 100644 --- a/native/crates/es-backup/src/lib.rs +++ b/native/crates/es-backup/src/lib.rs @@ -182,14 +182,16 @@ fn is_automatic_archive_name(path: &Path) -> bool { let Some(date) = parts.next() else { return false }; let Some(time) = parts.next() else { return false }; let Some(reason) = parts.next() else { return false }; - if date.len() != 8 || !date.bytes().all(|byte| byte.is_ascii_digit()) || time.len() != 6 || !time.bytes().all(|byte| byte.is_ascii_digit()) { + if date.len() != 8 + || !date.bytes().all(|byte| byte.is_ascii_digit()) + || time.len() != 6 + || !time.bytes().all(|byte| byte.is_ascii_digit()) + { return false; } AUTO_REASONS.iter().any(|automatic| { reason == *automatic - || reason - .strip_prefix(&format!("{automatic}-")) - .is_some_and(|suffix| suffix.parse::().is_ok()) + || reason.strip_prefix(&format!("{automatic}-")).is_some_and(|suffix| suffix.parse::().is_ok()) }) } @@ -203,10 +205,7 @@ fn automatic_archive_created(path: &Path) -> Option { return None; } let local = NaiveDateTime::parse_from_str(&format!("{date}-{time}"), "%Y%m%d-%H%M%S").ok()?; - Local - .from_local_datetime(&local) - .earliest() - .map(|created| created.timestamp_millis() as f64 / 1000.0) + Local.from_local_datetime(&local).earliest().map(|created| created.timestamp_millis() as f64 / 1000.0) } fn temp_dir(prefix: &str) -> Result { @@ -308,7 +307,9 @@ impl Backups { let mut candidates: Vec = entries .flatten() .map(|entry| entry.path()) - .filter(|path| path.extension().is_some_and(|extension| extension == "zip") && is_automatic_archive_name(path)) + .filter(|path| { + path.extension().is_some_and(|extension| extension == "zip") && is_automatic_archive_name(path) + }) .collect(); candidates.sort_by_key(|path| path.file_name().map(|name| name.to_os_string())); @@ -374,7 +375,13 @@ impl Backups { } } for path in share_files(dir) { - let arc = path.strip_prefix(dir).unwrap_or(&path).components().map(|c| c.as_os_str().to_string_lossy()).collect::>().join("/"); + let arc = path + .strip_prefix(dir) + .unwrap_or(&path) + .components() + .map(|c| c.as_os_str().to_string_lossy()) + .collect::>() + .join("/"); entries.push((path, arc)); } let manifest = json!({ @@ -417,7 +424,13 @@ impl Backups { fail(format!("The library could not be backed up because it failed its check: {last}")) } - fn write(&self, entries: &[(PathBuf, String)], manifest: Value, reason: &str, progress: Progress<'_>) -> Result { + fn write( + &self, + entries: &[(PathBuf, String)], + manifest: Value, + reason: &str, + progress: Progress<'_>, + ) -> Result { fs::create_dir_all(&self.root)?; let now = chrono::Local::now(); let base = format!("exportstudio-{}-{reason}", now.format("%Y%m%d-%H%M%S")); @@ -440,10 +453,16 @@ impl Backups { let total = entries.len(); let written = (|| -> Result<()> { let mut zip = ZipWriter::new(File::create(&partial)?); - let deflated = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).compression_level(Some(1)).large_file(true); + let deflated = SimpleFileOptions::default() + .compression_method(CompressionMethod::Deflated) + .compression_level(Some(1)) + .large_file(true); let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored).large_file(true); for (done, (path, arc)) in entries.iter().enumerate() { - let is_image = path.extension().and_then(|e| e.to_str()).is_some_and(|e| STORED_SUFFIXES.contains(&e.to_ascii_lowercase().as_str())); + let is_image = path + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| STORED_SUFFIXES.contains(&e.to_ascii_lowercase().as_str())); zip.start_file(arc, if is_image { stored } else { deflated })?; io::copy(&mut File::open(path)?, &mut zip)?; let done = done + 1; @@ -452,7 +471,9 @@ impl Backups { } } zip.start_file(MANIFEST, deflated)?; - zip.write_all(serde_json::to_string_pretty(&manifest).map_err(|e| Error::Message(e.to_string()))?.as_bytes())?; + zip.write_all( + serde_json::to_string_pretty(&manifest).map_err(|e| Error::Message(e.to_string()))?.as_bytes(), + )?; zip.finish()?; fs::rename(&partial, &final_path)?; Ok(()) @@ -503,10 +524,15 @@ impl Backups { progress(json!({ "stage": "checking", "reason": "restore", "done": 0, "total": 0 })); let mut zip = ZipArchive::new(File::open(&path)?)?; - let names: Vec = (0..zip.len()).filter_map(|i| zip.by_index(i).ok().filter(|f| !f.is_dir()).and_then(|f| f.name().ok().map(|n| n.into_owned()))).collect(); + let names: Vec = (0..zip.len()) + .filter_map(|i| { + zip.by_index(i).ok().filter(|f| !f.is_dir()).and_then(|f| f.name().ok().map(|n| n.into_owned())) + }) + .collect(); for name in &names { let mut sink = io::sink(); - io::copy(&mut zip.by_name(name)?, &mut sink).map_err(|_| Error::Message(format!("The backup is damaged ({name})")))?; + io::copy(&mut zip.by_name(name)?, &mut sink) + .map_err(|_| Error::Message(format!("The backup is damaged ({name})")))?; } if let Some(bad) = names.iter().find(|n| !safe_member(n)) { return fail(format!("The backup contains an unexpected file: {bad}")); @@ -527,7 +553,9 @@ impl Backups { io::copy(&mut zip.by_name(name)?, &mut File::create(&target)?)?; let done = done + 1; if done % 50 == 0 || done == members.len() { - progress(json!({ "stage": "extracting", "reason": "restore", "done": done, "total": members.len() })); + progress( + json!({ "stage": "extracting", "reason": "restore", "done": done, "total": members.len() }), + ); } } let name = src.file_name().unwrap_or_default().to_string_lossy().into_owned(); @@ -555,7 +583,8 @@ impl Backups { let db_dir = src.parent().unwrap_or_else(|| Path::new(".")); let name = src.file_name().unwrap_or_default().to_string_lossy().into_owned(); let replaced = self.root.join(format!("replaced-{stamp}")); - let mut targets: Vec<(String, String)> = DB_SUFFIXES.iter().map(|s| (format!("{name}{s}"), format!("{DB_ARC}{s}"))).collect(); + let mut targets: Vec<(String, String)> = + DB_SUFFIXES.iter().map(|s| (format!("{name}{s}"), format!("{DB_ARC}{s}"))).collect(); targets.extend(SIDE_FILES.iter().map(|n| ((*n).to_owned(), (*n).to_owned()))); targets.push(("share/PIONEER".into(), "share/PIONEER".into())); let mut moved_out = Vec::new(); @@ -619,7 +648,13 @@ impl Backups { walk(&replaced.join("share").join("PIONEER"), &mut share); share.sort(); for p in share { - let arc = p.strip_prefix(replaced).unwrap_or(&p).components().map(|c| c.as_os_str().to_string_lossy()).collect::>().join("/"); + let arc = p + .strip_prefix(replaced) + .unwrap_or(&p) + .components() + .map(|c| c.as_os_str().to_string_lossy()) + .collect::>() + .join("/"); entries.push((p, arc)); } if !replaced.join(&name).exists() || entries.is_empty() { diff --git a/native/crates/es-backup/src/tests.rs b/native/crates/es-backup/src/tests.rs index f7c856b..c1e2e71 100644 --- a/native/crates/es-backup/src/tests.rs +++ b/native/crates/es-backup/src/tests.rs @@ -19,7 +19,11 @@ fn scene() -> Scene { fs::write(db_dir.join("share/PIONEER/Artwork/abc/art.jpg"), b"jpeg").unwrap(); let verify = |p: &Path| { let text = fs::read_to_string(p).map_err(Error::from)?; - if text.contains("broken") { fail("The database is damaged") } else { Ok(Counts { tracks: 3, playlists: 2 }) } + if text.contains("broken") { + fail("The database is damaged") + } else { + Ok(Counts { tracks: 3, playlists: 2 }) + } }; let backups = Backups::new(dir.path().join("backups"), verify, || false); Scene { _dir: dir, db_dir, backups } @@ -33,10 +37,14 @@ fn quiet() -> impl Fn(Value) { fn a_manual_backup_holds_the_database_side_files_and_share_folder() { let s = scene(); let made = s.backups.create(&s.db_dir.join("master.db"), "manual", &quiet()).unwrap().unwrap(); - assert_eq!((made["tracks"].as_i64(), made["playlists"].as_i64(), made["files"].as_i64()), (Some(3), Some(2), Some(3))); + assert_eq!( + (made["tracks"].as_i64(), made["playlists"].as_i64(), made["files"].as_i64()), + (Some(3), Some(2), Some(3)) + ); let mut zip = ZipArchive::new(File::open(made["path"].as_str().unwrap()).unwrap()).unwrap(); - let mut names: Vec = (0..zip.len()).map(|i| zip.by_index(i).unwrap().name().unwrap().into_owned()).collect(); + let mut names: Vec = + (0..zip.len()).map(|i| zip.by_index(i).unwrap().name().unwrap().into_owned()).collect(); names.sort(); assert_eq!(names, ["manifest.json", "master.db", "masterPlaylists6.xml", "share/PIONEER/Artwork/abc/art.jpg"]); assert_eq!(s.backups.list(Some(&s.db_dir.join("master.db"))).len(), 1); diff --git a/native/crates/es-convert/src/inspect.rs b/native/crates/es-convert/src/inspect.rs index 3971f00..505769f 100644 --- a/native/crates/es-convert/src/inspect.rs +++ b/native/crates/es-convert/src/inspect.rs @@ -49,7 +49,8 @@ pub fn same_fingerprint(path: &Path, size: Option, mtime: Option<&str>) -> } let hinted_time: u128 = mtime?.trim().parse().ok()?; let meta = path.metadata().ok()?; - (i64::try_from(meta.len()).ok()? == hinted && nanos(&meta)? == hinted_time).then(|| (meta.len(), Some(hinted_time.to_string()))) + (i64::try_from(meta.len()).ok()? == hinted && nanos(&meta)? == hinted_time) + .then(|| (meta.len(), Some(hinted_time.to_string()))) } /// Header measurements for one local file. Missing and unreadable files have no audio. @@ -137,7 +138,12 @@ fn wav(file: &mut File, size: u64) -> std::io::Result> { if format == 0xFFFE && raw.len() >= 26 { format = u16::from_le_bytes([raw[24], raw[25]]); } - found = Some((format, u32::from(u16::from_le_bytes([raw[2], raw[3]])), le32(&raw[4..8]), u32::from(u16::from_le_bytes([raw[14], raw[15]])))); + found = Some(( + format, + u32::from(u16::from_le_bytes([raw[2], raw[3]])), + le32(&raw[4..8]), + u32::from(u16::from_le_bytes([raw[14], raw[15]])), + )); } } else if &head[..4] == b"data" { break; @@ -148,7 +154,14 @@ fn wav(file: &mut File, size: u64) -> std::io::Result> { } file.seek(SeekFrom::Start(next))?; } - Ok(found.map(|(format, channels, rate, bits)| Audio { kind: "WAV", sample_rate: rate, bit_depth: bits, channels, bitrate: 0, encoding: pcm(format) })) + Ok(found.map(|(format, channels, rate, bits)| Audio { + kind: "WAV", + sample_rate: rate, + bit_depth: bits, + channels, + bitrate: 0, + encoding: pcm(format), + })) } fn extended(raw: &[u8]) -> f64 { @@ -161,7 +174,11 @@ fn extended(raw: &[u8]) -> f64 { return 0.0; } let value = mantissa as f64 / (1u64 << 63) as f64 * 2f64.powi(exponent - 16383); - if raw[0] & 0x80 != 0 { -value } else { value } + if raw[0] & 0x80 != 0 { + -value + } else { + value + } } fn aiff(file: &mut File, size: u64, compressed: bool) -> std::io::Result> { @@ -185,14 +202,22 @@ fn aiff(file: &mut File, size: u64, compressed: bool) -> std::io::Result = if compressed && raw.len() >= 22 { raw[18..22].to_ascii_uppercase() } else { b"NONE".to_vec() }; + let compression: Vec = + if compressed && raw.len() >= 22 { raw[18..22].to_ascii_uppercase() } else { b"NONE".to_vec() }; let format = match compression.as_slice() { b"NONE" | b"TWOS" | b"SOWT" | b"RAW " => 1, b"FL32" | b"FL64" => 3, _ => 0, }; let rate = if rate == 0.0 { 0 } else { rate.round_ties_even() as u32 }; - return Ok(Some(Audio { kind: "AIFF", sample_rate: rate, bit_depth: bits, channels, bitrate: 0, encoding: pcm(format) })); + return Ok(Some(Audio { + kind: "AIFF", + sample_rate: rate, + bit_depth: bits, + channels, + bitrate: 0, + encoding: pcm(format), + })); } let next = pos + chunk + (chunk & 1); if chunk == 0 || next <= pos { @@ -264,7 +289,9 @@ fn mp4_walk(file: &mut File, end: u64, depth: u32, size: u64, out: &mut Mp4) -> return Ok(()); } match &kind { - b"moov" | b"trak" | b"mdia" | b"minf" | b"stbl" if depth < 6 => mp4_walk(file, box_end, depth + 1, size, out)?, + b"moov" | b"trak" | b"mdia" | b"minf" | b"stbl" if depth < 6 => { + mp4_walk(file, box_end, depth + 1, size, out)? + } b"mdhd" => { let version = read_exact_or_less(file, 1)?; let skip = if version.first() == Some(&0) { 12 } else { 20 }; @@ -323,7 +350,10 @@ fn mp3(file: &mut File, size: u64) -> std::io::Result> { let lead = read_exact_or_less(file, 10)?; let mut offset = 0u64; if lead.starts_with(b"ID3") && lead.len() >= 10 { - let tag = (u64::from(lead[6] & 0x7F) << 21) | (u64::from(lead[7] & 0x7F) << 14) | (u64::from(lead[8] & 0x7F) << 7) | u64::from(lead[9] & 0x7F); + let tag = (u64::from(lead[6] & 0x7F) << 21) + | (u64::from(lead[7] & 0x7F) << 14) + | (u64::from(lead[8] & 0x7F) << 7) + | u64::from(lead[9] & 0x7F); offset = 10 + tag; if lead[5] & 0x10 != 0 { offset += 10; @@ -345,7 +375,14 @@ fn mp3(file: &mut File, size: u64) -> std::io::Result> { const V2: [u32; 16] = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0]; let bitrate = if version == 3 { V1[bitrate_index] } else { V2[bitrate_index] }; let channels = if (frame[3] >> 6) & 3 == 3 { 1 } else { 2 }; - Ok(Some(Audio { kind: "MP3", sample_rate: RATES[version][rate_index], bit_depth: 0, channels, bitrate, encoding: "mp3" })) + Ok(Some(Audio { + kind: "MP3", + sample_rate: RATES[version][rate_index], + bit_depth: 0, + channels, + bitrate, + encoding: "mp3", + })) } #[cfg(test)] @@ -376,7 +413,10 @@ mod tests { std::fs::write(&path, wav_bytes(3, 32)).unwrap(); let found = inspect_file(&path); let audio = found.audio.unwrap(); - assert_eq!((audio.kind, audio.sample_rate, audio.bit_depth, audio.channels, audio.encoding), ("WAV", 44100, 32, 2, "float")); + assert_eq!( + (audio.kind, audio.sample_rate, audio.bit_depth, audio.channels, audio.encoding), + ("WAV", 44100, 32, 2, "float") + ); assert!(found.issues.is_empty()); } diff --git a/native/crates/es-convert/src/lib.rs b/native/crates/es-convert/src/lib.rs index 9f71ea8..420c758 100644 --- a/native/crates/es-convert/src/lib.rs +++ b/native/crates/es-convert/src/lib.rs @@ -34,7 +34,9 @@ pub struct Preset { fn whole(value: &serde_json::Value, key: &str, default: i64) -> i64 { match value.get(key) { - Some(v) => v.as_i64().or_else(|| v.as_str().and_then(|s| s.trim().parse().ok())).filter(|n| *n != 0).unwrap_or(default), + Some(v) => { + v.as_i64().or_else(|| v.as_str().and_then(|s| s.trim().parse().ok())).filter(|n| *n != 0).unwrap_or(default) + } None => default, } } @@ -105,8 +107,14 @@ fn codec_args(preset: &Preset) -> Vec { match preset.format { "wav" => vec!["-c:a".into(), format!("pcm_s{depth}le")], "aiff" => vec!["-c:a".into(), format!("pcm_s{depth}be")], - "flac" => [strings(&["-c:a", "flac", "-sample_fmt", if depth == 16 { "s16" } else { "s32" }]), raw(depth != 16)].concat(), - "alac" => [strings(&["-c:a", "alac", "-sample_fmt", if depth == 16 { "s16p" } else { "s32p" }]), raw(depth != 16)].concat(), + "flac" => { + [strings(&["-c:a", "flac", "-sample_fmt", if depth == 16 { "s16" } else { "s32" }]), raw(depth != 16)] + .concat() + } + "alac" => { + [strings(&["-c:a", "alac", "-sample_fmt", if depth == 16 { "s16p" } else { "s32p" }]), raw(depth != 16)] + .concat() + } "mp3" => vec!["-c:a".into(), "libmp3lame".into(), "-b:a".into(), format!("{}k", preset.bitrate.unwrap_or(320))], _ => vec!["-c:a".into(), "aac".into(), "-b:a".into(), format!("{}k", preset.bitrate.unwrap_or(320))], } @@ -183,9 +191,7 @@ fn run_ffmpeg(command: &[String], partial: &Path) -> Result<()> { // CREATE_NO_WINDOW: ffmpeg is a console program and the app has no console to share. #[cfg(windows)] std::os::windows::process::CommandExt::creation_flags(&mut ffmpeg, 0x0800_0000); - let mut child = ffmpeg - .spawn() - .map_err(|e| fail(format!("Could not start ffmpeg: {e}")))?; + let mut child = ffmpeg.spawn().map_err(|e| fail(format!("Could not start ffmpeg: {e}")))?; let mut stderr = child.stderr.take(); let reader = std::thread::spawn(move || { let mut text = String::new(); @@ -279,7 +285,9 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let file = dir.path().join("a.wav"); pcm_wav(&file); - let wav = |depth: i64, rate: i64| clean_preset(&json!({"format": "wav", "bitDepth": depth, "sampleRate": rate})).unwrap(); + let wav = |depth: i64, rate: i64| { + clean_preset(&json!({"format": "wav", "bitDepth": depth, "sampleRate": rate})).unwrap() + }; assert!(matches_format(&file, &wav(16, 44100))); assert!(matches_format(&file, &wav(24, 96000))); assert!(!matches_format(&file, &clean_preset(&json!({"format": "aiff"})).unwrap())); diff --git a/native/crates/es-deck/src/block.rs b/native/crates/es-deck/src/block.rs index 5dbf024..157898f 100644 --- a/native/crates/es-deck/src/block.rs +++ b/native/crates/es-deck/src/block.rs @@ -26,11 +26,6 @@ pub struct Block { impl Block { pub fn empty(generation: u32, position: u64) -> Self { - Self { - generation, - position, - frames: 0, - samples: [0.0; BLOCK_FRAMES * 2], - } + Self { generation, position, frames: 0, samples: [0.0; BLOCK_FRAMES * 2] } } } diff --git a/native/crates/es-deck/src/clock.rs b/native/crates/es-deck/src/clock.rs index b1593ab..9c97a87 100644 --- a/native/crates/es-deck/src/clock.rs +++ b/native/crates/es-deck/src/clock.rs @@ -115,9 +115,7 @@ impl DeckClock { /// Always before the first block of the new generation is pushed. pub fn bump_generation(&self) -> u32 { - self.generation - .fetch_add(1, Ordering::AcqRel) - .wrapping_add(1) + self.generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1) } pub fn sample_rate(&self) -> u32 { @@ -180,10 +178,7 @@ impl DeckClock { /// Makes `request` the only load whose result may be installed, and empties the deck. pub fn request_load(&self, request: u64) { - let _gate = self - .load_gate - .lock() - .unwrap_or_else(PoisonError::into_inner); + let _gate = self.load_gate.lock().unwrap_or_else(PoisonError::into_inner); self.requested_load.store(request, Ordering::Release); self.load_id.store(0, Ordering::Release); self.loaded.store(false, Ordering::Release); @@ -192,10 +187,7 @@ impl DeckClock { /// Publishes a finished load unless a newer one was asked for meanwhile. pub fn install_load(&self, request: u64) -> bool { - let _gate = self - .load_gate - .lock() - .unwrap_or_else(PoisonError::into_inner); + let _gate = self.load_gate.lock().unwrap_or_else(PoisonError::into_inner); if self.requested_load() != request { return false; } @@ -206,10 +198,7 @@ impl DeckClock { /// Whether a failed load still belongs to the current request. pub fn owns_load(&self, request: u64) -> bool { - let _gate = self - .load_gate - .lock() - .unwrap_or_else(PoisonError::into_inner); + let _gate = self.load_gate.lock().unwrap_or_else(PoisonError::into_inner); self.requested_load() == request } @@ -241,8 +230,7 @@ impl DeckClock { } pub fn set_looping(&self, on: bool) { - self.looping - .store(on && self.loop_range().is_some(), Ordering::Release); + self.looping.store(on && self.loop_range().is_some(), Ordering::Release); } /// The loop the deck is inside, if any. diff --git a/native/crates/es-deck/src/deck.rs b/native/crates/es-deck/src/deck.rs index 3305390..bbc478b 100644 --- a/native/crates/es-deck/src/deck.rs +++ b/native/crates/es-deck/src/deck.rs @@ -84,28 +84,23 @@ pub(crate) fn spawn( ) -> std::io::Result { let (tx, rx) = std::sync::mpsc::channel(); let worker_clock = Arc::clone(&clock); - std::thread::Builder::new() - .name(format!("es-deck-{deck}")) - .spawn(move || { - let mut worker = Worker { - deck, - clock: worker_clock, - producer, - device_rate, - events, - streamer: None, - generation: 0, - fresh: 0, - fresh_generation: 0, - scrub: None, - started: Instant::now(), - }; - worker.run(&rx); - })?; - Ok(DeckHandle { - commands: tx, - clock, - }) + std::thread::Builder::new().name(format!("es-deck-{deck}")).spawn(move || { + let mut worker = Worker { + deck, + clock: worker_clock, + producer, + device_rate, + events, + streamer: None, + generation: 0, + fresh: 0, + fresh_generation: 0, + scrub: None, + started: Instant::now(), + }; + worker.run(&rx); + })?; + Ok(DeckHandle { commands: tx, clock }) } struct Worker { @@ -180,11 +175,7 @@ impl Worker { } fn error(&self, load_id: u64, message: String) { - (self.events)(DeckEvent::Error { - deck: self.deck, - load_id, - message, - }); + (self.events)(DeckEvent::Error { deck: self.deck, load_id, message }); } fn load(&mut self, request: u64, path: &std::path::Path) { @@ -294,10 +285,8 @@ impl Worker { self.generation = self.clock.generation(); self.clock.set_end_of_stream(false); let head = self.clock.position() as f64; - self.scrub = Some(Scrub { - head: Scrubber::new(head, self.device_rate, self.now_ms()), - window: PcmWindow::default(), - }); + self.scrub = + Some(Scrub { head: Scrubber::new(head, self.device_rate, self.now_ms()), window: PcmWindow::default() }); } /// Keeps decoded audio around the scrub head: refilled after a jump, extended a step at a @@ -403,9 +392,7 @@ impl Worker { let start = streamer.position(); // Only up to the out point, so the jump lands on the frame. let room = active.map_or(BLOCK_FRAMES, |(_, to)| { - usize::try_from(to.saturating_sub(start)) - .unwrap_or(BLOCK_FRAMES) - .clamp(1, BLOCK_FRAMES) + usize::try_from(to.saturating_sub(start)).unwrap_or(BLOCK_FRAMES).clamp(1, BLOCK_FRAMES) }); let mut block = Block::empty(generation, start); let frames = match streamer.fill(&mut block.samples[..room * 2]) { diff --git a/native/crates/es-deck/src/fade.rs b/native/crates/es-deck/src/fade.rs index c6e165f..97e849e 100644 --- a/native/crates/es-deck/src/fade.rs +++ b/native/crates/es-deck/src/fade.rs @@ -28,11 +28,7 @@ impl Ramp { /// Moves one frame towards open or closed and returns that frame's gain. pub fn step(&mut self, open: bool) -> f32 { - self.at = if open { - (self.at + 1).min(FADE_FRAMES) - } else { - self.at.saturating_sub(1) - }; + self.at = if open { (self.at + 1).min(FADE_FRAMES) } else { self.at.saturating_sub(1) }; self.gain() } } diff --git a/native/crates/es-deck/src/isolator.rs b/native/crates/es-deck/src/isolator.rs index 056523e..8a20ced 100644 --- a/native/crates/es-deck/src/isolator.rs +++ b/native/crates/es-deck/src/isolator.rs @@ -46,20 +46,8 @@ impl Biquad { let (sin, cos) = w0.sin_cos(); let alpha = sin / (2.0 * q); let a0 = 1.0 + alpha; - let (b0, b1) = if high { - ((1.0 + cos) / 2.0, -(1.0 + cos)) - } else { - ((1.0 - cos) / 2.0, 1.0 - cos) - }; - Self { - b0: b0 / a0, - b1: b1 / a0, - b2: b0 / a0, - a1: -2.0 * cos / a0, - a2: (1.0 - alpha) / a0, - z1: 0.0, - z2: 0.0, - } + let (b0, b1) = if high { ((1.0 + cos) / 2.0, -(1.0 + cos)) } else { ((1.0 - cos) / 2.0, 1.0 - cos) }; + Self { b0: b0 / a0, b1: b1 / a0, b2: b0 / a0, a1: -2.0 * cos / a0, a2: (1.0 - alpha) / a0, z1: 0.0, z2: 0.0 } } fn step(&mut self, x: f64) -> f64 { @@ -81,10 +69,7 @@ impl Crossover { fn new(sample_rate: f64) -> Self { let low = Biquad::new(CROSSOVER_HZ, BUTTERWORTH_Q, sample_rate, false); let high = Biquad::new(CROSSOVER_HZ, BUTTERWORTH_Q, sample_rate, true); - Self { - low: [low; 2], - high: [high; 2], - } + Self { low: [low; 2], high: [high; 2] } } /// The input split into the band below the crossover and the rest. @@ -184,10 +169,7 @@ mod tests { fn killed_low_removes_the_bass_and_keeps_the_rest() { assert!(db(level_at(50.0, Some(0.0))) < -45.0, "50 Hz should be gone"); assert!(db(level_at(100.0, Some(0.0))) < -20.0, "100 Hz should be well down"); - assert!( - (db(level_at(200.0, Some(0.0))) + 6.0).abs() < 0.5, - "the crossover is 6 dB down" - ); + assert!((db(level_at(200.0, Some(0.0))) + 6.0).abs() < 0.5, "the crossover is 6 dB down"); assert!(db(level_at(1000.0, Some(0.0))).abs() < 0.1, "1 kHz is untouched"); } diff --git a/native/crates/es-deck/src/lib.rs b/native/crates/es-deck/src/lib.rs index 662fa99..f75e6b0 100644 --- a/native/crates/es-deck/src/lib.rs +++ b/native/crates/es-deck/src/lib.rs @@ -55,17 +55,8 @@ pub type DeckId = usize; #[derive(Debug, Clone)] pub enum DeckEvent { - Loaded { - deck: DeckId, - load_id: u64, - total_frames: u64, - sample_rate: u32, - }, - Error { - deck: DeckId, - load_id: u64, - message: String, - }, + Loaded { deck: DeckId, load_id: u64, total_frames: u64, sample_rate: u32 }, + Error { deck: DeckId, load_id: u64, message: String }, } /// Receives deck events. Called from a decode thread, never from the audio callback. @@ -101,9 +92,7 @@ const ISOLATOR_OFF: f32 = -1.0; impl Engine { /// `decks` decks on the system's default output. pub fn new(decks: usize, events: &EventSink) -> Result { - Self::with_sink(decks, events, |render| { - Ok(Arc::new(CpalSink::open(render)?) as Arc) - }) + Self::with_sink(decks, events, |render| Ok(Arc::new(CpalSink::open(render)?) as Arc)) } /// The same engine on a sink of the caller's choosing, which is how it is tested. @@ -111,8 +100,7 @@ impl Engine { where F: FnOnce(Render) -> Result>, { - let clocks: Vec> = - (0..decks).map(|_| Arc::new(DeckClock::default())).collect(); + let clocks: Vec> = (0..decks).map(|_| Arc::new(DeckClock::default())).collect(); let callback_clocks: Vec> = clocks.iter().map(Arc::clone).collect(); let sync = Arc::new(Mutex::new(BeatSync::new(decks, 0))); let callback_sync = Arc::clone(&sync); @@ -132,13 +120,9 @@ impl Engine { let master = Arc::new(AtomicU32::new(1.0_f32.to_bits())); let level = Arc::clone(&master); - let gains: Vec> = (0..decks) - .map(|_| Arc::new(AtomicU32::new(1.0_f32.to_bits()))) - .collect(); + let gains: Vec> = (0..decks).map(|_| Arc::new(AtomicU32::new(1.0_f32.to_bits()))).collect(); let deck_levels: Vec> = gains.iter().map(Arc::clone).collect(); - let lows: Vec> = (0..decks) - .map(|_| Arc::new(AtomicU32::new(ISOLATOR_OFF.to_bits()))) - .collect(); + let lows: Vec> = (0..decks).map(|_| Arc::new(AtomicU32::new(ISOLATOR_OFF.to_bits()))).collect(); let deck_lows: Vec> = lows.iter().map(Arc::clone).collect(); let mut isolators: Vec> = (0..decks).map(|_| None).collect(); let rate = Arc::new(AtomicU32::new(0)); @@ -156,12 +140,8 @@ impl Engine { if let Ok(mut sync) = callback_sync.try_lock() { sync.follow_tempo(&callback_clocks); } - for ((((reader, level), smooth), low), isolator) in readers - .iter_mut() - .zip(&deck_levels) - .zip(&mut deck_smoothed) - .zip(&deck_lows) - .zip(&mut isolators) + for ((((reader, level), smooth), low), isolator) in + readers.iter_mut().zip(&deck_levels).zip(&mut deck_smoothed).zip(&deck_lows).zip(&mut isolators) { let target = f32::from_bits(level.load(Ordering::Relaxed)); let smooth = smooth.get_or_insert_with(|| Smoothed::new(target, sample_rate, 10.0)); @@ -179,9 +159,8 @@ impl Engine { } } let target = f32::from_bits(level.load(Ordering::Relaxed)); - let smoothed = smoothed.get_or_insert_with(|| { - Smoothed::new(target, callback_rate.load(Ordering::Relaxed), 10.0) - }); + let smoothed = + smoothed.get_or_insert_with(|| Smoothed::new(target, callback_rate.load(Ordering::Relaxed), 10.0)); for frame in out.chunks_exact_mut(2) { let gain = smoothed.step(target); frame[0] = (frame[0] * gain).clamp(-1.0, 1.0); @@ -204,24 +183,9 @@ impl Engine { let mut handles = Vec::with_capacity(decks); for (id, (clock, producer)) in clocks.into_iter().zip(producers).enumerate() { clock.set_sample_rate(sample_rate); - handles.push(deck::spawn( - id, - clock, - producer, - sample_rate, - Arc::clone(events), - )?); - } - Ok(Self { - decks: handles, - sink, - sample_rate, - master, - gains, - lows, - sync, - timeline, - }) + handles.push(deck::spawn(id, clock, producer, sample_rate, Arc::clone(events))?); + } + Ok(Self { decks: handles, sink, sample_rate, master, gains, lows, sync, timeline }) } pub fn sample_rate(&self) -> u32 { @@ -246,10 +210,7 @@ impl Engine { let request = request.max(1); if let Some(handle) = self.deck(deck) { handle.clock().request_load(request); - handle.send(deck::Command::Load { - request, - path: PathBuf::from(path), - }); + handle.send(deck::Command::Load { request, path: PathBuf::from(path) }); } self.settle(); } @@ -302,19 +263,14 @@ impl Engine { .collect(); let link = lock(&self.sync).link(); if let Some((master, follower)) = link { - if [master, follower] - .iter() - .all(|d| ready.iter().any(|(r, _)| r == d)) - { + if [master, follower].iter().all(|d| ready.iter().any(|(r, _)| r == d)) { self.line_up_paused(follower); } } // Each deck may have just been moved. Wait (briefly) until all have the audio for where // they are now queued, so none starts a buffer late on an empty ring. let deadline = Instant::now() + READY_WAIT; - while ready.iter().any(|(_, handle)| !handle.clock().buffered()) - && Instant::now() < deadline - { + while ready.iter().any(|(_, handle)| !handle.clock().buffered()) && Instant::now() < deadline { std::thread::sleep(Duration::from_millis(1)); } // As with `play`, a deck that played to its end starts over. @@ -373,11 +329,7 @@ impl Engine { } let delta = (delta_ms * f64::from(self.sample_rate) / 1000.0).round() as i64; let frame = u64::try_from(clock.position() as i64 + delta).unwrap_or(0); - let keep_time = if clock.playing() && !clock.scrubbing() { - KeepTime::FromMove - } else { - KeepTime::No - }; + let keep_time = if clock.playing() && !clock.scrubbing() { KeepTime::FromMove } else { KeepTime::No }; self.move_to(deck, frame, keep_time); } @@ -422,11 +374,7 @@ impl Engine { } let frame = ms.max(0.0) * f64::from(self.sample_rate) / 1000.0; let total = clock.total(); - let frame = if total > 0 { - frame.min(total as f64) - } else { - frame - }; + let frame = if total > 0 { frame.min(total as f64) } else { frame }; clock.set_scrub_target(frame.round() as u64); handle.send(deck::Command::ScrubTo { frame, at_ms }); } @@ -451,10 +399,7 @@ impl Engine { fn jump(&self, deck: DeckId, frame: u64) { let playing = self.deck(deck).is_some_and(|d| d.clock().playing()); let moment = self.timeline.read(); - match playing - .then(|| self.on_partner_beat(deck, frame, &moment)) - .flatten() - { + match playing.then(|| self.on_partner_beat(deck, frame, &moment)).flatten() { Some(target) => self.move_to(deck, target, KeepTime::Since(moment.frames)), None => self.seek_frames(deck, frame), } @@ -543,11 +488,7 @@ impl Engine { let Some(handle) = self.deck(deck) else { return; }; - let tempo = if tempo.is_finite() { - tempo.clamp(MIN_TEMPO, MAX_TEMPO) - } else { - 1.0 - }; + let tempo = if tempo.is_finite() { tempo.clamp(MIN_TEMPO, MAX_TEMPO) } else { 1.0 }; handle.clock().set_tempo(tempo); } @@ -568,28 +509,18 @@ impl Engine { let Some(handle) = self.deck(deck) else { return; }; - handle - .clock() - .set_key_shift(semitones.clamp(-MAX_KEY_SHIFT, MAX_KEY_SHIFT)); + handle.clock().set_key_shift(semitones.clamp(-MAX_KEY_SHIFT, MAX_KEY_SHIFT)); } /// The master level, linear, 0 to 1. pub fn set_volume(&self, gain: f32) { - let safe = if gain.is_finite() { - gain.clamp(0.0, 1.0) - } else { - 1.0 - }; + let safe = if gain.is_finite() { gain.clamp(0.0, 1.0) } else { 1.0 }; self.master.store(safe.to_bits(), Ordering::Relaxed); } /// One deck's own level, linear, 0 to 1, glided like the master so a fader move never clicks. pub fn set_deck_gain(&self, deck: DeckId, gain: f32) { - let safe = if gain.is_finite() { - gain.clamp(0.0, 1.0) - } else { - 1.0 - }; + let safe = if gain.is_finite() { gain.clamp(0.0, 1.0) } else { 1.0 }; if let Some(level) = self.gains.get(deck) { level.store(safe.to_bits(), Ordering::Relaxed); } @@ -663,11 +594,7 @@ impl Engine { }; let moment = self.timeline.read(); // A paused deck may have moved since the callback last ran. - let own_at = if own.playing() { - moment.positions[deck] - } else { - own.position() - }; + let own_at = if own.playing() { moment.positions[deck] } else { own.position() }; let Some(target) = self.on_partner_beat(deck, own_at, &moment) else { return; }; diff --git a/native/crates/es-deck/src/reader.rs b/native/crates/es-deck/src/reader.rs index fad5765..5bc5912 100644 --- a/native/crates/es-deck/src/reader.rs +++ b/native/crates/es-deck/src/reader.rs @@ -27,13 +27,7 @@ pub(crate) struct Feed { impl Feed { fn new(consumer: Consumer) -> Self { - Self { - consumer, - current: None, - offset: 0, - generation: 0, - backlog: VecDeque::with_capacity(POSITIONS), - } + Self { consumer, current: None, offset: 0, generation: 0, backlog: VecDeque::with_capacity(POSITIONS) } } /// Puts a frame back in front of everything else. Frames go back newest first. Never grows @@ -55,11 +49,7 @@ impl Feed { if self.offset < usize::from(block.frames) { let i = self.offset * 2; self.offset += 1; - return Some(( - block.samples[i], - block.samples[i + 1], - block.position + self.offset as u64, - )); + return Some((block.samples[i], block.samples[i + 1], block.position + self.offset as u64)); } self.current = None; self.offset = 0; @@ -87,19 +77,13 @@ impl Feed { /// Discards blocks of an earlier generation at the front of the ring. Only the front can hold /// them: once the decode thread moves on, everything it queues is the new generation's. fn drop_stale(&mut self) { - while self - .consumer - .peek() - .is_ok_and(|block| block.generation < self.generation) - { + while self.consumer.peek().is_ok_and(|block| block.generation < self.generation) { let _ = self.consumer.pop(); } } fn left_in_block(&self) -> usize { - self.current - .as_ref() - .map_or(0, |b| usize::from(b.frames).saturating_sub(self.offset)) + self.current.as_ref().map_or(0, |b| usize::from(b.frames).saturating_sub(self.offset)) } fn drained(&self) -> bool { @@ -111,11 +95,7 @@ impl Feed { self.backlog.clear(); } self.generation = generation; - if self - .current - .as_ref() - .is_some_and(|b| b.generation < generation) - { + if self.current.as_ref().is_some_and(|b| b.generation < generation) { self.current = None; self.offset = 0; } @@ -149,11 +129,7 @@ pub(crate) struct DeckReader { } impl DeckReader { - pub fn new( - consumer: Consumer, - clock: Arc, - stretchers: Consumer>, - ) -> Self { + pub fn new(consumer: Consumer, clock: Arc, stretchers: Consumer>) -> Self { Self { feed: Feed::new(consumer), clock, @@ -381,10 +357,7 @@ impl DeckReader { /// Whether what is left is the last of the file and short enough that the fade must start. fn ending(&self) -> bool { - if !self.clock.end_of_stream() - || !self.feed.consumer.is_empty() - || !self.feed.backlog.is_empty() - { + if !self.clock.end_of_stream() || !self.feed.consumer.is_empty() || !self.feed.backlog.is_empty() { return false; } self.feed.left_in_block() <= usize::from(FADE_FRAMES) diff --git a/native/crates/es-deck/src/scrub.rs b/native/crates/es-deck/src/scrub.rs index bb94f38..0fd6e67 100644 --- a/native/crates/es-deck/src/scrub.rs +++ b/native/crates/es-deck/src/scrub.rs @@ -92,8 +92,7 @@ impl PcmWindow { let head = head.max(0.0) as u64; let end = head.saturating_add(keep); if self.end() > end { - self.data - .truncate((end.saturating_sub(self.start) as usize) * 2); + self.data.truncate((end.saturating_sub(self.start) as usize) * 2); } let first = head.saturating_sub(keep); if first > self.start { @@ -119,16 +118,8 @@ impl PcmWindow { let base = at.floor(); let t = (at - base) as f32; let i = base as i64; - let p = [ - self.frame(i - 1), - self.frame(i), - self.frame(i + 1), - self.frame(i + 2), - ]; - ( - catmull_rom([p[0].0, p[1].0, p[2].0, p[3].0], t), - catmull_rom([p[0].1, p[1].1, p[2].1, p[3].1], t), - ) + let p = [self.frame(i - 1), self.frame(i), self.frame(i + 1), self.frame(i + 2)]; + (catmull_rom([p[0].0, p[1].0, p[2].0, p[3].0], t), catmull_rom([p[0].1, p[1].1, p[2].1, p[3].1], t)) } } @@ -171,10 +162,7 @@ impl ScrubFilter { let a2 = g * a1; let a3 = g * a2; let mut out = [0.0f32; 2]; - for (ch, x) in [f64::from(input.0), f64::from(input.1)] - .into_iter() - .enumerate() - { + for (ch, x) in [f64::from(input.0), f64::from(input.1)].into_iter().enumerate() { let [ic1, ic2] = self.state[ch]; let v3 = x - ic2; let v1 = a1 * ic1 + a2 * v3; @@ -250,11 +238,7 @@ impl Scrubber { if dt > 0.0 { let measured = (frame - last_frame) / (dt / 1000.0 * self.sample_rate); // A gap much longer than usual means the pointer rested in between. - let measured = if dt > STOPPED_INTERVALS * self.interval_ms * 4.0 { - 0.0 - } else { - measured - }; + let measured = if dt > STOPPED_INTERVALS * self.interval_ms * 4.0 { 0.0 } else { measured }; self.speed += (measured.clamp(-MAX_RATE, MAX_RATE) - self.speed) * SPEED_SMOOTH; self.interval_ms += (dt.min(100.0) - self.interval_ms) * INTERVAL_SMOOTH; } @@ -286,11 +270,7 @@ impl Scrubber { } // The head runs ahead of the pointer to cover the ring's latency, so it is past the // pointer when the pointer stops. It stops too, rather than backing up audibly. - let wanted = if stopped { - 0.0 - } else { - (self.speed + CORRECT * error / block).clamp(-MAX_RATE, MAX_RATE) - }; + let wanted = if stopped { 0.0 } else { (self.speed + CORRECT * error / block).clamp(-MAX_RATE, MAX_RATE) }; let smooth = if stopped { STOP_SMOOTH } else { SMOOTH }; let mut next = self.rate + (wanted - self.rate) * smooth; let resting = self.speed == 0.0 && next.abs() < REST_RATE; @@ -360,11 +340,7 @@ mod tests { let mut next_event = 0.0; while now < ms + rest_ms { while next_event <= now && next_event <= ms { - s.point( - from + speed * next_event / 1000.0 * RATE as f64, - next_event, - now, - ); + s.point(from + speed * next_event / 1000.0 * RATE as f64, next_event, now); next_event += 8.0; } s.render(&w, &mut block, now); @@ -385,16 +361,10 @@ mod tests { let (ahead, fwd, _) = drag(from, 1.0, 400.0, 0.0); let (back, rev, _) = drag(from, -1.0, 400.0, 0.0); for (a, b) in ahead.iter().zip(&back) { - assert!( - ((a - from) + (b - from)).abs() < 1e-6, - "{a} and {b} are not mirrored" - ); + assert!(((a - from) + (b - from)).abs() < 1e-6, "{a} and {b} are not mirrored"); } let (f, r) = (rms(&fwd), rms(&rev)); - assert!( - (f - r).abs() / f < 0.05, - "forward {f} and backward {r} differ in level" - ); + assert!((f - r).abs() / f < 0.05, "forward {f} and backward {r} differ in level"); } #[test] @@ -403,15 +373,9 @@ mod tests { let (heads, audio, s) = drag(from, 1.0, 600.0, 0.0); let travelled = heads.last().unwrap() - from; let pointer = 0.6 * RATE as f64; - assert!( - (travelled - pointer).abs() < 0.08 * pointer, - "head moved {travelled}, pointer {pointer}" - ); + assert!((travelled - pointer).abs() < 0.08 * pointer, "head moved {travelled}, pointer {pointer}"); assert!((s.rate() - 1.0).abs() < 0.1, "rate settled at {}", s.rate()); - assert!( - rms(&audio[audio.len() / 2..]) > 0.2, - "full-speed scrub is audible" - ); + assert!(rms(&audio[audio.len() / 2..]) > 0.2, "full-speed scrub is audible"); } #[test] @@ -419,12 +383,7 @@ mod tests { let from = 5.0 * RATE as f64; let (_, audio, s) = drag(from, 1.5, 300.0, 400.0); assert!(s.settled(), "head still moving at rate {}", s.rate()); - assert!( - (s.head() - s.target()).abs() < 1.0, - "rests at {} not {}", - s.head(), - s.target() - ); + assert!((s.head() - s.target()).abs() < 1.0, "rests at {} not {}", s.head(), s.target()); let tail = &audio[audio.len() - BLOCK_FRAMES * 2..]; assert!(tail.iter().all(|v| v.abs() < 1e-3), "silent at rest"); } @@ -434,16 +393,9 @@ mod tests { let from = 5.0 * RATE as f64; let (heads, audio, s) = drag(from, 0.1, 1000.0, 0.0); for pair in heads.windows(2).skip(4) { - assert!( - pair[1] >= pair[0], - "the head went backwards on a slow forward drag" - ); + assert!(pair[1] >= pair[0], "the head went backwards on a slow forward drag"); } - assert!( - (s.rate() - 0.1).abs() < 0.03, - "rate {} for a 0.1x drag", - s.rate() - ); + assert!((s.rate() - 0.1).abs() < 0.03, "rate {} for a 0.1x drag", s.rate()); // Slow is dark and quiet: a 1 kHz tone at 0.1x is a 100 Hz tone, mostly passed, but // nothing in it may blow up. assert!(audio.iter().all(|v| v.is_finite() && v.abs() <= 1.0)); @@ -461,10 +413,7 @@ mod tests { peak = peak.max(l.abs()); } } - assert!( - peak < 0.01, - "Nyquist tone leaks {peak} through the slow filter" - ); + assert!(peak < 0.01, "Nyquist tone leaks {peak} through the slow filter"); assert!(f.cutoff_for(10.0) <= CUTOFF_CEILING * RATE as f64); assert!((f.cutoff_for(0.0) - CUTOFF_MIN).abs() < 1e-9); } diff --git a/native/crates/es-deck/src/sink.rs b/native/crates/es-deck/src/sink.rs index 7a0e9ef..a199d14 100644 --- a/native/crates/es-deck/src/sink.rs +++ b/native/crates/es-deck/src/sink.rs @@ -45,61 +45,54 @@ impl CpalSink { pub fn open(render: Render) -> Result { let (ready_tx, ready_rx) = mpsc::channel::>(); let (tx, rx) = mpsc::channel::(); - let thread = thread::Builder::new() - .name("es-audio-device".into()) - .spawn(move || { - let stream = match build_stream(render) { - Ok((stream, rate)) => { - let _ = ready_tx.send(Ok(rate)); - stream + let thread = thread::Builder::new().name("es-audio-device".into()).spawn(move || { + let stream = match build_stream(render) { + Ok((stream, rate)) => { + let _ = ready_tx.send(Ok(rate)); + stream + } + Err(e) => { + let _ = ready_tx.send(Err(e)); + return; + } + }; + let mut running = false; + let mut stop_pending = false; + loop { + let command = if stop_pending { + match rx.recv_timeout(IDLE_GRACE) { + Ok(c) => Some(c), + Err(RecvTimeoutError::Timeout) => None, + Err(RecvTimeoutError::Disconnected) => break, } - Err(e) => { - let _ = ready_tx.send(Err(e)); - return; + } else { + match rx.recv() { + Ok(c) => Some(c), + Err(_) => break, } }; - let mut running = false; - let mut stop_pending = false; - loop { - let command = if stop_pending { - match rx.recv_timeout(IDLE_GRACE) { - Ok(c) => Some(c), - Err(RecvTimeoutError::Timeout) => None, - Err(RecvTimeoutError::Disconnected) => break, - } - } else { - match rx.recv() { - Ok(c) => Some(c), - Err(_) => break, + match command { + Some(SinkCommand::Start) => { + stop_pending = false; + if !running { + running = stream.play().is_ok(); } - }; - match command { - Some(SinkCommand::Start) => { - stop_pending = false; - if !running { - running = stream.play().is_ok(); - } - } - Some(SinkCommand::Stop) => stop_pending = running, - Some(SinkCommand::Quit) => break, - None => { - stop_pending = false; - if running { - let _ = stream.pause(); - running = false; - } + } + Some(SinkCommand::Stop) => stop_pending = running, + Some(SinkCommand::Quit) => break, + None => { + stop_pending = false; + if running { + let _ = stream.pause(); + running = false; } } } - })?; - let sample_rate = ready_rx - .recv() - .map_err(|_| EngineError::Device("the audio thread did not start".into()))??; - Ok(Self { - sample_rate, - commands: Mutex::new(tx), - thread: Some(thread), - }) + } + })?; + let sample_rate = + ready_rx.recv().map_err(|_| EngineError::Device("the audio thread did not start".into()))??; + Ok(Self { sample_rate, commands: Mutex::new(tx), thread: Some(thread) }) } fn send(&self, command: SinkCommand) { @@ -134,9 +127,7 @@ impl Sink for CpalSink { fn build_stream(render: Render) -> Result<(cpal::Stream, u32)> { let host = cpal::default_host(); let device = host.default_output_device().ok_or(EngineError::NoDevice)?; - let supported = device - .default_output_config() - .map_err(|e| EngineError::Device(e.to_string()))?; + let supported = device.default_output_config().map_err(|e| EngineError::Device(e.to_string()))?; let format = supported.sample_format(); let config: cpal::StreamConfig = supported.into(); let rate = config.sample_rate.0; @@ -145,20 +136,14 @@ fn build_stream(render: Render) -> Result<(cpal::Stream, u32)> { SampleFormat::I16 => output::(&device, &config, render), SampleFormat::U16 => output::(&device, &config, render), SampleFormat::I32 => output::(&device, &config, render), - other => Err(EngineError::Device(format!( - "unsupported sample format {other}" - ))), + other => Err(EngineError::Device(format!("unsupported sample format {other}"))), }?; // Built paused: nothing plays until a deck asks for it. let _ = stream.pause(); Ok((stream, rate)) } -fn output( - device: &cpal::Device, - config: &cpal::StreamConfig, - mut render: Render, -) -> Result +fn output(device: &cpal::Device, config: &cpal::StreamConfig, mut render: Render) -> Result where T: SizedSample + FromSample, { @@ -173,9 +158,7 @@ where let buffer = &mut stereo[..frames * 2]; buffer.fill(0.0); render(buffer); - for (frame, pair) in - chunk.chunks_exact_mut(channels).zip(buffer.chunks_exact(2)) - { + for (frame, pair) in chunk.chunks_exact_mut(channels).zip(buffer.chunks_exact(2)) { if channels == 1 { frame[0] = T::from_sample((pair[0] + pair[1]) * 0.5); continue; @@ -203,11 +186,7 @@ pub struct NullSink { impl NullSink { pub fn new(render: Render, sample_rate: u32) -> Self { - Self { - sample_rate, - render: Mutex::new(render), - running: Arc::default(), - } + Self { sample_rate, render: Mutex::new(render), running: Arc::default() } } /// Renders `frames` frames of interleaved stereo, as the device callback would. @@ -234,12 +213,10 @@ impl Sink for NullSink { } fn start(&self) { - self.running - .store(true, std::sync::atomic::Ordering::Relaxed); + self.running.store(true, std::sync::atomic::Ordering::Relaxed); } fn stop(&self) { - self.running - .store(false, std::sync::atomic::Ordering::Relaxed); + self.running.store(false, std::sync::atomic::Ordering::Relaxed); } } diff --git a/native/crates/es-deck/src/smooth.rs b/native/crates/es-deck/src/smooth.rs index 79a9489..50f533f 100644 --- a/native/crates/es-deck/src/smooth.rs +++ b/native/crates/es-deck/src/smooth.rs @@ -9,10 +9,7 @@ impl Smoothed { /// `time_ms` is the time constant: the level covers about two thirds of a change in that time. pub fn new(initial: f32, sample_rate: u32, time_ms: f32) -> Self { let frames = (time_ms / 1000.0 * sample_rate.max(1) as f32).max(1.0); - Self { - value: initial, - coefficient: 1.0 - (-1.0 / frames).exp(), - } + Self { value: initial, coefficient: 1.0 - (-1.0 / frames).exp() } } pub fn step(&mut self, target: f32) -> f32 { diff --git a/native/crates/es-deck/src/sync.rs b/native/crates/es-deck/src/sync.rs index 1a0ccd1..22e0c48 100644 --- a/native/crates/es-deck/src/sync.rs +++ b/native/crates/es-deck/src/sync.rs @@ -40,9 +40,7 @@ impl Grid { } fn last_at_or_before(&self, frame: f64) -> usize { - self.times - .partition_point(|&t| t <= frame) - .saturating_sub(1) + self.times.partition_point(|&t| t <= frame).saturating_sub(1) } /// Fractional beats along the grid at `frame`. @@ -56,12 +54,7 @@ impl Grid { } let i = self.last_at_or_before(frame); let span = self.times[i + 1] - self.times[i]; - i as f64 - + if span > 0.0 { - (frame - self.times[i]) / span - } else { - 0.0 - } + i as f64 + if span > 0.0 { (frame - self.times[i]) / span } else { 0.0 } } /// The frame `beat` beats along the grid: the inverse of [`beat_at`](Self::beat_at). @@ -128,11 +121,7 @@ pub(crate) struct BeatSync { impl BeatSync { pub fn new(decks: usize, sample_rate: u32) -> Self { - Self { - sample_rate, - grids: vec![None; decks], - link: None, - } + Self { sample_rate, grids: vec![None; decks], link: None } } pub fn sample_rate(&self) -> u32 { @@ -149,11 +138,7 @@ impl BeatSync { let decks = self.grids.len(); self.link = link .filter(|&(master, follower)| master != follower && master < decks && follower < decks) - .map(|(master, follower)| Link { - master, - follower, - ratio: None, - }); + .map(|(master, follower)| Link { master, follower, ratio: None }); } pub fn link(&self) -> Option<(DeckId, DeckId)> { @@ -182,16 +167,14 @@ impl BeatSync { else { return; }; - let (Some(master), Some(follower)) = (clocks.get(link.master), clocks.get(link.follower)) - else { + let (Some(master), Some(follower)) = (clocks.get(link.master), clocks.get(link.follower)) else { return; }; let (master, follower) = (master.as_ref(), follower.as_ref()); if !master.loaded() || !follower.loaded() { return; } - let master_bpm = - master_grid.bpm_at(master.position() as f64, self.sample_rate) * master.tempo(); + let master_bpm = master_grid.bpm_at(master.position() as f64, self.sample_rate) * master.tempo(); let own_bpm = own_grid.bpm_at(follower.position() as f64, self.sample_rate); let kept = link .ratio @@ -213,11 +196,7 @@ impl BeatSync { let link = self.link?; let partner = self.partner(deck)?; let ratio = link.ratio?; - let own_ratio = if deck == link.follower { - ratio - } else { - 1.0 / ratio - }; + let own_ratio = if deck == link.follower { ratio } else { 1.0 / ratio }; let own_grid = self.grids.get(deck)?.as_ref()?; let partner_grid = self.grids.get(partner)?.as_ref()?; let own_beat = own_grid.beat_at(own_at); @@ -277,11 +256,7 @@ impl Timeline { continue; } let frames = self.frames.load(Ordering::Relaxed); - let positions = self - .positions - .iter() - .map(|p| p.load(Ordering::Relaxed)) - .collect(); + let positions = self.positions.iter().map(|p| p.load(Ordering::Relaxed)).collect(); fence(Ordering::Acquire); if self.seq.load(Ordering::Relaxed) == before { return Moment { frames, positions }; @@ -367,19 +342,10 @@ mod tests { sync.link.as_mut().unwrap().ratio = Some(1.0); let master_at = 100_000.0; let target = sync.phase_target(1, 90_000.0, master_at).unwrap(); - let grids = ( - sync.grids[0].as_ref().unwrap(), - sync.grids[1].as_ref().unwrap(), - ); + let grids = (sync.grids[0].as_ref().unwrap(), sync.grids[1].as_ref().unwrap()); assert!(beat_offset(grids.0.beat_at(master_at), grids.1.beat_at(target), 1.0).abs() < 1e-9); - assert!( - (target - 90_000.0).abs() <= 12_000.0, - "under half a beat away" - ); + assert!((target - 90_000.0).abs() <= 12_000.0, "under half a beat away"); let back = sync.phase_target(0, master_at, target).unwrap(); - assert!( - (back - master_at).abs() < 1e-6, - "the master is already in phase" - ); + assert!((back - master_at).abs() < 1e-6, "the master is already in phase"); } } diff --git a/native/crates/es-deck/src/tempo.rs b/native/crates/es-deck/src/tempo.rs index e190a36..101f453 100644 --- a/native/crates/es-deck/src/tempo.rs +++ b/native/crates/es-deck/src/tempo.rs @@ -19,9 +19,7 @@ pub const MAX_TEMPO: f64 = 2.0; pub(crate) fn catmull_rom(p: [f32; 4], t: f32) -> f32 { p[1] + 0.5 * t - * (p[2] - p[0] - + t * (2.0 * p[0] - 5.0 * p[1] + 4.0 * p[2] - p[3] - + t * (3.0 * (p[1] - p[2]) + p[3] - p[0]))) + * (p[2] - p[0] + t * (2.0 * p[0] - 5.0 * p[1] + 4.0 * p[2] - p[3] + t * (3.0 * (p[1] - p[2]) + p[3] - p[0]))) } /// How the deck turns file frames into output frames. @@ -46,11 +44,7 @@ pub(crate) struct Varispeed { impl Default for Varispeed { fn default() -> Self { - Self { - frames: [(0.0, 0.0); 4], - at: [0; 4], - phase: 3.0, - } + Self { frames: [(0.0, 0.0); 4], at: [0; 4], phase: 3.0 } } } @@ -162,8 +156,7 @@ impl Stretcher { for rate in [MIN_TEMPO, 1.0, MAX_TEMPO] { let frames = ((CHUNK as f64 * rate) as usize).min(self.input.len() / 2); for _ in 0..64 { - self.stretch - .process(&self.input[..frames * 2], &mut self.output[..]); + self.stretch.process(&self.input[..frames * 2], &mut self.output[..]); } } self.input.fill(0.0); @@ -190,11 +183,7 @@ impl Stretcher { let from = self.last_heard.map_or(0, |heard| heard + 1); for index in (from..self.fed).rev() { let i = (index as usize) % POSITIONS; - feed.unread(( - self.history[i * 2], - self.history[i * 2 + 1], - self.positions[i], - )); + feed.unread((self.history[i * 2], self.history[i * 2 + 1], self.positions[i])); } self.reset(); } @@ -235,8 +224,7 @@ impl Stretcher { self.fed = got as u64; let got = self.pull(feed, true, lead); let out = self.output_latency.min(self.scratch.len() / 2); - self.stretch - .process(&self.input[..got * 2], &mut self.scratch[..out * 2]); + self.stretch.process(&self.input[..got * 2], &mut self.scratch[..out * 2]); self.fed += got as u64; self.primed = true; true @@ -251,13 +239,8 @@ impl Stretcher { if got == 0 { return; } - self.carry = if got == frames { - wanted - frames as f64 - } else { - 0.0 - }; - self.stretch - .process(&self.input[..got * 2], &mut self.output[..]); + self.carry = if got == frames { wanted - frames as f64 } else { 0.0 }; + self.stretch.process(&self.input[..got * 2], &mut self.output[..]); self.chunk_start = self.fed; self.chunk_in = got; self.fed += got as u64; @@ -266,11 +249,7 @@ impl Stretcher { /// Moves the pitch, as a multiple of the file's. Takes effect from the next chunk. fn set_pitch(&mut self, pitch: f32) { - let pitch = if pitch.is_finite() && pitch > 0.0 { - pitch - } else { - 1.0 - }; + let pitch = if pitch.is_finite() && pitch > 0.0 { pitch } else { 1.0 }; if pitch != self.pitch { self.pitch = pitch; self.stretch.set_transpose_factor(pitch, None); @@ -301,10 +280,9 @@ impl Stretcher { let i = self.out_read; self.out_read += 1; // The input frame at the centre of what is heard now, behind the newest by the latency. - let fed_by_now = - self.chunk_start as f64 + (i + 1) as f64 * self.chunk_in as f64 / CHUNK as f64; - let heard = (fed_by_now - self.latency_frames(rate) as f64) - .clamp(0.0, self.fed.saturating_sub(1) as f64) as u64; + let fed_by_now = self.chunk_start as f64 + (i + 1) as f64 * self.chunk_in as f64 / CHUNK as f64; + let heard = + (fed_by_now - self.latency_frames(rate) as f64).clamp(0.0, self.fed.saturating_sub(1) as f64) as u64; self.last_heard = Some(heard); let at = self.positions[(heard as usize) % POSITIONS]; Some((self.output[i * 2], self.output[i * 2 + 1], at)) diff --git a/native/crates/es-deck/tests/common/mod.rs b/native/crates/es-deck/tests/common/mod.rs index f483bfc..a57248c 100644 --- a/native/crates/es-deck/tests/common/mod.rs +++ b/native/crates/es-deck/tests/common/mod.rs @@ -75,11 +75,7 @@ impl Rig { }) .unwrap(); let sink = slot.lock().unwrap().take().unwrap(); - Self { - engine, - sink, - events, - } + Self { engine, sink, events } } pub fn load(&self, path: &Path) { @@ -126,17 +122,10 @@ pub fn wait_for(mut done: impl FnMut() -> bool) { /// The largest jump between consecutive left-channel samples. pub fn largest_step(out: &[f32]) -> f32 { - out.chunks_exact(2) - .map(|f| f[0]) - .collect::>() - .windows(2) - .map(|w| (w[1] - w[0]).abs()) - .fold(0.0, f32::max) + out.chunks_exact(2).map(|f| f[0]).collect::>().windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0, f32::max) } /// Index of the first frame with any sound in it. pub fn first_audible(out: &[f32]) -> usize { - out.chunks_exact(2) - .position(|f| f[0] != 0.0) - .expect("no sound at all") + out.chunks_exact(2).position(|f| f[0] != 0.0).expect("no sound at all") } diff --git a/native/crates/es-deck/tests/engine.rs b/native/crates/es-deck/tests/engine.rs index da08648..521b60f 100644 --- a/native/crates/es-deck/tests/engine.rs +++ b/native/crates/es-deck/tests/engine.rs @@ -14,22 +14,11 @@ fn play_and_pause_fade_instead_of_clicking() { rig.load(&dc("playpause", RATE * 3)); rig.engine.play(0); let start = rig.pull(4096); - assert!( - largest_step(&start) <= fade_step(), - "start stepped {}", - largest_step(&start) - ); - assert!( - value(start[start.len() - 2]) > 25_000, - "should reach full level" - ); + assert!(largest_step(&start) <= fade_step(), "start stepped {}", largest_step(&start)); + assert!(value(start[start.len() - 2]) > 25_000, "should reach full level"); rig.engine.pause(0); let stop = rig.pull(4096); - assert!( - largest_step(&stop) <= fade_step(), - "stop stepped {}", - largest_step(&stop) - ); + assert!(largest_step(&stop) <= fade_step(), "stop stepped {}", largest_step(&stop)); assert_eq!(stop[stop.len() - 2], 0.0, "paused deck is silent"); } @@ -41,11 +30,7 @@ fn a_seek_while_playing_fades_out_and_back_in() { let _ = rig.pull(4096); rig.engine.seek(0, 3000.0); let around = rig.pull(8192); - assert!( - largest_step(&around) <= fade_step(), - "seek stepped {}", - largest_step(&around) - ); + assert!(largest_step(&around) <= fade_step(), "seek stepped {}", largest_step(&around)); let dips = around.chunks_exact(2).any(|f| f[0].abs() < 0.05); assert!(dips, "the join should pass through silence"); } @@ -56,11 +41,7 @@ fn a_seek_lands_on_the_exact_frame() { rig.load(&ramp("seekexact", RATE * 4)); rig.engine.seek(0, 1234.5); let frame = (1234.5_f64 * f64::from(RATE) / 1000.0).round() as u64; - assert_eq!( - rig.position(), - frame, - "a paused seek shows where it landed at once" - ); + assert_eq!(rig.position(), frame, "a paused seek shows where it landed at once"); rig.settle_ring(); rig.engine.play(0); let out = rig.pull(4096); @@ -68,10 +49,7 @@ fn a_seek_lands_on_the_exact_frame() { // from it exactly. let first = first_audible(&out); let i = first + usize::from(FADE_FRAMES) + 10; - assert_eq!( - value(out[i * 2]), - ((frame + (i - first) as u64) % 30_000) as i64 - ); + assert_eq!(value(out[i * 2]), ((frame + (i - first) as u64) % 30_000) as i64); } #[test] @@ -93,11 +71,7 @@ fn playing_to_the_end_fades_and_stops() { rig.load(&dc("end", frames)); rig.engine.play(0); let out = rig.pull(frames as usize + 4096); - assert!( - largest_step(&out) <= fade_step(), - "end stepped {}", - largest_step(&out) - ); + assert!(largest_step(&out) <= fade_step(), "end stepped {}", largest_step(&out)); assert!(!rig.engine.snapshot(0).unwrap().playing); assert_eq!(out[out.len() - 2], 0.0); } @@ -122,10 +96,7 @@ fn a_loop_seam_plays_straight_through() { expected = from as i64; } } - assert!( - values.iter().skip(open).any(|&v| v == from as i64), - "the loop wrapped" - ); + assert!(values.iter().skip(open).any(|&v| v == from as i64), "the loop wrapped"); } #[test] @@ -145,31 +116,16 @@ fn exit_plays_on_past_the_out_point_and_reloop_returns_to_the_in_point() { assert!(at > to + 4000, "carried on past the out point, at {at}"); let snap = rig.engine.snapshot(0).unwrap(); assert!(!snap.looping); - assert_eq!( - (snap.loop_in_frames, snap.loop_out_frames), - (from, to), - "the loop is kept for RELOOP" - ); + assert_eq!((snap.loop_in_frames, snap.loop_out_frames), (from, to), "the loop is kept for RELOOP"); rig.engine.set_looping(0, true); assert_eq!(rig.position(), from, "RELOOP goes to the in point"); rig.settle_ring(); let out = rig.pull(16_000); // Past the fade out of where it was and the fade in at the in point. - let values: Vec = out - .chunks_exact(2) - .skip(4096) - .map(|f| value(f[0])) - .collect(); - let outside = values - .iter() - .position(|&v| !(from as i64..to as i64).contains(&v)); - assert_eq!( - outside, - None, - "stays inside the loop: {:?}", - outside.map(|i| values[i]) - ); + let values: Vec = out.chunks_exact(2).skip(4096).map(|f| value(f[0])).collect(); + let outside = values.iter().position(|&v| !(from as i64..to as i64).contains(&v)); + assert_eq!(outside, None, "stays inside the loop: {:?}", outside.map(|i| values[i])); } #[test] @@ -185,11 +141,7 @@ fn an_exited_loop_resized_behind_the_playhead_leaves_it_in_place() { assert_eq!(rig.position(), at, "the playhead did not move"); let snap = rig.engine.snapshot(0).unwrap(); assert!(!snap.looping, "the loop stays exited"); - assert_eq!( - (snap.loop_in_frames, snap.loop_out_frames), - (24_000, 36_000), - "the range changed" - ); + assert_eq!((snap.loop_in_frames, snap.loop_out_frames), (24_000, 36_000), "the range changed"); } #[test] @@ -208,12 +160,8 @@ fn the_newest_load_wins() { #[test] fn a_missing_file_reports_an_error() { let rig = Rig::new(); - rig.engine - .load(0, std::path::Path::new("/nonexistent/track.mp3"), 7); + rig.engine.load(0, std::path::Path::new("/nonexistent/track.mp3"), 7); wait_for(|| !rig.events.lock().unwrap().is_empty()); let events = rig.events.lock().unwrap(); - assert!(matches!( - events[0], - es_deck::DeckEvent::Error { load_id: 7, .. } - )); + assert!(matches!(events[0], es_deck::DeckEvent::Error { load_id: 7, .. })); } diff --git a/native/crates/es-deck/tests/key.rs b/native/crates/es-deck/tests/key.rs index 02ee7c7..748dd22 100644 --- a/native/crates/es-deck/tests/key.rs +++ b/native/crates/es-deck/tests/key.rs @@ -4,18 +4,13 @@ use common::*; /// A sine at `hz`, at most about two thirds of full scale. fn sine(name: &str, frames: u32, hz: f64) -> std::path::PathBuf { - wav(name, frames, |i| { - ((f64::from(i) * 2.0 * std::f64::consts::PI * hz / f64::from(RATE)).sin() * 20_000.0) as i16 - }) + wav(name, frames, |i| ((f64::from(i) * 2.0 * std::f64::consts::PI * hz / f64::from(RATE)).sin() * 20_000.0) as i16) } /// Cycles per second of the left channel, from its upward zero crossings. fn frequency(out: &[f32]) -> f64 { let left: Vec = out.chunks_exact(2).map(|f| f[0]).collect(); - let crossings = left - .windows(2) - .filter(|w| w[0] < 0.0 && w[1] >= 0.0) - .count(); + let crossings = left.windows(2).filter(|w| w[0] < 0.0 && w[1] >= 0.0).count(); crossings as f64 * f64::from(RATE) / left.len() as f64 } @@ -84,11 +79,7 @@ fn back_at_no_shift_the_file_plays_exactly() { let out = rig.pull(4096); let values: Vec = out.chunks_exact(2).map(|f| value(f[0])).collect(); for pair in values.windows(2) { - assert_eq!( - pair[1], - (pair[0] + 1) % 30_000, - "frames are the file's, one after another" - ); + assert_eq!(pair[1], (pair[0] + 1) % 30_000, "frames are the file's, one after another"); } } diff --git a/native/crates/es-deck/tests/mix.rs b/native/crates/es-deck/tests/mix.rs index 146d89a..c3f7305 100644 --- a/native/crates/es-deck/tests/mix.rs +++ b/native/crates/es-deck/tests/mix.rs @@ -13,22 +13,13 @@ fn a_deck_gain_scales_only_that_deck() { rig.engine.play_together(&[0, 1]); let both = rig.pull(8192); let full = value(both[both.len() - 2]); - assert!( - (full - 26_000).abs() < 100, - "two halves make the whole: {full}" - ); + assert!((full - 26_000).abs() < 100, "two halves make the whole: {full}"); rig.engine.set_deck_gain(1, 0.0); let one = rig.pull(8192); let alone = value(one[one.len() - 2]); - assert!( - (alone * 2 - full).abs() < 200, - "silencing deck B should leave deck A alone: {alone} of {full}" - ); - assert!( - largest_step(&one) < 0.01, - "the level glides rather than steps" - ); + assert!((alone * 2 - full).abs() < 200, "silencing deck B should leave deck A alone: {alone} of {full}"); + assert!(largest_step(&one) < 0.01, "the level glides rather than steps"); rig.engine.set_deck_gain(0, 0.0); let none = rig.pull(8192); @@ -76,28 +67,15 @@ fn a_killed_low_takes_the_bass_out_of_only_that_deck() { rig.engine.play_together(&[0, 1]); let both = rig.pull(8192); let full = value(both[both.len() - 2]); - assert!( - (full - 26_000).abs() < 100, - "with the low up the isolator passes the bass: {full}" - ); + assert!((full - 26_000).abs() < 100, "with the low up the isolator passes the bass: {full}"); rig.engine.set_deck_low(0, Some(0.0)); let killed = rig.pull(16_384); let left = value(killed[killed.len() - 2]); - assert!( - (left * 2 - full).abs() < 200, - "killing deck A's low leaves deck B's bass alone: {left} of {full}" - ); - assert!( - largest_step(&killed) < 0.01, - "the low glides out rather than stepping" - ); + assert!((left * 2 - full).abs() < 200, "killing deck A's low leaves deck B's bass alone: {left} of {full}"); + assert!(largest_step(&killed) < 0.01, "the low glides out rather than stepping"); rig.engine.set_deck_low(0, None); let back = rig.pull(16_384); - assert_eq!( - value(back[back.len() - 2]), - full, - "out of the path, the deck plays untouched" - ); + assert_eq!(value(back[back.len() - 2]), full, "out of the path, the deck plays untouched"); } diff --git a/native/crates/es-deck/tests/scrub.rs b/native/crates/es-deck/tests/scrub.rs index 7a4ce00..850804e 100644 --- a/native/crates/es-deck/tests/scrub.rs +++ b/native/crates/es-deck/tests/scrub.rs @@ -39,11 +39,7 @@ fn a_paused_drag_is_heard_and_lands_exactly_under_the_pointer() { rig.engine.scrub_begin(0); let (audio, last) = drag(&rig, 1000.0, 60); let moving = &audio[audio.len() / 2..]; - assert!( - rms(moving) > 0.1, - "a normal-speed drag is audible, rms {}", - rms(moving) - ); + assert!(rms(moving) > 0.1, "a normal-speed drag is audible, rms {}", rms(moving)); rig.engine.scrub_end(0); let landed = (last * f64::from(RATE) / 1000.0).round() as u64; @@ -51,11 +47,7 @@ fn a_paused_drag_is_heard_and_lands_exactly_under_the_pointer() { assert!(!snap.scrubbing && !snap.playing); assert_eq!(snap.position_frames, landed, "lands on the pointer"); let after = rig.pull(4096); - assert_eq!( - after[after.len() - 2], - 0.0, - "silent once let go while paused" - ); + assert_eq!(after[after.len() - 2], 0.0, "silent once let go while paused"); assert_eq!(rig.position(), landed, "and stays there"); } @@ -69,17 +61,11 @@ fn letting_go_of_a_drag_while_playing_plays_on_from_the_pointer() { let (_, last) = drag(&rig, 2000.0, 20); rig.engine.scrub_end(0); let landed = (last * f64::from(RATE) / 1000.0).round() as u64; - assert!( - rig.engine.snapshot(0).unwrap().playing, - "still playing after the drag" - ); + assert!(rig.engine.snapshot(0).unwrap().playing, "still playing after the drag"); rig.settle_ring(); let _ = rig.pull(4096); let at = rig.position(); - assert!( - at > landed && at <= landed + 4096, - "plays on from {landed}, now at {at}" - ); + assert!(at > landed && at <= landed + 4096, "plays on from {landed}, now at {at}"); } #[test] @@ -91,11 +77,7 @@ fn taking_hold_of_a_playing_deck_silences_it_at_once_without_a_click() { rig.engine.scrub_begin(0); let held = rig.pull(2048); let fade = 26_000.0 / 32_768.0 / f32::from(FADE_FRAMES) + 1e-4; - assert!( - largest_step(&held) <= fade, - "stepped {}", - largest_step(&held) - ); + assert!(largest_step(&held) <= fade, "stepped {}", largest_step(&held)); let tail = &held[held.len() - 512..]; assert!( tail.iter().all(|v| v.abs() < 1e-3), diff --git a/native/crates/es-deck/tests/sync.rs b/native/crates/es-deck/tests/sync.rs index 0b722d2..8913fc0 100644 --- a/native/crates/es-deck/tests/sync.rs +++ b/native/crates/es-deck/tests/sync.rs @@ -51,10 +51,7 @@ fn a_follower_started_over_a_playing_master_lands_on_its_beat() { rig.engine.play(1); let _ = rig.pull(RATE as usize); let error = phase_error(&rig, BEAT as f64); - assert!( - error.abs() < TOLERANCE, - "from {start_ms} ms: off by {error} frames" - ); + assert!(error.abs() < TOLERANCE, "from {start_ms} ms: off by {error} frames"); } } @@ -63,10 +60,7 @@ fn a_follower_at_another_tempo_keeps_the_masters_and_its_beat() { let rig = two_decks("s-tempo", 126.0); rig.engine.set_sync(Some((0, 1))); let tempo = rig.engine.snapshot(1).unwrap().tempo; - assert!( - (tempo - 120.0 / 126.0).abs() < 1e-9, - "takes the master's tempo: {tempo}" - ); + assert!((tempo - 120.0 / 126.0).abs() < 1e-9, "takes the master's tempo: {tempo}"); rig.engine.play(0); let _ = rig.pull(RATE as usize / 2); rig.engine.seek(1, 3_100.0); @@ -90,11 +84,7 @@ fn a_master_started_under_a_playing_follower_joins_its_beat() { let _ = rig.pull(RATE as usize); let error = phase_error(&rig, BEAT as f64); assert!(error.abs() < TOLERANCE, "off by {error} frames"); - assert_eq!( - position(&rig, 1), - follower_before + u64::from(RATE), - "the deck already playing was left alone" - ); + assert_eq!(position(&rig, 1), follower_before + u64::from(RATE), "the deck already playing was left alone"); } #[test] @@ -106,17 +96,11 @@ fn a_cue_hold_plays_where_it_is_until_play_latches_it() { rig.engine.seek(1, 1_100.0); rig.engine.play_unsynced(1); let _ = rig.pull(RATE as usize / 2); - assert!( - phase_error(&rig, BEAT as f64).abs() > TOLERANCE, - "the hold was not moved onto the beat" - ); + assert!(phase_error(&rig, BEAT as f64).abs() > TOLERANCE, "the hold was not moved onto the beat"); rig.engine.align(1); let _ = rig.pull(RATE as usize / 2); let error = phase_error(&rig, BEAT as f64); - assert!( - error.abs() < TOLERANCE, - "off by {error} frames once latched" - ); + assert!(error.abs() < TOLERANCE, "off by {error} frames once latched"); } #[test] @@ -151,10 +135,7 @@ fn without_sync_a_deck_starts_where_it_was() { rig.engine.play(1); let _ = rig.pull(4096); let at = position(&rig, 1); - assert!( - at > u64::from(RATE) * 11 / 10, - "it plays on from 1.1 s: {at}" - ); + assert!(at > u64::from(RATE) * 11 / 10, "it plays on from 1.1 s: {at}"); assert!(phase_error(&rig, BEAT as f64).abs() > TOLERANCE); } @@ -170,10 +151,7 @@ fn handing_the_master_over_moves_neither_deck() { rig.engine.set_sync(Some((1, 0))); let _ = rig.pull(RATE as usize / 2); let half = u64::from(RATE) / 2; - assert_eq!( - (position(&rig, 0), position(&rig, 1)), - (before.0 + half, before.1 + half) - ); + assert_eq!((position(&rig, 0), position(&rig, 1)), (before.0 + half, before.1 + half)); } #[test] @@ -188,10 +166,7 @@ fn a_follower_at_the_start_of_its_track_moves_forward_onto_the_beat() { rig.engine.play(1); let _ = rig.pull(RATE as usize / 2); let error = phase_error(&rig, BEAT as f64); - assert!( - error.abs() < TOLERANCE, - "with the master from {master_ms} ms: off by {error} frames" - ); + assert!(error.abs() < TOLERANCE, "with the master from {master_ms} ms: off by {error} frames"); } } @@ -235,8 +210,7 @@ fn the_master_jumping_lands_on_the_followers_beat() { #[test] fn entering_a_loop_while_both_play_lands_on_the_partners_beat() { let rig = both_playing_in_phase("s-loop", true); - rig.engine - .set_loop(1, OFF_BEAT_MS, OFF_BEAT_MS + 4_000.0, true); + rig.engine.set_loop(1, OFF_BEAT_MS, OFF_BEAT_MS + 4_000.0, true); let _ = rig.pull(RATE as usize); let error = phase_error(&rig, BEAT as f64); assert!(error.abs() < TOLERANCE, "off by {error} frames"); @@ -247,10 +221,7 @@ fn without_sync_a_jump_goes_exactly_where_it_was_sent() { let rig = both_playing_in_phase("s-jump-unsynced", false); rig.engine.seek(1, OFF_BEAT_MS); let _ = rig.pull(RATE as usize); - assert!( - phase_error(&rig, BEAT as f64).abs() > TOLERANCE, - "left off the beat" - ); + assert!(phase_error(&rig, BEAT as f64).abs() > TOLERANCE, "left off the beat"); } #[test] @@ -262,9 +233,5 @@ fn a_paused_synced_deck_goes_exactly_where_it_was_sent() { rig.engine.seek(1, OFF_BEAT_MS); let _ = rig.pull(RATE as usize / 10); let asked = (OFF_BEAT_MS * f64::from(RATE) / 1000.0).round() as u64; - assert_eq!( - position(&rig, 1), - asked, - "CUE moves a paused deck to the frame" - ); + assert_eq!(position(&rig, 1), asked, "CUE moves a paused deck to the frame"); } diff --git a/native/crates/es-deck/tests/tempo.rs b/native/crates/es-deck/tests/tempo.rs index 40d7b7f..8dcb707 100644 --- a/native/crates/es-deck/tests/tempo.rs +++ b/native/crates/es-deck/tests/tempo.rs @@ -4,18 +4,13 @@ use common::*; /// A sine at `hz`, at most about two thirds of full scale. fn sine(name: &str, frames: u32, hz: f64) -> std::path::PathBuf { - wav(name, frames, |i| { - ((f64::from(i) * 2.0 * std::f64::consts::PI * hz / f64::from(RATE)).sin() * 20_000.0) as i16 - }) + wav(name, frames, |i| ((f64::from(i) * 2.0 * std::f64::consts::PI * hz / f64::from(RATE)).sin() * 20_000.0) as i16) } /// Cycles per second of the left channel, from its upward zero crossings. fn frequency(out: &[f32]) -> f64 { let left: Vec = out.chunks_exact(2).map(|f| f[0]).collect(); - let crossings = left - .windows(2) - .filter(|w| w[0] < 0.0 && w[1] >= 0.0) - .count(); + let crossings = left.windows(2).filter(|w| w[0] < 0.0 && w[1] >= 0.0).count(); crossings as f64 * f64::from(RATE) / left.len() as f64 } @@ -64,11 +59,7 @@ fn slowing_down_works_both_ways() { fn assert_exact(out: &[f32]) { let values: Vec = out.chunks_exact(2).map(|f| value(f[0])).collect(); for pair in values.windows(2) { - assert_eq!( - pair[1], - (pair[0] + 1) % 30_000, - "frames are the file's, one after another" - ); + assert_eq!(pair[1], (pair[0] + 1) % 30_000, "frames are the file's, one after another"); } } diff --git a/native/crates/es-deck/tests/timing.rs b/native/crates/es-deck/tests/timing.rs index b1d07db..f5a0211 100644 --- a/native/crates/es-deck/tests/timing.rs +++ b/native/crates/es-deck/tests/timing.rs @@ -17,8 +17,7 @@ type Path<'a> = (&'a str, f64, &'a dyn Fn(&Rig)); fn bursts(name: &str, frames: u32) -> std::path::PathBuf { wav(name, frames, |i| { if i % BURST_EVERY < BURST_LEN { - ((f64::from(i) * 2.0 * std::f64::consts::PI * 1000.0 / f64::from(RATE)).sin() - * 20_000.0) as i16 + ((f64::from(i) * 2.0 * std::f64::consts::PI * 1000.0 / f64::from(RATE)).sin() * 20_000.0) as i16 } else { 0 } @@ -68,15 +67,9 @@ fn lag_after(name: &str, tempo: f64, before: impl Fn(&Rig), switch: impl Fn(&Rig } fn assert_on_time(what: &str, lags: &[f64]) { - assert!( - lags.len() >= 4, - "{what}: too few bursts heard after the switch: {lags:?}" - ); + assert!(lags.len() >= 4, "{what}: too few bursts heard after the switch: {lags:?}"); for lag in lags { - assert!( - lag.abs() < TOLERANCE_MS, - "{what}: a burst was {lag:+.2} ms off the beat: {lags:?}" - ); + assert!(lag.abs() < TOLERANCE_MS, "{what}: a burst was {lag:+.2} ms off the beat: {lags:?}"); } } @@ -88,23 +81,13 @@ fn shifting_the_key_onto_the_stretcher_keeps_time() { #[test] fn clearing_the_key_shift_off_the_stretcher_keeps_time() { - let lags = lag_after( - "t-key-off", - 1.0, - |r| r.engine.set_key_shift(0, 1), - |r| r.engine.set_key_shift(0, 0), - ); + let lags = lag_after("t-key-off", 1.0, |r| r.engine.set_key_shift(0, 1), |r| r.engine.set_key_shift(0, 0)); assert_on_time("key +1 to 0", &lags); } #[test] fn switching_master_tempo_keeps_time_both_ways() { - let on = lag_after( - "t-mt-on", - 1.04, - |r| r.engine.set_tempo(0, 1.04), - |r| r.engine.set_master_tempo(0, true), - ); + let on = lag_after("t-mt-on", 1.04, |r| r.engine.set_tempo(0, 1.04), |r| r.engine.set_master_tempo(0, true)); assert_on_time("master tempo on", &on); let off = lag_after( "t-mt-off", @@ -135,22 +118,13 @@ fn every_path_starts_on_the_frame_it_was_sent_to() { setup(&rig); // A quarter of a second before the second burst. let lead = RATE / 4; - rig.engine.seek( - 0, - f64::from(BURST_EVERY * 2 - lead) * 1000.0 / f64::from(RATE), - ); + rig.engine.seek(0, f64::from(BURST_EVERY * 2 - lead) * 1000.0 / f64::from(RATE)); rig.settle_ring(); rig.engine.play(0); let out = rig.pull(RATE as usize); - let first = out - .chunks_exact(2) - .position(|f| f[0].abs() > 0.15) - .expect("no burst"); + let first = out.chunks_exact(2).position(|f| f[0].abs() > 0.15).expect("no burst"); let off = (first as f64 - f64::from(lead) / tempo) / f64::from(RATE) * 1000.0; - assert!( - off.abs() < TOLERANCE_MS, - "{name}: burst heard {off:+.2} ms from where it belongs" - ); + assert!(off.abs() < TOLERANCE_MS, "{name}: burst heard {off:+.2} ms from where it belongs"); } } @@ -196,11 +170,7 @@ fn a_deck_moved_just_before_starting_together_still_starts_with_the_other() { let _ = rig.pull(4096); let a = rig.engine.snapshot(0).unwrap().position_frames; let b = rig.engine.snapshot(1).unwrap().position_frames; - assert_eq!( - b - a, - u64::from(RATE) * 2, - "both decks moved the same distance from where they started" - ); + assert_eq!(b - a, u64::from(RATE) * 2, "both decks moved the same distance from where they started"); } #[test] @@ -235,10 +205,7 @@ fn nudging_one_deck_onto_another_lines_them_up_exactly() { let _ = rig.pull(8192); let a = rig.engine.snapshot(0).unwrap().position_frames; let b = rig.engine.snapshot(1).unwrap().position_frames; - assert_eq!( - b, a, - "deck B landed exactly level with deck A, with no time lost to the jump" - ); + assert_eq!(b, a, "deck B landed exactly level with deck A, with no time lost to the jump"); } #[test] @@ -254,8 +221,5 @@ fn a_paused_deck_moved_twice_plays_from_the_second_move() { let past_fade = first_audible(&out) + usize::from(FADE_FRAMES) * 2; let heard = value(out[past_fade * 2]); let expected = (i64::from(RATE) * 2 + past_fade as i64 - first_audible(&out) as i64) % 30_000; - assert!( - (heard - expected).abs() <= 1, - "playing from 2 s, not 1 s: heard {heard}, expected {expected}" - ); + assert!((heard - expected).abs() <= 1, "playing from 2 s, not 1 s: heard {heard}, expected {expected}"); } diff --git a/native/crates/es-decode/src/lib.rs b/native/crates/es-decode/src/lib.rs index f423c6a..453a508 100644 --- a/native/crates/es-decode/src/lib.rs +++ b/native/crates/es-decode/src/lib.rs @@ -6,9 +6,7 @@ use std::fs::File; use std::path::Path; -use rubato::{ - Resampler, SincFixedIn, SincInterpolationParameters, SincInterpolationType, WindowFunction, -}; +use rubato::{Resampler, SincFixedIn, SincInterpolationParameters, SincInterpolationType, WindowFunction}; use symphonia::core::audio::SampleBuffer; use symphonia::core::codecs::{Decoder, DecoderOptions, CODEC_TYPE_MP3, CODEC_TYPE_NULL}; use symphonia::core::errors::Error as SymphoniaError; @@ -82,10 +80,7 @@ impl Streamer { let probed = symphonia::default::get_probe().format( &hint, stream, - &FormatOptions { - enable_gapless: false, - ..Default::default() - }, + &FormatOptions { enable_gapless: false, ..Default::default() }, &MetadataOptions::default(), )?; let format = probed.format; @@ -95,25 +90,13 @@ impl Streamer { .find(|t| t.codec_params.codec != CODEC_TYPE_NULL) .ok_or_else(|| DecodeError::Format("no audio track".into()))?; let params = track.codec_params.clone(); - let source_rate = params - .sample_rate - .filter(|r| *r > 0) - .ok_or_else(|| DecodeError::Format("unknown sample rate".into()))?; + let source_rate = + params.sample_rate.filter(|r| *r > 0).ok_or_else(|| DecodeError::Format("unknown sample rate".into()))?; let decoder = symphonia::default::get_codecs().make(¶ms, &DecoderOptions::default())?; - let output_rate = if output_rate == 0 { - source_rate - } else { - output_rate - }; - let lead = if params.codec == CODEC_TYPE_MP3 { - rb_audio::rekordbox_lead_frames(path) - } else { - 0 - }; - let total = params - .n_frames - .map(|n| scale(n.saturating_add_signed(lead), source_rate, output_rate)) - .unwrap_or(0); + let output_rate = if output_rate == 0 { source_rate } else { output_rate }; + let lead = if params.codec == CODEC_TYPE_MP3 { rb_audio::rekordbox_lead_frames(path) } else { 0 }; + let total = + params.n_frames.map(|n| scale(n.saturating_add_signed(lead), source_rate, output_rate)).unwrap_or(0); let resampler = if source_rate == output_rate { None } else { @@ -179,8 +162,7 @@ impl Streamer { } let take = available.min(wanted - written); let from = self.ready_at; - out[written * 2..(written + take) * 2] - .copy_from_slice(&self.ready[from..from + take * 2]); + out[written * 2..(written + take) * 2].copy_from_slice(&self.ready[from..from + take * 2]); self.ready_at += take * 2; written += take; } @@ -194,11 +176,7 @@ impl Streamer { /// Moves to `frame` (output rate) exactly, and returns where it landed. pub fn seek(&mut self, frame: u64) -> Result { - let frame = if self.total > 0 { - frame.min(self.total) - } else { - frame - }; + let frame = if self.total > 0 { frame.min(self.total) } else { frame }; let source_frame = scale(frame, self.output_rate, self.source_rate); self.source.clear(); self.ready.clear(); @@ -212,13 +190,9 @@ impl Streamer { self.lead_left = u64::try_from(self.lead).unwrap_or(0).saturating_sub(source_frame); let source_frame = source_frame.saturating_add_signed(-self.lead); let seconds = source_frame as f64 / f64::from(self.source_rate); - let landed = self.format.seek( - SeekMode::Accurate, - SeekTo::Time { - time: Time::from(seconds), - track_id: Some(self.track_id), - }, - ); + let landed = self + .format + .seek(SeekMode::Accurate, SeekTo::Time { time: Time::from(seconds), track_id: Some(self.track_id) }); match landed { Ok(seeked) => { self.decoder.reset(); @@ -246,8 +220,7 @@ impl Streamer { fn ts_to_frames(&self, ts: u64) -> u64 { match self.time_base { Some(tb) if tb.denom > 0 => { - (u128::from(ts) * u128::from(tb.numer) * u128::from(self.source_rate) - / u128::from(tb.denom)) as u64 + (u128::from(ts) * u128::from(tb.numer) * u128::from(self.source_rate) / u128::from(tb.denom)) as u64 } _ => ts, } @@ -416,11 +389,9 @@ impl StereoResampler { } source.drain(..take * 2); self.fed += take as u64; - let Ok((_, out_frames)) = self.inner.process_into_buffer( - &[&self.input[0][..need], &self.input[1][..need]], - &mut self.output, - None, - ) else { + let Ok((_, out_frames)) = + self.inner.process_into_buffer(&[&self.input[0][..need], &self.input[1][..need]], &mut self.output, None) + else { return false; }; ready.clear(); @@ -547,10 +518,7 @@ mod tests { let k = 24_000usize; let expected = k as f64 * 44_100.0 / 48_000.0; let got = f64::from(all[k * 2]) * 32768.0; - assert!( - (got - expected).abs() < 2.0, - "frame {k}: {got} vs {expected}" - ); + assert!((got - expected).abs() < 2.0, "frame {k}: {got} vs {expected}"); } const MP3_FRAME: usize = 1152; diff --git a/native/crates/es-engine/src/analysis.rs b/native/crates/es-engine/src/analysis.rs index 721a03f..1a5672a 100644 --- a/native/crates/es-engine/src/analysis.rs +++ b/native/crates/es-engine/src/analysis.rs @@ -42,7 +42,11 @@ fn check(grid: &Grid) -> Result<()> { } /// Write `data` to each path through a temporary file; on any failure put back what was there before. -fn write_all(writes: &[(PathBuf, Vec)], previous: &[(PathBuf, Option>)], then: impl FnOnce() -> Result<()>) -> Result<()> { +fn write_all( + writes: &[(PathBuf, Vec)], + previous: &[(PathBuf, Option>)], + then: impl FnOnce() -> Result<()>, +) -> Result<()> { let result = (|| -> Result<()> { for (path, data) in writes { if let Some(parent) = path.parent() { @@ -57,7 +61,13 @@ fn write_all(writes: &[(PathBuf, Vec)], previous: &[(PathBuf, Option for (path, old) in previous { let restored = match old { Some(bytes) => std::fs::write(path, bytes), - None => std::fs::remove_file(path).or_else(|e| if e.kind() == std::io::ErrorKind::NotFound { Ok(()) } else { Err(e) }), + None => std::fs::remove_file(path).or_else(|e| { + if e.kind() == std::io::ErrorKind::NotFound { + Ok(()) + } else { + Err(e) + } + }), }; if let Err(e) = restored { eprintln!("[es-engine] could not restore {}: {e}", path.display()); @@ -83,7 +93,10 @@ pub fn set_beatgrid(lib: &mut Library, share: &Path, id: &str, grid: &Grid, move let times: Vec = grid.times.iter().map(|t| u32::try_from(*t).unwrap_or(0)).collect(); let beats: Vec = grid.beats.iter().map(|b| u16::try_from(*b).unwrap_or(0)).collect(); let bpms: Vec = grid.bpms.iter().map(|b| (b * 100.0).round_ties_even() / 100.0).collect(); - let mut writes = vec![(dat.clone(), patch_tags(&old_dat, &[("PQTZ", build_beatgrid(pqtz, ×, &beats, &bpms))], &[]).map_err(other)?)]; + let mut writes = vec![( + dat.clone(), + patch_tags(&old_dat, &[("PQTZ", build_beatgrid(pqtz, ×, &beats, &bpms))], &[]).map_err(other)?, + )]; let mut previous = vec![(dat.clone(), Some(old_dat.clone()))]; let ext = dat.with_extension("EXT"); @@ -91,7 +104,10 @@ pub fn set_beatgrid(lib: &mut Library, share: &Path, id: &str, grid: &Grid, move let old_ext = std::fs::read(&ext).map_err(other)?; let ext_tags = Tags::parse(old_ext.clone()).map_err(other)?; if let Some(pqt2) = ext_tags.first("PQT2") { - writes.push((ext.clone(), patch_tags(&old_ext, &[("PQT2", clear_extended_beatgrid(pqt2))], &[]).map_err(other)?)); + writes.push(( + ext.clone(), + patch_tags(&old_ext, &[("PQT2", clear_extended_beatgrid(pqt2))], &[]).map_err(other)?, + )); previous.push((ext, Some(old_ext))); } } @@ -130,17 +146,22 @@ pub struct Options { pub fn apply_analysis(lib: &mut Library, share: &Path, id: &str, result: &Analysis, options: Options) -> Result<()> { let files = lib.track_files(id)?.ok_or_else(|| Error::Other(format!("Unknown track {id}")))?; let features = build::features_from_bytes(&result.waveform); - let audio_name = Path::new(&files.folder_path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let audio_name = + Path::new(&files.folder_path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let relative = match files.analysis_path.clone() { Some(path) => path, None => { - let uuid = lib.track_uuid(id)?.filter(|u| u.len() > 3).ok_or_else(|| Error::Other("This track has no UUID".into()))?; + let uuid = lib + .track_uuid(id)? + .filter(|u| u.len() > 3) + .ok_or_else(|| Error::Other("This track has no UUID".into()))?; format!("/PIONEER/USBANLZ/{}/{}/ANLZ0000.DAT", &uuid[..3], &uuid[3..]) } }; let dat = share.join(relative.trim_matches(['/', '\\'])); - let kinds: Vec<(&str, &[&str], PathBuf)> = build::WAVE_TAGS.iter().map(|(kind, tags)| (*kind, *tags, dat.with_extension(kind))).collect(); + let kinds: Vec<(&str, &[&str], PathBuf)> = + build::WAVE_TAGS.iter().map(|(kind, tags)| (*kind, *tags, dat.with_extension(kind))).collect(); let existing: Vec, Tags)>> = kinds .iter() .map(|(_, _, path)| match std::fs::read(path) { @@ -181,11 +202,13 @@ pub fn apply_analysis(lib: &mut Library, share: &Path, id: &str, result: &Analys } } - let present: Vec = kinds.iter().zip(&existing).filter(|(_, e)| e.is_some()).map(|((_, _, p), _)| p.clone()).collect(); + let present: Vec = + kinds.iter().zip(&existing).filter(|(_, e)| e.is_some()).map(|((_, _, p), _)| p.clone()).collect(); if !present.is_empty() { back_up_once(id, &present).map_err(other)?; } - let previous: Vec<(PathBuf, Option>)> = writes.iter().map(|(p, _)| (p.clone(), std::fs::read(p).ok())).collect(); + let previous: Vec<(PathBuf, Option>)> = + writes.iter().map(|(p, _)| (p.clone(), std::fs::read(p).ok())).collect(); let write = AnalysisWrite { relative_path: &relative, bpm_x100: write_grid.then(|| (result.bpm * 100.0).round_ties_even() as i64), diff --git a/native/crates/es-engine/src/browse.rs b/native/crates/es-engine/src/browse.rs index 8adbcf7..bd032b5 100644 --- a/native/crates/es-engine/src/browse.rs +++ b/native/crates/es-engine/src/browse.rs @@ -29,8 +29,15 @@ pub fn file_row(path: &Path) -> Value { set(&mut row, "title", json!(f.title)); } for (key, value) in [ - ("artist", &f.artist), ("album", &f.album), ("genre", &f.genre), ("label", &f.label), ("remixer", &f.remixer), - ("originalArtist", &f.original_artist), ("composer", &f.composer), ("comment", &f.comment), ("key", &info.key), + ("artist", &f.artist), + ("album", &f.album), + ("genre", &f.genre), + ("label", &f.label), + ("remixer", &f.remixer), + ("originalArtist", &f.original_artist), + ("composer", &f.composer), + ("comment", &f.comment), + ("key", &info.key), ] { set(&mut row, key, json!(value)); } diff --git a/native/crates/es-engine/src/convert.rs b/native/crates/es-engine/src/convert.rs index 3c75995..c293617 100644 --- a/native/crates/es-engine/src/convert.rs +++ b/native/crates/es-engine/src/convert.rs @@ -6,7 +6,10 @@ use rb_anlz::decode::Tags; use rb_anlz::write::{patch_tags, path_tag, timeline_patches}; use rb_library::{ConversionTarget, Library, Stream}; -pub use es_convert::{build_command, clean_preset, convert_file, delay_offset_ms, encode, ffmpeg_path, matches_format, output_path, Preset}; +pub use es_convert::{ + build_command, clean_preset, convert_file, delay_offset_ms, encode, ffmpeg_path, matches_format, output_path, + Preset, +}; use crate::import::file_type_code; use crate::{Error, Result}; @@ -51,7 +54,14 @@ fn convert_one(lib: &mut Library, share: &Path, id: &str, preset: &Preset, mode: let info = es_tags::read(&target).map_err(|e| Error::Other(e.to_string()))?; let offset = delay_offset_ms(&source, &target).unwrap_or(0); let nonzero = |v: i64| (v != 0).then_some(v); - let old_files: Vec = files.analysis_path.as_deref().map(|rel| rb_anlz::files(share, rel)).unwrap_or_default().into_iter().filter(|p| p.is_file()).collect(); + let old_files: Vec = files + .analysis_path + .as_deref() + .map(|rel| rb_anlz::files(share, rel)) + .unwrap_or_default() + .into_iter() + .filter(|p| p.is_file()) + .collect(); let carries = old_files.iter().any(|p| p.extension().is_some_and(|e| e == "DAT")); let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let extension = target.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default(); @@ -102,7 +112,14 @@ fn convert_one(lib: &mut Library, share: &Path, id: &str, preset: &Preset, mode: /// Encode each track's audio file to `preset` and point the library at the result. A track that fails is left /// as it was. -pub fn convert_tracks(lib: &mut Library, share: &Path, ids: &[String], preset: &Preset, mode: Mode, progress: &dyn Fn(usize, usize, Option<&str>)) -> Outcome { +pub fn convert_tracks( + lib: &mut Library, + share: &Path, + ids: &[String], + preset: &Preset, + mode: Mode, + progress: &dyn Fn(usize, usize, Option<&str>), +) -> Outcome { let mut ordered: Vec<&String> = Vec::new(); for id in ids { if !ordered.contains(&id) { diff --git a/native/crates/es-engine/src/device_import.rs b/native/crates/es-engine/src/device_import.rs index 4606f9a..f028d5b 100644 --- a/native/crates/es-engine/src/device_import.rs +++ b/native/crates/es-engine/src/device_import.rs @@ -13,9 +13,9 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; -use rb_library::{DeviceData, Library, NewCue, PlaylistKind, TrackEdit}; use rb_device::paths::volume_path; use rb_device::{Cue as DeviceCue, Device, History, Playlist, Track as DeviceTrack}; +use rb_library::{DeviceData, Library, NewCue, PlaylistKind, TrackEdit}; use crate::import::{import_files, Options as FileOptions}; use crate::place::{candidate, destination, existing_copy, place_copy}; @@ -160,7 +160,11 @@ fn sessions(device: &Device) -> Vec<&History> { fn history_name(row: &History) -> String { let name = row.name.trim(); - if name.is_empty() { "Untitled".into() } else { name.into() } + if name.is_empty() { + "Untitled".into() + } else { + name.into() + } } /// The library's histories, as name and plays, to recognise a session imported before. @@ -177,7 +181,8 @@ fn known_histories(lib: &Library) -> Result)>> { /// Tracks in the order the playlists list them, then the histories, each once. fn ordered_tracks(children: &Children<'_>, device: &Device) -> Vec { let mut seen = Vec::new(); - let mut stack: Vec<&Playlist> = children.get(&0).map(|rows| rows.iter().rev().copied().collect()).unwrap_or_default(); + let mut stack: Vec<&Playlist> = + children.get(&0).map(|rows| rows.iter().rev().copied().collect()).unwrap_or_default(); while let Some(row) = stack.pop() { if row.folder { if let Some(inner) = children.get(&row.export_id) { @@ -216,7 +221,9 @@ fn target_root(options: &Options) -> (PathBuf, bool) { Some(folder) => (folder.clone(), false), None => { let music = options.music.clone().unwrap_or_else(|| { - std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map_or_else(|| PathBuf::from("."), |h| PathBuf::from(h).join("Music")) + std::env::var_os("HOME") + .or_else(|| std::env::var_os("USERPROFILE")) + .map_or_else(|| PathBuf::from("."), |h| PathBuf::from(h).join("Music")) }); (destination(&music), true) } @@ -262,12 +269,25 @@ pub fn preview(lib: &Library, volume: &Path, device: &Device, options: &Options) let mut playlists = Vec::new(); plan_playlists(&kids, 0, Some("root"), 0, &known, &mut playlists); let histories = plan_histories(lib, db_id, volume, device, &root, contents)?; - Ok(Plan { destination: root, layout: if contents { "Contents/Artist/Album" } else { "Artist/Album" }, playlists, histories, tracks }) + Ok(Plan { + destination: root, + layout: if contents { "Contents/Artist/Album" } else { "Artist/Album" }, + playlists, + histories, + tracks, + }) } /// The stick's sessions, and whether the library has each already. A play resolves to the library /// track an import would use: the library's own copy, or an earlier import's copy of the same file. -fn plan_histories(lib: &Library, db_id: i64, volume: &Path, device: &Device, root: &Path, contents: bool) -> Result> { +fn plan_histories( + lib: &Library, + db_id: i64, + volume: &Path, + device: &Device, + root: &Path, + contents: bool, +) -> Result> { let sessions = sessions(device); if sessions.is_empty() { return Ok(Vec::new()); @@ -282,8 +302,13 @@ fn plan_histories(lib: &Library, db_id: i64, volume: &Path, device: &Device, roo let track = device.track(id)?; library_copy(lib, db_id, track).or_else(|| { let audio = audio_of(volume, track)?; - let file_name = if track.filename.is_empty() { audio.file_name()?.to_string_lossy().into_owned() } else { track.filename.clone() }; - let copy = existing_copy(&audio, &candidate(root, &track.artist, &track.album, &file_name, contents))?; + let file_name = if track.filename.is_empty() { + audio.file_name()?.to_string_lossy().into_owned() + } else { + track.filename.clone() + }; + let copy = + existing_copy(&audio, &candidate(root, &track.artist, &track.album, &file_name, contents))?; // The library stores paths with forward slashes, as an import does. by_path.get(©.to_string_lossy().replace('\\', "/")).cloned() }) @@ -294,24 +319,45 @@ fn plan_histories(lib: &Library, db_id: i64, volume: &Path, device: &Device, roo .into_iter() .map(|row| { let name = history_name(row); - let plays: Option> = row.track_ids.iter().filter(|t| device.track(**t).is_some()).map(|t| resolve(*t)).collect(); + let plays: Option> = + row.track_ids.iter().filter(|t| device.track(**t).is_some()).map(|t| resolve(*t)).collect(); let exists = plays.is_some_and(|plays| known.iter().any(|(n, ids)| *n == name && *ids == plays)); PlannedHistory { name, tracks: row.track_ids.len(), exists } }) .collect()) } -fn find<'a>(nodes: &'a [rb_library::PlaylistNode], parent: &str, folder: bool, name: &str) -> Option<&'a rb_library::PlaylistNode> { +fn find<'a>( + nodes: &'a [rb_library::PlaylistNode], + parent: &str, + folder: bool, + name: &str, +) -> Option<&'a rb_library::PlaylistNode> { let kind = if folder { PlaylistKind::Folder } else { PlaylistKind::Playlist }; - nodes.iter().find(|n| n.parent_id == parent && n.kind == kind && (if n.name.trim().is_empty() { "Untitled" } else { n.name.trim() }) == name) + nodes.iter().find(|n| { + n.parent_id == parent + && n.kind == kind + && (if n.name.trim().is_empty() { "Untitled" } else { n.name.trim() }) == name + }) } fn name_of(row: &Playlist) -> String { let name = row.name.trim(); - if name.is_empty() { "Untitled".into() } else { name.into() } + if name.is_empty() { + "Untitled".into() + } else { + name.into() + } } -fn plan_playlists(kids: &Children<'_>, parent_export: i64, parent: Option<&str>, depth: usize, known: &Known, out: &mut Vec) { +fn plan_playlists( + kids: &Children<'_>, + parent_export: i64, + parent: Option<&str>, + depth: usize, + known: &Known, + out: &mut Vec, +) { for row in kids.get(&parent_export).map(Vec::as_slice).unwrap_or_default() { let name = name_of(row); let found = match known.lookup(row, parent, &name) { @@ -324,7 +370,13 @@ fn plan_playlists(kids: &Children<'_>, parent_export: i64, parent: Option<&str>, Match::Existing(node) => Some(node), Match::New => None, }; - out.push(PlannedPlaylist { name, folder: row.folder, depth, tracks: if row.folder { 0 } else { row.track_ids.len() }, exists: found.is_some() }); + out.push(PlannedPlaylist { + name, + folder: row.folder, + depth, + tracks: if row.folder { 0 } else { row.track_ids.len() }, + exists: found.is_some(), + }); if row.folder { plan_playlists(kids, row.export_id, found.map(|n| n.id.as_str()), depth + 1, known, out); } @@ -353,9 +405,20 @@ fn from_device_cue(cue: &DeviceCue) -> NewCue { } /// Give a freshly imported track the analysis files, cues and numbers it had on the stick. -fn carry(lib: &mut Library, share: &Path, volume: &Path, track: &DeviceTrack, content_id: &str, placed: &Path) -> Result<()> { +fn carry( + lib: &mut Library, + share: &Path, + volume: &Path, + track: &DeviceTrack, + content_id: &str, + placed: &Path, +) -> Result<()> { let uuid = lib.track_uuid(content_id)?.ok_or_else(|| Error::Other("the new track has no UUID".into()))?; - let relative = format!("/PIONEER/USBANLZ/{}/{}/ANLZ0000.DAT", uuid.chars().take(3).collect::(), uuid.chars().skip(3).collect::()); + let relative = format!( + "/PIONEER/USBANLZ/{}/{}/ANLZ0000.DAT", + uuid.chars().take(3).collect::(), + uuid.chars().skip(3).collect::() + ); let dat = share.join(relative.trim_start_matches('/')); let name = placed.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let path_tag = rb_anlz::write::path_tag(&format!("?/{name}")); @@ -371,7 +434,8 @@ fn carry(lib: &mut Library, share: &Path, volume: &Path, track: &DeviceTrack, co continue; } let data = std::fs::read(&from).map_err(|e| Error::Other(e.to_string()))?; - let patched = rb_anlz::write::replace_tags(&data, &[("PPTH", path_tag.clone())]).map_err(|e| Error::Other(e.to_string()))?; + let patched = rb_anlz::write::replace_tags(&data, &[("PPTH", path_tag.clone())]) + .map_err(|e| Error::Other(e.to_string()))?; let to = dat.with_extension(suffix); if let Some(parent) = to.parent() { std::fs::create_dir_all(parent).map_err(|e| Error::Other(e.to_string()))?; @@ -464,7 +528,11 @@ fn create_playlists( ) -> rb_library::Result<()> { for row in kids.get(&parent_export).map(Vec::as_slice).unwrap_or_default() { let name = name_of(row); - let ids: Vec = if row.folder { Vec::new() } else { row.track_ids.iter().filter_map(|t| resolved.get(t).cloned()).collect() }; + let ids: Vec = if row.folder { + Vec::new() + } else { + row.track_ids.iter().filter_map(|t| resolved.get(t).cloned()).collect() + }; let (id, is_new) = match known.lookup(row, Some(parent.as_deref().unwrap_or("root")), &name) { Match::Retired => { if row.folder { @@ -485,7 +553,11 @@ fn create_playlists( }; if row.folder { // Nothing inside a folder that was just made can already exist. - let inner = if is_new { &Known { existing: Vec::new(), policy: known.policy, origins: known.origins.clone() } } else { known }; + let inner = if is_new { + &Known { existing: Vec::new(), policy: known.policy, origins: known.origins.clone() } + } else { + known + }; create_playlists(tx, kids, row.export_id, Some(id), inner, resolved, created)?; } } @@ -524,7 +596,11 @@ pub fn import_device( outcome.failed.push((title, "Audio file is missing on the USB".into())); continue; }; - let file_name = if track.filename.is_empty() { audio.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default() } else { track.filename.clone() }; + let file_name = if track.filename.is_empty() { + audio.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default() + } else { + track.filename.clone() + }; let wanted = candidate(&root, &track.artist, &track.album, &file_name, contents); let (placed, created) = match place_copy(&audio, &wanted) { Ok(done) => done, @@ -533,7 +609,12 @@ pub fn import_device( continue; } }; - let imported = import_files(lib, share, &[placed.to_string_lossy().into_owned()], &FileOptions { artwork: true, playlist: None }); + let imported = import_files( + lib, + share, + &[placed.to_string_lossy().into_owned()], + &FileOptions { artwork: true, playlist: None }, + ); let done = match imported { Ok(done) if done.failed.is_empty() && !done.ids.is_empty() => done, other => { @@ -541,14 +622,20 @@ pub fn import_device( let _ = std::fs::remove_file(&placed); } let error = match other { - Ok(done) => done.failed.first().map_or_else(|| "Couldn’t import the track".to_owned(), |f| f.error.clone()), + Ok(done) => { + done.failed.first().map_or_else(|| "Couldn’t import the track".to_owned(), |f| f.error.clone()) + } Err(e) => e.to_string(), }; outcome.failed.push((title, error)); continue; } }; - if created { outcome.copied += 1 } else { outcome.reused += 1 } + if created { + outcome.copied += 1 + } else { + outcome.reused += 1 + } let content_id = done.ids[0].clone(); if !done.added.is_empty() { if let Err(e) = carry(lib, share, volume, track, &content_id, &placed) { @@ -560,7 +647,14 @@ pub fn import_device( progress(Progress { done: order.len(), total: order.len(), name: String::new() }); let known = Known::new(lib, volume, options.policy)?; - let wrapper_name = format!("Imported from {}", if device.device_name.is_empty() { volume.file_name().map_or_else(|| "device".into(), |n| n.to_string_lossy().into_owned()) } else { device.device_name.clone() }); + let wrapper_name = format!( + "Imported from {}", + if device.device_name.is_empty() { + volume.file_name().map_or_else(|| "device".into(), |n| n.to_string_lossy().into_owned()) + } else { + device.device_name.clone() + } + ); let mut known_histories = known_histories(lib)?; let mut created = 0; let mut histories = 0; diff --git a/native/crates/es-engine/src/import.rs b/native/crates/es-engine/src/import.rs index e95419e..0afc63c 100644 --- a/native/crates/es-engine/src/import.rs +++ b/native/crates/es-engine/src/import.rs @@ -107,7 +107,8 @@ pub fn import_files(lib: &mut Library, share: &Path, paths: &[String], options: outcome.failed.push(Failure { path: raw.clone(), error: format!("rekordbox can't import {shown} files") }); continue; } - let Some(size) = path.is_absolute().then(|| std::fs::metadata(path).ok().filter(|m| m.is_file())).flatten() else { + let Some(size) = path.is_absolute().then(|| std::fs::metadata(path).ok().filter(|m| m.is_file())).flatten() + else { outcome.failed.push(Failure { path: raw.clone(), error: "File not found".into() }); continue; }; @@ -162,7 +163,8 @@ pub fn import_files(lib: &mut Library, share: &Path, paths: &[String], options: ids.push(id.clone()); continue; } - let stem = Path::new(&item.facts.name).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let stem = + Path::new(&item.facts.name).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); let id = if let Some((id, _)) = rows.first() { tx.revive_track(id, &item.facts, &stream_of(&item.info))?; id.clone() diff --git a/native/crates/es-engine/src/lib.rs b/native/crates/es-engine/src/lib.rs index 2c4ed68..c24c170 100644 --- a/native/crates/es-engine/src/lib.rs +++ b/native/crates/es-engine/src/lib.rs @@ -7,8 +7,8 @@ pub mod convert; pub mod device_import; pub mod import; pub mod library; -pub mod relocate; pub mod place; +pub mod relocate; pub mod sync; pub use es_convert::inspect; diff --git a/native/crates/es-engine/src/library.rs b/native/crates/es-engine/src/library.rs index 1c82ea3..2fc2b4f 100644 --- a/native/crates/es-engine/src/library.rs +++ b/native/crates/es-engine/src/library.rs @@ -87,18 +87,9 @@ fn auto_due(backups: &Backups) -> bool { due } -fn back_up( - backups: &Backups, - source: &Path, - reason: &str, - emit: &impl Fn(ServiceEvent), -) -> Result> { - let made = backups.create(source, reason, &|progress| { - emit(ServiceEvent::BackupProgress(progress)) - }); - emit(ServiceEvent::BackupProgress( - json!({ "stage": "done", "reason": reason }), - )); +fn back_up(backups: &Backups, source: &Path, reason: &str, emit: &impl Fn(ServiceEvent)) -> Result> { + let made = backups.create(source, reason, &|progress| emit(ServiceEvent::BackupProgress(progress))); + emit(ServiceEvent::BackupProgress(json!({ "stage": "done", "reason": reason }))); let made = made?; if made.is_some() { emit(ServiceEvent::BackupChanged); @@ -111,16 +102,8 @@ pub enum ServiceEvent { BackupProgress(Value), BackupChanged, LibraryReloaded, - ConvertProgress { - done: usize, - total: usize, - id: Option, - }, - UsbImportProgress { - done: usize, - total: usize, - name: String, - }, + ConvertProgress { done: usize, total: usize, id: Option }, + UsbImportProgress { done: usize, total: usize, name: String }, UsbSyncProgress(crate::sync::Progress), } @@ -215,9 +198,7 @@ fn tag_edit(change: &TrackEdit) -> es_tags::Edit { composer: change.composer.clone(), comment: change.comment.clone(), year: change.year.map(|year| u32::try_from(year).unwrap_or(0)), - track_no: change - .track_no - .map(|number| u32::try_from(number).unwrap_or(0)), + track_no: change.track_no.map(|number| u32::try_from(number).unwrap_or(0)), } } @@ -235,10 +216,7 @@ impl LibraryService { fn with_backup_root(root: PathBuf) -> Self { let verify = |path: &Path| { rb_library::verify(path) - .map(|counts| es_backup::Counts { - tracks: counts.tracks, - playlists: counts.playlists, - }) + .map(|counts| es_backup::Counts { tracks: counts.tracks, playlists: counts.playlists }) .map_err(|error| es_backup::Error::Message(error.to_string())) }; Self { @@ -283,18 +261,12 @@ impl LibraryService { } fn read_model(&self) -> Result> { - let session = self - .session - .as_ref() - .ok_or_else(|| crate::Error::Other("Library not open".into()))?; + let session = self.session.as_ref().ok_or_else(|| crate::Error::Other("Library not open".into()))?; Ok(LibraryRead::new(session.database())) } pub fn info(&self) -> Result { - let session = self - .session - .as_ref() - .ok_or_else(|| crate::Error::Other("Library not open".into()))?; + let session = self.session.as_ref().ok_or_else(|| crate::Error::Other("Library not open".into()))?; Ok(LibraryInfo { db_path: session.source().to_string_lossy().into_owned(), snapshot_time: session.snapshot_time(), @@ -361,25 +333,13 @@ impl LibraryService { } pub fn playlist_selection(&self) -> Result<(Vec, u64)> { - let database = self - .session - .as_ref() - .ok_or_else(|| crate::Error::Other("Library not open".into()))? - .database(); - let ids = database - .playlists()? - .into_iter() - .map(|playlist| playlist.id) - .collect(); + let database = self.session.as_ref().ok_or_else(|| crate::Error::Other("Library not open".into()))?.database(); + let ids = database.playlists()?.into_iter().map(|playlist| playlist.id).collect(); Ok((ids, u64::try_from(database.db_id()?).unwrap_or(0))) } pub fn inspect_tracks(&self, requests: &[InspectionRequest]) -> Result> { - let database = self - .session - .as_ref() - .ok_or_else(|| crate::Error::Other("Library not open".into()))? - .database(); + let database = self.session.as_ref().ok_or_else(|| crate::Error::Other("Library not open".into()))?.database(); let mut inspected = Vec::new(); for request in requests.iter().take(80) { let files = database @@ -398,11 +358,9 @@ impl LibraryService { } let path = Path::new(&files.folder_path); if request.has_cache { - if let Some((size, mtime)) = crate::inspect::same_fingerprint( - path, - request.cached_size, - request.cached_mtime.as_deref(), - ) { + if let Some((size, mtime)) = + crate::inspect::same_fingerprint(path, request.cached_size, request.cached_mtime.as_deref()) + { inspected.push(TrackInspection { id: request.id.clone(), size, @@ -428,10 +386,7 @@ impl LibraryService { } fn edit(&mut self, change: impl FnOnce(&mut Tx<'_>) -> rb_library::Result) -> Result { - let session = self - .session - .as_mut() - .ok_or_else(|| crate::Error::Other("Library not open".into()))?; + let session = self.session.as_mut().ok_or_else(|| crate::Error::Other("Library not open".into()))?; session.with_live(|database| Ok(database.write(change)?)) } @@ -445,12 +400,7 @@ impl LibraryService { self.playlist_tracks(id) } - pub fn playlist_move( - &mut self, - id: &str, - track_ids: &[String], - index: usize, - ) -> Result> { + pub fn playlist_move(&mut self, id: &str, track_ids: &[String], index: usize) -> Result> { self.edit(|tx| tx.move_in_playlist(id, track_ids, index))?; self.playlist_tracks(id) } @@ -468,11 +418,7 @@ impl LibraryService { track_ids: &[String], ) -> Result<(String, Vec)> { let fallback = if folder { "New folder" } else { "New playlist" }; - let name = if name.trim().is_empty() { - fallback - } else { - name.trim() - }; + let name = if name.trim().is_empty() { fallback } else { name.trim() }; let parent = parent.filter(|parent| *parent != "root"); let id = self.edit(|tx| tx.create_playlist(name, parent, folder, track_ids))?; Ok((id, self.playlists()?)) @@ -492,20 +438,12 @@ impl LibraryService { self.playlists() } - pub fn tag_add( - &mut self, - tag_id: &str, - track_ids: &[String], - ) -> Result> { + pub fn tag_add(&mut self, tag_id: &str, track_ids: &[String]) -> Result> { self.edit(|tx| tx.add_tag(tag_id, track_ids))?; self.tracks_by_id(track_ids) } - pub fn tag_remove( - &mut self, - tag_id: &str, - track_ids: &[String], - ) -> Result> { + pub fn tag_remove(&mut self, tag_id: &str, track_ids: &[String]) -> Result> { self.edit(|tx| tx.remove_tag(tag_id, track_ids))?; self.tracks_by_id(track_ids) } @@ -521,12 +459,7 @@ impl LibraryService { self.cues(id) } - pub fn cue_add_memory( - &mut self, - id: &str, - ms: i64, - end_ms: Option, - ) -> Result> { + pub fn cue_add_memory(&mut self, id: &str, ms: i64, end_ms: Option) -> Result> { self.edit(|tx| tx.add_memory_cue(id, ms, end_ms))?; self.cues(id) } @@ -536,48 +469,28 @@ impl LibraryService { self.cues(id) } - pub fn cue_set_color( - &mut self, - id: &str, - cue_id: &str, - color: Option, - ) -> Result> { + pub fn cue_set_color(&mut self, id: &str, cue_id: &str, color: Option) -> Result> { self.edit(|tx| tx.set_cue_color(id, cue_id, color))?; self.cues(id) } pub fn remove_tracks(&mut self, ids: &[String]) -> Result { let removed = self.edit(|tx| tx.remove_tracks(ids))?; - let share = self - .session - .as_ref() - .ok_or_else(|| crate::Error::Other("Library not open".into()))? - .database() - .share_dir(); + let share = + self.session.as_ref().ok_or_else(|| crate::Error::Other("Library not open".into()))?.database().share_dir(); for item in &removed { if let Some(path) = &item.analysis_path { if let Err(error) = rb_anlz::discard(&rb_anlz::files(&share, path)) { - eprintln!( - "[es-engine] could not delete analysis files for {}: {error}", - item.id - ); + eprintln!("[es-engine] could not delete analysis files for {}: {error}", item.id); } } } let mut ids: Vec = removed.into_iter().map(|item| item.id).collect(); ids.sort_unstable(); - Ok(RemovedTracks { - ids, - playlists: self.playlists()?, - }) + Ok(RemovedTracks { ids, playlists: self.playlists()? }) } - pub fn track_update( - &mut self, - ids: &[String], - change: &TrackEdit, - write_tags: bool, - ) -> Result { + pub fn track_update(&mut self, ids: &[String], change: &TrackEdit, write_tags: bool) -> Result { let mut unique = ids.to_vec(); unique.dedup(); if change != &TrackEdit::default() && !unique.is_empty() { @@ -603,33 +516,24 @@ impl LibraryService { match es_tags::write(path, &file_edit) { Ok(()) => { if let Ok(metadata) = path.metadata() { - sizes - .push((id.clone(), i64::try_from(metadata.len()).unwrap_or(0))); + sizes.push((id.clone(), i64::try_from(metadata.len()).unwrap_or(0))); } } Err(error) => { - let name = path.file_name().map_or_else( - || files.folder_path.clone(), - |name| name.to_string_lossy().into_owned(), - ); + let name = path + .file_name() + .map_or_else(|| files.folder_path.clone(), |name| name.to_string_lossy().into_owned()); tag_errors.push(format!("{name}: {error}")); } } } if !sizes.is_empty() { - self.edit(|tx| { - sizes - .iter() - .try_for_each(|(id, size)| tx.set_file_size(id, *size)) - })?; + self.edit(|tx| sizes.iter().try_for_each(|(id, size)| tx.set_file_size(id, *size)))?; } } } - Ok(TrackUpdateResult { - tracks: self.tracks_by_id(&unique)?, - tag_errors, - }) + Ok(TrackUpdateResult { tracks: self.tracks_by_id(&unique)?, tag_errors }) } pub fn track_import( @@ -638,15 +542,9 @@ impl LibraryService { playlist: Option, artwork: bool, ) -> Result { - let session = self - .session - .as_ref() - .ok_or_else(|| crate::Error::Other("Library not open".into()))?; + let session = self.session.as_ref().ok_or_else(|| crate::Error::Other("Library not open".into()))?; let share = session.database().share_dir(); - let options = crate::import::Options { - artwork, - playlist: playlist.clone(), - }; + let options = crate::import::Options { artwork, playlist: playlist.clone() }; let outcome = self .session .as_mut() @@ -656,10 +554,7 @@ impl LibraryService { let failed = outcome .failed .into_iter() - .map(|failure| TrackImportFailure { - path: failure.path, - error: failure.error, - }) + .map(|failure| TrackImportFailure { path: failure.path, error: failure.error }) .collect(); Ok(TrackImportResult { tracks: self.tracks_by_id(&outcome.added)?, @@ -670,17 +565,10 @@ impl LibraryService { }) } - pub fn track_relocate( - &mut self, - moves: &[(String, String)], - ) -> Result> { - let session = self - .session - .as_mut() - .ok_or_else(|| crate::Error::Other("Library not open".into()))?; + pub fn track_relocate(&mut self, moves: &[(String, String)]) -> Result> { + let session = self.session.as_mut().ok_or_else(|| crate::Error::Other("Library not open".into()))?; let share = session.database().share_dir(); - let ids = - session.with_live(|database| crate::relocate::relocate(database, &share, moves))?; + let ids = session.with_live(|database| crate::relocate::relocate(database, &share, moves))?; self.tracks_by_id(&ids) } @@ -690,20 +578,11 @@ impl LibraryService { grid: &crate::analysis::Grid, cues: &[rb_library::CueMove], ) -> Result { - let session = self - .session - .as_mut() - .ok_or_else(|| crate::Error::Other("Library not open".into()))?; + let session = self.session.as_mut().ok_or_else(|| crate::Error::Other("Library not open".into()))?; let share = session.database().share_dir(); - let bpm = session.with_live(|database| { - crate::analysis::set_beatgrid(database, &share, id, grid, cues) - })?; + let bpm = session.with_live(|database| crate::analysis::set_beatgrid(database, &share, id, grid, cues))?; let reads = self.read_model()?; - Ok(BeatgridResult { - beatgrid: reads.beatgrid(id)?, - cues: reads.cues(id)?, - bpm, - }) + Ok(BeatgridResult { beatgrid: reads.beatgrid(id)?, cues: reads.cues(id)?, bpm }) } pub fn track_apply_analysis( @@ -712,14 +591,9 @@ impl LibraryService { analysis: &crate::analysis::Analysis, options: crate::analysis::Options, ) -> Result> { - let session = self - .session - .as_mut() - .ok_or_else(|| crate::Error::Other("Library not open".into()))?; + let session = self.session.as_mut().ok_or_else(|| crate::Error::Other("Library not open".into()))?; let share = session.database().share_dir(); - session.with_live(|database| { - crate::analysis::apply_analysis(database, &share, id, analysis, options) - })?; + session.with_live(|database| crate::analysis::apply_analysis(database, &share, id, analysis, options))?; Ok(self.tracks_by_id(&[id.to_owned()])?.into_iter().next()) } @@ -730,36 +604,18 @@ impl LibraryService { mode: crate::convert::Mode, emit: &impl Fn(ServiceEvent), ) -> Result { - let session = self - .session - .as_mut() - .ok_or_else(|| crate::Error::Other("Library not open".into()))?; + let session = self.session.as_mut().ok_or_else(|| crate::Error::Other("Library not open".into()))?; let share = session.database().share_dir(); let outcome = session.with_live(|database| { - Ok(crate::convert::convert_tracks( - database, - &share, - ids, - preset, - mode, - &|done, total, id| { - emit(ServiceEvent::ConvertProgress { - done, - total, - id: id.map(str::to_owned), - }); - }, - )) + Ok(crate::convert::convert_tracks(database, &share, ids, preset, mode, &|done, total, id| { + emit(ServiceEvent::ConvertProgress { done, total, id: id.map(str::to_owned) }); + })) })?; Ok(TrackConvertResult { tracks: self.tracks_by_id(&outcome.ids)?, ids: outcome.ids, originals: outcome.originals, - failed: outcome - .failed - .into_iter() - .map(|(id, error)| TrackConvertFailure { id, error }) - .collect(), + failed: outcome.failed.into_iter().map(|(id, error)| TrackConvertFailure { id, error }).collect(), }) } @@ -770,26 +626,16 @@ impl LibraryService { options: &crate::device_import::Options, emit: &impl Fn(ServiceEvent), ) -> Result { - let session = self - .session - .as_mut() - .ok_or_else(|| crate::Error::Other("Library not open".into()))?; + let session = self.session.as_mut().ok_or_else(|| crate::Error::Other("Library not open".into()))?; let share = session.database().share_dir(); session.with_live(|database| { - crate::device_import::import_device( - database, - &share, - volume, - device, - options, - &|progress| { - emit(ServiceEvent::UsbImportProgress { - done: progress.done, - total: progress.total, - name: progress.name, - }); - }, - ) + crate::device_import::import_device(database, &share, volume, device, options, &|progress| { + emit(ServiceEvent::UsbImportProgress { + done: progress.done, + total: progress.total, + name: progress.name, + }); + }) }) } @@ -802,11 +648,7 @@ impl LibraryService { decisions: Option<&rb_model::conflict::Decisions>, convert: Option<&crate::convert::Preset>, ) -> Result { - let database = self - .session - .as_ref() - .ok_or_else(|| crate::Error::Other("Library not open".into()))? - .database(); + let database = self.session.as_ref().ok_or_else(|| crate::Error::Other("Library not open".into()))?.database(); crate::sync::prepare_sync(database, volume, playlist_ids, decisions, convert) } @@ -816,11 +658,7 @@ impl LibraryService { playlist_ids: &[String], convert: Option<&crate::convert::Preset>, ) -> Result { - let database = self - .session - .as_ref() - .ok_or_else(|| crate::Error::Other("Library not open".into()))? - .database(); + let database = self.session.as_ref().ok_or_else(|| crate::Error::Other("Library not open".into()))?.database(); crate::sync::inspect_volume(database, volume, playlist_ids, convert) } @@ -837,10 +675,7 @@ impl LibraryService { } fn source(&self) -> Option { - self.session - .as_ref() - .map(|session| session.source().to_path_buf()) - .or_else(Database::installed_path) + self.session.as_ref().map(|session| session.source().to_path_buf()).or_else(Database::installed_path) } pub fn backup_list(&self) -> Vec { @@ -853,12 +688,7 @@ impl LibraryService { self.backups().settings() } - pub fn backup_set_settings( - &self, - auto: Option, - keep: Option, - interval: Option, - ) -> Result { + pub fn backup_set_settings(&self, auto: Option, keep: Option, interval: Option) -> Result { Ok(self.backups().set_settings(auto, keep, interval)?) } @@ -868,19 +698,13 @@ impl LibraryService { /// A manual backup, to run without holding the service. pub fn backup_create_job(&self) -> Result { - let source = self.source().ok_or_else(|| { - crate::Error::Other("No rekordbox library found on this computer".into()) - })?; + let source = + self.source().ok_or_else(|| crate::Error::Other("No rekordbox library found on this computer".into()))?; Ok(self.job(source, "manual")) } fn job(&self, source: PathBuf, reason: &'static str) -> BackupJob { - BackupJob { - backups: Arc::clone(&self.backups), - gate: Arc::clone(&self.backup_gate), - source, - reason, - } + BackupJob { backups: Arc::clone(&self.backups), gate: Arc::clone(&self.backup_gate), source, reason } } pub fn backup_delete(&self, id: &str) -> Result> { @@ -889,19 +713,14 @@ impl LibraryService { } pub fn backup_restore(&mut self, id: &str, emit: &impl Fn(ServiceEvent)) -> Result { - let source = self.source().ok_or_else(|| { - crate::Error::Other("No rekordbox library found on this computer".into()) - })?; + let source = + self.source().ok_or_else(|| crate::Error::Other("No rekordbox library found on this computer".into()))?; let backed_up = self.session.as_ref().is_some_and(LibrarySession::backed_up); let gate = Arc::clone(&self.backup_gate); let _gate = lock_gate(&gate); self.close(); - let restored = self.backups().restore(id, &source, &|progress| { - emit(ServiceEvent::BackupProgress(progress)) - }); - emit(ServiceEvent::BackupProgress( - json!({ "stage": "done", "reason": "restore" }), - )); + let restored = self.backups().restore(id, &source, &|progress| emit(ServiceEvent::BackupProgress(progress))); + emit(ServiceEvent::BackupProgress(json!({ "stage": "done", "reason": "restore" }))); emit(ServiceEvent::BackupChanged); let _ = self.open(source, false, backed_up); emit(ServiceEvent::LibraryReloaded); @@ -929,9 +748,7 @@ impl LibraryService { }; if writable && !session.backed_up() && auto_enabled(self.backups()) { if rb_library::rekordbox_running() { - return Err(crate::Error::Other( - "Close rekordbox before editing the library".into(), - )); + return Err(crate::Error::Other("Close rekordbox before editing the library".into())); } // Wait for a daily backup already running; it may make this one unnecessary. let gate = Arc::clone(&self.backup_gate); @@ -939,15 +756,9 @@ impl LibraryService { if auto_due(self.backups()) { back_up(self.backups(), session.source(), "before-edit", emit)?; } - self.session - .as_mut() - .expect("session checked above") - .mark_backed_up(); + self.session.as_mut().expect("session checked above").mark_backed_up(); } - self.session - .as_mut() - .expect("session checked above") - .set_writable(writable) + self.session.as_mut().expect("session checked above").set_writable(writable) } } @@ -961,7 +772,11 @@ fn open_snapshot(source: &Path) -> rb_library::Result { let started = std::time::Instant::now(); let result = Database::open_snapshot(source); if std::env::var_os("EXPORTSTUDIO_PROFILE_LIBRARY_OPEN").is_some() { - eprintln!("[library-profile] snapshot source={} total_ms={:.1}", source.display(), started.elapsed().as_secs_f64() * 1000.0); + eprintln!( + "[library-profile] snapshot source={} total_ms={:.1}", + source.display(), + started.elapsed().as_secs_f64() * 1000.0 + ); } result } @@ -969,11 +784,7 @@ fn open_snapshot(source: &Path) -> rb_library::Result { impl LibrarySession { pub fn open(source: PathBuf, writable: bool, backed_up: bool) -> Result { let database = open_snapshot(&source)?; - let live = if writable { - Some(Database::open_live(&source, Guard::RefuseWhileRunning)?) - } else { - None - }; + let live = if writable { Some(Database::open_live(&source, Guard::RefuseWhileRunning)?) } else { None }; Ok(Self { database, live, @@ -1044,9 +855,7 @@ impl LibrarySession { /// Run an edit against the guarded live database, then refresh the read snapshot. pub fn with_live(&mut self, work: impl FnOnce(&mut Database) -> Result) -> Result { if !self.writable { - return Err(crate::Error::Other( - "Unlock editing to make changes to the library".into(), - )); + return Err(crate::Error::Other("Unlock editing to make changes to the library".into())); } if self.guard == Guard::RefuseWhileRunning && rb_library::rekordbox_running() { return Err(rb_library::Error::RekordboxRunning.into()); @@ -1067,10 +876,7 @@ pub struct LibraryRead<'a> { impl<'a> LibraryRead<'a> { #[must_use] pub fn new(database: &'a Database) -> Self { - Self { - database, - share: database.share_dir(), - } + Self { database, share: database.share_dir() } } pub fn tracks(&self) -> Result> { @@ -1106,11 +912,7 @@ impl<'a> LibraryRead<'a> { } pub fn track_detail(&self, id: &str) -> Result { - Ok(es_index::detail::track_detail( - self.database, - &self.share, - id, - )?) + Ok(es_index::detail::track_detail(self.database, &self.share, id)?) } pub fn cues(&self, id: &str) -> Result> { @@ -1118,11 +920,7 @@ impl<'a> LibraryRead<'a> { } pub fn beatgrid(&self, id: &str) -> Result> { - Ok(es_index::detail::beatgrid_for( - self.database, - &self.share, - id, - )?) + Ok(es_index::detail::beatgrid_for(self.database, &self.share, id)?) } pub fn previews(&self, ids: &[String]) -> Result> { @@ -1130,13 +928,7 @@ impl<'a> LibraryRead<'a> { } pub fn resolve_media(&self, kind: &str, id: &str, size: &str) -> Result> { - Ok(es_index::media::resolve_media( - self.database, - &self.share, - kind, - id, - size, - )?) + Ok(es_index::media::resolve_media(self.database, &self.share, kind, id, size)?) } pub fn find_missing(&self, ids: &[String], directory: &Path) -> Result { @@ -1170,9 +962,7 @@ mod tests { { let connection = fixture::connect(&path).unwrap(); Rows(&connection).track("track-1", "Test track").unwrap(); - Rows(&connection) - .playlist("playlist-1", "Test playlist", 0) - .unwrap(); + Rows(&connection).playlist("playlist-1", "Test playlist", 0).unwrap(); } let mut service = LibraryService::with_backup_root(directory.path().join("backups")); @@ -1197,10 +987,7 @@ mod tests { let error = session.with_live(|_| Ok(())).unwrap_err(); - assert_eq!( - error.to_string(), - "Unlock editing to make changes to the library" - ); + assert_eq!(error.to_string(), "Unlock editing to make changes to the library"); } #[test] @@ -1227,9 +1014,7 @@ mod tests { let mut service = LibraryService::with_backup_root(directory.path().join("backups")); service.open(path, false, false).unwrap(); - assert!(service - .open(directory.path().join("missing.db"), false, false) - .is_err()); + assert!(service.open(directory.path().join("missing.db"), false, false).is_err()); assert!(service.session().is_none()); } @@ -1298,11 +1083,19 @@ mod tests { let stage = std::time::Instant::now(); let playlists = service.playlists().unwrap(); - eprintln!("[library-profile] playlists_ms={:.1} rows={}", stage.elapsed().as_secs_f64() * 1000.0, playlists.len()); + eprintln!( + "[library-profile] playlists_ms={:.1} rows={}", + stage.elapsed().as_secs_f64() * 1000.0, + playlists.len() + ); let stage = std::time::Instant::now(); let histories = service.histories().unwrap(); - eprintln!("[library-profile] histories_ms={:.1} rows={}", stage.elapsed().as_secs_f64() * 1000.0, histories.len()); + eprintln!( + "[library-profile] histories_ms={:.1} rows={}", + stage.elapsed().as_secs_f64() * 1000.0, + histories.len() + ); let stage = std::time::Instant::now(); let tags = service.my_tags().unwrap(); @@ -1310,11 +1103,19 @@ mod tests { let stage = std::time::Instant::now(); let members = service.playlist_members().unwrap(); - eprintln!("[library-profile] playlist_members_ms={:.1} rows={}", stage.elapsed().as_secs_f64() * 1000.0, members.len()); + eprintln!( + "[library-profile] playlist_members_ms={:.1} rows={}", + stage.elapsed().as_secs_f64() * 1000.0, + members.len() + ); let stage = std::time::Instant::now(); let volumes = rb_device::volumes::list(None); - eprintln!("[library-profile] usb_list_ms={:.1} volumes={}", stage.elapsed().as_secs_f64() * 1000.0, volumes.len()); + eprintln!( + "[library-profile] usb_list_ms={:.1} volumes={}", + stage.elapsed().as_secs_f64() * 1000.0, + volumes.len() + ); let stage = std::time::Instant::now(); let backup_created = service.daily_backup(&|_| {}).unwrap(); @@ -1332,15 +1133,11 @@ mod tests { { let connection = fixture::connect(&path).unwrap(); Rows(&connection).track("track-1", "Test track").unwrap(); - Rows(&connection) - .playlist("playlist-1", "Test playlist", 0) - .unwrap(); + Rows(&connection).playlist("playlist-1", "Test playlist", 0).unwrap(); } let mut service = writable_fixture_service(directory.path(), &path); - let ids = service - .playlist_add("playlist-1", &["track-1".into()]) - .unwrap(); + let ids = service.playlist_add("playlist-1", &["track-1".into()]).unwrap(); assert_eq!(ids, ["track-1"]); assert_eq!(service.playlist_tracks("playlist-1").unwrap(), ["track-1"]); @@ -1371,14 +1168,9 @@ mod tests { Rows(&connection).track("track-1", "Original").unwrap(); } let mut service = writable_fixture_service(directory.path(), &path); - let change = TrackEdit { - title: Some("Updated".into()), - ..TrackEdit::default() - }; + let change = TrackEdit { title: Some("Updated".into()), ..TrackEdit::default() }; - let result = service - .track_update(&["track-1".into()], &change, false) - .unwrap(); + let result = service.track_update(&["track-1".into()], &change, false).unwrap(); assert_eq!(result.tracks[0].title, "Updated"); assert!(result.tag_errors.is_empty()); @@ -1390,9 +1182,7 @@ mod tests { let path = fixture::build(directory.path(), 1).unwrap(); { let connection = fixture::connect(&path).unwrap(); - let journal_mode: String = connection - .query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0)) - .unwrap(); + let journal_mode: String = connection.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0)).unwrap(); assert_eq!(journal_mode.to_ascii_lowercase(), "wal"); Rows(&connection).track("track-1", "Test track").unwrap(); } @@ -1423,15 +1213,9 @@ mod tests { service.cue_add_memory("track-1", 500, Some(2500)).unwrap(); let cues = service.cue_set_hot("track-1", 1, 4000, Some(8000)).unwrap(); - let mut ranges: Vec<_> = cues - .iter() - .map(|cue| (cue.kind, cue.slot, cue.start, cue.end)) - .collect(); + let mut ranges: Vec<_> = cues.iter().map(|cue| (cue.kind, cue.slot, cue.start, cue.end)).collect(); ranges.sort_unstable(); - assert_eq!( - ranges, - [("hot", 1, 4000, Some(8000)), ("memory", 0, 500, Some(2500))] - ); + assert_eq!(ranges, [("hot", 1, 4000, Some(8000)), ("memory", 0, 500, Some(2500))]); } #[test] @@ -1446,11 +1230,7 @@ mod tests { let missing_path = directory.path().join("temporarily-missing.db"); service.session.as_mut().unwrap().source = missing_path; - assert!(service - .session_mut() - .unwrap() - .set_writable(false) - .is_err()); + assert!(service.session_mut().unwrap().set_writable(false).is_err()); assert!(service.session().unwrap().source_changed()); assert!(!service.session().unwrap().is_writable()); diff --git a/native/crates/es-engine/src/place.rs b/native/crates/es-engine/src/place.rs index 549ced2..de5a82b 100644 --- a/native/crates/es-engine/src/place.rs +++ b/native/crates/es-engine/src/place.rs @@ -31,12 +31,14 @@ fn trim_end(mut text: String) -> String { #[must_use] pub fn fat_safe(name: &str) -> String { - let replaced: String = name - .nfc() - .map(|c| if "/\\:*?\"<>|".contains(c) || u32::from(c) < 0x20 { '_' } else { c }) - .collect(); + let replaced: String = + name.nfc().map(|c| if "/\\:*?\"<>|".contains(c) || u32::from(c) < 0x20 { '_' } else { c }).collect(); let cleaned = trim_end(replaced); - if cleaned.is_empty() { "Unknown".into() } else { cleaned } + if cleaned.is_empty() { + "Unknown".into() + } else { + cleaned + } } #[must_use] @@ -46,7 +48,11 @@ pub fn dir_name(name: &str) -> String { return safe; } let cut = trim_end(safe.chars().take(DIR_NAME_MAX).collect()); - if cut.is_empty() { "Unknown".into() } else { cut } + if cut.is_empty() { + "Unknown".into() + } else { + cut + } } #[must_use] @@ -147,7 +153,8 @@ pub(crate) fn existing_copy(source: &Path, wanted: &Path) -> Option { /// Copy `source` beside `wanted` under a free name, never replacing a file. The copy is checked byte for byte. fn copy_new(source: &Path, wanted: &Path) -> Result { let parent = wanted.parent().ok_or_else(|| Error::Other("a copy needs a folder".into()))?; - let name = wanted.file_name().ok_or_else(|| Error::Other("a copy needs a name".into()))?.to_string_lossy().into_owned(); + let name = + wanted.file_name().ok_or_else(|| Error::Other("a copy needs a name".into()))?.to_string_lossy().into_owned(); fs::create_dir_all(parent).map_err(|e| Error::Other(e.to_string()))?; for n in 0..TRIES { let target = parent.join(if n == 0 { name.clone() } else { numbered(&name, n) }); @@ -163,7 +170,11 @@ fn copy_new(source: &Path, wanted: &Path) -> Result { out.sync_all() })(); let verified = copied.map_err(|e| e.to_string()).and_then(|()| { - if same_bytes(source, &target) { Ok(()) } else { Err(format!("the copy of {} did not match the device's file", source.display())) } + if same_bytes(source, &target) { + Ok(()) + } else { + Err(format!("the copy of {} did not match the device's file", source.display())) + } }); if let Err(message) = verified { let _ = fs::remove_file(&target); diff --git a/native/crates/es-engine/src/relocate.rs b/native/crates/es-engine/src/relocate.rs index 868c6a6..76a8c4e 100644 --- a/native/crates/es-engine/src/relocate.rs +++ b/native/crates/es-engine/src/relocate.rs @@ -74,7 +74,8 @@ pub fn relocate(lib: &mut Library, share: &Path, moves: &[(String, String)]) -> if tags.first("PPTH").is_none() { continue; } - let new = rb_anlz::write::replace_tags(&old, &[("PPTH", rb_anlz::write::path_tag(&item.stored))]).map_err(|e| Error::Other(e.to_string()))?; + let new = rb_anlz::write::replace_tags(&old, &[("PPTH", rb_anlz::write::path_tag(&item.stored))]) + .map_err(|e| Error::Other(e.to_string()))?; touched.push(path.clone()); writes.push((path, old, new)); } @@ -86,7 +87,9 @@ pub fn relocate(lib: &mut Library, share: &Path, moves: &[(String, String)]) -> let result = (|| -> Result<()> { for (path, _, new) in &writes { let tmp = path.with_extension("tmp"); - std::fs::write(&tmp, new).and_then(|()| std::fs::rename(&tmp, path)).map_err(|e| Error::Other(e.to_string()))?; + std::fs::write(&tmp, new) + .and_then(|()| std::fs::rename(&tmp, path)) + .map_err(|e| Error::Other(e.to_string()))?; } lib.write(|tx| { for item in &plan { @@ -144,7 +147,11 @@ pub fn find_missing(lib: &Library, ids: &[String], directory: &Path) -> Result Result, total: Option, unit: String, file: Option, name: String }, - Done { tracks: i64, playlists: i64 }, + Step { + phase: String, + done: Option, + total: Option, + unit: String, + file: Option, + name: String, + }, + Done { + tracks: i64, + playlists: i64, + }, } /// Through the file being copied (`bytes`) or converted (`milliseconds`). @@ -85,10 +95,9 @@ pub fn exporter() -> Result { let repo = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.."); candidates.push(repo.join("native/target/release").join(name)); candidates.push(repo.join("native/target/debug").join(name)); - candidates - .into_iter() - .find(|p| p.is_file()) - .ok_or_else(|| Error::Other("The USB export program is not built. From the app directory, run npm run build:native.".into())) + candidates.into_iter().find(|p| p.is_file()).ok_or_else(|| { + Error::Other("The USB export program is not built. From the app directory, run npm run build:native.".into()) + }) } fn analysis_files(share: &Path, track: &ExportTrack) -> Vec { @@ -139,7 +148,14 @@ fn track_job(share: &Path, track: &ExportTrack) -> Value { }) } -fn job(share: &Path, volume: &Path, bundle: &Bundle, operation: &str, decisions: Option<&Decisions>, convert: Option<&Preset>) -> Result { +fn job( + share: &Path, + volume: &Path, + bundle: &Bundle, + operation: &str, + decisions: Option<&Decisions>, + convert: Option<&Preset>, +) -> Result { let tracks: Vec = bundle.tracks.iter().map(|t| track_job(share, t)).collect(); let known: std::collections::HashSet = bundle.tracks.iter().map(|t| num(&t.id)).collect(); let mut playlists = Vec::new(); @@ -218,7 +234,9 @@ impl SyncCancel { fn attach(&self, input: ChildStdin) { *self.exporter_input() = Some(input); - if self.is_requested() { self.ask_exporter_to_stop(); } + if self.is_requested() { + self.ask_exporter_to_stop(); + } } fn ask_exporter_to_stop(&self) { @@ -267,7 +285,12 @@ pub fn sync_volume( } /// What syncing would change. `convert` must be what the sync will be given. -pub fn inspect_volume(lib: &Library, volume: &Path, playlist_ids: &[String], convert: Option<&Preset>) -> Result { +pub fn inspect_volume( + lib: &Library, + volume: &Path, + playlist_ids: &[String], + convert: Option<&Preset>, +) -> Result { let publisher = CommandPublisher::discover()?; inspect_volume_with_publisher(lib, volume, playlist_ids, convert, &publisher) } @@ -283,7 +306,11 @@ pub fn recover_volume(volume: &Path) -> Result<()> { fn mounted(volume: &Path) -> Result { let not_mounted = || Error::Other(format!("Volume is not mounted: {}", volume.display())); let volume = volume.canonicalize().map_err(|_| not_mounted())?; - if volume.is_dir() { Ok(volume) } else { Err(not_mounted()) } + if volume.is_dir() { + Ok(volume) + } else { + Err(not_mounted()) + } } pub fn inspect_volume_with_publisher( @@ -297,9 +324,13 @@ pub fn inspect_volume_with_publisher( let bundle = lib.export_bundle(playlist_ids)?; let body = job(&lib.share_dir(), &volume, &bundle, "inspect", None, convert)?; let result = publisher.publish(&body, &|_| {}, &SyncCancel::default())?; - serde_json::from_value(result.get("inspection").cloned() - .ok_or_else(|| Error::Other("USB inspection returned no diagnostics".into()))?) - .map_err(|error| Error::Other(format!("USB inspection response was invalid: {error}"))) + serde_json::from_value( + result + .get("inspection") + .cloned() + .ok_or_else(|| Error::Other("USB inspection returned no diagnostics".into()))?, + ) + .map_err(|error| Error::Other(format!("USB inspection response was invalid: {error}"))) } /// A sync whose export has been read from the library, so publishing it needs the library no more. @@ -362,10 +393,11 @@ fn run(binary: &Path, job: &Path, on_progress: &dyn Fn(Progress), cancel: &SyncC // CREATE_NO_WINDOW: es-usb is a console program and the app has no console to share. #[cfg(windows)] std::os::windows::process::CommandExt::creation_flags(&mut command, 0x0800_0000); - let mut child = command - .spawn() - .map_err(|e| Error::Other(format!("Could not start the USB export program: {e}")))?; - if let Some(input) = child.stdin.take() { cancel.attach(input); } + let mut child = + command.spawn().map_err(|e| Error::Other(format!("Could not start the USB export program: {e}")))?; + if let Some(input) = child.stdin.take() { + cancel.attach(input); + } let stdout = child.stdout.take().ok_or_else(|| Error::Other("no output from the USB export program".into()))?; let mut stderr = child.stderr.take(); let drain = std::thread::spawn(move || { @@ -380,7 +412,12 @@ fn run(binary: &Path, job: &Path, on_progress: &dyn Fn(Progress), cancel: &SyncC let Ok(event) = serde_json::from_str::(line.trim()) else { continue }; match event.get("event").and_then(Value::as_str) { Some("progress") => on_progress(Progress::Step { - phase: event.get("phase").and_then(Value::as_str).filter(|p| !p.is_empty()).unwrap_or("reading").to_owned(), + phase: event + .get("phase") + .and_then(Value::as_str) + .filter(|p| !p.is_empty()) + .unwrap_or("reading") + .to_owned(), done: event.get("done").and_then(Value::as_i64), total: event.get("total").and_then(Value::as_i64), unit: event.get("unit").and_then(Value::as_str).unwrap_or("tracks").to_owned(), @@ -397,9 +434,11 @@ fn run(binary: &Path, job: &Path, on_progress: &dyn Fn(Progress), cancel: &SyncC match (result, error) { (Some(result), None) if status.success() => Ok(result), (_, error) => { - let kind = error.as_ref().and_then(|e| e.get("kind")).and_then(Value::as_str).unwrap_or("export").to_owned(); + let kind = + error.as_ref().and_then(|e| e.get("kind")).and_then(Value::as_str).unwrap_or("export").to_owned(); let review = error.as_ref().and_then(|e| e.get("review")).filter(|value| !value.is_null()).cloned(); - let mut message = error.as_ref().and_then(|e| e.get("message")).and_then(Value::as_str).unwrap_or("").to_owned(); + let mut message = + error.as_ref().and_then(|e| e.get("message")).and_then(Value::as_str).unwrap_or("").to_owned(); if message.is_empty() { message = stderr.trim().to_owned(); } @@ -482,7 +521,8 @@ exit 1 #[test] fn a_conversion_travels_as_a_preset_es_usb_can_check_again() { let directory = tempfile::tempdir().unwrap(); - let preset = crate::convert::clean_preset(&json!({ "format": "wav", "bitDepth": 24, "sampleRate": 44100 })).unwrap(); + let preset = + crate::convert::clean_preset(&json!({ "format": "wav", "bitDepth": 24, "sampleRate": 44100 })).unwrap(); let body = job(directory.path(), directory.path(), &Bundle::default(), "inspect", None, Some(&preset)).unwrap(); assert_eq!(crate::convert::clean_preset(&body["conversion"]).unwrap(), preset); } @@ -499,16 +539,9 @@ exit 1 let volume = directory.path().join("STICK"); std::fs::create_dir_all(&volume).unwrap(); - let result = sync_volume_with_publisher( - &library, - &volume, - &["playlist-1".into()], - None, - None, - &FakePublisher, - &|_| {}, - ) - .unwrap(); + let result = + sync_volume_with_publisher(&library, &volume, &["playlist-1".into()], None, None, &FakePublisher, &|_| {}) + .unwrap(); assert_eq!((result.tracks, result.playlists), (0, 1)); } @@ -543,7 +576,8 @@ exit 1 let library = Library::open_live(&database_path, Guard::Off).unwrap(); let volume = directory.path().join("STICK"); std::fs::create_dir_all(&volume).unwrap(); - let review = inspect_volume_with_publisher(&library, &volume, &["playlist-1".into()], None, &FakePublisher).unwrap(); + let review = + inspect_volume_with_publisher(&library, &volume, &["playlist-1".into()], None, &FakePublisher).unwrap(); assert_eq!(review.token, "fixture"); assert!(review.diagnostics.is_empty()); } diff --git a/native/crates/es-engine/tests/analysis.rs b/native/crates/es-engine/tests/analysis.rs index 161beb1..94f6e29 100644 --- a/native/crates/es-engine/tests/analysis.rs +++ b/native/crates/es-engine/tests/analysis.rs @@ -1,10 +1,10 @@ use std::path::Path; +use es_engine::analysis::{apply_analysis, set_beatgrid, Analysis, Grid, Options}; +use es_engine::import::{import_files, Options as ImportOptions}; use rb_anlz::decode::{self, Tags}; use rb_library::fixture; use rb_library::{CueMove, Guard, Library}; -use es_engine::analysis::{apply_analysis, set_beatgrid, Analysis, Grid, Options}; -use es_engine::import::{import_files, Options as ImportOptions}; fn wav(path: &Path) { let data = 16000u32; @@ -29,7 +29,15 @@ fn scene() -> (tempfile::TempDir, Library, String) { let share = lib.share_dir(); let file = dir.path().join("Song.wav"); wav(&file); - let id = import_files(&mut lib, &share, &[file.to_string_lossy().into_owned()], &ImportOptions { artwork: false, playlist: None }).unwrap().ids[0].clone(); + let id = import_files( + &mut lib, + &share, + &[file.to_string_lossy().into_owned()], + &ImportOptions { artwork: false, playlist: None }, + ) + .unwrap() + .ids[0] + .clone(); (dir, lib, id) } diff --git a/native/crates/es-engine/tests/convert.rs b/native/crates/es-engine/tests/convert.rs index 6db41ed..29cb72e 100644 --- a/native/crates/es-engine/tests/convert.rs +++ b/native/crates/es-engine/tests/convert.rs @@ -2,12 +2,12 @@ use std::path::Path; -use rb_anlz::decode::{self, Tags}; -use rb_library::fixture; -use rb_library::{Guard, Library}; use es_engine::analysis::{apply_analysis, Analysis, Options as AnalysisOptions}; use es_engine::convert::{clean_preset, convert_tracks, delay_offset_ms, ffmpeg_path, Mode}; use es_engine::import::{import_files, Options}; +use rb_anlz::decode::{self, Tags}; +use rb_library::fixture; +use rb_library::{Guard, Library}; use serde_json::json; fn wav(path: &Path) { @@ -33,7 +33,15 @@ fn scene() -> (tempfile::TempDir, Library, String, std::path::PathBuf) { let share = lib.share_dir(); let file = dir.path().join("Song.wav"); wav(&file); - let id = import_files(&mut lib, &share, &[file.to_string_lossy().into_owned()], &Options { artwork: false, playlist: None }).unwrap().ids[0].clone(); + let id = import_files( + &mut lib, + &share, + &[file.to_string_lossy().into_owned()], + &Options { artwork: false, playlist: None }, + ) + .unwrap() + .ids[0] + .clone(); lib.write(|tx| tx.set_hot_cue(&id, 1, 500, None)).unwrap(); (dir, lib, id, file) } @@ -78,7 +86,8 @@ fn a_delay_moves_the_grid_and_the_detail_waveforms() { bpm: 128.0, duration: 1.0, }; - apply_analysis(&mut lib, &share, &id, &analysis, AnalysisOptions { overwrite: true, grid: true, key: false }).unwrap(); + apply_analysis(&mut lib, &share, &id, &analysis, AnalysisOptions { overwrite: true, grid: true, key: false }) + .unwrap(); let relative = lib.track_files(&id).unwrap().unwrap().analysis_path.unwrap(); let read = |suffix: &str| Tags::read(&rb_anlz::file(&share, &relative, suffix).unwrap()).unwrap(); let before = decode::rgb(&read("EXT")).unwrap(); @@ -91,11 +100,17 @@ fn a_delay_moves_the_grid_and_the_detail_waveforms() { let offset = delay_offset_ms(&wav_file, Path::new(&mp3)).unwrap(); assert!(offset > 0, "an MP3 starts later than its WAV"); - assert_eq!(decode::beatgrid(&read("DAT")).unwrap().times, [0, 469, 938].map(|t| t + u32::try_from(offset).unwrap())); + assert_eq!( + decode::beatgrid(&read("DAT")).unwrap().times, + [0, 469, 938].map(|t| t + u32::try_from(offset).unwrap()) + ); let columns = usize::try_from((offset * 150 + 500) / 1000).unwrap(); let after = decode::rgb(&read("EXT")).unwrap(); assert_eq!(after.length, before.length + columns); - assert!(after.heights[..columns].iter().chain(&after.colors[..columns * 3]).all(|v| *v == 0), "the new start is silent"); + assert!( + after.heights[..columns].iter().chain(&after.colors[..columns * 3]).all(|v| *v == 0), + "the new start is silent" + ); assert_eq!(after.heights[columns..], before.heights[..]); assert_eq!(after.colors[columns * 3..], before.colors[..]); let bands = decode::bands(&read("2EX"), "PWV7").unwrap(); diff --git a/native/crates/es-engine/tests/device_import.rs b/native/crates/es-engine/tests/device_import.rs index 3726551..08a880f 100644 --- a/native/crates/es-engine/tests/device_import.rs +++ b/native/crates/es-engine/tests/device_import.rs @@ -3,9 +3,9 @@ use std::path::{Path, PathBuf}; use std::process::Command; +use es_engine::device_import::{import_device, preview, Options, PlaylistPolicy, TrackStatus}; use rb_library::fixture::{self, Rows}; use rb_library::{Guard, Library}; -use es_engine::device_import::{import_device, preview, Options, PlaylistPolicy, TrackStatus}; use serde_json::json; use tempfile::TempDir; @@ -112,7 +112,8 @@ fn tracks_are_copied_imported_with_their_cues_and_put_in_new_playlists() { let tracks = w.lib.tracks(None).unwrap(); let first = tracks.iter().find(|t| t.title == "First").unwrap(); assert_eq!((first.artist.as_str(), first.bpm_x100, first.rating), ("Alpha", 12800, 4)); - let mut cues: Vec<_> = w.lib.cues(&first.id).unwrap().into_iter().map(|c| (c.kind, c.start_ms, c.comment)).collect(); + let mut cues: Vec<_> = + w.lib.cues(&first.id).unwrap().into_iter().map(|c| (c.kind, c.start_ms, c.comment)).collect(); cues.sort(); assert_eq!(cues, [(0, 500, String::new()), (1, 100, "drop".to_owned())]); @@ -129,7 +130,14 @@ fn with_histories(w: &World) -> rb_device::Device { let mut device = rb_device::read::read(&w.volume).unwrap().unwrap(); let id = |title: &str| device.tracks.iter().find(|t| t.title == title).unwrap().export_id; let (first, second) = (id("First"), id("Second")); - let history = |export_id: i64, name: &str, attribute: i64, track_ids: Vec| rb_device::History { export_id, name: name.into(), parent_id: 0, seq: export_id, attribute, track_ids }; + let history = |export_id: i64, name: &str, attribute: i64, track_ids: Vec| rb_device::History { + export_id, + name: name.into(), + parent_id: 0, + seq: export_id, + attribute, + track_ids, + }; device.histories = vec![ history(1, "2024", 1, Vec::new()), history(2, "HISTORY 001", 0, vec![second, first, second]), @@ -151,7 +159,14 @@ fn history_titles(w: &World, name: &str) -> Vec> { .unwrap() .into_iter() .filter(|h| h.name == name) - .map(|h| w.lib.history_track_ids(&h.id).unwrap().iter().map(|id| tracks.iter().find(|t| &t.id == id).unwrap().title.clone()).collect()) + .map(|h| { + w.lib + .history_track_ids(&h.id) + .unwrap() + .iter() + .map(|id| tracks.iter().find(|t| &t.id == id).unwrap().title.clone()) + .collect() + }) .collect() } @@ -203,7 +218,10 @@ fn a_stick_with_only_histories_can_be_imported() { device.playlists.clear(); let out = import_with(&mut w, &device, PlaylistPolicy::CreateNew); assert_eq!((out.histories, out.playlists, out.copied), (2, 0, 2)); - assert!(w.lib.playlists().unwrap().iter().all(|n| !n.name.starts_with("Imported from ")), "no empty wrapper folder"); + assert!( + w.lib.playlists().unwrap().iter().all(|n| !n.name.starts_with("Imported from ")), + "no empty wrapper folder" + ); let mut empty = with_histories(&w); empty.playlists.clear(); @@ -234,7 +252,10 @@ fn a_track_removed_from_a_playlist_is_not_put_back_by_the_default_policy() { run(&mut w, PlaylistPolicy::SkipExisting); let members = w.lib.playlist_track_ids(&set.id).unwrap(); assert_eq!(members.len(), 1, "the playlist keeps only what it had"); - assert!(w.lib.tracks(None).unwrap().iter().any(|t| t.title == "First"), "the track itself is back in the collection"); + assert!( + w.lib.tracks(None).unwrap().iter().any(|t| t.title == "First"), + "the track itself is back in the collection" + ); } #[test] @@ -268,7 +289,11 @@ fn a_track_from_another_library_is_never_mistaken_for_one_here() { conn.execute("UPDATE djmdProperty SET DBID = '9999'", []).unwrap(); let path = w.dir.path().join("elsewhere.wav"); wav(&path, 1); - conn.execute("INSERT INTO djmdContent (ID, Title, FolderPath) VALUES ('101', 'Unrelated', ?1)", [path.to_string_lossy().into_owned()]).unwrap(); + conn.execute( + "INSERT INTO djmdContent (ID, Title, FolderPath) VALUES ('101', 'Unrelated', ?1)", + [path.to_string_lossy().into_owned()], + ) + .unwrap(); Rows(&conn).playlist("1", "x", 0).unwrap(); } let device = rb_device::read::read(&w.volume).unwrap().unwrap(); @@ -283,7 +308,11 @@ fn a_track_this_library_exported_is_reused_not_copied() { wav(&path, 1); { let conn = fixture::connect(w.lib.path()).unwrap(); - conn.execute("INSERT INTO djmdContent (ID, Title, FolderPath) VALUES ('101', 'Mine', ?1)", [path.to_string_lossy().into_owned()]).unwrap(); + conn.execute( + "INSERT INTO djmdContent (ID, Title, FolderPath) VALUES ('101', 'Mine', ?1)", + [path.to_string_lossy().into_owned()], + ) + .unwrap(); } let out = run(&mut w, PlaylistPolicy::SkipExisting); assert_eq!((out.reused, out.copied), (1, 1)); @@ -377,7 +406,10 @@ fn both_usb_libraries_preserve_selected_and_unset_hot_cue_colours() { let track = w.lib.tracks(None).unwrap().into_iter().find(|t| t.title == "First").unwrap(); let cues = es_index::detail::cues_for(&w.lib, &share, &track.id).unwrap(); let selected = cues.iter().find(|c| c.slot == 1).unwrap(); - assert_eq!((selected.color_index, selected.color_code, selected.rgb.as_deref()), (Some(46), Some(46), Some("#ff005c"))); + assert_eq!( + (selected.color_index, selected.color_code, selected.rgb.as_deref()), + (Some(46), Some(46), Some("#ff005c")) + ); let unset = cues.iter().find(|c| c.slot == 2).unwrap(); assert_eq!((unset.color_index, unset.color_code, unset.rgb.as_deref()), (None, Some(0), Some("#00c4ff"))); let slot_d = cues.iter().find(|c| c.slot == 5).unwrap(); @@ -387,7 +419,10 @@ fn both_usb_libraries_preserve_selected_and_unset_hot_cue_colours() { w.lib.write(|tx| tx.set_cue_color(&track.id, &selected.id, None)).unwrap(); let previews = es_index::detail::previews(&w.lib, &share, &[track.id]).unwrap(); let cleared = previews[0].cues.iter().find(|c| c.slot == 1).unwrap(); - assert_eq!((cleared.color_index, cleared.color_code, cleared.rgb.as_deref()), (None, Some(46), Some("#ff005c"))); + assert_eq!( + (cleared.color_index, cleared.color_code, cleared.rgb.as_deref()), + (None, Some(46), Some("#ff005c")) + ); let slot_d = previews[0].cues.iter().find(|c| c.slot == 5).unwrap(); assert_eq!(slot_d.color_code, Some(8)); } diff --git a/native/crates/es-engine/tests/import.rs b/native/crates/es-engine/tests/import.rs index dc099fd..adc3094 100644 --- a/native/crates/es-engine/tests/import.rs +++ b/native/crates/es-engine/tests/import.rs @@ -1,8 +1,8 @@ use std::path::{Path, PathBuf}; +use es_engine::import::{import_files, Options}; use rb_library::fixture::{self, Rows}; use rb_library::{Guard, Library}; -use es_engine::import::{import_files, Options}; use tempfile::TempDir; /// A silent mono 16-bit WAV, long enough to read. diff --git a/native/crates/es-engine/tests/relocate.rs b/native/crates/es-engine/tests/relocate.rs index 94870b1..a71f82b 100644 --- a/native/crates/es-engine/tests/relocate.rs +++ b/native/crates/es-engine/tests/relocate.rs @@ -1,9 +1,9 @@ use std::path::Path; -use rb_library::fixture; -use rb_library::{Guard, Library}; use es_engine::import::{import_files, Options}; use es_engine::relocate::{find_missing, relocate}; +use rb_library::fixture; +use rb_library::{Guard, Library}; fn wav(path: &Path) { let data = 16000u32; @@ -29,7 +29,13 @@ fn a_moved_file_is_found_and_the_track_pointed_at_it() { let share = lib.share_dir(); let old = dir.path().join("Old Song.wav"); wav(&old); - let out = import_files(&mut lib, &share, &[old.to_string_lossy().into_owned()], &Options { artwork: false, playlist: None }).unwrap(); + let out = import_files( + &mut lib, + &share, + &[old.to_string_lossy().into_owned()], + &Options { artwork: false, playlist: None }, + ) + .unwrap(); let id = out.ids[0].clone(); let new_dir = dir.path().join("moved/deeper"); @@ -56,8 +62,17 @@ fn relocating_to_a_missing_file_changes_nothing() { let share = lib.share_dir(); let file = dir.path().join("a.wav"); wav(&file); - let id = import_files(&mut lib, &share, &[file.to_string_lossy().into_owned()], &Options { artwork: false, playlist: None }).unwrap().ids[0].clone(); - let err = relocate(&mut lib, &share, &[(id.clone(), dir.path().join("nope.wav").to_string_lossy().into_owned())]).unwrap_err(); + let id = import_files( + &mut lib, + &share, + &[file.to_string_lossy().into_owned()], + &Options { artwork: false, playlist: None }, + ) + .unwrap() + .ids[0] + .clone(); + let err = relocate(&mut lib, &share, &[(id.clone(), dir.path().join("nope.wav").to_string_lossy().into_owned())]) + .unwrap_err(); assert!(err.to_string().contains("Can't find nope.wav")); assert_eq!(Path::new(&lib.track_files(&id).unwrap().unwrap().folder_path), file); } diff --git a/native/crates/es-engine/tests/sync.rs b/native/crates/es-engine/tests/sync.rs index de4f6e6..cd946b6 100644 --- a/native/crates/es-engine/tests/sync.rs +++ b/native/crates/es-engine/tests/sync.rs @@ -2,10 +2,10 @@ use std::path::Path; -use rb_library::fixture::{self, Rows}; -use rb_library::{Guard, Library}; use es_engine::import::{import_files, Options}; use es_engine::sync::{prepare_sync, sync_volume, Progress}; +use rb_library::fixture::{self, Rows}; +use rb_library::{Guard, Library}; use std::cell::RefCell; fn wav(path: &Path, seconds: u32) { @@ -104,7 +104,9 @@ fn a_sync_cancelled_while_copying_leaves_the_stick_without_a_library() { let job = prepare_sync(&lib, &volume, &["10".to_owned()], None, None).unwrap(); let cancel = job.canceller(); let outcome = job.run(&|progress| { - if matches!(&progress, Progress::Step { phase, .. } if phase == "copy") { cancel.cancel(); } + if matches!(&progress, Progress::Step { phase, .. } if phase == "copy") { + cancel.cancel(); + } }); assert!(matches!(outcome, Err(es_engine::Error::Cancelled)), "{outcome:?}"); @@ -139,7 +141,13 @@ fn a_converted_sync_leaves_the_library_alone_and_the_next_changes_nothing() { std::fs::create_dir_all(&music).unwrap(); let file = music.join("One.wav"); wav(&file, 1); - let out = import_files(&mut lib, &share, &[file.to_string_lossy().into_owned()], &Options { artwork: false, playlist: Some("10".into()) }).unwrap(); + let out = import_files( + &mut lib, + &share, + &[file.to_string_lossy().into_owned()], + &Options { artwork: false, playlist: Some("10".into()) }, + ) + .unwrap(); let volume = dir.path().join("STICK"); std::fs::create_dir_all(&volume).unwrap(); let mp3 = es_engine::convert::clean_preset(&serde_json::json!({ "format": "mp3", "bitrate": 128 })).unwrap(); diff --git a/native/crates/es-index/examples/dump.rs b/native/crates/es-index/examples/dump.rs index 4bea68b..acc64d4 100644 --- a/native/crates/es-index/examples/dump.rs +++ b/native/crates/es-index/examples/dump.rs @@ -15,7 +15,8 @@ fn main() { "tags" => serde_json::to_string(&es_index::tag_nodes(&lib).unwrap()), "detail" => { let ids = std::env::args().nth(2).expect("comma separated ids"); - let all: Vec<_> = ids.split(',').map(|id| es_index::detail::track_detail(&lib, &share, id).unwrap()).collect(); + let all: Vec<_> = + ids.split(',').map(|id| es_index::detail::track_detail(&lib, &share, id).unwrap()).collect(); serde_json::to_string(&all) } other => panic!("unknown view {other}"), diff --git a/native/crates/es-index/src/detail.rs b/native/crates/es-index/src/detail.rs index 0f79e0c..c89b0b1 100644 --- a/native/crates/es-index/src/detail.rs +++ b/native/crates/es-index/src/detail.rs @@ -137,7 +137,9 @@ pub fn track_detail(lib: &Library, share: &Path, id: &str) -> Result { let ex2 = tags(share, relative, "2EX"); let rgb = ext.as_ref().and_then(decode::rgb); - let bands = |kind: &str| ex2.as_ref().and_then(|t| decode::bands(t, kind)).map(|b| Bands { length: b.length, bands: b64(&b.bands) }); + let bands = |kind: &str| { + ex2.as_ref().and_then(|t| decode::bands(t, kind)).map(|b| Bands { length: b.length, bands: b64(&b.bands) }) + }; let waveform = Waveform { rate: DETAIL_RATE, three_band: bands("PWV7"), @@ -145,7 +147,11 @@ pub fn track_detail(lib: &Library, share: &Path, id: &str) -> Result { mono: if rgb.is_some() { None } else { - ext.as_ref().and_then(decode::mono).map(|m| Mono { length: m.length, heights: b64(&m.heights), whiteness: b64(&m.whiteness) }) + ext.as_ref().and_then(decode::mono).map(|m| Mono { + length: m.length, + heights: b64(&m.heights), + whiteness: b64(&m.whiteness), + }) }, rgb: rgb.map(|r| Colour { length: r.length, heights: b64(&r.heights), colors: b64(&r.colors) }), }; @@ -153,7 +159,11 @@ pub fn track_detail(lib: &Library, share: &Path, id: &str) -> Result { id: id.to_owned(), file_exists: Path::new(&files.folder_path).is_file(), cues: cues(lib, id, ext.as_ref())?, - beatgrid: dat.as_ref().and_then(decode::beatgrid).map(|g| Grid { times: g.times, beats: g.beats, bpms: g.bpms }), + beatgrid: dat.as_ref().and_then(decode::beatgrid).map(|g| Grid { + times: g.times, + beats: g.beats, + bpms: g.bpms, + }), waveform, }) } @@ -215,7 +225,14 @@ impl Preview { heights: o.colour_length.map(|_| b64(&o.heights)), colors: o.colour_length.map(|_| b64(&o.colors)), }); - Self { id: id.to_owned(), memory, hot, phrase: ext.is_some_and(|e| e.first(rb_anlz::PHRASE_TAG).is_some()), cues, waveform } + Self { + id: id.to_owned(), + memory, + hot, + phrase: ext.is_some_and(|e| e.first(rb_anlz::PHRASE_TAG).is_some()), + cues, + waveform, + } } } diff --git a/native/crates/es-index/src/device.rs b/native/crates/es-index/src/device.rs index f183c86..e4b011d 100644 --- a/native/crates/es-index/src/device.rs +++ b/native/crates/es-index/src/device.rs @@ -75,7 +75,11 @@ pub fn track_row(volume: &Path, track: &Track) -> TrackRow { let stored = stored_file_type(track.file_type); TrackRow { id: track_key(&volume.to_string_lossy(), track.export_id), - title: if track.title.is_empty() { Some(stem(name_source)).filter(|s| !s.is_empty()).unwrap_or_else(|| "Untitled".into()) } else { track.title.clone() }, + title: if track.title.is_empty() { + Some(stem(name_source)).filter(|s| !s.is_empty()).unwrap_or_else(|| "Untitled".into()) + } else { + track.title.clone() + }, artist: track.artist.clone(), album: track.album.clone(), genre: track.genre.clone(), @@ -97,7 +101,10 @@ pub fn track_row(volume: &Path, track: &Track) -> TrackRow { bit_rate: track.bitrate, sample_rate: track.sample_rate, bit_depth: track.bit_depth, - file_type: stored.map_or_else(|| Path::new(name_source).extension().map(|e| e.to_string_lossy().to_uppercase()).unwrap_or_default(), str::to_owned), + file_type: stored.map_or_else( + || Path::new(name_source).extension().map(|e| e.to_string_lossy().to_uppercase()).unwrap_or_default(), + str::to_owned, + ), stored_type: stored, missing: audio.as_ref().is_none_or(|p| !p.is_file()), streaming: false, @@ -163,7 +170,9 @@ pub struct LibraryView { #[must_use] pub fn library_view(kind: LibraryKind, device: &Device) -> LibraryView { match kind { - LibraryKind::DeviceLibrary => LibraryView { id: "device", name: "Device Library", playlists: playlists(device) }, + LibraryKind::DeviceLibrary => { + LibraryView { id: "device", name: "Device Library", playlists: playlists(device) } + } LibraryKind::OneLibrary => LibraryView { id: "one", name: "OneLibrary", playlists: playlists(device) }, } } @@ -232,18 +241,32 @@ pub fn detail(volume: &Path, key: &str, track: &Track) -> Detail { let read = |suffix: &str| base.as_ref().and_then(|b| Tags::read(&b.with_extension(suffix)).ok()); let (dat, ext, ex2) = (read("DAT"), read("EXT"), read("2EX")); let rgb = ext.as_ref().and_then(decode::rgb); - let bands = |kind: &str| ex2.as_ref().and_then(|t| decode::bands(t, kind)).map(|b| Bands { length: b.length, bands: b64(&b.bands) }); + let bands = |kind: &str| { + ex2.as_ref().and_then(|t| decode::bands(t, kind)).map(|b| Bands { length: b.length, bands: b64(&b.bands) }) + }; let audio = audio_path(volume, track); Detail { id: key.to_owned(), file_exists: audio.as_ref().is_some_and(|p| p.is_file()), cues: device_cues(track, ext.as_ref()), - beatgrid: dat.as_ref().and_then(decode::beatgrid).map(|g| Grid { times: g.times, beats: g.beats, bpms: g.bpms }), + beatgrid: dat.as_ref().and_then(decode::beatgrid).map(|g| Grid { + times: g.times, + beats: g.beats, + bpms: g.bpms, + }), waveform: Waveform { rate: 150, three_band: bands("PWV7"), three_band_preview: bands("PWV6"), - mono: if rgb.is_some() { None } else { ext.as_ref().and_then(decode::mono).map(|m| Mono { length: m.length, heights: b64(&m.heights), whiteness: b64(&m.whiteness) }) }, + mono: if rgb.is_some() { + None + } else { + ext.as_ref().and_then(decode::mono).map(|m| Mono { + length: m.length, + heights: b64(&m.heights), + whiteness: b64(&m.whiteness), + }) + }, rgb: rgb.map(|r| Colour { length: r.length, heights: b64(&r.heights), colors: b64(&r.colors) }), }, } @@ -306,7 +329,11 @@ mod tests { let medium = original.with_file_name("cover_m.jpg"); std::fs::write(&medium, b"medium").unwrap(); assert_eq!(artwork_file(dir.path(), &track, "m"), Some(medium.clone())); - assert_eq!(artwork_file(dir.path(), &track, ""), Some(medium.clone()), "full size is the largest the stick holds"); + assert_eq!( + artwork_file(dir.path(), &track, ""), + Some(medium.clone()), + "full size is the largest the stick holds" + ); let windows_path = Track { artwork: relative.replace('/', "\\"), ..Track::default() }; assert_eq!(artwork_file(dir.path(), &windows_path, ""), Some(medium.clone())); std::fs::remove_file(original).unwrap(); @@ -327,14 +354,24 @@ mod tests { fn stick() -> Device { let track = |id: i64, title: &str| Track { export_id: id, title: title.into(), ..Track::default() }; - let history = |id: i64, name: &str, parent_id: i64, attribute: i64, track_ids: Vec| History { export_id: id, name: name.into(), parent_id, seq: id, attribute, track_ids }; + let history = |id: i64, name: &str, parent_id: i64, attribute: i64, track_ids: Vec| History { + export_id: id, + name: name.into(), + parent_id, + seq: id, + attribute, + track_ids, + }; Device { kind: LibraryKind::OneLibrary, root_name: String::new(), device_name: "STICK".into(), tracks: vec![track(1, "One"), track(2, "Two")], playlists: Vec::new(), - histories: vec![history(10, "2024", 0, 1, Vec::new()), history(11, "HISTORY 001", 10, 0, vec![2, 1, 2, 99])], + histories: vec![ + history(10, "2024", 0, 1, Vec::new()), + history(11, "HISTORY 001", 10, 0, vec![2, 1, 2, 99]), + ], } } diff --git a/native/crates/es-index/src/lib.rs b/native/crates/es-index/src/lib.rs index 6b925d4..ccd55aa 100644 --- a/native/crates/es-index/src/lib.rs +++ b/native/crates/es-index/src/lib.rs @@ -175,7 +175,11 @@ pub fn track_rows(lib: &Library, share: &Path, ids: Option<&[String]>) -> Result } fn root_if_empty(parent: String) -> String { - if parent.is_empty() { "root".into() } else { parent } + if parent.is_empty() { + "root".into() + } else { + parent + } } pub fn playlist_nodes(lib: &Library) -> Result> { diff --git a/native/crates/es-index/tests/rows.rs b/native/crates/es-index/tests/rows.rs index 321654c..0a51c6c 100644 --- a/native/crates/es-index/tests/rows.rs +++ b/native/crates/es-index/tests/rows.rs @@ -1,6 +1,6 @@ +use es_index::{history_nodes, playlist_nodes, track_rows}; use rb_library::fixture::{self, Rows}; use rb_library::{Guard, Library}; -use es_index::{history_nodes, playlist_nodes, track_rows}; #[test] fn rows_resolve_names_and_ignore_removed_tracks() { @@ -20,8 +20,11 @@ fn rows_resolve_names_and_ignore_removed_tracks() { rows.playlist("10", "Mix", 0).unwrap(); rows.song("10", "1", 1).unwrap(); rows.song("10", "2", 2).unwrap(); - conn.execute("INSERT INTO djmdHistory (ID, Name, Attribute, ParentID, Seq) VALUES ('h1', 'Set', 0, 'root', 1)", []) - .unwrap(); + conn.execute( + "INSERT INTO djmdHistory (ID, Name, Attribute, ParentID, Seq) VALUES ('h1', 'Set', 0, 'root', 1)", + [], + ) + .unwrap(); conn.execute("INSERT INTO djmdSongHistory (ID, HistoryID, ContentID, TrackNo) VALUES ('s1', 'h1', '2', 1)", []) .unwrap(); conn.execute("INSERT INTO djmdSongHistory (ID, HistoryID, ContentID, TrackNo) VALUES ('s2', 'h1', '1', 2)", []) diff --git a/native/crates/es-node/src/lib.rs b/native/crates/es-node/src/lib.rs index fd30f27..47accc6 100644 --- a/native/crates/es-node/src/lib.rs +++ b/native/crates/es-node/src/lib.rs @@ -12,9 +12,7 @@ mod usb_settings; use es_deck::{DeckEvent, DeckSnapshot, Engine, EventSink}; use napi::bindgen_prelude::*; -use napi::threadsafe_function::{ - ErrorStrategy, ThreadSafeCallContext, ThreadsafeFunction, ThreadsafeFunctionCallMode, -}; +use napi::threadsafe_function::{ErrorStrategy, ThreadSafeCallContext, ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi::{Env, JsFunction, Task}; use napi_derive::napi; @@ -68,12 +66,7 @@ impl From for DeckSnapshotJs { fn event_js(event: DeckEvent) -> DeckEventJs { match event { - DeckEvent::Loaded { - deck, - load_id, - total_frames, - sample_rate, - } => DeckEventJs { + DeckEvent::Loaded { deck, load_id, total_frames, sample_rate } => DeckEventJs { kind: "loaded".into(), deck: deck as u32, load_id: load_id as f64, @@ -81,11 +74,7 @@ fn event_js(event: DeckEvent) -> DeckEventJs { sample_rate, message: None, }, - DeckEvent::Error { - deck, - load_id, - message, - } => DeckEventJs { + DeckEvent::Error { deck, load_id, message } => DeckEventJs { kind: "error".into(), deck: deck as u32, load_id: load_id as f64, @@ -114,10 +103,8 @@ impl AudioEngine { decks: u32, #[napi(ts_arg_type = "(event: DeckEventJs) => void")] on_event: JsFunction, ) -> Result { - let mut tsfn: ThreadsafeFunction = on_event - .create_threadsafe_function(0, |ctx: ThreadSafeCallContext| { - Ok(vec![ctx.value]) - })?; + let mut tsfn: ThreadsafeFunction = + on_event.create_threadsafe_function(0, |ctx: ThreadSafeCallContext| Ok(vec![ctx.value]))?; // Events must not keep the process alive on their own. tsfn.unref(&env)?; let events: EventSink = Arc::new(move |event| { @@ -125,9 +112,7 @@ impl AudioEngine { }); let engine = Engine::new(decks.max(1) as usize, &events) .map_err(|e| Error::new(Status::GenericFailure, e.to_string()))?; - Ok(Self { - engine: Some(engine), - }) + Ok(Self { engine: Some(engine) }) } /// Stops playback and drops the device and decode threads. Further commands do nothing. @@ -331,9 +316,7 @@ impl AudioEngine { #[napi] pub fn snapshot(&self, deck: u32) -> Option { - self.engine() - .and_then(|e| e.snapshot(deck_index(deck))) - .map(Into::into) + self.engine().and_then(|e| e.snapshot(deck_index(deck))).map(Into::into) } #[napi] @@ -390,11 +373,7 @@ impl Task for Analyse { /// Decodes and analyses a file off the main thread. Null when it is too short to draw. #[napi(ts_return_type = "Promise")] pub fn analyse(path: String, bands: bool, quality: u32) -> AsyncTask { - AsyncTask::new(Analyse { - path, - bands, - quality, - }) + AsyncTask::new(Analyse { path, bands, quality }) } #[napi(object)] @@ -450,10 +429,7 @@ impl Task for AnalyseTrack { beat_numbers: Uint8Array::new(a.beats.iter().map(|b| b.number).collect()), beat_tempos: Uint16Array::new(a.beats.iter().map(|b| b.tempo_x100).collect()), beat_times: Uint32Array::new(a.beats.iter().map(|b| b.time_ms).collect()), - key: a.key.map(|k| KeyJs { - tonic: k.tonic as u32, - minor: k.minor, - }), + key: a.key.map(|k| KeyJs { tonic: k.tonic as u32, minor: k.minor }), waveform: Uint8Array::new(a.waveform), }) } diff --git a/native/crates/es-node/src/library.rs b/native/crates/es-node/src/library.rs index eed7553..9d832b0 100644 --- a/native/crates/es-node/src/library.rs +++ b/native/crates/es-node/src/library.rs @@ -7,12 +7,12 @@ use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Instant; use crate::usb::UsbOp; -use rb_library::{Library, TrackEdit}; use es_engine::library::{LibraryService, ServiceEvent}; use napi::bindgen_prelude::AsyncTask; use napi::threadsafe_function::{ErrorStrategy, ThreadSafeCallContext, ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi::{Env, JsFunction, Task}; use napi_derive::napi; +use rb_library::{Library, TrackEdit}; use serde::Serialize; use serde_json::{json, Value}; @@ -58,10 +58,9 @@ impl Core { } self.emit("convert.progress", &data); } - ServiceEvent::UsbImportProgress { done, total, name } => self.emit( - "usb.progress", - &json!({ "phase": "import", "done": done, "total": total, "name": name }), - ), + ServiceEvent::UsbImportProgress { done, total, name } => { + self.emit("usb.progress", &json!({ "phase": "import", "done": done, "total": total, "name": name })) + } ServiceEvent::UsbSyncProgress(progress) => { let data = match progress { es_engine::sync::Progress::Step { phase, done, total, unit, file, name } => { @@ -106,8 +105,19 @@ fn whole(value: &serde_json::Value, label: &str, limit: i64) -> napi::Result napi::Result { let map: serde_json::Map = serde_json::from_str(fields).map_err(failure)?; let known = [ - "title", "comment", "year", "trackNo", "rating", "color", "artist", "remixer", "originalArtist", "composer", - "album", "genre", "label", + "title", + "comment", + "year", + "trackNo", + "rating", + "color", + "artist", + "remixer", + "originalArtist", + "composer", + "album", + "genre", + "label", ]; let mut unknown: Vec<&str> = map.keys().map(String::as_str).filter(|k| !known.contains(k)).collect(); if !unknown.is_empty() { @@ -247,7 +257,11 @@ impl Run { let Some(job) = job else { return Ok(json!(false)) }; let emit = |event| self.core.emit_service_event(event); let made = job.run(&emit).map_err(failure)?; - if daily { Ok(json!(true)) } else { json_of(&made) } + if daily { + Ok(json!(true)) + } else { + json_of(&made) + } } fn perform(&self, service: &mut LibraryService) -> napi::Result { @@ -298,19 +312,21 @@ impl Run { Op::HistoryTracks(id) => return json_of(&service.history_tracks(id).map_err(failure)?), Op::TrackDetail(id) => return json_of(&service.track_detail(id).map_err(failure)?), Op::TrackPreviews(ids) => { - let (device, own): (Vec, Vec) = ids.iter().cloned().partition(|id| id.starts_with("usb:")); - let mut by_id: std::collections::HashMap = service - .previews(&own) - .map_err(failure)? - .into_iter() - .map(|row| (row.id.clone(), row)) - .collect(); + let (device, own): (Vec, Vec) = + ids.iter().cloned().partition(|id| id.starts_with("usb:")); + let mut by_id: std::collections::HashMap = + service.previews(&own).map_err(failure)?.into_iter().map(|row| (row.id.clone(), row)).collect(); let devices = &self.core.devices; for row in es_index::device::previews(&mut |volume| devices.load(volume).ok().flatten(), &device) { by_id.insert(row.id.clone(), row); } let mut seen = std::collections::HashSet::new(); - let ordered: Vec<_> = ids.iter().filter(|id| seen.insert(id.as_str())).take(80).filter_map(|id| by_id.remove(id)).collect(); + let ordered: Vec<_> = ids + .iter() + .filter(|id| seen.insert(id.as_str())) + .take(80) + .filter_map(|id| by_id.remove(id)) + .collect(); return json_of(&ordered); } Op::TrackFindMissing(ids, directory) => { @@ -330,9 +346,9 @@ impl Run { .filter(|id| !id.is_empty()) .ok_or_else(|| failure("tracks must be a list of track ids"))?; let has_cache = item.get("size").is_some() && item.get("mtime").is_some(); - let cached_size = item - .get("size") - .and_then(|size| size.as_i64().or_else(|| size.as_str().and_then(|value| value.trim().parse().ok()))); + let cached_size = item.get("size").and_then(|size| { + size.as_i64().or_else(|| size.as_str().and_then(|value| value.trim().parse().ok())) + }); let cached_mtime = item.get("mtime").and_then(|mtime| match mtime { Value::Null => None, Value::String(value) => Some(value.clone()), @@ -371,10 +387,8 @@ impl Run { } Op::TrackRelocate(body) => { let parsed: serde_json::Map = serde_json::from_str(body).map_err(failure)?; - let moves: Vec<(String, String)> = parsed - .into_iter() - .map(|(id, path)| (id, path.as_str().unwrap_or_default().to_owned())) - .collect(); + let moves: Vec<(String, String)> = + parsed.into_iter().map(|(id, path)| (id, path.as_str().unwrap_or_default().to_owned())).collect(); return json_of(&service.track_relocate(&moves).map_err(failure)?); } Op::BeatgridSet(id, body) => { @@ -399,9 +413,14 @@ impl Run { .iter() .filter_map(|item| { Some(rb_library::CueMove { - id: item.get("id").map(|value| value.as_str().map_or_else(|| value.to_string(), str::to_owned))?, + id: item + .get("id") + .map(|value| value.as_str().map_or_else(|| value.to_string(), str::to_owned))?, start_ms: item.get("start")?.as_f64()?.round_ties_even() as i64, - end_ms: item.get("end").and_then(Value::as_f64).map(|end| end.round_ties_even() as i64), + end_ms: item + .get("end") + .and_then(Value::as_f64) + .map(|end| end.round_ties_even() as i64), }) }) .collect() @@ -431,7 +450,10 @@ impl Run { .decode(result.get("waveform").and_then(Value::as_str).unwrap_or("")) .map_err(failure)?; let key = result.get("key").filter(|value| !value.is_null()).map(|value| { - (value.get("tonic").and_then(Value::as_i64).unwrap_or(0), value.get("minor").and_then(Value::as_bool).unwrap_or(false)) + ( + value.get("tonic").and_then(Value::as_i64).unwrap_or(0), + value.get("minor").and_then(Value::as_bool).unwrap_or(false), + ) }); let analysis = es_engine::analysis::Analysis { beats, @@ -440,7 +462,9 @@ impl Run { bpm: result.get("bpm").and_then(Value::as_f64).unwrap_or(0.0), duration: result.get("duration").and_then(Value::as_f64).unwrap_or(0.0), }; - let flag = |name: &str, default: bool| options.get(name).map_or(default, |value| value.as_bool().unwrap_or(false)); + let flag = |name: &str, default: bool| { + options.get(name).map_or(default, |value| value.as_bool().unwrap_or(false)) + }; let chosen = es_engine::analysis::Options { overwrite: flag("overwrite", false), grid: flag("grid", true), @@ -450,7 +474,8 @@ impl Run { } Op::Convert { ids, preset, mode } => { let mode = es_engine::convert::Mode::parse(mode).map_err(failure)?; - let preset = es_engine::convert::clean_preset(&serde_json::from_str(preset).map_err(failure)?).map_err(failure)?; + let preset = es_engine::convert::clean_preset(&serde_json::from_str(preset).map_err(failure)?) + .map_err(failure)?; let emit = |event| self.core.emit_service_event(event); return json_of(&service.track_convert(ids, &preset, mode, &emit).map_err(failure)?); } @@ -480,7 +505,8 @@ impl Run { return json_of(&service.playlist_tree_move(id, parent, *index as usize).map_err(failure)?); } Op::PlaylistCreate { name, parent, folder, ids } => { - let (id, playlists) = service.playlist_create(name, parent.as_deref(), *folder, ids).map_err(failure)?; + let (id, playlists) = + service.playlist_create(name, parent.as_deref(), *folder, ids).map_err(failure)?; return json_of(&json!({ "id": id, "playlists": playlists })); } Op::PlaylistRename(id, name) => return json_of(&service.playlist_rename(id, name).map_err(failure)?), @@ -678,10 +704,11 @@ impl RekordboxLibrary { env: Env, #[napi(ts_arg_type = "(event: string, data: string) => void")] callback: JsFunction, ) -> napi::Result<()> { - let mut handler: Events = callback.create_threadsafe_function(0, |ctx: ThreadSafeCallContext<(String, String)>| { - let (event, data) = ctx.value; - Ok(vec![ctx.env.create_string(&event)?, ctx.env.create_string(&data)?]) - })?; + let mut handler: Events = + callback.create_threadsafe_function(0, |ctx: ThreadSafeCallContext<(String, String)>| { + let (event, data) = ctx.value; + Ok(vec![ctx.env.create_string(&event)?, ctx.env.create_string(&data)?]) + })?; // Events must not keep the process alive on their own. handler.unref(&env)?; *self.core.events.lock().map_err(|_| failure("the event lock was poisoned"))? = Some(handler); @@ -876,7 +903,13 @@ impl RekordboxLibrary { } #[napi(ts_return_type = "Promise")] - pub fn usb_sync(&self, volume: String, playlist_ids: Vec, decisions: Option, convert: Option) -> AsyncTask { + pub fn usb_sync( + &self, + volume: String, + playlist_ids: Vec, + decisions: Option, + convert: Option, + ) -> AsyncTask { self.run(Op::Usb(UsbOp::Sync { volume, playlists: playlist_ids, decisions, convert })) } diff --git a/native/crates/es-node/src/usb.rs b/native/crates/es-node/src/usb.rs index 3cb1353..3e30e73 100644 --- a/native/crates/es-node/src/usb.rs +++ b/native/crates/es-node/src/usb.rs @@ -5,9 +5,9 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, MutexGuard, TryLockError}; use std::time::SystemTime; -use rb_device::{paths::pioneer_dir, volumes, Device, LibraryKind, Volume}; use es_engine::device_import::{self, PlaylistPolicy, TrackStatus}; use es_engine::sync::SyncCancel; +use rb_device::{paths::pioneer_dir, volumes, Device, LibraryKind, Volume}; use serde_json::{json, Value}; use crate::library::{failure, json_of, Core}; @@ -27,10 +27,27 @@ pub(crate) enum UsbOp { HistoryTracks(String, String), Detail(String), Media(String), - ImportPreview { volume: String, folder: Option, policy: Option }, - Import { volume: String, folder: Option, policy: Option }, - SyncReview { volume: String, playlists: Vec, convert: Option }, - Sync { volume: String, playlists: Vec, decisions: Option, convert: Option }, + ImportPreview { + volume: String, + folder: Option, + policy: Option, + }, + Import { + volume: String, + folder: Option, + policy: Option, + }, + SyncReview { + volume: String, + playlists: Vec, + convert: Option, + }, + Sync { + volume: String, + playlists: Vec, + decisions: Option, + convert: Option, + }, RecoveryStatus(String), Recover(String), } @@ -150,7 +167,12 @@ impl UsbOp { fn changes_stick(&self) -> bool { matches!( self, - Self::Eject(_) | Self::Format(_) | Self::SetSettings(..) | Self::Import { .. } | Self::Recover(_) | Self::Sync { .. } + Self::Eject(_) + | Self::Format(_) + | Self::SetSettings(..) + | Self::Import { .. } + | Self::Recover(_) + | Self::Sync { .. } ) } } @@ -189,7 +211,9 @@ impl RunningSync { } pub(crate) fn cancel(&self) { - if let Some(sync) = self.current().as_ref() { sync.cancel(); } + if let Some(sync) = self.current().as_ref() { + sync.cancel(); + } } fn current(&self) -> MutexGuard<'_, Option> { @@ -203,7 +227,8 @@ pub(crate) fn sync_off_lock(core: &Core, service: MutexGuard<'_, LibraryService> let UsbOp::Sync { volume, playlists, decisions, convert } = op else { unreachable!("not a sync") }; let _changing = core.stick_gate.enter()?; let volume = listed(volume)?; - let decisions = decisions.as_ref().map(|value| serde_json::from_value(value.clone())).transpose().map_err(failure)?; + let decisions = + decisions.as_ref().map(|value| serde_json::from_value(value.clone())).transpose().map_err(failure)?; let convert = preset(convert.as_ref())?; let job = service.usb_sync_job(&volume, playlists, decisions.as_ref(), convert.as_ref()).map_err(failure)?; drop(service); @@ -272,13 +297,17 @@ pub(crate) fn perform(core: &Core, service: &mut LibraryService, op: &UsbOp) -> } UsbOp::Selection(volume) => { let (ids, db_id) = service.playlist_selection().map_err(failure)?; - json_of(&json!({ "playlistIds": rb_device::selection::recorded_playlist_ids(&mounted(volume)?, &ids, db_id) })) + json_of( + &json!({ "playlistIds": rb_device::selection::recorded_playlist_ids(&mounted(volume)?, &ids, db_id) }), + ) } UsbOp::Tracks(volume, playlist) => { let volume = mounted(volume)?; match core.devices.load(&volume)? { None => Ok(json!([])), - Some(device) => json_of(&es_index::device::tracks(&volume, &device, playlist.as_deref()).map_err(failure)?), + Some(device) => { + json_of(&es_index::device::tracks(&volume, &device, playlist.as_deref()).map_err(failure)?) + } } } UsbOp::HistoryTracks(volume, history) => { @@ -289,7 +318,8 @@ pub(crate) fn perform(core: &Core, service: &mut LibraryService, op: &UsbOp) -> } } UsbOp::Detail(key) => { - let (volume, export_id) = es_index::device::parse_track_key(key).ok_or_else(|| failure("Not a device track"))?; + let (volume, export_id) = + es_index::device::parse_track_key(key).ok_or_else(|| failure("Not a device track"))?; let volume = mounted(&volume)?; let device = require(core.devices.load(&volume)?)?; let track = device.track(export_id).ok_or_else(|| failure(format!("Unknown device track {key}")))?; @@ -307,7 +337,8 @@ pub(crate) fn perform(core: &Core, service: &mut LibraryService, op: &UsbOp) -> let state = service.session().ok_or_else(|| failure("Library not open"))?; let volume = listed(volume)?; let device = require(core.devices.load(&volume)?)?; - let plan = device_import::preview(state.database(), &volume, &device, &import_options(folder, policy)?).map_err(failure)?; + let plan = device_import::preview(state.database(), &volume, &device, &import_options(folder, policy)?) + .map_err(failure)?; let status = |s: TrackStatus| match s { TrackStatus::Reuse => "reuse", TrackStatus::Copy => "copy", diff --git a/native/crates/es-node/src/usb_settings.rs b/native/crates/es-node/src/usb_settings.rs index e1cc346..b9a9e36 100644 --- a/native/crates/es-node/src/usb_settings.rs +++ b/native/crates/es-node/src/usb_settings.rs @@ -47,17 +47,11 @@ fn invalid() -> napi::Error { } fn text(value: &Value) -> napi::Result<&str> { - value - .as_str() - .filter(|text| !text.contains('\0') && text.len() <= 255) - .ok_or_else(invalid) + value.as_str().filter(|text| !text.contains('\0') && text.len() <= 255).ok_or_else(invalid) } fn color(value: &Value) -> napi::Result { - value - .as_i64() - .filter(|color| (0..=8).contains(color)) - .ok_or_else(invalid) + value.as_i64().filter(|color| (0..=8).contains(color)).ok_or_else(invalid) } fn edit_slots(current: &mut [settings::MenuSlot], value: &Value) -> napi::Result<()> { @@ -71,24 +65,16 @@ fn edit_slots(current: &mut [settings::MenuSlot], value: &Value) -> napi::Result if !ids.insert(id) { return Err(invalid()); } - let slot = current - .iter_mut() - .find(|slot| slot.id == id) - .ok_or_else(invalid)?; + let slot = current.iter_mut().find(|slot| slot.id == id).ok_or_else(invalid)?; slot.visible = row["visible"].as_bool().ok_or_else(invalid)?; - slot.seq = row["sequence"] - .as_i64() - .filter(|seq| *seq >= 0 && *seq <= 1000) - .ok_or_else(invalid)?; + slot.seq = row["sequence"].as_i64().filter(|seq| *seq >= 0 && *seq <= 1000).ok_or_else(invalid)?; } Ok(()) } pub(crate) fn edited(current: &DeviceSettings, value: &Value) -> napi::Result { if value["snapshot"] != view(current)["snapshot"] { - return Err(failure( - "Device settings changed; reload them before saving", - )); + return Err(failure("Device settings changed; reload them before saving")); } let mut next = current.clone(); let display = &value["display"]; diff --git a/native/crates/es-tags/src/lib.rs b/native/crates/es-tags/src/lib.rs index 7eefe27..b662799 100644 --- a/native/crates/es-tags/src/lib.rs +++ b/native/crates/es-tags/src/lib.rs @@ -60,7 +60,9 @@ fn open(path: &Path) -> Result { } let probe = Probe::open(path)?.options(ParseOptions::new().read_cover_art(true)); if probe.file_type().is_none() { - return Err(Error::Unsupported(path.extension().map_or_else(String::new, |e| format!(".{}", e.to_string_lossy())))); + return Err(Error::Unsupported( + path.extension().map_or_else(String::new, |e| format!(".{}", e.to_string_lossy())), + )); } Ok(probe.read()?) } @@ -85,7 +87,8 @@ fn original_artist(tag: &Tag) -> String { tag.items() .find_map(|item| match item.key() { ItemKey::Unknown(name) - if name.eq_ignore_ascii_case(VORBIS_ORIGINAL_ARTIST) || name.eq_ignore_ascii_case(MP4_ORIGINAL_ARTIST) => + if name.eq_ignore_ascii_case(VORBIS_ORIGINAL_ARTIST) + || name.eq_ignore_ascii_case(MP4_ORIGINAL_ARTIST) => { item.value().text().map(|s| s.trim().to_owned()) } @@ -174,7 +177,9 @@ pub fn write(path: &Path, edit: &Edit) -> Result<()> { } let probe = Probe::open(path)?; if probe.file_type().is_none() { - return Err(Error::Unsupported(path.extension().map_or_else(String::new, |e| format!(".{}", e.to_string_lossy())))); + return Err(Error::Unsupported( + path.extension().map_or_else(String::new, |e| format!(".{}", e.to_string_lossy())), + )); } let mut file = probe.read()?; let kind = if file.tag(TagType::Id3v2).is_some() { TagType::Id3v2 } else { file.primary_tag_type() }; @@ -192,12 +197,38 @@ pub fn write(path: &Path, edit: &Edit) -> Result<()> { (&edit.genre, ItemKey::Genre, vec![]), (&edit.composer, ItemKey::Composer, vec![]), (&edit.comment, ItemKey::Comment, vec![]), - (&edit.label, ItemKey::Label, if mp4 { vec![freeform("LABEL")] } else if vorbis { vec!["LABEL".into()] } else { vec![] }), - (&edit.remixer, ItemKey::Remixer, if mp4 { vec![freeform("REMIXER")] } else if vorbis { vec!["REMIXER".into()] } else { vec![] }), + ( + &edit.label, + ItemKey::Label, + if mp4 { + vec![freeform("LABEL")] + } else if vorbis { + vec!["LABEL".into()] + } else { + vec![] + }, + ), + ( + &edit.remixer, + ItemKey::Remixer, + if mp4 { + vec![freeform("REMIXER")] + } else if vorbis { + vec!["REMIXER".into()] + } else { + vec![] + }, + ), ( &edit.original_artist, ItemKey::OriginalArtist, - if mp4 { vec![freeform("ORIGINAL ARTIST")] } else if vorbis { vec!["ORIGINALARTIST".into()] } else { vec![] }, + if mp4 { + vec![freeform("ORIGINAL ARTIST")] + } else if vorbis { + vec!["ORIGINALARTIST".into()] + } else { + vec![] + }, ), ]; for (value, key, unknown) in fields { diff --git a/native/crates/es-tags/tests/write.rs b/native/crates/es-tags/tests/write.rs index 6f2a485..9de912c 100644 --- a/native/crates/es-tags/tests/write.rs +++ b/native/crates/es-tags/tests/write.rs @@ -37,7 +37,10 @@ fn every_field_round_trips_through_a_wav_and_repeats_do_not_stack_chunks() { write(&path, &edit).unwrap(); write(&path, &edit).unwrap(); let f = read(&path).unwrap().fields; - assert_eq!((f.title.as_str(), f.original_artist.as_str(), f.comment.as_str(), f.year, f.track_no), ("T", "O", "note", 2020, 3)); + assert_eq!( + (f.title.as_str(), f.original_artist.as_str(), f.comment.as_str(), f.year, f.track_no), + ("T", "O", "note", 2020, 3) + ); let bytes = std::fs::read(&path).unwrap(); assert_eq!(bytes.windows(4).filter(|w| w == b"ID3 " || w == b"id3 ").count(), 1); diff --git a/native/crates/es-usb/src/convert.rs b/native/crates/es-usb/src/convert.rs index 1d70814..eba2d05 100644 --- a/native/crates/es-usb/src/convert.rs +++ b/native/crates/es-usb/src/convert.rs @@ -43,7 +43,11 @@ impl AudioConverter for Ffmpeg { let narrow = |value: i64| u32::try_from(value).unwrap_or(0); let requested = narrow(self.preset.bitrate.unwrap_or(0)); // Only MP3 is encoded at a constant bitrate; AAC's is an average the encoder may undershoot. - let bitrate = if self.preset.format == "mp3" { requested } else { Some(narrow(info.bitrate)).filter(|b| *b > 0).unwrap_or(requested) }; + let bitrate = if self.preset.format == "mp3" { + requested + } else { + Some(narrow(info.bitrate)).filter(|b| *b > 0).unwrap_or(requested) + }; Ok(ConvertedAudio { offset_ms: es_convert::delay_offset_ms(source, destination).unwrap_or(0), bitrate, @@ -65,7 +69,11 @@ impl AudioConverter for Ffmpeg { let rate = u64::try_from(self.preset.sample_rate.unwrap_or(48_000)).unwrap_or(48_000); let pcm = rate * depth / 8 * 2; // Lossless compression roughly halves music; an estimate only. - if matches!(format, "flac" | "alac") { pcm * 3 / 5 } else { pcm } + if matches!(format, "flac" | "alac") { + pcm * 3 / 5 + } else { + pcm + } } }; seconds.saturating_mul(bytes_per_second).saturating_add(64 * 1024) @@ -84,7 +92,8 @@ mod tests { fn profiles_name_the_format_and_its_quality() { let mp3 = preset(&serde_json::json!({ "format": "mp3", "bitrate": 320 })).map(Ffmpeg::new); assert_eq!(mp3.as_ref().map(|c| (c.profile(), c.extension())), Some(("es-ffmpeg-v1:mp3-320k", "mp3"))); - let alac = preset(&serde_json::json!({ "format": "alac", "bitDepth": 24, "sampleRate": 96000 })).map(Ffmpeg::new); + let alac = + preset(&serde_json::json!({ "format": "alac", "bitDepth": 24, "sampleRate": 96000 })).map(Ffmpeg::new); assert_eq!(alac.as_ref().map(|c| (c.profile(), c.extension())), Some(("es-ffmpeg-v1:alac-24-96000", "m4a"))); } diff --git a/native/crates/es-usb/src/main.rs b/native/crates/es-usb/src/main.rs index af81a02..4e89227 100644 --- a/native/crates/es-usb/src/main.rs +++ b/native/crates/es-usb/src/main.rs @@ -48,7 +48,9 @@ struct Job { conversion: Option, } -fn default_operation() -> String { "export".into() } +fn default_operation() -> String { + "export".into() +} fn emit(value: &serde_json::Value) -> io::Result<()> { let mut output = io::stdout().lock(); @@ -77,7 +79,9 @@ fn cancel_requested_on_input() -> Arc { let flag = Arc::clone(&requested); std::thread::spawn(move || { let asks_to_cancel = io::stdin().lock().lines().map_while(Result::ok).any(|line| line.trim() == "cancel"); - if asks_to_cancel { flag.store(true, Ordering::SeqCst); } + if asks_to_cancel { + flag.store(true, Ordering::SeqCst); + } }); requested } @@ -113,11 +117,7 @@ fn run(path: &Path) -> Result<(), JobError> { playlists: job.playlists, my_tags: job.my_tags, }; - let options = rb_usb::Options { - settings_dir: job.settings_dir, - decisions: job.decisions, - converter, - }; + let options = rb_usb::Options { settings_dir: job.settings_dir, decisions: job.decisions, converter }; if job.operation == "inspect" { let inspection = rb_usb::inspect(&job.destination, &source, &options)?; emit(&serde_json::json!({ "event": "result", "inspection": inspection }))?; @@ -132,7 +132,8 @@ fn run(path: &Path) -> Result<(), JobError> { &source, &options, &mut |event| { - let file = event.file.map(|file| serde_json::json!({ "done": file.done, "total": file.total, "unit": file.unit })); + let file = + event.file.map(|file| serde_json::json!({ "done": file.done, "total": file.total, "unit": file.unit })); let _ = emit(&serde_json::json!({ "event": "progress", "phase": phase(event.stage), "done": event.done, "total": event.total, "unit": event.unit, "file": file, "name": event.title, @@ -198,7 +199,10 @@ mod tests { }; assert!(job(serde_json::Value::Null).is_ok_and(|c| c.is_none())); let wav = job(serde_json::json!({ "format": "wav", "bitDepth": 16, "sampleRate": 44100 })).ok().flatten(); - assert_eq!(wav.map(|c| (c.extension().to_owned(), c.profile().to_owned())), Some(("wav".into(), "es-ffmpeg-v1:wav-16-44100".into()))); + assert_eq!( + wav.map(|c| (c.extension().to_owned(), c.profile().to_owned())), + Some(("wav".into(), "es-ffmpeg-v1:wav-16-44100".into())) + ); assert!(job(serde_json::json!({ "format": "ogg" })).is_err()); } diff --git a/native/crates/es-wave/src/lib.rs b/native/crates/es-wave/src/lib.rs index 2ee94d2..2941311 100644 --- a/native/crates/es-wave/src/lib.rs +++ b/native/crates/es-wave/src/lib.rs @@ -46,9 +46,7 @@ pub fn wave_rates(length: usize, sample_rate: f64) -> WaveRates { fn scaled_rates(length: usize, sample_rate: f64, quality: u32) -> WaveRates { let scale = quality.clamp(1, 100) as f64 / 100.0; let duration = length as f64 / sample_rate; - let band_rate = (BAND_RATE * scale) - .min(sample_rate) - .min(MAX_BAND_FRAMES / duration); + let band_rate = (BAND_RATE * scale).min(sample_rate).min(MAX_BAND_FRAMES / duration); let env_rate = (ENVELOPE_RATE * scale).min(MAX_ENVELOPE_SAMPLES / duration); let band_step = sample_rate / band_rate; let env_step = sample_rate / env_rate; @@ -87,21 +85,8 @@ pub struct ScanSpec { /// Splits the scan into up to `parts` independent parts, each starting its band filters early /// enough to settle before its first entry. -pub fn plan_wave( - length: usize, - sample_rate: f64, - parts: usize, - want_bands: bool, - want_env: bool, -) -> Vec { - plan_with( - length, - sample_rate, - parts, - want_bands, - want_env, - wave_rates(length, sample_rate), - ) +pub fn plan_wave(length: usize, sample_rate: f64, parts: usize, want_bands: bool, want_env: bool) -> Vec { + plan_with(length, sample_rate, parts, want_bands, want_env, wave_rates(length, sample_rate)) } fn plan_with( @@ -126,31 +111,12 @@ fn plan_with( if band.1 == 0 && env.1 == 0 { continue; } - let band_start = if band.1 > 0 { - (band.0 as f64 * rates.band_step).floor() as usize - } else { - sample0 - }; - let band_filter_from = if band.1 > 0 { - band_start.saturating_sub(if band.0 == 0 { 0 } else { warmup }) - } else { - band_start - }; - let band_end = if band.1 > 0 { - frame_end(band.0 + band.1 - 1, rates.band_step, length) - } else { - sample0 - }; - let env_start = if env.1 > 0 { - (env.0 as f64 * rates.env_step).floor() as usize - } else { - band_filter_from - }; - let env_end = if env.1 > 0 { - frame_end(env.0 + env.1 - 1, rates.env_step, length) - } else { - band_end - }; + let band_start = if band.1 > 0 { (band.0 as f64 * rates.band_step).floor() as usize } else { sample0 }; + let band_filter_from = + if band.1 > 0 { band_start.saturating_sub(if band.0 == 0 { 0 } else { warmup }) } else { band_start }; + let band_end = if band.1 > 0 { frame_end(band.0 + band.1 - 1, rates.band_step, length) } else { sample0 }; + let env_start = if env.1 > 0 { (env.0 as f64 * rates.env_step).floor() as usize } else { band_filter_from }; + let env_end = if env.1 > 0 { frame_end(env.0 + env.1 - 1, rates.env_step, length) } else { band_end }; specs.push(ScanSpec { origin: band_filter_from.min(env_start), to: band_end.max(env_end), @@ -232,9 +198,7 @@ impl Biquad { } fn run(&mut self, x: f64) -> f64 { - let y = self.b0 * x + self.b1 * self.x1 + self.b2 * self.x2 - - self.a1 * self.y1 - - self.a2 * self.y2; + let y = self.b0 * x + self.b1 * self.x1 + self.b2 * self.x2 - self.a1 * self.y1 - self.a2 * self.y2; self.x2 = self.x1; self.x1 = x; self.y2 = self.y1; @@ -263,10 +227,7 @@ pub struct ScanOut { /// Scans one part. `samples` are the mono samples from `spec.origin` to `spec.to`. pub fn scan_part(spec: &ScanSpec, samples: &[f32]) -> ScanOut { let at = |index: usize| f64::from(samples[index - spec.origin]); - let mut out = ScanOut { - bands: vec![0; spec.band_frames * 3], - ..ScanOut::default() - }; + let mut out = ScanOut { bands: vec![0; spec.band_frames * 3], ..ScanOut::default() }; if spec.band_frames > 0 { let mut low = Biquad::new(Pass::Low, spec.sample_rate, LOW_HZ); let mut mid_high = Biquad::new(Pass::High, spec.sample_rate, LOW_HZ); @@ -292,17 +253,9 @@ pub fn scan_part(spec: &ScanSpec, samples: &[f32]) -> ScanOut { high_peak = high_peak.max(high.run(v).abs()); index += 1; } - let quantised = [ - quant_band(low_peak), - quant_band(mid_peak), - quant_band(high_peak), - ]; + let quantised = [quant_band(low_peak), quant_band(mid_peak), quant_band(high_peak)]; out.bands[k * 3..k * 3 + 3].copy_from_slice(&quantised); - out.band_max = out - .band_max - .max(quantised[0]) - .max(quantised[1]) - .max(quantised[2]); + out.band_max = out.band_max.max(quantised[0]).max(quantised[1]).max(quantised[2]); } } @@ -353,46 +306,19 @@ pub fn build(mono: &[f32], sample_rate: f64, parts: usize, want_bands: bool) -> build_scaled(mono, sample_rate, parts, want_bands, 100) } -fn build_scaled( - mono: &[f32], - sample_rate: f64, - parts: usize, - want_bands: bool, - quality: u32, -) -> Option { +fn build_scaled(mono: &[f32], sample_rate: f64, parts: usize, want_bands: bool, quality: u32) -> Option { let rates = scaled_rates(mono.len(), sample_rate, quality); if rates.env_frames < 2 { return None; } let want_bands = want_bands && rates.band_frames >= 2; - let specs = plan_with( - mono.len(), - sample_rate, - parts.max(1), - want_bands, - true, - rates, - ); - let scanned: Vec = specs - .par_iter() - .map(|spec| scan_part(spec, &mono[spec.origin..spec.to])) - .collect(); + let specs = plan_with(mono.len(), sample_rate, parts.max(1), want_bands, true, rates); + let scanned: Vec = specs.par_iter().map(|spec| scan_part(spec, &mono[spec.origin..spec.to])).collect(); - let data: Vec = scanned - .iter() - .flat_map(|part| part.env.iter().copied()) - .collect(); - let peak = scanned - .iter() - .map(|part| part.env_peak) - .max() - .unwrap_or(0) - .max(1); + let data: Vec = scanned.iter().flat_map(|part| part.env.iter().copied()).collect(); + let peak = scanned.iter().map(|part| part.env_peak).max().unwrap_or(0).max(1); let bands = want_bands.then(|| { - let mut bands: Vec = scanned - .iter() - .flat_map(|part| part.bands.iter().copied()) - .collect(); + let mut bands: Vec = scanned.iter().flat_map(|part| part.bands.iter().copied()).collect(); let max = scanned.iter().map(|part| part.band_max).max().unwrap_or(0); normalize_bands(&mut bands, max); bands @@ -401,21 +327,14 @@ fn build_scaled( rate: reported_rate(rates.env_frames, mono.len(), sample_rate), data, peak, - band_rate: if want_bands { - reported_rate(rates.band_frames, mono.len(), sample_rate) - } else { - 0.0 - }, + band_rate: if want_bands { reported_rate(rates.band_frames, mono.len(), sample_rate) } else { 0.0 }, bands, }) } /// Left and right averaged, as the renderer mixed them. Mono sources come out unchanged. pub fn mix_mono(interleaved: &[f32]) -> Vec { - interleaved - .chunks_exact(2) - .map(|frame| ((f64::from(frame[0]) + f64::from(frame[1])) * 0.5) as f32) - .collect() + interleaved.chunks_exact(2).map(|frame| ((f64::from(frame[0]) + f64::from(frame[1])) * 0.5) as f32).collect() } /// Decodes `path` at its own sample rate, through the same decoder the deck plays, and analyses it. @@ -432,18 +351,8 @@ pub fn analyse(path: &Path, want_bands: bool, quality: u32) -> Result Golden { let env_rate = f64::from_le_bytes(take(8).try_into().unwrap()); let env_peak = i32::from_le_bytes(take(4).try_into().unwrap()); let env_len = u32::from_le_bytes(take(4).try_into().unwrap()) as usize; - let env = take(env_len * 2) - .chunks_exact(2) - .map(|c| i16::from_le_bytes([c[0], c[1]])) - .collect(); + let env = take(env_len * 2).chunks_exact(2).map(|c| i16::from_le_bytes([c[0], c[1]])).collect(); let band_rate = f64::from_le_bytes(take(8).try_into().unwrap()); let band_len = u32::from_le_bytes(take(4).try_into().unwrap()) as usize; let bands = take(band_len).to_vec(); - Golden { - env_rate, - env_peak, - env, - band_rate, - bands, - } + Golden { env_rate, env_peak, env, band_rate, bands } } /// Noise, a 110 Hz triangle and a 3 kHz square with a swell each second, in whole 16-bit steps, @@ -52,18 +43,8 @@ fn signal(length: usize, sample_rate: i64) -> Vec { seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); let noise = i64::from((seed >> 8) % 4001) - 2000; let t = n % tri_period; - let tri = (if t * 2 < tri_period { - t - } else { - tri_period - t - }) * 24_000 - / tri_period - - 6000; - let sq = if (n % sq_period) * 2 < sq_period { - 3000 - } else { - -3000 - }; + let tri = (if t * 2 < tri_period { t } else { tri_period - t }) * 24_000 / tri_period - 6000; + let sq = if (n % sq_period) * 2 < sq_period { 3000 } else { -3000 }; let swell = 1 + (n % sample_rate) * 4 / sample_rate; ((noise + tri + sq) * swell / 4) as f32 / 32768.0 }) @@ -88,34 +69,16 @@ fn check(name: &str, sample_rate: i64, seconds: f64, parts: usize) { assert_eq!(wave.rate, golden.env_rate, "{name}: envelope rate"); assert_eq!(wave.data.len(), golden.env.len(), "{name}: envelope length"); - assert!( - (wave.peak - golden.env_peak).abs() <= 1, - "{name}: peak {} vs {}", - wave.peak, - golden.env_peak - ); + assert!((wave.peak - golden.env_peak).abs() <= 1, "{name}: peak {} vs {}", wave.peak, golden.env_peak); let (gap, at) = largest_gap(&wave.data, &golden.env); - assert!( - gap <= 1, - "{name}: envelope entry {at} is {} against {}", - wave.data[at], - golden.env[at] - ); + assert!(gap <= 1, "{name}: envelope entry {at} is {} against {}", wave.data[at], golden.env[at]); let bands = wave.bands.expect("bands asked for"); assert_eq!(wave.band_rate, golden.band_rate, "{name}: band rate"); assert_eq!(bands.len(), golden.bands.len(), "{name}: band length"); let (gap, at) = largest_gap(&bands, &golden.bands); - assert!( - gap <= 1, - "{name}: band value {at} is {} against {}", - bands[at], - golden.bands[at] - ); - assert!( - golden.bands.iter().any(|&b| b > 100), - "{name}: the fixture exercises the bands" - ); + assert!(gap <= 1, "{name}: band value {at} is {} against {}", bands[at], golden.bands[at]); + assert!(golden.bands.iter().any(|&b| b > 100), "{name}: the fixture exercises the bands"); } #[test] diff --git a/native/rustfmt.toml b/native/rustfmt.toml new file mode 100644 index 0000000..c775577 --- /dev/null +++ b/native/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 120 +use_small_heuristics = "Max" From 0d0b5e0d55921b032b4c9b51e869303233777208 Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 14:37:18 +0000 Subject: [PATCH 03/25] Clear the native clippy warnings Drop the allow for chunks_exact_to_as_chunks, a lint current clippy does not know, and check es-usb's schema error without unwrap_err. Co-Authored-By: Claude Opus 5.5 --- native/Cargo.toml | 1 - native/crates/es-usb/src/main.rs | 6 ++---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/native/Cargo.toml b/native/Cargo.toml index b04d603..4ba72d2 100644 --- a/native/Cargo.toml +++ b/native/Cargo.toml @@ -72,7 +72,6 @@ module_name_repetitions = "allow" must_use_candidate = "allow" missing_errors_doc = "allow" missing_panics_doc = "allow" -chunks_exact_to_as_chunks = "allow" manual_is_multiple_of = "allow" [profile.release] diff --git a/native/crates/es-usb/src/main.rs b/native/crates/es-usb/src/main.rs index 4e89227..ac1e8c6 100644 --- a/native/crates/es-usb/src/main.rs +++ b/native/crates/es-usb/src/main.rs @@ -210,10 +210,8 @@ mod tests { fn rejects_missing_or_unsupported_job_schema() { assert!(parse_job(br#"{"destination":"/tmp","tracks":[],"playlists":[]}"#).is_err()); let job = serde_json::json!({ "schemaVersion": JOB_SCHEMA_VERSION + 1, "destination": "/tmp", "tracks": [], "playlists": [] }); - assert!(parse_job(job.to_string().as_bytes()) - .unwrap_err() - .to_string() - .contains("Unsupported export job schema version")); + let error = parse_job(job.to_string().as_bytes()).err().map(|error| error.to_string()); + assert!(error.is_some_and(|message| message.contains("Unsupported export job schema version"))); } #[test] From 292c90cc59d9cf171e8f98b5c071d39d881d6ec7 Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 14:46:58 +0000 Subject: [PATCH 04/25] Find and name a track's sections structure::segment splits the beat grid into sections with checkerboard novelty over bar profiles (timbre, harmony, rhythm, loudness), starting sections only on the 4-bar grid phase that carries the most novelty, and names them intro, build, drop, breakdown or outro from their loudness and place. BarFeatures are measured once so tunings can be compared. The structure_eval example scores section starts against a DJ's cues from a cue_survey dump. On 425 tracks the tuned defaults put 71% of cues on a section start (F1 0.61), against 0.47 for every 16 bars and 0.57 for rekordbox's own phrase changes; held-out playlists score 0.56-0.62. Co-Authored-By: Claude Opus 5.5 --- .../es-analyse/examples/structure_eval.rs | 337 ++++++++++++++ native/crates/es-analyse/src/downbeat.rs | 12 +- native/crates/es-analyse/src/lib.rs | 1 + native/crates/es-analyse/src/structure.rs | 424 ++++++++++++++++++ native/crates/es-index/examples/cue_survey.rs | 1 + 5 files changed, 769 insertions(+), 6 deletions(-) create mode 100644 native/crates/es-analyse/examples/structure_eval.rs create mode 100644 native/crates/es-analyse/src/structure.rs diff --git a/native/crates/es-analyse/examples/structure_eval.rs b/native/crates/es-analyse/examples/structure_eval.rs new file mode 100644 index 0000000..17960b4 --- /dev/null +++ b/native/crates/es-analyse/examples/structure_eval.rs @@ -0,0 +1,337 @@ +//! Scores section starts against where a DJ put their cues, using a dump from `es-index`'s +//! `cue_survey` example. Cues sit on section changes, so a good segmenter's starts carry them. +//! Each track is measured once; tunings are then tried one setting at a time, keeping the best. +//! `cargo run --release -p es-analyse --example structure_eval -- survey.json` + +use std::collections::{BTreeMap, HashSet}; +use std::path::Path; + +use es_analyse::structure::{segment, BarFeatures, BarIndex, Section, SectionKind, Tuning}; +use es_analyse::{decode_mono, Beat, SAMPLE_RATE}; +use rayon::prelude::*; +use serde_json::Value; + +const ON_BEAT_TOLERANCE_MS: i64 = 15; + +struct Track { + title: String, + features: BarFeatures, + cue_bars: HashSet, + rekordbox_phrase_bars: Option>, + rekordbox_change_bars: Option>, + rekordbox_bar_kinds: Option>>, +} + +#[derive(Default, Clone, Copy)] +struct Score { + cues: usize, + starts: usize, + hits: usize, + tracks: usize, +} + +impl Score { + fn add(&mut self, cues: &HashSet, starts: &HashSet) { + self.cues += cues.len(); + self.starts += starts.len(); + self.hits += cues.intersection(starts).count(); + self.tracks += 1; + } + + fn recall(&self) -> f64 { + self.hits as f64 / self.cues.max(1) as f64 + } + + fn precision(&self) -> f64 { + self.hits as f64 / self.starts.max(1) as f64 + } + + fn f1(&self) -> f64 { + let (p, r) = (self.precision(), self.recall()); + if p + r == 0.0 { + 0.0 + } else { + 2.0 * p * r / (p + r) + } + } + + fn line(&self, name: &str) -> String { + format!( + "{name:<34} recall {:>5.1}% precision {:>5.1}% F1 {:.3} starts/track {:>5.1} cues/track {:.1}", + 100.0 * self.recall(), + 100.0 * self.precision(), + self.f1(), + self.starts as f64 / self.tracks.max(1) as f64, + self.cues as f64 / self.tracks.max(1) as f64 + ) + } +} + +fn main() -> Result<(), Box> { + let path = std::env::args().nth(1).ok_or("pass the survey JSON from cue_survey")?; + let survey: Vec = serde_json::from_str(&std::fs::read_to_string(path)?)?; + let tracks: Vec = survey.par_iter().filter_map(measure).collect(); + println!("measured {} of {} tracks\n", tracks.len(), survey.len()); + + report_baselines(&tracks); + let best = report_labels(&tracks, &tune(&tracks)); + println!("\nbest {best:?}"); + report_kinds(&tracks, &best); + Ok(()) +} + +fn measure(entry: &Value) -> Option { + let grid = entry.get("grid")?; + let times: Vec = numbers(&grid["times"]).into_iter().map(|t| t as u32).collect(); + let beat_numbers: Vec = numbers(&grid["beats"]).into_iter().map(|b| b as u8).collect(); + let beats: Vec = + times.iter().zip(&beat_numbers).map(|(&time_ms, &number)| Beat { number, tempo_x100: 0, time_ms }).collect(); + let bar_of_beat: BTreeMap = beats + .iter() + .enumerate() + .filter(|(_, b)| b.number == 1) + .enumerate() + .map(|(bar, (beat, _))| (beat, bar)) + .collect(); + let bar_at_ms = |ms: i64| { + let beat = times.partition_point(|&t| i64::from(t) < ms - ON_BEAT_TOLERANCE_MS); + let on_beat = times.get(beat).is_some_and(|&t| (i64::from(t) - ms).abs() <= ON_BEAT_TOLERANCE_MS); + on_beat.then(|| bar_of_beat.get(&beat).copied()).flatten() + }; + let cue_bars: HashSet = + entry["cues"].as_array()?.iter().filter_map(|cue| cue["startMs"].as_i64()).filter_map(bar_at_ms).collect(); + if cue_bars.is_empty() { + return None; + } + + let phrases = entry["structure"]["phrases"].as_array(); + let phrase_bar = |phrase: &Value| { + let first_beat = usize::try_from(phrase["firstBeat"].as_u64()?).ok()?.checked_sub(1)?; + bar_of_beat.get(&first_beat).copied() + }; + let rekordbox_phrase_bars = phrases.map(|all| all.iter().filter_map(phrase_bar).collect()); + let rekordbox_change_bars = phrases.map(|all| { + let kind = |phrase: &Value| phrase["label"].as_str().unwrap_or("").split(' ').next().unwrap_or("").to_owned(); + all.iter() + .enumerate() + .filter(|(index, phrase)| *index == 0 || kind(&all[index - 1]) != kind(phrase)) + .filter_map(|(_, phrase)| phrase_bar(phrase)) + .collect() + }); + + let downbeats: Vec = bar_of_beat.keys().copied().collect(); + let bar_containing = |beat: usize| downbeats.partition_point(|&first| first <= beat).saturating_sub(1); + let rekordbox_bar_kinds = phrases.map(|all| { + let mut kinds = vec![None; downbeats.len()]; + for (index, phrase) in all.iter().enumerate() { + let first_beat = |p: &Value| p["firstBeat"].as_u64().map_or(0, |b| b.saturating_sub(1) as usize); + let start = bar_containing(first_beat(phrase)); + let end = all.get(index + 1).map_or(downbeats.len(), |next| bar_containing(first_beat(next))); + let kind = rekordbox_kind(phrase["label"].as_str().unwrap_or("")); + kinds[start.min(downbeats.len())..end.min(downbeats.len())].fill(kind); + } + kinds + }); + + let audio = decode_mono(Path::new(entry["path"].as_str()?)).ok()?; + Some(Track { + title: format!("{} - {}", entry["artist"].as_str().unwrap_or(""), entry["title"].as_str().unwrap_or("")), + features: BarFeatures::measure(&audio, f64::from(SAMPLE_RATE), &beats), + cue_bars, + rekordbox_phrase_bars, + rekordbox_change_bars, + rekordbox_bar_kinds, + }) +} + +fn rekordbox_kind(label: &str) -> Option { + match label.split(' ').next()? { + "INTRO" => Some(SectionKind::Intro), + "UP" => Some(SectionKind::Build), + "DOWN" => Some(SectionKind::Breakdown), + "CHORUS" => Some(SectionKind::Drop), + "OUTRO" => Some(SectionKind::Outro), + _ => None, + } +} + +const KINDS: [SectionKind; 5] = + [SectionKind::Intro, SectionKind::Build, SectionKind::Drop, SectionKind::Breakdown, SectionKind::Outro]; + +/// Share of bars whose section kind matches rekordbox's, and the counts behind it, ours by theirs. +fn label_agreement(tracks: &[Track], tuning: &Tuning) -> (f64, [[usize; 5]; 5]) { + let mut counts = [[0usize; 5]; 5]; + for track in tracks { + let Some(theirs) = &track.rekordbox_bar_kinds else { continue }; + for section in segment(&track.features, tuning) { + let ours = KINDS.iter().position(|&k| k == section.kind).unwrap_or(0); + for bar in section.first_bar..section.first_bar + section.bars { + if let Some(Some(kind)) = theirs.get(bar) { + counts[ours][KINDS.iter().position(|k| k == kind).unwrap_or(0)] += 1; + } + } + } + } + let total: usize = counts.iter().flatten().sum(); + let agreed: usize = (0..5).map(|i| counts[i][i]).sum(); + (agreed as f64 / total.max(1) as f64, counts) +} + +fn report_labels(tracks: &[Track], best: &Tuning) -> Tuning { + println!("\nbar labels against rekordbox's:"); + let mut chosen = *best; + let mut chosen_agreement = 0.0; + for drop_energy in [0.5, 0.6, 0.7, 0.75, 0.8, 0.85, 0.9] { + let tuning = Tuning { drop_energy, ..*best }; + let (agreement, _) = label_agreement(tracks, &tuning); + println!(" drop energy {drop_energy}: {:.1}% of bars agree", 100.0 * agreement); + if agreement > chosen_agreement { + (chosen, chosen_agreement) = (tuning, agreement); + } + } + let (_, counts) = label_agreement(tracks, &chosen); + println!(" ours \\ theirs {}", KINDS.iter().map(|&k| format!("{:>9}", kind_name(k))).collect::()); + for (ours, row) in KINDS.iter().zip(counts) { + println!(" {:<14} {}", kind_name(*ours), row.iter().map(|n| format!("{n:>9}")).collect::()); + } + chosen +} + +fn numbers(value: &Value) -> Vec { + value.as_array().map(|all| all.iter().filter_map(Value::as_u64).collect()).unwrap_or_default() +} + +fn starts(sections: &[Section]) -> HashSet { + sections.iter().map(|section| section.first_bar).collect() +} + +fn score(tracks: &[Track], tuning: &Tuning) -> Score { + let mut total = Score::default(); + for track in tracks { + total.add(&track.cue_bars, &starts(&segment(&track.features, tuning))); + } + total +} + +fn report_baselines(tracks: &[Track]) { + for every in [8, 16, 32] { + let mut total = Score::default(); + for track in tracks { + total.add(&track.cue_bars, &(0..track.features.bars()).step_by(every).collect()); + } + println!("{}", total.line(&format!("every {every} bars from the first"))); + } + let with_phrases: Vec<&Track> = tracks.iter().filter(|t| t.rekordbox_phrase_bars.is_some()).collect(); + let (mut phrases, mut changes, mut ours) = (Score::default(), Score::default(), Score::default()); + for track in &with_phrases { + phrases.add(&track.cue_bars, track.rekordbox_phrase_bars.as_ref().unwrap_or(&HashSet::new())); + changes.add(&track.cue_bars, track.rekordbox_change_bars.as_ref().unwrap_or(&HashSet::new())); + ours.add(&track.cue_bars, &starts(&segment(&track.features, &Tuning::default()))); + } + println!("-- the {} tracks rekordbox phrased --", with_phrases.len()); + println!("{}", phrases.line("rekordbox phrase starts")); + println!("{}", changes.line("rekordbox phrase kind changes")); + println!("{}", ours.line("ours, default tuning")); +} + +type Setting = Vec<(String, Tuning)>; + +fn settings(base: &Tuning) -> Vec { + let vary = |name: &'static str, values: &[f64], set: fn(&mut Tuning, f64)| -> Setting { + values + .iter() + .map(|&value| { + let mut tuning = *base; + set(&mut tuning, value); + (format!("{name} {value}"), tuning) + }) + .collect() + }; + let kernels = [[2, 4], [4, 8], [4, 16], [8, 16], [2, 8]] + .iter() + .map(|&widths| (format!("kernels {widths:?}"), Tuning { kernel_half_widths: widths, ..*base })) + .collect(); + vec![ + vary("threshold", &[-0.75, -0.5, -0.25, 0.0, 0.25, 0.5, 0.75, 1.0], |t, v| t.boundary_threshold = v), + kernels, + vary("timbre", &[0.0, 0.5, 1.0, 2.0], |t, v| t.timbre_weight = v), + vary("harmony", &[0.0, 0.25, 0.5, 1.0, 2.0], |t, v| t.harmony_weight = v), + vary("rhythm", &[0.0, 0.5, 1.0, 2.0], |t, v| t.rhythm_weight = v), + vary("loudness", &[0.0, 0.5, 1.0, 2.0, 4.0], |t, v| t.loudness_weight = v), + ] +} + +fn tune(tracks: &[Track]) -> Tuning { + let mut best = Tuning::default(); + let mut best_score = score(tracks, &best); + println!("\n{}", best_score.line("start")); + for round in 1..=2 { + println!("-- round {round} --"); + for options in settings(&best) { + let scored: Vec<(String, Tuning, Score)> = + options.into_par_iter().map(|(label, tuning)| (label, tuning, score(tracks, &tuning))).collect(); + for (label, tuning, candidate) in scored { + if candidate.f1() > best_score.f1() + 1e-9 { + best = tuning; + best_score = candidate; + println!("{}", candidate.line(&label)); + } + } + } + } + println!("{}", best_score.line("best")); + best +} + +/// What our sections are called where the DJ cued, as "Drop#2" style anchors. +fn report_kinds(tracks: &[Track], tuning: &Tuning) { + let mut at_cues: BTreeMap = BTreeMap::new(); + let mut everywhere: BTreeMap = BTreeMap::new(); + for track in tracks { + let sections = segment(&track.features, tuning); + let mut seen: BTreeMap = BTreeMap::new(); + for section in §ions { + let kind = kind_name(section.kind); + let occurrence = seen.entry(kind.to_owned()).and_modify(|n| *n += 1).or_insert(1); + let anchor = format!("{kind}#{occurrence}"); + *everywhere.entry(anchor.clone()).or_default() += 1; + if track.cue_bars.contains(§ion.first_bar) { + *at_cues.entry(anchor).or_default() += 1; + } + } + } + let mut rows: Vec<_> = everywhere.into_iter().collect(); + rows.sort_by_key(|(_, found)| std::cmp::Reverse(*found)); + println!("\n{:<14} {:>6} {:>7}", "section start", "found", "cued"); + for (anchor, found) in rows.into_iter().take(24) { + let cued = at_cues.get(&anchor).copied().unwrap_or(0); + println!("{anchor:<14} {found:>6} {:>6.0}%", 100.0 * cued as f64 / found as f64); + } + if let Some(track) = tracks.first() { + println!("\nexample: {}", track.title); + for section in segment(&track.features, tuning) { + let cued = if track.cue_bars.contains(§ion.first_bar) { "cued" } else { "" }; + println!( + " bar {:>4} {:>3} bars {:<9} energy {:.2} {cued}", + section.first_bar, + section.bars, + kind_name(section.kind), + section.relative_energy + ); + } + let mut missed: Vec<_> = + track.cue_bars.difference(&starts(&segment(&track.features, tuning))).copied().collect(); + missed.sort_unstable(); + println!(" cues on no section start: bars {missed:?}"); + } +} + +fn kind_name(kind: SectionKind) -> &'static str { + match kind { + SectionKind::Intro => "Intro", + SectionKind::Build => "Build", + SectionKind::Drop => "Drop", + SectionKind::Breakdown => "Breakdown", + SectionKind::Outro => "Outro", + } +} diff --git a/native/crates/es-analyse/src/downbeat.rs b/native/crates/es-analyse/src/downbeat.rs index 89cd6ca..a14f88d 100644 --- a/native/crates/es-analyse/src/downbeat.rs +++ b/native/crates/es-analyse/src/downbeat.rs @@ -6,7 +6,7 @@ use crate::spectrum::Stft; -const BANDS: usize = 12; +pub(crate) const BANDS: usize = 12; const BAND_LO_HZ: f64 = 40.0; const BAND_HI_HZ: f64 = 12_000.0; /// Phrase lengths compared, in beats, and their weights. @@ -21,10 +21,10 @@ const START_WEIGHT: f64 = 0.6; const SOUNDING_DB: f64 = 20.0; /// Per-beat features: log band energies and a unit chroma, averaged over the beat. -struct Profiles { - bands: Vec<[f64; BANDS]>, - chroma: Vec<[f64; 12]>, - kick: Vec, +pub(crate) struct Profiles { + pub bands: Vec<[f64; BANDS]>, + pub chroma: Vec<[f64; 12]>, + pub kick: Vec, } fn band_edges(stft: &Stft) -> [usize; BANDS + 1] { @@ -37,7 +37,7 @@ fn band_edges(stft: &Stft) -> [usize; BANDS + 1] { edges } -fn profiles(stft: &Stft, beats: &[f64], low_onset: &dyn Fn(f64) -> f64) -> Profiles { +pub(crate) fn profiles(stft: &Stft, beats: &[f64], low_onset: &dyn Fn(f64) -> f64) -> Profiles { let edges = band_edges(stft); let bin_hz = stft.bin_hz(); let pitch: Vec> = (0..stft.bins) diff --git a/native/crates/es-analyse/src/lib.rs b/native/crates/es-analyse/src/lib.rs index c7b3816..62e2d3b 100644 --- a/native/crates/es-analyse/src/lib.rs +++ b/native/crates/es-analyse/src/lib.rs @@ -6,6 +6,7 @@ pub mod downbeat; pub mod key; pub mod onset; pub mod spectrum; +pub mod structure; pub mod tempo; pub mod waveform; diff --git a/native/crates/es-analyse/src/structure.rs b/native/crates/es-analyse/src/structure.rs new file mode 100644 index 0000000..cd16583 --- /dev/null +++ b/native/crates/es-analyse/src/structure.rs @@ -0,0 +1,424 @@ +//! Where a track's sections start, and what each one is: intro, build, drop, breakdown or outro. +//! +//! Every bar gets a profile of its timbre, harmony, rhythm and loudness. A section starts where the +//! bars after a line sound unlike the bars before it while each side sounds like itself: Foote's +//! checkerboard novelty over the bars' self-similarity. Dance music changes on phrase lines, so a +//! track's sections only start on one 4-bar grid, at the phase where its novelty lines up best. +//! Each section is then named from its energy and where it falls among the drops. + +use crate::downbeat::{self, BANDS}; +use crate::{onset, spectrum, Beat, KICK_HZ, ONSET_FRAME, ONSET_HOP}; + +pub type BarIndex = usize; +pub type BeatIndex = usize; + +const HAT_HZ: (f64, f64) = (6_000.0, 16_000.0); +const BEATS_PER_BAR: usize = 4; +const BARS_PER_PHRASE: usize = 4; +const MIN_KERNEL_SIDE: usize = 2; +/// How much of the track's energy range a build's second half must climb above its first. +const MIN_BUILD_RISE: f64 = 0.1; +const FLAT_SPREAD: f64 = 1e-9; +const QUIET_PERCENTILE: f64 = 0.1; +const LOUD_PERCENTILE: f64 = 0.95; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SectionKind { + Intro, + Build, + Drop, + Breakdown, + Outro, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Section { + pub first_beat: BeatIndex, + pub first_bar: BarIndex, + pub bars: usize, + pub kind: SectionKind, + /// 0 at the track's quiet end, 1 at its loud end. + pub relative_energy: f64, +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Tuning { + pub timbre_weight: f64, + pub harmony_weight: f64, + pub rhythm_weight: f64, + pub loudness_weight: f64, + pub kernel_half_widths: [usize; 2], + /// Standard deviations above the track's typical phrase line that a line's novelty must reach. + pub boundary_threshold: f64, + /// How far from the quietest section towards the most energetic a section must reach to be a drop. + pub drop_energy: f64, +} + +impl Default for Tuning { + fn default() -> Self { + Self { + timbre_weight: 1.0, + harmony_weight: 2.0, + rhythm_weight: 1.0, + loudness_weight: 0.5, + kernel_half_widths: [4, 8], + boundary_threshold: 0.0, + drop_energy: 0.6, + } + } +} + +/// What each bar of the grid sounds like, measured once so it can be segmented many ways. +pub struct BarFeatures { + first_beats: Vec, + timbre: Vec<[f64; BANDS]>, + harmony: Vec<[f64; 12]>, + kick: Vec, + hats: Vec, + loudness: Vec, +} + +impl BarFeatures { + pub fn measure(mono: &[f32], sample_rate: f64, beats: &[Beat]) -> Self { + let times: Vec = beats.iter().map(|beat| f64::from(beat.time_ms) / 1000.0).collect(); + let stft = spectrum::stft(mono, sample_rate, ONSET_FRAME, ONSET_HOP); + let kick = onset::smooth(&onset::flux(&stft, KICK_HZ.0, KICK_HZ.1), 1); + let hats = onset::smooth(&onset::flux(&stft, HAT_HZ.0, HAT_HZ.1), 1); + let per_beat = downbeat::profiles(&stft, ×, &|t| f64::from(kick.at_time(t))); + let first_beats: Vec = + beats.iter().enumerate().filter(|(_, beat)| beat.number == 1).map(|(index, _)| index).collect(); + + let mut bars = Self { + first_beats: first_beats.clone(), + timbre: Vec::new(), + harmony: Vec::new(), + kick: Vec::new(), + hats: Vec::new(), + loudness: Vec::new(), + }; + for (bar, &first) in first_beats.iter().enumerate() { + let end = first_beats.get(bar + 1).copied().unwrap_or((first + BEATS_PER_BAR).min(beats.len())); + let span = first..end; + bars.timbre.push(mean_rows(&per_beat.bands[span.clone()])); + bars.harmony.push(unit(mean_rows(&per_beat.chroma[span.clone()]))); + bars.kick.push(mean(&per_beat.kick[span.clone()])); + bars.hats.push(mean(×[span.clone()].iter().map(|&t| f64::from(hats.at_time(t))).collect::>())); + bars.loudness.push(mean(&per_beat.bands[span].iter().map(loudness).collect::>())); + } + bars + } + + pub fn bars(&self) -> usize { + self.first_beats.len() + } +} + +pub fn segment(features: &BarFeatures, tuning: &Tuning) -> Vec
{ + if features.bars() == 0 { + return Vec::new(); + } + let starts = section_starts(features, tuning); + name_sections(features, &starts, tuning) +} + +fn section_starts(features: &BarFeatures, tuning: &Tuning) -> Vec { + let distances = Distances::between_bars(features, tuning); + let novelty = tuning + .kernel_half_widths + .iter() + .map(|&half_width| standardise(&distances.novelty(half_width))) + .fold(vec![0.0; features.bars()], |sum, part| sum.iter().zip(&part).map(|(a, b)| a + b).collect()); + let lines: Vec = (phrase_phase(&novelty)..features.bars()).step_by(BARS_PER_PHRASE).collect(); + let line_scores = standardise(&lines.iter().map(|&bar| novelty[bar]).collect::>()); + + let mut starts = vec![0]; + for (index, &bar) in lines.iter().enumerate() { + let score = line_scores[index]; + let beats_previous = index == 0 || score >= line_scores[index - 1]; + let beats_next = line_scores.get(index + 1).is_none_or(|&next| score > next); + if bar > 0 && score > tuning.boundary_threshold && beats_previous && beats_next { + starts.push(bar); + } + } + starts +} + +/// The bar, 0 to 3, whose 4-bar grid carries the most novelty. +fn phrase_phase(novelty: &[f64]) -> BarIndex { + let line_total = |phase: BarIndex| novelty.iter().skip(phase).step_by(BARS_PER_PHRASE).sum::(); + (0..BARS_PER_PHRASE).max_by(|&a, &b| line_total(a).total_cmp(&line_total(b))).unwrap_or(0) +} + +struct Distances { + bars: usize, + values: Vec, +} + +impl Distances { + fn between_bars(features: &BarFeatures, tuning: &Tuning) -> Self { + let bars = features.bars(); + let mut columns: Vec<(Vec, f64)> = Vec::new(); + let mut add_group = |group: Vec>, weight: f64| { + let share = weight / (group.len() as f64).sqrt(); + columns.extend(group.into_iter().map(|column| (standardise(&column), share))); + }; + add_group( + (0..BANDS).map(|band| features.timbre.iter().map(|bar| bar[band]).collect()).collect(), + tuning.timbre_weight, + ); + add_group( + (0..12).map(|pitch| features.harmony.iter().map(|bar| bar[pitch]).collect()).collect(), + tuning.harmony_weight, + ); + add_group(vec![features.kick.clone(), features.hats.clone()], tuning.rhythm_weight); + add_group(vec![features.loudness.clone()], tuning.loudness_weight); + + let mut values = vec![0.0; bars * bars]; + for a in 0..bars { + for b in (a + 1)..bars { + let squared: f64 = + columns.iter().map(|(column, share)| (share * (column[a] - column[b])).powi(2)).sum(); + values[a * bars + b] = squared.sqrt(); + values[b * bars + a] = squared.sqrt(); + } + } + Self { bars, values } + } + + fn at(&self, a: BarIndex, b: BarIndex) -> f64 { + self.values[a * self.bars + b] + } + + fn mean_across(&self, left: std::ops::Range, right: std::ops::Range) -> f64 { + let pairs = (left.len() * right.len()) as f64; + left.flat_map(|a| right.clone().map(move |b| (a, b))).map(|(a, b)| self.at(a, b)).sum::() / pairs + } + + fn mean_within(&self, span: std::ops::Range) -> f64 { + let pairs = (span.len() * (span.len() - 1) / 2) as f64; + let total: f64 = + span.clone().flat_map(|a| ((a + 1)..span.end).map(move |b| (a, b))).map(|(a, b)| self.at(a, b)).sum(); + total / pairs + } + + /// For each bar, how unlike the bars before it the bars from it on sound, less how unlike + /// each side sounds within itself. + fn novelty(&self, half_width: usize) -> Vec { + (0..self.bars) + .map(|line| { + let before = line.saturating_sub(half_width)..line; + let after = line..(line + half_width).min(self.bars); + if before.len() < MIN_KERNEL_SIDE || after.len() < MIN_KERNEL_SIDE { + return 0.0; + } + let within = (self.mean_within(before.clone()) + self.mean_within(after.clone())) / 2.0; + self.mean_across(before, after) - within + }) + .collect() + } +} + +fn name_sections(features: &BarFeatures, starts: &[BarIndex], tuning: &Tuning) -> Vec
{ + let bar_energy = bar_energies(features); + let spans: Vec<(BarIndex, BarIndex)> = + starts.iter().zip(starts.iter().skip(1).copied().chain([features.bars()])).map(|(&a, b)| (a, b)).collect(); + let energies: Vec = spans.iter().map(|&(a, b)| mean(&bar_energy[a..b])).collect(); + let last = spans.len() - 1; + let frames_the_track = |index: usize| last > 0 && (index == 0 || index == last); + let mut is_drop: Vec = energies + .iter() + .enumerate() + .map(|(index, &energy)| !frames_the_track(index) && energy >= tuning.drop_energy) + .collect(); + if !is_drop.contains(&true) { + let loudest_inside = + (0..=last).filter(|&index| !frames_the_track(index)).max_by(|&a, &b| energies[a].total_cmp(&energies[b])); + if let Some(index) = loudest_inside { + is_drop[index] = true; + } + } + let first_drop = is_drop.iter().position(|&drop| drop).unwrap_or(last); + let last_drop = is_drop.iter().rposition(|&drop| drop).unwrap_or(last); + + spans + .iter() + .enumerate() + .map(|(index, &(first_bar, end_bar))| { + let leads_into_drop = is_drop.get(index + 1).copied().unwrap_or(false); + let kind = if last > 0 && index == 0 { + SectionKind::Intro + } else if last > 0 && index == last { + SectionKind::Outro + } else if is_drop[index] { + SectionKind::Drop + } else if index > last_drop { + SectionKind::Outro + } else if leads_into_drop && rises(&bar_energy[first_bar..end_bar]) { + SectionKind::Build + } else if index < first_drop { + SectionKind::Intro + } else { + SectionKind::Breakdown + }; + Section { + first_beat: features.first_beats[first_bar], + first_bar, + bars: end_bar - first_bar, + kind, + relative_energy: energies[index], + } + }) + .collect() +} + +/// Loudness stands for energy: a drop's sustained bass masks its kick's onsets, and a riser's noise +/// fills the spectrum as fully as a drop does. The range is taken between percentiles, so a silent +/// tail or one clipped bar doesn't squash every other bar together. +fn bar_energies(features: &BarFeatures) -> Vec { + let mut sorted = features.loudness.clone(); + sorted.sort_by(f64::total_cmp); + let at = |share: f64| sorted[((sorted.len() - 1) as f64 * share).round() as usize]; + let (quiet, loud) = (at(QUIET_PERCENTILE), at(LOUD_PERCENTILE)); + if loud - quiet < FLAT_SPREAD { + return vec![1.0; sorted.len()]; + } + features.loudness.iter().map(|level| ((level - quiet) / (loud - quiet)).clamp(0.0, 1.0)).collect() +} + +fn rises(energies: &[f64]) -> bool { + let half = energies.len() / 2; + half > 0 && mean(&energies[half..]) - mean(&energies[..half]) > MIN_BUILD_RISE +} + +fn loudness(bands: &[f64; BANDS]) -> f64 { + bands.iter().map(|log_energy| 10f64.powf(*log_energy)).sum::().log10() +} + +fn mean(values: &[f64]) -> f64 { + if values.is_empty() { + return 0.0; + } + values.iter().sum::() / values.len() as f64 +} + +fn mean_rows(rows: &[[f64; N]]) -> [f64; N] { + let mut sum = [0.0; N]; + for row in rows { + for (total, value) in sum.iter_mut().zip(row) { + *total += value; + } + } + sum.map(|total| total / rows.len().max(1) as f64) +} + +fn unit(values: [f64; N]) -> [f64; N] { + let norm = values.iter().map(|v| v * v).sum::().sqrt(); + if norm > 0.0 { + values.map(|v| v / norm) + } else { + values + } +} + +fn standardise(values: &[f64]) -> Vec { + let average = mean(values); + let spread = (values.iter().map(|v| (v - average).powi(2)).sum::() / values.len().max(1) as f64).sqrt(); + if spread < FLAT_SPREAD { + return vec![0.0; values.len()]; + } + values.iter().map(|v| (v - average) / spread).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::f64::consts::TAU; + + const RATE: f64 = 44_100.0; + const BPM: f64 = 128.0; + + #[derive(Clone, Copy)] + struct Part { + bars: usize, + kick: bool, + bass: bool, + hats: bool, + pad: bool, + riser: bool, + } + + const SILENT: Part = Part { bars: 0, kick: false, bass: false, hats: false, pad: false, riser: false }; + + fn render(parts: &[Part]) -> (Vec, Vec) { + let beat_seconds = 60.0 / BPM; + let mut audio = Vec::new(); + let mut beats = Vec::new(); + let mut noise = 7u32; + let mut beat_count = 0usize; + for part in parts { + let samples = (part.bars as f64 * 4.0 * beat_seconds * RATE) as usize; + for i in 0..samples { + let t = i as f64 / RATE; + let progress = i as f64 / samples as f64; + let since_beat = t % beat_seconds; + let off_beat = (t + beat_seconds / 2.0) % beat_seconds; + noise = noise.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let white = f64::from(noise >> 9) / f64::from(1u32 << 23) - 1.0; + let mut v = 0.0; + if part.kick { + v += 0.8 * (-since_beat * 18.0).exp() * (TAU * 55.0 * since_beat).sin(); + } + if part.bass { + v += 0.3 * (TAU * 41.2 * t).sin(); + } + if part.hats { + v += 0.15 * (-off_beat * 60.0).exp() * white; + } + if part.pad { + v += 0.06 * [261.63, 311.13, 392.0].iter().map(|hz| (TAU * hz * t).sin()).sum::(); + } + if part.riser { + v += 0.3 * progress * white; + } + audio.push(v as f32); + } + for _ in 0..part.bars * 4 { + let time_ms = (beat_count as f64 * beat_seconds * 1000.0).round() as u32; + beats.push(Beat { number: (beat_count % 4) as u8 + 1, tempo_x100: 12_800, time_ms }); + beat_count += 1; + } + } + (audio, beats) + } + + #[test] + fn finds_and_names_the_sections_of_a_dance_track() { + let intro = Part { bars: 16, kick: true, hats: true, ..SILENT }; + let drop = Part { bars: 16, kick: true, bass: true, hats: true, pad: true, ..SILENT }; + let breakdown = Part { bars: 16, pad: true, ..SILENT }; + let build = Part { bars: 8, pad: true, riser: true, ..SILENT }; + let outro = Part { bars: 16, kick: true, ..SILENT }; + let (audio, beats) = render(&[intro, drop, breakdown, build, drop, outro]); + + let sections = segment(&BarFeatures::measure(&audio, RATE, &beats), &Tuning::default()); + + let found: Vec<(BarIndex, SectionKind)> = sections.iter().map(|s| (s.first_bar, s.kind)).collect(); + assert_eq!( + found, + [ + (0, SectionKind::Intro), + (16, SectionKind::Drop), + (32, SectionKind::Breakdown), + (48, SectionKind::Build), + (56, SectionKind::Drop), + (72, SectionKind::Outro), + ] + ); + assert_eq!(sections[1].first_beat, 64); + } + + #[test] + fn a_grid_without_bars_has_no_sections() { + assert!(segment(&BarFeatures::measure(&[0.0; 4410], RATE, &[]), &Tuning::default()).is_empty()); + } +} diff --git a/native/crates/es-index/examples/cue_survey.rs b/native/crates/es-index/examples/cue_survey.rs index 8b2e193..0bb65bb 100644 --- a/native/crates/es-index/examples/cue_survey.rs +++ b/native/crates/es-index/examples/cue_survey.rs @@ -125,6 +125,7 @@ fn to_json(surveyed: &SurveyedTrack) -> serde_json::Value { "title": track.title, "artist": track.artist, "genre": track.genre, + "path": track.folder_path, "bpm": track.bpm_x100 as f64 / 100.0, "lengthSeconds": track.length, "grid": surveyed.grid.as_ref().map(|grid| json!({ "times": grid.times, "beats": grid.beats })), From 79af27cea7c9e8b92a6878f63d32d51e934e1585 Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 14:54:59 +0000 Subject: [PATCH 05/25] Save our sections as rekordbox phrases during analysis Track analysis now finds the sections too, and the engine writes them into the .EXT as a PSSI tag in rekordbox's high mood (intro, up, chorus, down, outro) when they fit the grid the track ends up with and the track has no phrases, or overwrite is asked for, or the grid is rewritten. Sections found on a grid the engine discards are never written. analyseTrack can be handed the grid a track keeps, which finds the sections on it instead of detecting a new grid. A "Detect phrases" analysis setting, on by default, turns this off. Bumps es-rekordbox-sdk for the PSSI writer. Co-Authored-By: Claude Opus 5.5 --- app/src/main/analysis.ts | 2 + app/src/main/audio/native.ts | 11 +++ app/src/preload/analysis.d.ts | 2 + app/src/preload/engine.ts | 1 + app/src/renderer/src/lib/analysis.svelte.ts | 3 + .../src/lib/components/AnalysisDialog.svelte | 21 +++++- .../settings/AnalysisSettings.svelte | 8 +- es-rekordbox-sdk | 2 +- native/Cargo.lock | 1 + .../es-analyse/examples/structure_eval.rs | 27 ++----- native/crates/es-analyse/src/lib.rs | 42 ++++++++++- native/crates/es-analyse/src/structure.rs | 18 +++++ native/crates/es-engine/Cargo.toml | 1 + native/crates/es-engine/src/analysis.rs | 74 ++++++++++++++++++- native/crates/es-engine/tests/analysis.rs | 51 ++++++++++++- native/crates/es-engine/tests/convert.rs | 1 + native/crates/es-node/src/lib.rs | 40 +++++++++- native/crates/es-node/src/library.rs | 18 +++++ 18 files changed, 288 insertions(+), 35 deletions(-) diff --git a/app/src/main/analysis.ts b/app/src/main/analysis.ts index 5d2018d..2b4f211 100644 --- a/app/src/main/analysis.ts +++ b/app/src/main/analysis.ts @@ -80,6 +80,7 @@ export class AnalysisQueue { const result = await native.analyseTrack(path, { grid: options.grid, key: options.key, + sections: options.phrases, dynamic: options.gridMode === 'dynamic', minBpm: options.minBpm, maxBpm: options.maxBpm, @@ -95,6 +96,7 @@ export class AnalysisQueue { bpm: result.bpm, beats, key: result.key ?? null, + sections: result.sections, waveform: waveform.toString('base64') }, options: { grid: options.grid, key: options.key, overwrite: options.overwrite } diff --git a/app/src/main/audio/native.ts b/app/src/main/audio/native.ts index 2d8d60d..5f9f84f 100644 --- a/app/src/main/audio/native.ts +++ b/app/src/main/audio/native.ts @@ -67,9 +67,18 @@ export interface NativeEngine { close(): void } +export interface NativeGrid { + times: number[] + beats: number[] + bpms: number[] +} + export interface NativeTrackAnalysisOptions { grid: boolean key: boolean + sections: boolean + /** Sections are found on this grid, and no new grid is detected. */ + keptGrid?: NativeGrid | null dynamic: boolean minBpm: number maxBpm: number @@ -89,6 +98,8 @@ export interface NativeTrackAnalysis { key?: { tonic: number; minor: boolean } | null /** Eight bytes per 1/150 s: peak and RMS of the whole signal, then the low, mid and high bands. */ waveform: Uint8Array + /** `firstBeat` indexes the kept grid when one was given, otherwise the beats above. */ + sections: { firstBeat: number; kind: string }[] } export interface NativeLibrary { diff --git a/app/src/preload/analysis.d.ts b/app/src/preload/analysis.d.ts index d25ca0d..f9704f8 100644 --- a/app/src/preload/analysis.d.ts +++ b/app/src/preload/analysis.d.ts @@ -7,6 +7,8 @@ export interface AnalysisOptions { grid: boolean /** Detect the musical key. */ key: boolean + /** Find the track's sections and save them as rekordbox phrases. */ + phrases: boolean gridMode: GridMode minBpm: number maxBpm: number diff --git a/app/src/preload/engine.ts b/app/src/preload/engine.ts index 4c3c86b..e01926c 100644 --- a/app/src/preload/engine.ts +++ b/app/src/preload/engine.ts @@ -162,6 +162,7 @@ export interface EngineCommandParams { beats?: number[][] waveform: string key?: { tonic: number; minor: boolean } | null + sections?: { firstBeat: number; kind: string }[] bpm?: number duration?: number } diff --git a/app/src/renderer/src/lib/analysis.svelte.ts b/app/src/renderer/src/lib/analysis.svelte.ts index e87bcd0..8515fed 100644 --- a/app/src/renderer/src/lib/analysis.svelte.ts +++ b/app/src/renderer/src/lib/analysis.svelte.ts @@ -25,6 +25,7 @@ export interface AnalysisSettings { highPrecision: boolean roundBpm: boolean key: boolean + phrases: boolean concurrency: number } @@ -38,6 +39,7 @@ export const DEFAULT_ANALYSIS_SETTINGS: Readonly = { highPrecision: true, roundBpm: true, key: true, + phrases: true, concurrency: 3 } const SETTING_KEYS = Object.keys(DEFAULT_ANALYSIS_SETTINGS) as (keyof AnalysisSettings)[] @@ -119,6 +121,7 @@ export class Analysis { return { grid: true, key: s.key, + phrases: s.phrases, gridMode: s.gridMode, minBpm: s.minBpm, maxBpm: s.maxBpm, diff --git a/app/src/renderer/src/lib/components/AnalysisDialog.svelte b/app/src/renderer/src/lib/components/AnalysisDialog.svelte index e0c6e6a..f9ae144 100644 --- a/app/src/renderer/src/lib/components/AnalysisDialog.svelte +++ b/app/src/renderer/src/lib/components/AnalysisDialog.svelte @@ -76,7 +76,11 @@ Normal fits one tempo to the track. Dynamic follows tempo changes. -
+
{#each GRID_MODES as mode (mode.id)} -{/snippet} \ No newline at end of file +{/snippet} diff --git a/app/src/renderer/src/lib/components/settings/AnalysisSettings.svelte b/app/src/renderer/src/lib/components/settings/AnalysisSettings.svelte index da750d6..b017850 100644 --- a/app/src/renderer/src/lib/components/settings/AnalysisSettings.svelte +++ b/app/src/renderer/src/lib/components/settings/AnalysisSettings.svelte @@ -44,7 +44,7 @@ analysis.set('auto', !s.auto)} /> @@ -92,6 +92,12 @@ on={s.key} onflip={() => analysis.set('key', !s.key)} /> + analysis.set('phrases', !s.phrases)} + /> Option { } } -const KINDS: [SectionKind; 5] = - [SectionKind::Intro, SectionKind::Build, SectionKind::Drop, SectionKind::Breakdown, SectionKind::Outro]; - /// Share of bars whose section kind matches rekordbox's, and the counts behind it, ours by theirs. fn label_agreement(tracks: &[Track], tuning: &Tuning) -> (f64, [[usize; 5]; 5]) { let mut counts = [[0usize; 5]; 5]; for track in tracks { let Some(theirs) = &track.rekordbox_bar_kinds else { continue }; for section in segment(&track.features, tuning) { - let ours = KINDS.iter().position(|&k| k == section.kind).unwrap_or(0); + let ours = SectionKind::ALL.iter().position(|&k| k == section.kind).unwrap_or(0); for bar in section.first_bar..section.first_bar + section.bars { if let Some(Some(kind)) = theirs.get(bar) { - counts[ours][KINDS.iter().position(|k| k == kind).unwrap_or(0)] += 1; + counts[ours][SectionKind::ALL.iter().position(|k| k == kind).unwrap_or(0)] += 1; } } } @@ -190,9 +187,9 @@ fn report_labels(tracks: &[Track], best: &Tuning) -> Tuning { } } let (_, counts) = label_agreement(tracks, &chosen); - println!(" ours \\ theirs {}", KINDS.iter().map(|&k| format!("{:>9}", kind_name(k))).collect::()); - for (ours, row) in KINDS.iter().zip(counts) { - println!(" {:<14} {}", kind_name(*ours), row.iter().map(|n| format!("{n:>9}")).collect::()); + println!(" ours \\ theirs {}", SectionKind::ALL.iter().map(|&k| format!("{:>9}", k.name())).collect::()); + for (ours, row) in SectionKind::ALL.iter().zip(counts) { + println!(" {:<14} {}", ours.name(), row.iter().map(|n| format!("{n:>9}")).collect::()); } chosen } @@ -291,7 +288,7 @@ fn report_kinds(tracks: &[Track], tuning: &Tuning) { let sections = segment(&track.features, tuning); let mut seen: BTreeMap = BTreeMap::new(); for section in §ions { - let kind = kind_name(section.kind); + let kind = section.kind.name(); let occurrence = seen.entry(kind.to_owned()).and_modify(|n| *n += 1).or_insert(1); let anchor = format!("{kind}#{occurrence}"); *everywhere.entry(anchor.clone()).or_default() += 1; @@ -315,7 +312,7 @@ fn report_kinds(tracks: &[Track], tuning: &Tuning) { " bar {:>4} {:>3} bars {:<9} energy {:.2} {cued}", section.first_bar, section.bars, - kind_name(section.kind), + section.kind.name(), section.relative_energy ); } @@ -325,13 +322,3 @@ fn report_kinds(tracks: &[Track], tuning: &Tuning) { println!(" cues on no section start: bars {missed:?}"); } } - -fn kind_name(kind: SectionKind) -> &'static str { - match kind { - SectionKind::Intro => "Intro", - SectionKind::Build => "Build", - SectionKind::Drop => "Drop", - SectionKind::Breakdown => "Breakdown", - SectionKind::Outro => "Outro", - } -} diff --git a/native/crates/es-analyse/src/lib.rs b/native/crates/es-analyse/src/lib.rs index 62e2d3b..a5a50ea 100644 --- a/native/crates/es-analyse/src/lib.rs +++ b/native/crates/es-analyse/src/lib.rs @@ -25,16 +25,19 @@ const ONSET_HOP: usize = 256; const KICK_HZ: (f64, f64) = (30.0, 150.0); const ONSET_HZ: (f64, f64) = (30.0, 16_000.0); -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone)] pub struct Options { pub tempo: TempoOptions, pub grid: bool, pub key: bool, + pub sections: bool, + /// Sections are found on this grid, and no new grid is detected. + pub kept_grid: Option>, } impl Default for Options { fn default() -> Self { - Self { tempo: TempoOptions::default(), grid: true, key: true } + Self { tempo: TempoOptions::default(), grid: true, key: true, sections: true, kept_grid: None } } } @@ -55,6 +58,8 @@ pub struct Analysis { pub key: Option, /// [`waveform::LANES`] bytes per entry at [`waveform::RATE`] entries per second. pub waveform: Vec, + /// On the kept grid when there is one, otherwise on `beats`. + pub sections: Vec, } /// Decodes `path` through the deck's decoder at [`SAMPLE_RATE`], mixed to mono. @@ -82,12 +87,27 @@ pub fn analyse_file(path: &Path, options: &Options) -> Result Analysis { let duration = mono.len() as f64 / sample_rate; + let detect_grid = options.grid && options.kept_grid.is_none(); let (grid, key) = rayon::join( - || options.grid.then(|| beatgrid(mono, sample_rate, duration, &options.tempo)).flatten(), + || detect_grid.then(|| beatgrid(mono, sample_rate, duration, &options.tempo)).flatten(), || options.key.then(|| key::analyse(mono, sample_rate)).flatten(), ); let (bpm, beats) = grid.unwrap_or_default(); - Analysis { duration, bpm, beats, key, waveform: waveform::features(mono, sample_rate) } + let section_grid = options.kept_grid.as_deref().unwrap_or(&beats); + let (waveform, sections) = rayon::join( + || waveform::features(mono, sample_rate), + || { + let wanted = options.sections && !section_grid.is_empty(); + let found = wanted.then(|| { + structure::segment( + &structure::BarFeatures::measure(mono, sample_rate, section_grid), + &structure::Tuning::default(), + ) + }); + found.unwrap_or_default() + }, + ); + Analysis { duration, bpm, beats, key, waveform, sections } } fn beatgrid(mono: &[f32], sample_rate: f64, duration: f64, opts: &TempoOptions) -> Option<(f64, Vec)> { @@ -190,6 +210,20 @@ mod tests { assert!((f64::from(change.time_ms) / 1000.0 - 48.0).abs() < 8.0, "changes at {}", change.time_ms); } + #[test] + fn sections_follow_a_kept_grid_instead_of_a_detected_one() { + let audio = track(128.0, 60.0, 0.0, &[220.0]); + let first_downbeat = |beats: &[Beat]| beats.iter().position(|beat| beat.number == 1); + let detected = analyse_samples(&audio, RATE, &Options::default()); + assert_eq!(detected.sections.first().map(|s| s.first_beat), first_downbeat(&detected.beats)); + + let kept_grid: Vec = detected.beats[2..].to_vec(); + let options = Options { kept_grid: Some(kept_grid.clone()), ..Options::default() }; + let kept = analyse_samples(&audio, RATE, &options); + assert!(kept.beats.is_empty()); + assert_eq!(kept.sections.first().map(|s| s.first_beat), first_downbeat(&kept_grid)); + } + #[test] fn beat_numbers() { assert_eq!(downbeat::numbers(6, 0), vec![1, 2, 3, 4, 1, 2]); diff --git a/native/crates/es-analyse/src/structure.rs b/native/crates/es-analyse/src/structure.rs index cd16583..417c804 100644 --- a/native/crates/es-analyse/src/structure.rs +++ b/native/crates/es-analyse/src/structure.rs @@ -31,6 +31,24 @@ pub enum SectionKind { Outro, } +impl SectionKind { + pub const ALL: [Self; 5] = [Self::Intro, Self::Build, Self::Drop, Self::Breakdown, Self::Outro]; + + pub fn name(self) -> &'static str { + match self { + Self::Intro => "intro", + Self::Build => "build", + Self::Drop => "drop", + Self::Breakdown => "breakdown", + Self::Outro => "outro", + } + } + + pub fn from_name(name: &str) -> Option { + Self::ALL.into_iter().find(|kind| kind.name() == name) + } +} + #[derive(Debug, Clone, PartialEq)] pub struct Section { pub first_beat: BeatIndex, diff --git a/native/crates/es-engine/Cargo.toml b/native/crates/es-engine/Cargo.toml index eaf67d2..1a2552c 100644 --- a/native/crates/es-engine/Cargo.toml +++ b/native/crates/es-engine/Cargo.toml @@ -10,6 +10,7 @@ rb-library.workspace = true es-backup.workspace = true es-convert.workspace = true es-index.workspace = true +es-analyse.workspace = true es-tags.workspace = true rb-device.workspace = true rb-anlz.workspace = true diff --git a/native/crates/es-engine/src/analysis.rs b/native/crates/es-engine/src/analysis.rs index 1a5672a..38cde34 100644 --- a/native/crates/es-engine/src/analysis.rs +++ b/native/crates/es-engine/src/analysis.rs @@ -2,8 +2,10 @@ use std::path::{Path, PathBuf}; +use es_analyse::structure::SectionKind; use rb_anlz::build::{self, Beat}; use rb_anlz::decode::{self, Tags}; +use rb_anlz::phrase::{self, Mood, Phrase, PhraseKind, SongStructure}; use rb_anlz::write::{build_beatgrid, clear_extended_beatgrid, patch_tags}; use rb_library::{AnalysisWrite, CueMove, Library}; @@ -122,10 +124,19 @@ pub fn set_beatgrid(lib: &mut Library, share: &Path, id: &str, grid: &Grid, move Ok(constant) } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SectionStart { + /// Index into the grid the sections were found on: `beats` when it isn't empty, otherwise the + /// grid the track keeps. + pub first_beat: usize, + pub kind: SectionKind, +} + /// What the native analyser found for a track. #[derive(Debug, Clone, Default)] pub struct Analysis { pub beats: Vec, + pub sections: Vec, /// Eight bytes per 1/150 s: peak and RMS of the whole signal and of the low, mid and high bands. pub waveform: Vec, pub key: Option<(i64, bool)>, @@ -141,8 +152,40 @@ pub struct Options { pub key: bool, } +fn phrase_kind(kind: SectionKind) -> PhraseKind { + match kind { + SectionKind::Intro => PhraseKind::Intro, + SectionKind::Build => PhraseKind::Up, + SectionKind::Drop => PhraseKind::Chorus, + SectionKind::Breakdown => PhraseKind::Down, + SectionKind::Outro => PhraseKind::Outro, + } +} + +/// The sections as rekordbox's phrases, in the high mood whose names fit dance music. +fn phrase_tag(sections: &[SectionStart], beat_count: usize) -> Vec { + let beat_number = |index: usize| u16::try_from(index + 1).unwrap_or(u16::MAX); + let phrases = sections + .iter() + .filter(|section| section.first_beat < beat_count) + .map(|section| Phrase { + first_beat: beat_number(section.first_beat), + kind: Some(phrase_kind(section.kind)), + variant: None, + fill_in_beat: None, + }) + .collect(); + phrase::song_structure_tag(&SongStructure { + mood: Mood::High, + end_beat: u16::try_from(beat_count).unwrap_or(u16::MAX), + phrases, + }) +} + /// Write an analysis: the analysis files, tempo, key and the analysed flag. Cues already in the files are -/// kept; phrases go when the grid they were counted on changes. +/// kept. Phrases are written from the sections when they fit the grid the track ends up with and +/// the track has none (or overwrite is asked for, or the grid changes); otherwise they go when the +/// grid they were counted on changes. pub fn apply_analysis(lib: &mut Library, share: &Path, id: &str, result: &Analysis, options: Options) -> Result<()> { let files = lib.track_files(id)?.ok_or_else(|| Error::Other(format!("Unknown track {id}")))?; let features = build::features_from_bytes(&result.waveform); @@ -169,8 +212,19 @@ pub fn apply_analysis(lib: &mut Library, share: &Path, id: &str, result: &Analys Err(_) => Ok(None), }) .collect::>()?; - let has_grid = existing[0].as_ref().and_then(|(_, t)| decode::beatgrid(t)).is_some_and(|g| !g.times.is_empty()); + let kept_beat_count = existing[0].as_ref().and_then(|(_, t)| decode::beatgrid(t)).map_or(0, |g| g.times.len()); + let has_grid = kept_beat_count > 0; let write_grid = options.grid && !result.beats.is_empty() && (options.overwrite || !has_grid); + let final_beat_count = if write_grid { result.beats.len() } else { kept_beat_count }; + let sections_fit_final_grid = write_grid || result.beats.is_empty(); + let has_phrases = kinds.iter().zip(&existing).any(|((kind, _, _), file)| { + *kind == "EXT" && file.as_ref().is_some_and(|(_, t)| t.first(rb_anlz::PHRASE_TAG).is_some()) + }); + let phrases = (sections_fit_final_grid + && !result.sections.is_empty() + && final_beat_count > 0 + && (write_grid || options.overwrite || !has_phrases)) + .then(|| phrase_tag(&result.sections, final_beat_count)); let fresh = build::new_files(&audio_name, if write_grid { &result.beats } else { &[] }, &features); let waves = if features.is_empty() { Vec::new() } else { build::wave_tags(&features) }; @@ -178,7 +232,13 @@ pub fn apply_analysis(lib: &mut Library, share: &Path, id: &str, result: &Analys for (index, (kind, wave_kinds, path)) in kinds.iter().enumerate() { let Some((bytes, tags)) = &existing[index] else { if let Some((_, data)) = fresh.iter().find(|(k, _)| k == kind) { - writes.push((path.clone(), data.clone())); + let data = match (&phrases, *kind) { + (Some(tag), "EXT") => { + patch_tags(data, &[(rb_anlz::PHRASE_TAG, tag.clone())], &[]).map_err(other)? + } + _ => data.clone(), + }; + writes.push((path.clone(), data)); } continue; }; @@ -195,7 +255,13 @@ pub fn apply_analysis(lib: &mut Library, share: &Path, id: &str, result: &Analys if let Some(pqt2) = tags.first("PQT2") { replace.push(("PQT2", clear_extended_beatgrid(pqt2))); } - drop.push(rb_anlz::PHRASE_TAG); + } + if *kind == "EXT" { + match &phrases { + Some(tag) => replace.push((rb_anlz::PHRASE_TAG, tag.clone())), + None if write_grid => drop.push(rb_anlz::PHRASE_TAG), + None => {} + } } if !replace.is_empty() || !drop.is_empty() { writes.push((path.clone(), patch_tags(bytes, &replace, &drop).map_err(other)?)); diff --git a/native/crates/es-engine/tests/analysis.rs b/native/crates/es-engine/tests/analysis.rs index 94f6e29..0c405a6 100644 --- a/native/crates/es-engine/tests/analysis.rs +++ b/native/crates/es-engine/tests/analysis.rs @@ -1,6 +1,7 @@ use std::path::Path; -use es_engine::analysis::{apply_analysis, set_beatgrid, Analysis, Grid, Options}; +use es_analyse::structure::SectionKind; +use es_engine::analysis::{apply_analysis, set_beatgrid, Analysis, Grid, Options, SectionStart}; use es_engine::import::{import_files, Options as ImportOptions}; use rb_anlz::decode::{self, Tags}; use rb_library::fixture; @@ -44,6 +45,7 @@ fn scene() -> (tempfile::TempDir, Library, String) { fn analysis() -> Analysis { Analysis { beats: vec![(1, 12800, 0), (2, 12800, 469), (3, 12800, 938), (4, 12800, 1406)], + sections: Vec::new(), waveform: (0..8 * 300).map(|i| (i * 7 % 251) as u8).collect(), key: Some((9, true)), bpm: 128.0, @@ -84,6 +86,53 @@ fn an_existing_grid_survives_unless_overwrite_is_asked_for() { assert_eq!(lib.tracks(Some(std::slice::from_ref(&id))).unwrap().remove(0).bpm_x100, 9000); } +fn sections(kinds: &[(usize, SectionKind)]) -> Vec { + kinds.iter().map(|&(first_beat, kind)| SectionStart { first_beat, kind }).collect() +} + +fn phrases(lib: &Library, share: &Path, id: &str) -> Option> { + let relative = lib.track_files(id).unwrap().unwrap().analysis_path.unwrap(); + let ext = Tags::read(&rb_anlz::file(share, &relative, "EXT").unwrap()).unwrap(); + let structure = rb_anlz::phrase::song_structure(&ext)?; + Some(structure.phrases.iter().map(|phrase| (phrase.first_beat, phrase.to_string())).collect()) +} + +#[test] +fn sections_are_written_as_rekordbox_phrases() { + let (_dir, mut lib, id) = scene(); + let share = lib.share_dir(); + let analysed = Analysis { sections: sections(&[(0, SectionKind::Intro), (2, SectionKind::Drop)]), ..analysis() }; + apply_analysis(&mut lib, &share, &id, &analysed, ALL).unwrap(); + assert_eq!(phrases(&lib, &share, &id), Some(vec![(1, "INTRO 1".into()), (3, "CHORUS 1".into())])); +} + +#[test] +fn phrases_already_there_stay_unless_overwrite_is_asked_for() { + let (_dir, mut lib, id) = scene(); + let share = lib.share_dir(); + let first = Analysis { sections: sections(&[(0, SectionKind::Intro)]), ..analysis() }; + apply_analysis(&mut lib, &share, &id, &first, ALL).unwrap(); + let on_kept_grid = Analysis { + beats: Vec::new(), + sections: sections(&[(0, SectionKind::Build), (2, SectionKind::Breakdown)]), + ..analysis() + }; + apply_analysis(&mut lib, &share, &id, &on_kept_grid, ALL).unwrap(); + assert_eq!(phrases(&lib, &share, &id), Some(vec![(1, "INTRO 1".into())])); + apply_analysis(&mut lib, &share, &id, &on_kept_grid, Options { overwrite: true, ..ALL }).unwrap(); + assert_eq!(phrases(&lib, &share, &id), Some(vec![(1, "UP 1".into()), (3, "DOWN".into())])); +} + +#[test] +fn sections_found_on_a_grid_that_is_not_kept_are_not_written() { + let (_dir, mut lib, id) = scene(); + let share = lib.share_dir(); + apply_analysis(&mut lib, &share, &id, &analysis(), ALL).unwrap(); + let on_new_grid = Analysis { sections: sections(&[(0, SectionKind::Outro)]), ..analysis() }; + apply_analysis(&mut lib, &share, &id, &on_new_grid, ALL).unwrap(); + assert_eq!(phrases(&lib, &share, &id), None); +} + #[test] fn a_hand_edited_grid_is_written_and_moves_cues() { let (_dir, mut lib, id) = scene(); diff --git a/native/crates/es-engine/tests/convert.rs b/native/crates/es-engine/tests/convert.rs index 29cb72e..b2de68d 100644 --- a/native/crates/es-engine/tests/convert.rs +++ b/native/crates/es-engine/tests/convert.rs @@ -85,6 +85,7 @@ fn a_delay_moves_the_grid_and_the_detail_waveforms() { key: None, bpm: 128.0, duration: 1.0, + ..Analysis::default() }; apply_analysis(&mut lib, &share, &id, &analysis, AnalysisOptions { overwrite: true, grid: true, key: false }) .unwrap(); diff --git a/native/crates/es-node/src/lib.rs b/native/crates/es-node/src/lib.rs index 47accc6..dcfec80 100644 --- a/native/crates/es-node/src/lib.rs +++ b/native/crates/es-node/src/lib.rs @@ -376,15 +376,31 @@ pub fn analyse(path: String, bands: bool, quality: u32) -> AsyncTask { AsyncTask::new(Analyse { path, bands, quality }) } +#[napi(object)] +pub struct GridJs { + pub times: Vec, + pub beats: Vec, + pub bpms: Vec, +} + #[napi(object)] pub struct TrackAnalysisOptionsJs { pub grid: bool, pub key: bool, + pub sections: bool, pub dynamic: bool, pub min_bpm: f64, pub max_bpm: f64, pub high_precision: bool, pub round_bpm: bool, + pub kept_grid: Option, +} + +#[napi(object)] +pub struct SectionJs { + /// Index into the grid the sections were found on. + pub first_beat: u32, + pub kind: String, } #[napi(object)] @@ -406,6 +422,7 @@ pub struct TrackAnalysisJs { pub key: Option, /// Eight bytes per 1/150 s: peak and RMS of the whole signal, then the low, mid and high bands. pub waveform: Uint8Array, + pub sections: Vec, } pub struct AnalyseTrack { @@ -431,11 +448,19 @@ impl Task for AnalyseTrack { beat_times: Uint32Array::new(a.beats.iter().map(|b| b.time_ms).collect()), key: a.key.map(|k| KeyJs { tonic: k.tonic as u32, minor: k.minor }), waveform: Uint8Array::new(a.waveform), + sections: a + .sections + .iter() + .map(|section| SectionJs { + first_beat: u32::try_from(section.first_beat).unwrap_or(u32::MAX), + kind: section.kind.name().to_owned(), + }) + .collect(), }) } } -/// Beatgrid, tempo, key and waveform loudness for a file, worked out off the main thread. +/// Beatgrid, tempo, key, sections and waveform loudness for a file, worked out off the main thread. #[napi(ts_return_type = "Promise")] pub fn analyse_track(path: String, options: TrackAnalysisOptionsJs) -> AsyncTask { AsyncTask::new(AnalyseTrack { @@ -443,6 +468,19 @@ pub fn analyse_track(path: String, options: TrackAnalysisOptionsJs) -> AsyncTask options: es_analyse::Options { grid: options.grid, key: options.key, + sections: options.sections, + kept_grid: options.kept_grid.map(|grid| { + grid.times + .iter() + .zip(&grid.beats) + .zip(&grid.bpms) + .map(|((&time_ms, &number), &bpm)| es_analyse::Beat { + number: u8::try_from(number).unwrap_or(0), + tempo_x100: (bpm * 100.0).round().clamp(0.0, f64::from(u16::MAX)) as u16, + time_ms, + }) + .collect() + }), tempo: es_analyse::TempoOptions { min_bpm: options.min_bpm, max_bpm: options.max_bpm.max(options.min_bpm + 1.0), diff --git a/native/crates/es-node/src/library.rs b/native/crates/es-node/src/library.rs index 9d832b0..0218c78 100644 --- a/native/crates/es-node/src/library.rs +++ b/native/crates/es-node/src/library.rs @@ -455,8 +455,26 @@ impl Run { value.get("minor").and_then(Value::as_bool).unwrap_or(false), ) }); + let sections = result + .get("sections") + .and_then(Value::as_array) + .map(|values| { + values + .iter() + .filter_map(|section| { + Some(es_engine::analysis::SectionStart { + first_beat: usize::try_from(section.get("firstBeat")?.as_u64()?).ok()?, + kind: es_analyse::structure::SectionKind::from_name( + section.get("kind")?.as_str()?, + )?, + }) + }) + .collect() + }) + .unwrap_or_default(); let analysis = es_engine::analysis::Analysis { beats, + sections, waveform, key, bpm: result.get("bpm").and_then(Value::as_f64).unwrap_or(0.0), From 0cd545a10e71f5c0ff26a17854e76675d2729910 Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 15:39:46 +0000 Subject: [PATCH 06/25] Show a track's phrases on the deck overview, as a developer option Track detail now carries the phrases in the analysis file, ours or rekordbox's. With "Show phrases" on in developer options, both deck modes draw them as a coloured strip along the top of the overview. Co-Authored-By: Claude Opus 5.5 --- .../lib/components/WaveformOverview.svelte | 14 ++++++++- .../settings/DeveloperSettings.svelte | 6 ++++ app/src/renderer/src/lib/deck/prefs.svelte.ts | 13 ++++++-- app/src/renderer/src/lib/deck/sections.ts | 17 +++++++++- .../renderer/src/lib/deck/session.svelte.ts | 1 + app/src/renderer/src/lib/player.svelte.ts | 6 ++++ app/src/renderer/src/lib/types.ts | 8 +++++ app/src/renderer/src/lib/waveform/colors.ts | 12 +++++++ app/tests/sections.test.ts | 21 ++++++++++++- native/crates/es-index/src/detail.rs | 31 +++++++++++++++---- native/crates/es-index/src/device.rs | 7 ++--- 11 files changed, 120 insertions(+), 16 deletions(-) diff --git a/app/src/renderer/src/lib/components/WaveformOverview.svelte b/app/src/renderer/src/lib/components/WaveformOverview.svelte index 32133ed..9f6dced 100644 --- a/app/src/renderer/src/lib/components/WaveformOverview.svelte +++ b/app/src/renderer/src/lib/components/WaveformOverview.svelte @@ -3,7 +3,7 @@ import { cueSections, formatBars, type CueSection } from '$lib/deck/sections' import { formatClock } from '$lib/format' import { setupCanvas } from '$lib/waveform/canvas' - import { CUE_POINT_COLOR } from '$lib/waveform/colors' + import { CUE_POINT_COLOR, PHRASE_COLORS, UNKNOWN_PHRASE_COLOR } from '$lib/waveform/colors' import { drawOverview } from '$lib/waveform/overview' import WaveformMarks from './WaveformMarks.svelte' @@ -32,6 +32,7 @@ : [] ) const bandWidth = (band: { start: number; end: number }): number => ((pct(band.end) - pct(band.start)) / 100) * width + const phraseColor = (label: string): string => PHRASE_COLORS[label.split(' ')[0]] ?? UNKNOWN_PHRASE_COLOR /** Owns the hover line while a section is pointed at, apart from the waveform's own hover. */ const SECTION_PREVIEW = 'section' @@ -131,6 +132,17 @@ }} > + {#each player.phraseSections as phrase (phrase.start)} + + {#if bandWidth(phrase) >= LABEL_MIN_WIDTH}{phrase.label}{/if} + + {/each}
prefs.setUnlimitedMemoryCues(!prefs.unlimitedMemoryCues)} /> + prefs.setShowPhrases(!prefs.showPhrases)} + /> {@render heightScaleSlider('Player waveform', 'Height of the scrolling waveform on each deck.', 'detail')} {@render heightScaleSlider( diff --git a/app/src/renderer/src/lib/deck/prefs.svelte.ts b/app/src/renderer/src/lib/deck/prefs.svelte.ts index ab851c5..77b17ff 100644 --- a/app/src/renderer/src/lib/deck/prefs.svelte.ts +++ b/app/src/renderer/src/lib/deck/prefs.svelte.ts @@ -16,9 +16,12 @@ export const DEFAULT_DECK_PREFS = { export class DeckPrefs { quantise = $state(storedFlag('quantise', DEFAULT_DECK_PREFS.quantise)) loadAtFirstCue = $state(storedFlag('loadAtFirstCue', DEFAULT_DECK_PREFS.loadAtFirstCue)) - cuePlacement = $state(storedChoice('cuePlacement', ['playhead', 'cuePoint'], DEFAULT_DECK_PREFS.cuePlacement)) + cuePlacement = $state( + storedChoice('cuePlacement', ['playhead', 'cuePoint'], DEFAULT_DECK_PREFS.cuePlacement) + ) snapPlayhead = $state(storedFlag('snapPlayhead')) unlimitedMemoryCues = $state(storedFlag('unlimitedMemoryCues')) + showPhrases = $state(storedFlag('showPhrases')) tempoReadout = $state( storedChoice('tempoReadout', ['absolute', 'relative'], DEFAULT_DECK_PREFS.tempoReadout) ) @@ -44,13 +47,19 @@ export class DeckPrefs { storeFlag('unlimitedMemoryCues', on) } + setShowPhrases(on: boolean): void { + this.showPhrases = on + storeFlag('showPhrases', on) + } + get developerOptionsAreDefault(): boolean { - return !this.snapPlayhead && !this.unlimitedMemoryCues && this.waveform.heightScalesAreDefault + return !this.snapPlayhead && !this.unlimitedMemoryCues && !this.showPhrases && this.waveform.heightScalesAreDefault } resetDeveloperOptions(): void { this.setSnapPlayhead(false) this.setUnlimitedMemoryCues(false) + this.setShowPhrases(false) this.waveform.resetHeightScales() } diff --git a/app/src/renderer/src/lib/deck/sections.ts b/app/src/renderer/src/lib/deck/sections.ts index 2ae4641..e6aa700 100644 --- a/app/src/renderer/src/lib/deck/sections.ts +++ b/app/src/renderer/src/lib/deck/sections.ts @@ -1,5 +1,5 @@ import { BEATS_PER_BAR, fractionalBeatIndex } from '../beat' -import type { Beatgrid, Cue } from '../types' +import type { Beatgrid, Cue, Phrase } from '../types' /** Cues closer together than this mark the same place, e.g. a hot cue on a memory cue. */ const SAME_PLACE_SECONDS = 0.05 @@ -51,6 +51,21 @@ export function cueSections(cues: readonly Cue[], grid: Beatgrid | null, bpm: nu return sections } +/** A phrase's stretch of the track, in seconds. */ +export interface PhraseSection { + start: number + end: number + label: string +} + +/** The phrases placed on the grid they count beats of, each running to the next or to `trackEnd`. */ +export function phraseSections(phrases: readonly Phrase[], grid: Beatgrid | null, trackEnd: number): PhraseSection[] { + const placed = phrases + .map((phrase) => ({ start: (grid?.times[phrase.firstBeat - 1] ?? NaN) / 1000, label: phrase.label })) + .filter((phrase) => Number.isFinite(phrase.start)) + return placed.map((phrase, i) => ({ ...phrase, end: placed[i + 1]?.start ?? trackEnd })) +} + /** A bar count as a label: whole bars plainly, anything else to the nearest quarter. */ export function formatBars(bars: number): string { const whole = Math.round(bars) diff --git a/app/src/renderer/src/lib/deck/session.svelte.ts b/app/src/renderer/src/lib/deck/session.svelte.ts index 23da49d..a9bcdd3 100644 --- a/app/src/renderer/src/lib/deck/session.svelte.ts +++ b/app/src/renderer/src/lib/deck/session.svelte.ts @@ -44,6 +44,7 @@ export class TrackSession { id: track.id, cues: [], beatgrid: null, + phrases: [], waveform: { rate: 1, rgb: null, threeBand: null, threeBandPreview: null, mono: null } } this.loading = false diff --git a/app/src/renderer/src/lib/player.svelte.ts b/app/src/renderer/src/lib/player.svelte.ts index b440b71..c384313 100644 --- a/app/src/renderer/src/lib/player.svelte.ts +++ b/app/src/renderer/src/lib/player.svelte.ts @@ -7,6 +7,7 @@ import { GridEditor } from './deck/grid.svelte' import { TrackSession } from './deck/session.svelte' import { WaveformDisplay } from './deck/display.svelte' import type { CuePlacement, DeckPrefs } from './deck/prefs.svelte' +import { phraseSections, type PhraseSection } from './deck/sections' import { TempoControl } from './deck/tempo.svelte' import { Listeners } from './listeners' import { @@ -94,6 +95,11 @@ export class Player { return this.prefs.cuePlacement } + get phraseSections(): PhraseSection[] { + if (!this.prefs.showPhrases || !this.detail) return [] + return phraseSections(this.detail.phrases, this.displayGrid, this.duration) + } + get track(): Track | null { return this.session.track } diff --git a/app/src/renderer/src/lib/types.ts b/app/src/renderer/src/lib/types.ts index 0b334d7..96f0a2d 100644 --- a/app/src/renderer/src/lib/types.ts +++ b/app/src/renderer/src/lib/types.ts @@ -177,10 +177,18 @@ export interface TrackPreview { } | null } +export interface Phrase { + /** 1-based, counting the beats of the grid. */ + firstBeat: number + /** As rekordbox shows it, such as `CHORUS 1`. */ + label: string +} + export interface TrackDetail { id: string cues: Cue[] beatgrid: Beatgrid | null + phrases: Phrase[] waveform: WaveformPayload } diff --git a/app/src/renderer/src/lib/waveform/colors.ts b/app/src/renderer/src/lib/waveform/colors.ts index 450cb68..dbb168d 100644 --- a/app/src/renderer/src/lib/waveform/colors.ts +++ b/app/src/renderer/src/lib/waveform/colors.ts @@ -1,4 +1,16 @@ export const CUE_POINT_COLOR = '#ff8a1f' + +/** Keyed by the first word of a rekordbox phrase label, in rekordbox's own colours. */ +export const PHRASE_COLORS: Record = { + INTRO: '#e0464a', + VERSE: '#3d7cf0', + UP: '#9b5cf0', + DOWN: '#d69a2c', + BRIDGE: '#2cb5c8', + CHORUS: '#3fbf5a', + OUTRO: '#5a6ee0' +} +export const UNKNOWN_PHRASE_COLOR = '#888888' export const LOOP_ACTIVE_COLOR = '#ffb020' export const TEMPO_FLAG_COLOR = '#b48cff' diff --git a/app/tests/sections.test.ts b/app/tests/sections.test.ts index 5936dff..a220c5e 100644 --- a/app/tests/sections.test.ts +++ b/app/tests/sections.test.ts @@ -4,9 +4,11 @@ import { describe, it } from 'node:test' register(new URL('./resolve-ts.mjs', import.meta.url).href) -const { barsBetween, cueSections, formatBars } = await import('../src/renderer/src/lib/deck/sections.ts') +const { barsBetween, cueSections, formatBars, phraseSections } = + await import('../src/renderer/src/lib/deck/sections.ts') type Beatgrid = import('../src/renderer/src/lib/types.ts').Beatgrid type Cue = import('../src/renderer/src/lib/types.ts').Cue +type Phrase = import('../src/renderer/src/lib/types.ts').Phrase /** A steady grid at `bpm` from `firstMs`, `count` beats long. */ function grid(bpm: number, count: number, firstMs = 0): Beatgrid { @@ -121,3 +123,20 @@ describe('formatBars', () => { assert.equal(formatBars(3.26), '3.25') }) }) + +describe('phraseSections', () => { + const phrase = (firstBeat: number, label: string): Phrase => ({ firstBeat, label }) + + it('places each phrase on its beat and runs it to the next', () => { + const sections = phraseSections([phrase(1, 'INTRO 1'), phrase(65, 'CHORUS 1')], grid(120, 128), 70) + assert.deepEqual(sections, [ + { start: 0, end: 32, label: 'INTRO 1' }, + { start: 32, end: 70, label: 'CHORUS 1' } + ]) + }) + + it('leaves out phrases past the end of the grid, and draws none without one', () => { + assert.equal(phraseSections([phrase(1, 'INTRO 1'), phrase(500, 'OUTRO 1')], grid(120, 128), 70).length, 1) + assert.deepEqual(phraseSections([phrase(1, 'INTRO 1')], null, 70), []) + }) +}) diff --git a/native/crates/es-index/src/detail.rs b/native/crates/es-index/src/detail.rs index c89b0b1..145a3e5 100644 --- a/native/crates/es-index/src/detail.rs +++ b/native/crates/es-index/src/detail.rs @@ -45,6 +45,27 @@ pub struct Grid { pub bpms: Vec, } +impl From for Grid { + fn from(grid: decode::Grid) -> Self { + Self { times: grid.times, beats: grid.beats, bpms: grid.bpms } + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Phrase { + /// 1-based, counting the beats of the grid. + pub first_beat: u16, + pub label: String, +} + +/// The phrases in an analysis file, as rekordbox labels them. +pub(crate) fn phrases(ext: Option<&Tags>) -> Vec { + let structure = ext.and_then(rb_anlz::phrase::song_structure); + let phrases = structure.map(|s| s.phrases).unwrap_or_default(); + phrases.iter().map(|phrase| Phrase { first_beat: phrase.first_beat, label: phrase.to_string() }).collect() +} + #[derive(Debug, Serialize)] pub struct Colour { pub length: usize, @@ -82,6 +103,7 @@ pub struct Detail { pub file_exists: bool, pub cues: Vec, pub beatgrid: Option, + pub phrases: Vec, pub waveform: Waveform, } @@ -159,11 +181,8 @@ pub fn track_detail(lib: &Library, share: &Path, id: &str) -> Result { id: id.to_owned(), file_exists: Path::new(&files.folder_path).is_file(), cues: cues(lib, id, ext.as_ref())?, - beatgrid: dat.as_ref().and_then(decode::beatgrid).map(|g| Grid { - times: g.times, - beats: g.beats, - bpms: g.bpms, - }), + beatgrid: dat.as_ref().and_then(decode::beatgrid).map(Grid::from), + phrases: phrases(ext.as_ref()), waveform, }) } @@ -172,7 +191,7 @@ pub fn track_detail(lib: &Library, share: &Path, id: &str) -> Result { pub fn beatgrid_for(lib: &Library, share: &Path, id: &str) -> Result> { let files = lib.track_files(id)?.ok_or_else(|| Error::NotFound(format!("track {id}")))?; let dat = tags(share, files.analysis_path.as_deref(), "DAT"); - Ok(dat.as_ref().and_then(decode::beatgrid).map(|g| Grid { times: g.times, beats: g.beats, bpms: g.bpms })) + Ok(dat.as_ref().and_then(decode::beatgrid).map(Grid::from)) } /// A short waveform for a browser row. diff --git a/native/crates/es-index/src/device.rs b/native/crates/es-index/src/device.rs index e4b011d..530242d 100644 --- a/native/crates/es-index/src/device.rs +++ b/native/crates/es-index/src/device.rs @@ -249,11 +249,8 @@ pub fn detail(volume: &Path, key: &str, track: &Track) -> Detail { id: key.to_owned(), file_exists: audio.as_ref().is_some_and(|p| p.is_file()), cues: device_cues(track, ext.as_ref()), - beatgrid: dat.as_ref().and_then(decode::beatgrid).map(|g| Grid { - times: g.times, - beats: g.beats, - bpms: g.bpms, - }), + beatgrid: dat.as_ref().and_then(decode::beatgrid).map(Grid::from), + phrases: crate::detail::phrases(ext.as_ref()), waveform: Waveform { rate: 150, three_band: bands("PWV7"), From d71fc1dee9d50f0df4156a2de5dbea960ca63799 Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 15:43:37 +0000 Subject: [PATCH 07/25] Show phrases on the scrolling waveform too With "Show phrases" on, the detail waveform tints each phrase's stretch, marks where it starts, and labels it in the band above the waveform. The overview and detail views share one phrase colour lookup. Co-Authored-By: Claude Opus 5.5 --- .../src/lib/components/WaveformDetail.svelte | 3 +- .../lib/components/WaveformOverview.svelte | 3 +- .../settings/DeveloperSettings.svelte | 2 +- app/src/renderer/src/lib/waveform/colors.ts | 8 +++-- app/src/renderer/src/lib/waveform/detail.ts | 2 ++ app/src/renderer/src/lib/waveform/frame.ts | 2 ++ app/src/renderer/src/lib/waveform/markers.ts | 33 ++++++++++++++++++- 7 files changed, 46 insertions(+), 7 deletions(-) diff --git a/app/src/renderer/src/lib/components/WaveformDetail.svelte b/app/src/renderer/src/lib/components/WaveformDetail.svelte index f17fac6..0c9ddf3 100644 --- a/app/src/renderer/src/lib/components/WaveformDetail.svelte +++ b/app/src/renderer/src/lib/components/WaveformDetail.svelte @@ -70,7 +70,8 @@ loop: player.loop, gridEditing: player.grid.editing, hotGridIndex, - tempoFlags: player.grid.flagMarks + tempoFlags: player.grid.flagMarks, + phrases: player.phraseSections }, canvas.width, canvas.height, diff --git a/app/src/renderer/src/lib/components/WaveformOverview.svelte b/app/src/renderer/src/lib/components/WaveformOverview.svelte index 9f6dced..a528910 100644 --- a/app/src/renderer/src/lib/components/WaveformOverview.svelte +++ b/app/src/renderer/src/lib/components/WaveformOverview.svelte @@ -3,7 +3,7 @@ import { cueSections, formatBars, type CueSection } from '$lib/deck/sections' import { formatClock } from '$lib/format' import { setupCanvas } from '$lib/waveform/canvas' - import { CUE_POINT_COLOR, PHRASE_COLORS, UNKNOWN_PHRASE_COLOR } from '$lib/waveform/colors' + import { CUE_POINT_COLOR, phraseColor } from '$lib/waveform/colors' import { drawOverview } from '$lib/waveform/overview' import WaveformMarks from './WaveformMarks.svelte' @@ -32,7 +32,6 @@ : [] ) const bandWidth = (band: { start: number; end: number }): number => ((pct(band.end) - pct(band.start)) / 100) * width - const phraseColor = (label: string): string => PHRASE_COLORS[label.split(' ')[0]] ?? UNKNOWN_PHRASE_COLOR /** Owns the hover line while a section is pointed at, apart from the waveform's own hover. */ const SECTION_PREVIEW = 'section' diff --git a/app/src/renderer/src/lib/components/settings/DeveloperSettings.svelte b/app/src/renderer/src/lib/components/settings/DeveloperSettings.svelte index fcc6d34..29d8f34 100644 --- a/app/src/renderer/src/lib/components/settings/DeveloperSettings.svelte +++ b/app/src/renderer/src/lib/components/settings/DeveloperSettings.svelte @@ -58,7 +58,7 @@ /> prefs.setShowPhrases(!prefs.showPhrases)} /> diff --git a/app/src/renderer/src/lib/waveform/colors.ts b/app/src/renderer/src/lib/waveform/colors.ts index dbb168d..2a4bd92 100644 --- a/app/src/renderer/src/lib/waveform/colors.ts +++ b/app/src/renderer/src/lib/waveform/colors.ts @@ -1,7 +1,7 @@ export const CUE_POINT_COLOR = '#ff8a1f' /** Keyed by the first word of a rekordbox phrase label, in rekordbox's own colours. */ -export const PHRASE_COLORS: Record = { +const PHRASE_COLORS: Record = { INTRO: '#e0464a', VERSE: '#3d7cf0', UP: '#9b5cf0', @@ -10,7 +10,11 @@ export const PHRASE_COLORS: Record = { CHORUS: '#3fbf5a', OUTRO: '#5a6ee0' } -export const UNKNOWN_PHRASE_COLOR = '#888888' +const UNKNOWN_PHRASE_COLOR = '#888888' + +export function phraseColor(label: string): string { + return PHRASE_COLORS[label.split(' ')[0]] ?? UNKNOWN_PHRASE_COLOR +} export const LOOP_ACTIVE_COLOR = '#ffb020' export const TEMPO_FLAG_COLOR = '#b48cff' diff --git a/app/src/renderer/src/lib/waveform/detail.ts b/app/src/renderer/src/lib/waveform/detail.ts index 6546722..d95a5b7 100644 --- a/app/src/renderer/src/lib/waveform/detail.ts +++ b/app/src/renderer/src/lib/waveform/detail.ts @@ -12,6 +12,7 @@ import { paintGridHandles, paintLoopEdges, paintLoops, + paintPhrases, paintPlayhead } from './markers' import { drawSampleWave, waveStride } from './samples' @@ -78,6 +79,7 @@ export function drawDetail( toX: (seconds) => ((seconds * wf.rate - from) / (to - from)) * pw } paintLoops(frame) + paintPhrases(frame) paintWave(frame, mode, samples, quality, fallBlocks, rgbColors, heightScale) paintLoopEdges(frame) paintBeatGrid(frame) diff --git a/app/src/renderer/src/lib/waveform/frame.ts b/app/src/renderer/src/lib/waveform/frame.ts index 462b431..60fe38b 100644 --- a/app/src/renderer/src/lib/waveform/frame.ts +++ b/app/src/renderer/src/lib/waveform/frame.ts @@ -1,3 +1,4 @@ +import type { PhraseSection } from '../deck/sections' import type { Beatgrid, Cue } from '../types' import type { Waveform } from './data' @@ -23,6 +24,7 @@ export interface DetailView { /** Beat under the pointer while editing, or -1. Dragging its handle shifts the grid. */ hotGridIndex: number tempoFlags?: TempoFlagMark[] + phrases?: PhraseSection[] } /** One draw of the detail view: the canvas in device pixels and the entries it spans. */ diff --git a/app/src/renderer/src/lib/waveform/markers.ts b/app/src/renderer/src/lib/waveform/markers.ts index 208c081..a751192 100644 --- a/app/src/renderer/src/lib/waveform/markers.ts +++ b/app/src/renderer/src/lib/waveform/markers.ts @@ -2,7 +2,7 @@ import { barBeatAt, countdownTo, firstIndexAtOrAfter } from '../beat' import { cueColor, hotCueLetter } from '../format' import type { Beatgrid, Cue } from '../types' -import { CUE_POINT_COLOR, LOOP_ACTIVE_COLOR, TEMPO_FLAG_COLOR } from './colors' +import { CUE_POINT_COLOR, LOOP_ACTIVE_COLOR, phraseColor, TEMPO_FLAG_COLOR } from './colors' import type { Waveform } from './data' import type { Frame, WidthFraction } from './frame' @@ -11,6 +11,37 @@ const HANDLE_W = 6 const HANDLE_H = 30 const HANDLE_HIT_X = 10 const HANDLE_HIT_Y = 18 +/** The phrase strip fills the clear band above the waveform, in CSS pixels. */ +const PHRASE_STRIP_H = 9 +const PHRASE_TINT_ALPHA = '1a' +const PHRASE_EDGE_ALPHA = '99' + +/** Each phrase as a faint tint over its stretch, a line where it starts, and a labelled strip along the top. */ +export function paintPhrases(frame: Frame): void { + const { ctx, view, pw, ph, dpr, toX } = frame + const strip = Math.round(PHRASE_STRIP_H * dpr) + const edge = Math.max(1, Math.round(dpr)) + ctx.font = `600 ${Math.round(7.5 * dpr)}px system-ui, sans-serif` + ctx.textBaseline = 'middle' + ctx.textAlign = 'left' + for (const phrase of view.phrases ?? []) { + const x0 = Math.round(toX(phrase.start)) + const x1 = Math.round(toX(phrase.end)) + if (x1 < 0 || x0 > pw) continue + const color = phraseColor(phrase.label) + ctx.fillStyle = color + PHRASE_TINT_ALPHA + ctx.fillRect(x0, strip, x1 - x0, ph - strip) + ctx.fillStyle = color + PHRASE_EDGE_ALPHA + ctx.fillRect(x0, 0, edge, ph) + ctx.fillStyle = color + ctx.fillRect(x0, 0, x1 - x0, strip) + const textX = Math.max(x0, 0) + 3 * dpr + if (x1 - textX > ctx.measureText(phrase.label).width) { + ctx.fillStyle = '#000000cc' + ctx.fillText(phrase.label, textX, strip / 2 + 0.5 * dpr) + } + } +} export function paintLoops(frame: Frame): void { const { ctx, view, pw, ph, toX } = frame From f45ccc581c43382342eb5f42952be62c053afa12 Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 16:28:03 +0000 Subject: [PATCH 08/25] Stop one miscounted section from shifting every phrase after it Sections were snapped to one 4-bar lattice per track, counted from the grid's downbeats, so an intro a bar short, a sweep before it, or a wrong downbeat moved every later phrase by the same gap. Now: - Novelty is measured at every beat, comparing whole bars counted back and on from it, so it stays as sharp as bar profiles without leaning on the downbeat. - Starts are chosen together by dynamic programming, each section's length counted from the start before it: 8, 16 and 32 bars are free, 4, 12, 24, 48 and 64 cost a little, and odd lengths more. Past an odd section the rest follow on from it. - A detected grid's downbeat is rechecked against which beat of the bar the phrase changes fall on, and moved when another beat carries three times as many. Kept grids are never renumbered. - A section leading into a drop is a build. rekordbox calls 90% of them UP; requiring an audible rise named most of them breakdowns. On grids our analysis detects, cues just missed by a section start drop from 15.4% to 9.0% at the same F1 (0.56), and downbeats agree with rekordbox's on 89.5% of tracks, up from 86.9%. Co-Authored-By: Claude Opus 5.5 --- .../es-analyse/examples/structure_eval.rs | 387 ++++++++++------ native/crates/es-analyse/src/lib.rs | 57 ++- native/crates/es-analyse/src/structure.rs | 413 +++++++++++------- 3 files changed, 553 insertions(+), 304 deletions(-) diff --git a/native/crates/es-analyse/examples/structure_eval.rs b/native/crates/es-analyse/examples/structure_eval.rs index 408757c..23c43a9 100644 --- a/native/crates/es-analyse/examples/structure_eval.rs +++ b/native/crates/es-analyse/examples/structure_eval.rs @@ -1,25 +1,36 @@ //! Scores section starts against where a DJ put their cues, using a dump from `es-index`'s //! `cue_survey` example. Cues sit on section changes, so a good segmenter's starts carry them. //! Each track is measured once; tunings are then tried one setting at a time, keeping the best. -//! `cargo run --release -p es-analyse --example structure_eval -- survey.json` +//! `cargo run --release -p es-analyse --example structure_eval -- survey.json [--our-grid]` +//! +//! `--our-grid` finds sections on the grid our own analysis detects instead of the one the survey +//! holds, as a track has after it is analysed here. Cues are then matched to its nearest beats. use std::collections::{BTreeMap, HashSet}; use std::path::Path; -use es_analyse::structure::{segment, BarFeatures, BarIndex, Section, SectionKind, Tuning}; -use es_analyse::{decode_mono, Beat, SAMPLE_RATE}; +use es_analyse::structure::{ + bar_phase, bar_phase_votes, segment, BeatFeatures, BeatIndex, Section, SectionKind, Tuning, +}; +use es_analyse::{analyse_samples, decode_mono, Beat, Options, SAMPLE_RATE}; use rayon::prelude::*; use serde_json::Value; -const ON_BEAT_TOLERANCE_MS: i64 = 15; +const SURVEY_ON_BEAT_MS: f64 = 15.0; +const OUR_GRID_ON_BEAT_SHARE: f64 = 0.25; +const NEAR_MISS_BEATS: usize = 8; +const BEATS_PER_BAR: usize = 4; struct Track { title: String, - features: BarFeatures, - cue_bars: HashSet, - rekordbox_phrase_bars: Option>, - rekordbox_change_bars: Option>, - rekordbox_bar_kinds: Option>>, + features: BeatFeatures, + first_downbeat: BeatIndex, + cue_beats: HashSet, + rekordbox_phrase_beats: Option>, + rekordbox_change_beats: Option>, + rekordbox_beat_kinds: Option>>, + /// With `--our-grid`: the beat of the survey grid's bar our downbeats mostly land on, 0 when they agree. + downbeat_offset: Option, } #[derive(Default, Clone, Copy)] @@ -27,14 +38,21 @@ struct Score { cues: usize, starts: usize, hits: usize, + near_misses: usize, tracks: usize, } impl Score { - fn add(&mut self, cues: &HashSet, starts: &HashSet) { + fn add(&mut self, cues: &HashSet, starts: &HashSet) { self.cues += cues.len(); self.starts += starts.len(); self.hits += cues.intersection(starts).count(); + self.near_misses += cues + .iter() + .filter(|&&cue| { + !starts.contains(&cue) && starts.iter().any(|&start| start.abs_diff(cue) <= NEAR_MISS_BEATS) + }) + .count(); self.tracks += 1; } @@ -57,95 +75,157 @@ impl Score { fn line(&self, name: &str) -> String { format!( - "{name:<34} recall {:>5.1}% precision {:>5.1}% F1 {:.3} starts/track {:>5.1} cues/track {:.1}", + "{name:<34} recall {:>5.1}% precision {:>5.1}% F1 {:.3} near misses {:>4.1}% starts/track {:>5.1}", 100.0 * self.recall(), 100.0 * self.precision(), self.f1(), + 100.0 * self.near_misses as f64 / self.cues.max(1) as f64, self.starts as f64 / self.tracks.max(1) as f64, - self.cues as f64 / self.tracks.max(1) as f64 ) } } fn main() -> Result<(), Box> { - let path = std::env::args().nth(1).ok_or("pass the survey JSON from cue_survey")?; + let mut args = std::env::args().skip(1); + let path = args.next().ok_or("pass the survey JSON from cue_survey")?; + let our_grid = args.any(|arg| arg == "--our-grid"); let survey: Vec = serde_json::from_str(&std::fs::read_to_string(path)?)?; - let tracks: Vec = survey.par_iter().filter_map(measure).collect(); - println!("measured {} of {} tracks\n", tracks.len(), survey.len()); + let tracks: Vec = survey.par_iter().filter_map(|entry| measure(entry, our_grid)).collect(); + println!("measured {} of {} tracks{}\n", tracks.len(), survey.len(), if our_grid { " on our grid" } else { "" }); + let offsets: Vec = tracks.iter().filter_map(|track| track.downbeat_offset).collect(); + if !offsets.is_empty() { + let count = |offset| offsets.iter().filter(|&&o| o == offset).count(); + println!( + "our downbeats against the survey grid's: on its beat 1 {:.1}%, beat 2 {:.1}%, beat 3 {:.1}%, beat 4 {:.1}% of tracks\n", + share(count(0), offsets.len()), + share(count(1), offsets.len()), + share(count(2), offsets.len()), + share(count(3), offsets.len()) + ); + report_phase_correction(&tracks); + } report_baselines(&tracks); - let best = report_labels(&tracks, &tune(&tracks)); + let best = tune(&tracks); + report_labels(&tracks, &best); println!("\nbest {best:?}"); - report_kinds(&tracks, &best); + report_anchors(&tracks, &best); Ok(()) } -fn measure(entry: &Value) -> Option { - let grid = entry.get("grid")?; - let times: Vec = numbers(&grid["times"]).into_iter().map(|t| t as u32).collect(); - let beat_numbers: Vec = numbers(&grid["beats"]).into_iter().map(|b| b as u8).collect(); - let beats: Vec = - times.iter().zip(&beat_numbers).map(|(&time_ms, &number)| Beat { number, tempo_x100: 0, time_ms }).collect(); - let bar_of_beat: BTreeMap = beats +fn numbers(value: &Value) -> Vec { + value.as_array().map(|all| all.iter().filter_map(Value::as_u64).collect()).unwrap_or_default() +} + +fn survey_grid(entry: &Value) -> Vec { + let times = numbers(&entry["grid"]["times"]); + let beat_numbers = numbers(&entry["grid"]["beats"]); + times .iter() - .enumerate() - .filter(|(_, b)| b.number == 1) - .enumerate() - .map(|(bar, (beat, _))| (beat, bar)) - .collect(); - let bar_at_ms = |ms: i64| { - let beat = times.partition_point(|&t| i64::from(t) < ms - ON_BEAT_TOLERANCE_MS); - let on_beat = times.get(beat).is_some_and(|&t| (i64::from(t) - ms).abs() <= ON_BEAT_TOLERANCE_MS); - on_beat.then(|| bar_of_beat.get(&beat).copied()).flatten() + .zip(&beat_numbers) + .map(|(&time_ms, &number)| Beat { number: number as u8, tempo_x100: 0, time_ms: time_ms as u32 }) + .collect() +} + +fn nearest_beat(beats: &[Beat], ms: f64, tolerance_ms: f64) -> Option { + let after = beats.partition_point(|beat| f64::from(beat.time_ms) < ms); + let distance = |index: usize| (f64::from(beats[index].time_ms) - ms).abs(); + [after.checked_sub(1), Some(after)] + .into_iter() + .flatten() + .filter(|&index| index < beats.len()) + .min_by(|&a, &b| distance(a).total_cmp(&distance(b))) + .filter(|&index| distance(index) <= tolerance_ms) +} + +fn measure(entry: &Value, our_grid: bool) -> Option { + let audio = decode_mono(Path::new(entry["path"].as_str()?)).ok()?; + let rate = f64::from(SAMPLE_RATE); + let beats = if our_grid { + analyse_samples(&audio, rate, &Options { key: false, sections: false, ..Options::default() }).beats + } else { + survey_grid(entry) }; - let cue_bars: HashSet = - entry["cues"].as_array()?.iter().filter_map(|cue| cue["startMs"].as_i64()).filter_map(bar_at_ms).collect(); - if cue_bars.is_empty() { + if beats.len() < 2 { + return None; + } + let beat_ms = f64::from(beats[1].time_ms - beats[0].time_ms); + let downbeat_offset = our_grid.then(|| { + let theirs = survey_grid(entry); + let mut offsets = [0usize; BEATS_PER_BAR]; + for beat in beats.iter().filter(|beat| beat.number == 1) { + if let Some(index) = nearest_beat(&theirs, f64::from(beat.time_ms), beat_ms * OUR_GRID_ON_BEAT_SHARE) { + offsets[(usize::from(theirs[index].number) + BEATS_PER_BAR - 1) % BEATS_PER_BAR] += 1; + } + } + (0..BEATS_PER_BAR).max_by_key(|&offset| offsets[offset]).unwrap_or(0) + }); + let tolerance = if our_grid { beat_ms * OUR_GRID_ON_BEAT_SHARE } else { SURVEY_ON_BEAT_MS }; + let cue_beats: HashSet = entry["cues"] + .as_array()? + .iter() + .filter_map(|cue| cue["startMs"].as_f64()) + .filter_map(|ms| nearest_beat(&beats, ms, tolerance)) + .collect(); + if cue_beats.is_empty() { return None; } - let phrases = entry["structure"]["phrases"].as_array(); - let phrase_bar = |phrase: &Value| { - let first_beat = usize::try_from(phrase["firstBeat"].as_u64()?).ok()?.checked_sub(1)?; - bar_of_beat.get(&first_beat).copied() - }; - let rekordbox_phrase_bars = phrases.map(|all| all.iter().filter_map(phrase_bar).collect()); - let rekordbox_change_bars = phrases.map(|all| { - let kind = |phrase: &Value| phrase["label"].as_str().unwrap_or("").split(' ').next().unwrap_or("").to_owned(); + let phrases = if our_grid { None } else { entry["structure"]["phrases"].as_array() }; + let phrase_beat = |phrase: &Value| usize::try_from(phrase["firstBeat"].as_u64()?).ok()?.checked_sub(1); + let kind_word = |phrase: &Value| phrase["label"].as_str().unwrap_or("").split(' ').next().unwrap_or("").to_owned(); + let rekordbox_phrase_beats = phrases.map(|all| all.iter().filter_map(phrase_beat).collect()); + let rekordbox_change_beats = phrases.map(|all| { all.iter() .enumerate() - .filter(|(index, phrase)| *index == 0 || kind(&all[index - 1]) != kind(phrase)) - .filter_map(|(_, phrase)| phrase_bar(phrase)) + .filter(|(index, phrase)| *index == 0 || kind_word(&all[index - 1]) != kind_word(phrase)) + .filter_map(|(_, phrase)| phrase_beat(phrase)) .collect() }); - - let downbeats: Vec = bar_of_beat.keys().copied().collect(); - let bar_containing = |beat: usize| downbeats.partition_point(|&first| first <= beat).saturating_sub(1); - let rekordbox_bar_kinds = phrases.map(|all| { - let mut kinds = vec![None; downbeats.len()]; + let rekordbox_beat_kinds = phrases.map(|all| { + let mut kinds = vec![None; beats.len()]; for (index, phrase) in all.iter().enumerate() { - let first_beat = |p: &Value| p["firstBeat"].as_u64().map_or(0, |b| b.saturating_sub(1) as usize); - let start = bar_containing(first_beat(phrase)); - let end = all.get(index + 1).map_or(downbeats.len(), |next| bar_containing(first_beat(next))); - let kind = rekordbox_kind(phrase["label"].as_str().unwrap_or("")); - kinds[start.min(downbeats.len())..end.min(downbeats.len())].fill(kind); + let start = phrase_beat(phrase).unwrap_or(0).min(beats.len()); + let end = all.get(index + 1).and_then(phrase_beat).unwrap_or(beats.len()).min(beats.len()); + kinds[start..end.max(start)].fill(rekordbox_kind(&kind_word(phrase))); } kinds }); - let audio = decode_mono(Path::new(entry["path"].as_str()?)).ok()?; Some(Track { title: format!("{} - {}", entry["artist"].as_str().unwrap_or(""), entry["title"].as_str().unwrap_or("")), - features: BarFeatures::measure(&audio, f64::from(SAMPLE_RATE), &beats), - cue_bars, - rekordbox_phrase_bars, - rekordbox_change_bars, - rekordbox_bar_kinds, + features: BeatFeatures::measure(&audio, rate, &beats), + first_downbeat: beats.iter().position(|beat| beat.number == 1).unwrap_or(0), + cue_beats, + rekordbox_phrase_beats, + rekordbox_change_beats, + rekordbox_beat_kinds, + downbeat_offset, }) } -fn rekordbox_kind(label: &str) -> Option { - match label.split(' ').next()? { +/// How often re-picking the downbeat from the bar-to-bar vote would put it where the survey grid has it. +fn report_phase_correction(tracks: &[Track]) { + let cases: Vec<(&Track, [f64; BEATS_PER_BAR], usize)> = tracks + .iter() + .filter_map(|track| { + let offset = track.downbeat_offset?; + let grid_phase = track.first_downbeat % BEATS_PER_BAR; + Some((track, bar_phase_votes(&track.features), (grid_phase + BEATS_PER_BAR - offset) % BEATS_PER_BAR)) + }) + .collect(); + for trust in [1.0, 1.25, 1.5, 2.0, 3.0, 5.0, f64::INFINITY] { + let right = cases + .iter() + .filter(|(track, votes, true_phase)| bar_phase(track.features.on_downbeat(), votes, trust) == *true_phase) + .count(); + println!(" re-picked at trust {trust}: downbeat right on {:.1}% of tracks", share(right, cases.len())); + } + println!(); +} + +fn rekordbox_kind(word: &str) -> Option { + match word { "INTRO" => Some(SectionKind::Intro), "UP" => Some(SectionKind::Build), "DOWN" => Some(SectionKind::Breakdown), @@ -155,75 +235,38 @@ fn rekordbox_kind(label: &str) -> Option { } } -/// Share of bars whose section kind matches rekordbox's, and the counts behind it, ours by theirs. -fn label_agreement(tracks: &[Track], tuning: &Tuning) -> (f64, [[usize; 5]; 5]) { - let mut counts = [[0usize; 5]; 5]; - for track in tracks { - let Some(theirs) = &track.rekordbox_bar_kinds else { continue }; - for section in segment(&track.features, tuning) { - let ours = SectionKind::ALL.iter().position(|&k| k == section.kind).unwrap_or(0); - for bar in section.first_bar..section.first_bar + section.bars { - if let Some(Some(kind)) = theirs.get(bar) { - counts[ours][SectionKind::ALL.iter().position(|k| k == kind).unwrap_or(0)] += 1; - } - } - } - } - let total: usize = counts.iter().flatten().sum(); - let agreed: usize = (0..5).map(|i| counts[i][i]).sum(); - (agreed as f64 / total.max(1) as f64, counts) -} - -fn report_labels(tracks: &[Track], best: &Tuning) -> Tuning { - println!("\nbar labels against rekordbox's:"); - let mut chosen = *best; - let mut chosen_agreement = 0.0; - for drop_energy in [0.5, 0.6, 0.7, 0.75, 0.8, 0.85, 0.9] { - let tuning = Tuning { drop_energy, ..*best }; - let (agreement, _) = label_agreement(tracks, &tuning); - println!(" drop energy {drop_energy}: {:.1}% of bars agree", 100.0 * agreement); - if agreement > chosen_agreement { - (chosen, chosen_agreement) = (tuning, agreement); - } - } - let (_, counts) = label_agreement(tracks, &chosen); - println!(" ours \\ theirs {}", SectionKind::ALL.iter().map(|&k| format!("{:>9}", k.name())).collect::()); - for (ours, row) in SectionKind::ALL.iter().zip(counts) { - println!(" {:<14} {}", ours.name(), row.iter().map(|n| format!("{n:>9}")).collect::()); - } - chosen -} - -fn numbers(value: &Value) -> Vec { - value.as_array().map(|all| all.iter().filter_map(Value::as_u64).collect()).unwrap_or_default() -} - -fn starts(sections: &[Section]) -> HashSet { - sections.iter().map(|section| section.first_bar).collect() +fn starts(sections: &[Section]) -> HashSet { + sections.iter().map(|section| section.first_beat).collect() } fn score(tracks: &[Track], tuning: &Tuning) -> Score { let mut total = Score::default(); for track in tracks { - total.add(&track.cue_bars, &starts(&segment(&track.features, tuning))); + total.add(&track.cue_beats, &starts(&segment(&track.features, tuning))); } total } fn report_baselines(tracks: &[Track]) { - for every in [8, 16, 32] { + for bars in [8, 16, 32] { let mut total = Score::default(); for track in tracks { - total.add(&track.cue_bars, &(0..track.features.bars()).step_by(every).collect()); + total.add( + &track.cue_beats, + &(track.first_downbeat..track.features.beats()).step_by(bars * BEATS_PER_BAR).collect(), + ); } - println!("{}", total.line(&format!("every {every} bars from the first"))); + println!("{}", total.line(&format!("every {bars} bars from the first"))); + } + let with_phrases: Vec<&Track> = tracks.iter().filter(|t| t.rekordbox_phrase_beats.is_some()).collect(); + if with_phrases.is_empty() { + return; } - let with_phrases: Vec<&Track> = tracks.iter().filter(|t| t.rekordbox_phrase_bars.is_some()).collect(); let (mut phrases, mut changes, mut ours) = (Score::default(), Score::default(), Score::default()); for track in &with_phrases { - phrases.add(&track.cue_bars, track.rekordbox_phrase_bars.as_ref().unwrap_or(&HashSet::new())); - changes.add(&track.cue_bars, track.rekordbox_change_bars.as_ref().unwrap_or(&HashSet::new())); - ours.add(&track.cue_bars, &starts(&segment(&track.features, &Tuning::default()))); + phrases.add(&track.cue_beats, track.rekordbox_phrase_beats.as_ref().unwrap_or(&HashSet::new())); + changes.add(&track.cue_beats, track.rekordbox_change_beats.as_ref().unwrap_or(&HashSet::new())); + ours.add(&track.cue_beats, &starts(&segment(&track.features, &Tuning::default()))); } println!("-- the {} tracks rekordbox phrased --", with_phrases.len()); println!("{}", phrases.line("rekordbox phrase starts")); @@ -244,17 +287,19 @@ fn settings(base: &Tuning) -> Vec { }) .collect() }; - let kernels = [[2, 4], [4, 8], [4, 16], [8, 16], [2, 8]] + let kernels = [[2, 4], [4, 8], [4, 16], [2, 8], [8, 16]] .iter() .map(|&widths| (format!("kernels {widths:?}"), Tuning { kernel_half_widths: widths, ..*base })) .collect(); vec![ - vary("threshold", &[-0.75, -0.5, -0.25, 0.0, 0.25, 0.5, 0.75, 1.0], |t, v| t.boundary_threshold = v), + vary("threshold", &[0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5], |t, v| t.boundary_threshold = v), + vary("uncommon length", &[0.0, 0.25, 0.5, 1.0], |t, v| t.uncommon_length_cost = v), + vary("odd length", &[0.5, 1.0, 1.5, 2.0, 3.0], |t, v| t.odd_length_cost = v), kernels, vary("timbre", &[0.0, 0.5, 1.0, 2.0], |t, v| t.timbre_weight = v), - vary("harmony", &[0.0, 0.25, 0.5, 1.0, 2.0], |t, v| t.harmony_weight = v), + vary("harmony", &[0.5, 1.0, 2.0, 3.0], |t, v| t.harmony_weight = v), vary("rhythm", &[0.0, 0.5, 1.0, 2.0], |t, v| t.rhythm_weight = v), - vary("loudness", &[0.0, 0.5, 1.0, 2.0, 4.0], |t, v| t.loudness_weight = v), + vary("loudness", &[0.0, 0.5, 1.0, 2.0], |t, v| t.loudness_weight = v), ] } @@ -280,19 +325,81 @@ fn tune(tracks: &[Track]) -> Tuning { best } -/// What our sections are called where the DJ cued, as "Drop#2" style anchors. -fn report_kinds(tracks: &[Track], tuning: &Tuning) { +/// How often our sections' kinds match rekordbox's over the beats they share (ours by theirs), +/// and how a section leading into a drop is named against rekordbox's UP or DOWN over the same +/// beats: rows are our build and breakdown, columns their up and down. +struct LabelAgreement { + beats: [[usize; 5]; 5], + before_drop: [[usize; 2]; 2], +} + +fn kind_index(kind: SectionKind) -> usize { + SectionKind::ALL.iter().position(|&k| k == kind).unwrap_or(0) +} + +fn label_agreement(tracks: &[Track], tuning: &Tuning) -> LabelAgreement { + let mut agreement = LabelAgreement { beats: [[0; 5]; 5], before_drop: [[0; 2]; 2] }; + for track in tracks { + let Some(theirs) = &track.rekordbox_beat_kinds else { continue }; + let sections = segment(&track.features, tuning); + for (index, section) in sections.iter().enumerate() { + let span = section.first_beat..section.first_beat + section.beats; + for beat in span.clone() { + if let Some(Some(kind)) = theirs.get(beat) { + agreement.beats[kind_index(section.kind)][kind_index(*kind)] += 1; + } + } + let leads_into_drop = sections.get(index + 1).is_some_and(|next| next.kind == SectionKind::Drop); + let our_side = match section.kind { + SectionKind::Build => 0, + SectionKind::Breakdown => 1, + _ => continue, + }; + let count = |kind| span.clone().filter(|&beat| theirs.get(beat) == Some(&Some(kind))).count(); + let (up, down) = (count(SectionKind::Build), count(SectionKind::Breakdown)); + if leads_into_drop && up + down > 0 { + agreement.before_drop[our_side][usize::from(down > up)] += 1; + } + } + } + agreement +} + +fn share(agreed: usize, total: usize) -> f64 { + 100.0 * agreed as f64 / total.max(1) as f64 +} + +fn report_labels(tracks: &[Track], tuning: &Tuning) { + if tracks.iter().all(|t| t.rekordbox_beat_kinds.is_none()) { + return; + } + let LabelAgreement { beats, before_drop } = label_agreement(tracks, tuning); + let all_beats: usize = beats.iter().flatten().sum(); + println!( + "\nlabels against rekordbox's: {:.1}% of beats agree", + share((0..5).map(|i| beats[i][i]).sum(), all_beats) + ); + println!( + " before drops, [[build: up, down], [breakdown: up, down]] {before_drop:?}: {:.1}% agree", + share(before_drop[0][0] + before_drop[1][1], before_drop.iter().flatten().sum()) + ); + println!(" ours \\ theirs {}", SectionKind::ALL.iter().map(|k| format!("{:>10}", k.name())).collect::()); + for (ours, row) in SectionKind::ALL.iter().zip(beats) { + println!(" {:<13} {}", ours.name(), row.iter().map(|n| format!("{n:>10}")).collect::()); + } +} + +/// What our sections are called where the DJ cued, as "drop#2" style anchors. +fn report_anchors(tracks: &[Track], tuning: &Tuning) { let mut at_cues: BTreeMap = BTreeMap::new(); let mut everywhere: BTreeMap = BTreeMap::new(); for track in tracks { - let sections = segment(&track.features, tuning); - let mut seen: BTreeMap = BTreeMap::new(); - for section in §ions { - let kind = section.kind.name(); - let occurrence = seen.entry(kind.to_owned()).and_modify(|n| *n += 1).or_insert(1); - let anchor = format!("{kind}#{occurrence}"); + let mut seen: BTreeMap<&str, usize> = BTreeMap::new(); + for section in segment(&track.features, tuning) { + let occurrence = seen.entry(section.kind.name()).and_modify(|n| *n += 1).or_insert(1); + let anchor = format!("{}#{occurrence}", section.kind.name()); *everywhere.entry(anchor.clone()).or_default() += 1; - if track.cue_bars.contains(§ion.first_bar) { + if track.cue_beats.contains(§ion.first_beat) { *at_cues.entry(anchor).or_default() += 1; } } @@ -300,25 +407,25 @@ fn report_kinds(tracks: &[Track], tuning: &Tuning) { let mut rows: Vec<_> = everywhere.into_iter().collect(); rows.sort_by_key(|(_, found)| std::cmp::Reverse(*found)); println!("\n{:<14} {:>6} {:>7}", "section start", "found", "cued"); - for (anchor, found) in rows.into_iter().take(24) { + for (anchor, found) in rows.into_iter().take(16) { let cued = at_cues.get(&anchor).copied().unwrap_or(0); - println!("{anchor:<14} {found:>6} {:>6.0}%", 100.0 * cued as f64 / found as f64); + println!("{anchor:<14} {found:>6} {:>6.0}%", share(cued, found)); } if let Some(track) = tracks.first() { println!("\nexample: {}", track.title); - for section in segment(&track.features, tuning) { - let cued = if track.cue_bars.contains(§ion.first_bar) { "cued" } else { "" }; + let sections = segment(&track.features, tuning); + for section in §ions { + let cued = if track.cue_beats.contains(§ion.first_beat) { "cued" } else { "" }; println!( - " bar {:>4} {:>3} bars {:<9} energy {:.2} {cued}", - section.first_bar, - section.bars, + " beat {:>4} {:>5} bars {:<9} energy {:.2} {cued}", + section.first_beat, + section.beats as f64 / BEATS_PER_BAR as f64, section.kind.name(), section.relative_energy ); } - let mut missed: Vec<_> = - track.cue_bars.difference(&starts(&segment(&track.features, tuning))).copied().collect(); + let mut missed: Vec<_> = track.cue_beats.difference(&starts(§ions)).copied().collect(); missed.sort_unstable(); - println!(" cues on no section start: bars {missed:?}"); + println!(" cues on no section start: beats {missed:?}"); } } diff --git a/native/crates/es-analyse/src/lib.rs b/native/crates/es-analyse/src/lib.rs index a5a50ea..8102dec 100644 --- a/native/crates/es-analyse/src/lib.rs +++ b/native/crates/es-analyse/src/lib.rs @@ -24,6 +24,9 @@ const ONSET_FRAME: usize = 1024; const ONSET_HOP: usize = 256; const KICK_HZ: (f64, f64) = (30.0, 150.0); const ONSET_HZ: (f64, f64) = (30.0, 16_000.0); +/// How many times more of the phrase changes another beat of the bar must carry before a detected +/// grid's downbeat moves to it. +const DOWNBEAT_RECHECK_TRUST: f64 = 3.0; #[derive(Debug, Clone)] pub struct Options { @@ -92,24 +95,46 @@ pub fn analyse_samples(mono: &[f32], sample_rate: f64, options: &Options) -> Ana || detect_grid.then(|| beatgrid(mono, sample_rate, duration, &options.tempo)).flatten(), || options.key.then(|| key::analyse(mono, sample_rate)).flatten(), ); - let (bpm, beats) = grid.unwrap_or_default(); - let section_grid = options.kept_grid.as_deref().unwrap_or(&beats); + let (bpm, mut beats) = grid.unwrap_or_default(); let (waveform, sections) = rayon::join( || waveform::features(mono, sample_rate), - || { - let wanted = options.sections && !section_grid.is_empty(); - let found = wanted.then(|| { - structure::segment( - &structure::BarFeatures::measure(mono, sample_rate, section_grid), - &structure::Tuning::default(), - ) - }); - found.unwrap_or_default() - }, + || recheck_downbeats_and_find_sections(mono, sample_rate, &mut beats, options), ); Analysis { duration, bpm, beats, key, waveform, sections } } +/// Sections on the kept grid, or on `detected` after checking its downbeats against where the +/// music changes: a detected grid is renumbered when another beat of the bar carries clearly more +/// of the track's phrase changes. A kept grid is the user's and is never renumbered. +fn recheck_downbeats_and_find_sections( + mono: &[f32], + sample_rate: f64, + detected: &mut [Beat], + options: &Options, +) -> Vec { + let segment = |features: &structure::BeatFeatures| { + if options.sections { + structure::segment(features, &structure::Tuning::default()) + } else { + Vec::new() + } + }; + if let Some(kept) = options.kept_grid.as_deref().filter(|kept| !kept.is_empty()) { + return segment(&structure::BeatFeatures::measure(mono, sample_rate, kept)); + } + if detected.is_empty() { + return Vec::new(); + } + let features = structure::BeatFeatures::measure(mono, sample_rate, detected); + let votes = structure::bar_phase_votes(&features); + let phase = structure::bar_phase(features.on_downbeat(), &votes, DOWNBEAT_RECHECK_TRUST); + let numbers = downbeat::numbers(detected.len(), phase); + for (beat, number) in detected.iter_mut().zip(numbers) { + beat.number = number; + } + segment(&features.counting_bars_from(phase)) +} + fn beatgrid(mono: &[f32], sample_rate: f64, duration: f64, opts: &TempoOptions) -> Option<(f64, Vec)> { let (stft, attacks) = rayon::join( || spectrum::stft(mono, sample_rate, ONSET_FRAME, ONSET_HOP), @@ -213,15 +238,13 @@ mod tests { #[test] fn sections_follow_a_kept_grid_instead_of_a_detected_one() { let audio = track(128.0, 60.0, 0.0, &[220.0]); - let first_downbeat = |beats: &[Beat]| beats.iter().position(|beat| beat.number == 1); let detected = analyse_samples(&audio, RATE, &Options::default()); - assert_eq!(detected.sections.first().map(|s| s.first_beat), first_downbeat(&detected.beats)); - - let kept_grid: Vec = detected.beats[2..].to_vec(); + let kept_grid: Vec = detected.beats[..detected.beats.len() / 2].to_vec(); let options = Options { kept_grid: Some(kept_grid.clone()), ..Options::default() }; let kept = analyse_samples(&audio, RATE, &options); assert!(kept.beats.is_empty()); - assert_eq!(kept.sections.first().map(|s| s.first_beat), first_downbeat(&kept_grid)); + let last = kept.sections.last().expect("sections on the kept grid"); + assert_eq!(last.first_beat + last.beats, kept_grid.len()); } #[test] diff --git a/native/crates/es-analyse/src/structure.rs b/native/crates/es-analyse/src/structure.rs index 417c804..ac3eb33 100644 --- a/native/crates/es-analyse/src/structure.rs +++ b/native/crates/es-analyse/src/structure.rs @@ -1,23 +1,33 @@ //! Where a track's sections start, and what each one is: intro, build, drop, breakdown or outro. //! -//! Every bar gets a profile of its timbre, harmony, rhythm and loudness. A section starts where the -//! bars after a line sound unlike the bars before it while each side sounds like itself: Foote's -//! checkerboard novelty over the bars' self-similarity. Dance music changes on phrase lines, so a -//! track's sections only start on one 4-bar grid, at the phase where its novelty lines up best. -//! Each section is then named from its energy and where it falls among the drops. +//! Every beat gets a profile of the bar that starts on it: its timbre, harmony, rhythm and loudness. +//! A beat is a likely section start when the bars counted on from it sound unlike the bars counted +//! back from it, while each side sounds like itself: Foote's checkerboard novelty over the bars' +//! self-similarity. Counting bars from every beat, rather than from the grid's downbeats, keeps a +//! downbeat that is off by a beat from moving every section with it. +//! +//! The starts are then chosen together, by dynamic programming: each section's length is counted +//! from the start before it, and lengths of 8, 16 and 32 bars cost nothing while others cost a +//! little. A section of an odd length is taken when the music clearly changes there, and every +//! section after it follows on from it rather than from a grid fixed for the whole track. use crate::downbeat::{self, BANDS}; use crate::{onset, spectrum, Beat, KICK_HZ, ONSET_FRAME, ONSET_HOP}; -pub type BarIndex = usize; pub type BeatIndex = usize; +pub type Beats = usize; +pub type Bars = usize; const HAT_HZ: (f64, f64) = (6_000.0, 16_000.0); -const BEATS_PER_BAR: usize = 4; -const BARS_PER_PHRASE: usize = 4; -const MIN_KERNEL_SIDE: usize = 2; -/// How much of the track's energy range a build's second half must climb above its first. -const MIN_BUILD_RISE: f64 = 0.1; +const BEATS_PER_BAR: Beats = 4; +const MIN_KERNEL_SIDE: Bars = 2; +const PHASE_PEAK_REACH: Beats = 2; +/// Changes in the first bars are left out of the phase vote: the comparison there is cut short. +const PHASE_VOTE_FROM: BeatIndex = 2 * BEATS_PER_BAR; +/// Standard deviations of bar-to-bar novelty a change needs to vote, and the most its vote can weigh. +const PHASE_VOTE_FLOOR: f64 = 1.0; +const PHASE_VOTE_CAP: f64 = 3.0; +const LONGEST_SECTION: Bars = 64; const FLAT_SPREAD: f64 = 1e-9; const QUIET_PERCENTILE: f64 = 0.1; const LOUD_PERCENTILE: f64 = 0.95; @@ -52,8 +62,7 @@ impl SectionKind { #[derive(Debug, Clone, PartialEq)] pub struct Section { pub first_beat: BeatIndex, - pub first_bar: BarIndex, - pub bars: usize, + pub beats: Beats, pub kind: SectionKind, /// 0 at the track's quiet end, 1 at its loud end. pub relative_energy: f64, @@ -65,9 +74,13 @@ pub struct Tuning { pub harmony_weight: f64, pub rhythm_weight: f64, pub loudness_weight: f64, - pub kernel_half_widths: [usize; 2], - /// Standard deviations above the track's typical phrase line that a line's novelty must reach. + pub kernel_half_widths: [Bars; 2], + /// Standard deviations of novelty a beat must stand above the track's typical beat to start a section. pub boundary_threshold: f64, + /// Novelty given up for a section of 4, 12, 24, 48 or 64 bars rather than 8, 16 or 32. + pub uncommon_length_cost: f64, + /// Novelty given up for a section of any other whole number of bars. + pub odd_length_cost: f64, /// How far from the quietest section towards the most energetic a section must reach to be a drop. pub drop_energy: f64, } @@ -80,15 +93,18 @@ impl Default for Tuning { rhythm_weight: 1.0, loudness_weight: 0.5, kernel_half_widths: [4, 8], - boundary_threshold: 0.0, + boundary_threshold: 0.25, + uncommon_length_cost: 0.5, + odd_length_cost: 3.0, drop_energy: 0.6, } } } -/// What each bar of the grid sounds like, measured once so it can be segmented many ways. -pub struct BarFeatures { - first_beats: Vec, +/// What the bar starting on each beat of the grid sounds like, measured once so it can be +/// segmented many ways. +pub struct BeatFeatures { + on_downbeat: Vec, timbre: Vec<[f64; BANDS]>, harmony: Vec<[f64; 12]>, kick: Vec, @@ -96,151 +112,229 @@ pub struct BarFeatures { loudness: Vec, } -impl BarFeatures { +impl BeatFeatures { pub fn measure(mono: &[f32], sample_rate: f64, beats: &[Beat]) -> Self { let times: Vec = beats.iter().map(|beat| f64::from(beat.time_ms) / 1000.0).collect(); let stft = spectrum::stft(mono, sample_rate, ONSET_FRAME, ONSET_HOP); let kick = onset::smooth(&onset::flux(&stft, KICK_HZ.0, KICK_HZ.1), 1); let hats = onset::smooth(&onset::flux(&stft, HAT_HZ.0, HAT_HZ.1), 1); let per_beat = downbeat::profiles(&stft, ×, &|t| f64::from(kick.at_time(t))); - let first_beats: Vec = - beats.iter().enumerate().filter(|(_, beat)| beat.number == 1).map(|(index, _)| index).collect(); - - let mut bars = Self { - first_beats: first_beats.clone(), - timbre: Vec::new(), - harmony: Vec::new(), - kick: Vec::new(), - hats: Vec::new(), - loudness: Vec::new(), - }; - for (bar, &first) in first_beats.iter().enumerate() { - let end = first_beats.get(bar + 1).copied().unwrap_or((first + BEATS_PER_BAR).min(beats.len())); - let span = first..end; - bars.timbre.push(mean_rows(&per_beat.bands[span.clone()])); - bars.harmony.push(unit(mean_rows(&per_beat.chroma[span.clone()]))); - bars.kick.push(mean(&per_beat.kick[span.clone()])); - bars.hats.push(mean(×[span.clone()].iter().map(|&t| f64::from(hats.at_time(t))).collect::>())); - bars.loudness.push(mean(&per_beat.bands[span].iter().map(loudness).collect::>())); + let hats_per_beat: Vec = times.iter().map(|&t| f64::from(hats.at_time(t))).collect(); + let loudness_per_beat: Vec = per_beat.bands.iter().map(loudness).collect(); + let bar_from = |first: BeatIndex| first..(first + BEATS_PER_BAR).min(beats.len()); + Self { + on_downbeat: beats.iter().map(|beat| beat.number == 1).collect(), + timbre: (0..beats.len()).map(|beat| mean_rows(&per_beat.bands[bar_from(beat)])).collect(), + harmony: (0..beats.len()).map(|beat| unit(mean_rows(&per_beat.chroma[bar_from(beat)]))).collect(), + kick: (0..beats.len()).map(|beat| mean(&per_beat.kick[bar_from(beat)])).collect(), + hats: (0..beats.len()).map(|beat| mean(&hats_per_beat[bar_from(beat)])).collect(), + loudness: (0..beats.len()).map(|beat| mean(&loudness_per_beat[bar_from(beat)])).collect(), } - bars } - pub fn bars(&self) -> usize { - self.first_beats.len() + pub fn on_downbeat(&self) -> &[bool] { + &self.on_downbeat + } + + /// The same beats with their bars counted from `phase`, the beat of the bar, 0 to 3. + #[must_use] + pub fn counting_bars_from(self, phase: Beats) -> Self { + let on_downbeat = (0..self.beats()).map(|beat| beat % BEATS_PER_BAR == phase).collect(); + Self { on_downbeat, ..self } + } + + pub fn beats(&self) -> Beats { + self.on_downbeat.len() } } -pub fn segment(features: &BarFeatures, tuning: &Tuning) -> Vec
{ - if features.bars() == 0 { +pub fn segment(features: &BeatFeatures, tuning: &Tuning) -> Vec
{ + if features.beats() == 0 { return Vec::new(); } let starts = section_starts(features, tuning); name_sections(features, &starts, tuning) } -fn section_starts(features: &BarFeatures, tuning: &Tuning) -> Vec { - let distances = Distances::between_bars(features, tuning); - let novelty = tuning +fn novelty(distances: &Distances, tuning: &Tuning) -> Vec { + let summed = tuning .kernel_half_widths .iter() .map(|&half_width| standardise(&distances.novelty(half_width))) - .fold(vec![0.0; features.bars()], |sum, part| sum.iter().zip(&part).map(|(a, b)| a + b).collect()); - let lines: Vec = (phrase_phase(&novelty)..features.bars()).step_by(BARS_PER_PHRASE).collect(); - let line_scores = standardise(&lines.iter().map(|&bar| novelty[bar]).collect::>()); - - let mut starts = vec![0]; - for (index, &bar) in lines.iter().enumerate() { - let score = line_scores[index]; - let beats_previous = index == 0 || score >= line_scores[index - 1]; - let beats_next = line_scores.get(index + 1).is_none_or(|&next| score > next); - if bar > 0 && score > tuning.boundary_threshold && beats_previous && beats_next { - starts.push(bar); - } + .fold(vec![0.0; distances.beats], |sum, part| sum.iter().zip(&part).map(|(a, b)| a + b).collect()); + standardise(&summed) +} + +fn length_cost(bars: Bars, tuning: &Tuning) -> f64 { + match bars { + 8 | 16 | 32 => 0.0, + 4 | 12 | 24 | 48 | 64 => tuning.uncommon_length_cost, + _ => tuning.odd_length_cost, } - starts } -/// The bar, 0 to 3, whose 4-bar grid carries the most novelty. -fn phrase_phase(novelty: &[f64]) -> BarIndex { - let line_total = |phase: BarIndex| novelty.iter().skip(phase).step_by(BARS_PER_PHRASE).sum::(); - (0..BARS_PER_PHRASE).max_by(|&a, &b| line_total(a).total_cmp(&line_total(b))).unwrap_or(0) +fn grid_phase(on_downbeat: &[bool]) -> Beats { + on_downbeat.iter().position(|&downbeat| downbeat).unwrap_or(0) % BEATS_PER_BAR +} + +/// How strongly the music changes on each beat of the bar, 0 to 3 counted from the grid's first +/// beat. Each bar is compared only with the one before, since wider comparisons barely notice a +/// shift of one beat. Every clear change then votes for the beat of the bar it peaks on, its vote +/// capped so one outsized change can't outvote the rest. +pub fn bar_phase_votes(features: &BeatFeatures) -> [f64; BEATS_PER_BAR] { + let tuning = Tuning::default(); + bar_phase_votes_between(&Distances::between_beats(features, &tuning, 2 * BEATS_PER_BAR)) +} + +fn bar_phase_votes_between(distances: &Distances) -> [f64; BEATS_PER_BAR] { + let novelty = standardise(&distances.novelty(1)); + let peaks_on = |beat: BeatIndex| { + let around = beat.saturating_sub(PHASE_PEAK_REACH)..(beat + PHASE_PEAK_REACH + 1).min(novelty.len()); + around.into_iter().all(|other| novelty[other] <= novelty[beat]) + }; + let mut votes = [0.0; BEATS_PER_BAR]; + for beat in (PHASE_VOTE_FROM..novelty.len()).filter(|&beat| novelty[beat] > PHASE_VOTE_FLOOR && peaks_on(beat)) { + votes[beat % BEATS_PER_BAR] += novelty[beat].min(PHASE_VOTE_CAP); + } + votes +} + +/// The beat of the bar, 0 to 3, that bars start on: the grid's downbeat, unless the music changes +/// on another beat of the bar `trust` times as strongly across the whole track. +pub fn bar_phase(on_downbeat: &[bool], votes: &[f64; BEATS_PER_BAR], trust: f64) -> Beats { + let grid_phase = grid_phase(on_downbeat); + let strongest = (0..BEATS_PER_BAR).max_by(|&a, &b| votes[a].total_cmp(&votes[b])).unwrap_or(grid_phase); + if votes[strongest] > votes[grid_phase] * trust { + strongest + } else { + grid_phase + } +} + +/// The section starts that earn the most novelty, less what their lengths cost. The track's first +/// beat always starts a section, and the others fall on the grid's downbeats; each section's length +/// is counted from the start before it, so after an odd-length section the rest follow on from it. +fn section_starts(features: &BeatFeatures, tuning: &Tuning) -> Vec { + let widest = tuning.kernel_half_widths.iter().copied().max().unwrap_or(1); + let distances = Distances::between_beats(features, tuning, 2 * widest * BEATS_PER_BAR); + let novelty = novelty(&distances, tuning); + let lines: Vec = + (grid_phase(&features.on_downbeat)..features.beats()).step_by(BEATS_PER_BAR).filter(|&b| b > 0).collect(); + let is_peak = |index: usize| { + let around = index.saturating_sub(1)..(index + 2).min(lines.len()); + around.into_iter().all(|other| novelty[lines[other]] <= novelty[lines[index]]) + }; + + let mut best = vec![f64::NEG_INFINITY; lines.len()]; + let mut previous: Vec> = vec![None; lines.len()]; + for index in (0..lines.len()).filter(|&index| is_peak(index)) { + let gain = novelty[lines[index]] - tuning.boundary_threshold; + best[index] = gain; + for bars in 1..=LONGEST_SECTION.min(index) { + let before = index - bars; + let total = best[before] + gain - length_cost(bars, tuning); + if total > best[index] { + best[index] = total; + previous[index] = Some(before); + } + } + } + + let last = (0..lines.len()).filter(|&index| best[index] > 0.0).max_by(|&a, &b| best[a].total_cmp(&best[b])); + let mut chosen: Vec = + std::iter::successors(last, |&index| previous[index]).map(|index| lines[index]).collect(); + chosen.push(0); + chosen.reverse(); + chosen } +/// Distances between the profiles of beats no further apart than `reach`. struct Distances { - bars: usize, + beats: Beats, + reach: Beats, values: Vec, } impl Distances { - fn between_bars(features: &BarFeatures, tuning: &Tuning) -> Self { - let bars = features.bars(); + fn between_beats(features: &BeatFeatures, tuning: &Tuning, reach: Beats) -> Self { + let beats = features.beats(); let mut columns: Vec<(Vec, f64)> = Vec::new(); let mut add_group = |group: Vec>, weight: f64| { let share = weight / (group.len() as f64).sqrt(); columns.extend(group.into_iter().map(|column| (standardise(&column), share))); }; add_group( - (0..BANDS).map(|band| features.timbre.iter().map(|bar| bar[band]).collect()).collect(), + (0..BANDS).map(|band| features.timbre.iter().map(|beat| beat[band]).collect()).collect(), tuning.timbre_weight, ); add_group( - (0..12).map(|pitch| features.harmony.iter().map(|bar| bar[pitch]).collect()).collect(), + (0..12).map(|pitch| features.harmony.iter().map(|beat| beat[pitch]).collect()).collect(), tuning.harmony_weight, ); add_group(vec![features.kick.clone(), features.hats.clone()], tuning.rhythm_weight); add_group(vec![features.loudness.clone()], tuning.loudness_weight); - let mut values = vec![0.0; bars * bars]; - for a in 0..bars { - for b in (a + 1)..bars { + let mut values = vec![0.0; beats * reach]; + for a in 0..beats { + for offset in 1..=reach.min(beats - 1 - a) { + let b = a + offset; let squared: f64 = columns.iter().map(|(column, share)| (share * (column[a] - column[b])).powi(2)).sum(); - values[a * bars + b] = squared.sqrt(); - values[b * bars + a] = squared.sqrt(); + values[a * reach + offset - 1] = squared.sqrt(); } } - Self { bars, values } + Self { beats, reach, values } } - fn at(&self, a: BarIndex, b: BarIndex) -> f64 { - self.values[a * self.bars + b] + fn at(&self, a: BeatIndex, b: BeatIndex) -> f64 { + let (low, high) = if a < b { (a, b) } else { (b, a) }; + if low == high { + return 0.0; + } + self.values[low * self.reach + (high - low) - 1] } - fn mean_across(&self, left: std::ops::Range, right: std::ops::Range) -> f64 { + fn mean_across(&self, left: &[BeatIndex], right: &[BeatIndex]) -> f64 { let pairs = (left.len() * right.len()) as f64; - left.flat_map(|a| right.clone().map(move |b| (a, b))).map(|(a, b)| self.at(a, b)).sum::() / pairs + left.iter().flat_map(|&a| right.iter().map(move |&b| self.at(a, b))).sum::() / pairs } - fn mean_within(&self, span: std::ops::Range) -> f64 { - let pairs = (span.len() * (span.len() - 1) / 2) as f64; + fn mean_within(&self, bars: &[BeatIndex]) -> f64 { + if bars.len() < 2 { + return 0.0; + } + let pairs = (bars.len() * (bars.len() - 1) / 2) as f64; let total: f64 = - span.clone().flat_map(|a| ((a + 1)..span.end).map(move |b| (a, b))).map(|(a, b)| self.at(a, b)).sum(); + bars.iter().enumerate().flat_map(|(i, &a)| bars[i + 1..].iter().map(move |&b| self.at(a, b))).sum(); total / pairs } - /// For each bar, how unlike the bars before it the bars from it on sound, less how unlike - /// each side sounds within itself. - fn novelty(&self, half_width: usize) -> Vec { - (0..self.bars) + /// For each beat, how unlike the bars counted back from it the bars counted on from it sound, + /// less how unlike each side sounds within itself. + fn novelty(&self, half_width: Bars) -> Vec { + (0..self.beats) .map(|line| { - let before = line.saturating_sub(half_width)..line; - let after = line..(line + half_width).min(self.bars); - if before.len() < MIN_KERNEL_SIDE || after.len() < MIN_KERNEL_SIDE { + let before: Vec = + (1..=half_width).filter_map(|bar| line.checked_sub(bar * BEATS_PER_BAR)).collect(); + let after: Vec = (0..half_width) + .map(|bar| line + bar * BEATS_PER_BAR) + .filter(|&first| first + BEATS_PER_BAR <= self.beats) + .collect(); + if before.len() < half_width.min(MIN_KERNEL_SIDE) || after.len() < half_width.min(MIN_KERNEL_SIDE) { return 0.0; } - let within = (self.mean_within(before.clone()) + self.mean_within(after.clone())) / 2.0; - self.mean_across(before, after) - within + let within = (self.mean_within(&before) + self.mean_within(&after)) / 2.0; + self.mean_across(&before, &after) - within }) .collect() } } -fn name_sections(features: &BarFeatures, starts: &[BarIndex], tuning: &Tuning) -> Vec
{ - let bar_energy = bar_energies(features); - let spans: Vec<(BarIndex, BarIndex)> = - starts.iter().zip(starts.iter().skip(1).copied().chain([features.bars()])).map(|(&a, b)| (a, b)).collect(); - let energies: Vec = spans.iter().map(|&(a, b)| mean(&bar_energy[a..b])).collect(); +fn name_sections(features: &BeatFeatures, starts: &[BeatIndex], tuning: &Tuning) -> Vec
{ + let energy = beat_energies(features); + let spans: Vec<(BeatIndex, BeatIndex)> = + starts.iter().zip(starts.iter().skip(1).copied().chain([features.beats()])).map(|(&a, b)| (a, b)).collect(); + let energies: Vec = spans.iter().map(|&(a, b)| mean(&energy[a..b])).collect(); let last = spans.len() - 1; let frames_the_track = |index: usize| last > 0 && (index == 0 || index == last); let mut is_drop: Vec = energies @@ -261,7 +355,7 @@ fn name_sections(features: &BarFeatures, starts: &[BarIndex], tuning: &Tuning) - spans .iter() .enumerate() - .map(|(index, &(first_bar, end_bar))| { + .map(|(index, &(first_beat, end_beat))| { let leads_into_drop = is_drop.get(index + 1).copied().unwrap_or(false); let kind = if last > 0 && index == 0 { SectionKind::Intro @@ -271,41 +365,34 @@ fn name_sections(features: &BarFeatures, starts: &[BarIndex], tuning: &Tuning) - SectionKind::Drop } else if index > last_drop { SectionKind::Outro - } else if leads_into_drop && rises(&bar_energy[first_bar..end_bar]) { + } else if leads_into_drop { SectionKind::Build } else if index < first_drop { SectionKind::Intro } else { SectionKind::Breakdown }; - Section { - first_beat: features.first_beats[first_bar], - first_bar, - bars: end_bar - first_bar, - kind, - relative_energy: energies[index], - } + Section { first_beat, beats: end_beat - first_beat, kind, relative_energy: energies[index] } }) .collect() } /// Loudness stands for energy: a drop's sustained bass masks its kick's onsets, and a riser's noise /// fills the spectrum as fully as a drop does. The range is taken between percentiles, so a silent -/// tail or one clipped bar doesn't squash every other bar together. -fn bar_energies(features: &BarFeatures) -> Vec { - let mut sorted = features.loudness.clone(); +/// tail or one clipped beat doesn't squash every other beat together. +fn beat_energies(features: &BeatFeatures) -> Vec { + between_percentiles(&features.loudness) +} + +fn between_percentiles(values: &[f64]) -> Vec { + let mut sorted = values.to_vec(); sorted.sort_by(f64::total_cmp); let at = |share: f64| sorted[((sorted.len() - 1) as f64 * share).round() as usize]; - let (quiet, loud) = (at(QUIET_PERCENTILE), at(LOUD_PERCENTILE)); - if loud - quiet < FLAT_SPREAD { - return vec![1.0; sorted.len()]; + let (low, high) = (at(QUIET_PERCENTILE), at(LOUD_PERCENTILE)); + if high - low < FLAT_SPREAD { + return vec![1.0; values.len()]; } - features.loudness.iter().map(|level| ((level - quiet) / (loud - quiet)).clamp(0.0, 1.0)).collect() -} - -fn rises(energies: &[f64]) -> bool { - let half = energies.len() / 2; - half > 0 && mean(&energies[half..]) - mean(&energies[..half]) > MIN_BUILD_RISE + values.iter().map(|value| ((value - low) / (high - low)).clamp(0.0, 1.0)).collect() } fn loudness(bands: &[f64; BANDS]) -> f64 { @@ -357,7 +444,7 @@ mod tests { #[derive(Clone, Copy)] struct Part { - bars: usize, + beats: usize, kick: bool, bass: bool, hats: bool, @@ -365,16 +452,19 @@ mod tests { riser: bool, } - const SILENT: Part = Part { bars: 0, kick: false, bass: false, hats: false, pad: false, riser: false }; + const SILENT: Part = Part { beats: 0, kick: false, bass: false, hats: false, pad: false, riser: false }; - fn render(parts: &[Part]) -> (Vec, Vec) { + fn bars(count: usize, part: Part) -> Part { + Part { beats: count * BEATS_PER_BAR, ..part } + } + + /// Audio for `parts` in turn, and a grid whose bars start `downbeat_offset` beats in. + fn render(parts: &[Part], downbeat_offset: usize) -> (Vec, Vec) { let beat_seconds = 60.0 / BPM; let mut audio = Vec::new(); - let mut beats = Vec::new(); let mut noise = 7u32; - let mut beat_count = 0usize; for part in parts { - let samples = (part.bars as f64 * 4.0 * beat_seconds * RATE) as usize; + let samples = (part.beats as f64 * beat_seconds * RATE) as usize; for i in 0..samples { let t = i as f64 / RATE; let progress = i as f64 / samples as f64; @@ -400,43 +490,72 @@ mod tests { } audio.push(v as f32); } - for _ in 0..part.bars * 4 { - let time_ms = (beat_count as f64 * beat_seconds * 1000.0).round() as u32; - beats.push(Beat { number: (beat_count % 4) as u8 + 1, tempo_x100: 12_800, time_ms }); - beat_count += 1; - } } + let total: usize = parts.iter().map(|part| part.beats).sum(); + let beats = (0..total) + .map(|index| Beat { + number: ((index + BEATS_PER_BAR - downbeat_offset % BEATS_PER_BAR) % BEATS_PER_BAR) as u8 + 1, + tempo_x100: 12_800, + time_ms: (index as f64 * beat_seconds * 1000.0).round() as u32, + }) + .collect(); (audio, beats) } - #[test] - fn finds_and_names_the_sections_of_a_dance_track() { - let intro = Part { bars: 16, kick: true, hats: true, ..SILENT }; - let drop = Part { bars: 16, kick: true, bass: true, hats: true, pad: true, ..SILENT }; - let breakdown = Part { bars: 16, pad: true, ..SILENT }; - let build = Part { bars: 8, pad: true, riser: true, ..SILENT }; - let outro = Part { bars: 16, kick: true, ..SILENT }; - let (audio, beats) = render(&[intro, drop, breakdown, build, drop, outro]); + fn found(parts: &[Part], downbeat_offset: usize) -> Vec<(BeatIndex, SectionKind)> { + let (audio, beats) = render(parts, downbeat_offset); + let sections = segment(&BeatFeatures::measure(&audio, RATE, &beats), &Tuning::default()); + sections.iter().map(|section| (section.first_beat, section.kind)).collect() + } - let sections = segment(&BarFeatures::measure(&audio, RATE, &beats), &Tuning::default()); + const INTRO: Part = Part { kick: true, hats: true, ..SILENT }; + const DROP: Part = Part { kick: true, bass: true, hats: true, pad: true, ..SILENT }; + const BREAKDOWN: Part = Part { pad: true, ..SILENT }; + const BUILD: Part = Part { pad: true, riser: true, ..SILENT }; + const OUTRO: Part = Part { kick: true, ..SILENT }; - let found: Vec<(BarIndex, SectionKind)> = sections.iter().map(|s| (s.first_bar, s.kind)).collect(); + #[test] + fn finds_and_names_the_sections_of_a_dance_track() { + let parts = + [bars(16, INTRO), bars(16, DROP), bars(16, BREAKDOWN), bars(8, BUILD), bars(16, DROP), bars(16, OUTRO)]; assert_eq!( - found, + found(&parts, 0), [ (0, SectionKind::Intro), - (16, SectionKind::Drop), - (32, SectionKind::Breakdown), - (48, SectionKind::Build), - (56, SectionKind::Drop), - (72, SectionKind::Outro), + (64, SectionKind::Drop), + (128, SectionKind::Breakdown), + (192, SectionKind::Build), + (224, SectionKind::Drop), + (288, SectionKind::Outro), ] ); - assert_eq!(sections[1].first_beat, 64); } #[test] - fn a_grid_without_bars_has_no_sections() { - assert!(segment(&BarFeatures::measure(&[0.0; 4410], RATE, &[]), &Tuning::default()).is_empty()); + fn bars_move_off_the_grid_downbeat_only_for_clearly_stronger_changes() { + let grid_on_beat_one = [false, true, false, false, false, true]; + assert_eq!(bar_phase(&grid_on_beat_one, &[2.0, 3.0, 0.0, 0.0], 3.0), 1); + assert_eq!(bar_phase(&grid_on_beat_one, &[10.0, 3.0, 0.0, 0.0], 3.0), 0); + assert_eq!(bar_phase(&grid_on_beat_one, &[0.0, 0.0, 0.0, 0.0], 3.0), 1); + } + + #[test] + fn a_short_sweep_before_the_intro_does_not_shift_the_sections_after_it() { + let sweep = Part { beats: 2, riser: true, ..SILENT }; + let parts = [sweep, bars(16, INTRO), bars(16, DROP), bars(16, BREAKDOWN), bars(16, DROP), bars(16, OUTRO)]; + let starts: Vec = found(&parts, 2).iter().map(|&(beat, _)| beat).collect(); + assert_eq!(starts, [0, 66, 130, 194, 258]); + } + + #[test] + fn sections_after_an_odd_length_one_count_on_from_it() { + let parts = [bars(16, INTRO), bars(7, BREAKDOWN), bars(16, DROP), bars(16, BREAKDOWN), bars(16, OUTRO)]; + let starts: Vec = found(&parts, 0).iter().map(|&(beat, _)| beat).collect(); + assert_eq!(starts, [0, 64, 92, 156, 220]); + } + + #[test] + fn a_grid_without_beats_has_no_sections() { + assert!(segment(&BeatFeatures::measure(&[0.0; 4410], RATE, &[]), &Tuning::default()).is_empty()); } } From 9d5577a16c0e9add400a83f1e051b6303dbc33e1 Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 16:40:41 +0000 Subject: [PATCH 09/25] Let a track's last section be a drop The last section was always named the outro. With longer sections the last drop often runs to the end, so it became the outro and every section after the first drop was named an outro with it. Now only the opening section is framed as the intro; the last section is an outro by the same rule as any other, coming after the last drop. Beats whose kind agrees with rekordbox's go from 63.7% to 67.4%, and beats rekordbox calls a drop that we called an outro from 3,042 to 285. Co-Authored-By: Claude Opus 5.5 --- native/crates/es-analyse/src/structure.rs | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/native/crates/es-analyse/src/structure.rs b/native/crates/es-analyse/src/structure.rs index ac3eb33..3d6a34a 100644 --- a/native/crates/es-analyse/src/structure.rs +++ b/native/crates/es-analyse/src/structure.rs @@ -336,15 +336,15 @@ fn name_sections(features: &BeatFeatures, starts: &[BeatIndex], tuning: &Tuning) starts.iter().zip(starts.iter().skip(1).copied().chain([features.beats()])).map(|(&a, b)| (a, b)).collect(); let energies: Vec = spans.iter().map(|&(a, b)| mean(&energy[a..b])).collect(); let last = spans.len() - 1; - let frames_the_track = |index: usize| last > 0 && (index == 0 || index == last); + let opens_the_track = |index: usize| last > 0 && index == 0; let mut is_drop: Vec = energies .iter() .enumerate() - .map(|(index, &energy)| !frames_the_track(index) && energy >= tuning.drop_energy) + .map(|(index, &energy)| !opens_the_track(index) && energy >= tuning.drop_energy) .collect(); if !is_drop.contains(&true) { let loudest_inside = - (0..=last).filter(|&index| !frames_the_track(index)).max_by(|&a, &b| energies[a].total_cmp(&energies[b])); + (0..=last).filter(|&index| !opens_the_track(index)).max_by(|&a, &b| energies[a].total_cmp(&energies[b])); if let Some(index) = loudest_inside { is_drop[index] = true; } @@ -357,10 +357,8 @@ fn name_sections(features: &BeatFeatures, starts: &[BeatIndex], tuning: &Tuning) .enumerate() .map(|(index, &(first_beat, end_beat))| { let leads_into_drop = is_drop.get(index + 1).copied().unwrap_or(false); - let kind = if last > 0 && index == 0 { + let kind = if opens_the_track(index) { SectionKind::Intro - } else if last > 0 && index == last { - SectionKind::Outro } else if is_drop[index] { SectionKind::Drop } else if index > last_drop { @@ -554,6 +552,16 @@ mod tests { assert_eq!(starts, [0, 64, 92, 156, 220]); } + #[test] + fn a_last_drop_that_runs_to_the_end_keeps_the_sections_before_it_out_of_the_outro() { + let parts = [bars(16, INTRO), bars(16, DROP), bars(16, BREAKDOWN), bars(8, BUILD), bars(32, DROP)]; + let kinds: Vec = found(&parts, 0).iter().map(|&(_, kind)| kind).collect(); + assert_eq!( + kinds, + [SectionKind::Intro, SectionKind::Drop, SectionKind::Breakdown, SectionKind::Build, SectionKind::Drop] + ); + } + #[test] fn a_grid_without_beats_has_no_sections() { assert!(segment(&BeatFeatures::measure(&[0.0; 4410], RATE, &[]), &Tuning::default()).is_empty()); From 963f85d3fa28ea0d69702078a546580fdeb20eb9 Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 16:51:30 +0000 Subject: [PATCH 10/25] Learn a DJ's cue style from tracks they have cued cue_style learns rules tied to sections ("every drop", "16 bars before the first drop", "every section, then every 32 bars") by greedily adding the rule that most raises the F1 of its cues against the DJ's, among rules that find cues on at least 10% of the tracks. Memory cues learn a set of rules; hot cues learn one single-cue rule per pad by the same search. Placing skips cues within a bar of one already placed. The cue_style_eval example cross-validates a style over a cue_survey dump. Learnt styles match or beat a cue on every section start (Uk 0.601 vs 0.590, DnB 0.555 vs 0.537) and pick up genre habits, such as cueing DnB sections again every 32 bars. The survey reading and scoring the two examples share now live in examples/survey. Co-Authored-By: Claude Opus 5.5 --- .../es-analyse/examples/cue_style_eval.rs | 192 +++++++++++ .../es-analyse/examples/structure_eval.rs | 92 +----- .../crates/es-analyse/examples/survey/mod.rs | 107 ++++++ native/crates/es-analyse/src/cue_style.rs | 312 ++++++++++++++++++ native/crates/es-analyse/src/lib.rs | 1 + native/crates/es-analyse/src/structure.rs | 2 +- 6 files changed, 619 insertions(+), 87 deletions(-) create mode 100644 native/crates/es-analyse/examples/cue_style_eval.rs create mode 100644 native/crates/es-analyse/examples/survey/mod.rs create mode 100644 native/crates/es-analyse/src/cue_style.rs diff --git a/native/crates/es-analyse/examples/cue_style_eval.rs b/native/crates/es-analyse/examples/cue_style_eval.rs new file mode 100644 index 0000000..1f78091 --- /dev/null +++ b/native/crates/es-analyse/examples/cue_style_eval.rs @@ -0,0 +1,192 @@ +//! How well a cue style learnt from some of a DJ's tracks places their memory cues on the rest, +//! using a dump from `es-index`'s `cue_survey` example. Tracks are split into folds; each fold's +//! cues are placed by a style learnt from all the others, and compared with where the DJ put them. +//! `cargo run --release -p es-analyse --example cue_style_eval -- survey.json` + +use std::collections::{BTreeMap, HashSet}; +use std::path::Path; + +use es_analyse::cue_style::{CueRule, CuedTrack, HotCueSlot, HotCueStyle, Learning, MemoryCueStyle, Which}; +use es_analyse::structure::{segment, BeatFeatures, BeatIndex, Section, Tuning}; +use es_analyse::{decode_mono, SAMPLE_RATE}; +use rayon::prelude::*; +use serde_json::Value; + +#[path = "survey/mod.rs"] +mod survey; +use survey::{nearest_beat, survey_grid, Score, BEATS_PER_BAR, SURVEY_ON_BEAT_MS}; + +const FOLDS: usize = 10; +const MEMORY_CUE_LIMIT: usize = 10; + +struct Track { + sections: Vec
, + beat_count: usize, + first_downbeat: BeatIndex, + memory_cues: HashSet, + hot_cues: Vec<(HotCueSlot, BeatIndex)>, +} + +impl Track { + fn cued(&self, cues: HashSet) -> CuedTrack { + CuedTrack { sections: self.sections.clone(), beat_count: self.beat_count, cues } + } +} + +fn main() -> Result<(), Box> { + let path = std::env::args().nth(1).ok_or("pass the survey JSON from cue_survey")?; + let survey = survey::load(&path)?; + let tracks: Vec = survey.par_iter().filter_map(measure).collect(); + let memory: Vec<&Track> = tracks.iter().filter(|track| !track.memory_cues.is_empty()).collect(); + println!("measured {} of {} tracks, {} with memory cues\n", tracks.len(), survey.len(), memory.len()); + + report_baselines(&memory); + for least_track_share in [0.02, 0.05, 0.1, 0.2] { + let score = cross_validate(&memory, &Learning { least_track_share }); + println!("{}", score.line(&format!("learnt, rules on {}%+ of tracks", least_track_share * 100.0))); + } + report_style(&memory); + report_missed(&memory); + report_hot_cues(&tracks); + Ok(()) +} + +fn measure(entry: &Value) -> Option { + let beats = survey_grid(entry); + if beats.len() < 2 { + return None; + } + let audio = decode_mono(Path::new(entry["path"].as_str()?)).ok()?; + let sections = segment(&BeatFeatures::measure(&audio, f64::from(SAMPLE_RATE), &beats), &Tuning::default()); + let mut memory_cues = HashSet::new(); + let mut hot_cues = Vec::new(); + for cue in entry["cues"].as_array()? { + let Some(beat) = cue["startMs"].as_f64().and_then(|ms| nearest_beat(&beats, ms, SURVEY_ON_BEAT_MS)) else { + continue; + }; + match cue["hotSlot"].as_str().and_then(|letter| letter.bytes().next()) { + Some(letter) => hot_cues.push((letter - b'A' + 1, beat)), + None => { + memory_cues.insert(beat); + } + } + } + Some(Track { + sections, + beat_count: beats.len(), + first_downbeat: beats.iter().position(|beat| beat.number == 1).unwrap_or(0), + memory_cues, + hot_cues, + }) +} + +fn report_baselines(tracks: &[&Track]) { + let (mut every_start, mut every_16_bars) = (Score::default(), Score::default()); + for track in tracks { + every_start.add(&track.memory_cues, &track.sections.iter().map(|s| s.first_beat).collect()); + let grid = (track.first_downbeat..track.beat_count).step_by(16 * BEATS_PER_BAR); + every_16_bars.add(&track.memory_cues, &grid.collect()); + } + println!("{}", every_start.line("a cue on every section start")); + println!("{}", every_16_bars.line("a cue every 16 bars")); +} + +fn cross_validate(tracks: &[&Track], learning: &Learning) -> Score { + let scores: Vec = (0..FOLDS) + .into_par_iter() + .map(|fold| { + let training: Vec = tracks + .iter() + .enumerate() + .filter(|(index, _)| index % FOLDS != fold) + .map(|(_, track)| track.cued(track.memory_cues.clone())) + .collect(); + let style = MemoryCueStyle::learn(&training, learning); + let mut score = Score::default(); + for track in tracks.iter().enumerate().filter(|(index, _)| index % FOLDS == fold).map(|(_, track)| track) { + let placed = style.place(&track.sections, track.beat_count, MEMORY_CUE_LIMIT); + score.add(&track.memory_cues, &placed.into_iter().collect()); + } + score + }) + .collect(); + scores.into_iter().fold(Score::default(), |total, fold| total.merged(&fold)) +} + +fn describe(rule: &CueRule) -> String { + let which = match rule.which { + Which::Nth(n) => format!("#{n}"), + Which::Last => "last".to_owned(), + Which::Every => "every".to_owned(), + }; + let kind = rule.kind.map_or("section", |kind| kind.name()); + let offset = match rule.bars_from_start { + 0 => "start".to_owned(), + bars => format!("{bars:+} bars"), + }; + let repeat = rule.then_every.map(|bars| format!(", then every {bars} bars")).unwrap_or_default(); + format!("{which} {kind}, {offset}{repeat}") +} + +fn report_style(tracks: &[&Track]) { + let training: Vec = tracks.iter().map(|track| track.cued(track.memory_cues.clone())).collect(); + let style = MemoryCueStyle::learn(&training, &Learning::default()); + println!("\nmemory cue style learnt from all {} tracks:", tracks.len()); + for learnt in &style.rules { + println!( + " {:<32} finds {:>4} cues, misplaces {:>4}", + describe(&learnt.rule), + learnt.cues_found, + learnt.cues_misplaced + ); + } +} + +/// Where the cues a style learnt from every track still misses sit, as bars into the section that +/// holds them and how long that section is. +fn report_missed(tracks: &[&Track]) { + let training: Vec = tracks.iter().map(|track| track.cued(track.memory_cues.clone())).collect(); + let style = MemoryCueStyle::learn(&training, &Learning::default()); + let mut into: BTreeMap = BTreeMap::new(); + let mut missed = 0; + for track in tracks { + let placed: HashSet = + style.place(&track.sections, track.beat_count, MEMORY_CUE_LIMIT).into_iter().collect(); + for &cue in track.memory_cues.difference(&placed) { + missed += 1; + let Some(section) = track.sections.iter().rev().find(|section| section.first_beat <= cue) else { continue }; + let bars = |beats: usize| beats as f64 / BEATS_PER_BAR as f64; + let key = format!( + "{:>5} bars into a {:>4}-bar {}", + bars(cue - section.first_beat), + bars(section.beats), + section.kind.name() + ); + *into.entry(key).or_default() += 1; + } + } + let mut rows: Vec<_> = into.into_iter().collect(); + rows.sort_by_key(|(_, count)| std::cmp::Reverse(*count)); + println!("\n{missed} cues missed; the commonest places:"); + for (place, count) in rows.into_iter().take(20) { + println!(" {count:>4} {place}"); + } +} + +fn report_hot_cues(tracks: &[Track]) { + let mut by_pad: BTreeMap> = BTreeMap::new(); + for track in tracks { + for &(slot, beat) in &track.hot_cues { + by_pad.entry(slot).or_default().push(track.cued(HashSet::from([beat]))); + } + } + if by_pad.is_empty() { + return; + } + let by_pad: Vec<(HotCueSlot, Vec)> = by_pad.into_iter().collect(); + let style = HotCueStyle::learn(&by_pad, &Learning::default()); + println!("\nhot cue style ({} hot cues in the survey):", by_pad.iter().map(|(_, t)| t.len()).sum::()); + for (slot, learnt) in &style.pads { + println!(" pad {}: {}", char::from(b'A' + slot - 1), describe(&learnt.rule)); + } +} diff --git a/native/crates/es-analyse/examples/structure_eval.rs b/native/crates/es-analyse/examples/structure_eval.rs index 23c43a9..fb1328b 100644 --- a/native/crates/es-analyse/examples/structure_eval.rs +++ b/native/crates/es-analyse/examples/structure_eval.rs @@ -12,14 +12,15 @@ use std::path::Path; use es_analyse::structure::{ bar_phase, bar_phase_votes, segment, BeatFeatures, BeatIndex, Section, SectionKind, Tuning, }; -use es_analyse::{analyse_samples, decode_mono, Beat, Options, SAMPLE_RATE}; +use es_analyse::{analyse_samples, decode_mono, Options, SAMPLE_RATE}; use rayon::prelude::*; use serde_json::Value; -const SURVEY_ON_BEAT_MS: f64 = 15.0; +#[path = "survey/mod.rs"] +mod survey; +use survey::{nearest_beat, share, survey_grid, Score, BEATS_PER_BAR, SURVEY_ON_BEAT_MS}; + const OUR_GRID_ON_BEAT_SHARE: f64 = 0.25; -const NEAR_MISS_BEATS: usize = 8; -const BEATS_PER_BAR: usize = 4; struct Track { title: String, @@ -33,63 +34,11 @@ struct Track { downbeat_offset: Option, } -#[derive(Default, Clone, Copy)] -struct Score { - cues: usize, - starts: usize, - hits: usize, - near_misses: usize, - tracks: usize, -} - -impl Score { - fn add(&mut self, cues: &HashSet, starts: &HashSet) { - self.cues += cues.len(); - self.starts += starts.len(); - self.hits += cues.intersection(starts).count(); - self.near_misses += cues - .iter() - .filter(|&&cue| { - !starts.contains(&cue) && starts.iter().any(|&start| start.abs_diff(cue) <= NEAR_MISS_BEATS) - }) - .count(); - self.tracks += 1; - } - - fn recall(&self) -> f64 { - self.hits as f64 / self.cues.max(1) as f64 - } - - fn precision(&self) -> f64 { - self.hits as f64 / self.starts.max(1) as f64 - } - - fn f1(&self) -> f64 { - let (p, r) = (self.precision(), self.recall()); - if p + r == 0.0 { - 0.0 - } else { - 2.0 * p * r / (p + r) - } - } - - fn line(&self, name: &str) -> String { - format!( - "{name:<34} recall {:>5.1}% precision {:>5.1}% F1 {:.3} near misses {:>4.1}% starts/track {:>5.1}", - 100.0 * self.recall(), - 100.0 * self.precision(), - self.f1(), - 100.0 * self.near_misses as f64 / self.cues.max(1) as f64, - self.starts as f64 / self.tracks.max(1) as f64, - ) - } -} - fn main() -> Result<(), Box> { let mut args = std::env::args().skip(1); let path = args.next().ok_or("pass the survey JSON from cue_survey")?; let our_grid = args.any(|arg| arg == "--our-grid"); - let survey: Vec = serde_json::from_str(&std::fs::read_to_string(path)?)?; + let survey = survey::load(&path)?; let tracks: Vec = survey.par_iter().filter_map(|entry| measure(entry, our_grid)).collect(); println!("measured {} of {} tracks{}\n", tracks.len(), survey.len(), if our_grid { " on our grid" } else { "" }); @@ -113,31 +62,6 @@ fn main() -> Result<(), Box> { Ok(()) } -fn numbers(value: &Value) -> Vec { - value.as_array().map(|all| all.iter().filter_map(Value::as_u64).collect()).unwrap_or_default() -} - -fn survey_grid(entry: &Value) -> Vec { - let times = numbers(&entry["grid"]["times"]); - let beat_numbers = numbers(&entry["grid"]["beats"]); - times - .iter() - .zip(&beat_numbers) - .map(|(&time_ms, &number)| Beat { number: number as u8, tempo_x100: 0, time_ms: time_ms as u32 }) - .collect() -} - -fn nearest_beat(beats: &[Beat], ms: f64, tolerance_ms: f64) -> Option { - let after = beats.partition_point(|beat| f64::from(beat.time_ms) < ms); - let distance = |index: usize| (f64::from(beats[index].time_ms) - ms).abs(); - [after.checked_sub(1), Some(after)] - .into_iter() - .flatten() - .filter(|&index| index < beats.len()) - .min_by(|&a, &b| distance(a).total_cmp(&distance(b))) - .filter(|&index| distance(index) <= tolerance_ms) -} - fn measure(entry: &Value, our_grid: bool) -> Option { let audio = decode_mono(Path::new(entry["path"].as_str()?)).ok()?; let rate = f64::from(SAMPLE_RATE); @@ -365,10 +289,6 @@ fn label_agreement(tracks: &[Track], tuning: &Tuning) -> LabelAgreement { agreement } -fn share(agreed: usize, total: usize) -> f64 { - 100.0 * agreed as f64 / total.max(1) as f64 -} - fn report_labels(tracks: &[Track], tuning: &Tuning) { if tracks.iter().all(|t| t.rekordbox_beat_kinds.is_none()) { return; diff --git a/native/crates/es-analyse/examples/survey/mod.rs b/native/crates/es-analyse/examples/survey/mod.rs new file mode 100644 index 0000000..2b78928 --- /dev/null +++ b/native/crates/es-analyse/examples/survey/mod.rs @@ -0,0 +1,107 @@ +//! Reading a `cue_survey` dump, and scoring placed beats against the DJ's cues, for the examples. + +#![allow(dead_code)] + +use std::collections::HashSet; + +use es_analyse::structure::BeatIndex; +use es_analyse::Beat; +use serde_json::Value; + +pub const SURVEY_ON_BEAT_MS: f64 = 15.0; +pub const NEAR_MISS_BEATS: usize = 8; +pub const BEATS_PER_BAR: usize = 4; + +pub fn load(path: &str) -> Result, Box> { + Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?) +} + +pub fn share(agreed: usize, total: usize) -> f64 { + 100.0 * agreed as f64 / total.max(1) as f64 +} + +pub fn numbers(value: &Value) -> Vec { + value.as_array().map(|all| all.iter().filter_map(Value::as_u64).collect()).unwrap_or_default() +} + +pub fn survey_grid(entry: &Value) -> Vec { + let times = numbers(&entry["grid"]["times"]); + let beat_numbers = numbers(&entry["grid"]["beats"]); + times + .iter() + .zip(&beat_numbers) + .map(|(&time_ms, &number)| Beat { number: number as u8, tempo_x100: 0, time_ms: time_ms as u32 }) + .collect() +} + +pub fn nearest_beat(beats: &[Beat], ms: f64, tolerance_ms: f64) -> Option { + let after = beats.partition_point(|beat| f64::from(beat.time_ms) < ms); + let distance = |index: usize| (f64::from(beats[index].time_ms) - ms).abs(); + [after.checked_sub(1), Some(after)] + .into_iter() + .flatten() + .filter(|&index| index < beats.len()) + .min_by(|&a, &b| distance(a).total_cmp(&distance(b))) + .filter(|&index| distance(index) <= tolerance_ms) +} + +/// Placed beats against the DJ's cues: on the very beat, or a near miss within a couple of bars. +#[derive(Default, Clone, Copy)] +pub struct Score { + cues: usize, + placed: usize, + hits: usize, + near_misses: usize, + tracks: usize, +} + +impl Score { + pub fn add(&mut self, cues: &HashSet, placed: &HashSet) { + self.cues += cues.len(); + self.placed += placed.len(); + self.hits += cues.intersection(placed).count(); + self.near_misses += cues + .iter() + .filter(|&&cue| !placed.contains(&cue) && placed.iter().any(|&beat| beat.abs_diff(cue) <= NEAR_MISS_BEATS)) + .count(); + self.tracks += 1; + } + + pub fn merged(self, other: &Score) -> Score { + Score { + cues: self.cues + other.cues, + placed: self.placed + other.placed, + hits: self.hits + other.hits, + near_misses: self.near_misses + other.near_misses, + tracks: self.tracks + other.tracks, + } + } + + pub fn recall(&self) -> f64 { + self.hits as f64 / self.cues.max(1) as f64 + } + + pub fn precision(&self) -> f64 { + self.hits as f64 / self.placed.max(1) as f64 + } + + pub fn f1(&self) -> f64 { + let (p, r) = (self.precision(), self.recall()); + if p + r == 0.0 { + 0.0 + } else { + 2.0 * p * r / (p + r) + } + } + + pub fn line(&self, name: &str) -> String { + format!( + "{name:<34} recall {:>5.1}% precision {:>5.1}% F1 {:.3} near misses {:>4.1}% placed/track {:>5.1}", + 100.0 * self.recall(), + 100.0 * self.precision(), + self.f1(), + 100.0 * self.near_misses as f64 / self.cues.max(1) as f64, + self.placed as f64 / self.tracks.max(1) as f64, + ) + } +} diff --git a/native/crates/es-analyse/src/cue_style.rs b/native/crates/es-analyse/src/cue_style.rs new file mode 100644 index 0000000..19e003c --- /dev/null +++ b/native/crates/es-analyse/src/cue_style.rs @@ -0,0 +1,312 @@ +//! A DJ's way of placing cues, learnt from tracks they have cued and replayed on new ones. +//! +//! A style is a list of rules, each a number of bars from the start of some section: "on every +//! drop", "16 bars before the first drop", "on the second breakdown", "on every drop and every 16 +//! bars through it". Rules are tied to sections rather than to bar counts from the top, because no +//! two tracks share a layout. +//! +//! Learning is greedy. Every rule that could be written is tried on every cued track; the rule that +//! most raises the F1 score of the kept rules' cues against the DJ's (balancing cues found against +//! cues put where the DJ had none) is kept, and the search repeats until no rule raises it. Memory cues learn a set of rules. Hot cues learn one rule per pad, by the same +//! search held to rules that give a single cue. + +use std::collections::HashSet; + +use crate::structure::{BeatIndex, Section, SectionKind}; + +pub type BarOffset = i32; +pub type Bars = u16; +pub type HotCueSlot = u8; + +const BEATS_PER_BAR: i64 = 4; +const OFFSETS: [BarOffset; 9] = [-32, -16, -8, -4, 0, 4, 8, 16, 32]; +const REPEATS: [Bars; 3] = [8, 16, 32]; +const LATEST_OCCURRENCE: u8 = 4; +/// Cues nearer than this to one already placed are left out. +const MIN_GAP_BEATS: usize = 4; + +/// Which of the sections of a kind a rule counts from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Which { + /// 1-based. + Nth(u8), + Last, + Every, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct CueRule { + /// `None` counts sections of every kind. + pub kind: Option, + pub which: Which, + pub bars_from_start: BarOffset, + /// Cue again this many bars on, and on, until the section ends. + pub then_every: Option, +} + +impl CueRule { + /// The beats this rule cues on a track with these sections and this many beats. + pub fn place(&self, sections: &[Section], beat_count: usize) -> Vec { + let matching: Vec<&Section> = + sections.iter().filter(|section| self.kind.is_none_or(|kind| section.kind == kind)).collect(); + let anchors: Vec<&Section> = match self.which { + Which::Every => matching, + Which::Last => matching.last().copied().into_iter().collect(), + Which::Nth(n) => matching.get(usize::from(n).saturating_sub(1)).copied().into_iter().collect(), + }; + anchors + .iter() + .flat_map(|section| { + let first = i64::try_from(section.first_beat).unwrap_or(i64::MAX); + let end = first.saturating_add(i64::try_from(section.beats).unwrap_or(0)); + let step = self.then_every.map(|bars| i64::from(bars) * BEATS_PER_BAR); + let start = first + i64::from(self.bars_from_start) * BEATS_PER_BAR; + std::iter::successors(Some(start), move |&beat| step.map(|step| beat + step).filter(|&next| next < end)) + }) + .filter_map(|beat| usize::try_from(beat).ok().filter(|&beat| beat < beat_count)) + .collect() + } + + fn gives_one_cue(&self) -> bool { + self.which != Which::Every && self.then_every.is_none() + } +} + +/// One track's sections and the cues the DJ put on it, of the kind being learnt. +pub struct CuedTrack { + pub sections: Vec
, + pub beat_count: usize, + pub cues: HashSet, +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Learning { + /// The share of training tracks a rule must find a cue on to be kept, so that a coincidence on + /// one or two tracks isn't learnt as a habit. + pub least_track_share: f64, +} + +impl Default for Learning { + fn default() -> Self { + Self { least_track_share: 0.1 } + } +} + +/// A rule kept by learning, with how often it found the DJ's cues. +#[derive(Debug, Clone, PartialEq)] +pub struct LearntRule { + pub rule: CueRule, + pub cues_found: usize, + pub cues_misplaced: usize, +} + +fn every_rule() -> Vec { + let kinds = std::iter::once(None).chain(SectionKind::ALL.into_iter().map(Some)); + let whiches: Vec = (1..=LATEST_OCCURRENCE).map(Which::Nth).chain([Which::Last, Which::Every]).collect(); + let kinds: Vec> = kinds.collect(); + let mut rules = Vec::new(); + for &kind in &kinds { + for &which in &whiches { + for &bars_from_start in &OFFSETS { + rules.push(CueRule { kind, which, bars_from_start, then_every: None }); + } + for &bars in &REPEATS { + rules.push(CueRule { kind, which, bars_from_start: 0, then_every: Some(bars) }); + } + } + } + rules +} + +/// The rules that find the most of the DJ's cues, most valuable first, at most `limit` of them. +fn learn_rules( + tracks: &[CuedTrack], + learning: &Learning, + limit: usize, + allowed: impl Fn(&CueRule) -> bool, +) -> Vec { + let candidates: Vec<(CueRule, Vec>)> = every_rule() + .into_iter() + .filter(|rule| allowed(rule)) + .map(|rule| (rule, tracks.iter().map(|track| rule.place(&track.sections, track.beat_count)).collect())) + .collect(); + let cue_count: usize = tracks.iter().map(|track| track.cues.len()).sum(); + let least_tracks = (learning.least_track_share * tracks.len() as f64).ceil() as usize; + let mut placed: Vec> = vec![HashSet::new(); tracks.len()]; + let (mut found_so_far, mut placed_so_far) = (0, 0); + let mut kept = Vec::new(); + while kept.len() < limit { + let added_by = |placements: &Vec>| { + let (mut found, mut misplaced, mut tracks_found_on) = (0, 0, 0); + for ((beats, track), already) in placements.iter().zip(tracks).zip(&placed) { + let fresh: HashSet<&BeatIndex> = beats.iter().filter(|beat| !already.contains(beat)).collect(); + let found_here = fresh.iter().filter(|beat| track.cues.contains(beat)).count(); + found += found_here; + misplaced += fresh.len() - found_here; + tracks_found_on += usize::from(found_here > 0); + } + (found, misplaced, tracks_found_on) + }; + let f1_with = |found: usize, misplaced: usize| { + 2.0 * (found_so_far + found) as f64 / (placed_so_far + found + misplaced + cue_count).max(1) as f64 + }; + let best = candidates + .iter() + .map(|(rule, placements)| (rule, placements, added_by(placements))) + .filter(|(_, _, (_, _, tracks_found_on))| *tracks_found_on >= least_tracks.max(1)) + .max_by(|a, b| f1_with(a.2 .0, a.2 .1).total_cmp(&f1_with(b.2 .0, b.2 .1))); + let Some((rule, placements, (found, misplaced, _))) = best else { break }; + if f1_with(found, misplaced) <= f1_with(0, 0) { + break; + } + for (already, beats) in placed.iter_mut().zip(placements) { + already.extend(beats); + } + found_so_far += found; + placed_so_far += found + misplaced; + kept.push(LearntRule { rule: *rule, cues_found: found, cues_misplaced: misplaced }); + } + kept +} + +/// Where the rules put cues on one track, in the rules' order of value, skipping any too near a +/// cue already placed, at most `limit` of them. +fn place_all(rules: &[CueRule], sections: &[Section], beat_count: usize, limit: usize) -> Vec { + let mut placed: Vec = Vec::new(); + for beat in rules.iter().flat_map(|rule| rule.place(sections, beat_count)) { + if placed.len() < limit && placed.iter().all(|&other| other.abs_diff(beat) >= MIN_GAP_BEATS) { + placed.push(beat); + } + } + placed.sort_unstable(); + placed +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MemoryCueStyle { + pub rules: Vec, +} + +impl MemoryCueStyle { + pub fn learn(tracks: &[CuedTrack], learning: &Learning) -> Self { + Self { rules: learn_rules(tracks, learning, usize::MAX, |_| true) } + } + + pub fn place(&self, sections: &[Section], beat_count: usize, limit: usize) -> Vec { + let rules: Vec = self.rules.iter().map(|learnt| learnt.rule).collect(); + place_all(&rules, sections, beat_count, limit) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct HotCueStyle { + pub pads: Vec<(HotCueSlot, LearntRule)>, +} + +impl HotCueStyle { + /// `tracks_by_pad` holds, for each pad, every training track with only that pad's cue. + pub fn learn(tracks_by_pad: &[(HotCueSlot, Vec)], learning: &Learning) -> Self { + let pads = tracks_by_pad + .iter() + .filter_map(|(slot, tracks)| { + let learnt = learn_rules(tracks, learning, 1, CueRule::gives_one_cue).into_iter().next()?; + Some((*slot, learnt)) + }) + .collect(); + Self { pads } + } + + /// A beat for each pad whose rule finds one, leaving a pad empty when an earlier pad holds a + /// cue too near it. + pub fn place(&self, sections: &[Section], beat_count: usize) -> Vec<(HotCueSlot, BeatIndex)> { + let mut placed: Vec<(HotCueSlot, BeatIndex)> = Vec::new(); + for (slot, learnt) in &self.pads { + let Some(beat) = learnt.rule.place(sections, beat_count).first().copied() else { continue }; + if placed.iter().all(|&(_, other)| other.abs_diff(beat) >= MIN_GAP_BEATS) { + placed.push((*slot, beat)); + } + } + placed + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn section(first_beat: BeatIndex, kind: SectionKind) -> Section { + Section { first_beat, beats: 64, kind, relative_energy: 0.5 } + } + + /// Intro, build, drop, breakdown, build, drop, outro, with the drops `drop_at` and `second_drop_at`. + fn track(drop_at: BeatIndex, second_drop_at: BeatIndex) -> Vec
{ + vec![ + section(0, SectionKind::Intro), + section(drop_at - 32, SectionKind::Build), + section(drop_at, SectionKind::Drop), + section(drop_at + 128, SectionKind::Breakdown), + section(second_drop_at - 32, SectionKind::Build), + section(second_drop_at, SectionKind::Drop), + section(second_drop_at + 128, SectionKind::Outro), + ] + } + + /// A DJ who cues the top, every drop, and 16 bars before each drop. + fn cued(sections: Vec
) -> CuedTrack { + let drops: Vec = + sections.iter().filter(|s| s.kind == SectionKind::Drop).map(|s| s.first_beat).collect(); + let mut cues: HashSet = drops.iter().flat_map(|&drop| [drop, drop - 64]).collect(); + cues.insert(0); + CuedTrack { sections, beat_count: 1000, cues } + } + + #[test] + fn rules_place_cues_relative_to_their_sections() { + let sections = track(128, 448); + let rule = |kind, which, bars_from_start| CueRule { kind, which, bars_from_start, then_every: None }; + assert_eq!(rule(Some(SectionKind::Drop), Which::Every, 0).place(§ions, 1000), [128, 448]); + assert_eq!(rule(Some(SectionKind::Drop), Which::Nth(2), -16).place(§ions, 1000), [384]); + assert_eq!(rule(Some(SectionKind::Build), Which::Last, 0).place(§ions, 1000), [416]); + assert_eq!(rule(None, Which::Nth(1), -4).place(§ions, 1000), Vec::::new()); + assert_eq!(rule(Some(SectionKind::Outro), Which::Every, 32).place(§ions, 600), Vec::::new()); + let through_drops = CueRule { then_every: Some(8), ..rule(Some(SectionKind::Drop), Which::Every, 0) }; + assert_eq!(through_drops.place(§ions, 1000), [128, 160, 448, 480]); + } + + #[test] + fn a_learnt_memory_style_finds_the_djs_cues_on_a_new_track() { + let training: Vec = + [(128, 448), (192, 512), (64, 384), (256, 640)].into_iter().map(|(a, b)| cued(track(a, b))).collect(); + let style = MemoryCueStyle::learn(&training, &Learning::default()); + + let new_track = track(160, 544); + assert_eq!(style.place(&new_track, 1000, 10), [0, 96, 160, 480, 544]); + } + + #[test] + fn hot_cue_pads_each_learn_one_place() { + let pad_tracks = |slot: HotCueSlot, pick: fn(&[Section]) -> BeatIndex| { + let tracks = [(128, 448), (192, 512), (64, 384)] + .into_iter() + .map(|(a, b)| { + let sections = track(a, b); + let cues = HashSet::from([pick(§ions)]); + CuedTrack { sections, beat_count: 1000, cues } + }) + .collect(); + (slot, tracks) + }; + let style = HotCueStyle::learn( + &[pad_tracks(1, |_| 0), pad_tracks(2, |s| s[2].first_beat), pad_tracks(3, |s| s[5].first_beat - 32)], + &Learning::default(), + ); + assert_eq!(style.place(&track(160, 544), 1000), [(1, 0), (2, 160), (3, 512)]); + } + + #[test] + fn cues_too_near_one_already_placed_are_left_out() { + let sections = vec![section(0, SectionKind::Intro), section(2, SectionKind::Drop)]; + let every_start = CueRule { kind: None, which: Which::Every, bars_from_start: 0, then_every: None }; + assert_eq!(place_all(&[every_start], §ions, 100, 10), [0]); + } +} diff --git a/native/crates/es-analyse/src/lib.rs b/native/crates/es-analyse/src/lib.rs index 8102dec..1bd7d57 100644 --- a/native/crates/es-analyse/src/lib.rs +++ b/native/crates/es-analyse/src/lib.rs @@ -2,6 +2,7 @@ //! from. Our own algorithm, written from published methods; it is not rekordbox's. mod attack; +pub mod cue_style; pub mod downbeat; pub mod key; pub mod onset; diff --git a/native/crates/es-analyse/src/structure.rs b/native/crates/es-analyse/src/structure.rs index 3d6a34a..ae15324 100644 --- a/native/crates/es-analyse/src/structure.rs +++ b/native/crates/es-analyse/src/structure.rs @@ -32,7 +32,7 @@ const FLAT_SPREAD: f64 = 1e-9; const QUIET_PERCENTILE: f64 = 0.1; const LOUD_PERCENTILE: f64 = 0.95; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum SectionKind { Intro, Build, From f640cd9747371ac97e9fa26d0745a9cac8d83deb Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 17:14:30 +0000 Subject: [PATCH 11/25] Auto cue tracks in the style of a cue palette MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Cue Palette in the sidebar holds the tracks to learn from: add tracks from their menu, a playlist's or folder's tracks from its menu, or drag them on. "Auto cue" on tracks, selections and playlists learns a memory or hot cue style from the DJ's own cues on the palette, places cues on each track's own grid by its sections, and writes them marked "Auto cue". Tracks that already have the DJ's own cues of that sort are left alone, and a later run replaces only the automatic ones. "What it learns…" on the palette lists the learnt rules in words. - es-analyse: CueStyle learns and places either sort and round-trips through JSON; sections_on and nearest_beat are shared. - es-node: learnCueStyle and placeCues, and cue.placeAuto through the engine to rb-library's replace_auto_cues. - main: an AutoCue queue reporting progress on autoCue:progress, shown in the status bar with a stop button and summed up when it finishes. Bumps es-rekordbox-sdk for replace_auto_cues. Co-Authored-By: Claude Opus 5.5 --- app/src/main/audio/native.ts | 17 +++ app/src/main/autoCue.ts | 141 ++++++++++++++++++ app/src/main/index.ts | 3 + app/src/main/library.ts | 7 + app/src/preload/autoCue.d.ts | 50 +++++++ app/src/preload/engine.ts | 1 + app/src/preload/index.d.ts | 7 + app/src/preload/index.ts | 17 +++ app/src/renderer/src/App.svelte | 24 ++- app/src/renderer/src/lib/autoCue.svelte.ts | 51 +++++++ app/src/renderer/src/lib/autoCueMenu.ts | 25 ++++ .../src/lib/components/CueStyleDialog.svelte | 65 ++++++++ .../src/lib/components/Sidebar.svelte | 68 ++++++++- .../src/lib/components/StatusBar.svelte | 25 +++- .../src/lib/components/TrackTable.svelte | 3 +- app/src/renderer/src/lib/context.ts | 2 + app/src/renderer/src/lib/cuePalette.svelte.ts | 41 +++++ app/src/renderer/src/lib/cueStyle.ts | 49 ++++++ app/src/renderer/src/lib/ipcError.ts | 5 + app/src/renderer/src/lib/library.svelte.ts | 31 +++- app/src/renderer/src/lib/trackMenu.ts | 5 + app/src/renderer/src/lib/types.ts | 1 + app/src/shared/cues.ts | 2 + app/tests/cueStyle.test.ts | 38 +++++ es-rekordbox-sdk | 2 +- native/Cargo.lock | 1 + native/crates/es-analyse/Cargo.toml | 2 +- .../crates/es-analyse/examples/survey/mod.rs | 11 +- native/crates/es-analyse/src/cue_style.rs | 102 ++++++++++++- native/crates/es-analyse/src/lib.rs | 14 +- native/crates/es-analyse/src/structure.rs | 10 +- native/crates/es-engine/src/library.rs | 11 ++ native/crates/es-node/Cargo.toml | 1 + native/crates/es-node/src/cue_style.rs | 120 +++++++++++++++ native/crates/es-node/src/lib.rs | 29 ++-- native/crates/es-node/src/library.rs | 13 ++ 36 files changed, 947 insertions(+), 47 deletions(-) create mode 100644 app/src/main/autoCue.ts create mode 100644 app/src/preload/autoCue.d.ts create mode 100644 app/src/renderer/src/lib/autoCue.svelte.ts create mode 100644 app/src/renderer/src/lib/autoCueMenu.ts create mode 100644 app/src/renderer/src/lib/components/CueStyleDialog.svelte create mode 100644 app/src/renderer/src/lib/cuePalette.svelte.ts create mode 100644 app/src/renderer/src/lib/cueStyle.ts create mode 100644 app/src/renderer/src/lib/ipcError.ts create mode 100644 app/src/shared/cues.ts create mode 100644 app/tests/cueStyle.test.ts create mode 100644 native/crates/es-node/src/cue_style.rs diff --git a/app/src/main/audio/native.ts b/app/src/main/audio/native.ts index 5f9f84f..a304f20 100644 --- a/app/src/main/audio/native.ts +++ b/app/src/main/audio/native.ts @@ -102,6 +102,19 @@ export interface NativeTrackAnalysis { sections: { firstBeat: number; kind: string }[] } +export interface NativeCuedTrack { + path: string + grid: NativeGrid + /** `kind` is 0 for a memory cue, otherwise the hot cue's slot as rekordbox numbers it. */ + cues: { kind: number; startMs: number }[] +} + +export interface NativePlacedCue { + /** 0 for a memory cue, otherwise the hot cue's slot as rekordbox numbers it. */ + kind: number + startMs: number +} + export interface NativeLibrary { open(path?: string | null): Promise reload(): Promise @@ -117,6 +130,7 @@ export interface NativeLibrary { mediaResolve(kind: string, id: string, size: string): Promise cueSetHot(id: string, kind: number, ms: number, endMs: number | null): Promise cueAddMemory(id: string, ms: number, endMs: number | null): Promise + cuePlaceAuto(id: string, hot: boolean, kinds: number[], startsMs: number[]): Promise cueDelete(id: string, cueId: string): Promise cueSetColor(id: string, cueId: string, colorIndex: number | null): Promise onEvent(callback: (event: string, data: string) => void): void @@ -175,6 +189,9 @@ export interface NativeModule { RekordboxLibrary: new () => NativeLibrary analyse(path: string, bands: boolean, quality: number): Promise analyseTrack(path: string, options: NativeTrackAnalysisOptions): Promise + /** A cue style, as JSON for `placeCues`, learnt from the tracks' memory cues or, with `hot`, hot cues. */ + learnCueStyle(tracks: NativeCuedTrack[], hot: boolean): Promise + placeCues(path: string, grid: NativeGrid, style: string): Promise } /** Built by `npm run build:native` into resources/, which electron-builder unpacks from the asar. */ diff --git a/app/src/main/autoCue.ts b/app/src/main/autoCue.ts new file mode 100644 index 0000000..dcab935 --- /dev/null +++ b/app/src/main/autoCue.ts @@ -0,0 +1,141 @@ +import { BrowserWindow, ipcMain } from 'electron' +import type { AutoCueFinished, AutoCueProgress, AutoCueRequest, CueSort } from '../preload/autoCue' +import { AUTO_CUE_COMMENT } from '../shared/cues' +import type { NativeCuedTrack, NativeGrid, NativeModule } from './audio/native' +import type { Library } from './library' + +const CONCURRENCY = 3 + +interface DetailCue { + kind: 'hot' | 'memory' + slot: number + start: number + comment: string +} + +interface Detail { + cues: DetailCue[] + beatgrid: NativeGrid | null +} + +const ofSort = (cue: DetailCue, sort: CueSort): boolean => cue.kind === sort +const isOwn = (cue: DetailCue): boolean => cue.comment !== AUTO_CUE_COMMENT + +/** + * Learns a cue style from the palette's tracks, then places cues with it on other tracks a few at + * a time and writes them, marked automatic. Tracks that already have the DJ's own cues of the + * sort are left alone. Progress goes to every window on `autoCue:progress`. + */ +export class AutoCue { + private progress: AutoCueProgress | null = null + private queue: string[] = [] + + constructor( + private library: Library, + private native: () => NativeModule | null + ) {} + + register(): void { + ipcMain.handle('autoCue:run', (_e, request: AutoCueRequest) => this.run(request)) + ipcMain.handle('autoCue:learn', (_e, paletteIds: string[], sort: CueSort) => this.learn(paletteIds, sort)) + ipcMain.handle('autoCue:cancel', () => this.cancel()) + } + + private addon(): NativeModule { + const native = this.native() + if (!native) throw new Error('The analyser could not be loaded') + return native + } + + private async source(id: string): Promise<{ path: string; detail: Detail } | null> { + const path = await this.library.call('media.resolve', { kind: 'audio', id, size: '' }) + const detail = await this.library.call('track.detail', { id }) + return path && detail.beatgrid?.times.length ? { path, detail } : null + } + + /** The style, as JSON, learnt from the DJ's own cues of `sort` on the palette's tracks. */ + private async learn(paletteIds: string[], sort: CueSort): Promise { + const tracks: NativeCuedTrack[] = [] + for (const id of paletteIds) { + const found = await this.source(id) + if (!found?.detail.beatgrid) continue + const cues = found.detail.cues + .filter((cue) => isOwn(cue) && ofSort(cue, sort)) + .map((cue) => ({ kind: cue.slot, startMs: cue.start })) + if (cues.length) tracks.push({ path: found.path, grid: found.detail.beatgrid, cues }) + } + if (!tracks.length) throw new Error(`No track in the cue palette has ${sort} cues to learn from`) + return this.addon().learnCueStyle(tracks, sort === 'hot') + } + + private async run({ trackIds, paletteIds, sort }: AutoCueRequest): Promise { + if (this.progress) throw new Error('Auto cue is already running') + this.progress = { learning: true, total: trackIds.length, done: 0, skipped: 0, failed: 0 } + this.broadcast() + let style: string + try { + style = await this.learn(paletteIds, sort) + } catch (err) { + this.progress = { ...this.progress, learning: false, error: (err as Error).message } + this.broadcast() + this.progress = null + return + } + this.progress = { ...this.progress, learning: false } + this.queue = [...trackIds] + this.broadcast() + await Promise.all(Array.from({ length: CONCURRENCY }, () => this.work(style, sort))) + this.progress = null + } + + private async work(style: string, sort: CueSort): Promise { + for (let id = this.queue.shift(); id != null; id = this.queue.shift()) { + this.finish(await this.cue(id, style, sort)) + } + } + + private async cue(id: string, style: string, sort: CueSort): Promise { + try { + const found = await this.source(id) + if (!found?.detail.beatgrid) return { id, error: 'No beatgrid or audio file; analyse the track first' } + if (found.detail.cues.some((cue) => isOwn(cue) && ofSort(cue, sort))) return { id, skipped: true } + const placed = await this.addon().placeCues(found.path, found.detail.beatgrid, style) + const cues = await this.library.call('cue.placeAuto', { + id, + hot: sort === 'hot', + kinds: placed.map((cue) => cue.kind), + startsMs: placed.map((cue) => cue.startMs) + }) + return { id, cues } + } catch (err) { + return { id, error: (err as Error).message } + } + } + + private finish(finished: AutoCueFinished): void { + if (!this.progress) return + this.progress = { + ...this.progress, + done: this.progress.done + (finished.cues ? 1 : 0), + skipped: this.progress.skipped + (finished.skipped ? 1 : 0), + failed: this.progress.failed + (finished.error ? 1 : 0) + } + this.broadcast(finished) + } + + /** Drops the tracks still waiting. Those already being cued finish and are saved. */ + private cancel(): void { + if (!this.progress) return + this.progress = { ...this.progress, total: this.progress.total - this.queue.length } + this.queue = [] + this.broadcast() + } + + private broadcast(finished?: AutoCueFinished): void { + if (!this.progress) return + const progress: AutoCueProgress = { ...this.progress, ...(finished ? { finished } : {}) } + for (const win of BrowserWindow.getAllWindows()) { + if (!win.isDestroyed()) win.webContents.send('autoCue:progress', progress) + } + } +} diff --git a/app/src/main/index.ts b/app/src/main/index.ts index b0349ee..87a4e6c 100644 --- a/app/src/main/index.ts +++ b/app/src/main/index.ts @@ -4,6 +4,7 @@ import { electronApp, optimizer, is } from '@electron-toolkit/utils' import icon from '../../resources/icon.png?asset' import macIcon from '../../resources/icon-mac.png?asset' import { AnalysisQueue } from './analysis' +import { AutoCue } from './autoCue' import { AudioBridge } from './audio/bridge' import { buildMenu, registerFiles } from './files' import { handleMediaProtocol, registerMediaScheme } from './media' @@ -19,6 +20,7 @@ process.env.EXPORTSTUDIO_FFMPEG ??= ffmpegBinary() const library = new Library(() => audio.addon()) const audio = new AudioBridge(library) const analysis = new AnalysisQueue(library, () => audio.addon()) +const autoCue = new AutoCue(library, () => audio.addon()) registerMediaScheme() function createWindow(): BrowserWindow { @@ -76,6 +78,7 @@ app.whenReady().then(() => { handleMediaProtocol(library) audio.register() analysis.register() + autoCue.register() buildMenu() registerFiles() loadSettings() diff --git a/app/src/main/library.ts b/app/src/main/library.ts index 5612cff..6b2591d 100644 --- a/app/src/main/library.ts +++ b/app/src/main/library.ts @@ -71,6 +71,13 @@ const WRITES: CommandHandlers = { 'cue.setHot': (lib, p) => lib.cueSetHot(text(p?.id), Number(p?.kind), Number(p?.ms), p?.endMs == null ? null : Number(p.endMs)), 'cue.addMemory': (lib, p) => lib.cueAddMemory(text(p?.id), Number(p?.ms), p?.endMs == null ? null : Number(p.endMs)), + 'cue.placeAuto': (lib, p) => + lib.cuePlaceAuto( + text(p?.id), + Boolean(p?.hot), + ((p?.kinds as unknown[]) ?? []).map(Number), + ((p?.startsMs as unknown[]) ?? []).map(Number) + ), 'cue.delete': (lib, p) => lib.cueDelete(text(p?.id), text(p?.cueId)), 'cue.setColor': (lib, p) => lib.cueSetColor(text(p?.id), text(p?.cueId), p?.colorIndex == null ? null : Number(p.colorIndex)), diff --git a/app/src/preload/autoCue.d.ts b/app/src/preload/autoCue.d.ts new file mode 100644 index 0000000..64187b3 --- /dev/null +++ b/app/src/preload/autoCue.d.ts @@ -0,0 +1,50 @@ +export type CueSort = 'memory' | 'hot' + +export interface AutoCueRequest { + /** The tracks to place cues on. */ + trackIds: string[] + /** The tracks whose cues the style is learnt from. */ + paletteIds: string[] + sort: CueSort +} + +export type SectionKind = 'intro' | 'build' | 'drop' | 'breakdown' | 'outro' + +export interface CueRule { + /** Null counts sections of every kind. */ + kind: SectionKind | null + which: { nth: number } | 'last' | 'every' + barsFromStart: number + /** Cue again this many bars on, and on, until the section ends. */ + thenEvery: number | null +} + +export interface LearntRule { + rule: CueRule + cuesFound: number + cuesMisplaced: number +} + +/** A style as the native learner writes it: rules for memory cues, or one rule per hot cue pad. */ +export type CueStyle = { cues: 'memory'; rules: LearntRule[] } | { cues: 'hot'; pads: [number, LearntRule][] } + +export interface AutoCueFinished { + id: string + /** The track's cues after the automatic ones were written. */ + cues?: unknown[] + /** Left alone because it already has the DJ's own cues of this sort. */ + skipped?: boolean + error?: string +} + +export interface AutoCueProgress { + /** Still learning the style, before any track is cued. */ + learning: boolean + total: number + done: number + skipped: number + failed: number + finished?: AutoCueFinished + /** Set once, when learning fails and nothing is cued. */ + error?: string +} diff --git a/app/src/preload/engine.ts b/app/src/preload/engine.ts index e01926c..33524e6 100644 --- a/app/src/preload/engine.ts +++ b/app/src/preload/engine.ts @@ -138,6 +138,7 @@ export interface EngineCommandParams { 'track.import': { paths: string[]; playlistId?: string | null; artwork?: boolean } 'cue.setHot': { id: string; kind: number; ms: number; endMs?: number | null } 'cue.addMemory': { id: string; ms: number; endMs?: number | null } + 'cue.placeAuto': { id: string; hot: boolean; kinds: number[]; startsMs: number[] } 'cue.delete': { id: string; cueId: string } 'cue.setColor': { id: string; cueId: string; colorIndex?: number | null } 'playlist.add': { id: string; trackIds: string[] } diff --git a/app/src/preload/index.d.ts b/app/src/preload/index.d.ts index 5e59ba3..5f287e1 100644 --- a/app/src/preload/index.d.ts +++ b/app/src/preload/index.d.ts @@ -1,4 +1,5 @@ import type { AnalysisJob, AnalysisProgress, MenuCommand } from './analysis' +import type { AutoCueProgress, AutoCueRequest, CueSort } from './autoCue' import type { AudioApi } from './audio' import type { EngineCallArgs } from './engine' import type { Update } from '../shared/updates' @@ -28,6 +29,12 @@ export interface Api { analyse(jobs: AnalysisJob[], concurrency: number): Promise cancelAnalysis(): Promise onAnalysis(listener: (progress: AnalysisProgress) => void): () => void + /** Learns a cue style from the palette's tracks and places cues with it, marked automatic. */ + autoCue(request: AutoCueRequest): Promise + /** The style, as JSON, the palette's tracks teach for cues of `sort`. */ + learnCueStyle(paletteIds: string[], sort: CueSort): Promise + cancelAutoCue(): Promise + onAutoCue(listener: (progress: AutoCueProgress) => void): () => void /** Preferences already on disk. `exists` is false until the file has been written. */ loadSettings(): { exists: boolean; values: Record } writeSetting(key: string, value: string): void diff --git a/app/src/preload/index.ts b/app/src/preload/index.ts index 607721d..89f4be7 100644 --- a/app/src/preload/index.ts +++ b/app/src/preload/index.ts @@ -1,6 +1,7 @@ import { contextBridge, ipcRenderer, webUtils } from 'electron' import type { AudioApi, DeckEvent, Tick } from './audio' import type { AnalysisJob, AnalysisProgress, MenuCommand } from './analysis' +import type { AutoCueProgress, AutoCueRequest, CueSort } from './autoCue' import type { EngineCallArgs } from './engine' import type { Update } from '../shared/updates' import type { ZipProgress, ZipResult, ZipSource } from '../shared/zip' @@ -74,6 +75,22 @@ const api = { return subscribe('analysis:progress', listener) }, + autoCue(request: AutoCueRequest): Promise { + return ipcRenderer.invoke('autoCue:run', request) + }, + + learnCueStyle(paletteIds: string[], sort: CueSort): Promise { + return ipcRenderer.invoke('autoCue:learn', paletteIds, sort) + }, + + cancelAutoCue(): Promise { + return ipcRenderer.invoke('autoCue:cancel') + }, + + onAutoCue(listener: (progress: AutoCueProgress) => void): () => void { + return subscribe('autoCue:progress', listener) + }, + loadSettings(): { exists: boolean; values: Record } { return ipcRenderer.sendSync('settings:load') }, diff --git a/app/src/renderer/src/App.svelte b/app/src/renderer/src/App.svelte index eacbb6a..785635a 100644 --- a/app/src/renderer/src/App.svelte +++ b/app/src/renderer/src/App.svelte @@ -4,6 +4,7 @@ import { browserPreviews } from '$lib/browserPreview.svelte' import { setApp } from '$lib/context' import { Analysis, analysable } from '$lib/analysis.svelte' + import { AutoCue } from '$lib/autoCue.svelte' import { Backups } from '$lib/backups.svelte' import { Library } from '$lib/library.svelte' import { Decks } from '$lib/decks.svelte' @@ -12,7 +13,7 @@ import { Keybinds } from '$lib/keybinds.svelte' import { isFileDrag } from '$lib/library/drop' import { getSetting, setSetting } from '$lib/settings' - import type { ConvertPreset, Track } from '$lib/types' + import type { ConvertPreset, Cue, Track } from '$lib/types' import TitleBar from '$lib/components/TitleBar.svelte' import StatusBar from '$lib/components/StatusBar.svelte' import TrackEditDialog from '$lib/components/TrackEditDialog.svelte' @@ -28,7 +29,8 @@ const keybinds = new Keybinds() const analysis = new Analysis() const backups = new Backups(library, decks, analysis) - setApp({ library, decks, keybinds, analysis, backups, audition: decks.audition }) + const autoCue = new AutoCue(library) + setApp({ library, decks, keybinds, analysis, autoCue, backups, audition: decks.audition }) const initialMode = modeById(getSetting('mode')) let mode = $state.raw(initialMode) @@ -47,7 +49,23 @@ decks.adoptImported(tracks) analysis.afterImport(tracks) }) - library.onRemoved((ids) => decks.ejectWhere((id) => ids.includes(id))) + library.onRemoved((ids) => { + decks.ejectWhere((id) => ids.includes(id)) + library.cuePalette.remove(ids) + }) + autoCue.onFinished(({ id, cues }) => { + if (!cues) return + browserPreviews.noteCues(id, cues as Cue[]) + for (const player of decks.withTrack(id)) void player.refreshDetail() + }) + autoCue.onBatchDone(({ done, skipped, failed, error }) => { + if (error) return library.notify(error, 'error') + const tracks = (count: number): string => (count === 1 ? 'one track' : `${count} tracks`) + const parts = [`Auto cued ${tracks(done)}`] + if (skipped) parts.push(`left ${tracks(skipped)} with your own cues alone`) + if (failed) parts.push(`couldn’t cue ${tracks(failed)}`) + library.notify(parts.join(', '), failed ? 'warning' : 'info') + }) analysis.onFinished((track) => { if (!track) return browserPreviews.forget([track.id]) diff --git a/app/src/renderer/src/lib/autoCue.svelte.ts b/app/src/renderer/src/lib/autoCue.svelte.ts new file mode 100644 index 0000000..47c0040 --- /dev/null +++ b/app/src/renderer/src/lib/autoCue.svelte.ts @@ -0,0 +1,51 @@ +import type { AutoCueFinished, AutoCueProgress, CueSort } from '../../../preload/autoCue' +import type { Library } from './library.svelte' +import { ipcErrorMessage } from './ipcError' +import { Listeners } from './listeners' +import type { Track } from './types' +import { isDeviceTrack } from './trackIds' + +const settled = (progress: AutoCueProgress): number => progress.done + progress.skipped + progress.failed + +/** Auto cue runs started from the library, and their progress in the main process. */ +export class AutoCue { + progress = $state.raw(null) + running = $derived( + !!this.progress && !this.progress.error && (this.progress.learning || settled(this.progress) < this.progress.total) + ) + private finished = new Listeners<[finished: AutoCueFinished]>() + private batchDone = new Listeners<[progress: AutoCueProgress]>() + + constructor(private library: Library) { + window.api.onAutoCue((progress) => { + this.progress = progress + if (progress.finished) this.finished.notify(progress.finished) + if (!this.running) this.batchDone.notify(progress) + }) + } + + onFinished(listener: (finished: AutoCueFinished) => void): () => void { + return this.finished.add(listener) + } + + onBatchDone(listener: (progress: AutoCueProgress) => void): () => void { + return this.batchDone.add(listener) + } + + /** Learns from the cue palette and cues `tracks`, telling the user why when it can't start. */ + run(tracks: Track[], sort: CueSort): void { + const trackIds = tracks.filter((t) => t.collected !== false && !isDeviceTrack(t.id)).map((t) => t.id) + const paletteIds = this.library.cuePalette.ids + if (!trackIds.length) return + if (!this.library.writable) return this.library.notify('Unlock editing to auto cue tracks') + if (!paletteIds.length) return this.library.notify('Add tracks you have cued to the cue palette first') + if (this.running) return this.library.notify('Auto cue is already running') + window.api + .autoCue({ trackIds, paletteIds, sort }) + .catch((err) => this.library.notify(ipcErrorMessage(err), 'error')) + } + + cancel(): void { + void window.api.cancelAutoCue() + } +} diff --git a/app/src/renderer/src/lib/autoCueMenu.ts b/app/src/renderer/src/lib/autoCueMenu.ts new file mode 100644 index 0000000..54743b7 --- /dev/null +++ b/app/src/renderer/src/lib/autoCueMenu.ts @@ -0,0 +1,25 @@ +import { BookmarkMinus, BookmarkPlus, WandSparkles } from '@lucide/svelte' +import type { CueSort } from '../../../preload/autoCue' +import type { CuePalette } from './cuePalette.svelte' +import type { MenuEntry } from './menu' + +/** "Auto cue" with a choice of memory or hot cues, for tracks, selections and playlists alike. */ +export function autoCueEntry(locked: boolean, run: (sort: CueSort) => void): MenuEntry { + return { + label: 'Auto cue', + icon: WandSparkles, + disabled: locked, + items: [ + { label: 'Memory cues', onselect: () => run('memory') }, + { label: 'Hot cues', onselect: () => run('hot') } + ] + } +} + +/** Adds the tracks to the cue palette, or takes them out when every one is already in it. */ +export function cuePaletteEntry(palette: CuePalette, ids: string[]): MenuEntry { + const allIn = ids.length > 0 && ids.every((id) => palette.has(id)) + return allIn + ? { label: 'Remove from cue palette', icon: BookmarkMinus, onselect: () => palette.remove(ids) } + : { label: 'Add to cue palette', icon: BookmarkPlus, onselect: () => palette.add(ids) } +} diff --git a/app/src/renderer/src/lib/components/CueStyleDialog.svelte b/app/src/renderer/src/lib/components/CueStyleDialog.svelte new file mode 100644 index 0000000..cf3f0eb --- /dev/null +++ b/app/src/renderer/src/lib/components/CueStyleDialog.svelte @@ -0,0 +1,65 @@ + + + onclose()} + onclick={(e) => { + if (e.target === e.currentTarget) e.currentTarget.close() + }} +> +
+

What the cue palette teaches

+

+ Learnt from the cues you placed yourself on the palette’s {paletteIds.length} + {paletteIds.length === 1 ? 'track' : 'tracks'}. Auto cue places cues by these rules, most useful first. +

+ {#each styles as style (style.title)} +

{style.title}

+ {#await style.learnt} +

Learning…

+ {:then learnt} + {@const rows = styleRows(learnt)} + {#if rows.length} +
    + {#each rows as row (row.label)} +
  • + {row.label} + + right {row.cuesFound}, wrong {row.cuesMisplaced} + +
  • + {/each} +
+ {:else} +

No habit shows up often enough to learn.

+ {/if} + {:catch error} +

{ipcErrorMessage(error)}

+ {/await} + {/each} +
+ +
+
+
diff --git a/app/src/renderer/src/lib/components/Sidebar.svelte b/app/src/renderer/src/lib/components/Sidebar.svelte index eae3fc0..a29a2a1 100644 --- a/app/src/renderer/src/lib/components/Sidebar.svelte +++ b/app/src/renderer/src/lib/components/Sidebar.svelte @@ -3,6 +3,8 @@ import { SvelteSet } from 'svelte/reactivity' import { Library as LibraryIcon, + Bookmark, + BookmarkPlus, ListMusic, ListPlus, Folder, @@ -26,6 +28,7 @@ Settings2, LoaderCircle } from '@lucide/svelte' + import { autoCueEntry } from '$lib/autoCueMenu' import { getApp } from '$lib/context' import { droppedPaths, isFileDrag } from '$lib/library/drop' import { PLAYLIST_TREE_DRAG_TYPE } from '$lib/library.svelte' @@ -35,6 +38,7 @@ import type { Source, View, Volume } from '$lib/types' import ConfirmDialog from './ConfirmDialog.svelte' import ContextMenu from './ContextMenu.svelte' + import CueStyleDialog from './CueStyleDialog.svelte' import DeviceSettingsDialog from './DeviceSettingsDialog.svelte' import ImportDialog from './ImportDialog.svelte' import SyncDialog from './SyncDialog.svelte' @@ -42,7 +46,8 @@ let { onsource }: { onsource?: () => void } = $props() - const { library, decks, audition } = getApp() + const { library, decks, audition, autoCue } = getApp() + let showingCueStyle = $state(false) let ejectingId = $state(null) let deviceSettingsId = $state(null) @@ -221,6 +226,31 @@ void library.importFiles(droppedPaths(e)) } + function cuePaletteMenu(e: MouseEvent): void { + e.preventDefault() + const empty = !library.cuePalette.ids.length + menu = menuAt(e, 'Cue Palette', [ + { label: 'What it learns…', icon: Sparkles, disabled: empty, onselect: () => (showingCueStyle = true) }, + SEPARATOR, + { label: 'Clear', icon: Trash2, danger: true, disabled: empty, onselect: () => library.cuePalette.clear() } + ]) + } + + function cuePaletteDragOver(e: DragEvent): void { + if (!library.dragging) return + e.preventDefault() + if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy' + dropKey = 'cuePalette' + } + + function cuePaletteDrop(e: DragEvent): void { + dropKey = null + const ids = library.dragging?.filter((id) => !isDeviceTrack(id)) + if (!ids?.length) return + e.preventDefault() + library.cuePalette.add(ids) + } + function importItems(): MenuEntry[] { const locked = !library.writable return [ @@ -335,6 +365,18 @@ onselect: () => openSync(node.id, '') }, exportZipEntry(library, () => void library.exportPlaylistZip(node)), + SEPARATOR, + { + label: 'Add tracks to cue palette', + icon: BookmarkPlus, + onselect: () => + void library.playlistNodeTracks(node).then((tracks) => library.cuePalette.add(tracks.map((t) => t.id))) + }, + autoCueEntry( + locked, + (sort) => void library.playlistNodeTracks(node).then((tracks) => autoCue.run(tracks, sort)) + ), + SEPARATOR, { label: 'Rename', icon: Pencil, disabled: locked, onselect: () => (library.renamingId = node.id) }, { label: 'Delete', icon: Trash2, danger: true, disabled: locked, onselect: () => (deleting = node) }, locked && SEPARATOR, @@ -625,6 +667,26 @@ Collection {library.collectionSize} +
-
+
+ {#if decks.prefs.showPhrases || editingPhrases} + + {/if}
{#if editingGrid} + {:else if editingPhrases} + {:else} {/if} diff --git a/app/src/renderer/src/lib/components/deck/PhraseEditorBar.svelte b/app/src/renderer/src/lib/components/deck/PhraseEditorBar.svelte new file mode 100644 index 0000000..5dd6faf --- /dev/null +++ b/app/src/renderer/src/lib/components/deck/PhraseEditorBar.svelte @@ -0,0 +1,99 @@ + + +{#snippet tool( + content: string | Component<{ class?: string }>, + title: string, + onclick: (e: MouseEvent) => void, + disabled = false +)} + +{/snippet} + + diff --git a/app/src/renderer/src/lib/components/settings/DeveloperSettings.svelte b/app/src/renderer/src/lib/components/settings/DeveloperSettings.svelte index 29d8f34..e079806 100644 --- a/app/src/renderer/src/lib/components/settings/DeveloperSettings.svelte +++ b/app/src/renderer/src/lib/components/settings/DeveloperSettings.svelte @@ -57,8 +57,8 @@ onflip={() => prefs.setUnlimitedMemoryCues(!prefs.unlimitedMemoryCues)} /> prefs.setShowPhrases(!prefs.showPhrases)} /> diff --git a/app/src/renderer/src/lib/deck/phrases.svelte.ts b/app/src/renderer/src/lib/deck/phrases.svelte.ts new file mode 100644 index 0000000..d37beac --- /dev/null +++ b/app/src/renderer/src/lib/deck/phrases.svelte.ts @@ -0,0 +1,169 @@ +import type { SectionKind } from '../../../../preload/analysis' +import { api } from '../api' +import { nearestBeatIndex } from '../beat' +import { ipcErrorMessage } from '../ipcError' +import { kindOfLabel, writtenLabel } from '../phraseKinds' +import type { Beatgrid, Phrase } from '../types' +import type { TrackSession } from './session.svelte' + +/** A phrase's start: an index into the track's grid, and what kind of phrase begins there. */ +export interface PhraseStart { + beat: number + kind: SectionKind +} + +const HISTORY_LIMIT = 200 + +const sameStarts = (a: readonly PhraseStart[], b: readonly PhraseStart[]): boolean => + a.length === b.length && a.every((start, i) => start.beat === b[i].beat && start.kind === b[i].kind) + +/** Phrase editing: the track's phrases held as starts on its grid, saved or discarded as a whole. */ +export class PhraseEditor { + editing = $state(false) + draft = $state.raw([]) + /** Our analysis is filling the draft in. */ + finding = $state(false) + error = $state(null) + private loaded: PhraseStart[] = [] + private undoStack = $state.raw([]) + private redoStack = $state.raw([]) + + readonly dirty: boolean + /** The draft as phrases to draw. */ + readonly phrases: Phrase[] + /** Which of the draft's phrases the playhead is in, or -1 before the first. */ + readonly current: number + + constructor( + private session: TrackSession, + /** The playhead, in seconds. */ + private position: () => number, + private grid: () => Beatgrid | null + ) { + this.dirty = $derived(!sameStarts(this.draft, this.loaded)) + this.phrases = $derived(this.draft.map((start) => ({ firstBeat: start.beat + 1, label: writtenLabel(start.kind) }))) + this.current = $derived(this.draft.findLastIndex((start) => start.beat <= this.playheadBeat())) + } + + get canEdit(): boolean { + return !!this.grid()?.times.length && !!this.session.detail + } + + get canUndo(): boolean { + return this.undoStack.length > 0 + } + + get canRedo(): boolean { + return this.redoStack.length > 0 + } + + get currentKind(): SectionKind | null { + return this.draft[this.current]?.kind ?? null + } + + begin(): void { + if (!this.canEdit) return + this.loaded = (this.session.detail?.phrases ?? []).map((phrase) => ({ + beat: phrase.firstBeat - 1, + kind: kindOfLabel(phrase.label) + })) + this.draft = this.loaded + this.undoStack = [] + this.redoStack = [] + this.error = null + this.editing = true + } + + cancel(): void { + this.editing = false + this.draft = [] + } + + async save(): Promise { + if (!this.dirty) return this.cancel() + const phrases = this.draft.map((start) => ({ firstBeat: start.beat, kind: start.kind })) + const saved = await this.session.edit( + (id) => api.setPhrases(id, phrases), + (detail, written) => ({ ...detail, phrases: written }) + ) + if (saved) this.cancel() + } + + /** Starts a phrase on the beat nearest the playhead, of the kind of the phrase it splits. */ + split(): void { + const beat = this.playheadBeat() + if (this.draft.some((start) => start.beat === beat)) return + const kind = this.currentKind ?? 'intro' + this.change([...this.draft, { beat, kind }]) + } + + /** Takes away the start of the phrase the playhead is in, so it joins the one before. */ + join(): void { + if (this.current < 0) return + this.change(this.draft.filter((_, i) => i !== this.current)) + } + + setKind(kind: SectionKind): void { + if (this.current < 0) { + this.change([...this.draft, { beat: this.playheadBeat(), kind }]) + return + } + this.change(this.draft.map((start, i) => (i === this.current ? { ...start, kind } : start))) + } + + /** Moves the start of the phrase the playhead is in by `beats`, stopping short of its neighbours. */ + move(beats: number): void { + const at = this.current + if (at < 0) return + const low = at > 0 ? this.draft[at - 1].beat + 1 : 0 + const high = (this.draft[at + 1]?.beat ?? this.grid()?.times.length ?? 1) - 1 + const beat = Math.max(low, Math.min(high, this.draft[at].beat + beats)) + if (beat === this.draft[at].beat) return + this.change(this.draft.map((start, i) => (i === at ? { ...start, beat } : start))) + } + + /** Replaces the draft with the sections our analysis finds, which can be undone. */ + async fillFromAnalysis(): Promise { + const id = this.session.track?.id + if (!id || this.finding) return + this.finding = true + this.error = null + try { + const sections = await window.api.trackSections(id) + if (this.editing && this.session.track?.id === id) { + this.change(sections.map((section) => ({ beat: section.firstBeat, kind: section.kind }))) + } + } catch (err) { + this.error = ipcErrorMessage(err) + } finally { + this.finding = false + } + } + + undo(): void { + const previous = this.undoStack.at(-1) + if (!previous) return + this.redoStack = [...this.redoStack, this.draft] + this.undoStack = this.undoStack.slice(0, -1) + this.draft = previous + } + + redo(): void { + const next = this.redoStack.at(-1) + if (!next) return + this.undoStack = [...this.undoStack, this.draft] + this.redoStack = this.redoStack.slice(0, -1) + this.draft = next + } + + private change(starts: PhraseStart[]): void { + this.undoStack = [...this.undoStack, this.draft].slice(-HISTORY_LIMIT) + this.redoStack = [] + this.draft = [...starts].sort((a, b) => a.beat - b.beat) + } + + private playheadBeat(): number { + const times = this.grid()?.times ?? [] + return times.length ? nearestBeatIndex(times, this.position() * 1000) : 0 + } +} diff --git a/app/src/renderer/src/lib/phraseKinds.ts b/app/src/renderer/src/lib/phraseKinds.ts new file mode 100644 index 0000000..8206ccd --- /dev/null +++ b/app/src/renderer/src/lib/phraseKinds.ts @@ -0,0 +1,32 @@ +import type { SectionKind } from '../../../preload/analysis' + +/** Our section kinds under the names rekordbox gives their phrases in a high-mood track. */ +export const PHRASE_KINDS: readonly { kind: SectionKind; name: string; meaning: string }[] = [ + { kind: 'intro', name: 'INTRO', meaning: 'Intro' }, + { kind: 'build', name: 'UP', meaning: 'Build' }, + { kind: 'drop', name: 'CHORUS', meaning: 'Drop' }, + { kind: 'breakdown', name: 'DOWN', meaning: 'Breakdown' }, + { kind: 'outro', name: 'OUTRO', meaning: 'Outro' } +] + +/** How the engine labels a phrase of each kind when it writes one. */ +const WRITTEN_LABELS: Record = { + intro: 'INTRO 1', + build: 'UP 1', + drop: 'CHORUS 1', + breakdown: 'DOWN', + outro: 'OUTRO 1' +} + +/** Mid- and low-mood names, read as the high-mood kinds they sit closest to. */ +const OTHER_MOODS: Record = { VERSE: 'build', BRIDGE: 'breakdown' } + +export function writtenLabel(kind: SectionKind): string { + return WRITTEN_LABELS[kind] +} + +/** The kind of a phrase from its rekordbox label, such as `CHORUS 2`. */ +export function kindOfLabel(label: string): SectionKind { + const word = label.split(' ')[0] + return PHRASE_KINDS.find((entry) => entry.name === word)?.kind ?? OTHER_MOODS[word] ?? 'intro' +} diff --git a/app/src/renderer/src/lib/player.svelte.ts b/app/src/renderer/src/lib/player.svelte.ts index c384313..d6c1481 100644 --- a/app/src/renderer/src/lib/player.svelte.ts +++ b/app/src/renderer/src/lib/player.svelte.ts @@ -7,6 +7,7 @@ import { GridEditor } from './deck/grid.svelte' import { TrackSession } from './deck/session.svelte' import { WaveformDisplay } from './deck/display.svelte' import type { CuePlacement, DeckPrefs } from './deck/prefs.svelte' +import { PhraseEditor } from './deck/phrases.svelte' import { phraseSections, type PhraseSection } from './deck/sections' import { TempoControl } from './deck/tempo.svelte' import { Listeners } from './listeners' @@ -53,6 +54,11 @@ export class Player { (seconds) => this.seek(seconds) ) readonly cues = new CueEditor(this.session, this.grid) + readonly phrases = new PhraseEditor( + this.session, + () => this.position, + () => this.displayGrid + ) readonly tempo: TempoControl readonly display: WaveformDisplay @@ -96,8 +102,8 @@ export class Player { } get phraseSections(): PhraseSection[] { - if (!this.prefs.showPhrases || !this.detail) return [] - return phraseSections(this.detail.phrases, this.displayGrid, this.duration) + const phrases = this.phrases.editing ? this.phrases.phrases : this.prefs.showPhrases ? this.detail?.phrases : null + return phrases ? phraseSections(phrases, this.displayGrid, this.duration) : [] } get track(): Track | null { diff --git a/app/tests/phraseKinds.test.ts b/app/tests/phraseKinds.test.ts new file mode 100644 index 0000000..c5e00f5 --- /dev/null +++ b/app/tests/phraseKinds.test.ts @@ -0,0 +1,20 @@ +import { register } from 'node:module' +import assert from 'node:assert/strict' +import { describe, it } from 'node:test' + +register(new URL('./resolve-ts.mjs', import.meta.url).href) + +const { kindOfLabel, writtenLabel, PHRASE_KINDS } = await import('../src/renderer/src/lib/phraseKinds.ts') + +describe('phrase kinds', () => { + it('reads every kind back from the label it is written with', () => { + for (const { kind } of PHRASE_KINDS) assert.equal(kindOfLabel(writtenLabel(kind)), kind) + }) + + it('reads rekordbox variants and other moods as the nearest kind', () => { + assert.equal(kindOfLabel('CHORUS 2'), 'drop') + assert.equal(kindOfLabel('UP 3'), 'build') + assert.equal(kindOfLabel('VERSE 4'), 'build') + assert.equal(kindOfLabel('BRIDGE'), 'breakdown') + }) +}) diff --git a/native/crates/es-engine/src/analysis.rs b/native/crates/es-engine/src/analysis.rs index 38cde34..fa73292 100644 --- a/native/crates/es-engine/src/analysis.rs +++ b/native/crates/es-engine/src/analysis.rs @@ -132,6 +132,33 @@ pub struct SectionStart { pub kind: SectionKind, } +/// Replace a track's phrases with `sections`, counted on the grid in its analysis file. No sections +/// takes its phrases away. +pub fn set_phrases(lib: &Library, share: &Path, id: &str, sections: &[SectionStart]) -> Result<()> { + let files = lib.track_files(id)?.ok_or_else(|| Error::Other(format!("Unknown track {id}")))?; + let dat = files + .analysis_path + .as_deref() + .and_then(|rel| rb_anlz::file(share, rel, "DAT")) + .filter(|p| p.is_file()) + .ok_or_else(|| Error::Other("Analyse this track before setting its phrases".into()))?; + let beat_count = Tags::read(&dat).ok().and_then(|tags| decode::beatgrid(&tags)).map_or(0, |grid| grid.times.len()); + if beat_count == 0 { + return Err(Error::Other("This track has no beatgrid to count phrases on".into())); + } + let ext = dat.with_extension("EXT"); + let old_ext = + std::fs::read(&ext).map_err(|_| Error::Other("This track has no analysis file to hold phrases".into()))?; + let patched = if sections.is_empty() { + patch_tags(&old_ext, &[], &[rb_anlz::PHRASE_TAG]) + } else { + patch_tags(&old_ext, &[(rb_anlz::PHRASE_TAG, phrase_tag(sections, beat_count))], &[]) + } + .map_err(other)?; + back_up_once(id, std::slice::from_ref(&ext)).map_err(other)?; + write_all(&[(ext.clone(), patched)], &[(ext, Some(old_ext))], || Ok(())) +} + /// What the native analyser found for a track. #[derive(Debug, Clone, Default)] pub struct Analysis { diff --git a/native/crates/es-engine/src/library.rs b/native/crates/es-engine/src/library.rs index 9b13d96..1ac09f5 100644 --- a/native/crates/es-engine/src/library.rs +++ b/native/crates/es-engine/src/library.rs @@ -596,6 +596,17 @@ impl LibraryService { Ok(BeatgridResult { beatgrid: reads.beatgrid(id)?, cues: reads.cues(id)?, bpm }) } + pub fn track_set_phrases( + &mut self, + id: &str, + sections: &[crate::analysis::SectionStart], + ) -> Result> { + let session = self.session.as_mut().ok_or_else(|| crate::Error::Other("Library not open".into()))?; + let share = session.database().share_dir(); + session.with_live(|database| crate::analysis::set_phrases(database, &share, id, sections))?; + self.read_model()?.phrases(id) + } + pub fn track_apply_analysis( &mut self, id: &str, @@ -934,6 +945,10 @@ impl<'a> LibraryRead<'a> { Ok(es_index::detail::beatgrid_for(self.database, &self.share, id)?) } + pub fn phrases(&self, id: &str) -> Result> { + Ok(es_index::detail::phrases_for(self.database, &self.share, id)?) + } + pub fn previews(&self, ids: &[String]) -> Result> { Ok(es_index::detail::previews(self.database, &self.share, ids)?) } diff --git a/native/crates/es-engine/tests/analysis.rs b/native/crates/es-engine/tests/analysis.rs index 0c405a6..6a9c14e 100644 --- a/native/crates/es-engine/tests/analysis.rs +++ b/native/crates/es-engine/tests/analysis.rs @@ -1,7 +1,7 @@ use std::path::Path; use es_analyse::structure::SectionKind; -use es_engine::analysis::{apply_analysis, set_beatgrid, Analysis, Grid, Options, SectionStart}; +use es_engine::analysis::{apply_analysis, set_beatgrid, set_phrases, Analysis, Grid, Options, SectionStart}; use es_engine::import::{import_files, Options as ImportOptions}; use rb_anlz::decode::{self, Tags}; use rb_library::fixture; @@ -133,6 +133,27 @@ fn sections_found_on_a_grid_that_is_not_kept_are_not_written() { assert_eq!(phrases(&lib, &share, &id), None); } +#[test] +fn hand_set_phrases_replace_the_tracks_and_none_clears_them() { + let (_dir, mut lib, id) = scene(); + let share = lib.share_dir(); + let analysed = Analysis { sections: sections(&[(0, SectionKind::Intro)]), ..analysis() }; + apply_analysis(&mut lib, &share, &id, &analysed, ALL).unwrap(); + set_phrases( + &lib, + &share, + &id, + §ions(&[(0, SectionKind::Intro), (1, SectionKind::Intro), (3, SectionKind::Drop)]), + ) + .unwrap(); + assert_eq!( + phrases(&lib, &share, &id), + Some(vec![(1, "INTRO 1".into()), (2, "INTRO 1".into()), (4, "CHORUS 1".into())]) + ); + set_phrases(&lib, &share, &id, &[]).unwrap(); + assert_eq!(phrases(&lib, &share, &id), None); +} + #[test] fn a_hand_edited_grid_is_written_and_moves_cues() { let (_dir, mut lib, id) = scene(); diff --git a/native/crates/es-index/src/detail.rs b/native/crates/es-index/src/detail.rs index 145a3e5..bfea5dd 100644 --- a/native/crates/es-index/src/detail.rs +++ b/native/crates/es-index/src/detail.rs @@ -187,6 +187,12 @@ pub fn track_detail(lib: &Library, share: &Path, id: &str) -> Result { }) } +/// A track's phrases as its analysis file holds them. +pub fn phrases_for(lib: &Library, share: &Path, id: &str) -> Result> { + let files = lib.track_files(id)?.ok_or_else(|| Error::NotFound(format!("track {id}")))?; + Ok(phrases(tags(share, files.analysis_path.as_deref(), "EXT").as_ref())) +} + /// A track's beat grid as its analysis file holds it. pub fn beatgrid_for(lib: &Library, share: &Path, id: &str) -> Result> { let files = lib.track_files(id)?.ok_or_else(|| Error::NotFound(format!("track {id}")))?; diff --git a/native/crates/es-node/src/library.rs b/native/crates/es-node/src/library.rs index 1fe43fa..b666a45 100644 --- a/native/crates/es-node/src/library.rs +++ b/native/crates/es-node/src/library.rs @@ -153,6 +153,20 @@ fn parse_edit(fields: &str) -> napi::Result { Ok(edit) } +/// Section starts sent as `[{ firstBeat, kind }]`, leaving out any that don't read. +fn section_starts(value: Option<&Value>) -> Vec { + let Some(values) = value.and_then(Value::as_array) else { return Vec::new() }; + values + .iter() + .filter_map(|section| { + Some(es_engine::analysis::SectionStart { + first_beat: usize::try_from(section.get("firstBeat")?.as_u64()?).ok()?, + kind: es_analyse::structure::SectionKind::from_name(section.get("kind")?.as_str()?)?, + }) + }) + .collect() +} + enum Op { Open(Option), Reload, @@ -174,6 +188,7 @@ enum Op { BeatgridSet(String, String), Convert { ids: Vec, preset: String, mode: String }, ApplyAnalysis(String, String), + SetPhrases(String, String), MediaResolve { kind: String, id: String, size: String }, CueSetHot(String, i64, i64, Option), CueAddMemory(String, i64, Option), @@ -227,6 +242,7 @@ impl Run { Op::CueDelete(_, _) => "cue.delete", Op::CueSetColor(_, _, _) => "cue.setColor", Op::TrackDetail(_) => "track.detail", + Op::SetPhrases(..) => "track.setPhrases", Op::TrackPreviews(_) => "track.previews", Op::Usb(UsbOp::List) => "usb.list", _ => "library.other", @@ -457,23 +473,7 @@ impl Run { value.get("minor").and_then(Value::as_bool).unwrap_or(false), ) }); - let sections = result - .get("sections") - .and_then(Value::as_array) - .map(|values| { - values - .iter() - .filter_map(|section| { - Some(es_engine::analysis::SectionStart { - first_beat: usize::try_from(section.get("firstBeat")?.as_u64()?).ok()?, - kind: es_analyse::structure::SectionKind::from_name( - section.get("kind")?.as_str()?, - )?, - }) - }) - .collect() - }) - .unwrap_or_default(); + let sections = section_starts(result.get("sections")); let analysis = es_engine::analysis::Analysis { beats, sections, @@ -511,6 +511,11 @@ impl Run { Op::CuePlaceAuto { id, hot, cues } => { return json_of(&service.cue_place_auto(id, *hot, cues).map_err(failure)?); } + Op::SetPhrases(id, body) => { + let input: Value = serde_json::from_str(body).map_err(failure)?; + let sections = section_starts(input.get("phrases")); + return json_of(&service.track_set_phrases(id, §ions).map_err(failure)?); + } Op::CueDelete(id, cue_id) => return json_of(&service.cue_delete(id, cue_id).map_err(failure)?), Op::CueSetColor(id, cue_id, color) => { return json_of(&service.cue_set_color(id, cue_id, *color).map_err(failure)?); @@ -713,6 +718,12 @@ impl RekordboxLibrary { self.run(Op::CuePlaceAuto { id, hot, cues }) } + /// Replace the track's phrases with `body`'s `phrases`, `[{ firstBeat, kind }]`. + #[napi(ts_return_type = "Promise")] + pub fn track_set_phrases(&self, id: String, body: String) -> AsyncTask { + self.run(Op::SetPhrases(id, body)) + } + #[napi(ts_return_type = "Promise")] pub fn cue_delete(&self, id: String, cue_id: String) -> AsyncTask { self.run(Op::CueDelete(id, cue_id)) From dcc6e08e7d25abd1e1984cff3ecf846dc8314df5 Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 18:31:17 +0000 Subject: [PATCH 13/25] Score our sections against hand-set phrases The phrase_score example reads the "phrase examples" playlist and, track by track, compares the phrases set on it with the sections we find on its own grid. It reports boundary F1 exact and within a bar, how many of the hand-set starts we find (split into the first phrase, kind changes and same-kind splits), our near-miss offsets in beats, per-beat label agreement with a confusion matrix, scores by genre, and every track worst first, marking those whose phrases rekordbox wrote. Co-Authored-By: Claude Opus 5.5 --- native/Cargo.lock | 2 + native/crates/es-analyse/Cargo.toml | 2 + .../es-analyse/examples/phrase_score.rs | 318 ++++++++++++++++++ 3 files changed, 322 insertions(+) create mode 100644 native/crates/es-analyse/examples/phrase_score.rs diff --git a/native/Cargo.lock b/native/Cargo.lock index 1ce8254..271eb2d 100644 --- a/native/Cargo.lock +++ b/native/Cargo.lock @@ -562,6 +562,8 @@ version = "0.1.0" dependencies = [ "es-decode", "rayon", + "rb-anlz", + "rb-library", "realfft", "serde", "serde_json", diff --git a/native/crates/es-analyse/Cargo.toml b/native/crates/es-analyse/Cargo.toml index 04737fb..213c87b 100644 --- a/native/crates/es-analyse/Cargo.toml +++ b/native/crates/es-analyse/Cargo.toml @@ -12,3 +12,5 @@ realfft = "3" [dev-dependencies] serde_json = "1" +rb-library.workspace = true +rb-anlz.workspace = true diff --git a/native/crates/es-analyse/examples/phrase_score.rs b/native/crates/es-analyse/examples/phrase_score.rs new file mode 100644 index 0000000..edfd378 --- /dev/null +++ b/native/crates/es-analyse/examples/phrase_score.rs @@ -0,0 +1,318 @@ +//! Scores our sections against the phrases set by hand on the tracks of the "phrase examples" +//! playlist. Each track is compared only with itself: its own phrases against the sections we find +//! on its own grid. Reads a snapshot of the installed library and changes nothing. +//! `cargo run --release -p es-analyse --example phrase_score` + +use std::collections::{BTreeMap, HashSet}; +use std::path::Path; + +use es_analyse::structure::{sections_on, BeatIndex, Section, SectionKind}; +use es_analyse::{decode_mono, Beat, SAMPLE_RATE}; +use rayon::prelude::*; +use rb_anlz::decode::{self, Tags}; +use rb_anlz::phrase::{self, Mood, PhraseKind, SongStructure}; +use rb_library::{Library, PlaylistKind, Track}; + +const PLAYLIST: &str = "phrase examples"; +const BEATS_PER_BAR: usize = 4; +/// How far a start may be from the hand-set one and still be found. +const TOLERANCES: [(&str, usize); 2] = [("exact", 0), ("within a bar", BEATS_PER_BAR)]; + +/// Where a hand-set phrase start sits: the first, a change of kind, or a split within one kind. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum StartSort { + First, + KindChange, + SameKindSplit, +} + +impl StartSort { + const ALL: [Self; 3] = [Self::First, Self::KindChange, Self::SameKindSplit]; + + fn name(self) -> &'static str { + match self { + Self::First => "first phrase", + Self::KindChange => "kind changes", + Self::SameKindSplit => "same-kind splits", + } + } +} + +struct Start { + beat: BeatIndex, + kind: SectionKind, +} + +struct Scored { + title: String, + genre: String, + theirs: Vec, + ours: Vec
, + end_beat: BeatIndex, + written_by_rekordbox: bool, +} + +/// Whether rekordbox wrote these phrases rather than this app: the app writes only the high mood, +/// every numbered kind as its first variant, and no fill-ins. +fn written_by_rekordbox(structure: &SongStructure) -> bool { + structure.mood != Mood::High + || structure.phrases.iter().any(|p| p.variant.is_some_and(|v| v != 1) || p.fill_in_beat.is_some()) +} + +/// The hand-set phrases' kinds in our words; mid and low moods' verses and bridges read as the +/// high-mood kinds nearest them. +fn kind_of(kind: Option) -> SectionKind { + match kind { + Some(PhraseKind::Up | PhraseKind::Verse) => SectionKind::Build, + Some(PhraseKind::Chorus) => SectionKind::Drop, + Some(PhraseKind::Down | PhraseKind::Bridge) => SectionKind::Breakdown, + Some(PhraseKind::Outro) => SectionKind::Outro, + Some(PhraseKind::Intro) | None => SectionKind::Intro, + } +} + +fn main() -> Result<(), Box> { + let path = Library::installed_path().ok_or("no installed rekordbox library")?; + let lib = Library::open_snapshot(&path)?; + let share = path.with_file_name("share"); + let playlists: Vec<_> = lib + .playlists()? + .into_iter() + .filter(|node| node.kind != PlaylistKind::Folder && node.name.trim().eq_ignore_ascii_case(PLAYLIST)) + .collect(); + let [playlist] = playlists.as_slice() else { + return Err(format!("expected one playlist called \"{PLAYLIST}\", found {}", playlists.len()).into()); + }; + let ids = lib.playlist_track_ids(&playlist.id)?; + let tracks = lib.tracks(Some(&ids))?; + println!("{} tracks in \"{PLAYLIST}\"\n", tracks.len()); + + let results: Vec> = tracks.par_iter().map(|track| score(&share, track)).collect(); + let mut scored = Vec::new(); + for result in results { + match result { + Ok(track) => scored.push(track), + Err(skipped) => println!("skipped {skipped}"), + } + } + report(&scored); + Ok(()) +} + +fn score(share: &Path, track: &Track) -> Result { + let title = format!("{} - {}", track.artist, track.title); + let analysis = |suffix| { + let relative = track.analysis_path.as_deref()?; + Tags::read(&rb_anlz::file(share, relative, suffix)?).ok() + }; + let grid = analysis("DAT").as_ref().and_then(decode::beatgrid).ok_or(format!("{title}: no beatgrid"))?; + let structure: SongStructure = + analysis("EXT").as_ref().and_then(phrase::song_structure).ok_or(format!("{title}: no phrases"))?; + let beats: Vec = grid + .times + .iter() + .zip(&grid.beats) + .zip(&grid.bpms) + .map(|((&time_ms, &number), &bpm)| Beat { + number: u8::try_from(number).unwrap_or(0), + tempo_x100: (bpm * 100.0).round() as u16, + time_ms, + }) + .collect(); + let mono = decode_mono(Path::new(&track.folder_path)).map_err(|e| format!("{title}: {e}"))?; + let theirs = structure + .phrases + .iter() + .map(|p| Start { beat: usize::from(p.first_beat).saturating_sub(1), kind: kind_of(p.kind) }) + .collect(); + Ok(Scored { + title, + genre: track.genre.clone(), + theirs, + ours: sections_on(&mono, f64::from(SAMPLE_RATE), &beats), + end_beat: usize::from(structure.end_beat).min(beats.len()), + written_by_rekordbox: written_by_rekordbox(&structure), + }) +} + +/// Hand-set starts paired one to one with ours no further than `tolerance` beats away, nearest +/// pairs first, as (theirs, ours) indices. +fn pairs(theirs: &[BeatIndex], ours: &[BeatIndex], tolerance: usize) -> Vec<(usize, usize)> { + let mut candidates: Vec<(usize, usize, usize)> = theirs + .iter() + .enumerate() + .flat_map(|(t, &a)| ours.iter().enumerate().map(move |(o, &b)| (a.abs_diff(b), t, o))) + .filter(|&(distance, _, _)| distance <= tolerance) + .collect(); + candidates.sort_unstable(); + let (mut used_theirs, mut used_ours) = (HashSet::new(), HashSet::new()); + let mut out = Vec::new(); + for (_, t, o) in candidates { + if !used_theirs.contains(&t) && !used_ours.contains(&o) { + used_theirs.insert(t); + used_ours.insert(o); + out.push((t, o)); + } + } + out +} + +impl Scored { + fn their_beats(&self) -> Vec { + self.theirs.iter().map(|start| start.beat).collect() + } + + fn our_beats(&self) -> Vec { + self.ours.iter().map(|section| section.first_beat).collect() + } + + fn sort_of(&self, index: usize) -> StartSort { + match index { + 0 => StartSort::First, + i if self.theirs[i].kind != self.theirs[i - 1].kind => StartSort::KindChange, + _ => StartSort::SameKindSplit, + } + } + + fn boundary_f1(&self, tolerance: usize) -> f64 { + let found = pairs(&self.their_beats(), &self.our_beats(), tolerance).len(); + f1(found, self.theirs.len(), self.ours.len()) + } + + /// Our kind and theirs on each beat both cover, inside their phrases. + fn beat_kinds(&self) -> Vec<(SectionKind, SectionKind)> { + let mut out = Vec::new(); + for (i, start) in self.theirs.iter().enumerate() { + let end = self.theirs.get(i + 1).map_or(self.end_beat, |next| next.beat); + for beat in start.beat..end { + let ours = self.ours.iter().rev().find(|section| section.first_beat <= beat); + if let Some(section) = ours { + out.push((start.kind, section.kind)); + } + } + } + out + } + + fn label_agreement(&self) -> f64 { + let kinds = self.beat_kinds(); + kinds.iter().filter(|(theirs, ours)| theirs == ours).count() as f64 / kinds.len().max(1) as f64 + } + + fn score(&self) -> f64 { + (self.boundary_f1(0) + self.label_agreement()) / 2.0 + } +} + +fn f1(found: usize, theirs: usize, ours: usize) -> f64 { + if theirs + ours == 0 { + 1.0 + } else { + 2.0 * found as f64 / (theirs + ours) as f64 + } +} + +fn percent(part: usize, whole: usize) -> String { + format!("{:>5.1}%", 100.0 * part as f64 / whole.max(1) as f64) +} + +fn report(tracks: &[Scored]) { + if tracks.is_empty() { + return; + } + let mean = |value: fn(&Scored) -> f64| tracks.iter().map(value).sum::() / tracks.len() as f64; + println!("== Overall, {} tracks ==", tracks.len()); + println!("track score (mean) {:.3}", mean(Scored::score)); + println!("boundary F1, exact (mean) {:.3}", mean(|t| t.boundary_f1(0))); + println!("boundary F1, within a bar {:.3}", mean(|t| t.boundary_f1(BEATS_PER_BAR))); + println!("label agreement (mean) {:.3}", mean(Scored::label_agreement)); + let theirs: usize = tracks.iter().map(|t| t.theirs.len()).sum(); + let ours: usize = tracks.iter().map(|t| t.ours.len()).sum(); + println!( + "phrases per track yours {:.1}, ours {:.1}", + theirs as f64 / tracks.len() as f64, + ours as f64 / tracks.len() as f64 + ); + + println!("\n== Your phrase starts we found =="); + println!("{:<18} {:>6} {:>8} {:>14}", "", "count", "exact", "within a bar"); + for sort in StartSort::ALL { + let mut found = [0usize; TOLERANCES.len()]; + let mut count = 0; + for track in tracks { + let theirs = track.their_beats(); + let ours = track.our_beats(); + let sorts: Vec = (0..theirs.len()).map(|i| track.sort_of(i)).collect(); + count += sorts.iter().filter(|&&s| s == sort).count(); + for (slot, (_, tolerance)) in TOLERANCES.iter().enumerate() { + found[slot] += pairs(&theirs, &ours, *tolerance).iter().filter(|(t, _)| sorts[*t] == sort).count(); + } + } + println!("{:<18} {count:>6} {:>8} {:>14}", sort.name(), percent(found[0], count), percent(found[1], count)); + } + let extra: usize = + tracks.iter().map(|t| t.ours.len() - pairs(&t.their_beats(), &t.our_beats(), BEATS_PER_BAR).len()).sum(); + println!("our starts with none of yours within a bar: {extra} ({} of ours)", percent(extra, ours)); + + let mut offsets: BTreeMap = BTreeMap::new(); + for track in tracks { + let (theirs, ours) = (track.their_beats(), track.our_beats()); + for (t, o) in pairs(&theirs, &ours, 2 * BEATS_PER_BAR) { + let offset = i64::try_from(ours[o]).unwrap_or(0) - i64::try_from(theirs[t]).unwrap_or(0); + if offset != 0 { + *offsets.entry(offset).or_default() += 1; + } + } + } + println!("\n== Near misses: our start minus yours, in beats =="); + for (offset, count) in &offsets { + println!(" {offset:>+4} {count}"); + } + + println!("\n== Labels, by beat: yours down, ours across =="); + let mut confusion = [[0usize; 5]; 5]; + let index = |kind: SectionKind| SectionKind::ALL.iter().position(|&k| k == kind).unwrap_or(0); + for (theirs, ours) in tracks.iter().flat_map(Scored::beat_kinds) { + confusion[index(theirs)][index(ours)] += 1; + } + println!("{:<11}{}", "", SectionKind::ALL.iter().map(|k| format!("{:>10}", k.name())).collect::()); + for (kind, row) in SectionKind::ALL.iter().zip(confusion) { + let total: usize = row.iter().sum(); + let cells: String = row.iter().map(|&n| format!("{:>10}", percent(n, total))).collect(); + println!("{:<11}{cells}", kind.name()); + } + + let mut genres: BTreeMap<&str, Vec> = BTreeMap::new(); + for track in tracks { + let genre = if track.genre.trim().is_empty() { "(no genre)" } else { track.genre.trim() }; + genres.entry(genre).or_default().push(track.score()); + } + println!("\n== By genre =="); + for (genre, scores) in &genres { + println!( + " {:<28} {:>3} tracks score {:.3}", + genre, + scores.len(), + scores.iter().sum::() / scores.len() as f64 + ); + } + + let mut by_score: Vec<&Scored> = tracks.iter().collect(); + by_score.sort_by(|a, b| a.score().total_cmp(&b.score())); + let by_rekordbox = tracks.iter().filter(|t| t.written_by_rekordbox).count(); + println!("\n== Tracks, worst first ({by_rekordbox} with phrases rekordbox wrote, marked rb) =="); + println!("{:>6} {:>8} {:>8} {:>7} {:>5} track", "score", "F1 exact", "F1 bar", "labels", "y/o"); + for track in by_score { + println!( + "{:>6.3} {:>8.3} {:>8.3} {:>7.3} {:>2}/{:<2} {:<3} {}", + track.score(), + track.boundary_f1(0), + track.boundary_f1(BEATS_PER_BAR), + track.label_agreement(), + track.theirs.len(), + track.ours.len(), + if track.written_by_rekordbox { "rb" } else { "" }, + track.title + ); + } +} From e14201206364567e9cfe1293473aa33cf64fed80 Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 19:01:59 +0000 Subject: [PATCH 14/25] Drop the by-genre summary from phrase_score The algorithm is meant to work whatever the genre, so scores are only read overall and per track. Co-Authored-By: Claude Opus 5.5 --- .../crates/es-analyse/examples/phrase_score.rs | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/native/crates/es-analyse/examples/phrase_score.rs b/native/crates/es-analyse/examples/phrase_score.rs index edfd378..23a6792 100644 --- a/native/crates/es-analyse/examples/phrase_score.rs +++ b/native/crates/es-analyse/examples/phrase_score.rs @@ -45,7 +45,6 @@ struct Start { struct Scored { title: String, - genre: String, theirs: Vec, ours: Vec
, end_beat: BeatIndex, @@ -127,7 +126,6 @@ fn score(share: &Path, track: &Track) -> Result { .collect(); Ok(Scored { title, - genre: track.genre.clone(), theirs, ours: sections_on(&mono, f64::from(SAMPLE_RATE), &beats), end_beat: usize::from(structure.end_beat).min(beats.len()), @@ -282,21 +280,6 @@ fn report(tracks: &[Scored]) { println!("{:<11}{cells}", kind.name()); } - let mut genres: BTreeMap<&str, Vec> = BTreeMap::new(); - for track in tracks { - let genre = if track.genre.trim().is_empty() { "(no genre)" } else { track.genre.trim() }; - genres.entry(genre).or_default().push(track.score()); - } - println!("\n== By genre =="); - for (genre, scores) in &genres { - println!( - " {:<28} {:>3} tracks score {:.3}", - genre, - scores.len(), - scores.iter().sum::() / scores.len() as f64 - ); - } - let mut by_score: Vec<&Scored> = tracks.iter().collect(); by_score.sort_by(|a, b| a.score().total_cmp(&b.score())); let by_rekordbox = tracks.iter().filter(|t| t.written_by_rekordbox).count(); From fba1398a8e892798bab97d1ab84684e81ef3bb57 Mon Sep 17 00:00:00 2001 From: claw1200 Date: Sat, 28 Nov 2026 21:54:53 +0000 Subject: [PATCH 15/25] Find phrase starts with finer, per-group novelty on a 4-bar lattice Scored against the hand-set phrases in "phrase examples", exact start F1 rises from 0.697 to 0.851 on the tuning tracks and from 0.747 to 0.860 on the held-out quarter. phrase_score now holds out a quarter of the tracks, reports label errors with build and breakdown as one group, prints one track's phrases beside ours, and searches tunings. PHRASE_TUNING.md records the approach and each step. Co-Authored-By: Claude Opus 5.5 --- native/crates/es-analyse/PHRASE_TUNING.md | 132 ++++++++++ .../es-analyse/examples/phrase_score.rs | 229 ++++++++++++++++-- .../es-analyse/examples/structure_eval.rs | 33 +-- .../crates/es-analyse/examples/tunings/mod.rs | 36 +++ native/crates/es-analyse/src/structure.rs | 193 +++++++++------ 5 files changed, 505 insertions(+), 118 deletions(-) create mode 100644 native/crates/es-analyse/PHRASE_TUNING.md create mode 100644 native/crates/es-analyse/examples/tunings/mod.rs diff --git a/native/crates/es-analyse/PHRASE_TUNING.md b/native/crates/es-analyse/PHRASE_TUNING.md new file mode 100644 index 0000000..63c9e09 --- /dev/null +++ b/native/crates/es-analyse/PHRASE_TUNING.md @@ -0,0 +1,132 @@ +# Phrase tuning + +How we make the phrase (section) analysis in [`src/structure.rs`](src/structure.rs) agree with +phrasing set by hand, and what we have learnt doing it. + +## The benchmark + +The tracks in the rekordbox playlist **"phrase examples"** have been phrased by hand in the deck's +phrase editor (a developer option). Those phrases are the answer key. The benchmark is +[`examples/phrase_score.rs`](examples/phrase_score.rs): + +```sh +cd native +cargo run --release -p es-analyse --example phrase_score # scores +cargo run --release -p es-analyse --example phrase_score -- alarm # one track's phrases beside ours +cargo run --release -p es-analyse --example phrase_score -- --search # look for a better tuning +``` + +`--search` measures each track once, then tries each setting in +[`examples/tunings/mod.rs`](examples/tunings/mod.rs) in turn, keeping whichever raises the tuning +tracks' exact start F1, until none does. A run takes a few seconds per setting. + +For each track it decodes the audio, finds our sections on the track's own beatgrid, and compares +them with that track's hand-set phrases. A track is only ever compared with itself; nothing is +learnt from the other tracks. It reads a snapshot of the library and changes nothing. + +### Held-out tracks + +A fixed quarter of the tracks (chosen by a hash of the track id) are held out. The script shows +only their totals; tuning decisions are made on the other three quarters. If a change lifts the +tuning set but not the held-out set, it is fitting these particular tracks rather than phrasing in +general, and is not kept. + +### What is measured + +| Measure | Meaning | +|---|---| +| **start F1, exact** | Phrase starts we place on exactly the hand-set beat, as F1 against the hand-set starts (mean per track). **The main target.** | +| start F1, within a bar | The same, allowing a bar of slack. The gap to exact is how much is near misses. | +| label agreement | Share of beats whose label matches. | +| label error by group | For each hand-set label, the share of its beats we call something else, with **build and breakdown counted as one group**: UP vs DOWN is often a matter of taste. | +| starts found by sort | Hand-set starts found, split into the first phrase, changes of kind, and splits within one kind (two 8-bar intros rather than one 16-bar intro). | +| extra starts | Our starts with no hand-set start within a bar. Keeps us from simply placing more starts. | +| phrase lengths | How long hand-set and our phrases are, in bars. | + +### Targets + +- start F1, exact: **above 0.85** +- label error, every group: **under 15%** + +## How the hand-set phrasing is done + +- One mood (high), so the labels are INTRO, UP, DOWN, CHORUS, OUTRO; the score reads them as + intro, build, breakdown, drop, outro. +- A new phrase starts where an element changes, even if the section stays the same kind, so two + 8-bar intros next to each other are not the same as one 16-bar intro. +- The style is the same across genres; the algorithm is genre-agnostic and uses no genre tags. +- UP vs DOWN is often a toss-up, so the score does not hold that confusion against us. + +## How the algorithm works + +1. **Per-beat features.** Each beat gets a profile of the bar starting on it, in four groups: + timbre (12 band energies), harmony (chroma), rhythm (kick and hat onsets) and loudness. +2. **Novelty, per group.** For each group on its own, and for each beat, a checkerboard (Foote) + comparison of the bars counted back from the beat with the bars counted on from it, at widths + of 1, 2, 4 and 8 bars, each standardised and summed. The groups' novelties are then summed by + weight. Measuring groups apart matters: an element coming in shows in its own group, but is + diluted when every feature is compared together. +3. **Choosing the starts.** Starts fall on the grid's downbeats. Dynamic programming picks the set + of starts that earns the most novelty, less a threshold per start and a cost per phrase length + (8 and 16 bars free; other multiples of 4 bars, and 32, cost a little; over 32 bars or not a + multiple of 4 bars cost more). Each length is counted from the start before it. Each track + also has a 4-bar phrase lattice: all four phases are tried, starts off the lattice cost extra, + and the phase that earns most is kept. +4. **Labelling.** Loudness between the 10th and 95th percentiles stands for energy. Sections above + `drop_energy` are drops; the first section is the intro, a section leading into a drop is a + build, sections after the last drop are the outro, and the rest are breakdowns. + +## Baseline (first run on the hand-set phrases) + +| | tuning (50) | held out (14) | +|---|---|---| +| start F1, exact | 0.697 | 0.747 | +| start F1, within a bar | 0.750 | 0.768 | +| label error: intro / build+breakdown / drop / outro | 19.5 / 38.5 / 8.5 / 58.1% | 27.7 / 35.5 / 2.2 / 71.9% | +| phrases per track, hand-set vs ours | 12.0 vs 9.0 | 13.1 vs 10.1 | + +What the baseline showed: + +- **We miss starts more than we misplace them.** A bar of slack lifts F1 by only 0.05. We find + about two thirds of changes of kind and under half of same-kind splits, while only about one + in ten of our starts is extra. +- **The hand-set phrasing is very regular.** 720 of 721 starts are on a downbeat, 94% are on a + 4-bar lattice counted from the second phrase, and 79% on an 8-bar lattice. Phrases are 8 bars + (230) or 16 bars (215), sometimes 32 (28) or 4 (36), and never 48 or 64; ours ran to 48 and 64. +- **Loud outros read as drops** (58% of outro beats). + +## Log + +Each entry: the change, then start F1 exact and label errors on the tuning and held-out sets. + +### 1. Finer novelty, a phrase lattice, novelty per feature group + +| | tuning | held out | +|---|---|---| +| start F1, exact | 0.697 → **0.851** | 0.747 → **0.860** | +| label error: intro / build+breakdown / drop / outro | 26.0 / 27.6 / 3.7 / 38.5% | 28.8 / 28.6 / 0.0 / 62.4% | +| phrases per track, hand-set vs ours | 12.0 vs 12.9 | 13.1 vs 14.4 | + +Found, tuning set: kind changes 66% → 86%, same-kind splits 46% → 78%. + +- **The novelty widths were too wide.** Measured as how well novelty ranks hand-set starts above + other downbeats (AUC), same-kind splits rose from 0.71 with widths of 4 and 8 bars to 0.88 with + 1, 2 and 4, and kind changes from 0.90 to 0.94. Widths 1, 2, 4 and 8 together did best in the + full score. +- **The start chooser could only take local peaks of novelty**, and dropped everything after its + best-scoring start. It now considers every downbeat and always runs to the end of the track. +- **Length costs now match the hand-set lengths:** 8 and 16 bars free, 32 bars no longer free, + 20 and 28 bars treated like 12 and 24 rather than like 7. +- **A 4-bar phrase lattice per track** keeps a fill bar's novelty, which often peaks a bar before + the section, from pulling every later start a bar early. +- **Novelty per feature group** (rather than one distance over every feature) lifted exact F1 + from 0.810 to 0.832 before the final settings. +- Tried and dropped: a 48-value bar-pattern feature (per-beat band energies within the bar), and + combining group novelties by maximum or p-norms instead of a sum. + +What is left: +- Most remaining misses and extra starts are the same question: whether a 16-bar section, + usually a drop, splits into 8 + 8. Novelty answers it only weakly (AUC about 0.75 at those + midpoints). +- A few tracks have irregular phrasing (Overmono "If We Ever") or a pickup the lattice phase gets + wrong ("Nonplus", every start 2 bars off). diff --git a/native/crates/es-analyse/examples/phrase_score.rs b/native/crates/es-analyse/examples/phrase_score.rs index 23a6792..a6f793c 100644 --- a/native/crates/es-analyse/examples/phrase_score.rs +++ b/native/crates/es-analyse/examples/phrase_score.rs @@ -1,22 +1,63 @@ //! Scores our sections against the phrases set by hand on the tracks of the "phrase examples" //! playlist. Each track is compared only with itself: its own phrases against the sections we find -//! on its own grid. Reads a snapshot of the installed library and changes nothing. -//! `cargo run --release -p es-analyse --example phrase_score` +//! on its own grid. A quarter of the tracks are held out: only their totals are shown, so tuning +//! against the rest can be checked for overfitting. Reads a snapshot of the installed library and +//! changes nothing. See `PHRASE_TUNING.md` beside this crate's manifest. +//! `cargo run --release -p es-analyse --example phrase_score [-- | --search]`: with +//! title words, prints those tracks' phrases beside ours; with `--search`, looks for a better tuning. use std::collections::{BTreeMap, HashSet}; use std::path::Path; -use es_analyse::structure::{sections_on, BeatIndex, Section, SectionKind}; +use es_analyse::structure::{segment, BeatFeatures, BeatIndex, Section, SectionKind, Tuning}; use es_analyse::{decode_mono, Beat, SAMPLE_RATE}; use rayon::prelude::*; use rb_anlz::decode::{self, Tags}; use rb_anlz::phrase::{self, Mood, PhraseKind, SongStructure}; use rb_library::{Library, PlaylistKind, Track}; +#[path = "tunings/mod.rs"] +mod tunings; +use tunings::settings; + const PLAYLIST: &str = "phrase examples"; const BEATS_PER_BAR: usize = 4; /// How far a start may be from the hand-set one and still be found. const TOLERANCES: [(&str, usize); 2] = [("exact", 0), ("within a bar", BEATS_PER_BAR)]; +const HELD_OUT_ONE_IN: u64 = 4; +/// How much a setting must raise the exact start F1 for the search to take it. +const SEARCH_MIN_GAIN: f64 = 0.001; + +/// The labels a track is judged on: up and down are too often a matter of taste to tell apart. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum LabelGroup { + Intro, + BuildOrBreakdown, + Drop, + Outro, +} + +impl LabelGroup { + const ALL: [Self; 4] = [Self::Intro, Self::BuildOrBreakdown, Self::Drop, Self::Outro]; + + fn of(kind: SectionKind) -> Self { + match kind { + SectionKind::Intro => Self::Intro, + SectionKind::Build | SectionKind::Breakdown => Self::BuildOrBreakdown, + SectionKind::Drop => Self::Drop, + SectionKind::Outro => Self::Outro, + } + } + + fn name(self) -> &'static str { + match self { + Self::Intro => "intro", + Self::BuildOrBreakdown => "build/breakdown", + Self::Drop => "drop", + Self::Outro => "outro", + } + } +} /// Where a hand-set phrase start sits: the first, a change of kind, or a split within one kind. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] @@ -45,12 +86,21 @@ struct Start { struct Scored { title: String, + held_out: bool, theirs: Vec<Start>, ours: Vec<Section>, end_beat: BeatIndex, + features: BeatFeatures, written_by_rekordbox: bool, } +/// A fixed quarter of the tracks, chosen by id so adding tracks leaves the others where they were. +fn held_out(id: &str) -> bool { + let fnv = + id.bytes().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3)); + fnv % HELD_OUT_ONE_IN == 0 +} + /// Whether rekordbox wrote these phrases rather than this app: the app writes only the high mood, /// every numbered kind as its first variant, and no fill-ins. fn written_by_rekordbox(structure: &SongStructure) -> bool { @@ -87,14 +137,23 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { println!("{} tracks in \"{PLAYLIST}\"\n", tracks.len()); let results: Vec<Result<Scored, String>> = tracks.par_iter().map(|track| score(&share, track)).collect(); - let mut scored = Vec::new(); + let mut scored: Vec<Scored> = Vec::new(); for result in results { match result { Ok(track) => scored.push(track), Err(skipped) => println!("skipped {skipped}"), } } - report(&scored); + match std::env::args().nth(1).as_deref() { + Some("--search") => search(&mut scored), + Some(title_words) => timelines(&scored, title_words), + None => { + let (held, tuning): (Vec<Scored>, Vec<Scored>) = scored.into_iter().partition(|track| track.held_out); + summary("Tuning", &tuning); + summary("Held out", &held); + report(&tuning); + } + } Ok(()) } @@ -119,6 +178,7 @@ fn score(share: &Path, track: &Track) -> Result<Scored, String> { }) .collect(); let mono = decode_mono(Path::new(&track.folder_path)).map_err(|e| format!("{title}: {e}"))?; + let features = BeatFeatures::measure(&mono, f64::from(SAMPLE_RATE), &beats); let theirs = structure .phrases .iter() @@ -126,13 +186,67 @@ fn score(share: &Path, track: &Track) -> Result<Scored, String> { .collect(); Ok(Scored { title, + held_out: held_out(&track.id), theirs, - ours: sections_on(&mono, f64::from(SAMPLE_RATE), &beats), + ours: segment(&features, &Tuning::default()), + features, end_beat: usize::from(structure.end_beat).min(beats.len()), written_by_rekordbox: written_by_rekordbox(&structure), }) } +/// Each setting tried in turn, keeping whichever raises the tuning tracks' exact start F1 most, +/// until none does. Held-out tracks are re-scored only to be shown beside it. +fn search(tracks: &mut [Scored]) { + let mut best = Tuning::default(); + let mut best_scores = retuned(tracks, &best); + println!("default: {}", best_scores.line()); + for round in 1..=3 { + let mut improved = false; + for (label, candidate) in settings(&best).into_iter().flatten() { + let scores = retuned(tracks, &candidate); + if scores.tuning_f1 > best_scores.tuning_f1 + SEARCH_MIN_GAIN { + println!("round {round}, {label}: {}", scores.line()); + best = candidate; + best_scores = scores; + improved = true; + } + } + if !improved { + break; + } + } + println!("\nbest: {best:#?}"); +} + +struct SearchScores { + tuning_f1: f64, + held_out_f1: f64, + tuning_group_agreement: f64, +} + +impl SearchScores { + fn line(&self) -> String { + format!( + "start F1 {:.3}, held out {:.3}; label groups agree {:.3}", + self.tuning_f1, self.held_out_f1, self.tuning_group_agreement + ) + } +} + +fn retuned(tracks: &mut [Scored], tuning: &Tuning) -> SearchScores { + tracks.par_iter_mut().for_each(|track| track.ours = segment(&track.features, tuning)); + let (held, tune): (Vec<&Scored>, Vec<&Scored>) = tracks.iter().partition(|track| track.held_out); + let mean = |set: &[&Scored], value: fn(&Scored) -> f64| { + set.iter().map(|t| value(t)).sum::<f64>() / set.len().max(1) as f64 + }; + SearchScores { + tuning_f1: mean(&tune, |t| t.boundary_f1(0)), + held_out_f1: mean(&held, |t| t.boundary_f1(0)), + tuning_group_agreement: mean(&tune, Scored::group_agreement), + } +} + /// Hand-set starts paired one to one with ours no further than `tolerance` beats away, nearest /// pairs first, as (theirs, ours) indices. fn pairs(theirs: &[BeatIndex], ours: &[BeatIndex], tolerance: usize) -> Vec<(usize, usize)> { @@ -197,6 +311,12 @@ impl Scored { kinds.iter().filter(|(theirs, ours)| theirs == ours).count() as f64 / kinds.len().max(1) as f64 } + fn group_agreement(&self) -> f64 { + let kinds = self.beat_kinds(); + let agree = kinds.iter().filter(|(theirs, ours)| LabelGroup::of(*theirs) == LabelGroup::of(*ours)).count(); + agree as f64 / kinds.len().max(1) as f64 + } + fn score(&self) -> f64 { (self.boundary_f1(0) + self.label_agreement()) / 2.0 } @@ -214,23 +334,71 @@ fn percent(part: usize, whole: usize) -> String { format!("{:>5.1}%", 100.0 * part as f64 / whole.max(1) as f64) } -fn report(tracks: &[Scored]) { +/// Each label group's share of hand-set beats we label as another group, over every beat of the tracks. +fn group_errors(tracks: &[Scored]) -> [(LabelGroup, f64); 4] { + LabelGroup::ALL.map(|group| { + let theirs: Vec<LabelGroup> = tracks + .iter() + .flat_map(Scored::beat_kinds) + .filter(|(theirs, _)| LabelGroup::of(*theirs) == group) + .map(|(_, ours)| LabelGroup::of(ours)) + .collect(); + let wrong = theirs.iter().filter(|&&ours| ours != group).count(); + (group, wrong as f64 / theirs.len().max(1) as f64) + }) +} + +fn summary(name: &str, tracks: &[Scored]) { if tracks.is_empty() { return; } let mean = |value: fn(&Scored) -> f64| tracks.iter().map(value).sum::<f64>() / tracks.len() as f64; - println!("== Overall, {} tracks ==", tracks.len()); - println!("track score (mean) {:.3}", mean(Scored::score)); - println!("boundary F1, exact (mean) {:.3}", mean(|t| t.boundary_f1(0))); - println!("boundary F1, within a bar {:.3}", mean(|t| t.boundary_f1(BEATS_PER_BAR))); - println!("label agreement (mean) {:.3}", mean(Scored::label_agreement)); - let theirs: usize = tracks.iter().map(|t| t.theirs.len()).sum(); - let ours: usize = tracks.iter().map(|t| t.ours.len()).sum(); + let per_track = |count: fn(&Scored) -> usize| tracks.iter().map(count).sum::<usize>() as f64 / tracks.len() as f64; + println!("== {name}, {} tracks ==", tracks.len()); + println!("track score (mean) {:.3}", mean(Scored::score)); + println!("start F1, exact (mean) {:.3} target 0.85", mean(|t| t.boundary_f1(0))); + println!("start F1, within a bar {:.3}", mean(|t| t.boundary_f1(BEATS_PER_BAR))); + println!("label agreement (mean) {:.3}", mean(Scored::label_agreement)); + println!(" build and breakdown as one {:.3}", mean(Scored::group_agreement)); + let errors = group_errors(tracks); + let cells: Vec<String> = + errors.iter().map(|(group, error)| format!("{} {:.1}%", group.name(), 100.0 * error)).collect(); + println!("label error by group {} target each under 15%", cells.join(", ")); println!( - "phrases per track yours {:.1}, ours {:.1}", - theirs as f64 / tracks.len() as f64, - ours as f64 / tracks.len() as f64 + "phrases per track yours {:.1}, ours {:.1}\n", + per_track(|t| t.theirs.len()), + per_track(|t| t.ours.len()) ); +} + +/// Each track whose title holds `filter`, phrase by phrase in bars from its first beat. +fn timelines(tracks: &[Scored], filter: &str) { + let bar = |beat: BeatIndex| beat as f64 / BEATS_PER_BAR as f64; + for track in tracks.iter().filter(|t| t.title.to_lowercase().contains(&filter.to_lowercase())) { + println!("\n{}{}", track.title, if track.held_out { " (held out)" } else { "" }); + let mut rows: Vec<(BeatIndex, String, String)> = Vec::new(); + for start in &track.theirs { + rows.push((start.beat, start.kind.name().to_owned(), String::new())); + } + for section in &track.ours { + match rows.iter_mut().find(|row| row.0 == section.first_beat) { + Some(row) => row.2 = section.kind.name().to_owned(), + None => rows.push((section.first_beat, String::new(), section.kind.name().to_owned())), + } + } + rows.sort_by_key(|row| row.0); + println!(" {:>7} {:<10} {:<10}", "bar", "yours", "ours"); + for (beat, theirs, ours) in rows { + println!(" {:>7.2} {theirs:<10} {ours:<10}", bar(beat)); + } + } +} + +fn report(tracks: &[Scored]) { + if tracks.is_empty() { + return; + } + let ours: usize = tracks.iter().map(|t| t.ours.len()).sum(); println!("\n== Your phrase starts we found =="); println!("{:<18} {:>6} {:>8} {:>14}", "", "count", "exact", "within a bar"); @@ -280,6 +448,33 @@ fn report(tracks: &[Scored]) { println!("{:<11}{cells}", kind.name()); } + println!("\n== Phrase lengths in bars: yours, ours =="); + let lengths = |starts: Vec<BeatIndex>, end: BeatIndex| -> Vec<usize> { + starts.iter().zip(starts.iter().skip(1).copied().chain([end])).map(|(a, b)| b.saturating_sub(*a)).collect() + }; + let mut by_length: BTreeMap<String, (usize, usize)> = BTreeMap::new(); + let bars_of = |beats: usize| { + if beats.is_multiple_of(BEATS_PER_BAR) { + format!("{:>5}", beats / BEATS_PER_BAR) + } else { + format!("{:>5.2}", beats as f64 / BEATS_PER_BAR as f64) + } + }; + for track in tracks { + let theirs = lengths(track.their_beats(), track.end_beat); + let ours = lengths(track.our_beats(), track.end_beat); + // The last phrase runs to the track's end, so its length says nothing about phrasing. + for &beats in &theirs[..theirs.len().saturating_sub(1)] { + by_length.entry(bars_of(beats)).or_default().0 += 1; + } + for &beats in &ours[..ours.len().saturating_sub(1)] { + by_length.entry(bars_of(beats)).or_default().1 += 1; + } + } + for (bars, (theirs, ours)) in by_length.iter().filter(|(_, (t, o))| t + o >= 3) { + println!(" {bars} {theirs:>4} {ours:>4}"); + } + let mut by_score: Vec<&Scored> = tracks.iter().collect(); by_score.sort_by(|a, b| a.score().total_cmp(&b.score())); let by_rekordbox = tracks.iter().filter(|t| t.written_by_rekordbox).count(); diff --git a/native/crates/es-analyse/examples/structure_eval.rs b/native/crates/es-analyse/examples/structure_eval.rs index fb1328b..f16b327 100644 --- a/native/crates/es-analyse/examples/structure_eval.rs +++ b/native/crates/es-analyse/examples/structure_eval.rs @@ -16,6 +16,10 @@ use es_analyse::{analyse_samples, decode_mono, Options, SAMPLE_RATE}; use rayon::prelude::*; use serde_json::Value; +#[path = "tunings/mod.rs"] +mod tunings; +use tunings::settings; + #[path = "survey/mod.rs"] mod survey; use survey::{nearest_beat, share, survey_grid, Score, BEATS_PER_BAR, SURVEY_ON_BEAT_MS}; @@ -198,35 +202,6 @@ fn report_baselines(tracks: &[Track]) { println!("{}", ours.line("ours, default tuning")); } -type Setting = Vec<(String, Tuning)>; - -fn settings(base: &Tuning) -> Vec<Setting> { - let vary = |name: &'static str, values: &[f64], set: fn(&mut Tuning, f64)| -> Setting { - values - .iter() - .map(|&value| { - let mut tuning = *base; - set(&mut tuning, value); - (format!("{name} {value}"), tuning) - }) - .collect() - }; - let kernels = [[2, 4], [4, 8], [4, 16], [2, 8], [8, 16]] - .iter() - .map(|&widths| (format!("kernels {widths:?}"), Tuning { kernel_half_widths: widths, ..*base })) - .collect(); - vec![ - vary("threshold", &[0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5], |t, v| t.boundary_threshold = v), - vary("uncommon length", &[0.0, 0.25, 0.5, 1.0], |t, v| t.uncommon_length_cost = v), - vary("odd length", &[0.5, 1.0, 1.5, 2.0, 3.0], |t, v| t.odd_length_cost = v), - kernels, - vary("timbre", &[0.0, 0.5, 1.0, 2.0], |t, v| t.timbre_weight = v), - vary("harmony", &[0.5, 1.0, 2.0, 3.0], |t, v| t.harmony_weight = v), - vary("rhythm", &[0.0, 0.5, 1.0, 2.0], |t, v| t.rhythm_weight = v), - vary("loudness", &[0.0, 0.5, 1.0, 2.0], |t, v| t.loudness_weight = v), - ] -} - fn tune(tracks: &[Track]) -> Tuning { let mut best = Tuning::default(); let mut best_score = score(tracks, &best); diff --git a/native/crates/es-analyse/examples/tunings/mod.rs b/native/crates/es-analyse/examples/tunings/mod.rs new file mode 100644 index 0000000..a51379f --- /dev/null +++ b/native/crates/es-analyse/examples/tunings/mod.rs @@ -0,0 +1,36 @@ +//! The settings a tuning search tries, each varied on its own from a base tuning. + +use es_analyse::structure::Tuning; + +pub type Setting = Vec<(String, Tuning)>; + +pub fn settings(base: &Tuning) -> Vec<Setting> { + let vary = |name: &'static str, values: &[f64], set: fn(&mut Tuning, f64)| -> Setting { + values + .iter() + .map(|&value| { + let mut tuning = *base; + set(&mut tuning, value); + (format!("{name} {value}"), tuning) + }) + .collect() + }; + let kernels: &[&'static [usize]] = &[&[1, 2, 4], &[1, 2, 4, 8], &[1, 4, 8], &[1, 2, 8], &[2, 4, 8]]; + vec![ + vary("threshold", &[0.25, 0.5, 0.75, 1.0], |t, v| t.boundary_threshold = v), + vary("4-bar multiple", &[0.25, 0.5, 1.0, 1.5], |t, v| t.four_bar_multiple_cost = v), + vary("32 bars", &[0.0, 0.5, 1.0, 2.0], |t, v| t.thirty_two_bar_cost = v), + vary("over 32 bars", &[1.0, 2.0, 3.0, 5.0], |t, v| t.over_thirty_two_bar_cost = v), + vary("odd length", &[2.0, 3.0, 4.0, 6.0], |t, v| t.odd_length_cost = v), + vary("off lattice", &[0.0, 0.5, 1.0, 2.0], |t, v| t.off_lattice_cost = v), + vary("timbre", &[0.5, 1.0, 1.5, 2.0], |t, v| t.timbre_weight = v), + vary("harmony", &[0.5, 1.0, 2.0, 3.0], |t, v| t.harmony_weight = v), + vary("rhythm", &[0.0, 0.5, 1.0, 2.0], |t, v| t.rhythm_weight = v), + vary("loudness", &[0.0, 0.5, 1.0, 2.0], |t, v| t.loudness_weight = v), + vary("drop energy", &[0.4, 0.5, 0.6, 0.7], |t, v| t.drop_energy = v), + kernels + .iter() + .map(|&widths| (format!("kernels {widths:?}"), Tuning { kernel_half_widths: widths, ..*base })) + .collect(), + ] +} diff --git a/native/crates/es-analyse/src/structure.rs b/native/crates/es-analyse/src/structure.rs index 4444a28..7c82e1a 100644 --- a/native/crates/es-analyse/src/structure.rs +++ b/native/crates/es-analyse/src/structure.rs @@ -3,13 +3,15 @@ //! Every beat gets a profile of the bar that starts on it: its timbre, harmony, rhythm and loudness. //! A beat is a likely section start when the bars counted on from it sound unlike the bars counted //! back from it, while each side sounds like itself: Foote's checkerboard novelty over the bars' -//! self-similarity. Counting bars from every beat, rather than from the grid's downbeats, keeps a -//! downbeat that is off by a beat from moving every section with it. +//! self-similarity, at widths from one bar to eight. Counting bars from every beat, rather than +//! from the grid's downbeats, keeps a downbeat that is off by a beat from moving every section. //! //! The starts are then chosen together, by dynamic programming: each section's length is counted -//! from the start before it, and lengths of 8, 16 and 32 bars cost nothing while others cost a -//! little. A section of an odd length is taken when the music clearly changes there, and every -//! section after it follows on from it rather than from a grid fixed for the whole track. +//! from the start before it, and lengths of 8 and 16 bars cost nothing while others cost a little. +//! Starts off the track's 4-bar phrase lattice cost a little more. A section of an odd length is +//! taken when the music clearly changes there, and every section after it follows on from it. +//! +//! `PHRASE_TUNING.md` beside this crate's manifest records how this is scored and tuned. use serde::{Deserialize, Serialize}; @@ -30,6 +32,7 @@ const PHASE_VOTE_FROM: BeatIndex = 2 * BEATS_PER_BAR; const PHASE_VOTE_FLOOR: f64 = 1.0; const PHASE_VOTE_CAP: f64 = 3.0; const LONGEST_SECTION: Bars = 64; +const LATTICE_BARS: Bars = 4; const FLAT_SPREAD: f64 = 1e-9; const QUIET_PERCENTILE: f64 = 0.1; const LOUD_PERCENTILE: f64 = 0.95; @@ -77,13 +80,18 @@ pub struct Tuning { pub harmony_weight: f64, pub rhythm_weight: f64, pub loudness_weight: f64, - pub kernel_half_widths: [Bars; 2], + pub kernel_half_widths: &'static [Bars], /// Standard deviations of novelty a beat must stand above the track's typical beat to start a section. pub boundary_threshold: f64, - /// Novelty given up for a section of 4, 12, 24, 48 or 64 bars rather than 8, 16 or 32. - pub uncommon_length_cost: f64, - /// Novelty given up for a section of any other whole number of bars. + /// Novelty given up for a section of 4, 12, 20, 24 or 28 bars rather than 8 or 16. + pub four_bar_multiple_cost: f64, + pub thirty_two_bar_cost: f64, + /// Novelty given up for a section of 36 bars or more, which also caps how long the last one runs. + pub over_thirty_two_bar_cost: f64, + /// Novelty given up for a section whose length isn't a multiple of 4 bars. pub odd_length_cost: f64, + /// Novelty given up for a start off the track's 4-bar phrase lattice. + pub off_lattice_cost: f64, /// How far from the quietest section towards the most energetic a section must reach to be a drop. pub drop_energy: f64, } @@ -95,10 +103,13 @@ impl Default for Tuning { harmony_weight: 2.0, rhythm_weight: 1.0, loudness_weight: 0.5, - kernel_half_widths: [4, 8], - boundary_threshold: 0.25, - uncommon_length_cost: 0.5, + kernel_half_widths: &[1, 2, 4, 8], + boundary_threshold: 0.5, + four_bar_multiple_cost: 1.0, + thirty_two_bar_cost: 1.0, + over_thirty_two_bar_cost: 3.0, odd_length_cost: 3.0, + off_lattice_cost: 1.0, drop_energy: 0.6, } } @@ -149,6 +160,26 @@ impl BeatFeatures { pub fn beats(&self) -> Beats { self.on_downbeat.len() } + + /// The standardised columns of each feature group, with the group's weight. + fn groups(&self, tuning: &Tuning) -> [(Vec<Vec<f64>>, f64); 4] { + [ + (columns_of(&self.timbre), tuning.timbre_weight), + (columns_of(&self.harmony), tuning.harmony_weight), + (vec![standardise(&self.kick), standardise(&self.hats)], tuning.rhythm_weight), + (vec![standardise(&self.loudness)], tuning.loudness_weight), + ] + } +} + +fn columns_of<const N: usize>(rows: &[[f64; N]]) -> Vec<Vec<f64>> { + (0..N).map(|i| standardise(&rows.iter().map(|row| row[i]).collect::<Vec<f64>>())).collect() +} + +/// A group's columns weighted so the group weighs `weight` in a distance however many columns it has. +fn weighted(columns: Vec<Vec<f64>>, weight: f64) -> Vec<(Vec<f64>, f64)> { + let share = weight / (columns.len() as f64).sqrt(); + columns.into_iter().map(|column| (column, share)).collect() } /// The sections of `mono` on `grid`, with the default tuning. @@ -164,20 +195,39 @@ pub fn segment(features: &BeatFeatures, tuning: &Tuning) -> Vec<Section> { name_sections(features, &starts, tuning) } -fn novelty(distances: &Distances, tuning: &Tuning) -> Vec<f64> { - let summed = tuning - .kernel_half_widths - .iter() - .map(|&half_width| standardise(&distances.novelty(half_width))) - .fold(vec![0.0; distances.beats], |sum, part| sum.iter().zip(&part).map(|(a, b)| a + b).collect()); - standardise(&summed) +/// Each feature group's novelty on its own, summed by weight: an element coming in or dropping +/// out stands out in its own group but is diluted among all the features together. +fn novelty(features: &BeatFeatures, tuning: &Tuning) -> Vec<f64> { + let widest = tuning.kernel_half_widths.iter().copied().max().unwrap_or(1); + let reach = 2 * widest * BEATS_PER_BAR; + let summed = features.groups(tuning).into_iter().filter(|(_, weight)| *weight > 0.0).map(|(columns, weight)| { + let distances = Distances::between(&weighted(columns, 1.0), features.beats(), reach); + let widths = tuning.kernel_half_widths.iter().map(|&half_width| standardise(&distances.novelty(half_width))); + standardise(&sum_columns(widths, features.beats())).into_iter().map(|novelty| weight * novelty).collect() + }); + standardise(&sum_columns(summed, features.beats())) +} + +fn sum_columns(columns: impl Iterator<Item = Vec<f64>>, len: usize) -> Vec<f64> { + columns.fold(vec![0.0; len], |sum, column| sum.iter().zip(&column).map(|(a, b)| a + b).collect()) } fn length_cost(bars: Bars, tuning: &Tuning) -> f64 { match bars { - 8 | 16 | 32 => 0.0, - 4 | 12 | 24 | 48 | 64 => tuning.uncommon_length_cost, - _ => tuning.odd_length_cost, + 8 | 16 => 0.0, + 32 => tuning.thirty_two_bar_cost, + _ if !bars.is_multiple_of(LATTICE_BARS) => tuning.odd_length_cost, + _ if bars > 32 => tuning.over_thirty_two_bar_cost, + _ => tuning.four_bar_multiple_cost, + } +} + +/// The last section runs to wherever the track ends, so only running long counts against it. +fn last_length_cost(bars: Bars, tuning: &Tuning) -> f64 { + if bars > 32 { + tuning.over_thirty_two_bar_cost + } else { + 0.0 } } @@ -190,8 +240,12 @@ fn grid_phase(on_downbeat: &[bool]) -> Beats { /// shift of one beat. Every clear change then votes for the beat of the bar it peaks on, its vote /// capped so one outsized change can't outvote the rest. pub fn bar_phase_votes(features: &BeatFeatures) -> [f64; BEATS_PER_BAR] { - let tuning = Tuning::default(); - bar_phase_votes_between(&Distances::between_beats(features, &tuning, 2 * BEATS_PER_BAR)) + let columns: Vec<(Vec<f64>, f64)> = features + .groups(&Tuning::default()) + .into_iter() + .flat_map(|(columns, weight)| weighted(columns, weight)) + .collect(); + bar_phase_votes_between(&Distances::between(&columns, features.beats(), 2 * BEATS_PER_BAR)) } fn bar_phase_votes_between(distances: &Distances) -> [f64; BEATS_PER_BAR] { @@ -219,41 +273,53 @@ pub fn bar_phase(on_downbeat: &[bool], votes: &[f64; BEATS_PER_BAR], trust: f64) } } -/// The section starts that earn the most novelty, less what their lengths cost. The track's first -/// beat always starts a section, and the others fall on the grid's downbeats; each section's length -/// is counted from the start before it, so after an odd-length section the rest follow on from it. +/// The section starts that earn the most novelty, less what their lengths and places cost. The +/// track's first beat always starts a section and the others fall on the grid's downbeats. Each +/// section's length is counted from the start before it, so after an odd-length section the rest +/// follow on from it, and starts on the track's 4-bar phrase lattice cost nothing; every lattice +/// is tried and the one that earns most is kept. fn section_starts(features: &BeatFeatures, tuning: &Tuning) -> Vec<BeatIndex> { - let widest = tuning.kernel_half_widths.iter().copied().max().unwrap_or(1); - let distances = Distances::between_beats(features, tuning, 2 * widest * BEATS_PER_BAR); - let novelty = novelty(&distances, tuning); - let lines: Vec<BeatIndex> = - (grid_phase(&features.on_downbeat)..features.beats()).step_by(BEATS_PER_BAR).filter(|&b| b > 0).collect(); - let is_peak = |index: usize| { - let around = index.saturating_sub(1)..(index + 2).min(lines.len()); - around.into_iter().all(|other| novelty[lines[other]] <= novelty[lines[index]]) - }; + let novelty = novelty(features, tuning); + let first_downbeat = grid_phase(&features.on_downbeat); + let lines: Vec<BeatIndex> = std::iter::once(0) + .chain((first_downbeat..features.beats()).step_by(BEATS_PER_BAR).filter(|&b| b > 0)) + .collect(); + let bar_of = |line: usize| lines[line].saturating_sub(first_downbeat) / BEATS_PER_BAR; + (0..LATTICE_BARS) + .map(|lattice_phase| { + let gain = |line: usize| { + let on_lattice = bar_of(line) % LATTICE_BARS == lattice_phase; + let lattice_cost = if on_lattice { 0.0 } else { tuning.off_lattice_cost }; + novelty[lines[line]] - tuning.boundary_threshold - lattice_cost + }; + best_starts(&lines, gain, tuning) + }) + .max_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, starts)| starts) + .unwrap_or_default() +} +/// The starts among `lines` that earn the most `gain`, less their lengths' costs, with what they earn. +fn best_starts(lines: &[BeatIndex], gain: impl Fn(usize) -> f64, tuning: &Tuning) -> (f64, Vec<BeatIndex>) { let mut best = vec![f64::NEG_INFINITY; lines.len()]; - let mut previous: Vec<Option<usize>> = vec![None; lines.len()]; - for index in (0..lines.len()).filter(|&index| is_peak(index)) { - let gain = novelty[lines[index]] - tuning.boundary_threshold; - best[index] = gain; - for bars in 1..=LONGEST_SECTION.min(index) { - let before = index - bars; - let total = best[before] + gain - length_cost(bars, tuning); - if total > best[index] { - best[index] = total; - previous[index] = Some(before); + let mut previous = vec![0; lines.len()]; + best[0] = 0.0; + for line in 1..lines.len() { + let gain = gain(line); + for bars in 1..=LONGEST_SECTION.min(line) { + let total = best[line - bars] + gain - length_cost(bars, tuning); + if total > best[line] { + best[line] = total; + previous[line] = line - bars; } } } - - let last = (0..lines.len()).filter(|&index| best[index] > 0.0).max_by(|&a, &b| best[a].total_cmp(&best[b])); - let mut chosen: Vec<BeatIndex> = - std::iter::successors(last, |&index| previous[index]).map(|index| lines[index]).collect(); - chosen.push(0); - chosen.reverse(); - chosen + let closing = |line: usize| best[line] - last_length_cost(lines.len() - line, tuning); + let last = (0..lines.len()).max_by(|&a, &b| closing(a).total_cmp(&closing(b))).unwrap_or(0); + let mut starts: Vec<BeatIndex> = + std::iter::successors(Some(last), |&line| (line > 0).then(|| previous[line])).map(|line| lines[line]).collect(); + starts.reverse(); + (closing(last), starts) } /// Distances between the profiles of beats no further apart than `reach`. @@ -264,30 +330,13 @@ struct Distances { } impl Distances { - fn between_beats(features: &BeatFeatures, tuning: &Tuning, reach: Beats) -> Self { - let beats = features.beats(); - let mut columns: Vec<(Vec<f64>, f64)> = Vec::new(); - let mut add_group = |group: Vec<Vec<f64>>, weight: f64| { - let share = weight / (group.len() as f64).sqrt(); - columns.extend(group.into_iter().map(|column| (standardise(&column), share))); - }; - add_group( - (0..BANDS).map(|band| features.timbre.iter().map(|beat| beat[band]).collect()).collect(), - tuning.timbre_weight, - ); - add_group( - (0..12).map(|pitch| features.harmony.iter().map(|beat| beat[pitch]).collect()).collect(), - tuning.harmony_weight, - ); - add_group(vec![features.kick.clone(), features.hats.clone()], tuning.rhythm_weight); - add_group(vec![features.loudness.clone()], tuning.loudness_weight); - + fn between(columns: &[(Vec<f64>, f64)], beats: Beats, reach: Beats) -> Self { let mut values = vec![0.0; beats * reach]; for a in 0..beats { for offset in 1..=reach.min(beats - 1 - a) { let b = a + offset; let squared: f64 = - columns.iter().map(|(column, share)| (share * (column[a] - column[b])).powi(2)).sum(); + columns.iter().map(|(column, weight)| (weight * (column[a] - column[b])).powi(2)).sum(); values[a * reach + offset - 1] = squared.sqrt(); } } From f1c749ffed897c8bb8c22366b5ab1195d9e8a712 Mon Sep 17 00:00:00 2001 From: claw1200 <carstenwood12@gmail.com> Date: Sat, 28 Nov 2026 22:15:58 +0000 Subject: [PATCH 16/25] Label sections by a stricter drop, drums alone, and the intro's length On the hand-set phrases, every label group's error on the tuning tracks is now under 15% (intro 13.5%, build/breakdown 13.5%, drop 11.7%, outro 11.3%), from 26/28/4/39%. Drops need more energy and can't be drums alone, which keeps loud DJ intros and outros out of them; the intro runs 16 bars, or up to 32 while its energy holds. phrase_score gains --on-your-starts to score labelling apart from placing starts, and its search weighs label errors. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- native/crates/es-analyse/PHRASE_TUNING.md | 49 +++++++++++++-- .../es-analyse/examples/phrase_score.rs | 63 +++++++++++++------ .../crates/es-analyse/examples/tunings/mod.rs | 5 +- native/crates/es-analyse/src/structure.rs | 61 ++++++++++++------ 4 files changed, 135 insertions(+), 43 deletions(-) diff --git a/native/crates/es-analyse/PHRASE_TUNING.md b/native/crates/es-analyse/PHRASE_TUNING.md index 63c9e09..eb8bbfd 100644 --- a/native/crates/es-analyse/PHRASE_TUNING.md +++ b/native/crates/es-analyse/PHRASE_TUNING.md @@ -14,11 +14,17 @@ cd native cargo run --release -p es-analyse --example phrase_score # scores cargo run --release -p es-analyse --example phrase_score -- alarm # one track's phrases beside ours cargo run --release -p es-analyse --example phrase_score -- --search # look for a better tuning +cargo run --release -p es-analyse --example phrase_score -- --on-your-starts # label the hand-set phrases ``` +`--on-your-starts` labels the hand-set phrases themselves, so labelling can be judged apart from +where the starts are placed. + `--search` measures each track once, then tries each setting in [`examples/tunings/mod.rs`](examples/tunings/mod.rs) in turn, keeping whichever raises the tuning -tracks' exact start F1, until none does. A run takes a few seconds per setting. +tracks' exact start F1 less their worst label group's error, until none does. A run takes a few +seconds per setting. Check what it finds against the held-out tracks before keeping it: with +around 50 tracks it will happily fit their quirks. For each track it decodes the audio, finds our sections on the track's own beatgrid, and compares them with that track's hand-set phrases. A track is only ever compared with itself; nothing is @@ -72,9 +78,14 @@ general, and is not kept. multiple of 4 bars cost more). Each length is counted from the start before it. Each track also has a 4-bar phrase lattice: all four phases are tried, starts off the lattice cost extra, and the phase that earns most is kept. -4. **Labelling.** Loudness between the 10th and 95th percentiles stands for energy. Sections above - `drop_energy` are drops; the first section is the intro, a section leading into a drop is a - build, sections after the last drop are the outro, and the rest are breakdowns. +4. **Labelling.** Loudness between the 10th and 95th percentiles stands for energy. + - **Drops** are sections above `drop_energy` (0.75), unless they are drums alone: a kick that + outweighs the mids, as in DJ-friendly intros and outros. A drop's bass masks its kick and + its lead fills the mids. + - **Intro:** the first section, and the sections before the first drop that end within 16 + bars; up to 32 bars while they keep `intro_energy` (a breakdown is where the beat drops out). + - **Outro:** every section after the last drop. + - **Build:** a section leading into a drop. **Breakdown:** the rest. ## Baseline (first run on the hand-set phrases) @@ -130,3 +141,33 @@ What is left: midpoints). - A few tracks have irregular phrasing (Overmono "If We Ever") or a pickup the lattice phase gets wrong ("Nonplus", every start 2 bars off). + +### 2. Labels: a stricter drop, drums alone, and an intro by length and energy + +| | tuning | held out | +|---|---|---| +| start F1, exact | 0.851 | 0.860 | +| label error: intro / build+breakdown / drop / outro | 26.0 / 27.6 / 3.7 / 38.5% → **13.5 / 13.5 / 11.7 / 11.3%** | 28.8 / 28.6 / 0.0 / 62.4% → 21.9 / 16.1 / 5.4 / 14.8% | +| the same on the hand-set starts | 11.5 / 12.7 / 10.1 / 3.2% | 19.2 / 18.4 / 6.0 / 9.9% | + +- **Labelling, not placement, was the problem:** on the hand-set starts the label errors were + nearly as bad as on ours. +- **Drops were called too readily.** Within a track, loudness ranks drops above everything else + well (AUC 0.96); the line was simply too low. Raised from 0.6 to 0.75. +- **Loud intros and outros** have drums without the rest: their kick stands about 1.4 standard + deviations above the track's, their 270 Hz – 4.6 kHz bands about 0.6 below. Drops are the + reverse. Excluding drums-alone sections from drops took outro error from 37% to 3% on the + hand-set starts. +- **Where the intro ends** was the hardest call. The hand-set intros are almost always 1 to 3 + sections, 8 to 32 bars in all, followed by breakdowns and builds. Calling everything before + the build intro (as before) or cutting at a fixed length swapped intro errors for breakdown + errors; sure intro up to 16 bars, then up to 32 bars while the energy holds, balances them. +- Tried and dropped: blending mid-band energy into the drop energy, or gating energy by it (fixed + outros but broke techno drops, which have few mids); a per-track drop line by Otsu's split + (worse); similarity to the track's main drop (no better than loudness alone). + +What is left: +- The held-out tracks miss the label target on intros (21.9%) and builds/breakdowns (16.1%). + Several of them open with two 16-bar intros, the case the intro rule finds hardest; there are + only about 20 such sections across all the tracks, too few to tune a finer rule on safely. +- Up vs down (build vs breakdown) is not scored; ours agree with yours about 55% of the time. diff --git a/native/crates/es-analyse/examples/phrase_score.rs b/native/crates/es-analyse/examples/phrase_score.rs index a6f793c..1f4eab1 100644 --- a/native/crates/es-analyse/examples/phrase_score.rs +++ b/native/crates/es-analyse/examples/phrase_score.rs @@ -3,13 +3,15 @@ //! on its own grid. A quarter of the tracks are held out: only their totals are shown, so tuning //! against the rest can be checked for overfitting. Reads a snapshot of the installed library and //! changes nothing. See `PHRASE_TUNING.md` beside this crate's manifest. -//! `cargo run --release -p es-analyse --example phrase_score [-- <title words> | --search]`: with -//! title words, prints those tracks' phrases beside ours; with `--search`, looks for a better tuning. +//! `cargo run --release -p es-analyse --example phrase_score [-- <title words> | --search | +//! --on-your-starts]`: with title words, prints those tracks' phrases beside ours; with +//! `--search`, looks for a better tuning; with `--on-your-starts`, labels the hand-set phrases +//! themselves, to score labelling apart from placing starts. use std::collections::{BTreeMap, HashSet}; use std::path::Path; -use es_analyse::structure::{segment, BeatFeatures, BeatIndex, Section, SectionKind, Tuning}; +use es_analyse::structure::{name_sections, segment, BeatFeatures, BeatIndex, Section, SectionKind, Tuning}; use es_analyse::{decode_mono, Beat, SAMPLE_RATE}; use rayon::prelude::*; use rb_anlz::decode::{self, Tags}; @@ -25,7 +27,7 @@ const BEATS_PER_BAR: usize = 4; /// How far a start may be from the hand-set one and still be found. const TOLERANCES: [(&str, usize); 2] = [("exact", 0), ("within a bar", BEATS_PER_BAR)]; const HELD_OUT_ONE_IN: u64 = 4; -/// How much a setting must raise the exact start F1 for the search to take it. +/// How much a setting must raise the search's objective for the search to take it. const SEARCH_MIN_GAIN: f64 = 0.001; /// The labels a track is judged on: up and down are too often a matter of taste to tell apart. @@ -146,17 +148,25 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { } match std::env::args().nth(1).as_deref() { Some("--search") => search(&mut scored), - Some(title_words) => timelines(&scored, title_words), - None => { - let (held, tuning): (Vec<Scored>, Vec<Scored>) = scored.into_iter().partition(|track| track.held_out); - summary("Tuning", &tuning); - summary("Held out", &held); - report(&tuning); + Some("--on-your-starts") => { + for track in &mut scored { + track.ours = name_sections(&track.features, &track.their_beats(), &Tuning::default()); + } + report_all(scored); } + Some(title_words) => timelines(&scored, title_words), + None => report_all(scored), } Ok(()) } +fn report_all(scored: Vec<Scored>) { + let (held, tuning): (Vec<Scored>, Vec<Scored>) = scored.into_iter().partition(|track| track.held_out); + summary("Tuning", &tuning); + summary("Held out", &held); + report(&tuning); +} + fn score(share: &Path, track: &Track) -> Result<Scored, String> { let title = format!("{} - {}", track.artist, track.title); let analysis = |suffix| { @@ -195,8 +205,8 @@ fn score(share: &Path, track: &Track) -> Result<Scored, String> { }) } -/// Each setting tried in turn, keeping whichever raises the tuning tracks' exact start F1 most, -/// until none does. Held-out tracks are re-scored only to be shown beside it. +/// Each setting tried in turn, keeping whichever raises the tuning tracks' exact start F1 less +/// their worst label group's error, until none does. Held-out tracks are re-scored only to be shown beside it. fn search(tracks: &mut [Scored]) { let mut best = Tuning::default(); let mut best_scores = retuned(tracks, &best); @@ -205,7 +215,7 @@ fn search(tracks: &mut [Scored]) { let mut improved = false; for (label, candidate) in settings(&best).into_iter().flatten() { let scores = retuned(tracks, &candidate); - if scores.tuning_f1 > best_scores.tuning_f1 + SEARCH_MIN_GAIN { + if scores.objective() > best_scores.objective() + SEARCH_MIN_GAIN { println!("round {round}, {label}: {}", scores.line()); best = candidate; best_scores = scores; @@ -222,18 +232,31 @@ fn search(tracks: &mut [Scored]) { struct SearchScores { tuning_f1: f64, held_out_f1: f64, - tuning_group_agreement: f64, + tuning_worst_label_error: f64, + held_out_worst_label_error: f64, } impl SearchScores { + /// Start placement and labelling weigh alike: each target is a share of beats or starts. + fn objective(&self) -> f64 { + self.tuning_f1 - self.tuning_worst_label_error + } + fn line(&self) -> String { format!( - "start F1 {:.3}, held out {:.3}; label groups agree {:.3}", - self.tuning_f1, self.held_out_f1, self.tuning_group_agreement + "start F1 {:.3}, held out {:.3}; worst label group error {:.1}%, held out {:.1}%", + self.tuning_f1, + self.held_out_f1, + 100.0 * self.tuning_worst_label_error, + 100.0 * self.held_out_worst_label_error ) } } +fn worst_label_error<'a>(tracks: impl IntoIterator<Item = &'a Scored> + Clone) -> f64 { + group_errors(tracks).iter().map(|(_, error)| *error).fold(0.0, f64::max) +} + fn retuned(tracks: &mut [Scored], tuning: &Tuning) -> SearchScores { tracks.par_iter_mut().for_each(|track| track.ours = segment(&track.features, tuning)); let (held, tune): (Vec<&Scored>, Vec<&Scored>) = tracks.iter().partition(|track| track.held_out); @@ -243,7 +266,8 @@ fn retuned(tracks: &mut [Scored], tuning: &Tuning) -> SearchScores { SearchScores { tuning_f1: mean(&tune, |t| t.boundary_f1(0)), held_out_f1: mean(&held, |t| t.boundary_f1(0)), - tuning_group_agreement: mean(&tune, Scored::group_agreement), + tuning_worst_label_error: worst_label_error(tune.iter().copied()), + held_out_worst_label_error: worst_label_error(held.iter().copied()), } } @@ -335,10 +359,11 @@ fn percent(part: usize, whole: usize) -> String { } /// Each label group's share of hand-set beats we label as another group, over every beat of the tracks. -fn group_errors(tracks: &[Scored]) -> [(LabelGroup, f64); 4] { +fn group_errors<'a>(tracks: impl IntoIterator<Item = &'a Scored> + Clone) -> [(LabelGroup, f64); 4] { LabelGroup::ALL.map(|group| { let theirs: Vec<LabelGroup> = tracks - .iter() + .clone() + .into_iter() .flat_map(Scored::beat_kinds) .filter(|(theirs, _)| LabelGroup::of(*theirs) == group) .map(|(_, ours)| LabelGroup::of(ours)) diff --git a/native/crates/es-analyse/examples/tunings/mod.rs b/native/crates/es-analyse/examples/tunings/mod.rs index a51379f..b50a803 100644 --- a/native/crates/es-analyse/examples/tunings/mod.rs +++ b/native/crates/es-analyse/examples/tunings/mod.rs @@ -27,7 +27,10 @@ pub fn settings(base: &Tuning) -> Vec<Setting> { vary("harmony", &[0.5, 1.0, 2.0, 3.0], |t, v| t.harmony_weight = v), vary("rhythm", &[0.0, 0.5, 1.0, 2.0], |t, v| t.rhythm_weight = v), vary("loudness", &[0.0, 0.5, 1.0, 2.0], |t, v| t.loudness_weight = v), - vary("drop energy", &[0.4, 0.5, 0.6, 0.7], |t, v| t.drop_energy = v), + vary("drop energy", &[0.4, 0.5, 0.6, 0.65, 0.7, 0.75, 0.8], |t, v| t.drop_energy = v), + vary("drums alone", &[0.25, 0.5, 0.75, 1.0, 1.5], |t, v| t.drums_alone_line = v), + vary("longest intro", &[16.0, 24.0, 32.0], |t, v| t.longest_intro = v as usize), + vary("intro energy", &[0.4, 0.5, 0.6, 0.7], |t, v| t.intro_energy = v), kernels .iter() .map(|&widths| (format!("kernels {widths:?}"), Tuning { kernel_half_widths: widths, ..*base })) diff --git a/native/crates/es-analyse/src/structure.rs b/native/crates/es-analyse/src/structure.rs index 7c82e1a..a6e09e8 100644 --- a/native/crates/es-analyse/src/structure.rs +++ b/native/crates/es-analyse/src/structure.rs @@ -33,6 +33,9 @@ const PHASE_VOTE_FLOOR: f64 = 1.0; const PHASE_VOTE_CAP: f64 = 3.0; const LONGEST_SECTION: Bars = 64; const LATTICE_BARS: Bars = 4; +const MID_BANDS: std::ops::RangeInclusive<usize> = 4..=9; +/// Sections before the first drop that end within this many bars are intro, however loud. +const SURE_INTRO_BARS: Bars = 16; const FLAT_SPREAD: f64 = 1e-9; const QUIET_PERCENTILE: f64 = 0.1; const LOUD_PERCENTILE: f64 = 0.95; @@ -94,6 +97,15 @@ pub struct Tuning { pub off_lattice_cost: f64, /// How far from the quietest section towards the most energetic a section must reach to be a drop. pub drop_energy: f64, + /// Standard deviations by which a section's kick must outweigh its mids for it to be drums + /// alone, as DJ-friendly intros and outros are, and never a drop however loud: a drop's bass + /// masks its kick, and its lead fills the mids. + pub drums_alone_line: f64, + /// Sections before the first drop stay intro while they end within this many bars of the + /// start, those ending after the first 16 bars only while they keep `intro_energy`: a + /// breakdown is where the beat drops out. + pub longest_intro: Bars, + pub intro_energy: f64, } impl Default for Tuning { @@ -110,7 +122,10 @@ impl Default for Tuning { over_thirty_two_bar_cost: 3.0, odd_length_cost: 3.0, off_lattice_cost: 1.0, - drop_energy: 0.6, + drop_energy: 0.75, + drums_alone_line: 0.75, + longest_intro: 32, + intro_energy: 0.6, } } } @@ -124,6 +139,7 @@ pub struct BeatFeatures { kick: Vec<f64>, hats: Vec<f64>, loudness: Vec<f64>, + mids: Vec<f64>, } impl BeatFeatures { @@ -134,7 +150,8 @@ impl BeatFeatures { let hats = onset::smooth(&onset::flux(&stft, HAT_HZ.0, HAT_HZ.1), 1); let per_beat = downbeat::profiles(&stft, ×, &|t| f64::from(kick.at_time(t))); let hats_per_beat: Vec<f64> = times.iter().map(|&t| f64::from(hats.at_time(t))).collect(); - let loudness_per_beat: Vec<f64> = per_beat.bands.iter().map(loudness).collect(); + let loudness_per_beat: Vec<f64> = per_beat.bands.iter().map(|bands| loudness(bands)).collect(); + let mids_per_beat: Vec<f64> = per_beat.bands.iter().map(|bands| loudness(&bands[MID_BANDS])).collect(); let bar_from = |first: BeatIndex| first..(first + BEATS_PER_BAR).min(beats.len()); Self { on_downbeat: beats.iter().map(|beat| beat.number == 1).collect(), @@ -143,6 +160,7 @@ impl BeatFeatures { kick: (0..beats.len()).map(|beat| mean(&per_beat.kick[bar_from(beat)])).collect(), hats: (0..beats.len()).map(|beat| mean(&hats_per_beat[bar_from(beat)])).collect(), loudness: (0..beats.len()).map(|beat| mean(&loudness_per_beat[bar_from(beat)])).collect(), + mids: (0..beats.len()).map(|beat| mean(&mids_per_beat[bar_from(beat)])).collect(), } } @@ -387,17 +405,22 @@ impl Distances { } } -fn name_sections(features: &BeatFeatures, starts: &[BeatIndex], tuning: &Tuning) -> Vec<Section> { - let energy = beat_energies(features); +/// What each section starting on `starts` is. Drops are the loud sections, other than drums alone; +/// the opening sections are the intro, the last drop's followers the outro, a section leading +/// into a drop a build, and the rest breakdowns. +pub fn name_sections(features: &BeatFeatures, starts: &[BeatIndex], tuning: &Tuning) -> Vec<Section> { + let energy = between_percentiles(&features.loudness); + let drumming: Vec<f64> = + standardise(&features.kick).iter().zip(standardise(&features.mids)).map(|(kick, mids)| kick - mids).collect(); let spans: Vec<(BeatIndex, BeatIndex)> = starts.iter().zip(starts.iter().skip(1).copied().chain([features.beats()])).map(|(&a, b)| (a, b)).collect(); - let energies: Vec<f64> = spans.iter().map(|&(a, b)| mean(&energy[a..b])).collect(); + let over_section = |values: &[f64], index: usize| mean(&values[spans[index].0..spans[index].1]); + let energies: Vec<f64> = (0..spans.len()).map(|index| over_section(&energy, index)).collect(); let last = spans.len() - 1; let opens_the_track = |index: usize| last > 0 && index == 0; - let mut is_drop: Vec<bool> = energies - .iter() - .enumerate() - .map(|(index, &energy)| !opens_the_track(index) && energy >= tuning.drop_energy) + let drums_alone = |index: usize| over_section(&drumming, index) >= tuning.drums_alone_line; + let mut is_drop: Vec<bool> = (0..=last) + .map(|index| !opens_the_track(index) && energies[index] >= tuning.drop_energy && !drums_alone(index)) .collect(); if !is_drop.contains(&true) { let loudest_inside = @@ -408,22 +431,26 @@ fn name_sections(features: &BeatFeatures, starts: &[BeatIndex], tuning: &Tuning) } let first_drop = is_drop.iter().position(|&drop| drop).unwrap_or(last); let last_drop = is_drop.iter().rposition(|&drop| drop).unwrap_or(last); + let bars_until_end = |index: usize| (spans[index].1 - spans[0].0) / BEATS_PER_BAR; + let keeps_the_intro_going = |index: usize| { + bars_until_end(index) <= SURE_INTRO_BARS + || (bars_until_end(index) <= tuning.longest_intro && energies[index] >= tuning.intro_energy) + }; + let intro_sections = 1 + (1..first_drop).take_while(|&index| keeps_the_intro_going(index)).count(); spans .iter() .enumerate() .map(|(index, &(first_beat, end_beat))| { let leads_into_drop = is_drop.get(index + 1).copied().unwrap_or(false); - let kind = if opens_the_track(index) { - SectionKind::Intro - } else if is_drop[index] { + let kind = if is_drop[index] { SectionKind::Drop } else if index > last_drop { SectionKind::Outro + } else if index < intro_sections { + SectionKind::Intro } else if leads_into_drop { SectionKind::Build - } else if index < first_drop { - SectionKind::Intro } else { SectionKind::Breakdown }; @@ -435,10 +462,6 @@ fn name_sections(features: &BeatFeatures, starts: &[BeatIndex], tuning: &Tuning) /// Loudness stands for energy: a drop's sustained bass masks its kick's onsets, and a riser's noise /// fills the spectrum as fully as a drop does. The range is taken between percentiles, so a silent /// tail or one clipped beat doesn't squash every other beat together. -fn beat_energies(features: &BeatFeatures) -> Vec<f64> { - between_percentiles(&features.loudness) -} - fn between_percentiles(values: &[f64]) -> Vec<f64> { let mut sorted = values.to_vec(); sorted.sort_by(f64::total_cmp); @@ -450,7 +473,7 @@ fn between_percentiles(values: &[f64]) -> Vec<f64> { values.iter().map(|value| ((value - low) / (high - low)).clamp(0.0, 1.0)).collect() } -fn loudness(bands: &[f64; BANDS]) -> f64 { +fn loudness(bands: &[f64]) -> f64 { bands.iter().map(|log_energy| 10f64.powf(*log_energy)).sum::<f64>().log10() } From 2d1e3d76733ec9db2255dc9076824e2599fb4538 Mon Sep 17 00:00:00 2001 From: claw1200 <carstenwood12@gmail.com> Date: Sat, 28 Nov 2026 22:40:50 +0000 Subject: [PATCH 17/25] Let cue rules count runs of a kind, and keep the most precise cues A rule can now count only the phrases that start a run of their kind, so "the second drop" skips the second half of a drop phrased in two, and "every section" cues wherever the kind changes. Over the memory cue limit, the cues of the most precise rules are kept rather than the earliest. Against the DJ's own memory cues, F1 rises from 0.628 to 0.700 (UK), 0.577 to 0.682 (DnB) and 0.654 to 0.693 (speed garage). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- app/src/preload/autoCue.d.ts | 2 + app/src/renderer/src/lib/cueStyle.ts | 8 +- app/tests/cueStyle.test.ts | 7 + .../es-analyse/examples/cue_style_eval.rs | 8 +- native/crates/es-analyse/src/cue_style.rs | 128 +++++++++++++++--- 5 files changed, 131 insertions(+), 22 deletions(-) diff --git a/app/src/preload/autoCue.d.ts b/app/src/preload/autoCue.d.ts index 17504bb..f9d2943 100644 --- a/app/src/preload/autoCue.d.ts +++ b/app/src/preload/autoCue.d.ts @@ -15,6 +15,8 @@ export type { SectionKind } export interface CueRule { /** Null counts sections of every kind. */ kind: SectionKind | null + /** Every phrase of the kind, or only those starting a run of it: a drop phrased in two counts once. */ + counting: 'everySection' | 'runStarts' which: { nth: number } | 'last' | 'every' barsFromStart: number /** Cue again this many bars on, and on, until the section ends. */ diff --git a/app/src/renderer/src/lib/cueStyle.ts b/app/src/renderer/src/lib/cueStyle.ts index 3b231c4..11a8876 100644 --- a/app/src/renderer/src/lib/cueStyle.ts +++ b/app/src/renderer/src/lib/cueStyle.ts @@ -3,8 +3,14 @@ import { hotCueLetter } from './format' const ORDINALS = ['first', 'second', 'third', 'fourth'] +/** A run of phrases of one kind reads as a section, so "the second drop" is the second run of drops. */ +function countedName(rule: CueRule): string { + if (rule.counting === 'runStarts') return rule.kind ?? 'section' + return rule.kind ? `${rule.kind} phrase` : 'phrase' +} + function sectionName(rule: CueRule): string { - const kind = rule.kind ?? 'section' + const kind = countedName(rule) if (rule.which === 'every') return `every ${kind}` if (rule.which === 'last') return `the last ${kind}` return `the ${ORDINALS[rule.which.nth - 1] ?? `#${rule.which.nth}`} ${kind}` diff --git a/app/tests/cueStyle.test.ts b/app/tests/cueStyle.test.ts index e981271..bf3276d 100644 --- a/app/tests/cueStyle.test.ts +++ b/app/tests/cueStyle.test.ts @@ -9,6 +9,7 @@ type CueRule = import('../src/preload/autoCue').CueRule const rule = (fields: Partial<CueRule>): CueRule => ({ kind: 'drop', + counting: 'runStarts', which: 'every', barsFromStart: 0, thenEvery: null, @@ -25,6 +26,12 @@ describe('describeRule', () => { ) }) + it('names single phrases apart from runs of a kind', () => { + assert.equal(describeRule(rule({ counting: 'everySection' })), 'At the start of every drop phrase') + assert.equal(describeRule(rule({ kind: null, counting: 'everySection' })), 'At the start of every phrase') + assert.equal(describeRule(rule({ kind: null })), 'At the start of every section') + }) + it('says when a rule cues again through the section', () => { assert.equal( describeRule(rule({ kind: null, thenEvery: 32 })), diff --git a/native/crates/es-analyse/examples/cue_style_eval.rs b/native/crates/es-analyse/examples/cue_style_eval.rs index 1f78091..d496b13 100644 --- a/native/crates/es-analyse/examples/cue_style_eval.rs +++ b/native/crates/es-analyse/examples/cue_style_eval.rs @@ -6,7 +6,9 @@ use std::collections::{BTreeMap, HashSet}; use std::path::Path; -use es_analyse::cue_style::{CueRule, CuedTrack, HotCueSlot, HotCueStyle, Learning, MemoryCueStyle, Which}; +use es_analyse::cue_style::{ + Counting, CueRule, CuedTrack, HotCueSlot, HotCueStyle, Learning, MemoryCueStyle, Which, +}; use es_analyse::structure::{segment, BeatFeatures, BeatIndex, Section, Tuning}; use es_analyse::{decode_mono, SAMPLE_RATE}; use rayon::prelude::*; @@ -120,6 +122,10 @@ fn describe(rule: &CueRule) -> String { Which::Every => "every".to_owned(), }; let kind = rule.kind.map_or("section", |kind| kind.name()); + let kind = match rule.counting { + Counting::EverySection => kind.to_owned(), + Counting::RunStarts => format!("{kind} run"), + }; let offset = match rule.bars_from_start { 0 => "start".to_owned(), bars => format!("{bars:+} bars"), diff --git a/native/crates/es-analyse/src/cue_style.rs b/native/crates/es-analyse/src/cue_style.rs index 6a8af81..d7690de 100644 --- a/native/crates/es-analyse/src/cue_style.rs +++ b/native/crates/es-analyse/src/cue_style.rs @@ -2,13 +2,14 @@ //! //! A style is a list of rules, each a number of bars from the start of some section: "on every //! drop", "16 bars before the first drop", "on the second breakdown", "on every drop and every 16 -//! bars through it". Rules are tied to sections rather than to bar counts from the top, because no -//! two tracks share a layout. +//! bars through it", "wherever the kind of section changes". Rules are tied to sections rather +//! than to bar counts from the top, because no two tracks share a layout. //! //! Learning is greedy. Every rule that could be written is tried on every cued track; the rule that //! most raises the F1 score of the kept rules' cues against the DJ's (balancing cues found against -//! cues put where the DJ had none) is kept, and the search repeats until no rule raises it. Memory cues learn a set of rules. Hot cues learn one rule per pad, by the same -//! search held to rules that give a single cue. +//! cues put where the DJ had none) is kept, and the search repeats until no rule raises it. Memory +//! cues learn a set of rules. Hot cues learn one rule per pad, by the same search held to rules +//! that give a single cue. use std::collections::{BTreeSet, HashSet}; @@ -39,11 +40,21 @@ pub enum Which { Every, } +/// Whether a rule counts every section of its kind, or only those that start a run of the kind, +/// so a drop phrased as two sections counts once. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Counting { + EverySection, + RunStarts, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CueRule { /// `None` counts sections of every kind. pub kind: Option<SectionKind>, + pub counting: Counting, pub which: Which, pub bars_from_start: BarOffset, /// Cue again this many bars on, and on, until the section ends. @@ -53,8 +64,16 @@ pub struct CueRule { impl CueRule { /// The beats this rule cues on a track with these sections and this many beats. pub fn place(&self, sections: &[Section], beat_count: usize) -> Vec<BeatIndex> { - let matching: Vec<&Section> = - sections.iter().filter(|section| self.kind.is_none_or(|kind| section.kind == kind)).collect(); + let starts_a_run = |index: usize| index == 0 || sections[index - 1].kind != sections[index].kind; + let matching: Vec<&Section> = sections + .iter() + .enumerate() + .filter(|&(index, section)| { + self.kind.is_none_or(|kind| section.kind == kind) + && (self.counting == Counting::EverySection || starts_a_run(index)) + }) + .map(|(_, section)| section) + .collect(); let anchors: Vec<&Section> = match self.which { Which::Every => matching, Which::Last => matching.last().copied().into_iter().collect(), @@ -113,12 +132,14 @@ fn every_rule() -> Vec<CueRule> { let kinds: Vec<Option<SectionKind>> = kinds.collect(); let mut rules = Vec::new(); for &kind in &kinds { - for &which in &whiches { - for &bars_from_start in &OFFSETS { - rules.push(CueRule { kind, which, bars_from_start, then_every: None }); - } - for &bars in &REPEATS { - rules.push(CueRule { kind, which, bars_from_start: 0, then_every: Some(bars) }); + for counting in [Counting::EverySection, Counting::RunStarts] { + for &which in &whiches { + for &bars_from_start in &OFFSETS { + rules.push(CueRule { kind, counting, which, bars_from_start, then_every: None }); + } + for &bars in &REPEATS { + rules.push(CueRule { kind, counting, which, bars_from_start: 0, then_every: Some(bars) }); + } } } } @@ -176,11 +197,20 @@ fn learn_rules( kept } -/// Where the rules put cues on one track, in the rules' order of value, skipping any too near a +impl LearntRule { + /// The share of the cues it placed in training that the DJ had placed too. + fn precision(&self) -> f64 { + self.cues_found as f64 / (self.cues_found + self.cues_misplaced).max(1) as f64 + } +} + +/// Where the rules put cues on one track, the most precise rules' first, skipping any too near a /// cue already placed, at most `limit` of them. -fn place_all(rules: &[CueRule], sections: &[Section], beat_count: usize, limit: usize) -> Vec<BeatIndex> { +fn place_all(rules: &[LearntRule], sections: &[Section], beat_count: usize, limit: usize) -> Vec<BeatIndex> { + let mut by_precision: Vec<&LearntRule> = rules.iter().collect(); + by_precision.sort_by(|a, b| b.precision().total_cmp(&a.precision())); let mut placed: Vec<BeatIndex> = Vec::new(); - for beat in rules.iter().flat_map(|rule| rule.place(sections, beat_count)) { + for beat in by_precision.iter().flat_map(|learnt| learnt.rule.place(sections, beat_count)) { if placed.len() < limit && placed.iter().all(|&other| other.abs_diff(beat) >= MIN_GAP_BEATS) { placed.push(beat); } @@ -201,8 +231,7 @@ impl MemoryCueStyle { } pub fn place(&self, sections: &[Section], beat_count: usize, limit: usize) -> Vec<BeatIndex> { - let rules: Vec<CueRule> = self.rules.iter().map(|learnt| learnt.rule).collect(); - place_all(&rules, sections, beat_count, limit) + place_all(&self.rules, sections, beat_count, limit) } } @@ -335,7 +364,13 @@ mod tests { #[test] fn rules_place_cues_relative_to_their_sections() { let sections = track(128, 448); - let rule = |kind, which, bars_from_start| CueRule { kind, which, bars_from_start, then_every: None }; + let rule = |kind, which, bars_from_start| CueRule { + kind, + counting: Counting::EverySection, + which, + bars_from_start, + then_every: None, + }; assert_eq!(rule(Some(SectionKind::Drop), Which::Every, 0).place(§ions, 1000), [128, 448]); assert_eq!(rule(Some(SectionKind::Drop), Which::Nth(2), -16).place(§ions, 1000), [384]); assert_eq!(rule(Some(SectionKind::Build), Which::Last, 0).place(§ions, 1000), [416]); @@ -396,7 +431,60 @@ mod tests { #[test] fn cues_too_near_one_already_placed_are_left_out() { let sections = vec![section(0, SectionKind::Intro), section(2, SectionKind::Drop)]; - let every_start = CueRule { kind: None, which: Which::Every, bars_from_start: 0, then_every: None }; - assert_eq!(place_all(&[every_start], §ions, 100, 10), [0]); + let every_start = CueRule { + kind: None, + counting: Counting::EverySection, + which: Which::Every, + bars_from_start: 0, + then_every: None, + }; + let learnt = LearntRule { rule: every_start, cues_found: 1, cues_misplaced: 0 }; + assert_eq!(place_all(&[learnt], §ions, 100, 10), [0]); + } + + #[test] + fn counting_run_starts_takes_a_drop_phrased_as_two_sections_once() { + let sections = vec![ + section(0, SectionKind::Intro), + section(64, SectionKind::Drop), + section(128, SectionKind::Drop), + section(192, SectionKind::Breakdown), + section(256, SectionKind::Drop), + ]; + let second_drop = |counting| CueRule { + kind: Some(SectionKind::Drop), + counting, + which: Which::Nth(2), + bars_from_start: 0, + then_every: None, + }; + assert_eq!(second_drop(Counting::EverySection).place(§ions, 1000), [128]); + assert_eq!(second_drop(Counting::RunStarts).place(§ions, 1000), [256]); + let every_change = CueRule { + kind: None, + counting: Counting::RunStarts, + which: Which::Every, + bars_from_start: 0, + then_every: None, + }; + assert_eq!(every_change.place(§ions, 1000), [0, 64, 192, 256]); + } + + #[test] + fn over_the_limit_the_most_precise_rules_cues_are_kept() { + let sections = + vec![section(0, SectionKind::Intro), section(64, SectionKind::Drop), section(128, SectionKind::Outro)]; + let at = |kind| CueRule { + kind: Some(kind), + counting: Counting::EverySection, + which: Which::Every, + bars_from_start: 0, + then_every: None, + }; + let rules = [ + LearntRule { rule: at(SectionKind::Intro), cues_found: 1, cues_misplaced: 3 }, + LearntRule { rule: at(SectionKind::Outro), cues_found: 3, cues_misplaced: 1 }, + ]; + assert_eq!(place_all(&rules, §ions, 1000, 1), [128]); } } From a49eb7400ffb0ef662871e994ea960311c8d8fad Mon Sep 17 00:00:00 2001 From: claw1200 <carstenwood12@gmail.com> Date: Sat, 28 Nov 2026 22:52:15 +0000 Subject: [PATCH 18/25] Clear memory or hot cues from tracks from their context menu "Clear cues" offers memory cues, hot cues or both, asks before deleting, and refreshes the waveforms, cue counts and any deck holding the tracks. The cue menu entries move to cueMenu.ts, and decks gain refreshTrack for the three places that reload a track's detail after an outside change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- app/src/main/audio/native.ts | 1 + app/src/main/library.ts | 1 + app/src/preload/engine.ts | 1 + app/src/renderer/src/App.svelte | 4 +-- app/src/renderer/src/lib/api.ts | 4 +++ .../src/lib/components/Sidebar.svelte | 2 +- .../src/lib/components/TrackTable.svelte | 36 ++++++++++++++++++- .../src/lib/{autoCueMenu.ts => cueMenu.ts} | 21 ++++++++++- app/src/renderer/src/lib/decks.svelte.ts | 5 +++ app/src/renderer/src/lib/trackMenu.ts | 4 ++- app/src/renderer/src/lib/types.ts | 6 ++++ es-rekordbox-sdk | 2 +- native/crates/es-engine/src/library.rs | 19 ++++++++++ native/crates/es-node/src/library.rs | 10 ++++++ 14 files changed, 109 insertions(+), 7 deletions(-) rename app/src/renderer/src/lib/{autoCueMenu.ts => cueMenu.ts} (55%) diff --git a/app/src/main/audio/native.ts b/app/src/main/audio/native.ts index 1bdb109..daefb71 100644 --- a/app/src/main/audio/native.ts +++ b/app/src/main/audio/native.ts @@ -132,6 +132,7 @@ export interface NativeLibrary { cueAddMemory(id: string, ms: number, endMs: number | null): Promise<unknown> cuePlaceAuto(id: string, hot: boolean, kinds: number[], startsMs: number[]): Promise<unknown> trackSetPhrases(id: string, body: string): Promise<unknown> + cueClear(ids: string[], memory: boolean, hot: boolean): Promise<unknown> cueDelete(id: string, cueId: string): Promise<unknown> cueSetColor(id: string, cueId: string, colorIndex: number | null): Promise<unknown> onEvent(callback: (event: string, data: string) => void): void diff --git a/app/src/main/library.ts b/app/src/main/library.ts index 0a1d846..b6deac6 100644 --- a/app/src/main/library.ts +++ b/app/src/main/library.ts @@ -78,6 +78,7 @@ const WRITES: CommandHandlers = { ((p?.kinds as unknown[]) ?? []).map(Number), ((p?.startsMs as unknown[]) ?? []).map(Number) ), + 'cue.clear': (lib, p) => lib.cueClear(list(p?.ids), Boolean(p?.memory), Boolean(p?.hot)), 'cue.delete': (lib, p) => lib.cueDelete(text(p?.id), text(p?.cueId)), 'cue.setColor': (lib, p) => lib.cueSetColor(text(p?.id), text(p?.cueId), p?.colorIndex == null ? null : Number(p.colorIndex)), diff --git a/app/src/preload/engine.ts b/app/src/preload/engine.ts index c6b7c74..2122cde 100644 --- a/app/src/preload/engine.ts +++ b/app/src/preload/engine.ts @@ -139,6 +139,7 @@ export interface EngineCommandParams { 'cue.setHot': { id: string; kind: number; ms: number; endMs?: number | null } 'cue.addMemory': { id: string; ms: number; endMs?: number | null } 'cue.placeAuto': { id: string; hot: boolean; kinds: number[]; startsMs: number[] } + 'cue.clear': { ids: string[]; memory: boolean; hot: boolean } 'cue.delete': { id: string; cueId: string } 'cue.setColor': { id: string; cueId: string; colorIndex?: number | null } 'playlist.add': { id: string; trackIds: string[] } diff --git a/app/src/renderer/src/App.svelte b/app/src/renderer/src/App.svelte index 785635a..49e3b6b 100644 --- a/app/src/renderer/src/App.svelte +++ b/app/src/renderer/src/App.svelte @@ -56,7 +56,7 @@ autoCue.onFinished(({ id, cues }) => { if (!cues) return browserPreviews.noteCues(id, cues as Cue[]) - for (const player of decks.withTrack(id)) void player.refreshDetail() + decks.refreshTrack(id) }) autoCue.onBatchDone(({ done, skipped, failed, error }) => { if (error) return library.notify(error, 'error') @@ -70,7 +70,7 @@ if (!track) return browserPreviews.forget([track.id]) library.updateRows([track]) - for (const player of decks.withTrack(track.id)) void player.refreshDetail() + decks.refreshTrack(track.id) }) analysis.onBatchDone((analysed, failed, error) => { if (!failed) return diff --git a/app/src/renderer/src/lib/api.ts b/app/src/renderer/src/lib/api.ts index 43392dc..7f0ad47 100644 --- a/app/src/renderer/src/lib/api.ts +++ b/app/src/renderer/src/lib/api.ts @@ -5,6 +5,7 @@ import type { BeatgridSaved, Cue, CueMove, + TrackCues, ConvertMode, ConvertPreset, ConvertResult, @@ -28,6 +29,7 @@ import type { Phrase } from './types' import type { SectionStart } from '../../../preload/analysis' +import type { CueSort } from '../../../preload/autoCue' import type { DeviceSettings, SyncDecisions, SyncInspection } from '../../../preload/engine' const call = window.api.call @@ -52,6 +54,8 @@ export const api = { addMemoryCue: (id: string, ms: number, endMs: number | null = null) => call<Cue[]>('cue.addMemory', { id, ms, endMs }), deleteCue: (id: string, cueId: string) => call<Cue[]>('cue.delete', { id, cueId }), + clearCues: (ids: string[], sorts: CueSort[]) => + call<TrackCues[]>('cue.clear', { ids, memory: sorts.includes('memory'), hot: sorts.includes('hot') }), setCueColor: (id: string, cueId: string, colorIndex: number | null) => call<Cue[]>('cue.setColor', { id, cueId, colorIndex }), setPhrases: (id: string, phrases: SectionStart[]) => call<Phrase[]>('track.setPhrases', { id, phrases }), diff --git a/app/src/renderer/src/lib/components/Sidebar.svelte b/app/src/renderer/src/lib/components/Sidebar.svelte index a29a2a1..198eb10 100644 --- a/app/src/renderer/src/lib/components/Sidebar.svelte +++ b/app/src/renderer/src/lib/components/Sidebar.svelte @@ -28,7 +28,7 @@ Settings2, LoaderCircle } from '@lucide/svelte' - import { autoCueEntry } from '$lib/autoCueMenu' + import { autoCueEntry } from '$lib/cueMenu' import { getApp } from '$lib/context' import { droppedPaths, isFileDrag } from '$lib/library/drop' import { PLAYLIST_TREE_DRAG_TYPE } from '$lib/library.svelte' diff --git a/app/src/renderer/src/lib/components/TrackTable.svelte b/app/src/renderer/src/lib/components/TrackTable.svelte index 764ebd9..08e4cbf 100644 --- a/app/src/renderer/src/lib/components/TrackTable.svelte +++ b/app/src/renderer/src/lib/components/TrackTable.svelte @@ -2,6 +2,8 @@ import { flushSync } from 'svelte' import { ArrowUp, ArrowDown } from '@lucide/svelte' import { browserPreviews } from '$lib/browserPreview.svelte' + import { cueSortsName } from '$lib/cueMenu' + import { ipcErrorMessage } from '$lib/ipcError' import { BROWSER_COLUMNS_KEY, COLUMNS, @@ -15,7 +17,7 @@ type Column } from '$lib/browserColumns' import { getApp } from '$lib/context' - import { artworkUrl } from '$lib/api' + import { api, artworkUrl } from '$lib/api' import { verdictForTrack, type Verdict } from '$lib/hardware/compatibility' import { formatBpm, formatDuration, keyColor, TRACK_COLORS } from '$lib/format' import { heardKey, keyMatch, keyMatchColor, withinCutoff, type KeyMatch } from '$lib/mix/harmonic' @@ -27,6 +29,7 @@ import { getSetting, setSetting } from '$lib/settings' import { fileMenu, trackMenu, type TrackMenuShortcut } from '$lib/trackMenu' import type { ConvertPreset, Track } from '$lib/types' + import type { CueSort } from '../../../../preload/autoCue' import ConfirmDialog from './ConfirmDialog.svelte' import ContextMenu from './ContextMenu.svelte' import WaveformThumb from './WaveformThumb.svelte' @@ -388,6 +391,23 @@ let rowMenu = $state<MenuRequest | null>(null) let deletingFiles = $state<Track[] | null>(null) + let clearingCues = $state<{ tracks: Track[]; sorts: CueSort[] } | null>(null) + + async function clearCues(tracks: Track[], sorts: CueSort[]): Promise<void> { + try { + const cleared = await api.clearCues( + tracks.map((track) => track.id), + sorts + ) + for (const { id, cues } of cleared) { + browserPreviews.noteCues(id, cues) + decks.refreshTrack(id) + } + if (cleared.length > 1) library.notify(`Cleared ${cueSortsName(sorts)} from ${cleared.length} tracks`) + } catch (err) { + library.notify(ipcErrorMessage(err), 'error') + } + } const trashName = window.api.platform === 'win32' ? 'Recycle Bin' : 'Trash' async function trashFiles(tracks: Track[]): Promise<void> { @@ -425,6 +445,7 @@ remove: onremove, analyse: onanalyse, autoCue: (tracks, sort) => autoCue.run(tracks, sort), + clearCues: (tracks, sorts) => (clearingCues = { tracks, sorts }), convert: onconvert, exportZip, shortcut @@ -891,6 +912,19 @@ <ContextMenu menu={rowMenu} onclose={() => (rowMenu = null)} /> {/if} + {#if clearingCues} + {@const { tracks, sorts } = clearingCues} + {@const name = cueSortsName(sorts)} + <ConfirmDialog + title={`Clear ${name}`} + message={`Delete all ${name} from ${tracks.length === 1 ? `“${tracks[0].title}”` : `${tracks.length} tracks`}? This can’t be undone.`} + confirmLabel={`Clear ${name}`} + danger + onconfirm={() => void clearCues(tracks, sorts)} + onclose={() => (clearingCues = null)} + /> + {/if} + {#if deletingFiles} {@const files = deletingFiles} <ConfirmDialog diff --git a/app/src/renderer/src/lib/autoCueMenu.ts b/app/src/renderer/src/lib/cueMenu.ts similarity index 55% rename from app/src/renderer/src/lib/autoCueMenu.ts rename to app/src/renderer/src/lib/cueMenu.ts index 54743b7..ee0920f 100644 --- a/app/src/renderer/src/lib/autoCueMenu.ts +++ b/app/src/renderer/src/lib/cueMenu.ts @@ -1,4 +1,4 @@ -import { BookmarkMinus, BookmarkPlus, WandSparkles } from '@lucide/svelte' +import { BookmarkMinus, BookmarkPlus, Eraser, WandSparkles } from '@lucide/svelte' import type { CueSort } from '../../../preload/autoCue' import type { CuePalette } from './cuePalette.svelte' import type { MenuEntry } from './menu' @@ -16,6 +16,25 @@ export function autoCueEntry(locked: boolean, run: (sort: CueSort) => void): Men } } +/** Which cues a clear takes, in words: "memory cues", "hot cues", or both. */ +export function cueSortsName(sorts: CueSort[]): string { + return sorts.length > 1 ? 'memory and hot cues' : `${sorts[0]} cues` +} + +/** "Clear cues" with a choice of memory cues, hot cues or both. */ +export function clearCuesEntry(locked: boolean, clear: (sorts: CueSort[]) => void): MenuEntry { + const choices: CueSort[][] = [['memory'], ['hot'], ['memory', 'hot']] + return { + label: 'Clear cues', + icon: Eraser, + disabled: locked, + items: choices.map((sorts) => { + const name = cueSortsName(sorts) + return { label: `${name[0].toUpperCase()}${name.slice(1)}…`, danger: true, onselect: () => clear(sorts) } + }) + } +} + /** Adds the tracks to the cue palette, or takes them out when every one is already in it. */ export function cuePaletteEntry(palette: CuePalette, ids: string[]): MenuEntry { const allIn = ids.length > 0 && ids.every((id) => palette.has(id)) diff --git a/app/src/renderer/src/lib/decks.svelte.ts b/app/src/renderer/src/lib/decks.svelte.ts index f6e9479..c4a22e3 100644 --- a/app/src/renderer/src/lib/decks.svelte.ts +++ b/app/src/renderer/src/lib/decks.svelte.ts @@ -70,6 +70,11 @@ export class Decks { return this.players.filter((player) => player.track?.id === trackId) } + /** Reloads the cues, grid and phrases of every deck holding the track, after they change elsewhere. */ + refreshTrack(trackId: string): void { + for (const player of this.withTrack(trackId)) void player.refreshDetail() + } + /** Points each deck holding a file from outside the collection at that file's new collection row. */ adoptImported(tracks: readonly Track[]): void { const byPath = new Map(tracks.map((track) => [pathKey(track.path), track])) diff --git a/app/src/renderer/src/lib/trackMenu.ts b/app/src/renderer/src/lib/trackMenu.ts index 0c71ec9..afb8522 100644 --- a/app/src/renderer/src/lib/trackMenu.ts +++ b/app/src/renderer/src/lib/trackMenu.ts @@ -21,7 +21,7 @@ import { Trash2 } from '@lucide/svelte' import type { CueSort } from '../../../preload/autoCue' -import { autoCueEntry, cuePaletteEntry } from './autoCueMenu' +import { autoCueEntry, clearCuesEntry, cuePaletteEntry } from './cueMenu' import { TRACK_COLORS } from './format' import { matchesPreset, presetLabel } from './convertPresets' import { loadPresets } from './convertPresetStore' @@ -42,6 +42,7 @@ export interface TrackMenuActions { remove: (tracks: Track[]) => void analyse: (tracks: Track[]) => void autoCue: (tracks: Track[], sort: CueSort) => void + clearCues: (tracks: Track[], sorts: CueSort[]) => void convert: (tracks: Track[], preset: ConvertPreset) => void exportZip: () => void shortcut: (id: TrackMenuShortcut) => string | undefined @@ -226,6 +227,7 @@ export function trackMenu(library: Library, decks: Decks, tracks: Track[], actio }, !device && autoCueEntry(locked, (sort) => actions.autoCue(tracks, sort)), !device && cuePaletteEntry(library.cuePalette, ids), + !device && clearCuesEntry(locked, (sorts) => actions.clearCues(tracks, sorts)), !device && { label: 'Convert file type', icon: FileAudio, diff --git a/app/src/renderer/src/lib/types.ts b/app/src/renderer/src/lib/types.ts index b46f4cd..7e240e8 100644 --- a/app/src/renderer/src/lib/types.ts +++ b/app/src/renderer/src/lib/types.ts @@ -136,6 +136,12 @@ export interface Cue { rgb?: string | null } +/** A track's cues after an edit to several tracks at once. */ +export interface TrackCues { + id: string + cues: Cue[] +} + export interface Beatgrid { times: number[] beats: number[] diff --git a/es-rekordbox-sdk b/es-rekordbox-sdk index 04b7f52..a5957be 160000 --- a/es-rekordbox-sdk +++ b/es-rekordbox-sdk @@ -1 +1 @@ -Subproject commit 04b7f52ba4d36338806cff0123faac08786fc01c +Subproject commit a5957bed5a21f17cdbdb1cd841f031a5d251a445 diff --git a/native/crates/es-engine/src/library.rs b/native/crates/es-engine/src/library.rs index 1ac09f5..03415f6 100644 --- a/native/crates/es-engine/src/library.rs +++ b/native/crates/es-engine/src/library.rs @@ -117,6 +117,13 @@ pub struct LibraryInfo { pub writable: bool, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TrackCues { + pub id: String, + pub cues: Vec<es_index::detail::Cue>, +} + #[derive(Debug)] pub struct RemovedTracks { pub ids: Vec<String>, @@ -475,6 +482,18 @@ impl LibraryService { self.cues(id) } + pub fn cue_clear(&mut self, ids: &[String], sorts: &[rb_library::CueSort]) -> Result<Vec<TrackCues>> { + self.edit(|tx| { + for id in ids { + for &sort in sorts { + tx.clear_cues(id, sort)?; + } + } + Ok(()) + })?; + ids.iter().map(|id| Ok(TrackCues { id: id.clone(), cues: self.cues(id)? })).collect() + } + pub fn cue_delete(&mut self, id: &str, cue_id: &str) -> Result<Vec<es_index::detail::Cue>> { self.edit(|tx| tx.delete_cue(id, cue_id))?; self.cues(id) diff --git a/native/crates/es-node/src/library.rs b/native/crates/es-node/src/library.rs index b666a45..6828f53 100644 --- a/native/crates/es-node/src/library.rs +++ b/native/crates/es-node/src/library.rs @@ -193,6 +193,7 @@ enum Op { CueSetHot(String, i64, i64, Option<i64>), CueAddMemory(String, i64, Option<i64>), CuePlaceAuto { id: String, hot: bool, cues: Vec<rb_library::AutoCue> }, + CueClear(Vec<String>, Vec<rb_library::CueSort>), CueDelete(String, String), CueSetColor(String, String, Option<i64>), TrackUpdate(Vec<String>, String, bool), @@ -239,6 +240,7 @@ impl Run { Op::CueSetHot(..) => "cue.setHot", Op::CueAddMemory(..) => "cue.addMemory", Op::CuePlaceAuto { .. } => "cue.placeAuto", + Op::CueClear(_, _) => "cue.clear", Op::CueDelete(_, _) => "cue.delete", Op::CueSetColor(_, _, _) => "cue.setColor", Op::TrackDetail(_) => "track.detail", @@ -516,6 +518,7 @@ impl Run { let sections = section_starts(input.get("phrases")); return json_of(&service.track_set_phrases(id, §ions).map_err(failure)?); } + Op::CueClear(ids, sorts) => return json_of(&service.cue_clear(ids, sorts).map_err(failure)?), Op::CueDelete(id, cue_id) => return json_of(&service.cue_delete(id, cue_id).map_err(failure)?), Op::CueSetColor(id, cue_id, color) => { return json_of(&service.cue_set_color(id, cue_id, *color).map_err(failure)?); @@ -724,6 +727,13 @@ impl RekordboxLibrary { self.run(Op::SetPhrases(id, body)) } + /// Delete every memory cue and loop, every hot cue, or both, from each track. + #[napi(ts_return_type = "Promise<unknown>")] + pub fn cue_clear(&self, ids: Vec<String>, memory: bool, hot: bool) -> AsyncTask<Run> { + let sorts = [(memory, rb_library::CueSort::Memory), (hot, rb_library::CueSort::Hot)]; + self.run(Op::CueClear(ids, sorts.into_iter().filter(|(chosen, _)| *chosen).map(|(_, sort)| sort).collect())) + } + #[napi(ts_return_type = "Promise<unknown>")] pub fn cue_delete(&self, id: String, cue_id: String) -> AsyncTask<Run> { self.run(Op::CueDelete(id, cue_id)) From 34f081f4c7c9ef1f8ac59e9300569ea22dcbe6cb Mon Sep 17 00:00:00 2001 From: claw1200 <carstenwood12@gmail.com> Date: Sat, 28 Nov 2026 23:21:24 +0000 Subject: [PATCH 19/25] Count hand-placed cues on the beat within a quarter of one, and score auto cue A grid nudged after cueing left cues a few ms off their beats, and the learner dropped any more than 15 ms away: 6 of 8 cues on one palette track. Cues now count on the nearest beat within a quarter of a beat. cue_score scores auto cue against the DJ's own memory cues on the app's cue palette, in-sample and cross-validated. The examples share their library reading in examples/library. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../crates/es-analyse/examples/cue_score.rs | 208 ++++++++++++++++++ .../es-analyse/examples/cue_style_eval.rs | 4 +- .../crates/es-analyse/examples/library/mod.rs | 100 +++++++++ .../es-analyse/examples/phrase_score.rs | 58 ++--- native/crates/es-analyse/src/lib.rs | 23 ++ native/crates/es-node/src/cue_style.rs | 6 +- 6 files changed, 350 insertions(+), 49 deletions(-) create mode 100644 native/crates/es-analyse/examples/cue_score.rs create mode 100644 native/crates/es-analyse/examples/library/mod.rs diff --git a/native/crates/es-analyse/examples/cue_score.rs b/native/crates/es-analyse/examples/cue_score.rs new file mode 100644 index 0000000..381e304 --- /dev/null +++ b/native/crates/es-analyse/examples/cue_score.rs @@ -0,0 +1,208 @@ +//! Scores auto cue against the DJ's own memory cues on the tracks of the app's cue palette, or of +//! a playlist. Sections are found on each track's own grid, as the app does. +//! +//! Two scores: in-sample, the style learnt from every track and placed back on them, which should +//! give back nearly what the DJ did; and cross-validated, each fifth of the tracks cued by a style +//! learnt from the other four fifths, which is how it does on tracks it hasn't seen. Targets are +//! held against the cross-validated score. Automatic cues are left out of the DJ's. +//! `cargo run --release -p es-analyse --example cue_score [-- <title words>] [--playlist <name>]` + +use std::collections::HashSet; + +use es_analyse::cue_style::{CuedTrack, Learning, MemoryCueStyle, MEMORY_CUE_LIMIT}; +use es_analyse::structure::{segment, BeatFeatures, BeatIndex, Section, Tuning}; +use es_analyse::{beat_of_cue, decode_mono, SAMPLE_RATE}; +use rayon::prelude::*; +use rb_library::write::AUTO_CUE_COMMENT; +use rb_library::Track; + +#[path = "library/mod.rs"] +mod library; +use library::{audio, fold_of, title, Share, Snapshot}; + +const FOLDS: u64 = 5; +const BEATS_PER_BAR: usize = 4; +const MEMORY_KIND: i64 = 0; +const RECALL_TARGET: f64 = 0.85; +const MISPLACED_TARGET: f64 = 0.15; + +struct Cued { + title: String, + fold: u64, + sections: Vec<Section>, + beat_count: usize, + cues: HashSet<BeatIndex>, +} + +impl Cued { + fn training(&self) -> CuedTrack { + CuedTrack { sections: self.sections.clone(), beat_count: self.beat_count, cues: self.cues.clone() } + } +} + +#[derive(Default, Clone, Copy)] +struct Score { + theirs: usize, + placed: usize, + found: usize, + within_a_bar: usize, +} + +impl Score { + fn of(theirs: &HashSet<BeatIndex>, placed: &[BeatIndex]) -> Self { + let near = |beat: BeatIndex| theirs.iter().any(|&cue| cue.abs_diff(beat) <= BEATS_PER_BAR); + Self { + theirs: theirs.len(), + placed: placed.len(), + found: placed.iter().filter(|beat| theirs.contains(beat)).count(), + within_a_bar: placed.iter().filter(|&&beat| near(beat)).count(), + } + } + + fn add(self, other: Self) -> Self { + Self { + theirs: self.theirs + other.theirs, + placed: self.placed + other.placed, + found: self.found + other.found, + within_a_bar: self.within_a_bar + other.within_a_bar, + } + } + + fn recall(&self) -> f64 { + self.found as f64 / self.theirs.max(1) as f64 + } + + fn misplaced(&self) -> f64 { + (self.placed - self.found) as f64 / self.placed.max(1) as f64 + } + + fn line(&self) -> String { + format!( + "your cues found {:>5.1}% (target {:.0}%+), ours where you had none {:>5.1}% (target under {:.0}%), \ + within a bar {:>5.1}%, {} of yours, {} of ours", + 100.0 * self.recall(), + 100.0 * RECALL_TARGET, + 100.0 * self.misplaced(), + 100.0 * MISPLACED_TARGET, + 100.0 * self.within_a_bar as f64 / self.placed.max(1) as f64, + self.theirs, + self.placed, + ) + } +} + +fn main() -> Result<(), Box<dyn std::error::Error>> { + let args: Vec<String> = std::env::args().skip(1).collect(); + let playlist = args.iter().position(|arg| arg == "--playlist").and_then(|at| args.get(at + 1)); + let title_words = args.first().filter(|arg| !arg.starts_with("--")); + + let snapshot = Snapshot::open()?; + let (tracks, source) = match playlist { + Some(name) => (snapshot.playlist_tracks(name)?, format!("\"{name}\"")), + None => (snapshot.cue_palette()?, "the cue palette".to_owned()), + }; + let with_cues: Vec<(Track, Vec<i64>)> = tracks + .into_iter() + .map(|track| { + let cues = snapshot.lib.cues(&track.id)?; + let own = cues.into_iter().filter(|cue| cue.kind == MEMORY_KIND && cue.comment != AUTO_CUE_COMMENT); + Ok((track, own.map(|cue| cue.start_ms).collect())) + }) + .collect::<Result<_, rb_library::Error>>()?; + let results: Vec<Result<Cued, String>> = + with_cues.par_iter().map(|(track, cues_ms)| measure(&snapshot.share, track, cues_ms)).collect(); + let mut cued = Vec::new(); + for result in results { + match result { + Ok(track) if !track.cues.is_empty() => cued.push(track), + Ok(track) => println!("skipped {}: no memory cues of yours", track.title), + Err(skipped) => println!("skipped {skipped}"), + } + } + println!("{} tracks with your memory cues in {source}\n", cued.len()); + + let in_sample = place_learnt_from(&cued, |_| true); + let cross_validated: Vec<Vec<BeatIndex>> = { + let by_fold: Vec<Vec<Vec<BeatIndex>>> = + (0..FOLDS).into_par_iter().map(|fold| place_learnt_from(&cued, |track| track.fold != fold)).collect(); + cued.iter().enumerate().map(|(index, track)| by_fold[track.fold as usize][index].clone()).collect() + }; + + if let Some(words) = title_words { + timelines(&cued, &cross_validated, words); + return Ok(()); + } + let total = |placed: &[Vec<BeatIndex>]| { + cued.iter().zip(placed).fold(Score::default(), |sum, (track, placed)| sum.add(Score::of(&track.cues, placed))) + }; + println!("in-sample {}", total(&in_sample).line()); + println!("cross-validated {}", total(&cross_validated).line()); + report_tracks(&cued, &cross_validated); + Ok(()) +} + +fn measure(share: &Share, track: &Track, cues_ms: &[i64]) -> Result<Cued, String> { + let title = title(track); + let grid = share.grid(track).ok_or(format!("{title}: no beatgrid"))?; + let mono = decode_mono(audio(track)).map_err(|e| format!("{title}: {e}"))?; + let features = BeatFeatures::measure(&mono, f64::from(SAMPLE_RATE), &grid); + let cues = cues_ms.iter().filter_map(|&ms| beat_of_cue(&grid, ms as f64)).collect(); + Ok(Cued { + title, + fold: fold_of(&track.id, FOLDS), + sections: segment(&features, &Tuning::default()), + beat_count: grid.len(), + cues, + }) +} + +/// For every track, where a style learnt from the tracks `learns_from` picks places its cues. +fn place_learnt_from(tracks: &[Cued], learns_from: impl Fn(&Cued) -> bool) -> Vec<Vec<BeatIndex>> { + let training: Vec<CuedTrack> = tracks.iter().filter(|track| learns_from(track)).map(Cued::training).collect(); + let style = MemoryCueStyle::learn(&training, &Learning::default()); + tracks.iter().map(|track| style.place(&track.sections, track.beat_count, MEMORY_CUE_LIMIT)).collect() +} + +fn report_tracks(tracks: &[Cued], placed: &[Vec<BeatIndex>]) { + let mut rows: Vec<(Score, &str)> = tracks + .iter() + .zip(placed) + .map(|(track, placed)| (Score::of(&track.cues, placed), track.title.as_str())) + .collect(); + rows.sort_by(|a, b| { + let badness = |score: &Score| (score.theirs - score.found) + (score.placed - score.found); + badness(&b.0).cmp(&badness(&a.0)) + }); + println!("\n== Tracks, most wrong cues first (cross-validated) =="); + println!("{:>6} {:>6} {:>7} track", "found", "missed", "extra"); + for (score, title) in rows { + println!("{:>6} {:>6} {:>7} {title}", score.found, score.theirs - score.found, score.placed - score.found); + } +} + +/// Each track whose title holds `words`, section by section in bars, with your cues and ours. +fn timelines(tracks: &[Cued], placed: &[Vec<BeatIndex>], words: &str) { + let bar = |beat: BeatIndex| beat as f64 / BEATS_PER_BAR as f64; + for (track, placed) in tracks.iter().zip(placed) { + if !track.title.to_lowercase().contains(&words.to_lowercase()) { + continue; + } + println!("\n{}", track.title); + let mut beats: Vec<BeatIndex> = track.sections.iter().map(|section| section.first_beat).collect(); + beats.extend(track.cues.iter().chain(placed)); + beats.sort_unstable(); + beats.dedup(); + println!(" {:>7} {:<10} {:>5} {:>5}", "bar", "section", "yours", "ours"); + for beat in beats { + let section = track.sections.iter().find(|section| section.first_beat == beat); + let mark = |cued: bool| if cued { "cue" } else { "" }; + println!( + " {:>7.2} {:<10} {:>5} {:>5}", + bar(beat), + section.map_or("", |section| section.kind.name()), + mark(track.cues.contains(&beat)), + mark(placed.contains(&beat)) + ); + } + } +} diff --git a/native/crates/es-analyse/examples/cue_style_eval.rs b/native/crates/es-analyse/examples/cue_style_eval.rs index d496b13..d36554e 100644 --- a/native/crates/es-analyse/examples/cue_style_eval.rs +++ b/native/crates/es-analyse/examples/cue_style_eval.rs @@ -6,9 +6,7 @@ use std::collections::{BTreeMap, HashSet}; use std::path::Path; -use es_analyse::cue_style::{ - Counting, CueRule, CuedTrack, HotCueSlot, HotCueStyle, Learning, MemoryCueStyle, Which, -}; +use es_analyse::cue_style::{Counting, CueRule, CuedTrack, HotCueSlot, HotCueStyle, Learning, MemoryCueStyle, Which}; use es_analyse::structure::{segment, BeatFeatures, BeatIndex, Section, Tuning}; use es_analyse::{decode_mono, SAMPLE_RATE}; use rayon::prelude::*; diff --git a/native/crates/es-analyse/examples/library/mod.rs b/native/crates/es-analyse/examples/library/mod.rs new file mode 100644 index 0000000..812f7ef --- /dev/null +++ b/native/crates/es-analyse/examples/library/mod.rs @@ -0,0 +1,100 @@ +//! Reading the installed rekordbox library for the scoring examples: a playlist's tracks, their +//! analysis files and grids. Opens a snapshot, so nothing is changed. + +#![allow(dead_code)] + +use std::path::{Path, PathBuf}; + +use es_analyse::Beat; +use rb_anlz::decode::{self, Tags}; +use rb_library::{Library, PlaylistKind, Track}; + +pub struct Snapshot { + pub lib: Library, + pub share: Share, +} + +/// Where the library keeps analysis files; apart from the database so threads can share it. +pub struct Share(PathBuf); + +impl Snapshot { + pub fn open() -> Result<Self, Box<dyn std::error::Error>> { + let path = Library::installed_path().ok_or("no installed rekordbox library")?; + let lib = Library::open_snapshot(&path)?; + Ok(Self { lib, share: Share(path.with_file_name("share")) }) + } + + /// The tracks in the app's cue palette, as it last saved its settings. + pub fn cue_palette(&self) -> Result<Vec<Track>, Box<dyn std::error::Error>> { + let path = app_settings().ok_or("can't tell where the app keeps its settings")?; + let settings: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path)?)?; + let palette = settings["cuePalette"].as_str().ok_or("the app's settings have no cue palette")?; + let ids: Vec<String> = serde_json::from_str(palette)?; + Ok(self.lib.tracks(Some(&ids))?) + } + + /// The tracks of the one playlist called `name`. + pub fn playlist_tracks(&self, name: &str) -> Result<Vec<Track>, Box<dyn std::error::Error>> { + let playlists: Vec<_> = self + .lib + .playlists()? + .into_iter() + .filter(|node| node.kind != PlaylistKind::Folder && node.name.trim().eq_ignore_ascii_case(name)) + .collect(); + let [playlist] = playlists.as_slice() else { + return Err(format!("expected one playlist called \"{name}\", found {}", playlists.len()).into()); + }; + let ids = self.lib.playlist_track_ids(&playlist.id)?; + Ok(self.lib.tracks(Some(&ids))?) + } +} + +impl Share { + /// The track's analysis file with this suffix: "DAT", "EXT" or "2EX". + pub fn analysis(&self, track: &Track, suffix: &str) -> Option<Tags> { + let relative = track.analysis_path.as_deref()?; + Tags::read(&rb_anlz::file(&self.0, relative, suffix)?).ok() + } + + pub fn grid(&self, track: &Track) -> Option<Vec<Beat>> { + let grid = decode::beatgrid(&self.analysis(track, "DAT")?)?; + let beats = grid + .times + .iter() + .zip(&grid.beats) + .zip(&grid.bpms) + .map(|((&time_ms, &number), &bpm)| Beat { + number: u8::try_from(number).unwrap_or(0), + tempo_x100: (bpm * 100.0).round() as u16, + time_ms, + }) + .collect(); + Some(beats) + } +} + +fn app_settings() -> Option<PathBuf> { + const APP: &str = "Export Studio"; + #[cfg(target_os = "macos")] + let base = std::env::var_os("HOME").map(|home| PathBuf::from(home).join("Library").join("Application Support")); + #[cfg(windows)] + let base = std::env::var_os("APPDATA").map(PathBuf::from); + #[cfg(not(any(target_os = "macos", windows)))] + let base = std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")); + base.map(|base| base.join(APP).join("settings.json")) +} + +pub fn title(track: &Track) -> String { + format!("{} - {}", track.artist, track.title) +} + +pub fn audio(track: &Track) -> &Path { + Path::new(&track.folder_path) +} + +/// Which of `folds` the track falls in, fixed by its id so adding tracks leaves the others put. +pub fn fold_of(id: &str, folds: u64) -> u64 { + let fnv = + id.bytes().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3)); + fnv % folds +} diff --git a/native/crates/es-analyse/examples/phrase_score.rs b/native/crates/es-analyse/examples/phrase_score.rs index 1f4eab1..e7522f2 100644 --- a/native/crates/es-analyse/examples/phrase_score.rs +++ b/native/crates/es-analyse/examples/phrase_score.rs @@ -9,14 +9,16 @@ //! themselves, to score labelling apart from placing starts. use std::collections::{BTreeMap, HashSet}; -use std::path::Path; use es_analyse::structure::{name_sections, segment, BeatFeatures, BeatIndex, Section, SectionKind, Tuning}; -use es_analyse::{decode_mono, Beat, SAMPLE_RATE}; +use es_analyse::{decode_mono, SAMPLE_RATE}; use rayon::prelude::*; -use rb_anlz::decode::{self, Tags}; use rb_anlz::phrase::{self, Mood, PhraseKind, SongStructure}; -use rb_library::{Library, PlaylistKind, Track}; +use rb_library::Track; + +#[path = "library/mod.rs"] +mod library; +use library::{audio, fold_of, title, Share, Snapshot}; #[path = "tunings/mod.rs"] mod tunings; @@ -96,11 +98,9 @@ struct Scored { written_by_rekordbox: bool, } -/// A fixed quarter of the tracks, chosen by id so adding tracks leaves the others where they were. +/// A fixed quarter of the tracks. fn held_out(id: &str) -> bool { - let fnv = - id.bytes().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3)); - fnv % HELD_OUT_ONE_IN == 0 + fold_of(id, HELD_OUT_ONE_IN) == 0 } /// Whether rekordbox wrote these phrases rather than this app: the app writes only the high mood, @@ -123,22 +123,11 @@ fn kind_of(kind: Option<PhraseKind>) -> SectionKind { } fn main() -> Result<(), Box<dyn std::error::Error>> { - let path = Library::installed_path().ok_or("no installed rekordbox library")?; - let lib = Library::open_snapshot(&path)?; - let share = path.with_file_name("share"); - let playlists: Vec<_> = lib - .playlists()? - .into_iter() - .filter(|node| node.kind != PlaylistKind::Folder && node.name.trim().eq_ignore_ascii_case(PLAYLIST)) - .collect(); - let [playlist] = playlists.as_slice() else { - return Err(format!("expected one playlist called \"{PLAYLIST}\", found {}", playlists.len()).into()); - }; - let ids = lib.playlist_track_ids(&playlist.id)?; - let tracks = lib.tracks(Some(&ids))?; + let snapshot = Snapshot::open()?; + let tracks = snapshot.playlist_tracks(PLAYLIST)?; println!("{} tracks in \"{PLAYLIST}\"\n", tracks.len()); - let results: Vec<Result<Scored, String>> = tracks.par_iter().map(|track| score(&share, track)).collect(); + let results: Vec<Result<Scored, String>> = tracks.par_iter().map(|track| score(&snapshot.share, track)).collect(); let mut scored: Vec<Scored> = Vec::new(); for result in results { match result { @@ -167,27 +156,12 @@ fn report_all(scored: Vec<Scored>) { report(&tuning); } -fn score(share: &Path, track: &Track) -> Result<Scored, String> { - let title = format!("{} - {}", track.artist, track.title); - let analysis = |suffix| { - let relative = track.analysis_path.as_deref()?; - Tags::read(&rb_anlz::file(share, relative, suffix)?).ok() - }; - let grid = analysis("DAT").as_ref().and_then(decode::beatgrid).ok_or(format!("{title}: no beatgrid"))?; +fn score(share: &Share, track: &Track) -> Result<Scored, String> { + let title = title(track); + let beats = share.grid(track).ok_or(format!("{title}: no beatgrid"))?; let structure: SongStructure = - analysis("EXT").as_ref().and_then(phrase::song_structure).ok_or(format!("{title}: no phrases"))?; - let beats: Vec<Beat> = grid - .times - .iter() - .zip(&grid.beats) - .zip(&grid.bpms) - .map(|((&time_ms, &number), &bpm)| Beat { - number: u8::try_from(number).unwrap_or(0), - tempo_x100: (bpm * 100.0).round() as u16, - time_ms, - }) - .collect(); - let mono = decode_mono(Path::new(&track.folder_path)).map_err(|e| format!("{title}: {e}"))?; + share.analysis(track, "EXT").as_ref().and_then(phrase::song_structure).ok_or(format!("{title}: no phrases"))?; + let mono = decode_mono(audio(track)).map_err(|e| format!("{title}: {e}"))?; let features = BeatFeatures::measure(&mono, f64::from(SAMPLE_RATE), &beats); let theirs = structure .phrases diff --git a/native/crates/es-analyse/src/lib.rs b/native/crates/es-analyse/src/lib.rs index 8074d68..896c432 100644 --- a/native/crates/es-analyse/src/lib.rs +++ b/native/crates/es-analyse/src/lib.rs @@ -28,6 +28,8 @@ const ONSET_HZ: (f64, f64) = (30.0, 16_000.0); /// How many times more of the phrase changes another beat of the bar must carry before a detected /// grid's downbeat moves to it. const DOWNBEAT_RECHECK_TRUST: f64 = 3.0; +/// How far from a beat, in beats, a cue placed by hand may sit and still count as on it. +const CUE_SNAP_BEATS: f64 = 0.25; #[derive(Debug, Clone)] pub struct Options { @@ -78,6 +80,16 @@ pub fn nearest_beat(grid: &[Beat], ms: f64, tolerance_ms: f64) -> Option<usize> .filter(|&index| distance(index) <= tolerance_ms) } +/// The beat a hand-placed cue sits on: the nearest one, if within a quarter of a beat. Cues are +/// put on beats, so a cue further off than its beat's own jitter is one the grid has moved under +/// since, and a quarter of a beat still can't reach the wrong beat. +pub fn beat_of_cue(grid: &[Beat], ms: f64) -> Option<usize> { + let nearest = nearest_beat(grid, ms, f64::INFINITY)?; + let neighbour = if nearest + 1 < grid.len() { nearest + 1 } else { nearest.checked_sub(1)? }; + let beat_ms = f64::from(grid[nearest].time_ms.abs_diff(grid[neighbour].time_ms)); + nearest_beat(grid, ms, beat_ms * CUE_SNAP_BEATS) +} + /// Decodes `path` through the deck's decoder at [`SAMPLE_RATE`], mixed to mono. pub fn decode_mono(path: &Path) -> Result<Vec<f32>, DecodeError> { let mut streamer = Streamer::open(path, SAMPLE_RATE)?; @@ -179,6 +191,17 @@ mod tests { const RATE: f64 = 44_100.0; + #[test] + fn a_cue_counts_on_the_nearest_beat_within_a_quarter_of_one() { + let grid: Vec<Beat> = (0..4u32) + .map(|index| Beat { number: (index % 4) as u8 + 1, tempo_x100: 13_800, time_ms: 28 + index * 435 }) + .collect(); + assert_eq!(beat_of_cue(&grid, 51.0), Some(0)); + assert_eq!(beat_of_cue(&grid, 463.0 - 100.0), Some(1)); + assert_eq!(beat_of_cue(&grid, 463.0 - 120.0), None); + assert_eq!(beat_of_cue(&grid, 1333.0 + 50.0), Some(3)); + } + /// A kick (decaying 55 Hz sine with a click) on every beat, hats on the off-beats, and a held /// chord, starting `offset` seconds in. fn track(bpm: f64, seconds: f64, offset: f64, chord: &[f64]) -> Vec<f32> { diff --git a/native/crates/es-node/src/cue_style.rs b/native/crates/es-node/src/cue_style.rs index 1d9e045..ce08117 100644 --- a/native/crates/es-node/src/cue_style.rs +++ b/native/crates/es-node/src/cue_style.rs @@ -5,7 +5,7 @@ use std::path::Path; use es_analyse::cue_style::{CueStyle, Learning, TrainingTrack}; use es_analyse::structure::sections_on; -use es_analyse::{decode_mono, nearest_beat, SAMPLE_RATE}; +use es_analyse::{beat_of_cue, decode_mono, SAMPLE_RATE}; use napi::bindgen_prelude::*; use napi::{Env, Task}; use napi_derive::napi; @@ -13,8 +13,6 @@ use rayon::prelude::*; use crate::GridJs; -/// A cue within this of a beat is taken to be on it; one further off is left out of learning. -const ON_BEAT_MS: f64 = 15.0; const MEMORY_KIND: u32 = 0; #[napi(object)] @@ -49,7 +47,7 @@ fn training_track(track: &CuedTrackJs) -> Option<TrainingTrack> { .cues .iter() .filter_map(|cue| { - let beat = nearest_beat(&grid, cue.start_ms, ON_BEAT_MS)?; + let beat = beat_of_cue(&grid, cue.start_ms)?; let pad = (cue.kind != MEMORY_KIND).then(|| u8::try_from(cue.kind).ok()).flatten(); Some((pad, beat)) }) From 6e7169372f00ec5a2723893d55e2be8e834c0126 Mon Sep 17 00:00:00 2001 From: claw1200 <carstenwood12@gmail.com> Date: Sun, 29 Nov 2026 17:52:08 +0000 Subject: [PATCH 20/25] Refactor cue style logic and enhance memory cue placement - Updated CueStyleDialog to clarify memory cue placement rules. - Modified cueStyle.ts to introduce SectionStart and improve cue likelihood calculations. - Added tests for new SectionStart descriptions and their behavior. - Enhanced cue_score.rs to report learned styles and improve memory cue placement logic. - Updated cue_style_eval.rs to streamline memory cue learning and reporting. - Improved phrase_score.rs to incorporate novelty in section naming. - Refined structure.rs to include change metrics for sections and adjust section naming logic. - Added CUE_TUNING.md to document cue tuning methodology and benchmarks. --- app/src/preload/autoCue.d.ts | 30 +- .../src/lib/components/CueStyleDialog.svelte | 7 +- app/src/renderer/src/lib/cueStyle.ts | 47 ++- app/tests/cueStyle.test.ts | 29 +- native/crates/es-analyse/CUE_TUNING.md | 88 +++++ .../crates/es-analyse/examples/cue_score.rs | 26 +- .../es-analyse/examples/cue_style_eval.rs | 34 +- .../es-analyse/examples/phrase_score.rs | 6 +- native/crates/es-analyse/src/cue_style.rs | 318 +++++++++++++----- native/crates/es-analyse/src/structure.rs | 28 +- 10 files changed, 486 insertions(+), 127 deletions(-) create mode 100644 native/crates/es-analyse/CUE_TUNING.md diff --git a/app/src/preload/autoCue.d.ts b/app/src/preload/autoCue.d.ts index f9d2943..e08bff6 100644 --- a/app/src/preload/autoCue.d.ts +++ b/app/src/preload/autoCue.d.ts @@ -29,8 +29,34 @@ export interface LearntRule { cuesMisplaced: number } -/** A style as the native learner writes it: rules for memory cues, or one rule per hot cue pad. */ -export type CueStyle = { cues: 'memory'; rules: LearntRule[] } | { cues: 'hot'; pads: [number, LearntRule][] } +/** What comes just before a section; a section after its own kind carries a run of that kind on. */ +export type Preceding = 'trackStart' | { section: SectionKind } + +/** A sort of section start. Null takes in every value. */ +export interface SectionStart { + kind: SectionKind | null + after: Preceding | null + /** Carrying a run on: whether a long run has played. Otherwise: whether the music changes more than usual. */ + standsOut: boolean | null +} + +export interface LearntStart { + start: SectionStart + cued: number + seen: number + likelihood: number +} + +export interface MemoryCueStyle { + /** Most likely first. */ + starts: LearntStart[] + /** How likely the DJ must be to cue a start for the style to cue it. */ + cueLine: number + closestCues: number +} + +/** A style as the native learner writes it: section starts for memory cues, or one rule per hot cue pad. */ +export type CueStyle = ({ cues: 'memory' } & MemoryCueStyle) | { cues: 'hot'; pads: [number, LearntRule][] } export interface AutoCueFinished { id: string diff --git a/app/src/renderer/src/lib/components/CueStyleDialog.svelte b/app/src/renderer/src/lib/components/CueStyleDialog.svelte index cf3f0eb..99f827d 100644 --- a/app/src/renderer/src/lib/components/CueStyleDialog.svelte +++ b/app/src/renderer/src/lib/components/CueStyleDialog.svelte @@ -30,7 +30,8 @@ <h2 class="text-[13.5px] font-semibold">What the cue palette teaches</h2> <p class="mt-1.5 text-[12.5px] leading-relaxed text-muted"> Learnt from the cues you placed yourself on the palette’s {paletteIds.length} - {paletteIds.length === 1 ? 'track' : 'tracks'}. Auto cue places cues by these rules, most useful first. + {paletteIds.length === 1 ? 'track' : 'tracks'}. Memory cues go on the section starts you cue most often, likeliest + first; hot cues follow one rule per pad. </p> {#each styles as style (style.title)} <h3 class="mt-4 mb-1 text-[10.5px] font-semibold tracking-wider text-faint uppercase">{style.title}</h3> @@ -43,9 +44,7 @@ {#each rows as row (row.label)} <li class="flex items-baseline gap-3 text-[12.5px]"> <span class="flex-1">{row.label}</span> - <span class="tabular shrink-0 text-[11px] text-faint"> - right {row.cuesFound}, wrong {row.cuesMisplaced} - </span> + <span class="tabular shrink-0 text-[11px] text-faint">{row.tally}</span> </li> {/each} </ul> diff --git a/app/src/renderer/src/lib/cueStyle.ts b/app/src/renderer/src/lib/cueStyle.ts index 11a8876..506f452 100644 --- a/app/src/renderer/src/lib/cueStyle.ts +++ b/app/src/renderer/src/lib/cueStyle.ts @@ -1,4 +1,4 @@ -import type { CueRule, CueStyle } from '../../../preload/autoCue' +import type { CueRule, CueStyle, LearntStart, SectionStart } from '../../../preload/autoCue' import { hotCueLetter } from './format' const ORDINALS = ['first', 'second', 'third', 'fourth'] @@ -32,24 +32,49 @@ export function describeRule(rule: CueRule): string { return rule.thenEvery ? `${place}, then every ${bars(rule.thenEvery)} through ${through}` : place } +const carriesOn = (start: SectionStart): boolean => + typeof start.after === 'object' && start.after !== null && start.after.section === start.kind + +const withArticle = (noun: string): string => `${/^[aeiou]/.test(noun) ? 'an' : 'a'} ${noun}` + +function precedingName(start: SectionStart): string { + if (start.after === null) return '' + if (start.after === 'trackStart') return ' opening the track' + return ` after ${withArticle(start.after.section)}` +} + +function standingName(start: SectionStart): string { + if (start.standsOut === null) return '' + if (carriesOn(start)) return start.standsOut ? ', after a long run of it' : ', early in a run of it' + return start.standsOut ? ', where the music changes more than usual' : ', where the music changes less than usual' +} + +/** A sort of section start in words, such as "A drop after a build, where the music changes more than usual". */ +export function describeStart(start: SectionStart): string { + const named = withArticle(start.kind ?? 'section') + precedingName(start) + standingName(start) + return named[0].toUpperCase() + named.slice(1) +} + +const isNarrowest = ({ start }: LearntStart): boolean => + start.kind !== null && start.after !== null && start.standsOut !== null + export interface StyleRow { label: string - cuesFound: number - cuesMisplaced: number + tally: string } -/** A learnt style as lines to read, each pad named for hot cues. */ +/** A learnt style as lines to read: for memory cues the section starts it cues, for hot cues each pad. */ export function styleRows(style: CueStyle): StyleRow[] { if (style.cues === 'memory') { - return style.rules.map(({ rule, cuesFound, cuesMisplaced }) => ({ - label: describeRule(rule), - cuesFound, - cuesMisplaced - })) + return style.starts + .filter((learnt) => isNarrowest(learnt) && learnt.likelihood >= style.cueLine) + .map(({ start, cued, seen, likelihood }) => ({ + label: describeStart(start), + tally: `${Math.round(likelihood * 100)}%, ${cued} of ${seen}` + })) } return style.pads.map(([slot, { rule, cuesFound, cuesMisplaced }]) => ({ label: `Pad ${hotCueLetter(slot)}: ${describeRule(rule)}`, - cuesFound, - cuesMisplaced + tally: `right ${cuesFound}, wrong ${cuesMisplaced}` })) } diff --git a/app/tests/cueStyle.test.ts b/app/tests/cueStyle.test.ts index bf3276d..239b3b1 100644 --- a/app/tests/cueStyle.test.ts +++ b/app/tests/cueStyle.test.ts @@ -4,8 +4,9 @@ import { describe, it } from 'node:test' register(new URL('./resolve-ts.mjs', import.meta.url).href) -const { describeRule } = await import('../src/renderer/src/lib/cueStyle.ts') +const { describeRule, describeStart } = await import('../src/renderer/src/lib/cueStyle.ts') type CueRule = import('../src/preload/autoCue').CueRule +type SectionStart = import('../src/preload/autoCue').SectionStart const rule = (fields: Partial<CueRule>): CueRule => ({ kind: 'drop', @@ -43,3 +44,29 @@ describe('describeRule', () => { ) }) }) + +describe('describeStart', () => { + const start = (fields: Partial<SectionStart>): SectionStart => ({ + kind: 'drop', + after: { section: 'build' }, + standsOut: null, + ...fields + }) + + it('names the kind and what comes before it', () => { + assert.equal(describeStart(start({})), 'A drop after a build') + assert.equal(describeStart(start({ kind: 'intro', after: 'trackStart' })), 'An intro opening the track') + assert.equal(describeStart(start({ kind: null, after: null })), 'A section') + }) + + it('says how a start stands out', () => { + assert.equal( + describeStart(start({ standsOut: true })), + 'A drop after a build, where the music changes more than usual' + ) + assert.equal( + describeStart(start({ after: { section: 'drop' }, standsOut: true })), + 'A drop after a drop, after a long run of it' + ) + }) +}) diff --git a/native/crates/es-analyse/CUE_TUNING.md b/native/crates/es-analyse/CUE_TUNING.md new file mode 100644 index 0000000..db4e77a --- /dev/null +++ b/native/crates/es-analyse/CUE_TUNING.md @@ -0,0 +1,88 @@ +# Cue tuning + +How we make auto cue in [`src/cue_style.rs`](src/cue_style.rs) place memory cues where the DJ +would, and what we have learnt doing it. Sections come from [phrase tuning](PHRASE_TUNING.md). + +## The benchmark + +The tracks of the app's **cue palette** carry memory cues the DJ placed by hand. The benchmark is +[`examples/cue_score.rs`](examples/cue_score.rs): + +```sh +cd native +cargo run --release -p es-analyse --example cue_score # scores +cargo run --release -p es-analyse --example cue_score -- --style # the style learnt from every track +cargo run --release -p es-analyse --example cue_score -- london # one track's cues, theirs and ours +cargo run --release -p es-analyse --example cue_score -- --playlist "phrase examples" +``` + +A hand-placed cue counts on its nearest beat when it is within a quarter of a beat of it, so a +cue set before the grid was nudged still counts. + +| Measure | Meaning | +|---|---| +| **your cues found** | Share of the DJ's cues we place on exactly their beat. | +| **ours where you had none** | Share of our cues on a beat the DJ left alone. | +| within a bar | Share of ours within a bar of one of theirs; the gap to exact is near misses. | + +Both are pooled over every cue, not averaged per track. **Cross-validated** is the honest +score: each fifth of the tracks is cued by a style learnt from the other four fifths. +**In-sample** learns from every track and places on them; it shows how much the style can hold. + +### Targets + +- your cues found: above 85% +- ours where you had none: under 15% + +The targets are a guide. The style is learnt from each DJ's own palette, so nothing here may be +fitted to one DJ's habits. + +## What a DJ's cues look like (one palette, 53 tracks, about 410 cues) + +- 92% sit exactly on a section start. Most of the rest are 8 bars into a 16-bar drop. +- No sort of start is cued reliably by its kind alone: the opening intro about 94%, a drop after + the intro 85%, a drop after a build 77%, a drop carrying on a drop 30%, a build after a + breakdown under 20%. +- Spacing matters. A drop that carries on another is cued about 17 times in 24 once 32 bars of + drop have played, against 10 in 71 after 16 bars. The DJ seldom puts cues under 8 bars apart. +- The DJ's own words: a repeated section is cued when the music changes a lot, the sections are + longer than 8 bars and differ in length, and there are cues to spare. On long tracks the + spread across the track comes before every small change. + +## How the style works + +1. **Section starts by sort.** Each start is told by its kind, what precedes it (the track's + start or a kind of section), and whether it stands out: for a section carrying on a run of its + kind, whether 32 bars of the kind have played; for any other, whether the music changes more + there than at the track's middle section start. +2. **Likelihood.** How often the DJ cued each sort of start, with the broader sort it belongs to + counted in as 4 sightings, so a sort seen on few tracks leans on its broader sort. +3. **The line.** The style cues sorts at or above the likelihood that best matches the DJ's own + cues in training (F1), and learns the closest the DJ puts cues (the 5th percentile of the + gaps between their neighbouring cues). +4. **Placing.** Likeliest starts first, skipping any closer than that to a cue already placed, + up to 10 cues. + +## Log + +| | found | extra | +|---|---|---| +| Greedy F1 rules (cross-validated) | 73.7% | 42.5% | +| Section starts by sort, with "a big change" | 75.6% | 29.3% | +| and "after a long run" for a section carrying on its kind | **80.1%** | **29.6%** | + +Tried and dropped: +- Conditions on the greedy rules (what precedes, a big change): the greedy search still took + "every change of kind" first, which mixes sorts cued 90% and 18% of the time. +- Learning rules most-reliable-first: fewer extras, but far fewer found. +- Both sections over 8 bars, or of different lengths, as the mark on a repeated section; the + previous run's length as the mark at a change of kind; requiring a big change and a long run + together. +- Cues 8, 16 or 32 bars into a section; a tighter cue budget per track. Each traded cues found + for extras one for one. + +What is left: +- A per-start logistic model over every measure (kind, neighbours, energy and novelty per + feature group, spacing since the last cue) reached about 81% / 29% cross-validated, and about + 82% / 24% even on the DJ's hand-set phrases. So 85% / 15% needs a signal we don't measure yet, + such as what comes in at a start (a vocal, a lead, a bassline switch). diff --git a/native/crates/es-analyse/examples/cue_score.rs b/native/crates/es-analyse/examples/cue_score.rs index 381e304..08e3de2 100644 --- a/native/crates/es-analyse/examples/cue_score.rs +++ b/native/crates/es-analyse/examples/cue_score.rs @@ -5,11 +5,12 @@ //! give back nearly what the DJ did; and cross-validated, each fifth of the tracks cued by a style //! learnt from the other four fifths, which is how it does on tracks it hasn't seen. Targets are //! held against the cross-validated score. Automatic cues are left out of the DJ's. -//! `cargo run --release -p es-analyse --example cue_score [-- <title words>] [--playlist <name>]` +//! `cargo run --release -p es-analyse --example cue_score [-- <title words> | --style] [--playlist <name>]` +//! `--style` shows the style learnt from every track. use std::collections::HashSet; -use es_analyse::cue_style::{CuedTrack, Learning, MemoryCueStyle, MEMORY_CUE_LIMIT}; +use es_analyse::cue_style::{CuedTrack, MemoryCueStyle, MEMORY_CUE_LIMIT}; use es_analyse::structure::{segment, BeatFeatures, BeatIndex, Section, Tuning}; use es_analyse::{beat_of_cue, decode_mono, SAMPLE_RATE}; use rayon::prelude::*; @@ -128,6 +129,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { cued.iter().enumerate().map(|(index, track)| by_fold[track.fold as usize][index].clone()).collect() }; + if args.iter().any(|arg| arg == "--style") { + report_style(&cued); + return Ok(()); + } if let Some(words) = title_words { timelines(&cued, &cross_validated, words); return Ok(()); @@ -159,8 +164,21 @@ fn measure(share: &Share, track: &Track, cues_ms: &[i64]) -> Result<Cued, String /// For every track, where a style learnt from the tracks `learns_from` picks places its cues. fn place_learnt_from(tracks: &[Cued], learns_from: impl Fn(&Cued) -> bool) -> Vec<Vec<BeatIndex>> { let training: Vec<CuedTrack> = tracks.iter().filter(|track| learns_from(track)).map(Cued::training).collect(); - let style = MemoryCueStyle::learn(&training, &Learning::default()); - tracks.iter().map(|track| style.place(&track.sections, track.beat_count, MEMORY_CUE_LIMIT)).collect() + let style = MemoryCueStyle::learn(&training); + tracks.iter().map(|track| style.place(&track.sections, MEMORY_CUE_LIMIT)).collect() +} + +fn report_style(tracks: &[Cued]) { + let style = MemoryCueStyle::learn(&tracks.iter().map(Cued::training).collect::<Vec<_>>()); + println!( + "Cues where you cue {:.0}% of the time or more, at least {} bars apart\n", + 100.0 * style.cue_line, + style.closest_cues / BEATS_PER_BAR + ); + println!("{:>11} {:>9} section start", "you cue it", "of"); + for learnt in &style.starts { + println!("{:>10.0}% {:>4} of {:<4} {}", 100.0 * learnt.likelihood, learnt.cued, learnt.seen, learnt.start); + } } fn report_tracks(tracks: &[Cued], placed: &[Vec<BeatIndex>]) { diff --git a/native/crates/es-analyse/examples/cue_style_eval.rs b/native/crates/es-analyse/examples/cue_style_eval.rs index d36554e..2feead9 100644 --- a/native/crates/es-analyse/examples/cue_style_eval.rs +++ b/native/crates/es-analyse/examples/cue_style_eval.rs @@ -6,7 +6,9 @@ use std::collections::{BTreeMap, HashSet}; use std::path::Path; -use es_analyse::cue_style::{Counting, CueRule, CuedTrack, HotCueSlot, HotCueStyle, Learning, MemoryCueStyle, Which}; +use es_analyse::cue_style::{ + Counting, CueRule, CuedTrack, HotCueSlot, HotCueStyle, Learning, MemoryCueStyle, Which, MEMORY_CUE_LIMIT, +}; use es_analyse::structure::{segment, BeatFeatures, BeatIndex, Section, Tuning}; use es_analyse::{decode_mono, SAMPLE_RATE}; use rayon::prelude::*; @@ -17,7 +19,6 @@ mod survey; use survey::{nearest_beat, survey_grid, Score, BEATS_PER_BAR, SURVEY_ON_BEAT_MS}; const FOLDS: usize = 10; -const MEMORY_CUE_LIMIT: usize = 10; struct Track { sections: Vec<Section>, @@ -41,10 +42,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { println!("measured {} of {} tracks, {} with memory cues\n", tracks.len(), survey.len(), memory.len()); report_baselines(&memory); - for least_track_share in [0.02, 0.05, 0.1, 0.2] { - let score = cross_validate(&memory, &Learning { least_track_share }); - println!("{}", score.line(&format!("learnt, rules on {}%+ of tracks", least_track_share * 100.0))); - } + println!("{}", cross_validate(&memory).line("learnt")); report_style(&memory); report_missed(&memory); report_hot_cues(&tracks); @@ -91,7 +89,7 @@ fn report_baselines(tracks: &[&Track]) { println!("{}", every_16_bars.line("a cue every 16 bars")); } -fn cross_validate(tracks: &[&Track], learning: &Learning) -> Score { +fn cross_validate(tracks: &[&Track]) -> Score { let scores: Vec<Score> = (0..FOLDS) .into_par_iter() .map(|fold| { @@ -101,10 +99,10 @@ fn cross_validate(tracks: &[&Track], learning: &Learning) -> Score { .filter(|(index, _)| index % FOLDS != fold) .map(|(_, track)| track.cued(track.memory_cues.clone())) .collect(); - let style = MemoryCueStyle::learn(&training, learning); + let style = MemoryCueStyle::learn(&training); let mut score = Score::default(); for track in tracks.iter().enumerate().filter(|(index, _)| index % FOLDS == fold).map(|(_, track)| track) { - let placed = style.place(&track.sections, track.beat_count, MEMORY_CUE_LIMIT); + let placed = style.place(&track.sections, MEMORY_CUE_LIMIT); score.add(&track.memory_cues, &placed.into_iter().collect()); } score @@ -134,15 +132,10 @@ fn describe(rule: &CueRule) -> String { fn report_style(tracks: &[&Track]) { let training: Vec<CuedTrack> = tracks.iter().map(|track| track.cued(track.memory_cues.clone())).collect(); - let style = MemoryCueStyle::learn(&training, &Learning::default()); - println!("\nmemory cue style learnt from all {} tracks:", tracks.len()); - for learnt in &style.rules { - println!( - " {:<32} finds {:>4} cues, misplaces {:>4}", - describe(&learnt.rule), - learnt.cues_found, - learnt.cues_misplaced - ); + let style = MemoryCueStyle::learn(&training); + println!("\nmemory cue style learnt from all {} tracks, cueing from {:.0}%:", tracks.len(), 100.0 * style.cue_line); + for learnt in &style.starts { + println!(" {:>4.0}% {:>4} of {:<4} {}", 100.0 * learnt.likelihood, learnt.cued, learnt.seen, learnt.start); } } @@ -150,12 +143,11 @@ fn report_style(tracks: &[&Track]) { /// holds them and how long that section is. fn report_missed(tracks: &[&Track]) { let training: Vec<CuedTrack> = tracks.iter().map(|track| track.cued(track.memory_cues.clone())).collect(); - let style = MemoryCueStyle::learn(&training, &Learning::default()); + let style = MemoryCueStyle::learn(&training); let mut into: BTreeMap<String, usize> = BTreeMap::new(); let mut missed = 0; for track in tracks { - let placed: HashSet<BeatIndex> = - style.place(&track.sections, track.beat_count, MEMORY_CUE_LIMIT).into_iter().collect(); + let placed: HashSet<BeatIndex> = style.place(&track.sections, MEMORY_CUE_LIMIT).into_iter().collect(); for &cue in track.memory_cues.difference(&placed) { missed += 1; let Some(section) = track.sections.iter().rev().find(|section| section.first_beat <= cue) else { continue }; diff --git a/native/crates/es-analyse/examples/phrase_score.rs b/native/crates/es-analyse/examples/phrase_score.rs index e7522f2..2acafa5 100644 --- a/native/crates/es-analyse/examples/phrase_score.rs +++ b/native/crates/es-analyse/examples/phrase_score.rs @@ -10,7 +10,7 @@ use std::collections::{BTreeMap, HashSet}; -use es_analyse::structure::{name_sections, segment, BeatFeatures, BeatIndex, Section, SectionKind, Tuning}; +use es_analyse::structure::{name_sections, novelty, segment, BeatFeatures, BeatIndex, Section, SectionKind, Tuning}; use es_analyse::{decode_mono, SAMPLE_RATE}; use rayon::prelude::*; use rb_anlz::phrase::{self, Mood, PhraseKind, SongStructure}; @@ -139,7 +139,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { Some("--search") => search(&mut scored), Some("--on-your-starts") => { for track in &mut scored { - track.ours = name_sections(&track.features, &track.their_beats(), &Tuning::default()); + let tuning = Tuning::default(); + let novelty = novelty(&track.features, &tuning); + track.ours = name_sections(&track.features, &track.their_beats(), &novelty, &tuning); } report_all(scored); } diff --git a/native/crates/es-analyse/src/cue_style.rs b/native/crates/es-analyse/src/cue_style.rs index d7690de..344839b 100644 --- a/native/crates/es-analyse/src/cue_style.rs +++ b/native/crates/es-analyse/src/cue_style.rs @@ -1,21 +1,23 @@ -//! A DJ's way of placing cues, learnt from tracks they have cued and replayed on new ones. +//! A DJ's way of placing cues, learnt from tracks they have cued and replayed on new ones. Cues +//! are tied to sections rather than to bar counts from the top, because no two tracks share a +//! layout. //! -//! A style is a list of rules, each a number of bars from the start of some section: "on every -//! drop", "16 bars before the first drop", "on the second breakdown", "on every drop and every 16 -//! bars through it", "wherever the kind of section changes". Rules are tied to sections rather -//! than to bar counts from the top, because no two tracks share a layout. +//! Memory cues are learnt as how often the DJ cues each sort of section start: a drop after a +//! build, a breakdown after a drop where the music changes more than usual, a drop carried on +//! after a long run of it. A sort seen on few tracks leans on the broader sort it belongs to. A new +//! track is cued on the sorts the DJ cues often enough, the likeliest first and no closer together +//! than the DJ puts cues, up to the limit, so a long track keeps its likeliest cues. //! -//! Learning is greedy. Every rule that could be written is tried on every cued track; the rule that -//! most raises the F1 score of the kept rules' cues against the DJ's (balancing cues found against -//! cues put where the DJ had none) is kept, and the search repeats until no rule raises it. Memory -//! cues learn a set of rules. Hot cues learn one rule per pad, by the same search held to rules -//! that give a single cue. +//! Hot cues learn one rule per pad, each a number of bars from the start of some section: "16 bars +//! before the first drop", "on the second breakdown". Learning is greedy: every rule that gives a +//! single cue is tried on every cued track, and the one that most raises the F1 score of its cues +//! against the DJ's is kept. -use std::collections::{BTreeSet, HashSet}; +use std::collections::{BTreeSet, HashMap, HashSet}; use serde::{Deserialize, Serialize}; -use crate::structure::{BeatIndex, Section, SectionKind}; +use crate::structure::{BeatIndex, Beats, Section, SectionKind, StandardDeviations}; pub type BarOffset = i32; pub type Bars = u16; @@ -29,6 +31,10 @@ const REPEATS: [Bars; 3] = [8, 16, 32]; const LATEST_OCCURRENCE: u8 = 4; /// Cues nearer than this to one already placed are left out. const MIN_GAP_BEATS: usize = 4; +const BROADER_START_WEIGHT: f64 = 4.0; +const SELDOM: f64 = 0.05; +const LONG_RUN_BARS: usize = 32; +const CUE_LINES: [f64; 7] = [0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55]; /// Which of the sections of a kind a rule counts from. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -197,44 +203,202 @@ fn learn_rules( kept } -impl LearntRule { - /// The share of the cues it placed in training that the DJ had placed too. - fn precision(&self) -> f64 { - self.cues_found as f64 / (self.cues_found + self.cues_misplaced).max(1) as f64 +/// What comes just before a section. A section after one of its own kind is that kind phrased in two. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Preceding { + TrackStart, + Section(SectionKind), +} + +/// A sort of section start. A field left `None` takes in every value, so a start can be as broad +/// as "the start of any drop". +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SectionStart { + pub kind: Option<SectionKind>, + pub after: Option<Preceding>, + /// See `stands_out`. + pub stands_out: Option<bool>, +} + +impl SectionStart { + /// This start, then ever broader ones that take it in. + fn broadening(self) -> Vec<Self> { + let unmarked = Self { stands_out: None, ..self }; + let after_anything = Self { after: None, ..unmarked }; + let mut chain = vec![self, unmarked, after_anything, Self { kind: None, ..after_anything }]; + chain.dedup(); + chain } } -/// Where the rules put cues on one track, the most precise rules' first, skipping any too near a -/// cue already placed, at most `limit` of them. -fn place_all(rules: &[LearntRule], sections: &[Section], beat_count: usize, limit: usize) -> Vec<BeatIndex> { - let mut by_precision: Vec<&LearntRule> = rules.iter().collect(); - by_precision.sort_by(|a, b| b.precision().total_cmp(&a.precision())); - let mut placed: Vec<BeatIndex> = Vec::new(); - for beat in by_precision.iter().flat_map(|learnt| learnt.rule.place(sections, beat_count)) { - if placed.len() < limit && placed.iter().all(|&other| other.abs_diff(beat) >= MIN_GAP_BEATS) { - placed.push(beat); +impl std::fmt::Display for SectionStart { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "{}", self.kind.map_or("section", SectionKind::name))?; + match self.after { + Some(Preceding::TrackStart) => write!(f, " opening the track")?, + Some(Preceding::Section(kind)) => write!(f, " after {}", kind.name())?, + None => {} + } + let carries_on = self.after.is_some_and(|after| after == self.kind.map_or(after, Preceding::Section)); + match (self.stands_out, carries_on) { + (Some(true), true) => write!(f, ", after a long run"), + (Some(false), true) => write!(f, ", after a short run"), + (Some(true), false) => write!(f, ", a big change"), + (Some(false), false) => write!(f, ", a small change"), + (None, _) => Ok(()), } } - placed.sort_unstable(); - placed +} + +/// Each section's start, told as narrowly as it can be, with its beat. +fn section_starts(sections: &[Section]) -> Vec<(SectionStart, BeatIndex)> { + let typical_change = typical_change(sections); + sections + .iter() + .enumerate() + .map(|(index, section)| { + let after = match index { + 0 => Preceding::TrackStart, + _ => Preceding::Section(sections[index - 1].kind), + }; + let start = SectionStart { + kind: Some(section.kind), + after: Some(after), + stands_out: Some(stands_out(sections, index, typical_change)), + }; + (start, section.first_beat) + }) + .collect() +} + +/// A section that carries on the kind before it stands out once a long run of the kind has played, +/// when a DJ who cues sparingly will want a new cue; any other stands out where the music changes +/// more than at the track's middle section start. +fn stands_out(sections: &[Section], index: usize, typical_change: StandardDeviations) -> bool { + let section = §ions[index]; + let run_start = sections[..index].iter().rev().take_while(|before| before.kind == section.kind).last(); + match run_start { + Some(run_start) => section.first_beat - run_start.first_beat >= LONG_RUN_BARS * BEATS_PER_BAR as usize, + None => section.change > typical_change, + } +} + +fn typical_change(sections: &[Section]) -> StandardDeviations { + let mut changes: Vec<StandardDeviations> = sections.iter().map(|section| section.change).collect(); + changes.sort_by(f64::total_cmp); + changes.get(changes.len() / 2).copied().unwrap_or(0.0) +} + +/// How often the DJ cued a sort of section start in training, and so how likely they are to cue +/// it on a new track. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LearntStart { + pub start: SectionStart, + pub cued: usize, + pub seen: usize, + pub likelihood: f64, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MemoryCueStyle { - pub rules: Vec<LearntRule>, + /// Most likely first. + pub starts: Vec<LearntStart>, + /// How likely the DJ must be to cue a start for the style to cue it. + pub cue_line: f64, + /// The DJ seldom puts cues closer together than this. + pub closest_cues: Beats, } impl MemoryCueStyle { - pub fn learn(tracks: &[CuedTrack], learning: &Learning) -> Self { - Self { rules: learn_rules(tracks, learning, usize::MAX, |_| true) } + /// Each start's likelihood is its own tally with the likelihood of the broader start it + /// belongs to counted in as `BROADER_START_WEIGHT` sightings, so a start seen on few tracks + /// leans on what is known of its sort. The line is wherever the style best matches the DJ's + /// own cues. + pub fn learn(tracks: &[CuedTrack]) -> Self { + let mut tallies: HashMap<SectionStart, (usize, usize)> = HashMap::new(); + for track in tracks { + for (start, beat) in section_starts(&track.sections) { + for broader in start.broadening() { + let (cued, seen) = tallies.entry(broader).or_default(); + *cued += usize::from(track.cues.contains(&beat)); + *seen += 1; + } + } + } + let likelihood_of = |start: SectionStart| { + start.broadening().iter().rev().fold(0.0, |broader_likelihood, broader| { + let (cued, seen) = tallies.get(broader).copied().unwrap_or_default(); + (cued as f64 + BROADER_START_WEIGHT * broader_likelihood) / (seen as f64 + BROADER_START_WEIGHT) + }) + }; + let mut starts: Vec<LearntStart> = tallies + .iter() + .map(|(&start, &(cued, seen))| LearntStart { start, cued, seen, likelihood: likelihood_of(start) }) + .collect(); + starts.sort_by(|a, b| b.likelihood.total_cmp(&a.likelihood).then(b.seen.cmp(&a.seen))); + let mut style = Self { starts, cue_line: 0.0, closest_cues: closest_cues(tracks) }; + style.cue_line = CUE_LINES + .into_iter() + .max_by(|&a, &b| style.agreement_at(a, tracks).total_cmp(&style.agreement_at(b, tracks))) + .unwrap_or_default(); + style + } + + /// The starts the DJ is likely enough to cue, most likely first, skipping any closer than they + /// would put cues to one already placed, at most `limit` of them. + pub fn place(&self, sections: &[Section], limit: usize) -> Vec<BeatIndex> { + let learnt: HashMap<SectionStart, f64> = + self.starts.iter().map(|learnt| (learnt.start, learnt.likelihood)).collect(); + let likelihood = + |start: SectionStart| start.broadening().iter().find_map(|broader| learnt.get(broader).copied()); + let mut likely: Vec<(f64, BeatIndex)> = section_starts(sections) + .into_iter() + .filter_map(|(start, beat)| Some((likelihood(start)?, beat))) + .filter(|&(likelihood, _)| likelihood >= self.cue_line) + .collect(); + likely.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1))); + let mut placed: Vec<BeatIndex> = Vec::new(); + for (_, beat) in likely { + if placed.len() < limit && placed.iter().all(|&other| other.abs_diff(beat) >= self.closest_cues) { + placed.push(beat); + } + } + placed.sort_unstable(); + placed } - pub fn place(&self, sections: &[Section], beat_count: usize, limit: usize) -> Vec<BeatIndex> { - place_all(&self.rules, sections, beat_count, limit) + /// F1 of the cues placed at `cue_line` against the DJ's. + fn agreement_at(&self, cue_line: f64, tracks: &[CuedTrack]) -> f64 { + let at_line = Self { cue_line, ..self.clone() }; + let (mut found, mut placed, mut theirs) = (0, 0, 0); + for track in tracks { + let beats = at_line.place(&track.sections, MEMORY_CUE_LIMIT); + found += beats.iter().filter(|beat| track.cues.contains(beat)).count(); + placed += beats.len(); + theirs += track.cues.len(); + } + 2.0 * found as f64 / (placed + theirs).max(1) as f64 } } +/// The gap between neighbouring cues that only `SELDOM` of the DJ's gaps fall short of. +fn closest_cues(tracks: &[CuedTrack]) -> Beats { + let mut gaps: Vec<Beats> = tracks + .iter() + .flat_map(|track| { + let mut cues: Vec<BeatIndex> = track.cues.iter().copied().collect(); + cues.sort_unstable(); + cues.windows(2).map(|pair| pair[1] - pair[0]).collect::<Vec<Beats>>() + }) + .collect(); + gaps.sort_unstable(); + gaps.get((gaps.len() as f64 * SELDOM) as usize).copied().unwrap_or(MIN_GAP_BEATS).max(MIN_GAP_BEATS) +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct HotCueStyle { @@ -298,7 +462,7 @@ impl CueStyle { .map(|track| track.cued(track.cues.iter().filter(|(pad, _)| pad.is_none()).map(|&(_, b)| b).collect())) .filter(|cued| !cued.cues.is_empty()) .collect(); - return Self::Memory(MemoryCueStyle::learn(&memory, learning)); + return Self::Memory(MemoryCueStyle::learn(&memory)); } let pads: BTreeSet<HotCueSlot> = tracks.iter().flat_map(|track| track.cues.iter().filter_map(|&(pad, _)| pad)).collect(); @@ -322,7 +486,7 @@ impl CueStyle { pub fn place(&self, sections: &[Section], beat_count: usize) -> Vec<(Option<HotCueSlot>, BeatIndex)> { match self { Self::Memory(style) => { - style.place(sections, beat_count, MEMORY_CUE_LIMIT).into_iter().map(|beat| (None, beat)).collect() + style.place(sections, MEMORY_CUE_LIMIT).into_iter().map(|beat| (None, beat)).collect() } Self::Hot(style) => { style.place(sections, beat_count).into_iter().map(|(pad, beat)| (Some(pad), beat)).collect() @@ -336,7 +500,7 @@ mod tests { use super::*; fn section(first_beat: BeatIndex, kind: SectionKind) -> Section { - Section { first_beat, beats: 64, kind, relative_energy: 0.5 } + Section { first_beat, beats: 64, kind, relative_energy: 0.5, change: 0.0 } } /// Intro, build, drop, breakdown, build, drop, outro, with the drops `drop_at` and `second_drop_at`. @@ -352,12 +516,13 @@ mod tests { ] } - /// A DJ who cues the top, every drop, and 16 bars before each drop. + /// A DJ who cues the top, each drop and the breakdown, but never a build or the outro. fn cued(sections: Vec<Section>) -> CuedTrack { - let drops: Vec<BeatIndex> = - sections.iter().filter(|s| s.kind == SectionKind::Drop).map(|s| s.first_beat).collect(); - let mut cues: HashSet<BeatIndex> = drops.iter().flat_map(|&drop| [drop, drop - 64]).collect(); - cues.insert(0); + let cues = sections + .iter() + .filter(|s| s.first_beat == 0 || matches!(s.kind, SectionKind::Drop | SectionKind::Breakdown)) + .map(|s| s.first_beat) + .collect(); CuedTrack { sections, beat_count: 1000, cues } } @@ -384,10 +549,45 @@ mod tests { fn a_learnt_memory_style_finds_the_djs_cues_on_a_new_track() { let training: Vec<CuedTrack> = [(128, 448), (192, 512), (64, 384), (256, 640)].into_iter().map(|(a, b)| cued(track(a, b))).collect(); - let style = MemoryCueStyle::learn(&training, &Learning::default()); + let style = MemoryCueStyle::learn(&training); + + assert_eq!(style.place(&track(160, 544), 10), [0, 160, 288, 544]); + } + + #[test] + fn over_the_limit_the_likeliest_cues_are_kept() { + let training: Vec<CuedTrack> = + [(128, 448), (192, 512), (64, 384), (256, 640)].into_iter().map(|(a, b)| cued(track(a, b))).collect(); + let style = MemoryCueStyle::learn(&training); + + assert_eq!(style.place(&track(160, 544), 2), [160, 544]); + } + + #[test] + fn a_section_carrying_on_a_long_run_of_its_kind_stands_out() { + let sections = vec![ + section(0, SectionKind::Intro), + section(64, SectionKind::Drop), + section(128, SectionKind::Drop), + section(192, SectionKind::Drop), + ]; + let typical_change = typical_change(§ions); + assert!(!stands_out(§ions, 2, typical_change)); + assert!(stands_out(§ions, 3, typical_change)); + } + + #[test] + fn cues_are_kept_as_far_apart_as_the_dj_keeps_them() { + let sections = |second_start| vec![section(0, SectionKind::Intro), section(second_start, SectionKind::Intro)]; + let training: Vec<CuedTrack> = [32, 64, 96] + .into_iter() + .map(|second| CuedTrack { sections: sections(second), beat_count: 1000, cues: HashSet::from([0, second]) }) + .collect(); + let style = MemoryCueStyle::learn(&training); - let new_track = track(160, 544); - assert_eq!(style.place(&new_track, 1000, 10), [0, 96, 160, 480, 544]); + assert_eq!(style.closest_cues, 32); + assert_eq!(style.place(§ions(16), 10), [0]); + assert_eq!(style.place(§ions(32), 10), [0, 32]); } #[test] @@ -428,20 +628,6 @@ mod tests { assert_eq!(serde_json::from_str::<CueStyle>(&json).unwrap(), hot); } - #[test] - fn cues_too_near_one_already_placed_are_left_out() { - let sections = vec![section(0, SectionKind::Intro), section(2, SectionKind::Drop)]; - let every_start = CueRule { - kind: None, - counting: Counting::EverySection, - which: Which::Every, - bars_from_start: 0, - then_every: None, - }; - let learnt = LearntRule { rule: every_start, cues_found: 1, cues_misplaced: 0 }; - assert_eq!(place_all(&[learnt], §ions, 100, 10), [0]); - } - #[test] fn counting_run_starts_takes_a_drop_phrased_as_two_sections_once() { let sections = vec![ @@ -469,22 +655,4 @@ mod tests { }; assert_eq!(every_change.place(§ions, 1000), [0, 64, 192, 256]); } - - #[test] - fn over_the_limit_the_most_precise_rules_cues_are_kept() { - let sections = - vec![section(0, SectionKind::Intro), section(64, SectionKind::Drop), section(128, SectionKind::Outro)]; - let at = |kind| CueRule { - kind: Some(kind), - counting: Counting::EverySection, - which: Which::Every, - bars_from_start: 0, - then_every: None, - }; - let rules = [ - LearntRule { rule: at(SectionKind::Intro), cues_found: 1, cues_misplaced: 3 }, - LearntRule { rule: at(SectionKind::Outro), cues_found: 3, cues_misplaced: 1 }, - ]; - assert_eq!(place_all(&rules, §ions, 1000, 1), [128]); - } } diff --git a/native/crates/es-analyse/src/structure.rs b/native/crates/es-analyse/src/structure.rs index a6e09e8..a4b6e3b 100644 --- a/native/crates/es-analyse/src/structure.rs +++ b/native/crates/es-analyse/src/structure.rs @@ -21,6 +21,7 @@ use crate::{onset, spectrum, Beat, KICK_HZ, ONSET_FRAME, ONSET_HOP}; pub type BeatIndex = usize; pub type Beats = usize; pub type Bars = usize; +pub type StandardDeviations = f64; const HAT_HZ: (f64, f64) = (6_000.0, 16_000.0); const BEATS_PER_BAR: Beats = 4; @@ -75,6 +76,8 @@ pub struct Section { pub kind: SectionKind, /// 0 at the track's quiet end, 1 at its loud end. pub relative_energy: f64, + /// How much the music changes on its first beat, against the track's typical beat. + pub change: StandardDeviations, } #[derive(Debug, Clone, Copy, PartialEq)] @@ -209,13 +212,14 @@ pub fn segment(features: &BeatFeatures, tuning: &Tuning) -> Vec<Section> { if features.beats() == 0 { return Vec::new(); } - let starts = section_starts(features, tuning); - name_sections(features, &starts, tuning) + let novelty = novelty(features, tuning); + let starts = section_starts(features, &novelty, tuning); + name_sections(features, &starts, &novelty, tuning) } /// Each feature group's novelty on its own, summed by weight: an element coming in or dropping /// out stands out in its own group but is diluted among all the features together. -fn novelty(features: &BeatFeatures, tuning: &Tuning) -> Vec<f64> { +pub fn novelty(features: &BeatFeatures, tuning: &Tuning) -> Vec<StandardDeviations> { let widest = tuning.kernel_half_widths.iter().copied().max().unwrap_or(1); let reach = 2 * widest * BEATS_PER_BAR; let summed = features.groups(tuning).into_iter().filter(|(_, weight)| *weight > 0.0).map(|(columns, weight)| { @@ -296,8 +300,7 @@ pub fn bar_phase(on_downbeat: &[bool], votes: &[f64; BEATS_PER_BAR], trust: f64) /// section's length is counted from the start before it, so after an odd-length section the rest /// follow on from it, and starts on the track's 4-bar phrase lattice cost nothing; every lattice /// is tried and the one that earns most is kept. -fn section_starts(features: &BeatFeatures, tuning: &Tuning) -> Vec<BeatIndex> { - let novelty = novelty(features, tuning); +fn section_starts(features: &BeatFeatures, novelty: &[StandardDeviations], tuning: &Tuning) -> Vec<BeatIndex> { let first_downbeat = grid_phase(&features.on_downbeat); let lines: Vec<BeatIndex> = std::iter::once(0) .chain((first_downbeat..features.beats()).step_by(BEATS_PER_BAR).filter(|&b| b > 0)) @@ -408,7 +411,12 @@ impl Distances { /// What each section starting on `starts` is. Drops are the loud sections, other than drums alone; /// the opening sections are the intro, the last drop's followers the outro, a section leading /// into a drop a build, and the rest breakdowns. -pub fn name_sections(features: &BeatFeatures, starts: &[BeatIndex], tuning: &Tuning) -> Vec<Section> { +pub fn name_sections( + features: &BeatFeatures, + starts: &[BeatIndex], + novelty: &[StandardDeviations], + tuning: &Tuning, +) -> Vec<Section> { let energy = between_percentiles(&features.loudness); let drumming: Vec<f64> = standardise(&features.kick).iter().zip(standardise(&features.mids)).map(|(kick, mids)| kick - mids).collect(); @@ -454,7 +462,13 @@ pub fn name_sections(features: &BeatFeatures, starts: &[BeatIndex], tuning: &Tun } else { SectionKind::Breakdown }; - Section { first_beat, beats: end_beat - first_beat, kind, relative_energy: energies[index] } + Section { + first_beat, + beats: end_beat - first_beat, + kind, + relative_energy: energies[index], + change: novelty[first_beat], + } }) .collect() } From e6b2b7fd4322344108fa18131875744a5e8cb9a0 Mon Sep 17 00:00:00 2001 From: claw1200 <carstenwood12@gmail.com> Date: Sun, 29 Nov 2026 18:15:03 +0000 Subject: [PATCH 21/25] Implement CueStyleCache for persistent storage of learnt cue styles and enhance nativeBuild function for version tracking --- app/src/main/audio/native.ts | 7 ++++ app/src/main/autoCue.ts | 16 +++++-- app/src/main/cueStyleCache.ts | 58 ++++++++++++++++++++++++++ native/crates/es-node/src/cue_style.rs | 40 +++++++++++++++--- 4 files changed, 112 insertions(+), 9 deletions(-) create mode 100644 app/src/main/cueStyleCache.ts diff --git a/app/src/main/audio/native.ts b/app/src/main/audio/native.ts index daefb71..fdd2b86 100644 --- a/app/src/main/audio/native.ts +++ b/app/src/main/audio/native.ts @@ -1,5 +1,6 @@ import { app } from 'electron' import { join, sep } from 'path' +import { statSync } from 'fs' export interface NativeDeckEvent { kind: 'loaded' | 'error' @@ -204,6 +205,12 @@ function addonPath(): string { ) } +/** Changes whenever the addon is rebuilt, so results it learnt can be told from a newer build's. */ +export function nativeBuild(): string { + const { size, mtimeMs } = statSync(addonPath()) + return `${size}:${mtimeMs}` +} + export function loadNative(): NativeModule { const module = { exports: {} as NativeModule } process.dlopen(module, addonPath()) diff --git a/app/src/main/autoCue.ts b/app/src/main/autoCue.ts index dcab935..880f8c6 100644 --- a/app/src/main/autoCue.ts +++ b/app/src/main/autoCue.ts @@ -1,7 +1,8 @@ import { BrowserWindow, ipcMain } from 'electron' import type { AutoCueFinished, AutoCueProgress, AutoCueRequest, CueSort } from '../preload/autoCue' import { AUTO_CUE_COMMENT } from '../shared/cues' -import type { NativeCuedTrack, NativeGrid, NativeModule } from './audio/native' +import { nativeBuild, type NativeCuedTrack, type NativeGrid, type NativeModule } from './audio/native' +import { CueStyleCache } from './cueStyleCache' import type { Library } from './library' const CONCURRENCY = 3 @@ -29,6 +30,7 @@ const isOwn = (cue: DetailCue): boolean => cue.comment !== AUTO_CUE_COMMENT export class AutoCue { private progress: AutoCueProgress | null = null private queue: string[] = [] + private styles = new CueStyleCache() constructor( private library: Library, @@ -53,7 +55,10 @@ export class AutoCue { return path && detail.beatgrid?.times.length ? { path, detail } : null } - /** The style, as JSON, learnt from the DJ's own cues of `sort` on the palette's tracks. */ + /** + * The style, as JSON, learnt from the DJ's own cues of `sort` on the palette's tracks, or kept + * from the last time it was learnt from the same tracks, cues and learner. + */ private async learn(paletteIds: string[], sort: CueSort): Promise<string> { const tracks: NativeCuedTrack[] = [] for (const id of paletteIds) { @@ -65,7 +70,12 @@ export class AutoCue { if (cues.length) tracks.push({ path: found.path, grid: found.detail.beatgrid, cues }) } if (!tracks.length) throw new Error(`No track in the cue palette has ${sort} cues to learn from`) - return this.addon().learnCueStyle(tracks, sort === 'hot') + const learntFrom = CueStyleCache.fingerprint({ learner: nativeBuild(), tracks }) + const kept = this.styles.style(sort, learntFrom) + if (kept) return kept + const style = await this.addon().learnCueStyle(tracks, sort === 'hot') + this.styles.keep(sort, learntFrom, style) + return style } private async run({ trackIds, paletteIds, sort }: AutoCueRequest): Promise<void> { diff --git a/app/src/main/cueStyleCache.ts b/app/src/main/cueStyleCache.ts new file mode 100644 index 0000000..41ebc82 --- /dev/null +++ b/app/src/main/cueStyleCache.ts @@ -0,0 +1,58 @@ +import { app } from 'electron' +import { createHash } from 'crypto' +import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'fs' +import { dirname, join } from 'path' +import type { CueSort } from '../preload/autoCue' + +const FILE_NAME = 'cue-styles.json' + +interface Learnt { + learntFrom: string + style: string +} + +/** + * Learnt cue styles kept on disk, one per sort, each with a fingerprint of what it was learnt from, + * so a style is only learnt again once its palette, the cues on it or the learner change. + */ +export class CueStyleCache { + private loaded: Partial<Record<CueSort, Learnt>> | null = null + + private get path(): string { + return join(app.getPath('userData'), FILE_NAME) + } + + private get learnt(): Partial<Record<CueSort, Learnt>> { + this.loaded ??= this.read() + return this.loaded + } + + static fingerprint(learntFrom: unknown): string { + return createHash('sha256').update(JSON.stringify(learntFrom)).digest('hex') + } + + style(sort: CueSort, learntFrom: string): string | null { + const learnt = this.learnt[sort] + return learnt?.learntFrom === learntFrom ? learnt.style : null + } + + keep(sort: CueSort, learntFrom: string, style: string): void { + this.learnt[sort] = { learntFrom, style } + try { + mkdirSync(dirname(this.path), { recursive: true }) + const tmp = `${this.path}.${process.pid}.tmp` + writeFileSync(tmp, JSON.stringify(this.learnt)) + renameSync(tmp, this.path) + } catch (err) { + console.error('[cue styles] failed to write', err) + } + } + + private read(): Partial<Record<CueSort, Learnt>> { + try { + return JSON.parse(readFileSync(this.path, 'utf8')) as Partial<Record<CueSort, Learnt>> + } catch { + return {} + } + } +} diff --git a/native/crates/es-node/src/cue_style.rs b/native/crates/es-node/src/cue_style.rs index ce08117..114e79a 100644 --- a/native/crates/es-node/src/cue_style.rs +++ b/native/crates/es-node/src/cue_style.rs @@ -1,11 +1,14 @@ //! Learning a DJ's cue style from tracks they have cued, and placing cues with it, off the main //! thread. Sections are always found on the track's own grid, since that is what its cues sit on. +use std::collections::HashMap; use std::path::Path; +use std::sync::{LazyLock, Mutex, PoisonError}; +use std::time::SystemTime; use es_analyse::cue_style::{CueStyle, Learning, TrainingTrack}; -use es_analyse::structure::sections_on; -use es_analyse::{beat_of_cue, decode_mono, SAMPLE_RATE}; +use es_analyse::structure::{sections_on, Section}; +use es_analyse::{beat_of_cue, decode_mono, Beat, SAMPLE_RATE}; use napi::bindgen_prelude::*; use napi::{Env, Task}; use napi_derive::napi; @@ -36,13 +39,39 @@ pub struct PlacedCueJs { pub start_ms: u32, } +#[derive(PartialEq, Eq, Hash)] +struct TrackOnGrid { + path: String, + modified: Option<SystemTime>, + beats: Vec<(u8, u32)>, +} + +/// Sections found this session, so learning again after one palette track changes decodes only that +/// track. +static SECTIONS: LazyLock<Mutex<HashMap<TrackOnGrid, Vec<Section>>>> = LazyLock::new(Mutex::default); + +fn sections_of(path: &str, grid: &[Beat]) -> Result<Vec<Section>> { + let track = TrackOnGrid { + path: path.to_owned(), + modified: std::fs::metadata(path).and_then(|metadata| metadata.modified()).ok(), + beats: grid.iter().map(|beat| (beat.number, beat.time_ms)).collect(), + }; + let known = || SECTIONS.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(sections) = known().get(&track) { + return Ok(sections.clone()); + } + let sections = sections_on(&decode_mono(Path::new(path)).map_err(failure)?, f64::from(SAMPLE_RATE), grid); + known().insert(track, sections.clone()); + Ok(sections) +} + fn failure(error: impl std::fmt::Display) -> Error { Error::new(Status::GenericFailure, error.to_string()) } fn training_track(track: &CuedTrackJs) -> Option<TrainingTrack> { let grid = track.grid.beats(); - let mono = decode_mono(Path::new(&track.path)).ok()?; + let sections = sections_of(&track.path, &grid).ok()?; let cues = track .cues .iter() @@ -52,7 +81,7 @@ fn training_track(track: &CuedTrackJs) -> Option<TrainingTrack> { Some((pad, beat)) }) .collect(); - Some(TrainingTrack { sections: sections_on(&mono, f64::from(SAMPLE_RATE), &grid), beat_count: grid.len(), cues }) + Some(TrainingTrack { sections, beat_count: grid.len(), cues }) } pub struct LearnCueStyle { @@ -97,8 +126,7 @@ impl Task for PlaceCues { fn compute(&mut self) -> Result<Self::Output> { let style: CueStyle = serde_json::from_str(&self.style).map_err(failure)?; let grid = self.grid.beats(); - let mono = decode_mono(Path::new(&self.path)).map_err(failure)?; - let sections = sections_on(&mono, f64::from(SAMPLE_RATE), &grid); + let sections = sections_of(&self.path, &grid)?; Ok(style .place(§ions, grid.len()) .into_iter() From acedee4841b1ec3e9ee5f0bad2797447a7489a13 Mon Sep 17 00:00:00 2001 From: claw1200 <carstenwood12@gmail.com> Date: Sun, 29 Nov 2026 18:15:24 +0000 Subject: [PATCH 22/25] fix decks not picking up new cues after auto place --- .../renderer/src/lib/components/Inspector.svelte | 4 ++-- app/src/renderer/src/lib/deck/session.svelte.ts | 16 +++++++++++++++- app/src/renderer/src/lib/decks.svelte.ts | 4 +++- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/app/src/renderer/src/lib/components/Inspector.svelte b/app/src/renderer/src/lib/components/Inspector.svelte index 737cb26..35d422a 100644 --- a/app/src/renderer/src/lib/components/Inspector.svelte +++ b/app/src/renderer/src/lib/components/Inspector.svelte @@ -13,7 +13,7 @@ keyColor, TRACK_COLORS } from '$lib/format' - import { loadDetail } from '$lib/deck/session.svelte' + import { watchDetail } from '$lib/deck/session.svelte' import type { Cue, EditableField, Track, TrackDetail } from '$lib/types' import EditableText from './EditableText.svelte' import RatingStars from './RatingStars.svelte' @@ -38,7 +38,7 @@ ) const MAX_NUMBER = 9999 - const detailPromise = $derived(track && !loose ? loadDetail(track.id).then((d) => d.detail) : null) + const detailPromise = $derived(track && !loose ? watchDetail(track.id).then((d) => d.detail) : null) type Row = { label: string; value: string; field?: EditableField; numeric?: boolean } diff --git a/app/src/renderer/src/lib/deck/session.svelte.ts b/app/src/renderer/src/lib/deck/session.svelte.ts index a9bcdd3..9bcd108 100644 --- a/app/src/renderer/src/lib/deck/session.svelte.ts +++ b/app/src/renderer/src/lib/deck/session.svelte.ts @@ -15,10 +15,24 @@ export function loadDetail(id: string): Promise<DetailEntry> { return entry } +const forgotten = $state({ count: 0 }) + export function clearDetailCache(): void { detailCache.clear() } +/** Drops a track's cached detail after it changes in the library, so the next load reads it afresh. */ +export function forgetDetail(id: string): void { + detailCache.delete(id) + forgotten.count++ +} + +/** `loadDetail`, loaded again by a reactive reader whenever a track's detail is forgotten. */ +export function watchDetail(id: string): Promise<DetailEntry> { + void forgotten.count + return loadDetail(id) +} + /** The track on the deck and its library detail: cues, beatgrid and the analysed waveform. */ export class TrackSession { track = $state.raw<Track | null>(null) @@ -77,7 +91,7 @@ export class TrackSession { const id = this.track?.id if (!id || this.track?.collected === false) return const token = this.token - clearDetailCache() + forgetDetail(id) try { const { detail, waveform } = await loadDetail(id) if (token !== this.token || this.track?.id !== id) return diff --git a/app/src/renderer/src/lib/decks.svelte.ts b/app/src/renderer/src/lib/decks.svelte.ts index c4a22e3..9125a31 100644 --- a/app/src/renderer/src/lib/decks.svelte.ts +++ b/app/src/renderer/src/lib/decks.svelte.ts @@ -1,6 +1,7 @@ import { ENGINE_DECKS } from '../../../shared/engine' import { Audition } from './audition.svelte' import { Output } from './deck/output.svelte' +import { forgetDetail } from './deck/session.svelte' import { DeckPrefs } from './deck/prefs.svelte' import { pathKey } from './library/views' import { Listeners } from './listeners' @@ -70,8 +71,9 @@ export class Decks { return this.players.filter((player) => player.track?.id === trackId) } - /** Reloads the cues, grid and phrases of every deck holding the track, after they change elsewhere. */ + /** Reloads the cues, grid and phrases of the track, on every deck holding it and the next to load it. */ refreshTrack(trackId: string): void { + forgetDetail(trackId) for (const player of this.withTrack(trackId)) void player.refreshDetail() } From 1385242dc21485a9bf1e0607d72255c81435ea95 Mon Sep 17 00:00:00 2001 From: claw1200 <carstenwood12@gmail.com> Date: Sun, 29 Nov 2026 18:21:20 +0000 Subject: [PATCH 23/25] replace any cues when auto cueing --- app/src/main/audio/native.ts | 1 + app/src/main/autoCue.ts | 13 ++--- app/src/main/library.ts | 1 + app/src/preload/autoCue.d.ts | 3 -- app/src/preload/engine.ts | 1 + app/src/renderer/src/App.svelte | 19 ++++++- app/src/renderer/src/lib/api.ts | 1 + app/src/renderer/src/lib/autoCue.svelte.ts | 50 ++++++++++++++++--- .../src/lib/components/StatusBar.svelte | 4 +- .../src/lib/components/TrackTable.svelte | 2 +- app/src/shared/cues.ts | 3 ++ native/crates/es-engine/src/library.rs | 12 ++++- native/crates/es-node/src/library.rs | 8 +++ 13 files changed, 93 insertions(+), 25 deletions(-) diff --git a/app/src/main/audio/native.ts b/app/src/main/audio/native.ts index fdd2b86..aefa350 100644 --- a/app/src/main/audio/native.ts +++ b/app/src/main/audio/native.ts @@ -128,6 +128,7 @@ export interface NativeLibrary { playlistTracks(id: string): Promise<unknown> historyTracks(id: string): Promise<unknown> trackDetail(id: string): Promise<unknown> + trackCues(ids: string[]): Promise<unknown> mediaResolve(kind: string, id: string, size: string): Promise<unknown> cueSetHot(id: string, kind: number, ms: number, endMs: number | null): Promise<unknown> cueAddMemory(id: string, ms: number, endMs: number | null): Promise<unknown> diff --git a/app/src/main/autoCue.ts b/app/src/main/autoCue.ts index 880f8c6..91ce072 100644 --- a/app/src/main/autoCue.ts +++ b/app/src/main/autoCue.ts @@ -1,6 +1,6 @@ import { BrowserWindow, ipcMain } from 'electron' import type { AutoCueFinished, AutoCueProgress, AutoCueRequest, CueSort } from '../preload/autoCue' -import { AUTO_CUE_COMMENT } from '../shared/cues' +import { isOwnCue } from '../shared/cues' import { nativeBuild, type NativeCuedTrack, type NativeGrid, type NativeModule } from './audio/native' import { CueStyleCache } from './cueStyleCache' import type { Library } from './library' @@ -20,12 +20,11 @@ interface Detail { } const ofSort = (cue: DetailCue, sort: CueSort): boolean => cue.kind === sort -const isOwn = (cue: DetailCue): boolean => cue.comment !== AUTO_CUE_COMMENT /** * Learns a cue style from the palette's tracks, then places cues with it on other tracks a few at - * a time and writes them, marked automatic. Tracks that already have the DJ's own cues of the - * sort are left alone. Progress goes to every window on `autoCue:progress`. + * a time and writes them, marked automatic, in place of every cue of the sort they had. Progress + * goes to every window on `autoCue:progress`. */ export class AutoCue { private progress: AutoCueProgress | null = null @@ -65,7 +64,7 @@ export class AutoCue { const found = await this.source(id) if (!found?.detail.beatgrid) continue const cues = found.detail.cues - .filter((cue) => isOwn(cue) && ofSort(cue, sort)) + .filter((cue) => isOwnCue(cue) && ofSort(cue, sort)) .map((cue) => ({ kind: cue.slot, startMs: cue.start })) if (cues.length) tracks.push({ path: found.path, grid: found.detail.beatgrid, cues }) } @@ -80,7 +79,7 @@ export class AutoCue { private async run({ trackIds, paletteIds, sort }: AutoCueRequest): Promise<void> { if (this.progress) throw new Error('Auto cue is already running') - this.progress = { learning: true, total: trackIds.length, done: 0, skipped: 0, failed: 0 } + this.progress = { learning: true, total: trackIds.length, done: 0, failed: 0 } this.broadcast() let style: string try { @@ -108,7 +107,6 @@ export class AutoCue { try { const found = await this.source(id) if (!found?.detail.beatgrid) return { id, error: 'No beatgrid or audio file; analyse the track first' } - if (found.detail.cues.some((cue) => isOwn(cue) && ofSort(cue, sort))) return { id, skipped: true } const placed = await this.addon().placeCues(found.path, found.detail.beatgrid, style) const cues = await this.library.call<unknown[]>('cue.placeAuto', { id, @@ -127,7 +125,6 @@ export class AutoCue { this.progress = { ...this.progress, done: this.progress.done + (finished.cues ? 1 : 0), - skipped: this.progress.skipped + (finished.skipped ? 1 : 0), failed: this.progress.failed + (finished.error ? 1 : 0) } this.broadcast(finished) diff --git a/app/src/main/library.ts b/app/src/main/library.ts index b6deac6..615b067 100644 --- a/app/src/main/library.ts +++ b/app/src/main/library.ts @@ -30,6 +30,7 @@ const READS: CommandHandlers = { } return lib.mediaResolve(text(p?.kind), text(p?.id), text(p?.size)) }, + 'track.cues': (lib, p) => lib.trackCues(list(p?.ids)), 'track.previews': (lib, p) => lib.trackPreviews(list(p?.ids)), 'files.read': (lib, p) => lib.filesRead(list(p?.paths)), 'track.findMissing': (lib, p) => lib.trackFindMissing(list(p?.ids), text(p?.directory)), diff --git a/app/src/preload/autoCue.d.ts b/app/src/preload/autoCue.d.ts index e08bff6..30e49e1 100644 --- a/app/src/preload/autoCue.d.ts +++ b/app/src/preload/autoCue.d.ts @@ -62,8 +62,6 @@ export interface AutoCueFinished { id: string /** The track's cues after the automatic ones were written. */ cues?: unknown[] - /** Left alone because it already has the DJ's own cues of this sort. */ - skipped?: boolean error?: string } @@ -72,7 +70,6 @@ export interface AutoCueProgress { learning: boolean total: number done: number - skipped: number failed: number finished?: AutoCueFinished /** Set once, when learning fails and nothing is cued. */ diff --git a/app/src/preload/engine.ts b/app/src/preload/engine.ts index 2122cde..8887b27 100644 --- a/app/src/preload/engine.ts +++ b/app/src/preload/engine.ts @@ -110,6 +110,7 @@ export interface EngineCommandParams { 'playlist.tracks': { id: string } 'history.tracks': { id: string } 'track.detail': { id: string } + 'track.cues': { ids: string[] } 'media.resolve': { kind: string; id: string; size?: string } 'track.previews': { ids: string[] } 'files.read': { paths: string[] } diff --git a/app/src/renderer/src/App.svelte b/app/src/renderer/src/App.svelte index 49e3b6b..a05d86e 100644 --- a/app/src/renderer/src/App.svelte +++ b/app/src/renderer/src/App.svelte @@ -21,6 +21,7 @@ import RemoveDialog from '$lib/components/RemoveDialog.svelte' import ConvertDialog from '$lib/components/ConvertDialog.svelte' import AnalysisDialog from '$lib/components/AnalysisDialog.svelte' + import ConfirmDialog from '$lib/components/ConfirmDialog.svelte' import type { AnalysisSettings } from '$lib/analysis.svelte' import type { SettingsSection } from '$lib/components/settings/sections' @@ -58,11 +59,10 @@ browserPreviews.noteCues(id, cues as Cue[]) decks.refreshTrack(id) }) - autoCue.onBatchDone(({ done, skipped, failed, error }) => { + autoCue.onBatchDone(({ done, failed, error }) => { if (error) return library.notify(error, 'error') const tracks = (count: number): string => (count === 1 ? 'one track' : `${count} tracks`) const parts = [`Auto cued ${tracks(done)}`] - if (skipped) parts.push(`left ${tracks(skipped)} with your own cues alone`) if (failed) parts.push(`couldn’t cue ${tracks(failed)}`) library.notify(parts.join(', '), failed ? 'warning' : 'info') }) @@ -293,4 +293,19 @@ onclose={() => (analysing = null)} /> {/if} + {#if autoCue.replacing} + {@const { request, ownCued } = autoCue.replacing} + {@const cues = `${request.sort} cues`} + {@const total = request.trackIds.length} + <ConfirmDialog + title={`Replace ${cues}`} + message={`Auto cue replaces every one of a track’s ${cues}. ${ + total === 1 ? 'This track has' : `${ownCued} of these ${total} tracks have` + } ${cues} you placed, which will be deleted. This can’t be undone.`} + confirmLabel={`Replace ${cues}`} + danger + onconfirm={() => autoCue.confirm()} + onclose={() => autoCue.dismiss()} + /> + {/if} </div> diff --git a/app/src/renderer/src/lib/api.ts b/app/src/renderer/src/lib/api.ts index 7f0ad47..8b39196 100644 --- a/app/src/renderer/src/lib/api.ts +++ b/app/src/renderer/src/lib/api.ts @@ -48,6 +48,7 @@ export const api = { playlistTracks: (id: string) => call<string[]>('playlist.tracks', { id }), historyTracks: (id: string) => call<string[]>('history.tracks', { id }), trackDetail: (id: string) => call<TrackDetail>('track.detail', { id }), + trackCues: (ids: string[]) => call<TrackCues[]>('track.cues', { ids }), trackPreviews: (ids: string[]) => call<TrackPreview[]>('track.previews', { ids }), setHotCue: (id: string, kind: number, ms: number, endMs: number | null = null) => call<Cue[]>('cue.setHot', { id, kind, ms, endMs }), diff --git a/app/src/renderer/src/lib/autoCue.svelte.ts b/app/src/renderer/src/lib/autoCue.svelte.ts index 47c0040..0bb12a8 100644 --- a/app/src/renderer/src/lib/autoCue.svelte.ts +++ b/app/src/renderer/src/lib/autoCue.svelte.ts @@ -1,15 +1,24 @@ -import type { AutoCueFinished, AutoCueProgress, CueSort } from '../../../preload/autoCue' +import type { AutoCueFinished, AutoCueProgress, AutoCueRequest, CueSort } from '../../../preload/autoCue' +import { isOwnCue } from '../../../shared/cues' +import { api } from './api' import type { Library } from './library.svelte' import { ipcErrorMessage } from './ipcError' import { Listeners } from './listeners' import type { Track } from './types' import { isDeviceTrack } from './trackIds' -const settled = (progress: AutoCueProgress): number => progress.done + progress.skipped + progress.failed +const settled = (progress: AutoCueProgress): number => progress.done + progress.failed + +/** A run waiting on the DJ to agree to lose the cues they placed on some of its tracks. */ +export interface AutoCueReplacing { + request: AutoCueRequest + ownCued: number +} /** Auto cue runs started from the library, and their progress in the main process. */ export class AutoCue { progress = $state.raw<AutoCueProgress | null>(null) + replacing = $state.raw<AutoCueReplacing | null>(null) running = $derived( !!this.progress && !this.progress.error && (this.progress.learning || settled(this.progress) < this.progress.total) ) @@ -24,6 +33,10 @@ export class AutoCue { }) } + get settled(): number { + return this.progress ? settled(this.progress) : 0 + } + onFinished(listener: (finished: AutoCueFinished) => void): () => void { return this.finished.add(listener) } @@ -32,17 +45,40 @@ export class AutoCue { return this.batchDone.add(listener) } - /** Learns from the cue palette and cues `tracks`, telling the user why when it can't start. */ - run(tracks: Track[], sort: CueSort): void { + /** + * Learns from the cue palette and cues `tracks`, telling the user why when it can't start. When + * some of them carry cues of the sort the DJ placed, it waits in `replacing` until `confirm`. + */ + async run(tracks: Track[], sort: CueSort): Promise<void> { const trackIds = tracks.filter((t) => t.collected !== false && !isDeviceTrack(t.id)).map((t) => t.id) const paletteIds = this.library.cuePalette.ids if (!trackIds.length) return if (!this.library.writable) return this.library.notify('Unlock editing to auto cue tracks') if (!paletteIds.length) return this.library.notify('Add tracks you have cued to the cue palette first') if (this.running) return this.library.notify('Auto cue is already running') - window.api - .autoCue({ trackIds, paletteIds, sort }) - .catch((err) => this.library.notify(ipcErrorMessage(err), 'error')) + const request = { trackIds, paletteIds, sort } + try { + const ownCued = (await api.trackCues(trackIds)).filter(({ cues }) => + cues.some((cue) => cue.kind === sort && isOwnCue(cue)) + ).length + if (ownCued) this.replacing = { request, ownCued } + else this.start(request) + } catch (err) { + this.library.notify(ipcErrorMessage(err), 'error') + } + } + + confirm(): void { + if (this.replacing) this.start(this.replacing.request) + this.replacing = null + } + + dismiss(): void { + this.replacing = null + } + + private start(request: AutoCueRequest): void { + window.api.autoCue(request).catch((err) => this.library.notify(ipcErrorMessage(err), 'error')) } cancel(): void { diff --git a/app/src/renderer/src/lib/components/StatusBar.svelte b/app/src/renderer/src/lib/components/StatusBar.svelte index 43e83dd..4ff466b 100644 --- a/app/src/renderer/src/lib/components/StatusBar.svelte +++ b/app/src/renderer/src/lib/components/StatusBar.svelte @@ -175,8 +175,8 @@ {/if} {#if autoCue.running && autoCue.progress} - {@const { learning, total, done, skipped, failed } = autoCue.progress} - {@const settled = done + skipped + failed} + {@const { learning, total } = autoCue.progress} + {@const settled = autoCue.settled} {@render task( learning ? 'Learning your cue style' diff --git a/app/src/renderer/src/lib/components/TrackTable.svelte b/app/src/renderer/src/lib/components/TrackTable.svelte index 08e4cbf..73e3aef 100644 --- a/app/src/renderer/src/lib/components/TrackTable.svelte +++ b/app/src/renderer/src/lib/components/TrackTable.svelte @@ -444,7 +444,7 @@ autoRelocate: onautorelocate, remove: onremove, analyse: onanalyse, - autoCue: (tracks, sort) => autoCue.run(tracks, sort), + autoCue: (tracks, sort) => void autoCue.run(tracks, sort), clearCues: (tracks, sorts) => (clearingCues = { tracks, sorts }), convert: onconvert, exportZip, diff --git a/app/src/shared/cues.ts b/app/src/shared/cues.ts index 3402a04..2025e6e 100644 --- a/app/src/shared/cues.ts +++ b/app/src/shared/cues.ts @@ -1,2 +1,5 @@ /** The comment the engine gives cues it places automatically; rb-library's `AUTO_CUE_COMMENT`. */ export const AUTO_CUE_COMMENT = 'Auto cue' + +/** A cue the DJ placed, rather than auto cue. */ +export const isOwnCue = (cue: { comment: string }): boolean => cue.comment !== AUTO_CUE_COMMENT diff --git a/native/crates/es-engine/src/library.rs b/native/crates/es-engine/src/library.rs index 03415f6..a6c5f45 100644 --- a/native/crates/es-engine/src/library.rs +++ b/native/crates/es-engine/src/library.rs @@ -471,14 +471,18 @@ impl LibraryService { self.cues(id) } - /// Replace the track's automatic memory or hot cues with `cues`, leaving the DJ's own. + /// Replace every one of the track's memory cues, or hot cues with `hot`, with automatic `cues`. pub fn cue_place_auto( &mut self, id: &str, hot: bool, cues: &[rb_library::AutoCue], ) -> Result<Vec<es_index::detail::Cue>> { - self.edit(|tx| tx.replace_auto_cues(id, hot, cues))?; + let sort = if hot { rb_library::CueSort::Hot } else { rb_library::CueSort::Memory }; + self.edit(|tx| { + tx.clear_cues(id, sort)?; + tx.replace_auto_cues(id, hot, cues) + })?; self.cues(id) } @@ -491,6 +495,10 @@ impl LibraryService { } Ok(()) })?; + self.track_cues(ids) + } + + pub fn track_cues(&self, ids: &[String]) -> Result<Vec<TrackCues>> { ids.iter().map(|id| Ok(TrackCues { id: id.clone(), cues: self.cues(id)? })).collect() } diff --git a/native/crates/es-node/src/library.rs b/native/crates/es-node/src/library.rs index 6828f53..979a80f 100644 --- a/native/crates/es-node/src/library.rs +++ b/native/crates/es-node/src/library.rs @@ -180,6 +180,7 @@ enum Op { PlaylistTracks(String), HistoryTracks(String), TrackDetail(String), + TrackCues(Vec<String>), TrackPreviews(Vec<String>), TrackRelocate(String), TrackFindMissing(Vec<String>, String), @@ -244,6 +245,7 @@ impl Run { Op::CueDelete(_, _) => "cue.delete", Op::CueSetColor(_, _, _) => "cue.setColor", Op::TrackDetail(_) => "track.detail", + Op::TrackCues(_) => "track.cues", Op::SetPhrases(..) => "track.setPhrases", Op::TrackPreviews(_) => "track.previews", Op::Usb(UsbOp::List) => "usb.list", @@ -331,6 +333,7 @@ impl Run { Op::PlaylistTracks(id) => return json_of(&service.playlist_tracks(id).map_err(failure)?), Op::HistoryTracks(id) => return json_of(&service.history_tracks(id).map_err(failure)?), Op::TrackDetail(id) => return json_of(&service.track_detail(id).map_err(failure)?), + Op::TrackCues(ids) => return json_of(&service.track_cues(ids).map_err(failure)?), Op::TrackPreviews(ids) => { let (device, own): (Vec<String>, Vec<String>) = ids.iter().cloned().partition(|id| id.starts_with("usb:")); @@ -658,6 +661,11 @@ impl RekordboxLibrary { self.run(Op::TrackDetail(id)) } + #[napi(ts_return_type = "Promise<unknown>")] + pub fn track_cues(&self, ids: Vec<String>) -> AsyncTask<Run> { + self.run(Op::TrackCues(ids)) + } + #[napi(ts_return_type = "Promise<unknown>")] pub fn track_previews(&self, ids: Vec<String>) -> AsyncTask<Run> { self.run(Op::TrackPreviews(ids)) From 80045b975b0ddd565e49c17e82b5427a2984c456 Mon Sep 17 00:00:00 2001 From: claw1200 <carstenwood12@gmail.com> Date: Sun, 29 Nov 2026 18:35:52 +0000 Subject: [PATCH 24/25] improve cue pallet dialog --- app/src/preload/autoCue.d.ts | 6 +- .../src/lib/components/CueStyleDialog.svelte | 71 +++++++++--- app/src/renderer/src/lib/cueStyle.ts | 107 +++++++++++++----- app/tests/cueStyle.test.ts | 54 +++++---- 4 files changed, 170 insertions(+), 68 deletions(-) diff --git a/app/src/preload/autoCue.d.ts b/app/src/preload/autoCue.d.ts index 30e49e1..34daa0d 100644 --- a/app/src/preload/autoCue.d.ts +++ b/app/src/preload/autoCue.d.ts @@ -55,8 +55,12 @@ export interface MemoryCueStyle { closestCues: number } +export interface HotCueStyle { + pads: [number, LearntRule][] +} + /** A style as the native learner writes it: section starts for memory cues, or one rule per hot cue pad. */ -export type CueStyle = ({ cues: 'memory' } & MemoryCueStyle) | { cues: 'hot'; pads: [number, LearntRule][] } +export type CueStyle = ({ cues: 'memory' } & MemoryCueStyle) | ({ cues: 'hot' } & HotCueStyle) export interface AutoCueFinished { id: string diff --git a/app/src/renderer/src/lib/components/CueStyleDialog.svelte b/app/src/renderer/src/lib/components/CueStyleDialog.svelte index 99f827d..2f9e9f9 100644 --- a/app/src/renderer/src/lib/components/CueStyleDialog.svelte +++ b/app/src/renderer/src/lib/components/CueStyleDialog.svelte @@ -1,6 +1,6 @@ <script lang="ts"> import { getApp } from '$lib/context' - import { styleRows } from '$lib/cueStyle' + import { memorySummary, padRules, type MemorySummary, type PadRule } from '$lib/cueStyle' import { ipcErrorMessage } from '$lib/ipcError' import { suspendModal } from '$lib/modal' import type { CueSort, CueStyle } from '../../../../preload/autoCue' @@ -28,28 +28,19 @@ > <form method="dialog" class="p-5"> <h2 class="text-[13.5px] font-semibold">What the cue palette teaches</h2> - <p class="mt-1.5 text-[12.5px] leading-relaxed text-muted"> - Learnt from the cues you placed yourself on the palette’s {paletteIds.length} - {paletteIds.length === 1 ? 'track' : 'tracks'}. Memory cues go on the section starts you cue most often, likeliest - first; hot cues follow one rule per pad. + <p class="mt-1 text-[12px] text-muted"> + From your own cues on {paletteIds.length} + {paletteIds.length === 1 ? 'track' : 'tracks'}. Shows only what auto cue uses, and how often you cue it. </p> {#each styles as style (style.title)} - <h3 class="mt-4 mb-1 text-[10.5px] font-semibold tracking-wider text-faint uppercase">{style.title}</h3> + <h3 class="mt-4 mb-1.5 text-[10.5px] font-semibold tracking-wider text-faint uppercase">{style.title}</h3> {#await style.learnt} <p class="text-[12px] text-faint">Learning…</p> {:then learnt} - {@const rows = styleRows(learnt)} - {#if rows.length} - <ul class="space-y-1"> - {#each rows as row (row.label)} - <li class="flex items-baseline gap-3 text-[12.5px]"> - <span class="flex-1">{row.label}</span> - <span class="tabular shrink-0 text-[11px] text-faint">{row.tally}</span> - </li> - {/each} - </ul> + {#if learnt.cues === 'memory'} + {@render memory(memorySummary(learnt))} {:else} - <p class="text-[12px] text-faint">No habit shows up often enough to learn.</p> + {@render pads(padRules(learnt))} {/if} {:catch error} <p class="text-[12px] text-faint">{ipcErrorMessage(error)}</p> @@ -62,3 +53,49 @@ </div> </form> </dialog> + +{#snippet nothingLearnt()} + <p class="text-[12px] text-faint">No habit shows up often enough to learn.</p> +{/snippet} + +{#snippet percentOf(value: number)} + <span class="tabular text-faint">{value}%</span> +{/snippet} + +{#snippet memory(summary: MemorySummary)} + {#if summary.cued.length} + <div class="grid grid-cols-[auto_1fr] items-baseline gap-x-3 gap-y-1.5"> + {#each summary.cued as { kind, places } (kind)} + <span class="text-[12.5px] font-medium capitalize">{kind}</span> + <div class="flex flex-wrap gap-1"> + {#each places as place (place.label)} + <span class="rounded-md bg-raised px-1.5 py-0.5 text-[11.5px]" + >{place.label} {@render percentOf(place.percent)}</span + > + {/each} + </div> + {/each} + </div> + <p class="mt-2 text-[11px] text-faint"> + Only places you cue {summary.leastPercent}% of the time or more, and never within {summary.barsApart} bars of another + cue. + {#if summary.notCued.length}Never cues a {summary.notCued.join(' or ')}.{/if} + </p> + {:else} + {@render nothingLearnt()} + {/if} +{/snippet} + +{#snippet pads(rules: PadRule[])} + {#if rules.length} + <div class="grid grid-cols-[auto_1fr_auto] items-baseline gap-x-3 gap-y-1 text-[12.5px]"> + {#each rules as { pad, rule, percent } (pad)} + <span class="rounded bg-raised px-1.5 text-[11px] font-semibold">{pad}</span> + <span>{rule}</span> + <span class="text-[11px]">{@render percentOf(percent)}</span> + {/each} + </div> + {:else} + {@render nothingLearnt()} + {/if} +{/snippet} diff --git a/app/src/renderer/src/lib/cueStyle.ts b/app/src/renderer/src/lib/cueStyle.ts index 506f452..3571a48 100644 --- a/app/src/renderer/src/lib/cueStyle.ts +++ b/app/src/renderer/src/lib/cueStyle.ts @@ -1,4 +1,13 @@ -import type { CueRule, CueStyle, LearntStart, SectionStart } from '../../../preload/autoCue' +import type { + CueRule, + HotCueStyle, + LearntRule, + LearntStart, + MemoryCueStyle, + SectionKind, + SectionStart +} from '../../../preload/autoCue' +import { BEATS_PER_BAR } from './beat' import { hotCueLetter } from './format' const ORDINALS = ['first', 'second', 'third', 'fourth'] @@ -35,46 +44,84 @@ export function describeRule(rule: CueRule): string { const carriesOn = (start: SectionStart): boolean => typeof start.after === 'object' && start.after !== null && start.after.section === start.kind -const withArticle = (noun: string): string => `${/^[aeiou]/.test(noun) ? 'an' : 'a'} ${noun}` - function precedingName(start: SectionStart): string { - if (start.after === null) return '' - if (start.after === 'trackStart') return ' opening the track' - return ` after ${withArticle(start.after.section)}` + if (start.after === 'trackStart') return 'opening' + return start.after ? `after ${start.after.section}` : 'anywhere' } function standingName(start: SectionStart): string { - if (start.standsOut === null) return '' - if (carriesOn(start)) return start.standsOut ? ', after a long run of it' : ', early in a run of it' - return start.standsOut ? ', where the music changes more than usual' : ', where the music changes less than usual' + if (carriesOn(start)) return start.standsOut ? 'long run' : 'short run' + return start.standsOut ? 'big change' : 'small change' } -/** A sort of section start in words, such as "A drop after a build, where the music changes more than usual". */ -export function describeStart(start: SectionStart): string { - const named = withArticle(start.kind ?? 'section') + precedingName(start) + standingName(start) - return named[0].toUpperCase() + named.slice(1) +const percent = (share: number): number => Math.round(share * 100) + +export interface CuedPlace { + /** Such as "after build" or "after drop · long run". */ + label: string + percent: number } -const isNarrowest = ({ start }: LearntStart): boolean => - start.kind !== null && start.after !== null && start.standsOut !== null +export interface CuedKind { + kind: SectionKind + places: CuedPlace[] +} -export interface StyleRow { - label: string - tally: string +export interface MemorySummary { + /** Likeliest first. */ + cued: CuedKind[] + notCued: SectionKind[] + leastPercent: number + barsApart: number } -/** A learnt style as lines to read: for memory cues the section starts it cues, for hot cues each pad. */ -export function styleRows(style: CueStyle): StyleRow[] { - if (style.cues === 'memory') { - return style.starts - .filter((learnt) => isNarrowest(learnt) && learnt.likelihood >= style.cueLine) - .map(({ start, cued, seen, likelihood }) => ({ - label: describeStart(start), - tally: `${Math.round(likelihood * 100)}%, ${cued} of ${seen}` - })) +/** + * The section starts a memory style cues, by kind. A start cued however much the music changes + * there reads as one place, at its own likelihood. + */ +export function memorySummary(style: MemoryCueStyle): MemorySummary { + const used = style.starts.filter( + ({ start, likelihood }) => + start.kind !== null && start.after !== null && start.standsOut !== null && likelihood >= style.cueLine + ) + const sameStart = (a: SectionStart, b: SectionStart): boolean => + a.kind === b.kind && JSON.stringify(a.after) === JSON.stringify(b.after) + const placeOf = ({ start, likelihood }: LearntStart): CuedPlace => { + const either = used.filter((other) => sameStart(other.start, start)).length > 1 + if (!either) return { label: `${precedingName(start)} · ${standingName(start)}`, percent: percent(likelihood) } + const unmarked = style.starts.find((other) => other.start.standsOut === null && sameStart(other.start, start)) + return { label: precedingName(start), percent: percent(unmarked?.likelihood ?? likelihood) } + } + const byKind = new Map<SectionKind, CuedPlace[]>() + for (const learnt of used) { + const kind = learnt.start.kind as SectionKind + const places = byKind.get(kind) ?? [] + const place = placeOf(learnt) + if (!places.some((other) => other.label === place.label)) places.push(place) + byKind.set(kind, places) } - return style.pads.map(([slot, { rule, cuesFound, cuesMisplaced }]) => ({ - label: `Pad ${hotCueLetter(slot)}: ${describeRule(rule)}`, - tally: `right ${cuesFound}, wrong ${cuesMisplaced}` + const seen = new Set(style.starts.flatMap(({ start }) => (start.kind ? [start.kind] : []))) + return { + cued: [...byKind].map(([kind, places]) => ({ kind, places: places.sort((a, b) => b.percent - a.percent) })), + notCued: [...seen].filter((kind) => !byKind.has(kind)), + leastPercent: percent(style.cueLine), + barsApart: style.closestCues / BEATS_PER_BAR + } +} + +export interface PadRule { + pad: string + rule: string + percent: number +} + +const precision = ({ cuesFound, cuesMisplaced }: LearntRule): number => + cuesFound / Math.max(1, cuesFound + cuesMisplaced) + +export function padRules(style: HotCueStyle): PadRule[] { + return style.pads.map(([slot, learnt]) => ({ + pad: hotCueLetter(slot), + rule: describeRule(learnt.rule), + percent: percent(precision(learnt)) })) } diff --git a/app/tests/cueStyle.test.ts b/app/tests/cueStyle.test.ts index 239b3b1..2a93dc5 100644 --- a/app/tests/cueStyle.test.ts +++ b/app/tests/cueStyle.test.ts @@ -4,7 +4,7 @@ import { describe, it } from 'node:test' register(new URL('./resolve-ts.mjs', import.meta.url).href) -const { describeRule, describeStart } = await import('../src/renderer/src/lib/cueStyle.ts') +const { describeRule, memorySummary } = await import('../src/renderer/src/lib/cueStyle.ts') type CueRule = import('../src/preload/autoCue').CueRule type SectionStart = import('../src/preload/autoCue').SectionStart @@ -45,28 +45,42 @@ describe('describeRule', () => { }) }) -describe('describeStart', () => { - const start = (fields: Partial<SectionStart>): SectionStart => ({ - kind: 'drop', - after: { section: 'build' }, - standsOut: null, - ...fields +describe('memorySummary', () => { + type LearntStart = import('../src/preload/autoCue').LearntStart + const learnt = (start: Partial<SectionStart>, likelihood: number): LearntStart => ({ + start: { kind: 'drop', after: { section: 'build' }, standsOut: null, ...start }, + cued: 0, + seen: 0, + likelihood + }) + const summary = memorySummary({ + cueLine: 0.4, + closestCues: 32, + starts: [ + learnt({}, 0.77), + learnt({ standsOut: true }, 0.82), + learnt({ standsOut: false }, 0.59), + learnt({ after: { section: 'drop' }, standsOut: true }, 0.57), + learnt({ after: { section: 'drop' }, standsOut: false }, 0.27), + learnt({ kind: 'build', after: { section: 'breakdown' }, standsOut: false }, 0.1) + ] }) - it('names the kind and what comes before it', () => { - assert.equal(describeStart(start({})), 'A drop after a build') - assert.equal(describeStart(start({ kind: 'intro', after: 'trackStart' })), 'An intro opening the track') - assert.equal(describeStart(start({ kind: null, after: null })), 'A section') + it('shows only the starts it cues, by kind', () => { + assert.deepEqual(summary.cued, [ + { + kind: 'drop', + places: [ + { label: 'after build', percent: 77 }, + { label: 'after drop · long run', percent: 57 } + ] + } + ]) + assert.deepEqual(summary.notCued, ['build']) }) - it('says how a start stands out', () => { - assert.equal( - describeStart(start({ standsOut: true })), - 'A drop after a build, where the music changes more than usual' - ) - assert.equal( - describeStart(start({ after: { section: 'drop' }, standsOut: true })), - 'A drop after a drop, after a long run of it' - ) + it('gives the line and spacing it cues by', () => { + assert.equal(summary.leastPercent, 40) + assert.equal(summary.barsApart, 8) }) }) From 3bf1a2cb78b9574111ca2940abecb860eb6e82a6 Mon Sep 17 00:00:00 2001 From: claw1200 <carstenwood12@gmail.com> Date: Sun, 29 Nov 2026 21:10:40 +0000 Subject: [PATCH 25/25] group cue options and remove playlists context options --- .../src/lib/components/Sidebar.svelte | 19 +----- app/src/renderer/src/lib/cueMenu.ts | 68 +++++++++++-------- app/src/renderer/src/lib/library.svelte.ts | 7 -- app/src/renderer/src/lib/menu.ts | 2 + app/src/renderer/src/lib/trackMenu.ts | 14 ++-- 5 files changed, 50 insertions(+), 60 deletions(-) diff --git a/app/src/renderer/src/lib/components/Sidebar.svelte b/app/src/renderer/src/lib/components/Sidebar.svelte index 198eb10..cd782ba 100644 --- a/app/src/renderer/src/lib/components/Sidebar.svelte +++ b/app/src/renderer/src/lib/components/Sidebar.svelte @@ -4,7 +4,6 @@ import { Library as LibraryIcon, Bookmark, - BookmarkPlus, ListMusic, ListPlus, Folder, @@ -28,13 +27,12 @@ Settings2, LoaderCircle } from '@lucide/svelte' - import { autoCueEntry } from '$lib/cueMenu' import { getApp } from '$lib/context' import { droppedPaths, isFileDrag } from '$lib/library/drop' import { PLAYLIST_TREE_DRAG_TYPE } from '$lib/library.svelte' import { buildTree, type TreeNode } from '$lib/library/tree' - import { menuAt, tidy, type MenuEntry, type MenuRequest } from '$lib/menu' - import { exportZipEntry, membershipIcon, SEPARATOR, unlockEntry } from '$lib/trackMenu' + import { menuAt, SEPARATOR, tidy, type MenuEntry, type MenuRequest } from '$lib/menu' + import { exportZipEntry, membershipIcon, unlockEntry } from '$lib/trackMenu' import type { Source, View, Volume } from '$lib/types' import ConfirmDialog from './ConfirmDialog.svelte' import ContextMenu from './ContextMenu.svelte' @@ -46,7 +44,7 @@ let { onsource }: { onsource?: () => void } = $props() - const { library, decks, audition, autoCue } = getApp() + const { library, decks, audition } = getApp() let showingCueStyle = $state(false) let ejectingId = $state<string | null>(null) @@ -366,17 +364,6 @@ }, exportZipEntry(library, () => void library.exportPlaylistZip(node)), SEPARATOR, - { - label: 'Add tracks to cue palette', - icon: BookmarkPlus, - onselect: () => - void library.playlistNodeTracks(node).then((tracks) => library.cuePalette.add(tracks.map((t) => t.id))) - }, - autoCueEntry( - locked, - (sort) => void library.playlistNodeTracks(node).then((tracks) => autoCue.run(tracks, sort)) - ), - SEPARATOR, { label: 'Rename', icon: Pencil, disabled: locked, onselect: () => (library.renamingId = node.id) }, { label: 'Delete', icon: Trash2, danger: true, disabled: locked, onselect: () => (deleting = node) }, locked && SEPARATOR, diff --git a/app/src/renderer/src/lib/cueMenu.ts b/app/src/renderer/src/lib/cueMenu.ts index ee0920f..7a62d81 100644 --- a/app/src/renderer/src/lib/cueMenu.ts +++ b/app/src/renderer/src/lib/cueMenu.ts @@ -1,44 +1,52 @@ -import { BookmarkMinus, BookmarkPlus, Eraser, WandSparkles } from '@lucide/svelte' +import { BookmarkMinus, BookmarkPlus, Eraser, Flag, WandSparkles } from '@lucide/svelte' import type { CueSort } from '../../../preload/autoCue' import type { CuePalette } from './cuePalette.svelte' -import type { MenuEntry } from './menu' - -/** "Auto cue" with a choice of memory or hot cues, for tracks, selections and playlists alike. */ -export function autoCueEntry(locked: boolean, run: (sort: CueSort) => void): MenuEntry { - return { - label: 'Auto cue', - icon: WandSparkles, - disabled: locked, - items: [ - { label: 'Memory cues', onselect: () => run('memory') }, - { label: 'Hot cues', onselect: () => run('hot') } - ] - } -} +import { SEPARATOR, type MenuEntry } from './menu' /** Which cues a clear takes, in words: "memory cues", "hot cues", or both. */ export function cueSortsName(sorts: CueSort[]): string { return sorts.length > 1 ? 'memory and hot cues' : `${sorts[0]} cues` } -/** "Clear cues" with a choice of memory cues, hot cues or both. */ -export function clearCuesEntry(locked: boolean, clear: (sorts: CueSort[]) => void): MenuEntry { - const choices: CueSort[][] = [['memory'], ['hot'], ['memory', 'hot']] - return { - label: 'Clear cues', - icon: Eraser, - disabled: locked, - items: choices.map((sorts) => { - const name = cueSortsName(sorts) - return { label: `${name[0].toUpperCase()}${name.slice(1)}…`, danger: true, onselect: () => clear(sorts) } - }) - } -} - /** Adds the tracks to the cue palette, or takes them out when every one is already in it. */ -export function cuePaletteEntry(palette: CuePalette, ids: string[]): MenuEntry { +function cuePaletteEntry(palette: CuePalette, ids: string[]): MenuEntry { const allIn = ids.length > 0 && ids.every((id) => palette.has(id)) return allIn ? { label: 'Remove from cue palette', icon: BookmarkMinus, onselect: () => palette.remove(ids) } : { label: 'Add to cue palette', icon: BookmarkPlus, onselect: () => palette.add(ids) } } + +export interface CueActions { + autoCue: (sort: CueSort) => void + clear: (sorts: CueSort[]) => void +} + +/** "Cues": auto cue, the cue palette and clearing, for tracks and selections. */ +export function cuesEntry(locked: boolean, palette: CuePalette, ids: string[], actions: CueActions): MenuEntry { + const autoCue = (sort: CueSort): MenuEntry => ({ + label: `Auto cue ${sort} cues`, + icon: WandSparkles, + disabled: locked, + onselect: () => actions.autoCue(sort) + }) + const clearChoices: CueSort[][] = [['memory'], ['hot'], ['memory', 'hot']] + const clear = (sorts: CueSort[]): MenuEntry => ({ + label: `Clear ${cueSortsName(sorts)}…`, + icon: Eraser, + danger: true, + disabled: locked, + onselect: () => actions.clear(sorts) + }) + return { + label: 'Cues', + icon: Flag, + items: [ + autoCue('memory'), + autoCue('hot'), + SEPARATOR, + cuePaletteEntry(palette, ids), + SEPARATOR, + ...clearChoices.map(clear) + ] + } +} diff --git a/app/src/renderer/src/lib/library.svelte.ts b/app/src/renderer/src/lib/library.svelte.ts index d918e05..32d379f 100644 --- a/app/src/renderer/src/lib/library.svelte.ts +++ b/app/src/renderer/src/lib/library.svelte.ts @@ -777,13 +777,6 @@ export class Library { .map((track) => ({ path: track.path, folders })) } - /** Every track in a playlist, or in the playlists under a folder, once each. */ - async playlistNodeTracks(node: TreeNode): Promise<Track[]> { - if (node.kind !== 'folder') return this.tracksOf(await api.playlistTracks(node.id)) - const nested = await Promise.all(node.children.map((child) => this.playlistNodeTracks(child))) - return [...new Map(nested.flat().map((track) => [track.id, track])).values()] - } - private async playlistZipSources(node: TreeNode, folders: string[]): Promise<ZipSource[]> { if (node.kind !== 'folder') { const ids = await api.playlistTracks(node.id) diff --git a/app/src/renderer/src/lib/menu.ts b/app/src/renderer/src/lib/menu.ts index e3760e0..93cece8 100644 --- a/app/src/renderer/src/lib/menu.ts +++ b/app/src/renderer/src/lib/menu.ts @@ -17,6 +17,8 @@ export interface MenuAction { export type MenuEntry = MenuAction | { kind: 'separator' } | { kind: 'header'; label: string } +export const SEPARATOR: MenuEntry = { kind: 'separator' } + export interface MenuRequest { x: number y: number diff --git a/app/src/renderer/src/lib/trackMenu.ts b/app/src/renderer/src/lib/trackMenu.ts index afb8522..5f813c4 100644 --- a/app/src/renderer/src/lib/trackMenu.ts +++ b/app/src/renderer/src/lib/trackMenu.ts @@ -21,14 +21,14 @@ import { Trash2 } from '@lucide/svelte' import type { CueSort } from '../../../preload/autoCue' -import { autoCueEntry, clearCuesEntry, cuePaletteEntry } from './cueMenu' +import { cuesEntry } from './cueMenu' import { TRACK_COLORS } from './format' import { matchesPreset, presetLabel } from './convertPresets' import { loadPresets } from './convertPresetStore' import type { Library } from './library.svelte' import { membership, type Membership } from './library/membership' import type { TreeNode } from './library/tree' -import { tidy, type MenuEntry } from './menu' +import { SEPARATOR, tidy, type MenuEntry } from './menu' import type { Decks } from './decks.svelte' import type { ConvertPreset, Track, TrackEdit } from './types' import { isDeviceTrack } from './trackIds' @@ -48,8 +48,6 @@ export interface TrackMenuActions { shortcut: (id: TrackMenuShortcut) => string | undefined } -export const SEPARATOR: MenuEntry = { kind: 'separator' } - export function unlockEntry(library: Library, decks: Decks): MenuEntry { const blocked = !!library.info?.rekordboxRunning return { @@ -225,9 +223,11 @@ export function trackMenu(library: Library, decks: Decks, tracks: Track[], actio disabled: locked || !analysable.length, onselect: () => actions.analyse(analysable) }, - !device && autoCueEntry(locked, (sort) => actions.autoCue(tracks, sort)), - !device && cuePaletteEntry(library.cuePalette, ids), - !device && clearCuesEntry(locked, (sorts) => actions.clearCues(tracks, sorts)), + !device && + cuesEntry(locked, library.cuePalette, ids, { + autoCue: (sort) => actions.autoCue(tracks, sort), + clear: (sorts) => actions.clearCues(tracks, sorts) + }), !device && { label: 'Convert file type', icon: FileAudio,