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 {
163 fn config(&self) -> &EncoderConfig;
164 fn format(&self) -> AudioEncoderFormat;
165 fn encode<'a>(
166 &'a mut self,
167 index: FrameIndex,
168 buffer: AudioBuffer,
169 ) -> EncoderFuture<'a, Vec<EncodedSample>>;
170 fn finish<'a>(&'a mut self) -> EncoderFuture<'a, AudioDrain>;
171}
172
173#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
175#[non_exhaustive]
176pub enum CodecProfile {
177 UncompressedGray8,
178 H264Baseline,
181 H264Main,
183 H264High,
186 HevcMain,
187 HevcMain10,
188 Av1Main,
189 Av1High,
190 Av1Professional,
191 Vp8,
194 Vp9Profile0,
196 Vp9Profile1,
198 Vp9Profile2,
200 Vp9Profile3,
202 AacLowComplexity,
203 Opus,
205 Vorbis,
207}
208
209#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
211#[non_exhaustive]
212pub enum HardwarePreference {
213 Require,
214 Prefer,
215 Avoid,
216}
217
218#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
220#[non_exhaustive]
221pub enum CodecImplementation {
222 Software,
223 Hardware,
224}
225
226#[derive(Clone, Debug, Eq, PartialEq)]
228#[non_exhaustive]
229pub enum CodecSupport {
230 Supported { implementation: CodecImplementation },
231 UnsupportedCodec,
232 UnsupportedProfile,
233 InvalidConfiguration { reason: String },
234 HardwareUnavailable,
235}
236
237impl CodecSupport {
238 pub const fn is_supported(&self) -> bool {
239 matches!(self, Self::Supported { .. })
240 }
241}
242
243#[derive(Clone, Debug, Eq, PartialEq)]
245pub struct VideoDecoderConfig {
246 pub codec: Codec,
247 pub profile: CodecProfile,
248 pub coded_dimensions: VideoDimensions,
249 pub output_format: PixelFormat,
250 pub color_range: ColorRange,
251 pub hardware: HardwarePreference,
252 pub configuration: Vec<u8>,
254}
255
256#[derive(Clone, Debug, Eq, PartialEq)]
258pub struct VideoEncoderConfig {
259 pub codec: Codec,
260 pub profile: CodecProfile,
261 pub coded_dimensions: VideoDimensions,
262 pub input_format: PixelFormat,
263 pub color_range: ColorRange,
264 pub hardware: HardwarePreference,
265 pub timescale: u32,
267 pub frame_duration: u32,
269 pub configuration: Vec<u8>,
270}
271
272#[derive(Clone, Debug, Eq, PartialEq)]
274pub struct EncodedVideoSample {
275 pub presentation_index: FrameIndex,
276 pub random_access: bool,
277 pub data: Vec<u8>,
278}
279
280pub trait SampleProvider: Send {
297 fn len(&self) -> usize;
299 fn is_empty(&self) -> bool {
300 self.len() == 0
301 }
302 fn is_random_access(&self, decode_index: usize) -> bool;
303 fn presentation_index(&self, decode_index: usize) -> FrameIndex;
304 fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>>;
306}
307
308impl SampleProvider for Vec<EncodedVideoSample> {
309 fn len(&self) -> usize {
310 self.as_slice().len()
311 }
312
313 fn is_random_access(&self, decode_index: usize) -> bool {
314 self[decode_index].random_access
315 }
316
317 fn presentation_index(&self, decode_index: usize) -> FrameIndex {
318 self[decode_index].presentation_index
319 }
320
321 fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>> {
322 Ok(Cow::Borrowed(&self[decode_index].data))
323 }
324}
325
326#[derive(Clone, Debug, Eq, PartialEq)]
328pub struct DecodedVideoFrame {
329 pub presentation_index: FrameIndex,
330 pub frame: VideoFrame,
331}
332
333#[derive(Clone, Debug, Default)]
335pub struct CancellationToken {
336 canceled: Arc<AtomicBool>,
337}
338
339impl CancellationToken {
340 pub fn new() -> Self {
341 Self::default()
342 }
343
344 pub fn cancel(&self) {
345 self.canceled.store(true, Ordering::Release);
346 }
347
348 pub fn is_canceled(&self) -> bool {
349 self.canceled.load(Ordering::Acquire)
350 }
351
352 #[doc(hidden)]
353 pub fn check(&self) -> Result<()> {
354 if self.is_canceled() {
355 Err(Error::new(ErrorKind::Canceled, "codec operation canceled"))
356 } else {
357 Ok(())
358 }
359 }
360}
361
362pub trait VideoDecoder: Send {
367 fn submit(
368 &mut self,
369 sample: &EncodedVideoSample,
370 cancellation: &CancellationToken,
371 ) -> Result<Vec<DecodedVideoFrame>>;
372 fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>>;
373 fn reset(&mut self) -> Result<()>;
374
375 fn set_output_wanted(&mut self, _wanted: bool) {}
396}
397
398pub trait VideoDecoderFactory {
400 fn capability(&self, configuration: &VideoDecoderConfig) -> CodecSupport;
401 fn create(
402 &self,
403 configuration: &VideoDecoderConfig,
404 limits: &Limits,
405 ) -> Result<Box<dyn VideoDecoder>>;
406}
407
408pub trait VideoEncoderFactory {
410 fn capability(&self, configuration: &VideoEncoderConfig) -> CodecSupport;
411 fn create(
412 &self,
413 configuration: &VideoEncoderConfig,
414 limits: &Limits,
415 ) -> Result<Box<dyn VideoEncoder>>;
416}
417
418#[derive(Clone, Debug, Eq, PartialEq)]
420pub struct AudioEncoderConfig {
421 pub codec: Codec,
422 pub profile: CodecProfile,
423 pub sample_rate: u32,
424 pub channels: u16,
425 pub timescale: u32,
427 pub configuration: Vec<u8>,
428}
429
430pub trait AudioEncoderFactory {
439 fn capability(&self, configuration: &AudioEncoderConfig) -> CodecSupport;
440 fn create(
441 &self,
442 configuration: &AudioEncoderConfig,
443 limits: &Limits,
444 ) -> Result<Box<dyn AudioEncoder>>;
445}
446
447#[doc(hidden)]
453pub fn parse_audio_bit_rate(configuration: &[u8]) -> Option<Option<u32>> {
454 match configuration {
455 [] => Some(None),
456 [a, b, c, d] => match u32::from_be_bytes([*a, *b, *c, *d]) {
457 0 => None,
458 bits_per_second => Some(Some(bits_per_second)),
459 },
460 _ => None,
461 }
462}
463
464#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
466pub struct DecodeStatistics {
467 pub samples_submitted: u64,
468 pub samples_skipped: u64,
471 pub cache_hits: u64,
472 pub resets: u64,
473 pub drains: u64,
474}
475
476pub struct ExactFrameReader {
478 configuration: VideoDecoderConfig,
479 decoder: Box<dyn VideoDecoder>,
480 samples: Box<dyn SampleProvider>,
481 decode_position_by_presentation: HashMap<FrameIndex, usize>,
482 cache: BTreeMap<FrameIndex, VideoFrame>,
483 lru: VecDeque<FrameIndex>,
484 published_since_reset: HashSet<FrameIndex>,
492 suppressed_since_reset: HashSet<FrameIndex>,
496 in_flight_since_reset: HashSet<FrameIndex>,
501 output_wanted: bool,
504 next_decode_position: Option<usize>,
505 session_start: Option<usize>,
508 seek_previews: Option<Arc<dyn SeekPreviewSource>>,
510 limits: Limits,
511 statistics: DecodeStatistics,
512}
513
514pub const SEEK_LATENCY_BUDGET: Duration = Duration::from_millis(50);
519
520pub trait SeekPreviewSource: Send + Sync {
532 fn nearest_at(&self, frame: FrameIndex) -> Option<(FrameIndex, VideoFrame)>;
535}
536
537#[derive(Clone, Debug, Eq, PartialEq)]
546pub enum Seek {
547 Exact(VideoFrame),
549 Preview {
551 picture: VideoFrame,
552 frame: FrameIndex,
555 },
556 Pending,
559}
560
561#[derive(Clone, Copy, Debug, Eq, PartialEq)]
568enum Request {
569 Destination,
572 Step,
575}
576
577impl Request {
578 fn cache_tail(self, limits: &Limits) -> u64 {
580 match self {
581 Self::Destination => u64::from(limits.max_cached_frames),
582 Self::Step => 0,
583 }
584 }
585}
586
587impl ExactFrameReader {
588 pub fn new(
589 factory: &dyn VideoDecoderFactory,
590 configuration: VideoDecoderConfig,
591 samples: Vec<EncodedVideoSample>,
592 limits: Limits,
593 ) -> Result<Self> {
594 Self::from_provider(factory, configuration, Box::new(samples), limits)
595 }
596
597 pub fn from_provider(
604 factory: &dyn VideoDecoderFactory,
605 configuration: VideoDecoderConfig,
606 samples: Box<dyn SampleProvider>,
607 limits: Limits,
608 ) -> Result<Self> {
609 if limits.max_cached_frames == 0 || limits.max_decode_samples_per_seek == 0 {
610 return Err(Error::new(
611 ErrorKind::ResourceLimit,
612 "exact-frame limits must permit cached frames and decode work",
613 ));
614 }
615 let capability = factory.capability(&configuration);
616 if !capability.is_supported() {
617 return Err(capability_error(capability));
618 }
619 if samples.is_empty() {
620 return Err(Error::new(
621 ErrorKind::InvalidInput,
622 "an exact-frame reader requires at least one sample",
623 ));
624 }
625 if !samples.is_random_access(0) {
626 return Err(Error::new(
627 ErrorKind::InvalidInput,
628 "the first decode-order sample must be a random-access point",
629 ));
630 }
631 let mut positions = HashMap::with_capacity(samples.len());
632 for position in 0..samples.len() {
633 if positions
634 .insert(samples.presentation_index(position), position)
635 .is_some()
636 {
637 return Err(Error::new(
638 ErrorKind::InvalidInput,
639 "presentation frame identities must be unique",
640 ));
641 }
642 }
643 let decoder = factory.create(&configuration, &limits)?;
644 Ok(Self {
645 configuration,
646 decoder,
647 samples,
648 decode_position_by_presentation: positions,
649 cache: BTreeMap::new(),
650 lru: VecDeque::new(),
651 published_since_reset: HashSet::new(),
652 suppressed_since_reset: HashSet::new(),
653 in_flight_since_reset: HashSet::new(),
654 output_wanted: true,
655 next_decode_position: None,
656 session_start: None,
657 seek_previews: None,
658 limits,
659 statistics: DecodeStatistics::default(),
660 })
661 }
662
663 fn sample_at(&self, position: usize) -> Result<EncodedVideoSample> {
667 Ok(EncodedVideoSample {
668 presentation_index: self.samples.presentation_index(position),
669 random_access: self.samples.is_random_access(position),
670 data: self.samples.read(position)?.into_owned(),
671 })
672 }
673
674 pub fn set_seek_previews(&mut self, previews: Option<Arc<dyn SeekPreviewSource>>) {
680 self.seek_previews = previews;
681 }
682
683 pub fn seek(&mut self, presentation_index: FrameIndex) -> Seek {
696 if let Some(frame) = self.cache.get(&presentation_index).cloned() {
697 self.statistics.cache_hits = self.statistics.cache_hits.saturating_add(1);
698 self.touch(presentation_index);
699 return Seek::Exact(frame);
700 }
701 match self
702 .seek_previews
703 .as_ref()
704 .and_then(|previews| previews.nearest_at(presentation_index))
705 {
706 Some((frame, picture)) => Seek::Preview { picture, frame },
707 None => Seek::Pending,
708 }
709 }
710
711 pub fn get(
720 &mut self,
721 presentation_index: FrameIndex,
722 cancellation: &CancellationToken,
723 ) -> Result<VideoFrame> {
724 self.get_request(presentation_index, Request::Destination, cancellation)
725 }
726
727 pub fn get_step(
742 &mut self,
743 presentation_index: FrameIndex,
744 cancellation: &CancellationToken,
745 ) -> Result<VideoFrame> {
746 self.get_request(presentation_index, Request::Step, cancellation)
747 }
748
749 fn get_request(
750 &mut self,
751 presentation_index: FrameIndex,
752 request: Request,
753 cancellation: &CancellationToken,
754 ) -> Result<VideoFrame> {
755 cancellation.check()?;
756 if let Some(frame) = self.cache.get(&presentation_index).cloned() {
757 self.statistics.cache_hits = self.statistics.cache_hits.saturating_add(1);
758 self.touch(presentation_index);
759 return Ok(frame);
760 }
761 let target_position = *self
762 .decode_position_by_presentation
763 .get(&presentation_index)
764 .ok_or_else(|| {
765 Error::new(ErrorKind::InvalidInput, "presentation frame is not indexed")
766 })?;
767 let random_access_position = self.nearest_random_access(target_position);
768 if !self.session_reaches(presentation_index, random_access_position) {
788 self.decoder.reset()?;
789 self.statistics.resets = self.statistics.resets.saturating_add(1);
790 self.published_since_reset.clear();
791 self.suppressed_since_reset.clear();
792 self.in_flight_since_reset.clear();
793 self.next_decode_position = Some(random_access_position);
794 self.session_start = Some(random_access_position);
795 }
796
797 let mut work = 0_u32;
798 while let Some(position) = self.next_decode_position {
799 cancellation.check()?;
800 if work >= self.limits.max_decode_samples_per_seek {
801 return Err(Error::new(
802 ErrorKind::ResourceLimit,
803 "exact-frame request exceeded the configured decode-work limit",
804 ));
805 }
806 if position == self.samples.len() {
807 self.set_output_wanted(true);
808 self.drain_internal(cancellation)?;
809 break;
810 }
811 let sample = self.sample_at(position)?;
815 let cache_tail = request.cache_tail(&self.limits);
838 let wanted = position >= target_position
839 || sample.presentation_index.0 >= presentation_index.0.saturating_sub(cache_tail);
840 self.set_output_wanted(wanted);
841 let suppressed = !self.output_wanted;
842 let outputs = self.decoder.submit(&sample, cancellation)?;
843 self.statistics.samples_submitted = self.statistics.samples_submitted.saturating_add(1);
844 if suppressed {
845 self.statistics.samples_skipped = self.statistics.samples_skipped.saturating_add(1);
846 self.suppressed_since_reset
847 .insert(sample.presentation_index);
848 } else {
849 self.in_flight_since_reset.insert(sample.presentation_index);
850 }
851 self.next_decode_position = Some(position + 1);
852 work += 1;
853 self.publish(outputs)?;
854 if let Some(frame) = self.cache.get(&presentation_index).cloned() {
855 self.touch(presentation_index);
856 return Ok(frame);
857 }
858 }
859 if let Some(frame) = self.cache.get(&presentation_index).cloned() {
860 self.touch(presentation_index);
861 Ok(frame)
862 } else {
863 Err(Error::new(
864 ErrorKind::MalformedMedia,
865 "decoder did not produce the requested presentation frame",
866 ))
867 }
868 }
869
870 pub fn decode_positions_for(
881 &self,
882 presentation_index: FrameIndex,
883 ) -> Result<std::ops::Range<usize>> {
884 if self.cache.contains_key(&presentation_index) {
885 return Ok(0..0);
886 }
887 let target_position = *self
888 .decode_position_by_presentation
889 .get(&presentation_index)
890 .ok_or_else(|| {
891 Error::new(ErrorKind::InvalidInput, "presentation frame is not indexed")
892 })?;
893 let random_access_position = self.nearest_random_access(target_position);
894 let start = match self.next_decode_position {
895 Some(next) if self.session_reaches(presentation_index, random_access_position) => next,
896 _ => random_access_position,
897 };
898 let len = self.samples.len();
899 let scan_end = target_position
900 .saturating_add(1)
901 .saturating_add(self.limits.max_decode_samples_per_seek as usize)
902 .min(len);
903 let mut end = target_position + 1;
904 for position in target_position + 1..scan_end {
905 let presented = self.samples.presentation_index(position);
906 if presented <= presentation_index {
907 end = position + 1;
908 } else if self.samples.is_random_access(position) {
909 break;
910 }
911 }
912 Ok(start..end.max((start + 1).min(len)))
913 }
914
915 fn session_reaches(
923 &self,
924 presentation_index: FrameIndex,
925 random_access_position: usize,
926 ) -> bool {
927 self.next_decode_position
928 .is_some_and(|position| position >= random_access_position)
929 && self
930 .session_start
931 .is_some_and(|start| start <= random_access_position)
932 && !self.published_since_reset.contains(&presentation_index)
933 && !self.suppressed_since_reset.contains(&presentation_index)
934 }
935
936 pub fn drain(&mut self, cancellation: &CancellationToken) -> Result<usize> {
938 cancellation.check()?;
939 self.set_output_wanted(true);
940 self.drain_internal(cancellation)
941 }
942
943 fn set_output_wanted(&mut self, wanted: bool) {
955 if self.output_wanted == wanted {
956 return;
957 }
958 if !wanted {
959 for frame in self.in_flight_since_reset.drain() {
960 self.suppressed_since_reset.insert(frame);
961 }
962 }
963 self.decoder.set_output_wanted(wanted);
964 self.output_wanted = wanted;
965 }
966
967 pub fn reset(&mut self) -> Result<()> {
969 self.set_output_wanted(true);
970 self.decoder.reset()?;
971 self.statistics.resets = self.statistics.resets.saturating_add(1);
972 self.next_decode_position = None;
973 self.session_start = None;
974 self.cache.clear();
975 self.lru.clear();
976 self.published_since_reset.clear();
977 self.suppressed_since_reset.clear();
978 self.in_flight_since_reset.clear();
979 Ok(())
980 }
981
982 pub const fn statistics(&self) -> DecodeStatistics {
983 self.statistics
984 }
985
986 pub fn cached_frames(&self) -> usize {
987 self.cache.len()
988 }
989
990 fn nearest_random_access(&self, target_position: usize) -> usize {
998 let target = self.samples.presentation_index(target_position);
999 (0..=target_position)
1000 .rev()
1001 .find(|&position| {
1002 self.samples.is_random_access(position)
1003 && self.samples.presentation_index(position) <= target
1004 })
1005 .unwrap_or(0)
1006 }
1007
1008 fn drain_internal(&mut self, cancellation: &CancellationToken) -> Result<usize> {
1009 let outputs = self.decoder.drain(cancellation)?;
1010 let count = outputs.len();
1011 self.statistics.drains = self.statistics.drains.saturating_add(1);
1012 self.next_decode_position = Some(self.samples.len());
1013 self.publish(outputs)?;
1014 Ok(count)
1015 }
1016
1017 fn publish(&mut self, outputs: Vec<DecodedVideoFrame>) -> Result<()> {
1018 for output in outputs {
1019 self.suppressed_since_reset
1023 .remove(&output.presentation_index);
1024 self.in_flight_since_reset
1025 .remove(&output.presentation_index);
1026 self.published_since_reset.insert(output.presentation_index);
1036 if !self
1037 .decode_position_by_presentation
1038 .contains_key(&output.presentation_index)
1039 {
1040 return Err(Error::new(
1041 ErrorKind::MalformedMedia,
1042 "decoder produced an unindexed presentation frame",
1043 ));
1044 }
1045 if output.frame.dimensions != self.configuration.coded_dimensions
1046 || output.frame.pixel_format != self.configuration.output_format
1047 || output.frame.color_range != self.configuration.color_range
1048 {
1049 return Err(Error::new(
1050 ErrorKind::MalformedMedia,
1051 "decoder output does not match its normalized configuration",
1052 ));
1053 }
1054 self.insert_cache(output.presentation_index, output.frame);
1055 }
1056 Ok(())
1057 }
1058
1059 fn insert_cache(&mut self, index: FrameIndex, frame: VideoFrame) {
1060 self.cache.insert(index, frame);
1061 self.touch(index);
1062 while self.cache.len() > self.limits.max_cached_frames as usize {
1063 if let Some(evicted) = self.lru.pop_front() {
1064 self.cache.remove(&evicted);
1065 }
1066 }
1067 }
1068
1069 fn touch(&mut self, index: FrameIndex) {
1070 self.lru.retain(|candidate| *candidate != index);
1071 self.lru.push_back(index);
1072 }
1073}
1074
1075fn capability_error(capability: CodecSupport) -> Error {
1076 let (kind, message) = match capability {
1077 CodecSupport::UnsupportedCodec => (
1078 ErrorKind::Unsupported,
1079 "decoder does not support the requested codec".into(),
1080 ),
1081 CodecSupport::UnsupportedProfile => (
1082 ErrorKind::Unsupported,
1083 "decoder does not support the requested profile".into(),
1084 ),
1085 CodecSupport::InvalidConfiguration { reason } => (ErrorKind::InvalidInput, reason),
1086 CodecSupport::HardwareUnavailable => (
1087 ErrorKind::Unsupported,
1088 "requested hardware decoder is unavailable".into(),
1089 ),
1090 CodecSupport::Supported { .. } => (
1091 ErrorKind::Internal,
1092 "decoder capability changed unexpectedly".into(),
1093 ),
1094 };
1095 Error::new(kind, message)
1096}
1097
1098pub fn uncompressed_video_decoder_factory() -> impl VideoDecoderFactory {
1103 UncompressedVideoDecoderFactory
1104}
1105
1106struct UncompressedVideoDecoderFactory;
1107
1108impl VideoDecoderFactory for UncompressedVideoDecoderFactory {
1109 fn capability(&self, configuration: &VideoDecoderConfig) -> CodecSupport {
1110 if configuration.codec != Codec::UncompressedVideo {
1111 return CodecSupport::UnsupportedCodec;
1112 }
1113 if configuration.profile != CodecProfile::UncompressedGray8 {
1114 return CodecSupport::UnsupportedProfile;
1115 }
1116 if configuration.output_format != PixelFormat::Gray8
1117 || !configuration.configuration.is_empty()
1118 {
1119 return CodecSupport::InvalidConfiguration {
1120 reason: "uncompressed Gray8 requires Gray8 output and no configuration bytes"
1121 .into(),
1122 };
1123 }
1124 if configuration.hardware == HardwarePreference::Require {
1125 return CodecSupport::HardwareUnavailable;
1126 }
1127 CodecSupport::Supported {
1128 implementation: CodecImplementation::Software,
1129 }
1130 }
1131
1132 fn create(
1133 &self,
1134 configuration: &VideoDecoderConfig,
1135 limits: &Limits,
1136 ) -> Result<Box<dyn VideoDecoder>> {
1137 let capability = self.capability(configuration);
1138 if !capability.is_supported() {
1139 return Err(capability_error(capability));
1140 }
1141 if configuration.coded_dimensions.width > limits.max_width
1142 || configuration.coded_dimensions.height > limits.max_height
1143 {
1144 return Err(Error::new(
1145 ErrorKind::ResourceLimit,
1146 "decoded dimensions exceed the configured limits",
1147 ));
1148 }
1149 let required = u64::from(configuration.coded_dimensions.width)
1150 .checked_mul(u64::from(configuration.coded_dimensions.height))
1151 .ok_or_else(|| Error::new(ErrorKind::ResourceLimit, "decoded frame size overflow"))?;
1152 if required > limits.max_allocation_bytes {
1153 return Err(Error::new(
1154 ErrorKind::ResourceLimit,
1155 "decoded frame exceeds the configured allocation limit",
1156 ));
1157 }
1158 Ok(Box::new(UncompressedVideoDecoder {
1159 configuration: configuration.clone(),
1160 limits: *limits,
1161 }))
1162 }
1163}
1164
1165struct UncompressedVideoDecoder {
1166 configuration: VideoDecoderConfig,
1167 limits: Limits,
1168}
1169
1170impl VideoDecoder for UncompressedVideoDecoder {
1171 fn submit(
1172 &mut self,
1173 sample: &EncodedVideoSample,
1174 cancellation: &CancellationToken,
1175 ) -> Result<Vec<DecodedVideoFrame>> {
1176 cancellation.check()?;
1177 let width = usize::try_from(self.configuration.coded_dimensions.width)
1178 .map_err(|_| Error::new(ErrorKind::ResourceLimit, "decoded width is too large"))?;
1179 let height = usize::try_from(self.configuration.coded_dimensions.height)
1180 .map_err(|_| Error::new(ErrorKind::ResourceLimit, "decoded height is too large"))?;
1181 let length = width
1182 .checked_mul(height)
1183 .ok_or_else(|| Error::new(ErrorKind::ResourceLimit, "decoded frame size overflow"))?;
1184 if sample.data.len() != length {
1185 return Err(Error::new(
1186 ErrorKind::MalformedMedia,
1187 "uncompressed Gray8 packet size does not match coded dimensions",
1188 ));
1189 }
1190 let frame = VideoFrame::new(
1191 self.configuration.coded_dimensions,
1192 PixelFormat::Gray8,
1193 self.configuration.color_range,
1194 vec![Plane {
1195 data: sample.data.clone(),
1196 stride: width,
1197 }],
1198 &self.limits,
1199 )?;
1200 Ok(vec![DecodedVideoFrame {
1201 presentation_index: sample.presentation_index,
1202 frame,
1203 }])
1204 }
1205
1206 fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
1207 cancellation.check()?;
1208 Ok(Vec::new())
1209 }
1210
1211 fn reset(&mut self) -> Result<()> {
1212 Ok(())
1213 }
1214}
1215
1216#[cfg(test)]
1217mod tests {
1218 use super::*;
1219 use std::sync::Mutex;
1220
1221 fn config() -> VideoDecoderConfig {
1222 VideoDecoderConfig {
1223 codec: Codec::UncompressedVideo,
1224 profile: CodecProfile::UncompressedGray8,
1225 coded_dimensions: VideoDimensions::new(1, 1, &Limits::default()).unwrap(),
1226 output_format: PixelFormat::Gray8,
1227 color_range: ColorRange::Full,
1228 hardware: HardwarePreference::Avoid,
1229 configuration: Vec::new(),
1230 }
1231 }
1232
1233 fn sample(index: u64, value: u8, random_access: bool) -> EncodedVideoSample {
1234 EncodedVideoSample {
1235 presentation_index: FrameIndex(index),
1236 random_access,
1237 data: vec![value],
1238 }
1239 }
1240
1241 fn value(frame: &VideoFrame) -> u8 {
1242 frame.planes[0].data[0]
1243 }
1244
1245 struct LoadOnDemand {
1248 samples: Vec<EncodedVideoSample>,
1249 loaded: Arc<Mutex<HashSet<usize>>>,
1250 }
1251
1252 impl SampleProvider for LoadOnDemand {
1253 fn len(&self) -> usize {
1254 self.samples.len()
1255 }
1256
1257 fn is_random_access(&self, decode_index: usize) -> bool {
1258 self.samples[decode_index].random_access
1259 }
1260
1261 fn presentation_index(&self, decode_index: usize) -> FrameIndex {
1262 self.samples[decode_index].presentation_index
1263 }
1264
1265 fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>> {
1266 if self.loaded.lock().unwrap().contains(&decode_index) {
1267 Ok(Cow::Borrowed(&self.samples[decode_index].data))
1268 } else {
1269 Err(Error::new(ErrorKind::WouldBlock, "not loaded yet"))
1270 }
1271 }
1272 }
1273
1274 #[test]
1278 fn a_request_waiting_on_an_unloaded_sample_resumes_where_it_stopped() {
1279 let loaded = Arc::new(Mutex::new(HashSet::new()));
1280 let samples = (0..12)
1281 .map(|index| sample(index, index as u8, index % 4 == 0))
1282 .collect();
1283 let mut reader = ExactFrameReader::from_provider(
1284 &uncompressed_video_decoder_factory(),
1285 config(),
1286 Box::new(LoadOnDemand {
1287 samples,
1288 loaded: loaded.clone(),
1289 }),
1290 Limits::default(),
1291 )
1292 .unwrap();
1293 let cancellation = CancellationToken::new();
1294
1295 assert_eq!(reader.decode_positions_for(FrameIndex(6)).unwrap(), 4..7);
1296 let error = reader.get(FrameIndex(6), &cancellation).unwrap_err();
1297 assert_eq!(error.kind(), ErrorKind::WouldBlock);
1298 assert_eq!(reader.statistics().samples_submitted, 0);
1299
1300 loaded.lock().unwrap().extend([4, 5]);
1301 let error = reader.get(FrameIndex(6), &cancellation).unwrap_err();
1302 assert_eq!(error.kind(), ErrorKind::WouldBlock);
1303 assert_eq!(reader.statistics().samples_submitted, 2);
1304 assert_eq!(reader.decode_positions_for(FrameIndex(6)).unwrap(), 6..7);
1306
1307 loaded.lock().unwrap().insert(6);
1308 assert_eq!(value(&reader.get(FrameIndex(6), &cancellation).unwrap()), 6);
1309 assert_eq!(reader.statistics().samples_submitted, 3);
1310 assert_eq!(reader.statistics().resets, 1);
1311
1312 assert!(
1315 reader
1316 .decode_positions_for(FrameIndex(6))
1317 .unwrap()
1318 .is_empty()
1319 );
1320 assert_eq!(reader.decode_positions_for(FrameIndex(7)).unwrap(), 7..8);
1321 assert_eq!(reader.decode_positions_for(FrameIndex(10)).unwrap(), 8..11);
1322 assert_eq!(reader.decode_positions_for(FrameIndex(1)).unwrap(), 0..2);
1323 }
1324
1325 #[test]
1328 fn decode_positions_for_a_reordered_frame_reach_the_samples_presented_before_it() {
1329 let samples = vec![
1331 sample(0, 0, true),
1332 sample(3, 3, false),
1333 sample(1, 1, false),
1334 sample(2, 2, false),
1335 sample(4, 4, true),
1336 ];
1337 let reader = ExactFrameReader::new(
1338 &uncompressed_video_decoder_factory(),
1339 config(),
1340 samples,
1341 Limits::default(),
1342 )
1343 .unwrap();
1344 assert_eq!(reader.decode_positions_for(FrameIndex(1)).unwrap(), 0..3);
1345 assert_eq!(reader.decode_positions_for(FrameIndex(2)).unwrap(), 0..4);
1346 assert_eq!(reader.decode_positions_for(FrameIndex(3)).unwrap(), 0..4);
1347 assert_eq!(reader.decode_positions_for(FrameIndex(4)).unwrap(), 4..5);
1348 }
1349
1350 fn single_group_reader(frames: u64) -> ExactFrameReader {
1354 let samples = (0..frames)
1355 .map(|index| sample(index, (index % 251) as u8, index == 0))
1356 .collect();
1357 ExactFrameReader::new(
1358 &uncompressed_video_decoder_factory(),
1359 config(),
1360 samples,
1361 Limits::default(),
1362 )
1363 .unwrap()
1364 }
1365
1366 struct StridedPreviews {
1370 stride: u64,
1371 frames: u64,
1372 }
1373
1374 impl SeekPreviewSource for StridedPreviews {
1375 fn nearest_at(&self, frame: FrameIndex) -> Option<(FrameIndex, VideoFrame)> {
1376 if self.frames == 0 {
1377 return None;
1378 }
1379 let at = (frame.0 / self.stride * self.stride).min(self.frames - 1);
1380 let picture = VideoFrame::new(
1381 config().coded_dimensions,
1382 PixelFormat::Gray8,
1383 ColorRange::Full,
1384 vec![Plane {
1385 data: vec![(at % 251) as u8],
1386 stride: 1,
1387 }],
1388 &Limits::default(),
1389 )
1390 .ok()?;
1391 Some((FrameIndex(at), picture))
1392 }
1393 }
1394
1395 #[test]
1399 fn a_seek_with_nothing_decoded_is_pending_and_submits_no_samples() {
1400 let mut reader = single_group_reader(512);
1401 assert_eq!(reader.seek(FrameIndex(511)), Seek::Pending);
1402 assert_eq!(reader.statistics().samples_submitted, 0);
1403 assert_eq!(reader.statistics().resets, 0);
1404 }
1405
1406 #[test]
1408 fn a_seek_into_the_cache_answers_exactly() {
1409 let mut reader = single_group_reader(64);
1410 let cancellation = CancellationToken::new();
1411 reader.get(FrameIndex(40), &cancellation).unwrap();
1412 let submitted = reader.statistics().samples_submitted;
1413 let Seek::Exact(frame) = reader.seek(FrameIndex(40)) else {
1414 panic!("a cached frame seeks exactly");
1415 };
1416 assert_eq!(value(&frame), 40);
1417 assert_eq!(
1418 reader.statistics().samples_submitted,
1419 submitted,
1420 "an exact seek decodes nothing"
1421 );
1422 }
1423
1424 #[test]
1428 fn a_seek_anywhere_on_a_single_group_track_decodes_nothing() {
1429 let mut reader = single_group_reader(512);
1430 reader.set_seek_previews(Some(Arc::new(StridedPreviews {
1431 stride: 12,
1432 frames: 512,
1433 })));
1434 for target in [0_u64, 1, 255, 400, 511] {
1435 match reader.seek(FrameIndex(target)) {
1436 Seek::Preview { frame, .. } => assert!(
1437 frame.0.abs_diff(target) < 12,
1438 "frame {target} answered by {frame:?}, further than one stride away"
1439 ),
1440 Seek::Exact(_) => {}
1441 Seek::Pending => panic!("frame {target} had no answer"),
1442 }
1443 }
1444 assert_eq!(
1445 reader.statistics().samples_submitted,
1446 0,
1447 "seeking is not decoding"
1448 );
1449 assert_eq!(reader.statistics().resets, 0);
1450 }
1451
1452 #[test]
1456 fn a_seek_to_any_position_answers_inside_the_latency_budget() {
1457 let frames = 768;
1458 let mut reader = single_group_reader(frames);
1459 reader.set_seek_previews(Some(Arc::new(StridedPreviews { stride: 12, frames })));
1460 let mut worst = Duration::ZERO;
1461 for step in 0..=100_u64 {
1462 let target = FrameIndex(step * (frames - 1) / 100);
1463 let started = std::time::Instant::now();
1464 let answer = reader.seek(target);
1465 worst = worst.max(started.elapsed());
1466 assert_ne!(answer, Seek::Pending, "frame {} had no answer", target.0);
1467 }
1468 assert!(
1469 worst < SEEK_LATENCY_BUDGET,
1470 "the worst seek took {worst:?}, over the {SEEK_LATENCY_BUDGET:?} budget"
1471 );
1472 }
1473
1474 #[test]
1477 fn detaching_the_preview_source_leaves_only_the_cache() {
1478 let mut reader = single_group_reader(64);
1479 reader.set_seek_previews(Some(Arc::new(StridedPreviews {
1480 stride: 12,
1481 frames: 64,
1482 })));
1483 assert!(matches!(reader.seek(FrameIndex(63)), Seek::Preview { .. }));
1484 reader.set_seek_previews(None);
1485 assert_eq!(reader.seek(FrameIndex(63)), Seek::Pending);
1486 }
1487
1488 #[test]
1493 fn a_leading_picture_is_decoded_from_the_random_access_point_before_it() {
1494 let samples = vec![
1495 sample(0, 10, true),
1496 sample(1, 11, false),
1497 sample(2, 12, false),
1498 sample(4, 14, true),
1499 sample(3, 13, false),
1500 sample(5, 15, false),
1501 ];
1502 let mut reader = ExactFrameReader::new(
1503 &uncompressed_video_decoder_factory(),
1504 config(),
1505 samples.clone(),
1506 Limits::default(),
1507 )
1508 .unwrap();
1509 let cancellation = CancellationToken::new();
1510 assert_eq!(
1511 value(&reader.get(FrameIndex(3), &cancellation).unwrap()),
1512 13
1513 );
1514 assert_eq!(reader.statistics().samples_submitted, 5);
1515
1516 let mut reader = ExactFrameReader::new(
1517 &uncompressed_video_decoder_factory(),
1518 config(),
1519 samples,
1520 Limits::default(),
1521 )
1522 .unwrap();
1523 assert_eq!(
1524 value(&reader.get(FrameIndex(5), &cancellation).unwrap()),
1525 15
1526 );
1527 assert_eq!(reader.statistics().samples_submitted, 3);
1528 }
1529
1530 #[test]
1531 fn capability_distinguishes_codec_profile_configuration_and_hardware() {
1532 let factory = uncompressed_video_decoder_factory();
1533 assert!(factory.capability(&config()).is_supported());
1534 let mut candidate = config();
1535 candidate.codec = Codec::Av1;
1536 assert_eq!(
1537 factory.capability(&candidate),
1538 CodecSupport::UnsupportedCodec
1539 );
1540 candidate = config();
1541 candidate.profile = CodecProfile::Av1Main;
1542 assert_eq!(
1543 factory.capability(&candidate),
1544 CodecSupport::UnsupportedProfile
1545 );
1546 candidate = config();
1547 candidate.output_format = PixelFormat::Rgba8;
1548 assert!(matches!(
1549 factory.capability(&candidate),
1550 CodecSupport::InvalidConfiguration { .. }
1551 ));
1552 candidate = config();
1553 candidate.hardware = HardwarePreference::Require;
1554 assert_eq!(
1555 factory.capability(&candidate),
1556 CodecSupport::HardwareUnavailable
1557 );
1558
1559 candidate = config();
1560 candidate.output_format = PixelFormat::Rgba8;
1561 assert_eq!(
1562 factory
1563 .create(&candidate, &Limits::default())
1564 .err()
1565 .unwrap()
1566 .kind(),
1567 ErrorKind::InvalidInput
1568 );
1569
1570 let restrictive = Limits {
1571 max_width: 0,
1572 ..Limits::default()
1573 };
1574 assert_eq!(
1575 factory
1576 .create(&config(), &restrictive)
1577 .err()
1578 .unwrap()
1579 .kind(),
1580 ErrorKind::ResourceLimit
1581 );
1582 }
1583
1584 #[test]
1588 fn a_request_before_the_open_session_start_resets_the_decoder() {
1589 let samples = (0..4)
1590 .map(|index| sample(index, index as u8 + 10, true))
1591 .collect();
1592 let mut reader = ExactFrameReader::new(
1593 &uncompressed_video_decoder_factory(),
1594 config(),
1595 samples,
1596 Limits {
1597 max_cached_frames: 1,
1598 ..Limits::default()
1599 },
1600 )
1601 .unwrap();
1602 let cancellation = CancellationToken::new();
1603 assert_eq!(
1604 value(&reader.get(FrameIndex(2), &cancellation).unwrap()),
1605 12
1606 );
1607 assert_eq!(
1608 value(&reader.get(FrameIndex(0), &cancellation).unwrap()),
1609 10
1610 );
1611 assert_eq!(reader.statistics().resets, 2);
1612 }
1613
1614 #[test]
1615 fn conformance_vector_reorders_exact_frames_and_reuses_bounded_state() {
1616 let samples = vec![
1617 sample(0, 10, true),
1618 sample(3, 40, false),
1619 sample(1, 20, false),
1620 sample(2, 30, false),
1621 sample(4, 50, true),
1622 sample(6, 70, false),
1623 sample(5, 60, false),
1624 ];
1625 let factory = uncompressed_video_decoder_factory();
1626 let mut reader = ExactFrameReader::new(
1627 &factory,
1628 config(),
1629 samples,
1630 Limits {
1631 max_cached_frames: 3,
1632 ..Limits::default()
1633 },
1634 )
1635 .unwrap();
1636 let cancellation = CancellationToken::new();
1637 assert_eq!(
1638 value(&reader.get(FrameIndex(1), &cancellation).unwrap()),
1639 20
1640 );
1641 let first = reader.statistics();
1642 assert_eq!(
1643 value(&reader.get(FrameIndex(2), &cancellation).unwrap()),
1644 30
1645 );
1646 assert_eq!(reader.statistics().resets, first.resets);
1647 assert_eq!(
1648 value(&reader.get(FrameIndex(3), &cancellation).unwrap()),
1649 40
1650 );
1651 assert!(reader.statistics().cache_hits > 0);
1652 assert_eq!(
1653 value(&reader.get(FrameIndex(5), &cancellation).unwrap()),
1654 60
1655 );
1656 assert_eq!(
1657 value(&reader.get(FrameIndex(0), &cancellation).unwrap()),
1658 10
1659 );
1660 assert!(reader.statistics().resets > first.resets);
1661 assert!(reader.cached_frames() <= 3);
1662 }
1663
1664 struct HintFactory {
1667 wanted: Arc<Mutex<Vec<(u64, bool)>>>,
1668 }
1669
1670 struct HintDecoder {
1671 configuration: VideoDecoderConfig,
1672 limits: Limits,
1673 wanted: Arc<Mutex<Vec<(u64, bool)>>>,
1674 output_wanted: bool,
1675 }
1676
1677 impl VideoDecoderFactory for HintFactory {
1678 fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
1679 CodecSupport::Supported {
1680 implementation: CodecImplementation::Software,
1681 }
1682 }
1683
1684 fn create(
1685 &self,
1686 configuration: &VideoDecoderConfig,
1687 limits: &Limits,
1688 ) -> Result<Box<dyn VideoDecoder>> {
1689 Ok(Box::new(HintDecoder {
1690 configuration: configuration.clone(),
1691 limits: *limits,
1692 wanted: Arc::clone(&self.wanted),
1693 output_wanted: true,
1694 }))
1695 }
1696 }
1697
1698 impl VideoDecoder for HintDecoder {
1699 fn submit(
1700 &mut self,
1701 sample: &EncodedVideoSample,
1702 cancellation: &CancellationToken,
1703 ) -> Result<Vec<DecodedVideoFrame>> {
1704 cancellation.check()?;
1705 self.wanted
1706 .lock()
1707 .expect("hint log poisoned")
1708 .push((sample.presentation_index.0, self.output_wanted));
1709 if !self.output_wanted {
1710 return Ok(Vec::new());
1711 }
1712 Ok(vec![DecodedVideoFrame {
1713 presentation_index: sample.presentation_index,
1714 frame: VideoFrame::new(
1715 self.configuration.coded_dimensions,
1716 PixelFormat::Gray8,
1717 ColorRange::Full,
1718 vec![Plane {
1719 data: sample.data.clone(),
1720 stride: 1,
1721 }],
1722 &self.limits,
1723 )?,
1724 }])
1725 }
1726
1727 fn drain(&mut self, _: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
1728 Ok(Vec::new())
1729 }
1730
1731 fn reset(&mut self) -> Result<()> {
1732 Ok(())
1733 }
1734
1735 fn set_output_wanted(&mut self, wanted: bool) {
1736 self.output_wanted = wanted;
1737 }
1738 }
1739
1740 struct ReplayFactory;
1745
1746 struct ReplayDecoder {
1747 configuration: VideoDecoderConfig,
1748 limits: Limits,
1749 previous: Option<(FrameIndex, u8)>,
1750 }
1751
1752 impl ReplayDecoder {
1753 fn produce(&self, presentation_index: FrameIndex, value: u8) -> Result<DecodedVideoFrame> {
1754 Ok(DecodedVideoFrame {
1755 presentation_index,
1756 frame: VideoFrame::new(
1757 self.configuration.coded_dimensions,
1758 PixelFormat::Gray8,
1759 ColorRange::Full,
1760 vec![Plane {
1761 data: vec![value],
1762 stride: 1,
1763 }],
1764 &self.limits,
1765 )?,
1766 })
1767 }
1768 }
1769
1770 impl VideoDecoderFactory for ReplayFactory {
1771 fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
1772 CodecSupport::Supported {
1773 implementation: CodecImplementation::Software,
1774 }
1775 }
1776
1777 fn create(
1778 &self,
1779 configuration: &VideoDecoderConfig,
1780 limits: &Limits,
1781 ) -> Result<Box<dyn VideoDecoder>> {
1782 Ok(Box::new(ReplayDecoder {
1783 configuration: configuration.clone(),
1784 limits: *limits,
1785 previous: None,
1786 }))
1787 }
1788 }
1789
1790 impl VideoDecoder for ReplayDecoder {
1791 fn submit(
1792 &mut self,
1793 sample: &EncodedVideoSample,
1794 cancellation: &CancellationToken,
1795 ) -> Result<Vec<DecodedVideoFrame>> {
1796 cancellation.check()?;
1797 let value = sample.data[0];
1798 let mut outputs = Vec::new();
1799 if let Some((index, previous)) = self.previous {
1800 outputs.push(self.produce(index, previous)?);
1801 }
1802 outputs.push(self.produce(sample.presentation_index, value)?);
1803 self.previous = Some((sample.presentation_index, value));
1804 Ok(outputs)
1805 }
1806
1807 fn drain(&mut self, _: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
1808 Ok(Vec::new())
1809 }
1810
1811 fn reset(&mut self) -> Result<()> {
1812 self.previous = None;
1813 Ok(())
1814 }
1815 }
1816
1817 #[test]
1821 fn a_frame_the_decoder_emits_twice_is_cached_again_rather_than_refused() {
1822 let mut reader = ExactFrameReader::new(
1823 &ReplayFactory,
1824 config(),
1825 single_group_of_pictures(),
1826 Limits::default(),
1827 )
1828 .unwrap();
1829 let cancellation = CancellationToken::new();
1830
1831 assert_eq!(
1834 value(&reader.get(FrameIndex(3), &cancellation).unwrap()),
1835 30
1836 );
1837 assert_eq!(
1838 value(&reader.get(FrameIndex(6), &cancellation).unwrap()),
1839 60
1840 );
1841
1842 let resets = reader.statistics().resets;
1845 let hits = reader.statistics().cache_hits;
1846 assert_eq!(
1847 value(&reader.get(FrameIndex(5), &cancellation).unwrap()),
1848 50
1849 );
1850 assert_eq!(reader.statistics().resets, resets);
1851 assert!(reader.statistics().cache_hits > hits);
1852 }
1853
1854 fn single_group_of_pictures() -> Vec<EncodedVideoSample> {
1857 (0..10)
1858 .map(|index| sample(index, (index * 10) as u8, index == 0))
1859 .collect()
1860 }
1861
1862 fn small_cache() -> Limits {
1865 Limits {
1866 max_cached_frames: 2,
1867 ..Limits::default()
1868 }
1869 }
1870
1871 #[test]
1872 fn walking_to_a_distant_frame_does_not_ask_for_the_pictures_it_passes() {
1873 let log = Arc::new(Mutex::new(Vec::new()));
1874 let factory = HintFactory {
1875 wanted: Arc::clone(&log),
1876 };
1877 let mut reader = ExactFrameReader::new(
1878 &factory,
1879 config(),
1880 single_group_of_pictures(),
1881 small_cache(),
1882 )
1883 .unwrap();
1884 let cancellation = CancellationToken::new();
1885
1886 assert_eq!(
1887 value(&reader.get(FrameIndex(8), &cancellation).unwrap()),
1888 80
1889 );
1890 assert_eq!(
1891 *log.lock().unwrap(),
1892 vec![
1893 (0, false),
1894 (1, false),
1895 (2, false),
1896 (3, false),
1897 (4, false),
1898 (5, false),
1899 (6, true),
1900 (7, true),
1901 (8, true),
1902 ],
1903 "only the target and the tail the cache can hold are produced"
1904 );
1905 let statistics = reader.statistics();
1906 assert_eq!(statistics.samples_submitted, 9);
1907 assert_eq!(statistics.samples_skipped, 6);
1908 assert_eq!(statistics.resets, 1, "the walk itself is one decode");
1909 }
1910
1911 #[test]
1912 fn a_frame_the_walk_went_past_is_decoded_again_rather_than_reported_missing() {
1913 let log = Arc::new(Mutex::new(Vec::new()));
1914 let factory = HintFactory {
1915 wanted: Arc::clone(&log),
1916 };
1917 let mut reader = ExactFrameReader::new(
1918 &factory,
1919 config(),
1920 single_group_of_pictures(),
1921 small_cache(),
1922 )
1923 .unwrap();
1924 let cancellation = CancellationToken::new();
1925 reader.get(FrameIndex(8), &cancellation).unwrap();
1926 let resets = reader.statistics().resets;
1927
1928 assert_eq!(
1932 value(&reader.get(FrameIndex(4), &cancellation).unwrap()),
1933 40
1934 );
1935 assert_eq!(reader.statistics().resets, resets + 1);
1936 assert_eq!(
1938 value(&reader.get(FrameIndex(4), &cancellation).unwrap()),
1939 40
1940 );
1941 assert_eq!(reader.statistics().resets, resets + 1);
1942 }
1943
1944 #[test]
1945 fn a_reordered_frame_at_or_past_the_target_is_kept_for_the_request_that_follows() {
1946 let samples = vec![
1950 sample(0, 0, true),
1951 sample(4, 40, false),
1952 sample(2, 20, false),
1953 sample(1, 10, false),
1954 sample(3, 30, false),
1955 sample(8, 80, false),
1956 sample(6, 60, false),
1957 sample(5, 50, false),
1958 sample(7, 70, false),
1959 ];
1960 let log = Arc::new(Mutex::new(Vec::new()));
1961 let factory = HintFactory {
1962 wanted: Arc::clone(&log),
1963 };
1964 let mut reader = ExactFrameReader::new(&factory, config(), samples, small_cache()).unwrap();
1965 let cancellation = CancellationToken::new();
1966
1967 assert_eq!(
1968 value(&reader.get(FrameIndex(4), &cancellation).unwrap()),
1969 40
1970 );
1971 let resets = reader.statistics().resets;
1972 for (index, expected) in [(1_u64, 10_u8), (2, 20), (3, 30)] {
1973 assert_eq!(
1974 value(&reader.get(FrameIndex(index), &cancellation).unwrap()),
1975 expected,
1976 "frame {index} is still available"
1977 );
1978 }
1979 assert_eq!(
1980 reader.statistics().resets,
1981 resets,
1982 "a frame after the target in decode order is not skipped"
1983 );
1984 assert_eq!(
1985 reader.statistics().samples_skipped,
1986 1,
1987 "only frame 0, the random-access point the walk starts from, is behind frame 4"
1988 );
1989 }
1990
1991 #[test]
1992 fn a_walk_leaves_the_frames_behind_its_target_cached_so_stepping_back_is_free() {
1993 let log = Arc::new(Mutex::new(Vec::new()));
1997 let factory = HintFactory {
1998 wanted: Arc::clone(&log),
1999 };
2000 let samples: Vec<_> = (0..40)
2001 .map(|index| sample(index, index as u8, index == 0))
2002 .collect();
2003 let mut reader = ExactFrameReader::new(
2004 &factory,
2005 config(),
2006 samples,
2007 Limits {
2008 max_cached_frames: 4,
2009 ..Limits::default()
2010 },
2011 )
2012 .unwrap();
2013 let cancellation = CancellationToken::new();
2014 reader.get(FrameIndex(32), &cancellation).unwrap();
2015 let after_walk = reader.statistics();
2016 assert_eq!(after_walk.samples_skipped, 28, "frames 0 to 27 are skipped");
2017
2018 for index in [31_u64, 30, 29] {
2019 assert_eq!(
2020 value(&reader.get(FrameIndex(index), &cancellation).unwrap()),
2021 index as u8
2022 );
2023 }
2024 assert_eq!(
2025 reader.statistics().resets,
2026 after_walk.resets,
2027 "the tail the walk kept is in the cache, so stepping back decodes nothing"
2028 );
2029 assert_eq!(
2030 reader.statistics().samples_submitted,
2031 after_walk.samples_submitted
2032 );
2033 }
2034
2035 #[test]
2036 fn a_step_converts_its_own_picture_and_no_tail_behind_it() {
2037 let log = Arc::new(Mutex::new(Vec::new()));
2042 let factory = HintFactory {
2043 wanted: Arc::clone(&log),
2044 };
2045 let samples: Vec<_> = (0..40)
2046 .map(|index| sample(index, index as u8, index == 0))
2047 .collect();
2048 let mut reader = ExactFrameReader::new(
2049 &factory,
2050 config(),
2051 samples,
2052 Limits {
2053 max_cached_frames: 4,
2054 ..Limits::default()
2055 },
2056 )
2057 .unwrap();
2058 let cancellation = CancellationToken::new();
2059
2060 assert_eq!(
2061 value(&reader.get_step(FrameIndex(32), &cancellation).unwrap()),
2062 32
2063 );
2064 let after_step = reader.statistics();
2065 assert_eq!(
2066 after_step.samples_skipped, 32,
2067 "frames 0 to 31 are all passed through, tail included"
2068 );
2069 assert_eq!(
2070 reader.cached_frames(),
2071 1,
2072 "only the picture the step asked for was converted"
2073 );
2074 }
2075
2076 #[test]
2077 fn a_walk_of_steps_converts_what_it_asks_for_rather_than_what_it_passes() {
2078 let log = Arc::new(Mutex::new(Vec::new()));
2083 let factory = HintFactory {
2084 wanted: Arc::clone(&log),
2085 };
2086 let samples: Vec<_> = (0..64)
2087 .map(|index| sample(index, index as u8, index == 0))
2088 .collect();
2089 let mut reader = ExactFrameReader::new(
2090 &factory,
2091 config(),
2092 samples,
2093 Limits {
2094 max_cached_frames: 8,
2095 ..Limits::default()
2096 },
2097 )
2098 .unwrap();
2099 let cancellation = CancellationToken::new();
2100
2101 let steps: Vec<u64> = (4..60).step_by(4).collect();
2103 for step in &steps {
2104 reader.get_step(FrameIndex(*step), &cancellation).unwrap();
2105 }
2106 let converted = reader.statistics().samples_submitted - reader.statistics().samples_skipped;
2107 assert_eq!(
2108 converted,
2109 steps.len() as u64,
2110 "one conversion per published step, not one per frame passed"
2111 );
2112 assert_eq!(
2113 reader.statistics().resets,
2114 1,
2115 "only the cold start resets; a forward walk of steps never starts over again"
2116 );
2117 }
2118
2119 #[test]
2120 fn a_step_walk_that_ends_in_a_destination_still_leaves_a_cache_tail_to_step_back_through() {
2121 let log = Arc::new(Mutex::new(Vec::new()));
2125 let factory = HintFactory {
2126 wanted: Arc::clone(&log),
2127 };
2128 let samples: Vec<_> = (0..40)
2129 .map(|index| sample(index, index as u8, index == 0))
2130 .collect();
2131 let mut reader = ExactFrameReader::new(
2132 &factory,
2133 config(),
2134 samples,
2135 Limits {
2136 max_cached_frames: 4,
2137 ..Limits::default()
2138 },
2139 )
2140 .unwrap();
2141 let cancellation = CancellationToken::new();
2142
2143 for step in [8_u64, 16, 24] {
2144 reader.get_step(FrameIndex(step), &cancellation).unwrap();
2145 }
2146 reader.get(FrameIndex(32), &cancellation).unwrap();
2147 let after_walk = reader.statistics();
2148
2149 for index in [31_u64, 30, 29] {
2150 assert_eq!(
2151 value(&reader.get(FrameIndex(index), &cancellation).unwrap()),
2152 index as u8
2153 );
2154 }
2155 assert_eq!(
2156 reader.statistics().resets,
2157 after_walk.resets,
2158 "the destination kept its tail, so stepping back decodes nothing"
2159 );
2160 assert_eq!(
2161 reader.statistics().samples_submitted,
2162 after_walk.samples_submitted
2163 );
2164 }
2165
2166 struct LateFactory;
2169
2170 struct LateDecoder {
2171 configuration: VideoDecoderConfig,
2172 limits: Limits,
2173 held: Option<EncodedVideoSample>,
2174 output_wanted: bool,
2175 }
2176
2177 impl VideoDecoderFactory for LateFactory {
2178 fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
2179 CodecSupport::Supported {
2180 implementation: CodecImplementation::Software,
2181 }
2182 }
2183
2184 fn create(
2185 &self,
2186 configuration: &VideoDecoderConfig,
2187 limits: &Limits,
2188 ) -> Result<Box<dyn VideoDecoder>> {
2189 Ok(Box::new(LateDecoder {
2190 configuration: configuration.clone(),
2191 limits: *limits,
2192 held: None,
2193 output_wanted: true,
2194 }))
2195 }
2196 }
2197
2198 impl LateDecoder {
2199 fn release(&self, sample: EncodedVideoSample) -> Result<Vec<DecodedVideoFrame>> {
2200 if !self.output_wanted {
2201 return Ok(Vec::new());
2202 }
2203 Ok(vec![DecodedVideoFrame {
2204 presentation_index: sample.presentation_index,
2205 frame: VideoFrame::new(
2206 self.configuration.coded_dimensions,
2207 PixelFormat::Gray8,
2208 ColorRange::Full,
2209 vec![Plane {
2210 data: sample.data,
2211 stride: 1,
2212 }],
2213 &self.limits,
2214 )?,
2215 }])
2216 }
2217 }
2218
2219 impl VideoDecoder for LateDecoder {
2220 fn submit(
2221 &mut self,
2222 sample: &EncodedVideoSample,
2223 cancellation: &CancellationToken,
2224 ) -> Result<Vec<DecodedVideoFrame>> {
2225 cancellation.check()?;
2226 match self.held.replace(sample.clone()) {
2227 Some(previous) => self.release(previous),
2228 None => Ok(Vec::new()),
2229 }
2230 }
2231
2232 fn drain(&mut self, _: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
2233 match self.held.take() {
2234 Some(held) => self.release(held),
2235 None => Ok(Vec::new()),
2236 }
2237 }
2238
2239 fn reset(&mut self) -> Result<()> {
2240 self.held = None;
2241 Ok(())
2242 }
2243
2244 fn set_output_wanted(&mut self, wanted: bool) {
2245 self.output_wanted = wanted;
2246 }
2247 }
2248
2249 #[test]
2250 fn a_frame_still_inside_a_reordering_decoder_when_output_stops_is_written_off_too() {
2251 let mut reader = ExactFrameReader::new(
2256 &LateFactory,
2257 config(),
2258 single_group_of_pictures(),
2259 small_cache(),
2260 )
2261 .unwrap();
2262 let cancellation = CancellationToken::new();
2263
2264 assert_eq!(
2268 value(&reader.get(FrameIndex(4), &cancellation).unwrap()),
2269 40
2270 );
2271 assert_eq!(
2272 value(&reader.get(FrameIndex(9), &cancellation).unwrap()),
2273 90
2274 );
2275 assert_eq!(
2276 value(&reader.get(FrameIndex(5), &cancellation).unwrap()),
2277 50,
2278 "the frame that was dropped in flight is decoded again, not reported missing"
2279 );
2280 }
2281
2282 #[test]
2283 fn a_decoder_that_ignores_the_hint_still_answers_every_frame() {
2284 let factory = uncompressed_video_decoder_factory();
2287 let mut reader = ExactFrameReader::new(
2288 &factory,
2289 config(),
2290 single_group_of_pictures(),
2291 small_cache(),
2292 )
2293 .unwrap();
2294 let cancellation = CancellationToken::new();
2295 reader.get(FrameIndex(8), &cancellation).unwrap();
2296 assert_eq!(reader.statistics().samples_skipped, 6);
2297 for index in 0..9_u64 {
2298 assert_eq!(
2299 value(&reader.get(FrameIndex(index), &cancellation).unwrap()),
2300 (index * 10) as u8,
2301 "frame {index} came back from the decoder that ignored the hint"
2302 );
2303 }
2304 }
2305
2306 #[test]
2307 fn malformed_packets_and_cancellation_are_reported() {
2308 let factory = uncompressed_video_decoder_factory();
2309 let mut reader = ExactFrameReader::new(
2310 &factory,
2311 config(),
2312 vec![EncodedVideoSample {
2313 presentation_index: FrameIndex(0),
2314 random_access: true,
2315 data: Vec::new(),
2316 }],
2317 Limits::default(),
2318 )
2319 .unwrap();
2320 assert_eq!(
2321 reader
2322 .get(FrameIndex(0), &CancellationToken::new())
2323 .unwrap_err()
2324 .kind(),
2325 ErrorKind::MalformedMedia
2326 );
2327 let canceled = CancellationToken::new();
2328 canceled.cancel();
2329 assert_eq!(
2330 reader.get(FrameIndex(0), &canceled).unwrap_err().kind(),
2331 ErrorKind::Canceled
2332 );
2333 }
2334
2335 #[test]
2336 fn random_access_decode_work_obeys_the_configured_bound() {
2337 let factory = uncompressed_video_decoder_factory();
2338 let mut reader = ExactFrameReader::new(
2339 &factory,
2340 config(),
2341 vec![sample(0, 1, true), sample(1, 2, false), sample(2, 3, false)],
2342 Limits {
2343 max_decode_samples_per_seek: 2,
2344 ..Limits::default()
2345 },
2346 )
2347 .unwrap();
2348 let error = reader
2349 .get(FrameIndex(2), &CancellationToken::new())
2350 .unwrap_err();
2351 assert_eq!(error.kind(), ErrorKind::ResourceLimit);
2352 assert_eq!(reader.statistics().samples_submitted, 2);
2353 }
2354
2355 struct DelayedFactory;
2356 impl VideoDecoderFactory for DelayedFactory {
2357 fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
2358 CodecSupport::Supported {
2359 implementation: CodecImplementation::Software,
2360 }
2361 }
2362 fn create(
2363 &self,
2364 configuration: &VideoDecoderConfig,
2365 limits: &Limits,
2366 ) -> Result<Box<dyn VideoDecoder>> {
2367 Ok(Box::new(DelayedDecoder {
2368 configuration: configuration.clone(),
2369 limits: *limits,
2370 delayed: None,
2371 }))
2372 }
2373 }
2374 struct DelayedDecoder {
2375 configuration: VideoDecoderConfig,
2376 limits: Limits,
2377 delayed: Option<EncodedVideoSample>,
2378 }
2379 impl DelayedDecoder {
2380 fn decode(&self, sample: EncodedVideoSample) -> Result<DecodedVideoFrame> {
2381 Ok(DecodedVideoFrame {
2382 presentation_index: sample.presentation_index,
2383 frame: VideoFrame::new(
2384 self.configuration.coded_dimensions,
2385 PixelFormat::Gray8,
2386 ColorRange::Full,
2387 vec![Plane {
2388 data: sample.data,
2389 stride: 1,
2390 }],
2391 &self.limits,
2392 )?,
2393 })
2394 }
2395 }
2396 impl VideoDecoder for DelayedDecoder {
2397 fn submit(
2398 &mut self,
2399 sample: &EncodedVideoSample,
2400 cancellation: &CancellationToken,
2401 ) -> Result<Vec<DecodedVideoFrame>> {
2402 cancellation.check()?;
2403 let previous = self.delayed.replace(sample.clone());
2404 previous
2405 .map(|sample| self.decode(sample).map(|frame| vec![frame]))
2406 .unwrap_or(Ok(Vec::new()))
2407 }
2408 fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
2409 cancellation.check()?;
2410 self.delayed
2411 .take()
2412 .map(|sample| self.decode(sample).map(|frame| vec![frame]))
2413 .unwrap_or(Ok(Vec::new()))
2414 }
2415 fn reset(&mut self) -> Result<()> {
2416 self.delayed = None;
2417 Ok(())
2418 }
2419 }
2420
2421 #[test]
2422 fn delayed_output_drains_and_reset_clears_state() {
2423 let mut reader = ExactFrameReader::new(
2424 &DelayedFactory,
2425 config(),
2426 vec![sample(0, 11, true), sample(1, 22, false)],
2427 Limits::default(),
2428 )
2429 .unwrap();
2430 let cancellation = CancellationToken::new();
2431 assert_eq!(
2432 value(&reader.get(FrameIndex(1), &cancellation).unwrap()),
2433 22
2434 );
2435 assert_eq!(reader.statistics().drains, 1);
2436 reader.reset().unwrap();
2437 assert_eq!(reader.cached_frames(), 0);
2438 assert_eq!(
2439 value(&reader.get(FrameIndex(0), &cancellation).unwrap()),
2440 11
2441 );
2442 }
2443
2444 #[test]
2445 fn sequential_playback_through_a_pipelined_decoder_does_not_reset_every_frame() {
2446 let mut reader = ExactFrameReader::new(
2452 &DelayedFactory,
2453 config(),
2454 vec![
2455 sample(0, 11, true),
2456 sample(1, 22, false),
2457 sample(2, 33, false),
2458 sample(3, 44, false),
2459 sample(4, 55, false),
2460 ],
2461 Limits::default(),
2462 )
2463 .unwrap();
2464 let cancellation = CancellationToken::new();
2465
2466 assert_eq!(
2467 value(&reader.get(FrameIndex(0), &cancellation).unwrap()),
2468 11
2469 );
2470 assert_eq!(reader.statistics().resets, 1);
2471
2472 for (index, expected) in [(1, 22_u8), (2, 33), (3, 44), (4, 55)] {
2473 let frame = reader.get(FrameIndex(index), &cancellation).unwrap();
2474 assert_eq!(value(&frame), expected);
2475 assert_eq!(
2476 reader.statistics().resets,
2477 1,
2478 "sequential forward playback must not reset once decoding has started"
2479 );
2480 }
2481 assert_eq!(reader.statistics().samples_submitted, 5);
2482 assert_eq!(reader.statistics().drains, 1);
2483 }
2484
2485 struct MalformedOutputFactory;
2486
2487 impl VideoDecoderFactory for MalformedOutputFactory {
2488 fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
2489 CodecSupport::Supported {
2490 implementation: CodecImplementation::Software,
2491 }
2492 }
2493
2494 fn create(
2495 &self,
2496 configuration: &VideoDecoderConfig,
2497 limits: &Limits,
2498 ) -> Result<Box<dyn VideoDecoder>> {
2499 let factory = UncompressedVideoDecoderFactory;
2500 factory.create(configuration, limits).map(|decoder| {
2501 Box::new(MalformedOutputDecoder {
2502 decoder,
2503 previous: None,
2504 }) as Box<dyn VideoDecoder>
2505 })
2506 }
2507 }
2508
2509 struct MalformedOutputDecoder {
2510 decoder: Box<dyn VideoDecoder>,
2511 previous: Option<FrameIndex>,
2512 }
2513
2514 impl VideoDecoder for MalformedOutputDecoder {
2515 fn submit(
2516 &mut self,
2517 sample: &EncodedVideoSample,
2518 cancellation: &CancellationToken,
2519 ) -> Result<Vec<DecodedVideoFrame>> {
2520 let mut output = self.decoder.submit(sample, cancellation)?;
2521 if let (Some(previous), Some(frame)) = (self.previous, output.first_mut()) {
2522 frame.presentation_index = previous;
2523 }
2524 self.previous = Some(sample.presentation_index);
2525 Ok(output)
2526 }
2527
2528 fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
2529 self.decoder.drain(cancellation)
2530 }
2531
2532 fn reset(&mut self) -> Result<()> {
2533 self.previous = None;
2534 self.decoder.reset()
2535 }
2536 }
2537
2538 #[test]
2539 fn malformed_backend_output_is_rejected() {
2540 let mut reader = ExactFrameReader::new(
2541 &MalformedOutputFactory,
2542 config(),
2543 vec![sample(0, 1, true), sample(1, 2, false)],
2544 Limits::default(),
2545 )
2546 .unwrap();
2547 let error = reader
2548 .get(FrameIndex(1), &CancellationToken::new())
2549 .unwrap_err();
2550 assert_eq!(error.kind(), ErrorKind::MalformedMedia);
2551 }
2552}