alpha2-native 0.9.0

Native headless and real-time host boundary for alpha2.
Documentation
//! Outputs that hold sound only: PCM in a WAVE file, or one encoded stream in its container.

use alpha2_ffmpeg_bridge::OutputFile;
use alpha2_media::{
    AudioBlock, AudioBlockSink, CancelToken, Container, EncodeError, PcmSampleFormat, SpeakerLayout,
};
use rsmpeg::avutil::AVDictionary;
use rsmpeg::ffi;

use crate::audio_input::{AudioStreamConfig, EncoderAudioInput, open_audio_encoder};
use crate::capabilities::NativeAudioCodec;
use crate::convert::{encode_adapter_error, encode_adapter_error_at};
use crate::encode::{
    AudioEncoderConfig, EncodeStageTimings, NativeWavEncodeSink, beat_encode_call,
    encode_audio_block, timed,
};
use crate::partial::{OutputTarget, PartialOutput, PublishReport, SeekNeed};

/// How an audio-only output stores its sound.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum AudioFileCodec {
    /// PCM samples, in a WAVE file.
    Pcm(PcmSampleFormat),
    /// One encoded stream.
    Encoded {
        /// The codec.
        codec: NativeAudioCodec,
        /// Bits per second; the host resolves the level.
        bit_rate: u32,
    },
}

/// Configuration of a transactional audio-only output.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct AudioFileConfig {
    /// The container; WAVE for PCM, one that offers the codec otherwise.
    pub container: Container,
    /// How the sound is stored.
    pub codec: AudioFileCodec,
    /// Project audio sample rate.
    pub sample_rate: u32,
    /// The speakers every block feeds, one plane each.
    pub speakers: SpeakerLayout,
}

/// One encoded audio stream muxed alone through the linked `FFmpeg` libraries: the audio half of
/// [`NativeAvEncodeSink`](crate::NativeAvEncodeSink), encoded on the calling thread.
pub struct NativeAudioEncodeSink {
    output: Option<OutputFile>,
    partial: PartialOutput,
    published: Option<PublishReport>,
    encoder: AudioEncoderConfig,
    encoder_name: String,
    input: EncoderAudioInput,
    encoded_samples: u64,
    frames_written: u64,
    complete: bool,
    stages: EncodeStageTimings,
}

/// The `ftyp` major brand of an MPEG-4 file that holds sound only, as its `.m4a` name says.
const M4A_BRAND: &std::ffi::CStr = c"M4A ";

impl NativeAudioEncodeSink {
    /// Creates the encoder and the muxer of `container` without touching the destination.
    ///
    /// # Errors
    /// For a codec the container does not offer, an invalid stream, an encoder the runtime lacks
    /// or cannot open, an existing output or a file-system failure.
    pub fn create(
        path: impl Into<OutputTarget>,
        container: Container,
        stream: AudioStreamConfig,
    ) -> Result<Self, EncodeError> {
        if !container.offers_audio(stream.codec.model()) {
            return Err(EncodeError::Adapter(format!(
                "{container} does not offer audio codec {}",
                stream.codec.as_str()
            )));
        }
        if stream.sample_rate == 0
            || stream.channels == 0
            || stream.channels > 8
            || stream.bit_rate == 0
        {
            return Err(EncodeError::Adapter(format!(
                "the audio output ({} channels at {} Hz, {} bit/s) is refused: 1 to 8 channels, a positive rate and bitrate",
                stream.channels, stream.sample_rate, stream.bit_rate
            )));
        }
        let target = path.into();
        let audio_only_name = target
            .path
            .extension()
            .and_then(std::ffi::OsStr::to_str)
            .is_some_and(|extension| {
                container
                    .audio_only_extensions()
                    .iter()
                    .any(|known| known.eq_ignore_ascii_case(extension))
            });
        let partial = PartialOutput::claim(&target, SeekNeed::Required)?;
        let mut output = crate::partial::open_muxer(&partial, container)?;
        let global_header =
            output.oformat().flags & i32::try_from(ffi::AVFMT_GLOBALHEADER).unwrap_or(0) != 0;
        let audio = open_audio_encoder(stream, global_header)?;
        let stream_index;
        {
            let mut muxed = output.new_stream();
            muxed.set_time_base(audio.encoder_time_base);
            muxed.set_codecpar(audio.encoder.extract_codecpar());
            stream_index = muxed.index;
        }
        let mut options = crate::convert::muxer_header_options(container);
        if container == Container::Mp4 && audio_only_name {
            options = Some(match options {
                Some(options) => options.set(c"brand", M4A_BRAND, 0),
                None => AVDictionary::new(c"brand", M4A_BRAND, 0),
            });
        }
        output
            .write_header(&mut options)
            .map_err(encode_adapter_error)?;
        let stream_time_base =
            output.streams()[usize::try_from(stream_index).unwrap_or(0)].time_base;
        Ok(Self {
            output: Some(output),
            partial,
            published: None,
            encoder: AudioEncoderConfig {
                encoder: audio.encoder,
                stream_index,
                encoder_time_base: audio.encoder_time_base,
                stream_time_base,
                sample_rate: audio.encoder_rate,
                sample_format: audio.sample_format,
            },
            encoder_name: audio.encoder_name,
            input: audio.input,
            encoded_samples: 0,
            frames_written: 0,
            complete: false,
            stages: EncodeStageTimings::default(),
        })
    }

