From 7e8926c516c5877040d611dae5be9688ec2e8a91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Goran=20Meki=C4=87?= Date: Wed, 2 Dec 2026 04:02:58 +0100 Subject: [PATCH] Groove templates in live view --- Cargo.lock | 2 +- Cargo.toml | 2 +- src/engine/history.rs | 6 +++ src/engine/mod.rs | 66 ++++++++++++++++++++++++++++++++ src/engine/runtime.rs | 1 + src/engine/session.rs | 53 ++++++++++++++++++++++++++ src/groove/mod.rs | 36 ++++++------------ src/message.rs | 5 +++ src/track/clip_render.rs | 2 +- src/track/mod.rs | 81 ++++++++++++++++++++++++++++++++++++++-- src/track/session.rs | 58 +++++++++++++++++++++++----- 11 files changed, 273 insertions(+), 39 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a6eccda..b47404b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -476,7 +476,7 @@ dependencies = [ [[package]] name = "maolan-engine" -version = "0.4.30" +version = "0.4.31" dependencies = [ "alsa", "arc-swap", diff --git a/Cargo.toml b/Cargo.toml index e5d3f10..fd4b18a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "maolan-engine" -version = "0.4.30" +version = "0.4.31" edition = "2024" description = "Audio engine for the Maolan DAW with audio/MIDI tracks, routing, export, and out-of-process CLAP/VST3/LV2 plugin support" license = "BSD-2-Clause" diff --git a/src/engine/history.rs b/src/engine/history.rs index a8cd927..476e223 100644 --- a/src/engine/history.rs +++ b/src/engine/history.rs @@ -1617,6 +1617,11 @@ mod undo_consistency { scene_index: 0, clip_id: Some("clip".to_string()), }, + Action::TrackSetSessionSlotGroove { + track_name: "t1".to_string(), + scene_index: 0, + groove: Some(crate::groove::GrooveSettings::default()), + }, Action::TrackSetSessionSlotPlayEnabled { track_name: "t1".to_string(), scene_index: 0, @@ -2124,6 +2129,7 @@ mod undo_consistency { | Action::SetSessionMidiLearnBinding { .. } | Action::TrackSetFrozen { .. } | Action::TrackSetSessionSlot { .. } + | Action::TrackSetSessionSlotGroove { .. } | Action::TrackSetSessionSlotPlayEnabled { .. } | Action::TrackSetSessionSlotStopEnabled { .. } | Action::TrackSetFolder { .. } diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 2fa9091..6ad05fa 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -1753,6 +1753,72 @@ mod tests { assert!(!snapshot.tracks.contains_key("snap")); } + #[cfg_attr( + all(miri, any(target_os = "freebsd", target_os = "macos")), + ignore = "Tokio runtime uses kqueue, which Miri does not support on FreeBSD or macOS" + )] + #[cfg_attr( + all(miri, target_os = "windows"), + ignore = "Tokio runtime uses Windows IOCP, which Miri does not support" + )] + #[tokio::test] + async fn copied_clip_inherits_groove_and_plugins_but_groove_edits_are_instance_scoped() { + let (mut engine, _client_rx) = make_engine_with_client(); + let track = Track::new("track".to_string(), 1, 1, 0, 0, 64, 48_000.0); + let mut clip = AudioClip::new("audio/clip.wav".to_string(), 0, 48_000); + clip.id = "shared-id".to_string(); + clip.groove = Some(crate::groove::GrooveSettings::default()); + clip.plugin_graph_json = Some(serde_json::json!({ + "plugins": [{"format": "CLAP", "uri": "example.clap"}], + "connections": [] + })); + let expected_groove = clip.groove.clone(); + let expected_plugins = clip.plugin_graph_json.clone(); + track.audio.push_clip(clip); + insert_track(&mut engine, track); + + engine + .handle_request(Action::ClipMove { + kind: Kind::Audio, + from: crate::message::ClipMoveFrom { + track_name: "track".to_string(), + clip_index: 0, + }, + to: crate::message::ClipMoveTo { + track_name: "track".to_string(), + sample_offset: 48_000, + input_channel: 0, + }, + copy: true, + }) + .await; + + { + let state = engine.state.lock(); + let track = state.tracks.get("track").expect("track exists").lock(); + let clips = track.audio.clips(); + assert_eq!(clips.len(), 2); + assert_eq!(clips[0].id, clips[1].id); + assert_eq!(clips[1].groove, expected_groove); + assert_eq!(clips[1].plugin_graph_json, expected_plugins); + } + + engine + .handle_request(Action::SetClipGroove { + track_name: "track".to_string(), + clip_index: 1, + kind: Kind::Audio, + groove: None, + }) + .await; + + let state = engine.state.lock(); + let track = state.tracks.get("track").expect("track exists").lock(); + let clips = track.audio.clips(); + assert_eq!(clips[0].groove, expected_groove); + assert_eq!(clips[1].groove, None); + } + #[cfg_attr( all(miri, any(target_os = "freebsd", target_os = "macos")), ignore = "Tokio runtime uses kqueue, which Miri does not support on FreeBSD or macOS" diff --git a/src/engine/runtime.rs b/src/engine/runtime.rs index e3cce4e..ff37c45 100644 --- a/src/engine/runtime.rs +++ b/src/engine/runtime.rs @@ -628,6 +628,7 @@ impl Engine { | Action::SetSessionPath(_) | Action::SessionArmMidiLearn { .. } | Action::TrackSetSessionSlot { .. } + | Action::TrackSetSessionSlotGroove { .. } | Action::TrackSetSessionSlotPlayEnabled { .. } | Action::TrackSetSessionSlotStopEnabled { .. } => { if self.handle_session_request(a.clone()).await { diff --git a/src/engine/session.rs b/src/engine/session.rs index b5dcb9e..f8a5289 100644 --- a/src/engine/session.rs +++ b/src/engine/session.rs @@ -1030,6 +1030,7 @@ impl Engine { scene_index, SessionSlot { clip_id: id.clone(), + groove: None, play_enabled, stop_enabled, }, @@ -1044,6 +1045,32 @@ impl Engine { false } + pub(crate) async fn handle_track_set_session_slot_groove(&mut self, a: Action) -> bool { + let Action::TrackSetSessionSlotGroove { + ref track_name, + scene_index, + ref groove, + } = a + else { + return false; + }; + let track = match self.track_handle_or_err(track_name) { + Ok(track) => track, + Err(e) => { + self.notify_clients(Err(e)).await; + return true; + } + }; + let mut track = track.lock(); + if let Some(slot) = track.rt.session_slots.get_mut(&scene_index) + && !slot.clip_id.is_empty() + { + slot.groove = groove.clone(); + track.rt.clip_groove_shifters.clear(); + } + false + } + pub(crate) async fn handle_track_set_session_slot_play_enabled(&mut self, a: Action) -> bool { let Action::TrackSetSessionSlotPlayEnabled { ref track_name, @@ -1068,6 +1095,7 @@ impl Engine { .entry(scene_index) .or_insert_with(|| SessionSlot { clip_id: String::new(), + groove: None, play_enabled: false, stop_enabled: false, }) @@ -1100,6 +1128,7 @@ impl Engine { .entry(scene_index) .or_insert_with(|| SessionSlot { clip_id: String::new(), + groove: None, play_enabled: false, stop_enabled: false, }) @@ -1150,6 +1179,11 @@ impl Engine { return true; } } + Action::TrackSetSessionSlotGroove { .. } => { + if self.handle_track_set_session_slot_groove(a.clone()).await { + return true; + } + } Action::TrackSetSessionSlotPlayEnabled { .. } => { if self .handle_track_set_session_slot_play_enabled(a.clone()) @@ -1178,6 +1212,7 @@ pub(crate) fn undo_should_record(action: &Action) -> bool { matches!( action, Action::TrackSetSessionSlot { .. } + | Action::TrackSetSessionSlotGroove { .. } | Action::TrackSetSessionSlotPlayEnabled { .. } | Action::TrackSetSessionSlotStopEnabled { .. } ) @@ -1205,6 +1240,24 @@ pub(crate) fn undo_inverse(action: &Action, state: &State) -> Option { }) } + Action::TrackSetSessionSlotGroove { + track_name, + scene_index, + groove: _, + } => { + let track = state.tracks.get(track_name)?; + let track_lock = track.lock(); + Some(Action::TrackSetSessionSlotGroove { + track_name: track_name.clone(), + scene_index: *scene_index, + groove: track_lock + .rt + .session_slots + .get(scene_index) + .and_then(|slot| slot.groove.clone()), + }) + } + Action::TrackSetSessionSlotPlayEnabled { track_name, scene_index, diff --git a/src/groove/mod.rs b/src/groove/mod.rs index 4ddb496..52165b3 100644 --- a/src/groove/mod.rs +++ b/src/groove/mod.rs @@ -58,7 +58,6 @@ impl GrooveBase { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GrooveSettings { pub base: GrooveBase, - pub swing_percent: f32, pub template: Option>, pub quantize: f32, pub timing: f32, @@ -70,7 +69,6 @@ impl Default for GrooveSettings { fn default() -> Self { Self { base: GrooveBase::Sixteenth, - swing_percent: 73.0, template: None, quantize: 0.0, timing: 100.0, @@ -100,7 +98,6 @@ impl GrooveSettings { timing: parsed.timing, random: parsed.random, velocity: parsed.velocity, - ..Self::default() }) } @@ -138,20 +135,11 @@ impl GrooveSettings { } pub fn offset_at_grid(&self, grid_index: i64, grid_samples: f64, seed: &str) -> f64 { - let timing = self.template_note_at_grid(grid_index).map_or_else( - || { - if self.template.is_none() && grid_index.rem_euclid(2) == 1 { - ((self.swing_percent.clamp(50.0, 99.0) - 50.0) * 2.0) as f64 / 100.0 - } else { - 0.0 - } - }, - |note| { - let ideal = (note.time_beats * self.base.divisions_per_beat()).round() - / self.base.divisions_per_beat(); - (note.time_beats - ideal) * self.base.divisions_per_beat() - }, - ); + let timing = self.template_note_at_grid(grid_index).map_or(0.0, |note| { + let ideal = (note.time_beats * self.base.divisions_per_beat()).round() + / self.base.divisions_per_beat(); + (note.time_beats - ideal) * self.base.divisions_per_beat() + }); let random = Self::random_at_grid(grid_index, seed) * 0.05 * Self::unit(self.random); grid_samples * (timing * Self::unit(self.timing) + random) } @@ -400,29 +388,29 @@ mod tests { use super::*; #[test] - fn swing_16ths_73_delays_alternate_grid_positions() { + fn no_template_produces_straight_timing() { let groove = GrooveSettings::default(); assert_eq!(groove.offset_at_grid(0, 6_000.0, "clip"), 0.0); - assert_eq!(groove.offset_at_grid(1, 6_000.0, "clip"), 2_760.0); + assert_eq!(groove.offset_at_grid(1, 6_000.0, "clip"), 0.0); assert_eq!(groove.offset_at_grid(2, 6_000.0, "clip"), 0.0); - assert_eq!(groove.tempo_at_grid(0, 6_000.0, "clip"), 6_000.0 / 8_760.0); - assert_eq!(groove.tempo_at_grid(1, 6_000.0, "clip"), 6_000.0 / 3_240.0); + assert_eq!(groove.tempo_at_grid(0, 6_000.0, "clip"), 1.0); + assert_eq!(groove.tempo_at_grid(1, 6_000.0, "clip"), 1.0); } #[test] fn zero_random_is_repeatable_and_quantize_zero_preserves_straight_notes() { let groove = GrooveSettings::default(); assert_eq!(groove.map_midi_sample(12_000, 6_000.0, "clip", 0), 12_000); - assert_eq!(groove.map_midi_sample(6_000, 6_000.0, "clip", 0), 8_760); + assert_eq!(groove.map_midi_sample(6_000, 6_000.0, "clip", 0), 6_000); } #[test] - fn quantize_is_applied_before_swing() { + fn quantize_snaps_notes_to_the_grid_before_groove_mapping() { let groove = GrooveSettings { quantize: 100.0, ..GrooveSettings::default() }; - assert_eq!(groove.map_midi_sample(5_900, 6_000.0, "clip", 0), 8_760); + assert_eq!(groove.map_midi_sample(5_900, 6_000.0, "clip", 0), 6_000); } #[test] diff --git a/src/message.rs b/src/message.rs index 66f5d99..29ea3a2 100644 --- a/src/message.rs +++ b/src/message.rs @@ -1380,6 +1380,11 @@ pub enum Action { scene_index: usize, clip_id: Option, }, + TrackSetSessionSlotGroove { + track_name: String, + scene_index: usize, + groove: Option, + }, TrackSetSessionSlotPlayEnabled { track_name: String, scene_index: usize, diff --git a/src/track/clip_render.rs b/src/track/clip_render.rs index 1dd7973..6380be6 100644 --- a/src/track/clip_render.rs +++ b/src/track/clip_render.rs @@ -768,7 +768,7 @@ impl TrackData { let settings = clip.groove.clone()?; let input_count = self.audio.ins.len().max(1); let channels = effective_channels_for(buffer_channel_count(buffer), input_count).min(2); - let key = format!("{}:{}", clip.id, clip.name); + let key = format!("{}:{}:{clip_start}", clip.id, clip.name); let bpm = self.rt.tempo_bpm; let valid = self .rt diff --git a/src/track/mod.rs b/src/track/mod.rs index 2dec09f..5028440 100644 --- a/src/track/mod.rs +++ b/src/track/mod.rs @@ -52,6 +52,8 @@ type MidiClipEvents = Arc)>>; pub struct SessionSlot { /// Identifier of the clip assigned to this slot. pub clip_id: String, + /// Groove applied only when this slot plays the referenced clip. + pub groove: Option, /// Whether this slot takes part in scene launches. pub play_enabled: bool, /// Whether this slot stops the track on scene launches. When neither @@ -64,6 +66,7 @@ impl SessionSlot { pub fn new(clip_id: String) -> Self { Self { clip_id, + groove: None, play_enabled: true, stop_enabled: false, } @@ -2009,7 +2012,20 @@ mod tests { track.set_disk_monitor(vec![true]); let mut clip = crate::midi::clip::MIDIClip::new("clip.mid".to_string(), 0, 12_000); clip.id = "grooved".to_string(); - clip.groove = Some(crate::groove::GrooveSettings::default()); + clip.groove = Some(crate::groove::GrooveSettings { + template: Some(Box::new(crate::groove::GrooveTemplate { + name: "Test".to_string(), + length_beats: 1.0, + notes: [0.0, 0.36, 0.5, 0.75] + .into_iter() + .map(|time_beats| crate::groove::GrooveNote { + time_beats, + velocity: 100.0, + }) + .collect(), + })), + ..crate::groove::GrooveSettings::default() + }); track.rt.midi_clip_cache.insert( "clip.mid".to_string(), Arc::new(vec![ @@ -2022,8 +2038,8 @@ mod tests { track.collect_midi_clip_events_recursive(&clip, 0, &mut events, 1024, &[(8_192, 9_216, 0)]); assert_eq!(events[0].len(), 2); - assert_eq!(events[0][0].frame, 568); - assert_eq!(events[0][1].frame, 622); + assert_eq!(events[0][0].frame, 448); + assert_eq!(events[0][1].frame, 504); } #[test] @@ -3073,6 +3089,65 @@ mod tests { ); } + #[test] + fn session_slots_override_source_groove_independently() { + let groove = crate::groove::GrooveSettings { + template: Some(Box::new(crate::groove::GrooveTemplate { + name: "Test".to_string(), + length_beats: 1.0, + notes: [0.0, 0.36, 0.5, 0.75] + .into_iter() + .map(|time_beats| crate::groove::GrooveNote { + time_beats, + velocity: 100.0, + }) + .collect(), + })), + ..crate::groove::GrooveSettings::default() + }; + let make_track = |scene_index, play_position_samples, slot_groove| { + let mut track = Track::new("t".to_string(), 0, 0, 1, 1, 1024, 48_000.0); + let mut clip = crate::midi::clip::MIDIClip::new("clip.mid".to_string(), 0, 12_000); + clip.id = "shared-id".to_string(); + clip.groove = Some(groove.clone()); + track.midi.push_clip(clip); + track.rt.midi_clip_cache.insert( + "clip.mid".to_string(), + Arc::new(vec![(6_000, vec![0x90, 60, 100])]), + ); + let mut slot = super::SessionSlot::new("shared-id".to_string()); + slot.groove = slot_groove; + track.rt.session_slots.insert(scene_index, slot); + track + .rt + .playing_session_clips + .push(super::PlayingSessionClip { + scene_index, + clip_id: "shared-id".to_string(), + kind: Kind::MIDI, + play_position_samples, + elapsed_samples: play_position_samples, + loop_enabled: false, + loop_start_samples: 0, + loop_end_samples: 0, + stop_at_sample: None, + active_midi_notes: std::collections::HashSet::new(), + }); + track + }; + + let mut straight = make_track(0, 6_000, None); + let mut straight_events = vec![Vec::new()]; + straight.mix_session_midi_into_inputs(&mut straight_events, 64); + assert_eq!(straight_events[0][0].frame, 0); + assert!(straight.midi.clips()[0].groove.is_some()); + + let mut grooved = make_track(1, 8_192, Some(groove.clone())); + let mut grooved_events = vec![Vec::new()]; + grooved.mix_session_midi_into_inputs(&mut grooved_events, 1024); + assert_eq!(grooved_events[0][0].frame, 448); + } + #[test] fn session_midi_stop_emits_note_off_for_active_notes() { let mut track = Track::new("t".to_string(), 0, 0, 1, 1, 8, 48_000.0); diff --git a/src/track/session.rs b/src/track/session.rs index 3ca1773..cb8ebf5 100644 --- a/src/track/session.rs +++ b/src/track/session.rs @@ -236,7 +236,7 @@ impl TrackData { continue; } let clip_id = self.rt.playing_session_clips[i].clip_id.clone(); - let arrangement_clip = match self + let mut arrangement_clip = match self .audio .clips() .iter() @@ -255,6 +255,11 @@ impl TrackData { continue; } }; + std::sync::Arc::make_mut(&mut arrangement_clip).groove = self + .rt + .session_slots + .get(&self.rt.playing_session_clips[i].scene_index) + .and_then(|slot| slot.groove.clone()); let clip_length = arrangement_clip.end.saturating_sub(arrangement_clip.start); if clip_length == 0 { remove_indices.push(i); @@ -393,7 +398,7 @@ impl TrackData { continue; } let clip_id = self.rt.playing_session_clips[i].clip_id.clone(); - let arrangement_clip = match self + let mut arrangement_clip = match self .midi .clips() .iter() @@ -412,6 +417,11 @@ impl TrackData { continue; } }; + std::sync::Arc::make_mut(&mut arrangement_clip).groove = self + .rt + .session_slots + .get(&self.rt.playing_session_clips[i].scene_index) + .and_then(|slot| slot.groove.clone()); let clip_length = arrangement_clip.end.saturating_sub(arrangement_clip.start); if clip_length == 0 { remove_indices.push(i); @@ -470,19 +480,49 @@ impl TrackData { let content_end = content_start.saturating_add(segment_len); for (source_sample, data) in events.iter() { - if *source_sample < content_start { + let (target_sample, data) = if let Some(groove) = arrangement_clip + .groove + .as_ref() + .filter(|_| !arrangement_clip.reversed) + { + let local_sample = source_sample.saturating_sub(arrangement_clip.offset); + if local_sample >= clip_length { + continue; + } + let grid_samples = groove.grid_samples(self.sample_rate, self.rt.tempo_bpm); + let voice = data.get(1).copied().unwrap_or(0); + let target_sample = + arrangement_clip + .offset + .saturating_add(groove.map_midi_sample( + local_sample, + grid_samples, + &arrangement_clip.id, + voice, + )); + let mut data = data.clone(); + if data.len() >= 3 && data[0] & 0xf0 == 0x90 && data[2] > 0 { + let scale = groove.midi_velocity_scale(*source_sample, grid_samples); + data[2] = (f32::from(data[2]) * scale).round().clamp(1.0, 127.0) as u8; + } + (target_sample, data) + } else { + (*source_sample, data.clone()) + }; + if target_sample < content_start { continue; } - if *source_sample >= content_end { - break; + if target_sample >= content_end { + if arrangement_clip.groove.is_none() { + break; + } + continue; } - let frame = out_offset + (source_sample - content_start); + let frame = out_offset + (target_sample - content_start); if frame >= frames { continue; } - for allocated in - self.allocate_mpe_event(MidiEvent::new(frame as u32, data.clone())) - { + for allocated in self.allocate_mpe_event(MidiEvent::new(frame as u32, data)) { let data = allocated.data.clone(); input_events[input_lane].push(allocated); if let Some(&status) = data.first() {