SPB Git

Repository Public

exec.rs 65.3 KB 1,518 lines rust

1//! ORIX Sonata2//! File: crates/sonata-semantics/src/exec.rs3//! Description: Execution of composition, track, bus and master statements: the cursor model,4//! voices, tuplets, swing, ties, articulations, tempo and signature changes, automation, and5//! the final assembly of the Musical IR.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use crate::builtins;11use crate::eval::{int_of, Analyzer, GlobalKind, SplitMix64, Stop, R};12use crate::value::{Num, Value};13use sonata_ir::*;14use sonata_parser::ast::*;15use std::collections::HashMap;16use std::rc::Rc;1718/// Sample rates a project may use.19pub const SAMPLE_RATES: &[u32] = &[44_100, 48_000, 88_200, 96_000, 176_400, 192_000];2021#[derive(Clone, Copy, PartialEq, Eq, Debug)]22pub(crate) enum Ctx {23    Composition,24    Track,25    Audio,26    Bus,27    Master,28}2930impl Ctx {31    fn label(self) -> &'static str {32        match self {33            Ctx::Composition => "a composition",34            Ctx::Track => "an instrument track",35            Ctx::Audio => "an audio track",36            Ctx::Bus => "a bus",37            Ctx::Master => "the master",38        }39    }40}4142/// The time context threaded through track statements.43#[derive(Clone, Debug)]44pub(crate) struct Cur {45    pub pos: Rational,46    pub voice: u32,47    pub transpose: f64,48    /// Swing ratio and unit.49    pub swing: Option<(Rational, Rational)>,50    /// Product of the enclosing tuplet ratios.51    pub scale: Rational,52}5354impl Cur {55    fn start(swing: Option<(Rational, Rational)>) -> Cur {56        Cur { pos: Rational::ZERO, voice: 0, transpose: 0.0, swing, scale: Rational::ONE }57    }58}5960pub(crate) struct PendingNote {61    nstart: Rational,62    ndur: Rational,63    delay: Rational,64    pitch: f64,65    velocity: f32,66    voice: u32,67    articulation: Articulation,68    bend: Vec<BendPoint>,69    span: Span,70    order: u32,71}7273pub(crate) struct PendingLane {74    target: AutomationTarget,75    points: Vec<(Rational, f64, Curve)>,76    span: Span,77}7879#[derive(Default)]80pub(crate) struct Strip {81    gain_db: f64,82    pan: f64,83    mute: bool,84    solo: bool,85    effects: Vec<EffectSpec>,86    sends: Vec<(Ident, f64, bool)>,87    output: Option<Ident>,88    automation: Vec<PendingLane>,89}9091struct PendingClip {92    asset: String,93    start: Rational,94    offset_sec: f64,95    length_sec: Option<f64>,96    gain_db: f64,97    fade_in_sec: f64,98    fade_out_sec: f64,99    span: Span,100}101102pub(crate) struct TrackBuild {103    id: u32,104    name: Ident,105    kind: TrackKind,106    instrument: Option<Rc<InstrumentSpec>>,107    range: Option<(u8, u8)>,108    strip: Strip,109    notes: Vec<PendingNote>,110    clips: Vec<PendingClip>,111    default_dur: Rational,112    default_vel: f64,113    articulation: Articulation,114    next_voice: u32,115    score_transposition: i32,116    /// Open ties: (voice, pitch bits) → index of the note waiting for its continuation.117    open_ties: HashMap<(u32, u64), usize>,118    range_warnings: u32,119    span: Span,120}121122enum TempoEvent {123    Set(f64),124    RampStart,125    RampEnd(f64),126}127128pub(crate) struct Comp {129    title: String,130    seed: u64,131    tuning: f64,132    tempo: Vec<(Rational, TempoEvent, Span)>,133    swing: Option<(Rational, Rational)>,134    tracks: Vec<TrackBuild>,135    buses: Vec<(Ident, Strip, Span)>,136    master: Strip,137    sample_rate: u32,138    peak_limit: Option<f64>,139    markers: Vec<(String, Rational, Span)>,140}141142impl Default for Comp {143    fn default() -> Self {144        Comp {145            title: String::new(),146            seed: 0,147            tuning: 440.0,148            tempo: Vec::new(),149            swing: None,150            tracks: Vec::new(),151            buses: Vec::new(),152            master: Strip::default(),153            sample_rate: 48_000,154            peak_limit: Some(-1.0),155            markers: Vec::new(),156        }157    }158}159160fn articulation_by_name(name: &str) -> Option<Articulation> {161    Some(match name {162        "normal" => Articulation::Normal,163        "legato" => Articulation::Legato,164        "staccato" => Articulation::Staccato,165        "staccatissimo" => Articulation::Staccatissimo,166        "tenuto" => Articulation::Tenuto,167        "marcato" => Articulation::Marcato,168        "accent" => Articulation::Accent,169        "pizzicato" => Articulation::Pizzicato,170        "tremolo" => Articulation::Tremolo,171        _ => return None,172    })173}174175fn rat(n: i64, d: i64) -> Rational {176    Rational::new(n, d).unwrap_or(Rational::ONE)177}178179/// Rejects asset paths that could leave the project's `assets/` directory.180pub fn asset_path_problem(path: &str) -> Option<&'static str> {181    if path.is_empty() {182        return Some("the path is empty");183    }184    if path.len() > 512 {185        return Some("the path is longer than 512 bytes");186    }187    if path.starts_with('/') || path.starts_with('~') || path.contains(':') {188        return Some("only paths relative to the project's assets directory are allowed");189    }190    if path.contains('\\') || path.contains('\0') || path.chars().any(|c| c.is_control()) {191        return Some("the path contains a backslash or a control character");192    }193    if path.split('/').any(|part| part == ".." || part == "." || part.is_empty()) {194        return Some("the path contains '..', '.' or an empty component");195    }196    None197}198199impl<'a> Analyzer<'a> {200    // ----- composition ----------------------------------------------------------------------201202    /// Evaluates a composition into a Program. Errors are reported; the caller decides from203    /// the diagnostics whether the Program is usable.204    pub fn run_composition(&mut self, c: &'a Composition) -> R<Program> {205        self.comp = Comp { title: c.title.value.clone(), ..Comp::default() };206        self.rng = SplitMix64::for_stream(0, u64::MAX);207        let mut cur = Cur::start(None);208        self.push_scope();209        // Pass 1: settings, buses, master, markers and variables, so every track sees the same210        // tempo, key, signatures and swing wherever it is declared.211        let is_track = |s: &Stmt| matches!(s.kind, StmtKind::Track { .. } | StmtKind::AudioTrack { .. });212        for s in c.body.stmts.iter().filter(|s| !is_track(s)) {213            let _ = self.exec_stmt(s, Ctx::Composition, &mut cur);214            if self.aborted {215                break;216            }217        }218        self.comp.swing = cur.swing;219        for s in c.body.stmts.iter().filter(|s| is_track(s)) {220            if self.aborted {221                break;222            }223            let _ = self.exec_stmt(s, Ctx::Composition, &mut cur);224        }225        self.pop_scope();226        if self.aborted {227            return Err(Stop);228        }229        self.assemble(c)230    }231232    fn exec_stmts(&mut self, stmts: &'a [Stmt], ctx: Ctx, cur: &mut Cur) -> R<()> {233        let mut i = 0;234        while i < stmts.len() {235            if self.aborted {236                return Err(Stop);237            }238            if matches!(stmts[i].kind, StmtKind::Voice { .. }) && ctx == Ctx::Track {239                // Adjacent voice blocks sound together, each on its own voice.240                let start = cur.pos;241                let mut end = start;242                while i < stmts.len() {243                    let StmtKind::Voice { body } = &stmts[i].kind else { break };244                    let mut sub = cur.clone();245                    sub.pos = start;246                    sub.voice = self.fresh_voice();247                    self.block(body, ctx, &mut sub);248                    end = end.max(sub.pos);249                    i += 1;250                }251                cur.pos = end;252                continue;253            }254            let _ = self.exec_stmt(&stmts[i], ctx, cur);255            i += 1;256        }257        if self.aborted {258            Err(Stop)259        } else {260            Ok(())261        }262    }263264    fn fresh_voice(&mut self) -> u32 {265        match self.track.as_mut() {266            Some(t) => {267                t.next_voice += 1;268                t.next_voice269            }270            None => 0,271        }272    }273274    /// Runs a block in a new variable scope. Scoped transforms do not leak out.275    fn block(&mut self, body: &'a Block, ctx: Ctx, cur: &mut Cur) {276        if self.enter_nest(body.span).is_err() {277            return;278        }279        let (transpose, swing, scale, voice) = (cur.transpose, cur.swing, cur.scale, cur.voice);280        self.push_scope();281        let _ = self.exec_stmts(&body.stmts, ctx, cur);282        self.pop_scope();283        self.nest -= 1;284        cur.transpose = transpose;285        cur.swing = swing;286        cur.scale = scale;287        cur.voice = voice;288    }289290    fn not_allowed<T>(&mut self, s: &Stmt, what: &str, ctx: Ctx, hint: &str) -> R<T> {291        let d = Diagnostic::error("S2008", s.span, format!("{what} is not allowed in {}", ctx.label()));292        self.report(if hint.is_empty() { d } else { d.with_suggestion(hint) });293        Err(Stop)294    }295296    fn duration(&mut self, e: &Expr, what: &str) -> R<Rational> {297        let v = self.eval(e)?;298        match v.as_duration() {299            Some(d) => Ok(d),300            None => {301                let hint = match v {302                    Value::Time(_) => "musical durations are fractions of a whole note (1/4), bars or beats; seconds are a different type",303                    Value::Num(Num::Float(_)) => "write the duration as an exact fraction, for example 3/8 instead of 0.375",304                    _ => "for example: 1/4, 3/8, 2bars, 1beat, dotted(1/4)",305                };306                self.err_hint("T3003", e.span, format!("{what} must be a musical duration, found {} ({})", v.type_name(), v.display()), hint)307            }308        }309    }310311    fn time(&mut self, e: &Expr, what: &str) -> R<f64> {312        let v = self.eval(e)?;313        let x = self.canonical(Unit::Seconds, &v, e.span, what)?;314        if x < 0.0 {315            return self.err("T3005", e.span, format!("{what} cannot be negative"));316        }317        Ok(x)318    }319320    fn add(&mut self, a: Rational, b: Rational, span: Span) -> R<Rational> {321        match a.checked_add(b) {322            Some(r) => Ok(r),323            None => self.overflow(span),324        }325    }326    fn mul(&mut self, a: Rational, b: Rational, span: Span) -> R<Rational> {327        match a.checked_mul(b) {328            Some(r) => Ok(r),329            None => self.overflow(span),330        }331    }332333    fn exec_stmt(&mut self, s: &'a Stmt, ctx: Ctx, cur: &mut Cur) -> R<()> {334        self.step(s.span)?;335        self.now = cur.pos;336        let musical = matches!(ctx, Ctx::Track);337        let timed = matches!(ctx, Ctx::Track | Ctx::Composition);338        match &s.kind {339            StmtKind::Let(l) => self.exec_let(l),340            StmtKind::Assign { target, value } => self.exec_assign(target, value),341            StmtKind::Return { .. } => self.not_allowed(s, "'return'", ctx, "return belongs to functions"),342            StmtKind::Tempo { value, ramp } => {343                if !timed {344                    return self.not_allowed(s, "'tempo'", ctx, "");345                }346                let bpm = match self.eval(value)? {347                    Value::Tempo(b) => b,348                    other => {349                        return self.err_hint(350                            "T3006",351                            value.span,352                            format!("tempo expects a value in bpm, found {}", other.type_name()),353                            "for example: tempo 120bpm",354                        )355                    }356                };357                if !(1.0..=1000.0).contains(&bpm) {358                    return self.err("M4003", value.span, format!("tempo {bpm} bpm is outside [1, 1000]"));359                }360                match ramp {361                    None => {362                        if cur.pos.is_zero() {363                            self.tempo0 = bpm;364                        }365                        self.comp.tempo.push((cur.pos, TempoEvent::Set(bpm), s.span));366                    }367                    Some(r) => {368                        let d = self.duration(r, "the ramp length")?;369                        if d <= Rational::ZERO {370                            return self.err("M4009", r.span, "the ramp length must be positive");371                        }372                        let end = self.add(cur.pos, d, s.span)?;373                        self.comp.tempo.push((cur.pos, TempoEvent::RampStart, s.span));374                        self.comp.tempo.push((end, TempoEvent::RampEnd(bpm), s.span));375                    }376                }377                Ok(())378            }379            StmtKind::Key { tonic, mode, .. } => {380                if ctx != Ctx::Composition {381                    return self.not_allowed(s, "'key'", ctx, "declare the key at the top of the composition");382                }383                let Some((m, _)) = builtins::mode_by_name(&mode.name) else {384                    return self.unknown("S2001", mode.span, "mode", &mode.name, builtins::mode_names());385                };386                let key = Key { tonic: tonic.pitch_class(), tonic_accidental: tonic.accidental, tonic_letter: tonic.letter, mode: m };387                self.key = Some(key);388                Ok(())389            }390            StmtKind::Signature { numerator, denominator } => {391                if !timed {392                    return self.not_allowed(s, "'signature'", ctx, "");393                }394                if !(1..=64).contains(numerator) || !denominator.is_power_of_two() || *denominator > 64 {395                    return self.err_hint(396                        "M4007",397                        s.span,398                        format!("{numerator}/{denominator} is not a valid signature"),399                        "the numerator is 1–64 and the denominator a power of two up to 64",400                    );401                }402                // Must fall on a bar line of the signature in effect before it.403                let prev = self.signatures.iter().rev().find(|p| p.0 <= cur.pos).cloned();404                if let Some((at, n, d, _)) = prev {405                    let bar = rat(n as i64, d as i64);406                    let offset = cur.pos.checked_sub(at).and_then(|o| o.checked_div(bar));407                    if !offset.map(|q| q.is_integer()).unwrap_or(false) {408                        return self.err_hint(409                            "M4002",410                            s.span,411                            format!("a signature change must fall on a bar line; position {} is inside a {n}/{d} bar", cur.pos),412                            "complete the bar with a rest first",413                        );414                    }415                }416                self.signatures.retain(|p| p.0 != cur.pos);417                self.signatures.push((cur.pos, *numerator, *denominator, s.span));418                self.signatures.sort_by_key(|p| p.0);419                Ok(())420            }421            StmtKind::Seed { value } => {422                if ctx != Ctx::Composition {423                    return self.not_allowed(s, "'seed'", ctx, "declare the seed at the top of the composition");424                }425                let v = self.eval(value)?;426                match int_of(&v) {427                    Some(n) if n >= 0 => {428                        self.comp.seed = n as u64;429                        self.rng = SplitMix64::for_stream(n as u64, u64::MAX);430                        Ok(())431                    }432                    _ => self.err("T3005", value.span, format!("the seed is a non-negative integer, found {}", v.display())),433                }434            }435            StmtKind::Tuning { value } => {436                if ctx != Ctx::Composition {437                    return self.not_allowed(s, "'tuning'", ctx, "");438                }439                match self.eval(value)? {440                    Value::Freq(f) if (220.0..=880.0).contains(&f) => {441                        self.comp.tuning = f;442                        Ok(())443                    }444                    Value::Freq(f) => self.err("M4016", value.span, format!("tuning {f} Hz is outside [220, 880] Hz (it is the frequency of A4)")),445                    other => {446                        self.err_hint("T3006", value.span, format!("tuning expects a frequency, found {}", other.type_name()), "for example: tuning 442Hz")447                    }448                }449            }450            StmtKind::Swing { ratio, unit, body } => {451                if !timed {452                    return self.not_allowed(s, "'swing'", ctx, "");453                }454                let r = match self.eval(ratio)? {455                    Value::Num(Num::Exact(r)) => r,456                    Value::Num(Num::Float(f)) => Rational::approximate(f, 1000).unwrap_or(rat(1, 2)),457                    other => {458                        return self.err_hint("T3006", ratio.span, format!("swing expects a ratio, found {}", other.type_name()), "for example: swing 60%")459                    }460                };461                if r < rat(1, 2) || r > rat(3, 4) {462                    return self.err_hint(463                        "M4006",464                        ratio.span,465                        format!("swing {}% is outside [50%, 75%]", r.to_f64() * 100.0),466                        "50% is straight, 66% is a triplet feel",467                    );468                }469                let u = match unit {470                    Some(u) => self.duration(u, "the swing unit")?,471                    None => rat(1, 8),472                };473                if u <= Rational::ZERO {474                    return self.err("M4009", s.span, "the swing unit must be positive");475                }476                let value = if r == rat(1, 2) { None } else { Some((r, u)) };477                match body {478                    Some(b) => {479                        let saved = cur.swing;480                        cur.swing = value;481                        self.push_scope();482                        let _ = self.exec_stmts(&b.stmts, ctx, cur);483                        self.pop_scope();484                        cur.swing = saved;485                    }486                    None => cur.swing = value,487                }488                Ok(())489            }490            StmtKind::Track { name, ty, body } => {491                if ctx != Ctx::Composition {492                    return self.not_allowed(s, "a track", ctx, "tracks are declared directly inside the composition");493                }494                let instrument = self.resolve_instrument(ty).ok();495                let range = instrument.as_ref().and_then(|i| self.registry.engine(&i.model)).map(|e| e.range);496                self.run_track(s, name, TrackKind::Instrument, instrument, range, body, Ctx::Track)497            }498            StmtKind::AudioTrack { name, body } => {499                if ctx != Ctx::Composition {500                    return self.not_allowed(s, "a track", ctx, "tracks are declared directly inside the composition");501                }502                self.run_track(s, name, TrackKind::Audio, None, None, body, Ctx::Audio)503            }504            StmtKind::Clip { asset, options } => {505                if ctx != Ctx::Audio {506                    return self.not_allowed(s, "'clip'", ctx, "clips belong to audio tracks: audio name { clip \"file.wav\" at 0bars }");507                }508                if let Some(problem) = asset_path_problem(&asset.value) {509                    return self.err_hint(510                        "I7005",511                        asset.span,512                        format!("unsafe asset path: {problem}"),513                        "assets are referenced relative to the project's assets directory, for example \"drums/loop.wav\"",514                    );515                }516                let mut clip = PendingClip {517                    asset: asset.value.clone(),518                    start: cur.pos,519                    offset_sec: 0.0,520                    length_sec: None,521                    gain_db: 0.0,522                    fade_in_sec: 0.0,523                    fade_out_sec: 0.0,524                    span: s.span,525                };526                for (k, v) in options {527                    match k.name.as_str() {528                        "at" => {529                            clip.start = self.duration(v, "the clip position")?;530                            if clip.start.is_negative() {531                                return self.err("M4010", v.span, "a position cannot be negative");532                            }533                        }534                        "offset" => clip.offset_sec = self.time(v, "the clip offset")?,535                        "length" => clip.length_sec = Some(self.time(v, "the clip length")?),536                        "fade_in" => clip.fade_in_sec = self.time(v, "the fade-in")?,537                        "fade_out" => clip.fade_out_sec = self.time(v, "the fade-out")?,538                        "gain" => {539                            let val = self.eval(v)?;540                            clip.gain_db = self.canonical(Unit::Decibel, &val, v.span, "the clip gain")?;541                        }542                        other => {543                            return self.unknown("S2009", k.span, "clip option", other, ["at", "offset", "length", "gain", "fade_in", "fade_out"].into_iter())544                        }545                    }546                }547                if let Some(t) = self.track.as_mut() {548                    t.clips.push(clip);549                }550                Ok(())551            }552            StmtKind::Bus { name, body } => {553                if ctx != Ctx::Composition {554                    return self.not_allowed(s, "a bus", ctx, "buses are declared directly inside the composition");555                }556                if let Some((first, _, _)) = self.comp.buses.iter().find(|(n, _, _)| n.name == name.name) {557                    let d =558                        Diagnostic::error("S2011", name.span, format!("bus '{}' is declared twice", name.name)).with_related(first.span, "first declared here");559                    self.report(d);560                    return Err(Stop);561                }562                let outer = std::mem::take(&mut self.strip);563                let mut sub = Cur::start(None);564                self.block(body, Ctx::Bus, &mut sub);565                let strip = std::mem::replace(&mut self.strip, outer);566                self.comp.buses.push((name.clone(), strip, s.span));567                Ok(())568            }569            StmtKind::Master { body } => {570                if ctx != Ctx::Composition {571                    return self.not_allowed(s, "'master'", ctx, "");572                }573                let outer = std::mem::replace(&mut self.strip, std::mem::take(&mut self.comp.master));574                let mut sub = Cur::start(None);575                self.block(body, Ctx::Master, &mut sub);576                self.comp.master = std::mem::replace(&mut self.strip, outer);577                Ok(())578            }579            StmtKind::Marker { name, at } => {580                if !timed {581                    return self.not_allowed(s, "'marker'", ctx, "");582                }583                let label = match self.eval(name)? {584                    Value::Str(t) => t.to_string(),585                    other => return self.err("T3006", name.span, format!("a marker name is a string, found {}", other.type_name())),586                };587                let pos = match at {588                    Some(e) => self.duration(e, "the marker position")?,589                    None => cur.pos,590                };591                if pos.is_negative() {592                    return self.err("M4010", s.span, "a position cannot be negative");593                }594                self.comp.markers.push((label, pos, s.span));595                Ok(())596            }597            StmtKind::Play { is_chord, what, modifiers } => {598                if !musical {599                    return self.not_allowed(s, "'play'", ctx, "notes belong to instrument tracks: instrument name: Type { play D4 }");600                }601                self.play(s, *is_chord, what, modifiers, cur)602            }603            StmtKind::Rest { duration } => {604                if !musical {605                    return self.not_allowed(s, "'rest'", ctx, "");606                }607                let d = self.duration(duration, "a rest")?;608                if d.is_negative() {609                    return self.err("M4009", duration.span, "a rest cannot be negative");610                }611                let d = self.mul(d, cur.scale, s.span)?;612                cur.pos = self.add(cur.pos, d, s.span)?;613                Ok(())614            }615            StmtKind::Sequence { body } => {616                self.block(body, ctx, cur);617                Ok(())618            }619            StmtKind::Voice { body } => {620                // Outside a track a voice block is a plain group.621                self.block(body, ctx, cur);622                Ok(())623            }624            StmtKind::Parallel { body } => {625                let start = cur.pos;626                let mut end = start;627                self.push_scope();628                for st in &body.stmts {629                    let mut sub = cur.clone();630                    sub.pos = start;631                    if let StmtKind::Voice { body } = &st.kind {632                        sub.voice = self.fresh_voice();633                        self.block(body, ctx, &mut sub);634                    } else {635                        let _ = self.exec_stmt(st, ctx, &mut sub);636                    }637                    end = end.max(sub.pos);638                    if self.aborted {639                        break;640                    }641                }642                self.pop_scope();643                cur.pos = end;644                Ok(())645            }646            StmtKind::At { position, body } => {647                if !timed {648                    return self.not_allowed(s, "'at'", ctx, "");649                }650                let pos = self.duration(position, "a position")?;651                if pos.is_negative() {652                    return self.err("M4010", position.span, "a position cannot be negative");653                }654                let mut sub = cur.clone();655                sub.pos = pos;656                self.block(body, ctx, &mut sub);657                Ok(())658            }659            StmtKind::Repeat { count, body } => {660                let n = self.count(count)?;661                for _ in 0..n {662                    self.step(s.span)?;663                    self.block(body, ctx, cur);664                }665                Ok(())666            }667            StmtKind::For { var, iter, body } => {668                let items = self.iterable(iter)?;669                for it in items.iter() {670                    self.step(s.span)?;671                    self.push_scope();672                    self.declare(var, it.clone(), true);673                    self.block(body, ctx, cur);674                    self.pop_scope();675                }676                Ok(())677            }678            StmtKind::If { cond, then, otherwise } => {679                let branch = if self.truth(cond)? { Some(then) } else { otherwise.as_ref() };680                if let Some(b) = branch {681                    self.block(b, ctx, cur);682                }683                Ok(())684            }685            StmtKind::Tuplet { n, m, body } => {686                if !musical {687                    return self.not_allowed(s, "'tuplet'", ctx, "");688                }689                let (nv, mv) = (self.eval(n)?, self.eval(m)?);690                let (Some(nn), Some(mm)) = (int_of(&nv), int_of(&mv)) else {691                    return self.err_hint(692                        "M4015",693                        s.span,694                        "a tuplet is written with two integers",695                        "for example: tuplet 3 in 2 { … } plays three notes in the time of two",696                    );697                };698                if !(1..=64).contains(&nn) || !(1..=64).contains(&mm) {699                    return self.err("M4015", s.span, "tuplet numbers must be between 1 and 64");700                }701                let saved = cur.scale;702                cur.scale = self.mul(cur.scale, rat(mm, nn), s.span)?;703                self.block(body, ctx, cur);704                cur.scale = saved;705                Ok(())706            }707            StmtKind::Transpose { interval, body } => {708                if !musical {709                    return self.not_allowed(s, "'transpose'", ctx, "");710                }711                let st = match self.eval(interval)? {712                    Value::Interval(i) => i,713                    Value::Num(n) => {714                        let d = Diagnostic::error("T3006", interval.span, "transpose expects an interval").with_suggestion(format!("write {}st", n.to_f64()));715                        self.report(d);716                        return Err(Stop);717                    }718                    other => return self.err("T3006", interval.span, format!("transpose expects an interval, found {}", other.type_name())),719                };720                match body {721                    Some(b) => {722                        let saved = cur.transpose;723                        cur.transpose += st;724                        self.block(b, ctx, cur);725                        cur.transpose = saved;726                    }727                    None => cur.transpose += st,728                }729                Ok(())730            }731            StmtKind::Effects { items } => {732                if ctx == Ctx::Composition {733                    return self.not_allowed(s, "'effects'", ctx, "put effects in a track, a bus or the master");734                }735                for it in items {736                    if let Ok(spec) = self.effect_spec(it) {737                        self.strip.effects.push(spec);738                    }739                }740                Ok(())741            }742            StmtKind::Automate { target, points } => {743                if ctx == Ctx::Composition {744                    return self.not_allowed(s, "'automate'", ctx, "automate a track, a bus or the master");745                }746                self.automate(s, target, points, ctx, cur)747            }748            StmtKind::Send { bus, gain, pre_fader } => {749                if !matches!(ctx, Ctx::Track | Ctx::Audio | Ctx::Bus) {750                    return self.not_allowed(s, "'send'", ctx, "");751                }752                let g = match gain {753                    Some(e) => {754                        let v = self.eval(e)?;755                        let x = self.canonical(Unit::Decibel, &v, e.span, "the send level")?;756                        if !(-120.0..=24.0).contains(&x) {757                            return self.err("T3005", e.span, format!("the send level {x} dB is outside [-120, 24] dB"));758                        }759                        x760                    }761                    None => 0.0,762                };763                self.strip.sends.push((bus.clone(), g, *pre_fader));764                Ok(())765            }766            StmtKind::Default { what, value } => {767                if !musical {768                    return self.not_allowed(s, "'default'", ctx, "");769                }770                match what.name.as_str() {771                    "duration" => {772                        let d = self.duration(value, "the default duration")?;773                        if d <= Rational::ZERO {774                            return self.err("M4009", value.span, "a duration must be positive");775                        }776                        if let Some(t) = self.track.as_mut() {777                            t.default_dur = d;778                        }779                    }780                    "velocity" => {781                        let v = self.velocity(value)?;782                        if let Some(t) = self.track.as_mut() {783                            t.default_vel = v;784                        }785                    }786                    other => return self.unknown("S2009", what.span, "default", other, ["duration", "velocity"].into_iter()),787                }788                Ok(())789            }790            StmtKind::Setting { name, value } => self.setting(s, name, value.as_ref(), ctx),791            StmtKind::Expr { expr } => {792                if let ExprKind::Call { callee, args } = &expr.kind {793                    if let Some(GlobalKind::Pattern(p)) = self.globals.get(callee.name.as_str()).map(|g| g.kind) {794                        if !timed {795                            return self.not_allowed(s, "a pattern call", ctx, "");796                        }797                        let bound = self.bind("pattern", &p.name.name, &p.params, args, s.span)?;798                        self.enter_call(s.span)?;799                        let saved = std::mem::replace(&mut self.scopes, vec![bound]);800                        let (transpose, swing, scale, voice) = (cur.transpose, cur.swing, cur.scale, cur.voice);801                        let _ = self.exec_stmts(&p.body.stmts, ctx, cur);802                        cur.transpose = transpose;803                        cur.swing = swing;804                        cur.scale = scale;805                        cur.voice = voice;806                        self.scopes = saved;807                        self.depth -= 1;808                        return if self.aborted { Err(Stop) } else { Ok(()) };809                    }810                }811                self.eval(expr).map(|_| ())812            }813        }814    }815816    #[allow(clippy::too_many_arguments)]817    fn run_track(818        &mut self,819        s: &'a Stmt,820        name: &Ident,821        kind: TrackKind,822        instrument: Option<Rc<InstrumentSpec>>,823        range: Option<(u8, u8)>,824        body: &'a Block,825        ctx: Ctx,826    ) -> R<()> {827        if let Some(first) = self.comp.tracks.iter().find(|t| t.name.name == name.name) {828            let d =829                Diagnostic::error("S2011", name.span, format!("track '{}' is declared twice", name.name)).with_related(first.name.span, "first declared here");830            self.report(d);831            return Err(Stop);832        }833        if self.comp.tracks.len() as u32 >= self.quotas.max_tracks {834            let max = self.quotas.max_tracks;835            return self.abort("Q6006", s.span, format!("a composition is limited to {max} tracks"));836        }837        let id = self.comp.tracks.len() as u32;838        let track = TrackBuild {839            id,840            name: name.clone(),841            kind,842            instrument,843            range,844            strip: Strip::default(),845            notes: Vec::new(),846            clips: Vec::new(),847            default_dur: rat(1, 4),848            default_vel: 0.8,849            articulation: Articulation::Normal,850            next_voice: 0,851            score_transposition: 0,852            open_ties: HashMap::new(),853            range_warnings: 0,854            span: s.span,855        };856        let outer_strip = std::mem::take(&mut self.strip);857        let outer_rng = std::mem::replace(&mut self.rng, SplitMix64::for_stream(self.comp.seed, id as u64));858        self.track = Some(track);859        let mut cur = Cur::start(self.comp.swing);860        self.block(body, ctx, &mut cur);861        self.rng = outer_rng;862        let mut track = self.track.take().expect("track set above");863        track.strip = std::mem::replace(&mut self.strip, outer_strip);864        let dangling: Vec<Span> = track.open_ties.values().map(|i| track.notes[*i].span).collect();865        for sp in dangling {866            self.warn("M4005", sp, "this tie has no continuation: no note of the same pitch follows in the same voice");867        }868        self.comp.tracks.push(track);869        if self.aborted {870            Err(Stop)871        } else {872            Ok(())873        }874    }875876    fn velocity(&mut self, e: &Expr) -> R<f64> {877        match self.eval(e)? {878            Value::Num(n) if (0.0..=1.0).contains(&n.to_f64()) => Ok(n.to_f64()),879            Value::Num(n) => self.err_hint(880                "M4008",881                e.span,882                format!("velocity {} is outside [0, 1]", n.to_f64()),883                "velocity is linear: 0 is silent, 1 is the loudest; MIDI 100 is about 0.79",884            ),885            other => self.err("T3006", e.span, format!("velocity is a number in [0, 1], found {}", other.type_name())),886        }887    }888889    fn play(&mut self, s: &Stmt, is_chord: bool, what: &Expr, modifiers: &[Modifier], cur: &mut Cur) -> R<()> {890        let v = self.eval(what)?;891        let mut pitches: Vec<f64> = Vec::new();892        match &v {893            Value::Pitch(p) if !is_chord => pitches.push(*p),894            Value::List(items) => {895                for it in items.iter() {896                    match it {897                        Value::Pitch(p) => pitches.push(*p),898                        Value::List(inner) if inner.iter().all(|x| matches!(x, Value::Pitch(_))) => {899                            pitches.extend(inner.iter().filter_map(|x| if let Value::Pitch(p) = x { Some(*p) } else { None }))900                        }901                        other => return self.err("T3004", what.span, format!("a chord is a list of pitches, found an element of type {}", other.type_name())),902                    }903                }904                if pitches.is_empty() {905                    return self.err_hint("T3004", what.span, "the chord is empty", "use `rest` for silence");906                }907            }908            Value::Pitch(_) => return self.err_hint("T3004", what.span, "chord needs a list of pitches", "write chord [D3, A3, D4], or use play for one note"),909            Value::PitchClass(pc) => {910                let name = sonata_parser::format::pitch_class_text(*pc);911                let d = Diagnostic::error("T3004", what.span, format!("'{name}' is a pitch class; a note needs an octave"))912                    .with_suggestion(format!("for example {name}4"))913                    .with_fix("add octave 4", Span::new(what.span.file, what.span.end, what.span.end), "4");914                self.report(d);915                return Err(Stop);916            }917            other => {918                return self.err_hint(919                    "T3004",920                    what.span,921                    format!("play needs a pitch or a list of pitches, found {} ({})", other.type_name(), other.display()),922                    "for example: play D4, or play [D3, A3, D4]",923                )924            }925        }926        let (default_dur, default_vel, default_art) = match self.track.as_ref() {927            Some(t) => (t.default_dur, t.default_vel, t.articulation),928            None => (rat(1, 4), 0.8, Articulation::Normal),929        };930        let (mut dur, mut vel, mut art, mut tie, mut bend) = (default_dur, default_vel, default_art, false, Vec::new());931        for m in modifiers {932            match &m.kind {933                ModifierKind::Duration { value } => {934                    dur = self.duration(value, "a note duration")?;935                    if dur <= Rational::ZERO {936                        return self.err("M4009", value.span, "a note duration must be positive");937                    }938                }939                ModifierKind::Velocity { value } => vel = self.velocity(value)?,940                ModifierKind::Articulation { name } => art = articulation_by_name(&name.name).unwrap_or(Articulation::Normal),941                ModifierKind::Tie => tie = true,942                ModifierKind::Bend { points } => {943                    for p in points {944                        let t = self.time(&p.at, "a bend time")?;945                        let st = match self.eval(&p.value)? {946                            Value::Interval(i) if i.abs() <= 48.0 => i,947                            Value::Interval(_) => return self.err("T3005", p.value.span, "a bend is limited to ±48 semitones"),948                            other => {949                                return self.err_hint(950                                    "T3006",951                                    p.value.span,952                                    format!("a bend value is an interval, found {}", other.type_name()),953                                    "for example: bend { 0ms: 0st, 200ms: 2st }",954                                )955                            }956                        };957                        if bend.last().map(|b: &BendPoint| t < b.offset_sec).unwrap_or(false) {958                            return self.err("M4011", p.span, "bend points must be in time order");959                        }960                        bend.push(BendPoint { offset_sec: t, semitones: st });961                    }962                }963            }964        }965        let ndur = self.mul(dur, cur.scale, s.span)?;966        let nstart = cur.pos;967        // Swing: a note starting on an odd multiple of the unit is delayed by (2r - 1)·unit.968        let mut delay = Rational::ZERO;969        if let Some((ratio, unit)) = cur.swing {970            if let Some(q) = nstart.checked_div(unit) {971                if q.is_integer() && q.num() % 2 != 0 {972                    let twice = self.mul(ratio, Rational::from_int(2), s.span)?;973                    let frac = twice.checked_sub(Rational::ONE).unwrap_or(Rational::ZERO);974                    delay = self.mul(frac, unit, s.span)?;975                }976            }977        }978        let velocity = match art {979            Articulation::Marcato => (vel * 1.2).min(1.0),980            Articulation::Accent => (vel * 1.25).min(1.0),981            _ => vel,982        } as f32;983        self.events += pitches.len() as u64;984        if self.events > self.quotas.max_events {985            let max = self.quotas.max_events;986            return self.abort("Q6001", s.span, format!("the composition produces more than {max} notes"));987        }988        let end = self.add(nstart, ndur, s.span)?;989        let transpose = cur.transpose;990        let voice = cur.voice;991        let mut warn: Option<(f64, (u8, u8))> = None;992        let mut dangling: Vec<Span> = Vec::new();993        if let Some(t) = self.track.as_mut() {994            for p in pitches {995                let pitch = p + transpose;996                if let Some((lo, hi)) = t.range {997                    if (pitch < lo as f64 || pitch > hi as f64) && t.range_warnings < 5 {998                        t.range_warnings += 1;999                        warn = Some((pitch, (lo, hi)));1000                    }1001                }1002                let key = (voice, pitch.to_bits());1003                if let Some(idx) = t.open_ties.get(&key).copied() {1004                    let prev_end = t.notes[idx].nstart.checked_add(t.notes[idx].ndur);1005                    if prev_end == Some(nstart) {1006                        // Continuation of a tie: one sounding note, lengthened.1007                        if let Some(total) = t.notes[idx].ndur.checked_add(ndur) {1008                            t.notes[idx].ndur = total;1009                        }1010                        if !tie {1011                            t.open_ties.remove(&key);1012                        }1013                        continue;1014                    }1015                    dangling.push(t.notes[idx].span);1016                    t.open_ties.remove(&key);1017                }1018                let order = t.notes.len() as u32;1019                t.notes.push(PendingNote { nstart, ndur, delay, pitch, velocity, voice, articulation: art, bend: bend.clone(), span: s.span, order });1020                if tie {1021                    t.open_ties.insert(key, t.notes.len() - 1);1022                }1023            }1024        }1025        for sp in dangling {1026            self.warn("M4005", sp, "this tie has no continuation: the next note of the same pitch does not start where it ends");1027        }1028        if let Some((pitch, (lo, hi))) = warn {1029            let model = self.track.as_ref().and_then(|t| t.instrument.as_ref()).map(|i| i.name.clone()).unwrap_or_default();1030            self.warn(1031                "M4001",1032                what.span,1033                format!(1034                    "{} is outside the range of {model} ({}–{}); it is rendered anyway",1035                    crate::value::pitch_name(pitch),1036                    crate::value::pitch_name(lo as f64),1037                    crate::value::pitch_name(hi as f64)1038                ),1039            );1040        }1041        cur.pos = end;1042        self.now = end;1043        Ok(())1044    }10451046    fn flag(&mut self, name: &Ident, value: Option<&Expr>) -> R<bool> {1047        match value {1048            None => Ok(true),1049            Some(e) => match self.eval(e)? {1050                Value::Bool(b) => Ok(b),1051                other => self.err("T3006", e.span, format!("'{}' is on or off (true/false), found {}", name.name, other.type_name())),1052            },1053        }1054    }10551056    fn setting(&mut self, s: &Stmt, name: &Ident, value: Option<&Expr>, ctx: Ctx) -> R<()> {1057        let strip_ctx = matches!(ctx, Ctx::Track | Ctx::Audio | Ctx::Bus);1058        macro_rules! need {1059            () => {1060                match value {1061                    Some(v) => v,1062                    None => return self.err("P1005", name.span, format!("'{}' needs a value", name.name)),1063                }1064            };1065        }1066        match (name.name.as_str(), ctx) {1067            ("gain", c) if c != Ctx::Composition => {1068                let e = need!();1069                let v = self.eval(e)?;1070                let x = self.canonical(Unit::Decibel, &v, e.span, "gain")?;1071                if !(-120.0..=24.0).contains(&x) {1072                    return self.err("T3005", e.span, format!("gain {x} dB is outside [-120, 24] dB"));1073                }1074                self.strip.gain_db = x;1075            }1076            ("pan", _) if strip_ctx => {1077                let e = need!();1078                match self.eval(e)? {1079                    Value::Num(n) if (-1.0..=1.0).contains(&n.to_f64()) => self.strip.pan = n.to_f64(),1080                    other => {1081                        return self.err_hint(1082                            "T3005",1083                            e.span,1084                            format!("pan is a number in [-1, 1], found {}", other.display()),1085                            "-1 is hard left, 0 centre, 1 hard right",1086                        )1087                    }1088                }1089            }1090            ("mute", _) if strip_ctx => self.strip.mute = self.flag(name, value)?,1091            ("solo", Ctx::Track | Ctx::Audio) => self.strip.solo = self.flag(name, value)?,1092            ("output", _) if strip_ctx => {1093                let e = need!();1094                match &e.kind {1095                    ExprKind::Ident { name: bus } if bus == "master" => self.strip.output = None,1096                    ExprKind::Ident { name: bus } => self.strip.output = Some(Ident { name: bus.clone(), span: e.span }),1097                    _ => return self.err_hint("T3006", e.span, "output expects the name of a bus", "for example: output hall"),1098                }1099            }1100            ("articulation", Ctx::Track) => {1101                let e = need!();1102                let label = match &e.kind {1103                    ExprKind::Ident { name } => name.clone(),1104                    _ => String::new(),1105                };1106                match articulation_by_name(&label) {1107                    Some(a) => {1108                        if let Some(t) = self.track.as_mut() {1109                            t.articulation = a;1110                        }1111                    }1112                    None => return self.unknown("S2001", e.span, "articulation", &label, ARTICULATIONS.iter().copied()),1113                }1114            }1115            ("score_transposition", Ctx::Track) => {1116                let e = need!();1117                let st = match self.eval(e)? {1118                    Value::Interval(i) if i.fract() == 0.0 && i.abs() <= 48.0 => i as i32,1119                    Value::Num(n) if n.as_int().map(|i| i.abs() <= 48).unwrap_or(false) => n.as_int().unwrap_or(0) as i32,1120                    other => {1121                        return self.err("T3005", e.span, format!("score_transposition is a whole number of semitones within ±48, found {}", other.display()))1122                    }1123                };1124                if let Some(t) = self.track.as_mut() {1125                    t.score_transposition = st;1126                }1127            }1128            ("sample_rate", Ctx::Master) => {1129                let e = need!();1130                match self.eval(e)? {1131                    Value::Freq(f) if f.fract() == 0.0 && SAMPLE_RATES.contains(&(f as u32)) => self.comp.sample_rate = f as u32,1132                    Value::Freq(f) => {1133                        let rates: Vec<String> = SAMPLE_RATES.iter().map(|r| format!("{r}Hz")).collect();1134                        return self.err_hint("M4012", e.span, format!("{f} Hz is not a supported sample rate"), format!("supported: {}", rates.join(", ")));1135                    }1136                    other => {1137                        return self.err_hint(1138                            "T3006",1139                            e.span,1140                            format!("sample_rate expects a frequency, found {}", other.type_name()),1141                            "for example: sample_rate 48000Hz",1142                        )1143                    }1144                }1145            }1146            ("peak_limit", Ctx::Master) => {1147                let e = need!();1148                match self.eval(e)? {1149                    Value::Bool(false) => self.comp.peak_limit = None,1150                    Value::Gain(g) if (-60.0..=0.0).contains(&g) => self.comp.peak_limit = Some(g),1151                    Value::Gain(g) => {1152                        return self.err_hint(1153                            "M4013",1154                            e.span,1155                            format!("peak_limit {g} dB is outside [-60, 0] dBFS"),1156                            "the limiter ceiling cannot be above full scale",1157                        )1158                    }1159                    other => {1160                        return self.err_hint(1161                            "T3006",1162                            e.span,1163                            format!("peak_limit expects a level in dB or `off`, found {}", other.type_name()),1164                            "for example: peak_limit -1dB",1165                        )1166                    }1167                }1168            }1169            (other, _) => {1170                let names: &[&str] = match ctx {1171                    Ctx::Composition => &["tempo", "key", "signature", "seed", "swing", "tuning", "marker", "instrument", "audio", "bus", "master"],1172                    Ctx::Track => &[1173                        "gain",1174                        "pan",1175                        "mute",1176                        "solo",1177                        "output",1178                        "articulation",1179                        "score_transposition",1180                        "send",1181                        "effects",1182                        "automate",1183                        "play",1184                        "chord",1185                        "rest",1186                    ],1187                    Ctx::Audio => &["gain", "pan", "mute", "solo", "output", "send", "effects", "automate", "clip"],1188                    Ctx::Bus => &["gain", "pan", "mute", "output", "send", "effects", "automate"],1189                    Ctx::Master => &["sample_rate", "peak_limit", "gain", "effects", "automate"],1190                };1191                let mut d = Diagnostic::error("S2009", name.span, format!("'{other}' is not a setting of {}", ctx.label()));1192                d = match Self::closest(other, names.iter().copied()) {1193                    Some(c) => d.with_suggestion(format!("did you mean '{c}'?")).with_fix(format!("replace with '{c}'"), name.span, c),1194                    None => d.with_suggestion(format!("available here: {}", names.join(", "))),1195                };1196                self.report(d);1197                let _ = s;1198                return Err(Stop);1199            }1200        }1201        Ok(())1202    }12031204    fn automate(&mut self, s: &Stmt, target: &AutoPath, points: &[AutoPoint], ctx: Ctx, cur: &Cur) -> R<()> {1205        // (target, unit, min, max, label)1206        let (tgt, unit, min, max, label): (AutomationTarget, Unit, f64, f64, String) = match (target.head.name.as_str(), &target.param) {1207            ("gain", None) => (AutomationTarget::Gain, Unit::Decibel, -120.0, 24.0, "gain".into()),1208            ("pan", None) if ctx != Ctx::Master => (AutomationTarget::Pan, Unit::Scalar, -1.0, 1.0, "pan".into()),1209            ("instrument", Some(p)) => {1210                let Some(spec) = self.track.as_ref().and_then(|t| t.instrument.clone()) else {1211                    return self.err("S2008", target.span, "only instrument tracks have instrument parameters");1212                };1213                let Some(engine) = self.registry.engine(&spec.model).cloned() else { return Err(Stop) };1214                let Some(desc) = engine.params.iter().find(|d| d.name == p.name) else {1215                    return self.unknown(1216                        "S2023",1217                        p.span,1218                        &format!("parameter of model '{}'", engine.model),1219                        &p.name,1220                        engine.params.iter().filter(|d| d.automatable).map(|d| d.name.as_str()),1221                    );1222                };1223                if !desc.automatable || matches!(desc.unit, Unit::Choice | Unit::HertzList | Unit::ScalarList) {1224                    return self.err("T3014", p.span, format!("parameter '{}' of model '{}' cannot be automated", desc.name, engine.model));1225                }1226                (AutomationTarget::Instrument { param: desc.name.clone() }, desc.unit, desc.min, desc.max, desc.name.clone())1227            }1228            (kind, Some(p)) => {1229                let nth = target.index.unwrap_or(0) as usize;1230                let found = self.strip.effects.iter().enumerate().filter(|(_, e)| e.kind == kind).nth(nth).map(|(i, _)| i);1231                let Some(index) = found else {1232                    let kinds: Vec<String> = self.strip.effects.iter().map(|e| e.kind.clone()).collect();1233                    let mut d = Diagnostic::error(1234                        "S2001",1235                        target.head.span,1236                        format!("this strip has no effect '{kind}'{}", if nth > 0 { format!(" number {nth}") } else { String::new() }),1237                    )1238                    .with_suggestion(1239                        "declare the effect in an `effects { }` block before automating it; targets are gain, pan, instrument.<param> and <effect>.<param>",1240                    );1241                    if let Some(c) = Self::closest(kind, kinds.iter().map(String::as_str)) {1242                        d = d.with_fix(format!("replace with '{c}'"), target.head.span, c);1243                    }1244                    self.report(d);1245                    return Err(Stop);1246                };1247                let Some(desc) = self.registry.effect(kind).cloned() else { return Err(Stop) };1248                match desc.params.iter().find(|d| d.name == p.name) {1249                    Some(pd) => {1250                        if !pd.automatable || matches!(pd.unit, Unit::Choice | Unit::HertzList | Unit::ScalarList) {1251                            return self.err("T3014", p.span, format!("parameter '{}' of effect '{kind}' cannot be automated", pd.name));1252                        }1253                        (AutomationTarget::Effect { index: index as u32, param: pd.name.clone() }, pd.unit, pd.min, pd.max, pd.name.clone())1254                    }1255                    None if p.name == "mix" => (AutomationTarget::Effect { index: index as u32, param: "mix".into() }, Unit::Ratio, 0.0, 1.0, "mix".into()),1256                    None => {1257                        let mut names: Vec<&str> = desc.params.iter().filter(|d| d.automatable).map(|d| d.name.as_str()).collect();1258                        names.push("mix");1259                        return self.unknown("S2023", p.span, &format!("parameter of effect '{kind}'"), &p.name, names.into_iter());1260                    }1261                }1262            }1263            (other, None) => {1264                return self.err_hint(1265                    "S2009",1266                    target.span,1267                    format!("'{other}' cannot be automated"),1268                    "targets are gain, pan, instrument.<param> and <effect>.<param>",1269                );1270            }1271        };1272        if points.is_empty() {1273            return self.err("M4011", s.span, "an automation needs at least one point");1274        }1275        let mut out: Vec<(Rational, f64, Curve)> = Vec::with_capacity(points.len());1276        for p in points {1277            let rel = self.duration(&p.at, "an automation position")?;1278            if rel.is_negative() {1279                return self.err("M4010", p.at.span, "a position cannot be negative");1280            }1281            let at = self.add(cur.pos, rel, p.span)?;1282            let v = self.eval(&p.value)?;1283            let x = self.canonical(unit, &v, p.value.span, &label)?;1284            if min < max && (x < min || x > max) {1285                return self.err("T3005", p.value.span, format!("{label} = {x} is outside [{min}, {max}]"));1286            }1287            let curve = match p.curve.as_ref().map(|c| c.name.as_str()) {1288                None | Some("linear") => Curve::Linear,1289                Some("step") | Some("hold") => Curve::Step,1290                Some("exp") | Some("exponential") => Curve::Exponential,1291                Some(other) => {1292                    let sp = p.curve.as_ref().map(|c| c.span).unwrap_or(p.span);1293                    return self.unknown("S2001", sp, "curve", other, ["linear", "step", "exp"].into_iter());1294                }1295            };1296            if out.last().map(|l| at < l.0).unwrap_or(false) {1297                return self.err("M4011", p.span, "automation points must be in time order");1298            }1299            out.push((at, x, curve));1300        }1301        self.strip.automation.push(PendingLane { target: tgt, points: out, span: s.span });1302        Ok(())1303    }13041305    // ----- assembly -------------------------------------------------------------------------13061307    fn tempo_map(&mut self) -> R<TempoMap> {1308        let mut events = std::mem::take(&mut self.comp.tempo);1309        events.sort_by_key(|e| e.0);1310        let mut points: Vec<TempoPoint> = Vec::new();1311        let mut set_at: Option<(Rational, f64)> = None;1312        let mut bpm = 120.0;1313        let quarter = rat(1, 4);1314        for (at, ev, span) in events {1315            let ramp = matches!(ev, TempoEvent::RampStart);1316            match ev {1317                TempoEvent::Set(b) => {1318                    if let Some((pat, pb)) = set_at {1319                        if pat == at && (pb - b).abs() > 1e-9 {1320                            return self.err_hint(1321                                "M4004",1322                                span,1323                                format!("two different tempos ({pb} and {b} bpm) are set at position {at}"),1324                                "set the tempo of a position once, preferably at composition level",1325                            );1326                        }1327                    }1328                    set_at = Some((at, b));1329                    bpm = b;1330                }1331                TempoEvent::RampEnd(b) => bpm = b,1332                TempoEvent::RampStart => {}1333            }1334            match points.last_mut() {1335                Some(last) if last.at == at => {1336                    last.bpm = bpm;1337                    last.ramp |= ramp;1338                }1339                _ => points.push(TempoPoint { at, bpm, beat_unit: quarter, ramp }),1340            }1341        }1342        if points.first().map(|p| !p.at.is_zero()).unwrap_or(true) {1343            points.insert(0, TempoPoint { at: Rational::ZERO, bpm: 120.0, beat_unit: quarter, ramp: false });1344        }1345        if let Some(last) = points.last_mut() {1346            last.ramp = false;1347        }1348        let map = TempoMap { points };1349        if let Err(e) = map.validate() {1350            return self.err("M4003", Span::default(), format!("invalid tempo map: {e}"));1351        }1352        Ok(map)1353    }13541355    fn lanes(&mut self, lanes: Vec<PendingLane>, map: &TempoMap) -> Vec<AutomationLane> {1356        lanes1357            .into_iter()1358            .map(|l| AutomationLane {1359                target: l.target,1360                points: l.points.into_iter().map(|(at, value, curve)| AutomationPoint { at, at_sec: map.seconds_at(at), value, curve }).collect(),1361                span: l.span,1362            })1363            .collect()1364    }13651366    fn routing(&mut self, strip: &Strip, bus_ids: &HashMap<String, u32>, own_bus: Option<u32>) -> (Vec<Send>, Output) {1367        let names: Vec<String> = bus_ids.keys().cloned().collect();1368        let mut sends = Vec::new();1369        for (bus, gain_db, pre_fader) in &strip.sends {1370            match bus_ids.get(&bus.name) {1371                Some(id) if Some(*id) == own_bus => {1372                    let _: R<()> = self.err("G5001", bus.span, format!("bus '{}' cannot send to itself", bus.name));1373                }1374                Some(id) => sends.push(Send { bus: *id, gain_db: *gain_db, pre_fader: *pre_fader }),1375                None => {1376                    let _: R<()> = self.unknown("S2001", bus.span, "bus", &bus.name, names.iter().map(String::as_str));1377                }1378            }1379        }1380        let output = match &strip.output {1381            None => Output::Master,1382            Some(bus) => match bus_ids.get(&bus.name) {1383                Some(id) if Some(*id) == own_bus => {1384                    let _: R<()> = self.err("G5001", bus.span, format!("bus '{}' cannot output to itself", bus.name));1385                    Output::Master1386                }1387                Some(id) => Output::Bus(*id),1388                None => {1389                    let _: R<()> = self.unknown("S2001", bus.span, "bus", &bus.name, names.iter().map(String::as_str));1390                    Output::Master1391                }1392            },1393        };1394        (sends, output)1395    }13961397    fn assemble(&mut self, c: &Composition) -> R<Program> {1398        let map = self.tempo_map()?;1399        let comp = std::mem::take(&mut self.comp);1400        let bus_ids: HashMap<String, u32> = comp.buses.iter().enumerate().map(|(i, (n, _, _))| (n.name.clone(), i as u32)).collect();1401        let mut program = Program::empty(&comp.title);1402        program.language_version = LANGUAGE_VERSION.to_string();1403        program.seed = comp.seed;1404        program.tuning_hz = comp.tuning;1405        program.key = self.key;1406        program.signatures = self.signatures.iter().map(|(at, n, d, _)| SignaturePoint { at: *at, numerator: *n, denominator: *d }).collect();1407        for tb in comp.tracks {1408            let (sends, output) = self.routing(&tb.strip, &bus_ids, None);1409            let mut pending = tb.notes;1410            let mut notes = Vec::with_capacity(pending.len());1411            pending.sort_by(|a, b| {1412                a.nstart1413                    .checked_add(a.delay)1414                    .cmp(&b.nstart.checked_add(b.delay))1415                    .then(a.pitch.partial_cmp(&b.pitch).unwrap_or(std::cmp::Ordering::Equal))1416                    .then(a.order.cmp(&b.order))1417            });1418            for (i, n) in pending.into_iter().enumerate() {1419                let factor = match n.articulation {1420                    Articulation::Staccato => rat(1, 2),1421                    Articulation::Staccatissimo => rat(1, 4),1422                    _ => Rational::ONE,1423                };1424                let start = self.add(n.nstart, n.delay, n.span)?;1425                let shaped = self.mul(n.ndur, factor, n.span)?;1426                let duration = match shaped.checked_sub(n.delay) {1427                    Some(d) if d > Rational::ZERO => d,1428                    _ => shaped,1429                };1430                let end = self.add(start, duration, n.span)?;1431                notes.push(NoteEvent {1432                    id: ((tb.id as u64) << 32) | i as u64,1433                    start,1434                    duration,1435                    notated_start: n.nstart,1436                    notated_duration: n.ndur,1437                    start_sec: map.seconds_at(start),1438                    end_sec: map.seconds_at(end),1439                    pitch: n.pitch,1440                    velocity: n.velocity,1441                    voice: n.voice,1442                    articulation: n.articulation,1443                    tied_from_previous: false,1444                    bend: n.bend,1445                    span: n.span,1446                });1447            }1448            let clips = tb1449                .clips1450                .into_iter()1451                .map(|cl| AudioClip {1452                    asset: cl.asset,1453                    start: cl.start,1454                    start_sec: map.seconds_at(cl.start),1455                    offset_sec: cl.offset_sec,1456                    length_sec: cl.length_sec,1457                    gain_db: cl.gain_db,1458                    fade_in_sec: cl.fade_in_sec,1459                    fade_out_sec: cl.fade_out_sec,1460                    span: cl.span,1461                })1462                .collect();1463            let automation = self.lanes(tb.strip.automation, &map);1464            program.tracks.push(Track {1465                id: tb.id,1466                name: tb.name.name,1467                kind: tb.kind,1468                instrument: tb.instrument.map(|i| (*i).clone()),1469                gain_db: tb.strip.gain_db,1470                pan: tb.strip.pan,1471                mute: tb.strip.mute,1472                solo: tb.strip.solo,1473                effects: tb.strip.effects,1474                sends,1475                output,1476                notes,1477                clips,1478                automation,1479                score_transposition: tb.score_transposition,1480                span: tb.span,1481            });1482        }1483        for (i, (name, strip, span)) in comp.buses.into_iter().enumerate() {1484            let (sends, output) = self.routing(&strip, &bus_ids, Some(i as u32));1485            let automation = self.lanes(strip.automation, &map);1486            program.buses.push(Bus {1487                id: i as u32,1488                name: name.name,1489                gain_db: strip.gain_db,1490                pan: strip.pan,1491                mute: strip.mute,1492                effects: strip.effects,1493                sends,1494                output,1495                automation,1496                span,1497            });1498        }1499        let master_automation = self.lanes(comp.master.automation, &map);1500        program.master = MasterSpec {1501            sample_rate: comp.sample_rate,1502            gain_db: comp.master.gain_db,1503            peak_limit_db: comp.peak_limit,1504            effects: comp.master.effects,1505            automation: master_automation,1506        };1507        let mut markers: Vec<Marker> = comp.markers.into_iter().map(|(name, at, span)| Marker { name, at, at_sec: map.seconds_at(at), span }).collect();1508        markers.sort_by_key(|m| m.at);1509        program.markers = markers;1510        program.tempo_map = map;1511        program.refresh_stats();1512        if program.tracks.is_empty() {1513            self.warn("M4014", c.title.span, "this composition has no track, so it is silent");1514        }1515        Ok(program)1516    }1517}1518
Files main
Menu

Theme