usbdac-core 0.1.21

Direct USB DAC playback for Rust audio applications on Android and Linux, with PCM, DoP, native DSD and bit-perfect reporting.
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
use crate::iso_packet_scheduler::IsoPacketScheduler;
use crate::iso_packet_validation::{
    account_timed_out_transfer, validate_iso_packet_descriptors, CompletionStats, PacketAcceptance,
};
use libusb1_sys::{
    constants::{
        LIBUSB_TRANSFER_CANCELLED, LIBUSB_TRANSFER_COMPLETED, LIBUSB_TRANSFER_ERROR,
        LIBUSB_TRANSFER_NO_DEVICE, LIBUSB_TRANSFER_OVERFLOW, LIBUSB_TRANSFER_STALL,
        LIBUSB_TRANSFER_TIMED_OUT,
    },
    libusb_iso_packet_descriptor,
};

fn completed_packets(packet_sizes: &[usize]) -> Vec<libusb_iso_packet_descriptor> {
    packet_sizes
        .iter()
        .map(|length| libusb_iso_packet_descriptor {
            length: *length as u32,
            actual_length: *length as u32,
            status: LIBUSB_TRANSFER_COMPLETED,
        })
        .collect()
}

#[test]
fn test_variable_44100_hz_packets_match_the_submitted_schedule() {
    let mut scheduler = IsoPacketScheduler::new(44_100, 4, 125);
    let packet_sizes = scheduler.next_transfer_packet_bytes();
    assert_eq!(&packet_sizes[..8], &[20, 24, 20, 24, 20, 24, 20, 24]);

    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    assert_eq!(
        validate_iso_packet_descriptors(
            &packet_sizes,
            &completed_packets(&packet_sizes),
            acceptance,
        ),
        Ok(Default::default())
    );
}

#[test]
fn test_issue_354_alternating_packet_phase_is_accepted() {
    let mut scheduler = IsoPacketScheduler::new(44_100, 4, 125);
    // The issue's capture is a 32-packet window; join whole transfers to get one.
    let mut packet_sizes = Vec::new();
    for _ in 0..(32 / scheduler.packets_per_transfer()) {
        packet_sizes.extend(scheduler.next_transfer_packet_bytes());
    }
    let mut descriptors = completed_packets(&packet_sizes);

    // Reconstruct the issue's 23 actual/expected mismatches: the host
    // controller repacketised the URB, so some 24-byte requests completed with
    // 20 bytes and some 20-byte requests with 24.
    for index in (1..16).chain(24..32) {
        descriptors[index].actual_length = 44 - descriptors[index].length;
    }
    assert_eq!(descriptors[0].actual_length, 20);
    assert_eq!(descriptors[0].length, 20);
    assert_eq!(descriptors[1].actual_length, 20);
    assert_eq!(descriptors[1].length, 24);

    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    let stats = validate_iso_packet_descriptors(&packet_sizes, &descriptors, acceptance).unwrap();
    assert_eq!(stats.short_packets, 23);
    assert_eq!(stats.shortfall_frames, 1);
    assert_eq!(stats.lost_bytes, 4);
    assert_eq!(stats.zero_packets, 0);
    assert_eq!(stats.descriptor_rewrites, 0);
}

#[test]
fn test_swapped_legal_sizes_are_accepted() {
    let packet_sizes = [20, 24];
    let mut descriptors = completed_packets(&packet_sizes);
    descriptors[0].actual_length = 24;
    descriptors[1].actual_length = 20;

    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    let stats = validate_iso_packet_descriptors(&packet_sizes, &descriptors, acceptance).unwrap();
    assert_eq!(stats.short_packets, 2);
    assert_eq!(stats.shortfall_frames, 0);
    assert_eq!(stats.lost_bytes, 0);
}

#[test]
fn test_descriptor_rewrite_is_diagnostic_only() {
    let mut descriptors = completed_packets(&[20]);
    descriptors[0].length = 24;
    descriptors[0].actual_length = 20;

    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    let stats = validate_iso_packet_descriptors(&[20], &descriptors, acceptance).unwrap();
    assert_eq!(stats.descriptor_rewrites, 1);
    assert_eq!(stats.short_packets, 0);
}

