forge
Explore
Log in

Don't you dare go Hollow

Clips play at a speed of their own

Browse files at this commit

f8effe8b7f334412b7f18e669134069187c7ce4bAhmet Kaan GümüşParent: b586b85
  • feat
    • clips play at a speed of their own
Show full message
✨ feat(timeline): clips play at a speed of their own

A clip gains a rate (`Speed`, thousandths of real time, 0.25x to 4x) and
every speed question is answered at the mapping seams that were already
there: `Clip::frames` is the source range divided by the rate, `end` is
built on it, and `map`/`span_at`/`composite_span_at` walk the offset
through `Speed::source_at`. `in_frame`/`out_frame` stay *source* frames,
so a trim and a split still address the file.

The picture needs no new decoder: the span says how many source frames it
reads, and `try_frame` brings the decoder's numbers back through the same
rate -- at 2x two decoded frames land on one timeline frame and the
display's drop-when-behind policy takes it from there. The sound is
resampled per segment inside the worker playback and the audio export
already share (linear interpolation, carried across packet seams), so the
pitch moves with the rate: tape, not pitch-preserve, and the card says so.
Each segment is told how much timeline it owes and pads or trims to it,
which is what keeps a run of speeded cuts from drifting.

Rounding is where a rate could break the lane, so it does not: `Speed::fit`
never hands a trim more source than its room holds, and `Speed::split_at`
refuses a cut a slow clip's rate cannot address rather than leaving two
halves that no longer add up. The fuzz sweeps set_speed in with the rest.

- card in the eq/colour pattern, on `j` and in the clip menu; a drag is one
  undo step for the whole linked group, 1.00x reachable by hand and by `r`
- clip boxes carry a "2.00x" mark, and their width, waveform and details
  row are the timeline length
- WAV/FLAC honour it; mp4 and AV1 *refuse* by name -- that path copies AAC
  packets and a resample is not a copy (ponytail names the upgrade path)
- .edith v8 carries the rate; v7 and older load at 1.00x
- `assets/test_speed_sync.mp4`: one flash, one beep, same instant. At 2x
  they still land together, to the frame.

15 changed files +1839 -165

