alpha2-host-core 0.10.0

FFmpeg-free native host logic for alpha2: the policies, audio timelines, cursor rules, providers, plugin runtime, protocol frames and request parsing native hosts share, and the decode, export and still pipeline the mobile hosts run.
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
//! Project audio for a real-time preview: a thread mixes ahead into a ring that the output
//! callback drains, and the samples the device took drive the preview's clock.
//!
//! The callback only copies from the ring, so it never allocates or waits; when the mix falls
//! behind it plays silence and counts the shortfall. Before rendering a block the mix thread makes
//! ready the audio it reads, so sources are decoded in windows as the mix reaches them.

use std::collections::VecDeque;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use alpha2_audio::{ProcessCtx, TransportState};
use alpha2_engine::{AudioRenderer, EngineProject, NodeLevels};
use alpha2_media::{AudioBlock, CancelToken};

use crate::audio_host::{CpalHostError, CpalOutputHost, ProjectAudioSources, RealtimeAudioSource};

/// Stereo frames the ring holds: a fifth of a second at 48 kHz, enough to ride out a busy mix
/// thread without delaying a seek much.
const RING_FRAMES: usize = 1 << 13;

/// Frames mixed at a time.
const MIX_BLOCK: usize = 1024;

/// Failures of one block in a row, 5 ms apart, after which the mix stops and the output plays
/// silence.
const MAX_CONSECUTIVE_MIX_FAILURES: u32 = 10;

const MOST_WAITING_LEVELS: usize = 64;

/// The levels of one mixed block.
#[derive(Clone, Debug, PartialEq)]
pub struct BlockLevels {
    /// The project sample the block starts at.
    pub start_sample: i64,
    /// How many samples the block holds.
    pub frames: usize,
    /// Every track and bus the mix runs, then the master, as [`AudioRenderer::levels`] gives them.
    pub nodes: Vec<NodeLevels>,
}

/// Why the mix failed last.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MixFailure {
    /// The renderer's or the sources' error.
    pub message: String,
    /// Failures in a row up to now; 0 once a later block mixed.
    pub consecutive: u32,
    /// Whether the mix gave up after 10 failures in a row.
    pub stopped: bool,
}

/// The ring between the mix thread and the output callback: interleaved stereo samples as bits,
/// with monotonic counts of frames written and read. A frame is written before the count that
/// covers it is released and read after it is acquired, so the samples need no ordering of their
/// own.
struct Ring {
    samples: Box<[AtomicU32]>,
    written: AtomicU64,
    read: AtomicU64,
    /// Frames below this count are dropped unread: a reposition discarded them.
    discard: AtomicU64,
    /// Frames the callback wanted and the ring did not have.
    short: AtomicU64,
}

impl Ring {
    fn new() -> Self {
        Self {
            samples: (0..RING_FRAMES * 2).map(|_| AtomicU32::new(0)).collect(),
            written: AtomicU64::new(0),
            read: AtomicU64::new(0),
            discard: AtomicU64::new(0),
            short: AtomicU64::new(0),
        }
    }

    fn put(&self, frame: u64, left: f32, right: f32) {
        let at = usize::try_from(frame % RING_FRAMES as u64).unwrap_or(0) * 2;
        self.samples[at].store(left.to_bits(), Ordering::Relaxed);
        self.samples[at + 1].store(right.to_bits(), Ordering::Relaxed);
    }

    fn get(&self, frame: u64) -> [f32; 2] {
        let at = usize::try_from(frame % RING_FRAMES as u64).unwrap_or(0) * 2;
        [
            f32::from_bits(self.samples[at].load(Ordering::Relaxed)),
            f32::from_bits(self.samples[at + 1].load(Ordering::Relaxed)),
        ]
    }
}

/// Plays the ring.
struct RingSource(Arc<Ring>);

impl RealtimeAudioSource for RingSource {
    fn render(&mut self, _ctx: &ProcessCtx, output: &mut [&mut [f32]]) {
        let ring = &self.0;
        let frames = output.first().map_or(0, |plane| plane.len());
        let read = ring
            .read
            .load(Ordering::Acquire)
            .max(ring.discard.load(Ordering::Acquire));
        let available = ring.written.load(Ordering::Acquire) - read;
        let taken = usize::try_from(available).unwrap_or(usize::MAX).min(frames);
        for index in 0..taken {
            let frame = ring.get(read + index as u64);
            for (channel, plane) in output.iter_mut().enumerate() {
                plane[index] = frame[channel.min(1)];
            }
        }
        for plane in output.iter_mut() {
            plane[taken..].fill(0.0);
        }
        ring.read.store(read + taken as u64, Ordering::Release);
        if taken < frames {
            ring.short
                .fetch_add((frames - taken) as u64, Ordering::Relaxed);
        }
    }
}

/// A project's mix ahead of the output: each block makes ready what it reads, then renders.
pub struct Mixer<S> {
    snapshot: EngineProject,
    renderer: AudioRenderer,
    sources: S,
    levels: bool,
}

impl<S: ProjectAudioSources> Mixer<S> {
    /// A stereo mix of `snapshot` reading `sources`.
    ///
    /// # Errors
    /// The renderer's refusal of the project.
    pub fn new(snapshot: EngineProject, sources: S) -> Result<Self, String> {
        let renderer =
            AudioRenderer::new(&snapshot, 2, MIX_BLOCK).map_err(|error| error.to_string())?;
        Ok(Self {
            snapshot,
            renderer,
            sources,
            levels: false,
        })
    }

    /// Measures the levels of each block from the next on, or stops.
    pub fn set_levels(&mut self, enabled: bool) {
        self.levels = enabled;
        self.renderer.set_levels(enabled);
    }

    /// The levels of the last block, empty while levels are off.
    #[must_use]
    pub fn levels(&self) -> &[NodeLevels] {
        self.renderer.levels()
    }

    /// Mixes `snapshot` from the next block on, its sources the ones `rebind` leaves.
    ///
    /// # Errors
    /// The renderer's refusal of the project; the mix is then unchanged.
    pub fn replace(
        &mut self,
        snapshot: EngineProject,
        rebind: impl FnOnce(&mut S),
    ) -> Result<(), String> {
        let mut renderer =
            AudioRenderer::new(&snapshot, 2, MIX_BLOCK).map_err(|error| error.to_string())?;
        renderer.set_levels(self.levels);
        self.renderer = renderer;
        self.snapshot = snapshot;
        rebind(&mut self.sources);
        Ok(())
    }

    /// The mix of `frames` frames, at most [`MIX_BLOCK`], from project sample `at`.
    ///
    /// # Errors
    /// What making the sources ready or rendering met, or a cancel by `cancel`.
    pub fn block(
        &mut self,
        at: i64,
        frames: usize,
        cancel: &CancelToken,
    ) -> Result<AudioBlock, String> {
        let frames = frames.min(MIX_BLOCK);
        let needs = self
            .renderer
            .audio_needs(&self.snapshot, at, frames)
            .map_err(|error| error.to_string())?;
        self.sources
            .prepare(&needs, cancel)
            .map_err(|error| error.to_string())?;
        let status = self
            .renderer
            .render(
                &self.snapshot,
                at,
                frames,
                &self.sources,
                TransportState::Playing,
            )
            .map_err(|error| error.to_string())?;
        Ok(self.renderer.block(&status))
    }
}

type Rebind<S> = Box<dyn FnOnce(&mut S) + Send>;

/// Where the mix thread mixes, set by the player's thread.
struct Control<S> {
    /// The project sample the next block starts at.
    next: i64,
    /// Bumped by every reposition; a block of an older one is dropped.
    generation: u64,
    running: bool,
    /// Stops the current reposition's source preparation.
    cancel: CancelToken,
    ended: bool,
    replacement: Option<(EngineProject, Rebind<S>)>,
    looped: Option<(i64, i64)>,
    levels: Option<bool>,
    measured: VecDeque<(u64, BlockLevels)>,
}

struct MixThread<S> {
    ring: Arc<Ring>,
    control: Arc<(Mutex<Control<S>>, Condvar)>,
    failure: Arc<Mutex<Option<MixFailure>>>,
    thread: Option<JoinHandle<()>>,
}

impl<S: ProjectAudioSources + Send + 'static> MixThread<S> {
    fn spawn(
        ring: Arc<Ring>,
        mixer: Mixer<S>,
        start_sample: i64,
        looped: Option<(i64, i64)>,
    ) -> std::io::Result<Self> {
        let control = Arc::new((
            Mutex::new(Control {
                next: start_sample,
                generation: 0,
                running: true,
                cancel: CancelToken::default(),
                ended: false,
                replacement: None,
                looped,
                levels: None,
                measured: VecDeque::new(),
            }),
            Condvar::new(),
        ));
        let failure = Arc::new(Mutex::new(None));
        let (mixer_ring, mixer_control, mixer_failure) = (
            Arc::clone(&ring),
            Arc::clone(&control),
            Arc::clone(&failure),
        );
        let thread = std::thread::Builder::new()
            .name("alpha2-preview-audio".into())
            .spawn(move || {
                let mut mixer = mixer;
                let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    mix(&mut mixer, &mixer_ring, &mixer_control, &mixer_failure);
                }));
                if let Err(payload) = ran {
                    *lock(&mixer_failure) = Some(MixFailure {
                        message: format!(
                            "the mix thread panicked: {}",
                            crate::panic_text(&*payload)
                        ),
                        consecutive: 0,
                        stopped: true,
                    });
                }
            })?;
        Ok(Self {
            ring,
            control,
            failure,
            thread: Some(thread),
        })
    }

    fn pause(&self) {
        let mut control = lock(&self.control.0);
        control.running = false;
        control.cancel.cancel();
    }

    fn reposition(&self, sample: i64) -> u64 {
        let (control, changed) = &*self.control;
        let mut control = lock(control);
        control.cancel.cancel();
        control.cancel = CancelToken::default();
        control.generation += 1;
        control.next = sample;
        control.running = true;
        let written = self.ring.written.load(Ordering::Acquire);
        self.ring.discard.store(written, Ordering::Release);
        control.measured.clear();
        changed.notify_all();
        written
    }

    fn replace(&self, snapshot: EngineProject, rebind: impl FnOnce(&mut S) + Send + 'static) {
        let mut control = lock(&self.control.0);
        control.replacement = Some((snapshot, Box::new(rebind)));
    }

    fn set_loop(&self, looped: Option<(i64, i64)>) {
        lock(&self.control.0).looped = looped.filter(|(start, end)| start < end);
    }

    fn set_levels(&self, enabled: bool) {
        let mut control = lock(&self.control.0);
        control.levels = Some(enabled);
        if !enabled {
            control.measured.clear();
        }
    }

    fn levels_before(&self, frame: u64) -> Vec<BlockLevels> {
        let mut control = lock(&self.control.0);
        let reached = control
            .measured
            .iter()
            .take_while(|(at, _)| *at <= frame)
            .count();
        control
            .measured
            .drain(..reached)
            .map(|(_, levels)| levels)
            .collect()
    }
}

