codecraft 0.1.2

A minimalist 3D game engine built on parts of Bevy (ECS, color) with wgpu and winit: OpenPBR materials, clustered lighting, a yakui-drawn UI, audio and gamepad haptics; its binary maps any folder, and the symbols of its Rust files, as a 3D wall of boxes
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
//! Sound out of the pad in the player's hands: a DualSense on USB is a 4-channel
//! sound card (speaker/headset on 1-2, haptic actuators on 3-4).
use std::ffi::CStr;
use std::time::Duration;

use rodio::Source;
use rodio::buffer::SamplesBuffer;
use rodio::cpal::traits::{DeviceTrait, HostTrait};

use super::synth::OnePole;

/// Haptic lane low-pass; above ~100 Hz the actuators buzz rather than kick.
const HAPTIC_CUTOFF_HZ: f32 = 120.0;

/// Identifies a pad's sound card and matches it to the HID device in the same plastic, via the USB container id on Windows.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum PadKey {
    /// The USB container id, as the 128 bits of its GUID.
    Container(u128),
    /// The n-th pad-shaped output in host order; not stable across replugging.
    Ordinal(usize),
}

impl std::fmt::Debug for PadKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Container(id) => write!(f, "Container({id:032x})"),
            Self::Ordinal(n) => write!(f, "Ordinal({n})"),
        }
    }
}

impl PadKey {
    /// The key a HID device's sound card will carry; `None` off Windows.
    pub fn of_hid_path(path: &CStr) -> Option<Self> {
        container_of_hid_path(path).map(Self::Container)
    }
}

/// The container id of the USB device behind a HID interface path, if it can be found.
pub fn container_of_hid_path(path: &CStr) -> Option<u128> {
    platform::container_of_hid_path(path)
}

/// One active output endpoint, with the friendly name and container id cpal does not pass through.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Endpoint {
    pub index: usize,
    /// The endpoint id string, which is what cpal's `DeviceTrait::id()` carries on Windows.
    pub id: String,
    /// The full name Windows shows, e.g. "Speakers (2- Wireless Controller)".
    pub friendly_name: String,
    pub container: Option<u128>,
}

/// Every active output endpoint, in cpal's order; empty off Windows.
pub fn endpoints() -> Vec<Endpoint> {
    platform::endpoints()
}

/// Whether an endpoint's friendly name is a PlayStation pad's.
pub fn is_pad_name(name: &str) -> bool {
    name.contains("Wireless Controller")
}

/// A GUID's 128 bits in text order, matching `windows::core::GUID::to_u128`.
pub fn guid_to_u128(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> u128 {
    (data1 as u128) << 96
        | (data2 as u128) << 80
        | (data3 as u128) << 64
        | u64::from_be_bytes(data4) as u128
}

/// One opened pad sound card.
pub struct PadSpeaker {
    /// Dropping this stops the sound, so it is kept.
    _device: rodio::MixerDeviceSink,
    mixer: rodio::mixer::Mixer,
    channels: rodio::ChannelCount,
    sample_rate: rodio::SampleRate,
    pub key: PadKey,
    pub name: String,
}

impl std::fmt::Debug for PadSpeaker {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PadSpeaker")
            .field("key", &self.key)
            .field("name", &self.name)
            .field("channels", &self.channels)
            .field("sample_rate", &self.sample_rate)
            .finish()
    }
}

impl PadSpeaker {
    /// What the pad's output runs at.
    pub fn sample_rate(&self) -> rodio::SampleRate {
        self.sample_rate
    }

    pub fn channels(&self) -> rodio::ChannelCount {
        self.channels
    }

    /// Plays a mono clip out of the pad at the given speaker and haptic gains; the mixer resamples if needed.
    pub fn play(&self, clip: SamplesBuffer, speaker: f32, haptic: f32) {
        self.add(clip, speaker, haptic);
    }

    /// Adds any mono source spread over the pad's lanes; a two-channel pad gets no haptic.
    pub fn add<S>(&self, source: S, speaker: f32, haptic: f32)
    where
        S: Source<Item = f32> + Send + 'static,
    {
        if self.channels.get() >= 4 {
            self.mixer.add(Quad::new(source, speaker, haptic));
        } else {
            self.mixer.add(Stereo::new(source, speaker, haptic));
        }
    }
}

