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 mut renderer = project_audio_renderer(snapshot, request, tap_sinks.len())?;
199    write_project_audio(
200        &mut renderer,
201        snapshot,
202        request,
203        sources,
204        (sink, tap_sinks),
205        cancel,
206    )
207}
208
209/// The true-peak ceiling a loudness target takes when it names none, in dBTP (EBU R128).
210pub const DEFAULT_TRUE_PEAK_CEILING_DBTP: f64 = -1.0;
211
212/// A loudness target (EBU R128, ITU-R BS.1770-4).
213#[derive(Copy, Clone, Debug, PartialEq)]
214pub struct LoudnessTarget {
215    /// Integrated loudness, in `-60..=0` LUFS.
216    pub target_lufs: f64,
217    /// The true-peak ceiling, in `-20..=0` dBTP. When the target would pass it, the gain is
218    /// lowered and the render left quieter than the target.
219    pub true_peak_ceiling_dbtp: f64,
220}
221
222impl LoudnessTarget {
223    /// # Errors
224    /// A message naming the field for a value out of range.
225    pub fn new(target_lufs: f64, true_peak_ceiling_dbtp: f64) -> Result<Self, String> {
226        if !(target_lufs.is_finite() && (-60.0..=0.0).contains(&target_lufs)) {
227            return Err(format!(
228                "loudness.targetLufs must be within -60..=0, received {target_lufs}"
229            ));
230        }
231        if !(true_peak_ceiling_dbtp.is_finite() && (-20.0..=0.0).contains(&true_peak_ceiling_dbtp))
232        {
233            return Err(format!(
234                "loudness.truePeakCeilingDbtp must be within -20..=0, received {true_peak_ceiling_dbtp}"
235            ));
236        }
237        Ok(Self {
238            target_lufs,
239            true_peak_ceiling_dbtp,
240        })
241    }
242}
243
244/// What a normalized render measured, planned and wrote.
245#[derive(Copy, Clone, Debug, PartialEq)]
246pub struct LoudnessOutcome {
247    /// The target it was asked for.
248    pub target: LoudnessTarget,
249    /// The master limiter's linear threshold, when the project has one.
250    pub limiter_threshold: Option<f64>,
251    /// The mix as it reached the limiter before any gain.
252    pub measured: alpha2_audio::LoudnessReport,
253    /// The gain planned from `measured`; `None` when the mix is silent below the absolute gate.
254    pub applied: Option<alpha2_audio::LoudnessNormalization>,
255    /// The mix as written, after the master limiter.
256    pub output: Option<alpha2_audio::LoudnessReport>,
257}
258
259impl LoudnessOutcome {
260    /// The export result's `loudness`, as every host reports it.
261    #[must_use]
262    pub fn to_json(&self) -> serde_json::Value {
263        let report = |report: &alpha2_audio::LoudnessReport| {
264            serde_json::json!({
265                "integratedLufs": report.integrated_lufs,
266                "loudnessRangeLu": report.loudness_range_lu,
267                "truePeakDbtp": report.true_peak_dbtp,
268                "samplePeakDbfs": report.sample_peak_dbfs,
269            })
270        };
271        serde_json::json!({
272            "targetLufs": self.target.target_lufs,
273            "truePeakCeilingDbtp": self.target.true_peak_ceiling_dbtp,
274            "limiterThreshold": self.limiter_threshold,
275            "measured": report(&self.measured),
276            "applied": self.applied.map(|plan| serde_json::json!({
277                "gainDb": plan.gain_db,
278                "integratedLufs": plan.integrated_lufs,
279                "truePeakDbtp": plan.true_peak_dbtp,
280                "peakLimited": plan.peak_limited,
281                "limiterLimited": plan.limiter_limited,
282            })),
283            "output": self.output.as_ref().map(report),
284        })
285    }
286}
287
288/// [`render_project_audio_with_taps`] normalized to `target` by a first pass that writes nothing.
289///
290/// Taps are read before the master, so the gain does not reach them.
291///
292/// # Errors
293/// As [`render_project_audio_with_taps`]; [`OfflineAudioError::MissingSources`] after the first
294/// pass, before anything is written. Every sink is aborted when the render fails.
295#[cfg(feature = "engine")]
296pub fn render_project_audio_normalized(
297    snapshot: &EngineProject,
298    request: &ProjectAudioRequest<'_>,
299    target: LoudnessTarget,
300    sources: &mut dyn ProjectAudioSources,
301    (sink, tap_sinks): (&mut dyn AudioBlockSink, &mut [&mut dyn AudioBlockSink]),
302    cancel: &CancelToken,
303) -> Result<LoudnessOutcome, OfflineAudioError> {
304    let mut renderer = project_audio_renderer(snapshot, request, tap_sinks.len())?;
305    let measured = match meter_project_audio(&mut renderer, snapshot, request, sources, cancel) {
306        Ok(measured) => measured,
307        Err(error) => {
308            abort_all(sink, tap_sinks)?;
309            return Err(error);
310        }
311    };
312    renderer.reset();
313    let limiter_threshold = renderer.limiter_threshold();
314    let applied = alpha2_audio::LoudnessNormalization::plan(
315        &measured,
316        target.target_lufs,
317        target.true_peak_ceiling_dbtp,
318        limiter_threshold,
319    );
320    if let Some(plan) = applied {
321        renderer
322            .set_normalization_gain_db(plan.gain_db)
323            .map_err(OfflineAudioError::Engine)?;
324    }
325    renderer
326        .set_output_loudness_metering(true)
327        .map_err(OfflineAudioError::Engine)?;
328    write_project_audio(
329        &mut renderer,
330        snapshot,
331        request,
332        sources,
333        (sink, tap_sinks),
334        cancel,
335    )?;
336    Ok(LoudnessOutcome {
337        target,
338        limiter_threshold,
339        measured,
340        applied,
341        output: renderer.output_loudness_report(),
342    })
343}
344
345#[cfg(feature = "engine")]
346fn meter_project_audio(
347    renderer: &mut AudioRenderer,
348    snapshot: &EngineProject,
349    request: &ProjectAudioRequest<'_>,
350    sources: &mut dyn ProjectAudioSources,
351    cancel: &CancelToken,
352) -> Result<alpha2_audio::LoudnessReport, OfflineAudioError> {
353    let ProjectAudioRequest {
354        start_sample,
355        total_frames,
356        block_sizes,
357        ..
358    } = *request;
359    renderer
360        .set_loudness_metering(true)
361        .map_err(OfflineAudioError::Engine)?;
362    let mut produced = 0;
363    let mut sequence = 0;
364    let mut missing: Vec<SourceId> = Vec::new();
365    while produced < total_frames {
366        if cancel.is_cancelled() {
367            return Err(OfflineAudioError::Sink(EncodeError::Cancelled));
368        }
369        let count = block_sizes[sequence % block_sizes.len()].min(total_frames - produced);
370        let at = start_sample.saturating_add(i64::try_from(produced).unwrap_or(i64::MAX));
371        let needs = renderer
372            .audio_needs(snapshot, at, count)
373            .map_err(OfflineAudioError::Engine)?;
374        sources
375            .prepare(&needs, cancel)
376            .map_err(OfflineAudioError::Sources)?;
377        let status = renderer
378            .render(snapshot, at, count, &*sources, TransportState::Playing)
379            .map_err(OfflineAudioError::Engine)?;
380        for source in status.missing_sources {
381            if !missing.contains(&source) {
382                missing.push(source);
383            }
384        }
385        produced += count;
386        sequence += 1;
387    }
388    if !missing.is_empty() {
389        return Err(OfflineAudioError::MissingSources(missing));
390    }
391    let report = renderer
392        .loudness_report()
393        .ok_or(OfflineAudioError::InvalidInput)?;
394    renderer
395        .set_loudness_metering(false)
396        .map_err(OfflineAudioError::Engine)?;
397    Ok(report)
398}
399
400#[cfg(feature = "engine")]
401fn project_audio_renderer(
402    snapshot: &EngineProject,
403    request: &ProjectAudioRequest<'_>,
404    tap_sinks: usize,
405) -> Result<AudioRenderer, OfflineAudioError> {
406    let ProjectAudioRequest {
407        channels,
408        start_sample,
409        total_frames,
410        block_sizes,
411        taps,
412    } = *request;
413    if total_frames == 0
414        || block_sizes.is_empty()
415        || block_sizes.contains(&0)
416        || start_sample < 0
417        || tap_sinks != taps.len()
418    {
419        return Err(OfflineAudioError::InvalidInput);
420    }
421    let max_block = block_sizes.iter().copied().max().unwrap_or(1);
422    AudioRenderer::with_taps(snapshot, channels, max_block, taps).map_err(OfflineAudioError::Engine)
423}
424
425#[cfg(feature = "engine")]
426fn write_project_audio(
427    renderer: &mut AudioRenderer,
428    snapshot: &EngineProject,
429    request: &ProjectAudioRequest<'_>,
430    sources: &mut dyn ProjectAudioSources,
431    (sink, tap_sinks): (&mut dyn AudioBlockSink, &mut [&mut dyn AudioBlockSink]),
432    cancel: &CancelToken,
433) -> Result<(), OfflineAudioError> {
434    let ProjectAudioRequest {
435        start_sample,
436        total_frames,
437        block_sizes,
438        ..
439    } = *request;
440    let mut produced = 0;
441    let mut sequence = 0;
442    let mut missing: Vec<SourceId> = Vec::new();
443    while produced < total_frames {
444        if cancel.is_cancelled() {
445            abort_all(sink, tap_sinks)?;
446            return Err(OfflineAudioError::Sink(EncodeError::Cancelled));
447        }
448        let count = block_sizes[sequence % block_sizes.len()].min(total_frames - produced);
449        let offset = i64::try_from(produced).unwrap_or(i64::MAX);
450        let at = start_sample.saturating_add(offset);
451        let needs = renderer
452            .audio_needs(snapshot, at, count)
453            .map_err(OfflineAudioError::Engine)?;
454        sources
455            .prepare(&needs, cancel)
456            .map_err(OfflineAudioError::Sources)?;
457        let status = renderer
458            .render(snapshot, at, count, &*sources, TransportState::Playing)
459            .map_err(OfflineAudioError::Engine)?;
460        for source in &status.missing_sources {
461            if !missing.contains(source) {
462                missing.push(source.clone());
463            }
464        }
465        let mut block = renderer.block(&status);
466        // The range is its own file: its first sample is the sink's sample zero.
467        block.start_sample = offset;
468        sink.write_audio(&block, cancel)
469            .map_err(OfflineAudioError::Sink)?;
470        for (index, tap_sink) in tap_sinks.iter_mut().enumerate() {
471            if let Some(mut block) = renderer.tap_block(index, &status) {
472                block.start_sample = offset;
473                tap_sink
474                    .write_audio(&block, cancel)
475                    .map_err(OfflineAudioError::Sink)?;
476            }
477        }
478        produced += count;
479        sequence += 1;
480    }
481    if !missing.is_empty() {
482        // Report an incomplete mix rather than committing partial audio.
483        abort_all(sink, tap_sinks)?;
484        return Err(OfflineAudioError::MissingSources(missing));
485    }
486    sink.finish_audio(cancel).map_err(OfflineAudioError::Sink)?;
487    for tap_sink in tap_sinks {
488        tap_sink
489            .finish_audio(cancel)
490            .map_err(OfflineAudioError::Sink)?;
491    }
492    Ok(())
493}
494
495#[cfg(feature = "engine")]
496fn abort_all(
497    sink: &mut dyn AudioBlockSink,
498    tap_sinks: &mut [&mut dyn AudioBlockSink],
499) -> Result<(), OfflineAudioError> {
500    let mut aborted = sink.abort_audio();
501    for tap_sink in tap_sinks {
502        aborted = aborted.and(tap_sink.abort_audio());
503    }
504    aborted.map_err(OfflineAudioError::Sink)
505}
506
507/// Host sample representation considered during deterministic negotiation.
508#[derive(Copy, Clone, Debug, Eq, PartialEq)]
509pub enum HostSampleFormat {
510    /// Native 32-bit floating point.
511    F32,
512    /// Signed 16-bit integer.
513    I16,
514    /// Any format not supported by the realtime host.
515    Unsupported,
516}
517
518/// Platform-neutral device range used by negotiation tests and cpal mapping.
519#[derive(Copy, Clone, Debug, Eq, PartialEq)]
520pub struct HostAudioConfig {
521    /// Channel count.
522    pub channels: u16,
523    /// Lowest supported sample rate.
524    pub min_sample_rate: u32,
525    /// Highest supported sample rate.
526    pub max_sample_rate: u32,
527    /// Device sample representation.
528    pub format: HostSampleFormat,
529}
530
531/// Selects an output that plays stereo, requiring exact project-rate `f32` support.
532///
533/// Prefers exactly two channels, then the fewest above two, then mono. Backends list counts
534/// differently (ALSA every count, WASAPI only the mix format's, `CoreAudio` the sum of stream
535/// channels), so a multichannel device may offer no stereo entry; stereo then goes to its first two
536/// channels (front left and right on all three) and the rest are silent.
537#[must_use]
538pub fn negotiate_output_config(
539    configs: &[HostAudioConfig],
540    project_rate: u32,
541) -> Option<HostAudioConfig> {
542    configs
543        .iter()
544        .copied()
545        .filter(|config| {
546            config.format == HostSampleFormat::F32
547                && config.channels > 0
548                && (config.min_sample_rate..=config.max_sample_rate).contains(&project_rate)
549        })
550        .min_by_key(|config| match config.channels {
551            2 => (0, 0),
552            1 => (2, 0),
553            more => (1, more),
554        })
555}
556
557/// Runs the same graph used by realtime hosts and writes exact project-rate blocks.
558///
559/// `inputs` are the graph's buses flattened, each bus's planes in the graph's layout; all channels
560/// must have the same length. Irregular `block_sizes` repeat until the source is exhausted.
561///
562/// # Errors
563/// Returns [`OfflineAudioError::InvalidInput`] when `inputs` are not exactly the graph's buses or
564/// the schedule is malformed, and [`OfflineAudioError::Sink`] when the destination rejects output.
565pub fn render_offline(
566    graph: &mut AudioGraph,
567    sample_rate: u32,
568    inputs: &[Vec<f32>],
569    block_sizes: &[usize],
570    sink: &mut dyn AudioBlockSink,
571    cancel: &CancelToken,
572) -> Result<(), OfflineAudioError> {
573    let layout = graph.layout();
574    let frames = inputs.first().map_or(0, Vec::len);
575    if sample_rate == 0
576        || inputs.is_empty()
577        || graph.buses().checked_mul(layout.channels()) != Some(inputs.len())
578        || inputs.iter().any(|channel| channel.len() != frames)
579        || block_sizes.is_empty()
580        || block_sizes.contains(&0)
581    {
582        return Err(OfflineAudioError::InvalidInput);
583    }
584    let max_block = block_sizes.iter().copied().max().unwrap_or(1);
585    graph.prepare(sample_rate, max_block);
586    let mut output: Vec<Vec<f32>> = (0..layout.channels())
587        .map(|_| vec![0.0; max_block])
588        .collect();
589    let mut offset = 0;
590    let mut sequence = 0;
591    while offset < frames {
592        if cancel.is_cancelled() {
593            sink.abort_audio().map_err(OfflineAudioError::Sink)?;
594            return Err(OfflineAudioError::Sink(EncodeError::Cancelled));
595        }
596        let count = block_sizes[sequence % block_sizes.len()].min(frames - offset);
597        let refs: Vec<&[f32]> = inputs
598            .iter()
599            .map(|channel| &channel[offset..offset + count])
600            .collect();
601        let mut outputs: Vec<&mut [f32]> = output
602            .iter_mut()
603            .map(|channel| &mut channel[..count])
604            .collect();
605        let sample_position = i64::try_from(offset).unwrap_or(i64::MAX);
606        graph.process(
607            &ProcessCtx {
608                position: MediaTime::from_ticks(
609                    sample_position
610                        .saturating_mul(TICKS_PER_SECOND)
611                        .div_euclid(i64::from(sample_rate)),
612                ),
613                sample_position,
614                sample_rate,
615                transport: TransportState::Playing,
616            },
617            &refs,
618            &mut outputs,
619        );
620        drop(outputs);
621        sink.write_audio(
622            &AudioBlock {
623                start_sample: sample_position,
624                sample_rate,
625                speakers: match layout {
626                    ChannelLayout::Mono => alpha2_media::SpeakerLayout::MONO,
627                    ChannelLayout::Stereo => alpha2_media::SpeakerLayout::STEREO,
628                },
629                channels: output
630                    .iter()
631                    .map(|channel| channel[..count].to_vec())
632                    .collect(),
633            },
634            cancel,
635        )
636        .map_err(OfflineAudioError::Sink)?;
637        offset += count;
638        sequence += 1;
639    }
640    sink.finish_audio(cancel).map_err(OfflineAudioError::Sink)
641}
642
643#[cfg(feature = "cpal-host")]
644mod realtime {
645    use std::sync::atomic::{AtomicU64, Ordering};
646    use std::sync::{Arc, Mutex, PoisonError};
647
648    use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
649    use cpal::{SampleFormat, Stream, StreamConfig};
650
651    use super::{
652        HostAudioConfig, HostSampleFormat, MediaTime, ProcessCtx, TICKS_PER_SECOND, TransportState,
653        negotiate_output_config,
654    };
655
656    /// Pull source invoked exclusively by the audio callback.
657    ///
658    /// `alpha2_engine::AudioRenderer` does not implement this, since timeline
659    /// evaluation may allocate. Realtime hosts supply a pre-indexed, allocation-free
660    /// source or a bounded producer ring.
661    pub trait RealtimeAudioSource: Send + 'static {
662        /// Fills project-rate planar output without allocation or blocking.
663        fn render(&mut self, ctx: &ProcessCtx, output: &mut [&mut [f32]]);
664        /// Algorithmic latency already present in the source graph.
665        fn latency_samples(&self) -> u32 {
666            0
667        }
668    }
669
670    /// Native realtime host failure.
671    #[derive(Debug)]
672    #[non_exhaustive]
673    pub enum CpalHostError {
674        /// No output device exists.
675        NoOutputDevice,
676        /// No compatible floating-point configuration exists.
677        NoCompatibleFormat,
678        /// The callback limit is zero frames.
679        InvalidCallbackSize,
680        /// Device query or stream construction failed.
681        Device(String),
682    }
683
684    impl std::fmt::Display for CpalHostError {
685        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
686            match self {
687                Self::NoOutputDevice => formatter.write_str("no audio output device is available"),
688                Self::NoCompatibleFormat => {
689                    formatter.write_str("no compatible audio output format is available")
690                }
691                Self::InvalidCallbackSize => {
692                    formatter.write_str("the audio callback limit must be at least one frame")
693                }
694                Self::Device(message) => write!(formatter, "audio device failed: {message}"),
695            }
696        }
697    }
698
699    impl std::error::Error for CpalHostError {}
700
701    /// Running cpal output stream, its observable underrun count and its last stream error.
702    pub struct CpalOutputHost {
703        stream: Stream,
704        underruns: Arc<AtomicU64>,
705        stream_error: Arc<Mutex<Option<String>>>,
706        sample_rate: u32,
707        channels: u16,
708        latency_samples: u32,
709    }
710
711    impl CpalOutputHost {
712        /// Opens the default output at the exact project rate in `f32`, with the
713        /// channels [`negotiate_output_config`] picks.
714        ///
715        /// `source` renders at most `max_callback_frames` at a time into preallocated scratch;
716        /// larger device buffers take several calls.
717        ///
718        /// # Errors
719        /// Returns [`CpalHostError::InvalidCallbackSize`] when `max_callback_frames` is zero, and a
720        /// device or format error when no exact realtime configuration can be opened.
721        pub fn open(
722            mut source: impl RealtimeAudioSource,
723            project_rate: u32,
724            max_callback_frames: usize,
725        ) -> Result<Self, CpalHostError> {
726            let device = cpal::default_host()
727                .default_output_device()
728                .ok_or(CpalHostError::NoOutputDevice)?;
729            if max_callback_frames == 0 {
730                return Err(CpalHostError::InvalidCallbackSize);
731            }
732            let supported = device
733                .supported_output_configs()
734                .map_err(|error| CpalHostError::Device(error.to_string()))?
735                .collect::<Vec<_>>();
736            let offered = supported
737                .iter()
738                .map(|config| HostAudioConfig {
739                    channels: config.channels(),
740                    min_sample_rate: config.min_sample_rate(),
741                    max_sample_rate: config.max_sample_rate(),
742                    format: match config.sample_format() {
743                        SampleFormat::F32 => HostSampleFormat::F32,
744                        SampleFormat::I16 => HostSampleFormat::I16,
745                        _ => HostSampleFormat::Unsupported,
746                    },
747                })
748                .collect::<Vec<_>>();
749            let chosen = negotiate_output_config(&offered, project_rate)
750                .ok_or(CpalHostError::NoCompatibleFormat)?;
751            let selected = offered
752                .iter()
753                .position(|config| *config == chosen)
754                .map(|index| supported[index])
755                .ok_or(CpalHostError::NoCompatibleFormat)?;
756            let device_rate = project_rate;
757            let config: StreamConfig = selected.with_sample_rate(device_rate).config();
758            let channels = usize::from(config.channels);
759            let mut planar = [
760                vec![0.0_f32; max_callback_frames],
761                vec![0.0_f32; max_callback_frames],
762            ];
763            let underruns = Arc::new(AtomicU64::new(0));
764            let callback_underruns = Arc::clone(&underruns);
765            let error_underruns = Arc::clone(&underruns);
766            let stream_error = Arc::new(Mutex::new(None));
767            let error_text = Arc::clone(&stream_error);
768            let mut sample_position = 0_i64;
769            let latency_samples = source.latency_samples();
770            let stream = device
771                .build_output_stream(
772                    &config,
773                    move |data: &mut [f32], _| {
774                        if !fill_device_buffer(
775                            &mut source,
776                            &mut planar,
777                            data,
778                            channels,
779                            device_rate,
780                            &mut sample_position,
781                        ) {
782                            callback_underruns.fetch_add(1, Ordering::Relaxed);
783                        }
784                    },
785                    move |error| {
786                        error_underruns.fetch_add(1, Ordering::Relaxed);
787                        *error_text.lock().unwrap_or_else(PoisonError::into_inner) =
788                            Some(error.to_string());
789                    },
790                    None,
791                )
792                .map_err(|error| CpalHostError::Device(error.to_string()))?;
793            Ok(Self {
794                stream,
795                underruns,
796                stream_error,
797                sample_rate: device_rate,
798                channels: config.channels,
799                latency_samples,
800            })
801        }
802        /// Starts callback delivery.
803        ///
804        /// # Errors
805        /// Returns the device error reported by cpal.
806        pub fn play(&self) -> Result<(), CpalHostError> {
807            self.stream
808                .play()
809                .map_err(|error| CpalHostError::Device(error.to_string()))
810        }
811        /// Stops callback delivery until [`Self::play`].
812        ///
813        /// # Errors
814        /// Returns the device error reported by cpal.
815        pub fn pause(&self) -> Result<(), CpalHostError> {
816            self.stream
817                .pause()
818                .map_err(|error| CpalHostError::Device(error.to_string()))
819        }
820        /// Errors the stream reported, plus device buffers that were not whole
821        /// frames and played silent.
822        #[must_use]
823        pub fn underruns(&self) -> u64 {
824            self.underruns.load(Ordering::Relaxed)
825        }
826        /// The last error the stream reported (a device that went away, for one), `None` while
827        /// it reported none.
828        #[must_use]
829        pub fn stream_error(&self) -> Option<String> {
830            self.stream_error
831                .lock()
832                .unwrap_or_else(PoisonError::into_inner)
833                .clone()
834        }
835        /// Negotiated device sample rate.
836        #[must_use]
837        pub const fn sample_rate(&self) -> u32 {
838            self.sample_rate
839        }
840        /// Negotiated output channels.
841        #[must_use]
842        pub const fn channels(&self) -> u16 {
843            self.channels
844        }
845        /// Source graph latency for transport compensation.
846        #[must_use]
847        pub const fn latency_samples(&self) -> u32 {
848            self.latency_samples
849        }
850    }
851
852    /// Renders `source` into one interleaved device buffer of
853    /// `channels`, advancing `sample_position`.
854    ///
855    /// Rendered in scratch-sized pieces. Mono devices get mono, others stereo in the first
856    /// two channels and silence elsewhere. Returns false, after writing silence, for a buffer
857    /// that is not whole frames.
858    pub(super) fn fill_device_buffer(
859        source: &mut impl RealtimeAudioSource,
860        planar: &mut [Vec<f32>; 2],
861        data: &mut [f32],
862        channels: usize,
863        device_rate: u32,
864        sample_position: &mut i64,
865    ) -> bool {
866        let piece = planar[0].len();
867        if channels == 0 || piece == 0 || !data.len().is_multiple_of(channels) {
868            data.fill(0.0);
869            return false;
870        }
871        let rendered = channels.min(2);
872        for chunk in data.chunks_mut(piece * channels) {
873            let frames = chunk.len() / channels;
874            let ctx = ProcessCtx {
875                position: MediaTime::from_ticks(
876                    sample_position
877                        .saturating_mul(TICKS_PER_SECOND)
878                        .div_euclid(i64::from(device_rate)),
879                ),
880                sample_position: *sample_position,
881                sample_rate: device_rate,
882                transport: TransportState::Playing,
883            };
884            let (left, right) = planar.split_at_mut(1);
885            if rendered == 1 {
886                source.render(&ctx, &mut [&mut left[0][..frames]]);
887            } else {
888                source.render(&ctx, &mut [&mut left[0][..frames], &mut right[0][..frames]]);
889            }
890            for (frame, destination) in chunk.chunks_exact_mut(channels).enumerate() {
891                for (channel, sample) in destination.iter_mut().enumerate() {
892                    *sample = if channel < rendered {
893                        planar[channel][frame]
894                    } else {
895                        0.0
896                    };
897                }
898            }
899            *sample_position =
900                sample_position.saturating_add(i64::try_from(frames).unwrap_or(i64::MAX));
901        }
902        true
903    }
904}
905
906#[cfg(feature = "cpal-host")]
907pub use realtime::*;
908
909#[cfg(test)]
910#[path = "audio_host_tests.rs"]
911mod tests;