SPB Git

Repository Public

music.rs 14.7 KB 466 lines rust

1//! ORIX Sonata2//! File: crates/sonata-ir/src/music.rs3//! Description: Musical IR — the compiled, fully evaluated composition: tracks, timestamped4//! notes, tempo map, automation, buses, markers. Sample-rate independent.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use crate::diag::Span;10use crate::patch::PatchSpec;11use crate::time::{Rational, SignaturePoint, TempoMap};12use serde::{Deserialize, Serialize};13use std::collections::BTreeMap;1415/// Version of the IR schema. Bumped on any incompatible change of the serialised form.16pub const IR_VERSION: u32 = 1;1718/// A parameter value in canonical units: seconds, hertz, decibels, linear ratios, semitones.19#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]20#[serde(untagged)]21pub enum ParamValue {22    Num(f64),23    List(Vec<f64>),24    Text(String),25}2627impl ParamValue {28    pub fn as_f64(&self) -> Option<f64> {29        match self {30            ParamValue::Num(v) => Some(*v),31            _ => None,32        }33    }34    pub fn as_list(&self) -> Option<&[f64]> {35        match self {36            ParamValue::List(v) => Some(v),37            _ => None,38        }39    }40    pub fn as_text(&self) -> Option<&str> {41        match self {42            ParamValue::Text(v) => Some(v),43            _ => None,44        }45    }46}4748pub type Params = BTreeMap<String, ParamValue>;4950/// A fully resolved instrument: a registry engine (`model`) plus parameter overrides.51///52/// Slots written `excitation pluck(position: 0.35)` are flattened: `"excitation" = Text("pluck")`53/// and `"excitation.position" = Num(0.35)`. Parameters absent from `params` take the engine default.54#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]55pub struct InstrumentSpec {56    /// Name of the definition in source (`GrandPiano`, `CrystalHarp`).57    pub name: String,58    /// Registry engine identifier (`piano`, `plucked_string`, `patch`, ...).59    pub model: String,60    pub params: Params,61    /// Present only when `model == "patch"`.62    #[serde(default, skip_serializing_if = "Option::is_none")]63    pub patch: Option<PatchSpec>,64}6566/// One effect in an insert chain. `params` hold canonical units; `mix` is dry/wet in [0, 1].67#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]68pub struct EffectSpec {69    pub kind: String,70    #[serde(default, skip_serializing_if = "Option::is_none")]71    pub preset: Option<String>,72    pub params: Params,73    pub mix: f64,74    pub bypass: bool,75    pub span: Span,76}7778#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]79#[serde(rename_all = "snake_case")]80pub enum Articulation {81    Normal,82    Legato,83    Staccato,84    Staccatissimo,85    Tenuto,86    Marcato,87    Accent,88    Pizzicato,89    Tremolo,90}9192/// A point of a per-note pitch curve (pitch bend / glide), relative to the note start.93#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]94pub struct BendPoint {95    pub offset_sec: f64,96    pub semitones: f64,97}9899/// One sounding note. `start`/`duration` are the **sounding** values after swing, tuplets, ties100/// and articulation were applied; `notated_start`/`notated_duration` keep the written values101/// for the score. Seconds are derived from the tempo map; samples are derived from seconds with102/// [`crate::time::seconds_to_samples`] at the rate in use.103#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]104pub struct NoteEvent {105    /// Stable within a compilation of the same source: `(track id << 32) | index in track`.106    pub id: u64,107    pub start: Rational,108    pub duration: Rational,109    pub notated_start: Rational,110    pub notated_duration: Rational,111    pub start_sec: f64,112    pub end_sec: f64,113    /// MIDI note number, fractional for microtones (69.0 = A4 = the tuning reference).114    pub pitch: f64,115    /// Linear velocity in [0, 1].116    pub velocity: f32,117    /// Voice (polyphonic line) inside the track; 0 unless `voice` blocks are used.118    pub voice: u32,119    pub articulation: Articulation,120    /// True when this note continues from a tie and must be merged for the score (already merged for audio).121    #[serde(default, skip_serializing_if = "std::ops::Not::not")]122    pub tied_from_previous: bool,123    #[serde(default, skip_serializing_if = "Vec::is_empty")]124    pub bend: Vec<BendPoint>,125    pub span: Span,126}127128#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]129#[serde(rename_all = "snake_case")]130pub enum Curve {131    /// Hold the previous value until this point.132    Step,133    Linear,134    /// Exponential approach (perceptually even for gains and frequencies).135    Exponential,136}137138#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]139pub struct AutomationPoint {140    pub at: Rational,141    pub at_sec: f64,142    /// Canonical unit of the target parameter.143    pub value: f64,144    /// Shape of the segment that **ends** at this point.145    pub curve: Curve,146}147148#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]149#[serde(tag = "kind", rename_all = "snake_case")]150pub enum AutomationTarget {151    /// Track or bus fader, in dB.152    Gain,153    /// Pan in [-1, 1].154    Pan,155    /// Parameter `param` of the effect at `index` in the insert chain.156    Effect { index: u32, param: String },157    /// A numeric instrument parameter.158    Instrument { param: String },159}160161#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]162pub struct AutomationLane {163    pub target: AutomationTarget,164    /// Sorted by `at`, at least one point.165    pub points: Vec<AutomationPoint>,166    pub span: Span,167}168169/// Where a track or bus sends its post-fader signal.170#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]171#[serde(tag = "kind", content = "bus", rename_all = "snake_case")]172pub enum Output {173    Master,174    Bus(u32),175}176177#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]178pub struct Send {179    pub bus: u32,180    pub gain_db: f64,181    pub pre_fader: bool,182}183184/// An audio asset placed on a track. `asset` is a path relative to the project's `assets/`185/// directory (validated: no `..`, no absolute path, no symlink escape).186#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]187pub struct AudioClip {188    pub asset: String,189    pub start: Rational,190    pub start_sec: f64,191    /// Offset into the asset, seconds.192    pub offset_sec: f64,193    /// Played length in seconds; `None` plays to the end of the asset.194    pub length_sec: Option<f64>,195    pub gain_db: f64,196    pub fade_in_sec: f64,197    pub fade_out_sec: f64,198    pub span: Span,199}200201#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]202#[serde(rename_all = "snake_case")]203pub enum TrackKind {204    Instrument,205    Audio,206}207208#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]209pub struct Track {210    /// Stable identifier: declaration order in the composition, starting at 0.211    pub id: u32,212    pub name: String,213    pub kind: TrackKind,214    /// `None` for audio tracks.215    pub instrument: Option<InstrumentSpec>,216    pub gain_db: f64,217    pub pan: f64,218    pub mute: bool,219    pub solo: bool,220    pub effects: Vec<EffectSpec>,221    pub sends: Vec<Send>,222    pub output: Output,223    /// Sorted by `(start, pitch, id)`.224    pub notes: Vec<NoteEvent>,225    pub clips: Vec<AudioClip>,226    pub automation: Vec<AutomationLane>,227    /// Written transposition of the instrument in semitones (score only; audio is concert pitch).228    #[serde(default)]229    pub score_transposition: i32,230    pub span: Span,231}232233#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]234pub struct Bus {235    pub id: u32,236    pub name: String,237    pub gain_db: f64,238    pub pan: f64,239    pub mute: bool,240    pub effects: Vec<EffectSpec>,241    pub sends: Vec<Send>,242    pub output: Output,243    pub automation: Vec<AutomationLane>,244    pub span: Span,245}246247#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]248pub struct MasterSpec {249    /// Project sample rate in Hz (44100, 48000, 88200, 96000, 176400, 192000).250    pub sample_rate: u32,251    pub gain_db: f64,252    /// Ceiling of the safety limiter in dBFS; `None` disables the limiter (scientific exports).253    pub peak_limit_db: Option<f64>,254    pub effects: Vec<EffectSpec>,255    pub automation: Vec<AutomationLane>,256}257258impl Default for MasterSpec {259    fn default() -> Self {260        MasterSpec { sample_rate: 48_000, gain_db: 0.0, peak_limit_db: Some(-1.0), effects: Vec::new(), automation: Vec::new() }261    }262}263264#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]265pub struct Marker {266    pub name: String,267    pub at: Rational,268    pub at_sec: f64,269    pub span: Span,270}271272#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]273#[serde(rename_all = "snake_case")]274pub enum Mode {275    Major,276    Minor,277    Dorian,278    Phrygian,279    Lydian,280    Mixolydian,281    Locrian,282    HarmonicMinor,283    MelodicMinor,284    PentatonicMajor,285    PentatonicMinor,286    Blues,287    WholeTone,288    Chromatic,289}290291#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]292pub struct Key {293    /// Pitch class of the tonic, 0 = C ... 11 = B.294    pub tonic: u8,295    /// Accidentals of the written tonic: -1 flat, 0 natural, +1 sharp (for score spelling).296    pub tonic_accidental: i8,297    /// Letter of the written tonic, 0 = C, 1 = D ... 6 = B.298    pub tonic_letter: u8,299    pub mode: Mode,300}301302/// Counters reported by the compiler and shown by the studio.303#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]304pub struct ProgramStats {305    pub tracks: u32,306    pub notes: u64,307    pub automation_points: u64,308    /// Largest number of simultaneously sounding notes (before release tails).309    pub max_polyphony: u32,310    pub duration_sec: f64,311}312313/// The compiled composition. This is the single artefact exchanged between the compiler and314/// every consumer (runtime, renderer, score, MIDI export, studio).315#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]316pub struct Program {317    pub ir_version: u32,318    /// Language version the source was compiled as (`"0.1"`).319    pub language_version: String,320    pub title: String,321    pub seed: u64,322    /// Frequency of A4 in Hz.323    pub tuning_hz: f64,324    pub key: Option<Key>,325    pub tempo_map: TempoMap,326    /// At least one point, the first at position 0.327    pub signatures: Vec<SignaturePoint>,328    pub tracks: Vec<Track>,329    pub buses: Vec<Bus>,330    pub master: MasterSpec,331    pub markers: Vec<Marker>,332    /// Musical end of the composition (end of the last note, clip or automation point).333    pub end: Rational,334    pub end_sec: f64,335    pub stats: ProgramStats,336}337338impl Program {339    pub fn empty(title: &str) -> Program {340        Program {341            ir_version: IR_VERSION,342            language_version: "0.1".into(),343            title: title.into(),344            seed: 0,345            tuning_hz: 440.0,346            key: None,347            tempo_map: TempoMap::default(),348            signatures: vec![SignaturePoint { at: Rational::ZERO, numerator: 4, denominator: 4 }],349            tracks: Vec::new(),350            buses: Vec::new(),351            master: MasterSpec::default(),352            markers: Vec::new(),353            end: Rational::ZERO,354            end_sec: 0.0,355            stats: ProgramStats::default(),356        }357    }358359    /// Frequency in Hz of a (possibly fractional) MIDI pitch under this program's tuning.360    pub fn pitch_to_hz(&self, pitch: f64) -> f64 {361        self.tuning_hz * ((pitch - 69.0) / 12.0).exp2()362    }363364    /// Recomputes `stats`, `end` and `end_sec` from the content.365    pub fn refresh_stats(&mut self) {366        let mut notes = 0u64;367        let mut auto = 0u64;368        let mut end = Rational::ZERO;369        let mut end_sec = 0.0f64;370        let mut edges: Vec<(f64, i32)> = Vec::new();371        for t in &self.tracks {372            notes += t.notes.len() as u64;373            for n in &t.notes {374                if let Some(e) = n.start.checked_add(n.duration) {375                    end = end.max(e);376                }377                end_sec = end_sec.max(n.end_sec);378                edges.push((n.start_sec, 1));379                edges.push((n.end_sec, -1));380            }381            for c in &t.clips {382                end = end.max(c.start);383                if let Some(l) = c.length_sec {384                    end_sec = end_sec.max(c.start_sec + l);385                }386            }387            for a in &t.automation {388                auto += a.points.len() as u64;389            }390        }391        for b in &self.buses {392            for a in &b.automation {393                auto += a.points.len() as u64;394            }395        }396        for a in &self.master.automation {397            auto += a.points.len() as u64;398        }399        // Note-offs sort before note-ons at the same instant: touching notes are not simultaneous.400        edges.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal).then(a.1.cmp(&b.1)));401        let (mut cur, mut max) = (0i32, 0i32);402        for (_, d) in edges {403            cur += d;404            max = max.max(cur);405        }406        self.end = end;407        self.end_sec = end_sec;408        self.stats = ProgramStats { tracks: self.tracks.len() as u32, notes, automation_points: auto, max_polyphony: max.max(0) as u32, duration_sec: end_sec };409    }410}411412#[cfg(test)]413mod tests {414    use super::*;415416    fn note(id: u64, s: f64, e: f64) -> NoteEvent {417        NoteEvent {418            id,419            start: Rational::approximate(s / 2.0, 960).unwrap(),420            duration: Rational::approximate((e - s) / 2.0, 960).unwrap(),421            notated_start: Rational::ZERO,422            notated_duration: Rational::ZERO,423            start_sec: s,424            end_sec: e,425            pitch: 60.0,426            velocity: 0.8,427            voice: 0,428            articulation: Articulation::Normal,429            tied_from_previous: false,430            bend: Vec::new(),431            span: Span::default(),432        }433    }434435    #[test]436    fn stats_and_round_trip() {437        let mut p = Program::empty("t");438        p.tracks.push(Track {439            id: 0,440            name: "a".into(),441            kind: TrackKind::Instrument,442            instrument: Some(InstrumentSpec { name: "X".into(), model: "sine".into(), params: Params::new(), patch: None }),443            gain_db: 0.0,444            pan: 0.0,445            mute: false,446            solo: false,447            effects: vec![],448            sends: vec![],449            output: Output::Master,450            notes: vec![note(0, 0.0, 1.0), note(1, 0.5, 1.5), note(2, 1.0, 2.0)],451            clips: vec![],452            automation: vec![],453            score_transposition: 0,454            span: Span::default(),455        });456        p.refresh_stats();457        assert_eq!(p.stats.notes, 3);458        assert_eq!(p.stats.max_polyphony, 2);459        assert!((p.end_sec - 2.0).abs() < 1e-12);460        assert!((p.pitch_to_hz(69.0) - 440.0).abs() < 1e-9);461        assert!((p.pitch_to_hz(81.0) - 880.0).abs() < 1e-9);462        let j = serde_json::to_string(&p).unwrap();463        assert_eq!(serde_json::from_str::<Program>(&j).unwrap(), p);464    }465}466
Files main
Menu

Theme