cpal 0.18.0

Low-level cross-platform audio I/O library.
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
use std::{
    cell::RefCell,
    rc::Rc,
    sync::{
        atomic::{AtomicBool, AtomicU64, Ordering},
        Arc, Mutex,
    },
    thread::JoinHandle,
    time::Instant,
};

use pipewire::{
    self as pw,
    context::ContextRc,
    core::{CoreRc, Listener as CoreListener, PW_ID_CORE},
    main_loop::MainLoopRc,
    metadata::{Metadata, MetadataListener},
    properties::PropertiesBox,
    registry::{Listener as RegistryListener, RegistryRc},
    spa::{
        param::{
            audio::{AudioFormat, AudioInfoRaw},
            format::{MediaSubtype, MediaType},
            format_utils, ParamType,
        },
        pod::{serialize::PodSerializer, Object, Pod, Value},
        utils::{Direction, SpaTypes},
    },
    stream::{StreamFlags, StreamListener, StreamRc, StreamState, Time},
    types::ObjectType,
};

use crate::{
    host::{
        emit_error, equilibrium::fill_equilibrium, frames_to_duration, latch::Latch,
        try_emit_error, ErrorCallbackArc,
    },
    traits::StreamTrait,
    Data, Error, ErrorKind, FrameCount, InputCallbackInfo, InputStreamTimestamp,
    OutputCallbackInfo, OutputStreamTimestamp, SampleFormat, StreamConfig, StreamInstant,
};

/// Counts the number of live [`PwInitGuard`] instances across all threads.
static PW_INIT_COUNT: Mutex<usize> = Mutex::new(0);

/// RAII guard that keeps the PipeWire library initialised for its lifetime.
pub(crate) struct PwInitGuard;

impl PwInitGuard {
    pub(crate) fn new() -> Self {
        let mut count = PW_INIT_COUNT.lock().unwrap_or_else(|e| e.into_inner());
        if *count == 0 {
            // pw::init() uses a OnceCell, preventing re-init after deinit.
            unsafe { pw::sys::pw_init(std::ptr::null_mut(), std::ptr::null_mut()) }
        }
        *count += 1;
        Self
    }
}

impl Drop for PwInitGuard {
    fn drop(&mut self) {
        let mut count = PW_INIT_COUNT.lock().unwrap_or_else(|e| e.into_inner());
        *count = count.saturating_sub(1);
        if *count == 0 {
            // Safety: the mutex ensures no other PwInitGuard exists at this
            // point. Every scope that creates PipeWire objects holds a guard
            // declared before those objects, so all PipeWire objects have
            // already been dropped before this decrement reached zero.
            unsafe { pw::deinit() }
        }
    }
}

pub(super) enum StreamCommand {
    Toggle(bool),
    Stop,
}

pub struct Stream {
    handle: Option<JoinHandle<()>>,
    controller: pw::channel::Sender<StreamCommand>,
    last_quantum: Arc<AtomicU64>,
    start: Instant,
    latch: Latch,
}

impl Stream {
    pub(super) fn new(
        handle: JoinHandle<()>,
        controller: pw::channel::Sender<StreamCommand>,
        last_quantum: Arc<AtomicU64>,
        start: Instant,
        latch: Latch,
    ) -> Self {
        Self {
            handle: Some(handle),
            controller,
            last_quantum,
            start,
            latch,
        }
    }

    /// Releases the latch so the worker thread can begin processing audio callbacks.
    pub fn signal_ready(&self) {
        self.latch.release();
    }
}

impl Drop for Stream {
    fn drop(&mut self) {
        // Unblock the worker in case the stream is dropped before signal_ready() was called.
        self.signal_ready();
        let _ = self.controller.send(StreamCommand::Stop);
        if let Some(handle) = self.handle.take() {
            // Prevent self-join: Stop was sent; the handle detaches and the thread exits after
            // the current callback returns.
            if handle.thread().id() != std::thread::current().id() {
                let _ = handle.join();
            }
        }
    }
}

