1use 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#[derive(Copy, Clone, Debug, Eq, PartialEq)]
21pub enum AudioFileCodec {
22 Pcm(PcmSampleFormat),
24 Encoded {
26 codec: NativeAudioCodec,
28 bit_rate: u32,
30 },
31}
32
33#[derive(Copy, Clone, Debug, Eq, PartialEq)]
35pub struct AudioFileConfig {
36 pub container: Container,
38 pub codec: AudioFileCodec,
40 pub sample_rate: u32,
42 pub speakers: SpeakerLayout,
44}
45
46pub 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
61const M4A_BRAND: &std::ffi::CStr = c"M4A ";
63
64impl NativeAudioEncodeSink {
65 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 #[must_use]
149 pub fn encoder_name(&self) -> &str {
150 &self.encoder_name
151 }
152
153 #[must_use]
155 pub const fn frames_written(&self) -> u64 {
156 self.frames_written
157 }
158
159 #[must_use]
161 pub const fn stage_timings(&self) -> EncodeStageTimings {
162 self.stages
163 }
164
165 #[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 pub fn seal(&mut self) -> Result<(), EncodeError> {
231 self.close_output()
232 .map_err(|error| self.partial.explain(error))
233 }
234
235 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
284pub enum NativeAudioFileSink {
286 Wav(Box<NativeWavEncodeSink>),
288 Encoded(Box<NativeAudioEncodeSink>),
290}
291
292impl NativeAudioFileSink {
293 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 #[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 #[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 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 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}