Skip to main content

alpha2_native/
encode.rs

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