alpha2-host-core 0.9.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
//! Supplies an extraction session the timeline's sound from the project mixer.

use alpha2_audio::TransportState;
use alpha2_engine::extract::{AudioChannels, Need, SuppliedAudio, TimelineAudioRead};
use alpha2_engine::{AudioRenderer, AudioTap, EngineProject};
use alpha2_media::CancelToken;

use crate::audio_host::{OfflineAudioError, ProjectAudioSources};

/// Answers a session's [`Need::TimelineAudio`] with what an export of the project mixes: the
/// master output after the limiter, without an export's loudness normalization gain, or a tap.
///
/// The mix is stereo at the project rate under exact continuity; `sources` decodes what each
/// block of it reads, as for an export. Another rate, a mono need and the order of the needs
/// are [`TimelineAudioRead`]'s.
pub struct TimelineAudioSupplier<S> {
    snapshot: EngineProject,
    renderer: AudioRenderer,
    tapped: bool,
    sources: S,
    read: TimelineAudioRead,
    cancel: CancelToken,
}

impl<S: ProjectAudioSources> TimelineAudioSupplier<S> {
    /// A supplier of `snapshot`'s master output, or of `tap`, at `rate`; `cancel` stops a
    /// decode.
    ///
    /// # Errors
    /// [`OfflineAudioError::Engine`] when the project cannot be mixed or lacks the tapped track
    /// or bus, [`OfflineAudioError::InvalidInput`] for a rate the mix cannot be converted to.
    pub fn new(
        snapshot: EngineProject,
        tap: Option<&AudioTap>,
        rate: u32,
        sources: S,
        cancel: CancelToken,
    ) -> Result<Self, OfflineAudioError> {
        let renderer = AudioRenderer::with_taps(
            &snapshot,
            2,
            alpha2_engine::extract::TIMELINE_MIX_BLOCK,
            tap.map_or(&[], std::slice::from_ref),
        )
        .map_err(OfflineAudioError::Engine)?;
        let read = TimelineAudioRead::new(renderer.sample_rate(), rate)
            .map_err(|_| OfflineAudioError::InvalidInput)?;
        Ok(Self {
            snapshot,
            renderer,
            tapped: tap.is_some(),
            sources,
            read,
            cancel,
        })
    }

    /// Exactly `frames` frames from `start_sample` at the supplier's rate, in `channels`: two
    /// for [`AudioChannels::Source`]. Samples before timeline zero are silent.
    ///
    /// # Errors
    /// [`OfflineAudioError::Engine`] when the mixer refuses a block,
    /// [`OfflineAudioError::Sources`] when the sources cannot make a block's audio ready (a
    /// cancel included), and [`OfflineAudioError::MissingSources`] when an audible clip had no
    /// decoded media.
    pub fn block(
        &mut self,
        start_sample: i64,
        frames: u32,
        channels: AudioChannels,
    ) -> Result<SuppliedAudio, OfflineAudioError> {
        self.read.begin(start_sample, frames, channels);
        while let Some((at, count)) = self.read.wanted() {
            let needs = self
                .renderer
                .audio_needs(&self.snapshot, at, count)
                .map_err(OfflineAudioError::Engine)?;
            self.sources
                .prepare(&needs, &self.cancel)
                .map_err(OfflineAudioError::Sources)?;
            let status = self
                .renderer
                .render(
                    &self.snapshot,
                    at,
                    count,
                    &self.sources,
                    TransportState::Playing,
                )
                .map_err(OfflineAudioError::Engine)?;
            if !status.missing_sources.is_empty() {
                return Err(OfflineAudioError::MissingSources(status.missing_sources));
            }
            let plane = |channel| {
                let plane = if self.tapped {
                    self.renderer.tap_channel(0, channel)
                } else {
                    self.renderer.channel(channel)
                };
                plane.get(..count).ok_or(OfflineAudioError::InvalidInput)
            };
            self.read
                .push(plane(0)?, plane(1)?)
                .map_err(|_| OfflineAudioError::InvalidInput)?;
        }
        self.read
            .finish()
            .map_err(|_| OfflineAudioError::InvalidInput)
    }

    /// The block `need` asks for.
    ///
    /// # Errors
    /// As [`Self::block`]; [`OfflineAudioError::InvalidInput`] for any other need.
    pub fn supply(&mut self, need: &Need) -> Result<SuppliedAudio, OfflineAudioError> {
        let Need::TimelineAudio {
            start_sample,
            frames,
            channels,
            ..
        } = need
        else {
            return Err(OfflineAudioError::InvalidInput);
        };
        self.block(*start_sample, *frames, *channels)
    }
}

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