impl<S> Drop for MixThread<S> {
    fn drop(&mut self) {
        {
            let (control, changed) = &*self.control;
            let mut control = lock(control);
            control.ended = true;
            control.cancel.cancel();
            changed.notify_all();
        }
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

/// A project's audio on the default output, one stream for the preview's life: paused,
/// repositioned and given a new project in place.
pub struct PreviewAudio<S> {
    mix: MixThread<S>,
    host: CpalOutputHost,
    looped: Option<(i64, i64)>,
    start_sample: i64,
    origin: u64,
}

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

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

impl<S: ProjectAudioSources + Send + 'static> PreviewAudio<S> {
    /// Starts `snapshot`'s mix of `sources` at project sample `start_sample` on the default
    /// output, with `looped` and `levels` as [`Self::set_loop`] and [`Self::set_levels`] take them.
    ///
    /// # Errors
    /// No output device, none at the project rate, or a platform without audio output for this
    /// process (Android before the app hands over its context).
    pub fn start(
        snapshot: EngineProject,
        sources: S,
        start_sample: i64,
        looped: Option<(i64, i64)>,
        levels: bool,
    ) -> Result<Self, CpalHostError> {
        let rate = snapshot.project().settings.sample_rate;
        let ring = Arc::new(Ring::new());
        let host = open_output(RingSource(Arc::clone(&ring)), rate)?;
        let mut mixer = Mixer::new(snapshot, sources).map_err(CpalHostError::Device)?;
        mixer.set_levels(levels);
        let looped = looped.filter(|(start, end)| start < end);
        let mix = MixThread::spawn(ring, mixer, start_sample, looped)
            .map_err(|error| CpalHostError::Device(error.to_string()))?;
        let audio = Self {
            mix,
            host,
            looped,
            start_sample,
            origin: 0,
        };
        audio.begin()?;
        Ok(audio)
    }

    /// Plays once the first blocks are in, so playback does not open on silence.
    fn begin(&self) -> Result<(), CpalHostError> {
        let until = Instant::now() + Duration::from_millis(200);
        let wanted = self.origin + (MIX_BLOCK * 2) as u64;
        while self.mix.ring.written.load(Ordering::Acquire) < wanted && Instant::now() < until {
            std::thread::sleep(Duration::from_millis(1));
        }
        self.host.play()
    }

    /// Stops the output and the mix where they are; [`Self::reposition`] plays again.
    ///
    /// # Errors
    /// The device error cpal reports.
    pub fn pause(&mut self) -> Result<(), CpalHostError> {
        self.mix.pause();
        self.host.pause()
    }

    /// Plays from project sample `sample`: the mix stops at its block boundary, the ring's
    /// unplayed frames are dropped, and the mix starts again there.
    ///
    /// # Errors
    /// The device error cpal reports.
    pub fn reposition(&mut self, sample: i64) -> Result<(), CpalHostError> {
        self.origin = self.mix.reposition(sample);
        self.start_sample = sample;
        self.begin()
    }

    /// Mixes `snapshot` from the next block on, with the sources `rebind` leaves of the current
    /// ones; `snapshot` must have the sample rate the output opened at.
    pub fn replace(&self, snapshot: EngineProject, rebind: impl FnOnce(&mut S) + Send + 'static) {
        self.mix.replace(snapshot, rebind);
    }

    /// Mixes the project samples `start..end` over and over, without a gap, from the next
    /// [`Self::reposition`] on, which must be within them; `None` mixes straight on again.
    pub fn set_loop(&mut self, looped: Option<(i64, i64)>) {
        self.looped = looped.filter(|(start, end)| start < end);
        self.mix.set_loop(self.looped);
    }

    /// The project sample the listener hears now: where playing started, plus what the device
    /// took since, less the output's latency, taken round the loop if one is set.
    #[must_use]
    pub fn heard_sample(&self) -> i64 {
        looped_sample(self.heard_run_sample(), self.looped)
    }

    /// The sample [`Self::heard_sample`] would be if the loop did not wrap: it only grows while
    /// playing, by what the device took.
    #[must_use]
    pub fn heard_run_sample(&self) -> i64 {
        let read = self.mix.ring.read.load(Ordering::Acquire);
        let taken = i64::try_from(read.saturating_sub(self.origin)).unwrap_or(i64::MAX);
        self.start_sample + taken - i64::from(self.host.latency_samples())
    }

    /// Whether the ring holds mixed samples the device has not taken.
    #[must_use]
    pub fn buffered(&self) -> bool {
        let ring = &self.mix.ring;
        let read = ring
            .read
            .load(Ordering::Acquire)
            .max(ring.discard.load(Ordering::Acquire));
        ring.written.load(Ordering::Acquire) > read
    }

    /// Output frames that played silent because the mix fell behind, plus stream errors.
    #[must_use]
    pub fn shortfall(&self) -> u64 {
        self.mix.ring.short.load(Ordering::Relaxed) + self.host.underruns()
    }

    /// The last error the output stream reported, `None` while it reported none.
    #[must_use]
    pub fn stream_error(&self) -> Option<String> {
        self.host.stream_error()
    }

    /// The mix's last failure, `None` while every block mixed.
    #[must_use]
    pub fn last_error(&self) -> Option<MixFailure> {
        lock(&self.mix.failure).clone()
    }

    /// Measures the levels of every track, bus and the master in each block mixed from now on,
    /// or stops and drops the levels not handed out.
    pub fn set_levels(&self, enabled: bool) {
        self.mix.set_levels(enabled);
    }

    /// The levels of the blocks whose first sample the listener hears now or heard, oldest first,
    /// each handed out once. A reposition drops the levels of what was mixed and not played.
    #[must_use]
    pub fn levels_heard(&self) -> Vec<BlockLevels> {
        let read = self.mix.ring.read.load(Ordering::Acquire);
        self.mix
            .levels_before(read.saturating_sub(u64::from(self.host.latency_samples())))
    }
}

/// Where `sample`, counted on as if `looped` did not wrap, falls within the loop.
#[must_use]
pub fn looped_sample(sample: i64, looped: Option<(i64, i64)>) -> i64 {
    match looped {
        Some((start, end)) if sample >= end && start < end => {
            start + (sample - start).rem_euclid(end - start)
        }
        _ => sample,
    }
}

/// Opens the default output playing `source` at `rate`.
#[cfg(not(target_os = "android"))]
fn open_output(source: RingSource, rate: u32) -> Result<CpalOutputHost, CpalHostError> {
    CpalOutputHost::open(source, rate, MIX_BLOCK)
}

/// Opens the default output playing `source` at `rate`.
///
/// cpal panics on Android before the app hands its context to `ndk_context`, which offers no way
/// to ask first; that panic is an output that cannot open, reported with its message.
#[cfg(target_os = "android")]
fn open_output(source: RingSource, rate: u32) -> Result<CpalOutputHost, CpalHostError> {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        CpalOutputHost::open(source, rate, MIX_BLOCK)
    }))
    .unwrap_or_else(|payload| {
        Err(CpalHostError::Device(format!(
            "this process has no audio output: {}",
            crate::panic_text(&*payload)
        )))
    })
}

