programmatic video rendering framework that is actually fast
fix(media): expose SAR-corrected video frame display dimensions (#244)
rszrszrszc08612420319
diff --git a/Cargo.lock b/Cargo.lockindex bdf955be..98da069a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -80,6 +80,14 @@ dependencies = ["pkg-config",]+[[package]]+name = "anamorphic-video"+version = "1.3.0"+dependencies = [+ "fframes",+ "fframes_skia_renderer",+]+[[package]]name = "android-activity"version = "0.6.1"diff --git a/Cargo.toml b/Cargo.tomlindex d5f945e6..bc4bee09 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -52,6 +52,7 @@ members = ["examples/shader-mode","examples/lottie","examples/svg-in-3d",+ "examples/anamorphic-video",][workspace.lints.rust]diff --git a/e2e/snapshots/anamorphic-video/50p.png b/e2e/snapshots/anamorphic-video/50p.pngnew file mode 100644index 00000000..68838f22Binary files /dev/null and b/e2e/snapshots/anamorphic-video/50p.png differdiff --git a/examples/anamorphic-video/Cargo.toml b/examples/anamorphic-video/Cargo.tomlnew file mode 100644index 00000000..776f1dee--- /dev/null+++ b/examples/anamorphic-video/Cargo.toml@@ -0,0 +1,32 @@+[package]+name = "anamorphic-video"+version = "1.3.0"+edition = "2024"+publish = false++[dependencies]+fframes = { workspace = true, features = ["compile-time-svgtree", "cli"] }++# `--renderer cpu|skia-cpu|gpu`: Skia on Metal on macOS, on Vulkan everywhere else+[target.'cfg(target_os = "macos")'.dependencies]+fframes_skia_renderer = { workspace = true, features = ["metal", "cli"] }++[target.'cfg(not(target_os = "macos"))'.dependencies]+fframes_skia_renderer = { workspace = true, features = ["vulkan", "cli"] }++# FFmpeg codecs, portable so cached source builds work across CI runner CPUs. Windows+# links a prebuilt FFmpeg instead (see README).+[target.'cfg(not(windows))'.dependencies]+fframes = { workspace = true, features = ["h264", "libav-agree-gpl", "build-portable"] }++[lib]+name = "anamorphic_video"+path = "src/lib.rs"+doctest = false++[[bin]]+name = "anamorphic-video"+path = "src/main.rs"++[lints]+workspace = truediff --git a/examples/anamorphic-video/README.md b/examples/anamorphic-video/README.mdnew file mode 100644index 00000000..edfc4faf--- /dev/null+++ b/examples/anamorphic-video/README.md@@ -0,0 +1,8 @@+# anamorphic-video++A clip stored with non-square pixels. `media/anamorphic.mp4` is 480×360 with a sample aspect+ratio of 4:3, so players show it at 640×360. The decoder stretches it to that size, so+`into_image()`, `width()` and `height()` all report 640×360. The red outline marks where the+clip's circle lands at that size. Drawn at the coded 480×360 it would be an ellipse.++From the repository root, `just render anamorphic-video` writes the video to a file.diff --git a/examples/anamorphic-video/media/anamorphic.mp4 b/examples/anamorphic-video/media/anamorphic.mp4new file mode 100644index 00000000..74e29e30Binary files /dev/null and b/examples/anamorphic-video/media/anamorphic.mp4 differdiff --git a/examples/anamorphic-video/src/lib.rs b/examples/anamorphic-video/src/lib.rsnew file mode 100644index 00000000..c0fac2a3--- /dev/null+++ b/examples/anamorphic-video/src/lib.rs@@ -0,0 +1,51 @@+use fframes::{+ AudioMap, FFramesContext, FFramesSyncedVideoFrame, Frame, Svgr, SyncVideoFrameInput, Video,+};++#[derive(Debug)]+pub struct AnamorphicVideo;++impl Video for AnamorphicVideo {+ const FPS: usize = 30;+ const WIDTH: usize = 1280;+ const HEIGHT: usize = 720;++ fn duration(&self) -> fframes::Duration<'_> {+ fframes::Duration::Seconds(1.)+ }++ fn audio(&self) -> AudioMap<'_> {+ AudioMap::none()+ }++ fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {+ let clip = frame+ .get_synced_video_frame(ctx, "anamorphic.mp4", &SyncVideoFrameInput::default())+ .map_or_else(Svgr::empty, |video| {+ let height = Self::HEIGHT as f32;+ let width = video.width() as f32 * height / video.height() as f32;+ let image = video.into_image();+ fframes::svgr!(+ <image+ href={image.href()}+ x={(Self::WIDTH as f32 - width) / 2.}+ width={width}+ height={height}+ />+ )+ });++ fframes::svgr!(+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 1280 720"+ width={ctx.current_video_size.width}+ height={ctx.current_video_size.height}+ >+ <rect width="1280" height="720" fill="#000" />+ {clip}+ <circle cx="640" cy="360" r="280" fill="none" stroke="#f43f5e" stroke-width="4" />+ </svg>+ )+ }+}diff --git a/examples/anamorphic-video/src/main.rs b/examples/anamorphic-video/src/main.rsnew file mode 100644index 00000000..7a303dbb--- /dev/null+++ b/examples/anamorphic-video/src/main.rs@@ -0,0 +1,25 @@+use std::process::ExitCode;++use anamorphic_video::AnamorphicVideo;+use fframes::{EncoderOptions, MediaDirectory, RenderOptions, cli};+use fframes_skia_renderer::cli::SkiaRenderers;++fn main() -> ExitCode {+ let folder = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("media");+ let directory = MediaDirectory::read_folder(folder).expect("media folder");+ let media = directory.process_media_source().expect("media");++ cli::new(+ &AnamorphicVideo,+ RenderOptions {+ media: Some(&media),+ video_encoder_options: EncoderOptions {+ preferred_encoder: Some("libx264"),+ ..Default::default()+ },+ ..Default::default()+ },+ )+ .renderers(SkiaRenderers::default())+ .run()+}diff --git a/fframes-media/src/video_decoder.rs b/fframes-media/src/video_decoder.rsindex f09dbd48..391bc7cd 100644--- a/fframes-media/src/video_decoder.rs+++ b/fframes-media/src/video_decoder.rs@@ -95,6 +95,8 @@ struct VideoStreamInfo {codec_ctx: *mut AVCodecContext,width: i32,height: i32,+ display_width: i32,+ display_height: i32,pixel_format: AVPixelFormat,color_space: AVColorSpace,color_range: AVColorRange,@@ -125,6 +127,7 @@ impl Drop for SwsScaler {}const PIX_FMT_SIZE: usize = size_of::<i32>();+const MAX_PIXEL_STRETCH: i64 = 4;/// 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@@ -244,15 +247,18 @@ impl SwsScaler {}fn new(video_stream_info: VideoStreamInfo) -> Self {- let frame_data_len =- video_stream_info.width as usize * video_stream_info.height as usize * PIX_FMT_SIZE;+ let (width, height) = (+ video_stream_info.display_width,+ video_stream_info.display_height,+ );+ let frame_data_len = width as usize * height as usize * PIX_FMT_SIZE;- let linesize: [i32; 7] = Self::calculate_linesize(video_stream_info.width);+ let linesize: [i32; 7] = Self::calculate_linesize(width);SwsScaler {linesize,frame_data_len,- height: video_stream_info.height,- width: video_stream_info.width,+ height,+ width,sws_ctx: std::ptr::null_mut(),options: None,source_format: None,@@ -267,8 +273,12 @@ impl SwsScaler {source_color: (AVColorSpace, AVColorRange),options: Option<FrameConvertOptions>,) -> Result<()> {- let new_width = options.map_or(self.video_stream_info.width, |o| o.resize.width as i32);- let new_height = options.map_or(self.video_stream_info.height, |o| o.resize.height as i32);+ let new_width = options.map_or(self.video_stream_info.display_width, |o| {+ o.resize.width as i32+ });+ let new_height = options.map_or(self.video_stream_info.display_height, |o| {+ o.resize.height as i32+ });let ctx = Self::init_sws_context(&self.video_stream_info,@@ -496,17 +506,11 @@ impl FFmpegFrameBuf {}pub fn get_stream_width(&self) -> u32 {- unsafe { self.sws_scaler.get().as_ref() }- .expect("Critical mememroy error: SWS scale is not allocated")- .video_stream_info- .width as u32+ self.video_stream_info.display_width as u32}pub fn get_stream_height(&self) -> u32 {- unsafe { self.sws_scaler.get().as_ref() }- .expect("Critical mememroy error: SWS scale is not allocated")- .video_stream_info- .height as u32+ self.video_stream_info.display_height as u32}pub fn get_width(&self) -> u32 {@@ -785,12 +789,36 @@ impl FFmpegDecoder {)));}+ let (width, height) = ((*video_dec_ctx).width, (*video_dec_ctx).height);+ let (display_width, display_height) = match [+ (*stream).sample_aspect_ratio,+ (*video_dec_ctx).sample_aspect_ratio,+ ]+ .into_iter()+ .find(|ratio| {+ let (num, den) = (i64::from(ratio.num), i64::from(ratio.den));+ num > 0+ && den > 0+ && num <= MAX_PIXEL_STRETCH * den+ && den <= MAX_PIXEL_STRETCH * num+ }) {+ Some(AVRational { num, den }) => {+ let ratio = f64::from(num) / f64::from(den);+ (+ (f64::from(width) * ratio.max(1.0)).round() as i32,+ (f64::from(height) / ratio.min(1.0)).round() as i32,+ )+ }+ None => (width, height),+ };Ok(VideoStreamInfo {hw_pix_fmt,stream_index: video_stream_idx,codec_ctx: video_dec_ctx,- width: (*video_dec_ctx).width,- height: (*video_dec_ctx).height,+ width,+ height,+ display_width,+ display_height,pixel_format: (*video_dec_ctx).pix_fmt,color_space: (*video_dec_ctx).colorspace,color_range: (*video_dec_ctx).color_range,@@ -1211,6 +1239,8 @@ mod color_tests {codec_ctx: ptr::null_mut(),width: WIDTH,height: HEIGHT,+ display_width: WIDTH,+ display_height: HEIGHT,pixel_format: AVPixelFormat::AV_PIX_FMT_YUV444P,color_space: space,color_range: range,diff --git a/fframes/src/video_data.rs b/fframes/src/video_data.rsindex b8a3bca5..2483397e 100644--- a/fframes/src/video_data.rs+++ b/fframes/src/video_data.rs@@ -44,8 +44,8 @@ pub fn set_video_frame_resolver(resolver: VideoFrameResolver) {pub trait FFramesSyncedVideoFrame<'media> {/// Gets the original image from the frame- /// This will perform color space conversion but will preserve the original frame- /// size. If you need to render the video frame in the smaller size, use `into_resized_image`.+ /// This will perform color space conversion and return the frame at `width()` by+ /// `height()`. If you need to render the video frame in the smaller size, use `into_resized_image`.////// This method take self to reuse frame data allocations, but you should not/// call this method more than once per the render function@@ -59,9 +59,9 @@ pub trait FFramesSyncedVideoFrame<'media> {/// call this method more than once per the render function#[allow(clippy::wrong_self_convention)]fn into_resized_image(&self, options: &FrameConvertOptions) -> Option<ImageData<'media>>;- /// Get the native height of the frame+ /// Get the height of the frame with non-square pixels stretched to square onesfn height(&self) -> u32;- /// Get the native size of the frame+ /// Get the width of the frame with non-square pixels stretched to square onesfn width(&self) -> u32;/// Get the frame index of the origin videofn timestamp_seconds(&self) -> f32;@@ -169,12 +169,10 @@ impl<'media> FFramesSyncedVideoFrame<'media> for crate::media::FFmpegFrameBuf {))}- /// Returns the original stream video widthfn width(&self) -> u32 {self.get_stream_width()}- /// Returns the original stream video heightfn height(&self) -> u32 {self.get_stream_height()}diff --git a/scripts/e2e.mjs b/scripts/e2e.mjsindex f249fd4d..710accec 100644--- a/scripts/e2e.mjs+++ b/scripts/e2e.mjs@@ -35,6 +35,7 @@ const out = join(target, "e2e", renderer);// media is kept outside Git.// prettier-ignoreconst examples = [+ { dir: "anamorphic-video", pkg: "anamorphic-video", bin: "anamorphic-video", frames: "50%" },{ dir: "audio-announce", pkg: "audio-announce-example", bin: "audio_announce_example_bin", frames: "5s,30s" },{ dir: "beta", pkg: "beta-example", bin: "beta_example_bin", frames: "CodeDemoScene@50%,IphoneScene@50%,BetaExamples@50%" },{ dir: "conference-splash-screen", pkg: "conference-splash-screen-example", bin: "conference_splash_screen_bin", frames: "SponsorScene@50%,SpeakerScene@50%" },