| 1 |
use coremidi_sys::MIDIPacketList; |
| 2 |
use coremidi_sys::{MIDIPacket, MIDIPacketNext, MIDITimeStamp}; |
| 3 |
|
| 4 |
use std::fmt; |
| 5 |
use std::ops::{Deref, DerefMut}; |
| 6 |
use std::slice; |
| 7 |
|
| 8 |
pub type Timestamp = u64; |
| 9 |
|
| 10 |
const MAX_PACKET_DATA_LENGTH: usize = 0xffffusize; |
| 11 |
|
| 12 |
#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] |
| 13 |
pub mod alignment { |
| 14 |
pub type Marker = [u32; 0]; // ensures 4-byte alignment (on ARM) |
| 15 |
pub const NEEDS_ALIGNMENT: bool = true; |
| 16 |
} |
| 17 |
|
| 18 |
#[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))] |
| 19 |
pub mod alignment { |
| 20 |
pub type Marker = [u8; 0]; // unaligned |
| 21 |
pub const NEEDS_ALIGNMENT: bool = false; |
| 22 |
} |
| 23 |
|
| 24 |
/// A collection of simultaneous MIDI events. |
| 25 |
/// See [MIDIPacket](https://developer.apple.com/reference/coremidi/midipacket). |
| 26 |
/// |
| 27 |
#[repr(C)] |
| 28 |
pub struct Packet { |
| 29 |
// NOTE: At runtime this type must only be used behind immutable references |
| 30 |
// that point to valid instances of MIDIPacket (mutable references would allow mem::swap). |
| 31 |
// This type must NOT implement `Copy`! |
| 32 |
// On ARM, this must be 4-byte aligned. |
| 33 |
inner: PacketInner, |
| 34 |
_alignment_marker: alignment::Marker, |
| 35 |
} |
| 36 |
|
| 37 |
#[repr(packed)] |
| 38 |
struct PacketInner { |
| 39 |
timestamp: MIDITimeStamp, |
| 40 |
length: u16, |
| 41 |
data: [u8; 0], // zero-length, because we cannot make this type bigger without knowing how much data there actually is |
| 42 |
} |
| 43 |
|
| 44 |
impl Packet { |
| 45 |
/// Get the packet timestamp. |
| 46 |
/// |
| 47 |
pub fn timestamp(&self) -> Timestamp { |
| 48 |
self.inner.timestamp as Timestamp |
| 49 |
} |
| 50 |
|
| 51 |
/// Get the packet data. This method just gives raw MIDI bytes. You would need another |
| 52 |
/// library to decode them and work with higher level events. |
| 53 |
/// |
| 54 |
/// |
| 55 |
/// The following example: |
| 56 |
/// |
| 57 |
/// ``` |
| 58 |
/// let packet_list = &coremidi::PacketBuffer::new(0, &[0x90, 0x40, 0x7f]); |
| 59 |
/// for packet in packet_list.iter() { |
| 60 |
/// for byte in packet.data() { |
| 61 |
/// print!(" {:x}", byte); |
| 62 |
/// } |
| 63 |
/// } |
| 64 |
/// ``` |
| 65 |
/// |
| 66 |
/// will print: |
| 67 |
/// |
| 68 |
/// ```text |
| 69 |
/// 90 40 7f |
| 70 |
/// ``` |
| 71 |
pub fn data(&self) -> &[u8] { |
| 72 |
let data_ptr = self.inner.data.as_ptr(); |
| 73 |
let data_len = self.inner.length as usize; |
| 74 |
unsafe { slice::from_raw_parts(data_ptr, data_len) } |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
impl fmt::Debug for Packet { |
| 79 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 80 |
let result = write!( |
| 81 |
f, |
| 82 |
"Packet(ptr={:x}, ts={:016x}, data=[", |
| 83 |
self as *const _ as usize, |
| 84 |
self.timestamp() as u64 |
| 85 |
); |
| 86 |
let result = self |
| 87 |
.data() |
| 88 |
.iter() |
| 89 |
.enumerate() |
| 90 |
.fold(result, |prev_result, (i, b)| match prev_result { |
| 91 |
Err(err) => Err(err), |
| 92 |
Ok(()) => { |
| 93 |
let sep = if i > 0 { ", " } else { "" }; |
| 94 |
write!(f, "{}{:02x}", sep, b) |
| 95 |
} |
| 96 |
}); |
| 97 |
result.and_then(|_| write!(f, "])")) |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
impl fmt::Display for Packet { |
| 102 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 103 |
let result = write!(f, "{:016x}:", self.timestamp()); |
| 104 |
self.data() |
| 105 |
.iter() |
| 106 |
.fold(result, |prev_result, b| match prev_result { |
| 107 |
Err(err) => Err(err), |
| 108 |
Ok(()) => write!(f, " {:02x}", b), |
| 109 |
}) |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
/// A [list of MIDI events](https://developer.apple.com/reference/coremidi/midipacketlist) being received from, or being sent to, one endpoint. |
| 114 |
/// |
| 115 |
#[repr(C)] |
| 116 |
pub struct PacketList { |
| 117 |
// NOTE: This type must only exist in the form of immutable references |
| 118 |
// pointing to valid instances of MIDIPacketList. |
| 119 |
// This type must NOT implement `Copy`! |
| 120 |
inner: PacketListInner, |
| 121 |
_do_not_construct: alignment::Marker, |
| 122 |
} |
| 123 |
|
| 124 |
#[repr(packed)] |
| 125 |
struct PacketListInner { |
| 126 |
num_packets: u32, |
| 127 |
data: [MIDIPacket; 0], |
| 128 |
} |
| 129 |
|
| 130 |
impl PacketList { |
| 131 |
/// For internal usage only. |
| 132 |
/// Requires this instance to actually point to a valid MIDIPacketList |
| 133 |
pub(crate) unsafe fn as_ptr(&self) -> *mut MIDIPacketList { |
| 134 |
self as *const PacketList as *mut PacketList as *mut MIDIPacketList |
| 135 |
} |
| 136 |
} |
| 137 |
|
| 138 |
impl PacketList { |
| 139 |
/// Check if the packet list is empty. |
| 140 |
/// |
| 141 |
pub fn is_empty(&self) -> bool { |
| 142 |
self.len() == 0 |
| 143 |
} |
| 144 |
|
| 145 |
/// Get the number of packets in the list. |
| 146 |
/// |
| 147 |
pub fn len(&self) -> usize { |
| 148 |
self.inner.num_packets as usize |
| 149 |
} |
| 150 |
|
| 151 |
/// Get an iterator for the packets in the list. |
| 152 |
/// |
| 153 |
pub fn iter(&self) -> PacketListIterator { |
| 154 |
PacketListIterator { |
| 155 |
count: self.len(), |
| 156 |
packet_ptr: std::ptr::addr_of!(self.inner.data) as *const MIDIPacket, |
| 157 |
_phantom: ::std::marker::PhantomData::default(), |
| 158 |
} |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
impl fmt::Debug for PacketList { |
| 163 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 164 |
let result = write!(f, "PacketList(ptr={:x}, packets=[", unsafe { |
| 165 |
self.as_ptr() as usize |
| 166 |
}); |
| 167 |
self.iter() |
| 168 |
.enumerate() |
| 169 |
.fold(result, |prev_result, (i, packet)| match prev_result { |
| 170 |
Err(err) => Err(err), |
| 171 |
Ok(()) => { |
| 172 |
let sep = if i != 0 { ", " } else { "" }; |
| 173 |
write!(f, "{}{:?}", sep, packet) |
| 174 |
} |
| 175 |
}) |
| 176 |
.and_then(|_| write!(f, "])")) |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
impl fmt::Display for PacketList { |
| 181 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 182 |
let num_packets = self.inner.num_packets; |
| 183 |
let result = write!(f, "PacketList(len={})", num_packets); |
| 184 |
self.iter() |
| 185 |
.fold(result, |prev_result, packet| match prev_result { |
| 186 |
Err(err) => Err(err), |
| 187 |
Ok(()) => write!(f, "\n {}", packet), |
| 188 |
}) |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
pub struct PacketListIterator<'a> { |
| 193 |
count: usize, |
| 194 |
packet_ptr: *const MIDIPacket, |
| 195 |
_phantom: ::std::marker::PhantomData<&'a Packet>, |
| 196 |
} |
| 197 |
|
| 198 |
impl<'a> Iterator for PacketListIterator<'a> { |
| 199 |
type Item = &'a Packet; |
| 200 |
|
| 201 |
fn next(&mut self) -> Option<&'a Packet> { |
| 202 |
if self.count > 0 { |
| 203 |
let packet = unsafe { &*(self.packet_ptr as *const Packet) }; |
| 204 |
self.count -= 1; |
| 205 |
self.packet_ptr = unsafe { MIDIPacketNext(self.packet_ptr) }; |
| 206 |
Some(packet) |
| 207 |
} else { |
| 208 |
None |
| 209 |
} |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
const PACKET_LIST_HEADER_SIZE: usize = 4; // MIDIPacketList::numPackets: UInt32 |
| 214 |
const PACKET_HEADER_SIZE: usize = 8 + // MIDIPacket::timeStamp: MIDITimeStamp/UInt64 |
| 215 |
2; // MIDIPacket::length: UInt16 |
| 216 |
|
| 217 |
const INLINE_PACKET_BUFFER_SIZE: usize = 28; // must be divisible by 4 |
| 218 |
|
| 219 |
enum PacketBufferStorage { |
| 220 |
/// Inline stores the data directy on the stack, if it is small enough. |
| 221 |
/// NOTE: using u32 ensures correct alignment (required on ARM) |
| 222 |
Inline([u32; INLINE_PACKET_BUFFER_SIZE / 4]), |
| 223 |
/// External is used whenever the size of the data exceeds INLINE_PACKET_BUFFER_SIZE. |
| 224 |
/// This means that the size of the contained vector is always greater than INLINE_PACKET_BUFFER_SIZE. |
| 225 |
External(Vec<u32>), |
| 226 |
} |
| 227 |
|
| 228 |
impl PacketBufferStorage { |
| 229 |
#[inline] |
| 230 |
pub fn with_capacity(capacity: usize) -> PacketBufferStorage { |
| 231 |
if capacity <= INLINE_PACKET_BUFFER_SIZE { |
| 232 |
PacketBufferStorage::Inline([0; INLINE_PACKET_BUFFER_SIZE / 4]) |
| 233 |
} else { |
| 234 |
let u32_len = ((capacity - 1) / 4) + 1; |
| 235 |
let mut buffer = Vec::with_capacity(u32_len); |
| 236 |
unsafe { |
| 237 |
buffer.set_len(u32_len); |
| 238 |
} |
| 239 |
PacketBufferStorage::External(buffer) |
| 240 |
} |
| 241 |
} |
| 242 |
|
| 243 |
#[inline] |
| 244 |
fn capacity(&self) -> usize { |
| 245 |
match *self { |
| 246 |
PacketBufferStorage::Inline(ref inline) => inline.len() * 4, |
| 247 |
PacketBufferStorage::External(ref vec) => vec.len() * 4, |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
#[inline] |
| 252 |
fn get_slice(&self) -> &[u8] { |
| 253 |
unsafe { |
| 254 |
match *self { |
| 255 |
PacketBufferStorage::Inline(ref inline) => { |
| 256 |
slice::from_raw_parts(inline.as_ptr() as *const u8, inline.len() * 4) |
| 257 |
} |
| 258 |
PacketBufferStorage::External(ref vec) => { |
| 259 |
slice::from_raw_parts(vec.as_ptr() as *const u8, vec.len() * 4) |
| 260 |
} |
| 261 |
} |
| 262 |
} |
| 263 |
} |
| 264 |
|
| 265 |
#[inline] |
| 266 |
fn get_slice_mut(&mut self) -> &mut [u8] { |
| 267 |
unsafe { |
| 268 |
match *self { |
| 269 |
PacketBufferStorage::Inline(ref mut inline) => { |
| 270 |
slice::from_raw_parts_mut(inline.as_mut_ptr() as *mut u8, inline.len() * 4) |
| 271 |
} |
| 272 |
PacketBufferStorage::External(ref mut vec) => { |
| 273 |
slice::from_raw_parts_mut(vec.as_mut_ptr() as *mut u8, vec.len() * 4) |
| 274 |
} |
| 275 |
} |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
unsafe fn assign_packet(&mut self, packet_offset: usize, time: MIDITimeStamp, data: &[u8]) { |
| 280 |
assert!(data.len() <= MAX_PACKET_DATA_LENGTH, "packet data too long"); // cannot store longer size in u16 |
| 281 |
|
| 282 |
if alignment::NEEDS_ALIGNMENT { |
| 283 |
debug_assert!(packet_offset & 0b11 == 0); |
| 284 |
} |
| 285 |
|
| 286 |
let slice = self.get_slice_mut(); |
| 287 |
let ptr = slice[packet_offset..].as_mut_ptr() as *mut Packet; |
| 288 |
(*ptr).inner.timestamp = time; |
| 289 |
(*ptr).inner.length = data.len() as u16; |
| 290 |
let packet_data_start = packet_offset + PACKET_HEADER_SIZE; |
| 291 |
slice[packet_data_start..(packet_data_start + data.len())].copy_from_slice(data); |
| 292 |
} |
| 293 |
|
| 294 |
/// Requires that there is a valid Packet at `offset`, which has enough space for `data` |
| 295 |
unsafe fn extend_packet(&mut self, packet_offset: usize, data: &[u8]) { |
| 296 |
let slice = self.get_slice_mut(); |
| 297 |
let ptr = slice[packet_offset..].as_mut_ptr() as *mut Packet; |
| 298 |
let packet_data_start = packet_offset + PACKET_HEADER_SIZE + (*ptr).inner.length as usize; |
| 299 |
(*ptr).inner.length += data.len() as u16; |
| 300 |
slice[packet_data_start..(packet_data_start + data.len())].copy_from_slice(data); |
| 301 |
} |
| 302 |
|
| 303 |
/// Call this only with larger length values (won't make the buffer smaller) |
| 304 |
unsafe fn ensure_capacity(&mut self, capacity: usize) { |
| 305 |
if capacity < INLINE_PACKET_BUFFER_SIZE || capacity < self.get_slice().len() { |
| 306 |
return; |
| 307 |
} |
| 308 |
|
| 309 |
let vec_capacity = ((capacity - 1) / 4) + 1; |
| 310 |
let vec: Option<Vec<u32>> = match *self { |
| 311 |
PacketBufferStorage::Inline(ref inline) => { |
| 312 |
let mut v = Vec::with_capacity(vec_capacity); |
| 313 |
v.extend_from_slice(inline); |
| 314 |
v.set_len(vec_capacity); |
| 315 |
Some(v) |
| 316 |
} |
| 317 |
PacketBufferStorage::External(ref mut vec) => { |
| 318 |
let current_len = vec.len(); |
| 319 |
vec.reserve(vec_capacity - current_len); |
| 320 |
vec.set_len(vec_capacity); |
| 321 |
None |
| 322 |
} |
| 323 |
}; |
| 324 |
|
| 325 |
// to prevent borrowcheck errors, this must come after the `match` |
| 326 |
if let Some(v) = vec { |
| 327 |
*self = PacketBufferStorage::External(v); |
| 328 |
} |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
impl Deref for PacketBufferStorage { |
| 333 |
type Target = PacketList; |
| 334 |
|
| 335 |
#[inline] |
| 336 |
fn deref(&self) -> &PacketList { |
| 337 |
unsafe { &*(self.get_slice().as_ptr() as *const PacketList) } |
| 338 |
} |
| 339 |
} |
| 340 |
|
| 341 |
impl DerefMut for PacketBufferStorage { |
| 342 |
// NOTE: Mutable references `&mut PacketList` must not be exposed in the public API! |
| 343 |
// The user could use mem::swap to modify the header without modifying the packets that follow. |
| 344 |
#[inline] |
| 345 |
fn deref_mut(&mut self) -> &mut PacketList { |
| 346 |
unsafe { &mut *(self.get_slice_mut().as_mut_ptr() as *mut PacketList) } |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
/// A mutable `PacketList` builder. |
| 351 |
/// |
| 352 |
/// A `PacketList` is an inmmutable reference to a [MIDIPacketList](https://developer.apple.com/reference/coremidi/midipacketlist) structure, |
| 353 |
/// while a `PacketBuffer` is a mutable structure that allows to build a `PacketList` by adding packets. |
| 354 |
/// It dereferences to a `PacketList`, so it can be used whenever a `PacketList` is needed. |
| 355 |
/// |
| 356 |
pub struct PacketBuffer { |
| 357 |
storage: PacketBufferStorage, |
| 358 |
last_packet_offset: usize, |
| 359 |
} |
| 360 |
|
| 361 |
impl Deref for PacketBuffer { |
| 362 |
type Target = PacketList; |
| 363 |
|
| 364 |
#[inline] |
| 365 |
fn deref(&self) -> &PacketList { |
| 366 |
self.storage.deref() |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
impl PacketBuffer { |
| 371 |
/// Create a `PacketBuffer` with a single packet containing the provided timestamp and data. |
| 372 |
/// |
| 373 |
/// According to the official documentation for CoreMIDI, the timestamp represents |
| 374 |
/// the time at which the events are to be played, where zero means "now". |
| 375 |
/// The timestamp applies to the first MIDI byte in the packet. |
| 376 |
/// |
| 377 |
/// Example on how to create a `PacketBuffer` with a single packet for a MIDI note on for C-5: |
| 378 |
/// |
| 379 |
/// ``` |
| 380 |
/// let buffer = coremidi::PacketBuffer::new(0, &[0x90, 0x3c, 0x7f]); |
| 381 |
/// assert_eq!(buffer.len(), 1) |
| 382 |
/// ``` |
| 383 |
pub fn new(time: MIDITimeStamp, data: &[u8]) -> PacketBuffer { |
| 384 |
let capacity = data.len() + PACKET_LIST_HEADER_SIZE + PACKET_HEADER_SIZE; |
| 385 |
let mut storage = PacketBufferStorage::with_capacity(capacity); |
| 386 |
storage.deref_mut().inner.num_packets = 1; |
| 387 |
let last_packet_offset = PACKET_LIST_HEADER_SIZE; |
| 388 |
unsafe { |
| 389 |
storage.assign_packet(last_packet_offset, time, data); |
| 390 |
} |
| 391 |
|
| 392 |
PacketBuffer { |
| 393 |
storage, |
| 394 |
last_packet_offset, |
| 395 |
} |
| 396 |
} |
| 397 |
|
| 398 |
/// Create an empty `PacketBuffer` with no packets. |
| 399 |
/// |
| 400 |
/// Example on how to create an empty `PacketBuffer` |
| 401 |
/// with a capacity for 128 bytes in total (including headers): |
| 402 |
/// |
| 403 |
/// ``` |
| 404 |
/// let buffer = coremidi::PacketBuffer::with_capacity(128); |
| 405 |
/// assert_eq!(buffer.len(), 0); |
| 406 |
/// assert_eq!(buffer.capacity(), 128); |
| 407 |
/// ``` |
| 408 |
pub fn with_capacity(capacity: usize) -> PacketBuffer { |
| 409 |
let capacity = std::cmp::max(capacity, INLINE_PACKET_BUFFER_SIZE); |
| 410 |
let mut storage = PacketBufferStorage::with_capacity(capacity); |
| 411 |
storage.deref_mut().inner.num_packets = 0; |
| 412 |
|
| 413 |
PacketBuffer { |
| 414 |
storage, |
| 415 |
last_packet_offset: PACKET_LIST_HEADER_SIZE, |
| 416 |
} |
| 417 |
} |
| 418 |
|
| 419 |
/// Get underlying buffer capacity in bytes |
| 420 |
pub fn capacity(&self) -> usize { |
| 421 |
self.storage.capacity() |
| 422 |
} |
| 423 |
|
| 424 |
/// Add a new event containing the provided timestamp and data. |
| 425 |
/// |
| 426 |
/// According to the official documentation for CoreMIDI, the timestamp represents |
| 427 |
/// the time at which the events are to be played, where zero means "now". |
| 428 |
/// The timestamp applies to the first MIDI byte in the packet. |
| 429 |
/// |
| 430 |
/// An event must not have a timestamp that is smaller than that of a previous event |
| 431 |
/// in the same `PacketList` |
| 432 |
/// |
| 433 |
/// Example: |
| 434 |
/// |
| 435 |
/// ``` |
| 436 |
/// let mut chord = coremidi::PacketBuffer::new(0, &[0x90, 0x3c, 0x7f]); |
| 437 |
/// chord.push_data(0, &[0x90, 0x40, 0x7f]); |
| 438 |
/// assert_eq!(chord.len(), 1); |
| 439 |
/// let repr = format!("{}", &chord as &coremidi::PacketList); |
| 440 |
/// assert_eq!(repr, "PacketList(len=1)\n 0000000000000000: 90 3c 7f 90 40 7f"); |
| 441 |
/// ``` |
| 442 |
pub fn push_data(&mut self, time: MIDITimeStamp, data: &[u8]) -> &mut Self { |
| 443 |
let (can_merge, previous_data_len) = self.can_merge_into_last_packet(time, data); |
| 444 |
|
| 445 |
if can_merge { |
| 446 |
let new_packet_size = Self::packet_size(previous_data_len + data.len()); |
| 447 |
unsafe { |
| 448 |
self.storage |
| 449 |
.ensure_capacity(self.last_packet_offset + new_packet_size); |
| 450 |
self.storage.extend_packet(self.last_packet_offset, data); |
| 451 |
} |
| 452 |
} else { |
| 453 |
let packet_size = Self::packet_size(data.len()); |
| 454 |
let next_offset = self.next_packet_offset(); |
| 455 |
unsafe { |
| 456 |
self.storage.ensure_capacity(next_offset + packet_size); |
| 457 |
self.storage.assign_packet(next_offset, time, data); |
| 458 |
} |
| 459 |
self.packet_list_mut().num_packets += 1; |
| 460 |
self.last_packet_offset = next_offset; |
| 461 |
} |
| 462 |
|
| 463 |
self |
| 464 |
} |
| 465 |
|
| 466 |
/// Clears the buffer, removing all packets. |
| 467 |
/// Note that this method has no effect on the allocated capacity of the buffer. |
| 468 |
pub fn clear(&mut self) { |
| 469 |
self.packet_list_mut().num_packets = 0; |
| 470 |
self.last_packet_offset = PACKET_LIST_HEADER_SIZE; |
| 471 |
} |
| 472 |
|
| 473 |
/// Checks whether the given tiemstamped data can be merged into the previous packet |
| 474 |
fn can_merge_into_last_packet(&self, time: MIDITimeStamp, data: &[u8]) -> (bool, usize) { |
| 475 |
if self.packet_list_is_empty() { |
| 476 |
(false, 0) |
| 477 |
} else { |
| 478 |
let previous_packet = self.last_packet(); |
| 479 |
let previous_packet_data = previous_packet.data(); |
| 480 |
let previous_data_len = previous_packet_data.len(); |
| 481 |
let can_merge = previous_packet.timestamp() == time |
| 482 |
&& Self::not_sysex(data) |
| 483 |
&& Self::has_status_byte(data) |
| 484 |
&& Self::not_sysex(previous_packet_data) |
| 485 |
&& Self::has_status_byte(previous_packet_data) |
| 486 |
&& previous_data_len + data.len() < MAX_PACKET_DATA_LENGTH; |
| 487 |
|
| 488 |
(can_merge, previous_data_len) |
| 489 |
} |
| 490 |
} |
| 491 |
|
| 492 |
#[inline] |
| 493 |
fn last_packet(&self) -> &Packet { |
| 494 |
assert!(self.packet_list().num_packets > 0); |
| 495 |
let packets_slice = self.storage.get_slice(); |
| 496 |
let packet_slot = &packets_slice[self.last_packet_offset..]; |
| 497 |
unsafe { &*(packet_slot.as_ptr() as *const Packet) } |
| 498 |
} |
| 499 |
|
| 500 |
#[inline] |
| 501 |
fn next_packet_offset(&self) -> usize { |
| 502 |
if self.packet_list_is_empty() { |
| 503 |
self.last_packet_offset |
| 504 |
} else { |
| 505 |
let data_len = self.last_packet().inner.length as usize; |
| 506 |
let next_offset = self.last_packet_offset + Self::packet_size(data_len); |
| 507 |
if alignment::NEEDS_ALIGNMENT { |
| 508 |
(next_offset + 3) & !(3usize) |
| 509 |
} else { |
| 510 |
next_offset |
| 511 |
} |
| 512 |
} |
| 513 |
} |
| 514 |
|
| 515 |
#[inline] |
| 516 |
fn not_sysex(data: &[u8]) -> bool { |
| 517 |
data[0] != 0xF0 |
| 518 |
} |
| 519 |
|
| 520 |
#[inline] |
| 521 |
fn has_status_byte(data: &[u8]) -> bool { |
| 522 |
data[0] & 0b10000000 != 0 |
| 523 |
} |
| 524 |
|
| 525 |
#[inline] |
| 526 |
fn packet_size(data_len: usize) -> usize { |
| 527 |
PACKET_HEADER_SIZE + data_len |
| 528 |
} |
| 529 |
|
| 530 |
#[inline] |
| 531 |
fn packet_list(&self) -> &PacketListInner { |
| 532 |
&self.storage.deref().inner |
| 533 |
} |
| 534 |
|
| 535 |
#[inline] |
| 536 |
fn packet_list_is_empty(&self) -> bool { |
| 537 |
self.packet_list().num_packets == 0 |
| 538 |
} |
| 539 |
|
| 540 |
#[inline] |
| 541 |
fn packet_list_mut(&mut self) -> &mut PacketListInner { |
| 542 |
&mut self.storage.deref_mut().inner |
| 543 |
} |
| 544 |
} |
| 545 |
|
| 546 |
#[cfg(test)] |
| 547 |
mod tests { |
| 548 |
use super::*; |
| 549 |
use coremidi_sys::{MIDIPacketList, MIDITimeStamp}; |
| 550 |
use std::mem; |
| 551 |
|
| 552 |
#[test] |
| 553 |
pub fn packet_struct_layout() { |
| 554 |
let expected_align = if super::alignment::NEEDS_ALIGNMENT { |
| 555 |
4 |
| 556 |
} else { |
| 557 |
1 |
| 558 |
}; |
| 559 |
assert_eq!(expected_align, mem::align_of::<Packet>()); |
| 560 |
assert_eq!(expected_align, mem::align_of::<PacketList>()); |
| 561 |
|
| 562 |
let dummy_packet: Packet = unsafe { mem::zeroed() }; |
| 563 |
let ptr = &dummy_packet as *const _ as *const u8; |
| 564 |
assert_eq!( |
| 565 |
PACKET_HEADER_SIZE, |
| 566 |
dummy_packet.inner.data.as_ptr() as usize - ptr as usize |
| 567 |
); |
| 568 |
|
| 569 |
let dummy_packet_list: PacketList = unsafe { mem::zeroed() }; |
| 570 |
let ptr = &dummy_packet_list as *const _ as *const u8; |
| 571 |
assert_eq!( |
| 572 |
PACKET_LIST_HEADER_SIZE, |
| 573 |
std::ptr::addr_of!(dummy_packet_list.inner.data) as usize - ptr as usize |
| 574 |
); |
| 575 |
} |
| 576 |
|
| 577 |
#[test] |
| 578 |
pub fn single_packet_alloc_inline() { |
| 579 |
let packet_buf = PacketBuffer::new(42, &[0x90u8, 0x40, 0x7f]); |
| 580 |
if let PacketBufferStorage::External(_) = packet_buf.storage { |
| 581 |
panic!("A single 3-byte message must not be allocated externally") |
| 582 |
} |
| 583 |
} |
| 584 |
|
| 585 |
#[test] |
| 586 |
fn packet_buffer_deref() { |
| 587 |
let packet_buf = PacketBuffer::new(42, &[0x90u8, 0x40, 0x7f]); |
| 588 |
let packet_list: &PacketList = &packet_buf; |
| 589 |
assert_eq!( |
| 590 |
unsafe { packet_list.as_ptr() as *const MIDIPacketList }, |
| 591 |
packet_buf.storage.get_slice().as_ptr() as *const _ as *const MIDIPacketList |
| 592 |
); |
| 593 |
} |
| 594 |
|
| 595 |
#[test] |
| 596 |
fn packet_list_length() { |
| 597 |
let mut packet_buf = PacketBuffer::new(42, &[0x90u8, 0x40, 0x7f]); |
| 598 |
packet_buf.push_data(43, &[0x91u8, 0x40, 0x7f]); |
| 599 |
packet_buf.push_data(44, &[0x80u8, 0x40, 0x7f]); |
| 600 |
packet_buf.push_data(45, &[0x81u8, 0x40, 0x7f]); |
| 601 |
assert_eq!(packet_buf.len(), 4); |
| 602 |
} |
| 603 |
|
| 604 |
#[test] |
| 605 |
fn packet_buffer_empty_with_capacity() { |
| 606 |
let packet_buf = PacketBuffer::with_capacity(128); |
| 607 |
assert_eq!(packet_buf.capacity(), 128); |
| 608 |
assert_eq!(packet_buf.len(), 0); |
| 609 |
} |
| 610 |
|
| 611 |
#[test] |
| 612 |
fn packet_buffer_with_capacity_zero() { |
| 613 |
let packet_buf = PacketBuffer::with_capacity(0); |
| 614 |
assert_eq!(packet_buf.capacity(), INLINE_PACKET_BUFFER_SIZE); |
| 615 |
assert_eq!(packet_buf.len(), 0); |
| 616 |
} |
| 617 |
|
| 618 |
#[test] |
| 619 |
fn packet_buffer_with_capacity() { |
| 620 |
let mut packet_buf = PacketBuffer::with_capacity(128); |
| 621 |
packet_buf.push_data(43, &[0x91u8, 0x40, 0x7f]); |
| 622 |
packet_buf.push_data(44, &[0x80u8, 0x40, 0x7f]); |
| 623 |
packet_buf.push_data(45, &[0x81u8, 0x40, 0x7f]); |
| 624 |
assert_eq!(packet_buf.capacity(), 128); |
| 625 |
assert_eq!(packet_buf.len(), 3); |
| 626 |
} |
| 627 |
|
| 628 |
#[test] |
| 629 |
fn packet_buffer_clear() { |
| 630 |
let mut packet_buf = PacketBuffer::new(42, &[0x90u8, 0x40, 0x7f]); |
| 631 |
packet_buf.push_data(43, &[0x91u8, 0x40, 0x7f]); |
| 632 |
packet_buf.push_data(44, &[0x80u8, 0x40, 0x7f]); |
| 633 |
packet_buf.push_data(45, &[0x81u8, 0x40, 0x7f]); |
| 634 |
assert_eq!(packet_buf.len(), 4); |
| 635 |
packet_buf.clear(); |
| 636 |
assert_eq!(packet_buf.len(), 0); |
| 637 |
} |
| 638 |
|
| 639 |
#[test] |
| 640 |
fn compare_equal_timestamps() { |
| 641 |
// these messages should be merged into a single packet |
| 642 |
unsafe { |
| 643 |
compare_packet_list(vec![ |
| 644 |
(42, vec![0x90, 0x40, 0x7f]), |
| 645 |
(42, vec![0x90, 0x41, 0x7f]), |
| 646 |
(42, vec![0x90, 0x42, 0x7f]), |
| 647 |
]) |
| 648 |
} |
| 649 |
} |
| 650 |
|
| 651 |
#[test] |
| 652 |
fn compare_unequal_timestamps() { |
| 653 |
unsafe { |
| 654 |
compare_packet_list(vec![ |
| 655 |
(42, vec![0x90, 0x40, 0x7f]), |
| 656 |
(43, vec![0x90, 0x40, 0x7f]), |
| 657 |
(44, vec![0x90, 0x40, 0x7f]), |
| 658 |
]) |
| 659 |
} |
| 660 |
} |
| 661 |
|
| 662 |
#[test] |
| 663 |
fn compare_sysex() { |
| 664 |
// the sysex must not be merged with the surrounding packets |
| 665 |
unsafe { |
| 666 |
compare_packet_list(vec![ |
| 667 |
(42, vec![0x90, 0x40, 0x7f]), |
| 668 |
(42, vec![0xF0, 0x01, 0x01, 0x01, 0x01, 0x01, 0xF7]), // sysex |
| 669 |
(42, vec![0x90, 0x41, 0x7f]), |
| 670 |
]) |
| 671 |
} |
| 672 |
} |
| 673 |
|
| 674 |
#[test] |
| 675 |
fn compare_sysex_split() { |
| 676 |
// the sysex must not be merged with the surrounding packets |
| 677 |
unsafe { |
| 678 |
compare_packet_list(vec![ |
| 679 |
(42, vec![0x90, 0x40, 0x7f]), |
| 680 |
(42, vec![0xF0, 0x01, 0x01, 0x01, 0x01]), // sysex part 1 |
| 681 |
(42, vec![0x01, 0xF7]), // sysex part 2 |
| 682 |
(42, vec![0x90, 0x41, 0x7f]), |
| 683 |
]) |
| 684 |
} |
| 685 |
} |
| 686 |
|
| 687 |
#[test] |
| 688 |
fn compare_sysex_split2() { |
| 689 |
// the sysex must not be merged with the surrounding packets |
| 690 |
unsafe { |
| 691 |
compare_packet_list(vec![ |
| 692 |
(42, vec![0x90, 0x40, 0x7f]), |
| 693 |
(42, vec![0xF0, 0x01, 0x01, 0x01, 0x01]), // sysex part 1 |
| 694 |
(42, vec![0x01, 0x01, 0x01]), // sysex part 2 |
| 695 |
(42, vec![0x01, 0xF7]), // sysex part 3 |
| 696 |
(42, vec![0x90, 0x41, 0x7f]), |
| 697 |
]) |
| 698 |
} |
| 699 |
} |
| 700 |
|
| 701 |
#[test] |
| 702 |
fn compare_sysex_malformed() { |
| 703 |
// the sysex must not be merged with the surrounding packets |
| 704 |
unsafe { |
| 705 |
compare_packet_list(vec![ |
| 706 |
(42, vec![0x90, 0x40, 0x7f]), |
| 707 |
(42, vec![0xF0, 0x01, 0x01, 0x01, 0x01]), // sysex part 1 |
| 708 |
(42, vec![0x01, 0x01, 0x01]), // sysex part 2 |
| 709 |
//(42, vec![0x01, 0xF7]), // sysex part 3 (missing) |
| 710 |
(42, vec![0x90, 0x41, 0x7f]), |
| 711 |
]) |
| 712 |
} |
| 713 |
} |
| 714 |
|
| 715 |
#[test] |
| 716 |
fn compare_sysex_long() { |
| 717 |
let mut sysex = vec![0xF0]; |
| 718 |
sysex.resize(301, 0x01); |
| 719 |
sysex.push(0xF7); |
| 720 |
unsafe { |
| 721 |
compare_packet_list(vec![ |
| 722 |
(42, vec![0x90, 0x40, 0x7f]), |
| 723 |
(43, vec![0x90, 0x41, 0x7f]), |
| 724 |
(43, sysex), |
| 725 |
]) |
| 726 |
} |
| 727 |
} |
| 728 |
|
| 729 |
/// Compares the results of building a PacketList using our PacketBuffer API |
| 730 |
/// and the native API (MIDIPacketListAdd, etc). |
| 731 |
unsafe fn compare_packet_list(packets: Vec<(MIDITimeStamp, Vec<u8>)>) { |
| 732 |
use coremidi_sys::{MIDIPacketListAdd, MIDIPacketListInit}; |
| 733 |
|
| 734 |
// allocate a buffer on the stack for building the list using native methods |
| 735 |
const BUFFER_SIZE: usize = 65536; // maximum allowed size |
| 736 |
let buffer: &mut [u8] = &mut [0; BUFFER_SIZE]; |
| 737 |
let pkt_list_ptr = buffer.as_mut_ptr() as *mut MIDIPacketList; |
| 738 |
|
| 739 |
// build the list |
| 740 |
let mut pkt_ptr = MIDIPacketListInit(pkt_list_ptr); |
| 741 |
for pkt in &packets { |
| 742 |
pkt_ptr = MIDIPacketListAdd( |
| 743 |
pkt_list_ptr, |
| 744 |
BUFFER_SIZE as u64, |
| 745 |
pkt_ptr, |
| 746 |
pkt.0, |
| 747 |
pkt.1.len() as u64, |
| 748 |
pkt.1.as_ptr(), |
| 749 |
); |
| 750 |
assert!(!pkt_ptr.is_null()); |
| 751 |
} |
| 752 |
let list_native = &*(pkt_list_ptr as *const _ as *const PacketList); |
| 753 |
|
| 754 |
// build the PacketBuffer, containing the same packets |
| 755 |
let mut packet_buf = PacketBuffer::new(packets[0].0, &packets[0].1); |
| 756 |
for pkt in &packets[1..] { |
| 757 |
packet_buf.push_data(pkt.0, &pkt.1); |
| 758 |
} |
| 759 |
|
| 760 |
// print buffer contents for debugging purposes |
| 761 |
let packet_buf_slice = packet_buf.storage.get_slice(); |
| 762 |
println!( |
| 763 |
"\nbuffer: {:?}", |
| 764 |
packet_buf_slice |
| 765 |
.iter() |
| 766 |
.map(|b| format!("{:02X}", b)) |
| 767 |
.collect::<Vec<String>>() |
| 768 |
.join(" ") |
| 769 |
); |
| 770 |
println!( |
| 771 |
"\nnative: {:?}", |
| 772 |
buffer[0..packet_buf_slice.len()] |
| 773 |
.iter() |
| 774 |
.map(|b| format!("{:02X}", b)) |
| 775 |
.collect::<Vec<String>>() |
| 776 |
.join(" ") |
| 777 |
); |
| 778 |
|
| 779 |
let list: &PacketList = &packet_buf; |
| 780 |
|
| 781 |
// check if the contents match |
| 782 |
assert_eq!( |
| 783 |
list_native.len(), |
| 784 |
list.len(), |
| 785 |
"PacketList lengths must match" |
| 786 |
); |
| 787 |
for (n, p) in list_native.iter().zip(list.iter()) { |
| 788 |
assert_eq!(n.data(), p.data()); |
| 789 |
} |
| 790 |
} |
| 791 |
} |