Skip to main content

alpha2_native/
encode.rs

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