Skip to main content

euv_core/media/video/
impl.rs

1use super::*;
2
3/// Default SDR BT.709 color profile for `VideoColorInfo`.
4impl Default for VideoColorInfo {
5    /// Creates standard 8-bit limited-range BT.709 SDR color metadata.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default SDR color metadata.
10    fn default() -> Self {
11        Self::sdr_bt709()
12    }
13}
14
15/// Color-space constructors, CICP `nclx` decoding, and HDR helpers for `VideoColorInfo`.
16impl VideoColorInfo {
17    /// Constructs standard 8-bit limited-range ITU-R BT.709 SDR color metadata.
18    ///
19    /// # Returns
20    ///
21    /// - `Self` - SDR BT.709 color metadata.
22    #[must_use]
23    pub const fn sdr_bt709() -> Self {
24        Self {
25            primaries: ColorPrimaries::Bt709,
26            transfer: TransferCharacteristics::Bt709,
27            matrix: MatrixCoefficients::Bt709,
28            range: ColorRange::Limited,
29            bit_depth: 8,
30            max_cll_nits: 0,
31            max_fall_nits: 0,
32        }
33    }
34
35    /// Constructs 10-bit HDR10 BT.2020 PQ ST.2084 color metadata with mastering light levels.
36    ///
37    /// # Arguments
38    ///
39    /// - `u16` - Maximum Content Light Level (`MaxCLL`) in nits.
40    /// - `u16` - Maximum Frame-Average Light Level (`MaxFALL`) in nits.
41    ///
42    /// # Returns
43    ///
44    /// - `Self` - HDR10 BT.2020 PQ color metadata.
45    #[must_use]
46    pub const fn hdr10_bt2020_pq(max_cll_nits: u16, max_fall_nits: u16) -> Self {
47        Self {
48            primaries: ColorPrimaries::Bt2020,
49            transfer: TransferCharacteristics::PqSt2084,
50            matrix: MatrixCoefficients::Bt2020Ncl,
51            range: ColorRange::Limited,
52            bit_depth: 10,
53            max_cll_nits,
54            max_fall_nits,
55        }
56    }
57
58    /// Decodes ISO/IEC 23091-2 (`colr` `nclx`) CICP integer codes into `VideoColorInfo`.
59    ///
60    /// # Arguments
61    ///
62    /// - `u16` - CICP color primaries code.
63    /// - `u16` - CICP transfer characteristics code.
64    /// - `u16` - CICP matrix coefficients code.
65    /// - `bool` - `true` for full-range quantization, `false` for studio limited range.
66    ///
67    /// # Returns
68    ///
69    /// - `Self` - Decoded color space and HDR metadata.
70    #[must_use]
71    pub const fn from_nclx(
72        primaries_code: u16,
73        transfer_code: u16,
74        matrix_code: u16,
75        full_range: bool,
76    ) -> Self {
77        let primaries: ColorPrimaries = match primaries_code {
78            1 => ColorPrimaries::Bt709,
79            5 | 6 => ColorPrimaries::Bt601,
80            9 => ColorPrimaries::Bt2020,
81            12 => ColorPrimaries::DisplayP3,
82            other => ColorPrimaries::Unknown(other),
83        };
84        let transfer: TransferCharacteristics = match transfer_code {
85            1 => TransferCharacteristics::Bt709,
86            8 => TransferCharacteristics::Linear,
87            13 => TransferCharacteristics::Srgb,
88            16 => TransferCharacteristics::PqSt2084,
89            18 => TransferCharacteristics::Hlg,
90            other => TransferCharacteristics::Unknown(other),
91        };
92        let matrix: MatrixCoefficients = match matrix_code {
93            0 => MatrixCoefficients::Identity,
94            1 => MatrixCoefficients::Bt709,
95            5 | 6 => MatrixCoefficients::Bt601,
96            9 => MatrixCoefficients::Bt2020Ncl,
97            other => MatrixCoefficients::Unknown(other),
98        };
99        let range: ColorRange = if full_range {
100            ColorRange::Full
101        } else {
102            ColorRange::Limited
103        };
104        let bit_depth: u8 = if matches!(
105            transfer,
106            TransferCharacteristics::PqSt2084 | TransferCharacteristics::Hlg
107        ) {
108            10
109        } else {
110            8
111        };
112        Self {
113            primaries,
114            transfer,
115            matrix,
116            range,
117            bit_depth,
118            max_cll_nits: 0,
119            max_fall_nits: 0,
120        }
121    }
122
123    /// Encodes this color metadata back into ISO/IEC 23091-2 (`nclx`) CICP integer codes.
124    ///
125    /// # Arguments
126    ///
127    /// - `&Self` - Color metadata reference.
128    ///
129    /// # Returns
130    ///
131    /// - `(u16, u16, u16, bool)` - `(primaries, transfer, matrix, full_range)` tuple.
132    #[must_use]
133    pub const fn to_nclx(&self) -> (u16, u16, u16, bool) {
134        let Self {
135            primaries,
136            transfer,
137            matrix,
138            range,
139            ..
140        } = *self;
141        let p_code: u16 = match primaries {
142            ColorPrimaries::Bt709 => 1,
143            ColorPrimaries::Bt601 => 6,
144            ColorPrimaries::Bt2020 => 9,
145            ColorPrimaries::DisplayP3 => 12,
146            ColorPrimaries::Unknown(code) => code,
147        };
148        let t_code: u16 = match transfer {
149            TransferCharacteristics::Bt709 => 1,
150            TransferCharacteristics::Linear => 8,
151            TransferCharacteristics::Srgb => 13,
152            TransferCharacteristics::PqSt2084 => 16,
153            TransferCharacteristics::Hlg => 18,
154            TransferCharacteristics::Unknown(code) => code,
155        };
156        let m_code: u16 = match matrix {
157            MatrixCoefficients::Identity => 0,
158            MatrixCoefficients::Bt709 => 1,
159            MatrixCoefficients::Bt601 => 6,
160            MatrixCoefficients::Bt2020Ncl => 9,
161            MatrixCoefficients::Unknown(code) => code,
162        };
163        let full_range: bool = matches!(range, ColorRange::Full);
164        (p_code, t_code, m_code, full_range)
165    }
166
167    /// Returns `true` when the transfer function indicates HDR (`PQ ST.2084` or `HLG`).
168    ///
169    /// # Arguments
170    ///
171    /// - `&Self` - Color metadata reference.
172    ///
173    /// # Returns
174    ///
175    /// - `bool` - `true` for HDR streams.
176    #[must_use]
177    pub const fn is_hdr(&self) -> bool {
178        let Self { transfer, .. } = *self;
179        matches!(
180            transfer,
181            TransferCharacteristics::PqSt2084 | TransferCharacteristics::Hlg
182        )
183    }
184}
185
186/// Platform hardware video decoder capability probe helpers.
187impl HardwareDecoderProbe {
188    /// Returns the preferred native hardware decode backend kind for the active compilation target.
189    ///
190    /// # Returns
191    ///
192    /// - `HardwareDecoderKind` - Target OS hardware decoder backend kind.
193    #[must_use]
194    pub const fn preferred_for_host() -> HardwareDecoderKind {
195        #[cfg(any(target_os = "macos", target_os = "ios"))]
196        {
197            HardwareDecoderKind::VideoToolbox
198        }
199        #[cfg(target_os = "android")]
200        {
201            HardwareDecoderKind::MediaCodec
202        }
203        #[cfg(target_os = "windows")]
204        {
205            HardwareDecoderKind::Dxva
206        }
207        #[cfg(target_os = "linux")]
208        {
209            HardwareDecoderKind::Vaapi
210        }
211        #[cfg(target_arch = "wasm32")]
212        {
213            HardwareDecoderKind::WebCodecs
214        }
215        #[cfg(not(any(
216            target_os = "macos",
217            target_os = "ios",
218            target_os = "android",
219            target_os = "windows",
220            target_os = "linux",
221            target_arch = "wasm32"
222        )))]
223        {
224            HardwareDecoderKind::SoftwareFallback
225        }
226    }
227
228    /// Returns baseline hardware capabilities associated with a target decoder backend kind.
229    ///
230    /// # Arguments
231    ///
232    /// - `HardwareDecoderKind` - Backend kind to query.
233    ///
234    /// # Returns
235    ///
236    /// - `HardwareDecoderCapabilities` - Advertised capability profile.
237    #[must_use]
238    pub const fn capabilities_for(kind: HardwareDecoderKind) -> HardwareDecoderCapabilities {
239        match kind {
240            HardwareDecoderKind::VideoToolbox => HardwareDecoderCapabilities {
241                kind,
242                zero_copy_gpu_interop: true,
243                supports_h264: true,
244                supports_h265: true,
245                supports_vp9: true,
246                supports_av1: true,
247                supports_hdr10: true,
248                max_width: 7_680,
249                max_height: 4_320,
250            },
251            HardwareDecoderKind::MediaCodec => HardwareDecoderCapabilities {
252                kind,
253                zero_copy_gpu_interop: true,
254                supports_h264: true,
255                supports_h265: true,
256                supports_vp9: true,
257                supports_av1: true,
258                supports_hdr10: true,
259                max_width: 3_840,
260                max_height: 2_160,
261            },
262            HardwareDecoderKind::Dxva | HardwareDecoderKind::Vaapi => HardwareDecoderCapabilities {
263                kind,
264                zero_copy_gpu_interop: true,
265                supports_h264: true,
266                supports_h265: true,
267                supports_vp9: true,
268                supports_av1: true,
269                supports_hdr10: true,
270                max_width: 7_680,
271                max_height: 4_320,
272            },
273            HardwareDecoderKind::WebCodecs => HardwareDecoderCapabilities {
274                kind,
275                zero_copy_gpu_interop: true,
276                supports_h264: true,
277                supports_h265: false,
278                supports_vp9: true,
279                supports_av1: true,
280                supports_hdr10: false,
281                max_width: 3_840,
282                max_height: 2_160,
283            },
284            HardwareDecoderKind::SoftwareFallback => HardwareDecoderCapabilities {
285                kind,
286                zero_copy_gpu_interop: false,
287                supports_h264: false,
288                supports_h265: false,
289                supports_vp9: false,
290                supports_av1: false,
291                supports_hdr10: true,
292                max_width: 4_096,
293                max_height: 2_160,
294            },
295        }
296    }
297}
298
299/// Default bounded CPU frame pool constructor.
300impl Default for VideoFramePool {
301    /// Creates a bounded `VideoFramePool` using `VIDEO_DEFAULT_POOL_CAPACITY`.
302    ///
303    /// # Returns
304    ///
305    /// - `Self` - Initialized pool.
306    fn default() -> Self {
307        Self::with_capacity(VIDEO_DEFAULT_POOL_CAPACITY)
308    }
309}
310
311/// Bounded zero-allocation steady-state buffer acquisition and recycling for `VideoFramePool`.
312impl VideoFramePool {
313    /// Creates a bounded CPU video frame pool allowing at most `capacity` simultaneous buffers.
314    ///
315    /// # Arguments
316    ///
317    /// - `usize` - Maximum number of buffers (`>= 1`).
318    ///
319    /// # Returns
320    ///
321    /// - `Self` - Bounded `VideoFramePool`.
322    #[must_use]
323    pub fn with_capacity(capacity: usize) -> Self {
324        let cap: usize = capacity.max(1);
325        let state: VideoFramePoolState = VideoFramePoolState {
326            capacity: cap,
327            in_use: 0,
328            next_slot_id: 0,
329            free_buffers: Vec::with_capacity(cap),
330            allocations: 0,
331            reuse_hits: 0,
332            backpressure_rejects: 0,
333            recycled_count: 0,
334        };
335        #[cfg(not(target_arch = "wasm32"))]
336        {
337            Self {
338                inner: Arc::new(Mutex::new(state)),
339            }
340        }
341        #[cfg(target_arch = "wasm32")]
342        {
343            Self {
344                inner: Rc::new(RefCell::new(state)),
345            }
346        }
347    }
348
349    /// Acquires a reusable RGBA8 frame buffer sized for `width x height`, returning `None` when bounded capacity is exhausted.
350    ///
351    /// # Arguments
352    ///
353    /// - `&Self` - Pool reference.
354    /// - `u32` - Frame width in pixels.
355    /// - `u32` - Frame height in pixels.
356    ///
357    /// # Returns
358    ///
359    /// - `Option<PooledVideoFrame>` - Reusable frame buffer or `None` under bounded backpressure.
360    #[must_use]
361    pub fn acquire(&self, width: u32, height: u32) -> Option<PooledVideoFrame> {
362        let needed: usize = (width as usize)
363            .checked_mul(height as usize)?
364            .checked_mul(4)?;
365        let Self { inner } = self;
366        #[cfg(not(target_arch = "wasm32"))]
367        let mut guard: MutexGuard<'_, VideoFramePoolState> =
368            inner
369                .lock()
370                .unwrap_or_else(|err: PoisonError<MutexGuard<'_, VideoFramePoolState>>| {
371                    err.into_inner()
372                });
373        #[cfg(target_arch = "wasm32")]
374        let mut guard: RefMut<'_, VideoFramePoolState> = inner.borrow_mut();
375        Self::acquire_locked(&mut guard, width, height, needed)
376    }
377
378    /// Internal locked buffer acquisition routine shared across native and wasm32 targets.
379    ///
380    /// # Arguments
381    ///
382    /// - `&mut VideoFramePoolState` - Mutable pool state.
383    /// - `u32` - Frame width in pixels.
384    /// - `u32` - Frame height in pixels.
385    /// - `usize` - Required byte length (`width * height * 4`).
386    ///
387    /// # Returns
388    ///
389    /// - `Option<PooledVideoFrame>` - Pooled buffer or `None` when full.
390    fn acquire_locked(
391        state: &mut VideoFramePoolState,
392        width: u32,
393        height: u32,
394        needed: usize,
395    ) -> Option<PooledVideoFrame> {
396        if state.get_in_use() >= state.get_capacity() {
397            let next_rejects: u64 = state.get_backpressure_rejects().saturating_add(1);
398            state.set_backpressure_rejects(next_rejects);
399            return None;
400        }
401        if let Some(mut recycled) = state.get_mut_free_buffers().pop() {
402            let next_in_use: usize = state.get_in_use().saturating_add(1);
403            state.set_in_use(next_in_use);
404            let next_hits: u64 = state.get_reuse_hits().saturating_add(1);
405            state.set_reuse_hits(next_hits);
406            recycled.set_width(width);
407            recycled.set_height(height);
408            let pixels: &mut Vec<u8> = recycled.get_mut_pixels();
409            if pixels.len() != needed {
410                pixels.resize(needed, 0);
411            }
412            return Some(recycled);
413        }
414        let slot_id: usize = state.get_next_slot_id();
415        state.set_next_slot_id(slot_id.saturating_add(1));
416        let next_in_use: usize = state.get_in_use().saturating_add(1);
417        state.set_in_use(next_in_use);
418        let next_allocs: u64 = state.get_allocations().saturating_add(1);
419        state.set_allocations(next_allocs);
420        Some(PooledVideoFrame {
421            slot_id,
422            width,
423            height,
424            pixels: vec![0; needed],
425        })
426    }
427
428    /// Returns a checked-out CPU video frame buffer back into the bounded pool for zero-allocation reuse.
429    ///
430    /// # Arguments
431    ///
432    /// - `&Self` - Pool reference.
433    /// - `PooledVideoFrame` - Frame buffer to recycle.
434    pub fn recycle(&self, frame: PooledVideoFrame) {
435        let Self { inner } = self;
436        #[cfg(not(target_arch = "wasm32"))]
437        let mut guard: MutexGuard<'_, VideoFramePoolState> =
438            inner
439                .lock()
440                .unwrap_or_else(|err: PoisonError<MutexGuard<'_, VideoFramePoolState>>| {
441                    err.into_inner()
442                });
443        #[cfg(target_arch = "wasm32")]
444        let mut guard: RefMut<'_, VideoFramePoolState> = inner.borrow_mut();
445        let next_in_use: usize = guard.get_in_use().saturating_sub(1);
446        guard.set_in_use(next_in_use);
447        let next_recycled: u64 = guard.get_recycled_count().saturating_add(1);
448        guard.set_recycled_count(next_recycled);
449        let cap: usize = guard.get_capacity();
450        if guard.get_free_buffers().len() < cap {
451            guard.get_mut_free_buffers().push(frame);
452        }
453    }
454
455    /// Recycles the CPU pixel buffer inside a `DecodedVideoFrame` when backed by `VideoFrameBacking::CpuPooled`.
456    ///
457    /// # Arguments
458    ///
459    /// - `&Self` - Pool reference.
460    /// - `DecodedVideoFrame` - Frame whose backing should be reclaimed if CPU-pooled.
461    pub fn recycle_decoded_frame(&self, frame: DecodedVideoFrame) {
462        let DecodedVideoFrame { backing, .. } = frame;
463        if let VideoFrameBacking::CpuPooled(pooled) = backing {
464            self.recycle(pooled);
465        }
466    }
467
468    /// Returns a point-in-time telemetry snapshot of pool capacity, reuse hits, and allocations.
469    ///
470    /// # Arguments
471    ///
472    /// - `&Self` - Pool reference.
473    ///
474    /// # Returns
475    ///
476    /// - `VideoFramePoolStats` - Pool usage and allocation telemetry.
477    #[must_use]
478    pub fn stats(&self) -> VideoFramePoolStats {
479        let Self { inner } = self;
480        #[cfg(not(target_arch = "wasm32"))]
481        let guard: MutexGuard<'_, VideoFramePoolState> =
482            inner
483                .lock()
484                .unwrap_or_else(|err: PoisonError<MutexGuard<'_, VideoFramePoolState>>| {
485                    err.into_inner()
486                });
487        #[cfg(target_arch = "wasm32")]
488        let guard: Ref<'_, VideoFramePoolState> = inner.borrow();
489        VideoFramePoolStats::new(
490            guard.get_capacity(),
491            guard.get_in_use(),
492            guard.get_free_buffers().len(),
493            guard.get_allocations(),
494            guard.get_reuse_hits(),
495            guard.get_backpressure_rejects(),
496            guard.get_recycled_count(),
497        )
498    }
499}
500
501/// Pure-Rust ISOBMFF/MP4 box parser, random-access keyframe lookup, and packet extraction for `Mp4Demuxer`.
502impl Mp4Demuxer {
503    /// Parses an ISOBMFF/MP4 byte stream (`ftyp`, `moov`/`mvhd`/`trak`/`tkhd`/`mdia`/`mdhd`/`hdlr`/`minf`/`stbl`, `mdat`).
504    ///
505    /// # Arguments
506    ///
507    /// - `Vec<u8>` - Complete MP4 container bytes.
508    ///
509    /// # Returns
510    ///
511    /// - `Result<Self, String>` - Parsed demuxer with indexed video/audio sample tables or descriptive error.
512    pub fn parse(bytes: Vec<u8>) -> Result<Self, String> {
513        if bytes.is_empty() {
514            return Err(VIDEO_ERR_MP4_EMPTY.to_string());
515        }
516        let mut major_brand: String = VIDEO_DEFAULT_BRAND_STR.to_string();
517        let mut compatible_brands: Vec<String> = Vec::new();
518        let mut movie_timescale: u32 = 1_000;
519        let mut movie_duration_us: u64 = 0;
520        let mut video_track: Option<Mp4TrackInfo> = None;
521        let mut audio_track: Option<Mp4TrackInfo> = None;
522        let mut found_moov: bool = false;
523        let mut cursor: usize = 0;
524        while cursor < bytes.len() {
525            let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
526                Self::read_box_header(&bytes, cursor, bytes.len())?;
527            if box_type == MP4_BOX_FTYP {
528                Self::parse_ftyp(
529                    &bytes[payload_start..box_end],
530                    &mut major_brand,
531                    &mut compatible_brands,
532                );
533            } else if box_type == MP4_BOX_MOOV {
534                found_moov = true;
535                Self::parse_moov(
536                    &bytes,
537                    payload_start,
538                    box_end,
539                    &mut movie_timescale,
540                    &mut movie_duration_us,
541                    &mut video_track,
542                    &mut audio_track,
543                )?;
544            }
545            cursor = box_end;
546        }
547        if !found_moov {
548            return Err(VIDEO_ERR_MP4_NO_MOOV.to_string());
549        }
550        let resolved_video: Mp4TrackInfo =
551            video_track.ok_or_else(|| VIDEO_ERR_MP4_NO_VIDEO_TRACK.to_string())?;
552        for sample in resolved_video.get_samples().iter() {
553            let end_offset: u64 = sample
554                .get_byte_offset()
555                .saturating_add(sample.get_byte_size() as u64);
556            if end_offset > (bytes.len() as u64) {
557                return Err(VIDEO_ERR_MP4_SAMPLE_BOUNDS.to_string());
558            }
559        }
560        if movie_duration_us == 0 {
561            movie_duration_us = resolved_video.get_duration_us();
562        }
563        Ok(Self {
564            bytes,
565            major_brand,
566            compatible_brands,
567            movie_timescale,
568            movie_duration_us,
569            video_track: resolved_video,
570            audio_track,
571        })
572    }
573
574    /// Returns the optional parsed audio track descriptor.
575    ///
576    /// # Arguments
577    ///
578    /// - `&Self` - Demuxer reference.
579    ///
580    /// # Returns
581    ///
582    /// - `Option<&Mp4TrackInfo>` - Audio track reference when present.
583    #[must_use]
584    pub fn audio_track(&self) -> Option<&Mp4TrackInfo> {
585        let Self { audio_track, .. } = self;
586        audio_track.as_ref()
587    }
588
589    /// Returns the total number of indexed video samples in decode order.
590    ///
591    /// # Arguments
592    ///
593    /// - `&Self` - Demuxer reference.
594    ///
595    /// # Returns
596    ///
597    /// - `usize` - Number of video samples.
598    #[must_use]
599    pub fn video_sample_count(&self) -> usize {
600        self.get_video_track().get_samples().len()
601    }
602
603    /// Builds a `VideoDecoderConfig` describing the primary video track's codec, resolution, and color/HDR metadata.
604    ///
605    /// # Arguments
606    ///
607    /// - `&Self` - Demuxer reference.
608    ///
609    /// # Returns
610    ///
611    /// - `VideoDecoderConfig` - Decoder configuration descriptor.
612    #[must_use]
613    pub fn video_decoder_config(&self) -> VideoDecoderConfig {
614        let track: &Mp4TrackInfo = self.get_video_track();
615        VideoDecoderConfig::new(
616            track.get_video_codec(),
617            track.get_width(),
618            track.get_height(),
619            track.get_color_info(),
620        )
621    }
622
623    /// Reads an `EncodedVideoPacket` for `sample_index` tagged with `generation`.
624    ///
625    /// # Arguments
626    ///
627    /// - `&Self` - Demuxer reference.
628    /// - `usize` - Zero-based decode-order video sample index.
629    /// - `u64` - Active seek generation tag.
630    ///
631    /// # Returns
632    ///
633    /// - `Option<EncodedVideoPacket>` - Extracted packet or `None` if `sample_index` is out of range.
634    #[must_use]
635    pub fn read_video_packet(
636        &self,
637        sample_index: usize,
638        generation: u64,
639    ) -> Option<EncodedVideoPacket> {
640        let sample: &Mp4Sample = self.get_video_track().get_samples().get(sample_index)?;
641        let start: usize = usize::try_from(sample.get_byte_offset()).ok()?;
642        let len: usize = sample.get_byte_size() as usize;
643        let end: usize = start.checked_add(len)?;
644        let slice: &[u8] = self.get_bytes().get(start..end)?;
645        Some(EncodedVideoPacket {
646            sample_index,
647            generation,
648            dts_us: sample.get_dts_us(),
649            pts_us: sample.get_pts_us(),
650            duration_us: sample.get_duration_us(),
651            is_keyframe: sample.get_is_keyframe(),
652            data: slice.to_vec(),
653        })
654    }
655
656    /// Finds the decode-order index of the closest preceding keyframe whose `pts_us <= target_pts_us`.
657    ///
658    /// # Arguments
659    ///
660    /// - `&Self` - Demuxer reference.
661    /// - `i64` - Target presentation timestamp in microseconds.
662    ///
663    /// # Returns
664    ///
665    /// - `usize` - Decode-order keyframe index (`0` if target precedes all keyframes).
666    #[must_use]
667    pub fn seek_keyframe_index(&self, target_pts_us: i64) -> usize {
668        let samples: &[Mp4Sample] = self.get_video_track().get_samples().as_slice();
669        let mut best_keyframe: usize = 0;
670        let mut best_pts: i64 = i64::MIN;
671        for sample in samples.iter() {
672            if sample.get_is_keyframe()
673                && sample.get_pts_us() <= target_pts_us
674                && sample.get_pts_us() >= best_pts
675            {
676                best_pts = sample.get_pts_us();
677                best_keyframe = sample.get_index();
678            }
679        }
680        best_keyframe
681    }
682
683    /// Reads an ISOBMFF box header supporting 32-bit sizes, 64-bit extended sizes (`size == 1`), and to-EOF (`size == 0`).
684    ///
685    /// # Arguments
686    ///
687    /// - `&[u8]` - Container byte slice.
688    /// - `usize` - Starting byte offset.
689    /// - `usize` - Exclusive upper bound within container.
690    ///
691    /// # Returns
692    ///
693    /// - `Result<([u8; 4], usize, usize), String>` - `(box_type, payload_start, box_end)` tuple.
694    fn read_box_header(
695        bytes: &[u8],
696        start: usize,
697        limit: usize,
698    ) -> Result<([u8; 4], usize, usize), String> {
699        if start.saturating_add(8) > limit {
700            return Err(VIDEO_ERR_MP4_TRUNCATED_BOX.to_string());
701        }
702        let size32: u32 = u32::from_be_bytes([
703            bytes[start],
704            bytes[start + 1],
705            bytes[start + 2],
706            bytes[start + 3],
707        ]);
708        let box_type: [u8; 4] = [
709            bytes[start + 4],
710            bytes[start + 5],
711            bytes[start + 6],
712            bytes[start + 7],
713        ];
714        if size32 == 0 {
715            return Ok((box_type, start + 8, limit));
716        }
717        if size32 == 1 {
718            if start.saturating_add(16) > limit {
719                return Err(VIDEO_ERR_MP4_TRUNCATED_BOX.to_string());
720            }
721            let size64: u64 = u64::from_be_bytes([
722                bytes[start + 8],
723                bytes[start + 9],
724                bytes[start + 10],
725                bytes[start + 11],
726                bytes[start + 12],
727                bytes[start + 13],
728                bytes[start + 14],
729                bytes[start + 15],
730            ]);
731            let total: usize =
732                usize::try_from(size64).map_err(|_| VIDEO_ERR_MP4_TRUNCATED_BOX.to_string())?;
733            if total < 16 || start.saturating_add(total) > limit {
734                return Err(VIDEO_ERR_MP4_TRUNCATED_BOX.to_string());
735            }
736            return Ok((box_type, start + 16, start + total));
737        }
738        let total: usize = size32 as usize;
739        if total < 8 || start.saturating_add(total) > limit {
740            return Err(VIDEO_ERR_MP4_TRUNCATED_BOX.to_string());
741        }
742        Ok((box_type, start + 8, start + total))
743    }
744
745    /// Parses an `ftyp` payload into major brand and compatible brand strings.
746    ///
747    /// # Arguments
748    ///
749    /// - `&[u8]` - `ftyp` payload bytes.
750    /// - `&mut String` - Destination major brand string.
751    /// - `&mut Vec<String>` - Destination compatible brands list.
752    fn parse_ftyp(payload: &[u8], major_brand: &mut String, compatible_brands: &mut Vec<String>) {
753        if payload.len() >= 4 {
754            *major_brand = Self::fourcc_to_string(&payload[0..4]);
755        }
756        let mut offset: usize = 8;
757        while offset.saturating_add(4) <= payload.len() {
758            compatible_brands.push(Self::fourcc_to_string(&payload[offset..offset + 4]));
759            offset += 4;
760        }
761    }
762
763    /// Converts a 4-byte FourCC slice into an ASCII string.
764    ///
765    /// # Arguments
766    ///
767    /// - `&[u8]` - 4-byte FourCC slice.
768    ///
769    /// # Returns
770    ///
771    /// - `String` - UTF-8 FourCC label.
772    fn fourcc_to_string(slice: &[u8]) -> String {
773        from_utf8(slice)
774            .map(|s: &str| s.to_string())
775            .unwrap_or_else(|_| VIDEO_DEFAULT_BRAND_STR.to_string())
776    }
777
778    /// Parses a `moov` container box extracting `mvhd` and all child `trak` boxes.
779    ///
780    /// # Arguments
781    ///
782    /// - `&[u8]` - Full container bytes.
783    /// - `usize` - Payload start offset.
784    /// - `usize` - Payload exclusive end offset.
785    /// - `&mut u32` - Movie timescale output.
786    /// - `&mut u64` - Movie duration in microseconds output.
787    /// - `&mut Option<Mp4TrackInfo>` - Primary video track output.
788    /// - `&mut Option<Mp4TrackInfo>` - Primary audio track output.
789    ///
790    /// # Returns
791    ///
792    /// - `Result<(), String>` - `Ok(())` on success or parse error.
793    fn parse_moov(
794        bytes: &[u8],
795        start: usize,
796        end: usize,
797        movie_timescale: &mut u32,
798        movie_duration_us: &mut u64,
799        video_track: &mut Option<Mp4TrackInfo>,
800        audio_track: &mut Option<Mp4TrackInfo>,
801    ) -> Result<(), String> {
802        let mut cursor: usize = start;
803        while cursor < end {
804            let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
805                Self::read_box_header(bytes, cursor, end)?;
806            if box_type == MP4_BOX_MVHD {
807                Self::parse_mvhd(
808                    &bytes[payload_start..box_end],
809                    movie_timescale,
810                    movie_duration_us,
811                );
812            } else if box_type == MP4_BOX_TRAK
813                && let Some(track) = Self::parse_trak(bytes, payload_start, box_end)?
814            {
815                if track.get_is_video() && video_track.is_none() {
816                    *video_track = Some(track);
817                } else if !track.get_is_video() && audio_track.is_none() {
818                    *audio_track = Some(track);
819                }
820            }
821            cursor = box_end;
822        }
823        Ok(())
824    }
825
826    /// Parses a version 0 or version 1 `mvhd` box for movie timescale and duration.
827    ///
828    /// # Arguments
829    ///
830    /// - `&[u8]` - `mvhd` payload bytes.
831    /// - `&mut u32` - Destination movie timescale.
832    /// - `&mut u64` - Destination movie duration in microseconds.
833    fn parse_mvhd(payload: &[u8], timescale_out: &mut u32, duration_us_out: &mut u64) {
834        if payload.len() < 4 {
835            return;
836        }
837        let version: u8 = payload[0];
838        if version == 0 && payload.len() >= 20 {
839            let scale: u32 =
840                u32::from_be_bytes([payload[12], payload[13], payload[14], payload[15]]);
841            let dur: u32 = u32::from_be_bytes([payload[16], payload[17], payload[18], payload[19]]);
842            if scale > 0 {
843                *timescale_out = scale;
844                *duration_us_out = Self::ticks_to_us(dur as u64, scale);
845            }
846        } else if version == 1 && payload.len() >= 32 {
847            let scale: u32 =
848                u32::from_be_bytes([payload[20], payload[21], payload[22], payload[23]]);
849            let dur: u64 = u64::from_be_bytes([
850                payload[24],
851                payload[25],
852                payload[26],
853                payload[27],
854                payload[28],
855                payload[29],
856                payload[30],
857                payload[31],
858            ]);
859            if scale > 0 {
860                *timescale_out = scale;
861                *duration_us_out = Self::ticks_to_us(dur, scale);
862            }
863        }
864    }
865
866    /// Parses a `trak` container box (`tkhd` + `mdia`) into an `Mp4TrackInfo` when `vide` or `soun`.
867    ///
868    /// # Arguments
869    ///
870    /// - `&[u8]` - Full container bytes.
871    /// - `usize` - Payload start offset.
872    /// - `usize` - Payload exclusive end offset.
873    ///
874    /// # Returns
875    ///
876    /// - `Result<Option<Mp4TrackInfo>, String>` - Parsed track info or `None` for non-media tracks.
877    fn parse_trak(bytes: &[u8], start: usize, end: usize) -> Result<Option<Mp4TrackInfo>, String> {
878        let mut track: Mp4TrackInfo = Mp4TrackInfo::default();
879        let mut handler_tag: [u8; 4] = [0; 4];
880        let mut raw_stbl: Mp4SampleTableRaw = Mp4SampleTableRaw::default();
881        let mut cursor: usize = start;
882        while cursor < end {
883            let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
884                Self::read_box_header(bytes, cursor, end)?;
885            if box_type == MP4_BOX_TKHD {
886                Self::parse_tkhd(&bytes[payload_start..box_end], &mut track);
887            } else if box_type == MP4_BOX_MDIA {
888                Self::parse_mdia(
889                    bytes,
890                    payload_start,
891                    box_end,
892                    &mut track,
893                    &mut handler_tag,
894                    &mut raw_stbl,
895                )?;
896            }
897            cursor = box_end;
898        }
899        if handler_tag != MP4_HANDLER_VIDE && handler_tag != MP4_HANDLER_SOUN {
900            return Ok(None);
901        }
902        track.set_is_video(handler_tag == MP4_HANDLER_VIDE);
903        let timescale: u32 = track.get_timescale().max(1);
904        let samples: Vec<Mp4Sample> = Self::build_samples(&raw_stbl, timescale);
905        if track.get_duration_us() == 0 && !samples.is_empty() {
906            let mut max_end_us: u64 = 0;
907            for sample in samples.iter() {
908                let start_pos: u64 = sample.get_pts_us().max(0) as u64;
909                let end_pos: u64 = start_pos.saturating_add(sample.get_duration_us());
910                if end_pos > max_end_us {
911                    max_end_us = end_pos;
912                }
913            }
914            track.set_duration_us(max_end_us);
915        }
916        track.set_samples(samples);
917        Ok(Some(track))
918    }
919
920    /// Parses a `tkhd` box for `track_id` and 16.16 display width/height.
921    ///
922    /// # Arguments
923    ///
924    /// - `&[u8]` - `tkhd` payload bytes.
925    /// - `&mut Mp4TrackInfo` - Destination track metadata.
926    fn parse_tkhd(payload: &[u8], track: &mut Mp4TrackInfo) {
927        if payload.len() < 4 {
928            return;
929        }
930        let version: u8 = payload[0];
931        if version == 0 && payload.len() >= 84 {
932            let id: u32 = u32::from_be_bytes([payload[12], payload[13], payload[14], payload[15]]);
933            let width_fixed: u32 =
934                u32::from_be_bytes([payload[76], payload[77], payload[78], payload[79]]);
935            let height_fixed: u32 =
936                u32::from_be_bytes([payload[80], payload[81], payload[82], payload[83]]);
937            track.set_track_id(id);
938            if track.get_width() == 0 {
939                track.set_width(width_fixed >> 16);
940            }
941            if track.get_height() == 0 {
942                track.set_height(height_fixed >> 16);
943            }
944        } else if version == 1 && payload.len() >= 96 {
945            let id: u32 = u32::from_be_bytes([payload[20], payload[21], payload[22], payload[23]]);
946            let width_fixed: u32 =
947                u32::from_be_bytes([payload[88], payload[89], payload[90], payload[91]]);
948            let height_fixed: u32 =
949                u32::from_be_bytes([payload[92], payload[93], payload[94], payload[95]]);
950            track.set_track_id(id);
951            if track.get_width() == 0 {
952                track.set_width(width_fixed >> 16);
953            }
954            if track.get_height() == 0 {
955                track.set_height(height_fixed >> 16);
956            }
957        }
958    }
959
960    /// Parses an `mdia` container box (`mdhd`, `hdlr`, `minf`).
961    ///
962    /// # Arguments
963    ///
964    /// - `&[u8]` - Full container bytes.
965    /// - `usize` - Payload start offset.
966    /// - `usize` - Payload exclusive end offset.
967    /// - `&mut Mp4TrackInfo` - Destination track metadata.
968    /// - `&mut [u8; 4]` - Destination handler type tag (`vide` / `soun`).
969    /// - `&mut Mp4SampleTableRaw` - Destination sample table accumulator.
970    ///
971    /// # Returns
972    ///
973    /// - `Result<(), String>` - `Ok(())` on success or parse error.
974    fn parse_mdia(
975        bytes: &[u8],
976        start: usize,
977        end: usize,
978        track: &mut Mp4TrackInfo,
979        handler_tag: &mut [u8; 4],
980        raw_stbl: &mut Mp4SampleTableRaw,
981    ) -> Result<(), String> {
982        let mut cursor: usize = start;
983        while cursor < end {
984            let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
985                Self::read_box_header(bytes, cursor, end)?;
986            if box_type == MP4_BOX_MDHD {
987                Self::parse_mdhd(&bytes[payload_start..box_end], track);
988            } else if box_type == MP4_BOX_HDLR {
989                let payload: &[u8] = &bytes[payload_start..box_end];
990                if payload.len() >= 12 {
991                    *handler_tag = [payload[8], payload[9], payload[10], payload[11]];
992                }
993            } else if box_type == MP4_BOX_MINF {
994                Self::parse_minf(bytes, payload_start, box_end, track, raw_stbl)?;
995            }
996            cursor = box_end;
997        }
998        Ok(())
999    }
1000
1001    /// Parses an `mdhd` box for media timescale and track duration.
1002    ///
1003    /// # Arguments
1004    ///
1005    /// - `&[u8]` - `mdhd` payload bytes.
1006    /// - `&mut Mp4TrackInfo` - Destination track metadata.
1007    fn parse_mdhd(payload: &[u8], track: &mut Mp4TrackInfo) {
1008        if payload.len() < 4 {
1009            return;
1010        }
1011        let version: u8 = payload[0];
1012        if version == 0 && payload.len() >= 20 {
1013            let scale: u32 =
1014                u32::from_be_bytes([payload[12], payload[13], payload[14], payload[15]]);
1015            let dur: u32 = u32::from_be_bytes([payload[16], payload[17], payload[18], payload[19]]);
1016            if scale > 0 {
1017                track.set_timescale(scale);
1018                track.set_duration_us(Self::ticks_to_us(dur as u64, scale));
1019            }
1020        } else if version == 1 && payload.len() >= 32 {
1021            let scale: u32 =
1022                u32::from_be_bytes([payload[20], payload[21], payload[22], payload[23]]);
1023            let dur: u64 = u64::from_be_bytes([
1024                payload[24],
1025                payload[25],
1026                payload[26],
1027                payload[27],
1028                payload[28],
1029                payload[29],
1030                payload[30],
1031                payload[31],
1032            ]);
1033            if scale > 0 {
1034                track.set_timescale(scale);
1035                track.set_duration_us(Self::ticks_to_us(dur, scale));
1036            }
1037        }
1038    }
1039
1040    /// Parses a `minf` box to locate and decode its `stbl` sample table.
1041    ///
1042    /// # Arguments
1043    ///
1044    /// - `&[u8]` - Full container bytes.
1045    /// - `usize` - Payload start offset.
1046    /// - `usize` - Payload exclusive end offset.
1047    /// - `&mut Mp4TrackInfo` - Destination track metadata.
1048    /// - `&mut Mp4SampleTableRaw` - Destination sample table accumulator.
1049    ///
1050    /// # Returns
1051    ///
1052    /// - `Result<(), String>` - `Ok(())` on success or parse error.
1053    fn parse_minf(
1054        bytes: &[u8],
1055        start: usize,
1056        end: usize,
1057        track: &mut Mp4TrackInfo,
1058        raw_stbl: &mut Mp4SampleTableRaw,
1059    ) -> Result<(), String> {
1060        let mut cursor: usize = start;
1061        while cursor < end {
1062            let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
1063                Self::read_box_header(bytes, cursor, end)?;
1064            if box_type == MP4_BOX_STBL {
1065                Self::parse_stbl(bytes, payload_start, box_end, track, raw_stbl)?;
1066            }
1067            cursor = box_end;
1068        }
1069        Ok(())
1070    }
1071
1072    /// Parses an `stbl` box (`stsd`, `stts`, `ctts`, `stss`, `stsc`, `stsz`, `stco`, `co64`).
1073    ///
1074    /// # Arguments
1075    ///
1076    /// - `&[u8]` - Full container bytes.
1077    /// - `usize` - Payload start offset.
1078    /// - `usize` - Payload exclusive end offset.
1079    /// - `&mut Mp4TrackInfo` - Destination track metadata.
1080    /// - `&mut Mp4SampleTableRaw` - Destination sample table accumulator.
1081    ///
1082    /// # Returns
1083    ///
1084    /// - `Result<(), String>` - `Ok(())` on success or parse error.
1085    fn parse_stbl(
1086        bytes: &[u8],
1087        start: usize,
1088        end: usize,
1089        track: &mut Mp4TrackInfo,
1090        raw_stbl: &mut Mp4SampleTableRaw,
1091    ) -> Result<(), String> {
1092        let mut cursor: usize = start;
1093        while cursor < end {
1094            let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
1095                Self::read_box_header(bytes, cursor, end)?;
1096            let payload: &[u8] = &bytes[payload_start..box_end];
1097            if box_type == MP4_BOX_STSD {
1098                Self::parse_stsd(bytes, payload_start, box_end, track)?;
1099            } else if box_type == MP4_BOX_STTS {
1100                Self::parse_stts(payload, raw_stbl);
1101            } else if box_type == MP4_BOX_CTTS {
1102                Self::parse_ctts(payload, raw_stbl);
1103            } else if box_type == MP4_BOX_STSS {
1104                Self::parse_stss(payload, raw_stbl);
1105            } else if box_type == MP4_BOX_STSC {
1106                Self::parse_stsc(payload, raw_stbl);
1107            } else if box_type == MP4_BOX_STSZ {
1108                Self::parse_stsz(payload, raw_stbl);
1109            } else if box_type == MP4_BOX_STCO {
1110                Self::parse_stco(payload, raw_stbl);
1111            } else if box_type == MP4_BOX_CO64 {
1112                Self::parse_co64(payload, raw_stbl);
1113            }
1114            cursor = box_end;
1115        }
1116        Ok(())
1117    }
1118
1119    /// Parses an `stsd` sample description box including visual codec FourCC, coded dimensions, audio config, and nested `colr` `nclx` box.
1120    ///
1121    /// # Arguments
1122    ///
1123    /// - `&[u8]` - Full container bytes.
1124    /// - `usize` - Payload start offset.
1125    /// - `usize` - Payload exclusive end offset.
1126    /// - `&mut Mp4TrackInfo` - Destination track metadata.
1127    ///
1128    /// # Returns
1129    ///
1130    /// - `Result<(), String>` - `Ok(())` on success or parse error.
1131    fn parse_stsd(
1132        bytes: &[u8],
1133        start: usize,
1134        end: usize,
1135        track: &mut Mp4TrackInfo,
1136    ) -> Result<(), String> {
1137        if start.saturating_add(8) > end {
1138            return Ok(());
1139        }
1140        let entry_count: u32 = u32::from_be_bytes([
1141            bytes[start + 4],
1142            bytes[start + 5],
1143            bytes[start + 6],
1144            bytes[start + 7],
1145        ]);
1146        if entry_count == 0 {
1147            return Ok(());
1148        }
1149        let entry_start: usize = start + 8;
1150        let (codec_tag, entry_payload_start, entry_end): ([u8; 4], usize, usize) =
1151            Self::read_box_header(bytes, entry_start, end)?;
1152        track.set_codec_fourcc(Self::fourcc_to_string(&codec_tag));
1153        let entry_payload: &[u8] = &bytes[entry_payload_start..entry_end];
1154        if codec_tag == MP4_CODEC_AVC1 || codec_tag == MP4_CODEC_AVC3 {
1155            track.set_video_codec(VideoCodec::H264);
1156        } else if codec_tag == MP4_CODEC_HVC1 || codec_tag == MP4_CODEC_HEV1 {
1157            track.set_video_codec(VideoCodec::H265);
1158        } else if codec_tag == MP4_CODEC_VP09 {
1159            track.set_video_codec(VideoCodec::Vp9);
1160        } else if codec_tag == MP4_CODEC_AV01 {
1161            track.set_video_codec(VideoCodec::Av1);
1162        } else if codec_tag == MP4_CODEC_RAWV || codec_tag == MP4_CODEC_RGBA {
1163            track.set_video_codec(VideoCodec::RawFrames);
1164        } else if codec_tag == MP4_CODEC_MP4A {
1165            track.set_audio_codec(AudioCodec::Aac);
1166        } else if codec_tag == MP4_CODEC_OPUS {
1167            track.set_audio_codec(AudioCodec::Opus);
1168        }
1169        let is_audio_codec: bool = codec_tag == MP4_CODEC_MP4A || codec_tag == MP4_CODEC_OPUS;
1170        if is_audio_codec {
1171            if entry_payload.len() >= 28 {
1172                let channels: u16 = u16::from_be_bytes([entry_payload[16], entry_payload[17]]);
1173                let sr_fixed: u32 = u32::from_be_bytes([
1174                    entry_payload[24],
1175                    entry_payload[25],
1176                    entry_payload[26],
1177                    entry_payload[27],
1178                ]);
1179                track.set_channels(channels);
1180                track.set_sample_rate_hz(sr_fixed >> 16);
1181            }
1182            return Ok(());
1183        }
1184        if entry_payload.len() >= 28 {
1185            let coded_w: u16 = u16::from_be_bytes([entry_payload[24], entry_payload[25]]);
1186            let coded_h: u16 = u16::from_be_bytes([entry_payload[26], entry_payload[27]]);
1187            if coded_w > 0 {
1188                track.set_width(coded_w as u32);
1189            }
1190            if coded_h > 0 {
1191                track.set_height(coded_h as u32);
1192            }
1193        }
1194        let mut child_cursor: usize = entry_payload_start.saturating_add(78);
1195        while child_cursor.saturating_add(8) <= entry_end {
1196            let Ok((child_type, child_start, child_end)) =
1197                Self::read_box_header(bytes, child_cursor, entry_end)
1198            else {
1199                break;
1200            };
1201            if child_type == MP4_BOX_COLR {
1202                Self::parse_colr(&bytes[child_start..child_end], track);
1203            }
1204            child_cursor = child_end;
1205        }
1206        Ok(())
1207    }
1208
1209    /// Parses a nested `colr` box supporting `nclx` CICP primaries, transfer, matrix, and full-range flag.
1210    ///
1211    /// # Arguments
1212    ///
1213    /// - `&[u8]` - `colr` payload bytes.
1214    /// - `&mut Mp4TrackInfo` - Destination track metadata.
1215    fn parse_colr(payload: &[u8], track: &mut Mp4TrackInfo) {
1216        if payload.len() >= 11 && payload[0..4] == MP4_BOX_NCLX {
1217            let primaries: u16 = u16::from_be_bytes([payload[4], payload[5]]);
1218            let transfer: u16 = u16::from_be_bytes([payload[6], payload[7]]);
1219            let matrix: u16 = u16::from_be_bytes([payload[8], payload[9]]);
1220            let full_range: bool = (payload[10] & 0x80) != 0;
1221            track.set_color_info(VideoColorInfo::from_nclx(
1222                primaries, transfer, matrix, full_range,
1223            ));
1224        }
1225    }
1226
1227    /// Parses an `stts` decoding time-to-sample table.
1228    ///
1229    /// # Arguments
1230    ///
1231    /// - `&[u8]` - `stts` payload bytes.
1232    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1233    fn parse_stts(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1234        if payload.len() < 8 {
1235            return;
1236        }
1237        let count: usize =
1238            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1239        let max_entries: usize = (payload.len() - 8) / 8;
1240        let entries: usize = count.min(max_entries);
1241        for i in 0..entries {
1242            let off: usize = 8 + i * 8;
1243            let sample_count: u32 = u32::from_be_bytes([
1244                payload[off],
1245                payload[off + 1],
1246                payload[off + 2],
1247                payload[off + 3],
1248            ]);
1249            let sample_delta: u32 = u32::from_be_bytes([
1250                payload[off + 4],
1251                payload[off + 5],
1252                payload[off + 6],
1253                payload[off + 7],
1254            ]);
1255            raw_stbl.get_mut_stts().push((sample_count, sample_delta));
1256        }
1257    }
1258
1259    /// Parses a `ctts` composition time-to-sample table (version 0 unsigned and version 1 signed).
1260    ///
1261    /// # Arguments
1262    ///
1263    /// - `&[u8]` - `ctts` payload bytes.
1264    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1265    fn parse_ctts(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1266        if payload.len() < 8 {
1267            return;
1268        }
1269        let version: u8 = payload[0];
1270        let count: usize =
1271            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1272        let max_entries: usize = (payload.len() - 8) / 8;
1273        let entries: usize = count.min(max_entries);
1274        for i in 0..entries {
1275            let off: usize = 8 + i * 8;
1276            let sample_count: u32 = u32::from_be_bytes([
1277                payload[off],
1278                payload[off + 1],
1279                payload[off + 2],
1280                payload[off + 3],
1281            ]);
1282            let offset_ticks: i32 = if version == 1 {
1283                i32::from_be_bytes([
1284                    payload[off + 4],
1285                    payload[off + 5],
1286                    payload[off + 6],
1287                    payload[off + 7],
1288                ])
1289            } else {
1290                u32::from_be_bytes([
1291                    payload[off + 4],
1292                    payload[off + 5],
1293                    payload[off + 6],
1294                    payload[off + 7],
1295                ]) as i32
1296            };
1297            raw_stbl.get_mut_ctts().push((sample_count, offset_ticks));
1298        }
1299    }
1300
1301    /// Parses an `stss` sync keyframe sample index table.
1302    ///
1303    /// # Arguments
1304    ///
1305    /// - `&[u8]` - `stss` payload bytes.
1306    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1307    fn parse_stss(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1308        if payload.len() < 8 {
1309            return;
1310        }
1311        let count: usize =
1312            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1313        let max_entries: usize = (payload.len() - 8) / 4;
1314        let entries: usize = count.min(max_entries);
1315        for i in 0..entries {
1316            let off: usize = 8 + i * 4;
1317            let sample_num: u32 = u32::from_be_bytes([
1318                payload[off],
1319                payload[off + 1],
1320                payload[off + 2],
1321                payload[off + 3],
1322            ]);
1323            raw_stbl.get_mut_stss().push(sample_num);
1324        }
1325    }
1326
1327    /// Parses an `stsc` sample-to-chunk mapping table.
1328    ///
1329    /// # Arguments
1330    ///
1331    /// - `&[u8]` - `stsc` payload bytes.
1332    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1333    fn parse_stsc(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1334        if payload.len() < 8 {
1335            return;
1336        }
1337        let count: usize =
1338            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1339        let max_entries: usize = (payload.len() - 8) / 12;
1340        let entries: usize = count.min(max_entries);
1341        for i in 0..entries {
1342            let off: usize = 8 + i * 12;
1343            let first_chunk: u32 = u32::from_be_bytes([
1344                payload[off],
1345                payload[off + 1],
1346                payload[off + 2],
1347                payload[off + 3],
1348            ]);
1349            let samples_per_chunk: u32 = u32::from_be_bytes([
1350                payload[off + 4],
1351                payload[off + 5],
1352                payload[off + 6],
1353                payload[off + 7],
1354            ]);
1355            raw_stbl
1356                .get_mut_stsc()
1357                .push((first_chunk, samples_per_chunk));
1358        }
1359    }
1360
1361    /// Parses an `stsz` sample size table.
1362    ///
1363    /// # Arguments
1364    ///
1365    /// - `&[u8]` - `stsz` payload bytes.
1366    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1367    fn parse_stsz(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1368        if payload.len() < 12 {
1369            return;
1370        }
1371        let default_size: u32 =
1372            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]);
1373        let sample_count: u32 =
1374            u32::from_be_bytes([payload[8], payload[9], payload[10], payload[11]]);
1375        raw_stbl.set_default_sample_size(default_size);
1376        raw_stbl.set_sample_count(sample_count);
1377        if default_size == 0 {
1378            let max_entries: usize = (payload.len() - 12) / 4;
1379            let entries: usize = (sample_count as usize).min(max_entries);
1380            for i in 0..entries {
1381                let off: usize = 12 + i * 4;
1382                let size: u32 = u32::from_be_bytes([
1383                    payload[off],
1384                    payload[off + 1],
1385                    payload[off + 2],
1386                    payload[off + 3],
1387                ]);
1388                raw_stbl.get_mut_sample_sizes().push(size);
1389            }
1390        }
1391    }
1392
1393    /// Parses a 32-bit `stco` chunk offset table.
1394    ///
1395    /// # Arguments
1396    ///
1397    /// - `&[u8]` - `stco` payload bytes.
1398    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1399    fn parse_stco(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1400        if payload.len() < 8 {
1401            return;
1402        }
1403        let count: usize =
1404            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1405        let max_entries: usize = (payload.len() - 8) / 4;
1406        let entries: usize = count.min(max_entries);
1407        for i in 0..entries {
1408            let off: usize = 8 + i * 4;
1409            let chunk_off: u32 = u32::from_be_bytes([
1410                payload[off],
1411                payload[off + 1],
1412                payload[off + 2],
1413                payload[off + 3],
1414            ]);
1415            raw_stbl.get_mut_chunk_offsets().push(chunk_off as u64);
1416        }
1417    }
1418
1419    /// Parses a 64-bit `co64` chunk offset table.
1420    ///
1421    /// # Arguments
1422    ///
1423    /// - `&[u8]` - `co64` payload bytes.
1424    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1425    fn parse_co64(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1426        if payload.len() < 8 {
1427            return;
1428        }
1429        let count: usize =
1430            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1431        let max_entries: usize = (payload.len() - 8) / 8;
1432        let entries: usize = count.min(max_entries);
1433        for i in 0..entries {
1434            let off: usize = 8 + i * 8;
1435            let chunk_off: u64 = u64::from_be_bytes([
1436                payload[off],
1437                payload[off + 1],
1438                payload[off + 2],
1439                payload[off + 3],
1440                payload[off + 4],
1441                payload[off + 5],
1442                payload[off + 6],
1443                payload[off + 7],
1444            ]);
1445            raw_stbl.get_mut_chunk_offsets().push(chunk_off);
1446        }
1447    }
1448
1449    /// Expands parsed `stts`/`ctts`/`stss`/`stsc`/`stsz`/`stco` tables into flat indexed `Mp4Sample` records.
1450    ///
1451    /// # Arguments
1452    ///
1453    /// - `&Mp4SampleTableRaw` - Raw parsed sample table arrays.
1454    /// - `u32` - Track media timescale in ticks per second.
1455    ///
1456    /// # Returns
1457    ///
1458    /// - `Vec<Mp4Sample>` - Ordered decode-order sample list.
1459    fn build_samples(raw: &Mp4SampleTableRaw, timescale: u32) -> Vec<Mp4Sample> {
1460        let total_samples: usize = raw.get_sample_count() as usize;
1461        if total_samples == 0 || raw.get_chunk_offsets().is_empty() {
1462            return Vec::new();
1463        }
1464        let mut durations: Vec<u32> = Vec::with_capacity(total_samples);
1465        for (run_count, delta) in raw.get_stts().iter().copied() {
1466            let take_count: usize =
1467                (run_count as usize).min(total_samples.saturating_sub(durations.len()));
1468            for _ in 0..take_count {
1469                durations.push(delta);
1470            }
1471            if durations.len() >= total_samples {
1472                break;
1473            }
1474        }
1475        let mut cto_ticks: Vec<i32> = Vec::with_capacity(total_samples);
1476        for (run_count, offset) in raw.get_ctts().iter().copied() {
1477            let take_count: usize =
1478                (run_count as usize).min(total_samples.saturating_sub(cto_ticks.len()));
1479            for _ in 0..take_count {
1480                cto_ticks.push(offset);
1481            }
1482            if cto_ticks.len() >= total_samples {
1483                break;
1484            }
1485        }
1486        let keyframe_set: HashSet<u32> = raw.get_stss().iter().copied().collect();
1487        let all_keyframes: bool = keyframe_set.is_empty();
1488        let chunk_offsets: &[u64] = raw.get_chunk_offsets().as_slice();
1489        let stsc: &[(u32, u32)] = raw.get_stsc().as_slice();
1490        let mut sample_offsets: Vec<u64> = Vec::with_capacity(total_samples);
1491        let mut sample_sizes: Vec<u32> = Vec::with_capacity(total_samples);
1492        let mut sample_cursor: usize = 0;
1493        let mut stsc_idx: usize = 0;
1494        for (chunk_zero_idx, chunk_base_offset) in chunk_offsets.iter().copied().enumerate() {
1495            let chunk_one_based: u32 = (chunk_zero_idx + 1) as u32;
1496            while stsc_idx + 1 < stsc.len() && stsc[stsc_idx + 1].0 <= chunk_one_based {
1497                stsc_idx += 1;
1498            }
1499            let spc: usize = stsc
1500                .get(stsc_idx)
1501                .map(|e: &(u32, u32)| e.1 as usize)
1502                .unwrap_or(1);
1503            let mut offset_in_chunk: u64 = chunk_base_offset;
1504            for _ in 0..spc {
1505                if sample_cursor >= total_samples {
1506                    break;
1507                }
1508                let size: u32 = if raw.get_default_sample_size() > 0 {
1509                    raw.get_default_sample_size()
1510                } else {
1511                    raw.get_sample_sizes()
1512                        .get(sample_cursor)
1513                        .copied()
1514                        .unwrap_or(0)
1515                };
1516                sample_offsets.push(offset_in_chunk);
1517                sample_sizes.push(size);
1518                offset_in_chunk = offset_in_chunk.saturating_add(size as u64);
1519                sample_cursor += 1;
1520            }
1521            if sample_cursor >= total_samples {
1522                break;
1523            }
1524        }
1525        let mut out: Vec<Mp4Sample> = Vec::with_capacity(sample_offsets.len());
1526        let mut dts_ticks: i64 = 0;
1527        for idx in 0..sample_offsets.len() {
1528            let dur_ticks: u32 = durations.get(idx).copied().unwrap_or(1);
1529            let cto: i64 = cto_ticks.get(idx).copied().unwrap_or(0) as i64;
1530            let dts_us: i64 = Self::signed_ticks_to_us(dts_ticks, timescale);
1531            let pts_us: i64 = Self::signed_ticks_to_us(dts_ticks.saturating_add(cto), timescale);
1532            let duration_us: u64 = Self::ticks_to_us(dur_ticks as u64, timescale);
1533            let one_based: u32 = (idx + 1) as u32;
1534            let is_keyframe: bool = all_keyframes || keyframe_set.contains(&one_based);
1535            out.push(Mp4Sample::new(
1536                idx,
1537                dts_us,
1538                pts_us,
1539                duration_us,
1540                sample_offsets[idx],
1541                sample_sizes[idx],
1542                is_keyframe,
1543            ));
1544            dts_ticks = dts_ticks.saturating_add(dur_ticks as i64);
1545        }
1546        out
1547    }
1548
1549    /// Converts unsigned timescale ticks to microseconds with `u128` overflow protection.
1550    ///
1551    /// # Arguments
1552    ///
1553    /// - `u64` - Duration in media timescale ticks.
1554    /// - `u32` - Media timescale in ticks per second.
1555    ///
1556    /// # Returns
1557    ///
1558    /// - `u64` - Converted duration in microseconds.
1559    #[must_use]
1560    fn ticks_to_us(ticks: u64, timescale: u32) -> u64 {
1561        let scale: u128 = (timescale.max(1)) as u128;
1562        (((ticks as u128) * (VIDEO_MICROS_PER_SEC as u128)) / scale) as u64
1563    }
1564
1565    /// Converts signed timescale ticks to signed microseconds.
1566    ///
1567    /// # Arguments
1568    ///
1569    /// - `i64` - Signed timestamp in media timescale ticks.
1570    /// - `u32` - Media timescale in ticks per second.
1571    ///
1572    /// # Returns
1573    ///
1574    /// - `i64` - Converted signed timestamp in microseconds.
1575    #[must_use]
1576    fn signed_ticks_to_us(ticks: i64, timescale: u32) -> i64 {
1577        let scale: i128 = (timescale.max(1)) as i128;
1578        (((ticks as i128) * (VIDEO_MICROS_PER_SEC as i128)) / scale) as i64
1579    }
1580}
1581
1582/// Pure-Rust ISOBMFF MP4 container builder emitting valid `ftyp`, `moov`, and `mdat` boxes.
1583impl Mp4ContainerBuilder {
1584    /// Serializes a single-track video MP4 container with `ftyp`, `moov` (including `colr` `nclx` HDR metadata and optional `ctts`), and `mdat`.
1585    ///
1586    /// # Arguments
1587    ///
1588    /// - `u32` - Coded frame width in pixels.
1589    /// - `u32` - Coded frame height in pixels.
1590    /// - `u32` - Media timescale in ticks per second (e.g. `90_000` or `60_000`).
1591    /// - `VideoCodec` - Video codec identifier mapped to ISOBMFF FourCC (`avc1`, `hvc1`, `vp09`, `av01`, `rawv`).
1592    /// - `VideoColorInfo` - Color primaries, transfer curve, matrix, and range encoded in `colr`/`nclx`.
1593    /// - `&[Mp4BuilderSample]` - Ordered decode-order video samples.
1594    ///
1595    /// # Returns
1596    ///
1597    /// - `Vec<u8>` - Complete spec-compliant MP4 byte stream.
1598    #[must_use]
1599    pub fn build_video_mp4(
1600        width: u32,
1601        height: u32,
1602        timescale: u32,
1603        codec: VideoCodec,
1604        color_info: VideoColorInfo,
1605        samples: &[Mp4BuilderSample],
1606    ) -> Vec<u8> {
1607        let safe_scale: u32 = timescale.max(1);
1608        let mut total_ticks: u32 = 0;
1609        let mut mdat_payload: Vec<u8> = Vec::new();
1610        for sample in samples.iter() {
1611            total_ticks = total_ticks.saturating_add(sample.get_duration_ticks());
1612            mdat_payload.extend_from_slice(sample.get_payload().as_slice());
1613        }
1614        let mut ftyp_payload: Vec<u8> = Vec::with_capacity(16);
1615        ftyp_payload.extend_from_slice(&MP4_BRAND_ISOM);
1616        ftyp_payload.extend_from_slice(&512_u32.to_be_bytes());
1617        ftyp_payload.extend_from_slice(&MP4_BRAND_ISOM);
1618        ftyp_payload.extend_from_slice(&MP4_BRAND_MP42);
1619        let ftyp_box: Vec<u8> = Self::wrap_box(MP4_BOX_FTYP, &ftyp_payload);
1620        let moov_placeholder: Vec<u8> = Self::build_moov_box(
1621            (width, height),
1622            (safe_scale, total_ticks),
1623            codec,
1624            color_info,
1625            samples,
1626            0,
1627        );
1628        let mdat_data_offset: u32 = (ftyp_box.len() + moov_placeholder.len() + 8) as u32;
1629        let moov_box: Vec<u8> = Self::build_moov_box(
1630            (width, height),
1631            (safe_scale, total_ticks),
1632            codec,
1633            color_info,
1634            samples,
1635            mdat_data_offset,
1636        );
1637        let mdat_box: Vec<u8> = Self::wrap_box(MP4_BOX_MDAT, &mdat_payload);
1638        let mut out: Vec<u8> = Vec::with_capacity(ftyp_box.len() + moov_box.len() + mdat_box.len());
1639        out.extend_from_slice(&ftyp_box);
1640        out.extend_from_slice(&moov_box);
1641        out.extend_from_slice(&mdat_box);
1642        out
1643    }
1644
1645    /// Builds a `moov` box with `mvhd` and one video `trak` referencing `mdat_data_offset`.
1646    ///
1647    /// # Arguments
1648    ///
1649    /// - `(u32, u32)` - Frame `(width, height)` in pixels.
1650    /// - `(u32, u32)` - `(timescale, total_ticks)` timing parameters.
1651    /// - `VideoCodec` - Video codec tag.
1652    /// - `VideoColorInfo` - Color space metadata.
1653    /// - `&[Mp4BuilderSample]` - Sample descriptors.
1654    /// - `u32` - File byte offset of the first sample inside `mdat`.
1655    ///
1656    /// # Returns
1657    ///
1658    /// - `Vec<u8>` - Complete `moov` box bytes.
1659    #[must_use]
1660    fn build_moov_box(
1661        dims: (u32, u32),
1662        timing: (u32, u32),
1663        codec: VideoCodec,
1664        color_info: VideoColorInfo,
1665        samples: &[Mp4BuilderSample],
1666        mdat_data_offset: u32,
1667    ) -> Vec<u8> {
1668        let (width, height): (u32, u32) = dims;
1669        let (timescale, total_ticks): (u32, u32) = timing;
1670        let mut mvhd_payload: Vec<u8> = vec![0; 100];
1671        mvhd_payload[12..16].copy_from_slice(&timescale.to_be_bytes());
1672        mvhd_payload[16..20].copy_from_slice(&total_ticks.to_be_bytes());
1673        mvhd_payload[20..24].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
1674        mvhd_payload[24..26].copy_from_slice(&0x0100_u16.to_be_bytes());
1675        mvhd_payload[96..100].copy_from_slice(&2_u32.to_be_bytes());
1676        let mvhd_box: Vec<u8> = Self::wrap_box(MP4_BOX_MVHD, &mvhd_payload);
1677        let mut tkhd_payload: Vec<u8> = vec![0; 84];
1678        tkhd_payload[3] = 3;
1679        tkhd_payload[12..16].copy_from_slice(&1_u32.to_be_bytes());
1680        tkhd_payload[20..24].copy_from_slice(&total_ticks.to_be_bytes());
1681        tkhd_payload[76..80].copy_from_slice(&(width << 16).to_be_bytes());
1682        tkhd_payload[80..84].copy_from_slice(&(height << 16).to_be_bytes());
1683        let tkhd_box: Vec<u8> = Self::wrap_box(MP4_BOX_TKHD, &tkhd_payload);
1684        let mut mdhd_payload: Vec<u8> = vec![0; 24];
1685        mdhd_payload[12..16].copy_from_slice(&timescale.to_be_bytes());
1686        mdhd_payload[16..20].copy_from_slice(&total_ticks.to_be_bytes());
1687        let mdhd_box: Vec<u8> = Self::wrap_box(MP4_BOX_MDHD, &mdhd_payload);
1688        let mut hdlr_payload: Vec<u8> = vec![0; 25];
1689        hdlr_payload[8..12].copy_from_slice(&MP4_HANDLER_VIDE);
1690        let hdlr_box: Vec<u8> = Self::wrap_box(MP4_BOX_HDLR, &hdlr_payload);
1691        let stbl_box: Vec<u8> =
1692            Self::build_stbl_box(width, height, codec, color_info, samples, mdat_data_offset);
1693        let minf_box: Vec<u8> = Self::wrap_box(MP4_BOX_MINF, &stbl_box);
1694        let mut mdia_payload: Vec<u8> = Vec::new();
1695        mdia_payload.extend_from_slice(&mdhd_box);
1696        mdia_payload.extend_from_slice(&hdlr_box);
1697        mdia_payload.extend_from_slice(&minf_box);
1698        let mdia_box: Vec<u8> = Self::wrap_box(MP4_BOX_MDIA, &mdia_payload);
1699        let mut trak_payload: Vec<u8> = Vec::new();
1700        trak_payload.extend_from_slice(&tkhd_box);
1701        trak_payload.extend_from_slice(&mdia_box);
1702        let trak_box: Vec<u8> = Self::wrap_box(MP4_BOX_TRAK, &trak_payload);
1703        let mut moov_payload: Vec<u8> = Vec::new();
1704        moov_payload.extend_from_slice(&mvhd_box);
1705        moov_payload.extend_from_slice(&trak_box);
1706        Self::wrap_box(MP4_BOX_MOOV, &moov_payload)
1707    }
1708
1709    /// Builds an `stbl` box containing `stsd` (+ `colr`), `stts`, optional `ctts`, `stss`, `stsc`, `stsz`, and `stco`.
1710    ///
1711    /// # Arguments
1712    ///
1713    /// - `u32` - Frame width in pixels.
1714    /// - `u32` - Frame height in pixels.
1715    /// - `VideoCodec` - Video codec tag.
1716    /// - `VideoColorInfo` - Color space metadata.
1717    /// - `&[Mp4BuilderSample]` - Sample descriptors.
1718    /// - `u32` - File byte offset of the first sample inside `mdat`.
1719    ///
1720    /// # Returns
1721    ///
1722    /// - `Vec<u8>` - Complete `stbl` box bytes.
1723    #[must_use]
1724    fn build_stbl_box(
1725        width: u32,
1726        height: u32,
1727        codec: VideoCodec,
1728        color_info: VideoColorInfo,
1729        samples: &[Mp4BuilderSample],
1730        mdat_data_offset: u32,
1731    ) -> Vec<u8> {
1732        let codec_tag: [u8; 4] = match codec {
1733            VideoCodec::H264 => MP4_CODEC_AVC1,
1734            VideoCodec::H265 => MP4_CODEC_HVC1,
1735            VideoCodec::Vp9 => MP4_CODEC_VP09,
1736            VideoCodec::Av1 => MP4_CODEC_AV01,
1737            VideoCodec::RawFrames => MP4_CODEC_RAWV,
1738        };
1739        let (p_code, t_code, m_code, full_range): (u16, u16, u16, bool) = color_info.to_nclx();
1740        let mut colr_payload: Vec<u8> = Vec::with_capacity(11);
1741        colr_payload.extend_from_slice(&MP4_BOX_NCLX);
1742        colr_payload.extend_from_slice(&p_code.to_be_bytes());
1743        colr_payload.extend_from_slice(&t_code.to_be_bytes());
1744        colr_payload.extend_from_slice(&m_code.to_be_bytes());
1745        colr_payload.push(if full_range { 0x80 } else { 0x00 });
1746        let colr_box: Vec<u8> = Self::wrap_box(MP4_BOX_COLR, &colr_payload);
1747        let mut visual_entry_payload: Vec<u8> = vec![0; 78];
1748        visual_entry_payload[6..8].copy_from_slice(&1_u16.to_be_bytes());
1749        visual_entry_payload[24..26].copy_from_slice(&(width as u16).to_be_bytes());
1750        visual_entry_payload[26..28].copy_from_slice(&(height as u16).to_be_bytes());
1751        visual_entry_payload[28..32].copy_from_slice(&0x0048_0000_u32.to_be_bytes());
1752        visual_entry_payload[32..36].copy_from_slice(&0x0048_0000_u32.to_be_bytes());
1753        visual_entry_payload[40..42].copy_from_slice(&1_u16.to_be_bytes());
1754        visual_entry_payload[74..76].copy_from_slice(&24_u16.to_be_bytes());
1755        visual_entry_payload[76..78].copy_from_slice(&0xFFFF_u16.to_be_bytes());
1756        visual_entry_payload.extend_from_slice(&colr_box);
1757        let visual_entry_box: Vec<u8> = Self::wrap_box(codec_tag, &visual_entry_payload);
1758        let mut stsd_payload: Vec<u8> = Vec::with_capacity(8 + visual_entry_box.len());
1759        stsd_payload.extend_from_slice(&0_u32.to_be_bytes());
1760        stsd_payload.extend_from_slice(&1_u32.to_be_bytes());
1761        stsd_payload.extend_from_slice(&visual_entry_box);
1762        let stsd_box: Vec<u8> = Self::wrap_box(MP4_BOX_STSD, &stsd_payload);
1763        let mut stts_payload: Vec<u8> = Vec::with_capacity(8 + samples.len() * 8);
1764        stts_payload.extend_from_slice(&0_u32.to_be_bytes());
1765        stts_payload.extend_from_slice(&(samples.len() as u32).to_be_bytes());
1766        for sample in samples.iter() {
1767            stts_payload.extend_from_slice(&1_u32.to_be_bytes());
1768            stts_payload.extend_from_slice(&sample.get_duration_ticks().to_be_bytes());
1769        }
1770        let stts_box: Vec<u8> = Self::wrap_box(MP4_BOX_STTS, &stts_payload);
1771        let has_ctts: bool = samples
1772            .iter()
1773            .any(|s: &Mp4BuilderSample| s.get_composition_offset_ticks() != 0);
1774        let mut stbl_payload: Vec<u8> = Vec::new();
1775        stbl_payload.extend_from_slice(&stsd_box);
1776        stbl_payload.extend_from_slice(&stts_box);
1777        if has_ctts {
1778            let mut ctts_payload: Vec<u8> = Vec::with_capacity(8 + samples.len() * 8);
1779            ctts_payload.extend_from_slice(&[1, 0, 0, 0]);
1780            ctts_payload.extend_from_slice(&(samples.len() as u32).to_be_bytes());
1781            for sample in samples.iter() {
1782                ctts_payload.extend_from_slice(&1_u32.to_be_bytes());
1783                ctts_payload
1784                    .extend_from_slice(&sample.get_composition_offset_ticks().to_be_bytes());
1785            }
1786            let ctts_box: Vec<u8> = Self::wrap_box(MP4_BOX_CTTS, &ctts_payload);
1787            stbl_payload.extend_from_slice(&ctts_box);
1788        }
1789        let keyframes: Vec<u32> = samples
1790            .iter()
1791            .enumerate()
1792            .filter_map(|(idx, s): (usize, &Mp4BuilderSample)| {
1793                if s.get_is_keyframe() {
1794                    Some((idx + 1) as u32)
1795                } else {
1796                    None
1797                }
1798            })
1799            .collect();
1800        if !keyframes.is_empty() {
1801            let mut stss_payload: Vec<u8> = Vec::with_capacity(8 + keyframes.len() * 4);
1802            stss_payload.extend_from_slice(&0_u32.to_be_bytes());
1803            stss_payload.extend_from_slice(&(keyframes.len() as u32).to_be_bytes());
1804            for kf in keyframes.iter().copied() {
1805                stss_payload.extend_from_slice(&kf.to_be_bytes());
1806            }
1807            let stss_box: Vec<u8> = Self::wrap_box(MP4_BOX_STSS, &stss_payload);
1808            stbl_payload.extend_from_slice(&stss_box);
1809        }
1810        let mut stsc_payload: Vec<u8> = Vec::with_capacity(20);
1811        stsc_payload.extend_from_slice(&0_u32.to_be_bytes());
1812        stsc_payload.extend_from_slice(&1_u32.to_be_bytes());
1813        stsc_payload.extend_from_slice(&1_u32.to_be_bytes());
1814        stsc_payload.extend_from_slice(&(samples.len() as u32).to_be_bytes());
1815        stsc_payload.extend_from_slice(&1_u32.to_be_bytes());
1816        let stsc_box: Vec<u8> = Self::wrap_box(MP4_BOX_STSC, &stsc_payload);
1817        let mut stsz_payload: Vec<u8> = Vec::with_capacity(12 + samples.len() * 4);
1818        stsz_payload.extend_from_slice(&0_u32.to_be_bytes());
1819        stsz_payload.extend_from_slice(&0_u32.to_be_bytes());
1820        stsz_payload.extend_from_slice(&(samples.len() as u32).to_be_bytes());
1821        for sample in samples.iter() {
1822            stsz_payload.extend_from_slice(&(sample.get_payload().len() as u32).to_be_bytes());
1823        }
1824        let stsz_box: Vec<u8> = Self::wrap_box(MP4_BOX_STSZ, &stsz_payload);
1825        let mut stco_payload: Vec<u8> = Vec::with_capacity(12);
1826        stco_payload.extend_from_slice(&0_u32.to_be_bytes());
1827        stco_payload.extend_from_slice(&1_u32.to_be_bytes());
1828        stco_payload.extend_from_slice(&mdat_data_offset.to_be_bytes());
1829        let stco_box: Vec<u8> = Self::wrap_box(MP4_BOX_STCO, &stco_payload);
1830        stbl_payload.extend_from_slice(&stsc_box);
1831        stbl_payload.extend_from_slice(&stsz_box);
1832        stbl_payload.extend_from_slice(&stco_box);
1833        Self::wrap_box(MP4_BOX_STBL, &stbl_payload)
1834    }
1835
1836    /// Wraps `payload` inside a standard 32-bit ISOBMFF box header.
1837    ///
1838    /// # Arguments
1839    ///
1840    /// - `[u8; 4]` - FourCC box type.
1841    /// - `&[u8]` - Box payload bytes.
1842    ///
1843    /// # Returns
1844    ///
1845    /// - `Vec<u8>` - Framed ISOBMFF box bytes.
1846    #[must_use]
1847    fn wrap_box(box_type: [u8; 4], payload: &[u8]) -> Vec<u8> {
1848        let total: u32 = (payload.len() + 8) as u32;
1849        let mut out: Vec<u8> = Vec::with_capacity(total as usize);
1850        out.extend_from_slice(&total.to_be_bytes());
1851        out.extend_from_slice(&box_type);
1852        out.extend_from_slice(payload);
1853        out
1854    }
1855}
1856
1857/// Convenience accessors for inspecting `DecodedVideoFrame` GPU handles or CPU pixel buffers.
1858impl DecodedVideoFrame {
1859    /// Returns the zero-copy GPU surface handle when this frame is GPU-backed.
1860    ///
1861    /// # Arguments
1862    ///
1863    /// - `&Self` - Decoded frame reference.
1864    ///
1865    /// # Returns
1866    ///
1867    /// - `Option<VideoGpuSurfaceHandle>` - GPU surface handle if backed by `GpuSurface`.
1868    #[must_use]
1869    pub fn gpu_surface(&self) -> Option<VideoGpuSurfaceHandle> {
1870        match self.get_backing() {
1871            VideoFrameBacking::GpuSurface(handle) => Some(*handle),
1872            VideoFrameBacking::CpuPooled(_) => None,
1873        }
1874    }
1875
1876    /// Returns a reference to the pooled CPU RGBA8 pixel slice when CPU-backed.
1877    ///
1878    /// # Arguments
1879    ///
1880    /// - `&Self` - Decoded frame reference.
1881    ///
1882    /// # Returns
1883    ///
1884    /// - `Option<&[u8]>` - RGBA8 pixel slice if backed by `CpuPooled`.
1885    #[must_use]
1886    pub fn cpu_rgba_pixels(&self) -> Option<&[u8]> {
1887        match self.get_backing() {
1888            VideoFrameBacking::CpuPooled(pooled) => Some(pooled.get_pixels().as_slice()),
1889            VideoFrameBacking::GpuSurface(_) => None,
1890        }
1891    }
1892
1893    /// Converts a CPU-backed frame into an `ImageBuffer` copy (returns `None` for zero-copy GPU surfaces to avoid readback).
1894    ///
1895    /// # Arguments
1896    ///
1897    /// - `&Self` - Decoded frame reference.
1898    ///
1899    /// # Returns
1900    ///
1901    /// - `Option<ImageBuffer>` - RGBA8 image buffer copy when CPU-backed.
1902    #[must_use]
1903    pub fn to_image_buffer(&self) -> Option<ImageBuffer> {
1904        let pixels: &[u8] = self.cpu_rgba_pixels()?;
1905        Some(ImageBuffer::new(
1906            self.get_width(),
1907            self.get_height(),
1908            pixels.to_vec(),
1909        ))
1910    }
1911}
1912
1913/// Packet encoders and YUV-to-RGB color conversion helpers for `SoftwareVideoDecoder`.
1914impl SoftwareVideoDecoder {
1915    /// Encodes an intra-coded `EVF1` RGBA8 frame packet for pure-Rust software decoding.
1916    ///
1917    /// # Arguments
1918    ///
1919    /// - `u32` - Frame width in pixels.
1920    /// - `u32` - Frame height in pixels.
1921    /// - `&[u8]` - Packed RGBA8 pixel data (`width * height * 4`).
1922    ///
1923    /// # Returns
1924    ///
1925    /// - `Vec<u8>` - Encoded `EVF1` intra RGBA8 packet bytes.
1926    #[must_use]
1927    pub fn encode_intra_rgba_packet(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
1928        let mut out: Vec<u8> = Vec::with_capacity(13 + rgba.len());
1929        out.extend_from_slice(VIDEO_SW_FRAME_MAGIC);
1930        out.push(VIDEO_SW_PACKET_INTRA_RGBA);
1931        out.extend_from_slice(&width.to_le_bytes());
1932        out.extend_from_slice(&height.to_le_bytes());
1933        out.extend_from_slice(rgba);
1934        out
1935    }
1936
1937    /// Encodes an intra-coded `EVF1` tri-planar YUV420P frame packet decoded using the track's `VideoColorInfo` matrix and range.
1938    ///
1939    /// # Arguments
1940    ///
1941    /// - `u32` - Frame width in pixels.
1942    /// - `u32` - Frame height in pixels.
1943    /// - `&[u8]` - Y luma plane (`width * height`).
1944    /// - `&[u8]` - U (Cb) chroma plane (`ceil(width / 2) * ceil(height / 2)`).
1945    /// - `&[u8]` - V (Cr) chroma plane (`ceil(width / 2) * ceil(height / 2)`).
1946    ///
1947    /// # Returns
1948    ///
1949    /// - `Vec<u8>` - Encoded `EVF1` intra YUV420P packet bytes.
1950    #[must_use]
1951    pub fn encode_intra_yuv420p_packet(
1952        width: u32,
1953        height: u32,
1954        y_plane: &[u8],
1955        u_plane: &[u8],
1956        v_plane: &[u8],
1957    ) -> Vec<u8> {
1958        let mut out: Vec<u8> =
1959            Vec::with_capacity(13 + y_plane.len() + u_plane.len() + v_plane.len());
1960        out.extend_from_slice(VIDEO_SW_FRAME_MAGIC);
1961        out.push(VIDEO_SW_PACKET_INTRA_YUV420P);
1962        out.extend_from_slice(&width.to_le_bytes());
1963        out.extend_from_slice(&height.to_le_bytes());
1964        out.extend_from_slice(y_plane);
1965        out.extend_from_slice(u_plane);
1966        out.extend_from_slice(v_plane);
1967        out
1968    }
1969
1970    /// Encodes an inter-coded P-frame XOR delta packet relative to `prev_rgba`.
1971    ///
1972    /// # Arguments
1973    ///
1974    /// - `u32` - Frame width in pixels.
1975    /// - `u32` - Frame height in pixels.
1976    /// - `&[u8]` - Previous reference RGBA8 frame bytes.
1977    /// - `&[u8]` - Target RGBA8 frame bytes.
1978    ///
1979    /// # Returns
1980    ///
1981    /// - `Vec<u8>` - Encoded `EVF1` P-frame delta packet bytes.
1982    #[must_use]
1983    pub fn encode_delta_xor_packet(
1984        width: u32,
1985        height: u32,
1986        prev_rgba: &[u8],
1987        target_rgba: &[u8],
1988    ) -> Vec<u8> {
1989        let len: usize = prev_rgba.len().min(target_rgba.len());
1990        let mut out: Vec<u8> = Vec::with_capacity(13 + len);
1991        out.extend_from_slice(VIDEO_SW_FRAME_MAGIC);
1992        out.push(VIDEO_SW_PACKET_DELTA_XOR);
1993        out.extend_from_slice(&width.to_le_bytes());
1994        out.extend_from_slice(&height.to_le_bytes());
1995        for i in 0..len {
1996            out.push(prev_rgba[i] ^ target_rgba[i]);
1997        }
1998        out
1999    }
2000
2001    /// Converts tri-planar 8-bit YUV420P samples into packed RGBA8 honoring `VideoColorInfo` matrix coefficients and quantization range.
2002    ///
2003    /// # Arguments
2004    ///
2005    /// - `u32` - Frame width in pixels.
2006    /// - `u32` - Frame height in pixels.
2007    /// - `&[u8]` - Concatenated `Y + U + V` planes.
2008    /// - `VideoColorInfo` - Color matrix and range metadata.
2009    /// - `&mut [u8]` - Destination RGBA8 buffer (`width * height * 4`).
2010    fn convert_yuv420p_to_rgba(
2011        width: u32,
2012        height: u32,
2013        yuv: &[u8],
2014        color_info: VideoColorInfo,
2015        dst_rgba: &mut [u8],
2016    ) {
2017        let w: usize = width as usize;
2018        let h: usize = height as usize;
2019        let cw: usize = w.div_ceil(2);
2020        let ch: usize = h.div_ceil(2);
2021        let y_len: usize = w * h;
2022        let uv_len: usize = cw * ch;
2023        let y_plane: &[u8] = &yuv[0..y_len];
2024        let u_plane: &[u8] = &yuv[y_len..(y_len + uv_len)];
2025        let v_plane: &[u8] = &yuv[(y_len + uv_len)..(y_len + uv_len * 2)];
2026        let (kr, kb): (f32, f32) = match color_info.get_matrix() {
2027            MatrixCoefficients::Bt601 => (0.299, 0.114),
2028            MatrixCoefficients::Bt2020Ncl => (0.2627, 0.0593),
2029            MatrixCoefficients::Bt709
2030            | MatrixCoefficients::Identity
2031            | MatrixCoefficients::Unknown(_) => (0.2126, 0.0722),
2032        };
2033        let kg: f32 = 1.0 - kr - kb;
2034        let full_range: bool = color_info.get_range() == ColorRange::Full;
2035        for row in 0..h {
2036            let crow: usize = row / 2;
2037            for col in 0..w {
2038                let y_raw: f32 = y_plane[row * w + col] as f32;
2039                let uv_idx: usize = crow * cw + (col / 2);
2040                let cb_raw: f32 = u_plane[uv_idx] as f32;
2041                let cr_raw: f32 = v_plane[uv_idx] as f32;
2042                let (y_norm, cb_norm, cr_norm): (f32, f32, f32) = if full_range {
2043                    (
2044                        y_raw / 255.0,
2045                        (cb_raw - 128.0) / 255.0,
2046                        (cr_raw - 128.0) / 255.0,
2047                    )
2048                } else {
2049                    (
2050                        ((y_raw - 16.0) / 219.0).clamp(0.0, 1.0),
2051                        (cb_raw - 128.0) / 224.0,
2052                        (cr_raw - 128.0) / 224.0,
2053                    )
2054                };
2055                let r: f32 = y_norm + 2.0 * (1.0 - kr) * cr_norm;
2056                let b: f32 = y_norm + 2.0 * (1.0 - kb) * cb_norm;
2057                let g: f32 = y_norm
2058                    - (2.0 * kb * (1.0 - kb) / kg) * cb_norm
2059                    - (2.0 * kr * (1.0 - kr) / kg) * cr_norm;
2060                let dst: usize = (row * w + col) * 4;
2061                dst_rgba[dst] = (r.clamp(0.0, 1.0) * 255.0).round() as u8;
2062                dst_rgba[dst + 1] = (g.clamp(0.0, 1.0) * 255.0).round() as u8;
2063                dst_rgba[dst + 2] = (b.clamp(0.0, 1.0) * 255.0).round() as u8;
2064                dst_rgba[dst + 3] = 255;
2065            }
2066        }
2067    }
2068}
2069
2070/// Pure-Rust software fallback `VideoDecoderBackend` implementation for `SoftwareVideoDecoder`.
2071impl VideoDecoderBackend for SoftwareVideoDecoder {
2072    /// Returns `HardwareDecoderKind::SoftwareFallback`.
2073    ///
2074    /// # Arguments
2075    ///
2076    /// - `&Self` - Decoder reference.
2077    ///
2078    /// # Returns
2079    ///
2080    /// - `HardwareDecoderKind` - Always `SoftwareFallback`.
2081    fn backend_kind(&self) -> HardwareDecoderKind {
2082        HardwareDecoderKind::SoftwareFallback
2083    }
2084
2085    /// Returns software fallback capabilities.
2086    ///
2087    /// # Arguments
2088    ///
2089    /// - `&Self` - Decoder reference.
2090    ///
2091    /// # Returns
2092    ///
2093    /// - `HardwareDecoderCapabilities` - Software capability profile.
2094    fn capabilities(&self) -> HardwareDecoderCapabilities {
2095        HardwareDecoderProbe::capabilities_for(HardwareDecoderKind::SoftwareFallback)
2096    }
2097
2098    /// Configures the software decoder for the track's dimensions and color metadata.
2099    ///
2100    /// # Arguments
2101    ///
2102    /// - `&Self` - Mutable software decoder.
2103    /// - `&VideoDecoderConfig` - Video track configuration.
2104    ///
2105    /// # Returns
2106    ///
2107    /// - `Result<(), String>` - `Ok(())` when dimensions are valid.
2108    fn configure(&mut self, config: &VideoDecoderConfig) -> Result<(), String> {
2109        if config.get_width() == 0 || config.get_height() == 0 {
2110            return Err(VIDEO_ERR_UNSUPPORTED_DIMENSIONS.to_string());
2111        }
2112        self.set_config(*config);
2113        self.flush();
2114        Ok(())
2115    }
2116
2117    /// Decodes an `EVF1` intra/YUV420P/delta packet or raw RGBA8 frame into a pooled CPU `DecodedVideoFrame`.
2118    ///
2119    /// # Arguments
2120    ///
2121    /// - `&Self` - Mutable software decoder.
2122    /// - `&EncodedVideoPacket` - Encoded packet with DTS/PTS and seek generation.
2123    /// - `&VideoFramePool` - Bounded CPU pixel pool.
2124    ///
2125    /// # Returns
2126    ///
2127    /// - `Result<Option<DecodedVideoFrame>, String>` - Decoded CPU pooled frame or error.
2128    fn decode_packet(
2129        &mut self,
2130        packet: &EncodedVideoPacket,
2131        pool: &VideoFramePool,
2132    ) -> Result<Option<DecodedVideoFrame>, String> {
2133        let data: &[u8] = packet.get_data().as_slice();
2134        let config: VideoDecoderConfig = self.get_config();
2135        let (width, height, kind, payload): (u32, u32, u8, &[u8]) =
2136            if data.len() >= 13 && &data[0..4] == VIDEO_SW_FRAME_MAGIC {
2137                let pkt_kind: u8 = data[4];
2138                let w: u32 = u32::from_le_bytes([data[5], data[6], data[7], data[8]]);
2139                let h: u32 = u32::from_le_bytes([data[9], data[10], data[11], data[12]]);
2140                (w, h, pkt_kind, &data[13..])
2141            } else if config.get_codec() == VideoCodec::RawFrames {
2142                (
2143                    config.get_width(),
2144                    config.get_height(),
2145                    VIDEO_SW_PACKET_INTRA_RGBA,
2146                    data,
2147                )
2148            } else {
2149                return Err(VIDEO_ERR_UNSUPPORTED_CODEC.to_string());
2150            };
2151        if width == 0 || height == 0 {
2152            return Err(VIDEO_ERR_UNSUPPORTED_DIMENSIONS.to_string());
2153        }
2154        let rgba_len: usize = (width as usize)
2155            .checked_mul(height as usize)
2156            .and_then(|v: usize| v.checked_mul(4))
2157            .ok_or_else(|| VIDEO_ERR_UNSUPPORTED_DIMENSIONS.to_string())?;
2158        let mut pooled: PooledVideoFrame = pool
2159            .acquire(width, height)
2160            .ok_or_else(|| VIDEO_ERR_POOL_EXHAUSTED.to_string())?;
2161        match kind {
2162            VIDEO_SW_PACKET_INTRA_RGBA => {
2163                if payload.len() != rgba_len {
2164                    pool.recycle(pooled);
2165                    return Err(VIDEO_ERR_SW_PACKET_SIZE.to_string());
2166                }
2167                pooled.get_mut_pixels().copy_from_slice(payload);
2168            }
2169            VIDEO_SW_PACKET_INTRA_YUV420P => {
2170                let y_len: usize = (width as usize) * (height as usize);
2171                let uv_len: usize = (width as usize).div_ceil(2) * (height as usize).div_ceil(2);
2172                if payload.len() != y_len + uv_len * 2 {
2173                    pool.recycle(pooled);
2174                    return Err(VIDEO_ERR_SW_PACKET_SIZE.to_string());
2175                }
2176                Self::convert_yuv420p_to_rgba(
2177                    width,
2178                    height,
2179                    payload,
2180                    config.get_color_info(),
2181                    pooled.get_mut_pixels().as_mut_slice(),
2182                );
2183            }
2184            VIDEO_SW_PACKET_DELTA_XOR => {
2185                let has_ref: bool = self.get_has_reference();
2186                let Self { reference_rgba, .. } = self;
2187                if !has_ref || reference_rgba.len() != rgba_len {
2188                    pool.recycle(pooled);
2189                    return Err(VIDEO_ERR_SW_DELTA_NO_REF.to_string());
2190                }
2191                if payload.len() != rgba_len {
2192                    pool.recycle(pooled);
2193                    return Err(VIDEO_ERR_SW_PACKET_SIZE.to_string());
2194                }
2195                let dst: &mut [u8] = pooled.get_mut_pixels().as_mut_slice();
2196                for i in 0..rgba_len {
2197                    dst[i] = reference_rgba[i] ^ payload[i];
2198                }
2199            }
2200            _ => {
2201                pool.recycle(pooled);
2202                return Err(VIDEO_ERR_SW_PACKET_INVALID.to_string());
2203            }
2204        }
2205        {
2206            let Self { reference_rgba, .. } = self;
2207            if reference_rgba.len() != rgba_len {
2208                reference_rgba.resize(rgba_len, 0);
2209            }
2210            reference_rgba.copy_from_slice(pooled.get_pixels().as_slice());
2211        }
2212        self.set_has_reference(true);
2213        let next_decoded: u64 = self.get_decoded_frames().saturating_add(1);
2214        self.set_decoded_frames(next_decoded);
2215        Ok(Some(DecodedVideoFrame {
2216            sample_index: packet.get_sample_index(),
2217            generation: packet.get_generation(),
2218            dts_us: packet.get_dts_us(),
2219            pts_us: packet.get_pts_us(),
2220            duration_us: packet.get_duration_us(),
2221            width,
2222            height,
2223            color_info: config.get_color_info(),
2224            backing: VideoFrameBacking::CpuPooled(pooled),
2225        }))
2226    }
2227
2228    /// Clears the retained reference frame upon seek or discontinuity.
2229    ///
2230    /// # Arguments
2231    ///
2232    /// - `&Self` - Mutable software decoder.
2233    fn flush(&mut self) {
2234        self.set_has_reference(false);
2235        let Self { reference_rgba, .. } = self;
2236        reference_rgba.clear();
2237    }
2238}
2239
2240/// Constructors for `HardwareZeroCopyDecoder`.
2241impl HardwareZeroCopyDecoder {
2242    /// Creates a zero-copy GPU interop hardware decoder adapter bound to `kind` and `device_id`.
2243    ///
2244    /// # Arguments
2245    ///
2246    /// - `HardwareDecoderKind` - Target hardware backend (`VideoToolbox`, `MediaCodec`, `Vaapi`, `Dxva`, `WebCodecs`).
2247    /// - `u64` - Target GPU device identifier.
2248    ///
2249    /// # Returns
2250    ///
2251    /// - `Self` - Initialized zero-copy GPU hardware decoder adapter.
2252    #[must_use]
2253    pub fn for_backend(kind: HardwareDecoderKind, device_id: u64) -> Self {
2254        Self {
2255            kind,
2256            device_id,
2257            pixel_format: VideoPixelFormat::Nv12,
2258            config: VideoDecoderConfig::default(),
2259            next_surface_id: 1,
2260            next_fence_value: 1,
2261        }
2262    }
2263}
2264
2265/// Zero-copy GPU surface `VideoDecoderBackend` implementation for `HardwareZeroCopyDecoder`.
2266impl VideoDecoderBackend for HardwareZeroCopyDecoder {
2267    /// Returns the configured hardware backend kind.
2268    ///
2269    /// # Arguments
2270    ///
2271    /// - `&Self` - Hardware decoder reference.
2272    ///
2273    /// # Returns
2274    ///
2275    /// - `HardwareDecoderKind` - Active hardware backend kind.
2276    fn backend_kind(&self) -> HardwareDecoderKind {
2277        self.get_kind()
2278    }
2279
2280    /// Returns hardware capabilities for the configured platform backend.
2281    ///
2282    /// # Arguments
2283    ///
2284    /// - `&Self` - Hardware decoder reference.
2285    ///
2286    /// # Returns
2287    ///
2288    /// - `HardwareDecoderCapabilities` - Hardware capability descriptor.
2289    fn capabilities(&self) -> HardwareDecoderCapabilities {
2290        HardwareDecoderProbe::capabilities_for(self.get_kind())
2291    }
2292
2293    /// Configures surface format (`P010` for HDR10/10-bit streams, `Nv12` for SDR) and track geometry.
2294    ///
2295    /// # Arguments
2296    ///
2297    /// - `&Self` - Mutable hardware decoder.
2298    /// - `&VideoDecoderConfig` - Video track metadata.
2299    ///
2300    /// # Returns
2301    ///
2302    /// - `Result<(), String>` - `Ok(())` when dimensions are valid.
2303    fn configure(&mut self, config: &VideoDecoderConfig) -> Result<(), String> {
2304        if config.get_width() == 0 || config.get_height() == 0 {
2305            return Err(VIDEO_ERR_UNSUPPORTED_DIMENSIONS.to_string());
2306        }
2307        self.set_config(*config);
2308        let fmt: VideoPixelFormat =
2309            if config.get_color_info().is_hdr() || config.get_color_info().get_bit_depth() >= 10 {
2310                VideoPixelFormat::P010
2311            } else {
2312                VideoPixelFormat::Nv12
2313            };
2314        self.set_pixel_format(fmt);
2315        Ok(())
2316    }
2317
2318    /// Emits a zero-copy `VideoGpuSurfaceHandle` backed frame without touching the CPU frame pool.
2319    ///
2320    /// # Arguments
2321    ///
2322    /// - `&Self` - Mutable hardware decoder.
2323    /// - `&EncodedVideoPacket` - Demuxed video packet.
2324    /// - `&VideoFramePool` - Unused CPU pool (zero CPU allocation on hardware zero-copy path).
2325    ///
2326    /// # Returns
2327    ///
2328    /// - `Result<Option<DecodedVideoFrame>, String>` - GPU-surface-backed decoded frame.
2329    fn decode_packet(
2330        &mut self,
2331        packet: &EncodedVideoPacket,
2332        _pool: &VideoFramePool,
2333    ) -> Result<Option<DecodedVideoFrame>, String> {
2334        let config: VideoDecoderConfig = self.get_config();
2335        let surface_id: u64 = self.get_next_surface_id();
2336        self.set_next_surface_id(surface_id.saturating_add(1));
2337        let fence_value: u64 = self.get_next_fence_value();
2338        self.set_next_fence_value(fence_value.saturating_add(1));
2339        let handle: VideoGpuSurfaceHandle = VideoGpuSurfaceHandle {
2340            surface_id,
2341            device_id: self.get_device_id(),
2342            generation: packet.get_generation(),
2343            width: config.get_width(),
2344            height: config.get_height(),
2345            pixel_format: self.get_pixel_format(),
2346            color_info: config.get_color_info(),
2347            fence_value,
2348            zero_copy: true,
2349            backend: self.get_kind(),
2350        };
2351        Ok(Some(DecodedVideoFrame {
2352            sample_index: packet.get_sample_index(),
2353            generation: packet.get_generation(),
2354            dts_us: packet.get_dts_us(),
2355            pts_us: packet.get_pts_us(),
2356            duration_us: packet.get_duration_us(),
2357            width: config.get_width(),
2358            height: config.get_height(),
2359            color_info: config.get_color_info(),
2360            backing: VideoFrameBacking::GpuSurface(handle),
2361        }))
2362    }
2363
2364    /// Resets hardware decoder reorder state on seek.
2365    ///
2366    /// # Arguments
2367    ///
2368    /// - `&Self` - Mutable hardware decoder.
2369    fn flush(&mut self) {}
2370}
2371
2372/// Bounded PTS-ordered insertion, seek-generation draining, and due-frame retrieval for `PtsFrameQueue`.
2373impl PtsFrameQueue {
2374    /// Creates a bounded `PtsFrameQueue` retaining at most `capacity` decoded frames.
2375    ///
2376    /// # Arguments
2377    ///
2378    /// - `usize` - Maximum queued frame count (`>= 1`).
2379    ///
2380    /// # Returns
2381    ///
2382    /// - `Self` - Empty bounded queue.
2383    #[must_use]
2384    pub fn with_capacity(capacity: usize) -> Self {
2385        let cap: usize = capacity.max(1);
2386        Self {
2387            capacity: cap,
2388            frames: Vec::with_capacity(cap),
2389            stale_generation_drops: 0,
2390        }
2391    }
2392
2393    /// Returns `true` when the queue is at its bounded capacity.
2394    ///
2395    /// # Arguments
2396    ///
2397    /// - `&Self` - Queue reference.
2398    ///
2399    /// # Returns
2400    ///
2401    /// - `bool` - `true` when `len() >= capacity`.
2402    #[must_use]
2403    pub fn is_full(&self) -> bool {
2404        self.get_frames().len() >= self.get_capacity()
2405    }
2406
2407    /// Returns the number of frames currently buffered in the queue.
2408    ///
2409    /// # Arguments
2410    ///
2411    /// - `&Self` - Queue reference.
2412    ///
2413    /// # Returns
2414    ///
2415    /// - `usize` - Queued frame count.
2416    #[must_use]
2417    pub fn len(&self) -> usize {
2418        self.get_frames().len()
2419    }
2420
2421    /// Returns `true` when no frames are queued.
2422    ///
2423    /// # Arguments
2424    ///
2425    /// - `&Self` - Queue reference.
2426    ///
2427    /// # Returns
2428    ///
2429    /// - `bool` - `true` iff empty.
2430    #[must_use]
2431    pub fn is_empty(&self) -> bool {
2432        self.get_frames().is_empty()
2433    }
2434
2435    /// Inserts `frame` in ascending `pts_us` order (reordering B-frames automatically), returning `Some(frame)` if the bounded queue is full.
2436    ///
2437    /// # Arguments
2438    ///
2439    /// - `&Self` - Mutable PTS queue.
2440    /// - `DecodedVideoFrame` - Frame to insert.
2441    ///
2442    /// # Returns
2443    ///
2444    /// - `Option<DecodedVideoFrame>` - `None` when inserted, or `Some(frame)` when queue is at bounded capacity.
2445    pub fn push_ordered(&mut self, frame: DecodedVideoFrame) -> Option<DecodedVideoFrame> {
2446        if self.is_full() {
2447            return Some(frame);
2448        }
2449        let target_pts: i64 = frame.get_pts_us();
2450        let insert_pos: usize = self
2451            .get_frames()
2452            .partition_point(|existing: &DecodedVideoFrame| existing.get_pts_us() <= target_pts);
2453        self.get_mut_frames().insert(insert_pos, frame);
2454        None
2455    }
2456
2457    /// Peeks the earliest presentation timestamp currently waiting at the front of the queue.
2458    ///
2459    /// # Arguments
2460    ///
2461    /// - `&Self` - Queue reference.
2462    ///
2463    /// # Returns
2464    ///
2465    /// - `Option<i64>` - Front frame PTS in microseconds, if any.
2466    #[must_use]
2467    pub fn peek_front_pts_us(&self) -> Option<i64> {
2468        self.get_frames()
2469            .first()
2470            .map(|f: &DecodedVideoFrame| f.get_pts_us())
2471    }
2472
2473    /// Removes and recycles every queued frame whose `generation != active_generation`.
2474    ///
2475    /// # Arguments
2476    ///
2477    /// - `&Self` - Mutable PTS queue.
2478    /// - `u64` - Active seek generation.
2479    /// - `&VideoFramePool` - Pool receiving recycled CPU buffers.
2480    ///
2481    /// # Returns
2482    ///
2483    /// - `usize` - Number of stale frames drained.
2484    pub fn drain_stale_generations(
2485        &mut self,
2486        active_generation: u64,
2487        pool: &VideoFramePool,
2488    ) -> usize {
2489        let mut drained: usize = 0;
2490        let existing: Vec<DecodedVideoFrame> = take(self.get_mut_frames());
2491        let mut kept: Vec<DecodedVideoFrame> = Vec::with_capacity(existing.len());
2492        for frame in existing.into_iter() {
2493            if frame.get_generation() == active_generation {
2494                kept.push(frame);
2495            } else {
2496                pool.recycle_decoded_frame(frame);
2497                drained += 1;
2498            }
2499        }
2500        *self.get_mut_frames() = kept;
2501        let next_drops: u64 = self
2502            .get_stale_generation_drops()
2503            .saturating_add(drained as u64);
2504        self.set_stale_generation_drops(next_drops);
2505        drained
2506    }
2507
2508    /// Drains all queued frames and recycles any CPU-pooled buffers back into `pool`.
2509    ///
2510    /// # Arguments
2511    ///
2512    /// - `&Self` - Mutable PTS queue.
2513    /// - `&VideoFramePool` - Pool receiving recycled CPU buffers.
2514    pub fn clear_and_recycle(&mut self, pool: &VideoFramePool) {
2515        let existing: Vec<DecodedVideoFrame> = take(self.get_mut_frames());
2516        for frame in existing.into_iter() {
2517            pool.recycle_decoded_frame(frame);
2518        }
2519    }
2520}
2521
2522/// Audio-master / monotonic clock A/V synchronization and cadence-preserving frame selection for `AvSyncScheduler`.
2523impl AvSyncScheduler {
2524    /// Creates an initialized `AvSyncScheduler` starting at `0 us` with `1.0x` playback rate.
2525    ///
2526    /// # Returns
2527    ///
2528    /// - `Self` - Ready scheduler.
2529    #[must_use]
2530    pub fn new_default() -> Self {
2531        Self {
2532            clock_source: AvSyncClockSource::MonotonicFallback,
2533            clock_pts_us: 0,
2534            playback_rate: 1.0,
2535            max_late_us: VIDEO_DEFAULT_MAX_LATE_US,
2536            last_presented_pts_us: None,
2537            frames_presented: 0,
2538            frames_held_vsync: 0,
2539            frames_dropped_late: 0,
2540        }
2541    }
2542
2543    /// Returns the PTS in microseconds of the most recently presented frame.
2544    ///
2545    /// # Arguments
2546    ///
2547    /// - `&Self` - Scheduler reference.
2548    ///
2549    /// # Returns
2550    ///
2551    /// - `Option<i64>` - Last presented PTS or `None`.
2552    #[must_use]
2553    pub const fn last_presented_pts_us(&self) -> Option<i64> {
2554        let Self {
2555            last_presented_pts_us,
2556            ..
2557        } = *self;
2558        last_presented_pts_us
2559    }
2560
2561    /// Switches to `AudioMaster` synchronization and updates the active clock position from hardware audio playback.
2562    ///
2563    /// # Arguments
2564    ///
2565    /// - `&Self` - Mutable scheduler.
2566    /// - `i64` - Current hardware audio playback timestamp in microseconds.
2567    pub fn update_audio_clock_us(&mut self, audio_pts_us: i64) {
2568        self.set_clock_source(AvSyncClockSource::AudioMaster);
2569        self.set_clock_pts_us(audio_pts_us.max(0));
2570    }
2571
2572    /// Advances the fallback monotonic clock by `delta_us * playback_rate` when audio master is inactive or muted.
2573    ///
2574    /// # Arguments
2575    ///
2576    /// - `&Self` - Mutable scheduler.
2577    /// - `u64` - Elapsed wall display delta in microseconds.
2578    pub fn advance_monotonic_us(&mut self, delta_us: u64) {
2579        self.set_clock_source(AvSyncClockSource::MonotonicFallback);
2580        let rate: f64 = (self.get_playback_rate().clamp(0.25, 4.0)) as f64;
2581        let scaled: i64 = ((delta_us as f64) * rate).round() as i64;
2582        let next_clock: i64 = self.get_clock_pts_us().saturating_add(scaled.max(0));
2583        self.set_clock_pts_us(next_clock);
2584    }
2585
2586    /// Resets the scheduler clock directly to `target_pts_us` after a seek discontinuity.
2587    ///
2588    /// # Arguments
2589    ///
2590    /// - `&Self` - Mutable scheduler.
2591    /// - `i64` - New target playback timestamp in microseconds.
2592    pub fn reset_for_seek(&mut self, target_pts_us: i64) {
2593        self.set_clock_pts_us(target_pts_us.max(0));
2594        let Self {
2595            last_presented_pts_us,
2596            ..
2597        } = self;
2598        *last_presented_pts_us = None;
2599    }
2600
2601    /// Selects the frame due for presentation on the current VSync tick without ever forging new frames when display Hz exceeds video FPS.
2602    ///
2603    /// # Arguments
2604    ///
2605    /// - `&Self` - Mutable scheduler.
2606    /// - `&mut PtsFrameQueue` - Bounded PTS-ordered decoded frame queue.
2607    /// - `&VideoFramePool` - Pool receiving any dropped late CPU frames.
2608    /// - `bool` - Whether the decoder has reached end-of-stream.
2609    /// - `bool` - Whether a frame is already currently displayed on screen.
2610    ///
2611    /// # Returns
2612    ///
2613    /// - `VideoPresentDecision` - `PresentNewFrame`, `HoldCurrentFrame`, `Buffering`, or `Ended`.
2614    pub fn select_frame_for_vsync(
2615        &mut self,
2616        queue: &mut PtsFrameQueue,
2617        pool: &VideoFramePool,
2618        reached_eos: bool,
2619        has_displayed_frame: bool,
2620    ) -> VideoPresentDecision {
2621        let clock_us: i64 = self.get_clock_pts_us();
2622        let Some(front_pts) = queue.peek_front_pts_us() else {
2623            if reached_eos {
2624                return VideoPresentDecision::Ended;
2625            }
2626            if has_displayed_frame {
2627                let next_held: u64 = self.get_frames_held_vsync().saturating_add(1);
2628                self.set_frames_held_vsync(next_held);
2629                return VideoPresentDecision::HoldCurrentFrame;
2630            }
2631            return VideoPresentDecision::Buffering;
2632        };
2633        if front_pts > clock_us.saturating_add(VIDEO_PRESENT_TOLERANCE_US) {
2634            let next_held: u64 = self.get_frames_held_vsync().saturating_add(1);
2635            self.set_frames_held_vsync(next_held);
2636            return VideoPresentDecision::HoldCurrentFrame;
2637        }
2638        let mut due_count: usize = 0;
2639        for frame in queue.get_frames().iter() {
2640            if frame.get_pts_us() <= clock_us.saturating_add(VIDEO_PRESENT_TOLERANCE_US) {
2641                due_count += 1;
2642            } else {
2643                break;
2644            }
2645        }
2646        let max_late: i64 = self.get_max_late_us().max(0);
2647        let mut chosen: Option<DecodedVideoFrame> = None;
2648        let mut dropped: u64 = 0;
2649        for idx in 0..due_count {
2650            let frame: DecodedVideoFrame = queue.get_mut_frames().remove(0);
2651            let is_last_due: bool = idx + 1 == due_count;
2652            let lateness: i64 = clock_us.saturating_sub(frame.get_pts_us());
2653            if !is_last_due {
2654                let _: bool = lateness > max_late;
2655                pool.recycle_decoded_frame(frame);
2656                dropped = dropped.saturating_add(1);
2657            } else {
2658                chosen = Some(frame);
2659            }
2660        }
2661        if dropped > 0 {
2662            let next_dropped: u64 = self.get_frames_dropped_late().saturating_add(dropped);
2663            self.set_frames_dropped_late(next_dropped);
2664        }
2665        if let Some(frame) = chosen {
2666            let pts: i64 = frame.get_pts_us();
2667            let Self {
2668                last_presented_pts_us,
2669                ..
2670            } = self;
2671            *last_presented_pts_us = Some(pts);
2672            let next_presented: u64 = self.get_frames_presented().saturating_add(1);
2673            self.set_frames_presented(next_presented);
2674            VideoPresentDecision::PresentNewFrame(frame)
2675        } else if reached_eos {
2676            VideoPresentDecision::Ended
2677        } else {
2678            VideoPresentDecision::HoldCurrentFrame
2679        }
2680    }
2681}
2682
2683/// Multi-threaded (native) / deterministic pumpable (wasm32) structured video playback pipeline implementation.
2684impl VideoPlaybackPipeline {
2685    /// Opens an MP4 byte stream using the pure-Rust `SoftwareVideoDecoder` fallback and bounded queue/pool capacities.
2686    ///
2687    /// # Arguments
2688    ///
2689    /// - `Vec<u8>` - Complete MP4 container bytes.
2690    ///
2691    /// # Returns
2692    ///
2693    /// - `Result<Self, String>` - Initialized video playback pipeline or parse/config error.
2694    pub fn from_mp4_bytes(bytes: Vec<u8>) -> Result<Self, String> {
2695        Self::from_mp4_with_backend(
2696            bytes,
2697            Box::new(SoftwareVideoDecoder::default()),
2698            VIDEO_DEFAULT_QUEUE_CAPACITY,
2699            VIDEO_DEFAULT_POOL_CAPACITY,
2700        )
2701    }
2702
2703    /// Opens an MP4 byte stream using a custom hardware or software `VideoDecoderBackend`.
2704    ///
2705    /// # Arguments
2706    ///
2707    /// - `Vec<u8>` - Complete MP4 container bytes.
2708    /// - `Box<dyn VideoDecoderBackend>` - Hardware zero-copy or software decoder backend.
2709    /// - `usize` - Bounded PTS frame queue capacity.
2710    /// - `usize` - Bounded CPU RGBA8 frame pool capacity.
2711    ///
2712    /// # Returns
2713    ///
2714    /// - `Result<Self, String>` - Initialized video playback pipeline or error.
2715    pub fn from_mp4_with_backend(
2716        bytes: Vec<u8>,
2717        mut decoder: Box<dyn VideoDecoderBackend>,
2718        queue_capacity: usize,
2719        pool_capacity: usize,
2720    ) -> Result<Self, String> {
2721        let demuxer: Mp4Demuxer = Mp4Demuxer::parse(bytes)?;
2722        let config: VideoDecoderConfig = demuxer.video_decoder_config();
2723        decoder.configure(&config)?;
2724        let backend_kind: HardwareDecoderKind = decoder.backend_kind();
2725        let color_info: VideoColorInfo = config.get_color_info();
2726        let pool: VideoFramePool = VideoFramePool::with_capacity(pool_capacity);
2727        let scheduler: AvSyncScheduler = AvSyncScheduler::new_default();
2728        #[cfg(not(target_arch = "wasm32"))]
2729        {
2730            let shared_state: VideoWorkerShared = VideoWorkerShared {
2731                queue: PtsFrameQueue::with_capacity(queue_capacity),
2732                active_generation: 1,
2733                next_sample_index: 0,
2734                seek_preroll_target_us: 0,
2735                pending_seek: None,
2736                playing: true,
2737                reached_eos: demuxer.video_sample_count() == 0,
2738                shutdown: false,
2739                packets_decoded: 0,
2740                seek_preroll_frames_discarded: 0,
2741                last_error: None,
2742            };
2743            let worker_shared: Arc<(Mutex<VideoWorkerShared>, Condvar)> =
2744                Arc::new((Mutex::new(shared_state), Condvar::new()));
2745            let worker_shared_clone: Arc<(Mutex<VideoWorkerShared>, Condvar)> =
2746                Arc::clone(&worker_shared);
2747            let worker_demuxer: Mp4Demuxer = demuxer.clone();
2748            let worker_pool: VideoFramePool = pool.clone();
2749            let handle_opt: Option<JoinHandle<()>> = Builder::new()
2750                .name(VIDEO_WORKER_THREAD_NAME.to_string())
2751                .spawn(move || {
2752                    Self::worker_loop(worker_demuxer, decoder, worker_pool, worker_shared_clone);
2753                })
2754                .ok();
2755            Ok(Self {
2756                demuxer,
2757                pool,
2758                scheduler,
2759                backend_kind,
2760                color_info,
2761                state: PlaybackState::Playing,
2762                current_frame: None,
2763                active_generation: 1,
2764                worker_shared,
2765                worker_handle: handle_opt,
2766            })
2767        }
2768        #[cfg(target_arch = "wasm32")]
2769        {
2770            let reached_eos: bool = demuxer.video_sample_count() == 0;
2771            Ok(Self {
2772                demuxer,
2773                pool,
2774                scheduler,
2775                backend_kind,
2776                color_info,
2777                state: PlaybackState::Playing,
2778                current_frame: None,
2779                active_generation: 1,
2780                wasm_decoder: decoder,
2781                wasm_queue: PtsFrameQueue::with_capacity(queue_capacity),
2782                wasm_next_sample: 0,
2783                wasm_preroll_target_us: 0,
2784                wasm_eos: reached_eos,
2785                wasm_packets_decoded: 0,
2786                wasm_preroll_discarded: 0,
2787                wasm_last_error: None,
2788            })
2789        }
2790    }
2791
2792    /// Background decode thread loop draining MP4 packets into the bounded PTS-ordered queue.
2793    ///
2794    /// # Arguments
2795    ///
2796    /// - `Mp4Demuxer` - Owned container demuxer.
2797    /// - `Box<dyn VideoDecoderBackend>` - Owned hardware or software decoder.
2798    /// - `VideoFramePool` - Shared bounded CPU frame pool.
2799    /// - `Arc<(Mutex<VideoWorkerShared>, Condvar)>` - Shared queue and wakeup condvar.
2800    #[cfg(not(target_arch = "wasm32"))]
2801    fn worker_loop(
2802        demuxer: Mp4Demuxer,
2803        mut decoder: Box<dyn VideoDecoderBackend>,
2804        pool: VideoFramePool,
2805        shared: Arc<(Mutex<VideoWorkerShared>, Condvar)>,
2806    ) {
2807        let total_samples: usize = demuxer.video_sample_count();
2808        loop {
2809            let work_item: Option<(usize, u64, i64)> = {
2810                let mut guard: MutexGuard<'_, VideoWorkerShared> = shared.0.lock().unwrap_or_else(
2811                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
2812                );
2813                loop {
2814                    if guard.get_shutdown() {
2815                        return;
2816                    }
2817                    let pending_seek: Option<(u64, usize, i64)> = {
2818                        let VideoWorkerShared { pending_seek, .. } = &mut *guard;
2819                        pending_seek.take()
2820                    };
2821                    if let Some((new_gen, kf_idx, target_pts)) = pending_seek {
2822                        decoder.flush();
2823                        let _: usize = guard
2824                            .get_mut_queue()
2825                            .drain_stale_generations(new_gen, &pool);
2826                        guard.set_active_generation(new_gen);
2827                        guard.set_next_sample_index(kf_idx);
2828                        guard.set_seek_preroll_target_us(target_pts);
2829                        guard.set_reached_eos(kf_idx >= total_samples);
2830                        let VideoWorkerShared { last_error, .. } = &mut *guard;
2831                        *last_error = None;
2832                    }
2833                    let can_decode: bool = guard.get_playing()
2834                        && !guard.get_reached_eos()
2835                        && !guard.get_queue().is_full()
2836                        && guard.get_next_sample_index() < total_samples;
2837                    if can_decode {
2838                        let idx: usize = guard.get_next_sample_index();
2839                        let gen_id: u64 = guard.get_active_generation();
2840                        let target_pts: i64 = guard.get_seek_preroll_target_us();
2841                        guard.set_next_sample_index(idx.saturating_add(1));
2842                        break Some((idx, gen_id, target_pts));
2843                    }
2844                    guard = shared.1.wait(guard).unwrap_or_else(
2845                        |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
2846                    );
2847                }
2848            };
2849            let Some((sample_idx, packet_gen, preroll_target_us)) = work_item else {
2850                continue;
2851            };
2852            let Some(packet) = demuxer.read_video_packet(sample_idx, packet_gen) else {
2853                let mut guard: MutexGuard<'_, VideoWorkerShared> = shared.0.lock().unwrap_or_else(
2854                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
2855                );
2856                if guard.get_active_generation() == packet_gen {
2857                    guard.set_reached_eos(true);
2858                }
2859                shared.1.notify_all();
2860                continue;
2861            };
2862            let decode_res: Result<Option<DecodedVideoFrame>, String> =
2863                decoder.decode_packet(&packet, &pool);
2864            let mut guard: MutexGuard<'_, VideoWorkerShared> = shared.0.lock().unwrap_or_else(
2865                |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
2866            );
2867            if guard.get_active_generation() != packet_gen || guard.get_shutdown() {
2868                if let Ok(Some(stale)) = decode_res {
2869                    pool.recycle_decoded_frame(stale);
2870                }
2871                shared.1.notify_all();
2872                continue;
2873            }
2874            match decode_res {
2875                Ok(Some(frame)) => {
2876                    let next_decoded: u64 = guard.get_packets_decoded().saturating_add(1);
2877                    guard.set_packets_decoded(next_decoded);
2878                    if frame.get_pts_us() < preroll_target_us && sample_idx + 1 < total_samples {
2879                        pool.recycle_decoded_frame(frame);
2880                        let next_disc: u64 =
2881                            guard.get_seek_preroll_frames_discarded().saturating_add(1);
2882                        guard.set_seek_preroll_frames_discarded(next_disc);
2883                    } else if let Some(rejected) = guard.get_mut_queue().push_ordered(frame) {
2884                        pool.recycle_decoded_frame(rejected);
2885                    }
2886                }
2887                Ok(None) => {}
2888                Err(msg) => {
2889                    let VideoWorkerShared { last_error, .. } = &mut *guard;
2890                    *last_error = Some(msg);
2891                    guard.set_reached_eos(true);
2892                }
2893            }
2894            if sample_idx + 1 >= total_samples {
2895                guard.set_reached_eos(true);
2896            }
2897            shared.1.notify_all();
2898        }
2899    }
2900
2901    /// Returns a reference to the parsed MP4 demuxer.
2902    ///
2903    /// # Arguments
2904    ///
2905    /// - `&Self` - Pipeline reference.
2906    ///
2907    /// # Returns
2908    ///
2909    /// - `&Mp4Demuxer` - Demuxer reference.
2910    #[must_use]
2911    pub fn demuxer(&self) -> &Mp4Demuxer {
2912        let Self { demuxer, .. } = self;
2913        demuxer
2914    }
2915
2916    /// Returns a reference to the bounded CPU video frame pool.
2917    ///
2918    /// # Arguments
2919    ///
2920    /// - `&Self` - Pipeline reference.
2921    ///
2922    /// # Returns
2923    ///
2924    /// - `&VideoFramePool` - Frame pool reference.
2925    #[must_use]
2926    pub fn frame_pool(&self) -> &VideoFramePool {
2927        let Self { pool, .. } = self;
2928        pool
2929    }
2930
2931    /// Returns a reference to the active A/V synchronization scheduler.
2932    ///
2933    /// # Arguments
2934    ///
2935    /// - `&Self` - Pipeline reference.
2936    ///
2937    /// # Returns
2938    ///
2939    /// - `&AvSyncScheduler` - Scheduler reference.
2940    #[must_use]
2941    pub fn scheduler(&self) -> &AvSyncScheduler {
2942        let Self { scheduler, .. } = self;
2943        scheduler
2944    }
2945
2946    /// Returns a mutable reference to the A/V synchronization scheduler.
2947    ///
2948    /// # Arguments
2949    ///
2950    /// - `&Self` - Mutable pipeline.
2951    ///
2952    /// # Returns
2953    ///
2954    /// - `&mut AvSyncScheduler` - Mutable scheduler reference.
2955    pub fn scheduler_mut(&mut self) -> &mut AvSyncScheduler {
2956        let Self { scheduler, .. } = self;
2957        scheduler
2958    }
2959
2960    /// Returns the active decoder backend kind (`VideoToolbox`, `MediaCodec`, `Vaapi`, `Dxva`, `WebCodecs`, or `SoftwareFallback`).
2961    ///
2962    /// # Arguments
2963    ///
2964    /// - `&Self` - Pipeline reference.
2965    ///
2966    /// # Returns
2967    ///
2968    /// - `HardwareDecoderKind` - Active backend kind.
2969    #[must_use]
2970    pub const fn backend_kind(&self) -> HardwareDecoderKind {
2971        let Self { backend_kind, .. } = *self;
2972        backend_kind
2973    }
2974
2975    /// Returns preserved color primaries, transfer curve, matrix, range, and HDR metadata.
2976    ///
2977    /// # Arguments
2978    ///
2979    /// - `&Self` - Pipeline reference.
2980    ///
2981    /// # Returns
2982    ///
2983    /// - `VideoColorInfo` - Track color and HDR metadata.
2984    #[must_use]
2985    pub const fn color_info(&self) -> VideoColorInfo {
2986        let Self { color_info, .. } = *self;
2987        color_info
2988    }
2989
2990    /// Returns the active transport playback state.
2991    ///
2992    /// # Arguments
2993    ///
2994    /// - `&Self` - Pipeline reference.
2995    ///
2996    /// # Returns
2997    ///
2998    /// - `PlaybackState` - Current playback state.
2999    #[must_use]
3000    pub const fn playback_state(&self) -> PlaybackState {
3001        let Self { state, .. } = *self;
3002        state
3003    }
3004
3005    /// Returns the currently displayed decoded frame, if any.
3006    ///
3007    /// # Arguments
3008    ///
3009    /// - `&Self` - Pipeline reference.
3010    ///
3011    /// # Returns
3012    ///
3013    /// - `Option<&DecodedVideoFrame>` - Active frame reference.
3014    #[must_use]
3015    pub fn current_frame(&self) -> Option<&DecodedVideoFrame> {
3016        let Self { current_frame, .. } = self;
3017        current_frame.as_ref()
3018    }
3019
3020    /// Returns the active seek generation counter.
3021    ///
3022    /// # Arguments
3023    ///
3024    /// - `&Self` - Pipeline reference.
3025    ///
3026    /// # Returns
3027    ///
3028    /// - `u64` - Active generation counter.
3029    #[must_use]
3030    pub const fn active_generation(&self) -> u64 {
3031        let Self {
3032            active_generation, ..
3033        } = *self;
3034        active_generation
3035    }
3036
3037    /// Resumes background decoding and playback.
3038    ///
3039    /// # Arguments
3040    ///
3041    /// - `&Self` - Mutable pipeline.
3042    pub fn play(&mut self) {
3043        let Self { state, .. } = self;
3044        *state = PlaybackState::Playing;
3045        #[cfg(not(target_arch = "wasm32"))]
3046        {
3047            let Self { worker_shared, .. } = self;
3048            let mut guard: MutexGuard<'_, VideoWorkerShared> =
3049                worker_shared.0.lock().unwrap_or_else(
3050                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3051                );
3052            guard.set_playing(true);
3053            worker_shared.1.notify_all();
3054        }
3055    }
3056
3057    /// Pauses playback and suspends background worker decoding until resumed.
3058    ///
3059    /// # Arguments
3060    ///
3061    /// - `&Self` - Mutable pipeline.
3062    pub fn pause(&mut self) {
3063        let Self { state, .. } = self;
3064        *state = PlaybackState::Paused;
3065        #[cfg(not(target_arch = "wasm32"))]
3066        {
3067            let Self { worker_shared, .. } = self;
3068            let mut guard: MutexGuard<'_, VideoWorkerShared> =
3069                worker_shared.0.lock().unwrap_or_else(
3070                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3071                );
3072            guard.set_playing(false);
3073            worker_shared.1.notify_all();
3074        }
3075    }
3076
3077    /// Executes a generation-tagged seek: drains stale frames, rewinds demuxer to the preceding keyframe, flushes decoder, and prerolls to `target_pts_us`.
3078    ///
3079    /// # Arguments
3080    ///
3081    /// - `&Self` - Mutable pipeline.
3082    /// - `i64` - Target presentation timestamp in microseconds.
3083    ///
3084    /// # Returns
3085    ///
3086    /// - `u64` - Newly incremented generation identifier.
3087    pub fn seek_us(&mut self, target_pts_us: i64) -> u64 {
3088        let clamped_target: i64 = target_pts_us.max(0);
3089        let keyframe_idx: usize = self.demuxer().seek_keyframe_index(clamped_target);
3090        let next_gen: u64 = {
3091            let Self {
3092                active_generation,
3093                scheduler,
3094                current_frame,
3095                pool,
3096                state,
3097                ..
3098            } = self;
3099            *active_generation = active_generation.saturating_add(1);
3100            scheduler.reset_for_seek(clamped_target);
3101            if let Some(old_frame) = current_frame.take() {
3102                pool.recycle_decoded_frame(old_frame);
3103            }
3104            if *state == PlaybackState::Ended {
3105                *state = PlaybackState::Playing;
3106            }
3107            *active_generation
3108        };
3109        #[cfg(not(target_arch = "wasm32"))]
3110        {
3111            let Self {
3112                worker_shared,
3113                pool,
3114                ..
3115            } = self;
3116            let mut guard: MutexGuard<'_, VideoWorkerShared> =
3117                worker_shared.0.lock().unwrap_or_else(
3118                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3119                );
3120            let _: usize = guard
3121                .get_mut_queue()
3122                .drain_stale_generations(next_gen, pool);
3123            guard.set_active_generation(next_gen);
3124            guard.set_reached_eos(false);
3125            let VideoWorkerShared { pending_seek, .. } = &mut *guard;
3126            *pending_seek = Some((next_gen, keyframe_idx, clamped_target));
3127            worker_shared.1.notify_all();
3128        }
3129        #[cfg(target_arch = "wasm32")]
3130        {
3131            let Self {
3132                wasm_decoder,
3133                wasm_queue,
3134                wasm_next_sample,
3135                wasm_preroll_target_us,
3136                wasm_eos,
3137                wasm_last_error,
3138                pool,
3139                demuxer,
3140                ..
3141            } = self;
3142            wasm_decoder.flush();
3143            let _: usize = wasm_queue.drain_stale_generations(next_gen, pool);
3144            *wasm_next_sample = keyframe_idx;
3145            *wasm_preroll_target_us = clamped_target;
3146            *wasm_eos = keyframe_idx >= demuxer.video_sample_count();
3147            *wasm_last_error = None;
3148        }
3149        next_gen
3150    }
3151
3152    /// Waits on native targets (or pumps on wasm32) until at least `min_frames` frames of the active generation are queued or EOS/timeout occurs.
3153    ///
3154    /// # Arguments
3155    ///
3156    /// - `&Self` - Mutable pipeline.
3157    /// - `usize` - Minimum queued frames desired.
3158    /// - `u64` - Maximum wait timeout in milliseconds.
3159    ///
3160    /// # Returns
3161    ///
3162    /// - `usize` - Number of queued frames currently ready.
3163    pub fn wait_until_queued(&mut self, min_frames: usize, timeout_ms: u64) -> usize {
3164        #[cfg(not(target_arch = "wasm32"))]
3165        {
3166            let Self {
3167                worker_shared,
3168                active_generation,
3169                ..
3170            } = self;
3171            let active_gen: u64 = *active_generation;
3172            let deadline: Instant = Instant::now() + Duration::from_millis(timeout_ms);
3173            let mut guard: MutexGuard<'_, VideoWorkerShared> =
3174                worker_shared.0.lock().unwrap_or_else(
3175                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3176                );
3177            while (guard.get_queue().len() < min_frames || {
3178                let VideoWorkerShared { pending_seek, .. } = &*guard;
3179                pending_seek.is_some()
3180            }) && !guard.get_reached_eos()
3181                && guard.get_active_generation() == active_gen
3182            {
3183                let now: Instant = Instant::now();
3184                if now >= deadline {
3185                    break;
3186                }
3187                let rem: Duration = deadline.saturating_duration_since(now);
3188                guard = worker_shared
3189                    .1
3190                    .wait_timeout(guard, rem)
3191                    .unwrap_or_else(|err: PoisonError<(MutexGuard<'_, VideoWorkerShared>, _)>| {
3192                        err.into_inner()
3193                    })
3194                    .0;
3195            }
3196            guard.get_queue().len()
3197        }
3198        #[cfg(target_arch = "wasm32")]
3199        {
3200            let _: u64 = timeout_ms;
3201            let mut iterations: usize = 0;
3202            while self.queued_frame_count() < min_frames && !self.reached_eos() && iterations < 512
3203            {
3204                let _: bool = self.pump_decode_once();
3205                iterations += 1;
3206            }
3207            self.queued_frame_count()
3208        }
3209    }
3210
3211    /// Synchronously pumps one decode step on WebAssembly targets (returns `false` on native where the background thread runs continuously).
3212    ///
3213    /// # Arguments
3214    ///
3215    /// - `&Self` - Mutable pipeline.
3216    ///
3217    /// # Returns
3218    ///
3219    /// - `bool` - `true` if a packet was decoded on this pump call.
3220    pub fn pump_decode_once(&mut self) -> bool {
3221        #[cfg(not(target_arch = "wasm32"))]
3222        {
3223            false
3224        }
3225        #[cfg(target_arch = "wasm32")]
3226        {
3227            let Self {
3228                demuxer,
3229                pool,
3230                active_generation,
3231                wasm_decoder,
3232                wasm_queue,
3233                wasm_next_sample,
3234                wasm_preroll_target_us,
3235                wasm_eos,
3236                wasm_packets_decoded,
3237                wasm_preroll_discarded,
3238                wasm_last_error,
3239                ..
3240            } = self;
3241            let total: usize = demuxer.video_sample_count();
3242            if *wasm_eos || wasm_queue.is_full() || *wasm_next_sample >= total {
3243                if *wasm_next_sample >= total {
3244                    *wasm_eos = true;
3245                }
3246                return false;
3247            }
3248            let sample_idx: usize = *wasm_next_sample;
3249            *wasm_next_sample = sample_idx.saturating_add(1);
3250            let Some(packet) = demuxer.read_video_packet(sample_idx, *active_generation) else {
3251                *wasm_eos = true;
3252                return false;
3253            };
3254            match wasm_decoder.decode_packet(&packet, pool) {
3255                Ok(Some(frame)) => {
3256                    *wasm_packets_decoded = wasm_packets_decoded.saturating_add(1);
3257                    if frame.get_pts_us() < *wasm_preroll_target_us && sample_idx + 1 < total {
3258                        pool.recycle_decoded_frame(frame);
3259                        *wasm_preroll_discarded = wasm_preroll_discarded.saturating_add(1);
3260                    } else if let Some(rejected) = wasm_queue.push_ordered(frame) {
3261                        pool.recycle_decoded_frame(rejected);
3262                    }
3263                }
3264                Ok(None) => {}
3265                Err(msg) => {
3266                    *wasm_last_error = Some(msg);
3267                    *wasm_eos = true;
3268                }
3269            }
3270            if sample_idx + 1 >= total {
3271                *wasm_eos = true;
3272            }
3273            true
3274        }
3275    }
3276
3277    /// Evaluates one display VSync tick against the A/V sync scheduler, moving a due frame into `current_frame()` with zero pixel copies and recycling the previous CPU frame.
3278    ///
3279    /// # Arguments
3280    ///
3281    /// - `&Self` - Mutable pipeline.
3282    /// - `Option<i64>` - Optional hardware audio master timestamp in microseconds (`None` uses monotonic `vsync_dt_us`).
3283    /// - `u64` - Elapsed display VSync interval in microseconds (`e.g. 6_944` at 144Hz or `16_667` at 60Hz).
3284    ///
3285    /// # Returns
3286    ///
3287    /// - `VideoPresentOutcome` - Whether a new frame replaced `current_frame()`, held current frame, buffered, or ended.
3288    pub fn present_vsync(
3289        &mut self,
3290        audio_master_pts_us: Option<i64>,
3291        vsync_dt_us: u64,
3292    ) -> VideoPresentOutcome {
3293        if self.playback_state() != PlaybackState::Playing {
3294            return VideoPresentOutcome::HoldCurrentFrame;
3295        }
3296        if let Some(audio_us) = audio_master_pts_us {
3297            self.scheduler_mut().update_audio_clock_us(audio_us);
3298        } else {
3299            self.scheduler_mut().advance_monotonic_us(vsync_dt_us);
3300        }
3301        let has_displayed: bool = self.current_frame().is_some();
3302        #[cfg(not(target_arch = "wasm32"))]
3303        let decision: VideoPresentDecision = {
3304            let Self {
3305                worker_shared,
3306                scheduler,
3307                pool,
3308                active_generation,
3309                ..
3310            } = self;
3311            let active_gen: u64 = *active_generation;
3312            let mut guard: MutexGuard<'_, VideoWorkerShared> =
3313                worker_shared.0.lock().unwrap_or_else(
3314                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3315                );
3316            let _: usize = guard
3317                .get_mut_queue()
3318                .drain_stale_generations(active_gen, pool);
3319            let pending_seek_active: bool = {
3320                let VideoWorkerShared { pending_seek, .. } = &*guard;
3321                pending_seek.is_some()
3322            };
3323            let eos: bool = !pending_seek_active && guard.get_reached_eos();
3324            let res: VideoPresentDecision =
3325                scheduler.select_frame_for_vsync(guard.get_mut_queue(), pool, eos, has_displayed);
3326            worker_shared.1.notify_all();
3327            res
3328        };
3329        #[cfg(target_arch = "wasm32")]
3330        let decision: VideoPresentDecision = {
3331            let Self {
3332                wasm_queue,
3333                wasm_eos,
3334                scheduler,
3335                pool,
3336                active_generation,
3337                ..
3338            } = self;
3339            let _: usize = wasm_queue.drain_stale_generations(*active_generation, pool);
3340            scheduler.select_frame_for_vsync(wasm_queue, pool, *wasm_eos, has_displayed)
3341        };
3342        match decision {
3343            VideoPresentDecision::PresentNewFrame(next_frame) => {
3344                let pts_us: i64 = next_frame.get_pts_us();
3345                let sample_index: usize = next_frame.get_sample_index();
3346                let generation: u64 = next_frame.get_generation();
3347                let zero_copy_gpu: bool = next_frame.gpu_surface().is_some();
3348                let Self {
3349                    current_frame,
3350                    pool,
3351                    ..
3352                } = self;
3353                if let Some(previous) = current_frame.replace(next_frame) {
3354                    pool.recycle_decoded_frame(previous);
3355                }
3356                VideoPresentOutcome::Presented {
3357                    pts_us,
3358                    sample_index,
3359                    generation,
3360                    zero_copy_gpu,
3361                }
3362            }
3363            VideoPresentDecision::HoldCurrentFrame => VideoPresentOutcome::HoldCurrentFrame,
3364            VideoPresentDecision::Buffering => VideoPresentOutcome::Buffering,
3365            VideoPresentDecision::Ended => {
3366                let Self { state, .. } = self;
3367                *state = PlaybackState::Ended;
3368                VideoPresentOutcome::Ended
3369            }
3370        }
3371    }
3372
3373    /// Returns the number of decoded frames currently buffered in the PTS queue.
3374    ///
3375    /// # Arguments
3376    ///
3377    /// - `&Self` - Pipeline reference.
3378    ///
3379    /// # Returns
3380    ///
3381    /// - `usize` - Queued frame count.
3382    #[must_use]
3383    pub fn queued_frame_count(&self) -> usize {
3384        #[cfg(not(target_arch = "wasm32"))]
3385        {
3386            let Self { worker_shared, .. } = self;
3387            let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3388                |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3389            );
3390            guard.get_queue().len()
3391        }
3392        #[cfg(target_arch = "wasm32")]
3393        {
3394            let Self { wasm_queue, .. } = self;
3395            wasm_queue.len()
3396        }
3397    }
3398
3399    /// Returns `true` when the decoder worker has reached end-of-stream for the active generation.
3400    ///
3401    /// # Arguments
3402    ///
3403    /// - `&Self` - Pipeline reference.
3404    ///
3405    /// # Returns
3406    ///
3407    /// - `bool` - `true` when end-of-stream has been reached.
3408    #[must_use]
3409    pub fn reached_eos(&self) -> bool {
3410        #[cfg(not(target_arch = "wasm32"))]
3411        {
3412            let Self { worker_shared, .. } = self;
3413            let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3414                |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3415            );
3416            guard.get_reached_eos()
3417        }
3418        #[cfg(target_arch = "wasm32")]
3419        {
3420            let Self { wasm_eos, .. } = self;
3421            *wasm_eos
3422        }
3423    }
3424
3425    /// Returns total packets decoded by the pipeline worker across playback and seeks.
3426    ///
3427    /// # Arguments
3428    ///
3429    /// - `&Self` - Pipeline reference.
3430    ///
3431    /// # Returns
3432    ///
3433    /// - `u64` - Total packets decoded.
3434    #[must_use]
3435    pub fn packets_decoded(&self) -> u64 {
3436        #[cfg(not(target_arch = "wasm32"))]
3437        {
3438            let Self { worker_shared, .. } = self;
3439            let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3440                |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3441            );
3442            guard.get_packets_decoded()
3443        }
3444        #[cfg(target_arch = "wasm32")]
3445        {
3446            let Self {
3447                wasm_packets_decoded,
3448                ..
3449            } = self;
3450            *wasm_packets_decoded
3451        }
3452    }
3453
3454    /// Returns total preroll frames decoded and discarded while advancing from a keyframe to a seek target PTS.
3455    ///
3456    /// # Arguments
3457    ///
3458    /// - `&Self` - Pipeline reference.
3459    ///
3460    /// # Returns
3461    ///
3462    /// - `u64` - Preroll frames discarded during seek catch-up.
3463    #[must_use]
3464    pub fn seek_preroll_frames_discarded(&self) -> u64 {
3465        #[cfg(not(target_arch = "wasm32"))]
3466        {
3467            let Self { worker_shared, .. } = self;
3468            let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3469                |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3470            );
3471            guard.get_seek_preroll_frames_discarded()
3472        }
3473        #[cfg(target_arch = "wasm32")]
3474        {
3475            let Self {
3476                wasm_preroll_discarded,
3477                ..
3478            } = self;
3479            *wasm_preroll_discarded
3480        }
3481    }
3482
3483    /// Returns the last worker decode error, if any occurred.
3484    ///
3485    /// # Arguments
3486    ///
3487    /// - `&Self` - Pipeline reference.
3488    ///
3489    /// # Returns
3490    ///
3491    /// - `Option<String>` - Error message when present.
3492    #[must_use]
3493    pub fn last_error(&self) -> Option<String> {
3494        #[cfg(not(target_arch = "wasm32"))]
3495        {
3496            let Self { worker_shared, .. } = self;
3497            let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3498                |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3499            );
3500            let VideoWorkerShared { last_error, .. } = &*guard;
3501            last_error.clone()
3502        }
3503        #[cfg(target_arch = "wasm32")]
3504        {
3505            let Self {
3506                wasm_last_error, ..
3507            } = self;
3508            wasm_last_error.clone()
3509        }
3510    }
3511}
3512
3513/// Clean shutdown and background thread join on `Drop` for `VideoPlaybackPipeline`.
3514impl Drop for VideoPlaybackPipeline {
3515    /// Signals the background decode worker to exit, recycles buffered CPU frames, and joins the worker thread cleanly.
3516    ///
3517    /// # Arguments
3518    ///
3519    /// - `&Self` - Mutable pipeline being dropped.
3520    fn drop(&mut self) {
3521        #[cfg(not(target_arch = "wasm32"))]
3522        {
3523            let Self {
3524                worker_shared,
3525                worker_handle,
3526                current_frame,
3527                pool,
3528                ..
3529            } = self;
3530            {
3531                let mut guard: MutexGuard<'_, VideoWorkerShared> =
3532                    worker_shared.0.lock().unwrap_or_else(
3533                        |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3534                    );
3535                guard.set_shutdown(true);
3536                guard.get_mut_queue().clear_and_recycle(pool);
3537                worker_shared.1.notify_all();
3538            }
3539            if let Some(handle) = worker_handle.take() {
3540                let _: Result<(), Box<dyn Any + Send>> = handle.join();
3541            }
3542            if let Some(frame) = current_frame.take() {
3543                pool.recycle_decoded_frame(frame);
3544            }
3545        }
3546        #[cfg(target_arch = "wasm32")]
3547        {
3548            let Self {
3549                wasm_queue,
3550                current_frame,
3551                pool,
3552                ..
3553            } = self;
3554            wasm_queue.clear_and_recycle(pool);
3555            if let Some(frame) = current_frame.take() {
3556                pool.recycle_decoded_frame(frame);
3557            }
3558        }
3559    }
3560}