Skip to main content

alpha2_native/
encode.rs

1//! Muxed A/V and WAV encode sinks.
2
3use crate::video_backend::VideoReceiveError;
4use std::collections::VecDeque;
5use std::fs;
6use std::io::{BufWriter, Seek, SeekFrom, Write};
7use std::sync::mpsc::{self, Receiver, SyncSender};
8use std::sync::{Arc, Mutex};
9use std::thread::{self, JoinHandle};
10use std::time::{Duration, Instant};
11
12use crate::audio_input::{AudioStreamConfig, EncoderAudioInput, open_audio_encoder};
13use crate::capabilities::{
14    AvEncodeConfig, NativeVideoEncoderSelection, VideoEncoderOpenRequest, open_video_encoder,
15};
16use crate::convert::{
17    codec_thread_budget, configure_rgba_to_yuv, encode_adapter_error, encode_adapter_error_at,
18    tick_base,
19};
20use crate::partial::{OutputTarget, PartialOutput, PublishReport, SeekNeed};
21use alpha2_ffmpeg_bridge::OutputFile;
22use alpha2_ffmpeg_bridge::Yuv420pFrameBuffer;
23use alpha2_media::{
24    AudioBlock, AudioBlockSink, CancelToken, DecodedVideoFrame, EncodeError, EncodeEvent,
25    EncodeSink, MAX_AUDIO_CHANNELS, PixelFormat, SpeakerLayout,
26};
27use alpha2_time::MediaTime;
28use rsmpeg::avcodec::{AVCodecContext, AVPacket};
29use rsmpeg::avutil::{AVRational, av_rescale_q};
30use rsmpeg::error::RsmpegError;
31use rsmpeg::ffi;
32
33/// Where one encode sink's wall time went, split into codec, packet drain and mux write so a
34/// change in one is visible.
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
36pub struct EncodeStageTimings {
37    /// Waiting before `avcodec_send_frame` for the GPU to finish a surface the encoder cannot wait
38    /// for itself. Zero on paths whose encoder waits on the GPU or takes CPU frames.
39    pub video_input_ready_wait: Duration,
40    /// `avcodec_send_frame` for video: the codec itself.
41    pub video_send_frame: Duration,
42    /// `avcodec_receive_packet` for video.
43    pub video_receive_packet: Duration,
44    /// `av_interleaved_write_frame` for video packets.
45    pub video_mux_write: Duration,
46    /// `avcodec_send_frame` for audio.
47    pub audio_send_frame: Duration,
48    /// `avcodec_receive_packet` for audio.
49    pub audio_receive_packet: Duration,
50    /// `av_interleaved_write_frame` for audio packets.
51    pub audio_mux_write: Duration,
52}
53
54impl EncodeStageTimings {
55    /// What elapsed between `self` and a later snapshot.
56    #[must_use]
57    pub fn since(self, earlier: Self) -> Self {
58        Self {
59            video_input_ready_wait: self
60                .video_input_ready_wait
61                .saturating_sub(earlier.video_input_ready_wait),
62            video_send_frame: self
63                .video_send_frame
64                .saturating_sub(earlier.video_send_frame),
65            video_receive_packet: self
66                .video_receive_packet
67                .saturating_sub(earlier.video_receive_packet),
68            video_mux_write: self.video_mux_write.saturating_sub(earlier.video_mux_write),
69            audio_send_frame: self
70                .audio_send_frame
71                .saturating_sub(earlier.audio_send_frame),
72            audio_receive_packet: self
73                .audio_receive_packet
74                .saturating_sub(earlier.audio_receive_packet),
75            audio_mux_write: self.audio_mux_write.saturating_sub(earlier.audio_mux_write),
76        }
77    }
78}
79
80pub(crate) use alpha2_host_core::encode_watch::beat_encode_call;
81
82/// Runs `body`, an encoder or muxer call, adding its time to `total` and beating the watch.
83pub(crate) fn timed<T>(total: &mut Duration, body: impl FnOnce() -> T) -> T {
84    beat_encode_call();
85    let started = Instant::now();
86    let value = body();
87    *total = total.saturating_add(started.elapsed());
88    value
89}
90
91/// Transactional IEEE-f32 WAV encoder used by native offline audio export.
92pub struct NativeWavEncodeSink {
93    pub(crate) file: Option<BufWriter<fs::File>>,
94    /// The partial file `file` writes. Declared after `file`, which closes first.
95    pub(crate) partial: PartialOutput,
96    /// How the finished file was published.
97    pub(crate) published: Option<PublishReport>,
98    pub(crate) sample_rate: u32,
99    pub(crate) channels: u16,
100    /// The speakers every block feeds.
101    pub(crate) speakers: SpeakerLayout,
102    /// The `WAVE_FORMAT_EXTENSIBLE` channel mask for a non-default layout; `None` writes a plain
103    /// IEEE-float header, which readers take as the default.
104    pub(crate) channel_mask: Option<u32>,
105    /// The block plane for each interleaved channel, in the mask's bit order as WAVE requires.
106    pub(crate) plane_order: Vec<usize>,
107    pub(crate) frames_written: u64,
108    pub(crate) complete: bool,
109    /// One block's samples, interleaved, reused across blocks.
110    pub(crate) interleaved: Vec<u8>,
111}
112
113/// Bytes the WAV sink gathers before each write (about five seconds of 48 kHz stereo).
114const WAV_WRITE_BUFFER: usize = 1 << 20;
115
116/// Audio/video sink that encodes and interleaves through the linked `FFmpeg` libraries.
117///
118/// Video frames and audio blocks must arrive in nondecreasing start-time order; ready
119/// packets are muxed incrementally.
120pub struct NativeAvEncodeSink {
121    pub(crate) output: Option<OutputFile>,
122    /// The partial file `output` writes. Declared after `output`, which closes first.
123    pub(crate) partial: PartialOutput,
124    /// How the finished file was published.
125    pub(crate) published: Option<PublishReport>,
126    pub(crate) video_encoder: crate::video_backend::TaggedVideoEncoder,
127    pub(crate) video_stream_index: i32,
128    pub(crate) video_encoder_time_base: AVRational,
129    /// One frame in `video_encoder_time_base`.
130    pub(crate) video_frame_units: i64,
131    pub(crate) video_stream_time_base: AVRational,
132    pub(crate) video_scaler: alpha2_ffmpeg_bridge::PackedScaler,
133    /// Turns decoded YUV of any layout into the encoder's 4:2:0.
134    pub(crate) yuv_input: crate::convert::Yuv420pConverter,
135    pub(crate) width: i32,
136    pub(crate) height: i32,
137    pub(crate) last_video_pts: Option<i64>,
138    /// Audio encoding runs on its own thread so video encoding cannot serialize it.
139    pub(crate) audio: AudioEncodeThread,
140    /// The project's audio, as the audio encoder takes it.
141    pub(crate) audio_input: EncoderAudioInput,
142    pub(crate) video_packets: VecDeque<QueuedPacket>,
143    pub(crate) last_input_ticks: Option<i64>,
144    pub(crate) complete: bool,
145    pub(crate) video_selection: NativeVideoEncoderSelection,
146    pub(crate) stages: EncodeStageTimings,
147}
148
149pub(crate) enum AudioCommand {
150    /// One frame of samples and the input tick reached. Every frame is the encoder's frame size
151    /// except possibly the last.
152    Block(Vec<Vec<f32>>, i64),
153    /// No more input: flush and stop, the input having reached the tick.
154    Finish(i64),
155}
156
157/// What the audio encode thread has produced, and how far it has got.
158///
159/// The muxer stays on the video worker; only finished packets and a watermark cross threads.
160#[derive(Default)]
161pub(crate) struct AudioQueueState {
162    /// Packets in production order, which for one stream is DTS order.
163    pub(crate) packets: VecDeque<QueuedPacket>,
164    /// Input ticks the thread has consumed and produced every packet for.
165    ///
166    /// The muxer writes no video packet past this, which keeps the interleave identical to a
167    /// single-threaded sink regardless of audio thread timing.
168    pub(crate) consumed_ticks: i64,
169    /// Set once the thread has flushed its encoder and will produce no more.
170    pub(crate) finished: bool,
171    /// The thread's first failure, surfaced by the muxer.
172    pub(crate) failure: Option<String>,
173    /// The thread's share of the sink's stage totals.
174    pub(crate) stages: EncodeStageTimings,
175}
176
177/// Handle to the audio encode thread.
178pub(crate) struct AudioEncodeThread {
179    commands: Option<SyncSender<AudioCommand>>,
180    join: Option<JoinHandle<()>>,
181    state: Arc<Mutex<AudioQueueState>>,
182}
183
184impl AudioEncodeThread {
185    pub(crate) fn lock(&self) -> std::sync::MutexGuard<'_, AudioQueueState> {
186        self.state
187            .lock()
188            .unwrap_or_else(std::sync::PoisonError::into_inner)
189    }
190
191    /// Hands one command over, reporting the thread's failure if it has stopped.
192    pub(crate) fn send(&self, command: AudioCommand) -> Result<(), EncodeError> {
193        let sent = match self.commands.as_ref() {
194            Some(sender) => sender.send(command).is_ok(),
195            None => return Err(EncodeError::Adapter("audio encoder is closed".into())),
196        };
197        if sent {
198            return Ok(());
199        }
200        let failure = self.lock().failure.clone();
201        Err(EncodeError::Adapter(failure.unwrap_or_else(|| {
202            "audio encoder stopped before accepting a block".into()
203        })))
204    }
205
206    /// Stops the thread, leaving whatever it produced in the queue.
207    pub(crate) fn shutdown(&mut self) {
208        drop(self.commands.take());
209        if let Some(join) = self.join.take() {
210            let _ = join.join();
211        }
212    }
213}
214
215impl Drop for AudioEncodeThread {
216    fn drop(&mut self) {
217        self.shutdown();
218    }
219}
220
221/// A finished packet waiting for the muxer, ordered by its DTS in ticks.
222pub(crate) struct QueuedPacket {
223    pub(crate) sort_ticks: i64,
224    pub(crate) packet: AVPacket,
225}
226
227impl NativeAvEncodeSink {
228    /// Creates linked-library video, audio, and container encoders without
229    /// touching the destination.
230    ///
231    /// # Errors
232    /// Returns an encoder error for invalid configuration, paths, or stale component outputs.
233    pub fn create(
234        path: impl Into<OutputTarget>,
235        config: AvEncodeConfig,
236    ) -> Result<Self, EncodeError> {
237        Self::create_selected(path, config, None, &|_| codec_thread_budget())
238    }
239
240    /// Creates the requested concrete video encoder by its `FFmpeg` short name.
241    ///
242    /// # Errors
243    /// Returns an encoder error when the name is unavailable, implements a different codec, or the
244    /// remaining configuration is invalid.
245    pub fn create_with_video_encoder(
246        path: impl Into<OutputTarget>,
247        config: AvEncodeConfig,
248        encoder_name: &str,
249    ) -> Result<Self, EncodeError> {
250        Self::create_selected(path, config, Some(encoder_name), &|_| codec_thread_budget())
251    }
252
253    /// Creates an encoder whose software thread count the caller decides.
254    ///
255    /// `software_threads` is asked at most once, only when a CPU candidate opens, so a hardware
256    /// candidate that falls through to software still gets a software share of the CPU.
257    ///
258    /// `encoder_name` pins one encoder; `None` tries the codec's candidates in preference order.
259    ///
260    /// # Errors
261    /// Returns an encoder error when no candidate opens, or for invalid configuration,
262    /// paths, codecs, or muxers.
263    pub fn create_with_video_encoder_threads(
264        path: impl Into<OutputTarget>,
265        config: AvEncodeConfig,
266        encoder_name: Option<&str>,
267        software_threads: &dyn Fn(Option<usize>) -> i64,
268    ) -> Result<Self, EncodeError> {
269        Self::create_selected(path, config, encoder_name, software_threads)
270    }
271
272    #[allow(clippy::too_many_lines)]
273    pub(crate) fn create_selected(
274        path: impl Into<OutputTarget>,
275        config: AvEncodeConfig,
276        encoder_name: Option<&str>,
277        software_threads: &dyn Fn(Option<usize>) -> i64,
278    ) -> Result<Self, EncodeError> {
279        crate::video_encode::check_video_config(&config.video)?;
280        if !config
281            .video
282            .container
283            .offers_audio(config.audio_codec.model())
284        {
285            return Err(EncodeError::Adapter(format!(
286                "{} does not offer audio codec {}",
287                config.video.container,
288                config.audio_codec.as_str()
289            )));
290        }
291        if config.audio_sample_rate == 0
292            || config.audio_channels == 0
293            || config.audio_channels > 8
294            || config.audio_bit_rate == 0
295        {
296            return Err(EncodeError::Adapter(format!(
297                "the audio output ({} channels at {} Hz, {} bit/s) is refused: 1 to 8 channels, a positive rate and bitrate",
298                config.audio_channels, config.audio_sample_rate, config.audio_bit_rate
299            )));
300        }
301        let target = path.into();
302        let partial = PartialOutput::claim(&target, SeekNeed::Required)?;
303        let mut output = crate::partial::open_muxer(&partial, config.video.container)?;
304        let global_header =
305            output.oformat().flags & i32::try_from(ffi::AVFMT_GLOBALHEADER).unwrap_or(0) != 0;
306
307        let width = i32::try_from(config.video.width)
308            .map_err(|_| EncodeError::Adapter("width is out of range".into()))?;
309        let height = i32::try_from(config.video.height)
310            .map_err(|_| EncodeError::Adapter("height is out of range".into()))?;
311        let (video_encoder, video_selection) = open_video_encoder(&VideoEncoderOpenRequest {
312            config: &config.video,
313            requested_name: encoder_name,
314            threads: crate::capabilities::SoftwareEncoderThreads::new(software_threads),
315            global_header,
316            width,
317            height,
318        })?;
319        // The frame length, or the finest unit an encoder that cannot hold it takes.
320        let video_encoder_time_base = video_encoder.time_base();
321
322        let audio = open_audio_encoder(
323            AudioStreamConfig {
324                codec: config.audio_codec,
325                sample_rate: config.audio_sample_rate,
326                channels: config.audio_channels,
327                bit_rate: config.audio_bit_rate,
328            },
329            global_header,
330        )?;
331        let audio_encoder_time_base = audio.encoder_time_base;
332
333        let video_stream_index;
334        {
335            let mut stream = output.new_stream();
336            stream.set_time_base(video_encoder_time_base);
337            stream.set_codecpar(video_encoder.codec_parameters());
338            crate::video_encode::describe_output_stream(
339                &mut stream,
340                video_encoder.codec_id(),
341                config.video.display,
342                config.video.container,
343            )?;
344            video_stream_index = stream.index;
345        }
346        let audio_stream_index;
347        {
348            let mut stream = output.new_stream();
349            stream.set_time_base(audio_encoder_time_base);
350            stream.set_codecpar(audio.encoder.extract_codecpar());
351            audio_stream_index = stream.index;
352        }
353        output
354            .write_header(&mut crate::convert::muxer_header_options(
355                config.video.container,
356            ))
357            .map_err(encode_adapter_error)?;
358        let video_stream_time_base =
359            output.streams()[usize::try_from(video_stream_index).unwrap_or(0)].time_base;
360        let audio_stream_time_base =
361            output.streams()[usize::try_from(audio_stream_index).unwrap_or(0)].time_base;
362        let mut video_scaler = alpha2_ffmpeg_bridge::PackedScaler::new(
363            width,
364            height,
365            ffi::AV_PIX_FMT_RGBA,
366            ffi::AV_PIX_FMT_YUV420P,
367        )
368        .map_err(|_| EncodeError::Adapter("cannot create RGBA to YUV scaler".into()))?;
369        configure_rgba_to_yuv(&mut video_scaler, config.video.color)
370            .map_err(encode_adapter_error)?;
371        let audio_input = audio.input;
372        let audio = spawn_audio_encoder(AudioEncoderConfig {
373            encoder: audio.encoder,
374            stream_index: audio_stream_index,
375            encoder_time_base: audio_encoder_time_base,
376            stream_time_base: audio_stream_time_base,
377            sample_rate: audio.encoder_rate,
378            sample_format: audio.sample_format,
379        })?;
380        Ok(Self {
381            output: Some(output),
382            partial,
383            published: None,
384            video_encoder,
385            video_stream_index,
386            video_encoder_time_base,
387            video_frame_units: crate::mux::frame_units(
388                config.video.frame_rate,
389                video_encoder_time_base,
390            ),
391            video_stream_time_base,
392            video_scaler,
393            yuv_input: crate::convert::Yuv420pConverter::new(config.video.color),
394            width,
395            height,
396            last_video_pts: None,
397            audio,
398            audio_input,
399            video_packets: VecDeque::new(),
400            last_input_ticks: None,
401            complete: false,
402            video_selection,
403            stages: EncodeStageTimings::default(),
404        })
405    }
406
407    /// Audio packets the thread has produced and the muxer has not written.
408    #[cfg(test)]
409    pub(crate) fn queued_audio_packets(&self) -> usize {
410        self.audio.lock().packets.len()
411    }
412
413    /// Where this sink's time has gone so far, both threads together.
414    #[must_use]
415    pub fn stage_timings(&self) -> EncodeStageTimings {
416        let audio = self.audio.lock().stages;
417        EncodeStageTimings {
418            audio_send_frame: audio.audio_send_frame,
419            audio_receive_packet: audio.audio_receive_packet,
420            ..self.stages
421        }
422    }
423
424    /// The video encoder this sink opened, and the candidates it passed over.
425    #[must_use]
426    pub fn video_selection(&self) -> &NativeVideoEncoderSelection {
427        &self.video_selection
428    }
429
430    /// How the finished file was published; `None` until it is.
431    #[must_use]
432    pub fn publish_report(&self) -> Option<PublishReport> {
433        self.published
434    }
435
436    pub(crate) fn cleanup(&mut self) -> Result<(), EncodeError> {
437        // Stop the audio thread first so nothing is queued against a closed output.
438        self.audio.shutdown();
439        drop(self.output.take());
440        self.partial.discard()
441    }
442
443    /// Queues one finished video packet for the muxer.
444    fn queue_video_packet(&mut self, mut packet: AVPacket) {
445        packet.set_stream_index(self.video_stream_index);
446        crate::mux::fill_frame_duration(&mut packet, self.video_frame_units);
447        packet.rescale_ts(self.video_encoder_time_base, self.video_stream_time_base);
448        let timestamp = if packet.dts == ffi::AV_NOPTS_VALUE {
449            packet.pts
450        } else {
451            packet.dts
452        };
453        self.video_packets.push_back(QueuedPacket {
454            sort_ticks: av_rescale_q(timestamp, self.video_stream_time_base, tick_base()),
455            packet,
456        });
457    }
458
459    /// Takes the next packet the muxer may write, or `None` to wait.
460    ///
461    /// Deterministic interleaving: earlier DTS wins and video wins ties; video is held
462    /// until audio has consumed all input through its timestamp. The coordinator's channel
463    /// bounds how far video leads.
464    fn pop_next_packet(&mut self, flushing: bool) -> Result<Option<QueuedPacket>, EncodeError> {
465        let mut state = self.audio.lock();
466        if let Some(error) = state.failure.clone() {
467            return Err(EncodeError::Adapter(error));
468        }
469        let take_audio = match (self.video_packets.front(), state.packets.front()) {
470            (Some(video), Some(audio)) => audio.sort_ticks < video.sort_ticks,
471            (None, Some(_)) => true,
472            (_, None) => false,
473        };
474        if take_audio {
475            return Ok(state.packets.pop_front());
476        }
477        let Some(video) = self.video_packets.front() else {
478            return Ok(None);
479        };
480        if !flushing && !state.finished && state.consumed_ticks < video.sort_ticks {
481            return Ok(None);
482        }
483        drop(state);
484        Ok(self.video_packets.pop_front())
485    }
486
487    pub(crate) fn write_ready_packets(&mut self, flushing: bool) -> Result<(), EncodeError> {
488        while let Some(mut queued) = self.pop_next_packet(flushing)? {
489            // The muxer is shared, so charge the write to the packet's stream.
490            let video = queued.packet.stream_index == self.video_stream_index;
491            let total = if video {
492                &mut self.stages.video_mux_write
493            } else {
494                &mut self.stages.audio_mux_write
495            };
496            let output = self
497                .output
498                .as_mut()
499                .ok_or_else(|| EncodeError::Adapter("muxer is already closed".into()))?;
500            let bytes = u64::try_from(queued.packet.size).unwrap_or(0);
501            timed(total, || output.interleaved_write_frame(&mut queued.packet))
502                .map_err(|error| encode_adapter_error_at("packet write failed", error))?;
503            self.partial.wrote(bytes)?;
504        }
505        Ok(())
506    }
507
508    pub(crate) fn drain_video_packets(&mut self, flushing: bool) -> Result<(), EncodeError> {
509        loop {
510            let received = timed(&mut self.stages.video_receive_packet, || {
511                self.video_encoder.receive_packet()
512            });
513            match received {
514                Ok(packet) => self.queue_video_packet(packet),
515                Err(VideoReceiveError::Codec(RsmpegError::EncoderDrainError)) if !flushing => {
516                    return Ok(());
517                }
518                Err(VideoReceiveError::Codec(
519                    RsmpegError::EncoderFlushedError | RsmpegError::EncoderDrainError,
520                )) if flushing => {
521                    return Ok(());
522                }
523                Err(VideoReceiveError::Codec(error)) => {
524                    return Err(encode_adapter_error_at(
525                        "video encoder packet drain failed",
526                        error,
527                    ));
528                }
529                Err(VideoReceiveError::Filter(error)) => return Err(error),
530            }
531        }
532    }
533
534    /// Encodes a frame the caller already packed, without copying it (see
535    /// [`crate::NativeVideoEncodeSink::write_prepared_video`]).
536    ///
537    /// # Errors
538    /// Returns an error for a frame sized differently from this encoder, a non-monotonic
539    /// timestamp, or a codec failure.
540    pub fn write_prepared_video(
541        &mut self,
542        frame: &mut Yuv420pFrameBuffer,
543        pts: MediaTime,
544    ) -> Result<(), EncodeError> {
545        let (width, height) = frame.size();
546        if width != usize::try_from(self.width).unwrap_or(0)
547            || height != usize::try_from(self.height).unwrap_or(0)
548        {
549            return Err(EncodeError::Adapter(
550                "encoder input dimensions do not match its configuration".into(),
551            ));
552        }
553        if crate::convert::pixel_format(self.video_selection.pixels).ok()
554            != Some(frame.frame().format)
555        {
556            return Err(EncodeError::Adapter(
557                "encoder input pixel format does not match its configuration".into(),
558            ));
559        }
560        let pts = av_rescale_q(pts.ticks(), tick_base(), self.video_encoder_time_base);
561        if self.last_video_pts.is_some_and(|previous| pts <= previous) {
562            return Err(EncodeError::InvalidTimestamp);
563        }
564        frame.set_presentation(pts, self.video_encoder_time_base);
565        timed(&mut self.stages.video_send_frame, || {
566            self.video_encoder.send_frame(Some(frame.frame()))
567        })
568        .map_err(|error| {
569            encode_adapter_error_at("video encoder rejected a YUV420P frame", error)
570        })?;
571        self.last_video_pts = Some(pts);
572        self.drain_video_packets(false)
573            .and_then(|()| self.write_ready_packets(false))
574            .map_err(|error| self.partial.explain(error))
575    }
576
577    pub(crate) fn write_video(&mut self, frame: &DecodedVideoFrame) -> Result<(), EncodeError> {
578        // Decoded and RGBA frames are converted to YUV420P; other outputs take
579        // caller-packed frames ([`Self::write_prepared_video`]).
580        if !self.video_selection.pixels.is_yuv420p() {
581            return Err(EncodeError::Adapter(format!(
582                "this encoder takes packed {} frames",
583                self.video_selection.pixels.ffmpeg_name()
584            )));
585        }
586        if frame.visible_rect.width != u32::try_from(self.width).unwrap_or(0)
587            || frame.visible_rect.height != u32::try_from(self.height).unwrap_or(0)
588        {
589            return Err(EncodeError::Adapter(
590                "encoder input dimensions do not match its configuration".into(),
591            ));
592        }
593        let pts = av_rescale_q(frame.pts.ticks(), tick_base(), self.video_encoder_time_base);
594        if self.last_video_pts.is_some_and(|previous| pts <= previous) {
595            return Err(EncodeError::InvalidTimestamp);
596        }
597        if let Some(mut yuv) = self.yuv_input.convert(frame, self.width, self.height)? {
598            yuv.set_pts(pts);
599            yuv.set_time_base(self.video_encoder_time_base);
600            timed(&mut self.stages.video_send_frame, || {
601                self.video_encoder.send_frame(Some(&yuv))
602            })
603            .map_err(|error| {
604                encode_adapter_error_at("video encoder rejected a YUV420P frame", error)
605            })?;
606            self.last_video_pts = Some(pts);
607            self.drain_video_packets(false)?;
608            return self.write_ready_packets(false);
609        }
610        if frame.pixel_format != PixelFormat::Rgba8 || frame.planes.len() != 1 {
611            return Err(EncodeError::Adapter(
612                "encoder expects YUV planes or one RGBA8 plane".into(),
613            ));
614        }
615        let plane = &frame.planes[0];
616        let expected = usize::try_from(self.width)
617            .ok()
618            .and_then(|width| {
619                usize::try_from(self.height)
620                    .ok()
621                    .and_then(|height| width.checked_mul(height))
622            })
623            .and_then(|pixels| pixels.checked_mul(4))
624            .ok_or_else(|| EncodeError::Adapter("frame dimensions overflow".into()))?;
625        if plane.bytes.len() != expected
626            || plane.stride != u32::try_from(self.width).unwrap_or(0) * 4
627        {
628            return Err(EncodeError::Adapter(
629                "RGBA plane is not tightly packed".into(),
630            ));
631        }
632        // Without alpha in the output, keep premultiplied RGB: frames arrive opaque
633        // over the project background, and dividing alpha out would show
634        // translucent layers at full strength.
635        let rgba = alpha2_ffmpeg_bridge::rgba_frame(&plane.bytes, self.width, self.height)
636            .map_err(encode_adapter_error)?;
637        let mut yuv = self
638            .video_scaler
639            .convert_to_frame(&rgba)
640            .map_err(encode_adapter_error)?;
641        yuv.set_pts(pts);
642        yuv.set_time_base(self.video_encoder_time_base);
643        timed(&mut self.stages.video_send_frame, || {
644            self.video_encoder.send_frame(Some(&yuv))
645        })
646        .map_err(|error| {
647            encode_adapter_error_at("video encoder rejected a converted YUV420P frame", error)
648        })?;
649        self.last_video_pts = Some(pts);
650        self.drain_video_packets(false)?;
651        self.write_ready_packets(false)
652    }
653
654    /// Buffers one audio block and hands every whole encoder frame to the thread.
655    pub(crate) fn write_audio(&mut self, block: &AudioBlock) -> Result<(), EncodeError> {
656        let frames = self.audio_input.push(block)?;
657        let covered = self.audio_input.received_ticks();
658        for frame in frames {
659            self.audio.send(AudioCommand::Block(frame, covered))?;
660        }
661        // Drain here too: an audio-only stretch has no video packet to trigger it.
662        self.write_ready_packets(false)
663    }
664}
665
666pub(crate) struct AudioEncoderConfig {
667    pub(crate) encoder: AVCodecContext,
668    pub(crate) stream_index: i32,
669    pub(crate) encoder_time_base: AVRational,
670    pub(crate) stream_time_base: AVRational,
671    /// The rate the encoder runs at.
672    pub(crate) sample_rate: u32,
673    /// The sample format its frames carry.
674    pub(crate) sample_format: ffi::AVSampleFormat,
675}
676
677/// Starts the audio encoder on its own thread.
678///
679/// The channel is two deep; a deeper queue would only add backlog the muxer holds anyway.
680///
681/// # Errors
682/// When the OS refuses the thread (thread limit, or no memory for its stack).
683pub(crate) fn spawn_audio_encoder(
684    config: AudioEncoderConfig,
685) -> Result<AudioEncodeThread, EncodeError> {
686    let (commands, receiver) = mpsc::sync_channel(2);
687    let state = Arc::new(Mutex::new(AudioQueueState::default()));
688    let worker_state = Arc::clone(&state);
689    let run = move || run_audio_encoder(config, &receiver, &worker_state);
690    let builder = thread::Builder::new().name("alpha2-audio-encode".to_owned());
691    #[cfg(test)]
692    let spawned = if REFUSE_AUDIO_ENCODE_THREAD.with(std::cell::Cell::take) {
693        drop(run);
694        Err(std::io::Error::from(std::io::ErrorKind::WouldBlock))
695    } else {
696        builder.spawn(run)
697    };
698    #[cfg(not(test))]
699    let spawned = builder.spawn(run);
700    let join = spawned.map_err(|error| {
701        encode_adapter_error_at("failed to start the audio encode thread", error)
702    })?;
703    Ok(AudioEncodeThread {
704        commands: Some(commands),
705        join: Some(join),
706        state,
707    })
708}
709
710#[cfg(test)]
711thread_local! {
712    /// Makes the next audio encode thread on this thread fail to start, as a thread limit does.
713    pub(crate) static REFUSE_AUDIO_ENCODE_THREAD: std::cell::Cell<bool> =
714        const { std::cell::Cell::new(false) };
715}
716
717/// Encodes blocks into packets until the channel closes or a `Finish` lands.
718fn run_audio_encoder(
719    mut config: AudioEncoderConfig,
720    commands: &Receiver<AudioCommand>,
721    state: &Arc<Mutex<AudioQueueState>>,
722) {
723    let mut encoded_samples = 0_u64;
724    loop {
725        let Ok(command) = commands.recv() else {
726            // The sink dropped the sender without finishing (abort or cancel).
727            return;
728        };
729        let (channels, covered, last) = match command {
730            AudioCommand::Block(channels, covered) => (Some(channels), covered, false),
731            AudioCommand::Finish(covered) => (None, covered, true),
732        };
733        let mut stages = EncodeStageTimings::default();
734        let outcome = encode_audio_block(
735            &mut config,
736            channels.as_deref(),
737            &mut encoded_samples,
738            &mut stages,
739        );
740        let mut guard = state
741            .lock()
742            .unwrap_or_else(std::sync::PoisonError::into_inner);
743        guard.stages.audio_send_frame = guard
744            .stages
745            .audio_send_frame
746            .saturating_add(stages.audio_send_frame);
747        guard.stages.audio_receive_packet = guard
748            .stages
749            .audio_receive_packet
750            .saturating_add(stages.audio_receive_packet);
751        match outcome {
752            Ok(packets) => guard.packets.extend(packets),
753            Err(error) => {
754                if guard.failure.is_none() {
755                    guard.failure = Some(error.to_string());
756                }
757                guard.finished = true;
758                return;
759            }
760        }
761        guard.consumed_ticks = guard.consumed_ticks.max(covered);
762        if last {
763            guard.finished = true;
764            return;
765        }
766    }
767}
768
769/// Encodes one audio frame, or with `None` flushes the encoder's delayed tail, and
770/// drains the resulting packets.
771fn encode_audio_block(
772    config: &mut AudioEncoderConfig,
773    channels: Option<&[Vec<f32>]>,
774    encoded_samples: &mut u64,
775    stages: &mut EncodeStageTimings,
776) -> Result<Vec<QueuedPacket>, EncodeError> {
777    let last = channels.is_none();
778    if let Some(channels) = channels {
779        let pts = i64::try_from(*encoded_samples).map_err(|_| EncodeError::InvalidTimestamp)?;
780        let frame = alpha2_ffmpeg_bridge::audio_frame(
781            channels,
782            config.sample_format,
783            i32::try_from(config.sample_rate).unwrap_or(i32::MAX),
784            pts,
785        )
786        .map_err(encode_adapter_error)?;
787        timed(&mut stages.audio_send_frame, || {
788            config.encoder.send_frame(Some(&frame))
789        })
790        .map_err(|error| encode_adapter_error_at("audio encoder rejected a frame", error))?;
791        let samples = channels.first().map_or(0, Vec::len);
792        *encoded_samples =
793            encoded_samples.saturating_add(u64::try_from(samples).unwrap_or(u64::MAX));
794    } else {
795        timed(&mut stages.audio_send_frame, || {
796            config.encoder.send_frame(None)
797        })
798        .map_err(encode_adapter_error)?;
799    }
800    let mut packets = Vec::new();
801    loop {
802        let received = timed(&mut stages.audio_receive_packet, || {
803            config.encoder.receive_packet()
804        });
805        match received {
806            Ok(mut packet) => {
807                packet.set_stream_index(config.stream_index);
808                packet.rescale_ts(config.encoder_time_base, config.stream_time_base);
809                let timestamp = if packet.dts == ffi::AV_NOPTS_VALUE {
810                    packet.pts
811                } else {
812                    packet.dts
813                };
814                packets.push(QueuedPacket {
815                    sort_ticks: av_rescale_q(timestamp, config.stream_time_base, tick_base()),
816                    packet,
817                });
818            }
819            Err(RsmpegError::EncoderDrainError) if !last => return Ok(packets),
820            Err(RsmpegError::EncoderFlushedError | RsmpegError::EncoderDrainError) if last => {
821                return Ok(packets);
822            }
823            Err(error) => {
824                return Err(encode_adapter_error_at(
825                    "audio encoder packet drain failed",
826                    error,
827                ));
828            }
829        }
830    }
831}
832
833impl EncodeSink for NativeAvEncodeSink {
834    fn write(&mut self, event: EncodeEvent, cancel: &CancelToken) -> Result<(), EncodeError> {
835        if cancel.is_cancelled() {
836            self.cleanup()?;
837            return Err(EncodeError::Cancelled);
838        }
839        let ticks = match &event {
840            EncodeEvent::Video(frame) => frame.pts.ticks(),
841            EncodeEvent::Audio(block) => block.start_time().ticks(),
842        };
843        if self
844            .last_input_ticks
845            .is_some_and(|previous| ticks < previous)
846        {
847            return Err(EncodeError::InvalidTimestamp);
848        }
849        match event {
850            EncodeEvent::Video(frame) => self.write_video(&frame),
851            EncodeEvent::Audio(block) => self.write_audio(&block),
852        }
853        .map_err(|error| self.partial.explain(error))?;
854        self.last_input_ticks = Some(ticks);
855        Ok(())
856    }
857    fn finish(&mut self, cancel: &CancelToken) -> Result<(), EncodeError> {
858        if cancel.is_cancelled() {
859            self.cleanup()?;
860            return Err(EncodeError::Cancelled);
861        }
862        self.close_output()
863            .map_err(|error| self.partial.explain(error))?;
864        self.published = Some(self.partial.finish(cancel)?);
865        self.complete = true;
866        Ok(())
867    }
868    fn abort(&mut self) -> Result<(), EncodeError> {
869        self.cleanup()
870    }
871}
872
873impl NativeAvEncodeSink {
874    /// Flushes both encoders, writes the trailer and closes the file,
875    /// before [`EncodeSink::finish`] publishes.
876    fn close_output(&mut self) -> Result<(), EncodeError> {
877        // Let the thread flush and wait, so every audio packet exists before the final interleave.
878        let covered = self.audio_input.received_ticks();
879        for frame in self.audio_input.finish() {
880            self.audio.send(AudioCommand::Block(frame, covered))?;
881        }
882        self.audio.send(AudioCommand::Finish(covered))?;
883        self.audio.shutdown();
884        if let Some(error) = self.audio.lock().failure.clone() {
885            return Err(EncodeError::Adapter(error));
886        }
887        timed(&mut self.stages.video_send_frame, || {
888            self.video_encoder.send_frame(None)
889        })
890        .map_err(encode_adapter_error)?;
891        self.drain_video_packets(true)?;
892        self.write_ready_packets(true)?;
893        beat_encode_call();
894        self.output
895            .as_mut()
896            .ok_or_else(|| EncodeError::Adapter("muxer is already closed".into()))?
897            .write_trailer()
898            .map_err(encode_adapter_error)?;
899        // A write error reported only at close fails the export here, before the rename.
900        if let Some(output) = self.output.take() {
901            beat_encode_call();
902            output
903                .close()
904                .map_err(|error| encode_adapter_error_at("closing the output", error))?;
905        }
906        Ok(())
907    }
908}
909
910impl Drop for NativeAvEncodeSink {
911    fn drop(&mut self) {
912        if !self.complete {
913            let _ = self.cleanup();
914        }
915    }
916}
917
918impl NativeWavEncodeSink {
919    /// Creates a non-overwriting sibling-partial WAV output of `channels` in the default layout.
920    ///
921    /// # Errors
922    /// Returns an error for invalid PCM format, existing paths, or filesystem failures.
923    pub fn create(
924        path: impl Into<OutputTarget>,
925        sample_rate: u32,
926        channels: u16,
927    ) -> Result<Self, EncodeError> {
928        let speakers = SpeakerLayout::default_for(usize::from(channels))
929            .ok_or_else(|| EncodeError::Adapter("invalid WAV format".into()))?;
930        Self::create_with_speakers(path, sample_rate, speakers)
931    }
932
933    /// Creates a WAV output whose blocks feed `speakers`.
934    ///
935    /// The default layout for the count gets a plain header; any other is `WAVE_FORMAT_EXTENSIBLE`
936    /// with its channel mask and planes in the mask's bit order.
937    ///
938    /// # Errors
939    /// Returns an error for invalid PCM format, a layout a WAVE channel mask cannot express
940    /// (unnamed, repeated, or beyond the 18 positions), existing paths, or filesystem failures.
941    pub fn create_with_speakers(
942        path: impl Into<OutputTarget>,
943        sample_rate: u32,
944        speakers: SpeakerLayout,
945    ) -> Result<Self, EncodeError> {
946        let channels = u16::try_from(speakers.channels())
947            .ok()
948            .filter(|_| sample_rate != 0 && speakers.channels() <= MAX_AUDIO_CHANNELS)
949            .ok_or_else(|| EncodeError::Adapter("invalid WAV format".into()))?;
950        let (channel_mask, plane_order) = wav_channel_layout(&speakers)?;
951        let target = path.into();
952        let partial = PartialOutput::claim(&target, SeekNeed::Required)?;
953        let mut file = BufWriter::with_capacity(WAV_WRITE_BUFFER, partial.open_file()?);
954        file.write_all(&wav_header_with_mask(
955            sample_rate,
956            channels,
957            channel_mask,
958            0,
959        )?)
960        .map_err(encode_adapter_error)?;
961        Ok(Self {
962            file: Some(file),
963            partial,
964            published: None,
965            sample_rate,
966            channels,
967            speakers,
968            channel_mask,
969            plane_order,
970            frames_written: 0,
971            complete: false,
972            interleaved: Vec::new(),
973        })
974    }
975
976    pub(crate) fn write_block(&mut self, block: &AudioBlock) -> Result<(), EncodeError> {
977        if block.sample_rate != self.sample_rate
978            || block.channels.len() != usize::from(self.channels)
979            || block.channels.is_empty()
980        {
981            return Err(EncodeError::Adapter("audio block format changed".into()));
982        }
983        if block.speakers != self.speakers {
984            return Err(EncodeError::Adapter("audio block speakers changed".into()));
985        }
986        let frames = block.channels[0].len();
987        if block.channels.iter().any(|channel| channel.len() != frames) {
988            return Err(EncodeError::Adapter("audio channel lengths differ".into()));
989        }
990        if u64::try_from(block.start_sample).ok() != Some(self.frames_written) {
991            return Err(EncodeError::InvalidTimestamp);
992        }
993        // Refuse before writing rather than after writing 4 GiB that is then removed.
994        let frames_after = self
995            .frames_written
996            .saturating_add(u64::try_from(frames).unwrap_or(u64::MAX));
997        self.data_bytes(frames_after)?;
998        let file = self
999            .file
1000            .as_mut()
1001            .ok_or_else(|| EncodeError::Adapter("WAV sink is closed".into()))?;
1002        self.interleaved.clear();
1003        for frame in 0..frames {
1004            for plane in &self.plane_order {
1005                self.interleaved
1006                    .extend_from_slice(&block.channels[*plane][frame].to_le_bytes());
1007            }
1008        }
1009        self.partial
1010            .wrote(u64::try_from(self.interleaved.len()).unwrap_or(u64::MAX))?;
1011        file.write_all(&self.interleaved)
1012            .map_err(encode_adapter_error)?;
1013        self.frames_written = self
1014            .frames_written
1015            .saturating_add(u64::try_from(frames).unwrap_or(u64::MAX));
1016        Ok(())
1017    }
1018
1019    /// The `data` chunk size after `frames` frames, while the RIFF size fits 32 bits.
1020    fn data_bytes(&self, frames: u64) -> Result<u32, EncodeError> {
1021        let overhead = if self.channel_mask.is_some() {
1022            WAV_EXTENSIBLE_OVERHEAD
1023        } else {
1024            WAV_PLAIN_OVERHEAD
1025        };
1026        #[cfg(test)]
1027        let limit = RIFF_LIMIT.with(std::cell::Cell::get);
1028        #[cfg(not(test))]
1029        let limit = u64::from(u32::MAX);
1030        frames
1031            .checked_mul(u64::from(self.channels))
1032            .and_then(|samples| samples.checked_mul(4))
1033            .filter(|bytes| bytes.saturating_add(u64::from(overhead)) <= limit)
1034            .and_then(|bytes| u32::try_from(bytes).ok())
1035            .ok_or_else(|| {
1036                EncodeError::Adapter(format!(
1037                    "{frames} frames of {} channels are more than the 4 GiB a WAV file holds",
1038                    self.channels
1039                ))
1040            })
1041    }
1042
1043    /// How the finished file was published; `None` until it is.
1044    #[must_use]
1045    pub fn publish_report(&self) -> Option<PublishReport> {
1046        self.published
1047    }
1048
1049    pub(crate) fn commit(&mut self, cancel: &CancelToken) -> Result<(), EncodeError> {
1050        let data_bytes = self.data_bytes(self.frames_written)?;
1051        let header = wav_header_with_mask(
1052            self.sample_rate,
1053            self.channels,
1054            self.channel_mask,
1055            data_bytes,
1056        )?;
1057        let mut file = self
1058            .file
1059            .take()
1060            .ok_or_else(|| EncodeError::Adapter("WAV sink is closed".into()))?;
1061        file.seek(SeekFrom::Start(0))
1062            .and_then(|_| file.write_all(&header))
1063            .and_then(|()| file.flush())
1064            .map_err(|error| self.partial.explain(encode_adapter_error(error)))?;
1065        drop(file);
1066        self.published = Some(self.partial.finish(cancel)?);
1067        self.complete = true;
1068        Ok(())
1069    }
1070}
1071
1072impl AudioBlockSink for NativeWavEncodeSink {
1073    fn write_audio(&mut self, block: &AudioBlock, cancel: &CancelToken) -> Result<(), EncodeError> {
1074        if cancel.is_cancelled() {
1075            self.abort_audio()?;
1076            return Err(EncodeError::Cancelled);
1077        }
1078        self.write_block(block)
1079            .map_err(|error| self.partial.explain(error))
1080    }
1081    fn finish_audio(&mut self, cancel: &CancelToken) -> Result<(), EncodeError> {
1082        if cancel.is_cancelled() {
1083            self.abort_audio()?;
1084            return Err(EncodeError::Cancelled);
1085        }
1086        self.commit(cancel)
1087    }
1088    fn abort_audio(&mut self) -> Result<(), EncodeError> {
1089        // Close without writing out samples the file is about to lose.
1090        drop(self.file.take().map(BufWriter::into_parts));
1091        self.partial.discard()
1092    }
1093}
1094
1095impl EncodeSink for NativeWavEncodeSink {
1096    fn write(&mut self, event: EncodeEvent, cancel: &CancelToken) -> Result<(), EncodeError> {
1097        match event {
1098            EncodeEvent::Audio(block) => self.write_audio(&block, cancel),
1099            EncodeEvent::Video(_) => {
1100                Err(EncodeError::Adapter("WAV sink accepts audio only".into()))
1101            }
1102        }
1103    }
1104    fn finish(&mut self, cancel: &CancelToken) -> Result<(), EncodeError> {
1105        self.finish_audio(cancel)
1106    }
1107    fn abort(&mut self) -> Result<(), EncodeError> {
1108        self.abort_audio()
1109    }
1110}
1111
1112impl Drop for NativeWavEncodeSink {
1113    fn drop(&mut self) {
1114        if !self.complete {
1115            let _ = self.abort_audio();
1116        }
1117    }
1118}
1119
1120/// The channel mask for `speakers` (`None` for the default layout) and the plane order of
1121/// the interleaved channels.
1122fn wav_channel_layout(speakers: &SpeakerLayout) -> Result<(Option<u32>, Vec<usize>), EncodeError> {
1123    let identity = (0..speakers.channels()).collect::<Vec<_>>();
1124    if SpeakerLayout::default_for(speakers.channels()) == Some(*speakers) {
1125        return Ok((None, identity));
1126    }
1127    let mut mask = 0_u32;
1128    for speaker in speakers.speakers() {
1129        let bit = speaker.ffmpeg_channel();
1130        if bit >= 18 || mask & (1 << bit) != 0 {
1131            return Err(EncodeError::Adapter(format!(
1132                "a WAVE channel mask cannot say the speakers {}",
1133                speakers.describe()
1134            )));
1135        }
1136        mask |= 1 << bit;
1137    }
1138    let mut order = identity;
1139    order.sort_by_key(|plane| speakers.speakers()[*plane].ffmpeg_channel());
1140    Ok((Some(mask), order))
1141}
1142
1143/// RIFF chunk size beyond the `data` samples, plain header.
1144const WAV_PLAIN_OVERHEAD: u32 = 36;
1145/// The same with a `WAVE_FORMAT_EXTENSIBLE` header.
1146const WAV_EXTENSIBLE_OVERHEAD: u32 = 60;
1147
1148#[cfg(test)]
1149thread_local! {
1150    /// The RIFF size limit for WAV sinks on this thread; tests lower it from `u32::MAX`.
1151    pub(crate) static RIFF_LIMIT: std::cell::Cell<u64> =
1152        const { std::cell::Cell::new(u32::MAX as u64) };
1153}
1154
1155fn riff_size(data_bytes: u32, overhead: u32) -> Result<u32, EncodeError> {
1156    data_bytes
1157        .checked_add(overhead)
1158        .ok_or_else(|| EncodeError::Adapter("WAV exceeds the RIFF size limit".into()))
1159}
1160
1161/// A WAV header: plain IEEE-float, or `WAVE_FORMAT_EXTENSIBLE` with `channel_mask` and
1162/// the IEEE-float subformat.
1163///
1164/// # Errors
1165/// When the RIFF chunk's size does not fit its 32 bits.
1166pub(crate) fn wav_header_with_mask(
1167    sample_rate: u32,
1168    channels: u16,
1169    channel_mask: Option<u32>,
1170    data_bytes: u32,
1171) -> Result<Vec<u8>, EncodeError> {
1172    let Some(mask) = channel_mask else {
1173        return Ok(wav_header(sample_rate, channels, data_bytes)?.to_vec());
1174    };
1175    let plain = wav_header(sample_rate, channels, 0)?;
1176    let mut header = Vec::with_capacity(68);
1177    header.extend_from_slice(b"RIFF");
1178    header.extend_from_slice(&riff_size(data_bytes, WAV_EXTENSIBLE_OVERHEAD)?.to_le_bytes());
1179    header.extend_from_slice(b"WAVEfmt ");
1180    header.extend_from_slice(&40_u32.to_le_bytes());
1181    header.extend_from_slice(&0xfffe_u16.to_le_bytes());
1182    // Channels, rate, byte rate, block align and bits per sample, as the plain header has them.
1183    header.extend_from_slice(&plain[22..36]);
1184    header.extend_from_slice(&22_u16.to_le_bytes());
1185    header.extend_from_slice(&32_u16.to_le_bytes());
1186    header.extend_from_slice(&mask.to_le_bytes());
1187    // KSDATAFORMAT_SUBTYPE_IEEE_FLOAT.
1188    header.extend_from_slice(&[
1189        0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b,
1190        0x71,
1191    ]);
1192    header.extend_from_slice(b"data");
1193    header.extend_from_slice(&data_bytes.to_le_bytes());
1194    Ok(header)
1195}
1196
1197/// A plain IEEE-float WAV header.
1198///
1199/// # Errors
1200/// When the RIFF chunk's size does not fit its 32 bits.
1201pub(crate) fn wav_header(
1202    sample_rate: u32,
1203    channels: u16,
1204    data_bytes: u32,
1205) -> Result<[u8; 44], EncodeError> {
1206    let mut header = [0_u8; 44];
1207    header[0..4].copy_from_slice(b"RIFF");
1208    header[4..8].copy_from_slice(&riff_size(data_bytes, WAV_PLAIN_OVERHEAD)?.to_le_bytes());
1209    header[8..12].copy_from_slice(b"WAVE");
1210    header[12..16].copy_from_slice(b"fmt ");
1211    header[16..20].copy_from_slice(&16_u32.to_le_bytes());
1212    header[20..22].copy_from_slice(&3_u16.to_le_bytes());
1213    header[22..24].copy_from_slice(&channels.to_le_bytes());
1214    header[24..28].copy_from_slice(&sample_rate.to_le_bytes());
1215    let byte_rate = sample_rate
1216        .saturating_mul(u32::from(channels))
1217        .saturating_mul(4);
1218    header[28..32].copy_from_slice(&byte_rate.to_le_bytes());
1219    header[32..34].copy_from_slice(&channels.saturating_mul(4).to_le_bytes());
1220    header[34..36].copy_from_slice(&32_u16.to_le_bytes());
1221    header[36..40].copy_from_slice(b"data");
1222    header[40..44].copy_from_slice(&data_bytes.to_le_bytes());
1223    Ok(header)
1224}