1use std::{collections::BTreeMap, time::Duration};
4
5use crate::{DType, Error, Matrix, Result, Runtime, Texture, runtime::VideoDecoderBackend};
6
7use super::{
8 Av1Parser, Av1Profile, Av1SequenceHeader, H264PictureLayout, H264PictureParameterSet,
9 H264Profile, H264SequenceParameterSet, H264SliceHeader, H265PictureParameterSet, H265Profile,
10 H265SequenceParameterSet, H265VideoParameterSet, NalUnit, VideoChromaSubsampling, VideoCodec,
11 VideoColorInfo, VideoColorMatrix, VideoColorRange, VideoComponentBitDepth, VideoContainerInfo,
12 VideoDecodeProfile, VideoFrame, VideoFrameTiming, VideoPacket, Vp9Parser, Vp9Profile,
13 parse_h264_pps, parse_h264_slice_header, parse_h264_sps, parse_h265_pps, parse_h265_slice_header,
14 parse_h265_sps, parse_h265_vps, parse_nal_annex_b,
15};
16
17pub struct VideoDecoder {
26 state: Option<DecoderState>,
27}
28
29struct DecoderState {
30 backend: VideoDecoderBackend,
31 info: VideoContainerInfo,
32 codec: DecoderCodecState,
33 pending_display: BTreeMap<(u64, u64), VideoFrame>,
34 next_decode_sequence: u64,
35 reorder_depth: usize,
36 require_random_access: bool,
37 h265_skip_rasl: bool,
38 output_mode: Option<DecodeOutputMode>,
39}
40
41#[derive(Clone, Copy, PartialEq, Eq)]
42enum DecodeOutputMode {
43 HostPlanar,
44 Native,
45 RecordedPlanes,
46}
47
48enum DecodedBacking {
49 HostPlanar(crate::video::VideoHostPlanes),
50 Native(crate::runtime::NativeDecodedFrame),
51 DevicePlanar(super::DevicePlanar),
52}
53
54enum DecoderCodecState {
55 H264 {
56 sequence_parameter_set: Option<Box<H264SequenceParameterSet>>,
57 picture_parameter_set: Option<Box<H264PictureParameterSet>>,
58 },
59 H265 {
60 video_parameter_set: Option<Box<H265VideoParameterSet>>,
61 sequence_parameter_set: Option<Box<H265SequenceParameterSet>>,
62 picture_parameter_set: Option<Box<H265PictureParameterSet>>,
63 },
64 Av1 {
65 parser: Box<Av1Parser>,
66 parameter_sequence: Option<Box<Av1SequenceHeader>>,
67 },
68 Vp9 {
69 parser: Vp9Parser,
70 },
71}
72
73impl VideoDecoder {
74 pub fn new(runtime: &Runtime, info: VideoContainerInfo) -> Result<Self> {
83 let profile = info.decode_profile().ok_or_else(|| {
84 Error::missing_capability("the stream has no Vulkan-queryable decode profile")
85 })?;
86 let backend = VideoDecoderBackend::create(
87 runtime,
88 profile,
89 super::VideoExtent {
90 width: info.width(),
91 height: info.height(),
92 },
93 )?;
94 Self::with_backend(info, profile, backend)
95 }
96
97 fn with_backend(
98 info: VideoContainerInfo,
99 profile: VideoDecodeProfile,
100 backend: VideoDecoderBackend,
101 ) -> Result<Self> {
102 let codec = match (info.codec(), profile) {
103 (
104 VideoCodec::H264,
105 VideoDecodeProfile::H264 {
106 profile: H264Profile::Baseline | H264Profile::Main | H264Profile::High,
107 picture_layout: H264PictureLayout::Progressive,
108 chroma_subsampling: VideoChromaSubsampling::Yuv420,
109 luma_bit_depth: VideoComponentBitDepth::Eight,
110 chroma_bit_depth: VideoComponentBitDepth::Eight,
111 },
112 )
113 | (
114 VideoCodec::H264,
115 VideoDecodeProfile::H264 {
116 profile: H264Profile::High10,
117 picture_layout: H264PictureLayout::Progressive,
118 chroma_subsampling: VideoChromaSubsampling::Yuv420,
119 luma_bit_depth: VideoComponentBitDepth::Ten,
120 chroma_bit_depth: VideoComponentBitDepth::Ten,
121 },
122 ) => DecoderCodecState::H264 {
123 sequence_parameter_set: None,
124 picture_parameter_set: None,
125 },
126 (
127 VideoCodec::H265,
128 VideoDecodeProfile::H265 {
129 profile: H265Profile::Main | H265Profile::Main10 | H265Profile::MainStillPicture,
130 chroma_subsampling: VideoChromaSubsampling::Yuv420,
131 luma_bit_depth: VideoComponentBitDepth::Eight | VideoComponentBitDepth::Ten,
132 chroma_bit_depth: VideoComponentBitDepth::Eight | VideoComponentBitDepth::Ten,
133 },
134 ) => DecoderCodecState::H265 {
135 video_parameter_set: None,
136 sequence_parameter_set: None,
137 picture_parameter_set: None,
138 },
139 (
140 VideoCodec::Av1,
141 VideoDecodeProfile::Av1 {
142 profile: Av1Profile::Main,
143 film_grain_support: false,
144 chroma_subsampling: VideoChromaSubsampling::Yuv420,
145 luma_bit_depth: VideoComponentBitDepth::Eight | VideoComponentBitDepth::Ten,
146 chroma_bit_depth: VideoComponentBitDepth::Eight | VideoComponentBitDepth::Ten,
147 },
148 ) => DecoderCodecState::Av1 {
149 parser: Box::new(Av1Parser::default()),
150 parameter_sequence: None,
151 },
152 (
153 VideoCodec::Vp9,
154 VideoDecodeProfile::Vp9 {
155 profile: Vp9Profile::Profile0 | Vp9Profile::Profile2,
156 chroma_subsampling: VideoChromaSubsampling::Yuv420,
157 luma_bit_depth: VideoComponentBitDepth::Eight | VideoComponentBitDepth::Ten,
158 chroma_bit_depth: VideoComponentBitDepth::Eight | VideoComponentBitDepth::Ten,
159 },
160 ) => DecoderCodecState::Vp9 {
161 parser: Vp9Parser::default(),
162 },
163 _ => {
164 return Err(Error::missing_capability(
165 "the public decoder admits progressive H.264 Baseline/Main/High/High10, H.265 Main/Main10/MainStillPicture, AV1 Main 8/10-bit 4:2:0 without film grain, and VP9 Profile 0/2 8/10-bit 4:2:0",
166 ));
167 }
168 };
169 Ok(Self {
170 state: Some(DecoderState {
171 backend,
172 info,
173 codec,
174 pending_display: BTreeMap::new(),
175 next_decode_sequence: 0,
176 reorder_depth: 0,
177 require_random_access: true,
178 h265_skip_rasl: false,
179 output_mode: None,
180 }),
181 })
182 }
183
184 pub fn decode(&mut self, packet: &VideoPacket) -> Result<Option<VideoFrame>> {
196 self.decode_with_mode(packet, DecodeOutputMode::HostPlanar)
197 }
198
199 pub fn decode_native(&mut self, packet: &VideoPacket) -> Result<Option<VideoFrame>> {
217 self.decode_with_mode(packet, DecodeOutputMode::Native)
218 }
219
220 pub fn read_native_yuv420p(&mut self, frame: &VideoFrame) -> Result<Vec<u8>> {
234 let state = self
235 .state
236 .as_mut()
237 .ok_or_else(|| Error::failed_precondition("VideoDecoder is closed"))?;
238 let native = frame.native_backing().ok_or_else(|| {
239 Error::invalid_argument("native video readback requires a native decoded frame")
240 })?;
241 match state.backend.read_native_yuv420(native)? {
242 crate::video::VideoHostPlanes::U8(bytes) => Ok(std::sync::Arc::unwrap_or_clone(bytes)),
243 crate::video::VideoHostPlanes::U16(_) => Err(Error::missing_capability(
244 "read_native_yuv420p requires an 8-bit native frame; use read_native_yuv420p10",
245 )),
246 }
247 }
248
249 pub fn read_native_yuv420p10(&mut self, frame: &VideoFrame) -> Result<Vec<u16>> {
260 let state = self
261 .state
262 .as_mut()
263 .ok_or_else(|| Error::failed_precondition("VideoDecoder is closed"))?;
264 let native = frame.native_backing().ok_or_else(|| {
265 Error::invalid_argument("native video readback requires a native decoded frame")
266 })?;
267 match state.backend.read_native_yuv420(native)? {
268 crate::video::VideoHostPlanes::U16(bytes) => Ok(std::sync::Arc::unwrap_or_clone(bytes)),
269 crate::video::VideoHostPlanes::U8(_) => Err(Error::missing_capability(
270 "read_native_yuv420p10 requires a 10- or 12-bit native frame",
271 )),
272 }
273 }
274
275 pub fn native_frame_texture(&mut self, frame: &VideoFrame) -> Result<Texture> {
291 let state = self
292 .state
293 .as_mut()
294 .ok_or_else(|| Error::failed_precondition("VideoDecoder is closed"))?;
295 let native = frame.native_backing().ok_or_else(|| {
296 Error::invalid_argument("native frame conversion requires a native decoded frame")
297 })?;
298 let color = frame.color_info();
299 let color_space = match color.matrix() {
300 VideoColorMatrix::Bt601 => 0_u32,
301 VideoColorMatrix::Bt709 | VideoColorMatrix::Unspecified => 1_u32,
302 VideoColorMatrix::Bt2020 => 2_u32,
303 };
304 let full_range = matches!(color.range(), VideoColorRange::Full);
305 let (storage, width, height) =
306 state
307 .backend
308 .read_native_rgba8(native, color_space, full_range)?;
309 let data = Matrix::from_runtime_storage(
310 state.backend.runtime(),
311 storage,
312 vec![height as usize, width as usize, 4],
313 DType::U8,
314 )?;
315 crate::render::texture_from_matrix(data, width as usize, height as usize)
316 }
317
318 pub fn stage_native_planes(&self, frame: &VideoFrame) -> Result<VideoFrame> {
330 let state = self
331 .state
332 .as_ref()
333 .ok_or_else(|| Error::failed_precondition("VideoDecoder is closed"))?;
334 let native = frame
335 .native_backing()
336 .ok_or_else(|| Error::invalid_argument("plane staging requires a native decoded frame"))?;
337 let width = frame.width();
338 let height = frame.height();
339 let format = native.format();
340 let planes = state
341 .backend
342 .allocate_decoded_planes(format, width, height)?;
343 state.backend.stage_native_planes(native, &planes.planes)?;
344 Ok(VideoFrame::from_device_planar(
345 planes,
346 frame.timing(),
347 frame.color_info(),
348 ))
349 }
350
351 pub fn record_to_planes(&self, packets: &[VideoPacket]) -> Result<Vec<VideoFrame>> {
369 let state = self
370 .state
371 .as_ref()
372 .ok_or_else(|| Error::failed_precondition("VideoDecoder is closed"))?;
373 if packets.is_empty() {
374 return Err(Error::invalid_argument(
375 "recorded decode requires at least one packet",
376 ));
377 }
378 let profile = state
379 .info
380 .decode_profile()
381 .ok_or_else(|| Error::internal("open decoder has no decode profile"))?;
382 let mut recording =
383 Self::with_backend(state.info, profile, state.backend.begin_decode_capture()?)?;
384 let mut frames = Vec::with_capacity(packets.len());
385 for packet in packets {
386 if let Some(frame) = recording.decode_with_mode(packet, DecodeOutputMode::RecordedPlanes)? {
387 frames.push(frame);
388 }
389 }
390 let recording = recording
391 .state
392 .take()
393 .ok_or_else(|| Error::internal("video decode recording was closed"))?;
394 frames.extend(recording.pending_display.into_values());
395 recording.backend.finish_decode_capture()?;
396 Ok(frames)
397 }
398
399 pub(crate) fn stage_native_canvas_frame(&mut self, frame: &VideoFrame) -> Result<VideoFrame> {
400 let state = self
401 .state
402 .as_mut()
403 .ok_or_else(|| Error::failed_precondition("VideoDecoder is closed"))?;
404 let native = frame
405 .native_backing()
406 .ok_or_else(|| Error::invalid_argument("canvas staging requires a native decoded frame"))?;
407 let (storage, layout) = state.backend.stage_native_canvas_planes(native)?;
408 Ok(frame.with_canvas_planes(storage, layout))
409 }
410
411 fn decode_with_mode(
412 &mut self,
413 packet: &VideoPacket,
414 output_mode: DecodeOutputMode,
415 ) -> Result<Option<VideoFrame>> {
416 let state = self
417 .state
418 .as_mut()
419 .ok_or_else(|| Error::failed_precondition("VideoDecoder is closed"))?;
420 state.backend.require_decode_submission()?;
421 if packet.track_id() != state.info.track_id() {
422 return Err(Error::invalid_argument(
423 "video packet track does not match the decoder stream",
424 ));
425 }
426 if state.require_random_access && !packet.is_keyframe() {
427 return Err(Error::failed_precondition(
428 "the first packet after create or flush must be random access",
429 ));
430 }
431 if state
432 .output_mode
433 .is_some_and(|active| active != output_mode)
434 {
435 return Err(Error::failed_precondition(
436 "video decoder output mode cannot change before flush",
437 ));
438 }
439
440 let decoded =
441 match &mut state.codec {
442 DecoderCodecState::H264 {
443 sequence_parameter_set,
444 picture_parameter_set,
445 } => {
446 let nals = parse_nal_annex_b(packet.data());
447 if sequence_parameter_set.is_none() {
448 let (sps, pps) = h264_parameters(&nals, state.info)?;
449 state.backend.set_h264_parameters(&sps, &pps)?;
450 state.reorder_depth = sps
451 .vui
452 .as_ref()
453 .and_then(|vui| vui.bitstream_restriction)
454 .map_or(16, |restriction| {
455 restriction.max_num_reorder_frames as usize
456 });
457 *sequence_parameter_set = Some(Box::new(sps));
458 *picture_parameter_set = Some(Box::new(pps));
459 }
460 let sps = sequence_parameter_set.as_ref().ok_or_else(|| {
461 Error::failed_precondition("H.264 decoder has no sequence parameter set")
462 })?;
463 let pps = picture_parameter_set.as_ref().ok_or_else(|| {
464 Error::failed_precondition("H.264 decoder has no picture parameter set")
465 })?;
466 if output_mode == DecodeOutputMode::RecordedPlanes && !state.require_random_access {
467 for nal in &nals {
468 let changed = match nal.nal_unit_type() {
469 7 => parse_h264_sps(nal.payload())? != **sps,
470 8 => parse_h264_pps(nal.payload(), sps)? != **pps,
471 _ => false,
472 };
473 if changed {
474 return Err(Error::missing_capability(
475 "recorded H.264 parameter sets must remain unchanged",
476 ));
477 }
478 }
479 }
480 let (coded_slice, slice) = h264_picture(&nals, sps, pps)?;
481 let backing =
482 match output_mode {
483 DecodeOutputMode::HostPlanar => DecodedBacking::HostPlanar(
484 state.backend.decode_h264(coded_slice, sps, pps, &slice)?,
485 ),
486 DecodeOutputMode::Native => DecodedBacking::Native(
487 state
488 .backend
489 .decode_h264_native(coded_slice, sps, pps, &slice)?,
490 ),
491 DecodeOutputMode::RecordedPlanes => DecodedBacking::DevicePlanar(
492 state
493 .backend
494 .record_h264_picture(coded_slice, sps, pps, &slice)?,
495 ),
496 };
497 Some((
498 backing,
499 usize::try_from(state.info.width())
500 .map_err(|_| Error::out_of_range("H.264 width exceeds usize"))?,
501 usize::try_from(state.info.height())
502 .map_err(|_| Error::out_of_range("H.264 height exceeds usize"))?,
503 h264_color_info(sps),
504 ))
505 }
506 DecoderCodecState::H265 {
507 video_parameter_set,
508 sequence_parameter_set,
509 picture_parameter_set,
510 } => {
511 let nals = parse_nal_annex_b(packet.data());
512 let find_parameter = |nal_type| {
513 nals
514 .iter()
515 .find(|nal| ((nal.payload()[0] >> 1) & 0x3f) == nal_type)
516 .map(|nal| nal.payload())
517 };
518 if sequence_parameter_set.is_none() {
519 let vps = parse_h265_vps(find_parameter(32).ok_or_else(|| {
520 Error::failed_precondition("initial H.265 packet contains no VPS")
521 })?)?;
522 let sps = parse_h265_sps(find_parameter(33).ok_or_else(|| {
523 Error::failed_precondition("initial H.265 packet contains no SPS")
524 })?)?;
525 let pps = parse_h265_pps(find_parameter(34).ok_or_else(|| {
526 Error::failed_precondition("initial H.265 packet contains no PPS")
527 })?)?;
528 if sps.width != state.info.width() || sps.height != state.info.height() {
529 return Err(Error::invalid_argument(
530 "H.265 parameter-set geometry differs from container metadata",
531 ));
532 }
533 state.backend.set_h265_parameters(&vps, &sps, &pps)?;
534 let sub_layer = usize::try_from(sps.max_sub_layers_minus_1)
535 .map_err(|_| Error::out_of_range("H.265 sub-layer index exceeds usize"))?;
536 state.reorder_depth =
537 usize::try_from(*sps.max_num_reorder_pictures.get(sub_layer).ok_or_else(|| {
538 Error::data_loss("H.265 SPS reorder depth has no active sub-layer")
539 })?)
540 .map_err(|_| Error::out_of_range("H.265 reorder depth exceeds usize"))?;
541 if output_mode == DecodeOutputMode::RecordedPlanes {
542 *video_parameter_set = Some(Box::new(vps));
543 }
544 *sequence_parameter_set = Some(Box::new(sps));
545 *picture_parameter_set = Some(Box::new(pps));
546 }
547 let sps = sequence_parameter_set.as_ref().ok_or_else(|| {
548 Error::failed_precondition("H.265 decoder has no sequence parameter set")
549 })?;
550 let pps = picture_parameter_set.as_ref().ok_or_else(|| {
551 Error::failed_precondition("H.265 decoder has no picture parameter set")
552 })?;
553 if output_mode == DecodeOutputMode::RecordedPlanes && !state.require_random_access {
554 for nal in &nals {
555 let changed = match (nal.payload()[0] >> 1) & 0x3f {
556 32 => video_parameter_set.as_deref() != Some(&parse_h265_vps(nal.payload())?),
557 33 => parse_h265_sps(nal.payload())? != **sps,
558 34 => parse_h265_pps(nal.payload())? != **pps,
559 _ => false,
560 };
561 if changed {
562 return Err(Error::missing_capability(
563 "recorded HEVC parameter sets must remain unchanged",
564 ));
565 }
566 }
567 }
568 let mut coded = nals
569 .iter()
570 .filter(|nal| ((nal.payload()[0] >> 1) & 0x3f) < 32);
571 let slice_nal = coded
572 .next()
573 .ok_or_else(|| Error::invalid_argument("H.265 access unit contains no coded slice"))?;
574 if coded.next().is_some() {
575 return Err(Error::missing_capability(
576 "the H.265 decoder currently accepts one slice segment per picture",
577 ));
578 }
579 let slice = parse_h265_slice_header(slice_nal.payload(), sps, pps)?;
580 if state.require_random_access {
581 if !slice.is_irap {
582 return Err(Error::data_loss(
583 "H.265 random access requires an IRAP picture",
584 ));
585 }
586 state.backend.restart_h265()?;
587 }
588 if slice.is_irap {
589 state.h265_skip_rasl =
590 state.require_random_access || (16..=20).contains(&slice.nal_unit_type);
591 }
592 if state.h265_skip_rasl && (8..=9).contains(&slice.nal_unit_type) {
595 return Ok(None);
596 }
597
598 let coded_slice = slice_nal.prefixed_slice()?;
599 let backing =
600 match output_mode {
601 DecodeOutputMode::HostPlanar => DecodedBacking::HostPlanar(
602 state.backend.decode_h265(coded_slice, sps, pps, &slice)?,
603 ),
604 DecodeOutputMode::Native => DecodedBacking::Native(
605 state
606 .backend
607 .decode_h265_native(coded_slice, sps, pps, &slice)?,
608 ),
609 DecodeOutputMode::RecordedPlanes => DecodedBacking::DevicePlanar(
610 state
611 .backend
612 .record_h265_picture(coded_slice, sps, pps, &slice)?,
613 ),
614 };
615 Some((
616 backing,
617 usize::try_from(sps.width)
618 .map_err(|_| Error::out_of_range("H.265 width exceeds usize"))?,
619 usize::try_from(sps.height)
620 .map_err(|_| Error::out_of_range("H.265 height exceeds usize"))?,
621 h265_color_info(sps),
622 ))
623 }
624 DecoderCodecState::Av1 {
625 parser,
626 parameter_sequence,
627 } => {
628 let mut next_parser = parser.clone();
629 let pictures = next_parser.parse_access_unit(packet.data())?;
630 if pictures.is_empty() {
631 return Err(Error::invalid_argument(
632 "AV1 access unit contains no complete picture",
633 ));
634 }
635 if pictures
636 .iter()
637 .filter(|picture| picture.frame.show_existing_frame || picture.frame.show_frame)
638 .count()
639 > 1
640 {
641 return Err(Error::missing_capability(
642 "one AV1 packet exposes more than one display picture",
643 ));
644 }
645 let sequence = &pictures[0].sequence;
646 if pictures.iter().any(|picture| picture.sequence != *sequence) {
647 return Err(Error::missing_capability(
648 "AV1 sequence changes within one access unit",
649 ));
650 }
651 if pictures.iter().any(|picture| {
652 picture.frame.frame_size_override
653 || picture.frame.use_superres
654 || picture.frame.render_and_frame_size_different
655 }) {
656 return Err(Error::missing_capability(
657 "AV1 per-picture size override, super-resolution, and distinct render size are not admitted",
658 ));
659 }
660 if sequence.coded_width() != state.info.width()
661 || sequence.coded_height() != state.info.height()
662 {
663 return Err(Error::invalid_argument(
664 "AV1 sequence geometry differs from container metadata",
665 ));
666 }
667 match parameter_sequence {
668 Some(current) if current.as_ref() != sequence => {
669 return Err(Error::missing_capability(
670 "AV1 sequence changes require a new decoder session",
671 ));
672 }
673 Some(_) => {}
674 None => {
675 state.backend.set_av1_parameters(sequence)?;
676 *parameter_sequence = Some(Box::new(sequence.clone()));
677 }
678 }
679 state.reorder_depth = 0;
680 let mut displayed = None;
681 for picture in &pictures {
682 let backing = match output_mode {
683 DecodeOutputMode::RecordedPlanes => state
684 .backend
685 .record_av1_picture(packet.data(), picture)?
686 .map(DecodedBacking::DevicePlanar),
687 DecodeOutputMode::HostPlanar => {
688 let planes = if picture.frame.show_existing_frame {
689 state.backend.show_existing_av1(&picture.frame)?
690 } else {
691 state.backend.decode_av1(packet.data(), picture)?
692 };
693 Some(DecodedBacking::HostPlanar(planes))
694 }
695 DecodeOutputMode::Native => {
696 let frame = if picture.frame.show_existing_frame {
697 state.backend.show_existing_av1_native(&picture.frame)?
698 } else {
699 state.backend.decode_av1_native(packet.data(), picture)?
700 };
701 Some(DecodedBacking::Native(frame))
702 }
703 };
704 if (picture.frame.show_existing_frame || picture.frame.show_frame)
705 && let Some(backing) = backing
706 {
707 displayed = Some(backing);
708 }
709 }
710 *parser = next_parser;
711 displayed.map(|backing| {
712 (
713 backing,
714 usize::from(sequence.max_frame_width_minus_1) + 1,
715 usize::from(sequence.max_frame_height_minus_1) + 1,
716 av1_color_info(sequence),
717 )
718 })
719 }
720 DecoderCodecState::Vp9 { parser } => {
721 let mut next_parser = parser.clone();
722 let pictures = next_parser.parse_access_unit(packet.data())?;
723 if pictures.is_empty() {
724 return Err(Error::invalid_argument(
725 "VP9 access unit contains no complete picture",
726 ));
727 }
728 if pictures
729 .iter()
730 .filter(|picture| picture.show_existing_frame || picture.show_frame)
731 .count()
732 > 1
733 {
734 return Err(Error::missing_capability(
735 "one VP9 packet exposes more than one display picture",
736 ));
737 }
738 if pictures.iter().any(|picture| {
739 !matches!(picture.profile, 0 | 2)
740 || !matches!(picture.color.bit_depth, 8 | 10)
741 || !picture.color.subsampling_x
742 || !picture.color.subsampling_y
743 }) {
744 return Err(Error::missing_capability(
745 "the public VP9 decoder admits Profile 0/2 8/10-bit 4:2:0 only",
746 ));
747 }
748 if pictures.iter().any(|picture| {
749 picture.frame_width != state.info.width()
750 || picture.frame_height != state.info.height()
751 || picture.render_width != picture.frame_width
752 || picture.render_height != picture.frame_height
753 }) {
754 return Err(Error::missing_capability(
755 "VP9 dynamic coded or distinct render extents are not admitted",
756 ));
757 }
758 state.reorder_depth = 0;
759 let mut displayed = None;
760 for picture in &pictures {
761 let backing = match output_mode {
762 DecodeOutputMode::RecordedPlanes => state
763 .backend
764 .record_vp9_picture(packet.data(), picture)?
765 .map(DecodedBacking::DevicePlanar),
766 DecodeOutputMode::HostPlanar => {
767 let planes = if picture.show_existing_frame {
768 state.backend.show_existing_vp9(picture)?
769 } else {
770 state.backend.decode_vp9(packet.data(), picture)?
771 };
772 Some(DecodedBacking::HostPlanar(planes))
773 }
774 DecodeOutputMode::Native => {
775 let frame = if picture.show_existing_frame {
776 state.backend.show_existing_vp9_native(picture)?
777 } else {
778 state.backend.decode_vp9_native(packet.data(), picture)?
779 };
780 Some(DecodedBacking::Native(frame))
781 }
782 };
783 if (picture.show_existing_frame || picture.show_frame)
784 && let Some(backing) = backing
785 {
786 displayed = Some((backing, picture.color));
787 }
788 }
789 *parser = next_parser;
790 displayed.map(|(backing, color)| {
791 (
792 backing,
793 state.info.width() as usize,
794 state.info.height() as usize,
795 vp9_color_info(color),
796 )
797 })
798 }
799 };
800 state.require_random_access = false;
801 state.output_mode = Some(output_mode);
802 let Some((backing, width, height, color)) = decoded else {
803 return Ok(None);
804 };
805 let timing = packet_timing(packet, state.info)?;
806 let frame = match backing {
807 DecodedBacking::HostPlanar(planes) => {
808 VideoFrame::from_host_planes(planes, width, height, timing, color)?
809 }
810 DecodedBacking::Native(frame) => VideoFrame::from_native(frame, timing, color),
811 DecodedBacking::DevicePlanar(planes) => VideoFrame::from_device_planar(planes, timing, color),
812 };
813 let sequence = state.next_decode_sequence;
814 state.next_decode_sequence = state
815 .next_decode_sequence
816 .checked_add(1)
817 .ok_or_else(|| Error::resource_exhausted("video decode sequence exhausted"))?;
818 state
819 .pending_display
820 .insert((packet.presentation_timestamp(), sequence), frame);
821 if state.pending_display.len() > state.reorder_depth {
822 Ok(state.pending_display.pop_first().map(|(_, frame)| frame))
823 } else {
824 Ok(None)
825 }
826 }
827
828 pub fn flush(&mut self) -> Result<Vec<VideoFrame>> {
833 let state = self
834 .state
835 .as_mut()
836 .ok_or_else(|| Error::failed_precondition("VideoDecoder is closed"))?;
837 state.require_random_access = true;
838 state.output_mode = None;
839 Ok(
840 std::mem::take(&mut state.pending_display)
841 .into_values()
842 .collect(),
843 )
844 }
845
846 pub fn close(&mut self) {
848 self.state = None;
849 }
850
851 #[must_use]
853 pub const fn is_open(&self) -> bool {
854 self.state.is_some()
855 }
856
857 #[must_use]
859 pub fn info(&self) -> Option<VideoContainerInfo> {
860 self.state.as_ref().map(|state| state.info)
861 }
862}
863
864fn h264_parameters(
865 nals: &[NalUnit<'_>],
866 info: VideoContainerInfo,
867) -> Result<(H264SequenceParameterSet, H264PictureParameterSet)> {
868 let parameter = |kind| {
869 nals
870 .iter()
871 .find(|nal| nal.nal_unit_type() == kind)
872 .map(|nal| nal.payload())
873 };
874 let sps = parse_h264_sps(
875 parameter(7)
876 .ok_or_else(|| Error::failed_precondition("initial H.264 packet contains no SPS"))?,
877 )?;
878 let pps = parse_h264_pps(
879 parameter(8)
880 .ok_or_else(|| Error::failed_precondition("initial H.264 packet contains no PPS"))?,
881 &sps,
882 )?;
883 if !sps.frame_mbs_only || !matches!(sps.pic_order_count_type, 0 | 2) {
884 return Err(Error::missing_capability(
885 "the H.264 decoder currently requires progressive POC-type-zero or POC-type-two streams",
886 ));
887 }
888 let (_, visible) = sps.progressive_420_crop()?;
889 if visible.width != info.width() || visible.height != info.height() {
890 return Err(Error::invalid_argument(
891 "H.264 parameter-set geometry differs from container metadata",
892 ));
893 }
894 Ok((sps, pps))
895}
896
897fn h264_picture<'a>(
898 nals: &[NalUnit<'a>],
899 sps: &H264SequenceParameterSet,
900 pps: &H264PictureParameterSet,
901) -> Result<(&'a [u8], H264SliceHeader)> {
902 let mut coded = nals
903 .iter()
904 .filter(|nal| matches!(nal.nal_unit_type(), 1 | 5));
905 let nal = coded
906 .next()
907 .ok_or_else(|| Error::invalid_argument("H.264 access unit contains no coded slice"))?;
908 if coded.next().is_some() {
909 return Err(Error::missing_capability(
910 "the H.264 decoder currently accepts one slice per picture",
911 ));
912 }
913 let slice = parse_h264_slice_header(nal.payload(), sps, pps)?;
914 Ok((nal.prefixed_slice()?, slice))
915}
916
917fn packet_timing(packet: &VideoPacket, info: VideoContainerInfo) -> Result<VideoFrameTiming> {
918 let time_base = info.time_base();
919 let pts = ticks_to_duration(packet.presentation_timestamp(), time_base)?;
920 let duration = (packet.duration() != 0)
921 .then(|| ticks_to_duration(u64::from(packet.duration()), time_base))
922 .transpose()?;
923 VideoFrameTiming::new(pts, duration)
924}
925
926fn ticks_to_duration(ticks: u64, time_base: super::VideoTimeBase) -> Result<Duration> {
927 let nanos = u128::from(ticks)
928 .checked_mul(u128::from(time_base.numerator()))
929 .and_then(|value| value.checked_mul(1_000_000_000))
930 .ok_or_else(|| Error::out_of_range("video timestamp overflows nanoseconds"))?
931 / u128::from(time_base.denominator());
932 let seconds = u64::try_from(nanos / 1_000_000_000)
933 .map_err(|_| Error::out_of_range("video timestamp exceeds Duration"))?;
934 let subsec_nanos = u32::try_from(nanos % 1_000_000_000)
935 .map_err(|_| Error::out_of_range("video timestamp remainder exceeds u32"))?;
936 Ok(Duration::new(seconds, subsec_nanos))
937}
938
939fn h264_color_info(sps: &H264SequenceParameterSet) -> VideoColorInfo {
940 let Some(signal) = sps.vui.as_ref().and_then(|vui| vui.video_signal) else {
941 return VideoColorInfo::unspecified();
942 };
943 video_color_info(
944 signal
945 .colour_description
946 .map(|description| description.matrix_coefficients),
947 signal.full_range,
948 )
949}
950
951fn h265_color_info(sps: &H265SequenceParameterSet) -> VideoColorInfo {
952 let Some(signal) = sps.vui.as_ref().and_then(|vui| vui.video_signal) else {
953 return VideoColorInfo::unspecified();
954 };
955 video_color_info(
956 signal
957 .colour_description
958 .map(|description| description.matrix_coefficients),
959 signal.full_range,
960 )
961}
962
963fn av1_color_info(sequence: &Av1SequenceHeader) -> VideoColorInfo {
964 video_color_info(
965 sequence
966 .color
967 .color_description
968 .map(|description| description.matrix_coefficients),
969 sequence.color.full_range,
970 )
971}
972
973fn vp9_color_info(color: super::vp9::Vp9ColorConfig) -> VideoColorInfo {
974 let matrix = match color.color_space {
975 1 | 3 => VideoColorMatrix::Bt601,
976 2 => VideoColorMatrix::Bt709,
977 5 => VideoColorMatrix::Bt2020,
978 _ => VideoColorMatrix::Unspecified,
979 };
980 VideoColorInfo::new(
981 matrix,
982 if color.full_range {
983 VideoColorRange::Full
984 } else {
985 VideoColorRange::Limited
986 },
987 )
988}
989
990fn video_color_info(matrix_coefficients: Option<u8>, full_range: bool) -> VideoColorInfo {
991 let matrix = match matrix_coefficients {
992 Some(5 | 6) => VideoColorMatrix::Bt601,
993 Some(1) => VideoColorMatrix::Bt709,
994 Some(9) => VideoColorMatrix::Bt2020,
995 _ => VideoColorMatrix::Unspecified,
996 };
997 VideoColorInfo::new(
998 matrix,
999 if full_range {
1000 VideoColorRange::Full
1001 } else {
1002 VideoColorRange::Limited
1003 },
1004 )
1005}