Skip to content

programmatic video rendering framework that is actually fast

fix(media): size video frame buffers after the scaler changes output size (#196)

Ashton Chew1f746701c991
diff --git a/fframes-media/src/video_decoder.rs b/fframes-media/src/video_decoder.rs
index a3fe3997..fbfb0434 100644
--- a/fframes-media/src/video_decoder.rs
+++ b/fframes-media/src/video_decoder.rs
@@ -126,6 +126,13 @@ impl Drop for SwsScaler {
const PIX_FMT_SIZE: usize = size_of::<i32>();
+/// Bytes `sws_scale` may write past the end of an RGBA image whose rows are `width * 4` bytes
+/// apart. The x86 YUV to RGB converter of `FFmpeg` (`yuv2rgb_fn` in
+/// `libswscale/x86/yuv_2_rgb.asm`) stores whole blocks of 16 pixels (64 bytes), at least one
+/// per row, so it can write up to 60 bytes past the last row. Frames allocated by `FFmpeg`
+/// have padding there.
+const SWS_DST_PADDING: usize = 64;
+
impl SwsScaler {
unsafe fn init_sws_context(
video_stream_info: &VideoStreamInfo,
@@ -287,7 +294,7 @@ impl SwsScaler {
&mut self,
options: Option<FrameConvertOptions>,
source_frame: *mut AVFrame,
- rgba_dst: &mut [u8],
+ rgba_dst: &mut Vec<u8>,
) -> Result<()> {
let source_pix_fmt: AVPixelFormat = std::mem::transmute((*source_frame).format);
// Decoded frame metadata takes precedence over the stream defaults and
@@ -309,6 +316,13 @@ impl SwsScaler {
self.reinit_sws_context(source_pix_fmt, source_color, options)?;
}
+ // A reused buffer may still have the length of another output size. This
+ // reallocates only when the output grows and does nothing when the size is
+ // unchanged. `sws_scale` can write past the image, see `SWS_DST_PADDING`.
+ let capacity = self.frame_data_len + SWS_DST_PADDING;
+ rgba_dst.reserve(capacity.saturating_sub(rgba_dst.len()));
+ rgba_dst.resize(self.frame_data_len, 0);
+
let ret = sws_scale(
self.sws_ctx,
(*source_frame).data.as_ptr().cast::<*const u8>(),
@@ -428,14 +442,6 @@ unsafe impl Send for FFmpegFrameBuf {}
unsafe impl Sync for FFmpegFrameBuf {}
impl FFmpegFrameBuf {
- fn alloc_data_vec(ctx: &SwsScaler) -> Vec<u8> {
- let frame_data_len = ctx.frame_data_len;
- let mut data_vec = Vec::with_capacity(frame_data_len * PIX_FMT_SIZE);
- data_vec.reserve(frame_data_len);
- data_vec.resize(frame_data_len, 0);
- data_vec
- }
-
unsafe fn new(
resource_name: String,
video_stream_info: VideoStreamInfo,
@@ -462,7 +468,6 @@ impl FFmpegFrameBuf {
unsafe fn write_new_frame(&self) -> Option<&'static mut ScaledFrameImage> {
unsafe {
let queue = self.data_buf.get().as_mut()?;
- let scaler = self.sws_scaler.get().as_ref()?;
let latest_pts = (*self.latest_av_frame).pts;
// fast path for the cpu renderer which will always have capacity 1
@@ -474,19 +479,15 @@ impl FFmpegFrameBuf {
return Some(image);
}
+ // `SwsScaler::convert` sizes the buffer once it knows the requested output size
if queue.len() == queue.capacity() {
let mut last_buffer = queue.pop_front()?;
-
- if last_buffer.data.len() != scaler.frame_data_len {
- last_buffer.data.set_len(scaler.frame_data_len);
- }
-
last_buffer.pts = latest_pts;
queue.push_back(last_buffer);
} else {
queue.push_back(ScaledFrameImage {
pts: latest_pts,
- data: Self::alloc_data_vec(scaler),
+ data: Vec::new(),
});
}
diff --git a/fframes-media/tests/video_decoder_eof.rs b/fframes-media/tests/video_decoder_eof.rs
index 5e14f508..a228cfa0 100644
--- a/fframes-media/tests/video_decoder_eof.rs
+++ b/fframes-media/tests/video_decoder_eof.rs
@@ -1,5 +1,6 @@
#![cfg(not(target_arch = "wasm32"))]
+use std::collections::HashMap;
use std::path::PathBuf;
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -16,8 +17,12 @@ impl VideoFixture {
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 {
+ Self::with_size(b_frames, rate, frames, (32, 32))
+ }
+
+ // Requires the ffmpeg CLI with libx264, like the end-to-end render tests.
+ fn with_size(b_frames: usize, rate: usize, frames: i64, (width, height): (u32, u32)) -> Self {
static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
let dir = std::env::temp_dir().join(format!(
"fframes-decoder-eof-{}-{}",
@@ -35,7 +40,7 @@ impl VideoFixture {
"-f",
"lavfi",
"-i",
- &format!("testsrc2=size=32x32:rate={rate}"),
+ &format!("testsrc2=size={width}x{height}:rate={rate}"),
"-frames:v",
&frames.to_string(),
"-c:v",
@@ -210,3 +215,65 @@ fn last_frame_is_shown_until_the_stream_ends_at_a_higher_fps() {
let frame = decoder.get_raw_frame();
assert!((unsafe { frame.timestamp_seconds() } - last_frame_seconds).abs() < 0.0001);
}
+
+fn convert_frame(decoder: &mut FFmpegDecoder, index: i64, size: Option<(u32, u32)>) -> Vec<u8> {
+ let options = size.map(|(width, height)| FrameConvertOptions {
+ resize: ResizeVideoFrame { width, height },
+ });
+ let (width, height) = size.unwrap_or((32, 32));
+ unsafe {
+ assert!(
+ decoder.decode_up_to(index).unwrap(),
+ "missing frame {index}"
+ );
+ let image = decoder
+ .get_raw_frame()
+ .convert_last_decoded_frame_into_svg_image(options.as_ref())
+ .unwrap();
+ assert_eq!((image.width, image.height), (width, height));
+ assert_eq!(
+ image.data.len(),
+ (width * height * 4) as usize,
+ "wrong data length for frame {index} at {width}x{height}"
+ );
+ image.data.to_vec()
+ }
+}
+
+#[test]
+fn frames_can_be_requested_at_a_larger_size_than_before() {
+ let video = VideoFixture::new(0);
+ // The 32x32 stream at its own size, grown and shrunk, four frames each.
+ let sizes = [None, Some((256, 256)), Some((16, 16))];
+ // The CPU renderer decodes into a single reused buffer, the Skia pipeline into a ring.
+ for buffer_size in [1, 3] {
+ let mut decoder = unsafe { FFmpegDecoder::new(&video.path(), FPS, buffer_size) }.unwrap();
+ // Decoders that are only ever asked for one size
+ let mut references = HashMap::new();
+ for index in 0..12 {
+ let size = sizes[index as usize / 4];
+ let image = convert_frame(&mut decoder, index, size);
+ let reference = references
+ .entry(size)
+ .or_insert_with(|| unsafe { FFmpegDecoder::new(&video.path(), FPS, 1) }.unwrap());
+ assert!(
+ image == convert_frame(reference, index, size),
+ "frame {index} at {size:?} differs from a decoder that only converts to that size \
+ (buffer size {buffer_size})"
+ );
+ }
+ }
+}
+
+#[test]
+fn frames_can_be_converted_at_widths_that_are_not_a_multiple_of_16() {
+ // At their own size, swscale's x86 YUV to RGB converter writes these rows in whole blocks
+ // of 16 pixels, from 56 bytes (2 px wide) to 8 bytes (46 px) past the last one
+ for width in [2, 40, 42, 44, 46] {
+ let video = VideoFixture::with_size(0, FPS, 8, (width, 32));
+ let mut decoder = unsafe { FFmpegDecoder::new(&video.path(), FPS, 1) }.unwrap();
+ for index in 0..8 {
+ convert_frame(&mut decoder, index, Some((width, 32)));
+ }
+ }
+}