From f8effe8b7f334412b7f18e669134069187c7ce4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 10 Aug 2026 20:46:39 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(timeline):=20clips=20play=20at?= =?UTF-8?q?=20a=20speed=20of=20their=20own?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- crates/app/src/keymap.rs | 24 +- crates/app/src/main.rs | 422 +++++++++++++++++++- crates/engine/src/audio.rs | 238 ++++++++++- crates/engine/src/edith.rs | 204 +++++++--- crates/engine/src/export.rs | 46 ++- crates/engine/src/lib.rs | 2 +- crates/engine/src/playback.rs | 78 +++- crates/engine/src/project.rs | 594 +++++++++++++++++++++++++--- crates/engine/tests/audio_export.rs | 6 +- crates/engine/tests/eq_audio.rs | 3 +- crates/engine/tests/export.rs | 5 +- crates/engine/tests/lanes.rs | 4 +- crates/engine/tests/saveload.rs | 29 +- crates/engine/tests/speed.rs | 332 ++++++++++++++++ scripts/gen_fixtures.sh | 17 + 15 files changed, 1839 insertions(+), 165 deletions(-) create mode 100644 crates/engine/tests/speed.rs diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index ebe7f8b..672359a 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -70,13 +70,14 @@ pub enum ActionId { VolumeUp, VolumeDown, Equalizer, + Speed, CancelExport, } impl ActionId { /// Display order everywhere -- the editor lists them in it and /// [`Keymap::defaults`] binds them in it. - pub const ALL: [ActionId; 31] = [ + pub const ALL: [ActionId; 32] = [ ActionId::Play, ActionId::StepBack, ActionId::StepForward, @@ -107,6 +108,7 @@ impl ActionId { ActionId::VolumeUp, ActionId::VolumeDown, ActionId::Equalizer, + ActionId::Speed, ActionId::CancelExport, ]; @@ -143,6 +145,7 @@ impl ActionId { ActionId::VolumeUp => "Volume up", ActionId::VolumeDown => "Volume down", ActionId::Equalizer => "Equalizer", + ActionId::Speed => "Speed (tape)…", ActionId::CancelExport => "Cancel export", } } @@ -181,6 +184,7 @@ impl ActionId { ActionId::VolumeUp => "volume-up", ActionId::VolumeDown => "volume-down", ActionId::Equalizer => "equalizer", + ActionId::Speed => "speed", ActionId::CancelExport => "cancel-export", } } @@ -209,7 +213,11 @@ impl ActionId { | ActionId::Delete | ActionId::Lift | ActionId::Color - | ActionId::Fit => Category::Clips, + | ActionId::Fit + // A rate is the clip's, not the sound's: it re-times the picture + // and the sound together, and the card opens on whichever half was + // clicked. + | ActionId::Speed => Category::Clips, // The project's own picture size is not a clip's business, and not // a file operation either: it is what the viewer is looking at. ActionId::Resolution => Category::View, @@ -507,6 +515,11 @@ impl Keymap { // The one free letter that says the word: "e" is already the // export and an equalizer is the q in nobody else's way. b(ActionId::Equalizer, "q", false), + // "s" is the save's ctrl chord, so the speed card takes the + // unshifted letter beside it: "j" was free, sits under the + // right hand with the other clip keys (k grades, l lifts), and + // is not next to anything that deletes. + b(ActionId::Speed, "j", false), b(ActionId::CancelExport, "escape", false), ], } @@ -769,7 +782,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 33); + assert_eq!(k.entries().len(), 34); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); // The seek keys: bare arrows a frame, ctrl arrows a second, and the two // ends of the timeline. @@ -814,7 +827,8 @@ mod tests { // The modifier is half the chord: ctrl+e is not e. assert_eq!(k.lookup("e", true), None); assert_eq!(k.lookup("space", true), None); - assert_eq!(k.lookup("j", false), None); + assert_eq!(k.lookup("j", false), Some(ActionId::Speed)); + assert_eq!(k.lookup("j", true), None); // Nothing is bound twice, or lookup's first match would be a coin toss. for (i, a) in k.entries().iter().enumerate() { assert!( @@ -996,7 +1010,7 @@ mod tests { assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); // The label is the editor's column, and never the file's word for it. assert_eq!(ActionId::CancelExport.label(), "Cancel export"); - assert_eq!(ActionId::ALL.len(), 31); + assert_eq!(ActionId::ALL.len(), 32); } #[test] diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index a45c70b..0e3ecad 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -13,7 +13,7 @@ use engine::audio::StreamInfo; use engine::color::ColorParams; use engine::eq::{Band, BandKind, EqParams}; use engine::export::{ExportSettings, Format}; -use engine::project::{Edge, Lane, LaneKind, Source}; +use engine::project::{Edge, Lane, LaneKind, Source, Speed}; use engine::scale::FitPolicy; use engine::{Clip, ExportHandle, Frame, PlaybackSession}; use gpui::{ @@ -311,7 +311,7 @@ impl RowItem { /// action a stroke already reaches -- the menu is a second way *to* the actions /// and never a second version of them -- so both the label and the hint come /// out of the keymap registry and the two can never disagree. -const MENU_ITEMS: [ActionId; 10] = [ +const MENU_ITEMS: [ActionId; 11] = [ ActionId::Cut, ActionId::Delete, ActionId::Lift, @@ -319,6 +319,7 @@ const MENU_ITEMS: [ActionId; 10] = [ ActionId::Detach, ActionId::Group, ActionId::Equalizer, + ActionId::Speed, ActionId::Color, ActionId::Fit, ActionId::ToggleMute, @@ -339,6 +340,23 @@ const EQ_GAIN_LIMIT: f32 = 12.; /// single band. const EQ_STEP: f32 = 1.; +/// A twentieth of real time per keystroke, in the thousandths a [`Speed`] is +/// held in: fine enough to creep up on a rate, coarse enough that the whole +/// range is eighty presses and not eight hundred -- and it divides 1000, so +/// stepping from anywhere lands on exactly 1.00x on the way past. +const SPEED_STEP: i32 = 50; + +/// The rates the card's buttons offer, so the ones people actually name are one +/// click and not a drag. Real time is among them: it is the reset. +const SPEED_PRESETS: [u16; 6] = [250, 500, 1000, 1500, 2000, 4000]; + +/// A rate from a number of thousandths that may have run off either end -- what +/// a keystroke and a drag both produce. Clamped, not refused: a hand pushing +/// past the limit means "as far as it goes", exactly as a trim does. +fn speed_at(permille: i32) -> Speed { + Speed::from_permille(permille.clamp(0, i32::from(u16::MAX)) as u16) +} + /// The graph's frequency axis: the range an ear works in, and the range every /// band a file can carry sits inside. Log-spaced, so an octave is an octave /// wherever it falls. @@ -542,6 +560,17 @@ struct Player { /// there. `None` when it is closed, which is the only place that state /// lives: the grade itself is the project's. color_open: Option<(Lane, usize)>, + /// The speed card is up on this clip -- the lane it is on and its index + /// there, exactly as the colour card's handle is. `None` when it is closed; + /// the rate itself is the project's, so there is nothing else to hold. + speed_open: Option<(Lane, usize)>, + /// The speed bar's box, recorded at prepaint: a mouse listener is handed the + /// window position only, so this is what a press and a drag are read against + /// ([`frac_along`]). + speed_bar: Rc>>, + /// The bar is being dragged. On the root like the colour card's, for the + /// same reason: the pointer leaves a 4 px bar on the first move. + speed_dragging: bool, /// Which of the card's four sliders the arrow keys and a drag move. The /// card's own focus, since nothing in it takes gpui's (ledger:182). color_band: usize, @@ -708,6 +737,7 @@ impl Player { ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx), ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx), ActionId::Equalizer => self.open_eq(cx), + ActionId::Speed => self.open_speed(cx), // Nothing to cancel while nothing is exporting; the export guard in // the key handler is what answers this one while there is. ActionId::CancelExport => {} @@ -953,6 +983,108 @@ impl Player { self.write_color(params, !first, cx); } + /// Opens the speed card on the clip whose rate is to change: the selected + /// one, or -- with nothing selected -- the clip the picture is coming from, + /// which is what a person means by "this shot". Either half of a take will + /// do: a rate applies to the whole group, so opening it on the sound and + /// opening it on the picture are the same card. + fn open_speed(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let Some(session) = &self.session else { + self.notice = Some("no timeline to re-time — open a file first".into()); + cx.notify(); + return; + }; + match self + .selected + .or_else(|| session.video_clip_at(session.now())) + { + Some(clip) => { + self.speed_open = Some(clip); + self.speed_dragging = false; + // One card at a time, the rule the other three follow. + self.keys_open = false; + self.export_open = false; + self.eq_open = None; + self.color_open = None; + self.context_menu = None; + } + None => self.notice = Some("no clip under the playhead to re-time".into()), + } + cx.notify(); + } + + /// What the card's clip plays at right now -- real time for one nobody has + /// touched, which is where the bar starts. + fn card_speed(&self) -> Speed { + self.speed_open + .zip(self.session.as_ref()) + .map_or(Speed::NORMAL, |((lane, idx), session)| { + session.speed_of(lane, idx) + }) + } + + /// Writes a rate at the card's clip and its whole group -- one undo step for + /// the lot ([`engine::PlaybackSession::set_speed`]). The engine reseeks, so + /// the picture runs at the new rate and the sound is resampled from the next + /// chunk on; a refusal (a slower clip would run into its neighbour) comes + /// back in the engine's own words and *names* the clip in the way, because + /// "it did not fit" is not something a person can go and fix. + fn set_speed(&mut self, speed: Speed, cx: &mut Context) { + self.write_speed(speed, false, cx); + } + + /// Both writes: `live` is the one that takes no undo step, which is what + /// every sample *inside* a drag goes through -- so a drag from 1.00x to + /// 2.00x is one undo press and lands back where the hand picked it up, and + /// the whole linked group comes back with it. + fn write_speed(&mut self, speed: Speed, live: bool, cx: &mut Context) { + let Some((lane, idx)) = self.speed_open else { + return; + }; + let Some(session) = &mut self.session else { + return; + }; + if speed != session.speed_of(lane, idx) { + let wrote = match live { + true => session.set_speed_live(lane, idx, speed), + false => session.set_speed(lane, idx, speed), + }; + match wrote { + Ok(()) => self.reset_after_reseek(), + Err(e) => self.notice = Some(e.to_string().into()), + } + } + cx.notify(); + } + + /// One [`SPEED_STEP`] per keystroke, clamped to what a [`Speed`] can hold. + fn nudge_speed(&mut self, steps: i32, cx: &mut Context) { + let at = i32::from(self.card_speed().permille()) + steps * SPEED_STEP; + self.set_speed(speed_at(at), cx); + } + + /// Where the pointer sits along the bar, as a rate: the left end is + /// [`Speed::MIN`] and the right end [`Speed::MAX`], on the same + /// [`SPEED_STEP`] grid the keys move on -- so a drag can land on exactly + /// 1.00x and the same drag twice is one entry, not forty. + /// `first` is the press: it takes the undo step the whole gesture rolls back + /// to, and every sample after it is live -- the colour card's rule, for the + /// colour card's reason. + fn drag_speed(&mut self, x: Pixels, first: bool, cx: &mut Context) { + let along = frac_along(x, self.speed_bar.get()); + let lo = f32::from(Speed::MIN.permille()); + let hi = f32::from(Speed::MAX.permille()); + let raw = lo + along * (hi - lo); + // Snapped to the grid, then to real time itself when it is within half a + // step of it: 1.00x is the one value a hand must be able to hit, and + // nothing about the bar's geometry guarantees a pixel lands on it. + let stepped = (raw / SPEED_STEP as f32).round() as i32 * SPEED_STEP; + self.write_speed(speed_at(stepped), !first, cx); + } + /// Whether a card owns the window. While one does the timeline under it is /// out of reach, so a right-click there opens no menu -- the same rule the /// key handler and the drop target already follow. @@ -961,6 +1093,7 @@ impl Player { || self.export_open || self.eq_open.is_some() || self.color_open.is_some() + || self.speed_open.is_some() || self.exporting().is_some() } @@ -2344,6 +2477,29 @@ impl Render for Player { cx.notify(); return; } + // The speed card, the same way again: its arrows move the rate + // and `r` puts it back to real time, and neither means anything + // outside the card -- so neither is a binding (see `FIXED`, + // where the keys menu still lists them). + if this.speed_open.is_some() { + match color_key(key) { + Some(ColorKey::Close) => { + this.speed_open = None; + this.speed_dragging = false; + } + // The card has one value, so the pair that picks a + // slider on the colour card moves this one by a whole + // preset's worth instead of a step. + Some(ColorKey::Band(step)) => { + this.nudge_speed(if step == 1 { -2 } else { 2 }, cx) + } + Some(ColorKey::Nudge(steps)) => this.nudge_speed(steps as i32, cx), + Some(ColorKey::Reset) => this.set_speed(Speed::NORMAL, cx), + None => {} + } + cx.notify(); + return; + } // A clip menu names an index, and every edit below moves // indices -- so a stroke closes it before it acts. Escape means // that and nothing else, which is the `esc` the keys menu @@ -2426,6 +2582,16 @@ impl Render for Player { } return; } + // The speed bar, the same 4 px and the same live writes: the + // press took the undo step and every sample since is live. + if this.speed_dragging { + if event.pressed_button == Some(MouseButton::Left) { + this.drag_speed(event.position.x, false, cx); + } else { + this.speed_dragging = false; + } + return; + } if !this.scrubbing { return; } @@ -2462,6 +2628,10 @@ impl Render for Player { this.drag_color(event.position.x, false, cx); return; } + if std::mem::take(&mut this.speed_dragging) { + this.drag_speed(event.position.x, false, cx); + return; + } if std::mem::take(&mut this.scrubbing) { this.scrub_to(event.position.x, true, cx); } @@ -2540,6 +2710,7 @@ impl Render for Player { .children(self.export_card(cx)) .children(self.eq_card(cx)) .children(self.color_card(cx)) + .children(self.speed_card(cx)) } } @@ -3834,6 +4005,138 @@ impl Player { ) } + /// The speed card: one bar from a quarter speed to four times it, the rates + /// people name as buttons under it, and the clip's new length in frames -- + /// which is the number a person is actually choosing. Built like the colour + /// card down to the scrim and the bar's own hit height, because it is the + /// same kind of card: one continuous value on one clip, live at the clip as + /// it moves. + /// + /// Honest about what it does: the sound is *resampled*, so the pitch goes up + /// with the rate, which is what the tape in the title means. + fn speed_card(&self, cx: &mut Context) -> Option { + let (lane, idx) = self.speed_open?; + let speed = self.card_speed(); + let session = self.session.as_ref()?; + let clip = session.lane_clips(lane).get(idx).copied()?; + let lo = f32::from(Speed::MIN.permille()); + let hi = f32::from(Speed::MAX.permille()); + let frac = ((f32::from(speed.permille()) - lo) / (hi - lo)).clamp(0., 1.); + let presets: Vec<_> = SPEED_PRESETS + .into_iter() + .map(|permille| { + let at = Speed::from_permille(permille); + div() + .id(("speed-preset", usize::from(permille))) + .flex_1() + .flex() + .h(px(CONTROL_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(match at == speed { + true => SELECTED, + false => CHROME, + })) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.set_speed(at, cx); + })) + .child(format!("{at}")) + }) + .collect(); + Some( + div() + .absolute() + .inset_0() + .flex() + .justify_center() + .items_center() + .bg(rgba(0x101010cc)) + .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .child( + div() + .w(px(COLOR_W)) + .flex() + .flex_col() + .gap(px(6.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(SURFACE)) + .child(div().flex_none().px(px(6.)).child(format!( + "Speed (tape) — {} clip {}", + lane.label(), + idx + 1 + ))) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child( + "drag the bar or ←→ moves it, r is 1.00x — the pitch moves with the rate; esc closes", + ), + ) + .child( + // 4 px to look at and a whole row to hit (WCAG + // 2.5.8), the split the colour sliders and the ruler + // both make. + div() + .id("speed-bar") + .relative() + .w_full() + .h(px(KEYS_ROW_H)) + .flex() + .items_center() + .cursor_pointer() + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + this.speed_dragging = true; + this.drag_speed(event.position.x, true, cx); + }), + ) + .child(bounds_probe(self.speed_bar.clone())) + .child( + div() + .w_full() + .h(px(4.)) + .rounded(px(2.)) + .bg(rgb(CHROME)) + .child( + div() + .h_full() + .w(relative(frac)) + .rounded(px(2.)) + .bg(rgb(ACCENT)), + ), + ), + ) + .child(div().flex().gap(px(4.)).children(presets)) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + // What the choice *is*, in the numbers the + // timeline is measured in: the source range + // never moves, the room it takes does. + .child(format!( + "{speed} — {} source frames over {} on the timeline ({})", + clip.len(), + clip.frames(), + timecode(f64::from(clip.frames()) / self.fps, self.fps) + )), + ), + ), + ) + } + /// The menu a right-click on a library row opens: what can be done with the /// *file* rather than with a clip of it, and a turn-over side saying what /// that file is. Built like [`Player::context_card`] down to the scrim, the @@ -4055,7 +4358,11 @@ impl Player { "Source range", format!("{} – {}", secs(clip.in_frame), secs(clip.out_frame)), ), - ("This clip", secs(clip.len())), + // How long it is *where it sits*, which its rate decides -- and + // the rate itself beside it, because a clip half its source's + // length could be either a trim or a 2x. + ("This clip", secs(clip.frames())), + ("Speed", format!("{} (tape)", clip.speed)), ("Source duration", secs(session.file_frames(&source.path))), ] { rows.push( @@ -4296,9 +4603,12 @@ impl Player { // What a drag on an edge is showing, which is the clip // itself while nothing is being dragged. let clip = &self.trimmed(lane, i, *clip); + // Its *timeline* length, which a speed halves or + // quadruples: the box is as wide as the clip is long + // where it sits, not as long as the source it reads. let (start, len) = ( f64::from(clip.start) / self.fps, - f64::from(clip.len()) / self.fps, + f64::from(clip.frames()) / self.fps, ); let on = marked((lane, i), clip.link, sel, sel_link); // A group with a half in the other lane wears its tint; @@ -4442,6 +4752,25 @@ impl Player { .child(inner), ) })) + // A speeded clip says so on the box, in the corner + // the label does not reach: the box's width alone + // cannot say whether a short clip is a trim or a + // clip at 4x, and that is the difference between a + // cut and a re-time. + .when(!clip.speed.is_normal(), |d| { + d.child( + div() + .absolute() + .top_0() + .right_0() + .px(px(3.)) + .rounded(px(3.)) + .bg(rgb(ACCENT)) + .text_size(px(9.)) + .text_color(rgb(SURFACE)) + .child(format!("{}", clip.speed)), + ) + }) .when_some(label.filter(|_| show_label(bed_w * width)), |d, label| { d.child( div() @@ -4716,8 +5045,19 @@ fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool // A fit policy is a picture setting for the same reason. ActionId::Color | ActionId::Fit => lane.kind == LaneKind::Video, // Splits this clip only from inside it: at either edge there is nothing - // to split off (project.rs `splittable`). - ActionId::Cut => clip.start < playhead && playhead < clip.end(), + // to split off -- and, on a speeded clip, only at a frame its own rate + // can address, which is the same question `splittable` asks. + ActionId::Cut => { + clip.start < playhead + && playhead < clip.end() + && clip + .speed + .split_at(clip.len(), playhead - clip.start) + .is_some() + } + // A rate applies to a clip of either kind and to its whole group, so + // there is no lane it means nothing on -- `_ => true` below is its + // answer, and the engine words the one refusal there is (no room). // Rejoins whatever meets at the playhead, so it can mean something only // at an edge of this clip. Whether those two halves were ever one take // is the engine's question, and it words that refusal itself. @@ -5735,13 +6075,13 @@ mod tests { Format, HEADER_GAP, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, - RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, - WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, color_snap, - envelope, eq_x, eq_y, export_path, export_settings, format_key, format_line, - format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project, - keymap, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit, retarget, - scrub_due, show_label, source_tint, span_partner, start_frac, timecode, unseen_paths, - unseen_sources, whole_take, width_frac, window_title, + RULER_HIT_H, SELECTED, SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, + Speed, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, + cancels_export, color_snap, envelope, eq_x, eq_y, export_path, export_settings, format_key, + format_line, format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier, + is_project, keymap, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit, + retarget, scrub_due, show_label, source_tint, span_partner, speed_at, start_frac, timecode, + unseen_paths, unseen_sources, whole_take, width_frac, window_title, }; use super::{file_name, file_uri, library_rows}; @@ -6028,6 +6368,7 @@ mod tests { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; assert_eq!(clip.end(), 90); // Cut splits from inside only: neither edge has anything to split off. @@ -6942,6 +7283,58 @@ mod tests { assert!(KEYS_ROW_H >= HIT_MIN); } + /// The speed bar is the same round trip -- pixels -> rate -> fill -- with + /// one thing the colour sliders do not have to promise: **exactly 1.00x has + /// to be reachable**, by a hand as well as by the reset. A grid that missed + /// it would leave a clip nobody could put back. + #[test] + fn the_speed_bar_lands_where_it_paints_and_real_time_is_reachable() { + let bar = Bounds { + origin: point(px(180.), px(240.)), + size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)), + }; + let (lo, hi) = ( + f32::from(Speed::MIN.permille()), + f32::from(Speed::MAX.permille()), + ); + // The same arithmetic `Player::drag_speed` runs, which is the one thing + // a test of it can share without re-deriving it. + let at = |x: f32| { + let raw = lo + frac_along(px(x), bar) * (hi - lo); + speed_at((raw / SPEED_STEP as f32).round() as i32 * SPEED_STEP) + }; + assert_eq!(at(180.), Speed::MIN, "the left end is a quarter speed"); + assert_eq!(at(180. + COLOR_BAR_W), Speed::MAX, "the right end is 4x"); + assert_eq!(at(-4000.), Speed::MIN, "off the left clamps"); + assert_eq!(at(9999.), Speed::MAX, "off the right clamps"); + let mut hits_real_time = false; + for step in 0..=240 { + let along = step as f32 / 240.; + let speed = at(180. + along * COLOR_BAR_W); + hits_real_time |= speed == Speed::NORMAL; + assert_eq!( + i32::from(speed.permille()) % SPEED_STEP, + 0, + "{speed} is off the {SPEED_STEP} grid the keys move on" + ); + // What the bar paints from that rate is where the pointer was, to + // within the half step the snap costs. + let painted = (f32::from(speed.permille()) - lo) / (hi - lo); + let slack = SPEED_STEP as f32 / (hi - lo) / 2. + 1e-4; + assert!( + (painted - along).abs() <= slack, + "pressed at {along}, paints at {painted}" + ); + } + assert!(hits_real_time, "a drag can land on exactly 1.00x"); + // ...and every preset the card offers is a rate the bar can also reach. + for permille in SPEED_PRESETS { + assert_eq!(Speed::from_permille(permille).permille(), permille); + assert_eq!(i32::from(permille) % SPEED_STEP, 0); + } + assert!(SPEED_PRESETS.contains(&Speed::NORMAL.permille()), "reset"); + } + /// A colour slider is dragged straight to a value, so where the pointer /// lands and where the bar then paints have to be the same place: this is /// the round trip [`Player::drag_color`] makes, pixels -> value -> fill. @@ -7633,6 +8026,9 @@ fn main() { eq_band: 0, eq_dragging: false, eq_graph: Rc::default(), + speed_open: None, + speed_bar: Rc::default(), + speed_dragging: false, color_open: None, color_band: 0, color_dragging: false, diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 1644894..c81c8a0 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -245,6 +245,28 @@ impl AudioSession { sources: &[(PathBuf, usize)], segs: &[(Option, f64, f64)], eqs: &[Option], + ) -> crate::Result)>> { + Self::open_multi_streams_speed(sources, segs, eqs, &[]) + } + + /// [`open_multi_streams_eq`](Self::open_multi_streams_eq) with a *rate* per + /// segment as well: `speeds[i]` says how fast segment `i` is read and how + /// much timeline it owes ([`crate::project::Stretch`]), `None` for one at + /// real time. [`crate::Project::audio_speeds_from`] is what builds it, beside + /// the very list the segments come from. + /// + /// Resampling happens **per segment**, inside the worker and before the mix, + /// for the equalizer's reasons: two clips at two speeds must not be read + /// into one another, and the interpolator's memory dies with the segment. A + /// list shorter than `segs` (the empty one every plain caller passes) means + /// the rest play at real time, so nothing here can shift a rate onto the + /// wrong clip and a project with no speeds decodes exactly the samples it + /// always did. + pub fn open_multi_streams_speed( + sources: &[(PathBuf, usize)], + segs: &[(Option, f64, f64)], + eqs: &[Option], + speeds: &[Option], ) -> crate::Result)>> { let Some((path, stream)) = sources.first() else { return Ok(None); @@ -330,6 +352,23 @@ impl AudioSession { }) .collect(); + // One resampler per speeded segment, built where the sample rate is + // known: what the timeline owes it is seconds there and frames here. + let speeds: Vec> = segments + .iter() + .enumerate() + .map(|(i, _)| { + speeds.get(i).and_then(Option::as_ref).map(|s| { + Resample::new( + s.step, + (s.timeline_secs * f64::from(meta.sample_rate)) + .round() + .max(0.) as u64, + ) + }) + }) + .collect(); + let (tx, rx) = sync_channel(32); thread::Builder::new() .name("audio-decode".into()) @@ -339,6 +378,7 @@ impl AudioSession { channels: meta.channels as usize, segments, eqs, + speeds, timeline, tx, }) @@ -384,13 +424,37 @@ impl AudioSession { sources: &[(PathBuf, usize)], lanes: &[Vec<(Option, f64, f64)>], eqs: &[Vec>], + ) -> crate::Result)>> { + Self::open_mixed_streams_speed(sources, lanes, eqs, &[]) + } + + /// [`open_mixed_streams_eq`](Self::open_mixed_streams_eq) with + /// [`open_multi_streams_speed`](Self::open_multi_streams_speed)'s per-segment + /// rates, one list per lane -- [`crate::Project::audio_speeds_from`] is what + /// shapes them, off the same walk the segments come from. + /// + /// A resample is each lane's worker's own business and happens **before** + /// the sum, exactly as the filtering does: every lane still hands the mixer + /// as many samples as the timeline says, so the lanes stay sample-aligned by + /// construction and a mix is still an add. + pub fn open_mixed_streams_speed( + sources: &[(PathBuf, usize)], + lanes: &[Vec<(Option, f64, f64)>], + eqs: &[Vec>], + speeds: &[Vec>], ) -> crate::Result)>> { let [first, rest @ ..] = lanes else { return Ok(None); }; if rest.is_empty() { let flat = Vec::new(); - return Self::open_multi_streams_eq(sources, first, eqs.first().unwrap_or(&flat)); + let plain = Vec::new(); + return Self::open_multi_streams_speed( + sources, + first, + eqs.first().unwrap_or(&flat), + speeds.first().unwrap_or(&plain), + ); } let mut meta = None; let mut rxs = Vec::with_capacity(lanes.len()); @@ -398,8 +462,13 @@ impl AudioSession { // Every lane probes the same source 0, so the metas agree by // construction; `None` from any of them is a silent timeline. let flat = Vec::new(); - let Some((lane_meta, rx)) = - Self::open_multi_streams_eq(sources, segs, eqs.get(i).unwrap_or(&flat))? + let plain = Vec::new(); + let Some((lane_meta, rx)) = Self::open_multi_streams_speed( + sources, + segs, + eqs.get(i).unwrap_or(&flat), + speeds.get(i).unwrap_or(&plain), + )? else { return Ok(None); }; @@ -1511,6 +1580,104 @@ impl Segment { } } +/// One speeded segment's resampler: the tape effect, done by reading the +/// decoded samples at a rate other than the one they were written at, so the +/// pitch moves with the speed. Linear interpolation between the two frames a +/// fractional position falls between -- one multiply-add per channel, which is +/// nothing beside the decode that produced them, and enough that a 2x clip is +/// not the aliasing mess plain sample-dropping would give. +/// +/// It lives across the whole segment: `pos` carries the fraction over a packet +/// boundary and `tail` keeps the frame before the buffer, so the interpolation +/// at the seam is the same one it would have been inside a buffer. A segment +/// starts one clean and drops it at the end, which is what makes a seek a reset +/// for free -- exactly as the equalizer's state does. +/// +/// `owed` is what the timeline gives the segment, in frames per channel: +/// resampling resolves to whole samples and a clip's own window resolves to +/// whole *source* frames, so the two miss each other by a sample or two per +/// clip. Truncating and padding to what is owed keeps that from accumulating +/// into audible drift over a timeline of speeded cuts -- the picture's clip +/// boundaries are exact by construction, and this makes the sound's exact too. +struct Resample { + /// Source frames per output frame: the speed itself. + step: f64, + /// Where the next output frame reads, relative to the current buffer's + /// first frame. Negative means it reads across the seam, into `tail`. + pos: f64, + /// The last frame of the buffer before this one, one sample per channel. + tail: Vec, + /// Output frames per channel still to be emitted for this segment. + owed: u64, +} + +impl Resample { + fn new(step: f64, owed: u64) -> Self { + Self { + step, + pos: 0., + tail: Vec::new(), + owed, + } + } + + /// Rewrites `buf` in place as the frames this rate reads out of it. Never + /// more than is owed, so the segment cannot overrun the room the timeline + /// gave it. + fn process(&mut self, buf: &mut Vec, channels: usize) { + let frames = buf.len() / channels; + if frames == 0 || channels == 0 { + return; + } + let mut out: Vec = Vec::with_capacity(buf.len()); + while self.owed > (out.len() / channels) as u64 { + let left = self.pos.floor(); + let right = left as i64 + 1; + if right > frames as i64 - 1 { + break; // the frame it would interpolate towards is not here yet + } + let frac = (self.pos - left) as f32; + let (left, right) = (left as i64, right as usize); + for c in 0..channels { + // Before the buffer means the previous one's last frame; at the + // very first buffer of a segment `pos` is 0, so this cannot be + // asked for an empty tail. + let a = match left < 0 { + true => self.tail.get(c).copied().unwrap_or(0.), + false => buf[left as usize * channels + c], + }; + let b = buf[right * channels + c]; + out.push(a + (b - a) * frac); + } + self.pos += self.step; + } + self.tail.clear(); + self.tail.extend_from_slice(&buf[(frames - 1) * channels..]); + self.pos -= frames as f64; + self.owed -= (out.len() / channels) as u64; + *buf = out; + } + + /// The silence the segment still owes when its source ran out before the + /// timeline did -- a rounding frame or two, or a clip whose file is shorter + /// than the edit says. `false` means the consumer went away. + fn flush(&mut self, channels: usize, timeline: &mut u64, tx: &SyncSender) -> bool { + while self.owed > 0 { + let frames = self.owed.min(u64::from(SAMPLES_PER_PACKET)); + let chunk = AudioChunk { + start_sample: *timeline, + samples: vec![0.0; frames as usize * channels], + }; + if tx.send(chunk).is_err() { + return false; + } + *timeline += frames; + self.owed -= frames; + } + true + } +} + struct Worker { /// Indexed by [`Segment::source`]; only the sources some segment names are /// `Some`, the rest were never opened. @@ -1522,6 +1689,10 @@ struct Worker { /// Beside the segments rather than inside them so the emit path can hold the /// window rules and the filter memory at once without splitting a borrow. eqs: Vec>, + /// One per entry of `segments` again: the rate that segment is read at, or + /// `None` for one at real time -- which is every segment of a project nobody + /// has speeded, and the path that emits the decoder's own samples untouched. + speeds: Vec>, /// `start_sample` of the first chunk. timeline: u64, tx: SyncSender, @@ -1603,8 +1774,11 @@ fn run(mut w: Worker) { // A short list is "flat from here on" (`open_multi_streams_eq`), which this // pads out so the zip below still walks every segment. eqs.resize_with(segments.len(), || None); + let mut speeds = std::mem::take(&mut w.speeds); + // ...and a short rate list is "real time from here on", for the same reason. + speeds.resize_with(segments.len(), || None); - for (seg, eq) in segments.iter().zip(eqs.iter_mut()) { + for ((seg, eq), speed) in segments.iter().zip(eqs.iter_mut()).zip(speeds.iter_mut()) { let Some(source) = seg.source else { // A gap: hand the device real silence rather than nothing at all, // in the same packet-sized chunks decoding produces, so `fed` and @@ -1629,13 +1803,31 @@ fn run(mut w: Worker) { }; let track = match track { Track::Sym(track) => { - if !run_sym(track, seg, eq.as_mut(), channels, &mut timeline, &w.tx) { + if !run_sym( + track, + seg, + eq.as_mut(), + speed, + channels, + &mut timeline, + &w.tx, + ) || !settle(speed, channels, &mut timeline, &w.tx) + { return; // consumer went away } continue; } Track::Ac3(track) => { - if !run_ac3(track, seg, eq.as_mut(), channels, &mut timeline, &w.tx) { + if !run_ac3( + track, + seg, + eq.as_mut(), + speed, + channels, + &mut timeline, + &w.tx, + ) || !settle(speed, channels, &mut timeline, &w.tx) + { return; // consumer went away } continue; @@ -1684,6 +1876,7 @@ fn run(mut w: Worker) { channels, seg, eq.as_mut(), + speed.as_mut(), pos, next, &mut timeline, @@ -1693,6 +1886,24 @@ fn run(mut w: Worker) { } pos = next; } + if !settle(speed, channels, &mut timeline, &w.tx) { + return; // consumer went away + } + } +} + +/// Pays out whatever silence a speeded segment still owes the timeline (see +/// [`Resample::flush`]). Nothing at all at real time, where a segment owes the +/// timeline only the samples it decoded. +fn settle( + speed: &mut Option, + channels: usize, + timeline: &mut u64, + tx: &SyncSender, +) -> bool { + match speed { + Some(speed) => speed.flush(channels, timeline, tx), + None => true, } } @@ -1717,6 +1928,7 @@ fn emit( channels: usize, seg: &Segment, eq: Option<&mut EqState>, + speed: Option<&mut Resample>, pos: u64, next: u64, timeline: &mut u64, @@ -1736,6 +1948,16 @@ fn emit( if interleaved.is_empty() { return true; // nothing left of it; the loop head ends the segment } + // The rate first, the filter second: what the equalizer's bands are set in + // is the frequency a listener hears, and after a resample that is not the + // frequency the file was written at. A segment at real time has no + // resampler at all and reaches the filter with the decoder's own samples. + if let Some(speed) = speed { + speed.process(interleaved, channels); + if interleaved.is_empty() { + return true; // this buffer resolved to no output frame of its own + } + } if let Some(eq) = eq { eq.process(interleaved); } @@ -1755,6 +1977,7 @@ fn run_ac3( track: &mut Ac3Track, seg: &Segment, mut eq: Option<&mut EqState>, + speed: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, @@ -1794,6 +2017,7 @@ fn run_ac3( channels, seg, eq.as_deref_mut(), + speed.as_mut(), pos, next, timeline, @@ -1819,6 +2043,7 @@ fn run_sym( track: &mut SymTrack, seg: &Segment, mut eq: Option<&mut EqState>, + speed: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, @@ -1876,6 +2101,7 @@ fn run_sym( channels, seg, eq.as_deref_mut(), + speed.as_mut(), pos, next, timeline, diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 0e5208c..0d4ef79 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -1,16 +1,16 @@ //! The project file: a line of text per thing, and nothing else. //! //! ```text -//! edith 7 +//! edith 8 //! playhead 90 //! resolution 1920 1080 //! source 0 test_av.mp4 //! source 1 /elsewhere/test_av2.mp4 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk //! color 0.1:1.2:0.9:-0.3 -//! video 1 0 0 120 0 0 0 0 fit -//! audio 1 0 0 120 0 0 0 - fit -//! video 2 120 0 120 1 - - - fill +//! video 1 0 0 120 0 0 0 0 fit 1000 +//! audio 1 0 0 120 0 0 0 - fit 1000 +//! video 2 120 0 120 1 - - - fill 2000 //! audio 2 //! ``` //! @@ -39,22 +39,28 @@ //! -- the first colour line is color 0 -- printed and refused by the same rules. //! //! A lane line is ` -//! `: which lane the clip is on -- its kind and its 1-based number +//! `: which lane the clip is on -- its kind and its 1-based number //! among the lanes of that kind, the [`crate::project::Lane::label`] a header //! column shows -- then where the clip sits on the timeline, the half-open //! source range it plays, the file it plays from, its group id, the eq line it //! plays through, the colour line it is graded by (`-` for none of those three) //! and how it meets a project canvas of another shape, spelled `fit`, `fill`, -//! `stretch` or `center` ([`crate::scale::FitPolicy`]). Timeline placement is +//! `stretch` or `center` ([`crate::scale::FitPolicy`]), and how fast it plays, +//! in thousandths of real time ([`crate::project::Speed`], `1000` for a clip +//! nobody has speeded). Timeline placement is //! explicit, so a *gap* is simply a stretch no line covers -- there is nothing -//! to write for one, and nothing that can disagree about its length. +//! to write for one, and nothing that can disagree about its length. The `` +//! and `` are *source* frames whatever the speed says: how long the clip is +//! on the timeline is that range divided by the rate, and is written nowhere. //! //! A lane is declared by the clips on it, in the order the lanes are displayed //! in; a lane holding *nothing* has a bare ` ` line instead, which //! is the only way an empty lane could still be there on the way back. A lane //! number may not skip one of its kind. //! -//! **Version 6** was this without the `resolution` line and without the clip's +//! **Version 7** was this without the clip's speed field -- every clip of such +//! a project plays at real time, which is the only rate there was. +//! **Version 6** was that without the `resolution` line and without the clip's //! fit field -- such a project is the size of its first source and letterboxes //! nothing, because nothing on it could differ in size. **Version 5** was that //! without the colour lines and without the clip's colour @@ -63,10 +69,11 @@ //! lane and one audio lane, no more. **Version 2** wrote `source ` as //! well, which is this file's stream 0 -- one per file, whichever audio track //! came first. **Version 1** wrote that and one lane, queued end to end: `clip -//! `. All five still load -- a v1 file's clips are laid out +//! `. All six still load -- a v1 file's clips are laid out //! cumulatively and copied onto both lanes as one group each, which is exactly //! what a v1 timeline meant, and an older file simply equalizes and grades -//! nothing -- and saving any of them writes v7. An older reader refuses a newer +//! nothing, and an older one plays everything at real time -- and saving any of +//! them writes v8. An older reader refuses a newer //! file by name. //! //! 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}; use crate::color::ColorParams; use crate::eq::{Band, BandKind, EqParams}; -use crate::project::{Clip, Lane, LaneKind, Source}; +use crate::project::{Clip, Lane, LaneKind, Source, Speed}; use crate::scale::FitPolicy; /// What [`save`] writes. Read support goes back to `edith 1`; see the module /// docs for what those dialects looked like. -const MAGIC: &[u8] = b"edith 7"; +const MAGIC: &[u8] = b"edith 8"; +const MAGIC_V7: &[u8] = b"edith 7"; const MAGIC_V6: &[u8] = b"edith 6"; const MAGIC_V5: &[u8] = b"edith 5"; const MAGIC_V4: &[u8] = b"edith 4"; @@ -256,12 +264,13 @@ fn emit( let color = c.color.map_or("-".to_string(), |e| e.to_string()); out.extend_from_slice( format!( - "{keyword} {ord} {} {} {} {} {link} {eq} {color} {}\n", + "{keyword} {ord} {} {} {} {} {link} {eq} {color} {} {}\n", c.start, c.in_frame, c.out_frame, c.source, - fit_name(c.fit) + fit_name(c.fit), + c.speed.permille() ) .as_bytes(), ); @@ -280,8 +289,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // The dialects that wrote a source line without its stream field. Reading // one is the whole of what "an old project still opens" means here. let streamless = v1 || first == MAGIC_V2; - // The one that carries a project resolution and per-clip fit policies... - let v7 = first == MAGIC; + // The one that carries a per-clip speed... + let v8 = first == MAGIC; + // ...the ones that carry a project resolution and per-clip fit policies... + let v7 = v8 || first == MAGIC_V7; // ...the ones that carry colour grades... let v6 = v7 || first == MAGIC_V6; // ...the ones that carry equalizer settings... @@ -430,6 +441,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }, &doc, n, @@ -459,9 +471,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { if numbered && rest.is_empty() { continue; } - // v7 grew the fit field, v6 the colour one and v5 the eq one; - // every older dialect ends at the link. - let want = 5 + usize::from(v5) + usize::from(v6) + usize::from(v7); + // v8 grew the speed field, v7 the fit one, v6 the colour one and + // v5 the eq one; every older dialect ends at the link. + let want = + 5 + usize::from(v5) + usize::from(v6) + usize::from(v7) + usize::from(v8); let f = fields(rest, want, "clip", n)?; let clip = check( Clip { @@ -476,6 +489,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?, color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?, fit: fit_policy(f.get(7).copied(), n)?, + speed: speed_of(f.get(8).copied(), n)?, }, &doc, n, @@ -581,7 +595,7 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result { // Everything downstream -- `Clip::end`, the overlap check, the v1 queue -- // adds `start + len` as plain `u32`, which panics in debug and wraps in // release on a crafted file. Bound it here, at the door. - if clip.start.checked_add(clip.len()).is_none() { + if clip.start.checked_add(clip.frames()).is_none() { return Err(format!( "line {line}: clip at {} runs past the last frame there is", clip.start @@ -591,6 +605,29 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result { Ok(clip) } +/// A clip's `` field: thousandths of real time, as +/// [`crate::project::Speed`] holds it -- `1000` is the rate it was shot at. A +/// dialect with no such field (everything before v8) means real time, which is +/// what such a project always played at. A number outside the range the editor +/// can set is *refused* rather than clamped: a project file is generated, so +/// that is a corrupt line and not a dialect. +fn speed_of(field: Option<&[u8]>, line: usize) -> crate::Result { + let Some(field) = field else { + return Ok(Speed::NORMAL); + }; + let permille = number(field, line)?; + let speed = Speed::from_permille(permille.min(u32::from(u16::MAX)) as u16); + if u32::from(speed.permille()) != permille { + return Err(format!( + "line {line}: speed {permille} is outside {}-{} thousandths", + Speed::MIN.permille(), + Speed::MAX.permille() + ) + .into()); + } + Ok(speed) +} + /// How a fit policy is spelled in the file. One word each, so a clip line stays /// readable, and the same word the parser takes back. fn fit_name(fit: FitPolicy) -> &'static str { @@ -746,6 +783,7 @@ mod tests { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, } } @@ -795,10 +833,10 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 12); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ - video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\ - audio 1 0 0 30 0 0 - - fit\n", + video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ + audio 1 0 0 30 0 0 - - fit 1000\n", "the file under the project directory is written relative to it, \ each with the audio stream it plays" ); @@ -832,9 +870,9 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 7); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 7\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ - video 1 0 0 30 0 4 - - fit\naudio 1\n\ - video 2 40 0 10 0 - - - fit\naudio 2 0 0 30 0 4 - - fit\n", + "edith 8\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ + video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", "an empty lane is a line of its own; everything else is its clips" ); let back = parse(&bytes, &dir).expect("parse"); @@ -940,12 +978,12 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 16777215.0:-0.1:3.918315e-39:hs\n\ eq\n\ - video 1 0 0 30 0 0 0 - fit\nvideo 1 30 10 20 0 - 1 - fit\n\ - audio 1 0 0 30 0 0 0 - fit\naudio 1 30 0 10 0 - 2 - fit\n", + video 1 0 0 30 0 0 0 - fit 1000\nvideo 1 30 10 20 0 - 1 - fit 1000\n\ + audio 1 0 0 30 0 0 0 - fit 1000\naudio 1 30 0 10 0 - 2 - fit 1000\n", "the table comes before the clips, and a clip names a line of it" ); @@ -1016,11 +1054,13 @@ mod tests { Clip { color: Some(0), fit: FitPolicy::default(), + speed: Speed::NORMAL, ..clip(0, 0, 30, 0, Some(0)) }, Clip { color: Some(1), fit: FitPolicy::default(), + speed: Speed::NORMAL, ..clip(30, 10, 20, 0, None) }, ], @@ -1028,11 +1068,13 @@ mod tests { Clip { color: Some(0), fit: FitPolicy::default(), + speed: Speed::NORMAL, ..clip(0, 0, 30, 0, Some(0)) }, Clip { color: Some(2), fit: FitPolicy::default(), + speed: Speed::NORMAL, ..clip(30, 0, 10, 0, None) }, ], @@ -1040,12 +1082,12 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ color 0.1:1.2:0.9:-0.3\n\ color -1e-7:16777215.0:3.918315e-39:-0.0\n\ color 0.0:1.0:1.0:0.0\n\ - video 1 0 0 30 0 0 - 0 fit\nvideo 1 30 10 20 0 - - 1 fit\n\ - audio 1 0 0 30 0 0 - 0 fit\naudio 1 30 0 10 0 - - 2 fit\n", + video 1 0 0 30 0 0 - 0 fit 1000\nvideo 1 30 10 20 0 - - 1 fit 1000\n\ + audio 1 0 0 30 0 0 - 0 fit 1000\naudio 1 30 0 10 0 - - 2 fit 1000\n", "the table comes before the clips, and a clip names a line of it" ); @@ -1105,9 +1147,81 @@ mod tests { (1280, 720), old.playhead )), - "edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ - video 1 0 0 30 0 0 0 - fit\naudio 1 0 0 30 0 0 - - fit\n" + video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" + ); + } + + /// The whole of the v8 bump, the eq and colour tests' twin: a clip's rate is + /// written on its own line, comes back as the very number that was set, and + /// a v7 file -- which has no such field -- loads at real time and re-saves + /// saying so. + #[test] + fn speeds_round_trip_and_a_v7_file_plays_at_real_time() { + let dir = PathBuf::from("/proj"); + let sources = vec![Source::new("/proj/a.mp4", 0)]; + let speeded = |start, in_frame, out_frame, permille| Clip { + start, + in_frame, + out_frame, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::from_permille(permille), + }; + // 30 source frames at 2x is 15 timeline frames, which is where the + // second clip starts -- the file writes the source range and the rate, + // and the length on the timeline is derived from the two. + let lanes = vec![ + ( + LaneKind::Video, + vec![speeded(0, 0, 30, 2000), speeded(15, 30, 40, 250)], + ), + (LaneKind::Audio, vec![speeded(0, 0, 30, 2000)]), + ]; + let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); + assert_eq!( + String::from_utf8_lossy(&bytes), + "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ + audio 1 0 0 30 0 - - - fit 2000\n", + "the rate is the clip line's last field, in thousandths" + ); + let back = parse(&bytes, &dir).expect("parse"); + assert_eq!(back.lanes, lanes, "every clip keeps the rate it named"); + + // ...and the dialect before it, which had no rate to name. + let v7 = b"edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 0 - - fit\naudio 1 0 0 30 0 0 - - fit\n"; + let old = parse(v7, &dir).expect("v7 parses"); + assert!( + old.lanes + .iter() + .flat_map(|(_, clips)| clips) + .all(|c| c.speed == Speed::NORMAL), + "nothing before v8 plays at anything but real time" + ); + assert_eq!( + String::from_utf8_lossy(&emit( + &dir, + &old.sources, + &old.lanes, + &old.eq, + &old.color, + (1280, 720), + old.playhead + )), + "edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" + ); + // A rate outside what the editor can set is a corrupt line, by name. + let bad = b"edith 8\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 9000\n"; + assert_eq!( + parse(bad, &dir).unwrap_err().to_string(), + "line 3: speed 9000 is outside 250-4000 thousandths" ); } @@ -1241,10 +1355,10 @@ mod tests { assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); assert_eq!( String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), - "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ - video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\ - audio 1 0 0 30 0 0 - - fit\n" + video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ + audio 1 0 0 30 0 0 - - fit 1000\n" ); // An empty lane's line is still the whole of that lane, eq or no eq. let empty = parse( @@ -1294,10 +1408,10 @@ mod tests { let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); assert_eq!( String::from_utf8_lossy(&v5), - "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 0 /elsewhere/b.mp4\n\ - video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\ - audio 1 0 0 30 0 0 - - fit\n", + video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ + audio 1 0 0 30 0 0 - - fit 1000\n", "a re-saved v2 project differs only by its version, the lane \ numbers, the streams it always meant and an equalizer it has none of" ); @@ -1326,7 +1440,7 @@ mod tests { // Saved again it is the current version, which round-trips to the // same document. let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); - assert!(v5.starts_with(b"edith 7\n")); + assert!(v5.starts_with(b"edith 8\n")); let again = parse(&v5, &dir).expect("v5 parses"); assert_eq!(again.lanes, back.lanes); // A dialect may not be mixed: lane lines under v1, `clip` under v2. @@ -1428,8 +1542,8 @@ mod tests { let bytes = std::fs::read(&path).expect("read back"); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 7\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ - video 1 0 0 30 0 - - - fit\naudio 1 0 0 30 0 - - - fit\n" + "edith 8\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" ); // Loading rejoins the *given* directory, so the file is reached by the // way the project was opened -- the same file, through the link, still @@ -1473,10 +1587,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 8\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) + let err = parse(b"edith 9\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 8"); + assert_eq!(err, "line 1: unsupported version 9"); for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { assert_eq!( parse(junk, &dir).unwrap_err().to_string(), diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 9fe7757..c45171c 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -317,6 +317,42 @@ fn copy_audio( AudioSession::copy_multi_streams(&project.audio_sources(), segments) } +/// The picture formats' answer to a speeded clip: **refused, by name**. +/// +/// A clip at another rate is a clip whose pictures have to be picked out of its +/// source at that rate and whose sound has to be resampled. The sound alone +/// settles it here: this path *copies* AAC packets ([`copy_audio`]) and a +/// resample is not a copy -- exporting it anyway would write the picture at one +/// speed and the sound at another, which is the one failure a user would not +/// notice until the file was somewhere else. So the whole export is refused +/// rather than half-honoured, and the refusal says which clip and what to do: +/// WAV and FLAC are decoded and mixed, and they honour it. +/// +/// AV1 carries no sound at all and could honour the picture on its own, and is +/// refused with the rest: a video export that silently dropped the rate on one +/// format and kept it on another would be worse than one rule. +/// +/// ponytail: the ceiling is the packet copy and the frame walk in [`run`], which +/// steps its decoder once per output picture. Upgrade path is a `skip(n)` on +/// [`ClipDecoder`] for a rate above real time, a held picture below it, and an +/// AAC encoder (or a decode-and-re-encode) for the sound -- at which point this +/// check becomes the `Format::Av1` arm alone. +fn speeds_refused(project: &Project, meta: &VideoMeta) -> crate::Result<()> { + for lane in project.lanes() { + if let Some(clip) = project.lane(lane).iter().find(|c| !c.speed.is_normal()) { + return Err(format!( + "the {} clip at {} plays at {} and a picture export cannot re-time it: \ + export WAV or FLAC, which are resampled, or set that clip back to 1.00x", + lane.label(), + timecode(clip.start, meta.frame_rate), + clip.speed + ) + .into()); + } + } + Ok(()) +} + fn run( project: &Project, meta: &VideoMeta, @@ -325,6 +361,7 @@ fn run( settings: &ExportSettings, ) -> crate::Result<()> { let total = project.timeline_frames(); + speeds_refused(project, meta)?; let sources = project.sources(); // Audio first: a track has to be declared when the muxer is created, which // happens as soon as the first coded picture arrives. None of it for AV1 -- @@ -502,7 +539,14 @@ fn run_audio( // playback's feeder reads from -- there is no second place here that could // apply them differently. let eqs = project.audio_eqs_from(0, meta.frame_rate); - let Some((audio, chunks)) = AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs)? else { + // ...and the rates with them, for exactly the same reason: a speeded clip is + // resampled inside the worker playback feeds from, so a WAV of a timeline at + // 2x is half as long and holds the samples that were heard -- not a + // second pass here that could disagree with what the ear got. + let speeds = project.audio_speeds_from(0, meta.frame_rate); + let Some((audio, chunks)) = + AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds)? + else { return Err("this timeline has no audio to export".into()); }; let channels = usize::from(audio.channels); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1aa7b84..3077af3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -26,7 +26,7 @@ pub use demux::{Codec, VideoMeta}; pub use export::ExportHandle; pub use mux::{AudioParams, Mp4Muxer, VideoParams}; pub use playback::PlaybackSession; -pub use project::{Clip, Project}; +pub use project::{Clip, Project, Speed}; /// Whether a path names a standalone audio file -- a source with no picture, /// which belongs on the audio lane and nowhere else. Extension only, lowercased: diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 1abb98c..b739bdc 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -25,7 +25,7 @@ use crate::color::ColorParams; use crate::decode::{DecodeSession, Frame, Worker}; use crate::demux::{Codec, Demuxer, VideoMeta}; use crate::eq::EqParams; -use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span}; +use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span, Speed}; use crate::scale::{Composer, FitPolicy}; /// How long the feeder waits out a full ring. The ring holds a second, so this @@ -309,6 +309,7 @@ impl PlaybackSession { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; let project = Project::from_parts( vec![Source::new(path, 0)], @@ -374,6 +375,7 @@ impl PlaybackSession { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; // No group and no audio clip: a still is silent, and a clip on `A1` // playing from a PNG is a source the audio worker cannot open. @@ -654,10 +656,17 @@ impl PlaybackSession { // A gap's worker indexes from zero, a decoder's from its in // point: `base` is whichever this span started at. An empty // timeline has no span, and its one black frame is frame 0. - let (start, base) = self - .span - .map_or((0, 0), |s| (s.start, s.from.map_or(0, |(_, i)| i))); - frame.index = start + frame.index.saturating_sub(base); + let (start, base, speed) = self.span.map_or((0, 0, Speed::NORMAL), |s| { + (s.start, s.from.map_or(0, |(_, i)| i), s.speed) + }); + // ...and a *speeded* clip's decoder counts source frames + // faster than the timeline does, so the offset comes back + // through the clip's own rate. At 2x two decoded frames land + // on one timeline frame and the display drops the earlier of + // them; at half speed each lands two apart and is held until + // it is due. Real time divides by one and is the arithmetic + // this always did. + frame.index = start + speed.timeline_at(frame.index.saturating_sub(base)); return Some(frame); } Err(TryRecvError::Empty) => return None, @@ -733,15 +742,18 @@ impl PlaybackSession { // the worker carries it and every frame it converts wears it. Some(Span { start, - len, from: Some((source, in_frame)), + .. }) if crate::is_image(&self.project.sources()[source].path) => { // A still: the same grade and the same canvas as any other // clip, over a picture decoded once and repeated for the span. + // As many pictures as the span reads *source* frames, so a still + // is numbered like a decoder's output and a speed reaches it + // through the same rewrite (`try_frame`) as any other clip. DecodeSession::open_still( &self.project.sources()[source].path, in_frame, - len, + span.expect("matched above").source_len(), self.project .composite_color_at(start) .copied() @@ -756,12 +768,14 @@ impl PlaybackSession { } Some(Span { start, - len, from: Some((source, in_frame)), + .. }) => DecodeSession::open_worker( &self.project.sources()[source].path, in_frame, - in_frame + len, + // Source frames, which a speed makes more (or fewer) than the + // timeline frames the span covers. + in_frame + span.expect("matched above").source_len(), self.project .composite_color_at(start) .copied() @@ -961,6 +975,36 @@ impl PlaybackSession { true } + /// How fast the clip at `idx` of `lane` plays -- what a card shows before + /// anyone drags it. + pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed { + self.project.speed_of(lane, idx) + } + + /// Sets it, for that clip and its whole group ([`Project::set_speed`]): one + /// undo step for the lot. Reseeks like every other edit, so the picture runs + /// -- and the sound is resampled -- from the next frame on rather than at the + /// next play. The `Err` names the clip in the way when slowing one down + /// would run it into its neighbour, and nothing changes. + pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> { + // Spelled out rather than through `edit`, whose closure hands back a + // bool and would drop the refusal's own words. + self.project.set_speed(lane, idx, speed)?; + let now = self.now(); + self.seek(now); + Ok(()) + } + + /// [`set_speed`](Self::set_speed) without the undo step -- the samples inside + /// one drag ([`Project::set_speed_live`]). Reseeks like the committing one, + /// which is what makes the bar move the picture under the hand. + pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> { + self.project.set_speed_live(lane, idx, speed)?; + let now = self.now(); + self.seek(now); + Ok(()) + } + /// Where that edge may land, `(first, last)` timeline frame inclusive: what /// a drag clamps the pointer to so the box it draws is the box /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index. @@ -1166,6 +1210,7 @@ impl PlaybackSession { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; // Which lane a source may land on is decided here and only here, so a // front-end never has to make the same call twice: a file with no @@ -1478,13 +1523,20 @@ impl PlaybackSession { // changed a band restarts the workers with the new curve already in // them, and no live channel has to reach into a running one. let eqs = self.project.audio_eqs_from(target, fps); + // ...and the rates, the same way again: a speeded segment is + // resampled inside its own worker, before the mix, so what the ear + // hears is what the timeline shows. Empty for a project nobody has + // speeded, which is the path that decodes the same samples it always + // did. + let speeds = self.project.audio_speeds_from(target, fps); // Each source on the stream it was placed with: what plays is what // the library row said, and what an export copies (`export::run`). let sources = self.project.audio_sources(); - audio_running = match AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs) { - Ok(Some((_, rx))) => audio.spawn_feeder(rx), - _ => false, - }; + audio_running = + match AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds) { + Ok(Some((_, rx))) => audio.spawn_feeder(rx), + _ => false, + }; if !audio_running { // Nothing will ever be fed again; let `tick` fall to wall time // instead of waiting on a device that has no more work coming. diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index ca4c9d5..e04e66b 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -68,6 +68,116 @@ use crate::color::ColorParams; use crate::eq::EqParams; use crate::scale::FitPolicy; +/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it +/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for +/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly +/// comparable nor exactly writable, and `.edith` has to read back the very +/// number that was set. A thousandth is finer than any card can drag and coarser +/// than any rounding anyone can hear. +/// +/// The rate alone: a speeded clip is resampled, so its pitch moves with it (the +/// tape effect). Nothing here preserves pitch and nothing here plays backwards +/// -- [`Speed::MIN`] is a quarter speed, [`Speed::MAX`] four times. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] +pub struct Speed(u16); + +impl Speed { + /// Real time -- what every clip is until something says otherwise, and the + /// value every path in this engine short-circuits on. + pub const NORMAL: Speed = Speed(1000); + pub const MIN: Speed = Speed(250); + pub const MAX: Speed = Speed(4000); + + /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse) + /// unrepresentable rather than merely refused: nothing downstream divides + /// by a speed that could be nothing. + pub fn from_permille(permille: u16) -> Self { + Speed(permille.clamp(Self::MIN.0, Self::MAX.0)) + } + + pub fn permille(self) -> u16 { + self.0 + } + + pub fn is_normal(self) -> bool { + self == Self::NORMAL + } + + /// As a multiplier, for the sound worker and for a label. + pub fn as_f64(self) -> f64 { + f64::from(self.0) / 1000. + } + + /// How many *timeline* frames `source` source frames occupy at this rate -- + /// the clip's footprint. Rounded to the nearest frame and **never zero**: a + /// clip that occupied no frames would be an empty placement, which the lane + /// invariant forbids and which nothing could ever click on again. + pub fn frames(self, source: u32) -> u32 { + let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0); + n.clamp(1, u64::from(u32::MAX)) as u32 + } + + /// The mapping itself: which source frame of a clip the `offset`th timeline + /// frame of it plays. Floored, so the first timeline frame is the clip's own + /// in-point at every rate. + pub fn source_at(self, offset: u32) -> u32 { + (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32 + } + + /// Its inverse, for a decoder's frames on their way back out: which timeline + /// frame of the clip the `offset`th *source* frame of it lands on. + pub fn timeline_at(self, offset: u32) -> u32 { + (u64::from(offset) * 1000 / u64::from(self.0)).min(u64::from(u32::MAX)) as u32 + } + + /// The longest source range that still *fits* in `frames` timeline frames at + /// this rate, and at least one frame. What a trim commits: rounding could + /// otherwise hand back a range one frame wider than the room the edge was + /// clamped to, and a clip that outgrew its room would overlap its + /// neighbour -- the one thing a lane may never do. At real time this is + /// `frames` itself, so nothing about an unspeeded trim changes. + pub fn fit(self, frames: u32) -> u32 { + let mut src = self.source_at(frames).max(1); + while src > 1 && self.frames(src) > frames { + src -= 1; + } + src + } + + /// Where in the source a cut `offset` timeline frames into a clip of `len` + /// source frames falls -- and `None` when this rate cannot address that + /// frame at all. + /// + /// At half speed a clip of ten source frames is twenty timeline frames long + /// and every source frame is on screen twice, so a cut between the two + /// showings of one frame is not a cut in the *file*: taking it would leave + /// two halves whose lengths no longer add up to the clip that was cut -- + /// a hole in the lane, or an overlap of the next clip. Refused instead, so + /// the model stays exact and the front-end can say why. At real time every + /// interior frame answers, which is the path a project without speeds is on. + pub fn split_at(self, len: u32, offset: u32) -> Option { + let src = self.source_at(offset); + (src > 0 + && src < len + && self.frames(src) == offset + && self.frames(len - src) == self.frames(len) - offset) + .then_some(src) + } +} + +impl Default for Speed { + fn default() -> Self { + Self::NORMAL + } +} + +impl std::fmt::Display for Speed { + /// `2.00x` -- what a card prints and what a clip box is marked with. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:.2}x", self.as_f64()) + } +} + /// A half-open `[in_frame, out_frame)` range of frames of source /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start). /// Never empty. @@ -103,17 +213,37 @@ pub struct Clip { /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars /// where the aspect does not agree. pub fit: FitPolicy, + /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the + /// eq and colour indexes: it is two bytes with nothing to share, and a table + /// would put a level of indirection between the mapping and the one number + /// every frame of it is divided by. + /// + /// It does **not** move `in_frame`/`out_frame`: those stay the source range + /// the clip plays, so a trim and a split still address the file. What it + /// changes is how many *timeline* frames that range is spread over + /// ([`Clip::frames`]). + pub speed: Speed, } impl Clip { - /// Frame count; `>= 1` by the never-empty invariant. + /// Source frame count; `>= 1` by the never-empty invariant. What the clip + /// reads out of its file -- not how long it is on the timeline, which is + /// [`Clip::frames`] and differs the moment it is speeded. pub fn len(&self) -> u32 { self.out_frame - self.in_frame } + /// Timeline frames it occupies: its source range at its own speed, never + /// zero (see [`Speed::frames`]). Every placement question -- where it ends, + /// what it overlaps, how wide its box is -- is asked of this and not of + /// [`Clip::len`]. + pub fn frames(&self) -> u32 { + self.speed.frames(self.len()) + } + /// One past the last timeline frame it covers. pub fn end(&self) -> u32 { - self.start + self.len() + self.start + self.frames() } } @@ -235,6 +365,12 @@ pub struct Span { /// `(source index, first source frame)`, or `None` for a gap -- which the /// engine renders as black frames and as silence. pub from: Option<(usize, u32)>, + /// The rate the clip this came off plays at ([`Clip::speed`]); + /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is + /// timeline frames whatever it says -- the speed is how many *source* frames + /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers + /// come back to the timeline. + pub speed: Speed, } impl Span { @@ -242,6 +378,30 @@ impl Span { pub fn end(&self) -> u32 { self.start + self.len } + + /// How many source frames it reads: what a decoder is asked for and how wide + /// an audio window is. `len` at real time, and the one arithmetic both the + /// picture and the sound go through, so they cannot disagree about where a + /// speeded clip ends. + pub fn source_len(&self) -> u32 { + match self.from { + Some(_) => self.speed.source_at(self.len).max(1), + None => self.len, + } + } +} + +/// What one speeded audio segment asks of the worker: how many source frames to +/// consume per output frame, and how many seconds of timeline it has to fill. +/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no +/// resampling at all. +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct Stretch { + /// Source frames per output frame -- the speed as a multiplier. + pub step: f64, + /// What the segment owes the timeline, which is what it is padded or + /// trimmed to. + pub timeline_secs: f64, } /// What a save writes and a load takes back: the sources, every lane in @@ -290,6 +450,7 @@ impl Project { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; Self { // A file is opened on its first audio stream: nothing has picked @@ -358,7 +519,7 @@ impl Project { ) .into()); } - if c.start.checked_add(c.len()).is_none() { + if c.start.checked_add(c.frames()).is_none() { return Err(format!( "{name} clip at {} runs past the last frame there is", c.start @@ -517,6 +678,7 @@ impl Project { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; for data in &mut self.lanes { data.clips.push(clip); @@ -758,6 +920,77 @@ impl Project { true } + /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an + /// index that is not there, which is what every clip starts at anyway. + pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed { + self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed) + } + + /// Sets it, for the clip **and its whole group**: a link is one span on + /// however many lanes ([`links_are_consistent`]), so a picture sped up away + /// from its sound would be a group no save could load. One snapshot, so the + /// group's change is one [`Project::undo`]. + /// + /// The source range is untouched -- a speed says how many timeline frames + /// that range is spread over ([`Clip::frames`]), which is why a trim and a + /// split still address the file afterwards. + /// + /// Refused, changing nothing and costing no undo step, when the clip would + /// grow into the one after it on its own lane: slowing a clip down makes it + /// wider, and a lane may not overlap itself. The refusal *names* the clip in + /// the way -- by lane and timeline frame -- because "it did not fit" is not + /// something a user can go and fix. Also for an index that is not there. + pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> { + self.write_speed(lane, idx, speed, true) + } + + /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside* + /// one pointer drag, whose first write (a plain `set_speed`) already took the + /// snapshot the gesture rolls back to. A drag across the bar is one undo, + /// not one per rate it passed through -- exactly as + /// [`set_color_live`](Self::set_color_live) is for a slider. + pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> { + self.write_speed(lane, idx, speed, false) + } + + fn write_speed( + &mut self, + lane: Lane, + idx: usize, + speed: Speed, + snapshot: bool, + ) -> crate::Result<()> { + let Some(members) = self.group_of(lane, idx) else { + return Err(format!("there is no clip {idx} on {}", lane.label()).into()); + }; + for &(l, i) in &members { + let clips = &self.lanes[l].clips; + let mut moved = clips[i]; + moved.speed = speed; + if let Some(next) = clips.get(i + 1) + && moved.end() > next.start + { + let name = handles(&self.lanes)[l].label(); + return Err(format!( + "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \ + move it along, or trim this one first", + moved.end(), + next.start + ) + .into()); + } + } + if snapshot { + self.snapshot(); + } + for (l, i) in members { + self.lanes[l].clips[i].speed = speed; + debug_assert!(sorted_disjoint(&self.lanes[l].clips)); + } + debug_assert!(links_are_consistent(&self.lanes).is_ok()); + Ok(()) + } + /// How the clip at `idx` of `lane` meets a project canvas of another shape. /// [`FitPolicy::Fit`] for an index that is not there, which is the default /// every clip starts at anyway. @@ -796,7 +1029,12 @@ impl Project { } pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> { - self.lane(lane).iter().map(|c| (c.start, c.len())).collect() + // Timeline frames, not source ones: a box on a lane is as wide as the + // clip is long *there*, which a speed halves or quadruples. + self.lane(lane) + .iter() + .map(|c| (c.start, c.frames())) + .collect() } /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap @@ -805,10 +1043,7 @@ impl Project { pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> { let clips = self.lane(lane); let idx = at(clips, timeline_frame)?; - Some(( - idx, - clips[idx].in_frame + (timeline_frame - clips[idx].start), - )) + Some((idx, source_frame(&clips[idx], timeline_frame))) } /// [`map`](Project::map) on `V1` -- the mapping a decoder follows. @@ -831,13 +1066,12 @@ impl Project { Some(idx) => Span { start: timeline_frame, len: clips[idx].end() - timeline_frame, - from: Some(( - clips[idx].source, - clips[idx].in_frame + (timeline_frame - clips[idx].start), - )), + from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))), + speed: clips[idx].speed, }, None => Span { start: timeline_frame, + speed: Speed::NORMAL, // The next placement, or the end of the timeline: a gap is // bounded by what comes after it, never by its own bookkeeping. len: clips @@ -892,20 +1126,18 @@ impl Project { let winner = video .iter() .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some()); - let (from, until) = match winner { + let (from, speed, until) = match winner { Some(i) => { let clips = self.lane(video[i]); let idx = at(clips, timeline_frame).expect("just found above"); ( - Some(( - clips[idx].source, - clips[idx].in_frame + (timeline_frame - clips[idx].start), - )), + Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))), + clips[idx].speed, clips[idx].end(), ) } // Nothing covers it: black until something above the floor starts. - None => (None, total), + None => (None, Speed::NORMAL, total), }; let takeover = video[winner.map_or(0, |i| i + 1)..] .iter() @@ -916,6 +1148,7 @@ impl Project { start: timeline_frame, len: takeover.map_or(until, |t| t.min(until)) - timeline_frame, from, + speed, }) } @@ -1012,7 +1245,11 @@ impl Project { continue; }; let mut tail = data.clips[idx]; - tail.in_frame += timeline_frame - tail.start; + // Where the cut lands *in the file*, which is the clip's own rate + // away from where it lands on the timeline. Both halves keep the + // speed, and `splittable` has already refused any frame at which + // the two would not add up to the one being cut. + tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so"); tail.start = timeline_frame; tail.link = right; data.clips[idx].out_frame = tail.in_frame; @@ -1295,12 +1532,19 @@ impl Project { let c = &mut self.lanes[l].clips[i]; match edge { Edge::Start => { + // The frames that stay play what they played, so the room + // that survives is measured from the *end*: at a speed the + // source range that fits in it is `Speed::fit`'s answer, and + // at real time it is the offset itself, unchanged. + let keep = c.speed.fit(c.end() - to).min(c.out_frame); // Non-negative by `lo`, which is what keeps the in-point on // the source. - c.in_frame = (i64::from(c.in_frame) + i64::from(to) - i64::from(c.start)) as u32; + c.in_frame = c.out_frame - keep; c.start = to; } - Edge::End => c.out_frame = c.in_frame + (to - c.start), + // Never wider than the room the edge was clamped to: see + // [`Speed::fit`]. + Edge::End => c.out_frame = c.in_frame + c.speed.fit(to - c.start), } debug_assert!(sorted_disjoint(&self.lanes[l].clips)); } @@ -1325,27 +1569,32 @@ impl Project { let c = clips[i]; let (member_lo, member_hi) = match edge { Edge::Start => ( - // Back to the source's own first frame, and never over the - // clip in front of it. Saturating because a clip may hold - // *more* head than the timeline has room for -- a ripple - // delete slides a clip back to frame 0 with its in-point - // wherever the cut left it -- and frame 0 is the other wall. + // Back to the source's own first frame -- as many *timeline* + // frames as that head is worth at the clip's rate, which at + // real time is the head itself -- and never over the clip in + // front of it. Saturating because a clip may hold *more* + // head than the timeline has room for -- a ripple delete + // slides a clip back to frame 0 with its in-point wherever + // the cut left it -- and frame 0 is the other wall. c.start - .saturating_sub(c.in_frame) + .saturating_sub(c.speed.timeline_at(c.in_frame)) .max(i.checked_sub(1).map_or(0, |p| clips[p].end())), c.end() - 1, ), Edge::End => ( c.start + 1, - // Out to whatever is left of the source, and never over the - // clip behind it. + // Out to whatever is left of the source -- again in timeline + // frames, at this clip's rate -- and never over the clip + // behind it. c.start .saturating_add( - source_frames - .get(c.source) - .copied() - .unwrap_or(c.out_frame) - .saturating_sub(c.in_frame), + c.speed.timeline_at( + source_frames + .get(c.source) + .copied() + .unwrap_or(c.out_frame) + .saturating_sub(c.in_frame), + ), ) .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)), ), @@ -1415,7 +1664,9 @@ impl Project { // that clip -- and a save the engine's own `open_project` then refuses. let picture_only = crate::is_image(&source.path); let at = timeline_frame.min(self.timeline_frames()); - let len = clip.len(); + // The room it takes on the timeline, which its speed decides -- not the + // source range it reads. + let len = clip.frames(); // Room for it: `open_room` adds `len` to every start from `at` on, and a // hand-written file may hold a clip that ends at the very last frame // (`edith::check` permits `start + len == u32::MAX`). Refused here @@ -1430,6 +1681,19 @@ impl Project { { return false; } + // ...and room *to open*: the paste splits whatever it lands inside of, + // and a speeded clip can only be cut where its own rate has a source + // frame ([`Speed::split_at`]). Refused rather than pasted over the top + // of one, which is the overlap a lane may never hold. At real time every + // frame answers, so this cannot refuse an unspeeded paste. + let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end()); + if self + .lanes + .iter() + .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none()) + { + return false; + } self.snapshot(); let clip = Clip { start: at, @@ -1450,7 +1714,7 @@ impl Project { .filter_map(|&kind| self.index(Lane::new(kind, 0))) .collect(); for (i, data) in self.lanes.iter_mut().enumerate() { - open_room(&mut data.clips, at, clip.len()); + open_room(&mut data.clips, at, len); if takes.contains(&i) { let idx = data.clips.partition_point(|c| c.start < at); data.clips.insert(idx, clip); @@ -1515,7 +1779,7 @@ impl Project { let Some(clip) = self.lane(lane).get(idx).copied() else { return false; }; - self.ripple_delete(clip.start, clip.len()) + self.ripple_delete(clip.start, clip.frames()) } /// Restore every lane from before the last successful edit -- the clips and @@ -1555,11 +1819,13 @@ impl Project { .iter() .map(|span| match span.from { // A clip's window is in *source* seconds: where in the file it - // reads from, which a delete before it never shifts. + // reads from, which a delete before it never shifts. How many + // source frames that is, is the span's own arithmetic -- at a + // speed it is not the timeline length ([`Span::source_len`]). Some((source, in_frame)) => ( Some(source), f64::from(in_frame) / fps, - f64::from(in_frame + span.len) / fps, + f64::from(in_frame + span.source_len()) / fps, ), // A gap has no file, so all it can say is how long it is. None => (None, 0.0, f64::from(span.len) / fps), @@ -1607,6 +1873,52 @@ impl Project { } } + /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s + /// segments plays at, and how long the timeline gives it: the same lanes in + /// the same order, one entry per segment, `None` for a segment at real time + /// -- which is every segment of a project nobody has speeded, and the path + /// the audio worker leaves bit-identical. + /// + /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason: + /// the segment tuple is what every opener and a dozen tests speak, and a + /// rate is not part of *which samples* a segment names. + /// + /// The seconds are what makes a resample exact: a segment's own window + /// resolves to whole source frames, and dividing that by the rate would + /// leave each clip a fraction of a frame short or long -- a drift that grows + /// clip by clip. Told how much timeline it owes, the worker pads or trims + /// the last few samples of each segment instead, so the sound stays locked + /// to the picture however many speeded cuts it walks through. + pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec>> { + self.audio_lanes() + .into_iter() + .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps)) + .collect() + } + + /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching + /// [`lane_segments_from`](Project::lane_segments_from) entry for entry -- + /// same walk, same `fps` refusal. + pub fn lane_speeds_from( + &self, + lane: Lane, + timeline_frame: u32, + fps: f64, + ) -> Vec> { + if !(fps.is_finite() && fps > 0.0) { + return Vec::new(); + } + self.spans_from(lane, timeline_frame) + .iter() + .map(|span| { + (!span.speed.is_normal()).then(|| Stretch { + step: span.speed.as_f64(), + timeline_secs: f64::from(span.len) / fps, + }) + }) + .collect() + } + /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s /// segments plays through: the same lanes in the same order, one entry per /// segment, `None` where the segment is a gap or its clip plays flat. @@ -1705,6 +2017,16 @@ fn handles(lanes: &[LaneData]) -> Vec { .collect() } +/// Which source frame a clip plays at `timeline_frame`: its in-point plus the +/// offset *at the clip's own rate*. The one place the two frame spaces meet, so +/// a speed cannot be applied twice or forgotten in one of them. +fn source_frame(c: &Clip, timeline_frame: u32) -> u32 { + // Clamped inside the clip's own range: rounding at a slow rate can put the + // last timeline frame of a clip a frame past its out-point, and a source + // frame outside the range is one the next clip owns. + (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1) +} + /// Index of the clip covering `frame`, or `None` for a gap or past the end. /// Binary search: the sorted-disjoint invariant is what makes it legal. fn at(clips: &[Clip], frame: u32) -> Option { @@ -1716,7 +2038,20 @@ fn at(clips: &[Clip], frame: u32) -> Option { /// there would cut in two. A placement's own first frame is not inside it. fn splittable(clips: &[Clip], frame: u32) -> Option { let idx = at(clips, frame)?; - (frame > clips[idx].start).then_some(idx) + // ...and, on a speeded clip, one its rate can actually address + // ([`Speed::split_at`]): a cut between two showings of one source frame + // would leave halves that no longer add up to the clip that was cut. + (frame > clips[idx].start) + .then_some(idx) + .filter(|&idx| split_source(&clips[idx], frame).is_some()) +} + +/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's +/// rate cannot address that frame. +fn split_source(c: &Clip, frame: u32) -> Option { + c.speed + .split_at(c.len(), frame - c.start) + .map(|src| c.in_frame + src) } /// 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 { fn joinable(clips: &[Clip], frame: u32) -> Option { let idx = clips.iter().position(|c| c.end() == frame)?; let next = clips.get(idx + 1)?; + let joined = clips[idx].len() + next.len(); (next.start == frame && next.source == clips[idx].source - && next.in_frame == clips[idx].out_frame) - .then_some(idx) + && next.in_frame == clips[idx].out_frame + // ...at one rate, and one that puts the rejoined clip back in exactly + // the room the two took up: what a split could have produced, which is + // all this undoes. + && next.speed == clips[idx].speed + && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames()) + .then_some(idx) } /// The lane invariant: sorted by `start`, no two placements overlapping, no @@ -1824,19 +2165,24 @@ fn clear(clips: &mut Vec, start: u32, end: u32) { out.push(c); continue; } - // The head that survives in front of the hole. + // The head that survives in front of the hole -- as much source as fits + // in the room in front of it at this clip's own rate ([`Speed::fit`]), + // which at real time is that room itself. Never *more*: a head that + // outgrew its room would reach into the hole it is being cut out of. if c.start < start { out.push(Clip { - out_frame: c.in_frame + (start - c.start), + out_frame: c.in_frame + c.speed.fit(start - c.start).min(c.len()), link: None, ..c }); } - // ...and the tail behind it, which keeps reading where it would have. + // ...and the tail behind it, which keeps reading up to where it would + // have: measured from its out-point for the head's reason, so what it + // occupies still ends where the whole clip did. if c.end() > end { out.push(Clip { start: end, - in_frame: c.in_frame + (end - c.start), + in_frame: c.out_frame - c.speed.fit(c.end() - end).min(c.len()), link: None, ..c }); @@ -1852,7 +2198,11 @@ fn clear(clips: &mut Vec, start: u32, end: u32) { fn open_room(clips: &mut Vec, at: u32, len: u32) { if let Some(idx) = splittable(clips, at) { let mut tail = clips[idx]; - tail.in_frame += at - tail.start; + // The cut in *source* frames, at the clip's own rate. `splittable` has + // already refused a frame the rate cannot address, which is why + // [`Project::paste`] refuses one too rather than opening room inside a + // clip that cannot be cut there. + tail.in_frame = split_source(&tail, at).expect("splittable said so"); tail.start = at; tail.link = None; clips[idx].out_frame = tail.in_frame; @@ -1892,6 +2242,7 @@ mod tests { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, } } @@ -2177,7 +2528,8 @@ mod tests { Some(Span { start: 6, len: 3, - from: Some((0, 6)) + from: Some((0, 6)), + speed: Speed::NORMAL }) ); assert_eq!(p.span_at(Lane::V1, 9), None); @@ -2211,6 +2563,7 @@ mod tests { eq: None, color: None, fit: FitPolicy::Fit, + speed: Speed::NORMAL, }; #[test] @@ -2398,7 +2751,8 @@ mod tests { Some(Span { start: 3, len: 2, - from: None + from: None, + speed: Speed::NORMAL }) ); assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on"); @@ -2416,7 +2770,8 @@ mod tests { Some(Span { start: 5, len: 4, - from: None + from: None, + speed: Speed::NORMAL }), "the audio lane holds silence to the end of the picture" ); @@ -2507,7 +2862,8 @@ mod tests { Some(Span { start: 9, len: 11, - from: None + from: None, + speed: Speed::NORMAL }) ); assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip"); @@ -3398,6 +3754,7 @@ mod tests { vec![Clip { color: Some(i), fit: FitPolicy::default(), + speed: Speed::NORMAL, ..video[0] }] }; @@ -3459,6 +3816,7 @@ mod tests { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; // The door: named errors, one per cause. @@ -3559,6 +3917,94 @@ mod tests { ); } + /// The mapping a speed changes, and the one it does not: a 2x clip reads two + /// source frames per timeline frame and still starts at its own in-point, + /// and a half-speed one shows every source frame twice. + #[test] + fn a_rate_maps_timeline_frames_onto_source_frames() { + let mut p = Project::single(FILE, 40); + p.set_speed(Lane::V1, 0, Speed::from_permille(2000)) + .expect("room enough"); + assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x"); + assert_eq!( + p.map(Lane::V1, 0), + Some((0, 0)), + "and it starts where it did" + ); + assert_eq!(p.map(Lane::V1, 1), Some((0, 2))); + assert_eq!(p.map(Lane::V1, 19), Some((0, 38))); + assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does"); + // The span a decoder is handed: as many source frames as it will read. + let span = p.span_at(Lane::V1, 0).expect("a span"); + assert_eq!((span.len, span.source_len()), (20, 40)); + // ...and the same clip the other way round. + let mut p = Project::single(FILE, 40); + p.set_speed(Lane::V1, 0, Speed::from_permille(500)) + .expect("room enough"); + assert_eq!(p.timeline_frames(), 80); + assert_eq!(p.map(Lane::V1, 0), Some((0, 0))); + assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice"); + assert_eq!(p.map(Lane::V1, 2), Some((0, 1))); + assert_eq!( + p.map(Lane::V1, 79), + Some((0, 39)), + "and the last timeline frame is still inside the source range" + ); + } + + /// A trim of a speeded clip is still a trim of its *source*, and the edge + /// still stops at the wall: the room a rate leaves is measured in timeline + /// frames and the range it commits in source ones. + #[test] + fn trimming_a_speeded_clip_stays_inside_its_room() { + let mut p = Project::single(FILE, 40); + p.set_speed(Lane::V1, 0, Speed::from_permille(2000)) + .expect("room enough"); + // A second clip butted against the first, so the wall is a real one. + assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0))); + let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip"); + assert_eq!(room, (1, 20), "out to the neighbour and no further"); + assert!( + !p.trim(Lane::V1, 0, Edge::End, 30, &[40]), + "clamped to the wall, which is where the edge already is" + ); + let c = p.clips()[0]; + assert_eq!(c.end(), 20, "so nothing moved"); + assert_eq!(c.out_frame, 40, "and it is still the whole source range"); + // ...and in: half the timeline frames is half the source range. + assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40])); + let c = p.clips()[0]; + assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames"); + assert_eq!(c.end(), 10, "and ten timeline frames of them"); + assert!(sorted_disjoint(p.clips())); + } + + /// The frames a rate cannot address: at half speed each source frame is on + /// screen twice, and the cut between the two showings is not a cut in the + /// file. Refused, so the two halves always add up to the clip that was cut. + #[test] + fn a_slow_clip_cuts_only_where_its_source_has_a_frame() { + let mut p = Project::single(FILE, 10); + p.set_speed(Lane::V1, 0, Speed::from_permille(500)) + .expect("room enough"); + assert_eq!(p.timeline_frames(), 20); + assert!( + !p.split(3), + "an odd frame is between two showings of one frame" + ); + assert_eq!(p.clips().len(), 1, "and nothing was cut"); + assert!(p.split(4), "an even one is a frame boundary"); + let halves = p.clips().to_vec(); + assert_eq!( + (halves[0].end(), halves[1].start, halves[1].end()), + (4, 4, 20), + "the halves meet, and still end where the clip did" + ); + assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames"); + assert!(p.regroup(4), "and the inverse puts it back"); + assert_eq!(p.clips().len(), 1); + } + /// The same claim, swept: random op sequences off the public surface, the /// project reloaded after every one of them. A failure prints its seed, and /// the seed replays the whole sequence. @@ -3584,7 +4030,7 @@ mod tests { .unwrap_or(&clip(0, 0, 5, 0)); let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 }; let idx = next(4) as usize; - let _ = match next(13) { + let _ = match next(14) { 0 => p.split(frame), 1 => p.regroup(frame), 2 => p.lift(lane, idx), @@ -3602,6 +4048,13 @@ mod tests { // reason: it rides on the clip and its orphans must go. 10 => p.set_color(lane, idx, Some(grade_at(next(4)))), 11 => p.set_color(lane, idx, None), + // ...and a rate in with them, which is the one of the three + // that moves *placements*: a clip that grew has to be + // refused rather than overlap, and one that shrank leaves a + // lane that still loads. Both are what `reloads` asks. + 12 => p + .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250)) + .is_ok(), _ => p.append_clip(0, 1 + next(9)), }; reloads(&p, &format!("seed {seed}, step {step}")); @@ -3711,7 +4164,8 @@ mod tests { Some(Span { start: 0, len: 4, - from: None + from: None, + speed: Speed::NORMAL }) ); // Every lane still covers the whole timeline, gaps included. @@ -3807,6 +4261,7 @@ mod tests { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; let lanes = vec![ LaneData { @@ -3841,6 +4296,7 @@ mod tests { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; // V1, A1, V2, A2 -- one take over [0, 4) on all four. let kinds = [ @@ -3944,9 +4400,15 @@ mod tests { .unwrap_or(&clip(0, 0, 5, 0)); let lane = lanes[next(3) as usize]; let idx = next(4) as usize; - let _ = match next(12) { + let _ = match next(13) { 10 => p.set_eq(lane, idx, Some(band_at(next(4)))), 11 => p.set_eq(lane, idx, None), + // A rate, which on many lanes is the group rule as well: + // every clip carrying the link moves together or none of + // them does, and `invariants_hold` is what says so. + 12 => p + .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250)) + .is_ok(), 0 => p.split(frame), 1 => p.regroup(frame), 2 => p.lift(lane, idx), @@ -3991,17 +4453,20 @@ mod tests { Span { start: 0, len: 10, - from: Some((0, 0)) + from: Some((0, 0)), + speed: Speed::NORMAL }, Span { start: 10, len: 10, - from: Some((1, 5)) + from: Some((1, 5)), + speed: Speed::NORMAL }, Span { start: 20, len: 10, - from: Some((0, 20)) + from: Some((0, 20)), + speed: Speed::NORMAL }, ], "V2 takes over for its own span and hands V1 back" @@ -4012,7 +4477,8 @@ mod tests { Some(Span { start: 15, len: 5, - from: Some((1, 10)) + from: Some((1, 10)), + speed: Speed::NORMAL }) ); assert_eq!(p.composite_span_at(30), None, "past the end"); @@ -4032,22 +4498,26 @@ mod tests { Span { start: 0, len: 5, - from: Some((0, 0)) + from: Some((0, 0)), + speed: Speed::NORMAL }, Span { start: 5, len: 5, - from: None + from: None, + speed: Speed::NORMAL }, Span { start: 10, len: 10, - from: Some((1, 0)) + from: Some((1, 0)), + speed: Speed::NORMAL }, Span { start: 20, len: 10, - from: None + from: None, + speed: Speed::NORMAL }, ] ); diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index b93983f..416e4df 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -15,8 +15,7 @@ use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use engine::export::{ExportSettings, Format}; -use engine::project::LaneKind; -use engine::project::Source; +use engine::project::{LaneKind, Source, Speed}; use engine::scale::FitPolicy; use engine::{AudioSession, Clip, ExportHandle, Project}; @@ -68,6 +67,7 @@ fn mixed_project() -> Project { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; Project::from_parts( vec![ @@ -89,6 +89,7 @@ fn mixed_project() -> Project { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }], ), (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]), @@ -325,6 +326,7 @@ fn a_51_ac3_source_round_trips_through_a_wav() { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }], )], Vec::new(), diff --git a/crates/engine/tests/eq_audio.rs b/crates/engine/tests/eq_audio.rs index ff2d38e..f88590e 100644 --- a/crates/engine/tests/eq_audio.rs +++ b/crates/engine/tests/eq_audio.rs @@ -23,7 +23,7 @@ use std::time::{Duration, Instant}; use engine::eq::{Band, BandKind, EqParams}; use engine::export::{ExportSettings, Format}; -use engine::project::{Lane, LaneKind, Source}; +use engine::project::{Lane, LaneKind, Source, Speed}; use engine::scale::FitPolicy; use engine::{AudioSession, Clip, ExportHandle, Project}; @@ -61,6 +61,7 @@ fn clip(start: u32, source: usize, frames: u32) -> Clip { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, } } diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 7c900ae..8a364e9 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -22,8 +22,7 @@ use std::time::{Duration, Instant}; use engine::export::ExportSettings; use engine::hw::HwEncoder; use engine::mux::{Mp4Muxer, VideoParams, parameter_sets}; -use engine::project::Lane; -use engine::project::Source; +use engine::project::{Lane, Source, Speed}; use engine::scale::FitPolicy; use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; @@ -195,6 +194,7 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; let clips = vec![clip(0, 0), clip(1, 10)]; let project = Project::from_parts( @@ -275,6 +275,7 @@ fn exports_the_audio_stream_the_timeline_plays() { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; // Stream 1 is the 22.05 kHz mono French track; stream 0 is 44.1 kHz // stereo. A project may only hold streams that agree, so this timeline is diff --git a/crates/engine/tests/lanes.rs b/crates/engine/tests/lanes.rs index 328e919..90a7e37 100644 --- a/crates/engine/tests/lanes.rs +++ b/crates/engine/tests/lanes.rs @@ -14,7 +14,7 @@ use std::sync::Once; use std::time::{Duration, Instant}; use engine::export::{ExportSettings, Format}; -use engine::project::{Clip, LaneKind, Source}; +use engine::project::{Clip, LaneKind, Source, Speed}; use engine::scale::FitPolicy; use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; @@ -239,6 +239,7 @@ fn the_mp4_copy_follows_the_lane_that_holds_the_sound() { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; let project = Project::from_parts( vec![Source::new(&source, 0)], @@ -299,6 +300,7 @@ fn two_audio_lanes_are_summed() { eq: None, color: None, fit: FitPolicy::default(), + speed: Speed::NORMAL, }; let a2 = project.add_lane(LaneKind::Audio); assert!(project.place(a2, TOP_IN, doubled), "place the second lane"); diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index 80f3bd3..3c287c1 100644 --- a/crates/engine/tests/saveload.rs +++ b/crates/engine/tests/saveload.rs @@ -209,7 +209,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() { let v2 = dir.join("new.edith"); loaded.save_project(&v2).expect("save"); let text = std::fs::read_to_string(&v2).expect("read back"); - assert!(text.starts_with("edith 7\n"), "{text}"); + assert!(text.starts_with("edith 8\n"), "{text}"); assert!( text.contains("\nresolution 1280 720\n"), "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() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\ - video 1 0 0 30 0 3 - - fit\naudio 1\n\ - video 2 40 0 20 0 - - - fit\naudio 2 0 0 30 0 3 - - fit\n", + "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\ + video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\ + video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n", "a four-lane project is written as it was read, three versions on" ); } @@ -327,11 +327,11 @@ fn a_version_5_project_carries_per_clip_equalizers() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\ + "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 12000.0:6.25:0.5:hs\n\ - video 1 0 0 30 0 - 0 - fit\nvideo 1 30 30 60 0 - 1 - fit\n\ - audio 1 0 0 30 0 - 0 - fit\naudio 1 30 30 60 0 - - - fit\n", + video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\ + audio 1 0 0 30 0 - 0 - fit 1000\naudio 1 30 30 60 0 - - - fit 1000\n", "the equalizer table and every clip's index survive a round trip" ); } @@ -362,12 +362,12 @@ fn a_version_6_project_carries_per_clip_colours() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\ + "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ color 0.1:1.2:0.9:-0.3\n\ color -0.25:1.0:0.0:0.5\n\ - video 1 0 0 30 0 - 0 0 fit\nvideo 1 30 30 60 0 - - 1 fit\n\ - audio 1 0 0 30 0 - - 0 fit\naudio 1 30 30 60 0 - - - fit\n", + video 1 0 0 30 0 - 0 0 fit 1000\nvideo 1 30 30 60 0 - - 1 fit 1000\n\ + audio 1 0 0 30 0 - - 0 fit 1000\naudio 1 30 30 60 0 - - - fit 1000\n", "the colour table and every clip's index survive a round trip" ); // 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() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - text, - "a v7 project is written exactly as it was read" + "edith 8\nplayhead 0\nresolution 960 720\nsource 0 test_av.mp4\n\ + video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\ + audio 1 0 0 60 0 - - - fit 1000\n", + "a v7 project is written back as the v8 it now is: the same clips, each \ + saying it plays at real time, which is what it always played at" ); // The refusals the new grammar adds, each naming its line. @@ -667,7 +670,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() { for (text, want) in [ ( - "edith 8\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", + "edith 9\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", "line 1", ), // An eq index the table does not hold, and a band shape there is none. diff --git a/crates/engine/tests/speed.rs b/crates/engine/tests/speed.rs new file mode 100644 index 0000000..1d630bc --- /dev/null +++ b/crates/engine/tests/speed.rs @@ -0,0 +1,332 @@ +//! Per-clip speed where it has to be true: in the pictures a preview shows, in +//! the samples the device is fed, in the file an export writes, and in the +//! project file the whole lot survives in. +//! +//! Everything goes through the front door. A `Project` is edited with +//! `set_speed` and then read exactly as `PlaybackSession::seek` reads it -- +//! `audio_segments_from` + `audio_eqs_from` + `audio_speeds_from` handed to the +//! same opener playback hands them to, and `composite_span_at` handed to the +//! same decoder. Nothing calls the resampler directly; `project.rs`'s own unit +//! tests own the placement arithmetic, and what is measured here is the wiring. +//! +//! The fixture is `test_speed_sync.mp4` (`gen_fixtures.sh`): black with one white +//! flash from t=1.0 to t=1.1, silent with a 1 kHz beep over exactly that +//! stretch. A re-timed clip that drifts puts the beep where the flash is not, +//! which is the whole reason that file exists. + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use engine::export::{ExportSettings, Format}; +use engine::project::{Lane, Speed}; +use engine::{AudioSession, DecodeSession, ExportHandle, Project}; + +const RATE: u32 = 44_100; +const FPS: f64 = 30.0; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// The sync fixture as a fresh project: one video clip and one audio clip, +/// grouped, covering the whole file -- what opening it in the editor gives. +fn sync_project() -> (Project, engine::VideoMeta) { + let path = asset("test_speed_sync.mp4"); + let (meta, _) = engine::demux::Demuxer::open(&path).expect("open the sync fixture"); + (Project::single(&path, meta.frame_count), meta) +} + +/// What the device would be fed, drained to the end: the exact three lists +/// `PlaybackSession::seek` builds, handed to the exact opener it hands them to. +fn play(project: &Project) -> Vec { + let sources = project.audio_sources(); + let segs = project.audio_segments_from(0, FPS); + let eqs = project.audio_eqs_from(0, FPS); + let speeds = project.audio_speeds_from(0, FPS); + let (meta, chunks) = AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds) + .expect("open the timeline's audio") + .expect("the timeline has audio"); + assert_eq!((meta.sample_rate, meta.channels), (RATE, 2)); + let mut samples = Vec::new(); + for chunk in chunks { + samples.extend(chunk.samples); + } + samples +} + +/// When the beep starts, in timeline seconds: the first sample above a tenth of +/// full scale, which the silence around it is nowhere near. +fn beep_at(samples: &[f32]) -> f64 { + let at = samples + .iter() + .position(|s| s.abs() > 0.1) + .expect("the fixture beeps"); + at as f64 / 2.0 / f64::from(RATE) +} + +/// When the flash shows, in timeline seconds: the first frame the composite maps +/// to a white picture, walked exactly as `PlaybackSession::try_frame` walks it +/// -- the decoder is opened over the span's *source* range and its frame numbers +/// come back through the span's own rate. +fn flash_at(project: &Project) -> f64 { + let span = project.composite_span_at(0).expect("a span at frame 0"); + let (source, in_frame) = span.from.expect("the span plays a clip"); + let path = &project.sources()[source].path; + let (_, frames, _) = DecodeSession::open_range(path, in_frame, in_frame + span.source_len()) + .expect("open the fixture's picture"); + for frame in frames { + // Mid-picture, so a stray edge pixel cannot answer for the frame. + let middle = frame.bgra.len() / 2 / 4 * 4; + if frame.bgra[middle] > 200 { + let timeline = span.start + span.speed.timeline_at(frame.index - in_frame); + return f64::from(timeline) / FPS; + } + } + panic!("the fixture flashes"); +} + +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { + let started = Instant::now(); + while !handle.is_finished() { + assert!(started.elapsed() < limit, "export did not finish"); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("a finished export has an outcome") +} + +fn out_path(name: &str, ext: &str) -> PathBuf { + std::env::temp_dir().join(format!("edith-speed-{name}-{}.{ext}", std::process::id())) +} + +/// The headline: a clip at 2x is half as long on the timeline, plays the same +/// source range, and its box is the one thing that moved. +#[test] +fn a_clip_at_2x_takes_half_the_timeline_and_the_same_source() { + let (mut project, _) = sync_project(); + let before = project.clips()[0]; + project + .set_speed(Lane::V1, 0, Speed::from_permille(2000)) + .expect("nothing is in the way of a clip that got shorter"); + let after = project.clips()[0]; + assert_eq!( + (after.in_frame, after.out_frame), + (before.in_frame, before.out_frame), + "the source range a trim and a split address is untouched" + ); + assert_eq!( + after.frames(), + before.frames().div_ceil(2), + "half the timeline frames, rounded" + ); + assert_eq!(project.timeline_frames(), after.frames()); + // ...and its sound with it, on the other lane: one rate for the group. + assert_eq!(project.speed_of(Lane::A1, 0).permille(), 2000); + assert_eq!(project.lane(Lane::A1)[0].end(), after.end()); +} + +/// The invariant a footprint may never break, over the whole legal range: a +/// clip always occupies at least one frame, whatever it is divided by. +#[test] +fn no_rate_ever_makes_a_clip_occupy_nothing() { + for permille in [250, 333, 500, 999, 1000, 1001, 1500, 2000, 3999, 4000] { + let speed = Speed::from_permille(permille); + for len in [1, 2, 3, 7, 30, 999] { + assert!( + speed.frames(len) >= 1, + "{len} source frames at {speed} occupies nothing" + ); + } + } +} + +/// Slowing a clip down makes it wider, and a lane may not overlap itself: the +/// refusal *names* the clip in the way, and costs no undo step. +#[test] +fn a_slow_down_into_the_next_clip_is_refused_by_name() { + let (mut project, meta) = sync_project(); + let half = meta.frame_count / 2; + assert!(project.split(half), "cut the take in two"); + let before = project.clips().to_vec(); + let text = project + .set_speed(Lane::V1, 0, Speed::from_permille(500)) + .expect_err("the first half cannot double in length where it sits") + .to_string(); + assert!(text.contains(&half.to_string()), "{text}"); + assert!(text.contains("0.50x"), "{text}"); + assert_eq!(project.clips(), before, "nothing moved"); + // ...and the refusal cost no undo step of its own: the one press left is + // the split's, which puts the take back together. + assert!(project.undo(), "the split is still the last thing undone"); + assert_eq!(project.clips().len(), 1, "the take is whole again"); + assert!(!project.undo(), "and nothing else was ever pushed"); +} + +/// One rate change is one undo press, for the whole linked group -- the picture +/// and the sound come back together. +#[test] +fn one_speed_change_is_one_undo_for_the_whole_group() { + let (mut project, _) = sync_project(); + let (video, audio) = (project.clips().to_vec(), project.lane(Lane::A1).to_vec()); + project + .set_speed(Lane::A1, 0, Speed::from_permille(2000)) + .expect("room enough"); + // A drag is one snapshot and then live writes, which is what keeps a + // gesture across the card's bar one undo and not forty. + for permille in [1500, 1750, 4000] { + project + .set_speed_live(Lane::A1, 0, Speed::from_permille(permille)) + .expect("room enough"); + } + assert!(project.undo(), "one press"); + assert_eq!(project.clips(), video, "the picture is back"); + assert_eq!(project.lane(Lane::A1), audio, "and its sound with it"); + assert!(!project.undo(), "there was only ever one step"); +} + +/// A rate follows the clip through a split and through the clipboard, exactly +/// as an equalizer does: both halves keep it, and so does a paste. +#[test] +fn speed_survives_a_split_and_a_paste() { + let (mut project, meta) = sync_project(); + project + .set_speed(Lane::V1, 0, Speed::from_permille(2000)) + .expect("room enough"); + let whole = project.clips()[0].frames(); + assert!(project.split(whole / 2), "a 2x clip cuts on any frame"); + let halves = project.clips().to_vec(); + assert_eq!(halves.len(), 2); + assert!( + halves.iter().all(|c| c.speed.permille() == 2000), + "both halves play at the rate the whole did" + ); + assert_eq!( + halves[0].frames() + halves[1].frames(), + whole, + "and they still add up to the clip that was cut" + ); + assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames"); + assert_eq!(halves[1].end(), whole, "the lane is unchanged in length"); + + let copied = halves[0]; + assert!(project.paste(whole, copied), "paste it at the end"); + let pasted = *project.clips().last().expect("something was pasted"); + assert_eq!(pasted.speed, copied.speed, "a copy carries the rate"); + assert_eq!( + pasted.frames(), + copied.frames(), + "and therefore the room it takes" + ); + let _ = meta; +} + +/// The one the anti-list is about: at 2x the beep still lands on the flash. The +/// picture comes off the decoder through the span's own rate and the sound comes +/// out of the resampler in the worker -- two independent paths, measured against +/// each other. +#[test] +fn the_beep_stays_on_the_flash_at_every_rate() { + // Where the fixture's own mark sits, measured rather than assumed: what the + // rates below are checked against is this, divided. + let (base, _) = sync_project(); + let (mark, mark_beep) = (flash_at(&base), beep_at(&play(&base))); + println!("real time: flash at {mark:.3}s, beep at {mark_beep:.3}s"); + assert!( + (mark - mark_beep).abs() <= 1.0 / FPS && mark > 2.0 / FPS, + "the fixture's flash and beep are its whole point: {mark:.3}s / {mark_beep:.3}s" + ); + for permille in [2000, 500, 1500] { + let (mut project, _) = sync_project(); + let speed = Speed::from_permille(permille); + project + .set_speed(Lane::V1, 0, speed) + .expect("one clip on the timeline has room for any rate"); + let flash = flash_at(&project); + let beep = beep_at(&play(&project)); + let apart = (flash - beep).abs(); + println!("{speed}: flash at {flash:.3}s, beep at {beep:.3}s, {apart:.3}s apart"); + assert!( + apart <= 1.0 / FPS, + "{speed}: the beep is {apart:.3}s off the flash, which is more than a frame" + ); + // ...and both of them moved: at 2x the mark is at half its own time, and + // a test that measured two things standing still would pass forever. + let expected = mark / speed.as_f64(); + assert!( + (flash - expected).abs() <= 2.0 / FPS, + "{speed}: the flash should be around {expected:.3}s, not {flash:.3}s" + ); + } +} + +/// A WAV of a speeded timeline is as long as the timeline says, and it is the +/// sound that was heard -- the beep in the file sits where the preview put it. +#[test] +fn a_wav_export_of_a_2x_timeline_matches_the_preview() { + let (mut project, meta) = sync_project(); + project + .set_speed(Lane::V1, 0, Speed::from_permille(2000)) + .expect("room enough"); + let frames = project.timeline_frames(); + let heard = beep_at(&play(&project)); + let out = out_path("wav", "wav"); + let handle = engine::export::start( + project, + meta, + &out, + &ExportSettings { + format: Format::Wav, + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(120)).expect("wav export"); + let mut reader = hound::WavReader::open(&out).expect("read the export back"); + let spec = reader.spec(); + let samples: Vec = reader + .samples::() + .map(|s| f32::from(s.expect("a sample")) / f32::from(i16::MAX)) + .collect(); + let written = samples.len() / usize::from(spec.channels); + let expected = (f64::from(frames) / FPS * f64::from(RATE)).round() as usize; + assert!( + written.abs_diff(expected) <= spec.sample_rate as usize / 30, + "the file is {written} frames and the timeline is {expected}" + ); + let in_file = beep_at(&samples); + assert!( + (in_file - heard).abs() <= 1.0 / FPS, + "the beep is at {in_file:.3}s in the file and was at {heard:.3}s in the preview" + ); + std::fs::remove_file(&out).ok(); +} + +/// A picture export cannot re-time a clip, so it says so and writes nothing -- +/// which is the one thing it may not do silently. Both picture formats, because +/// a rule that held for one of them would be the surprise. +#[test] +fn a_picture_export_refuses_a_speeded_clip_by_name() { + for format in [Format::Mp4, Format::Av1] { + let (mut project, meta) = sync_project(); + project + .set_speed(Lane::V1, 0, Speed::from_permille(2000)) + .expect("room enough"); + let out = out_path("refuse", "mp4"); + let handle = engine::export::start( + project, + meta.clone(), + &out, + &ExportSettings { + format, + ..Default::default() + }, + ); + let text = wait(&handle, Duration::from_secs(120)) + .expect_err("a speeded timeline is not exportable as a picture") + .to_string(); + assert!(text.contains("2.00x"), "{format:?}: {text}"); + assert!(text.contains("V1"), "{format:?}: {text}"); + assert!(text.contains("WAV"), "{format:?}: {text}"); + assert!(!out.exists(), "{format:?}: no file was written"); + } +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index fdeaa59..12106b6 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -113,6 +113,23 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_av1.mkv +# Sync fixture: one flash and one beep, at the same instant. Black picture with +# a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that +# stretch — so a test can find each of them and say how far apart they came out. +# What it is for is *speed*: a re-timed clip that drifts puts the beep somewhere +# the flash is not, and nothing else in the fixture set has a mark to measure +# that against. Same 30 fps / 44.1k stereo shape as test_av.mp4, so it can share +# a timeline with the rest. +# The beep is silence-then-tone-then-silence rather than a gated tone: lavfi's +# `sine` comes out at an eighth of full scale, and a mark a test looks for has +# to be plainly louder than anything around it. +ffmpeg -y -f lavfi -i "color=c=black:s=320x180:r=30:d=3" \ + -f lavfi -i "sine=frequency=1000:duration=0.1:sample_rate=44100" \ + -filter_complex "[0:v]drawbox=x=0:y=0:w=iw:h=ih:color=white:t=fill:\ +enable='between(t,1,1.1)'[v];\ +[1:a]volume=6,aformat=channel_layouts=stereo,adelay=1000|1000,apad=whole_dur=3[a]" \ + -map "[v]" -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ + -c:a aac -b:a 128k assets/test_speed_sync.mp4 # Mismatch fixture: different resolution and no audio track at all, so import # has something concrete to refuse. ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \