Skip to main content

alpha2_host_core/
audio_host.rs

1use std::collections::HashMap;
2
3use alpha2_audio::{AudioGraph, ChannelLayout, ProcessCtx, TransportState};
4#[cfg(feature = "engine")]
5use alpha2_engine::{AudioRenderer, AudioTap, EngineProject};
6use alpha2_media::{
7    AudioBlock, AudioBlockProvider, AudioBlockSink, AudioSpan, CancelToken, EncodeError, SourceId,
8};
9use alpha2_time::{MediaTime, TICKS_PER_SECOND};
10
11/// Native offline-render failure.
12#[derive(Clone, Debug, Eq, PartialEq)]
13#[non_exhaustive]
14pub enum OfflineAudioError {
15    /// Input channel count or length is invalid.
16    InvalidInput,
17    /// Sink rejected a block.
18    Sink(EncodeError),
19    /// The project could not be mixed at the requested configuration.
20    #[cfg(feature = "engine")]
21    Engine(alpha2_engine::EngineError),
22    /// An audible clip needed media the caller had not decoded.
23    MissingSources(Vec<SourceId>),
24    /// The sources could not make ready what a block reads.
25    #[cfg(feature = "engine")]
26    Sources(crate::audio_windows::AudioWindowError),
27}
28
29impl std::fmt::Display for OfflineAudioError {
30    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        match self {
32            Self::InvalidInput => formatter.write_str("offline audio input is invalid"),
33            Self::Sink(error) => write!(formatter, "offline audio sink failed: {error}"),
34            #[cfg(feature = "engine")]
35            Self::Engine(error) => write!(formatter, "offline audio rendering failed: {error}"),
36            #[cfg(feature = "engine")]
37            Self::Sources(error) => write!(formatter, "offline audio sources failed: {error}"),
38            Self::MissingSources(sources) => {
39                write!(
40                    formatter,
41                    "offline audio is missing {} sources",
42                    sources.len()
43                )
44            }
45        }
46    }
47}
48
49impl std::error::Error for OfflineAudioError {
50    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51        match self {
52            Self::Sink(error) => Some(error),
53            #[cfg(feature = "engine")]
54            Self::Engine(error) => Some(error),
55            #[cfg(feature = "engine")]
56            Self::Sources(error) => Some(error),
57            _ => None,
58        }
59    }
60}
61
62/// Decoded, project-rate planar audio held per source audio stream for offline mixing; one
63/// whole-stream block each, indexed by absolute source position.
64#[derive(Default)]
65pub struct DecodedAudioSources {
66    sources: HashMap<(SourceId, Option<u32>), AudioBlock>,
67}
68
69impl DecodedAudioSources {
70    /// Creates an empty cache.
71    #[must_use]
72    pub fn new() -> Self {
73        Self::default()
74    }
75
76    /// Retains one source's decoded default audio stream, replacing any earlier block.
77    pub fn insert(&mut self, source: SourceId, block: AudioBlock) {
78        self.sources.insert((source, None), block);
79    }
80
81    /// Retains audio stream `stream` of a source (`AudioProperties::stream`), replacing any
82    /// earlier block.
83    pub fn insert_stream(&mut self, source: SourceId, stream: Option<u32>, block: AudioBlock) {
84        self.sources.insert((source, stream), block);
85    }
86
87    /// Drops every stream of one source's decoded audio.
88    pub fn remove(&mut self, source: &SourceId) -> bool {
89        let before = self.sources.len();
90        self.sources.retain(|(held, _), _| held != source);
91        self.sources.len() != before
92    }
93
94    /// Returns how many source streams are retained.
95    #[must_use]
96    pub fn len(&self) -> usize {
97        self.sources.len()
98    }
99
100    /// Returns whether no source is retained.
101    #[must_use]
102    pub fn is_empty(&self) -> bool {
103        self.sources.is_empty()
104    }
105}
106
107/// Each block is its source's entire audio; outside it the source is silent.
108impl AudioBlockProvider for DecodedAudioSources {
109    fn block(
110        &self,
111        source: &SourceId,
112        stream: Option<u32>,
113        _start_sample: i64,
114        _frames: usize,
115    ) -> Option<AudioSpan<'_>> {
116        self.sources
117            .get(&(source.clone(), stream))
118            .map(AudioSpan::whole)
119    }
120}
121
122/// The audio a project mix reads: decoded whole ([`DecodedAudioSources`]), or held in windows a
123/// host fills as the mix reaches them ([`crate::audio_windows::WindowedAudioSources`]).
124#[cfg(feature = "engine")]
125pub trait ProjectAudioSources: AudioBlockProvider {
126    /// Makes ready what `needs` reads, before the block that reads it renders. Audio decoded
127    /// whole needs nothing.
128    ///
129    /// # Errors
130    /// What decoding or holding the audio met.
131    fn prepare(
132        &mut self,
133        _needs: &[alpha2_engine::AudioNeed],
134        _cancel: &CancelToken,
135    ) -> Result<(), crate::audio_windows::AudioWindowError> {
136        Ok(())
137    }
138}
139
140#[cfg(feature = "engine")]
141impl ProjectAudioSources for DecodedAudioSources {}
142
143/// One offline project-audio render request.
144#[cfg(feature = "engine")]
145#[derive(Copy, Clone, Debug, Eq, PartialEq)]
146pub struct ProjectAudioRequest<'a> {
147    /// Output channel count. One or two.
148    pub channels: usize,
149    /// Absolute project-rate sample index the range starts at, written as sample zero.
150    pub start_sample: i64,
151    /// Samples per channel to produce.
152    pub total_frames: usize,
153    /// Repeating block schedule, which may be irregular.
154    pub block_sizes: &'a [usize],
155    /// Tracks and buses to read beside the mix, for [`render_project_audio_with_taps`].
156    pub taps: &'a [AudioTap],
157}
158
159/// Mixes a whole project audio range and writes exact project-rate blocks.
160///
161/// The offline counterpart of the browser pump: `sources` makes ready what each block reads and
162/// the engine does gain, fades, panning, effects, bus summing and limiting. Irregular `block_sizes` repeat, so
163/// callers can prove the mix is independent of block size.
164///
165/// # Errors
166/// Returns [`OfflineAudioError::InvalidInput`] for an empty schedule or range,
167/// [`OfflineAudioError::Engine`] when the renderer rejects the configuration,
168/// [`OfflineAudioError::Sources`] when the sources cannot make a block's audio ready,
169/// [`OfflineAudioError::MissingSources`] when an audible clip had no decoded media, and
170/// [`OfflineAudioError::Sink`] when the destination rejects output.
171#[cfg(feature = "engine")]
172pub fn render_project_audio(
173    snapshot: &EngineProject,
174    request: &ProjectAudioRequest<'_>,
175    sources: &mut dyn ProjectAudioSources,
176    sink: &mut dyn AudioBlockSink,
177    cancel: &CancelToken,
178) -> Result<(), OfflineAudioError> {
179    render_project_audio_with_taps(snapshot, request, sources, sink, &mut [], cancel)
180}
181
182/// [`render_project_audio`], also writing each of `request.taps` into the sink at its position
183/// in `tap_sinks`: the same blocks as the mix's, sample for sample in line with them. A tap is
184/// read before the master, so it carries no master effects, gain or limiter.
185///
186/// # Errors
187/// As [`render_project_audio`]; [`OfflineAudioError::InvalidInput`] also when `tap_sinks` are
188/// not one per tap. Every sink is aborted when the render fails.
189#[cfg(feature = "engine")]
190pub fn render_project_audio_with_taps(
191    snapshot: &EngineProject,
192    request: &ProjectAudioRequest<'_>,
193    sources: &mut dyn ProjectAudioSources,
194    sink: &mut dyn AudioBlockSink,
195    tap_sinks: &mut [&mut dyn AudioBlockSink],
196    cancel: &CancelToken,
197) -> Result<(), OfflineAudioError> {
198    let ProjectAudioRequest {
199        channels,
200        start_sample,
201        total_frames,
202        block_sizes,
203        taps,
204    } = *request;
205    if total_frames == 0
206        || block_sizes.is_empty()
207        || block_sizes.contains(&0)
208        || start_sample < 0
209        || tap_sinks.len() != taps.len()
210    {
211        return Err(OfflineAudioError::InvalidInput);
212    }
213    let max_block = block_sizes.iter().copied().max().unwrap_or(1);
214    let mut renderer = AudioRenderer::with_taps(snapshot, channels, max_block, taps)
215        .map_err(OfflineAudioError::Engine)?;
216
217    let mut produced = 0;
218    let mut sequence = 0;
219    let mut missing: Vec<SourceId> = Vec::new();
220    while produced < total_frames {
221        if cancel.is_cancelled() {
222            abort_all(sink, tap_sinks)?;
223            return Err(OfflineAudioError::Sink(EncodeError::Cancelled));
224        }
225        let count = block_sizes[sequence % block_sizes.len()].min(total_frames - produced);
226        let offset = i64::try_from(produced).unwrap_or(i64::MAX);
227        let at = start_sample.saturating_add(offset);
228        let needs = renderer
229            .audio_needs(snapshot, at, count)
230            .map_err(OfflineAudioError::Engine)?;
231        sources
232            .prepare(&needs, cancel)
233            .map_err(OfflineAudioError::Sources)?;
234        let status = renderer
235            .render(snapshot, at, count, &*sources, TransportState::Playing)
236            .map_err(OfflineAudioError::Engine)?;
237        for source in &status.missing_sources {
238            if !missing.contains(source) {
239                missing.push(source.clone());
240            }
241        }
242        let mut block = renderer.block(&status);
243        // The range is its own file: its first sample is the sink's sample zero.
244        block.start_sample = offset;
245        sink.write_audio(&block, cancel)
246            .map_err(OfflineAudioError::Sink)?;
247        for (index, tap_sink) in tap_sinks.iter_mut().enumerate() {
248            if let Some(mut block) = renderer.tap_block(index, &status) {
249                block.start_sample = offset;
250                tap_sink
251                    .write_audio(&block, cancel)
252                    .map_err(OfflineAudioError::Sink)?;
253            }
254        }
255        produced += count;
256        sequence += 1;
257    }
258    if !missing.is_empty() {
259        // Report an incomplete mix rather than committing partial audio.
260        abort_all(sink, tap_sinks)?;
261        return Err(OfflineAudioError::MissingSources(missing));
262    }
263    sink.finish_audio(cancel).map_err(OfflineAudioError::Sink)?;
264    for tap_sink in tap_sinks {
265        tap_sink
266            .finish_audio(cancel)
267            .map_err(OfflineAudioError::Sink)?;
268    }
269    Ok(())
270}
271
272#[cfg(feature = "engine")]
273fn abort_all(
274    sink: &mut dyn AudioBlockSink,
275    tap_sinks: &mut [&mut dyn AudioBlockSink],
276) -> Result<(), OfflineAudioError> {
277    let mut aborted = sink.abort_audio();
278    for tap_sink in tap_sinks {
279        aborted = aborted.and(tap_sink.abort_audio());
280    }
281    aborted.map_err(OfflineAudioError::Sink)
282}
283
284/// Host sample representation considered during deterministic negotiation.
285#[derive(Copy, Clone, Debug, Eq, PartialEq)]
286pub enum HostSampleFormat {
287    /// Native 32-bit floating point.
288    F32,
289    /// Signed 16-bit integer.
290    I16,
291    /// Any format not supported by the realtime host.
292    Unsupported,
293}
294
295/// Platform-neutral device range used by negotiation tests and cpal mapping.
296#[derive(Copy, Clone, Debug, Eq, PartialEq)]
297pub struct HostAudioConfig {
298    /// Channel count.
299    pub channels: u16,
300    /// Lowest supported sample rate.
301    pub min_sample_rate: u32,
302    /// Highest supported sample rate.
303    pub max_sample_rate: u32,
304    /// Device sample representation.
305    pub format: HostSampleFormat,
306}
307
308/// Selects an output that plays stereo, requiring exact project-rate `f32` support.
309///
310/// Prefers exactly two channels, then the fewest above two, then mono. Backends list counts
311/// differently (ALSA every count, WASAPI only the mix format's, `CoreAudio` the sum of stream
312/// channels), so a multichannel device may offer no stereo entry; stereo then goes to its first two
313/// channels (front left and right on all three) and the rest are silent.
314#[must_use]
315pub fn negotiate_output_config(
316    configs: &[HostAudioConfig],
317    project_rate: u32,
318) -> Option<HostAudioConfig> {
319    configs
320        .iter()
321        .copied()
322        .filter(|config| {
323            config.format == HostSampleFormat::F32
324                && config.channels > 0
325                && (config.min_sample_rate..=config.max_sample_rate).contains(&project_rate)
326        })
327        .min_by_key(|config| match config.channels {
328            2 => (0, 0),
329            1 => (2, 0),
330            more => (1, more),
331        })
332}
333
334/// Runs the same graph used by realtime hosts and writes exact project-rate blocks.
335///
336/// `inputs` are the graph's buses flattened, each bus's planes in the graph's layout; all channels
337/// must have the same length. Irregular `block_sizes` repeat until the source is exhausted.
338///
339/// # Errors
340/// Returns [`OfflineAudioError::InvalidInput`] when `inputs` are not exactly the graph's buses or
341/// the schedule is malformed, and [`OfflineAudioError::Sink`] when the destination rejects output.
342pub fn render_offline(
343    graph: &mut AudioGraph,
344    sample_rate: u32,
345    inputs: &[Vec<f32>],
346    block_sizes: &[usize],
347    sink: &mut dyn AudioBlockSink,
348    cancel: &CancelToken,
349) -> Result<(), OfflineAudioError> {
350    let layout = graph.layout();
351    let frames = inputs.first().map_or(0, Vec::len);
352    if sample_rate == 0
353        || inputs.is_empty()
354        || graph.buses().checked_mul(layout.channels()) != Some(inputs.len())
355        || inputs.iter().any(|channel| channel.len() != frames)
356        || block_sizes.is_empty()
357        || block_sizes.contains(&0)
358    {
359        return Err(OfflineAudioError::InvalidInput);
360    }
361    let max_block = block_sizes.iter().copied().max().unwrap_or(1);
362    graph.prepare(sample_rate, max_block);
363    let mut output: Vec<Vec<f32>> = (0..layout.channels())
364        .map(|_| vec![0.0; max_block])
365        .collect();
366    let mut offset = 0;
367    let mut sequence = 0;
368    while offset < frames {
369        if cancel.is_cancelled() {
370            sink.abort_audio().map_err(OfflineAudioError::Sink)?;
371            return Err(OfflineAudioError::Sink(EncodeError::Cancelled));
372        }
373        let count = block_sizes[sequence % block_sizes.len()].min(frames - offset);
374        let refs: Vec<&[f32]> = inputs
375            .iter()
376            .map(|channel| &channel[offset..offset + count])
377            .collect();
378        let mut outputs: Vec<&mut [f32]> = output
379            .iter_mut()
380            .map(|channel| &mut channel[..count])
381            .collect();
382        let sample_position = i64::try_from(offset).unwrap_or(i64::MAX);
383        graph.process(
384            &ProcessCtx {
385                position: MediaTime::from_ticks(
386                    sample_position
387                        .saturating_mul(TICKS_PER_SECOND)
388                        .div_euclid(i64::from(sample_rate)),
389                ),
390                sample_position,
391                sample_rate,
392                transport: TransportState::Playing,
393            },
394            &refs,
395            &mut outputs,
396        );
397        drop(outputs);
398        sink.write_audio(
399            &AudioBlock {
400                start_sample: sample_position,
401                sample_rate,
402                speakers: match layout {
403                    ChannelLayout::Mono => alpha2_media::SpeakerLayout::MONO,
404                    ChannelLayout::Stereo => alpha2_media::SpeakerLayout::STEREO,
405                },
406                channels: output
407                    .iter()
408                    .map(|channel| channel[..count].to_vec())
409                    .collect(),
410            },
411            cancel,
412        )
413        .map_err(OfflineAudioError::Sink)?;
414        offset += count;
415        sequence += 1;
416    }
417    sink.finish_audio(cancel).map_err(OfflineAudioError::Sink)
418}
419
420#[cfg(feature = "cpal-host")]
421mod realtime {
422    use std::sync::atomic::{AtomicU64, Ordering};
423    use std::sync::{Arc, Mutex, PoisonError};
424
425    use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
426    use cpal::{SampleFormat, Stream, StreamConfig};
427
428    use super::{
429        HostAudioConfig, HostSampleFormat, MediaTime, ProcessCtx, TICKS_PER_SECOND, TransportState,
430        negotiate_output_config,
431    };
432
433    /// Pull source invoked exclusively by the audio callback.
434    ///
435    /// `alpha2_engine::AudioRenderer` does not implement this, since timeline
436    /// evaluation may allocate. Realtime hosts supply a pre-indexed, allocation-free
437    /// source or a bounded producer ring.
438    pub trait RealtimeAudioSource: Send + 'static {
439        /// Fills project-rate planar output without allocation or blocking.
440        fn render(&mut self, ctx: &ProcessCtx, output: &mut [&mut [f32]]);
441        /// Algorithmic latency already present in the source graph.
442        fn latency_samples(&self) -> u32 {
443            0
444        }
445    }
446
447    /// Native realtime host failure.
448    #[derive(Debug)]
449    #[non_exhaustive]
450    pub enum CpalHostError {
451        /// No output device exists.
452        NoOutputDevice,
453        /// No compatible floating-point configuration exists.
454        NoCompatibleFormat,
455        /// The callback limit is zero frames.
456        InvalidCallbackSize,
457        /// Device query or stream construction failed.
458        Device(String),
459    }
460
461    impl std::fmt::Display for CpalHostError {
462        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
463            match self {
464                Self::NoOutputDevice => formatter.write_str("no audio output device is available"),
465                Self::NoCompatibleFormat => {
466                    formatter.write_str("no compatible audio output format is available")
467                }
468                Self::InvalidCallbackSize => {
469                    formatter.write_str("the audio callback limit must be at least one frame")
470                }
471                Self::Device(message) => write!(formatter, "audio device failed: {message}"),
472            }
473        }
474    }
475
476    impl std::error::Error for CpalHostError {}
477
478    /// Running cpal output stream, its observable underrun count and its last stream error.
479    pub struct CpalOutputHost {
480        stream: Stream,
481        underruns: Arc<AtomicU64>,
482        stream_error: Arc<Mutex<Option<String>>>,
483        sample_rate: u32,
484        channels: u16,
485        latency_samples: u32,
486    }
487
488    impl CpalOutputHost {
489        /// Opens the default output at the exact project rate in `f32`, with the
490        /// channels [`negotiate_output_config`] picks.
491        ///
492        /// `source` renders at most `max_callback_frames` at a time into preallocated scratch;
493        /// larger device buffers take several calls.
494        ///
495        /// # Errors
496        /// Returns [`CpalHostError::InvalidCallbackSize`] when `max_callback_frames` is zero, and a
497        /// device or format error when no exact realtime configuration can be opened.
498        pub fn open(
499            mut source: impl RealtimeAudioSource,
500            project_rate: u32,
501            max_callback_frames: usize,
502        ) -> Result<Self, CpalHostError> {
503            let device = cpal::default_host()
504                .default_output_device()
505                .ok_or(CpalHostError::NoOutputDevice)?;
506            if max_callback_frames == 0 {
507                return Err(CpalHostError::InvalidCallbackSize);
508            }
509            let supported = device
510                .supported_output_configs()
511                .map_err(|error| CpalHostError::Device(error.to_string()))?
512                .collect::<Vec<_>>();
513            let offered = supported
514                .iter()
515                .map(|config| HostAudioConfig {
516                    channels: config.channels(),
517                    min_sample_rate: config.min_sample_rate(),
518                    max_sample_rate: config.max_sample_rate(),
519                    format: match config.sample_format() {
520                        SampleFormat::F32 => HostSampleFormat::F32,
521                        SampleFormat::I16 => HostSampleFormat::I16,
522                        _ => HostSampleFormat::Unsupported,
523                    },
524                })
525                .collect::<Vec<_>>();
526            let chosen = negotiate_output_config(&offered, project_rate)
527                .ok_or(CpalHostError::NoCompatibleFormat)?;
528            let selected = offered
529                .iter()
530                .position(|config| *config == chosen)
531                .map(|index| supported[index])
532                .ok_or(CpalHostError::NoCompatibleFormat)?;
533            let device_rate = project_rate;
534            let config: StreamConfig = selected.with_sample_rate(device_rate).config();
535            let channels = usize::from(config.channels);
536            let mut planar = [
537                vec![0.0_f32; max_callback_frames],
538                vec![0.0_f32; max_callback_frames],
539            ];
540            let underruns = Arc::new(AtomicU64::new(0));
541            let callback_underruns = Arc::clone(&underruns);
542            let error_underruns = Arc::clone(&underruns);
543            let stream_error = Arc::new(Mutex::new(None));
544            let error_text = Arc::clone(&stream_error);
545            let mut sample_position = 0_i64;
546            let latency_samples = source.latency_samples();
547            let stream = device
548                .build_output_stream(
549                    &config,
550                    move |data: &mut [f32], _| {
551                        if !fill_device_buffer(
552                            &mut source,
553                            &mut planar,
554                            data,
555                            channels,
556                            device_rate,
557                            &mut sample_position,
558                        ) {
559                            callback_underruns.fetch_add(1, Ordering::Relaxed);
560                        }
561                    },
562                    move |error| {
563                        error_underruns.fetch_add(1, Ordering::Relaxed);
564                        *error_text.lock().unwrap_or_else(PoisonError::into_inner) =
565                            Some(error.to_string());
566                    },
567                    None,
568                )
569                .map_err(|error| CpalHostError::Device(error.to_string()))?;
570            Ok(Self {
571                stream,
572                underruns,
573                stream_error,
574                sample_rate: device_rate,
575                channels: config.channels,
576                latency_samples,
577            })
578        }
579        /// Starts callback delivery.
580        ///
581        /// # Errors
582        /// Returns the device error reported by cpal.
583        pub fn play(&self) -> Result<(), CpalHostError> {
584            self.stream
585                .play()
586                .map_err(|error| CpalHostError::Device(error.to_string()))
587        }
588        /// Stops callback delivery until [`Self::play`].
589        ///
590        /// # Errors
591        /// Returns the device error reported by cpal.
592        pub fn pause(&self) -> Result<(), CpalHostError> {
593            self.stream
594                .pause()
595                .map_err(|error| CpalHostError::Device(error.to_string()))
596        }
597        /// Errors the stream reported, plus device buffers that were not whole
598        /// frames and played silent.
599        #[must_use]
600        pub fn underruns(&self) -> u64 {
601            self.underruns.load(Ordering::Relaxed)
602        }
603        /// The last error the stream reported (a device that went away, for one), `None` while
604        /// it reported none.
605        #[must_use]
606        pub fn stream_error(&self) -> Option<String> {
607            self.stream_error
608                .lock()
609                .unwrap_or_else(PoisonError::into_inner)
610                .clone()
611        }
612        /// Negotiated device sample rate.
613        #[must_use]
614        pub const fn sample_rate(&self) -> u32 {
615            self.sample_rate
616        }
617        /// Negotiated output channels.
618        #[must_use]
619        pub const fn channels(&self) -> u16 {
620            self.channels
621        }
622        /// Source graph latency for transport compensation.
623        #[must_use]
624        pub const fn latency_samples(&self) -> u32 {
625            self.latency_samples
626        }
627    }
628
629    /// Renders `source` into one interleaved device buffer of
630    /// `channels`, advancing `sample_position`.
631    ///
632    /// Rendered in scratch-sized pieces. Mono devices get mono, others stereo in the first
633    /// two channels and silence elsewhere. Returns false, after writing silence, for a buffer
634    /// that is not whole frames.
635    pub(super) fn fill_device_buffer(
636        source: &mut impl RealtimeAudioSource,
637        planar: &mut [Vec<f32>; 2],
638        data: &mut [f32],
639        channels: usize,
640        device_rate: u32,
641        sample_position: &mut i64,
642    ) -> bool {
643        let piece = planar[0].len();
644        if channels == 0 || piece == 0 || !data.len().is_multiple_of(channels) {
645            data.fill(0.0);
646            return false;
647        }
648        let rendered = channels.min(2);
649        for chunk in data.chunks_mut(piece * channels) {
650            let frames = chunk.len() / channels;
651            let ctx = ProcessCtx {
652                position: MediaTime::from_ticks(
653                    sample_position
654                        .saturating_mul(TICKS_PER_SECOND)
655                        .div_euclid(i64::from(device_rate)),
656                ),
657                sample_position: *sample_position,
658                sample_rate: device_rate,
659                transport: TransportState::Playing,
660            };
661            let (left, right) = planar.split_at_mut(1);
662            if rendered == 1 {
663                source.render(&ctx, &mut [&mut left[0][..frames]]);
664            } else {
665                source.render(&ctx, &mut [&mut left[0][..frames], &mut right[0][..frames]]);
666            }
667            for (frame, destination) in chunk.chunks_exact_mut(channels).enumerate() {
668                for (channel, sample) in destination.iter_mut().enumerate() {
669                    *sample = if channel < rendered {
670                        planar[channel][frame]
671                    } else {
672                        0.0
673                    };
674                }
675            }
676            *sample_position =
677                sample_position.saturating_add(i64::try_from(frames).unwrap_or(i64::MAX));
678        }
679        true
680    }
681}
682
683#[cfg(feature = "cpal-host")]
684pub use realtime::*;
685
686#[cfg(test)]
687#[path = "audio_host_tests.rs"]
688mod tests;