dioxus-audio 0.2.1

Audio recording, playback, analysis, and UI components for Dioxus
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
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
//! Audio recording state and hooks.

use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;
use std::time::Duration;

use dioxus::prelude::*;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
use wasm_bindgen::JsCast;

use crate::AudioError;
use crate::analysis::AudioAnalyser;
use crate::devices::MicrophonePermission;
use crate::{AudioInputId, RecordedAudio, RecordingChunk, RecordingId};

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
mod web;

/// An opaque, application-supplied live audio source.
///
/// Recorder snapshots exactly one live audio track and its shutdown agreement
/// when [`AudioRecorder::start_with_source`] accepts a Recording. The default
/// agreement preserves the track.
#[derive(Clone)]
pub struct RecordingSource {
    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    stream: web_sys::MediaStream,
    shutdown: RecordingSourceShutdown,
    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    _unsupported: (),
}

impl fmt::Debug for RecordingSource {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RecordingSource")
            .field("shutdown", &self.shutdown)
            .finish_non_exhaustive()
    }
}

/// Authority granted to Recorder for an accepted supplied Recording Source.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RecordingSourceShutdown {
    /// Leave the accepted audio track under application control.
    #[default]
    PreserveTracks,
    /// Stop the accepted audio track when Recorder cleans up the Recording.
    ///
    /// Stopping a shared track affects every consumer of that track.
    StopAudioTracks,
}

/// Browser-reported availability of the accepted Recording Source.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RecordingSourceAvailability {
    Live,
    Interrupted,
}

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
impl RecordingSource {
    /// Wrap a browser media stream as a preserved Recording Source.
    ///
    /// The raw stream remains application-owned and is not exposed again by
    /// Recorder. Source validation occurs when a Recording is started.
    pub fn from_media_stream(stream: &web_sys::MediaStream) -> Self {
        Self {
            stream: <web_sys::MediaStream as AsRef<wasm_bindgen::JsValue>>::as_ref(stream)
                .clone()
                .unchecked_into(),
            shutdown: RecordingSourceShutdown::PreserveTracks,
        }
    }

    /// Set the shutdown authority snapshotted when Recorder accepts a start.
    pub fn with_shutdown(mut self, shutdown: RecordingSourceShutdown) -> Self {
        self.shutdown = shutdown;
        self
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RecorderStatus {
    Idle,
    Preparing,
    Recording,
    Paused,
    Stopping,
    Failed(AudioError),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CompletionDisposition {
    Save,
    Discard,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RecordingTerminalIntent {
    Save(RecordingCompletionCause),
    Discard,
}

impl RecordingTerminalIntent {
    fn disposition(self) -> CompletionDisposition {
        match self {
            Self::Save(_) => CompletionDisposition::Save,
            Self::Discard => CompletionDisposition::Discard,
        }
    }

    fn completion_cause(self) -> Option<RecordingCompletionCause> {
        match self {
            Self::Save(cause) => Some(cause),
            Self::Discard => None,
        }
    }
}

/// Why a Recording completed with Recorded Audio.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RecordingCompletionCause {
    /// The application requested completion.
    Requested,
    /// The accepted Recording Source ended externally.
    SourceEnded,
    /// The Recording ended without an earlier application or source intent.
    UnexpectedEnd,
}

/// The terminal outcome of an accepted Recording.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RecordingOutcome {
    Completed {
        recording_id: RecordingId,
        cause: RecordingCompletionCause,
    },
    Discarded(RecordingId),
    Failed {
        recording_id: RecordingId,
        error: AudioError,
    },
}

impl RecordingOutcome {
    pub fn recording_id(&self) -> RecordingId {
        match self {
            Self::Completed { recording_id, .. } | Self::Discarded(recording_id) => *recording_id,
            Self::Failed { recording_id, .. } => *recording_id,
        }
    }
}

/// The terminal failure of incremental Recording Chunk delivery.
///
/// Capture and final Recorded Audio assembly continue independently after this
/// failure, but this Recording will deliver no later chunks.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RecordingChunkDeliveryFailure {
    recording_id: RecordingId,
    failed_sequence: u64,
    error: AudioError,
}

impl RecordingChunkDeliveryFailure {
    pub fn recording_id(&self) -> RecordingId {
        self.recording_id
    }

