Repository Public
1//! ORIX Sonata2//! File: crates/sonata-ir/src/overrides.rs3//! Description: Studio overrides — explicit, reversible edits made in the visual studio and4//! stored beside the code (`studio.json`). The code stays canonical: overrides are applied to the5//! compiled Program, each one carries the fingerprint of what it edited, and an override whose6//! target changed in the code is reported as a conflict and skipped, never applied blindly.7//!8//! Author: Simon-Pierre Boucher9//! Contact: contact@spboucher.ai1011use crate::music::{Articulation, NoteEvent, Program};12use crate::time::Rational;13use serde::{Deserialize, Serialize};1415/// Mixer state set from the studio for one strip, by name (`master` for the master strip).16#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]17pub struct StripOverride {18 pub strip: String,19 #[serde(default, skip_serializing_if = "Option::is_none")]20 pub gain_db: Option<f64>,21 #[serde(default, skip_serializing_if = "Option::is_none")]22 pub pan: Option<f64>,23 #[serde(default, skip_serializing_if = "Option::is_none")]24 pub mute: Option<bool>,25 #[serde(default, skip_serializing_if = "Option::is_none")]26 pub solo: Option<bool>,27}2829/// An edit of one compiled note, addressed by track name and the note's compile index (the low30/// 32 bits of `NoteEvent::id`), guarded by the note's original start and pitch.31#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]32pub struct NoteOverride {33 pub track: String,34 pub index: u32,35 /// Fingerprint: start and pitch of the note when the override was made.36 pub original_start: Rational,37 pub original_pitch: f64,38 #[serde(default, skip_serializing_if = "Option::is_none")]39 pub start: Option<Rational>,40 #[serde(default, skip_serializing_if = "Option::is_none")]41 pub duration: Option<Rational>,42 #[serde(default, skip_serializing_if = "Option::is_none")]43 pub pitch: Option<f64>,44 #[serde(default, skip_serializing_if = "Option::is_none")]45 pub velocity: Option<f32>,46 #[serde(default)]47 pub deleted: bool,48}4950/// A note drawn in the studio that does not exist in the code.51#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]52pub struct AddedNote {53 pub track: String,54 pub start: Rational,55 pub duration: Rational,56 pub pitch: f64,57 pub velocity: f32,58}5960#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]61pub struct Overrides {62 #[serde(default)]63 pub strips: Vec<StripOverride>,64 #[serde(default)]65 pub notes: Vec<NoteOverride>,66 /// Notes added in the studio, appended after the code's notes of their track.67 #[serde(default)]68 pub added: Vec<AddedNote>,69}7071/// An override that could not be applied.72#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]73pub struct OverrideConflict {74 /// `strip`, `note` or `added`.75 pub kind: String,76 /// Index in `Overrides::strips` or `Overrides::notes`.77 pub index: u32,78 pub reason: String,79}8081impl Overrides {82 pub fn is_empty(&self) -> bool {83 self.strips.is_empty() && self.notes.is_empty() && self.added.is_empty()84 }8586 /// Applies the overrides. Values are clamped to the same ranges the language enforces87 /// (gain -120..+24 dB, pan -1..1, velocity 0..1, pitch 0..127, positive durations).88 /// Returns the overrides that were skipped, with the reason.89 pub fn apply(&self, program: &mut Program) -> Vec<OverrideConflict> {90 let mut conflicts = Vec::new();91 for (i, s) in self.strips.iter().enumerate() {92 let gain = s.gain_db.filter(|g| g.is_finite()).map(|g| g.clamp(-120.0, 24.0));93 let pan = s.pan.filter(|p| p.is_finite()).map(|p| p.clamp(-1.0, 1.0));94 if s.strip == "master" {95 if let Some(g) = gain {96 program.master.gain_db = g;97 }98 continue;99 }100 if let Some(t) = program.tracks.iter_mut().find(|t| t.name == s.strip) {101 if let Some(g) = gain {102 t.gain_db = g;103 }104 if let Some(p) = pan {105 t.pan = p;106 }107 if let Some(m) = s.mute {108 t.mute = m;109 }110 if let Some(m) = s.solo {111 t.solo = m;112 }113 } else if let Some(b) = program.buses.iter_mut().find(|b| b.name == s.strip) {114 if let Some(g) = gain {115 b.gain_db = g;116 }117 if let Some(p) = pan {118 b.pan = p;119 }120 if let Some(m) = s.mute {121 b.mute = m;122 }123 } else {124 conflicts.push(OverrideConflict {125 kind: "strip".into(),126 index: i as u32,127 reason: format!("no track or bus named '{}' in the code any more", s.strip),128 });129 }130 }131 let mut delete: Vec<(usize, usize)> = Vec::new();132 for (i, o) in self.notes.iter().enumerate() {133 let Some((ti, track)) = program.tracks.iter_mut().enumerate().find(|(_, t)| t.name == o.track) else {134 conflicts.push(OverrideConflict { kind: "note".into(), index: i as u32, reason: format!("no track named '{}' in the code any more", o.track) });135 continue;136 };137 // Notes are addressed by the index the compiler gave them (low 32 bits of the id), so138 // an address stays valid whatever order the notes are in.139 let Some(pos) = track.notes.iter().position(|n| n.id & 0xffff_ffff == o.index as u64) else {140 conflicts.push(OverrideConflict {141 kind: "note".into(),142 index: i as u32,143 reason: format!("track '{}' has no note #{} any more", o.track, o.index),144 });145 continue;146 };147 let note = &mut track.notes[pos];148 if note.notated_start != o.original_start || (note.pitch - o.original_pitch).abs() > 1e-9 {149 conflicts.push(OverrideConflict {150 kind: "note".into(),151 index: i as u32,152 reason: format!("note #{} of '{}' was changed in the code after this edit", o.index, o.track),153 });154 continue;155 }156 if o.deleted {157 delete.push((ti, pos));158 continue;159 }160 if let Some(s) = o.start.filter(|s| !s.is_negative()) {161 note.start = s;162 note.notated_start = s;163 }164 if let Some(d) = o.duration.filter(|d| *d > Rational::ZERO) {165 note.duration = d;166 note.notated_duration = d;167 }168 if let Some(p) = o.pitch.filter(|p| p.is_finite()) {169 note.pitch = p.clamp(0.0, 127.0);170 }171 if let Some(v) = o.velocity.filter(|v| v.is_finite()) {172 note.velocity = v.clamp(0.0, 1.0);173 }174 let end = note.start.checked_add(note.duration).unwrap_or(note.start);175 note.start_sec = program.tempo_map.seconds_at(note.start);176 note.end_sec = program.tempo_map.seconds_at(end);177 }178 // Delete from the highest index down so earlier indices stay valid; ids are kept.179 delete.sort_by(|a, b| b.cmp(a));180 delete.dedup();181 for (ti, ni) in delete {182 program.tracks[ti].notes.remove(ni);183 }184 // Added notes get ids above every compiled note of their track: (track << 32) | 0x8000_0000 | n.185 for (i, a) in self.added.iter().enumerate() {186 let Some(track) = program.tracks.iter_mut().find(|t| t.name == a.track) else {187 conflicts.push(OverrideConflict {188 kind: "added".into(),189 index: i as u32,190 reason: format!("no track named '{}' in the code any more", a.track),191 });192 continue;193 };194 if a.start.is_negative() || a.duration <= Rational::ZERO || !a.pitch.is_finite() || !a.velocity.is_finite() {195 conflicts.push(OverrideConflict {196 kind: "added".into(),197 index: i as u32,198 reason: "the added note has an invalid position, length, pitch or velocity".into(),199 });200 continue;201 }202 let end = a.start.checked_add(a.duration).unwrap_or(a.start);203 track.notes.push(NoteEvent {204 id: ((track.id as u64) << 32) | 0x8000_0000 | i as u64,205 start: a.start,206 duration: a.duration,207 notated_start: a.start,208 notated_duration: a.duration,209 start_sec: program.tempo_map.seconds_at(a.start),210 end_sec: program.tempo_map.seconds_at(end),211 pitch: a.pitch.clamp(0.0, 127.0),212 velocity: a.velocity.clamp(0.0, 1.0),213 voice: 0,214 articulation: Articulation::Normal,215 tied_from_previous: false,216 bend: Vec::new(),217 span: track.span,218 });219 }220 if !self.notes.is_empty() || !self.added.is_empty() {221 for t in &mut program.tracks {222 t.notes.sort_by(|a, b| a.start.cmp(&b.start).then(a.pitch.total_cmp(&b.pitch)).then(a.id.cmp(&b.id)));223 }224 }225 program.refresh_stats();226 conflicts227 }228}229230#[cfg(test)]231mod tests {232 use super::*;233 use crate::diag::Span;234 use crate::music::*;235236 fn program() -> Program {237 let mut p = Program::empty("t");238 let q = Rational::new(1, 4).unwrap();239 let mk = |i: u64, start: Rational, pitch: f64| NoteEvent {240 id: i,241 start,242 duration: q,243 notated_start: start,244 notated_duration: q,245 start_sec: start.to_f64() * 2.0,246 end_sec: start.to_f64() * 2.0 + 0.5,247 pitch,248 velocity: 0.8,249 voice: 0,250 articulation: Articulation::Normal,251 tied_from_previous: false,252 bend: vec![],253 span: Span::default(),254 };255 p.tracks.push(Track {256 id: 0,257 name: "piano".into(),258 kind: TrackKind::Instrument,259 instrument: None,260 gain_db: -8.0,261 pan: 0.0,262 mute: false,263 solo: false,264 effects: vec![],265 sends: vec![],266 output: Output::Master,267 notes: vec![mk(0, Rational::ZERO, 60.0), mk(1, q, 62.0), mk(2, Rational::new(1, 2).unwrap(), 64.0)],268 clips: vec![],269 automation: vec![],270 score_transposition: 0,271 span: Span::default(),272 });273 p.refresh_stats();274 p275 }276277 #[test]278 fn applies_and_reports_conflicts() {279 let mut p = program();280 let q = Rational::new(1, 4).unwrap();281 let o = Overrides {282 strips: vec![283 StripOverride { strip: "piano".into(), gain_db: Some(99.0), pan: Some(-0.5), mute: None, solo: Some(true) },284 StripOverride { strip: "ghost".into(), ..Default::default() },285 ],286 notes: vec![287 NoteOverride {288 track: "piano".into(),289 index: 1,290 original_start: q,291 original_pitch: 62.0,292 start: Some(Rational::ONE),293 duration: None,294 pitch: Some(65.0),295 velocity: Some(2.0),296 deleted: false,297 },298 NoteOverride {299 track: "piano".into(),300 index: 0,301 original_start: Rational::ZERO,302 original_pitch: 60.0,303 start: None,304 duration: None,305 pitch: None,306 velocity: None,307 deleted: true,308 },309 NoteOverride {310 track: "piano".into(),311 index: 2,312 original_start: q,313 original_pitch: 64.0,314 start: None,315 duration: None,316 pitch: Some(10.0),317 velocity: None,318 deleted: false,319 },320 ],321 added: vec![],322 };323 let conflicts = o.apply(&mut p);324 assert_eq!(conflicts.len(), 2);325 assert!(conflicts[0].reason.contains("ghost"));326 assert!(conflicts[1].reason.contains("changed in the code"));327 let t = &p.tracks[0];328 assert_eq!((t.gain_db, t.pan, t.solo), (24.0, -0.5, true));329 assert_eq!(t.notes.len(), 2);330 assert_eq!(t.notes[0].pitch, 64.0, "untouched note");331 let moved = &t.notes[1];332 assert_eq!((moved.start, moved.pitch, moved.velocity), (Rational::ONE, 65.0, 1.0));333 assert!((moved.start_sec - 2.0).abs() < 1e-12 && (moved.end_sec - 2.5).abs() < 1e-12);334 assert!((p.end_sec - 2.5).abs() < 1e-12);335 let json = serde_json::to_string(&o).unwrap();336 assert_eq!(serde_json::from_str::<Overrides>(&json).unwrap(), o);337 assert!(serde_json::from_str::<Overrides>("{}").unwrap().is_empty());338339 let mut p = program();340 let add = Overrides {341 added: vec![342 AddedNote { track: "piano".into(), start: Rational::new(3, 4).unwrap(), duration: q, pitch: 72.0, velocity: 0.5 },343 AddedNote { track: "nobody".into(), start: Rational::ZERO, duration: q, pitch: 60.0, velocity: 0.5 },344 AddedNote { track: "piano".into(), start: Rational::ZERO, duration: Rational::ZERO, pitch: 60.0, velocity: 0.5 },345 ],346 ..Default::default()347 };348 let conflicts = add.apply(&mut p);349 assert_eq!(conflicts.len(), 2);350 assert_eq!(p.tracks[0].notes.len(), 4);351 let n = p.tracks[0].notes.last().unwrap();352 assert_eq!((n.pitch, n.start_sec, n.end_sec), (72.0, 1.5, 2.0));353 assert_eq!(n.id & 0x8000_0000, 0x8000_0000);354 }355}356