#[test]
fn test_unaligned_oversized_and_over_request_are_rejected() {
    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    for actual_length in [19, 21, 28] {
        let mut descriptors = completed_packets(&[24]);
        descriptors[0].actual_length = actual_length;
        let error = validate_iso_packet_descriptors(&[24], &descriptors, acceptance).unwrap_err();
        assert!(error.contains("isochronous transfer completed with packet errors:"));
        assert!(error.contains("legal=20/24 frame=4"));
    }
}

#[test]
fn test_zero_length_packets_are_counted_not_rejected() {
    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    let mut descriptors = completed_packets(&[24]);
    descriptors[0].actual_length = 0;
    let stats = validate_iso_packet_descriptors(&[24], &descriptors, acceptance).unwrap();
    assert_eq!(stats.zero_packets, 1);
    assert_eq!(stats.shortfall_frames, 6);
    assert_eq!(stats.lost_bytes, 24);

    // A packet nobody asked anything of is not a dropped packet.
    let empty_request =
        validate_iso_packet_descriptors(&[0, 4], &completed_packets(&[0, 4]), acceptance).unwrap();
    assert_eq!(empty_request.zero_packets, 0);
    assert_eq!(empty_request.lost_bytes, 0);
}

#[test]
fn test_unrecoverable_packet_errors_are_rejected_even_when_lengths_match() {
    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    for (status, label) in [
        (LIBUSB_TRANSFER_NO_DEVICE, "no_device"),
        (LIBUSB_TRANSFER_CANCELLED, "cancelled"),
        (99, "unknown"),
    ] {
        let mut descriptors = completed_packets(&[24]);
        descriptors[0].status = status;
        let error = validate_iso_packet_descriptors(&[24], &descriptors, acceptance).unwrap_err();
        assert!(error.contains("status_errors=1"));
        assert!(error.contains(&format!("status={}({})", label, status)));
    }
}

#[test]
fn test_failed_packet_recovery_accounts_every_known_empty_request() {
    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    let schedule = [24, 20, 24];
    let mut packets = completed_packets(&schedule);
    packets[0].status = LIBUSB_TRANSFER_ERROR;
    packets[0].actual_length = 0;
    packets[1].actual_length = 24; // a legal larger neighbour cannot mask the error

    let stats = validate_iso_packet_descriptors(&schedule, &packets, acceptance).unwrap();
    assert_eq!(stats.lost_bytes, 24);
    assert_eq!(stats.shortfall_frames, 6);
    assert!(
        validate_iso_packet_descriptors(&schedule, &packets, PacketAcceptance::exact()).is_err()
    );

    packets[0].length = 20;
    assert!(validate_iso_packet_descriptors(&schedule, &packets, acceptance).is_err());
    packets[0].length = 24;

    packets[2].status = LIBUSB_TRANSFER_ERROR;
    packets[2].actual_length = 0;
    assert_eq!(
        validate_iso_packet_descriptors(&schedule, &packets, acceptance)
            .unwrap()
            .lost_bytes,
        48
    );
    packets[2].status = LIBUSB_TRANSFER_COMPLETED;
    packets[2].actual_length = 24;

    for status in [LIBUSB_TRANSFER_NO_DEVICE, LIBUSB_TRANSFER_CANCELLED] {
        packets[0].status = status;
        assert!(validate_iso_packet_descriptors(&schedule, &packets, acceptance).is_err());
    }
}