fn keep_levels(
    measured: &mut VecDeque<(u64, BlockLevels)>,
    nodes: &[NodeLevels],
    written: u64,
    start_sample: i64,
    frames: usize,
) {
    if nodes.is_empty() {
        return;
    }
    if measured.len() >= MOST_WAITING_LEVELS {
        measured.pop_front();
    }
    measured.push_back((
        written,
        BlockLevels {
            start_sample,
            frames,
            nodes: nodes.to_vec(),
        },
    ));
}

/// Mixes ahead of the callback until the audio drops, or until one block fails
/// [`MAX_CONSECUTIVE_MIX_FAILURES`] times in a row.
fn mix<S: ProjectAudioSources>(
    mixer: &mut Mixer<S>,
    ring: &Ring,
    control: &(Mutex<Control<S>>, Condvar),
    failure: &Mutex<Option<MixFailure>>,
) {
    let (control, changed) = control;
    let mut consecutive = 0_u32;
    loop {
        let (at, generation, cancel, replacement, looped, levels) = {
            let mut state = lock(control);
            while !state.running && !state.ended {
                state = changed.wait(state).unwrap_or_else(PoisonError::into_inner);
            }
            if state.ended {
                return;
            }
            (
                state.next,
                state.generation,
                state.cancel.clone(),
                state.replacement.take(),
                state.looped,
                state.levels.take(),
            )
        };
        if let Some(enabled) = levels {
            mixer.set_levels(enabled);
        }
        let wanted = looped
            .filter(|&(_, end)| at < end)
            .map_or(MIX_BLOCK, |(_, end)| {
                usize::try_from(end - at).map_or(MIX_BLOCK, |left| left.min(MIX_BLOCK))
            });
        if let Some((snapshot, rebind)) = replacement
            && let Err(message) = mixer.replace(snapshot, rebind)
        {
            *lock(failure) = Some(MixFailure {
                message: format!("the new project's audio does not mix: {message}"),
                consecutive: 0,
                stopped: false,
            });
        }
        let free = RING_FRAMES as u64
            - (ring.written.load(Ordering::Acquire)
                - ring
                    .read
                    .load(Ordering::Acquire)
                    .max(ring.discard.load(Ordering::Acquire)));
        if free < MIX_BLOCK as u64 {
            std::thread::sleep(Duration::from_millis(5));
            continue;
        }
        let block = mixer.block(at, wanted, &cancel);
        let state = lock(control);
        if state.generation != generation || !state.running || state.ended {
            continue;
        }
        let block = match block {
            Ok(block) => block,
            Err(message) => {
                drop(state);
                consecutive += 1;
                let stopped = consecutive >= MAX_CONSECUTIVE_MIX_FAILURES;
                *lock(failure) = Some(MixFailure {
                    message,
                    consecutive,
                    stopped,
                });
                if stopped {
                    return;
                }
                std::thread::sleep(Duration::from_millis(5));
                continue;
            }
        };
        if std::mem::take(&mut consecutive) > 0
            && let Some(last) = lock(failure).as_mut()
        {
            last.consecutive = 0;
        }
        let written = ring.written.load(Ordering::Acquire);
        let frames = block.channels.first().map_or(0, Vec::len);
        let mut state = state;
        if state.levels != Some(false) {
            keep_levels(&mut state.measured, mixer.levels(), written, at, frames);
        }
        for index in 0..frames {
            let left = block.channels[0][index];
            let right = block.channels.get(1).map_or(left, |plane| plane[index]);
            ring.put(written + index as u64, left, right);
        }
        ring.written
            .store(written + frames as u64, Ordering::Release);
        let next = at + i64::try_from(frames).unwrap_or(0);
        state.next = match looped {
            Some((start, end)) if next >= end => start,
            _ => next,
        };
    }
}

#[cfg(test)]
#[path = "preview_audio_tests.rs"]
mod tests;