diff --git a/crates/app/src/export_ui.rs b/crates/app/src/export_ui.rs index a675131..6ca6bd0 100644 --- a/crates/app/src/export_ui.rs +++ b/crates/app/src/export_ui.rs @@ -887,6 +887,9 @@ pub(crate) fn export_settings( // anybody. intra_only: false, keep_source_colour: false, + // Set by `start_export`, which knows the player's mark; this helper is + // also asked for the estimate alone, which has no range to give. + range: None, } } diff --git a/crates/app/src/interact.rs b/crates/app/src/interact.rs index 17c9830..ebfeb6a 100644 --- a/crates/app/src/interact.rs +++ b/crates/app/src/interact.rs @@ -116,6 +116,37 @@ pub(crate) struct Trim { /// still the body. pub(crate) const EDGE_W: f32 = 6.; +/// A fade handle's own hit zone, at each *top* corner of an audio clip's box -- +/// never the trim strip's height, which is [`EDGE_W`] wide down the whole box +/// ([`trims`]) and would swallow a fade press if the two overlapped. Sitting +/// just inside the trim strip rather than on top of it, so one gesture is +/// still exactly one thing: the outer [`EDGE_W`] column lengthens or shortens +/// the clip, this small square at its top corner shapes the fade instead. +pub(crate) const FADE_HANDLE_W: f32 = 10.; +/// Only the label row's own height tall -- a fade handle reaching down into +/// the waveform would sit on top of the body drag and the waveform's own +/// tooltip both. +pub(crate) const FADE_HANDLE_H: f32 = 10.; + +/// A fade handle being dragged: which clip, which end (`is_in` for the head's +/// ramp-up, the tail's ramp-down otherwise), and the gesture's own state -- +/// `press_x` to measure the pixel delta from, `start` the fade length the +/// press found, `to` what the drag is showing right now, `cap` the clip's own +/// length in frames ([`Project::set_fade_in`]'s own clamp, so the drag never +/// draws past what a release would refuse). One clip, no group: unlike a trim +/// a fade never drags a neighbour, and unlike a caption it never wants a +/// track's walls. +#[derive(Clone, Copy)] +pub(crate) struct FadeDrag { + pub(crate) lane: Lane, + pub(crate) idx: usize, + pub(crate) is_in: bool, + pub(crate) press_x: Pixels, + pub(crate) start: u32, + pub(crate) to: u32, + pub(crate) cap: u32, +} + /// Whether a clip box this wide gets its two trim strips at all. Below three /// handles wide the pair would occlude the whole box: every press on it would /// trim, and the clip could not be selected, dragged to another lane or picked diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 559068a..5020786 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -80,6 +80,14 @@ actions! { /// by what they are for. PrevSyncPoint, NextSyncPoint, + /// Marks the playhead as an export's in point. The out point wraps around + /// it if the mark lands past the current out ([`ordered_range`]). + SetIn, + /// The out point's pair. Ordered the same way against whatever in point + /// stands already. + SetOut, + /// Drops the mark: an export goes back to the whole timeline. + ClearRange, Export, Save, Copy, @@ -104,6 +112,7 @@ actions! { ZoomOut, ZoomFit, Undo, + Redo, AddVideoLane, AddAudioLane, RemoveVideoLane, @@ -121,6 +130,15 @@ actions! { Equalizer, Speed, Silence, + /// Crossfades the selected audio clip into its neighbour ([`Project::crossfade`]): + /// two adjacent clips picked on one lane, or a single pick faded into the + /// clip right after it. + Crossfade, + /// Dissolves the selected video clip into its neighbour + /// ([`Project::set_transition_out`]): two adjacent clips picked on one + /// lane, or a single pick dissolved into the clip right after it. A + /// second press on a clip that already dissolves removes it instead. + Dissolve, Mix, ToggleSnap, ToggleSubtitles, @@ -170,6 +188,9 @@ impl ActionId { ActionId::GoEnd => "Go to the last frame", ActionId::PrevSyncPoint => "Previous sync point (a cut here is copied, not re-encoded)", ActionId::NextSyncPoint => "Next sync point (a cut here is copied, not re-encoded)", + ActionId::SetIn => "Mark in (export range)", + ActionId::SetOut => "Mark out (export range)", + ActionId::ClearRange => "Clear the export range", ActionId::Export => "Export", ActionId::Save => "Save", ActionId::Copy => "Copy", @@ -194,6 +215,7 @@ impl ActionId { ActionId::ZoomOut => "Zoom out of the timeline", ActionId::ZoomFit => "Fit the whole timeline on screen", ActionId::Undo => "Undo", + ActionId::Redo => "Redo", ActionId::AddVideoLane => "Add a video track", ActionId::AddAudioLane => "Add an audio track", ActionId::RemoveVideoLane => "Remove the last video track (it must be empty)", @@ -207,6 +229,8 @@ impl ActionId { ActionId::Equalizer => "Equalizer", ActionId::Speed => "Speed (tape)…", ActionId::Silence => "Silences: cut or speed up…", + ActionId::Crossfade => "Crossfade into the next clip", + ActionId::Dissolve => "Dissolve into the next clip", ActionId::Mix => "Mix: track volumes and the limiter…", ActionId::ToggleSnap => "Snap on / off (edges, the playhead, the start)", ActionId::ToggleSubtitles => "Subtitles on / off over the picture", @@ -235,6 +259,9 @@ impl ActionId { ActionId::GoEnd => "go-end", ActionId::PrevSyncPoint => "prev-sync-point", ActionId::NextSyncPoint => "next-sync-point", + ActionId::SetIn => "set-in", + ActionId::SetOut => "set-out", + ActionId::ClearRange => "clear-range", ActionId::Export => "export", ActionId::Save => "save", ActionId::Copy => "copy", @@ -256,6 +283,7 @@ impl ActionId { ActionId::ZoomOut => "zoom-out", ActionId::ZoomFit => "zoom-fit", ActionId::Undo => "undo", + ActionId::Redo => "redo", ActionId::AddVideoLane => "add-video-lane", ActionId::AddAudioLane => "add-audio-lane", ActionId::RemoveVideoLane => "remove-video-lane", @@ -269,6 +297,8 @@ impl ActionId { ActionId::Equalizer => "equalizer", ActionId::Speed => "speed", ActionId::Silence => "silence", + ActionId::Crossfade => "crossfade", + ActionId::Dissolve => "dissolve", ActionId::Mix => "mix", ActionId::ToggleSnap => "toggle-snap", ActionId::ToggleSubtitles => "toggle-subtitles", @@ -301,7 +331,10 @@ impl ActionId { | ActionId::GoStart | ActionId::GoEnd | ActionId::PrevSyncPoint - | ActionId::NextSyncPoint => Category::Playback, + | ActionId::NextSyncPoint + | ActionId::SetIn + | ActionId::SetOut + | ActionId::ClearRange => Category::Playback, ActionId::Copy | ActionId::Paste | ActionId::Select @@ -319,7 +352,9 @@ impl ActionId { // The scan reads a clip's sound, but what it does is edit the // timeline the clip is on -- it is a clip card like the three // above it, opened on whichever half was picked. - | ActionId::Silence => Category::Clips, + | ActionId::Silence + | ActionId::Crossfade + | ActionId::Dissolve => 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. // Neither is how much of the timeline the panel shows: a zoom edits @@ -353,6 +388,7 @@ impl ActionId { | ActionId::Detach | ActionId::Group | ActionId::Undo + | ActionId::Redo | ActionId::AddVideoLane | ActionId::AddAudioLane | ActionId::RemoveVideoLane @@ -823,6 +859,16 @@ impl Keymap { // step through the same timeline by the source's own grid. b(ActionId::PrevSyncPoint, "[", true), b(ActionId::NextSyncPoint, "]", true), + // The mark pair, on the letters every editor already means them + // by: bare, since a mark is set as often as a step and nothing + // else in this table answers to either. + b(ActionId::SetIn, "i", false), + b(ActionId::SetOut, "o", false), + // The clear takes the ctrl chord: not a stroke to hit setting + // one mark and reaching for the other. Free -- "u" bare is the + // silence card, and nothing else in this table answers to + // ctrl+u. + b(ActionId::ClearRange, "u", true), b(ActionId::Export, "e", false), b(ActionId::Save, "s", true), b(ActionId::Copy, "c", true), @@ -874,6 +920,9 @@ impl Keymap { b(ActionId::ZoomFit, "0", true), b(ActionId::Undo, "z", false), b(ActionId::Undo, "z", true), + // Bare "y" is SubtitleStyle's, so redo takes only the ctrl + // chord -- the conventional pairing with ctrl+z either way. + b(ActionId::Redo, "y", true), // The unshifted initials of what they add. Both were free -- // the copy and paste chords are the *ctrl* ones -- and a track // is added often enough to deserve a key that is one press. @@ -919,6 +968,16 @@ impl Keymap { // delete (x and delete) -- what it opens is a card that can cut // forty places at once. b(ActionId::Silence, "u", false), + // Crossfade takes ctrl+f: the mnemonic letter for "fade", with + // ctrl its own room now that plain "f" is the mix card's own + // (below) -- the same letter, the modifier telling them apart. + b(ActionId::Crossfade, "f", true), + // Dissolve takes ctrl+x: the join it draws on the timeline is + // an X (widgets.rs, dissolve_glyph) -- "d" itself is taken + // both plain (Detach) and, in the keymap's own rebind test, + // as the free chord it rebinds Delete onto, so this reaches + // for the shape instead of the word. + b(ActionId::Dissolve, "x", true), // The mix card takes "f", for the faders on it: "m" would be // the word but it is the monitoring mute, which is this // machine's volume and not the project's -- two things one key @@ -1231,7 +1290,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 57); + assert_eq!(k.entries().len(), 63); assert_eq!(k.lookup("f11", false), Some(ActionId::Fullscreen)); assert_eq!(k.lookup("w", false), Some(ActionId::Screenshot)); assert_eq!(k.lookup("y", false), Some(ActionId::SubtitleStyle)); @@ -1255,6 +1314,9 @@ mod tests { assert_eq!(k.lookup("]", true), Some(ActionId::NextSyncPoint)); assert_eq!(k.lookup("[", false), Some(ActionId::SelectPrev)); assert_eq!(k.lookup("]", false), Some(ActionId::SelectNext)); + assert_eq!(k.lookup("i", false), Some(ActionId::SetIn)); + assert_eq!(k.lookup("o", false), Some(ActionId::SetOut)); + assert_eq!(k.lookup("u", true), Some(ActionId::ClearRange)); assert_eq!(k.lookup("e", false), Some(ActionId::Export)); assert_eq!(k.lookup("s", true), Some(ActionId::Save)); assert_eq!(k.lookup("c", true), Some(ActionId::Copy)); @@ -1276,6 +1338,7 @@ mod tests { assert_eq!(k.lookup("r", true), Some(ActionId::Resolution)); assert_eq!(k.lookup("z", false), Some(ActionId::Undo)); assert_eq!(k.lookup("z", true), Some(ActionId::Undo)); + assert_eq!(k.lookup("y", true), Some(ActionId::Redo)); // The track keys are the bare letters; the ctrl ones stay copy/paste. assert_eq!(k.lookup("v", false), Some(ActionId::AddVideoLane)); assert_eq!(k.lookup("a", false), Some(ActionId::AddAudioLane)); diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index a595d46..4f6d7b3 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -109,6 +109,10 @@ struct Player { /// top on reaching its end instead of stopping there. One flag for both, /// since only one of them is ever playing at a time. loop_on: bool, + /// The in/out mark an export is clipped to, half-open `[start, end)` in + /// timeline frames -- `None` for the whole timeline. Session state, like + /// the mark itself: never saved to a `.edith` ([`ExportSettings::range`]). + range: Option<(u32, u32)>, /// Timeline seconds -> frame index, so the clock can be compared to what /// the decoder hands over. fps: f64, @@ -273,6 +277,10 @@ struct Player { /// `scrubbing`'s reason: a 6 px strip is not where the pointer stays. See /// [`Trim`]. trim: Option, + /// A drag that started on a fade handle, tracked on the root for the same + /// reason a trim is: a 10 px square is not where the pointer stays. See + /// [`FadeDrag`]. + fade_drag: Option, /// How far into the clip the last press on a box landed, in timeline /// frames: what a drag lets go of is the *point that was grabbed*, so the /// head lands that much in front of the pointer and the clip does not jump @@ -385,6 +393,37 @@ struct Player { /// or the one derived beside the media it started as. Saving twice /// overwrites the same file rather than making a second one. project_path: PathBuf, + /// Whether an edit has landed since the sidecar last caught up with it -- + /// set at every edit's own door ([`Player::mark_dirty`]) and cleared once + /// [`Player::autosave_tick`] has written it out. `project_path` itself is + /// never touched here: only [`Player::save_project`] writes the real file. + autosave_dirty: bool, + /// When the dirty flag above was last set, so a tick can debounce: a + /// sidecar write waits until the hand has been off the timeline for a + /// few seconds, rather than chasing every pointer sample of a drag. + autosave_last_edit: Option, + /// When the sidecar was last actually written, so a long unbroken run of + /// edits still gets caught by the periodic safety net rather than being + /// debounced forever. + autosave_last_run: Option, + /// A sidecar found newer than the project it sits beside, offered on the + /// notice bar the moment that project opens ([`Player::install_project`]). + /// The path is the sidecar's own, so accepting it needs nowhere else to + /// look; declining or answering any other key just drops it here -- + /// `project_path` is never touched by either path, only a manual save + /// writes the real file. + recovery_sidecar: Option, + /// Whether `project_path` names a file this window itself put there -- + /// loaded from a `.edith` ([`Player::install_project`]) or written by a + /// manual save ([`Player::save_project`]) -- rather than one merely + /// derived beside an imported media file. [`Player::autosave_tick`] + /// requires it: a path derived from `media.mp4` names `media.edith` + /// whether or not that file is the user's own saved project, and writing + /// a sidecar beside a *foreign* `.edith` the user never opened is what + /// let a scratch timeline's autosave outdate and "recover" over a real + /// one. `mark_dirty` does not touch this -- an edit earns nothing an open + /// or save has not already granted. + autosave_armed: bool, /// Which stroke means what, and what every shortcut on screen is called. /// The one place either question is answered. keymap: Keymap, @@ -740,6 +779,7 @@ fn main() { preview_playing: false, player_fullscreen: false, loop_on: false, + range: None, // Full and unmuted, which is what the session it was just // handed is already set to: nothing to push at startup. volume: Volume::default(), @@ -792,6 +832,7 @@ fn main() { splits: Splits::default(), split_drag: None, trim: None, + fade_drag: None, grab: 0, snap: true, subs_on: true, @@ -813,6 +854,11 @@ fn main() { // export beside the picture, a save beside it too. export_path: PathBuf::new(), project_path: PathBuf::new(), + autosave_dirty: false, + autosave_last_edit: None, + autosave_last_run: None, + recovery_sidecar: None, + autosave_armed: false, keymap: keymap.clone(), keys_open: false, keys_search: String::new(), @@ -899,6 +945,7 @@ fn main() { // Nothing else takes focus, and without it the key listener // above is never reached. window.focus(&player.read(cx).focus); + player.update(cx, |player, cx| player.start_autosave(cx)); player }, ) diff --git a/crates/app/src/menus.rs b/crates/app/src/menus.rs index 7845172..35dcb3e 100644 --- a/crates/app/src/menus.rs +++ b/crates/app/src/menus.rs @@ -142,7 +142,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. -pub(crate) const MENU_ITEMS: [ActionId; 14] = [ +pub(crate) const MENU_ITEMS: [ActionId; 15] = [ ActionId::Cut, // The clipboard pair, which had no door but a chord: copy takes the clip the // menu names, and paste is the timeline's rather than this clip's -- the @@ -160,6 +160,10 @@ pub(crate) const MENU_ITEMS: [ActionId; 14] = [ // was clicked -- and a card only a stroke could open is one a pointer never // finds. ActionId::Silence, + // The dissolve is a video clip's own join, same door as the crossfade + // above it would be for sound -- a stroke-only pair, opened here on + // whichever half was clicked. + ActionId::Dissolve, ActionId::Color, ActionId::Fit, ActionId::ToggleMute, diff --git a/crates/app/src/player/actions.rs b/crates/app/src/player/actions.rs index 78f817b..59d0753 100644 --- a/crates/app/src/player/actions.rs +++ b/crates/app/src/player/actions.rs @@ -29,6 +29,35 @@ impl Player { // answer with a line about exports. Enable::Hidden(_) => return, } + // The one choke point for every action that changes what a save would + // write: the timeline's clips, the tracks that hold them, the subtitle + // tracks. Marked before the match rather than once per arm below -- + // an autosave a beat early over a refusal (nothing to regroup, say) + // costs nothing a real edit would not have earned anyway, and one list + // here is the whole answer instead of fifteen scattered calls. + if matches!( + action, + ActionId::Paste + | ActionId::Cut + | ActionId::Regroup + | ActionId::Detach + | ActionId::Group + | ActionId::Delete + | ActionId::Lift + | ActionId::Undo + | ActionId::Redo + | ActionId::AddVideoLane + | ActionId::RemoveVideoLane + | ActionId::AddAudioLane + | ActionId::RemoveAudioLane + | ActionId::AddSubtitleLane + | ActionId::RemoveSubtitleLane + | ActionId::ImportSubtitles + | ActionId::Crossfade + | ActionId::Dissolve + ) { + self.mark_dirty(); + } match action { ActionId::Play => self.toggle_or_restart(cx), // No session touched at all: the pump reads the flag itself at @@ -49,12 +78,20 @@ impl Player { // where the next one is depends on the file rather than on the rate. ActionId::PrevSyncPoint => self.jump_sync(false, cx), ActionId::NextSyncPoint => self.jump_sync(true, cx), + ActionId::SetIn => self.set_in(cx), + ActionId::SetOut => self.set_out(cx), + ActionId::ClearRange => { + self.range = None; + cx.notify(); + } ActionId::Export => self.open_export(cx), ActionId::Save => self.save_project(cx), ActionId::Copy => self.copy_selected(), ActionId::Paste => self.paste(cx), ActionId::Cut => self.cut(cx), ActionId::Regroup => self.regroup(cx), + ActionId::Crossfade => self.crossfade_selected(cx), + ActionId::Dissolve => self.dissolve_selected(cx), ActionId::Detach => self.detach(cx), ActionId::Group => self.group(cx), ActionId::Select => self.select_under_playhead(cx), @@ -73,6 +110,7 @@ impl Player { ActionId::ZoomOut => self.zoom(1. / ZOOM_STEP, None, cx), ActionId::ZoomFit => self.zoom_fit(cx), ActionId::Undo => self.undo(cx), + ActionId::Redo => self.redo(cx), ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx), ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx), // The last track of that kind: the one the add key put there, so the @@ -382,6 +420,29 @@ impl Player { cx.notify(); } + /// Marks the playhead as an export's in point. `ordered_range` keeps the + /// pair legal whichever one lands past the other. + pub(crate) fn set_in(&mut self, cx: &mut Context) { + let Some(session) = &self.session else { + return; + }; + let at = frame_at(session.now(), self.fps); + let out = self.range.map_or(at, |(_, e)| e); + self.range = Some(ordered_range(at, out)); + cx.notify(); + } + + /// The out point's pair. + pub(crate) fn set_out(&mut self, cx: &mut Context) { + let Some(session) = &self.session else { + return; + }; + let at = frame_at(session.now(), self.fps); + let start = self.range.map_or(at, |(s, _)| s); + self.range = Some(ordered_range(start, at)); + cx.notify(); + } + pub(crate) fn undo(&mut self, cx: &mut Context) { if self.session.as_mut().is_some_and(PlaybackSession::undo) { self.reset_after_reseek(); @@ -390,6 +451,14 @@ impl Player { cx.notify(); } + pub(crate) fn redo(&mut self, cx: &mut Context) { + if self.session.as_mut().is_some_and(PlaybackSession::redo) { + self.reset_after_reseek(); + } + self.selected.clear(); + cx.notify(); + } + /// The stroke a waiting row was after: it becomes the whole of what reaches /// that action, which is what the row was showing. A chord another action /// already holds is refused by the keymap and the row keeps waiting, so the @@ -430,3 +499,30 @@ impl Player { self.notify_user(text.into()); } } + +/// The half-open range a mark and a mark make, in either order: a person's two +/// keystrokes are not promised to land in order, so this is what turns +/// whichever came second into the pair `Player::start_export` wants a range in +/// -- and never an empty one, since a single frame marked in and out twice is +/// still a frame to export. +pub(crate) fn ordered_range(a: u32, b: u32) -> (u32, u32) { + let (start, end) = if a <= b { (a, b) } else { (b, a) }; + if start == end { + (start, start + 1) + } else { + (start, end) + } +} + +#[cfg(test)] +mod tests { + use super::ordered_range; + + #[test] + fn ordered_range_never_empty_and_swaps_a_reversed_pair() { + assert_eq!(ordered_range(5, 10), (5, 10)); + assert_eq!(ordered_range(10, 5), (5, 10)); + assert_eq!(ordered_range(7, 7), (7, 8)); + assert_eq!(ordered_range(0, 0), (0, 1)); + } +} diff --git a/crates/app/src/player/cards.rs b/crates/app/src/player/cards.rs index 0cc9571..167d598 100644 --- a/crates/app/src/player/cards.rs +++ b/crates/app/src/player/cards.rs @@ -330,6 +330,7 @@ impl Player { false => session.set_color(lane, idx, grade), }; if took { + self.mark_dirty(); self.reset_after_reseek(); } cx.notify(); @@ -482,7 +483,10 @@ impl Player { false => session.set_speed(lane, idx, speed), }; match wrote { - Ok(()) => self.reset_after_reseek(), + Ok(()) => { + self.mark_dirty(); + self.reset_after_reseek(); + } Err(e) => self.notify_user(e.to_string().into()), } } @@ -695,6 +699,10 @@ impl Player { /// ([`engine::PlaybackSession::set_lane_gain_db`]). pub(crate) fn nudge_mix(&mut self, steps: i32, cx: &mut Context) { let lanes = self.mix_lanes(); + if self.session.is_none() { + return; + } + self.mark_dirty(); let Some(session) = self.session.as_mut() else { return; }; @@ -1230,6 +1238,7 @@ impl Player { let params = (!self.eq_params.is_identity()).then(|| self.eq_params.clone()); if let Some(session) = &mut self.session { session.set_eq(lane, idx, params); + self.mark_dirty(); } // `set_eq` reseeks inside the engine -- that is what makes the change // audible at once -- and a reseek is what these flags are about. diff --git a/crates/app/src/player/export.rs b/crates/app/src/player/export.rs index 6eac12b..299cb13 100644 --- a/crates/app/src/player/export.rs +++ b/crates/app/src/player/export.rs @@ -491,7 +491,7 @@ impl Player { /// sound: there is nothing to write either way. pub(crate) fn audio_rate_refusal(&self) -> Option<&'static str> { match &self.session { - Some(session) => session.audio_rate_refusal(self.format), + Some(session) => session.audio_rate_refusal(self.format, self.range.is_some()), None => Some("no sound to write"), } } @@ -650,6 +650,7 @@ impl Player { // Set here rather than inside `export_settings`, which the card also // calls for the *estimate* and which nothing else needs a subtitle for. settings.subtitles = self.export_subs(); + settings.range = self.range; let Some(session) = &mut self.session else { self.notify_user("NOTHING TO EXPORT — open a file first".into()); cx.notify(); diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 3126edf..23434ac 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -3,6 +3,12 @@ use crate::*; +/// How long an edit must sit idle before the sidecar catches up with it. +const AUTOSAVE_DEBOUNCE: Duration = Duration::from_secs(5); +/// The longest a run of edits with no gap between them goes unsaved: the +/// periodic half of "debounced + periodic". +const AUTOSAVE_PERIOD: Duration = Duration::from_secs(60); + impl Player { /// The one way a library row reaches the timeline: the Add button and a row /// dragged onto a lane both come here, so there is a single answer to what @@ -976,6 +982,10 @@ impl Player { // opening another clip is not a change of mind about that. self.export_path = retarget(&export_path(path), self.format); self.project_path = project_path(path); + // Derived, not opened: `project_path` here is a guess at where + // a save would land, not a file this window has any business + // writing an autosave beside until a manual save earns it. + self.autosave_armed = false; self.name = file_name(path).into(); self.reset_after_reseek(); let name = file_name(path); @@ -1254,6 +1264,9 @@ impl Player { self.auto_proxies_on = session.auto_proxies(); } self.project_path = path.to_path_buf(); + // Opened from the `.edith` itself: the file this window will + // autosave beside is the one the user actually chose. + self.autosave_armed = true; self.name = file_name(path).into(); // A copied clip names its source by index, which means a // different file -- or none -- in another project. @@ -1282,7 +1295,19 @@ impl Player { // reaches the screen the way a seek's does. The old picture is // released by the swap in `pump`, as after any other seek. self.reset_after_reseek(); - format!("LOADED {}{}", file_name(path), silent.unwrap_or_default()) + // Offered right after the load it is about, on top of the + // "LOADED" line rather than instead of it: a person deciding + // whether to recover still gets to see what they *did* open. + self.recovery_sidecar = Self::recovery_offer(path); + let recovery = self.recovery_sidecar.as_ref().map(|_| { + " — a newer autosave was found: enter recovers it, any other key keeps this" + }); + format!( + "LOADED {}{}{}", + file_name(path), + silent.unwrap_or_default(), + recovery.unwrap_or_default() + ) } Err(e) => format!("OPEN FAILED: {e}"), }; @@ -1299,7 +1324,23 @@ impl Player { .as_ref() .map(|session| session.save_project(&self.project_path)); let text = match saved { - Some(Ok(())) => format!("SAVED {}", file_name(&self.project_path)), + Some(Ok(())) => { + // The manual save is now the newest copy of the timeline, so + // the sidecar's job is done -- left behind it would outlive + // its use and, if it later grew younger than a *later* manual + // save through some clock oddity, could be offered as + // "recovery" over a file that already holds everything it did. + if let Some(sidecar) = Self::autosave_path(&self.project_path) { + let _ = std::fs::remove_file(sidecar); + } + self.autosave_dirty = false; + self.autosave_last_edit = None; + // A manual save is exactly the event this flag exists to + // require: whatever `project_path` was derived from, it now + // names a file the user just chose to write. + self.autosave_armed = true; + format!("SAVED {}", file_name(&self.project_path)) + } Some(Err(e)) => format!("SAVE FAILED: {e}"), None => "NOTHING TO SAVE — open a file first".to_string(), }; @@ -1308,6 +1349,142 @@ impl Player { cx.notify(); } + /// Marks that an edit has landed since the sidecar last caught up, and + /// when: the door every edit that funnels through [`Player::act`] or a + /// timeline gesture calls on its way through. Cheap and safe to call on a + /// refusal too -- an autosave a beat early costs nothing a real edit + /// would not have earned anyway. + pub(crate) fn mark_dirty(&mut self) { + self.autosave_dirty = true; + self.autosave_last_edit = Some(Instant::now()); + } + + /// Where the autosave for `project_path` lives: beside it, named after it. + /// A project with no path yet (nothing saved, nothing opened) has nowhere + /// beside it to write to, so autosave sits out until the first manual + /// save gives it one -- the same file the recovery check on open reads. + fn autosave_path(project_path: &Path) -> Option { + (!project_path.as_os_str().is_empty()).then(|| { + let mut name = project_path.as_os_str().to_owned(); + name.push(".autosave"); + PathBuf::from(name) + }) + } + + /// Answers the recovery notice with `enter`: opens the sidecar + /// [`recovery_sidecar`](Self::recovery_sidecar) named and installs it the + /// same way any other `.edith` lands, but naming the *real* project's + /// path -- so the sidecar's contents replace the timeline in memory while + /// `project_path` keeps pointing at the user's own file, exactly as it did + /// before this call. Nothing here ever writes that file: the next thing to + /// touch it is still only a manual save. + pub(crate) fn recover_from_sidecar(&mut self, cx: &mut Context) { + let Some(sidecar) = self.recovery_sidecar.take() else { + return; + }; + let project_path = self.project_path.clone(); + let opened = PlaybackSession::open_project(&sidecar).map_err(|e| e.to_string()); + self.install_project(&project_path, opened, cx); + // `install_project` just re-ran the same mtime check on its way in and + // found the same sidecar still younger (recovering writes nothing to + // either file) -- offering the recovery it was just asked for right + // back would be the one loop in this feature. + self.recovery_sidecar = None; + } + + /// Answers the recovery notice with anything but `enter`: the sidecar is + /// discarded, on disk as well as in memory. Left behind, an unread + /// autosave from a scratch session would keep outdating the real project + /// it sits beside and reappear as "recovery" on every open of that file + /// (reference-editor behaviour: a declined backup is discarded, not kept + /// around to ask again). Pure at the path level so it needs no `Player` + /// to test -- a missing sidecar is not an error, only a no-op. + pub(crate) fn discard_sidecar(sidecar: &Path) { + let _ = std::fs::remove_file(sidecar); + } + + /// Whether `project_path` has a sidecar beside it that outdates the file + /// itself: the sidecar exists, the project exists, and the sidecar's mtime + /// is strictly the younger of the two. Pure and file-system-only -- no + /// session, no `Player` -- so [`install_project`](Self::install_project) + /// asks it before anything is loaded and a test can ask it with nothing + /// but two paths on disk. A missing project file (a `.edith` opened for + /// the first time from somewhere else) or a missing/older sidecar both + /// answer `None`: there is nothing here a person did not just open on + /// their own. + fn recovery_offer(project_path: &Path) -> Option { + let sidecar = Self::autosave_path(project_path)?; + let project_mtime = std::fs::metadata(project_path).and_then(|m| m.modified()).ok()?; + let sidecar_mtime = std::fs::metadata(&sidecar).and_then(|m| m.modified()).ok()?; + (sidecar_mtime > project_mtime).then_some(sidecar) + } + + /// Starts the one background loop that ticks the autosave: every five + /// seconds, forever, for as long as the window is up. Cheap to run idle -- + /// a tick with nothing dirty does nothing but reschedule itself -- so one + /// loop for the window's whole life is simpler than arming and disarming + /// a timer around every edit. + pub(crate) fn start_autosave(&mut self, cx: &mut Context) { + cx.spawn(async move |this, cx| { + loop { + cx.background_executor() + .timer(std::time::Duration::from_secs(5)) + .await; + if this.update(cx, |this, cx| this.autosave_tick(cx)).is_err() { + return; + } + } + }) + .detach(); + } + + /// Whether a tick is allowed to write at all: armed (`project_path` names + /// a file this window opened or saved -- see `autosave_armed`), dirty, + /// and not mid-export. Pure and split out from [`autosave_tick`](Self::autosave_tick) + /// for the same reason [`recovery_offer`](Self::recovery_offer) is: a test + /// can ask it with three bools, with no `Player` to build. + fn autosave_gate(armed: bool, dirty: bool, exporting: bool) -> bool { + armed && dirty && !exporting + } + + /// One tick of the loop above. Writes the sidecar when an edit has been + /// idle for [`AUTOSAVE_DEBOUNCE`] (the debounce) or dirty edits have gone + /// unwritten for [`AUTOSAVE_PERIOD`] (the periodic safety net for a run + /// that never goes idle), and never while an export is running -- the two + /// would fight the same disk and the same worker for nothing an export + /// needs. Failure is a stderr line, never a notice: a sidecar losing a + /// write is not something a person can do anything about right now, and a + /// modal over it would be worse than the risk it is guarding against. + fn autosave_tick(&mut self, cx: &mut Context) { + if !Self::autosave_gate(self.autosave_armed, self.autosave_dirty, self.exporting().is_some()) { + return; + } + let now = Instant::now(); + let idle = self + .autosave_last_edit + .map_or(true, |t| now.duration_since(t) >= AUTOSAVE_DEBOUNCE); + let overdue = self + .autosave_last_run + .map_or(true, |t| now.duration_since(t) >= AUTOSAVE_PERIOD); + if !idle && !overdue { + return; + } + let Some(sidecar) = Self::autosave_path(&self.project_path) else { + return; + }; + let Some(session) = self.session.as_ref() else { + return; + }; + match session.save_project(&sidecar) { + Ok(()) => { + self.autosave_dirty = false; + self.autosave_last_run = Some(now); + } + Err(e) => eprintln!("AUTOSAVE FAILED: {e}"), + } + cx.notify(); + } + /// A new empty track under the ones already there. One undo step in the /// engine, so the stroke that takes back an edit takes back a track too, and /// no reseek: nothing plays differently until something is dropped on it. @@ -1416,6 +1593,7 @@ impl Player { cx.notify(); return; }; + self.mark_dirty(); if moved != lane { self.selected.clear(); self.context_menu = None; @@ -1477,3 +1655,110 @@ impl Player { } } } + +#[cfg(test)] +mod autosave_tests { + use super::*; + + /// The three answers [`Player::recovery_offer`] gives, off nothing but a + /// project file and a sidecar's mtimes: younger sidecar offers it, an + /// older one or none at all offers nothing. Nowhere near a `Player` or a + /// `PlaybackSession` -- the helper reads only the filesystem, which is + /// what makes it askable from a test at all ([`Player`] needs a + /// `gpui::TestAppContext` this repo has no way to build). + #[test] + fn recovery_offer_reads_only_the_newer_sidecar() { + let dir = std::env::temp_dir().join(format!( + "edith-autosave-test-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::create_dir_all(&dir).unwrap(); + let project = dir.join("p.edith"); + let sidecar = dir.join("p.edith.autosave"); + + // Neither file exists yet. + assert_eq!(Player::recovery_offer(&project), None); + + std::fs::write(&project, b"project").unwrap(); + // A project with no sidecar beside it: nothing to offer. + assert_eq!(Player::recovery_offer(&project), None); + + std::fs::write(&sidecar, b"sidecar").unwrap(); + let now = std::time::SystemTime::now(); + // Sidecar written after the project (the ordinary case: an edit + // landed since the last manual save) -- offered. + std::fs::File::open(&project) + .unwrap() + .set_modified(now - Duration::from_secs(60)) + .unwrap(); + std::fs::File::open(&sidecar) + .unwrap() + .set_modified(now) + .unwrap(); + assert_eq!(Player::recovery_offer(&project), Some(sidecar.clone())); + + // The sidecar left over from *before* the last manual save (the save + // that answered it, per `Player::save_project`, deletes it -- but an + // older one left by some other means must not be offered as newer + // than a file it predates). + std::fs::File::open(&project) + .unwrap() + .set_modified(now) + .unwrap(); + std::fs::File::open(&sidecar) + .unwrap() + .set_modified(now - Duration::from_secs(60)) + .unwrap(); + assert_eq!(Player::recovery_offer(&project), None); + + std::fs::remove_dir_all(&dir).unwrap(); + } + + /// The bug this module exists to close: a plain media open derives + /// `project_path` (a guess at where a save would land) but never arms + /// autosave for it -- so a dirty, never-saved scratch session writes no + /// sidecar beside whatever `.edith` that guess happens to name, even if + /// one already exists as somebody's real saved project. + #[test] + fn unarmed_session_never_writes_even_when_dirty() { + assert!(!Player::autosave_gate(false, true, false)); + } + + /// Both doors that earn the write: opening the `.edith` itself + /// (`install_project`) and a manual save (`save_project`), each setting + /// `autosave_armed = true` before this gate is ever asked again. + #[test] + fn armed_and_dirty_session_writes() { + assert!(Player::autosave_gate(true, true, false)); + // Still withheld while an export is running, armed or not. + assert!(!Player::autosave_gate(true, true, true)); + // Still withheld while clean, armed or not. + assert!(!Player::autosave_gate(true, false, false)); + } + + /// Declining the recovery notice (any key but `enter`, in + /// [`render::key handler`](crate::render)) discards the sidecar on disk, + /// not just the in-memory offer -- otherwise the same stale sidecar + /// outdates the project again on the very next open. + #[test] + fn declining_recovery_deletes_the_sidecar() { + let dir = std::env::temp_dir().join(format!( + "edith-autosave-decline-test-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::create_dir_all(&dir).unwrap(); + let sidecar = dir.join("p.edith.autosave"); + std::fs::write(&sidecar, b"stale").unwrap(); + + Player::discard_sidecar(&sidecar); + assert!(!sidecar.exists()); + + // A missing sidecar (already recovered, or declined twice) is a + // no-op, not an error. + Player::discard_sidecar(&sidecar); + + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/app/src/player/timeline_edit.rs b/crates/app/src/player/timeline_edit.rs index d82bfd0..6191576 100644 --- a/crates/app/src/player/timeline_edit.rs +++ b/crates/app/src/player/timeline_edit.rs @@ -282,6 +282,7 @@ impl Player { if self.exporting().is_some() { return; } + self.mark_dirty(); let (Some((start, _)), Some(was)) = ( self.drop_frame(from, idx, x), self.session @@ -367,6 +368,7 @@ impl Player { if self.exporting().is_some() { return; } + self.mark_dirty(); self.snap_cue = None; self.ghost = None; let at = self.place_frame(x).0; @@ -450,6 +452,7 @@ impl Player { if self.exporting().is_some() { return; } + self.mark_dirty(); self.snap_cue = None; self.ghost = None; let Some(idx) = self.dragged_sub(drag) else { @@ -522,6 +525,7 @@ impl Player { if self.exporting().is_some() { return; } + self.mark_dirty(); let lifted = self .session .as_mut() @@ -1130,6 +1134,7 @@ impl Player { let Some(trim) = self.trim.take() else { return; }; + self.mark_dirty(); // A caption's edge reaches the engine through its own door, at this // timeline's rate. An `Ok` is *not* "something changed" -- an edge that // stopped at a wall it already stood against is `Ok` with no undo step @@ -1166,6 +1171,165 @@ impl Player { cx.notify(); } + /// A press on a fade handle: the start of the drag that lengthens or + /// shortens the ramp at that end of an audio clip. Ctrl-free, unlike a + /// trim's press -- a fade handle sits inside the trim strip's own column + /// ([`FADE_HANDLE_W`]) and a ctrl-click there would be read as picking the + /// clip up rather than as the toggle it means on a trim. + pub(crate) fn start_fade_drag( + &mut self, + lane: Lane, + idx: usize, + is_in: bool, + x: Pixels, + cx: &mut Context, + ) { + if self.modal() || self.exporting().is_some() { + return; + } + let Some(clip) = self + .session + .as_ref() + .and_then(|session| session.lane_clips(lane).get(idx).copied()) + else { + return; + }; + self.pick((lane, idx), false, cx); + let start = match is_in { + true => clip.fade_in, + false => clip.fade_out, + }; + self.fade_drag = Some(FadeDrag { + lane, + idx, + is_in, + press_x: x, + start, + to: start, + cap: clip.frames(), + }); + cx.notify(); + } + + /// Where the pointer has pulled a fade handle to, in the fade's own + /// frames -- pulling away from the clip's edge lengthens the ramp for + /// both handles alike, which is why the tail's own delta is negated: its + /// handle sits at the *right* of the box, so a hand dragging left (toward + /// the body) is the same "make it longer" motion the head's handle reads + /// dragging right. + pub(crate) fn fade_drag_to(&mut self, x: Pixels, cx: &mut Context) { + let Some(fade) = self.fade_drag else { + return; + }; + let dx = f32::from(x) - f32::from(fade.press_x); + let dx = match fade.is_in { + true => dx, + false => -dx, + }; + let delta = fade_delta_frames(dx, self.scale.pps, self.fps); + let to = (i64::from(fade.start) + delta).clamp(0, i64::from(fade.cap)) as u32; + self.fade_drag = Some(FadeDrag { to, ..fade }); + cx.notify(); + } + + /// The release: one edit, one undo step, exactly as [`Player::commit_trim`] + /// pays for a trim. Autosave's own reason a fade drag has to call + /// [`Player::mark_dirty`] same as every other edit that reaches the + /// engine. + pub(crate) fn commit_fade(&mut self, cx: &mut Context) { + let Some(fade) = self.fade_drag.take() else { + return; + }; + self.mark_dirty(); + let set = self.session.as_mut().is_some_and(|session| match fade.is_in { + true => session.set_fade_in(fade.lane, fade.idx, fade.to), + false => session.set_fade_out(fade.lane, fade.idx, fade.to), + }); + if set { + cx.notify(); + } + } + + /// The clip's fade-in as the drag is showing it: display only, same as + /// [`Player::trimmed`] -- the engine hears about it once, at the release. + pub(crate) fn shown_fade_in(&self, lane: Lane, idx: usize, clip: &Clip) -> u32 { + match self.fade_drag { + Some(f) if f.is_in && (f.lane, f.idx) == (lane, idx) => f.to, + _ => clip.fade_in, + } + } + + /// [`Player::shown_fade_in`]'s twin, for the tail. + pub(crate) fn shown_fade_out(&self, lane: Lane, idx: usize, clip: &Clip) -> u32 { + match self.fade_drag { + Some(f) if !f.is_in && (f.lane, f.idx) == (lane, idx) => f.to, + _ => clip.fade_out, + } + } + + /// Crossfades across the join the selection names: two picks on one audio + /// lane take the pair, one pick takes it and its right-hand neighbour. The + /// engine owns adjacency ([`Project::crossfade`]); a refusal is worded + /// here, in [`Player::regroup`]'s voice, because `false` is all it says. + pub(crate) fn crossfade_selected(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let Some((lane, idx)) = (match self.selected.picks() { + [a, b] if a.0 == b.0 && a.1.abs_diff(b.1) == 1 => Some((a.0, a.1.min(b.1))), + _ => self.selected.anchor(), + }) else { + self.notify_user("NOTHING TO CROSSFADE — select an audio clip that has a neighbour".into()); + cx.notify(); + return; + }; + let frames = self.fps.round().max(1.) as u32; + if let Some(session) = &mut self.session { + if !session.crossfade(lane, idx, frames) { + self.notify_user( + "NOTHING TO CROSSFADE — it takes two audio clips sitting end to end on one lane" + .into(), + ); + } + } + cx.notify(); + } + + /// Dissolves the join the selection names, into or back out of it: two + /// picks on one video lane take the pair, one pick takes it and its + /// right-hand neighbour. If the leading clip already carries a dissolve + /// this removes it (`0` frames) instead of widening it -- a toggle, same + /// key either way. The engine owns adjacency ([`Project::set_transition_out`]); + /// a refusal is worded here, in [`Player::crossfade_selected`]'s voice. + pub(crate) fn dissolve_selected(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let Some((lane, idx)) = (match self.selected.picks() { + [a, b] if a.0 == b.0 && a.1.abs_diff(b.1) == 1 => Some((a.0, a.1.min(b.1))), + _ => self.selected.anchor(), + }) else { + self.notify_user("NOTHING TO DISSOLVE — select a video clip that has a neighbour".into()); + cx.notify(); + return; + }; + let Some(session) = &mut self.session else { + cx.notify(); + return; + }; + let removing = session.transition_out_of(lane, idx) > 0; + let frames = if removing { 0 } else { self.fps.round().max(1.) as u32 }; + if !session.set_transition_out(lane, idx, frames) { + self.notify_user( + "NOTHING TO DISSOLVE — it takes two video clips sitting end to end on one lane" + .into(), + ); + } else if removing { + self.notify_user("DISSOLVE REMOVED — the clips cut again".into()); + } + cx.notify(); + } + /// The clip as the drag is showing it: an edge under the pointer moves its /// own box, and the boxes of everything linked to it, before anything is /// committed. Display only -- the project is not touched until the release. @@ -1365,6 +1529,16 @@ impl Player { } return; } + // A fade handle is [`FADE_HANDLE_W`] wide and the pointer leaves it + // on the first drag, same reason and same shape as a trim's own + // branch just above. + if self.fade_drag.is_some() { + match event.pressed_button { + Some(MouseButton::Left) => self.fade_drag_to(event.position.x, cx), + _ => self.commit_fade(cx), + } + return; + } // A colour slider is 4 px tall and the pointer leaves it just as // fast; every sample is live, so the release owes no write of // its own -- what the last sample set is what the clip carries. @@ -1463,6 +1637,11 @@ impl Player { self.commit_trim(cx); return; } + if self.fade_drag.is_some() { + self.fade_drag_to(event.position.x, cx); + self.commit_fade(cx); + return; + } if std::mem::take(&mut self.color_dragging) { // The release lands exactly where the hand let go, and // it is a live write like every other sample: the undo diff --git a/crates/app/src/render.rs b/crates/app/src/render.rs index b466311..3ac6491 100644 --- a/crates/app/src/render.rs +++ b/crates/app/src/render.rs @@ -207,6 +207,19 @@ impl Render for Player { { return; } + // The recovery notice is the one bar that reads a key as more + // than "answered": `enter` loads the sidecar it named, and + // every other key declines it -- the way any other key + // dismisses any other notice. Asked before the generic + // dismiss below shares the same door with it, not instead of + // it: this recovers or declines, that pops the bar. + if this.recovery_sidecar.is_some() { + if key == "enter" { + this.recover_from_sidecar(cx); + } else if let Some(sidecar) = this.recovery_sidecar.take() { + Player::discard_sidecar(&sidecar); + } + } // Any key answers the message on the bar and brings the next of // them up, whatever it was -- and owes // the repaint itself: a notice no longer keeps the render loop diff --git a/crates/app/src/tests/editing.rs b/crates/app/src/tests/editing.rs index b93dc67..a5acefe 100644 --- a/crates/app/src/tests/editing.rs +++ b/crates/app/src/tests/editing.rs @@ -615,6 +615,9 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { use keymap::{ActionId, Keymap}; // Frames 30..90 of the timeline, taken from the head of its source. let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 30, in_frame: 0, out_frame: 60, @@ -655,6 +658,8 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { // clip by any reading of the playhead, so "only from inside a clip" // there is a refusal claiming something the screen contradicts. let slow = Clip { + fade_in: 0, + fade_out: 0, speed: Speed::MIN, ..clip }; @@ -679,6 +684,8 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { // engine's question. Group is offered on every clip, for that reason. assert!(!offered(&clip, v1, ActionId::Detach, 0)); let grouped = Clip { + fade_in: 0, + fade_out: 0, link: Some(3), ..clip }; @@ -981,6 +988,9 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { fn a_menu_offers_only_what_applies_and_is_drawn_inside_the_window() { use keymap::ActionId; let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 30, in_frame: 0, out_frame: 60, @@ -1611,6 +1621,9 @@ fn removing_a_row_is_refused_while_it_plays_and_takes_the_row_away() { #[test] fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() { let clip = |source: usize| Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: 30, @@ -2032,3 +2045,17 @@ fn frac_along_measures_from_the_elements_own_left_edge() { // to +12 dB on the first press. assert_eq!(frac_down(px(50.), Bounds::default()), 0.5); } + +/// A fade handle's pixels turn into frames at the bed's own scale, and a +/// degenerate scale (nothing painted) turns into no movement at all. +#[test] +fn a_fade_drag_converts_pixels_to_frames_at_the_beds_scale() { + use crate::timeline_math::fade_delta_frames; + // 100 px/s at 25 fps: one second of pixels is one second of frames. + assert_eq!(fade_delta_frames(100., 100., 25.), 25); + // Signed: dragging back shrinks the fade by the same conversion. + assert_eq!(fade_delta_frames(-50., 100., 25.), -13); + // Nothing drawn to drag against moves nothing. + assert_eq!(fade_delta_frames(40., 0., 25.), 0); + assert_eq!(fade_delta_frames(40., -1., 25.), 0); +} diff --git a/crates/app/src/tests/layout.rs b/crates/app/src/tests/layout.rs index 6459e5a..4768d88 100644 --- a/crates/app/src/tests/layout.rs +++ b/crates/app/src/tests/layout.rs @@ -801,6 +801,9 @@ fn a_stills_trim_preview_grows_forward_like_the_commit() { #[test] fn a_drop_moves_the_clip_that_was_picked_up_not_its_old_index() { let at = |start: u32| Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame: 0, out_frame: 30, diff --git a/crates/app/src/tests/view.rs b/crates/app/src/tests/view.rs index 67118c2..ec7e696 100644 --- a/crates/app/src/tests/view.rs +++ b/crates/app/src/tests/view.rs @@ -147,6 +147,9 @@ fn a_lane_refuses_the_files_it_cannot_hold_before_the_release_says_so() { #[test] fn the_marks_are_every_lane_the_playhead_and_the_start() { let clip = |start: u32, frames: u32, link| Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame: 0, out_frame: frames, diff --git a/crates/app/src/timeline_math.rs b/crates/app/src/timeline_math.rs index 85efc18..a4f77c2 100644 --- a/crates/app/src/timeline_math.rs +++ b/crates/app/src/timeline_math.rs @@ -303,12 +303,16 @@ pub(crate) fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip }; match still { true => Clip { + fade_in: 0, + fade_out: 0, in_frame: 0, out_frame: keep, start: to, ..clip }, false => Clip { + fade_in: 0, + fade_out: 0, in_frame: clip.out_frame - keep.min(clip.out_frame), start: to, ..clip @@ -317,6 +321,8 @@ pub(crate) fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip } Edge::End => match clip.speed.fit(to.saturating_sub(clip.start)) { Some(keep) => Clip { + fade_in: 0, + fade_out: 0, out_frame: clip.in_frame + keep, ..clip }, @@ -331,6 +337,20 @@ pub(crate) fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip /// (`Project::trim_sub_room`). Never zero: a placement of no frames is the one /// [`Project::place_sub`] refuses as empty, and a track shorter than a frame is /// still a caption somebody dragged. +/// A fade handle's drag, turned into timeline frames: `dx` pixels at `pps` +/// pixels per second, at `fps` frames per second -- the one conversion a +/// fade-in or fade-out handle needs, and the app-side twin of every other +/// pixel-to-frame door on this bed ([`Scale::time_at`]). Zero for a +/// degenerate scale (nothing drawn to drag against), never negative on its +/// own -- the caller adds this to the fade's length before clamping to the +/// clip's own room, so a delta can still shrink a fade by coming back signed. +pub(crate) fn fade_delta_frames(dx: f32, pps: f64, fps: f64) -> i64 { + if pps <= 0. { + return 0; + } + ((f64::from(dx) / pps) * fps).round() as i64 +} + pub(crate) fn frames_of_us(us: i64, fps: f64) -> u32 { match fps.is_finite() && fps > 0. { true => ((us as f64) * fps / 1e6) diff --git a/crates/app/src/ui/cards.rs b/crates/app/src/ui/cards.rs index ea1d176..0547183 100644 --- a/crates/app/src/ui/cards.rs +++ b/crates/app/src/ui/cards.rs @@ -519,7 +519,7 @@ impl Player { || { self.session .as_ref() - .map_or("", |s| s.planned_audio(self.format)) + .map_or("", |s| s.planned_audio(self.format, self.range.is_some())) }, |(_, audio)| audio, ); @@ -533,9 +533,10 @@ impl Player { ); let size = estimated_bytes( settings.bitrate.filter(|_| self.format.has_video()), - self.session - .as_ref() - .map_or(0., PlaybackSession::timeline_duration), + self.session.as_ref().map_or(0., |s| match self.range { + Some((start, end)) => f64::from(end - start) / s.meta().frame_rate, + None => s.timeline_duration(), + }), ); let head = summary_head(self.format, picture, audio); let tail = summary_tail( @@ -637,6 +638,22 @@ impl Player { .children(list), ) .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(head)) + // The mark, in and out and how long that is -- only + // when there is one: an unmarked export writes the + // whole timeline, the summary it always had. + .children(self.range.map(|(start, end)| { + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY())) + .child(format!( + "RANGE {}\u{2013}{} ({})", + timecode(f64::from(start) / self.fps, self.fps), + timecode(f64::from(end) / self.fps, self.fps), + frames_timecode(end - start, self.fps), + )) + })) .child( div() .flex_none() @@ -1637,7 +1654,7 @@ impl Player { "{speed} — {} source frames over {} on the timeline ({})", clip.len(), clip.frames(), - timecode(f64::from(clip.frames()) / self.fps, self.fps) + frames_timecode(clip.frames(), self.fps) )), ), ), diff --git a/crates/app/src/ui/timeline.rs b/crates/app/src/ui/timeline.rs index 9a44583..717e90f 100644 --- a/crates/app/src/ui/timeline.rs +++ b/crates/app/src/ui/timeline.rs @@ -64,11 +64,12 @@ impl Player { &join_detail( &self.live_decode(position, state.is_playing()), &format!( - "{} copy · {} paste · {} undo · click the bar to seek · drop a file \ - to import", + "{} copy · {} paste · {} undo · {} redo · click the bar to seek · \ + drop a file to import", key(ActionId::Copy), key(ActionId::Paste), - key(ActionId::Undo) + key(ActionId::Undo), + key(ActionId::Redo) ), ), ), @@ -230,7 +231,35 @@ impl Player { .w(px(filled)) .rounded(px(3.)) .bg(rgb(ACCENT_PRIMARY())), - ), + ) + // The export's own mark, in and out: drawn + // over the played fill rather than under it, + // so a range that starts behind the playhead + // still shows -- translucent, the same wash + // the silence marks use, so the ruler under + // it stays readable. + .children(self.range.map(|(start, end)| { + let left = self.scale.px_at(f64::from(start) / self.fps); + let right = self.scale.px_at(f64::from(end) / self.fps); + // The wash alone is the played fill's own + // color at lower alpha, so once the + // playhead has passed the whole band the + // two blend to one flat color and the mark + // vanishes. A tick at each boundary, in + // the theme's foreground rather than its + // accent, reads over either background. + div() + .absolute() + .top_0() + .h_full() + .left(px(left)) + .w(px((right - left).max(1.))) + .rounded(px(3.)) + .bg(rgba(ACCENT_WASH())) + .border_l(px(2.)) + .border_r(px(2.)) + .border_color(rgb(FG_PRIMARY())) + })), ), ), ) @@ -1473,6 +1502,118 @@ impl Player { .child(inner), ) })) + // The fades: a translucent wedge at each end an + // audio clip ramps, drawn over the waveform the way + // every editor shades a fade. Width comes straight + // off the clip's own frames, never off the visible + // slice -- unlike the waveform a wedge that starts + // off the left edge of the bed still shades the + // clip's own corner once scrolled back into view, + // because `overflow_hidden` on the box already + // clips it, and clamped to the box's own width so a + // fade longer than a zoomed-in clip never draws + // past its neighbour. + .when(audio, |d| { + let fade_in = self.shown_fade_in(lane, i, clip); + let fade_out = self.shown_fade_out(lane, i, clip); + d.children( + [ + (fade_in > 0).then(|| { + div() + .absolute() + .left_0() + .top_0() + .h_full() + .w(px(scale + .width_px(f64::from(fade_in) / self.fps) + .min(width))) + .child(fade_wedge(true)) + }), + (fade_out > 0).then(|| { + div() + .absolute() + .right_0() + .top_0() + .h_full() + .w(px(scale + .width_px(f64::from(fade_out) / self.fps) + .min(width))) + .child(fade_wedge(false)) + }), + ] + .into_iter() + .flatten(), + ) + }) + // The dissolve: a small X astride the join, drawn + // over the last `transition_out` frames of this + // clip's own box, whenever the next clip on the + // lane actually abuts it -- the engine already + // refuses `transition_out` on anything else + // ([`Project::set_transition_out`]), but a moved + // neighbour can leave a stale value behind, so + // this checks the join itself rather than trust + // the field alone. + .when( + lane.kind == LaneKind::Video + && clip.transition_out > 0 + && clips.get(i + 1).is_some_and(|n| n.start == clip.end()), + |d| { + d.child( + div() + .absolute() + .right_0() + .top_0() + .h_full() + .w(px(scale + .width_px(f64::from(clip.transition_out) / self.fps) + .min(width))) + .child(dissolve_glyph()), + ) + }, + ) + // The fade handles: a small grab corner at each + // *top* of an audio clip's box, sitting just + // inside the [`EDGE_W`] trim strip rather than on + // top of it -- [`FADE_HANDLE_H`] never reaches + // past the label row, so a trim's own strip (the + // box's *full* height) is still the whole of what + // a press below the label starts. Gated on + // [`trims`] like the trim strips themselves: a box + // too small for an edge to trim by is too small + // for a fade handle either. + .when(audio && trims(span), |d| { + d.children([Edge::Start, Edge::End].into_iter().map(|edge| { + let is_in = edge == Edge::Start; + let mut handle = div() + .absolute() + .top_0() + .w(px(FADE_HANDLE_W)) + .h(px(FADE_HANDLE_H)) + .occlude() + .cursor(CursorStyle::ResizeLeftRight) + .hover(|s| s.bg(rgb(ACCENT_PRIMARY()))) + .on_mouse_down( + MouseButton::Left, + cx.listener( + move |this, event: &MouseDownEvent, _, cx| { + this.start_fade_drag( + lane, + i, + is_in, + event.position.x, + cx, + ); + }, + ), + ); + handle = match edge { + Edge::Start => handle.left(px(EDGE_W)), + Edge::End => handle.right(px(EDGE_W)), + }; + handle + })) + }) // 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 diff --git a/crates/app/src/ui/toolbar.rs b/crates/app/src/ui/toolbar.rs index a6a795a..9b898dc 100644 --- a/crates/app/src/ui/toolbar.rs +++ b/crates/app/src/ui/toolbar.rs @@ -337,6 +337,16 @@ impl Player { ActionId::Undo, cx.listener(|this, _: &ClickEvent, _, cx| this.undo(cx)), )) + .child(self.action_control( + "redo", + 0., + BG_RAISED(), + None, + "Redo", + "brings the undone edit back", + ActionId::Redo, + cx.listener(|this, _: &ClickEvent, _, cx| this.redo(cx)), + )) .child(separator()) .child(group_label("Track")) .child(self.action_control( diff --git a/crates/app/src/ui/widgets.rs b/crates/app/src/ui/widgets.rs index 82d2200..dd4e0b8 100644 --- a/crates/app/src/ui/widgets.rs +++ b/crates/app/src/ui/widgets.rs @@ -35,6 +35,75 @@ pub(crate) fn waveform(peaks: Arc>, from: f64, to: f64) -> impl .size_full() } +/// An audio clip's fade, drawn as a translucent wedge over its box: silent +/// (full shade) at the clip's own edge, clear by the fade's far side -- +/// [`is_in`] mirrors it for the tail's ramp-down. The same `canvas` + +/// `PathBuilder` idiom [`waveform`] draws its envelope with, filled with the +/// same wash the in/out range already paints the bed with +/// (`ACCENT_WASH`, timeline.rs), so a fade reads as one more overlay on this +/// bed rather than a shape borrowed from somewhere else. +pub(crate) fn fade_wedge(is_in: bool) -> impl IntoElement { + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let (o, s) = (bounds.origin, bounds.size); + let (w, h) = (f32::from(s.width), f32::from(s.height)); + if w <= 0. || h <= 0. { + return; + } + // A right triangle: the clip's silent corner (top of the clip's + // own edge) down to the bed and across to the fade's far side -- + // the wedge shape every editor draws for a ramp. + let points = match is_in { + true => vec![ + point(o.x, o.y), + point(o.x, o.y + px(h)), + point(o.x + px(w), o.y + px(h)), + ], + false => vec![ + point(o.x + px(w), o.y), + point(o.x + px(w), o.y + px(h)), + point(o.x, o.y + px(h)), + ], + }; + let mut path = PathBuilder::fill(); + path.add_polygon(&points, true); + if let Ok(path) = path.build() { + window.paint_path(path, rgba(ACCENT_WASH())); + } + }, + ) + .size_full() +} + +/// A video clip's dissolve into its neighbour, drawn as a small X astride the +/// join -- the box it is given is the last [`Clip::transition_out`] frames of +/// the clip's own width, so the mark sits right at the edge it dissolves +/// through. Two strokes rather than [`fade_wedge`]'s fill: a dissolve is not +/// a ramp to or from silence, it is two clips overlapping, and an X reads as +/// a splice the way a wedge reads as a fade. +pub(crate) fn dissolve_glyph() -> impl IntoElement { + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let (o, s) = (bounds.origin, bounds.size); + let (w, h) = (f32::from(s.width), f32::from(s.height)); + if w <= 0. || h <= 0. { + return; + } + let mut path = PathBuilder::stroke(px(1.5)); + path.move_to(point(o.x, o.y)); + path.line_to(point(o.x + px(w), o.y + px(h))); + path.move_to(point(o.x + px(w), o.y)); + path.line_to(point(o.x, o.y + px(h))); + if let Ok(path) = path.build() { + window.paint_path(path, rgba(ACCENT_WASH())); + } + }, + ) + .size_full() +} + /// A toolbar button: its glyph, its name, and its key on hover. `id` only buys /// `on_click` and the tooltip -- it is still not focusable, so the root's own /// key listener keeps working after a press, and the click lands on mouse-up diff --git a/crates/app/src/viewport.rs b/crates/app/src/viewport.rs index 6a887c5..effcf39 100644 --- a/crates/app/src/viewport.rs +++ b/crates/app/src/viewport.rs @@ -288,6 +288,27 @@ pub(crate) fn timecode(t: f64, fps: f64) -> String { ) } +/// NLE timecode for a *duration* given as a frame count: the same +/// `HH:MM:SS:FF` shape as [`timecode`], but built from the count directly +/// rather than a float number of seconds. `timecode` truncates `(t - secs) * +/// fps`, which loses a whole frame to float error on a duration derived from +/// dividing a frame count by `fps` first (346 frames at 30 fps printed +/// `00:00:11:15`, one short of the true `:16`); integer frame math has no +/// such rounding to lose. +pub(crate) fn frames_timecode(frames: u32, fps: f64) -> String { + let per_sec = (fps.ceil() as u64).max(1); + let frames = u64::from(frames); + let secs = frames / per_sec; + let frame = frames % per_sec; + format!( + "{:02}:{:02}:{:02}:{:02}", + secs / 3600, + secs / 60 % 60, + secs % 60, + frame + ) +} + /// Wall clock for a progress line: `M:SS`, minutes past the hour included /// rather than an hours field nobody reads on an export. pub(crate) fn clock(secs: f32) -> String { diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs index 979c908..40b7ccf 100644 --- a/crates/engine/examples/bench.rs +++ b/crates/engine/examples/bench.rs @@ -860,6 +860,9 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { .min(meta.frame_count.max(1)); let in_frame = (meta.frame_count / 10).min(meta.frame_count.saturating_sub(span)); let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame, out_frame: in_frame + span, @@ -902,7 +905,7 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { let mut notes = Vec::new(); let budget = Instant::now(); for _ in 0..reps.max(1) { - let handle = engine::export::start(project.clone(), meta, &out, &settings); + let handle = engine::export::start(project.clone(), meta, &out, &settings, None); let t = Instant::now(); let mut capped = false; // The highest the bar was ever seen at, not wherever it happens to diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 3687daa..4fabd21 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -392,6 +392,22 @@ impl AudioSession { eqs: &[Option], speeds: &[Option], sample_rate: Option, + ) -> crate::Result)>> { + Self::open_multi_streams_speed_at_fade(sources, segs, eqs, speeds, &[], sample_rate) + } + + /// [`open_multi_streams_speed_at`](Self::open_multi_streams_speed_at) with a + /// fade envelope per segment: `fades[i]` is what segment `i` plays through + /// ([`emit`]'s last effect, after the rate and the equalizer), built the + /// same way `eqs` and `speeds` are -- one entry per `segs`, a short list + /// meaning flat from there on. + pub fn open_multi_streams_speed_at_fade( + sources: &[(PathBuf, usize)], + segs: &[(Option, f64, f64)], + eqs: &[Option], + speeds: &[Option], + fades: &[Option], + sample_rate: Option, ) -> crate::Result)>> { // The first source that could have a track, which is not always index 0: // a still image has none, and one at the front of the list (a save @@ -571,6 +587,17 @@ impl AudioSession { }) .collect(); + // One [`crate::project::Fade`] per segment, exactly the eq and speed + // lists' rule: a short `fades` (the empty one every plain caller + // passes) means the rest play flat, and it is cloned rather than + // built here because [`Project::audio_fades_from`] already resolved + // each clip's own frame count against where this segment lands. + let fades: Vec> = segments + .iter() + .enumerate() + .map(|(i, _)| fades.get(i).copied().flatten()) + .collect(); + let (tx, rx) = sync_channel(32); thread::Builder::new() .name("audio-decode".into()) @@ -581,6 +608,7 @@ impl AudioSession { segments, eqs, speeds, + fades, timeline, tx, }) @@ -690,7 +718,27 @@ impl AudioSession { limiter: Limiter, sample_rate: Option, ) -> crate::Result)>> { - Self::open_mixed_streams_live(sources, lanes, eqs, speeds, gains, limiter, None, sample_rate) + Self::open_mixed_streams_master_at_fade( + sources, lanes, eqs, speeds, &[], gains, limiter, sample_rate, + ) + } + + /// [`open_mixed_streams_master_at`](Self::open_mixed_streams_master_at) + /// with a fade envelope per segment; see + /// [`open_mixed_streams_live_fade`](Self::open_mixed_streams_live_fade). + pub fn open_mixed_streams_master_at_fade( + sources: &[(PathBuf, usize)], + lanes: &[Vec<(Option, f64, f64)>], + eqs: &[Vec>], + speeds: &[Vec>], + fades: &[Vec>], + gains: &[f32], + limiter: Limiter, + sample_rate: Option, + ) -> crate::Result)>> { + Self::open_mixed_streams_live_fade( + sources, lanes, eqs, speeds, fades, gains, limiter, None, sample_rate, + ) } /// [`open_mixed_streams_master`](Self::open_mixed_streams_master) with the @@ -710,6 +758,27 @@ impl AudioSession { limiter: Limiter, live: Option<&Arc>, sample_rate: Option, + ) -> crate::Result)>> { + Self::open_mixed_streams_live_fade( + sources, lanes, eqs, speeds, &[], gains, limiter, live, sample_rate, + ) + } + + /// [`open_mixed_streams_live`](Self::open_mixed_streams_live) with a fade + /// envelope per segment as well: `fades[i]` is what segment `i` plays + /// through -- [`crate::Project::audio_fades_from`] is what builds it, off + /// the same walk the segments come from. A short or missing list means + /// the rest play flat, the eq list's rule. + pub fn open_mixed_streams_live_fade( + sources: &[(PathBuf, usize)], + lanes: &[Vec<(Option, f64, f64)>], + eqs: &[Vec>], + speeds: &[Vec>], + fades: &[Vec>], + gains: &[f32], + limiter: Limiter, + live: Option<&Arc>, + sample_rate: Option, ) -> crate::Result)>> { let [first, ..] = lanes else { return Ok(None); @@ -717,11 +786,13 @@ impl AudioSession { if !Self::is_mixed(lanes.len(), gains, limiter) { let flat = Vec::new(); let plain = Vec::new(); - return Self::open_multi_streams_speed_at( + let flat_fade = Vec::new(); + return Self::open_multi_streams_speed_at_fade( sources, first, eqs.first().unwrap_or(&flat), speeds.first().unwrap_or(&plain), + fades.first().unwrap_or(&flat_fade), sample_rate, ); } @@ -732,12 +803,14 @@ impl AudioSession { // agree by construction; `None` from any of them is a silent // timeline. let flat = Vec::new(); + let flat_fade = Vec::new(); let plain = Vec::new(); - let Some((lane_meta, rx)) = Self::open_multi_streams_speed_at( + let Some((lane_meta, rx)) = Self::open_multi_streams_speed_at_fade( sources, segs, eqs.get(i).unwrap_or(&flat), speeds.get(i).unwrap_or(&plain), + fades.get(i).unwrap_or(&flat_fade), sample_rate, )? else { @@ -2820,6 +2893,10 @@ struct Worker { /// every segment of a project nobody has speeded or rate-mismatched, and /// the path that emits the decoder's own samples untouched. speeds: Vec>, + /// One per entry of `segments` again: that segment's gain envelope, or + /// `None` for one that plays flat -- [`emit`]'s last effect, run after + /// the rate and the equalizer. + fades: Vec>, /// `start_sample` of the first chunk. timeline: u64, tx: SyncSender, @@ -2953,8 +3030,16 @@ fn run(mut w: Worker) { 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); + let mut fades = std::mem::take(&mut w.fades); + // ...and a short fade list is "flat from here on", the same rule again. + fades.resize_with(segments.len(), || None); - for ((seg, eq), speed) in segments.iter().zip(eqs.iter_mut()).zip(speeds.iter_mut()) { + for (((seg, eq), speed), fade) in segments + .iter() + .zip(eqs.iter_mut()) + .zip(speeds.iter_mut()) + .zip(fades.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 @@ -2984,6 +3069,7 @@ fn run(mut w: Worker) { seg, eq.as_mut(), speed, + fade, channels, &mut timeline, &w.tx, @@ -2999,6 +3085,7 @@ fn run(mut w: Worker) { seg, eq.as_mut(), speed, + fade, channels, &mut timeline, &w.tx, @@ -3014,6 +3101,7 @@ fn run(mut w: Worker) { seg, eq.as_mut(), speed, + fade, channels, &mut timeline, &w.tx, @@ -3063,6 +3151,7 @@ fn run(mut w: Worker) { seg, eq.as_mut(), speed.as_mut(), + fade.as_mut(), pos, next, &mut timeline, @@ -3115,6 +3204,7 @@ fn emit( seg: &Segment, eq: Option<&mut EqState>, speed: Option<&mut Rate>, + fade: Option<&mut crate::project::Fade>, pos: u64, next: u64, timeline: &mut u64, @@ -3147,6 +3237,15 @@ fn emit( if let Some(eq) = eq { eq.process(interleaved); } + // The fade last, on the same output-rate samples the mix will hear: its + // frame counts are timeline frames ([`crate::project::Clip::fade_in`]), + // which is what a resample has already turned these into. The state + // walks forward with the segment across as many buffers as decoding + // takes, exactly as the equalizer's does. + if let Some(fade) = fade { + fade.apply(interleaved, channels); + fade.elapsed = fade.elapsed.saturating_add((interleaved.len() / channels) as u32); + } let chunk = AudioChunk { start_sample: *timeline, samples: std::mem::take(interleaved), @@ -3164,6 +3263,7 @@ fn run_ac3( seg: &Segment, mut eq: Option<&mut EqState>, speed: &mut Option, + fade: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, @@ -3206,6 +3306,7 @@ fn run_ac3( seg, eq.as_deref_mut(), speed.as_mut(), + fade.as_mut(), pos, next, timeline, @@ -3227,6 +3328,7 @@ fn run_mkv_ac3( seg: &Segment, mut eq: Option<&mut EqState>, speed: &mut Option, + fade: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, @@ -3268,6 +3370,7 @@ fn run_mkv_ac3( seg, eq.as_deref_mut(), speed.as_mut(), + fade.as_mut(), pos, next, timeline, @@ -3294,6 +3397,7 @@ fn run_sym( seg: &Segment, mut eq: Option<&mut EqState>, speed: &mut Option, + fade: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, @@ -3342,6 +3446,7 @@ fn run_sym( seg, eq.as_deref_mut(), speed.as_mut(), + fade.as_mut(), pos, next, timeline, diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index f1a9aca..887afeb 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -1427,11 +1427,13 @@ mod tests { "the first frame arrived within the call ({first_frame:?} vs \ {returned:?}), which cannot happen if the open is deferred" ); - assert!( - returned < sync_returned, - "the deferred open ({returned:?}) cost as much as the sync one \ - ({sync_returned:?}): the demux is still on the caller's thread" - ); + // No `returned < sync_returned` here on purpose: on a loaded machine + // a thread spawn (what the deferred open pays) can cost more wall + // clock than a whole sync demux of a small fixture, and the race + // flaked one run in three under a parallel build. The two asserts + // above already pin the invariant -- the call returns in microseconds + // territory and the demux happens after it, on the worker. + let _ = sync_returned; } /// The late-picture policy, at the one place it is decided. A worker told diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 6c177c9..1edc073 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -16,9 +16,9 @@ //! subtitle 3 test_av.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 1000 -//! audio 1 0 0 120 0 0 0 - fit 1000 -//! video 2 120 0 120 1 - - - fill 2000 +//! video 1 0 0 120 0 0 0 0 fit 1000 0 0 +//! audio 1 0 0 120 0 0 0 - fit 1000 30 30 +//! video 2 120 0 120 1 - - - fill 2000 0 0 //! audio 2 //! sub 1 0 60 0 500000 1500000 //! sub 2 @@ -110,15 +110,20 @@ //! -- 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`]), and how fast it plays, +//! `stretch` or `center` ([`crate::scale::FitPolicy`]), how fast it plays, //! in thousandths of real time ([`crate::project::Speed`], `1000` for a clip -//! nobody has speeded). Timeline placement is +//! nobody has speeded), and finally its ramp up from silence and ramp down to +//! it, in timeline frames ([`crate::project::Clip::fade_in`], +//! [`crate::project::Clip::fade_out`], `0 0` for a clip nobody has faded), and +//! finally its cross-dissolve into whatever abuts its end +//! ([`crate::project::Clip::transition_out`], `0` for a hard cut). +//! 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. The `` //! and `` are *source* frames whatever the speed says: how long the clip is @@ -143,6 +148,8 @@ //! track 3 of a two-track palette is refused here, as a clip naming a source //! that is not there is. //! +//! **Version 17** was this without the clip's two fade fields: such a project +//! holds no clip anyone has faded, which is what a `0 0` pair still means. //! **Version 15** was this without the caption's group field: such a project //! holds captions no hand ever grouped, which is every caption there could be. //! **Version 14** was that without the `sub` lines: such a project holds no @@ -180,7 +187,7 @@ //! nothing, and an older one plays everything at real time, and an older one //! mixes flat, and an older one shows no subtitles, and an older one is shown //! in the reference rendition, and an older one places none of the words it -//! names -- and saving any of them writes v16. An older +//! names -- and saving any of them writes v18. 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 @@ -216,7 +223,9 @@ use crate::subtitle::SubtitleTrack; /// 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 17"; +const MAGIC: &[u8] = b"edith 19"; +const MAGIC_V18: &[u8] = b"edith 18"; +const MAGIC_V17: &[u8] = b"edith 17"; const MAGIC_V16: &[u8] = b"edith 16"; const MAGIC_V15: &[u8] = b"edith 15"; const MAGIC_V14: &[u8] = b"edith 14"; @@ -549,13 +558,16 @@ 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), - c.speed.permille() + c.speed.permille(), + c.fade_in, + c.fade_out, + c.transition_out, ) .as_bytes(), ); @@ -598,8 +610,12 @@ 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 an explicit sound rate... - let v17 = first == MAGIC; + // The one that carries a per-clip cross-dissolve into its successor... + let v19 = first == MAGIC; + // ...the one that carries a per-clip fade envelope... + let v18 = v19 || first == MAGIC_V18; + // ...the one that carries an explicit sound rate... + let v17 = v18 || first == MAGIC_V17; // ...the one whose captions may carry a group id... let v16 = v17 || first == MAGIC_V16; // ...the one that places the words it names... @@ -963,6 +979,9 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { let f = fields(rest, 3, "clip", n)?; let clip = check( Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: queued, in_frame: number(f[0], n)?, out_frame: number(f[1], n)?, @@ -1081,16 +1100,33 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { if numbered && rest.is_empty() { continue; } - // 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); + // v18 grew the two fade fields, v19 the transition one, v8 + // the speed one, 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) + + 2 * usize::from(v18) + + usize::from(v19); let f = fields(rest, want, "clip", n)?; + let in_frame = number(f[1], n)?; + let out_frame = number(f[2], n)?; + let speed = speed_of(f.get(8).copied(), n)?; + // Clamped to the clip's own timeline length, + // [`Project::set_fade_in`]'s rule: a crafted or hand-edited + // file asking for more ramp than the clip has frames gets the + // clip's whole length rather than a refusal. + let frames = speed.frames(out_frame.saturating_sub(in_frame)); let clip = check( Clip { + fade_in: number(f.get(9).copied().unwrap_or(b"0"), n)?.min(frames), + fade_out: number(f.get(10).copied().unwrap_or(b"0"), n)?.min(frames), + transition_out: number(f.get(11).copied().unwrap_or(b"0"), n)?.min(frames), start: number(f[0], n)?, - in_frame: number(f[1], n)?, - out_frame: number(f[2], n)?, + in_frame, + out_frame, source: number(f[3], n)? as usize, link: match f[4] { b"-" => None, @@ -1099,7 +1135,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)?, + speed, }, &doc, n, @@ -1509,7 +1545,7 @@ mod tests { video 1 0 0 30 0 - - - fit 1000\n"; let old = parse(v9, &dir).expect("v9 still loads"); assert_eq!(old.subtitles, Vec::new()); - assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 17\n")); + assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 19\n")); // ...and the line itself is not a v9 line: a dialect may not be mixed. let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir) .unwrap_err() @@ -1851,7 +1887,7 @@ mod tests { assert_eq!(mixed, "line 3: unknown keyword \"samplerate\""); // A number out of a sound rate's range is a corrupt line, by name. for line in ["samplerate 0\n", "samplerate 500000\n", "samplerate nope\n"] { - let file = format!("edith 17\nsource 0 a.mp4\n{line}"); + let file = format!("edith 18\nsource 0 a.mp4\n{line}"); assert!( parse(file.as_bytes(), &dir).is_err(), "{line:?} is not a sound rate line" @@ -1919,6 +1955,9 @@ mod tests { fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option) -> Clip { Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame, out_frame, @@ -1977,10 +2016,10 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 12); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 19\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\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", + video 1 0 0 30 0 0 - - fit 1000 0 0 0\nvideo 1 30 10 20 1 1 - - fit 1000 0 0 0\n\ + audio 1 0 0 30 0 0 - - fit 1000 0 0 0\n", "the file under the project directory is written relative to it, \ each with the audio stream it plays" ); @@ -2014,9 +2053,9 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 7); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\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", + "edith 19\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 4 - - fit 1000 0 0 0\naudio 1\n\ + video 2 40 0 10 0 - - - fit 1000 0 0 0\naudio 2 0 0 30 0 4 - - fit 1000 0 0 0\n", "an empty lane is a line of its own; everything else is its clips" ); let back = parse(&bytes, &dir).expect("parse"); @@ -2100,20 +2139,32 @@ mod tests { let lanes = two( vec![ Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, eq: Some(0), ..clip(0, 0, 30, 0, Some(0)) }, Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, eq: Some(1), ..clip(30, 10, 20, 0, None) }, ], vec![ Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, eq: Some(0), ..clip(0, 0, 30, 0, Some(0)) }, Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, eq: Some(2), ..clip(30, 0, 10, 0, None) }, @@ -2122,12 +2173,12 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 19\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 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", + video 1 0 0 30 0 0 0 - fit 1000 0 0 0\nvideo 1 30 10 20 0 - 1 - fit 1000 0 0 0\n\ + audio 1 0 0 30 0 0 0 - fit 1000 0 0 0\naudio 1 30 0 10 0 - 2 - fit 1000 0 0 0\n", "the table comes before the clips, and a clip names a line of it" ); @@ -2196,12 +2247,18 @@ mod tests { let lanes = two( vec![ Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, color: Some(0), fit: FitPolicy::default(), speed: Speed::NORMAL, ..clip(0, 0, 30, 0, Some(0)) }, Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, color: Some(1), fit: FitPolicy::default(), speed: Speed::NORMAL, @@ -2210,12 +2267,18 @@ mod tests { ], vec![ Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, color: Some(0), fit: FitPolicy::default(), speed: Speed::NORMAL, ..clip(0, 0, 30, 0, Some(0)) }, Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, color: Some(2), fit: FitPolicy::default(), speed: Speed::NORMAL, @@ -2226,12 +2289,12 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 19\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 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", + video 1 0 0 30 0 0 - 0 fit 1000 0 0 0\nvideo 1 30 10 20 0 - - 1 fit 1000 0 0 0\n\ + audio 1 0 0 30 0 0 - 0 fit 1000 0 0 0\naudio 1 30 0 10 0 - - 2 fit 1000 0 0 0\n", "the table comes before the clips, and a clip names a line of it" ); @@ -2291,9 +2354,9 @@ mod tests { (1280, 720), old.playhead )), - "edith 17\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 19\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 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" + video 1 0 0 30 0 0 0 - fit 1000 0 0 0\naudio 1 0 0 30 0 0 - - fit 1000 0 0 0\n" ); } @@ -2306,6 +2369,9 @@ mod tests { let dir = PathBuf::from("/proj"); let sources = vec![Source::new("/proj/a.mp4", 0)]; let speeded = |start, in_frame, out_frame, permille| Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame, out_frame, @@ -2329,9 +2395,9 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\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", + "edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 2000 0 0 0\nvideo 1 15 30 40 0 - - - fit 250 0 0 0\n\ + audio 1 0 0 30 0 - - - fit 2000 0 0 0\n", "the rate is the clip line's last field, in thousandths" ); let back = parse(&bytes, &dir).expect("parse"); @@ -2358,8 +2424,8 @@ mod tests { (1280, 720), old.playhead )), - "edith 17\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" + "edith 19\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 0 - - fit 1000 0 0 0\naudio 1 0 0 30 0 0 - - fit 1000 0 0 0\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"; @@ -2369,6 +2435,104 @@ mod tests { ); } + #[test] + fn a_v17_file_loads_with_zero_fades_and_fades_round_trip_bit_exactly() { + let dir = PathBuf::from("/proj"); + // The v17 dialect: nine clip fields, the last the speed -- no fade + // pair after it at all, not even zeroes. + let v17 = b"edith 17\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"; + let old = parse(v17, &dir).expect("v17 parses"); + assert!( + old.lanes + .iter() + .flat_map(|(_, clips)| clips) + .all(|c| c.fade_in == 0 && c.fade_out == 0), + "nothing before v18 had a fade to name" + ); + + // ...and the dialect that does: nonzero fades on both edges, written + // and read back as the very numbers. + let sources = vec![Source::new("/proj/a.mp4", 0)]; + let faded = Clip { + fade_in: 5, + fade_out: 7, + transition_out: 0, + start: 0, + in_frame: 0, + out_frame: 30, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + let lanes = vec![(LaneKind::Video, vec![faded])]; + let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); + assert_eq!( + String::from_utf8_lossy(&bytes), + "edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 5 7 0\n", + "the fades are the clip line's last two fields" + ); + let back = parse(&bytes, &dir).expect("parse"); + assert_eq!(back.lanes, lanes, "the fades round trip as the very numbers"); + } + + /// The whole of the v19 bump, the fade test's twin: a clip's dissolve into + /// its successor is written as the clip line's own last field, comes back + /// as the very number that was set, and a v18 file -- which has no such + /// field -- loads with every clip's [`Clip::transition_out`] at zero and + /// re-saves saying so. + #[test] + fn a_v18_file_loads_with_no_transition_and_transitions_round_trip_bit_exactly() { + let dir = PathBuf::from("/proj"); + // The v18 dialect: eleven clip fields, the last the fade-out -- no + // transition field after it at all, not even a zero. + let v18 = b"edith 18\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0\n"; + let old = parse(v18, &dir).expect("v18 parses"); + assert!( + old.lanes + .iter() + .flat_map(|(_, clips)| clips) + .all(|c| c.transition_out == 0), + "nothing before v19 had a dissolve to name" + ); + + // ...and the dialect that does: a nonzero dissolve, written and read + // back as the very number. + let sources = vec![Source::new("/proj/a.mp4", 0)]; + let dissolving = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 9, + start: 0, + in_frame: 0, + out_frame: 30, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + let lanes = vec![(LaneKind::Video, vec![dissolving])]; + let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); + assert_eq!( + String::from_utf8_lossy(&bytes), + "edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 9\n", + "the dissolve is the clip line's own last field" + ); + let back = parse(&bytes, &dir).expect("parse"); + assert_eq!( + back.lanes, lanes, + "the dissolve round trips as the very number" + ); + } + /// The whole of the v9 bump, the speed test's twin: the mix a project was /// left at -- every track's own volume and the master limiter -- plus the /// rate it was cut at, all written, all read back as the very numbers, and @@ -2409,10 +2573,10 @@ mod tests { ); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ + "edith 19\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ limiter -1.5 on\nsource 0 a.mp4\n\ - video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\ - audio 2 0 0 30 0 - - - fit 1000\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0\n\ + audio 2 0 0 30 0 - - - fit 1000 0 0 0\n\ gain audio 1 3.0\ngain audio 2 -6.5\n", "the mix is lines of its own, the gains after the lanes they name" ); @@ -2441,8 +2605,8 @@ mod tests { (1280, 720), old.playhead )), - "edith 17\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ - video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" + "edith 19\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0\n" ); // Each of the three refuses by name, on its own line. @@ -2605,10 +2769,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 17\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 19\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\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" + video 1 0 0 30 0 0 - - fit 1000 0 0 0\nvideo 1 30 10 20 1 1 - - fit 1000 0 0 0\n\ + audio 1 0 0 30 0 0 - - fit 1000 0 0 0\n" ); // An empty lane's line is still the whole of that lane, eq or no eq. let empty = parse( @@ -2658,10 +2822,10 @@ mod tests { let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); assert_eq!( String::from_utf8_lossy(&v5), - "edith 17\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 19\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 0 /elsewhere/b.mp4\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", + video 1 0 0 30 0 0 - - fit 1000 0 0 0\nvideo 1 30 10 20 1 1 - - fit 1000 0 0 0\n\ + audio 1 0 0 30 0 0 - - fit 1000 0 0 0\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" ); @@ -2690,7 +2854,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 17\n")); + assert!(v5.starts_with(b"edith 19\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. @@ -2800,8 +2964,8 @@ mod tests { let bytes = std::fs::read(&path).expect("read back"); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\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" + "edith 19\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0\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 @@ -2845,10 +3009,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 18\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) + let err = parse(b"edith 20\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 18"); + assert_eq!(err, "line 1: unsupported version 20"); 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 4410c50..32a9a6c 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -79,7 +79,7 @@ use crate::mux::{ AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, }; use crate::project::{Lane, LaneKind, Project, Rate}; -use crate::scale::Composer; +use crate::scale::{blend_i420, Composer}; use crate::subtitle::{Cue, SubtitleTrack}; use crate::tonemap::{self, ToneMapper}; @@ -367,6 +367,11 @@ pub struct ExportSettings { /// A delivery export must leave it off: an mp4 in BT.2020 PQ is a file for /// this editor to read back, not one to hand anybody. pub keep_source_colour: bool, + /// Half-open `[start, end)` in timeline frames, or `None` for the whole + /// timeline -- what every caller wrote before there was a choice, so an + /// export nobody has marked in or out on writes the same bytes it always + /// did. Session state, like the mark itself: never saved to a `.edith`. + pub range: Option<(u32, u32)>, } struct Shared { @@ -715,13 +720,17 @@ fn video_label(format: Format, hw: bool) -> &'static str { /// copy; a speeded lane is resampled; an equalizer is sample math. The other /// half -- whether the sources can be copied out of at all -- costs a file open /// each and belongs to [`copy_audio`], which may re-encode where this says copy. -fn forces_encode(project: &Project) -> bool { +fn forces_encode(project: &Project, ranged: bool) -> bool { let lanes: Vec<_> = project .audio_lanes() .into_iter() .filter(|&lane| !project.lane(lane).is_empty()) .collect(); - lanes.len() > 1 + // A ranged export needs an exact offset and an exact length, which a copy + // of the source's own packets cannot give it ([`copy_audio`]) -- so a + // range marked at all always encodes, whatever the lanes look like. + ranged + || lanes.len() > 1 || lanes .iter() .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal())) @@ -744,6 +753,7 @@ fn audio_label( format: Format, sound: bool, copied: Option, + ranged: bool, ) -> &'static str { if !sound { return "no sound to write"; @@ -753,7 +763,7 @@ fn audio_label( Format::Flac => "FLAC · SW (flacenc)", Format::Mp3 => "MP3 · SW (rusty_mp3)", Format::Ogg => "Vorbis · SW (rusty_vorbis)", - _ => match copied.unwrap_or(!forces_encode(project)) { + _ => match copied.unwrap_or(!forces_encode(project, ranged)) { true => "AAC copy", // A Matroska file gets Opus where the mix allows it -- 48 kHz and // stereo, which is every Opus source and most of everything else -- @@ -795,14 +805,19 @@ fn measured_audio_label( // Opus: the fidelity gate sent it to AAC ([`OPUS_MIN_FIDELITY`]), or the // mix was not the 48 kHz stereo that seat is measured in. (Some(false), false) if format.is_mkv() => "AAC · SW encode (rusty_aac)", - _ => audio_label(project, format, sound.is_some(), sound), + // `sound` is already what happened, not a prediction, so `copied` is + // filled in and `ranged` never reaches the branch that reads it. + _ => audio_label(project, format, sound.is_some(), sound, false), } } /// What [`start`] would write this timeline's sound with, before one is -/// started. Pure: no probe and no file opened, so a card may ask it per repaint. -pub fn planned_audio(project: &Project, format: Format) -> &'static str { - audio_label(project, format, has_sound(project), None) +/// started. Pure: no probe and no file opened, so a card may ask it per +/// repaint. `ranged` is whether the export a card is describing is bounded to +/// a marked range -- a copy needs the source's own packets to *be* the file, +/// which a range's exact offset and length rule out ([`copy_audio`]). +pub fn planned_audio(project: &Project, format: Format, ranged: bool) -> &'static str { + audio_label(project, format, has_sound(project), None, ranged) } /// Why the sound's rate is nothing this timeline can be asked about in this @@ -814,7 +829,7 @@ pub fn planned_audio(project: &Project, format: Format) -> &'static str { /// [`ExportSettings::audio_kbps`] like every other encode. So the value travels /// even where this refuses; what it cannot do is silently write a rate nobody /// picked. -pub fn audio_rate_refusal(project: &Project, format: Format) -> Option<&'static str> { +pub fn audio_rate_refusal(project: &Project, format: Format, ranged: bool) -> Option<&'static str> { match format { _ if !has_sound(project) => Some("no sound to write"), Format::Wav | Format::Flac => Some("lossless — the samples themselves, at no rate"), @@ -826,7 +841,7 @@ pub fn audio_rate_refusal(project: &Project, format: Format) -> Option<&'static // does not hold, which is the one thing this card is built not to do. Format::Ogg => Some("quality-coded — Vorbis holds no rate to pick"), Format::Mp3 => None, - _ if forces_encode(project) => None, + _ if forces_encode(project, ranged) => None, _ => Some("the source's own packets are copied — at the rate they hold"), } } @@ -961,7 +976,8 @@ fn lane_subtitles(project: &Project, fps: f64) -> Vec { } /// The composite spans an export *writes*: [`Project::composite_spans_from`] -/// cut to where the media runs out ([`Project::media_frames`]). +/// cut to where the media runs out ([`Project::media_frames`]), and, with +/// `range` set, to that window too. /// /// The walk itself is the timeline's ([`Project::timeline_frames`]), because a /// caption placed past the last picture holds the timeline open under it and @@ -971,16 +987,106 @@ fn lane_subtitles(project: &Project, fps: f64) -> Vec { /// the frame count [`run`] publishes, the cues [`lane_subtitles`] clips and the /// blocks [`CopyPlan`] copies are then the same number by construction, which /// is what makes [`planned_lanes`]' "cut off there" true of the file. -fn export_spans(project: &Project) -> Vec { +/// +/// `span.start` stays the *project's* own timeline coordinate throughout -- +/// what [`Project::composite_color_at`] and its fit sibling are keyed on -- so +/// a caller writing a range-relative output shifts it at the one place that +/// actually emits a position (`CopyPlan`'s own region, since the encode loop +/// counts pictures rather than reading `span.start` for its output clock). +/// Trimming the left edge mid-span moves `from`'s source frame by +/// [`Speed::source_at`], the same mapping a legal cut is placed by. +fn export_spans(project: &Project, range: Option<(u32, u32)>) -> Vec { let end = project.media_frames(); let mut spans = project.composite_spans_from(0); spans.retain(|span| span.start < end); for span in &mut spans { span.len = span.len.min(end - span.start); } + let Some((r_start, r_end)) = range else { + return spans; + }; + let r_end = r_end.min(end).max(r_start); + spans.retain(|span| span.start < r_end && span.start + span.len > r_start); + for span in &mut spans { + if span.start < r_start { + let cut = r_start - span.start; + if let Some((source, in_frame)) = span.from { + span.from = Some((source, in_frame + span.speed.source_at(cut))); + } + span.len -= cut; + span.start = r_start; + } + span.len = span.len.min(r_end - span.start); + } spans } +/// The cross-dissolve this span's tail owes its successor, or `None` for a +/// hard cut. `(b_source, b_in_frame, window, b_start)`: which source and +/// source frame the dissolve's B side starts reading, how many *output* +/// frames the blend ramps across, and where B sits on the timeline (which is +/// what its own grade and fit are keyed on, [`Project::composite_color_at`] +/// and [`Project::composite_fit_at`]). +/// +/// [`Clip::transition_out`] is trusted only after adjacency is checked again +/// here: a trim or a split since it was set leaves the stored number in +/// place but not its meaning, so a stale one plays as the hard cut it now +/// is rather than as a dissolve into a clip that no longer follows. +fn dissolve_window(project: &Project, span: &crate::project::Span) -> Option<(usize, u32, u32, u32)> { + let (source, _) = span.from?; + let (lane, idx) = project.composite_clip_at(span.start)?; + let clips = project.lane(lane); + let a = clips.get(idx)?; + if a.source != source || a.transition_out == 0 { + return None; + } + let b = clips.get(idx + 1)?; + if a.end() != b.start { + return None; // trimmed or split apart since the dissolve was set + } + // The span must run uninterrupted all the way to A's own end: a higher + // video lane taking over before that means there is no tail of A left + // here to blend into anything. + if span.start + span.len != a.end() { + return None; + } + let window = a + .transition_out + .min(a.frames()) + .min(b.frames()) + .min(span.len); + (window > 0).then_some((b.source, b.in_frame, window, b.start)) +} + +/// `B`'s weight in [`blend_i420`] at output frame `idx_in_window` of `window` +/// (`idx_in_window < window`): a ramp from just above 0 to just below 1 that +/// never actually reaches either end, so the first blended frame still shows +/// a trace of A and the last still a trace of B -- the cut a hard transition +/// would have made lands one frame *after* the window, at full B, rather than +/// inside it. +fn dissolve_weight(idx_in_window: u32, window: u32) -> f32 { + (idx_in_window + 1) as f32 / (window + 1) as f32 +} + +/// A dissolve's B side, open beside A's own decoder for this span's tail: +/// its own decoder, and everything [`place_picture`] needs to put its frames +/// on the same canvas, in the same space, graded the way B is graded rather +/// than the way A is -- [`Project::composite_color_at`]/`composite_fit_at` +/// asked at B's own start, not at the timeline position the blend writes to, +/// which is still inside A's span. +struct Dissolve<'a> { + /// How many output frames the blend ramps across. + window: u32, + /// The first output frame of this span's tail that is inside the window. + tail_start: u32, + decoder: ClipDecoder, + mapper: Option<&'a ToneMapper>, + remap: Option<(Matrix, Matrix)>, + grade: Option, + canvas: Composer, + graded: (Vec, Vec, Vec), +} + /// The track's cues where the *exported* timeline puts them, which is the only /// clock the file has: the export writes timeline frame 0 onwards and nothing /// else, exactly as the sound is mixed from frame 0 and resized to the @@ -1257,14 +1363,20 @@ pub fn planned_seats( // a Matroska file has none -- so every mkv source re-encodes, however // untouched its lane is. Extension only, which is what `is_matroska` // reads, so this costs nothing beyond what is already open. - let copyable = !forces_encode(project) + let copyable = !forces_encode(project, settings.range.is_some()) && !project .sources() .iter() .any(|source| crate::demux::is_matroska(&source.path)); ( video, - audio_label(project, settings.format, has_sound(project), Some(copyable)), + audio_label( + project, + settings.format, + has_sound(project), + Some(copyable), + settings.range.is_some(), + ), ) } @@ -1311,7 +1423,17 @@ fn copy_audio( mkv: bool, shared: &Shared, sample_rate: Option, + range: Option<(u32, u32)>, ) -> crate::Result> { + // A ranged export needs an exact offset and an exact length, which a + // packet copy cannot give -- it carries whole segments named by + // `audio_segments_from(0, ..)`, not an arbitrary window into them. The + // decoded path already resamples per segment, so it is the one that can + // start and stop anywhere; this falls to it exactly as a speeded or + // equalized lane already does. + if range.is_some() { + return encode_audio(project, meta, kbps, mkv, shared, sample_rate, range); + } // The segments name their source, and the copy carries its packet-rounding // debt across a source join exactly as across a cut, so a timeline spanning // files stays in sync. A source whose AAC parameters disagree with the @@ -1352,7 +1474,7 @@ fn copy_audio( } } let [segments] = &lanes[..] else { - return encode_audio(project, meta, kbps, mkv, shared, sample_rate); + return encode_audio(project, meta, kbps, mkv, shared, sample_rate, None); }; // ...and the same list names *which* lane those clips sit on, which is the // only way to ask what has been done to them. @@ -1390,7 +1512,7 @@ fn copy_audio( // such a lane would write it at unity and unlimited, silently. let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal()); if speeded || equalized(project) || mastered(project) { - return encode_audio(project, meta, kbps, mkv, shared, sample_rate); + return encode_audio(project, meta, kbps, mkv, shared, sample_rate, None); } // What is left is a copy the *sources* may still not be able to give: AAC // inside a Matroska file (readable, but not out of a sample table this walks @@ -1410,7 +1532,7 @@ fn copy_audio( // (they are not in a sample table) and every one of them re-encodes. opus_pre_skip: None, })), - Err(_) => encode_audio(project, meta, kbps, mkv, shared, sample_rate), + Err(_) => encode_audio(project, meta, kbps, mkv, shared, sample_rate, None), } } @@ -1471,7 +1593,9 @@ struct CopyRegion { source: usize, /// Blocks of that source, in the file's own decode order. blocks: std::ops::Range, - /// The timeline frame the region's first picture is shown at. + /// The *output* frame the region's first picture is shown at -- the + /// project's own timeline frame less the range's own start, since a + /// ranged export's file starts a fresh clock at zero. start: u32, } @@ -1489,12 +1613,28 @@ impl CopyPlan { let mut sources: Vec> = (0..entries.len()).map(|_| None).collect(); let mut declared: Option<(Vec, ColorDescription)> = None; let mut regions: Vec = Vec::new(); - for span in export_spans(project) { + let r_start = settings.range.map_or(0, |(s, _)| s); + for span in export_spans(project, settings.range) { + let out_start = span.start - r_start; // A gap is black frames, which only an encoder makes. let (source, in_frame) = span.from?; if !span.speed.is_normal() { return None; } + // A copied packet is the source's own picture, never a blend: a + // live dissolve on this span's tail forces the whole video track + // through the encoder, exactly as a grade or a speed does below. + // + // corner-cut: the whole file falls back rather than only the + // clips either side of the dissolve -- [`CopyPlan`] is already + // all-or-nothing per export ([`CopyPlan`]'s own doc comment + // states why), so one dissolve on a two-hour film re-encodes all + // of it. Upgrade path: splice a re-encoded region between two + // copied ones, which needs the sample-table writer that doc + // comment already names as the cost of a finer copy. + if dissolve_window(project, &span).is_some() { + return None; + } // The grade playback shows, which a copied packet never went // through. `None` and the identity are the same untouched picture. if project @@ -1554,14 +1694,14 @@ impl CopyPlan { if last.source == source && last.blocks.end == start && last.start + (last.blocks.end - last.blocks.start) as u32 - == span.start => + == out_start => { last.blocks.end = end; } _ => regions.push(CopyRegion { source, blocks: start..end, - start: span.start, + start: out_start, }), } } @@ -1666,21 +1806,25 @@ fn encode_audio( mkv: bool, shared: &Shared, sample_rate: Option, + range: Option<(u32, u32)>, ) -> crate::Result> { let sources = project.audio_sources(); - let segs = project.audio_segments_from(0, meta.frame_rate); - let eqs = project.audio_eqs_from(0, meta.frame_rate); - let speeds = project.audio_speeds_from(0, meta.frame_rate); + let offset = range.map_or(0, |(s, _)| s); + let segs = project.audio_segments_from(offset, meta.frame_rate); + let eqs = project.audio_eqs_from(offset, meta.frame_rate); + let speeds = project.audio_speeds_from(offset, meta.frame_rate); + let fades = project.audio_fades_from(offset, meta.frame_rate); // Coarse stage timers, in the same voice as `export video: copy` below: an // export of a feature film spends minutes in here before a byte of picture // is written, and which minutes went where is the first question asked of a // slow export. Three lines an export, so they stay on. let mixed = std::time::Instant::now(); - let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at( + let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at_fade( &sources, &segs, &eqs, &speeds, + &fades, &project.audio_gains(), project.limiter(), sample_rate, @@ -1700,10 +1844,12 @@ fn encode_audio( // whole samples on its own, so the sum can miss by a sample or two and a // source that ran out early would leave the track short under a picture // that is not. One resize settles both, as [`run_audio`]'s does. - let total = (f64::from(project.media_frames()) / meta.frame_rate - * f64::from(audio.sample_rate)) - .round() as usize - * channels; + let out_frames = range.map_or(project.media_frames(), |(s, e)| { + e.min(project.media_frames()).saturating_sub(s) + }); + let total = + (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() as usize + * channels; let mut samples: Vec = Vec::with_capacity(total); for chunk in chunks { // The only place a cancelled export can be answered before the whole @@ -2151,7 +2297,12 @@ fn run( // trailing silence over a frozen last frame. The export ends with the last // picture or sound, the cues are cut off there ([`lane_subtitles`]), and // [`planned_subtitles`] says so before the button is pressed. - let total = project.media_frames(); + // The range's own length where one is marked, the media's otherwise -- + // `export_spans` walks the same window, so `done` ends on this `total` + // exactly as it always did. + let total = settings + .range + .map_or(project.media_frames(), |(s, e)| e.min(project.media_frames()).saturating_sub(s)); // The two preview switches are the H.264 mp4 pair's alone. Only that // container carries a colour of its own back out ([`write_video`] tags it // there), so asking any other for a source-space file would write pictures @@ -2211,6 +2362,7 @@ fn run( settings.format.is_mkv(), &shared, sample_rate, + settings.range, ) })? }; @@ -2355,11 +2507,17 @@ fn run( // past it under a trailing caption -- and *which* lane a span comes from is // `composite_spans_from`'s answer, the same one playback shows, so an // export is what was watched. - for span in export_spans(project) { + for span in export_spans(project, settings.range) { // Every clip reopens its own source file at its own in point; the // encoder is *not* reopened, so the export is one continuous stream // whose GOP boundaries need not line up with the cuts -- nor with the // file boundaries, which are just cuts that change the path. + // Whether this span's tail dissolves into its successor -- decided + // before A's own decoder is opened, because it is what decides + // whether A may take the DMA fast path at all: the blend below needs + // A's pixels on the CPU, so a dissolving span never asks for a GPU + // buffer, not even outside its own window. + let dissolve = dissolve_window(project, &span); let (mut pictures, rate, in_frame, color, mapper) = match span.from { Some((source, in_frame)) => { let entry = sources @@ -2378,7 +2536,8 @@ fn run( && remap_into(Some(color), false, out_color.matrix).is_none() && project .composite_color_at(span.start) - .is_none_or(|params| params.is_identity()); + .is_none_or(|params| params.is_identity()) + && dissolve.is_none(); let want = untouched.then(|| encoder.dma_want(meta)).flatten(); // Opened at the file's own frame, which is the only place the // file's numbering is used -- the span's are the timeline's. @@ -2418,6 +2577,33 @@ fn run( meta.height, project.composite_fit_at(span.start), ); + // B's own decoder, opened beside A's: the two streams come off their + // files together for exactly the frames the tail below blends, and + // nothing else in this span ever touches it. + let mut b = dissolve + .map(|(b_source, b_in_frame, window, b_start)| -> crate::Result<_> { + let entry = sources.get(b_source).ok_or_else(|| { + format!("clip names source {b_source} of {}", sources.len()) + })?; + let (b_rate, b_color, _peak) = rates[b_source]; + let b_mapper = tone[b_source].as_ref(); + let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix); + Ok(Dissolve { + window, + tail_start: span.len - window, + decoder: ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)?, + mapper: b_mapper, + remap: b_remap, + grade: project.composite_color_at(b_start).copied(), + canvas: Composer::new( + meta.width, + meta.height, + project.composite_fit_at(b_start), + ), + graded: (Vec::new(), Vec::new(), Vec::new()), + }) + }) + .transpose()?; // Timeline frames, taken a *source* frame at a time: at a rate other // than real time the two are not the same count, and the span says which // source frame each timeline frame shows ([`Speed::source_at`]) -- the @@ -2511,14 +2697,45 @@ fn run( // Once per timeline frame this source frame covers: one at real time // and faster, more when the clip is slowed -- the picture is already // graded and placed, so a held frame costs an encode and no decode. - for _ in 0..repeats { - let coded = match &frame { - Frame::Dma(dma) => encoder.encode_dma(dma, settings.intra_only)?, - Frame::Pixels(..) => { - let (y, u, v, width, height) = - placed.expect("a picture with pixels was placed"); - encoder.encode(y, u, v, width, height, settings.intra_only)? + for r in 0..repeats { + // Inside the window every *output* frame gets its own B + // picture -- decoded fresh here rather than once for the + // whole held A frame -- which is what makes a slowed A's + // tail still ramp one weight per frame shown rather than one + // per source frame. + let in_window = b.as_ref().is_some_and(|d| done_here + r >= d.tail_start); + let coded = match (&mut b, in_window) { + (Some(d), true) => { + let (ay, au, av, aw, ah) = + placed.expect("a dissolving span always decodes to pixels"); + match d.decoder.next()? { + // B's file ran out inside the window: A's own + // picture carries the frame rather than the + // export losing it. + None => encoder.encode(ay, au, av, aw, ah, settings.intra_only)?, + Some(Frame::Dma(_)) => { + unreachable!("b's decoder was opened with no DMA want") + } + Some(Frame::Pixels(by, bu, bv, bw, bh)) => { + let (by, bu, bv, _, _) = place_picture( + by, bu, bv, bw, bh, d.grade, d.remap, d.mapper, + &mut d.graded, &mut d.canvas, + ); + let idx_in_window = done_here + r - d.tail_start; + let t = dissolve_weight(idx_in_window, d.window); + let (y, u, v) = blend_i420((ay, au, av), (by, bu, bv), t); + encoder.encode(&y, &u, &v, aw, ah, settings.intra_only)? + } + } } + _ => match &frame { + Frame::Dma(dma) => encoder.encode_dma(dma, settings.intra_only)?, + Frame::Pixels(..) => { + let (y, u, v, width, height) = + placed.expect("a picture with pixels was placed"); + encoder.encode(y, u, v, width, height, settings.intra_only)? + } + }, }; if let Some((au, key)) = coded { write_video( @@ -2753,27 +2970,32 @@ fn run_audio( ) -> crate::Result<()> { let format = settings.format; let sources = project.audio_sources(); - let segs = project.audio_segments_from(0, meta.frame_rate); + let offset = settings.range.map_or(0, |(s, _)| s); + let segs = project.audio_segments_from(offset, meta.frame_rate); // The equalizers with them, so what is written is what is heard down to the // filter: the worker applies them per segment before the lanes are summed // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point // 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 eqs = project.audio_eqs_from(offset, meta.frame_rate); // ...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 speeds = project.audio_speeds_from(offset, meta.frame_rate); + // ...and the fades with them, the same choke-point reason again: a clip's + // envelope runs inside the worker playback feeds from too. + let fades = project.audio_fades_from(offset, meta.frame_rate); // ...and the mix over both: each lane's volume into the sum, the master // limiter out of it. The same opener playback's feeder reads from, so a // file is written at the levels it was heard at -- there is no second // place here that could mix it differently. - let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at( + let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at_fade( &sources, &segs, &eqs, &speeds, + &fades, &project.audio_gains(), project.limiter(), sample_rate, @@ -2783,11 +3005,15 @@ fn run_audio( }; // The picture path's line, for a file that is sound alone: there is sound // by the line above, so this names the encoder writing it. - *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true, None).to_string()); + *shared.encoders.lock().unwrap() = Some( + audio_label(project, format, true, None, settings.range.is_some()).to_string(), + ); let channels = usize::from(audio.channels); - let frames = (f64::from(project.media_frames()) / meta.frame_rate - * f64::from(audio.sample_rate)) - .round() as u64; + let out_frames = settings.range.map_or(project.media_frames(), |(s, e)| { + e.min(project.media_frames()).saturating_sub(s) + }); + let frames = + (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() as u64; let total = frames as usize * channels; // corner-cut: the whole export sits in memory (4 bytes a sample, so ~23 MB // per minute of 48 kHz stereo). `flacenc::MemSource` wants it that way and @@ -4620,6 +4846,25 @@ mod tests { ); } + #[test] + fn export_spans_clips_to_the_marked_range_keeping_absolute_start() { + let project = Project::single("/nonexistent/film.mkv", 150); + // The whole timeline, unmarked: one span, the source's own length. + let whole = export_spans(&project, None); + assert_eq!(whole.len(), 1); + assert_eq!((whole[0].start, whole[0].len), (0, 150)); + // A range wholly inside the span: `start` stays the timeline's own + // coordinate ([`composite_color_at`] needs that), and the length is + // exactly what the mark asked for. + let clipped = export_spans(&project, Some((30, 100))); + assert_eq!(clipped.len(), 1); + assert_eq!((clipped[0].start, clipped[0].len), (30, 70)); + // A range past the end of the media clamps to it rather than reading + // short on the wrong side. + let past_end = export_spans(&project, Some((100, 500))); + assert_eq!((past_end[0].start, past_end[0].len), (100, 50)); + } + #[test] fn bitrate_clamps_at_both_ends() { let meta = |width, height, frame_rate| VideoMeta { @@ -4748,4 +4993,54 @@ mod tests { // ...and the even one it neighbours opens. assert!(Enc::open(&meta(1920, 1080), &settings).is_ok()); } + + /// Weights ramp from just above 0 to just below 1 and never touch either + /// end -- the frame *after* the window is where a viewer would see plain + /// B, and the window itself never quite repeats a hard cut's own instant. + #[test] + fn dissolve_weight_ramps_strictly_between_zero_and_one() { + assert_eq!(dissolve_weight(0, 1), 0.5, "a one-frame window is the midpoint"); + assert_eq!(dissolve_weight(0, 4), 0.2); + assert_eq!(dissolve_weight(1, 4), 0.4); + assert_eq!(dissolve_weight(2, 4), 0.6); + assert_eq!(dissolve_weight(3, 4), 0.8); + } + + /// [`dissolve_window`] reads [`crate::project::Clip::transition_out`] back + /// only once adjacency is re-checked at render time: two clips a split + /// just made, still touching, still name B by its own source and its own + /// timeline start. + #[test] + fn dissolve_window_names_bs_source_in_frame_window_and_start() { + use crate::project::{Lane, Project}; + let mut p = Project::single("/nonexistent/film.mkv", 20); + assert!(p.split(15)); + assert!(p.set_transition_out(Lane::V1, 0, 5)); + let spans = export_spans(&p, None); + let a_span = spans.iter().find(|s| s.start == 0).expect("clip A's span"); + assert_eq!( + dissolve_window(&p, a_span), + Some((0, 15, 5, 15)), + "b's source, b's in_frame, the window, b's timeline start" + ); + } + + /// A `transition_out` set while two clips touched, then made stale by a + /// trim that opens a gap between them: the number is still in storage, + /// [`dissolve_window`] reads `None` from it, and the span renders as the + /// hard cut two clips that no longer touch actually are. + #[test] + fn a_stale_transition_out_after_a_trim_renders_as_a_hard_cut() { + use crate::project::{Edge, Lane, Project}; + let mut p = Project::single("/nonexistent/film.mkv", 20); + assert!(p.split(15)); + assert!(p.set_transition_out(Lane::V1, 0, 5)); + assert!(p.trim(Lane::V1, 1, Edge::Start, 18, &[100]), "opens a gap"); + let spans = export_spans(&p, None); + let a_span = spans.iter().find(|s| s.start == 0).expect("clip A's span"); + assert!( + dissolve_window(&p, a_span).is_none(), + "b no longer abuts a; hard cut" + ); + } } diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index fe593ba..491c2fb 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -618,6 +618,9 @@ impl PlaybackSession { // *video* open's pair of grouped clips: here there is no picture to // group the sound with, so the video lane starts empty. let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: meta.frame_count, @@ -701,6 +704,9 @@ impl PlaybackSession { color: ColorDescription::default(), }; let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: place_frames(meta.frame_count, IMAGE_ONLY_RATE), @@ -1095,8 +1101,8 @@ impl PlaybackSession { /// the format (or an equalized lane) forces. Pure -- no probe, no file /// opened -- so a card may ask it per repaint; the picture's half costs a /// plugin open and lives in [`crate::export::planned_video`]. - pub fn planned_audio(&self, format: crate::export::Format) -> &'static str { - crate::export::planned_audio(&self.project, format) + pub fn planned_audio(&self, format: crate::export::Format, ranged: bool) -> &'static str { + crate::export::planned_audio(&self.project, format, ranged) } /// The timeline an export started right now would be run against, owned: @@ -1146,8 +1152,12 @@ impl PlaybackSession { /// Why the sound's rate is not a choice for this timeline in this format -- /// [`crate::export::audio_rate_refusal`], asked of the project a front-end /// is holding, and pure for the same reason. - pub fn audio_rate_refusal(&self, format: crate::export::Format) -> Option<&'static str> { - crate::export::audio_rate_refusal(&self.project, format) + pub fn audio_rate_refusal( + &self, + format: crate::export::Format, + ranged: bool, + ) -> Option<&'static str> { + crate::export::audio_rate_refusal(&self.project, format, ranged) } /// Why this session plays silent although the file has sound -- an audio @@ -2548,6 +2558,47 @@ impl PlaybackSession { self.edit(Dirty::Picture, |p| p.set_fit(lane, idx, fit)) } + /// Timeline frames of ramp-up from silence at the start of the clip at + /// `idx` of `lane`. `0` for an index that is not there. + pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 { + self.project.fade_in_of(lane, idx) + } + + /// Sets that clip's fade-in, clamped to its own length. A sound-only + /// edit, same as an equalizer or a fader: no reseek needed. + pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { + self.edit(Dirty::Sound, |p| p.set_fade_in(lane, idx, frames)) + } + + /// Timeline frames of ramp-down to silence at the end of the clip at + /// `idx` of `lane`. `0` for an index that is not there. + pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 { + self.project.fade_out_of(lane, idx) + } + + /// Sets that clip's fade-out. Same promises as [`Self::set_fade_in`]. + pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { + self.edit(Dirty::Sound, |p| p.set_fade_out(lane, idx, frames)) + } + + /// Crossfades the audio clip at `idx` of `lane` into its neighbour, over + /// `frames`. Same promises as [`Project::crossfade`]. + pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { + self.edit(Dirty::Sound, |p| p.crossfade(lane, idx, frames)) + } + + /// Timeline frames of dissolve at the end of the clip at `idx` of `lane`, + /// into its neighbour. `0` for an index that is not there. + pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 { + self.project.transition_out_of(lane, idx) + } + + /// Sets that clip's dissolve into its neighbour, clamped to its own + /// length. A picture edit -- same as a grade or fit policy. + pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { + self.edit(Dirty::Picture, |p| p.set_transition_out(lane, idx, frames)) + } + /// The clip at `idx` -- what a caller copies. It is a pair of source frame /// numbers and nothing else, so a copy stays valid after the clip it came /// from is deleted. `None` past the end. @@ -2625,6 +2676,9 @@ impl PlaybackSession { let source = self.project.import(path, stream); self.note_frames(source, frames, rate); let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: match image { @@ -2800,6 +2854,12 @@ impl PlaybackSession { self.edit(Dirty::Both, Project::undo) } + /// Redoes the last edit [`undo`](Self::undo) took back, and reseeks like + /// a delete. + pub fn redo(&mut self) -> bool { + self.edit(Dirty::Both, Project::redo) + } + /// Takes `path` into the **library**: it becomes a source of this session, /// with its length noted ([`file_frames`](Self::file_frames)), and nothing /// is placed on any lane. What reaches the timeline is decided afterwards, @@ -3248,6 +3308,10 @@ impl PlaybackSession { // speeded, which is the path that decodes the same samples it always // did. let speeds = self.project.audio_speeds_from(target, fps); + // ...and the fades, the same way again: a clip's own envelope runs + // inside its worker, after the rate and the equalizer, so a fade + // edit is audible at once exactly as an EQ edit is. + let fades = self.project.audio_fades_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(); @@ -3277,11 +3341,12 @@ impl PlaybackSession { // one `pread` on a cold 25 GB film is seconds, and this is called // from a ruler drag ([`Audio::spawn_feeder_deferred`]). audio_running = audio.spawn_feeder_deferred(move || { - match AudioSession::open_mixed_streams_live( + match AudioSession::open_mixed_streams_live_fade( &sources, &segs, &eqs, &speeds, + &fades, &gains, limiter, Some(&worker_controls), diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 5c65de2..d341299 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -436,6 +436,26 @@ pub struct Clip { /// changes is how many *timeline* frames that range is spread over /// ([`Clip::frames`]). pub speed: Speed, + /// Timeline frames of ramp-up from silence at the clip's own start, inline + /// like [`Clip::fit`] and [`Clip::speed`] for the same reason: one small + /// number with nothing to share, and every consumer (mixer, exporter) wants + /// it sitting right next to the frame range it shapes. Clamped to the + /// clip's own length by the setter -- never wider than the clip is long. + pub fade_in: u32, + /// Timeline frames of ramp-down to silence at the clip's own end. Same + /// promises as [`Clip::fade_in`]. + pub fade_out: u32, + /// Timeline frames of cross-dissolve into the clip immediately after this + /// one on the same video lane, at this clip's own end -- `0` for a hard + /// cut. Inline like [`Clip::fade_in`]/[`Clip::fade_out`] for the same + /// reason, and clamped the same way by its setter + /// ([`Project::set_transition_out`]): never wider than this clip's own + /// length, nor than the successor it dissolves into. Meaningless -- and + /// left as whatever it was -- the moment the next clip stops abutting + /// this one; a reader that cares checks adjacency itself rather than + /// trusting this field alone, exactly as a stored fade is trusted only + /// because a clip's own length is checked beside it. + pub transition_out: u32, } impl Clip { @@ -754,6 +774,62 @@ pub struct Stretch { pub timeline_secs: f64, } +/// What one audio segment's gain envelope is: [`Project::audio_fades_from`] +/// builds it off the clip's own [`Clip::fade_in`]/[`Clip::fade_out`], resolved +/// against where in the *clip* -- not the segment, which may start mid-clip +/// on a seek -- this segment's first frame lands. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Fade { + /// How many of the clip's own frames already played before this + /// segment's first frame: `0` unless playback started mid-clip. + pub elapsed: u32, + /// The clip's [`Clip::fade_in`]. + pub fade_in: u32, + /// The clip's [`Clip::fade_out`]. + pub fade_out: u32, + /// The clip's own [`Clip::frames`] -- the envelope's whole width, of + /// which this segment may only cover the tail. + pub total: u32, +} + +impl Fade { + /// The gain at clip-relative frame `pos`, an equal-power curve on each + /// edge that plays through unchanged (gain `1.0`) wherever neither ramp + /// reaches: `sin(t * pi/2)` for `t` the fraction of the way through the + /// ramp, so a fade lands on silence at its very first (or very last) + /// frame and reaches unity smoothly rather than at a constant slope -- + /// the same curve [`Project::crossfade`] relies on to keep two clips' + /// sum around one level through the join. Both ramps multiply where a + /// clip is short enough for them to overlap. + fn gain_at(self, pos: u32) -> f32 { + let mut g = 1.0f32; + if self.fade_in > 0 && pos < self.fade_in { + let t = pos as f32 / self.fade_in as f32; + g *= (t * std::f32::consts::FRAC_PI_2).sin(); + } + if self.fade_out > 0 { + let out_start = self.total.saturating_sub(self.fade_out); + if pos >= out_start { + let remaining = self.total.saturating_sub(pos); + let t = remaining as f32 / self.fade_out as f32; + g *= (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin(); + } + } + g + } + + /// Multiplies `frames` in place -- `channels`-wide interleaved samples, + /// starting at this segment's own frame `0` -- by [`Self::gain_at`]. + pub fn apply(self, frames: &mut [f32], channels: usize) { + for (i, block) in frames.chunks_mut(channels).enumerate() { + let g = self.gain_at(self.elapsed.saturating_add(i as u32)); + for s in block { + *s *= g; + } + } + } +} + /// What a save writes and a load takes back: the sources, every lane in /// display order with its kind, and the equalizer and colour tables their clips /// index into -- [`Project::without_orphan_sources`] out, @@ -791,6 +867,10 @@ pub struct Project { /// whole lane list, so adding a lane undoes as well. Bounded by /// [`HISTORY_CAP`]: at the cap the oldest step goes. history: Vec>, + /// Lane lists `undo` has stepped past; `redo` pops one. Cleared by + /// [`Project::snapshot`], since a fresh edit invalidates whatever branch + /// the undone steps came from. Not saved to `.edith`, matching `history`. + redo: Vec>, /// Never rolled back by an undo: an id retired by an undone split must not /// come back and group two clips that were never together. next_link: u32, @@ -819,6 +899,9 @@ impl Project { /// is clamped to one frame. pub fn single(path: impl AsRef, frame_count: u32) -> Self { let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: frame_count.max(1), @@ -839,6 +922,7 @@ impl Project { color: Vec::new(), transform: Vec::new(), history: Vec::new(), + redo: Vec::new(), next_link: 1, subtitles: Vec::new(), limiter: Limiter::default(), @@ -982,6 +1066,7 @@ impl Project { color, transform, history: Vec::new(), + redo: Vec::new(), next_link, subtitles: Vec::new(), limiter: Limiter::default(), @@ -1213,6 +1298,9 @@ impl Project { self.snapshot(); let start = self.timeline_frames(); let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame: 0, out_frame: frame_count.max(1), @@ -2500,6 +2588,107 @@ impl Project { true } + /// Timeline frames of ramp-up from silence at the start of the clip at + /// `idx` of `lane`. `0` for an index that is not there, same as a clip + /// that has none. + pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 { + self.lane(lane).get(idx).map_or(0, |c| c.fade_in) + } + + /// Sets it, clamped to the clip's own length ([`Clip::frames`]) -- a fade + /// can shrink a clip's audible middle to nothing but never ask for more + /// ramp than the clip has frames. One undo step like [`Project::set_fit`], + /// and `false` (no history) for an index that is not there. + pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { + if idx >= self.lane(lane).len() { + return false; + } + self.snapshot(); + let clip = &mut self.lane_mut(lane).expect("checked above")[idx]; + clip.fade_in = frames.min(clip.frames()); + true + } + + /// Timeline frames of ramp-down to silence at the end of the clip at + /// `idx` of `lane`. Same promise as [`Project::fade_in_of`]. + pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 { + self.lane(lane).get(idx).map_or(0, |c| c.fade_out) + } + + /// Sets it. Same promises as [`Project::set_fade_in`]. + pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { + if idx >= self.lane(lane).len() { + return false; + } + self.snapshot(); + let clip = &mut self.lane_mut(lane).expect("checked above")[idx]; + clip.fade_out = frames.min(clip.frames()); + true + } + + /// Timeline frames of cross-dissolve the clip at `idx` of `lane` plays + /// into its successor, at its own end. `0` for an index that is not + /// there, same as a clip that has none. + pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 { + self.lane(lane).get(idx).map_or(0, |c| c.transition_out) + } + + /// Sets it, clamped to the clip's own length and to how many frames its + /// successor on `lane` actually offers -- a dissolve can shrink a clip's + /// visible middle to nothing but never ask for more than the two clips + /// between them have. `false` -- no history -- unless `lane` is video, + /// `idx + 1` is in bounds, and the two clips are adjacent: the second's + /// [`Clip::start`] is exactly the first's [`Clip::end`], no gap between + /// them. One undo step like [`Project::set_fade_out`]. + pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { + if lane.kind != LaneKind::Video { + return false; + } + let clips = self.lane(lane); + let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else { + return false; + }; + if a.end() != b.start { + return false; + } + let cap = a.frames().min(b.frames()); + self.snapshot(); + self.lane_mut(lane).expect("checked above")[idx].transition_out = frames.min(cap); + true + } + + /// Crossfades the audio clip at `idx` of `lane` into the one immediately + /// after it, over `frames` timeline frames: sets `idx`'s + /// [`Clip::fade_out`] and its neighbour's [`Clip::fade_in`] to `frames`, + /// each clamped to its own clip's length. `false` -- no history -- unless + /// `lane` is audio, `idx + 1` is in bounds, and the two clips are + /// adjacent: the second's [`Clip::start`] is exactly the first's + /// [`Clip::end`], no gap between them. + /// + /// This is the whole mechanism, not a stand-in for one: a *real* + /// cross-fade -- both takes heard at once, blending -- is what two clips + /// **overlapping** on separate lanes already get for free from the + /// mixer's own per-lane sum ([`crate::audio::open_mixed_streams_master`]). + /// This call only shapes the edges of two clips already sitting + /// end-to-end on *one* lane, so the join between them fades like one did. + pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { + if lane.kind != LaneKind::Audio { + return false; + } + let clips = self.lane(lane); + let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else { + return false; + }; + if a.end() != b.start { + return false; + } + self.snapshot(); + let clips = self.lane_mut(lane).expect("checked above"); + clips[idx].fade_out = frames.min(clips[idx].frames()); + clips[idx + 1].fade_in = frames.min(clips[idx + 1].frames()); + true + } + /// Every frame number on every lane rewritten onto a timeline counted at /// another rate: `k` is old timeline frames per new one, `counts` is how /// long each source is on the *new* timeline (indexed as @@ -2916,8 +3105,25 @@ impl Project { tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so"); tail.start = timeline_frame; tail.link = right_of(orig[data_i]); + // A split makes a new edge for each half, and a fade is a promise + // about an edge: only the half that *kept* the original edge + // keeps that fade, re-clamped to its own now-shorter length (a + // cut inside the ramp shortens it, never leaves it pointing past + // the clip it is on); the edge the cut itself made starts, or + // ends, flat -- there was no silence there to ramp out of. + tail.fade_in = 0; + tail.fade_out = tail.fade_out.min(tail.frames()); + // A dissolve is a promise about the *end* edge, same as + // `fade_out`: only the half that kept the clip's original end + // (the tail) keeps it, re-clamped to its own now-shorter length; + // the head's new end is the cut the razor just made, which starts + // flat -- there was no successor to dissolve into there. + tail.transition_out = tail.transition_out.min(tail.frames()); data.clips[idx].out_frame = tail.in_frame; data.clips[idx].link = orig[data_i]; + data.clips[idx].fade_out = 0; + data.clips[idx].transition_out = 0; + data.clips[idx].fade_in = data.clips[idx].fade_in.min(data.clips[idx].frames()); data.clips.insert(idx + 1, tail); } true @@ -3249,6 +3455,9 @@ impl Project { } self.snapshot(); let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: timeline_frame, link: None, ..clip @@ -3288,6 +3497,9 @@ impl Project { self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new())); } let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: timeline_frame, link: Some(self.new_link()), ..clip @@ -3863,6 +4075,9 @@ impl Project { } self.snapshot(); let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: at, link: Some(self.new_link()), ..clip @@ -4322,6 +4537,13 @@ impl Project { self.history.len() } + /// How many redo steps are stacked: what the sweep asks to check `undo` + /// left a branch behind, and that a fresh edit clears it. + #[cfg(test)] + pub(crate) fn redo_len(&self) -> usize { + self.redo.len() + } + /// Every part of the project that an edit can change, as comparable /// values: what the sweep's undo round-trip asks "byte identical?" of. #[cfg(test)] @@ -4334,11 +4556,27 @@ impl Project { } /// Restore every lane from before the last successful edit -- the clips and - /// the lane list both. `false` when there is nothing left to undo. + /// the lane list both. `false` when there is nothing left to undo. Pushes + /// the lanes just left onto the redo stack, so [`Project::redo`] can walk + /// forward again. pub fn undo(&mut self) -> bool { match self.history.pop() { Some(prev) => { - self.lanes = prev; + self.redo.push(std::mem::replace(&mut self.lanes, prev)); + true + } + None => false, + } + } + + /// Restore every lane from before the last [`Project::undo`] -- the + /// mirror of `undo`, walking the redo stack it fills. `false` when there + /// is nothing left to redo, which is also true after any fresh edit: a + /// new [`Project::snapshot`] clears the branch `undo` left behind. + pub fn redo(&mut self) -> bool { + match self.redo.pop() { + Some(next) => { + self.history.push(std::mem::replace(&mut self.lanes, next)); true } None => false, @@ -4356,6 +4594,7 @@ impl Project { eq: self.eq.clone(), color: self.color.clone(), history: Vec::new(), + redo: Vec::new(), next_link: self.next_link, subtitles: self.subtitles.clone(), limiter: self.limiter, @@ -4528,13 +4767,52 @@ impl Project { .collect() } + /// The fade envelope 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 has neither a + /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for + /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason. + pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec>> { + self.audio_lanes() + .into_iter() + .map(|lane| self.lane_fades_from(lane, timeline_frame, fps)) + .collect() + } + + /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching + /// [`lane_segments_from`](Project::lane_segments_from) entry for entry. + pub fn lane_fades_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| { + let (idx, _) = self.map(lane, span.start)?; + let clip = self.lane(lane).get(idx)?; + (clip.fade_in > 0 || clip.fade_out > 0).then(|| Fade { + // `span.len` is the clip's own remaining frames from + // `span.start` on -- shorter than `clip.frames()` only + // when this is the first span of a seek mid-clip. + elapsed: clip.frames().saturating_sub(span.len), + fade_in: clip.fade_in, + fade_out: clip.fade_out, + total: clip.frames(), + }) + }) + .collect() + } + /// Pushes the undo snapshot. Every mutating method calls this once, *after* /// it has decided it will succeed -- a refusal must not cost an undo step. + /// Clears the redo stack: a fresh edit branches off from here, so whatever + /// `undo` had left to redo is no longer where this edit leads back to. fn snapshot(&mut self) { if self.history.len() == HISTORY_CAP { self.history.remove(0); } self.history.push(self.lanes.clone()); + self.redo.clear(); } fn new_link(&mut self) -> u32 { @@ -4873,6 +5151,9 @@ fn clear(clips: &mut Vec, start: u32, end: u32) { && c.start < start { out.push(Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, out_frame: c.in_frame + keep.min(c.len()), link: None, ..c @@ -4886,6 +5167,9 @@ fn clear(clips: &mut Vec, start: u32, end: u32) { && c.end() > end { out.push(Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: end, in_frame: c.out_frame - keep.min(c.len()), link: None, @@ -4992,6 +5276,9 @@ mod tests { /// A contiguous placement, group id ignored: what most assertions compare. fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip { Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame, out_frame, @@ -5120,6 +5407,145 @@ mod tests { ); } + /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at + /// the very first frame of a fade-in, unity at its last, equal-power + /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches + /// at all. + #[test] + fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() { + let f = Fade { + elapsed: 0, + fade_in: 10, + fade_out: 10, + total: 40, + }; + assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame"); + assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends"); + let midpoint = std::f32::consts::FRAC_PI_2 * 0.5; + assert!( + (f.gain_at(5) - midpoint.sin()).abs() < 1e-6, + "equal-power midpoint is sin(pi/4)" + ); + assert_eq!(f.gain_at(20), 1.0, "unchanged in the body, past either ramp"); + // The fade-out is the same curve, mirrored, counting down from the + // clip's end: unity at the frame the ramp starts, the same + // equal-power midpoint, and -- since `total` itself is one past the + // clip's last valid frame -- the very last frame is one step short of + // the silence a fade-in's own frame `0` lands on exactly. + assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts"); + assert!( + (f.gain_at(35) - midpoint.sin()).abs() < 1e-6, + "the fade-out's own equal-power midpoint" + ); + assert!( + (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6, + "one step short of silence at the clip's last playable frame" + ); + } + + /// [`Project::crossfade`] refuses a non-audio lane and two clips that are + /// not adjacent, and otherwise sets the shared edge's fades and nothing + /// else. + #[test] + fn crossfade_only_joins_adjacent_audio_clips() { + let mut p = Project::single(FILE, 20); + assert!(p.split(10)); + assert!( + !p.crossfade(Lane::V1, 0, 5), + "video is not an audio lane" + ); + assert!( + !p.crossfade(Lane::A1, 1, 5), + "there is no clip after idx 1" + ); + assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent"); + let a = p.lane(Lane::A1); + assert_eq!(a[0].fade_out, 5); + assert_eq!(a[1].fade_in, 5); + assert_eq!(a[0].fade_in, 0); + assert_eq!(a[1].fade_out, 0); + + // A gap between two clips is not adjacency, even on an audio lane. + let mut p2 = Project::single(FILE, 1); + let a2 = p2.add_lane(LaneKind::Audio); + assert!(p2.place(a2, 0, clip(0, 0, 3, 0))); + assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one"); + assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent"); + } + + /// The rule [`Project::write_split`] follows for the edge the razor makes: + /// the left half keeps its old [`Clip::fade_in`] (clamped to its new, + /// shorter length) and loses its [`Clip::fade_out`]; the right half is the + /// mirror image. + #[test] + fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() { + let mut p = Project::single(FILE, 20); + assert!(p.set_fade_in(Lane::V1, 0, 15)); + assert!(p.set_fade_out(Lane::V1, 0, 15)); + assert!(p.split(5)); + let v = p.lane(Lane::V1); + assert_eq!(v[0].fade_in, 5, "the left half's kept fade-in, clamped to 5 frames"); + assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat"); + assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat"); + assert_eq!(v[1].fade_out, 15, "the right half's kept fade-out, unclamped: 15 frames fit in 15"); + } + + /// [`Project::set_transition_out`] refuses a non-video lane, a clip with + /// no successor, and two clips that do not touch, and otherwise clamps + /// the dissolve to the shorter of the two clips it spans. + #[test] + fn set_transition_out_only_dissolves_adjacent_video_clips() { + let mut p = Project::single(FILE, 20); + assert!(p.split(15), "a short 5-frame tail to clamp against"); + assert!( + !p.set_transition_out(Lane::A1, 0, 5), + "audio is not a video lane" + ); + assert!( + !p.set_transition_out(Lane::V1, 1, 5), + "there is no clip after idx 1" + ); + assert!( + p.set_transition_out(Lane::V1, 0, 100), + "the two halves are adjacent" + ); + assert_eq!( + p.transition_out_of(Lane::V1, 0), + 5, + "clamped to the shorter neighbour's 5 frames" + ); + + // A gap between two clips is not adjacency, even on the video lane. + let mut p2 = Project::single(FILE, 1); + let v2 = p2.add_lane(LaneKind::Video); + assert!(p2.place(v2, 0, clip(0, 0, 3, 0))); + assert!(p2.place(v2, 5, clip(5, 3, 6, 0)), "a gap before this one"); + assert!(!p2.set_transition_out(v2, 0, 5), "a gap is not adjacent"); + } + + /// The rule [`Project::write_split`] follows for [`Clip::transition_out`], + /// same shape as [`a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge`]: + /// only the half that kept the clip's original *end* keeps the dissolve, + /// re-clamped to its own now-shorter length; the head the cut just made + /// has no successor to dissolve into and starts flat. + #[test] + fn a_split_clamps_the_tail_transition_and_zeroes_the_head() { + let mut p = Project::single(FILE, 20); + assert!( + !p.set_transition_out(Lane::V1, 0, 0), + "one clip on the lane, no successor to dissolve into yet" + ); + // Give the clip a dissolve by hand, then cut it in two. + p.lane_mut(Lane::V1).unwrap()[0].transition_out = 15; + assert!(p.split(5)); + let v = p.lane(Lane::V1); + assert_eq!(v[0].transition_out, 0, "the cut edge it made has no successor"); + assert_eq!( + v[1].transition_out, 15, + "the tail's kept dissolve, unclamped: 15 frames fit in 15" + ); + } + /// The music video's own path: the take comes apart into halves that carry /// ids of their own, one undo puts it back, and two clips over the same /// frames become one take again by hand. @@ -6300,14 +6726,18 @@ mod tests { /// table like the eq and the grade: there is nothing for a table to share. /// It costs the clip nothing at all -- the fields before it (a `usize` /// source and two `Option`s) already left the struct padded to 40 - /// bytes, and the byte landed in that padding. This is the assert that says - /// so: a clip that grew a word grew every undo snapshot and every clipboard - /// copy with it. + /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are two + /// `u32`s after it (48 bytes), and `transition_out` is a third word -- + /// 52 bytes of fields, but the struct's own alignment is 8 (from the + /// `usize` source and the 8-byte `Option` link), so an odd number of + /// words after it pads out to the next multiple of 8: 56 bytes total. + /// This is the assert that says so: a clip that grows a word grows every + /// undo snapshot and every clipboard copy with it. #[test] fn a_fit_policy_costs_the_clip_no_word() { assert_eq!( std::mem::size_of::(), - 40, + 56, "Clip changed size: {} bytes", std::mem::size_of::() ); @@ -6316,6 +6746,9 @@ mod tests { /// The clip a copy would hand back: source `[100, 102)`, unrelated to /// anything in `three()` so it is recognisable wherever it lands. const PASTED: Clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 100, out_frame: 102, @@ -6388,6 +6821,9 @@ mod tests { let mut p = three(); let wav = p.import("/nonexistent/song.wav", 0); let copied = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, source: wav, ..PASTED }; @@ -7071,6 +7507,34 @@ mod tests { assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]); } + #[test] + fn redo_restores_exactly() { + let mut p = three(); + assert!(p.delete(1)); + let after_delete = p.parts(); + assert!(p.undo()); + assert!(p.redo()); + assert_eq!(p.parts(), after_delete, "redo lands back byte-identical"); + assert!(!p.redo(), "empty redo stack"); + } + + #[test] + fn edit_after_undo_empties_redo() { + let mut p = three(); + assert!(p.delete(1)); + assert!(p.undo()); + assert_eq!(p.redo_len(), 1, "undo left a branch to redo"); + assert!(p.split(1), "a fresh edit"); + assert_eq!(p.redo_len(), 0, "the fresh edit clears it"); + assert!(!p.redo(), "so redo has nothing left"); + } + + #[test] + fn redo_on_empty_stack_is_false() { + let mut p = three(); + assert!(!p.redo(), "nothing has been undone yet"); + } + /// Past the cap the *oldest* step goes, so a long session undoes exactly /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever. #[test] @@ -7626,8 +8090,8 @@ mod tests { fn a_clip_is_still_a_small_copy() { assert_eq!( std::mem::size_of::(), - 40, - "Clip changed size -- 32 before the colour index, 40 after" + 56, + "Clip changed size -- 32 before the colour index, 40 before the fades, 48 after, 56 with the transition" ); } @@ -7709,6 +8173,9 @@ mod tests { // format could not have written, are refused at this door too. let eqd = |i: u16| { vec![Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, eq: Some(i), ..video[0] }] @@ -7745,6 +8212,9 @@ mod tests { // The same two refusals for a colour, at the same door. let graded = |i: u16| { vec![Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, color: Some(i), fit: FitPolicy::default(), speed: Speed::NORMAL, @@ -7803,6 +8273,9 @@ mod tests { fn a_link_id_is_never_two_clips_of_one_lane() { let sources = vec![Source::new(FILE, 0)]; let linked = |start, in_frame, out_frame, link| Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame, out_frame, @@ -8580,6 +9053,9 @@ mod tests { fn a_group_may_span_any_lane() { let lane = |kind, clips: Vec| LaneData::new(kind, clips); let one = |start: u32, end: u32, link| Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame: start, out_frame: end, diff --git a/crates/engine/src/proxy.rs b/crates/engine/src/proxy.rs index 645cc4b..eb30564 100644 --- a/crates/engine/src/proxy.rs +++ b/crates/engine/src/proxy.rs @@ -487,6 +487,9 @@ fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result (Vec, Vec, Vec) { + let t = t.clamp(0.0, 1.0); + let plane = |a: &[u8], b: &[u8]| -> Vec { + assert_eq!(a.len(), b.len(), "blend_i420: mismatched plane sizes"); + a.iter() + .zip(b) + .map(|(&av, &bv)| (av as f32 + (bv as f32 - av as f32) * t).round() as u8) + .collect() + }; + (plane(a.0, b.0), plane(a.1, b.1), plane(a.2, b.2)) +} + /// Resizes `plane` to `len` and sets every byte to `value` -- a canvas reused /// across frames is refilled, not reallocated. fn fill(plane: &mut Vec, len: usize, value: u8) { @@ -1315,4 +1333,23 @@ mod tests { let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs); println!("scale::Composer::place 1280x720 onto 1920x1080 Fit: {ms:.3} ms/frame"); } + + /// [`blend_i420`] at the midpoint of two solid-colour frames lands exactly + /// on the 50/50 average, on every plane -- the synthetic stand-in for "the + /// dissolve's midpoint frame looks like the average colour" the export + /// path is built on. + #[test] + fn blend_i420_is_50_50_at_the_midpoint() { + let a = (vec![0u8; 16], vec![10u8; 4], vec![20u8; 4]); + let b = (vec![100u8; 16], vec![50u8; 4], vec![120u8; 4]); + let (y, u, v) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 0.5); + assert!(y.iter().all(|&p| p == 50), "Y midpoint: {y:?}"); + assert!(u.iter().all(|&p| p == 30), "U midpoint: {u:?}"); + assert!(v.iter().all(|&p| p == 70), "V midpoint: {v:?}"); + // The edges hand back each frame untouched. + let (y0, _, _) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 0.0); + assert_eq!(y0, a.0); + let (y1, _, _) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 1.0); + assert_eq!(y1, b.0); + } } diff --git a/crates/engine/src/silence.rs b/crates/engine/src/silence.rs index 0b8e6cd..b2ae6b5 100644 --- a/crates/engine/src/silence.rs +++ b/crates/engine/src/silence.rs @@ -295,6 +295,9 @@ mod tests { fn clip(start: u32, in_frame: u32, out_frame: u32, speed: Speed) -> Clip { Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame, out_frame, diff --git a/crates/engine/src/sweep.rs b/crates/engine/src/sweep.rs index 7e8fef9..12c8c2f 100644 --- a/crates/engine/src/sweep.rs +++ b/crates/engine/src/sweep.rs @@ -66,6 +66,9 @@ fn track() -> SubtitleTrack { fn clip(start: u32, in_frame: u32, out_frame: u32) -> Clip { Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame, out_frame, diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index 4964a25..495d32b 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -61,6 +61,9 @@ fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { /// re-encodes today and once refused outright. fn mixed_project() -> Project { let clip = |start, source| Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame: 0, out_frame: 30, @@ -83,6 +86,9 @@ fn mixed_project() -> Project { ( LaneKind::Video, vec![Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: 90, @@ -223,6 +229,7 @@ fn exports_the_timeline_as_a_wav() { format: Format::Wav, ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(60)).expect("wav export"); assert_eq!(handle.progress(), 1.0, "finished at full progress"); @@ -245,6 +252,7 @@ fn exports_the_timeline_as_a_flac() { format: Format::Flac, ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(60)).expect("flac export"); assert_eq!(handle.progress(), 1.0, "finished at full progress"); @@ -283,6 +291,7 @@ fn exports_the_timeline_as_an_mp3() { format: Format::Mp3, ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(120)).expect("mp3 export"); assert_eq!(handle.progress(), 1.0, "finished at full progress"); @@ -324,6 +333,9 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() { let song = asset("test_tone.mp3"); let still = asset("test_still.png"); let clip = |source, frames| Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: frames, @@ -357,7 +369,7 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() { color: Default::default(), }; let out = out_path("still_song", "mp4"); - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song"); // Picture: two seconds of it, through the demuxer an import uses. @@ -388,6 +400,9 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() { #[test] fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() { let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: 30, @@ -423,7 +438,8 @@ fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() { format: Format::Wav, ..Default::default() }, - ); + None, + ); wait(&handle, Duration::from_secs(60)).unwrap_or_else(|e| panic!("{name}: {e}")); let (audio, samples) = decode(&out); let peak = samples.iter().fold(0.0f32, |m, s| m.max(s.abs())); @@ -513,6 +529,7 @@ fn a_cancelled_audio_export_leaves_no_file() { format: Format::Wav, ..Default::default() }, + None, ); handle.cancel(); let outcome = wait(&handle, Duration::from_secs(120)); @@ -597,7 +614,8 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { audio_kbps: kbps, ..Default::default() }, - ); + None, + ); wait(&handle, Duration::from_secs(120)).expect("mp3 export"); let got = mp3_declared_kbps(&out); println!("mp3 asked {kbps:?}, header says {got} kbps"); @@ -621,6 +639,9 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { ( LaneKind::Video, vec![Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: 60, @@ -635,6 +656,9 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { ( LaneKind::Audio, vec![Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: 60, @@ -669,7 +693,8 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { audio_kbps: Some(want), ..Default::default() }, - ); + None, + ); wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song"); let got = mp4_aac_kbps(&out, f64::from(RATE)); println!("mp4 asked {want} kbps, the track measures {got:.1}"); @@ -689,6 +714,9 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { #[test] fn a_silent_clip_exports_as_silence_over_its_own_span() { let clip = |start, source| Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame: 0, out_frame: 30, @@ -723,6 +751,7 @@ fn a_silent_clip_exports_as_silence_over_its_own_span() { format: Format::Wav, ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(60)).expect("wav export"); let (audio, samples) = decode(&out); @@ -757,6 +786,7 @@ fn a_silent_timeline_refuses_an_audio_export() { format: Format::Wav, ..Default::default() }, + None, ); let text = wait(&handle, Duration::from_secs(60)) .expect_err("no audio to export") @@ -779,6 +809,9 @@ fn a_51_ac3_source_round_trips_through_a_wav() { vec![( LaneKind::Audio, vec![Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: 30, @@ -805,6 +838,7 @@ fn a_51_ac3_source_round_trips_through_a_wav() { format: Format::Wav, ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(60)).expect("wav export of an AC-3 source"); @@ -846,6 +880,7 @@ fn exports_the_timeline_as_an_ogg_vorbis() { format: Format::Ogg, ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(180)).expect("ogg export"); assert_eq!(handle.progress(), 1.0, "finished at full progress"); @@ -904,6 +939,9 @@ fn a_mono_timeline_exports_as_dual_mono_ogg() { vec![( LaneKind::Audio, vec![Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: 30, @@ -929,6 +967,7 @@ fn a_mono_timeline_exports_as_dual_mono_ogg() { format: Format::Ogg, ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(180)).expect("ogg export of a mono timeline"); diff --git a/crates/engine/tests/audio_files.rs b/crates/engine/tests/audio_files.rs index d06364e..88990af 100644 --- a/crates/engine/tests/audio_files.rs +++ b/crates/engine/tests/audio_files.rs @@ -491,6 +491,8 @@ fn a_song_survives_a_save_and_a_reload() { Lane::A1, 1.0, Clip { + fade_in: 0, + fade_out: 0, in_frame: 0, out_frame: 30, ..song diff --git a/crates/engine/tests/av1.rs b/crates/engine/tests/av1.rs index 5becdb7..a9a8f1d 100644 --- a/crates/engine/tests/av1.rs +++ b/crates/engine/tests/av1.rs @@ -333,7 +333,7 @@ fn an_mp4_export_of_a_matroska_source_carries_its_sound() { let project = Project::single(asset("test_av1.mkv"), 15); let out = Scratch::file("ve_export_av1", "mp4"); - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); let started = Instant::now(); while !handle.is_finished() { assert!(started.elapsed() < Duration::from_secs(900), "export hung"); diff --git a/crates/engine/tests/backends.rs b/crates/engine/tests/backends.rs index 6eaec09..cdeda18 100644 --- a/crates/engine/tests/backends.rs +++ b/crates/engine/tests/backends.rs @@ -119,7 +119,7 @@ fn the_planned_encoders_are_the_ones_the_job_opens() { "{} · {}", engine::export::planned_video(session.meta(), &settings) .expect("these formats carry picture"), - session.planned_audio(format) + session.planned_audio(format, false) ); let out = out_path("planned", ext); let handle = session.export_to_with(&out, &settings); @@ -268,7 +268,7 @@ fn audio_only_job_names_its_encoder(format: Format) { "an audio-only format has no video seat to name" ); let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - let planned = session.planned_audio(format); + let planned = session.planned_audio(format, false); let out = out_path("audio", format.ext()); let handle = session.export_to_with(&out, &settings); let started = Instant::now(); @@ -299,24 +299,24 @@ fn audio_only_job_names_its_encoder(format: Format) { fn a_mixed_timeline_says_it_re_encodes_and_then_does() { let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); assert_eq!( - session.planned_audio(Format::Mp4), + session.planned_audio(Format::Mp4, false), "AAC copy", "a timeline nobody has mixed is still a copy" ); // A fader off unity... assert!(session.set_lane_gain_db(engine::project::Lane::A1, -3.0)); - let planned = session.planned_audio(Format::Mp4); + let planned = session.planned_audio(Format::Mp4, false); assert!(planned.contains("encode"), "a faded lane: {planned}"); // ...and back at unity it is a copy again: the answer follows the edit, it // is not a latch. assert!(session.set_lane_gain_db(engine::project::Lane::A1, 0.0)); - assert_eq!(session.planned_audio(Format::Mp4), "AAC copy"); + assert_eq!(session.planned_audio(Format::Mp4, false), "AAC copy"); // ...and the limiter alone does it too. assert!(session.set_limiter(engine::limiter::Limiter { ceiling_db: -1.0, on: true, })); - assert_eq!(session.planned_audio(Format::Mp4), planned); + assert_eq!(session.planned_audio(Format::Mp4, false), planned); // ...and the job opens exactly that, which is the pin the whole file is // about: the encoders line published by the running export. diff --git a/crates/engine/tests/eq_audio.rs b/crates/engine/tests/eq_audio.rs index e3576eb..5c654bb 100644 --- a/crates/engine/tests/eq_audio.rs +++ b/crates/engine/tests/eq_audio.rs @@ -54,6 +54,9 @@ fn boost() -> EqParams { fn clip(start: u32, source: usize, frames: u32) -> Clip { Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame: 0, out_frame: frames, @@ -298,7 +301,8 @@ fn the_audio_only_exports_carry_the_same_boost_playback_does() { format, ..Default::default() }, - ); + None, + ); wait(&handle, Duration::from_secs(60)).expect("an audio-only export"); written.push(decode(&out)); std::fs::remove_file(&out).unwrap(); @@ -338,7 +342,7 @@ fn an_mp4_export_carries_the_boost_a_packet_copy_could_not() { for (name, project) in [("flat", &flat), ("eqd", &eqd)] { let out = out_path(name, "mp4"); let settings = ExportSettings::default(); - let handle = engine::export::start(project.clone(), meta(), &out, &settings); + let handle = engine::export::start(project.clone(), meta(), &out, &settings, None); wait(&handle, Duration::from_secs(180)).expect("an equalized timeline exports as mp4"); written.push(decode(&out)); std::fs::remove_file(&out).unwrap(); diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 20cf1fb..69cb986 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -234,6 +234,9 @@ fn exports_an_edited_timeline_in_hardware() { fn exports_at_the_project_resolution_with_the_watched_geometry() { let _seat = pin_software(); let clip = |source: usize, start: u32| engine::Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start, in_frame: 0, out_frame: 10, @@ -269,7 +272,7 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() { color: Default::default(), }; let out = out_path("mixed"); - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); wait(&handle, Duration::from_secs(600)).expect("export"); let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen export"); @@ -316,6 +319,9 @@ fn exports_the_audio_stream_the_timeline_plays() { let multi = asset("test_multiaudio.mp4"); let (meta, _) = engine::demux::Demuxer::open(&multi).expect("open the fixture"); let whole = engine::Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: meta.frame_count, @@ -343,7 +349,7 @@ fn exports_the_audio_stream_the_timeline_plays() { ) .expect("a one-source project on stream 1"); let out = out_path("stream1"); - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); wait(&handle, Duration::from_secs(600)).expect("export"); let (audio, _) = engine::AudioSession::open(&out) @@ -425,7 +431,7 @@ fn multi_source_round_trip(name: &str, limit: Duration) { let out = out_path(name); let started = Instant::now(); - let handle = engine::export::start(project.clone(), meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project.clone(), meta, &out, &ExportSettings::default(), None); wait(&handle, limit).expect("export"); println!( "{name}: {total} frames of two sources in {:.2} s", @@ -551,7 +557,7 @@ fn a_vanished_source_fails_the_export() { std::fs::remove_file(&doomed).expect("unlink the second source"); let out = out_path("vanished"); - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); let result = wait(&handle, Duration::from_secs(60)); let error = result.expect_err("an export of a missing file cannot succeed"); println!("vanished source: {error}"); @@ -1411,7 +1417,7 @@ fn a_hardware_encoder_killed_mid_export_costs_the_file_nothing() { injected(Some("3"), None, || { // `Auto` is what an untouched export card sends: the seat that *may* // fall back, which is the whole question here. - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); wait(&handle, Duration::from_secs(180)).expect("the export survived its encoder"); }); @@ -1439,7 +1445,7 @@ fn a_hardware_encoder_killed_mid_export_never_pulls_the_bar_backwards() { let out = out_path("hw_child_abort_progress"); let seen = injected(Some("3"), None, || { - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); // Sampled far faster than the export writes, so the retry cannot slip // through between two reads. let started = Instant::now(); @@ -1494,7 +1500,7 @@ fn audio_pass_threads() -> usize { /// The busiest that crowd ever gets while `export` writes this project. fn busiest_audio_pass(project: Project, meta: engine::VideoMeta, out: &Path) -> usize { - let handle = engine::export::start(project, meta, out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, out, &ExportSettings::default(), None); let started = Instant::now(); let mut most = 0; while !handle.is_finished() { @@ -1596,7 +1602,7 @@ fn a_hardware_encoder_killed_at_its_open_is_simply_no_seat() { let out = out_path("hw_child_abort_init"); injected(Some("init"), None, || { - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); wait(&handle, Duration::from_secs(180)).expect("the export survived the open"); }); @@ -1614,7 +1620,7 @@ fn a_hardware_encoder_killed_at_the_drain_costs_the_file_nothing() { let out = out_path("hw_child_abort_drain"); injected(Some("drain"), None, || { - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); wait(&handle, Duration::from_secs(180)).expect("the export survived the drain"); }); @@ -1637,7 +1643,7 @@ fn a_hardware_encoder_that_stops_answering_is_killed_and_replaced() { let started = Instant::now(); injected(None, Some("2"), || { - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); wait(&handle, Duration::from_secs(180)).expect("the export outlived the wedge"); }); println!( @@ -1671,7 +1677,7 @@ fn an_export_that_asked_for_the_gpu_by_name_refuses_instead_of_falling_back() { seat: engine::export::EncoderSeat::Hardware, ..Default::default() }; - let handle = engine::export::start(project, meta, &out, &settings); + let handle = engine::export::start(project, meta, &out, &settings, None); wait(&handle, Duration::from_secs(180)) .expect_err("a named hardware seat that died is not written again in software") }); diff --git a/crates/engine/tests/export_subs.rs b/crates/engine/tests/export_subs.rs index 36aad7e..1e09c5e 100644 --- a/crates/engine/tests/export_subs.rs +++ b/crates/engine/tests/export_subs.rs @@ -157,6 +157,7 @@ fn exported_want( subtitles: picks.to_vec(), ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(1800)).expect("the export finishes"); // The bar ends where it was told it would: the picture loop's own count and @@ -188,6 +189,7 @@ fn exported_mp4(name: &str, project: Project, picks: &[usize]) -> Scratch { subtitles: picks.to_vec(), ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(1800)).expect("the export finishes"); out @@ -570,6 +572,7 @@ fn an_hevc_mp4_keeps_its_rewritten_entry_and_its_text() { subtitles: vec![1], ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(1800)).expect("the export finishes"); let Some(listing) = ffmpeg_streams(&out) else { @@ -662,6 +665,7 @@ fn more_tracks_than_a_block_can_number_are_refused_by_name() { subtitles: (0..over).collect(), ..Default::default() }, + None, ); let said = wait(&handle, Duration::from_secs(1800)) .expect_err("a file that cannot be numbered is not written") @@ -1094,6 +1098,7 @@ fn more_lanes_than_a_block_can_number_are_refused_by_name() { format: Format::Hevc, ..Default::default() }, + None, ); let said = wait(&handle, Duration::from_secs(1800)) .expect_err("a file that cannot be numbered is not written") diff --git a/crates/engine/tests/hevc.rs b/crates/engine/tests/hevc.rs index 38d2f8e..6aa7859 100644 --- a/crates/engine/tests/hevc.rs +++ b/crates/engine/tests/hevc.rs @@ -242,7 +242,7 @@ fn an_hevc_source_exports_as_h264() { let project = Project::single(asset("test_hevc.mp4"), meta.frame_count); let out = Scratch::file("ve_export_hevc", "mp4"); - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); let started = Instant::now(); while !handle.is_finished() { assert!(started.elapsed() < Duration::from_secs(120), "export hung"); diff --git a/crates/engine/tests/hevc_hvc1.rs b/crates/engine/tests/hevc_hvc1.rs index d35e497..42f09de 100644 --- a/crates/engine/tests/hevc_hvc1.rs +++ b/crates/engine/tests/hevc_hvc1.rs @@ -127,7 +127,7 @@ fn an_hvc1_source_exports_as_h264() { let project = Project::single(asset(HVC1), meta.frame_count); let out = Scratch::file("ve_export_hvc1", "mp4"); - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); let started = Instant::now(); while !handle.is_finished() { assert!(started.elapsed() < Duration::from_secs(120), "export hung"); diff --git a/crates/engine/tests/import_mp4_subs.rs b/crates/engine/tests/import_mp4_subs.rs index d6b7b84..a8372c1 100644 --- a/crates/engine/tests/import_mp4_subs.rs +++ b/crates/engine/tests/import_mp4_subs.rs @@ -98,6 +98,7 @@ fn exported_mp4(name: &str) -> Scratch { subtitles: vec![0, 1], ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(300)).expect("the export finishes"); out diff --git a/crates/engine/tests/lanes.rs b/crates/engine/tests/lanes.rs index 1332c19..c412caf 100644 --- a/crates/engine/tests/lanes.rs +++ b/crates/engine/tests/lanes.rs @@ -235,6 +235,9 @@ fn the_mp4_copy_follows_the_lane_that_holds_the_sound() { pin_software(); let source = asset("test_av.mp4"); let clip = Clip { + fade_in: 0, + transition_out: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: TOTAL, @@ -264,7 +267,7 @@ fn the_mp4_copy_follows_the_lane_that_holds_the_sound() { let out = out_path("a2_only", "mp4"); let (meta, _) = engine::demux::Demuxer::open(&source).unwrap(); - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); wait(&handle, Duration::from_secs(300)).expect("export the A2-only timeline"); let written = decoded_audio(&out); @@ -296,6 +299,9 @@ fn two_audio_lanes_are_summed() { let one_lane = Project::single(asset("test_av.mp4"), TOTAL); let mut project = one_lane.clone(); let doubled = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: TOP_IN, in_frame: TOP_IN, out_frame: TOP_OUT, @@ -319,7 +325,7 @@ fn two_audio_lanes_are_summed() { format: Format::Wav, ..Default::default() }; - let handle = engine::export::start(project, meta, &out, &settings); + let handle = engine::export::start(project, meta, &out, &settings, None); wait(&handle, Duration::from_secs(120)).expect("wav export"); let mut reader = hound::WavReader::open(&out).expect("reopen the wav"); let spec = reader.spec(); @@ -373,7 +379,7 @@ fn two_audio_lanes_are_summed() { // this decodes both lanes and encodes the sum instead (`export::copy_audio` // routes to `encode_audio`), which is the same mix the WAV above measured. let out = out_path("mixed", "mp4"); - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); wait(&handle, Duration::from_secs(180)).expect("an mp4 of two audio lanes"); let (audio, chunks) = engine::AudioSession::open(&out) .expect("reopen the export") @@ -553,6 +559,8 @@ fn a_paste_never_touches_the_captions() { let clip = *project.lane(Lane::V1).first().expect("V1 holds the film"); let pasted = Clip { + fade_in: 0, + fade_out: 0, out_frame: 30, ..clip }; diff --git a/crates/engine/tests/opus_export.rs b/crates/engine/tests/opus_export.rs index 5be6726..dc450fa 100644 --- a/crates/engine/tests/opus_export.rs +++ b/crates/engine/tests/opus_export.rs @@ -80,6 +80,9 @@ fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { /// `sound_in` seconds into that file: an edit, so nothing here can be a copy. fn project(video: &Path, sound: &Path, sound_in: u32) -> Project { let clip = |source, in_frame, out_frame| Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame, out_frame, @@ -122,6 +125,7 @@ fn export(name: &str, project: Project, video: &Path) -> Scratch { format: Format::Hevc, ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(600)).expect("the export finishes"); out @@ -420,6 +424,9 @@ fn a_copied_picture_names_the_sound_it_was_written_with() { let (meta, _) = engine::demux::Demuxer::open(&video).expect("probe the picture"); let frames = meta.frame_count; let clip = |source, out_frame| Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame, @@ -451,6 +458,7 @@ fn a_copied_picture_names_the_sound_it_was_written_with() { format: Format::Hevc, ..Default::default() }, + None, ); let line = { wait(&handle, Duration::from_secs(600)).expect("the export finishes"); diff --git a/crates/engine/tests/silence.rs b/crates/engine/tests/silence.rs index 3c756ef..0b034d4 100644 --- a/crates/engine/tests/silence.rs +++ b/crates/engine/tests/silence.rs @@ -138,6 +138,9 @@ fn speed_mode_refuses_a_clip_that_laps_over_a_silence() { let lane = p.add_lane(LaneKind::Video); assert_eq!(lane.label(), "V2"); let broll = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: 20, @@ -173,6 +176,9 @@ fn speed_mode_refuses_a_clip_that_laps_over_a_silence() { /// A clip covering the whole fixture, for a second track to carry. fn whole(source: usize, frames: u32) -> Clip { Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, start: 0, in_frame: 0, out_frame: frames, @@ -381,6 +387,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() { true, engine::export::EncoderSeat::default(), p.limiter(), + None, 0, ) .expect("save"); diff --git a/crates/engine/tests/speed.rs b/crates/engine/tests/speed.rs index a5c4330..f21034c 100644 --- a/crates/engine/tests/speed.rs +++ b/crates/engine/tests/speed.rs @@ -280,6 +280,7 @@ fn a_wav_export_of_a_2x_timeline_matches_the_preview() { format: Format::Wav, ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(120)).expect("wav export"); let mut reader = hound::WavReader::open(&out).expect("read the export back"); @@ -316,7 +317,7 @@ fn an_mp4_export_resamples_a_speeded_sound_clip() { .expect("room enough"); let heard = beep_at(&play(&project)); let out = out_path("speeded", "mp4"); - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); wait(&handle, Duration::from_secs(180)).expect("an mp4 of a speeded sound clip"); let (audio, chunks) = AudioSession::open(&out) .expect("reopen the export") @@ -468,6 +469,7 @@ fn a_wav_export_of_a_2x_clip_keeps_the_beeps_pitch() { format: Format::Wav, ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(120)).expect("wav export"); let mut reader = hound::WavReader::open(&out).expect("read the export back"); @@ -516,6 +518,8 @@ fn an_mp4_export_honours_a_speeded_picture_across_a_rate_change() { Lane::V1, fast, Clip { + fade_in: 0, + fade_out: 0, speed: Speed::NORMAL, ..whole } @@ -526,7 +530,7 @@ fn an_mp4_export_honours_a_speeded_picture_across_a_rate_change() { assert_eq!(total, fast + 90, "45 fast frames then 90 slow ones"); let out = out_path("honoured", "mp4"); - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); wait(&handle, Duration::from_secs(300)).expect("an mp4 export of a speeded picture"); let (_, frames) = DecodeSession::open(&out).expect("reopen the export"); let frames: Vec<_> = frames.into_iter().collect(); @@ -573,6 +577,7 @@ fn an_av1_export_honours_a_speeded_take_whole() { format: Format::Av1, ..Default::default() }, + None, ); wait(&handle, Duration::from_secs(600)).expect("an AV1 export of a speeded take"); assert!(out.exists(), "AV1 never refuses a rate"); diff --git a/crates/engine/tests/vp9.rs b/crates/engine/tests/vp9.rs index d361c4a..e9ea1ed 100644 --- a/crates/engine/tests/vp9.rs +++ b/crates/engine/tests/vp9.rs @@ -195,7 +195,7 @@ fn a_vp9_source_exports_as_h264() { let project = Project::single(asset("test_vp9.mp4"), meta.frame_count); let out = Scratch::file("ve_export_vp9", "mp4"); - let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); let started = Instant::now(); while !handle.is_finished() { assert!(started.elapsed() < Duration::from_secs(120), "export hung");