diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 7ed6df1..84b027d 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -3580,12 +3580,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 eb8ee9b..0acc07a 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 @@ -345,6 +347,19 @@ fn copy_audio( ) .into()); } + // A frame *rate* of its own is not one of those, and that is deliberate: + // do not "fix" this into a re-encode. A clip counts the **timeline's** + // frames whatever its file was shot at ([`Rate`]), so the window this copy + // trims a source's sound to is `start..end` in whole timeline frames -- + // exactly the seconds the picture covers -- and the file is read at the + // pitch it was recorded at, which is what playing at the rate it was shot at + // means. There is no per-clip stretch to express, so the packets are already + // the right sound in the right place; re-encoding a conformed lane would buy + // nothing and cost a generation of loss on every mixed-rate export + // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot` + // measures the copied sound against the picture). A *speed* is different + // because it resamples, which is why it is refused above. + // // ...and last, whether any clip on it carries an equalizer. An EQ is sample // math and a copy never decodes, so copying such a lane would write the clip // *flat*, silently -- the failure a missing audio track is. This lane is @@ -469,6 +484,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; @@ -483,14 +508,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 @@ -521,10 +550,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; @@ -622,6 +665,24 @@ 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) { + // ...and one whose rate cannot be named against the timeline's, which + // `matches_timeline` refuses at import, so nothing on a timeline is on + // this arm either. + Ok((meta, _)) => Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), + 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 cc58c39..c16245b 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, }) @@ -554,9 +578,16 @@ impl PlaybackSession { // clip check below indexes this list by source, so it must line up with // `doc.sources` whichever entry the scaffolding came from. let mut counts = Vec::with_capacity(doc.sources.len()); + // Beside it, one entry per source, grown at every `push` below: the + // scaffold 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::with_capacity(doc.sources.len()); for (i, source) in doc.sources.iter().enumerate() { if i == scaffold { counts.push(meta.frame_count); + rates.push(Rate::REAL_TIME); continue; } // A still has neither a rate to match nor a track to match with: @@ -567,6 +598,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 @@ -576,13 +608,15 @@ 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) + let rate = matches_timeline(source, &other, &meta, &first_audio) .map_err(|e| format!("source {}: {e}", source.path.display()))?; - counts.push(other.frame_count); + 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 @@ -656,6 +690,8 @@ impl PlaybackSession { audio_disabled, project, counts, + rates, + span_rate: Rate::REAL_TIME, span, eos: false, }; @@ -733,9 +769,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, @@ -805,6 +847,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 @@ -841,10 +891,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() @@ -1120,13 +1177,36 @@ 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.source_of(path) + .map_or(Rate::REAL_TIME, |i| self.rates[i]) + } + + /// Which source `path` is, canonicalising only if it has to: a source's own + /// path is canonical ([`Source::new`]), so a caller handing one back from + /// [`sources`](Self::sources) -- which is every library row -- hits on the + /// first walk and never pays for the `canonicalize` syscall the second one + /// makes. One rule, so a path that names a length names a rate too. + fn source_of(&self, path: &Path) -> Option { + let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted); + at(path).or_else(|| at(&Source::new(path, 0).path)) } /// How long the whole of `path` is, in timeline frames: the length noted @@ -1138,14 +1218,20 @@ impl PlaybackSession { /// audio tracks it carries -- the picture's frame count for an mp4, the /// playing time for a song. pub fn file_frames(&self, path: &Path) -> u32 { - let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted); - // A source's own path is canonical ([`Source::new`]), so a caller - // handing one back from [`sources`](Self::sources) -- which is every - // library row -- hits on the first walk and never pays for the - // `canonicalize` syscall the second one makes. - at(path) - .or_else(|| at(&Source::new(path, 0).path)) - .map_or(0, |i| self.counts[i]) + self.source_of(path).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 @@ -1304,8 +1390,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, @@ -1387,6 +1474,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); @@ -1441,11 +1529,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); @@ -1458,9 +1549,15 @@ impl PlaybackSession { // Stream 0: an import brings a file in on its first audio track, and // [`place_stream_at`](Self::place_stream_at) is how any other one of // its streams reaches the timeline afterwards. - matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?; + // ...and the rate it will be read at comes back from the check that + // accepted it, so the number the refusal was decided on is the number + // the file is played by. + let rate = 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`]). + self.note_frames(source, rate.timeline_at(meta.frame_count), rate); Ok(source) } @@ -1480,7 +1577,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) } @@ -1504,7 +1601,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) } @@ -1766,15 +1863,16 @@ impl Drop for PlaybackSession { /// Whether `path`, already demuxed to `meta`, may join a timeline whose /// parameters are `timeline` and whose audio probes as `first`: same codec, -/// same frame rate, same audio parameters or both silent. +/// same audio parameters or both silent, and a frame rate that can be named +/// against the timeline's. The [`Rate`] it will be read at comes back with the +/// answer, so the number the check was decided on is the number it plays by. /// /// *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 @@ -1785,7 +1883,7 @@ fn matches_timeline( meta: &VideoMeta, timeline: &VideoMeta, first: &Option, -) -> crate::Result<()> { +) -> crate::Result { // Codec first: one timeline is one kind of source. Mixing them would decode // (every clip opens its own decoder) but on a machine without the VA-API // plugin the VP9 half would be black frames with the refusal only on @@ -1798,15 +1896,20 @@ 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()); - } - audio_matches(source, first) + // The frame rate is *not* a refusal any more: 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. + // + // A rate that cannot be *named* still is, and this is the one place it is + // caught: `Rate::from_fps` builds itself out of the muxer's own timescales, + // and a file whose rate has none of those (a container that says nothing and + // holds one block, so the demuxer measures 0 fps) would otherwise be read + // 1:1 in silence -- the old rate gate refused those too, by arithmetic + // accident. The `Err` is `mux::frame_timing`'s own words. + let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?; + audio_matches(source, first)?; + Ok(rate) } /// Whether a candidate's audio may join a timeline whose first source probes as diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 7c7fe1e..5ae102b 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -221,9 +221,120 @@ impl std::fmt::Display for Speed { } } +/// What a file's own frame rate is against the timeline's, as an exact +/// rational: 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`). +/// +/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and +/// stays `800/1001` however far the timeline runs, where a rate rounded to +/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a +/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`). +/// +/// [`PlaybackSession`]: crate::PlaybackSession +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Rate { + /// Frames of the file... + source: u32, + /// ...per this many frames of the timeline it plays on. Never zero. + timeline: u32, +} + +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`, + /// exactly. + /// + /// Both rates come out of a container as a division, so neither is ever the + /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what + /// already knows how to name one exactly -- it is the same pair the muxer + /// counts an export's frames in -- and this is that pair divided by that + /// pair, reduced. A rate no timescale can name is an `Err` in that + /// function's own words rather than a silent 1:1 -- `matches_timeline` is + /// where a file carrying one is refused by name, beside the codec. + /// + /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every + /// timeline that had ever opened in this editor before mixed rates. + pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result { + let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?; + let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?; + // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks). + let num = u64::from(src_scale) * u64::from(tl_ticks); + let den = u64::from(src_ticks) * u64::from(tl_scale); + let g = gcd(num, den); + let (mut num, mut den) = (num / g, den / g); + // A ratio no pair of real frame rates produces, but the fields are `u32` + // so that every multiplication below fits a `u64` at any frame count. + while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) { + (num, den) = (num.div_ceil(2), den.div_ceil(2)); + } + Ok(Self { + source: num.max(1) as u32, + timeline: den.max(1) as u32, + }) + } + + 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 { + f64::from(self.source) / f64::from(self.timeline) + } + + /// 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) * u64::from(self.source) / u64::from(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) * u64::from(self.timeline)) + .div_ceil(u64::from(self.source)) + .min(u64::from(u32::MAX)) as u32 + } +} + +/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its +/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it. +fn gcd(a: u64, b: u64) -> u64 { + match b { + 0 => a.max(1), + b => gcd(b, a % b), + } +} + /// 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 @@ -4557,6 +4668,87 @@ 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::from_fps(source_fps, timeline_fps).expect("a nameable rate"); + 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 of the *rate itself*, + // not an accumulation and not a rounded rate, so an hour in is as + // true as the first second. (Held to the real ratio of the two rates + // the caller asked for -- `as_f64` would be true of a wrong rate.) + for n in [1u32, 100, 10_000, 500_000, 3_000_000] { + let want = f64::from(n) * source_fps / 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::from_fps(30., 30.).expect("30 over 30").is_real_time()); + assert!( + Rate::from_fps(30.0004, 30.) + .expect("30.0004 over 30") + .is_real_time(), + "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001" + ); + // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the + // one thing `matches_timeline` refuses a file for now that the rate gate + // is gone. + assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all"); + assert!(Rate::from_fps(30., f64::NAN).is_err()); + 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 exactly 800/1001 of a + // file frame. + let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 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 * 800 / 1001) 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..68d8156 --- /dev/null +++ b/crates/engine/tests/mixed_fps.rs @@ -0,0 +1,419 @@ +//! 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, Rate, 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() + ); + // ...and the sound that came down with each take is the same length as its + // picture: a placed take is one linked group, so a rate that stretched only + // the picture would slide the two apart on the very first drag. + let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1)); + assert_eq!(video.len(), 3, "the 30 fps take and the two others"); + assert_eq!(audio.len(), video.len(), "one audio clip per take"); + for (v, a) in video.iter().zip(audio) { + assert_eq!((v.start, v.len()), (a.start, a.len()), "{v:?} vs {a:?}"); + } +} + +/// The NTSC ratio, which the 23.976 fps fixture is shot at: 24000/1001 over 30 +/// is exactly 800/1001, and it stays exact however far the timeline runs. A rate +/// rounded to a float -- or to milli-fps -- would leave a fraction of a frame +/// per clip to pile up into a visible drift over an hour, which is why the +/// mapping is built out of the muxer's own timescales and not a division. +#[test] +fn a_23_976_rate_is_exact_and_never_drifts() { + let ntsc = Rate::from_fps(24_000.0 / 1001.0, FPS).expect("23.976 over 30"); + assert!( + (ntsc.as_f64() - 800.0 / 1001.0).abs() < 1e-15, + "{}", + ntsc.as_f64() + ); + // Independent integer arithmetic, out to an hour of source and past it: 800 + // source frames per 1001 timeline ones, and a file's length is that ceiled + // (the last picture must still be reachable by a trim). + for source in [1u64, 2, 24, 1000, 86_486, 500_000, 1_000_000] { + assert_eq!( + u64::from(ntsc.timeline_at(source as u32)), + (source * 1001).div_ceil(800), + "{source} source frames" + ); + } + // ...and the two directions stay each other's inverse at every one of them: + // the frame an export writes at timeline frame `d` is the frame playback is + // holding there, which is what `timeline_at`'s ceil buys. + for d in [0u32, 1, 2, 3, 1000, 100_000, 1_000_000] { + let source = ntsc.source_at(d); + assert!(ntsc.timeline_at(source) <= d, "frame {d} is not yet due"); + assert!( + ntsc.timeline_at(source + 1) > d, + "the next frame is due too early at {d}" + ); + } + // A timeline's own rate conforms by nothing at all, exactly -- whichever of + // the two rates it is written at. + assert!(Rate::from_fps(FPS, FPS).expect("30 over 30").is_real_time()); + assert!( + Rate::from_fps(24_000.0 / 1001.0, 24_000.0 / 1001.0) + .expect("ntsc over ntsc") + .is_real_time() + ); + // A rate no timescale can name is refused rather than read 1:1 in silence: + // the one thing `matches_timeline` still turns a file away for. + assert!(Rate::from_fps(0.0, FPS).is_err(), "not a rate at all"); +} + +/// 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"); + // ...and the frame in front of it is the 30 fps take, frame for frame: a + // rate belongs to the source that has one, so the clip beside it is read + // exactly as it was before any of this existed. + let av = asset("test_av.mp4"); + session.seek(f64::from(start - 1) / FPS); + let before = next_frame(&mut session, "the last frame of the 30 fps take"); + assert_eq!(before.index, start - 1); + assert!( + before.bgra == source_frame(&av, start - 1), + "the 30 fps clip is still frame for frame" + ); +} + +/// A trim of a clip at another rate is dragged in *timeline* frames and commits +/// the source range those frames are worth -- so the box is exactly the room it +/// was dragged to, and the picture at its new edge is the file's own frame +/// there. +#[test] +fn a_clip_at_another_rate_trims_to_the_room_it_was_dragged_to() { + let pal = asset("test_25fps.mp4"); + let mut session = open(asset("test_av.mp4")); + import_and_place(&mut session, &pal); + session.pause(); + let start = 150u32; + // Drag its tail back to 30 timeline frames of room: one second, which at 25 + // fps is the file's first 25 pictures. + assert!( + session.trim_clip(Lane::V1, 1, Edge::End, start + 30), + "trim the tail of the 25 fps clip" + ); + let clip = session.lane_clips(Lane::V1)[1]; + assert_eq!((clip.start, clip.len()), (start, 30), "{clip:?}"); + session.seek(f64::from(start + 29) / FPS); + let last = next_frame(&mut session, "the trimmed tail"); + assert!( + last.bgra == source_frame(&pal, 24), + "one second of a 25 fps file ends on its frame 24" + ); + // ...and its head, dragged forward into source it keeps: 6 timeline frames + // in is 5 source frames in, and the tail did not move. + assert!(session.trim_clip(Lane::V1, 1, Edge::Start, start + 6)); + let clip = session.lane_clips(Lane::V1)[1]; + assert_eq!((clip.start, clip.len()), (start + 6, 24), "{clip:?}"); + session.seek(f64::from(start + 6) / FPS); + let head = next_frame(&mut session, "the trimmed head"); + assert!( + head.bgra == source_frame(&pal, 5), + "6 frames of a 30 fps timeline is 5 frames of a 25 fps file" + ); +} + +/// 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" + ); + + // ...and *which* picture each of those frames is: the very one playback + // holds there, which is the whole reason the two conversions are one + // floor/ceil pair. Nearer its own source frame than either neighbour rather + // than equal to it -- the export is re-encoded, so no pixel survives whole. + for offset in [0u32, 1, 6, 12, 24, 29] { + let want = (u64::from(offset) * 25_000 / 30_000) as u32; + let mine = difference(&written[(15 + offset) as usize], &source_frame(&pal, want)); + for other in [want.saturating_sub(1), want + 1] { + if other == want { + continue; + } + assert!( + mine < difference(&written[(15 + offset) as usize], &source_frame(&pal, other)), + "exported frame {offset} of the 25 fps clip is nearer source \ + frame {other} than its own {want}" + ); + } + } + + // The sound came out as long as the picture, from a *packet copy*: a clip + // counts timeline frames whatever its file was shot at, so the window this + // export trimmed the 25 fps file's AAC to is whole timeline frames and the + // copy is in sync. This is the assertion behind the note in + // `export::copy_audio` that says not to turn a conformed lane into a + // re-encode. + let secs = engine::AudioSession::duration_secs(&out) + .expect("probe the export") + .expect("the export has sound"); + let want = f64::from(total) / FPS; + assert!( + (secs - want).abs() < 0.05, + "sound is {secs} s under {want} s of picture" + ); + 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 1de0018..b121be0 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -161,15 +161,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