Skip to content

programmatic video rendering framework that is actually fast

fix(renderer): render at RenderOptions::override_fps (#278)

Bohdan356429f82b16
diff --git a/e2e/tests/render_smoke.rs b/e2e/tests/render_smoke.rs
index d61ddbbb..fd5de3ec 100644
--- a/e2e/tests/render_smoke.rs
+++ b/e2e/tests/render_smoke.rs
@@ -7,8 +7,8 @@ use fframes::media::FFmpegDecoder;
use fframes::{AudioMap, Color, Duration, FFramesContext, Frame, RenderOptions, Svgr, Video};
const FPS: usize = 10;
-const FRAMES: usize = 20;
-const SWITCH_AT: usize = FRAMES / 2;
+const SECONDS: f32 = 2.0;
+const SWITCH_AT_SECONDS: f32 = SECONDS / 2.0;
#[derive(Debug)]
struct SmokeVideo;
@@ -20,7 +20,7 @@ impl Video for SmokeVideo {
const BACKGROUND_COLOR: Color = Color::BLACK;
fn duration(&self) -> Duration<'_> {
- Duration::Frames(FRAMES)
+ Duration::Seconds(SECONDS)
}
fn audio(&self) -> AudioMap<'_> {
@@ -28,7 +28,7 @@ impl Video for SmokeVideo {
}
fn render_frame<'a>(&'a self, frame: Frame, _ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
- let fill = if frame.index < SWITCH_AT {
+ let fill = if frame.seconds() < SWITCH_AT_SECONDS {
"#ff0000"
} else {
"#0000ff"
@@ -76,9 +76,11 @@ fn assert_color_close(actual: [u8; 4], expected: [u8; 3], frame: usize) {
);
}
-#[test]
-fn renders_and_decodes_video() {
- let dir = std::env::temp_dir().join(format!("fframes-smoke-{}", std::process::id()));
+/// Renders `SmokeVideo` and checks the encoded frame rate and that the color switches
+/// at `SWITCH_AT_SECONDS` when counted in that frame rate.
+fn render_and_check(name: &str, override_fps: Option<usize>) {
+ let expected_fps = override_fps.unwrap_or(FPS);
+ let dir = std::env::temp_dir().join(format!("fframes-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let output = dir.join("smoke.mp4");
@@ -92,6 +94,7 @@ fn renders_and_decodes_video() {
&RenderOptions {
logger: fframes::fframes_logger::FFramesLoggerVariant::Silent,
tmp_files_directory: Some(&dir.join("chunks")),
+ override_fps,
..Default::default()
},
)
@@ -99,14 +102,41 @@ fn renders_and_decodes_video() {
assert!(std::fs::metadata(&output).unwrap().len() > 0);
- let mut decoder = unsafe { FFmpegDecoder::new(&output, FPS, 1) }.unwrap();
+ let mut decoder = unsafe { FFmpegDecoder::new(&output, expected_fps, 1) }.unwrap();
+ assert_eq!(
+ decoder.get_raw_frame().get_stream_fps(),
+ expected_fps as f32
+ );
+
+ let after_switch = (SWITCH_AT_SECONDS * expected_fps as f32) as usize + 2;
assert_color_close(center_pixel(&mut decoder, 0), [255, 0, 0], 0);
assert_color_close(
- center_pixel(&mut decoder, SWITCH_AT + 2),
+ center_pixel(&mut decoder, after_switch),
[0, 0, 255],
- SWITCH_AT + 2,
+ after_switch,
+ );
+
+ let frames = (SECONDS * expected_fps as f32) as usize;
+ assert_color_close(
+ center_pixel(&mut decoder, frames - 1),
+ [0, 0, 255],
+ frames - 1,
+ );
+ assert!(
+ !unsafe { decoder.decode_up_to(frames as i64) }.unwrap(),
+ "the video has more than {frames} frames"
);
drop(decoder);
let _ = std::fs::remove_dir_all(&dir);
}
+
+#[test]
+fn renders_and_decodes_video() {
+ render_and_check("smoke", None);
+}
+
+#[test]
+fn override_fps_sets_the_rendered_frame_rate() {
+ render_and_check("override-fps", Some(FPS / 2));
+}
diff --git a/fframes/src/frame.rs b/fframes/src/frame.rs
index fddb71cb..51d9ff79 100644
--- a/fframes/src/frame.rs
+++ b/fframes/src/frame.rs
@@ -19,7 +19,7 @@ pub struct Frame {
/// The frame index without current scene offset. If rendering within a scene will show the frame index within a whole video. Can be used to get the current video timestamp inside a scene.
/// If passed as an argument to the `Video` always equals to the `index` value.
pub global_index: usize,
- /// FPS of the video. Always equals to the FPS constant.
+ /// FPS of the video: `Video::FPS`, or `RenderOptions::override_fps` when it is set.
pub fps: usize,
text_cache: Option<TextCache>,
worker_local_video_decoders: VideoDecodersWorker,
diff --git a/fframes/src/renderer/cli.rs b/fframes/src/renderer/cli.rs
index bb2cdf6e..5ccd4730 100644
--- a/fframes/src/renderer/cli.rs
+++ b/fframes/src/renderer/cli.rs
@@ -1503,7 +1503,7 @@ fn mixer_for<'a, 'm: 'a, V: Video>(
) -> (AudioMixer<'m>, std::ops::Range<usize>) {
let options = previewer.options();
let time_base = crate::TimeBase {
- fps: V::FPS,
+ fps: previewer.timeline().fps,
sample_rate: options.audio_encoder_options.sample_rate,
};
let samples = AudioTimelineSamples::from_frames(range.start, &time_base).as_usize()
@@ -1578,7 +1578,7 @@ fn audio<'a, 'm: 'a, V: Video>(
let (mut mixer, samples) = mixer_for(previewer, frames.clone());
let (left, right) = mixer.render_all();
let to_samples = |frame: usize| {
- ((frame as f64 / V::FPS as f64 * sample_rate as f64).round() as usize)
+ ((frame as f64 / timeline.fps as f64 * sample_rate as f64).round() as usize)
.clamp(samples.start, samples.end)
- samples.start
};
@@ -1639,11 +1639,12 @@ fn audio<'a, 'm: 'a, V: Video>(
let (mixer, _) = mixer_for(previewer, timeline.full_range());
let mut results = Vec::new();
for (spec, frame) in resolve_frames(previewer, &at)? {
- let sample = (frame as f64 / V::FPS as f64 * sample_rate as f64).round() as usize;
+ let sample =
+ (frame as f64 / timeline.fps as f64 * sample_rate as f64).round() as usize;
results.push(AudioAt {
spec,
frame,
- seconds: frame as f64 / V::FPS as f64,
+ seconds: frame as f64 / timeline.fps as f64,
tracks: mixer.active_tracks_at(sample),
});
}
diff --git a/fframes/src/renderer/preview.rs b/fframes/src/renderer/preview.rs
index ca5ae72d..8400340a 100644
--- a/fframes/src/renderer/preview.rs
+++ b/fframes/src/renderer/preview.rs
@@ -306,7 +306,7 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
let scenes = video.define_scenes();
let mut runtime = FFramesRendererRuntime::new(
TimeBase {
- fps: TVideo::FPS,
+ fps: options.fps(TVideo::FPS)?,
sample_rate: options.audio_encoder_options.sample_rate,
},
video,
@@ -324,7 +324,7 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
}
let timeline_index = TimelineIndex::new(
- TVideo::FPS,
+ runtime.time_base.fps,
runtime.timeline.duration_in_frames,
runtime.timeline.scenes.as_ref(),
);
@@ -371,7 +371,7 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
let index = &self.timeline_index;
let time_base = self.runtime.time_base;
TimelineReport {
- fps: TVideo::FPS,
+ fps: time_base.fps,
width: TVideo::WIDTH,
height: TVideo::HEIGHT,
duration_frames: index.duration_in_frames,
@@ -757,7 +757,7 @@ impl<'p, 'media: 'p, TVideo: Video> Conversion<'p, 'media, TVideo> {
Frame::__internal_make_for_renderer(
frame,
frame,
- TVideo::FPS,
+ self.ctx.time_base.fps,
worker.text_cache.clone(),
worker.decoders.clone(),
),
@@ -975,6 +975,26 @@ mod batch_tests {
}
}
+ #[test]
+ fn previewer_follows_override_fps() {
+ let video = Changing { panic_at: None };
+ let options = RenderOptions {
+ override_fps: Some(20),
+ ..Default::default()
+ };
+ let previewer = Previewer::new(&video, &options).unwrap();
+ assert_eq!(
+ previewer.timeline().resolve_range("0.5s..1s").unwrap(),
+ 10..20
+ );
+
+ let zero = RenderOptions {
+ override_fps: Some(0),
+ ..Default::default()
+ };
+ assert!(Previewer::new(&video, &zero).is_err());
+ }
+
#[cfg(feature = "cli")]
#[test]
fn native_preview_resolves_the_start_without_an_export_backend() {
diff --git a/fframes/src/renderer/renderer.rs b/fframes/src/renderer/renderer.rs
index 87d580c3..303f3e39 100644
--- a/fframes/src/renderer/renderer.rs
+++ b/fframes/src/renderer/renderer.rs
@@ -27,6 +27,9 @@ pub struct RenderOptions<'a, 'media> {
pub logger: FFramesLoggerVariant,
pub audio_encoder_options: EncoderOptions<'a>,
pub video_encoder_options: EncoderOptions<'a>,
+ /// Renders and encodes at this frame rate instead of `Video::FPS`. `Frame::seconds`
+ /// follows it, so a 2 s video at `Some(30)` has 60 frames whatever `Video::FPS` is.
+ /// `Some(0)` makes rendering return an error.
pub override_fps: Option<usize>,
/// Directory used to store temporary files and artifacts generated for rendering and encoding.
pub tmp_files_directory: Option<&'a PathBuf>,
@@ -58,6 +61,17 @@ pub struct RenderOptions<'a, 'media> {
}
impl RenderOptions<'_, '_> {
+ /// The frame rate to render at: `override_fps`, or `video_fps` when it is `None`.
+ pub(crate) fn fps(&self, video_fps: usize) -> FFramesRendererResult<usize> {
+ match self.override_fps {
+ Some(0) => Err(super::FFramesRendererError::Custom(
+ "override_fps must be positive".to_owned(),
+ )),
+ Some(fps) => Ok(fps),
+ None => Ok(video_fps),
+ }
+ }
+
/// The frames that will be rendered for a video of `duration_in_frames`, clamped to it.
pub fn output_frame_range(&self, duration_in_frames: usize) -> std::ops::Range<usize> {
match &self.frame_range {
@@ -233,7 +247,7 @@ pub fn render<
mut font_source,
} = FFramesRendererRuntime::new(
TimeBase {
- fps: TVideo::FPS,
+ fps: options.fps(TVideo::FPS)?,
sample_rate: options.audio_encoder_options.sample_rate,
},
video,
@@ -333,7 +347,7 @@ pub fn render_frame<
mut font_source,
} = FFramesRendererRuntime::new(
TimeBase {
- fps: TVideo::FPS,
+ fps: options.fps(TVideo::FPS)?,
sample_rate: options.audio_encoder_options.sample_rate,
},
video,
@@ -371,7 +385,7 @@ pub fn render_frame<
crate::Frame::__internal_make_for_renderer(
frame_index,
frame_index,
- TVideo::FPS,
+ time_base.fps,
None,
decoders,
),