Skip to main content

alpha2_native/
audio_encode.rs

1//! Outputs that hold sound only: PCM in a WAVE file, or one encoded stream in its container.
2
3use alpha2_ffmpeg_bridge::OutputFile;
4use alpha2_media::{
5    AudioBlock, AudioBlockSink, CancelToken, Container, EncodeError, PcmSampleFormat, SpeakerLayout,
6};
7use rsmpeg::avutil::AVDictionary;
8use rsmpeg::ffi;
9
10use crate::audio_input::{AudioStreamConfig, EncoderAudioInput, open_audio_encoder};
11use crate::capabilities::NativeAudioCodec;
12use crate::convert::{encode_adapter_error, encode_adapter_error_at};
13use crate::encode::{
14    AudioEncoderConfig, EncodeStageTimings, NativeWavEncodeSink, beat_encode_call,
15    encode_audio_block, timed,
16};
17use crate::partial::{OutputTarget, PartialOutput, PublishReport, SeekNeed};
18
19/// How an audio-only output stores its sound.
20#[derive(Copy, Clone, Debug, Eq, PartialEq)]
21pub enum AudioFileCodec {
22    /// PCM samples, in a WAVE file.
23    Pcm(PcmSampleFormat),
24    /// One encoded stream.
25    Encoded {
26        /// The codec.
27        codec: NativeAudioCodec,
28        /// Bits per second; the host resolves the level.
29        bit_rate: u32,
30    },
31}
32
33/// Configuration of a transactional audio-only output.
34#[derive(Copy, Clone, Debug, Eq, PartialEq)]
35pub struct AudioFileConfig {
36    /// The container; WAVE for PCM, one that offers the codec otherwise.
37    pub container: Container,
38    /// How the sound is stored.
39    pub codec: AudioFileCodec,
40    /// Project audio sample rate.
41    pub sample_rate: u32,
42    /// The speakers every block feeds, one plane each.
43    pub speakers: SpeakerLayout,
44}
45
46/// One encoded audio stream muxed alone through the linked `FFmpeg` libraries: the audio half of
47/// [`NativeAvEncodeSink`](crate::NativeAvEncodeSink), encoded on the calling thread.
48pub struct NativeAudioEncodeSink {
49    output: Option<OutputFile>,
50    partial: PartialOutput,
51    published: Option<PublishReport>,
52    encoder: AudioEncoderConfig,
53    encoder_name: String,
54    input: EncoderAudioInput,
55    encoded_samples: u64,
56    frames_written: u64,
57    complete: bool,
58    stages: EncodeStageTimings,
59}
60
61/// The `ftyp` major brand of an MPEG-4 file that holds sound only, as its `.m4a` name says.
62const M4A_BRAND: &std::ffi::CStr = c"M4A ";
63
64impl NativeAudioEncodeSink {
65    /// Creates the encoder and the muxer of `container` without touching the destination.
66    ///
67    /// # Errors
68    /// For a codec the container does not offer, an invalid stream, an encoder the runtime lacks
69    /// or cannot open, an existing output or a file-system failure.
70    pub fn create(
71        path: impl Into<OutputTarget>,
72        container: Container,
73        stream: AudioStreamConfig,
74    ) -> Result<Self, EncodeError> {
75        if !container.offers_audio(stream.codec.model()) {
76            return Err(EncodeError::Adapter(format!(
77                "{container} does not offer audio codec {}",
78                stream.codec.as_str()
79            )));
80        }
81        if stream.sample_rate == 0
82            || stream.channels == 0
83            || stream.channels > 8
84            || stream.bit_rate == 0
85        {
86            return Err(EncodeError::Adapter(format!(
87                "the audio output ({} channels at {} Hz, {} bit/s) is refused: 1 to 8 channels, a positive rate and bitrate",
88                stream.channels, stream.sample_rate, stream.bit_rate
89            )));
90        }
91        let target = path.into();
92        let audio_only_name = target
93            .path
94            .extension()
95            .and_then(std::ffi::OsStr::to_str)
96            .is_some_and(|extension| {
97                container
98                    .audio_only_extensions()
99                    .iter()
100                    .any(|known| known.eq_ignore_ascii_case(extension))
101            });
102        let partial = PartialOutput::claim(&target, SeekNeed::Required)?;
103        let mut output = crate::partial::open_muxer(&partial, container)?;
104        let global_header =
105            output.oformat().flags & i32::try_from(ffi::AVFMT_GLOBALHEADER).unwrap_or(0) != 0;
106        let audio = open_audio_encoder(stream, global_header)?;
107        let stream_index;
108        {
109            let mut muxed = output.new_stream();
110            muxed.set_time_base(audio.encoder_time_base);
111            muxed.set_codecpar(audio.encoder.extract_codecpar());
112            stream_index = muxed.index;
113        }
114        let mut options = crate::convert::muxer_header_options(container);
115        if container == Container::Mp4 && audio_only_name {
116            options = Some(match options {
117                Some(options) => options.set(c"brand", M4A_BRAND, 0),
118                None => AVDictionary::new(c"brand", M4A_BRAND, 0),
119            });
120        }
121        output
122            .write_header(&mut options)
123            .map_err(encode_adapter_error)?;
124        let stream_time_base =
125            output.streams()[usize::try_from(stream_index).unwrap_or(0)].time_base;
126        Ok(Self {
127            output: Some(output),
128            partial,
129            published: None,
130            encoder: AudioEncoderConfig {
131                encoder: audio.encoder,
132                stream_index,
133                encoder_time_base: audio.encoder_time_base,
134                stream_time_base,
135                sample_rate: audio.encoder_rate,
136                sample_format: audio.sample_format,
137            },
138            encoder_name: audio.encoder_name,
139            input: audio.input,
140            encoded_samples: 0,
141            frames_written: 0,
142            complete: false,
143            stages: EncodeStageTimings::default(),
144        })
145    }
146
147    /// The `FFmpeg` name of the encoder that opened.
148    #[must_use]
149    pub fn encoder_name(&self) -> &str {
150        &self.encoder_name
151    }
152
153    /// Project-rate samples per channel taken so far.
154    #[must_use]
155    pub const fn frames_written(&self) -> u64 {
156        self.frames_written
157    }
158
159    /// Where this sink's time has gone so far.
160    #[must_use]
161    pub const fn stage_timings(&self) -> EncodeStageTimings {
162        self.stages
163    }
164
165    /// How the finished file was published; `None` until it is.
166    #[must_use]
167    pub const fn publish_report(&self) -> Option<PublishReport> {
168        self.published
169    }
170
171    fn encode(&mut self, frame: Option<&[Vec<f32>]>) -> Result<(), EncodeError> {
172        let packets = encode_audio_block(
173            &mut self.encoder,
174            frame,
175            &mut self.encoded_samples,
176            &mut self.stages,
177        )?;
178        let output = self
179            .output
180            .as_mut()
181            .ok_or_else(|| EncodeError::Adapter("muxer is already closed".into()))?;
182        for mut queued in packets {
183            let bytes = u64::try_from(queued.packet.size).unwrap_or(0);
184            timed(&mut self.stages.audio_mux_write, || {
185                output.interleaved_write_frame(&mut queued.packet)
186            })
187            .map_err(|error| encode_adapter_error_at("packet write failed", error))?;
188            self.partial.wrote(bytes)?;
189        }
190        Ok(())
191    }
192
193    fn write_block(&mut self, block: &AudioBlock) -> Result<(), EncodeError> {
194        let frames = self.input.push(block)?;
195        for frame in frames {
196            self.encode(Some(&frame))?;
197        }
198        let taken = block.channels.first().map_or(0, Vec::len);
199        self.frames_written = self
200            .frames_written
201            .saturating_add(u64::try_from(taken).unwrap_or(u64::MAX));
202        Ok(())
203    }
204
205    fn close_output(&mut self) -> Result<(), EncodeError> {
206        for frame in self.input.finish() {
207            self.encode(Some(&frame))?;
208        }
209        self.encode(None)?;
210        beat_encode_call();
211        self.output
212            .as_mut()
213            .ok_or_else(|| EncodeError::Adapter("muxer is already closed".into()))?
214            .write_trailer()
215            .map_err(encode_adapter_error)?;
216        if let Some(output) = self.output.take() {
217            beat_encode_call();
218            output
219                .close()
220                .map_err(|error| encode_adapter_error_at("closing the output", error))?;
221        }
222        Ok(())
223    }
224
225    /// Flushes the encoder, writes the trailer and closes the file, which stays a partial file
226    /// until [`Self::publish`].
227    ///
228    /// # Errors
229    /// When the encoder, the muxer or the file system refuses.
230    pub fn seal(&mut self) -> Result<(), EncodeError> {
231        self.close_output()
232            .map_err(|error| self.partial.explain(error))
233    }
234
235    /// Moves the sealed file into place.
236    ///
237    /// # Errors
238    /// As [`PartialOutput::finish`].
239    pub fn publish(&mut self, cancel: &CancelToken) -> Result<PublishReport, EncodeError> {
240        let report = self.partial.finish(cancel)?;
241        self.published = Some(report);
242        self.complete = true;
243        Ok(report)
244    }
245
246    fn cleanup(&mut self) -> Result<(), EncodeError> {
247        drop(self.output.take());
248        self.partial.discard()
249    }
250}
251
252impl AudioBlockSink for NativeAudioEncodeSink {
253    fn write_audio(&mut self, block: &AudioBlock, cancel: &CancelToken) -> Result<(), EncodeError> {
254        if cancel.is_cancelled() {
255            self.cleanup()?;
256            return Err(EncodeError::Cancelled);
257        }
258        self.write_block(block)
259            .map_err(|error| self.partial.explain(error))
260    }
261
262    fn finish_audio(&mut self, cancel: &CancelToken) -> Result<(), EncodeError> {
263        if cancel.is_cancelled() {
264            self.cleanup()?;
265            return Err(EncodeError::Cancelled);
266        }
267        self.seal()?;
268        self.publish(cancel).map(|_| ())
269    }
270
271    fn abort_audio(&mut self) -> Result<(), EncodeError> {
272        self.cleanup()
273    }
274}
275
276impl Drop for NativeAudioEncodeSink {
277    fn drop(&mut self) {
278        if !self.complete {
279            let _ = self.cleanup();
280        }
281    }
282}
283
284/// A transactional audio-only output of either kind.
285pub enum NativeAudioFileSink {
286    /// PCM in a WAVE file.
287    Wav(Box<NativeWavEncodeSink>),
288    /// One encoded stream in its container.
289    Encoded(Box<NativeAudioEncodeSink>),
290}
291
292impl NativeAudioFileSink {
293    /// Creates the output `config` describes without touching the destination.
294    ///
295    /// # Errors
296    /// For PCM outside a WAVE file or an encoded codec in one, a layout an encoder does not
297    /// take, and as [`NativeWavEncodeSink::create_with_format`] and
298    /// [`NativeAudioEncodeSink::create`].
299    pub fn create(
300        path: impl Into<OutputTarget>,
301        config: AudioFileConfig,
302    ) -> Result<Self, EncodeError> {
303        match (config.codec, config.container) {
304            (AudioFileCodec::Pcm(samples), Container::Wav) => {
305                NativeWavEncodeSink::create_with_format(
306                    path,
307                    config.sample_rate,
308                    config.speakers,
309                    samples,
310                )
311                .map(|sink| Self::Wav(Box::new(sink)))
312            }
313            (AudioFileCodec::Pcm(_), container) => Err(EncodeError::Adapter(format!(
314                "{container} does not hold PCM; a WAVE file does"
315            ))),
316            (AudioFileCodec::Encoded { codec, .. }, Container::Wav) => Err(EncodeError::Adapter(
317                format!("wav does not offer audio codec {}", codec.as_str()),
318            )),
319            (AudioFileCodec::Encoded { codec, bit_rate }, container) => {
320                let channels = u16::try_from(config.speakers.channels()).map_err(|_| {
321                    EncodeError::Adapter("the audio output has too many channels".into())
322                })?;
323                NativeAudioEncodeSink::create(
324                    path,
325                    container,
326                    AudioStreamConfig {
327                        codec,
328                        sample_rate: config.sample_rate,
329                        channels,
330                        bit_rate,
331                    },
332                )
333                .map(|sink| Self::Encoded(Box::new(sink)))
334            }
335        }
336    }
337
338    /// The `FFmpeg` name of the encoder; `None` for PCM, which has none.
339    #[must_use]
340    pub fn encoder_name(&self) -> Option<&str> {
341        match self {
342            Self::Wav(_) => None,
343            Self::Encoded(sink) => Some(sink.encoder_name()),
344        }
345    }
346
347    /// Project-rate samples per channel taken so far.
348    #[must_use]
349    pub fn frames_written(&self) -> u64 {
350        match self {
351            Self::Wav(sink) => sink.frames_written(),
352            Self::Encoded(sink) => sink.frames_written(),
353        }
354    }
355
356    /// Completes and closes the file, which stays a partial file until [`Self::publish`], so
357    /// several outputs of one export can all be whole before any is moved into place.
358    ///
359    /// # Errors
360    /// When the encoder, the muxer or the file system refuses.
361    pub fn seal(&mut self) -> Result<(), EncodeError> {
362        match self {
363            Self::Wav(sink) => sink.seal(),
364            Self::Encoded(sink) => sink.seal(),
365        }
366    }
367
368    /// Moves the sealed file into place.
369    ///
370    /// # Errors
371    /// As [`PartialOutput::finish`].
372    pub fn publish(&mut self, cancel: &CancelToken) -> Result<PublishReport, EncodeError> {
373        match self {
374            Self::Wav(sink) => sink.publish(cancel),
375            Self::Encoded(sink) => sink.publish(cancel),
376        }
377    }
378}
379
380impl AudioBlockSink for NativeAudioFileSink {
381    fn write_audio(&mut self, block: &AudioBlock, cancel: &CancelToken) -> Result<(), EncodeError> {
382        match self {
383            Self::Wav(sink) => sink.write_audio(block, cancel),
384            Self::Encoded(sink) => sink.write_audio(block, cancel),
385        }
386    }
387
388    fn finish_audio(&mut self, cancel: &CancelToken) -> Result<(), EncodeError> {
389        match self {
390            Self::Wav(sink) => sink.finish_audio(cancel),
391            Self::Encoded(sink) => sink.finish_audio(cancel),
392        }
393    }
394
395    fn abort_audio(&mut self) -> Result<(), EncodeError> {
396        match self {
397            Self::Wav(sink) => sink.abort_audio(),
398            Self::Encoded(sink) => sink.abort_audio(),
399        }
400    }
401}