#[test]
fn test_empty_error_bursts_retain_exact_loss_for_each_packet() {
    let schedule = [24, 24, 24, 24];
    for status in [
        LIBUSB_TRANSFER_ERROR,
        LIBUSB_TRANSFER_TIMED_OUT,
        LIBUSB_TRANSFER_OVERFLOW,
    ] {
        let mut packets = completed_packets(&schedule);
        for packet in &mut packets {
            packet.status = status;
            packet.actual_length = 0;
        }
        let stats = validate_iso_packet_descriptors(
            &schedule,
            &packets,
            PacketAcceptance::new(48_000, 125, 4),
        )
        .unwrap();
        assert_eq!(stats.lost_bytes, 96);
        assert_eq!(stats.lost_ring_frames(4), 24);
        packets[0].actual_length = 4;
        assert_eq!(
            validate_iso_packet_descriptors(
                &schedule,
                &packets,
                PacketAcceptance::new(48_000, 125, 4)
            )
            .unwrap()
            .lost_bytes,
            96
        );
    }
}

#[test]
fn test_packet_count_mismatches_are_rejected_and_identified() {
    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    let error = validate_iso_packet_descriptors(&[20, 24], &completed_packets(&[20]), acceptance)
        .unwrap_err();
    assert!(error.contains("packet_counts=requested:2,descriptors:1"));
    assert!(error.contains("packet count changed"));

    let error = validate_iso_packet_descriptors(&[20], &completed_packets(&[20, 24]), acceptance)
        .unwrap_err();
    assert!(error.contains("packet_counts=requested:1,descriptors:2"));
}

#[test]
fn test_matching_schedules_across_rates_formats_and_service_intervals() {
    for sample_rate in [
        44_100, 48_000, 88_200, 96_000, 176_400, 192_000, 352_800, 384_000,
    ] {
        for channels in [1, 2] {
            for subslot_bytes in [1, 2, 3, 4] {
                for service_interval_us in [125, 250, 1_000] {
                    let bytes_per_frame = channels * subslot_bytes;
                    let mut scheduler =
                        IsoPacketScheduler::new(sample_rate, bytes_per_frame, service_interval_us);
                    let acceptance =
                        PacketAcceptance::new(sample_rate, service_interval_us, bytes_per_frame);
                    for _ in 0..8 {
                        let packet_sizes = scheduler.next_transfer_packet_bytes();
                        assert_eq!(
                            validate_iso_packet_descriptors(
                                &packet_sizes,
                                &completed_packets(&packet_sizes),
                                acceptance,
                            ),
                            Ok(Default::default())
                        );
                    }
                }
            }
        }
    }
}

#[test]
fn test_feedback_paced_packets_use_the_actual_submitted_schedule() {
    for sample_rate in [44_100, 48_000, 352_800] {
        let mut scheduler = IsoPacketScheduler::new(sample_rate, 6, 125);
        let acceptance = PacketAcceptance::new(sample_rate, 125, 6);
        let nominal = f64::from(sample_rate) * 125.0 / 1_000_000.0;
        assert!(scheduler.update_feedback_frames_per_packet(nominal * 0.9998));
        for _ in 0..64 {
            let packet_sizes = scheduler.next_transfer_packet_bytes();
            assert_eq!(
                validate_iso_packet_descriptors(
                    &packet_sizes,
                    &completed_packets(&packet_sizes),
                    acceptance,
                ),
                Ok(Default::default())
            );
        }
    }
}

#[test]
fn test_stale_schedule_with_a_different_packet_count_is_rejected() {
    let mut scheduler = IsoPacketScheduler::new(44_100, 4, 125);
    let mut old_packet_sizes = Vec::new();
    for _ in 0..2 {
        old_packet_sizes.extend(scheduler.next_transfer_packet_bytes());
    }
    let current_packet_sizes = scheduler.next_transfer_packet_bytes();
    let descriptors = completed_packets(&current_packet_sizes);

    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    assert!(validate_iso_packet_descriptors(&old_packet_sizes, &descriptors, acceptance).is_err());
    assert_eq!(
        validate_iso_packet_descriptors(&current_packet_sizes, &descriptors, acceptance),
        Ok(Default::default())
    );
}