    pub fn failed_sequence(&self) -> u64 {
        self.failed_sequence
    }

    pub fn error(&self) -> &AudioError {
        &self.error
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RecorderCommandError {
    message: &'static str,
}

impl RecorderCommandError {
    pub fn message(&self) -> &'static str {
        self.message
    }
}

impl fmt::Display for RecorderCommandError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.message)
    }
}

impl std::error::Error for RecorderCommandError {}

#[derive(Debug)]
pub struct RecorderLifecycle {
    status: RecorderStatus,
    generation: u64,
    active_recording: Option<RecordingId>,
    next_chunk_sequence: u64,
    terminal_intent: RecordingTerminalIntent,
    finalizing: bool,
    has_unconsumed_recording: bool,
}

impl Default for RecorderLifecycle {
    fn default() -> Self {
        Self {
            status: RecorderStatus::Idle,
            generation: 0,
            active_recording: None,
            next_chunk_sequence: 0,
            terminal_intent: RecordingTerminalIntent::Save(RecordingCompletionCause::Requested),
            finalizing: false,
            has_unconsumed_recording: false,
        }
    }
}

impl RecorderLifecycle {
    pub fn status(&self) -> &RecorderStatus {
        &self.status
    }

    pub fn start(&mut self) -> Result<RecordingId, RecorderCommandError> {
        if self.has_unconsumed_recording {
            return Err(command_error(
                "clear the completed recording before starting another",
            ));
        }
        if !matches!(
            self.status,
            RecorderStatus::Idle | RecorderStatus::Failed(_)
        ) {
            return Err(command_error("recording is already active"));
        }

        self.generation = self.generation.wrapping_add(1);
        let recording_id = RecordingId::from_generation(self.generation);
        self.active_recording = Some(recording_id);
        self.next_chunk_sequence = 0;
        self.terminal_intent = RecordingTerminalIntent::Save(RecordingCompletionCause::Requested);
        self.finalizing = false;
        self.status = RecorderStatus::Preparing;
        Ok(recording_id)
    }

    pub fn started(&mut self, recording_id: RecordingId) -> bool {
        if self.active_recording == Some(recording_id)
            && matches!(self.status, RecorderStatus::Preparing)
        {
            self.status = RecorderStatus::Recording;
            true
        } else {
            false
        }
    }

    pub fn stop(&mut self) -> Result<(), RecorderCommandError> {
        if !matches!(
            self.status,
            RecorderStatus::Recording | RecorderStatus::Paused
        ) {
            return Err(command_error(
                "recording cannot be stopped in its current state",
            ));
        }

        self.terminal_intent = RecordingTerminalIntent::Save(RecordingCompletionCause::Requested);
        self.status = RecorderStatus::Stopping;
        Ok(())
    }

    /// Accept external Recording Source completion as the terminal intent.
    pub fn source_ended(&mut self) -> bool {
        if !matches!(
            self.status,
            RecorderStatus::Recording | RecorderStatus::Paused
        ) {
            return false;
        }

        self.terminal_intent = RecordingTerminalIntent::Save(RecordingCompletionCause::SourceEnded);
        self.status = RecorderStatus::Stopping;
        true
    }

    pub fn completion_cause(&self, recording_id: RecordingId) -> Option<RecordingCompletionCause> {
        (self.active_recording == Some(recording_id))
            .then(|| self.terminal_intent.completion_cause())
            .flatten()
    }

    pub fn pause(&mut self) -> Result<(), RecorderCommandError> {
        if !matches!(self.status, RecorderStatus::Recording) {
            return Err(command_error("recording can only be paused while active"));
        }
        self.status = RecorderStatus::Paused;
        Ok(())
    }

    pub fn resume(&mut self) -> Result<(), RecorderCommandError> {
        if !matches!(self.status, RecorderStatus::Paused) {
            return Err(command_error("recording can only be resumed while paused"));
        }
        self.status = RecorderStatus::Recording;
        Ok(())
    }

    pub fn request_chunk_boundary(&self) -> Result<(), RecorderCommandError> {
        if !matches!(
            self.status,
            RecorderStatus::Recording | RecorderStatus::Paused
        ) {
            return Err(command_error(
                "a chunk boundary can only be requested while recording or paused",
            ));
        }
        Ok(())
    }

