Skip to main content

alpha2_native/
audio_input.rs

1//! Audio encoder input: project audio at a rate the codec carries, cut into whole frames plus an
2//! exact last frame, in the encoder's sample format.
3//!
4//! `aac` takes only MPEG-4 rates and `libopus` only 8, 12, 16, 24 and 48 kHz, while projects run at
5//! 8 to 96 kHz. Unsupported rates export at the next one up (48 kHz for Opus above 24), resampled
6//! by `alpha2_audio::Resampler`. The last frame is exactly what is left (`aac` accepts a short
7//! frame, `libopus` pads it), so the track ends where the export's audio does.
8
9use alpha2_media::EncodeError;
10use rsmpeg::avcodec::{AVCodecContext, AVCodecRef};
11use rsmpeg::avutil::{AVChannelLayout, AVRational, ra};
12use rsmpeg::ffi;
13
14use crate::capabilities::NativeAudioCodec;
15use crate::convert::encode_adapter_error;
16pub(crate) use alpha2_host_core::audio_frames::EncoderAudioInput;
17
18/// The audio stream an export encodes, beside its video or alone.
19#[derive(Copy, Clone, Debug, Eq, PartialEq)]
20pub struct AudioStreamConfig {
21    /// The codec to encode.
22    pub codec: NativeAudioCodec,
23    /// Project audio sample rate.
24    pub sample_rate: u32,
25    /// Channel count.
26    pub channels: u16,
27    /// Bitrate in bits per second; the host resolves the level.
28    pub bit_rate: u32,
29}
30
31/// An opened audio encoder, before it has a stream.
32pub(crate) struct OpenedAudioEncoder {
33    pub(crate) encoder: AVCodecContext,
34    pub(crate) encoder_name: String,
35    pub(crate) encoder_time_base: AVRational,
36    /// The input the encoder takes its frames from.
37    pub(crate) input: EncoderAudioInput,
38    /// The rate it is encoded at ([`encoder_sample_rate`]).
39    pub(crate) encoder_rate: u32,
40    /// The sample format its frames carry ([`encoder_sample_format`]).
41    pub(crate) sample_format: ffi::AVSampleFormat,
42}
43
44/// Opens the encoder for `config` with global headers, which every export container uses.
45///
46/// # Errors
47/// When the runtime has no encoder for the codec, it takes none of the sample formats alpha2 can
48/// provide, it has no fixed frame size, or it does not open.
49pub(crate) fn open_audio_encoder(
50    config: AudioStreamConfig,
51    global_header: bool,
52) -> Result<OpenedAudioEncoder, EncodeError> {
53    let AudioStreamConfig {
54        codec,
55        sample_rate,
56        channels,
57        bit_rate,
58    } = config;
59    let encoder_codec = crate::capabilities::audio_encoder(codec).ok_or_else(|| {
60        EncodeError::Adapter(format!(
61            "this FFmpeg runtime has no {} encoder",
62            codec.as_str()
63        ))
64    })?;
65    let sample_format = encoder_sample_format(&encoder_codec).ok_or_else(|| {
66        EncodeError::Adapter(format!(
67            "the {} encoder takes neither float nor 16-bit samples",
68            codec.as_str()
69        ))
70    })?;
71    let encoder_rate = encoder_sample_rate(&encoder_codec, sample_rate);
72    let rate = i32::try_from(encoder_rate)
73        .map_err(|_| EncodeError::Adapter("audio sample rate is out of range".into()))?;
74    let encoder_time_base = ra(1, rate);
75    let mut encoder = AVCodecContext::new(&encoder_codec);
76    encoder.set_sample_rate(rate);
77    encoder.set_sample_fmt(sample_format);
78    encoder.set_ch_layout(AVChannelLayout::from_nb_channels(i32::from(channels)).into_inner());
79    encoder.set_time_base(encoder_time_base);
80    encoder.set_bit_rate(i64::from(bit_rate));
81    if global_header {
82        encoder.set_flags(
83            encoder.flags | i32::try_from(ffi::AV_CODEC_FLAG_GLOBAL_HEADER).unwrap_or(0),
84        );
85    }
86    encoder.open(None).map_err(encode_adapter_error)?;
87    let frame_size = usize::try_from(encoder.frame_size)
88        .ok()
89        .filter(|size| *size > 0)
90        .ok_or_else(|| {
91            EncodeError::Adapter(format!(
92                "the {} encoder has no fixed frame size",
93                codec.as_str()
94            ))
95        })?;
96    Ok(OpenedAudioEncoder {
97        encoder,
98        encoder_name: encoder_codec.name().to_string_lossy().into_owned(),
99        encoder_time_base,
100        input: EncoderAudioInput::new(sample_rate, encoder_rate, usize::from(channels), frame_size),
101        encoder_rate,
102        sample_format,
103    })
104}
105
106/// The sample format alpha2 hands `codec`: the first it takes of planar float, interleaved float,
107/// interleaved 16-bit; planar float if it lists none; `None` if it takes none of the three.
108pub(crate) fn encoder_sample_format(codec: &AVCodecRef<'_>) -> Option<ffi::AVSampleFormat> {
109    let Some(formats) = codec.sample_fmts() else {
110        return Some(ffi::AV_SAMPLE_FMT_FLTP);
111    };
112    [
113        ffi::AV_SAMPLE_FMT_FLTP,
114        ffi::AV_SAMPLE_FMT_FLT,
115        ffi::AV_SAMPLE_FMT_S16,
116    ]
117    .into_iter()
118    .find(|format| formats.contains(format))
119}
120
121/// The rate `codec` encodes a `project_rate` project at
122/// ([`alpha2_host_core::audio_frames::encoder_sample_rate`]).
123pub(crate) fn encoder_sample_rate(codec: &AVCodecRef<'_>, project_rate: u32) -> u32 {
124    let rates = codec.supported_samplerates().map(|rates| {
125        rates
126            .iter()
127            .filter_map(|rate| u32::try_from(*rate).ok())
128            .collect::<Vec<_>>()
129    });
130    alpha2_host_core::audio_frames::encoder_sample_rate(rates.as_deref(), project_rate)
131}