/// Opens every pad sound card the host has, each at its own default format.
/// Opening at two channels would make Windows fold the pair into all four and feed the actuators the speaker signal.
pub fn open_pad_speakers() -> Vec<PadSpeaker> {
    let endpoints = endpoints();
    let devices = match rodio::cpal::default_host().output_devices() {
        Ok(devices) => devices,
        Err(error) => {
            log::warn!("could not list audio outputs ({error}); no pad speakers");
            return Vec::new();
        }
    };

    let mut pads = Vec::new();
    // Counts pads opened or not, so an ordinal key is stable when an earlier pad fails to open.
    let mut seen = 0;
    for device in devices {
        let Ok(config) = device.default_output_config() else {
            continue;
        };
        let endpoint = device
            .id()
            .ok()
            .and_then(|id| endpoints.iter().find(|endpoint| endpoint.id == id.1));
        let is_pad = match endpoint {
            Some(endpoint) => is_pad_name(&endpoint.friendly_name),
            None => config.channels() == 4,
        };
        if !is_pad {
            continue;
        }

        let name = match endpoint {
            Some(endpoint) => endpoint.friendly_name.clone(),
            None => device
                .description()
                .map(|description| description.name().to_owned())
                .unwrap_or_else(|_| "unnamed output".to_owned()),
        };
        let key = match endpoint.and_then(|endpoint| endpoint.container) {
            Some(container) => PadKey::Container(container),
            None => PadKey::Ordinal(seen),
        };
        seen += 1;

        let opened =
            rodio::DeviceSinkBuilder::from_device(device).and_then(|builder| builder.open_stream());
        let mut device = match opened {
            Ok(device) => device,
            Err(error) => {
                log::warn!("could not open pad speaker {name}: {error}");
                continue;
            }
        };
        device.log_on_drop(false);
        let channels = device.config().channel_count();
        let sample_rate = device.config().sample_rate();
        log::info!("pad speaker: {name}, {channels} ch {sample_rate} Hz");
        pads.push(PadSpeaker {
            mixer: device.mixer().clone(),
            _device: device,
            channels,
            sample_rate,
            key,
            name,
        });
    }
    pads
}

/// A source folded to mono and spread over `N` interleaved lanes: `[speaker, speaker, haptic, haptic]` for four, speaker only for two.
pub struct Spread<S, const N: usize> {
    inner: S,
    speaker: f32,
    haptic: f32,
    filter: OnePole,
    frame: [f32; N],
    left: usize,
}

/// The four lanes of a pad.
pub type Quad<S> = Spread<S, 4>;

/// Speaker lanes only.
pub type Stereo<S> = Spread<S, 2>;

impl<S: Source<Item = f32>, const N: usize> Spread<S, N> {
    pub fn new(inner: S, speaker: f32, haptic: f32) -> Self {
        const {
            assert!(N == 2 || N == 4, "a pad has two lanes or four");
        }
        let filter = OnePole::new(inner.sample_rate().get() as f32, HAPTIC_CUTOFF_HZ);
        Self {
            inner,
            speaker,
            haptic,
            filter,
            frame: [0.0; N],
            left: 0,
        }
    }

    fn mono(&mut self) -> Option<f32> {
        let channels = self.inner.channels().get() as usize;
        let mut sum = self.inner.next()?;
        for _ in 1..channels {
            sum += self.inner.next()?;
        }
        Some(sum / channels as f32)
    }
}

impl<S: Source<Item = f32>, const N: usize> Iterator for Spread<S, N> {
    type Item = f32;

    fn next(&mut self) -> Option<f32> {
        if self.left == 0 {
            let sample = self.mono()?;
            let felt = self.filter.step(sample) * self.haptic;
            let heard = sample * self.speaker;
            self.frame = [heard; N];
            if N == 4 {
                self.frame[2] = felt;
                self.frame[3] = felt;
            }
            self.left = N;
        }
        let sample = self.frame[N - self.left];
        self.left -= 1;
        Some(sample)
    }
}

