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
use crate::{
    build_status_byte, extract_type_from_status_byte, Channel, ControllerNumber,
    FuzzyMessageSuperType, KeyNumber, ShortMessage, ShortMessageType, TimeCodeQuarterFrame, U14,
    U7,
};
use derive_more::Display;

/// An error which can occur when trying to create a [`ShortMessage`] from raw bytes.
///
/// [`ShortMessage`]: trait.ShortMessage.html
#[derive(Clone, Eq, PartialEq, Debug, Display)]
#[display(fmt = "invalid MIDI message bytes")]
pub struct FromBytesError(pub(crate) ());

impl core_error::Error for FromBytesError {}

/// Static methods for creating short MIDI messages.
///
/// This trait is supposed to be implemented for structs that represent a short MIDI message *and*
/// also support their creation. Only one method needs to be implemented, the rest is done by
/// default methods.
pub trait ShortMessageFactory: ShortMessage + Sized {
    /// Creates a MIDI message from the given bytes without checking the status byte. The tuple
    /// consists of the status byte, data byte 1 and data byte 2 in exactly this order.
    ///
    /// # Safety
    ///
    /// Callers must make sure that the given status byte is valid, otherwise an invalid MIDI
    /// message will be created.
    ///
    /// Implementations can therefore assume that the given status byte is valid. This method is
    /// usually called by [`from_bytes`], which checks the necessary preconditions.
    ///
    /// [`from_bytes`]: #method.from_bytes
    unsafe fn from_bytes_unchecked(bytes: (u8, U7, U7)) -> Self;

    /// Creates a MIDI message from the given bytes. The tuple consists of the status byte, data
    /// byte 1 and data byte 2 in exactly this order.
    ///
    /// # Errors
    ///
    /// If the given status byte is invalid, an error will be returned.
    ///
    /// # Design
    ///
    /// Although one could argue that calling such a function with illegal input values is a
    /// violation of its contract, this function returns a result rather than panicking. It's
    /// because - unlike the functions in [`test_util`] - this function is primarily intended
    /// to be used in real-world situations where the bytes come from somewhere else (e.g. from a
    /// DAW) and therefore acts a bit like a parse function where client code should be able to
    /// recover from wrong input.
    ///
    /// [`test_util`]: test_util/index.html
    fn from_bytes(bytes: (u8, U7, U7)) -> Result<Self, FromBytesError> {
        extract_type_from_status_byte(bytes.0).map_err(|_| FromBytesError(()))?;
        Ok(unsafe { Self::from_bytes_unchecked(bytes) })
    }

    /// Creates this message from a MIDI message of another type.
    fn from_other(msg: &impl ShortMessage) -> Self {
        msg.to_other()
    }

