rustysynth-ext 1.5.0

A SoundFont (sf2, sf3) MIDI synthesizer written in pure Rust (a fork of rustysynth)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
use std::cmp::Ordering;
use std::io::Read;

use crate::MidiFileError;
use crate::MidiFileLoopType;
use crate::binary_reader::BinaryReader;
use crate::four_cc::FourCC;
use crate::read_counter::ReadCounter;

/// A single event of a merged MIDI file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MidiMessage {
    /// A channel message; `status` includes the channel in its low nibble.
    Normal { status: u8, data1: u8, data2: u8 },
    /// A tempo change in microseconds per quarter note (FF 51 03).
    ///
    /// Only seen while parsing; tempo changes are folded into the event times
    /// and never appear in the merged list.
    TempoChange { bytes: [u8; 3] },
    /// Loop start marker (loop extensions only).
    LoopStart,
    /// Loop end marker (loop extensions only).
    LoopEnd,
    /// End of track.
    EndOfTrack,
}

impl MidiMessage {
    pub(crate) fn common1(status: u8, data1: u8) -> Self {
        Self::Normal {
            status,
            data1,
            data2: 0,
        }
    }

    pub(crate) fn common2(status: u8, data1: u8, data2: u8, loop_type: MidiFileLoopType) -> Self {
        let command = status & 0xF0;

        if command == 0xB0 {
            match loop_type {
                MidiFileLoopType::RpgMaker if data1 == 111 => {
                    return MidiMessage::LoopStart;
                }

                MidiFileLoopType::IncredibleMachine => {
                    if data1 == 110 {
                        return MidiMessage::LoopStart;
                    }
                    if data1 == 111 {
                        return MidiMessage::LoopEnd;
                    }
                }

                MidiFileLoopType::FinalFantasy => {
                    if data1 == 116 {
                        return MidiMessage::LoopStart;
                    }
                    if data1 == 117 {
                        return MidiMessage::LoopEnd;
                    }
                }

                _ => (),
            }
        }

        Self::Normal {
            status,
            data1,
            data2,
        }
    }

    pub(crate) fn tempo_change(tempo: i32) -> Self {
        // Truncate to u24
        let bytes = tempo.to_be_bytes()[1..].try_into().unwrap();
        Self::TempoChange { bytes }
    }
}

/// Represents a standard MIDI file.
#[derive(Debug)]
#[non_exhaustive]
pub struct MidiFile {
    pub(crate) messages: Vec<MidiMessage>,
    pub(crate) times: Vec<f64>,
}

impl MidiFile {
    /// Loads a MIDI file from the stream.
    ///
    /// # Arguments
    ///
    /// * `reader` - The data stream used to load the MIDI file.
    pub fn new<R: Read>(reader: &mut R) -> Result<Self, MidiFileError> {
        MidiFile::new_with_loop_type(reader, MidiFileLoopType::LoopPoint(0))
    }