impl<S: Source<Item = f32>, const N: usize> Source for Spread<S, N> {
    // Must be exact: the mixer's UniformSourceIterator rebuilds its converters after this many samples.
    fn current_span_len(&self) -> Option<usize> {
        let channels = self.inner.channels().get() as usize;
        self.inner
            .current_span_len()
            .map(|span| span / channels * N + self.left)
    }

    fn channels(&self) -> rodio::ChannelCount {
        rodio::ChannelCount::new(N as u16).expect("N is two or four")
    }

    fn sample_rate(&self) -> rodio::SampleRate {
        self.inner.sample_rate()
    }

    fn total_duration(&self) -> Option<Duration> {
        self.inner.total_duration()
    }
}

/// The Windows side: container ids from the device tree and from audio endpoint property stores.
#[cfg(windows)]
mod platform {
    use std::ffi::CStr;

    use windows::Win32::Devices::DeviceAndDriverInstallation::{
        CM_Get_DevNode_PropertyW, CM_Get_Device_Interface_PropertyW, CM_LOCATE_DEVNODE_NORMAL,
        CM_Locate_DevNodeW, CR_BUFFER_SMALL, CR_SUCCESS,
    };
    use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;
    use windows::Win32::Devices::Properties::{
        DEVPKEY_Device_ContainerId, DEVPKEY_Device_InstanceId, DEVPROP_TYPE_GUID,
        DEVPROP_TYPE_STRING, DEVPROPTYPE,
    };
    use windows::Win32::Foundation::{DEVPROPKEY, PROPERTYKEY, RPC_E_CHANGED_MODE};
    use windows::Win32::Media::Audio::{
        DEVICE_STATE_ACTIVE, IDeviceTopology, IMMDevice, IMMDeviceEnumerator, IMMEndpoint,
        MMDeviceEnumerator, eAll, eRender,
    };
    use windows::Win32::System::Com::StructuredStorage::PropVariantClear;
    use windows::Win32::System::Com::{
        CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoTaskMemFree,
        CoUninitialize, STGM_READ,
    };
    use windows::Win32::System::Variant::{VT_CLSID, VT_LPWSTR};
    use windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore;
    use windows::core::{GUID, HRESULT, Interface, PCWSTR, PWSTR};

    use super::{Endpoint, guid_to_u128};

    /// The device-tree container id key, as an endpoint property store files it.
    const PKEY_DEVICE_CONTAINER_ID: PROPERTYKEY = PROPERTYKEY {
        fmtid: DEVPKEY_Device_ContainerId.fmtid,
        pid: DEVPKEY_Device_ContainerId.pid,
    };

    /// Per-thread COM init. `RPC_E_CHANGED_MODE` (cpal got here first) is usable but must not be paired with an uninitialise.
    struct ComInit(HRESULT);

    impl ComInit {
        fn usable(&self) -> bool {
            self.0.is_ok() || self.0 == RPC_E_CHANGED_MODE
        }
    }

    impl Drop for ComInit {
        fn drop(&mut self) {
            if self.0.is_ok() {
                unsafe { CoUninitialize() };
            }
        }
    }