    /// The `FFmpeg` name of the encoder that opened.
    #[must_use]
    pub fn encoder_name(&self) -> &str {
        &self.encoder_name
    }

    /// Project-rate samples per channel taken so far.
    #[must_use]
    pub const fn frames_written(&self) -> u64 {
        self.frames_written
    }

    /// Where this sink's time has gone so far.
    #[must_use]
    pub const fn stage_timings(&self) -> EncodeStageTimings {
        self.stages
    }

    /// How the finished file was published; `None` until it is.
    #[must_use]
    pub const fn publish_report(&self) -> Option<PublishReport> {
        self.published
    }

    fn encode(&mut self, frame: Option<&[Vec<f32>]>) -> Result<(), EncodeError> {
        let packets = encode_audio_block(
            &mut self.encoder,
            frame,
            &mut self.encoded_samples,
            &mut self.stages,
        )?;
        let output = self
            .output
            .as_mut()
            .ok_or_else(|| EncodeError::Adapter("muxer is already closed".into()))?;
        for mut queued in packets {
            let bytes = u64::try_from(queued.packet.size).unwrap_or(0);
            timed(&mut self.stages.audio_mux_write, || {
                output.interleaved_write_frame(&mut queued.packet)
            })
            .map_err(|error| encode_adapter_error_at("packet write failed", error))?;
            self.partial.wrote(bytes)?;
        }
        Ok(())
    }

    fn write_block(&mut self, block: &AudioBlock) -> Result<(), EncodeError> {
        let frames = self.input.push(block)?;
        for frame in frames {
            self.encode(Some(&frame))?;
        }
        let taken = block.channels.first().map_or(0, Vec::len);
        self.frames_written = self
            .frames_written
            .saturating_add(u64::try_from(taken).unwrap_or(u64::MAX));
        Ok(())
    }

    fn close_output(&mut self) -> Result<(), EncodeError> {
        for frame in self.input.finish() {
            self.encode(Some(&frame))?;
        }
        self.encode(None)?;
        beat_encode_call();
        self.output
            .as_mut()
            .ok_or_else(|| EncodeError::Adapter("muxer is already closed".into()))?
            .write_trailer()
            .map_err(encode_adapter_error)?;
        if let Some(output) = self.output.take() {
            beat_encode_call();
            output
                .close()
                .map_err(|error| encode_adapter_error_at("closing the output", error))?;
        }
        Ok(())
    }

    /// Flushes the encoder, writes the trailer and closes the file, which stays a partial file
    /// until [`Self::publish`].
    ///
    /// # Errors
    /// When the encoder, the muxer or the file system refuses.
    pub fn seal(&mut self) -> Result<(), EncodeError> {
        self.close_output()
            .map_err(|error| self.partial.explain(error))
    }

    /// Moves the sealed file into place.
    ///
    /// # Errors
    /// As [`PartialOutput::finish`].
    pub fn publish(&mut self, cancel: &CancelToken) -> Result<PublishReport, EncodeError> {
        let report = self.partial.finish(cancel)?;
        self.published = Some(report);
        self.complete = true;
        Ok(report)
    }

    fn cleanup(&mut self) -> Result<(), EncodeError> {
        drop(self.output.take());
        self.partial.discard()
    }
}

impl AudioBlockSink for NativeAudioEncodeSink {
    fn write_audio(&mut self, block: &AudioBlock, cancel: &CancelToken) -> Result<(), EncodeError> {
        if cancel.is_cancelled() {
            self.cleanup()?;
            return Err(EncodeError::Cancelled);
        }
        self.write_block(block)
            .map_err(|error| self.partial.explain(error))
    }