impl StreamTrait for Stream {
    fn play(&self) -> Result<(), Error> {
        self.controller
            .send(StreamCommand::Toggle(true))
            .map_err(|_| {
                Error::with_message(
                    ErrorKind::StreamInvalidated,
                    "stream command channel closed",
                )
            })?;
        Ok(())
    }
    fn pause(&self) -> Result<(), Error> {
        self.controller
            .send(StreamCommand::Toggle(false))
            .map_err(|_| {
                Error::with_message(
                    ErrorKind::StreamInvalidated,
                    "stream command channel closed",
                )
            })?;
        Ok(())
    }

    fn now(&self) -> StreamInstant {
        monotonic_stream_instant().unwrap_or_else(|| stream_instant_from_start(self.start))
    }

    fn buffer_size(&self) -> Result<FrameCount, Error> {
        Ok(self.last_quantum.load(Ordering::Relaxed) as _)
    }
}

pub(crate) const SUPPORTED_FORMATS: &[SampleFormat] = &[
    SampleFormat::I8,
    SampleFormat::U8,
    SampleFormat::I16,
    SampleFormat::U16,
    SampleFormat::I24,
    SampleFormat::U24,
    SampleFormat::I32,
    SampleFormat::U32,
    // I64/U64 are excluded: libspa has no mapping for them yet.
    // SampleFormat::I64,
    // SampleFormat::U64,
    SampleFormat::F32,
    SampleFormat::F64,
];

impl From<SampleFormat> for AudioFormat {
    fn from(value: SampleFormat) -> Self {
        match value {
            SampleFormat::I8 => Self::S8,
            SampleFormat::U8 => Self::U8,

            #[cfg(target_endian = "little")]
            SampleFormat::I16 => Self::S16LE,
            #[cfg(target_endian = "big")]
            SampleFormat::I16 => Self::S16BE,
            #[cfg(target_endian = "little")]
            SampleFormat::U16 => Self::U16LE,
            #[cfg(target_endian = "big")]
            SampleFormat::U16 => Self::U16BE,

            #[cfg(target_endian = "little")]
            SampleFormat::I24 => Self::S24LE,
            #[cfg(target_endian = "big")]
            SampleFormat::I24 => Self::S24BE,
            #[cfg(target_endian = "little")]
            SampleFormat::U24 => Self::U24LE,
            #[cfg(target_endian = "big")]
            SampleFormat::U24 => Self::U24BE,
            #[cfg(target_endian = "little")]
            SampleFormat::I32 => Self::S32LE,
            #[cfg(target_endian = "big")]
            SampleFormat::I32 => Self::S32BE,
            #[cfg(target_endian = "little")]
            SampleFormat::U32 => Self::U32LE,
            #[cfg(target_endian = "big")]
            SampleFormat::U32 => Self::U32BE,
            #[cfg(target_endian = "little")]
            SampleFormat::F32 => Self::F32LE,
            #[cfg(target_endian = "big")]
            SampleFormat::F32 => Self::F32BE,
            #[cfg(target_endian = "little")]
            SampleFormat::F64 => Self::F64LE,
            #[cfg(target_endian = "big")]
            SampleFormat::F64 => Self::F64BE,
            // NOTE: Seems PipeWire does support U64 and I64, but libspa doesn't yet.
            // TODO: Maybe add the support in the future
            _ => Self::Unknown,
        }
    }
}

pub struct UserData<D> {
    data_callback: D,
    error_callback: ErrorCallbackArc,
    sample_format: SampleFormat,
    format: AudioInfoRaw,
    last_quantum: Arc<AtomicU64>,
    start: Instant,
    is_default_device: Arc<AtomicBool>,
    has_connected: bool,
    invalidated: Arc<AtomicBool>,
    pending_device_changed: Arc<AtomicBool>,
    #[cfg(feature = "realtime")]
    rt_promoted: bool,
}

impl<D> UserData<D> {
    // `#[cold]` because it only runs on the first cycle and whenever PipeWire renegotiates the graph quantum.
    #[cfg(feature = "realtime")]
    #[cold]
    fn promote_realtime(&mut self, frames: FrameCount) {
        // Set regardless of success, so a failed promotion isn't retried until the quantum changes.
        self.rt_promoted = true;
        if let Err(e) =
            audio_thread_priority::promote_current_thread_to_real_time(frames, self.format.rate())
        {
            let _ = try_emit_error(&self.error_callback, Error::from(e));
        }
    }

