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    /// - `B` - Complete MP4 container bytes convertible into shared `Arc<[u8]>`.
508    ///
509    /// # Returns
510    ///
511    /// - `Result<Self, String>` - Parsed demuxer with indexed video/audio sample tables or descriptive error.
512    pub fn parse<B>(bytes: B) -> Result<Self, String>
513    where
514        B: Into<Arc<[u8]>>,
515    {
516        let shared_bytes: Arc<[u8]> = bytes.into();
517        let raw: &[u8] = shared_bytes.as_ref();
518        if raw.is_empty() {
519            return Err(VIDEO_ERR_MP4_EMPTY.to_string());
520        }
521        let mut major_brand: String = VIDEO_DEFAULT_BRAND_STR.to_string();
522        let mut compatible_brands: Vec<String> = Vec::new();
523        let mut movie_timescale: u32 = 1_000;
524        let mut movie_duration_us: u64 = 0;
525        let mut video_track: Option<Mp4TrackInfo> = None;
526        let mut audio_track: Option<Mp4TrackInfo> = None;
527        let mut found_moov: bool = false;
528        let mut cursor: usize = 0;
529        while cursor < raw.len() {
530            let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
531                Self::read_box_header(raw, cursor, raw.len())?;
532            if box_type == MP4_BOX_FTYP {
533                Self::parse_ftyp(
534                    &raw[payload_start..box_end],
535                    &mut major_brand,
536                    &mut compatible_brands,
537                );
538            } else if box_type == MP4_BOX_MOOV {
539                found_moov = true;
540                Self::parse_moov(
541                    raw,
542                    payload_start,
543                    box_end,
544                    &mut movie_timescale,
545                    &mut movie_duration_us,
546                    &mut video_track,
547                    &mut audio_track,
548                )?;
549            }
550            cursor = box_end;
551        }
552        if !found_moov {
553            return Err(VIDEO_ERR_MP4_NO_MOOV.to_string());
554        }
555        let resolved_video: Mp4TrackInfo =
556            video_track.ok_or_else(|| VIDEO_ERR_MP4_NO_VIDEO_TRACK.to_string())?;
557        for sample in resolved_video.get_samples().iter() {
558            let end_offset: u64 = sample
559                .get_byte_offset()
560                .saturating_add(sample.get_byte_size() as u64);
561            if end_offset > (raw.len() as u64) {
562                return Err(VIDEO_ERR_MP4_SAMPLE_BOUNDS.to_string());
563            }
564        }
565        if movie_duration_us == 0 {
566            movie_duration_us = resolved_video.get_duration_us();
567        }
568        Ok(Self {
569            bytes: shared_bytes,
570            major_brand,
571            compatible_brands,
572            movie_timescale,
573            movie_duration_us,
574            video_track: resolved_video,
575            audio_track,
576        })
577    }
578
579    /// Returns a borrowed slice over the backing MP4 container bytes.
580    ///
581    /// # Arguments
582    ///
583    /// - `&Self` - Demuxer reference.
584    ///
585    /// # Returns
586    ///
587    /// - `&[u8]` - Backing MP4 byte slice.
588    #[must_use]
589    pub fn get_bytes(&self) -> &[u8] {
590        self.bytes.as_ref()
591    }
592
593    /// Returns a borrowed reference to the shared `Arc<[u8]>` backing MP4 container bytes.
594    ///
595    /// # Arguments
596    ///
597    /// - `&Self` - Demuxer reference.
598    ///
599    /// # Returns
600    ///
601    /// - `&Arc<[u8]>` - Shared atomic container byte storage.
602    #[must_use]
603    pub fn bytes_arc(&self) -> &Arc<[u8]> {
604        let Self { bytes, .. } = self;
605        bytes
606    }
607
608    /// Returns the optional parsed audio track descriptor.
609    ///
610    /// # Arguments
611    ///
612    /// - `&Self` - Demuxer reference.
613    ///
614    /// # Returns
615    ///
616    /// - `Option<&Mp4TrackInfo>` - Audio track reference when present.
617    #[must_use]
618    pub fn audio_track(&self) -> Option<&Mp4TrackInfo> {
619        let Self { audio_track, .. } = self;
620        audio_track.as_ref()
621    }
622
623    /// Returns the total number of indexed video samples in decode order.
624    ///
625    /// # Arguments
626    ///
627    /// - `&Self` - Demuxer reference.
628    ///
629    /// # Returns
630    ///
631    /// - `usize` - Number of video samples.
632    #[must_use]
633    pub fn video_sample_count(&self) -> usize {
634        self.get_video_track().get_samples().len()
635    }
636
637    /// Builds a `VideoDecoderConfig` describing the primary video track's codec, resolution, and color/HDR metadata.
638    ///
639    /// # Arguments
640    ///
641    /// - `&Self` - Demuxer reference.
642    ///
643    /// # Returns
644    ///
645    /// - `VideoDecoderConfig` - Decoder configuration descriptor.
646    #[must_use]
647    pub fn video_decoder_config(&self) -> VideoDecoderConfig {
648        let track: &Mp4TrackInfo = self.get_video_track();
649        VideoDecoderConfig::new(
650            track.get_video_codec(),
651            track.get_width(),
652            track.get_height(),
653            track.get_color_info(),
654        )
655    }
656
657    /// Borrows the sample metadata and zero-copy encoded byte slice for `sample_index`.
658    ///
659    /// # Arguments
660    ///
661    /// - `&Self` - Demuxer reference.
662    /// - `usize` - Zero-based decode-order video sample index.
663    ///
664    /// # Returns
665    ///
666    /// - `Option<(&Mp4Sample, &[u8])>` - Sample metadata and borrowed byte slice if in bounds.
667    #[must_use]
668    pub fn read_video_sample_slice(&self, sample_index: usize) -> Option<(&Mp4Sample, &[u8])> {
669        let sample: &Mp4Sample = self.get_video_track().get_samples().get(sample_index)?;
670        let start: usize = usize::try_from(sample.get_byte_offset()).ok()?;
671        let len: usize = sample.get_byte_size() as usize;
672        let end: usize = start.checked_add(len)?;
673        let slice: &[u8] = self.get_bytes().get(start..end)?;
674        Some((sample, slice))
675    }
676
677    /// Reads a zero-copy `EncodedVideoPacket` referencing `sample_index`'s byte range inside the shared MP4 buffer.
678    ///
679    /// # Arguments
680    ///
681    /// - `&Self` - Demuxer reference.
682    /// - `usize` - Zero-based decode-order video sample index.
683    /// - `u64` - Active seek generation tag.
684    ///
685    /// # Returns
686    ///
687    /// - `Option<EncodedVideoPacket>` - Zero-copy packet view or `None` if `sample_index` is out of range.
688    #[must_use]
689    pub fn read_video_packet(
690        &self,
691        sample_index: usize,
692        generation: u64,
693    ) -> Option<EncodedVideoPacket> {
694        let sample: &Mp4Sample = self.get_video_track().get_samples().get(sample_index)?;
695        let start: usize = usize::try_from(sample.get_byte_offset()).ok()?;
696        let len: usize = sample.get_byte_size() as usize;
697        let end: usize = start.checked_add(len)?;
698        if end > self.get_bytes().len() {
699            return None;
700        }
701        Some(EncodedVideoPacket::from_shared_range(
702            sample,
703            generation,
704            Arc::clone(self.bytes_arc()),
705            start,
706            end,
707        ))
708    }
709
710    /// Finds the decode-order index of the closest preceding keyframe whose `pts_us <= target_pts_us`.
711    ///
712    /// # Arguments
713    ///
714    /// - `&Self` - Demuxer reference.
715    /// - `i64` - Target presentation timestamp in microseconds.
716    ///
717    /// # Returns
718    ///
719    /// - `usize` - Decode-order keyframe index (`0` if target precedes all keyframes).
720    #[must_use]
721    pub fn seek_keyframe_index(&self, target_pts_us: i64) -> usize {
722        let samples: &[Mp4Sample] = self.get_video_track().get_samples().as_slice();
723        let mut best_keyframe: usize = 0;
724        let mut best_pts: i64 = i64::MIN;
725        for sample in samples.iter() {
726            if sample.get_is_keyframe()
727                && sample.get_pts_us() <= target_pts_us
728                && sample.get_pts_us() >= best_pts
729            {
730                best_pts = sample.get_pts_us();
731                best_keyframe = sample.get_index();
732            }
733        }
734        best_keyframe
735    }
736
737    /// Reads an ISOBMFF box header supporting 32-bit sizes, 64-bit extended sizes (`size == 1`), and to-EOF (`size == 0`).
738    ///
739    /// # Arguments
740    ///
741    /// - `&[u8]` - Container byte slice.
742    /// - `usize` - Starting byte offset.
743    /// - `usize` - Exclusive upper bound within container.
744    ///
745    /// # Returns
746    ///
747    /// - `Result<([u8; 4], usize, usize), String>` - `(box_type, payload_start, box_end)` tuple.
748    fn read_box_header(
749        bytes: &[u8],
750        start: usize,
751        limit: usize,
752    ) -> Result<([u8; 4], usize, usize), String> {
753        if start.saturating_add(8) > limit {
754            return Err(VIDEO_ERR_MP4_TRUNCATED_BOX.to_string());
755        }
756        let size32: u32 = u32::from_be_bytes([
757            bytes[start],
758            bytes[start + 1],
759            bytes[start + 2],
760            bytes[start + 3],
761        ]);
762        let box_type: [u8; 4] = [
763            bytes[start + 4],
764            bytes[start + 5],
765            bytes[start + 6],
766            bytes[start + 7],
767        ];
768        if size32 == 0 {
769            return Ok((box_type, start + 8, limit));
770        }
771        if size32 == 1 {
772            if start.saturating_add(16) > limit {
773                return Err(VIDEO_ERR_MP4_TRUNCATED_BOX.to_string());
774            }
775            let size64: u64 = u64::from_be_bytes([
776                bytes[start + 8],
777                bytes[start + 9],
778                bytes[start + 10],
779                bytes[start + 11],
780                bytes[start + 12],
781                bytes[start + 13],
782                bytes[start + 14],
783                bytes[start + 15],
784            ]);
785            let total: usize =
786                usize::try_from(size64).map_err(|_| VIDEO_ERR_MP4_TRUNCATED_BOX.to_string())?;
787            if total < 16 || start.saturating_add(total) > limit {
788                return Err(VIDEO_ERR_MP4_TRUNCATED_BOX.to_string());
789            }
790            return Ok((box_type, start + 16, start + total));
791        }
792        let total: usize = size32 as usize;
793        if total < 8 || start.saturating_add(total) > limit {
794            return Err(VIDEO_ERR_MP4_TRUNCATED_BOX.to_string());
795        }
796        Ok((box_type, start + 8, start + total))
797    }
798
799    /// Parses an `ftyp` payload into major brand and compatible brand strings.
800    ///
801    /// # Arguments
802    ///
803    /// - `&[u8]` - `ftyp` payload bytes.
804    /// - `&mut String` - Destination major brand string.
805    /// - `&mut Vec<String>` - Destination compatible brands list.
806    fn parse_ftyp(payload: &[u8], major_brand: &mut String, compatible_brands: &mut Vec<String>) {
807        if payload.len() >= 4 {
808            *major_brand = Self::fourcc_to_string(&payload[0..4]);
809        }
810        let mut offset: usize = 8;
811        while offset.saturating_add(4) <= payload.len() {
812            compatible_brands.push(Self::fourcc_to_string(&payload[offset..offset + 4]));
813            offset += 4;
814        }
815    }
816
817    /// Converts a 4-byte FourCC slice into an ASCII string.
818    ///
819    /// # Arguments
820    ///
821    /// - `&[u8]` - 4-byte FourCC slice.
822    ///
823    /// # Returns
824    ///
825    /// - `String` - UTF-8 FourCC label.
826    fn fourcc_to_string(slice: &[u8]) -> String {
827        from_utf8(slice)
828            .map(|s: &str| s.to_string())
829            .unwrap_or_else(|_| VIDEO_DEFAULT_BRAND_STR.to_string())
830    }
831
832    /// Parses a `moov` container box extracting `mvhd` and all child `trak` boxes.
833    ///
834    /// # Arguments
835    ///
836    /// - `&[u8]` - Full container bytes.
837    /// - `usize` - Payload start offset.
838    /// - `usize` - Payload exclusive end offset.
839    /// - `&mut u32` - Movie timescale output.
840    /// - `&mut u64` - Movie duration in microseconds output.
841    /// - `&mut Option<Mp4TrackInfo>` - Primary video track output.
842    /// - `&mut Option<Mp4TrackInfo>` - Primary audio track output.
843    ///
844    /// # Returns
845    ///
846    /// - `Result<(), String>` - `Ok(())` on success or parse error.
847    fn parse_moov(
848        bytes: &[u8],
849        start: usize,
850        end: usize,
851        movie_timescale: &mut u32,
852        movie_duration_us: &mut u64,
853        video_track: &mut Option<Mp4TrackInfo>,
854        audio_track: &mut Option<Mp4TrackInfo>,
855    ) -> Result<(), String> {
856        let mut cursor: usize = start;
857        while cursor < end {
858            let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
859                Self::read_box_header(bytes, cursor, end)?;
860            if box_type == MP4_BOX_MVHD {
861                Self::parse_mvhd(
862                    &bytes[payload_start..box_end],
863                    movie_timescale,
864                    movie_duration_us,
865                );
866            } else if box_type == MP4_BOX_TRAK
867                && let Some(track) = Self::parse_trak(bytes, payload_start, box_end)?
868            {
869                if track.get_is_video() && video_track.is_none() {
870                    *video_track = Some(track);
871                } else if !track.get_is_video() && audio_track.is_none() {
872                    *audio_track = Some(track);
873                }
874            }
875            cursor = box_end;
876        }
877        Ok(())
878    }
879
880    /// Parses a version 0 or version 1 `mvhd` box for movie timescale and duration.
881    ///
882    /// # Arguments
883    ///
884    /// - `&[u8]` - `mvhd` payload bytes.
885    /// - `&mut u32` - Destination movie timescale.
886    /// - `&mut u64` - Destination movie duration in microseconds.
887    fn parse_mvhd(payload: &[u8], timescale_out: &mut u32, duration_us_out: &mut u64) {
888        if payload.len() < 4 {
889            return;
890        }
891        let version: u8 = payload[0];
892        if version == 0 && payload.len() >= 20 {
893            let scale: u32 =
894                u32::from_be_bytes([payload[12], payload[13], payload[14], payload[15]]);
895            let dur: u32 = u32::from_be_bytes([payload[16], payload[17], payload[18], payload[19]]);
896            if scale > 0 {
897                *timescale_out = scale;
898                *duration_us_out = Self::ticks_to_us(dur as u64, scale);
899            }
900        } else if version == 1 && payload.len() >= 32 {
901            let scale: u32 =
902                u32::from_be_bytes([payload[20], payload[21], payload[22], payload[23]]);
903            let dur: u64 = u64::from_be_bytes([
904                payload[24],
905                payload[25],
906                payload[26],
907                payload[27],
908                payload[28],
909                payload[29],
910                payload[30],
911                payload[31],
912            ]);
913            if scale > 0 {
914                *timescale_out = scale;
915                *duration_us_out = Self::ticks_to_us(dur, scale);
916            }
917        }
918    }
919
920    /// Parses a `trak` container box (`tkhd` + `mdia`) into an `Mp4TrackInfo` when `vide` or `soun`.
921    ///
922    /// # Arguments
923    ///
924    /// - `&[u8]` - Full container bytes.
925    /// - `usize` - Payload start offset.
926    /// - `usize` - Payload exclusive end offset.
927    ///
928    /// # Returns
929    ///
930    /// - `Result<Option<Mp4TrackInfo>, String>` - Parsed track info or `None` for non-media tracks.
931    fn parse_trak(bytes: &[u8], start: usize, end: usize) -> Result<Option<Mp4TrackInfo>, String> {
932        let mut track: Mp4TrackInfo = Mp4TrackInfo::default();
933        let mut handler_tag: [u8; 4] = [0; 4];
934        let mut raw_stbl: Mp4SampleTableRaw = Mp4SampleTableRaw::default();
935        let mut cursor: usize = start;
936        while cursor < end {
937            let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
938                Self::read_box_header(bytes, cursor, end)?;
939            if box_type == MP4_BOX_TKHD {
940                Self::parse_tkhd(&bytes[payload_start..box_end], &mut track);
941            } else if box_type == MP4_BOX_MDIA {
942                Self::parse_mdia(
943                    bytes,
944                    payload_start,
945                    box_end,
946                    &mut track,
947                    &mut handler_tag,
948                    &mut raw_stbl,
949                )?;
950            }
951            cursor = box_end;
952        }
953        if handler_tag != MP4_HANDLER_VIDE && handler_tag != MP4_HANDLER_SOUN {
954            return Ok(None);
955        }
956        track.set_is_video(handler_tag == MP4_HANDLER_VIDE);
957        let timescale: u32 = track.get_timescale().max(1);
958        let samples: Vec<Mp4Sample> = Self::build_samples(&raw_stbl, timescale);
959        if track.get_duration_us() == 0 && !samples.is_empty() {
960            let mut max_end_us: u64 = 0;
961            for sample in samples.iter() {
962                let start_pos: u64 = sample.get_pts_us().max(0) as u64;
963                let end_pos: u64 = start_pos.saturating_add(sample.get_duration_us());
964                if end_pos > max_end_us {
965                    max_end_us = end_pos;
966                }
967            }
968            track.set_duration_us(max_end_us);
969        }
970        track.set_samples(samples);
971        Ok(Some(track))
972    }
973
974    /// Parses a `tkhd` box for `track_id` and 16.16 display width/height.
975    ///
976    /// # Arguments
977    ///
978    /// - `&[u8]` - `tkhd` payload bytes.
979    /// - `&mut Mp4TrackInfo` - Destination track metadata.
980    fn parse_tkhd(payload: &[u8], track: &mut Mp4TrackInfo) {
981        if payload.len() < 4 {
982            return;
983        }
984        let version: u8 = payload[0];
985        if version == 0 && payload.len() >= 84 {
986            let id: u32 = u32::from_be_bytes([payload[12], payload[13], payload[14], payload[15]]);
987            let width_fixed: u32 =
988                u32::from_be_bytes([payload[76], payload[77], payload[78], payload[79]]);
989            let height_fixed: u32 =
990                u32::from_be_bytes([payload[80], payload[81], payload[82], payload[83]]);
991            track.set_track_id(id);
992            if track.get_width() == 0 {
993                track.set_width(width_fixed >> 16);
994            }
995            if track.get_height() == 0 {
996                track.set_height(height_fixed >> 16);
997            }
998        } else if version == 1 && payload.len() >= 96 {
999            let id: u32 = u32::from_be_bytes([payload[20], payload[21], payload[22], payload[23]]);
1000            let width_fixed: u32 =
1001                u32::from_be_bytes([payload[88], payload[89], payload[90], payload[91]]);
1002            let height_fixed: u32 =
1003                u32::from_be_bytes([payload[92], payload[93], payload[94], payload[95]]);
1004            track.set_track_id(id);
1005            if track.get_width() == 0 {
1006                track.set_width(width_fixed >> 16);
1007            }
1008            if track.get_height() == 0 {
1009                track.set_height(height_fixed >> 16);
1010            }
1011        }
1012    }
1013
1014    /// Parses an `mdia` container box (`mdhd`, `hdlr`, `minf`).
1015    ///
1016    /// # Arguments
1017    ///
1018    /// - `&[u8]` - Full container bytes.
1019    /// - `usize` - Payload start offset.
1020    /// - `usize` - Payload exclusive end offset.
1021    /// - `&mut Mp4TrackInfo` - Destination track metadata.
1022    /// - `&mut [u8; 4]` - Destination handler type tag (`vide` / `soun`).
1023    /// - `&mut Mp4SampleTableRaw` - Destination sample table accumulator.
1024    ///
1025    /// # Returns
1026    ///
1027    /// - `Result<(), String>` - `Ok(())` on success or parse error.
1028    fn parse_mdia(
1029        bytes: &[u8],
1030        start: usize,
1031        end: usize,
1032        track: &mut Mp4TrackInfo,
1033        handler_tag: &mut [u8; 4],
1034        raw_stbl: &mut Mp4SampleTableRaw,
1035    ) -> Result<(), String> {
1036        let mut cursor: usize = start;
1037        while cursor < end {
1038            let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
1039                Self::read_box_header(bytes, cursor, end)?;
1040            if box_type == MP4_BOX_MDHD {
1041                Self::parse_mdhd(&bytes[payload_start..box_end], track);
1042            } else if box_type == MP4_BOX_HDLR {
1043                let payload: &[u8] = &bytes[payload_start..box_end];
1044                if payload.len() >= 12 {
1045                    *handler_tag = [payload[8], payload[9], payload[10], payload[11]];
1046                }
1047            } else if box_type == MP4_BOX_MINF {
1048                Self::parse_minf(bytes, payload_start, box_end, track, raw_stbl)?;
1049            }
1050            cursor = box_end;
1051        }
1052        Ok(())
1053    }
1054
1055    /// Parses an `mdhd` box for media timescale and track duration.
1056    ///
1057    /// # Arguments
1058    ///
1059    /// - `&[u8]` - `mdhd` payload bytes.
1060    /// - `&mut Mp4TrackInfo` - Destination track metadata.
1061    fn parse_mdhd(payload: &[u8], track: &mut Mp4TrackInfo) {
1062        if payload.len() < 4 {
1063            return;
1064        }
1065        let version: u8 = payload[0];
1066        if version == 0 && payload.len() >= 20 {
1067            let scale: u32 =
1068                u32::from_be_bytes([payload[12], payload[13], payload[14], payload[15]]);
1069            let dur: u32 = u32::from_be_bytes([payload[16], payload[17], payload[18], payload[19]]);
1070            if scale > 0 {
1071                track.set_timescale(scale);
1072                track.set_duration_us(Self::ticks_to_us(dur as u64, scale));
1073            }
1074        } else if version == 1 && payload.len() >= 32 {
1075            let scale: u32 =
1076                u32::from_be_bytes([payload[20], payload[21], payload[22], payload[23]]);
1077            let dur: u64 = u64::from_be_bytes([
1078                payload[24],
1079                payload[25],
1080                payload[26],
1081                payload[27],
1082                payload[28],
1083                payload[29],
1084                payload[30],
1085                payload[31],
1086            ]);
1087            if scale > 0 {
1088                track.set_timescale(scale);
1089                track.set_duration_us(Self::ticks_to_us(dur, scale));
1090            }
1091        }
1092    }
1093
1094    /// Parses a `minf` box to locate and decode its `stbl` sample table.
1095    ///
1096    /// # Arguments
1097    ///
1098    /// - `&[u8]` - Full container bytes.
1099    /// - `usize` - Payload start offset.
1100    /// - `usize` - Payload exclusive end offset.
1101    /// - `&mut Mp4TrackInfo` - Destination track metadata.
1102    /// - `&mut Mp4SampleTableRaw` - Destination sample table accumulator.
1103    ///
1104    /// # Returns
1105    ///
1106    /// - `Result<(), String>` - `Ok(())` on success or parse error.
1107    fn parse_minf(
1108        bytes: &[u8],
1109        start: usize,
1110        end: usize,
1111        track: &mut Mp4TrackInfo,
1112        raw_stbl: &mut Mp4SampleTableRaw,
1113    ) -> Result<(), String> {
1114        let mut cursor: usize = start;
1115        while cursor < end {
1116            let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
1117                Self::read_box_header(bytes, cursor, end)?;
1118            if box_type == MP4_BOX_STBL {
1119                Self::parse_stbl(bytes, payload_start, box_end, track, raw_stbl)?;
1120            }
1121            cursor = box_end;
1122        }
1123        Ok(())
1124    }
1125
1126    /// Parses an `stbl` box (`stsd`, `stts`, `ctts`, `stss`, `stsc`, `stsz`, `stco`, `co64`).
1127    ///
1128    /// # Arguments
1129    ///
1130    /// - `&[u8]` - Full container bytes.
1131    /// - `usize` - Payload start offset.
1132    /// - `usize` - Payload exclusive end offset.
1133    /// - `&mut Mp4TrackInfo` - Destination track metadata.
1134    /// - `&mut Mp4SampleTableRaw` - Destination sample table accumulator.
1135    ///
1136    /// # Returns
1137    ///
1138    /// - `Result<(), String>` - `Ok(())` on success or parse error.
1139    fn parse_stbl(
1140        bytes: &[u8],
1141        start: usize,
1142        end: usize,
1143        track: &mut Mp4TrackInfo,
1144        raw_stbl: &mut Mp4SampleTableRaw,
1145    ) -> Result<(), String> {
1146        let mut cursor: usize = start;
1147        while cursor < end {
1148            let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
1149                Self::read_box_header(bytes, cursor, end)?;
1150            let payload: &[u8] = &bytes[payload_start..box_end];
1151            if box_type == MP4_BOX_STSD {
1152                Self::parse_stsd(bytes, payload_start, box_end, track)?;
1153            } else if box_type == MP4_BOX_STTS {
1154                Self::parse_stts(payload, raw_stbl);
1155            } else if box_type == MP4_BOX_CTTS {
1156                Self::parse_ctts(payload, raw_stbl);
1157            } else if box_type == MP4_BOX_STSS {
1158                Self::parse_stss(payload, raw_stbl);
1159            } else if box_type == MP4_BOX_STSC {
1160                Self::parse_stsc(payload, raw_stbl);
1161            } else if box_type == MP4_BOX_STSZ {
1162                Self::parse_stsz(payload, raw_stbl);
1163            } else if box_type == MP4_BOX_STCO {
1164                Self::parse_stco(payload, raw_stbl);
1165            } else if box_type == MP4_BOX_CO64 {
1166                Self::parse_co64(payload, raw_stbl);
1167            }
1168            cursor = box_end;
1169        }
1170        Ok(())
1171    }
1172
1173    /// Parses an `stsd` sample description box including visual codec FourCC, coded dimensions, audio config, and nested `colr` `nclx` box.
1174    ///
1175    /// # Arguments
1176    ///
1177    /// - `&[u8]` - Full container bytes.
1178    /// - `usize` - Payload start offset.
1179    /// - `usize` - Payload exclusive end offset.
1180    /// - `&mut Mp4TrackInfo` - Destination track metadata.
1181    ///
1182    /// # Returns
1183    ///
1184    /// - `Result<(), String>` - `Ok(())` on success or parse error.
1185    fn parse_stsd(
1186        bytes: &[u8],
1187        start: usize,
1188        end: usize,
1189        track: &mut Mp4TrackInfo,
1190    ) -> Result<(), String> {
1191        if start.saturating_add(8) > end {
1192            return Ok(());
1193        }
1194        let entry_count: u32 = u32::from_be_bytes([
1195            bytes[start + 4],
1196            bytes[start + 5],
1197            bytes[start + 6],
1198            bytes[start + 7],
1199        ]);
1200        if entry_count == 0 {
1201            return Ok(());
1202        }
1203        let entry_start: usize = start + 8;
1204        let (codec_tag, entry_payload_start, entry_end): ([u8; 4], usize, usize) =
1205            Self::read_box_header(bytes, entry_start, end)?;
1206        track.set_codec_fourcc(Self::fourcc_to_string(&codec_tag));
1207        let entry_payload: &[u8] = &bytes[entry_payload_start..entry_end];
1208        if codec_tag == MP4_CODEC_AVC1 || codec_tag == MP4_CODEC_AVC3 {
1209            track.set_video_codec(VideoCodec::H264);
1210        } else if codec_tag == MP4_CODEC_HVC1 || codec_tag == MP4_CODEC_HEV1 {
1211            track.set_video_codec(VideoCodec::H265);
1212        } else if codec_tag == MP4_CODEC_VP09 {
1213            track.set_video_codec(VideoCodec::Vp9);
1214        } else if codec_tag == MP4_CODEC_AV01 {
1215            track.set_video_codec(VideoCodec::Av1);
1216        } else if codec_tag == MP4_CODEC_RAWV || codec_tag == MP4_CODEC_RGBA {
1217            track.set_video_codec(VideoCodec::RawFrames);
1218        } else if codec_tag == MP4_CODEC_MP4A {
1219            track.set_audio_codec(AudioCodec::Aac);
1220        } else if codec_tag == MP4_CODEC_OPUS {
1221            track.set_audio_codec(AudioCodec::Opus);
1222        }
1223        let is_audio_codec: bool = codec_tag == MP4_CODEC_MP4A || codec_tag == MP4_CODEC_OPUS;
1224        if is_audio_codec {
1225            if entry_payload.len() >= 28 {
1226                let channels: u16 = u16::from_be_bytes([entry_payload[16], entry_payload[17]]);
1227                let sr_fixed: u32 = u32::from_be_bytes([
1228                    entry_payload[24],
1229                    entry_payload[25],
1230                    entry_payload[26],
1231                    entry_payload[27],
1232                ]);
1233                track.set_channels(channels);
1234                track.set_sample_rate_hz(sr_fixed >> 16);
1235            }
1236            return Ok(());
1237        }
1238        if entry_payload.len() >= 28 {
1239            let coded_w: u16 = u16::from_be_bytes([entry_payload[24], entry_payload[25]]);
1240            let coded_h: u16 = u16::from_be_bytes([entry_payload[26], entry_payload[27]]);
1241            if coded_w > 0 {
1242                track.set_width(coded_w as u32);
1243            }
1244            if coded_h > 0 {
1245                track.set_height(coded_h as u32);
1246            }
1247        }
1248        let mut child_cursor: usize = entry_payload_start.saturating_add(78);
1249        while child_cursor.saturating_add(8) <= entry_end {
1250            let Ok((child_type, child_start, child_end)) =
1251                Self::read_box_header(bytes, child_cursor, entry_end)
1252            else {
1253                break;
1254            };
1255            if child_type == MP4_BOX_COLR {
1256                Self::parse_colr(&bytes[child_start..child_end], track);
1257            }
1258            child_cursor = child_end;
1259        }
1260        Ok(())
1261    }
1262
1263    /// Parses a nested `colr` box supporting `nclx` CICP primaries, transfer, matrix, and full-range flag.
1264    ///
1265    /// # Arguments
1266    ///
1267    /// - `&[u8]` - `colr` payload bytes.
1268    /// - `&mut Mp4TrackInfo` - Destination track metadata.
1269    fn parse_colr(payload: &[u8], track: &mut Mp4TrackInfo) {
1270        if payload.len() >= 11 && payload[0..4] == MP4_BOX_NCLX {
1271            let primaries: u16 = u16::from_be_bytes([payload[4], payload[5]]);
1272            let transfer: u16 = u16::from_be_bytes([payload[6], payload[7]]);
1273            let matrix: u16 = u16::from_be_bytes([payload[8], payload[9]]);
1274            let full_range: bool = (payload[10] & 0x80) != 0;
1275            track.set_color_info(VideoColorInfo::from_nclx(
1276                primaries, transfer, matrix, full_range,
1277            ));
1278        }
1279    }
1280
1281    /// Parses an `stts` decoding time-to-sample table.
1282    ///
1283    /// # Arguments
1284    ///
1285    /// - `&[u8]` - `stts` payload bytes.
1286    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1287    fn parse_stts(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1288        if payload.len() < 8 {
1289            return;
1290        }
1291        let count: usize =
1292            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1293        let max_entries: usize = (payload.len() - 8) / 8;
1294        let entries: usize = count.min(max_entries);
1295        for i in 0..entries {
1296            let off: usize = 8 + i * 8;
1297            let sample_count: u32 = u32::from_be_bytes([
1298                payload[off],
1299                payload[off + 1],
1300                payload[off + 2],
1301                payload[off + 3],
1302            ]);
1303            let sample_delta: u32 = u32::from_be_bytes([
1304                payload[off + 4],
1305                payload[off + 5],
1306                payload[off + 6],
1307                payload[off + 7],
1308            ]);
1309            raw_stbl.get_mut_stts().push((sample_count, sample_delta));
1310        }
1311    }
1312
1313    /// Parses a `ctts` composition time-to-sample table (version 0 unsigned and version 1 signed).
1314    ///
1315    /// # Arguments
1316    ///
1317    /// - `&[u8]` - `ctts` payload bytes.
1318    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1319    fn parse_ctts(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1320        if payload.len() < 8 {
1321            return;
1322        }
1323        let version: u8 = payload[0];
1324        let count: usize =
1325            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1326        let max_entries: usize = (payload.len() - 8) / 8;
1327        let entries: usize = count.min(max_entries);
1328        for i in 0..entries {
1329            let off: usize = 8 + i * 8;
1330            let sample_count: u32 = u32::from_be_bytes([
1331                payload[off],
1332                payload[off + 1],
1333                payload[off + 2],
1334                payload[off + 3],
1335            ]);
1336            let offset_ticks: i32 = if version == 1 {
1337                i32::from_be_bytes([
1338                    payload[off + 4],
1339                    payload[off + 5],
1340                    payload[off + 6],
1341                    payload[off + 7],
1342                ])
1343            } else {
1344                u32::from_be_bytes([
1345                    payload[off + 4],
1346                    payload[off + 5],
1347                    payload[off + 6],
1348                    payload[off + 7],
1349                ]) as i32
1350            };
1351            raw_stbl.get_mut_ctts().push((sample_count, offset_ticks));
1352        }
1353    }
1354
1355    /// Parses an `stss` sync keyframe sample index table.
1356    ///
1357    /// # Arguments
1358    ///
1359    /// - `&[u8]` - `stss` payload bytes.
1360    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1361    fn parse_stss(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1362        if payload.len() < 8 {
1363            return;
1364        }
1365        let count: usize =
1366            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1367        let max_entries: usize = (payload.len() - 8) / 4;
1368        let entries: usize = count.min(max_entries);
1369        for i in 0..entries {
1370            let off: usize = 8 + i * 4;
1371            let sample_num: u32 = u32::from_be_bytes([
1372                payload[off],
1373                payload[off + 1],
1374                payload[off + 2],
1375                payload[off + 3],
1376            ]);
1377            raw_stbl.get_mut_stss().push(sample_num);
1378        }
1379    }
1380
1381    /// Parses an `stsc` sample-to-chunk mapping table.
1382    ///
1383    /// # Arguments
1384    ///
1385    /// - `&[u8]` - `stsc` payload bytes.
1386    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1387    fn parse_stsc(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1388        if payload.len() < 8 {
1389            return;
1390        }
1391        let count: usize =
1392            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1393        let max_entries: usize = (payload.len() - 8) / 12;
1394        let entries: usize = count.min(max_entries);
1395        for i in 0..entries {
1396            let off: usize = 8 + i * 12;
1397            let first_chunk: u32 = u32::from_be_bytes([
1398                payload[off],
1399                payload[off + 1],
1400                payload[off + 2],
1401                payload[off + 3],
1402            ]);
1403            let samples_per_chunk: u32 = u32::from_be_bytes([
1404                payload[off + 4],
1405                payload[off + 5],
1406                payload[off + 6],
1407                payload[off + 7],
1408            ]);
1409            raw_stbl
1410                .get_mut_stsc()
1411                .push((first_chunk, samples_per_chunk));
1412        }
1413    }
1414
1415    /// Parses an `stsz` sample size table.
1416    ///
1417    /// # Arguments
1418    ///
1419    /// - `&[u8]` - `stsz` payload bytes.
1420    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1421    fn parse_stsz(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1422        if payload.len() < 12 {
1423            return;
1424        }
1425        let default_size: u32 =
1426            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]);
1427        let sample_count: u32 =
1428            u32::from_be_bytes([payload[8], payload[9], payload[10], payload[11]]);
1429        raw_stbl.set_default_sample_size(default_size);
1430        raw_stbl.set_sample_count(sample_count);
1431        if default_size == 0 {
1432            let max_entries: usize = (payload.len() - 12) / 4;
1433            let entries: usize = (sample_count as usize).min(max_entries);
1434            for i in 0..entries {
1435                let off: usize = 12 + i * 4;
1436                let size: u32 = u32::from_be_bytes([
1437                    payload[off],
1438                    payload[off + 1],
1439                    payload[off + 2],
1440                    payload[off + 3],
1441                ]);
1442                raw_stbl.get_mut_sample_sizes().push(size);
1443            }
1444        }
1445    }
1446
1447    /// Parses a 32-bit `stco` chunk offset table.
1448    ///
1449    /// # Arguments
1450    ///
1451    /// - `&[u8]` - `stco` payload bytes.
1452    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1453    fn parse_stco(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1454        if payload.len() < 8 {
1455            return;
1456        }
1457        let count: usize =
1458            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1459        let max_entries: usize = (payload.len() - 8) / 4;
1460        let entries: usize = count.min(max_entries);
1461        for i in 0..entries {
1462            let off: usize = 8 + i * 4;
1463            let chunk_off: u32 = u32::from_be_bytes([
1464                payload[off],
1465                payload[off + 1],
1466                payload[off + 2],
1467                payload[off + 3],
1468            ]);
1469            raw_stbl.get_mut_chunk_offsets().push(chunk_off as u64);
1470        }
1471    }
1472
1473    /// Parses a 64-bit `co64` chunk offset table.
1474    ///
1475    /// # Arguments
1476    ///
1477    /// - `&[u8]` - `co64` payload bytes.
1478    /// - `&mut Mp4SampleTableRaw` - Destination raw sample table.
1479    fn parse_co64(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1480        if payload.len() < 8 {
1481            return;
1482        }
1483        let count: usize =
1484            u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1485        let max_entries: usize = (payload.len() - 8) / 8;
1486        let entries: usize = count.min(max_entries);
1487        for i in 0..entries {
1488            let off: usize = 8 + i * 8;
1489            let chunk_off: u64 = u64::from_be_bytes([
1490                payload[off],
1491                payload[off + 1],
1492                payload[off + 2],
1493                payload[off + 3],
1494                payload[off + 4],
1495                payload[off + 5],
1496                payload[off + 6],
1497                payload[off + 7],
1498            ]);
1499            raw_stbl.get_mut_chunk_offsets().push(chunk_off);
1500        }
1501    }
1502
1503    /// Expands parsed `stts`/`ctts`/`stss`/`stsc`/`stsz`/`stco` tables into flat indexed `Mp4Sample` records.
1504    ///
1505    /// # Arguments
1506    ///
1507    /// - `&Mp4SampleTableRaw` - Raw parsed sample table arrays.
1508    /// - `u32` - Track media timescale in ticks per second.
1509    ///
1510    /// # Returns
1511    ///
1512    /// - `Vec<Mp4Sample>` - Ordered decode-order sample list.
1513    fn build_samples(raw: &Mp4SampleTableRaw, timescale: u32) -> Vec<Mp4Sample> {
1514        let total_samples: usize = raw.get_sample_count() as usize;
1515        if total_samples == 0 || raw.get_chunk_offsets().is_empty() {
1516            return Vec::new();
1517        }
1518        let mut durations: Vec<u32> = Vec::with_capacity(total_samples);
1519        for (run_count, delta) in raw.get_stts().iter().copied() {
1520            let take_count: usize =
1521                (run_count as usize).min(total_samples.saturating_sub(durations.len()));
1522            for _ in 0..take_count {
1523                durations.push(delta);
1524            }
1525            if durations.len() >= total_samples {
1526                break;
1527            }
1528        }
1529        let mut cto_ticks: Vec<i32> = Vec::with_capacity(total_samples);
1530        for (run_count, offset) in raw.get_ctts().iter().copied() {
1531            let take_count: usize =
1532                (run_count as usize).min(total_samples.saturating_sub(cto_ticks.len()));
1533            for _ in 0..take_count {
1534                cto_ticks.push(offset);
1535            }
1536            if cto_ticks.len() >= total_samples {
1537                break;
1538            }
1539        }
1540        let keyframe_set: HashSet<u32> = raw.get_stss().iter().copied().collect();
1541        let all_keyframes: bool = keyframe_set.is_empty();
1542        let chunk_offsets: &[u64] = raw.get_chunk_offsets().as_slice();
1543        let stsc: &[(u32, u32)] = raw.get_stsc().as_slice();
1544        let mut sample_offsets: Vec<u64> = Vec::with_capacity(total_samples);
1545        let mut sample_sizes: Vec<u32> = Vec::with_capacity(total_samples);
1546        let mut sample_cursor: usize = 0;
1547        let mut stsc_idx: usize = 0;
1548        for (chunk_zero_idx, chunk_base_offset) in chunk_offsets.iter().copied().enumerate() {
1549            let chunk_one_based: u32 = (chunk_zero_idx + 1) as u32;
1550            while stsc_idx + 1 < stsc.len() && stsc[stsc_idx + 1].0 <= chunk_one_based {
1551                stsc_idx += 1;
1552            }
1553            let spc: usize = stsc
1554                .get(stsc_idx)
1555                .map(|e: &(u32, u32)| e.1 as usize)
1556                .unwrap_or(1);
1557            let mut offset_in_chunk: u64 = chunk_base_offset;
1558            for _ in 0..spc {
1559                if sample_cursor >= total_samples {
1560                    break;
1561                }
1562                let size: u32 = if raw.get_default_sample_size() > 0 {
1563                    raw.get_default_sample_size()
1564                } else {
1565                    raw.get_sample_sizes()
1566                        .get(sample_cursor)
1567                        .copied()
1568                        .unwrap_or(0)
1569                };
1570                sample_offsets.push(offset_in_chunk);
1571                sample_sizes.push(size);
1572                offset_in_chunk = offset_in_chunk.saturating_add(size as u64);
1573                sample_cursor += 1;
1574            }
1575            if sample_cursor >= total_samples {
1576                break;
1577            }
1578        }
1579        let mut out: Vec<Mp4Sample> = Vec::with_capacity(sample_offsets.len());
1580        let mut dts_ticks: i64 = 0;
1581        for idx in 0..sample_offsets.len() {
1582            let dur_ticks: u32 = durations.get(idx).copied().unwrap_or(1);
1583            let cto: i64 = cto_ticks.get(idx).copied().unwrap_or(0) as i64;
1584            let dts_us: i64 = Self::signed_ticks_to_us(dts_ticks, timescale);
1585            let pts_us: i64 = Self::signed_ticks_to_us(dts_ticks.saturating_add(cto), timescale);
1586            let duration_us: u64 = Self::ticks_to_us(dur_ticks as u64, timescale);
1587            let one_based: u32 = (idx + 1) as u32;
1588            let is_keyframe: bool = all_keyframes || keyframe_set.contains(&one_based);
1589            out.push(Mp4Sample::new(
1590                idx,
1591                dts_us,
1592                pts_us,
1593                duration_us,
1594                sample_offsets[idx],
1595                sample_sizes[idx],
1596                is_keyframe,
1597            ));
1598            dts_ticks = dts_ticks.saturating_add(dur_ticks as i64);
1599        }
1600        out
1601    }
1602
1603    /// Converts unsigned timescale ticks to microseconds with `u128` overflow protection.
1604    ///
1605    /// # Arguments
1606    ///
1607    /// - `u64` - Duration in media timescale ticks.
1608    /// - `u32` - Media timescale in ticks per second.
1609    ///
1610    /// # Returns
1611    ///
1612    /// - `u64` - Converted duration in microseconds.
1613    #[must_use]
1614    fn ticks_to_us(ticks: u64, timescale: u32) -> u64 {
1615        let scale: u128 = (timescale.max(1)) as u128;
1616        (((ticks as u128) * (VIDEO_MICROS_PER_SEC as u128)) / scale) as u64
1617    }
1618
1619    /// Converts signed timescale ticks to signed microseconds.
1620    ///
1621    /// # Arguments
1622    ///
1623    /// - `i64` - Signed timestamp in media timescale ticks.
1624    /// - `u32` - Media timescale in ticks per second.
1625    ///
1626    /// # Returns
1627    ///
1628    /// - `i64` - Converted signed timestamp in microseconds.
1629    #[must_use]
1630    fn signed_ticks_to_us(ticks: i64, timescale: u32) -> i64 {
1631        let scale: i128 = (timescale.max(1)) as i128;
1632        (((ticks as i128) * (VIDEO_MICROS_PER_SEC as i128)) / scale) as i64
1633    }
1634}
1635
1636/// Pure-Rust ISOBMFF MP4 container builder emitting valid `ftyp`, `moov`, and `mdat` boxes.
1637impl Mp4ContainerBuilder {
1638    /// Serializes a single-track video MP4 container with `ftyp`, `moov` (including `colr` `nclx` HDR metadata and optional `ctts`), and `mdat`.
1639    ///
1640    /// # Arguments
1641    ///
1642    /// - `u32` - Coded frame width in pixels.
1643    /// - `u32` - Coded frame height in pixels.
1644    /// - `u32` - Media timescale in ticks per second (e.g. `90_000` or `60_000`).
1645    /// - `VideoCodec` - Video codec identifier mapped to ISOBMFF FourCC (`avc1`, `hvc1`, `vp09`, `av01`, `rawv`).
1646    /// - `VideoColorInfo` - Color primaries, transfer curve, matrix, and range encoded in `colr`/`nclx`.
1647    /// - `&[Mp4BuilderSample]` - Ordered decode-order video samples.
1648    ///
1649    /// # Returns
1650    ///
1651    /// - `Vec<u8>` - Complete spec-compliant MP4 byte stream.
1652    #[must_use]
1653    pub fn build_video_mp4(
1654        width: u32,
1655        height: u32,
1656        timescale: u32,
1657        codec: VideoCodec,
1658        color_info: VideoColorInfo,
1659        samples: &[Mp4BuilderSample],
1660    ) -> Vec<u8> {
1661        let safe_scale: u32 = timescale.max(1);
1662        let mut total_ticks: u32 = 0;
1663        let mut mdat_payload: Vec<u8> = Vec::new();
1664        for sample in samples.iter() {
1665            total_ticks = total_ticks.saturating_add(sample.get_duration_ticks());
1666            mdat_payload.extend_from_slice(sample.get_payload().as_slice());
1667        }
1668        let mut ftyp_payload: Vec<u8> = Vec::with_capacity(16);
1669        ftyp_payload.extend_from_slice(&MP4_BRAND_ISOM);
1670        ftyp_payload.extend_from_slice(&512_u32.to_be_bytes());
1671        ftyp_payload.extend_from_slice(&MP4_BRAND_ISOM);
1672        ftyp_payload.extend_from_slice(&MP4_BRAND_MP42);
1673        let ftyp_box: Vec<u8> = Self::wrap_box(MP4_BOX_FTYP, &ftyp_payload);
1674        let moov_placeholder: Vec<u8> = Self::build_moov_box(
1675            (width, height),
1676            (safe_scale, total_ticks),
1677            codec,
1678            color_info,
1679            samples,
1680            0,
1681        );
1682        let mdat_data_offset: u32 = (ftyp_box.len() + moov_placeholder.len() + 8) as u32;
1683        let moov_box: Vec<u8> = Self::build_moov_box(
1684            (width, height),
1685            (safe_scale, total_ticks),
1686            codec,
1687            color_info,
1688            samples,
1689            mdat_data_offset,
1690        );
1691        let mdat_box: Vec<u8> = Self::wrap_box(MP4_BOX_MDAT, &mdat_payload);
1692        let mut out: Vec<u8> = Vec::with_capacity(ftyp_box.len() + moov_box.len() + mdat_box.len());
1693        out.extend_from_slice(&ftyp_box);
1694        out.extend_from_slice(&moov_box);
1695        out.extend_from_slice(&mdat_box);
1696        out
1697    }
1698
1699    /// Builds a `moov` box with `mvhd` and one video `trak` referencing `mdat_data_offset`.
1700    ///
1701    /// # Arguments
1702    ///
1703    /// - `(u32, u32)` - Frame `(width, height)` in pixels.
1704    /// - `(u32, u32)` - `(timescale, total_ticks)` timing parameters.
1705    /// - `VideoCodec` - Video codec tag.
1706    /// - `VideoColorInfo` - Color space metadata.
1707    /// - `&[Mp4BuilderSample]` - Sample descriptors.
1708    /// - `u32` - File byte offset of the first sample inside `mdat`.
1709    ///
1710    /// # Returns
1711    ///
1712    /// - `Vec<u8>` - Complete `moov` box bytes.
1713    #[must_use]
1714    fn build_moov_box(
1715        dims: (u32, u32),
1716        timing: (u32, u32),
1717        codec: VideoCodec,
1718        color_info: VideoColorInfo,
1719        samples: &[Mp4BuilderSample],
1720        mdat_data_offset: u32,
1721    ) -> Vec<u8> {
1722        let (width, height): (u32, u32) = dims;
1723        let (timescale, total_ticks): (u32, u32) = timing;
1724        let mut mvhd_payload: Vec<u8> = vec![0; 100];
1725        mvhd_payload[12..16].copy_from_slice(&timescale.to_be_bytes());
1726        mvhd_payload[16..20].copy_from_slice(&total_ticks.to_be_bytes());
1727        mvhd_payload[20..24].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
1728        mvhd_payload[24..26].copy_from_slice(&0x0100_u16.to_be_bytes());
1729        mvhd_payload[96..100].copy_from_slice(&2_u32.to_be_bytes());
1730        let mvhd_box: Vec<u8> = Self::wrap_box(MP4_BOX_MVHD, &mvhd_payload);
1731        let mut tkhd_payload: Vec<u8> = vec![0; 84];
1732        tkhd_payload[3] = 3;
1733        tkhd_payload[12..16].copy_from_slice(&1_u32.to_be_bytes());
1734        tkhd_payload[20..24].copy_from_slice(&total_ticks.to_be_bytes());
1735        tkhd_payload[76..80].copy_from_slice(&(width << 16).to_be_bytes());
1736        tkhd_payload[80..84].copy_from_slice(&(height << 16).to_be_bytes());
1737        let tkhd_box: Vec<u8> = Self::wrap_box(MP4_BOX_TKHD, &tkhd_payload);
1738        let mut mdhd_payload: Vec<u8> = vec![0; 24];
1739        mdhd_payload[12..16].copy_from_slice(&timescale.to_be_bytes());
1740        mdhd_payload[16..20].copy_from_slice(&total_ticks.to_be_bytes());
1741        let mdhd_box: Vec<u8> = Self::wrap_box(MP4_BOX_MDHD, &mdhd_payload);
1742        let mut hdlr_payload: Vec<u8> = vec![0; 25];
1743        hdlr_payload[8..12].copy_from_slice(&MP4_HANDLER_VIDE);
1744        let hdlr_box: Vec<u8> = Self::wrap_box(MP4_BOX_HDLR, &hdlr_payload);
1745        let stbl_box: Vec<u8> =
1746            Self::build_stbl_box(width, height, codec, color_info, samples, mdat_data_offset);
1747        let minf_box: Vec<u8> = Self::wrap_box(MP4_BOX_MINF, &stbl_box);
1748        let mut mdia_payload: Vec<u8> = Vec::new();
1749        mdia_payload.extend_from_slice(&mdhd_box);
1750        mdia_payload.extend_from_slice(&hdlr_box);
1751        mdia_payload.extend_from_slice(&minf_box);
1752        let mdia_box: Vec<u8> = Self::wrap_box(MP4_BOX_MDIA, &mdia_payload);
1753        let mut trak_payload: Vec<u8> = Vec::new();
1754        trak_payload.extend_from_slice(&tkhd_box);
1755        trak_payload.extend_from_slice(&mdia_box);
1756        let trak_box: Vec<u8> = Self::wrap_box(MP4_BOX_TRAK, &trak_payload);
1757        let mut moov_payload: Vec<u8> = Vec::new();
1758        moov_payload.extend_from_slice(&mvhd_box);
1759        moov_payload.extend_from_slice(&trak_box);
1760        Self::wrap_box(MP4_BOX_MOOV, &moov_payload)
1761    }
1762
1763    /// Builds an `stbl` box containing `stsd` (+ `colr`), `stts`, optional `ctts`, `stss`, `stsc`, `stsz`, and `stco`.
1764    ///
1765    /// # Arguments
1766    ///
1767    /// - `u32` - Frame width in pixels.
1768    /// - `u32` - Frame height in pixels.
1769    /// - `VideoCodec` - Video codec tag.
1770    /// - `VideoColorInfo` - Color space metadata.
1771    /// - `&[Mp4BuilderSample]` - Sample descriptors.
1772    /// - `u32` - File byte offset of the first sample inside `mdat`.
1773    ///
1774    /// # Returns
1775    ///
1776    /// - `Vec<u8>` - Complete `stbl` box bytes.
1777    #[must_use]
1778    fn build_stbl_box(
1779        width: u32,
1780        height: u32,
1781        codec: VideoCodec,
1782        color_info: VideoColorInfo,
1783        samples: &[Mp4BuilderSample],
1784        mdat_data_offset: u32,
1785    ) -> Vec<u8> {
1786        let codec_tag: [u8; 4] = match codec {
1787            VideoCodec::H264 => MP4_CODEC_AVC1,
1788            VideoCodec::H265 => MP4_CODEC_HVC1,
1789            VideoCodec::Vp9 => MP4_CODEC_VP09,
1790            VideoCodec::Av1 => MP4_CODEC_AV01,
1791            VideoCodec::RawFrames => MP4_CODEC_RAWV,
1792        };
1793        let (p_code, t_code, m_code, full_range): (u16, u16, u16, bool) = color_info.to_nclx();
1794        let mut colr_payload: Vec<u8> = Vec::with_capacity(11);
1795        colr_payload.extend_from_slice(&MP4_BOX_NCLX);
1796        colr_payload.extend_from_slice(&p_code.to_be_bytes());
1797        colr_payload.extend_from_slice(&t_code.to_be_bytes());
1798        colr_payload.extend_from_slice(&m_code.to_be_bytes());
1799        colr_payload.push(if full_range { 0x80 } else { 0x00 });
1800        let colr_box: Vec<u8> = Self::wrap_box(MP4_BOX_COLR, &colr_payload);
1801        let mut visual_entry_payload: Vec<u8> = vec![0; 78];
1802        visual_entry_payload[6..8].copy_from_slice(&1_u16.to_be_bytes());
1803        visual_entry_payload[24..26].copy_from_slice(&(width as u16).to_be_bytes());
1804        visual_entry_payload[26..28].copy_from_slice(&(height as u16).to_be_bytes());
1805        visual_entry_payload[28..32].copy_from_slice(&0x0048_0000_u32.to_be_bytes());
1806        visual_entry_payload[32..36].copy_from_slice(&0x0048_0000_u32.to_be_bytes());
1807        visual_entry_payload[40..42].copy_from_slice(&1_u16.to_be_bytes());
1808        visual_entry_payload[74..76].copy_from_slice(&24_u16.to_be_bytes());
1809        visual_entry_payload[76..78].copy_from_slice(&0xFFFF_u16.to_be_bytes());
1810        visual_entry_payload.extend_from_slice(&colr_box);
1811        let visual_entry_box: Vec<u8> = Self::wrap_box(codec_tag, &visual_entry_payload);
1812        let mut stsd_payload: Vec<u8> = Vec::with_capacity(8 + visual_entry_box.len());
1813        stsd_payload.extend_from_slice(&0_u32.to_be_bytes());
1814        stsd_payload.extend_from_slice(&1_u32.to_be_bytes());
1815        stsd_payload.extend_from_slice(&visual_entry_box);
1816        let stsd_box: Vec<u8> = Self::wrap_box(MP4_BOX_STSD, &stsd_payload);
1817        let mut stts_payload: Vec<u8> = Vec::with_capacity(8 + samples.len() * 8);
1818        stts_payload.extend_from_slice(&0_u32.to_be_bytes());
1819        stts_payload.extend_from_slice(&(samples.len() as u32).to_be_bytes());
1820        for sample in samples.iter() {
1821            stts_payload.extend_from_slice(&1_u32.to_be_bytes());
1822            stts_payload.extend_from_slice(&sample.get_duration_ticks().to_be_bytes());
1823        }
1824        let stts_box: Vec<u8> = Self::wrap_box(MP4_BOX_STTS, &stts_payload);
1825        let has_ctts: bool = samples
1826            .iter()
1827            .any(|s: &Mp4BuilderSample| s.get_composition_offset_ticks() != 0);
1828        let mut stbl_payload: Vec<u8> = Vec::new();
1829        stbl_payload.extend_from_slice(&stsd_box);
1830        stbl_payload.extend_from_slice(&stts_box);
1831        if has_ctts {
1832            let mut ctts_payload: Vec<u8> = Vec::with_capacity(8 + samples.len() * 8);
1833            ctts_payload.extend_from_slice(&[1, 0, 0, 0]);
1834            ctts_payload.extend_from_slice(&(samples.len() as u32).to_be_bytes());
1835            for sample in samples.iter() {
1836                ctts_payload.extend_from_slice(&1_u32.to_be_bytes());
1837                ctts_payload
1838                    .extend_from_slice(&sample.get_composition_offset_ticks().to_be_bytes());
1839            }
1840            let ctts_box: Vec<u8> = Self::wrap_box(MP4_BOX_CTTS, &ctts_payload);
1841            stbl_payload.extend_from_slice(&ctts_box);
1842        }
1843        let keyframes: Vec<u32> = samples
1844            .iter()
1845            .enumerate()
1846            .filter_map(|(idx, s): (usize, &Mp4BuilderSample)| {
1847                if s.get_is_keyframe() {
1848                    Some((idx + 1) as u32)
1849                } else {
1850                    None
1851                }
1852            })
1853            .collect();
1854        if !keyframes.is_empty() {
1855            let mut stss_payload: Vec<u8> = Vec::with_capacity(8 + keyframes.len() * 4);
1856            stss_payload.extend_from_slice(&0_u32.to_be_bytes());
1857            stss_payload.extend_from_slice(&(keyframes.len() as u32).to_be_bytes());
1858            for kf in keyframes.iter().copied() {
1859                stss_payload.extend_from_slice(&kf.to_be_bytes());
1860            }
1861            let stss_box: Vec<u8> = Self::wrap_box(MP4_BOX_STSS, &stss_payload);
1862            stbl_payload.extend_from_slice(&stss_box);
1863        }
1864        let mut stsc_payload: Vec<u8> = Vec::with_capacity(20);
1865        stsc_payload.extend_from_slice(&0_u32.to_be_bytes());
1866        stsc_payload.extend_from_slice(&1_u32.to_be_bytes());
1867        stsc_payload.extend_from_slice(&1_u32.to_be_bytes());
1868        stsc_payload.extend_from_slice(&(samples.len() as u32).to_be_bytes());
1869        stsc_payload.extend_from_slice(&1_u32.to_be_bytes());
1870        let stsc_box: Vec<u8> = Self::wrap_box(MP4_BOX_STSC, &stsc_payload);
1871        let mut stsz_payload: Vec<u8> = Vec::with_capacity(12 + samples.len() * 4);
1872        stsz_payload.extend_from_slice(&0_u32.to_be_bytes());
1873        stsz_payload.extend_from_slice(&0_u32.to_be_bytes());
1874        stsz_payload.extend_from_slice(&(samples.len() as u32).to_be_bytes());
1875        for sample in samples.iter() {
1876            stsz_payload.extend_from_slice(&(sample.get_payload().len() as u32).to_be_bytes());
1877        }
1878        let stsz_box: Vec<u8> = Self::wrap_box(MP4_BOX_STSZ, &stsz_payload);
1879        let mut stco_payload: Vec<u8> = Vec::with_capacity(12);
1880        stco_payload.extend_from_slice(&0_u32.to_be_bytes());
1881        stco_payload.extend_from_slice(&1_u32.to_be_bytes());
1882        stco_payload.extend_from_slice(&mdat_data_offset.to_be_bytes());
1883        let stco_box: Vec<u8> = Self::wrap_box(MP4_BOX_STCO, &stco_payload);
1884        stbl_payload.extend_from_slice(&stsc_box);
1885        stbl_payload.extend_from_slice(&stsz_box);
1886        stbl_payload.extend_from_slice(&stco_box);
1887        Self::wrap_box(MP4_BOX_STBL, &stbl_payload)
1888    }
1889
1890    /// Wraps `payload` inside a standard 32-bit ISOBMFF box header.
1891    ///
1892    /// # Arguments
1893    ///
1894    /// - `[u8; 4]` - FourCC box type.
1895    /// - `&[u8]` - Box payload bytes.
1896    ///
1897    /// # Returns
1898    ///
1899    /// - `Vec<u8>` - Framed ISOBMFF box bytes.
1900    #[must_use]
1901    fn wrap_box(box_type: [u8; 4], payload: &[u8]) -> Vec<u8> {
1902        let total: u32 = (payload.len() + 8) as u32;
1903        let mut out: Vec<u8> = Vec::with_capacity(total as usize);
1904        out.extend_from_slice(&total.to_be_bytes());
1905        out.extend_from_slice(&box_type);
1906        out.extend_from_slice(payload);
1907        out
1908    }
1909}
1910
1911/// Content-based equality for `EncodedVideoPacket` comparing metadata and active byte slice.
1912impl PartialEq for EncodedVideoPacket {
1913    /// Compares packet timing, index, generation, keyframe flag, and active encoded payload slice.
1914    ///
1915    /// # Arguments
1916    ///
1917    /// - `&Self` - Left-hand packet.
1918    /// - `&Self` - Right-hand packet.
1919    ///
1920    /// # Returns
1921    ///
1922    /// - `bool` - `true` when metadata and encoded payload bytes match.
1923    fn eq(&self, other: &Self) -> bool {
1924        self.get_sample_index() == other.get_sample_index()
1925            && self.get_generation() == other.get_generation()
1926            && self.get_dts_us() == other.get_dts_us()
1927            && self.get_pts_us() == other.get_pts_us()
1928            && self.get_duration_us() == other.get_duration_us()
1929            && self.get_is_keyframe() == other.get_is_keyframe()
1930            && self.data_slice() == other.data_slice()
1931    }
1932}
1933
1934/// Reflexive equality marker for `EncodedVideoPacket`.
1935impl Eq for EncodedVideoPacket {}
1936
1937/// Zero-copy range constructors and slice accessors for `EncodedVideoPacket`.
1938impl EncodedVideoPacket {
1939    /// Creates a zero-copy packet referencing `byte_start..byte_end` inside shared `source` bytes.
1940    ///
1941    /// # Arguments
1942    ///
1943    /// - `&Mp4Sample` - Sample metadata supplying index, timestamps, duration, and keyframe flag.
1944    /// - `u64` - Active seek generation tag.
1945    /// - `Arc<[u8]>` - Shared backing container byte buffer.
1946    /// - `usize` - Inclusive start byte offset inside `source`.
1947    /// - `usize` - Exclusive end byte offset inside `source`.
1948    ///
1949    /// # Returns
1950    ///
1951    /// - `Self` - Zero-copy packet view.
1952    #[must_use]
1953    pub fn from_shared_range(
1954        sample: &Mp4Sample,
1955        generation: u64,
1956        source: Arc<[u8]>,
1957        byte_start: usize,
1958        byte_end: usize,
1959    ) -> Self {
1960        let clamped_end: usize = byte_end.min(source.len());
1961        let clamped_start: usize = byte_start.min(clamped_end);
1962        Self {
1963            sample_index: sample.get_index(),
1964            generation,
1965            dts_us: sample.get_dts_us(),
1966            pts_us: sample.get_pts_us(),
1967            duration_us: sample.get_duration_us(),
1968            is_keyframe: sample.get_is_keyframe(),
1969            source,
1970            byte_start: clamped_start,
1971            byte_end: clamped_end,
1972        }
1973    }
1974
1975    /// Creates a standalone packet wrapping `data` convertible into `Arc<[u8]>`.
1976    ///
1977    /// # Arguments
1978    ///
1979    /// - `usize` - Zero-based sample index.
1980    /// - `u64` - Seek/pipeline generation tag.
1981    /// - `(i64, i64, u64)` - Timing tuple `(dts_us, pts_us, duration_us)`.
1982    /// - `bool` - Whether this packet is an intra keyframe.
1983    /// - `B` - Encoded payload bytes convertible into `Arc<[u8]>`.
1984    ///
1985    /// # Returns
1986    ///
1987    /// - `Self` - Initialized `EncodedVideoPacket`.
1988    #[must_use]
1989    pub fn from_bytes<B>(
1990        sample_index: usize,
1991        generation: u64,
1992        timing: (i64, i64, u64),
1993        is_keyframe: bool,
1994        data: B,
1995    ) -> Self
1996    where
1997        B: Into<Arc<[u8]>>,
1998    {
1999        let (dts_us, pts_us, duration_us): (i64, i64, u64) = timing;
2000        let shared: Arc<[u8]> = data.into();
2001        let len: usize = shared.len();
2002        Self {
2003            sample_index,
2004            generation,
2005            dts_us,
2006            pts_us,
2007            duration_us,
2008            is_keyframe,
2009            source: shared,
2010            byte_start: 0,
2011            byte_end: len,
2012        }
2013    }
2014
2015    /// Returns a zero-copy borrowed slice over this packet's encoded bytes.
2016    ///
2017    /// # Arguments
2018    ///
2019    /// - `&Self` - Packet reference.
2020    ///
2021    /// # Returns
2022    ///
2023    /// - `&[u8]` - Encoded packet payload slice.
2024    #[must_use]
2025    pub fn get_data(&self) -> &[u8] {
2026        let start: usize = self.get_byte_start();
2027        let end: usize = self.get_byte_end();
2028        self.source.get(start..end).unwrap_or(&[])
2029    }
2030
2031    /// Returns a zero-copy borrowed slice over this packet's encoded bytes.
2032    ///
2033    /// # Arguments
2034    ///
2035    /// - `&Self` - Packet reference.
2036    ///
2037    /// # Returns
2038    ///
2039    /// - `&[u8]` - Encoded packet payload slice.
2040    #[must_use]
2041    pub fn data_slice(&self) -> &[u8] {
2042        self.get_data()
2043    }
2044
2045    /// Returns a reference to the shared backing `Arc<[u8]>` buffer.
2046    ///
2047    /// # Arguments
2048    ///
2049    /// - `&Self` - Packet reference.
2050    ///
2051    /// # Returns
2052    ///
2053    /// - `&Arc<[u8]>` - Shared container or standalone byte storage.
2054    #[must_use]
2055    pub fn source_arc(&self) -> &Arc<[u8]> {
2056        let Self { source, .. } = self;
2057        source
2058    }
2059}
2060
2061/// Convenience accessors for inspecting `DecodedVideoFrame` GPU handles or CPU pixel buffers.
2062impl DecodedVideoFrame {
2063    /// Returns the zero-copy GPU surface handle when this frame is GPU-backed.
2064    ///
2065    /// # Arguments
2066    ///
2067    /// - `&Self` - Decoded frame reference.
2068    ///
2069    /// # Returns
2070    ///
2071    /// - `Option<VideoGpuSurfaceHandle>` - GPU surface handle if backed by `GpuSurface`.
2072    #[must_use]
2073    pub fn gpu_surface(&self) -> Option<VideoGpuSurfaceHandle> {
2074        match self.get_backing() {
2075            VideoFrameBacking::GpuSurface(handle) => Some(*handle),
2076            VideoFrameBacking::CpuPooled(_) => None,
2077        }
2078    }
2079
2080    /// Returns a reference to the pooled CPU RGBA8 pixel slice when CPU-backed.
2081    ///
2082    /// # Arguments
2083    ///
2084    /// - `&Self` - Decoded frame reference.
2085    ///
2086    /// # Returns
2087    ///
2088    /// - `Option<&[u8]>` - RGBA8 pixel slice if backed by `CpuPooled`.
2089    #[must_use]
2090    pub fn cpu_rgba_pixels(&self) -> Option<&[u8]> {
2091        match self.get_backing() {
2092            VideoFrameBacking::CpuPooled(pooled) => Some(pooled.get_pixels().as_slice()),
2093            VideoFrameBacking::GpuSurface(_) => None,
2094        }
2095    }
2096
2097    /// Converts a CPU-backed frame into an `ImageBuffer` copy (returns `None` for zero-copy GPU surfaces to avoid readback).
2098    ///
2099    /// # Arguments
2100    ///
2101    /// - `&Self` - Decoded frame reference.
2102    ///
2103    /// # Returns
2104    ///
2105    /// - `Option<ImageBuffer>` - RGBA8 image buffer copy when CPU-backed.
2106    #[must_use]
2107    pub fn to_image_buffer(&self) -> Option<ImageBuffer> {
2108        let pixels: &[u8] = self.cpu_rgba_pixels()?;
2109        Some(ImageBuffer::new(
2110            self.get_width(),
2111            self.get_height(),
2112            pixels,
2113        ))
2114    }
2115}
2116
2117/// Packet encoders and YUV-to-RGB color conversion helpers for `SoftwareVideoDecoder`.
2118impl SoftwareVideoDecoder {
2119    /// Encodes an intra-coded `EVF1` RGBA8 frame packet for pure-Rust software decoding.
2120    ///
2121    /// # Arguments
2122    ///
2123    /// - `u32` - Frame width in pixels.
2124    /// - `u32` - Frame height in pixels.
2125    /// - `&[u8]` - Packed RGBA8 pixel data (`width * height * 4`).
2126    ///
2127    /// # Returns
2128    ///
2129    /// - `Vec<u8>` - Encoded `EVF1` intra RGBA8 packet bytes.
2130    #[must_use]
2131    pub fn encode_intra_rgba_packet(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
2132        let mut out: Vec<u8> = Vec::with_capacity(13 + rgba.len());
2133        out.extend_from_slice(VIDEO_SW_FRAME_MAGIC);
2134        out.push(VIDEO_SW_PACKET_INTRA_RGBA);
2135        out.extend_from_slice(&width.to_le_bytes());
2136        out.extend_from_slice(&height.to_le_bytes());
2137        out.extend_from_slice(rgba);
2138        out
2139    }
2140
2141    /// Encodes an intra-coded `EVF1` tri-planar YUV420P frame packet decoded using the track's `VideoColorInfo` matrix and range.
2142    ///
2143    /// # Arguments
2144    ///
2145    /// - `u32` - Frame width in pixels.
2146    /// - `u32` - Frame height in pixels.
2147    /// - `&[u8]` - Y luma plane (`width * height`).
2148    /// - `&[u8]` - U (Cb) chroma plane (`ceil(width / 2) * ceil(height / 2)`).
2149    /// - `&[u8]` - V (Cr) chroma plane (`ceil(width / 2) * ceil(height / 2)`).
2150    ///
2151    /// # Returns
2152    ///
2153    /// - `Vec<u8>` - Encoded `EVF1` intra YUV420P packet bytes.
2154    #[must_use]
2155    pub fn encode_intra_yuv420p_packet(
2156        width: u32,
2157        height: u32,
2158        y_plane: &[u8],
2159        u_plane: &[u8],
2160        v_plane: &[u8],
2161    ) -> Vec<u8> {
2162        let mut out: Vec<u8> =
2163            Vec::with_capacity(13 + y_plane.len() + u_plane.len() + v_plane.len());
2164        out.extend_from_slice(VIDEO_SW_FRAME_MAGIC);
2165        out.push(VIDEO_SW_PACKET_INTRA_YUV420P);
2166        out.extend_from_slice(&width.to_le_bytes());
2167        out.extend_from_slice(&height.to_le_bytes());
2168        out.extend_from_slice(y_plane);
2169        out.extend_from_slice(u_plane);
2170        out.extend_from_slice(v_plane);
2171        out
2172    }
2173
2174    /// Encodes an inter-coded P-frame XOR delta packet relative to `prev_rgba`.
2175    ///
2176    /// # Arguments
2177    ///
2178    /// - `u32` - Frame width in pixels.
2179    /// - `u32` - Frame height in pixels.
2180    /// - `&[u8]` - Previous reference RGBA8 frame bytes.
2181    /// - `&[u8]` - Target RGBA8 frame bytes.
2182    ///
2183    /// # Returns
2184    ///
2185    /// - `Vec<u8>` - Encoded `EVF1` P-frame delta packet bytes.
2186    #[must_use]
2187    pub fn encode_delta_xor_packet(
2188        width: u32,
2189        height: u32,
2190        prev_rgba: &[u8],
2191        target_rgba: &[u8],
2192    ) -> Vec<u8> {
2193        let len: usize = prev_rgba.len().min(target_rgba.len());
2194        let mut out: Vec<u8> = Vec::with_capacity(13 + len);
2195        out.extend_from_slice(VIDEO_SW_FRAME_MAGIC);
2196        out.push(VIDEO_SW_PACKET_DELTA_XOR);
2197        out.extend_from_slice(&width.to_le_bytes());
2198        out.extend_from_slice(&height.to_le_bytes());
2199        for i in 0..len {
2200            out.push(prev_rgba[i] ^ target_rgba[i]);
2201        }
2202        out
2203    }
2204
2205    /// Resolves Q16 fixed-point `[cy, c_rv, c_gu, c_gv, c_bu]` conversion coefficients for `color_info`.
2206    ///
2207    /// # Arguments
2208    ///
2209    /// - `VideoColorInfo` - Color matrix and quantization range metadata.
2210    ///
2211    /// # Returns
2212    ///
2213    /// - `[i32; 5]` - Fixed-point Q16 conversion coefficients.
2214    #[must_use]
2215    const fn yuv_q16_coeffs(color_info: VideoColorInfo) -> [i32; 5] {
2216        let VideoColorInfo { matrix, range, .. } = color_info;
2217        let full_range: bool = matches!(range, ColorRange::Full);
2218        match (matrix, full_range) {
2219            (MatrixCoefficients::Bt601, false) => YUV_COEFFS_BT601_LIMITED,
2220            (MatrixCoefficients::Bt601, true) => YUV_COEFFS_BT601_FULL,
2221            (MatrixCoefficients::Bt2020Ncl, false) => YUV_COEFFS_BT2020_LIMITED,
2222            (MatrixCoefficients::Bt2020Ncl, true) => YUV_COEFFS_BT2020_FULL,
2223            (
2224                MatrixCoefficients::Bt709
2225                | MatrixCoefficients::Identity
2226                | MatrixCoefficients::Unknown(_),
2227                false,
2228            ) => YUV_COEFFS_BT709_LIMITED,
2229            (
2230                MatrixCoefficients::Bt709
2231                | MatrixCoefficients::Identity
2232                | MatrixCoefficients::Unknown(_),
2233                true,
2234            ) => YUV_COEFFS_BT709_FULL,
2235        }
2236    }
2237
2238    /// Writes a single Q16 fixed-point YUV pixel into a 4-byte RGBA8 destination slice.
2239    ///
2240    /// # Arguments
2241    ///
2242    /// - `i32` - Pre-scaled Q16 luma term from the luma lookup table.
2243    /// - `(i32, i32, i32)` - Precomputed chroma terms `(r_uv, g_uv, b_uv)` including rounding bias.
2244    /// - `&mut [u8]` - 4-byte destination pixel slice.
2245    #[inline(always)]
2246    fn write_yuv_q16_pixel(y_scaled: i32, chroma_rgb: (i32, i32, i32), dst: &mut [u8]) {
2247        let (r_uv, g_uv, b_uv): (i32, i32, i32) = chroma_rgb;
2248        let r: u8 = ((y_scaled + r_uv) >> YUV_Q16_SHIFT).clamp(0, 255) as u8;
2249        let g: u8 = ((y_scaled + g_uv) >> YUV_Q16_SHIFT).clamp(0, 255) as u8;
2250        let b: u8 = ((y_scaled + b_uv) >> YUV_Q16_SHIFT).clamp(0, 255) as u8;
2251        dst[0] = r;
2252        dst[1] = g;
2253        dst[2] = b;
2254        dst[3] = 255;
2255    }
2256
2257    /// Converts tri-planar 8-bit YUV420P samples into packed RGBA8 using Q16 fixed-point integer math honoring `VideoColorInfo`.
2258    ///
2259    /// # Arguments
2260    ///
2261    /// - `u32` - Frame width in pixels.
2262    /// - `u32` - Frame height in pixels.
2263    /// - `&[u8]` - Concatenated `Y + U + V` planes.
2264    /// - `VideoColorInfo` - Color matrix and range metadata.
2265    /// - `&mut [u8]` - Destination RGBA8 buffer (`width * height * 4`).
2266    fn convert_yuv420p_to_rgba(
2267        width: u32,
2268        height: u32,
2269        yuv: &[u8],
2270        color_info: VideoColorInfo,
2271        dst_rgba: &mut [u8],
2272    ) {
2273        let w: usize = width as usize;
2274        let h: usize = height as usize;
2275        if w == 0 || h == 0 {
2276            return;
2277        }
2278        let cw: usize = w.div_ceil(2);
2279        let ch: usize = h.div_ceil(2);
2280        let y_len: usize = w * h;
2281        let uv_len: usize = cw * ch;
2282        let y_plane: &[u8] = &yuv[0..y_len];
2283        let u_plane: &[u8] = &yuv[y_len..(y_len + uv_len)];
2284        let v_plane: &[u8] = &yuv[(y_len + uv_len)..(y_len + uv_len * 2)];
2285        let coeffs: [i32; 5] = Self::yuv_q16_coeffs(color_info);
2286        let cy: i32 = coeffs[0];
2287        let c_rv: i32 = coeffs[1];
2288        let c_gu: i32 = coeffs[2];
2289        let c_gv: i32 = coeffs[3];
2290        let c_bu: i32 = coeffs[4];
2291        let full_range: bool = color_info.get_range() == ColorRange::Full;
2292        let mut y_lut: [i32; 256] = [0; 256];
2293        for (idx, slot) in y_lut.iter_mut().enumerate() {
2294            let y_val: i32 = idx as i32;
2295            let y_eff: i32 = if full_range {
2296                y_val
2297            } else {
2298                y_val.clamp(YUV_LIMITED_Y_MIN, YUV_LIMITED_Y_MAX) - YUV_LIMITED_Y_MIN
2299            };
2300            *slot = y_eff * cy;
2301        }
2302        let pairs_x: usize = w / 2;
2303        let pairs_y: usize = h / 2;
2304        let has_odd_x: bool = (w & 1) != 0;
2305        let row_rgba_bytes: usize = w * 4;
2306        for py in 0..pairs_y {
2307            let row0: usize = py * 2;
2308            let row1: usize = row0 + 1;
2309            let y_row0: &[u8] = &y_plane[(row0 * w)..((row0 + 1) * w)];
2310            let y_row1: &[u8] = &y_plane[(row1 * w)..((row1 + 1) * w)];
2311            let u_row: &[u8] = &u_plane[(py * cw)..((py + 1) * cw)];
2312            let v_row: &[u8] = &v_plane[(py * cw)..((py + 1) * cw)];
2313            let dst_pair: &mut [u8] =
2314                &mut dst_rgba[(row0 * row_rgba_bytes)..((row1 + 1) * row_rgba_bytes)];
2315            let (dst_row0, dst_row1): (&mut [u8], &mut [u8]) =
2316                dst_pair.split_at_mut(row_rgba_bytes);
2317            for px in 0..pairs_x {
2318                let du: i32 = (u_row[px] as i32) - YUV_CHROMA_BIAS;
2319                let dv: i32 = (v_row[px] as i32) - YUV_CHROMA_BIAS;
2320                let chroma: (i32, i32, i32) = (
2321                    c_rv * dv + YUV_Q16_HALF,
2322                    c_gu * du + c_gv * dv + YUV_Q16_HALF,
2323                    c_bu * du + YUV_Q16_HALF,
2324                );
2325                let col0: usize = px * 2;
2326                let dst0: usize = col0 * 4;
2327                Self::write_yuv_q16_pixel(
2328                    y_lut[y_row0[col0] as usize],
2329                    chroma,
2330                    &mut dst_row0[dst0..(dst0 + 4)],
2331                );
2332                Self::write_yuv_q16_pixel(
2333                    y_lut[y_row0[col0 + 1] as usize],
2334                    chroma,
2335                    &mut dst_row0[(dst0 + 4)..(dst0 + 8)],
2336                );
2337                Self::write_yuv_q16_pixel(
2338                    y_lut[y_row1[col0] as usize],
2339                    chroma,
2340                    &mut dst_row1[dst0..(dst0 + 4)],
2341                );
2342                Self::write_yuv_q16_pixel(
2343                    y_lut[y_row1[col0 + 1] as usize],
2344                    chroma,
2345                    &mut dst_row1[(dst0 + 4)..(dst0 + 8)],
2346                );
2347            }
2348            if has_odd_x {
2349                let last_col: usize = w - 1;
2350                let du: i32 = (u_row[pairs_x] as i32) - YUV_CHROMA_BIAS;
2351                let dv: i32 = (v_row[pairs_x] as i32) - YUV_CHROMA_BIAS;
2352                let chroma: (i32, i32, i32) = (
2353                    c_rv * dv + YUV_Q16_HALF,
2354                    c_gu * du + c_gv * dv + YUV_Q16_HALF,
2355                    c_bu * du + YUV_Q16_HALF,
2356                );
2357                let dst_last: usize = last_col * 4;
2358                Self::write_yuv_q16_pixel(
2359                    y_lut[y_row0[last_col] as usize],
2360                    chroma,
2361                    &mut dst_row0[dst_last..(dst_last + 4)],
2362                );
2363                Self::write_yuv_q16_pixel(
2364                    y_lut[y_row1[last_col] as usize],
2365                    chroma,
2366                    &mut dst_row1[dst_last..(dst_last + 4)],
2367                );
2368            }
2369        }
2370        if (h & 1) != 0 {
2371            let last_row: usize = h - 1;
2372            let crow: usize = pairs_y;
2373            let y_row: &[u8] = &y_plane[(last_row * w)..((last_row + 1) * w)];
2374            let u_row: &[u8] = &u_plane[(crow * cw)..((crow + 1) * cw)];
2375            let v_row: &[u8] = &v_plane[(crow * cw)..((crow + 1) * cw)];
2376            let dst_row: &mut [u8] =
2377                &mut dst_rgba[(last_row * row_rgba_bytes)..((last_row + 1) * row_rgba_bytes)];
2378            for px in 0..pairs_x {
2379                let du: i32 = (u_row[px] as i32) - YUV_CHROMA_BIAS;
2380                let dv: i32 = (v_row[px] as i32) - YUV_CHROMA_BIAS;
2381                let chroma: (i32, i32, i32) = (
2382                    c_rv * dv + YUV_Q16_HALF,
2383                    c_gu * du + c_gv * dv + YUV_Q16_HALF,
2384                    c_bu * du + YUV_Q16_HALF,
2385                );
2386                let col0: usize = px * 2;
2387                let dst0: usize = col0 * 4;
2388                Self::write_yuv_q16_pixel(
2389                    y_lut[y_row[col0] as usize],
2390                    chroma,
2391                    &mut dst_row[dst0..(dst0 + 4)],
2392                );
2393                Self::write_yuv_q16_pixel(
2394                    y_lut[y_row[col0 + 1] as usize],
2395                    chroma,
2396                    &mut dst_row[(dst0 + 4)..(dst0 + 8)],
2397                );
2398            }
2399            if has_odd_x {
2400                let last_col: usize = w - 1;
2401                let du: i32 = (u_row[pairs_x] as i32) - YUV_CHROMA_BIAS;
2402                let dv: i32 = (v_row[pairs_x] as i32) - YUV_CHROMA_BIAS;
2403                let chroma: (i32, i32, i32) = (
2404                    c_rv * dv + YUV_Q16_HALF,
2405                    c_gu * du + c_gv * dv + YUV_Q16_HALF,
2406                    c_bu * du + YUV_Q16_HALF,
2407                );
2408                let dst_last: usize = last_col * 4;
2409                Self::write_yuv_q16_pixel(
2410                    y_lut[y_row[last_col] as usize],
2411                    chroma,
2412                    &mut dst_row[dst_last..(dst_last + 4)],
2413                );
2414            }
2415        }
2416    }
2417}
2418
2419/// Pure-Rust software fallback `VideoDecoderBackend` implementation for `SoftwareVideoDecoder`.
2420impl VideoDecoderBackend for SoftwareVideoDecoder {
2421    /// Returns `HardwareDecoderKind::SoftwareFallback`.
2422    ///
2423    /// # Arguments
2424    ///
2425    /// - `&Self` - Decoder reference.
2426    ///
2427    /// # Returns
2428    ///
2429    /// - `HardwareDecoderKind` - Always `SoftwareFallback`.
2430    fn backend_kind(&self) -> HardwareDecoderKind {
2431        HardwareDecoderKind::SoftwareFallback
2432    }
2433
2434    /// Returns software fallback capabilities.
2435    ///
2436    /// # Arguments
2437    ///
2438    /// - `&Self` - Decoder reference.
2439    ///
2440    /// # Returns
2441    ///
2442    /// - `HardwareDecoderCapabilities` - Software capability profile.
2443    fn capabilities(&self) -> HardwareDecoderCapabilities {
2444        HardwareDecoderProbe::capabilities_for(HardwareDecoderKind::SoftwareFallback)
2445    }
2446
2447    /// Configures the software decoder for the track's dimensions and color metadata.
2448    ///
2449    /// # Arguments
2450    ///
2451    /// - `&Self` - Mutable software decoder.
2452    /// - `&VideoDecoderConfig` - Video track configuration.
2453    ///
2454    /// # Returns
2455    ///
2456    /// - `Result<(), String>` - `Ok(())` when dimensions are valid.
2457    fn configure(&mut self, config: &VideoDecoderConfig) -> Result<(), String> {
2458        if config.get_width() == 0 || config.get_height() == 0 {
2459            return Err(VIDEO_ERR_UNSUPPORTED_DIMENSIONS.to_string());
2460        }
2461        self.set_config(*config);
2462        self.flush();
2463        Ok(())
2464    }
2465
2466    /// Decodes an `EVF1` intra/YUV420P/delta packet or raw RGBA8 frame into a pooled CPU `DecodedVideoFrame`.
2467    ///
2468    /// # Arguments
2469    ///
2470    /// - `&Self` - Mutable software decoder.
2471    /// - `&EncodedVideoPacket` - Encoded packet with DTS/PTS and seek generation.
2472    /// - `&VideoFramePool` - Bounded CPU pixel pool.
2473    ///
2474    /// # Returns
2475    ///
2476    /// - `Result<Option<DecodedVideoFrame>, String>` - Decoded CPU pooled frame or error.
2477    fn decode_packet(
2478        &mut self,
2479        packet: &EncodedVideoPacket,
2480        pool: &VideoFramePool,
2481    ) -> Result<Option<DecodedVideoFrame>, String> {
2482        let data: &[u8] = packet.data_slice();
2483        let config: VideoDecoderConfig = self.get_config();
2484        let (width, height, kind, payload): (u32, u32, u8, &[u8]) =
2485            if data.len() >= 13 && &data[0..4] == VIDEO_SW_FRAME_MAGIC {
2486                let pkt_kind: u8 = data[4];
2487                let w: u32 = u32::from_le_bytes([data[5], data[6], data[7], data[8]]);
2488                let h: u32 = u32::from_le_bytes([data[9], data[10], data[11], data[12]]);
2489                (w, h, pkt_kind, &data[13..])
2490            } else if config.get_codec() == VideoCodec::RawFrames {
2491                (
2492                    config.get_width(),
2493                    config.get_height(),
2494                    VIDEO_SW_PACKET_INTRA_RGBA,
2495                    data,
2496                )
2497            } else {
2498                return Err(VIDEO_ERR_UNSUPPORTED_CODEC.to_string());
2499            };
2500        if width == 0 || height == 0 {
2501            return Err(VIDEO_ERR_UNSUPPORTED_DIMENSIONS.to_string());
2502        }
2503        let rgba_len: usize = (width as usize)
2504            .checked_mul(height as usize)
2505            .and_then(|v: usize| v.checked_mul(4))
2506            .ok_or_else(|| VIDEO_ERR_UNSUPPORTED_DIMENSIONS.to_string())?;
2507        let mut pooled: PooledVideoFrame = pool
2508            .acquire(width, height)
2509            .ok_or_else(|| VIDEO_ERR_POOL_EXHAUSTED.to_string())?;
2510        match kind {
2511            VIDEO_SW_PACKET_INTRA_RGBA => {
2512                if payload.len() != rgba_len {
2513                    pool.recycle(pooled);
2514                    return Err(VIDEO_ERR_SW_PACKET_SIZE.to_string());
2515                }
2516                pooled.get_mut_pixels().copy_from_slice(payload);
2517            }
2518            VIDEO_SW_PACKET_INTRA_YUV420P => {
2519                let y_len: usize = (width as usize) * (height as usize);
2520                let uv_len: usize = (width as usize).div_ceil(2) * (height as usize).div_ceil(2);
2521                if payload.len() != y_len + uv_len * 2 {
2522                    pool.recycle(pooled);
2523                    return Err(VIDEO_ERR_SW_PACKET_SIZE.to_string());
2524                }
2525                Self::convert_yuv420p_to_rgba(
2526                    width,
2527                    height,
2528                    payload,
2529                    config.get_color_info(),
2530                    pooled.get_mut_pixels().as_mut_slice(),
2531                );
2532            }
2533            VIDEO_SW_PACKET_DELTA_XOR => {
2534                let has_ref: bool = self.get_has_reference();
2535                let Self { reference_rgba, .. } = self;
2536                if !has_ref || reference_rgba.len() != rgba_len {
2537                    pool.recycle(pooled);
2538                    return Err(VIDEO_ERR_SW_DELTA_NO_REF.to_string());
2539                }
2540                if payload.len() != rgba_len {
2541                    pool.recycle(pooled);
2542                    return Err(VIDEO_ERR_SW_PACKET_SIZE.to_string());
2543                }
2544                let dst: &mut [u8] = pooled.get_mut_pixels().as_mut_slice();
2545                for i in 0..rgba_len {
2546                    dst[i] = reference_rgba[i] ^ payload[i];
2547                }
2548            }
2549            _ => {
2550                pool.recycle(pooled);
2551                return Err(VIDEO_ERR_SW_PACKET_INVALID.to_string());
2552            }
2553        }
2554        {
2555            let Self { reference_rgba, .. } = self;
2556            if reference_rgba.len() != rgba_len {
2557                reference_rgba.resize(rgba_len, 0);
2558            }
2559            reference_rgba.copy_from_slice(pooled.get_pixels().as_slice());
2560        }
2561        self.set_has_reference(true);
2562        let next_decoded: u64 = self.get_decoded_frames().saturating_add(1);
2563        self.set_decoded_frames(next_decoded);
2564        Ok(Some(DecodedVideoFrame {
2565            sample_index: packet.get_sample_index(),
2566            generation: packet.get_generation(),
2567            dts_us: packet.get_dts_us(),
2568            pts_us: packet.get_pts_us(),
2569            duration_us: packet.get_duration_us(),
2570            width,
2571            height,
2572            color_info: config.get_color_info(),
2573            backing: VideoFrameBacking::CpuPooled(pooled),
2574        }))
2575    }
2576
2577    /// Clears the retained reference frame upon seek or discontinuity.
2578    ///
2579    /// # Arguments
2580    ///
2581    /// - `&Self` - Mutable software decoder.
2582    fn flush(&mut self) {
2583        self.set_has_reference(false);
2584        let Self { reference_rgba, .. } = self;
2585        reference_rgba.clear();
2586    }
2587}
2588
2589/// Constructors for `HardwareZeroCopyDecoder`.
2590impl HardwareZeroCopyDecoder {
2591    /// Creates a zero-copy GPU interop hardware decoder adapter bound to `kind` and `device_id`.
2592    ///
2593    /// # Arguments
2594    ///
2595    /// - `HardwareDecoderKind` - Target hardware backend (`VideoToolbox`, `MediaCodec`, `Vaapi`, `Dxva`, `WebCodecs`).
2596    /// - `u64` - Target GPU device identifier.
2597    ///
2598    /// # Returns
2599    ///
2600    /// - `Self` - Initialized zero-copy GPU hardware decoder adapter.
2601    #[must_use]
2602    pub fn for_backend(kind: HardwareDecoderKind, device_id: u64) -> Self {
2603        Self {
2604            kind,
2605            device_id,
2606            pixel_format: VideoPixelFormat::Nv12,
2607            config: VideoDecoderConfig::default(),
2608            next_surface_id: 1,
2609            next_fence_value: 1,
2610        }
2611    }
2612}
2613
2614/// Zero-copy GPU surface `VideoDecoderBackend` implementation for `HardwareZeroCopyDecoder`.
2615impl VideoDecoderBackend for HardwareZeroCopyDecoder {
2616    /// Returns the configured hardware backend kind.
2617    ///
2618    /// # Arguments
2619    ///
2620    /// - `&Self` - Hardware decoder reference.
2621    ///
2622    /// # Returns
2623    ///
2624    /// - `HardwareDecoderKind` - Active hardware backend kind.
2625    fn backend_kind(&self) -> HardwareDecoderKind {
2626        self.get_kind()
2627    }
2628
2629    /// Returns hardware capabilities for the configured platform backend.
2630    ///
2631    /// # Arguments
2632    ///
2633    /// - `&Self` - Hardware decoder reference.
2634    ///
2635    /// # Returns
2636    ///
2637    /// - `HardwareDecoderCapabilities` - Hardware capability descriptor.
2638    fn capabilities(&self) -> HardwareDecoderCapabilities {
2639        HardwareDecoderProbe::capabilities_for(self.get_kind())
2640    }
2641
2642    /// Configures surface format (`P010` for HDR10/10-bit streams, `Nv12` for SDR) and track geometry.
2643    ///
2644    /// # Arguments
2645    ///
2646    /// - `&Self` - Mutable hardware decoder.
2647    /// - `&VideoDecoderConfig` - Video track metadata.
2648    ///
2649    /// # Returns
2650    ///
2651    /// - `Result<(), String>` - `Ok(())` when dimensions are valid.
2652    fn configure(&mut self, config: &VideoDecoderConfig) -> Result<(), String> {
2653        if config.get_width() == 0 || config.get_height() == 0 {
2654            return Err(VIDEO_ERR_UNSUPPORTED_DIMENSIONS.to_string());
2655        }
2656        self.set_config(*config);
2657        let fmt: VideoPixelFormat =
2658            if config.get_color_info().is_hdr() || config.get_color_info().get_bit_depth() >= 10 {
2659                VideoPixelFormat::P010
2660            } else {
2661                VideoPixelFormat::Nv12
2662            };
2663        self.set_pixel_format(fmt);
2664        Ok(())
2665    }
2666
2667    /// Emits a zero-copy `VideoGpuSurfaceHandle` backed frame without touching the CPU frame pool.
2668    ///
2669    /// # Arguments
2670    ///
2671    /// - `&Self` - Mutable hardware decoder.
2672    /// - `&EncodedVideoPacket` - Demuxed video packet.
2673    /// - `&VideoFramePool` - Unused CPU pool (zero CPU allocation on hardware zero-copy path).
2674    ///
2675    /// # Returns
2676    ///
2677    /// - `Result<Option<DecodedVideoFrame>, String>` - GPU-surface-backed decoded frame.
2678    fn decode_packet(
2679        &mut self,
2680        packet: &EncodedVideoPacket,
2681        _pool: &VideoFramePool,
2682    ) -> Result<Option<DecodedVideoFrame>, String> {
2683        let config: VideoDecoderConfig = self.get_config();
2684        let surface_id: u64 = self.get_next_surface_id();
2685        self.set_next_surface_id(surface_id.saturating_add(1));
2686        let fence_value: u64 = self.get_next_fence_value();
2687        self.set_next_fence_value(fence_value.saturating_add(1));
2688        let handle: VideoGpuSurfaceHandle = VideoGpuSurfaceHandle {
2689            surface_id,
2690            device_id: self.get_device_id(),
2691            generation: packet.get_generation(),
2692            width: config.get_width(),
2693            height: config.get_height(),
2694            pixel_format: self.get_pixel_format(),
2695            color_info: config.get_color_info(),
2696            fence_value,
2697            zero_copy: true,
2698            backend: self.get_kind(),
2699        };
2700        Ok(Some(DecodedVideoFrame {
2701            sample_index: packet.get_sample_index(),
2702            generation: packet.get_generation(),
2703            dts_us: packet.get_dts_us(),
2704            pts_us: packet.get_pts_us(),
2705            duration_us: packet.get_duration_us(),
2706            width: config.get_width(),
2707            height: config.get_height(),
2708            color_info: config.get_color_info(),
2709            backing: VideoFrameBacking::GpuSurface(handle),
2710        }))
2711    }
2712
2713    /// Resets hardware decoder reorder state on seek.
2714    ///
2715    /// # Arguments
2716    ///
2717    /// - `&Self` - Mutable hardware decoder.
2718    fn flush(&mut self) {}
2719}
2720
2721/// Bounded PTS-ordered insertion, seek-generation draining, and due-frame retrieval for `PtsFrameQueue`.
2722impl PtsFrameQueue {
2723    /// Creates a bounded `PtsFrameQueue` retaining at most `capacity` decoded frames.
2724    ///
2725    /// # Arguments
2726    ///
2727    /// - `usize` - Maximum queued frame count (`>= 1`).
2728    ///
2729    /// # Returns
2730    ///
2731    /// - `Self` - Empty bounded queue.
2732    #[must_use]
2733    pub fn with_capacity(capacity: usize) -> Self {
2734        let cap: usize = capacity.max(1);
2735        Self {
2736            capacity: cap,
2737            frames: VecDeque::with_capacity(cap),
2738            stale_generation_drops: 0,
2739        }
2740    }
2741
2742    /// Returns `true` when the queue is at its bounded capacity.
2743    ///
2744    /// # Arguments
2745    ///
2746    /// - `&Self` - Queue reference.
2747    ///
2748    /// # Returns
2749    ///
2750    /// - `bool` - `true` when `len() >= capacity`.
2751    #[must_use]
2752    pub fn is_full(&self) -> bool {
2753        self.get_frames().len() >= self.get_capacity()
2754    }
2755
2756    /// Returns the number of frames currently buffered in the queue.
2757    ///
2758    /// # Arguments
2759    ///
2760    /// - `&Self` - Queue reference.
2761    ///
2762    /// # Returns
2763    ///
2764    /// - `usize` - Queued frame count.
2765    #[must_use]
2766    pub fn len(&self) -> usize {
2767        self.get_frames().len()
2768    }
2769
2770    /// Returns `true` when no frames are queued.
2771    ///
2772    /// # Arguments
2773    ///
2774    /// - `&Self` - Queue reference.
2775    ///
2776    /// # Returns
2777    ///
2778    /// - `bool` - `true` iff empty.
2779    #[must_use]
2780    pub fn is_empty(&self) -> bool {
2781        self.get_frames().is_empty()
2782    }
2783
2784    /// Inserts `frame` in ascending `pts_us` order (reordering B-frames automatically), returning `Some(frame)` if the bounded queue is full.
2785    ///
2786    /// # Arguments
2787    ///
2788    /// - `&Self` - Mutable PTS queue.
2789    /// - `DecodedVideoFrame` - Frame to insert.
2790    ///
2791    /// # Returns
2792    ///
2793    /// - `Option<DecodedVideoFrame>` - `None` when inserted, or `Some(frame)` when queue is at bounded capacity.
2794    pub fn push_ordered(&mut self, frame: DecodedVideoFrame) -> Option<DecodedVideoFrame> {
2795        if self.is_full() {
2796            return Some(frame);
2797        }
2798        let target_pts: i64 = frame.get_pts_us();
2799        let frames: &mut VecDeque<DecodedVideoFrame> = self.get_mut_frames();
2800        if frames
2801            .back()
2802            .is_none_or(|last: &DecodedVideoFrame| last.get_pts_us() <= target_pts)
2803        {
2804            frames.push_back(frame);
2805            return None;
2806        }
2807        let mut lo: usize = 0;
2808        let mut hi: usize = frames.len();
2809        while lo < hi {
2810            let mid: usize = lo + ((hi - lo) >> 1);
2811            if frames[mid].get_pts_us() <= target_pts {
2812                lo = mid + 1;
2813            } else {
2814                hi = mid;
2815            }
2816        }
2817        frames.insert(lo, frame);
2818        None
2819    }
2820
2821    /// Peeks the earliest presentation timestamp currently waiting at the front of the queue.
2822    ///
2823    /// # Arguments
2824    ///
2825    /// - `&Self` - Queue reference.
2826    ///
2827    /// # Returns
2828    ///
2829    /// - `Option<i64>` - Front frame PTS in microseconds, if any.
2830    #[must_use]
2831    pub fn peek_front_pts_us(&self) -> Option<i64> {
2832        self.get_frames()
2833            .front()
2834            .map(|f: &DecodedVideoFrame| f.get_pts_us())
2835    }
2836
2837    /// Returns `true` when at least one buffered frame has a generation different from `active_generation`.
2838    ///
2839    /// # Arguments
2840    ///
2841    /// - `&Self` - Queue reference.
2842    /// - `u64` - Active seek generation.
2843    ///
2844    /// # Returns
2845    ///
2846    /// - `bool` - `true` when stale-generation frames are present.
2847    #[must_use]
2848    pub fn has_stale_generation(&self, active_generation: u64) -> bool {
2849        self.get_frames()
2850            .iter()
2851            .any(|frame: &DecodedVideoFrame| frame.get_generation() != active_generation)
2852    }
2853
2854    /// Removes and recycles every queued frame whose `generation != active_generation` in place with zero heap allocations.
2855    ///
2856    /// # Arguments
2857    ///
2858    /// - `&Self` - Mutable PTS queue.
2859    /// - `u64` - Active seek generation.
2860    /// - `&VideoFramePool` - Pool receiving recycled CPU buffers.
2861    ///
2862    /// # Returns
2863    ///
2864    /// - `usize` - Number of stale frames drained.
2865    pub fn drain_stale_generations(
2866        &mut self,
2867        active_generation: u64,
2868        pool: &VideoFramePool,
2869    ) -> usize {
2870        if !self.has_stale_generation(active_generation) {
2871            return 0;
2872        }
2873        let mut drained: usize = 0;
2874        self.get_mut_frames()
2875            .retain_mut(|frame: &mut DecodedVideoFrame| {
2876                if frame.get_generation() == active_generation {
2877                    return true;
2878                }
2879                let DecodedVideoFrame { backing, .. } = frame;
2880                if let VideoFrameBacking::CpuPooled(pooled) = backing {
2881                    let recycled: PooledVideoFrame = take(pooled);
2882                    pool.recycle(recycled);
2883                }
2884                drained += 1;
2885                false
2886            });
2887        let next_drops: u64 = self
2888            .get_stale_generation_drops()
2889            .saturating_add(drained as u64);
2890        self.set_stale_generation_drops(next_drops);
2891        drained
2892    }
2893
2894    /// Drains all queued frames and recycles any CPU-pooled buffers back into `pool` while preserving queue capacity.
2895    ///
2896    /// # Arguments
2897    ///
2898    /// - `&Self` - Mutable PTS queue.
2899    /// - `&VideoFramePool` - Pool receiving recycled CPU buffers.
2900    pub fn clear_and_recycle(&mut self, pool: &VideoFramePool) {
2901        let frames: &mut VecDeque<DecodedVideoFrame> = self.get_mut_frames();
2902        while let Some(frame) = frames.pop_front() {
2903            pool.recycle_decoded_frame(frame);
2904        }
2905    }
2906}
2907
2908/// Audio-master / monotonic clock A/V synchronization and cadence-preserving frame selection for `AvSyncScheduler`.
2909impl AvSyncScheduler {
2910    /// Creates an initialized `AvSyncScheduler` starting at `0 us` with `1.0x` playback rate.
2911    ///
2912    /// # Returns
2913    ///
2914    /// - `Self` - Ready scheduler.
2915    #[must_use]
2916    pub fn new_default() -> Self {
2917        Self {
2918            clock_source: AvSyncClockSource::MonotonicFallback,
2919            clock_pts_us: 0,
2920            playback_rate: 1.0,
2921            max_late_us: VIDEO_DEFAULT_MAX_LATE_US,
2922            last_presented_pts_us: None,
2923            frames_presented: 0,
2924            frames_held_vsync: 0,
2925            frames_dropped_late: 0,
2926        }
2927    }
2928
2929    /// Returns the PTS in microseconds of the most recently presented frame.
2930    ///
2931    /// # Arguments
2932    ///
2933    /// - `&Self` - Scheduler reference.
2934    ///
2935    /// # Returns
2936    ///
2937    /// - `Option<i64>` - Last presented PTS or `None`.
2938    #[must_use]
2939    pub const fn last_presented_pts_us(&self) -> Option<i64> {
2940        let Self {
2941            last_presented_pts_us,
2942            ..
2943        } = *self;
2944        last_presented_pts_us
2945    }
2946
2947    /// Switches to `AudioMaster` synchronization and updates the active clock position from hardware audio playback.
2948    ///
2949    /// # Arguments
2950    ///
2951    /// - `&Self` - Mutable scheduler.
2952    /// - `i64` - Current hardware audio playback timestamp in microseconds.
2953    pub fn update_audio_clock_us(&mut self, audio_pts_us: i64) {
2954        self.set_clock_source(AvSyncClockSource::AudioMaster);
2955        self.set_clock_pts_us(audio_pts_us.max(0));
2956    }
2957
2958    /// Advances the fallback monotonic clock by `delta_us * playback_rate` when audio master is inactive or muted.
2959    ///
2960    /// # Arguments
2961    ///
2962    /// - `&Self` - Mutable scheduler.
2963    /// - `u64` - Elapsed wall display delta in microseconds.
2964    pub fn advance_monotonic_us(&mut self, delta_us: u64) {
2965        self.set_clock_source(AvSyncClockSource::MonotonicFallback);
2966        let rate: f64 = (self.get_playback_rate().clamp(0.25, 4.0)) as f64;
2967        let scaled: i64 = ((delta_us as f64) * rate).round() as i64;
2968        let next_clock: i64 = self.get_clock_pts_us().saturating_add(scaled.max(0));
2969        self.set_clock_pts_us(next_clock);
2970    }
2971
2972    /// Resets the scheduler clock directly to `target_pts_us` after a seek discontinuity.
2973    ///
2974    /// # Arguments
2975    ///
2976    /// - `&Self` - Mutable scheduler.
2977    /// - `i64` - New target playback timestamp in microseconds.
2978    pub fn reset_for_seek(&mut self, target_pts_us: i64) {
2979        self.set_clock_pts_us(target_pts_us.max(0));
2980        let Self {
2981            last_presented_pts_us,
2982            ..
2983        } = self;
2984        *last_presented_pts_us = None;
2985    }
2986
2987    /// Selects the frame due for presentation on the current VSync tick without ever forging new frames when display Hz exceeds video FPS.
2988    ///
2989    /// # Arguments
2990    ///
2991    /// - `&Self` - Mutable scheduler.
2992    /// - `&mut PtsFrameQueue` - Bounded PTS-ordered decoded frame queue.
2993    /// - `&VideoFramePool` - Pool receiving any dropped late CPU frames.
2994    /// - `bool` - Whether the decoder has reached end-of-stream.
2995    /// - `bool` - Whether a frame is already currently displayed on screen.
2996    ///
2997    /// # Returns
2998    ///
2999    /// - `VideoPresentDecision` - `PresentNewFrame`, `HoldCurrentFrame`, `Buffering`, or `Ended`.
3000    pub fn select_frame_for_vsync(
3001        &mut self,
3002        queue: &mut PtsFrameQueue,
3003        pool: &VideoFramePool,
3004        reached_eos: bool,
3005        has_displayed_frame: bool,
3006    ) -> VideoPresentDecision {
3007        let clock_us: i64 = self.get_clock_pts_us();
3008        let Some(front_pts) = queue.peek_front_pts_us() else {
3009            if reached_eos {
3010                return VideoPresentDecision::Ended;
3011            }
3012            if has_displayed_frame {
3013                let next_held: u64 = self.get_frames_held_vsync().saturating_add(1);
3014                self.set_frames_held_vsync(next_held);
3015                return VideoPresentDecision::HoldCurrentFrame;
3016            }
3017            return VideoPresentDecision::Buffering;
3018        };
3019        if front_pts > clock_us.saturating_add(VIDEO_PRESENT_TOLERANCE_US) {
3020            let next_held: u64 = self.get_frames_held_vsync().saturating_add(1);
3021            self.set_frames_held_vsync(next_held);
3022            return VideoPresentDecision::HoldCurrentFrame;
3023        }
3024        let mut due_count: usize = 0;
3025        for frame in queue.get_frames().iter() {
3026            if frame.get_pts_us() <= clock_us.saturating_add(VIDEO_PRESENT_TOLERANCE_US) {
3027                due_count += 1;
3028            } else {
3029                break;
3030            }
3031        }
3032        let max_late: i64 = self.get_max_late_us().max(0);
3033        let mut chosen: Option<DecodedVideoFrame> = None;
3034        let mut dropped: u64 = 0;
3035        for idx in 0..due_count {
3036            let Some(frame) = queue.get_mut_frames().pop_front() else {
3037                break;
3038            };
3039            let is_last_due: bool = idx + 1 == due_count;
3040            let lateness: i64 = clock_us.saturating_sub(frame.get_pts_us());
3041            if !is_last_due {
3042                let _: bool = lateness > max_late;
3043                pool.recycle_decoded_frame(frame);
3044                dropped = dropped.saturating_add(1);
3045            } else {
3046                chosen = Some(frame);
3047            }
3048        }
3049        if dropped > 0 {
3050            let next_dropped: u64 = self.get_frames_dropped_late().saturating_add(dropped);
3051            self.set_frames_dropped_late(next_dropped);
3052        }
3053        if let Some(frame) = chosen {
3054            let pts: i64 = frame.get_pts_us();
3055            let Self {
3056                last_presented_pts_us,
3057                ..
3058            } = self;
3059            *last_presented_pts_us = Some(pts);
3060            let next_presented: u64 = self.get_frames_presented().saturating_add(1);
3061            self.set_frames_presented(next_presented);
3062            VideoPresentDecision::PresentNewFrame(frame)
3063        } else if reached_eos {
3064            VideoPresentDecision::Ended
3065        } else {
3066            VideoPresentDecision::HoldCurrentFrame
3067        }
3068    }
3069}
3070
3071/// Multi-threaded (native) / deterministic pumpable (wasm32) structured video playback pipeline implementation.
3072impl VideoPlaybackPipeline {
3073    /// Opens an MP4 byte stream using the pure-Rust `SoftwareVideoDecoder` fallback and bounded queue/pool capacities.
3074    ///
3075    /// # Arguments
3076    ///
3077    /// - `B` - Complete MP4 container bytes convertible into `Arc<[u8]>`.
3078    ///
3079    /// # Returns
3080    ///
3081    /// - `Result<Self, String>` - Initialized video playback pipeline or parse/config error.
3082    pub fn from_mp4_bytes<B>(bytes: B) -> Result<Self, String>
3083    where
3084        B: Into<Arc<[u8]>>,
3085    {
3086        Self::from_mp4_with_backend(
3087            bytes,
3088            Box::new(SoftwareVideoDecoder::default()),
3089            VIDEO_DEFAULT_QUEUE_CAPACITY,
3090            VIDEO_DEFAULT_POOL_CAPACITY,
3091        )
3092    }
3093
3094    /// Opens an MP4 byte stream using a custom hardware or software `VideoDecoderBackend`.
3095    ///
3096    /// # Arguments
3097    ///
3098    /// - `B` - Complete MP4 container bytes convertible into `Arc<[u8]>`.
3099    /// - `Box<dyn VideoDecoderBackend>` - Hardware zero-copy or software decoder backend.
3100    /// - `usize` - Bounded PTS frame queue capacity.
3101    /// - `usize` - Bounded CPU RGBA8 frame pool capacity.
3102    ///
3103    /// # Returns
3104    ///
3105    /// - `Result<Self, String>` - Initialized video playback pipeline or error.
3106    pub fn from_mp4_with_backend<B>(
3107        bytes: B,
3108        mut decoder: Box<dyn VideoDecoderBackend>,
3109        queue_capacity: usize,
3110        pool_capacity: usize,
3111    ) -> Result<Self, String>
3112    where
3113        B: Into<Arc<[u8]>>,
3114    {
3115        let demuxer: Arc<Mp4Demuxer> = Arc::new(Mp4Demuxer::parse(bytes)?);
3116        let config: VideoDecoderConfig = demuxer.video_decoder_config();
3117        decoder.configure(&config)?;
3118        let backend_kind: HardwareDecoderKind = decoder.backend_kind();
3119        let color_info: VideoColorInfo = config.get_color_info();
3120        let pool: VideoFramePool = VideoFramePool::with_capacity(pool_capacity);
3121        let scheduler: AvSyncScheduler = AvSyncScheduler::new_default();
3122        #[cfg(not(target_arch = "wasm32"))]
3123        {
3124            let initial_eos: bool = demuxer.video_sample_count() == 0;
3125            let shared_state: VideoWorkerShared = VideoWorkerShared {
3126                queue: PtsFrameQueue::with_capacity(queue_capacity),
3127                active_generation: 1,
3128                next_sample_index: 0,
3129                seek_preroll_target_us: 0,
3130                pending_seek: None,
3131                playing: true,
3132                reached_eos: initial_eos,
3133                shutdown: false,
3134                packets_decoded: 0,
3135                seek_preroll_frames_discarded: 0,
3136                last_error: None,
3137            };
3138            let initial_hint: u64 = if initial_eos {
3139                VIDEO_FAST_HOLD_NONE
3140            } else {
3141                VIDEO_FAST_HOLD_COVERED
3142            };
3143            let worker_shared: Arc<(Mutex<VideoWorkerShared>, Condvar, AtomicU64)> = Arc::new((
3144                Mutex::new(shared_state),
3145                Condvar::new(),
3146                AtomicU64::new(initial_hint),
3147            ));
3148            let worker_shared_clone: Arc<(Mutex<VideoWorkerShared>, Condvar, AtomicU64)> =
3149                Arc::clone(&worker_shared);
3150            let worker_demuxer: Arc<Mp4Demuxer> = Arc::clone(&demuxer);
3151            let worker_pool: VideoFramePool = pool.clone();
3152            let handle_opt: Option<JoinHandle<()>> = Builder::new()
3153                .name(VIDEO_WORKER_THREAD_NAME.to_string())
3154                .spawn(move || {
3155                    Self::worker_loop(worker_demuxer, decoder, worker_pool, worker_shared_clone);
3156                })
3157                .ok();
3158            Ok(Self {
3159                demuxer,
3160                pool,
3161                scheduler,
3162                backend_kind,
3163                color_info,
3164                state: PlaybackState::Playing,
3165                current_frame: None,
3166                active_generation: 1,
3167                worker_shared,
3168                worker_handle: handle_opt,
3169            })
3170        }
3171        #[cfg(target_arch = "wasm32")]
3172        {
3173            let reached_eos: bool = demuxer.video_sample_count() == 0;
3174            Ok(Self {
3175                demuxer,
3176                pool,
3177                scheduler,
3178                backend_kind,
3179                color_info,
3180                state: PlaybackState::Playing,
3181                current_frame: None,
3182                active_generation: 1,
3183                wasm_decoder: decoder,
3184                wasm_queue: PtsFrameQueue::with_capacity(queue_capacity),
3185                wasm_next_sample: 0,
3186                wasm_preroll_target_us: 0,
3187                wasm_eos: reached_eos,
3188                wasm_packets_decoded: 0,
3189                wasm_preroll_discarded: 0,
3190                wasm_last_error: None,
3191            })
3192        }
3193    }
3194
3195    /// Publishes an atomic fast-hold hint summarizing the queue's front PTS, pending seek state, and EOS status.
3196    ///
3197    /// # Arguments
3198    ///
3199    /// - `&VideoWorkerShared` - Locked worker coordination state.
3200    /// - `&AtomicU64` - Atomic fast-hold hint updated with `Release` ordering.
3201    #[cfg(not(target_arch = "wasm32"))]
3202    fn sync_fast_hold_hint(guard: &VideoWorkerShared, hint: &AtomicU64) {
3203        let VideoWorkerShared { pending_seek, .. } = guard;
3204        let active_gen: u64 = guard.get_active_generation();
3205        let queue: &PtsFrameQueue = guard.get_queue();
3206        let next_hint: u64 = if pending_seek.is_some() || queue.has_stale_generation(active_gen) {
3207            VIDEO_FAST_HOLD_NONE
3208        } else if let Some(front_pts) = queue.peek_front_pts_us() {
3209            if front_pts >= 0 && (front_pts as u64) < VIDEO_FAST_HOLD_COVERED {
3210                front_pts as u64
3211            } else {
3212                VIDEO_FAST_HOLD_NONE
3213            }
3214        } else if guard.get_reached_eos() {
3215            VIDEO_FAST_HOLD_NONE
3216        } else {
3217            VIDEO_FAST_HOLD_COVERED
3218        };
3219        hint.store(next_hint, Ordering::Release);
3220    }
3221
3222    /// Background decode thread loop draining MP4 packets into the bounded PTS-ordered queue.
3223    ///
3224    /// # Arguments
3225    ///
3226    /// - `Arc<Mp4Demuxer>` - Shared zero-copy container demuxer.
3227    /// - `Box<dyn VideoDecoderBackend>` - Owned hardware or software decoder.
3228    /// - `VideoFramePool` - Shared bounded CPU frame pool.
3229    /// - `Arc<(Mutex<VideoWorkerShared>, Condvar, AtomicU64)>` - Shared queue, condvar, and fast-hold hint.
3230    #[cfg(not(target_arch = "wasm32"))]
3231    fn worker_loop(
3232        demuxer: Arc<Mp4Demuxer>,
3233        mut decoder: Box<dyn VideoDecoderBackend>,
3234        pool: VideoFramePool,
3235        shared: Arc<(Mutex<VideoWorkerShared>, Condvar, AtomicU64)>,
3236    ) {
3237        let total_samples: usize = demuxer.video_sample_count();
3238        loop {
3239            let work_item: Option<(usize, u64, i64)> = {
3240                let mut guard: MutexGuard<'_, VideoWorkerShared> = shared.0.lock().unwrap_or_else(
3241                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3242                );
3243                loop {
3244                    if guard.get_shutdown() {
3245                        return;
3246                    }
3247                    let pending_seek: Option<(u64, usize, i64)> = {
3248                        let VideoWorkerShared { pending_seek, .. } = &mut *guard;
3249                        pending_seek.take()
3250                    };
3251                    if let Some((new_gen, kf_idx, target_pts)) = pending_seek {
3252                        decoder.flush();
3253                        let _: usize = guard
3254                            .get_mut_queue()
3255                            .drain_stale_generations(new_gen, &pool);
3256                        guard.set_active_generation(new_gen);
3257                        guard.set_next_sample_index(kf_idx);
3258                        guard.set_seek_preroll_target_us(target_pts);
3259                        guard.set_reached_eos(kf_idx >= total_samples);
3260                        let VideoWorkerShared { last_error, .. } = &mut *guard;
3261                        *last_error = None;
3262                        Self::sync_fast_hold_hint(&guard, &shared.2);
3263                    }
3264                    let can_decode: bool = guard.get_playing()
3265                        && !guard.get_reached_eos()
3266                        && !guard.get_queue().is_full()
3267                        && guard.get_next_sample_index() < total_samples;
3268                    if can_decode {
3269                        let idx: usize = guard.get_next_sample_index();
3270                        let gen_id: u64 = guard.get_active_generation();
3271                        let target_pts: i64 = guard.get_seek_preroll_target_us();
3272                        guard.set_next_sample_index(idx.saturating_add(1));
3273                        break Some((idx, gen_id, target_pts));
3274                    }
3275                    guard = shared.1.wait(guard).unwrap_or_else(
3276                        |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3277                    );
3278                }
3279            };
3280            let Some((sample_idx, packet_gen, preroll_target_us)) = work_item else {
3281                continue;
3282            };
3283            let Some(packet) = demuxer.read_video_packet(sample_idx, packet_gen) else {
3284                let mut guard: MutexGuard<'_, VideoWorkerShared> = shared.0.lock().unwrap_or_else(
3285                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3286                );
3287                if guard.get_active_generation() == packet_gen {
3288                    guard.set_reached_eos(true);
3289                    Self::sync_fast_hold_hint(&guard, &shared.2);
3290                }
3291                shared.1.notify_all();
3292                continue;
3293            };
3294            let decode_res: Result<Option<DecodedVideoFrame>, String> =
3295                decoder.decode_packet(&packet, &pool);
3296            let mut guard: MutexGuard<'_, VideoWorkerShared> = shared.0.lock().unwrap_or_else(
3297                |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3298            );
3299            if guard.get_active_generation() != packet_gen || guard.get_shutdown() {
3300                if let Ok(Some(stale)) = decode_res {
3301                    pool.recycle_decoded_frame(stale);
3302                }
3303                Self::sync_fast_hold_hint(&guard, &shared.2);
3304                shared.1.notify_all();
3305                continue;
3306            }
3307            match decode_res {
3308                Ok(Some(frame)) => {
3309                    let next_decoded: u64 = guard.get_packets_decoded().saturating_add(1);
3310                    guard.set_packets_decoded(next_decoded);
3311                    if frame.get_pts_us() < preroll_target_us && sample_idx + 1 < total_samples {
3312                        pool.recycle_decoded_frame(frame);
3313                        let next_disc: u64 =
3314                            guard.get_seek_preroll_frames_discarded().saturating_add(1);
3315                        guard.set_seek_preroll_frames_discarded(next_disc);
3316                    } else if let Some(rejected) = guard.get_mut_queue().push_ordered(frame) {
3317                        pool.recycle_decoded_frame(rejected);
3318                    }
3319                }
3320                Ok(None) => {}
3321                Err(msg) => {
3322                    let VideoWorkerShared { last_error, .. } = &mut *guard;
3323                    *last_error = Some(msg);
3324                    guard.set_reached_eos(true);
3325                }
3326            }
3327            if sample_idx + 1 >= total_samples {
3328                guard.set_reached_eos(true);
3329            }
3330            Self::sync_fast_hold_hint(&guard, &shared.2);
3331            shared.1.notify_all();
3332        }
3333    }
3334
3335    /// Returns a reference to the parsed MP4 demuxer.
3336    ///
3337    /// # Arguments
3338    ///
3339    /// - `&Self` - Pipeline reference.
3340    ///
3341    /// # Returns
3342    ///
3343    /// - `&Mp4Demuxer` - Demuxer reference.
3344    #[must_use]
3345    pub fn demuxer(&self) -> &Mp4Demuxer {
3346        let Self { demuxer, .. } = self;
3347        demuxer.as_ref()
3348    }
3349
3350    /// Returns a reference to the bounded CPU video frame pool.
3351    ///
3352    /// # Arguments
3353    ///
3354    /// - `&Self` - Pipeline reference.
3355    ///
3356    /// # Returns
3357    ///
3358    /// - `&VideoFramePool` - Frame pool reference.
3359    #[must_use]
3360    pub fn frame_pool(&self) -> &VideoFramePool {
3361        let Self { pool, .. } = self;
3362        pool
3363    }
3364
3365    /// Returns a reference to the active A/V synchronization scheduler.
3366    ///
3367    /// # Arguments
3368    ///
3369    /// - `&Self` - Pipeline reference.
3370    ///
3371    /// # Returns
3372    ///
3373    /// - `&AvSyncScheduler` - Scheduler reference.
3374    #[must_use]
3375    pub fn scheduler(&self) -> &AvSyncScheduler {
3376        let Self { scheduler, .. } = self;
3377        scheduler
3378    }
3379
3380    /// Returns a mutable reference to the A/V synchronization scheduler.
3381    ///
3382    /// # Arguments
3383    ///
3384    /// - `&Self` - Mutable pipeline.
3385    ///
3386    /// # Returns
3387    ///
3388    /// - `&mut AvSyncScheduler` - Mutable scheduler reference.
3389    pub fn scheduler_mut(&mut self) -> &mut AvSyncScheduler {
3390        let Self { scheduler, .. } = self;
3391        scheduler
3392    }
3393
3394    /// Returns the active decoder backend kind (`VideoToolbox`, `MediaCodec`, `Vaapi`, `Dxva`, `WebCodecs`, or `SoftwareFallback`).
3395    ///
3396    /// # Arguments
3397    ///
3398    /// - `&Self` - Pipeline reference.
3399    ///
3400    /// # Returns
3401    ///
3402    /// - `HardwareDecoderKind` - Active backend kind.
3403    #[must_use]
3404    pub const fn backend_kind(&self) -> HardwareDecoderKind {
3405        let Self { backend_kind, .. } = *self;
3406        backend_kind
3407    }
3408
3409    /// Returns preserved color primaries, transfer curve, matrix, range, and HDR metadata.
3410    ///
3411    /// # Arguments
3412    ///
3413    /// - `&Self` - Pipeline reference.
3414    ///
3415    /// # Returns
3416    ///
3417    /// - `VideoColorInfo` - Track color and HDR metadata.
3418    #[must_use]
3419    pub const fn color_info(&self) -> VideoColorInfo {
3420        let Self { color_info, .. } = *self;
3421        color_info
3422    }
3423
3424    /// Returns the active transport playback state.
3425    ///
3426    /// # Arguments
3427    ///
3428    /// - `&Self` - Pipeline reference.
3429    ///
3430    /// # Returns
3431    ///
3432    /// - `PlaybackState` - Current playback state.
3433    #[must_use]
3434    pub const fn playback_state(&self) -> PlaybackState {
3435        let Self { state, .. } = *self;
3436        state
3437    }
3438
3439    /// Returns the currently displayed decoded frame, if any.
3440    ///
3441    /// # Arguments
3442    ///
3443    /// - `&Self` - Pipeline reference.
3444    ///
3445    /// # Returns
3446    ///
3447    /// - `Option<&DecodedVideoFrame>` - Active frame reference.
3448    #[must_use]
3449    pub fn current_frame(&self) -> Option<&DecodedVideoFrame> {
3450        let Self { current_frame, .. } = self;
3451        current_frame.as_ref()
3452    }
3453
3454    /// Returns the active seek generation counter.
3455    ///
3456    /// # Arguments
3457    ///
3458    /// - `&Self` - Pipeline reference.
3459    ///
3460    /// # Returns
3461    ///
3462    /// - `u64` - Active generation counter.
3463    #[must_use]
3464    pub const fn active_generation(&self) -> u64 {
3465        let Self {
3466            active_generation, ..
3467        } = *self;
3468        active_generation
3469    }
3470
3471    /// Resumes background decoding and playback.
3472    ///
3473    /// # Arguments
3474    ///
3475    /// - `&Self` - Mutable pipeline.
3476    pub fn play(&mut self) {
3477        let Self { state, .. } = self;
3478        *state = PlaybackState::Playing;
3479        #[cfg(not(target_arch = "wasm32"))]
3480        {
3481            let Self { worker_shared, .. } = self;
3482            let mut guard: MutexGuard<'_, VideoWorkerShared> =
3483                worker_shared.0.lock().unwrap_or_else(
3484                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3485                );
3486            guard.set_playing(true);
3487            worker_shared.1.notify_all();
3488        }
3489    }
3490
3491    /// Pauses playback and suspends background worker decoding until resumed.
3492    ///
3493    /// # Arguments
3494    ///
3495    /// - `&Self` - Mutable pipeline.
3496    pub fn pause(&mut self) {
3497        let Self { state, .. } = self;
3498        *state = PlaybackState::Paused;
3499        #[cfg(not(target_arch = "wasm32"))]
3500        {
3501            let Self { worker_shared, .. } = self;
3502            let mut guard: MutexGuard<'_, VideoWorkerShared> =
3503                worker_shared.0.lock().unwrap_or_else(
3504                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3505                );
3506            guard.set_playing(false);
3507            worker_shared.1.notify_all();
3508        }
3509    }
3510
3511    /// Executes a generation-tagged seek: drains stale frames, rewinds demuxer to the preceding keyframe, flushes decoder, and prerolls to `target_pts_us`.
3512    ///
3513    /// # Arguments
3514    ///
3515    /// - `&Self` - Mutable pipeline.
3516    /// - `i64` - Target presentation timestamp in microseconds.
3517    ///
3518    /// # Returns
3519    ///
3520    /// - `u64` - Newly incremented generation identifier.
3521    pub fn seek_us(&mut self, target_pts_us: i64) -> u64 {
3522        let clamped_target: i64 = target_pts_us.max(0);
3523        let keyframe_idx: usize = self.demuxer().seek_keyframe_index(clamped_target);
3524        let next_gen: u64 = {
3525            let Self {
3526                active_generation,
3527                scheduler,
3528                current_frame,
3529                pool,
3530                state,
3531                ..
3532            } = self;
3533            *active_generation = active_generation.saturating_add(1);
3534            scheduler.reset_for_seek(clamped_target);
3535            if let Some(old_frame) = current_frame.take() {
3536                pool.recycle_decoded_frame(old_frame);
3537            }
3538            if *state == PlaybackState::Ended {
3539                *state = PlaybackState::Playing;
3540            }
3541            *active_generation
3542        };
3543        #[cfg(not(target_arch = "wasm32"))]
3544        {
3545            let Self {
3546                worker_shared,
3547                pool,
3548                ..
3549            } = self;
3550            let mut guard: MutexGuard<'_, VideoWorkerShared> =
3551                worker_shared.0.lock().unwrap_or_else(
3552                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3553                );
3554            let _: usize = guard
3555                .get_mut_queue()
3556                .drain_stale_generations(next_gen, pool);
3557            guard.set_active_generation(next_gen);
3558            guard.set_reached_eos(false);
3559            let VideoWorkerShared { pending_seek, .. } = &mut *guard;
3560            *pending_seek = Some((next_gen, keyframe_idx, clamped_target));
3561            Self::sync_fast_hold_hint(&guard, &worker_shared.2);
3562            worker_shared.1.notify_all();
3563        }
3564        #[cfg(target_arch = "wasm32")]
3565        {
3566            let Self {
3567                wasm_decoder,
3568                wasm_queue,
3569                wasm_next_sample,
3570                wasm_preroll_target_us,
3571                wasm_eos,
3572                wasm_last_error,
3573                pool,
3574                demuxer,
3575                ..
3576            } = self;
3577            wasm_decoder.flush();
3578            let _: usize = wasm_queue.drain_stale_generations(next_gen, pool);
3579            *wasm_next_sample = keyframe_idx;
3580            *wasm_preroll_target_us = clamped_target;
3581            *wasm_eos = keyframe_idx >= demuxer.video_sample_count();
3582            *wasm_last_error = None;
3583        }
3584        next_gen
3585    }
3586
3587    /// Waits on native targets (or pumps on wasm32) until at least `min_frames` frames of the active generation are queued or EOS/timeout occurs.
3588    ///
3589    /// # Arguments
3590    ///
3591    /// - `&Self` - Mutable pipeline.
3592    /// - `usize` - Minimum queued frames desired.
3593    /// - `u64` - Maximum wait timeout in milliseconds.
3594    ///
3595    /// # Returns
3596    ///
3597    /// - `usize` - Number of queued frames currently ready.
3598    pub fn wait_until_queued(&mut self, min_frames: usize, timeout_ms: u64) -> usize {
3599        #[cfg(not(target_arch = "wasm32"))]
3600        {
3601            let Self {
3602                worker_shared,
3603                active_generation,
3604                ..
3605            } = self;
3606            let active_gen: u64 = *active_generation;
3607            let deadline: Instant = Instant::now() + Duration::from_millis(timeout_ms);
3608            let mut guard: MutexGuard<'_, VideoWorkerShared> =
3609                worker_shared.0.lock().unwrap_or_else(
3610                    |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3611                );
3612            while (guard.get_queue().len() < min_frames || {
3613                let VideoWorkerShared { pending_seek, .. } = &*guard;
3614                pending_seek.is_some()
3615            }) && !guard.get_reached_eos()
3616                && guard.get_active_generation() == active_gen
3617            {
3618                let now: Instant = Instant::now();
3619                if now >= deadline {
3620                    break;
3621                }
3622                let rem: Duration = deadline.saturating_duration_since(now);
3623                guard = worker_shared
3624                    .1
3625                    .wait_timeout(guard, rem)
3626                    .unwrap_or_else(|err: PoisonError<(MutexGuard<'_, VideoWorkerShared>, _)>| {
3627                        err.into_inner()
3628                    })
3629                    .0;
3630            }
3631            guard.get_queue().len()
3632        }
3633        #[cfg(target_arch = "wasm32")]
3634        {
3635            let _: u64 = timeout_ms;
3636            let mut iterations: usize = 0;
3637            while self.queued_frame_count() < min_frames && !self.reached_eos() && iterations < 512
3638            {
3639                let _: bool = self.pump_decode_once();
3640                iterations += 1;
3641            }
3642            self.queued_frame_count()
3643        }
3644    }
3645
3646    /// Synchronously pumps one decode step on WebAssembly targets (returns `false` on native where the background thread runs continuously).
3647    ///
3648    /// # Arguments
3649    ///
3650    /// - `&Self` - Mutable pipeline.
3651    ///
3652    /// # Returns
3653    ///
3654    /// - `bool` - `true` if a packet was decoded on this pump call.
3655    pub fn pump_decode_once(&mut self) -> bool {
3656        #[cfg(not(target_arch = "wasm32"))]
3657        {
3658            false
3659        }
3660        #[cfg(target_arch = "wasm32")]
3661        {
3662            let Self {
3663                demuxer,
3664                pool,
3665                active_generation,
3666                wasm_decoder,
3667                wasm_queue,
3668                wasm_next_sample,
3669                wasm_preroll_target_us,
3670                wasm_eos,
3671                wasm_packets_decoded,
3672                wasm_preroll_discarded,
3673                wasm_last_error,
3674                ..
3675            } = self;
3676            let total: usize = demuxer.video_sample_count();
3677            if *wasm_eos || wasm_queue.is_full() || *wasm_next_sample >= total {
3678                if *wasm_next_sample >= total {
3679                    *wasm_eos = true;
3680                }
3681                return false;
3682            }
3683            let sample_idx: usize = *wasm_next_sample;
3684            *wasm_next_sample = sample_idx.saturating_add(1);
3685            let Some(packet) = demuxer.read_video_packet(sample_idx, *active_generation) else {
3686                *wasm_eos = true;
3687                return false;
3688            };
3689            match wasm_decoder.decode_packet(&packet, pool) {
3690                Ok(Some(frame)) => {
3691                    *wasm_packets_decoded = wasm_packets_decoded.saturating_add(1);
3692                    if frame.get_pts_us() < *wasm_preroll_target_us && sample_idx + 1 < total {
3693                        pool.recycle_decoded_frame(frame);
3694                        *wasm_preroll_discarded = wasm_preroll_discarded.saturating_add(1);
3695                    } else if let Some(rejected) = wasm_queue.push_ordered(frame) {
3696                        pool.recycle_decoded_frame(rejected);
3697                    }
3698                }
3699                Ok(None) => {}
3700                Err(msg) => {
3701                    *wasm_last_error = Some(msg);
3702                    *wasm_eos = true;
3703                }
3704            }
3705            if sample_idx + 1 >= total {
3706                *wasm_eos = true;
3707            }
3708            true
3709        }
3710    }
3711
3712    /// 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.
3713    ///
3714    /// # Arguments
3715    ///
3716    /// - `&Self` - Mutable pipeline.
3717    /// - `Option<i64>` - Optional hardware audio master timestamp in microseconds (`None` uses monotonic `vsync_dt_us`).
3718    /// - `u64` - Elapsed display VSync interval in microseconds (`e.g. 6_944` at 144Hz or `16_667` at 60Hz).
3719    ///
3720    /// # Returns
3721    ///
3722    /// - `VideoPresentOutcome` - Whether a new frame replaced `current_frame()`, held current frame, buffered, or ended.
3723    pub fn present_vsync(
3724        &mut self,
3725        audio_master_pts_us: Option<i64>,
3726        vsync_dt_us: u64,
3727    ) -> VideoPresentOutcome {
3728        if self.playback_state() != PlaybackState::Playing {
3729            return VideoPresentOutcome::HoldCurrentFrame;
3730        }
3731        if let Some(audio_us) = audio_master_pts_us {
3732            self.scheduler_mut().update_audio_clock_us(audio_us);
3733        } else {
3734            self.scheduler_mut().advance_monotonic_us(vsync_dt_us);
3735        }
3736        let active_gen: u64 = self.active_generation();
3737        let due_deadline: i64 = self
3738            .scheduler()
3739            .get_clock_pts_us()
3740            .saturating_add(VIDEO_PRESENT_TOLERANCE_US);
3741        let fast_hold: bool = if let Some(cur) = self.current_frame()
3742            && cur.get_generation() == active_gen
3743        {
3744            let cur_dur: u64 = cur.get_duration_us();
3745            let cur_end_us: i64 = cur
3746                .get_pts_us()
3747                .saturating_add(i64::try_from(cur_dur).unwrap_or(i64::MAX));
3748            let covered_by_active: bool = cur_dur == 0 || due_deadline < cur_end_us;
3749            #[cfg(not(target_arch = "wasm32"))]
3750            {
3751                let Self { worker_shared, .. } = self;
3752                let hint: u64 = worker_shared.2.load(Ordering::Acquire);
3753                if hint == VIDEO_FAST_HOLD_NONE {
3754                    false
3755                } else if hint == VIDEO_FAST_HOLD_COVERED {
3756                    cur_dur > 0 && due_deadline < cur_end_us
3757                } else {
3758                    covered_by_active && due_deadline < (hint as i64)
3759                }
3760            }
3761            #[cfg(target_arch = "wasm32")]
3762            {
3763                let Self {
3764                    wasm_queue,
3765                    wasm_eos,
3766                    ..
3767                } = self;
3768                if wasm_queue.has_stale_generation(active_gen) {
3769                    false
3770                } else if let Some(front_pts) = wasm_queue.peek_front_pts_us() {
3771                    covered_by_active && due_deadline < front_pts
3772                } else {
3773                    !*wasm_eos && cur_dur > 0 && due_deadline < cur_end_us
3774                }
3775            }
3776        } else {
3777            false
3778        };
3779        if fast_hold {
3780            let next_held: u64 = self.scheduler().get_frames_held_vsync().saturating_add(1);
3781            self.scheduler_mut().set_frames_held_vsync(next_held);
3782            return VideoPresentOutcome::HoldCurrentFrame;
3783        }
3784        let has_displayed: bool = self.current_frame().is_some();
3785        #[cfg(not(target_arch = "wasm32"))]
3786        let decision: VideoPresentDecision = {
3787            let Self {
3788                worker_shared,
3789                scheduler,
3790                pool,
3791                ..
3792            } = self;
3793            let (res, freed_slot): (VideoPresentDecision, bool) = {
3794                let mut guard: MutexGuard<'_, VideoWorkerShared> =
3795                    worker_shared.0.lock().unwrap_or_else(
3796                        |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3797                    );
3798                let before_len: usize = guard.get_queue().len();
3799                let _: usize = guard
3800                    .get_mut_queue()
3801                    .drain_stale_generations(active_gen, pool);
3802                let pending_seek_active: bool = {
3803                    let VideoWorkerShared { pending_seek, .. } = &*guard;
3804                    pending_seek.is_some()
3805                };
3806                let eos: bool = !pending_seek_active && guard.get_reached_eos();
3807                let picked: VideoPresentDecision = scheduler.select_frame_for_vsync(
3808                    guard.get_mut_queue(),
3809                    pool,
3810                    eos,
3811                    has_displayed,
3812                );
3813                Self::sync_fast_hold_hint(&guard, &worker_shared.2);
3814                let slot_freed: bool = guard.get_queue().len() < before_len;
3815                (picked, slot_freed)
3816            };
3817            if freed_slot {
3818                worker_shared.1.notify_one();
3819            }
3820            res
3821        };
3822        #[cfg(target_arch = "wasm32")]
3823        let decision: VideoPresentDecision = {
3824            let Self {
3825                wasm_queue,
3826                wasm_eos,
3827                scheduler,
3828                pool,
3829                ..
3830            } = self;
3831            let _: usize = wasm_queue.drain_stale_generations(active_gen, pool);
3832            scheduler.select_frame_for_vsync(wasm_queue, pool, *wasm_eos, has_displayed)
3833        };
3834        match decision {
3835            VideoPresentDecision::PresentNewFrame(next_frame) => {
3836                let pts_us: i64 = next_frame.get_pts_us();
3837                let sample_index: usize = next_frame.get_sample_index();
3838                let generation: u64 = next_frame.get_generation();
3839                let zero_copy_gpu: bool = next_frame.gpu_surface().is_some();
3840                let Self {
3841                    current_frame,
3842                    pool,
3843                    ..
3844                } = self;
3845                if let Some(previous) = current_frame.replace(next_frame) {
3846                    pool.recycle_decoded_frame(previous);
3847                }
3848                VideoPresentOutcome::Presented {
3849                    pts_us,
3850                    sample_index,
3851                    generation,
3852                    zero_copy_gpu,
3853                }
3854            }
3855            VideoPresentDecision::HoldCurrentFrame => VideoPresentOutcome::HoldCurrentFrame,
3856            VideoPresentDecision::Buffering => VideoPresentOutcome::Buffering,
3857            VideoPresentDecision::Ended => {
3858                let Self { state, .. } = self;
3859                *state = PlaybackState::Ended;
3860                VideoPresentOutcome::Ended
3861            }
3862        }
3863    }
3864
3865    /// Returns the number of decoded frames currently buffered in the PTS queue.
3866    ///
3867    /// # Arguments
3868    ///
3869    /// - `&Self` - Pipeline reference.
3870    ///
3871    /// # Returns
3872    ///
3873    /// - `usize` - Queued frame count.
3874    #[must_use]
3875    pub fn queued_frame_count(&self) -> usize {
3876        #[cfg(not(target_arch = "wasm32"))]
3877        {
3878            let Self { worker_shared, .. } = self;
3879            let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3880                |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3881            );
3882            guard.get_queue().len()
3883        }
3884        #[cfg(target_arch = "wasm32")]
3885        {
3886            let Self { wasm_queue, .. } = self;
3887            wasm_queue.len()
3888        }
3889    }
3890
3891    /// Returns `true` when the decoder worker has reached end-of-stream for the active generation.
3892    ///
3893    /// # Arguments
3894    ///
3895    /// - `&Self` - Pipeline reference.
3896    ///
3897    /// # Returns
3898    ///
3899    /// - `bool` - `true` when end-of-stream has been reached.
3900    #[must_use]
3901    pub fn reached_eos(&self) -> bool {
3902        #[cfg(not(target_arch = "wasm32"))]
3903        {
3904            let Self { worker_shared, .. } = self;
3905            let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3906                |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3907            );
3908            guard.get_reached_eos()
3909        }
3910        #[cfg(target_arch = "wasm32")]
3911        {
3912            let Self { wasm_eos, .. } = self;
3913            *wasm_eos
3914        }
3915    }
3916
3917    /// Returns total packets decoded by the pipeline worker across playback and seeks.
3918    ///
3919    /// # Arguments
3920    ///
3921    /// - `&Self` - Pipeline reference.
3922    ///
3923    /// # Returns
3924    ///
3925    /// - `u64` - Total packets decoded.
3926    #[must_use]
3927    pub fn packets_decoded(&self) -> u64 {
3928        #[cfg(not(target_arch = "wasm32"))]
3929        {
3930            let Self { worker_shared, .. } = self;
3931            let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3932                |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3933            );
3934            guard.get_packets_decoded()
3935        }
3936        #[cfg(target_arch = "wasm32")]
3937        {
3938            let Self {
3939                wasm_packets_decoded,
3940                ..
3941            } = self;
3942            *wasm_packets_decoded
3943        }
3944    }
3945
3946    /// Returns total preroll frames decoded and discarded while advancing from a keyframe to a seek target PTS.
3947    ///
3948    /// # Arguments
3949    ///
3950    /// - `&Self` - Pipeline reference.
3951    ///
3952    /// # Returns
3953    ///
3954    /// - `u64` - Preroll frames discarded during seek catch-up.
3955    #[must_use]
3956    pub fn seek_preroll_frames_discarded(&self) -> u64 {
3957        #[cfg(not(target_arch = "wasm32"))]
3958        {
3959            let Self { worker_shared, .. } = self;
3960            let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3961                |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3962            );
3963            guard.get_seek_preroll_frames_discarded()
3964        }
3965        #[cfg(target_arch = "wasm32")]
3966        {
3967            let Self {
3968                wasm_preroll_discarded,
3969                ..
3970            } = self;
3971            *wasm_preroll_discarded
3972        }
3973    }
3974
3975    /// Returns the last worker decode error, if any occurred.
3976    ///
3977    /// # Arguments
3978    ///
3979    /// - `&Self` - Pipeline reference.
3980    ///
3981    /// # Returns
3982    ///
3983    /// - `Option<String>` - Error message when present.
3984    #[must_use]
3985    pub fn last_error(&self) -> Option<String> {
3986        #[cfg(not(target_arch = "wasm32"))]
3987        {
3988            let Self { worker_shared, .. } = self;
3989            let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3990                |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3991            );
3992            let VideoWorkerShared { last_error, .. } = &*guard;
3993            last_error.clone()
3994        }
3995        #[cfg(target_arch = "wasm32")]
3996        {
3997            let Self {
3998                wasm_last_error, ..
3999            } = self;
4000            wasm_last_error.clone()
4001        }
4002    }
4003}
4004
4005/// Clean shutdown and background thread join on `Drop` for `VideoPlaybackPipeline`.
4006impl Drop for VideoPlaybackPipeline {
4007    /// Signals the background decode worker to exit, recycles buffered CPU frames, and joins the worker thread cleanly.
4008    ///
4009    /// # Arguments
4010    ///
4011    /// - `&Self` - Mutable pipeline being dropped.
4012    fn drop(&mut self) {
4013        #[cfg(not(target_arch = "wasm32"))]
4014        {
4015            let Self {
4016                worker_shared,
4017                worker_handle,
4018                current_frame,
4019                pool,
4020                ..
4021            } = self;
4022            {
4023                let mut guard: MutexGuard<'_, VideoWorkerShared> =
4024                    worker_shared.0.lock().unwrap_or_else(
4025                        |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
4026                    );
4027                guard.set_shutdown(true);
4028                guard.get_mut_queue().clear_and_recycle(pool);
4029                worker_shared
4030                    .2
4031                    .store(VIDEO_FAST_HOLD_NONE, Ordering::Release);
4032                worker_shared.1.notify_all();
4033            }
4034            if let Some(handle) = worker_handle.take() {
4035                let _: Result<(), Box<dyn Any + Send>> = handle.join();
4036            }
4037            if let Some(frame) = current_frame.take() {
4038                pool.recycle_decoded_frame(frame);
4039            }
4040        }
4041        #[cfg(target_arch = "wasm32")]
4042        {
4043            let Self {
4044                wasm_queue,
4045                current_frame,
4046                pool,
4047                ..
4048            } = self;
4049            wasm_queue.clear_and_recycle(pool);
4050            if let Some(frame) = current_frame.take() {
4051                pool.recycle_decoded_frame(frame);
4052            }
4053        }
4054    }
4055}