midi_file 0.2.0

For reading and writing MIDI files.
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
use crate::byte_iter::ByteIter;
use crate::core::bits::{decode_14_bit_number, encode_14_bit_number};
use crate::core::{
    Channel, ControlValue, MonoModeChannels, NoteNumber, PitchBendValue, PressureValue, Program,
    QuarterFrameValue, SongNumber, SongPosition, StatusType, Velocity,
};
use crate::error::{Context, Result};
use crate::scribe::Scribe;
use std::convert::TryFrom;
use std::io::{Read, Write};

pub(crate) trait WriteBytes {
    fn write<W: Write>(&self, w: &mut Scribe<W>) -> Result<()>;
}

/// Represents the data that is common, and required for both [`Message::NoteOn`] and
/// [`Message::NoteOff`] messages.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct NoteMessage {
    pub(crate) channel: Channel,
    pub(crate) note_number: NoteNumber,
    pub(crate) velocity: Velocity,
}

impl NoteMessage {
    /// Create a new `NoteMessage`.
    pub fn new(channel: Channel, note_number: NoteNumber, velocity: Velocity) -> Self {
        Self {
            channel,
            note_number,
            velocity,
        }
    }

    /// Getter for the `channel` field.
    pub fn channel(&self) -> Channel {
        self.channel
    }

    /// Getter for the `note_number` field.
    pub fn note_number(&self) -> NoteNumber {
        self.note_number
    }

    /// Getter for the `velocity` field.
    pub fn velocity(&self) -> Velocity {
        self.velocity
    }

    fn parse<R: Read>(iter: &mut ByteIter<R>, channel: Channel) -> Result<Self> {
        Ok(NoteMessage {
            channel,
            note_number: iter.read_or_die().context(io!())?.into(),
            velocity: iter.read_or_die().context(io!())?.into(),
        })
    }

    fn write<W: Write>(&self, w: &mut Scribe<W>, st: StatusType) -> Result<()> {
        write_status_byte(w, st, self.channel)?;
        w.write_all(&self.note_number.get().to_be_bytes())
            .context(wr!())?;
        w.write_all(&self.velocity.get().to_be_bytes())
            .context(wr!())?;
        Ok(())
    }
}

/// Provides the ability to change an instrument (sound, patch, etc.) by specifying the affected
/// channel number and the new program value.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ProgramChangeValue {
    pub(crate) channel: Channel,
    pub(crate) program: Program,
}

impl ProgramChangeValue {
    /// Create a new `ProgramChangeValue`.
    pub fn new(channel: Channel, program: Program) -> Self {
        Self { channel, program }
    }

    /// Get the channel value.
    pub fn channel(&self) -> Channel {
        self.channel
    }

    /// Get the program value.
    pub fn program(&self) -> Program {
        self.program
    }
}

impl WriteBytes for ProgramChangeValue {
    fn write<W: Write>(&self, w: &mut Scribe<W>) -> Result<()> {
        write_status_byte(w, StatusType::Program, self.channel)?;
        write_u8!(w, self.program.get())?;
        Ok(())
    }
}

/// Channel Pressure (After-touch), status `0xD`. This message is most often sent by pressing down
/// on the key after it "bottoms out". Unlike polyphonic after-touch it carries the single greatest
/// pressure value of all the currently depressed keys.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ChannelPressureMessage {
    pub(crate) channel: Channel,
    pub(crate) pressure: PressureValue,
}

impl ChannelPressureMessage {
    /// Create a new `ChannelPressureMessage`.
    pub fn new(channel: Channel, pressure: PressureValue) -> Self {
        Self { channel, pressure }
    }

    /// Getter for the `channel` field.
    pub fn channel(&self) -> Channel {
        self.channel
    }

    /// Getter for the `pressure` field.
    pub fn pressure(&self) -> PressureValue {
        self.pressure
    }

    fn parse<R: Read>(iter: &mut ByteIter<R>, channel: Channel) -> Result<Self> {
        Ok(Self {
            channel,
            pressure: iter.read_or_die().context(io!())?.into(),
        })
    }
}

impl WriteBytes for ChannelPressureMessage {
    fn write<W: Write>(&self, w: &mut Scribe<W>) -> Result<()> {
        write_status_byte(w, StatusType::ChannelPressure, self.channel)?;
        write_u8!(w, self.pressure.get())?;
        Ok(())
    }
}

/// Provides the ability to pitch bend a channel by specifying a pitch bend value between
/// 0 and 16383 where 8192 (the middle) is no pitch bend. Above 8192 bends the note up and
/// below bends the note down. The actual pitch change depends upon the device (e.g. synth)
/// but by default the range is +/- 2 semitones around the standard note pitch.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct PitchBendMessage {
    pub(crate) channel: Channel,
    pub(crate) pitch_bend: PitchBendValue,
}

impl PitchBendMessage {
    /// Create a new `PitchBendMessage`.
    pub fn new(channel: Channel, pitch_bend: PitchBendValue) -> Self {
        Self {
            channel,
            pitch_bend,
        }
    }

    /// Get the channel value.
    pub fn channel(&self) -> Channel {
        self.channel
    }

    /// Get the pitch bend value (0 - 16383).
    pub fn pitch_bend(&self) -> PitchBendValue {
        self.pitch_bend
    }
}