    /// Loads a MIDI file from the stream with a specified loop type.
    ///
    /// # Arguments
    ///
    /// * `reader` - The data stream used to load the MIDI file.
    /// * `loop_type` - The type of the loop extension to be used.
    ///
    /// # Remarks
    ///
    /// `MidiFileLoopType` has the following variants:
    /// * `LoopPoint(usize)` - Specifies the loop start point by a tick value.
    /// * `RpgMaker` - The RPG Maker style loop.
    ///   CC #111 will be the loop start point.
    /// * `IncredibleMachine` - The Incredible Machine style loop.
    ///   CC #110 and #111 will be the start and end points of the loop.
    /// * `FinalFantasy` - The Final Fantasy style loop.
    ///   CC #116 and #117 will be the start and end points of the loop.
    pub fn new_with_loop_type<R: Read>(
        reader: &mut R,
        loop_type: MidiFileLoopType,
    ) -> Result<Self, MidiFileError> {
        let chunk_type = BinaryReader::read_four_cc(reader)?;
        if chunk_type != b"MThd" {
            return Err(MidiFileError::InvalidChunkType {
                expected: FourCC::from_bytes(*b"MThd"),
                actual: chunk_type,
            });
        }

        let size = BinaryReader::read_i32_big_endian(reader)?;
        if size != 6 {
            return Err(MidiFileError::InvalidChunkData(FourCC::from_bytes(
                *b"MThd",
            )));
        }

        let format = BinaryReader::read_i16_big_endian(reader)?;
        if !(format == 0 || format == 1) {
            return Err(MidiFileError::UnsupportedFormat(format));
        }

        // The SMF specification requires at least one track chunk.
        let track_count = BinaryReader::read_i16_big_endian(reader)?;
        if track_count <= 0 {
            return Err(MidiFileError::InvalidChunkData(FourCC::from_bytes(
                *b"MThd",
            )));
        }

        // The time division must be a positive number of ticks per quarter
        // note. SMPTE timecode divisions are encoded with bit 15 set (i.e. a
        // negative value here) and are not supported.
        let resolution = BinaryReader::read_i16_big_endian(reader)?;
        if resolution <= 0 {
            return Err(MidiFileError::InvalidTimeDivision(resolution));
        }
        let track_count = track_count as i32;
        let resolution = resolution as i32;

        let mut message_lists: Vec<Vec<MidiMessage>> = Vec::with_capacity(track_count as usize);
        let mut tick_lists: Vec<Vec<i32>> = Vec::with_capacity(track_count as usize);

        for _i in 0..track_count {
            let (message_list, tick_list) = MidiFile::read_track(reader, loop_type)?;
            message_lists.push(message_list);
            tick_lists.push(tick_list);
        }

        match loop_type {
            MidiFileLoopType::LoopPoint(loop_point) if loop_point != 0 => {
                let loop_point = loop_point as i32;
                let tick_list = &mut tick_lists[0];
                let message_list = &mut message_lists[0];

                if loop_point <= *tick_list.last().unwrap() {
                    for i in 0..tick_list.len() {
                        if tick_list[i] >= loop_point {
                            tick_list.insert(i, loop_point);
                            message_list.insert(i, MidiMessage::LoopStart);
                            break;
                        }
                    }
                } else {
                    tick_list.push(loop_point);
                    message_list.push(MidiMessage::LoopStart);
                }
            }
            _ => (),
        }

        let (messages, times) = MidiFile::merge_tracks(&message_lists, &tick_lists, resolution);

        Ok(Self { messages, times })
    }

    fn discard_data<R: Read>(reader: &mut R) -> Result<(), MidiFileError> {
        let size = BinaryReader::read_i32_variable_length(reader)? as usize;
        BinaryReader::discard_data(reader, size)?;
        Ok(())
    }

    fn read_tempo<R: Read>(reader: &mut R) -> Result<i32, MidiFileError> {
        let size = BinaryReader::read_i32_variable_length(reader)?;
        if size != 3 {
            return Err(MidiFileError::InvalidTempoValue);
        }

        let b1 = BinaryReader::read_u8(reader)? as i32;
        let b2 = BinaryReader::read_u8(reader)? as i32;
        let b3 = BinaryReader::read_u8(reader)? as i32;

        Ok((b1 << 16) | (b2 << 8) | b3)
    }

