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/// acorde does not encode audio; this keeps the requested output explicit in the deterministic
472/// schedule handed to a Composer or other 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, 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 and accumulates the sounding duration of each contiguous segment. Malformed
2415/// or non-contiguous tie endings remain as independent events so playback never silently drops
2416/// a note.
2417fn merge_tied_events(score: &Score, events: Vec<PlaybackEvent>) -> Vec<PlaybackEvent> {
2418    use std::collections::HashMap;
2419
2420    struct PendingTie {
2421        index: usize,
2422        staff: usize,
2423        voice: usize,
2424    }
2425
2426    let mut merged = Vec::with_capacity(events.len());
2427    let mut pending: HashMap<(usize, i32), Vec<PendingTie>> = HashMap::new();
2428    for event in events {
2429        let Some(source) = event.source.as_ref() else {
2430            merged.push(event);
2431            continue;
2432        };
2433        let tied_staff = score
2434            .parts
2435            .get(source.part)
2436            .and_then(|part| part.staves.get(source.staff));
2437        let tied_note = tied_staff
2438            .and_then(|staff| staff.measures.get(source.measure))
2439            .and_then(|measure| measure.voices.get(source.voice))
2440            .and_then(|voice| voice.get(source.note));
2441        let (Some(staff), Some(note)) = (tied_staff, tied_note) else {
2442            merged.push(event);
2443            continue;
2444        };
2445        // A chord may tie only some of its pitches: use the flags of the pitch that sounds here.
2446        let transpose_cents = i32::from(staff.transpose_semitones) * 100;
2447        let pitch_index = note
2448            .pitches
2449            .iter()
2450            .position(|pitch| pitch.to_midi_cents() + transpose_cents == event.pitch_midi_cents);
2451        let (tie_start, tie_end) = match pitch_index {
2452            Some(index) => (note.pitch_tie_start(index), note.pitch_tie_end(index)),
2453            None => (note.tie_start, note.tie_end),
2454        };
2455        let source_staff = source.staff;
2456        let source_voice = source.voice;
2457        let key = (source.part, event.pitch_midi_cents);
2458        if let Some(candidates) = pending.get_mut(&key) {
2459            candidates.retain(|candidate| {
2460                let previous: &PlaybackEvent = &merged[candidate.index];
2461                previous.time_beats + previous.duration_beats >= event.time_beats - 1e-9
2462            });
2463            if tie_end {
2464                let matching = candidates
2465                    .iter()
2466                    .enumerate()
2467                    .filter(|(_, candidate)| {
2468                        let previous: &PlaybackEvent = &merged[candidate.index];
2469                        (previous.time_beats + previous.duration_beats - event.time_beats).abs()
2470                            < 1e-9
2471                    })
2472                    .max_by_key(|(_, candidate)| {
2473                        (
2474                            candidate.staff == source.staff,
2475                            candidate.voice == source.voice,
2476                        )
2477                    })
2478                    .map(|(position, _)| position);
2479                if let Some(position) = matching {
2480                    let mut candidate = candidates.remove(position);
2481                    let previous = &mut merged[candidate.index];
2482                    previous.duration_beats += event.duration_beats;
2483                    previous.duration_secs += event.duration_secs;
2484                    if tie_start {
2485                        candidate.staff = source.staff;
2486                        candidate.voice = source.voice;
2487                        candidates.push(candidate);
2488                    }
2489                    continue;
2490                }
2491            }
2492        }
2493
2494        let index = merged.len();
2495        merged.push(event);
2496        if tie_start {
2497            pending.entry(key).or_default().push(PendingTie {
2498                index,
2499                staff: source_staff,
2500                voice: source_voice,
2501            });
2502        }
2503    }
2504    merged
2505}
2506
2507/// Convert a score into playback events while enforcing the host-comparison event bound.
2508pub fn to_playback_events_bounded(
2509    score: &Score,
2510    options: &PlaybackOptions,
2511) -> Result<Vec<PlaybackEvent>, crate::Error> {
2512    let events = to_playback_events(score, options);
2513    if events.len() > MAX_PLAYBACK_COMPARISON_EVENTS {
2514        return Err(crate::Error::PlaybackComparisonTooLarge(events.len()));
2515    }
2516    Ok(events)
2517}
2518
2519// ── PlaybackPosition + compute_playback_position ──────────────────────────────
2520
2521/// Score position at a specific elapsed time.
2522#[derive(Debug, Clone, Serialize, Deserialize)]
2523pub struct PlaybackPosition {
2524    /// Physical measure index (0-based), same coordinate space as [`PlaybackEvent`] fields.
2525    pub measure_index: usize,
2526    /// Beat offset within the measure (`0.0 … time_sig.total_beats()`).
2527    pub beat: f64,
2528}
2529
2530struct MeasureSegment {
2531    measure_idx: usize,
2532    start_secs: f64,
2533    duration_secs: f64,
2534    beats: f64,
2535    bpm: f64,
2536    ramp_to_bpm: Option<f64>,
2537}
2538
2539fn build_measure_segments(score: &Score, options: &PlaybackOptions) -> Vec<MeasureSegment> {
2540    let init_bpm = initial_tempo_bpm(score, options);
2541    let tempo_marks = score_tempo_marks(score);
2542    let full_seq = measure_sequence(score);
2543    let seq: Vec<usize> = if let Some((lo, hi)) = options.loop_region {
2544        full_seq
2545            .into_iter()
2546            .filter(|&i| i >= lo && i <= hi)
2547            .collect()
2548    } else {
2549        full_seq
2550    };
2551
2552    let mut segments = Vec::with_capacity(seq.len());
2553    let mut cursor_secs = 0.0f64;
2554    let mut current_bpm = init_bpm;
2555
2556    for idx in seq {
2557        let mark = tempo_marks.get(idx).copied().unwrap_or_default();
2558        if let Some(t) = mark.bpm.and_then(|tempo| written_tempo_bpm(options, tempo)) {
2559            current_bpm = t;
2560        }
2561        let beats = score.playback_measure_beats(idx);
2562        let ramp_to_bpm = written_tempo_ramp_bpm(options, mark.ramp_to_bpm);
2563        let duration_secs = tempo_ramp_seconds(current_bpm, ramp_to_bpm, beats, beats);
2564
2565        segments.push(MeasureSegment {
2566            measure_idx: idx,
2567            start_secs: cursor_secs,
2568            duration_secs,
2569            beats,
2570            bpm: current_bpm,
2571            ramp_to_bpm,
2572        });
2573        cursor_secs += duration_secs;
2574        if let Some(end_bpm) = ramp_to_bpm {
2575            current_bpm = end_bpm;
2576        }
2577    }
2578    segments
2579}
2580
2581/// Map `elapsed_secs` to a position within the score.
2582///
2583/// Returns `None` if `elapsed_secs` is negative or past the end of the last measure.
2584/// Pass the same [`PlaybackOptions`] used for [`to_playback_events`] so that `loop_region`
2585/// and tempo overrides are applied consistently.
2586pub fn compute_playback_position(
2587    score: &Score,
2588    options: &PlaybackOptions,
2589    elapsed_secs: f64,
2590) -> Option<PlaybackPosition> {
2591    if elapsed_secs < 0.0 {
2592        return None;
2593    }
2594    let segments = build_measure_segments(score, options);
2595    for seg in &segments {
2596        if elapsed_secs < seg.start_secs + seg.duration_secs + 1e-9 {
2597            let beat = tempo_ramp_beats_at_seconds(
2598                seg.bpm,
2599                seg.ramp_to_bpm,
2600                seg.beats,
2601                elapsed_secs - seg.start_secs,
2602            )
2603            .clamp(0.0, seg.beats);
2604            return Some(PlaybackPosition {
2605                measure_index: seg.measure_idx,
2606                beat,
2607            });
2608        }
2609    }
2610    None
2611}
2612
2613#[cfg(test)]
2614mod tests {
2615    use super::*;
2616    use crate::model::{
2617        duration::Duration,
2618        pitch::{Pitch, Step},
2619        score::{MidiAftertouch, MidiControlChange, MidiPitchBend, MidiProgramChange, Note, Score},
2620    };
2621
2622    fn opts(bpm: Option<u16>) -> PlaybackOptions {
2623        PlaybackOptions {
2624            bpm_override: bpm,
2625            ..Default::default()
2626        }
2627    }
2628
2629    #[test]
2630    fn playback_options_accepts_an_empty_json_object_as_defaults() {
2631        let parsed: PlaybackOptions = serde_json::from_str("{}").expect("default playback options");
2632        assert_eq!(parsed, PlaybackOptions::default());
2633    }
2634
2635    #[test]
2636    fn bounded_playback_events_match_unbounded_schedule_within_limit() {
2637        let score = Score::new("bounded", 120, 4, 4, 0, 1);
2638        let options = opts(Some(120));
2639        let unbounded = to_playback_events(&score, &options);
2640        let bounded = to_playback_events_bounded(&score, &options).expect("bounded schedule");
2641        assert_eq!(bounded, unbounded);
2642    }
2643
2644    #[test]
2645    fn bars_after_a_meter_change_keep_the_new_meter() {
2646        use crate::model::duration::Duration;
2647        use crate::{Note, Pitch, Step, TimeSignature};
2648        let mut score = Score::new("meter", 120, 4, 4, 0, 3);
2649        let staff = &mut score.parts[0].staves[0];
2650        staff.measures[1].time_sig = Some(TimeSignature {
2651            numerator: 3,
2652            denominator: 4,
2653        });
2654        for measure in &mut staff.measures {
2655            measure.voices[0] = vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
2656        }
2657        let onsets: Vec<f64> = to_playback_events(&score, &opts(Some(120)))
2658            .iter()
2659            .filter(|event| event.address.is_some())
2660            .map(|event| event.time_beats)
2661            .collect();
2662        // 4/4, then two bars of 3/4: the third bar starts at 4 + 3, not 4 + 4.
2663        assert_eq!(onsets, vec![0.0, 4.0, 7.0]);
2664    }
2665
2666    #[test]
2667    fn tempo_written_on_either_part_governs_the_whole_score() {
2668        let mut score = Score::new("shared tempo", 120, 4, 4, 0, 2);
2669        let mut second = score.parts[0].clone();
2670        second.id = "second".into();
2671        score.parts.push(second);
2672        for part in &mut score.parts {
2673            for measure in &mut part.staves[0].measures {
2674                measure.voices[0] = vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
2675            }
2676        }
2677        score.parts[0].staves[0].measures[0].tempo = Some(92);
2678        score.parts[1].staves[0].measures[1].tempo = Some(60);
2679        let options = PlaybackOptions {
2680            metronome: Some(MetronomeConfig::default()),
2681            ..Default::default()
2682        };
2683        let events = to_playback_events(&score, &options);
2684        for part_index in 0..2 {
2685            let first = events
2686                .iter()
2687                .find(|event| {
2688                    event.part_index == part_index
2689                        && event
2690                            .source
2691                            .as_ref()
2692                            .is_some_and(|source| source.measure == 0)
2693                })
2694                .unwrap();
2695            let second = events
2696                .iter()
2697                .find(|event| {
2698                    event.part_index == part_index
2699                        && event
2700                            .source
2701                            .as_ref()
2702                            .is_some_and(|source| source.measure == 1)
2703                })
2704                .unwrap();
2705            assert!((first.duration_secs - 60.0 / 92.0).abs() < 1e-9);
2706            assert!((second.time_secs - 4.0 * 60.0 / 92.0).abs() < 1e-9);
2707            assert!((second.duration_secs - 1.0).abs() < 1e-9);
2708        }
2709        let clicks: Vec<_> = events.iter().filter(|event| event.is_metronome).collect();
2710        assert!((clicks[1].time_secs - 60.0 / 92.0).abs() < 1e-9);
2711        assert!((clicks[4].time_secs - 4.0 * 60.0 / 92.0).abs() < 1e-9);
2712        let position = compute_playback_position(&score, &options, 1.5 * 60.0 / 92.0).unwrap();
2713        assert_eq!(position.measure_index, 0);
2714        assert!((position.beat - 1.5).abs() < 1e-9);
2715        let timeline_1 = offline_measure_times(&score, &options, 1, 0, &score_tempo_marks(&score));
2716        assert!((timeline_1[0].bpm - 92.0).abs() < 1e-9);
2717        assert!((timeline_1[1].bpm - 60.0).abs() < 1e-9);
2718    }
2719
2720    #[test]
2721    fn empty_score_no_events() {
2722        let score = Score::new("T", 120, 4, 4, 0, 1);
2723        assert!(to_playback_events(&score, &opts(None)).is_empty());
2724    }
2725
2726    #[test]
2727    fn single_note_at_beat_zero() {
2728        let mut score = Score::new("T", 120, 4, 4, 0, 1);
2729        score.parts[0].staves[0].measures[0].voices[0] =
2730            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
2731        let events = to_playback_events(&score, &opts(None));
2732        assert_eq!(events.len(), 1);
2733        assert_eq!(events[0].address.as_deref(), Some("0:0:0:0:0"));
2734        assert_eq!(
2735            events[0].source,
2736            Some(NoteAddr {
2737                part: 0,
2738                staff: 0,
2739                measure: 0,
2740                voice: 0,
2741                note: 0,
2742            })
2743        );
2744        assert!((events[0].time_beats).abs() < 1e-9);
2745        assert_eq!(events[0].pitch_midi, 60);
2746        assert_eq!(events[0].velocity, 64);
2747        assert!((events[0].duration_beats - 1.0).abs() < 1e-9);
2748        assert_eq!(events[0].part_index, 0);
2749    }
2750
2751    #[test]
2752    fn tied_notes_are_one_continuous_playback_event() {
2753        let mut score = Score::new("T", 120, 4, 4, 0, 1);
2754        let mut first = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
2755        first.tie_start = true;
2756        let mut second = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
2757        second.tie_end = true;
2758        score.parts[0].staves[0].measures[0].voices[0] = vec![first, second];
2759
2760        let events = to_playback_events(&score, &opts(None));
2761        assert_eq!(events.len(), 1);
2762        assert_eq!(
2763            events[0].source.as_ref().map(|address| address.note),
2764            Some(0)
2765        );
2766        assert!((events[0].time_beats).abs() < 1e-9);
2767        assert!((events[0].duration_beats - 2.0).abs() < 1e-9);
2768        assert!((events[0].duration_secs - 1.0).abs() < 1e-9);
2769    }
2770
2771    #[test]
2772    fn a_tie_on_one_chord_pitch_holds_only_that_pitch() {
2773        let mut score = Score::new("T", 120, 4, 4, 0, 1);
2774        // C–G chord tied on C only into another C–G chord: G re-strikes, C sustains.
2775        let chord = || {
2776            let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
2777            note.pitches.push(Pitch::new(Step::G, 4));
2778            note
2779        };
2780        let mut first = chord();
2781        first.set_pitch_ties(&[true, false], &[false, false]);
2782        let mut second = chord();
2783        second.set_pitch_ties(&[false, false], &[true, false]);
2784        assert!(first.tie_start && second.tie_end);
2785        score.parts[0].staves[0].measures[0].voices[0] = vec![first, second];
2786
2787        let events = to_playback_events(&score, &opts(None));
2788        let durations = |midi: u8| {
2789            events
2790                .iter()
2791                .filter(|event| event.pitch_midi == midi)
2792                .map(|event| event.duration_beats)
2793                .collect::<Vec<_>>()
2794        };
2795        assert_eq!(durations(60), vec![2.0]);
2796        assert_eq!(durations(67), vec![1.0, 1.0]);
2797    }
2798
2799    #[test]
2800    fn ties_cross_measure_boundaries_and_tempo_changes_without_retriggering() {
2801        let mut score = Score::new("T", 120, 4, 4, 0, 2);
2802        let first_measure = &mut score.parts[0].staves[0].measures[0];
2803        let mut first = Note::new(Pitch::new(Step::C, 4), Duration::Whole);
2804        first.tie_start = true;
2805        first_measure.voices[0] = vec![first];
2806
2807        let second_measure = &mut score.parts[0].staves[0].measures[1];
2808        second_measure.tempo = Some(60);
2809        let mut second = Note::new(Pitch::new(Step::C, 4), Duration::Whole);
2810        second.tie_end = true;
2811        second_measure.voices[0] = vec![second];
2812
2813        let events = to_playback_events(&score, &opts(None));
2814        assert_eq!(events.len(), 1);
2815        assert_eq!(
2816            events[0].source.as_ref().map(|address| address.measure),
2817            Some(0)
2818        );
2819        assert!((events[0].time_beats).abs() < 1e-9);
2820        assert!((events[0].duration_beats - 8.0).abs() < 1e-9);
2821        assert!((events[0].duration_secs - 6.0).abs() < 1e-9);
2822    }
2823
2824    #[test]
2825    fn ties_continue_across_voice_and_staff_changes() {
2826        let whole_c = || Note::new(Pitch::new(Step::C, 4), Duration::Whole);
2827
2828        let mut voice_score = Score::new("voice change", 120, 4, 4, 0, 2);
2829        let mut start = whole_c();
2830        start.tie_start = true;
2831        let mut end = whole_c();
2832        end.tie_end = true;
2833        voice_score.parts[0].staves[0].measures[0].voices[0] = vec![start.clone()];
2834        voice_score.parts[0].staves[0].measures[1].voices[1] = vec![end.clone()];
2835        let events = to_playback_events(&voice_score, &opts(None));
2836        assert_eq!(events.len(), 1);
2837        assert_eq!(events[0].time_beats, 0.0);
2838        assert_eq!(events[0].duration_beats, 8.0);
2839
2840        let mut staff_score = Score::new("staff change", 120, 4, 4, 0, 2);
2841        let second_staff = staff_score.parts[0].staves[0].clone();
2842        staff_score.parts[0].staves.push(second_staff);
2843        staff_score.parts[0].staves[0].measures[0].voices[0] = vec![start];
2844        staff_score.parts[0].staves[1].measures[1].voices[0] = vec![end];
2845        let events = to_playback_events(&staff_score, &opts(None));
2846        assert_eq!(events.len(), 1);
2847        assert_eq!(events[0].time_beats, 0.0);
2848        assert_eq!(events[0].duration_beats, 8.0);
2849    }
2850
2851    #[test]
2852    fn cross_voice_tie_keeps_independent_unison_attacks() {
2853        let mut score = Score::new("unison", 120, 4, 4, 0, 2);
2854        let mut start = Note::new(Pitch::new(Step::C, 4), Duration::Whole);
2855        start.tie_start = true;
2856        let mut end = Note::new(Pitch::new(Step::C, 4), Duration::Whole);
2857        end.tie_end = true;
2858        score.parts[0].staves[0].measures[0].voices[0] = vec![start];
2859        score.parts[0].staves[0].measures[0].voices[1] =
2860            vec![Note::new(Pitch::new(Step::C, 4), Duration::Whole)];
2861        score.parts[0].staves[0].measures[1].voices[1] = vec![end];
2862        score.parts[0].staves[0].measures[1].voices[2] =
2863            vec![Note::new(Pitch::new(Step::C, 4), Duration::Whole)];
2864
2865        let mut durations: Vec<_> = to_playback_events(&score, &opts(None))
2866            .into_iter()
2867            .map(|event| event.duration_beats)
2868            .collect();
2869        durations.sort_by(f64::total_cmp);
2870        assert_eq!(durations, vec![4.0, 4.0, 8.0]);
2871    }
2872
2873    #[test]
2874    fn malformed_tie_end_does_not_drop_playback_event() {
2875        let mut score = Score::new("T", 120, 4, 4, 0, 1);
2876        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
2877        note.tie_end = true;
2878        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
2879        let events = to_playback_events(&score, &opts(None));
2880        assert_eq!(events.len(), 1);
2881        assert!((events[0].duration_beats - 1.0).abs() < 1e-9);
2882    }
2883
2884    #[test]
2885    fn microtonal_playback_event_keeps_exact_midi_cents() {
2886        let mut score = Score::new("T", 120, 4, 4, 0, 1);
2887        score.parts[0].staves[0].measures[0].voices[0] = vec![Note::new(
2888            Pitch::with_microtone(Step::C, 4, 0, 50),
2889            Duration::Quarter,
2890        )];
2891        let events = to_playback_events(&score, &opts(None));
2892        assert_eq!(events[0].pitch_midi, 61);
2893        assert_eq!(events[0].pitch_midi_cents, 6050);
2894    }
2895
2896    #[test]
2897    fn chord_expands_to_multiple_events() {
2898        let mut score = Score::new("T", 120, 4, 4, 0, 1);
2899        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
2900        note.pitches.push(Pitch::new(Step::E, 4));
2901        note.pitches.push(Pitch::new(Step::G, 4));
2902        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
2903        let events = to_playback_events(&score, &opts(None));
2904        assert_eq!(events.len(), 3);
2905        assert!(
2906            events
2907                .iter()
2908                .all(|event| event.address.as_deref() == Some("0:0:0:0:0"))
2909        );
2910        assert!(events.iter().all(|e| e.time_beats.abs() < 1e-9));
2911    }
2912
2913    #[test]
2914    fn playback_events_preserve_authored_chord_symbol_without_inventing_notes() {
2915        let mut score = Score::new("Harmony", 120, 4, 4, 0, 1);
2916        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
2917        note.chord_symbol = Some(ChordSymbol {
2918            root: "C".into(),
2919            kind: "major-seventh".into(),
2920            bass: Some("E".into()),
2921            placement: None,
2922            extender: false,
2923            harmonic_degree: None,
2924            harmony_function: None,
2925            harmony_type: None,
2926            chord_ref: None,
2927            range_end: None,
2928            degrees: Vec::new(),
2929        });
2930        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
2931
2932        let events = to_playback_events(&score, &PlaybackOptions::default());
2933        assert_eq!(events.len(), 1);
2934        assert_eq!(events[0].pitch_midi, 60);
2935        assert_eq!(
2936            events[0]
2937                .chord_symbol
2938                .as_ref()
2939                .map(ChordSymbol::display_text),
2940            Some("Cmaj7/E".into())
2941        );
2942    }
2943
2944    #[test]
2945    fn authored_realization_default_keeps_ornament_as_one_semantic_event() {
2946        let mut score = Score::new("authored ornament", 120, 4, 4, 0, 1);
2947        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
2948        note.articulations.push(Articulation::Trill);
2949        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
2950
2951        let events = to_playback_events(&score, &PlaybackOptions::default());
2952        assert_eq!(events.len(), 1);
2953        assert_eq!(events[0].pitch_midi, 60);
2954        assert_eq!(events[0].articulations, vec![Articulation::Trill]);
2955    }
2956
2957    #[test]
2958    fn ornament_arpeggio_profile_realizes_trill_with_pinned_timing() {
2959        let mut score = Score::new("realized ornament", 120, 4, 4, 0, 1);
2960        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
2961        note.articulations.push(Articulation::Trill);
2962        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
2963
2964        let events = to_playback_events(
2965            &score,
2966            &PlaybackOptions {
2967                realization_profile: PlaybackRealizationProfile::OrnamentArpeggioV1,
2968                ..Default::default()
2969            },
2970        );
2971        assert_eq!(events.len(), 4);
2972        assert_eq!(
2973            events
2974                .iter()
2975                .map(|event| event.pitch_midi)
2976                .collect::<Vec<_>>(),
2977            vec![60, 61, 60, 61]
2978        );
2979        for (index, event) in events.iter().enumerate() {
2980            assert!((event.time_beats - index as f64 * 0.25).abs() < 1e-9);
2981            assert!((event.duration_beats - 0.25).abs() < 1e-9);
2982            assert!((event.time_secs - index as f64 * 0.125).abs() < 1e-9);
2983            assert!((event.duration_secs - 0.125).abs() < 1e-9);
2984        }
2985    }
2986
2987    #[test]
2988    fn ornament_arpeggio_profile_staggers_chord_in_authored_direction() {
2989        let mut score = Score::new("realized arpeggio", 120, 4, 4, 0, 1);
2990        let mut chord = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
2991        chord.pitches.push(Pitch::new(Step::E, 4));
2992        chord.pitches.push(Pitch::new(Step::G, 4));
2993        chord.arpeggiate = Some(false);
2994        score.parts[0].staves[0].measures[0].voices[0] = vec![chord];
2995
2996        let events = to_playback_events(
2997            &score,
2998            &PlaybackOptions {
2999                realization_profile: PlaybackRealizationProfile::OrnamentArpeggioV1,
3000                ..Default::default()
3001            },
3002        );
3003        assert_eq!(events.len(), 3);
3004        let by_pitch: BTreeMap<_, _> = events
3005            .iter()
3006            .map(|event| (event.pitch_midi, event.time_beats))
3007            .collect();
3008        assert!((by_pitch[&67] - 0.0).abs() < 1e-9);
3009        assert!((by_pitch[&64] - 0.09).abs() < 1e-9);
3010        assert!((by_pitch[&60] - 0.18).abs() < 1e-9);
3011    }
3012
3013    #[test]
3014    fn grace_notes_excluded() {
3015        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3016        let mut grace = Note::new(Pitch::new(Step::D, 4), Duration::Eighth);
3017        grace.is_grace = true;
3018        let regular = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3019        score.parts[0].staves[0].measures[0].voices[0] = vec![grace, regular];
3020        let events = to_playback_events(&score, &opts(None));
3021        assert_eq!(events.len(), 1);
3022        assert_eq!(events[0].pitch_midi, 60);
3023    }
3024
3025    #[test]
3026    fn metronome_events_have_no_source_address() {
3027        let score = Score::new("T", 120, 4, 4, 0, 1);
3028        let options = PlaybackOptions {
3029            metronome: Some(MetronomeConfig::default()),
3030            ..Default::default()
3031        };
3032        let events = to_playback_events(&score, &options);
3033        assert!(!events.is_empty());
3034        assert!(events.iter().all(|event| event.address.is_none()));
3035    }
3036
3037    #[test]
3038    fn second_note_has_correct_time() {
3039        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3040        score.parts[0].staves[0].measures[0].voices[0] = vec![
3041            Note::new(Pitch::new(Step::C, 4), Duration::Quarter),
3042            Note::new(Pitch::new(Step::D, 4), Duration::Quarter),
3043        ];
3044        let events = to_playback_events(&score, &opts(None));
3045        assert_eq!(events.len(), 2);
3046        assert!((events[0].time_beats).abs() < 1e-9);
3047        assert!((events[1].time_beats - 1.0).abs() < 1e-9);
3048    }
3049
3050    #[test]
3051    fn sparse_voice_keeps_measure_boundaries() {
3052        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3053        let note = || Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3054        score.parts[0].staves[0].measures[0].voices[1] = vec![note()];
3055        score.parts[0].staves[0].measures[1].voices[1] = vec![note()];
3056
3057        let events = to_playback_events(&score, &opts(None));
3058        assert_eq!(events.len(), 2);
3059        assert!((events[0].time_beats).abs() < 1e-9);
3060        assert!((events[1].time_beats - 4.0).abs() < 1e-9);
3061        assert!((events[1].time_secs - 2.0).abs() < 1e-9);
3062    }
3063
3064    #[test]
3065    fn time_secs_120_bpm_quarter_note_is_half_second() {
3066        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3067        score.parts[0].staves[0].measures[0].voices[0] =
3068            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3069        let events = to_playback_events(&score, &opts(None));
3070        assert!((events[0].time_secs).abs() < 1e-9);
3071        assert!((events[0].duration_secs - 0.5).abs() < 1e-9);
3072    }
3073
3074    #[test]
3075    fn bpm_override_changes_time_secs() {
3076        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3077        score.parts[0].staves[0].measures[0].voices[0] = vec![
3078            Note::new(Pitch::new(Step::C, 4), Duration::Quarter),
3079            Note::new(Pitch::new(Step::D, 4), Duration::Quarter),
3080        ];
3081        let events = to_playback_events(&score, &opts(Some(60)));
3082        assert!((events[0].time_secs).abs() < 1e-9);
3083        assert!((events[1].time_secs - 1.0).abs() < 1e-9);
3084    }
3085
3086    #[test]
3087    fn tempo_multiplier_preserves_written_tempo_changes_and_ramps() {
3088        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3089        score.parts[0].staves[0].measures[0].tempo_ramp_to = Some(60);
3090        score.parts[0].staves[0].measures[1].tempo = Some(90);
3091        score.parts[0].staves[0].measures[0].voices[0] =
3092            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3093        score.parts[0].staves[0].measures[1].voices[0] =
3094            vec![Note::new(Pitch::new(Step::D, 4), Duration::Quarter)];
3095        let options = PlaybackOptions {
3096            tempo_multiplier: 0.5,
3097            ..Default::default()
3098        };
3099
3100        let events = to_playback_events(&score, &options);
3101        let second_measure_start = tempo_ramp_seconds(60.0, Some(30.0), 4.0, 4.0);
3102        assert!((events[1].time_secs - second_measure_start).abs() < 1e-9);
3103
3104        let one_beat_into_ramp = tempo_ramp_seconds(60.0, Some(30.0), 4.0, 1.0);
3105        let position = compute_playback_position(&score, &options, one_beat_into_ramp).unwrap();
3106        assert_eq!(position.measure_index, 0);
3107        assert!((position.beat - 1.0).abs() < 1e-9);
3108
3109        let second_measure_position =
3110            compute_playback_position(&score, &options, second_measure_start + 60.0 / 45.0)
3111                .unwrap();
3112        assert_eq!(second_measure_position.measure_index, 1);
3113        assert!((second_measure_position.beat - 1.0).abs() < 1e-9);
3114    }
3115
3116    #[test]
3117    fn bpm_override_suppresses_written_tempo_changes_and_ramps() {
3118        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3119        score.parts[0].staves[0].measures[0].tempo_ramp_to = Some(60);
3120        score.parts[0].staves[0].measures[1].tempo = Some(90);
3121        score.parts[0].staves[0].measures[0].voices[0] =
3122            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3123        score.parts[0].staves[0].measures[1].voices[0] =
3124            vec![Note::new(Pitch::new(Step::D, 4), Duration::Quarter)];
3125        let options = PlaybackOptions {
3126            bpm_override: Some(120),
3127            ..Default::default()
3128        };
3129
3130        let events = to_playback_events(&score, &options);
3131        assert!((events[1].time_secs - 2.0).abs() < 1e-9);
3132        let position = compute_playback_position(&score, &options, 2.5).unwrap();
3133        assert_eq!(position.measure_index, 1);
3134        assert!((position.beat - 1.0).abs() < 1e-9);
3135    }
3136
3137    #[test]
3138    fn playback_position_tracks_repeats_rests_and_meter_changes_with_a_tempo_multiplier() {
3139        use crate::model::notation::{Barline, TimeSignature};
3140
3141        let mut score = Score::new("transport", 120, 4, 4, 0, 3);
3142        let staff = &mut score.parts[0].staves[0];
3143        staff.measures[0].barline_left = Barline::RepeatStart;
3144        staff.measures[1].time_sig = Some(TimeSignature {
3145            numerator: 3,
3146            denominator: 4,
3147        });
3148        staff.measures[2].barline_right = Barline::RepeatEnd;
3149        staff.measures[0].voices[0] = vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3150        staff.measures[1].voices[0] = vec![Note::rest(Duration::Quarter)];
3151        staff.measures[2].voices[0] = vec![Note::new(Pitch::new(Step::D, 4), Duration::Quarter)];
3152        let options = PlaybackOptions {
3153            tempo_multiplier: 0.5,
3154            ..Default::default()
3155        };
3156
3157        let events = to_playback_events(&score, &options);
3158        let note_starts: Vec<f64> = events
3159            .iter()
3160            .filter(|event| event.address.is_some())
3161            .map(|event| event.time_secs)
3162            .collect();
3163        // 4/4 (4s), then 3/4 rest (3s) and note (3s). The repeat restarts at 10s.
3164        assert_eq!(note_starts, vec![0.0, 7.0, 10.0, 17.0]);
3165
3166        let middle = compute_playback_position(&score, &options, 5.0).unwrap();
3167        assert_eq!(middle.measure_index, 1);
3168        assert!((middle.beat - 1.0).abs() < 1e-9);
3169
3170        let repeated = compute_playback_position(&score, &options, 10.5).unwrap();
3171        assert_eq!(repeated.measure_index, 0);
3172        assert!((repeated.beat - 0.5).abs() < 1e-9);
3173    }
3174
3175    #[test]
3176    fn transpose_semitones_shifts_midi_output() {
3177        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3178        score.parts[0].staves[0].transpose_semitones = -2;
3179        score.parts[0].staves[0].measures[0].voices[0] =
3180            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3181        let events = to_playback_events(&score, &opts(None));
3182        assert_eq!(events.len(), 1);
3183        assert_eq!(events[0].pitch_midi, 58);
3184    }
3185
3186    #[test]
3187    fn percussion_channel_9_ignores_transpose_semitones() {
3188        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3189        score.parts[0].midi_channel = 9;
3190        score.parts[0].staves[0].transpose_semitones = -2;
3191        score.parts[0].staves[0].measures[0].voices[0] =
3192            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3193        let events = to_playback_events(&score, &opts(None));
3194        assert_eq!(events.len(), 1);
3195        assert_eq!(events[0].pitch_midi, 60);
3196    }
3197
3198    #[test]
3199    fn staccato_halves_duration_beats() {
3200        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3201        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3202        note.articulations
3203            .push(crate::model::notation::Articulation::Staccato);
3204        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3205        let events = to_playback_events(&score, &opts(None));
3206        assert_eq!(events.len(), 1);
3207        assert!((events[0].duration_beats - 0.5).abs() < 1e-9);
3208    }
3209
3210    #[test]
3211    fn staccatissimo_also_halves_duration() {
3212        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3213        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3214        note.articulations
3215            .push(crate::model::notation::Articulation::Staccatissimo);
3216        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3217        let events = to_playback_events(&score, &opts(None));
3218        assert!((events[0].duration_beats - 0.5).abs() < 1e-9);
3219    }
3220
3221    #[test]
3222    fn staccato_does_not_shift_next_note_time() {
3223        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3224        let mut n1 = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3225        n1.articulations
3226            .push(crate::model::notation::Articulation::Staccato);
3227        let n2 = Note::new(Pitch::new(Step::D, 4), Duration::Quarter);
3228        score.parts[0].staves[0].measures[0].voices[0] = vec![n1, n2];
3229        let events = to_playback_events(&score, &opts(None));
3230        assert_eq!(events.len(), 2);
3231        assert!((events[1].time_beats - 1.0).abs() < 1e-9);
3232    }
3233
3234    #[test]
3235    fn dynamics_hold_until_the_next_marking_across_voices_and_bars() {
3236        use crate::model::notation::Dynamic;
3237        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3238        let quarters = |dynamics: [Option<Dynamic>; 4]| -> Vec<Note> {
3239            dynamics
3240                .into_iter()
3241                .map(|dynamic| {
3242                    let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3243                    note.dynamic = dynamic;
3244                    note
3245                })
3246                .collect()
3247        };
3248        // Bar 1: p, (p), sf, (p) ; bar 2: fp, (p), pf, (f). Voice 2 in bar 1 holds a half
3249        // note at beat 2, when voice 1's sf sounds, and one at beat 0.
3250        score.parts[0].staves[0].measures[0].voices[0] =
3251            quarters([Some(Dynamic::P), None, Some(Dynamic::Sf), None]);
3252        score.parts[0].staves[0].measures[0].voices[1] = vec![
3253            Note::new(Pitch::new(Step::C, 3), Duration::Half),
3254            Note::new(Pitch::new(Step::C, 3), Duration::Half),
3255        ];
3256        score.parts[0].staves[0].measures[1].voices[0] =
3257            quarters([Some(Dynamic::Fp), None, Some(Dynamic::Pf), None]);
3258        let events = to_playback_events(&score, &opts(None));
3259        let velocities = |pitch: u8| -> Vec<u8> {
3260            events
3261                .iter()
3262                .filter(|event| event.pitch_midi == pitch)
3263                .map(|event| event.velocity)
3264                .collect()
3265        };
3266        let (p, f, sf) = (
3267            Dynamic::P.to_velocity(),
3268            Dynamic::F.to_velocity(),
3269            Dynamic::Sf.to_velocity(),
3270        );
3271        assert_eq!(velocities(60), vec![p, p, sf, p, f, p, p, f]);
3272        assert_eq!(velocities(48), vec![p, sf]);
3273        // Before any marking, notes keep the historical default.
3274        assert_eq!(
3275            DynamicTimeline::default().velocity(0, 0.0, None),
3276            DynamicTimeline::DEFAULT_VELOCITY
3277        );
3278    }
3279
3280    #[test]
3281    fn hairpins_ramp_towards_the_following_marking_or_two_steps() {
3282        use crate::model::notation::{Dynamic, HairpinKind};
3283        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3284        let mut bar = |index: usize, dynamics: [Option<Dynamic>; 4], end: Option<Dynamic>| {
3285            let mut notes: Vec<Note> = dynamics
3286                .into_iter()
3287                .map(|dynamic| {
3288                    let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3289                    note.dynamic = dynamic;
3290                    note
3291                })
3292                .collect();
3293            notes[0].hairpin_start = Some(HairpinKind::Crescendo);
3294            notes[2].hairpin_end = true;
3295            notes[3].dynamic = end;
3296            score.parts[0].staves[0].measures[index].voices[0] = notes;
3297        };
3298        // Bar 1: p < (three beats) f. Bar 2: < with nothing after: two steps above f.
3299        bar(0, [Some(Dynamic::P), None, None, None], Some(Dynamic::F));
3300        bar(1, [None, None, None, None], None);
3301        let events = to_playback_events(&score, &opts(None));
3302        let velocities: Vec<u8> = events.iter().map(|event| event.velocity).collect();
3303        assert_eq!(&velocities[..4], &[48, 60, 72, 84]);
3304        assert_eq!(&velocities[4..], &[84, 92, 100, 108]);
3305    }
3306
3307    #[test]
3308    fn dynamic_names_round_trip_and_compounds_continue_at_their_second_level() {
3309        use crate::model::notation::Dynamic;
3310        for dynamic in Dynamic::ALL {
3311            assert_eq!(
3312                Dynamic::from_musicxml_str(dynamic.to_musicxml_str()),
3313                Some(dynamic)
3314            );
3315        }
3316        assert_eq!(Dynamic::from_musicxml_str("fffff"), Some(Dynamic::Ffff));
3317        assert_eq!(Dynamic::Sfpp.sustained_level(), Some(Dynamic::Pp));
3318        assert_eq!(Dynamic::Sfz.sustained_level(), None);
3319        assert_eq!(Dynamic::from_musicxml_str("other"), None);
3320    }
3321
3322    #[test]
3323    fn accent_boosts_velocity_clamped() {
3324        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3325        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3326        note.articulations
3327            .push(crate::model::notation::Articulation::Accent);
3328        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3329        let events = to_playback_events(&score, &opts(None));
3330        assert_eq!(events[0].velocity, 84);
3331    }
3332
3333    #[test]
3334    fn accent_clamped_at_127() {
3335        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3336        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3337        note.dynamic = Some(crate::model::notation::Dynamic::Ffff);
3338        note.articulations
3339            .push(crate::model::notation::Articulation::Accent);
3340        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3341        let events = to_playback_events(&score, &opts(None));
3342        assert_eq!(events[0].velocity, 127);
3343    }
3344
3345    #[test]
3346    fn tenuto_keeps_full_duration() {
3347        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3348        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3349        note.articulations
3350            .push(crate::model::notation::Articulation::Tenuto);
3351        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3352        let events = to_playback_events(&score, &opts(None));
3353        assert!((events[0].duration_beats - 1.0).abs() < 1e-9);
3354    }
3355
3356    #[test]
3357    fn pedal_start_sets_pedal_field() {
3358        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3359        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3360        note.pedal_start = true;
3361        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3362        let events = to_playback_events(&score, &opts(None));
3363        assert!(events[0].pedal);
3364    }
3365
3366    #[test]
3367    fn no_pedal_start_pedal_is_false() {
3368        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3369        score.parts[0].staves[0].measures[0].voices[0] =
3370            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3371        let events = to_playback_events(&score, &opts(None));
3372        assert!(!events[0].pedal);
3373    }
3374
3375    #[test]
3376    fn set_tempo_at_measure_changes_time_secs() {
3377        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3378        score.parts[0].staves[0].measures[0].voices[0] =
3379            vec![Note::new(Pitch::new(Step::C, 4), Duration::Whole)];
3380        score.parts[0].staves[0].measures[1].tempo = Some(60);
3381        score.parts[0].staves[0].measures[1].voices[0] =
3382            vec![Note::new(Pitch::new(Step::D, 4), Duration::Whole)];
3383        let events = to_playback_events(&score, &opts(None));
3384        assert_eq!(events.len(), 2);
3385        assert!((events[0].time_secs).abs() < 1e-9);
3386        assert!((events[0].duration_secs - 2.0).abs() < 1e-9);
3387        assert!((events[1].time_secs - 2.0).abs() < 1e-9);
3388        assert!((events[1].duration_secs - 4.0).abs() < 1e-9);
3389    }
3390
3391    #[test]
3392    fn muted_part_produces_no_events() {
3393        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3394        score.parts[0].staves[0].measures[0].voices[0] =
3395            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3396        let options = PlaybackOptions {
3397            muted_parts: vec![0],
3398            ..Default::default()
3399        };
3400        assert!(to_playback_events(&score, &options).is_empty());
3401    }
3402
3403    #[test]
3404    fn part_index_field_set_correctly() {
3405        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3406        score.parts[0].staves[0].measures[0].voices[0] =
3407            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3408        let events = to_playback_events(&score, &opts(None));
3409        assert_eq!(events[0].part_index, 0);
3410    }
3411
3412    // ── loop_region ───────────────────────────────────────────────────────────
3413
3414    #[test]
3415    fn loop_region_filters_measures() {
3416        // 3 measures; notes in measures 0, 1, 2. Loop on [1,2] → only events from 1,2.
3417        let mut score = Score::new("T", 120, 4, 4, 0, 3);
3418        for mi in 0..3 {
3419            score.parts[0].staves[0].measures[mi].voices[0] =
3420                vec![Note::new(Pitch::new(Step::C, 4), Duration::Whole)];
3421        }
3422        let options = PlaybackOptions {
3423            loop_region: Some((1, 2)),
3424            ..Default::default()
3425        };
3426        let events = to_playback_events(&score, &options);
3427        assert_eq!(events.len(), 2);
3428        // First event in the region should start at beat 0 (region-relative)
3429        assert!((events[0].time_beats).abs() < 1e-9);
3430    }
3431
3432    #[test]
3433    fn loop_region_none_plays_all_measures() {
3434        let mut score = Score::new("T", 120, 4, 4, 0, 3);
3435        for mi in 0..3 {
3436            score.parts[0].staves[0].measures[mi].voices[0] =
3437                vec![Note::new(Pitch::new(Step::C, 4), Duration::Whole)];
3438        }
3439        let events = to_playback_events(&score, &opts(None));
3440        assert_eq!(events.len(), 3);
3441    }
3442
3443    // ── Fermata ───────────────────────────────────────────────────────────────
3444
3445    #[test]
3446    fn fermata_multiplier_extends_duration() {
3447        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3448        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3449        note.articulations
3450            .push(crate::model::notation::Articulation::Fermata);
3451        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3452        let options = PlaybackOptions {
3453            fermata_multiplier: 2.0,
3454            ..Default::default()
3455        };
3456        let events = to_playback_events(&score, &options);
3457        assert_eq!(events.len(), 1);
3458        assert!((events[0].duration_beats - 2.0).abs() < 1e-9);
3459    }
3460
3461    #[test]
3462    fn fermata_default_multiplier_is_1_5() {
3463        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3464        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3465        note.articulations
3466            .push(crate::model::notation::Articulation::Fermata);
3467        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3468        let events = to_playback_events(&score, &PlaybackOptions::default());
3469        assert_eq!(events.len(), 1);
3470        assert!((events[0].duration_beats - 1.5).abs() < 1e-9);
3471    }
3472
3473    #[test]
3474    fn fermata_hold_is_an_explicit_post_note_request_separate_from_extension() {
3475        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3476        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3477        note.articulations
3478            .push(crate::model::notation::Articulation::Fermata);
3479        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3480        let options = PlaybackOptions {
3481            fermata_multiplier: 2.0,
3482            fermata_hold_beats: 0.75,
3483            ..Default::default()
3484        };
3485        let events = to_playback_events(&score, &options);
3486        assert!((events[0].duration_beats - 2.0).abs() < 1e-9);
3487        assert!((events[0].post_note_pause_beats - 0.75).abs() < 1e-9);
3488    }
3489
3490    #[test]
3491    fn invalid_fermata_hold_is_safely_ignored() {
3492        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3493        let mut note = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3494        note.articulations
3495            .push(crate::model::notation::Articulation::Fermata);
3496        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
3497        let options = PlaybackOptions {
3498            fermata_hold_beats: f64::NAN,
3499            ..Default::default()
3500        };
3501        assert_eq!(
3502            to_playback_events(&score, &options)[0].post_note_pause_beats,
3503            0.0
3504        );
3505    }
3506
3507    #[test]
3508    fn non_fermata_note_unaffected_by_fermata_multiplier() {
3509        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3510        score.parts[0].staves[0].measures[0].voices[0] =
3511            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3512        let options = PlaybackOptions {
3513            fermata_multiplier: 3.0,
3514            ..Default::default()
3515        };
3516        let events = to_playback_events(&score, &options);
3517        assert!((events[0].duration_beats - 1.0).abs() < 1e-9);
3518    }
3519
3520    // ── swing ─────────────────────────────────────────────────────────────────
3521
3522    #[test]
3523    fn swing_triplet_first_eighth_is_long() {
3524        // Two eighth notes in one measure; swing=0.67 → first=0.67, second=0.33
3525        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3526        score.parts[0].staves[0].measures[0].voices[0] = vec![
3527            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3528            Note::new(Pitch::new(Step::D, 4), Duration::Eighth),
3529        ];
3530        let options = PlaybackOptions {
3531            swing: Some(0.67),
3532            ..Default::default()
3533        };
3534        let events = to_playback_events(&score, &options);
3535        // events are sorted by time_beats; C comes first (time_beats=0), D second
3536        let e_c = events.iter().find(|e| e.pitch_midi == 60).unwrap();
3537        let e_d = events.iter().find(|e| e.pitch_midi == 62).unwrap();
3538        assert!(
3539            (e_c.duration_beats - 0.67).abs() < 1e-9,
3540            "first eighth should be 0.67"
3541        );
3542        assert!(
3543            (e_d.duration_beats - 0.33).abs() < 1e-9,
3544            "second eighth should be 0.33"
3545        );
3546        // D starts at 0.67, not 0.5
3547        assert!(
3548            (e_d.time_beats - 0.67).abs() < 1e-9,
3549            "second note start should be at 0.67"
3550        );
3551    }
3552
3553    #[test]
3554    fn swing_does_not_stretch_an_unpaired_eighth() {
3555        let mut score = Score::new("unpaired", 120, 4, 4, 0, 1);
3556        score.parts[0].staves[0].measures[0].voices[0] = vec![
3557            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3558            Note::new(Pitch::new(Step::D, 4), Duration::Quarter),
3559        ];
3560        let events = to_playback_events(
3561            &score,
3562            &PlaybackOptions {
3563                swing: Some(2.0 / 3.0),
3564                ..Default::default()
3565            },
3566        );
3567        assert!((events[0].duration_beats - 0.5).abs() < 1e-9);
3568        assert!((events[1].time_beats - 0.5).abs() < 1e-9);
3569    }
3570
3571    #[test]
3572    fn cue_note_does_not_sound_or_pair_with_a_written_eighth() {
3573        let mut score = Score::new("cue", 120, 4, 4, 0, 1);
3574        let mut cue = Note::new(Pitch::new(Step::D, 4), Duration::Eighth);
3575        cue.is_cue = true;
3576        score.parts[0].staves[0].measures[0].voices[0] = vec![
3577            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3578            cue,
3579            Note::new(Pitch::new(Step::E, 4), Duration::Eighth),
3580        ];
3581        let events = to_playback_events(
3582            &score,
3583            &PlaybackOptions {
3584                swing: Some(2.0 / 3.0),
3585                ..Default::default()
3586            },
3587        );
3588        assert_eq!(events.len(), 2);
3589        assert_eq!(events[0].pitch_midi, 60);
3590        assert_eq!(events[0].duration_beats, 0.5);
3591        assert_eq!(events[1].pitch_midi, 64);
3592        assert_eq!(events[1].time_beats, 0.5);
3593    }
3594
3595    #[test]
3596    fn swing_requires_metric_alignment_and_a_matching_next_note() {
3597        let mut score = Score::new("metric boundary", 120, 4, 4, 0, 1);
3598        score.parts[0].staves[0].measures[0].voices[0] = vec![
3599            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3600            Note::new(Pitch::new(Step::D, 4), Duration::Quarter),
3601            Note::new(Pitch::new(Step::E, 4), Duration::Eighth),
3602            Note::new(Pitch::new(Step::F, 4), Duration::Eighth),
3603            Note::new(Pitch::new(Step::G, 4), Duration::Eighth),
3604            Note::new(Pitch::new(Step::A, 4), Duration::Eighth),
3605        ];
3606        let events = to_playback_events(
3607            &score,
3608            &PlaybackOptions {
3609                swing: Some(2.0 / 3.0),
3610                ..Default::default()
3611            },
3612        );
3613        assert!((events[0].time_beats).abs() < 1e-9);
3614        assert!((events[0].duration_beats - 0.5).abs() < 1e-9);
3615        assert!((events[2].time_beats - 1.5).abs() < 1e-9);
3616        assert!((events[2].duration_beats - 0.5).abs() < 1e-9);
3617        assert!((events[3].time_beats - 2.0).abs() < 1e-9);
3618        assert!((events[3].duration_beats - 2.0 / 3.0).abs() < 1e-9);
3619        assert!((events[4].time_beats - 8.0 / 3.0).abs() < 1e-9);
3620        assert!((events[4].duration_beats - 1.0 / 3.0).abs() < 1e-9);
3621        assert!((events[5].time_beats - 3.0).abs() < 1e-9);
3622        assert!((events[5].duration_beats - 0.5).abs() < 1e-9);
3623    }
3624
3625    #[test]
3626    fn swing_keeps_the_offbeat_delay_after_an_eighth_rest() {
3627        let mut score = Score::new("rest swing", 120, 4, 4, 0, 1);
3628        score.parts[0].staves[0].measures[0].voices[0] = vec![
3629            Note::rest(Duration::Eighth),
3630            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3631            Note::new(Pitch::new(Step::D, 4), Duration::Quarter),
3632        ];
3633        let events = to_playback_events(
3634            &score,
3635            &PlaybackOptions {
3636                swing: Some(2.0 / 3.0),
3637                ..Default::default()
3638            },
3639        );
3640        assert!((events[0].time_beats - 2.0 / 3.0).abs() < 1e-9);
3641        assert!((events[0].duration_beats - 1.0 / 3.0).abs() < 1e-9);
3642        assert!((events[1].time_beats - 1.0).abs() < 1e-9);
3643    }
3644
3645    #[test]
3646    fn invalid_swing_ratios_keep_straight_finite_timing() {
3647        let mut score = Score::new("invalid swing", 120, 4, 4, 0, 1);
3648        score.parts[0].staves[0].measures[0].voices[0] = vec![
3649            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3650            Note::new(Pitch::new(Step::D, 4), Duration::Eighth),
3651        ];
3652        for ratio in [f64::NAN, f64::INFINITY, -1.0, 0.5, 1.0] {
3653            let events = to_playback_events(
3654                &score,
3655                &PlaybackOptions {
3656                    swing: Some(ratio),
3657                    ..Default::default()
3658                },
3659            );
3660            assert_eq!(events.len(), 2);
3661            assert_eq!(events[0].duration_beats, 0.5);
3662            assert_eq!(events[1].time_beats, 0.5);
3663            assert_eq!(events[1].duration_beats, 0.5);
3664            assert!(events.iter().all(|event| event.time_secs.is_finite()));
3665        }
3666    }
3667
3668    #[test]
3669    fn pickup_swing_uses_metric_position_in_the_full_bar() {
3670        let mut score = Score::new("pickup swing", 120, 4, 4, 0, 1);
3671        let measure = &mut score.parts[0].staves[0].measures[0];
3672        measure.actual_length = Some(crate::MeasureLength {
3673            numerator: 3,
3674            denominator: 8,
3675        });
3676        measure.voices[0] = vec![
3677            Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3678            Note::new(Pitch::new(Step::D, 4), Duration::Eighth),
3679            Note::new(Pitch::new(Step::E, 4), Duration::Eighth),
3680        ];
3681        let events = to_playback_events(
3682            &score,
3683            &PlaybackOptions {
3684                swing: Some(2.0 / 3.0),
3685                ..Default::default()
3686            },
3687        );
3688        assert_eq!(events[0].duration_beats, 0.5);
3689        assert!((events[1].time_beats - 0.5).abs() < 1e-9);
3690        assert!((events[1].duration_beats - 2.0 / 3.0).abs() < 1e-9);
3691        assert!((events[2].time_beats - 7.0 / 6.0).abs() < 1e-9);
3692        assert!((events[2].duration_beats - 1.0 / 3.0).abs() < 1e-9);
3693    }
3694
3695    #[test]
3696    fn swing_non_eighth_not_affected() {
3697        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3698        score.parts[0].staves[0].measures[0].voices[0] =
3699            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3700        let options = PlaybackOptions {
3701            swing: Some(0.67),
3702            ..Default::default()
3703        };
3704        let events = to_playback_events(&score, &options);
3705        assert!(
3706            (events[0].duration_beats - 1.0).abs() < 1e-9,
3707            "quarter note unaffected"
3708        );
3709    }
3710
3711    #[test]
3712    fn swing_none_is_straight() {
3713        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3714        score.parts[0].staves[0].measures[0].voices[0] =
3715            vec![Note::new(Pitch::new(Step::C, 4), Duration::Eighth)];
3716        let options = PlaybackOptions {
3717            swing: None,
3718            ..Default::default()
3719        };
3720        let events = to_playback_events(&score, &options);
3721        assert!(
3722            (events[0].duration_beats - 0.5).abs() < 1e-9,
3723            "no swing = straight eighth"
3724        );
3725    }
3726
3727    #[test]
3728    fn channel_matches_part_midi_channel() {
3729        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3730        score.parts[0].midi_channel = 3;
3731        score.parts[0].staves[0].measures[0].voices[0] =
3732            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3733        let events = to_playback_events(&score, &opts(None));
3734        assert_eq!(events[0].channel, 3);
3735    }
3736
3737    #[test]
3738    fn swing_unit_default_is_eighth() {
3739        assert_eq!(PlaybackOptions::default().swing_unit, Duration::Eighth);
3740    }
3741
3742    #[test]
3743    fn swing_unit_sixteenth() {
3744        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3745        score.parts[0].staves[0].measures[0].voices[0] = vec![
3746            Note::new(Pitch::new(Step::C, 4), Duration::Sixteenth),
3747            Note::new(Pitch::new(Step::D, 4), Duration::Sixteenth),
3748        ];
3749        let options = PlaybackOptions {
3750            swing: Some(0.67),
3751            swing_unit: Duration::Sixteenth,
3752            ..Default::default()
3753        };
3754        let events = to_playback_events(&score, &options);
3755        let e_c = events.iter().find(|e| e.pitch_midi == 60).unwrap();
3756        let e_d = events.iter().find(|e| e.pitch_midi == 62).unwrap();
3757        assert!(
3758            (e_c.duration_beats - 0.335).abs() < 1e-9,
3759            "first 16th should be 0.335"
3760        );
3761        assert!(
3762            (e_d.duration_beats - 0.165).abs() < 1e-9,
3763            "second 16th should be 0.165"
3764        );
3765    }
3766
3767    #[test]
3768    fn swing_resets_per_measure() {
3769        // 2 measures each with 2 eighth notes; each measure's first eighth should be "long"
3770        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3771        let pair = || {
3772            vec![
3773                Note::new(Pitch::new(Step::C, 4), Duration::Eighth),
3774                Note::new(Pitch::new(Step::D, 4), Duration::Eighth),
3775            ]
3776        };
3777        score.parts[0].staves[0].measures[0].voices[0] = pair();
3778        score.parts[0].staves[0].measures[1].voices[0] = pair();
3779        let options = PlaybackOptions {
3780            swing: Some(0.67),
3781            ..Default::default()
3782        };
3783        let events = to_playback_events(&score, &options);
3784        // Four events sorted by time: m0-C, m0-D, m1-C, m1-D
3785        let durations: Vec<f64> = events.iter().map(|e| e.duration_beats).collect();
3786        // m0 first (long)
3787        assert!((durations[0] - 0.67).abs() < 1e-9, "m0 first note long");
3788        // m0 second (short)
3789        assert!((durations[1] - 0.33).abs() < 1e-9, "m0 second note short");
3790        // m1 first (long again — reset)
3791        assert!(
3792            (durations[2] - 0.67).abs() < 1e-9,
3793            "m1 first note long (reset)"
3794        );
3795        // m1 second (short)
3796        assert!((durations[3] - 0.33).abs() < 1e-9, "m1 second note short");
3797    }
3798
3799    #[test]
3800    fn multi_voice_events_preserve_source_voice_addresses() {
3801        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3802        score.parts[0].staves[0].measures[0].voices[0] =
3803            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
3804        score.parts[0].staves[0].measures[0].voices[1] =
3805            vec![Note::new(Pitch::new(Step::E, 4), Duration::Quarter)];
3806
3807        let events = to_playback_events(&score, &PlaybackOptions::default());
3808        let addresses: Vec<&str> = events
3809            .iter()
3810            .filter_map(|event| event.address.as_deref())
3811            .collect();
3812        assert!(addresses.contains(&"0:0:0:0:0"));
3813        assert!(addresses.contains(&"0:0:0:1:0"));
3814    }
3815
3816    #[test]
3817    fn playback_exposes_original_musicxml_voice_number_alongside_slot_address() {
3818        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3819        let measure = &mut score.parts[0].staves[0].measures[0];
3820        measure.voices[1] = vec![Note::new(Pitch::new(Step::E, 4), Duration::Quarter)];
3821        measure.source_voice_numbers[1] = Some(5);
3822
3823        let events = to_playback_events(&score, &PlaybackOptions::default());
3824        let event = events
3825            .iter()
3826            .find(|event| event.address.as_deref() == Some("0:0:0:1:0"))
3827            .expect("event from slot 1");
3828        assert_eq!(event.source.as_ref().map(|source| source.voice), Some(1));
3829        assert_eq!(event.source_voice_number, Some(5));
3830    }
3831
3832    // ── compute_playback_position ─────────────────────────────────────────────
3833
3834    #[test]
3835    fn playback_position_at_zero_is_measure_0_beat_0() {
3836        let score = Score::new("T", 120, 4, 4, 0, 4);
3837        let pos = compute_playback_position(&score, &PlaybackOptions::default(), 0.0).unwrap();
3838        assert_eq!(pos.measure_index, 0);
3839        assert!(pos.beat.abs() < 1e-9);
3840    }
3841
3842    #[test]
3843    fn playback_position_at_half_measure_is_beat_2() {
3844        // 4/4, 120 BPM → 1 measure = 2.0 s; 0.5 s = beat 1.0
3845        let score = Score::new("T", 120, 4, 4, 0, 4);
3846        let pos = compute_playback_position(&score, &PlaybackOptions::default(), 0.5).unwrap();
3847        assert_eq!(pos.measure_index, 0);
3848        assert!(
3849            (pos.beat - 1.0).abs() < 1e-9,
3850            "expected beat 1.0, got {}",
3851            pos.beat
3852        );
3853    }
3854
3855    #[test]
3856    fn playback_position_beyond_score_is_none() {
3857        // 4/4, 120 BPM, 1 measure = 2.0 s; 10.0 s is beyond
3858        let score = Score::new("T", 120, 4, 4, 0, 1);
3859        assert!(compute_playback_position(&score, &PlaybackOptions::default(), 10.0).is_none());
3860    }
3861
3862    #[test]
3863    fn playback_position_tempo_change_takes_effect() {
3864        // measure 0: 120 BPM (2.0 s), measure 1: 60 BPM (4.0 s)
3865        // At elapsed=2.5 s → inside measure 1, 0.5 s into it → beat 0.5
3866        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3867        score.parts[0].staves[0].measures[1].tempo = Some(60);
3868        let pos = compute_playback_position(&score, &PlaybackOptions::default(), 2.5).unwrap();
3869        assert_eq!(pos.measure_index, 1);
3870        assert!(
3871            (pos.beat - 0.5).abs() < 1e-9,
3872            "expected beat 0.5, got {}",
3873            pos.beat
3874        );
3875    }
3876
3877    #[test]
3878    fn playback_position_loop_region_starts_at_zero() {
3879        // loop_region=[1,2] → elapsed=0 should map to measure 1, beat 0
3880        let score = Score::new("T", 120, 4, 4, 0, 4);
3881        let options = PlaybackOptions {
3882            loop_region: Some((1, 2)),
3883            ..Default::default()
3884        };
3885        let pos = compute_playback_position(&score, &options, 0.0).unwrap();
3886        assert_eq!(pos.measure_index, 1);
3887        assert!(pos.beat.abs() < 1e-9);
3888    }
3889
3890    // ── MetronomeConfig ───────────────────────────────────────────────────────
3891
3892    #[test]
3893    fn metronome_injects_beat_events() {
3894        // 4/4, 1 measure → should inject 4 metronome events
3895        let score = Score::new("T", 120, 4, 4, 0, 1);
3896        let options = PlaybackOptions {
3897            metronome: Some(MetronomeConfig::default()),
3898            ..Default::default()
3899        };
3900        let events = to_playback_events(&score, &options);
3901        let metro_events: Vec<_> = events.iter().filter(|e| e.is_metronome).collect();
3902        assert_eq!(metro_events.len(), 4, "expected 4 metronome clicks in 4/4");
3903    }
3904
3905    #[test]
3906    fn metronome_accent_is_first_beat() {
3907        let score = Score::new("T", 120, 4, 4, 0, 1);
3908        let metro = MetronomeConfig::default();
3909        let options = PlaybackOptions {
3910            metronome: Some(metro.clone()),
3911            ..Default::default()
3912        };
3913        let events = to_playback_events(&score, &options);
3914        let mut metro_events: Vec<_> = events.iter().filter(|e| e.is_metronome).collect();
3915        metro_events.sort_by(|a, b| a.time_beats.partial_cmp(&b.time_beats).unwrap());
3916        assert_eq!(metro_events[0].pitch_midi, metro.accent_pitch);
3917        assert_eq!(metro_events[0].velocity, metro.accent_velocity);
3918    }
3919
3920    #[test]
3921    fn metronome_regular_beat_pitch() {
3922        let score = Score::new("T", 120, 4, 4, 0, 1);
3923        let metro = MetronomeConfig::default();
3924        let options = PlaybackOptions {
3925            metronome: Some(metro.clone()),
3926            ..Default::default()
3927        };
3928        let events = to_playback_events(&score, &options);
3929        let mut metro_events: Vec<_> = events.iter().filter(|e| e.is_metronome).collect();
3930        metro_events.sort_by(|a, b| a.time_beats.partial_cmp(&b.time_beats).unwrap());
3931        for ev in &metro_events[1..] {
3932            assert_eq!(ev.pitch_midi, metro.beat_pitch);
3933            assert_eq!(ev.velocity, metro.beat_velocity);
3934        }
3935    }
3936
3937    #[test]
3938    fn metronome_integrates_measure_tempo_ramp_and_carries_ending_tempo() {
3939        let mut score = Score::new("T", 120, 4, 4, 0, 2);
3940        score.parts[0].staves[0].measures[0].tempo_ramp_to = Some(60);
3941        let options = PlaybackOptions {
3942            metronome: Some(MetronomeConfig::default()),
3943            ..Default::default()
3944        };
3945
3946        let mut clicks: Vec<_> = to_playback_events(&score, &options)
3947            .into_iter()
3948            .filter(|event| event.is_metronome)
3949            .collect();
3950        clicks.sort_by(|left, right| left.time_beats.total_cmp(&right.time_beats));
3951
3952        let expected_second_beat = tempo_ramp_seconds(120.0, Some(60.0), 4.0, 1.0);
3953        let expected_second_measure = tempo_ramp_seconds(120.0, Some(60.0), 4.0, 4.0);
3954        assert!((clicks[1].time_secs - expected_second_beat).abs() < 1e-9);
3955        assert!((clicks[4].time_secs - expected_second_measure).abs() < 1e-9);
3956        assert!((clicks[5].time_secs - (expected_second_measure + 1.0)).abs() < 1e-9);
3957    }
3958
3959    #[test]
3960    fn metronome_events_are_marked() {
3961        let score = Score::new("T", 120, 4, 4, 0, 1);
3962        let options = PlaybackOptions {
3963            metronome: Some(MetronomeConfig::default()),
3964            ..Default::default()
3965        };
3966        let events = to_playback_events(&score, &options);
3967        assert!(events.iter().any(|e| e.is_metronome));
3968    }
3969
3970    #[test]
3971    fn metronome_none_produces_no_extra_events() {
3972        let score = Score::new("T", 120, 4, 4, 0, 1);
3973        let events = to_playback_events(&score, &PlaybackOptions::default());
3974        assert!(events.iter().all(|e| !e.is_metronome));
3975    }
3976
3977    #[test]
3978    fn offline_render_manifest_uses_event_end_as_exact_frame_length() {
3979        let mut score = Score::new("T", 120, 4, 4, 0, 1);
3980        score.parts[0].staves[0].measures[0].voices[0][0] =
3981            Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
3982        let request = OfflineRenderRequest {
3983            format: OfflineRenderFormat::Flac,
3984            sample_rate_hz: 48_000,
3985            channels: 2,
3986            provider_identity: Some("test-provider@1".into()),
3987            ..Default::default()
3988        };
3989
3990        let manifest = build_offline_render_manifest(&score, &PlaybackOptions::default(), &request)
3991            .expect("valid render manifest");
3992        assert_eq!(manifest.contract_version, OFFLINE_RENDER_CONTRACT_VERSION);
3993        assert!(manifest.validate().is_ok());
3994        assert_eq!(manifest.format, OfflineRenderFormat::Flac);
3995        assert_eq!(manifest.duration_frames, 24_000);
3996        assert_eq!(manifest.events.len(), 1);
3997        assert_eq!(manifest.frame_events.len(), 1);
3998        assert_eq!(manifest.frame_events[0].start_frame, 0);
3999        assert_eq!(manifest.frame_events[0].duration_frames, 24_000);
4000        assert_eq!(manifest.frame_events[0].end_frame, 24_000);
4001        assert_eq!(manifest.playback_options, PlaybackOptions::default());
4002        assert_eq!(
4003            manifest.provider_identity.as_deref(),
4004            Some("test-provider@1")
4005        );
4006    }
4007
4008    #[test]
4009    fn offline_render_manifest_rejects_out_of_range_audio_shape() {
4010        let score = Score::new("T", 120, 4, 4, 0, 1);
4011        let request = OfflineRenderRequest {
4012            sample_rate_hz: 0,
4013            ..Default::default()
4014        };
4015        assert!(matches!(
4016            build_offline_render_manifest(&score, &PlaybackOptions::default(), &request),
4017            Err(crate::Error::InvalidOfflineRenderRequest)
4018        ));
4019    }
4020
4021    #[test]
4022    fn offline_render_manifest_selection_keeps_source_address_and_release_tail() {
4023        let mut score = Score::new("T", 120, 4, 4, 0, 1);
4024        score.parts[0].staves[0].measures[0].voices[0] = vec![
4025            Note::new(Pitch::new(Step::C, 4), Duration::Quarter),
4026            Note::new(Pitch::new(Step::D, 4), Duration::Quarter),
4027        ];
4028        let events = to_playback_events(&score, &PlaybackOptions::default());
4029        score.parts[0].midi_control_changes.push(MidiControlChange {
4030            tick: 480,
4031            channel: 0,
4032            controller: 7,
4033            value: 100,
4034        });
4035        let request = OfflineRenderRequest {
4036            sample_rate_hz: 8_000,
4037            release_tail_millis: 125,
4038            scope: OfflineRenderScope::Selection {
4039                addresses: vec![events[1].source.clone().expect("source address")],
4040            },
4041            ..Default::default()
4042        };
4043        let manifest = build_offline_render_manifest(&score, &PlaybackOptions::default(), &request)
4044            .expect("selection manifest");
4045        assert_eq!(manifest.events.len(), 1);
4046        assert_eq!(manifest.events[0].source, events[1].source);
4047        assert_eq!(manifest.frame_events[0].start_frame, 0);
4048        assert!(manifest.semantic_events.iter().any(|event| matches!(
4049            event.kind,
4050            OfflineRenderSemanticEventKind::Controller {
4051                channel: 0,
4052                controller: 7,
4053                value: 100
4054            }
4055        ) && event.frame == 0));
4056        assert_eq!(manifest.release_tail_frames, 1_000);
4057        assert_eq!(manifest.duration_frames, 5_000);
4058    }
4059
4060    #[test]
4061    fn offline_render_request_owned_options_override_legacy_argument() {
4062        let mut score = Score::new("T", 120, 4, 4, 0, 1);
4063        score.parts[0].staves[0].measures[0].voices[0][0] =
4064            Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
4065        let request_options = PlaybackOptions {
4066            bpm_override: Some(60),
4067            ..Default::default()
4068        };
4069        let manifest = build_offline_render_manifest(
4070            &score,
4071            &PlaybackOptions::default(),
4072            &OfflineRenderRequest {
4073                sample_rate_hz: 48_000,
4074                playback_options: Some(request_options.clone()),
4075                ..Default::default()
4076            },
4077        )
4078        .expect("request-owned playback options");
4079        assert_eq!(manifest.playback_options, request_options);
4080        assert_eq!(manifest.frame_events[0].duration_frames, 48_000);
4081    }
4082
4083    #[test]
4084    fn offline_manifest_projects_typed_midi_events_to_exact_frames() {
4085        let mut score = Score::new("MIDI semantics", 120, 4, 4, 0, 1);
4086        score.parts[0].midi_pitch_bends.push(MidiPitchBend {
4087            tick: 480,
4088            channel: 2,
4089            value: -512,
4090        });
4091        score.parts[0].midi_program_changes.push(MidiProgramChange {
4092            tick: 480,
4093            channel: 2,
4094            program: 41,
4095        });
4096        score.parts[0].midi_aftertouch.push(MidiAftertouch {
4097            tick: 480,
4098            channel: 2,
4099            key: Some(64),
4100            value: 88,
4101        });
4102        let manifest = build_offline_render_manifest(
4103            &score,
4104            &PlaybackOptions::default(),
4105            &OfflineRenderRequest {
4106                sample_rate_hz: 48_000,
4107                ..Default::default()
4108            },
4109        )
4110        .expect("manifest builds");
4111        for kind in [
4112            OfflineRenderSemanticEventKind::PitchBend {
4113                channel: 2,
4114                value: -512,
4115            },
4116            OfflineRenderSemanticEventKind::ProgramChange {
4117                channel: 2,
4118                program: 41,
4119            },
4120            OfflineRenderSemanticEventKind::Aftertouch {
4121                channel: 2,
4122                key: Some(64),
4123                value: 88,
4124            },
4125        ] {
4126            assert!(manifest.semantic_events.iter().any(|event| {
4127                event.kind == kind
4128                    && event.frame == 24_000
4129                    && event
4130                        .measure
4131                        .as_ref()
4132                        .is_some_and(|address| address.part == 0 && address.measure == 0)
4133            }));
4134        }
4135    }
4136
4137    #[test]
4138    fn offline_manifest_frames_cover_repeat_ramp_fermata_pedal_bend_and_instrument_change() {
4139        let mut score = Score::new("fixture", 120, 4, 4, 0, 2);
4140        let mut first = Note::new(Pitch::new(Step::C, 4), Duration::Quarter);
4141        first.pedal_start = true;
4142        first.articulations = vec![Articulation::Fermata, Articulation::BreathMark];
4143        first.guitar_bend_curve = vec![GuitarBendPoint {
4144            position_per_mille: 500,
4145            alter_cents: 100,
4146        }];
4147        score.parts[0].staves[0].measures[0].voices[0] = vec![first];
4148        score.parts[0].staves[0].measures[0].barline_left =
4149            super::super::notation::Barline::RepeatStart;
4150        score.parts[0].staves[0].measures[0].tempo_ramp_to = Some(60);
4151        score.parts[0].staves[0].measures[0].navigation = Some("Segno".to_string());
4152        score.parts[0].midi_control_changes.push(MidiControlChange {
4153            tick: 480,
4154            channel: 0,
4155            controller: 11,
4156            value: 96,
4157        });
4158
4159        let mut second = Note::new(Pitch::new(Step::D, 4), Duration::Quarter);
4160        second.pedal_end = true;
4161        score.parts[0].staves[0].measures[1].voices[0] = vec![second];
4162        score.parts[0].staves[0].measures[1].barline_right =
4163            super::super::notation::Barline::RepeatEnd;
4164        let mut flute = crate::InstrumentDefinition::new("flute", "Flute");
4165        flute.midi_channel = 2;
4166        flute.midi_program = 73;
4167        score.parts[0].staves[0].measures[1].instrument_change = Some(flute);
4168
4169        let request = OfflineRenderRequest {
4170            sample_rate_hz: 48_000,
4171            playback_options: Some(PlaybackOptions {
4172                fermata_multiplier: 1.5,
4173                fermata_hold_beats: 0.25,
4174                ..Default::default()
4175            }),
4176            ..Default::default()
4177        };
4178        let manifest = build_offline_render_manifest(&score, &PlaybackOptions::default(), &request)
4179            .expect("fixture manifest");
4180        assert_eq!(manifest.frame_events.len(), 4);
4181        let measures: Vec<usize> = manifest
4182            .frame_events
4183            .iter()
4184            .map(|event| event.event.source.as_ref().unwrap().measure)
4185            .collect();
4186        assert_eq!(measures, vec![0, 1, 0, 1]);
4187        assert!(manifest.frame_events[0].event.pedal);
4188        assert_eq!(manifest.frame_events[0].event.post_note_pause_beats, 0.25);
4189        assert_eq!(manifest.frame_events[0].event.pitch_bend_curve.len(), 1);
4190        assert_eq!(
4191            manifest.frame_events[1].event.instrument_id.as_deref(),
4192            Some("flute")
4193        );
4194        assert_eq!(manifest.frame_events[3].event.program, 73);
4195        assert!(manifest.semantic_events.iter().any(|event| {
4196            matches!(
4197                &event.kind,
4198                OfflineRenderSemanticEventKind::InstrumentChange {
4199                    instrument_id,
4200                    channel: 2,
4201                    program: 73,
4202                    transpose_semitones: 0,
4203                } if instrument_id == "flute"
4204            ) && event
4205                .measure
4206                .as_ref()
4207                .is_some_and(|address| address.measure == 1)
4208                && event.frame == manifest.frame_events[1].start_frame
4209        }));
4210        assert!(manifest.semantic_events.iter().any(|event| matches!(
4211            event.kind,
4212            OfflineRenderSemanticEventKind::Pedal { down: true }
4213        ) && event.frame
4214            == manifest.frame_events[0].start_frame));
4215        assert!(manifest.semantic_events.iter().any(|event| matches!(
4216            event.kind,
4217            OfflineRenderSemanticEventKind::Pedal { down: false }
4218        ) && event.frame
4219            == manifest.frame_events[1].start_frame));
4220        assert!(manifest.semantic_events.iter().any(|event| matches!(
4221            event.kind,
4222            OfflineRenderSemanticEventKind::Articulation {
4223                articulation: Articulation::Fermata
4224            }
4225        )));
4226        assert!(manifest.semantic_events.iter().any(|event| matches!(
4227            event.kind,
4228            OfflineRenderSemanticEventKind::GuitarBend { .. }
4229        )));
4230        let tempo_events = manifest
4231            .semantic_events
4232            .iter()
4233            .filter(|event| matches!(event.kind, OfflineRenderSemanticEventKind::Tempo { .. }))
4234            .count();
4235        let navigation_events = manifest
4236            .semantic_events
4237            .iter()
4238            .filter(|event| {
4239                matches!(
4240                    event.kind,
4241                    OfflineRenderSemanticEventKind::Navigation { .. }
4242                )
4243            })
4244            .count();
4245        let control_frames: Vec<u64> = manifest
4246            .semantic_events
4247            .iter()
4248            .filter_map(|event| {
4249                matches!(
4250                    event.kind,
4251                    OfflineRenderSemanticEventKind::Controller {
4252                        channel: 0,
4253                        controller: 11,
4254                        value: 96
4255                    }
4256                )
4257                .then_some(event.frame)
4258            })
4259            .collect();
4260        assert_eq!(tempo_events, 2);
4261        assert_eq!(navigation_events, 2);
4262        assert_eq!(control_frames.len(), 2);
4263        let ramp_duration = tempo_ramp_seconds(120.0, Some(60.0), 4.0, 4.0);
4264        assert_eq!(
4265            control_frames[0],
4266            (tempo_ramp_seconds(120.0, Some(60.0), 4.0, 1.0) * 48_000.0).round() as u64
4267        );
4268        assert_eq!(control_frames[1], 373_084);
4269
4270        let expected_starts = [0.0, ramp_duration, ramp_duration + 4.0, ramp_duration + 8.0];
4271        for (frame_event, expected_secs) in manifest.frame_events.iter().zip(expected_starts) {
4272            assert_eq!(
4273                frame_event.start_frame,
4274                (expected_secs * 48_000.0).round() as u64
4275            );
4276        }
4277    }
4278
4279    #[test]
4280    fn offline_render_manifest_reports_unresolved_selection_address() {
4281        let score = Score::new("T", 120, 4, 4, 0, 1);
4282        let request = OfflineRenderRequest {
4283            scope: OfflineRenderScope::Selection {
4284                addresses: vec![NoteAddr {
4285                    part: 0,
4286                    staff: 0,
4287                    measure: 0,
4288                    voice: 0,
4289                    note: 99,
4290                }],
4291            },
4292            ..Default::default()
4293        };
4294        let manifest = build_offline_render_manifest(&score, &PlaybackOptions::default(), &request)
4295            .expect("empty selection is representable");
4296        assert_eq!(manifest.events.len(), 0);
4297        assert_eq!(
4298            manifest.diagnostics,
4299            vec![
4300                OfflineRenderDiagnostic {
4301                    kind: OfflineRenderDiagnosticKind::UnresolvedSelectionAddress,
4302                    source: Some(NoteAddr {
4303                        part: 0,
4304                        staff: 0,
4305                        measure: 0,
4306                        voice: 0,
4307                        note: 99,
4308                    }),
4309                },
4310                OfflineRenderDiagnostic {
4311                    kind: OfflineRenderDiagnosticKind::EmptySelection,
4312                    source: None,
4313                },
4314            ]
4315        );
4316    }
4317
4318    #[test]
4319    fn offline_render_manifest_v1_json_migrates_with_v2_defaults() {
4320        let legacy = serde_json::json!({
4321            "contract_version": 1,
4322            "playback_contract_version": 2,
4323            "format": "Wav",
4324            "sample_rate_hz": 48_000,
4325            "channels": 2,
4326            "duration_frames": 0,
4327            "events": []
4328        });
4329        let manifest: OfflineRenderManifest =
4330            serde_json::from_value(legacy).expect("v1 manifest remains readable");
4331        assert_eq!(manifest.contract_version, 1);
4332        assert_eq!(manifest.scope, OfflineRenderScope::FullScore);
4333        assert_eq!(manifest.release_tail_frames, 0);
4334        assert_eq!(manifest.playback_options, PlaybackOptions::default());
4335        assert!(manifest.frame_events.is_empty());
4336        assert!(manifest.diagnostics.is_empty());
4337        assert!(manifest.validate().is_ok());
4338    }
4339
4340    #[test]
4341    fn offline_render_manifest_validation_rejects_tampered_frame_and_tail_boundaries() {
4342        let mut score = Score::new("T", 120, 4, 4, 0, 1);
4343        score.parts[0].staves[0].measures[0].voices[0] =
4344            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
4345        let manifest = build_offline_render_manifest(
4346            &score,
4347            &PlaybackOptions::default(),
4348            &OfflineRenderRequest {
4349                sample_rate_hz: 48_000,
4350                release_tail_millis: 100,
4351                ..Default::default()
4352            },
4353        )
4354        .expect("manifest builds");
4355        assert!(manifest.validate().is_ok());
4356
4357        let mut invalid_tail = manifest.clone();
4358        invalid_tail.duration_frames = invalid_tail.duration_frames.saturating_sub(1);
4359        assert!(matches!(
4360            invalid_tail.validate(),
4361            Err(crate::Error::InvalidOfflineRenderRequest)
4362        ));
4363
4364        let mut invalid_frame = manifest;
4365        invalid_frame.frame_events[0].end_frame =
4366            invalid_frame.frame_events[0].end_frame.saturating_add(1);
4367        assert!(matches!(
4368            invalid_frame.validate(),
4369            Err(crate::Error::InvalidOfflineRenderRequest)
4370        ));
4371    }
4372
4373    #[test]
4374    fn routing_manifest_prefers_instrument_bus_and_isolates_metronome() {
4375        let mut score = Score::new("routing", 120, 4, 4, 0, 1);
4376        let mut instrument = crate::InstrumentDefinition::new("flute", "Flute");
4377        instrument.midi_channel = 2;
4378        instrument.midi_program = 73;
4379        score.parts[0].instrument = Some(instrument);
4380        score.parts[0].staves[0].measures[0].voices[0] =
4381            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
4382        let options = PlaybackOptions {
4383            metronome: Some(MetronomeConfig::default()),
4384            ..Default::default()
4385        };
4386        let mut config = PlaybackRoutingConfig {
4387            provider_identity: Some("sf2-host@1".into()),
4388            ..Default::default()
4389        };
4390        config.part_buses.insert(0, "parts".into());
4391        config
4392            .instrument_buses
4393            .insert("flute".into(), "winds".into());
4394        config.aux_sends.push(PlaybackAuxSend {
4395            source_bus: "winds".into(),
4396            destination_bus: "reverb".into(),
4397            gain_db: -12.0,
4398        });
4399        config.effect_routes.push(PlaybackEffectRoute {
4400            bus_id: "reverb".into(),
4401            effect_id: "convolution".into(),
4402            enabled: true,
4403        });
4404
4405        let manifest = build_playback_routing_manifest(&score, &options, &config)
4406            .expect("valid routing manifest");
4407        assert_eq!(manifest.contract_version, PLAYBACK_ROUTING_CONTRACT_VERSION);
4408        assert_eq!(manifest.provider_identity.as_deref(), Some("sf2-host@1"));
4409        assert!(manifest.routes.iter().any(|route| {
4410            route.instrument_id.as_deref() == Some("flute") && route.bus_id == "winds"
4411        }));
4412        assert!(
4413            manifest
4414                .routes
4415                .iter()
4416                .any(|route| route.is_metronome && route.bus_id == "metronome")
4417        );
4418        assert_eq!(manifest.aux_sends.len(), 1);
4419        assert_eq!(manifest.effect_routes.len(), 1);
4420    }
4421
4422    #[test]
4423    fn routing_manifest_rejects_unsafe_bus_and_non_finite_send_gain() {
4424        let score = Score::new("routing", 120, 4, 4, 0, 1);
4425        let config = PlaybackRoutingConfig {
4426            master_bus: "not a bus".into(),
4427            ..Default::default()
4428        };
4429        assert!(matches!(
4430            build_playback_routing_manifest(&score, &PlaybackOptions::default(), &config),
4431            Err(crate::Error::InvalidPlaybackRouting)
4432        ));
4433
4434        let mut config = PlaybackRoutingConfig::default();
4435        config.aux_sends.push(PlaybackAuxSend {
4436            source_bus: "part".into(),
4437            destination_bus: "master".into(),
4438            gain_db: f64::NAN,
4439        });
4440        assert!(matches!(
4441            build_playback_routing_manifest(&score, &PlaybackOptions::default(), &config),
4442            Err(crate::Error::InvalidPlaybackRouting)
4443        ));
4444    }
4445
4446    #[test]
4447    fn timing_corpus_reports_score_schedule_results_without_audio_claims() {
4448        let mut score = Score::new("corpus", 120, 4, 4, 0, 1);
4449        score.parts[0].staves[0].measures[0].voices[0] =
4450            vec![Note::new(Pitch::new(Step::C, 4), Duration::Quarter)];
4451        let expected_events = to_playback_events(&score, &PlaybackOptions::default());
4452        let report = evaluate_playback_timing_corpus(&[PlaybackTimingCase {
4453            id: "quarter-note".into(),
4454            score,
4455            options: PlaybackOptions::default(),
4456            expected_events,
4457            tolerance: PlaybackTimingTolerance::default(),
4458        }])
4459        .expect("valid timing corpus");
4460        assert_eq!(
4461            report.contract_version,
4462            PLAYBACK_TIMING_CORPUS_CONTRACT_VERSION
4463        );
4464        assert_eq!(report.total_cases, 1);
4465        assert_eq!(report.passed_cases, 1);
4466        assert!(report.cases[0].report.within_tolerance);
4467    }
4468
4469    #[test]
4470    fn timing_corpus_rejects_empty_or_duplicate_case_ids() {
4471        assert!(matches!(
4472            evaluate_playback_timing_corpus(&[]),
4473            Err(crate::Error::InvalidPlaybackTimingCorpus)
4474        ));
4475        let score = Score::new("corpus", 120, 4, 4, 0, 1);
4476        let case = PlaybackTimingCase {
4477            id: "duplicate".into(),
4478            expected_events: to_playback_events(&score, &PlaybackOptions::default()),
4479            score,
4480            options: PlaybackOptions::default(),
4481            tolerance: PlaybackTimingTolerance::default(),
4482        };
4483        assert!(matches!(
4484            evaluate_playback_timing_corpus(&[case.clone(), case]),
4485            Err(crate::Error::InvalidPlaybackTimingCorpus)
4486        ));
4487    }
4488
4489    fn comparison_event(time_secs: f64, duration_secs: f64) -> PlaybackEvent {
4490        PlaybackEvent {
4491            address: Some("0:0:0:0:0".into()),
4492            source: Some(NoteAddr {
4493                part: 0,
4494                staff: 0,
4495                measure: 0,
4496                voice: 0,
4497                note: 0,
4498            }),
4499            source_voice_number: None,
4500            time_beats: 0.0,
4501            time_secs,
4502            pitch_midi: 60,
4503            pitch_midi_cents: 6000,
4504            pitch_bend_curve: Vec::new(),
4505            post_note_pause_beats: 0.0,
4506            articulations: Vec::new(),
4507            chord_symbol: None,
4508            guitar_technique: None,
4509            velocity: 64,
4510            duration_beats: 1.0,
4511            duration_secs,
4512            pedal: false,
4513            part_index: 0,
4514            channel: 0,
4515            program: 0,
4516            instrument_id: None,
4517            is_metronome: false,
4518        }
4519    }
4520
4521    #[test]
4522    fn legacy_playback_event_json_defaults_bend_curve() {
4523        let event: PlaybackEvent = serde_json::from_str(
4524            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}"#,
4525        )
4526        .expect("legacy playback event remains readable");
4527        assert!(event.pitch_bend_curve.is_empty());
4528        assert_eq!(event.guitar_technique, None);
4529    }
4530
4531    #[test]
4532    fn tempo_ramp_uses_integrated_event_timing_and_carries_target_forward() {
4533        let mut score = Score::new("ramp", 120, 4, 4, 0, 2);
4534        for measure in &mut score.parts[0].staves[0].measures {
4535            measure.voices[0] = vec![
4536                crate::Note::new(crate::Pitch::new(crate::Step::C, 4), crate::Duration::Half),
4537                crate::Note::new(crate::Pitch::new(crate::Step::D, 4), crate::Duration::Half),
4538            ];
4539        }
4540        score.parts[0].staves[0].measures[0].tempo_ramp_to = Some(60);
4541        let events = to_playback_events(&score, &PlaybackOptions::default());
4542        assert_eq!(events.len(), 4);
4543        let expected_measure_secs = 4.0 * 60.0 / (60.0 - 120.0) * (60.0f64 / 120.0).ln();
4544        assert!((events[2].time_secs - expected_measure_secs).abs() < 1e-9);
4545        assert!((events[0].duration_secs - 1.1507282898).abs() < 1e-6);
4546        assert!((events[2].duration_secs - 2.0).abs() < 1e-9);
4547    }
4548
4549    #[test]
4550    fn breath_and_caesura_expose_deterministic_post_note_pause() {
4551        let mut score = Score::new("pause", 120, 4, 4, 0, 1);
4552        let mut breath = crate::Note::new(
4553            crate::Pitch::new(crate::Step::C, 4),
4554            crate::Duration::Quarter,
4555        );
4556        breath.articulations.push(Articulation::BreathMark);
4557        let mut caesura = crate::Note::new(
4558            crate::Pitch::new(crate::Step::D, 4),
4559            crate::Duration::Quarter,
4560        );
4561        caesura
4562            .articulations
4563            .extend([Articulation::BreathMark, Articulation::Caesura]);
4564        score.parts[0].staves[0].measures[0].voices[0] = vec![breath, caesura];
4565
4566        let events = to_playback_events(&score, &PlaybackOptions::default());
4567        assert_eq!(events.len(), 2);
4568        assert_eq!(events[0].post_note_pause_beats, 0.25);
4569        assert_eq!(events[1].post_note_pause_beats, 0.5);
4570        assert_eq!(
4571            events[1].articulations,
4572            vec![Articulation::BreathMark, Articulation::Caesura]
4573        );
4574    }
4575
4576    #[test]
4577    fn measure_instrument_change_resolves_on_playback_events() {
4578        let mut score = Score::new("instrument", 120, 4, 4, 0, 2);
4579        let mut base = crate::InstrumentDefinition::new("piano", "Piano");
4580        base.midi_channel = 1;
4581        base.midi_program = 0;
4582        score.parts[0].instrument = Some(base);
4583        let mut change = crate::InstrumentDefinition::new("flute", "Flute");
4584        change.midi_channel = 2;
4585        change.midi_program = 73;
4586        change.transpose_semitones = -2;
4587        score.parts[0].staves[0].measures[1].instrument_change = Some(change);
4588        for measure in &mut score.parts[0].staves[0].measures {
4589            measure.voices[0] = vec![crate::Note::new(
4590                crate::Pitch::new(crate::Step::C, 4),
4591                crate::Duration::Whole,
4592            )];
4593        }
4594
4595        let events = to_playback_events(&score, &PlaybackOptions::default());
4596        assert_eq!(events.len(), 2);
4597        assert_eq!(
4598            (
4599                events[0].channel,
4600                events[0].program,
4601                events[0].instrument_id.as_deref()
4602            ),
4603            (1, 0, Some("piano"))
4604        );
4605        assert_eq!(
4606            (
4607                events[1].channel,
4608                events[1].program,
4609                events[1].instrument_id.as_deref()
4610            ),
4611            (2, 73, Some("flute"))
4612        );
4613        assert_eq!(events[0].pitch_midi, 60);
4614        assert_eq!(events[1].pitch_midi, 58);
4615    }
4616
4617    #[test]
4618    fn generic_playback_event_preserves_authored_guitar_technique() {
4619        let mut score = Score::new("technique", 120, 4, 4, 0, 1);
4620        let mut note = Note::new(Pitch::new(Step::E, 4), Duration::Quarter);
4621        note.guitar_technique = Some(GuitarTechnique::HammerOn);
4622        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
4623
4624        let event = to_playback_events(&score, &PlaybackOptions::default())
4625            .into_iter()
4626            .next()
4627            .expect("one note event");
4628        assert_eq!(event.guitar_technique, Some(GuitarTechnique::HammerOn));
4629    }
4630
4631    #[test]
4632    fn playback_timing_comparison_reports_tolerance_and_identity() {
4633        let expected = [comparison_event(1.0, 0.5)];
4634        let actual = [comparison_event(1.004, 0.503)];
4635        let report = compare_playback_timing(
4636            &expected,
4637            &actual,
4638            &PlaybackTimingTolerance {
4639                start_secs: 0.005,
4640                duration_secs: 0.005,
4641            },
4642        )
4643        .expect("comparison");
4644        assert!(report.within_tolerance);
4645        assert_eq!(report.matched_events, 1);
4646        assert_eq!(
4647            report.contract_version,
4648            PLAYBACK_COMPARISON_CONTRACT_VERSION
4649        );
4650
4651        let mut typed_only = comparison_event(1.004, 0.503);
4652        typed_only.address = None;
4653        let report = compare_playback_timing(
4654            &expected,
4655            &[typed_only],
4656            &PlaybackTimingTolerance::default(),
4657        )
4658        .expect("typed source comparison");
4659        assert_eq!(report.matched_events, 1);
4660
4661        let actual = [comparison_event(1.02, 0.6)];
4662        let report =
4663            compare_playback_timing(&expected, &actual, &PlaybackTimingTolerance::default())
4664                .expect("comparison");
4665        assert!(!report.within_tolerance);
4666        assert!(
4667            report
4668                .mismatches
4669                .iter()
4670                .any(|m| matches!(m, PlaybackTimingMismatch::StartTime { index: 0, .. }))
4671        );
4672        assert!(
4673            report
4674                .mismatches
4675                .iter()
4676                .any(|m| matches!(m, PlaybackTimingMismatch::Duration { index: 0, .. }))
4677        );
4678    }
4679
4680    #[test]
4681    fn playback_timing_comparison_rejects_instrument_route_mismatch() {
4682        let expected = comparison_event(0.0, 0.5);
4683        let mut actual = expected.clone();
4684        actual.program = 73;
4685        assert!(
4686            compare_playback_timing(&[expected], &[actual], &PlaybackTimingTolerance::default(),)
4687                .expect("comparison")
4688                .mismatches
4689                .iter()
4690                .any(|mismatch| matches!(
4691                    mismatch,
4692                    PlaybackTimingMismatch::EventIdentity { index: 0 }
4693                ))
4694        );
4695    }
4696
4697    #[test]
4698    fn playback_timing_comparison_rejects_invalid_tolerance() {
4699        let error = compare_playback_timing(
4700            &[],
4701            &[],
4702            &PlaybackTimingTolerance {
4703                start_secs: -0.1,
4704                duration_secs: 0.0,
4705            },
4706        );
4707        assert!(matches!(
4708            error,
4709            Err(crate::Error::InvalidPlaybackComparison)
4710        ));
4711    }
4712
4713    #[test]
4714    fn tablature_performance_projection_keeps_position_and_reports_pitch_error() {
4715        let mut score = Score::new("Tab", 120, 4, 4, 0, 1);
4716        score.parts[0].staves[0].tablature = Some(super::super::notation::TablatureConfig {
4717            lines: 6,
4718            tuning_midi: vec![40, 45, 50, 55, 59, 64],
4719            capo: 0,
4720        });
4721        let notes = &mut score.parts[0].staves[0].measures[0].voices[0];
4722        *notes = vec![crate::Note::new(
4723            crate::Pitch::new(crate::Step::C, 4),
4724            crate::Duration::Quarter,
4725        )];
4726        notes[0].tab_position = Some(super::super::notation::TabPosition {
4727            string: 1,
4728            fret: 20,
4729        });
4730        notes[0].guitar_technique = Some(super::super::notation::GuitarTechnique::Bend);
4731        notes[0].guitar_bend_alter_cents = Some(150);
4732        notes[0].guitar_bend_curve = vec![
4733            super::super::score::GuitarBendPoint {
4734                position_per_mille: 0,
4735                alter_cents: 0,
4736            },
4737            super::super::score::GuitarBendPoint {
4738                position_per_mille: 500,
4739                alter_cents: 150,
4740            },
4741            super::super::score::GuitarBendPoint {
4742                position_per_mille: 1_000,
4743                alter_cents: 0,
4744            },
4745        ];
4746        let report = project_tablature_performance(&score, &PlaybackOptions::default())
4747            .expect("tablature projection");
4748        assert_eq!(report.events.len(), 1);
4749        assert_eq!(report.events[0].string, 1);
4750        assert_eq!(report.events[0].fret, 20);
4751        assert_eq!(
4752            report.events[0].technique,
4753            Some(super::super::notation::GuitarTechnique::Bend)
4754        );
4755        assert_eq!(report.events[0].bend_alter_cents, Some(150));
4756        assert_eq!(report.events[0].bend_curve.len(), 3);
4757        assert_eq!(report.events[0].bend_curve[1].position_per_mille, 500);
4758        assert_eq!(report.events[0].bend_curve[1].alter_cents, 150);
4759        assert_eq!(
4760            report.events[0].playback.pitch_bend_curve,
4761            report.events[0].bend_curve
4762        );
4763        assert!(report.diagnostics.is_empty());
4764
4765        score.parts[0].staves[0].measures[0].voices[0][0].tab_position =
4766            Some(super::super::notation::TabPosition {
4767                string: 1,
4768                fret: 19,
4769            });
4770        let report = project_tablature_performance(&score, &PlaybackOptions::default())
4771            .expect("tablature projection");
4772        assert_eq!(report.events[0].pitch_error_cents, 100);
4773        assert!(matches!(
4774            report.diagnostics[0],
4775            TablaturePerformanceDiagnostic::PitchMismatch {
4776                error_cents: 100,
4777                ..
4778            }
4779        ));
4780    }
4781
4782    #[test]
4783    fn tablature_performance_projection_does_not_invent_missing_positions() {
4784        let mut score = Score::new("Tab", 120, 4, 4, 0, 1);
4785        score.parts[0].staves[0].tablature = Some(super::super::notation::TablatureConfig {
4786            lines: 6,
4787            tuning_midi: vec![40, 45, 50, 55, 59, 64],
4788            capo: 0,
4789        });
4790        score.parts[0].staves[0].measures[0].voices[0].push(crate::Note::new(
4791            crate::Pitch::new(crate::Step::C, 4),
4792            crate::Duration::Quarter,
4793        ));
4794        let report = project_tablature_performance(&score, &PlaybackOptions::default())
4795            .expect("tablature projection");
4796        assert!(report.events.is_empty());
4797        assert!(matches!(
4798            report.diagnostics[0],
4799            TablaturePerformanceDiagnostic::MissingPosition { .. }
4800        ));
4801    }
4802
4803    #[test]
4804    fn tablature_performance_event_accepts_legacy_json_without_technique() {
4805        let mut score = Score::new("Tab", 120, 4, 4, 0, 1);
4806        score.parts[0].staves[0].tablature = Some(super::super::notation::TablatureConfig {
4807            lines: 6,
4808            tuning_midi: vec![40, 45, 50, 55, 59, 64],
4809            capo: 0,
4810        });
4811        let mut note = crate::Note::new(
4812            crate::Pitch::new(crate::Step::C, 4),
4813            crate::Duration::Quarter,
4814        );
4815        note.tab_position = Some(super::super::notation::TabPosition {
4816            string: 1,
4817            fret: 20,
4818        });
4819        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
4820        let report = project_tablature_performance(&score, &PlaybackOptions::default())
4821            .expect("tablature projection");
4822        let mut legacy = serde_json::to_value(&report.events[0]).expect("event JSON");
4823        legacy
4824            .as_object_mut()
4825            .expect("event object")
4826            .remove("technique");
4827        let restored: TablaturePerformanceEvent =
4828            serde_json::from_value(legacy).expect("legacy event JSON");
4829        assert_eq!(restored.technique, None);
4830    }
4831
4832    #[test]
4833    fn tablature_round_trip_report_preserves_authored_positions() {
4834        let mut score = Score::new("Tab", 120, 4, 4, 0, 1);
4835        score.parts[0].staves[0].tablature = Some(super::super::notation::TablatureConfig {
4836            lines: 6,
4837            tuning_midi: vec![40, 45, 50, 55, 59, 64],
4838            capo: 2,
4839        });
4840        let mut note = crate::Note::new(
4841            crate::Pitch::new(crate::Step::C, 4),
4842            crate::Duration::Quarter,
4843        );
4844        note.tab_positions = vec![crate::TabPosition { string: 5, fret: 1 }];
4845        score.parts[0].staves[0].measures[0].voices[0] = vec![note];
4846        let report = tablature_round_trip_report(&score).expect("tab round-trip report");
4847        assert!(report.equivalent);
4848        assert_eq!(report.checked_notes, 1);
4849        assert_eq!(report.positioned_notes, 1);
4850        assert!(report.diagnostics.is_empty());
4851    }
4852
4853    #[test]
4854    fn tablature_performance_uses_measure_local_tuning_change() {
4855        let mut score = Score::new("Local tuning", 120, 4, 4, 0, 2);
4856        let staff = &mut score.parts[0].staves[0];
4857        staff.tablature = Some(super::super::notation::TablatureConfig {
4858            lines: 6,
4859            tuning_midi: vec![40, 45, 50, 55, 59, 64],
4860            capo: 0,
4861        });
4862        staff.measures[1].tablature_change = Some(super::super::notation::TablatureConfig {
4863            lines: 6,
4864            tuning_midi: vec![38, 45, 50, 55, 59, 64],
4865            capo: 0,
4866        });
4867        let mut note = Note::new(Pitch::new(Step::C, 3), Duration::Quarter);
4868        note.tab_position = Some(TabPosition {
4869            string: 1,
4870            fret: 10,
4871        });
4872        staff.measures[1].voices[0] = vec![note];
4873
4874        let report = project_tablature_performance(&score, &PlaybackOptions::default())
4875            .expect("tablature projection");
4876        assert_eq!(report.events.len(), 1);
4877        assert_eq!(report.events[0].expected_pitch_midi_cents, 4_800);
4878        assert!(!report.diagnostics.iter().any(|diagnostic| matches!(
4879            diagnostic,
4880            TablaturePerformanceDiagnostic::PitchMismatch { .. }
4881        )));
4882    }
4883}