forge
Explore
Log in

Don't you dare go Hollow

A clip shot at another rate plays at the speed it was shot at

Browse files at this commit

26af1e4c6f881350ada78c991c36a862a6a9a722Ahmet Kaan GümüşParent: b211fe1
  • feat
    • a clip shot at another rate plays at the speed it was shot at
Show full message
✨ feat(timeline): a clip shot at another rate plays at the speed it was shot at

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.rsmodified+7 -1
@@ -3416,12 +3416,18 @@ impl Player {
3416 None => String::new(),3416 None => String::new(),
3417 }3417 }
3418 ),3418 ),
3419+ // The file's *own* frame rate, not the timeline's: a clip shot
3420+ // at another rate plays at the speed it was shot at, and the
3421+ // row that says where it came from has to say which rate that
3422+ // was.
3419 (None, Some(meta)) => format!(3423 (None, Some(meta)) => format!(
3420 "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",3424 "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",
3421 row.path.display(),3425 row.path.display(),
3422 meta.width,3426 meta.width,
3423 meta.height,3427 meta.height,
3424- meta.frame_rate3428+ self.session
3429+ .as_ref()
3430+ .map_or(meta.frame_rate, |session| session.file_fps(&row.path))
3425 ),3431 ),
3426 (None, None) => row.path.display().to_string(),3432 (None, None) => row.path.display().to_string(),
3427 };3433 };
crates/engine/src/export.rsmodified+52 -7
@@ -15,7 +15,9 @@
15 //! picture is re-encoded, so the frame walk honours a rate: it takes the source15 //! picture is re-encoded, so the frame walk honours a rate: it takes the source
16 //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the16 //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the
17 //! very frame preview holds there) and encodes a held one again rather than17 //! very frame preview holds there) and encodes a held one again rather than
18-//! decoding it twice. The sound is *copied* unless a filter forces a decode, and18+//! decoding it twice. A clip whose *file* was shot at another rate than the
19+//! timeline goes through the same walk with one more conversion on the end
20+//! ([`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
19 //! a packet carries no rate -- so a speeded clip on the one audio lane an mp421 //! a packet carries no rate -- so a speeded clip on the one audio lane an mp4
20 //! copies is refused by name ([`copy_audio`]) rather than written out at 1.00x22 //! copies is refused by name ([`copy_audio`]) rather than written out at 1.00x
21 //! under a re-timed picture.23 //! under a re-timed picture.
@@ -44,7 +46,7 @@ use crate::audio::{AudioMeta, AudioSession};
44 use crate::demux::{Demuxer, VideoMeta};46 use crate::demux::{Demuxer, VideoMeta};
45 use crate::hw::{HwEncoder, HwSession};47 use crate::hw::{HwEncoder, HwSession};
46 use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams};48 use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams};
47-use crate::project::{LaneKind, Project};49+use crate::project::{LaneKind, Project, Rate};
48 use crate::scale::Composer;50 use crate::scale::Composer;
49 51
50 /// Progress is reported in permille: an atomic integer the render loop can read52 /// Progress is reported in permille: an atomic integer the render loop can read
@@ -467,6 +469,16 @@ fn run(
467 chan_conf: track.chan_conf,469 chan_conf: track.chan_conf,
468 });470 });
469 471
472+ // One header parse per source, before any of them is decoded: what rate
473+ // each file was shot at against the timeline's ([`Rate`]), which is how the
474+ // clip's timeline frames below become frames of the file. Real time for a
475+ // still, a song and a single-rate project, where every conversion below is
476+ // the identity.
477+ let rates: Vec<Rate> = sources
478+ .iter()
479+ .map(|source| source_rate(&source.path, meta.frame_rate))
480+ .collect();
481+
470 let mut encoder = Enc::open(meta, settings)?;482 let mut encoder = Enc::open(meta, settings)?;
471 let mut muxer = None;483 let mut muxer = None;
472 let mut done = 0u32;484 let mut done = 0u32;
@@ -481,14 +493,18 @@ fn run(
481 // encoder is *not* reopened, so the export is one continuous stream493 // encoder is *not* reopened, so the export is one continuous stream
482 // whose GOP boundaries need not line up with the cuts -- nor with the494 // whose GOP boundaries need not line up with the cuts -- nor with the
483 // file boundaries, which are just cuts that change the path.495 // file boundaries, which are just cuts that change the path.
484- let mut pictures = match span.from {496+ let (mut pictures, rate, in_frame) = match span.from {
485 Some((source, in_frame)) => {497 Some((source, in_frame)) => {
486 let entry = sources498 let entry = sources
487 .get(source)499 .get(source)
488 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;500 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
489- Some(ClipDecoder::open(&entry.path, in_frame)?)501+ let rate = rates[source];
502+ // Opened at the file's own frame, which is the only place the
503+ // file's numbering is used -- the span's are the timeline's.
504+ let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?;
505+ (Some(pictures), rate, in_frame)
490 }506 }
491- None => None,507+ None => (None, Rate::REAL_TIME, 0),
492 };508 };
493 // What this span is graded by -- the same answer playback's decoder509 // What this span is graded by -- the same answer playback's decoder
494 // carries, so the export is the picture that was watched. `None` for a510 // carries, so the export is the picture that was watched. `None` for a
@@ -519,10 +535,24 @@ fn run(
519 let mut done_here = 0u32;535 let mut done_here = 0u32;
520 // Source frames already taken out of this span's decoder.536 // Source frames already taken out of this span's decoder.
521 let mut taken = 0u32;537 let mut taken = 0u32;
538+ // The whole of the mapping, in the order it composes: the speed says
539+ // which of the clip's (timeline-rate) frames a timeline frame shows,
540+ // and the rate says which frame of the *file* that is -- counted from
541+ // the one the decoder was opened at. At real time and at the timeline's
542+ // own rate this is `Speed::source_at` and nothing else, which is the
543+ // walk a single-rate project has always taken.
544+ let opened_at = rate.source_at(in_frame);
545+ let source_at =
546+ |offset: u32| rate.source_at(in_frame + span.speed.source_at(offset)) - opened_at;
522 while done_here < span.len {547 while done_here < span.len {
523 cancelled(shared)?;548 cancelled(shared)?;
524- let want = span.speed.source_at(done_here);549+ let want = source_at(done_here);
525- let repeats = span.speed.repeats(done_here, span.len);550+ // How many timeline frames from here show that same picture: one at
551+ // real time, more when the clip is slowed or its file is slower
552+ // than the timeline. Encoded again rather than decoded twice.
553+ let repeats = (done_here..span.len)
554+ .take_while(|&offset| source_at(offset) == want)
555+ .count() as u32;
526 let picture = match &mut pictures {556 let picture = match &mut pictures {
527 Some(pictures) => {557 Some(pictures) => {
528 let mut ran_out = false;558 let mut ran_out = false;
@@ -620,6 +650,21 @@ fn run(
620 Ok(())650 Ok(())
621 }651 }
622 652
653+/// What rate `path` was shot at against a timeline at `timeline_fps`
654+/// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own
655+/// -- a still, a song -- and for one that will not open here: the decoder is
656+/// opened a few lines later and fails the export by name, which is a better
657+/// error than this one could raise.
658+fn source_rate(path: &Path, timeline_fps: f64) -> Rate {
659+ if crate::is_image(path) || crate::is_audio(path) {
660+ return Rate::REAL_TIME;
661+ }
662+ match Demuxer::open(path) {
663+ Ok((meta, _)) => Rate::new(meta.frame_rate, timeline_fps),
664+ Err(_) => Rate::REAL_TIME,
665+ }
666+}
667+
623 /// Where a clip sits on the timeline as a person reads it: `mm:ss`, short668 /// Where a clip sits on the timeline as a person reads it: `mm:ss`, short
624 /// enough to sit inside a refusal and exact enough to go and find the clip.669 /// enough to sit inside a refusal and exact enough to go and find the clip.
625 /// Not the app's frame-accurate timecode -- an engine refusal is prose, and a670 /// Not the app's frame-accurate timecode -- an engine refusal is prose, and a
crates/engine/src/lib.rsmodified+1 -1
@@ -27,7 +27,7 @@ pub use demux::{Codec, VideoMeta};
27 pub use export::ExportHandle;27 pub use export::ExportHandle;
28 pub use mux::{AudioParams, Mp4Muxer, VideoParams};28 pub use mux::{AudioParams, Mp4Muxer, VideoParams};
29 pub use playback::PlaybackSession;29 pub use playback::PlaybackSession;
30-pub use project::{Clip, Project, Speed};30+pub use project::{Clip, Project, Rate, Speed};
31 31
32 /// Whether a path names a standalone audio file -- a source with no picture,32 /// Whether a path names a standalone audio file -- a source with no picture,
33 /// which belongs on the audio lane and nowhere else. Extension only, lowercased:33 /// which belongs on the audio lane and nowhere else. Extension only, lowercased:
crates/engine/src/playback.rsmodified+125 -36
@@ -25,7 +25,7 @@ use crate::color::ColorParams;
25 use crate::decode::{DecodeSession, Frame, Worker};25 use crate::decode::{DecodeSession, Frame, Worker};
26 use crate::demux::{Codec, Demuxer, VideoMeta};26 use crate::demux::{Codec, Demuxer, VideoMeta};
27 use crate::eq::EqParams;27 use crate::eq::EqParams;
28-use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span, Speed};28+use crate::project::{Clip, Edge, Lane, LaneKind, Project, Rate, Source, Span, Speed};
29 use crate::scale::{Composer, FitPolicy};29 use crate::scale::{Composer, FitPolicy};
30 30
31 /// How long the feeder waits out a full ring. The ring holds a second, so this31 /// 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);
40 /// honest; both are what a video imported onto such a timeline is held to40 /// honest; both are what a video imported onto such a timeline is held to
41 /// ([`matches_timeline`]).41 /// ([`matches_timeline`]).
42 ///42 ///
43-/// ponytail: a 25 fps video refused by an audio-only timeline it could have43+/// ponytail: a 25 fps video imported onto an audio-only timeline it could have
44-/// defined is the ceiling here. Upgrade path is adopting the first *picture's*44+/// defined plays at 25 fps, correctly, but on a 30 fps timeline -- it is read
45-/// rate and codec on import, which means retiming every audio clip already45+/// through [`Rate`] like any other file shot at another rate rather than
46-/// placed in frames.46+/// defining one. Upgrade path is adopting the first *picture's* rate and codec
47+/// on import, which means retiming every audio clip already placed in frames.
47 const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0);48 const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0);
48 49
49 /// The frame rate a timeline scaffolded from a still image runs at, for50 /// The frame rate a timeline scaffolded from a still image runs at, for
@@ -193,6 +194,20 @@ pub struct PlaybackSession {
193 /// not -- with the single exception `sources` itself has,194 /// not -- with the single exception `sources` itself has,
194 /// [`Self::remove_source`], which takes the same entry out of both.195 /// [`Self::remove_source`], which takes the same entry out of both.
195 counts: Vec<u32>,196 counts: Vec<u32>,
197+ /// What each source's own frame rate is against this timeline's, indexed
198+ /// and grown exactly as [`Self::counts`] is (and shortened with it by
199+ /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the
200+ /// timeline's rate -- and for a still and a song, which have no rate of
201+ /// their own -- so a single-rate project converts nothing anywhere.
202+ ///
203+ /// A clip counts *timeline* frames ([`Rate`]); this is the one thing that
204+ /// knows which frames of the file those are, and only
205+ /// [`start_span`](Self::start_span) and [`try_frame`](Self::try_frame) ask.
206+ rates: Vec<Rate>,
207+ /// The rate of the source the current worker is decoding, kept beside
208+ /// [`Self::span`] because the frames coming back are numbered in *its*
209+ /// file's frames and nothing else can put them back on the timeline.
210+ span_rate: Rate,
196 /// What the current video worker was opened for: where it sits on the211 /// What the current video worker was opened for: where it sits on the
197 /// timeline, how long it runs, and which source frame it started at --212 /// timeline, how long it runs, and which source frame it started at --
198 /// together they rewrite a source frame index into a timeline one. Not a213 /// together they rewrite a source frame index into a timeline one. Not a
@@ -265,6 +280,9 @@ impl PlaybackSession {
265 audio_disabled,280 audio_disabled,
266 project,281 project,
267 counts: vec![meta.frame_count],282 counts: vec![meta.frame_count],
283+ // Source 0 *is* the timeline's rate: it defined it.
284+ rates: vec![Rate::REAL_TIME],
285+ span_rate: Rate::REAL_TIME,
268 span,286 span,
269 eos: false,287 eos: false,
270 })288 })
@@ -365,6 +383,9 @@ impl PlaybackSession {
365 audio_disabled,383 audio_disabled,
366 project,384 project,
367 counts: vec![meta.frame_count],385 counts: vec![meta.frame_count],
386+ // Source 0 *is* the timeline's rate: it defined it.
387+ rates: vec![Rate::REAL_TIME],
388+ span_rate: Rate::REAL_TIME,
368 span,389 span,
369 eos: false,390 eos: false,
370 })391 })
@@ -431,6 +452,9 @@ impl PlaybackSession {
431 audio_disabled: None,452 audio_disabled: None,
432 project,453 project,
433 counts: vec![meta.frame_count],454 counts: vec![meta.frame_count],
455+ // Source 0 *is* the timeline's rate: it defined it.
456+ rates: vec![Rate::REAL_TIME],
457+ span_rate: Rate::REAL_TIME,
434 span,458 span,
435 eos: false,459 eos: false,
436 })460 })
@@ -529,6 +553,11 @@ impl PlaybackSession {
529 let first_audio = first_audio_of(&doc.sources)?;553 let first_audio = first_audio_of(&doc.sources)?;
530 554
531 let mut counts = vec![meta.frame_count];555 let mut counts = vec![meta.frame_count];
556+ // Source 0 defines the rate, so it is read frame for frame; every other
557+ // one is however long it is *in this timeline's frames*, which is the
558+ // length `import` noted for it and the wall the clip check below holds
559+ // it to.
560+ let mut rates = vec![Rate::REAL_TIME];
532 for source in &doc.sources[1..] {561 for source in &doc.sources[1..] {
533 // A still has neither a rate to match nor a track to match with:562 // A still has neither a rate to match nor a track to match with:
534 // its length is the one it is held to, recomputed exactly as the563 // its length is the one it is held to, recomputed exactly as the
@@ -538,6 +567,7 @@ impl PlaybackSession {
538 crate::decode::image_size(&source.path)567 crate::decode::image_size(&source.path)
539 .map_err(|e| format!("source {}: {e}", source.path.display()))?;568 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
540 counts.push(image_frames(meta.frame_rate));569 counts.push(image_frames(meta.frame_rate));
570+ rates.push(Rate::REAL_TIME);
541 continue;571 continue;
542 }572 }
543 // A source with no picture is checked on what it does have, and573 // A source with no picture is checked on what it does have, and
@@ -547,13 +577,16 @@ impl PlaybackSession {
547 audio_matches(source, &first_audio)577 audio_matches(source, &first_audio)
548 .map_err(|e| format!("source {}: {e}", source.path.display()))?;578 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
549 counts.push(audio_frames(&source.path, meta.frame_rate)?);579 counts.push(audio_frames(&source.path, meta.frame_rate)?);
580+ rates.push(Rate::REAL_TIME);
550 continue;581 continue;
551 }582 }
552 let (other, _) = Demuxer::open(&source.path)583 let (other, _) = Demuxer::open(&source.path)
553 .map_err(|e| format!("source {}: {e}", source.path.display()))?;584 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
554 matches_timeline(source, &other, &meta, &first_audio)585 matches_timeline(source, &other, &meta, &first_audio)
555 .map_err(|e| format!("source {}: {e}", source.path.display()))?;586 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
556- counts.push(other.frame_count);587+ let rate = Rate::new(other.frame_rate, meta.frame_rate);
588+ counts.push(rate.timeline_at(other.frame_count));
589+ rates.push(rate);
557 }590 }
558 // The video lane can only play files that have pictures. Hand-written591 // The video lane can only play files that have pictures. Hand-written
559 // (or hand-edited) project files are the one door this can come in592 // (or hand-edited) project files are the one door this can come in
@@ -619,6 +652,8 @@ impl PlaybackSession {
619 audio_disabled,652 audio_disabled,
620 project,653 project,
621 counts,654 counts,
655+ rates,
656+ span_rate: Rate::REAL_TIME,
622 span,657 span,
623 eos: false,658 eos: false,
624 };659 };
@@ -687,9 +722,15 @@ impl PlaybackSession {
687 // (`speed_maps_both_ways`). An empty timeline has no span,722 // (`speed_maps_both_ways`). An empty timeline has no span,
688 // and its one black frame is frame 0. Real time is the723 // and its one black frame is frame 0. Real time is the
689 // arithmetic this always did, frame for frame.724 // arithmetic this always did, frame for frame.
690- frame.index = self725+ // ...through the file's own rate first, which is the ceil
691- .span726+ // half of *that* pair: the picture at source frame `i` is
692- .map_or(frame.index, |s| s.timeline_at(frame.index));727+ // due at the first timeline-rate frame that shows it, and a
728+ // slower file's picture is therefore held for the frames in
729+ // between. Real time for a gap and for a single-rate
730+ // project, where this is the identity.
731+ frame.index = self.span.map_or(frame.index, |s| {
732+ s.timeline_at(self.span_rate.timeline_at(frame.index))
733+ });
693 return Some(frame);734 return Some(frame);
694 }735 }
695 Err(TryRecvError::Empty) => return None,736 Err(TryRecvError::Empty) => return None,
@@ -759,6 +800,14 @@ impl PlaybackSession {
759 /// timeline still moves, there are simply no more pictures, and the800 /// timeline still moves, there are simply no more pictures, and the
760 /// disconnected receiver carries the session on to the next span.801 /// disconnected receiver carries the session on to the next span.
761 fn start_span(&mut self, span: Option<Span>) {802 fn start_span(&mut self, span: Option<Span>) {
803+ // Which file's frames the worker about to be opened will number its
804+ // pictures in: the span's own source, and real time for a gap, whose
805+ // black worker counts timeline frames already. Set before the open,
806+ // because the open is the first thing that converts with it.
807+ self.span_rate = match span.and_then(|s| s.from) {
808+ Some((source, _)) => self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME),
809+ None => Rate::REAL_TIME,
810+ };
762 let opened = match span {811 let opened = match span {
763 // The grade is the composite's at this frame -- the same clip the812 // The grade is the composite's at this frame -- the same clip the
764 // span itself came from -- and it is constant across the span, so813 // span itself came from -- and it is constant across the span, so
@@ -795,10 +844,17 @@ impl PlaybackSession {
795 ..844 ..
796 }) => DecodeSession::open_worker(845 }) => DecodeSession::open_worker(
797 &self.project.sources()[source].path,846 &self.project.sources()[source].path,
798- in_frame,847+ // The file's own frames, which is the only place they exist:
848+ // a clip counts the timeline's ([`Rate`]).
849+ self.span_rate.source_at(in_frame),
799 // Source frames, which a speed makes more (or fewer) than the850 // Source frames, which a speed makes more (or fewer) than the
800- // timeline frames the span covers.851+ // timeline frames the span covers -- and which a file shot at
801- in_frame + span.expect("matched above").source_len(),852+ // another rate makes fewer (or more) again. One past the last
853+ // frame this span shows, not one past its length: at another
854+ // rate those are two different frames.
855+ self.span_rate.source_at(
856+ in_frame + span.expect("matched above").source_len().saturating_sub(1),
857+ ) + 1,
802 self.project858 self.project
803 .composite_color_at(start)859 .composite_color_at(start)
804 .copied()860 .copied()
@@ -1074,13 +1130,29 @@ impl PlaybackSession {
1074 self.project.trim_room(lane, idx, edge, &self.counts)1130 self.project.trim_room(lane, idx, edge, &self.counts)
1075 }1131 }
1076 1132
1077- /// Records how long a source is, for a source index that may be one1133+ /// Records how long a source is and what rate it was shot at, for a source
1078- /// `Project::import` just made or one it handed back. See [`Self::counts`].1134+ /// index that may be one `Project::import` just made or one it handed back.
1079- fn note_frames(&mut self, source: usize, frames: u32) {1135+ /// See [`Self::counts`] and [`Self::rates`], which are one table in two
1136+ /// vectors and grow together.
1137+ fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) {
1080 if source == self.counts.len() {1138 if source == self.counts.len() {
1081 self.counts.push(frames);1139 self.counts.push(frames);
1140+ self.rates.push(rate);
1082 }1141 }
1083 debug_assert_eq!(self.counts.len(), self.project.sources().len());1142 debug_assert_eq!(self.counts.len(), self.project.sources().len());
1143+ debug_assert_eq!(self.rates.len(), self.counts.len());
1144+ }
1145+
1146+ /// The rate noted for whichever source plays `path`, by
1147+ /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however
1148+ /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session
1149+ /// has never taken in.
1150+ fn file_rate(&self, path: &Path) -> Rate {
1151+ self.project
1152+ .sources()
1153+ .iter()
1154+ .position(|s| s.path == path)
1155+ .map_or(Rate::REAL_TIME, |i| self.rates[i])
1084 }1156 }
1085 1157
1086 /// How long the whole of `path` is, in timeline frames: the length noted1158 /// How long the whole of `path` is, in timeline frames: the length noted
@@ -1102,6 +1174,19 @@ impl PlaybackSession {
1102 .map_or(0, |i| self.counts[i])1174 .map_or(0, |i| self.counts[i])
1103 }1175 }
1104 1176
1177+ /// What rate the file at `path` was *shot* at, in frames per second -- which
1178+ /// is the timeline's own rate for every source that shares it, and is not
1179+ /// for one placed at another ([`Rate`]). By path like
1180+ /// [`file_frames`](Self::file_frames), and the timeline's rate for a file
1181+ /// this session has never taken in (and for a still and a song, which were
1182+ /// shot at no rate at all).
1183+ ///
1184+ /// What a library row names the file with: the timeline's rate there would
1185+ /// be a lie about a 23.976 fps file the moment one can join.
1186+ pub fn file_fps(&self, path: &Path) -> f64 {
1187+ self.file_rate(path).as_f64() * self.meta.frame_rate
1188+ }
1189+
1105 /// The clip the picture is coming from at `timeline_secs`: the lane it sits1190 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
1106 /// on and its index there, by the same topmost-lane-wins rule the decoder1191 /// on and its index there, by the same topmost-lane-wins rule the decoder
1107 /// follows. `None` over a gap and past the end. What a card that grades1192 /// follows. `None` over a gap and past the end. What a card that grades
@@ -1258,8 +1343,9 @@ impl PlaybackSession {
1258 let first = self.first_audio()?;1343 let first = self.first_audio()?;
1259 audio_matches(&wanted, &first)?;1344 audio_matches(&wanted, &first)?;
1260 }1345 }
1346+ let rate = self.file_rate(&wanted.path);
1261 let source = self.project.import(path, stream);1347 let source = self.project.import(path, stream);
1262- self.note_frames(source, frames);1348+ self.note_frames(source, frames, rate);
1263 let clip = Clip {1349 let clip = Clip {
1264 start: 0,1350 start: 0,
1265 in_frame: 0,1351 in_frame: 0,
@@ -1334,6 +1420,7 @@ impl PlaybackSession {
1334 // count one index late.1420 // count one index late.
1335 if idx < self.counts.len() {1421 if idx < self.counts.len() {
1336 self.counts.remove(idx);1422 self.counts.remove(idx);
1423+ self.rates.remove(idx);
1337 }1424 }
1338 let now = self.now();1425 let now = self.now();
1339 self.seek(now);1426 self.seek(now);
@@ -1387,11 +1474,14 @@ impl PlaybackSession {
1387 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take1474 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take
1388 /// back, and nothing reseeks.1475 /// back, and nothing reseeks.
1389 ///1476 ///
1390- /// Refused unless it can join the timeline -- same codec, same frame rate,1477+ /// Refused unless it can join the timeline -- same codec, same audio
1391- /// same audio parameters or both silent; the `Err` names the property that1478+ /// parameters or both silent; the `Err` names the property that disagrees,
1392- /// disagrees, for a caller to show. Nothing is changed by a refusal. A1479+ /// for a caller to show. Nothing is changed by a refusal. A *resolution* of
1393- /// *resolution* of its own is not a refusal: the clip is placed on the1480+ /// its own is not a refusal: the clip is placed on the project canvas by its
1394- /// project canvas by its fit policy ([`PlaybackSession::set_fit`]).1481+ /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame
1482+ /// rate* of its own: the file is placed for the seconds it lasts and read at
1483+ /// [`Rate`] against the timeline's rate, so it plays at the speed it was
1484+ /// shot at.
1395 pub fn import(&mut self, path: &Path) -> crate::Result<usize> {1485 pub fn import(&mut self, path: &Path) -> crate::Result<usize> {
1396 if crate::is_audio(path) {1486 if crate::is_audio(path) {
1397 return self.import_audio(path);1487 return self.import_audio(path);
@@ -1406,7 +1496,11 @@ impl PlaybackSession {
1406 // its streams reaches the timeline afterwards.1496 // its streams reaches the timeline afterwards.
1407 matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?;1497 matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?;
1408 let source = self.project.import(path, 0);1498 let source = self.project.import(path, 0);
1409- self.note_frames(source, meta.frame_count);1499+ // Its length *on this timeline*: a file shot slower than the timeline
1500+ // runs covers more frames than it holds, which is the whole of what
1501+ // placing it at another rate means ([`Rate`]).
1502+ let rate = Rate::new(meta.frame_rate, self.meta.frame_rate);
1503+ self.note_frames(source, rate.timeline_at(meta.frame_count), rate);
1410 Ok(source)1504 Ok(source)
1411 }1505 }
1412 1506
@@ -1426,7 +1520,7 @@ impl PlaybackSession {
1426 audio_matches(&Source::new(path, 0), &first)?;1520 audio_matches(&Source::new(path, 0), &first)?;
1427 let frames = audio_frames(path, self.meta.frame_rate)?;1521 let frames = audio_frames(path, self.meta.frame_rate)?;
1428 let source = self.project.import(path, 0);1522 let source = self.project.import(path, 0);
1429- self.note_frames(source, frames);1523+ self.note_frames(source, frames, Rate::REAL_TIME);
1430 Ok(source)1524 Ok(source)
1431 }1525 }
1432 1526
@@ -1450,7 +1544,7 @@ impl PlaybackSession {
1450 .into());1544 .into());
1451 }1545 }
1452 let source = self.project.import(path, 0);1546 let source = self.project.import(path, 0);
1453- self.note_frames(source, image_frames(self.meta.frame_rate));1547+ self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME);
1454 Ok(source)1548 Ok(source)
1455 }1549 }
1456 1550
@@ -1717,10 +1811,9 @@ impl Drop for PlaybackSession {
1717 /// *Not* the same size any more. A project has its own resolution1811 /// *Not* the same size any more. A project has its own resolution
1718 /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its1812 /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its
1719 /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a1813 /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a
1720-/// letterboxed clip rather than a refusal. The frame rate stays refused on1814+/// letterboxed clip rather than a refusal, and so is a frame rate of its own:
1721-/// purpose: mixing rates means resampling the *timeline*, which is a different1815+/// the timeline keeps its own rate and the file is read at [`Rate`] against it
1722-/// problem from resampling a picture, and a refusal is the honest answer until1816+/// ([`PlaybackSession::import`] notes how long it is *here*).
1723-/// it is solved.
1724 ///1817 ///
1725 /// The `Err` names the property that disagrees, and those strings are what a1818 /// The `Err` names the property that disagrees, and those strings are what a
1726 /// front-end shows verbatim; [`PlaybackSession::import`] and1819 /// front-end shows verbatim; [`PlaybackSession::import`] and
@@ -1744,14 +1837,10 @@ fn matches_timeline(
1744 )1837 )
1745 .into());1838 .into());
1746 }1839 }
1747- // Container frame rates are computed from timescales, so never `==`.1840+ // The frame rate is *not* one of these: a file shot at another rate is
1748- if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 {1841+ // placed for the seconds it lasts and read through [`Rate`] at the
1749- return Err(format!(1842+ // decoder's door, so it plays at the speed it was shot at on a timeline
1750- "{:.3} fps does not match the timeline's {:.3} fps",1843+ // that counts frames faster or slower.
1751- meta.frame_rate, timeline.frame_rate
1752- )
1753- .into());
1754- }
1755 audio_matches(source, first)1844 audio_matches(source, first)
1756 }1845 }
1757 1846
crates/engine/src/project.rsmodified+160 -0
@@ -221,9 +221,97 @@ impl std::fmt::Display for Speed {
221 }221 }
222 }222 }
223 223
224+/// What a file's own frame rate is against the timeline's, as an exact rational
225+/// in thousandths of a frame per second: how many frames of the *file* one frame
226+/// of the timeline is worth.
227+///
228+/// Every frame number in this module counts **timeline** frames -- a clip's
229+/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
230+/// timeline is as many frames long as the seconds it lasts, and every edit
231+/// (trim, split, speed, paste) is the same arithmetic it always was. This is the
232+/// one conversion, and it happens at the decoder's door: [`PlaybackSession`]
233+/// opens a worker with it and [`crate::export`] pulls pictures through it. The
234+/// file's own numbering exists nowhere else.
235+///
236+/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an
237+/// export encodes at a timeline frame has to be the frame playback is holding
238+/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
239+/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
240+///
241+/// ponytail: the rate is rounded to milli-fps, so 24000/1001 is carried as
242+/// 23.976 -- about a frame per 40000, or a frame off after seven hours of one
243+/// clip. Upgrade path is carrying the container's own timescale rational in
244+/// [`crate::VideoMeta`] and building this from it.
245+///
246+/// [`PlaybackSession`]: crate::PlaybackSession
247+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
248+pub struct Rate {
249+ /// Milli-fps of the file...
250+ source: u64,
251+ /// ...and of the timeline it plays on.
252+ timeline: u64,
253+}
254+
255+impl Rate {
256+ /// A file shot at the timeline's own rate: every conversion below is the
257+ /// identity, which is the path a single-rate project is on.
258+ pub const REAL_TIME: Self = Self {
259+ source: 1,
260+ timeline: 1,
261+ };
262+
263+ /// The rate of a file at `source_fps` on a timeline at `timeline_fps`.
264+ /// Rounded to milli-fps, and [`REAL_TIME`](Self::REAL_TIME) for the rates
265+ /// that agree there -- container rates are computed from timescales, so
266+ /// "the same rate" is never `==` either.
267+ pub fn new(source_fps: f64, timeline_fps: f64) -> Self {
268+ let milli = |fps: f64| match fps.is_finite() && fps > 0. {
269+ true => (fps * 1000.).round().clamp(1., 1e9) as u64,
270+ // Not a rate at all: read the file frame for frame rather than
271+ // dividing the timeline by a zero.
272+ false => 0,
273+ };
274+ match (milli(source_fps), milli(timeline_fps)) {
275+ (0, _) | (_, 0) => Self::REAL_TIME,
276+ (source, timeline) if source == timeline => Self::REAL_TIME,
277+ (source, timeline) => Self { source, timeline },
278+ }
279+ }
280+
281+ pub fn is_real_time(self) -> bool {
282+ self.source == self.timeline
283+ }
284+
285+ /// As a multiplier of the timeline's rate: what a *file's* own frame rate
286+ /// is, given the timeline's, for a library row that names it.
287+ pub fn as_f64(self) -> f64 {
288+ self.source as f64 / self.timeline as f64
289+ }
290+
291+ /// Which frame of the file the `frame`th timeline-rate frame of it is:
292+ /// floored, [`Speed::source_at`]'s half of the pair.
293+ pub fn source_at(self, frame: u32) -> u32 {
294+ (u64::from(frame) * self.source / self.timeline).min(u64::from(u32::MAX)) as u32
295+ }
296+
297+ /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
298+ /// timeline-rate frame that shows source frame `source_frame` -- which is
299+ /// the stamp playback puts on a decoded picture, and, applied to a file's
300+ /// frame *count*, how long that file is in timeline frames.
301+ pub fn timeline_at(self, source_frame: u32) -> u32 {
302+ (u64::from(source_frame) * self.timeline)
303+ .div_ceil(self.source)
304+ .min(u64::from(u32::MAX)) as u32
305+ }
306+}
307+
224 /// A half-open `[in_frame, out_frame)` range of frames of source308 /// A half-open `[in_frame, out_frame)` range of frames of source
225 /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).309 /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
226 /// Never empty.310 /// Never empty.
311+///
312+/// Counted at the **timeline's** frame rate, not the file's: a source shot at
313+/// another rate is converted at the decoder's door ([`Rate`]), so every edit
314+/// here is frames of one clock.
227 #[derive(Clone, Copy, PartialEq, Eq, Debug)]315 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
228 pub struct Clip {316 pub struct Clip {
229 /// Timeline frame the clip's first frame is shown at. Meaningless on a317 /// Timeline frame the clip's first frame is shown at. Meaningless on a
@@ -4539,6 +4627,78 @@ mod tests {
4539 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");4627 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
4540 }4628 }
4541 4629
4630+ /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
4631+ /// export encodes at a timeline frame is the one playback is holding there,
4632+ /// a file is as long in timeline frames as the seconds it lasts, and the two
4633+ /// compose so a speeded clip at another rate is exactly both.
4634+ #[test]
4635+ fn rate_composes_with_speed() {
4636+ // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
4637+ // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
4638+ // the identity map or a single-rate project would move.
4639+ for (source_fps, timeline_fps) in [
4640+ (24000. / 1001., 30.),
4641+ (30., 24000. / 1001.),
4642+ (60., 30.),
4643+ (25., 30.),
4644+ (30., 30.),
4645+ ] {
4646+ let rate = Rate::new(source_fps, timeline_fps);
4647+ for n in 0..2000u32 {
4648+ let source = rate.source_at(n);
4649+ // The stamp is the *first* timeline-rate frame that shows it, so
4650+ // the picture on screen at `n` is the picture encoded at `n`.
4651+ let held = (0..=source + 4)
4652+ .filter(|&s| rate.timeline_at(s) <= n)
4653+ .next_back();
4654+ assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
4655+ }
4656+ // A file of `count` frames is `timeline_at(count)` frames long here,
4657+ // and its last one still reads a frame the file has.
4658+ for count in 1..500u32 {
4659+ let frames = rate.timeline_at(count);
4660+ assert!(frames >= 1, "a file is never zero frames long");
4661+ assert!(
4662+ rate.source_at(frames - 1) < count,
4663+ "{source_fps} on {timeline_fps}: {count} frames reads past the file"
4664+ );
4665+ }
4666+ // No drift: the mapping is one exact division, not an accumulation,
4667+ // so an hour in is as true as the first second. (`Rate` rounds the
4668+ // rate itself to milli-fps -- 23.976 for 24000/1001 -- which is the
4669+ // 3e-8 the tolerance below allows for.)
4670+ let milli = |fps: f64| (fps * 1000.).round();
4671+ for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
4672+ let want = f64::from(n) * milli(source_fps) / milli(timeline_fps);
4673+ assert!(
4674+ (f64::from(rate.source_at(n)) - want).abs() < 1.,
4675+ "{source_fps} on {timeline_fps}: frame {n} drifted"
4676+ );
4677+ }
4678+ }
4679+ // The timeline's own rate is the identity, whichever way it is written.
4680+ assert!(Rate::new(30., 30.).is_real_time());
4681+ assert!(Rate::new(30.0004, 30.).is_real_time(), "milli-fps rounding");
4682+ assert!(Rate::new(0., 30.).is_real_time(), "not a rate at all");
4683+ for n in 0..1000 {
4684+ assert_eq!(Rate::REAL_TIME.source_at(n), n);
4685+ assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
4686+ }
4687+ // ...and the composition, in the order the decoder's door applies it:
4688+ // the speed picks the clip's (timeline-rate) frame, the rate picks the
4689+ // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
4690+ // timeline frames per frame shown, each of them 0.799 of a file frame.
4691+ let rate = Rate::new(24000. / 1001., 30.);
4692+ let speed = Speed::from_permille(2000);
4693+ for d in 0..100u32 {
4694+ assert_eq!(
4695+ rate.source_at(speed.source_at(d)),
4696+ (u64::from(d) * 2 * 23976 / 30000) as u32,
4697+ "2x of a 23.976 fps file at timeline frame {d}"
4698+ );
4699+ }
4700+ }
4701+
4542 /// The mapping a speed changes, and the one it does not: a 2x clip reads two4702 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
4543 /// source frames per timeline frame and still starts at its own in-point,4703 /// source frames per timeline frame and still starts at its own in-point,
4544 /// and a half-speed one shows every source frame twice.4704 /// and a half-speed one shows every source frame twice.
crates/engine/tests/audio_files.rsmodified+9 -8
@@ -386,20 +386,21 @@ fn a_video_joins_a_timeline_a_song_started() {
386 import_and_place(&mut session, &asset("test_av.mp4"));386 import_and_place(&mut session, &asset("test_av.mp4"));
387 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last");387 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last");
388 assert_eq!(session.lane_clips(Lane::A1).len(), 2);388 assert_eq!(session.lane_clips(Lane::A1).len(), 2);
389- // And a file at another rate is refused in the timeline's own words rather389+ // A sample rate the device cannot have two of is still refused in the
390- // than silently retiming the song already on the lane -- the sample rate at390+ // timeline's own words...
391- // one door, the *frame* rate at the other: the canvas a song scaffolds has
392- // a frame rate of its own (30 fps), and a 25 fps picture cannot join it.
393 let e = refusal(session.import(&asset("test_tone_48k.wav")));391 let e = refusal(session.import(&asset("test_tone_48k.wav")));
394 assert_eq!(392 assert_eq!(
395 e,393 e,
396 "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch"394 "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch"
397 );395 );
398- assert_eq!(
399- refusal(session.import(&asset("test_25fps.mp4"))),
400- "25.000 fps does not match the timeline's 30.000 fps"
401- );
402 assert_eq!(session.sources().len(), 2, "a refusal left a library row");396 assert_eq!(session.sources().len(), 2, "a refusal left a library row");
397+ // ...but a *frame* rate of its own is not a refusal: the canvas a song
398+ // scaffolds runs at 30 fps and a 25 fps picture joins it at the length it
399+ // lasts in seconds (50 frames of file, 60 of timeline).
400+ session
401+ .import(&asset("test_25fps.mp4"))
402+ .expect("25 fps joins the 30 fps canvas a song scaffolded");
403+ assert_eq!(session.file_frames(&asset("test_25fps.mp4")), 60);
403 }404 }
404 405
405 /// Blocks until the export settles, whichever way it settled.406 /// Blocks until the export settles, whichever way it settled.
crates/engine/tests/mixed_fps.rsadded+280 -0
@@ -0,0 +1,280 @@
1+//! Clips shot at other frame rates on one timeline: what a 25 fps and a 23.976
2+//! fps file do on the 30 fps timeline `test_av.mp4` scaffolds.
3+//!
4+//! Everything goes through the front door -- `import`, `place_stream_at`,
5+//! `seek`, `export_to_with`, `open_project` -- because the whole claim is that a
6+//! *user* can put two rates on one timeline and watch both at the speed they
7+//! were shot at. `project.rs`'s own `rate_composes_with_speed` owns the
8+//! arithmetic; what is measured here is that the pictures and the file agree
9+//! with it.
10+//!
11+//! ```text
12+//! cargo test -p engine --test mixed_fps
13+//! ```
14+
15+use std::path::{Path, PathBuf};
16+use std::thread::sleep;
17+use std::time::{Duration, Instant};
18+
19+use engine::export::{ExportSettings, Format};
20+use engine::project::{Edge, Lane, Speed};
21+use engine::{DecodeSession, Frame, PlaybackSession};
22+
23+/// The timeline's rate, which `test_av.mp4` (30 fps, 5 s) defines.
24+const FPS: f64 = 30.0;
25+
26+fn asset(name: &str) -> PathBuf {
27+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
28+ .join("../../assets")
29+ .join(name)
30+}
31+
32+/// Silent, for `tests/playback.rs`'s reason: the suite plays real files.
33+fn open(path: impl AsRef<Path>) -> PlaybackSession {
34+ let session = PlaybackSession::open(path).expect("open");
35+ session.set_gain(0.0);
36+ session
37+}
38+
39+fn next_frame(session: &mut PlaybackSession, what: &str) -> Frame {
40+ let deadline = Instant::now() + Duration::from_secs(10);
41+ loop {
42+ if let Some(frame) = session.try_frame() {
43+ return frame;
44+ }
45+ assert!(Instant::now() < deadline, "no frame after {what}");
46+ sleep(Duration::from_millis(4));
47+ }
48+}
49+
50+/// One frame of a file, decoded straight from it: the picture a mapping is
51+/// checked against, in the file's *own* numbering.
52+fn source_frame(path: &Path, index: u32) -> Vec<u8> {
53+ let (_, rx, _cancel) = DecodeSession::open_range(path, index, index + 1).expect("open_range");
54+ let frame = rx
55+ .recv_timeout(Duration::from_secs(10))
56+ .expect("reference frame");
57+ assert_eq!(frame.index, index, "open_range starts where it is told");
58+ frame.bgra
59+}
60+
61+/// Imports `path` and drags it onto the end of the timeline, the way a library
62+/// row reaches a lane.
63+fn import_and_place(session: &mut PlaybackSession, path: &Path) {
64+ session.import(path).expect("the file joins this timeline");
65+ let end = session.timeline_duration();
66+ assert!(
67+ session
68+ .place_stream_at(end, path, 0, None)
69+ .expect("a file just imported is on this timeline"),
70+ "the drag onto the end of the timeline"
71+ );
72+}
73+
74+fn wait(handle: &engine::ExportHandle) -> engine::Result<()> {
75+ let deadline = Instant::now() + Duration::from_secs(180);
76+ while !handle.is_finished() {
77+ assert!(Instant::now() < deadline, "export did not finish");
78+ sleep(Duration::from_millis(20));
79+ }
80+ handle.result().expect("a finished export has an outcome")
81+}
82+
83+/// How different two pictures are, sampled: a re-encode moves every pixel a
84+/// little and a *different* picture of `testsrc2` moves them a lot, so the two
85+/// are never close to the threshold below.
86+fn difference(a: &[u8], b: &[u8]) -> f64 {
87+ assert_eq!(a.len(), b.len(), "two pictures of one size");
88+ let (mut sum, mut n) = (0f64, 0u32);
89+ for i in (0..a.len()).step_by(997) {
90+ sum += f64::from(a[i].abs_diff(b[i]));
91+ n += 1;
92+ }
93+ sum / f64::from(n.max(1))
94+}
95+
96+/// A file's length is the seconds it lasts, in the timeline's frames -- not the
97+/// frames it holds. That is the whole of what placing another rate means: 50
98+/// frames of 25 fps and 48 of 23.976 fps are both two seconds, and two seconds
99+/// of a 30 fps timeline is 60 frames.
100+#[test]
101+fn a_file_at_another_rate_is_placed_for_the_seconds_it_lasts() {
102+ let mut session = open(asset("test_av.mp4"));
103+ assert_eq!(session.file_frames(&asset("test_av.mp4")), 150, "5 s at 30");
104+
105+ let pal = asset("test_25fps.mp4");
106+ session
107+ .import(&pal)
108+ .expect("25 fps joins a 30 fps timeline");
109+ assert_eq!(session.file_frames(&pal), 60, "50 frames at 25 fps is 2 s");
110+
111+ // 24000/1001: 48 frames is 2.002 s, which is 60.06 frames of 30 fps --
112+ // rounded *up*, so the last picture is still reachable by a trim.
113+ let ntsc = asset("test_23976fps.mp4");
114+ session.import(&ntsc).expect("23.976 joins it too");
115+ assert_eq!(session.file_frames(&ntsc), 61);
116+
117+ // ...and placed, both are as long on the timeline as they are in the ear.
118+ let end = session.timeline_duration();
119+ session
120+ .place_stream_at(end, &pal, 0, None)
121+ .expect("the drag");
122+ assert!(
123+ (session.timeline_duration() - (5.0 + 2.0)).abs() < 1e-9,
124+ "a 2 s clip made the timeline {} s",
125+ session.timeline_duration()
126+ );
127+ let end = session.timeline_duration();
128+ session
129+ .place_stream_at(end, &ntsc, 0, None)
130+ .expect("the drag");
131+ assert!(
132+ (session.timeline_duration() - (5.0 + 2.0 + 61. / FPS)).abs() < 1e-9,
133+ "{} s",
134+ session.timeline_duration()
135+ );
136+}
137+
138+/// The picture on screen at a timeline frame is the picture the *file* holds
139+/// there: frame `floor(offset * 25/30)` of a 25 fps clip, which is what playing
140+/// at the speed it was shot at means, frame for frame.
141+#[test]
142+fn playback_shows_the_frame_the_file_holds_there() {
143+ let pal = asset("test_25fps.mp4");
144+ let mut session = open(asset("test_av.mp4"));
145+ import_and_place(&mut session, &pal);
146+ session.pause();
147+ // The clip starts at timeline frame 150 (5 s) and runs 60 frames.
148+ let start = 150u32;
149+ for offset in [0u32, 1, 5, 6, 29, 30, 47, 59] {
150+ let at = start + offset;
151+ session.seek(f64::from(at) / FPS);
152+ let landed = next_frame(&mut session, "a seek into the 25 fps clip");
153+ assert_eq!(landed.index, at, "a seek lands on the frame it asked for");
154+ let want = (u64::from(offset) * 25_000 / 30_000) as u32;
155+ assert!(
156+ landed.bgra == source_frame(&pal, want),
157+ "timeline frame {at} (offset {offset}) is not source frame {want}"
158+ );
159+ }
160+ // Past the last picture the file holds, the clip is still on the timeline:
161+ // its last frame is shown, not black and not a panic.
162+ session.seek(f64::from(start + 59) / FPS);
163+ let last = next_frame(&mut session, "the last frame of the clip");
164+ assert!(last.bgra == source_frame(&pal, 49), "source frame 49 last");
165+}
166+
167+/// A speed and a frame rate compose: a 2x 25 fps clip on a 30 fps timeline is
168+/// half as many timeline frames and reads twice as far into the file for each
169+/// of them.
170+#[test]
171+fn a_speeded_clip_at_another_rate_is_exactly_both() {
172+ let pal = asset("test_25fps.mp4");
173+ let mut session = open(asset("test_av.mp4"));
174+ import_and_place(&mut session, &pal);
175+ session
176+ .set_speed(Lane::V1, 1, Speed::from_permille(2000))
177+ .expect("nothing is in the way of a clip that got shorter");
178+ session.pause();
179+ let start = 150u32;
180+ assert!(
181+ (session.timeline_duration() - (5.0 + 1.0)).abs() < 1e-9,
182+ "2 s at 2x is 1 s: {}",
183+ session.timeline_duration()
184+ );
185+ for offset in [0u32, 3, 14, 29] {
186+ let at = start + offset;
187+ session.seek(f64::from(at) / FPS);
188+ let landed = next_frame(&mut session, "a seek into the speeded clip");
189+ assert_eq!(landed.index, at);
190+ // The speed picks the clip's (timeline-rate) frame, the rate picks the
191+ // file's -- in that order, which is the order the decoder's door
192+ // applies them.
193+ let want = (u64::from(offset) * 2 * 25_000 / 30_000) as u32;
194+ assert!(
195+ landed.bgra == source_frame(&pal, want),
196+ "2x at offset {offset} is not source frame {want}"
197+ );
198+ }
199+}
200+
201+/// A saved project reloads at the same lengths: `open_project` recomputes every
202+/// source's rate from the file, so a mixed-rate timeline is not one that only
203+/// the session that built it could hold.
204+#[test]
205+fn a_mixed_rate_project_reloads_unchanged() {
206+ let pal = asset("test_25fps.mp4");
207+ let mut session = open(asset("test_av.mp4"));
208+ import_and_place(&mut session, &pal);
209+ let duration = session.timeline_duration();
210+ let spans = session.clip_spans();
211+ let path = std::env::temp_dir().join(format!("edith-mixed-{}.edith", std::process::id()));
212+ session.save_project(&path).expect("save");
213+
214+ let reloaded = PlaybackSession::open_project(&path).expect("a mixed-rate project reopens");
215+ assert_eq!(reloaded.clip_spans(), spans, "the same clips, in seconds");
216+ assert!((reloaded.timeline_duration() - duration).abs() < 1e-9);
217+ assert_eq!(reloaded.file_frames(&pal), 60, "the length was recomputed");
218+ std::fs::remove_file(&path).ok();
219+}
220+
221+/// The export is what was watched: as many frames as the timeline has, and the
222+/// 25 fps clip walked through its file at 25 fps -- 25 pictures over 30 frames,
223+/// not 30 of them and not 25 held to the end.
224+#[test]
225+fn an_export_of_two_rates_runs_at_the_speed_it_was_shot() {
226+ let pal = asset("test_25fps.mp4");
227+ let mut session = open(asset("test_av.mp4"));
228+ // A short head of the 30 fps take, then the whole of the 25 fps one --
229+ // enough of each to be a mixed timeline, short enough to encode in a test.
230+ // The sound comes with it: a placed take is one linked group.
231+ assert!(
232+ session.trim_clip(Lane::V1, 0, Edge::End, 15),
233+ "trim the 30 fps take to half a second"
234+ );
235+ import_and_place(&mut session, &pal);
236+ assert!(
237+ session.trim_clip(Lane::V1, 1, Edge::End, 45),
238+ "one second of the 25 fps clip"
239+ );
240+ let total = (session.timeline_duration() * FPS).round() as u32;
241+ assert_eq!(total, 45, "15 frames of 30 fps and 30 of the 25 fps clip");
242+
243+ let out = std::env::temp_dir().join(format!("edith-mixed-{}.mp4", std::process::id()));
244+ wait(&session.export_to_with(
245+ &out,
246+ &ExportSettings {
247+ format: Format::Mp4,
248+ ..ExportSettings::default()
249+ },
250+ ))
251+ .expect("the export");
252+
253+ // Duration first: the file is as long as the timeline, so the mixed rates
254+ // did not stretch or shorten it.
255+ let (meta, rx, _cancel) = DecodeSession::open_range(&out, 0, u32::MAX).expect("reopen");
256+ assert!(
257+ (meta.frame_rate - FPS).abs() < 0.01,
258+ "the export runs at the timeline's rate: {}",
259+ meta.frame_rate
260+ );
261+ assert_eq!(
262+ meta.frame_count, total,
263+ "the export is the timeline's length"
264+ );
265+ let written: Vec<Vec<u8>> = rx.into_iter().map(|frame| frame.bgra).collect();
266+ assert_eq!(written.len() as u32, total, "every frame came back");
267+
268+ // ...and motion: inside the 25 fps clip, 30 exported frames show 25
269+ // pictures, so 5 of them are a picture held from the frame before. A clip
270+ // played at the wrong rate would hold none (too fast, and it would run out
271+ // of file) or hold half of them (too slow).
272+ let held = (16..total as usize)
273+ .filter(|&i| difference(&written[i - 1], &written[i]) < 2.0)
274+ .count();
275+ assert_eq!(
276+ held, 5,
277+ "30 timeline frames of a 25 fps clip hold 5 pictures over"
278+ );
279+ std::fs::remove_file(&out).ok();
280+}
crates/engine/tests/playback.rsmodified+8 -7
@@ -813,14 +813,15 @@ fn import_refuses_what_does_not_match() {
813 "a resolution of its own is not a refusal any more: {err}"813 "a resolution of its own is not a refusal any more: {err}"
814 );814 );
815 815
816- // Same codec, same audio, 25 fps: the one property left, named with both816+ // A frame rate of its own is no longer a refusal either: 25 fps joins a
817- // rates. Mixing rates would mean retiming the timeline itself, and there is817+ // 30 fps timeline and is read at `Rate` against it -- see
818- // no resampler for that, so the refusal is the honest answer.818+ // `tests/mixed_fps.rs` for what it then plays like.
819- let err = session819+ session
820 .import(&asset("test_25fps.mp4"))820 .import(&asset("test_25fps.mp4"))
821- .expect_err("25 fps must not join a 30 fps timeline")821+ .expect("25 fps may join a 30 fps timeline");
822- .to_string();822+ session
823- assert_eq!(err, "25.000 fps does not match the timeline's 30.000 fps");823+ .remove_source(&asset("test_25fps.mp4"), 0)
824+ .expect("...and the row it made comes back off");
824 825
825 // Same size and rate, no audio track: the timeline has one.826 // Same size and rate, no audio track: the timeline has one.
826 let err = session827 let err = session
scripts/gen_fixtures.shmodified+11 -3
@@ -135,15 +135,23 @@ enable='between(t,1,1.1)'[v];\
135 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \135 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \
136 -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4136 -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4
137 # Frame-rate fixture: test_av.mp4 in every respect a timeline is held to -- same137 # Frame-rate fixture: test_av.mp4 in every respect a timeline is held to -- same
138-# codec, same profile, same 44.1k stereo AAC -- except that it runs at 25 fps.138+# codec, same profile, same 44.1k stereo AAC -- except that it runs at 25 fps,
139-# The only thing left for an import to refuse is the rate, which is what makes139+# so a timeline of 30 fps clips has one at another rate to read through `Rate`.
140-# the refusal's wording testable.
141 ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=25:duration=2 \140 ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=25:duration=2 \
142 -f lavfi -i "sine=frequency=440:duration=2" \141 -f lavfi -i "sine=frequency=440:duration=2" \
143 -f lavfi -i "sine=frequency=880:duration=2" \142 -f lavfi -i "sine=frequency=880:duration=2" \
144 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \143 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
145 -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \144 -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
146 -c:a aac -b:a 128k assets/test_25fps.mp4145 -c:a aac -b:a 128k assets/test_25fps.mp4
146+# ...and the same again at 23.976 fps (24000/1001), the rate whose ratio to a
147+# 30 fps timeline does not terminate: what the frame mapping's rounding is
148+# actually tested against.
149+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=24000/1001:duration=2 \
150+ -f lavfi -i "sine=frequency=440:duration=2" \
151+ -f lavfi -i "sine=frequency=880:duration=2" \
152+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
153+ -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
154+ -c:a aac -b:a 128k assets/test_23976fps.mp4
147 # Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the155 # Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the
148 # A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song156 # A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song
149 # can share a timeline with the video clips and the peaks tests can reuse the157 # can share a timeline with the video clips and the peaks tests can reuse the