    fn read_track<R: Read>(
        reader: &mut R,
        loop_type: MidiFileLoopType,
    ) -> Result<(Vec<MidiMessage>, Vec<i32>), MidiFileError> {
        let chunk_type = BinaryReader::read_four_cc(reader)?;
        if chunk_type != b"MTrk" {
            return Err(MidiFileError::InvalidChunkType {
                expected: FourCC::from_bytes(*b"MTrk"),
                actual: chunk_type,
            });
        }

        let size_i32 = BinaryReader::read_i32_big_endian(reader)?;
        // A negative chunk size is malformed data; casting it straight to
        // `usize` would wrap into a huge allocation bound / skip bound.
        if size_i32 < 0 {
            return Err(MidiFileError::InvalidChunkData(FourCC::from_bytes(
                *b"MTrk",
            )));
        }
        let size = size_i32 as usize;
        let reader = &mut ReadCounter::new(reader);

        let mut messages: Vec<MidiMessage> = Vec::new();
        let mut ticks: Vec<i32> = Vec::new();

        let mut tick: i32 = 0;
        let mut last_status: u8 = 0;

        loop {
            // Stay inside this track chunk: a track without an EndOfTrack, or
            // a chunk size smaller than the event data, must not bleed into
            // the bytes of the following chunk.
            if reader.bytes_read() >= size {
                return Err(MidiFileError::InvalidChunkData(FourCC::from_bytes(
                    *b"MTrk",
                )));
            }

            let delta = BinaryReader::read_i32_variable_length(reader)?;
            let first = BinaryReader::read_u8(reader)?;

            // A delta time that pushes the tick past the range of the type would
            // make the timing jump backwards instead of failing the load.
            // https://github.com/sinshu/rustysynth/issues/57
            let Some(next) = tick.checked_add(delta) else {
                return Err(MidiFileError::InvalidChunkData(FourCC::from_bytes(
                    *b"MTrk",
                )));
            };
            tick = next;

            if (first & 128) == 0 {
                let command = last_status & 0xF0;
                if command == 0xC0 || command == 0xD0 {
                    messages.push(MidiMessage::common1(last_status, first));
                    ticks.push(tick);
                } else {
                    let data2 = BinaryReader::read_u8(reader)?;
                    messages.push(MidiMessage::common2(last_status, first, data2, loop_type));
                    ticks.push(tick);
                }

                continue;
            }

            match first {
                0xF0 => MidiFile::discard_data(reader)?,
                0xF7 => MidiFile::discard_data(reader)?,
                0xFF => match BinaryReader::read_u8(reader)? {
                    0x2F => {
                        BinaryReader::read_u8(reader)?;
                        messages.push(MidiMessage::EndOfTrack);
                        ticks.push(tick);

                        // Some MIDI files may have events inserted after the EOT.
                        // Such events should be ignored. An EOT past the
                        // declared chunk end means the size itself is corrupt:
                        // error out instead of underflowing the subtraction.
                        match reader.bytes_read().cmp(&size) {
                            Ordering::Less => {
                                BinaryReader::discard_data(reader, size - reader.bytes_read())?;
                            }
                            Ordering::Equal => (),
                            Ordering::Greater => {
                                return Err(MidiFileError::InvalidChunkData(FourCC::from_bytes(
                                    *b"MTrk",
                                )));
                            }
                        }

                        return Ok((messages, ticks));
                    }
                    0x51 => {
                        messages.push(MidiMessage::tempo_change(MidiFile::read_tempo(reader)?));
                        ticks.push(tick);
                    }
                    _ => MidiFile::discard_data(reader)?,
                },
                _ => {
                    let command = first & 0xF0;
                    if command == 0xC0 || command == 0xD0 {
                        let data1 = BinaryReader::read_u8(reader)?;
                        messages.push(MidiMessage::common1(first, data1));
                        ticks.push(tick);
                    } else {
                        let data1 = BinaryReader::read_u8(reader)?;
                        let data2 = BinaryReader::read_u8(reader)?;
                        messages.push(MidiMessage::common2(first, data1, data2, loop_type));
                        ticks.push(tick);
                    }
                }
            }

            // Per the SMF specification, only channel messages update the
            // running status byte; SysEx and Meta events interrupt (clear) it.
            last_status = if first >= 0xF0 { 0 } else { first };
        }
    }

    fn merge_tracks(
        message_lists: &[Vec<MidiMessage>],
        tick_lists: &[Vec<i32>],
        resolution: i32,
    ) -> (Vec<MidiMessage>, Vec<f64>) {
        // Every merged message corresponds to one entry in one of the tick lists.
        let total_messages: usize = tick_lists.iter().map(Vec::len).sum();
        let mut merged_messages: Vec<MidiMessage> = Vec::with_capacity(total_messages);
        let mut merged_times: Vec<f64> = Vec::with_capacity(total_messages);

        let mut indices: Vec<usize> = vec![0; message_lists.len()];

        let mut current_tick: i32 = 0;
        let mut current_time: f64 = 0.0;

        let mut tempo: f64 = 120.0;

        loop {
            // A tick can be as large as i32::MAX, so the sentinel that marks
            // "no track left" has to stay outside the range of the values it is
            // compared against.
            let mut min_tick = i64::MAX;
            let mut min_index: i32 = -1;

            for ch in 0..tick_lists.len() {
                if indices[ch] < tick_lists[ch].len() {
                    let tick = tick_lists[ch][indices[ch]] as i64;
                    if tick < min_tick {
                        min_tick = tick;
                        min_index = ch as i32;
                    }
                }
            }

            if min_index == -1 {
                break;
            }

            let next_tick = tick_lists[min_index as usize][indices[min_index as usize]];
            let delta_tick = next_tick as i64 - current_tick as i64;
            let delta_time = 60.0 / (resolution as f64 * tempo) * delta_tick as f64;

            current_tick = next_tick;
            current_time += delta_time;

            let message = message_lists[min_index as usize][indices[min_index as usize]];
            if let MidiMessage::TempoChange { bytes } = message {
                let tempo_i32 = i32::from_be_bytes([0, bytes[0], bytes[1], bytes[2]]);
                // A tempo of 0 microseconds per quarter note is invalid data;
                // keep the previous tempo instead of dividing by zero.
                if tempo_i32 > 0 {
                    tempo = 60000000.0 / tempo_i32 as f64;
                }
            } else {
                merged_messages.push(message);
                merged_times.push(current_time);
            }

            indices[min_index as usize] += 1;
        }

        (merged_messages, merged_times)
    }

