Skip to content

programmatic video rendering framework that is actually fast

fix(media): keep showing the last video frame until the stream ends (#172)

Janek Mannbae393f6192e
diff --git a/fframes-media/src/video_decoder.rs b/fframes-media/src/video_decoder.rs
index 71e99a4f..0dd78b48 100644
--- a/fframes-media/src/video_decoder.rs
+++ b/fframes-media/src/video_decoder.rs
@@ -183,6 +183,9 @@ impl SwsScaler {
pub struct FFmpegDecoder {
pub current_loop: i64,
hw_frame: *mut AVFrame,
+ /// Frames are received here and moved into the target frame, so the newest decoded frame
+ /// survives `avcodec_receive_frame` returning EOF (which unrefs the frame it is given).
+ recv_frame: *mut AVFrame,
frame_buf: Arc<FFmpegFrameBuf>,
fmt_ctx: *mut AVFormatContext,
video_stream_info: VideoStreamInfo,
@@ -193,6 +196,8 @@ pub struct FFmpegDecoder {
last_offset: Option<i64>,
/// A null packet has been sent; receive delayed frames until decoder EOF.
draining: bool,
+ /// The target frame holds a frame decoded since the last seek.
+ has_decoded_frame: bool,
}
unsafe impl Send for FFmpegDecoder {}
@@ -521,6 +526,12 @@ impl FFmpegDecoder {
ptr::null_mut()
};
+ let recv_frame = av_frame_alloc();
+ if recv_frame.is_null() {
+ avformat_close_input(&raw mut fmt_ctx);
+ return Err(FFramesMediaError::LibAVAllocationError("av_frame"));
+ }
+
let custom_time_base = AVRational {
num: 1,
den: target_fps as i32,
@@ -536,6 +547,7 @@ impl FFmpegDecoder {
pkt,
fmt_ctx,
hw_frame,
+ recv_frame,
frame_buf: Arc::new(FFmpegFrameBuf::new(
filename.to_string_lossy().to_string(),
video_stream_info,
@@ -547,6 +559,7 @@ impl FFmpegDecoder {
current_loop: 0,
last_offset: None,
draining: false,
+ has_decoded_frame: false,
})
}
}
@@ -649,6 +662,7 @@ impl FFmpegDecoder {
(*self.frame_buf.latest_av_frame).pts = -1;
avcodec_flush_buffers(self.video_stream_info.codec_ctx);
self.draining = false;
+ self.has_decoded_frame = false;
av_packet_unref(self.pkt);
Ok(())
@@ -753,16 +767,29 @@ impl FFmpegDecoder {
loop {
// A previous call may have returned with more decoded frames queued.
// Consume them before sending another packet (which could return EAGAIN).
- let ret = avcodec_receive_frame(self.video_stream_info.codec_ctx, target_frame);
+ let ret = avcodec_receive_frame(self.video_stream_info.codec_ctx, self.recv_frame);
match ret {
0 => {
+ av_frame_unref(target_frame);
+ av_frame_move_ref(target_frame, self.recv_frame);
+ self.has_decoded_frame = true;
if (*target_frame).pts >= target_pts {
self.transfer_hardware_surface_data(target_frame)?;
return Ok(true);
}
continue;
}
- AVERROR_EOF => return Ok(false),
+ AVERROR_EOF => {
+ // The target lies after the last frame's timestamp but before the end of
+ // the stream (e.g. a 24 fps clip sampled at 30 fps): the last frame is
+ // still the one on screen, so return it instead of reporting the end.
+ let shows_last_frame =
+ self.has_decoded_frame && offset < self.duration_in_frames;
+ if shows_last_frame {
+ self.transfer_hardware_surface_data(target_frame)?;
+ }
+ return Ok(shows_last_frame);
+ }
val if val == AVERROR(EAGAIN) && !self.draining => {}
_ => {
return Err(FFramesMediaError::LibAVAudioDecodingError((
@@ -811,6 +838,7 @@ impl FFmpegDecoder {
impl Drop for FFmpegDecoder {
fn drop(&mut self) {
unsafe {
+ av_frame_free(&raw mut self.recv_frame);
avcodec_free_context(&raw mut self.video_stream_info.codec_ctx);
avformat_close_input(&raw mut self.fmt_ctx);
av_packet_free(&raw mut self.pkt);
diff --git a/fframes-media/tests/video_decoder_eof.rs b/fframes-media/tests/video_decoder_eof.rs
index 4e9c7d55..e3136912 100644
--- a/fframes-media/tests/video_decoder_eof.rs
+++ b/fframes-media/tests/video_decoder_eof.rs
@@ -12,8 +12,12 @@ const FRAME_COUNT: i64 = 300;
struct VideoFixture(PathBuf);
impl VideoFixture {
- // Requires the ffmpeg CLI with libx264, like the end-to-end render tests.
fn new(b_frames: usize) -> Self {
+ Self::with_rate(b_frames, FPS, FRAME_COUNT)
+ }
+
+ // Requires the ffmpeg CLI with libx264, like the end-to-end render tests.
+ fn with_rate(b_frames: usize, rate: usize, frames: i64) -> Self {
static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
let dir = std::env::temp_dir().join(format!(
"fframes-decoder-eof-{}-{}",
@@ -31,9 +35,9 @@ impl VideoFixture {
"-f",
"lavfi",
"-i",
- "testsrc2=size=32x32:rate=30",
+ &format!("testsrc2=size=32x32:rate={rate}"),
"-frames:v",
- "300",
+ &frames.to_string(),
"-c:v",
"libx264",
"-pix_fmt",
@@ -126,3 +130,45 @@ fn videos_without_b_frames_stop_at_eof() {
assert!(!unsafe { decoder.decode_up_to(FRAME_COUNT) }.unwrap());
}
}
+
+#[test]
+fn last_frame_is_shown_until_the_stream_ends_at_a_higher_fps() {
+ // 48 frames at 24 fps last 2 s, i.e. 60 frames at 30 fps. Offset 59 (1.967 s) falls after the
+ // last frame's timestamp (1.958 s) but before the end, so it must still show that frame.
+ let video = VideoFixture::with_rate(3, 24, 48);
+ let mut decoder = unsafe { FFmpegDecoder::new(&video.path(), FPS, 1) }.unwrap();
+ let last_frame_seconds = 47. / 24.;
+ for index in 0..60 {
+ unsafe {
+ assert!(
+ decoder.decode_up_to(index).unwrap(),
+ "missing frame {index}"
+ );
+ let frame = decoder.get_raw_frame();
+ let expected_seconds = (index as f32 / FPS as f32 * 24.).ceil().min(47.) / 24.;
+ assert!(
+ (frame.timestamp_seconds() - expected_seconds).abs() < 0.0001,
+ "wrong timestamp for frame {index}: {}",
+ frame.timestamp_seconds()
+ );
+ }
+ }
+ let frame = decoder.get_raw_frame();
+ assert!((unsafe { frame.timestamp_seconds() } - last_frame_seconds).abs() < 0.0001);
+ let image = unsafe { frame.convert_last_decoded_frame_into_svg_image(None) }.unwrap();
+ assert_eq!(image.data.len(), 32 * 32 * 4);
+
+ // Past the end there is nothing to show, and looping wraps to the first frame.
+ for _ in 0..2 {
+ assert!(!unsafe { decoder.decode_up_to(60) }.unwrap());
+ }
+ let offset = unsafe { decoder.adjust_offset_for_looping(60) }.unwrap();
+ assert_eq!(offset, 0);
+ assert_frame(&mut decoder, 0);
+
+ // A seek straight to the tail must not return a frame left over from before the seek.
+ unsafe { decoder.seek_to_offset(59) }.unwrap();
+ assert!(unsafe { decoder.decode_up_to(59) }.unwrap());
+ let frame = decoder.get_raw_frame();
+ assert!((unsafe { frame.timestamp_seconds() } - last_frame_seconds).abs() < 0.0001);
+}