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 {
7070 VolumeUp,
7171 VolumeDown,
7272 Equalizer,
73+ Speed,
7374 CancelExport,
7475 }
7576
7677 impl ActionId {
7778 /// Display order everywhere -- the editor lists them in it and
7879 /// [`Keymap::defaults`] binds them in it.
79- pub const ALL: [ActionId; 31] = [
80+ pub const ALL: [ActionId; 32] = [
8081 ActionId::Play,
8182 ActionId::StepBack,
8283 ActionId::StepForward,
@@ -107,6 +108,7 @@ impl ActionId {
107108 ActionId::VolumeUp,
108109 ActionId::VolumeDown,
109110 ActionId::Equalizer,
111+ ActionId::Speed,
110112 ActionId::CancelExport,
111113 ];
112114
@@ -143,6 +145,7 @@ impl ActionId {
143145 ActionId::VolumeUp => "Volume up",
144146 ActionId::VolumeDown => "Volume down",
145147 ActionId::Equalizer => "Equalizer",
148+ ActionId::Speed => "Speed (tape)…",
146149 ActionId::CancelExport => "Cancel export",
147150 }
148151 }
@@ -181,6 +184,7 @@ impl ActionId {
181184 ActionId::VolumeUp => "volume-up",
182185 ActionId::VolumeDown => "volume-down",
183186 ActionId::Equalizer => "equalizer",
187+ ActionId::Speed => "speed",
184188 ActionId::CancelExport => "cancel-export",
185189 }
186190 }
@@ -209,7 +213,11 @@ impl ActionId {
209213 | ActionId::Delete
210214 | ActionId::Lift
211215 | 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,
213221 // The project's own picture size is not a clip's business, and not
214222 // a file operation either: it is what the viewer is looking at.
215223 ActionId::Resolution => Category::View,
@@ -507,6 +515,11 @@ impl Keymap {
507515 // The one free letter that says the word: "e" is already the
508516 // export and an equalizer is the q in nobody else's way.
509517 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),
510523 b(ActionId::CancelExport, "escape", false),
511524 ],
512525 }
@@ -769,7 +782,7 @@ mod tests {
769782 #[test]
770783 fn every_default_stroke_reaches_its_action() {
771784 let k = Keymap::defaults();
772- assert_eq!(k.entries().len(), 33);
785+ assert_eq!(k.entries().len(), 34);
773786 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
774787 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
775788 // ends of the timeline.
@@ -814,7 +827,8 @@ mod tests {
814827 // The modifier is half the chord: ctrl+e is not e.
815828 assert_eq!(k.lookup("e", true), None);
816829 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);
818832 // Nothing is bound twice, or lookup's first match would be a coin toss.
819833 for (i, a) in k.entries().iter().enumerate() {
820834 assert!(
@@ -996,7 +1010,7 @@ mod tests {
9961010 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
9971011 // The label is the editor's column, and never the file's word for it.
9981012 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
999- assert_eq!(ActionId::ALL.len(), 31);
1013+ assert_eq!(ActionId::ALL.len(), 32);
10001014 }
10011015
10021016 #[test]
crates/app/src/main.rsmodified+409 -13
@@ -13,7 +13,7 @@ use engine::audio::StreamInfo;
1313 use engine::color::ColorParams;
1414 use engine::eq::{Band, BandKind, EqParams};
1515 use engine::export::{ExportSettings, Format};
16-use engine::project::{Edge, Lane, LaneKind, Source};
16+use engine::project::{Edge, Lane, LaneKind, Source, Speed};
1717 use engine::scale::FitPolicy;
1818 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
1919 use gpui::{
@@ -311,7 +311,7 @@ impl RowItem {
311311 /// action a stroke already reaches -- the menu is a second way *to* the actions
312312 /// and never a second version of them -- so both the label and the hint come
313313 /// out of the keymap registry and the two can never disagree.
314-const MENU_ITEMS: [ActionId; 10] = [
314+const MENU_ITEMS: [ActionId; 11] = [
315315 ActionId::Cut,
316316 ActionId::Delete,
317317 ActionId::Lift,
@@ -319,6 +319,7 @@ const MENU_ITEMS: [ActionId; 10] = [
319319 ActionId::Detach,
320320 ActionId::Group,
321321 ActionId::Equalizer,
322+ ActionId::Speed,
322323 ActionId::Color,
323324 ActionId::Fit,
324325 ActionId::ToggleMute,
@@ -339,6 +340,23 @@ const EQ_GAIN_LIMIT: f32 = 12.;
339340 /// single band.
340341 const EQ_STEP: f32 = 1.;
341342
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+
342360 /// The graph's frequency axis: the range an ear works in, and the range every
343361 /// band a file can carry sits inside. Log-spaced, so an octave is an octave
344362 /// wherever it falls.
@@ -542,6 +560,17 @@ struct Player {
542560 /// there. `None` when it is closed, which is the only place that state
543561 /// lives: the grade itself is the project's.
544562 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,
545574 /// Which of the card's four sliders the arrow keys and a drag move. The
546575 /// card's own focus, since nothing in it takes gpui's (ledger:182).
547576 color_band: usize,
@@ -708,6 +737,7 @@ impl Player {
708737 ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx),
709738 ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),
710739 ActionId::Equalizer => self.open_eq(cx),
740+ ActionId::Speed => self.open_speed(cx),
711741 // Nothing to cancel while nothing is exporting; the export guard in
712742 // the key handler is what answers this one while there is.
713743 ActionId::CancelExport => {}
@@ -953,6 +983,108 @@ impl Player {
953983 self.write_color(params, !first, cx);
954984 }
955985
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+
9561088 /// Whether a card owns the window. While one does the timeline under it is
9571089 /// out of reach, so a right-click there opens no menu -- the same rule the
9581090 /// key handler and the drop target already follow.
@@ -961,6 +1093,7 @@ impl Player {
9611093 || self.export_open
9621094 || self.eq_open.is_some()
9631095 || self.color_open.is_some()
1096+ || self.speed_open.is_some()
9641097 || self.exporting().is_some()
9651098 }
9661099
@@ -2344,6 +2477,29 @@ impl Render for Player {
23442477 cx.notify();
23452478 return;
23462479 }
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+ }
23472503 // A clip menu names an index, and every edit below moves
23482504 // indices -- so a stroke closes it before it acts. Escape means
23492505 // that and nothing else, which is the `esc` the keys menu
@@ -2426,6 +2582,16 @@ impl Render for Player {
24262582 }
24272583 return;
24282584 }
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+ }
24292595 if !this.scrubbing {
24302596 return;
24312597 }
@@ -2462,6 +2628,10 @@ impl Render for Player {
24622628 this.drag_color(event.position.x, false, cx);
24632629 return;
24642630 }
2631+ if std::mem::take(&mut this.speed_dragging) {
2632+ this.drag_speed(event.position.x, false, cx);
2633+ return;
2634+ }
24652635 if std::mem::take(&mut this.scrubbing) {
24662636 this.scrub_to(event.position.x, true, cx);
24672637 }
@@ -2540,6 +2710,7 @@ impl Render for Player {
25402710 .children(self.export_card(cx))
25412711 .children(self.eq_card(cx))
25422712 .children(self.color_card(cx))
2713+ .children(self.speed_card(cx))
25432714 }
25442715 }
25452716
@@ -3834,6 +4005,138 @@ impl Player {
38344005 )
38354006 }
38364007
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+
38374140 /// The menu a right-click on a library row opens: what can be done with the
38384141 /// *file* rather than with a clip of it, and a turn-over side saying what
38394142 /// that file is. Built like [`Player::context_card`] down to the scrim, the
@@ -4055,7 +4358,11 @@ impl Player {
40554358 "Source range",
40564359 format!("{} – {}", secs(clip.in_frame), secs(clip.out_frame)),
40574360 ),
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)),
40594366 ("Source duration", secs(session.file_frames(&source.path))),
40604367 ] {
40614368 rows.push(
@@ -4296,9 +4603,12 @@ impl Player {
42964603 // What a drag on an edge is showing, which is the clip
42974604 // itself while nothing is being dragged.
42984605 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.
42994609 let (start, len) = (
43004610 f64::from(clip.start) / self.fps,
4301- f64::from(clip.len()) / self.fps,
4611+ f64::from(clip.frames()) / self.fps,
43024612 );
43034613 let on = marked((lane, i), clip.link, sel, sel_link);
43044614 // A group with a half in the other lane wears its tint;
@@ -4442,6 +4752,25 @@ impl Player {
44424752 .child(inner),
44434753 )
44444754 }))
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+ })
44454774 .when_some(label.filter(|_| show_label(bed_w * width)), |d, label| {
44464775 d.child(
44474776 div()
@@ -4716,8 +5045,19 @@ fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool
47165045 // A fit policy is a picture setting for the same reason.
47175046 ActionId::Color | ActionId::Fit => lane.kind == LaneKind::Video,
47185047 // Splits this clip only from inside it: at either edge there is nothing
4719- // to split off (project.rs `splittable`).
4720- ActionId::Cut => clip.start < playhead && playhead < clip.end(),
5048+ // to split off -- and, on a speeded clip, only at a frame its own rate
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).
47215061 // Rejoins whatever meets at the playhead, so it can mean something only
47225062 // at an edge of this clip. Whether those two halves were ever one take
47235063 // is the engine's question, and it words that refusal itself.
@@ -5735,13 +6075,13 @@ mod tests {
57356075 Format, HEADER_GAP, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM,
57366076 KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX,
57376077 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,
5739- WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, color_snap,
5740- envelope, eq_x, eq_y, export_path, export_settings, format_key, format_line,
5741- format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project,
5742- keymap, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit, retarget,
5743- scrub_due, show_label, source_tint, span_partner, start_frac, timecode, unseen_paths,
5744- unseen_sources, whole_take, width_frac, window_title,
6078+ RULER_HIT_H, SELECTED, SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source,
6079+ Speed, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add,
6080+ cancels_export, color_snap, envelope, eq_x, eq_y, export_path, export_settings, format_key,
6081+ format_line, format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier,
6082+ is_project, keymap, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit,
6083+ retarget, scrub_due, show_label, source_tint, span_partner, speed_at, start_frac, timecode,
6084+ unseen_paths, unseen_sources, whole_take, width_frac, window_title,
57456085 };
57466086 use super::{file_name, file_uri, library_rows};
57476087
@@ -6028,6 +6368,7 @@ mod tests {
60286368 eq: None,
60296369 color: None,
60306370 fit: FitPolicy::default(),
6371+ speed: Speed::NORMAL,
60316372 };
60326373 assert_eq!(clip.end(), 90);
60336374 // Cut splits from inside only: neither edge has anything to split off.
@@ -6942,6 +7283,58 @@ mod tests {
69427283 assert!(KEYS_ROW_H >= HIT_MIN);
69437284 }
69447285
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+
69457338 /// A colour slider is dragged straight to a value, so where the pointer
69467339 /// lands and where the bar then paints have to be the same place: this is
69477340 /// the round trip [`Player::drag_color`] makes, pixels -> value -> fill.
@@ -7633,6 +8026,9 @@ fn main() {
76338026 eq_band: 0,
76348027 eq_dragging: false,
76358028 eq_graph: Rc::default(),
8029+ speed_open: None,
8030+ speed_bar: Rc::default(),
8031+ speed_dragging: false,
76368032 color_open: None,
76378033 color_band: 0,
76388034 color_dragging: false,
crates/engine/src/audio.rsmodified+232 -6
@@ -245,6 +245,28 @@ impl AudioSession {
245245 sources: &[(PathBuf, usize)],
246246 segs: &[(Option<usize>, f64, f64)],
247247 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>],
248270 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
249271 let Some((path, stream)) = sources.first() else {
250272 return Ok(None);
@@ -330,6 +352,23 @@ impl AudioSession {
330352 })
331353 .collect();
332354
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+
333372 let (tx, rx) = sync_channel(32);
334373 thread::Builder::new()
335374 .name("audio-decode".into())
@@ -339,6 +378,7 @@ impl AudioSession {
339378 channels: meta.channels as usize,
340379 segments,
341380 eqs,
381+ speeds,
342382 timeline,
343383 tx,
344384 })
@@ -384,13 +424,37 @@ impl AudioSession {
384424 sources: &[(PathBuf, usize)],
385425 lanes: &[Vec<(Option<usize>, f64, f64)>],
386426 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>>],
387445 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
388446 let [first, rest @ ..] = lanes else {
389447 return Ok(None);
390448 };
391449 if rest.is_empty() {
392450 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+ );
394458 }
395459 let mut meta = None;
396460 let mut rxs = Vec::with_capacity(lanes.len());
@@ -398,8 +462,13 @@ impl AudioSession {
398462 // Every lane probes the same source 0, so the metas agree by
399463 // construction; `None` from any of them is a silent timeline.
400464 let flat = Vec::new();
401- let Some((lane_meta, rx)) =
402- Self::open_multi_streams_eq(sources, segs, eqs.get(i).unwrap_or(&flat))?
465+ let plain = Vec::new();
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+ )?
403472 else {
404473 return Ok(None);
405474 };
@@ -1511,6 +1580,104 @@ impl Segment {
15111580 }
15121581 }
15131582
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+
15141681 struct Worker {
15151682 /// Indexed by [`Segment::source`]; only the sources some segment names are
15161683 /// `Some`, the rest were never opened.
@@ -1522,6 +1689,10 @@ struct Worker {
15221689 /// Beside the segments rather than inside them so the emit path can hold the
15231690 /// window rules and the filter memory at once without splitting a borrow.
15241691 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>>,
15251696 /// `start_sample` of the first chunk.
15261697 timeline: u64,
15271698 tx: SyncSender<AudioChunk>,
@@ -1603,8 +1774,11 @@ fn run(mut w: Worker) {
16031774 // A short list is "flat from here on" (`open_multi_streams_eq`), which this
16041775 // pads out so the zip below still walks every segment.
16051776 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);
16061780
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()) {
16081782 let Some(source) = seg.source else {
16091783 // A gap: hand the device real silence rather than nothing at all,
16101784 // in the same packet-sized chunks decoding produces, so `fed` and
@@ -1629,13 +1803,31 @@ fn run(mut w: Worker) {
16291803 };
16301804 let track = match track {
16311805 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+ {
16331816 return; // consumer went away
16341817 }
16351818 continue;
16361819 }
16371820 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+ {
16391831 return; // consumer went away
16401832 }
16411833 continue;
@@ -1684,6 +1876,7 @@ fn run(mut w: Worker) {
16841876 channels,
16851877 seg,
16861878 eq.as_mut(),
1879+ speed.as_mut(),
16871880 pos,
16881881 next,
16891882 &mut timeline,
@@ -1693,6 +1886,24 @@ fn run(mut w: Worker) {
16931886 }
16941887 pos = next;
16951888 }
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,
16961907 }
16971908 }
16981909
@@ -1717,6 +1928,7 @@ fn emit(
17171928 channels: usize,
17181929 seg: &Segment,
17191930 eq: Option<&mut EqState>,
1931+ speed: Option<&mut Resample>,
17201932 pos: u64,
17211933 next: u64,
17221934 timeline: &mut u64,
@@ -1736,6 +1948,16 @@ fn emit(
17361948 if interleaved.is_empty() {
17371949 return true; // nothing left of it; the loop head ends the segment
17381950 }
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+ }
17391961 if let Some(eq) = eq {
17401962 eq.process(interleaved);
17411963 }
@@ -1755,6 +1977,7 @@ fn run_ac3(
17551977 track: &mut Ac3Track,
17561978 seg: &Segment,
17571979 mut eq: Option<&mut EqState>,
1980+ speed: &mut Option<Resample>,
17581981 channels: usize,
17591982 timeline: &mut u64,
17601983 tx: &SyncSender<AudioChunk>,
@@ -1794,6 +2017,7 @@ fn run_ac3(
17942017 channels,
17952018 seg,
17962019 eq.as_deref_mut(),
2020+ speed.as_mut(),
17972021 pos,
17982022 next,
17992023 timeline,
@@ -1819,6 +2043,7 @@ fn run_sym(
18192043 track: &mut SymTrack,
18202044 seg: &Segment,
18212045 mut eq: Option<&mut EqState>,
2046+ speed: &mut Option<Resample>,
18222047 channels: usize,
18232048 timeline: &mut u64,
18242049 tx: &SyncSender<AudioChunk>,
@@ -1876,6 +2101,7 @@ fn run_sym(
18762101 channels,
18772102 seg,
18782103 eq.as_deref_mut(),
2104+ speed.as_mut(),
18792105 pos,
18802106 next,
18812107 timeline,
crates/engine/src/edith.rsmodified+159 -45
@@ -1,16 +1,16 @@
11 //! The project file: a line of text per thing, and nothing else.
22 //!
33 //! ```text
4-//! edith 7
4+//! edith 8
55 //! playhead 90
66 //! resolution 1920 1080
77 //! source 0 test_av.mp4
88 //! source 1 /elsewhere/test_av2.mp4
99 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
1010 //! color 0.1:1.2:0.9:-0.3
11-//! video 1 0 0 120 0 0 0 0 fit
12-//! audio 1 0 0 120 0 0 0 - fit
13-//! video 2 120 0 120 1 - - - fill
11+//! video 1 0 0 120 0 0 0 0 fit 1000
12+//! audio 1 0 0 120 0 0 0 - fit 1000
13+//! video 2 120 0 120 1 - - - fill 2000
1414 //! audio 2
1515 //! ```
1616 //!
@@ -39,22 +39,28 @@
3939 //! -- the first colour line is color 0 -- printed and refused by the same rules.
4040 //!
4141 //! 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 number
42+//! <color> <fit> <speed>`: which lane the clip is on -- its kind and its 1-based number
4343 //! among the lanes of that kind, the [`crate::project::Lane::label`] a header
4444 //! column shows -- then where the clip sits on the timeline, the half-open
4545 //! source range it plays, the file it plays from, its group id, the eq line it
4646 //! plays through, the colour line it is graded by (`-` for none of those three)
4747 //! and how it meets a project canvas of another shape, spelled `fit`, `fill`,
48-//! `stretch` or `center` ([`crate::scale::FitPolicy`]). Timeline placement is
48+//! `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
4951 //! 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.
5155 //!
5256 //! A lane is declared by the clips on it, in the order the lanes are displayed
5357 //! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
5458 //! is the only way an empty lane could still be there on the way back. A lane
5559 //! number may not skip one of its kind.
5660 //!
57-//! **Version 6** was this without the `resolution` line and without the clip's
61+//! **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
5864 //! fit field -- such a project is the size of its first source and letterboxes
5965 //! nothing, because nothing on it could differ in size. **Version 5** was that
6066 //! without the colour lines and without the clip's colour
@@ -63,10 +69,11 @@
6369 //! lane and one audio lane, no more. **Version 2** wrote `source <path>` as
6470 //! well, which is this file's stream 0 -- one per file, whichever audio track
6571 //! 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 out
72+//! <in> <out> <source>`. All six still load -- a v1 file's clips are laid out
6773 //! cumulatively and copied onto both lanes as one group each, which is exactly
6874 //! 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 newer
75+//! nothing, and an older one plays everything at real time -- and saving any of
76+//! them writes v8. An older reader refuses a newer
7077 //! file by name.
7178 //!
7279 //! 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};
95102
96103 use crate::color::ColorParams;
97104 use crate::eq::{Band, BandKind, EqParams};
98-use crate::project::{Clip, Lane, LaneKind, Source};
105+use crate::project::{Clip, Lane, LaneKind, Source, Speed};
99106 use crate::scale::FitPolicy;
100107
101108 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
102109 /// 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";
104112 const MAGIC_V6: &[u8] = b"edith 6";
105113 const MAGIC_V5: &[u8] = b"edith 5";
106114 const MAGIC_V4: &[u8] = b"edith 4";
@@ -256,12 +264,13 @@ fn emit(
256264 let color = c.color.map_or("-".to_string(), |e| e.to_string());
257265 out.extend_from_slice(
258266 format!(
259- "{keyword} {ord} {} {} {} {} {link} {eq} {color} {}\n",
267+ "{keyword} {ord} {} {} {} {} {link} {eq} {color} {} {}\n",
260268 c.start,
261269 c.in_frame,
262270 c.out_frame,
263271 c.source,
264- fit_name(c.fit)
272+ fit_name(c.fit),
273+ c.speed.permille()
265274 )
266275 .as_bytes(),
267276 );
@@ -280,8 +289,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
280289 // The dialects that wrote a source line without its stream field. Reading
281290 // one is the whole of what "an old project still opens" means here.
282291 let streamless = v1 || first == MAGIC_V2;
283- // The one that carries a project resolution and per-clip fit policies...
284- let v7 = first == MAGIC;
292+ // The one that carries a per-clip speed...
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;
285296 // ...the ones that carry colour grades...
286297 let v6 = v7 || first == MAGIC_V6;
287298 // ...the ones that carry equalizer settings...
@@ -430,6 +441,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
430441 eq: None,
431442 color: None,
432443 fit: FitPolicy::default(),
444+ speed: Speed::NORMAL,
433445 },
434446 &doc,
435447 n,
@@ -459,9 +471,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
459471 if numbered && rest.is_empty() {
460472 continue;
461473 }
462- // v7 grew the fit field, v6 the colour one and v5 the eq one;
463- // every older dialect ends at the link.
464- let want = 5 + usize::from(v5) + usize::from(v6) + usize::from(v7);
474+ // v8 grew the speed field, v7 the fit one, v6 the colour one and
475+ // v5 the eq one; every older dialect ends at the link.
476+ let want =
477+ 5 + usize::from(v5) + usize::from(v6) + usize::from(v7) + usize::from(v8);
465478 let f = fields(rest, want, "clip", n)?;
466479 let clip = check(
467480 Clip {
@@ -476,6 +489,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
476489 eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?,
477490 color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?,
478491 fit: fit_policy(f.get(7).copied(), n)?,
492+ speed: speed_of(f.get(8).copied(), n)?,
479493 },
480494 &doc,
481495 n,
@@ -581,7 +595,7 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
581595 // Everything downstream -- `Clip::end`, the overlap check, the v1 queue --
582596 // adds `start + len` as plain `u32`, which panics in debug and wraps in
583597 // 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() {
585599 return Err(format!(
586600 "line {line}: clip at {} runs past the last frame there is",
587601 clip.start
@@ -591,6 +605,29 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
591605 Ok(clip)
592606 }
593607
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+
594631 /// How a fit policy is spelled in the file. One word each, so a clip line stays
595632 /// readable, and the same word the parser takes back.
596633 fn fit_name(fit: FitPolicy) -> &'static str {
@@ -746,6 +783,7 @@ mod tests {
746783 eq: None,
747784 color: None,
748785 fit: FitPolicy::default(),
786+ speed: Speed::NORMAL,
749787 }
750788 }
751789
@@ -795,10 +833,10 @@ mod tests {
795833 let bytes = flat(&dir, &sources, &lanes, 12);
796834 assert_eq!(
797835 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\
799837 source 2 /elsewhere/b.mp4\n\
800- video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\
801- audio 1 0 0 30 0 0 - - fit\n",
838+ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
839+ audio 1 0 0 30 0 0 - - fit 1000\n",
802840 "the file under the project directory is written relative to it, \
803841 each with the audio stream it plays"
804842 );
@@ -832,9 +870,9 @@ mod tests {
832870 let bytes = flat(&dir, &sources, &lanes, 7);
833871 assert_eq!(
834872 String::from_utf8_lossy(&bytes),
835- "edith 7\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
836- video 1 0 0 30 0 4 - - fit\naudio 1\n\
837- video 2 40 0 10 0 - - - fit\naudio 2 0 0 30 0 4 - - fit\n",
873+ "edith 8\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
874+ video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\
875+ video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",
838876 "an empty lane is a line of its own; everything else is its clips"
839877 );
840878 let back = parse(&bytes, &dir).expect("parse");
@@ -940,12 +978,12 @@ mod tests {
940978 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
941979 assert_eq!(
942980 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\
944982 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
945983 eq 16777215.0:-0.1:3.918315e-39:hs\n\
946984 eq\n\
947- video 1 0 0 30 0 0 0 - fit\nvideo 1 30 10 20 0 - 1 - fit\n\
948- audio 1 0 0 30 0 0 0 - fit\naudio 1 30 0 10 0 - 2 - fit\n",
985+ video 1 0 0 30 0 0 0 - fit 1000\nvideo 1 30 10 20 0 - 1 - fit 1000\n\
986+ audio 1 0 0 30 0 0 0 - fit 1000\naudio 1 30 0 10 0 - 2 - fit 1000\n",
949987 "the table comes before the clips, and a clip names a line of it"
950988 );
951989
@@ -1016,11 +1054,13 @@ mod tests {
10161054 Clip {
10171055 color: Some(0),
10181056 fit: FitPolicy::default(),
1057+ speed: Speed::NORMAL,
10191058 ..clip(0, 0, 30, 0, Some(0))
10201059 },
10211060 Clip {
10221061 color: Some(1),
10231062 fit: FitPolicy::default(),
1063+ speed: Speed::NORMAL,
10241064 ..clip(30, 10, 20, 0, None)
10251065 },
10261066 ],
@@ -1028,11 +1068,13 @@ mod tests {
10281068 Clip {
10291069 color: Some(0),
10301070 fit: FitPolicy::default(),
1071+ speed: Speed::NORMAL,
10311072 ..clip(0, 0, 30, 0, Some(0))
10321073 },
10331074 Clip {
10341075 color: Some(2),
10351076 fit: FitPolicy::default(),
1077+ speed: Speed::NORMAL,
10361078 ..clip(30, 0, 10, 0, None)
10371079 },
10381080 ],
@@ -1040,12 +1082,12 @@ mod tests {
10401082 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
10411083 assert_eq!(
10421084 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\
10441086 color 0.1:1.2:0.9:-0.3\n\
10451087 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
10461088 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\
1048- audio 1 0 0 30 0 0 - 0 fit\naudio 1 30 0 10 0 - - 2 fit\n",
1089+ video 1 0 0 30 0 0 - 0 fit 1000\nvideo 1 30 10 20 0 - - 1 fit 1000\n\
1090+ audio 1 0 0 30 0 0 - 0 fit 1000\naudio 1 30 0 10 0 - - 2 fit 1000\n",
10491091 "the table comes before the clips, and a clip names a line of it"
10501092 );
10511093
@@ -1105,9 +1147,81 @@ mod tests {
11051147 (1280, 720),
11061148 old.playhead
11071149 )),
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\
11091151 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"
11111225 );
11121226 }
11131227
@@ -1241,10 +1355,10 @@ mod tests {
12411355 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
12421356 assert_eq!(
12431357 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\
12451359 source 2 /elsewhere/b.mp4\n\
1246- video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\
1247- audio 1 0 0 30 0 0 - - fit\n"
1360+ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1361+ audio 1 0 0 30 0 0 - - fit 1000\n"
12481362 );
12491363 // An empty lane's line is still the whole of that lane, eq or no eq.
12501364 let empty = parse(
@@ -1294,10 +1408,10 @@ mod tests {
12941408 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
12951409 assert_eq!(
12961410 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\
12981412 source 0 /elsewhere/b.mp4\n\
1299- video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\
1300- audio 1 0 0 30 0 0 - - fit\n",
1413+ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1414+ audio 1 0 0 30 0 0 - - fit 1000\n",
13011415 "a re-saved v2 project differs only by its version, the lane \
13021416 numbers, the streams it always meant and an equalizer it has none of"
13031417 );
@@ -1326,7 +1440,7 @@ mod tests {
13261440 // Saved again it is the current version, which round-trips to the
13271441 // same document.
13281442 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"));
13301444 let again = parse(&v5, &dir).expect("v5 parses");
13311445 assert_eq!(again.lanes, back.lanes);
13321446 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
@@ -1428,8 +1542,8 @@ mod tests {
14281542 let bytes = std::fs::read(&path).expect("read back");
14291543 assert_eq!(
14301544 String::from_utf8_lossy(&bytes),
1431- "edith 7\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"
1545+ "edith 8\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
1546+ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
14331547 );
14341548 // Loading rejoins the *given* directory, so the file is reached by the
14351549 // way the project was opened -- the same file, through the link, still
@@ -1473,10 +1587,10 @@ mod tests {
14731587 #[test]
14741588 fn a_wrong_first_line_is_refused_by_name() {
14751589 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)
14771591 .unwrap_err()
14781592 .to_string();
1479- assert_eq!(err, "line 1: unsupported version 8");
1593+ assert_eq!(err, "line 1: unsupported version 9");
14801594 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
14811595 assert_eq!(
14821596 parse(junk, &dir).unwrap_err().to_string(),
crates/engine/src/export.rsmodified+45 -1
@@ -317,6 +317,42 @@ fn copy_audio(
317317 AudioSession::copy_multi_streams(&project.audio_sources(), segments)
318318 }
319319
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+
320356 fn run(
321357 project: &Project,
322358 meta: &VideoMeta,
@@ -325,6 +361,7 @@ fn run(
325361 settings: &ExportSettings,
326362 ) -> crate::Result<()> {
327363 let total = project.timeline_frames();
364+ speeds_refused(project, meta)?;
328365 let sources = project.sources();
329366 // Audio first: a track has to be declared when the muxer is created, which
330367 // happens as soon as the first coded picture arrives. None of it for AV1 --
@@ -502,7 +539,14 @@ fn run_audio(
502539 // playback's feeder reads from -- there is no second place here that could
503540 // apply them differently.
504541 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 {
506550 return Err("this timeline has no audio to export".into());
507551 };
508552 let channels = usize::from(audio.channels);
crates/engine/src/lib.rsmodified+1 -1
@@ -26,7 +26,7 @@ pub use demux::{Codec, VideoMeta};
2626 pub use export::ExportHandle;
2727 pub use mux::{AudioParams, Mp4Muxer, VideoParams};
2828 pub use playback::PlaybackSession;
29-pub use project::{Clip, Project};
29+pub use project::{Clip, Project, Speed};
3030
3131 /// Whether a path names a standalone audio file -- a source with no picture,
3232 /// 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;
2525 use crate::decode::{DecodeSession, Frame, Worker};
2626 use crate::demux::{Codec, Demuxer, VideoMeta};
2727 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};
2929 use crate::scale::{Composer, FitPolicy};
3030
3131 /// How long the feeder waits out a full ring. The ring holds a second, so this
@@ -309,6 +309,7 @@ impl PlaybackSession {
309309 eq: None,
310310 color: None,
311311 fit: FitPolicy::default(),
312+ speed: Speed::NORMAL,
312313 };
313314 let project = Project::from_parts(
314315 vec![Source::new(path, 0)],
@@ -374,6 +375,7 @@ impl PlaybackSession {
374375 eq: None,
375376 color: None,
376377 fit: FitPolicy::default(),
378+ speed: Speed::NORMAL,
377379 };
378380 // No group and no audio clip: a still is silent, and a clip on `A1`
379381 // playing from a PNG is a source the audio worker cannot open.
@@ -654,10 +656,17 @@ impl PlaybackSession {
654656 // A gap's worker indexes from zero, a decoder's from its in
655657 // point: `base` is whichever this span started at. An empty
656658 // timeline has no span, and its one black frame is frame 0.
657- let (start, base) = self
658- .span
659- .map_or((0, 0), |s| (s.start, s.from.map_or(0, |(_, i)| i)));
660- frame.index = start + frame.index.saturating_sub(base);
659+ let (start, base, speed) = self.span.map_or((0, 0, Speed::NORMAL), |s| {
660+ (s.start, s.from.map_or(0, |(_, i)| i), s.speed)
661+ });
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));
661670 return Some(frame);
662671 }
663672 Err(TryRecvError::Empty) => return None,
@@ -733,15 +742,18 @@ impl PlaybackSession {
733742 // the worker carries it and every frame it converts wears it.
734743 Some(Span {
735744 start,
736- len,
737745 from: Some((source, in_frame)),
746+ ..
738747 }) if crate::is_image(&self.project.sources()[source].path) => {
739748 // A still: the same grade and the same canvas as any other
740749 // 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.
741753 DecodeSession::open_still(
742754 &self.project.sources()[source].path,
743755 in_frame,
744- len,
756+ span.expect("matched above").source_len(),
745757 self.project
746758 .composite_color_at(start)
747759 .copied()
@@ -756,12 +768,14 @@ impl PlaybackSession {
756768 }
757769 Some(Span {
758770 start,
759- len,
760771 from: Some((source, in_frame)),
772+ ..
761773 }) => DecodeSession::open_worker(
762774 &self.project.sources()[source].path,
763775 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(),
765779 self.project
766780 .composite_color_at(start)
767781 .copied()
@@ -961,6 +975,36 @@ impl PlaybackSession {
961975 true
962976 }
963977
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+
9641008 /// Where that edge may land, `(first, last)` timeline frame inclusive: what
9651009 /// a drag clamps the pointer to so the box it draws is the box
9661010 /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.
@@ -1166,6 +1210,7 @@ impl PlaybackSession {
11661210 eq: None,
11671211 color: None,
11681212 fit: FitPolicy::default(),
1213+ speed: Speed::NORMAL,
11691214 };
11701215 // Which lane a source may land on is decided here and only here, so a
11711216 // front-end never has to make the same call twice: a file with no
@@ -1478,13 +1523,20 @@ impl PlaybackSession {
14781523 // changed a band restarts the workers with the new curve already in
14791524 // them, and no live channel has to reach into a running one.
14801525 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);
14811532 // Each source on the stream it was placed with: what plays is what
14821533 // the library row said, and what an export copies (`export::run`).
14831534 let sources = self.project.audio_sources();
1484- audio_running = match AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs) {
1485- Ok(Some((_, rx))) => audio.spawn_feeder(rx),
1486- _ => false,
1487- };
1535+ audio_running =
1536+ match AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds) {
1537+ Ok(Some((_, rx))) => audio.spawn_feeder(rx),
1538+ _ => false,
1539+ };
14881540 if !audio_running {
14891541 // Nothing will ever be fed again; let `tick` fall to wall time
14901542 // 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;
6868 use crate::eq::EqParams;
6969 use crate::scale::FitPolicy;
7070
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+
71181 /// A half-open `[in_frame, out_frame)` range of frames of source
72182 /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
73183 /// Never empty.
@@ -103,17 +213,37 @@ pub struct Clip {
103213 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
104214 /// where the aspect does not agree.
105215 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,
106226 }
107227
108228 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.
110232 pub fn len(&self) -> u32 {
111233 self.out_frame - self.in_frame
112234 }
113235
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+
114244 /// One past the last timeline frame it covers.
115245 pub fn end(&self) -> u32 {
116- self.start + self.len()
246+ self.start + self.frames()
117247 }
118248 }
119249
@@ -235,6 +365,12 @@ pub struct Span {
235365 /// `(source index, first source frame)`, or `None` for a gap -- which the
236366 /// engine renders as black frames and as silence.
237367 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,
238374 }
239375
240376 impl Span {
@@ -242,6 +378,30 @@ impl Span {
242378 pub fn end(&self) -> u32 {
243379 self.start + self.len
244380 }
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,
245405 }
246406
247407 /// What a save writes and a load takes back: the sources, every lane in
@@ -290,6 +450,7 @@ impl Project {
290450 eq: None,
291451 color: None,
292452 fit: FitPolicy::default(),
453+ speed: Speed::NORMAL,
293454 };
294455 Self {
295456 // A file is opened on its first audio stream: nothing has picked
@@ -358,7 +519,7 @@ impl Project {
358519 )
359520 .into());
360521 }
361- if c.start.checked_add(c.len()).is_none() {
522+ if c.start.checked_add(c.frames()).is_none() {
362523 return Err(format!(
363524 "{name} clip at {} runs past the last frame there is",
364525 c.start
@@ -517,6 +678,7 @@ impl Project {
517678 eq: None,
518679 color: None,
519680 fit: FitPolicy::default(),
681+ speed: Speed::NORMAL,
520682 };
521683 for data in &mut self.lanes {
522684 data.clips.push(clip);
@@ -758,6 +920,77 @@ impl Project {
758920 true
759921 }
760922
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+
761994 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
762995 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
763996 /// every clip starts at anyway.
@@ -796,7 +1029,12 @@ impl Project {
7961029 }
7971030
7981031 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()
8001038 }
8011039
8021040 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
@@ -805,10 +1043,7 @@ impl Project {
8051043 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
8061044 let clips = self.lane(lane);
8071045 let idx = at(clips, timeline_frame)?;
808- Some((
809- idx,
810- clips[idx].in_frame + (timeline_frame - clips[idx].start),
811- ))
1046+ Some((idx, source_frame(&clips[idx], timeline_frame)))
8121047 }
8131048
8141049 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
@@ -831,13 +1066,12 @@ impl Project {
8311066 Some(idx) => Span {
8321067 start: timeline_frame,
8331068 len: clips[idx].end() - timeline_frame,
834- from: Some((
835- clips[idx].source,
836- clips[idx].in_frame + (timeline_frame - clips[idx].start),
837- )),
1069+ from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
1070+ speed: clips[idx].speed,
8381071 },
8391072 None => Span {
8401073 start: timeline_frame,
1074+ speed: Speed::NORMAL,
8411075 // The next placement, or the end of the timeline: a gap is
8421076 // bounded by what comes after it, never by its own bookkeeping.
8431077 len: clips
@@ -892,20 +1126,18 @@ impl Project {
8921126 let winner = video
8931127 .iter()
8941128 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
895- let (from, until) = match winner {
1129+ let (from, speed, until) = match winner {
8961130 Some(i) => {
8971131 let clips = self.lane(video[i]);
8981132 let idx = at(clips, timeline_frame).expect("just found above");
8991133 (
900- Some((
901- clips[idx].source,
902- clips[idx].in_frame + (timeline_frame - clips[idx].start),
903- )),
1134+ Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
1135+ clips[idx].speed,
9041136 clips[idx].end(),
9051137 )
9061138 }
9071139 // Nothing covers it: black until something above the floor starts.
908- None => (None, total),
1140+ None => (None, Speed::NORMAL, total),
9091141 };
9101142 let takeover = video[winner.map_or(0, |i| i + 1)..]
9111143 .iter()
@@ -916,6 +1148,7 @@ impl Project {
9161148 start: timeline_frame,
9171149 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
9181150 from,
1151+ speed,
9191152 })
9201153 }
9211154
@@ -1012,7 +1245,11 @@ impl Project {
10121245 continue;
10131246 };
10141247 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");
10161253 tail.start = timeline_frame;
10171254 tail.link = right;
10181255 data.clips[idx].out_frame = tail.in_frame;
@@ -1295,12 +1532,19 @@ impl Project {
12951532 let c = &mut self.lanes[l].clips[i];
12961533 match edge {
12971534 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);
12981540 // Non-negative by `lo`, which is what keeps the in-point on
12991541 // 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;
13011543 c.start = to;
13021544 }
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),
13041548 }
13051549 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
13061550 }
@@ -1325,27 +1569,32 @@ impl Project {
13251569 let c = clips[i];
13261570 let (member_lo, member_hi) = match edge {
13271571 Edge::Start => (
1328- // Back to the source's own first frame, and never over the
1329- // clip in front of it. Saturating because a clip may hold
1330- // *more* head than the timeline has room for -- a ripple
1331- // delete slides a clip back to frame 0 with its in-point
1332- // wherever the cut left it -- and frame 0 is the other wall.
1572+ // Back to the source's own first frame -- as many *timeline*
1573+ // frames as that head is worth at the clip's rate, which at
1574+ // real time is the head itself -- and never over the clip in
1575+ // front of it. Saturating because a clip may hold *more*
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.
13331579 c.start
1334- .saturating_sub(c.in_frame)
1580+ .saturating_sub(c.speed.timeline_at(c.in_frame))
13351581 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
13361582 c.end() - 1,
13371583 ),
13381584 Edge::End => (
13391585 c.start + 1,
1340- // Out to whatever is left of the source, and never over the
1341- // clip behind it.
1586+ // Out to whatever is left of the source -- again in timeline
1587+ // frames, at this clip's rate -- and never over the clip
1588+ // behind it.
13421589 c.start
13431590 .saturating_add(
1344- source_frames
1345- .get(c.source)
1346- .copied()
1347- .unwrap_or(c.out_frame)
1348- .saturating_sub(c.in_frame),
1591+ c.speed.timeline_at(
1592+ source_frames
1593+ .get(c.source)
1594+ .copied()
1595+ .unwrap_or(c.out_frame)
1596+ .saturating_sub(c.in_frame),
1597+ ),
13491598 )
13501599 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
13511600 ),
@@ -1415,7 +1664,9 @@ impl Project {
14151664 // that clip -- and a save the engine's own `open_project` then refuses.
14161665 let picture_only = crate::is_image(&source.path);
14171666 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();
14191670 // Room for it: `open_room` adds `len` to every start from `at` on, and a
14201671 // hand-written file may hold a clip that ends at the very last frame
14211672 // (`edith::check` permits `start + len == u32::MAX`). Refused here
@@ -1430,6 +1681,19 @@ impl Project {
14301681 {
14311682 return false;
14321683 }
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+ }
14331697 self.snapshot();
14341698 let clip = Clip {
14351699 start: at,
@@ -1450,7 +1714,7 @@ impl Project {
14501714 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
14511715 .collect();
14521716 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);
14541718 if takes.contains(&i) {
14551719 let idx = data.clips.partition_point(|c| c.start < at);
14561720 data.clips.insert(idx, clip);
@@ -1515,7 +1779,7 @@ impl Project {
15151779 let Some(clip) = self.lane(lane).get(idx).copied() else {
15161780 return false;
15171781 };
1518- self.ripple_delete(clip.start, clip.len())
1782+ self.ripple_delete(clip.start, clip.frames())
15191783 }
15201784
15211785 /// Restore every lane from before the last successful edit -- the clips and
@@ -1555,11 +1819,13 @@ impl Project {
15551819 .iter()
15561820 .map(|span| match span.from {
15571821 // 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`]).
15591825 Some((source, in_frame)) => (
15601826 Some(source),
15611827 f64::from(in_frame) / fps,
1562- f64::from(in_frame + span.len) / fps,
1828+ f64::from(in_frame + span.source_len()) / fps,
15631829 ),
15641830 // A gap has no file, so all it can say is how long it is.
15651831 None => (None, 0.0, f64::from(span.len) / fps),
@@ -1607,6 +1873,52 @@ impl Project {
16071873 }
16081874 }
16091875
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+
16101922 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
16111923 /// segments plays through: the same lanes in the same order, one entry per
16121924 /// segment, `None` where the segment is a gap or its clip plays flat.
@@ -1705,6 +2017,16 @@ fn handles(lanes: &[LaneData]) -> Vec<Lane> {
17052017 .collect()
17062018 }
17072019
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+
17082030 /// Index of the clip covering `frame`, or `None` for a gap or past the end.
17092031 /// Binary search: the sorted-disjoint invariant is what makes it legal.
17102032 fn at(clips: &[Clip], frame: u32) -> Option<usize> {
@@ -1716,7 +2038,20 @@ fn at(clips: &[Clip], frame: u32) -> Option<usize> {
17162038 /// there would cut in two. A placement's own first frame is not inside it.
17172039 fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
17182040 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)
17202055 }
17212056
17222057 /// 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> {
17242059 fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
17252060 let idx = clips.iter().position(|c| c.end() == frame)?;
17262061 let next = clips.get(idx + 1)?;
2062+ let joined = clips[idx].len() + next.len();
17272063 (next.start == frame
17282064 && next.source == clips[idx].source
1729- && next.in_frame == clips[idx].out_frame)
1730- .then_some(idx)
2065+ && next.in_frame == clips[idx].out_frame
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)
17312072 }
17322073
17332074 /// 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) {
18242165 out.push(c);
18252166 continue;
18262167 }
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.
18282172 if c.start < start {
18292173 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()),
18312175 link: None,
18322176 ..c
18332177 });
18342178 }
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.
18362182 if c.end() > end {
18372183 out.push(Clip {
18382184 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()),
18402186 link: None,
18412187 ..c
18422188 });
@@ -1852,7 +2198,11 @@ fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
18522198 fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
18532199 if let Some(idx) = splittable(clips, at) {
18542200 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");
18562206 tail.start = at;
18572207 tail.link = None;
18582208 clips[idx].out_frame = tail.in_frame;
@@ -1892,6 +2242,7 @@ mod tests {
18922242 eq: None,
18932243 color: None,
18942244 fit: FitPolicy::default(),
2245+ speed: Speed::NORMAL,
18952246 }
18962247 }
18972248
@@ -2177,7 +2528,8 @@ mod tests {
21772528 Some(Span {
21782529 start: 6,
21792530 len: 3,
2180- from: Some((0, 6))
2531+ from: Some((0, 6)),
2532+ speed: Speed::NORMAL
21812533 })
21822534 );
21832535 assert_eq!(p.span_at(Lane::V1, 9), None);
@@ -2211,6 +2563,7 @@ mod tests {
22112563 eq: None,
22122564 color: None,
22132565 fit: FitPolicy::Fit,
2566+ speed: Speed::NORMAL,
22142567 };
22152568
22162569 #[test]
@@ -2398,7 +2751,8 @@ mod tests {
23982751 Some(Span {
23992752 start: 3,
24002753 len: 2,
2401- from: None
2754+ from: None,
2755+ speed: Speed::NORMAL
24022756 })
24032757 );
24042758 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
@@ -2416,7 +2770,8 @@ mod tests {
24162770 Some(Span {
24172771 start: 5,
24182772 len: 4,
2419- from: None
2773+ from: None,
2774+ speed: Speed::NORMAL
24202775 }),
24212776 "the audio lane holds silence to the end of the picture"
24222777 );
@@ -2507,7 +2862,8 @@ mod tests {
25072862 Some(Span {
25082863 start: 9,
25092864 len: 11,
2510- from: None
2865+ from: None,
2866+ speed: Speed::NORMAL
25112867 })
25122868 );
25132869 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
@@ -3398,6 +3754,7 @@ mod tests {
33983754 vec![Clip {
33993755 color: Some(i),
34003756 fit: FitPolicy::default(),
3757+ speed: Speed::NORMAL,
34013758 ..video[0]
34023759 }]
34033760 };
@@ -3459,6 +3816,7 @@ mod tests {
34593816 eq: None,
34603817 color: None,
34613818 fit: FitPolicy::default(),
3819+ speed: Speed::NORMAL,
34623820 };
34633821
34643822 // The door: named errors, one per cause.
@@ -3559,6 +3917,94 @@ mod tests {
35593917 );
35603918 }
35613919
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+
35624008 /// The same claim, swept: random op sequences off the public surface, the
35634009 /// project reloaded after every one of them. A failure prints its seed, and
35644010 /// the seed replays the whole sequence.
@@ -3584,7 +4030,7 @@ mod tests {
35844030 .unwrap_or(&clip(0, 0, 5, 0));
35854031 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
35864032 let idx = next(4) as usize;
3587- let _ = match next(13) {
4033+ let _ = match next(14) {
35884034 0 => p.split(frame),
35894035 1 => p.regroup(frame),
35904036 2 => p.lift(lane, idx),
@@ -3602,6 +4048,13 @@ mod tests {
36024048 // reason: it rides on the clip and its orphans must go.
36034049 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
36044050 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(),
36054058 _ => p.append_clip(0, 1 + next(9)),
36064059 };
36074060 reloads(&p, &format!("seed {seed}, step {step}"));
@@ -3711,7 +4164,8 @@ mod tests {
37114164 Some(Span {
37124165 start: 0,
37134166 len: 4,
3714- from: None
4167+ from: None,
4168+ speed: Speed::NORMAL
37154169 })
37164170 );
37174171 // Every lane still covers the whole timeline, gaps included.
@@ -3807,6 +4261,7 @@ mod tests {
38074261 eq: None,
38084262 color: None,
38094263 fit: FitPolicy::default(),
4264+ speed: Speed::NORMAL,
38104265 };
38114266 let lanes = vec![
38124267 LaneData {
@@ -3841,6 +4296,7 @@ mod tests {
38414296 eq: None,
38424297 color: None,
38434298 fit: FitPolicy::default(),
4299+ speed: Speed::NORMAL,
38444300 };
38454301 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
38464302 let kinds = [
@@ -3944,9 +4400,15 @@ mod tests {
39444400 .unwrap_or(&clip(0, 0, 5, 0));
39454401 let lane = lanes[next(3) as usize];
39464402 let idx = next(4) as usize;
3947- let _ = match next(12) {
4403+ let _ = match next(13) {
39484404 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
39494405 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(),
39504412 0 => p.split(frame),
39514413 1 => p.regroup(frame),
39524414 2 => p.lift(lane, idx),
@@ -3991,17 +4453,20 @@ mod tests {
39914453 Span {
39924454 start: 0,
39934455 len: 10,
3994- from: Some((0, 0))
4456+ from: Some((0, 0)),
4457+ speed: Speed::NORMAL
39954458 },
39964459 Span {
39974460 start: 10,
39984461 len: 10,
3999- from: Some((1, 5))
4462+ from: Some((1, 5)),
4463+ speed: Speed::NORMAL
40004464 },
40014465 Span {
40024466 start: 20,
40034467 len: 10,
4004- from: Some((0, 20))
4468+ from: Some((0, 20)),
4469+ speed: Speed::NORMAL
40054470 },
40064471 ],
40074472 "V2 takes over for its own span and hands V1 back"
@@ -4012,7 +4477,8 @@ mod tests {
40124477 Some(Span {
40134478 start: 15,
40144479 len: 5,
4015- from: Some((1, 10))
4480+ from: Some((1, 10)),
4481+ speed: Speed::NORMAL
40164482 })
40174483 );
40184484 assert_eq!(p.composite_span_at(30), None, "past the end");
@@ -4032,22 +4498,26 @@ mod tests {
40324498 Span {
40334499 start: 0,
40344500 len: 5,
4035- from: Some((0, 0))
4501+ from: Some((0, 0)),
4502+ speed: Speed::NORMAL
40364503 },
40374504 Span {
40384505 start: 5,
40394506 len: 5,
4040- from: None
4507+ from: None,
4508+ speed: Speed::NORMAL
40414509 },
40424510 Span {
40434511 start: 10,
40444512 len: 10,
4045- from: Some((1, 0))
4513+ from: Some((1, 0)),
4514+ speed: Speed::NORMAL
40464515 },
40474516 Span {
40484517 start: 20,
40494518 len: 10,
4050- from: None
4519+ from: None,
4520+ speed: Speed::NORMAL
40514521 },
40524522 ]
40534523 );
crates/engine/tests/audio_export.rsmodified+4 -2
@@ -15,8 +15,7 @@ use std::path::{Path, PathBuf};
1515 use std::time::{Duration, Instant};
1616
1717 use engine::export::{ExportSettings, Format};
18-use engine::project::LaneKind;
19-use engine::project::Source;
18+use engine::project::{LaneKind, Source, Speed};
2019 use engine::scale::FitPolicy;
2120 use engine::{AudioSession, Clip, ExportHandle, Project};
2221
@@ -68,6 +67,7 @@ fn mixed_project() -> Project {
6867 eq: None,
6968 color: None,
7069 fit: FitPolicy::default(),
70+ speed: Speed::NORMAL,
7171 };
7272 Project::from_parts(
7373 vec![
@@ -89,6 +89,7 @@ fn mixed_project() -> Project {
8989 eq: None,
9090 color: None,
9191 fit: FitPolicy::default(),
92+ speed: Speed::NORMAL,
9293 }],
9394 ),
9495 (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]),
@@ -325,6 +326,7 @@ fn a_51_ac3_source_round_trips_through_a_wav() {
325326 eq: None,
326327 color: None,
327328 fit: FitPolicy::default(),
329+ speed: Speed::NORMAL,
328330 }],
329331 )],
330332 Vec::new(),
crates/engine/tests/eq_audio.rsmodified+2 -1
@@ -23,7 +23,7 @@ use std::time::{Duration, Instant};
2323
2424 use engine::eq::{Band, BandKind, EqParams};
2525 use engine::export::{ExportSettings, Format};
26-use engine::project::{Lane, LaneKind, Source};
26+use engine::project::{Lane, LaneKind, Source, Speed};
2727 use engine::scale::FitPolicy;
2828 use engine::{AudioSession, Clip, ExportHandle, Project};
2929
@@ -61,6 +61,7 @@ fn clip(start: u32, source: usize, frames: u32) -> Clip {
6161 eq: None,
6262 color: None,
6363 fit: FitPolicy::default(),
64+ speed: Speed::NORMAL,
6465 }
6566 }
6667
crates/engine/tests/export.rsmodified+3 -2
@@ -22,8 +22,7 @@ use std::time::{Duration, Instant};
2222 use engine::export::ExportSettings;
2323 use engine::hw::HwEncoder;
2424 use engine::mux::{Mp4Muxer, VideoParams, parameter_sets};
25-use engine::project::Lane;
26-use engine::project::Source;
25+use engine::project::{Lane, Source, Speed};
2726 use engine::scale::FitPolicy;
2827 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
2928
@@ -195,6 +194,7 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() {
195194 eq: None,
196195 color: None,
197196 fit: FitPolicy::default(),
197+ speed: Speed::NORMAL,
198198 };
199199 let clips = vec![clip(0, 0), clip(1, 10)];
200200 let project = Project::from_parts(
@@ -275,6 +275,7 @@ fn exports_the_audio_stream_the_timeline_plays() {
275275 eq: None,
276276 color: None,
277277 fit: FitPolicy::default(),
278+ speed: Speed::NORMAL,
278279 };
279280 // Stream 1 is the 22.05 kHz mono French track; stream 0 is 44.1 kHz
280281 // 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;
1414 use std::time::{Duration, Instant};
1515
1616 use engine::export::{ExportSettings, Format};
17-use engine::project::{Clip, LaneKind, Source};
17+use engine::project::{Clip, LaneKind, Source, Speed};
1818 use engine::scale::FitPolicy;
1919 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
2020
@@ -239,6 +239,7 @@ fn the_mp4_copy_follows_the_lane_that_holds_the_sound() {
239239 eq: None,
240240 color: None,
241241 fit: FitPolicy::default(),
242+ speed: Speed::NORMAL,
242243 };
243244 let project = Project::from_parts(
244245 vec![Source::new(&source, 0)],
@@ -299,6 +300,7 @@ fn two_audio_lanes_are_summed() {
299300 eq: None,
300301 color: None,
301302 fit: FitPolicy::default(),
303+ speed: Speed::NORMAL,
302304 };
303305 let a2 = project.add_lane(LaneKind::Audio);
304306 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() {
209209 let v2 = dir.join("new.edith");
210210 loaded.save_project(&v2).expect("save");
211211 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}");
213213 assert!(
214214 text.contains("\nresolution 1280 720\n"),
215215 "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() {
297297 loaded.save_project(&again).expect("save");
298298 assert_eq!(
299299 std::fs::read_to_string(&again).expect("read back"),
300- "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\
301- video 1 0 0 30 0 3 - - fit\naudio 1\n\
302- video 2 40 0 20 0 - - - fit\naudio 2 0 0 30 0 3 - - fit\n",
300+ "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\
301+ video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\
302+ video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n",
303303 "a four-lane project is written as it was read, three versions on"
304304 );
305305 }
@@ -327,11 +327,11 @@ fn a_version_5_project_carries_per_clip_equalizers() {
327327 loaded.save_project(&again).expect("save");
328328 assert_eq!(
329329 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\
331331 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
332332 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\
334- audio 1 0 0 30 0 - 0 - fit\naudio 1 30 30 60 0 - - - 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 1000\naudio 1 30 30 60 0 - - - fit 1000\n",
335335 "the equalizer table and every clip's index survive a round trip"
336336 );
337337 }
@@ -362,12 +362,12 @@ fn a_version_6_project_carries_per_clip_colours() {
362362 loaded.save_project(&again).expect("save");
363363 assert_eq!(
364364 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\
366366 eq 80.0:-3.0:0.707:ls\n\
367367 color 0.1:1.2:0.9:-0.3\n\
368368 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\
370- audio 1 0 0 30 0 - - 0 fit\naudio 1 30 30 60 0 - - - 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 1000\naudio 1 30 30 60 0 - - - fit 1000\n",
371371 "the colour table and every clip's index survive a round trip"
372372 );
373373 // 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() {
412412 loaded.save_project(&again).expect("save");
413413 assert_eq!(
414414 std::fs::read_to_string(&again).expect("read back"),
415- text,
416- "a v7 project is written exactly as it was read"
415+ "edith 8\nplayhead 0\nresolution 960 720\nsource 0 test_av.mp4\n\
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"
417420 );
418421
419422 // The refusals the new grammar adds, each naming its line.
@@ -667,7 +670,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() {
667670
668671 for (text, want) in [
669672 (
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",
671674 "line 1",
672675 ),
673676 // 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 \
113113 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
114114 -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
115115 -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
116133 # Mismatch fixture: different resolution and no audio track at all, so import
117134 # has something concrete to refuse.
118135 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \