Skip to main content

acorde_core/model/
playback.rs

1use super::duration::Duration;
2use super::notation::{Articulation, ChordSymbol, GuitarTechnique, TabPosition};
3use super::repeat::measure_sequence;
4use super::score::{GuitarBendPoint, Note, NoteAddr, Score};
5use serde::{Deserialize, Serialize};
6use std::collections::{BTreeMap, BTreeSet};
7
8fn default_fermata_multiplier() -> f64 {
9    1.5
10}
11fn default_fermata_hold_beats() -> f64 {
12    0.0
13}
14fn default_swing_unit() -> Duration {
15    Duration::Eighth
16}
17fn default_tempo_multiplier() -> f64 {
18    1.0
19}
20fn default_metronome_channel() -> u8 {
21    9
22}
23fn default_accent_pitch() -> u8 {
24    76
25}
26fn default_beat_pitch() -> u8 {
27    77
28}
29fn default_accent_velocity() -> u8 {
30    100
31}
32fn default_beat_velocity() -> u8 {
33    70
34}
35
36/// Explicit opt-in event realization policy.
37///
38/// [`Authored`](Self::Authored) is the default: ornaments and arpeggiation remain notation
39/// semantics on one event. The versioned realization profile is deliberately opt-in so hosts
40/// never receive invented attacks merely by upgrading acorde.
41#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
42#[serde(rename_all = "kebab-case")]
43pub enum PlaybackRealizationProfile {
44    /// Preserve authored event semantics without generating auxiliary attacks.
45    #[default]
46    Authored,
47    /// Deterministic chromatic ornament attacks and chord arpeggiation for preview providers.
48    ///
49    /// Trills and shakes alternate the written pitch with one chromatic semitone above; mordents
50    /// and turns use a fixed four-attack figure. Chord tones marked `arpeggiate` are staggered
51    /// low-to-high (or high-to-low) by at most 0.18 beats. This is a reproducible preview policy,
52    /// not a claim about historical performance practice.
53    OrnamentArpeggioV1,
54}
55
56/// Click-track injected into [`to_playback_events`] output.
57///
58/// Metronome events are tagged with `PlaybackEvent.is_metronome = true` and can be
59/// routed separately by checking `channel` (default 9 = GM drums).
60#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
61pub struct MetronomeConfig {
62    /// MIDI channel for the click track. Default 9 (GM drum channel).
63    #[serde(default = "default_metronome_channel")]
64    pub channel: u8,
65    /// MIDI note for the accented first beat. Default 76 (High Wood Block).
66    #[serde(default = "default_accent_pitch")]
67    pub accent_pitch: u8,
68    /// MIDI note for regular beats. Default 77 (Low Wood Block).
69    #[serde(default = "default_beat_pitch")]
70    pub beat_pitch: u8,
71    /// Velocity for the accented first beat. Default 100.
72    #[serde(default = "default_accent_velocity")]
73    pub accent_velocity: u8,
74    /// Velocity for regular beats. Default 70.
75    #[serde(default = "default_beat_velocity")]
76    pub beat_velocity: u8,
77}
78
79impl Default for MetronomeConfig {
80    fn default() -> Self {
81        Self {
82            channel: 9,
83            accent_pitch: 76,
84            beat_pitch: 77,
85            accent_velocity: 100,
86            beat_velocity: 70,
87        }
88    }
89}
90
91/// Options for [`to_playback_events`].
92#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
93#[serde(default)]
94pub struct PlaybackOptions {
95    /// Replaces every written tempo when `Some` and suppresses written tempo ramps.
96    ///
97    /// Use [`tempo_multiplier`](Self::tempo_multiplier) when a host needs to speed up or slow
98    /// down a score while retaining the written tempo map.
99    pub bpm_override: Option<u16>,
100    /// Multiplies every effective tempo, including written tempo changes and ramps.
101    ///
102    /// The default `1.0` preserves the score. Non-finite or non-positive values are normalized
103    /// to `1.0` so an untrusted host option cannot produce an invalid schedule.
104    #[serde(default = "default_tempo_multiplier")]
105    pub tempo_multiplier: f64,
106    /// Part indices to silence. Events from these parts are omitted entirely.
107    pub muted_parts: Vec<usize>,
108    /// Restrict playback to measures in the inclusive range `[start, end]`.
109    /// Physical measure indices (0-based). `None` plays the full sequence.
110    /// Events within the region start at `time_beats = 0`.
111    #[serde(default)]
112    pub loop_region: Option<(usize, usize)>,
113    /// Duration multiplier for notes with `Fermata` articulation. Default 1.5.
114    #[serde(default = "default_fermata_multiplier")]
115    pub fermata_multiplier: f64,
116    /// Additional beat-domain hold requested after a fermata note. Default 0 keeps legacy
117    /// multiplier-only behavior; hosts decide how to realize the resulting silence.
118    #[serde(default = "default_fermata_hold_beats")]
119    pub fermata_hold_beats: f64,
120    /// Swing ratio for aligned pairs of plain notes or rests of [`swing_unit`] duration.
121    /// `None` = straight.
122    /// `0.67` ≈ triplet swing (2:1). Valid range: (0.5, 1.0).
123    /// Applied only when both adjacent rhythmic units match `swing_unit`, with no tuplet or dot.
124    #[serde(default)]
125    pub swing: Option<f64>,
126    /// Note duration that swing is applied to. Defaults to `Duration::Eighth`.
127    /// Set to `Duration::Sixteenth` for Latin/funk 16th-note swing.
128    #[serde(default = "default_swing_unit")]
129    pub swing_unit: Duration,
130    /// When `Some`, injects metronome click events into the event list.
131    /// Clicks are tagged with `PlaybackEvent.is_metronome = true`.
132    #[serde(default)]
133    pub metronome: Option<MetronomeConfig>,
134    /// Optional realization policy. The default retains authored ornament and arpeggio marks
135    /// without synthesizing extra events.
136    #[serde(default)]
137    pub realization_profile: PlaybackRealizationProfile,
138}
139
140impl Default for PlaybackOptions {
141    fn default() -> Self {
142        Self {
143            bpm_override: None,
144            tempo_multiplier: 1.0,
145            muted_parts: Vec::new(),
146            loop_region: None,
147            fermata_multiplier: 1.5,
148            fermata_hold_beats: 0.0,
149            swing: None,
150            swing_unit: Duration::Eighth,
151            metronome: None,
152            realization_profile: PlaybackRealizationProfile::Authored,
153        }
154    }
155}
156
157fn normalized_tempo_multiplier(options: &PlaybackOptions) -> f64 {
158    let multiplier = options.tempo_multiplier;
159    if multiplier.is_finite() && multiplier > 0.0 {
160        multiplier
161    } else {
162        1.0
163    }
164}
165
166fn swingable_rhythm_slot(note: &Note, unit: &Duration) -> bool {
167    !note.is_grace
168        && !note.is_cue
169        && note.tuplet.is_none()
170        && note.dot_count == 0
171        && note.duration == *unit
172}
173
174fn starts_swing_pair(
175    notes: &[Note],
176    note_index: usize,
177    written_beats: f64,
178    grid_offset_beats: f64,
179    measure_beats: f64,
180    unit: &Duration,
181) -> bool {
182    let Some(first) = notes.get(note_index) else {
183        return false;
184    };
185    let Some(second) = notes.get(note_index + 1) else {
186        return false;
187    };
188    if !swingable_rhythm_slot(first, unit) || !swingable_rhythm_slot(second, unit) {
189        return false;
190    }
191    let pair_beats = first.beats() * 2.0;
192    if written_beats + pair_beats > measure_beats + 1e-9 {
193        return false;
194    }
195    let slot = (written_beats + grid_offset_beats) / pair_beats;
196    (slot - slot.round()).abs() < 1e-9
197}
198
199fn initial_tempo_bpm(score: &Score, options: &PlaybackOptions) -> f64 {
200    f64::from(
201        options
202            .bpm_override
203            .unwrap_or(score.settings.tempo_bpm)
204            .max(1),
205    ) * normalized_tempo_multiplier(options)
206}
207
208fn written_tempo_bpm(options: &PlaybackOptions, tempo: u16) -> Option<f64> {
209    options
210        .bpm_override
211        .is_none()
212        .then(|| f64::from(tempo.max(1)) * normalized_tempo_multiplier(options))
213}
214
215fn written_tempo_ramp_bpm(options: &PlaybackOptions, tempo: Option<u16>) -> Option<f64> {
216    options.bpm_override.is_none().then_some(())?;
217    tempo.map(|tempo| f64::from(tempo.max(1)) * normalized_tempo_multiplier(options))
218}
219
220#[derive(Clone, Copy, Default)]
221struct ScoreTempoMark {
222    bpm: Option<u16>,
223    ramp_to_bpm: Option<u16>,
224}
225
226/// Tempo directions are score-wide even when an interchange format places them on one part.
227/// Resolve each field from the first staff that writes it, in score order.
228fn score_tempo_marks(score: &Score) -> Vec<ScoreTempoMark> {
229    let count = score
230        .parts
231        .iter()
232        .flat_map(|part| &part.staves)
233        .map(|staff| staff.measures.len())
234        .max()
235        .unwrap_or(0);
236    let mut marks = vec![ScoreTempoMark::default(); count];
237    for (index, mark) in marks.iter_mut().enumerate() {
238        for part in &score.parts {
239            for staff in &part.staves {
240                if let Some(measure) = staff.measures.get(index) {
241                    mark.bpm = mark.bpm.or(measure.tempo);
242                    mark.ramp_to_bpm = mark.ramp_to_bpm.or(measure.tempo_ramp_to);
243                }
244            }
245        }
246    }
247    marks
248}
249
250fn semantic_tempo_bpm(bpm: f64) -> u16 {
251    bpm.round().clamp(1.0, f64::from(u16::MAX)) as u16
252}
253
254/// A single sounding event suitable for audio playback engines (e.g. Web Audio, Tone.js).
255///
256/// Grace notes and rests are excluded. Chords are expanded to one event per pitch.
257#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
258pub struct PlaybackEvent {
259    /// Stable source note address (`part:staff:measure:voice:note`), or `None` for metronome events.
260    /// Chord pitches share the address of their source note.
261    #[serde(default, skip_serializing_if = "Option::is_none")]
262    pub address: Option<String>,
263    /// Typed source address for notation hosts; `None` for metronome events.
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub source: Option<NoteAddr>,
266    /// Original MusicXML voice number when the source used a non-default identifier.
267    /// `source` remains the stable four-slot canonical address used by editing APIs.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub source_voice_number: Option<u32>,
270    /// Absolute beat position from the start of the score.
271    pub time_beats: f64,
272    /// Absolute time in seconds from the start of the score.
273    pub time_secs: f64,
274    /// MIDI pitch number (0–127).
275    pub pitch_midi: u8,
276    /// Exact sounding pitch in hundredths of a MIDI semitone.
277    ///
278    /// `pitch_midi` is retained as a compatibility convenience for integer-MIDI hosts;
279    /// microtonal-capable hosts should use this field.
280    #[serde(default)]
281    pub pitch_midi_cents: i32,
282    /// Authored normalized pitch-bend curve for a bend-capable host. Each point is relative to
283    /// `pitch_midi_cents` and positioned within this event's sounding duration. Empty means the
284    /// event has no authored continuous bend.
285    #[serde(default)]
286    pub pitch_bend_curve: Vec<GuitarBendPoint>,
287    /// Authored pause requested after this note by a breath mark or caesura. The host decides
288    /// how to realize the silence while preserving this deterministic beat-domain contract.
289    #[serde(default)]
290    pub post_note_pause_beats: f64,
291    /// Authored articulation and ornament marks for a provider to interpret. The core schedule
292    /// deliberately does not invent auxiliary pitches for trill, mordent, or turn.
293    #[serde(default)]
294    pub articulations: Vec<Articulation>,
295    /// Authored chord symbol at this note position. It is a semantic cue for accompaniment or
296    /// harmonic playback providers; acorde does not invent accompaniment notes.
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub chord_symbol: Option<ChordSymbol>,
299    /// Authored guitar playing technique, when present. Providers may map this stable semantic
300    /// value to keyswitches or synthesis behavior without score re-parsing.
301    #[serde(default, skip_serializing_if = "Option::is_none")]
302    pub guitar_technique: Option<GuitarTechnique>,
303    /// MIDI velocity (1–127). Derived from the staff's [`Dynamic`](crate::Dynamic) in force
304    /// (see [`DynamicTimeline`]); 64 before the first marking.
305    /// Boosted by +20 for Accent / Marcato articulations (clamped to 127).
306    pub velocity: u8,
307    /// Sounding duration in beats. Halved for Staccato / Staccatissimo.
308    pub duration_beats: f64,
309    /// Sounding duration in seconds.
310    pub duration_secs: f64,
311    /// True when the note has `pedal_start` set (sustain pedal down).
312    pub pedal: bool,
313    /// Index of the part this event originates from (useful for per-channel MIDI routing).
314    pub part_index: usize,
315    /// MIDI channel of the originating part (`part.midi_channel`). For Tone.js channel routing.
316    pub channel: u8,
317    /// Effective General MIDI program after applying any measure-local instrument change.
318    #[serde(default)]
319    pub program: u8,
320    /// Stable effective instrument ID when the part or measure declares one.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub instrument_id: Option<String>,
323    /// `true` for metronome click events injected via [`MetronomeConfig`].
324    #[serde(default)]
325    pub is_metronome: bool,
326}
327
328/// Version of the host-neutral playback timing comparison contract.
329pub const PLAYBACK_COMPARISON_CONTRACT_VERSION: u16 = 2;
330/// Maximum number of events accepted by one comparison operation.
331pub const MAX_PLAYBACK_COMPARISON_EVENTS: usize = 1_000_000;
332const MAX_PLAYBACK_MISMATCHES: usize = 256;
333/// Maximum number of projected tablature events retained in one report.
334pub const MAX_TAB_PERFORMANCE_EVENTS: usize = 1_000_000;
335const MAX_TAB_PERFORMANCE_DIAGNOSTICS: usize = 1_024;
336
337/// Version of the host-neutral offline rendering manifest contract.
338pub const OFFLINE_RENDER_CONTRACT_VERSION: u16 = 3;
339
340/// Score material selected for an offline render.  Addresses remain those of the
341/// source score even when a view or a range is selected.
342#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
343#[serde(rename_all = "kebab-case")]
344pub enum OfflineRenderScope {
345    #[default]
346    FullScore,
347    MeasureRange {
348        start: usize,
349        end: usize,
350    },
351    Selection {
352        addresses: Vec<NoteAddr>,
353    },
354}
355
356/// Navigation realization selected by an offline-render request.
357#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
358#[serde(rename_all = "kebab-case")]
359pub enum OfflineRenderNavigationPolicy {
360    /// Follow the score's authored repeats, jumps and endings.
361    #[default]
362    Authored,
363}
364
365/// One event with integer sample-frame boundaries for an offline renderer.
366#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
367pub struct OfflineRenderFrameEvent {
368    pub event: PlaybackEvent,
369    pub start_frame: u64,
370    pub duration_frames: u64,
371    pub end_frame: u64,
372}
373
374/// A non-note semantic action expressed on the same sample-frame clock as
375/// [`OfflineRenderFrameEvent`].  Audio providers can consume these without
376/// reverse-engineering notation from a note schedule.
377#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
378#[serde(rename_all = "kebab-case")]
379pub enum OfflineRenderSemanticEventKind {
380    /// A measure-local instrument routing change. Providers apply this before
381    /// attacks at the same frame rather than inferring it from note events.
382    InstrumentChange {
383        instrument_id: String,
384        channel: u8,
385        program: u8,
386        transpose_semitones: i8,
387    },
388    Controller {
389        channel: u8,
390        controller: u8,
391        value: u8,
392    },
393    /// Signed MIDI 14-bit pitch bend retained from the interchange timeline.
394    PitchBend {
395        channel: u8,
396        value: i16,
397    },
398    /// MIDI program selection at a canonical score tick.
399    ProgramChange {
400        channel: u8,
401        program: u8,
402    },
403    /// Channel pressure or key pressure at a canonical score tick.
404    Aftertouch {
405        channel: u8,
406        #[serde(default, skip_serializing_if = "Option::is_none")]
407        key: Option<u8>,
408        value: u8,
409    },
410    Tempo {
411        bpm: u16,
412        #[serde(default, skip_serializing_if = "Option::is_none")]
413        ramp_to_bpm: Option<u16>,
414    },
415    Navigation {
416        marker: String,
417    },
418    Pedal {
419        down: bool,
420    },
421    Articulation {
422        articulation: Articulation,
423    },
424    GuitarBend {
425        points: Vec<GuitarBendPoint>,
426    },
427    /// A semantic release boundary.  It intentionally has no synthesis
428    /// parameters: providers decide how a release tail is rendered.
429    ReleaseTail,
430}
431
432/// A source-addressable non-note action in an offline render manifest.
433#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
434pub struct OfflineRenderSemanticFrameEvent {
435    pub kind: OfflineRenderSemanticEventKind,
436    pub frame: u64,
437    #[serde(default, skip_serializing_if = "Option::is_none")]
438    pub source: Option<NoteAddr>,
439    #[serde(default, skip_serializing_if = "Option::is_none")]
440    pub measure: Option<OfflineRenderMeasureAddress>,
441}
442
443/// Stable source location for a measure-scoped offline action.
444#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
445pub struct OfflineRenderMeasureAddress {
446    pub part: usize,
447    pub staff: usize,
448    pub measure: usize,
449}
450
451/// Machine-readable condition observed while deriving an offline schedule.
452#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
453#[serde(rename_all = "kebab-case")]
454pub enum OfflineRenderDiagnosticKind {
455    /// A selected canonical note address did not yield a sounding event.
456    UnresolvedSelectionAddress,
457    /// A valid selection contained no sounding events after scheduling.
458    EmptySelection,
459}
460
461/// Source-located diagnostic for a provider-neutral offline manifest.
462#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
463pub struct OfflineRenderDiagnostic {
464    pub kind: OfflineRenderDiagnosticKind,
465    #[serde(default, skip_serializing_if = "Option::is_none")]
466    pub source: Option<NoteAddr>,
467}
468
469/// Encoded audio format requested from a host-side offline renderer.
470///
471/// The core does not encode audio; this keeps the requested output explicit in the deterministic
472/// schedule handed to the native SF2 renderer, Composer, or another host.
473#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
474pub enum OfflineRenderFormat {
475    #[default]
476    Wav,
477    Flac,
478    Mp3,
479}
480
481/// Host-neutral parameters for an offline render operation.
482#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
483pub struct OfflineRenderRequest {
484    /// Requested encoded format. The host reports unsupported formats explicitly.
485    #[serde(default)]
486    pub format: OfflineRenderFormat,
487    /// PCM sample rate used to convert event seconds to exact sample frames.
488    #[serde(default = "default_offline_render_sample_rate")]
489    pub sample_rate_hz: u32,
490    /// Requested interleaved output channel count.
491    #[serde(default = "default_offline_render_channels")]
492    pub channels: u8,
493    /// Stable name/version of the selected host provider, when already chosen.
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub provider_identity: Option<String>,
496    /// Stable provider asset identifier (for example a host preset or sample set).
497    #[serde(default, skip_serializing_if = "Option::is_none")]
498    pub asset_identity: Option<String>,
499    /// Optional linked view to resolve before event scheduling.
500    #[serde(default, skip_serializing_if = "Option::is_none")]
501    pub view_id: Option<String>,
502    #[serde(default)]
503    pub scope: OfflineRenderScope,
504    #[serde(default)]
505    pub navigation_policy: OfflineRenderNavigationPolicy,
506    /// Extra release tail after the final sounding event, in milliseconds.
507    #[serde(default)]
508    pub release_tail_millis: u32,
509    /// Full reproducible playback policy. When omitted, the legacy function
510    /// argument is used and copied into the manifest for migration clarity.
511    #[serde(default, skip_serializing_if = "Option::is_none")]
512    pub playback_options: Option<PlaybackOptions>,
513}
514
515fn default_offline_render_sample_rate() -> u32 {
516    48_000
517}
518
519fn default_offline_render_channels() -> u8 {
520    2
521}
522
523impl Default for OfflineRenderRequest {
524    fn default() -> Self {
525        Self {
526            format: OfflineRenderFormat::Wav,
527            sample_rate_hz: default_offline_render_sample_rate(),
528            channels: default_offline_render_channels(),
529            provider_identity: None,
530            asset_identity: None,
531            view_id: None,
532            scope: OfflineRenderScope::FullScore,
533            navigation_policy: OfflineRenderNavigationPolicy::Authored,
534            release_tail_millis: 0,
535            playback_options: None,
536        }
537    }
538}
539
540/// Sample-accurate event schedule for a host-side offline render.
541///
542/// `duration_frames` is derived from the final event's end time and deliberately excludes codec
543/// padding. A host owns synthesis, tail policy, file creation, and encoded bytes.
544#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
545pub struct OfflineRenderManifest {
546    pub contract_version: u16,
547    pub playback_contract_version: u16,
548    pub format: OfflineRenderFormat,
549    pub sample_rate_hz: u32,
550    pub channels: u8,
551    #[serde(default, skip_serializing_if = "Option::is_none")]
552    pub provider_identity: Option<String>,
553    #[serde(default, skip_serializing_if = "Option::is_none")]
554    pub asset_identity: Option<String>,
555    #[serde(default, skip_serializing_if = "Option::is_none")]
556    pub view_id: Option<String>,
557    #[serde(default)]
558    pub scope: OfflineRenderScope,
559    #[serde(default)]
560    pub navigation_policy: OfflineRenderNavigationPolicy,
561    #[serde(default)]
562    pub release_tail_frames: u64,
563    /// The exact timing policy that produced this manifest.
564    #[serde(default)]
565    pub playback_options: PlaybackOptions,
566    pub duration_frames: u64,
567    pub events: Vec<PlaybackEvent>,
568    /// Frame-quantized equivalents of `events`; retained alongside the legacy
569    /// seconds schedule so v1 clients can migrate without losing semantics.
570    #[serde(default)]
571    pub frame_events: Vec<OfflineRenderFrameEvent>,
572    /// Pedal, articulation, bend and release semantics on the exact output
573    /// sample clock.  Note attacks remain in [`Self::frame_events`].
574    #[serde(default)]
575    pub semantic_events: Vec<OfflineRenderSemanticFrameEvent>,
576    #[serde(default)]
577    pub diagnostics: Vec<OfflineRenderDiagnostic>,
578}
579
580impl OfflineRenderManifest {
581    /// Validate a persisted provider-neutral schedule before a host hands it to
582    /// a synthesizer. Legacy v1/v2 manifests remain readable; current manifests
583    /// additionally require a one-to-one frame schedule for every note event.
584    pub fn validate(&self) -> Result<(), crate::Error> {
585        if !(1..=OFFLINE_RENDER_CONTRACT_VERSION).contains(&self.contract_version)
586            || !(8_000..=384_000).contains(&self.sample_rate_hz)
587            || !(1..=8).contains(&self.channels)
588            || self.release_tail_frames > self.duration_frames
589        {
590            return Err(crate::Error::InvalidOfflineRenderRequest);
591        }
592
593        if self.contract_version >= 2 && self.frame_events.len() != self.events.len() {
594            return Err(crate::Error::InvalidOfflineRenderRequest);
595        }
596        let mut latest_event_end = 0_u64;
597        for (index, frame_event) in self.frame_events.iter().enumerate() {
598            let Some(expected_event) = self.events.get(index) else {
599                return Err(crate::Error::InvalidOfflineRenderRequest);
600            };
601            if frame_event.event != *expected_event
602                || frame_event
603                    .start_frame
604                    .checked_add(frame_event.duration_frames)
605                    != Some(frame_event.end_frame)
606                || frame_event.end_frame > self.duration_frames
607            {
608                return Err(crate::Error::InvalidOfflineRenderRequest);
609            }
610            latest_event_end = latest_event_end.max(frame_event.end_frame);
611        }
612        let latest_semantic_frame = self
613            .semantic_events
614            .iter()
615            .map(|event| event.frame)
616            .max()
617            .unwrap_or(0);
618        if latest_semantic_frame > self.duration_frames {
619            return Err(crate::Error::InvalidOfflineRenderRequest);
620        }
621        if self.contract_version >= 2
622            && latest_event_end
623                .max(latest_semantic_frame)
624                .checked_add(self.release_tail_frames)
625                != Some(self.duration_frames)
626        {
627            return Err(crate::Error::InvalidOfflineRenderRequest);
628        }
629        Ok(())
630    }
631}
632
633/// Host-reported result metadata for an [`OfflineRenderManifest`].
634///
635/// This is a result contract, not proof of audio quality or device-independent equivalence.
636#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
637pub struct OfflineRenderResult {
638    pub contract_version: u16,
639    pub format: OfflineRenderFormat,
640    pub sample_rate_hz: u32,
641    pub channels: u8,
642    #[serde(default, skip_serializing_if = "Option::is_none")]
643    pub provider_identity: Option<String>,
644    pub duration_frames: u64,
645    pub output_bytes: u64,
646}
647
648/// A host-side auxiliary send between two logical playback buses.
649#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
650pub struct PlaybackAuxSend {
651    pub source_bus: String,
652    pub destination_bus: String,
653    /// Gain applied before the destination effect chain, in dB.
654    pub gain_db: f64,
655}
656
657/// Identifies a host effect attached to a logical bus without carrying provider-specific settings.
658#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
659pub struct PlaybackEffectRoute {
660    pub bus_id: String,
661    pub effect_id: String,
662    #[serde(default = "default_effect_enabled")]
663    pub enabled: bool,
664}
665
666fn default_effect_enabled() -> bool {
667    true
668}
669
670/// Host-neutral routing choices resolved after score playback events are generated.
671#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
672pub struct PlaybackRoutingConfig {
673    #[serde(default, skip_serializing_if = "Option::is_none")]
674    pub provider_identity: Option<String>,
675    #[serde(default = "default_master_bus")]
676    pub master_bus: String,
677    #[serde(default = "default_metronome_bus")]
678    pub metronome_bus: String,
679    /// Part-index routes, overridden by a matching stable instrument ID.
680    #[serde(default)]
681    pub part_buses: BTreeMap<usize, String>,
682    #[serde(default)]
683    pub instrument_buses: BTreeMap<String, String>,
684    #[serde(default)]
685    pub aux_sends: Vec<PlaybackAuxSend>,
686    #[serde(default)]
687    pub effect_routes: Vec<PlaybackEffectRoute>,
688}
689
690fn default_master_bus() -> String {
691    "master".into()
692}
693
694fn default_metronome_bus() -> String {
695    "metronome".into()
696}
697
698impl Default for PlaybackRoutingConfig {
699    fn default() -> Self {
700        Self {
701            provider_identity: None,
702            master_bus: default_master_bus(),
703            metronome_bus: default_metronome_bus(),
704            part_buses: BTreeMap::new(),
705            instrument_buses: BTreeMap::new(),
706            aux_sends: Vec::new(),
707            effect_routes: Vec::new(),
708        }
709    }
710}
711
712/// One unique event source route in a [`PlaybackRoutingManifest`].
713#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
714pub struct PlaybackBusRoute {
715    pub part_index: usize,
716    pub channel: u8,
717    pub program: u8,
718    #[serde(default, skip_serializing_if = "Option::is_none")]
719    pub instrument_id: Option<String>,
720    pub is_metronome: bool,
721    pub bus_id: String,
722}
723
724/// Deterministic logical routing graph for score playback events.
725#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
726pub struct PlaybackRoutingManifest {
727    pub contract_version: u16,
728    #[serde(default, skip_serializing_if = "Option::is_none")]
729    pub provider_identity: Option<String>,
730    pub master_bus: String,
731    pub metronome_bus: String,
732    pub routes: Vec<PlaybackBusRoute>,
733    pub aux_sends: Vec<PlaybackAuxSend>,
734    pub effect_routes: Vec<PlaybackEffectRoute>,
735}
736
737/// Version of the host-neutral routing manifest contract.
738pub const PLAYBACK_ROUTING_CONTRACT_VERSION: u16 = 1;
739
740fn valid_routing_id(value: &str) -> bool {
741    !value.is_empty()
742        && value.len() <= 64
743        && value
744            .bytes()
745            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
746}
747
748fn validate_playback_routing(config: &PlaybackRoutingConfig) -> Result<(), crate::Error> {
749    if !valid_routing_id(&config.master_bus)
750        || !valid_routing_id(&config.metronome_bus)
751        || config.part_buses.values().any(|bus| !valid_routing_id(bus))
752        || config
753            .instrument_buses
754            .values()
755            .any(|bus| !valid_routing_id(bus))
756        || config.aux_sends.len() > 64
757        || config.effect_routes.len() > 128
758    {
759        return Err(crate::Error::InvalidPlaybackRouting);
760    }
761    for send in &config.aux_sends {
762        if !valid_routing_id(&send.source_bus)
763            || !valid_routing_id(&send.destination_bus)
764            || !send.gain_db.is_finite()
765            || !(-120.0..=24.0).contains(&send.gain_db)
766        {
767            return Err(crate::Error::InvalidPlaybackRouting);
768        }
769    }
770    if config
771        .effect_routes
772        .iter()
773        .any(|effect| !valid_routing_id(&effect.bus_id) || !valid_routing_id(&effect.effect_id))
774    {
775        return Err(crate::Error::InvalidPlaybackRouting);
776    }
777    Ok(())
778}
779
780/// Resolve a bounded, deterministic logical routing graph for a score schedule.
781pub fn build_playback_routing_manifest(
782    score: &Score,
783    playback_options: &PlaybackOptions,
784    config: &PlaybackRoutingConfig,
785) -> Result<PlaybackRoutingManifest, crate::Error> {
786    validate_playback_routing(config)?;
787    let events = to_playback_events_bounded(score, playback_options)?;
788    let mut routes = BTreeMap::new();
789    for event in events {
790        let bus_id = if event.is_metronome {
791            config.metronome_bus.clone()
792        } else if let Some(bus) = event
793            .instrument_id
794            .as_ref()
795            .and_then(|instrument_id| config.instrument_buses.get(instrument_id))
796        {
797            bus.clone()
798        } else if let Some(bus) = config.part_buses.get(&event.part_index) {
799            bus.clone()
800        } else {
801            config.master_bus.clone()
802        };
803        let route = PlaybackBusRoute {
804            part_index: event.part_index,
805            channel: event.channel,
806            program: event.program,
807            instrument_id: event.instrument_id,
808            is_metronome: event.is_metronome,
809            bus_id,
810        };
811        routes.insert(route.clone(), route);
812    }
813    Ok(PlaybackRoutingManifest {
814        contract_version: PLAYBACK_ROUTING_CONTRACT_VERSION,
815        provider_identity: config.provider_identity.clone(),
816        master_bus: config.master_bus.clone(),
817        metronome_bus: config.metronome_bus.clone(),
818        routes: routes.into_values().collect(),
819        aux_sends: config.aux_sends.clone(),
820        effect_routes: config.effect_routes.clone(),
821    })
822}
823
824/// Build a bounded sample-accurate schedule for a host-side offline render.
825pub fn build_offline_render_manifest(
826    score: &Score,
827    playback_options: &PlaybackOptions,
828    request: &OfflineRenderRequest,
829) -> Result<OfflineRenderManifest, crate::Error> {
830    if !(8_000..=384_000).contains(&request.sample_rate_hz) || !(1..=8).contains(&request.channels)
831    {
832        return Err(crate::Error::InvalidOfflineRenderRequest);
833    }
834    let resolved_score = match request.view_id.as_deref() {
835        Some(view_id) => score.resolve_view(view_id)?,
836        None => score.clone(),
837    };
838    let mut effective_options = request
839        .playback_options
840        .clone()
841        .unwrap_or_else(|| playback_options.clone());
842    if let OfflineRenderScope::MeasureRange { start, end } = request.scope {
843        if start > end {
844            return Err(crate::Error::InvalidOfflineRenderRequest);
845        }
846        effective_options.loop_region = Some((start, end));
847    }
848    let mut events = to_playback_events_bounded(&resolved_score, &effective_options)?;
849    let mut diagnostics = Vec::new();
850    let mut selection_origin_secs = 0.0;
851    if let OfflineRenderScope::Selection { ref addresses } = request.scope {
852        if addresses.is_empty() {
853            return Err(crate::Error::InvalidOfflineRenderRequest);
854        }
855        for address in addresses {
856            if !events
857                .iter()
858                .any(|event| event.source.as_ref() == Some(address))
859            {
860                diagnostics.push(OfflineRenderDiagnostic {
861                    kind: OfflineRenderDiagnosticKind::UnresolvedSelectionAddress,
862                    source: Some(address.clone()),
863                });
864            }
865        }
866        events.retain(|event| {
867            event
868                .source
869                .as_ref()
870                .is_some_and(|source| addresses.contains(source))
871        });
872        let origin_secs = events
873            .iter()
874            .map(|event| event.time_secs)
875            .fold(f64::INFINITY, f64::min);
876        if origin_secs.is_finite() {
877            selection_origin_secs = origin_secs;
878            for event in &mut events {
879                event.time_secs -= origin_secs;
880            }
881        }
882        if events.is_empty() {
883            diagnostics.push(OfflineRenderDiagnostic {
884                kind: OfflineRenderDiagnosticKind::EmptySelection,
885                source: None,
886            });
887        }
888    }
889    let duration_secs = events
890        .iter()
891        .map(|event| event.time_secs + event.duration_secs)
892        .fold(0.0_f64, f64::max);
893    if !duration_secs.is_finite() || duration_secs < 0.0 {
894        return Err(crate::Error::InvalidOfflineRenderRequest);
895    }
896    let release_tail_frames =
897        (f64::from(request.release_tail_millis) * f64::from(request.sample_rate_hz) / 1_000.0)
898            .ceil();
899    let duration_frames = (duration_secs * f64::from(request.sample_rate_hz)).ceil();
900    if !duration_frames.is_finite() || duration_frames > u64::MAX as f64 {
901        return Err(crate::Error::InvalidOfflineRenderRequest);
902    }
903    if !release_tail_frames.is_finite()
904        || release_tail_frames > u64::MAX as f64
905        || duration_frames > (u64::MAX as f64 - release_tail_frames)
906    {
907        return Err(crate::Error::InvalidOfflineRenderRequest);
908    }
909    let frame_events = events
910        .iter()
911        .cloned()
912        .map(|event| {
913            let start_frame = (event.time_secs * f64::from(request.sample_rate_hz)).round() as u64;
914            let end_frame = ((event.time_secs + event.duration_secs)
915                * f64::from(request.sample_rate_hz))
916            .ceil() as u64;
917            OfflineRenderFrameEvent {
918                duration_frames: end_frame.saturating_sub(start_frame),
919                event,
920                start_frame,
921                end_frame,
922            }
923        })
924        .collect::<Vec<_>>();
925    let mut semantic_events = Vec::new();
926    for event in &frame_events {
927        let source = event.event.source.clone();
928        if event.event.pedal {
929            semantic_events.push(OfflineRenderSemanticFrameEvent {
930                kind: OfflineRenderSemanticEventKind::Pedal { down: true },
931                frame: event.start_frame,
932                source: source.clone(),
933                measure: None,
934            });
935        }
936        if source.as_ref().is_some_and(|address| {
937            resolved_score
938                .parts
939                .get(address.part)
940                .and_then(|part| part.staves.get(address.staff))
941                .and_then(|staff| staff.measures.get(address.measure))
942                .and_then(|measure| measure.voices.get(address.voice))
943                .and_then(|voice| voice.get(address.note))
944                .is_some_and(|note| note.pedal_end)
945        }) {
946            semantic_events.push(OfflineRenderSemanticFrameEvent {
947                kind: OfflineRenderSemanticEventKind::Pedal { down: false },
948                frame: event.start_frame,
949                source: source.clone(),
950                measure: None,
951            });
952        }
953        for articulation in &event.event.articulations {
954            semantic_events.push(OfflineRenderSemanticFrameEvent {
955                kind: OfflineRenderSemanticEventKind::Articulation {
956                    articulation: articulation.clone(),
957                },
958                frame: event.start_frame,
959                source: source.clone(),
960                measure: None,
961            });
962        }
963        if !event.event.pitch_bend_curve.is_empty() {
964            semantic_events.push(OfflineRenderSemanticFrameEvent {
965                kind: OfflineRenderSemanticEventKind::GuitarBend {
966                    points: event.event.pitch_bend_curve.clone(),
967                },
968                frame: event.start_frame,
969                source,
970                measure: None,
971            });
972        }
973    }
974    append_measure_semantic_events(
975        &resolved_score,
976        &effective_options,
977        request.sample_rate_hz,
978        &request.scope,
979        selection_origin_secs,
980        &mut semantic_events,
981    );
982    // Automation can outlive the final sounding note (for example an imported
983    // program change on an otherwise silent measure). The manifest duration
984    // must retain those actions before adding any host release tail.
985    let semantic_end_frame = semantic_events
986        .iter()
987        .map(|event| event.frame)
988        .max()
989        .unwrap_or(0);
990    let content_duration_frames = (duration_frames as u64).max(semantic_end_frame);
991    if release_tail_frames > 0.0 {
992        semantic_events.push(OfflineRenderSemanticFrameEvent {
993            kind: OfflineRenderSemanticEventKind::ReleaseTail,
994            frame: content_duration_frames,
995            source: None,
996            measure: None,
997        });
998    }
999    let manifest = OfflineRenderManifest {
1000        contract_version: OFFLINE_RENDER_CONTRACT_VERSION,
1001        playback_contract_version: PLAYBACK_COMPARISON_CONTRACT_VERSION,
1002        format: request.format,
1003        sample_rate_hz: request.sample_rate_hz,
1004        channels: request.channels,
1005        provider_identity: request.provider_identity.clone(),
1006        asset_identity: request.asset_identity.clone(),
1007        view_id: request.view_id.clone(),
1008        scope: request.scope.clone(),
1009        navigation_policy: request.navigation_policy,
1010        release_tail_frames: release_tail_frames as u64,
1011        playback_options: effective_options,
1012        duration_frames: content_duration_frames + release_tail_frames as u64,
1013        events,
1014        frame_events,
1015        semantic_events,
1016        diagnostics,
1017    };
1018    manifest.validate()?;
1019    Ok(manifest)
1020}
1021
1022#[derive(Clone, Copy)]
1023struct OfflineMeasureTime {
1024    measure: usize,
1025    start_secs: f64,
1026    bpm: f64,
1027    ramp_to_bpm: Option<f64>,
1028    beats: f64,
1029}
1030
1031fn offline_measure_times(
1032    score: &Score,
1033    options: &PlaybackOptions,
1034    part: usize,
1035    staff: usize,
1036    tempo_marks: &[ScoreTempoMark],
1037) -> Vec<OfflineMeasureTime> {
1038    let Some(staff_ref) = score
1039        .parts
1040        .get(part)
1041        .and_then(|part| part.staves.get(staff))
1042    else {
1043        return Vec::new();
1044    };
1045    let sequence = measure_sequence(score).into_iter().filter(|measure| {
1046        options
1047            .loop_region
1048            .is_none_or(|(start, end)| *measure >= start && *measure <= end)
1049    });
1050    let mut bpm = initial_tempo_bpm(score, options);
1051    let mut secs = 0.0;
1052    let mut result = Vec::new();
1053    for measure_index in sequence {
1054        if staff_ref.measures.get(measure_index).is_none() {
1055            continue;
1056        }
1057        let mark = tempo_marks.get(measure_index).copied().unwrap_or_default();
1058        if let Some(tempo) = mark.bpm.and_then(|tempo| written_tempo_bpm(options, tempo)) {
1059            bpm = tempo;
1060        }
1061        let beats = score.playback_measure_beats(measure_index);
1062        let ramp_to_bpm = written_tempo_ramp_bpm(options, mark.ramp_to_bpm);
1063        result.push(OfflineMeasureTime {
1064            measure: measure_index,
1065            start_secs: secs,
1066            bpm,
1067            ramp_to_bpm,
1068            beats,
1069        });
1070        secs += tempo_ramp_seconds(bpm, ramp_to_bpm, beats, beats);
1071        if let Some(end_bpm) = ramp_to_bpm {
1072            bpm = end_bpm;
1073        }
1074    }
1075    result
1076}
1077
1078fn append_measure_semantic_events(
1079    score: &Score,
1080    options: &PlaybackOptions,
1081    sample_rate_hz: u32,
1082    scope: &OfflineRenderScope,
1083    origin_secs: f64,
1084    events: &mut Vec<OfflineRenderSemanticFrameEvent>,
1085) {
1086    let tempo_marks = score_tempo_marks(score);
1087    for (part_index, part) in score.parts.iter().enumerate() {
1088        let timeline = offline_measure_times(score, options, part_index, 0, &tempo_marks);
1089        let Some(staff) = part.staves.first() else {
1090            continue;
1091        };
1092        let mut tick_starts = Vec::with_capacity(staff.measures.len());
1093        let mut tick = 0u64;
1094        for measure_index in 0..staff.measures.len() {
1095            tick_starts.push(tick);
1096            let beats = score.playback_measure_beats(measure_index);
1097            tick = tick.saturating_add((beats * 480.0).round() as u64);
1098        }
1099        for time in timeline {
1100            if let OfflineRenderScope::Selection { addresses } = scope
1101                && !addresses
1102                    .iter()
1103                    .any(|address| address.part == part_index && address.measure == time.measure)
1104            {
1105                continue;
1106            }
1107            let address = OfflineRenderMeasureAddress {
1108                part: part_index,
1109                staff: 0,
1110                measure: time.measure,
1111            };
1112            let frame = ((time.start_secs - origin_secs).max(0.0) * f64::from(sample_rate_hz))
1113                .round() as u64;
1114            let measure = &staff.measures[time.measure];
1115            let mark = tempo_marks.get(time.measure).copied().unwrap_or_default();
1116            if part_index == 0
1117                && options.bpm_override.is_none()
1118                && (mark.bpm.is_some() || mark.ramp_to_bpm.is_some())
1119            {
1120                events.push(OfflineRenderSemanticFrameEvent {
1121                    kind: OfflineRenderSemanticEventKind::Tempo {
1122                        bpm: semantic_tempo_bpm(time.bpm),
1123                        ramp_to_bpm: time.ramp_to_bpm.map(semantic_tempo_bpm),
1124                    },
1125                    frame,
1126                    source: None,
1127                    measure: Some(address.clone()),
1128                });
1129            }
1130            if part_index == 0
1131                && let Some(marker) = &measure.navigation
1132            {
1133                events.push(OfflineRenderSemanticFrameEvent {
1134                    kind: OfflineRenderSemanticEventKind::Navigation {
1135                        marker: marker.clone(),
1136                    },
1137                    frame,
1138                    source: None,
1139                    measure: Some(address.clone()),
1140                });
1141            }
1142            if let Some(instrument) = &measure.instrument_change {
1143                events.push(OfflineRenderSemanticFrameEvent {
1144                    kind: OfflineRenderSemanticEventKind::InstrumentChange {
1145                        instrument_id: instrument.id.clone(),
1146                        channel: instrument.midi_channel,
1147                        program: instrument.midi_program,
1148                        transpose_semitones: instrument.transpose_semitones,
1149                    },
1150                    frame,
1151                    source: None,
1152                    measure: Some(address.clone()),
1153                });
1154            }
1155            let start_tick = tick_starts[time.measure];
1156            let end_tick = start_tick.saturating_add((time.beats * 480.0).round() as u64);
1157            for control in &part.midi_control_changes {
1158                if control.tick < start_tick || control.tick >= end_tick {
1159                    continue;
1160                }
1161                let local_beats = (control.tick - start_tick) as f64 / 480.0;
1162                let secs = time.start_secs
1163                    + tempo_ramp_seconds(time.bpm, time.ramp_to_bpm, time.beats, local_beats);
1164                events.push(OfflineRenderSemanticFrameEvent {
1165                    kind: OfflineRenderSemanticEventKind::Controller {
1166                        channel: control.channel,
1167                        controller: control.controller,
1168                        value: control.value,
1169                    },
1170                    frame: ((secs - origin_secs).max(0.0) * f64::from(sample_rate_hz)).round()
1171                        as u64,
1172                    source: None,
1173                    measure: Some(address.clone()),
1174                });
1175            }
1176            for bend in &part.midi_pitch_bends {
1177                if bend.tick < start_tick || bend.tick >= end_tick {
1178                    continue;
1179                }
1180                let local_beats = (bend.tick - start_tick) as f64 / 480.0;
1181                let secs = time.start_secs
1182                    + tempo_ramp_seconds(time.bpm, time.ramp_to_bpm, time.beats, local_beats);
1183                events.push(OfflineRenderSemanticFrameEvent {
1184                    kind: OfflineRenderSemanticEventKind::PitchBend {
1185                        channel: bend.channel,
1186                        value: bend.value,
1187                    },
1188                    frame: ((secs - origin_secs).max(0.0) * f64::from(sample_rate_hz)).round()
1189                        as u64,
1190                    source: None,
1191                    measure: Some(address.clone()),
1192                });
1193            }
1194            for program in &part.midi_program_changes {
1195                if program.tick < start_tick || program.tick >= end_tick {
1196                    continue;
1197                }
1198                let local_beats = (program.tick - start_tick) as f64 / 480.0;
1199                let secs = time.start_secs
1200                    + tempo_ramp_seconds(time.bpm, time.ramp_to_bpm, time.beats, local_beats);
1201                events.push(OfflineRenderSemanticFrameEvent {
1202                    kind: OfflineRenderSemanticEventKind::ProgramChange {
1203                        channel: program.channel,
1204                        program: program.program,
1205                    },
1206                    frame: ((secs - origin_secs).max(0.0) * f64::from(sample_rate_hz)).round()
1207                        as u64,
1208                    source: None,
1209                    measure: Some(address.clone()),
1210                });
1211            }
1212            for aftertouch in &part.midi_aftertouch {
1213                if aftertouch.tick < start_tick || aftertouch.tick >= end_tick {
1214                    continue;
1215                }
1216                let local_beats = (aftertouch.tick - start_tick) as f64 / 480.0;
1217                let secs = time.start_secs
1218                    + tempo_ramp_seconds(time.bpm, time.ramp_to_bpm, time.beats, local_beats);
1219                events.push(OfflineRenderSemanticFrameEvent {
1220                    kind: OfflineRenderSemanticEventKind::Aftertouch {
1221                        channel: aftertouch.channel,
1222                        key: aftertouch.key,
1223                        value: aftertouch.value,
1224                    },
1225                    frame: ((secs - origin_secs).max(0.0) * f64::from(sample_rate_hz)).round()
1226                        as u64,
1227                    source: None,
1228                    measure: Some(address.clone()),
1229                });
1230            }
1231        }
1232    }
1233    events.sort_by_key(|event| event.frame);
1234}
1235
1236/// Timing tolerances for comparing a host/backend event trace with acorde's schedule.
1237#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1238pub struct PlaybackTimingTolerance {
1239    pub start_secs: f64,
1240    pub duration_secs: f64,
1241}
1242
1243impl Default for PlaybackTimingTolerance {
1244    fn default() -> Self {
1245        Self {
1246            start_secs: 0.005,
1247            duration_secs: 0.005,
1248        }
1249    }
1250}
1251
1252/// A typed difference in a host playback trace. Audio rendering is deliberately not compared.
1253#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1254pub enum PlaybackTimingMismatch {
1255    EventCount { expected: usize, actual: usize },
1256    EventIdentity { index: usize },
1257    StartTime { index: usize, error_secs: f64 },
1258    Duration { index: usize, error_secs: f64 },
1259}
1260
1261/// Deterministic report for a bounded playback timing comparison.
1262#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1263pub struct PlaybackTimingReport {
1264    pub contract_version: u16,
1265    pub expected_events: usize,
1266    pub actual_events: usize,
1267    pub matched_events: usize,
1268    pub max_start_error_secs: f64,
1269    pub max_duration_error_secs: f64,
1270    pub within_tolerance: bool,
1271    pub mismatches: Vec<PlaybackTimingMismatch>,
1272}
1273
1274/// Compare a host-provided event trace with the deterministic score schedule.
1275///
1276/// This contract covers event identity and timing only. Web Audio scheduling,
1277/// SoundFont decoding, device latency, and rendered PCM remain host/provider concerns.
1278pub fn compare_playback_timing(
1279    expected: &[PlaybackEvent],
1280    actual: &[PlaybackEvent],
1281    tolerance: &PlaybackTimingTolerance,
1282) -> Result<PlaybackTimingReport, crate::Error> {
1283    if !tolerance.start_secs.is_finite()
1284        || tolerance.start_secs < 0.0
1285        || !tolerance.duration_secs.is_finite()
1286        || tolerance.duration_secs < 0.0
1287    {
1288        return Err(crate::Error::InvalidPlaybackComparison);
1289    }
1290    if expected.len() > MAX_PLAYBACK_COMPARISON_EVENTS {
1291        return Err(crate::Error::PlaybackComparisonTooLarge(expected.len()));
1292    }
1293    if actual.len() > MAX_PLAYBACK_COMPARISON_EVENTS {
1294        return Err(crate::Error::PlaybackComparisonTooLarge(actual.len()));
1295    }
1296    let mut mismatches = Vec::new();
1297    if expected.len() != actual.len() {
1298        mismatches.push(PlaybackTimingMismatch::EventCount {
1299            expected: expected.len(),
1300            actual: actual.len(),
1301        });
1302    }
1303    let mut matched_events = 0;
1304    let mut max_start_error_secs: f64 = 0.0;
1305    let mut max_duration_error_secs: f64 = 0.0;
1306    for (index, (expected_event, actual_event)) in expected.iter().zip(actual).enumerate() {
1307        let source_identity_matches = match (&expected_event.source, &actual_event.source) {
1308            (Some(expected), Some(actual)) => expected == actual,
1309            _ => expected_event.address == actual_event.address,
1310        };
1311        let identity_matches = source_identity_matches
1312            && expected_event.pitch_midi_cents == actual_event.pitch_midi_cents
1313            && expected_event.velocity == actual_event.velocity
1314            && expected_event.part_index == actual_event.part_index
1315            && expected_event.channel == actual_event.channel
1316            && expected_event.program == actual_event.program
1317            && expected_event.instrument_id == actual_event.instrument_id
1318            && expected_event.pitch_bend_curve == actual_event.pitch_bend_curve
1319            && expected_event.post_note_pause_beats == actual_event.post_note_pause_beats
1320            && expected_event.articulations == actual_event.articulations
1321            && expected_event.chord_symbol == actual_event.chord_symbol
1322            && expected_event.guitar_technique == actual_event.guitar_technique
1323            && expected_event.is_metronome == actual_event.is_metronome;
1324        let start_error_secs = (expected_event.time_secs - actual_event.time_secs).abs();
1325        let duration_error_secs = (expected_event.duration_secs - actual_event.duration_secs).abs();
1326        if start_error_secs.is_finite() {
1327            max_start_error_secs = max_start_error_secs.max(start_error_secs);
1328        }
1329        if duration_error_secs.is_finite() {
1330            max_duration_error_secs = max_duration_error_secs.max(duration_error_secs);
1331        }
1332        let start_matches =
1333            start_error_secs.is_finite() && start_error_secs <= tolerance.start_secs;
1334        let duration_matches =
1335            duration_error_secs.is_finite() && duration_error_secs <= tolerance.duration_secs;
1336        if identity_matches && start_matches && duration_matches {
1337            matched_events += 1;
1338            continue;
1339        }
1340        if mismatches.len() < MAX_PLAYBACK_MISMATCHES {
1341            if !identity_matches {
1342                mismatches.push(PlaybackTimingMismatch::EventIdentity { index });
1343            }
1344            if !start_matches && mismatches.len() < MAX_PLAYBACK_MISMATCHES {
1345                mismatches.push(PlaybackTimingMismatch::StartTime {
1346                    index,
1347                    error_secs: start_error_secs,
1348                });
1349            }
1350            if !duration_matches && mismatches.len() < MAX_PLAYBACK_MISMATCHES {
1351                mismatches.push(PlaybackTimingMismatch::Duration {
1352                    index,
1353                    error_secs: duration_error_secs,
1354                });
1355            }
1356        }
1357    }
1358    Ok(PlaybackTimingReport {
1359        contract_version: PLAYBACK_COMPARISON_CONTRACT_VERSION,
1360        expected_events: expected.len(),
1361        actual_events: actual.len(),
1362        matched_events,
1363        max_start_error_secs,
1364        max_duration_error_secs,
1365        within_tolerance: mismatches.is_empty(),
1366        mismatches,
1367    })
1368}
1369
1370/// Version of the score-schedule timing corpus contract.
1371pub const PLAYBACK_TIMING_CORPUS_CONTRACT_VERSION: u16 = 1;
1372const MAX_PLAYBACK_TIMING_CORPUS_CASES: usize = 256;
1373
1374/// One score-backed timing case, independent from an audio synthesis backend.
1375#[derive(Debug, Clone, Serialize, Deserialize)]
1376pub struct PlaybackTimingCase {
1377    pub id: String,
1378    pub score: Score,
1379    #[serde(default)]
1380    pub options: PlaybackOptions,
1381    pub expected_events: Vec<PlaybackEvent>,
1382    #[serde(default)]
1383    pub tolerance: PlaybackTimingTolerance,
1384}
1385
1386/// Result for one [`PlaybackTimingCase`].
1387#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1388pub struct PlaybackTimingCaseReport {
1389    pub id: String,
1390    pub report: PlaybackTimingReport,
1391}
1392
1393/// Deterministic aggregate result for a score-schedule timing corpus.
1394#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1395pub struct PlaybackTimingCorpusReport {
1396    pub contract_version: u16,
1397    pub total_cases: usize,
1398    pub passed_cases: usize,
1399    pub cases: Vec<PlaybackTimingCaseReport>,
1400}
1401
1402/// Compare score-generated schedules against a bounded corpus of expected event traces.
1403///
1404/// The corpus verifies notation-to-event semantics only. It makes no assertion about synthesized
1405/// PCM, codec output, browser scheduling, or real-time device latency.
1406pub fn evaluate_playback_timing_corpus(
1407    cases: &[PlaybackTimingCase],
1408) -> Result<PlaybackTimingCorpusReport, crate::Error> {
1409    if cases.is_empty() || cases.len() > MAX_PLAYBACK_TIMING_CORPUS_CASES {
1410        return Err(crate::Error::InvalidPlaybackTimingCorpus);
1411    }
1412    let mut ids = BTreeSet::new();
1413    let mut reports = Vec::with_capacity(cases.len());
1414    let mut passed_cases = 0;
1415    for case in cases {
1416        if !valid_routing_id(&case.id) || !ids.insert(case.id.clone()) {
1417            return Err(crate::Error::InvalidPlaybackTimingCorpus);
1418        }
1419        let actual = to_playback_events_bounded(&case.score, &case.options)?;
1420        let report = compare_playback_timing(&case.expected_events, &actual, &case.tolerance)?;
1421        if report.within_tolerance {
1422            passed_cases += 1;
1423        }
1424        reports.push(PlaybackTimingCaseReport {
1425            id: case.id.clone(),
1426            report,
1427        });
1428    }
1429    Ok(PlaybackTimingCorpusReport {
1430        contract_version: PLAYBACK_TIMING_CORPUS_CONTRACT_VERSION,
1431        total_cases: cases.len(),
1432        passed_cases,
1433        cases: reports,
1434    })
1435}
1436
1437/// Version of the host-neutral tablature performance projection contract.
1438pub const TAB_PERFORMANCE_CONTRACT_VERSION: u16 = 4;
1439
1440#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1441pub struct TablaturePerformanceEvent {
1442    pub playback: PlaybackEvent,
1443    pub string: u8,
1444    pub fret: u8,
1445    /// Authored guitar technique for the host playback adapter, when present.
1446    #[serde(default)]
1447    pub technique: Option<GuitarTechnique>,
1448    /// Authored bend alteration in cents, when the technique is `Bend`.
1449    #[serde(default)]
1450    pub bend_alter_cents: Option<i16>,
1451    /// Normalized bend/hold/release curve for a bend-capable host. Positions are per-mille of
1452    /// this event's sounding duration and values are cents relative to the written pitch.
1453    #[serde(default)]
1454    pub bend_curve: Vec<GuitarBendPoint>,
1455    pub expected_pitch_midi_cents: i32,
1456    pub pitch_error_cents: i32,
1457}
1458
1459#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1460pub enum TablaturePerformanceDiagnostic {
1461    NoTablatureStaff {
1462        address: String,
1463    },
1464    MissingPosition {
1465        address: String,
1466        pitch_index: usize,
1467    },
1468    StringOutOfRange {
1469        address: String,
1470        string: u8,
1471        lines: u8,
1472    },
1473    TuningUnavailable {
1474        address: String,
1475        string: u8,
1476    },
1477    PitchMismatch {
1478        address: String,
1479        pitch_index: usize,
1480        error_cents: i32,
1481    },
1482}
1483
1484#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1485pub struct TablaturePerformanceReport {
1486    pub contract_version: u16,
1487    pub events: Vec<TablaturePerformanceEvent>,
1488    pub diagnostics: Vec<TablaturePerformanceDiagnostic>,
1489}
1490
1491/// Version of the score-model tablature round-trip diagnostic contract.
1492pub const TAB_ROUND_TRIP_CONTRACT_VERSION: u16 = 1;
1493
1494#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1495pub struct TablatureRoundTripReport {
1496    pub contract_version: u16,
1497    pub checked_notes: usize,
1498    pub positioned_notes: usize,
1499    pub equivalent: bool,
1500    pub diagnostics: Vec<TablatureRoundTripDiagnostic>,
1501}
1502
1503#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1504pub enum TablatureRoundTripDiagnostic {
1505    StructureMismatch {
1506        address: String,
1507    },
1508    TablatureConfigMismatch {
1509        address: String,
1510    },
1511    PositionMismatch {
1512        address: String,
1513        pitch_index: usize,
1514        expected: Option<TabPosition>,
1515        actual: Option<TabPosition>,
1516    },
1517}
1518
1519/// Verify that authored tablature survives the canonical score JSON round-trip.
1520///
1521/// This checks score-model persistence only. It does not claim MusicXML/MSCX or external
1522/// application equivalence; those format and host comparisons remain separate gates.
1523pub fn tablature_round_trip_report(
1524    score: &Score,
1525) -> Result<TablatureRoundTripReport, crate::Error> {
1526    let encoded = serde_json::to_string(score)
1527        .map_err(|error| crate::Error::TabRoundTripSerialization(error.to_string()))?;
1528    let restored: Score = serde_json::from_str(&encoded)
1529        .map_err(|error| crate::Error::TabRoundTripSerialization(error.to_string()))?;
1530    let mut checked_notes = 0;
1531    let mut positioned_notes = 0;
1532    let mut diagnostics = Vec::new();
1533    for (part_index, part) in score.parts.iter().enumerate() {
1534        let Some(restored_part) = restored.parts.get(part_index) else {
1535            diagnostics.push(TablatureRoundTripDiagnostic::StructureMismatch {
1536                address: format!("{part_index}"),
1537            });
1538            continue;
1539        };
1540        for (staff_index, staff) in part.staves.iter().enumerate() {
1541            let address = format!("{part_index}:{staff_index}");
1542            let Some(restored_staff) = restored_part.staves.get(staff_index) else {
1543                diagnostics.push(TablatureRoundTripDiagnostic::StructureMismatch { address });
1544                continue;
1545            };
1546            if staff.tablature != restored_staff.tablature {
1547                diagnostics.push(TablatureRoundTripDiagnostic::TablatureConfigMismatch {
1548                    address: address.clone(),
1549                });
1550            }
1551            for (measure_index, measure) in staff.measures.iter().enumerate() {
1552                let Some(restored_measure) = restored_staff.measures.get(measure_index) else {
1553                    diagnostics.push(TablatureRoundTripDiagnostic::StructureMismatch {
1554                        address: format!("{address}:{measure_index}"),
1555                    });
1556                    continue;
1557                };
1558                for (voice_index, voice) in measure.voices.iter().enumerate() {
1559                    let Some(restored_voice) = restored_measure.voices.get(voice_index) else {
1560                        diagnostics.push(TablatureRoundTripDiagnostic::StructureMismatch {
1561                            address: format!("{address}:{measure_index}:{voice_index}"),
1562                        });
1563                        continue;
1564                    };
1565                    for (note_index, note) in voice.iter().enumerate() {
1566                        checked_notes += 1;
1567                        if !note.tab_positions.is_empty() || note.tab_position.is_some() {
1568                            positioned_notes += 1;
1569                        }
1570                        let note_address =
1571                            format!("{address}:{measure_index}:{voice_index}:{note_index}");
1572                        let Some(restored_note) = restored_voice.get(note_index) else {
1573                            diagnostics.push(TablatureRoundTripDiagnostic::StructureMismatch {
1574                                address: note_address,
1575                            });
1576                            continue;
1577                        };
1578                        let pitch_count = note.pitches.len().max(note.tab_positions.len()).max(1);
1579                        for pitch_index in 0..pitch_count {
1580                            let expected = note
1581                                .tab_positions
1582                                .get(pitch_index)
1583                                .cloned()
1584                                .or_else(|| note.tab_position.clone());
1585                            let actual = restored_note
1586                                .tab_positions
1587                                .get(pitch_index)
1588                                .cloned()
1589                                .or_else(|| restored_note.tab_position.clone());
1590                            if expected != actual {
1591                                diagnostics.push(TablatureRoundTripDiagnostic::PositionMismatch {
1592                                    address: note_address.clone(),
1593                                    pitch_index,
1594                                    expected,
1595                                    actual,
1596                                });
1597                            }
1598                        }
1599                    }
1600                }
1601            }
1602        }
1603    }
1604    Ok(TablatureRoundTripReport {
1605        contract_version: TAB_ROUND_TRIP_CONTRACT_VERSION,
1606        checked_notes,
1607        positioned_notes,
1608        equivalent: diagnostics.is_empty(),
1609        diagnostics,
1610    })
1611}
1612
1613/// Project score playback events onto authored tablature positions.
1614///
1615/// This operation never invents a string or fret. Callers may run
1616/// [`assign_tablature_positions`](crate::assign_tablature_positions) before this
1617/// projection when automatic positions are desired.
1618pub fn project_tablature_performance(
1619    score: &Score,
1620    options: &PlaybackOptions,
1621) -> Result<TablaturePerformanceReport, crate::Error> {
1622    let playback = to_playback_events(score, options);
1623    if playback.len() > MAX_TAB_PERFORMANCE_EVENTS {
1624        return Err(crate::Error::TabPerformanceTooLarge(playback.len()));
1625    }
1626    let mut events = Vec::new();
1627    let mut diagnostics = Vec::new();
1628    for event in playback {
1629        let Some(address) = event.address.as_deref() else {
1630            continue;
1631        };
1632        let Some((part_index, staff_index, measure_index, voice_index, note_index)) =
1633            parse_playback_address(address)
1634        else {
1635            continue;
1636        };
1637        let Some(staff) = score
1638            .parts
1639            .get(part_index)
1640            .and_then(|part| part.staves.get(staff_index))
1641        else {
1642            continue;
1643        };
1644        let Some(note) = staff
1645            .measures
1646            .get(measure_index)
1647            .and_then(|measure| measure.voices.get(voice_index))
1648            .and_then(|voice| voice.get(note_index))
1649        else {
1650            continue;
1651        };
1652        let Some(tab) = staff.tablature_at(measure_index) else {
1653            push_tab_diagnostic(
1654                &mut diagnostics,
1655                TablaturePerformanceDiagnostic::NoTablatureStaff {
1656                    address: address.into(),
1657                },
1658            );
1659            continue;
1660        };
1661        let transpose_cents = if event.channel == 9 {
1662            0
1663        } else {
1664            i32::from(staff.transpose_semitones) * 100
1665        };
1666        let written_pitch_cents = event.pitch_midi_cents - transpose_cents;
1667        let pitch_index = note
1668            .pitches
1669            .iter()
1670            .position(|pitch| pitch.to_midi_cents() == written_pitch_cents)
1671            .unwrap_or(0);
1672        let position = note
1673            .tab_positions
1674            .get(pitch_index)
1675            .or(note.tab_position.as_ref());
1676        let Some(position) = position else {
1677            push_tab_diagnostic(
1678                &mut diagnostics,
1679                TablaturePerformanceDiagnostic::MissingPosition {
1680                    address: address.into(),
1681                    pitch_index,
1682                },
1683            );
1684            continue;
1685        };
1686        if position.string == 0 || position.string > tab.lines {
1687            push_tab_diagnostic(
1688                &mut diagnostics,
1689                TablaturePerformanceDiagnostic::StringOutOfRange {
1690                    address: address.into(),
1691                    string: position.string,
1692                    lines: tab.lines,
1693                },
1694            );
1695            continue;
1696        }
1697        let Some(tuning) = tab.tuning_midi.get(usize::from(position.string - 1)) else {
1698            push_tab_diagnostic(
1699                &mut diagnostics,
1700                TablaturePerformanceDiagnostic::TuningUnavailable {
1701                    address: address.into(),
1702                    string: position.string,
1703                },
1704            );
1705            continue;
1706        };
1707        let expected_pitch_midi_cents =
1708            tuning.saturating_add(i16::from(position.fret) + i16::from(tab.capo)) as i32 * 100;
1709        let pitch_error_cents = event.pitch_midi_cents - expected_pitch_midi_cents;
1710        if pitch_error_cents != 0 {
1711            push_tab_diagnostic(
1712                &mut diagnostics,
1713                TablaturePerformanceDiagnostic::PitchMismatch {
1714                    address: address.into(),
1715                    pitch_index,
1716                    error_cents: pitch_error_cents,
1717                },
1718            );
1719        }
1720        events.push(TablaturePerformanceEvent {
1721            playback: event,
1722            string: position.string,
1723            fret: position.fret,
1724            technique: note.guitar_technique.clone(),
1725            bend_alter_cents: note.guitar_bend_alter_cents,
1726            bend_curve: note.guitar_bend_curve.clone(),
1727            expected_pitch_midi_cents,
1728            pitch_error_cents,
1729        });
1730    }
1731    Ok(TablaturePerformanceReport {
1732        contract_version: TAB_PERFORMANCE_CONTRACT_VERSION,
1733        events,
1734        diagnostics,
1735    })
1736}
1737
1738fn parse_playback_address(address: &str) -> Option<(usize, usize, usize, usize, usize)> {
1739    let mut fields = address.split(':').map(|field| field.parse::<usize>().ok());
1740    Some((
1741        fields.next()??,
1742        fields.next()??,
1743        fields.next()??,
1744        fields.next()??,
1745        fields.next()??,
1746    ))
1747}
1748
1749fn push_tab_diagnostic(
1750    diagnostics: &mut Vec<TablaturePerformanceDiagnostic>,
1751    diagnostic: TablaturePerformanceDiagnostic,
1752) {
1753    if diagnostics.len() < MAX_TAB_PERFORMANCE_DIAGNOSTICS {
1754        diagnostics.push(diagnostic);
1755    }
1756}
1757
1758/// Dynamic levels of one staff along a played measure order, so a marking carries on until
1759/// the next one as in engraved music: a level (p, f, …) holds, an accent (sf, sfz, fz, rfz,
1760/// sffz) lifts only its own moment, and a compound (fp, sfp, pf, …) attacks at the first
1761/// level and continues at the second. A hairpin ramps the level across its notes towards the
1762/// marking that follows it (or two dynamic steps up or down when none follows at once) and
1763/// leaves the level there. Before the first marking notes play at velocity 64.
1764#[derive(Debug, Clone, Default)]
1765pub struct DynamicTimeline {
1766    /// Start of each position of the order, in beats from the start.
1767    position_beats: Vec<f64>,
1768    /// (time, attack, level after), in time order.
1769    changes: Vec<(f64, u8, u8)>,
1770    /// Hairpins as (start, end, from velocity, to velocity).
1771    ramps: Vec<(f64, f64, u8, u8)>,
1772}
1773
1774/// One dynamic event on a staff timeline: a written marking or the level a hairpin reaches.
1775#[derive(Clone, Copy)]
1776enum DynamicMark {
1777    Marking(crate::Dynamic),
1778    Level(u8),
1779}
1780
1781impl DynamicTimeline {
1782    /// Velocity of a note before any dynamic marking.
1783    pub const DEFAULT_VELOCITY: u8 = 64;
1784    /// How far a hairpin moves the level when no marking follows it (two dynamic steps).
1785    const HAIRPIN_STEP: i16 = 24;
1786
1787    /// Collect the markings and hairpins of every voice of `staff` along `order` (measure
1788    /// indices as played, repeats expanded). Grace and cue notes take no time.
1789    pub fn for_staff(staff: &crate::Staff, order: &[usize]) -> Self {
1790        let mut position_beats = Vec::with_capacity(order.len());
1791        let mut marks: Vec<(f64, DynamicMark)> = Vec::new();
1792        // (start, end, crescendo)
1793        let mut hairpins: Vec<(f64, f64, bool)> = Vec::new();
1794        let mut open_hairpins: [Option<(f64, bool)>; 4] = [None; 4];
1795        let mut elapsed = 0.0;
1796        for &measure_index in order {
1797            position_beats.push(elapsed);
1798            let Some(measure) = staff.measures.get(measure_index) else {
1799                continue;
1800            };
1801            let mut length: f64 = 0.0;
1802            for (voice_index, voice) in measure.voices.iter().enumerate() {
1803                let mut beats = 0.0;
1804                for note in voice {
1805                    let onset = elapsed + beats;
1806                    if let Some(dynamic) = note.dynamic
1807                        && !note.is_rest
1808                    {
1809                        marks.push((onset, DynamicMark::Marking(dynamic)));
1810                    }
1811                    let end = onset + note.beats();
1812                    // A note may end one hairpin and start the next.
1813                    let ends_earlier = note.hairpin_end && open_hairpins[voice_index].is_some();
1814                    if ends_earlier && let Some((start, up)) = open_hairpins[voice_index].take() {
1815                        hairpins.push((start, end, up));
1816                    }
1817                    if let Some(kind) = note.hairpin_start {
1818                        open_hairpins[voice_index] =
1819                            Some((onset, kind == crate::HairpinKind::Crescendo));
1820                    }
1821                    if note.hairpin_end
1822                        && !ends_earlier
1823                        && let Some((start, up)) = open_hairpins[voice_index].take()
1824                    {
1825                        hairpins.push((start, end, up));
1826                    }
1827                    beats += note.beats();
1828                }
1829                length = length.max(beats);
1830            }
1831            elapsed += length;
1832        }
1833        marks.sort_by(|a, b| a.0.total_cmp(&b.0));
1834        let written = Self::resolve(&marks);
1835        let mut ramps = Vec::new();
1836        for (start, end, up) in hairpins {
1837            if end <= start {
1838                continue;
1839            }
1840            let from = Self::level_at(&written, start);
1841            // The marking the hairpin leads to, if one comes within a beat of its end.
1842            let next = written
1843                .iter()
1844                .find(|&&(time, _, _)| time >= end - 1e-9)
1845                .filter(|&&(time, _, _)| time <= end + 1.0)
1846                .map(|&(_, attack, _)| attack)
1847                .filter(|&attack| if up { attack > from } else { attack < from });
1848            let to = next.unwrap_or_else(|| {
1849                let step = if up {
1850                    Self::HAIRPIN_STEP
1851                } else {
1852                    -Self::HAIRPIN_STEP
1853                };
1854                (i16::from(from) + step).clamp(1, 127) as u8
1855            });
1856            if next.is_none() {
1857                marks.push((end, DynamicMark::Level(to)));
1858            }
1859            ramps.push((start, end, from, to));
1860        }
1861        marks.sort_by(|a, b| a.0.total_cmp(&b.0));
1862        Self {
1863            position_beats,
1864            changes: Self::resolve(&marks),
1865            ramps,
1866        }
1867    }
1868
1869    fn resolve(marks: &[(f64, DynamicMark)]) -> Vec<(f64, u8, u8)> {
1870        let mut level = Self::DEFAULT_VELOCITY;
1871        marks
1872            .iter()
1873            .map(|&(time, mark)| match mark {
1874                DynamicMark::Marking(dynamic) => {
1875                    if let Some(next) = dynamic.sustained_level() {
1876                        level = next.to_velocity();
1877                    }
1878                    (time, dynamic.to_velocity(), level)
1879                }
1880                DynamicMark::Level(velocity) => {
1881                    level = velocity;
1882                    (time, velocity, level)
1883                }
1884            })
1885            .collect()
1886    }
1887
1888    fn level_at(changes: &[(f64, u8, u8)], time: f64) -> u8 {
1889        let before = changes.partition_point(|&(t, _, _)| t <= time + 1e-9);
1890        before
1891            .checked_sub(1)
1892            .map_or(Self::DEFAULT_VELOCITY, |index| changes[index].2)
1893    }
1894
1895    /// Velocity of a note at `beats` into the measure at `position` of the order: its own
1896    /// marking's attack, the attack of a marking at the same moment in another voice, the
1897    /// point a hairpin has reached, or the level in force.
1898    pub fn velocity(&self, position: usize, beats: f64, own: Option<crate::Dynamic>) -> u8 {
1899        if let Some(dynamic) = own {
1900            return dynamic.to_velocity();
1901        }
1902        let time = self.position_beats.get(position).copied().unwrap_or(0.0) + beats;
1903        let before = self.changes.partition_point(|&(t, _, _)| t <= time + 1e-9);
1904        let current = before.checked_sub(1).map(|index| self.changes[index]);
1905        if let Some((t, attack, _)) = current
1906            && (t - time).abs() <= 1e-9
1907        {
1908            return attack;
1909        }
1910        if let Some(&(start, end, from, to)) = self
1911            .ramps
1912            .iter()
1913            .rev()
1914            .find(|&&(start, end, _, _)| start <= time + 1e-9 && time < end - 1e-9)
1915        {
1916            let fraction = ((time - start) / (end - start)).clamp(0.0, 1.0);
1917            let value = f64::from(from) + (f64::from(to) - f64::from(from)) * fraction;
1918            return value.round().clamp(1.0, 127.0) as u8;
1919        }
1920        current.map_or(Self::DEFAULT_VELOCITY, |(_, _, level)| level)
1921    }
1922}
1923
1924/// Convert a [`Score`] into a flat, time-ordered list of [`PlaybackEvent`]s.
1925///
1926/// All parts, staves, and voices are included unless excluded via [`PlaybackOptions`].
1927/// Repeat sections and volta brackets are expanded using [`measure_sequence`].
1928/// Events are sorted by `time_beats`.
1929pub fn to_playback_events(score: &Score, options: &PlaybackOptions) -> Vec<PlaybackEvent> {
1930    // A pedal held only as a typed spanner still presses the pedal on its first note.
1931    let materialized = score.with_legacy_spanner_flags();
1932    let score: &Score = &materialized;
1933    let bpm = initial_tempo_bpm(score, options);
1934    let tempo_marks = score_tempo_marks(score);
1935    let measure_lengths: Vec<f64> = (0..tempo_marks.len())
1936        .map(|index| score.playback_measure_beats(index))
1937        .collect();
1938    let swing_ratio = options
1939        .swing
1940        .filter(|ratio| ratio.is_finite() && *ratio > 0.5 && *ratio < 1.0);
1941    let full_seq = measure_sequence(score);
1942    let seq: Vec<usize> = if let Some((lo, hi)) = options.loop_region {
1943        full_seq
1944            .into_iter()
1945            .filter(|&idx| idx >= lo && idx <= hi)
1946            .collect()
1947    } else {
1948        full_seq
1949    };
1950    let mut events: Vec<PlaybackEvent> = Vec::new();
1951
1952    for (part_index, part) in score.parts.iter().enumerate() {
1953        if options.muted_parts.contains(&part_index) {
1954            continue;
1955        }
1956        for (staff_index, staff) in part.staves.iter().enumerate() {
1957            let dynamics = DynamicTimeline::for_staff(staff, &seq);
1958            for voice_idx in 0..4usize {
1959                let mut time_beats = 0.0f64;
1960                let mut time_secs_cursor = 0.0f64;
1961                let mut current_bpm = bpm;
1962                for (seq_position, &idx) in seq.iter().enumerate() {
1963                    let measure = match staff.measures.get(idx) {
1964                        Some(m) => m,
1965                        None => continue,
1966                    };
1967                    let instrument = measure
1968                        .instrument_change
1969                        .as_ref()
1970                        .or(part.instrument.as_ref());
1971                    let channel = instrument.map_or(part.midi_channel, |value| value.midi_channel);
1972                    let program = instrument.map_or(part.midi_program, |value| value.midi_program);
1973                    let instrument_id = instrument.map(|value| value.id.clone());
1974                    let mark = tempo_marks.get(idx).copied().unwrap_or_default();
1975                    if let Some(b) = mark.bpm.and_then(|tempo| written_tempo_bpm(options, tempo)) {
1976                        current_bpm = b;
1977                    }
1978                    let measure_beats = measure_lengths[idx];
1979                    let grid_offset_beats = if idx == 0
1980                        && measure_beats
1981                            < staff
1982                                .meter_at(idx, &score.settings.time_signature)
1983                                .total_beats()
1984                    {
1985                        (staff
1986                            .meter_at(idx, &score.settings.time_signature)
1987                            .total_beats()
1988                            - measure_beats)
1989                            .max(0.0)
1990                    } else {
1991                        0.0
1992                    };
1993                    let ramp_end_bpm = written_tempo_ramp_bpm(options, mark.ramp_to_bpm);
1994                    let measure_start_beats = time_beats;
1995                    let measure_start_secs = time_secs_cursor;
1996                    let mut local_beats = 0.0f64;
1997                    // Unswung position, which dynamic markings are keyed by.
1998                    let mut written_beats = 0.0f64;
1999                    let mut swing_second = false;
2000                    for (note_index, note) in measure.voices[voice_idx].iter().enumerate() {
2001                        if note.is_grace || note.is_cue {
2002                            continue;
2003                        }
2004                        let onset_written_beats = written_beats;
2005                        written_beats += note.beats();
2006                        let dur = if let Some(ratio) = swing_ratio {
2007                            if swing_second {
2008                                swing_second = false;
2009                                (1.0 - ratio) * note.beats() * 2.0
2010                            } else if starts_swing_pair(
2011                                &measure.voices[voice_idx],
2012                                note_index,
2013                                onset_written_beats,
2014                                grid_offset_beats,
2015                                measure_beats,
2016                                &options.swing_unit,
2017                            ) {
2018                                swing_second = true;
2019                                ratio * note.beats() * 2.0
2020                            } else {
2021                                note.beats()
2022                            }
2023                        } else {
2024                            note.beats()
2025                        };
2026                        if !note.is_rest {
2027                            let mut velocity =
2028                                dynamics.velocity(seq_position, onset_written_beats, note.dynamic);
2029                            let mut sounding_dur = dur;
2030                            for art in &note.articulations {
2031                                match art {
2032                                    Articulation::Staccato | Articulation::Staccatissimo => {
2033                                        sounding_dur *= 0.5;
2034                                    }
2035                                    Articulation::Accent | Articulation::Marcato => {
2036                                        velocity = velocity.saturating_add(20).min(127);
2037                                    }
2038                                    Articulation::Fermata => {
2039                                        sounding_dur *= options.fermata_multiplier;
2040                                    }
2041                                    _ => {}
2042                                }
2043                            }
2044                            let pedal = note.pedal_start;
2045                            let fermata_hold_beats = if options.fermata_hold_beats.is_finite() {
2046                                options.fermata_hold_beats.max(0.0)
2047                            } else {
2048                                0.0
2049                            };
2050                            let post_note_pause_beats =
2051                                note.articulations
2052                                    .iter()
2053                                    .fold(0.0f64, |pause, articulation| {
2054                                        pause.max(match articulation {
2055                                            Articulation::BreathMark => 0.25,
2056                                            Articulation::Caesura => 0.5,
2057                                            Articulation::Fermata => fermata_hold_beats,
2058                                            _ => 0.0,
2059                                        })
2060                                    });
2061                            let transpose = if channel == 9 {
2062                                0i8
2063                            } else {
2064                                staff.transpose_semitones.saturating_add(
2065                                    instrument.map_or(0, |value| value.transpose_semitones),
2066                                )
2067                            };
2068                            for (pitch_index, pitch) in note.pitches.iter().enumerate() {
2069                                // An unpitched note sounds its instrument's percussion key.
2070                                let percussion = part.percussion_key(note, pitch_index);
2071                                let transpose = if percussion.is_some() { 0 } else { transpose };
2072                                let midi = percussion.map_or_else(
2073                                    || (pitch.to_midi() + transpose as i16).clamp(0, 127) as u8,
2074                                    |key| key.min(127),
2075                                );
2076                                events.push(PlaybackEvent {
2077                                    address: Some(format!(
2078                                        "{part_index}:{staff_index}:{idx}:{voice_idx}:{note_index}"
2079                                    )),
2080                                    source: Some(NoteAddr {
2081                                        part: part_index,
2082                                        staff: staff_index,
2083                                        measure: idx,
2084                                        voice: voice_idx,
2085                                        note: note_index,
2086                                    }),
2087                                    source_voice_number: measure.source_voice_numbers[voice_idx],
2088                                    time_beats: measure_start_beats + local_beats,
2089                                    time_secs: measure_start_secs
2090                                        + tempo_ramp_seconds(
2091                                            current_bpm,
2092                                            ramp_end_bpm,
2093                                            measure_beats,
2094                                            local_beats,
2095                                        ),
2096                                    pitch_midi: midi,
2097                                    pitch_midi_cents: if percussion.is_some() {
2098                                        i32::from(midi) * 100
2099                                    } else {
2100                                        pitch.to_midi_cents() + transpose as i32 * 100
2101                                    },
2102                                    pitch_bend_curve: note.guitar_bend_curve.clone(),
2103                                    post_note_pause_beats,
2104                                    articulations: note.articulations.clone(),
2105                                    chord_symbol: note.chord_symbol.clone(),
2106                                    guitar_technique: note.guitar_technique.clone(),
2107                                    velocity,
2108                                    duration_beats: sounding_dur,
2109                                    duration_secs: tempo_ramp_seconds(
2110                                        current_bpm,
2111                                        ramp_end_bpm,
2112                                        measure_beats,
2113                                        local_beats + sounding_dur,
2114                                    ) - tempo_ramp_seconds(
2115                                        current_bpm,
2116                                        ramp_end_bpm,
2117                                        measure_beats,
2118                                        local_beats,
2119                                    ),
2120                                    pedal,
2121                                    part_index,
2122                                    channel,
2123                                    program,
2124                                    instrument_id: instrument_id.clone(),
2125                                    is_metronome: false,
2126                                });
2127                            }
2128                        }
2129                        local_beats += dur;
2130                    }
2131                    // A voice may omit rests, but the next measure still starts
2132                    // at the notated bar boundary. This also keeps sparse voices
2133                    // aligned with compute_playback_position and other voices.
2134                    time_beats = measure_start_beats + measure_beats;
2135                    time_secs_cursor = measure_start_secs
2136                        + tempo_ramp_seconds(
2137                            current_bpm,
2138                            ramp_end_bpm,
2139                            measure_beats,
2140                            measure_beats,
2141                        );
2142                    if let Some(end_bpm) = ramp_end_bpm {
2143                        current_bpm = end_bpm;
2144                    }
2145                }
2146            }
2147        }
2148    }
2149
2150    if let Some(ref metro) = options.metronome {
2151        let mut cursor_secs = 0.0f64;
2152        let mut cursor_beats = 0.0f64;
2153        let mut metro_bpm = bpm;
2154        for &idx in &seq {
2155            let first_staff = score.parts.first().and_then(|p| p.staves.first());
2156            let mark = tempo_marks.get(idx).copied().unwrap_or_default();
2157            if let Some(t) = mark.bpm.and_then(|tempo| written_tempo_bpm(options, tempo)) {
2158                metro_bpm = t;
2159            }
2160            let ts = first_staff.map_or(&score.settings.time_signature, |s| {
2161                s.meter_at(idx, &score.settings.time_signature)
2162            });
2163            let measure_beats = measure_lengths[idx];
2164            let ramp_end_bpm = written_tempo_ramp_bpm(options, mark.ramp_to_bpm);
2165            let beat_unit = ts.beat_unit_beats();
2166            let num_beats = (measure_beats / beat_unit).round() as u32;
2167            for b in 0..num_beats {
2168                let is_accent = b == 0;
2169                let beat_offset_beats = b as f64 * beat_unit;
2170                let beat_offset_secs =
2171                    tempo_ramp_seconds(metro_bpm, ramp_end_bpm, measure_beats, beat_offset_beats);
2172                events.push(PlaybackEvent {
2173                    address: None,
2174                    source: None,
2175                    source_voice_number: None,
2176                    time_beats: cursor_beats + b as f64 * beat_unit,
2177                    time_secs: cursor_secs + beat_offset_secs,
2178                    pitch_midi: if is_accent {
2179                        metro.accent_pitch
2180                    } else {
2181                        metro.beat_pitch
2182                    },
2183                    pitch_midi_cents: i32::from(if is_accent {
2184                        metro.accent_pitch
2185                    } else {
2186                        metro.beat_pitch
2187                    }) * 100,
2188                    pitch_bend_curve: Vec::new(),
2189                    post_note_pause_beats: 0.0,
2190                    articulations: Vec::new(),
2191                    chord_symbol: None,
2192                    guitar_technique: None,
2193                    velocity: if is_accent {
2194                        metro.accent_velocity
2195                    } else {
2196                        metro.beat_velocity
2197                    },
2198                    duration_beats: beat_unit * 0.1,
2199                    duration_secs: tempo_ramp_seconds(
2200                        metro_bpm,
2201                        ramp_end_bpm,
2202                        measure_beats,
2203                        beat_offset_beats + beat_unit * 0.1,
2204                    ) - beat_offset_secs,
2205                    pedal: false,
2206                    part_index: usize::MAX,
2207                    channel: metro.channel,
2208                    program: 0,
2209                    instrument_id: None,
2210                    is_metronome: true,
2211                });
2212            }
2213            cursor_secs +=
2214                tempo_ramp_seconds(metro_bpm, ramp_end_bpm, measure_beats, measure_beats);
2215            cursor_beats += measure_beats;
2216            if let Some(end_bpm) = ramp_end_bpm {
2217                metro_bpm = end_bpm;
2218            }
2219        }
2220    }
2221
2222    // Parts, staves and voices are projected separately. Sort before resolving ties so a
2223    // continuation moved to another staff or voice follows its start on the shared clock.
2224    events.sort_by(|a, b| {
2225        a.time_beats
2226            .partial_cmp(&b.time_beats)
2227            .unwrap_or(std::cmp::Ordering::Equal)
2228    });
2229    events = merge_tied_events(score, options, events);
2230    events = apply_realization_profile(score, events, options.realization_profile);
2231    events.sort_by(|a, b| {
2232        a.time_beats
2233            .partial_cmp(&b.time_beats)
2234            .unwrap_or(std::cmp::Ordering::Equal)
2235    });
2236    events
2237}
2238
2239const ORNAMENT_ATTACK_COUNT: usize = 4;
2240const ARPEGGIO_MAX_SPREAD_BEATS: f64 = 0.18;
2241
2242fn apply_realization_profile(
2243    score: &Score,
2244    mut events: Vec<PlaybackEvent>,
2245    profile: PlaybackRealizationProfile,
2246) -> Vec<PlaybackEvent> {
2247    if profile == PlaybackRealizationProfile::Authored {
2248        return events;
2249    }
2250
2251    let mut chord_groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();
2252    for (index, event) in events.iter().enumerate() {
2253        if !event.is_metronome
2254            && let Some(address) = &event.address
2255        {
2256            chord_groups.entry(address.clone()).or_default().push(index);
2257        }
2258    }
2259    for indices in chord_groups.into_values() {
2260        let Some(source) = events[indices[0]].source.as_ref() else {
2261            continue;
2262        };
2263        let Some(direction) = score
2264            .parts
2265            .get(source.part)
2266            .and_then(|part| part.staves.get(source.staff))
2267            .and_then(|staff| staff.measures.get(source.measure))
2268            .and_then(|measure| measure.voices.get(source.voice))
2269            .and_then(|voice| voice.get(source.note))
2270            .and_then(|note| note.arpeggiate)
2271        else {
2272            continue;
2273        };
2274        if indices.len() < 2 {
2275            continue;
2276        }
2277        let mut ordered = indices;
2278        ordered.sort_by_key(|&index| events[index].pitch_midi_cents);
2279        if !direction {
2280            ordered.reverse();
2281        }
2282        let max_spread = events[ordered[0]]
2283            .duration_beats
2284            .max(0.0)
2285            .mul_add(0.5, 0.0)
2286            .min(ARPEGGIO_MAX_SPREAD_BEATS);
2287        let step = max_spread / (ordered.len() - 1) as f64;
2288        for (ordinal, index) in ordered.into_iter().enumerate() {
2289            shift_event_time(&mut events[index], step * ordinal as f64);
2290        }
2291    }
2292
2293    let mut realized = Vec::with_capacity(events.len());
2294    for event in events {
2295        let offsets = ornament_offsets(&event.articulations);
2296        if offsets.is_empty() || event.is_metronome || event.duration_beats <= 0.0 {
2297            realized.push(event);
2298            continue;
2299        }
2300        let attack_beats = event.duration_beats / ORNAMENT_ATTACK_COUNT as f64;
2301        let attack_secs = event.duration_secs / ORNAMENT_ATTACK_COUNT as f64;
2302        for (ordinal, semitones) in offsets.into_iter().enumerate() {
2303            let mut attack = event.clone();
2304            let displacement = i32::from(semitones) * 100;
2305            attack.pitch_midi_cents = (attack.pitch_midi_cents + displacement).clamp(0, 12_700);
2306            attack.pitch_midi =
2307                ((i32::from(attack.pitch_midi) + i32::from(semitones)).clamp(0, 127)) as u8;
2308            attack.time_beats += attack_beats * ordinal as f64;
2309            attack.time_secs += attack_secs * ordinal as f64;
2310            attack.duration_beats = attack_beats;
2311            attack.duration_secs = attack_secs;
2312            if ordinal > 0 {
2313                attack.chord_symbol = None;
2314            }
2315            realized.push(attack);
2316        }
2317    }
2318    realized
2319}
2320
2321fn shift_event_time(event: &mut PlaybackEvent, offset_beats: f64) {
2322    if offset_beats <= 0.0 || event.duration_beats <= 0.0 {
2323        return;
2324    }
2325    event.time_beats += offset_beats;
2326    event.time_secs += event.duration_secs * (offset_beats / event.duration_beats);
2327}
2328
2329fn ornament_offsets(articulations: &[Articulation]) -> Vec<i8> {
2330    if articulations
2331        .iter()
2332        .any(|articulation| matches!(articulation, Articulation::Trill | Articulation::Shake))
2333    {
2334        return vec![0, 1, 0, 1];
2335    }
2336    if articulations
2337        .iter()
2338        .any(|articulation| matches!(articulation, Articulation::Mordent))
2339    {
2340        return vec![0, 1, 0, 0];
2341    }
2342    if articulations
2343        .iter()
2344        .any(|articulation| matches!(articulation, Articulation::InvertedMordent))
2345    {
2346        return vec![0, -1, 0, 0];
2347    }
2348    if articulations
2349        .iter()
2350        .any(|articulation| matches!(articulation, Articulation::Turn))
2351    {
2352        return vec![1, 0, -1, 0];
2353    }
2354    if articulations
2355        .iter()
2356        .any(|articulation| matches!(articulation, Articulation::InvertedTurn))
2357    {
2358        return vec![-1, 0, 1, 0];
2359    }
2360    Vec::new()
2361}
2362
2363/// Integrate seconds over `beats` while BPM changes linearly across a measure.
2364fn tempo_ramp_seconds(start_bpm: f64, end_bpm: Option<f64>, measure_beats: f64, beats: f64) -> f64 {
2365    let beats = beats.max(0.0);
2366    let Some(end_bpm) = end_bpm else {
2367        return beats / start_bpm * 60.0;
2368    };
2369    if measure_beats <= 0.0 || (end_bpm - start_bpm).abs() < f64::EPSILON {
2370        return beats / start_bpm * 60.0;
2371    }
2372    let delta = end_bpm - start_bpm;
2373    let bpm_at_beats = start_bpm + delta * beats / measure_beats;
2374    if bpm_at_beats <= 0.0 {
2375        return beats / start_bpm * 60.0;
2376    }
2377    60.0 * measure_beats / delta * (bpm_at_beats / start_bpm).ln()
2378}
2379
2380/// Inverse of [`tempo_ramp_seconds`] within one measure.
2381///
2382/// This keeps visual/browser cursors on the same clock as emitted playback events when a written
2383/// tempo ramp is active. Invalid or degenerate ramps fall back to constant-tempo conversion.
2384fn tempo_ramp_beats_at_seconds(
2385    start_bpm: f64,
2386    end_bpm: Option<f64>,
2387    measure_beats: f64,
2388    seconds: f64,
2389) -> f64 {
2390    let seconds = seconds.max(0.0);
2391    let Some(end_bpm) = end_bpm else {
2392        return seconds * start_bpm / 60.0;
2393    };
2394    if measure_beats <= 0.0 || (end_bpm - start_bpm).abs() < f64::EPSILON {
2395        return seconds * start_bpm / 60.0;
2396    }
2397    let delta = end_bpm - start_bpm;
2398    let exponent = seconds * delta / (60.0 * measure_beats);
2399    let ratio = exponent.exp();
2400    if !ratio.is_finite() {
2401        return measure_beats;
2402    }
2403    let beats = measure_beats * start_bpm * (ratio - 1.0) / delta;
2404    if beats.is_finite() {
2405        beats
2406    } else {
2407        measure_beats
2408    }
2409}
2410
2411/// Coalesce adjacent playback events that are connected by authored ties.
2412///
2413/// Ties are a notational continuation, not repeated attacks. The event keeps the first
2414/// source address. The notated duration determines continuity; articulations on any segment
2415/// affect the combined note once. Malformed or non-contiguous tie endings remain independent.
2416fn merge_tied_events(
2417    score: &Score,
2418    options: &PlaybackOptions,
2419    events: Vec<PlaybackEvent>,
2420) -> Vec<PlaybackEvent> {
2421    use std::collections::HashMap;
2422
2423    struct PendingTie {
2424        index: usize,
2425        staff: usize,
2426        voice: usize,
2427        notated_end_beats: f64,
2428        staccato: bool,
2429    }
2430
2431    let mut merged = Vec::with_capacity(events.len());
2432    let mut pending: HashMap<(usize, i32), Vec<PendingTie>> = HashMap::new();
2433    let mut clock = None;
2434    for event in events {
2435        let Some(source) = event.source.as_ref() else {
2436            merged.push(event);
2437            continue;
2438        };
2439        let tied_staff = score
2440            .parts
2441            .get(source.part)
2442            .and_then(|part| part.staves.get(source.staff));
2443        let tied_note = tied_staff
2444            .and_then(|staff| staff.measures.get(source.measure))
2445            .and_then(|measure| measure.voices.get(source.voice))
2446            .and_then(|voice| voice.get(source.note));
2447        let (Some(staff), Some(note)) = (tied_staff, tied_note) else {
2448            merged.push(event);
2449            continue;
2450        };
2451        // A chord may tie only some of its pitches: use the flags of the pitch that sounds here.
2452        let transpose_cents = i32::from(staff.transpose_semitones) * 100;
2453        let pitch_index = note
2454            .pitches
2455            .iter()
2456            .position(|pitch| pitch.to_midi_cents() + transpose_cents == event.pitch_midi_cents);
2457        let (tie_start, tie_end) = match pitch_index {
2458            Some(index) => (note.pitch_tie_start(index), note.pitch_tie_end(index)),
2459            None => (note.tie_start, note.tie_end),
2460        };
2461        let mut articulation_scale = 1.0;
2462        let mut staccato = false;
2463        for articulation in &note.articulations {
2464            match articulation {
2465                Articulation::Staccato | Articulation::Staccatissimo => {
2466                    articulation_scale *= 0.5;
2467                    staccato = true;
2468                }
2469                Articulation::Fermata => articulation_scale *= options.fermata_multiplier,
2470                _ => {}
2471            }
2472        }
2473        let notated_duration = if articulation_scale.is_finite()
2474            && articulation_scale > 0.0
2475            && event.duration_beats.is_finite()
2476        {
2477            event.duration_beats / articulation_scale
2478        } else {
2479            note.beats()
2480        };
2481        let source_staff = source.staff;
2482        let source_voice = source.voice;
2483        let key = (source.part, event.pitch_midi_cents);
2484        if let Some(candidates) = pending.get_mut(&key) {
2485            candidates.retain(|candidate| candidate.notated_end_beats >= event.time_beats - 1e-9);
2486            if tie_end {
2487                let matching = candidates
2488                    .iter()
2489                    .enumerate()
2490                    .filter(|(_, candidate)| {
2491                        (candidate.notated_end_beats - event.time_beats).abs() < 1e-9
2492                    })
2493                    .max_by_key(|(_, candidate)| {
2494                        (
2495                            candidate.staff == source.staff,
2496                            candidate.voice == source.voice,
2497                        )
2498                    })
2499                    .map(|(position, _)| position);
2500                if let Some(position) = matching {
2501                    let mut candidate = candidates.remove(position);
2502                    let previous = &mut merged[candidate.index];
2503                    for articulation in event.articulations.iter().filter(|articulation| {
2504                        matches!(
2505                            articulation,
2506                            Articulation::Staccato | Articulation::Staccatissimo
2507                        )
2508                    }) {
2509                        if !previous.articulations.contains(articulation) {
2510                            previous.articulations.push(articulation.clone());
2511                        }
2512                    }
2513                    candidate.notated_end_beats = event.time_beats + notated_duration;
2514                    candidate.staccato |= staccato;
2515                    previous.duration_beats += event.duration_beats;
2516                    previous.duration_secs += event.duration_secs;
2517                    if candidate.staccato {
2518                        previous.duration_beats =
2519                            (candidate.notated_end_beats - previous.time_beats) * 0.5;
2520                        let timeline =
2521                            clock.get_or_insert_with(|| playback_measure_clock(score, options));
2522                        if let Some(end_secs) = playback_secs_at_beat(
2523                            timeline,
2524                            previous.time_beats + previous.duration_beats,
2525                        ) {
2526                            previous.duration_secs = end_secs - previous.time_secs;
2527                        }
2528                    }
2529                    if tie_start {
2530                        candidate.staff = source.staff;
2531                        candidate.voice = source.voice;
2532                        candidates.push(candidate);
2533                    }
2534                    continue;
2535                }
2536            }
2537        }
2538
2539        let index = merged.len();
2540        merged.push(event);
2541        if tie_start {
2542            pending.entry(key).or_default().push(PendingTie {
2543                index,
2544                staff: source_staff,
2545                voice: source_voice,
2546                notated_end_beats: merged[index].time_beats + notated_duration,
2547                staccato,
2548            });
2549        }
2550    }
2551    merged
2552}
2553
2554#[derive(Clone, Copy)]
2555struct PlaybackClockMeasure {
2556    start_beats: f64,
2557    start_secs: f64,
2558    bpm: f64,
2559    ramp_to_bpm: Option<f64>,
2560    beats: f64,
2561}
2562
2563fn playback_measure_clock(score: &Score, options: &PlaybackOptions) -> Vec<PlaybackClockMeasure> {
2564    let marks = score_tempo_marks(score);
2565    let mut bpm = initial_tempo_bpm(score, options);
2566    let mut start_beats = 0.0;
2567    let mut start_secs = 0.0;
2568    let mut clock = Vec::new();
2569    for index in measure_sequence(score).into_iter().filter(|index| {
2570        options
2571            .loop_region
2572            .is_none_or(|(start, end)| *index >= start && *index <= end)
2573    }) {
2574        let mark = marks.get(index).copied().unwrap_or_default();
2575        if let Some(next) = mark.bpm.and_then(|tempo| written_tempo_bpm(options, tempo)) {
2576            bpm = next;
2577        }
2578        let beats = score.playback_measure_beats(index);
2579        let ramp_to_bpm = written_tempo_ramp_bpm(options, mark.ramp_to_bpm);
2580        clock.push(PlaybackClockMeasure {
2581            start_beats,
2582            start_secs,
2583            bpm,
2584            ramp_to_bpm,
2585            beats,
2586        });
2587        start_beats += beats;
2588        start_secs += tempo_ramp_seconds(bpm, ramp_to_bpm, beats, beats);
2589        if let Some(next) = ramp_to_bpm {
2590            bpm = next;
2591        }
2592    }
2593    clock
2594}
2595
2596fn playback_secs_at_beat(clock: &[PlaybackClockMeasure], beat: f64) -> Option<f64> {
2597    let index = clock.partition_point(|measure| measure.start_beats <= beat);
2598    let measure = clock.get(index.saturating_sub(1))?;
2599    let offset = beat - measure.start_beats;
2600    if offset > measure.beats + 1e-9 {
2601        return None;
2602    }
2603    Some(
2604        measure.start_secs
2605            + tempo_ramp_seconds(
2606                measure.bpm,
2607                measure.ramp_to_bpm,
2608                measure.beats,
2609                offset.clamp(0.0, measure.beats),
2610            ),
2611    )
2612}
2613
2614/// Convert a score into playback events while enforcing the host-comparison event bound.
2615pub fn to_playback_events_bounded(
2616    score: &Score,
2617    options: &PlaybackOptions,
2618) -> Result<Vec<PlaybackEvent>, crate::Error> {
2619    let events = to_playback_events(score, options);
2620    if events.len() > MAX_PLAYBACK_COMPARISON_EVENTS {
2621        return Err(crate::Error::PlaybackComparisonTooLarge(events.len()));
2622    }
2623    Ok(events)
2624}
2625
2626// ── PlaybackPosition + compute_playback_position ──────────────────────────────
2627
2628/// Score position at a specific elapsed time.
2629#[derive(Debug, Clone, Serialize, Deserialize)]
2630pub struct PlaybackPosition {
2631    /// Physical measure index (0-based), same coordinate space as [`PlaybackEvent`] fields.
2632    pub measure_index: usize,
2633    /// Beat offset within the measure (`0.0 … time_sig.total_beats()`).
2634    pub beat: f64,
2635}
2636
2637struct MeasureSegment {
2638    measure_idx: usize,
2639    start_secs: f64,
2640    duration_secs: f64,
2641    beats: f64,
2642    bpm: f64,
2643    ramp_to_bpm: Option<f64>,
2644}
2645
2646fn build_measure_segments(score: &Score, options: &PlaybackOptions) -> Vec<MeasureSegment> {
2647    let init_bpm = initial_tempo_bpm(score, options);
2648    let tempo_marks = score_tempo_marks(score);
2649    let full_seq = measure_sequence(score);
2650    let seq: Vec<usize> = if let Some((lo, hi)) = options.loop_region {
2651        full_seq
2652            .into_iter()
2653            .filter(|&i| i >= lo && i <= hi)
2654            .collect()
2655    } else {
2656        full_seq
2657    };
2658
2659    let mut segments = Vec::with_capacity(seq.len());
2660    let mut cursor_secs = 0.0f64;
2661    let mut current_bpm = init_bpm;
2662
2663    for idx in seq {
2664        let mark = tempo_marks.get(idx).copied().unwrap_or_default();
2665        if let Some(t) = mark.bpm.and_then(|tempo| written_tempo_bpm(options, tempo)) {
2666            current_bpm = t;
2667        }
2668        let beats = score.playback_measure_beats(idx);
2669        let ramp_to_bpm = written_tempo_ramp_bpm(options, mark.ramp_to_bpm);
2670        let duration_secs = tempo_ramp_seconds(current_bpm, ramp_to_bpm, beats, beats);
2671
2672        segments.push(MeasureSegment {
2673            measure_idx: idx,
2674            start_secs: cursor_secs,
2675            duration_secs,
2676            beats,
2677            bpm: current_bpm,
2678            ramp_to_bpm,
2679        });
2680        cursor_secs += duration_secs;
2681        if let Some(end_bpm) = ramp_to_bpm {
2682            current_bpm = end_bpm;
2683        }
2684    }
2685    segments
2686}
2687
2688/// Map `elapsed_secs` to a position within the score.
2689///
2690/// Returns `None` if `elapsed_secs` is negative or past the end of the last measure.
2691/// Pass the same [`PlaybackOptions`] used for [`to_playback_events`] so that `loop_region`
2692/// and tempo overrides are applied consistently.
2693pub fn compute_playback_position(
2694    score: &Score,
2695    options: &PlaybackOptions,
2696    elapsed_secs: f64,
2697) -> Option<PlaybackPosition> {
2698    if elapsed_secs < 0.0 {
2699        return None;
2700    }
2701    let segments = build_measure_segments(score, options);
2702    for seg in &segments {
2703        if elapsed_secs < seg.start_secs + seg.duration_secs + 1e-9 {
2704            let beat = tempo_ramp_beats_at_seconds(
2705                seg.bpm,
2706                seg.ramp_to_bpm,
2707                seg.beats,
2708                elapsed_secs - seg.start_secs,
2709            )
2710            .clamp(0.0, seg.beats);
2711            return Some(PlaybackPosition {
2712                measure_index: seg.measure_idx,
2713                beat,
2714            });
2715        }
2716    }
2717    None
2718}
2719
2720#[cfg(test)]
2721mod tests {
2722    use super::*;
2723    use crate::model::{
2724        duration::Duration,
2725        pitch::{Pitch, Step},
2726        score::{MidiAftertouch, MidiControlChange, MidiPitchBend, MidiProgramChange, Note, Score},
2727    };
2728
2729    fn opts(bpm: Option<u16>) -> PlaybackOptions {
2730        PlaybackOptions {
2731            bpm_override: bpm,
2732            ..Default::default()
2733        }
2734    }
2735
2736    #[test]
2737    fn playback_options_accepts_an_empty_json_object_as_defaults() {
2738        let parsed: PlaybackOptions = serde_json::from_str("{}").expect("default playback options");
2739        assert_eq!(parsed, PlaybackOptions::default());
2740    }
2741
2742    #[test]
2743    fn bounded_playback_events_match_unbounded_schedule_within_limit() {
2744        let score = Score::new("bounded", 120, 4, 4, 0, 1);
2745        let options = opts(Some(120));
2746        let unbounded = to_playback_events(&score, &options);
2747        let bounded = to_playback_events_bounded(&score, &options).expect("bounded schedule");
2748        assert_eq!(bounded, unbounded);
2749    }
2750
2751    #[test]
2752    fn bars_after_a_meter_change_keep_the_new_meter() {
2753        use crate::model::duration::Duration;
2754        use crate::{Note, Pitch, Step, TimeSignature};
2755        let mut score = Score::new("meter", 120, 4, 4, 0, 3);
2756        let staff = &mut score.parts[0].staves[0];
2757        staff.measures[1].time_sig = Some(TimeSignature {
2758            numerator: 3,
2759            denominator: 4,
2760        });
2761        for measure in &mut staff.measures {
2762            measure.voices[0] = vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
2763        }
2764        let onsets: Vec<f64> = to_playback_events(&score, &opts(Some(120)))
2765            .iter()
2766            .filter(|event| event.address.is_some())
2767            .map(|event| event.time_beats)
2768            .collect();
2769        // 4/4, then two bars of 3/4: the third bar starts at 4 + 3, not 4 + 4.
2770        assert_eq!(onsets, vec![0.0, 4.0, 7.0]);
2771    }
2772
2773    #[test]
2774    fn tempo_written_on_either_part_governs_the_whole_score() {
2775        let mut score = Score::new("shared tempo", 120, 4, 4, 0, 2);
2776        let mut second = score.parts[0].clone();
2777        second.id = "second".into();
2778        score.parts.push(second);
2779        for part in &mut score.parts {
2780            for measure in &mut part.staves[0].measures {
2781                measure.voices[0] = vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
2782            }
2783        }
2784        score.parts[0].staves[0].measures[0].tempo = Some(92);
2785        score.parts[1].staves[0].measures[1].tempo = Some(60);
2786        let options = PlaybackOptions {
2787            metronome: Some(MetronomeConfig::default()),
2788            ..Default::default()
2789        };
2790        let events = to_playback_events(&score, &options);
2791        for part_index in 0..2 {
2792            let first = events
2793                .iter()
2794                .find(|event| {
2795                    event.part_index == part_index
2796                        && event
2797                            .source
2798                            .as_ref()
2799                            .is_some_and(|source| source.measure == 0)
2800                })
2801                .unwrap();
2802            let second = events
2803                .iter()
2804                .find(|event| {
2805                    event.part_index == part_index
2806                        && event
2807                            .source
2808                            .as_ref()
2809                            .is_some_and(|source| source.measure == 1)
2810                })
2811                .unwrap();
2812            assert!((first.duration_secs - 60.0 / 92.0).abs() < 1e-9);
2813            assert!((second.time_secs - 4.0 * 60.0 / 92.0).abs() < 1e-9);
2814            assert!((second.duration_secs - 1.0).abs() < 1e-9);
2815        }
2816        let clicks: Vec<_> = events.iter().filter(|event| event.is_metronome).collect();
2817        assert!((clicks[1].time_secs - 60.0 / 92.0).abs() < 1e-9);
2818        assert!((clicks[4].time_secs - 4.0 * 60.0 / 92.0).abs() < 1e-9);
2819        let position = compute_playback_position(&score, &options, 1.5 * 60.0 / 92.0).unwrap();
2820        assert_eq!(position.measure_index, 0);
2821        assert!((position.beat - 1.5).abs() < 1e-9);
2822        let timeline_1 = offline_measure_times(&score, &options, 1, 0, &score_tempo_marks(&score));
2823        assert!((timeline_1[0].bpm - 92.0).abs() < 1e-9);
2824        assert!((timeline_1[1].bpm - 60.0).abs() < 1e-9);
2825    }
2826
2827    #[test]
2828    fn empty_score_no_events() {
2829        let score = Score::new("T", 120, 4, 4, 0, 1);
2830        assert!(to_playback_events(&score, &opts(None)).is_empty());
2831    }
2832
2833    #[test]
2834    fn single_note_at_beat_zero() {
2835        let mut score = Score::new("T", 120, 4, 4, 0, 1);
2836        score.parts[0].staves[0].measures[0].voices[0] =
2837            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
2838        let events = to_playback_events(&score, &opts(None));
2839        assert_eq!(events.len(), 1);
2840        assert_eq!(events[0].address.as_deref(), Some("0:0:0:0:0"));
2841        assert_eq!(
2842            events[0].source,
2843            Some(NoteAddr {
2844                part: 0,
2845                staff: 0,
2846                measure: 0,
2847                voice: 0,
2848                note: 0,
2849            })
2850        );
2851        assert!((events[0].time_beats).abs() < 1e-9);
2852        assert_eq!(events[0].pitch_midi, 60);
2853        assert_eq!(events[0].velocity, 64);
2854        assert!((events[0].duration_beats - 1.0).abs() < 1e-9);
2855        assert_eq!(events[0].part_index, 0);
2856    }
2857
2858    #[test]
2859    fn tied_notes_are_one_continuous_playback_event() {
2860        let mut score = Score::new("T", 120, 4, 4, 0, 1);
2861        let mut first = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
2862        first.tie_start = true;
2863        let mut second = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
2864        second.tie_end = true;
2865        score.parts[0].staves[0].measures[0].voices[0] = vec![first, second];
2866
2867        let events = to_playback_events(&score, &opts(None));
2868        assert_eq!(events.len(), 1);
2869        assert_eq!(
2870            events[0].source.as_ref().map(|address| address.note),
2871            Some(0)
2872        );
2873        assert!((events[0].time_beats).abs() < 1e-9);
2874        assert!((events[0].duration_beats - 2.0).abs() < 1e-9);
2875        assert!((events[0].duration_secs - 1.0).abs() < 1e-9);
2876    }
2877
2878    #[test]
2879    fn staccato_tied_across_barline_has_one_half_length_attack() {
2880        for marks in [[true, false], [false, true], [true, true]] {
2881            let mut score = Score::new("tied staccato", 120, 4, 4, 0, 2);
2882            let mut first = Note::new(Pitch::new(Step::D, 5), Duration::Eighth);
2883            first.tie_start = true;
2884            let mut second = Note::new(Pitch::new(Step::D, 5), Duration::Eighth);
2885            second.tie_end = true;
2886            if marks[0] {
2887                first.articulations.push(Articulation::Staccato);
2888            }
2889            if marks[1] {
2890                second.articulations.push(Articulation::Staccato);
2891            }
2892            score.parts[0].staves[0].measures[0].voices[0] = vec![
2893                Note::rest(Duration::Half),
2894                Note::rest(Duration::Quarter),
2895                Note::rest(Duration::Eighth),
2896                first,
2897            ];
2898            score.parts[0].staves[0].measures[1].voices[0] = vec![second];
2899            let events = to_playback_events(&score, &opts(None));
2900            assert_eq!(events.len(), 1, "articulations: {marks:?}");
2901            assert_eq!(events[0].pitch_midi, 74);
2902            assert_eq!(events[0].time_beats, 3.5);
2903            assert!(events[0].articulations.contains(&Articulation::Staccato));
2904            assert!((events[0].duration_beats - 0.5).abs() < 1e-9);
2905            assert!((events[0].duration_secs - 0.25).abs() < 1e-9);
2906        }
2907    }
2908
2909    #[test]
2910    fn tied_staccato_uses_tempo_at_sounding_end() {
2911        let mut score = Score::new("tied tempo", 120, 4, 4, 0, 2);
2912        let mut first = Note::new(Pitch::new(Step::D, 5), Duration::Eighth);
2913        first.tie_start = true;
2914        first.articulations.push(Articulation::Staccato);
2915        let mut second = Note::new(Pitch::new(Step::D, 5), Duration::Quarter);
2916        second.dot_count = 1;
2917        second.tie_end = true;
2918        score.parts[0].staves[0].measures[0].voices[0] = vec![
2919            Note::rest(Duration::Half),
2920            Note::rest(Duration::Quarter),
2921            Note::rest(Duration::Eighth),
2922            first,
2923        ];
2924        score.parts[0].staves[0].measures[1].tempo = Some(60);
2925        score.parts[0].staves[0].measures[1].voices[0] = vec![second];
2926        let events = to_playback_events(&score, &opts(None));
2927        assert_eq!(events.len(), 1);
2928        assert!((events[0].duration_beats - 1.0).abs() < 1e-9);
2929        assert!((events[0].duration_secs - 0.75).abs() < 1e-9);
2930    }
2931
2932    #[test]
2933    fn a_tie_on_one_chord_pitch_holds_only_that_pitch() {
2934        let mut score = Score::new("T", 120, 4, 4, 0, 1);
2935        // C–G chord tied on C only into another C–G chord: G re-strikes, C sustains.
2936        let chord = || {
2937            let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
2938            note.pitches.push(Pitch::new(Step::G, 4));
2939            note
2940        };
2941        let mut first = chord();
2942        first.set_pitch_ties(&[true, false], &[false, false]);
2943        let mut second = chord();
2944        second.set_pitch_ties(&[false, false], &[true, false]);
2945        assert!(first.tie_start && second.tie_end);
2946        score.parts[0].staves[0].measures[0].voices[0] = vec![first, second];
2947
2948        let events = to_playback_events(&score, &opts(None));
2949        let durations = |midi: u8| {
2950            events
2951                .iter()
2952                .filter(|event| event.pitch_midi == midi)
2953                .map(|event| event.duration_beats)
2954                .collect::<Vec<_>>()
2955        };
2956        assert_eq!(durations(60), vec![2.0]);
2957        assert_eq!(durations(67), vec![1.0, 1.0]);
2958    }
2959
2960    #[test]
2961    fn ties_cross_measure_boundaries_and_tempo_changes_without_retriggering() {
2962        let mut score = Score::new("T", 120, 4, 4, 0, 2);
2963        let first_measure = &mut score.parts[0].staves[0].measures[0];
2964        let mut first = Note::new(Pitch::new(Step::C, 4), Duration::Whole);
2965        first.tie_start = true;
2966        first_measure.voices[0] = vec![first];
2967
2968        let second_measure = &mut score.parts[0].staves[0].measures[1];
2969        second_measure.tempo = Some(60);
2970        let mut second = Note::new(Pitch::new(Step::C, 4), Duration::Whole);
2971        second.tie_end = true;
2972        second_measure.voices[0] = vec![second];
2973
2974        let events = to_playback_events(&score, &opts(None));
2975        assert_eq!(events.len(), 1);
2976        assert_eq!(
2977            events[0].source.as_ref().map(|address| address.measure),
2978            Some(0)
2979        );
2980        assert!((events[0].time_beats).abs() < 1e-9);
2981        assert!((events[0].duration_beats - 8.0).abs() < 1e-9);
2982        assert!((events[0].duration_secs - 6.0).abs() < 1e-9);
2983    }
2984
2985    #[test]
2986    fn ties_continue_across_voice_and_staff_changes() {
2987        let whole_c = || Note::new(Pitch::new(Step::C, 4), Duration::Whole);
2988
2989        let mut voice_score = Score::new("voice change", 120, 4, 4, 0, 2);
2990        let mut start = whole_c();
2991        start.tie_start = true;
2992        let mut end = whole_c();
2993        end.tie_end = true;
2994        voice_score.parts[0].staves[0].measures[0].voices[0] = vec![start.clone()];
2995        voice_score.parts[0].staves[0].measures[1].voices[1] = vec![end.clone()];
2996        let events = to_playback_events(&voice_score, &opts(None));
2997        assert_eq!(events.len(), 1);
2998        assert_eq!(events[0].time_beats, 0.0);
2999        assert_eq!(events[0].duration_beats, 8.0);
3000
3001        let mut staff_score = Score::new("staff change", 120, 4, 4, 0, 2);
3002        let second_staff = staff_score.parts[0].staves[0].clone();
3003        staff_score.parts[0].staves.push(second_staff);
3004        staff_score.parts[0].staves[0].measures[0].voices[0] = vec![start];
3005        staff_score.parts[0].staves[1].measures[1].voices[0] = vec![end];
3006        let events = to_playback_events(&staff_score, &opts(None));
3007        assert_eq!(events.len(), 1);
3008        assert_eq!(events[0].time_beats, 0.0);
3009        assert_eq!(events[0].duration_beats, 8.0);
3010    }
3011
3012    #[test]
3013    fn cross_voice_tie_keeps_independent_unison_attacks() {
3014        let mut score = Score::new("unison", 120, 4, 4, 0, 2);
3015        let mut start = Note::new(Pitch::new(Step::C, 4), Duration::Whole);
3016        start.tie_start = true;
3017        let mut end = Note::new(Pitch::new(Step::C, 4), Duration::Whole);
3018        end.tie_end = true;
3019        score.parts[0].staves[0].measures[0].voices[0] = vec![start];
3020        score.parts[0].staves[0].measures[0].voices[1] =
3021            vec![Note::new(Pitch::new(Step::C, 4), Duration::Whole)];
3022        score.parts[0].staves[0].measures[1].voices[1] = vec![end];
3023        score.parts[0].staves[0].measures[1].voices[2] =
3024            vec![Note::new(Pitch::new(Step::C, 4), Duration::Whole)];
3025
3026        let mut durations: Vec<_> = to_playback_events(&score, &opts(None))
3027            .into_iter()
3028            .map(|event| event.duration_beats)
3029            .collect();
3030        durations.sort_by(f64::total_cmp);
3031        assert_eq!(durations, vec![4.0, 4.0, 8.0]);
3032    }
3033
3034    #[test]
3035    fn malformed_tie_end_does_not_drop_playback_event() {
3036        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3037        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3038        note.tie_end = true;
3039        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3040        let events = to_playback_events(&score, &opts(None));
3041        assert_eq!(events.len(), 1);
3042        assert!((events[0].duration_beats - 1.0).abs() < 1e-9);
3043    }
3044
3045    #[test]
3046    fn microtonal_playback_event_keeps_exact_midi_cents() {
3047        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3048        score.parts[0].staves[0].measures[0].voices[0] = vec![Note::new(
3049            Pitch::with_microtone(Step::C, 4, 0, 50),
3050            Duration::Quarter,
3051        )];
3052        let events = to_playback_events(&score, &opts(None));
3053        assert_eq!(events[0].pitch_midi, 61);
3054        assert_eq!(events[0].pitch_midi_cents, 6050);
3055    }
3056
3057    #[test]
3058    fn chord_expands_to_multiple_events() {
3059        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3060        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3061        note.pitches.push(Pitch::new(Step::E, 4));
3062        note.pitches.push(Pitch::new(Step::G, 4));
3063        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3064        let events = to_playback_events(&score, &opts(None));
3065        assert_eq!(events.len(), 3);
3066        assert!(
3067            events
3068                .iter()
3069                .all(|event| event.address.as_deref() == Some("0:0:0:0:0"))
3070        );
3071        assert!(events.iter().all(|e| e.time_beats.abs() < 1e-9));
3072    }
3073
3074    #[test]
3075    fn playback_events_preserve_authored_chord_symbol_without_inventing_notes() {
3076        let mut score = Score::new("Harmony", 120, 4, 4, 0, 1);
3077        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3078        note.chord_symbol = Some(ChordSymbol {
3079            root: "C".into(),
3080            kind: "major-seventh".into(),
3081            bass: Some("E".into()),
3082            placement: None,
3083            extender: false,
3084            harmonic_degree: None,
3085            harmony_function: None,
3086            harmony_type: None,
3087            chord_ref: None,
3088            range_end: None,
3089            degrees: Vec::new(),
3090        });
3091        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3092
3093        let events = to_playback_events(&score, &PlaybackOptions::default());
3094        assert_eq!(events.len(), 1);
3095        assert_eq!(events[0].pitch_midi, 60);
3096        assert_eq!(
3097            events[0]
3098                .chord_symbol
3099                .as_ref()
3100                .map(ChordSymbol::display_text),
3101            Some("Cmaj7/E".into())
3102        );
3103    }
3104
3105    #[test]
3106    fn authored_realization_default_keeps_ornament_as_one_semantic_event() {
3107        let mut score = Score::new("authored ornament", 120, 4, 4, 0, 1);
3108        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3109        note.articulations.push(Articulation::Trill);
3110        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3111
3112        let events = to_playback_events(&score, &PlaybackOptions::default());
3113        assert_eq!(events.len(), 1);
3114        assert_eq!(events[0].pitch_midi, 60);
3115        assert_eq!(events[0].articulations, vec![Articulation::Trill]);
3116    }
3117
3118    #[test]
3119    fn ornament_arpeggio_profile_realizes_trill_with_pinned_timing() {
3120        let mut score = Score::new("realized ornament", 120, 4, 4, 0, 1);
3121        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3122        note.articulations.push(Articulation::Trill);
3123        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3124
3125        let events = to_playback_events(
3126            &score,
3127            &PlaybackOptions {
3128                realization_profile: PlaybackRealizationProfile::OrnamentArpeggioV1,
3129                ..Default::default()
3130            },
3131        );
3132        assert_eq!(events.len(), 4);
3133        assert_eq!(
3134            events
3135                .iter()
3136                .map(|event| event.pitch_midi)
3137                .collect::<Vec<_>>(),
3138            vec![60, 61, 60, 61]
3139        );
3140        for (index, event) in events.iter().enumerate() {
3141            assert!((event.time_beats - index as f64 * 0.25).abs() < 1e-9);
3142            assert!((event.duration_beats - 0.25).abs() < 1e-9);
3143            assert!((event.time_secs - index as f64 * 0.125).abs() < 1e-9);
3144            assert!((event.duration_secs - 0.125).abs() < 1e-9);
3145        }
3146    }
3147
3148    #[test]
3149    fn ornament_arpeggio_profile_staggers_chord_in_authored_direction() {
3150        let mut score = Score::new("realized arpeggio", 120, 4, 4, 0, 1);
3151        let mut chord = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3152        chord.pitches.push(Pitch::new(Step::E, 4));
3153        chord.pitches.push(Pitch::new(Step::G, 4));
3154        chord.arpeggiate = Some(false);
3155        score.parts[0].staves[0].measures[0].voices[0] = vec![chord];
3156
3157        let events = to_playback_events(
3158            &score,
3159            &PlaybackOptions {
3160                realization_profile: PlaybackRealizationProfile::OrnamentArpeggioV1,
3161                ..Default::default()
3162            },
3163        );
3164        assert_eq!(events.len(), 3);
3165        let by_pitch: BTreeMap<_, _> = events
3166            .iter()
3167            .map(|event| (event.pitch_midi, event.time_beats))
3168            .collect();
3169        assert!((by_pitch[&67] - 0.0).abs() < 1e-9);
3170        assert!((by_pitch[&64] - 0.09).abs() < 1e-9);
3171        assert!((by_pitch[&60] - 0.18).abs() < 1e-9);
3172    }
3173
3174    #[test]
3175    fn grace_notes_excluded() {
3176        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3177        let mut grace = Note::new(Pitch::new(Step::D, 4), Duration::Eighth);
3178        grace.is_grace = true;
3179        let regular = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3180        score.parts[0].staves[0].measures[0].voices[0] = vec![grace, regular];
3181        let events = to_playback_events(&score, &opts(None));
3182        assert_eq!(events.len(), 1);
3183        assert_eq!(events[0].pitch_midi, 60);
3184    }
3185
3186    #[test]
3187    fn metronome_events_have_no_source_address() {
3188        let score = Score::new("T", 120, 4, 4, 0, 1);
3189        let options = PlaybackOptions {
3190            metronome: Some(MetronomeConfig::default()),
3191            ..Default::default()
3192        };
3193        let events = to_playback_events(&score, &options);
3194        assert!(!events.is_empty());
3195        assert!(events.iter().all(|event| event.address.is_none()));
3196    }
3197
3198    #[test]
3199    fn second_note_has_correct_time() {
3200        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3201        score.parts[0].staves[0].measures[0].voices[0] = vec![
3202            Note::new(Pitch::new(Step::C, 4), Duration::Quarter),
3203            Note::new(Pitch::new(Step::D, 4), Duration::Quarter),
3204        ];
3205        let events = to_playback_events(&score, &opts(None));
3206        assert_eq!(events.len(), 2);
3207        assert!((events[0].time_beats).abs() < 1e-9);
3208        assert!((events[1].time_beats - 1.0).abs() < 1e-9);
3209    }
3210
3211    #[test]
3212    fn sparse_voice_keeps_measure_boundaries() {
3213        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3214        let note = || Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3215        score.parts[0].staves[0].measures[0].voices[1] = vec![note()];
3216        score.parts[0].staves[0].measures[1].voices[1] = vec![note()];
3217
3218        let events = to_playback_events(&score, &opts(None));
3219        assert_eq!(events.len(), 2);
3220        assert!((events[0].time_beats).abs() < 1e-9);
3221        assert!((events[1].time_beats - 4.0).abs() < 1e-9);
3222        assert!((events[1].time_secs - 2.0).abs() < 1e-9);
3223    }
3224
3225    #[test]
3226    fn time_secs_120_bpm_quarter_note_is_half_second() {
3227        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3228        score.parts[0].staves[0].measures[0].voices[0] =
3229            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3230        let events = to_playback_events(&score, &opts(None));
3231        assert!((events[0].time_secs).abs() < 1e-9);
3232        assert!((events[0].duration_secs - 0.5).abs() < 1e-9);
3233    }
3234
3235    #[test]
3236    fn bpm_override_changes_time_secs() {
3237        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3238        score.parts[0].staves[0].measures[0].voices[0] = vec![
3239            Note::new(Pitch::new(Step::C, 4), Duration::Quarter),
3240            Note::new(Pitch::new(Step::D, 4), Duration::Quarter),
3241        ];
3242        let events = to_playback_events(&score, &opts(Some(60)));
3243        assert!((events[0].time_secs).abs() < 1e-9);
3244        assert!((events[1].time_secs - 1.0).abs() < 1e-9);
3245    }
3246
3247    #[test]
3248    fn tempo_multiplier_preserves_written_tempo_changes_and_ramps() {
3249        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3250        score.parts[0].staves[0].measures[0].tempo_ramp_to = Some(60);
3251        score.parts[0].staves[0].measures[1].tempo = Some(90);
3252        score.parts[0].staves[0].measures[0].voices[0] =
3253            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3254        score.parts[0].staves[0].measures[1].voices[0] =
3255            vec![Note::new(Pitch::new(Step::D, 4), Duration::Quarter)];
3256        let options = PlaybackOptions {
3257            tempo_multiplier: 0.5,
3258            ..Default::default()
3259        };
3260
3261        let events = to_playback_events(&score, &options);
3262        let second_measure_start = tempo_ramp_seconds(60.0, Some(30.0), 4.0, 4.0);
3263        assert!((events[1].time_secs - second_measure_start).abs() < 1e-9);
3264
3265        let one_beat_into_ramp = tempo_ramp_seconds(60.0, Some(30.0), 4.0, 1.0);
3266        let position = compute_playback_position(&score, &options, one_beat_into_ramp).unwrap();
3267        assert_eq!(position.measure_index, 0);
3268        assert!((position.beat - 1.0).abs() < 1e-9);
3269
3270        let second_measure_position =
3271            compute_playback_position(&score, &options, second_measure_start + 60.0 / 45.0)
3272                .unwrap();
3273        assert_eq!(second_measure_position.measure_index, 1);
3274        assert!((second_measure_position.beat - 1.0).abs() < 1e-9);
3275    }
3276
3277    #[test]
3278    fn bpm_override_suppresses_written_tempo_changes_and_ramps() {
3279        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3280        score.parts[0].staves[0].measures[0].tempo_ramp_to = Some(60);
3281        score.parts[0].staves[0].measures[1].tempo = Some(90);
3282        score.parts[0].staves[0].measures[0].voices[0] =
3283            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3284        score.parts[0].staves[0].measures[1].voices[0] =
3285            vec![Note::new(Pitch::new(Step::D, 4), Duration::Quarter)];
3286        let options = PlaybackOptions {
3287            bpm_override: Some(120),
3288            ..Default::default()
3289        };
3290
3291        let events = to_playback_events(&score, &options);
3292        assert!((events[1].time_secs - 2.0).abs() < 1e-9);
3293        let position = compute_playback_position(&score, &options, 2.5).unwrap();
3294        assert_eq!(position.measure_index, 1);
3295        assert!((position.beat - 1.0).abs() < 1e-9);
3296    }
3297
3298    #[test]
3299    fn playback_position_tracks_repeats_rests_and_meter_changes_with_a_tempo_multiplier() {
3300        use crate::model::notation::{Barline, TimeSignature};
3301
3302        let mut score = Score::new("transport", 120, 4, 4, 0, 3);
3303        let staff = &mut score.parts[0].staves[0];
3304        staff.measures[0].barline_left = Barline::RepeatStart;
3305        staff.measures[1].time_sig = Some(TimeSignature {
3306            numerator: 3,
3307            denominator: 4,
3308        });
3309        staff.measures[2].barline_right = Barline::RepeatEnd;
3310        staff.measures[0].voices[0] = vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3311        staff.measures[1].voices[0] = vec![Note::rest(Duration::Quarter)];
3312        staff.measures[2].voices[0] = vec![Note::new(Pitch::new(Step::D, 4), Duration::Quarter)];
3313        let options = PlaybackOptions {
3314            tempo_multiplier: 0.5,
3315            ..Default::default()
3316        };
3317
3318        let events = to_playback_events(&score, &options);
3319        let note_starts: Vec<f64> = events
3320            .iter()
3321            .filter(|event| event.address.is_some())
3322            .map(|event| event.time_secs)
3323            .collect();
3324        // 4/4 (4s), then 3/4 rest (3s) and note (3s). The repeat restarts at 10s.
3325        assert_eq!(note_starts, vec![0.0, 7.0, 10.0, 17.0]);
3326
3327        let middle = compute_playback_position(&score, &options, 5.0).unwrap();
3328        assert_eq!(middle.measure_index, 1);
3329        assert!((middle.beat - 1.0).abs() < 1e-9);
3330
3331        let repeated = compute_playback_position(&score, &options, 10.5).unwrap();
3332        assert_eq!(repeated.measure_index, 0);
3333        assert!((repeated.beat - 0.5).abs() < 1e-9);
3334    }
3335
3336    #[test]
3337    fn transpose_semitones_shifts_midi_output() {
3338        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3339        score.parts[0].staves[0].transpose_semitones = -2;
3340        score.parts[0].staves[0].measures[0].voices[0] =
3341            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3342        let events = to_playback_events(&score, &opts(None));
3343        assert_eq!(events.len(), 1);
3344        assert_eq!(events[0].pitch_midi, 58);
3345    }
3346
3347    #[test]
3348    fn percussion_channel_9_ignores_transpose_semitones() {
3349        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3350        score.parts[0].midi_channel = 9;
3351        score.parts[0].staves[0].transpose_semitones = -2;
3352        score.parts[0].staves[0].measures[0].voices[0] =
3353            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3354        let events = to_playback_events(&score, &opts(None));
3355        assert_eq!(events.len(), 1);
3356        assert_eq!(events[0].pitch_midi, 60);
3357    }
3358
3359    #[test]
3360    fn staccato_halves_duration_beats() {
3361        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3362        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3363        note.articulations
3364            .push(crate::model::notation::Articulation::Staccato);
3365        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3366        let events = to_playback_events(&score, &opts(None));
3367        assert_eq!(events.len(), 1);
3368        assert!((events[0].duration_beats - 0.5).abs() < 1e-9);
3369    }
3370
3371    #[test]
3372    fn staccatissimo_also_halves_duration() {
3373        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3374        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3375        note.articulations
3376            .push(crate::model::notation::Articulation::Staccatissimo);
3377        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3378        let events = to_playback_events(&score, &opts(None));
3379        assert!((events[0].duration_beats - 0.5).abs() < 1e-9);
3380    }
3381
3382    #[test]
3383    fn staccato_does_not_shift_next_note_time() {
3384        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3385        let mut n1 = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3386        n1.articulations
3387            .push(crate::model::notation::Articulation::Staccato);
3388        let n2 = Note::new(Pitch::new(Step::D, 4), Duration::Quarter);
3389        score.parts[0].staves[0].measures[0].voices[0] = vec![n1, n2];
3390        let events = to_playback_events(&score, &opts(None));
3391        assert_eq!(events.len(), 2);
3392        assert!((events[1].time_beats - 1.0).abs() < 1e-9);
3393    }
3394
3395    #[test]
3396    fn dynamics_hold_until_the_next_marking_across_voices_and_bars() {
3397        use crate::model::notation::Dynamic;
3398        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3399        let quarters = |dynamics: [Option<Dynamic>; 4]| -> Vec<Note> {
3400            dynamics
3401                .into_iter()
3402                .map(|dynamic| {
3403                    let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3404                    note.dynamic = dynamic;
3405                    note
3406                })
3407                .collect()
3408        };
3409        // Bar 1: p, (p), sf, (p) ; bar 2: fp, (p), pf, (f). Voice 2 in bar 1 holds a half
3410        // note at beat 2, when voice 1's sf sounds, and one at beat 0.
3411        score.parts[0].staves[0].measures[0].voices[0] =
3412            quarters([Some(Dynamic::P), None, Some(Dynamic::Sf), None]);
3413        score.parts[0].staves[0].measures[0].voices[1] = vec![
3414            Note::new(Pitch::new(Step::C, 3), Duration::Half),
3415            Note::new(Pitch::new(Step::C, 3), Duration::Half),
3416        ];
3417        score.parts[0].staves[0].measures[1].voices[0] =
3418            quarters([Some(Dynamic::Fp), None, Some(Dynamic::Pf), None]);
3419        let events = to_playback_events(&score, &opts(None));
3420        let velocities = |pitch: u8| -> Vec<u8> {
3421            events
3422                .iter()
3423                .filter(|event| event.pitch_midi == pitch)
3424                .map(|event| event.velocity)
3425                .collect()
3426        };
3427        let (p, f, sf) = (
3428            Dynamic::P.to_velocity(),
3429            Dynamic::F.to_velocity(),
3430            Dynamic::Sf.to_velocity(),
3431        );
3432        assert_eq!(velocities(60), vec![p, p, sf, p, f, p, p, f]);
3433        assert_eq!(velocities(48), vec![p, sf]);
3434        // Before any marking, notes keep the historical default.
3435        assert_eq!(
3436            DynamicTimeline::default().velocity(0, 0.0, None),
3437            DynamicTimeline::DEFAULT_VELOCITY
3438        );
3439    }
3440
3441    #[test]
3442    fn hairpins_ramp_towards_the_following_marking_or_two_steps() {
3443        use crate::model::notation::{Dynamic, HairpinKind};
3444        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3445        let mut bar = |index: usize, dynamics: [Option<Dynamic>; 4], end: Option<Dynamic>| {
3446            let mut notes: Vec<Note> = dynamics
3447                .into_iter()
3448                .map(|dynamic| {
3449                    let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3450                    note.dynamic = dynamic;
3451                    note
3452                })
3453                .collect();
3454            notes[0].hairpin_start = Some(HairpinKind::Crescendo);
3455            notes[2].hairpin_end = true;
3456            notes[3].dynamic = end;
3457            score.parts[0].staves[0].measures[index].voices[0] = notes;
3458        };
3459        // Bar 1: p < (three beats) f. Bar 2: < with nothing after: two steps above f.
3460        bar(0, [Some(Dynamic::P), None, None, None], Some(Dynamic::F));
3461        bar(1, [None, None, None, None], None);
3462        let events = to_playback_events(&score, &opts(None));
3463        let velocities: Vec<u8> = events.iter().map(|event| event.velocity).collect();
3464        assert_eq!(&velocities[..4], &[48, 60, 72, 84]);
3465        assert_eq!(&velocities[4..], &[84, 92, 100, 108]);
3466    }
3467
3468    #[test]
3469    fn dynamic_names_round_trip_and_compounds_continue_at_their_second_level() {
3470        use crate::model::notation::Dynamic;
3471        for dynamic in Dynamic::ALL {
3472            assert_eq!(
3473                Dynamic::from_musicxml_str(dynamic.to_musicxml_str()),
3474                Some(dynamic)
3475            );
3476        }
3477        assert_eq!(Dynamic::from_musicxml_str("fffff"), Some(Dynamic::Ffff));
3478        assert_eq!(Dynamic::Sfpp.sustained_level(), Some(Dynamic::Pp));
3479        assert_eq!(Dynamic::Sfz.sustained_level(), None);
3480        assert_eq!(Dynamic::from_musicxml_str("other"), None);
3481    }
3482
3483    #[test]
3484    fn accent_boosts_velocity_clamped() {
3485        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3486        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3487        note.articulations
3488            .push(crate::model::notation::Articulation::Accent);
3489        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3490        let events = to_playback_events(&score, &opts(None));
3491        assert_eq!(events[0].velocity, 84);
3492    }
3493
3494    #[test]
3495    fn accent_clamped_at_127() {
3496        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3497        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3498        note.dynamic = Some(crate::model::notation::Dynamic::Ffff);
3499        note.articulations
3500            .push(crate::model::notation::Articulation::Accent);
3501        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3502        let events = to_playback_events(&score, &opts(None));
3503        assert_eq!(events[0].velocity, 127);
3504    }
3505
3506    #[test]
3507    fn tenuto_keeps_full_duration() {
3508        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3509        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3510        note.articulations
3511            .push(crate::model::notation::Articulation::Tenuto);
3512        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3513        let events = to_playback_events(&score, &opts(None));
3514        assert!((events[0].duration_beats - 1.0).abs() < 1e-9);
3515    }
3516
3517    #[test]
3518    fn pedal_start_sets_pedal_field() {
3519        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3520        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3521        note.pedal_start = true;
3522        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3523        let events = to_playback_events(&score, &opts(None));
3524        assert!(events[0].pedal);
3525    }
3526
3527    #[test]
3528    fn no_pedal_start_pedal_is_false() {
3529        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3530        score.parts[0].staves[0].measures[0].voices[0] =
3531            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3532        let events = to_playback_events(&score, &opts(None));
3533        assert!(!events[0].pedal);
3534    }
3535
3536    #[test]
3537    fn set_tempo_at_measure_changes_time_secs() {
3538        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3539        score.parts[0].staves[0].measures[0].voices[0] =
3540            vec![Note::new(Pitch::new(Step::C, 4), Duration::Whole)];
3541        score.parts[0].staves[0].measures[1].tempo = Some(60);
3542        score.parts[0].staves[0].measures[1].voices[0] =
3543            vec![Note::new(Pitch::new(Step::D, 4), Duration::Whole)];
3544        let events = to_playback_events(&score, &opts(None));
3545        assert_eq!(events.len(), 2);
3546        assert!((events[0].time_secs).abs() < 1e-9);
3547        assert!((events[0].duration_secs - 2.0).abs() < 1e-9);
3548        assert!((events[1].time_secs - 2.0).abs() < 1e-9);
3549        assert!((events[1].duration_secs - 4.0).abs() < 1e-9);
3550    }
3551
3552    #[test]
3553    fn muted_part_produces_no_events() {
3554        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3555        score.parts[0].staves[0].measures[0].voices[0] =
3556            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3557        let options = PlaybackOptions {
3558            muted_parts: vec![0],
3559            ..Default::default()
3560        };
3561        assert!(to_playback_events(&score, &options).is_empty());
3562    }
3563
3564    #[test]
3565    fn part_index_field_set_correctly() {
3566        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3567        score.parts[0].staves[0].measures[0].voices[0] =
3568            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3569        let events = to_playback_events(&score, &opts(None));
3570        assert_eq!(events[0].part_index, 0);
3571    }
3572
3573    // ── loop_region ───────────────────────────────────────────────────────────
3574
3575    #[test]
3576    fn loop_region_filters_measures() {
3577        // 3 measures; notes in measures 0, 1, 2. Loop on [1,2] → only events from 1,2.
3578        let mut score = Score::new("T", 120, 4, 4, 0, 3);
3579        for mi in 0..3 {
3580            score.parts[0].staves[0].measures[mi].voices[0] =
3581                vec![Note::new(Pitch::new(Step::C, 4), Duration::Whole)];
3582        }
3583        let options = PlaybackOptions {
3584            loop_region: Some((1, 2)),
3585            ..Default::default()
3586        };
3587        let events = to_playback_events(&score, &options);
3588        assert_eq!(events.len(), 2);
3589        // First event in the region should start at beat 0 (region-relative)
3590        assert!((events[0].time_beats).abs() < 1e-9);
3591    }
3592
3593    #[test]
3594    fn loop_region_none_plays_all_measures() {
3595        let mut score = Score::new("T", 120, 4, 4, 0, 3);
3596        for mi in 0..3 {
3597            score.parts[0].staves[0].measures[mi].voices[0] =
3598                vec![Note::new(Pitch::new(Step::C, 4), Duration::Whole)];
3599        }
3600        let events = to_playback_events(&score, &opts(None));
3601        assert_eq!(events.len(), 3);
3602    }
3603
3604    // ── Fermata ───────────────────────────────────────────────────────────────
3605
3606    #[test]
3607    fn fermata_multiplier_extends_duration() {
3608        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3609        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3610        note.articulations
3611            .push(crate::model::notation::Articulation::Fermata);
3612        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3613        let options = PlaybackOptions {
3614            fermata_multiplier: 2.0,
3615            ..Default::default()
3616        };
3617        let events = to_playback_events(&score, &options);
3618        assert_eq!(events.len(), 1);
3619        assert!((events[0].duration_beats - 2.0).abs() < 1e-9);
3620    }
3621
3622    #[test]
3623    fn fermata_default_multiplier_is_1_5() {
3624        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3625        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3626        note.articulations
3627            .push(crate::model::notation::Articulation::Fermata);
3628        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3629        let events = to_playback_events(&score, &PlaybackOptions::default());
3630        assert_eq!(events.len(), 1);
3631        assert!((events[0].duration_beats - 1.5).abs() < 1e-9);
3632    }
3633
3634    #[test]
3635    fn fermata_hold_is_an_explicit_post_note_request_separate_from_extension() {
3636        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3637        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3638        note.articulations
3639            .push(crate::model::notation::Articulation::Fermata);
3640        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3641        let options = PlaybackOptions {
3642            fermata_multiplier: 2.0,
3643            fermata_hold_beats: 0.75,
3644            ..Default::default()
3645        };
3646        let events = to_playback_events(&score, &options);
3647        assert!((events[0].duration_beats - 2.0).abs() < 1e-9);
3648        assert!((events[0].post_note_pause_beats - 0.75).abs() < 1e-9);
3649    }
3650
3651    #[test]
3652    fn invalid_fermata_hold_is_safely_ignored() {
3653        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3654        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3655        note.articulations
3656            .push(crate::model::notation::Articulation::Fermata);
3657        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3658        let options = PlaybackOptions {
3659            fermata_hold_beats: f64::NAN,
3660            ..Default::default()
3661        };
3662        assert_eq!(
3663            to_playback_events(&score, &options)[0].post_note_pause_beats,
3664            0.0
3665        );
3666    }
3667
3668    #[test]
3669    fn non_fermata_note_unaffected_by_fermata_multiplier() {
3670        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3671        score.parts[0].staves[0].measures[0].voices[0] =
3672            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3673        let options = PlaybackOptions {
3674            fermata_multiplier: 3.0,
3675            ..Default::default()
3676        };
3677        let events = to_playback_events(&score, &options);
3678        assert!((events[0].duration_beats - 1.0).abs() < 1e-9);
3679    }
3680
3681    // ── swing ─────────────────────────────────────────────────────────────────
3682
3683    #[test]
3684    fn swing_triplet_first_eighth_is_long() {
3685        // Two eighth notes in one measure; swing=0.67 → first=0.67, second=0.33
3686        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3687        score.parts[0].staves[0].measures[0].voices[0] = vec![
3688            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3689            Note::new(Pitch::new(Step::D, 4), Duration::Eighth),
3690        ];
3691        let options = PlaybackOptions {
3692            swing: Some(0.67),
3693            ..Default::default()
3694        };
3695        let events = to_playback_events(&score, &options);
3696        // events are sorted by time_beats; C comes first (time_beats=0), D second
3697        let e_c = events.iter().find(|e| e.pitch_midi == 60).unwrap();
3698        let e_d = events.iter().find(|e| e.pitch_midi == 62).unwrap();
3699        assert!(
3700            (e_c.duration_beats - 0.67).abs() < 1e-9,
3701            "first eighth should be 0.67"
3702        );
3703        assert!(
3704            (e_d.duration_beats - 0.33).abs() < 1e-9,
3705            "second eighth should be 0.33"
3706        );
3707        // D starts at 0.67, not 0.5
3708        assert!(
3709            (e_d.time_beats - 0.67).abs() < 1e-9,
3710            "second note start should be at 0.67"
3711        );
3712    }
3713
3714    #[test]
3715    fn swing_does_not_stretch_an_unpaired_eighth() {
3716        let mut score = Score::new("unpaired", 120, 4, 4, 0, 1);
3717        score.parts[0].staves[0].measures[0].voices[0] = vec![
3718            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3719            Note::new(Pitch::new(Step::D, 4), Duration::Quarter),
3720        ];
3721        let events = to_playback_events(
3722            &score,
3723            &PlaybackOptions {
3724                swing: Some(2.0 / 3.0),
3725                ..Default::default()
3726            },
3727        );
3728        assert!((events[0].duration_beats - 0.5).abs() < 1e-9);
3729        assert!((events[1].time_beats - 0.5).abs() < 1e-9);
3730    }
3731
3732    #[test]
3733    fn cue_note_does_not_sound_or_pair_with_a_written_eighth() {
3734        let mut score = Score::new("cue", 120, 4, 4, 0, 1);
3735        let mut cue = Note::new(Pitch::new(Step::D, 4), Duration::Eighth);
3736        cue.is_cue = true;
3737        score.parts[0].staves[0].measures[0].voices[0] = vec![
3738            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3739            cue,
3740            Note::new(Pitch::new(Step::E, 4), Duration::Eighth),
3741        ];
3742        let events = to_playback_events(
3743            &score,
3744            &PlaybackOptions {
3745                swing: Some(2.0 / 3.0),
3746                ..Default::default()
3747            },
3748        );
3749        assert_eq!(events.len(), 2);
3750        assert_eq!(events[0].pitch_midi, 60);
3751        assert_eq!(events[0].duration_beats, 0.5);
3752        assert_eq!(events[1].pitch_midi, 64);
3753        assert_eq!(events[1].time_beats, 0.5);
3754    }
3755
3756    #[test]
3757    fn swing_requires_metric_alignment_and_a_matching_next_note() {
3758        let mut score = Score::new("metric boundary", 120, 4, 4, 0, 1);
3759        score.parts[0].staves[0].measures[0].voices[0] = vec![
3760            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3761            Note::new(Pitch::new(Step::D, 4), Duration::Quarter),
3762            Note::new(Pitch::new(Step::E, 4), Duration::Eighth),
3763            Note::new(Pitch::new(Step::F, 4), Duration::Eighth),
3764            Note::new(Pitch::new(Step::G, 4), Duration::Eighth),
3765            Note::new(Pitch::new(Step::A, 4), Duration::Eighth),
3766        ];
3767        let events = to_playback_events(
3768            &score,
3769            &PlaybackOptions {
3770                swing: Some(2.0 / 3.0),
3771                ..Default::default()
3772            },
3773        );
3774        assert!((events[0].time_beats).abs() < 1e-9);
3775        assert!((events[0].duration_beats - 0.5).abs() < 1e-9);
3776        assert!((events[2].time_beats - 1.5).abs() < 1e-9);
3777        assert!((events[2].duration_beats - 0.5).abs() < 1e-9);
3778        assert!((events[3].time_beats - 2.0).abs() < 1e-9);
3779        assert!((events[3].duration_beats - 2.0 / 3.0).abs() < 1e-9);
3780        assert!((events[4].time_beats - 8.0 / 3.0).abs() < 1e-9);
3781        assert!((events[4].duration_beats - 1.0 / 3.0).abs() < 1e-9);
3782        assert!((events[5].time_beats - 3.0).abs() < 1e-9);
3783        assert!((events[5].duration_beats - 0.5).abs() < 1e-9);
3784    }
3785
3786    #[test]
3787    fn swing_keeps_the_offbeat_delay_after_an_eighth_rest() {
3788        let mut score = Score::new("rest swing", 120, 4, 4, 0, 1);
3789        score.parts[0].staves[0].measures[0].voices[0] = vec![
3790            Note::rest(Duration::Eighth),
3791            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3792            Note::new(Pitch::new(Step::D, 4), Duration::Quarter),
3793        ];
3794        let events = to_playback_events(
3795            &score,
3796            &PlaybackOptions {
3797                swing: Some(2.0 / 3.0),
3798                ..Default::default()
3799            },
3800        );
3801        assert!((events[0].time_beats - 2.0 / 3.0).abs() < 1e-9);
3802        assert!((events[0].duration_beats - 1.0 / 3.0).abs() < 1e-9);
3803        assert!((events[1].time_beats - 1.0).abs() < 1e-9);
3804    }
3805
3806    #[test]
3807    fn invalid_swing_ratios_keep_straight_finite_timing() {
3808        let mut score = Score::new("invalid swing", 120, 4, 4, 0, 1);
3809        score.parts[0].staves[0].measures[0].voices[0] = vec![
3810            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3811            Note::new(Pitch::new(Step::D, 4), Duration::Eighth),
3812        ];
3813        for ratio in [f64::NAN, f64::INFINITY, -1.0, 0.5, 1.0] {
3814            let events = to_playback_events(
3815                &score,
3816                &PlaybackOptions {
3817                    swing: Some(ratio),
3818                    ..Default::default()
3819                },
3820            );
3821            assert_eq!(events.len(), 2);
3822            assert_eq!(events[0].duration_beats, 0.5);
3823            assert_eq!(events[1].time_beats, 0.5);
3824            assert_eq!(events[1].duration_beats, 0.5);
3825            assert!(events.iter().all(|event| event.time_secs.is_finite()));
3826        }
3827    }
3828
3829    #[test]
3830    fn pickup_swing_uses_metric_position_in_the_full_bar() {
3831        let mut score = Score::new("pickup swing", 120, 4, 4, 0, 1);
3832        let measure = &mut score.parts[0].staves[0].measures[0];
3833        measure.actual_length = Some(crate::MeasureLength {
3834            numerator: 3,
3835            denominator: 8,
3836        });
3837        measure.voices[0] = vec![
3838            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3839            Note::new(Pitch::new(Step::D, 4), Duration::Eighth),
3840            Note::new(Pitch::new(Step::E, 4), Duration::Eighth),
3841        ];
3842        let events = to_playback_events(
3843            &score,
3844            &PlaybackOptions {
3845                swing: Some(2.0 / 3.0),
3846                ..Default::default()
3847            },
3848        );
3849        assert_eq!(events[0].duration_beats, 0.5);
3850        assert!((events[1].time_beats - 0.5).abs() < 1e-9);
3851        assert!((events[1].duration_beats - 2.0 / 3.0).abs() < 1e-9);
3852        assert!((events[2].time_beats - 7.0 / 6.0).abs() < 1e-9);
3853        assert!((events[2].duration_beats - 1.0 / 3.0).abs() < 1e-9);
3854    }
3855
3856    #[test]
3857    fn swing_non_eighth_not_affected() {
3858        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3859        score.parts[0].staves[0].measures[0].voices[0] =
3860            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3861        let options = PlaybackOptions {
3862            swing: Some(0.67),
3863            ..Default::default()
3864        };
3865        let events = to_playback_events(&score, &options);
3866        assert!(
3867            (events[0].duration_beats - 1.0).abs() < 1e-9,
3868            "quarter note unaffected"
3869        );
3870    }
3871
3872    #[test]
3873    fn swing_none_is_straight() {
3874        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3875        score.parts[0].staves[0].measures[0].voices[0] =
3876            vec![Note::new(Pitch::new(Step::C, 4), Duration::Eighth)];
3877        let options = PlaybackOptions {
3878            swing: None,
3879            ..Default::default()
3880        };
3881        let events = to_playback_events(&score, &options);
3882        assert!(
3883            (events[0].duration_beats - 0.5).abs() < 1e-9,
3884            "no swing = straight eighth"
3885        );
3886    }
3887
3888    #[test]
3889    fn channel_matches_part_midi_channel() {
3890        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3891        score.parts[0].midi_channel = 3;
3892        score.parts[0].staves[0].measures[0].voices[0] =
3893            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3894        let events = to_playback_events(&score, &opts(None));
3895        assert_eq!(events[0].channel, 3);
3896    }
3897
3898    #[test]
3899    fn swing_unit_default_is_eighth() {
3900        assert_eq!(PlaybackOptions::default().swing_unit, Duration::Eighth);
3901    }
3902
3903    #[test]
3904    fn swing_unit_sixteenth() {
3905        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3906        score.parts[0].staves[0].measures[0].voices[0] = vec![
3907            Note::new(Pitch::new(Step::C, 4), Duration::Sixteenth),
3908            Note::new(Pitch::new(Step::D, 4), Duration::Sixteenth),
3909        ];
3910        let options = PlaybackOptions {
3911            swing: Some(0.67),
3912            swing_unit: Duration::Sixteenth,
3913            ..Default::default()
3914        };
3915        let events = to_playback_events(&score, &options);
3916        let e_c = events.iter().find(|e| e.pitch_midi == 60).unwrap();
3917        let e_d = events.iter().find(|e| e.pitch_midi == 62).unwrap();
3918        assert!(
3919            (e_c.duration_beats - 0.335).abs() < 1e-9,
3920            "first 16th should be 0.335"
3921        );
3922        assert!(
3923            (e_d.duration_beats - 0.165).abs() < 1e-9,
3924            "second 16th should be 0.165"
3925        );
3926    }
3927
3928    #[test]
3929    fn swing_resets_per_measure() {
3930        // 2 measures each with 2 eighth notes; each measure's first eighth should be "long"
3931        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3932        let pair = || {
3933            vec![
3934                Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3935                Note::new(Pitch::new(Step::D, 4), Duration::Eighth),
3936            ]
3937        };
3938        score.parts[0].staves[0].measures[0].voices[0] = pair();
3939        score.parts[0].staves[0].measures[1].voices[0] = pair();
3940        let options = PlaybackOptions {
3941            swing: Some(0.67),
3942            ..Default::default()
3943        };
3944        let events = to_playback_events(&score, &options);
3945        // Four events sorted by time: m0-C, m0-D, m1-C, m1-D
3946        let durations: Vec<f64> = events.iter().map(|e| e.duration_beats).collect();
3947        // m0 first (long)
3948        assert!((durations[0] - 0.67).abs() < 1e-9, "m0 first note long");
3949        // m0 second (short)
3950        assert!((durations[1] - 0.33).abs() < 1e-9, "m0 second note short");
3951        // m1 first (long again — reset)
3952        assert!(
3953            (durations[2] - 0.67).abs() < 1e-9,
3954            "m1 first note long (reset)"
3955        );
3956        // m1 second (short)
3957        assert!((durations[3] - 0.33).abs() < 1e-9, "m1 second note short");
3958    }
3959
3960    #[test]
3961    fn multi_voice_events_preserve_source_voice_addresses() {
3962        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3963        score.parts[0].staves[0].measures[0].voices[0] =
3964            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3965        score.parts[0].staves[0].measures[0].voices[1] =
3966            vec![Note::new(Pitch::new(Step::E, 4), Duration::Quarter)];
3967
3968        let events = to_playback_events(&score, &PlaybackOptions::default());
3969        let addresses: Vec<&str> = events
3970            .iter()
3971            .filter_map(|event| event.address.as_deref())
3972            .collect();
3973        assert!(addresses.contains(&"0:0:0:0:0"));
3974        assert!(addresses.contains(&"0:0:0:1:0"));
3975    }
3976
3977    #[test]
3978    fn playback_exposes_original_musicxml_voice_number_alongside_slot_address() {
3979        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3980        let measure = &mut score.parts[0].staves[0].measures[0];
3981        measure.voices[1] = vec![Note::new(Pitch::new(Step::E, 4), Duration::Quarter)];
3982        measure.source_voice_numbers[1] = Some(5);
3983
3984        let events = to_playback_events(&score, &PlaybackOptions::default());
3985        let event = events
3986            .iter()
3987            .find(|event| event.address.as_deref() == Some("0:0:0:1:0"))
3988            .expect("event from slot 1");
3989        assert_eq!(event.source.as_ref().map(|source| source.voice), Some(1));
3990        assert_eq!(event.source_voice_number, Some(5));
3991    }
3992
3993    // ── compute_playback_position ─────────────────────────────────────────────
3994
3995    #[test]
3996    fn playback_position_at_zero_is_measure_0_beat_0() {
3997        let score = Score::new("T", 120, 4, 4, 0, 4);
3998        let pos = compute_playback_position(&score, &PlaybackOptions::default(), 0.0).unwrap();
3999        assert_eq!(pos.measure_index, 0);
4000        assert!(pos.beat.abs() < 1e-9);
4001    }
4002
4003    #[test]
4004    fn playback_position_at_half_measure_is_beat_2() {
4005        // 4/4, 120 BPM → 1 measure = 2.0 s; 0.5 s = beat 1.0
4006        let score = Score::new("T", 120, 4, 4, 0, 4);
4007        let pos = compute_playback_position(&score, &PlaybackOptions::default(), 0.5).unwrap();
4008        assert_eq!(pos.measure_index, 0);
4009        assert!(
4010            (pos.beat - 1.0).abs() < 1e-9,
4011            "expected beat 1.0, got {}",
4012            pos.beat
4013        );
4014    }
4015
4016    #[test]
4017    fn playback_position_beyond_score_is_none() {
4018        // 4/4, 120 BPM, 1 measure = 2.0 s; 10.0 s is beyond
4019        let score = Score::new("T", 120, 4, 4, 0, 1);
4020        assert!(compute_playback_position(&score, &PlaybackOptions::default(), 10.0).is_none());
4021    }
4022
4023    #[test]
4024    fn playback_position_tempo_change_takes_effect() {
4025        // measure 0: 120 BPM (2.0 s), measure 1: 60 BPM (4.0 s)
4026        // At elapsed=2.5 s → inside measure 1, 0.5 s into it → beat 0.5
4027        let mut score = Score::new("T", 120, 4, 4, 0, 2);
4028        score.parts[0].staves[0].measures[1].tempo = Some(60);
4029        let pos = compute_playback_position(&score, &PlaybackOptions::default(), 2.5).unwrap();
4030        assert_eq!(pos.measure_index, 1);
4031        assert!(
4032            (pos.beat - 0.5).abs() < 1e-9,
4033            "expected beat 0.5, got {}",
4034            pos.beat
4035        );
4036    }
4037
4038    #[test]
4039    fn playback_position_loop_region_starts_at_zero() {
4040        // loop_region=[1,2] → elapsed=0 should map to measure 1, beat 0
4041        let score = Score::new("T", 120, 4, 4, 0, 4);
4042        let options = PlaybackOptions {
4043            loop_region: Some((1, 2)),
4044            ..Default::default()
4045        };
4046        let pos = compute_playback_position(&score, &options, 0.0).unwrap();
4047        assert_eq!(pos.measure_index, 1);
4048        assert!(pos.beat.abs() < 1e-9);
4049    }
4050
4051    // ── MetronomeConfig ───────────────────────────────────────────────────────
4052
4053    #[test]
4054    fn metronome_injects_beat_events() {
4055        // 4/4, 1 measure → should inject 4 metronome events
4056        let score = Score::new("T", 120, 4, 4, 0, 1);
4057        let options = PlaybackOptions {
4058            metronome: Some(MetronomeConfig::default()),
4059            ..Default::default()
4060        };
4061        let events = to_playback_events(&score, &options);
4062        let metro_events: Vec<_> = events.iter().filter(|e| e.is_metronome).collect();
4063        assert_eq!(metro_events.len(), 4, "expected 4 metronome clicks in 4/4");
4064    }
4065
4066    #[test]
4067    fn metronome_accent_is_first_beat() {
4068        let score = Score::new("T", 120, 4, 4, 0, 1);
4069        let metro = MetronomeConfig::default();
4070        let options = PlaybackOptions {
4071            metronome: Some(metro.clone()),
4072            ..Default::default()
4073        };
4074        let events = to_playback_events(&score, &options);
4075        let mut metro_events: Vec<_> = events.iter().filter(|e| e.is_metronome).collect();
4076        metro_events.sort_by(|a, b| a.time_beats.partial_cmp(&b.time_beats).unwrap());
4077        assert_eq!(metro_events[0].pitch_midi, metro.accent_pitch);
4078        assert_eq!(metro_events[0].velocity, metro.accent_velocity);
4079    }
4080
4081    #[test]
4082    fn metronome_regular_beat_pitch() {
4083        let score = Score::new("T", 120, 4, 4, 0, 1);
4084        let metro = MetronomeConfig::default();
4085        let options = PlaybackOptions {
4086            metronome: Some(metro.clone()),
4087            ..Default::default()
4088        };
4089        let events = to_playback_events(&score, &options);
4090        let mut metro_events: Vec<_> = events.iter().filter(|e| e.is_metronome).collect();
4091        metro_events.sort_by(|a, b| a.time_beats.partial_cmp(&b.time_beats).unwrap());
4092        for ev in &metro_events[1..] {
4093            assert_eq!(ev.pitch_midi, metro.beat_pitch);
4094            assert_eq!(ev.velocity, metro.beat_velocity);
4095        }
4096    }
4097
4098    #[test]
4099    fn metronome_integrates_measure_tempo_ramp_and_carries_ending_tempo() {
4100        let mut score = Score::new("T", 120, 4, 4, 0, 2);
4101        score.parts[0].staves[0].measures[0].tempo_ramp_to = Some(60);
4102        let options = PlaybackOptions {
4103            metronome: Some(MetronomeConfig::default()),
4104            ..Default::default()
4105        };
4106
4107        let mut clicks: Vec<_> = to_playback_events(&score, &options)
4108            .into_iter()
4109            .filter(|event| event.is_metronome)
4110            .collect();
4111        clicks.sort_by(|left, right| left.time_beats.total_cmp(&right.time_beats));
4112
4113        let expected_second_beat = tempo_ramp_seconds(120.0, Some(60.0), 4.0, 1.0);
4114        let expected_second_measure = tempo_ramp_seconds(120.0, Some(60.0), 4.0, 4.0);
4115        assert!((clicks[1].time_secs - expected_second_beat).abs() < 1e-9);
4116        assert!((clicks[4].time_secs - expected_second_measure).abs() < 1e-9);
4117        assert!((clicks[5].time_secs - (expected_second_measure + 1.0)).abs() < 1e-9);
4118    }
4119
4120    #[test]
4121    fn metronome_events_are_marked() {
4122        let score = Score::new("T", 120, 4, 4, 0, 1);
4123        let options = PlaybackOptions {
4124            metronome: Some(MetronomeConfig::default()),
4125            ..Default::default()
4126        };
4127        let events = to_playback_events(&score, &options);
4128        assert!(events.iter().any(|e| e.is_metronome));
4129    }
4130
4131    #[test]
4132    fn metronome_none_produces_no_extra_events() {
4133        let score = Score::new("T", 120, 4, 4, 0, 1);
4134        let events = to_playback_events(&score, &PlaybackOptions::default());
4135        assert!(events.iter().all(|e| !e.is_metronome));
4136    }
4137
4138    #[test]
4139    fn offline_render_manifest_uses_event_end_as_exact_frame_length() {
4140        let mut score = Score::new("T", 120, 4, 4, 0, 1);
4141        score.parts[0].staves[0].measures[0].voices[0][0] =
4142            Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
4143        let request = OfflineRenderRequest {
4144            format: OfflineRenderFormat::Flac,
4145            sample_rate_hz: 48_000,
4146            channels: 2,
4147            provider_identity: Some("test-provider@1".into()),
4148            ..Default::default()
4149        };
4150
4151        let manifest = build_offline_render_manifest(&score, &PlaybackOptions::default(), &request)
4152            .expect("valid render manifest");
4153        assert_eq!(manifest.contract_version, OFFLINE_RENDER_CONTRACT_VERSION);
4154        assert!(manifest.validate().is_ok());
4155        assert_eq!(manifest.format, OfflineRenderFormat::Flac);
4156        assert_eq!(manifest.duration_frames, 24_000);
4157        assert_eq!(manifest.events.len(), 1);
4158        assert_eq!(manifest.frame_events.len(), 1);
4159        assert_eq!(manifest.frame_events[0].start_frame, 0);
4160        assert_eq!(manifest.frame_events[0].duration_frames, 24_000);
4161        assert_eq!(manifest.frame_events[0].end_frame, 24_000);
4162        assert_eq!(manifest.playback_options, PlaybackOptions::default());
4163        assert_eq!(
4164            manifest.provider_identity.as_deref(),
4165            Some("test-provider@1")
4166        );
4167    }
4168
4169    #[test]
4170    fn offline_render_manifest_rejects_out_of_range_audio_shape() {
4171        let score = Score::new("T", 120, 4, 4, 0, 1);
4172        let request = OfflineRenderRequest {
4173            sample_rate_hz: 0,
4174            ..Default::default()
4175        };
4176        assert!(matches!(
4177            build_offline_render_manifest(&score, &PlaybackOptions::default(), &request),
4178            Err(crate::Error::InvalidOfflineRenderRequest)
4179        ));
4180    }
4181
4182    #[test]
4183    fn offline_render_manifest_selection_keeps_source_address_and_release_tail() {
4184        let mut score = Score::new("T", 120, 4, 4, 0, 1);
4185        score.parts[0].staves[0].measures[0].voices[0] = vec![
4186            Note::new(Pitch::new(Step::C, 4), Duration::Quarter),
4187            Note::new(Pitch::new(Step::D, 4), Duration::Quarter),
4188        ];
4189        let events = to_playback_events(&score, &PlaybackOptions::default());
4190        score.parts[0].midi_control_changes.push(MidiControlChange {
4191            tick: 480,
4192            channel: 0,
4193            controller: 7,
4194            value: 100,
4195        });
4196        let request = OfflineRenderRequest {
4197            sample_rate_hz: 8_000,
4198            release_tail_millis: 125,
4199            scope: OfflineRenderScope::Selection {
4200                addresses: vec![events[1].source.clone().expect("source address")],
4201            },
4202            ..Default::default()
4203        };
4204        let manifest = build_offline_render_manifest(&score, &PlaybackOptions::default(), &request)
4205            .expect("selection manifest");
4206        assert_eq!(manifest.events.len(), 1);
4207        assert_eq!(manifest.events[0].source, events[1].source);
4208        assert_eq!(manifest.frame_events[0].start_frame, 0);
4209        assert!(manifest.semantic_events.iter().any(|event| matches!(
4210            event.kind,
4211            OfflineRenderSemanticEventKind::Controller {
4212                channel: 0,
4213                controller: 7,
4214                value: 100
4215            }
4216        ) && event.frame == 0));
4217        assert_eq!(manifest.release_tail_frames, 1_000);
4218        assert_eq!(manifest.duration_frames, 5_000);
4219    }
4220
4221    #[test]
4222    fn offline_render_request_owned_options_override_legacy_argument() {
4223        let mut score = Score::new("T", 120, 4, 4, 0, 1);
4224        score.parts[0].staves[0].measures[0].voices[0][0] =
4225            Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
4226        let request_options = PlaybackOptions {
4227            bpm_override: Some(60),
4228            ..Default::default()
4229        };
4230        let manifest = build_offline_render_manifest(
4231            &score,
4232            &PlaybackOptions::default(),
4233            &OfflineRenderRequest {
4234                sample_rate_hz: 48_000,
4235                playback_options: Some(request_options.clone()),
4236                ..Default::default()
4237            },
4238        )
4239        .expect("request-owned playback options");
4240        assert_eq!(manifest.playback_options, request_options);
4241        assert_eq!(manifest.frame_events[0].duration_frames, 48_000);
4242    }
4243
4244    #[test]
4245    fn offline_manifest_projects_typed_midi_events_to_exact_frames() {
4246        let mut score = Score::new("MIDI semantics", 120, 4, 4, 0, 1);
4247        score.parts[0].midi_pitch_bends.push(MidiPitchBend {
4248            tick: 480,
4249            channel: 2,
4250            value: -512,
4251        });
4252        score.parts[0].midi_program_changes.push(MidiProgramChange {
4253            tick: 480,
4254            channel: 2,
4255            program: 41,
4256        });
4257        score.parts[0].midi_aftertouch.push(MidiAftertouch {
4258            tick: 480,
4259            channel: 2,
4260            key: Some(64),
4261            value: 88,
4262        });
4263        let manifest = build_offline_render_manifest(
4264            &score,
4265            &PlaybackOptions::default(),
4266            &OfflineRenderRequest {
4267                sample_rate_hz: 48_000,
4268                ..Default::default()
4269            },
4270        )
4271        .expect("manifest builds");
4272        for kind in [
4273            OfflineRenderSemanticEventKind::PitchBend {
4274                channel: 2,
4275                value: -512,
4276            },
4277            OfflineRenderSemanticEventKind::ProgramChange {
4278                channel: 2,
4279                program: 41,
4280            },
4281            OfflineRenderSemanticEventKind::Aftertouch {
4282                channel: 2,
4283                key: Some(64),
4284                value: 88,
4285            },
4286        ] {
4287            assert!(manifest.semantic_events.iter().any(|event| {
4288                event.kind == kind
4289                    && event.frame == 24_000
4290                    && event
4291                        .measure
4292                        .as_ref()
4293                        .is_some_and(|address| address.part == 0 && address.measure == 0)
4294            }));
4295        }
4296    }
4297
4298    #[test]
4299    fn offline_manifest_frames_cover_repeat_ramp_fermata_pedal_bend_and_instrument_change() {
4300        let mut score = Score::new("fixture", 120, 4, 4, 0, 2);
4301        let mut first = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
4302        first.pedal_start = true;
4303        first.articulations = vec![Articulation::Fermata, Articulation::BreathMark];
4304        first.guitar_bend_curve = vec![GuitarBendPoint {
4305            position_per_mille: 500,
4306            alter_cents: 100,
4307        }];
4308        score.parts[0].staves[0].measures[0].voices[0] = vec![first];
4309        score.parts[0].staves[0].measures[0].barline_left =
4310            super::super::notation::Barline::RepeatStart;
4311        score.parts[0].staves[0].measures[0].tempo_ramp_to = Some(60);
4312        score.parts[0].staves[0].measures[0].navigation = Some("Segno".to_string());
4313        score.parts[0].midi_control_changes.push(MidiControlChange {
4314            tick: 480,
4315            channel: 0,
4316            controller: 11,
4317            value: 96,
4318        });
4319
4320        let mut second = Note::new(Pitch::new(Step::D, 4), Duration::Quarter);
4321        second.pedal_end = true;
4322        score.parts[0].staves[0].measures[1].voices[0] = vec![second];
4323        score.parts[0].staves[0].measures[1].barline_right =
4324            super::super::notation::Barline::RepeatEnd;
4325        let mut flute = crate::InstrumentDefinition::new("flute", "Flute");
4326        flute.midi_channel = 2;
4327        flute.midi_program = 73;
4328        score.parts[0].staves[0].measures[1].instrument_change = Some(flute);
4329
4330        let request = OfflineRenderRequest {
4331            sample_rate_hz: 48_000,
4332            playback_options: Some(PlaybackOptions {
4333                fermata_multiplier: 1.5,
4334                fermata_hold_beats: 0.25,
4335                ..Default::default()
4336            }),
4337            ..Default::default()
4338        };
4339        let manifest = build_offline_render_manifest(&score, &PlaybackOptions::default(), &request)
4340            .expect("fixture manifest");
4341        assert_eq!(manifest.frame_events.len(), 4);
4342        let measures: Vec<usize> = manifest
4343            .frame_events
4344            .iter()
4345            .map(|event| event.event.source.as_ref().unwrap().measure)
4346            .collect();
4347        assert_eq!(measures, vec![0, 1, 0, 1]);
4348        assert!(manifest.frame_events[0].event.pedal);
4349        assert_eq!(manifest.frame_events[0].event.post_note_pause_beats, 0.25);
4350        assert_eq!(manifest.frame_events[0].event.pitch_bend_curve.len(), 1);
4351        assert_eq!(
4352            manifest.frame_events[1].event.instrument_id.as_deref(),
4353            Some("flute")
4354        );
4355        assert_eq!(manifest.frame_events[3].event.program, 73);
4356        assert!(manifest.semantic_events.iter().any(|event| {
4357            matches!(
4358                &event.kind,
4359                OfflineRenderSemanticEventKind::InstrumentChange {
4360                    instrument_id,
4361                    channel: 2,
4362                    program: 73,
4363                    transpose_semitones: 0,
4364                } if instrument_id == "flute"
4365            ) && event
4366                .measure
4367                .as_ref()
4368                .is_some_and(|address| address.measure == 1)
4369                && event.frame == manifest.frame_events[1].start_frame
4370        }));
4371        assert!(manifest.semantic_events.iter().any(|event| matches!(
4372            event.kind,
4373            OfflineRenderSemanticEventKind::Pedal { down: true }
4374        ) && event.frame
4375            == manifest.frame_events[0].start_frame));
4376        assert!(manifest.semantic_events.iter().any(|event| matches!(
4377            event.kind,
4378            OfflineRenderSemanticEventKind::Pedal { down: false }
4379        ) && event.frame
4380            == manifest.frame_events[1].start_frame));
4381        assert!(manifest.semantic_events.iter().any(|event| matches!(
4382            event.kind,
4383            OfflineRenderSemanticEventKind::Articulation {
4384                articulation: Articulation::Fermata
4385            }
4386        )));
4387        assert!(manifest.semantic_events.iter().any(|event| matches!(
4388            event.kind,
4389            OfflineRenderSemanticEventKind::GuitarBend { .. }
4390        )));
4391        let tempo_events = manifest
4392            .semantic_events
4393            .iter()
4394            .filter(|event| matches!(event.kind, OfflineRenderSemanticEventKind::Tempo { .. }))
4395            .count();
4396        let navigation_events = manifest
4397            .semantic_events
4398            .iter()
4399            .filter(|event| {
4400                matches!(
4401                    event.kind,
4402                    OfflineRenderSemanticEventKind::Navigation { .. }
4403                )
4404            })
4405            .count();
4406        let control_frames: Vec<u64> = manifest
4407            .semantic_events
4408            .iter()
4409            .filter_map(|event| {
4410                matches!(
4411                    event.kind,
4412                    OfflineRenderSemanticEventKind::Controller {
4413                        channel: 0,
4414                        controller: 11,
4415                        value: 96
4416                    }
4417                )
4418                .then_some(event.frame)
4419            })
4420            .collect();
4421        assert_eq!(tempo_events, 2);
4422        assert_eq!(navigation_events, 2);
4423        assert_eq!(control_frames.len(), 2);
4424        let ramp_duration = tempo_ramp_seconds(120.0, Some(60.0), 4.0, 4.0);
4425        assert_eq!(
4426            control_frames[0],
4427            (tempo_ramp_seconds(120.0, Some(60.0), 4.0, 1.0) * 48_000.0).round() as u64
4428        );
4429        assert_eq!(control_frames[1], 373_084);
4430
4431        let expected_starts = [0.0, ramp_duration, ramp_duration + 4.0, ramp_duration + 8.0];
4432        for (frame_event, expected_secs) in manifest.frame_events.iter().zip(expected_starts) {
4433            assert_eq!(
4434                frame_event.start_frame,
4435                (expected_secs * 48_000.0).round() as u64
4436            );
4437        }
4438    }
4439
4440    #[test]
4441    fn offline_render_manifest_reports_unresolved_selection_address() {
4442        let score = Score::new("T", 120, 4, 4, 0, 1);
4443        let request = OfflineRenderRequest {
4444            scope: OfflineRenderScope::Selection {
4445                addresses: vec![NoteAddr {
4446                    part: 0,
4447                    staff: 0,
4448                    measure: 0,
4449                    voice: 0,
4450                    note: 99,
4451                }],
4452            },
4453            ..Default::default()
4454        };
4455        let manifest = build_offline_render_manifest(&score, &PlaybackOptions::default(), &request)
4456            .expect("empty selection is representable");
4457        assert_eq!(manifest.events.len(), 0);
4458        assert_eq!(
4459            manifest.diagnostics,
4460            vec![
4461                OfflineRenderDiagnostic {
4462                    kind: OfflineRenderDiagnosticKind::UnresolvedSelectionAddress,
4463                    source: Some(NoteAddr {
4464                        part: 0,
4465                        staff: 0,
4466                        measure: 0,
4467                        voice: 0,
4468                        note: 99,
4469                    }),
4470                },
4471                OfflineRenderDiagnostic {
4472                    kind: OfflineRenderDiagnosticKind::EmptySelection,
4473                    source: None,
4474                },
4475            ]
4476        );
4477    }
4478
4479    #[test]
4480    fn offline_render_manifest_v1_json_migrates_with_v2_defaults() {
4481        let legacy = serde_json::json!({
4482            "contract_version": 1,
4483            "playback_contract_version": 2,
4484            "format": "Wav",
4485            "sample_rate_hz": 48_000,
4486            "channels": 2,
4487            "duration_frames": 0,
4488            "events": []
4489        });
4490        let manifest: OfflineRenderManifest =
4491            serde_json::from_value(legacy).expect("v1 manifest remains readable");
4492        assert_eq!(manifest.contract_version, 1);
4493        assert_eq!(manifest.scope, OfflineRenderScope::FullScore);
4494        assert_eq!(manifest.release_tail_frames, 0);
4495        assert_eq!(manifest.playback_options, PlaybackOptions::default());
4496        assert!(manifest.frame_events.is_empty());
4497        assert!(manifest.diagnostics.is_empty());
4498        assert!(manifest.validate().is_ok());
4499    }
4500
4501    #[test]
4502    fn offline_render_manifest_validation_rejects_tampered_frame_and_tail_boundaries() {
4503        let mut score = Score::new("T", 120, 4, 4, 0, 1);
4504        score.parts[0].staves[0].measures[0].voices[0] =
4505            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
4506        let manifest = build_offline_render_manifest(
4507            &score,
4508            &PlaybackOptions::default(),
4509            &OfflineRenderRequest {
4510                sample_rate_hz: 48_000,
4511                release_tail_millis: 100,
4512                ..Default::default()
4513            },
4514        )
4515        .expect("manifest builds");
4516        assert!(manifest.validate().is_ok());
4517
4518        let mut invalid_tail = manifest.clone();
4519        invalid_tail.duration_frames = invalid_tail.duration_frames.saturating_sub(1);
4520        assert!(matches!(
4521            invalid_tail.validate(),
4522            Err(crate::Error::InvalidOfflineRenderRequest)
4523        ));
4524
4525        let mut invalid_frame = manifest;
4526        invalid_frame.frame_events[0].end_frame =
4527            invalid_frame.frame_events[0].end_frame.saturating_add(1);
4528        assert!(matches!(
4529            invalid_frame.validate(),
4530            Err(crate::Error::InvalidOfflineRenderRequest)
4531        ));
4532    }
4533
4534    #[test]
4535    fn routing_manifest_prefers_instrument_bus_and_isolates_metronome() {
4536        let mut score = Score::new("routing", 120, 4, 4, 0, 1);
4537        let mut instrument = crate::InstrumentDefinition::new("flute", "Flute");
4538        instrument.midi_channel = 2;
4539        instrument.midi_program = 73;
4540        score.parts[0].instrument = Some(instrument);
4541        score.parts[0].staves[0].measures[0].voices[0] =
4542            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
4543        let options = PlaybackOptions {
4544            metronome: Some(MetronomeConfig::default()),
4545            ..Default::default()
4546        };
4547        let mut config = PlaybackRoutingConfig {
4548            provider_identity: Some("sf2-host@1".into()),
4549            ..Default::default()
4550        };
4551        config.part_buses.insert(0, "parts".into());
4552        config
4553            .instrument_buses
4554            .insert("flute".into(), "winds".into());
4555        config.aux_sends.push(PlaybackAuxSend {
4556            source_bus: "winds".into(),
4557            destination_bus: "reverb".into(),
4558            gain_db: -12.0,
4559        });
4560        config.effect_routes.push(PlaybackEffectRoute {
4561            bus_id: "reverb".into(),
4562            effect_id: "convolution".into(),
4563            enabled: true,
4564        });
4565
4566        let manifest = build_playback_routing_manifest(&score, &options, &config)
4567            .expect("valid routing manifest");
4568        assert_eq!(manifest.contract_version, PLAYBACK_ROUTING_CONTRACT_VERSION);
4569        assert_eq!(manifest.provider_identity.as_deref(), Some("sf2-host@1"));
4570        assert!(manifest.routes.iter().any(|route| {
4571            route.instrument_id.as_deref() == Some("flute") && route.bus_id == "winds"
4572        }));
4573        assert!(
4574            manifest
4575                .routes
4576                .iter()
4577                .any(|route| route.is_metronome && route.bus_id == "metronome")
4578        );
4579        assert_eq!(manifest.aux_sends.len(), 1);
4580        assert_eq!(manifest.effect_routes.len(), 1);
4581    }
4582
4583    #[test]
4584    fn routing_manifest_rejects_unsafe_bus_and_non_finite_send_gain() {
4585        let score = Score::new("routing", 120, 4, 4, 0, 1);
4586        let config = PlaybackRoutingConfig {
4587            master_bus: "not a bus".into(),
4588            ..Default::default()
4589        };
4590        assert!(matches!(
4591            build_playback_routing_manifest(&score, &PlaybackOptions::default(), &config),
4592            Err(crate::Error::InvalidPlaybackRouting)
4593        ));
4594
4595        let mut config = PlaybackRoutingConfig::default();
4596        config.aux_sends.push(PlaybackAuxSend {
4597            source_bus: "part".into(),
4598            destination_bus: "master".into(),
4599            gain_db: f64::NAN,
4600        });
4601        assert!(matches!(
4602            build_playback_routing_manifest(&score, &PlaybackOptions::default(), &config),
4603            Err(crate::Error::InvalidPlaybackRouting)
4604        ));
4605    }
4606
4607    #[test]
4608    fn timing_corpus_reports_score_schedule_results_without_audio_claims() {
4609        let mut score = Score::new("corpus", 120, 4, 4, 0, 1);
4610        score.parts[0].staves[0].measures[0].voices[0] =
4611            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
4612        let expected_events = to_playback_events(&score, &PlaybackOptions::default());
4613        let report = evaluate_playback_timing_corpus(&[PlaybackTimingCase {
4614            id: "quarter-note".into(),
4615            score,
4616            options: PlaybackOptions::default(),
4617            expected_events,
4618            tolerance: PlaybackTimingTolerance::default(),
4619        }])
4620        .expect("valid timing corpus");
4621        assert_eq!(
4622            report.contract_version,
4623            PLAYBACK_TIMING_CORPUS_CONTRACT_VERSION
4624        );
4625        assert_eq!(report.total_cases, 1);
4626        assert_eq!(report.passed_cases, 1);
4627        assert!(report.cases[0].report.within_tolerance);
4628    }
4629
4630    #[test]
4631    fn timing_corpus_rejects_empty_or_duplicate_case_ids() {
4632        assert!(matches!(
4633            evaluate_playback_timing_corpus(&[]),
4634            Err(crate::Error::InvalidPlaybackTimingCorpus)
4635        ));
4636        let score = Score::new("corpus", 120, 4, 4, 0, 1);
4637        let case = PlaybackTimingCase {
4638            id: "duplicate".into(),
4639            expected_events: to_playback_events(&score, &PlaybackOptions::default()),
4640            score,
4641            options: PlaybackOptions::default(),
4642            tolerance: PlaybackTimingTolerance::default(),
4643        };
4644        assert!(matches!(
4645            evaluate_playback_timing_corpus(&[case.clone(), case]),
4646            Err(crate::Error::InvalidPlaybackTimingCorpus)
4647        ));
4648    }
4649
4650    fn comparison_event(time_secs: f64, duration_secs: f64) -> PlaybackEvent {
4651        PlaybackEvent {
4652            address: Some("0:0:0:0:0".into()),
4653            source: Some(NoteAddr {
4654                part: 0,
4655                staff: 0,
4656                measure: 0,
4657                voice: 0,
4658                note: 0,
4659            }),
4660            source_voice_number: None,
4661            time_beats: 0.0,
4662            time_secs,
4663            pitch_midi: 60,
4664            pitch_midi_cents: 6000,
4665            pitch_bend_curve: Vec::new(),
4666            post_note_pause_beats: 0.0,
4667            articulations: Vec::new(),
4668            chord_symbol: None,
4669            guitar_technique: None,
4670            velocity: 64,
4671            duration_beats: 1.0,
4672            duration_secs,
4673            pedal: false,
4674            part_index: 0,
4675            channel: 0,
4676            program: 0,
4677            instrument_id: None,
4678            is_metronome: false,
4679        }
4680    }
4681
4682    #[test]
4683    fn legacy_playback_event_json_defaults_bend_curve() {
4684        let event: PlaybackEvent = serde_json::from_str(
4685            r#"{"address":null,"source":null,"source_voice_number":null,"time_beats":0.0,"time_secs":0.0,"pitch_midi":60,"pitch_midi_cents":6000,"velocity":64,"duration_beats":1.0,"duration_secs":0.5,"pedal":false,"part_index":0,"channel":0,"is_metronome":false}"#,
4686        )
4687        .expect("legacy playback event remains readable");
4688        assert!(event.pitch_bend_curve.is_empty());
4689        assert_eq!(event.guitar_technique, None);
4690    }
4691
4692    #[test]
4693    fn tempo_ramp_uses_integrated_event_timing_and_carries_target_forward() {
4694        let mut score = Score::new("ramp", 120, 4, 4, 0, 2);
4695        for measure in &mut score.parts[0].staves[0].measures {
4696            measure.voices[0] = vec![
4697                crate::Note::new(crate::Pitch::new(crate::Step::C, 4), crate::Duration::Half),
4698                crate::Note::new(crate::Pitch::new(crate::Step::D, 4), crate::Duration::Half),
4699            ];
4700        }
4701        score.parts[0].staves[0].measures[0].tempo_ramp_to = Some(60);
4702        let events = to_playback_events(&score, &PlaybackOptions::default());
4703        assert_eq!(events.len(), 4);
4704        let expected_measure_secs = 4.0 * 60.0 / (60.0 - 120.0) * (60.0f64 / 120.0).ln();
4705        assert!((events[2].time_secs - expected_measure_secs).abs() < 1e-9);
4706        assert!((events[0].duration_secs - 1.1507282898).abs() < 1e-6);
4707        assert!((events[2].duration_secs - 2.0).abs() < 1e-9);
4708    }
4709
4710    #[test]
4711    fn breath_and_caesura_expose_deterministic_post_note_pause() {
4712        let mut score = Score::new("pause", 120, 4, 4, 0, 1);
4713        let mut breath = crate::Note::new(
4714            crate::Pitch::new(crate::Step::C, 4),
4715            crate::Duration::Quarter,
4716        );
4717        breath.articulations.push(Articulation::BreathMark);
4718        let mut caesura = crate::Note::new(
4719            crate::Pitch::new(crate::Step::D, 4),
4720            crate::Duration::Quarter,
4721        );
4722        caesura
4723            .articulations
4724            .extend([Articulation::BreathMark, Articulation::Caesura]);
4725        score.parts[0].staves[0].measures[0].voices[0] = vec![breath, caesura];
4726
4727        let events = to_playback_events(&score, &PlaybackOptions::default());
4728        assert_eq!(events.len(), 2);
4729        assert_eq!(events[0].post_note_pause_beats, 0.25);
4730        assert_eq!(events[1].post_note_pause_beats, 0.5);
4731        assert_eq!(
4732            events[1].articulations,
4733            vec![Articulation::BreathMark, Articulation::Caesura]
4734        );
4735    }
4736
4737    #[test]
4738    fn measure_instrument_change_resolves_on_playback_events() {
4739        let mut score = Score::new("instrument", 120, 4, 4, 0, 2);
4740        let mut base = crate::InstrumentDefinition::new("piano", "Piano");
4741        base.midi_channel = 1;
4742        base.midi_program = 0;
4743        score.parts[0].instrument = Some(base);
4744        let mut change = crate::InstrumentDefinition::new("flute", "Flute");
4745        change.midi_channel = 2;
4746        change.midi_program = 73;
4747        change.transpose_semitones = -2;
4748        score.parts[0].staves[0].measures[1].instrument_change = Some(change);
4749        for measure in &mut score.parts[0].staves[0].measures {
4750            measure.voices[0] = vec![crate::Note::new(
4751                crate::Pitch::new(crate::Step::C, 4),
4752                crate::Duration::Whole,
4753            )];
4754        }
4755
4756        let events = to_playback_events(&score, &PlaybackOptions::default());
4757        assert_eq!(events.len(), 2);
4758        assert_eq!(
4759            (
4760                events[0].channel,
4761                events[0].program,
4762                events[0].instrument_id.as_deref()
4763            ),
4764            (1, 0, Some("piano"))
4765        );
4766        assert_eq!(
4767            (
4768                events[1].channel,
4769                events[1].program,
4770                events[1].instrument_id.as_deref()
4771            ),
4772            (2, 73, Some("flute"))
4773        );
4774        assert_eq!(events[0].pitch_midi, 60);
4775        assert_eq!(events[1].pitch_midi, 58);
4776    }
4777
4778    #[test]
4779    fn generic_playback_event_preserves_authored_guitar_technique() {
4780        let mut score = Score::new("technique", 120, 4, 4, 0, 1);
4781        let mut note = Note::new(Pitch::new(Step::E, 4), Duration::Quarter);
4782        note.guitar_technique = Some(GuitarTechnique::HammerOn);
4783        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
4784
4785        let event = to_playback_events(&score, &PlaybackOptions::default())
4786            .into_iter()
4787            .next()
4788            .expect("one note event");
4789        assert_eq!(event.guitar_technique, Some(GuitarTechnique::HammerOn));
4790    }
4791
4792    #[test]
4793    fn playback_timing_comparison_reports_tolerance_and_identity() {
4794        let expected = [comparison_event(1.0, 0.5)];
4795        let actual = [comparison_event(1.004, 0.503)];
4796        let report = compare_playback_timing(
4797            &expected,
4798            &actual,
4799            &PlaybackTimingTolerance {
4800                start_secs: 0.005,
4801                duration_secs: 0.005,
4802            },
4803        )
4804        .expect("comparison");
4805        assert!(report.within_tolerance);
4806        assert_eq!(report.matched_events, 1);
4807        assert_eq!(
4808            report.contract_version,
4809            PLAYBACK_COMPARISON_CONTRACT_VERSION
4810        );
4811
4812        let mut typed_only = comparison_event(1.004, 0.503);
4813        typed_only.address = None;
4814        let report = compare_playback_timing(
4815            &expected,
4816            &[typed_only],
4817            &PlaybackTimingTolerance::default(),
4818        )
4819        .expect("typed source comparison");
4820        assert_eq!(report.matched_events, 1);
4821
4822        let actual = [comparison_event(1.02, 0.6)];
4823        let report =
4824            compare_playback_timing(&expected, &actual, &PlaybackTimingTolerance::default())
4825                .expect("comparison");
4826        assert!(!report.within_tolerance);
4827        assert!(
4828            report
4829                .mismatches
4830                .iter()
4831                .any(|m| matches!(m, PlaybackTimingMismatch::StartTime { index: 0, .. }))
4832        );
4833        assert!(
4834            report
4835                .mismatches
4836                .iter()
4837                .any(|m| matches!(m, PlaybackTimingMismatch::Duration { index: 0, .. }))
4838        );
4839    }
4840
4841    #[test]
4842    fn playback_timing_comparison_rejects_instrument_route_mismatch() {
4843        let expected = comparison_event(0.0, 0.5);
4844        let mut actual = expected.clone();
4845        actual.program = 73;
4846        assert!(
4847            compare_playback_timing(&[expected], &[actual], &PlaybackTimingTolerance::default(),)
4848                .expect("comparison")
4849                .mismatches
4850                .iter()
4851                .any(|mismatch| matches!(
4852                    mismatch,
4853                    PlaybackTimingMismatch::EventIdentity { index: 0 }
4854                ))
4855        );
4856    }
4857
4858    #[test]
4859    fn playback_timing_comparison_rejects_invalid_tolerance() {
4860        let error = compare_playback_timing(
4861            &[],
4862            &[],
4863            &PlaybackTimingTolerance {
4864                start_secs: -0.1,
4865                duration_secs: 0.0,
4866            },
4867        );
4868        assert!(matches!(
4869            error,
4870            Err(crate::Error::InvalidPlaybackComparison)
4871        ));
4872    }
4873
4874    #[test]
4875    fn tablature_performance_projection_keeps_position_and_reports_pitch_error() {
4876        let mut score = Score::new("Tab", 120, 4, 4, 0, 1);
4877        score.parts[0].staves[0].tablature = Some(super::super::notation::TablatureConfig {
4878            lines: 6,
4879            tuning_midi: vec![40, 45, 50, 55, 59, 64],
4880            capo: 0,
4881        });
4882        let notes = &mut score.parts[0].staves[0].measures[0].voices[0];
4883        *notes = vec![crate::Note::new(
4884            crate::Pitch::new(crate::Step::C, 4),
4885            crate::Duration::Quarter,
4886        )];
4887        notes[0].tab_position = Some(super::super::notation::TabPosition {
4888            string: 1,
4889            fret: 20,
4890        });
4891        notes[0].guitar_technique = Some(super::super::notation::GuitarTechnique::Bend);
4892        notes[0].guitar_bend_alter_cents = Some(150);
4893        notes[0].guitar_bend_curve = vec![
4894            super::super::score::GuitarBendPoint {
4895                position_per_mille: 0,
4896                alter_cents: 0,
4897            },
4898            super::super::score::GuitarBendPoint {
4899                position_per_mille: 500,
4900                alter_cents: 150,
4901            },
4902            super::super::score::GuitarBendPoint {
4903                position_per_mille: 1_000,
4904                alter_cents: 0,
4905            },
4906        ];
4907        let report = project_tablature_performance(&score, &PlaybackOptions::default())
4908            .expect("tablature projection");
4909        assert_eq!(report.events.len(), 1);
4910        assert_eq!(report.events[0].string, 1);
4911        assert_eq!(report.events[0].fret, 20);
4912        assert_eq!(
4913            report.events[0].technique,
4914            Some(super::super::notation::GuitarTechnique::Bend)
4915        );
4916        assert_eq!(report.events[0].bend_alter_cents, Some(150));
4917        assert_eq!(report.events[0].bend_curve.len(), 3);
4918        assert_eq!(report.events[0].bend_curve[1].position_per_mille, 500);
4919        assert_eq!(report.events[0].bend_curve[1].alter_cents, 150);
4920        assert_eq!(
4921            report.events[0].playback.pitch_bend_curve,
4922            report.events[0].bend_curve
4923        );
4924        assert!(report.diagnostics.is_empty());
4925
4926        score.parts[0].staves[0].measures[0].voices[0][0].tab_position =
4927            Some(super::super::notation::TabPosition {
4928                string: 1,
4929                fret: 19,
4930            });
4931        let report = project_tablature_performance(&score, &PlaybackOptions::default())
4932            .expect("tablature projection");
4933        assert_eq!(report.events[0].pitch_error_cents, 100);
4934        assert!(matches!(
4935            report.diagnostics[0],
4936            TablaturePerformanceDiagnostic::PitchMismatch {
4937                error_cents: 100,
4938                ..
4939            }
4940        ));
4941    }
4942
4943    #[test]
4944    fn tablature_performance_projection_does_not_invent_missing_positions() {
4945        let mut score = Score::new("Tab", 120, 4, 4, 0, 1);
4946        score.parts[0].staves[0].tablature = Some(super::super::notation::TablatureConfig {
4947            lines: 6,
4948            tuning_midi: vec![40, 45, 50, 55, 59, 64],
4949            capo: 0,
4950        });
4951        score.parts[0].staves[0].measures[0].voices[0].push(crate::Note::new(
4952            crate::Pitch::new(crate::Step::C, 4),
4953            crate::Duration::Quarter,
4954        ));
4955        let report = project_tablature_performance(&score, &PlaybackOptions::default())
4956            .expect("tablature projection");
4957        assert!(report.events.is_empty());
4958        assert!(matches!(
4959            report.diagnostics[0],
4960            TablaturePerformanceDiagnostic::MissingPosition { .. }
4961        ));
4962    }
4963
4964    #[test]
4965    fn tablature_performance_event_accepts_legacy_json_without_technique() {
4966        let mut score = Score::new("Tab", 120, 4, 4, 0, 1);
4967        score.parts[0].staves[0].tablature = Some(super::super::notation::TablatureConfig {
4968            lines: 6,
4969            tuning_midi: vec![40, 45, 50, 55, 59, 64],
4970            capo: 0,
4971        });
4972        let mut note = crate::Note::new(
4973            crate::Pitch::new(crate::Step::C, 4),
4974            crate::Duration::Quarter,
4975        );
4976        note.tab_position = Some(super::super::notation::TabPosition {
4977            string: 1,
4978            fret: 20,
4979        });
4980        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
4981        let report = project_tablature_performance(&score, &PlaybackOptions::default())
4982            .expect("tablature projection");
4983        let mut legacy = serde_json::to_value(&report.events[0]).expect("event JSON");
4984        legacy
4985            .as_object_mut()
4986            .expect("event object")
4987            .remove("technique");
4988        let restored: TablaturePerformanceEvent =
4989            serde_json::from_value(legacy).expect("legacy event JSON");
4990        assert_eq!(restored.technique, None);
4991    }
4992
4993    #[test]
4994    fn tablature_round_trip_report_preserves_authored_positions() {
4995        let mut score = Score::new("Tab", 120, 4, 4, 0, 1);
4996        score.parts[0].staves[0].tablature = Some(super::super::notation::TablatureConfig {
4997            lines: 6,
4998            tuning_midi: vec![40, 45, 50, 55, 59, 64],
4999            capo: 2,
5000        });
5001        let mut note = crate::Note::new(
5002            crate::Pitch::new(crate::Step::C, 4),
5003            crate::Duration::Quarter,
5004        );
5005        note.tab_positions = vec![crate::TabPosition { string: 5, fret: 1 }];
5006        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
5007        let report = tablature_round_trip_report(&score).expect("tab round-trip report");
5008        assert!(report.equivalent);
5009        assert_eq!(report.checked_notes, 1);
5010        assert_eq!(report.positioned_notes, 1);
5011        assert!(report.diagnostics.is_empty());
5012    }
5013
5014    #[test]
5015    fn tablature_performance_uses_measure_local_tuning_change() {
5016        let mut score = Score::new("Local tuning", 120, 4, 4, 0, 2);
5017        let staff = &mut score.parts[0].staves[0];
5018        staff.tablature = Some(super::super::notation::TablatureConfig {
5019            lines: 6,
5020            tuning_midi: vec![40, 45, 50, 55, 59, 64],
5021            capo: 0,
5022        });
5023        staff.measures[1].tablature_change = Some(super::super::notation::TablatureConfig {
5024            lines: 6,
5025            tuning_midi: vec![38, 45, 50, 55, 59, 64],
5026            capo: 0,
5027        });
5028        let mut note = Note::new(Pitch::new(Step::C, 3), Duration::Quarter);
5029        note.tab_position = Some(TabPosition {
5030            string: 1,
5031            fret: 10,
5032        });
5033        staff.measures[1].voices[0] = vec![note];
5034
5035        let report = project_tablature_performance(&score, &PlaybackOptions::default())
5036            .expect("tablature projection");
5037        assert_eq!(report.events.len(), 1);
5038        assert_eq!(report.events[0].expected_pitch_midi_cents, 4_800);
5039        assert!(!report.diagnostics.iter().any(|diagnostic| matches!(
5040            diagnostic,
5041            TablaturePerformanceDiagnostic::PitchMismatch { .. }
5042        )));
5043    }
5044}