    /// Get the length of the MIDI file in seconds.
    pub fn get_length(&self) -> f64 {
        self.times.last().copied().unwrap_or(0.0)
    }

    /// Get the merged message list of the MIDI file.
    ///
    /// Parallel to [`get_times`](Self::get_times): message *i* occurs at
    /// `get_times()[i]`. Tempo changes are already folded into the times.
    pub fn get_messages(&self) -> &[MidiMessage] {
        &self.messages
    }

    /// Get the time of every message in absolute seconds.
    ///
    /// Parallel to [`get_messages`](Self::get_messages).
    pub fn get_times(&self) -> &[f64] {
        &self.times
    }

    /// Creates a MIDI file from an event list without parsing.
    ///
    /// Times must be in non-decreasing order (same-time events allowed);
    /// returns [`MidiFileError::InvalidEventList`] otherwise. Accepts any
    /// iterator of `(time, message)` pairs.
    pub fn new_with_events<I>(events: I) -> Result<Self, MidiFileError>
    where
        I: IntoIterator<Item = (f64, MidiMessage)>,
    {
        let mut file = Self::default();
        file.extend_events(events)?;
        Ok(file)
    }

    /// Appends events to the end of the MIDI file.
    ///
    /// Appended times must be non-decreasing and not earlier than the last
    /// existing time; otherwise returns [`MidiFileError::InvalidEventList`]
    /// and leaves the file unchanged. To replace all events, call
    /// [`clear`](Self::clear) first.
    pub fn extend_events<I>(&mut self, events: I) -> Result<(), MidiFileError>
    where
        I: IntoIterator<Item = (f64, MidiMessage)>,
    {
        let base = self.messages.len();
        let mut last_time = self.times.last().copied().unwrap_or(f64::NEG_INFINITY);

        let iter = events.into_iter();
        let (min, max) = iter.size_hint();
        // `Vec::reserve` is a no-op when the current capacity already
        // suffices, so appending a similar amount of events reuses the
        // existing allocation.
        let capacity = max.unwrap_or(min);
        self.messages.reserve(capacity);
        self.times.reserve(capacity);

        for (time, message) in iter {
            // `partial_cmp` yields `None` for NaN, so NaN times are also
            // rejected here.
            if !matches!(
                time.partial_cmp(&last_time),
                Some(Ordering::Greater | Ordering::Equal)
            ) {
                self.messages.truncate(base);
                self.times.truncate(base);
                return Err(MidiFileError::InvalidEventList);
            }
            last_time = time;
            self.messages.push(message);
            self.times.push(time);
        }
        Ok(())
    }

    /// Removes all events from the MIDI file.
    pub fn clear(&mut self) {
        self.messages.clear();
        self.times.clear();
    }
}