impl WriteBytes for PitchBendMessage {
    fn write<W: Write>(&self, w: &mut Scribe<W>) -> Result<()> {
        write_status_byte(w, StatusType::PitchBend, self.channel)?;
        let decoded = self.pitch_bend.get();
        let encoded = encode_14_bit_number(decoded);
        write_u8!(w, ((encoded >> 8) as u8))?;
        write_u8!(w, ((encoded & 0b0000000011111111) as u8))?;
        Ok(())
    }
}

/// Represents an on/off state for MIDI messages such as Local Control.
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[allow(dead_code)]
#[derive(Default)]
pub enum OnOff {
    /// The "on" state.
    On = 127,
    /// The "off" state.
    #[default]
    Off = 0,
}

/// A parameter found on most MIDI keyboards that have built-in sounds. Local Control can be set on
/// or off, and is normally found in the global parameters for a particular instrument. When enabled
/// the keyboard is electronically connected to the internal sounds of the instrument. This is the
/// “normal” or default mode for most instruments. When turned off the keyboard only transmits MIDI
/// to the MIDI out jack. The built-in sounds can then only be accessed from a MIDI input (or an
/// internal sequencer where applicable). When people use keyboards with external sequencing
/// equipment local control is normally turned off, and the sounds are just driven through the
/// sequencer. This prevents a phenomenon known as MIDI echo, where a sound is triggered directly by
/// the keyboard, and then a very short time later the same note is played again due to the data
/// being passed through the sequencer.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct LocalControlValue {
    channel: Channel,
    on_off: OnOff,
}

impl LocalControlValue {
    /// Create a new `LocalControlValue`.
    pub fn new(channel: Channel, on_off: OnOff) -> Self {
        Self { channel, on_off }
    }

    /// A getter for the `channel` field.
    pub fn channel(&self) -> Channel {
        self.channel
    }

    /// A getter for the `on_off` field.
    pub fn on_off(&self) -> OnOff {
        self.on_off
    }
}

/// When Mono mode is selected, a single voice is assigned per MIDI Channel. This means that only
/// one note can be played on a given Channel at a given time.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct MonoModeOnValue {
    channel: Channel,
    mono_mode_channels: MonoModeChannels,
}

impl MonoModeOnValue {
    /// Create a new `MonoModeOnValue`.
    pub fn new(channel: Channel, mono_mode_channels: MonoModeChannels) -> Self {
        Self {
            channel,
            mono_mode_channels,
        }
    }

    /// A getter for the `channel` field.
    pub fn channel(&self) -> Channel {
        self.channel
    }

    /// A getter for the `mono_mode_channels` field.
    pub fn mono_mode_channels(&self) -> MonoModeChannels {
        self.mono_mode_channels
    }
}

/// MIDI Time Code Quarter Frame, status `0xF1`. Carries one data byte holding a 3-bit message
/// type and a 4-bit value, packed as `0nnndddd`.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct MidiTimeCodeQuarterFrameMessage {
    pub(crate) value: QuarterFrameValue,
}

impl MidiTimeCodeQuarterFrameMessage {
    /// Create a new `MidiTimeCodeQuarterFrameMessage`.
    pub fn new(value: QuarterFrameValue) -> Self {
        Self { value }
    }

    /// Getter for the `value` field.
    pub fn value(&self) -> QuarterFrameValue {
        self.value
    }

    fn parse<R: Read>(iter: &mut ByteIter<R>) -> Result<Self> {
        Ok(Self {
            value: iter.read_or_die().context(io!())?.into(),
        })
    }

    fn write<W: Write>(&self, w: &mut Scribe<W>) -> Result<()> {
        write_u8!(w, STATUS_MTC_QUARTER_FRAME)?;
        write_u8!(w, self.value.get())?;
        Ok(())
    }
}

/// Song Position Pointer, status `0xF2`. A 14-bit register holding the number of MIDI beats
/// (1 beat = six MIDI clocks) since the start of the song, transmitted LSB first.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct SongPositionPointerMessage {
    pub(crate) position: SongPosition,
}

impl SongPositionPointerMessage {
    /// Create a new `SongPositionPointerMessage`.
    pub fn new(position: SongPosition) -> Self {
        Self { position }
    }

    /// Getter for the `position` field.
    pub fn position(&self) -> SongPosition {
        self.position
    }

    fn parse<R: Read>(iter: &mut ByteIter<R>) -> Result<Self> {
        let value = iter.read_u16().context(io!())?;
        Ok(Self {
            position: SongPosition::new(decode_14_bit_number(value)),
        })
    }

    fn write<W: Write>(&self, w: &mut Scribe<W>) -> Result<()> {
        write_u8!(w, STATUS_SONG_POSITION)?;
        let encoded = encode_14_bit_number(self.position.get());
        write_u8!(w, ((encoded >> 8) as u8))?;
        write_u8!(w, ((encoded & 0b0000000011111111) as u8))?;
        Ok(())
    }
}

/// Song Select, status `0xF3`. Specifies which sequence or song is to be played.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct SongSelectMessage {
    pub(crate) song: SongNumber,
}

impl SongSelectMessage {
    /// Create a new `SongSelectMessage`.
    pub fn new(song: SongNumber) -> Self {
        Self { song }
    }

    /// Getter for the `song` field.
    pub fn song(&self) -> SongNumber {
        self.song
    }

    fn parse<R: Read>(iter: &mut ByteIter<R>) -> Result<Self> {
        Ok(Self {
            song: iter.read_or_die().context(io!())?.into(),
        })
    }