    thread_local! {
        static COM: ComInit = ComInit(unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) });
    }

    fn com_usable() -> bool {
        COM.with(ComInit::usable)
    }

    fn wide(text: &str) -> Vec<u16> {
        text.encode_utf16().chain(std::iter::once(0)).collect()
    }

    /// Takes a string COM handed us and frees the memory it came in.
    unsafe fn take_string(text: PWSTR) -> Option<String> {
        if text.is_null() {
            return None;
        }
        let owned = unsafe { text.to_string() }.ok();
        unsafe { CoTaskMemFree(Some(text.as_ptr() as *const _)) };
        owned
    }

    fn interface_string(path: &[u16], key: &DEVPROPKEY) -> Option<String> {
        let mut kind = DEVPROPTYPE::default();
        let mut size = 0u32;
        let asked = unsafe {
            CM_Get_Device_Interface_PropertyW(
                PCWSTR(path.as_ptr()),
                key,
                &mut kind,
                None,
                &mut size,
                0,
            )
        };
        if asked != CR_BUFFER_SMALL || kind != DEVPROP_TYPE_STRING || size < 2 {
            return None;
        }
        let mut buffer = vec![0u16; size as usize / 2];
        let read = unsafe {
            CM_Get_Device_Interface_PropertyW(
                PCWSTR(path.as_ptr()),
                key,
                &mut kind,
                Some(buffer.as_mut_ptr() as *mut u8),
                &mut size,
                0,
            )
        };
        if read != CR_SUCCESS {
            return None;
        }
        let end = buffer.iter().position(|&c| c == 0).unwrap_or(buffer.len());
        Some(String::from_utf16_lossy(&buffer[..end]))
    }

    fn devnode_guid(devinst: u32, key: &DEVPROPKEY) -> Option<u128> {
        let mut kind = DEVPROPTYPE::default();
        let mut guid = GUID::default();
        let mut size = std::mem::size_of::<GUID>() as u32;
        let read = unsafe {
            CM_Get_DevNode_PropertyW(
                devinst,
                key,
                &mut kind,
                Some(&mut guid as *mut GUID as *mut u8),
                &mut size,
                0,
            )
        };
        if read != CR_SUCCESS || kind != DEVPROP_TYPE_GUID {
            return None;
        }
        Some(guid_to_u128(guid.data1, guid.data2, guid.data3, guid.data4))
    }

    /// The container id of the device behind any interface path, HID or audio.
    fn container_of_interface(path: &str) -> Option<u128> {
        let instance = interface_string(&wide(path), &DEVPKEY_Device_InstanceId)?;
        let instance = wide(&instance);
        let mut devinst = 0u32;
        let located = unsafe {
            CM_Locate_DevNodeW(
                &mut devinst,
                PCWSTR(instance.as_ptr()),
                CM_LOCATE_DEVNODE_NORMAL,
            )
        };
        if located != CR_SUCCESS {
            return None;
        }
        devnode_guid(devinst, &DEVPKEY_Device_ContainerId)
    }

    pub fn container_of_hid_path(path: &CStr) -> Option<u128> {
        container_of_interface(&path.to_string_lossy())
    }

    unsafe fn store_string(store: &IPropertyStore, key: &PROPERTYKEY) -> Option<String> {
        let mut value = unsafe { store.GetValue(key) }.ok()?;
        let inner = unsafe { &value.Anonymous.Anonymous };
        let text = if inner.vt == VT_LPWSTR {
            unsafe { inner.Anonymous.pwszVal.to_string() }.ok()
        } else {
            None
        };
        unsafe { PropVariantClear(&mut value) }.ok();
        text
    }

    unsafe fn store_guid(store: &IPropertyStore, key: &PROPERTYKEY) -> Option<u128> {
        let mut value = unsafe { store.GetValue(key) }.ok()?;
        let inner = unsafe { &value.Anonymous.Anonymous };
        let guid = if inner.vt == VT_CLSID {
            let pointer = unsafe { inner.Anonymous.puuid };
            (!pointer.is_null()).then(|| unsafe { *pointer })
        } else {
            None
        };
        unsafe { PropVariantClear(&mut value) }.ok();
        guid.map(|guid| guid_to_u128(guid.data1, guid.data2, guid.data3, guid.data4))
    }

    /// The adapter's interface path from an endpoint's topology; the connector id is `{2}.<path>\<pin>`.
    pub fn adapter_path_of(device: &IMMDevice) -> Option<String> {
        unsafe {
            let topology: IDeviceTopology = device.Activate(CLSCTX_ALL, None).ok()?;
            let connector = topology.GetConnector(0).ok()?;
            let id = take_string(connector.GetDeviceIdConnectedTo().ok()?)?;
            let path = id.strip_prefix("{2}.").unwrap_or(&id);
            let end = path.rfind('}')?;
            Some(path[..=end].to_owned())
        }
    }

    /// Every active render endpoint, using the same enumeration and filter as cpal so the indices line up.
    pub fn endpoints() -> Vec<Endpoint> {
        if !com_usable() {
            log::warn!("COM would not initialise; pads cannot be told apart");
            return Vec::new();
        }
        let mut found = Vec::new();
        unsafe {
            let enumerator: IMMDeviceEnumerator =
                match CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL) {
                    Ok(enumerator) => enumerator,
                    Err(error) => {
                        log::warn!("no audio endpoint enumerator ({error})");
                        return found;
                    }
                };
            let Ok(collection) = enumerator.EnumAudioEndpoints(eAll, DEVICE_STATE_ACTIVE) else {
                return found;
            };
            let count = collection.GetCount().unwrap_or(0);
            for item in 0..count {
                let Ok(device) = collection.Item(item) else {
                    continue;
                };
                let flow = device
                    .cast::<IMMEndpoint>()
                    .and_then(|endpoint| endpoint.GetDataFlow());
                if flow != Ok(eRender) {
                    continue;
                }
                let Some(id) = device.GetId().ok().and_then(|id| take_string(id)) else {
                    continue;
                };
                let store = device.OpenPropertyStore(STGM_READ).ok();
                let friendly_name = store
                    .as_ref()
                    .and_then(|store| store_string(store, &PKEY_Device_FriendlyName))
                    .unwrap_or_default();
                let container = store
                    .as_ref()
                    .and_then(|store| store_guid(store, &PKEY_DEVICE_CONTAINER_ID))
                    .or_else(|| {
                        adapter_path_of(&device).and_then(|path| container_of_interface(&path))
                    });
                found.push(Endpoint {
                    index: found.len(),
                    id,
                    friendly_name,
                    container,
                });
            }
        }
        found
    }
}

