From 0d2b3e582f63f226d322268068ad5b74b3524438 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Goran=20Meki=C4=87?= Date: Tue, 1 Dec 2026 10:39:36 +0100 Subject: [PATCH] Add support for groove templates --- Cargo.lock | 62 ++++- Cargo.toml | 4 +- src/audio/clip.rs | 2 + src/engine/history.rs | 3 + src/engine/mod.rs | 3 + src/engine/recording.rs | 2 + src/engine/runtime.rs | 1 + src/engine/topology.rs | 77 ++++++ src/groove/agr.rs | 201 ++++++++++++++++ src/groove/mod.rs | 490 +++++++++++++++++++++++++++++++++++++++ src/history.rs | 2 + src/lib.rs | 1 + src/message.rs | 13 ++ src/midi/clip.rs | 2 + src/osc.rs | 1 + src/track/clip_render.rs | 153 ++++++++++++ src/track/mod.rs | 85 +++++++ 17 files changed, 1100 insertions(+), 2 deletions(-) create mode 100644 src/groove/agr.rs create mode 100644 src/groove/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 3c13758..a6eccda 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aes" version = "0.8.4" @@ -185,6 +191,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam-deque" version = "0.8.8" @@ -283,6 +298,17 @@ version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -450,7 +476,7 @@ dependencies = [ [[package]] name = "maolan-engine" -version = "0.4.29" +version = "0.4.30" dependencies = [ "alsa", "arc-swap", @@ -461,6 +487,7 @@ dependencies = [ "crossbeam-queue", "fearless_simd", "fearless_simd_macros", + "flate2", "jack", "libc", "maolan-asio", @@ -478,6 +505,7 @@ dependencies = [ "oxideav-mp4", "oxideav-ogg", "oxideav-vorbis", + "quick-xml", "rayon", "rtrb", "rubato", @@ -517,6 +545,16 @@ dependencies = [ "rayon", ] +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.5" @@ -749,6 +787,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "quote" version = "1.0.47" @@ -927,6 +975,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "slab" version = "0.4.12" @@ -1395,6 +1449,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 3fa27e6..e5d3f10 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "maolan-engine" -version = "0.4.29" +version = "0.4.30" 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" @@ -40,6 +40,8 @@ rubato = "5.0.1" audioadapter = "5.0" audioadapter-buffers = "5.2" timestretch = "0.17.0" +flate2 = "1.1.11" +quick-xml = { version = "0.42.0", features = ["serialize"] } mixosc = { version = "0.0.18", optional = true, default-features = false } [dev-dependencies] diff --git a/src/audio/clip.rs b/src/audio/clip.rs index b97fdac..475723c 100644 --- a/src/audio/clip.rs +++ b/src/audio/clip.rs @@ -11,6 +11,7 @@ pub struct AudioClip { pub input_channel: usize, pub muted: bool, pub reversed: bool, + pub groove: Option, pub gain_db: f32, pub peaks_file: Option, pub fade_enabled: bool, @@ -39,6 +40,7 @@ impl AudioClip { input_channel: 0, muted: false, reversed: false, + groove: None, gain_db: 0.0, peaks_file: None, fade_enabled: true, diff --git a/src/engine/history.rs b/src/engine/history.rs index ec5e30c..a8cd927 100644 --- a/src/engine/history.rs +++ b/src/engine/history.rs @@ -406,6 +406,7 @@ mod tests { input_channel: 0, muted: false, reversed: false, + groove: None, gain_db: 0.0, peaks_file: None, kind: Kind::Audio, @@ -1651,6 +1652,7 @@ mod undo_consistency { input_channel: 0, muted: false, reversed: false, + groove: None, gain_db: 0.0, peaks_file: None, kind: Kind::Audio, @@ -2143,6 +2145,7 @@ mod undo_consistency { | Action::SetClipBounds { .. } | Action::SetClipMuted { .. } | Action::SetClipReversed { .. } + | Action::SetClipGroove { .. } | Action::SetClipSourceName { .. } | Action::SetClipPitchCorrection { .. } | Action::ClearAllMidiLearnBindings diff --git a/src/engine/mod.rs b/src/engine/mod.rs index dbc288f..2fa9091 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -250,6 +250,7 @@ pub(crate) struct ClipAddRequest<'a> { input_channel: usize, muted: bool, reversed: bool, + groove: Option, gain_db: f32, peaks_file: Option, kind: Kind, @@ -936,6 +937,7 @@ mod tests { input_channel: 0, muted: false, reversed: false, + groove: None, gain_db: 0.0, peaks_file: None, kind: Kind::Audio, @@ -1002,6 +1004,7 @@ mod tests { input_channel: 0, muted: false, reversed: false, + groove: None, gain_db: 0.0, peaks_file: None, kind: Kind::Audio, diff --git a/src/engine/recording.rs b/src/engine/recording.rs index 97b5a4c..5bd241f 100644 --- a/src/engine/recording.rs +++ b/src/engine/recording.rs @@ -597,6 +597,7 @@ impl Engine { input_channel: 0, muted: false, reversed: false, + groove: None, gain_db: 0.0, peaks_file: peaks_path.is_some().then_some(peaks_rel), kind: Kind::Audio, @@ -772,6 +773,7 @@ impl Engine { input_channel: 0, muted: false, reversed: false, + groove: None, gain_db: 0.0, peaks_file: None, kind: Kind::MIDI, diff --git a/src/engine/runtime.rs b/src/engine/runtime.rs index 05718a7..e3cce4e 100644 --- a/src/engine/runtime.rs +++ b/src/engine/runtime.rs @@ -770,6 +770,7 @@ impl Engine { | Action::SyncClipBounds { .. } | Action::SetClipMuted { .. } | Action::SetClipReversed { .. } + | Action::SetClipGroove { .. } | Action::SetClipGainDb { .. } | Action::SetClipPitchCorrection { .. } | Action::Connect { .. } diff --git a/src/engine/topology.rs b/src/engine/topology.rs index d926f3e..51efc70 100644 --- a/src/engine/topology.rs +++ b/src/engine/topology.rs @@ -620,6 +620,7 @@ impl Engine { clip.input_channel = request.input_channel.min(max_lane); clip.muted = request.muted; clip.reversed = request.reversed; + clip.groove = request.groove; clip.gain_db = request.gain_db; clip.peaks_file = request.peaks_file; clip.fade_enabled = request.fade_enabled; @@ -656,6 +657,7 @@ impl Engine { clip.input_channel = request.input_channel.min(max_lane); clip.muted = request.muted; clip.reversed = request.reversed; + clip.groove = request.groove; track.midi.push_clip(clip); } } @@ -682,6 +684,7 @@ impl Engine { clip.input_channel = data.input_channel; clip.muted = data.muted; clip.reversed = data.reversed; + clip.groove = data.groove.clone(); clip.gain_db = data.gain_db; clip.peaks_file = data.peaks_file.clone(); clip.fade_enabled = data.fade_enabled; @@ -724,6 +727,7 @@ impl Engine { clip.input_channel = data.input_channel; clip.muted = data.muted; clip.reversed = data.reversed; + clip.groove = data.groove.clone(); clip.grouped_clips = data .grouped_clips .iter() @@ -1087,6 +1091,32 @@ impl Engine { } } + pub(crate) fn set_clip_groove( + &self, + track_name: &str, + clip_index: usize, + kind: Kind, + groove: Option, + ) { + let Some(track) = self.state.lock().tracks.get(track_name).cloned() else { + return; + }; + let mut track = track.lock(); + match kind { + Kind::Audio => { + track.audio.update_clip(clip_index, |clip| { + clip.groove = groove; + }); + track.rt.clip_groove_shifters.clear(); + } + Kind::MIDI => { + track.midi.update_clip(clip_index, |clip| { + clip.groove = groove; + }); + } + } + } + pub(crate) fn set_clip_bounds( &self, track_name: &str, @@ -2695,6 +2725,7 @@ impl Engine { input_channel, muted, reversed, + groove, gain_db, ref peaks_file, kind, @@ -2727,6 +2758,7 @@ impl Engine { input_channel, muted, reversed, + groove: groove.clone(), gain_db, peaks_file: peaks_file.clone(), kind, @@ -3570,6 +3602,14 @@ impl Engine { } => { self.set_clip_reversed(track_name, clip_index, kind, reversed); } + Action::SetClipGroove { + ref track_name, + clip_index, + kind, + ref groove, + } => { + self.set_clip_groove(track_name, clip_index, kind, groove.clone()); + } Action::SetClipGainDb { ref track_name, clip_index, @@ -3706,6 +3746,7 @@ pub(crate) fn undo_should_record(action: &Action) -> bool { | Action::SetClipBounds { .. } | Action::SetClipMuted { .. } | Action::SetClipReversed { .. } + | Action::SetClipGroove { .. } | Action::SetClipSourceName { .. } | Action::SetClipPitchCorrection { .. } | Action::Connect { .. } @@ -3973,6 +4014,7 @@ pub(crate) fn undo_inverse(action: &Action, state: &State) -> Option { input_channel: clip.input_channel, muted: clip.muted, reversed: clip.reversed, + groove: clip.groove.clone(), gain_db: clip.gain_db, peaks_file: clip.peaks_file.clone(), kind: Kind::Audio, @@ -4016,6 +4058,7 @@ pub(crate) fn undo_inverse(action: &Action, state: &State) -> Option { input_channel: clip.input_channel, muted: clip.muted, reversed: clip.reversed, + groove: clip.groove.clone(), gain_db: 0.0, peaks_file: None, kind: Kind::MIDI, @@ -4282,6 +4325,38 @@ pub(crate) fn undo_inverse(action: &Action, state: &State) -> Option { }) } + Action::SetClipGroove { + track_name, + clip_index, + kind, + .. + } => { + let track = state.tracks.get(track_name)?; + let track_lock = track.lock(); + let groove = match kind { + Kind::Audio => track_lock + .audio + .clips() + .get(*clip_index) + .cloned()? + .groove + .clone(), + Kind::MIDI => track_lock + .midi + .clips() + .get(*clip_index) + .cloned()? + .groove + .clone(), + }; + Some(Action::SetClipGroove { + track_name: track_name.clone(), + clip_index: *clip_index, + kind: *kind, + groove, + }) + } + Action::SetClipSourceName { track_name, clip_index, @@ -4979,6 +5054,7 @@ pub(crate) fn undo_inverse_actions(action: &Action, state: &State) -> Option Option, + #[serde(rename = "Clip")] + clip: Clip, + #[serde(rename = "QuantizationAmount", default)] + quantization: Option>, + #[serde(rename = "TimingAmount", default)] + timing: Option>, + #[serde(rename = "RandomAmount", default)] + random: Option>, + #[serde(rename = "VelocityAmount", default)] + velocity: Option>, +} + +#[derive(Deserialize)] +struct Clip { + #[serde(rename = "Value")] + value: ClipValue, +} + +#[derive(Deserialize)] +struct ClipValue { + #[serde(rename = "MidiClip")] + midi_clip: MidiClip, +} + +#[derive(Deserialize)] +struct MidiClip { + #[serde(rename = "Loop")] + loop_settings: Loop, + #[serde(rename = "Grid")] + grid: Grid, + #[serde(rename = "Notes")] + notes: Notes, +} + +#[derive(Deserialize)] +struct Loop { + #[serde(rename = "LoopEnd")] + end: Value, +} + +#[derive(Deserialize)] +struct Grid { + #[serde(rename = "FixedDenominator")] + fixed_denominator: Value, +} + +#[derive(Deserialize)] +struct Notes { + #[serde(rename = "KeyTracks")] + key_tracks: KeyTracks, +} + +#[derive(Deserialize)] +struct KeyTracks { + #[serde(rename = "KeyTrack", default)] + tracks: Vec, +} + +#[derive(Deserialize)] +struct KeyTrack { + #[serde(rename = "Notes")] + notes: NoteList, +} + +#[derive(Deserialize)] +struct NoteList { + #[serde(rename = "MidiNoteEvent", default)] + events: Vec, +} + +#[derive(Deserialize)] +struct NoteEvent { + #[serde(rename = "@Time")] + time: f64, + #[serde(rename = "@Velocity")] + velocity: f32, +} + +#[derive(Deserialize)] +struct Value { + #[serde(rename = "@Value")] + value: T, +} + +pub(super) struct ParsedAgr { + pub template: GrooveTemplate, + pub denominator: u32, + pub quantize: f32, + pub timing: f32, + pub random: f32, + pub velocity: f32, +} + +pub(super) fn parse_with_settings(bytes: &[u8]) -> Result { + let file: Ableton = quick_xml::de::from_reader(std::io::BufReader::new(GzDecoder::new(bytes))) + .map_err(|error| format!("Invalid Ableton groove file: {error}"))?; + let groove = file.groove; + let clip = groove.clip.value.midi_clip; + let mut notes = clip + .notes + .key_tracks + .tracks + .into_iter() + .flat_map(|track| track.notes.events) + .map(|event| GrooveNote { + time_beats: event.time, + velocity: event.velocity, + }) + .collect::>(); + if notes.is_empty() { + return Err("Ableton groove contains no MIDI notes".to_string()); + } + if !clip.loop_settings.end.value.is_finite() || clip.loop_settings.end.value <= 0.0 { + return Err("Ableton groove has an invalid clip length".to_string()); + } + if notes.iter().any(|note| { + !note.time_beats.is_finite() || !note.velocity.is_finite() || note.velocity < 0.0 + }) { + return Err("Ableton groove contains an invalid note".to_string()); + } + notes.sort_by(|left, right| left.time_beats.total_cmp(&right.time_beats)); + Ok(ParsedAgr { + template: GrooveTemplate { + name: groove.name.value, + length_beats: clip.loop_settings.end.value, + notes, + }, + denominator: clip.grid.fixed_denominator.value, + quantize: groove.quantization.map_or(0.0, |value| value.value), + timing: groove.timing.map_or(100.0, |value| value.value), + random: groove.random.map_or(0.0, |value| value.value), + velocity: groove.velocity.map_or(0.0, |value| value.value), + }) +} + +pub(super) fn parse(bytes: &[u8]) -> Result { + parse_with_settings(bytes).map(|parsed| parsed.template) +} + +#[cfg(test)] +mod tests { + use super::*; + use flate2::{Compression, write::GzEncoder}; + use std::io::Write; + + fn compressed(xml: &str) -> Vec { + let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); + encoder.write_all(xml.as_bytes()).expect("compress AGR"); + encoder.finish().expect("finish AGR") + } + + #[test] + fn parses_groove_notes_and_saved_parameters() { + let bytes = compressed( + r#" + + + + + + + "#, + ); + let parsed = parse_with_settings(&bytes).expect("parse AGR"); + assert_eq!(parsed.template.name, "Pocket"); + assert_eq!(parsed.template.length_beats, 4.0); + assert_eq!(parsed.denominator, 16); + assert_eq!(parsed.quantize, 10.0); + assert_eq!(parsed.timing, 80.0); + assert_eq!(parsed.random, 5.0); + assert_eq!(parsed.velocity, -20.0); + assert_eq!(parsed.template.notes[0].time_beats, 0.0); + assert_eq!(parsed.template.notes[0].velocity, 120.0); + assert_eq!(parsed.template.notes[1].time_beats, 0.25); + } + + #[test] + fn rejects_groove_without_notes() { + let bytes = compressed( + r#" + + "#, + ); + assert!(parse(&bytes).is_err()); + } +} diff --git a/src/groove/mod.rs b/src/groove/mod.rs new file mode 100644 index 0000000..4ddb496 --- /dev/null +++ b/src/groove/mod.rs @@ -0,0 +1,490 @@ +use serde::{Deserialize, Serialize}; + +mod agr; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct GrooveNote { + pub time_beats: f64, + pub velocity: f32, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct GrooveTemplate { + pub name: String, + pub length_beats: f64, + pub notes: Vec, +} + +impl GrooveTemplate { + pub fn from_agr_bytes(bytes: &[u8]) -> Result { + agr::parse(bytes) + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum GrooveBase { + Eighth, + #[default] + Sixteenth, + ThirtySecond, +} + +impl std::fmt::Display for GrooveBase { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(match self { + Self::Eighth => "1/8", + Self::Sixteenth => "1/16", + Self::ThirtySecond => "1/32", + }) + } +} + +impl GrooveBase { + pub const ALL: [Self; 3] = [Self::Eighth, Self::Sixteenth, Self::ThirtySecond]; + + pub fn divisions_per_beat(self) -> f64 { + match self { + Self::Eighth => 2.0, + Self::Sixteenth => 4.0, + Self::ThirtySecond => 8.0, + } + } + + pub fn grid_samples(self, sample_rate: f64, bpm: f64) -> f64 { + sample_rate * 60.0 / bpm.max(1.0) / self.divisions_per_beat() + } +} + +#[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, + pub random: f32, + pub velocity: f32, +} + +impl Default for GrooveSettings { + fn default() -> Self { + Self { + base: GrooveBase::Sixteenth, + swing_percent: 73.0, + template: None, + quantize: 0.0, + timing: 100.0, + random: 0.0, + velocity: 0.0, + } + } +} + +impl GrooveSettings { + pub fn from_agr_bytes(bytes: &[u8]) -> Result { + let parsed = agr::parse_with_settings(bytes)?; + let base = match parsed.denominator { + 8 => GrooveBase::Eighth, + 16 => GrooveBase::Sixteenth, + 32 => GrooveBase::ThirtySecond, + denominator => { + return Err(format!( + "Unsupported Ableton groove grid denominator: {denominator}" + )); + } + }; + Ok(Self { + base, + template: Some(Box::new(parsed.template)), + quantize: parsed.quantize, + timing: parsed.timing, + random: parsed.random, + velocity: parsed.velocity, + ..Self::default() + }) + } + + pub fn grid_samples(&self, sample_rate: f64, bpm: f64) -> f64 { + self.base.grid_samples(sample_rate, bpm) + } + + fn unit(value: f32) -> f64 { + (value.clamp(0.0, 100.0) / 100.0) as f64 + } + + fn random_at_grid(grid_index: i64, seed: &str) -> f64 { + let mut hash = 0xcbf29ce484222325_u64; + for byte in seed.bytes().chain(grid_index.to_le_bytes()) { + hash ^= u64::from(byte); + hash = hash.wrapping_mul(0x100000001b3); + } + let unit = (hash >> 11) as f64 / ((1_u64 << 53) - 1) as f64; + unit * 2.0 - 1.0 + } + + fn template_note_at_grid(&self, grid_index: i64) -> Option<&GrooveNote> { + let template = self.template.as_ref()?; + let slots = (template.length_beats * self.base.divisions_per_beat()) + .round() + .max(1.0) as usize; + let slot = grid_index.rem_euclid(slots as i64) as usize; + if template.notes.len() == slots { + template.notes.get(slot) + } else { + template.notes.iter().find(|note| { + (note.time_beats * self.base.divisions_per_beat()).round() as i64 == slot as i64 + }) + } + } + + 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 random = Self::random_at_grid(grid_index, seed) * 0.05 * Self::unit(self.random); + grid_samples * (timing * Self::unit(self.timing) + random) + } + + pub fn offset_at_sample(&self, sample: f64, grid_samples: f64, seed: &str) -> f64 { + if grid_samples <= 0.0 || !grid_samples.is_finite() { + return 0.0; + } + let grid_position = sample.max(0.0) / grid_samples; + let grid_index = grid_position.floor() as i64; + let fraction = grid_position - grid_index as f64; + let from = self.offset_at_grid(grid_index, grid_samples, seed); + let to = self.offset_at_grid(grid_index + 1, grid_samples, seed); + from + (to - from) * fraction + } + + pub fn source_sample(&self, sample: f64, grid_samples: f64, seed: &str) -> f64 { + (sample - self.offset_at_sample(sample, grid_samples, seed)).max(0.0) + } + + pub fn tempo_at_grid(&self, grid_index: i64, grid_samples: f64, seed: &str) -> f64 { + let from = self.offset_at_grid(grid_index, grid_samples, seed); + let to = self.offset_at_grid(grid_index + 1, grid_samples, seed); + (grid_samples / (grid_samples + to - from).max(grid_samples * 0.25)).clamp(0.25, 4.0) + } + + pub fn map_midi_sample( + &self, + sample: usize, + grid_samples: f64, + seed: &str, + voice: u8, + ) -> usize { + if grid_samples <= 0.0 || !grid_samples.is_finite() { + return sample; + } + let sample = sample as f64; + let nearest_grid = (sample / grid_samples).round() * grid_samples; + let quantized = sample + (nearest_grid - sample) * Self::unit(self.quantize); + let voice_seed = format!("{seed}:voice-{voice}"); + (quantized + self.offset_at_sample(quantized, grid_samples, &voice_seed)) + .round() + .max(0.0) as usize + } + + pub fn midi_velocity_scale(&self, source_sample: usize, grid_samples: f64) -> f32 { + if grid_samples <= 0.0 { + return 1.0; + } + let grid_index = (source_sample as f64 / grid_samples).round() as i64; + if let Some(note) = self.template_note_at_grid(grid_index) { + let amount = self.velocity.clamp(-100.0, 100.0) / 100.0; + return 1.0 + (note.velocity / 100.0 - 1.0) * amount; + } + if self.velocity > 0.0 && grid_index.rem_euclid(2) == 1 { + 1.0 - 0.2 * self.velocity.clamp(0.0, 100.0) / 100.0 + } else { + 1.0 + } + } +} + +pub struct LiveGrooveShifterConfig { + pub sample_rate: usize, + pub channels: usize, + pub settings: GrooveSettings, + pub bpm: f64, + pub seed: String, + pub clip_start: usize, + pub source_offset: usize, +} + +pub struct LiveGrooveShifter { + sessions: Vec, + settings: GrooveSettings, + bpm: f64, + seeds: Vec, + sample_rate: u32, + epoch_origin: usize, + next_output_frame: usize, + next_grid_index: i64, + next_command_id: u64, + rendered: Vec>, + source_samples: Vec, + output_samples: Vec, +} + +impl LiveGrooveShifter { + pub fn new(config: LiveGrooveShifterConfig, output_frame: usize) -> Result { + let LiveGrooveShifterConfig { + sample_rate, + channels, + settings, + bpm, + seed, + clip_start, + source_offset, + } = config; + let channels = channels.clamp(1, 2); + let sample_rate = sample_rate.clamp(32_000, 192_000) as u32; + let grid_samples = settings.grid_samples(f64::from(sample_rate), bpm); + let local_output = output_frame.saturating_sub(clip_start) as f64; + let grid_index = (local_output / grid_samples).floor() as i64; + let seeds = (0..channels) + .map(|channel| format!("{seed}:groove-channel-{channel}")) + .collect::>(); + let mut sessions = Vec::with_capacity(channels); + for seed in &seeds { + let tempo = settings.tempo_at_grid(grid_index, grid_samples, seed); + let config = timestretch::SessionConfig { + source_sample_rate: sample_rate, + output_sample_rate: sample_rate, + channels: 1, + source_access: timestretch::SourceAccess::Seekable, + parameters: timestretch::Parameters::keylock( + timestretch::TempoRate::new(tempo).map_err(|error| error.to_string())?, + ), + max_commands: 4096, + ..timestretch::SessionConfig::default() + }; + let mut session = timestretch::StreamSession::prepare(config) + .map_err(|error| error.to_string())? + .activate(); + let source_frame = source_offset.saturating_add( + settings + .source_sample(local_output, grid_samples, seed) + .round() as usize, + ); + session + .seek(source_frame as u64) + .map_err(|error| error.to_string())?; + sessions.push(session); + } + Ok(Self { + sessions, + settings, + bpm, + seeds, + sample_rate, + epoch_origin: output_frame, + next_output_frame: output_frame, + next_grid_index: grid_index + 1, + next_command_id: 1, + rendered: vec![Vec::new(); channels], + source_samples: Vec::new(), + output_samples: Vec::new(), + }) + } + + fn schedule_until(&mut self, output_end: usize) -> Result<(), String> { + let grid_samples = self + .settings + .grid_samples(f64::from(self.sample_rate), self.bpm); + while (self.next_grid_index as f64 * grid_samples) < output_end as f64 { + let boundary = (self.next_grid_index as f64 * grid_samples).round() as usize; + let at_output_frame = boundary.saturating_sub(self.epoch_origin) as u64; + for (session, seed) in self.sessions.iter_mut().zip(&self.seeds) { + let tempo = self + .settings + .tempo_at_grid(self.next_grid_index, grid_samples, seed); + session + .schedule( + self.next_command_id, + at_output_frame, + timestretch::Parameters::keylock( + timestretch::TempoRate::new(tempo) + .map_err(|error| error.to_string())?, + ), + ) + .map_err(|error| error.to_string())?; + } + self.next_command_id += 1; + self.next_grid_index += 1; + } + Ok(()) + } + + pub fn render( + &mut self, + request_start_frame: usize, + frames: usize, + mut fill_input: F, + ) -> Result<&[Vec], String> + where + F: FnMut(usize, usize, &mut [f32]), + { + if request_start_frame != self.next_output_frame { + return Err("Groove renderer requires a transport reset".to_string()); + } + for channel in &mut self.rendered { + channel.clear(); + channel.resize(frames, 0.0); + } + self.schedule_until( + self.epoch_origin + .saturating_add(frames) + .saturating_add(65_536), + )?; + for (channel, session) in self.sessions.iter_mut().enumerate() { + let mut written = 0; + let mut idle_cycles = 0; + while written < frames { + if let Some(request) = session.source_request() { + self.source_samples.resize(request.frames, 0.0); + fill_input( + request.start_frame as usize, + channel, + &mut self.source_samples, + ); + session + .supply(request, &self.source_samples) + .map_err(|error| error.to_string())?; + } + session.advance(16_384); + self.output_samples.resize(frames - written, 0.0); + let stamp = session + .read_output(&mut self.output_samples) + .map_err(|error| error.to_string())?; + if stamp.frames == 0 { + idle_cycles += 1; + if idle_cycles > 128 { + return Err("Groove renderer made no progress".to_string()); + } + continue; + } + idle_cycles = 0; + self.rendered[channel][written..written + stamp.frames] + .copy_from_slice(&self.output_samples[..stamp.frames]); + written += stamp.frames; + session + .acknowledge( + stamp + .consumed(stamp.frames) + .map_err(|error| error.to_string())?, + ) + .map_err(|error| error.to_string())?; + } + } + self.next_output_frame = request_start_frame.saturating_add(frames); + Ok(&self.rendered) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn swing_16ths_73_delays_alternate_grid_positions() { + 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(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); + } + + #[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); + } + + #[test] + fn quantize_is_applied_before_swing() { + let groove = GrooveSettings { + quantize: 100.0, + ..GrooveSettings::default() + }; + assert_eq!(groove.map_midi_sample(5_900, 6_000.0, "clip", 0), 8_760); + } + + #[test] + #[cfg_attr(miri, ignore = "Timestretch DSP interpretation exceeds one minute")] + fn random_latency_differs_between_stereo_channels() { + let mut shifter = LiveGrooveShifter::new( + LiveGrooveShifterConfig { + sample_rate: 48_000, + channels: 2, + settings: GrooveSettings { + random: 100.0, + ..GrooveSettings::default() + }, + bpm: 120.0, + seed: "clip".to_string(), + clip_start: 0, + source_offset: 0, + }, + 0, + ) + .expect("groove shifter"); + let rendered = shifter + .render(0, 16_384, |start, _channel, samples| { + for (index, sample) in samples.iter_mut().enumerate() { + *sample = ((start + index) as f32 * 0.01).sin(); + } + }) + .expect("stereo groove"); + assert!( + rendered[0] + .iter() + .zip(&rendered[1]) + .any(|(left, right)| (left - right).abs() > 1.0e-5) + ); + } + + #[test] + #[cfg_attr(miri, ignore = "Timestretch DSP interpretation exceeds one minute")] + fn live_groove_renders_finite_sequential_blocks() { + let mut shifter = LiveGrooveShifter::new( + LiveGrooveShifterConfig { + sample_rate: 48_000, + channels: 1, + settings: GrooveSettings::default(), + bpm: 120.0, + seed: "clip".to_string(), + clip_start: 0, + source_offset: 0, + }, + 0, + ) + .expect("groove shifter"); + let mut fill = |start: usize, _channel: usize, samples: &mut [f32]| { + for (index, sample) in samples.iter_mut().enumerate() { + *sample = ((start + index) as f32 * 0.01).sin(); + } + }; + let first = shifter.render(0, 256, &mut fill).expect("first block"); + assert_eq!(first[0].len(), 256); + assert!(first[0].iter().all(|sample| sample.is_finite())); + let second = shifter.render(256, 256, fill).expect("second block"); + assert_eq!(second[0].len(), 256); + assert!(second[0].iter().all(|sample| sample.is_finite())); + } +} diff --git a/src/history.rs b/src/history.rs index 3cf427c..3267ab2 100644 --- a/src/history.rs +++ b/src/history.rs @@ -13,6 +13,7 @@ pub(crate) fn audio_clip_to_data( input_channel: clip.input_channel, muted: clip.muted, reversed: clip.reversed, + groove: clip.groove.clone(), gain_db: clip.gain_db, peaks_file: clip.peaks_file.clone(), fade_enabled: clip.fade_enabled, @@ -46,6 +47,7 @@ pub(crate) fn midi_clip_to_data( input_channel: clip.input_channel, muted: clip.muted, reversed: clip.reversed, + groove: clip.groove.clone(), grouped_clips: clip.grouped_clips.iter().map(midi_clip_to_data).collect(), } } diff --git a/src/lib.rs b/src/lib.rs index 8cd192f..fa909ba 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,6 +30,7 @@ pub mod connectable; mod cycle_trace; mod engine; pub use engine::Engine; +pub mod groove; pub mod history; mod hw; pub mod iodelay; diff --git a/src/message.rs b/src/message.rs index 5dc3671..66f5d99 100644 --- a/src/message.rs +++ b/src/message.rs @@ -335,6 +335,8 @@ pub struct AudioClipData { #[serde(default)] pub reversed: bool, #[serde(default)] + pub groove: Option, + #[serde(default)] pub gain_db: f32, pub peaks_file: Option, pub fade_enabled: bool, @@ -369,6 +371,8 @@ pub struct MidiClipData { pub muted: bool, #[serde(default)] pub reversed: bool, + #[serde(default)] + pub groove: Option, pub grouped_clips: Vec, } @@ -1142,6 +1146,7 @@ pub enum Action { input_channel: usize, muted: bool, reversed: bool, + groove: Option, gain_db: f32, peaks_file: Option, kind: Kind, @@ -1220,6 +1225,12 @@ pub enum Action { kind: Kind, reversed: bool, }, + SetClipGroove { + track_name: String, + clip_index: usize, + kind: Kind, + groove: Option, + }, SetClipGainDb { track_name: String, clip_index: usize, @@ -2115,6 +2126,7 @@ mod tests { input_channel: 1, muted: true, reversed: false, + groove: None, gain_db: 0.0, peaks_file: Some("peaks/group.json".to_string()), fade_enabled: false, @@ -2170,6 +2182,7 @@ mod tests { input_channel: 3, muted: true, reversed: false, + groove: None, grouped_clips: vec![MidiClipData { name: "child.mid".to_string(), start: 0, diff --git a/src/midi/clip.rs b/src/midi/clip.rs index 18f12b9..abe7b83 100644 --- a/src/midi/clip.rs +++ b/src/midi/clip.rs @@ -8,6 +8,7 @@ pub struct MIDIClip { pub input_channel: usize, pub muted: bool, pub reversed: bool, + pub groove: Option, pub grouped_clips: Vec, } @@ -22,6 +23,7 @@ impl MIDIClip { input_channel: 0, muted: false, reversed: false, + groove: None, grouped_clips: Vec::new(), } } diff --git a/src/osc.rs b/src/osc.rs index 6718691..5d0da6e 100644 --- a/src/osc.rs +++ b/src/osc.rs @@ -1541,6 +1541,7 @@ fn parse_add_clip(mut args: OscArgs<'_>) -> Result { input_channel, muted, reversed: false, + groove: None, gain_db: 0.0, peaks_file: None, kind, diff --git a/src/track/clip_render.rs b/src/track/clip_render.rs index bb69cec..1dd7973 100644 --- a/src/track/clip_render.rs +++ b/src/track/clip_render.rs @@ -756,6 +756,102 @@ impl TrackData { } } + fn render_grooved_audio_clip( + &mut self, + clip: &crate::audio::clip::AudioClip, + buffer: &Arc, + clip_start: usize, + absolute_from: usize, + request_len: usize, + out: &mut Vec>, + ) -> Option<()> { + 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 bpm = self.rt.tempo_bpm; + let valid = self + .rt + .clip_groove_shifters + .get(&key) + .is_some_and(|cached| { + cached.start == clip_start + && cached.end == clip.end + && cached.offset == clip.offset + && cached.settings == settings + && cached.bpm == bpm + }); + let seed = if clip.id.is_empty() { + clip.name.clone() + } else { + clip.id.clone() + }; + let mut cached = if valid { + self.rt.clip_groove_shifters.remove(&key)? + } else { + CachedClipGrooveShifter { + start: clip_start, + end: clip.end, + offset: clip.offset, + settings: settings.clone(), + bpm, + shifter: crate::groove::LiveGrooveShifter::new( + crate::groove::LiveGrooveShifterConfig { + sample_rate: self.sample_rate.round().max(1.0) as usize, + channels, + settings: settings.clone(), + bpm, + seed: seed.clone(), + clip_start, + source_offset: clip.offset, + }, + absolute_from, + ) + .ok()?, + } + }; + let mut window = std::mem::take(&mut self.rt.clip_window_scratch); + let mut bytes = std::mem::take(&mut self.rt.clip_window_bytes); + let mut window_interleaved = std::mem::take(&mut self.rt.clip_window_interleaved); + let rendered = + cached + .shifter + .render(absolute_from, request_len, |start, channel, samples| { + let source_channels = clip_sample_window( + buffer, + start, + samples.len(), + &mut window, + &mut bytes, + &mut window_interleaved, + ) + .unwrap_or(1); + let source_channel = if source_channels == 1 { 0 } else { channel }; + samples.fill(0.0); + if let Some(plane) = window.get(source_channel) { + samples.copy_from_slice(plane); + } + }); + self.rt.clip_window_scratch = window; + self.rt.clip_window_bytes = bytes; + self.rt.clip_window_interleaved = window_interleaved; + match rendered { + Ok(rendered) => { + reset_channel_buffers(out, input_count, request_len); + for (channel, block) in out.iter_mut().enumerate().take(channels) { + let source_channel = if channels == 1 { 0 } else { channel }; + block.copy_from_slice(&rendered[source_channel][..request_len]); + } + self.rt.clip_groove_shifters.insert(key, cached); + Some(()) + } + Err(error) => { + tracing::warn!("Groove rendering failed for '{}': {error}", clip.name); + None + } + } + } + pub(crate) fn render_audio_clip_segment( &mut self, clip: &crate::audio::clip::AudioClip, @@ -992,6 +1088,36 @@ impl TrackData { return Some(()); } + if clip.groove.is_some() + && !clip.reversed + && self + .render_grooved_audio_clip( + clip, + &buffer, + clip_start, + absolute_from, + request_len, + out, + ) + .is_some() + { + if clip.gain_db != 0.0 { + let gain = 10.0f32.powf(clip.gain_db / 20.0); + for channel in &mut *out { + crate::simd::mul_inplace(channel, gain); + } + } + Self::apply_audio_clip_fades(clip, clip_start, clip_len, absolute_from, out); + #[cfg(feature = "plugins")] + if has_clip_plugins + && let Ok(processed) = + self.process_clip_plugin_runtime_segment(clip, out, absolute_from, request_len) + { + *out = processed; + } + return Some(()); + } + // Reversed playback reads the source backwards, which the streaming // rings cannot do; read the needed window and walk it in reverse. #[cfg(feature = "audio")] @@ -1274,6 +1400,33 @@ impl TrackData { ) }; for (source_sample, data) in events.iter() { + if let Some(groove) = clip.groove.as_ref().filter(|_| !clip.reversed) { + let local_sample = source_sample.saturating_sub(clip.offset); + if local_sample >= clip_len { + continue; + } + let source_absolute = clip_start.saturating_add(local_sample); + let grid_samples = groove.grid_samples(self.sample_rate, self.rt.tempo_bpm); + let voice = data.get(1).copied().unwrap_or(0); + let absolute_sample = + groove.map_midi_sample(source_absolute, grid_samples, &clip.id, voice); + if absolute_sample < from || absolute_sample >= to { + continue; + } + 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; + } + let frame_idx = + out_offset.saturating_add(absolute_sample.saturating_sub(*segment_start)); + if frame_idx < frames { + input_events[input_lane].extend( + self.allocate_mpe_event(MidiEvent::new(frame_idx as u32, data)), + ); + } + continue; + } if *source_sample < source_from { continue; } diff --git a/src/track/mod.rs b/src/track/mod.rs index 9e0d814..2dec09f 100644 --- a/src/track/mod.rs +++ b/src/track/mod.rs @@ -101,6 +101,15 @@ pub(crate) struct ClipPitchShifter { shifter: LivePitchShifter, } +pub(crate) struct CachedClipGrooveShifter { + start: usize, + end: usize, + offset: usize, + settings: crate::groove::GrooveSettings, + bpm: f64, + shifter: crate::groove::LiveGrooveShifter, +} + #[cfg(feature = "plugins")] #[derive(Debug)] pub(crate) struct ClipPluginRuntime { @@ -798,6 +807,7 @@ pub struct TrackRt { #[cfg(feature = "plugins")] active_clip_plugin_keys: HashSet>, pub(crate) clip_pitch_shifters: HashMap, + pub(crate) clip_groove_shifters: HashMap, midi_clip_cache: HashMap, internal_output_routes_cache: Vec>>, audio_route_cache_dirty: bool, @@ -873,6 +883,7 @@ impl TrackRt { #[cfg(feature = "plugins")] active_clip_plugin_keys: HashSet::new(), clip_pitch_shifters: HashMap::new(), + clip_groove_shifters: HashMap::new(), midi_clip_cache: HashMap::new(), internal_output_routes_cache: Vec::new(), audio_route_cache_dirty: true, @@ -1941,6 +1952,80 @@ mod tests { ); } + #[test] + #[cfg_attr(miri, ignore = "Timestretch DSP interpretation exceeds one minute")] + fn audio_groove_renders_buffered_clip() { + let mut track = Track::new("t".to_string(), 1, 1, 0, 0, 256, 48_000.0); + let samples = (0..24_000) + .map(|index| (index as f32 * 0.01).sin()) + .collect(); + track.insert_audio_clip_buffer_for_test( + "clip.wav", + Arc::new(AudioClipBuffer::Buffered { + channels: 1, + samples, + }), + ); + let mut clip = AudioClip::new("clip.wav".to_string(), 0, 12_000); + clip.id = "grooved".to_string(); + clip.fade_enabled = false; + clip.groove = Some(crate::groove::GrooveSettings::default()); + let mut out = Vec::new(); + #[cfg(feature = "plugins")] + let mut active_clip_plugin_keys = std::collections::HashSet::new(); + + track + .render_audio_clip_segment( + &clip, + 0, + 0, + 256, + #[cfg(feature = "plugins")] + &mut active_clip_plugin_keys, + &mut out, + ) + .expect("first grooved block"); + track + .render_audio_clip_segment( + &clip, + 0, + 256, + 256, + #[cfg(feature = "plugins")] + &mut active_clip_plugin_keys, + &mut out, + ) + .expect("second grooved block"); + + assert_eq!(out.len(), 1); + assert_eq!(out[0].len(), 256); + assert!(out[0].iter().all(|sample| sample.is_finite())); + assert!(out[0].iter().any(|sample| sample.abs() > f32::EPSILON)); + } + + #[test] + fn midi_groove_delays_events_into_later_render_blocks() { + let mut track = Track::new("t".to_string(), 0, 0, 1, 1, 1024, 48_000.0); + 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()); + track.rt.midi_clip_cache.insert( + "clip.mid".to_string(), + Arc::new(vec![ + (6_000, vec![0x90, 60, 100]), + (6_100, vec![0x80, 60, 64]), + ]), + ); + let mut events = vec![Vec::new()]; + + 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); + } + #[test] fn midi_clip_emits_note_off_at_exact_clip_end() { let mut track = Track::new("t".to_string(), 0, 0, 1, 1, 8, 48_000.0);