    fn state_changed(&mut self, new: StreamState) {
        match new {
            StreamState::Streaming => self.has_connected = true,
            StreamState::Unconnected => {
                // Let the metadata monitor fire for default-device streams
                if self.has_connected
                    && !self.is_default_device.load(Ordering::Relaxed)
                    && !self.invalidated.swap(true, Ordering::Relaxed)
                {
                    emit_error(
                        &self.error_callback,
                        Error::with_message(ErrorKind::DeviceNotAvailable, "Device disconnected"),
                    );
                }
            }
            StreamState::Error(e) => {
                if !self.invalidated.swap(true, Ordering::Relaxed) {
                    emit_error(
                        &self.error_callback,
                        Error::with_message(ErrorKind::StreamInvalidated, e),
                    );
                }
            }
            StreamState::Paused | StreamState::Connecting => {}
        }
    }
}

/// Returns a hardware timestamp for the current graph cycle, or `None` if
/// the driver has not started yet or the rate is unavailable.
fn pw_stream_time(stream: &pw::stream::Stream) -> Option<Time> {
    let t = stream.time().ok()?;
    if t.now() <= 0 || t.rate().denom == 0 {
        return None;
    }
    debug_assert_eq!(t.rate().num, 1, "unexpected pw_time rate.num");
    Some(t)
}

impl<D> UserData<D>
where
    D: FnMut(&Data, &InputCallbackInfo) + Send + 'static,
{
    fn publish_data_in(&mut self, stream: &pw::stream::Stream, frames: usize, data: &Data) {
        #[cfg(feature = "realtime")]
        {
            let prev = self.last_quantum.swap(frames as u64, Ordering::Relaxed);
            if !self.rt_promoted || frames as u64 != prev {
                self.promote_realtime(frames as FrameCount);
            }
        }

        #[cfg(not(feature = "realtime"))]
        self.last_quantum.store(frames as u64, Ordering::Relaxed);

        let (callback, capture) = match pw_stream_time(stream) {
            Some(t) => {
                let delay_ns = t.delay() * 1_000_000_000i64 / t.rate().denom as i64;
                (
                    StreamInstant::from_nanos(t.now() as u64),
                    StreamInstant::from_nanos((t.now() - delay_ns.max(0)) as u64),
                )
            }
            None => {
                let cb = monotonic_stream_instant()
                    .unwrap_or_else(|| stream_instant_from_start(self.start));
                let capture = cb
                    .checked_sub(frames_to_duration(frames as FrameCount, self.format.rate()))
                    .unwrap_or(StreamInstant::ZERO);
                (cb, capture)
            }
        };
        let timestamp = InputStreamTimestamp { callback, capture };
        let info = InputCallbackInfo { timestamp };
        (self.data_callback)(data, &info);
    }
}

impl<D> UserData<D>
where
    D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static,
{
    fn publish_data_out(&mut self, stream: &pw::stream::Stream, frames: usize, data: &mut Data) {
        #[cfg(feature = "realtime")]
        {
            let prev = self.last_quantum.swap(frames as u64, Ordering::Relaxed);
            if !self.rt_promoted || frames as u64 != prev {
                self.promote_realtime(frames as FrameCount);
            }
        }

        #[cfg(not(feature = "realtime"))]
        self.last_quantum.store(frames as u64, Ordering::Relaxed);

        let (callback, playback) = match pw_stream_time(stream) {
            Some(t) => {
                let delay_ns = t.delay() * 1_000_000_000i64 / t.rate().denom as i64;
                (
                    StreamInstant::from_nanos(t.now() as u64),
                    StreamInstant::from_nanos((t.now() + delay_ns.max(0)) as u64),
                )
            }
            None => {
                let cb = monotonic_stream_instant()
                    .unwrap_or_else(|| stream_instant_from_start(self.start));
                let pl = cb + frames_to_duration(frames as FrameCount, self.format.rate());
                (cb, pl)
            }
        };
        let timestamp = OutputStreamTimestamp { callback, playback };
        let info = OutputCallbackInfo { timestamp };
        (self.data_callback)(data, &info);
    }
}