/// Off Windows there is no container id, so a pad is any four-channel output keyed by ordinal.
#[cfg(not(windows))]
mod platform {
    use std::ffi::CStr;

    use super::Endpoint;

    pub fn container_of_hid_path(_path: &CStr) -> Option<u128> {
        None
    }

    pub fn endpoints() -> Vec<Endpoint> {
        Vec::new()
    }
}

#[cfg(test)]
mod tests {
    use std::f32::consts::TAU;

    use super::*;

    const RATE: u32 = 48000;

    fn rate() -> rodio::SampleRate {
        rodio::SampleRate::new(RATE).unwrap()
    }

    fn mono(samples: Vec<f32>) -> SamplesBuffer {
        SamplesBuffer::new(rodio::ChannelCount::MIN, rate(), samples)
    }

    fn tone(hz: f32, seconds: f32) -> SamplesBuffer {
        let count = (RATE as f32 * seconds) as usize;
        mono(
            (0..count)
                .map(|i| (TAU * hz * i as f32 / RATE as f32).sin())
                .collect(),
        )
    }

    fn lane_peak(samples: &[f32], lanes: usize, lane: usize, skip: usize) -> f32 {
        samples
            .iter()
            .skip(skip * lanes + lane)
            .step_by(lanes)
            .fold(0.0f32, |peak, s| peak.max(s.abs()))
    }

    #[test]
    fn a_mono_impulse_comes_out_as_four_samples_with_the_right_gains() {
        let quad = Quad::new(mono(vec![1.0, 0.0]), 0.5, 0.8);
        assert_eq!(quad.channels().get(), 4);
        assert_eq!(quad.sample_rate().get(), RATE);

        let out: Vec<f32> = quad.collect();
        assert_eq!(out.len(), 8, "four lanes per mono sample");
        assert_eq!(out[0], 0.5);
        assert_eq!(out[1], 0.5);
        // One step of the low-pass on an impulse is the filter's coefficient.
        let coefficient = 1.0 - (-TAU * HAPTIC_CUTOFF_HZ / RATE as f32).exp();
        assert!((out[2] - 0.8 * coefficient).abs() < 1e-6, "{}", out[2]);
        assert_eq!(out[2], out[3], "both hands get the same thump");
        assert!(
            out[2] > 0.0 && out[2] < 0.05,
            "and it is well under the speaker's"
        );
        assert_eq!(out[4], 0.0);
        assert!(out[6] > 0.0 && out[6] < out[2]);
    }

