Skip to content

programmatic video rendering framework that is actually fast

fix(renderer): preserve straight colors in alpha exports (#243)

Dmitriy Kovalenkoc2927a8a335d
diff --git a/fframes/src/renderer/frame_export.rs b/fframes/src/renderer/frame_export.rs
index 2910db7a..daf4e932 100644
--- a/fframes/src/renderer/frame_export.rs
+++ b/fframes/src/renderer/frame_export.rs
@@ -570,12 +570,14 @@ impl Drop for FramePool {
}
}
-/// Converts RGBA8 pixels into frames of a software pixel format on the CPU: the built-in
-/// SIMD converter for yuv420p, swscale for every other format.
+/// Converts premultiplied RGBA8 pixels into frames of a software pixel format on the CPU:
+/// the built-in SIMD converter for yuv420p, swscale for every other format. Alpha formats
+/// receive straight colors; formats without alpha keep the colors composited over black.
pub struct RgbaFrameConverter {
pool: FramePool,
sws: *mut SwsContext,
matrix: YuvMatrix,
+ straight_rgba: Option<Vec<u8>>,
}
unsafe impl Send for RgbaFrameConverter {}
@@ -629,7 +631,13 @@ impl RgbaFrameConverter {
sws
};
- Ok(Self { pool, sws, matrix })
+ Ok(Self {
+ pool,
+ sws,
+ matrix,
+ straight_rgba: (pixel_format_flags(format) & AV_PIX_FMT_FLAG_ALPHA as u64 != 0)
+ .then(Vec::new),
+ })
}
/// For the frames `input` asks for.
@@ -637,16 +645,43 @@ impl RgbaFrameConverter {
Self::with_matrix(input.pixel_format, input.color_matrix, width, height)
}
- /// `rgba` is `width * height * 4` bytes without line padding.
+ /// `rgba` is premultiplied, with `width * height * 4` bytes without line padding.
pub fn convert(&mut self, rgba: &[u8]) -> RenderEncodingResult<VideoFrame> {
+ self.convert_pixels(rgba, true)
+ }
+
+ fn convert_pixels(
+ &mut self,
+ rgba: &[u8],
+ premultiplied: bool,
+ ) -> RenderEncodingResult<VideoFrame> {
let (width, height) = (self.pool.width, self.pool.height);
- if rgba.len() < width as usize * height as usize * 4 {
+ let byte_len = width as usize * height as usize * 4;
+ if rgba.len() < byte_len {
return Err(RenderEncodingError::Internal(format!(
"{} bytes of RGBA do not make a {width}x{height} frame",
rgba.len()
)));
}
+ // swscale reads RGBA as straight colors. Only undo premultiplication when the
+ // destination retains alpha, using scratch storage so the caller's pixels survive.
+ let rgba = if premultiplied && let Some(straight) = &mut self.straight_rgba {
+ straight.clear();
+ straight.extend_from_slice(&rgba[..byte_len]);
+ for pixel in straight.as_chunks_mut::<4>().0 {
+ let alpha = u32::from(pixel[3]);
+ if alpha != 0 && alpha != 255 {
+ for channel in &mut pixel[..3] {
+ *channel = ((u32::from(*channel) * 255 + alpha / 2) / alpha).min(255) as u8;
+ }
+ }
+ }
+ straight.as_slice()
+ } else {
+ rgba
+ };
+
let frame = self.pool.get()?;
unsafe {
let raw = &*frame.as_ptr();
@@ -791,7 +826,8 @@ impl<R: FrameRenderer> EncoderFrameRenderer for RgbaEncoderFrameRenderer<R> {
.render_tree(tree, background, self.width, self.height)?;
self.converter
- .convert(&frame.pixels)
+ // FrameRenderer already returns straight RGBA, unlike the native rasterizers.
+ .convert_pixels(&frame.pixels, false)
.map_err(|err| FFramesRendererError::from_chunk(0, err))
}
}
diff --git a/fframes/src/renderer/segment_writer.rs b/fframes/src/renderer/segment_writer.rs
index e4248eb1..5cf01ac0 100644
--- a/fframes/src/renderer/segment_writer.rs
+++ b/fframes/src/renderer/segment_writer.rs
@@ -94,7 +94,7 @@ impl<'a, 'o, 'm> SegmentWriter<'a, 'o, 'm> {
self.submit_with(claim, |_| Ok(frame))
}
- /// Encodes the RGBA pixels of a claimed frame, converting them on the CPU.
+ /// Encodes the premultiplied RGBA pixels of a claimed frame, converting them on the CPU.
pub fn submit(&self, claim: FrameClaim, rgba: &[u8]) -> RenderEncodingResult<()> {
self.submit_with(claim, |segment| self.convert(segment, rgba))
}
diff --git a/fframes/src/renderer/tests/alpha_render_tests.rs b/fframes/src/renderer/tests/alpha_render_tests.rs
new file mode 100644
index 00000000..99241bf1
--- /dev/null
+++ b/fframes/src/renderer/tests/alpha_render_tests.rs
@@ -0,0 +1,130 @@
+//! Renders half-transparent red over a transparent background, encodes it in color profiles
+//! with and without alpha, and decodes the file again.
+
+use crate::ffmpeg_sys_fframes::AVPixelFormat::{self, *};
+use crate::media::FFmpegDecoder;
+use crate::{
+ AudioMap, Color, Duration, EncoderOptions, FFramesContext, Frame, RenderOptions, Svgr, Video,
+ YuvMatrix, cpu::CpuRenderingBackend, fframes_logger::FFramesLoggerVariant,
+};
+
+#[derive(Debug)]
+struct HalfRed;
+
+impl Video for HalfRed {
+ const FPS: usize = 10;
+ const WIDTH: usize = 64;
+ const HEIGHT: usize = 64;
+ const BACKGROUND_COLOR: Color = Color::TRANSPARENT;
+
+ fn duration(&self) -> Duration<'_> {
+ Duration::Frames(2)
+ }
+
+ fn audio(&self) -> AudioMap<'_> {
+ AudioMap::none()
+ }
+
+ // The renderer stores it premultiplied, as (128, 0, 0, 128).
+ fn render_frame<'a>(&'a self, _frame: Frame, _ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ crate::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64">
+ <rect width="64" height="64" fill="#f00" fill-opacity="0.5" />
+ </svg>
+ )
+ }
+}
+
+/// The center pixel of the first frame. The decoder premultiplies videos with alpha, so a file
+/// that stores straight colors gives back the pixels the renderer drew.
+fn render_and_decode(
+ encoder: &str,
+ extension: &str,
+ pixel_format: AVPixelFormat,
+ matrix: YuvMatrix,
+) -> [u8; 4] {
+ let directory =
+ std::env::temp_dir().join(format!("fframes-alpha-{encoder}-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir(&directory).unwrap();
+ let output = directory.join(format!("half-red.{extension}"));
+
+ crate::render(
+ &output,
+ &HalfRed,
+ CpuRenderingBackend {
+ concurrency: 1,
+ ..Default::default()
+ },
+ &RenderOptions {
+ logger: FFramesLoggerVariant::Silent,
+ tmp_files_directory: Some(&directory.join("chunks")),
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some(encoder),
+ pixel_format,
+ color_matrix: matrix,
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ )
+ .unwrap_or_else(|err| panic!("{encoder} {pixel_format:?}: {err}"));
+
+ let pixel = unsafe {
+ let mut decoder = FFmpegDecoder::new(&output, HalfRed::FPS, 1).unwrap();
+ assert!(decoder.decode_up_to(0).unwrap());
+ let image = decoder
+ .get_raw_frame()
+ .convert_last_decoded_frame_into_svg_image(None)
+ .unwrap();
+ let center = (32 * 64 + 32) * 4;
+ image.data[center..center + 4].try_into().unwrap()
+ };
+ std::fs::remove_dir_all(directory).unwrap();
+ pixel
+}
+
+fn assert_close(actual: [u8; 4], expected: [u8; 4], tolerance: u8, profile: &str) {
+ assert!(
+ actual
+ .iter()
+ .zip(expected)
+ .all(|(a, e)| a.abs_diff(e) <= tolerance),
+ "{profile}: expected {expected:?}, decoded {actual:?}"
+ );
+}
+
+#[test]
+fn alpha_profiles_decode_to_the_rendered_pixels() {
+ for (encoder, extension, pixel_format, matrix, tolerance) in [
+ ("qtrle", "mov", AV_PIX_FMT_ARGB, YuvMatrix::Bt601, 0),
+ ("ffv1", "mkv", AV_PIX_FMT_YUVA420P, YuvMatrix::Bt601, 3),
+ ("ffv1", "mkv", AV_PIX_FMT_YUVA420P, YuvMatrix::Bt709, 3),
+ ("ffv1", "mkv", AV_PIX_FMT_YUVA444P, YuvMatrix::Bt601, 3),
+ ("ffv1", "mkv", AV_PIX_FMT_YUVA444P, YuvMatrix::Bt709, 3),
+ (
+ "prores_ks",
+ "mov",
+ AV_PIX_FMT_YUVA444P10LE,
+ YuvMatrix::Bt709,
+ 4,
+ ),
+ ] {
+ let profile = format!("{encoder} {pixel_format:?} {matrix:?}");
+ let pixel = render_and_decode(encoder, extension, pixel_format, matrix);
+ // stored premultiplied, the red would decode as 64
+ assert_close(pixel, [128, 0, 0, 128], tolerance, &profile);
+ }
+}
+
+#[test]
+fn profiles_without_alpha_composite_over_black() {
+ for (pixel_format, matrix) in [
+ (AV_PIX_FMT_YUV420P, YuvMatrix::Bt601),
+ (AV_PIX_FMT_YUV420P, YuvMatrix::Bt709),
+ (AV_PIX_FMT_YUV444P, YuvMatrix::Bt709),
+ ] {
+ let profile = format!("ffv1 {pixel_format:?} {matrix:?}");
+ let pixel = render_and_decode("ffv1", "mkv", pixel_format, matrix);
+ assert_close(pixel, [128, 0, 0, 255], 3, &profile);
+ }
+}
diff --git a/fframes/src/renderer/tests/mod.rs b/fframes/src/renderer/tests/mod.rs
index c64a852f..073dbcc3 100644
--- a/fframes/src/renderer/tests/mod.rs
+++ b/fframes/src/renderer/tests/mod.rs
@@ -1,3 +1,5 @@
+#[cfg(feature = "cpu_renderer")]
+mod alpha_render_tests;
mod preview_tests;
#[cfg(feature = "cpu_renderer")]
mod svgr_image_tests;