    /// Creates a Channel message.
    ///
    /// # Panics
    ///
    /// This function panics if the given type is not a channel message type.
    fn channel_message(r#type: ShortMessageType, channel: Channel, data_1: U7, data_2: U7) -> Self {
        assert_eq!(r#type.super_type(), FuzzyMessageSuperType::Channel);
        unsafe {
            Self::from_bytes_unchecked((build_status_byte(r#type.into(), channel), data_1, data_2))
        }
    }

    /// Creates a System Common message.
    ///
    /// # Panics
    ///
    /// This function panics if the given type is not a System Common message type.
    fn system_common_message(r#type: ShortMessageType, data_1: U7, data_2: U7) -> Self {
        assert_eq!(r#type.super_type(), FuzzyMessageSuperType::SystemCommon);
        unsafe { Self::from_bytes_unchecked((r#type.into(), data_1, data_2)) }
    }

    /// Creates a System Real Time message.
    ///
    /// # Panics
    ///
    /// This function panics if the given type is not a System Real Time message type.
    fn system_real_time_message(r#type: ShortMessageType) -> Self {
        assert_eq!(r#type.super_type(), FuzzyMessageSuperType::SystemRealTime);
        unsafe { Self::from_bytes_unchecked((r#type.into(), U7::MIN, U7::MIN)) }
    }

    /// Creates a Note On message.
    fn note_on(channel: Channel, key_number: KeyNumber, velocity: U7) -> Self {
        unsafe {
            Self::from_bytes_unchecked((
                build_status_byte(ShortMessageType::NoteOn.into(), channel),
                key_number.into(),
                velocity,
            ))
        }
    }

    /// Creates a Note Off message.
    fn note_off(channel: Channel, key_number: KeyNumber, velocity: U7) -> Self {
        unsafe {
            Self::from_bytes_unchecked((
                build_status_byte(ShortMessageType::NoteOff.into(), channel),
                key_number.into(),
                velocity,
            ))
        }
    }

    /// Creates a Control Change message.
    fn control_change(
        channel: Channel,
        controller_number: ControllerNumber,
        control_value: U7,
    ) -> Self {
        unsafe {
            Self::from_bytes_unchecked((
                build_status_byte(ShortMessageType::ControlChange.into(), channel),
                controller_number.into(),
                control_value,
            ))
        }
    }

    /// Creates a Program Change message.
    fn program_change(channel: Channel, program_number: U7) -> Self {
        unsafe {
            Self::from_bytes_unchecked((
                build_status_byte(ShortMessageType::ProgramChange.into(), channel),
                program_number,
                U7::MIN,
            ))
        }
    }

    /// Creates a Polyphonic Key Pressure message.
    fn polyphonic_key_pressure(
        channel: Channel,
        key_number: KeyNumber,
        pressure_amount: U7,
    ) -> Self {
        unsafe {
            Self::from_bytes_unchecked((
                build_status_byte(ShortMessageType::PolyphonicKeyPressure.into(), channel),
                key_number.into(),
                pressure_amount,
            ))
        }
    }

    /// Creates a Channel Pressure message.
    fn channel_pressure(channel: Channel, pressure_amount: U7) -> Self {
        unsafe {
            Self::from_bytes_unchecked((
                build_status_byte(ShortMessageType::ChannelPressure.into(), channel),
                pressure_amount,
                U7::MIN,
            ))
        }
    }

    /// Creates a Pitch Bend Change message.
    fn pitch_bend_change(channel: Channel, pitch_bend_value: U14) -> Self {
        unsafe {
            Self::from_bytes_unchecked((
                build_status_byte(ShortMessageType::PitchBendChange.into(), channel),
                U7((pitch_bend_value.get() & 0x7f) as u8),
                U7((pitch_bend_value.get() >> 7) as u8),
            ))
        }
    }

    /// Creates the start of a System Exclusive message.
    fn system_exclusive_start() -> Self {
        unsafe {
            Self::from_bytes_unchecked((
                ShortMessageType::SystemExclusiveStart.into(),
                U7::MIN,
                U7::MIN,
            ))
        }
    }

    /// Creates a MIDI Time Code Quarter Frame message.
    fn time_code_quarter_frame(frame: TimeCodeQuarterFrame) -> Self {
        unsafe {
            Self::from_bytes_unchecked((
                ShortMessageType::TimeCodeQuarterFrame.into(),
                frame.into(),
                U7::MIN,
            ))
        }
    }

    /// Creates a Song Position Pointer message.
    fn song_position_pointer(position: U14) -> Self {
        unsafe {
            Self::from_bytes_unchecked((
                ShortMessageType::SongPositionPointer.into(),
                U7((position.get() & 0x7f) as u8),
                U7((position.get() >> 7) as u8),
            ))
        }
    }

    /// Creates a Song Select message.
    fn song_select(song_number: U7) -> Self {
        unsafe {
            Self::from_bytes_unchecked((ShortMessageType::SongSelect.into(), song_number, U7::MIN))
        }
    }

    /// Creates a Tune Request message.
    fn tune_request() -> Self {
        unsafe {
            Self::from_bytes_unchecked((ShortMessageType::TuneRequest.into(), U7::MIN, U7::MIN))
        }
    }

    /// Creates the end of a System Exclusive message.
    fn system_exclusive_end() -> Self {
        unsafe {
            Self::from_bytes_unchecked((
                ShortMessageType::SystemExclusiveEnd.into(),
                U7::MIN,
                U7::MIN,
            ))
        }
    }

    /// Creates a Timing Clock message.
    fn timing_clock() -> Self {
        unsafe {
            Self::from_bytes_unchecked((ShortMessageType::TimingClock.into(), U7::MIN, U7::MIN))
        }
    }

    /// Creates a Start message.
    fn start() -> Self {
        unsafe { Self::from_bytes_unchecked((ShortMessageType::Start.into(), U7::MIN, U7::MIN)) }
    }

    /// Creates a Continue message.
    fn r#continue() -> Self {
        unsafe { Self::from_bytes_unchecked((ShortMessageType::Continue.into(), U7::MIN, U7::MIN)) }
    }

    /// Creates a Stop message.
    fn stop() -> Self {
        unsafe { Self::from_bytes_unchecked((ShortMessageType::Stop.into(), U7::MIN, U7::MIN)) }
    }

    /// Creates an Active Sensing message.
    fn active_sensing() -> Self {
        unsafe {
            Self::from_bytes_unchecked((ShortMessageType::ActiveSensing.into(), U7::MIN, U7::MIN))
        }
    }

    /// Creates a System Reset message.
    fn system_reset() -> Self {
        unsafe {
            Self::from_bytes_unchecked((ShortMessageType::SystemReset.into(), U7::MIN, U7::MIN))
        }
    }
}