#[test]
fn test_failure_packet_dump_is_bounded_but_totals_cover_all_packets() {
    let packet_sizes = vec![24; 40];
    let mut descriptors = completed_packets(&packet_sizes);
    for packet in &mut descriptors {
        // 22 bytes is neither 20 nor 24 and is not frame-aligned.
        packet.actual_length = 22;
    }

    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    let error =
        validate_iso_packet_descriptors(&packet_sizes, &descriptors, acceptance).unwrap_err();
    assert!(!error.contains("#32:"));
    assert!(error.contains("omitted_packets=8"));
    assert!(error.contains("requested_total=960 descriptor_total=960 actual_total=880"));
    assert!(error.contains("length_mismatches=40"));
}

#[test]
fn test_exact_mode_still_rejects_any_shortfall() {
    let mut descriptors = completed_packets(&[24]);
    descriptors[0].actual_length = 20;
    assert!(
        validate_iso_packet_descriptors(&[24], &descriptors, PacketAcceptance::exact()).is_err()
    );
    assert_eq!(
        validate_iso_packet_descriptors(
            &[24],
            &completed_packets(&[24]),
            PacketAcceptance::exact()
        ),
        Ok(Default::default())
    );
}

#[test]
fn test_exact_mode_rejects_a_zero_length_completion_of_a_non_empty_packet() {
    let mut descriptors = completed_packets(&[24]);
    descriptors[0].actual_length = 0;
    let error = validate_iso_packet_descriptors(&[24], &descriptors, PacketAcceptance::exact())
        .unwrap_err();
    assert!(error.contains("zero-length completion of a non-empty packet"));
    assert!(error.contains("actual_total=0"));

    // One dead packet among healthy ones is still an error in exact mode.
    let mut descriptors = completed_packets(&[24, 24, 24]);
    descriptors[1].actual_length = 0;
    assert!(validate_iso_packet_descriptors(
        &[24, 24, 24],
        &descriptors,
        PacketAcceptance::exact()
    )
    .is_err());
}

#[test]
fn test_exact_mode_accepts_an_empty_request_that_completes_empty() {
    assert_eq!(
        validate_iso_packet_descriptors(
            &[0, 24],
            &completed_packets(&[0, 24]),
            PacketAcceptance::exact()
        ),
        Ok(Default::default())
    );
}

#[test]
fn test_envelope_mode_still_tolerates_zero_length_completions() {
    // Envelope-based streams count the shortfall as loss instead of failing;
    // only exact mode treats a zero-length completion as an error.
    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    let mut descriptors = completed_packets(&[24, 20]);
    descriptors[0].actual_length = 0;
    let stats = validate_iso_packet_descriptors(&[24, 20], &descriptors, acceptance).unwrap();
    assert_eq!(stats.zero_packets, 1);
    assert_eq!(stats.lost_bytes, 24);
}

#[test]
fn test_lost_bytes_is_the_submitted_total_minus_the_delivered_total() {
    let acceptance = PacketAcceptance::new(44_100, 125, 4);

    // A swap of the two legal sizes with an equal URB total delivers everything.
    let mut swapped = completed_packets(&[20, 24]);
    swapped[0].actual_length = 24;
    swapped[1].actual_length = 20;
    let stats = validate_iso_packet_descriptors(&[20, 24], &swapped, acceptance).unwrap();
    assert_eq!((stats.short_packets, stats.lost_bytes), (2, 0));

    // An all-zero URB loses all of it.
    let mut zeroed = completed_packets(&[20, 24, 20, 24]);
    for packet in &mut zeroed {
        packet.actual_length = 0;
    }
    let stats = validate_iso_packet_descriptors(&[20, 24, 20, 24], &zeroed, acceptance).unwrap();
    assert_eq!((stats.zero_packets, stats.lost_bytes), (4, 88));
    assert_eq!(stats.lost_ring_frames(4), 22);
}

#[test]
fn test_lost_ring_frames_rounds_up_and_never_divides_by_zero() {
    let stats = CompletionStats {
        lost_bytes: 5,
        ..CompletionStats::default()
    };
    assert_eq!(stats.lost_ring_frames(4), 2);
    assert_eq!(stats.lost_ring_frames(0), 5);
    assert_eq!(CompletionStats::default().lost_ring_frames(4), 0);
}

