use libusb1_sys::constants::LIBUSB_TRANSFER_CANCELLED;
use std::time::{Duration, Instant};
pub(crate) const FLUSH_CANCEL_TIMEOUT: Duration = Duration::from_millis(1_000);
pub(crate) fn flush_cancel_targets(
current_epoch: u64,
slots: impl IntoIterator<Item = (bool, u64, usize)>,
) -> Vec<usize> {
let stale: Vec<(usize, usize)> = slots
.into_iter()
.enumerate()
.filter(|(_, (in_flight, epoch, _))| *in_flight && *epoch != current_epoch)
.map(|(index, (_, _, music_frames))| (index, music_frames))
.collect();
if stale.iter().any(|(_, music_frames)| *music_frames > 0) {
stale.into_iter().map(|(index, _)| index).collect()
} else {
Vec::new()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Completion {
Played,
CancelledByFlush,
UnexpectedCancel,
}
pub(crate) fn classify_completion(status: i32, cancelled_for_flush: bool) -> Completion {
match (status == LIBUSB_TRANSFER_CANCELLED, cancelled_for_flush) {
(true, true) => Completion::CancelledByFlush,
(true, false) => Completion::UnexpectedCancel,
(false, _) => Completion::Played,
}
}
pub(crate) fn wait_for_acknowledgements(
mut pending: impl FnMut() -> usize,
mut pump: impl FnMut() -> Result<(), String>,
timeout: Duration,
) -> Result<(), String> {
let started = Instant::now();
loop {
let outstanding = pending();
if outstanding == 0 {
return Ok(());
}
if started.elapsed() >= timeout {
return Err(format!(
"flush: {outstanding} isochronous transfer(s) did not come back within {} ms of being cancelled",
timeout.as_millis()
));
}
pump()?;
}
}
#[cfg(test)]
mod tests {
use super::*;
use libusb1_sys::constants::{
LIBUSB_TRANSFER_COMPLETED, LIBUSB_TRANSFER_ERROR, LIBUSB_TRANSFER_TIMED_OUT,
};
#[test]
fn music_of_an_earlier_epoch_on_the_bus_is_cancelled_with_everything_before_the_flush() {
let slots = [(true, 3, 96), (true, 3, 0), (false, 3, 96), (true, 4, 96)];
assert_eq!(flush_cancel_targets(4, slots), vec![0, 1]);
}
#[test]
fn transfers_filled_after_the_flush_are_never_cancelled() {
let slots = [(true, 4, 96), (true, 4, 0), (true, 4, 96)];
assert!(flush_cancel_targets(4, slots).is_empty());
}
#[test]
fn a_flush_while_only_silence_is_queued_leaves_the_bus_alone() {
let silence = [(true, 3, 0); 8];
assert!(flush_cancel_targets(4, silence).is_empty());
assert!(flush_cancel_targets(4, [(false, 0, 0); 8]).is_empty());
assert!(flush_cancel_targets(4, []).is_empty());
}
#[test]
fn an_idle_slot_is_never_a_target_whatever_it_remembers() {
assert!(flush_cancel_targets(4, [(false, 3, 96)]).is_empty());
}
#[test]
fn a_cancelled_flush_transfer_is_neither_loss_nor_a_failure() {
assert_eq!(
classify_completion(LIBUSB_TRANSFER_CANCELLED, true),
Completion::CancelledByFlush
);
assert_eq!(
classify_completion(LIBUSB_TRANSFER_CANCELLED, false),
Completion::UnexpectedCancel
);
}
#[test]
fn a_transfer_that_finished_before_the_cancel_arrived_is_accounted_normally() {
for status in [LIBUSB_TRANSFER_COMPLETED, LIBUSB_TRANSFER_TIMED_OUT, LIBUSB_TRANSFER_ERROR] {
assert_eq!(classify_completion(status, true), Completion::Played);
assert_eq!(classify_completion(status, false), Completion::Played);
}
}
#[test]
fn the_wait_ends_as_soon_as_every_transfer_is_back() {
let outstanding = std::cell::Cell::new(3);
let pumps = std::cell::Cell::new(0);
wait_for_acknowledgements(
|| outstanding.get(),
|| {
pumps.set(pumps.get() + 1);
outstanding.set(outstanding.get() - 1);
Ok(())
},
Duration::from_secs(5),
)
.unwrap();
assert_eq!(pumps.get(), 3);
wait_for_acknowledgements(|| 0, || panic!("pumped"), Duration::from_secs(5)).unwrap();
}
#[test]
fn a_transfer_that_never_returns_ends_the_wait_with_a_clear_error() {
let started = Instant::now();
let error = wait_for_acknowledgements(
|| 2,
|| {
std::thread::sleep(Duration::from_millis(2));
Ok(())
},
Duration::from_millis(30),
)
.unwrap_err();
assert!(started.elapsed() < Duration::from_secs(2), "bounded");
assert!(error.contains("2 isochronous transfer(s)"), "{error}");
assert!(error.contains("30 ms"), "{error}");
assert!(error.contains("flush"), "{error}");
}
#[test]
fn a_failing_pump_is_reported_at_once() {
let error = wait_for_acknowledgements(|| 1, || Err("libusb_handle_events failed".into()), Duration::from_secs(5))
.unwrap_err();
assert_eq!(error, "libusb_handle_events failed");
}
}