programmatic video rendering framework that is actually fast
feat(video): add Clip to play a part of a video file inside a scene (#250)
Dmitriy Kovalenkof5ef6f1e7205
diff --git a/AGENTS.md b/AGENTS.mdindex 475c32d8..ebb9f15e 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -477,6 +477,18 @@ let Some(video_frame) = frame.get_synced_video_frame(ctx, "clip.mp4", &fframes::}) else { return Svgr::empty() };let image = video_frame.into_image(); // <image href={image.href()} .../>+// A part of a file (footage): seconds 19.2..24.7 of the file (`0.0..` to its end), from+// second 1.2 of the scene (`.at`, default 0). `.speed(1.5)`, `.reverse()`, `.looping()`. Each clip has its own decoder,+// so a clip and a picture in picture of the same file do not slow each other down. Store clips+// in the scene, `duration` = `clip.duration()`. The clip gives an image of the current frame:+// draw it with your own size, crop, transform, filter, mask, or pass it to a shader.+let plan = fframes::Clip::new("screen.mov", 19.2..24.7).at(1.2).editor_fallback_image(ctx.get_image("poster.jpg"));+let pip = plan.image_at_width(&frame, ctx, 440).map(|image| svgr!( // decoded at the shown size+ <image href={image.href()} x="580" y="1180" width="440" height="660" preserveAspectRatio="xMidYMid slice" />+)); // `{pip}` in svgr!: an Option<Svgr> is nothing when None+// One frame of a file (a freeze frame): seconds of the file, not of the timeline.+let still = frame.video_frame_at(ctx, "IMG_0926.mov", 21.0, None);+// Audio spectrum for the current frame (see examples/audio-announce).let bars = frame.visualize_audio_frame(fframes::VisualizeFrameInput {audio: ctx.get_audio("track.mp3")?, // listed in `fn audio`, so it is loadeddiff --git a/examples/teej-podcast/src/teej_podcast.rs b/examples/teej-podcast/src/teej_podcast.rsindex 446ed485..2f6e3b54 100644--- a/examples/teej-podcast/src/teej_podcast.rs+++ b/examples/teej-podcast/src/teej_podcast.rs@@ -1,10 +1,7 @@use crate::Chapter;use crate::{constants::*, create_transition_keyframes_for_chapters};use fframes::animation::KeyFramesAnimation;-use fframes::{- AudioMap, FFramesContext, FFramesSyncedVideoFrame, FontQuery, Frame, TextOverflow, Transform,- Video,-};+use fframes::{AudioMap, Clip, FFramesContext, FontQuery, Frame, TextOverflow, Transform, Video};use std::borrow::Cow;use std::sync::OnceLock;@@ -12,6 +9,9 @@ use std::sync::OnceLock;pub struct TeejPodcast<'a> {chapters: &'a [Chapter<'a>],chapters_animation: KeyFramesAnimation<f32>,+ /// The two camera recordings, each played from its start to its end.+ left: Clip<'static>,+ right: Clip<'static>,/// Chapter titles shortened to their rectangle, see [`Self::fit_titles`].fitted_titles: OnceLock<Vec<String>>,}@@ -22,6 +22,8 @@ impl TeejPodcast<'_> {TeejPodcast {chapters,chapters_animation,+ left: Clip::new("left.mp4", 0.0..),+ right: Clip::new("right.mp4", 0.0..),fitted_titles: OnceLock::new(),}}@@ -80,31 +82,9 @@ impl Video for TeejPodcast<'_> {fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> fframes::Svgr<'a> {let mut frame = frame;- let left_frame = frame- .get_synced_video_frame(- ctx,- "left.mp4",- &fframes::SyncVideoFrameInput {- start_from: 0.,- looping: false,- editor_fallback_image: ctx.get_image("left.jpg"),- ..Default::default()- },- )- .map(|fr| fr.into_image());-- let right_frame = frame- .get_synced_video_frame(- ctx,- "right.mp4",- &fframes::SyncVideoFrameInput {- start_from: 0.,- looping: false,- editor_fallback_image: ctx.get_image("right.jpg"),- ..Default::default()- },- )- .map(|fr| fr.into_image());+ // The editor shows left.jpg and right.jpg until it has decoded the frames.+ let left_frame = self.left.image(&frame, ctx);+ let right_frame = self.right.image(&frame, ctx);// The chapter whose time range contains the current frame; the last// chapter stays active until the end.diff --git a/fframes-media/src/video_decoder.rs b/fframes-media/src/video_decoder.rsindex a6d5aadd..27226d10 100644--- a/fframes-media/src/video_decoder.rs+++ b/fframes-media/src/video_decoder.rs@@ -1069,6 +1069,54 @@ impl FFmpegDecoder {unsafe { self.decode_up_to_pts(self.offset_pts(offset)) }}+ /// Decodes the frame at `seconds` of the stream, independent of the target fps and+ /// the playback speed. The time is rounded to a microsecond first, so a time like+ /// `19.2` shows the frame at 19.2 s and not the frame after it.+ /// # Safety+ /// Generally safe but uses libav functions+ pub unsafe fn decode_at_seconds(&mut self, seconds: f64) -> Result<bool> {+ unsafe {+ let micros = (seconds.max(0.0) * 1_000_000.0).round() as i64;+ let pts = av_rescale_q(+ micros,+ AVRational {+ num: 1,+ den: 1_000_000,+ },+ self.video_stream_info.time_base,+ );+ self.decode_up_to_pts(pts)+ }+ }++ /// [`Self::decode_at_seconds`] for a part of the stream from `loop_start` to its end+ /// that plays again after the end: `seconds` past the end wrap to `loop_start`.+ /// # Safety+ /// Generally safe but uses libav functions+ pub unsafe fn decode_at_seconds_looping(+ &mut self,+ seconds: f64,+ loop_start: f64,+ ) -> Result<bool> {+ unsafe {+ // An unknown duration can't be looped over.+ let Some(duration) = self.stream_duration() else {+ return self.decode_at_seconds(seconds);+ };+ let length = duration as f64 * av_q2d(self.video_stream_info.time_base) - loop_start;+ if length <= 0.0 {+ return self.decode_at_seconds(seconds);+ }++ let seconds = loop_start + (seconds - loop_start).rem_euclid(length);+ if self.decode_at_seconds(seconds)? {+ return Ok(true);+ }+ // The frames end before the stream's duration: start the next loop.+ self.decode_at_seconds(loop_start)+ }+ }+unsafe fn decode_up_to_pts(&mut self, target_pts: i64) -> Result<bool> {unsafe {if (*self.frame_buf.latest_av_frame).pts == target_pts {diff --git a/fframes/src/clip.rs b/fframes/src/clip.rsnew file mode 100644index 00000000..a7592d69--- /dev/null+++ b/fframes/src/clip.rs@@ -0,0 +1,273 @@+//! A part of a video file played inside a scene.++use std::hash::{DefaultHasher, Hash, Hasher};+use std::ops::{Bound, Range, RangeBounds};+use std::sync::Arc;++use crate::media::ImageData;+use crate::video_data::FFramesSyncedVideoFrame;+use crate::{+ Duration, FFramesContext, Frame, FrameConvertOptions, PlaybackSpeed, ResizeVideoFrame,+};++/// Added to the length of a clip before it is cut to whole frames, so a length like+/// `24.7 - 19.2` that float math makes a bit shorter than 5.5 s does not lose a frame.+const FRAME_EPSILON_SECONDS: f64 = 1e-4;++/// A part of a video file: the seconds `source` of `video`, played at `speed` from the+/// second `at` of the scene that shows it.+///+/// A clip has no position on the timeline, so it moves with its scene when an earlier+/// scene gets shorter. Put the sound that belongs to the clip (the voice recorded with+/// it) into the scene's `audio` at the same second.+///+/// [`Clip::image`] gives the frame of the current frame as an image. Draw it like any+/// other image, with your own size, crop, transform, filter, mask or shader:+///+/// ```rust,ignore+/// use fframes::{+/// AudioMap, AudioTimestamp::Second, AudioTrack, Clip, Duration, FFramesContext, Frame,+/// Scene, Svgr,+/// };+///+/// /// The DJI recording starts 3.650375 s before the camera file.+/// const DJI_AFTER_CAMERA: f64 = 3.650375;+///+/// #[derive(Debug)]+/// struct Hook<'a> {+/// face: Clip<'a>,+/// plan: Clip<'a>,+/// }+///+/// impl Scene for Hook<'_> {+/// fn duration(&self) -> Duration<'_> {+/// self.face.duration()+/// }+///+/// fn audio(&self) -> AudioMap<'_> {+/// AudioMap::from([AudioTrack::new(+/// "dji_13.wav",+/// Second(0.)..Second(self.face.seconds() as f32),+/// )+/// .offset((self.face.source.start + DJI_AFTER_CAMERA) as f32)])+/// }+///+/// fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {+/// let Some(face) = self.face.image(&frame, ctx) else { return Svgr::empty() };+/// // decoded at the size it is shown+/// let plan = self.plan.image_at_width(&frame, ctx, 440);+/// fframes::svgr!(+/// <g>+/// <image href={face.href()} x="0" y="0" width="1080" height="1920"+/// preserveAspectRatio="xMidYMid slice" />+/// {plan.map(|plan| fframes::svgr!(+/// <image href={plan.href()} x="580" y="1180" width="440" height="660"+/// preserveAspectRatio="xMidYMid slice" clip-path="url(#rounded)" />+/// ))}+/// </g>+/// )+/// }+/// }+///+/// let hook = Hook {+/// face: Clip::new("IMG_0926.mov", 19.2..24.7),+/// // a screen recording from 1.2 s of the scene+/// plan: Clip::new("screen.mov", 3.0..6.0).speed(1.5).at(1.2),+/// };+/// ```+///+/// Each clip decodes with its own decoder, so a clip and a picture in picture of the+/// same file do not slow each other down. A reversed clip seeks back on every frame:+/// with long keyframe intervals (phone footage) it is slow to render.+#[derive(Debug, Clone)]+pub struct Clip<'a> {+ /// The video file, a name of the media folder.+ pub video: &'a str,+ /// The seconds of the file the clip plays, `start` included, `end` not. An `end` of+ /// `f64::INFINITY` plays to the end of the file.+ pub source: Range<f64>,+ /// The second of the scene when the clip starts. Default `0.0`.+ pub at: f32,+ /// `2.0` plays the clip twice as fast (and half as long), `0.5` at half speed.+ /// Kept to 1/1000 like [`PlaybackSpeed`]. Default `1.0`.+ pub speed: f32,+ /// Plays the clip backwards, from the end of `source` to its start. Needs an end.+ pub reverse: bool,+ /// Starts the clip again after its end, for as long as the scene shows it. A clip to the+ /// end of the file starts again at the end of the file.+ pub looping: bool,+ /// The image the editor shows until the frame is decoded.+ pub editor_fallback_image: Option<&'a ImageData<'a>>,+}++impl<'a> Clip<'a> {+ /// The seconds `source` of `video` at normal speed, from the start of the scene.+ /// `19.2..24.7` plays 5.5 s of the file, `19.2..` plays from 19.2 s to the end of the+ /// file.+ pub fn new(video: &'a str, source: impl RangeBounds<f64>) -> Self {+ let start = match source.start_bound() {+ Bound::Included(&start) | Bound::Excluded(&start) => start,+ Bound::Unbounded => 0.0,+ };+ let end = match source.end_bound() {+ Bound::Included(&end) | Bound::Excluded(&end) => end,+ Bound::Unbounded => f64::INFINITY,+ };+ Self {+ video,+ source: start..end,+ at: 0.0,+ speed: 1.0,+ reverse: false,+ looping: false,+ editor_fallback_image: None,+ }+ }++ #[must_use]+ pub fn at(mut self, seconds: f32) -> Self {+ self.at = seconds;+ self+ }++ #[must_use]+ pub fn speed(mut self, speed: f32) -> Self {+ self.speed = speed;+ self+ }++ #[must_use]+ pub fn reverse(mut self) -> Self {+ self.reverse = true;+ self+ }++ #[must_use]+ pub fn looping(mut self) -> Self {+ self.looping = true;+ self+ }++ #[must_use]+ pub fn editor_fallback_image(mut self, image: Option<&'a ImageData<'a>>) -> Self {+ self.editor_fallback_image = image;+ self+ }++ fn speed_value(&self) -> f64 {+ f64::from(PlaybackSpeed::new(self.speed).thousandths()) / f64::from(PlaybackSpeed::SCALE)+ }++ fn source_seconds_len(&self) -> f64 {+ (self.source.end - self.source.start).max(0.0)+ }++ /// The length of the clip on the timeline in seconds: the source length divided by+ /// the speed. Infinite for a clip to the end of the file.+ pub fn seconds(&self) -> f64 {+ self.source_seconds_len() / self.speed_value()+ }++ /// The length of the clip, for the `duration` of the scene that shows it. It does not+ /// include `at`. A clip to the end of the file lasts the rest of the file at normal+ /// speed: give it an end to play it at another speed.+ pub fn duration(&self) -> Duration<'a> {+ if self.source.end.is_finite() {+ Duration::Seconds((self.seconds() + FRAME_EPSILON_SECONDS) as f32)+ } else if self.source.start > 0.0 {+ Duration::FromVideo(self.video) - Duration::Seconds(self.source.start as f32)+ } else {+ Duration::FromVideo(self.video)+ }+ }++ /// The number of frames the clip plays at `fps`, the same as [`Clip::duration`].+ /// `usize::MAX` for a clip to the end of the file.+ pub fn frames(&self, fps: usize) -> usize {+ ((self.seconds() + FRAME_EPSILON_SECONDS) * fps as f64) as usize+ }++ /// The second of the file shown on frame `index` of the clip (0 is the first frame of+ /// the clip, at `at`). `None` after the end of the clip unless it loops.+ pub fn source_seconds(&self, index: usize, fps: usize) -> Option<f64> {+ let frames = self.frames(fps);+ if frames == 0 || (index >= frames && !self.looping) {+ return None;+ }++ let step = self.speed_value() / fps as f64;+ let played = (index % frames) as f64 * step;+ let seconds = if self.reverse {+ (self.source.end - step - played).max(self.source.start)+ } else {+ self.source.start + played+ };+ Some(seconds)+ }++ /// The decoded frame of the clip on `frame` of the scene, with its size and timestamp.+ /// `None` before `at`, after the end, or when the file is missing or fails to decode.+ pub fn frame(+ &self,+ frame: &Frame,+ ctx: &FFramesContext<'_, '_>,+ ) -> Option<Arc<impl FFramesSyncedVideoFrame<'a> + use<'a>>> {+ let start_frame = (f64::from(self.at) * frame.fps as f64).round() as usize;+ let index = frame.index.checked_sub(start_frame)?;+ let seconds = self.source_seconds(index, frame.fps)?;+ // The end of an open clip is known to the decoder only, so it wraps the time there.+ let loop_start =+ (self.looping && !self.source.end.is_finite()).then_some(self.source.start);+ frame.video_frame_at_keyed(+ ctx,+ self.video,+ seconds,+ loop_start,+ self.decoder_key(),+ self.editor_fallback_image,+ )+ }++ /// The clip on `frame` of the scene as an image at the size of the video file, for+ /// `<image href={image.href()} ... />` or a shader. `None` when [`Clip::frame`] is.+ pub fn image(&self, frame: &Frame, ctx: &FFramesContext<'_, '_>) -> Option<ImageData<'a>> {+ Some(self.frame(frame, ctx)?.into_image())+ }++ /// [`Clip::image`] decoded at `width` pixels, the height follows the aspect ratio of+ /// the file. A 4K clip shown small (a picture in picture) converts faster this way.+ pub fn image_at_width(+ &self,+ frame: &Frame,+ ctx: &FFramesContext<'_, '_>,+ width: u32,+ ) -> Option<ImageData<'a>> {+ let video_frame = self.frame(frame, ctx)?;+ let height = (f64::from(width) * f64::from(video_frame.height())+ / f64::from(video_frame.width().max(1)))+ .round() as u32;+ video_frame.into_resized_image(&FrameConvertOptions {+ resize: ResizeVideoFrame {+ width: width.max(1),+ height: height.max(1),+ },+ })+ }++ /// Clips that show the same source second on every frame share a decoder, other clips+ /// never do.+ fn decoder_key(&self) -> u64 {+ let mut hasher = DefaultHasher::new();+ self.video.hash(&mut hasher);+ self.source.start.to_bits().hash(&mut hasher);+ self.source.end.to_bits().hash(&mut hasher);+ PlaybackSpeed::new(self.speed)+ .thousandths()+ .hash(&mut hasher);+ self.reverse.hash(&mut hasher);+ self.looping.hash(&mut hasher);+ self.at.to_bits().hash(&mut hasher);+ // 0 is the key of `Frame::video_frame_at`+ hasher.finish().max(1)+ }+}diff --git a/fframes/src/frame.rs b/fframes/src/frame.rsindex 6c7ff475..dab6d2ce 100644--- a/fframes/src/frame.rs+++ b/fframes/src/frame.rs@@ -468,6 +468,45 @@ impl Frame {.ok().flatten()}++ /// Returns the frame at `seconds` of the video file, wherever it is on the timeline.+ /// This is a seek into the file: `video_frame_at(ctx, "clip.mp4", 19.2, None)` is the+ /// frame at 19.2 s of `clip.mp4` on every frame of the video (a freeze frame). To play+ /// a part of a file, use [`Clip`](crate::Clip).+ ///+ /// Returns `None` if the file is not found, `seconds` is after its last frame, or the+ /// frame fails to decode. The editor decodes on the grid of the video's fps and shows+ /// `editor_fallback_image` until the frame is decoded.+ pub fn video_frame_at<'f>(+ &self,+ ctx: &crate::FFramesContext<'_, '_>,+ file_name: &str,+ seconds: f64,+ editor_fallback_image: Option<&'f crate::media::ImageData<'f>>,+ ) -> Option<Arc<impl FFramesSyncedVideoFrame<'f> + use<'f>>> {+ self.video_frame_at_keyed(ctx, file_name, seconds, None, 0, editor_fallback_image)+ }++ /// `video_frame_at` with the decoder of `key`. Different keys never share a decoder.+ /// With a `loop_start`, seconds past the end of the file wrap to it.+ pub(crate) fn video_frame_at_keyed<'f>(+ &self,+ ctx: &crate::FFramesContext<'_, '_>,+ file_name: &str,+ seconds: f64,+ loop_start: Option<f64>,+ key: u64,+ editor_fallback_image: Option<&'f crate::media::ImageData<'f>>,+ ) -> Option<crate::video_data::SourceFrame<'f>> {+ let video = ctx.get_video(file_name)?;+ self.worker_local_video_decoders+ .get_frame_at_source(video, seconds, loop_start, key, ctx, editor_fallback_image)+ .map_err(|e| {+ crate::log!("Error while decoding video frame: {:?}", e);+ })+ .ok()+ .flatten()+ }}#[cfg(test)]diff --git a/fframes/src/lib.rs b/fframes/src/lib.rsindex a68c9f5a..fb71c2a7 100644--- a/fframes/src/lib.rs+++ b/fframes/src/lib.rs@@ -110,6 +110,7 @@ mod audio_effects;mod audio_map;mod audio_mix;mod audio_window_functions;+mod clip;mod color;mod duration;mod fframes_context;@@ -150,6 +151,7 @@ pub use audio_effects::*;pub use audio_map::*;pub use audio_mix::*;pub use audio_window_functions::*;+pub use clip::*;pub use color::*;pub use duration::*;pub use fframes_context::*;diff --git a/fframes/src/svgr.rs b/fframes/src/svgr.rsindex 75c24c47..ca9639ba 100644--- a/fframes/src/svgr.rs+++ b/fframes/src/svgr.rs@@ -50,6 +50,14 @@ impl<'a> Svgr<'a> {}}+/// `None` is nothing, so `{clip.image(&frame, ctx).map(|image| svgr!(...))}` draws the+/// element only while there is an image.+impl<'a> From<Option<Svgr<'a>>> for Svgr<'a> {+ fn from(value: Option<Svgr<'a>>) -> Self {+ value.unwrap_or_default()+ }+}+#[cfg(any(not(feature = "compile-time-svgtree"), target_arch = "wasm32"))]impl From<String> for Svgr<'_> {fn from(value: String) -> Self {diff --git a/fframes/src/video_data.rs b/fframes/src/video_data.rsindex b6112ee3..b342ea17 100644--- a/fframes/src/video_data.rs+++ b/fframes/src/video_data.rs@@ -17,6 +17,13 @@ use std::{#[cfg(target_arch = "wasm32")]use std::cell::Cell;+/// A decoded frame of a video file.+#[cfg(not(target_arch = "wasm32"))]+pub(crate) type SourceFrame<'media> = Arc<crate::media::FFmpegFrameBuf>;+/// A decoded frame of a video file: the editor's frame or the fallback image.+#[cfg(target_arch = "wasm32")]+pub(crate) type SourceFrame<'media> = Arc<WasmEditorVideoFrameFallback<'media>>;+/// Data returned by the video frame resolver callback.#[cfg(target_arch = "wasm32")]pub struct VideoFrameData {@@ -70,8 +77,8 @@ pub trait FFramesSyncedVideoFrame<'media> {#[derive(Debug, Clone, Copy)]pub struct SyncVideoFrameInput<'media> {- /// The seconds timestamp in seconds to start playing the video from- /// If not provided starts playing from the beginning of the video or scene.+ /// The second of the video (or scene) when the file starts playing from its beginning.+ /// It is not a position in the file: to play a part of a file use [`Clip`](crate::Clip).pub start_from: f32,/// If `true` the video playback will be looped and will start from the beginning on the end./// Also if `true` the `get_synced_video_frame` API should never return None, only in case of@@ -213,31 +220,50 @@ struct DecoderEntry {slot: DecoderSlot,}-/// Each decoder keeps the file open and its frames in memory. A file played at more-/// speeds closes the idle decoder that was used least recently.+/// What a decoder of a file is used for. Each key has its own decoder, so two uses of+/// one file at different positions do not seek the same decoder back and forth.+#[cfg(not(target_arch = "wasm32"))]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum DecoderKey {+ /// `get_synced_video_frame` at a playback speed.+ Speed(PlaybackSpeed),+ /// `video_frame_at` with this key (one per `Clip`).+ Source(u64),+}++#[cfg(not(target_arch = "wasm32"))]+impl From<PlaybackSpeed> for DecoderKey {+ fn from(speed: PlaybackSpeed) -> Self {+ Self::Speed(speed)+ }+}++/// Each decoder keeps the file open and its frames in memory. A file used with more+/// keys closes the idle decoder that was used least recently.#[cfg(not(target_arch = "wasm32"))]const MAX_DECODERS_PER_VIDEO: usize = 4;#[cfg(not(target_arch = "wasm32"))]#[derive(Default)]struct DecoderPool {- /// The decoders of each file, one per playback speed: offsets of different speeds- /// point to different parts of the file.- sources: HashMap<PathBuf, Vec<(PlaybackSpeed, DecoderEntry)>>,+ /// The decoders of each file, one per playback speed and one per clip: offsets of+ /// different speeds and clips point to different parts of the file.+ sources: HashMap<PathBuf, Vec<(DecoderKey, DecoderEntry)>>,generation: u64,accesses: u64,}#[cfg(not(target_arch = "wasm32"))]impl DecoderPool {- fn slot(&mut self, path: &Path, speed: PlaybackSpeed) -> DecoderSlot {+ fn slot(&mut self, path: &Path, key: impl Into<DecoderKey>) -> DecoderSlot {+ let key = key.into();self.accesses += 1;let decoders = if let Some(decoders) = self.sources.get_mut(path) {decoders} else {self.sources.entry(path.to_owned()).or_default()};- let index = if let Some(index) = decoders.iter().position(|(s, _)| *s == speed) {+ let index = if let Some(index) = decoders.iter().position(|(k, _)| *k == key) {index} else {if decoders.len() >= MAX_DECODERS_PER_VIDEO@@ -250,7 +276,7 @@ impl DecoderPool {{decoders.remove(idle);}- decoders.push((speed, DecoderEntry::default()));+ decoders.push((key, DecoderEntry::default()));decoders.len() - 1};let entry = &mut decoders[index].1;@@ -259,7 +285,7 @@ impl DecoderPool {Arc::clone(&entry.slot)}- /// The decoders of `path` at every speed. A bare file name finds an unambiguous source.+ /// The decoders of `path` at every speed and of every clip. A bare file name finds an unambiguous source.fn slots_of(&self, path: &Path) -> Vec<DecoderSlot> {let decoders = self.sources.get(path).or_else(|| {let mut matches = self@@ -366,9 +392,7 @@ impl VideoDecodersWorker {offset: i64,ctx: &FFramesContext<'_, 'media>,options: &SyncVideoFrameInput<'media>,- ) -> crate::error::Result<Option<Arc<impl FFramesSyncedVideoFrame<'media> + 'media>>> {- use crate::media::{ImageMetadata, OwnedSharedString};-+ ) -> crate::error::Result<Option<SourceFrame<'media>>> {let Some(metadata) = media_ref.metadata else {return Ok(None);};@@ -383,46 +407,50 @@ impl VideoDecodersWorker {return Ok(None);}- // Call into JS to get a decoded video frame from the buffer manager.- // The callback is synchronous — it returns a buffered frame or None.- if let Some(filename) = media_ref.path.file_name().map(|f| f.to_string_lossy()) {- let is_preview = matches!(ctx.mode, crate::FFramesMode::EditorTimelinePreview);- let frame_data = VIDEO_FRAME_RESOLVER.with(|resolver| {- resolver- .get()- .and_then(|resolve| resolve(&filename, offset, is_preview))- });-- if let Some(data) = frame_data {- // preview_url (data URL) is used for timeline canvas rendering- // where SVG-as-image blocks blob URL resolution.- // Falls back to the main url if no preview_url is provided.- let preview_source = data.preview_url.as_deref().unwrap_or(&data.url);-- return Ok(Some(Arc::new(WasmEditorVideoFrameFallback {- fallback_image: ImageData::new_from_web_source(- OwnedSharedString::new_owned(preview_source.to_owned()),- data.url,- format!("__video_frame_{}_{}", filename, offset),- ImageMetadata {- width: data.width,- height: data.height,- },- ),- video_metadata: metadata,- })));- }- }+ Ok(editor_frame(+ media_ref,+ metadata,+ offset,+ ctx,+ options.editor_fallback_image,+ ))+ }- // Fall back to static fallback image (no decoded frames available yet)- let Some(fallback_image) = options.editor_fallback_image else {+ /// The frame at `seconds` of the file in the editor: the frame of the decode queue+ /// on the grid of the video's fps, or the fallback image. With a `loop_start`,+ /// seconds past the end of the file wrap to it.+ #[cfg(target_arch = "wasm32")]+ pub(crate) fn get_frame_at_source<'f>(+ &self,+ media_ref: &VideoMedia,+ seconds: f64,+ loop_start: Option<f64>,+ _key: u64,+ ctx: &FFramesContext<'_, '_>,+ editor_fallback_image: Option<&'f ImageData<'f>>,+ ) -> crate::error::Result<Option<SourceFrame<'f>>> {+ let Some(metadata) = media_ref.metadata else {return Ok(None);};+ let duration = f64::from(metadata.duration);+ let seconds = match loop_start {+ Some(loop_start) if duration > loop_start => {+ loop_start + (seconds - loop_start).rem_euclid(duration - loop_start)+ }+ _ => seconds,+ };+ if seconds >= duration {+ return Ok(None);+ }- Ok(Some(Arc::new(WasmEditorVideoFrameFallback {- fallback_image: fallback_image.clone(),- video_metadata: metadata,- })))+ let offset = (seconds * ctx.time_base.fps as f64).round() as i64;+ Ok(editor_frame(+ media_ref,+ metadata,+ offset,+ ctx,+ editor_fallback_image,+ ))}#[cfg(not(target_arch = "wasm32"))]@@ -478,6 +506,88 @@ impl VideoDecodersWorker {Ok(has_frame.then(|| decoder.retained_frame()).transpose()?)}}++ /// The frame at `seconds` of the file, decoded by the decoder of `key`. With a+ /// `loop_start`, seconds past the end of the file wrap to it.+ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) fn get_frame_at_source<'f>(+ &self,+ VideoMedia { path, .. }: &VideoMedia,+ seconds: f64,+ loop_start: Option<f64>,+ key: u64,+ ctx: &FFramesContext<'_, '_>,+ _editor_fallback_image: Option<&'f ImageData<'f>>,+ ) -> Result<Option<SourceFrame<'f>>> {+ let slot = self.pool.lock()?.slot(path, DecoderKey::Source(key));+ let mut guard = slot.lock()?;+ unsafe {+ let decoder = match guard.as_mut() {+ Some(decoder) => decoder,+ None => guard.insert(fframes_media::FFmpegDecoder::new_with_mode(+ path,+ ctx.time_base.fps,+ self.buffer_size,+ self.mode,+ )?),+ };+ let has_frame = match loop_start {+ Some(loop_start) => decoder.decode_at_seconds_looping(seconds, loop_start)?,+ None => decoder.decode_at_seconds(seconds)?,+ };+ Ok(has_frame.then(|| decoder.retained_frame()).transpose()?)+ }+ }+}++/// The frame at `offset` (frames of the video's fps) from the editor's decode queue, or+/// the fallback image while it is not decoded.+#[cfg(target_arch = "wasm32")]+fn editor_frame<'f>(+ media_ref: &VideoMedia,+ metadata: GeneralVideoFileMetadata,+ offset: i64,+ ctx: &FFramesContext<'_, '_>,+ editor_fallback_image: Option<&'f ImageData<'f>>,+) -> Option<SourceFrame<'f>> {+ use crate::media::{ImageMetadata, OwnedSharedString};++ // Call into JS to get a decoded video frame from the buffer manager.+ // The callback is synchronous — it returns a buffered frame or None.+ if let Some(filename) = media_ref.path.file_name().map(|f| f.to_string_lossy()) {+ let is_preview = matches!(ctx.mode, crate::FFramesMode::EditorTimelinePreview);+ let frame_data = VIDEO_FRAME_RESOLVER.with(|resolver| {+ resolver+ .get()+ .and_then(|resolve| resolve(&filename, offset, is_preview))+ });++ if let Some(data) = frame_data {+ // preview_url (data URL) is used for timeline canvas rendering+ // where SVG-as-image blocks blob URL resolution.+ // Falls back to the main url if no preview_url is provided.+ let preview_source = data.preview_url.as_deref().unwrap_or(&data.url);++ return Some(Arc::new(WasmEditorVideoFrameFallback {+ fallback_image: ImageData::new_from_web_source(+ OwnedSharedString::new_owned(preview_source.to_owned()),+ data.url,+ format!("__video_frame_{}_{}", filename, offset),+ ImageMetadata {+ width: data.width,+ height: data.height,+ },+ ),+ video_metadata: metadata,+ }));+ }+ }++ // Fall back to static fallback image (no decoded frames available yet)+ Some(Arc::new(WasmEditorVideoFrameFallback {+ fallback_image: editor_fallback_image?.clone(),+ video_metadata: metadata,+ }))}#[cfg(all(test, not(target_arch = "wasm32")))]@@ -527,11 +637,11 @@ mod decoder_pool_tests {drop(normal);// A fifth speed closes the idle decoder used least recently, not the one in use.pool.slot(clip, PlaybackSpeed::new(3.0));- let speeds: Vec<_> = pool.sources[clip]- .iter()- .map(|(speed, _)| speed.thousandths())- .collect();- assert_eq!(speeds, [2000, 500, 1500, 3000]);+ let keys: Vec<_> = pool.sources[clip].iter().map(|(key, _)| *key).collect();+ assert_eq!(+ keys,+ [2.0, 0.5, 1.5, 3.0].map(|speed| DecoderKey::Speed(PlaybackSpeed::new(speed)))+ );assert_eq!(pool.slots_of(Path::new("clip.mp4")).len(), 4);drop(held);}diff --git a/skills/fframes-video/SKILL.md b/skills/fframes-video/SKILL.mdindex b335da10..beedc25a 100644--- a/skills/fframes-video/SKILL.md+++ b/skills/fframes-video/SKILL.md@@ -29,7 +29,7 @@ When matching a supplied video, first follow the reference-analysis guidance in`references/design.md`. Its cuts, pacing and motion take precedence over the design defaultsbelow; fast edits and intentional black frames may be part of the requested result.-## Two rules before anything else+## Three rules before anything else### Plan before you write code@@ -69,6 +69,27 @@ strokes, objects that react to each other, elements carried across cuts. Beforeuser anything, look at a strip and ask whether the video would still work for a differentproduct with only the text changed. If it would, change the idea, not the colors.+### The video is the Rust crate and `media/`++Every decision about the video is in Rust code: which part of a file plays, when and at what+speed, how a voice syncs with its picture, captions, music, grading and the export settings.+Put the files into `media/` as the user gave them.++- Do not write Python, shell or ffmpeg scripts that cut, join, retime or grade media, that+ generate Rust code or data tables, or that change the file after `$R render` (remux, retag,+ replace the audio). Reading files to measure them (`ffprobe`, a sync offset) is fine.+- Footage: make one scene for each spoken segment. `Clip::new("IMG_0926.mov", 19.2..24.7)`+ plays seconds 19.2 to 24.7 of the file. The scene's `fn audio` places the voice recorded+ with it, so picture and voice move together when an earlier scene changes. Inserts and+ picture in picture are clips of the same scene (`.at(1.2)`). `clip.image(&frame, ctx)` gives+ an image: draw it with your own size, crop, transform, filter, mask or shader. To remove a+ phrase, split the clip into two clips. See `references/api.md`.+- Write measured values (the offset between a camera file and an audio recorder) as named+ constants with a comment that says what was measured and in which direction.+- If fframes cannot express something the user asked for, stop and tell the user what was+ asked, which part fframes cannot do, and the closest result that works. Do not work around+ it with an external tool.+## 1. InstallRust from <https://rustup.rs>, then the system libraries ffmpeg is built with:@@ -287,6 +308,8 @@ impl Video for MyVideo<'_> {- Measure text rather than guess: `frame.text_width`, `frame.text_fit(.., TextOverflow::Ellipsis)`,`frame.text_break_lines` for paragraphs. `inspect` catches text leaving the canvas, not textleaving its own box, so check boxes in a `frame` PNG.+- Camera or phone footage plays through `fframes::Clip` inside scenes (see the rules at the+ top). `frame.video_frame_at(ctx, file, seconds, None)` is one frame of a file (a freeze frame).- GPU shaders (SkSL or Shadertoy GLSL) run on the Skia backend through `fframes::Shader`; theytake images and synced video frames as input (green-screen keying, color grading). See`references/api.md`.diff --git a/skills/fframes-video/references/api.md b/skills/fframes-video/references/api.mdindex 47f75f84..508f42e3 100644--- a/skills/fframes-video/references/api.md+++ b/skills/fframes-video/references/api.md@@ -175,6 +175,17 @@ family, size and weight in the `<text>` attributes. `text-anchor="middle"` cente- Video frames: `frame.get_synced_video_frame(ctx, "clip.mp4", &SyncVideoFrameInput { start_from, looping, speed, editor_fallback_image })`(`speed: 2.0` plays twice as fast, `..Default::default()` keeps 1.0)then `<image href={video_frame.href()} .../>` (needs the `compile-time-svgtree` feature).+ `start_from` is when the video starts on the timeline, not a position in the file.+- Footage: `Clip::new("IMG_0926.mov", 19.2..24.7)` is seconds 19.2 to 24.7 of the file,+ `Clip::new("cam.mp4", 0.0..)` the whole file (`.at(1.2)` starts it at 1.2 s of the scene, `.speed(1.5)`, `.reverse()`, `.looping()`).+ In a scene, `fn duration` returns `self.face.duration()` and `render_frame` takes+ `self.face.image(&frame, ctx)` (or `image_at_width(&frame, ctx, 440)` for a small picture in+ picture), an `Option<ImageData>` drawn as `<image href={image.href()} ...>` with any+ transform, filter, mask or shader. `{option_of_svgr}` in `svgr!` draws nothing for `None`.+ Put the voice of the clip into the scene's `audio` with `.offset(...)` into the audio file,+ so it moves with the scene. Cut a phrase by splitting the clip into two clips, never by+ cutting the file.+- One frame of a file: `frame.video_frame_at(ctx, "IMG_0926.mov", 21.0, None)` (seconds of the file).- Subtitles: `ctx.get_subtitles("subs.vtt").and_then(|s| frame.get_subtitle_phrase(s))`.- Audio spectrum: `frame.visualize_audio_frame(VisualizeFrameInput { audio, sample_size: SampleSize::S256, smooth_level: 4, window: Some(WindowFunction::Hann) })`.