From 98cb574a44a1816de96a52601b2eb0f59d5b7c52 Mon Sep 17 00:00:00 2001 From: gitwide-cloud Date: Thu, 3 Dec 2026 15:23:55 -0800 Subject: [PATCH 1/4] Add Library beat-grid review and isolated metronome audition --- apps/amp-player/src/grid_editor.rs | 494 +++++++++++++++++++++++ apps/amp-player/src/main.rs | 5 + apps/amp-player/src/mixer.rs | 11 + apps/amp-player/src/organized_library.rs | 3 + apps/amp-player/src/playlist_builder.rs | 38 +- apps/amp-player/src/preparer.rs | 6 + apps/amp-player/src/track_columns.rs | 2 + apps/amp-player/src/waveform.rs | 82 +++- crates/amp-core/src/grid_review.rs | 189 +++++++++ crates/amp-core/src/lib.rs | 1 + crates/amp-core/src/mix_schedule.rs | 3 +- 11 files changed, 823 insertions(+), 11 deletions(-) create mode 100644 apps/amp-player/src/grid_editor.rs create mode 100644 crates/amp-core/src/grid_review.rs diff --git a/apps/amp-player/src/grid_editor.rs b/apps/amp-player/src/grid_editor.rs new file mode 100644 index 00000000..3e1b5fd9 --- /dev/null +++ b/apps/amp-player/src/grid_editor.rs @@ -0,0 +1,494 @@ +//! Library-only grid audition. Never borrows or changes the live DJ decks. +use amp_core::{Library, Preparation, Track, grid_review, preparation}; +use eframe::egui; +use std::{ + path::{Path, PathBuf}, + sync::atomic::Ordering::Relaxed, + time::Instant, +}; + +#[derive(Default)] +pub struct Editor { + pub open: bool, + pub revision: u64, + root: PathBuf, + owner: PathBuf, + relative: PathBuf, + path: PathBuf, + title: String, + original: Preparation, + draft: Preparation, + saved_revision: Option>, + batch: Vec, + cursor: f64, + span: f64, + wave: crate::waveform::Lane, + overview: crate::waveform::Lane, + audio: Option, + metronome: bool, + taps: Vec, + status: String, + dirty: bool, +} + +#[cfg(test)] +mod tests { + use super::*; + fn fixture() -> (tempfile::TempDir, Library, Editor) { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("one.wav"), b"audio fixture").unwrap(); + let mut p = Preparation { + bpm: Some(120.), + beat_offset: Some(0.2), + cue_in: 8., + cue_out: Some(90.), + ..Default::default() + }; + p.manual_cues.push(preparation::Cue { + id: "owner-cue".into(), + label: "Keep this cue".into(), + seconds: 16., + ..Default::default() + }); + p.extensions + .insert("regions".into(), serde_json::json!([{"start":8,"end":12}])); + preparation::save(dir.path(), Path::new("one.wav"), &p).unwrap(); + let lib = amp_core::scan(dir.path()).unwrap(); + let mut editor = Editor::default(); + editor.select(dir.path(), &lib.tracks[0], vec!["one.wav".into()]); + (dir, lib, editor) + } + #[test] + fn review_persists_grid_without_cue_or_audio_changes() { + let (dir, mut library, mut editor) = fixture(); + let before = preparation::load(&dir.path().join("one.wav")).unwrap(); + grid_review::set_bar_one(&mut editor.draft, 4.125).unwrap(); + editor.dirty = true; + assert_eq!( + preparation::load(&dir.path().join("one.wav")).unwrap(), + before + ); + editor.save(&mut library).unwrap(); + let saved = preparation::load(&dir.path().join("one.wav")).unwrap(); + assert_eq!(grid_review::status(&saved), grid_review::Status::Reviewed); + assert_eq!(saved.manual_cues, before.manual_cues); + assert_eq!(saved.cue_in, before.cue_in); + assert_eq!(saved.cue_out, before.cue_out); + assert_eq!(saved.extensions["regions"], before.extensions["regions"]); + assert_eq!( + std::fs::read(dir.path().join("one.wav")).unwrap(), + b"audio fixture" + ); + assert_eq!( + grid_review::status(&library.tracks[0].preparation), + grid_review::Status::Reviewed + ); + assert!(!editor.dirty); + assert!(editor.audio.is_none()); + } + #[test] + fn concurrent_preparation_save_is_not_overwritten() { + let (dir, mut library, mut editor) = fixture(); + let mut other = editor.original.clone(); + other.cue_in = 22.; + preparation::save(dir.path(), Path::new("one.wav"), &other).unwrap(); + grid_review::set_bar_one(&mut editor.draft, 3.).unwrap(); + editor.dirty = true; + assert!(editor.save(&mut library).is_err()); + assert!(editor.dirty); + assert_eq!( + preparation::load(&dir.path().join("one.wav")) + .unwrap() + .cue_in, + 22. + ); + } + #[test] + fn closing_and_reopening_retains_unsaved_grid() { + let (dir, library, mut editor) = fixture(); + grid_review::set_bar_one(&mut editor.draft, 3.).unwrap(); + editor.dirty = true; + editor.open = false; + editor.select(dir.path(), &library.tracks[0], vec![]); + assert!(editor.open && editor.dirty); + assert_eq!( + editor.draft.extensions["mix_bar_anchor"], + serde_json::json!(3.) + ); + } +} +impl Editor { + pub fn select(&mut self, root: &Path, track: &Track, batch: Vec) { + if self.dirty { + self.open = true; + if self.root == root && self.path == track.path { + return; + } + self.status = + "Save the grid or discard your changes before choosing another song.".into(); + return; + } + let result = (|| { + let (owner, relative) = + amp_core::music_sources::owner(root, &track.path).map_err(|e| e.to_string())?; + let (original, revision) = preparation::load_with_revision(&owner.join(&relative))?; + Ok::<_, String>((owner, relative, original, revision)) + })(); + match result { + Ok((owner, relative, original, revision)) => { + self.audio = None; + self.root = root.into(); + self.owner = owner; + self.relative = relative; + self.path = track.path.clone(); + self.title = track.title.clone(); + self.draft = track.preparation.clone(); + self.original = original; + self.saved_revision = revision; + self.batch = batch; + self.cursor = 0.; + self.span = 16.; + self.taps.clear(); + self.status.clear(); + self.dirty = false; + self.open = true; + } + Err(e) => { + self.status = e; + self.open = true; + } + } + } + pub fn stop(&mut self) { + self.audio = None; + } + fn duration(&self) -> f64 { + self.draft + .analysis + .as_ref() + .map(|a| a.duration) + .or_else(|| { + self.draft + .extensions + .get("audio_properties")? + .get("duration")? + .as_f64() + }) + .or(self.draft.cue_out) + .filter(|v| v.is_finite() && *v > 0.) + .unwrap_or(300.) + } + fn audition(&mut self) -> Result<(), String> { + let mut track = Track { + path: self.relative.clone(), + title: self.title.clone(), + preparation: self.draft.clone(), + }; + // Review the whole original recording, independently of saved cue/region bounds. + track.preparation.cue_in = self.cursor; + track.preparation.cue_out = None; + track.preparation.extensions.remove("playback_rate"); + if self.audio.is_none() { + self.audio = Some(crate::mixer::Engine::new()?); + } + if let Some(audio) = &mut self.audio { + audio.load_original(0, &self.owner, &track, true)?; + audio.set_fader(0.); + } + Ok(()) + } + fn save(&mut self, library: &mut Library) -> Result<(), String> { + let approved = grid_review::approve(&self.original, &self.draft)?; + preparation::save_if_unchanged( + &self.owner, + &self.relative, + &approved, + self.saved_revision.as_deref(), + )?; + let (saved, revision) = preparation::load_with_revision(&self.owner.join(&self.relative))?; + if let Some(track) = library.tracks.iter_mut().find(|t| t.path == self.path) { + // Keep runtime-only metadata in the in-memory catalog too. + track.preparation = grid_review::approve(&track.preparation, &saved)?; + } + self.original = saved.clone(); + self.draft = saved; + self.saved_revision = revision; + self.dirty = false; + self.revision = self.revision.wrapping_add(1); + self.status = "Grid reviewed and saved. Cues and other preparation kept; playing decks are unchanged.".into(); + Ok(()) + } + pub fn show(&mut self, ctx: &egui::Context, library: Option<&mut Library>, blocked: bool) { + if !self.open { + self.stop(); + return; + } + if blocked { + self.stop(); + } + if self.path.as_os_str().is_empty() { + egui::Window::new("Review beat grid") + .open(&mut self.open) + .show(ctx, |ui| { + ui.label(&self.status); + }); + return; + } + let mut open = true; + let mut next = None; + let mut save = false; + let mut discard = false; + let duration = self.duration(); + if let Some(audio) = &self.audio + && audio.playing(0) + { + self.cursor = audio.source_position(0).min(duration); + ctx.request_repaint_after(std::time::Duration::from_millis(16)); + } + egui::Window::new("Review beat grid") + .open(&mut open) + .default_size(egui::vec2(1040., 650.)) + .min_width(520.) + .vscroll(true) + .show(ctx, |ui| { + ui.heading(&self.title); + ui.label( + "Line up beats with the music, set the first bar, then mark the grid reviewed.", + ); + ui.horizontal_wrapped(|ui| { + ui.strong(format!( + "Grid: {}", + grid_review::status(&self.draft).label() + )); + if self.dirty { + ui.colored_label(egui::Color32::GOLD, "Unsaved grid changes"); + } + let index = self.batch.iter().position(|p| p == &self.path); + if let Some(i) = index { + ui.label(format!("{} / {} songs", i + 1, self.batch.len())); + if ui + .add_enabled(i > 0 && !self.dirty, egui::Button::new("Previous song")) + .clicked() + { + next = self.batch.get(i - 1).cloned(); + } + if ui + .add_enabled( + i + 1 < self.batch.len() && !self.dirty, + egui::Button::new("Next song"), + ) + .clicked() + { + next = self.batch.get(i + 1).cloned(); + } + } + }); + ui.horizontal_wrapped(|ui| { + let playing = self.audio.as_ref().is_some_and(|a| a.playing(0)); + if ui + .add_enabled( + !blocked, + egui::Button::new(if playing { + "Pause preview" + } else { + "Play preview" + }), + ) + .clicked() + { + if playing { + if let Some(audio) = &mut self.audio { + audio.pause(0); + } + } else if let Err(e) = self.audition() { + self.status = e; + } + } + if ui.button("Stop preview").clicked() { + self.stop(); + } + ui.checkbox(&mut self.metronome, "Metronome"); + ui.label(format!("{:.3} s", self.cursor)); + if blocked { + ui.weak("Pause Player/DJ and live casting before previewing here."); + } + }); + self.overview.overview = true; + self.overview.height = Some(65.); + self.overview.frequency_colors = true; + self.overview.hide_caption = true; + let track = Track { + path: self.path.clone(), + title: self.title.clone(), + preparation: self.draft.clone(), + }; + self.overview + .show(ui, &self.root, Some(&track), self.cursor, duration, 0); + let mut seek = self.overview.seek.take(); + ui.horizontal_wrapped(|ui| { + if ui.button("Zoom in").clicked() { + self.span = (self.span / 2.).max(2.); + } + if ui.button("Zoom out").clicked() { + self.span = (self.span * 2.).min(256.); + } + if ui.button("← Earlier").clicked() { + seek = Some((self.cursor - self.span / 2.).max(0.)); + } + if ui.button("Later →").clicked() { + seek = Some((self.cursor + self.span / 2.).min(duration)); + } + ui.weak("Low = red · Mid = green · High = blue. Gold lines start bars."); + }); + self.wave.height = Some(240.); + self.wave.frequency_colors = true; + self.wave.hide_caption = true; + self.wave + .show(ui, &self.root, Some(&track), self.cursor, self.span, 0); + if let Some(at) = self.wave.seek.take() { + seek = Some(at); + } + if let Some(delta) = self.wave.scrub.take().or(self.wave.drag.take()) { + seek = Some(self.cursor + delta); + } + if let Some(at) = seek { + let playing = self.audio.as_ref().is_some_and(|a| a.playing(0)); + self.cursor = at.clamp(0., duration); + if playing && let Err(e) = self.audition() { + self.status = e; + } + } + let before = ( + self.draft.bpm, + self.draft.beat_offset, + self.draft.extensions.get("mix_bar_anchor").cloned(), + ); + ui.horizontal_wrapped(|ui| { + let mut bpm = self.draft.bpm.unwrap_or(120.); + if ui + .add( + egui::DragValue::new(&mut bpm) + .range(40. ..=300.) + .speed(0.1) + .prefix("BPM "), + ) + .changed() + { + if let Err(e) = grid_review::tempo(&mut self.draft, bpm) { + self.status = e; + } + } + for (label, scale) in [("BPM ×2", 2.), ("BPM ÷2", 0.5)] { + if ui.button(label).clicked() + && let Err(e) = grid_review::tempo(&mut self.draft, bpm * scale) + { + self.status = e; + } + } + if ui.button("Tap tempo").clicked() { + let now = Instant::now(); + if self + .taps + .last() + .is_some_and(|t| now.duration_since(*t).as_secs_f64() > 2.) + { + self.taps.clear(); + } + self.taps.push(now); + if self.taps.len() > 8 { + self.taps.remove(0); + } + if self.taps.len() >= 3 { + let elapsed = now.duration_since(self.taps[0]).as_secs_f64(); + if let Err(e) = grid_review::tempo( + &mut self.draft, + 60. * (self.taps.len() - 1) as f64 / elapsed, + ) { + self.status = e; + } + } + } + }); + ui.horizontal_wrapped(|ui| { + if ui.button("Set bar 1 here").clicked() + && let Err(e) = grid_review::set_bar_one(&mut self.draft, self.cursor) + { + self.status = e; + } + for (label, step) in [ + ("← 10 ms", -0.01), + ("← 1 ms", -0.001), + ("1 ms →", 0.001), + ("10 ms →", 0.01), + ] { + if ui.button(label).clicked() + && let Err(e) = grid_review::nudge(&mut self.draft, step) + { + self.status = e; + } + } + }); + if before + != ( + self.draft.bpm, + self.draft.beat_offset, + self.draft.extensions.get("mix_bar_anchor").cloned(), + ) + { + self.dirty = true; + } + ui.horizontal_wrapped(|ui| { + save = ui + .add_enabled( + grid_review::valid(&self.draft), + egui::Button::new("Grid looks right → mark reviewed"), + ) + .clicked(); + discard = ui + .add_enabled(self.dirty, egui::Button::new("Discard grid changes")) + .clicked(); + }); + ui.label(&self.status); + }); + if discard { + self.draft = self.original.clone(); + self.dirty = false; + self.taps.clear(); + } + if let Some(library) = library { + if save && let Err(e) = self.save(library) { + self.status = format!("{e}. Your grid changes are still here."); + } + if let Some(path) = next + && let Some(track) = library.tracks.iter().find(|t| t.path == path) + { + self.select(&self.root.clone(), track, self.batch.clone()); + } + } + if let Some(audio) = &self.audio { + audio + .controls + .grid_click_bpm + .store(self.draft.bpm.unwrap_or(120.).to_bits(), Relaxed); + audio.controls.grid_click_anchor.store( + self.draft + .extensions + .get("mix_bar_anchor") + .and_then(|v| v.as_f64()) + .or(self.draft.beat_offset) + .unwrap_or(0.) + .to_bits(), + Relaxed, + ); + audio + .controls + .grid_click + .store(self.metronome && grid_review::valid(&self.draft), Relaxed); + } + // A close never discards edits: they remain available on reopening. + self.open = open; + if !open { + self.stop(); + } + } +} diff --git a/apps/amp-player/src/main.rs b/apps/amp-player/src/main.rs index 9a6161f9..75edea1a 100644 --- a/apps/amp-player/src/main.rs +++ b/apps/amp-player/src/main.rs @@ -28,6 +28,7 @@ mod dragdrop; mod engine; mod engine_download; mod genre_picker; +mod grid_editor; mod google_cast; mod hot_cues; mod icons; @@ -3906,6 +3907,10 @@ impl eframe::App for Player { self.catalog_updated = std::time::Instant::now(); } } + let grid_revision = self.preparer.grid.revision; + let grid_blocked = !self.library_open || self.library_preview_blocked() || self.smart_preview.active(); + self.preparer.grid.show(ui.ctx(), self.library.as_mut(), grid_blocked); + if self.preparer.grid.revision != grid_revision { self.library_generation = self.library_generation.wrapping_add(1); } if let Some((path, seconds)) = self.preparer.preview.take() { if self.library_preview_blocked() { self.status = diff --git a/apps/amp-player/src/mixer.rs b/apps/amp-player/src/mixer.rs index 33451f14..097d5c65 100644 --- a/apps/amp-player/src/mixer.rs +++ b/apps/amp-player/src/mixer.rs @@ -78,6 +78,9 @@ pub struct Controls { intent_identity: u64, pub(crate) output_gate: Arc, pub broadcast_player_only: AtomicBool, + pub grid_click: AtomicBool, + pub grid_click_bpm: AtomicU64, + pub grid_click_anchor: AtomicU64, pub pair: [AtomicU32; 2], pub master_bpm: AtomicU32, clock_origin_frame: AtomicU64, @@ -201,6 +204,9 @@ impl Default for Controls { Self { output_gate: crate::output_admission::current(), broadcast_player_only: AtomicBool::new(false), + grid_click: AtomicBool::new(false), + grid_click_bpm: AtomicU64::new(120f64.to_bits()), + grid_click_anchor: AtomicU64::new(0), pair: [AtomicU32::new(0), AtomicU32::new(1)], key_lock: std::array::from_fn(|_| AtomicBool::new(false)), key_lock_available: std::array::from_fn(|_| AtomicBool::new(false)), @@ -1623,6 +1629,11 @@ impl Mixer { || scratch_read.is_some_and(|(deck, _)| deck == d), ); } + if d == 0 && c.grid_click.load(Relaxed) { + let seconds = source.position / self.rate as f64 + f64::from_bits(c.source_origin[d].load(Relaxed)); + let click = amp_core::grid_review::click(seconds, f64::from_bits(c.grid_click_bpm.load(Relaxed)), f64::from_bits(c.grid_click_anchor.load(Relaxed))); + for sample in &mut frame { *sample += click; } + } v.gain += (get(&c.gain[d]).clamp(0., 1.) - v.gain) * 0.004; v.trim += (trims[d] - v.trim) * 0.004; for ch in 0..2 { diff --git a/apps/amp-player/src/organized_library.rs b/apps/amp-player/src/organized_library.rs index 4cb981d6..775c2088 100644 --- a/apps/amp-player/src/organized_library.rs +++ b/apps/amp-player/src/organized_library.rs @@ -27,6 +27,7 @@ pub(super) struct LibraryBuilder { checked: std::collections::BTreeSet, folders: String, tracks: String, + needs_grid_review: bool, suggestions: Vec, suggest_to_queue: bool, results: Option, @@ -36,6 +37,8 @@ struct LibraryResults { folder: PathBuf, general: String, tracks: String, + needs_grid_review: bool, + grid_revision: u64, refreshed: std::time::Instant, indices: Vec, } diff --git a/apps/amp-player/src/playlist_builder.rs b/apps/amp-player/src/playlist_builder.rs index 4d701b03..589b538f 100644 --- a/apps/amp-player/src/playlist_builder.rs +++ b/apps/amp-player/src/playlist_builder.rs @@ -6,6 +6,8 @@ impl Player { && r.folder == self.folder && r.general == self.search && r.tracks == self.library_builder.tracks + && r.needs_grid_review == self.library_builder.needs_grid_review + && r.grid_revision == self.preparer.grid.revision && r.refreshed.elapsed() < Duration::from_secs(1) }); if !fresh { @@ -20,6 +22,7 @@ impl Player { (!self.search.trim().is_empty() || t.path.starts_with(&self.folder)) && matches_track(t, &self.search) && matches_track(t, &self.library_builder.tracks) + && (!self.library_builder.needs_grid_review || amp_core::grid_review::status(&t.preparation).needs_review()) }) .map(|(i, _)| i) .collect() @@ -30,6 +33,8 @@ impl Player { folder: self.folder.clone(), general: self.search.clone(), tracks: self.library_builder.tracks.clone(), + needs_grid_review: self.library_builder.needs_grid_review, + grid_revision: self.preparer.grid.revision, refreshed: std::time::Instant::now(), indices, }); @@ -159,6 +164,35 @@ impl Player { self.folder = PathBuf::new(); } }); + ui.horizontal_wrapped(|ui| { + ui.checkbox(&mut self.library_builder.needs_grid_review, "Needs grid review"); + if ui.button("Review grids in these results…").clicked() { + let indices = self.library_browser_results(); + if let Some(lib) = &self.library && let Some(track) = indices.first().and_then(|i| lib.tracks.get(*i)) { + self.preparer.grid.select(&self.root, track, indices.iter().map(|i| lib.tracks[*i].path.clone()).collect()); + } + } + ui.menu_button("Review playlist grids…", |ui| { + for (_, playlist) in &self.dj_browser.playlists { + if ui.button(&playlist.name).clicked() { + if let Some(lib) = &self.library && let Some(track) = playlist.tracks.iter().find_map(|p| lib.tracks.iter().find(|t| &t.path == p)) { + self.preparer.grid.select(&self.root, track, playlist.tracks.clone()); + } + ui.close(); + } + } + ui.separator(); + for playlist in &self.run.settings.playlists { + if ui.button(format!("{} · Smart", playlist.name)).clicked() { + if let Some(lib) = &self.library { + let batch: Vec<_> = lib.tracks.iter().filter(|t| amp_core::show::eligible(playlist, t)).collect(); + if let Some(track) = batch.first() { self.preparer.grid.select(&self.root, track, batch.iter().map(|t| t.path.clone()).collect()); } + } + ui.close(); + } + } + }); + }); let mut filtered = self.library_browser_results(); let checked = self.checked_library_indices().len(); ui.horizontal_wrapped(|ui| { @@ -271,7 +305,7 @@ impl Player { let title_width = (row_width*0.29).max(190.); ui.horizontal(|ui| { ui.add_sized([28.,20.],egui::Label::new("✓")); - for (key,label,w) in [("title","Title",title_width),("artist","Artist",155.),("album","Album / Genre",180.),("length","Length / BPM / Key",155.)] { crate::track_sort::button(ui,"library-picker",key,label,w); } + for (key,label,w) in [("title","Title",title_width),("artist","Artist",155.),("album","Album / Genre",180.),("length","Length / BPM / Key / Grid",155.)] { crate::track_sort::button(ui,"library-picker",key,label,w); } }); if let Some(lib)=&self.library { let order=crate::track_sort::rows(ui.ctx(),"library-picker",self.library_generation,lib,&filtered); @@ -295,7 +329,7 @@ impl Player { if row.double_clicked() { if editing { preview=Some(index); } else { play=Some(index); } } ui.add_sized([155.,44.],egui::Label::new(track_columns::cell(track,"artist")).truncate()); ui.add_sized([180.,44.],egui::Label::new(format!("{}\n{}",track_columns::cell(track,"album"),track_columns::cell(track,"genre"))).truncate()); - ui.add_sized([155.,44.],egui::Label::new(format!("{} · {} · {}",track_columns::cell(track,"length"),track_columns::cell(track,"bpm"),track_columns::cell(track,"key"))).truncate()); + ui.add_sized([155.,44.],egui::Label::new(format!("{} · {} · {}\nGrid: {}",track_columns::cell(track,"length"),track_columns::cell(track,"bpm"),track_columns::cell(track,"key"),amp_core::grid_review::status(&track.preparation).label())).truncate()); if ui.button("Preview").clicked() { preview=Some(index); } }); }} diff --git a/apps/amp-player/src/preparer.rs b/apps/amp-player/src/preparer.rs index b1d0ce73..14d7bf85 100644 --- a/apps/amp-player/src/preparer.rs +++ b/apps/amp-player/src/preparer.rs @@ -20,6 +20,7 @@ struct Update { #[derive(Default)] pub struct Preparer { pub revision: u64, + pub grid: crate::grid_editor::Editor, analysis_summary: Option<(PathBuf, std::time::Instant, usize, usize, usize)>, saved_stats_root: PathBuf, saved_stats_failures: usize, @@ -111,6 +112,10 @@ impl Preparer { ui.weak("Select a song below to prepare its waveform and energy sections."); return; }; + if ui.button("Review beat grid…").clicked() { + let batch = library.as_ref().map(|l| l.tracks.iter().map(|t| t.path.clone()).collect()).unwrap_or_default(); + self.grid.select(root, track, batch); + } if !self.busy() && !self.title.is_empty() && !self.selected_track(root, track) @@ -537,6 +542,7 @@ impl Preparer { pub fn guard_preview(&mut self, blocked: bool) { self.preview_blocked = blocked; if blocked { + self.grid.stop(); self.stem_preview = None; } } diff --git a/apps/amp-player/src/track_columns.rs b/apps/amp-player/src/track_columns.rs index 762124ee..f5479388 100644 --- a/apps/amp-player/src/track_columns.rs +++ b/apps/amp-player/src/track_columns.rs @@ -23,6 +23,7 @@ pub const FIELDS: &[(&str, &str, f32, bool)] = &[ ("length", "Length", 75., true), ("energy", "Energy", 75., false), ("analysis", "Analysis", 120., true), + ("grid", "Beat grid", 100., false), ("stems", "Stems", 110., true), ("rating", "Rating", 70., false), ("bitrate", "Bitrate", 80., false), @@ -156,6 +157,7 @@ pub fn cell(t: &_core::Track, key: &str) -> String { .or(p.cue_out) .map(|v| format!("{:02}:{:02}", v as u64 / 60, v as u64 % 60)) .unwrap_or_default(), + "grid" => amp_core::grid_review::status(p).label().into(), "analysis" => if analysis.is_some_and(|a| a.reviewed) { "Reviewed" } else if analysis.is_some() { diff --git a/apps/amp-player/src/waveform.rs b/apps/amp-player/src/waveform.rs index 6e82ee3c..44353cb1 100644 --- a/apps/amp-player/src/waveform.rs +++ b/apps/amp-player/src/waveform.rs @@ -10,11 +10,12 @@ use std::{ mpsc, }, }; -type Peaks = Arc<[[f32; 2]]>; +type Peaks = Arc<[[f32; 5]]>; const BIN: usize = 160; // 20 ms, independent of device sample rate. #[derive(Default)] pub struct Lane { pub height: Option, + pub frequency_colors: bool, pub overview: bool, pub overlay: bool, pub ignore_seek: bool, @@ -27,7 +28,7 @@ pub struct Lane { retry_after: Option, cancel: Option>, rx: Option>>, - peaks: Arc<[[f32; 2]]>, + peaks: Arc<[[f32; 5]]>, error: Option, } /// Wheel down advances, wheel up rewinds. Shift gives fine adjustment. @@ -74,10 +75,10 @@ pub(super) fn pointer_drag(ui: &egui::Ui, response: &egui::Response, span: f64) } #[derive(Default)] struct CacheEntry { - peaks: Option>, + peaks: Option>, building: bool, } -fn shared_decode(path: &Path, cancel: &AtomicBool) -> Result, String> { +fn shared_decode(path: &Path, cancel: &AtomicBool) -> Result, String> { use std::sync::{Condvar, Mutex, OnceLock}; type Entry = Arc<(Mutex, Condvar)>; static CACHE: OnceLock>> = OnceLock::new(); @@ -107,7 +108,7 @@ fn shared_decode(path: &Path, cancel: &AtomicBool) -> Result, St .0; } drop(state); - let result = decode(path, cancel).map(Arc::<[[f32; 2]]>::from); + let result = decode(path, cancel).map(Arc::<[[f32; 5]]>::from); let mut state = entry.0.lock().map_err(|_| "Waveform cache unavailable")?; state.building = false; if let Ok(peaks) = &result { @@ -116,7 +117,7 @@ fn shared_decode(path: &Path, cancel: &AtomicBool) -> Result, St entry.1.notify_all(); result } -fn decode(path: &Path, cancel: &AtomicBool) -> Result, String> { +fn decode(path: &Path, cancel: &AtomicBool) -> Result, String> { let mut child = amp_core::command("ffmpeg") .args(["-v", "error", "-i"]) .arg(path) @@ -130,6 +131,7 @@ fn decode(path: &Path, cancel: &AtomicBool) -> Result, String> { let result = (|| { let mut stdout = child.stdout.take().ok_or("No waveform decoder output")?; let mut peaks = Vec::new(); + let (mut low, mut mid) = (0f32, 0f32); let mut bytes = [0u8; BIN * 4]; loop { if cancel.load(Ordering::Relaxed) { @@ -146,14 +148,22 @@ fn decode(path: &Path, cancel: &AtomicBool) -> Result, String> { if n == 0 { break; } - let mut peak = [0f32; 2]; + let mut peak = [0f32; 5]; for b in bytes[..n].as_chunks::<4>().0 { let v = f32::from_le_bytes(*b); if v.is_finite() { peak[0] = peak[0].min(v); peak[1] = peak[1].max(v); + low += 0.1116 * (v - low); // 150 Hz at 8 kHz + mid += 0.6752 * (v - mid); // 2 kHz at 8 kHz + peak[2] += low * low; + peak[3] += (mid - low).powi(2); + peak[4] += (v - mid).powi(2); } } + for band in &mut peak[2..] { + *band = (*band / (n / 4).max(1) as f32).sqrt(); + } peaks.push(peak); if n < bytes.len() { break; @@ -508,9 +518,65 @@ impl Lane { graph.center().y - p[0].clamp(-1., 0.) * graph.height() / 2., ), ], - Stroke::new((rect.width() / (span as f32 * 50.)).max(1.), color), + Stroke::new( + (rect.width() / (span as f32 * 50.)).max(1.), + if self.frequency_colors { + let bands = self.peaks[i..(i + stride).min(hi)] + .iter() + .fold([0f32; 3], |a, b| { + std::array::from_fn(|j| a[j].max(b[j + 2])) + }); + let scale = bands.iter().sum::().max(1e-8); + Color32::from_rgb( + (40. + 215. * bands[0] / scale) as u8, + (40. + 215. * bands[1] / scale) as u8, + (40. + 215. * bands[2] / scale) as u8, + ) + } else { + color + }, + ), ); } + if self.frequency_colors && amp_core::grid_review::valid(&t.preparation) { + let beat = 60. / t.preparation.bpm.unwrap_or(120.); + let anchor = t + .preparation + .extensions + .get("mix_bar_anchor") + .and_then(|v| v.as_f64()) + .unwrap_or(t.preparation.beat_offset.unwrap_or(0.)); + let first = ((start - anchor) / beat).ceil() as i64; + for n in first..first + ((span / beat).ceil() as i64).min(2048) { + let time = anchor + n as f64 * beat; + if time < 0. { + continue; + } + let x = time_x(time, camera, span, rect); + let bar = n.rem_euclid(4) == 0; + painter.vline( + x, + graph.y_range(), + Stroke::new( + if bar { 2. } else { 1. }, + if bar { + Color32::GOLD + } else { + Color32::WHITE.gamma_multiply(0.35) + }, + ), + ); + if bar && span <= 64. { + painter.text( + egui::pos2(x + 3., rect.top()), + egui::Align2::LEFT_TOP, + format!("Bar {}", n.div_euclid(4) + 1), + egui::FontId::monospace(12.), + Color32::GOLD, + ); + } + } + } if self.overview && let Some(profile) = amp_core::energy_profile::read(&t.preparation) { diff --git a/crates/amp-core/src/grid_review.rs b/crates/amp-core/src/grid_review.rs new file mode 100644 index 00000000..c993b399 --- /dev/null +++ b/crates/amp-core/src/grid_review.rs @@ -0,0 +1,189 @@ +//! Manual constant-grid corrections. Only grid fields are copied on approval. +use crate::Preparation; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Status { + None, + Estimated, + Reliable, + Reviewed, +} +impl Status { + pub fn label(self) -> &'static str { + match self { + Self::None => "None", + Self::Estimated => "Estimated", + Self::Reliable => "Reliable", + Self::Reviewed => "Reviewed", + } + } + pub fn needs_review(self) -> bool { + matches!(self, Self::None | Self::Estimated) + } +} +pub fn status(p: &Preparation) -> Status { + if !valid(p) { + return Status::None; + } + if p.extensions.get("grid_reviewed").and_then(|v| v.as_bool()) == Some(true) + || (!p.extensions.contains_key("grid_reviewed") + && (p.manual_override || p.analysis.as_ref().is_some_and(|a| a.reviewed))) + { + Status::Reviewed + } else if crate::mix_schedule::timing_reliable(p) { + Status::Reliable + } else { + Status::Estimated + } +} +pub fn valid(p: &Preparation) -> bool { + p.bpm + .is_some_and(|v| v.is_finite() && (40. ..=300.).contains(&v)) + && p.beat_offset.is_some_and(|v| v.is_finite() && v >= 0.) +} +/// Establish bar numbering independently of the normalized beat phase. +pub fn set_bar_one(p: &mut Preparation, seconds: f64) -> Result<(), String> { + let bpm = p + .bpm + .filter(|v| v.is_finite() && (40. ..=300.).contains(v)) + .ok_or("Set a tempo between 40 and 300 BPM first")?; + if !seconds.is_finite() || seconds < 0. { + return Err("Choose a position in the song".into()); + } + p.beat_offset = Some(seconds.rem_euclid(60. / bpm)); + p.extensions + .insert("mix_bar_anchor".into(), serde_json::json!(seconds)); + changed(p); + Ok(()) +} +pub fn changed(p: &mut Preparation) { + p.extensions + .insert("grid_reviewed".into(), serde_json::json!(false)); +} +pub fn nudge(p: &mut Preparation, delta: f64) -> Result<(), String> { + if !valid(p) || !delta.is_finite() { + return Err("Set a tempo and beat position first".into()); + } + let period = 60. / p.bpm.unwrap_or(120.); + p.beat_offset = p.beat_offset.map(|v| (v + delta).rem_euclid(period)); + for key in ["mix_bar_anchor", "mix_phrase_anchor"] { + if let Some(v) = p.extensions.get(key).and_then(|v| v.as_f64()) { + p.extensions + .insert(key.into(), serde_json::json!((v + delta).max(0.))); + } + } + changed(p); + Ok(()) +} +pub fn tempo(p: &mut Preparation, bpm: f64) -> Result<(), String> { + if !bpm.is_finite() || !(40. ..=300.).contains(&bpm) { + return Err("Tempo must be between 40 and 300 BPM".into()); + } + let anchor = p + .extensions + .get("mix_bar_anchor") + .and_then(|v| v.as_f64()) + .or(p.beat_offset) + .unwrap_or(0.); + p.bpm = Some(bpm); + p.beat_offset = Some(anchor.rem_euclid(60. / bpm)); + changed(p); + Ok(()) +} +/// Approval does not copy analysis proposals, cues, regions, tags, or energy. +pub fn approve(original: &Preparation, grid: &Preparation) -> Result { + if !valid(grid) { + return Err("Set a valid tempo and beat position before marking the grid reviewed".into()); + } + let mut p = original.clone(); + p.bpm = grid.bpm; + p.beat_offset = grid.beat_offset; + for key in ["mix_bar_anchor", "mix_phrase_anchor"] { + if let Some(v) = grid.extensions.get(key) { + p.extensions.insert(key.into(), v.clone()); + } else { + p.extensions.remove(key); + } + } + p.extensions + .insert("grid_reviewed".into(), serde_json::json!(true)); + p.manual_override = true; + p.schema_version = Some(1); + if let Some(a) = &mut p.analysis { + a.reviewed = true; + } + crate::preparation::validate(&p)?; + Ok(p) +} +/// Sample-clock click: no UI timer, allocation, or separate playback clock. +pub fn click(seconds: f64, bpm: f64, anchor: f64) -> f32 { + if ![seconds, bpm, anchor].iter().all(|v| v.is_finite()) || !(40. ..=300.).contains(&bpm) { + return 0.; + } + let period = 60. / bpm; + let elapsed = (seconds - anchor).rem_euclid(period); + if elapsed >= 0.02 { + return 0.; + } + let beat = ((seconds - anchor) / period).floor() as i64; + let frequency = if beat.rem_euclid(4) == 0 { + 1800. + } else { + 1200. + }; + ((elapsed * frequency * std::f64::consts::TAU).sin() * (1. - elapsed / 0.02) * 0.18) as f32 +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn correction_and_approval_preserve_other_preparation() { + let mut original = Preparation { + bpm: Some(120.), + beat_offset: Some(0.1), + cue_in: 12., + cue_out: Some(180.), + ..Default::default() + }; + original.extensions.insert( + "regions".into(), + serde_json::json!([{"start": 20, "end":30}]), + ); + original + .extensions + .insert("energy".into(), serde_json::json!(0.7)); + let mut grid = original.clone(); + set_bar_one(&mut grid, 8.25).unwrap(); + nudge(&mut grid, -0.01).unwrap(); + tempo(&mut grid, 240.).unwrap(); + grid.cue_in = 99.; // an unrelated draft must never be approved accidentally + let p = approve(&original, &grid).unwrap(); + assert_eq!(p.cue_in, 12.); + assert_eq!(p.cue_out, original.cue_out); + assert_eq!(p.extensions["regions"], original.extensions["regions"]); + assert_eq!(p.extensions["energy"], original.extensions["energy"]); + assert!((p.extensions["mix_bar_anchor"].as_f64().unwrap() - 8.24).abs() < 1e-9); + assert_eq!(status(&p), Status::Reviewed); + nudge(&mut grid, 0.001).unwrap(); + assert_eq!(status(&grid), Status::Estimated); + } + #[test] + fn invalid_grid_cannot_be_approved() { + for bpm in [f64::NAN, 0., 301.] { + let p = Preparation { + bpm: Some(bpm), + beat_offset: Some(0.), + ..Default::default() + }; + assert!(approve(&Preparation::default(), &p).is_err()); + } + } + #[test] + fn click_uses_source_grid_and_bar_accent() { + assert_eq!(click(0.1, 120., 0.), 0.); + assert!(click(0.0001, 120., 0.).abs() > 0.1); + assert_eq!(click(0.5001, 120., 0.), click(2.5001, 120., 0.)); + assert_eq!(click(0., f64::NAN, 0.), 0.); + } +} diff --git a/crates/amp-core/src/lib.rs b/crates/amp-core/src/lib.rs index 3eadf15a..2f32c29e 100644 --- a/crates/amp-core/src/lib.rs +++ b/crates/amp-core/src/lib.rs @@ -18,6 +18,7 @@ pub mod coordination; pub mod cue_policy; pub mod discovery; pub mod energy_profile; +pub mod grid_review; pub mod engine_api; pub mod knowledge; pub mod library_commits; diff --git a/crates/amp-core/src/mix_schedule.rs b/crates/amp-core/src/mix_schedule.rs index f23c9813..76b4c69b 100644 --- a/crates/amp-core/src/mix_schedule.rs +++ b/crates/amp-core/src/mix_schedule.rs @@ -67,7 +67,8 @@ pub fn phrase_anchor(p: &Preparation) -> Option { /// Hand-approved grids retain priority. Automatic constant grids must not drive /// quantized transitions when analysis reports low confidence or audible drift. pub fn timing_reliable(p: &Preparation) -> bool { - p.bpm + p.extensions.get("grid_reviewed").and_then(|v| v.as_bool()) != Some(false) + && p.bpm .is_some_and(|b| b.is_finite() && (40. ..=300.).contains(&b)) && p.beat_offset.is_some_and(|o| o.is_finite() && o >= 0.) && (p.manual_override From 226db50abfae75a076aced2b74ed34866972c482 Mon Sep 17 00:00:00 2001 From: gitwide-cloud Date: Thu, 3 Dec 2026 15:28:21 -0800 Subject: [PATCH 2/4] Protect fresh grid edits and retain the latest owner work queue --- apps/amp-player/src/grid_editor.rs | 123 ++- apps/amp-player/src/main.rs | 2 +- apps/amp-player/src/mixer.rs | 20 + crates/amp-core/src/grid_review.rs | 24 +- docs/AMP_VERSE_IMPROVEMENT_QUEUE.md | 1186 +++++++++++++++++++++++---- docs/GRID_REVIEW.md | 35 + 6 files changed, 1200 insertions(+), 190 deletions(-) create mode 100644 docs/GRID_REVIEW.md diff --git a/apps/amp-player/src/grid_editor.rs b/apps/amp-player/src/grid_editor.rs index 3e1b5fd9..fa0d5b20 100644 --- a/apps/amp-player/src/grid_editor.rs +++ b/apps/amp-player/src/grid_editor.rs @@ -68,7 +68,7 @@ mod tests { preparation::load(&dir.path().join("one.wav")).unwrap(), before ); - editor.save(&mut library).unwrap(); + editor.save(dir.path(), &mut library).unwrap(); let saved = preparation::load(&dir.path().join("one.wav")).unwrap(); assert_eq!(grid_review::status(&saved), grid_review::Status::Reviewed); assert_eq!(saved.manual_cues, before.manual_cues); @@ -94,7 +94,7 @@ mod tests { preparation::save(dir.path(), Path::new("one.wav"), &other).unwrap(); grid_review::set_bar_one(&mut editor.draft, 3.).unwrap(); editor.dirty = true; - assert!(editor.save(&mut library).is_err()); + assert!(editor.save(dir.path(), &mut library).is_err()); assert!(editor.dirty); assert_eq!( preparation::load(&dir.path().join("one.wav")) @@ -116,6 +116,55 @@ mod tests { serde_json::json!(3.) ); } + #[test] + fn opening_after_another_clients_save_uses_the_fresh_grid() { + let (dir, mut library, mut editor) = fixture(); + let mut fresh = editor.original.clone(); + grid_review::tempo(&mut fresh, 128.).unwrap(); + grid_review::set_bar_one(&mut fresh, 6.).unwrap(); + preparation::save(dir.path(), Path::new("one.wav"), &fresh).unwrap(); + editor.select(dir.path(), &library.tracks[0], vec![]); + assert_eq!(editor.draft.bpm, Some(128.)); + assert_eq!( + editor.draft.extensions["mix_bar_anchor"], + serde_json::json!(6.) + ); + editor.save(dir.path(), &mut library).unwrap(); + let saved = preparation::load(&dir.path().join("one.wav")).unwrap(); + assert_eq!(saved.bpm, Some(128.)); + assert_eq!(saved.extensions["mix_bar_anchor"], serde_json::json!(6.)); + } + #[test] + fn switching_libraries_cannot_write_the_previous_songs_grid() { + let (dir, _, mut editor) = fixture(); + let (other, mut other_library, _) = fixture(); + let before = preparation::load(&dir.path().join("one.wav")).unwrap(); + let other_before = other_library.tracks[0].preparation.clone(); + grid_review::set_bar_one(&mut editor.draft, 9.).unwrap(); + assert!(editor.save(other.path(), &mut other_library).is_err()); + assert_eq!( + preparation::load(&dir.path().join("one.wav")).unwrap(), + before + ); + assert_eq!(other_library.tracks[0].preparation, other_before); + } + #[test] + fn playlist_navigation_skips_missing_entries() { + let (_, mut library, mut editor) = fixture(); + let mut next = library.tracks[0].clone(); + next.path = "three.wav".into(); + library.tracks.push(next); + editor.batch = vec!["one.wav".into(), "missing.wav".into(), "three.wav".into()]; + assert_eq!( + editor.neighbor(&library, 0, true).unwrap().path, + Path::new("three.wav") + ); + assert_eq!( + editor.neighbor(&library, 2, false).unwrap().path, + Path::new("one.wav") + ); + assert!(editor.neighbor(&library, 2, true).is_none()); + } } impl Editor { pub fn select(&mut self, root: &Path, track: &Track, batch: Vec) { @@ -142,7 +191,21 @@ impl Editor { self.relative = relative; self.path = track.path.clone(); self.title = track.title.clone(); - self.draft = track.preparation.clone(); + // The scan may be older than another client's saved correction. + // Its revision and editable fields must describe the same snapshot. + self.draft = original.clone(); + if revision.is_none() { + self.draft.bpm = track.preparation.bpm; + self.draft.beat_offset = track.preparation.beat_offset; + } + for key in ["audio_properties", "embedded_tags", "embedded_genres"] { + if let Some(value) = track.preparation.extensions.get(key) { + self.draft + .extensions + .entry(key.into()) + .or_insert_with(|| value.clone()); + } + } self.original = original; self.saved_revision = revision; self.batch = batch; @@ -162,6 +225,16 @@ impl Editor { pub fn stop(&mut self) { self.audio = None; } + fn neighbor<'a>(&self, library: &'a Library, index: usize, forward: bool) -> Option<&'a Track> { + let indices: Box> = if forward { + Box::new(index + 1..self.batch.len()) + } else { + Box::new((0..index).rev()) + }; + indices + .filter_map(|i| library.tracks.iter().find(|t| t.path == self.batch[i])) + .next() + } fn duration(&self) -> f64 { self.draft .analysis @@ -197,7 +270,10 @@ impl Editor { } Ok(()) } - fn save(&mut self, library: &mut Library) -> Result<(), String> { + fn save(&mut self, root: &Path, library: &mut Library) -> Result<(), String> { + if root != self.root { + return Err("Return to this song's Library before saving its grid".into()); + } let approved = grid_review::approve(&self.original, &self.draft)?; preparation::save_if_unchanged( &self.owner, @@ -218,7 +294,13 @@ impl Editor { self.status = "Grid reviewed and saved. Cues and other preparation kept; playing decks are unchanged.".into(); Ok(()) } - pub fn show(&mut self, ctx: &egui::Context, library: Option<&mut Library>, blocked: bool) { + pub fn show( + &mut self, + ctx: &egui::Context, + root: &Path, + library: Option<&mut Library>, + blocked: bool, + ) { if !self.open { self.stop(); return; @@ -226,6 +308,21 @@ impl Editor { if blocked { self.stop(); } + if root != self.root && !self.path.as_os_str().is_empty() { + self.stop(); + egui::Window::new("Review beat grid") + .open(&mut self.open) + .show(ctx, |ui| { + ui.label("This grid belongs to another Library. Return there to keep editing."); + if ui.button("Discard grid draft and close").clicked() { + self.dirty = false; + } + }); + if !self.dirty { + self.open = false; + } + return; + } if self.path.as_os_str().is_empty() { egui::Window::new("Review beat grid") .open(&mut self.open) @@ -270,7 +367,7 @@ impl Editor { .add_enabled(i > 0 && !self.dirty, egui::Button::new("Previous song")) .clicked() { - next = self.batch.get(i - 1).cloned(); + next = Some((i, false)); } if ui .add_enabled( @@ -279,7 +376,7 @@ impl Editor { ) .clicked() { - next = self.batch.get(i + 1).cloned(); + next = Some((i, true)); } } }); @@ -456,13 +553,15 @@ impl Editor { self.taps.clear(); } if let Some(library) = library { - if save && let Err(e) = self.save(library) { + if save && let Err(e) = self.save(root, library) { self.status = format!("{e}. Your grid changes are still here."); } - if let Some(path) = next - && let Some(track) = library.tracks.iter().find(|t| t.path == path) - { - self.select(&self.root.clone(), track, self.batch.clone()); + if let Some((i, forward)) = next { + if let Some(track) = self.neighbor(library, i, forward) { + self.select(&self.root.clone(), track, self.batch.clone()); + } else { + self.status = "No more available songs in this batch. Reconnect missing music sources to review those songs.".into(); + } } } if let Some(audio) = &self.audio { diff --git a/apps/amp-player/src/main.rs b/apps/amp-player/src/main.rs index 75edea1a..a0bc8b82 100644 --- a/apps/amp-player/src/main.rs +++ b/apps/amp-player/src/main.rs @@ -3909,7 +3909,7 @@ impl eframe::App for Player { } let grid_revision = self.preparer.grid.revision; let grid_blocked = !self.library_open || self.library_preview_blocked() || self.smart_preview.active(); - self.preparer.grid.show(ui.ctx(), self.library.as_mut(), grid_blocked); + self.preparer.grid.show(ui.ctx(), &self.root, self.library.as_mut(), grid_blocked); if self.preparer.grid.revision != grid_revision { self.library_generation = self.library_generation.wrapping_add(1); } if let Some((path, seconds)) = self.preparer.preview.take() { if self.library_preview_blocked() { diff --git a/apps/amp-player/src/mixer.rs b/apps/amp-player/src/mixer.rs index 097d5c65..9b87ccee 100644 --- a/apps/amp-player/src/mixer.rs +++ b/apps/amp-player/src/mixer.rs @@ -3374,6 +3374,26 @@ fn stream>( mod tests { use super::*; #[test] + fn grid_review_click_is_sample_clocked_and_silent_when_paused_or_disabled() { + let run = |enabled: bool, playing: bool, block: usize| { + let controls = Arc::new(Controls::default()); + controls.grid_click.store(enabled, Relaxed); + controls.grid_click_bpm.store(120f64.to_bits(), Relaxed); + let (tx, rx) = mpsc::sync_channel(32); + let mut mixer = Mixer::new(8000, rx, controls); + tx.send(Command::Load(0, source(0., 16000), playing, 1)).unwrap(); + let mut result = Vec::new(); + for _ in 0..8000/block { mixer.render(block, |_, f| result.push(f)); } + result + }; + let one = run(true, true, 1); + assert!(one.iter().any(|f| f[0].abs() > 0.01)); + assert_eq!(one, run(true, true, 100)); + for frames in [run(false, true, 100), run(true, false, 100)] { + assert!(frames.iter().all(|f| *f == [0.; 2])); + } + } + #[test] fn buildup_handoff_reaches_the_new_drop_on_the_audio_clock() { let c = Arc::new(Controls::default()); let (tx, rx) = mpsc::sync_channel(32); diff --git a/crates/amp-core/src/grid_review.rs b/crates/amp-core/src/grid_review.rs index c993b399..39bcb22d 100644 --- a/crates/amp-core/src/grid_review.rs +++ b/crates/amp-core/src/grid_review.rs @@ -68,8 +68,15 @@ pub fn nudge(p: &mut Preparation, delta: f64) -> Result<(), String> { p.beat_offset = p.beat_offset.map(|v| (v + delta).rem_euclid(period)); for key in ["mix_bar_anchor", "mix_phrase_anchor"] { if let Some(v) = p.extensions.get(key).and_then(|v| v.as_f64()) { - p.extensions - .insert(key.into(), serde_json::json!((v + delta).max(0.))); + let shifted = v + delta; + // Keep a nonnegative anchor on the same 4/4 bar phase. Clamping it + // to zero would disagree with the wrapped beat phase after a nudge. + let anchor = if shifted < 0. { + shifted.rem_euclid(4. * period) + } else { + shifted + }; + p.extensions.insert(key.into(), serde_json::json!(anchor)); } } changed(p); @@ -180,6 +187,19 @@ mod tests { } } #[test] + fn negative_nudge_at_start_keeps_bar_and_beat_phase_aligned() { + let mut p = Preparation { + bpm: Some(120.), + ..Default::default() + }; + set_bar_one(&mut p, 0.).unwrap(); + nudge(&mut p, -0.001).unwrap(); + let anchor = p.extensions["mix_bar_anchor"].as_f64().unwrap(); + assert!((anchor - 1.999).abs() < 1e-9); + assert!((anchor.rem_euclid(0.5) - p.beat_offset.unwrap()).abs() < 1e-9); + assert!(click(anchor + 0.0001, 120., anchor).abs() > 0.1); + } + #[test] fn click_uses_source_grid_and_bar_accent() { assert_eq!(click(0.1, 120., 0.), 0.); assert!(click(0.0001, 120., 0.).abs() > 0.1); diff --git a/docs/AMP_VERSE_IMPROVEMENT_QUEUE.md b/docs/AMP_VERSE_IMPROVEMENT_QUEUE.md index b346001f..a34976dd 100644 --- a/docs/AMP_VERSE_IMPROVEMENT_QUEUE.md +++ b/docs/AMP_VERSE_IMPROVEMENT_QUEUE.md @@ -1,175 +1,1011 @@ -# AMP Verse — owner improvement queue - -Accepted 2026-12-03 from the owner's chat. Requirements and acceptance gates, -not completion claims. This order supersedes earlier backlog ordering. - -## Build order - -1. Engines: Tasks 1–5, then 6–10. Detailed requirements and corrections are in - [AUTO_MIX_ENERGY_TASKS.md](AUTO_MIX_ENERGY_TASKS.md). -2. LAN Library and remote playing: Tasks 17–21. -3. Reliability: Task 16, before relying on unattended runs. -4. Companion / meeting show control: Tasks 11–14, last. - -Task 15 is independent and may run at any time. Queued means authorized scope, -not evidence that work has been implemented, tested or released. - -## Tasks 1–10 — engines - -Keep the existing detailed contract: explicit incoming section-energy ranking; -normalized track/section scoring; richer rhythmic/band/flux features; supported -section boundaries/downbeat confidence; style energy arcs; optional Beat This -beat/downbeat analysis; optional All-In-One labeled sections and real bar counts; -key timeline; section-aware controls/cue rules; phrase-aware Auto Mix. - -Models remain optional, outside the base player. Preserve reviewed/manual -preparation, propose changes separately, and do not trigger unsolicited library -reanalysis. Keep the hand-annotated 10–20-song set and 20-transition listening -gate; tests and actual listening are distinct evidence. - -## Part 3 — meeting show control (build last) - -Meeting machine: amp-player desktop feeds the mixer. Control chain: -Node-RED → OnTime → Companion → AMP Verse. Library owns cues/regions; Player -handles instant intros/walk-ups; DJ handles background/recognition; Lab makes -sampler clips. Keep the existing simple optional-password trusted-LAN model. - -### Task 11 — named intro regions and instant Player playback - -Library stores non-destructive named regions: start/end, fade-in/out, gain and -after-action (stop / hand back to DJ / next region). Player obeys exact bounds. -Companion arm_intro pre-decodes; fire_intro always starts at region start. -Second-press behavior is configurable restart / ignore / fade out. Support an -ordered intro run sheet and optional next-intro auto-arm. - -Companion actions: arm_intro, fire_intro, stop_intro, intro next/previous. -Feedback: armed amber, playing green, failed red; variables: armed name and -time remaining. Armed command-accepted → first non-silent output frame target -is <100 ms, 50/50 trials. Verify sample-accurate fades/end and unchanged source -hash. Render latency does not by itself prove physical output latency. - -### Task 12 — Player and DJ sharing the room - -Allow independent output device/channel pairs for Player, DJ master and Sampler; -default remains shared output. An intro coordinates DJ duck/pause with per-intro -level/fade settings, then restores/resumes. Keep an interrupt stack so a -recognition/intro returns to the prior playlist/style/energy. Emergency mute is -global. Verify shared output never runs both at full level; separate routing -only reaches assigned channels; resume restores prior context. - -### Task 13 — recognition and pre-meeting checks - -Preload assigned recognition music; land on saved cue, otherwise a supported -chorus/drop from Task 7, play N bars, then hand back. A configured backup hype -song is explicitly authorized if assigned audio is missing/unprepared/unloadable; -show red Companion feedback. This is a visible configured backup, not a hidden -success path. Target backup within two seconds. - -One pre-meeting check validates all Companion/run-sheet/show file references, -preparation, cues/regions and output devices. Show a green/red result and problem -list. Test deleted/renamed files and invalid cues. Merge docs/COMPANION.md into -the integration module README so the current setup has one authoritative guide. - -### Task 14 — Lab clip and sampler maker - -Export Lab clips directly into the sampler library with name/color/gain/trim/ -fades. Assign banks from Library; add Companion bank selection and feedback to -existing sampler actions. Import a folder or AIMP playlist of existing clips as -a sampler bank or intro list; preserve source material and remapping identity. - -### Task 15 — remove integrated YouTube and Suno downloads (independent) - -Remove desktop lab_youtube/lab_suno and wiring in lab, lab_music_source and main; -Android SunoImport/UrlDownload and download-only YouTubeUrl/ImportUrl code/tests; -setup_lab_youtube tools/fixtures; yt-dlp/Deno paths in music-import verification, -music-import-engine/build workflows; obsolete LAB_YOUTUBE/SUNO_DOWNLOAD_RESEARCH -docs and related yt-dlp/Deno notices/assets. Inspect actual dependencies before -deleting shared utilities. Update distribution/module metadata accordingly. - -Keep local-file import, recording and every existing user clip. Workspace builds -and tests must pass; search yt-dlp/suno/youtube for remaining download code paths. -Historical documentation mentions are allowed. This supersedes earlier requests -to implement these integrated downloaders; the downloader is a separate app. - -### Task 16 — unattended reliability (after LAN, before unattended reliance) - -Audit unwrap/expect on control/file/decode/network paths and replace reachable -failures with logged, visible errors. Audio rendering must be panic-free. Bad -files, missing network storage and dropped outputs must skip/recover explicitly -rather than terminate the app. Keep minimized operation/autostart usable and -prevent modal dialogs blocking Companion. - -Separate render/control/automation modules in mixer/main/performance without -behavior change. Qualify with a real 24-hour Auto DJ soak plus periodic intro/ -recognition commands; record memory, handles, underruns and stalls. Start that -combined soak after its dependent meeting actions exist; do not claim it passed -from an engine-only run or add a perpetual polling monitor to the product. - -## Part 4 — LAN library and remote playing (after engines) - -Server serves music/playlists/preparation on demand. Clients play and mix -locally; serving a playlist does not mean the server plays it continuously. -Finish and prove [LIBRARY-LIVE-REMOTE.md](LIBRARY-LIVE-REMOTE.md), not a redesign. -Run each existing workflow on real devices and record the baseline before fixes. - -### Task 17 — acceptance of current Library/Remote behavior - -Turn every contract bullet into a script or written scenario. Run on one server -(Windows/Linux), Windows desktop and Android phone on the same LAN. Record -build-specific evidence in docs/ACCEPTANCE_LAN.md. Fix in order: discovery/pairing, -browse, play, offline download, sync. Every row needs an honest result; unavailable -equipment is blocked/not run, never pass. All discovery/browse/play rows must pass. - -### Task 18 — complete offline Auto Mix bundles - -Define one shared playlist bundle: audio; BPM/variable beat/downbeat grid; -key/timeline; energy profile/sections; cues/regions; loudness; playlist order/ -rules; hash manifest and analyzer version. Android uses the shared JNI policy and -the same preparation versions as desktop. New server analysis shows update -available; unchanged audio hashes mean analysis-only refresh transfers zero -audio bytes. Download then airplane-mode Auto Mix a complete 20-song playlist. - -### Task 19 — guest takeover of room audio - -Primary: guest desktop/Android broadcasts live Player/DJ master to server -(existing live_dj source). One Take over room button; server/Remote show Now -playing from device; owner Return to server music. Secondary: server temporarily -pulls a guest-shared playlist and mixes it; no main-library addition without -owner approval. Approve takeover per paired device once; guests get no library -editing rights. - -Fade station→guest and back without double audio; restore previous server -playlist/energy. Provide a latency/buffer setting. On source disconnect/sleep, -explicitly restore server music within five seconds. This owner-requested return -policy supersedes the earlier blanket no-fallback instruction only for this -case; show the source change, do not hide it. Use connection/stream events rather -than reintroducing server polling. Test 20 takeovers/returns with no silent gap ->1 s or overlapping audio, plus cable-pull recovery within five seconds. - -### Task 20 — USB offline path - -Use Task 18's bundle for playlist export to USB, with incremental changed-file -writes. Desktop/server open read-only without network/import. Optional import -deduplicates by audio hash and treats incoming cues as proposals where server -preparation exists. Android supports read-only USB-OTG where available. Verify -export→different computer→Auto Mix preserving cues/analysis; one-song change -rewrites only its changed files and necessary manifest/index metadata. - -### Task 21 — separate-downloader ingestion - -Watch a server Inbox using filesystem events. Hash/deduplicate incoming audio; -identify using existing MusicBrainz lookup, plus AcoustID when tags are absent; -organize verified results as Artist/Album/Artist - Title.ext and queue analysis. -Unknown identification goes to review, never a guessed destination/tag. - -Never directly overwrite/rename prepared or referenced songs. Any approved -rename goes through Library identity/reference updates for playlists/cues/ -Companion. Test duplicate drop leaves one copy and unidentified audio enters -review. Verify service availability/credentials before enabling optional lookup. - -## Shared exclusions and protections - -No Spotify-style recommendations, new stem models/effects, stronger control API -security redesign, or overwriting saved cues/manual/reviewed preparation. Keep -optional passwords. Preserve existing user audio. The explicit backup/return -behaviors above do not authorize hidden generic fallbacks or recurring polling. +# AMP Verse — improvement task list + +Status (RC34): Tasks 1–5 and 15 are done and released. Task 6 is in progress +on a separate branch. + +This file is the single work queue. Work top to bottom; keep each task in its +own draft PR, source-only, and publish an app release only when the owner +asks or a batch of fixes is fully verified. + +Build order (owner priority): +A. **RC34 follow-ups** — Tasks 22–26, 28 and 29 (bugs heard while + listening, DJ screen layout, manual-mixing info, tricks not firing). First. + Inside Part A, start with **Task 28 items 11–14 (beat-grid review view)** + and **Task 29**, then Task 22, then the rest. +0. **Task 0 — split the giant files.** After Task 6 finishes and before + Tasks 7–10, because Tasks 9–10 work inside these files. +1. **Engines** — Part 2 (Tasks 6–10), then Task 27 (DJ tricks). +2. **LAN library and remote playing** — Part 4 (Tasks 17–21). +3. **Reliability** — Task 16, before relying on long unattended runs. +4. **Companion / meeting show control** — Part 3 (Tasks 11–14), last. + +--- + +# Part A — RC34 follow-ups (do first) + +## Task 22 — Auto Mix mixed into the same song (bug) + +Heard on RC34: Auto Mix transitioned into the song that was already playing. + +**Evidence (owner screenshot):** the same file, "The Goodfellas Havent You +Heard Of Lev…" (artist missing, 128 BPM, 12A, 5:40), was loaded on **A2 and B1 +at the same time** (A2 at 0:52, B1 at 0:33), and also on a third side deck in +the left panel. Both main decks show the red X icon next to the title, so +check what that state means (missing analysis, failed load or excluded) and +whether it affects selection. With six physical decks (A1–A3, B1–B3), the +"already loaded" exclusion must cover **every** loaded deck, not only the +active A/B pair. + +**Second screenshot:** A2 had "The Goodfellas Dance The Night Away El…" +(130 BPM, 3A, 4:35, likely an extended mix) and B1 had "The Goodfellas +Dance The Night Away" (130 BPM, 2A, 3:37). Same song, different edits, mixed +into each other: exactly the "same song, different edit" case below. The +two versions also show different keys (3A vs 2A), so check whether one key +reading is wrong. The status bar showed "Dirty Talk (CK Party Starter) Dirty +removed from edm · mixing next now", so Dislike/removal itself worked. + +**Likely causes** in `crates/amp-core/src/show.rs::ranked_candidates()`: +1. The current song is excluded by **index** (`Some(i) != current`), not by + identity. If the same song appears at another index, or `current` is + `None` / the list changed while playing, it can be chosen again. +2. `song_id()` is path-based, so duplicate files of the same audio, or the + same song in another folder or edit, bypass the recent-repeat filter. + +**Fix:** +- Exclude the currently playing and currently loaded songs by identity in + every selection path: desktop, server `radio.rs`, Android + `DjEngine`/`PhoneSmartRules`, `smart::order` and the new bounded + reordering pass. +- "Same song" = same audio hash, OR same normalized artist + title + (ignore case, "feat.", and bracketed mix/edit labels). A different edit + of the same song counts as a repeat for the recent filter. +- Never allow the current song as a candidate, even when the recent + fallback relaxes. If it is the only candidate, stop or use the configured + fallback, and log why. +- Repeats a user deliberately placed in a regular playlist stay allowed, + but never back-to-back. + +**Tests (must fail before the fix):** same file at two indices; two paths +with identical audio hash; "Song (Radio Edit)" vs "Song (Extended Mix)" by +the same artist inside the recent window; `current = None` with the playing +song in the list; matching Android parity tests. + +--- + +## Task 23 — Transition log and "Flag last transition" button + +The owner can't always catch song names, so problems need to be recorded +automatically. + +**Do:** +- Record every Auto Mix transition: time, outgoing and incoming song + (title, artist, file path, song ID), style, target vs actual energy, + entry/exit points, gain applied to each deck, and why the incoming song + was chosen (top candidates and scores). +- "Flag last transition" button on desktop, Android and Remote (Companion + action later). One press marks the most recent transition as bad, with an + optional quick reason: repeat song / beats off / bad timing / volume jump / + energy jump / vocal clash. +- Keep the last 500 transitions; export flagged ones as a JSON/CSV report. +- Read-only: logging and flagging never change songs, cues or preparation. + +**Acceptance:** after 10 transitions and 2 flags, the export lists exactly +those 2 with all fields filled; the log survives an app restart. + +--- + +## Task 24 — Volume normalization still uneven + +Heard on RC34: levels between songs are still a little off. +Code: `crates/amp-core/src/loudness.rs::auto_gain_db` (target −14 LUFS), +`apps/amp-player/src/live_mix.rs` and `apps/amp-cast/src/{radio,studio}.rs` +(ffmpeg `loudnorm I=-16`). + +**Problems and fixes:** +1. **Peak cap blocks boosting quiet, dynamic songs.** Gain is + `min(-14 - LUFS, -1 - true_peak)`, so a -18 LUFS song with peaks near + 0 dBTP gets almost no boost and stays ~4 LU quieter. Boost to the target + and let a true-peak look-ahead limiter on the deck/master catch peaks. + Keep a max boost (e.g. +9 dB) and report heavy limiting in the log. +2. **Whole-song loudness is skewed by long quiet intros/breakdowns.** + Measure loudness for mixing on the main sections (e.g. loudness of the + upper half of sections by energy, from the RC34 section data). Keep + whole-song LUFS stored for display. +3. **Double normalization on streams.** Server/Cast/live broadcast applies + real-time `loudnorm` (−16) on top of the deck gain (−14), which can pump + around transitions. Use one target everywhere, and replace real-time + `loudnorm` on already-normalized DJ output with a plain limiter + (keep `loudnorm` only for sources that have no analysis). +4. **Unanalyzed songs get 0 dB.** Measure loudness quickly on load (or + before a song is chosen by Auto Mix) when it is missing, and prefer + analyzed songs for automatic selection. +5. Single configurable target (default −14 LUFS) shared by desktop, + server, Android and streams. + +**Acceptance:** +- Test set: a modern loud master, a dynamic older recording, a track with a + long quiet intro, and an unanalyzed file. Played through Auto Mix, the + main sections of all four measure within ±1 LU of each other (short-term + loudness), with no true peak above −1 dBTP. +- Stream path: loudness of the server stream across 10 transitions stays + within ±1 LU, without pumping at the transition points. +- Saved trims and manual gain stay respected. + +--- + +## Task 25 — Explicit songs get into Auto Mix + +Heard on RC34: a very explicit track ("The Goodfellas Haven't You Heard +Of L…", artist missing, 128 BPM 12A) played in Auto Mix. + +**Current behavior:** `crates/amp-core/src/content_advisory.rs` only knows a +song is explicit from an embedded iTunes-style ParentalAdvisory tag or a +manual setting. Most MP3s have neither, so they are `Unknown`. The smart +filter "Clean / non-explicit (known clean only)" exists, but a playlist only +gets it if the user adds it, and it excludes every `Unknown` song. + +**Fix:** +1. **Quick marking:** a "Mark explicit" / "Mark clean" action on the deck + (next to Dislike), in the library list (multi-select and whole folder), + on Android and Remote, and as a Flag reason in Task 23. Marking a song + playing on air also lets Auto Mix fade it out early if the playlist + requires clean songs. +2. **Name hints:** treat "(Dirty)", "(Explicit)", "[Explicit]" in title or + file name as Explicit; "(Clean)", "(Radio Edit)", "(Clean Edit)" as a + Clean hint. Hints are proposals the user can confirm in bulk. +3. **Automatic detection (optional analysis add-on):** run local + speech-to-text (e.g. a Whisper model via ONNX) on the vocal stem, check + against a profanity word list, and store Explicit/Clean with a confidence + and the timestamps of matches. No cloud upload. Results are proposals; + manual choices always win. +4. **Playlist policy per style/use:** each smart playlist gets a content + setting: Any / Avoid explicit (skip Explicit, allow Unknown) / Clean only + (known clean). Defaults: Meeting, Walk-In, Recognition, Background, + Everyday = Avoid explicit; Party = Any. Apply on desktop, server and + Android. +5. Show an "E" badge on decks and library rows; show the count of Unknown + songs per playlist so the user knows what still needs checking. + +**Acceptance:** a playlist set to Avoid explicit never selects a song marked +Explicit (desktop, server, Android tests); marking the on-air song Explicit +in a Clean-only playlist triggers a fade to the next song; detection on a +known explicit test clip proposes Explicit with timestamps and never +overwrites a manual Clean. + +--- + +## Task 26 — DJ screen layout: fill the space, readable song names + +Owner request after using RC34 (desktop DJ view). + +**Do:** +1. **Remove the empty space** to the sides of the main decks (A and B) and + between the decks, the level meters and the side panels. Use the full + window width. +2. **Main decks slightly larger:** give the freed space to the two main + deck panels (platter, title area and controls scale up a little). +3. **Mini decks bigger:** the side decks (A1/A3, B2/B3 panels on the left + and right) grow to fill the remaining space; title, time, Play/Sync/Loop + and the deck button must be easy to read and press. +4. **Scrolling song names:** when a title or artist doesn't fit, scroll it + (marquee) instead of cutting it off with "…". Pause briefly at the start, + scroll smoothly, loop. Apply to main decks, mini decks, the Player and the + library "now playing" line. Hovering shows the full name as a tooltip. + No scrolling when the text fits. +5. Must still work at the smallest supported window size and on a + 1920×1080 screen; no overlapping controls. Respect Windows display + scaling (100–150%). +6. UI-only change: no change to audio, mixing or saved data. + +**Acceptance:** screenshots at 1280×720, 1920×1080 and 2560×1440 show no +large empty side margins, larger main and mini decks, and a long title that +scrolls fully. Existing UI tests pass. + +--- + +## Task 28 — More DJ information on screen for manual mixing + +Owner feedback: the DJ screen doesn't show enough to mix by hand, compared +with djay Pro 6. Do the parts that use data AMP already has now; the parts +that need Task 7 sections plug in when Task 7 lands (see also Task 9). +Works together with the Task 26 layout change; keep the screen readable. + +**Now (existing data):** +1. **Big time display per deck:** remaining time large (e.g. "-3:42"), + elapsed smaller; flash in the last 30 s. Today's "00:03 / 04:35" is too + small. +2. **Key match between decks:** show each deck's key in Camelot with a + color: green = compatible (same, ±1, relative), amber = energy-boost + jump (+2/+7), red = clash. Show the key at the current position once + fluid key (Task 8) exists. +3. **Tempo match:** each deck's current BPM (after pitch) and the + difference to the other deck ("+1.5 BPM / +1.2%"), with a one-tap + match. +4. **Beat phase meter:** a bar under the waveforms showing whether the + decks' beats line up (how many ms or fractions of a beat apart), plus + a 1-2-3-4 beat counter per deck. +5. **Energy:** current energy level (1–10) per deck and the next section's + energy (from RC34 section data), with a small energy curve on the + overview waveform. +6. **Zoomed waveforms with beat grid:** scrolling, zoomable waveforms for + both decks stacked, with beat and bar lines (bar lines stronger), cue + and loop markers, and the current playhead aligned in the middle. +7. **Readable section labels on the overview waveform:** today the labels + (e.g. "energy drop") are tiny and overlap the waveform. Draw them as a + colored strip above the waveform with readable text. +8. **Cue markers with names** on both the overview and zoomed waveforms; + hot cue pads show the cue name and its bar position. + +**After Task 7 (sections with labels and bar counts):** +9. Color-coded sections (intro/verse/pre/chorus/build/drop/break/outro) + with bar counts, user-customizable colors. +10. Bar countdown: "Chorus · 8 bars · 3 left" per deck and on the platter + ring, plus a phrase strip that shows both decks' sections lined up in + time (Task 9 phrase sync uses the same strip). + +**Beat-grid review in Library (blocking — do this part first):** +The owner can't see where beats and phrases are on the current waveform, so +he can't confirm a grid or pick mix points. That also blocks Auto Mix +tricks, which need a reviewed/reliable grid (Task 29). +11. A grid editor view in Library: large, zoomable, scrollable waveform + colored by frequency (low/mid/high) so kicks and snares stand out + clearly, with beat lines and stronger bar lines drawn over it. +12. Controls: play/scrub with a metronome click on the grid, "set bar 1 + here" at the playhead, nudge grid left/right (fine steps), BPM ×2 / ÷2, + tap tempo, and a "Grid looks right → mark reviewed" button. +13. Show the grid status per song in Library lists (reliable / estimated / + reviewed / none), with a filter for "needs grid review" and a playlist + batch view so the owner can step through songs quickly. +14. Saving marks the grid as reviewed (`analysis.reviewed` / manual + override) without touching cues, regions or other preparation. + +**Also:** show the meaning of the red X icon next to titles (or replace it +with a clear label, e.g. "Not analyzed", "Analysis failed", "No artwork"). + +**Acceptance:** with two analyzed songs loaded, a screenshot shows remaining +time, key match color, BPM difference, beat phase, energy and beat-gridded +zoomed waveforms, all readable at 1920×1080. UI-only for items 1–8: no change +to audio, mixing or saved data. + +--- + +## Task 29 — Auto Mix tricks almost never play (bug) + +Owner report on RC34: the current trick transitions don't kick in. Code +review of `apps/amp-player/src/performance.rs` and `transition_styles.rs` +found these causes: + +1. **Scratch never runs in Auto DJ.** The scratch bridge requires + `!self.run.auto` (`bridge_needed`), and the Auto DJ `effect_plan` has no + Scratch branch. When the rotation picks Scratch in Auto DJ, nothing + happens and the slot becomes a plain fade. +2. **Almost every trick needs a "reliable" beat grid on the outgoing song.** + Stutter, Brake, Filter and Bass swap all go through + `timing_reliable(outgoing)`; Scratch/Stutter/LoopBuild/Beatmatch also + need it on the incoming song. `timing_reliable` requires + `rhythm_quality.stable == true` with ≥ 3 windows and confidence ≥ 0.5 + (or a reviewed/manual grid). Many library songs probably fail this, so + the trick is silently dropped. Brake and Filter don't need a precise grid + and should fall back to a BPM-only or time-based version. +3. **Fixed rotation with no fallback.** A trick is attempted only on every + Nth completed handoff (default 4), the type is chosen by a fixed rotation + index, and if that one type fails its checks the transition is a plain + fade. It never tries another enabled trick that would work. +4. **Other silent skips:** Dislike/feedback skips, Mix Now/immediate + transitions and the `safe` check (outgoing must still be playing, not + looping, > 0.9 s remaining) also drop the trick, with no log entry. + +**Fix:** +- Add a Scratch branch to the Auto DJ path (Task 27 adds the real patterns; + for now, run the existing scratch-in when Scratch is chosen in Auto DJ). +- When the chosen trick can't run, try the other enabled tricks whose + requirements are met before falling back to a fade; keep the "every N" + spacing. +- Brake, Filter and echo-style tricks work with BPM only (or no grid) using + time-based lengths; only beat-synced tricks need the reliable grid. +- Log every trick decision in the Task 23 transition log: chosen trick, or + the exact reason it was skipped (grid unreliable on outgoing/incoming, + not the Nth mix, feedback skip, unsafe position, missing stems). +- Show in DJ Settings how many songs in the current playlist have a + reliable grid, with a "Review grid" shortcut. + +**Acceptance:** with every = 1 and all tricks enabled, a 10-transition Auto +DJ run on songs with reliable grids uses a trick on every transition; on +songs without reliable grids, Brake/Filter still happen and beat-synced +tricks are logged as skipped with the reason; Scratch plays in Auto DJ. + +--- + +# Task 0 — Split the giant files (no behavior change) + +**Where:** `apps/amp-player/src/mixer.rs` (~5.9k lines), `main.rs` (~5.6k), +`performance.rs` (~5k). + +**Do:** +1. `mixer.rs` → `mixer/` module: audio render/callback path, deck state, + sampler voices, output device setup, crossfade/fade math, tests. +2. `performance.rs` → `performance/` module: Auto Mix orchestration, + transition scheduling, progression/energy arc, Companion/show actions, + tests. +3. `main.rs` → keep app startup and top-level wiring only; move each + screen/panel (player, DJ, library, sampler, settings, lab entry) into its + own file. +4. Pure moves and visibility changes only: no renamed behavior, no logic + edits, no new features in the same PR. Keep public APIs used by + `control.rs`, Android JNI and the server unchanged. +5. Keep the lock-free audio path exactly as it is (no new locks, allocations + or logging in the render callback). + +**Acceptance:** +- Full workspace tests, strict Clippy and the rendered-audio transition + checks pass with the same results before and after. +- No new file over ~1,500 lines. +- One PR, merged before Task 7 starts. + +--- + +# Part 1 — Auto Mix energy fixes (done in RC34) + +Review of `gitwide-cloud/amp-verse` at commit `e314628` (v1.1.0-rc.33). +Do the tasks in order: 1 and 2 are small and the later tasks depend on them. +Each task keeps the project's existing rules: never rewrite manual/reviewed +preparation, propose reanalysis results separately, no GPL or neural-model +dependencies in the base player, strict Clippy and workspace tests pass. + +--- + +## Task 1 — Section energy is ignored during ranking (bug) + +**Where:** `crates/amp-core/src/show.rs` (candidate `score` closure, ~line 502–530), +`crates/amp-core/src/smart.rs::energy`. + +**Problem:** The scorer computes the incoming entry section's energy and writes +it to `prepared.extensions["energy"]`, then calls `smart::cost`. But +`smart::energy()` reads `perceptual_energy` first and only falls back to +`energy`. For every analyzed track (anything with loudness), the section value +is discarded and ranking uses the whole-track number instead. + +**Fix:** Pass the entry energy into the cost explicitly instead of smuggling it +through `extensions`. For example, add `smart::cost_with_entry(a, b, target, +b_entry_energy: Option)` and use the entry value when present, the +track value otherwise. Do not mutate the cloned preparation's `energy` key. + +**Acceptance:** +- New unit test: two candidates with identical `perceptual_energy`, but + different entry-section energy; the one whose entry section is closer to the + target ranks first. +- Existing `show.rs` tests still pass. + +--- + +## Task 2 — Put track and section energy on one normalized scale + +**Where:** `crates/amp-core/src/energy_profile.rs::build`, +`crates/amp-core/src/analysis.rs` (`result()` and the decode loop), +`crates/amp-core/src/perceptual_energy.rs`. + +**Problem:** Two different measurements are compared as if they were one: +- `perceptual_energy` (track level, used as the *target*) = onset flux on a + -14 LUFS normalized envelope. +- `energy_profile` sections (the thing matched *against* the target) = raw RMS + in dB, mapped -48..-6 dB → 0..1, with **no** loudness normalization. +- The legacy `energy` key uses the same un-normalized RMS dB. + +Result: section energy follows mastering loudness (a loud pop ballad can +outscore quietly mastered techno), and a target from one scale is matched to +sections on another. + +**Fix:** +1. Pass `integrated_lufs` into `energy_profile::build` and apply the same gain + `10^((-14 - lufs) / 20)` to the RMS before converting to dB. +2. Compute section energy with the same function used for track energy + (factor the scoring out of `perceptual_energy::from_rms` so it can run on a + slice). Track energy should equal the duration-weighted section mean (or be + derived from the same features), so target and sections are comparable. +3. Bump `Profile.version` to 2 and the engine ID to `amp-prep-heuristic-6`. + Version-1 profiles must still load (treat as legacy, lower confidence); + do not trigger unsolicited library reanalysis. +4. Check the other readers of these values still behave: + `hype_sections.rs`, `dj_phrasing.rs`, `transition_plan.rs`, + `smart_filters.rs`, `review.rs`, `apps/amp-cast/src/radio.rs`, + `apps/amp-player/src/{preparer,waveform,section_controls,performance}.rs`, + Android `DjEngine.java` and `PhoneSmartRules.java`. + +**Acceptance:** +- Test: the same synthetic track rendered at two gains (e.g. +6 dB) produces + section energies within 0.01 of each other (mirror the existing + `f07_mastering_gain_does_not_change_rhythmic_energy` test). +- Test: a sustained loud pad scores lower than a quieter, percussive loop at + section level, not only at track level. + +--- + +## Task 3 — Richer energy features (closer to Flow / Mixed In Key behavior) + +**Where:** decode loop in `crates/amp-core/src/analysis.rs`, new module +e.g. `crates/amp-core/src/energy_features.rs`. + +**Problem:** Energy uses only full-band RMS and a second-difference onset proxy. +Perceived dance-floor energy mostly follows drum density, bass weight and +brightness. + +**Fix:** Per analysis block (and aggregated per section), compute on the +loudness-normalized signal: +- **Low band (≈30–150 Hz)** energy and onset rate → kick/bass drive. +- **High band (≈5–11 kHz at the 11.025 kHz rate, i.e. up to Nyquist)** onset + density → hats/percussion. +- **Spectral centroid** → brightness. +- **Spectral flux** (positive, full band) → busy-ness. +- Normalized loudness (from Task 2). + +Combine into one 0..1 score with documented weights (start roughly: +low 0.30, onset density 0.25, flux 0.20, centroid 0.10, loudness 0.15) and +expose the individual features in the profile for debugging. Keep the weights +in one constant table so they can be tuned. + +**Acceptance:** +- Synthetic tests: (a) kick + hats loop > pad of equal loudness; + (b) adding a four-on-the-floor kick to a pad raises energy; + (c) breakdown section (kick removed) scores lower than the drop around it. +- Run on the supplied real MP3s used in earlier validation and log the 1–10 + values per section for a listening check. +- Note: Mixed In Key's energy method is patented/proprietary. Implement from + the generic features above, not by imitating their scale's internals. + +--- + +## Task 4 — Find real section boundaries instead of fixed 16-beat blocks + +**Where:** `energy_profile::build`, `crates/amp-core/src/rhythm.rs`, +`crates/amp-core/src/energy_cues.rs`. + +**Problem:** Sections are fixed 16-beat blocks starting from a beat offset that +the docs say is not a verified downbeat, so boundaries can fall mid-phrase. +Breakdown/drop candidates come from relative energy only. + +**Fix:** +1. Build a per-beat (or per-bar) feature vector: chroma (already computed), + Task 3 band energies, spectral centroid. +2. Compute a self-similarity matrix and a checkerboard-kernel novelty curve + (Foote method); peak-pick boundaries. +3. Snap boundaries to the nearest 8-, 16- or 32-bar position when the grid is + stable (`rhythm_quality.stable`), otherwise keep exact audio time. +4. Downbeat estimate: score each of the 4 beat phases by low-band onset + strength + novelty peaks and pick the best; store confidence and leave it + unknown when confidence is low. +5. Keep the current fixed-block sections as the fallback when the novelty + curve has no clear peaks. + +**Acceptance:** +- Synthetic test: a track built as 32 bars low energy → 32 bars high → + 16 bars low returns boundaries within one beat of bars 33 and 65. +- Test: a 1-beat offset error in the input grid does not move boundaries off + the true change by more than one beat. +- Reference: Zehren et al., "Automatic Detection of Cue Points for DJ Mixing" + (arXiv 2007.08411) and the switch-point follow-up (MDPI Signals 2024). + +--- + +## Task 5 — Give each mix style an energy arc + +**Where:** `crates/amp-core/src/smart.rs::order`, +`crates/amp-dj-policy/src/lib.rs::pair_cost`/`pair_cost_with_context`, +`crates/amp-core/src/show.rs` (`target_energy`, `Style`). + +**Problem:** `smart::order` is greedy nearest-neighbor, and its `target` stays +fixed at the first song's energy for the whole run. The energy penalty is +linear (`|Δ| × 4` plus `|target − b| × 6`), so a 3-level jump costs only 3× +a 1-level jump. + +**Fix:** +1. Define a target curve per style as a function of set progress (0..1), + in 1–10 units, e.g.: + - **Chill:** 3 → 5 → 4 + - **Steady:** 5 → 6 → 6 → 5 + - **Hype:** 5 → 7 → 8–9 peak around 70% → 7 + Progress = elapsed time / planned duration, or song index / count. +2. Use the curve value at each step as `target` instead of the first song's + energy. Server stations without a planned length use elapsed time with a + loop. +3. Change the jump penalty to be gentle within ±1 level (0.111 on the 0..1 + scale) and steep above it (e.g. quadratic beyond 1 level). +4. Optional: replace greedy ordering with a short beam search (width 4–8) + over the next 3 songs so one good pick doesn't strand the set. + +**Acceptance:** +- Test: with a pool spanning levels 3–9, Hype ordering rises then falls with + no step bigger than 2 levels when a smaller step is available. +- Test: Steady keeps all steps within ±1 when the pool allows it. +- Existing curate/order permutation tests still pass. + +--- + +--- + +# Part 2 — TrackSense-style structure analysis (djay Pro 6 reference) + +Goal: know bar 1, every section, its label and its bar count, then build the +DJ features on that. Reference behavior: djay Pro 6 "TrackSense" (labeled, +color-coded sections with bar counts, fluid key, pre-trigger jumps, phrase +sync, bar countdown, section-based auto cues, phrase-aware Auto Mix). +Implement independently; no proprietary code or binaries. + +**Packaging rule for all of Part 2:** neural models ship as an **optional +analysis add-on** (same pattern as stems), never in the base player. Base +player must keep working with the heuristic results from Part 1 when the +add-on is missing. Results go into preparation as proposals; manual and +reviewed data stay protected. Bump the engine ID (e.g. `amp-prep-structure-1`) +and do not trigger unsolicited library reanalysis. + +--- + +## Task 6 — Neural beat and downbeat grid + +**Where:** new crate e.g. `crates/amp-structure` (feature-gated), wired into +`crates/amp-core/src/analysis.rs` / `analysis_queue.rs` and the optional engine. + +**Do:** +1. Run **Beat This!** (CPJKU/beat_this, MIT, ISMIR 2024) from Rust via the + `ort` crate using an ONNX export of the `final0` checkpoint. Input is a + 128-bin log-mel spectrogram; output is frame-wise beat and downbeat + logits at 50 fps. Match the reference preprocessing exactly and verify + against the Python package on a few test files (beat times within 10 ms). +2. Store a **variable** beat list and downbeat list (not just constant BPM + + offset). Keep the existing constant `bpm` as the median for display and + ranking. +3. Derive meter (beats per bar) and a per-bar confidence. Low confidence → + keep the Part 1 heuristic grid and mark it unverified. +4. Update `rhythm_quality` to report downbeat confidence; make the cue/grid + snapping in `rhythm.rs` and `energy_cues.rs` use downbeats when available. + +**Acceptance:** downbeat F-measure reported on a small hand-annotated set +(10–20 of the user's own tracks, mixed genres); grid stays phase-locked +through a whole song with a tempo drift (live drummer track). + +--- + +## Task 7 — Labeled sections with bar counts + +**Where:** `crates/amp-structure`, `energy_profile.rs` (Profile v3), +`apps/amp-player/src/{waveform,section_controls,preparer}.rs`. + +**Do:** +1. Run **All-In-One** (mir-aidj/all-in-one, `allin1`) for functional + segments. Its labels: start, end, intro, outro, break, bridge, inst, solo, + verse, chorus. Prefer an ONNX export run from Rust; if that is not feasible, + run it as a separate optional worker process (like `amp-stem-worker`) and + exchange JSON. Reuse its beats/downbeats to cross-check Task 6. +2. Snap every section boundary to the nearest downbeat; store `bars` per + section (odd lengths like 9, 10, 12 bars must survive — no forcing to 4/8/16). +3. **EDM layer** on top (heuristic, using Task 3 features): + - `build`: rising energy / onset density / high-band energy over the + 4–16 bars before a high-energy section. + - `drop`: section starting with a large energy jump after a `break` or + `build`, with strong low band. + - `pre_chorus`: short section (2–8 bars) directly before a `chorus` that + differs from the preceding verse. +4. Profile v3 section fields: `label`, `bars`, `start_bar`, `confidence`, + `source` (`model` / `heuristic` / `manual`). Older profiles still load. +5. UI: color sections by label (user-customizable colors), show label + bar + count, keep RGB waveform as an option. + +**Acceptance:** on the hand-annotated set, boundary hit rate within one beat +and label accuracy reported; a no-chorus track (e.g. a long rap verse) is not +forced to contain a chorus; a known 9-bar chorus is reported as 9 bars. + +--- + +## Task 8 — Fluid key (key changes over time) + +**Where:** `crates/amp-core/src/analysis_chroma.rs`, `analysis.rs`. + +**Do:** +1. Compute key per section (Task 7) and per 8-bar window using the existing + chroma pipeline. +2. Smooth with an HMM/Viterbi pass over the 24 keys with a high self- + transition probability, so the key only changes on sustained evidence and + preferably on section boundaries. +3. Store a `key_timeline` (start, end, Camelot key, confidence). Keep the + track-level key as the key of the longest stretch, not an average. +4. Use the key **at the actual transition point** in `amp-dj-policy` + harmonic cost (outgoing key at exit, incoming key at entry). + +**Acceptance:** synthetic test with a modulation up a semitone at bar 33 +reports two keys with the change within one bar; a steady-key track reports +one key. + +--- + +## Task 9 — Section-aware DJ controls + +**Where:** `apps/amp-player/src/{mixer,live_mix,transition_controls,hot_cues}.rs`, +`crates/amp-dj-policy/src/transition.rs`, Android `DjEngine.java` (via Remote). + +**Do:** +1. **Pre-trigger:** Shift+click a section to queue a jump that fires exactly + at the end of the current section (use the fixed-boundary scheduler from + `TRANSITION_LANDING.md`). Queued state blinks; click again to cancel. + Optional queued actions at the same boundary: stem mute pattern + (e.g. acapella), pause after section. +2. **Phrase sync button:** shift the incoming deck by whole beats so its next + section boundary lines up with the playing deck's next section boundary; + never move more than one section length. +3. **Bar countdown:** bars remaining in the current section and bars until the + next section, on the platter and above the waveforms; a phrase strip that + shows both decks' sections lined up in time. +4. **Auto cues from sections ("rules"):** rules like "N bars before first + verse", "start of first chorus", "intro start", with color/name and two + cue banks (A/B). Only fill songs that have no saved cues unless the user + chooses otherwise; never overwrite manual cues. +5. **Learn from playlist:** for a chosen playlist, measure where the user's + existing cues sit relative to sections (label + bar offset), keep patterns + that appear in most songs, and propose them as rules for review. + +**Acceptance:** pre-trigger fires on the boundary sample-accurately in the +render tests; phrase sync aligns boundaries within one beat; learn-from- +playlist reproduces a simple synthetic rule (8-bar, 4-bar, verse-start cues) +from 10 cued songs. + +--- + +## Task 10 — Phrase-aware Auto Mix + +**Where:** `crates/amp-core/src/{mix_schedule,transition_plan,show,dj_phrasing}.rs`, +`crates/amp-dj-policy`, `apps/amp-player/src/{performance,live_mix}.rs`. + +**Do:** +1. **Exit choice:** end the outgoing song at a labeled boundary (end of a + chorus, start of an outro/break), never mid-section, respecting the + Quick/Balanced/Full length settings. +2. **Entry choice:** start the incoming song so its target section + (verse/chorus/drop, by style) begins exactly at the outgoing exit; the + overlap uses the incoming intro bars. Pick crossfade length in bars + (4/8/16) to fit the intro, not a fixed number of seconds. +3. **Vocal clash avoidance:** if both decks have vocal sections overlapping + in the blend and stems are prepared, mute the outgoing vocal during the + overlap; without stems, prefer a shorter blend or an instrumental entry. +4. **Ordering:** add structure fit (does A have a clean exit that pairs with + B's intro length?) and key at the transition point (Task 8) to the + pair cost, alongside the energy arc from Task 5. +5. Keep every existing protection: manual cue-out/mix-out wins, saved cues + and preparation are never rewritten. + +**Acceptance:** render tests on synthetic labeled tracks show the incoming +target section starting on the outgoing exit boundary within one beat; a +listening log on 20 real transitions with pass/fail notes per transition. + +--- + +## Task 27 — Auto Mix DJ tricks that sound like a real DJ + +Owner request after watching djay Pro 6 demos with scratching. Builds on +Tasks 6–7 (downbeats and sections); do it after Task 10. + +**What exists today:** `apps/amp-player/src/transition_styles.rs` has +Scratch, Stutter, Tape brake, Filter sweep, Bass swap, Beatmatch, Loop +buildup, Stem handoff and Vocal/instrumental mashup. Auto DJ rotates through +the enabled ones every N mixes (default 4) and only when both beat grids are +confident. The scratch "flourish" is disabled for Auto DJ +(`performance.rs`: `!self.run.auto && chosen == Style::Scratch`). + +**Do:** +1. **Musical timing:** every trick starts and ends on the bar/phrase grid + (Task 6 downbeats, Task 7 section boundaries). Scratches and stutters + land on bar 1 or a section change; brakes and echo-outs finish exactly + on the incoming downbeat. +2. **Choose the trick by context, not rotation.** Score each enabled trick + per transition from: genre/tags, tempo gap, key compatibility, energy + direction, section types at exit/entry, stems availability and vocal + overlap. Examples: scratch-in for hip-hop/throwbacks around 85–105 BPM; + echo-out or tape brake when tempo or genre jumps too far to blend; bass + swap for EDM at matching tempo; mashup only when keys match and stems + are prepared; filter sweep into a build. Keep a short "recently used" + memory so the same trick doesn't repeat back-to-back. Log the chosen + trick and why in the Task 23 transition log. +3. **Real scratch patterns for Auto DJ:** baby, forward/chirp, transformer, + flare (1-click), and tear, defined as platter-motion curves plus + crossfader cut timing, scaled to the BPM, on the incoming or outgoing + track's chosen sample (a vocal hit or drum hit found from stems/onsets). + Enable the scratch flourish for Auto DJ when context allows. +4. **Record your own scratches:** record a scratch performance from the + Android vinyl scratch or desktop (platter motion + crossfader) and save it + as a reusable pattern Auto DJ can play at any tempo. +5. **New tricks:** echo-out (beat-synced 1/2, 3/4, 1 beat; optionally on + the vocal stem only), loop roll (1/2 → 1/4 → 1/8 beat), spinback/backspin, + and acapella-out/instrumental-in using stems. +6. **Per-mode intensity:** Meeting and Background = no tricks (clean blends + only), Everyday = rare and subtle (filter, echo), Party = frequent and + varied; owner can override per playlist. Recognition/Walk-In hits may use + a scratch-in or brake if enabled. +7. **Safety:** never apply a rhythmic trick without a confident grid; + respect manual cues and the Manual DJ Lock; no clipping (limiter after + effects); a failed trick falls back to a clean blend, never silence. + +**Acceptance:** +- Render tests: each trick starts/ends within 10 ms of the intended + bar/beat at 90, 128 and 174 BPM; output peaks stay under the limiter + ceiling. +- Selection tests: tempo gap > 8% never picks a beat-matched blend; + mismatched keys never pick a mashup; Meeting mode picks no tricks. +- A recorded user scratch pattern replays at 90 and 128 BPM in time. +- A 30-minute Party listening log with tricks noted, for owner review. + +--- + +# Part 3 — Meeting show control (replace AIMP + manual clips) — build last + +Context: the meeting machine runs the **desktop app** (amp-player) feeding a +mixer, controlled by Companion (Node-RED → OnTime → Companion → AMP Verse). +Roles: +- **Library** — where cue points and clip regions are set (used by Player and DJ). +- **Player** — instant intro/walk-up songs (replaces AIMP + hand-clipped files). +- **DJ** — pre-meeting mix, recognition mixing, background. +- **Lab** — clip maker for sound effects and sampler pads. + +The control network is closed/trusted; keep the current simple password model. +Build this part after the engines (Parts 1–2) and the LAN library (Part 4). + +--- + +## Task 11 — Intro regions in Library, instant playback in Player + +**Where:** `apps/amp-player/src/{preparer,main,control,session}.rs`, +`crates/amp-core/src/preparation.rs`, Companion module (`integrations/companion`). + +**Do:** +1. **Named regions** in Library: on any song, save one or more regions + (e.g. "Intro – Pedro", "Walk-up short") = start, end, fade-in, fade-out, + gain. Non-destructive: the source file is never cut. This replaces + hand-clipping files for AIMP. +2. **Player plays a region** start→end with its fades, then stops (or follows + the region's "after" setting: stop / hand back to DJ / next region). +3. **Armed state:** Companion `arm_intro` loads and pre-decodes a region into + memory so `fire_intro` is instant. Optional auto-arm of the next intro from + an ordered intro list (run sheet), so one button press is enough. +4. **Restart semantics:** firing an intro always starts from the region start; + a second press while playing does what the setting says (restart / ignore / + fade out). Never resume from a random position. +5. **Latency target:** press → audio at the output in under 100 ms for an armed + region. Add a test that measures command-accepted → first non-silent frame. +6. Companion: actions `arm_intro`, `fire_intro`, `stop_intro`, intro list + next/previous; feedback for armed (amber), playing (green), failed (red); + variables for armed region name and time remaining. + +**Acceptance:** an armed region plays within the latency target 50/50 times in +a loop test; fades and end point are sample-accurate in a render test; the +source audio hash is unchanged. + +--- + +## Task 12 — Player and DJ sharing the room + +**Where:** `apps/amp-player/src/{mixer,live_mix,monitor,performance}.rs`, settings. + +**Do:** +1. **Separate outputs (preferred):** let Player, DJ master and Sampler each + pick an output device and channel pair (e.g. Player → interface 1/2, + DJ → 3/4), so each lands on its own mixer channel. Default stays one + shared output. +2. **Software coordination (always on as a safety net):** when an intro fires, + the DJ automatically ducks or pauses (per-intro setting: duck level, + fade time, pause vs duck); when the intro ends, the DJ restores/resumes. + One Companion button = the whole sequence. +3. **Return-to-background:** after a recognition or intro moment, the DJ + resumes the previous playlist/style/energy automatically (an interrupt + stack), without anyone choosing the next song. +4. Emergency mute stays global across Player, DJ and Sampler. + +**Acceptance:** with a shared output, an intro over a running DJ mix never +plays both at full level; with separate outputs, each engine plays only on its +assigned channels; resume returns to the same playlist and energy. + +--- + +## Task 13 — Recognition and pre-meeting on the DJ + +**Where:** `apps/amp-player/src/performance.rs`, `crates/amp-core/src/show.rs`, +Companion module. + +**Do:** +1. **Recognition hit:** pre-load the assigned recognition songs so the mix-in + starts without waiting for decode. Land on the saved cue; if none, land on + the chorus/drop once Task 7 labels exist, play N bars, then hand back. +2. **Backup song:** if the assigned song is missing, unprepared or fails to + load, play a configured backup hype song instead of silence and turn the + Companion button red. +3. **Pre-meeting check:** one action that verifies every song/region/cue + referenced by Companion buttons, the intro list and show playlists: file + exists, prepared, cue/region valid, output device present. Result as one + green/red feedback plus a list of problems in the UI. +4. Merge `docs/COMPANION.md` (old generic-HTTP description) into the module + README so one document describes the current setup. + +**Acceptance:** pre-meeting check catches a deleted file, a renamed file and +an invalid cue in a test library; recognition with a missing song plays the +backup within two seconds. + +--- + +## Task 14 — Lab as clip and sampler maker + +**Where:** `apps/amp-player/src/{lab,lab_editor,lab_audio,sampler}.rs`, +Android `android/features/lab`. + +**Do:** +1. Lab exports a clip straight into the **sampler library** (name, color, + gain, trim, fades) without a manual file step. +2. Sampler banks assignable from Library and callable from Companion + (`sampler` pad action already exists — add bank select and feedback). +3. Import existing AIMP material: a folder or AIMP playlist of the hand-made + clips becomes a sampler bank or an intro list, so current Companion + buttons can be remapped quickly. + +--- + +## Task 15 — Remove YouTube and Suno download + +**Remove:** `apps/amp-player/src/{lab_youtube,lab_suno}.rs` and their wiring in +`lab.rs`, `lab_music_source.rs`, `main.rs`; Android `SunoImport.java`, +`UrlDownload.java` (+ `YouTubeUrl.java`, `ImportUrl.java` if only used for +this) and their tests (`SunoImportTest`, `UrlImportDeviceTest`); +`tools/setup_lab_youtube.py`, `tools/test_setup_lab_youtube.py`, +`tools/lab_youtube_fixture.rs`; the yt-dlp/Deno parts of +`tools/verify_music_import_engine.py`, `.github/workflows/music-import-engine.yml` +and `build.yml`; `docs/LAB_YOUTUBE.md`, `docs/SUNO_DOWNLOAD_RESEARCH.md`; the +yt-dlp/Deno sections of `THIRD_PARTY_NOTICES.md` and +`android/features/lab/assets/licenses/youtubedl-android`. + +**Keep:** Lab import from local files and recording. Existing clips the user +already made stay untouched. + +**Acceptance:** workspace builds and tests pass; `grep -ri "yt-dlp\|suno\|youtube"` +finds no remaining download code paths (docs/history mentions are fine). + +--- + +## Task 16 — Unattended reliability + +**Where:** whole desktop app, with priority on `mixer.rs`, `performance.rs`, +`main.rs`, `control.rs`. + +**Do:** +1. Audit `unwrap()`/`expect()` (~2,700 in amp-player). Replace those on + control, file, decode and network paths with errors that are logged and + shown; keep the lock-free audio path panic-free. +2. A bad file, missing network drive or dropped output device skips or + recovers; music never stops because of one failure. +3. The app auto-starts, keeps running minimized, and no modal dialog blocks + Companion commands. +4. 24-hour soak test: continuous Auto DJ + periodic intro/recognition + commands; report memory, handles, underruns and any stalls. +5. (Moved to Task 0 — file splitting.) + +--- + +# Part 4 — LAN music library ("iTunes, but on the LAN") and remote playing + +Goal: the server library is the home of the music, playlists and analysis. +Phones and computers on the LAN browse it, play or mix locally, download +playlists for offline use **with everything Auto Mix needs**, and any +computer can take over the room so a guest (RVP, family) plays their music +instead of the server. USB works as an offline delivery path too. + +Much of this is already specified in `docs/LIBRARY-LIVE-REMOTE.md` +("requirements, not a claim that all have passed"). Part 4 is about +**finishing and proving** those requirements, not redesigning them. Each task +starts by running the listed scenario on real devices and recording +pass/fail before changing code. + +--- + +## Task 17 — Acceptance run of the existing Library/Remote contract + +**Do:** turn every bullet of `docs/LIBRARY-LIVE-REMOTE.md` into a scripted +scenario (where possible automated, otherwise a written checklist) run on: +server (Windows or Linux), one Windows desktop, one Android phone, same LAN. +Record pass/fail with build number in a single `docs/ACCEPTANCE_LAN.md` +table. Fix failures in order of user impact: discovery/pairing → browse → +play → download offline → sync. + +**Acceptance:** the table exists, every row has a result, and all +discovery/browse/play rows pass. + +--- + +## Task 18 — Offline playlists that can Auto Mix with no server + +**Where:** Android `PlaylistSync.java`, `DjEngine.java`, `PhoneSmartRules.java`; +`apps/amp-cast/src/playlist_sync.rs`; `crates/amp-core` preparation export. + +**Do:** +1. Define one **offline bundle** per playlist: audio files + preparation + (BPM, beat/downbeat grid, key/key timeline, energy profile + sections, + cues/regions, loudness) + playlist order/rules, with a manifest of hashes + and the analysis engine version. +2. Android Auto Mix must use the bundle exactly as desktop would (same + `amp-dj-policy` via JNI, same profile version handling from Parts 1–2). +3. When the server has newer analysis for a downloaded song, the phone shows + "update available" and refreshes the analysis without re-downloading audio + when the audio hash is unchanged. +4. Airplane-mode test: download a playlist, disconnect, run Auto Mix through + the whole playlist. + +**Acceptance:** airplane-mode Auto Mix completes a 20-song playlist with +energy/key-based transitions; analysis-only refresh transfers no audio bytes. + +--- + +## Task 19 — Any LAN computer can take over the room + +Two ways a guest plays their own music through the room system: + +1. **Guest streams to the server (primary):** the guest runs AMP desktop (or + the Android app) and uses **Broadcast to server**. The server's output + switches from its own station to the guest's live Player/DJ master + (`live_dj` source already exists). Must have: one clear "Take over room" + button, a visible "Now playing from: " on the server UI and + Remote, and an owner override ("Return to server music"). +2. **Guest's music played by the server:** the guest shares a playlist from + their device; the server pulls the songs (temporary, not added to the main + library unless the owner approves) and Auto Mixes them. + +**Do:** +- Smooth switch: when a guest takes over, fade the server station out and + the guest in (no gap, no double audio); on return, fade back to the + server's previous playlist/energy. +- If the guest's stream drops (Wi-Fi, laptop sleeps), fall back to server + music within a few seconds instead of silence. +- Latency/buffer setting so guest audio stays stable on Wi-Fi. +- Guests never get library editing rights; take-over can be allowed per + paired device (owner approves a device once). + +**Acceptance:** guest laptop takes over and returns 20 times without a +silent gap > 1 s or overlapping audio; pulling the guest's network cable +falls back to server music within 5 s. + +--- + +## Task 20 — USB as an offline path + +**Do:** +1. **Export to USB:** pick playlists → write a portable library to a USB + drive (audio + preparation + playlists + manifest), same bundle format as + Task 18. Incremental: only changed files are rewritten. +2. **Play from USB:** desktop and server can open a USB library read-only + and Player/DJ/Auto Mix it with no network and no import. +3. **Import from USB:** optionally copy a USB library into the server + library, reusing existing songs by audio hash (no duplicates) and keeping + the USB's cues as a proposal when the server already has preparation. +4. Android: open a USB-OTG library read-only (if the device supports it). + +**Acceptance:** export → unplug → plug into another computer → Auto Mix plays +the playlist with cues and analysis intact; re-export after one change +rewrites only that song's files. + +--- + +## Task 21 — Library ingestion from the separate downloader + +The MP3 downloader is a separate app. AMP only needs a clean drop-off point. + +**Do:** +1. Watched **Inbox** folder on the server library: new files are hashed, + deduplicated against the library, tagged via the existing MusicBrainz + lookup (plus AcoustID fingerprint when tags are missing), moved to + `Artist/Album/Artist - Title.ext`, and queued for analysis. +2. Never overwrite or rename a file that already has preparation or is + referenced by a playlist/cue/Companion button; renames go through the + library so song IDs are updated everywhere. +3. A review list for files that could not be identified. + +**Acceptance:** dropping the same song twice leaves one copy; an +unidentified file lands in the review list, not in a random folder. + +--- + +## Out of scope +- Spotify-style recommendations (needs data access an independent app is + unlikely to get). +- New stem-separation models or stem effects. +- Stronger network security for the control API (closed network by design). +- Any change that rewrites saved cues, manual overrides or reviewed preparation. diff --git a/docs/GRID_REVIEW.md b/docs/GRID_REVIEW.md new file mode 100644 index 00000000..cb5f388f --- /dev/null +++ b/docs/GRID_REVIEW.md @@ -0,0 +1,35 @@ +# Library beat-grid review (Task 28, items 11–14) + +Source candidate only; not included in the published RC34 downloads. + +Open Library → Review beat grid on a selected song, or use Review grids in +these results / Review playlist grids. The latter includes regular and Smart +Playlists. Previous/Next skips songs that are no longer available. + +The overview jumps through the recording. The large waveform supports click, +drag and wheel scrubbing, zoom and Earlier/Later navigation. Low, mid and high +frequency content is colored red, green and blue; gold lines mark 4/4 bars. +These bars are a constant-tempo editing grid, not neural meter detection. + +Play preview auditions an independent original-audio decoder. The optional +metronome follows source samples in that decoder's render callback. Library +preview stops when Player/DJ, live casting, another preview or another Library +owns the output. It does not load or move any live deck. + +Set bar 1 at the playhead, adjust BPM (including ×2/÷2 or tapping), and nudge +the grid by 1 or 10 ms. Then choose **Grid looks right → mark reviewed**. +Saving checks that the preparation has not changed since opening; only tempo, +beat phase and bar/phrase anchors are copied into the saved preparation. +Existing cues, regions, tags, energy and proposals are retained. The audio +file is never rewritten, and existing playing-deck snapshots stay unchanged. + +Library rows show None / Estimated / Reliable / Reviewed. Needs grid review +filters None and Estimated. Existing manual/reviewed grids retain their legacy +status. A newly edited grid is explicitly unreviewed until approved. + +Closing retains an unsaved grid draft. Reopening another song asks the user to +save or discard that draft. Switching Library suspends the editor and refuses +any save into a different catalog. + +Validation is tracked in the draft PR. Physical listening and desktop visual +acceptance must be recorded separately from pure math/render or fixture tests. From 9ca84fc9e9fbcd5d6c35007544b9379b25bc4d1c Mon Sep 17 00:00:00 2001 From: gitwide-cloud Date: Thu, 3 Dec 2026 15:37:05 -0800 Subject: [PATCH 3/4] Save grid corrections atomically while preserving independent cue edits --- apps/amp-player/src/grid_editor.rs | 341 ++++++++++++++++------------ apps/amp-player/src/main.rs | 13 +- apps/amp-player/src/mixer.rs | 20 +- apps/amp-player/src/preparer.rs | 5 +- apps/amp-player/src/waveform.rs | 4 +- crates/amp-core/src/lib.rs | 2 +- crates/amp-core/src/mix_schedule.rs | 2 +- crates/amp-core/src/preparation.rs | 34 ++- 8 files changed, 263 insertions(+), 158 deletions(-) diff --git a/apps/amp-player/src/grid_editor.rs b/apps/amp-player/src/grid_editor.rs index fa0d5b20..a479eb23 100644 --- a/apps/amp-player/src/grid_editor.rs +++ b/apps/amp-player/src/grid_editor.rs @@ -31,141 +31,6 @@ pub struct Editor { dirty: bool, } -#[cfg(test)] -mod tests { - use super::*; - fn fixture() -> (tempfile::TempDir, Library, Editor) { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("one.wav"), b"audio fixture").unwrap(); - let mut p = Preparation { - bpm: Some(120.), - beat_offset: Some(0.2), - cue_in: 8., - cue_out: Some(90.), - ..Default::default() - }; - p.manual_cues.push(preparation::Cue { - id: "owner-cue".into(), - label: "Keep this cue".into(), - seconds: 16., - ..Default::default() - }); - p.extensions - .insert("regions".into(), serde_json::json!([{"start":8,"end":12}])); - preparation::save(dir.path(), Path::new("one.wav"), &p).unwrap(); - let lib = amp_core::scan(dir.path()).unwrap(); - let mut editor = Editor::default(); - editor.select(dir.path(), &lib.tracks[0], vec!["one.wav".into()]); - (dir, lib, editor) - } - #[test] - fn review_persists_grid_without_cue_or_audio_changes() { - let (dir, mut library, mut editor) = fixture(); - let before = preparation::load(&dir.path().join("one.wav")).unwrap(); - grid_review::set_bar_one(&mut editor.draft, 4.125).unwrap(); - editor.dirty = true; - assert_eq!( - preparation::load(&dir.path().join("one.wav")).unwrap(), - before - ); - editor.save(dir.path(), &mut library).unwrap(); - let saved = preparation::load(&dir.path().join("one.wav")).unwrap(); - assert_eq!(grid_review::status(&saved), grid_review::Status::Reviewed); - assert_eq!(saved.manual_cues, before.manual_cues); - assert_eq!(saved.cue_in, before.cue_in); - assert_eq!(saved.cue_out, before.cue_out); - assert_eq!(saved.extensions["regions"], before.extensions["regions"]); - assert_eq!( - std::fs::read(dir.path().join("one.wav")).unwrap(), - b"audio fixture" - ); - assert_eq!( - grid_review::status(&library.tracks[0].preparation), - grid_review::Status::Reviewed - ); - assert!(!editor.dirty); - assert!(editor.audio.is_none()); - } - #[test] - fn concurrent_preparation_save_is_not_overwritten() { - let (dir, mut library, mut editor) = fixture(); - let mut other = editor.original.clone(); - other.cue_in = 22.; - preparation::save(dir.path(), Path::new("one.wav"), &other).unwrap(); - grid_review::set_bar_one(&mut editor.draft, 3.).unwrap(); - editor.dirty = true; - assert!(editor.save(dir.path(), &mut library).is_err()); - assert!(editor.dirty); - assert_eq!( - preparation::load(&dir.path().join("one.wav")) - .unwrap() - .cue_in, - 22. - ); - } - #[test] - fn closing_and_reopening_retains_unsaved_grid() { - let (dir, library, mut editor) = fixture(); - grid_review::set_bar_one(&mut editor.draft, 3.).unwrap(); - editor.dirty = true; - editor.open = false; - editor.select(dir.path(), &library.tracks[0], vec![]); - assert!(editor.open && editor.dirty); - assert_eq!( - editor.draft.extensions["mix_bar_anchor"], - serde_json::json!(3.) - ); - } - #[test] - fn opening_after_another_clients_save_uses_the_fresh_grid() { - let (dir, mut library, mut editor) = fixture(); - let mut fresh = editor.original.clone(); - grid_review::tempo(&mut fresh, 128.).unwrap(); - grid_review::set_bar_one(&mut fresh, 6.).unwrap(); - preparation::save(dir.path(), Path::new("one.wav"), &fresh).unwrap(); - editor.select(dir.path(), &library.tracks[0], vec![]); - assert_eq!(editor.draft.bpm, Some(128.)); - assert_eq!( - editor.draft.extensions["mix_bar_anchor"], - serde_json::json!(6.) - ); - editor.save(dir.path(), &mut library).unwrap(); - let saved = preparation::load(&dir.path().join("one.wav")).unwrap(); - assert_eq!(saved.bpm, Some(128.)); - assert_eq!(saved.extensions["mix_bar_anchor"], serde_json::json!(6.)); - } - #[test] - fn switching_libraries_cannot_write_the_previous_songs_grid() { - let (dir, _, mut editor) = fixture(); - let (other, mut other_library, _) = fixture(); - let before = preparation::load(&dir.path().join("one.wav")).unwrap(); - let other_before = other_library.tracks[0].preparation.clone(); - grid_review::set_bar_one(&mut editor.draft, 9.).unwrap(); - assert!(editor.save(other.path(), &mut other_library).is_err()); - assert_eq!( - preparation::load(&dir.path().join("one.wav")).unwrap(), - before - ); - assert_eq!(other_library.tracks[0].preparation, other_before); - } - #[test] - fn playlist_navigation_skips_missing_entries() { - let (_, mut library, mut editor) = fixture(); - let mut next = library.tracks[0].clone(); - next.path = "three.wav".into(); - library.tracks.push(next); - editor.batch = vec!["one.wav".into(), "missing.wav".into(), "three.wav".into()]; - assert_eq!( - editor.neighbor(&library, 0, true).unwrap().path, - Path::new("three.wav") - ); - assert_eq!( - editor.neighbor(&library, 2, false).unwrap().path, - Path::new("one.wav") - ); - assert!(editor.neighbor(&library, 2, true).is_none()); - } -} impl Editor { pub fn select(&mut self, root: &Path, track: &Track, batch: Vec) { if self.dirty { @@ -275,7 +140,7 @@ impl Editor { return Err("Return to this song's Library before saving its grid".into()); } let approved = grid_review::approve(&self.original, &self.draft)?; - preparation::save_if_unchanged( + preparation::save_grid_if_unchanged( &self.owner, &self.relative, &approved, @@ -344,7 +209,7 @@ impl Editor { } egui::Window::new("Review beat grid") .open(&mut open) - .default_size(egui::vec2(1040., 650.)) + .default_size(egui::vec2(1040., 760.)) .min_width(520.) .vscroll(true) .show(ctx, |ui| { @@ -470,10 +335,9 @@ impl Editor { .prefix("BPM "), ) .changed() + && let Err(e) = grid_review::tempo(&mut self.draft, bpm) { - if let Err(e) = grid_review::tempo(&mut self.draft, bpm) { - self.status = e; - } + self.status = e; } for (label, scale) in [("BPM ×2", 2.), ("BPM ÷2", 0.5)] { if ui.button(label).clicked() @@ -591,3 +455,200 @@ impl Editor { } } } + +#[cfg(test)] +mod tests { + use super::*; + fn fixture() -> (tempfile::TempDir, Library, Editor) { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("one.wav"), b"audio fixture").unwrap(); + let mut p = Preparation { + bpm: Some(120.), + beat_offset: Some(0.2), + cue_in: 8., + cue_out: Some(90.), + ..Default::default() + }; + p.manual_cues.push(preparation::Cue { + id: "owner-cue".into(), + label: "Keep this cue".into(), + seconds: 16., + ..Default::default() + }); + p.extensions + .insert("regions".into(), serde_json::json!([{"start":8,"end":12}])); + preparation::save(dir.path(), Path::new("one.wav"), &p).unwrap(); + let lib = amp_core::scan(dir.path()).unwrap(); + let mut editor = Editor::default(); + editor.select(dir.path(), &lib.tracks[0], vec!["one.wav".into()]); + (dir, lib, editor) + } + #[test] + fn review_persists_grid_without_cue_or_audio_changes() { + let (dir, mut library, mut editor) = fixture(); + let before = preparation::load(&dir.path().join("one.wav")).unwrap(); + grid_review::set_bar_one(&mut editor.draft, 4.125).unwrap(); + editor.dirty = true; + assert_eq!( + preparation::load(&dir.path().join("one.wav")).unwrap(), + before + ); + editor.save(dir.path(), &mut library).unwrap(); + let saved = preparation::load(&dir.path().join("one.wav")).unwrap(); + assert_eq!(grid_review::status(&saved), grid_review::Status::Reviewed); + assert_eq!(saved.manual_cues, before.manual_cues); + assert_eq!(saved.cue_in, before.cue_in); + assert_eq!(saved.cue_out, before.cue_out); + assert_eq!(saved.extensions["regions"], before.extensions["regions"]); + assert_eq!( + std::fs::read(dir.path().join("one.wav")).unwrap(), + b"audio fixture" + ); + assert_eq!( + grid_review::status(&library.tracks[0].preparation), + grid_review::Status::Reviewed + ); + assert!(!editor.dirty); + assert!(editor.audio.is_none()); + } + #[test] + fn concurrent_preparation_save_is_not_overwritten() { + let (dir, mut library, mut editor) = fixture(); + let mut other = editor.original.clone(); + other.cue_in = 22.; + preparation::save(dir.path(), Path::new("one.wav"), &other).unwrap(); + grid_review::set_bar_one(&mut editor.draft, 3.).unwrap(); + editor.dirty = true; + editor.save(dir.path(), &mut library).unwrap(); + assert_eq!( + preparation::load(&dir.path().join("one.wav")) + .unwrap() + .cue_in, + 22. + ); + } + #[test] + fn concurrent_tempo_change_cannot_merge_with_an_older_phase_edit() { + let (dir, mut library, mut editor) = fixture(); + let mut other = editor.original.clone(); + grid_review::tempo(&mut other, 130.).unwrap(); + preparation::save(dir.path(), Path::new("one.wav"), &other).unwrap(); + grid_review::set_bar_one(&mut editor.draft, 3.).unwrap(); + editor.dirty = true; + assert!( + editor + .save(dir.path(), &mut library) + .unwrap_err() + .contains("Beat grid changed") + ); + assert!(editor.dirty); + assert_eq!( + preparation::load(&dir.path().join("one.wav")).unwrap().bpm, + Some(130.) + ); + } + #[test] + fn closing_and_reopening_retains_unsaved_grid() { + let (dir, library, mut editor) = fixture(); + grid_review::set_bar_one(&mut editor.draft, 3.).unwrap(); + editor.dirty = true; + editor.open = false; + editor.select(dir.path(), &library.tracks[0], vec![]); + assert!(editor.open && editor.dirty); + assert_eq!( + editor.draft.extensions["mix_bar_anchor"], + serde_json::json!(3.) + ); + } + #[test] + fn opening_after_another_clients_save_uses_the_fresh_grid() { + let (dir, mut library, mut editor) = fixture(); + let mut fresh = editor.original.clone(); + grid_review::tempo(&mut fresh, 128.).unwrap(); + grid_review::set_bar_one(&mut fresh, 6.).unwrap(); + preparation::save(dir.path(), Path::new("one.wav"), &fresh).unwrap(); + editor.select(dir.path(), &library.tracks[0], vec![]); + assert_eq!(editor.draft.bpm, Some(128.)); + assert_eq!( + editor.draft.extensions["mix_bar_anchor"], + serde_json::json!(6.) + ); + editor.save(dir.path(), &mut library).unwrap(); + let saved = preparation::load(&dir.path().join("one.wav")).unwrap(); + assert_eq!(saved.bpm, Some(128.)); + assert_eq!(saved.extensions["mix_bar_anchor"], serde_json::json!(6.)); + } + #[test] + fn switching_libraries_cannot_write_the_previous_songs_grid() { + let (dir, _, mut editor) = fixture(); + let (other, mut other_library, _) = fixture(); + let before = preparation::load(&dir.path().join("one.wav")).unwrap(); + let other_before = other_library.tracks[0].preparation.clone(); + grid_review::set_bar_one(&mut editor.draft, 9.).unwrap(); + assert!(editor.save(other.path(), &mut other_library).is_err()); + assert_eq!( + preparation::load(&dir.path().join("one.wav")).unwrap(), + before + ); + assert_eq!(other_library.tracks[0].preparation, other_before); + } + #[test] + fn playlist_navigation_skips_missing_entries() { + let (_, mut library, mut editor) = fixture(); + let mut next = library.tracks[0].clone(); + next.path = "three.wav".into(); + library.tracks.push(next); + editor.batch = vec!["one.wav".into(), "missing.wav".into(), "three.wav".into()]; + assert_eq!( + editor.neighbor(&library, 0, true).unwrap().path, + Path::new("three.wav") + ); + assert_eq!( + editor.neighbor(&library, 2, false).unwrap().path, + Path::new("one.wav") + ); + assert!(editor.neighbor(&library, 2, true).is_none()); + } + #[test] + fn review_view_exposes_controls_without_saving_or_starting_audio() { + let (dir, mut library, mut editor) = fixture(); + let before = preparation::load(&dir.path().join("one.wav")).unwrap(); + let ctx = egui::Context::default(); + let mut texts = String::new(); + for _ in 0..3 { + let output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(1280., 900.), + )), + ..Default::default() + }, + |ui| editor.show(ui.ctx(), dir.path(), Some(&mut library), true), + ); + for shape in output.shapes { + if let egui::Shape::Text(text) = shape.shape { + texts.push_str(&text.galley.job.text); + texts.push('\n'); + } + } + } + for action in [ + "Play preview", + "Metronome", + "Zoom in", + "Zoom out", + "Set bar 1 here", + "Tap tempo", + "BPM ×2", + "Grid looks right", + ] { + assert!(texts.contains(action), "missing control {action}"); + } + assert!(editor.audio.is_none()); + assert_eq!( + preparation::load(&dir.path().join("one.wav")).unwrap(), + before + ); + } +} diff --git a/apps/amp-player/src/main.rs b/apps/amp-player/src/main.rs index a0bc8b82..8f0083e9 100644 --- a/apps/amp-player/src/main.rs +++ b/apps/amp-player/src/main.rs @@ -28,8 +28,8 @@ mod dragdrop; mod engine; mod engine_download; mod genre_picker; -mod grid_editor; mod google_cast; +mod grid_editor; mod hot_cues; mod icons; mod key_lock; @@ -3908,9 +3908,14 @@ impl eframe::App for Player { } } let grid_revision = self.preparer.grid.revision; - let grid_blocked = !self.library_open || self.library_preview_blocked() || self.smart_preview.active(); - self.preparer.grid.show(ui.ctx(), &self.root, self.library.as_mut(), grid_blocked); - if self.preparer.grid.revision != grid_revision { self.library_generation = self.library_generation.wrapping_add(1); } + let grid_blocked = + !self.library_open || self.library_preview_blocked() || self.smart_preview.active(); + self.preparer + .grid + .show(ui.ctx(), &self.root, self.library.as_mut(), grid_blocked); + if self.preparer.grid.revision != grid_revision { + self.library_generation = self.library_generation.wrapping_add(1); + } if let Some((path, seconds)) = self.preparer.preview.take() { if self.library_preview_blocked() { self.status = diff --git a/apps/amp-player/src/mixer.rs b/apps/amp-player/src/mixer.rs index 9b87ccee..aeb32d4a 100644 --- a/apps/amp-player/src/mixer.rs +++ b/apps/amp-player/src/mixer.rs @@ -1630,9 +1630,16 @@ impl Mixer { ); } if d == 0 && c.grid_click.load(Relaxed) { - let seconds = source.position / self.rate as f64 + f64::from_bits(c.source_origin[d].load(Relaxed)); - let click = amp_core::grid_review::click(seconds, f64::from_bits(c.grid_click_bpm.load(Relaxed)), f64::from_bits(c.grid_click_anchor.load(Relaxed))); - for sample in &mut frame { *sample += click; } + let seconds = source.position / self.rate as f64 + + f64::from_bits(c.source_origin[d].load(Relaxed)); + let click = amp_core::grid_review::click( + seconds, + f64::from_bits(c.grid_click_bpm.load(Relaxed)), + f64::from_bits(c.grid_click_anchor.load(Relaxed)), + ); + for sample in &mut frame { + *sample += click; + } } v.gain += (get(&c.gain[d]).clamp(0., 1.) - v.gain) * 0.004; v.trim += (trims[d] - v.trim) * 0.004; @@ -3381,9 +3388,12 @@ mod tests { controls.grid_click_bpm.store(120f64.to_bits(), Relaxed); let (tx, rx) = mpsc::sync_channel(32); let mut mixer = Mixer::new(8000, rx, controls); - tx.send(Command::Load(0, source(0., 16000), playing, 1)).unwrap(); + tx.send(Command::Load(0, source(0., 16000), playing, 1)) + .unwrap(); let mut result = Vec::new(); - for _ in 0..8000/block { mixer.render(block, |_, f| result.push(f)); } + for _ in 0..8000 / block { + mixer.render(block, |_, f| result.push(f)); + } result }; let one = run(true, true, 1); diff --git a/apps/amp-player/src/preparer.rs b/apps/amp-player/src/preparer.rs index 14d7bf85..ce31ba6e 100644 --- a/apps/amp-player/src/preparer.rs +++ b/apps/amp-player/src/preparer.rs @@ -113,7 +113,10 @@ impl Preparer { return; }; if ui.button("Review beat grid…").clicked() { - let batch = library.as_ref().map(|l| l.tracks.iter().map(|t| t.path.clone()).collect()).unwrap_or_default(); + let batch = library + .as_ref() + .map(|l| l.tracks.iter().map(|t| t.path.clone()).collect()) + .unwrap_or_default(); self.grid.select(root, track, batch); } if !self.busy() diff --git a/apps/amp-player/src/waveform.rs b/apps/amp-player/src/waveform.rs index 44353cb1..2fece081 100644 --- a/apps/amp-player/src/waveform.rs +++ b/apps/amp-player/src/waveform.rs @@ -154,8 +154,8 @@ fn decode(path: &Path, cancel: &AtomicBool) -> Result, String> { if v.is_finite() { peak[0] = peak[0].min(v); peak[1] = peak[1].max(v); - low += 0.1116 * (v - low); // 150 Hz at 8 kHz - mid += 0.6752 * (v - mid); // 2 kHz at 8 kHz + low += 0.1111 * (v - low); // 150 Hz at 8 kHz + mid += 0.7921 * (v - mid); // 2 kHz at 8 kHz peak[2] += low * low; peak[3] += (mid - low).powi(2); peak[4] += (v - mid).powi(2); diff --git a/crates/amp-core/src/lib.rs b/crates/amp-core/src/lib.rs index 2f32c29e..83c37dc9 100644 --- a/crates/amp-core/src/lib.rs +++ b/crates/amp-core/src/lib.rs @@ -18,8 +18,8 @@ pub mod coordination; pub mod cue_policy; pub mod discovery; pub mod energy_profile; -pub mod grid_review; pub mod engine_api; +pub mod grid_review; pub mod knowledge; pub mod library_commits; pub mod music_annotations; diff --git a/crates/amp-core/src/mix_schedule.rs b/crates/amp-core/src/mix_schedule.rs index 76b4c69b..0fce7a01 100644 --- a/crates/amp-core/src/mix_schedule.rs +++ b/crates/amp-core/src/mix_schedule.rs @@ -69,7 +69,7 @@ pub fn phrase_anchor(p: &Preparation) -> Option { pub fn timing_reliable(p: &Preparation) -> bool { p.extensions.get("grid_reviewed").and_then(|v| v.as_bool()) != Some(false) && p.bpm - .is_some_and(|b| b.is_finite() && (40. ..=300.).contains(&b)) + .is_some_and(|b| b.is_finite() && (40. ..=300.).contains(&b)) && p.beat_offset.is_some_and(|o| o.is_finite() && o >= 0.) && (p.manual_override || p.analysis.as_ref().is_some_and(|a| a.reviewed) diff --git a/crates/amp-core/src/preparation.rs b/crates/amp-core/src/preparation.rs index dfcf0c90..20851024 100644 --- a/crates/amp-core/src/preparation.rs +++ b/crates/amp-core/src/preparation.rs @@ -180,7 +180,7 @@ pub fn load_with_revision(path: &Path) -> Result<(Preparation, Option>), } } pub fn save(root: &Path, relative: &Path, p: &Preparation) -> Result<(), String> { - save_record(root, relative, p, None, None) + save_record(root, relative, p, None, None, false) } pub fn save_if_unchanged( root: &Path, @@ -188,7 +188,17 @@ pub fn save_if_unchanged( p: &Preparation, expected: Option<&[u8]>, ) -> Result<(), String> { - save_record(root, relative, p, Some(expected), None) + save_record(root, relative, p, Some(expected), None, false) +} +/// Grid phase, tempo and anchors are one correction. Check them together under +/// the publication lock; unrelated cue/tag edits still use the normal merge. +pub fn save_grid_if_unchanged( + root: &Path, + relative: &Path, + p: &Preparation, + expected: Option<&[u8]>, +) -> Result<(), String> { + save_record(root, relative, p, Some(expected), None, true) } pub fn publish_claimed( root: &Path, @@ -197,7 +207,7 @@ pub fn publish_claimed( expected: Option<&[u8]>, lease: &crate::coordination::Lease, ) -> Result<(), String> { - save_record(root, relative, p, Some(expected), Some(lease)) + save_record(root, relative, p, Some(expected), Some(lease), false) } fn save_record( root: &Path, @@ -205,10 +215,11 @@ fn save_record( p: &Preparation, expected: Option>, lease: Option<&crate::coordination::Lease>, + grid_guard: bool, ) -> Result<(), String> { let (owner, path) = crate::music_sources::owner(root, relative).map_err(|e| e.to_string())?; if owner != root.canonicalize().map_err(|e| e.to_string())? { - return save_record(&owner, &path, p, expected, lease); + return save_record(&owner, &path, p, expected, lease, grid_guard); } crate::storage::enroll(root)?; let _migration = crate::coordination::Lock::acquire(&root.join("ampdj/catalog-migration"))?; @@ -388,6 +399,21 @@ fn save_record( } base = current_json.clone(); } + if grid_guard + && [ + "bpm", + "beat_offset", + "mix_bar_anchor", + "mix_phrase_anchor", + "grid_reviewed", + ] + .iter() + .any(|key| base.get(*key) != current_json.get(*key)) + { + return Err( + "Beat grid changed on another device; reload before approving this correction".into(), + ); + } let merged = crate::coordination::merge(&base, ¤t_json, &proposed, &device, &library)?; let checked: Preparation = serde_json::from_value(merged).map_err(|e| e.to_string())?; checked.validate()?; From 299cd633e40ad7a25ba47135fb4c9caa54ca0558 Mon Sep 17 00:00:00 2001 From: gitwide-cloud Date: Thu, 3 Dec 2026 15:46:37 -0800 Subject: [PATCH 4/4] Complete headless grid-review interaction verification --- apps/amp-player/src/grid_editor.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/amp-player/src/grid_editor.rs b/apps/amp-player/src/grid_editor.rs index a479eb23..08f1bbf2 100644 --- a/apps/amp-player/src/grid_editor.rs +++ b/apps/amp-player/src/grid_editor.rs @@ -616,7 +616,7 @@ mod tests { let ctx = egui::Context::default(); let mut texts = String::new(); for _ in 0..3 { - let output = ctx.run_ui( + let mut output = ctx.run_ui( egui::RawInput { screen_rect: Some(egui::Rect::from_min_size( egui::Pos2::ZERO, @@ -626,6 +626,7 @@ mod tests { }, |ui| editor.show(ui.ctx(), dir.path(), Some(&mut library), true), ); + output.textures_delta.clear(); for shape in output.shapes { if let egui::Shape::Text(text) = shape.shape { texts.push_str(&text.galley.job.text);