1use crate::{
2 AudioBuffer, Codec, ColorRange, Error, ErrorKind, FrameIndex, FrameSource, Limits, PixelFormat,
3 Plane, Result, VideoDimensions, VideoFrame,
4};
5use std::borrow::Cow;
6use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
7use std::future::Future;
8use std::pin::Pin;
9use std::sync::Arc;
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::time::Duration;
12
13pub type EncoderFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + 'a>>;
15
16#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum TrackKind {
19 Video,
20 Audio,
21}
22
23#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub struct SampleDependency {
26 pub is_leading: u8,
27 pub depends_on: u8,
28 pub is_depended_on: u8,
29 pub has_redundancy: u8,
30}
31
32impl SampleDependency {
33 pub const INDEPENDENT: Self = Self {
34 is_leading: 0,
35 depends_on: 2,
36 is_depended_on: 0,
37 has_redundancy: 0,
38 };
39
40 pub const DEPENDENT: Self = Self {
41 is_leading: 0,
42 depends_on: 1,
43 is_depended_on: 0,
44 has_redundancy: 0,
45 };
46
47 #[doc(hidden)]
48 pub fn to_sdtp(self) -> u8 {
49 ((self.is_leading & 3) << 6)
50 | ((self.depends_on & 3) << 4)
51 | ((self.is_depended_on & 3) << 2)
52 | (self.has_redundancy & 3)
53 }
54}
55
56#[derive(Clone, Debug, Eq, PartialEq)]
58pub struct EncodedSample {
59 pub data: Vec<u8>,
60 pub dts: i64,
61 pub pts: i64,
62 pub duration: u32,
63 pub is_sync: bool,
64 pub dependency: SampleDependency,
65}
66
67#[derive(Clone, Debug, Eq, PartialEq)]
69pub struct EncoderConfig {
70 pub codec: Codec,
71 pub timescale: u32,
72 pub decoder_config: Vec<u8>,
74}
75
76#[derive(Clone, Copy, Debug, Eq, PartialEq)]
78pub struct VideoEncoderFormat {
79 pub dimensions: VideoDimensions,
80 pub pixel_format: PixelFormat,
81}
82
83#[derive(Clone, Copy, Debug, Eq, PartialEq)]
85pub struct AudioEncoderFormat {
86 pub sample_rate: u32,
87 pub channels: u16,
88}
89
90#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
92pub struct AudioGapless {
93 pub priming: u32,
94 pub padding: u32,
95}
96
97#[derive(Clone, Debug, Default, Eq, PartialEq)]
99pub struct AudioDrain {
100 pub samples: Vec<EncodedSample>,
101 pub gapless: AudioGapless,
102}
103
104pub trait VideoEncoder {
106 fn config(&self) -> &EncoderConfig;
107 fn format(&self) -> VideoEncoderFormat;
108 fn implementation(&self) -> CodecImplementation {
117 CodecImplementation::Software
118 }
119 fn backend_name(&self) -> &str {
123 "zvidlib"
124 }
125 fn encode<'a>(
126 &'a mut self,
127 index: FrameIndex,
128 frame: FrameSource<'a>,
129 ) -> EncoderFuture<'a, Vec<EncodedSample>>;
130 fn finish<'a>(&'a mut self) -> EncoderFuture<'a, Vec<EncodedSample>>;
131}
132
133pub trait AudioEncoder {
156 fn config(&self) -> &EncoderConfig;
157 fn format(&self) -> AudioEncoderFormat;
158 fn encode<'a>(
159 &'a mut self,
160 index: FrameIndex,
161 buffer: AudioBuffer,
162 ) -> EncoderFuture<'a, Vec<EncodedSample>>;
163 fn finish<'a>(&'a mut self) -> EncoderFuture<'a, AudioDrain>;
164}
165
166#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
168#[non_exhaustive]
169pub enum CodecProfile {
170 UncompressedGray8,
171 H264Baseline,
174 H264Main,
176 H264High,
179 HevcMain,
180 HevcMain10,
181 Av1Main,
182 Av1High,
183 Av1Professional,
184 Vp8,
187 Vp9Profile0,
189 Vp9Profile1,
191 Vp9Profile2,
193 Vp9Profile3,
195 AacLowComplexity,
196 Opus,
198 Vorbis,
200}
201
202#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
204#[non_exhaustive]
205pub enum HardwarePreference {
206 Require,
207 Prefer,
208 Avoid,
209}
210
211#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
213#[non_exhaustive]
214pub enum CodecImplementation {
215 Software,
216 Hardware,
217}
218
219#[derive(Clone, Debug, Eq, PartialEq)]
221#[non_exhaustive]
222pub enum CodecSupport {
223 Supported { implementation: CodecImplementation },
224 UnsupportedCodec,
225 UnsupportedProfile,
226 InvalidConfiguration { reason: String },
227 HardwareUnavailable,
228}
229
230impl CodecSupport {
231 pub const fn is_supported(&self) -> bool {
232 matches!(self, Self::Supported { .. })
233 }
234}
235
236#[derive(Clone, Debug, Eq, PartialEq)]
238pub struct VideoDecoderConfig {
239 pub codec: Codec,
240 pub profile: CodecProfile,
241 pub coded_dimensions: VideoDimensions,
242 pub output_format: PixelFormat,
243 pub color_range: ColorRange,
244 pub hardware: HardwarePreference,
245 pub configuration: Vec<u8>,
247}
248
249#[derive(Clone, Debug, Eq, PartialEq)]
251pub struct VideoEncoderConfig {
252 pub codec: Codec,
253 pub profile: CodecProfile,
254 pub coded_dimensions: VideoDimensions,
255 pub input_format: PixelFormat,
256 pub color_range: ColorRange,
257 pub hardware: HardwarePreference,
258 pub timescale: u32,
260 pub frame_duration: u32,
262 pub configuration: Vec<u8>,
263}
264
265#[derive(Clone, Debug, Eq, PartialEq)]
267pub struct EncodedVideoSample {
268 pub presentation_index: FrameIndex,
269 pub random_access: bool,
270 pub data: Vec<u8>,
271}
272
273pub trait SampleProvider: Send {
290 fn len(&self) -> usize;
292 fn is_empty(&self) -> bool {
293 self.len() == 0
294 }
295 fn is_random_access(&self, decode_index: usize) -> bool;
296 fn presentation_index(&self, decode_index: usize) -> FrameIndex;
297 fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>>;
299}
300
301impl SampleProvider for Vec<EncodedVideoSample> {
302 fn len(&self) -> usize {
303 self.as_slice().len()
304 }
305
306 fn is_random_access(&self, decode_index: usize) -> bool {
307 self[decode_index].random_access
308 }
309
310 fn presentation_index(&self, decode_index: usize) -> FrameIndex {
311 self[decode_index].presentation_index
312 }
313
314 fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>> {
315 Ok(Cow::Borrowed(&self[decode_index].data))
316 }
317}
318
319#[derive(Clone, Debug, Eq, PartialEq)]
321pub struct DecodedVideoFrame {
322 pub presentation_index: FrameIndex,
323 pub frame: VideoFrame,
324}
325
326#[derive(Clone, Debug, Default)]
328pub struct CancellationToken {
329 canceled: Arc<AtomicBool>,
330}
331
332impl CancellationToken {
333 pub fn new() -> Self {
334 Self::default()
335 }
336
337 pub fn cancel(&self) {
338 self.canceled.store(true, Ordering::Release);
339 }
340
341 pub fn is_canceled(&self) -> bool {
342 self.canceled.load(Ordering::Acquire)
343 }
344
345 #[doc(hidden)]
346 pub fn check(&self) -> Result<()> {
347 if self.is_canceled() {
348 Err(Error::new(ErrorKind::Canceled, "codec operation canceled"))
349 } else {
350 Ok(())
351 }
352 }
353}
354
355pub trait VideoDecoder: Send {
360 fn submit(
361 &mut self,
362 sample: &EncodedVideoSample,
363 cancellation: &CancellationToken,
364 ) -> Result<Vec<DecodedVideoFrame>>;
365 fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>>;
366 fn reset(&mut self) -> Result<()>;
367
368 fn set_output_wanted(&mut self, _wanted: bool) {}
389}
390
391pub trait VideoDecoderFactory {
393 fn capability(&self, configuration: &VideoDecoderConfig) -> CodecSupport;
394 fn create(
395 &self,
396 configuration: &VideoDecoderConfig,
397 limits: &Limits,
398 ) -> Result<Box<dyn VideoDecoder>>;
399}
400
401pub trait VideoEncoderFactory {
403 fn capability(&self, configuration: &VideoEncoderConfig) -> CodecSupport;
404 fn create(
405 &self,
406 configuration: &VideoEncoderConfig,
407 limits: &Limits,
408 ) -> Result<Box<dyn VideoEncoder>>;
409}
410
411#[derive(Clone, Debug, Eq, PartialEq)]
413pub struct AudioEncoderConfig {
414 pub codec: Codec,
415 pub profile: CodecProfile,
416 pub sample_rate: u32,
417 pub channels: u16,
418 pub timescale: u32,
420 pub configuration: Vec<u8>,
421}
422
423pub trait AudioEncoderFactory {
432 fn capability(&self, configuration: &AudioEncoderConfig) -> CodecSupport;
433 fn create(
434 &self,
435 configuration: &AudioEncoderConfig,
436 limits: &Limits,
437 ) -> Result<Box<dyn AudioEncoder>>;
438}
439
440#[doc(hidden)]
446pub fn parse_audio_bit_rate(configuration: &[u8]) -> Option<Option<u32>> {
447 match configuration {
448 [] => Some(None),
449 [a, b, c, d] => match u32::from_be_bytes([*a, *b, *c, *d]) {
450 0 => None,
451 bits_per_second => Some(Some(bits_per_second)),
452 },
453 _ => None,
454 }
455}
456
457#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
459pub struct DecodeStatistics {
460 pub samples_submitted: u64,
461 pub samples_skipped: u64,
464 pub cache_hits: u64,
465 pub resets: u64,
466 pub drains: u64,
467}
468
469pub struct ExactFrameReader {
471 configuration: VideoDecoderConfig,
472 decoder: Box<dyn VideoDecoder>,
473 samples: Box<dyn SampleProvider>,
474 decode_position_by_presentation: HashMap<FrameIndex, usize>,
475 cache: BTreeMap<FrameIndex, VideoFrame>,
476 lru: VecDeque<FrameIndex>,
477 published_since_reset: HashSet<FrameIndex>,
485 suppressed_since_reset: HashSet<FrameIndex>,
489 in_flight_since_reset: HashSet<FrameIndex>,
494 output_wanted: bool,
497 next_decode_position: Option<usize>,
498 session_start: Option<usize>,
501 seek_previews: Option<Arc<dyn SeekPreviewSource>>,
503 limits: Limits,
504 statistics: DecodeStatistics,
505}
506
507pub const SEEK_LATENCY_BUDGET: Duration = Duration::from_millis(50);
512
513pub trait SeekPreviewSource: Send + Sync {
525 fn nearest_at(&self, frame: FrameIndex) -> Option<(FrameIndex, VideoFrame)>;
528}
529
530#[derive(Clone, Debug, Eq, PartialEq)]
539pub enum Seek {
540 Exact(VideoFrame),
542 Preview {
544 picture: VideoFrame,
545 frame: FrameIndex,
548 },
549 Pending,
552}
553
554#[derive(Clone, Copy, Debug, Eq, PartialEq)]
561enum Request {
562 Destination,
565 Step,
568}
569
570impl Request {
571 fn cache_tail(self, limits: &Limits) -> u64 {
573 match self {
574 Self::Destination => u64::from(limits.max_cached_frames),
575 Self::Step => 0,
576 }
577 }
578}
579
580impl ExactFrameReader {
581 pub fn new(
582 factory: &dyn VideoDecoderFactory,
583 configuration: VideoDecoderConfig,
584 samples: Vec<EncodedVideoSample>,
585 limits: Limits,
586 ) -> Result<Self> {
587 Self::from_provider(factory, configuration, Box::new(samples), limits)
588 }
589
590 pub fn from_provider(
597 factory: &dyn VideoDecoderFactory,
598 configuration: VideoDecoderConfig,
599 samples: Box<dyn SampleProvider>,
600 limits: Limits,
601 ) -> Result<Self> {
602 if limits.max_cached_frames == 0 || limits.max_decode_samples_per_seek == 0 {
603 return Err(Error::new(
604 ErrorKind::ResourceLimit,
605 "exact-frame limits must permit cached frames and decode work",
606 ));
607 }
608 let capability = factory.capability(&configuration);
609 if !capability.is_supported() {
610 return Err(capability_error(capability));
611 }
612 if samples.is_empty() {
613 return Err(Error::new(
614 ErrorKind::InvalidInput,
615 "an exact-frame reader requires at least one sample",
616 ));
617 }
618 if !samples.is_random_access(0) {
619 return Err(Error::new(
620 ErrorKind::InvalidInput,
621 "the first decode-order sample must be a random-access point",
622 ));
623 }
624 let mut positions = HashMap::with_capacity(samples.len());
625 for position in 0..samples.len() {
626 if positions
627 .insert(samples.presentation_index(position), position)
628 .is_some()
629 {
630 return Err(Error::new(
631 ErrorKind::InvalidInput,
632 "presentation frame identities must be unique",
633 ));
634 }
635 }
636 let decoder = factory.create(&configuration, &limits)?;
637 Ok(Self {
638 configuration,
639 decoder,
640 samples,
641 decode_position_by_presentation: positions,
642 cache: BTreeMap::new(),
643 lru: VecDeque::new(),
644 published_since_reset: HashSet::new(),
645 suppressed_since_reset: HashSet::new(),
646 in_flight_since_reset: HashSet::new(),
647 output_wanted: true,
648 next_decode_position: None,
649 session_start: None,
650 seek_previews: None,
651 limits,
652 statistics: DecodeStatistics::default(),
653 })
654 }
655
656 fn sample_at(&self, position: usize) -> Result<EncodedVideoSample> {
660 Ok(EncodedVideoSample {
661 presentation_index: self.samples.presentation_index(position),
662 random_access: self.samples.is_random_access(position),
663 data: self.samples.read(position)?.into_owned(),
664 })
665 }
666
667 pub fn set_seek_previews(&mut self, previews: Option<Arc<dyn SeekPreviewSource>>) {
673 self.seek_previews = previews;
674 }
675
676 pub fn seek(&mut self, presentation_index: FrameIndex) -> Seek {
689 if let Some(frame) = self.cache.get(&presentation_index).cloned() {
690 self.statistics.cache_hits = self.statistics.cache_hits.saturating_add(1);
691 self.touch(presentation_index);
692 return Seek::Exact(frame);
693 }
694 match self
695 .seek_previews
696 .as_ref()
697 .and_then(|previews| previews.nearest_at(presentation_index))
698 {
699 Some((frame, picture)) => Seek::Preview { picture, frame },
700 None => Seek::Pending,
701 }
702 }
703
704 pub fn get(
713 &mut self,
714 presentation_index: FrameIndex,
715 cancellation: &CancellationToken,
716 ) -> Result<VideoFrame> {
717 self.get_request(presentation_index, Request::Destination, cancellation)
718 }
719
720 pub fn get_step(
735 &mut self,
736 presentation_index: FrameIndex,
737 cancellation: &CancellationToken,
738 ) -> Result<VideoFrame> {
739 self.get_request(presentation_index, Request::Step, cancellation)
740 }
741
742 fn get_request(
743 &mut self,
744 presentation_index: FrameIndex,
745 request: Request,
746 cancellation: &CancellationToken,
747 ) -> Result<VideoFrame> {
748 cancellation.check()?;
749 if let Some(frame) = self.cache.get(&presentation_index).cloned() {
750 self.statistics.cache_hits = self.statistics.cache_hits.saturating_add(1);
751 self.touch(presentation_index);
752 return Ok(frame);
753 }
754 let target_position = *self
755 .decode_position_by_presentation
756 .get(&presentation_index)
757 .ok_or_else(|| {
758 Error::new(ErrorKind::InvalidInput, "presentation frame is not indexed")
759 })?;
760 let random_access_position = self.nearest_random_access(target_position);
761 if !self.session_reaches(presentation_index, random_access_position) {
781 self.decoder.reset()?;
782 self.statistics.resets = self.statistics.resets.saturating_add(1);
783 self.published_since_reset.clear();
784 self.suppressed_since_reset.clear();
785 self.in_flight_since_reset.clear();
786 self.next_decode_position = Some(random_access_position);
787 self.session_start = Some(random_access_position);
788 }
789
790 let mut work = 0_u32;
791 while let Some(position) = self.next_decode_position {
792 cancellation.check()?;
793 if work >= self.limits.max_decode_samples_per_seek {
794 return Err(Error::new(
795 ErrorKind::ResourceLimit,
796 "exact-frame request exceeded the configured decode-work limit",
797 ));
798 }
799 if position == self.samples.len() {
800 self.set_output_wanted(true);
801 self.drain_internal(cancellation)?;
802 break;
803 }
804 let sample = self.sample_at(position)?;
808 let cache_tail = request.cache_tail(&self.limits);
831 let wanted = position >= target_position
832 || sample.presentation_index.0 >= presentation_index.0.saturating_sub(cache_tail);
833 self.set_output_wanted(wanted);
834 let suppressed = !self.output_wanted;
835 let outputs = self.decoder.submit(&sample, cancellation)?;
836 self.statistics.samples_submitted = self.statistics.samples_submitted.saturating_add(1);
837 if suppressed {
838 self.statistics.samples_skipped = self.statistics.samples_skipped.saturating_add(1);
839 self.suppressed_since_reset
840 .insert(sample.presentation_index);
841 } else {
842 self.in_flight_since_reset.insert(sample.presentation_index);
843 }
844 self.next_decode_position = Some(position + 1);
845 work += 1;
846 self.publish(outputs)?;
847 if let Some(frame) = self.cache.get(&presentation_index).cloned() {
848 self.touch(presentation_index);
849 return Ok(frame);
850 }
851 }
852 if let Some(frame) = self.cache.get(&presentation_index).cloned() {
853 self.touch(presentation_index);
854 Ok(frame)
855 } else {
856 Err(Error::new(
857 ErrorKind::MalformedMedia,
858 "decoder did not produce the requested presentation frame",
859 ))
860 }
861 }
862
863 pub fn decode_positions_for(
874 &self,
875 presentation_index: FrameIndex,
876 ) -> Result<std::ops::Range<usize>> {
877 if self.cache.contains_key(&presentation_index) {
878 return Ok(0..0);
879 }
880 let target_position = *self
881 .decode_position_by_presentation
882 .get(&presentation_index)
883 .ok_or_else(|| {
884 Error::new(ErrorKind::InvalidInput, "presentation frame is not indexed")
885 })?;
886 let random_access_position = self.nearest_random_access(target_position);
887 let start = match self.next_decode_position {
888 Some(next) if self.session_reaches(presentation_index, random_access_position) => next,
889 _ => random_access_position,
890 };
891 let len = self.samples.len();
892 let scan_end = target_position
893 .saturating_add(1)
894 .saturating_add(self.limits.max_decode_samples_per_seek as usize)
895 .min(len);
896 let mut end = target_position + 1;
897 for position in target_position + 1..scan_end {
898 let presented = self.samples.presentation_index(position);
899 if presented <= presentation_index {
900 end = position + 1;
901 } else if self.samples.is_random_access(position) {
902 break;
903 }
904 }
905 Ok(start..end.max((start + 1).min(len)))
906 }
907
908 fn session_reaches(
916 &self,
917 presentation_index: FrameIndex,
918 random_access_position: usize,
919 ) -> bool {
920 self.next_decode_position
921 .is_some_and(|position| position >= random_access_position)
922 && self
923 .session_start
924 .is_some_and(|start| start <= random_access_position)
925 && !self.published_since_reset.contains(&presentation_index)
926 && !self.suppressed_since_reset.contains(&presentation_index)
927 }
928
929 pub fn drain(&mut self, cancellation: &CancellationToken) -> Result<usize> {
931 cancellation.check()?;
932 self.set_output_wanted(true);
933 self.drain_internal(cancellation)
934 }
935
936 fn set_output_wanted(&mut self, wanted: bool) {
948 if self.output_wanted == wanted {
949 return;
950 }
951 if !wanted {
952 for frame in self.in_flight_since_reset.drain() {
953 self.suppressed_since_reset.insert(frame);
954 }
955 }
956 self.decoder.set_output_wanted(wanted);
957 self.output_wanted = wanted;
958 }
959
960 pub fn reset(&mut self) -> Result<()> {
962 self.set_output_wanted(true);
963 self.decoder.reset()?;
964 self.statistics.resets = self.statistics.resets.saturating_add(1);
965 self.next_decode_position = None;
966 self.session_start = None;
967 self.cache.clear();
968 self.lru.clear();
969 self.published_since_reset.clear();
970 self.suppressed_since_reset.clear();
971 self.in_flight_since_reset.clear();
972 Ok(())
973 }
974
975 pub const fn statistics(&self) -> DecodeStatistics {
976 self.statistics
977 }
978
979 pub fn cached_frames(&self) -> usize {
980 self.cache.len()
981 }
982
983 fn nearest_random_access(&self, target_position: usize) -> usize {
991 let target = self.samples.presentation_index(target_position);
992 (0..=target_position)
993 .rev()
994 .find(|&position| {
995 self.samples.is_random_access(position)
996 && self.samples.presentation_index(position) <= target
997 })
998 .unwrap_or(0)
999 }
1000
1001 fn drain_internal(&mut self, cancellation: &CancellationToken) -> Result<usize> {
1002 let outputs = self.decoder.drain(cancellation)?;
1003 let count = outputs.len();
1004 self.statistics.drains = self.statistics.drains.saturating_add(1);
1005 self.next_decode_position = Some(self.samples.len());
1006 self.publish(outputs)?;
1007 Ok(count)
1008 }
1009
1010 fn publish(&mut self, outputs: Vec<DecodedVideoFrame>) -> Result<()> {
1011 for output in outputs {
1012 self.suppressed_since_reset
1016 .remove(&output.presentation_index);
1017 self.in_flight_since_reset
1018 .remove(&output.presentation_index);
1019 self.published_since_reset.insert(output.presentation_index);
1029 if !self
1030 .decode_position_by_presentation
1031 .contains_key(&output.presentation_index)
1032 {
1033 return Err(Error::new(
1034 ErrorKind::MalformedMedia,
1035 "decoder produced an unindexed presentation frame",
1036 ));
1037 }
1038 if output.frame.dimensions != self.configuration.coded_dimensions
1039 || output.frame.pixel_format != self.configuration.output_format
1040 || output.frame.color_range != self.configuration.color_range
1041 {
1042 return Err(Error::new(
1043 ErrorKind::MalformedMedia,
1044 "decoder output does not match its normalized configuration",
1045 ));
1046 }
1047 self.insert_cache(output.presentation_index, output.frame);
1048 }
1049 Ok(())
1050 }
1051
1052 fn insert_cache(&mut self, index: FrameIndex, frame: VideoFrame) {
1053 self.cache.insert(index, frame);
1054 self.touch(index);
1055 while self.cache.len() > self.limits.max_cached_frames as usize {
1056 if let Some(evicted) = self.lru.pop_front() {
1057 self.cache.remove(&evicted);
1058 }
1059 }
1060 }
1061
1062 fn touch(&mut self, index: FrameIndex) {
1063 self.lru.retain(|candidate| *candidate != index);
1064 self.lru.push_back(index);
1065 }
1066}
1067
1068fn capability_error(capability: CodecSupport) -> Error {
1069 let (kind, message) = match capability {
1070 CodecSupport::UnsupportedCodec => (
1071 ErrorKind::Unsupported,
1072 "decoder does not support the requested codec".into(),
1073 ),
1074 CodecSupport::UnsupportedProfile => (
1075 ErrorKind::Unsupported,
1076 "decoder does not support the requested profile".into(),
1077 ),
1078 CodecSupport::InvalidConfiguration { reason } => (ErrorKind::InvalidInput, reason),
1079 CodecSupport::HardwareUnavailable => (
1080 ErrorKind::Unsupported,
1081 "requested hardware decoder is unavailable".into(),
1082 ),
1083 CodecSupport::Supported { .. } => (
1084 ErrorKind::Internal,
1085 "decoder capability changed unexpectedly".into(),
1086 ),
1087 };
1088 Error::new(kind, message)
1089}
1090
1091pub fn uncompressed_video_decoder_factory() -> impl VideoDecoderFactory {
1096 UncompressedVideoDecoderFactory
1097}
1098
1099struct UncompressedVideoDecoderFactory;
1100
1101impl VideoDecoderFactory for UncompressedVideoDecoderFactory {
1102 fn capability(&self, configuration: &VideoDecoderConfig) -> CodecSupport {
1103 if configuration.codec != Codec::UncompressedVideo {
1104 return CodecSupport::UnsupportedCodec;
1105 }
1106 if configuration.profile != CodecProfile::UncompressedGray8 {
1107 return CodecSupport::UnsupportedProfile;
1108 }
1109 if configuration.output_format != PixelFormat::Gray8
1110 || !configuration.configuration.is_empty()
1111 {
1112 return CodecSupport::InvalidConfiguration {
1113 reason: "uncompressed Gray8 requires Gray8 output and no configuration bytes"
1114 .into(),
1115 };
1116 }
1117 if configuration.hardware == HardwarePreference::Require {
1118 return CodecSupport::HardwareUnavailable;
1119 }
1120 CodecSupport::Supported {
1121 implementation: CodecImplementation::Software,
1122 }
1123 }
1124
1125 fn create(
1126 &self,
1127 configuration: &VideoDecoderConfig,
1128 limits: &Limits,
1129 ) -> Result<Box<dyn VideoDecoder>> {
1130 let capability = self.capability(configuration);
1131 if !capability.is_supported() {
1132 return Err(capability_error(capability));
1133 }
1134 if configuration.coded_dimensions.width > limits.max_width
1135 || configuration.coded_dimensions.height > limits.max_height
1136 {
1137 return Err(Error::new(
1138 ErrorKind::ResourceLimit,
1139 "decoded dimensions exceed the configured limits",
1140 ));
1141 }
1142 let required = u64::from(configuration.coded_dimensions.width)
1143 .checked_mul(u64::from(configuration.coded_dimensions.height))
1144 .ok_or_else(|| Error::new(ErrorKind::ResourceLimit, "decoded frame size overflow"))?;
1145 if required > limits.max_allocation_bytes {
1146 return Err(Error::new(
1147 ErrorKind::ResourceLimit,
1148 "decoded frame exceeds the configured allocation limit",
1149 ));
1150 }
1151 Ok(Box::new(UncompressedVideoDecoder {
1152 configuration: configuration.clone(),
1153 limits: *limits,
1154 }))
1155 }
1156}
1157
1158struct UncompressedVideoDecoder {
1159 configuration: VideoDecoderConfig,
1160 limits: Limits,
1161}
1162
1163impl VideoDecoder for UncompressedVideoDecoder {
1164 fn submit(
1165 &mut self,
1166 sample: &EncodedVideoSample,
1167 cancellation: &CancellationToken,
1168 ) -> Result<Vec<DecodedVideoFrame>> {
1169 cancellation.check()?;
1170 let width = usize::try_from(self.configuration.coded_dimensions.width)
1171 .map_err(|_| Error::new(ErrorKind::ResourceLimit, "decoded width is too large"))?;
1172 let height = usize::try_from(self.configuration.coded_dimensions.height)
1173 .map_err(|_| Error::new(ErrorKind::ResourceLimit, "decoded height is too large"))?;
1174 let length = width
1175 .checked_mul(height)
1176 .ok_or_else(|| Error::new(ErrorKind::ResourceLimit, "decoded frame size overflow"))?;
1177 if sample.data.len() != length {
1178 return Err(Error::new(
1179 ErrorKind::MalformedMedia,
1180 "uncompressed Gray8 packet size does not match coded dimensions",
1181 ));
1182 }
1183 let frame = VideoFrame::new(
1184 self.configuration.coded_dimensions,
1185 PixelFormat::Gray8,
1186 self.configuration.color_range,
1187 vec![Plane {
1188 data: sample.data.clone(),
1189 stride: width,
1190 }],
1191 &self.limits,
1192 )?;
1193 Ok(vec![DecodedVideoFrame {
1194 presentation_index: sample.presentation_index,
1195 frame,
1196 }])
1197 }
1198
1199 fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
1200 cancellation.check()?;
1201 Ok(Vec::new())
1202 }
1203
1204 fn reset(&mut self) -> Result<()> {
1205 Ok(())
1206 }
1207}
1208
1209#[cfg(test)]
1210mod tests {
1211 use super::*;
1212 use std::sync::Mutex;
1213
1214 fn config() -> VideoDecoderConfig {
1215 VideoDecoderConfig {
1216 codec: Codec::UncompressedVideo,
1217 profile: CodecProfile::UncompressedGray8,
1218 coded_dimensions: VideoDimensions::new(1, 1, &Limits::default()).unwrap(),
1219 output_format: PixelFormat::Gray8,
1220 color_range: ColorRange::Full,
1221 hardware: HardwarePreference::Avoid,
1222 configuration: Vec::new(),
1223 }
1224 }
1225
1226 fn sample(index: u64, value: u8, random_access: bool) -> EncodedVideoSample {
1227 EncodedVideoSample {
1228 presentation_index: FrameIndex(index),
1229 random_access,
1230 data: vec![value],
1231 }
1232 }
1233
1234 fn value(frame: &VideoFrame) -> u8 {
1235 frame.planes[0].data[0]
1236 }
1237
1238 struct LoadOnDemand {
1241 samples: Vec<EncodedVideoSample>,
1242 loaded: Arc<Mutex<HashSet<usize>>>,
1243 }
1244
1245 impl SampleProvider for LoadOnDemand {
1246 fn len(&self) -> usize {
1247 self.samples.len()
1248 }
1249
1250 fn is_random_access(&self, decode_index: usize) -> bool {
1251 self.samples[decode_index].random_access
1252 }
1253
1254 fn presentation_index(&self, decode_index: usize) -> FrameIndex {
1255 self.samples[decode_index].presentation_index
1256 }
1257
1258 fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>> {
1259 if self.loaded.lock().unwrap().contains(&decode_index) {
1260 Ok(Cow::Borrowed(&self.samples[decode_index].data))
1261 } else {
1262 Err(Error::new(ErrorKind::WouldBlock, "not loaded yet"))
1263 }
1264 }
1265 }
1266
1267 #[test]
1271 fn a_request_waiting_on_an_unloaded_sample_resumes_where_it_stopped() {
1272 let loaded = Arc::new(Mutex::new(HashSet::new()));
1273 let samples = (0..12)
1274 .map(|index| sample(index, index as u8, index % 4 == 0))
1275 .collect();
1276 let mut reader = ExactFrameReader::from_provider(
1277 &uncompressed_video_decoder_factory(),
1278 config(),
1279 Box::new(LoadOnDemand {
1280 samples,
1281 loaded: loaded.clone(),
1282 }),
1283 Limits::default(),
1284 )
1285 .unwrap();
1286 let cancellation = CancellationToken::new();
1287
1288 assert_eq!(reader.decode_positions_for(FrameIndex(6)).unwrap(), 4..7);
1289 let error = reader.get(FrameIndex(6), &cancellation).unwrap_err();
1290 assert_eq!(error.kind(), ErrorKind::WouldBlock);
1291 assert_eq!(reader.statistics().samples_submitted, 0);
1292
1293 loaded.lock().unwrap().extend([4, 5]);
1294 let error = reader.get(FrameIndex(6), &cancellation).unwrap_err();
1295 assert_eq!(error.kind(), ErrorKind::WouldBlock);
1296 assert_eq!(reader.statistics().samples_submitted, 2);
1297 assert_eq!(reader.decode_positions_for(FrameIndex(6)).unwrap(), 6..7);
1299
1300 loaded.lock().unwrap().insert(6);
1301 assert_eq!(value(&reader.get(FrameIndex(6), &cancellation).unwrap()), 6);
1302 assert_eq!(reader.statistics().samples_submitted, 3);
1303 assert_eq!(reader.statistics().resets, 1);
1304
1305 assert!(
1308 reader
1309 .decode_positions_for(FrameIndex(6))
1310 .unwrap()
1311 .is_empty()
1312 );
1313 assert_eq!(reader.decode_positions_for(FrameIndex(7)).unwrap(), 7..8);
1314 assert_eq!(reader.decode_positions_for(FrameIndex(10)).unwrap(), 8..11);
1315 assert_eq!(reader.decode_positions_for(FrameIndex(1)).unwrap(), 0..2);
1316 }
1317
1318 #[test]
1321 fn decode_positions_for_a_reordered_frame_reach_the_samples_presented_before_it() {
1322 let samples = vec![
1324 sample(0, 0, true),
1325 sample(3, 3, false),
1326 sample(1, 1, false),
1327 sample(2, 2, false),
1328 sample(4, 4, true),
1329 ];
1330 let reader = ExactFrameReader::new(
1331 &uncompressed_video_decoder_factory(),
1332 config(),
1333 samples,
1334 Limits::default(),
1335 )
1336 .unwrap();
1337 assert_eq!(reader.decode_positions_for(FrameIndex(1)).unwrap(), 0..3);
1338 assert_eq!(reader.decode_positions_for(FrameIndex(2)).unwrap(), 0..4);
1339 assert_eq!(reader.decode_positions_for(FrameIndex(3)).unwrap(), 0..4);
1340 assert_eq!(reader.decode_positions_for(FrameIndex(4)).unwrap(), 4..5);
1341 }
1342
1343 fn single_group_reader(frames: u64) -> ExactFrameReader {
1347 let samples = (0..frames)
1348 .map(|index| sample(index, (index % 251) as u8, index == 0))
1349 .collect();
1350 ExactFrameReader::new(
1351 &uncompressed_video_decoder_factory(),
1352 config(),
1353 samples,
1354 Limits::default(),
1355 )
1356 .unwrap()
1357 }
1358
1359 struct StridedPreviews {
1363 stride: u64,
1364 frames: u64,
1365 }
1366
1367 impl SeekPreviewSource for StridedPreviews {
1368 fn nearest_at(&self, frame: FrameIndex) -> Option<(FrameIndex, VideoFrame)> {
1369 if self.frames == 0 {
1370 return None;
1371 }
1372 let at = (frame.0 / self.stride * self.stride).min(self.frames - 1);
1373 let picture = VideoFrame::new(
1374 config().coded_dimensions,
1375 PixelFormat::Gray8,
1376 ColorRange::Full,
1377 vec![Plane {
1378 data: vec![(at % 251) as u8],
1379 stride: 1,
1380 }],
1381 &Limits::default(),
1382 )
1383 .ok()?;
1384 Some((FrameIndex(at), picture))
1385 }
1386 }
1387
1388 #[test]
1392 fn a_seek_with_nothing_decoded_is_pending_and_submits_no_samples() {
1393 let mut reader = single_group_reader(512);
1394 assert_eq!(reader.seek(FrameIndex(511)), Seek::Pending);
1395 assert_eq!(reader.statistics().samples_submitted, 0);
1396 assert_eq!(reader.statistics().resets, 0);
1397 }
1398
1399 #[test]
1401 fn a_seek_into_the_cache_answers_exactly() {
1402 let mut reader = single_group_reader(64);
1403 let cancellation = CancellationToken::new();
1404 reader.get(FrameIndex(40), &cancellation).unwrap();
1405 let submitted = reader.statistics().samples_submitted;
1406 let Seek::Exact(frame) = reader.seek(FrameIndex(40)) else {
1407 panic!("a cached frame seeks exactly");
1408 };
1409 assert_eq!(value(&frame), 40);
1410 assert_eq!(
1411 reader.statistics().samples_submitted,
1412 submitted,
1413 "an exact seek decodes nothing"
1414 );
1415 }
1416
1417 #[test]
1421 fn a_seek_anywhere_on_a_single_group_track_decodes_nothing() {
1422 let mut reader = single_group_reader(512);
1423 reader.set_seek_previews(Some(Arc::new(StridedPreviews {
1424 stride: 12,
1425 frames: 512,
1426 })));
1427 for target in [0_u64, 1, 255, 400, 511] {
1428 match reader.seek(FrameIndex(target)) {
1429 Seek::Preview { frame, .. } => assert!(
1430 frame.0.abs_diff(target) < 12,
1431 "frame {target} answered by {frame:?}, further than one stride away"
1432 ),
1433 Seek::Exact(_) => {}
1434 Seek::Pending => panic!("frame {target} had no answer"),
1435 }
1436 }
1437 assert_eq!(
1438 reader.statistics().samples_submitted,
1439 0,
1440 "seeking is not decoding"
1441 );
1442 assert_eq!(reader.statistics().resets, 0);
1443 }
1444
1445 #[test]
1449 fn a_seek_to_any_position_answers_inside_the_latency_budget() {
1450 let frames = 768;
1451 let mut reader = single_group_reader(frames);
1452 reader.set_seek_previews(Some(Arc::new(StridedPreviews { stride: 12, frames })));
1453 let mut worst = Duration::ZERO;
1454 for step in 0..=100_u64 {
1455 let target = FrameIndex(step * (frames - 1) / 100);
1456 let started = std::time::Instant::now();
1457 let answer = reader.seek(target);
1458 worst = worst.max(started.elapsed());
1459 assert_ne!(answer, Seek::Pending, "frame {} had no answer", target.0);
1460 }
1461 assert!(
1462 worst < SEEK_LATENCY_BUDGET,
1463 "the worst seek took {worst:?}, over the {SEEK_LATENCY_BUDGET:?} budget"
1464 );
1465 }
1466
1467 #[test]
1470 fn detaching_the_preview_source_leaves_only_the_cache() {
1471 let mut reader = single_group_reader(64);
1472 reader.set_seek_previews(Some(Arc::new(StridedPreviews {
1473 stride: 12,
1474 frames: 64,
1475 })));
1476 assert!(matches!(reader.seek(FrameIndex(63)), Seek::Preview { .. }));
1477 reader.set_seek_previews(None);
1478 assert_eq!(reader.seek(FrameIndex(63)), Seek::Pending);
1479 }
1480
1481 #[test]
1486 fn a_leading_picture_is_decoded_from_the_random_access_point_before_it() {
1487 let samples = vec![
1488 sample(0, 10, true),
1489 sample(1, 11, false),
1490 sample(2, 12, false),
1491 sample(4, 14, true),
1492 sample(3, 13, false),
1493 sample(5, 15, false),
1494 ];
1495 let mut reader = ExactFrameReader::new(
1496 &uncompressed_video_decoder_factory(),
1497 config(),
1498 samples.clone(),
1499 Limits::default(),
1500 )
1501 .unwrap();
1502 let cancellation = CancellationToken::new();
1503 assert_eq!(
1504 value(&reader.get(FrameIndex(3), &cancellation).unwrap()),
1505 13
1506 );
1507 assert_eq!(reader.statistics().samples_submitted, 5);
1508
1509 let mut reader = ExactFrameReader::new(
1510 &uncompressed_video_decoder_factory(),
1511 config(),
1512 samples,
1513 Limits::default(),
1514 )
1515 .unwrap();
1516 assert_eq!(
1517 value(&reader.get(FrameIndex(5), &cancellation).unwrap()),
1518 15
1519 );
1520 assert_eq!(reader.statistics().samples_submitted, 3);
1521 }
1522
1523 #[test]
1524 fn capability_distinguishes_codec_profile_configuration_and_hardware() {
1525 let factory = uncompressed_video_decoder_factory();
1526 assert!(factory.capability(&config()).is_supported());
1527 let mut candidate = config();
1528 candidate.codec = Codec::Av1;
1529 assert_eq!(
1530 factory.capability(&candidate),
1531 CodecSupport::UnsupportedCodec
1532 );
1533 candidate = config();
1534 candidate.profile = CodecProfile::Av1Main;
1535 assert_eq!(
1536 factory.capability(&candidate),
1537 CodecSupport::UnsupportedProfile
1538 );
1539 candidate = config();
1540 candidate.output_format = PixelFormat::Rgba8;
1541 assert!(matches!(
1542 factory.capability(&candidate),
1543 CodecSupport::InvalidConfiguration { .. }
1544 ));
1545 candidate = config();
1546 candidate.hardware = HardwarePreference::Require;
1547 assert_eq!(
1548 factory.capability(&candidate),
1549 CodecSupport::HardwareUnavailable
1550 );
1551
1552 candidate = config();
1553 candidate.output_format = PixelFormat::Rgba8;
1554 assert_eq!(
1555 factory
1556 .create(&candidate, &Limits::default())
1557 .err()
1558 .unwrap()
1559 .kind(),
1560 ErrorKind::InvalidInput
1561 );
1562
1563 let restrictive = Limits {
1564 max_width: 0,
1565 ..Limits::default()
1566 };
1567 assert_eq!(
1568 factory
1569 .create(&config(), &restrictive)
1570 .err()
1571 .unwrap()
1572 .kind(),
1573 ErrorKind::ResourceLimit
1574 );
1575 }
1576
1577 #[test]
1581 fn a_request_before_the_open_session_start_resets_the_decoder() {
1582 let samples = (0..4)
1583 .map(|index| sample(index, index as u8 + 10, true))
1584 .collect();
1585 let mut reader = ExactFrameReader::new(
1586 &uncompressed_video_decoder_factory(),
1587 config(),
1588 samples,
1589 Limits {
1590 max_cached_frames: 1,
1591 ..Limits::default()
1592 },
1593 )
1594 .unwrap();
1595 let cancellation = CancellationToken::new();
1596 assert_eq!(
1597 value(&reader.get(FrameIndex(2), &cancellation).unwrap()),
1598 12
1599 );
1600 assert_eq!(
1601 value(&reader.get(FrameIndex(0), &cancellation).unwrap()),
1602 10
1603 );
1604 assert_eq!(reader.statistics().resets, 2);
1605 }
1606
1607 #[test]
1608 fn conformance_vector_reorders_exact_frames_and_reuses_bounded_state() {
1609 let samples = vec![
1610 sample(0, 10, true),
1611 sample(3, 40, false),
1612 sample(1, 20, false),
1613 sample(2, 30, false),
1614 sample(4, 50, true),
1615 sample(6, 70, false),
1616 sample(5, 60, false),
1617 ];
1618 let factory = uncompressed_video_decoder_factory();
1619 let mut reader = ExactFrameReader::new(
1620 &factory,
1621 config(),
1622 samples,
1623 Limits {
1624 max_cached_frames: 3,
1625 ..Limits::default()
1626 },
1627 )
1628 .unwrap();
1629 let cancellation = CancellationToken::new();
1630 assert_eq!(
1631 value(&reader.get(FrameIndex(1), &cancellation).unwrap()),
1632 20
1633 );
1634 let first = reader.statistics();
1635 assert_eq!(
1636 value(&reader.get(FrameIndex(2), &cancellation).unwrap()),
1637 30
1638 );
1639 assert_eq!(reader.statistics().resets, first.resets);
1640 assert_eq!(
1641 value(&reader.get(FrameIndex(3), &cancellation).unwrap()),
1642 40
1643 );
1644 assert!(reader.statistics().cache_hits > 0);
1645 assert_eq!(
1646 value(&reader.get(FrameIndex(5), &cancellation).unwrap()),
1647 60
1648 );
1649 assert_eq!(
1650 value(&reader.get(FrameIndex(0), &cancellation).unwrap()),
1651 10
1652 );
1653 assert!(reader.statistics().resets > first.resets);
1654 assert!(reader.cached_frames() <= 3);
1655 }
1656
1657 struct HintFactory {
1660 wanted: Arc<Mutex<Vec<(u64, bool)>>>,
1661 }
1662
1663 struct HintDecoder {
1664 configuration: VideoDecoderConfig,
1665 limits: Limits,
1666 wanted: Arc<Mutex<Vec<(u64, bool)>>>,
1667 output_wanted: bool,
1668 }
1669
1670 impl VideoDecoderFactory for HintFactory {
1671 fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
1672 CodecSupport::Supported {
1673 implementation: CodecImplementation::Software,
1674 }
1675 }
1676
1677 fn create(
1678 &self,
1679 configuration: &VideoDecoderConfig,
1680 limits: &Limits,
1681 ) -> Result<Box<dyn VideoDecoder>> {
1682 Ok(Box::new(HintDecoder {
1683 configuration: configuration.clone(),
1684 limits: *limits,
1685 wanted: Arc::clone(&self.wanted),
1686 output_wanted: true,
1687 }))
1688 }
1689 }
1690
1691 impl VideoDecoder for HintDecoder {
1692 fn submit(
1693 &mut self,
1694 sample: &EncodedVideoSample,
1695 cancellation: &CancellationToken,
1696 ) -> Result<Vec<DecodedVideoFrame>> {
1697 cancellation.check()?;
1698 self.wanted
1699 .lock()
1700 .expect("hint log poisoned")
1701 .push((sample.presentation_index.0, self.output_wanted));
1702 if !self.output_wanted {
1703 return Ok(Vec::new());
1704 }
1705 Ok(vec![DecodedVideoFrame {
1706 presentation_index: sample.presentation_index,
1707 frame: VideoFrame::new(
1708 self.configuration.coded_dimensions,
1709 PixelFormat::Gray8,
1710 ColorRange::Full,
1711 vec![Plane {
1712 data: sample.data.clone(),
1713 stride: 1,
1714 }],
1715 &self.limits,
1716 )?,
1717 }])
1718 }
1719
1720 fn drain(&mut self, _: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
1721 Ok(Vec::new())
1722 }
1723
1724 fn reset(&mut self) -> Result<()> {
1725 Ok(())
1726 }
1727
1728 fn set_output_wanted(&mut self, wanted: bool) {
1729 self.output_wanted = wanted;
1730 }
1731 }
1732
1733 struct ReplayFactory;
1738
1739 struct ReplayDecoder {
1740 configuration: VideoDecoderConfig,
1741 limits: Limits,
1742 previous: Option<(FrameIndex, u8)>,
1743 }
1744
1745 impl ReplayDecoder {
1746 fn produce(&self, presentation_index: FrameIndex, value: u8) -> Result<DecodedVideoFrame> {
1747 Ok(DecodedVideoFrame {
1748 presentation_index,
1749 frame: VideoFrame::new(
1750 self.configuration.coded_dimensions,
1751 PixelFormat::Gray8,
1752 ColorRange::Full,
1753 vec![Plane {
1754 data: vec![value],
1755 stride: 1,
1756 }],
1757 &self.limits,
1758 )?,
1759 })
1760 }
1761 }
1762
1763 impl VideoDecoderFactory for ReplayFactory {
1764 fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
1765 CodecSupport::Supported {
1766 implementation: CodecImplementation::Software,
1767 }
1768 }
1769
1770 fn create(
1771 &self,
1772 configuration: &VideoDecoderConfig,
1773 limits: &Limits,
1774 ) -> Result<Box<dyn VideoDecoder>> {
1775 Ok(Box::new(ReplayDecoder {
1776 configuration: configuration.clone(),
1777 limits: *limits,
1778 previous: None,
1779 }))
1780 }
1781 }
1782
1783 impl VideoDecoder for ReplayDecoder {
1784 fn submit(
1785 &mut self,
1786 sample: &EncodedVideoSample,
1787 cancellation: &CancellationToken,
1788 ) -> Result<Vec<DecodedVideoFrame>> {
1789 cancellation.check()?;
1790 let value = sample.data[0];
1791 let mut outputs = Vec::new();
1792 if let Some((index, previous)) = self.previous {
1793 outputs.push(self.produce(index, previous)?);
1794 }
1795 outputs.push(self.produce(sample.presentation_index, value)?);
1796 self.previous = Some((sample.presentation_index, value));
1797 Ok(outputs)
1798 }
1799
1800 fn drain(&mut self, _: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
1801 Ok(Vec::new())
1802 }
1803
1804 fn reset(&mut self) -> Result<()> {
1805 self.previous = None;
1806 Ok(())
1807 }
1808 }
1809
1810 #[test]
1814 fn a_frame_the_decoder_emits_twice_is_cached_again_rather_than_refused() {
1815 let mut reader = ExactFrameReader::new(
1816 &ReplayFactory,
1817 config(),
1818 single_group_of_pictures(),
1819 Limits::default(),
1820 )
1821 .unwrap();
1822 let cancellation = CancellationToken::new();
1823
1824 assert_eq!(
1827 value(&reader.get(FrameIndex(3), &cancellation).unwrap()),
1828 30
1829 );
1830 assert_eq!(
1831 value(&reader.get(FrameIndex(6), &cancellation).unwrap()),
1832 60
1833 );
1834
1835 let resets = reader.statistics().resets;
1838 let hits = reader.statistics().cache_hits;
1839 assert_eq!(
1840 value(&reader.get(FrameIndex(5), &cancellation).unwrap()),
1841 50
1842 );
1843 assert_eq!(reader.statistics().resets, resets);
1844 assert!(reader.statistics().cache_hits > hits);
1845 }
1846
1847 fn single_group_of_pictures() -> Vec<EncodedVideoSample> {
1850 (0..10)
1851 .map(|index| sample(index, (index * 10) as u8, index == 0))
1852 .collect()
1853 }
1854
1855 fn small_cache() -> Limits {
1858 Limits {
1859 max_cached_frames: 2,
1860 ..Limits::default()
1861 }
1862 }
1863
1864 #[test]
1865 fn walking_to_a_distant_frame_does_not_ask_for_the_pictures_it_passes() {
1866 let log = Arc::new(Mutex::new(Vec::new()));
1867 let factory = HintFactory {
1868 wanted: Arc::clone(&log),
1869 };
1870 let mut reader = ExactFrameReader::new(
1871 &factory,
1872 config(),
1873 single_group_of_pictures(),
1874 small_cache(),
1875 )
1876 .unwrap();
1877 let cancellation = CancellationToken::new();
1878
1879 assert_eq!(
1880 value(&reader.get(FrameIndex(8), &cancellation).unwrap()),
1881 80
1882 );
1883 assert_eq!(
1884 *log.lock().unwrap(),
1885 vec![
1886 (0, false),
1887 (1, false),
1888 (2, false),
1889 (3, false),
1890 (4, false),
1891 (5, false),
1892 (6, true),
1893 (7, true),
1894 (8, true),
1895 ],
1896 "only the target and the tail the cache can hold are produced"
1897 );
1898 let statistics = reader.statistics();
1899 assert_eq!(statistics.samples_submitted, 9);
1900 assert_eq!(statistics.samples_skipped, 6);
1901 assert_eq!(statistics.resets, 1, "the walk itself is one decode");
1902 }
1903
1904 #[test]
1905 fn a_frame_the_walk_went_past_is_decoded_again_rather_than_reported_missing() {
1906 let log = Arc::new(Mutex::new(Vec::new()));
1907 let factory = HintFactory {
1908 wanted: Arc::clone(&log),
1909 };
1910 let mut reader = ExactFrameReader::new(
1911 &factory,
1912 config(),
1913 single_group_of_pictures(),
1914 small_cache(),
1915 )
1916 .unwrap();
1917 let cancellation = CancellationToken::new();
1918 reader.get(FrameIndex(8), &cancellation).unwrap();
1919 let resets = reader.statistics().resets;
1920
1921 assert_eq!(
1925 value(&reader.get(FrameIndex(4), &cancellation).unwrap()),
1926 40
1927 );
1928 assert_eq!(reader.statistics().resets, resets + 1);
1929 assert_eq!(
1931 value(&reader.get(FrameIndex(4), &cancellation).unwrap()),
1932 40
1933 );
1934 assert_eq!(reader.statistics().resets, resets + 1);
1935 }
1936
1937 #[test]
1938 fn a_reordered_frame_at_or_past_the_target_is_kept_for_the_request_that_follows() {
1939 let samples = vec![
1943 sample(0, 0, true),
1944 sample(4, 40, false),
1945 sample(2, 20, false),
1946 sample(1, 10, false),
1947 sample(3, 30, false),
1948 sample(8, 80, false),
1949 sample(6, 60, false),
1950 sample(5, 50, false),
1951 sample(7, 70, false),
1952 ];
1953 let log = Arc::new(Mutex::new(Vec::new()));
1954 let factory = HintFactory {
1955 wanted: Arc::clone(&log),
1956 };
1957 let mut reader = ExactFrameReader::new(&factory, config(), samples, small_cache()).unwrap();
1958 let cancellation = CancellationToken::new();
1959
1960 assert_eq!(
1961 value(&reader.get(FrameIndex(4), &cancellation).unwrap()),
1962 40
1963 );
1964 let resets = reader.statistics().resets;
1965 for (index, expected) in [(1_u64, 10_u8), (2, 20), (3, 30)] {
1966 assert_eq!(
1967 value(&reader.get(FrameIndex(index), &cancellation).unwrap()),
1968 expected,
1969 "frame {index} is still available"
1970 );
1971 }
1972 assert_eq!(
1973 reader.statistics().resets,
1974 resets,
1975 "a frame after the target in decode order is not skipped"
1976 );
1977 assert_eq!(
1978 reader.statistics().samples_skipped,
1979 1,
1980 "only frame 0, the random-access point the walk starts from, is behind frame 4"
1981 );
1982 }
1983
1984 #[test]
1985 fn a_walk_leaves_the_frames_behind_its_target_cached_so_stepping_back_is_free() {
1986 let log = Arc::new(Mutex::new(Vec::new()));
1990 let factory = HintFactory {
1991 wanted: Arc::clone(&log),
1992 };
1993 let samples: Vec<_> = (0..40)
1994 .map(|index| sample(index, index as u8, index == 0))
1995 .collect();
1996 let mut reader = ExactFrameReader::new(
1997 &factory,
1998 config(),
1999 samples,
2000 Limits {
2001 max_cached_frames: 4,
2002 ..Limits::default()
2003 },
2004 )
2005 .unwrap();
2006 let cancellation = CancellationToken::new();
2007 reader.get(FrameIndex(32), &cancellation).unwrap();
2008 let after_walk = reader.statistics();
2009 assert_eq!(after_walk.samples_skipped, 28, "frames 0 to 27 are skipped");
2010
2011 for index in [31_u64, 30, 29] {
2012 assert_eq!(
2013 value(&reader.get(FrameIndex(index), &cancellation).unwrap()),
2014 index as u8
2015 );
2016 }
2017 assert_eq!(
2018 reader.statistics().resets,
2019 after_walk.resets,
2020 "the tail the walk kept is in the cache, so stepping back decodes nothing"
2021 );
2022 assert_eq!(
2023 reader.statistics().samples_submitted,
2024 after_walk.samples_submitted
2025 );
2026 }
2027
2028 #[test]
2029 fn a_step_converts_its_own_picture_and_no_tail_behind_it() {
2030 let log = Arc::new(Mutex::new(Vec::new()));
2035 let factory = HintFactory {
2036 wanted: Arc::clone(&log),
2037 };
2038 let samples: Vec<_> = (0..40)
2039 .map(|index| sample(index, index as u8, index == 0))
2040 .collect();
2041 let mut reader = ExactFrameReader::new(
2042 &factory,
2043 config(),
2044 samples,
2045 Limits {
2046 max_cached_frames: 4,
2047 ..Limits::default()
2048 },
2049 )
2050 .unwrap();
2051 let cancellation = CancellationToken::new();
2052
2053 assert_eq!(
2054 value(&reader.get_step(FrameIndex(32), &cancellation).unwrap()),
2055 32
2056 );
2057 let after_step = reader.statistics();
2058 assert_eq!(
2059 after_step.samples_skipped, 32,
2060 "frames 0 to 31 are all passed through, tail included"
2061 );
2062 assert_eq!(
2063 reader.cached_frames(),
2064 1,
2065 "only the picture the step asked for was converted"
2066 );
2067 }
2068
2069 #[test]
2070 fn a_walk_of_steps_converts_what_it_asks_for_rather_than_what_it_passes() {
2071 let log = Arc::new(Mutex::new(Vec::new()));
2076 let factory = HintFactory {
2077 wanted: Arc::clone(&log),
2078 };
2079 let samples: Vec<_> = (0..64)
2080 .map(|index| sample(index, index as u8, index == 0))
2081 .collect();
2082 let mut reader = ExactFrameReader::new(
2083 &factory,
2084 config(),
2085 samples,
2086 Limits {
2087 max_cached_frames: 8,
2088 ..Limits::default()
2089 },
2090 )
2091 .unwrap();
2092 let cancellation = CancellationToken::new();
2093
2094 let steps: Vec<u64> = (4..60).step_by(4).collect();
2096 for step in &steps {
2097 reader.get_step(FrameIndex(*step), &cancellation).unwrap();
2098 }
2099 let converted = reader.statistics().samples_submitted - reader.statistics().samples_skipped;
2100 assert_eq!(
2101 converted,
2102 steps.len() as u64,
2103 "one conversion per published step, not one per frame passed"
2104 );
2105 assert_eq!(
2106 reader.statistics().resets,
2107 1,
2108 "only the cold start resets; a forward walk of steps never starts over again"
2109 );
2110 }
2111
2112 #[test]
2113 fn a_step_walk_that_ends_in_a_destination_still_leaves_a_cache_tail_to_step_back_through() {
2114 let log = Arc::new(Mutex::new(Vec::new()));
2118 let factory = HintFactory {
2119 wanted: Arc::clone(&log),
2120 };
2121 let samples: Vec<_> = (0..40)
2122 .map(|index| sample(index, index as u8, index == 0))
2123 .collect();
2124 let mut reader = ExactFrameReader::new(
2125 &factory,
2126 config(),
2127 samples,
2128 Limits {
2129 max_cached_frames: 4,
2130 ..Limits::default()
2131 },
2132 )
2133 .unwrap();
2134 let cancellation = CancellationToken::new();
2135
2136 for step in [8_u64, 16, 24] {
2137 reader.get_step(FrameIndex(step), &cancellation).unwrap();
2138 }
2139 reader.get(FrameIndex(32), &cancellation).unwrap();
2140 let after_walk = reader.statistics();
2141
2142 for index in [31_u64, 30, 29] {
2143 assert_eq!(
2144 value(&reader.get(FrameIndex(index), &cancellation).unwrap()),
2145 index as u8
2146 );
2147 }
2148 assert_eq!(
2149 reader.statistics().resets,
2150 after_walk.resets,
2151 "the destination kept its tail, so stepping back decodes nothing"
2152 );
2153 assert_eq!(
2154 reader.statistics().samples_submitted,
2155 after_walk.samples_submitted
2156 );
2157 }
2158
2159 struct LateFactory;
2162
2163 struct LateDecoder {
2164 configuration: VideoDecoderConfig,
2165 limits: Limits,
2166 held: Option<EncodedVideoSample>,
2167 output_wanted: bool,
2168 }
2169
2170 impl VideoDecoderFactory for LateFactory {
2171 fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
2172 CodecSupport::Supported {
2173 implementation: CodecImplementation::Software,
2174 }
2175 }
2176
2177 fn create(
2178 &self,
2179 configuration: &VideoDecoderConfig,
2180 limits: &Limits,
2181 ) -> Result<Box<dyn VideoDecoder>> {
2182 Ok(Box::new(LateDecoder {
2183 configuration: configuration.clone(),
2184 limits: *limits,
2185 held: None,
2186 output_wanted: true,
2187 }))
2188 }
2189 }
2190
2191 impl LateDecoder {
2192 fn release(&self, sample: EncodedVideoSample) -> Result<Vec<DecodedVideoFrame>> {
2193 if !self.output_wanted {
2194 return Ok(Vec::new());
2195 }
2196 Ok(vec![DecodedVideoFrame {
2197 presentation_index: sample.presentation_index,
2198 frame: VideoFrame::new(
2199 self.configuration.coded_dimensions,
2200 PixelFormat::Gray8,
2201 ColorRange::Full,
2202 vec![Plane {
2203 data: sample.data,
2204 stride: 1,
2205 }],
2206 &self.limits,
2207 )?,
2208 }])
2209 }
2210 }
2211
2212 impl VideoDecoder for LateDecoder {
2213 fn submit(
2214 &mut self,
2215 sample: &EncodedVideoSample,
2216 cancellation: &CancellationToken,
2217 ) -> Result<Vec<DecodedVideoFrame>> {
2218 cancellation.check()?;
2219 match self.held.replace(sample.clone()) {
2220 Some(previous) => self.release(previous),
2221 None => Ok(Vec::new()),
2222 }
2223 }
2224
2225 fn drain(&mut self, _: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
2226 match self.held.take() {
2227 Some(held) => self.release(held),
2228 None => Ok(Vec::new()),
2229 }
2230 }
2231
2232 fn reset(&mut self) -> Result<()> {
2233 self.held = None;
2234 Ok(())
2235 }
2236
2237 fn set_output_wanted(&mut self, wanted: bool) {
2238 self.output_wanted = wanted;
2239 }
2240 }
2241
2242 #[test]
2243 fn a_frame_still_inside_a_reordering_decoder_when_output_stops_is_written_off_too() {
2244 let mut reader = ExactFrameReader::new(
2249 &LateFactory,
2250 config(),
2251 single_group_of_pictures(),
2252 small_cache(),
2253 )
2254 .unwrap();
2255 let cancellation = CancellationToken::new();
2256
2257 assert_eq!(
2261 value(&reader.get(FrameIndex(4), &cancellation).unwrap()),
2262 40
2263 );
2264 assert_eq!(
2265 value(&reader.get(FrameIndex(9), &cancellation).unwrap()),
2266 90
2267 );
2268 assert_eq!(
2269 value(&reader.get(FrameIndex(5), &cancellation).unwrap()),
2270 50,
2271 "the frame that was dropped in flight is decoded again, not reported missing"
2272 );
2273 }
2274
2275 #[test]
2276 fn a_decoder_that_ignores_the_hint_still_answers_every_frame() {
2277 let factory = uncompressed_video_decoder_factory();
2280 let mut reader = ExactFrameReader::new(
2281 &factory,
2282 config(),
2283 single_group_of_pictures(),
2284 small_cache(),
2285 )
2286 .unwrap();
2287 let cancellation = CancellationToken::new();
2288 reader.get(FrameIndex(8), &cancellation).unwrap();
2289 assert_eq!(reader.statistics().samples_skipped, 6);
2290 for index in 0..9_u64 {
2291 assert_eq!(
2292 value(&reader.get(FrameIndex(index), &cancellation).unwrap()),
2293 (index * 10) as u8,
2294 "frame {index} came back from the decoder that ignored the hint"
2295 );
2296 }
2297 }
2298
2299 #[test]
2300 fn malformed_packets_and_cancellation_are_reported() {
2301 let factory = uncompressed_video_decoder_factory();
2302 let mut reader = ExactFrameReader::new(
2303 &factory,
2304 config(),
2305 vec![EncodedVideoSample {
2306 presentation_index: FrameIndex(0),
2307 random_access: true,
2308 data: Vec::new(),
2309 }],
2310 Limits::default(),
2311 )
2312 .unwrap();
2313 assert_eq!(
2314 reader
2315 .get(FrameIndex(0), &CancellationToken::new())
2316 .unwrap_err()
2317 .kind(),
2318 ErrorKind::MalformedMedia
2319 );
2320 let canceled = CancellationToken::new();
2321 canceled.cancel();
2322 assert_eq!(
2323 reader.get(FrameIndex(0), &canceled).unwrap_err().kind(),
2324 ErrorKind::Canceled
2325 );
2326 }
2327
2328 #[test]
2329 fn random_access_decode_work_obeys_the_configured_bound() {
2330 let factory = uncompressed_video_decoder_factory();
2331 let mut reader = ExactFrameReader::new(
2332 &factory,
2333 config(),
2334 vec![sample(0, 1, true), sample(1, 2, false), sample(2, 3, false)],
2335 Limits {
2336 max_decode_samples_per_seek: 2,
2337 ..Limits::default()
2338 },
2339 )
2340 .unwrap();
2341 let error = reader
2342 .get(FrameIndex(2), &CancellationToken::new())
2343 .unwrap_err();
2344 assert_eq!(error.kind(), ErrorKind::ResourceLimit);
2345 assert_eq!(reader.statistics().samples_submitted, 2);
2346 }
2347
2348 struct DelayedFactory;
2349 impl VideoDecoderFactory for DelayedFactory {
2350 fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
2351 CodecSupport::Supported {
2352 implementation: CodecImplementation::Software,
2353 }
2354 }
2355 fn create(
2356 &self,
2357 configuration: &VideoDecoderConfig,
2358 limits: &Limits,
2359 ) -> Result<Box<dyn VideoDecoder>> {
2360 Ok(Box::new(DelayedDecoder {
2361 configuration: configuration.clone(),
2362 limits: *limits,
2363 delayed: None,
2364 }))
2365 }
2366 }
2367 struct DelayedDecoder {
2368 configuration: VideoDecoderConfig,
2369 limits: Limits,
2370 delayed: Option<EncodedVideoSample>,
2371 }
2372 impl DelayedDecoder {
2373 fn decode(&self, sample: EncodedVideoSample) -> Result<DecodedVideoFrame> {
2374 Ok(DecodedVideoFrame {
2375 presentation_index: sample.presentation_index,
2376 frame: VideoFrame::new(
2377 self.configuration.coded_dimensions,
2378 PixelFormat::Gray8,
2379 ColorRange::Full,
2380 vec![Plane {
2381 data: sample.data,
2382 stride: 1,
2383 }],
2384 &self.limits,
2385 )?,
2386 })
2387 }
2388 }
2389 impl VideoDecoder for DelayedDecoder {
2390 fn submit(
2391 &mut self,
2392 sample: &EncodedVideoSample,
2393 cancellation: &CancellationToken,
2394 ) -> Result<Vec<DecodedVideoFrame>> {
2395 cancellation.check()?;
2396 let previous = self.delayed.replace(sample.clone());
2397 previous
2398 .map(|sample| self.decode(sample).map(|frame| vec![frame]))
2399 .unwrap_or(Ok(Vec::new()))
2400 }
2401 fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
2402 cancellation.check()?;
2403 self.delayed
2404 .take()
2405 .map(|sample| self.decode(sample).map(|frame| vec![frame]))
2406 .unwrap_or(Ok(Vec::new()))
2407 }
2408 fn reset(&mut self) -> Result<()> {
2409 self.delayed = None;
2410 Ok(())
2411 }
2412 }
2413
2414 #[test]
2415 fn delayed_output_drains_and_reset_clears_state() {
2416 let mut reader = ExactFrameReader::new(
2417 &DelayedFactory,
2418 config(),
2419 vec![sample(0, 11, true), sample(1, 22, false)],
2420 Limits::default(),
2421 )
2422 .unwrap();
2423 let cancellation = CancellationToken::new();
2424 assert_eq!(
2425 value(&reader.get(FrameIndex(1), &cancellation).unwrap()),
2426 22
2427 );
2428 assert_eq!(reader.statistics().drains, 1);
2429 reader.reset().unwrap();
2430 assert_eq!(reader.cached_frames(), 0);
2431 assert_eq!(
2432 value(&reader.get(FrameIndex(0), &cancellation).unwrap()),
2433 11
2434 );
2435 }
2436
2437 #[test]
2438 fn sequential_playback_through_a_pipelined_decoder_does_not_reset_every_frame() {
2439 let mut reader = ExactFrameReader::new(
2445 &DelayedFactory,
2446 config(),
2447 vec![
2448 sample(0, 11, true),
2449 sample(1, 22, false),
2450 sample(2, 33, false),
2451 sample(3, 44, false),
2452 sample(4, 55, false),
2453 ],
2454 Limits::default(),
2455 )
2456 .unwrap();
2457 let cancellation = CancellationToken::new();
2458
2459 assert_eq!(
2460 value(&reader.get(FrameIndex(0), &cancellation).unwrap()),
2461 11
2462 );
2463 assert_eq!(reader.statistics().resets, 1);
2464
2465 for (index, expected) in [(1, 22_u8), (2, 33), (3, 44), (4, 55)] {
2466 let frame = reader.get(FrameIndex(index), &cancellation).unwrap();
2467 assert_eq!(value(&frame), expected);
2468 assert_eq!(
2469 reader.statistics().resets,
2470 1,
2471 "sequential forward playback must not reset once decoding has started"
2472 );
2473 }
2474 assert_eq!(reader.statistics().samples_submitted, 5);
2475 assert_eq!(reader.statistics().drains, 1);
2476 }
2477
2478 struct MalformedOutputFactory;
2479
2480 impl VideoDecoderFactory for MalformedOutputFactory {
2481 fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
2482 CodecSupport::Supported {
2483 implementation: CodecImplementation::Software,
2484 }
2485 }
2486
2487 fn create(
2488 &self,
2489 configuration: &VideoDecoderConfig,
2490 limits: &Limits,
2491 ) -> Result<Box<dyn VideoDecoder>> {
2492 let factory = UncompressedVideoDecoderFactory;
2493 factory.create(configuration, limits).map(|decoder| {
2494 Box::new(MalformedOutputDecoder {
2495 decoder,
2496 previous: None,
2497 }) as Box<dyn VideoDecoder>
2498 })
2499 }
2500 }
2501
2502 struct MalformedOutputDecoder {
2503 decoder: Box<dyn VideoDecoder>,
2504 previous: Option<FrameIndex>,
2505 }
2506
2507 impl VideoDecoder for MalformedOutputDecoder {
2508 fn submit(
2509 &mut self,
2510 sample: &EncodedVideoSample,
2511 cancellation: &CancellationToken,
2512 ) -> Result<Vec<DecodedVideoFrame>> {
2513 let mut output = self.decoder.submit(sample, cancellation)?;
2514 if let (Some(previous), Some(frame)) = (self.previous, output.first_mut()) {
2515 frame.presentation_index = previous;
2516 }
2517 self.previous = Some(sample.presentation_index);
2518 Ok(output)
2519 }
2520
2521 fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
2522 self.decoder.drain(cancellation)
2523 }
2524
2525 fn reset(&mut self) -> Result<()> {
2526 self.previous = None;
2527 self.decoder.reset()
2528 }
2529 }
2530
2531 #[test]
2532 fn malformed_backend_output_is_rejected() {
2533 let mut reader = ExactFrameReader::new(
2534 &MalformedOutputFactory,
2535 config(),
2536 vec![sample(0, 1, true), sample(1, 2, false)],
2537 Limits::default(),
2538 )
2539 .unwrap();
2540 let error = reader
2541 .get(FrameIndex(1), &CancellationToken::new())
2542 .unwrap_err();
2543 assert_eq!(error.kind(), ErrorKind::MalformedMedia);
2544 }
2545}