    /// Reserve the next contiguous sequence for a non-empty Recording Chunk.
    pub fn next_chunk_sequence(&mut self, recording_id: RecordingId) -> Option<u64> {
        let accepts_chunk = self.active_recording == Some(recording_id)
            && !self.finalizing
            && (matches!(
                self.status,
                RecorderStatus::Recording | RecorderStatus::Paused
            ) || (matches!(self.status, RecorderStatus::Stopping)
                && matches!(self.terminal_intent, RecordingTerminalIntent::Save(_))));
        if !accepts_chunk {
            return None;
        }

        let sequence = self.next_chunk_sequence;
        self.next_chunk_sequence = self.next_chunk_sequence.checked_add(1)?;
        Some(sequence)
    }

    pub fn cancel(&mut self) -> Result<(), RecorderCommandError> {
        match self.status {
            RecorderStatus::Preparing => {
                self.active_recording = None;
                self.status = RecorderStatus::Idle;
            }
            RecorderStatus::Recording | RecorderStatus::Paused => {
                self.terminal_intent = RecordingTerminalIntent::Discard;
                self.status = RecorderStatus::Stopping;
            }
            _ => {
                return Err(command_error(
                    "recording cannot be cancelled in its current state",
                ));
            }
        }

        Ok(())
    }

    pub fn begin_finalize(&mut self, recording_id: RecordingId) -> Option<CompletionDisposition> {
        if self.active_recording != Some(recording_id) || self.finalizing {
            return None;
        }

        match self.status {
            RecorderStatus::Stopping => {}
            RecorderStatus::Recording | RecorderStatus::Paused => {
                self.terminal_intent =
                    RecordingTerminalIntent::Save(RecordingCompletionCause::UnexpectedEnd);
                self.status = RecorderStatus::Stopping;
            }
            _ => return None,
        }

        self.finalizing = true;
        Some(self.terminal_intent.disposition())
    }

    pub fn complete_finalize(&mut self, recording_id: RecordingId) -> bool {
        if self.active_recording != Some(recording_id) || !self.finalizing {
            return false;
        }

        self.active_recording = None;
        self.finalizing = false;
        self.has_unconsumed_recording =
            matches!(self.terminal_intent, RecordingTerminalIntent::Save(_));
        self.status = RecorderStatus::Idle;
        true
    }

    pub fn clear_completed(&mut self) {
        self.has_unconsumed_recording = false;
    }

    pub fn failed(&mut self, recording_id: RecordingId, error: AudioError) -> bool {
        if self.active_recording != Some(recording_id) {
            return false;
        }

        self.active_recording = None;
        self.finalizing = false;
        self.status = RecorderStatus::Failed(error);
        true
    }

    pub fn configuration_failed(&mut self, error: AudioError) -> bool {
        if self.active_recording.is_some()
            || !matches!(
                self.status,
                RecorderStatus::Idle | RecorderStatus::Failed(_)
            )
        {
            return false;
        }
        self.status = RecorderStatus::Failed(error);
        true
    }

    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    fn abandon(&mut self) {
        self.active_recording = None;
        self.finalizing = false;
    }
}

fn command_error(message: &'static str) -> RecorderCommandError {
    RecorderCommandError { message }
}

/// A best-effort or required value requested for a Recording Source.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RecordingConstraint<T> {
    /// Prefer this value while allowing the browser to select another.
    Ideal(T),
    /// Require this value or reject source acquisition.
    Exact(T),
}

/// Portable startup constraints applied when the Recorder acquires a source.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RecordingConstraints {
    pub channel_count: Option<RecordingConstraint<u32>>,
    pub sample_rate: Option<RecordingConstraint<u32>>,
    pub echo_cancellation: Option<RecordingConstraint<bool>>,
    pub noise_suppression: Option<RecordingConstraint<bool>>,
    pub latency: Option<RecordingConstraint<Duration>>,
}

/// Constraint fields that the browser reports recognizing.
///
/// Recognition does not prove that any particular value is available.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RecorderConstraintCapabilities {
    pub channel_count: bool,
    pub sample_rate: bool,
    pub echo_cancellation: bool,
    pub noise_suppression: bool,
    pub latency: bool,
}

