forge
Explore
Log in

Don't you dare go Hollow

The project frame rate is a list to pick from

Browse files at this commit

d2e25cc5592e9d639cdce4e1048767518ec90164Ahmet Kaan GümüşParent: edf0cd9
  • feat
    • the project frame rate is a list to pick from
Show full message
✨ feat(rate): the project frame rate is a list to pick from

The panel could only ever read the rate out. Now it opens the rates the
way the resolution button opens the sizes -- 23.976 through 60 with the
media's own cycled in and the one in force marked -- and picking one
conforms the whole timeline to it.

PlaybackSession::set_frame_rate maps every frame number on every lane
through one Rate (Project::retime), so a take keeps its seconds, its
footage and its sync while being counted on the new grid; every source is
re-read through a Rate against it and an export comes out at it. The v9
fps line now governs a video-scaffolded project too, so a project cut at
24 reopens at 24 instead of at the media's 30 with every clip number
still counted in 24ths.
crates/app/src/main.rsmodified+143 -5
@@ -369,15 +369,20 @@ struct Picker {
369 #[derive(Clone, Copy, PartialEq, Eq, Debug)]369 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
370 enum Pick {370 enum Pick {
371 Resolution,371 Resolution,
372+ Fps,
372 Fit(Lane, usize),373 Fit(Lane, usize),
373 }374 }
374 375
375 /// One value a list offers, carrying everything picking it needs -- so a click376 /// One value a list offers, carrying everything picking it needs -- so a click
376 /// goes straight to the value rather than to a position in a list that was377 /// goes straight to the value rather than to a position in a list that was
377 /// built somewhere else.378 /// built somewhere else.
378-#[derive(Clone, Copy, PartialEq, Eq, Debug)]379+/// `Eq` is off it for the rate: a frame rate is the `f64` the engine is told,
380+/// bit for bit (23.976023976... is not 23.976), and nothing here keys a map on a
381+/// choice -- comparing two is all a list row ever does.
382+#[derive(Clone, Copy, PartialEq, Debug)]
379 enum Choice {383 enum Choice {
380 Size(u32, u32),384 Size(u32, u32),
385+ Fps(f64),
381 Fit(Lane, usize, FitPolicy),386 Fit(Lane, usize, FitPolicy),
382 }387 }
383 388
@@ -498,6 +503,23 @@ fn keys_rows() -> Vec<KeyRow> {
498 /// them, which is what makes the trip round come back to where it started.503 /// them, which is what makes the trip round come back to where it started.
499 const RESOLUTIONS: [(u32, u32); 4] = [(3840, 2160), (1920, 1080), (1280, 720), (854, 480)];504 const RESOLUTIONS: [(u32, u32); 4] = [(3840, 2160), (1920, 1080), (1280, 720), (854, 480)];
500 505
506+/// The project frame rates the list offers, slowest first: the rates footage is
507+/// actually shot and delivered at, the NTSC ones written as the ratios they are
508+/// (`24000/1001`, not `23.976`) -- the engine conforms the timeline to the very
509+/// number it is handed, so a rate rounded here would be a rate no timescale can
510+/// name. The media's own is cycled in beside them
511+/// ([`frame_rate_ladder`]), which is what keeps the way back on the list.
512+const FRAME_RATES: [f64; 8] = [
513+ 24_000. / 1001.,
514+ 24.,
515+ 25.,
516+ 30_000. / 1001.,
517+ 30.,
518+ 50.,
519+ 60_000. / 1001.,
520+ 60.,
521+];
522+
501 /// How far a band may be pushed either way, in dB. The engine clamps nothing523 /// How far a band may be pushed either way, in dB. The engine clamps nothing
502 /// here -- it will filter whatever it is given -- so this is a UI decision:524 /// here -- it will filter whatever it is given -- so this is a UI decision:
503 /// past about this a peaking band stops sounding like tone and starts sounding525 /// past about this a peaking band stops sounding like tone and starts sounding
@@ -1455,6 +1477,23 @@ impl Player {
1455 cx.notify();1477 cx.notify();
1456 }1478 }
1457 1479
1480+ /// The project cut at another rate: the list names one and this is where it
1481+ /// happens, the way [`apply_resolution`](Self::apply_resolution) is for a
1482+ /// size. The whole timeline is conformed to it by the engine
1483+ /// ([`PlaybackSession::set_frame_rate`]) -- same seconds, same footage --
1484+ /// and the rate the app itself counts frames in follows, since every
1485+ /// timecode, ruler mark and step key here is measured in it.
1486+ fn apply_frame_rate(&mut self, fps: f64, cx: &mut Context<Self>) {
1487+ if let Some(session) = &mut self.session
1488+ && session.set_frame_rate(fps)
1489+ {
1490+ self.fps = session.meta().frame_rate;
1491+ self.notice = Some(format!("PROJECT: {} fps", fps_label(fps)).into());
1492+ self.reset_after_reseek();
1493+ }
1494+ cx.notify();
1495+ }
1496+
1458 /// Opens a choice list on a setting, where it was asked for. One floating1497 /// Opens a choice list on a setting, where it was asked for. One floating
1459 /// thing at a time: the click that opens it is the click that closes1498 /// thing at a time: the click that opens it is the click that closes
1460 /// whatever menu it was opened from.1499 /// whatever menu it was opened from.
@@ -1472,6 +1511,7 @@ impl Player {
1472 self.picker = None;1511 self.picker = None;
1473 match choice {1512 match choice {
1474 Choice::Size(w, h) => self.apply_resolution(w, h, cx),1513 Choice::Size(w, h) => self.apply_resolution(w, h, cx),
1514+ Choice::Fps(fps) => self.apply_frame_rate(fps, cx),
1475 Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx),1515 Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx),
1476 }1516 }
1477 }1517 }
@@ -1487,6 +1527,7 @@ impl Player {
1487 Pick::Resolution => {1527 Pick::Resolution => {
1488 resolution_choices(session.resolution(), session.native_resolution())1528 resolution_choices(session.resolution(), session.native_resolution())
1489 }1529 }
1530+ Pick::Fps => fps_choices(session.meta().frame_rate, session.native_frame_rate()),
1490 Pick::Fit(lane, idx) => {1531 Pick::Fit(lane, idx) => {
1491 fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution())1532 fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution())
1492 }1533 }
@@ -4886,6 +4927,30 @@ impl Player {
4886 this.open_picker(Pick::Resolution, event.position(), cx)4927 this.open_picker(Pick::Resolution, event.position(), cx)
4887 }),4928 }),
4888 ))4929 ))
4930+ // The rate every clip is counted in, which is also the rate
4931+ // the export is written at -- the other half of "the project
4932+ // is not the media", and the one the panel could only ever
4933+ // read out before. A click opens the rates with this one
4934+ // marked; picking one conforms the whole timeline to it.
4935+ .child(control(
4936+ "fps",
4937+ None,
4938+ match self.session.is_some() {
4939+ true => format!("{} fps", fps_label(self.fps)),
4940+ false => "Rate".to_string(),
4941+ },
4942+ match self.session.is_some() {
4943+ true => format!(
4944+ "click to pick a frame rate — the project is cut at {} fps",
4945+ fps_label(self.fps)
4946+ ),
4947+ false => "the project's frame rate — open a file first".to_string(),
4948+ },
4949+ live,
4950+ cx.listener(|this, event: &ClickEvent, _, cx| {
4951+ this.open_picker(Pick::Fps, event.position(), cx)
4952+ }),
4953+ ))
4889 // How much of the timeline the panel below is showing --4954 // How much of the timeline the panel below is showing --
4890 // beside the resolution, since neither of them edits4955 // beside the resolution, since neither of them edits
4891 // anything: they are both what is being looked at. The4956 // anything: they are both what is being looked at. The
@@ -8909,6 +8974,53 @@ fn resolution_choices(current: (u32, u32), native: (u32, u32)) -> Vec<ChoiceRow>
8909 .collect()8974 .collect()
8910 }8975 }
8911 8976
8977+/// Every project frame rate on offer, slowest first: [`FRAME_RATES`] with the
8978+/// media's own cycled in at its place by speed, so a project already cut at a
8979+/// listed rate does not see it twice and the media's own rate -- the one a
8980+/// project moved off it has no other way back to -- is always there.
8981+/// [`resolution_ladder`]'s rule, for the other setting the project has of its
8982+/// own.
8983+fn frame_rate_ladder(native: f64) -> Vec<f64> {
8984+ let mut rates = FRAME_RATES.to_vec();
8985+ // Bit for bit: 23.976023976... is not 23.976, and a rate that read as
8986+ // "already listed" when it is not would take the media's own off the list.
8987+ if !rates.contains(&native) {
8988+ let at = rates
8989+ .iter()
8990+ .position(|&fps| fps > native)
8991+ .unwrap_or(rates.len());
8992+ rates.insert(at, native);
8993+ }
8994+ rates
8995+}
8996+
8997+/// The rate list's rows: every rung of the ladder, the media's own said so, and
8998+/// the one in force marked. Named as a person writes a rate ([`fps_label`]),
8999+/// with what it is for beside it -- short, or the row loses its tail to the
9000+/// truncation the resolution list already met.
9001+fn fps_choices(current: f64, native: f64) -> Vec<ChoiceRow> {
9002+ frame_rate_ladder(native)
9003+ .into_iter()
9004+ .map(|fps| {
9005+ (
9006+ Choice::Fps(fps),
9007+ format!("{} fps", fps_label(fps)).into(),
9008+ match fps == native {
9009+ true => "the media's own".to_string(),
9010+ // The rates that are a ratio are the ones nobody can tell
9011+ // from their neighbour by the label alone.
9012+ false => match (fps - fps.round()).abs() < 0.001 {
9013+ true => String::new(),
9014+ false => "NTSC".to_string(),
9015+ },
9016+ }
9017+ .into(),
9018+ fps == current,
9019+ )
9020+ })
9021+ .collect()
9022+}
9023+
8912 /// The fit list's rows: all four policies against the canvas they place a9024 /// The fit list's rows: all four policies against the canvas they place a
8913 /// picture on, since the word alone ("fill") says nothing about the size it is9025 /// picture on, since the word alone ("fill") says nothing about the size it is
8914 /// filling -- which is the very thing the notice says after a stroke.9026 /// filling -- which is the very thing the notice says after a stroke.
@@ -10272,7 +10384,8 @@ mod tests {
10272 bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, containers,10384 bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, containers,
10273 enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y,10385 enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y,
10274 estimated_mb, export_path, export_settings, format_key,10386 estimated_mb, export_path, export_settings, format_key,
10275- format_line, format_refusal, fps_label, frac_along, frac_down, frame_at, histogram,10387+ format_line, format_refusal, fps_choices, fps_label, frac_along, frac_down, frame_at,
10388+ frame_rate_ladder, histogram,
10276 inserted_band, is_bare_modifier, is_project, keymap, keys_rows, lanes_h, marked, menu_at,10389 inserted_band, is_bare_modifier, is_project, keymap, keys_rows, lanes_h, marked, menu_at,
10277 next_container,10390 next_container,
10278 normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due,10391 normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due,
@@ -10281,7 +10394,7 @@ mod tests {
10281 whole_take, window_title,10394 whole_take, window_title,
10282 };10395 };
10283 use super::{10396 use super::{
10284- Choice, Edge, FITS, LaneKind, PPS_DEFAULT, RESOLUTIONS, Repeat, Scale, View,10397+ Choice, Edge, FITS, FRAME_RATES, LaneKind, PPS_DEFAULT, RESOLUTIONS, Repeat, Scale, View,
10285 ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, fit_choices,10398 ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, fit_choices,
10286 library_rows, live_idx, next_fit, next_resolution, px_along, repeats, resolution_choices,10399 library_rows, live_idx, next_fit, next_resolution, px_along, repeats, resolution_choices,
10287 resolution_ladder, span_label, trimmed_clip, unscannable, visible_slice,10400 resolution_ladder, span_label, trimmed_clip, unscannable, visible_slice,
@@ -12948,10 +13061,35 @@ mod tests {
12948 assert!(fits[2].3, "the clip's own policy is not marked");13061 assert!(fits[2].3, "the clip's own policy is not marked");
12949 assert!(fits[0].2.contains("1920x1080"), "{}", fits[0].2);13062 assert!(fits[0].2.contains("1920x1080"), "{}", fits[0].2);
12950 13063
13064+ // The rate list, the other setting the project has of its own: every
13065+ // rate on offer, the media's own cycled in at its place by speed and
13066+ // said so, and the one the timeline is cut at marked. The value carried
13067+ // is the `f64` the engine conforms to, not the rounded label -- 23.976
13068+ // is not 24000/1001, and a rate the timescales cannot name is refused.
13069+ let ntsc = 24_000. / 1001.;
13070+ let rates = frame_rate_ladder(25.);
13071+ assert_eq!(rates.len(), FRAME_RATES.len(), "25 is already on the list");
13072+ let odd = frame_rate_ladder(48.);
13073+ assert_eq!(odd[5], 48., "the media's own, in its place by speed");
13074+ assert_eq!(odd.len(), FRAME_RATES.len() + 1);
13075+ let fps = fps_choices(ntsc, 48.);
13076+ assert_eq!(fps.len(), odd.len());
13077+ assert_eq!(fps.iter().filter(|(.., picked)| *picked).count(), 1);
13078+ assert_eq!(fps[0].0, Choice::Fps(ntsc), "the ratio, not 23.976");
13079+ assert_eq!(fps[0].1.as_ref(), "23.976 fps");
13080+ assert!(fps[0].3, "the rate in force is not marked");
13081+ assert!(fps[5].2.contains("the media's own"), "{}", fps[5].2);
13082+ for (.., detail, _) in &fps {
13083+ assert!(detail.chars().count() < 26, "{detail} loses its tail");
13084+ }
13085+
12951 // The open list fits the floor the menus are measured against: the13086 // The open list fits the floor the menus are measured against: the
12952- // longest of them is the resolution ladder, and it hangs at the pointer13087+ // longest of them is the rate ladder with an odd rate cycled in, and it
12953- // with every row on screen. Rows are click targets (WCAG 2.5.8).13088+ // hangs at the pointer with every row on screen. Rows are click targets
13089+ // (WCAG 2.5.8).
12954 assert!(MENU_ROW_H >= HIT_MIN);13090 assert!(MENU_ROW_H >= HIT_MIN);
13091+ assert!(odd.len() > ladder.len(), "the longest list moved");
13092+ assert!(MENU_PAD * 2. + odd.len() as f32 * MENU_ROW_H <= 360.);
12955 let tall = MENU_PAD * 2. + ladder.len() as f32 * MENU_ROW_H;13093 let tall = MENU_PAD * 2. + ladder.len() as f32 * MENU_ROW_H;
12956 assert!(tall <= 360., "the list is taller than the floor");13094 assert!(tall <= 360., "the list is taller than the floor");
12957 assert_eq!(13095 assert_eq!(
crates/engine/src/edith.rsmodified+7 -4
@@ -19,10 +19,13 @@
19 //! gain audio 1 -3.019 //! gain audio 1 -3.0
20 //! ```20 //! ```
21 //!21 //!
22-//! The `fps` line is the rate the timeline was cut at, printed so it reads back22+//! The `fps` line is the rate the timeline was cut at -- the scaffolding
23-//! bit-exactly. A file without one (every dialect before v9) means "whatever23+//! source's own unless a rate was picked
24-//! the scaffolding source runs at", which is what such a project always was and24+//! ([`crate::PlaybackSession::set_frame_rate`]), and the *only* thing that says
25-//! is an answer only a project holding a video has25+//! so once one was, since every clip number in the file is counted in it.
26+//! Printed so it reads back bit-exactly. A file without one (every dialect
27+//! before v9) means "whatever the scaffolding source runs at", which is what
28+//! such a project always was and is an answer only a project holding a video has
26 //! ([`crate::PlaybackSession::open_project`]).29 //! ([`crate::PlaybackSession::open_project`]).
27 //!30 //!
28 //! A `subtitle` line is `subtitle <track> <path>`: which track of that file the31 //! A `subtitle` line is `subtitle <track> <path>`: which track of that file the
crates/engine/src/playback.rsmodified+93 -2
@@ -158,6 +158,11 @@ pub struct PlaybackSession {
158 /// starts here, and a caller offering sizes to pick from needs the media's158 /// starts here, and a caller offering sizes to pick from needs the media's
159 /// own among them or a project moved off it could never come back.159 /// own among them or a project moved off it could never come back.
160 native: (u32, u32),160 native: (u32, u32),
161+ /// ...and the scaffolding source's own frame rate, kept for exactly that
162+ /// reason: the project rate starts here, and the list a caller offers rates
163+ /// from needs the media's own on it or a project moved off it has no way
164+ /// back ([`PlaybackSession::set_frame_rate`] is not an undo step either).
165+ native_fps: f64,
161 frames: Receiver<Frame>,166 frames: Receiver<Frame>,
162 /// The current decode worker.167 /// The current decode worker.
163 worker: Worker,168 worker: Worker,
@@ -277,6 +282,7 @@ impl PlaybackSession {
277 Ok(Self {282 Ok(Self {
278 meta,283 meta,
279 native: (meta.width, meta.height),284 native: (meta.width, meta.height),
285+ native_fps: meta.frame_rate,
280 frames: stream.frames,286 frames: stream.frames,
281 worker: stream.worker,287 worker: stream.worker,
282 backend: stream.backend,288 backend: stream.backend,
@@ -375,6 +381,7 @@ impl PlaybackSession {
375 Ok(Self {381 Ok(Self {
376 meta,382 meta,
377 native: (width, height),383 native: (width, height),
384+ native_fps: frame_rate,
378 frames: stream.frames,385 frames: stream.frames,
379 worker: stream.worker,386 worker: stream.worker,
380 backend: stream.backend,387 backend: stream.backend,
@@ -451,6 +458,7 @@ impl PlaybackSession {
451 Ok(Self {458 Ok(Self {
452 meta,459 meta,
453 native: (meta.width, meta.height),460 native: (meta.width, meta.height),
461+ native_fps: IMAGE_ONLY_RATE,
454 frames: stream.frames,462 frames: stream.frames,
455 worker: stream.worker,463 worker: stream.worker,
456 backend: stream.backend,464 backend: stream.backend,
@@ -585,6 +593,32 @@ impl PlaybackSession {
585 meta.width = width;593 meta.width = width;
586 meta.height = height;594 meta.height = height;
587 }595 }
596+ // ...and the project's own *rate*, which is the scaffold's unless the
597+ // file says otherwise. The two made-up rates above already took the
598+ // saved one (their counts are computed from it); a scaffold with a
599+ // picture keeps its own here, so a project cut at a rate nobody picked
600+ // is the file it always was -- and one where a rate *was* picked
601+ // ([`set_frame_rate`](Self::set_frame_rate)) comes back at it rather
602+ // than at the media's, which would leave every clip number counted in
603+ // frames the timeline no longer has.
604+ let native_fps = match crate::is_audio(&first.path) {
605+ true => AUDIO_ONLY_CANVAS.2,
606+ false if crate::is_image(&first.path) => IMAGE_ONLY_RATE,
607+ false => meta.frame_rate,
608+ };
609+ if let Some(fps) = saved_fps {
610+ meta.frame_rate = fps;
611+ }
612+ // A song and a still have no rate of their own to be conformed from:
613+ // their length above was counted in the timeline's frames already,
614+ // whatever those are. A file with pictures is read through [`Rate`] like
615+ // any other source when the project is cut at another rate.
616+ let made_up = crate::is_audio(&first.path) || crate::is_image(&first.path);
617+ let scaffold_rate = match made_up || native_fps == meta.frame_rate {
618+ true => Rate::REAL_TIME,
619+ false => Rate::from_fps(native_fps, meta.frame_rate)
620+ .map_err(|e| format!("source {}: {e}", first.path.display()))?,
621+ };
588 let first_audio = first_audio_of(&doc.sources)?;622 let first_audio = first_audio_of(&doc.sources)?;
589 623
590 // In source order, with the scaffold's own count in its own slot: the624 // In source order, with the scaffold's own count in its own slot: the
@@ -599,8 +633,8 @@ impl PlaybackSession {
599 let mut rates = Vec::with_capacity(doc.sources.len());633 let mut rates = Vec::with_capacity(doc.sources.len());
600 for (i, source) in doc.sources.iter().enumerate() {634 for (i, source) in doc.sources.iter().enumerate() {
601 if i == scaffold {635 if i == scaffold {
602- counts.push(meta.frame_count);636+ counts.push(scaffold_rate.timeline_at(meta.frame_count));
603- rates.push(Rate::REAL_TIME);637+ rates.push(scaffold_rate);
604 continue;638 continue;
605 }639 }
606 // A still has neither a rate to match nor a track to match with:640 // A still has neither a rate to match nor a track to match with:
@@ -704,6 +738,7 @@ impl PlaybackSession {
704 let mut session = Self {738 let mut session = Self {
705 meta,739 meta,
706 native,740 native,
741+ native_fps,
707 frames: stream.frames,742 frames: stream.frames,
708 worker: stream.worker,743 worker: stream.worker,
709 backend: stream.backend,744 backend: stream.backend,
@@ -1442,6 +1477,62 @@ impl PlaybackSession {
1442 true1477 true
1443 }1478 }
1444 1479
1480+ /// The scaffolding source's own frame rate -- what the project rate started
1481+ /// as, and the one rate a caller offering a list of them must not leave out
1482+ /// ([`native_resolution`](Self::native_resolution)'s reason).
1483+ pub fn native_frame_rate(&self) -> f64 {
1484+ self.native_fps
1485+ }
1486+
1487+ /// Cuts this timeline at `fps` from here on: every clip is *conformed* to
1488+ /// the new rate ([`Project::retime`]), every source is read through a
1489+ /// [`Rate`] against it, and an export written from this session comes out at
1490+ /// it. The edit survives as the same seconds of the same footage on a finer
1491+ /// or coarser grid -- a 30 fps take on a timeline moved to 24 keeps its
1492+ /// length and its sync, it is simply counted in 24ths now.
1493+ ///
1494+ /// Reseeks like [`set_resolution`](Self::set_resolution), so the picture and
1495+ /// the sound under the playhead are already the new rate's when this
1496+ /// returns. `false` -- changing nothing -- for a rate that is not a rate, for
1497+ /// the one already in force, and for one no timescale can name
1498+ /// ([`crate::mux::frame_timing`], the same wall a file of an unnameable rate
1499+ /// is refused at).
1500+ ///
1501+ /// ponytail: not an undo step, exactly as the project resolution is not --
1502+ /// and this one *moves the frame numbers*, so the way back is picking the
1503+ /// old rate (or the media's, [`native_frame_rate`](Self::native_frame_rate))
1504+ /// rather than a `z`, and it lands within a frame of where it started rather
1505+ /// than on it (see [`Project::retime`]). Upgrade path is the same one: the
1506+ /// project's settings snapshotted beside the lanes.
1507+ pub fn set_frame_rate(&mut self, fps: f64) -> bool {
1508+ if !fps.is_finite() || fps <= 0.0 || fps == self.meta.frame_rate {
1509+ return false;
1510+ }
1511+ // Old timeline frames per new one, exactly -- the one map every frame
1512+ // number on every lane goes through. Built before anything is touched,
1513+ // since a rate no timescale can name is a refusal and not a half-retimed
1514+ // project.
1515+ let Ok(k) = Rate::from_fps(self.meta.frame_rate, fps) else {
1516+ return false;
1517+ };
1518+ // Lengths first: the retime holds every clip inside its source's *new*
1519+ // length, so a clip that played to the last frame of its file still
1520+ // does rather than naming one past the end.
1521+ for count in &mut self.counts {
1522+ *count = k.timeline_at(*count).max(1);
1523+ }
1524+ self.project.retime(k, &self.counts);
1525+ // A file's own rate has not changed; what it is *against* has.
1526+ for rate in &mut self.rates {
1527+ *rate = rate.then(k);
1528+ }
1529+ self.meta.frame_rate = fps;
1530+ self.meta.frame_count = k.timeline_at(self.meta.frame_count).max(1);
1531+ let now = self.now();
1532+ self.seek(now);
1533+ true
1534+ }
1535+
1445 /// How the clip at `idx` of `lane` meets a project canvas of another shape.1536 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
1446 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {1537 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
1447 self.project.fit_of(lane, idx)1538 self.project.fit_of(lane, idx)
crates/engine/src/project.rsmodified+65 -2
@@ -289,6 +289,11 @@ impl Rate {
289 // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).289 // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
290 let num = u64::from(src_scale) * u64::from(tl_ticks);290 let num = u64::from(src_scale) * u64::from(tl_ticks);
291 let den = u64::from(src_ticks) * u64::from(tl_scale);291 let den = u64::from(src_ticks) * u64::from(tl_scale);
292+ Ok(Self::reduced(num, den))
293+ }
294+
295+ /// `num` frames of a file per `den` frames of a timeline, in lowest terms.
296+ fn reduced(num: u64, den: u64) -> Self {
292 let g = gcd(num, den);297 let g = gcd(num, den);
293 let (mut num, mut den) = (num / g, den / g);298 let (mut num, mut den) = (num / g, den / g);
294 // A ratio no pair of real frame rates produces, but the fields are `u32`299 // A ratio no pair of real frame rates produces, but the fields are `u32`
@@ -296,10 +301,22 @@ impl Rate {
296 while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {301 while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
297 (num, den) = (num.div_ceil(2), den.div_ceil(2));302 (num, den) = (num.div_ceil(2), den.div_ceil(2));
298 }303 }
299- Ok(Self {304+ Self {
300 source: num.max(1) as u32,305 source: num.max(1) as u32,
301 timeline: den.max(1) as u32,306 timeline: den.max(1) as u32,
302- })307+ }
308+ }
309+
310+ /// The same file against a timeline that has itself been retimed: `self` is
311+ /// its frames per frame of the old timeline and `k` is old frames per new
312+ /// one, so this is its frames per frame of the *new* one -- exactly, without
313+ /// going back through an `f64` fps that names neither rate
314+ /// ([`crate::PlaybackSession::set_frame_rate`]).
315+ pub fn then(self, k: Rate) -> Self {
316+ Self::reduced(
317+ u64::from(self.source) * u64::from(k.source),
318+ u64::from(self.timeline) * u64::from(k.timeline),
319+ )
303 }320 }
304 321
305 pub fn is_real_time(self) -> bool {322 pub fn is_real_time(self) -> bool {
@@ -1423,6 +1440,52 @@ impl Project {
1423 true1440 true
1424 }1441 }
1425 1442
1443+ /// Every frame number on every lane rewritten onto a timeline counted at
1444+ /// another rate: `k` is old timeline frames per new one, `counts` is how
1445+ /// long each source is on the *new* timeline (indexed as
1446+ /// [`Project::sources`] is), and the edit survives as the same seconds of
1447+ /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
1448+ /// the edit list, and the only thing that touches the frame numbers without
1449+ /// being an edit anyone made.
1450+ ///
1451+ /// Every position -- a clip's start and its end alike -- goes through the
1452+ /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
1453+ /// stays a gap, and a take's picture and its sound land on the same frame on
1454+ /// their two lanes: no lane can drift against another. A clip is then only
1455+ /// ever made to *fit* the room its own start and end mapped to, never to
1456+ /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
1457+ /// below is the backstop for the one case that could: a slow clip so short
1458+ /// that no source range fits its new room at all).
1459+ ///
1460+ /// ponytail: not exact both ways. Each rate change re-rounds every boundary
1461+ /// onto the new grid, so a rate picked, unpicked and picked again is within
1462+ /// a frame of where it started rather than back at it. Upgrade path is
1463+ /// keeping the edit list at one reference rate and conforming on the way
1464+ /// out, which every frame number in this module would then be measured in.
1465+ pub fn retime(&mut self, k: Rate, counts: &[u32]) {
1466+ for lane in &mut self.lanes {
1467+ let mut cursor = 0;
1468+ for clip in &mut lane.clips {
1469+ let start = k.timeline_at(clip.start).max(cursor);
1470+ // The room its own end mapped to -- never zero, since a clip is
1471+ // never empty even on a grid too coarse to hold it.
1472+ let room = k.timeline_at(clip.end()).saturating_sub(start).max(1);
1473+ let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
1474+ // Its footage, held inside the file's new length: a clip whose
1475+ // out-point was the last frame of its source must not come out
1476+ // of this naming a frame past the end -- that is a project that
1477+ // would not open again ([`crate::PlaybackSession::open_project`]
1478+ // refuses one by name).
1479+ let in_frame = k.timeline_at(clip.in_frame).min(count - 1);
1480+ let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
1481+ clip.start = start;
1482+ clip.in_frame = in_frame;
1483+ clip.out_frame = in_frame + len;
1484+ cursor = clip.end();
1485+ }
1486+ }
1487+ }
1488+
1426 /// Length of the timeline in frames: where the *last* lane runs out. A lane1489 /// Length of the timeline in frames: where the *last* lane runs out. A lane
1427 /// that ends early is a trailing gap in that lane, not a shorter timeline.1490 /// that ends early is a trailing gap in that lane, not a shorter timeline.
1428 pub fn timeline_frames(&self) -> u32 {1491 pub fn timeline_frames(&self) -> u32 {
crates/engine/tests/mixed_fps.rsmodified+109 -0
@@ -323,6 +323,115 @@ fn a_mixed_rate_project_reloads_unchanged() {
323 std::fs::remove_file(&path).ok();323 std::fs::remove_file(&path).ok();
324 }324 }
325 325
326+/// The project's rate is the user's to pick, exactly as its resolution is. The
327+/// timeline is *conformed* to it -- the same seconds of the same footage,
328+/// counted on a new grid -- every source is read through a [`Rate`] against it,
329+/// the media's own rate stays reachable, and a save comes back at the rate it
330+/// was cut at rather than at the media's.
331+#[test]
332+fn the_project_rate_is_picked_and_the_timeline_is_conformed_to_it() {
333+ let pal = asset("test_25fps.mp4");
334+ let mut session = open(asset("test_av.mp4"));
335+ import_and_place(&mut session, &pal);
336+ let duration = session.timeline_duration();
337+ assert_eq!(session.native_frame_rate(), FPS, "the media's own rate");
338+ assert!(!session.set_frame_rate(FPS), "the rate already in force");
339+ assert!(!session.set_frame_rate(0.0), "not a rate at all");
340+
341+ assert!(
342+ session.set_frame_rate(24.0),
343+ "24 is a rate a timescale can name"
344+ );
345+ assert_eq!(session.meta().frame_rate, 24.0);
346+ assert!(
347+ (session.timeline_duration() - duration).abs() < 1.0 / 24.0,
348+ "the timeline is {} s where it was {duration} s",
349+ session.timeline_duration()
350+ );
351+ // Both files are read through a rate against the new grid now: 5 s and 2 s,
352+ // in 24ths.
353+ assert_eq!(session.file_frames(&asset("test_av.mp4")), 120, "5 s at 24");
354+ assert_eq!(session.file_frames(&pal), 48, "2 s at 24");
355+ // ...and each take is still one take on both lanes: every frame number goes
356+ // through one map, so a picture cannot drift off its sound.
357+ let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1));
358+ assert_eq!(video.len(), 2, "the 30 fps take and the 25 fps one");
359+ for (v, a) in video.iter().zip(audio) {
360+ assert_eq!((v.start, v.len()), (a.start, a.len()), "{v:?} vs {a:?}");
361+ }
362+
363+ let path = std::env::temp_dir().join(format!("edith-rate-{}.edith", std::process::id()));
364+ session.save_project(&path).expect("save");
365+ let reloaded = PlaybackSession::open_project(&path).expect("a retimed project reopens");
366+ assert_eq!(reloaded.meta().frame_rate, 24.0, "the rate it was cut at");
367+ assert_eq!(
368+ reloaded.clip_spans(),
369+ session.clip_spans(),
370+ "the same clips"
371+ );
372+ assert_eq!(reloaded.file_frames(&pal), 48, "recomputed against 24");
373+ assert_eq!(
374+ reloaded.native_frame_rate(),
375+ FPS,
376+ "the way back is still there"
377+ );
378+ std::fs::remove_file(&path).ok();
379+
380+ // ...and that way back is a pick like any other: the media's own rate.
381+ let native = session.native_frame_rate();
382+ assert!(session.set_frame_rate(native), "back to the media's own");
383+ assert_eq!(session.file_frames(&pal), 60, "2 s at 30 again");
384+ assert!(
385+ (session.timeline_duration() - duration).abs() < 1.0 / 24.0,
386+ "{} s after the round trip, {duration} s before",
387+ session.timeline_duration()
388+ );
389+}
390+
391+/// ...and an export of it comes out at that rate: the file is written at 24 fps,
392+/// as many frames as the conformed timeline has, with its sound as long as its
393+/// picture.
394+#[test]
395+fn an_export_runs_at_the_rate_the_project_was_cut_at() {
396+ let mut session = open(asset("test_av.mp4"));
397+ assert!(
398+ session.trim_clip(Lane::V1, 0, Edge::End, 30),
399+ "one second of the 30 fps take"
400+ );
401+ assert!(session.set_frame_rate(24.0), "cut it at 24 instead");
402+ let total = (session.timeline_duration() * 24.0).round() as u32;
403+ assert_eq!(total, 24, "one second, in 24ths");
404+
405+ let out = std::env::temp_dir().join(format!("edith-rate-{}.mp4", std::process::id()));
406+ wait(&session.export_to_with(
407+ &out,
408+ &ExportSettings {
409+ format: Format::Mp4,
410+ ..ExportSettings::default()
411+ },
412+ ))
413+ .expect("the export");
414+
415+ let (meta, _rx, _cancel) = DecodeSession::open_range(&out, 0, u32::MAX).expect("reopen");
416+ assert!(
417+ (meta.frame_rate - 24.0).abs() < 0.01,
418+ "the export runs at the picked rate: {}",
419+ meta.frame_rate
420+ );
421+ assert_eq!(
422+ meta.frame_count, total,
423+ "the export is the timeline's length"
424+ );
425+ let secs = engine::AudioSession::duration_secs(&out)
426+ .expect("probe the export")
427+ .expect("the export has sound");
428+ assert!(
429+ (secs - f64::from(total) / 24.0).abs() < 0.05,
430+ "sound is {secs} s under a second of picture"
431+ );
432+ std::fs::remove_file(&out).ok();
433+}
434+
326 /// The export is what was watched: as many frames as the timeline has, and the435 /// The export is what was watched: as many frames as the timeline has, and the
327 /// 25 fps clip walked through its file at 25 fps -- 25 pictures over 30 frames,436 /// 25 fps clip walked through its file at 25 fps -- 25 pictures over 30 frames,
328 /// not 30 of them and not 25 held to the end.437 /// not 30 of them and not 25 held to the end.