    fn finish_audio(&mut self, cancel: &CancelToken) -> Result<(), EncodeError> {
        if cancel.is_cancelled() {
            self.cleanup()?;
            return Err(EncodeError::Cancelled);
        }
        self.seal()?;
        self.publish(cancel).map(|_| ())
    }

    fn abort_audio(&mut self) -> Result<(), EncodeError> {
        self.cleanup()
    }
}

impl Drop for NativeAudioEncodeSink {
    fn drop(&mut self) {
        if !self.complete {
            let _ = self.cleanup();
        }
    }
}

/// A transactional audio-only output of either kind.
pub enum NativeAudioFileSink {
    /// PCM in a WAVE file.
    Wav(Box<NativeWavEncodeSink>),
    /// One encoded stream in its container.
    Encoded(Box<NativeAudioEncodeSink>),
}

impl NativeAudioFileSink {
    /// Creates the output `config` describes without touching the destination.
    ///
    /// # Errors
    /// For PCM outside a WAVE file or an encoded codec in one, a layout an encoder does not
    /// take, and as [`NativeWavEncodeSink::create_with_format`] and
    /// [`NativeAudioEncodeSink::create`].
    pub fn create(
        path: impl Into<OutputTarget>,
        config: AudioFileConfig,
    ) -> Result<Self, EncodeError> {
        match (config.codec, config.container) {
            (AudioFileCodec::Pcm(samples), Container::Wav) => {
                NativeWavEncodeSink::create_with_format(
                    path,
                    config.sample_rate,
                    config.speakers,
                    samples,
                )
                .map(|sink| Self::Wav(Box::new(sink)))
            }
            (AudioFileCodec::Pcm(_), container) => Err(EncodeError::Adapter(format!(
                "{container} does not hold PCM; a WAVE file does"
            ))),
            (AudioFileCodec::Encoded { codec, .. }, Container::Wav) => Err(EncodeError::Adapter(
                format!("wav does not offer audio codec {}", codec.as_str()),
            )),
            (AudioFileCodec::Encoded { codec, bit_rate }, container) => {
                let channels = u16::try_from(config.speakers.channels()).map_err(|_| {
                    EncodeError::Adapter("the audio output has too many channels".into())
                })?;
                NativeAudioEncodeSink::create(
                    path,
                    container,
                    AudioStreamConfig {
                        codec,
                        sample_rate: config.sample_rate,
                        channels,
                        bit_rate,
                    },
                )
                .map(|sink| Self::Encoded(Box::new(sink)))
            }
        }
    }

    /// The `FFmpeg` name of the encoder; `None` for PCM, which has none.
    #[must_use]
    pub fn encoder_name(&self) -> Option<&str> {
        match self {
            Self::Wav(_) => None,
            Self::Encoded(sink) => Some(sink.encoder_name()),
        }
    }

    /// Project-rate samples per channel taken so far.
    #[must_use]
    pub fn frames_written(&self) -> u64 {
        match self {
            Self::Wav(sink) => sink.frames_written(),
            Self::Encoded(sink) => sink.frames_written(),
        }
    }

    /// Completes and closes the file, which stays a partial file until [`Self::publish`], so
    /// several outputs of one export can all be whole before any is moved into place.
    ///
    /// # Errors
    /// When the encoder, the muxer or the file system refuses.
    pub fn seal(&mut self) -> Result<(), EncodeError> {
        match self {
            Self::Wav(sink) => sink.seal(),
            Self::Encoded(sink) => sink.seal(),
        }
    }

    /// Moves the sealed file into place.
    ///
    /// # Errors
    /// As [`PartialOutput::finish`].
    pub fn publish(&mut self, cancel: &CancelToken) -> Result<PublishReport, EncodeError> {
        match self {
            Self::Wav(sink) => sink.publish(cancel),
            Self::Encoded(sink) => sink.publish(cancel),
        }
    }
}

impl AudioBlockSink for NativeAudioFileSink {
    fn write_audio(&mut self, block: &AudioBlock, cancel: &CancelToken) -> Result<(), EncodeError> {
        match self {
            Self::Wav(sink) => sink.write_audio(block, cancel),
            Self::Encoded(sink) => sink.write_audio(block, cancel),
        }
    }

    fn finish_audio(&mut self, cancel: &CancelToken) -> Result<(), EncodeError> {
        match self {
            Self::Wav(sink) => sink.finish_audio(cancel),
            Self::Encoded(sink) => sink.finish_audio(cancel),
        }
    }

    fn abort_audio(&mut self) -> Result<(), EncodeError> {
        match self {
            Self::Wav(sink) => sink.abort_audio(),
            Self::Encoded(sink) => sink.abort_audio(),
        }
    }
}