    #[test]
    fn the_haptic_lane_keeps_a_thump_and_drops_a_crack() {
        let low: Vec<f32> = Quad::new(tone(30.0, 0.5), 1.0, 1.0).collect();
        let high: Vec<f32> = Quad::new(tone(5000.0, 0.5), 1.0, 1.0).collect();
        let settle = RATE as usize / 10;
        let low_felt = lane_peak(&low, 4, 2, settle);
        let high_felt = lane_peak(&high, 4, 2, settle);
        assert!(low_felt > 0.9, "the thump got through at {low_felt}");
        assert!(high_felt < 0.05, "the crack got through at {high_felt}");
        assert!(lane_peak(&high, 4, 0, settle) > 0.99);
        assert!(lane_peak(&low, 4, 0, settle) > 0.99);
    }

    #[test]
    fn a_stereo_output_gets_the_speaker_lanes_and_nothing_felt() {
        let stereo = Stereo::new(mono(vec![1.0, -0.5]), 0.5, 0.8);
        assert_eq!(stereo.channels().get(), 2);
        let out: Vec<f32> = stereo.collect();
        assert_eq!(out, vec![0.5, 0.5, -0.25, -0.25]);
    }

    #[test]
    fn a_stereo_source_is_folded_to_mono_before_it_is_spread() {
        let clip = SamplesBuffer::new(
            rodio::ChannelCount::new(2).unwrap(),
            rate(),
            vec![1.0, 0.0, 0.5, 0.5],
        );
        let out: Vec<f32> = Stereo::new(clip, 1.0, 0.0).collect();
        assert_eq!(out, vec![0.5, 0.5, 0.5, 0.5]);
    }

    /// A mono source that reports its remaining span, unlike `SamplesBuffer`, which reports its whole length until spent.
    struct Remaining(Vec<f32>);

    impl Iterator for Remaining {
        type Item = f32;
        fn next(&mut self) -> Option<f32> {
            (!self.0.is_empty()).then(|| self.0.remove(0))
        }
    }

    impl Source for Remaining {
        fn current_span_len(&self) -> Option<usize> {
            Some(self.0.len())
        }
        fn channels(&self) -> rodio::ChannelCount {
            rodio::ChannelCount::MIN
        }
        fn sample_rate(&self) -> rodio::SampleRate {
            rate()
        }
        fn total_duration(&self) -> Option<Duration> {
            Some(Duration::from_millis(7))
        }
    }

    #[test]
    fn the_span_is_counted_in_output_samples() {
        let mut quad = Quad::new(Remaining(vec![0.1, 0.2, 0.3]), 1.0, 1.0);
        assert_eq!(quad.current_span_len(), Some(12));
        quad.next();
        assert_eq!(
            quad.current_span_len(),
            Some(11),
            "three of the frame left, and two frames"
        );
        let rest = quad.by_ref().count();
        assert_eq!(rest, 11);
        assert_eq!(quad.current_span_len(), Some(0));
        assert_eq!(quad.total_duration(), Some(Duration::from_millis(7)));

        let quad = Quad::new(mono(vec![0.1, 0.2, 0.3]), 1.0, 1.0);
        assert_eq!(quad.current_span_len(), Some(12));
        assert_eq!(quad.count(), 12);
    }

    #[test]
    fn a_loop_with_no_spans_reports_none() {
        struct Endless;
        impl Iterator for Endless {
            type Item = f32;
            fn next(&mut self) -> Option<f32> {
                Some(0.0)
            }
        }
        impl Source for Endless {
            fn current_span_len(&self) -> Option<usize> {
                None
            }
            fn channels(&self) -> rodio::ChannelCount {
                rodio::ChannelCount::MIN
            }
            fn sample_rate(&self) -> rodio::SampleRate {
                rate()
            }
            fn total_duration(&self) -> Option<Duration> {
                None
            }
        }
        let quad = Quad::new(Endless, 1.0, 1.0);
        assert_eq!(quad.current_span_len(), None);
        assert_eq!(quad.total_duration(), None);
    }