#[test]
fn test_timed_out_transfer_credits_only_packets_that_completed_in_full() {
    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    let packet_sizes = [20, 24, 20, 24];

    // libusb reports a packet the timeout cancelled as COMPLETED with 0 bytes.
    let mut descriptors = completed_packets(&packet_sizes);
    descriptors[2].actual_length = 0;
    descriptors[3].actual_length = 20; // short fragment: not credited
    let stats = account_timed_out_transfer(&packet_sizes, &descriptors, acceptance);
    assert_eq!(stats.lost_bytes, 44);
    assert_eq!(stats.shortfall_frames, 11);
    assert_eq!((stats.short_packets, stats.zero_packets), (0, 0));

    // A packet with an error status is lost even though it reports full length.
    let mut descriptors = completed_packets(&packet_sizes);
    descriptors[0].status = LIBUSB_TRANSFER_ERROR;
    assert_eq!(
        account_timed_out_transfer(&packet_sizes, &descriptors, acceptance).lost_bytes,
        20
    );

    // Every packet whole means nothing was lost.
    assert_eq!(
        account_timed_out_transfer(&packet_sizes, &completed_packets(&packet_sizes), acceptance)
            .lost_bytes,
        0
    );
}

#[test]
fn test_timed_out_transfer_with_mismatched_descriptors_loses_the_whole_urb() {
    let acceptance = PacketAcceptance::new(44_100, 125, 4);
    let packet_sizes = [20, 24, 20, 24];
    let stats =
        account_timed_out_transfer(&packet_sizes, &completed_packets(&[20, 24]), acceptance);
    assert_eq!(stats.lost_bytes, 88);
    assert_eq!(stats.shortfall_frames, 22);
    let stats = account_timed_out_transfer(&packet_sizes, &[], acceptance);
    assert_eq!(stats.lost_bytes, 88);
}

#[test]
fn tx_length_prefix_is_not_audio_or_lost_frames() {
    let acceptance = PacketAcceptance::new(44_100, 125, 6).with_packet_prefix(4);
    let schedule = [34, 40]; // 30/36 audio bytes, 4-byte headers.
    let mut packets = completed_packets(&schedule);
    assert_eq!(
        validate_iso_packet_descriptors(&schedule, &packets, acceptance).unwrap(),
        CompletionStats::default()
    );
    packets[0].actual_length = 40;
    packets[1].actual_length = 34;
    assert_eq!(
        validate_iso_packet_descriptors(&schedule, &packets, acceptance)
            .unwrap()
            .lost_bytes,
        0
    );
    for packet in &mut packets {
        packet.status = LIBUSB_TRANSFER_ERROR;
        packet.actual_length = 0;
    }
    let stats = validate_iso_packet_descriptors(&schedule, &packets, acceptance).unwrap();
    assert_eq!(stats.lost_bytes, 66);
    assert_eq!(stats.lost_ring_frames(6), 11);
    packets[0] = completed_packets(&[34]).remove(0);
    assert_eq!(
        account_timed_out_transfer(&schedule, &packets, acceptance).lost_bytes,
        36
    );
    packets[0].actual_length = 4;
    packets[1] = completed_packets(&[40]).remove(0);
    assert_eq!(
        validate_iso_packet_descriptors(&schedule, &packets, acceptance)
            .unwrap()
            .lost_bytes,
        30
    );
    packets[0].actual_length = 3;
    assert!(validate_iso_packet_descriptors(&schedule, &packets, acceptance).is_err());
}

#[test]
fn stalled_partial_packet_is_charged_without_crediting_unconfirmed_bytes() {
    let mut packets = completed_packets(&[24, 24]);
    packets[0].status = LIBUSB_TRANSFER_STALL;
    packets[0].actual_length = 12;
    let stats =
        validate_iso_packet_descriptors(&[24, 24], &packets, PacketAcceptance::new(48_000, 125, 4))
            .unwrap();
    assert_eq!(stats.lost_bytes, 24);
}