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