    fn write<W: Write>(&self, w: &mut Scribe<W>) -> Result<()> {
        write_u8!(w, STATUS_SONG_SELECT)?;
        write_u8!(w, self.song.get())?;
        Ok(())
    }
}

/// A MIDI message is made up of an eight-bit status byte which is generally followed by one or two
/// data bytes. There are a number of different types of MIDI messages. At the highest level, MIDI
/// messages are classified as being either Channel Messages or System Messages. Channel messages
/// are those which apply to a specific Channel, and the Channel number is included in the status
/// byte for these messages. System messages are not Channel specific, and no Channel number is
/// indicated in their status bytes.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Message {
    /// `0x8`: sent when a note is released.
    NoteOff(NoteMessage),
    /// `0x9`: sent when a note is depressed. A velocity of 0 acts as a note off.
    NoteOn(NoteMessage),
    /// `0xA`: polyphonic key pressure (aftertouch) for an individual key.
    PolyPressure(NoteMessage),
    /// `0xB` with a controller number 0-119: a control change.
    Control(ControlChangeValue),
    /// `0xC`: changes the patch (instrument sound) on a channel.
    ProgramChange(ProgramChangeValue),
    /// `0xD`: channel pressure (aftertouch), the greatest pressure of all depressed keys.
    ChannelPressure(ChannelPressureMessage),
    /// `0xE`: a change in the pitch wheel, measured by a fourteen-bit value.
    PitchBend(PitchBendMessage),
    /// `0xB` controller 120: turns all sound on the channel off.
    AllSoundsOff(Channel),
    /// `0xB` controller 121: resets all controllers on the channel.
    ResetAllControllers(Channel),
    /// `0xB` controller 122, value 0: the keyboard responds only to received MIDI data.
    LocalControlOff(Channel),
    /// `0xB` controller 122, value 127: restores the normal keyboard-to-sound connection.
    LocalControlOn(Channel),
    /// `0xB` controller 123: turns all notes on the channel off.
    AllNotesOff(Channel),
    /// `0xB` controller 124: omni mode off (also causes all notes off).
    OmniModeOff(Channel),
    /// `0xB` controller 125: omni mode on (also causes all notes off).
    OmniModeOn(Channel),
    /// `0xB` controller 126: mono mode on, i.e. poly mode off (also causes all notes off).
    MonoModeOn(MonoModeOnValue),
    /// `0xB` controller 127: poly mode on, i.e. mono mode off (also causes all notes off).
    PolyModeOn(Channel),
    /// `0xF1`: a MIDI time code quarter frame.
    MidiTimeCodeQuarterFrame(MidiTimeCodeQuarterFrameMessage),
    /// `0xF2`: the number of MIDI beats since the start of the song.
    SongPositionPointer(SongPositionPointerMessage),
    /// `0xF3`: specifies which sequence or song is to be played.
    SongSelect(SongSelectMessage),
    /// `0xF6`: upon receiving this, all analog synthesizers should tune their oscillators.
    TuneRequest,
    /// `0xF8`: sent 24 times per quarter note when synchronization is required.
    TimingClock,
    /// `0xF9`: an undefined system realtime status byte.
    Undefined1,
    /// `0xFA`: start the current sequence playing.
    Start,
    /// `0xFB`: continue at the point the sequence was stopped.
    Continue,
    /// `0xFC`: stop the current sequence.
    Stop,
    /// `0xFD`: an undefined system realtime status byte.
    Undefined2,
    /// `0xFE`: sent every 300ms (max) when the connection should be presumed alive.
    ActiveSensing,
}

impl Default for Message {
    fn default() -> Self {
        Message::AllSoundsOff(Channel::default())
    }
}

impl Message {
    pub(crate) fn parse<R: Read>(iter: &mut ByteIter<R>) -> Result<Self> {
        // check if the first byte is a status byte. if not, then this should be a running status
        // message.
        let byte = if matches!(iter.peek_or_die().context(io!())?, 0x00..=0x7F) {
            iter.set_running_status_detected();
            iter.latest_message_byte()
                .context(ctx!(crate::error::ErrorType::RunningStatus))?
        } else {
            iter.read_or_die().context(io!())?
        };

        // system realtime messages: single-byte messages that do not affect running status.
        // 0xff cannot be reached here because it introduces a meta event in a MIDI file and is
        // dispatched by Event::parse.
        match byte {
            STATUS_TIMING_CLOCK => return Ok(Message::TimingClock),
            STATUS_UNDEFINED_1 => return Ok(Message::Undefined1),
            STATUS_START => return Ok(Message::Start),
            STATUS_CONTINUE => return Ok(Message::Continue),
            STATUS_STOP => return Ok(Message::Stop),
            STATUS_UNDEFINED_2 => return Ok(Message::Undefined2),
            STATUS_ACTIVE_SENSING => return Ok(Message::ActiveSensing),
            _ => {}
        }

        // system common messages cancel running status. 0xf0 and 0xf7 are sysex events dispatched
        // by Event::parse; 0xf4 and 0xf5 are undefined and their data lengths are unknown, so they
        // cannot be parsed past.
        match byte {
            STATUS_MTC_QUARTER_FRAME => {
                iter.set_latest_message_byte(None);
                return Ok(Message::MidiTimeCodeQuarterFrame(
                    MidiTimeCodeQuarterFrameMessage::parse(iter)?,
                ));
            }
            STATUS_SONG_POSITION => {
                iter.set_latest_message_byte(None);
                return Ok(Message::SongPositionPointer(
                    SongPositionPointerMessage::parse(iter)?,
                ));
            }
            STATUS_SONG_SELECT => {
                iter.set_latest_message_byte(None);
                return Ok(Message::SongSelect(SongSelectMessage::parse(iter)?));
            }
            STATUS_TUNE_REQUEST => {
                iter.set_latest_message_byte(None);
                return Ok(Message::TuneRequest);
            }
            0xf0 | 0xf4 | 0xf5 | 0xf7 => {
                invalid_file!("unexpected status byte {:#04X}", byte)
            }
            _ => {}
        }

        // a channel voice or channel mode message: participates in running status.
        iter.set_latest_message_byte(Some(byte));
        let (status_type, channel) = split_byte(byte)?;
        match status_type {
            StatusType::NoteOff => Ok(Message::NoteOff(NoteMessage::parse(iter, channel)?)),
            StatusType::NoteOn => Ok(Message::NoteOn(NoteMessage::parse(iter, channel)?)),
            StatusType::PolyPressure => {
                Ok(Message::PolyPressure(NoteMessage::parse(iter, channel)?))
            }
            StatusType::ControlOrSelectChannelMode => parse_0xb(iter, channel),
            StatusType::Program => {
                let program: Program = iter.read_or_die().context(io!())?.into();
                Ok(Message::ProgramChange(ProgramChangeValue {
                    channel,
                    program,
                }))
            }
            StatusType::ChannelPressure => Ok(Message::ChannelPressure(
                ChannelPressureMessage::parse(iter, channel)?,
            )),
            StatusType::PitchBend => {
                let value = iter.read_u16().context(io!())?;
                let decoded = decode_14_bit_number(value);
                Ok(Message::PitchBend(PitchBendMessage {
                    channel,
                    pitch_bend: PitchBendValue::new(decoded),
                }))
            }
            // every 0xF status byte was handled above
            StatusType::System => invalid_file!("unexpected status byte {:#04X}", byte),
        }
    }

    pub(crate) fn write<W: Write>(&self, w: &mut Scribe<W>) -> Result<()> {
        match self {
            Message::NoteOff(value) => value.write(w, StatusType::NoteOff),
            Message::NoteOn(value) => value.write(w, StatusType::NoteOn),
            Message::PolyPressure(value) => value.write(w, StatusType::PolyPressure),
            Message::Control(value) => value.write(w),
            Message::ProgramChange(value) => value.write(w),
            Message::ChannelPressure(value) => value.write(w),
            Message::PitchBend(value) => value.write(w),
            Message::AllSoundsOff(channel) => write_chanmod(w, *channel, CONTROL_ALL_SOUNDS_OFF, 0),
            Message::ResetAllControllers(channel) => {
                write_chanmod(w, *channel, CONTROL_RESET_ALL_CONTROLLERS, 0)
            }
            Message::LocalControlOff(channel) => {
                write_chanmod(w, *channel, CONTROL_LOCAL_CONTROL, 0)
            }
            Message::LocalControlOn(channel) => {
                write_chanmod(w, *channel, CONTROL_LOCAL_CONTROL, 127)
            }
            Message::AllNotesOff(channel) => write_chanmod(w, *channel, CONTROL_ALL_NOTES_OFF, 0),
            Message::OmniModeOff(channel) => write_chanmod(w, *channel, CONTROL_OMNI_MODE_OFF, 0),
            Message::OmniModeOn(channel) => write_chanmod(w, *channel, CONTROL_OMNI_MODE_ON, 0),
            Message::MonoModeOn(m) => write_chanmod(
                w,
                m.channel,
                CONTROL_MONO_MODE_ON,
                m.mono_mode_channels.get(),
            ),
            Message::PolyModeOn(channel) => write_chanmod(w, *channel, CONTROL_POLY_MODE_ON, 0),
            // system common messages cancel running status
            Message::MidiTimeCodeQuarterFrame(value) => {
                w.clear_running_status();
                value.write(w)
            }
            Message::SongPositionPointer(value) => {
                w.clear_running_status();
                value.write(w)
            }
            Message::SongSelect(value) => {
                w.clear_running_status();
                value.write(w)
            }
            Message::TuneRequest => {
                w.clear_running_status();
                write_u8!(w, STATUS_TUNE_REQUEST)
            }
            // system realtime messages are a single byte and do not affect running status
            Message::TimingClock => write_u8!(w, STATUS_TIMING_CLOCK),
            Message::Undefined1 => write_u8!(w, STATUS_UNDEFINED_1),
            Message::Start => write_u8!(w, STATUS_START),
            Message::Continue => write_u8!(w, STATUS_CONTINUE),
            Message::Stop => write_u8!(w, STATUS_STOP),
            Message::Undefined2 => write_u8!(w, STATUS_UNDEFINED_2),
            Message::ActiveSensing => write_u8!(w, STATUS_ACTIVE_SENSING),
        }
    }
}

// system common status bytes
pub(crate) const STATUS_MTC_QUARTER_FRAME: u8 = 0xf1;
pub(crate) const STATUS_SONG_POSITION: u8 = 0xf2;
pub(crate) const STATUS_SONG_SELECT: u8 = 0xf3;
pub(crate) const STATUS_TUNE_REQUEST: u8 = 0xf6;

// system realtime status bytes
pub(crate) const STATUS_TIMING_CLOCK: u8 = 0xf8;
pub(crate) const STATUS_UNDEFINED_1: u8 = 0xf9;
pub(crate) const STATUS_START: u8 = 0xfa;
pub(crate) const STATUS_CONTINUE: u8 = 0xfb;
pub(crate) const STATUS_STOP: u8 = 0xfc;
pub(crate) const STATUS_UNDEFINED_2: u8 = 0xfd;
pub(crate) const STATUS_ACTIVE_SENSING: u8 = 0xfe;

pub(crate) const CONTROL_ALL_SOUNDS_OFF: u8 = 120;
pub(crate) const CONTROL_RESET_ALL_CONTROLLERS: u8 = 121;
pub(crate) const CONTROL_LOCAL_CONTROL: u8 = 122;
pub(crate) const CONTROL_ALL_NOTES_OFF: u8 = 123;
pub(crate) const CONTROL_OMNI_MODE_OFF: u8 = 124;
pub(crate) const CONTROL_OMNI_MODE_ON: u8 = 125;
pub(crate) const CONTROL_MONO_MODE_ON: u8 = 126;
pub(crate) const CONTROL_POLY_MODE_ON: u8 = 127;

/// Returns (4-bit status part, 4-bit channel).
fn split_byte(status_byte: u8) -> Result<(StatusType, Channel)> {
    let status_type_val = status_byte >> 4;
    let status_type = StatusType::from_u8(status_type_val)?;
    let channel_value = status_byte & 0b0000_1111;
    let channel: Channel = channel_value.into();
    Ok((status_type, channel))
}

/// Combines the status part and channel part of a channel voice message.
fn merge_byte(status: StatusType, channel: Channel) -> u8 {
    let status_number = status as u8;
    let status_bits = status_number << 4;
    let channel_bits = channel.get();
    status_bits | channel_bits
}

/// Combines then writes the status part and channel part of a channel voice message.
fn write_status_byte<W: Write>(
    w: &mut Scribe<W>,
    status: StatusType,
    channel: Channel,
) -> Result<()> {
    let data = merge_byte(status, channel);
    w.write_status_byte(data)
}

fn parse_0xb<R: Read>(iter: &mut ByteIter<R>, channel: Channel) -> Result<Message> {
    let first_data_byte = iter.read_or_die().context(io!())?;
    match first_data_byte {
        0..=119 => parse_control(iter, channel, first_data_byte),
        120..=127 => parse_chanmod(iter, channel, first_data_byte),
        _ => invalid_file!("expected value between 0 and 127, got {}", first_data_byte),
    }
}

fn parse_chanmod<R>(it: &mut ByteIter<R>, chan: Channel, first_byte: u8) -> Result<Message>
where
    R: Read,
{
    let second_byte = it.read_or_die().context(io!())?;
    match first_byte {
        CONTROL_ALL_SOUNDS_OFF => Ok(Message::AllSoundsOff(chan)),
        CONTROL_RESET_ALL_CONTROLLERS => Ok(Message::ResetAllControllers(chan)),
        CONTROL_LOCAL_CONTROL => {
            // The spec says 127 for "on", but anything nonzero is treated as "on".
            if second_byte == 0 {
                Ok(Message::LocalControlOff(chan))
            } else {
                Ok(Message::LocalControlOn(chan))
            }
        }
        CONTROL_ALL_NOTES_OFF => Ok(Message::AllNotesOff(chan)),
        CONTROL_OMNI_MODE_OFF => Ok(Message::OmniModeOff(chan)),
        CONTROL_OMNI_MODE_ON => Ok(Message::OmniModeOn(chan)),
        CONTROL_MONO_MODE_ON => Ok(Message::MonoModeOn(MonoModeOnValue {
            channel: chan,
            mono_mode_channels: MonoModeChannels::new(second_byte),
        })),
        CONTROL_POLY_MODE_ON => Ok(Message::PolyModeOn(chan)),
        _ => invalid_file!("Bad channel mode value {:#04X}", first_byte),
    }
}

fn write_chanmod<W>(w: &mut Scribe<W>, channel: Channel, controller: u8, value: u8) -> Result<()>
where
    W: Write,
{
    debug_assert!(matches!(controller, 120..=127));
    debug_assert!(matches!(value, 0..=127));
    let status_byte = 0xB0u8 | channel.get();
    w.write_status_byte(status_byte)?;
    write_u8!(w, controller)?;
    write_u8!(w, value)?;
    Ok(())
}

fn parse_control<R>(it: &mut ByteIter<R>, chan: Channel, first_data_byte: u8) -> Result<Message>
where
    R: Read,
{
    let control = Control::try_from_u8(first_data_byte)?;
    let value: ControlValue = it.read_or_die().context(io!())?.into();
    Ok(Message::Control(ControlChangeValue {
        channel: chan,
        control,
        value,
    }))
}

/// Represents the control byte in a [`ControlChangeValue`]. Values greater than one byte require
/// sending two messages, one with the most-significant byte and one with the least-significant
/// byte. `Control` values greater than 31 are for the Lsb in these two-byte messages.
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
#[allow(missing_docs)]
pub enum Control {
    #[default]
    BankSelect = 0,
    ModWheel = 1,
    BreathController = 2,
    Undefined3 = 3,
    FootController = 4,
    PortamentoTime = 5,
    DataEntryMsb = 6,
    ChannelVolume = 7,
    Balance = 8,
    Undefined9 = 9,
    Pan = 10,
    ExpressionController = 11,
    EffectControl1 = 12,
    EffectControl2 = 13,
    Undefined14,
    Undefined15,
    GeneralPurpose1 = 16,
    GeneralPurpose2 = 17,
    GeneralPurpose3 = 18,
    GeneralPurpose4 = 19,
    Undefined20 = 20,
    Undefined21 = 21,
    Undefined22 = 22,
    Undefined23 = 23,
    Undefined24 = 24,
    Undefined25 = 25,
    Undefined26 = 26,
    Undefined27 = 27,
    Undefined28 = 28,
    Undefined29 = 29,
    Undefined30 = 30,
    Undefined31 = 31,