pub struct StreamData<D> {
    pub mainloop: MainLoopRc,
    pub listener: StreamListener<UserData<D>>,
    pub stream: StreamRc,
    pub context: ContextRc,
    pub core: CoreRc,
    pub core_monitor: CoreListener,
    pub error_callback: ErrorCallbackArc,
    pub pending_device_changed: Arc<AtomicBool>,
    pub invalidated: Arc<AtomicBool>,
    pub is_default_device: Arc<AtomicBool>,
}

/// Fallback timestamp using elapsed time since stream creation.
fn stream_instant_from_start(start: Instant) -> StreamInstant {
    let elapsed = start.elapsed();
    StreamInstant::new(elapsed.as_secs(), elapsed.subsec_nanos())
}

/// Read `clock_gettime` and return it as a [`StreamInstant`].
///
/// This is the same clock source used by `pw_stream_get_time_n`, so values returned
/// here are directly comparable with the `callback`/`capture`/`playback` instants
/// delivered to the data callback.
fn monotonic_stream_instant() -> Option<StreamInstant> {
    let mut ts = libc::timespec {
        tv_sec: 0,
        tv_nsec: 0,
    };
    let rc = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
    if rc == 0 {
        Some(StreamInstant::new(ts.tv_sec as u64, ts.tv_nsec as u32))
    } else {
        None
    }
}

fn remote_props() -> Option<PropertiesBox> {
    let socket = super::utils::find_socket_path()?;
    let mut props = PropertiesBox::new();
    props.insert(*pw::keys::REMOTE_NAME, socket.to_string_lossy().as_ref());
    Some(props)
}

/// Holds the metadata proxy and its listener alive for the duration of the stream, so that
/// default-device changes are delivered via `error_callback`.
struct MetadataObjects {
    _listener: MetadataListener,
    _metadata: Metadata,
}

pub struct DefaultDeviceMonitor {
    _registry: RegistryRc,
    _registry_listener: RegistryListener,
    _meta_objects: Rc<RefCell<Option<MetadataObjects>>>,
}

impl DefaultDeviceMonitor {
    /// Subscribe to the `"default"` metadata object and fire `error_callback` with
    /// [`ErrorKind::DeviceChanged`] whenever its key changes.
    pub(super) fn new(
        registry: RegistryRc,
        key: &'static str,
        error_callback: ErrorCallbackArc,
        invalidated: Arc<AtomicBool>,
        pending_device_changed: Arc<AtomicBool>,
    ) -> Self {
        let meta_objects: Rc<RefCell<Option<MetadataObjects>>> = Rc::new(RefCell::new(None));
        let meta_objects_ref = meta_objects.clone();
        let registry_ref = registry.clone();

        let registry_listener = registry
            .add_listener_local()
            .global(move |global| {
                if global.type_ != ObjectType::Metadata {
                    return;
                }
                if !global.props.is_some_and(|props| {
                    props
                        .get(super::utils::METADATA_NAME)
                        .is_some_and(|v| v == super::utils::default::NAME)
                }) {
                    return;
                }
                let metadata: Metadata = match registry_ref.bind(global) {
                    Ok(m) => m,
                    Err(e) => {
                        emit_error(
                            &error_callback,
                            Error::with_message(
                                ErrorKind::BackendError,
                                format!("PipeWire: failed to bind metadata object; device change notifications may be incomplete: {e}"),
                            ),
                        );
                        return;
                    }
                };
                let error_callback_cb = error_callback.clone();
                let invalidated_cb = invalidated.clone();
                let pending_device_changed_cb = pending_device_changed.clone();

                let last_value: RefCell<Option<Option<String>>> = RefCell::new(None);
                let listener = metadata
                    .add_listener_local()
                    .property(move |_subject, prop_key, _type, value| {
                        if prop_key == Some(key) {
                            let prev = last_value.borrow_mut().replace(value.map(str::to_owned));
                            if let Some(old) = prev {
                                if old.as_deref() != value {
                                    if value.is_some() {
                                        if try_emit_error(
                                            &error_callback_cb,
                                            Error::with_message(
                                                ErrorKind::DeviceChanged,
                                                "default device changed",
                                            ),
                                        )
                                        .is_err()
                                        {
                                            pending_device_changed_cb
                                                .store(true, Ordering::Relaxed);
                                        }
                                    } else if !invalidated_cb.swap(true, Ordering::Relaxed) {
                                        emit_error(
                                            &error_callback_cb,
                                            Error::with_message(
                                                ErrorKind::DeviceNotAvailable,
                                                "default device removed",
                                            ),
                                        );
                                    }
                                }
                            }
                        }
                        0
                    })
                    .register();
                *meta_objects_ref.borrow_mut() = Some(MetadataObjects {
                    _listener: listener,
                    _metadata: metadata,
                });
            })
            .register();

        DefaultDeviceMonitor {
            _registry: registry,
            _registry_listener: registry_listener,
            _meta_objects: meta_objects,
        }
    }
}