/// Effective settings reported by an acquired Recording Source.
///
/// Every field is optional because browser reporting varies.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RecordingSourceSettings {
    pub channel_count: Option<u32>,
    pub sample_rate: Option<u32>,
    pub echo_cancellation: Option<bool>,
    pub noise_suppression: Option<bool>,
    pub latency: Option<Duration>,
}

type RecordingChunkHandler = Rc<RefCell<Box<dyn FnMut(RecordingChunk)>>>;

/// Opt-in cadence and callback for ordered Recording Chunk delivery.
#[derive(Clone)]
pub struct RecordingChunkDelivery {
    /// Approximate interval at which the browser should create chunk boundaries.
    ///
    /// Boundaries may be empty, late, or dependent on earlier fragments.
    pub cadence: Duration,
    on_chunk: RecordingChunkHandler,
}

impl fmt::Debug for RecordingChunkDelivery {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RecordingChunkDelivery")
            .field("cadence", &self.cadence)
            .finish_non_exhaustive()
    }
}

impl PartialEq for RecordingChunkDelivery {
    fn eq(&self, other: &Self) -> bool {
        self.cadence == other.cadence && Rc::ptr_eq(&self.on_chunk, &other.on_chunk)
    }
}

impl RecordingChunkDelivery {
    /// Configure ordered push delivery at an approximate cadence.
    pub fn new(cadence: Duration, on_chunk: impl FnMut(RecordingChunk) + 'static) -> Self {
        Self {
            cadence,
            on_chunk: Rc::new(RefCell::new(Box::new(on_chunk))),
        }
    }

    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    fn call(&self, chunk: RecordingChunk) {
        (self.on_chunk.borrow_mut())(chunk);
    }

    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    fn time_slice_millis(&self) -> i32 {
        i32::try_from(self.cadence.as_millis())
            .expect("validated Recording Chunk cadence fits in an i32")
    }
}

#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct RecorderOptions {
    pub fft_size: u32,
    pub smoothing: f64,
    pub peak_interval: Duration,
    pub constraints: RecordingConstraints,
    pub mime_types: Vec<String>,
    pub audio_bits_per_second: Option<u32>,
    pub chunk_delivery: Option<RecordingChunkDelivery>,
}

impl Default for RecorderOptions {
    fn default() -> Self {
        Self {
            fft_size: 256,
            smoothing: 0.8,
            peak_interval: Duration::from_millis(100),
            constraints: RecordingConstraints::default(),
            mime_types: vec![
                "audio/webm;codecs=opus".to_string(),
                "audio/webm".to_string(),
                "audio/mp4".to_string(),
            ],
            audio_bits_per_second: None,
            chunk_delivery: None,
        }
    }
}