    // These represent the "LSB" for items 0-31. When a 0-31 message is larger than one byte,
    // two messages are sent, one with the MSB and one with the LSB.
    BankSelectLsb = 32,
    ModWheelLsb = 33,
    BreathControllerLsb = 34,
    Undefined3Lsb = 35,
    FootControllerLsb = 36,
    PortamentoTimeLsb = 37,
    DataEntryMsbLsb = 38,
    ChannelVolumeLsb = 39,
    BalanceLsb = 40,
    Undefined9Lsb = 41,
    PanLsb = 42,
    ExpressionControllerLsb = 43,
    EffectControl1Lsb = 44,
    EffectControl2Lsb = 45,
    Undefined14Lsb = 46,
    Undefined15Lsb = 47,
    GeneralPurpose1Lsb = 48,
    GeneralPurpose2Lsb = 49,
    GeneralPurpose3Lsb = 50,
    GeneralPurpose4Lsb = 51,
    Undefined20Lsb = 52,
    Undefined21Lsb = 53,
    Undefined22Lsb = 54,
    Undefined23Lsb = 55,
    Undefined24Lsb = 56,
    Undefined25Lsb = 57,
    Undefined26Lsb = 58,
    Undefined27Lsb = 59,
    Undefined28Lsb = 60,
    Undefined29Lsb = 61,
    Undefined30Lsb = 62,
    Undefined31Lsb = 63,

    DamperPedalSustain = 64,
    PortamentoOnOff = 65,
    Sostenuto = 66,
    SoftPedal = 67,
    LegatoFootswitch = 68,
    Hold2 = 69,
    SoundVariation = 70,
    HarmonicIntensity = 71,
    ReleaseTime = 72,
    AttackTime = 73,
    Brightness = 74,
    SoundControllers6 = 75,
    SoundControllers7 = 76,
    SoundControllers8 = 77,
    SoundControllers9 = 78,
    SoundControllers10 = 79,
    GeneralPurpose5 = 80,
    GeneralPurpose6 = 81,
    GeneralPurpose7 = 82,
    GeneralPurpose8 = 83,
    PortamentoControl = 84,
    Undefined85 = 85,
    Undefined86 = 86,
    Undefined87 = 87,
    Undefined88 = 88,
    Undefined89 = 89,
    Undefined90 = 90,
    Effects1Depth = 91,
    Effects2Depth = 92,
    Effects3Depth = 93,
    Effects4Depth = 94,
    Effects5Depth = 95,
    DataIncrement = 96,
    DataDecrement = 97,
    NonRegisteredParameterNumberLsb = 98,
    NonRegisteredParameterNumberMsb = 99,
    RegisteredParameterNumberLsb = 100,
    RegisteredParameterNumberMsb = 101,
    Undefined102 = 102,
    Undefined103 = 103,
    Undefined104 = 104,
    Undefined105 = 105,
    Undefined106 = 106,
    Undefined107 = 107,
    Undefined108 = 108,
    Undefined109 = 109,
    Undefined110 = 110,
    Undefined111 = 111,
    Undefined112 = 112,
    Undefined113 = 113,
    Undefined114 = 114,
    Undefined115 = 115,
    Undefined116 = 116,
    Undefined117 = 117,
    Undefined118 = 118,
    Undefined119 = 119,
}

