1use super::*;
2
3impl Default for VideoColorInfo {
5 fn default() -> Self {
11 Self::sdr_bt709()
12 }
13}
14
15impl VideoColorInfo {
17 #[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 #[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 #[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 #[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 #[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
186impl HardwareDecoderProbe {
188 #[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 #[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
299impl Default for VideoFramePool {
301 fn default() -> Self {
307 Self::with_capacity(VIDEO_DEFAULT_POOL_CAPACITY)
308 }
309}
310
311impl VideoFramePool {
313 #[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 #[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 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 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 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 #[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
501impl Mp4Demuxer {
503 pub fn parse(bytes: Vec<u8>) -> Result<Self, String> {
513 if bytes.is_empty() {
514 return Err(VIDEO_ERR_MP4_EMPTY.to_string());
515 }
516 let mut major_brand: String = VIDEO_DEFAULT_BRAND_STR.to_string();
517 let mut compatible_brands: Vec<String> = Vec::new();
518 let mut movie_timescale: u32 = 1_000;
519 let mut movie_duration_us: u64 = 0;
520 let mut video_track: Option<Mp4TrackInfo> = None;
521 let mut audio_track: Option<Mp4TrackInfo> = None;
522 let mut found_moov: bool = false;
523 let mut cursor: usize = 0;
524 while cursor < bytes.len() {
525 let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
526 Self::read_box_header(&bytes, cursor, bytes.len())?;
527 if box_type == MP4_BOX_FTYP {
528 Self::parse_ftyp(
529 &bytes[payload_start..box_end],
530 &mut major_brand,
531 &mut compatible_brands,
532 );
533 } else if box_type == MP4_BOX_MOOV {
534 found_moov = true;
535 Self::parse_moov(
536 &bytes,
537 payload_start,
538 box_end,
539 &mut movie_timescale,
540 &mut movie_duration_us,
541 &mut video_track,
542 &mut audio_track,
543 )?;
544 }
545 cursor = box_end;
546 }
547 if !found_moov {
548 return Err(VIDEO_ERR_MP4_NO_MOOV.to_string());
549 }
550 let resolved_video: Mp4TrackInfo =
551 video_track.ok_or_else(|| VIDEO_ERR_MP4_NO_VIDEO_TRACK.to_string())?;
552 for sample in resolved_video.get_samples().iter() {
553 let end_offset: u64 = sample
554 .get_byte_offset()
555 .saturating_add(sample.get_byte_size() as u64);
556 if end_offset > (bytes.len() as u64) {
557 return Err(VIDEO_ERR_MP4_SAMPLE_BOUNDS.to_string());
558 }
559 }
560 if movie_duration_us == 0 {
561 movie_duration_us = resolved_video.get_duration_us();
562 }
563 Ok(Self {
564 bytes,
565 major_brand,
566 compatible_brands,
567 movie_timescale,
568 movie_duration_us,
569 video_track: resolved_video,
570 audio_track,
571 })
572 }
573
574 #[must_use]
584 pub fn audio_track(&self) -> Option<&Mp4TrackInfo> {
585 let Self { audio_track, .. } = self;
586 audio_track.as_ref()
587 }
588
589 #[must_use]
599 pub fn video_sample_count(&self) -> usize {
600 self.get_video_track().get_samples().len()
601 }
602
603 #[must_use]
613 pub fn video_decoder_config(&self) -> VideoDecoderConfig {
614 let track: &Mp4TrackInfo = self.get_video_track();
615 VideoDecoderConfig::new(
616 track.get_video_codec(),
617 track.get_width(),
618 track.get_height(),
619 track.get_color_info(),
620 )
621 }
622
623 #[must_use]
635 pub fn read_video_packet(
636 &self,
637 sample_index: usize,
638 generation: u64,
639 ) -> Option<EncodedVideoPacket> {
640 let sample: &Mp4Sample = self.get_video_track().get_samples().get(sample_index)?;
641 let start: usize = usize::try_from(sample.get_byte_offset()).ok()?;
642 let len: usize = sample.get_byte_size() as usize;
643 let end: usize = start.checked_add(len)?;
644 let slice: &[u8] = self.get_bytes().get(start..end)?;
645 Some(EncodedVideoPacket {
646 sample_index,
647 generation,
648 dts_us: sample.get_dts_us(),
649 pts_us: sample.get_pts_us(),
650 duration_us: sample.get_duration_us(),
651 is_keyframe: sample.get_is_keyframe(),
652 data: slice.to_vec(),
653 })
654 }
655
656 #[must_use]
667 pub fn seek_keyframe_index(&self, target_pts_us: i64) -> usize {
668 let samples: &[Mp4Sample] = self.get_video_track().get_samples().as_slice();
669 let mut best_keyframe: usize = 0;
670 let mut best_pts: i64 = i64::MIN;
671 for sample in samples.iter() {
672 if sample.get_is_keyframe()
673 && sample.get_pts_us() <= target_pts_us
674 && sample.get_pts_us() >= best_pts
675 {
676 best_pts = sample.get_pts_us();
677 best_keyframe = sample.get_index();
678 }
679 }
680 best_keyframe
681 }
682
683 fn read_box_header(
695 bytes: &[u8],
696 start: usize,
697 limit: usize,
698 ) -> Result<([u8; 4], usize, usize), String> {
699 if start.saturating_add(8) > limit {
700 return Err(VIDEO_ERR_MP4_TRUNCATED_BOX.to_string());
701 }
702 let size32: u32 = u32::from_be_bytes([
703 bytes[start],
704 bytes[start + 1],
705 bytes[start + 2],
706 bytes[start + 3],
707 ]);
708 let box_type: [u8; 4] = [
709 bytes[start + 4],
710 bytes[start + 5],
711 bytes[start + 6],
712 bytes[start + 7],
713 ];
714 if size32 == 0 {
715 return Ok((box_type, start + 8, limit));
716 }
717 if size32 == 1 {
718 if start.saturating_add(16) > limit {
719 return Err(VIDEO_ERR_MP4_TRUNCATED_BOX.to_string());
720 }
721 let size64: u64 = u64::from_be_bytes([
722 bytes[start + 8],
723 bytes[start + 9],
724 bytes[start + 10],
725 bytes[start + 11],
726 bytes[start + 12],
727 bytes[start + 13],
728 bytes[start + 14],
729 bytes[start + 15],
730 ]);
731 let total: usize =
732 usize::try_from(size64).map_err(|_| VIDEO_ERR_MP4_TRUNCATED_BOX.to_string())?;
733 if total < 16 || start.saturating_add(total) > limit {
734 return Err(VIDEO_ERR_MP4_TRUNCATED_BOX.to_string());
735 }
736 return Ok((box_type, start + 16, start + total));
737 }
738 let total: usize = size32 as usize;
739 if total < 8 || start.saturating_add(total) > limit {
740 return Err(VIDEO_ERR_MP4_TRUNCATED_BOX.to_string());
741 }
742 Ok((box_type, start + 8, start + total))
743 }
744
745 fn parse_ftyp(payload: &[u8], major_brand: &mut String, compatible_brands: &mut Vec<String>) {
753 if payload.len() >= 4 {
754 *major_brand = Self::fourcc_to_string(&payload[0..4]);
755 }
756 let mut offset: usize = 8;
757 while offset.saturating_add(4) <= payload.len() {
758 compatible_brands.push(Self::fourcc_to_string(&payload[offset..offset + 4]));
759 offset += 4;
760 }
761 }
762
763 fn fourcc_to_string(slice: &[u8]) -> String {
773 from_utf8(slice)
774 .map(|s: &str| s.to_string())
775 .unwrap_or_else(|_| VIDEO_DEFAULT_BRAND_STR.to_string())
776 }
777
778 fn parse_moov(
794 bytes: &[u8],
795 start: usize,
796 end: usize,
797 movie_timescale: &mut u32,
798 movie_duration_us: &mut u64,
799 video_track: &mut Option<Mp4TrackInfo>,
800 audio_track: &mut Option<Mp4TrackInfo>,
801 ) -> Result<(), String> {
802 let mut cursor: usize = start;
803 while cursor < end {
804 let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
805 Self::read_box_header(bytes, cursor, end)?;
806 if box_type == MP4_BOX_MVHD {
807 Self::parse_mvhd(
808 &bytes[payload_start..box_end],
809 movie_timescale,
810 movie_duration_us,
811 );
812 } else if box_type == MP4_BOX_TRAK
813 && let Some(track) = Self::parse_trak(bytes, payload_start, box_end)?
814 {
815 if track.get_is_video() && video_track.is_none() {
816 *video_track = Some(track);
817 } else if !track.get_is_video() && audio_track.is_none() {
818 *audio_track = Some(track);
819 }
820 }
821 cursor = box_end;
822 }
823 Ok(())
824 }
825
826 fn parse_mvhd(payload: &[u8], timescale_out: &mut u32, duration_us_out: &mut u64) {
834 if payload.len() < 4 {
835 return;
836 }
837 let version: u8 = payload[0];
838 if version == 0 && payload.len() >= 20 {
839 let scale: u32 =
840 u32::from_be_bytes([payload[12], payload[13], payload[14], payload[15]]);
841 let dur: u32 = u32::from_be_bytes([payload[16], payload[17], payload[18], payload[19]]);
842 if scale > 0 {
843 *timescale_out = scale;
844 *duration_us_out = Self::ticks_to_us(dur as u64, scale);
845 }
846 } else if version == 1 && payload.len() >= 32 {
847 let scale: u32 =
848 u32::from_be_bytes([payload[20], payload[21], payload[22], payload[23]]);
849 let dur: u64 = u64::from_be_bytes([
850 payload[24],
851 payload[25],
852 payload[26],
853 payload[27],
854 payload[28],
855 payload[29],
856 payload[30],
857 payload[31],
858 ]);
859 if scale > 0 {
860 *timescale_out = scale;
861 *duration_us_out = Self::ticks_to_us(dur, scale);
862 }
863 }
864 }
865
866 fn parse_trak(bytes: &[u8], start: usize, end: usize) -> Result<Option<Mp4TrackInfo>, String> {
878 let mut track: Mp4TrackInfo = Mp4TrackInfo::default();
879 let mut handler_tag: [u8; 4] = [0; 4];
880 let mut raw_stbl: Mp4SampleTableRaw = Mp4SampleTableRaw::default();
881 let mut cursor: usize = start;
882 while cursor < end {
883 let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
884 Self::read_box_header(bytes, cursor, end)?;
885 if box_type == MP4_BOX_TKHD {
886 Self::parse_tkhd(&bytes[payload_start..box_end], &mut track);
887 } else if box_type == MP4_BOX_MDIA {
888 Self::parse_mdia(
889 bytes,
890 payload_start,
891 box_end,
892 &mut track,
893 &mut handler_tag,
894 &mut raw_stbl,
895 )?;
896 }
897 cursor = box_end;
898 }
899 if handler_tag != MP4_HANDLER_VIDE && handler_tag != MP4_HANDLER_SOUN {
900 return Ok(None);
901 }
902 track.set_is_video(handler_tag == MP4_HANDLER_VIDE);
903 let timescale: u32 = track.get_timescale().max(1);
904 let samples: Vec<Mp4Sample> = Self::build_samples(&raw_stbl, timescale);
905 if track.get_duration_us() == 0 && !samples.is_empty() {
906 let mut max_end_us: u64 = 0;
907 for sample in samples.iter() {
908 let start_pos: u64 = sample.get_pts_us().max(0) as u64;
909 let end_pos: u64 = start_pos.saturating_add(sample.get_duration_us());
910 if end_pos > max_end_us {
911 max_end_us = end_pos;
912 }
913 }
914 track.set_duration_us(max_end_us);
915 }
916 track.set_samples(samples);
917 Ok(Some(track))
918 }
919
920 fn parse_tkhd(payload: &[u8], track: &mut Mp4TrackInfo) {
927 if payload.len() < 4 {
928 return;
929 }
930 let version: u8 = payload[0];
931 if version == 0 && payload.len() >= 84 {
932 let id: u32 = u32::from_be_bytes([payload[12], payload[13], payload[14], payload[15]]);
933 let width_fixed: u32 =
934 u32::from_be_bytes([payload[76], payload[77], payload[78], payload[79]]);
935 let height_fixed: u32 =
936 u32::from_be_bytes([payload[80], payload[81], payload[82], payload[83]]);
937 track.set_track_id(id);
938 if track.get_width() == 0 {
939 track.set_width(width_fixed >> 16);
940 }
941 if track.get_height() == 0 {
942 track.set_height(height_fixed >> 16);
943 }
944 } else if version == 1 && payload.len() >= 96 {
945 let id: u32 = u32::from_be_bytes([payload[20], payload[21], payload[22], payload[23]]);
946 let width_fixed: u32 =
947 u32::from_be_bytes([payload[88], payload[89], payload[90], payload[91]]);
948 let height_fixed: u32 =
949 u32::from_be_bytes([payload[92], payload[93], payload[94], payload[95]]);
950 track.set_track_id(id);
951 if track.get_width() == 0 {
952 track.set_width(width_fixed >> 16);
953 }
954 if track.get_height() == 0 {
955 track.set_height(height_fixed >> 16);
956 }
957 }
958 }
959
960 fn parse_mdia(
975 bytes: &[u8],
976 start: usize,
977 end: usize,
978 track: &mut Mp4TrackInfo,
979 handler_tag: &mut [u8; 4],
980 raw_stbl: &mut Mp4SampleTableRaw,
981 ) -> Result<(), String> {
982 let mut cursor: usize = start;
983 while cursor < end {
984 let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
985 Self::read_box_header(bytes, cursor, end)?;
986 if box_type == MP4_BOX_MDHD {
987 Self::parse_mdhd(&bytes[payload_start..box_end], track);
988 } else if box_type == MP4_BOX_HDLR {
989 let payload: &[u8] = &bytes[payload_start..box_end];
990 if payload.len() >= 12 {
991 *handler_tag = [payload[8], payload[9], payload[10], payload[11]];
992 }
993 } else if box_type == MP4_BOX_MINF {
994 Self::parse_minf(bytes, payload_start, box_end, track, raw_stbl)?;
995 }
996 cursor = box_end;
997 }
998 Ok(())
999 }
1000
1001 fn parse_mdhd(payload: &[u8], track: &mut Mp4TrackInfo) {
1008 if payload.len() < 4 {
1009 return;
1010 }
1011 let version: u8 = payload[0];
1012 if version == 0 && payload.len() >= 20 {
1013 let scale: u32 =
1014 u32::from_be_bytes([payload[12], payload[13], payload[14], payload[15]]);
1015 let dur: u32 = u32::from_be_bytes([payload[16], payload[17], payload[18], payload[19]]);
1016 if scale > 0 {
1017 track.set_timescale(scale);
1018 track.set_duration_us(Self::ticks_to_us(dur as u64, scale));
1019 }
1020 } else if version == 1 && payload.len() >= 32 {
1021 let scale: u32 =
1022 u32::from_be_bytes([payload[20], payload[21], payload[22], payload[23]]);
1023 let dur: u64 = u64::from_be_bytes([
1024 payload[24],
1025 payload[25],
1026 payload[26],
1027 payload[27],
1028 payload[28],
1029 payload[29],
1030 payload[30],
1031 payload[31],
1032 ]);
1033 if scale > 0 {
1034 track.set_timescale(scale);
1035 track.set_duration_us(Self::ticks_to_us(dur, scale));
1036 }
1037 }
1038 }
1039
1040 fn parse_minf(
1054 bytes: &[u8],
1055 start: usize,
1056 end: usize,
1057 track: &mut Mp4TrackInfo,
1058 raw_stbl: &mut Mp4SampleTableRaw,
1059 ) -> Result<(), String> {
1060 let mut cursor: usize = start;
1061 while cursor < end {
1062 let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
1063 Self::read_box_header(bytes, cursor, end)?;
1064 if box_type == MP4_BOX_STBL {
1065 Self::parse_stbl(bytes, payload_start, box_end, track, raw_stbl)?;
1066 }
1067 cursor = box_end;
1068 }
1069 Ok(())
1070 }
1071
1072 fn parse_stbl(
1086 bytes: &[u8],
1087 start: usize,
1088 end: usize,
1089 track: &mut Mp4TrackInfo,
1090 raw_stbl: &mut Mp4SampleTableRaw,
1091 ) -> Result<(), String> {
1092 let mut cursor: usize = start;
1093 while cursor < end {
1094 let (box_type, payload_start, box_end): ([u8; 4], usize, usize) =
1095 Self::read_box_header(bytes, cursor, end)?;
1096 let payload: &[u8] = &bytes[payload_start..box_end];
1097 if box_type == MP4_BOX_STSD {
1098 Self::parse_stsd(bytes, payload_start, box_end, track)?;
1099 } else if box_type == MP4_BOX_STTS {
1100 Self::parse_stts(payload, raw_stbl);
1101 } else if box_type == MP4_BOX_CTTS {
1102 Self::parse_ctts(payload, raw_stbl);
1103 } else if box_type == MP4_BOX_STSS {
1104 Self::parse_stss(payload, raw_stbl);
1105 } else if box_type == MP4_BOX_STSC {
1106 Self::parse_stsc(payload, raw_stbl);
1107 } else if box_type == MP4_BOX_STSZ {
1108 Self::parse_stsz(payload, raw_stbl);
1109 } else if box_type == MP4_BOX_STCO {
1110 Self::parse_stco(payload, raw_stbl);
1111 } else if box_type == MP4_BOX_CO64 {
1112 Self::parse_co64(payload, raw_stbl);
1113 }
1114 cursor = box_end;
1115 }
1116 Ok(())
1117 }
1118
1119 fn parse_stsd(
1132 bytes: &[u8],
1133 start: usize,
1134 end: usize,
1135 track: &mut Mp4TrackInfo,
1136 ) -> Result<(), String> {
1137 if start.saturating_add(8) > end {
1138 return Ok(());
1139 }
1140 let entry_count: u32 = u32::from_be_bytes([
1141 bytes[start + 4],
1142 bytes[start + 5],
1143 bytes[start + 6],
1144 bytes[start + 7],
1145 ]);
1146 if entry_count == 0 {
1147 return Ok(());
1148 }
1149 let entry_start: usize = start + 8;
1150 let (codec_tag, entry_payload_start, entry_end): ([u8; 4], usize, usize) =
1151 Self::read_box_header(bytes, entry_start, end)?;
1152 track.set_codec_fourcc(Self::fourcc_to_string(&codec_tag));
1153 let entry_payload: &[u8] = &bytes[entry_payload_start..entry_end];
1154 if codec_tag == MP4_CODEC_AVC1 || codec_tag == MP4_CODEC_AVC3 {
1155 track.set_video_codec(VideoCodec::H264);
1156 } else if codec_tag == MP4_CODEC_HVC1 || codec_tag == MP4_CODEC_HEV1 {
1157 track.set_video_codec(VideoCodec::H265);
1158 } else if codec_tag == MP4_CODEC_VP09 {
1159 track.set_video_codec(VideoCodec::Vp9);
1160 } else if codec_tag == MP4_CODEC_AV01 {
1161 track.set_video_codec(VideoCodec::Av1);
1162 } else if codec_tag == MP4_CODEC_RAWV || codec_tag == MP4_CODEC_RGBA {
1163 track.set_video_codec(VideoCodec::RawFrames);
1164 } else if codec_tag == MP4_CODEC_MP4A {
1165 track.set_audio_codec(AudioCodec::Aac);
1166 } else if codec_tag == MP4_CODEC_OPUS {
1167 track.set_audio_codec(AudioCodec::Opus);
1168 }
1169 let is_audio_codec: bool = codec_tag == MP4_CODEC_MP4A || codec_tag == MP4_CODEC_OPUS;
1170 if is_audio_codec {
1171 if entry_payload.len() >= 28 {
1172 let channels: u16 = u16::from_be_bytes([entry_payload[16], entry_payload[17]]);
1173 let sr_fixed: u32 = u32::from_be_bytes([
1174 entry_payload[24],
1175 entry_payload[25],
1176 entry_payload[26],
1177 entry_payload[27],
1178 ]);
1179 track.set_channels(channels);
1180 track.set_sample_rate_hz(sr_fixed >> 16);
1181 }
1182 return Ok(());
1183 }
1184 if entry_payload.len() >= 28 {
1185 let coded_w: u16 = u16::from_be_bytes([entry_payload[24], entry_payload[25]]);
1186 let coded_h: u16 = u16::from_be_bytes([entry_payload[26], entry_payload[27]]);
1187 if coded_w > 0 {
1188 track.set_width(coded_w as u32);
1189 }
1190 if coded_h > 0 {
1191 track.set_height(coded_h as u32);
1192 }
1193 }
1194 let mut child_cursor: usize = entry_payload_start.saturating_add(78);
1195 while child_cursor.saturating_add(8) <= entry_end {
1196 let Ok((child_type, child_start, child_end)) =
1197 Self::read_box_header(bytes, child_cursor, entry_end)
1198 else {
1199 break;
1200 };
1201 if child_type == MP4_BOX_COLR {
1202 Self::parse_colr(&bytes[child_start..child_end], track);
1203 }
1204 child_cursor = child_end;
1205 }
1206 Ok(())
1207 }
1208
1209 fn parse_colr(payload: &[u8], track: &mut Mp4TrackInfo) {
1216 if payload.len() >= 11 && payload[0..4] == MP4_BOX_NCLX {
1217 let primaries: u16 = u16::from_be_bytes([payload[4], payload[5]]);
1218 let transfer: u16 = u16::from_be_bytes([payload[6], payload[7]]);
1219 let matrix: u16 = u16::from_be_bytes([payload[8], payload[9]]);
1220 let full_range: bool = (payload[10] & 0x80) != 0;
1221 track.set_color_info(VideoColorInfo::from_nclx(
1222 primaries, transfer, matrix, full_range,
1223 ));
1224 }
1225 }
1226
1227 fn parse_stts(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1234 if payload.len() < 8 {
1235 return;
1236 }
1237 let count: usize =
1238 u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1239 let max_entries: usize = (payload.len() - 8) / 8;
1240 let entries: usize = count.min(max_entries);
1241 for i in 0..entries {
1242 let off: usize = 8 + i * 8;
1243 let sample_count: u32 = u32::from_be_bytes([
1244 payload[off],
1245 payload[off + 1],
1246 payload[off + 2],
1247 payload[off + 3],
1248 ]);
1249 let sample_delta: u32 = u32::from_be_bytes([
1250 payload[off + 4],
1251 payload[off + 5],
1252 payload[off + 6],
1253 payload[off + 7],
1254 ]);
1255 raw_stbl.get_mut_stts().push((sample_count, sample_delta));
1256 }
1257 }
1258
1259 fn parse_ctts(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1266 if payload.len() < 8 {
1267 return;
1268 }
1269 let version: u8 = payload[0];
1270 let count: usize =
1271 u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1272 let max_entries: usize = (payload.len() - 8) / 8;
1273 let entries: usize = count.min(max_entries);
1274 for i in 0..entries {
1275 let off: usize = 8 + i * 8;
1276 let sample_count: u32 = u32::from_be_bytes([
1277 payload[off],
1278 payload[off + 1],
1279 payload[off + 2],
1280 payload[off + 3],
1281 ]);
1282 let offset_ticks: i32 = if version == 1 {
1283 i32::from_be_bytes([
1284 payload[off + 4],
1285 payload[off + 5],
1286 payload[off + 6],
1287 payload[off + 7],
1288 ])
1289 } else {
1290 u32::from_be_bytes([
1291 payload[off + 4],
1292 payload[off + 5],
1293 payload[off + 6],
1294 payload[off + 7],
1295 ]) as i32
1296 };
1297 raw_stbl.get_mut_ctts().push((sample_count, offset_ticks));
1298 }
1299 }
1300
1301 fn parse_stss(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1308 if payload.len() < 8 {
1309 return;
1310 }
1311 let count: usize =
1312 u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1313 let max_entries: usize = (payload.len() - 8) / 4;
1314 let entries: usize = count.min(max_entries);
1315 for i in 0..entries {
1316 let off: usize = 8 + i * 4;
1317 let sample_num: u32 = u32::from_be_bytes([
1318 payload[off],
1319 payload[off + 1],
1320 payload[off + 2],
1321 payload[off + 3],
1322 ]);
1323 raw_stbl.get_mut_stss().push(sample_num);
1324 }
1325 }
1326
1327 fn parse_stsc(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1334 if payload.len() < 8 {
1335 return;
1336 }
1337 let count: usize =
1338 u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1339 let max_entries: usize = (payload.len() - 8) / 12;
1340 let entries: usize = count.min(max_entries);
1341 for i in 0..entries {
1342 let off: usize = 8 + i * 12;
1343 let first_chunk: u32 = u32::from_be_bytes([
1344 payload[off],
1345 payload[off + 1],
1346 payload[off + 2],
1347 payload[off + 3],
1348 ]);
1349 let samples_per_chunk: u32 = u32::from_be_bytes([
1350 payload[off + 4],
1351 payload[off + 5],
1352 payload[off + 6],
1353 payload[off + 7],
1354 ]);
1355 raw_stbl
1356 .get_mut_stsc()
1357 .push((first_chunk, samples_per_chunk));
1358 }
1359 }
1360
1361 fn parse_stsz(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1368 if payload.len() < 12 {
1369 return;
1370 }
1371 let default_size: u32 =
1372 u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]);
1373 let sample_count: u32 =
1374 u32::from_be_bytes([payload[8], payload[9], payload[10], payload[11]]);
1375 raw_stbl.set_default_sample_size(default_size);
1376 raw_stbl.set_sample_count(sample_count);
1377 if default_size == 0 {
1378 let max_entries: usize = (payload.len() - 12) / 4;
1379 let entries: usize = (sample_count as usize).min(max_entries);
1380 for i in 0..entries {
1381 let off: usize = 12 + i * 4;
1382 let size: u32 = u32::from_be_bytes([
1383 payload[off],
1384 payload[off + 1],
1385 payload[off + 2],
1386 payload[off + 3],
1387 ]);
1388 raw_stbl.get_mut_sample_sizes().push(size);
1389 }
1390 }
1391 }
1392
1393 fn parse_stco(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1400 if payload.len() < 8 {
1401 return;
1402 }
1403 let count: usize =
1404 u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1405 let max_entries: usize = (payload.len() - 8) / 4;
1406 let entries: usize = count.min(max_entries);
1407 for i in 0..entries {
1408 let off: usize = 8 + i * 4;
1409 let chunk_off: u32 = u32::from_be_bytes([
1410 payload[off],
1411 payload[off + 1],
1412 payload[off + 2],
1413 payload[off + 3],
1414 ]);
1415 raw_stbl.get_mut_chunk_offsets().push(chunk_off as u64);
1416 }
1417 }
1418
1419 fn parse_co64(payload: &[u8], raw_stbl: &mut Mp4SampleTableRaw) {
1426 if payload.len() < 8 {
1427 return;
1428 }
1429 let count: usize =
1430 u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]) as usize;
1431 let max_entries: usize = (payload.len() - 8) / 8;
1432 let entries: usize = count.min(max_entries);
1433 for i in 0..entries {
1434 let off: usize = 8 + i * 8;
1435 let chunk_off: u64 = u64::from_be_bytes([
1436 payload[off],
1437 payload[off + 1],
1438 payload[off + 2],
1439 payload[off + 3],
1440 payload[off + 4],
1441 payload[off + 5],
1442 payload[off + 6],
1443 payload[off + 7],
1444 ]);
1445 raw_stbl.get_mut_chunk_offsets().push(chunk_off);
1446 }
1447 }
1448
1449 fn build_samples(raw: &Mp4SampleTableRaw, timescale: u32) -> Vec<Mp4Sample> {
1460 let total_samples: usize = raw.get_sample_count() as usize;
1461 if total_samples == 0 || raw.get_chunk_offsets().is_empty() {
1462 return Vec::new();
1463 }
1464 let mut durations: Vec<u32> = Vec::with_capacity(total_samples);
1465 for (run_count, delta) in raw.get_stts().iter().copied() {
1466 let take_count: usize =
1467 (run_count as usize).min(total_samples.saturating_sub(durations.len()));
1468 for _ in 0..take_count {
1469 durations.push(delta);
1470 }
1471 if durations.len() >= total_samples {
1472 break;
1473 }
1474 }
1475 let mut cto_ticks: Vec<i32> = Vec::with_capacity(total_samples);
1476 for (run_count, offset) in raw.get_ctts().iter().copied() {
1477 let take_count: usize =
1478 (run_count as usize).min(total_samples.saturating_sub(cto_ticks.len()));
1479 for _ in 0..take_count {
1480 cto_ticks.push(offset);
1481 }
1482 if cto_ticks.len() >= total_samples {
1483 break;
1484 }
1485 }
1486 let keyframe_set: HashSet<u32> = raw.get_stss().iter().copied().collect();
1487 let all_keyframes: bool = keyframe_set.is_empty();
1488 let chunk_offsets: &[u64] = raw.get_chunk_offsets().as_slice();
1489 let stsc: &[(u32, u32)] = raw.get_stsc().as_slice();
1490 let mut sample_offsets: Vec<u64> = Vec::with_capacity(total_samples);
1491 let mut sample_sizes: Vec<u32> = Vec::with_capacity(total_samples);
1492 let mut sample_cursor: usize = 0;
1493 let mut stsc_idx: usize = 0;
1494 for (chunk_zero_idx, chunk_base_offset) in chunk_offsets.iter().copied().enumerate() {
1495 let chunk_one_based: u32 = (chunk_zero_idx + 1) as u32;
1496 while stsc_idx + 1 < stsc.len() && stsc[stsc_idx + 1].0 <= chunk_one_based {
1497 stsc_idx += 1;
1498 }
1499 let spc: usize = stsc
1500 .get(stsc_idx)
1501 .map(|e: &(u32, u32)| e.1 as usize)
1502 .unwrap_or(1);
1503 let mut offset_in_chunk: u64 = chunk_base_offset;
1504 for _ in 0..spc {
1505 if sample_cursor >= total_samples {
1506 break;
1507 }
1508 let size: u32 = if raw.get_default_sample_size() > 0 {
1509 raw.get_default_sample_size()
1510 } else {
1511 raw.get_sample_sizes()
1512 .get(sample_cursor)
1513 .copied()
1514 .unwrap_or(0)
1515 };
1516 sample_offsets.push(offset_in_chunk);
1517 sample_sizes.push(size);
1518 offset_in_chunk = offset_in_chunk.saturating_add(size as u64);
1519 sample_cursor += 1;
1520 }
1521 if sample_cursor >= total_samples {
1522 break;
1523 }
1524 }
1525 let mut out: Vec<Mp4Sample> = Vec::with_capacity(sample_offsets.len());
1526 let mut dts_ticks: i64 = 0;
1527 for idx in 0..sample_offsets.len() {
1528 let dur_ticks: u32 = durations.get(idx).copied().unwrap_or(1);
1529 let cto: i64 = cto_ticks.get(idx).copied().unwrap_or(0) as i64;
1530 let dts_us: i64 = Self::signed_ticks_to_us(dts_ticks, timescale);
1531 let pts_us: i64 = Self::signed_ticks_to_us(dts_ticks.saturating_add(cto), timescale);
1532 let duration_us: u64 = Self::ticks_to_us(dur_ticks as u64, timescale);
1533 let one_based: u32 = (idx + 1) as u32;
1534 let is_keyframe: bool = all_keyframes || keyframe_set.contains(&one_based);
1535 out.push(Mp4Sample::new(
1536 idx,
1537 dts_us,
1538 pts_us,
1539 duration_us,
1540 sample_offsets[idx],
1541 sample_sizes[idx],
1542 is_keyframe,
1543 ));
1544 dts_ticks = dts_ticks.saturating_add(dur_ticks as i64);
1545 }
1546 out
1547 }
1548
1549 #[must_use]
1560 fn ticks_to_us(ticks: u64, timescale: u32) -> u64 {
1561 let scale: u128 = (timescale.max(1)) as u128;
1562 (((ticks as u128) * (VIDEO_MICROS_PER_SEC as u128)) / scale) as u64
1563 }
1564
1565 #[must_use]
1576 fn signed_ticks_to_us(ticks: i64, timescale: u32) -> i64 {
1577 let scale: i128 = (timescale.max(1)) as i128;
1578 (((ticks as i128) * (VIDEO_MICROS_PER_SEC as i128)) / scale) as i64
1579 }
1580}
1581
1582impl Mp4ContainerBuilder {
1584 #[must_use]
1599 pub fn build_video_mp4(
1600 width: u32,
1601 height: u32,
1602 timescale: u32,
1603 codec: VideoCodec,
1604 color_info: VideoColorInfo,
1605 samples: &[Mp4BuilderSample],
1606 ) -> Vec<u8> {
1607 let safe_scale: u32 = timescale.max(1);
1608 let mut total_ticks: u32 = 0;
1609 let mut mdat_payload: Vec<u8> = Vec::new();
1610 for sample in samples.iter() {
1611 total_ticks = total_ticks.saturating_add(sample.get_duration_ticks());
1612 mdat_payload.extend_from_slice(sample.get_payload().as_slice());
1613 }
1614 let mut ftyp_payload: Vec<u8> = Vec::with_capacity(16);
1615 ftyp_payload.extend_from_slice(&MP4_BRAND_ISOM);
1616 ftyp_payload.extend_from_slice(&512_u32.to_be_bytes());
1617 ftyp_payload.extend_from_slice(&MP4_BRAND_ISOM);
1618 ftyp_payload.extend_from_slice(&MP4_BRAND_MP42);
1619 let ftyp_box: Vec<u8> = Self::wrap_box(MP4_BOX_FTYP, &ftyp_payload);
1620 let moov_placeholder: Vec<u8> = Self::build_moov_box(
1621 (width, height),
1622 (safe_scale, total_ticks),
1623 codec,
1624 color_info,
1625 samples,
1626 0,
1627 );
1628 let mdat_data_offset: u32 = (ftyp_box.len() + moov_placeholder.len() + 8) as u32;
1629 let moov_box: Vec<u8> = Self::build_moov_box(
1630 (width, height),
1631 (safe_scale, total_ticks),
1632 codec,
1633 color_info,
1634 samples,
1635 mdat_data_offset,
1636 );
1637 let mdat_box: Vec<u8> = Self::wrap_box(MP4_BOX_MDAT, &mdat_payload);
1638 let mut out: Vec<u8> = Vec::with_capacity(ftyp_box.len() + moov_box.len() + mdat_box.len());
1639 out.extend_from_slice(&ftyp_box);
1640 out.extend_from_slice(&moov_box);
1641 out.extend_from_slice(&mdat_box);
1642 out
1643 }
1644
1645 #[must_use]
1660 fn build_moov_box(
1661 dims: (u32, u32),
1662 timing: (u32, u32),
1663 codec: VideoCodec,
1664 color_info: VideoColorInfo,
1665 samples: &[Mp4BuilderSample],
1666 mdat_data_offset: u32,
1667 ) -> Vec<u8> {
1668 let (width, height): (u32, u32) = dims;
1669 let (timescale, total_ticks): (u32, u32) = timing;
1670 let mut mvhd_payload: Vec<u8> = vec![0; 100];
1671 mvhd_payload[12..16].copy_from_slice(×cale.to_be_bytes());
1672 mvhd_payload[16..20].copy_from_slice(&total_ticks.to_be_bytes());
1673 mvhd_payload[20..24].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
1674 mvhd_payload[24..26].copy_from_slice(&0x0100_u16.to_be_bytes());
1675 mvhd_payload[96..100].copy_from_slice(&2_u32.to_be_bytes());
1676 let mvhd_box: Vec<u8> = Self::wrap_box(MP4_BOX_MVHD, &mvhd_payload);
1677 let mut tkhd_payload: Vec<u8> = vec![0; 84];
1678 tkhd_payload[3] = 3;
1679 tkhd_payload[12..16].copy_from_slice(&1_u32.to_be_bytes());
1680 tkhd_payload[20..24].copy_from_slice(&total_ticks.to_be_bytes());
1681 tkhd_payload[76..80].copy_from_slice(&(width << 16).to_be_bytes());
1682 tkhd_payload[80..84].copy_from_slice(&(height << 16).to_be_bytes());
1683 let tkhd_box: Vec<u8> = Self::wrap_box(MP4_BOX_TKHD, &tkhd_payload);
1684 let mut mdhd_payload: Vec<u8> = vec![0; 24];
1685 mdhd_payload[12..16].copy_from_slice(×cale.to_be_bytes());
1686 mdhd_payload[16..20].copy_from_slice(&total_ticks.to_be_bytes());
1687 let mdhd_box: Vec<u8> = Self::wrap_box(MP4_BOX_MDHD, &mdhd_payload);
1688 let mut hdlr_payload: Vec<u8> = vec![0; 25];
1689 hdlr_payload[8..12].copy_from_slice(&MP4_HANDLER_VIDE);
1690 let hdlr_box: Vec<u8> = Self::wrap_box(MP4_BOX_HDLR, &hdlr_payload);
1691 let stbl_box: Vec<u8> =
1692 Self::build_stbl_box(width, height, codec, color_info, samples, mdat_data_offset);
1693 let minf_box: Vec<u8> = Self::wrap_box(MP4_BOX_MINF, &stbl_box);
1694 let mut mdia_payload: Vec<u8> = Vec::new();
1695 mdia_payload.extend_from_slice(&mdhd_box);
1696 mdia_payload.extend_from_slice(&hdlr_box);
1697 mdia_payload.extend_from_slice(&minf_box);
1698 let mdia_box: Vec<u8> = Self::wrap_box(MP4_BOX_MDIA, &mdia_payload);
1699 let mut trak_payload: Vec<u8> = Vec::new();
1700 trak_payload.extend_from_slice(&tkhd_box);
1701 trak_payload.extend_from_slice(&mdia_box);
1702 let trak_box: Vec<u8> = Self::wrap_box(MP4_BOX_TRAK, &trak_payload);
1703 let mut moov_payload: Vec<u8> = Vec::new();
1704 moov_payload.extend_from_slice(&mvhd_box);
1705 moov_payload.extend_from_slice(&trak_box);
1706 Self::wrap_box(MP4_BOX_MOOV, &moov_payload)
1707 }
1708
1709 #[must_use]
1724 fn build_stbl_box(
1725 width: u32,
1726 height: u32,
1727 codec: VideoCodec,
1728 color_info: VideoColorInfo,
1729 samples: &[Mp4BuilderSample],
1730 mdat_data_offset: u32,
1731 ) -> Vec<u8> {
1732 let codec_tag: [u8; 4] = match codec {
1733 VideoCodec::H264 => MP4_CODEC_AVC1,
1734 VideoCodec::H265 => MP4_CODEC_HVC1,
1735 VideoCodec::Vp9 => MP4_CODEC_VP09,
1736 VideoCodec::Av1 => MP4_CODEC_AV01,
1737 VideoCodec::RawFrames => MP4_CODEC_RAWV,
1738 };
1739 let (p_code, t_code, m_code, full_range): (u16, u16, u16, bool) = color_info.to_nclx();
1740 let mut colr_payload: Vec<u8> = Vec::with_capacity(11);
1741 colr_payload.extend_from_slice(&MP4_BOX_NCLX);
1742 colr_payload.extend_from_slice(&p_code.to_be_bytes());
1743 colr_payload.extend_from_slice(&t_code.to_be_bytes());
1744 colr_payload.extend_from_slice(&m_code.to_be_bytes());
1745 colr_payload.push(if full_range { 0x80 } else { 0x00 });
1746 let colr_box: Vec<u8> = Self::wrap_box(MP4_BOX_COLR, &colr_payload);
1747 let mut visual_entry_payload: Vec<u8> = vec![0; 78];
1748 visual_entry_payload[6..8].copy_from_slice(&1_u16.to_be_bytes());
1749 visual_entry_payload[24..26].copy_from_slice(&(width as u16).to_be_bytes());
1750 visual_entry_payload[26..28].copy_from_slice(&(height as u16).to_be_bytes());
1751 visual_entry_payload[28..32].copy_from_slice(&0x0048_0000_u32.to_be_bytes());
1752 visual_entry_payload[32..36].copy_from_slice(&0x0048_0000_u32.to_be_bytes());
1753 visual_entry_payload[40..42].copy_from_slice(&1_u16.to_be_bytes());
1754 visual_entry_payload[74..76].copy_from_slice(&24_u16.to_be_bytes());
1755 visual_entry_payload[76..78].copy_from_slice(&0xFFFF_u16.to_be_bytes());
1756 visual_entry_payload.extend_from_slice(&colr_box);
1757 let visual_entry_box: Vec<u8> = Self::wrap_box(codec_tag, &visual_entry_payload);
1758 let mut stsd_payload: Vec<u8> = Vec::with_capacity(8 + visual_entry_box.len());
1759 stsd_payload.extend_from_slice(&0_u32.to_be_bytes());
1760 stsd_payload.extend_from_slice(&1_u32.to_be_bytes());
1761 stsd_payload.extend_from_slice(&visual_entry_box);
1762 let stsd_box: Vec<u8> = Self::wrap_box(MP4_BOX_STSD, &stsd_payload);
1763 let mut stts_payload: Vec<u8> = Vec::with_capacity(8 + samples.len() * 8);
1764 stts_payload.extend_from_slice(&0_u32.to_be_bytes());
1765 stts_payload.extend_from_slice(&(samples.len() as u32).to_be_bytes());
1766 for sample in samples.iter() {
1767 stts_payload.extend_from_slice(&1_u32.to_be_bytes());
1768 stts_payload.extend_from_slice(&sample.get_duration_ticks().to_be_bytes());
1769 }
1770 let stts_box: Vec<u8> = Self::wrap_box(MP4_BOX_STTS, &stts_payload);
1771 let has_ctts: bool = samples
1772 .iter()
1773 .any(|s: &Mp4BuilderSample| s.get_composition_offset_ticks() != 0);
1774 let mut stbl_payload: Vec<u8> = Vec::new();
1775 stbl_payload.extend_from_slice(&stsd_box);
1776 stbl_payload.extend_from_slice(&stts_box);
1777 if has_ctts {
1778 let mut ctts_payload: Vec<u8> = Vec::with_capacity(8 + samples.len() * 8);
1779 ctts_payload.extend_from_slice(&[1, 0, 0, 0]);
1780 ctts_payload.extend_from_slice(&(samples.len() as u32).to_be_bytes());
1781 for sample in samples.iter() {
1782 ctts_payload.extend_from_slice(&1_u32.to_be_bytes());
1783 ctts_payload
1784 .extend_from_slice(&sample.get_composition_offset_ticks().to_be_bytes());
1785 }
1786 let ctts_box: Vec<u8> = Self::wrap_box(MP4_BOX_CTTS, &ctts_payload);
1787 stbl_payload.extend_from_slice(&ctts_box);
1788 }
1789 let keyframes: Vec<u32> = samples
1790 .iter()
1791 .enumerate()
1792 .filter_map(|(idx, s): (usize, &Mp4BuilderSample)| {
1793 if s.get_is_keyframe() {
1794 Some((idx + 1) as u32)
1795 } else {
1796 None
1797 }
1798 })
1799 .collect();
1800 if !keyframes.is_empty() {
1801 let mut stss_payload: Vec<u8> = Vec::with_capacity(8 + keyframes.len() * 4);
1802 stss_payload.extend_from_slice(&0_u32.to_be_bytes());
1803 stss_payload.extend_from_slice(&(keyframes.len() as u32).to_be_bytes());
1804 for kf in keyframes.iter().copied() {
1805 stss_payload.extend_from_slice(&kf.to_be_bytes());
1806 }
1807 let stss_box: Vec<u8> = Self::wrap_box(MP4_BOX_STSS, &stss_payload);
1808 stbl_payload.extend_from_slice(&stss_box);
1809 }
1810 let mut stsc_payload: Vec<u8> = Vec::with_capacity(20);
1811 stsc_payload.extend_from_slice(&0_u32.to_be_bytes());
1812 stsc_payload.extend_from_slice(&1_u32.to_be_bytes());
1813 stsc_payload.extend_from_slice(&1_u32.to_be_bytes());
1814 stsc_payload.extend_from_slice(&(samples.len() as u32).to_be_bytes());
1815 stsc_payload.extend_from_slice(&1_u32.to_be_bytes());
1816 let stsc_box: Vec<u8> = Self::wrap_box(MP4_BOX_STSC, &stsc_payload);
1817 let mut stsz_payload: Vec<u8> = Vec::with_capacity(12 + samples.len() * 4);
1818 stsz_payload.extend_from_slice(&0_u32.to_be_bytes());
1819 stsz_payload.extend_from_slice(&0_u32.to_be_bytes());
1820 stsz_payload.extend_from_slice(&(samples.len() as u32).to_be_bytes());
1821 for sample in samples.iter() {
1822 stsz_payload.extend_from_slice(&(sample.get_payload().len() as u32).to_be_bytes());
1823 }
1824 let stsz_box: Vec<u8> = Self::wrap_box(MP4_BOX_STSZ, &stsz_payload);
1825 let mut stco_payload: Vec<u8> = Vec::with_capacity(12);
1826 stco_payload.extend_from_slice(&0_u32.to_be_bytes());
1827 stco_payload.extend_from_slice(&1_u32.to_be_bytes());
1828 stco_payload.extend_from_slice(&mdat_data_offset.to_be_bytes());
1829 let stco_box: Vec<u8> = Self::wrap_box(MP4_BOX_STCO, &stco_payload);
1830 stbl_payload.extend_from_slice(&stsc_box);
1831 stbl_payload.extend_from_slice(&stsz_box);
1832 stbl_payload.extend_from_slice(&stco_box);
1833 Self::wrap_box(MP4_BOX_STBL, &stbl_payload)
1834 }
1835
1836 #[must_use]
1847 fn wrap_box(box_type: [u8; 4], payload: &[u8]) -> Vec<u8> {
1848 let total: u32 = (payload.len() + 8) as u32;
1849 let mut out: Vec<u8> = Vec::with_capacity(total as usize);
1850 out.extend_from_slice(&total.to_be_bytes());
1851 out.extend_from_slice(&box_type);
1852 out.extend_from_slice(payload);
1853 out
1854 }
1855}
1856
1857impl DecodedVideoFrame {
1859 #[must_use]
1869 pub fn gpu_surface(&self) -> Option<VideoGpuSurfaceHandle> {
1870 match self.get_backing() {
1871 VideoFrameBacking::GpuSurface(handle) => Some(*handle),
1872 VideoFrameBacking::CpuPooled(_) => None,
1873 }
1874 }
1875
1876 #[must_use]
1886 pub fn cpu_rgba_pixels(&self) -> Option<&[u8]> {
1887 match self.get_backing() {
1888 VideoFrameBacking::CpuPooled(pooled) => Some(pooled.get_pixels().as_slice()),
1889 VideoFrameBacking::GpuSurface(_) => None,
1890 }
1891 }
1892
1893 #[must_use]
1903 pub fn to_image_buffer(&self) -> Option<ImageBuffer> {
1904 let pixels: &[u8] = self.cpu_rgba_pixels()?;
1905 Some(ImageBuffer::new(
1906 self.get_width(),
1907 self.get_height(),
1908 pixels.to_vec(),
1909 ))
1910 }
1911}
1912
1913impl SoftwareVideoDecoder {
1915 #[must_use]
1927 pub fn encode_intra_rgba_packet(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
1928 let mut out: Vec<u8> = Vec::with_capacity(13 + rgba.len());
1929 out.extend_from_slice(VIDEO_SW_FRAME_MAGIC);
1930 out.push(VIDEO_SW_PACKET_INTRA_RGBA);
1931 out.extend_from_slice(&width.to_le_bytes());
1932 out.extend_from_slice(&height.to_le_bytes());
1933 out.extend_from_slice(rgba);
1934 out
1935 }
1936
1937 #[must_use]
1951 pub fn encode_intra_yuv420p_packet(
1952 width: u32,
1953 height: u32,
1954 y_plane: &[u8],
1955 u_plane: &[u8],
1956 v_plane: &[u8],
1957 ) -> Vec<u8> {
1958 let mut out: Vec<u8> =
1959 Vec::with_capacity(13 + y_plane.len() + u_plane.len() + v_plane.len());
1960 out.extend_from_slice(VIDEO_SW_FRAME_MAGIC);
1961 out.push(VIDEO_SW_PACKET_INTRA_YUV420P);
1962 out.extend_from_slice(&width.to_le_bytes());
1963 out.extend_from_slice(&height.to_le_bytes());
1964 out.extend_from_slice(y_plane);
1965 out.extend_from_slice(u_plane);
1966 out.extend_from_slice(v_plane);
1967 out
1968 }
1969
1970 #[must_use]
1983 pub fn encode_delta_xor_packet(
1984 width: u32,
1985 height: u32,
1986 prev_rgba: &[u8],
1987 target_rgba: &[u8],
1988 ) -> Vec<u8> {
1989 let len: usize = prev_rgba.len().min(target_rgba.len());
1990 let mut out: Vec<u8> = Vec::with_capacity(13 + len);
1991 out.extend_from_slice(VIDEO_SW_FRAME_MAGIC);
1992 out.push(VIDEO_SW_PACKET_DELTA_XOR);
1993 out.extend_from_slice(&width.to_le_bytes());
1994 out.extend_from_slice(&height.to_le_bytes());
1995 for i in 0..len {
1996 out.push(prev_rgba[i] ^ target_rgba[i]);
1997 }
1998 out
1999 }
2000
2001 fn convert_yuv420p_to_rgba(
2011 width: u32,
2012 height: u32,
2013 yuv: &[u8],
2014 color_info: VideoColorInfo,
2015 dst_rgba: &mut [u8],
2016 ) {
2017 let w: usize = width as usize;
2018 let h: usize = height as usize;
2019 let cw: usize = w.div_ceil(2);
2020 let ch: usize = h.div_ceil(2);
2021 let y_len: usize = w * h;
2022 let uv_len: usize = cw * ch;
2023 let y_plane: &[u8] = &yuv[0..y_len];
2024 let u_plane: &[u8] = &yuv[y_len..(y_len + uv_len)];
2025 let v_plane: &[u8] = &yuv[(y_len + uv_len)..(y_len + uv_len * 2)];
2026 let (kr, kb): (f32, f32) = match color_info.get_matrix() {
2027 MatrixCoefficients::Bt601 => (0.299, 0.114),
2028 MatrixCoefficients::Bt2020Ncl => (0.2627, 0.0593),
2029 MatrixCoefficients::Bt709
2030 | MatrixCoefficients::Identity
2031 | MatrixCoefficients::Unknown(_) => (0.2126, 0.0722),
2032 };
2033 let kg: f32 = 1.0 - kr - kb;
2034 let full_range: bool = color_info.get_range() == ColorRange::Full;
2035 for row in 0..h {
2036 let crow: usize = row / 2;
2037 for col in 0..w {
2038 let y_raw: f32 = y_plane[row * w + col] as f32;
2039 let uv_idx: usize = crow * cw + (col / 2);
2040 let cb_raw: f32 = u_plane[uv_idx] as f32;
2041 let cr_raw: f32 = v_plane[uv_idx] as f32;
2042 let (y_norm, cb_norm, cr_norm): (f32, f32, f32) = if full_range {
2043 (
2044 y_raw / 255.0,
2045 (cb_raw - 128.0) / 255.0,
2046 (cr_raw - 128.0) / 255.0,
2047 )
2048 } else {
2049 (
2050 ((y_raw - 16.0) / 219.0).clamp(0.0, 1.0),
2051 (cb_raw - 128.0) / 224.0,
2052 (cr_raw - 128.0) / 224.0,
2053 )
2054 };
2055 let r: f32 = y_norm + 2.0 * (1.0 - kr) * cr_norm;
2056 let b: f32 = y_norm + 2.0 * (1.0 - kb) * cb_norm;
2057 let g: f32 = y_norm
2058 - (2.0 * kb * (1.0 - kb) / kg) * cb_norm
2059 - (2.0 * kr * (1.0 - kr) / kg) * cr_norm;
2060 let dst: usize = (row * w + col) * 4;
2061 dst_rgba[dst] = (r.clamp(0.0, 1.0) * 255.0).round() as u8;
2062 dst_rgba[dst + 1] = (g.clamp(0.0, 1.0) * 255.0).round() as u8;
2063 dst_rgba[dst + 2] = (b.clamp(0.0, 1.0) * 255.0).round() as u8;
2064 dst_rgba[dst + 3] = 255;
2065 }
2066 }
2067 }
2068}
2069
2070impl VideoDecoderBackend for SoftwareVideoDecoder {
2072 fn backend_kind(&self) -> HardwareDecoderKind {
2082 HardwareDecoderKind::SoftwareFallback
2083 }
2084
2085 fn capabilities(&self) -> HardwareDecoderCapabilities {
2095 HardwareDecoderProbe::capabilities_for(HardwareDecoderKind::SoftwareFallback)
2096 }
2097
2098 fn configure(&mut self, config: &VideoDecoderConfig) -> Result<(), String> {
2109 if config.get_width() == 0 || config.get_height() == 0 {
2110 return Err(VIDEO_ERR_UNSUPPORTED_DIMENSIONS.to_string());
2111 }
2112 self.set_config(*config);
2113 self.flush();
2114 Ok(())
2115 }
2116
2117 fn decode_packet(
2129 &mut self,
2130 packet: &EncodedVideoPacket,
2131 pool: &VideoFramePool,
2132 ) -> Result<Option<DecodedVideoFrame>, String> {
2133 let data: &[u8] = packet.get_data().as_slice();
2134 let config: VideoDecoderConfig = self.get_config();
2135 let (width, height, kind, payload): (u32, u32, u8, &[u8]) =
2136 if data.len() >= 13 && &data[0..4] == VIDEO_SW_FRAME_MAGIC {
2137 let pkt_kind: u8 = data[4];
2138 let w: u32 = u32::from_le_bytes([data[5], data[6], data[7], data[8]]);
2139 let h: u32 = u32::from_le_bytes([data[9], data[10], data[11], data[12]]);
2140 (w, h, pkt_kind, &data[13..])
2141 } else if config.get_codec() == VideoCodec::RawFrames {
2142 (
2143 config.get_width(),
2144 config.get_height(),
2145 VIDEO_SW_PACKET_INTRA_RGBA,
2146 data,
2147 )
2148 } else {
2149 return Err(VIDEO_ERR_UNSUPPORTED_CODEC.to_string());
2150 };
2151 if width == 0 || height == 0 {
2152 return Err(VIDEO_ERR_UNSUPPORTED_DIMENSIONS.to_string());
2153 }
2154 let rgba_len: usize = (width as usize)
2155 .checked_mul(height as usize)
2156 .and_then(|v: usize| v.checked_mul(4))
2157 .ok_or_else(|| VIDEO_ERR_UNSUPPORTED_DIMENSIONS.to_string())?;
2158 let mut pooled: PooledVideoFrame = pool
2159 .acquire(width, height)
2160 .ok_or_else(|| VIDEO_ERR_POOL_EXHAUSTED.to_string())?;
2161 match kind {
2162 VIDEO_SW_PACKET_INTRA_RGBA => {
2163 if payload.len() != rgba_len {
2164 pool.recycle(pooled);
2165 return Err(VIDEO_ERR_SW_PACKET_SIZE.to_string());
2166 }
2167 pooled.get_mut_pixels().copy_from_slice(payload);
2168 }
2169 VIDEO_SW_PACKET_INTRA_YUV420P => {
2170 let y_len: usize = (width as usize) * (height as usize);
2171 let uv_len: usize = (width as usize).div_ceil(2) * (height as usize).div_ceil(2);
2172 if payload.len() != y_len + uv_len * 2 {
2173 pool.recycle(pooled);
2174 return Err(VIDEO_ERR_SW_PACKET_SIZE.to_string());
2175 }
2176 Self::convert_yuv420p_to_rgba(
2177 width,
2178 height,
2179 payload,
2180 config.get_color_info(),
2181 pooled.get_mut_pixels().as_mut_slice(),
2182 );
2183 }
2184 VIDEO_SW_PACKET_DELTA_XOR => {
2185 let has_ref: bool = self.get_has_reference();
2186 let Self { reference_rgba, .. } = self;
2187 if !has_ref || reference_rgba.len() != rgba_len {
2188 pool.recycle(pooled);
2189 return Err(VIDEO_ERR_SW_DELTA_NO_REF.to_string());
2190 }
2191 if payload.len() != rgba_len {
2192 pool.recycle(pooled);
2193 return Err(VIDEO_ERR_SW_PACKET_SIZE.to_string());
2194 }
2195 let dst: &mut [u8] = pooled.get_mut_pixels().as_mut_slice();
2196 for i in 0..rgba_len {
2197 dst[i] = reference_rgba[i] ^ payload[i];
2198 }
2199 }
2200 _ => {
2201 pool.recycle(pooled);
2202 return Err(VIDEO_ERR_SW_PACKET_INVALID.to_string());
2203 }
2204 }
2205 {
2206 let Self { reference_rgba, .. } = self;
2207 if reference_rgba.len() != rgba_len {
2208 reference_rgba.resize(rgba_len, 0);
2209 }
2210 reference_rgba.copy_from_slice(pooled.get_pixels().as_slice());
2211 }
2212 self.set_has_reference(true);
2213 let next_decoded: u64 = self.get_decoded_frames().saturating_add(1);
2214 self.set_decoded_frames(next_decoded);
2215 Ok(Some(DecodedVideoFrame {
2216 sample_index: packet.get_sample_index(),
2217 generation: packet.get_generation(),
2218 dts_us: packet.get_dts_us(),
2219 pts_us: packet.get_pts_us(),
2220 duration_us: packet.get_duration_us(),
2221 width,
2222 height,
2223 color_info: config.get_color_info(),
2224 backing: VideoFrameBacking::CpuPooled(pooled),
2225 }))
2226 }
2227
2228 fn flush(&mut self) {
2234 self.set_has_reference(false);
2235 let Self { reference_rgba, .. } = self;
2236 reference_rgba.clear();
2237 }
2238}
2239
2240impl HardwareZeroCopyDecoder {
2242 #[must_use]
2253 pub fn for_backend(kind: HardwareDecoderKind, device_id: u64) -> Self {
2254 Self {
2255 kind,
2256 device_id,
2257 pixel_format: VideoPixelFormat::Nv12,
2258 config: VideoDecoderConfig::default(),
2259 next_surface_id: 1,
2260 next_fence_value: 1,
2261 }
2262 }
2263}
2264
2265impl VideoDecoderBackend for HardwareZeroCopyDecoder {
2267 fn backend_kind(&self) -> HardwareDecoderKind {
2277 self.get_kind()
2278 }
2279
2280 fn capabilities(&self) -> HardwareDecoderCapabilities {
2290 HardwareDecoderProbe::capabilities_for(self.get_kind())
2291 }
2292
2293 fn configure(&mut self, config: &VideoDecoderConfig) -> Result<(), String> {
2304 if config.get_width() == 0 || config.get_height() == 0 {
2305 return Err(VIDEO_ERR_UNSUPPORTED_DIMENSIONS.to_string());
2306 }
2307 self.set_config(*config);
2308 let fmt: VideoPixelFormat =
2309 if config.get_color_info().is_hdr() || config.get_color_info().get_bit_depth() >= 10 {
2310 VideoPixelFormat::P010
2311 } else {
2312 VideoPixelFormat::Nv12
2313 };
2314 self.set_pixel_format(fmt);
2315 Ok(())
2316 }
2317
2318 fn decode_packet(
2330 &mut self,
2331 packet: &EncodedVideoPacket,
2332 _pool: &VideoFramePool,
2333 ) -> Result<Option<DecodedVideoFrame>, String> {
2334 let config: VideoDecoderConfig = self.get_config();
2335 let surface_id: u64 = self.get_next_surface_id();
2336 self.set_next_surface_id(surface_id.saturating_add(1));
2337 let fence_value: u64 = self.get_next_fence_value();
2338 self.set_next_fence_value(fence_value.saturating_add(1));
2339 let handle: VideoGpuSurfaceHandle = VideoGpuSurfaceHandle {
2340 surface_id,
2341 device_id: self.get_device_id(),
2342 generation: packet.get_generation(),
2343 width: config.get_width(),
2344 height: config.get_height(),
2345 pixel_format: self.get_pixel_format(),
2346 color_info: config.get_color_info(),
2347 fence_value,
2348 zero_copy: true,
2349 backend: self.get_kind(),
2350 };
2351 Ok(Some(DecodedVideoFrame {
2352 sample_index: packet.get_sample_index(),
2353 generation: packet.get_generation(),
2354 dts_us: packet.get_dts_us(),
2355 pts_us: packet.get_pts_us(),
2356 duration_us: packet.get_duration_us(),
2357 width: config.get_width(),
2358 height: config.get_height(),
2359 color_info: config.get_color_info(),
2360 backing: VideoFrameBacking::GpuSurface(handle),
2361 }))
2362 }
2363
2364 fn flush(&mut self) {}
2370}
2371
2372impl PtsFrameQueue {
2374 #[must_use]
2384 pub fn with_capacity(capacity: usize) -> Self {
2385 let cap: usize = capacity.max(1);
2386 Self {
2387 capacity: cap,
2388 frames: Vec::with_capacity(cap),
2389 stale_generation_drops: 0,
2390 }
2391 }
2392
2393 #[must_use]
2403 pub fn is_full(&self) -> bool {
2404 self.get_frames().len() >= self.get_capacity()
2405 }
2406
2407 #[must_use]
2417 pub fn len(&self) -> usize {
2418 self.get_frames().len()
2419 }
2420
2421 #[must_use]
2431 pub fn is_empty(&self) -> bool {
2432 self.get_frames().is_empty()
2433 }
2434
2435 pub fn push_ordered(&mut self, frame: DecodedVideoFrame) -> Option<DecodedVideoFrame> {
2446 if self.is_full() {
2447 return Some(frame);
2448 }
2449 let target_pts: i64 = frame.get_pts_us();
2450 let insert_pos: usize = self
2451 .get_frames()
2452 .partition_point(|existing: &DecodedVideoFrame| existing.get_pts_us() <= target_pts);
2453 self.get_mut_frames().insert(insert_pos, frame);
2454 None
2455 }
2456
2457 #[must_use]
2467 pub fn peek_front_pts_us(&self) -> Option<i64> {
2468 self.get_frames()
2469 .first()
2470 .map(|f: &DecodedVideoFrame| f.get_pts_us())
2471 }
2472
2473 pub fn drain_stale_generations(
2485 &mut self,
2486 active_generation: u64,
2487 pool: &VideoFramePool,
2488 ) -> usize {
2489 let mut drained: usize = 0;
2490 let existing: Vec<DecodedVideoFrame> = take(self.get_mut_frames());
2491 let mut kept: Vec<DecodedVideoFrame> = Vec::with_capacity(existing.len());
2492 for frame in existing.into_iter() {
2493 if frame.get_generation() == active_generation {
2494 kept.push(frame);
2495 } else {
2496 pool.recycle_decoded_frame(frame);
2497 drained += 1;
2498 }
2499 }
2500 *self.get_mut_frames() = kept;
2501 let next_drops: u64 = self
2502 .get_stale_generation_drops()
2503 .saturating_add(drained as u64);
2504 self.set_stale_generation_drops(next_drops);
2505 drained
2506 }
2507
2508 pub fn clear_and_recycle(&mut self, pool: &VideoFramePool) {
2515 let existing: Vec<DecodedVideoFrame> = take(self.get_mut_frames());
2516 for frame in existing.into_iter() {
2517 pool.recycle_decoded_frame(frame);
2518 }
2519 }
2520}
2521
2522impl AvSyncScheduler {
2524 #[must_use]
2530 pub fn new_default() -> Self {
2531 Self {
2532 clock_source: AvSyncClockSource::MonotonicFallback,
2533 clock_pts_us: 0,
2534 playback_rate: 1.0,
2535 max_late_us: VIDEO_DEFAULT_MAX_LATE_US,
2536 last_presented_pts_us: None,
2537 frames_presented: 0,
2538 frames_held_vsync: 0,
2539 frames_dropped_late: 0,
2540 }
2541 }
2542
2543 #[must_use]
2553 pub const fn last_presented_pts_us(&self) -> Option<i64> {
2554 let Self {
2555 last_presented_pts_us,
2556 ..
2557 } = *self;
2558 last_presented_pts_us
2559 }
2560
2561 pub fn update_audio_clock_us(&mut self, audio_pts_us: i64) {
2568 self.set_clock_source(AvSyncClockSource::AudioMaster);
2569 self.set_clock_pts_us(audio_pts_us.max(0));
2570 }
2571
2572 pub fn advance_monotonic_us(&mut self, delta_us: u64) {
2579 self.set_clock_source(AvSyncClockSource::MonotonicFallback);
2580 let rate: f64 = (self.get_playback_rate().clamp(0.25, 4.0)) as f64;
2581 let scaled: i64 = ((delta_us as f64) * rate).round() as i64;
2582 let next_clock: i64 = self.get_clock_pts_us().saturating_add(scaled.max(0));
2583 self.set_clock_pts_us(next_clock);
2584 }
2585
2586 pub fn reset_for_seek(&mut self, target_pts_us: i64) {
2593 self.set_clock_pts_us(target_pts_us.max(0));
2594 let Self {
2595 last_presented_pts_us,
2596 ..
2597 } = self;
2598 *last_presented_pts_us = None;
2599 }
2600
2601 pub fn select_frame_for_vsync(
2615 &mut self,
2616 queue: &mut PtsFrameQueue,
2617 pool: &VideoFramePool,
2618 reached_eos: bool,
2619 has_displayed_frame: bool,
2620 ) -> VideoPresentDecision {
2621 let clock_us: i64 = self.get_clock_pts_us();
2622 let Some(front_pts) = queue.peek_front_pts_us() else {
2623 if reached_eos {
2624 return VideoPresentDecision::Ended;
2625 }
2626 if has_displayed_frame {
2627 let next_held: u64 = self.get_frames_held_vsync().saturating_add(1);
2628 self.set_frames_held_vsync(next_held);
2629 return VideoPresentDecision::HoldCurrentFrame;
2630 }
2631 return VideoPresentDecision::Buffering;
2632 };
2633 if front_pts > clock_us.saturating_add(VIDEO_PRESENT_TOLERANCE_US) {
2634 let next_held: u64 = self.get_frames_held_vsync().saturating_add(1);
2635 self.set_frames_held_vsync(next_held);
2636 return VideoPresentDecision::HoldCurrentFrame;
2637 }
2638 let mut due_count: usize = 0;
2639 for frame in queue.get_frames().iter() {
2640 if frame.get_pts_us() <= clock_us.saturating_add(VIDEO_PRESENT_TOLERANCE_US) {
2641 due_count += 1;
2642 } else {
2643 break;
2644 }
2645 }
2646 let max_late: i64 = self.get_max_late_us().max(0);
2647 let mut chosen: Option<DecodedVideoFrame> = None;
2648 let mut dropped: u64 = 0;
2649 for idx in 0..due_count {
2650 let frame: DecodedVideoFrame = queue.get_mut_frames().remove(0);
2651 let is_last_due: bool = idx + 1 == due_count;
2652 let lateness: i64 = clock_us.saturating_sub(frame.get_pts_us());
2653 if !is_last_due {
2654 let _: bool = lateness > max_late;
2655 pool.recycle_decoded_frame(frame);
2656 dropped = dropped.saturating_add(1);
2657 } else {
2658 chosen = Some(frame);
2659 }
2660 }
2661 if dropped > 0 {
2662 let next_dropped: u64 = self.get_frames_dropped_late().saturating_add(dropped);
2663 self.set_frames_dropped_late(next_dropped);
2664 }
2665 if let Some(frame) = chosen {
2666 let pts: i64 = frame.get_pts_us();
2667 let Self {
2668 last_presented_pts_us,
2669 ..
2670 } = self;
2671 *last_presented_pts_us = Some(pts);
2672 let next_presented: u64 = self.get_frames_presented().saturating_add(1);
2673 self.set_frames_presented(next_presented);
2674 VideoPresentDecision::PresentNewFrame(frame)
2675 } else if reached_eos {
2676 VideoPresentDecision::Ended
2677 } else {
2678 VideoPresentDecision::HoldCurrentFrame
2679 }
2680 }
2681}
2682
2683impl VideoPlaybackPipeline {
2685 pub fn from_mp4_bytes(bytes: Vec<u8>) -> Result<Self, String> {
2695 Self::from_mp4_with_backend(
2696 bytes,
2697 Box::new(SoftwareVideoDecoder::default()),
2698 VIDEO_DEFAULT_QUEUE_CAPACITY,
2699 VIDEO_DEFAULT_POOL_CAPACITY,
2700 )
2701 }
2702
2703 pub fn from_mp4_with_backend(
2716 bytes: Vec<u8>,
2717 mut decoder: Box<dyn VideoDecoderBackend>,
2718 queue_capacity: usize,
2719 pool_capacity: usize,
2720 ) -> Result<Self, String> {
2721 let demuxer: Mp4Demuxer = Mp4Demuxer::parse(bytes)?;
2722 let config: VideoDecoderConfig = demuxer.video_decoder_config();
2723 decoder.configure(&config)?;
2724 let backend_kind: HardwareDecoderKind = decoder.backend_kind();
2725 let color_info: VideoColorInfo = config.get_color_info();
2726 let pool: VideoFramePool = VideoFramePool::with_capacity(pool_capacity);
2727 let scheduler: AvSyncScheduler = AvSyncScheduler::new_default();
2728 #[cfg(not(target_arch = "wasm32"))]
2729 {
2730 let shared_state: VideoWorkerShared = VideoWorkerShared {
2731 queue: PtsFrameQueue::with_capacity(queue_capacity),
2732 active_generation: 1,
2733 next_sample_index: 0,
2734 seek_preroll_target_us: 0,
2735 pending_seek: None,
2736 playing: true,
2737 reached_eos: demuxer.video_sample_count() == 0,
2738 shutdown: false,
2739 packets_decoded: 0,
2740 seek_preroll_frames_discarded: 0,
2741 last_error: None,
2742 };
2743 let worker_shared: Arc<(Mutex<VideoWorkerShared>, Condvar)> =
2744 Arc::new((Mutex::new(shared_state), Condvar::new()));
2745 let worker_shared_clone: Arc<(Mutex<VideoWorkerShared>, Condvar)> =
2746 Arc::clone(&worker_shared);
2747 let worker_demuxer: Mp4Demuxer = demuxer.clone();
2748 let worker_pool: VideoFramePool = pool.clone();
2749 let handle_opt: Option<JoinHandle<()>> = Builder::new()
2750 .name(VIDEO_WORKER_THREAD_NAME.to_string())
2751 .spawn(move || {
2752 Self::worker_loop(worker_demuxer, decoder, worker_pool, worker_shared_clone);
2753 })
2754 .ok();
2755 Ok(Self {
2756 demuxer,
2757 pool,
2758 scheduler,
2759 backend_kind,
2760 color_info,
2761 state: PlaybackState::Playing,
2762 current_frame: None,
2763 active_generation: 1,
2764 worker_shared,
2765 worker_handle: handle_opt,
2766 })
2767 }
2768 #[cfg(target_arch = "wasm32")]
2769 {
2770 let reached_eos: bool = demuxer.video_sample_count() == 0;
2771 Ok(Self {
2772 demuxer,
2773 pool,
2774 scheduler,
2775 backend_kind,
2776 color_info,
2777 state: PlaybackState::Playing,
2778 current_frame: None,
2779 active_generation: 1,
2780 wasm_decoder: decoder,
2781 wasm_queue: PtsFrameQueue::with_capacity(queue_capacity),
2782 wasm_next_sample: 0,
2783 wasm_preroll_target_us: 0,
2784 wasm_eos: reached_eos,
2785 wasm_packets_decoded: 0,
2786 wasm_preroll_discarded: 0,
2787 wasm_last_error: None,
2788 })
2789 }
2790 }
2791
2792 #[cfg(not(target_arch = "wasm32"))]
2801 fn worker_loop(
2802 demuxer: Mp4Demuxer,
2803 mut decoder: Box<dyn VideoDecoderBackend>,
2804 pool: VideoFramePool,
2805 shared: Arc<(Mutex<VideoWorkerShared>, Condvar)>,
2806 ) {
2807 let total_samples: usize = demuxer.video_sample_count();
2808 loop {
2809 let work_item: Option<(usize, u64, i64)> = {
2810 let mut guard: MutexGuard<'_, VideoWorkerShared> = shared.0.lock().unwrap_or_else(
2811 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
2812 );
2813 loop {
2814 if guard.get_shutdown() {
2815 return;
2816 }
2817 let pending_seek: Option<(u64, usize, i64)> = {
2818 let VideoWorkerShared { pending_seek, .. } = &mut *guard;
2819 pending_seek.take()
2820 };
2821 if let Some((new_gen, kf_idx, target_pts)) = pending_seek {
2822 decoder.flush();
2823 let _: usize = guard
2824 .get_mut_queue()
2825 .drain_stale_generations(new_gen, &pool);
2826 guard.set_active_generation(new_gen);
2827 guard.set_next_sample_index(kf_idx);
2828 guard.set_seek_preroll_target_us(target_pts);
2829 guard.set_reached_eos(kf_idx >= total_samples);
2830 let VideoWorkerShared { last_error, .. } = &mut *guard;
2831 *last_error = None;
2832 }
2833 let can_decode: bool = guard.get_playing()
2834 && !guard.get_reached_eos()
2835 && !guard.get_queue().is_full()
2836 && guard.get_next_sample_index() < total_samples;
2837 if can_decode {
2838 let idx: usize = guard.get_next_sample_index();
2839 let gen_id: u64 = guard.get_active_generation();
2840 let target_pts: i64 = guard.get_seek_preroll_target_us();
2841 guard.set_next_sample_index(idx.saturating_add(1));
2842 break Some((idx, gen_id, target_pts));
2843 }
2844 guard = shared.1.wait(guard).unwrap_or_else(
2845 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
2846 );
2847 }
2848 };
2849 let Some((sample_idx, packet_gen, preroll_target_us)) = work_item else {
2850 continue;
2851 };
2852 let Some(packet) = demuxer.read_video_packet(sample_idx, packet_gen) else {
2853 let mut guard: MutexGuard<'_, VideoWorkerShared> = shared.0.lock().unwrap_or_else(
2854 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
2855 );
2856 if guard.get_active_generation() == packet_gen {
2857 guard.set_reached_eos(true);
2858 }
2859 shared.1.notify_all();
2860 continue;
2861 };
2862 let decode_res: Result<Option<DecodedVideoFrame>, String> =
2863 decoder.decode_packet(&packet, &pool);
2864 let mut guard: MutexGuard<'_, VideoWorkerShared> = shared.0.lock().unwrap_or_else(
2865 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
2866 );
2867 if guard.get_active_generation() != packet_gen || guard.get_shutdown() {
2868 if let Ok(Some(stale)) = decode_res {
2869 pool.recycle_decoded_frame(stale);
2870 }
2871 shared.1.notify_all();
2872 continue;
2873 }
2874 match decode_res {
2875 Ok(Some(frame)) => {
2876 let next_decoded: u64 = guard.get_packets_decoded().saturating_add(1);
2877 guard.set_packets_decoded(next_decoded);
2878 if frame.get_pts_us() < preroll_target_us && sample_idx + 1 < total_samples {
2879 pool.recycle_decoded_frame(frame);
2880 let next_disc: u64 =
2881 guard.get_seek_preroll_frames_discarded().saturating_add(1);
2882 guard.set_seek_preroll_frames_discarded(next_disc);
2883 } else if let Some(rejected) = guard.get_mut_queue().push_ordered(frame) {
2884 pool.recycle_decoded_frame(rejected);
2885 }
2886 }
2887 Ok(None) => {}
2888 Err(msg) => {
2889 let VideoWorkerShared { last_error, .. } = &mut *guard;
2890 *last_error = Some(msg);
2891 guard.set_reached_eos(true);
2892 }
2893 }
2894 if sample_idx + 1 >= total_samples {
2895 guard.set_reached_eos(true);
2896 }
2897 shared.1.notify_all();
2898 }
2899 }
2900
2901 #[must_use]
2911 pub fn demuxer(&self) -> &Mp4Demuxer {
2912 let Self { demuxer, .. } = self;
2913 demuxer
2914 }
2915
2916 #[must_use]
2926 pub fn frame_pool(&self) -> &VideoFramePool {
2927 let Self { pool, .. } = self;
2928 pool
2929 }
2930
2931 #[must_use]
2941 pub fn scheduler(&self) -> &AvSyncScheduler {
2942 let Self { scheduler, .. } = self;
2943 scheduler
2944 }
2945
2946 pub fn scheduler_mut(&mut self) -> &mut AvSyncScheduler {
2956 let Self { scheduler, .. } = self;
2957 scheduler
2958 }
2959
2960 #[must_use]
2970 pub const fn backend_kind(&self) -> HardwareDecoderKind {
2971 let Self { backend_kind, .. } = *self;
2972 backend_kind
2973 }
2974
2975 #[must_use]
2985 pub const fn color_info(&self) -> VideoColorInfo {
2986 let Self { color_info, .. } = *self;
2987 color_info
2988 }
2989
2990 #[must_use]
3000 pub const fn playback_state(&self) -> PlaybackState {
3001 let Self { state, .. } = *self;
3002 state
3003 }
3004
3005 #[must_use]
3015 pub fn current_frame(&self) -> Option<&DecodedVideoFrame> {
3016 let Self { current_frame, .. } = self;
3017 current_frame.as_ref()
3018 }
3019
3020 #[must_use]
3030 pub const fn active_generation(&self) -> u64 {
3031 let Self {
3032 active_generation, ..
3033 } = *self;
3034 active_generation
3035 }
3036
3037 pub fn play(&mut self) {
3043 let Self { state, .. } = self;
3044 *state = PlaybackState::Playing;
3045 #[cfg(not(target_arch = "wasm32"))]
3046 {
3047 let Self { worker_shared, .. } = self;
3048 let mut guard: MutexGuard<'_, VideoWorkerShared> =
3049 worker_shared.0.lock().unwrap_or_else(
3050 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3051 );
3052 guard.set_playing(true);
3053 worker_shared.1.notify_all();
3054 }
3055 }
3056
3057 pub fn pause(&mut self) {
3063 let Self { state, .. } = self;
3064 *state = PlaybackState::Paused;
3065 #[cfg(not(target_arch = "wasm32"))]
3066 {
3067 let Self { worker_shared, .. } = self;
3068 let mut guard: MutexGuard<'_, VideoWorkerShared> =
3069 worker_shared.0.lock().unwrap_or_else(
3070 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3071 );
3072 guard.set_playing(false);
3073 worker_shared.1.notify_all();
3074 }
3075 }
3076
3077 pub fn seek_us(&mut self, target_pts_us: i64) -> u64 {
3088 let clamped_target: i64 = target_pts_us.max(0);
3089 let keyframe_idx: usize = self.demuxer().seek_keyframe_index(clamped_target);
3090 let next_gen: u64 = {
3091 let Self {
3092 active_generation,
3093 scheduler,
3094 current_frame,
3095 pool,
3096 state,
3097 ..
3098 } = self;
3099 *active_generation = active_generation.saturating_add(1);
3100 scheduler.reset_for_seek(clamped_target);
3101 if let Some(old_frame) = current_frame.take() {
3102 pool.recycle_decoded_frame(old_frame);
3103 }
3104 if *state == PlaybackState::Ended {
3105 *state = PlaybackState::Playing;
3106 }
3107 *active_generation
3108 };
3109 #[cfg(not(target_arch = "wasm32"))]
3110 {
3111 let Self {
3112 worker_shared,
3113 pool,
3114 ..
3115 } = self;
3116 let mut guard: MutexGuard<'_, VideoWorkerShared> =
3117 worker_shared.0.lock().unwrap_or_else(
3118 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3119 );
3120 let _: usize = guard
3121 .get_mut_queue()
3122 .drain_stale_generations(next_gen, pool);
3123 guard.set_active_generation(next_gen);
3124 guard.set_reached_eos(false);
3125 let VideoWorkerShared { pending_seek, .. } = &mut *guard;
3126 *pending_seek = Some((next_gen, keyframe_idx, clamped_target));
3127 worker_shared.1.notify_all();
3128 }
3129 #[cfg(target_arch = "wasm32")]
3130 {
3131 let Self {
3132 wasm_decoder,
3133 wasm_queue,
3134 wasm_next_sample,
3135 wasm_preroll_target_us,
3136 wasm_eos,
3137 wasm_last_error,
3138 pool,
3139 demuxer,
3140 ..
3141 } = self;
3142 wasm_decoder.flush();
3143 let _: usize = wasm_queue.drain_stale_generations(next_gen, pool);
3144 *wasm_next_sample = keyframe_idx;
3145 *wasm_preroll_target_us = clamped_target;
3146 *wasm_eos = keyframe_idx >= demuxer.video_sample_count();
3147 *wasm_last_error = None;
3148 }
3149 next_gen
3150 }
3151
3152 pub fn wait_until_queued(&mut self, min_frames: usize, timeout_ms: u64) -> usize {
3164 #[cfg(not(target_arch = "wasm32"))]
3165 {
3166 let Self {
3167 worker_shared,
3168 active_generation,
3169 ..
3170 } = self;
3171 let active_gen: u64 = *active_generation;
3172 let deadline: Instant = Instant::now() + Duration::from_millis(timeout_ms);
3173 let mut guard: MutexGuard<'_, VideoWorkerShared> =
3174 worker_shared.0.lock().unwrap_or_else(
3175 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3176 );
3177 while (guard.get_queue().len() < min_frames || {
3178 let VideoWorkerShared { pending_seek, .. } = &*guard;
3179 pending_seek.is_some()
3180 }) && !guard.get_reached_eos()
3181 && guard.get_active_generation() == active_gen
3182 {
3183 let now: Instant = Instant::now();
3184 if now >= deadline {
3185 break;
3186 }
3187 let rem: Duration = deadline.saturating_duration_since(now);
3188 guard = worker_shared
3189 .1
3190 .wait_timeout(guard, rem)
3191 .unwrap_or_else(|err: PoisonError<(MutexGuard<'_, VideoWorkerShared>, _)>| {
3192 err.into_inner()
3193 })
3194 .0;
3195 }
3196 guard.get_queue().len()
3197 }
3198 #[cfg(target_arch = "wasm32")]
3199 {
3200 let _: u64 = timeout_ms;
3201 let mut iterations: usize = 0;
3202 while self.queued_frame_count() < min_frames && !self.reached_eos() && iterations < 512
3203 {
3204 let _: bool = self.pump_decode_once();
3205 iterations += 1;
3206 }
3207 self.queued_frame_count()
3208 }
3209 }
3210
3211 pub fn pump_decode_once(&mut self) -> bool {
3221 #[cfg(not(target_arch = "wasm32"))]
3222 {
3223 false
3224 }
3225 #[cfg(target_arch = "wasm32")]
3226 {
3227 let Self {
3228 demuxer,
3229 pool,
3230 active_generation,
3231 wasm_decoder,
3232 wasm_queue,
3233 wasm_next_sample,
3234 wasm_preroll_target_us,
3235 wasm_eos,
3236 wasm_packets_decoded,
3237 wasm_preroll_discarded,
3238 wasm_last_error,
3239 ..
3240 } = self;
3241 let total: usize = demuxer.video_sample_count();
3242 if *wasm_eos || wasm_queue.is_full() || *wasm_next_sample >= total {
3243 if *wasm_next_sample >= total {
3244 *wasm_eos = true;
3245 }
3246 return false;
3247 }
3248 let sample_idx: usize = *wasm_next_sample;
3249 *wasm_next_sample = sample_idx.saturating_add(1);
3250 let Some(packet) = demuxer.read_video_packet(sample_idx, *active_generation) else {
3251 *wasm_eos = true;
3252 return false;
3253 };
3254 match wasm_decoder.decode_packet(&packet, pool) {
3255 Ok(Some(frame)) => {
3256 *wasm_packets_decoded = wasm_packets_decoded.saturating_add(1);
3257 if frame.get_pts_us() < *wasm_preroll_target_us && sample_idx + 1 < total {
3258 pool.recycle_decoded_frame(frame);
3259 *wasm_preroll_discarded = wasm_preroll_discarded.saturating_add(1);
3260 } else if let Some(rejected) = wasm_queue.push_ordered(frame) {
3261 pool.recycle_decoded_frame(rejected);
3262 }
3263 }
3264 Ok(None) => {}
3265 Err(msg) => {
3266 *wasm_last_error = Some(msg);
3267 *wasm_eos = true;
3268 }
3269 }
3270 if sample_idx + 1 >= total {
3271 *wasm_eos = true;
3272 }
3273 true
3274 }
3275 }
3276
3277 pub fn present_vsync(
3289 &mut self,
3290 audio_master_pts_us: Option<i64>,
3291 vsync_dt_us: u64,
3292 ) -> VideoPresentOutcome {
3293 if self.playback_state() != PlaybackState::Playing {
3294 return VideoPresentOutcome::HoldCurrentFrame;
3295 }
3296 if let Some(audio_us) = audio_master_pts_us {
3297 self.scheduler_mut().update_audio_clock_us(audio_us);
3298 } else {
3299 self.scheduler_mut().advance_monotonic_us(vsync_dt_us);
3300 }
3301 let has_displayed: bool = self.current_frame().is_some();
3302 #[cfg(not(target_arch = "wasm32"))]
3303 let decision: VideoPresentDecision = {
3304 let Self {
3305 worker_shared,
3306 scheduler,
3307 pool,
3308 active_generation,
3309 ..
3310 } = self;
3311 let active_gen: u64 = *active_generation;
3312 let mut guard: MutexGuard<'_, VideoWorkerShared> =
3313 worker_shared.0.lock().unwrap_or_else(
3314 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3315 );
3316 let _: usize = guard
3317 .get_mut_queue()
3318 .drain_stale_generations(active_gen, pool);
3319 let pending_seek_active: bool = {
3320 let VideoWorkerShared { pending_seek, .. } = &*guard;
3321 pending_seek.is_some()
3322 };
3323 let eos: bool = !pending_seek_active && guard.get_reached_eos();
3324 let res: VideoPresentDecision =
3325 scheduler.select_frame_for_vsync(guard.get_mut_queue(), pool, eos, has_displayed);
3326 worker_shared.1.notify_all();
3327 res
3328 };
3329 #[cfg(target_arch = "wasm32")]
3330 let decision: VideoPresentDecision = {
3331 let Self {
3332 wasm_queue,
3333 wasm_eos,
3334 scheduler,
3335 pool,
3336 active_generation,
3337 ..
3338 } = self;
3339 let _: usize = wasm_queue.drain_stale_generations(*active_generation, pool);
3340 scheduler.select_frame_for_vsync(wasm_queue, pool, *wasm_eos, has_displayed)
3341 };
3342 match decision {
3343 VideoPresentDecision::PresentNewFrame(next_frame) => {
3344 let pts_us: i64 = next_frame.get_pts_us();
3345 let sample_index: usize = next_frame.get_sample_index();
3346 let generation: u64 = next_frame.get_generation();
3347 let zero_copy_gpu: bool = next_frame.gpu_surface().is_some();
3348 let Self {
3349 current_frame,
3350 pool,
3351 ..
3352 } = self;
3353 if let Some(previous) = current_frame.replace(next_frame) {
3354 pool.recycle_decoded_frame(previous);
3355 }
3356 VideoPresentOutcome::Presented {
3357 pts_us,
3358 sample_index,
3359 generation,
3360 zero_copy_gpu,
3361 }
3362 }
3363 VideoPresentDecision::HoldCurrentFrame => VideoPresentOutcome::HoldCurrentFrame,
3364 VideoPresentDecision::Buffering => VideoPresentOutcome::Buffering,
3365 VideoPresentDecision::Ended => {
3366 let Self { state, .. } = self;
3367 *state = PlaybackState::Ended;
3368 VideoPresentOutcome::Ended
3369 }
3370 }
3371 }
3372
3373 #[must_use]
3383 pub fn queued_frame_count(&self) -> usize {
3384 #[cfg(not(target_arch = "wasm32"))]
3385 {
3386 let Self { worker_shared, .. } = self;
3387 let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3388 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3389 );
3390 guard.get_queue().len()
3391 }
3392 #[cfg(target_arch = "wasm32")]
3393 {
3394 let Self { wasm_queue, .. } = self;
3395 wasm_queue.len()
3396 }
3397 }
3398
3399 #[must_use]
3409 pub fn reached_eos(&self) -> bool {
3410 #[cfg(not(target_arch = "wasm32"))]
3411 {
3412 let Self { worker_shared, .. } = self;
3413 let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3414 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3415 );
3416 guard.get_reached_eos()
3417 }
3418 #[cfg(target_arch = "wasm32")]
3419 {
3420 let Self { wasm_eos, .. } = self;
3421 *wasm_eos
3422 }
3423 }
3424
3425 #[must_use]
3435 pub fn packets_decoded(&self) -> u64 {
3436 #[cfg(not(target_arch = "wasm32"))]
3437 {
3438 let Self { worker_shared, .. } = self;
3439 let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3440 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3441 );
3442 guard.get_packets_decoded()
3443 }
3444 #[cfg(target_arch = "wasm32")]
3445 {
3446 let Self {
3447 wasm_packets_decoded,
3448 ..
3449 } = self;
3450 *wasm_packets_decoded
3451 }
3452 }
3453
3454 #[must_use]
3464 pub fn seek_preroll_frames_discarded(&self) -> u64 {
3465 #[cfg(not(target_arch = "wasm32"))]
3466 {
3467 let Self { worker_shared, .. } = self;
3468 let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3469 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3470 );
3471 guard.get_seek_preroll_frames_discarded()
3472 }
3473 #[cfg(target_arch = "wasm32")]
3474 {
3475 let Self {
3476 wasm_preroll_discarded,
3477 ..
3478 } = self;
3479 *wasm_preroll_discarded
3480 }
3481 }
3482
3483 #[must_use]
3493 pub fn last_error(&self) -> Option<String> {
3494 #[cfg(not(target_arch = "wasm32"))]
3495 {
3496 let Self { worker_shared, .. } = self;
3497 let guard: MutexGuard<'_, VideoWorkerShared> = worker_shared.0.lock().unwrap_or_else(
3498 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3499 );
3500 let VideoWorkerShared { last_error, .. } = &*guard;
3501 last_error.clone()
3502 }
3503 #[cfg(target_arch = "wasm32")]
3504 {
3505 let Self {
3506 wasm_last_error, ..
3507 } = self;
3508 wasm_last_error.clone()
3509 }
3510 }
3511}
3512
3513impl Drop for VideoPlaybackPipeline {
3515 fn drop(&mut self) {
3521 #[cfg(not(target_arch = "wasm32"))]
3522 {
3523 let Self {
3524 worker_shared,
3525 worker_handle,
3526 current_frame,
3527 pool,
3528 ..
3529 } = self;
3530 {
3531 let mut guard: MutexGuard<'_, VideoWorkerShared> =
3532 worker_shared.0.lock().unwrap_or_else(
3533 |err: PoisonError<MutexGuard<'_, VideoWorkerShared>>| err.into_inner(),
3534 );
3535 guard.set_shutdown(true);
3536 guard.get_mut_queue().clear_and_recycle(pool);
3537 worker_shared.1.notify_all();
3538 }
3539 if let Some(handle) = worker_handle.take() {
3540 let _: Result<(), Box<dyn Any + Send>> = handle.join();
3541 }
3542 if let Some(frame) = current_frame.take() {
3543 pool.recycle_decoded_frame(frame);
3544 }
3545 }
3546 #[cfg(target_arch = "wasm32")]
3547 {
3548 let Self {
3549 wasm_queue,
3550 current_frame,
3551 pool,
3552 ..
3553 } = self;
3554 wasm_queue.clear_and_recycle(pool);
3555 if let Some(frame) = current_frame.take() {
3556 pool.recycle_decoded_frame(frame);
3557 }
3558 }
3559 }
3560}