impl RecorderOptions {
    pub fn validate(&self) -> Result<(), AudioError> {
        if !(32..=32768).contains(&self.fft_size) || !self.fft_size.is_power_of_two() {
            return Err(AudioError::new(
                crate::AudioErrorKind::InvalidConfiguration,
                "fft_size must be a power of two between 32 and 32768",
            ));
        }
        if !(0.0..=1.0).contains(&self.smoothing) {
            return Err(AudioError::new(
                crate::AudioErrorKind::InvalidConfiguration,
                "smoothing must be between 0 and 1",
            ));
        }
        if self.peak_interval.is_zero() {
            return Err(AudioError::new(
                crate::AudioErrorKind::InvalidConfiguration,
                "peak_interval must be greater than zero",
            ));
        }
        if let Some(delivery) = &self.chunk_delivery
            && (delivery.cadence.as_millis() == 0
                || delivery.cadence.as_millis() > i32::MAX as u128)
        {
            return Err(AudioError::new(
                crate::AudioErrorKind::InvalidConfiguration,
                "Recording Chunk cadence must be between 1 millisecond and 2147483647 milliseconds",
            ));
        }
        Ok(())
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MicrophoneStatus {
    pub permission: MicrophonePermission,
    pub recorder: RecorderStatus,
    pub input_device: Option<AudioInputId>,
    pub muted: bool,
}

#[derive(Clone, Copy, PartialEq)]
pub struct AudioRecorder {
    status: ReadSignal<RecorderStatus>,
    completed: ReadSignal<Option<RecordedAudio>>,
    analyser: ReadSignal<Option<AudioAnalyser>>,
    elapsed: ReadSignal<Duration>,
    source_availability: ReadSignal<Option<RecordingSourceAvailability>>,
    microphone: ReadSignal<MicrophoneStatus>,
    requested_constraints: ReadSignal<Option<RecordingConstraints>>,
    constraint_capabilities: ReadSignal<Option<RecorderConstraintCapabilities>>,
    settings: ReadSignal<Option<RecordingSourceSettings>>,
    media_type: ReadSignal<Option<String>>,
    outcome: ReadSignal<Option<RecordingOutcome>>,
    chunk_delivery_failure: ReadSignal<Option<RecordingChunkDeliveryFailure>>,
    start: Callback<(), Result<(), RecorderCommandError>>,
    start_with_source: Callback<RecordingSource, Result<(), RecorderCommandError>>,
    pause: Callback<(), Result<(), RecorderCommandError>>,
    resume: Callback<(), Result<(), RecorderCommandError>>,
    request_chunk_boundary: Callback<(), Result<(), RecorderCommandError>>,
    stop: Callback<(), Result<(), RecorderCommandError>>,
    cancel: Callback<(), Result<(), RecorderCommandError>>,
    take_completed: Callback<(), Option<RecordedAudio>>,
    clear_completed: Callback,
}

impl AudioRecorder {
    pub fn status(self) -> ReadSignal<RecorderStatus> {
        self.status
    }

    pub fn completed(self) -> ReadSignal<Option<RecordedAudio>> {
        self.completed
    }

    pub fn analyser(self) -> ReadSignal<Option<AudioAnalyser>> {
        self.analyser
    }

    pub fn elapsed(self) -> ReadSignal<Duration> {
        self.elapsed
    }

    /// Browser-reported availability of the active Recording Source.
    ///
    /// Interruption does not pause Recording or elapsed time. This
    /// observation does not inspect application control of the track's enabled
    /// state.
    pub fn source_availability(self) -> ReadSignal<Option<RecordingSourceAvailability>> {
        self.source_availability
    }

    pub fn microphone(self) -> ReadSignal<MicrophoneStatus> {
        self.microphone
    }

    /// Constraints snapshotted by the most recently accepted start request.
    pub fn requested_constraints(self) -> ReadSignal<Option<RecordingConstraints>> {
        self.requested_constraints
    }

    /// Constraint fields that the browser reports recognizing.
    ///
    /// Recognition does not imply that a particular value can be acquired.
    pub fn constraint_capabilities(self) -> ReadSignal<Option<RecorderConstraintCapabilities>> {
        self.constraint_capabilities
    }

    /// Effective settings reported by the acquired Recording Source.
    pub fn settings(self) -> ReadSignal<Option<RecordingSourceSettings>> {
        self.settings
    }

    /// Encoder media type selected for the current or most recent Recording.
    pub fn media_type(self) -> ReadSignal<Option<String>> {
        self.media_type
    }

    /// Terminal outcome of the most recently accepted Recording, if any.
    pub fn outcome(self) -> ReadSignal<Option<RecordingOutcome>> {
        self.outcome
    }

    /// Terminal incremental delivery failure for the current or most recent Recording.
    pub fn chunk_delivery_failure(self) -> ReadSignal<Option<RecordingChunkDeliveryFailure>> {
        self.chunk_delivery_failure
    }

    pub fn start(self) -> Result<(), RecorderCommandError> {
        self.start.call(())
    }

    /// Start a Recording from one application-supplied live audio track.
    ///
    /// Video tracks are ignored. The supplied audio track is never stopped by
    /// Recorder under this default preserve-tracks agreement.
    pub fn start_with_source(self, source: RecordingSource) -> Result<(), RecorderCommandError> {
        self.start_with_source.call(source)
    }

    pub fn pause(self) -> Result<(), RecorderCommandError> {
        self.pause.call(())
    }

    pub fn resume(self) -> Result<(), RecorderCommandError> {
        self.resume.call(())
    }

    /// Ask the browser to create a best-effort Recording Chunk boundary.
    ///
    /// The request is available only to an opted-in Recording while active or
    /// paused. It does not promise exact timing, non-empty output, or an
    /// independently playable chunk.
    pub fn request_chunk_boundary(self) -> Result<(), RecorderCommandError> {
        self.request_chunk_boundary.call(())
    }

    pub fn stop(self) -> Result<(), RecorderCommandError> {
        self.stop.call(())
    }

    pub fn cancel(self) -> Result<(), RecorderCommandError> {
        self.cancel.call(())
    }

    pub fn clear_completed(self) {
        self.clear_completed.call(());
    }

    /// Move the completed recording out without cloning its audio buffer.
    pub fn take_completed(self) -> Option<RecordedAudio> {
        self.take_completed.call(())
    }
}

/// Probe whether the browser recognizes a Recorder media type.
///
/// A positive result does not guarantee that source acquisition, Recorder
/// construction, or a complete Recording will succeed.
pub fn is_recorder_mime_type_supported(mime_type: &str) -> bool {
    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    {
        web_sys::MediaRecorder::is_type_supported(mime_type)
    }

    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    {
        let _ = mime_type;
        false
    }
}

/// Create a recorder controller. The selected input is snapshotted by `start`.
pub fn use_audio_recorder(
    options: RecorderOptions,
    selected_input: ReadSignal<Option<AudioInputId>>,
) -> AudioRecorder {
    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    {
        web::use_web_audio_recorder(options, selected_input)
    }

    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    {
        let _ = (options, selected_input);
        use_unsupported_audio_recorder()
    }
}

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
fn use_unsupported_audio_recorder() -> AudioRecorder {
    let error = AudioError::unsupported();
    let mut status = use_signal(|| RecorderStatus::Idle);
    let completed = use_signal(|| None::<RecordedAudio>);
    let analyser = use_signal(|| None::<AudioAnalyser>);
    let elapsed = use_signal(|| Duration::ZERO);
    let source_availability = use_signal(|| None::<RecordingSourceAvailability>);
    let requested_constraints = use_signal(|| None::<RecordingConstraints>);
    let constraint_capabilities = use_signal(|| None::<RecorderConstraintCapabilities>);
    let settings = use_signal(|| None::<RecordingSourceSettings>);
    let media_type = use_signal(|| None::<String>);
    let outcome = use_signal(|| None::<RecordingOutcome>);
    let chunk_delivery_failure = use_signal(|| None::<RecordingChunkDeliveryFailure>);
    let mut microphone = use_signal(|| MicrophoneStatus {
        permission: MicrophonePermission::Unknown,
        recorder: RecorderStatus::Idle,
        input_device: None,
        muted: false,
    });
    use_effect(move || {
        let status_error = RecorderStatus::Failed(error.clone());
        status.set(status_error.clone());
        microphone.set(MicrophoneStatus {
            permission: MicrophonePermission::Unsupported,
            recorder: status_error,
            input_device: None,
            muted: false,
        });
    });
    let unsupported: Callback<(), Result<(), RecorderCommandError>> = use_callback(|()| {
        Err(command_error(
            "audio recording is unsupported on this platform",
        ))
    });
    let unsupported_source: Callback<RecordingSource, Result<(), RecorderCommandError>> =
        use_callback(|_| {
            Err(command_error(
                "audio recording is unsupported on this platform",
            ))
        });
    let mut completed_to_clear = completed;
    let clear_completed = use_callback(move |()| completed_to_clear.set(None));
    let mut completed_to_take = completed;
    let take_completed = use_callback(move |()| completed_to_take.write().take());

    AudioRecorder {
        status: status.into(),
        completed: completed.into(),
        analyser: analyser.into(),
        elapsed: elapsed.into(),
        source_availability: source_availability.into(),
        microphone: microphone.into(),
        requested_constraints: requested_constraints.into(),
        constraint_capabilities: constraint_capabilities.into(),
        settings: settings.into(),
        media_type: media_type.into(),
        outcome: outcome.into(),
        chunk_delivery_failure: chunk_delivery_failure.into(),
        start: unsupported,
        start_with_source: unsupported_source,
        pause: unsupported,
        resume: unsupported,
        request_chunk_boundary: unsupported,
        stop: unsupported,
        cancel: unsupported,
        take_completed,
        clear_completed,
    }
}