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, 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}
156
157/// Mixes a whole project audio range and writes exact project-rate blocks.
158///
159/// The offline counterpart of the browser pump: `sources` makes ready what each block reads and
160/// the engine does gain, fades, panning, effects, bus summing and limiting. Irregular `block_sizes` repeat, so
161/// callers can prove the mix is independent of block size.
162///
163/// # Errors
164/// Returns [`OfflineAudioError::InvalidInput`] for an empty schedule or range,
165/// [`OfflineAudioError::Engine`] when the renderer rejects the configuration,
166/// [`OfflineAudioError::Sources`] when the sources cannot make a block's audio ready,
167/// [`OfflineAudioError::MissingSources`] when an audible clip had no decoded media, and
168/// [`OfflineAudioError::Sink`] when the destination rejects output.
169#[cfg(feature = "engine")]
170pub fn render_project_audio(
171    snapshot: &EngineProject,
172    request: &ProjectAudioRequest<'_>,
173    sources: &mut dyn ProjectAudioSources,
174    sink: &mut dyn AudioBlockSink,
175    cancel: &CancelToken,
176) -> Result<(), OfflineAudioError> {
177    let ProjectAudioRequest {
178        channels,
179        start_sample,
180        total_frames,
181        block_sizes,
182    } = *request;
183    if total_frames == 0 || block_sizes.is_empty() || block_sizes.contains(&0) || start_sample < 0 {
184        return Err(OfflineAudioError::InvalidInput);
185    }
186    let max_block = block_sizes.iter().copied().max().unwrap_or(1);
187    let mut renderer =
188        AudioRenderer::new(snapshot, channels, max_block).map_err(OfflineAudioError::Engine)?;
189
190    let mut produced = 0;
191    let mut sequence = 0;
192    let mut missing: Vec<SourceId> = Vec::new();
193    while produced < total_frames {
194        if cancel.is_cancelled() {
195            sink.abort_audio().map_err(OfflineAudioError::Sink)?;
196            return Err(OfflineAudioError::Sink(EncodeError::Cancelled));
197        }
198        let count = block_sizes[sequence % block_sizes.len()].min(total_frames - produced);
199        let offset = i64::try_from(produced).unwrap_or(i64::MAX);
200        let at = start_sample.saturating_add(offset);
201        let needs = renderer
202            .audio_needs(snapshot, at, count)
203            .map_err(OfflineAudioError::Engine)?;
204        sources
205            .prepare(&needs, cancel)
206            .map_err(OfflineAudioError::Sources)?;
207        let status = renderer
208            .render(snapshot, at, count, &*sources, TransportState::Playing)
209            .map_err(OfflineAudioError::Engine)?;
210        for source in &status.missing_sources {
211            if !missing.contains(source) {
212                missing.push(source.clone());
213            }
214        }
215        let mut block = renderer.block(&status);
216        // The range is its own file: its first sample is the sink's sample zero.
217        block.start_sample = offset;
218        sink.write_audio(&block, cancel)
219            .map_err(OfflineAudioError::Sink)?;
220        produced += count;
221        sequence += 1;
222    }
223    if !missing.is_empty() {
224        // Report an incomplete mix rather than committing partial audio.
225        sink.abort_audio().map_err(OfflineAudioError::Sink)?;
226        return Err(OfflineAudioError::MissingSources(missing));
227    }
228    sink.finish_audio(cancel).map_err(OfflineAudioError::Sink)
229}
230
231/// Host sample representation considered during deterministic negotiation.
232#[derive(Copy, Clone, Debug, Eq, PartialEq)]
233pub enum HostSampleFormat {
234    /// Native 32-bit floating point.
235    F32,
236    /// Signed 16-bit integer.
237    I16,
238    /// Any format not supported by the realtime host.
239    Unsupported,
240}
241
242/// Platform-neutral device range used by negotiation tests and cpal mapping.
243#[derive(Copy, Clone, Debug, Eq, PartialEq)]
244pub struct HostAudioConfig {
245    /// Channel count.
246    pub channels: u16,
247    /// Lowest supported sample rate.
248    pub min_sample_rate: u32,
249    /// Highest supported sample rate.
250    pub max_sample_rate: u32,
251    /// Device sample representation.
252    pub format: HostSampleFormat,
253}
254
255/// Selects an output that plays stereo, requiring exact project-rate `f32` support.
256///
257/// Prefers exactly two channels, then the fewest above two, then mono. Backends list counts
258/// differently (ALSA every count, WASAPI only the mix format's, `CoreAudio` the sum of stream
259/// channels), so a multichannel device may offer no stereo entry; stereo then goes to its first two
260/// channels (front left and right on all three) and the rest are silent.
261#[must_use]
262pub fn negotiate_output_config(
263    configs: &[HostAudioConfig],
264    project_rate: u32,
265) -> Option<HostAudioConfig> {
266    configs
267        .iter()
268        .copied()
269        .filter(|config| {
270            config.format == HostSampleFormat::F32
271                && config.channels > 0
272                && (config.min_sample_rate..=config.max_sample_rate).contains(&project_rate)
273        })
274        .min_by_key(|config| match config.channels {
275            2 => (0, 0),
276            1 => (2, 0),
277            more => (1, more),
278        })
279}
280
281/// Runs the same graph used by realtime hosts and writes exact project-rate blocks.
282///
283/// `inputs` are the graph's buses flattened, each bus's planes in the graph's layout; all channels
284/// must have the same length. Irregular `block_sizes` repeat until the source is exhausted.
285///
286/// # Errors
287/// Returns [`OfflineAudioError::InvalidInput`] when `inputs` are not exactly the graph's buses or
288/// the schedule is malformed, and [`OfflineAudioError::Sink`] when the destination rejects output.
289pub fn render_offline(
290    graph: &mut AudioGraph,
291    sample_rate: u32,
292    inputs: &[Vec<f32>],
293    block_sizes: &[usize],
294    sink: &mut dyn AudioBlockSink,
295    cancel: &CancelToken,
296) -> Result<(), OfflineAudioError> {
297    let layout = graph.layout();
298    let frames = inputs.first().map_or(0, Vec::len);
299    if sample_rate == 0
300        || inputs.is_empty()
301        || graph.buses().checked_mul(layout.channels()) != Some(inputs.len())
302        || inputs.iter().any(|channel| channel.len() != frames)
303        || block_sizes.is_empty()
304        || block_sizes.contains(&0)
305    {
306        return Err(OfflineAudioError::InvalidInput);
307    }
308    let max_block = block_sizes.iter().copied().max().unwrap_or(1);
309    graph.prepare(sample_rate, max_block);
310    let mut output: Vec<Vec<f32>> = (0..layout.channels())
311        .map(|_| vec![0.0; max_block])
312        .collect();
313    let mut offset = 0;
314    let mut sequence = 0;
315    while offset < frames {
316        if cancel.is_cancelled() {
317            sink.abort_audio().map_err(OfflineAudioError::Sink)?;
318            return Err(OfflineAudioError::Sink(EncodeError::Cancelled));
319        }
320        let count = block_sizes[sequence % block_sizes.len()].min(frames - offset);
321        let refs: Vec<&[f32]> = inputs
322            .iter()
323            .map(|channel| &channel[offset..offset + count])
324            .collect();
325        let mut outputs: Vec<&mut [f32]> = output
326            .iter_mut()
327            .map(|channel| &mut channel[..count])
328            .collect();
329        let sample_position = i64::try_from(offset).unwrap_or(i64::MAX);
330        graph.process(
331            &ProcessCtx {
332                position: MediaTime::from_ticks(
333                    sample_position
334                        .saturating_mul(TICKS_PER_SECOND)
335                        .div_euclid(i64::from(sample_rate)),
336                ),
337                sample_position,
338                sample_rate,
339                transport: TransportState::Playing,
340            },
341            &refs,
342            &mut outputs,
343        );
344        drop(outputs);
345        sink.write_audio(
346            &AudioBlock {
347                start_sample: sample_position,
348                sample_rate,
349                speakers: match layout {
350                    ChannelLayout::Mono => alpha2_media::SpeakerLayout::MONO,
351                    ChannelLayout::Stereo => alpha2_media::SpeakerLayout::STEREO,
352                },
353                channels: output
354                    .iter()
355                    .map(|channel| channel[..count].to_vec())
356                    .collect(),
357            },
358            cancel,
359        )
360        .map_err(OfflineAudioError::Sink)?;
361        offset += count;
362        sequence += 1;
363    }
364    sink.finish_audio(cancel).map_err(OfflineAudioError::Sink)
365}
366
367#[cfg(feature = "cpal-host")]
368mod realtime {
369    use std::sync::atomic::{AtomicU64, Ordering};
370    use std::sync::{Arc, Mutex, PoisonError};
371
372    use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
373    use cpal::{SampleFormat, Stream, StreamConfig};
374
375    use super::{
376        HostAudioConfig, HostSampleFormat, MediaTime, ProcessCtx, TICKS_PER_SECOND, TransportState,
377        negotiate_output_config,
378    };
379
380    /// Pull source invoked exclusively by the audio callback.
381    ///
382    /// `alpha2_engine::AudioRenderer` does not implement this, since timeline
383    /// evaluation may allocate. Realtime hosts supply a pre-indexed, allocation-free
384    /// source or a bounded producer ring.
385    pub trait RealtimeAudioSource: Send + 'static {
386        /// Fills project-rate planar output without allocation or blocking.
387        fn render(&mut self, ctx: &ProcessCtx, output: &mut [&mut [f32]]);
388        /// Algorithmic latency already present in the source graph.
389        fn latency_samples(&self) -> u32 {
390            0
391        }
392    }
393
394    /// Native realtime host failure.
395    #[derive(Debug)]
396    #[non_exhaustive]
397    pub enum CpalHostError {
398        /// No output device exists.
399        NoOutputDevice,
400        /// No compatible floating-point configuration exists.
401        NoCompatibleFormat,
402        /// The callback limit is zero frames.
403        InvalidCallbackSize,
404        /// Device query or stream construction failed.
405        Device(String),
406    }
407
408    impl std::fmt::Display for CpalHostError {
409        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
410            match self {
411                Self::NoOutputDevice => formatter.write_str("no audio output device is available"),
412                Self::NoCompatibleFormat => {
413                    formatter.write_str("no compatible audio output format is available")
414                }
415                Self::InvalidCallbackSize => {
416                    formatter.write_str("the audio callback limit must be at least one frame")
417                }
418                Self::Device(message) => write!(formatter, "audio device failed: {message}"),
419            }
420        }
421    }
422
423    impl std::error::Error for CpalHostError {}
424
425    /// Running cpal output stream, its observable underrun count and its last stream error.
426    pub struct CpalOutputHost {
427        stream: Stream,
428        underruns: Arc<AtomicU64>,
429        stream_error: Arc<Mutex<Option<String>>>,
430        sample_rate: u32,
431        channels: u16,
432        latency_samples: u32,
433    }
434
435    impl CpalOutputHost {
436        /// Opens the default output at the exact project rate in `f32`, with the
437        /// channels [`negotiate_output_config`] picks.
438        ///
439        /// `source` renders at most `max_callback_frames` at a time into preallocated scratch;
440        /// larger device buffers take several calls.
441        ///
442        /// # Errors
443        /// Returns [`CpalHostError::InvalidCallbackSize`] when `max_callback_frames` is zero, and a
444        /// device or format error when no exact realtime configuration can be opened.
445        pub fn open(
446            mut source: impl RealtimeAudioSource,
447            project_rate: u32,
448            max_callback_frames: usize,
449        ) -> Result<Self, CpalHostError> {
450            let device = cpal::default_host()
451                .default_output_device()
452                .ok_or(CpalHostError::NoOutputDevice)?;
453            if max_callback_frames == 0 {
454                return Err(CpalHostError::InvalidCallbackSize);
455            }
456            let supported = device
457                .supported_output_configs()
458                .map_err(|error| CpalHostError::Device(error.to_string()))?
459                .collect::<Vec<_>>();
460            let offered = supported
461                .iter()
462                .map(|config| HostAudioConfig {
463                    channels: config.channels(),
464                    min_sample_rate: config.min_sample_rate(),
465                    max_sample_rate: config.max_sample_rate(),
466                    format: match config.sample_format() {
467                        SampleFormat::F32 => HostSampleFormat::F32,
468                        SampleFormat::I16 => HostSampleFormat::I16,
469                        _ => HostSampleFormat::Unsupported,
470                    },
471                })
472                .collect::<Vec<_>>();
473            let chosen = negotiate_output_config(&offered, project_rate)
474                .ok_or(CpalHostError::NoCompatibleFormat)?;
475            let selected = offered
476                .iter()
477                .position(|config| *config == chosen)
478                .map(|index| supported[index])
479                .ok_or(CpalHostError::NoCompatibleFormat)?;
480            let device_rate = project_rate;
481            let config: StreamConfig = selected.with_sample_rate(device_rate).config();
482            let channels = usize::from(config.channels);
483            let mut planar = [
484                vec![0.0_f32; max_callback_frames],
485                vec![0.0_f32; max_callback_frames],
486            ];
487            let underruns = Arc::new(AtomicU64::new(0));
488            let callback_underruns = Arc::clone(&underruns);
489            let error_underruns = Arc::clone(&underruns);
490            let stream_error = Arc::new(Mutex::new(None));
491            let error_text = Arc::clone(&stream_error);
492            let mut sample_position = 0_i64;
493            let latency_samples = source.latency_samples();
494            let stream = device
495                .build_output_stream(
496                    &config,
497                    move |data: &mut [f32], _| {
498                        if !fill_device_buffer(
499                            &mut source,
500                            &mut planar,
501                            data,
502                            channels,
503                            device_rate,
504                            &mut sample_position,
505                        ) {
506                            callback_underruns.fetch_add(1, Ordering::Relaxed);
507                        }
508                    },
509                    move |error| {
510                        error_underruns.fetch_add(1, Ordering::Relaxed);
511                        *error_text.lock().unwrap_or_else(PoisonError::into_inner) =
512                            Some(error.to_string());
513                    },
514                    None,
515                )
516                .map_err(|error| CpalHostError::Device(error.to_string()))?;
517            Ok(Self {
518                stream,
519                underruns,
520                stream_error,
521                sample_rate: device_rate,
522                channels: config.channels,
523                latency_samples,
524            })
525        }
526        /// Starts callback delivery.
527        ///
528        /// # Errors
529        /// Returns the device error reported by cpal.
530        pub fn play(&self) -> Result<(), CpalHostError> {
531            self.stream
532                .play()
533                .map_err(|error| CpalHostError::Device(error.to_string()))
534        }
535        /// Stops callback delivery until [`Self::play`].
536        ///
537        /// # Errors
538        /// Returns the device error reported by cpal.
539        pub fn pause(&self) -> Result<(), CpalHostError> {
540            self.stream
541                .pause()
542                .map_err(|error| CpalHostError::Device(error.to_string()))
543        }
544        /// Errors the stream reported, plus device buffers that were not whole
545        /// frames and played silent.
546        #[must_use]
547        pub fn underruns(&self) -> u64 {
548            self.underruns.load(Ordering::Relaxed)
549        }
550        /// The last error the stream reported (a device that went away, for one), `None` while
551        /// it reported none.
552        #[must_use]
553        pub fn stream_error(&self) -> Option<String> {
554            self.stream_error
555                .lock()
556                .unwrap_or_else(PoisonError::into_inner)
557                .clone()
558        }
559        /// Negotiated device sample rate.
560        #[must_use]
561        pub const fn sample_rate(&self) -> u32 {
562            self.sample_rate
563        }
564        /// Negotiated output channels.
565        #[must_use]
566        pub const fn channels(&self) -> u16 {
567            self.channels
568        }
569        /// Source graph latency for transport compensation.
570        #[must_use]
571        pub const fn latency_samples(&self) -> u32 {
572            self.latency_samples
573        }
574    }
575
576    /// Renders `source` into one interleaved device buffer of
577    /// `channels`, advancing `sample_position`.
578    ///
579    /// Rendered in scratch-sized pieces. Mono devices get mono, others stereo in the first
580    /// two channels and silence elsewhere. Returns false, after writing silence, for a buffer
581    /// that is not whole frames.
582    pub(super) fn fill_device_buffer(
583        source: &mut impl RealtimeAudioSource,
584        planar: &mut [Vec<f32>; 2],
585        data: &mut [f32],
586        channels: usize,
587        device_rate: u32,
588        sample_position: &mut i64,
589    ) -> bool {
590        let piece = planar[0].len();
591        if channels == 0 || piece == 0 || !data.len().is_multiple_of(channels) {
592            data.fill(0.0);
593            return false;
594        }
595        let rendered = channels.min(2);
596        for chunk in data.chunks_mut(piece * channels) {
597            let frames = chunk.len() / channels;
598            let ctx = ProcessCtx {
599                position: MediaTime::from_ticks(
600                    sample_position
601                        .saturating_mul(TICKS_PER_SECOND)
602                        .div_euclid(i64::from(device_rate)),
603                ),
604                sample_position: *sample_position,
605                sample_rate: device_rate,
606                transport: TransportState::Playing,
607            };
608            let (left, right) = planar.split_at_mut(1);
609            if rendered == 1 {
610                source.render(&ctx, &mut [&mut left[0][..frames]]);
611            } else {
612                source.render(&ctx, &mut [&mut left[0][..frames], &mut right[0][..frames]]);
613            }
614            for (frame, destination) in chunk.chunks_exact_mut(channels).enumerate() {
615                for (channel, sample) in destination.iter_mut().enumerate() {
616                    *sample = if channel < rendered {
617                        planar[channel][frame]
618                    } else {
619                        0.0
620                    };
621                }
622            }
623            *sample_position =
624                sample_position.saturating_add(i64::try_from(frames).unwrap_or(i64::MAX));
625        }
626        true
627    }
628}
629
630#[cfg(feature = "cpal-host")]
631pub use realtime::*;
632
633#[cfg(test)]
634#[path = "audio_host_tests.rs"]
635mod tests;