pub struct ConnectParams {
    pub config: StreamConfig,
    pub properties: PropertiesBox,
    pub sample_format: SampleFormat,
    pub last_quantum: Arc<AtomicU64>,
    pub start: Instant,
    pub connect_automatically: bool,
}

pub fn connect_output<D, E>(
    params: ConnectParams,
    data_callback: D,
    error_callback: E,
) -> Result<StreamData<D>, pw::Error>
where
    D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static,
    E: FnMut(Error) + Send + 'static,
{
    let ConnectParams {
        config,
        properties,
        sample_format,
        last_quantum,
        start,
        connect_automatically,
    } = params;

    let mainloop = MainLoopRc::new(None)?;
    let context = ContextRc::new(&mainloop, None)?;
    let core = context.connect_rc(remote_props())?;

    let error_callback: ErrorCallbackArc = Arc::new(Mutex::new(error_callback));
    let invalidated = Arc::new(AtomicBool::new(false));

    let pending_device_changed = Arc::new(AtomicBool::new(false));
    let is_default_device = Arc::new(AtomicBool::new(false));

    let core_monitor = {
        let invalidated_core = invalidated.clone();
        let error_callback_core = error_callback.clone();
        core.add_listener_local()
            .error(move |id, _seq, _res, message| {
                if id == PW_ID_CORE && !invalidated_core.swap(true, Ordering::Relaxed) {
                    emit_error(
                        &error_callback_core,
                        Error::with_message(
                            ErrorKind::StreamInvalidated,
                            format!("PipeWire server error: {message}"),
                        ),
                    );
                }
            })
            .register()
    };

    let error_callback_out = error_callback.clone();
    let data = UserData {
        data_callback,
        error_callback,
        sample_format,
        format: Default::default(),
        last_quantum,
        start,
        invalidated: invalidated.clone(),
        is_default_device: is_default_device.clone(),
        has_connected: false,
        pending_device_changed: pending_device_changed.clone(),
        #[cfg(feature = "realtime")]
        rt_promoted: false,
    };
    let channels = config.channels as _;
    let rate = config.sample_rate as _;
    let stream = StreamRc::new(
        core.clone(),
        &format!("cpal-playback-{}", std::process::id()),
        properties,
    )?;

    let listener = stream
        .add_local_listener_with_user_data(data)
        .param_changed(move |stream, user_data, id, param| {
            let Some(param) = param else {
                return;
            };
            if id != ParamType::Format.as_raw() {
                return;
            }

            let (media_type, media_subtype) = match format_utils::parse_format(param) {
                Ok(v) => v,
                Err(_) => return,
            };

            // only accept raw audio
            if media_type != MediaType::Audio || media_subtype != MediaSubtype::Raw {
                return;
            }
            // call a helper function to parse the format for us.
            // When the format update, we check the format first, in case it does not fit what we
            // set
            match user_data.format.parse(param) {
                Ok(_) => {
                    let current_channels = user_data.format.channels();
                    let current_rate = user_data.format.rate();
                    let expected_fmt =
                        AudioFormat::from(user_data.sample_format);
                    let current_fmt = user_data.format.format();
                    let mismatch = current_channels != channels
                        || current_rate != rate
                        || current_fmt != expected_fmt;
                    if mismatch && !user_data.invalidated.swap(true, Ordering::Relaxed) {
                        let fmt_note = if current_fmt != expected_fmt {
                            "; sample format differs"
                        } else {
                            ""
                        };
                        emit_error(
                            &user_data.error_callback,
                            Error::with_message(
                                ErrorKind::UnsupportedConfig,
                                format!("Negotiated format mismatch: expected {channels} channels at {rate} Hz, got {current_channels} channels at {current_rate} Hz{fmt_note}"),
                            ),
                        );
                        if let Err(e) = stream.set_active(false) {
                            emit_error(
                                &user_data.error_callback,
                                Error::with_message(
                                    ErrorKind::StreamInvalidated,
                                    format!("PipeWire: failed to stop stream: {e}"),
                                ),
                            );
                        }
                    }
                }
                Err(e) => {
                    if !user_data.invalidated.swap(true, Ordering::Relaxed) {
                        emit_error(
                            &user_data.error_callback,
                            Error::with_message(
                                ErrorKind::StreamInvalidated,
                                format!("PipeWire: failed to parse negotiated audio format: {e}"),
                            ),
                        );
                        if let Err(e) = stream.set_active(false) {
                            emit_error(
                                &user_data.error_callback,
                                Error::with_message(
                                    ErrorKind::StreamInvalidated,
                                    format!("PipeWire: failed to stop stream: {e}"),
                                ),
                            );
                        }
                    }
                }
            }
        })
        .state_changed(|_stream, user_data, _old, new| {
            user_data.state_changed(new);
        })
        .process(|stream, user_data| {
            if user_data.pending_device_changed.load(Ordering::Relaxed)
                && try_emit_error(
                    &user_data.error_callback,
                    Error::with_message(ErrorKind::DeviceChanged, "Default device changed"),
                )
                .is_ok()
            {
                user_data.pending_device_changed.store(false, Ordering::Relaxed);
            }

            let n_channels = user_data.format.channels();
            if n_channels == 0 {
                return; // format not yet negotiated by param_changed
            }

            if let Some(mut buffer) = stream.dequeue_buffer() {
                // Read the requested frame count before mutably borrowing datas_mut().
                let requested = buffer.requested() as usize;
                let datas = buffer.datas_mut();
                if datas.is_empty() {
                    return;
                }
                let buf_data = &mut datas[0];

                let stride = user_data.sample_format.sample_size() * n_channels as usize;
                // frames = samples / channels or frames = data_len / stride
                // Honor the frame count PipeWire requests this cycle, capped by the
                // mapped buffer capacity to guard against any mismatch.
                let frames = requested.min(buf_data.as_raw().maxsize as usize / stride);
                let Some(samples) = buf_data.data() else {
                    return;
                };

                // samples = frames * channels or samples = data_len / sample_size
                let n_samples = frames * n_channels as usize;

                // Pre-fill only the active region with equilibrium before handing it to the
                // callback.
                let active = &mut samples[..frames * stride];
                fill_equilibrium(active, user_data.sample_format);

                let data = active.as_mut_ptr() as *mut ();
                let mut data =
                    unsafe { Data::from_parts(data, n_samples, user_data.sample_format) };
                user_data.publish_data_out(stream, frames, &mut data);
                let chunk = buf_data.chunk_mut();
                *chunk.offset_mut() = 0;
                *chunk.stride_mut() = stride as i32;
                *chunk.size_mut() = (frames * stride) as u32;
            }
        })
        .register()?;
    let mut audio_info = AudioInfoRaw::new();
    audio_info.set_format(sample_format.into());
    audio_info.set_rate(rate);
    audio_info.set_channels(channels);

    let obj = Object {
        type_: SpaTypes::ObjectParamFormat.as_raw(),
        id: ParamType::EnumFormat.as_raw(),
        properties: audio_info.into(),
    };
    let values: Vec<u8> =
        PodSerializer::serialize(std::io::Cursor::new(Vec::new()), &Value::Object(obj))
            .unwrap()
            .0
            .into_inner();

    let mut params = [Pod::from_bytes(&values).unwrap()];

    // RT_PROCESS is intentionally absent: with add_local_listener the process callback always
    // runs on this mainloop thread, not the separate data-loop thread RT_PROCESS creates.
    // That thread promotes itself to RT from the process callback, once when the negotiated
    // quantum is known and again whenever PipeWire renegotiates it.
    let mut flags = StreamFlags::MAP_BUFFERS;
    if connect_automatically {
        flags |= StreamFlags::AUTOCONNECT;
    }

    stream.connect(Direction::Output, None, flags, &mut params)?;

    Ok(StreamData {
        mainloop,
        listener,
        stream,
        context,
        core,
        core_monitor,
        error_callback: error_callback_out,
        pending_device_changed,
        invalidated,
        is_default_device,
    })
}

