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.
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_time_base: AVRational,
35    /// The input the encoder takes its frames from.
36    pub(crate) input: EncoderAudioInput,
37    /// The rate it is encoded at ([`encoder_sample_rate`]).
38    pub(crate) encoder_rate: u32,
39    /// The sample format its frames carry ([`encoder_sample_format`]).
40    pub(crate) sample_format: ffi::AVSampleFormat,
41}
42
43/// Opens the encoder for `config` with global headers, which every export container uses.
44///
45/// # Errors
46/// When the runtime has no encoder for the codec, it takes none of the sample formats alpha2 can
47/// provide, it has no fixed frame size, or it does not open.
48pub(crate) fn open_audio_encoder(
49    config: AudioStreamConfig,
50    global_header: bool,
51) -> Result<OpenedAudioEncoder, EncodeError> {
52    let AudioStreamConfig {
53        codec,
54        sample_rate,
55        channels,
56        bit_rate,
57    } = config;
58    let encoder_codec = crate::capabilities::audio_encoder(codec).ok_or_else(|| {
59        EncodeError::Adapter(format!(
60            "this FFmpeg runtime has no {} encoder",
61            codec.as_str()
62        ))
63    })?;
64    let sample_format = encoder_sample_format(&encoder_codec).ok_or_else(|| {
65        EncodeError::Adapter(format!(
66            "the {} encoder takes neither float nor 16-bit samples",
67            codec.as_str()
68        ))
69    })?;
70    let encoder_rate = encoder_sample_rate(&encoder_codec, sample_rate);
71    let rate = i32::try_from(encoder_rate)
72        .map_err(|_| EncodeError::Adapter("audio sample rate is out of range".into()))?;
73    let encoder_time_base = ra(1, rate);
74    let mut encoder = AVCodecContext::new(&encoder_codec);
75    encoder.set_sample_rate(rate);
76    encoder.set_sample_fmt(sample_format);
77    encoder.set_ch_layout(AVChannelLayout::from_nb_channels(i32::from(channels)).into_inner());
78    encoder.set_time_base(encoder_time_base);
79    encoder.set_bit_rate(i64::from(bit_rate));
80    if global_header {
81        encoder.set_flags(
82            encoder.flags | i32::try_from(ffi::AV_CODEC_FLAG_GLOBAL_HEADER).unwrap_or(0),
83        );
84    }
85    encoder.open(None).map_err(encode_adapter_error)?;
86    let frame_size = usize::try_from(encoder.frame_size)
87        .ok()
88        .filter(|size| *size > 0)
89        .ok_or_else(|| {
90            EncodeError::Adapter(format!(
91                "the {} encoder has no fixed frame size",
92                codec.as_str()
93            ))
94        })?;
95    Ok(OpenedAudioEncoder {
96        encoder,
97        encoder_time_base,
98        input: EncoderAudioInput::new(sample_rate, encoder_rate, usize::from(channels), frame_size),
99        encoder_rate,
100        sample_format,
101    })
102}
103
104/// The sample format alpha2 hands `codec`: the first it takes of planar float, interleaved float,
105/// interleaved 16-bit; planar float if it lists none; `None` if it takes none of the three.
106pub(crate) fn encoder_sample_format(codec: &AVCodecRef<'_>) -> Option<ffi::AVSampleFormat> {
107    let Some(formats) = codec.sample_fmts() else {
108        return Some(ffi::AV_SAMPLE_FMT_FLTP);
109    };
110    [
111        ffi::AV_SAMPLE_FMT_FLTP,
112        ffi::AV_SAMPLE_FMT_FLT,
113        ffi::AV_SAMPLE_FMT_S16,
114    ]
115    .into_iter()
116    .find(|format| formats.contains(format))
117}
118
119/// The rate `codec` encodes a `project_rate` project at
120/// ([`alpha2_host_core::audio_frames::encoder_sample_rate`]).
121pub(crate) fn encoder_sample_rate(codec: &AVCodecRef<'_>, project_rate: u32) -> u32 {
122    let rates = codec.supported_samplerates().map(|rates| {
123        rates
124            .iter()
125            .filter_map(|rate| u32::try_from(*rate).ok())
126            .collect::<Vec<_>>()
127    });
128    alpha2_host_core::audio_frames::encoder_sample_rate(rates.as_deref(), project_rate)
129}