crates/app/src/keymap.rsmodified+19 -5
@@ -70,13 +70,14 @@ pub enum ActionId {
70 VolumeUp,70 VolumeUp,
71 VolumeDown,71 VolumeDown,
72 Equalizer,72 Equalizer,
73+ Speed,
73 CancelExport,74 CancelExport,
74 }75 }
75 76
76 impl ActionId {77 impl ActionId {
77 /// Display order everywhere -- the editor lists them in it and78 /// Display order everywhere -- the editor lists them in it and
78 /// [`Keymap::defaults`] binds them in it.79 /// [`Keymap::defaults`] binds them in it.
79- pub const ALL: [ActionId; 31] = [80+ pub const ALL: [ActionId; 32] = [
80 ActionId::Play,81 ActionId::Play,
81 ActionId::StepBack,82 ActionId::StepBack,
82 ActionId::StepForward,83 ActionId::StepForward,
@@ -107,6 +108,7 @@ impl ActionId {
107 ActionId::VolumeUp,108 ActionId::VolumeUp,
108 ActionId::VolumeDown,109 ActionId::VolumeDown,
109 ActionId::Equalizer,110 ActionId::Equalizer,
111+ ActionId::Speed,
110 ActionId::CancelExport,112 ActionId::CancelExport,
111 ];113 ];
112 114
@@ -143,6 +145,7 @@ impl ActionId {
143 ActionId::VolumeUp => "Volume up",145 ActionId::VolumeUp => "Volume up",
144 ActionId::VolumeDown => "Volume down",146 ActionId::VolumeDown => "Volume down",
145 ActionId::Equalizer => "Equalizer",147 ActionId::Equalizer => "Equalizer",
148+ ActionId::Speed => "Speed (tape)…",
146 ActionId::CancelExport => "Cancel export",149 ActionId::CancelExport => "Cancel export",
147 }150 }
148 }151 }
@@ -181,6 +184,7 @@ impl ActionId {
181 ActionId::VolumeUp => "volume-up",184 ActionId::VolumeUp => "volume-up",
182 ActionId::VolumeDown => "volume-down",185 ActionId::VolumeDown => "volume-down",
183 ActionId::Equalizer => "equalizer",186 ActionId::Equalizer => "equalizer",
187+ ActionId::Speed => "speed",
184 ActionId::CancelExport => "cancel-export",188 ActionId::CancelExport => "cancel-export",
185 }189 }
186 }190 }
@@ -209,7 +213,11 @@ impl ActionId {
209 | ActionId::Delete213 | ActionId::Delete
210 | ActionId::Lift214 | ActionId::Lift
211 | ActionId::Color215 | ActionId::Color
212- | ActionId::Fit => Category::Clips,216+ | ActionId::Fit
217+ // A rate is the clip's, not the sound's: it re-times the picture
218+ // and the sound together, and the card opens on whichever half was
219+ // clicked.
220+ | ActionId::Speed => Category::Clips,
213 // The project's own picture size is not a clip's business, and not221 // The project's own picture size is not a clip's business, and not
214 // a file operation either: it is what the viewer is looking at.222 // a file operation either: it is what the viewer is looking at.
215 ActionId::Resolution => Category::View,223 ActionId::Resolution => Category::View,
@@ -507,6 +515,11 @@ impl Keymap {
507 // The one free letter that says the word: "e" is already the515 // The one free letter that says the word: "e" is already the
508 // export and an equalizer is the q in nobody else's way.516 // export and an equalizer is the q in nobody else's way.
509 b(ActionId::Equalizer, "q", false),517 b(ActionId::Equalizer, "q", false),
518+ // "s" is the save's ctrl chord, so the speed card takes the
519+ // unshifted letter beside it: "j" was free, sits under the
520+ // right hand with the other clip keys (k grades, l lifts), and
521+ // is not next to anything that deletes.
522+ b(ActionId::Speed, "j", false),
510 b(ActionId::CancelExport, "escape", false),523 b(ActionId::CancelExport, "escape", false),
511 ],524 ],
512 }525 }
@@ -769,7 +782,7 @@ mod tests {
769 #[test]782 #[test]
770 fn every_default_stroke_reaches_its_action() {783 fn every_default_stroke_reaches_its_action() {
771 let k = Keymap::defaults();784 let k = Keymap::defaults();
772- assert_eq!(k.entries().len(), 33);785+ assert_eq!(k.entries().len(), 34);
773 assert_eq!(k.lookup("space", false), Some(ActionId::Play));786 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
774 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two787 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
775 // ends of the timeline.788 // ends of the timeline.
@@ -814,7 +827,8 @@ mod tests {
814 // The modifier is half the chord: ctrl+e is not e.827 // The modifier is half the chord: ctrl+e is not e.
815 assert_eq!(k.lookup("e", true), None);828 assert_eq!(k.lookup("e", true), None);
816 assert_eq!(k.lookup("space", true), None);829 assert_eq!(k.lookup("space", true), None);
817- assert_eq!(k.lookup("j", false), None);830+ assert_eq!(k.lookup("j", false), Some(ActionId::Speed));
831+ assert_eq!(k.lookup("j", true), None);
818 // Nothing is bound twice, or lookup's first match would be a coin toss.832 // Nothing is bound twice, or lookup's first match would be a coin toss.
819 for (i, a) in k.entries().iter().enumerate() {833 for (i, a) in k.entries().iter().enumerate() {
820 assert!(834 assert!(
@@ -996,7 +1010,7 @@ mod tests {
996 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");1010 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
997 // The label is the editor's column, and never the file's word for it.1011 // The label is the editor's column, and never the file's word for it.
998 assert_eq!(ActionId::CancelExport.label(), "Cancel export");1012 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
999- assert_eq!(ActionId::ALL.len(), 31);1013+ assert_eq!(ActionId::ALL.len(), 32);
1000 }1014 }
1001 1015
1002 #[test]1016 #[test]
crates/app/src/main.rsmodified+409 -13
@@ -13,7 +13,7 @@ use engine::audio::StreamInfo;
13 use engine::color::ColorParams;13 use engine::color::ColorParams;
14 use engine::eq::{Band, BandKind, EqParams};14 use engine::eq::{Band, BandKind, EqParams};
15 use engine::export::{ExportSettings, Format};15 use engine::export::{ExportSettings, Format};
16-use engine::project::{Edge, Lane, LaneKind, Source};16+use engine::project::{Edge, Lane, LaneKind, Source, Speed};
17 use engine::scale::FitPolicy;17 use engine::scale::FitPolicy;
18 use engine::{Clip, ExportHandle, Frame, PlaybackSession};18 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
19 use gpui::{19 use gpui::{
@@ -311,7 +311,7 @@ impl RowItem {
311 /// action a stroke already reaches -- the menu is a second way *to* the actions311 /// action a stroke already reaches -- the menu is a second way *to* the actions
312 /// and never a second version of them -- so both the label and the hint come312 /// and never a second version of them -- so both the label and the hint come
313 /// out of the keymap registry and the two can never disagree.313 /// out of the keymap registry and the two can never disagree.
314-const MENU_ITEMS: [ActionId; 10] = [314+const MENU_ITEMS: [ActionId; 11] = [
315 ActionId::Cut,315 ActionId::Cut,
316 ActionId::Delete,316 ActionId::Delete,
317 ActionId::Lift,317 ActionId::Lift,
@@ -319,6 +319,7 @@ const MENU_ITEMS: [ActionId; 10] = [
319 ActionId::Detach,319 ActionId::Detach,
320 ActionId::Group,320 ActionId::Group,
321 ActionId::Equalizer,321 ActionId::Equalizer,
322+ ActionId::Speed,
322 ActionId::Color,323 ActionId::Color,
323 ActionId::Fit,324 ActionId::Fit,
324 ActionId::ToggleMute,325 ActionId::ToggleMute,
@@ -339,6 +340,23 @@ const EQ_GAIN_LIMIT: f32 = 12.;
339 /// single band.340 /// single band.
340 const EQ_STEP: f32 = 1.;341 const EQ_STEP: f32 = 1.;
341 342
343+/// A twentieth of real time per keystroke, in the thousandths a [`Speed`] is
344+/// held in: fine enough to creep up on a rate, coarse enough that the whole
345+/// range is eighty presses and not eight hundred -- and it divides 1000, so
346+/// stepping from anywhere lands on exactly 1.00x on the way past.
347+const SPEED_STEP: i32 = 50;
348+
349+/// The rates the card's buttons offer, so the ones people actually name are one
350+/// click and not a drag. Real time is among them: it is the reset.
351+const SPEED_PRESETS: [u16; 6] = [250, 500, 1000, 1500, 2000, 4000];
352+
353+/// A rate from a number of thousandths that may have run off either end -- what
354+/// a keystroke and a drag both produce. Clamped, not refused: a hand pushing
355+/// past the limit means "as far as it goes", exactly as a trim does.
356+fn speed_at(permille: i32) -> Speed {
357+ Speed::from_permille(permille.clamp(0, i32::from(u16::MAX)) as u16)
358+}
359+
342 /// The graph's frequency axis: the range an ear works in, and the range every360 /// The graph's frequency axis: the range an ear works in, and the range every
343 /// band a file can carry sits inside. Log-spaced, so an octave is an octave361 /// band a file can carry sits inside. Log-spaced, so an octave is an octave
344 /// wherever it falls.362 /// wherever it falls.
@@ -542,6 +560,17 @@ struct Player {
542 /// there. `None` when it is closed, which is the only place that state560 /// there. `None` when it is closed, which is the only place that state
543 /// lives: the grade itself is the project's.561 /// lives: the grade itself is the project's.
544 color_open: Option<(Lane, usize)>,562 color_open: Option<(Lane, usize)>,
563+ /// The speed card is up on this clip -- the lane it is on and its index
564+ /// there, exactly as the colour card's handle is. `None` when it is closed;
565+ /// the rate itself is the project's, so there is nothing else to hold.
566+ speed_open: Option<(Lane, usize)>,
567+ /// The speed bar's box, recorded at prepaint: a mouse listener is handed the
568+ /// window position only, so this is what a press and a drag are read against
569+ /// ([`frac_along`]).
570+ speed_bar: Rc<Cell<Bounds<Pixels>>>,
571+ /// The bar is being dragged. On the root like the colour card's, for the
572+ /// same reason: the pointer leaves a 4 px bar on the first move.
573+ speed_dragging: bool,
545 /// Which of the card's four sliders the arrow keys and a drag move. The574 /// Which of the card's four sliders the arrow keys and a drag move. The
546 /// card's own focus, since nothing in it takes gpui's (ledger:182).575 /// card's own focus, since nothing in it takes gpui's (ledger:182).
547 color_band: usize,576 color_band: usize,
@@ -708,6 +737,7 @@ impl Player {
708 ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx),737 ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx),
709 ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),738 ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),
710 ActionId::Equalizer => self.open_eq(cx),739 ActionId::Equalizer => self.open_eq(cx),
740+ ActionId::Speed => self.open_speed(cx),
711 // Nothing to cancel while nothing is exporting; the export guard in741 // Nothing to cancel while nothing is exporting; the export guard in
712 // the key handler is what answers this one while there is.742 // the key handler is what answers this one while there is.
713 ActionId::CancelExport => {}743 ActionId::CancelExport => {}
@@ -953,6 +983,108 @@ impl Player {
953 self.write_color(params, !first, cx);983 self.write_color(params, !first, cx);
954 }984 }
955 985
986+ /// Opens the speed card on the clip whose rate is to change: the selected
987+ /// one, or -- with nothing selected -- the clip the picture is coming from,
988+ /// which is what a person means by "this shot". Either half of a take will
989+ /// do: a rate applies to the whole group, so opening it on the sound and
990+ /// opening it on the picture are the same card.
991+ fn open_speed(&mut self, cx: &mut Context<Self>) {
992+ if self.exporting().is_some() {
993+ return;
994+ }
995+ let Some(session) = &self.session else {
996+ self.notice = Some("no timeline to re-time — open a file first".into());
997+ cx.notify();
998+ return;
999+ };
1000+ match self
1001+ .selected
1002+ .or_else(|| session.video_clip_at(session.now()))
1003+ {
1004+ Some(clip) => {
1005+ self.speed_open = Some(clip);
1006+ self.speed_dragging = false;
1007+ // One card at a time, the rule the other three follow.
1008+ self.keys_open = false;
1009+ self.export_open = false;
1010+ self.eq_open = None;
1011+ self.color_open = None;
1012+ self.context_menu = None;
1013+ }
1014+ None => self.notice = Some("no clip under the playhead to re-time".into()),
1015+ }
1016+ cx.notify();
1017+ }
1018+
1019+ /// What the card's clip plays at right now -- real time for one nobody has
1020+ /// touched, which is where the bar starts.
1021+ fn card_speed(&self) -> Speed {
1022+ self.speed_open
1023+ .zip(self.session.as_ref())
1024+ .map_or(Speed::NORMAL, |((lane, idx), session)| {
1025+ session.speed_of(lane, idx)
1026+ })
1027+ }
1028+
1029+ /// Writes a rate at the card's clip and its whole group -- one undo step for
1030+ /// the lot ([`engine::PlaybackSession::set_speed`]). The engine reseeks, so
1031+ /// the picture runs at the new rate and the sound is resampled from the next
1032+ /// chunk on; a refusal (a slower clip would run into its neighbour) comes
1033+ /// back in the engine's own words and *names* the clip in the way, because
1034+ /// "it did not fit" is not something a person can go and fix.
1035+ fn set_speed(&mut self, speed: Speed, cx: &mut Context<Self>) {
1036+ self.write_speed(speed, false, cx);
1037+ }
1038+
1039+ /// Both writes: `live` is the one that takes no undo step, which is what
1040+ /// every sample *inside* a drag goes through -- so a drag from 1.00x to
1041+ /// 2.00x is one undo press and lands back where the hand picked it up, and
1042+ /// the whole linked group comes back with it.
1043+ fn write_speed(&mut self, speed: Speed, live: bool, cx: &mut Context<Self>) {
1044+ let Some((lane, idx)) = self.speed_open else {
1045+ return;
1046+ };
1047+ let Some(session) = &mut self.session else {
1048+ return;
1049+ };
1050+ if speed != session.speed_of(lane, idx) {
1051+ let wrote = match live {
1052+ true => session.set_speed_live(lane, idx, speed),
1053+ false => session.set_speed(lane, idx, speed),
1054+ };
1055+ match wrote {
1056+ Ok(()) => self.reset_after_reseek(),
1057+ Err(e) => self.notice = Some(e.to_string().into()),
1058+ }
1059+ }
1060+ cx.notify();
1061+ }
1062+
1063+ /// One [`SPEED_STEP`] per keystroke, clamped to what a [`Speed`] can hold.
1064+ fn nudge_speed(&mut self, steps: i32, cx: &mut Context<Self>) {
1065+ let at = i32::from(self.card_speed().permille()) + steps * SPEED_STEP;
1066+ self.set_speed(speed_at(at), cx);
1067+ }
1068+
1069+ /// Where the pointer sits along the bar, as a rate: the left end is
1070+ /// [`Speed::MIN`] and the right end [`Speed::MAX`], on the same
1071+ /// [`SPEED_STEP`] grid the keys move on -- so a drag can land on exactly
1072+ /// 1.00x and the same drag twice is one entry, not forty.
1073+ /// `first` is the press: it takes the undo step the whole gesture rolls back
1074+ /// to, and every sample after it is live -- the colour card's rule, for the
1075+ /// colour card's reason.
1076+ fn drag_speed(&mut self, x: Pixels, first: bool, cx: &mut Context<Self>) {
1077+ let along = frac_along(x, self.speed_bar.get());
1078+ let lo = f32::from(Speed::MIN.permille());
1079+ let hi = f32::from(Speed::MAX.permille());
1080+ let raw = lo + along * (hi - lo);
1081+ // Snapped to the grid, then to real time itself when it is within half a
1082+ // step of it: 1.00x is the one value a hand must be able to hit, and
1083+ // nothing about the bar's geometry guarantees a pixel lands on it.
1084+ let stepped = (raw / SPEED_STEP as f32).round() as i32 * SPEED_STEP;
1085+ self.write_speed(speed_at(stepped), !first, cx);
1086+ }
1087+
956 /// Whether a card owns the window. While one does the timeline under it is1088 /// Whether a card owns the window. While one does the timeline under it is
957 /// out of reach, so a right-click there opens no menu -- the same rule the1089 /// out of reach, so a right-click there opens no menu -- the same rule the
958 /// key handler and the drop target already follow.1090 /// key handler and the drop target already follow.
@@ -961,6 +1093,7 @@ impl Player {
961 || self.export_open1093 || self.export_open
962 || self.eq_open.is_some()1094 || self.eq_open.is_some()
963 || self.color_open.is_some()1095 || self.color_open.is_some()
1096+ || self.speed_open.is_some()
964 || self.exporting().is_some()1097 || self.exporting().is_some()
965 }1098 }
966 1099
@@ -2344,6 +2477,29 @@ impl Render for Player {
2344 cx.notify();2477 cx.notify();
2345 return;2478 return;
2346 }2479 }
2480+ // The speed card, the same way again: its arrows move the rate
2481+ // and `r` puts it back to real time, and neither means anything
2482+ // outside the card -- so neither is a binding (see `FIXED`,
2483+ // where the keys menu still lists them).
2484+ if this.speed_open.is_some() {
2485+ match color_key(key) {
2486+ Some(ColorKey::Close) => {
2487+ this.speed_open = None;
2488+ this.speed_dragging = false;
2489+ }
2490+ // The card has one value, so the pair that picks a
2491+ // slider on the colour card moves this one by a whole
2492+ // preset's worth instead of a step.
2493+ Some(ColorKey::Band(step)) => {
2494+ this.nudge_speed(if step == 1 { -2 } else { 2 }, cx)
2495+ }
2496+ Some(ColorKey::Nudge(steps)) => this.nudge_speed(steps as i32, cx),
2497+ Some(ColorKey::Reset) => this.set_speed(Speed::NORMAL, cx),
2498+ None => {}
2499+ }
2500+ cx.notify();
2501+ return;
2502+ }
2347 // A clip menu names an index, and every edit below moves2503 // A clip menu names an index, and every edit below moves
2348 // indices -- so a stroke closes it before it acts. Escape means2504 // indices -- so a stroke closes it before it acts. Escape means
2349 // that and nothing else, which is the `esc` the keys menu2505 // that and nothing else, which is the `esc` the keys menu
@@ -2426,6 +2582,16 @@ impl Render for Player {
2426 }2582 }
2427 return;2583 return;
2428 }2584 }
2585+ // The speed bar, the same 4 px and the same live writes: the
2586+ // press took the undo step and every sample since is live.
2587+ if this.speed_dragging {
2588+ if event.pressed_button == Some(MouseButton::Left) {
2589+ this.drag_speed(event.position.x, false, cx);
2590+ } else {
2591+ this.speed_dragging = false;
2592+ }
2593+ return;
2594+ }
2429 if !this.scrubbing {2595 if !this.scrubbing {
2430 return;2596 return;
2431 }2597 }
@@ -2462,6 +2628,10 @@ impl Render for Player {
2462 this.drag_color(event.position.x, false, cx);2628 this.drag_color(event.position.x, false, cx);
2463 return;2629 return;
2464 }2630 }
2631+ if std::mem::take(&mut this.speed_dragging) {
2632+ this.drag_speed(event.position.x, false, cx);
2633+ return;
2634+ }
2465 if std::mem::take(&mut this.scrubbing) {2635 if std::mem::take(&mut this.scrubbing) {
2466 this.scrub_to(event.position.x, true, cx);2636 this.scrub_to(event.position.x, true, cx);
2467 }2637 }
@@ -2540,6 +2710,7 @@ impl Render for Player {
2540 .children(self.export_card(cx))2710 .children(self.export_card(cx))
2541 .children(self.eq_card(cx))2711 .children(self.eq_card(cx))
2542 .children(self.color_card(cx))2712 .children(self.color_card(cx))
2713+ .children(self.speed_card(cx))
2543 }2714 }
2544 }2715 }
2545 2716
@@ -3834,6 +4005,138 @@ impl Player {
3834 )4005 )
3835 }4006 }
3836 4007
4008+ /// The speed card: one bar from a quarter speed to four times it, the rates
4009+ /// people name as buttons under it, and the clip's new length in frames --
4010+ /// which is the number a person is actually choosing. Built like the colour
4011+ /// card down to the scrim and the bar's own hit height, because it is the
4012+ /// same kind of card: one continuous value on one clip, live at the clip as
4013+ /// it moves.
4014+ ///
4015+ /// Honest about what it does: the sound is *resampled*, so the pitch goes up
4016+ /// with the rate, which is what the tape in the title means.
4017+ fn speed_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
4018+ let (lane, idx) = self.speed_open?;
4019+ let speed = self.card_speed();
4020+ let session = self.session.as_ref()?;
4021+ let clip = session.lane_clips(lane).get(idx).copied()?;
4022+ let lo = f32::from(Speed::MIN.permille());
4023+ let hi = f32::from(Speed::MAX.permille());
4024+ let frac = ((f32::from(speed.permille()) - lo) / (hi - lo)).clamp(0., 1.);
4025+ let presets: Vec<_> = SPEED_PRESETS
4026+ .into_iter()
4027+ .map(|permille| {
4028+ let at = Speed::from_permille(permille);
4029+ div()
4030+ .id(("speed-preset", usize::from(permille)))
4031+ .flex_1()
4032+ .flex()
4033+ .h(px(CONTROL_H))
4034+ .items_center()
4035+ .justify_center()
4036+ .rounded(px(3.))
4037+ .bg(rgb(match at == speed {
4038+ true => SELECTED,
4039+ false => CHROME,
4040+ }))
4041+ .cursor_pointer()
4042+ .hover(|s| s.bg(rgb(HOVER)))
4043+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
4044+ this.set_speed(at, cx);
4045+ }))
4046+ .child(format!("{at}"))
4047+ })
4048+ .collect();
4049+ Some(
4050+ div()
4051+ .absolute()
4052+ .inset_0()
4053+ .flex()
4054+ .justify_center()
4055+ .items_center()
4056+ .bg(rgba(0x101010cc))
4057+ .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
4058+ cx.stop_propagation()
4059+ })
4060+ .child(
4061+ div()
4062+ .w(px(COLOR_W))
4063+ .flex()
4064+ .flex_col()
4065+ .gap(px(6.))
4066+ .p(px(12.))
4067+ .rounded(px(6.))
4068+ .bg(rgb(SURFACE))
4069+ .child(div().flex_none().px(px(6.)).child(format!(
4070+ "Speed (tape) — {} clip {}",
4071+ lane.label(),
4072+ idx + 1
4073+ )))
4074+ .child(
4075+ div()
4076+ .flex_none()
4077+ .px(px(6.))
4078+ .text_size(px(11.))
4079+ .text_color(rgb(INK_DIM))
4080+ .child(
4081+ "drag the bar or ←→ moves it, r is 1.00x — the pitch moves with the rate; esc closes",
4082+ ),
4083+ )
4084+ .child(
4085+ // 4 px to look at and a whole row to hit (WCAG
4086+ // 2.5.8), the split the colour sliders and the ruler
4087+ // both make.
4088+ div()
4089+ .id("speed-bar")
4090+ .relative()
4091+ .w_full()
4092+ .h(px(KEYS_ROW_H))
4093+ .flex()
4094+ .items_center()
4095+ .cursor_pointer()
4096+ .on_mouse_down(
4097+ MouseButton::Left,
4098+ cx.listener(move |this, event: &MouseDownEvent, _, cx| {
4099+ this.speed_dragging = true;
4100+ this.drag_speed(event.position.x, true, cx);
4101+ }),
4102+ )
4103+ .child(bounds_probe(self.speed_bar.clone()))
4104+ .child(
4105+ div()
4106+ .w_full()
4107+ .h(px(4.))
4108+ .rounded(px(2.))
4109+ .bg(rgb(CHROME))
4110+ .child(
4111+ div()
4112+ .h_full()
4113+ .w(relative(frac))
4114+ .rounded(px(2.))
4115+ .bg(rgb(ACCENT)),
4116+ ),
4117+ ),
4118+ )
4119+ .child(div().flex().gap(px(4.)).children(presets))
4120+ .child(
4121+ div()
4122+ .flex_none()
4123+ .px(px(6.))
4124+ .text_size(px(11.))
4125+ .text_color(rgb(INK_DIM))
4126+ // What the choice *is*, in the numbers the
4127+ // timeline is measured in: the source range
4128+ // never moves, the room it takes does.
4129+ .child(format!(
4130+ "{speed} — {} source frames over {} on the timeline ({})",
4131+ clip.len(),
4132+ clip.frames(),
4133+ timecode(f64::from(clip.frames()) / self.fps, self.fps)
4134+ )),
4135+ ),
4136+ ),
4137+ )
4138+ }
4139+
3837 /// The menu a right-click on a library row opens: what can be done with the4140 /// The menu a right-click on a library row opens: what can be done with the
3838 /// *file* rather than with a clip of it, and a turn-over side saying what4141 /// *file* rather than with a clip of it, and a turn-over side saying what
3839 /// that file is. Built like [`Player::context_card`] down to the scrim, the4142 /// that file is. Built like [`Player::context_card`] down to the scrim, the
@@ -4055,7 +4358,11 @@ impl Player {
4055 "Source range",4358 "Source range",
4056 format!("{} – {}", secs(clip.in_frame), secs(clip.out_frame)),4359 format!("{} – {}", secs(clip.in_frame), secs(clip.out_frame)),
4057 ),4360 ),
4058- ("This clip", secs(clip.len())),4361+ // How long it is *where it sits*, which its rate decides -- and
4362+ // the rate itself beside it, because a clip half its source's
4363+ // length could be either a trim or a 2x.
4364+ ("This clip", secs(clip.frames())),
4365+ ("Speed", format!("{} (tape)", clip.speed)),
4059 ("Source duration", secs(session.file_frames(&source.path))),4366 ("Source duration", secs(session.file_frames(&source.path))),
4060 ] {4367 ] {
4061 rows.push(4368 rows.push(
@@ -4296,9 +4603,12 @@ impl Player {
4296 // What a drag on an edge is showing, which is the clip4603 // What a drag on an edge is showing, which is the clip
4297 // itself while nothing is being dragged.4604 // itself while nothing is being dragged.
4298 let clip = &self.trimmed(lane, i, *clip);4605 let clip = &self.trimmed(lane, i, *clip);
4606+ // Its *timeline* length, which a speed halves or
4607+ // quadruples: the box is as wide as the clip is long
4608+ // where it sits, not as long as the source it reads.
4299 let (start, len) = (4609 let (start, len) = (
4300 f64::from(clip.start) / self.fps,4610 f64::from(clip.start) / self.fps,
4301- f64::from(clip.len()) / self.fps,4611+ f64::from(clip.frames()) / self.fps,
4302 );4612 );
4303 let on = marked((lane, i), clip.link, sel, sel_link);4613 let on = marked((lane, i), clip.link, sel, sel_link);
4304 // A group with a half in the other lane wears its tint;4614 // A group with a half in the other lane wears its tint;
@@ -4442,6 +4752,25 @@ impl Player {
4442 .child(inner),4752 .child(inner),
4443 )4753 )
4444 }))4754 }))
4755+ // A speeded clip says so on the box, in the corner
4756+ // the label does not reach: the box's width alone
4757+ // cannot say whether a short clip is a trim or a
4758+ // clip at 4x, and that is the difference between a
4759+ // cut and a re-time.
4760+ .when(!clip.speed.is_normal(), |d| {
4761+ d.child(
4762+ div()
4763+ .absolute()
4764+ .top_0()
4765+ .right_0()
4766+ .px(px(3.))
4767+ .rounded(px(3.))
4768+ .bg(rgb(ACCENT))
4769+ .text_size(px(9.))
4770+ .text_color(rgb(SURFACE))
4771+ .child(format!("{}", clip.speed)),
4772+ )
4773+ })
4445 .when_some(label.filter(|_| show_label(bed_w * width)), |d, label| {4774 .when_some(label.filter(|_| show_label(bed_w * width)), |d, label| {
4446 d.child(4775 d.child(
4447 div()4776 div()
@@ -4716,8 +5045,19 @@ fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool
4716 // A fit policy is a picture setting for the same reason.5045 // A fit policy is a picture setting for the same reason.
4717 ActionId::Color | ActionId::Fit => lane.kind == LaneKind::Video,5046 ActionId::Color | ActionId::Fit => lane.kind == LaneKind::Video,
4718 // Splits this clip only from inside it: at either edge there is nothing5047 // Splits this clip only from inside it: at either edge there is nothing
4719- // to split off (project.rs `splittable`).5048+ // to split off -- and, on a speeded clip, only at a frame its own rate
4720- ActionId::Cut => clip.start < playhead && playhead < clip.end(),5049+ // can address, which is the same question `splittable` asks.
5050+ ActionId::Cut => {
5051+ clip.start < playhead
5052+ && playhead < clip.end()
5053+ && clip
5054+ .speed
5055+ .split_at(clip.len(), playhead - clip.start)
5056+ .is_some()
5057+ }
5058+ // A rate applies to a clip of either kind and to its whole group, so
5059+ // there is no lane it means nothing on -- `_ => true` below is its
5060+ // answer, and the engine words the one refusal there is (no room).
4721 // Rejoins whatever meets at the playhead, so it can mean something only5061 // Rejoins whatever meets at the playhead, so it can mean something only
4722 // at an edge of this clip. Whether those two halves were ever one take5062 // at an edge of this clip. Whether those two halves were ever one take
4723 // is the engine's question, and it words that refusal itself.5063 // is the engine's question, and it words that refusal itself.
@@ -5735,13 +6075,13 @@ mod tests {
5735 Format, HEADER_GAP, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM,6075 Format, HEADER_GAP, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM,
5736 KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX,6076 KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX,
5737 LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H,6077 LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H,
5738- RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume,6078+ RULER_HIT_H, SELECTED, SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source,
5739- WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, color_snap,6079+ Speed, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add,
5740- envelope, eq_x, eq_y, export_path, export_settings, format_key, format_line,6080+ cancels_export, color_snap, envelope, eq_x, eq_y, export_path, export_settings, format_key,
5741- format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project,6081+ format_line, format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier,
5742- keymap, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit, retarget,6082+ is_project, keymap, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit,
5743- scrub_due, show_label, source_tint, span_partner, start_frac, timecode, unseen_paths,6083+ retarget, scrub_due, show_label, source_tint, span_partner, speed_at, start_frac, timecode,
5744- unseen_sources, whole_take, width_frac, window_title,6084+ unseen_paths, unseen_sources, whole_take, width_frac, window_title,
5745 };6085 };
5746 use super::{file_name, file_uri, library_rows};6086 use super::{file_name, file_uri, library_rows};
5747 6087
@@ -6028,6 +6368,7 @@ mod tests {
6028 eq: None,6368 eq: None,
6029 color: None,6369 color: None,
6030 fit: FitPolicy::default(),6370 fit: FitPolicy::default(),
6371+ speed: Speed::NORMAL,
6031 };6372 };
6032 assert_eq!(clip.end(), 90);6373 assert_eq!(clip.end(), 90);
6033 // Cut splits from inside only: neither edge has anything to split off.6374 // Cut splits from inside only: neither edge has anything to split off.
@@ -6942,6 +7283,58 @@ mod tests {
6942 assert!(KEYS_ROW_H >= HIT_MIN);7283 assert!(KEYS_ROW_H >= HIT_MIN);
6943 }7284 }
6944 7285
7286+ /// The speed bar is the same round trip -- pixels -> rate -> fill -- with
7287+ /// one thing the colour sliders do not have to promise: **exactly 1.00x has
7288+ /// to be reachable**, by a hand as well as by the reset. A grid that missed
7289+ /// it would leave a clip nobody could put back.
7290+ #[test]
7291+ fn the_speed_bar_lands_where_it_paints_and_real_time_is_reachable() {
7292+ let bar = Bounds {
7293+ origin: point(px(180.), px(240.)),
7294+ size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)),
7295+ };
7296+ let (lo, hi) = (
7297+ f32::from(Speed::MIN.permille()),
7298+ f32::from(Speed::MAX.permille()),
7299+ );
7300+ // The same arithmetic `Player::drag_speed` runs, which is the one thing
7301+ // a test of it can share without re-deriving it.
7302+ let at = |x: f32| {
7303+ let raw = lo + frac_along(px(x), bar) * (hi - lo);
7304+ speed_at((raw / SPEED_STEP as f32).round() as i32 * SPEED_STEP)
7305+ };
7306+ assert_eq!(at(180.), Speed::MIN, "the left end is a quarter speed");
7307+ assert_eq!(at(180. + COLOR_BAR_W), Speed::MAX, "the right end is 4x");
7308+ assert_eq!(at(-4000.), Speed::MIN, "off the left clamps");
7309+ assert_eq!(at(9999.), Speed::MAX, "off the right clamps");
7310+ let mut hits_real_time = false;
7311+ for step in 0..=240 {
7312+ let along = step as f32 / 240.;
7313+ let speed = at(180. + along * COLOR_BAR_W);
7314+ hits_real_time |= speed == Speed::NORMAL;
7315+ assert_eq!(
7316+ i32::from(speed.permille()) % SPEED_STEP,
7317+ 0,
7318+ "{speed} is off the {SPEED_STEP} grid the keys move on"
7319+ );
7320+ // What the bar paints from that rate is where the pointer was, to
7321+ // within the half step the snap costs.
7322+ let painted = (f32::from(speed.permille()) - lo) / (hi - lo);
7323+ let slack = SPEED_STEP as f32 / (hi - lo) / 2. + 1e-4;
7324+ assert!(
7325+ (painted - along).abs() <= slack,
7326+ "pressed at {along}, paints at {painted}"
7327+ );
7328+ }
7329+ assert!(hits_real_time, "a drag can land on exactly 1.00x");
7330+ // ...and every preset the card offers is a rate the bar can also reach.
7331+ for permille in SPEED_PRESETS {
7332+ assert_eq!(Speed::from_permille(permille).permille(), permille);
7333+ assert_eq!(i32::from(permille) % SPEED_STEP, 0);
7334+ }
7335+ assert!(SPEED_PRESETS.contains(&Speed::NORMAL.permille()), "reset");
7336+ }
7337+
6945 /// A colour slider is dragged straight to a value, so where the pointer7338 /// A colour slider is dragged straight to a value, so where the pointer
6946 /// lands and where the bar then paints have to be the same place: this is7339 /// lands and where the bar then paints have to be the same place: this is
6947 /// the round trip [`Player::drag_color`] makes, pixels -> value -> fill.7340 /// the round trip [`Player::drag_color`] makes, pixels -> value -> fill.
@@ -7633,6 +8026,9 @@ fn main() {
7633 eq_band: 0,8026 eq_band: 0,
7634 eq_dragging: false,8027 eq_dragging: false,
7635 eq_graph: Rc::default(),8028 eq_graph: Rc::default(),
8029+ speed_open: None,
8030+ speed_bar: Rc::default(),
8031+ speed_dragging: false,
7636 color_open: None,8032 color_open: None,
7637 color_band: 0,8033 color_band: 0,
7638 color_dragging: false,8034 color_dragging: false,
crates/engine/src/audio.rsmodified+232 -6
@@ -245,6 +245,28 @@ impl AudioSession {
245 sources: &[(PathBuf, usize)],245 sources: &[(PathBuf, usize)],
246 segs: &[(Option<usize>, f64, f64)],246 segs: &[(Option<usize>, f64, f64)],
247 eqs: &[Option<EqParams>],247 eqs: &[Option<EqParams>],
248+ ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
249+ Self::open_multi_streams_speed(sources, segs, eqs, &[])
250+ }
251+
252+ /// [`open_multi_streams_eq`](Self::open_multi_streams_eq) with a *rate* per
253+ /// segment as well: `speeds[i]` says how fast segment `i` is read and how
254+ /// much timeline it owes ([`crate::project::Stretch`]), `None` for one at
255+ /// real time. [`crate::Project::audio_speeds_from`] is what builds it, beside
256+ /// the very list the segments come from.
257+ ///
258+ /// Resampling happens **per segment**, inside the worker and before the mix,
259+ /// for the equalizer's reasons: two clips at two speeds must not be read
260+ /// into one another, and the interpolator's memory dies with the segment. A
261+ /// list shorter than `segs` (the empty one every plain caller passes) means
262+ /// the rest play at real time, so nothing here can shift a rate onto the
263+ /// wrong clip and a project with no speeds decodes exactly the samples it
264+ /// always did.
265+ pub fn open_multi_streams_speed(
266+ sources: &[(PathBuf, usize)],
267+ segs: &[(Option<usize>, f64, f64)],
268+ eqs: &[Option<EqParams>],
269+ speeds: &[Option<crate::project::Stretch>],
248 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {270 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
249 let Some((path, stream)) = sources.first() else {271 let Some((path, stream)) = sources.first() else {
250 return Ok(None);272 return Ok(None);
@@ -330,6 +352,23 @@ impl AudioSession {
330 })352 })
331 .collect();353 .collect();
332 354
355+ // One resampler per speeded segment, built where the sample rate is
356+ // known: what the timeline owes it is seconds there and frames here.
357+ let speeds: Vec<Option<Resample>> = segments
358+ .iter()
359+ .enumerate()
360+ .map(|(i, _)| {
361+ speeds.get(i).and_then(Option::as_ref).map(|s| {
362+ Resample::new(
363+ s.step,
364+ (s.timeline_secs * f64::from(meta.sample_rate))
365+ .round()
366+ .max(0.) as u64,
367+ )
368+ })
369+ })
370+ .collect();
371+
333 let (tx, rx) = sync_channel(32);372 let (tx, rx) = sync_channel(32);
334 thread::Builder::new()373 thread::Builder::new()
335 .name("audio-decode".into())374 .name("audio-decode".into())
@@ -339,6 +378,7 @@ impl AudioSession {
339 channels: meta.channels as usize,378 channels: meta.channels as usize,
340 segments,379 segments,
341 eqs,380 eqs,
381+ speeds,
342 timeline,382 timeline,
343 tx,383 tx,
344 })384 })
@@ -384,13 +424,37 @@ impl AudioSession {
384 sources: &[(PathBuf, usize)],424 sources: &[(PathBuf, usize)],
385 lanes: &[Vec<(Option<usize>, f64, f64)>],425 lanes: &[Vec<(Option<usize>, f64, f64)>],
386 eqs: &[Vec<Option<EqParams>>],426 eqs: &[Vec<Option<EqParams>>],
427+ ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
428+ Self::open_mixed_streams_speed(sources, lanes, eqs, &[])
429+ }
430+
431+ /// [`open_mixed_streams_eq`](Self::open_mixed_streams_eq) with
432+ /// [`open_multi_streams_speed`](Self::open_multi_streams_speed)'s per-segment
433+ /// rates, one list per lane -- [`crate::Project::audio_speeds_from`] is what
434+ /// shapes them, off the same walk the segments come from.
435+ ///
436+ /// A resample is each lane's worker's own business and happens **before**
437+ /// the sum, exactly as the filtering does: every lane still hands the mixer
438+ /// as many samples as the timeline says, so the lanes stay sample-aligned by
439+ /// construction and a mix is still an add.
440+ pub fn open_mixed_streams_speed(
441+ sources: &[(PathBuf, usize)],
442+ lanes: &[Vec<(Option<usize>, f64, f64)>],
443+ eqs: &[Vec<Option<EqParams>>],
444+ speeds: &[Vec<Option<crate::project::Stretch>>],
387 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {445 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
388 let [first, rest @ ..] = lanes else {446 let [first, rest @ ..] = lanes else {
389 return Ok(None);447 return Ok(None);
390 };448 };
391 if rest.is_empty() {449 if rest.is_empty() {
392 let flat = Vec::new();450 let flat = Vec::new();
393- return Self::open_multi_streams_eq(sources, first, eqs.first().unwrap_or(&flat));451+ let plain = Vec::new();
452+ return Self::open_multi_streams_speed(
453+ sources,
454+ first,
455+ eqs.first().unwrap_or(&flat),
456+ speeds.first().unwrap_or(&plain),
457+ );
394 }458 }
395 let mut meta = None;459 let mut meta = None;
396 let mut rxs = Vec::with_capacity(lanes.len());460 let mut rxs = Vec::with_capacity(lanes.len());
@@ -398,8 +462,13 @@ impl AudioSession {
398 // Every lane probes the same source 0, so the metas agree by462 // Every lane probes the same source 0, so the metas agree by
399 // construction; `None` from any of them is a silent timeline.463 // construction; `None` from any of them is a silent timeline.
400 let flat = Vec::new();464 let flat = Vec::new();
401- let Some((lane_meta, rx)) =465+ let plain = Vec::new();
402- Self::open_multi_streams_eq(sources, segs, eqs.get(i).unwrap_or(&flat))?466+ let Some((lane_meta, rx)) = Self::open_multi_streams_speed(
467+ sources,
468+ segs,
469+ eqs.get(i).unwrap_or(&flat),
470+ speeds.get(i).unwrap_or(&plain),
471+ )?
403 else {472 else {
404 return Ok(None);473 return Ok(None);
405 };474 };
@@ -1511,6 +1580,104 @@ impl Segment {
1511 }1580 }
1512 }1581 }
1513 1582
1583+/// One speeded segment's resampler: the tape effect, done by reading the
1584+/// decoded samples at a rate other than the one they were written at, so the
1585+/// pitch moves with the speed. Linear interpolation between the two frames a
1586+/// fractional position falls between -- one multiply-add per channel, which is
1587+/// nothing beside the decode that produced them, and enough that a 2x clip is
1588+/// not the aliasing mess plain sample-dropping would give.
1589+///
1590+/// It lives across the whole segment: `pos` carries the fraction over a packet
1591+/// boundary and `tail` keeps the frame before the buffer, so the interpolation
1592+/// at the seam is the same one it would have been inside a buffer. A segment
1593+/// starts one clean and drops it at the end, which is what makes a seek a reset
1594+/// for free -- exactly as the equalizer's state does.
1595+///
1596+/// `owed` is what the timeline gives the segment, in frames per channel:
1597+/// resampling resolves to whole samples and a clip's own window resolves to
1598+/// whole *source* frames, so the two miss each other by a sample or two per
1599+/// clip. Truncating and padding to what is owed keeps that from accumulating
1600+/// into audible drift over a timeline of speeded cuts -- the picture's clip
1601+/// boundaries are exact by construction, and this makes the sound's exact too.
1602+struct Resample {
1603+ /// Source frames per output frame: the speed itself.
1604+ step: f64,
1605+ /// Where the next output frame reads, relative to the current buffer's
1606+ /// first frame. Negative means it reads across the seam, into `tail`.
1607+ pos: f64,
1608+ /// The last frame of the buffer before this one, one sample per channel.
1609+ tail: Vec<f32>,
1610+ /// Output frames per channel still to be emitted for this segment.
1611+ owed: u64,
1612+}
1613+
1614+impl Resample {
1615+ fn new(step: f64, owed: u64) -> Self {
1616+ Self {
1617+ step,
1618+ pos: 0.,
1619+ tail: Vec::new(),
1620+ owed,
1621+ }
1622+ }
1623+
1624+ /// Rewrites `buf` in place as the frames this rate reads out of it. Never
1625+ /// more than is owed, so the segment cannot overrun the room the timeline
1626+ /// gave it.
1627+ fn process(&mut self, buf: &mut Vec<f32>, channels: usize) {
1628+ let frames = buf.len() / channels;
1629+ if frames == 0 || channels == 0 {
1630+ return;
1631+ }
1632+ let mut out: Vec<f32> = Vec::with_capacity(buf.len());
1633+ while self.owed > (out.len() / channels) as u64 {
1634+ let left = self.pos.floor();
1635+ let right = left as i64 + 1;
1636+ if right > frames as i64 - 1 {
1637+ break; // the frame it would interpolate towards is not here yet
1638+ }
1639+ let frac = (self.pos - left) as f32;
1640+ let (left, right) = (left as i64, right as usize);
1641+ for c in 0..channels {
1642+ // Before the buffer means the previous one's last frame; at the
1643+ // very first buffer of a segment `pos` is 0, so this cannot be
1644+ // asked for an empty tail.
1645+ let a = match left < 0 {
1646+ true => self.tail.get(c).copied().unwrap_or(0.),
1647+ false => buf[left as usize * channels + c],
1648+ };
1649+ let b = buf[right * channels + c];
1650+ out.push(a + (b - a) * frac);
1651+ }
1652+ self.pos += self.step;
1653+ }
1654+ self.tail.clear();
1655+ self.tail.extend_from_slice(&buf[(frames - 1) * channels..]);
1656+ self.pos -= frames as f64;
1657+ self.owed -= (out.len() / channels) as u64;
1658+ *buf = out;
1659+ }
1660+
1661+ /// The silence the segment still owes when its source ran out before the
1662+ /// timeline did -- a rounding frame or two, or a clip whose file is shorter
1663+ /// than the edit says. `false` means the consumer went away.
1664+ fn flush(&mut self, channels: usize, timeline: &mut u64, tx: &SyncSender<AudioChunk>) -> bool {
1665+ while self.owed > 0 {
1666+ let frames = self.owed.min(u64::from(SAMPLES_PER_PACKET));
1667+ let chunk = AudioChunk {
1668+ start_sample: *timeline,
1669+ samples: vec![0.0; frames as usize * channels],
1670+ };
1671+ if tx.send(chunk).is_err() {
1672+ return false;
1673+ }
1674+ *timeline += frames;
1675+ self.owed -= frames;
1676+ }
1677+ true
1678+ }
1679+}
1680+
1514 struct Worker {1681 struct Worker {
1515 /// Indexed by [`Segment::source`]; only the sources some segment names are1682 /// Indexed by [`Segment::source`]; only the sources some segment names are
1516 /// `Some`, the rest were never opened.1683 /// `Some`, the rest were never opened.
@@ -1522,6 +1689,10 @@ struct Worker {
1522 /// Beside the segments rather than inside them so the emit path can hold the1689 /// Beside the segments rather than inside them so the emit path can hold the
1523 /// window rules and the filter memory at once without splitting a borrow.1690 /// window rules and the filter memory at once without splitting a borrow.
1524 eqs: Vec<Option<EqState>>,1691 eqs: Vec<Option<EqState>>,
1692+ /// One per entry of `segments` again: the rate that segment is read at, or
1693+ /// `None` for one at real time -- which is every segment of a project nobody
1694+ /// has speeded, and the path that emits the decoder's own samples untouched.
1695+ speeds: Vec<Option<Resample>>,
1525 /// `start_sample` of the first chunk.1696 /// `start_sample` of the first chunk.
1526 timeline: u64,1697 timeline: u64,
1527 tx: SyncSender<AudioChunk>,1698 tx: SyncSender<AudioChunk>,
@@ -1603,8 +1774,11 @@ fn run(mut w: Worker) {
1603 // A short list is "flat from here on" (`open_multi_streams_eq`), which this1774 // A short list is "flat from here on" (`open_multi_streams_eq`), which this
1604 // pads out so the zip below still walks every segment.1775 // pads out so the zip below still walks every segment.
1605 eqs.resize_with(segments.len(), || None);1776 eqs.resize_with(segments.len(), || None);
1777+ let mut speeds = std::mem::take(&mut w.speeds);
1778+ // ...and a short rate list is "real time from here on", for the same reason.
1779+ speeds.resize_with(segments.len(), || None);
1606 1780
1607- for (seg, eq) in segments.iter().zip(eqs.iter_mut()) {1781+ for ((seg, eq), speed) in segments.iter().zip(eqs.iter_mut()).zip(speeds.iter_mut()) {
1608 let Some(source) = seg.source else {1782 let Some(source) = seg.source else {
1609 // A gap: hand the device real silence rather than nothing at all,1783 // A gap: hand the device real silence rather than nothing at all,
1610 // in the same packet-sized chunks decoding produces, so `fed` and1784 // in the same packet-sized chunks decoding produces, so `fed` and
@@ -1629,13 +1803,31 @@ fn run(mut w: Worker) {
1629 };1803 };
1630 let track = match track {1804 let track = match track {
1631 Track::Sym(track) => {1805 Track::Sym(track) => {
1632- if !run_sym(track, seg, eq.as_mut(), channels, &mut timeline, &w.tx) {1806+ if !run_sym(
1807+ track,
1808+ seg,
1809+ eq.as_mut(),
1810+ speed,
1811+ channels,
1812+ &mut timeline,
1813+ &w.tx,
1814+ ) || !settle(speed, channels, &mut timeline, &w.tx)
1815+ {
1633 return; // consumer went away1816 return; // consumer went away
1634 }1817 }
1635 continue;1818 continue;
1636 }1819 }
1637 Track::Ac3(track) => {1820 Track::Ac3(track) => {
1638- if !run_ac3(track, seg, eq.as_mut(), channels, &mut timeline, &w.tx) {1821+ if !run_ac3(
1822+ track,
1823+ seg,
1824+ eq.as_mut(),
1825+ speed,
1826+ channels,
1827+ &mut timeline,
1828+ &w.tx,
1829+ ) || !settle(speed, channels, &mut timeline, &w.tx)
1830+ {
1639 return; // consumer went away1831 return; // consumer went away
1640 }1832 }
1641 continue;1833 continue;
@@ -1684,6 +1876,7 @@ fn run(mut w: Worker) {
1684 channels,1876 channels,
1685 seg,1877 seg,
1686 eq.as_mut(),1878 eq.as_mut(),
1879+ speed.as_mut(),
1687 pos,1880 pos,
1688 next,1881 next,
1689 &mut timeline,1882 &mut timeline,
@@ -1693,6 +1886,24 @@ fn run(mut w: Worker) {
1693 }1886 }
1694 pos = next;1887 pos = next;
1695 }1888 }
1889+ if !settle(speed, channels, &mut timeline, &w.tx) {
1890+ return; // consumer went away
1891+ }
1892+ }
1893+}
1894+
1895+/// Pays out whatever silence a speeded segment still owes the timeline (see
1896+/// [`Resample::flush`]). Nothing at all at real time, where a segment owes the
1897+/// timeline only the samples it decoded.
1898+fn settle(
1899+ speed: &mut Option<Resample>,
1900+ channels: usize,
1901+ timeline: &mut u64,
1902+ tx: &SyncSender<AudioChunk>,
1903+) -> bool {
1904+ match speed {
1905+ Some(speed) => speed.flush(channels, timeline, tx),
1906+ None => true,
1696 }1907 }
1697 }1908 }
1698 1909
@@ -1717,6 +1928,7 @@ fn emit(
1717 channels: usize,1928 channels: usize,
1718 seg: &Segment,1929 seg: &Segment,
1719 eq: Option<&mut EqState>,1930 eq: Option<&mut EqState>,
1931+ speed: Option<&mut Resample>,
1720 pos: u64,1932 pos: u64,
1721 next: u64,1933 next: u64,
1722 timeline: &mut u64,1934 timeline: &mut u64,
@@ -1736,6 +1948,16 @@ fn emit(
1736 if interleaved.is_empty() {1948 if interleaved.is_empty() {
1737 return true; // nothing left of it; the loop head ends the segment1949 return true; // nothing left of it; the loop head ends the segment
1738 }1950 }
1951+ // The rate first, the filter second: what the equalizer's bands are set in
1952+ // is the frequency a listener hears, and after a resample that is not the
1953+ // frequency the file was written at. A segment at real time has no
1954+ // resampler at all and reaches the filter with the decoder's own samples.
1955+ if let Some(speed) = speed {
1956+ speed.process(interleaved, channels);
1957+ if interleaved.is_empty() {
1958+ return true; // this buffer resolved to no output frame of its own
1959+ }
1960+ }
1739 if let Some(eq) = eq {1961 if let Some(eq) = eq {
1740 eq.process(interleaved);1962 eq.process(interleaved);
1741 }1963 }
@@ -1755,6 +1977,7 @@ fn run_ac3(
1755 track: &mut Ac3Track,1977 track: &mut Ac3Track,
1756 seg: &Segment,1978 seg: &Segment,
1757 mut eq: Option<&mut EqState>,1979 mut eq: Option<&mut EqState>,
1980+ speed: &mut Option<Resample>,
1758 channels: usize,1981 channels: usize,
1759 timeline: &mut u64,1982 timeline: &mut u64,
1760 tx: &SyncSender<AudioChunk>,1983 tx: &SyncSender<AudioChunk>,
@@ -1794,6 +2017,7 @@ fn run_ac3(
1794 channels,2017 channels,
1795 seg,2018 seg,
1796 eq.as_deref_mut(),2019 eq.as_deref_mut(),
2020+ speed.as_mut(),
1797 pos,2021 pos,
1798 next,2022 next,
1799 timeline,2023 timeline,
@@ -1819,6 +2043,7 @@ fn run_sym(
1819 track: &mut SymTrack,2043 track: &mut SymTrack,
1820 seg: &Segment,2044 seg: &Segment,
1821 mut eq: Option<&mut EqState>,2045 mut eq: Option<&mut EqState>,
2046+ speed: &mut Option<Resample>,
1822 channels: usize,2047 channels: usize,
1823 timeline: &mut u64,2048 timeline: &mut u64,
1824 tx: &SyncSender<AudioChunk>,2049 tx: &SyncSender<AudioChunk>,
@@ -1876,6 +2101,7 @@ fn run_sym(
1876 channels,2101 channels,
1877 seg,2102 seg,
1878 eq.as_deref_mut(),2103 eq.as_deref_mut(),
2104+ speed.as_mut(),
1879 pos,2105 pos,
1880 next,2106 next,
1881 timeline,2107 timeline,
crates/engine/src/edith.rsmodified+159 -45
@@ -1,16 +1,16 @@
1 //! The project file: a line of text per thing, and nothing else.1 //! The project file: a line of text per thing, and nothing else.
2 //!2 //!
3 //! ```text3 //! ```text
4-//! edith 74+//! edith 8
5 //! playhead 905 //! playhead 90
6 //! resolution 1920 10806 //! resolution 1920 1080
7 //! source 0 test_av.mp47 //! source 0 test_av.mp4
8 //! source 1 /elsewhere/test_av2.mp48 //! source 1 /elsewhere/test_av2.mp4
9 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk9 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
10 //! color 0.1:1.2:0.9:-0.310 //! color 0.1:1.2:0.9:-0.3
11-//! video 1 0 0 120 0 0 0 0 fit11+//! video 1 0 0 120 0 0 0 0 fit 1000
12-//! audio 1 0 0 120 0 0 0 - fit12+//! audio 1 0 0 120 0 0 0 - fit 1000
13-//! video 2 120 0 120 1 - - - fill13+//! video 2 120 0 120 1 - - - fill 2000
14 //! audio 214 //! audio 2
15 //! ```15 //! ```
16 //!16 //!
@@ -39,22 +39,28 @@
39 //! -- the first colour line is color 0 -- printed and refused by the same rules.39 //! -- the first colour line is color 0 -- printed and refused by the same rules.
40 //!40 //!
41 //! A lane line is `<kind> <lane> <start> <in> <out> <source> <link> <eq>41 //! A lane line is `<kind> <lane> <start> <in> <out> <source> <link> <eq>
42-//! <color> <fit>`: which lane the clip is on -- its kind and its 1-based number42+//! <color> <fit> <speed>`: which lane the clip is on -- its kind and its 1-based number
43 //! among the lanes of that kind, the [`crate::project::Lane::label`] a header43 //! among the lanes of that kind, the [`crate::project::Lane::label`] a header
44 //! column shows -- then where the clip sits on the timeline, the half-open44 //! column shows -- then where the clip sits on the timeline, the half-open
45 //! source range it plays, the file it plays from, its group id, the eq line it45 //! source range it plays, the file it plays from, its group id, the eq line it
46 //! plays through, the colour line it is graded by (`-` for none of those three)46 //! plays through, the colour line it is graded by (`-` for none of those three)
47 //! and how it meets a project canvas of another shape, spelled `fit`, `fill`,47 //! and how it meets a project canvas of another shape, spelled `fit`, `fill`,
48-//! `stretch` or `center` ([`crate::scale::FitPolicy`]). Timeline placement is48+//! `stretch` or `center` ([`crate::scale::FitPolicy`]), and how fast it plays,
49+//! in thousandths of real time ([`crate::project::Speed`], `1000` for a clip
50+//! nobody has speeded). Timeline placement is
49 //! explicit, so a *gap* is simply a stretch no line covers -- there is nothing51 //! explicit, so a *gap* is simply a stretch no line covers -- there is nothing
50-//! to write for one, and nothing that can disagree about its length.52+//! to write for one, and nothing that can disagree about its length. The `<in>`
53+//! and `<out>` are *source* frames whatever the speed says: how long the clip is
54+//! on the timeline is that range divided by the rate, and is written nowhere.
51 //!55 //!
52 //! A lane is declared by the clips on it, in the order the lanes are displayed56 //! A lane is declared by the clips on it, in the order the lanes are displayed
53 //! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which57 //! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
54 //! is the only way an empty lane could still be there on the way back. A lane58 //! is the only way an empty lane could still be there on the way back. A lane
55 //! number may not skip one of its kind.59 //! number may not skip one of its kind.
56 //!60 //!
57-//! **Version 6** was this without the `resolution` line and without the clip's61+//! **Version 7** was this without the clip's speed field -- every clip of such
62+//! a project plays at real time, which is the only rate there was.
63+//! **Version 6** was that without the `resolution` line and without the clip's
58 //! fit field -- such a project is the size of its first source and letterboxes64 //! fit field -- such a project is the size of its first source and letterboxes
59 //! nothing, because nothing on it could differ in size. **Version 5** was that65 //! nothing, because nothing on it could differ in size. **Version 5** was that
60 //! without the colour lines and without the clip's colour66 //! without the colour lines and without the clip's colour
@@ -63,10 +69,11 @@
63 //! lane and one audio lane, no more. **Version 2** wrote `source <path>` as69 //! lane and one audio lane, no more. **Version 2** wrote `source <path>` as
64 //! well, which is this file's stream 0 -- one per file, whichever audio track70 //! well, which is this file's stream 0 -- one per file, whichever audio track
65 //! came first. **Version 1** wrote that and one lane, queued end to end: `clip71 //! came first. **Version 1** wrote that and one lane, queued end to end: `clip
66-//! <in> <out> <source>`. All five still load -- a v1 file's clips are laid out72+//! <in> <out> <source>`. All six still load -- a v1 file's clips are laid out
67 //! cumulatively and copied onto both lanes as one group each, which is exactly73 //! cumulatively and copied onto both lanes as one group each, which is exactly
68 //! what a v1 timeline meant, and an older file simply equalizes and grades74 //! what a v1 timeline meant, and an older file simply equalizes and grades
69-//! nothing -- and saving any of them writes v7. An older reader refuses a newer75+//! nothing, and an older one plays everything at real time -- and saving any of
76+//! them writes v8. An older reader refuses a newer
70 //! file by name.77 //! file by name.
71 //!78 //!
72 //! Text because an edit list is a few integers and a path, and a path is79 //! Text because an edit list is a few integers and a path, and a path is
@@ -95,12 +102,13 @@ use std::path::{Path, PathBuf};
95 102
96 use crate::color::ColorParams;103 use crate::color::ColorParams;
97 use crate::eq::{Band, BandKind, EqParams};104 use crate::eq::{Band, BandKind, EqParams};
98-use crate::project::{Clip, Lane, LaneKind, Source};105+use crate::project::{Clip, Lane, LaneKind, Source, Speed};
99 use crate::scale::FitPolicy;106 use crate::scale::FitPolicy;
100 107
101 /// What [`save`] writes. Read support goes back to `edith 1`; see the module108 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
102 /// docs for what those dialects looked like.109 /// docs for what those dialects looked like.
103-const MAGIC: &[u8] = b"edith 7";110+const MAGIC: &[u8] = b"edith 8";
111+const MAGIC_V7: &[u8] = b"edith 7";
104 const MAGIC_V6: &[u8] = b"edith 6";112 const MAGIC_V6: &[u8] = b"edith 6";
105 const MAGIC_V5: &[u8] = b"edith 5";113 const MAGIC_V5: &[u8] = b"edith 5";
106 const MAGIC_V4: &[u8] = b"edith 4";114 const MAGIC_V4: &[u8] = b"edith 4";
@@ -256,12 +264,13 @@ fn emit(
256 let color = c.color.map_or("-".to_string(), |e| e.to_string());264 let color = c.color.map_or("-".to_string(), |e| e.to_string());
257 out.extend_from_slice(265 out.extend_from_slice(
258 format!(266 format!(
259- "{keyword} {ord} {} {} {} {} {link} {eq} {color} {}\n",267+ "{keyword} {ord} {} {} {} {} {link} {eq} {color} {} {}\n",
260 c.start,268 c.start,
261 c.in_frame,269 c.in_frame,
262 c.out_frame,270 c.out_frame,
263 c.source,271 c.source,
264- fit_name(c.fit)272+ fit_name(c.fit),
273+ c.speed.permille()
265 )274 )
266 .as_bytes(),275 .as_bytes(),
267 );276 );
@@ -280,8 +289,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
280 // The dialects that wrote a source line without its stream field. Reading289 // The dialects that wrote a source line without its stream field. Reading
281 // one is the whole of what "an old project still opens" means here.290 // one is the whole of what "an old project still opens" means here.
282 let streamless = v1 || first == MAGIC_V2;291 let streamless = v1 || first == MAGIC_V2;
283- // The one that carries a project resolution and per-clip fit policies...292+ // The one that carries a per-clip speed...
284- let v7 = first == MAGIC;293+ let v8 = first == MAGIC;
294+ // ...the ones that carry a project resolution and per-clip fit policies...
295+ let v7 = v8 || first == MAGIC_V7;
285 // ...the ones that carry colour grades...296 // ...the ones that carry colour grades...
286 let v6 = v7 || first == MAGIC_V6;297 let v6 = v7 || first == MAGIC_V6;
287 // ...the ones that carry equalizer settings...298 // ...the ones that carry equalizer settings...
@@ -430,6 +441,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
430 eq: None,441 eq: None,
431 color: None,442 color: None,
432 fit: FitPolicy::default(),443 fit: FitPolicy::default(),
444+ speed: Speed::NORMAL,
433 },445 },
434 &doc,446 &doc,
435 n,447 n,
@@ -459,9 +471,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
459 if numbered && rest.is_empty() {471 if numbered && rest.is_empty() {
460 continue;472 continue;
461 }473 }
462- // v7 grew the fit field, v6 the colour one and v5 the eq one;474+ // v8 grew the speed field, v7 the fit one, v6 the colour one and
463- // every older dialect ends at the link.475+ // v5 the eq one; every older dialect ends at the link.
464- let want = 5 + usize::from(v5) + usize::from(v6) + usize::from(v7);476+ let want =
477+ 5 + usize::from(v5) + usize::from(v6) + usize::from(v7) + usize::from(v8);
465 let f = fields(rest, want, "clip", n)?;478 let f = fields(rest, want, "clip", n)?;
466 let clip = check(479 let clip = check(
467 Clip {480 Clip {
@@ -476,6 +489,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
476 eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?,489 eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?,
477 color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?,490 color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?,
478 fit: fit_policy(f.get(7).copied(), n)?,491 fit: fit_policy(f.get(7).copied(), n)?,
492+ speed: speed_of(f.get(8).copied(), n)?,
479 },493 },
480 &doc,494 &doc,
481 n,495 n,
@@ -581,7 +595,7 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
581 // Everything downstream -- `Clip::end`, the overlap check, the v1 queue --595 // Everything downstream -- `Clip::end`, the overlap check, the v1 queue --
582 // adds `start + len` as plain `u32`, which panics in debug and wraps in596 // adds `start + len` as plain `u32`, which panics in debug and wraps in
583 // release on a crafted file. Bound it here, at the door.597 // release on a crafted file. Bound it here, at the door.
584- if clip.start.checked_add(clip.len()).is_none() {598+ if clip.start.checked_add(clip.frames()).is_none() {
585 return Err(format!(599 return Err(format!(
586 "line {line}: clip at {} runs past the last frame there is",600 "line {line}: clip at {} runs past the last frame there is",
587 clip.start601 clip.start
@@ -591,6 +605,29 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
591 Ok(clip)605 Ok(clip)
592 }606 }
593 607
608+/// A clip's `<speed>` field: thousandths of real time, as
609+/// [`crate::project::Speed`] holds it -- `1000` is the rate it was shot at. A
610+/// dialect with no such field (everything before v8) means real time, which is
611+/// what such a project always played at. A number outside the range the editor
612+/// can set is *refused* rather than clamped: a project file is generated, so
613+/// that is a corrupt line and not a dialect.
614+fn speed_of(field: Option<&[u8]>, line: usize) -> crate::Result<Speed> {
615+ let Some(field) = field else {
616+ return Ok(Speed::NORMAL);
617+ };
618+ let permille = number(field, line)?;
619+ let speed = Speed::from_permille(permille.min(u32::from(u16::MAX)) as u16);
620+ if u32::from(speed.permille()) != permille {
621+ return Err(format!(
622+ "line {line}: speed {permille} is outside {}-{} thousandths",
623+ Speed::MIN.permille(),
624+ Speed::MAX.permille()
625+ )
626+ .into());
627+ }
628+ Ok(speed)
629+}
630+
594 /// How a fit policy is spelled in the file. One word each, so a clip line stays631 /// How a fit policy is spelled in the file. One word each, so a clip line stays
595 /// readable, and the same word the parser takes back.632 /// readable, and the same word the parser takes back.
596 fn fit_name(fit: FitPolicy) -> &'static str {633 fn fit_name(fit: FitPolicy) -> &'static str {
@@ -746,6 +783,7 @@ mod tests {
746 eq: None,783 eq: None,
747 color: None,784 color: None,
748 fit: FitPolicy::default(),785 fit: FitPolicy::default(),
786+ speed: Speed::NORMAL,
749 }787 }
750 }788 }
751 789
@@ -795,10 +833,10 @@ mod tests {
795 let bytes = flat(&dir, &sources, &lanes, 12);833 let bytes = flat(&dir, &sources, &lanes, 12);
796 assert_eq!(834 assert_eq!(
797 String::from_utf8_lossy(&bytes),835 String::from_utf8_lossy(&bytes),
798- "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\836+ "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
799 source 2 /elsewhere/b.mp4\n\837 source 2 /elsewhere/b.mp4\n\
800- video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\838+ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
801- audio 1 0 0 30 0 0 - - fit\n",839+ audio 1 0 0 30 0 0 - - fit 1000\n",
802 "the file under the project directory is written relative to it, \840 "the file under the project directory is written relative to it, \
803 each with the audio stream it plays"841 each with the audio stream it plays"
804 );842 );
@@ -832,9 +870,9 @@ mod tests {
832 let bytes = flat(&dir, &sources, &lanes, 7);870 let bytes = flat(&dir, &sources, &lanes, 7);
833 assert_eq!(871 assert_eq!(
834 String::from_utf8_lossy(&bytes),872 String::from_utf8_lossy(&bytes),
835- "edith 7\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\873+ "edith 8\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
836- video 1 0 0 30 0 4 - - fit\naudio 1\n\874+ video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\
837- video 2 40 0 10 0 - - - fit\naudio 2 0 0 30 0 4 - - fit\n",875+ video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",
838 "an empty lane is a line of its own; everything else is its clips"876 "an empty lane is a line of its own; everything else is its clips"
839 );877 );
840 let back = parse(&bytes, &dir).expect("parse");878 let back = parse(&bytes, &dir).expect("parse");
@@ -940,12 +978,12 @@ mod tests {
940 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);978 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
941 assert_eq!(979 assert_eq!(
942 String::from_utf8_lossy(&bytes),980 String::from_utf8_lossy(&bytes),
943- "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\981+ "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
944 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\982 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
945 eq 16777215.0:-0.1:3.918315e-39:hs\n\983 eq 16777215.0:-0.1:3.918315e-39:hs\n\
946 eq\n\984 eq\n\
947- video 1 0 0 30 0 0 0 - fit\nvideo 1 30 10 20 0 - 1 - fit\n\985+ video 1 0 0 30 0 0 0 - fit 1000\nvideo 1 30 10 20 0 - 1 - fit 1000\n\
948- audio 1 0 0 30 0 0 0 - fit\naudio 1 30 0 10 0 - 2 - fit\n",986+ audio 1 0 0 30 0 0 0 - fit 1000\naudio 1 30 0 10 0 - 2 - fit 1000\n",
949 "the table comes before the clips, and a clip names a line of it"987 "the table comes before the clips, and a clip names a line of it"
950 );988 );
951 989
@@ -1016,11 +1054,13 @@ mod tests {
1016 Clip {1054 Clip {
1017 color: Some(0),1055 color: Some(0),
1018 fit: FitPolicy::default(),1056 fit: FitPolicy::default(),
1057+ speed: Speed::NORMAL,
1019 ..clip(0, 0, 30, 0, Some(0))1058 ..clip(0, 0, 30, 0, Some(0))
1020 },1059 },
1021 Clip {1060 Clip {
1022 color: Some(1),1061 color: Some(1),
1023 fit: FitPolicy::default(),1062 fit: FitPolicy::default(),
1063+ speed: Speed::NORMAL,
1024 ..clip(30, 10, 20, 0, None)1064 ..clip(30, 10, 20, 0, None)
1025 },1065 },
1026 ],1066 ],
@@ -1028,11 +1068,13 @@ mod tests {
1028 Clip {1068 Clip {
1029 color: Some(0),1069 color: Some(0),
1030 fit: FitPolicy::default(),1070 fit: FitPolicy::default(),
1071+ speed: Speed::NORMAL,
1031 ..clip(0, 0, 30, 0, Some(0))1072 ..clip(0, 0, 30, 0, Some(0))
1032 },1073 },
1033 Clip {1074 Clip {
1034 color: Some(2),1075 color: Some(2),
1035 fit: FitPolicy::default(),1076 fit: FitPolicy::default(),
1077+ speed: Speed::NORMAL,
1036 ..clip(30, 0, 10, 0, None)1078 ..clip(30, 0, 10, 0, None)
1037 },1079 },
1038 ],1080 ],
@@ -1040,12 +1082,12 @@ mod tests {
1040 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);1082 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
1041 assert_eq!(1083 assert_eq!(
1042 String::from_utf8_lossy(&bytes),1084 String::from_utf8_lossy(&bytes),
1043- "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\1085+ "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1044 color 0.1:1.2:0.9:-0.3\n\1086 color 0.1:1.2:0.9:-0.3\n\
1045 color -1e-7:16777215.0:3.918315e-39:-0.0\n\1087 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
1046 color 0.0:1.0:1.0:0.0\n\1088 color 0.0:1.0:1.0:0.0\n\
1047- video 1 0 0 30 0 0 - 0 fit\nvideo 1 30 10 20 0 - - 1 fit\n\1089+ video 1 0 0 30 0 0 - 0 fit 1000\nvideo 1 30 10 20 0 - - 1 fit 1000\n\
1048- audio 1 0 0 30 0 0 - 0 fit\naudio 1 30 0 10 0 - - 2 fit\n",1090+ audio 1 0 0 30 0 0 - 0 fit 1000\naudio 1 30 0 10 0 - - 2 fit 1000\n",
1049 "the table comes before the clips, and a clip names a line of it"1091 "the table comes before the clips, and a clip names a line of it"
1050 );1092 );
1051 1093
@@ -1105,9 +1147,81 @@ mod tests {
1105 (1280, 720),1147 (1280, 720),
1106 old.playhead1148 old.playhead
1107 )),1149 )),
1108- "edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\1150+ "edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1109 eq 80.0:-3.0:0.707:ls\n\1151 eq 80.0:-3.0:0.707:ls\n\
1110- video 1 0 0 30 0 0 0 - fit\naudio 1 0 0 30 0 0 - - fit\n"1152+ video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
1153+ );
1154+ }
1155+
1156+ /// The whole of the v8 bump, the eq and colour tests' twin: a clip's rate is
1157+ /// written on its own line, comes back as the very number that was set, and
1158+ /// a v7 file -- which has no such field -- loads at real time and re-saves
1159+ /// saying so.
1160+ #[test]
1161+ fn speeds_round_trip_and_a_v7_file_plays_at_real_time() {
1162+ let dir = PathBuf::from("/proj");
1163+ let sources = vec![Source::new("/proj/a.mp4", 0)];
1164+ let speeded = |start, in_frame, out_frame, permille| Clip {
1165+ start,
1166+ in_frame,
1167+ out_frame,
1168+ source: 0,
1169+ link: None,
1170+ eq: None,
1171+ color: None,
1172+ fit: FitPolicy::default(),
1173+ speed: Speed::from_permille(permille),
1174+ };
1175+ // 30 source frames at 2x is 15 timeline frames, which is where the
1176+ // second clip starts -- the file writes the source range and the rate,
1177+ // and the length on the timeline is derived from the two.
1178+ let lanes = vec![
1179+ (
1180+ LaneKind::Video,
1181+ vec![speeded(0, 0, 30, 2000), speeded(15, 30, 40, 250)],
1182+ ),
1183+ (LaneKind::Audio, vec![speeded(0, 0, 30, 2000)]),
1184+ ];
1185+ let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
1186+ assert_eq!(
1187+ String::from_utf8_lossy(&bytes),
1188+ "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1189+ video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\
1190+ audio 1 0 0 30 0 - - - fit 2000\n",
1191+ "the rate is the clip line's last field, in thousandths"
1192+ );
1193+ let back = parse(&bytes, &dir).expect("parse");
1194+ assert_eq!(back.lanes, lanes, "every clip keeps the rate it named");
1195+
1196+ // ...and the dialect before it, which had no rate to name.
1197+ let v7 = b"edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1198+ video 1 0 0 30 0 0 - - fit\naudio 1 0 0 30 0 0 - - fit\n";
1199+ let old = parse(v7, &dir).expect("v7 parses");
1200+ assert!(
1201+ old.lanes
1202+ .iter()
1203+ .flat_map(|(_, clips)| clips)
1204+ .all(|c| c.speed == Speed::NORMAL),
1205+ "nothing before v8 plays at anything but real time"
1206+ );
1207+ assert_eq!(
1208+ String::from_utf8_lossy(&emit(
1209+ &dir,
1210+ &old.sources,
1211+ &old.lanes,
1212+ &old.eq,
1213+ &old.color,
1214+ (1280, 720),
1215+ old.playhead
1216+ )),
1217+ "edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1218+ video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
1219+ );
1220+ // A rate outside what the editor can set is a corrupt line, by name.
1221+ let bad = b"edith 8\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 9000\n";
1222+ assert_eq!(
1223+ parse(bad, &dir).unwrap_err().to_string(),
1224+ "line 3: speed 9000 is outside 250-4000 thousandths"
1111 );1225 );
1112 }1226 }
1113 1227
@@ -1241,10 +1355,10 @@ mod tests {
1241 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");1355 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
1242 assert_eq!(1356 assert_eq!(
1243 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),1357 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
1244- "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\1358+ "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1245 source 2 /elsewhere/b.mp4\n\1359 source 2 /elsewhere/b.mp4\n\
1246- video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\1360+ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1247- audio 1 0 0 30 0 0 - - fit\n"1361+ audio 1 0 0 30 0 0 - - fit 1000\n"
1248 );1362 );
1249 // An empty lane's line is still the whole of that lane, eq or no eq.1363 // An empty lane's line is still the whole of that lane, eq or no eq.
1250 let empty = parse(1364 let empty = parse(
@@ -1294,10 +1408,10 @@ mod tests {
1294 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);1408 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1295 assert_eq!(1409 assert_eq!(
1296 String::from_utf8_lossy(&v5),1410 String::from_utf8_lossy(&v5),
1297- "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\1411+ "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1298 source 0 /elsewhere/b.mp4\n\1412 source 0 /elsewhere/b.mp4\n\
1299- video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\1413+ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1300- audio 1 0 0 30 0 0 - - fit\n",1414+ audio 1 0 0 30 0 0 - - fit 1000\n",
1301 "a re-saved v2 project differs only by its version, the lane \1415 "a re-saved v2 project differs only by its version, the lane \
1302 numbers, the streams it always meant and an equalizer it has none of"1416 numbers, the streams it always meant and an equalizer it has none of"
1303 );1417 );
@@ -1326,7 +1440,7 @@ mod tests {
1326 // Saved again it is the current version, which round-trips to the1440 // Saved again it is the current version, which round-trips to the
1327 // same document.1441 // same document.
1328 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);1442 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1329- assert!(v5.starts_with(b"edith 7\n"));1443+ assert!(v5.starts_with(b"edith 8\n"));
1330 let again = parse(&v5, &dir).expect("v5 parses");1444 let again = parse(&v5, &dir).expect("v5 parses");
1331 assert_eq!(again.lanes, back.lanes);1445 assert_eq!(again.lanes, back.lanes);
1332 // A dialect may not be mixed: lane lines under v1, `clip` under v2.1446 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
@@ -1428,8 +1542,8 @@ mod tests {
1428 let bytes = std::fs::read(&path).expect("read back");1542 let bytes = std::fs::read(&path).expect("read back");
1429 assert_eq!(1543 assert_eq!(
1430 String::from_utf8_lossy(&bytes),1544 String::from_utf8_lossy(&bytes),
1431- "edith 7\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\1545+ "edith 8\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
1432- video 1 0 0 30 0 - - - fit\naudio 1 0 0 30 0 - - - fit\n"1546+ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
1433 );1547 );
1434 // Loading rejoins the *given* directory, so the file is reached by the1548 // Loading rejoins the *given* directory, so the file is reached by the
1435 // way the project was opened -- the same file, through the link, still1549 // way the project was opened -- the same file, through the link, still
@@ -1473,10 +1587,10 @@ mod tests {
1473 #[test]1587 #[test]
1474 fn a_wrong_first_line_is_refused_by_name() {1588 fn a_wrong_first_line_is_refused_by_name() {
1475 let dir = PathBuf::from("/proj");1589 let dir = PathBuf::from("/proj");
1476- let err = parse(b"edith 8\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)1590+ let err = parse(b"edith 9\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
1477 .unwrap_err()1591 .unwrap_err()
1478 .to_string();1592 .to_string();
1479- assert_eq!(err, "line 1: unsupported version 8");1593+ assert_eq!(err, "line 1: unsupported version 9");
1480 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {1594 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
1481 assert_eq!(1595 assert_eq!(
1482 parse(junk, &dir).unwrap_err().to_string(),1596 parse(junk, &dir).unwrap_err().to_string(),
crates/engine/src/export.rsmodified+45 -1
@@ -317,6 +317,42 @@ fn copy_audio(
317 AudioSession::copy_multi_streams(&project.audio_sources(), segments)317 AudioSession::copy_multi_streams(&project.audio_sources(), segments)
318 }318 }
319 319
320+/// The picture formats' answer to a speeded clip: **refused, by name**.
321+///
322+/// A clip at another rate is a clip whose pictures have to be picked out of its
323+/// source at that rate and whose sound has to be resampled. The sound alone
324+/// settles it here: this path *copies* AAC packets ([`copy_audio`]) and a
325+/// resample is not a copy -- exporting it anyway would write the picture at one
326+/// speed and the sound at another, which is the one failure a user would not
327+/// notice until the file was somewhere else. So the whole export is refused
328+/// rather than half-honoured, and the refusal says which clip and what to do:
329+/// WAV and FLAC are decoded and mixed, and they honour it.
330+///
331+/// AV1 carries no sound at all and could honour the picture on its own, and is
332+/// refused with the rest: a video export that silently dropped the rate on one
333+/// format and kept it on another would be worse than one rule.
334+///
335+/// ponytail: the ceiling is the packet copy and the frame walk in [`run`], which
336+/// steps its decoder once per output picture. Upgrade path is a `skip(n)` on
337+/// [`ClipDecoder`] for a rate above real time, a held picture below it, and an
338+/// AAC encoder (or a decode-and-re-encode) for the sound -- at which point this
339+/// check becomes the `Format::Av1` arm alone.
340+fn speeds_refused(project: &Project, meta: &VideoMeta) -> crate::Result<()> {
341+ for lane in project.lanes() {
342+ if let Some(clip) = project.lane(lane).iter().find(|c| !c.speed.is_normal()) {
343+ return Err(format!(
344+ "the {} clip at {} plays at {} and a picture export cannot re-time it: \
345+ export WAV or FLAC, which are resampled, or set that clip back to 1.00x",
346+ lane.label(),
347+ timecode(clip.start, meta.frame_rate),
348+ clip.speed
349+ )
350+ .into());
351+ }
352+ }
353+ Ok(())
354+}
355+
320 fn run(356 fn run(
321 project: &Project,357 project: &Project,
322 meta: &VideoMeta,358 meta: &VideoMeta,
@@ -325,6 +361,7 @@ fn run(
325 settings: &ExportSettings,361 settings: &ExportSettings,
326 ) -> crate::Result<()> {362 ) -> crate::Result<()> {
327 let total = project.timeline_frames();363 let total = project.timeline_frames();
364+ speeds_refused(project, meta)?;
328 let sources = project.sources();365 let sources = project.sources();
329 // Audio first: a track has to be declared when the muxer is created, which366 // Audio first: a track has to be declared when the muxer is created, which
330 // happens as soon as the first coded picture arrives. None of it for AV1 --367 // happens as soon as the first coded picture arrives. None of it for AV1 --
@@ -502,7 +539,14 @@ fn run_audio(
502 // playback's feeder reads from -- there is no second place here that could539 // playback's feeder reads from -- there is no second place here that could
503 // apply them differently.540 // apply them differently.
504 let eqs = project.audio_eqs_from(0, meta.frame_rate);541 let eqs = project.audio_eqs_from(0, meta.frame_rate);
505- let Some((audio, chunks)) = AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs)? else {542+ // ...and the rates with them, for exactly the same reason: a speeded clip is
543+ // resampled inside the worker playback feeds from, so a WAV of a timeline at
544+ // 2x is half as long and holds the samples that were heard -- not a
545+ // second pass here that could disagree with what the ear got.
546+ let speeds = project.audio_speeds_from(0, meta.frame_rate);
547+ let Some((audio, chunks)) =
548+ AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds)?
549+ else {
506 return Err("this timeline has no audio to export".into());550 return Err("this timeline has no audio to export".into());
507 };551 };
508 let channels = usize::from(audio.channels);552 let channels = usize::from(audio.channels);
crates/engine/src/lib.rsmodified+1 -1
@@ -26,7 +26,7 @@ pub use demux::{Codec, VideoMeta};
26 pub use export::ExportHandle;26 pub use export::ExportHandle;
27 pub use mux::{AudioParams, Mp4Muxer, VideoParams};27 pub use mux::{AudioParams, Mp4Muxer, VideoParams};
28 pub use playback::PlaybackSession;28 pub use playback::PlaybackSession;
29-pub use project::{Clip, Project};29+pub use project::{Clip, Project, Speed};
30 30
31 /// Whether a path names a standalone audio file -- a source with no picture,31 /// Whether a path names a standalone audio file -- a source with no picture,
32 /// which belongs on the audio lane and nowhere else. Extension only, lowercased:32 /// which belongs on the audio lane and nowhere else. Extension only, lowercased:
crates/engine/src/playback.rsmodified+65 -13
@@ -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};28+use crate::project::{Clip, Edge, Lane, LaneKind, Project, 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
@@ -309,6 +309,7 @@ impl PlaybackSession {
309 eq: None,309 eq: None,
310 color: None,310 color: None,
311 fit: FitPolicy::default(),311 fit: FitPolicy::default(),
312+ speed: Speed::NORMAL,
312 };313 };
313 let project = Project::from_parts(314 let project = Project::from_parts(
314 vec![Source::new(path, 0)],315 vec![Source::new(path, 0)],
@@ -374,6 +375,7 @@ impl PlaybackSession {
374 eq: None,375 eq: None,
375 color: None,376 color: None,
376 fit: FitPolicy::default(),377 fit: FitPolicy::default(),
378+ speed: Speed::NORMAL,
377 };379 };
378 // No group and no audio clip: a still is silent, and a clip on `A1`380 // No group and no audio clip: a still is silent, and a clip on `A1`
379 // playing from a PNG is a source the audio worker cannot open.381 // playing from a PNG is a source the audio worker cannot open.
@@ -654,10 +656,17 @@ impl PlaybackSession {
654 // A gap's worker indexes from zero, a decoder's from its in656 // A gap's worker indexes from zero, a decoder's from its in
655 // point: `base` is whichever this span started at. An empty657 // point: `base` is whichever this span started at. An empty
656 // timeline has no span, and its one black frame is frame 0.658 // timeline has no span, and its one black frame is frame 0.
657- let (start, base) = self659+ let (start, base, speed) = self.span.map_or((0, 0, Speed::NORMAL), |s| {
658- .span660+ (s.start, s.from.map_or(0, |(_, i)| i), s.speed)
659- .map_or((0, 0), |s| (s.start, s.from.map_or(0, |(_, i)| i)));661+ });
660- frame.index = start + frame.index.saturating_sub(base);662+ // ...and a *speeded* clip's decoder counts source frames
663+ // faster than the timeline does, so the offset comes back
664+ // through the clip's own rate. At 2x two decoded frames land
665+ // on one timeline frame and the display drops the earlier of
666+ // them; at half speed each lands two apart and is held until
667+ // it is due. Real time divides by one and is the arithmetic
668+ // this always did.
669+ frame.index = start + speed.timeline_at(frame.index.saturating_sub(base));
661 return Some(frame);670 return Some(frame);
662 }671 }
663 Err(TryRecvError::Empty) => return None,672 Err(TryRecvError::Empty) => return None,
@@ -733,15 +742,18 @@ impl PlaybackSession {
733 // the worker carries it and every frame it converts wears it.742 // the worker carries it and every frame it converts wears it.
734 Some(Span {743 Some(Span {
735 start,744 start,
736- len,
737 from: Some((source, in_frame)),745 from: Some((source, in_frame)),
746+ ..
738 }) if crate::is_image(&self.project.sources()[source].path) => {747 }) if crate::is_image(&self.project.sources()[source].path) => {
739 // A still: the same grade and the same canvas as any other748 // A still: the same grade and the same canvas as any other
740 // clip, over a picture decoded once and repeated for the span.749 // clip, over a picture decoded once and repeated for the span.
750+ // As many pictures as the span reads *source* frames, so a still
751+ // is numbered like a decoder's output and a speed reaches it
752+ // through the same rewrite (`try_frame`) as any other clip.
741 DecodeSession::open_still(753 DecodeSession::open_still(
742 &self.project.sources()[source].path,754 &self.project.sources()[source].path,
743 in_frame,755 in_frame,
744- len,756+ span.expect("matched above").source_len(),
745 self.project757 self.project
746 .composite_color_at(start)758 .composite_color_at(start)
747 .copied()759 .copied()
@@ -756,12 +768,14 @@ impl PlaybackSession {
756 }768 }
757 Some(Span {769 Some(Span {
758 start,770 start,
759- len,
760 from: Some((source, in_frame)),771 from: Some((source, in_frame)),
772+ ..
761 }) => DecodeSession::open_worker(773 }) => DecodeSession::open_worker(
762 &self.project.sources()[source].path,774 &self.project.sources()[source].path,
763 in_frame,775 in_frame,
764- in_frame + len,776+ // Source frames, which a speed makes more (or fewer) than the
777+ // timeline frames the span covers.
778+ in_frame + span.expect("matched above").source_len(),
765 self.project779 self.project
766 .composite_color_at(start)780 .composite_color_at(start)
767 .copied()781 .copied()
@@ -961,6 +975,36 @@ impl PlaybackSession {
961 true975 true
962 }976 }
963 977
978+ /// How fast the clip at `idx` of `lane` plays -- what a card shows before
979+ /// anyone drags it.
980+ pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
981+ self.project.speed_of(lane, idx)
982+ }
983+
984+ /// Sets it, for that clip and its whole group ([`Project::set_speed`]): one
985+ /// undo step for the lot. Reseeks like every other edit, so the picture runs
986+ /// -- and the sound is resampled -- from the next frame on rather than at the
987+ /// next play. The `Err` names the clip in the way when slowing one down
988+ /// would run it into its neighbour, and nothing changes.
989+ pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
990+ // Spelled out rather than through `edit`, whose closure hands back a
991+ // bool and would drop the refusal's own words.
992+ self.project.set_speed(lane, idx, speed)?;
993+ let now = self.now();
994+ self.seek(now);
995+ Ok(())
996+ }
997+
998+ /// [`set_speed`](Self::set_speed) without the undo step -- the samples inside
999+ /// one drag ([`Project::set_speed_live`]). Reseeks like the committing one,
1000+ /// which is what makes the bar move the picture under the hand.
1001+ pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
1002+ self.project.set_speed_live(lane, idx, speed)?;
1003+ let now = self.now();
1004+ self.seek(now);
1005+ Ok(())
1006+ }
1007+
964 /// Where that edge may land, `(first, last)` timeline frame inclusive: what1008 /// Where that edge may land, `(first, last)` timeline frame inclusive: what
965 /// a drag clamps the pointer to so the box it draws is the box1009 /// a drag clamps the pointer to so the box it draws is the box
966 /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.1010 /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.
@@ -1166,6 +1210,7 @@ impl PlaybackSession {
1166 eq: None,1210 eq: None,
1167 color: None,1211 color: None,
1168 fit: FitPolicy::default(),1212 fit: FitPolicy::default(),
1213+ speed: Speed::NORMAL,
1169 };1214 };
1170 // Which lane a source may land on is decided here and only here, so a1215 // Which lane a source may land on is decided here and only here, so a
1171 // front-end never has to make the same call twice: a file with no1216 // front-end never has to make the same call twice: a file with no
@@ -1478,13 +1523,20 @@ impl PlaybackSession {
1478 // changed a band restarts the workers with the new curve already in1523 // changed a band restarts the workers with the new curve already in
1479 // them, and no live channel has to reach into a running one.1524 // them, and no live channel has to reach into a running one.
1480 let eqs = self.project.audio_eqs_from(target, fps);1525 let eqs = self.project.audio_eqs_from(target, fps);
1526+ // ...and the rates, the same way again: a speeded segment is
1527+ // resampled inside its own worker, before the mix, so what the ear
1528+ // hears is what the timeline shows. Empty for a project nobody has
1529+ // speeded, which is the path that decodes the same samples it always
1530+ // did.
1531+ let speeds = self.project.audio_speeds_from(target, fps);
1481 // Each source on the stream it was placed with: what plays is what1532 // Each source on the stream it was placed with: what plays is what
1482 // the library row said, and what an export copies (`export::run`).1533 // the library row said, and what an export copies (`export::run`).
1483 let sources = self.project.audio_sources();1534 let sources = self.project.audio_sources();
1484- audio_running = match AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs) {1535+ audio_running =
1485- Ok(Some((_, rx))) => audio.spawn_feeder(rx),1536+ match AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds) {
1486- _ => false,1537+ Ok(Some((_, rx))) => audio.spawn_feeder(rx),
1487- };1538+ _ => false,
1539+ };
1488 if !audio_running {1540 if !audio_running {
1489 // Nothing will ever be fed again; let `tick` fall to wall time1541 // Nothing will ever be fed again; let `tick` fall to wall time
1490 // instead of waiting on a device that has no more work coming.1542 // instead of waiting on a device that has no more work coming.
crates/engine/src/project.rsmodified+532 -62
@@ -68,6 +68,116 @@ use crate::color::ColorParams;
68 use crate::eq::EqParams;68 use crate::eq::EqParams;
69 use crate::scale::FitPolicy;69 use crate::scale::FitPolicy;
70 70
71+/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
72+/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
73+/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
74+/// comparable nor exactly writable, and `.edith` has to read back the very
75+/// number that was set. A thousandth is finer than any card can drag and coarser
76+/// than any rounding anyone can hear.
77+///
78+/// The rate alone: a speeded clip is resampled, so its pitch moves with it (the
79+/// tape effect). Nothing here preserves pitch and nothing here plays backwards
80+/// -- [`Speed::MIN`] is a quarter speed, [`Speed::MAX`] four times.
81+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
82+pub struct Speed(u16);
83+
84+impl Speed {
85+ /// Real time -- what every clip is until something says otherwise, and the
86+ /// value every path in this engine short-circuits on.
87+ pub const NORMAL: Speed = Speed(1000);
88+ pub const MIN: Speed = Speed(250);
89+ pub const MAX: Speed = Speed(4000);
90+
91+ /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse)
92+ /// unrepresentable rather than merely refused: nothing downstream divides
93+ /// by a speed that could be nothing.
94+ pub fn from_permille(permille: u16) -> Self {
95+ Speed(permille.clamp(Self::MIN.0, Self::MAX.0))
96+ }
97+
98+ pub fn permille(self) -> u16 {
99+ self.0
100+ }
101+
102+ pub fn is_normal(self) -> bool {
103+ self == Self::NORMAL
104+ }
105+
106+ /// As a multiplier, for the sound worker and for a label.
107+ pub fn as_f64(self) -> f64 {
108+ f64::from(self.0) / 1000.
109+ }
110+
111+ /// How many *timeline* frames `source` source frames occupy at this rate --
112+ /// the clip's footprint. Rounded to the nearest frame and **never zero**: a
113+ /// clip that occupied no frames would be an empty placement, which the lane
114+ /// invariant forbids and which nothing could ever click on again.
115+ pub fn frames(self, source: u32) -> u32 {
116+ let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0);
117+ n.clamp(1, u64::from(u32::MAX)) as u32
118+ }
119+
120+ /// The mapping itself: which source frame of a clip the `offset`th timeline
121+ /// frame of it plays. Floored, so the first timeline frame is the clip's own
122+ /// in-point at every rate.
123+ pub fn source_at(self, offset: u32) -> u32 {
124+ (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32
125+ }
126+
127+ /// Its inverse, for a decoder's frames on their way back out: which timeline
128+ /// frame of the clip the `offset`th *source* frame of it lands on.
129+ pub fn timeline_at(self, offset: u32) -> u32 {
130+ (u64::from(offset) * 1000 / u64::from(self.0)).min(u64::from(u32::MAX)) as u32
131+ }
132+
133+ /// The longest source range that still *fits* in `frames` timeline frames at
134+ /// this rate, and at least one frame. What a trim commits: rounding could
135+ /// otherwise hand back a range one frame wider than the room the edge was
136+ /// clamped to, and a clip that outgrew its room would overlap its
137+ /// neighbour -- the one thing a lane may never do. At real time this is
138+ /// `frames` itself, so nothing about an unspeeded trim changes.
139+ pub fn fit(self, frames: u32) -> u32 {
140+ let mut src = self.source_at(frames).max(1);
141+ while src > 1 && self.frames(src) > frames {
142+ src -= 1;
143+ }
144+ src
145+ }
146+
147+ /// Where in the source a cut `offset` timeline frames into a clip of `len`
148+ /// source frames falls -- and `None` when this rate cannot address that
149+ /// frame at all.
150+ ///
151+ /// At half speed a clip of ten source frames is twenty timeline frames long
152+ /// and every source frame is on screen twice, so a cut between the two
153+ /// showings of one frame is not a cut in the *file*: taking it would leave
154+ /// two halves whose lengths no longer add up to the clip that was cut --
155+ /// a hole in the lane, or an overlap of the next clip. Refused instead, so
156+ /// the model stays exact and the front-end can say why. At real time every
157+ /// interior frame answers, which is the path a project without speeds is on.
158+ pub fn split_at(self, len: u32, offset: u32) -> Option<u32> {
159+ let src = self.source_at(offset);
160+ (src > 0
161+ && src < len
162+ && self.frames(src) == offset
163+ && self.frames(len - src) == self.frames(len) - offset)
164+ .then_some(src)
165+ }
166+}
167+
168+impl Default for Speed {
169+ fn default() -> Self {
170+ Self::NORMAL
171+ }
172+}
173+
174+impl std::fmt::Display for Speed {
175+ /// `2.00x` -- what a card prints and what a clip box is marked with.
176+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177+ write!(f, "{:.2}x", self.as_f64())
178+ }
179+}
180+
71 /// A half-open `[in_frame, out_frame)` range of frames of source181 /// A half-open `[in_frame, out_frame)` range of frames of source
72 /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).182 /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
73 /// Never empty.183 /// Never empty.
@@ -103,17 +213,37 @@ pub struct Clip {
103 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars213 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
104 /// where the aspect does not agree.214 /// where the aspect does not agree.
105 pub fit: FitPolicy,215 pub fit: FitPolicy,
216+ /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the
217+ /// eq and colour indexes: it is two bytes with nothing to share, and a table
218+ /// would put a level of indirection between the mapping and the one number
219+ /// every frame of it is divided by.
220+ ///
221+ /// It does **not** move `in_frame`/`out_frame`: those stay the source range
222+ /// the clip plays, so a trim and a split still address the file. What it
223+ /// changes is how many *timeline* frames that range is spread over
224+ /// ([`Clip::frames`]).
225+ pub speed: Speed,
106 }226 }
107 227
108 impl Clip {228 impl Clip {
109- /// Frame count; `>= 1` by the never-empty invariant.229+ /// Source frame count; `>= 1` by the never-empty invariant. What the clip
230+ /// reads out of its file -- not how long it is on the timeline, which is
231+ /// [`Clip::frames`] and differs the moment it is speeded.
110 pub fn len(&self) -> u32 {232 pub fn len(&self) -> u32 {
111 self.out_frame - self.in_frame233 self.out_frame - self.in_frame
112 }234 }
113 235
236+ /// Timeline frames it occupies: its source range at its own speed, never
237+ /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
238+ /// what it overlaps, how wide its box is -- is asked of this and not of
239+ /// [`Clip::len`].
240+ pub fn frames(&self) -> u32 {
241+ self.speed.frames(self.len())
242+ }
243+
114 /// One past the last timeline frame it covers.244 /// One past the last timeline frame it covers.
115 pub fn end(&self) -> u32 {245 pub fn end(&self) -> u32 {
116- self.start + self.len()246+ self.start + self.frames()
117 }247 }
118 }248 }
119 249
@@ -235,6 +365,12 @@ pub struct Span {
235 /// `(source index, first source frame)`, or `None` for a gap -- which the365 /// `(source index, first source frame)`, or `None` for a gap -- which the
236 /// engine renders as black frames and as silence.366 /// engine renders as black frames and as silence.
237 pub from: Option<(usize, u32)>,367 pub from: Option<(usize, u32)>,
368+ /// The rate the clip this came off plays at ([`Clip::speed`]);
369+ /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
370+ /// timeline frames whatever it says -- the speed is how many *source* frames
371+ /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
372+ /// come back to the timeline.
373+ pub speed: Speed,
238 }374 }
239 375
240 impl Span {376 impl Span {
@@ -242,6 +378,30 @@ impl Span {
242 pub fn end(&self) -> u32 {378 pub fn end(&self) -> u32 {
243 self.start + self.len379 self.start + self.len
244 }380 }
381+
382+ /// How many source frames it reads: what a decoder is asked for and how wide
383+ /// an audio window is. `len` at real time, and the one arithmetic both the
384+ /// picture and the sound go through, so they cannot disagree about where a
385+ /// speeded clip ends.
386+ pub fn source_len(&self) -> u32 {
387+ match self.from {
388+ Some(_) => self.speed.source_at(self.len).max(1),
389+ None => self.len,
390+ }
391+ }
392+}
393+
394+/// What one speeded audio segment asks of the worker: how many source frames to
395+/// consume per output frame, and how many seconds of timeline it has to fill.
396+/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
397+/// resampling at all.
398+#[derive(Clone, Copy, PartialEq, Debug)]
399+pub struct Stretch {
400+ /// Source frames per output frame -- the speed as a multiplier.
401+ pub step: f64,
402+ /// What the segment owes the timeline, which is what it is padded or
403+ /// trimmed to.
404+ pub timeline_secs: f64,
245 }405 }
246 406
247 /// What a save writes and a load takes back: the sources, every lane in407 /// What a save writes and a load takes back: the sources, every lane in
@@ -290,6 +450,7 @@ impl Project {
290 eq: None,450 eq: None,
291 color: None,451 color: None,
292 fit: FitPolicy::default(),452 fit: FitPolicy::default(),
453+ speed: Speed::NORMAL,
293 };454 };
294 Self {455 Self {
295 // A file is opened on its first audio stream: nothing has picked456 // A file is opened on its first audio stream: nothing has picked
@@ -358,7 +519,7 @@ impl Project {
358 )519 )
359 .into());520 .into());
360 }521 }
361- if c.start.checked_add(c.len()).is_none() {522+ if c.start.checked_add(c.frames()).is_none() {
362 return Err(format!(523 return Err(format!(
363 "{name} clip at {} runs past the last frame there is",524 "{name} clip at {} runs past the last frame there is",
364 c.start525 c.start
@@ -517,6 +678,7 @@ impl Project {
517 eq: None,678 eq: None,
518 color: None,679 color: None,
519 fit: FitPolicy::default(),680 fit: FitPolicy::default(),
681+ speed: Speed::NORMAL,
520 };682 };
521 for data in &mut self.lanes {683 for data in &mut self.lanes {
522 data.clips.push(clip);684 data.clips.push(clip);
@@ -758,6 +920,77 @@ impl Project {
758 true920 true
759 }921 }
760 922
923+ /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
924+ /// index that is not there, which is what every clip starts at anyway.
925+ pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
926+ self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
927+ }
928+
929+ /// Sets it, for the clip **and its whole group**: a link is one span on
930+ /// however many lanes ([`links_are_consistent`]), so a picture sped up away
931+ /// from its sound would be a group no save could load. One snapshot, so the
932+ /// group's change is one [`Project::undo`].
933+ ///
934+ /// The source range is untouched -- a speed says how many timeline frames
935+ /// that range is spread over ([`Clip::frames`]), which is why a trim and a
936+ /// split still address the file afterwards.
937+ ///
938+ /// Refused, changing nothing and costing no undo step, when the clip would
939+ /// grow into the one after it on its own lane: slowing a clip down makes it
940+ /// wider, and a lane may not overlap itself. The refusal *names* the clip in
941+ /// the way -- by lane and timeline frame -- because "it did not fit" is not
942+ /// something a user can go and fix. Also for an index that is not there.
943+ pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
944+ self.write_speed(lane, idx, speed, true)
945+ }
946+
947+ /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
948+ /// one pointer drag, whose first write (a plain `set_speed`) already took the
949+ /// snapshot the gesture rolls back to. A drag across the bar is one undo,
950+ /// not one per rate it passed through -- exactly as
951+ /// [`set_color_live`](Self::set_color_live) is for a slider.
952+ pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
953+ self.write_speed(lane, idx, speed, false)
954+ }
955+
956+ fn write_speed(
957+ &mut self,
958+ lane: Lane,
959+ idx: usize,
960+ speed: Speed,
961+ snapshot: bool,
962+ ) -> crate::Result<()> {
963+ let Some(members) = self.group_of(lane, idx) else {
964+ return Err(format!("there is no clip {idx} on {}", lane.label()).into());
965+ };
966+ for &(l, i) in &members {
967+ let clips = &self.lanes[l].clips;
968+ let mut moved = clips[i];
969+ moved.speed = speed;
970+ if let Some(next) = clips.get(i + 1)
971+ && moved.end() > next.start
972+ {
973+ let name = handles(&self.lanes)[l].label();
974+ return Err(format!(
975+ "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
976+ move it along, or trim this one first",
977+ moved.end(),
978+ next.start
979+ )
980+ .into());
981+ }
982+ }
983+ if snapshot {
984+ self.snapshot();
985+ }
986+ for (l, i) in members {
987+ self.lanes[l].clips[i].speed = speed;
988+ debug_assert!(sorted_disjoint(&self.lanes[l].clips));
989+ }
990+ debug_assert!(links_are_consistent(&self.lanes).is_ok());
991+ Ok(())
992+ }
993+
761 /// How the clip at `idx` of `lane` meets a project canvas of another shape.994 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
762 /// [`FitPolicy::Fit`] for an index that is not there, which is the default995 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
763 /// every clip starts at anyway.996 /// every clip starts at anyway.
@@ -796,7 +1029,12 @@ impl Project {
796 }1029 }
797 1030
798 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {1031 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
799- self.lane(lane).iter().map(|c| (c.start, c.len())).collect()1032+ // Timeline frames, not source ones: a box on a lane is as wide as the
1033+ // clip is long *there*, which a speed halves or quadruples.
1034+ self.lane(lane)
1035+ .iter()
1036+ .map(|c| (c.start, c.frames()))
1037+ .collect()
800 }1038 }
801 1039
802 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap1040 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
@@ -805,10 +1043,7 @@ impl Project {
805 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {1043 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
806 let clips = self.lane(lane);1044 let clips = self.lane(lane);
807 let idx = at(clips, timeline_frame)?;1045 let idx = at(clips, timeline_frame)?;
808- Some((1046+ Some((idx, source_frame(&clips[idx], timeline_frame)))
809- idx,
810- clips[idx].in_frame + (timeline_frame - clips[idx].start),
811- ))
812 }1047 }
813 1048
814 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.1049 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
@@ -831,13 +1066,12 @@ impl Project {
831 Some(idx) => Span {1066 Some(idx) => Span {
832 start: timeline_frame,1067 start: timeline_frame,
833 len: clips[idx].end() - timeline_frame,1068 len: clips[idx].end() - timeline_frame,
834- from: Some((1069+ from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
835- clips[idx].source,1070+ speed: clips[idx].speed,
836- clips[idx].in_frame + (timeline_frame - clips[idx].start),
837- )),
838 },1071 },
839 None => Span {1072 None => Span {
840 start: timeline_frame,1073 start: timeline_frame,
1074+ speed: Speed::NORMAL,
841 // The next placement, or the end of the timeline: a gap is1075 // The next placement, or the end of the timeline: a gap is
842 // bounded by what comes after it, never by its own bookkeeping.1076 // bounded by what comes after it, never by its own bookkeeping.
843 len: clips1077 len: clips
@@ -892,20 +1126,18 @@ impl Project {
892 let winner = video1126 let winner = video
893 .iter()1127 .iter()
894 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());1128 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
895- let (from, until) = match winner {1129+ let (from, speed, until) = match winner {
896 Some(i) => {1130 Some(i) => {
897 let clips = self.lane(video[i]);1131 let clips = self.lane(video[i]);
898 let idx = at(clips, timeline_frame).expect("just found above");1132 let idx = at(clips, timeline_frame).expect("just found above");
899 (1133 (
900- Some((1134+ Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
901- clips[idx].source,1135+ clips[idx].speed,
902- clips[idx].in_frame + (timeline_frame - clips[idx].start),
903- )),
904 clips[idx].end(),1136 clips[idx].end(),
905 )1137 )
906 }1138 }
907 // Nothing covers it: black until something above the floor starts.1139 // Nothing covers it: black until something above the floor starts.
908- None => (None, total),1140+ None => (None, Speed::NORMAL, total),
909 };1141 };
910 let takeover = video[winner.map_or(0, |i| i + 1)..]1142 let takeover = video[winner.map_or(0, |i| i + 1)..]
911 .iter()1143 .iter()
@@ -916,6 +1148,7 @@ impl Project {
916 start: timeline_frame,1148 start: timeline_frame,
917 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,1149 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
918 from,1150 from,
1151+ speed,
919 })1152 })
920 }1153 }
921 1154
@@ -1012,7 +1245,11 @@ impl Project {
1012 continue;1245 continue;
1013 };1246 };
1014 let mut tail = data.clips[idx];1247 let mut tail = data.clips[idx];
1015- tail.in_frame += timeline_frame - tail.start;1248+ // Where the cut lands *in the file*, which is the clip's own rate
1249+ // away from where it lands on the timeline. Both halves keep the
1250+ // speed, and `splittable` has already refused any frame at which
1251+ // the two would not add up to the one being cut.
1252+ tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");
1016 tail.start = timeline_frame;1253 tail.start = timeline_frame;
1017 tail.link = right;1254 tail.link = right;
1018 data.clips[idx].out_frame = tail.in_frame;1255 data.clips[idx].out_frame = tail.in_frame;
@@ -1295,12 +1532,19 @@ impl Project {
1295 let c = &mut self.lanes[l].clips[i];1532 let c = &mut self.lanes[l].clips[i];
1296 match edge {1533 match edge {
1297 Edge::Start => {1534 Edge::Start => {
1535+ // The frames that stay play what they played, so the room
1536+ // that survives is measured from the *end*: at a speed the
1537+ // source range that fits in it is `Speed::fit`'s answer, and
1538+ // at real time it is the offset itself, unchanged.
1539+ let keep = c.speed.fit(c.end() - to).min(c.out_frame);
1298 // Non-negative by `lo`, which is what keeps the in-point on1540 // Non-negative by `lo`, which is what keeps the in-point on
1299 // the source.1541 // the source.
1300- c.in_frame = (i64::from(c.in_frame) + i64::from(to) - i64::from(c.start)) as u32;1542+ c.in_frame = c.out_frame - keep;
1301 c.start = to;1543 c.start = to;
1302 }1544 }
1303- Edge::End => c.out_frame = c.in_frame + (to - c.start),1545+ // Never wider than the room the edge was clamped to: see
1546+ // [`Speed::fit`].
1547+ Edge::End => c.out_frame = c.in_frame + c.speed.fit(to - c.start),
1304 }1548 }
1305 debug_assert!(sorted_disjoint(&self.lanes[l].clips));1549 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
1306 }1550 }
@@ -1325,27 +1569,32 @@ impl Project {
1325 let c = clips[i];1569 let c = clips[i];
1326 let (member_lo, member_hi) = match edge {1570 let (member_lo, member_hi) = match edge {
1327 Edge::Start => (1571 Edge::Start => (
1328- // Back to the source's own first frame, and never over the1572+ // Back to the source's own first frame -- as many *timeline*
1329- // clip in front of it. Saturating because a clip may hold1573+ // frames as that head is worth at the clip's rate, which at
1330- // *more* head than the timeline has room for -- a ripple1574+ // real time is the head itself -- and never over the clip in
1331- // delete slides a clip back to frame 0 with its in-point1575+ // front of it. Saturating because a clip may hold *more*
1332- // wherever the cut left it -- and frame 0 is the other wall.1576+ // head than the timeline has room for -- a ripple delete
1577+ // slides a clip back to frame 0 with its in-point wherever
1578+ // the cut left it -- and frame 0 is the other wall.
1333 c.start1579 c.start
1334- .saturating_sub(c.in_frame)1580+ .saturating_sub(c.speed.timeline_at(c.in_frame))
1335 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),1581 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
1336 c.end() - 1,1582 c.end() - 1,
1337 ),1583 ),
1338 Edge::End => (1584 Edge::End => (
1339 c.start + 1,1585 c.start + 1,
1340- // Out to whatever is left of the source, and never over the1586+ // Out to whatever is left of the source -- again in timeline
1341- // clip behind it.1587+ // frames, at this clip's rate -- and never over the clip
1588+ // behind it.
1342 c.start1589 c.start
1343 .saturating_add(1590 .saturating_add(
1344- source_frames1591+ c.speed.timeline_at(
1345- .get(c.source)1592+ source_frames
1346- .copied()1593+ .get(c.source)
1347- .unwrap_or(c.out_frame)1594+ .copied()
1348- .saturating_sub(c.in_frame),1595+ .unwrap_or(c.out_frame)
1596+ .saturating_sub(c.in_frame),
1597+ ),
1349 )1598 )
1350 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),1599 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
1351 ),1600 ),
@@ -1415,7 +1664,9 @@ impl Project {
1415 // that clip -- and a save the engine's own `open_project` then refuses.1664 // that clip -- and a save the engine's own `open_project` then refuses.
1416 let picture_only = crate::is_image(&source.path);1665 let picture_only = crate::is_image(&source.path);
1417 let at = timeline_frame.min(self.timeline_frames());1666 let at = timeline_frame.min(self.timeline_frames());
1418- let len = clip.len();1667+ // The room it takes on the timeline, which its speed decides -- not the
1668+ // source range it reads.
1669+ let len = clip.frames();
1419 // Room for it: `open_room` adds `len` to every start from `at` on, and a1670 // Room for it: `open_room` adds `len` to every start from `at` on, and a
1420 // hand-written file may hold a clip that ends at the very last frame1671 // hand-written file may hold a clip that ends at the very last frame
1421 // (`edith::check` permits `start + len == u32::MAX`). Refused here1672 // (`edith::check` permits `start + len == u32::MAX`). Refused here
@@ -1430,6 +1681,19 @@ impl Project {
1430 {1681 {
1431 return false;1682 return false;
1432 }1683 }
1684+ // ...and room *to open*: the paste splits whatever it lands inside of,
1685+ // and a speeded clip can only be cut where its own rate has a source
1686+ // frame ([`Speed::split_at`]). Refused rather than pasted over the top
1687+ // of one, which is the overlap a lane may never hold. At real time every
1688+ // frame answers, so this cannot refuse an unspeeded paste.
1689+ let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
1690+ if self
1691+ .lanes
1692+ .iter()
1693+ .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
1694+ {
1695+ return false;
1696+ }
1433 self.snapshot();1697 self.snapshot();
1434 let clip = Clip {1698 let clip = Clip {
1435 start: at,1699 start: at,
@@ -1450,7 +1714,7 @@ impl Project {
1450 .filter_map(|&kind| self.index(Lane::new(kind, 0)))1714 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
1451 .collect();1715 .collect();
1452 for (i, data) in self.lanes.iter_mut().enumerate() {1716 for (i, data) in self.lanes.iter_mut().enumerate() {
1453- open_room(&mut data.clips, at, clip.len());1717+ open_room(&mut data.clips, at, len);
1454 if takes.contains(&i) {1718 if takes.contains(&i) {
1455 let idx = data.clips.partition_point(|c| c.start < at);1719 let idx = data.clips.partition_point(|c| c.start < at);
1456 data.clips.insert(idx, clip);1720 data.clips.insert(idx, clip);
@@ -1515,7 +1779,7 @@ impl Project {
1515 let Some(clip) = self.lane(lane).get(idx).copied() else {1779 let Some(clip) = self.lane(lane).get(idx).copied() else {
1516 return false;1780 return false;
1517 };1781 };
1518- self.ripple_delete(clip.start, clip.len())1782+ self.ripple_delete(clip.start, clip.frames())
1519 }1783 }
1520 1784
1521 /// Restore every lane from before the last successful edit -- the clips and1785 /// Restore every lane from before the last successful edit -- the clips and
@@ -1555,11 +1819,13 @@ impl Project {
1555 .iter()1819 .iter()
1556 .map(|span| match span.from {1820 .map(|span| match span.from {
1557 // A clip's window is in *source* seconds: where in the file it1821 // A clip's window is in *source* seconds: where in the file it
1558- // reads from, which a delete before it never shifts.1822+ // reads from, which a delete before it never shifts. How many
1823+ // source frames that is, is the span's own arithmetic -- at a
1824+ // speed it is not the timeline length ([`Span::source_len`]).
1559 Some((source, in_frame)) => (1825 Some((source, in_frame)) => (
1560 Some(source),1826 Some(source),
1561 f64::from(in_frame) / fps,1827 f64::from(in_frame) / fps,
1562- f64::from(in_frame + span.len) / fps,1828+ f64::from(in_frame + span.source_len()) / fps,
1563 ),1829 ),
1564 // A gap has no file, so all it can say is how long it is.1830 // A gap has no file, so all it can say is how long it is.
1565 None => (None, 0.0, f64::from(span.len) / fps),1831 None => (None, 0.0, f64::from(span.len) / fps),
@@ -1607,6 +1873,52 @@ impl Project {
1607 }1873 }
1608 }1874 }
1609 1875
1876+ /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
1877+ /// segments plays at, and how long the timeline gives it: the same lanes in
1878+ /// the same order, one entry per segment, `None` for a segment at real time
1879+ /// -- which is every segment of a project nobody has speeded, and the path
1880+ /// the audio worker leaves bit-identical.
1881+ ///
1882+ /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
1883+ /// the segment tuple is what every opener and a dozen tests speak, and a
1884+ /// rate is not part of *which samples* a segment names.
1885+ ///
1886+ /// The seconds are what makes a resample exact: a segment's own window
1887+ /// resolves to whole source frames, and dividing that by the rate would
1888+ /// leave each clip a fraction of a frame short or long -- a drift that grows
1889+ /// clip by clip. Told how much timeline it owes, the worker pads or trims
1890+ /// the last few samples of each segment instead, so the sound stays locked
1891+ /// to the picture however many speeded cuts it walks through.
1892+ pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
1893+ self.audio_lanes()
1894+ .into_iter()
1895+ .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
1896+ .collect()
1897+ }
1898+
1899+ /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
1900+ /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
1901+ /// same walk, same `fps` refusal.
1902+ pub fn lane_speeds_from(
1903+ &self,
1904+ lane: Lane,
1905+ timeline_frame: u32,
1906+ fps: f64,
1907+ ) -> Vec<Option<Stretch>> {
1908+ if !(fps.is_finite() && fps > 0.0) {
1909+ return Vec::new();
1910+ }
1911+ self.spans_from(lane, timeline_frame)
1912+ .iter()
1913+ .map(|span| {
1914+ (!span.speed.is_normal()).then(|| Stretch {
1915+ step: span.speed.as_f64(),
1916+ timeline_secs: f64::from(span.len) / fps,
1917+ })
1918+ })
1919+ .collect()
1920+ }
1921+
1610 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s1922 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
1611 /// segments plays through: the same lanes in the same order, one entry per1923 /// segments plays through: the same lanes in the same order, one entry per
1612 /// segment, `None` where the segment is a gap or its clip plays flat.1924 /// segment, `None` where the segment is a gap or its clip plays flat.
@@ -1705,6 +2017,16 @@ fn handles(lanes: &[LaneData]) -> Vec<Lane> {
1705 .collect()2017 .collect()
1706 }2018 }
1707 2019
2020+/// Which source frame a clip plays at `timeline_frame`: its in-point plus the
2021+/// offset *at the clip's own rate*. The one place the two frame spaces meet, so
2022+/// a speed cannot be applied twice or forgotten in one of them.
2023+fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
2024+ // Clamped inside the clip's own range: rounding at a slow rate can put the
2025+ // last timeline frame of a clip a frame past its out-point, and a source
2026+ // frame outside the range is one the next clip owns.
2027+ (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1)
2028+}
2029+
1708 /// Index of the clip covering `frame`, or `None` for a gap or past the end.2030 /// Index of the clip covering `frame`, or `None` for a gap or past the end.
1709 /// Binary search: the sorted-disjoint invariant is what makes it legal.2031 /// Binary search: the sorted-disjoint invariant is what makes it legal.
1710 fn at(clips: &[Clip], frame: u32) -> Option<usize> {2032 fn at(clips: &[Clip], frame: u32) -> Option<usize> {
@@ -1716,7 +2038,20 @@ fn at(clips: &[Clip], frame: u32) -> Option<usize> {
1716 /// there would cut in two. A placement's own first frame is not inside it.2038 /// there would cut in two. A placement's own first frame is not inside it.
1717 fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {2039 fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
1718 let idx = at(clips, frame)?;2040 let idx = at(clips, frame)?;
1719- (frame > clips[idx].start).then_some(idx)2041+ // ...and, on a speeded clip, one its rate can actually address
2042+ // ([`Speed::split_at`]): a cut between two showings of one source frame
2043+ // would leave halves that no longer add up to the clip that was cut.
2044+ (frame > clips[idx].start)
2045+ .then_some(idx)
2046+ .filter(|&idx| split_source(&clips[idx], frame).is_some())
2047+}
2048+
2049+/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
2050+/// rate cannot address that frame.
2051+fn split_source(c: &Clip, frame: u32) -> Option<u32> {
2052+ c.speed
2053+ .split_at(c.len(), frame - c.start)
2054+ .map(|src| c.in_frame + src)
1720 }2055 }
1721 2056
1722 /// Index of the first of the two clips a [`Project::regroup`] at `frame` would2057 /// Index of the first of the two clips a [`Project::regroup`] at `frame` would
@@ -1724,10 +2059,16 @@ fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
1724 fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {2059 fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
1725 let idx = clips.iter().position(|c| c.end() == frame)?;2060 let idx = clips.iter().position(|c| c.end() == frame)?;
1726 let next = clips.get(idx + 1)?;2061 let next = clips.get(idx + 1)?;
2062+ let joined = clips[idx].len() + next.len();
1727 (next.start == frame2063 (next.start == frame
1728 && next.source == clips[idx].source2064 && next.source == clips[idx].source
1729- && next.in_frame == clips[idx].out_frame)2065+ && next.in_frame == clips[idx].out_frame
1730- .then_some(idx)2066+ // ...at one rate, and one that puts the rejoined clip back in exactly
2067+ // the room the two took up: what a split could have produced, which is
2068+ // all this undoes.
2069+ && next.speed == clips[idx].speed
2070+ && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
2071+ .then_some(idx)
1731 }2072 }
1732 2073
1733 /// The lane invariant: sorted by `start`, no two placements overlapping, no2074 /// The lane invariant: sorted by `start`, no two placements overlapping, no
@@ -1824,19 +2165,24 @@ fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
1824 out.push(c);2165 out.push(c);
1825 continue;2166 continue;
1826 }2167 }
1827- // The head that survives in front of the hole.2168+ // The head that survives in front of the hole -- as much source as fits
2169+ // in the room in front of it at this clip's own rate ([`Speed::fit`]),
2170+ // which at real time is that room itself. Never *more*: a head that
2171+ // outgrew its room would reach into the hole it is being cut out of.
1828 if c.start < start {2172 if c.start < start {
1829 out.push(Clip {2173 out.push(Clip {
1830- out_frame: c.in_frame + (start - c.start),2174+ out_frame: c.in_frame + c.speed.fit(start - c.start).min(c.len()),
1831 link: None,2175 link: None,
1832 ..c2176 ..c
1833 });2177 });
1834 }2178 }
1835- // ...and the tail behind it, which keeps reading where it would have.2179+ // ...and the tail behind it, which keeps reading up to where it would
2180+ // have: measured from its out-point for the head's reason, so what it
2181+ // occupies still ends where the whole clip did.
1836 if c.end() > end {2182 if c.end() > end {
1837 out.push(Clip {2183 out.push(Clip {
1838 start: end,2184 start: end,
1839- in_frame: c.in_frame + (end - c.start),2185+ in_frame: c.out_frame - c.speed.fit(c.end() - end).min(c.len()),
1840 link: None,2186 link: None,
1841 ..c2187 ..c
1842 });2188 });
@@ -1852,7 +2198,11 @@ fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
1852 fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {2198 fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
1853 if let Some(idx) = splittable(clips, at) {2199 if let Some(idx) = splittable(clips, at) {
1854 let mut tail = clips[idx];2200 let mut tail = clips[idx];
1855- tail.in_frame += at - tail.start;2201+ // The cut in *source* frames, at the clip's own rate. `splittable` has
2202+ // already refused a frame the rate cannot address, which is why
2203+ // [`Project::paste`] refuses one too rather than opening room inside a
2204+ // clip that cannot be cut there.
2205+ tail.in_frame = split_source(&tail, at).expect("splittable said so");
1856 tail.start = at;2206 tail.start = at;
1857 tail.link = None;2207 tail.link = None;
1858 clips[idx].out_frame = tail.in_frame;2208 clips[idx].out_frame = tail.in_frame;
@@ -1892,6 +2242,7 @@ mod tests {
1892 eq: None,2242 eq: None,
1893 color: None,2243 color: None,
1894 fit: FitPolicy::default(),2244 fit: FitPolicy::default(),
2245+ speed: Speed::NORMAL,
1895 }2246 }
1896 }2247 }
1897 2248
@@ -2177,7 +2528,8 @@ mod tests {
2177 Some(Span {2528 Some(Span {
2178 start: 6,2529 start: 6,
2179 len: 3,2530 len: 3,
2180- from: Some((0, 6))2531+ from: Some((0, 6)),
2532+ speed: Speed::NORMAL
2181 })2533 })
2182 );2534 );
2183 assert_eq!(p.span_at(Lane::V1, 9), None);2535 assert_eq!(p.span_at(Lane::V1, 9), None);
@@ -2211,6 +2563,7 @@ mod tests {
2211 eq: None,2563 eq: None,
2212 color: None,2564 color: None,
2213 fit: FitPolicy::Fit,2565 fit: FitPolicy::Fit,
2566+ speed: Speed::NORMAL,
2214 };2567 };
2215 2568
2216 #[test]2569 #[test]
@@ -2398,7 +2751,8 @@ mod tests {
2398 Some(Span {2751 Some(Span {
2399 start: 3,2752 start: 3,
2400 len: 2,2753 len: 2,
2401- from: None2754+ from: None,
2755+ speed: Speed::NORMAL
2402 })2756 })
2403 );2757 );
2404 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");2758 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
@@ -2416,7 +2770,8 @@ mod tests {
2416 Some(Span {2770 Some(Span {
2417 start: 5,2771 start: 5,
2418 len: 4,2772 len: 4,
2419- from: None2773+ from: None,
2774+ speed: Speed::NORMAL
2420 }),2775 }),
2421 "the audio lane holds silence to the end of the picture"2776 "the audio lane holds silence to the end of the picture"
2422 );2777 );
@@ -2507,7 +2862,8 @@ mod tests {
2507 Some(Span {2862 Some(Span {
2508 start: 9,2863 start: 9,
2509 len: 11,2864 len: 11,
2510- from: None2865+ from: None,
2866+ speed: Speed::NORMAL
2511 })2867 })
2512 );2868 );
2513 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");2869 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
@@ -3398,6 +3754,7 @@ mod tests {
3398 vec![Clip {3754 vec![Clip {
3399 color: Some(i),3755 color: Some(i),
3400 fit: FitPolicy::default(),3756 fit: FitPolicy::default(),
3757+ speed: Speed::NORMAL,
3401 ..video[0]3758 ..video[0]
3402 }]3759 }]
3403 };3760 };
@@ -3459,6 +3816,7 @@ mod tests {
3459 eq: None,3816 eq: None,
3460 color: None,3817 color: None,
3461 fit: FitPolicy::default(),3818 fit: FitPolicy::default(),
3819+ speed: Speed::NORMAL,
3462 };3820 };
3463 3821
3464 // The door: named errors, one per cause.3822 // The door: named errors, one per cause.
@@ -3559,6 +3917,94 @@ mod tests {
3559 );3917 );
3560 }3918 }
3561 3919
3920+ /// The mapping a speed changes, and the one it does not: a 2x clip reads two
3921+ /// source frames per timeline frame and still starts at its own in-point,
3922+ /// and a half-speed one shows every source frame twice.
3923+ #[test]
3924+ fn a_rate_maps_timeline_frames_onto_source_frames() {
3925+ let mut p = Project::single(FILE, 40);
3926+ p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
3927+ .expect("room enough");
3928+ assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
3929+ assert_eq!(
3930+ p.map(Lane::V1, 0),
3931+ Some((0, 0)),
3932+ "and it starts where it did"
3933+ );
3934+ assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
3935+ assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
3936+ assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
3937+ // The span a decoder is handed: as many source frames as it will read.
3938+ let span = p.span_at(Lane::V1, 0).expect("a span");
3939+ assert_eq!((span.len, span.source_len()), (20, 40));
3940+ // ...and the same clip the other way round.
3941+ let mut p = Project::single(FILE, 40);
3942+ p.set_speed(Lane::V1, 0, Speed::from_permille(500))
3943+ .expect("room enough");
3944+ assert_eq!(p.timeline_frames(), 80);
3945+ assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
3946+ assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
3947+ assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
3948+ assert_eq!(
3949+ p.map(Lane::V1, 79),
3950+ Some((0, 39)),
3951+ "and the last timeline frame is still inside the source range"
3952+ );
3953+ }
3954+
3955+ /// A trim of a speeded clip is still a trim of its *source*, and the edge
3956+ /// still stops at the wall: the room a rate leaves is measured in timeline
3957+ /// frames and the range it commits in source ones.
3958+ #[test]
3959+ fn trimming_a_speeded_clip_stays_inside_its_room() {
3960+ let mut p = Project::single(FILE, 40);
3961+ p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
3962+ .expect("room enough");
3963+ // A second clip butted against the first, so the wall is a real one.
3964+ assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
3965+ let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
3966+ assert_eq!(room, (1, 20), "out to the neighbour and no further");
3967+ assert!(
3968+ !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
3969+ "clamped to the wall, which is where the edge already is"
3970+ );
3971+ let c = p.clips()[0];
3972+ assert_eq!(c.end(), 20, "so nothing moved");
3973+ assert_eq!(c.out_frame, 40, "and it is still the whole source range");
3974+ // ...and in: half the timeline frames is half the source range.
3975+ assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
3976+ let c = p.clips()[0];
3977+ assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
3978+ assert_eq!(c.end(), 10, "and ten timeline frames of them");
3979+ assert!(sorted_disjoint(p.clips()));
3980+ }
3981+
3982+ /// The frames a rate cannot address: at half speed each source frame is on
3983+ /// screen twice, and the cut between the two showings is not a cut in the
3984+ /// file. Refused, so the two halves always add up to the clip that was cut.
3985+ #[test]
3986+ fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
3987+ let mut p = Project::single(FILE, 10);
3988+ p.set_speed(Lane::V1, 0, Speed::from_permille(500))
3989+ .expect("room enough");
3990+ assert_eq!(p.timeline_frames(), 20);
3991+ assert!(
3992+ !p.split(3),
3993+ "an odd frame is between two showings of one frame"
3994+ );
3995+ assert_eq!(p.clips().len(), 1, "and nothing was cut");
3996+ assert!(p.split(4), "an even one is a frame boundary");
3997+ let halves = p.clips().to_vec();
3998+ assert_eq!(
3999+ (halves[0].end(), halves[1].start, halves[1].end()),
4000+ (4, 4, 20),
4001+ "the halves meet, and still end where the clip did"
4002+ );
4003+ assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
4004+ assert!(p.regroup(4), "and the inverse puts it back");
4005+ assert_eq!(p.clips().len(), 1);
4006+ }
4007+
3562 /// The same claim, swept: random op sequences off the public surface, the4008 /// The same claim, swept: random op sequences off the public surface, the
3563 /// project reloaded after every one of them. A failure prints its seed, and4009 /// project reloaded after every one of them. A failure prints its seed, and
3564 /// the seed replays the whole sequence.4010 /// the seed replays the whole sequence.
@@ -3584,7 +4030,7 @@ mod tests {
3584 .unwrap_or(&clip(0, 0, 5, 0));4030 .unwrap_or(&clip(0, 0, 5, 0));
3585 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };4031 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
3586 let idx = next(4) as usize;4032 let idx = next(4) as usize;
3587- let _ = match next(13) {4033+ let _ = match next(14) {
3588 0 => p.split(frame),4034 0 => p.split(frame),
3589 1 => p.regroup(frame),4035 1 => p.regroup(frame),
3590 2 => p.lift(lane, idx),4036 2 => p.lift(lane, idx),
@@ -3602,6 +4048,13 @@ mod tests {
3602 // reason: it rides on the clip and its orphans must go.4048 // reason: it rides on the clip and its orphans must go.
3603 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),4049 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
3604 11 => p.set_color(lane, idx, None),4050 11 => p.set_color(lane, idx, None),
4051+ // ...and a rate in with them, which is the one of the three
4052+ // that moves *placements*: a clip that grew has to be
4053+ // refused rather than overlap, and one that shrank leaves a
4054+ // lane that still loads. Both are what `reloads` asks.
4055+ 12 => p
4056+ .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
4057+ .is_ok(),
3605 _ => p.append_clip(0, 1 + next(9)),4058 _ => p.append_clip(0, 1 + next(9)),
3606 };4059 };
3607 reloads(&p, &format!("seed {seed}, step {step}"));4060 reloads(&p, &format!("seed {seed}, step {step}"));
@@ -3711,7 +4164,8 @@ mod tests {
3711 Some(Span {4164 Some(Span {
3712 start: 0,4165 start: 0,
3713 len: 4,4166 len: 4,
3714- from: None4167+ from: None,
4168+ speed: Speed::NORMAL
3715 })4169 })
3716 );4170 );
3717 // Every lane still covers the whole timeline, gaps included.4171 // Every lane still covers the whole timeline, gaps included.
@@ -3807,6 +4261,7 @@ mod tests {
3807 eq: None,4261 eq: None,
3808 color: None,4262 color: None,
3809 fit: FitPolicy::default(),4263 fit: FitPolicy::default(),
4264+ speed: Speed::NORMAL,
3810 };4265 };
3811 let lanes = vec![4266 let lanes = vec![
3812 LaneData {4267 LaneData {
@@ -3841,6 +4296,7 @@ mod tests {
3841 eq: None,4296 eq: None,
3842 color: None,4297 color: None,
3843 fit: FitPolicy::default(),4298 fit: FitPolicy::default(),
4299+ speed: Speed::NORMAL,
3844 };4300 };
3845 // V1, A1, V2, A2 -- one take over [0, 4) on all four.4301 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
3846 let kinds = [4302 let kinds = [
@@ -3944,9 +4400,15 @@ mod tests {
3944 .unwrap_or(&clip(0, 0, 5, 0));4400 .unwrap_or(&clip(0, 0, 5, 0));
3945 let lane = lanes[next(3) as usize];4401 let lane = lanes[next(3) as usize];
3946 let idx = next(4) as usize;4402 let idx = next(4) as usize;
3947- let _ = match next(12) {4403+ let _ = match next(13) {
3948 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),4404 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
3949 11 => p.set_eq(lane, idx, None),4405 11 => p.set_eq(lane, idx, None),
4406+ // A rate, which on many lanes is the group rule as well:
4407+ // every clip carrying the link moves together or none of
4408+ // them does, and `invariants_hold` is what says so.
4409+ 12 => p
4410+ .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
4411+ .is_ok(),
3950 0 => p.split(frame),4412 0 => p.split(frame),
3951 1 => p.regroup(frame),4413 1 => p.regroup(frame),
3952 2 => p.lift(lane, idx),4414 2 => p.lift(lane, idx),
@@ -3991,17 +4453,20 @@ mod tests {
3991 Span {4453 Span {
3992 start: 0,4454 start: 0,
3993 len: 10,4455 len: 10,
3994- from: Some((0, 0))4456+ from: Some((0, 0)),
4457+ speed: Speed::NORMAL
3995 },4458 },
3996 Span {4459 Span {
3997 start: 10,4460 start: 10,
3998 len: 10,4461 len: 10,
3999- from: Some((1, 5))4462+ from: Some((1, 5)),
4463+ speed: Speed::NORMAL
4000 },4464 },
4001 Span {4465 Span {
4002 start: 20,4466 start: 20,
4003 len: 10,4467 len: 10,
4004- from: Some((0, 20))4468+ from: Some((0, 20)),
4469+ speed: Speed::NORMAL
4005 },4470 },
4006 ],4471 ],
4007 "V2 takes over for its own span and hands V1 back"4472 "V2 takes over for its own span and hands V1 back"
@@ -4012,7 +4477,8 @@ mod tests {
4012 Some(Span {4477 Some(Span {
4013 start: 15,4478 start: 15,
4014 len: 5,4479 len: 5,
4015- from: Some((1, 10))4480+ from: Some((1, 10)),
4481+ speed: Speed::NORMAL
4016 })4482 })
4017 );4483 );
4018 assert_eq!(p.composite_span_at(30), None, "past the end");4484 assert_eq!(p.composite_span_at(30), None, "past the end");
@@ -4032,22 +4498,26 @@ mod tests {
4032 Span {4498 Span {
4033 start: 0,4499 start: 0,
4034 len: 5,4500 len: 5,
4035- from: Some((0, 0))4501+ from: Some((0, 0)),
4502+ speed: Speed::NORMAL
4036 },4503 },
4037 Span {4504 Span {
4038 start: 5,4505 start: 5,
4039 len: 5,4506 len: 5,
4040- from: None4507+ from: None,
4508+ speed: Speed::NORMAL
4041 },4509 },
4042 Span {4510 Span {
4043 start: 10,4511 start: 10,
4044 len: 10,4512 len: 10,
4045- from: Some((1, 0))4513+ from: Some((1, 0)),
4514+ speed: Speed::NORMAL
4046 },4515 },
4047 Span {4516 Span {
4048 start: 20,4517 start: 20,
4049 len: 10,4518 len: 10,
4050- from: None4519+ from: None,
4520+ speed: Speed::NORMAL
4051 },4521 },
4052 ]4522 ]
4053 );4523 );
crates/engine/tests/audio_export.rsmodified+4 -2
@@ -15,8 +15,7 @@ use std::path::{Path, PathBuf};
15 use std::time::{Duration, Instant};15 use std::time::{Duration, Instant};
16 16
17 use engine::export::{ExportSettings, Format};17 use engine::export::{ExportSettings, Format};
18-use engine::project::LaneKind;18+use engine::project::{LaneKind, Source, Speed};
19-use engine::project::Source;
20 use engine::scale::FitPolicy;19 use engine::scale::FitPolicy;
21 use engine::{AudioSession, Clip, ExportHandle, Project};20 use engine::{AudioSession, Clip, ExportHandle, Project};
22 21
@@ -68,6 +67,7 @@ fn mixed_project() -> Project {
68 eq: None,67 eq: None,
69 color: None,68 color: None,
70 fit: FitPolicy::default(),69 fit: FitPolicy::default(),
70+ speed: Speed::NORMAL,
71 };71 };
72 Project::from_parts(72 Project::from_parts(
73 vec![73 vec![
@@ -89,6 +89,7 @@ fn mixed_project() -> Project {
89 eq: None,89 eq: None,
90 color: None,90 color: None,
91 fit: FitPolicy::default(),91 fit: FitPolicy::default(),
92+ speed: Speed::NORMAL,
92 }],93 }],
93 ),94 ),
94 (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]),95 (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]),
@@ -325,6 +326,7 @@ fn a_51_ac3_source_round_trips_through_a_wav() {
325 eq: None,326 eq: None,
326 color: None,327 color: None,
327 fit: FitPolicy::default(),328 fit: FitPolicy::default(),
329+ speed: Speed::NORMAL,
328 }],330 }],
329 )],331 )],
330 Vec::new(),332 Vec::new(),
crates/engine/tests/eq_audio.rsmodified+2 -1
@@ -23,7 +23,7 @@ use std::time::{Duration, Instant};
23 23
24 use engine::eq::{Band, BandKind, EqParams};24 use engine::eq::{Band, BandKind, EqParams};
25 use engine::export::{ExportSettings, Format};25 use engine::export::{ExportSettings, Format};
26-use engine::project::{Lane, LaneKind, Source};26+use engine::project::{Lane, LaneKind, Source, Speed};
27 use engine::scale::FitPolicy;27 use engine::scale::FitPolicy;
28 use engine::{AudioSession, Clip, ExportHandle, Project};28 use engine::{AudioSession, Clip, ExportHandle, Project};
29 29
@@ -61,6 +61,7 @@ fn clip(start: u32, source: usize, frames: u32) -> Clip {
61 eq: None,61 eq: None,
62 color: None,62 color: None,
63 fit: FitPolicy::default(),63 fit: FitPolicy::default(),
64+ speed: Speed::NORMAL,
64 }65 }
65 }66 }
66 67
crates/engine/tests/export.rsmodified+3 -2
@@ -22,8 +22,7 @@ use std::time::{Duration, Instant};
22 use engine::export::ExportSettings;22 use engine::export::ExportSettings;
23 use engine::hw::HwEncoder;23 use engine::hw::HwEncoder;
24 use engine::mux::{Mp4Muxer, VideoParams, parameter_sets};24 use engine::mux::{Mp4Muxer, VideoParams, parameter_sets};
25-use engine::project::Lane;25+use engine::project::{Lane, Source, Speed};
26-use engine::project::Source;
27 use engine::scale::FitPolicy;26 use engine::scale::FitPolicy;
28 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};27 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
29 28
@@ -195,6 +194,7 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() {
195 eq: None,194 eq: None,
196 color: None,195 color: None,
197 fit: FitPolicy::default(),196 fit: FitPolicy::default(),
197+ speed: Speed::NORMAL,
198 };198 };
199 let clips = vec![clip(0, 0), clip(1, 10)];199 let clips = vec![clip(0, 0), clip(1, 10)];
200 let project = Project::from_parts(200 let project = Project::from_parts(
@@ -275,6 +275,7 @@ fn exports_the_audio_stream_the_timeline_plays() {
275 eq: None,275 eq: None,
276 color: None,276 color: None,
277 fit: FitPolicy::default(),277 fit: FitPolicy::default(),
278+ speed: Speed::NORMAL,
278 };279 };
279 // Stream 1 is the 22.05 kHz mono French track; stream 0 is 44.1 kHz280 // Stream 1 is the 22.05 kHz mono French track; stream 0 is 44.1 kHz
280 // stereo. A project may only hold streams that agree, so this timeline is281 // stereo. A project may only hold streams that agree, so this timeline is
crates/engine/tests/lanes.rsmodified+3 -1
@@ -14,7 +14,7 @@ use std::sync::Once;
14 use std::time::{Duration, Instant};14 use std::time::{Duration, Instant};
15 15
16 use engine::export::{ExportSettings, Format};16 use engine::export::{ExportSettings, Format};
17-use engine::project::{Clip, LaneKind, Source};17+use engine::project::{Clip, LaneKind, Source, Speed};
18 use engine::scale::FitPolicy;18 use engine::scale::FitPolicy;
19 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};19 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
20 20
@@ -239,6 +239,7 @@ fn the_mp4_copy_follows_the_lane_that_holds_the_sound() {
239 eq: None,239 eq: None,
240 color: None,240 color: None,
241 fit: FitPolicy::default(),241 fit: FitPolicy::default(),
242+ speed: Speed::NORMAL,
242 };243 };
243 let project = Project::from_parts(244 let project = Project::from_parts(
244 vec![Source::new(&source, 0)],245 vec![Source::new(&source, 0)],
@@ -299,6 +300,7 @@ fn two_audio_lanes_are_summed() {
299 eq: None,300 eq: None,
300 color: None,301 color: None,
301 fit: FitPolicy::default(),302 fit: FitPolicy::default(),
303+ speed: Speed::NORMAL,
302 };304 };
303 let a2 = project.add_lane(LaneKind::Audio);305 let a2 = project.add_lane(LaneKind::Audio);
304 assert!(project.place(a2, TOP_IN, doubled), "place the second lane");306 assert!(project.place(a2, TOP_IN, doubled), "place the second lane");
crates/engine/tests/saveload.rsmodified+16 -13
@@ -209,7 +209,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() {
209 let v2 = dir.join("new.edith");209 let v2 = dir.join("new.edith");
210 loaded.save_project(&v2).expect("save");210 loaded.save_project(&v2).expect("save");
211 let text = std::fs::read_to_string(&v2).expect("read back");211 let text = std::fs::read_to_string(&v2).expect("read back");
212- assert!(text.starts_with("edith 7\n"), "{text}");212+ assert!(text.starts_with("edith 8\n"), "{text}");
213 assert!(213 assert!(
214 text.contains("\nresolution 1280 720\n"),214 text.contains("\nresolution 1280 720\n"),
215 "a project with no resolution of its own is saved at source 0's: {text}"215 "a project with no resolution of its own is saved at source 0's: {text}"
@@ -297,9 +297,9 @@ fn a_version_4_project_holds_more_than_two_lanes() {
297 loaded.save_project(&again).expect("save");297 loaded.save_project(&again).expect("save");
298 assert_eq!(298 assert_eq!(
299 std::fs::read_to_string(&again).expect("read back"),299 std::fs::read_to_string(&again).expect("read back"),
300- "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\300+ "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\
301- video 1 0 0 30 0 3 - - fit\naudio 1\n\301+ video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\
302- video 2 40 0 20 0 - - - fit\naudio 2 0 0 30 0 3 - - fit\n",302+ video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n",
303 "a four-lane project is written as it was read, three versions on"303 "a four-lane project is written as it was read, three versions on"
304 );304 );
305 }305 }
@@ -327,11 +327,11 @@ fn a_version_5_project_carries_per_clip_equalizers() {
327 loaded.save_project(&again).expect("save");327 loaded.save_project(&again).expect("save");
328 assert_eq!(328 assert_eq!(
329 std::fs::read_to_string(&again).expect("read back"),329 std::fs::read_to_string(&again).expect("read back"),
330- "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\330+ "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\
331 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\331 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
332 eq 12000.0:6.25:0.5:hs\n\332 eq 12000.0:6.25:0.5:hs\n\
333- video 1 0 0 30 0 - 0 - fit\nvideo 1 30 30 60 0 - 1 - fit\n\333+ video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\
334- audio 1 0 0 30 0 - 0 - fit\naudio 1 30 30 60 0 - - - fit\n",334+ audio 1 0 0 30 0 - 0 - fit 1000\naudio 1 30 30 60 0 - - - fit 1000\n",
335 "the equalizer table and every clip's index survive a round trip"335 "the equalizer table and every clip's index survive a round trip"
336 );336 );
337 }337 }
@@ -362,12 +362,12 @@ fn a_version_6_project_carries_per_clip_colours() {
362 loaded.save_project(&again).expect("save");362 loaded.save_project(&again).expect("save");
363 assert_eq!(363 assert_eq!(
364 std::fs::read_to_string(&again).expect("read back"),364 std::fs::read_to_string(&again).expect("read back"),
365- "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\365+ "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\
366 eq 80.0:-3.0:0.707:ls\n\366 eq 80.0:-3.0:0.707:ls\n\
367 color 0.1:1.2:0.9:-0.3\n\367 color 0.1:1.2:0.9:-0.3\n\
368 color -0.25:1.0:0.0:0.5\n\368 color -0.25:1.0:0.0:0.5\n\
369- video 1 0 0 30 0 - 0 0 fit\nvideo 1 30 30 60 0 - - 1 fit\n\369+ video 1 0 0 30 0 - 0 0 fit 1000\nvideo 1 30 30 60 0 - - 1 fit 1000\n\
370- audio 1 0 0 30 0 - - 0 fit\naudio 1 30 30 60 0 - - - fit\n",370+ audio 1 0 0 30 0 - - 0 fit 1000\naudio 1 30 30 60 0 - - - fit 1000\n",
371 "the colour table and every clip's index survive a round trip"371 "the colour table and every clip's index survive a round trip"
372 );372 );
373 // A dialect that could not say either one means the defaults, and those are373 // A dialect that could not say either one means the defaults, and those are
@@ -412,8 +412,11 @@ fn a_version_7_project_carries_a_resolution_and_fit_policies() {
412 loaded.save_project(&again).expect("save");412 loaded.save_project(&again).expect("save");
413 assert_eq!(413 assert_eq!(
414 std::fs::read_to_string(&again).expect("read back"),414 std::fs::read_to_string(&again).expect("read back"),
415- text,415+ "edith 8\nplayhead 0\nresolution 960 720\nsource 0 test_av.mp4\n\
416- "a v7 project is written exactly as it was read"416+ video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\
417+ audio 1 0 0 60 0 - - - fit 1000\n",
418+ "a v7 project is written back as the v8 it now is: the same clips, each \
419+ saying it plays at real time, which is what it always played at"
417 );420 );
418 421
419 // The refusals the new grammar adds, each naming its line.422 // The refusals the new grammar adds, each naming its line.
@@ -667,7 +670,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() {
667 670
668 for (text, want) in [671 for (text, want) in [
669 (672 (
670- "edith 8\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n",673+ "edith 9\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n",
671 "line 1",674 "line 1",
672 ),675 ),
673 // An eq index the table does not hold, and a band shape there is none.676 // An eq index the table does not hold, and a band shape there is none.
crates/engine/tests/speed.rsadded+332 -0
@@ -0,0 +1,332 @@
1+//! Per-clip speed where it has to be true: in the pictures a preview shows, in
2+//! the samples the device is fed, in the file an export writes, and in the
3+//! project file the whole lot survives in.
4+//!
5+//! Everything goes through the front door. A `Project` is edited with
6+//! `set_speed` and then read exactly as `PlaybackSession::seek` reads it --
7+//! `audio_segments_from` + `audio_eqs_from` + `audio_speeds_from` handed to the
8+//! same opener playback hands them to, and `composite_span_at` handed to the
9+//! same decoder. Nothing calls the resampler directly; `project.rs`'s own unit
10+//! tests own the placement arithmetic, and what is measured here is the wiring.
11+//!
12+//! The fixture is `test_speed_sync.mp4` (`gen_fixtures.sh`): black with one white
13+//! flash from t=1.0 to t=1.1, silent with a 1 kHz beep over exactly that
14+//! stretch. A re-timed clip that drifts puts the beep where the flash is not,
15+//! which is the whole reason that file exists.
16+
17+use std::path::PathBuf;
18+use std::time::{Duration, Instant};
19+
20+use engine::export::{ExportSettings, Format};
21+use engine::project::{Lane, Speed};
22+use engine::{AudioSession, DecodeSession, ExportHandle, Project};
23+
24+const RATE: u32 = 44_100;
25+const FPS: f64 = 30.0;
26+
27+fn asset(name: &str) -> PathBuf {
28+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
29+ .join("../../assets")
30+ .join(name)
31+}
32+
33+/// The sync fixture as a fresh project: one video clip and one audio clip,
34+/// grouped, covering the whole file -- what opening it in the editor gives.
35+fn sync_project() -> (Project, engine::VideoMeta) {
36+ let path = asset("test_speed_sync.mp4");
37+ let (meta, _) = engine::demux::Demuxer::open(&path).expect("open the sync fixture");
38+ (Project::single(&path, meta.frame_count), meta)
39+}
40+
41+/// What the device would be fed, drained to the end: the exact three lists
42+/// `PlaybackSession::seek` builds, handed to the exact opener it hands them to.
43+fn play(project: &Project) -> Vec<f32> {
44+ let sources = project.audio_sources();
45+ let segs = project.audio_segments_from(0, FPS);
46+ let eqs = project.audio_eqs_from(0, FPS);
47+ let speeds = project.audio_speeds_from(0, FPS);
48+ let (meta, chunks) = AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds)
49+ .expect("open the timeline's audio")
50+ .expect("the timeline has audio");
51+ assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
52+ let mut samples = Vec::new();
53+ for chunk in chunks {
54+ samples.extend(chunk.samples);
55+ }
56+ samples
57+}
58+
59+/// When the beep starts, in timeline seconds: the first sample above a tenth of
60+/// full scale, which the silence around it is nowhere near.
61+fn beep_at(samples: &[f32]) -> f64 {
62+ let at = samples
63+ .iter()
64+ .position(|s| s.abs() > 0.1)
65+ .expect("the fixture beeps");
66+ at as f64 / 2.0 / f64::from(RATE)
67+}
68+
69+/// When the flash shows, in timeline seconds: the first frame the composite maps
70+/// to a white picture, walked exactly as `PlaybackSession::try_frame` walks it
71+/// -- the decoder is opened over the span's *source* range and its frame numbers
72+/// come back through the span's own rate.
73+fn flash_at(project: &Project) -> f64 {
74+ let span = project.composite_span_at(0).expect("a span at frame 0");
75+ let (source, in_frame) = span.from.expect("the span plays a clip");
76+ let path = &project.sources()[source].path;
77+ let (_, frames, _) = DecodeSession::open_range(path, in_frame, in_frame + span.source_len())
78+ .expect("open the fixture's picture");
79+ for frame in frames {
80+ // Mid-picture, so a stray edge pixel cannot answer for the frame.
81+ let middle = frame.bgra.len() / 2 / 4 * 4;
82+ if frame.bgra[middle] > 200 {
83+ let timeline = span.start + span.speed.timeline_at(frame.index - in_frame);
84+ return f64::from(timeline) / FPS;
85+ }
86+ }
87+ panic!("the fixture flashes");
88+}
89+
90+fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
91+ let started = Instant::now();
92+ while !handle.is_finished() {
93+ assert!(started.elapsed() < limit, "export did not finish");
94+ std::thread::sleep(Duration::from_millis(20));
95+ }
96+ handle.result().expect("a finished export has an outcome")
97+}
98+
99+fn out_path(name: &str, ext: &str) -> PathBuf {
100+ std::env::temp_dir().join(format!("edith-speed-{name}-{}.{ext}", std::process::id()))
101+}
102+
103+/// The headline: a clip at 2x is half as long on the timeline, plays the same
104+/// source range, and its box is the one thing that moved.
105+#[test]
106+fn a_clip_at_2x_takes_half_the_timeline_and_the_same_source() {
107+ let (mut project, _) = sync_project();
108+ let before = project.clips()[0];
109+ project
110+ .set_speed(Lane::V1, 0, Speed::from_permille(2000))
111+ .expect("nothing is in the way of a clip that got shorter");
112+ let after = project.clips()[0];
113+ assert_eq!(
114+ (after.in_frame, after.out_frame),
115+ (before.in_frame, before.out_frame),
116+ "the source range a trim and a split address is untouched"
117+ );
118+ assert_eq!(
119+ after.frames(),
120+ before.frames().div_ceil(2),
121+ "half the timeline frames, rounded"
122+ );
123+ assert_eq!(project.timeline_frames(), after.frames());
124+ // ...and its sound with it, on the other lane: one rate for the group.
125+ assert_eq!(project.speed_of(Lane::A1, 0).permille(), 2000);
126+ assert_eq!(project.lane(Lane::A1)[0].end(), after.end());
127+}
128+
129+/// The invariant a footprint may never break, over the whole legal range: a
130+/// clip always occupies at least one frame, whatever it is divided by.
131+#[test]
132+fn no_rate_ever_makes_a_clip_occupy_nothing() {
133+ for permille in [250, 333, 500, 999, 1000, 1001, 1500, 2000, 3999, 4000] {
134+ let speed = Speed::from_permille(permille);
135+ for len in [1, 2, 3, 7, 30, 999] {
136+ assert!(
137+ speed.frames(len) >= 1,
138+ "{len} source frames at {speed} occupies nothing"
139+ );
140+ }
141+ }
142+}
143+
144+/// Slowing a clip down makes it wider, and a lane may not overlap itself: the
145+/// refusal *names* the clip in the way, and costs no undo step.
146+#[test]
147+fn a_slow_down_into_the_next_clip_is_refused_by_name() {
148+ let (mut project, meta) = sync_project();
149+ let half = meta.frame_count / 2;
150+ assert!(project.split(half), "cut the take in two");
151+ let before = project.clips().to_vec();
152+ let text = project
153+ .set_speed(Lane::V1, 0, Speed::from_permille(500))
154+ .expect_err("the first half cannot double in length where it sits")
155+ .to_string();
156+ assert!(text.contains(&half.to_string()), "{text}");
157+ assert!(text.contains("0.50x"), "{text}");
158+ assert_eq!(project.clips(), before, "nothing moved");
159+ // ...and the refusal cost no undo step of its own: the one press left is
160+ // the split's, which puts the take back together.
161+ assert!(project.undo(), "the split is still the last thing undone");
162+ assert_eq!(project.clips().len(), 1, "the take is whole again");
163+ assert!(!project.undo(), "and nothing else was ever pushed");
164+}
165+
166+/// One rate change is one undo press, for the whole linked group -- the picture
167+/// and the sound come back together.
168+#[test]
169+fn one_speed_change_is_one_undo_for_the_whole_group() {
170+ let (mut project, _) = sync_project();
171+ let (video, audio) = (project.clips().to_vec(), project.lane(Lane::A1).to_vec());
172+ project
173+ .set_speed(Lane::A1, 0, Speed::from_permille(2000))
174+ .expect("room enough");
175+ // A drag is one snapshot and then live writes, which is what keeps a
176+ // gesture across the card's bar one undo and not forty.
177+ for permille in [1500, 1750, 4000] {
178+ project
179+ .set_speed_live(Lane::A1, 0, Speed::from_permille(permille))
180+ .expect("room enough");
181+ }
182+ assert!(project.undo(), "one press");
183+ assert_eq!(project.clips(), video, "the picture is back");
184+ assert_eq!(project.lane(Lane::A1), audio, "and its sound with it");
185+ assert!(!project.undo(), "there was only ever one step");
186+}
187+
188+/// A rate follows the clip through a split and through the clipboard, exactly
189+/// as an equalizer does: both halves keep it, and so does a paste.
190+#[test]
191+fn speed_survives_a_split_and_a_paste() {
192+ let (mut project, meta) = sync_project();
193+ project
194+ .set_speed(Lane::V1, 0, Speed::from_permille(2000))
195+ .expect("room enough");
196+ let whole = project.clips()[0].frames();
197+ assert!(project.split(whole / 2), "a 2x clip cuts on any frame");
198+ let halves = project.clips().to_vec();
199+ assert_eq!(halves.len(), 2);
200+ assert!(
201+ halves.iter().all(|c| c.speed.permille() == 2000),
202+ "both halves play at the rate the whole did"
203+ );
204+ assert_eq!(
205+ halves[0].frames() + halves[1].frames(),
206+ whole,
207+ "and they still add up to the clip that was cut"
208+ );
209+ assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
210+ assert_eq!(halves[1].end(), whole, "the lane is unchanged in length");
211+
212+ let copied = halves[0];
213+ assert!(project.paste(whole, copied), "paste it at the end");
214+ let pasted = *project.clips().last().expect("something was pasted");
215+ assert_eq!(pasted.speed, copied.speed, "a copy carries the rate");
216+ assert_eq!(
217+ pasted.frames(),
218+ copied.frames(),
219+ "and therefore the room it takes"
220+ );
221+ let _ = meta;
222+}
223+
224+/// The one the anti-list is about: at 2x the beep still lands on the flash. The
225+/// picture comes off the decoder through the span's own rate and the sound comes
226+/// out of the resampler in the worker -- two independent paths, measured against
227+/// each other.
228+#[test]
229+fn the_beep_stays_on_the_flash_at_every_rate() {
230+ // Where the fixture's own mark sits, measured rather than assumed: what the
231+ // rates below are checked against is this, divided.
232+ let (base, _) = sync_project();
233+ let (mark, mark_beep) = (flash_at(&base), beep_at(&play(&base)));
234+ println!("real time: flash at {mark:.3}s, beep at {mark_beep:.3}s");
235+ assert!(
236+ (mark - mark_beep).abs() <= 1.0 / FPS && mark > 2.0 / FPS,
237+ "the fixture's flash and beep are its whole point: {mark:.3}s / {mark_beep:.3}s"
238+ );
239+ for permille in [2000, 500, 1500] {
240+ let (mut project, _) = sync_project();
241+ let speed = Speed::from_permille(permille);
242+ project
243+ .set_speed(Lane::V1, 0, speed)
244+ .expect("one clip on the timeline has room for any rate");
245+ let flash = flash_at(&project);
246+ let beep = beep_at(&play(&project));
247+ let apart = (flash - beep).abs();
248+ println!("{speed}: flash at {flash:.3}s, beep at {beep:.3}s, {apart:.3}s apart");
249+ assert!(
250+ apart <= 1.0 / FPS,
251+ "{speed}: the beep is {apart:.3}s off the flash, which is more than a frame"
252+ );
253+ // ...and both of them moved: at 2x the mark is at half its own time, and
254+ // a test that measured two things standing still would pass forever.
255+ let expected = mark / speed.as_f64();
256+ assert!(
257+ (flash - expected).abs() <= 2.0 / FPS,
258+ "{speed}: the flash should be around {expected:.3}s, not {flash:.3}s"
259+ );
260+ }
261+}
262+
263+/// A WAV of a speeded timeline is as long as the timeline says, and it is the
264+/// sound that was heard -- the beep in the file sits where the preview put it.
265+#[test]
266+fn a_wav_export_of_a_2x_timeline_matches_the_preview() {
267+ let (mut project, meta) = sync_project();
268+ project
269+ .set_speed(Lane::V1, 0, Speed::from_permille(2000))
270+ .expect("room enough");
271+ let frames = project.timeline_frames();
272+ let heard = beep_at(&play(&project));
273+ let out = out_path("wav", "wav");
274+ let handle = engine::export::start(
275+ project,
276+ meta,
277+ &out,
278+ &ExportSettings {
279+ format: Format::Wav,
280+ ..Default::default()
281+ },
282+ );
283+ wait(&handle, Duration::from_secs(120)).expect("wav export");
284+ let mut reader = hound::WavReader::open(&out).expect("read the export back");
285+ let spec = reader.spec();
286+ let samples: Vec<f32> = reader
287+ .samples::<i16>()
288+ .map(|s| f32::from(s.expect("a sample")) / f32::from(i16::MAX))
289+ .collect();
290+ let written = samples.len() / usize::from(spec.channels);
291+ let expected = (f64::from(frames) / FPS * f64::from(RATE)).round() as usize;
292+ assert!(
293+ written.abs_diff(expected) <= spec.sample_rate as usize / 30,
294+ "the file is {written} frames and the timeline is {expected}"
295+ );
296+ let in_file = beep_at(&samples);
297+ assert!(
298+ (in_file - heard).abs() <= 1.0 / FPS,
299+ "the beep is at {in_file:.3}s in the file and was at {heard:.3}s in the preview"
300+ );
301+ std::fs::remove_file(&out).ok();
302+}
303+
304+/// A picture export cannot re-time a clip, so it says so and writes nothing --
305+/// which is the one thing it may not do silently. Both picture formats, because
306+/// a rule that held for one of them would be the surprise.
307+#[test]
308+fn a_picture_export_refuses_a_speeded_clip_by_name() {
309+ for format in [Format::Mp4, Format::Av1] {
310+ let (mut project, meta) = sync_project();
311+ project
312+ .set_speed(Lane::V1, 0, Speed::from_permille(2000))
313+ .expect("room enough");
314+ let out = out_path("refuse", "mp4");
315+ let handle = engine::export::start(
316+ project,
317+ meta.clone(),
318+ &out,
319+ &ExportSettings {
320+ format,
321+ ..Default::default()
322+ },
323+ );
324+ let text = wait(&handle, Duration::from_secs(120))
325+ .expect_err("a speeded timeline is not exportable as a picture")
326+ .to_string();
327+ assert!(text.contains("2.00x"), "{format:?}: {text}");
328+ assert!(text.contains("V1"), "{format:?}: {text}");
329+ assert!(text.contains("WAV"), "{format:?}: {text}");
330+ assert!(!out.exists(), "{format:?}: no file was written");
331+ }
332+}
scripts/gen_fixtures.shmodified+17 -0
@@ -113,6 +113,23 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
113 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \113 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
114 -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \114 -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
115 -c:a aac -b:a 128k assets/test_av1.mkv115 -c:a aac -b:a 128k assets/test_av1.mkv
116+# Sync fixture: one flash and one beep, at the same instant. Black picture with
117+# a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that
118+# stretch — so a test can find each of them and say how far apart they came out.
119+# What it is for is *speed*: a re-timed clip that drifts puts the beep somewhere
120+# the flash is not, and nothing else in the fixture set has a mark to measure
121+# that against. Same 30 fps / 44.1k stereo shape as test_av.mp4, so it can share
122+# a timeline with the rest.
123+# The beep is silence-then-tone-then-silence rather than a gated tone: lavfi's
124+# `sine` comes out at an eighth of full scale, and a mark a test looks for has
125+# to be plainly louder than anything around it.
126+ffmpeg -y -f lavfi -i "color=c=black:s=320x180:r=30:d=3" \
127+ -f lavfi -i "sine=frequency=1000:duration=0.1:sample_rate=44100" \
128+ -filter_complex "[0:v]drawbox=x=0:y=0:w=iw:h=ih:color=white:t=fill:\
129+enable='between(t,1,1.1)'[v];\
130+[1:a]volume=6,aformat=channel_layouts=stereo,adelay=1000|1000,apad=whole_dur=3[a]" \
131+ -map "[v]" -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
132+ -c:a aac -b:a 128k assets/test_speed_sync.mp4
116 # Mismatch fixture: different resolution and no audio track at all, so import133 # Mismatch fixture: different resolution and no audio track at all, so import
117 # has something concrete to refuse.134 # has something concrete to refuse.
118 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 \