pub fn connect_input<D, E>(
    params: ConnectParams,
    data_callback: D,
    error_callback: E,
) -> Result<StreamData<D>, pw::Error>
where
    D: FnMut(&Data, &InputCallbackInfo) + Send + 'static,
    E: FnMut(Error) + Send + 'static,
{
    let ConnectParams {
        config,
        properties,
        sample_format,
        last_quantum,
        start,
        connect_automatically,
    } = params;

    let mainloop = MainLoopRc::new(None)?;
    let context = ContextRc::new(&mainloop, None)?;
    let core = context.connect_rc(remote_props())?;

    let error_callback: ErrorCallbackArc = Arc::new(Mutex::new(error_callback));
    let invalidated = Arc::new(AtomicBool::new(false));

    let pending_device_changed = Arc::new(AtomicBool::new(false));
    let is_default_device = Arc::new(AtomicBool::new(false));

    let core_monitor = {
        let invalidated_core = invalidated.clone();
        let error_callback_core = error_callback.clone();
        core.add_listener_local()
            .error(move |id, _seq, _res, message| {
                if id == PW_ID_CORE && !invalidated_core.swap(true, Ordering::Relaxed) {
                    emit_error(
                        &error_callback_core,
                        Error::with_message(
                            ErrorKind::StreamInvalidated,
                            format!("PipeWire server error: {message}"),
                        ),
                    );
                }
            })
            .register()
    };

    let error_callback_out = error_callback.clone();
    let data = UserData {
        data_callback,
        error_callback,
        sample_format,
        format: Default::default(),
        last_quantum,
        start,
        invalidated: invalidated.clone(),
        is_default_device: is_default_device.clone(),
        has_connected: false,
        pending_device_changed: pending_device_changed.clone(),
        #[cfg(feature = "realtime")]
        rt_promoted: false,
    };

    let channels = config.channels as _;
    let rate = config.sample_rate as _;
    let stream = StreamRc::new(
        core.clone(),
        &format!("cpal-capture-{}", std::process::id()),
        properties,
    )?;
    let listener = stream
        .add_local_listener_with_user_data(data)
        .param_changed(move |stream, user_data, id, param| {
            let Some(param) = param else {
                return;
            };
            if id != ParamType::Format.as_raw() {
                return;
            }

            let (media_type, media_subtype) = match format_utils::parse_format(param) {
                Ok(v) => v,
                Err(_) => return,
            };

            // only accept raw audio
            if media_type != MediaType::Audio || media_subtype != MediaSubtype::Raw {
                return;
            }

            // call a helper function to parse the format for us.
            // When the format update, we check the format first, in case it does not fit what we
            // set
            match user_data.format.parse(param) {
                Ok(_) => {
                    let current_channels = user_data.format.channels();
                    let current_rate = user_data.format.rate();
                    let expected_fmt =
                        AudioFormat::from(user_data.sample_format);
                    let current_fmt = user_data.format.format();
                    let mismatch = current_channels != channels
                        || current_rate != rate
                        || current_fmt != expected_fmt;
                    if mismatch && !user_data.invalidated.swap(true, Ordering::Relaxed) {
                        let fmt_note = if current_fmt != expected_fmt {
                            "; sample format differs"
                        } else {
                            ""
                        };
                        emit_error(
                            &user_data.error_callback,
                            Error::with_message(
                                ErrorKind::UnsupportedConfig,
                                format!("Negotiated format mismatch: expected {channels} channels at {rate} Hz, got {current_channels} channels at {current_rate} Hz{fmt_note}"),
                            ),
                        );
                        if let Err(e) = stream.set_active(false) {
                            emit_error(
                                &user_data.error_callback,
                                Error::with_message(
                                    ErrorKind::StreamInvalidated,
                                    format!("PipeWire: failed to stop stream: {e}"),
                                ),
                            );
                        }
                    }
                }
                Err(e) => {
                    if !user_data.invalidated.swap(true, Ordering::Relaxed) {
                        emit_error(
                            &user_data.error_callback,
                            Error::with_message(
                                ErrorKind::StreamInvalidated,
                                format!("PipeWire: failed to parse negotiated audio format: {e}"),
                            ),
                        );
                        if let Err(e) = stream.set_active(false) {
                            emit_error(
                                &user_data.error_callback,
                                Error::with_message(
                                    ErrorKind::StreamInvalidated,
                                    format!("PipeWire: failed to stop stream: {e}"),
                                ),
                            );
                        }
                    }
                }
            }
        })
        .state_changed(|_stream, user_data, _old, new| {
            user_data.state_changed(new);
        })
        .process(|stream, user_data| {
            if user_data.pending_device_changed.load(Ordering::Relaxed)
                && try_emit_error(
                    &user_data.error_callback,
                    Error::with_message(ErrorKind::DeviceChanged, "Default device changed"),
                )
                .is_ok()
            {
                user_data.pending_device_changed.store(false, Ordering::Relaxed);
            }

            let n_channels = user_data.format.channels();
            if n_channels == 0 {
                return; // format not yet negotiated by param_changed
            }

            if let Some(mut buffer) = stream.dequeue_buffer() {
                let datas = buffer.datas_mut();
                if datas.is_empty() {
                    return;
                }
                let data = &mut datas[0];
                let n_samples = data.chunk().size() / user_data.sample_format.sample_size() as u32;
                let frames = n_samples / n_channels;

                let Some(samples) = data.data() else {
                    return;
                };
                let data = samples.as_mut_ptr() as *mut ();
                let data =
                    unsafe { Data::from_parts(data, n_samples as usize, user_data.sample_format) };
                user_data.publish_data_in(stream, frames as usize, &data);
            }
        })
        .register()?;
    let mut audio_info = AudioInfoRaw::new();
    audio_info.set_format(sample_format.into());
    audio_info.set_rate(rate);
    audio_info.set_channels(channels);

    let obj = Object {
        type_: SpaTypes::ObjectParamFormat.as_raw(),
        id: ParamType::EnumFormat.as_raw(),
        properties: audio_info.into(),
    };
    let values: Vec<u8> =
        PodSerializer::serialize(std::io::Cursor::new(Vec::new()), &Value::Object(obj))
            .unwrap()
            .0
            .into_inner();

    let mut params = [Pod::from_bytes(&values).unwrap()];

    // RT_PROCESS is intentionally absent: with add_local_listener the process callback always
    // runs on this mainloop thread, not the separate data-loop thread RT_PROCESS creates.
    // That thread promotes itself to RT from the process callback, once when the negotiated
    // quantum is known and again whenever PipeWire renegotiates it.
    let mut flags = StreamFlags::MAP_BUFFERS;
    if connect_automatically {
        flags |= StreamFlags::AUTOCONNECT;
    }

    stream.connect(Direction::Input, None, flags, &mut params)?;

    Ok(StreamData {
        mainloop,
        listener,
        stream,
        context,
        core,
        core_monitor,
        error_callback: error_callback_out,
        pending_device_changed,
        invalidated,
        is_default_device,
    })
}