    #[test]
    fn a_key_is_its_container_and_nothing_else() {
        assert_eq!(PadKey::Container(7), PadKey::Container(7));
        assert_ne!(PadKey::Container(7), PadKey::Container(8));
        assert_ne!(PadKey::Container(1), PadKey::Ordinal(1));
        assert_eq!(PadKey::Ordinal(0), PadKey::Ordinal(0));
        assert_eq!(
            format!(
                "{:?}",
                PadKey::Container(0x8c7ed206_3f8a_4827_b3ab_ae9e1faefc6c)
            ),
            "Container(8c7ed2063f8a4827b3abae9e1faefc6c)",
            "a log line shows the GUID's digits, not a decimal",
        );
        assert_eq!(format!("{:?}", PadKey::Ordinal(2)), "Ordinal(2)");
        let mut set = std::collections::HashSet::new();
        set.insert(PadKey::Container(7));
        assert!(set.contains(&PadKey::Container(7)), "and it hashes");
    }

    #[test]
    fn a_pad_is_known_by_the_name_sony_gave_the_usb_device() {
        assert!(is_pad_name("Speakers (Wireless Controller)"));
        assert!(is_pad_name("Speakers (2- Wireless Controller)"));
        assert!(is_pad_name("Headphones (3- Wireless Controller)"));
        assert!(!is_pad_name("Speakers"));
        assert!(!is_pad_name("Speakers (Realtek(R) Audio)"));
        assert!(!is_pad_name("DELL U4320Q"));
        assert!(!is_pad_name(""));
    }

    #[test]
    fn a_guid_reads_as_the_number_its_text_form_writes() {
        let number = guid_to_u128(
            0x8c7ed206,
            0x3f8a,
            0x4827,
            [0xb3, 0xab, 0xae, 0x9e, 0x1f, 0xae, 0xfc, 0x6c],
        );
        assert_eq!(number, 0x8c7ed206_3f8a_4827_b3ab_ae9e1faefc6c);
        assert_eq!(guid_to_u128(0, 0, 0, [0; 8]), 0);
        assert_eq!(guid_to_u128(0, 0, 0, [0, 0, 0, 0, 0, 0, 0, 1]), 1);
        #[cfg(windows)]
        assert_eq!(
            number,
            windows::core::GUID::from_u128(0x8c7ed206_3f8a_4827_b3ab_ae9e1faefc6c).to_u128(),
            "and it is the same number the windows crate makes",
        );
    }

    /// A printout of this machine's devices: `cargo test -p codecraft --lib pads::probe -- --ignored --nocapture`.
    #[test]
    #[ignore]
    fn probe() {
        println!("cpal output devices:");
        if let Ok(devices) = rodio::cpal::default_host().output_devices() {
            for (index, device) in devices.enumerate() {
                let name = device
                    .description()
                    .map(|description| description.name().to_owned())
                    .unwrap_or_else(|error| format!("<{error}>"));
                let id = device
                    .id()
                    .map(|id| id.1)
                    .unwrap_or_else(|error| format!("<{error}>"));
                match device.default_output_config() {
                    Ok(config) => println!(
                        "  {index}: {name:?}  {} ch {} Hz {:?}  id {id}",
                        config.channels(),
                        config.sample_rate(),
                        config.sample_format(),
                    ),
                    Err(error) => println!("  {index}: {name:?}  <{error}>  id {id}"),
                }
            }
        }

        println!("render endpoints:");
        for endpoint in endpoints() {
            println!(
                "  {}: {:?}  container {}  id {}",
                endpoint.index,
                endpoint.friendly_name,
                endpoint
                    .container
                    .map(|c| format!("{c:032x}"))
                    .unwrap_or_else(|| "none".to_owned()),
                endpoint.id,
            );
        }

        println!("PlayStation HID interfaces:");
        if let Ok(api) = hidapi::HidApi::new() {
            for info in api.device_list().filter(|info| info.vendor_id() == 0x054C) {
                println!(
                    "  pid {:04x} interface {}: {:?}  container {}",
                    info.product_id(),
                    info.interface_number(),
                    info.path(),
                    container_of_hid_path(info.path())
                        .map(|c| format!("{c:032x}"))
                        .unwrap_or_else(|| "none".to_owned()),
                );
            }
        }

        println!("pad speakers opened:");
        for pad in open_pad_speakers() {
            println!("  {pad:?}");
        }
    }
}