impl Control {
    pub(crate) fn try_from_u8(value: u8) -> Result<Self> {
        match value {
            x if x == Control::BankSelect as u8 => Ok(Control::BankSelect),
            x if x == Control::ModWheel as u8 => Ok(Control::ModWheel),
            x if x == Control::BreathController as u8 => Ok(Control::BreathController),
            x if x == Control::Undefined3 as u8 => Ok(Control::Undefined3),
            x if x == Control::FootController as u8 => Ok(Control::FootController),
            x if x == Control::PortamentoTime as u8 => Ok(Control::PortamentoTime),
            x if x == Control::DataEntryMsb as u8 => Ok(Control::DataEntryMsb),
            x if x == Control::ChannelVolume as u8 => Ok(Control::ChannelVolume),
            x if x == Control::Balance as u8 => Ok(Control::Balance),
            x if x == Control::Undefined9 as u8 => Ok(Control::Undefined9),
            x if x == Control::Pan as u8 => Ok(Control::Pan),
            x if x == Control::ExpressionController as u8 => Ok(Control::ExpressionController),
            x if x == Control::EffectControl1 as u8 => Ok(Control::EffectControl1),
            x if x == Control::EffectControl2 as u8 => Ok(Control::EffectControl2),
            x if x == Control::Undefined14 as u8 => Ok(Control::Undefined14),
            x if x == Control::Undefined15 as u8 => Ok(Control::Undefined15),
            x if x == Control::GeneralPurpose1 as u8 => Ok(Control::GeneralPurpose1),
            x if x == Control::GeneralPurpose2 as u8 => Ok(Control::GeneralPurpose2),
            x if x == Control::GeneralPurpose3 as u8 => Ok(Control::GeneralPurpose3),
            x if x == Control::GeneralPurpose4 as u8 => Ok(Control::GeneralPurpose4),
            x if x == Control::Undefined20 as u8 => Ok(Control::Undefined20),
            x if x == Control::Undefined21 as u8 => Ok(Control::Undefined21),
            x if x == Control::Undefined22 as u8 => Ok(Control::Undefined22),
            x if x == Control::Undefined23 as u8 => Ok(Control::Undefined23),
            x if x == Control::Undefined24 as u8 => Ok(Control::Undefined24),
            x if x == Control::Undefined25 as u8 => Ok(Control::Undefined25),
            x if x == Control::Undefined26 as u8 => Ok(Control::Undefined26),
            x if x == Control::Undefined27 as u8 => Ok(Control::Undefined27),
            x if x == Control::Undefined28 as u8 => Ok(Control::Undefined28),
            x if x == Control::Undefined29 as u8 => Ok(Control::Undefined29),
            x if x == Control::Undefined30 as u8 => Ok(Control::Undefined30),
            x if x == Control::Undefined31 as u8 => Ok(Control::Undefined31),
            x if x == Control::BankSelectLsb as u8 => Ok(Control::BankSelectLsb),
            x if x == Control::ModWheelLsb as u8 => Ok(Control::ModWheelLsb),
            x if x == Control::BreathControllerLsb as u8 => Ok(Control::BreathControllerLsb),
            x if x == Control::Undefined3Lsb as u8 => Ok(Control::Undefined3Lsb),
            x if x == Control::FootControllerLsb as u8 => Ok(Control::FootControllerLsb),
            x if x == Control::PortamentoTimeLsb as u8 => Ok(Control::PortamentoTimeLsb),
            x if x == Control::DataEntryMsbLsb as u8 => Ok(Control::DataEntryMsbLsb),
            x if x == Control::ChannelVolumeLsb as u8 => Ok(Control::ChannelVolumeLsb),
            x if x == Control::BalanceLsb as u8 => Ok(Control::BalanceLsb),
            x if x == Control::Undefined9Lsb as u8 => Ok(Control::Undefined9Lsb),
            x if x == Control::PanLsb as u8 => Ok(Control::PanLsb),
            x if x == Control::ExpressionControllerLsb as u8 => {
                Ok(Control::ExpressionControllerLsb)
            }
            x if x == Control::EffectControl1Lsb as u8 => Ok(Control::EffectControl1Lsb),
            x if x == Control::EffectControl2Lsb as u8 => Ok(Control::EffectControl2Lsb),
            x if x == Control::Undefined14Lsb as u8 => Ok(Control::Undefined14Lsb),
            x if x == Control::Undefined15Lsb as u8 => Ok(Control::Undefined15Lsb),
            x if x == Control::GeneralPurpose1Lsb as u8 => Ok(Control::GeneralPurpose1Lsb),
            x if x == Control::GeneralPurpose2Lsb as u8 => Ok(Control::GeneralPurpose2Lsb),
            x if x == Control::GeneralPurpose3Lsb as u8 => Ok(Control::GeneralPurpose3Lsb),
            x if x == Control::GeneralPurpose4Lsb as u8 => Ok(Control::GeneralPurpose4Lsb),
            x if x == Control::Undefined20Lsb as u8 => Ok(Control::Undefined20Lsb),
            x if x == Control::Undefined21Lsb as u8 => Ok(Control::Undefined21Lsb),
            x if x == Control::Undefined22Lsb as u8 => Ok(Control::Undefined22Lsb),
            x if x == Control::Undefined23Lsb as u8 => Ok(Control::Undefined23Lsb),
            x if x == Control::Undefined24Lsb as u8 => Ok(Control::Undefined24Lsb),
            x if x == Control::Undefined25Lsb as u8 => Ok(Control::Undefined25Lsb),
            x if x == Control::Undefined26Lsb as u8 => Ok(Control::Undefined26Lsb),
            x if x == Control::Undefined27Lsb as u8 => Ok(Control::Undefined27Lsb),
            x if x == Control::Undefined28Lsb as u8 => Ok(Control::Undefined28Lsb),
            x if x == Control::Undefined29Lsb as u8 => Ok(Control::Undefined29Lsb),
            x if x == Control::Undefined30Lsb as u8 => Ok(Control::Undefined30Lsb),
            x if x == Control::Undefined31Lsb as u8 => Ok(Control::Undefined31Lsb),
            x if x == Control::DamperPedalSustain as u8 => Ok(Control::DamperPedalSustain),
            x if x == Control::PortamentoOnOff as u8 => Ok(Control::PortamentoOnOff),
            x if x == Control::Sostenuto as u8 => Ok(Control::Sostenuto),
            x if x == Control::SoftPedal as u8 => Ok(Control::SoftPedal),
            x if x == Control::LegatoFootswitch as u8 => Ok(Control::LegatoFootswitch),
            x if x == Control::Hold2 as u8 => Ok(Control::Hold2),
            x if x == Control::SoundVariation as u8 => Ok(Control::SoundVariation),
            x if x == Control::HarmonicIntensity as u8 => Ok(Control::HarmonicIntensity),
            x if x == Control::ReleaseTime as u8 => Ok(Control::ReleaseTime),
            x if x == Control::AttackTime as u8 => Ok(Control::AttackTime),
            x if x == Control::Brightness as u8 => Ok(Control::Brightness),
            x if x == Control::SoundControllers6 as u8 => Ok(Control::SoundControllers6),
            x if x == Control::SoundControllers7 as u8 => Ok(Control::SoundControllers7),
            x if x == Control::SoundControllers8 as u8 => Ok(Control::SoundControllers8),
            x if x == Control::SoundControllers9 as u8 => Ok(Control::SoundControllers9),
            x if x == Control::SoundControllers10 as u8 => Ok(Control::SoundControllers10),
            x if x == Control::GeneralPurpose5 as u8 => Ok(Control::GeneralPurpose5),
            x if x == Control::GeneralPurpose6 as u8 => Ok(Control::GeneralPurpose6),
            x if x == Control::GeneralPurpose7 as u8 => Ok(Control::GeneralPurpose7),
            x if x == Control::GeneralPurpose8 as u8 => Ok(Control::GeneralPurpose8),
            x if x == Control::PortamentoControl as u8 => Ok(Control::PortamentoControl),
            x if x == Control::Undefined85 as u8 => Ok(Control::Undefined85),
            x if x == Control::Undefined86 as u8 => Ok(Control::Undefined86),
            x if x == Control::Undefined87 as u8 => Ok(Control::Undefined87),
            x if x == Control::Undefined88 as u8 => Ok(Control::Undefined88),
            x if x == Control::Undefined89 as u8 => Ok(Control::Undefined89),
            x if x == Control::Undefined90 as u8 => Ok(Control::Undefined90),
            x if x == Control::Effects1Depth as u8 => Ok(Control::Effects1Depth),
            x if x == Control::Effects2Depth as u8 => Ok(Control::Effects2Depth),
            x if x == Control::Effects3Depth as u8 => Ok(Control::Effects3Depth),
            x if x == Control::Effects4Depth as u8 => Ok(Control::Effects4Depth),
            x if x == Control::Effects5Depth as u8 => Ok(Control::Effects5Depth),
            x if x == Control::DataIncrement as u8 => Ok(Control::DataIncrement),
            x if x == Control::DataDecrement as u8 => Ok(Control::DataDecrement),
            x if x == Control::NonRegisteredParameterNumberLsb as u8 => {
                Ok(Control::NonRegisteredParameterNumberLsb)
            }
            x if x == Control::NonRegisteredParameterNumberMsb as u8 => {
                Ok(Control::NonRegisteredParameterNumberMsb)
            }
            x if x == Control::RegisteredParameterNumberLsb as u8 => {
                Ok(Control::RegisteredParameterNumberLsb)
            }
            x if x == Control::RegisteredParameterNumberMsb as u8 => {
                Ok(Control::RegisteredParameterNumberMsb)
            }
            x if x == Control::Undefined102 as u8 => Ok(Control::Undefined102),
            x if x == Control::Undefined103 as u8 => Ok(Control::Undefined103),
            x if x == Control::Undefined104 as u8 => Ok(Control::Undefined104),
            x if x == Control::Undefined105 as u8 => Ok(Control::Undefined105),
            x if x == Control::Undefined106 as u8 => Ok(Control::Undefined106),
            x if x == Control::Undefined107 as u8 => Ok(Control::Undefined107),
            x if x == Control::Undefined108 as u8 => Ok(Control::Undefined108),
            x if x == Control::Undefined109 as u8 => Ok(Control::Undefined109),
            x if x == Control::Undefined110 as u8 => Ok(Control::Undefined110),
            x if x == Control::Undefined111 as u8 => Ok(Control::Undefined111),
            x if x == Control::Undefined112 as u8 => Ok(Control::Undefined112),
            x if x == Control::Undefined113 as u8 => Ok(Control::Undefined113),
            x if x == Control::Undefined114 as u8 => Ok(Control::Undefined114),
            x if x == Control::Undefined115 as u8 => Ok(Control::Undefined115),
            x if x == Control::Undefined116 as u8 => Ok(Control::Undefined116),
            x if x == Control::Undefined117 as u8 => Ok(Control::Undefined117),
            x if x == Control::Undefined118 as u8 => Ok(Control::Undefined118),
            x if x == Control::Undefined119 as u8 => Ok(Control::Undefined119),
            _ => ctx!(crate::error::ErrorType::Other)().fail(),
        }
    }
}

impl TryFrom<u8> for Control {
    type Error = crate::Error;

    fn try_from(value: u8) -> crate::Result<Self> {
        Self::try_from_u8(value)
    }
}

/// Represents a MIDI Control Change message, which includes a channel, a control number, and a
/// value.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ControlChangeValue {
    channel: Channel,
    control: Control,
    value: ControlValue,
}

impl ControlChangeValue {
    /// Create a new `ControlChangeValue`.
    pub fn new(channel: Channel, control: Control, value: ControlValue) -> Self {
        Self {
            channel,
            control,
            value,
        }
    }

    /// A getter for the `channel` field.
    pub fn channel(&self) -> Channel {
        self.channel
    }

    /// A getter for the `control` field.
    pub fn control(&self) -> Control {
        self.control
    }

    /// A getter for the `value` field.
    pub fn value(&self) -> ControlValue {
        self.value
    }
}

impl WriteBytes for ControlChangeValue {
    fn write<W: Write>(&self, w: &mut Scribe<W>) -> Result<()> {
        write_status_byte(w, StatusType::ControlOrSelectChannelMode, self.channel)?;
        write_u8!(w, self.control as u8)?;
        write_u8!(w, self.value.get())?;
        Ok(())
    }
}