1
//! Microphone-capture widget (SUPER_PLAN_2 §4 P7) - a "dumb widget" with the
2
//! same architecture as the camera/screencap/video widgets, only the medium is
3
//! audio (no GL texture).
4
//!
5
//! `MicrophoneWidget::create(config).with_on_frame(data, cb).dom()` yields an
6
//! invisible node that, on `AfterMount`, starts a background capture thread.
7
//! Each captured [`AudioFrame`] flows through the writeback to the user's
8
//! `on_frame` hook (the backreference DI pattern), so app code can save,
9
//! process, or **send** the audio over the network (the azul-meet audio seam) -
10
//! all via the public API, no globals. The mic permission is the existing
11
//! `Capability::Microphone`.
12
//!
13
//! This tick uses a self-contained **test-tone** worker (a 440 Hz sine, no
14
//! platform deps); the real AVAudioEngine / AAudio / cpal capture worker
15
//! (dll-side) swaps in later.
16

            
17
use alloc::vec::Vec;
18

            
19
use azul_core::{
20
    audio::{AudioConfig, AudioFrame},
21
    callbacks::Update,
22
    dom::{ComponentEventFilter, DatasetMergeCallbackType, Dom, EventFilter},
23
    refany::{OptionRefAny, RefAny},
24
    task::{ThreadId, ThreadReceiver},
25
};
26
use azul_css::impl_option_inner; // for impl_widget_callback!'s impl_option!
27
use azul_css::F32Vec;
28

            
29
use super::capture_common::{mic_backend, terminate_requested};
30
use crate::{
31
    callbacks::{Callback, CallbackInfo, CallbackType},
32
    thread::{
33
        Thread, ThreadCallback, ThreadReceiveMsg, ThreadSender, ThreadWriteBackMsg,
34
        WriteBackCallback,
35
    },
36
};
37

            
38
// --- User hook: on_frame (backreference DI, FFI-exposed) ---
39

            
40
/// User hook fired once per captured audio chunk.
41
///
42
/// The widget's private writeback invokes it with each
43
/// [`AudioFrame`] so application code can save it, apply effects, or send it
44
/// over the network (azul-meet). Returns `Update` like any callback. Wired via
45
/// [`MicrophoneWidget::with_on_frame`].
46
pub type OnAudioFrameCallbackType = extern "C" fn(RefAny, CallbackInfo, AudioFrame) -> Update;
47
impl_widget_callback!(
48
    OnAudioFrame,
49
    OptionOnAudioFrame,
50
    OnAudioFrameCallback,
51
    OnAudioFrameCallbackType
52
);
53

            
54
// Host-invoker plumbing for managed-FFI bindings - see core/src/host_invoker.rs.
55
azul_core::impl_managed_callback! {
56
    wrapper:        OnAudioFrameCallback,
57
    info_ty:        CallbackInfo,
58
    return_ty:      Update,
59
    default_ret:    Update::DoNothing,
60
    invoker_static: ON_AUDIO_FRAME_INVOKER,
61
    invoker_ty:     AzOnAudioFrameCallbackInvoker,
62
    thunk_fn:       az_on_audio_frame_callback_thunk,
63
    setter_fn:      AzApp_setOnAudioFrameCallbackInvoker,
64
    from_handle_fn: AzOnAudioFrameCallback_createFromHostHandle,
65
    extra_args:     [ frame: AudioFrame ],
66
}
67

            
68
/// Invoke the optional `on_frame` hook with `frame`, returning the user's
69
/// `Update` (`DoNothing` when no hook is set).
70
7
fn invoke_on_audio_frame(
71
7
    hook: &OptionOnAudioFrame,
72
7
    info: &CallbackInfo,
73
7
    frame: AudioFrame,
74
7
) -> Update {
75
7
    match hook {
76
5
        OptionOnAudioFrame::Some(h) => (h.callback.cb)(h.refany.clone(), *info, frame),
77
2
        OptionOnAudioFrame::None => Update::DoNothing,
78
    }
79
7
}
80

            
81
/// Init data handed to the capture worker thread.
82
struct MicThreadInit {
83
    sample_rate: u32,
84
    channels: u16,
85
}
86

            
87
/// Live state for one microphone widget, carried across relayout by
88
/// [`merge_microphone_state`].
89
#[derive(Debug)]
90
pub struct MicrophoneWidgetState {
91
    /// The requested capture configuration (rate + channels).
92
    pub config: AudioConfig,
93
    /// `true` once the capture thread has been started.
94
    pub started: bool,
95
    /// Optional user hook invoked with each captured frame (save / effects /
96
    /// send). Re-set on every fresh build (see [`merge_microphone_state`]).
97
    pub on_frame: OptionOnAudioFrame,
98
}
99

            
100
/// A microphone-capture widget. `create(config).with_on_frame(..).dom()` yields
101
/// an invisible node a background capture thread feeds.
102
#[repr(C)]
103
#[derive(Debug)]
104
pub struct MicrophoneWidget {
105
    /// Requested capture config (sample rate, channels).
106
    pub config: AudioConfig,
107
    /// Optional per-frame user hook (save / effects / send - azul-meet).
108
    pub on_frame: OptionOnAudioFrame,
109
}
110

            
111
impl MicrophoneWidget {
112
    /// Create a microphone widget for the given capture config.
113
    #[must_use]
114
19
    pub const fn create(config: AudioConfig) -> Self {
115
19
        Self {
116
19
            config,
117
19
            on_frame: OptionOnAudioFrame::None,
118
19
        }
119
19
    }
120

            
121
    /// Set a hook invoked with every captured audio chunk - for saving,
122
    /// effects, or sending over the network (azul-meet). The backreference DI
123
    /// pattern (see `architecture.md`).
124
9
    pub fn set_on_frame<C: Into<OnAudioFrameCallback>>(&mut self, data: RefAny, on_frame: C) {
125
9
        self.on_frame = Some(OnAudioFrame {
126
9
            refany: data,
127
9
            callback: on_frame.into(),
128
9
        })
129
9
        .into();
130
9
    }
131

            
132
    /// Builder form of [`set_on_frame`](Self::set_on_frame).
133
    #[must_use]
134
5
    pub fn with_on_frame<C: Into<OnAudioFrameCallback>>(
135
5
        mut self,
136
5
        data: RefAny,
137
5
        on_frame: C,
138
5
    ) -> Self {
139
5
        self.set_on_frame(data, on_frame);
140
5
        self
141
5
    }
142

            
143
    /// Build the widget's DOM: a single invisible node, fed by a background
144
    /// capture thread started on mount. Place it anywhere in your tree - the
145
    /// capture lives as long as the node is mounted (unmount stops it).
146
    #[must_use]
147
9
    pub fn dom(self) -> Dom {
148
9
        let state = MicrophoneWidgetState {
149
9
            config: self.config,
150
9
            started: false,
151
9
            on_frame: self.on_frame,
152
9
        };
153
9
        let dataset = RefAny::new(state);
154

            
155
9
        Dom::create_div()
156
9
            .with_dataset(OptionRefAny::Some(dataset.clone()))
157
9
            .with_merge_callback(azul_core::dom::DatasetMergeCallback::from_ptr(
158
9
                merge_microphone_state,
159
            ))
160
9
            .with_callback(
161
9
                EventFilter::Component(ComponentEventFilter::AfterMount),
162
9
                dataset,
163
9
                Callback::from_ptr(mic_on_after_mount),
164
            )
165
9
    }
166
}
167

            
168
/// `AfterMount`: start the background capture thread exactly once.
169
3
extern "C" fn mic_on_after_mount(mut data: RefAny, mut info: CallbackInfo) -> Update {
170
    let (rate, channels) = {
171
3
        let Some(mut s) = data.downcast_mut::<MicrophoneWidgetState>() else {
172
2
            return Update::DoNothing;
173
        };
174
1
        if s.started {
175
1
            return Update::DoNothing;
176
        }
177
        s.started = true;
178
        let rate = if s.config.sample_rate > 0 {
179
            s.config.sample_rate
180
        } else {
181
            48_000
182
        };
183
        let channels = s.config.channels.max(1);
184
        (rate, channels)
185
    };
186

            
187
    info.add_thread(
188
        ThreadId::unique(),
189
        Thread::create(
190
            RefAny::new(MicThreadInit {
191
                sample_rate: rate,
192
                channels,
193
            }),
194
            data.clone(),
195
            ThreadCallback::new(mic_worker),
196
        ),
197
    );
198
    Update::DoNothing
199
3
}
200

            
201
/// Background worker (test tone): a 440 Hz sine in ~20 ms chunks until the
202
/// widget unmounts. The real `AVAudioEngine` / `AAudio` / cpal capture loop
203
/// replaces it (dll-side).
204
#[allow(clippy::cast_precision_loss)] // bounded graphics/coord/counter/fixed-point cast
205
6
extern "C" fn mic_worker(mut init: RefAny, mut sender: ThreadSender, mut recv: ThreadReceiver) {
206
6
    let (rate, channels) = init
207
6
        .downcast_ref::<MicThreadInit>()
208
6
        .map_or((48_000, 1), |i| (i.sample_rate, i.channels));
209

            
210
    // Real platform capture if the dll registered a mic backend (ALSA on
211
    // Linux); otherwise the 440 Hz test tone below.
212
6
    if let Some(backend) = mic_backend() {
213
6
        let handle = (backend.open)(rate, channels);
214
6
        if handle != 0 {
215
6
            let mut buf: Vec<f32> = Vec::new();
216
            loop {
217
                // See `capture_common::terminate_requested`: an ALSA read is
218
                // not interruptible from the terminate channel, so the check
219
                // has to happen between reads.
220
6
                if terminate_requested(&mut recv) {
221
1
                    break;
222
5
                }
223
5
                let frames = (backend.read)(handle, &mut buf);
224
5
                if frames == 0 {
225
3
                    break;
226
2
                }
227
2
                let frame = AudioFrame {
228
2
                    sample_rate: rate,
229
2
                    channels,
230
2
                    samples: F32Vec::from_vec(buf.clone()),
231
2
                };
232
2
                if !sender.send(ThreadReceiveMsg::WriteBack(ThreadWriteBackMsg::new(
233
2
                    WriteBackCallback::new(mic_writeback),
234
2
                    RefAny::new(frame),
235
2
                ))) {
236
2
                    break;
237
                }
238
            }
239
6
            (backend.close)(handle);
240
6
            return;
241
        }
242
    }
243

            
244
    // Reaching here means a MicrophoneWidget is live and about to feed a
245
    // synthetic 440 Hz TEST TONE instead of the microphone — the most
246
    // misleading fallback in the tree if unannounced. Say why, once.
247
    {
248
        static TEST_TONE_ANNOUNCE: std::sync::Once = std::sync::Once::new();
249
        let have_backend = mic_backend().is_some();
250
        TEST_TONE_ANNOUNCE.call_once(|| {
251
            if have_backend {
252
                eprintln!(
253
                    "[azul][microphone] the platform microphone backend failed to open (device \
254
                     missing/busy or libasound unavailable — see lines above) — feeding a \
255
                     synthetic 440 Hz TEST TONE instead of the microphone"
256
                );
257
            } else {
258
                eprintln!(
259
                    "[azul][microphone] no microphone backend is registered in this build/OS — \
260
                     feeding a synthetic 440 Hz TEST TONE instead of the microphone"
261
                );
262
            }
263
        });
264
    }
