programmatic video rendering framework that is actually fast
fix(media): loop MKV and WebM clips using the container duration
heojunfob6ffb97cb20b
diff --git a/fframes-media/src/video_decoder.rs b/fframes-media/src/video_decoder.rsindex 81c0d732..7d280ac2 100644--- a/fframes-media/src/video_decoder.rs+++ b/fframes-media/src/video_decoder.rs@@ -12,6 +12,17 @@ use std::ptr;use std::sync::Arc;use usvgr::PreloadedImageData;+/// The video stream's duration in its own time base. Matroska and `WebM` leave the stream+/// duration unset (`AV_NOPTS_VALUE`) and only carry the container's, so fall back to that.+unsafe fn stream_duration(fmt_ctx: *mut AVFormatContext, stream: *mut AVStream) -> i64 {+ unsafe {+ if (*stream).duration != AV_NOPTS_VALUE || (*fmt_ctx).duration == AV_NOPTS_VALUE {+ return (*stream).duration;+ }+ av_rescale_q((*fmt_ctx).duration, AV_TIME_BASE_Q, (*stream).time_base)+ }+}+const FFRAMES_VIDEO_PATH_TAG: &str = "___fframes_internal_video_frame_pts___";// just a little bit faster than the format! macropub fn encode_video_resource(resource: &str, pts: i64) -> String {@@ -736,7 +747,7 @@ impl FFmpegDecoder {color_space: (*video_dec_ctx).colorspace,color_range: (*video_dec_ctx).color_range,time_base: (*stream).time_base,- duration: (*stream).duration,+ duration: stream_duration(fmt_ctx, stream),frame_rate: (*stream).r_frame_rate,})}diff --git a/fframes-media/tests/video_decoder_looping.rs b/fframes-media/tests/video_decoder_looping.rsnew file mode 100644index 00000000..16eb9aa7--- /dev/null+++ b/fframes-media/tests/video_decoder_looping.rs@@ -0,0 +1,98 @@+#![cfg(not(target_arch = "wasm32"))]++use std::path::PathBuf;+use std::process::Command;++use fframes_media::FFmpegDecoder;++const FPS: usize = 30;+const FRAME_COUNT: i64 = 90;++struct VideoFixture(PathBuf);++impl VideoFixture {+ // Requires the ffmpeg CLI with libx264, like the end-to-end render tests.+ fn new(extension: &str) -> Self {+ let dir = std::env::temp_dir().join(format!(+ "fframes-decoder-looping-{}-{extension}",+ std::process::id()+ ));+ std::fs::create_dir_all(&dir).unwrap();+ let fixture = Self(dir.join(format!("video.{extension}")));+ let output = Command::new("ffmpeg")+ .args([+ "-hide_banner",+ "-loglevel",+ "error",+ "-y",+ "-f",+ "lavfi",+ "-i",+ "testsrc2=size=32x32:rate=30",+ "-frames:v",+ &FRAME_COUNT.to_string(),+ "-c:v",+ "libx264",+ "-pix_fmt",+ "yuv420p",+ "-g",+ "30",+ "-an",+ ])+ .arg(&fixture.0)+ .output()+ .expect("ffmpeg with libx264 is required for video decoder tests");+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ fixture+ }+}++impl Drop for VideoFixture {+ fn drop(&mut self) {+ if let Some(dir) = self.0.parent() {+ let _ = std::fs::remove_dir_all(dir);+ }+ }+}++fn assert_loops(extension: &str) {+ let video = VideoFixture::new(extension);+ let mut decoder = unsafe { FFmpegDecoder::new(&video.0, FPS, 1) }.unwrap();+ let seconds = unsafe { decoder.get_raw_frame().get_stream_duration_in_frames() };+ assert!(+ (seconds - FRAME_COUNT as f32 / FPS as f32).abs() < 0.05,+ "{extension}: stream duration {seconds}s"+ );++ for index in 0..FRAME_COUNT * 2 + 5 {+ unsafe {+ let offset = decoder.adjust_offset_for_looping(index).unwrap();+ assert_eq!(offset, index % FRAME_COUNT, "{extension}: request {index}");+ assert!(+ decoder.decode_up_to(offset).unwrap(),+ "{extension}: missing frame {index}"+ );+ // Matroska stores milliseconds, so frame 7 sits at 0.233s: compare to the nearest frame.+ let shown = decoder.get_raw_frame().timestamp_seconds() * FPS as f32;+ assert!(+ (shown - offset as f32).abs() < 0.5,+ "{extension}: request {index} showed frame {shown}"+ );+ }+ }+}++#[test]+fn mp4_clips_loop_back_to_the_start() {+ assert_loops("mp4");+}++// Matroska (and WebM) leave the video stream's duration unset; the container carries it.+#[test]+fn mkv_clips_loop_back_to_the_start() {+ assert_loops("mkv");+}