impl Default for MidiFile {
    /// Creates an empty MIDI file.
    fn default() -> Self {
        Self {
            messages: Vec::new(),
            times: Vec::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_message_size() {
        // Avoid increasing the size of the MidiMessage type
        assert_eq!(size_of::<MidiMessage>(), 4);
    }

    /// Encodes a value as a MIDI variable-length quantity.
    fn vlq(mut value: u32) -> Vec<u8> {
        let mut groups = Vec::new();
        loop {
            groups.push((value & 0x7F) as u8);
            value >>= 7;
            if value == 0 {
                break;
            }
        }
        groups.reverse();
        let last = groups.len() - 1;
        for (i, byte) in groups.iter_mut().enumerate() {
            if i != last {
                *byte |= 0x80;
            }
        }
        groups
    }

    /// Builds an `MThd` header chunk.
    fn mthd(format: u16, track_count: u16, resolution: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        bytes.extend_from_slice(b"MThd");
        bytes.extend_from_slice(&6u32.to_be_bytes());
        bytes.extend_from_slice(&format.to_be_bytes());
        bytes.extend_from_slice(&track_count.to_be_bytes());
        bytes.extend_from_slice(&resolution.to_be_bytes());
        bytes
    }

    /// Appends an `MTrk` chunk with the given event data.
    fn mtrk(bytes: &mut Vec<u8>, data: &[u8]) {
        bytes.extend_from_slice(b"MTrk");
        bytes.extend_from_slice(&(data.len() as u32).to_be_bytes());
        bytes.extend_from_slice(data);
    }

    // Events: delta 480: note on (60, 100); delta 480: end of track.
    // PPQ 480 at the default 120 BPM: 480 ticks = 0.5 s.
    fn note_at_480() -> Vec<u8> {
        let mut data = mthd(0, 1, 480);
        let mut track = vlq(480);
        track.extend_from_slice(&[0x90, 0x3C, 0x64]);
        track.extend_from_slice(&vlq(480));
        track.extend_from_slice(&[0xFF, 0x2F, 0x00]);
        mtrk(&mut data, &track);
        data
    }

    fn assert_close(actual: f64, expected: f64) {
        assert!(
            (actual - expected).abs() < 1e-6,
            "expected {expected}, but was {actual}"
        );
    }

    #[test]
    fn test_default_tempo_timing() {
        let data = note_at_480();
        let midi = MidiFile::new(&mut data.as_slice()).unwrap();

        assert_eq!(midi.messages.len(), 2);
        assert_eq!(
            midi.messages[0],
            MidiMessage::Normal {
                status: 0x90,
                data1: 0x3C,
                data2: 0x64,
            }
        );
        assert_eq!(midi.messages[1], MidiMessage::EndOfTrack);
        assert_eq!(midi.times.len(), 2);
        assert_close(midi.times[0], 0.5);
        assert_close(midi.times[1], 1.0);
        assert_close(midi.get_length(), 1.0);
    }

    #[test]
    fn test_tempo_change_timing() {
        // Tempo change to 250000 us/quarter = 240 BPM at tick 0, then a note
        // at tick 480 (0.25 s at 240 BPM) and EOT at tick 960 (0.5 s).
        let mut data = mthd(0, 1, 480);
        let mut track = vlq(0);
        track.extend_from_slice(&[0xFF, 0x51, 0x03, 0x03, 0xD0, 0x90]);
        track.extend_from_slice(&vlq(480));
        track.extend_from_slice(&[0x90, 0x3C, 0x64]);
        track.extend_from_slice(&vlq(480));
        track.extend_from_slice(&[0xFF, 0x2F, 0x00]);
        mtrk(&mut data, &track);

        let midi = MidiFile::new(&mut data.as_slice()).unwrap();

        // The tempo change is consumed during the merge and not emitted.
        assert_eq!(midi.messages.len(), 2);
        assert_close(midi.times[0], 0.25);
        assert_close(midi.times[1], 0.5);
        assert_close(midi.get_length(), 0.5);
    }

    #[test]
    fn test_invalid_tempo_value_is_ignored() {
        // A tempo of 0 us/quarter is invalid; the previous tempo (the 120 BPM
        // default) must be kept, so timing stays intact instead of collapsing.
        let mut data = mthd(0, 1, 480);
        let mut track = vlq(0);
        track.extend_from_slice(&[0xFF, 0x51, 0x03, 0x00, 0x00, 0x00]);
        track.extend_from_slice(&vlq(480));
        track.extend_from_slice(&[0x90, 0x3C, 0x64]);
        track.extend_from_slice(&vlq(480));
        track.extend_from_slice(&[0xFF, 0x2F, 0x00]);
        mtrk(&mut data, &track);

        let midi = MidiFile::new(&mut data.as_slice()).unwrap();
        assert_eq!(midi.messages.len(), 2);
        assert_close(midi.times[0], 0.5);
        assert_close(midi.times[1], 1.0);
    }

    #[test]
    fn test_running_status_within_channel_messages() {
        // Three note-on events in a row using running status.
        let mut data = mthd(0, 1, 480);
        let mut track = vlq(0);
        track.extend_from_slice(&[0x90, 0x3C, 0x64]); // full status
        track.extend_from_slice(&vlq(0));
        track.extend_from_slice(&[0x3D, 0x60]); // running status
        track.extend_from_slice(&vlq(0));
        track.extend_from_slice(&[0x3E, 0x50]); // running status
        track.extend_from_slice(&vlq(0));
        track.extend_from_slice(&[0xFF, 0x2F, 0x00]);
        mtrk(&mut data, &track);

        let midi = MidiFile::new(&mut data.as_slice()).unwrap();
        assert_eq!(
            midi.messages,
            vec![
                MidiMessage::Normal {
                    status: 0x90,
                    data1: 0x3C,
                    data2: 0x64,
                },
                MidiMessage::Normal {
                    status: 0x90,
                    data1: 0x3D,
                    data2: 0x60,
                },
                MidiMessage::Normal {
                    status: 0x90,
                    data1: 0x3E,
                    data2: 0x50,
                },
                MidiMessage::EndOfTrack,
            ]
        );
    }

    #[test]
    fn test_running_status_cleared_by_meta_event() {
        // Per the SMF specification, Meta events interrupt (clear) running
        // status, so the data byte after the tempo event must not reuse the
        // previous channel status. It is parsed with status 0 instead.
        let mut data = mthd(0, 1, 480);
        let mut track = vlq(0);
        track.extend_from_slice(&[0x90, 0x3C, 0x64]);
        track.extend_from_slice(&vlq(0));
        track.extend_from_slice(&[0xFF, 0x51, 0x03, 0x07, 0xA1, 0x20]); // 500000 us
        track.extend_from_slice(&vlq(0));
        track.extend_from_slice(&[0x3D, 0x64]); // data byte after a Meta event
        track.extend_from_slice(&vlq(0));
        track.extend_from_slice(&[0xFF, 0x2F, 0x00]);
        mtrk(&mut data, &track);

        let midi = MidiFile::new(&mut data.as_slice()).unwrap();
        assert_eq!(
            midi.messages,
            vec![
                MidiMessage::Normal {
                    status: 0x90,
                    data1: 0x3C,
                    data2: 0x64,
                },
                MidiMessage::Normal {
                    status: 0x00,
                    data1: 0x3D,
                    data2: 0x64,
                },
                MidiMessage::EndOfTrack,
            ]
        );
    }

    #[test]
    fn test_smpte_time_division_is_rejected() {
        // Bit 15 set => SMPTE timecode division (0xE7 0x28 = 25 fps x 40).
        // Negative resolutions cannot produce meaningful tick-to-second
        // timing, so the file is rejected with a clear error.
        let data = mthd(0, 1, 0xE728);
        assert!(matches!(
            MidiFile::new(&mut data.as_slice()),
            Err(MidiFileError::InvalidTimeDivision(-6360))
        ));
    }

    #[test]
    fn test_zero_time_division_is_rejected() {
        let data = mthd(0, 1, 0x0000);
        assert!(matches!(
            MidiFile::new(&mut data.as_slice()),
            Err(MidiFileError::InvalidTimeDivision(0))
        ));
    }

    #[test]
    fn test_empty_track_list_is_rejected() {
        // The SMF specification requires at least one track chunk.
        let data = mthd(0, 0, 480);
        assert!(matches!(
            MidiFile::new(&mut data.as_slice()),
            Err(MidiFileError::InvalidChunkData(_))
        ));
    }

    #[test]
    fn test_message_accessors() {
        let data = note_at_480();
        let midi = MidiFile::new(&mut data.as_slice()).unwrap();

        assert_eq!(midi.get_messages().len(), 2);
        assert_eq!(midi.get_times().len(), 2);
        assert_close(midi.get_times()[0], 0.5);
        assert_close(midi.get_times()[1], 1.0);

        let events: Vec<(f64, MidiMessage)> = midi
            .get_times()
            .iter()
            .copied()
            .zip(midi.get_messages().iter().copied())
            .collect();
        assert_eq!(events.len(), 2);
        assert_close(events[0].0, 0.5);
        assert_eq!(
            events[0].1,
            MidiMessage::Normal {
                status: 0x90,
                data1: 0x3C,
                data2: 0x64,
            }
        );
        assert_close(events[1].0, 1.0);
        assert_eq!(events[1].1, MidiMessage::EndOfTrack);
    }

    #[test]
    fn test_construct_with_events() {
        let midi = MidiFile::new_with_events(vec![
            (
                0.25,
                MidiMessage::Normal {
                    status: 0x90,
                    data1: 60,
                    data2: 100,
                },
            ),
            (0.5, MidiMessage::EndOfTrack),
        ])
        .unwrap();

        assert_eq!(midi.get_messages().len(), 2);
        assert_eq!(midi.get_times(), &[0.25, 0.5]);
        assert_close(midi.get_length(), 0.5);
        assert_close(midi.get_times()[0], 0.25);
        assert_eq!(
            midi.get_messages()[0],
            MidiMessage::Normal {
                status: 0x90,
                data1: 60,
                data2: 100,
            }
        );
    }

    #[test]
    fn test_construct_allows_same_time_events() {
        let midi = MidiFile::new_with_events(vec![
            (
                0.0,
                MidiMessage::Normal {
                    status: 0x90,
                    data1: 60,
                    data2: 100,
                },
            ),
            (
                0.0,
                MidiMessage::Normal {
                    status: 0x90,
                    data1: 61,
                    data2: 100,
                },
            ),
        ])
        .unwrap();
        assert_eq!(midi.get_messages().len(), 2);
    }

    #[test]
    fn test_construct_from_iterator_without_vec() {
        // Any iterator of (time, message) pairs is accepted, so the caller
        // never has to build an intermediate Vec.
        let midi = MidiFile::new_with_events((0..3).map(|i| {
            (
                i as f64 * 0.5,
                MidiMessage::Normal {
                    status: 0x90,
                    data1: i as u8,
                    data2: 100,
                },
            )
        }))
        .unwrap();
        assert_eq!(midi.get_messages().len(), 3);
        assert_eq!(midi.get_times(), &[0.0, 0.5, 1.0]);
    }

    #[test]
    fn test_construct_rejects_unsorted_times() {
        let result = MidiFile::new_with_events(vec![
            (0.5, MidiMessage::EndOfTrack),
            (
                0.25,
                MidiMessage::Normal {
                    status: 0x90,
                    data1: 60,
                    data2: 100,
                },
            ),
        ]);
        assert!(matches!(result, Err(MidiFileError::InvalidEventList)));
    }

    #[test]
    fn test_construct_rejects_nan_time() {
        let result = MidiFile::new_with_events(vec![(f64::NAN, MidiMessage::EndOfTrack)]);
        assert!(matches!(result, Err(MidiFileError::InvalidEventList)));
    }

    #[test]
    fn test_extend_events_and_clear() {
        let mut midi = MidiFile::default();
        assert!(midi.get_messages().is_empty());
        assert_close(midi.get_length(), 0.0);

        midi.extend_events(vec![(0.5, MidiMessage::EndOfTrack)])
            .unwrap();
        assert_eq!(midi.get_times(), &[0.5]);
        assert_close(midi.get_length(), 0.5);

        // Appending keeps the existing events; same-time events are allowed.
        midi.extend_events(vec![(0.5, MidiMessage::EndOfTrack)])
            .unwrap();
        assert_eq!(midi.get_messages().len(), 2);
        assert_eq!(midi.get_times(), &[0.5, 0.5]);

        midi.clear();
        assert!(midi.get_messages().is_empty());
        assert_close(midi.get_length(), 0.0);
    }

    #[test]
    fn test_extend_events_reuses_allocation() {
        let mut midi = MidiFile::default();

        let events: Vec<(f64, MidiMessage)> = (0..100)
            .map(|i| {
                (
                    i as f64 * 0.01,
                    MidiMessage::Normal {
                        status: 0x90,
                        data1: i as u8,
                        data2: 0,
                    },
                )
            })
            .collect();
        midi.extend_events(events.iter().copied()).unwrap();
        let messages_capacity = midi.messages.capacity();
        let times_capacity = midi.times.capacity();
        assert!(messages_capacity >= 100);
        assert!(times_capacity >= 100);

        // clear() + extend() is the way to replace all events; it must reuse
        // the existing buffers instead of allocating new ones.
        midi.clear();
        midi.extend_events(vec![(0.0, MidiMessage::EndOfTrack)])
            .unwrap();
        assert_eq!(midi.messages.capacity(), messages_capacity);
        assert_eq!(midi.times.capacity(), times_capacity);
        assert_eq!(midi.get_messages().len(), 1);
        assert_eq!(midi.get_times(), &[0.0]);
    }

    #[test]
    fn test_extend_events_invalid_input_is_transactional() {
        let mut midi = MidiFile::new_with_events(vec![(0.0, MidiMessage::EndOfTrack)]).unwrap();

        // Out-of-order input (earlier than an existing event, or descending
        // within the batch) must leave the file unchanged.
        let result = midi.extend_events(vec![
            (0.5, MidiMessage::EndOfTrack),
            (0.25, MidiMessage::EndOfTrack),
        ]);
        assert!(matches!(result, Err(MidiFileError::InvalidEventList)));
        assert_eq!(midi.get_messages().len(), 1);
        assert_eq!(midi.get_times(), &[0.0]);

        // An event earlier than the last existing one (0.0) must also be
        // rejected, leaving the file unchanged.
        let result = midi.extend_events(vec![(-0.5, MidiMessage::EndOfTrack)]);
        assert!(matches!(result, Err(MidiFileError::InvalidEventList)));
        assert_eq!(midi.get_times(), &[0.0]);
    }

    #[test]
    fn test_vlq_encoding() {
        assert_eq!(vlq(0), vec![0x00]);
        assert_eq!(vlq(0x40), vec![0x40]);
        assert_eq!(vlq(0x7F), vec![0x7F]);
        assert_eq!(vlq(0x80), vec![0x81, 0x00]);
        assert_eq!(vlq(480), vec![0x83, 0x60]);
        assert_eq!(vlq(0x1FFFFF), vec![0xFF, 0xFF, 0x7F]);
    }

    #[test]
    fn test_negative_mtrk_size_is_rejected() {
        // A negative MTrk chunk size is malformed; it must not wrap into a
        // huge `usize` bound when cast.
        let mut data = mthd(0, 1, 480);
        data.extend_from_slice(b"MTrk");
        data.extend_from_slice(&(-1i32).to_be_bytes());
        data.extend_from_slice(&[0x00, 0xFF, 0x2F, 0x00]);
        assert!(matches!(
            MidiFile::new(&mut data.as_slice()),
            Err(MidiFileError::InvalidChunkData(_))
        ));
    }

    #[test]
    fn test_empty_mtrk_is_rejected() {
        // Zero-length track data holds no EndOfTrack, so the track is
        // truncated rather than empty-but-valid.
        let mut data = mthd(0, 1, 480);
        mtrk(&mut data, &[]);
        assert!(matches!(
            MidiFile::new(&mut data.as_slice()),
            Err(MidiFileError::InvalidChunkData(_))
        ));
    }

    #[test]
    fn test_track_without_eot_does_not_bleed_into_next_chunk() {
        // Track 1 has a note but no EndOfTrack and its declared size covers
        // exactly that note. The parser must stop at the chunk end instead
        // of consuming track 2's header bytes as events.
        let mut data = mthd(0, 2, 480);
        let mut track1 = vlq(0);
        track1.extend_from_slice(&[0x90, 0x3C, 0x64]);
        mtrk(&mut data, &track1);
        let mut track2 = vlq(480);
        track2.extend_from_slice(&[0x90, 0x3C, 0x64]);
        track2.extend_from_slice(&vlq(480));
        track2.extend_from_slice(&[0xFF, 0x2F, 0x00]);
        mtrk(&mut data, &track2);
        assert!(matches!(
            MidiFile::new(&mut data.as_slice()),
            Err(MidiFileError::InvalidChunkData(_))
        ));
    }

    #[test]
    fn test_eot_past_chunk_end_is_rejected() {
        // The EndOfTrack event ends beyond the declared chunk size: the size
        // itself is corrupt. This must error instead of underflowing the
        // trailing-bytes subtraction.
        let mut data = mthd(0, 1, 480);
        data.extend_from_slice(b"MTrk");
        data.extend_from_slice(&2u32.to_be_bytes());
        data.extend_from_slice(&[0x00, 0xFF, 0x2F, 0x00]);
        assert!(matches!(
            MidiFile::new(&mut data.as_slice()),
            Err(MidiFileError::InvalidChunkData(_))
        ));
    }

    // Delta times accumulate into an i32 tick. Summing past the range of the
    // type used to wrap around, which made the timing jump backwards (#57).
    #[test]
    fn test_a_tick_overflow_is_rejected() {
        let mut data = mthd(0, 1, 480);
        let mut track = Vec::new();

        // 2^28 - 1 is the largest delta a four byte variable length quantity
        // can encode, so eight of them approach the i32 limit and the ninth
        // passes it.
        for _ in 0..10 {
            track.extend_from_slice(&vlq(0x0FFF_FFFF));
            track.extend_from_slice(&[0x90, 0x3C, 0x64]);
        }
        mtrk(&mut data, &track);

        assert!(matches!(
            MidiFile::new(&mut data.as_slice()),
            Err(MidiFileError::InvalidChunkData(_))
        ));
    }

    // A tick is allowed to reach exactly i32::MAX. When the sentinel used to
    // find the next event was also i32::MAX, an event on that tick was never
    // selected and the whole remaining sequence was dropped without an error.
    #[test]
    fn test_a_tick_at_the_type_limit_is_kept() {
        let mut data = mthd(0, 1, 480);
        let mut track = Vec::new();

        // Eight of the largest deltas reach 2^31 - 8, and a delta of 7 puts the
        // last event exactly on i32::MAX.
        for _ in 0..8 {
            track.extend_from_slice(&vlq(0x0FFF_FFFF));
            track.extend_from_slice(&[0x90, 0x3C, 0x64]);
        }
        track.extend_from_slice(&vlq(7));
        track.extend_from_slice(&[0xFF, 0x2F, 0x00]);
        mtrk(&mut data, &track);

        let midi = MidiFile::new(&mut data.as_slice()).unwrap();
        assert_eq!(midi.messages.len(), 9);
        assert_eq!(*midi.messages.last().unwrap(), MidiMessage::EndOfTrack);
    }
}