265

            
266
    let frames_per_chunk = (rate as usize / 50).max(1); // ~20 ms
267
    let step = 2.0 * core::f32::consts::PI * 440.0 / rate as f32;
268
    let mut phase: f32 = 0.0;
269
    loop {
270
        if terminate_requested(&mut recv) {
271
            break;
272
        }
273
        let mut samples = Vec::with_capacity(frames_per_chunk * channels as usize);
274
        for _ in 0..frames_per_chunk {
275
            let s = phase.sin() * 0.2;
276
            phase += step;
277
            if phase > 2.0 * core::f32::consts::PI {
278
                phase -= 2.0 * core::f32::consts::PI;
279
            }
280
            for _ in 0..channels {
281
                samples.push(s);
282
            }
283
        }
284
        let frame = AudioFrame {
285
            sample_rate: rate,
286
            channels,
287
            samples: F32Vec::from_vec(samples),
288
        };
289
        let sent = sender.send(ThreadReceiveMsg::WriteBack(ThreadWriteBackMsg::new(
290
            WriteBackCallback::new(mic_writeback),
291
            RefAny::new(frame),
292
        )));
293
        if !sent {
294
            break;
295
        }
296
        std::thread::sleep(std::time::Duration::from_millis(20));
297
    }
298
6
}
299

            
300
/// Writeback (main thread): hand the captured frame to the user's `on_frame`
301
/// hook. No GL - audio has no texture.
302
6
extern "C" fn mic_writeback(
303
6
    mut writeback_data: RefAny,
304
6
    mut frame_data: RefAny,
305
6
    info: CallbackInfo,
306
6
) -> Update {
307
6
    let hook = match writeback_data.downcast_ref::<MicrophoneWidgetState>() {
308
4
        Some(s) => s.on_frame.clone(),
309
2
        None => return Update::DoNothing,
310
    };
311
4
    frame_data
312
4
        .downcast_ref::<AudioFrame>()
313
4
        .map_or(Update::DoNothing, |frame| {
314
3
            invoke_on_audio_frame(&hook, &info, frame.clone())
315
3
        })
316
6
}
317

            
318
/// Carry live state forward across relayout (config + started; the `on_frame`
319
/// hook is taken from the fresh build).
320
7
extern "C" fn merge_microphone_state(mut new_data: RefAny, mut old_data: RefAny) -> RefAny {
321
    {
322
7
        let new_guard = new_data.downcast_mut::<MicrophoneWidgetState>();
323
7
        let old_guard = old_data.downcast_ref::<MicrophoneWidgetState>();
324
7
        if let (Some(mut new_g), Some(old_g)) = (new_guard, old_guard) {
325
4
            new_g.started = old_g.started;
326
4
        }
327
    }
328
7
    new_data
329
7
}
330

            
331
// ============================================================================
332
// Generated adversarial tests
333
// ============================================================================
334

            
335
#[cfg(test)]
336
#[allow(clippy::too_many_lines, clippy::cast_possible_truncation)]
337
mod autotest_generated {
338
    use std::{
339
        collections::BTreeMap,
340
        sync::{
341
            mpsc::{channel, Receiver, Sender},
342
            Arc, Mutex,
343
        },
344
    };
345

            
346
    use azul_core::{
347
        dom::{DomId, DomNodeId, NodeType},
348
        geom::OptionLogicalPosition,
349
        gl::OptionGlContextPtr,
350
        hit_test::ScrollPosition,
351
        resources::RendererResources,
352
        styled_dom::NodeHierarchyItemId,
353
        task::{
354
            OptionThreadSendMsg, ThreadReceiverDestructorCallback, ThreadReceiverInner,
355
            ThreadRecvCallback, ThreadSendMsg,
356
        },
357
        window::{MonitorVec, RawWindowHandle},
358
    };
359
    use azul_css::system::SystemStyle;
360
    use rust_fontconfig::FcFontCache;
361

            
362
    use super::*;
363
    #[cfg(feature = "icu")]
364
    use crate::icu::IcuLocalizerHandle;
365
    use crate::{
366
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
367
        thread::{
368
            ThreadSendCallback, ThreadSenderDestructorCallback, ThreadSenderInner,
369
            WriteBackCallbackType,
370
        },
371
        window::LayoutWindow,
372
        window_state::FullWindowState,
373
    };
374

            
375
    // ------------------------------------------------------------------
376
    // Helpers
377
    // ------------------------------------------------------------------
378

            
379
    /// An `AudioConfig` with the given rate + channel count.
380
    const fn cfg(sample_rate: u32, channels: u16) -> AudioConfig {
381
        AudioConfig {
382
            sample_rate,
383
            channels,
384
        }
385
    }
386

            
387
    /// An interleaved `AudioFrame`. `AudioFrame` has no `Default`, so every test
388
    /// spells out its rate / channel count / samples.
389
    fn frame(sample_rate: u32, channels: u16, samples: Vec<f32>) -> AudioFrame {
390
        AudioFrame {
391
            sample_rate,
392
            channels,
393
            samples: F32Vec::from_vec(samples),
394
        }
395
    }
396

            
397
    /// A `MicrophoneWidgetState` payload with no `on_frame` hook.
398
    fn state(config: AudioConfig, started: bool) -> RefAny {
399
        RefAny::new(MicrophoneWidgetState {
400
            config,
401
            started,
402
            on_frame: OptionOnAudioFrame::None,
403
        })
404
    }
405

            
406
    /// `(config, started, has_hook)` of a `MicrophoneWidgetState` payload.
407
    fn read_state(data: &mut RefAny) -> (AudioConfig, bool, bool) {
408
        let s = data
409
            .downcast_ref::<MicrophoneWidgetState>()
410
            .expect("payload must still be a MicrophoneWidgetState");
411
        (
412
            s.config,
413
            s.started,
414
            matches!(s.on_frame, OptionOnAudioFrame::Some(_)),
415
        )
416
    }
417

            
418
    // ---- frame hook -------------------------------------------------------
419

            
420
    /// Records every frame a widget's `on_frame` hook is handed, verbatim.
421
    struct FrameLog {
422
        seen: Vec<(u32, u16, Vec<f32>)>,
423
    }
424

            
425
    extern "C" fn record_frame(mut data: RefAny, _: CallbackInfo, frame: AudioFrame) -> Update {
426
        if let Some(mut log) = data.downcast_mut::<FrameLog>() {
427
            log.seen.push((
428
                frame.sample_rate,
429
                frame.channels,
430
                frame.samples.as_ref().to_vec(),
431
            ));
432
        }
433
        Update::RefreshDom
434
    }
435

            
436
    extern "C" fn frame_do_nothing(_: RefAny, _: CallbackInfo, _: AudioFrame) -> Update {
437
        Update::DoNothing
438
    }
439

            
440
    /// The frames recorded by a `FrameLog` payload.
441
    fn logged_frames(data: &mut RefAny) -> Vec<(u32, u16, Vec<f32>)> {
442
        data.downcast_ref::<FrameLog>()
443
            .expect("payload must still be a FrameLog")
444
            .seen
445
            .clone()
446
    }
447

            
448
    fn new_log() -> RefAny {
449
        RefAny::new(FrameLog { seen: Vec::new() })
450
    }
451

            
452
    /// An `on_frame` hook that records into `log`.
453
    fn hook_into(log: &RefAny) -> OptionOnAudioFrame {
454
        Some(OnAudioFrame {
455
            refany: log.clone(),
456
            callback: (record_frame as OnAudioFrameCallbackType).into(),
457
        })
458
        .into()
459
    }
460

            
461
    /// A `MicrophoneWidgetState` whose `on_frame` hook writes into `log`.
462
    fn state_with_hook(config: AudioConfig, started: bool, log: &RefAny) -> RefAny {
463
        RefAny::new(MicrophoneWidgetState {
464
            config,
465
            started,
466
            on_frame: hook_into(log),
467
        })
468
    }
469

            
470
    // ---- CallbackInfo harness --------------------------------------------
471

            
472
    /// Runs `f` against a real `CallbackInfo` over an empty `LayoutWindow` (no GL
473
    /// context). Returns `f`'s value plus every `CallbackChange` the callback
474
    /// recorded.
475
    fn with_callback_info<R>(f: impl FnOnce(CallbackInfo) -> R) -> (R, Vec<CallbackChange>) {
476
        let layout_window =
477
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
478
        let renderer_resources = RendererResources::default();
479
        let previous_window_state: Option<FullWindowState> = None;
480
        let current_window_state = FullWindowState::default();
481
        let gl_context = OptionGlContextPtr::None;
482
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
483
            BTreeMap::new();
484
        let window_handle = RawWindowHandle::Unsupported;
485
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
486

            
487
        let ref_data = CallbackInfoRefData {
488
            layout_window: &layout_window,
489
            renderer_resources: &renderer_resources,
490
            previous_window_state: &previous_window_state,
491
            current_window_state: &current_window_state,
492
            gl_context: &gl_context,
493
            current_scroll_manager: &scroll_states,
494
            current_window_handle: &window_handle,
495
            system_callbacks: &system_callbacks,
496
            system_style: Arc::new(SystemStyle::default()),
497
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
498
            #[cfg(feature = "icu")]
499
            icu_localizer: IcuLocalizerHandle::default(),
500
            ctx: OptionRefAny::None,
501
        };
502

            
503
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
504

            
505
        let info = CallbackInfo::new(
506
            &ref_data,
507
            &changes,
508
            DomNodeId {
509
                dom: DomId::ROOT_ID,
510
                node: NodeHierarchyItemId::NONE,
511
            },
512
            OptionLogicalPosition::None,
513
            OptionLogicalPosition::None,
514
        );
515

            
516
        let out = f(info);
517
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
518
        (out, recorded)
519
    }
520

            
521
    // ---- mic_worker harness ----------------------------------------------
522

            
523
    /// One frame `mic_worker` handed to its sender.
524
    #[derive(Debug, Clone, PartialEq)]
525
    struct SentFrame {
526
        sample_rate: u32,
527
        channels: u16,
528
        samples: Vec<f32>,
529
        /// The writeback fn pointer the worker attached, as an address.
530
        writeback: usize,
531
    }
532

            
533
    /// Everything `mic_worker` pushed. Guarded by `WORKER_GATE` - the worker's send
534
    /// callback is a plain C fn pointer, so it has nowhere else to put its result.
535
    static WORKER_LOG: Mutex<Vec<SentFrame>> = Mutex::new(Vec::new());
536
    static WORKER_GATE: Mutex<()> = Mutex::new(());
537

            
538
    /// Records the frame, then reports the send as *failed* - i.e. "the main thread
539
    /// is gone", the only signal `mic_worker` has to stop. A worker that ignored it
540
    /// would hang this test forever (the tone loop is unbounded).
541
    extern "C" fn record_and_stop(
542
        _sender: *const core::ffi::c_void,
543
        msg: ThreadReceiveMsg,
544
    ) -> bool {
545
        if let ThreadReceiveMsg::WriteBack(mut wb) = msg {
546
            let writeback = wb.callback.cb as usize;
547
            if let Some(f) = wb.refany.downcast_ref::<AudioFrame>() {
548
                WORKER_LOG
549
                    .lock()
550
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
551
                    .push(SentFrame {
552
                        sample_rate: f.sample_rate,
553
                        channels: f.channels,
554
                        samples: f.samples.as_ref().to_vec(),
555
                        writeback,
556
                    });
557
            }
558
        }
559
        false
560
    }
561

            
562
    extern "C" fn sender_drop_noop(_: *mut ThreadSenderInner) {}
563
    extern "C" fn receiver_drop_noop(_: *mut ThreadReceiverInner) {}
564
    extern "C" fn recv_nothing(_: *const core::ffi::c_void) -> OptionThreadSendMsg {
565
        OptionThreadSendMsg::None
566
    }
567

            
568
    /// A `ThreadSender` whose every `send` is recorded and then rejected.
569
    fn stopped_sender() -> (Receiver<ThreadReceiveMsg>, ThreadSender) {
570
        let (tx, rx) = channel::<ThreadReceiveMsg>();
571
        let sender = ThreadSender::new(ThreadSenderInner {
572
            ptr: Box::new(tx),
573
            send_fn: ThreadSendCallback {
574
                cb: record_and_stop,
575
            },
576
            destructor: ThreadSenderDestructorCallback {
577
                cb: sender_drop_noop,
578
            },
579
        });
580
        (rx, sender)
581
    }
582

            
583
    /// A `ThreadReceiver` that never delivers anything (`mic_worker` ignores it).
584
    fn silent_receiver() -> (Sender<ThreadSendMsg>, ThreadReceiver) {
585
        let (tx, rx) = channel::<ThreadSendMsg>();
586
        let receiver = ThreadReceiver::new(ThreadReceiverInner {
587
            ptr: Box::new(rx),
588
            recv_fn: ThreadRecvCallback { cb: recv_nothing },
589
            destructor: ThreadReceiverDestructorCallback {
590
                cb: receiver_drop_noop,
591
            },
592
        });
593
        (tx, receiver)
594
    }
595

            
596
    /// Runs `mic_worker` with `init` against a sender that rejects the first frame.
597
    ///
598
    /// Returns `(frames the worker managed to send, took_the_test_tone_path)`. The
599
    /// flag is read *after* the run on purpose: `MIC_BACKEND` is a `OnceLock`, so
600
    /// "still unregistered afterwards" proves it was unregistered *during* the run
601
    /// — and another test in this binary (`capture_common`) may register one at any
602
    /// time. Assertions about the 440 Hz tone are gated on it; the path-independent
603
    /// invariants are always checked.
604
    fn run_worker(init: RefAny) -> (Vec<SentFrame>, bool) {
605
        let _gate = WORKER_GATE
606
            .lock()
607
            .unwrap_or_else(std::sync::PoisonError::into_inner);
608
        WORKER_LOG
609
            .lock()
610
            .unwrap_or_else(std::sync::PoisonError::into_inner)
611
            .clear();
612

            
613
        let (_rx, sender) = stopped_sender();
614
        let (_tx, receiver) = silent_receiver();
615
        mic_worker(init, sender, receiver);
616

            
617
        let sent = WORKER_LOG
618
            .lock()
619
            .unwrap_or_else(std::sync::PoisonError::into_inner)
620
            .clone();
621
        (sent, mic_backend().is_none())
622
    }
623

            
624
    /// The tone worker's chunk length: ~20 ms of interleaved samples, never empty
625
    /// in the frame dimension.
626
    fn expected_chunk_len(sample_rate: u32, channels: u16) -> usize {
627
        (sample_rate as usize / 50).max(1) * channels as usize
628
    }
629

            
630
    // ------------------------------------------------------------------
631
    // invoke_on_audio_frame
632
    // ------------------------------------------------------------------
633

            
634
    #[test]
635
    fn invoke_without_a_hook_is_donothing_even_for_a_degenerate_frame() {
636
        let (update, _) = with_callback_info(|info| {
637
            // 0 channels + huge rate + no samples: nothing may divide by the channel
638
            // count or index the (empty) sample buffer.
639
            invoke_on_audio_frame(
640
                &OptionOnAudioFrame::None,
641
                &info,
642
                frame(u32::MAX, 0, Vec::new()),
643
            )
644
        });
645
        assert_eq!(update, Update::DoNothing);
646
    }
647

            
648
    #[test]
649
    fn invoke_forwards_the_frame_verbatim_and_returns_the_hooks_update() {
650
        let mut log = new_log();
651
        let hook = hook_into(&log);
652
        let samples = vec![-1.0_f32, 0.0, 1.0, 0.5];
653

            
654
        let (update, _) = with_callback_info(|info| {
655
            invoke_on_audio_frame(&hook, &info, frame(44_100, 2, samples.clone()))
656
        });
657

            
658
        assert_eq!(update, Update::RefreshDom, "the hook's Update must win");
659
        assert_eq!(logged_frames(&mut log), vec![(44_100, 2, samples)]);
660
    }
661

            
662
    #[test]
663
    fn invoke_passes_nan_infinite_and_negative_zero_samples_through_untouched() {
664
        // The widget is a transport, not a filter: hostile float payloads must reach
665
        // the user hook exactly as captured, with no normalisation and no panic.
666
        let mut log = new_log();
667
        let hook = hook_into(&log);
668
        let hostile = vec![
669
            f32::NAN,
670
            f32::INFINITY,
671
            f32::NEG_INFINITY,
672
            -0.0,
673
            f32::MIN,
674
            f32::MAX,
675
        ];
676

            
677
        let (update, _) =
678
            with_callback_info(|info| invoke_on_audio_frame(&hook, &info, frame(0, 1, hostile)));
679

            
680
        assert_eq!(update, Update::RefreshDom);
681
        let seen = logged_frames(&mut log);
682
        assert_eq!(seen.len(), 1);
683
        let (rate, channels, samples) = &seen[0];
684
        assert_eq!(
685
            (*rate, *channels),
686
            (0, 1),
687
            "a 0 Hz frame is forwarded as-is"
688
        );
689
        assert!(samples[0].is_nan(), "NaN must not be normalised");
690
        assert_eq!(samples[1], f32::INFINITY);
691
        assert_eq!(samples[2], f32::NEG_INFINITY);
692
        assert!(
693
            samples[3] == 0.0 && samples[3].is_sign_negative(),
694
            "-0.0 must keep its sign bit"
695
        );
696
        assert_eq!(samples[4], f32::MIN);
697
        assert_eq!(samples[5], f32::MAX);
698
    }
699

            
700
    #[test]
701
    fn invoke_forwards_a_frame_whose_sample_count_contradicts_its_channel_count() {
702
        // 65535 channels but 3 samples: `frame_count()` must floor to 0 rather than
703
        // divide by zero or wrap, and the hook still sees the frame.
704
        let mut log = new_log();
705
        let hook = hook_into(&log);
706
        let bogus = frame(u32::MAX, u16::MAX, vec![0.1, 0.2, 0.3]);
707
        assert_eq!(bogus.frame_count(), 0);
708

            
709
        let (update, _) = with_callback_info(|info| invoke_on_audio_frame(&hook, &info, bogus));
710

            
711
        assert_eq!(update, Update::RefreshDom);
712
        assert_eq!(
713
            logged_frames(&mut log),
714
            vec![(u32::MAX, u16::MAX, vec![0.1, 0.2, 0.3])]
715
        );
716
    }
717

            
718
    // ------------------------------------------------------------------
719
    // MicrophoneWidget::create / set_on_frame / with_on_frame
720
    // ------------------------------------------------------------------
721

            
722
    #[test]
723
    fn create_stores_the_config_verbatim_and_leaves_the_hook_unset() {
724
        for (rate, channels) in [
725
            (0, 0),
726
            (1, 1),
727
            (48_000, 2),
728
            (u32::MAX, u16::MAX),
729
            (u32::MAX, 0),
730
            (0, u16::MAX),
731
        ] {
732
            let widget = MicrophoneWidget::create(cfg(rate, channels));
733
            assert_eq!(
734
                widget.config,
735
                cfg(rate, channels),
736
                "create must not normalise the config"
737
            );
738
            assert!(
739
                matches!(widget.on_frame, OptionOnAudioFrame::None),
740
                "a fresh widget has no frame hook"
741
            );
742
        }
743

            
744
        let default = MicrophoneWidget::create(AudioConfig::default());
745
        assert_eq!(default.config, cfg(48_000, 1));
746
    }
747

            
748
    #[test]
749
    fn with_on_frame_installs_the_hook_keeps_the_config_and_shares_the_user_data() {
750
        let data = new_log();
751
        let widget = MicrophoneWidget::create(cfg(u32::MAX, u16::MAX))
752
            .with_on_frame(data.clone(), record_frame as OnAudioFrameCallbackType);
753

            
754
        assert_eq!(
755
            widget.config,
756
            cfg(u32::MAX, u16::MAX),
757
            "the builder must not touch the config"
758
        );
759
        let OptionOnAudioFrame::Some(hook) = &widget.on_frame else {
760
            panic!("with_on_frame must install a hook");
761
        };
762
        assert_eq!(
763
            hook.callback.cb as usize,
764
            record_frame as OnAudioFrameCallbackType as usize
765
        );
766
        assert_eq!(
767
            hook.refany, data,
768
            "the widget must hold the caller's RefAny, not a fresh allocation"
769
        );
770
    }
771

            
772
    #[test]
773
    fn set_on_frame_twice_keeps_only_the_last_hook_and_releases_the_first_payload() {
774
        let first = new_log();
775
        let second = new_log();
776
        let mut widget = MicrophoneWidget::create(cfg(8_000, 1));
777
        widget.set_on_frame(first.clone(), record_frame as OnAudioFrameCallbackType);
778
        widget.set_on_frame(second.clone(), frame_do_nothing as OnAudioFrameCallbackType);
779

            
780
        let OptionOnAudioFrame::Some(hook) = &widget.on_frame else {
781
            panic!("hook must still be set");
782
        };
783
        assert_eq!(
784
            hook.callback.cb as usize, frame_do_nothing as OnAudioFrameCallbackType as usize,
785
            "the second set_on_frame must replace the first"
786
        );
787
        assert_eq!(hook.refany, second);
788
        assert_ne!(
789
            hook.refany, first,
790
            "the first payload must have been dropped"
791
        );
792
        assert_eq!(widget.config, cfg(8_000, 1));
793
    }
794

            
795
    #[test]
796
    fn set_on_frame_accepts_the_same_refany_for_both_hooks() {
797
        // Re-registering the *same* payload must not free it (a double-drop would
798
        // show up as a corrupt downcast here).
799
        let mut data = new_log();
800
        let mut widget = MicrophoneWidget::create(cfg(48_000, 2));
801
        widget.set_on_frame(data.clone(), record_frame as OnAudioFrameCallbackType);
802
        widget.set_on_frame(data.clone(), record_frame as OnAudioFrameCallbackType);
803

            
804
        assert!(matches!(widget.on_frame, OptionOnAudioFrame::Some(_)));
805
        assert!(logged_frames(&mut data).is_empty());
806
    }
807

            
808
    // ------------------------------------------------------------------
809
    // MicrophoneWidget::dom
810
    // ------------------------------------------------------------------
811

            
812
    #[test]
813
    fn dom_is_one_div_with_one_after_mount_callback_a_dataset_and_a_merge_callback() {
814
        let dom = MicrophoneWidget::create(cfg(48_000, 2)).dom();
815

            
816
        assert_eq!(dom.root.get_node_type(), &NodeType::Div);
817
        assert_eq!(
818
            dom.children.as_ref().len(),
819
            0,
820
            "the widget is a single node"
821
        );
822

            
823
        let callbacks = dom.root.get_callbacks();
824
        assert_eq!(
825
            callbacks.as_ref().len(),
826
            1,
827
            "exactly one callback: the AfterMount capture-thread starter"
828
        );
829
        assert_eq!(
830
            callbacks.as_ref()[0].event,
831
            EventFilter::Component(ComponentEventFilter::AfterMount)
832
        );
833
        assert_eq!(
834
            callbacks.as_ref()[0].callback.cb,
835
            mic_on_after_mount as CallbackType as usize
836
        );
837

            
838
        let merge = dom
839
            .root
840
            .get_merge_callback()
841
            .expect("state must survive relayout");
842
        assert_eq!(
843
            merge.cb as usize,
844
            merge_microphone_state as DatasetMergeCallbackType as usize
845
        );
846

            
847
        let mut dataset = dom
848
            .root
849
            .get_dataset()
850
            .cloned()
851
            .expect("the node must carry its MicrophoneWidgetState");
852
        assert_eq!(read_state(&mut dataset), (cfg(48_000, 2), false, false));
853
    }
854

            
855
    #[test]
856
    fn dom_shares_one_state_between_the_dataset_and_the_after_mount_callback() {
857
        let dom = MicrophoneWidget::create(cfg(48_000, 1)).dom();
858
        let mut dataset = dom.root.get_dataset().cloned().expect("dataset");
859
        let mut callback_data = dom.root.get_callbacks().as_ref()[0].refany.clone();
860

            
861
        assert_eq!(
862
            callback_data, dataset,
863
            "AfterMount must see the very state the dataset carries"
864
        );
865

            
866
        {
867
            let mut s = dataset
868
                .downcast_mut::<MicrophoneWidgetState>()
869
                .expect("state");
870
            s.started = true;
871
        }
872
        assert!(
873
            read_state(&mut callback_data).1,
874
            "a write through the dataset must be visible to the callback"
875
        );
876
    }
877

            
878
    #[test]
879
    fn dom_carries_an_extreme_config_and_the_hook_into_the_state_unnormalised() {
880
        // Normalisation (0 -> 48 kHz, channels.max(1)) happens on AfterMount, not at
881
        // build time - the state must record exactly what the user asked for.
882
        for (rate, channels) in [(0, 0), (1, u16::MAX), (u32::MAX, 1)] {
883
            let dom = MicrophoneWidget::create(cfg(rate, channels))
884
                .with_on_frame(new_log(), record_frame as OnAudioFrameCallbackType)
885
                .dom();
886
            let mut dataset = dom.root.get_dataset().cloned().expect("dataset");
887
            assert_eq!(read_state(&mut dataset), (cfg(rate, channels), false, true));
888
        }
889
    }
890

            
891
    #[test]
892
    fn dom_built_twice_yields_two_independent_states() {
893
        let a = MicrophoneWidget::create(cfg(8_000, 1)).dom();
894
        let b = MicrophoneWidget::create(cfg(8_000, 1)).dom();
895
        let mut a_ds = a.root.get_dataset().cloned().expect("dataset");
896
        let mut b_ds = b.root.get_dataset().cloned().expect("dataset");
897

            
898
        assert_ne!(a_ds, b_ds, "two widgets must not share one capture state");
899
        {
900
            let mut s = a_ds.downcast_mut::<MicrophoneWidgetState>().expect("state");
901
            s.started = true;
902
        }
903
        assert!(!read_state(&mut b_ds).1, "the second widget is untouched");
904
    }
905

            
906
    // ------------------------------------------------------------------
907
    // mic_on_after_mount
908
    //
909
    // NOTE: the *first* mount is deliberately not exercised - it spawns a real
910
    // capture thread, and `ThreadInner`'s destructor joins that thread while its
911
    // receiver is still alive. `mic_worker` never reads its receiver and only
912
    // stops when a send fails, so the join would hang the test binary forever
913
    // (see the report). Only the guard paths below can be driven safely.
914
    // ------------------------------------------------------------------
915

            
916
    #[test]
917
    fn after_mount_ignores_a_dataset_that_is_not_a_microphone_state() {
918
        let (update, changes) =
919
            with_callback_info(|info| mic_on_after_mount(RefAny::new(0_u32), info));
920

            
921
        assert_eq!(update, Update::DoNothing);
922
        assert!(
923
            changes.is_empty(),
924
            "a foreign dataset must not start a capture thread"
925
        );
926
    }
927

            
928
    #[test]
929
    fn after_mount_is_a_no_op_once_the_capture_thread_has_started() {
930
        let mut data = state(cfg(0, 0), true);
931
        let (update, changes) = with_callback_info(|info| mic_on_after_mount(data.clone(), info));
932

            
933
        assert_eq!(update, Update::DoNothing);
934
        assert!(
935
            changes.is_empty(),
936
            "AfterMount must start the capture thread at most once"
937
        );
938
        assert_eq!(
939
            read_state(&mut data),
940
            (cfg(0, 0), true, false),
941
            "a re-mount must not rewrite the state"
942
        );
943
    }
944

            
945
    #[test]
946
    fn after_mount_starts_nothing_while_the_state_is_borrowed_elsewhere() {
947
        // A live shared borrow makes `downcast_mut` fail. The guard must bail out
948
        // (no thread, no panic) instead of unwrapping.
949
        let data = state(cfg(48_000, 2), false);
950
        let mut probe = data.clone();
951
        let guard = probe
952
            .downcast_ref::<MicrophoneWidgetState>()
953
            .expect("shared borrow");
954

            
955
        let (update, changes) = with_callback_info(|info| mic_on_after_mount(data.clone(), info));
956

            
957
        assert_eq!(update, Update::DoNothing);
958
        assert!(changes.is_empty(), "a borrowed state must not be mounted");
959
        assert!(!guard.started, "the state must still be untouched");
960
        drop(guard);
961

            
962
        let mut after = data;
963
        assert_eq!(read_state(&mut after), (cfg(48_000, 2), false, false));
964
    }
965

            
966
    // ------------------------------------------------------------------
967
    // mic_worker
968
    // ------------------------------------------------------------------
969

            
970
    #[test]
971
    fn worker_stops_after_the_first_rejected_send_and_tags_frames_with_its_init() {
972
        let (sent, tone_path) = run_worker(RefAny::new(MicThreadInit {
973
            sample_rate: 8_000,
974
            channels: 2,
975
        }));
976

            
977
        // Path-independent: a rejected send stops the loop, and every frame carries
978
        // the requested format plus the mic writeback.
979
        assert!(
980
            sent.len() <= 1,
981
            "the worker must stop after the first rejected send, not spin"
982
        );
983
        for f in &sent {
984
            assert_eq!((f.sample_rate, f.channels), (8_000, 2));
985
            assert_eq!(f.writeback, mic_writeback as WriteBackCallbackType as usize);
986
        }
987

            
988
        if !tone_path {
989
            return; // a platform backend is registered: not the test tone
990
        }
991
        assert_eq!(sent.len(), 1);
992
        let samples = &sent[0].samples;
993
        assert_eq!(
994
            samples.len(),
995
            expected_chunk_len(8_000, 2),
996
            "~20 ms of interleaved stereo at 8 kHz"
997
        );
998
        assert!(
999
            samples.iter().all(|s| s.is_finite() && s.abs() <= 0.2),
            "the tone must stay finite and inside +/-0.2"
        );
        assert_eq!(samples[0], 0.0, "the tone starts at phase 0");
        for pair in samples.chunks_exact(2) {
            assert_eq!(pair[0], pair[1], "both channels carry the same mono tone");
        }
    }
    #[test]
    fn worker_with_a_foreign_init_falls_back_to_48khz_mono() {
        let (sent, tone_path) = run_worker(RefAny::new(0_u64));
        for f in &sent {
            assert_eq!(
                (f.sample_rate, f.channels),
                (48_000, 1),
                "a bad init must not panic - it defaults"
            );
        }
        if !tone_path {
            return;
        }
        assert_eq!(sent.len(), 1);
        assert_eq!(sent[0].samples.len(), expected_chunk_len(48_000, 1));
    }
    #[test]
    fn worker_with_a_zero_sample_rate_emits_one_finite_chunk_instead_of_dividing_by_zero() {
        // rate 0 makes the phase step `2*PI*440/0.0` = +inf. The chunk length still
        // has to clamp to >= 1 frame, the emitted samples still have to be finite,
        // and the worker still has to terminate.
        let (sent, tone_path) = run_worker(RefAny::new(MicThreadInit {
            sample_rate: 0,
            channels: 1,
        }));
        // Path-independent: whatever produced the frame, it carries the requested
        // format.
        for f in &sent {
            assert_eq!((f.sample_rate, f.channels), (0, 1));
        }
        if !tone_path {
            return;
        }
        // Tone-path only, like every sibling worker test. `capture_common`'s
        // `register_mic_backend_is_first_wins_and_passes_f32_samples_through`
        // installs a process-wide `OnceLock` backend whose `read` deliberately
        // yields `[NaN, inf, -inf, -0.0]` to prove the vtable passes samples
        // through untouched. Once that test has run, `mic_worker` takes the
        // backend branch and never evaluates a phase step at all — so asserting
        // finiteness ABOVE the gate made this test fail depending on which other
        // test happened to run first in the same process. (It passed under
        // `cargo nextest`, which forks per test, and failed under `cargo test`,
        // which does not.)
        assert!(
            sent.iter().all(|f| f.samples.iter().all(|s| s.is_finite())),
            "an infinite phase step must not leak NaN/inf into the samples"
        );
        assert_eq!(sent.len(), 1);
        assert_eq!(sent[0].samples, vec![0.0_f32], "one frame, at phase 0");
    }
    #[test]
    fn worker_with_zero_channels_emits_an_empty_chunk_and_stops() {
        let (sent, tone_path) = run_worker(RefAny::new(MicThreadInit {
            sample_rate: 48_000,
            channels: 0,
        }));
        for f in &sent {
            assert_eq!(f.channels, 0);
        }
        if !tone_path {
            return;
        }
        assert_eq!(sent.len(), 1);
        assert!(
            sent[0].samples.is_empty(),
            "0 channels interleaves 0 samples per frame"
        );
        // The frame such a worker produces must still be safe to inspect.
        assert_eq!(frame(48_000, 0, sent[0].samples.clone()).frame_count(), 0);
    }
    #[test]
    fn worker_chunk_length_clamps_to_one_frame_for_sub_50hz_rates() {
        // `rate / 50` truncates to 0 below 50 Hz; without the `.max(1)` the worker
        // would emit empty chunks forever.
        for (rate, channels, expected) in [
            (1_u32, 1_u16, 1_usize),
            (49, 1, 1),
            (50, 1, 1),
            (99, 2, 2),
            (100, 2, 4),
            (100, 3, 6),
        ] {
            let (sent, tone_path) = run_worker(RefAny::new(MicThreadInit {
                sample_rate: rate,
                channels,
            }));
            if !tone_path {
                return;
            }
            assert_eq!(sent.len(), 1, "rate {rate} must emit exactly one chunk");
            assert_eq!(
                sent[0].samples.len(),
                expected,
                "rate {rate} x {channels} ch must clamp to >= 1 frame"
            );
            assert_eq!(expected_chunk_len(rate, channels), expected);
            assert!(
                sent[0]
                    .samples
                    .iter()
                    .all(|s| s.is_finite() && s.abs() <= 0.2),
                "a phase step larger than a full period must still yield bounded samples"
            );
        }
    }
    // ------------------------------------------------------------------
    // mic_writeback
    // ------------------------------------------------------------------
    #[test]
    fn writeback_hands_the_frame_to_the_hook_and_returns_its_update() {
        let mut log = new_log();
        let data = state_with_hook(cfg(44_100, 2), true, &log);
        let frame_data = RefAny::new(frame(44_100, 2, vec![0.25, -0.25, 0.5, -0.5]));
        let (update, _) =
            with_callback_info(|info| mic_writeback(data.clone(), frame_data.clone(), info));
        assert_eq!(update, Update::RefreshDom, "the hook's Update must win");
        assert_eq!(
            logged_frames(&mut log),
            vec![(44_100, 2, vec![0.25, -0.25, 0.5, -0.5])]
        );
    }
    #[test]
    fn writeback_without_a_hook_is_a_no_op() {
        let data = state(cfg(48_000, 1), true);
        let frame_data = RefAny::new(frame(48_000, 1, vec![0.0; 8]));
        let (update, changes) =
            with_callback_info(|info| mic_writeback(data.clone(), frame_data.clone(), info));
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "audio has no texture - nothing to change"
        );
    }
    #[test]
    fn writeback_ignores_frame_data_of_the_wrong_type() {
        let mut log = new_log();
        let data = state_with_hook(cfg(48_000, 1), true, &log);
        let (update, changes) =
            with_callback_info(|info| mic_writeback(data.clone(), RefAny::new(0_u32), info));
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(
            logged_frames(&mut log).is_empty(),
            "the user hook must not fire without a frame"
        );
    }
    #[test]
    fn writeback_survives_a_writeback_dataset_that_is_not_a_microphone_state() {
        let (update, changes) = with_callback_info(|info| {
            mic_writeback(
                RefAny::new(0_u32),
                RefAny::new(frame(8_000, 1, vec![0.0])),
                info,
            )
        });
        assert_eq!(
            update,
            Update::DoNothing,
            "a foreign dataset means no hook - but no panic either"
        );
        assert!(changes.is_empty());
    }
    #[test]
    fn writeback_forwards_a_malformed_frame_to_the_hook_untouched() {
        // Hostile payload: a rate/channel count that no device produces, no samples,
        // NaN-free but nonsensical. The writeback is a transport - it must neither
        // validate nor panic.
        let mut log = new_log();
        let data = state_with_hook(cfg(48_000, 2), true, &log);
        let bogus = RefAny::new(frame(u32::MAX, u16::MAX, Vec::new()));
        let (update, _) =
            with_callback_info(|info| mic_writeback(data.clone(), bogus.clone(), info));
        assert_eq!(update, Update::RefreshDom);
        assert_eq!(
            logged_frames(&mut log),
            vec![(u32::MAX, u16::MAX, Vec::new())]
        );
    }
    #[test]
    fn writeback_is_a_no_op_while_the_state_is_mutably_borrowed() {
        let mut log = new_log();
        let data = state_with_hook(cfg(48_000, 1), true, &log);
        let mut probe = data.clone();
        let guard = probe
            .downcast_mut::<MicrophoneWidgetState>()
            .expect("exclusive borrow");
        let frame_data = RefAny::new(frame(48_000, 1, vec![0.1]));
        let (update, changes) =
            with_callback_info(|info| mic_writeback(data.clone(), frame_data.clone(), info));
        assert_eq!(
            update,
            Update::DoNothing,
            "a blocked downcast must not panic"
        );
        assert!(changes.is_empty());
        drop(guard);
        assert!(logged_frames(&mut log).is_empty());
    }
    // ------------------------------------------------------------------
    // merge_microphone_state
    // ------------------------------------------------------------------
    #[test]
    fn merge_takes_started_from_old_and_everything_else_from_new() {
        let log = new_log();
        let new_data = state_with_hook(cfg(44_100, 2), false, &log);
        let old_data = state(cfg(8_000, 1), true);
        let mut merged = merge_microphone_state(new_data, old_data);
        assert_eq!(
            read_state(&mut merged),
            (cfg(44_100, 2), true, true),
            "config + hook come from the fresh build, 'started' from the old state"
        );
    }
    #[test]
    fn merge_takes_started_from_old_even_when_that_clears_it() {
        // The old state is authoritative for the thread flag in both directions -
        // otherwise a remount could start a second capture thread.
        let new_data = state(cfg(48_000, 1), true);
        let old_data = state(cfg(48_000, 1), false);
        let mut merged = merge_microphone_state(new_data, old_data);
        assert!(!read_state(&mut merged).1);
    }
    #[test]
    fn merge_returns_the_new_allocation_itself_not_a_copy() {
        let new_data = state(cfg(48_000, 1), false);
        let handle = new_data.clone();
        let merged = merge_microphone_state(new_data, state(cfg(48_000, 1), true));
        assert_eq!(merged, handle, "merge must hand back the same state object");
    }
    #[test]
    fn merge_leaves_the_new_state_alone_when_the_old_one_is_foreign() {
        let new_data = state(cfg(48_000, 2), true);
        let mut merged = merge_microphone_state(new_data, RefAny::new(0_u32));
        assert_eq!(
            read_state(&mut merged),
            (cfg(48_000, 2), true, false),
            "nothing to carry forward from a foreign payload"
        );
    }
    #[test]
    fn merge_returns_a_foreign_new_dataset_untouched() {
        let old_data = state(cfg(48_000, 1), true);
        let mut merged = merge_microphone_state(RefAny::new(77_u32), old_data);
        assert_eq!(
            merged.downcast_ref::<u32>().map(|v| *v),
            Some(77),
            "merge must hand back exactly the payload it was given"
        );
    }
    #[test]
    fn merge_of_a_dataset_with_itself_does_not_panic() {
        // The same RefAny on both sides: the mutable + shared borrow overlap, so the
        // merge is skipped rather than aliasing. Either way the state must survive.
        let mut data = state_with_hook(cfg(48_000, 2), true, &new_log());
        let mut merged = merge_microphone_state(data.clone(), data.clone());
        assert_eq!(read_state(&mut merged), (cfg(48_000, 2), true, true));
        assert_eq!(read_state(&mut data), (cfg(48_000, 2), true, true));
    }
    #[test]
    fn a_rebuilt_dom_merges_the_running_thread_flag_forward() {
        // The relayout round trip, through the callbacks `dom()` actually wires:
        // mount marks `started`, the fresh build starts at `false`, and the merge
        // carries the flag across so AfterMount cannot start a second thread.
        let old = MicrophoneWidget::create(cfg(48_000, 1)).dom();
        let mut old_ds = old.root.get_dataset().cloned().expect("dataset");
        {
            let mut s = old_ds
                .downcast_mut::<MicrophoneWidgetState>()
                .expect("state");
            s.started = true;
        }
        let new = MicrophoneWidget::create(cfg(44_100, 2))
            .with_on_frame(new_log(), record_frame as OnAudioFrameCallbackType)
            .dom();
        let new_ds = new.root.get_dataset().cloned().expect("dataset");
        let merge = new.root.get_merge_callback().expect("merge callback");
        let mut merged = (merge.cb)(new_ds, old_ds);
        assert_eq!(
            read_state(&mut merged),
            (cfg(44_100, 2), true, true),
            "the rebuilt widget keeps its new config + hook but inherits the thread"
        );
    }
    /// REGRESSION (B3): a capture worker must ACKNOWLEDGE `TerminateThread`.
    ///
    /// Reported from azul-meet on macOS after using camera + screenshare — the
    /// framework printed, twice (once per capture worker):
    ///
    /// ```text
    /// [azul][thread] a background thread did not acknowledge TerminateThread
    /// within 2000ms and was DETACHED rather than joined.
    /// ```
    ///
    /// Root cause: the worker took its receiver as `_recv` and never polled it,
    /// so the terminate message was never observed. The only exit was
    /// `sender.send()` returning false, which does NOT happen at shutdown
    /// because the main thread still owns the receiving end while it waits out
    /// the grace period. Fixed by `capture_common::terminate_requested`.
    ///
    /// The budget here is the framework's own:
    /// `THREAD_TERMINATE_GRACE_STEPS (200) * 10ms = 2000ms`.
    #[test]
    fn mic_worker_acknowledges_terminate_within_the_grace_budget() {
        use crate::thread::{Thread, ThreadCallback};
        let t = Thread::create(
            RefAny::new(MicThreadInit {
                sample_rate: 8_000,
                channels: 1,
            }),
            RefAny::new(0_usize),
            ThreadCallback::new(mic_worker),
        );
        assert!(
            t.send_message(ThreadSendMsg::TerminateThread),
            "the worker holds its receiver alive, so the send must succeed"
        );
        let finished = || {
            t.ptr
                .lock()
                .expect("thread mutex must not be poisoned")
                .is_finished()
        };
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(2_000);
        while !finished() && std::time::Instant::now() < deadline {
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        assert!(
            finished(),
            "mic_worker did not acknowledge TerminateThread within 2000ms — at shutdown it would \
             be DETACHED rather than joined"
        );
    }
}