From 26af1e4c6f881350ada78c991c36a862a6a9a722 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 11 Aug 2026 02:18:41 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(timeline):=20a=20clip=20shot?= =?UTF-8?q?=20at=20another=20rate=20plays=20at=20the=20speed=20it=20was=20?= =?UTF-8?q?shot=20at?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A frame rate of its own is no longer a refusal at import. Every frame number in the edit list counts the *timeline's* frames -- a clip's in/out included -- and a file shot at another rate is converted once, at the decoder's door: `Rate` (milli-fps rational, `Speed`'s floor/ceil pair) says which frame of the file a timeline-rate frame is. Playback opens its worker through it and stamps the pictures coming back through its inverse; the export walks its span through it after the speed, so a 2x 24 fps clip on a 30 fps timeline is exactly both. Nothing in `project.rs` changed: placement, trim, split, paste and speed are the same arithmetic on one clock, and a single-rate project takes the identity map everywhere it used to take nothing. A library row now names the *file's* rate rather than the timeline's, which was true only while every source shared it. --- crates/app/src/main.rs | 8 +- crates/engine/src/export.rs | 59 +++++- crates/engine/src/lib.rs | 2 +- crates/engine/src/playback.rs | 161 +++++++++++++---- crates/engine/src/project.rs | 160 +++++++++++++++++ crates/engine/tests/audio_files.rs | 17 +- crates/engine/tests/mixed_fps.rs | 280 +++++++++++++++++++++++++++++ crates/engine/tests/playback.rs | 15 +- scripts/gen_fixtures.sh | 14 +- 9 files changed, 653 insertions(+), 63 deletions(-) create mode 100644 crates/engine/tests/mixed_fps.rs diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index c428579..90ab753 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -3416,12 +3416,18 @@ impl Player { None => String::new(), } ), + // The file's *own* frame rate, not the timeline's: a clip shot + // at another rate plays at the speed it was shot at, and the + // row that says where it came from has to say which rate that + // was. (None, Some(meta)) => format!( "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead", row.path.display(), meta.width, meta.height, - meta.frame_rate + self.session + .as_ref() + .map_or(meta.frame_rate, |session| session.file_fps(&row.path)) ), (None, None) => row.path.display().to_string(), }; diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index fd16471..b636bdb 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -15,7 +15,9 @@ //! picture is re-encoded, so the frame walk honours a rate: it takes the source //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the //! very frame preview holds there) and encodes a held one again rather than -//! decoding it twice. The sound is *copied* unless a filter forces a decode, and +//! decoding it twice. A clip whose *file* was shot at another rate than the +//! timeline goes through the same walk with one more conversion on the end +//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at. The sound is *copied* unless a filter forces a decode, and //! a packet carries no rate -- so a speeded clip on the one audio lane an mp4 //! copies is refused by name ([`copy_audio`]) rather than written out at 1.00x //! under a re-timed picture. @@ -44,7 +46,7 @@ use crate::audio::{AudioMeta, AudioSession}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams}; -use crate::project::{LaneKind, Project}; +use crate::project::{LaneKind, Project, Rate}; use crate::scale::Composer; /// Progress is reported in permille: an atomic integer the render loop can read @@ -467,6 +469,16 @@ fn run( chan_conf: track.chan_conf, }); + // One header parse per source, before any of them is decoded: what rate + // each file was shot at against the timeline's ([`Rate`]), which is how the + // clip's timeline frames below become frames of the file. Real time for a + // still, a song and a single-rate project, where every conversion below is + // the identity. + let rates: Vec = sources + .iter() + .map(|source| source_rate(&source.path, meta.frame_rate)) + .collect(); + let mut encoder = Enc::open(meta, settings)?; let mut muxer = None; let mut done = 0u32; @@ -481,14 +493,18 @@ fn run( // encoder is *not* reopened, so the export is one continuous stream // whose GOP boundaries need not line up with the cuts -- nor with the // file boundaries, which are just cuts that change the path. - let mut pictures = match span.from { + let (mut pictures, rate, in_frame) = match span.from { Some((source, in_frame)) => { let entry = sources .get(source) .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; - Some(ClipDecoder::open(&entry.path, in_frame)?) + let rate = rates[source]; + // Opened at the file's own frame, which is the only place the + // file's numbering is used -- the span's are the timeline's. + let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?; + (Some(pictures), rate, in_frame) } - None => None, + None => (None, Rate::REAL_TIME, 0), }; // What this span is graded by -- the same answer playback's decoder // carries, so the export is the picture that was watched. `None` for a @@ -519,10 +535,24 @@ fn run( let mut done_here = 0u32; // Source frames already taken out of this span's decoder. let mut taken = 0u32; + // The whole of the mapping, in the order it composes: the speed says + // which of the clip's (timeline-rate) frames a timeline frame shows, + // and the rate says which frame of the *file* that is -- counted from + // the one the decoder was opened at. At real time and at the timeline's + // own rate this is `Speed::source_at` and nothing else, which is the + // walk a single-rate project has always taken. + let opened_at = rate.source_at(in_frame); + let source_at = + |offset: u32| rate.source_at(in_frame + span.speed.source_at(offset)) - opened_at; while done_here < span.len { cancelled(shared)?; - let want = span.speed.source_at(done_here); - let repeats = span.speed.repeats(done_here, span.len); + let want = source_at(done_here); + // How many timeline frames from here show that same picture: one at + // real time, more when the clip is slowed or its file is slower + // than the timeline. Encoded again rather than decoded twice. + let repeats = (done_here..span.len) + .take_while(|&offset| source_at(offset) == want) + .count() as u32; let picture = match &mut pictures { Some(pictures) => { let mut ran_out = false; @@ -620,6 +650,21 @@ fn run( Ok(()) } +/// What rate `path` was shot at against a timeline at `timeline_fps` +/// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own +/// -- a still, a song -- and for one that will not open here: the decoder is +/// opened a few lines later and fails the export by name, which is a better +/// error than this one could raise. +fn source_rate(path: &Path, timeline_fps: f64) -> Rate { + if crate::is_image(path) || crate::is_audio(path) { + return Rate::REAL_TIME; + } + match Demuxer::open(path) { + Ok((meta, _)) => Rate::new(meta.frame_rate, timeline_fps), + Err(_) => Rate::REAL_TIME, + } +} + /// Where a clip sits on the timeline as a person reads it: `mm:ss`, short /// enough to sit inside a refusal and exact enough to go and find the clip. /// Not the app's frame-accurate timecode -- an engine refusal is prose, and a diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 246839b..015bbd7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -27,7 +27,7 @@ pub use demux::{Codec, VideoMeta}; pub use export::ExportHandle; pub use mux::{AudioParams, Mp4Muxer, VideoParams}; pub use playback::PlaybackSession; -pub use project::{Clip, Project, Speed}; +pub use project::{Clip, Project, Rate, Speed}; /// Whether a path names a standalone audio file -- a source with no picture, /// which belongs on the audio lane and nowhere else. Extension only, lowercased: diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 13cd7e2..c981f46 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -25,7 +25,7 @@ use crate::color::ColorParams; use crate::decode::{DecodeSession, Frame, Worker}; use crate::demux::{Codec, Demuxer, VideoMeta}; use crate::eq::EqParams; -use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span, Speed}; +use crate::project::{Clip, Edge, Lane, LaneKind, Project, Rate, Source, Span, Speed}; use crate::scale::{Composer, FitPolicy}; /// How long the feeder waits out a full ring. The ring holds a second, so this @@ -40,10 +40,11 @@ const RING_FULL_WAIT: Duration = Duration::from_millis(10); /// honest; both are what a video imported onto such a timeline is held to /// ([`matches_timeline`]). /// -/// ponytail: a 25 fps video refused by an audio-only timeline it could have -/// defined is the ceiling here. Upgrade path is adopting the first *picture's* -/// rate and codec on import, which means retiming every audio clip already -/// placed in frames. +/// ponytail: a 25 fps video imported onto an audio-only timeline it could have +/// defined plays at 25 fps, correctly, but on a 30 fps timeline -- it is read +/// through [`Rate`] like any other file shot at another rate rather than +/// defining one. Upgrade path is adopting the first *picture's* rate and codec +/// on import, which means retiming every audio clip already placed in frames. const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); /// The frame rate a timeline scaffolded from a still image runs at, for @@ -193,6 +194,20 @@ pub struct PlaybackSession { /// not -- with the single exception `sources` itself has, /// [`Self::remove_source`], which takes the same entry out of both. counts: Vec, + /// What each source's own frame rate is against this timeline's, indexed + /// and grown exactly as [`Self::counts`] is (and shortened with it by + /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the + /// timeline's rate -- and for a still and a song, which have no rate of + /// their own -- so a single-rate project converts nothing anywhere. + /// + /// A clip counts *timeline* frames ([`Rate`]); this is the one thing that + /// knows which frames of the file those are, and only + /// [`start_span`](Self::start_span) and [`try_frame`](Self::try_frame) ask. + rates: Vec, + /// The rate of the source the current worker is decoding, kept beside + /// [`Self::span`] because the frames coming back are numbered in *its* + /// file's frames and nothing else can put them back on the timeline. + span_rate: Rate, /// What the current video worker was opened for: where it sits on the /// timeline, how long it runs, and which source frame it started at -- /// together they rewrite a source frame index into a timeline one. Not a @@ -265,6 +280,9 @@ impl PlaybackSession { audio_disabled, project, counts: vec![meta.frame_count], + // Source 0 *is* the timeline's rate: it defined it. + rates: vec![Rate::REAL_TIME], + span_rate: Rate::REAL_TIME, span, eos: false, }) @@ -365,6 +383,9 @@ impl PlaybackSession { audio_disabled, project, counts: vec![meta.frame_count], + // Source 0 *is* the timeline's rate: it defined it. + rates: vec![Rate::REAL_TIME], + span_rate: Rate::REAL_TIME, span, eos: false, }) @@ -431,6 +452,9 @@ impl PlaybackSession { audio_disabled: None, project, counts: vec![meta.frame_count], + // Source 0 *is* the timeline's rate: it defined it. + rates: vec![Rate::REAL_TIME], + span_rate: Rate::REAL_TIME, span, eos: false, }) @@ -529,6 +553,11 @@ impl PlaybackSession { let first_audio = first_audio_of(&doc.sources)?; let mut counts = vec![meta.frame_count]; + // Source 0 defines the rate, so it is read frame for frame; every other + // one is however long it is *in this timeline's frames*, which is the + // length `import` noted for it and the wall the clip check below holds + // it to. + let mut rates = vec![Rate::REAL_TIME]; for source in &doc.sources[1..] { // A still has neither a rate to match nor a track to match with: // its length is the one it is held to, recomputed exactly as the @@ -538,6 +567,7 @@ impl PlaybackSession { crate::decode::image_size(&source.path) .map_err(|e| format!("source {}: {e}", source.path.display()))?; counts.push(image_frames(meta.frame_rate)); + rates.push(Rate::REAL_TIME); continue; } // A source with no picture is checked on what it does have, and @@ -547,13 +577,16 @@ impl PlaybackSession { audio_matches(source, &first_audio) .map_err(|e| format!("source {}: {e}", source.path.display()))?; counts.push(audio_frames(&source.path, meta.frame_rate)?); + rates.push(Rate::REAL_TIME); continue; } let (other, _) = Demuxer::open(&source.path) .map_err(|e| format!("source {}: {e}", source.path.display()))?; matches_timeline(source, &other, &meta, &first_audio) .map_err(|e| format!("source {}: {e}", source.path.display()))?; - counts.push(other.frame_count); + let rate = Rate::new(other.frame_rate, meta.frame_rate); + counts.push(rate.timeline_at(other.frame_count)); + rates.push(rate); } // The video lane can only play files that have pictures. Hand-written // (or hand-edited) project files are the one door this can come in @@ -619,6 +652,8 @@ impl PlaybackSession { audio_disabled, project, counts, + rates, + span_rate: Rate::REAL_TIME, span, eos: false, }; @@ -687,9 +722,15 @@ impl PlaybackSession { // (`speed_maps_both_ways`). An empty timeline has no span, // and its one black frame is frame 0. Real time is the // arithmetic this always did, frame for frame. - frame.index = self - .span - .map_or(frame.index, |s| s.timeline_at(frame.index)); + // ...through the file's own rate first, which is the ceil + // half of *that* pair: the picture at source frame `i` is + // due at the first timeline-rate frame that shows it, and a + // slower file's picture is therefore held for the frames in + // between. Real time for a gap and for a single-rate + // project, where this is the identity. + frame.index = self.span.map_or(frame.index, |s| { + s.timeline_at(self.span_rate.timeline_at(frame.index)) + }); return Some(frame); } Err(TryRecvError::Empty) => return None, @@ -759,6 +800,14 @@ impl PlaybackSession { /// timeline still moves, there are simply no more pictures, and the /// disconnected receiver carries the session on to the next span. fn start_span(&mut self, span: Option) { + // Which file's frames the worker about to be opened will number its + // pictures in: the span's own source, and real time for a gap, whose + // black worker counts timeline frames already. Set before the open, + // because the open is the first thing that converts with it. + self.span_rate = match span.and_then(|s| s.from) { + Some((source, _)) => self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME), + None => Rate::REAL_TIME, + }; let opened = match span { // The grade is the composite's at this frame -- the same clip the // span itself came from -- and it is constant across the span, so @@ -795,10 +844,17 @@ impl PlaybackSession { .. }) => DecodeSession::open_worker( &self.project.sources()[source].path, - in_frame, + // The file's own frames, which is the only place they exist: + // a clip counts the timeline's ([`Rate`]). + self.span_rate.source_at(in_frame), // Source frames, which a speed makes more (or fewer) than the - // timeline frames the span covers. - in_frame + span.expect("matched above").source_len(), + // timeline frames the span covers -- and which a file shot at + // another rate makes fewer (or more) again. One past the last + // frame this span shows, not one past its length: at another + // rate those are two different frames. + self.span_rate.source_at( + in_frame + span.expect("matched above").source_len().saturating_sub(1), + ) + 1, self.project .composite_color_at(start) .copied() @@ -1074,13 +1130,29 @@ impl PlaybackSession { self.project.trim_room(lane, idx, edge, &self.counts) } - /// Records how long a source is, for a source index that may be one - /// `Project::import` just made or one it handed back. See [`Self::counts`]. - fn note_frames(&mut self, source: usize, frames: u32) { + /// Records how long a source is and what rate it was shot at, for a source + /// index that may be one `Project::import` just made or one it handed back. + /// See [`Self::counts`] and [`Self::rates`], which are one table in two + /// vectors and grow together. + fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) { if source == self.counts.len() { self.counts.push(frames); + self.rates.push(rate); } debug_assert_eq!(self.counts.len(), self.project.sources().len()); + debug_assert_eq!(self.rates.len(), self.counts.len()); + } + + /// The rate noted for whichever source plays `path`, by + /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however + /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session + /// has never taken in. + fn file_rate(&self, path: &Path) -> Rate { + self.project + .sources() + .iter() + .position(|s| s.path == path) + .map_or(Rate::REAL_TIME, |i| self.rates[i]) } /// How long the whole of `path` is, in timeline frames: the length noted @@ -1102,6 +1174,19 @@ impl PlaybackSession { .map_or(0, |i| self.counts[i]) } + /// What rate the file at `path` was *shot* at, in frames per second -- which + /// is the timeline's own rate for every source that shares it, and is not + /// for one placed at another ([`Rate`]). By path like + /// [`file_frames`](Self::file_frames), and the timeline's rate for a file + /// this session has never taken in (and for a still and a song, which were + /// shot at no rate at all). + /// + /// What a library row names the file with: the timeline's rate there would + /// be a lie about a 23.976 fps file the moment one can join. + pub fn file_fps(&self, path: &Path) -> f64 { + self.file_rate(path).as_f64() * self.meta.frame_rate + } + /// The clip the picture is coming from at `timeline_secs`: the lane it sits /// on and its index there, by the same topmost-lane-wins rule the decoder /// follows. `None` over a gap and past the end. What a card that grades @@ -1258,8 +1343,9 @@ impl PlaybackSession { let first = self.first_audio()?; audio_matches(&wanted, &first)?; } + let rate = self.file_rate(&wanted.path); let source = self.project.import(path, stream); - self.note_frames(source, frames); + self.note_frames(source, frames, rate); let clip = Clip { start: 0, in_frame: 0, @@ -1334,6 +1420,7 @@ impl PlaybackSession { // count one index late. if idx < self.counts.len() { self.counts.remove(idx); + self.rates.remove(idx); } let now = self.now(); self.seek(now); @@ -1387,11 +1474,14 @@ impl PlaybackSession { /// nothing playable, so there is nothing for [`undo`](Self::undo) to take /// back, and nothing reseeks. /// - /// Refused unless it can join the timeline -- same codec, same frame rate, - /// same audio parameters or both silent; the `Err` names the property that - /// disagrees, for a caller to show. Nothing is changed by a refusal. A - /// *resolution* of its own is not a refusal: the clip is placed on the - /// project canvas by its fit policy ([`PlaybackSession::set_fit`]). + /// Refused unless it can join the timeline -- same codec, same audio + /// parameters or both silent; the `Err` names the property that disagrees, + /// for a caller to show. Nothing is changed by a refusal. A *resolution* of + /// its own is not a refusal: the clip is placed on the project canvas by its + /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame + /// rate* of its own: the file is placed for the seconds it lasts and read at + /// [`Rate`] against the timeline's rate, so it plays at the speed it was + /// shot at. pub fn import(&mut self, path: &Path) -> crate::Result { if crate::is_audio(path) { return self.import_audio(path); @@ -1406,7 +1496,11 @@ impl PlaybackSession { // its streams reaches the timeline afterwards. matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?; let source = self.project.import(path, 0); - self.note_frames(source, meta.frame_count); + // Its length *on this timeline*: a file shot slower than the timeline + // runs covers more frames than it holds, which is the whole of what + // placing it at another rate means ([`Rate`]). + let rate = Rate::new(meta.frame_rate, self.meta.frame_rate); + self.note_frames(source, rate.timeline_at(meta.frame_count), rate); Ok(source) } @@ -1426,7 +1520,7 @@ impl PlaybackSession { audio_matches(&Source::new(path, 0), &first)?; let frames = audio_frames(path, self.meta.frame_rate)?; let source = self.project.import(path, 0); - self.note_frames(source, frames); + self.note_frames(source, frames, Rate::REAL_TIME); Ok(source) } @@ -1450,7 +1544,7 @@ impl PlaybackSession { .into()); } let source = self.project.import(path, 0); - self.note_frames(source, image_frames(self.meta.frame_rate)); + self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME); Ok(source) } @@ -1717,10 +1811,9 @@ impl Drop for PlaybackSession { /// *Not* the same size any more. A project has its own resolution /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a -/// letterboxed clip rather than a refusal. The frame rate stays refused on -/// purpose: mixing rates means resampling the *timeline*, which is a different -/// problem from resampling a picture, and a refusal is the honest answer until -/// it is solved. +/// letterboxed clip rather than a refusal, and so is a frame rate of its own: +/// the timeline keeps its own rate and the file is read at [`Rate`] against it +/// ([`PlaybackSession::import`] notes how long it is *here*). /// /// The `Err` names the property that disagrees, and those strings are what a /// front-end shows verbatim; [`PlaybackSession::import`] and @@ -1744,14 +1837,10 @@ fn matches_timeline( ) .into()); } - // Container frame rates are computed from timescales, so never `==`. - if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 { - return Err(format!( - "{:.3} fps does not match the timeline's {:.3} fps", - meta.frame_rate, timeline.frame_rate - ) - .into()); - } + // The frame rate is *not* one of these: a file shot at another rate is + // placed for the seconds it lasts and read through [`Rate`] at the + // decoder's door, so it plays at the speed it was shot at on a timeline + // that counts frames faster or slower. audio_matches(source, first) } diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 1620522..557cf96 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -221,9 +221,97 @@ impl std::fmt::Display for Speed { } } +/// What a file's own frame rate is against the timeline's, as an exact rational +/// in thousandths of a frame per second: how many frames of the *file* one frame +/// of the timeline is worth. +/// +/// Every frame number in this module counts **timeline** frames -- a clip's +/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps +/// timeline is as many frames long as the seconds it lasts, and every edit +/// (trim, split, speed, paste) is the same arithmetic it always was. This is the +/// one conversion, and it happens at the decoder's door: [`PlaybackSession`] +/// opens a worker with it and [`crate::export`] pulls pictures through it. The +/// file's own numbering exists nowhere else. +/// +/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an +/// export encodes at a timeline frame has to be the frame playback is holding +/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps +/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`). +/// +/// ponytail: the rate is rounded to milli-fps, so 24000/1001 is carried as +/// 23.976 -- about a frame per 40000, or a frame off after seven hours of one +/// clip. Upgrade path is carrying the container's own timescale rational in +/// [`crate::VideoMeta`] and building this from it. +/// +/// [`PlaybackSession`]: crate::PlaybackSession +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Rate { + /// Milli-fps of the file... + source: u64, + /// ...and of the timeline it plays on. + timeline: u64, +} + +impl Rate { + /// A file shot at the timeline's own rate: every conversion below is the + /// identity, which is the path a single-rate project is on. + pub const REAL_TIME: Self = Self { + source: 1, + timeline: 1, + }; + + /// The rate of a file at `source_fps` on a timeline at `timeline_fps`. + /// Rounded to milli-fps, and [`REAL_TIME`](Self::REAL_TIME) for the rates + /// that agree there -- container rates are computed from timescales, so + /// "the same rate" is never `==` either. + pub fn new(source_fps: f64, timeline_fps: f64) -> Self { + let milli = |fps: f64| match fps.is_finite() && fps > 0. { + true => (fps * 1000.).round().clamp(1., 1e9) as u64, + // Not a rate at all: read the file frame for frame rather than + // dividing the timeline by a zero. + false => 0, + }; + match (milli(source_fps), milli(timeline_fps)) { + (0, _) | (_, 0) => Self::REAL_TIME, + (source, timeline) if source == timeline => Self::REAL_TIME, + (source, timeline) => Self { source, timeline }, + } + } + + pub fn is_real_time(self) -> bool { + self.source == self.timeline + } + + /// As a multiplier of the timeline's rate: what a *file's* own frame rate + /// is, given the timeline's, for a library row that names it. + pub fn as_f64(self) -> f64 { + self.source as f64 / self.timeline as f64 + } + + /// Which frame of the file the `frame`th timeline-rate frame of it is: + /// floored, [`Speed::source_at`]'s half of the pair. + pub fn source_at(self, frame: u32) -> u32 { + (u64::from(frame) * self.source / self.timeline).min(u64::from(u32::MAX)) as u32 + } + + /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first + /// timeline-rate frame that shows source frame `source_frame` -- which is + /// the stamp playback puts on a decoded picture, and, applied to a file's + /// frame *count*, how long that file is in timeline frames. + pub fn timeline_at(self, source_frame: u32) -> u32 { + (u64::from(source_frame) * self.timeline) + .div_ceil(self.source) + .min(u64::from(u32::MAX)) as u32 + } +} + /// A half-open `[in_frame, out_frame)` range of frames of source /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start). /// Never empty. +/// +/// Counted at the **timeline's** frame rate, not the file's: a source shot at +/// another rate is converted at the decoder's door ([`Rate`]), so every edit +/// here is frames of one clock. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Clip { /// Timeline frame the clip's first frame is shown at. Meaningless on a @@ -4539,6 +4627,78 @@ mod tests { assert_eq!(Speed::from_permille(2500).to_string(), "2.50x"); } + /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an + /// export encodes at a timeline frame is the one playback is holding there, + /// a file is as long in timeline frames as the seconds it lasts, and the two + /// compose so a speeded clip at another rate is exactly both. + #[test] + fn rate_composes_with_speed() { + // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976, + // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be + // the identity map or a single-rate project would move. + for (source_fps, timeline_fps) in [ + (24000. / 1001., 30.), + (30., 24000. / 1001.), + (60., 30.), + (25., 30.), + (30., 30.), + ] { + let rate = Rate::new(source_fps, timeline_fps); + for n in 0..2000u32 { + let source = rate.source_at(n); + // The stamp is the *first* timeline-rate frame that shows it, so + // the picture on screen at `n` is the picture encoded at `n`. + let held = (0..=source + 4) + .filter(|&s| rate.timeline_at(s) <= n) + .next_back(); + assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}"); + } + // A file of `count` frames is `timeline_at(count)` frames long here, + // and its last one still reads a frame the file has. + for count in 1..500u32 { + let frames = rate.timeline_at(count); + assert!(frames >= 1, "a file is never zero frames long"); + assert!( + rate.source_at(frames - 1) < count, + "{source_fps} on {timeline_fps}: {count} frames reads past the file" + ); + } + // No drift: the mapping is one exact division, not an accumulation, + // so an hour in is as true as the first second. (`Rate` rounds the + // rate itself to milli-fps -- 23.976 for 24000/1001 -- which is the + // 3e-8 the tolerance below allows for.) + let milli = |fps: f64| (fps * 1000.).round(); + for n in [1u32, 100, 10_000, 500_000, 3_000_000] { + let want = f64::from(n) * milli(source_fps) / milli(timeline_fps); + assert!( + (f64::from(rate.source_at(n)) - want).abs() < 1., + "{source_fps} on {timeline_fps}: frame {n} drifted" + ); + } + } + // The timeline's own rate is the identity, whichever way it is written. + assert!(Rate::new(30., 30.).is_real_time()); + assert!(Rate::new(30.0004, 30.).is_real_time(), "milli-fps rounding"); + assert!(Rate::new(0., 30.).is_real_time(), "not a rate at all"); + for n in 0..1000 { + assert_eq!(Rate::REAL_TIME.source_at(n), n); + assert_eq!(Rate::REAL_TIME.timeline_at(n), n); + } + // ...and the composition, in the order the decoder's door applies it: + // the speed picks the clip's (timeline-rate) frame, the rate picks the + // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two + // timeline frames per frame shown, each of them 0.799 of a file frame. + let rate = Rate::new(24000. / 1001., 30.); + let speed = Speed::from_permille(2000); + for d in 0..100u32 { + assert_eq!( + rate.source_at(speed.source_at(d)), + (u64::from(d) * 2 * 23976 / 30000) as u32, + "2x of a 23.976 fps file at timeline frame {d}" + ); + } + } + /// The mapping a speed changes, and the one it does not: a 2x clip reads two /// source frames per timeline frame and still starts at its own in-point, /// and a half-speed one shows every source frame twice. diff --git a/crates/engine/tests/audio_files.rs b/crates/engine/tests/audio_files.rs index 8169baf..c0dc532 100644 --- a/crates/engine/tests/audio_files.rs +++ b/crates/engine/tests/audio_files.rs @@ -386,20 +386,21 @@ fn a_video_joins_a_timeline_a_song_started() { import_and_place(&mut session, &asset("test_av.mp4")); assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last"); assert_eq!(session.lane_clips(Lane::A1).len(), 2); - // And a file at another rate is refused in the timeline's own words rather - // than silently retiming the song already on the lane -- the sample rate at - // one door, the *frame* rate at the other: the canvas a song scaffolds has - // a frame rate of its own (30 fps), and a 25 fps picture cannot join it. + // A sample rate the device cannot have two of is still refused in the + // timeline's own words... let e = refusal(session.import(&asset("test_tone_48k.wav"))); assert_eq!( e, "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch" ); - assert_eq!( - refusal(session.import(&asset("test_25fps.mp4"))), - "25.000 fps does not match the timeline's 30.000 fps" - ); assert_eq!(session.sources().len(), 2, "a refusal left a library row"); + // ...but a *frame* rate of its own is not a refusal: the canvas a song + // scaffolds runs at 30 fps and a 25 fps picture joins it at the length it + // lasts in seconds (50 frames of file, 60 of timeline). + session + .import(&asset("test_25fps.mp4")) + .expect("25 fps joins the 30 fps canvas a song scaffolded"); + assert_eq!(session.file_frames(&asset("test_25fps.mp4")), 60); } /// Blocks until the export settles, whichever way it settled. diff --git a/crates/engine/tests/mixed_fps.rs b/crates/engine/tests/mixed_fps.rs new file mode 100644 index 0000000..d6146b4 --- /dev/null +++ b/crates/engine/tests/mixed_fps.rs @@ -0,0 +1,280 @@ +//! Clips shot at other frame rates on one timeline: what a 25 fps and a 23.976 +//! fps file do on the 30 fps timeline `test_av.mp4` scaffolds. +//! +//! Everything goes through the front door -- `import`, `place_stream_at`, +//! `seek`, `export_to_with`, `open_project` -- because the whole claim is that a +//! *user* can put two rates on one timeline and watch both at the speed they +//! were shot at. `project.rs`'s own `rate_composes_with_speed` owns the +//! arithmetic; what is measured here is that the pictures and the file agree +//! with it. +//! +//! ```text +//! cargo test -p engine --test mixed_fps +//! ``` + +use std::path::{Path, PathBuf}; +use std::thread::sleep; +use std::time::{Duration, Instant}; + +use engine::export::{ExportSettings, Format}; +use engine::project::{Edge, Lane, Speed}; +use engine::{DecodeSession, Frame, PlaybackSession}; + +/// The timeline's rate, which `test_av.mp4` (30 fps, 5 s) defines. +const FPS: f64 = 30.0; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Silent, for `tests/playback.rs`'s reason: the suite plays real files. +fn open(path: impl AsRef) -> PlaybackSession { + let session = PlaybackSession::open(path).expect("open"); + session.set_gain(0.0); + session +} + +fn next_frame(session: &mut PlaybackSession, what: &str) -> Frame { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Some(frame) = session.try_frame() { + return frame; + } + assert!(Instant::now() < deadline, "no frame after {what}"); + sleep(Duration::from_millis(4)); + } +} + +/// One frame of a file, decoded straight from it: the picture a mapping is +/// checked against, in the file's *own* numbering. +fn source_frame(path: &Path, index: u32) -> Vec { + let (_, rx, _cancel) = DecodeSession::open_range(path, index, index + 1).expect("open_range"); + let frame = rx + .recv_timeout(Duration::from_secs(10)) + .expect("reference frame"); + assert_eq!(frame.index, index, "open_range starts where it is told"); + frame.bgra +} + +/// Imports `path` and drags it onto the end of the timeline, the way a library +/// row reaches a lane. +fn import_and_place(session: &mut PlaybackSession, path: &Path) { + session.import(path).expect("the file joins this timeline"); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, path, 0, None) + .expect("a file just imported is on this timeline"), + "the drag onto the end of the timeline" + ); +} + +fn wait(handle: &engine::ExportHandle) -> engine::Result<()> { + let deadline = Instant::now() + Duration::from_secs(180); + while !handle.is_finished() { + assert!(Instant::now() < deadline, "export did not finish"); + sleep(Duration::from_millis(20)); + } + handle.result().expect("a finished export has an outcome") +} + +/// How different two pictures are, sampled: a re-encode moves every pixel a +/// little and a *different* picture of `testsrc2` moves them a lot, so the two +/// are never close to the threshold below. +fn difference(a: &[u8], b: &[u8]) -> f64 { + assert_eq!(a.len(), b.len(), "two pictures of one size"); + let (mut sum, mut n) = (0f64, 0u32); + for i in (0..a.len()).step_by(997) { + sum += f64::from(a[i].abs_diff(b[i])); + n += 1; + } + sum / f64::from(n.max(1)) +} + +/// A file's length is the seconds it lasts, in the timeline's frames -- not the +/// frames it holds. That is the whole of what placing another rate means: 50 +/// frames of 25 fps and 48 of 23.976 fps are both two seconds, and two seconds +/// of a 30 fps timeline is 60 frames. +#[test] +fn a_file_at_another_rate_is_placed_for_the_seconds_it_lasts() { + let mut session = open(asset("test_av.mp4")); + assert_eq!(session.file_frames(&asset("test_av.mp4")), 150, "5 s at 30"); + + let pal = asset("test_25fps.mp4"); + session + .import(&pal) + .expect("25 fps joins a 30 fps timeline"); + assert_eq!(session.file_frames(&pal), 60, "50 frames at 25 fps is 2 s"); + + // 24000/1001: 48 frames is 2.002 s, which is 60.06 frames of 30 fps -- + // rounded *up*, so the last picture is still reachable by a trim. + let ntsc = asset("test_23976fps.mp4"); + session.import(&ntsc).expect("23.976 joins it too"); + assert_eq!(session.file_frames(&ntsc), 61); + + // ...and placed, both are as long on the timeline as they are in the ear. + let end = session.timeline_duration(); + session + .place_stream_at(end, &pal, 0, None) + .expect("the drag"); + assert!( + (session.timeline_duration() - (5.0 + 2.0)).abs() < 1e-9, + "a 2 s clip made the timeline {} s", + session.timeline_duration() + ); + let end = session.timeline_duration(); + session + .place_stream_at(end, &ntsc, 0, None) + .expect("the drag"); + assert!( + (session.timeline_duration() - (5.0 + 2.0 + 61. / FPS)).abs() < 1e-9, + "{} s", + session.timeline_duration() + ); +} + +/// The picture on screen at a timeline frame is the picture the *file* holds +/// there: frame `floor(offset * 25/30)` of a 25 fps clip, which is what playing +/// at the speed it was shot at means, frame for frame. +#[test] +fn playback_shows_the_frame_the_file_holds_there() { + let pal = asset("test_25fps.mp4"); + let mut session = open(asset("test_av.mp4")); + import_and_place(&mut session, &pal); + session.pause(); + // The clip starts at timeline frame 150 (5 s) and runs 60 frames. + let start = 150u32; + for offset in [0u32, 1, 5, 6, 29, 30, 47, 59] { + let at = start + offset; + session.seek(f64::from(at) / FPS); + let landed = next_frame(&mut session, "a seek into the 25 fps clip"); + assert_eq!(landed.index, at, "a seek lands on the frame it asked for"); + let want = (u64::from(offset) * 25_000 / 30_000) as u32; + assert!( + landed.bgra == source_frame(&pal, want), + "timeline frame {at} (offset {offset}) is not source frame {want}" + ); + } + // Past the last picture the file holds, the clip is still on the timeline: + // its last frame is shown, not black and not a panic. + session.seek(f64::from(start + 59) / FPS); + let last = next_frame(&mut session, "the last frame of the clip"); + assert!(last.bgra == source_frame(&pal, 49), "source frame 49 last"); +} + +/// A speed and a frame rate compose: a 2x 25 fps clip on a 30 fps timeline is +/// half as many timeline frames and reads twice as far into the file for each +/// of them. +#[test] +fn a_speeded_clip_at_another_rate_is_exactly_both() { + let pal = asset("test_25fps.mp4"); + let mut session = open(asset("test_av.mp4")); + import_and_place(&mut session, &pal); + session + .set_speed(Lane::V1, 1, Speed::from_permille(2000)) + .expect("nothing is in the way of a clip that got shorter"); + session.pause(); + let start = 150u32; + assert!( + (session.timeline_duration() - (5.0 + 1.0)).abs() < 1e-9, + "2 s at 2x is 1 s: {}", + session.timeline_duration() + ); + for offset in [0u32, 3, 14, 29] { + let at = start + offset; + session.seek(f64::from(at) / FPS); + let landed = next_frame(&mut session, "a seek into the speeded clip"); + assert_eq!(landed.index, at); + // The speed picks the clip's (timeline-rate) frame, the rate picks the + // file's -- in that order, which is the order the decoder's door + // applies them. + let want = (u64::from(offset) * 2 * 25_000 / 30_000) as u32; + assert!( + landed.bgra == source_frame(&pal, want), + "2x at offset {offset} is not source frame {want}" + ); + } +} + +/// A saved project reloads at the same lengths: `open_project` recomputes every +/// source's rate from the file, so a mixed-rate timeline is not one that only +/// the session that built it could hold. +#[test] +fn a_mixed_rate_project_reloads_unchanged() { + let pal = asset("test_25fps.mp4"); + let mut session = open(asset("test_av.mp4")); + import_and_place(&mut session, &pal); + let duration = session.timeline_duration(); + let spans = session.clip_spans(); + let path = std::env::temp_dir().join(format!("edith-mixed-{}.edith", std::process::id())); + session.save_project(&path).expect("save"); + + let reloaded = PlaybackSession::open_project(&path).expect("a mixed-rate project reopens"); + assert_eq!(reloaded.clip_spans(), spans, "the same clips, in seconds"); + assert!((reloaded.timeline_duration() - duration).abs() < 1e-9); + assert_eq!(reloaded.file_frames(&pal), 60, "the length was recomputed"); + std::fs::remove_file(&path).ok(); +} + +/// The export is what was watched: as many frames as the timeline has, and the +/// 25 fps clip walked through its file at 25 fps -- 25 pictures over 30 frames, +/// not 30 of them and not 25 held to the end. +#[test] +fn an_export_of_two_rates_runs_at_the_speed_it_was_shot() { + let pal = asset("test_25fps.mp4"); + let mut session = open(asset("test_av.mp4")); + // A short head of the 30 fps take, then the whole of the 25 fps one -- + // enough of each to be a mixed timeline, short enough to encode in a test. + // The sound comes with it: a placed take is one linked group. + assert!( + session.trim_clip(Lane::V1, 0, Edge::End, 15), + "trim the 30 fps take to half a second" + ); + import_and_place(&mut session, &pal); + assert!( + session.trim_clip(Lane::V1, 1, Edge::End, 45), + "one second of the 25 fps clip" + ); + let total = (session.timeline_duration() * FPS).round() as u32; + assert_eq!(total, 45, "15 frames of 30 fps and 30 of the 25 fps clip"); + + let out = std::env::temp_dir().join(format!("edith-mixed-{}.mp4", std::process::id())); + wait(&session.export_to_with( + &out, + &ExportSettings { + format: Format::Mp4, + ..ExportSettings::default() + }, + )) + .expect("the export"); + + // Duration first: the file is as long as the timeline, so the mixed rates + // did not stretch or shorten it. + let (meta, rx, _cancel) = DecodeSession::open_range(&out, 0, u32::MAX).expect("reopen"); + assert!( + (meta.frame_rate - FPS).abs() < 0.01, + "the export runs at the timeline's rate: {}", + meta.frame_rate + ); + assert_eq!( + meta.frame_count, total, + "the export is the timeline's length" + ); + let written: Vec> = rx.into_iter().map(|frame| frame.bgra).collect(); + assert_eq!(written.len() as u32, total, "every frame came back"); + + // ...and motion: inside the 25 fps clip, 30 exported frames show 25 + // pictures, so 5 of them are a picture held from the frame before. A clip + // played at the wrong rate would hold none (too fast, and it would run out + // of file) or hold half of them (too slow). + let held = (16..total as usize) + .filter(|&i| difference(&written[i - 1], &written[i]) < 2.0) + .count(); + assert_eq!( + held, 5, + "30 timeline frames of a 25 fps clip hold 5 pictures over" + ); + std::fs::remove_file(&out).ok(); +} diff --git a/crates/engine/tests/playback.rs b/crates/engine/tests/playback.rs index ea97884..5268282 100644 --- a/crates/engine/tests/playback.rs +++ b/crates/engine/tests/playback.rs @@ -813,14 +813,15 @@ fn import_refuses_what_does_not_match() { "a resolution of its own is not a refusal any more: {err}" ); - // Same codec, same audio, 25 fps: the one property left, named with both - // rates. Mixing rates would mean retiming the timeline itself, and there is - // no resampler for that, so the refusal is the honest answer. - let err = session + // A frame rate of its own is no longer a refusal either: 25 fps joins a + // 30 fps timeline and is read at `Rate` against it -- see + // `tests/mixed_fps.rs` for what it then plays like. + session .import(&asset("test_25fps.mp4")) - .expect_err("25 fps must not join a 30 fps timeline") - .to_string(); - assert_eq!(err, "25.000 fps does not match the timeline's 30.000 fps"); + .expect("25 fps may join a 30 fps timeline"); + session + .remove_source(&asset("test_25fps.mp4"), 0) + .expect("...and the row it made comes back off"); // Same size and rate, no audio track: the timeline has one. let err = session diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 12106b6..db2acaf 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -135,15 +135,23 @@ enable='between(t,1,1.1)'[v];\ ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4 # Frame-rate fixture: test_av.mp4 in every respect a timeline is held to -- same -# codec, same profile, same 44.1k stereo AAC -- except that it runs at 25 fps. -# The only thing left for an import to refuse is the rate, which is what makes -# the refusal's wording testable. +# codec, same profile, same 44.1k stereo AAC -- except that it runs at 25 fps, +# so a timeline of 30 fps clips has one at another rate to read through `Rate`. ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=25:duration=2 \ -f lavfi -i "sine=frequency=440:duration=2" \ -f lavfi -i "sine=frequency=880:duration=2" \ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_25fps.mp4 +# ...and the same again at 23.976 fps (24000/1001), the rate whose ratio to a +# 30 fps timeline does not terminate: what the frame mapping's rounding is +# actually tested against. +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=24000/1001:duration=2 \ + -f lavfi -i "sine=frequency=440:duration=2" \ + -f lavfi -i "sine=frequency=880:duration=2" \ + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ + -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ + -c:a aac -b:a 128k assets/test_23976fps.mp4 # Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the # A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song # can share a timeline with the video clips and the peaks tests can reuse the