diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 02bd4dc..87200b9 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -48,6 +48,8 @@ pub enum ActionId { Delete, Lift, Color, + Fit, + Resolution, Undo, AddVideoLane, AddAudioLane, @@ -61,7 +63,7 @@ pub enum ActionId { impl ActionId { /// Display order everywhere -- the editor lists them in it and /// [`Keymap::defaults`] binds them in it. - pub const ALL: [ActionId; 18] = [ + pub const ALL: [ActionId; 20] = [ ActionId::Play, ActionId::Export, ActionId::Save, @@ -72,6 +74,8 @@ impl ActionId { ActionId::Delete, ActionId::Lift, ActionId::Color, + ActionId::Fit, + ActionId::Resolution, ActionId::Undo, ActionId::AddVideoLane, ActionId::AddAudioLane, @@ -95,6 +99,8 @@ impl ActionId { ActionId::Delete => "Delete", ActionId::Lift => "Lift (leave a gap)", ActionId::Color => "Colour…", + ActionId::Fit => "Fit policy: fit → fill → stretch → centre", + ActionId::Resolution => "Project resolution: source → 2160p → 1080p → 720p → 480p", ActionId::Undo => "Undo", ActionId::AddVideoLane => "Add a video track", ActionId::AddAudioLane => "Add an audio track", @@ -120,6 +126,8 @@ impl ActionId { ActionId::Delete => "delete", ActionId::Lift => "lift", ActionId::Color => "color", + ActionId::Fit => "fit", + ActionId::Resolution => "resolution", ActionId::Undo => "undo", ActionId::AddVideoLane => "add-video-lane", ActionId::AddAudioLane => "add-audio-lane", @@ -145,7 +153,11 @@ impl ActionId { | ActionId::Paste | ActionId::Delete | ActionId::Lift - | ActionId::Color => Category::Clips, + | ActionId::Color + | ActionId::Fit => Category::Clips, + // The project's own picture size is not a clip's business, and not + // a file operation either: it is what the viewer is looking at. + ActionId::Resolution => Category::View, ActionId::Cut | ActionId::Regroup | ActionId::Undo @@ -379,6 +391,13 @@ impl Keymap { // k: free, next to nothing that edits, and one press like the // rest of the clip keys. b(ActionId::Color, "k", false), + // The fit policy is a clip key like the grade beside it: "p" for + // policy, free, and one press like the rest of them. The project + // resolution is not a clip key and takes a ctrl chord, next to + // nothing that edits and out of the way of a stray press -- + // it changes what every clip is composed onto. + b(ActionId::Fit, "p", false), + b(ActionId::Resolution, "r", true), b(ActionId::Undo, "z", false), b(ActionId::Undo, "z", true), // The unshifted initials of what they add. Both were free -- @@ -621,7 +640,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 20); + assert_eq!(k.entries().len(), 22); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); assert_eq!(k.lookup("e", false), Some(ActionId::Export)); assert_eq!(k.lookup("s", true), Some(ActionId::Save)); @@ -633,6 +652,8 @@ mod tests { assert_eq!(k.lookup("delete", false), Some(ActionId::Delete)); assert_eq!(k.lookup("l", false), Some(ActionId::Lift)); assert_eq!(k.lookup("k", false), Some(ActionId::Color)); + assert_eq!(k.lookup("p", false), Some(ActionId::Fit)); + 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)); // The track keys are the bare letters; the ctrl ones stay copy/paste. @@ -773,7 +794,7 @@ mod tests { ); // The label is the editor's column, and never the file's word for it. assert_eq!(ActionId::CancelExport.label(), "Cancel export"); - assert_eq!(ActionId::ALL.len(), 18); + assert_eq!(ActionId::ALL.len(), 20); } #[test] diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 6dabdc3..1ba1fd7 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -14,6 +14,7 @@ use engine::color::ColorParams; use engine::eq::{Band, BandKind, EqParams}; use engine::export::{ExportSettings, Format}; use engine::project::{Lane, LaneKind, Source}; +use engine::scale::FitPolicy; use engine::{Clip, ExportHandle, Frame, PlaybackSession}; use gpui::{ AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent, @@ -221,16 +222,22 @@ struct ContextMenu { /// action a stroke already reaches -- the menu is a second way *to* the actions /// and never a second version of them -- so both the label and the hint come /// out of the keymap registry and the two can never disagree. -const MENU_ITEMS: [ActionId; 7] = [ +const MENU_ITEMS: [ActionId; 8] = [ ActionId::Cut, ActionId::Delete, ActionId::Lift, ActionId::Regroup, ActionId::Equalizer, ActionId::Color, + ActionId::Fit, ActionId::ToggleMute, ]; +/// The project resolutions [`Player::cycle_resolution`] offers, largest first. +/// A short list of the sizes people name; the media's own is cycled in beside +/// them, which is what makes the trip round come back to where it started. +const RESOLUTIONS: [(u32, u32); 4] = [(3840, 2160), (1920, 1080), (1280, 720), (854, 480)]; + /// How far a band may be pushed either way, in dB. The engine clamps nothing /// here -- it will filter whatever it is given -- so this is a UI decision: /// past about this a peaking band stops sounding like tone and starts sounding @@ -497,6 +504,8 @@ impl Player { ActionId::Delete => self.delete_selected(cx), ActionId::Lift => self.lift_selected(cx), ActionId::Color => self.open_color(cx), + ActionId::Fit => self.cycle_fit(cx), + ActionId::Resolution => self.cycle_resolution(cx), ActionId::Undo => self.undo(cx), ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx), ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx), @@ -510,6 +519,64 @@ impl Player { } } + /// Cycles the fit policy of the clip the picture is coming from -- the + /// clicked one when it is a video clip, else the composite's own, exactly as + /// the colour card picks its target. A whole card for one four-valued + /// setting would be a card to close; a stroke that cycles it and says what + /// it landed on is the same setting with nothing to dismiss. + /// + /// Only means anything when the clip is not the project's size -- a clip + /// that already fills the canvas looks the same under all four -- so the + /// notice says the size it is placing, not just the word. + fn cycle_fit(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let Some(session) = &mut self.session else { + self.notice = Some("no timeline to fit — open a file first".into()); + cx.notify(); + return; + }; + let target = self + .selected + .filter(|(lane, _)| lane.kind == LaneKind::Video) + .or_else(|| session.video_clip_at(session.now())); + let Some((lane, idx)) = target else { + self.notice = Some("no clip under the playhead to fit".into()); + cx.notify(); + return; + }; + let next = next_fit(session.fit_of(lane, idx)); + if session.set_fit(lane, idx, next) { + let (w, h) = session.resolution(); + self.notice = Some(format!("FIT POLICY: {} on {w}x{h}", fit_label(next)).into()); + self.reset_after_reseek(); + } + cx.notify(); + } + + /// Cycles the *project's* resolution through [`RESOLUTIONS`], starting from + /// the media's own -- the one size that must stay reachable, since a project + /// moved off it has no other way back (the resolution is not an undo step). + /// Every clip is recomposed onto it, so this is what makes "the project + /// resolution and the media's are different things" a thing a user can see. + fn cycle_resolution(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let Some(session) = &mut self.session else { + self.notice = Some("no timeline to resize — open a file first".into()); + cx.notify(); + return; + }; + let (width, height) = next_resolution(session.resolution(), session.native_resolution()); + if session.set_resolution(width, height) { + self.notice = Some(format!("PROJECT: {width}x{height}").into()); + self.reset_after_reseek(); + } + cx.notify(); + } + /// Opens the colour card on the clip a grade would go on: the clip that was /// clicked when it is a video one, and otherwise the clip the picture is /// coming from -- the one the engine's own compositing rule picks, which is @@ -2543,14 +2610,18 @@ impl Player { ) // What the picked row really writes. `moov` last is the // muxer's own shape -- an mp4 is playable only once it - // is finished. + // is finished. The project's resolution is on the same + // line because it *is* what the file comes out at, + // whatever size the media on the timeline are: this is + // the one place the number is shown, and ctrl+r is what + // changes it. .child( div() .flex_none() .px(px(6.)) .text_size(px(11.)) .text_color(rgb(INK_DIM)) - .child(format_line(self.format)), + .child(export_line(self.format, self.session.as_ref())), ) .child( div() @@ -3497,7 +3568,8 @@ fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool ActionId::Equalizer => lane.kind == LaneKind::Audio, // A grade is a picture setting and an audio clip has no picture: the // item is there on every clip, and dimmed where it would mean nothing. - ActionId::Color => lane.kind == LaneKind::Video, + // A fit policy is a picture setting for the same reason. + ActionId::Color | ActionId::Fit => lane.kind == LaneKind::Video, // Splits this clip only from inside it: at either edge there is nothing // to split off (project.rs `splittable`). ActionId::Cut => clip.start < playhead && playhead < clip.end(), @@ -3826,6 +3898,63 @@ fn band_mut(params: &mut ColorParams, band: usize) -> &mut f32 { /// The line under the rows: what the picked format really writes, in the terms /// a file is judged by afterwards. +/// The next policy round the cycle, in the order the action's label reads. +fn next_fit(fit: FitPolicy) -> FitPolicy { + match fit { + FitPolicy::Fit => FitPolicy::Fill, + FitPolicy::Fill => FitPolicy::Stretch, + FitPolicy::Stretch => FitPolicy::Center, + FitPolicy::Center => FitPolicy::Fit, + } +} + +/// What a person calls one, said as what it does to the picture. +fn fit_label(fit: FitPolicy) -> &'static str { + match fit { + FitPolicy::Fit => "fit (whole picture, bars)", + FitPolicy::Fill => "fill (cropped, no bars)", + FitPolicy::Stretch => "stretch (aspect broken)", + FitPolicy::Center => "centre (1:1, no resample)", + } +} + +/// The next project resolution after `current`, over [`RESOLUTIONS`] with the +/// media's own size cycled in at its place by size -- so the trip round always +/// comes back to the media, whatever odd shape it is, and a project already at a +/// listed size does not see it twice. +fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) { + let mut sizes: Vec<(u32, u32)> = RESOLUTIONS.to_vec(); + if !sizes.contains(&native) { + // By area, descending, like the list itself: the cycle then reads as one + // ladder rather than a list with a stray rung at the end. + let at = sizes + .iter() + .position(|&(w, h)| { + u64::from(w) * u64::from(h) < u64::from(native.0) * u64::from(native.1) + }) + .unwrap_or(sizes.len()); + sizes.insert(at, native); + } + let at = sizes.iter().position(|&s| s == current); + // A project at a size nobody listed (a hand-edited file) joins the cycle at + // the top rather than being stuck. + sizes[at.map_or(0, |at| (at + 1) % sizes.len())] +} + +/// [`format_line`] plus the project's resolution, which is what a video export +/// is written at however many sizes the media on the timeline are. Only for the +/// formats that carry a picture -- a WAV has no resolution to state. +fn export_line(format: Format, session: Option<&PlaybackSession>) -> String { + let line = format_line(format); + match session.filter(|_| format.has_video()) { + Some(session) => { + let (w, h) = session.resolution(); + format!("{line} · project {w}x{h}") + } + None => line.to_string(), + } +} + fn format_line(format: Format) -> &'static str { match format { Format::Mp4 => "H.264 · MP4 · moov at end", @@ -4266,6 +4395,7 @@ mod tests { }; use super::{file_name, library_rows}; use engine::PlaybackSession; + use engine::scale::FitPolicy; use gpui::{Bounds, Pixels, point, px, size}; use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -4288,6 +4418,7 @@ mod tests { link: None, eq: None, color: None, + fit: FitPolicy::default(), } } @@ -4479,6 +4610,7 @@ mod tests { link: None, eq: None, color: None, + fit: FitPolicy::default(), }; assert_eq!(clip.end(), 90); // Cut splits from inside only: neither edge has anything to split off. @@ -4543,11 +4675,13 @@ mod tests { // Silent like the engine suite: this opens the real device. session.set_gain(0.0); assert_eq!(session.sources().len(), 1); + // 640x360 would join now (the project canvas places it); this file is + // also silent, and a silent file cannot join a timeline with sound. let refusal = session .import(&asset("test_mismatch.mp4")) - .expect_err("640x360 must not join a 1280x720 timeline") + .expect_err("a silent file must not join a timeline with audio") .to_string(); - assert!(refusal.contains("640"), "refusal must name it: {refusal}"); + assert!(refusal.contains("audio"), "refusal must name it: {refusal}"); assert_eq!(session.sources().len(), 1, "a refusal added a row"); // An accepted one does add a row, and it reads as the whole file: 4 s // at 30 fps, exactly what was appended. diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 1188b8c..7643e51 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -10,9 +10,10 @@ use std::thread; use rusty_h264::Decoder; use crate::color::ColorParams; -use crate::convert::i420_to_bgra_with; +use crate::convert::{i420_to_bgra, i420_to_bgra_with}; use crate::demux::{Codec, Demuxer, VideoMeta}; use crate::hw::HwSession; +use crate::scale::Composer; /// One decoded picture, ready to hand to a renderer. pub struct Frame { @@ -122,8 +123,15 @@ impl DecodeSession { ) -> crate::Result<(VideoMeta, Receiver, Arc)> { // Ungraded: the public API opens a *file*, and a colour grade belongs to // a clip of a timeline. `PlaybackSession` is what has one to pass. - let (meta, stream) = - Self::open_worker(path, start_frame, end_frame, ColorParams::default())?; + let (meta, stream) = Self::open_worker( + path, + start_frame, + end_frame, + ColorParams::default(), + // No project, no canvas: the file-level API hands back the + // pictures the file holds, at the size it holds them. + Composer::passthrough(), + )?; // The public API hands out the flag alone, so the worker is detached and // the receiver goes to the caller: nothing here joins anything. Ok((meta, stream.frames, stream.worker.detach())) @@ -185,11 +193,17 @@ impl DecodeSession { /// /// In-process only: a caller that outlives its workers has to be able to /// join them at exit. + /// + /// `canvas` is the project's own resolution and this clip's fit policy: the + /// frames come out at *that* size, whatever the file's is. A + /// [`Composer::passthrough`] (or one already the source's size) leaves every + /// picture exactly as it was decoded. pub(crate) fn open_worker( path: impl AsRef, start_frame: u32, end_frame: u32, color: ColorParams, + canvas: Composer, ) -> crate::Result<(VideoMeta, FrameStream)> { let path = path.as_ref().to_path_buf(); let (meta, demuxer) = Demuxer::open(&path)?; @@ -231,6 +245,7 @@ impl DecodeSession { if worker_cancel.load(Ordering::Relaxed) { return; } + let mut render = Render::new(color, canvas); // The plugin has to be opened on the thread that uses it: its // VA-API state is not `Send`-safe across a later hand-off. if let Some(hw) = open_hw(&path, start_frame) { @@ -240,7 +255,7 @@ impl DecodeSession { return; } eprintln!("decode backend: hardware (VA-API plugin)"); - if run_hw(hw, &tx, start_frame, end_frame, &color, &worker_cancel) { + if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) { return; } // A driver that opens but cannot decode a single frame is @@ -254,7 +269,14 @@ impl DecodeSession { return; } eprintln!("decode backend: software (rusty_h264)"); - run(demuxer, tx, start_frame, end_frame, &color, &worker_cancel) + run( + demuxer, + tx, + start_frame, + end_frame, + &mut render, + &worker_cancel, + ) })?; Ok(( meta, @@ -269,6 +291,77 @@ impl DecodeSession { } } +/// One clip's pictures on their way to the renderer: graded, placed on the +/// project canvas, converted. Both decode loops go through it, so hardware and +/// software cannot show two different pictures. +/// +/// The order is grade, then place (see [`Composer`]): a grade is the clip's own, +/// applied at the resolution it was shot at, and the letterbox bars around it +/// are not the clip -- a brightness grade must not lift them off black. +/// +/// A project at the media's own resolution never reaches any of that: it takes +/// the fused graded conversion, the one path this engine had before there was a +/// project resolution, byte for byte and allocation for allocation. +struct Render { + color: ColorParams, + canvas: Composer, + /// The graded copy of the source planes, refilled per frame and kept across + /// the worker's whole range. Empty unless the clip is both graded *and* + /// placed, which is the only case that needs it. + graded: (Vec, Vec, Vec), +} + +impl Render { + fn new(color: ColorParams, canvas: Composer) -> Self { + Self { + color, + canvas, + graded: (Vec::new(), Vec::new(), Vec::new()), + } + } + + fn frame( + &mut self, + index: u32, + y: &[u8], + u: &[u8], + v: &[u8], + width: u32, + height: u32, + ) -> Frame { + if self.canvas.is_passthrough(width, height) { + return Frame { + index, + width, + height, + bgra: i420_to_bgra_with(&self.color, y, u, v, width as usize, height as usize), + }; + } + let (gy, gu, gv) = &mut self.graded; + let (y, u, v) = if self.color.is_identity() { + (y, u, v) + } else { + gy.clear(); + gy.extend_from_slice(y); + gu.clear(); + gu.extend_from_slice(u); + gv.clear(); + gv.extend_from_slice(v); + crate::color::apply_yuv(&self.color, gy, gu, gv); + (&gy[..], &gu[..], &gv[..]) + }; + let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height); + Frame { + index, + width, + height, + // Ungraded on purpose: the grade is already in the pixels above and + // the canvas around them must stay the black it was filled with. + bgra: i420_to_bgra(y, u, v, width as usize, height as usize), + } + } +} + /// `None` when the software path must be used: forced by `VE_SW=1`, or the /// plugin is absent/broken/unable to open this particular file. fn open_hw(path: &PathBuf, start_frame: u32) -> Option { @@ -289,7 +382,7 @@ fn run_hw( tx: &SyncSender, start_frame: u32, end_frame: u32, - color: &ColorParams, + render: &mut Render, cancel: &AtomicBool, ) -> bool { let mut index = start_frame; @@ -299,12 +392,7 @@ fn run_hw( } match hw.next_frame() { Ok(Some((y, u, v, width, height))) => { - let frame = Frame { - index, - width, - height, - bgra: i420_to_bgra_with(color, y, u, v, width as usize, height as usize), - }; + let frame = render.frame(index, y, u, v, width, height); index += 1; if tx.send(frame).is_err() { return true; // consumer went away @@ -353,6 +441,7 @@ mod tests { 0, u32::MAX, ColorParams::default(), + Composer::passthrough(), ) .expect("open"); // Nothing is ever received: two frames fill the channel and the next @@ -377,7 +466,7 @@ fn run( tx: SyncSender, start_frame: u32, end_frame: u32, - color: &ColorParams, + render: &mut Render, cancel: &AtomicBool, ) { let mut decoder = Decoder::new(); @@ -413,12 +502,14 @@ fn run( index += 1; continue; } - let frame = Frame { - index: index as u32, - width: yuv.width as u32, - height: yuv.height as u32, - bgra: i420_to_bgra_with(color, &yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height), - }; + let frame = render.frame( + index as u32, + &yuv.y, + &yuv.u, + &yuv.v, + yuv.width as u32, + yuv.height as u32, + ); index += 1; if tx.send(frame).is_err() { break; // consumer went away diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 7c8876e..48198d5 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -1,18 +1,25 @@ //! The project file: a line of text per thing, and nothing else. //! //! ```text -//! edith 6 +//! edith 7 //! playhead 90 +//! resolution 1920 1080 //! source 0 test_av.mp4 //! source 1 /elsewhere/test_av2.mp4 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk //! color 0.1:1.2:0.9:-0.3 -//! video 1 0 0 120 0 0 0 0 -//! audio 1 0 0 120 0 0 0 - -//! video 2 120 0 120 1 - - - +//! video 1 0 0 120 0 0 0 0 fit +//! audio 1 0 0 120 0 0 0 - fit +//! video 2 120 0 120 1 - - - fill //! audio 2 //! ``` //! +//! The `resolution` line is the **project's** picture size, which is a +//! different thing from any source's: media of other sizes are placed on it. +//! It belongs once, beside the playhead, and a file without one (every dialect +//! before v7) means "source 0's own picture", which is what such a project +//! always was. +//! //! A source line is `source