From bd89527f631c61a78423286cb249abde6f42a0c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 10 Aug 2026 11:50:48 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(video):=20per-clip=20color=20g?= =?UTF-8?q?rade=20is=20live=20in=20render=20and=20export?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The grade a clip carries now reaches the picture. `Project::composite_clip_at` names the clip the composite shows at a frame and `composite_color_at` its grade, so playback's decode worker (folded into `i420_to_bgra_with`, free in the loop that was reading those samples anyway) and the export's encoder (onto per-span scratch, since the planes are borrowed) grade from one answer. `PlaybackSession::set_color` is an edit like any other, so it reseeks -- which is what repaints the frame already on screen, paused or playing. The card: `k` (or the clip menu's Colour…) opens four sliders on the selected video clip, or on the clip under the playhead when nothing is selected, so it is reachable with no pointer at all. Arrows pick and move a slider, r resets, esc closes; a slider walked back to the middle takes the grade off, which keeps an ungraded project byte-identical -- verified: the same two-clip export before and after this slice is md5 98522c19cefac2f7851b51de6416a493 both times. --- crates/app/src/keymap.rs | 40 +++- crates/app/src/main.rs | 335 ++++++++++++++++++++++++++++++++-- crates/engine/src/decode.rs | 39 +++- crates/engine/src/export.rs | 25 +++ crates/engine/src/playback.rs | 46 ++++- crates/engine/src/project.rs | 36 +++- crates/engine/tests/color.rs | 183 +++++++++++++++++++ 7 files changed, 667 insertions(+), 37 deletions(-) create mode 100644 crates/engine/tests/color.rs diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 6e02828..68a0888 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -47,6 +47,7 @@ pub enum ActionId { Regroup, Delete, Lift, + Color, Undo, AddVideoLane, AddAudioLane, @@ -59,7 +60,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; 16] = [ + pub const ALL: [ActionId; 17] = [ ActionId::Play, ActionId::Export, ActionId::Save, @@ -69,6 +70,7 @@ impl ActionId { ActionId::Regroup, ActionId::Delete, ActionId::Lift, + ActionId::Color, ActionId::Undo, ActionId::AddVideoLane, ActionId::AddAudioLane, @@ -90,6 +92,7 @@ impl ActionId { ActionId::Regroup => "Regroup", ActionId::Delete => "Delete", ActionId::Lift => "Lift (leave a gap)", + ActionId::Color => "Colour…", ActionId::Undo => "Undo", ActionId::AddVideoLane => "Add a video track", ActionId::AddAudioLane => "Add an audio track", @@ -113,6 +116,7 @@ impl ActionId { ActionId::Regroup => "regroup", ActionId::Delete => "delete", ActionId::Lift => "lift", + ActionId::Color => "color", ActionId::Undo => "undo", ActionId::AddVideoLane => "add-video-lane", ActionId::AddAudioLane => "add-audio-lane", @@ -133,7 +137,11 @@ impl ActionId { pub fn category(self) -> Category { match self { ActionId::Play => Category::Playback, - ActionId::Copy | ActionId::Paste | ActionId::Delete | ActionId::Lift => Category::Clips, + ActionId::Copy + | ActionId::Paste + | ActionId::Delete + | ActionId::Lift + | ActionId::Color => Category::Clips, ActionId::Cut | ActionId::Regroup | ActionId::Undo @@ -191,7 +199,7 @@ pub struct Fixed { pub category: Category, } -pub const FIXED: [Fixed; 5] = [ +pub const FIXED: [Fixed; 8] = [ Fixed { chord: "esc", label: "Close this card or clip menu, or cancel a capture", @@ -217,6 +225,23 @@ pub const FIXED: [Fixed; 5] = [ label: "Erase a bitrate digit", category: Category::File, }, + // The colour card's own three, which mean nothing outside it -- the same + // card-local input the export card's digits are. + Fixed { + chord: "↑ / ↓", + label: "Pick a colour slider", + category: Category::Clips, + }, + Fixed { + chord: "← / →", + label: "Move the picked colour slider", + category: Category::Clips, + }, + Fixed { + chord: "r", + label: "Take the colour grade off the clip", + category: Category::Clips, + }, ]; /// A stroke as the key handler sees it: gpui's key name plus the one modifier @@ -320,6 +345,10 @@ impl Keymap { b(ActionId::Delete, "x", false), b(ActionId::Delete, "delete", false), b(ActionId::Lift, "l", false), + // The c of colour is Cut and ctrl+c is Copy, so the grade takes + // k: free, next to nothing that edits, and one press like the + // rest of the clip keys. + b(ActionId::Color, "k", false), b(ActionId::Undo, "z", false), b(ActionId::Undo, "z", true), // The unshifted initials of what they add. Both were free -- @@ -559,7 +588,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 18); + assert_eq!(k.entries().len(), 19); 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)); @@ -570,6 +599,7 @@ mod tests { assert_eq!(k.lookup("x", false), Some(ActionId::Delete)); 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("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. @@ -709,7 +739,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(), 16); + assert_eq!(ActionId::ALL.len(), 17); } #[test] diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index a876490..26abbb1 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -10,6 +10,7 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use engine::audio::StreamInfo; +use engine::color::ColorParams; use engine::export::{ExportSettings, Format}; use engine::project::{Lane, LaneKind, Source}; use engine::{Clip, ExportHandle, Frame, PlaybackSession}; @@ -219,14 +220,36 @@ 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; 5] = [ +const MENU_ITEMS: [ActionId; 6] = [ ActionId::Cut, ActionId::Delete, ActionId::Lift, ActionId::Regroup, + ActionId::Color, ActionId::ToggleMute, ]; +/// The colour card's four controls, in the order it lists them: what each is +/// called and the range it moves in. The order is `ColorParams`' own, which is +/// what [`color_band`] indexes. +const COLOR_BANDS: [(&str, f32, f32); 4] = [ + ("Brightness", -1., 1.), + ("Contrast", 0., 2.), + ("Saturation", 0., 2.), + ("Tint (cool–warm)", -1., 1.), +]; + +/// A press of a nudge key or button: a fortieth of a band's range, so a slider +/// crosses it in forty presses and every stop is a number the file can write. +const COLOR_STEP: f32 = 0.05; + +/// The card's width: a slider row is a label, two buttons, the bar and the +/// value, and the longest label has to fit beside all four without truncating +/// (measured against "Tint (cool–warm)" at 460). +const COLOR_W: f32 = 460.; +/// How much of a slider row the bar itself gets. +const COLOR_BAR_W: f32 = 140.; + struct Player { /// The timeline, once there is one. A run with no file opens without it and /// waits: the first media import or project load is what fills it, and @@ -321,6 +344,13 @@ struct Player { /// Which file the card will write. Kept across closes like the quality, and /// what [`Player::export_path`](Player) is named after. format: Format, + /// The colour card is up on this clip -- the lane it is on and its index + /// there. `None` when it is closed, which is the only place that state + /// lives: the grade itself is the project's. + color_open: Option<(Lane, usize)>, + /// Which of the card's four sliders the arrow keys and the buttons move. + /// The card's own focus, since nothing in it takes gpui's (ledger:182). + color_band: usize, /// The action whose row is waiting for a stroke. The next key that is /// neither escape nor a lone modifier becomes the whole of what reaches it. rebinding: Option, @@ -431,6 +461,7 @@ impl Player { ActionId::Regroup => self.regroup(cx), ActionId::Delete => self.delete_selected(cx), ActionId::Lift => self.lift_selected(cx), + ActionId::Color => self.open_color(cx), ActionId::Undo => self.undo(cx), ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx), ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx), @@ -443,11 +474,86 @@ impl Player { } } + /// 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 + /// what a person means by "this shot". That fallback is also what makes the + /// card reachable with no pointer at all: clip selection is a click and + /// nothing else (ledger:182). + fn open_color(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let Some(session) = &self.session else { + self.notice = Some("no timeline to grade — 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())); + match target { + Some(clip) => { + self.color_open = Some(clip); + self.color_band = 0; + // One card at a time, the rule both the others already follow. + self.keys_open = false; + self.export_open = false; + self.context_menu = None; + } + None => self.notice = Some("no clip under the playhead to grade".into()), + } + cx.notify(); + } + + /// What the card's clip is graded by right now -- the identity for one + /// nobody has graded, which is what the sliders start at. + fn color_params(&self) -> ColorParams { + self.color_open + .zip(self.session.as_ref()) + .and_then(|((lane, idx), session)| session.color_of(lane, idx).copied()) + .unwrap_or_default() + } + + /// Puts `params` on the card's clip, or takes the grade off when they are + /// the identity -- a slider walked back to the middle leaves the clip + /// ungraded rather than carrying a do-nothing entry, which is what keeps an + /// untouched project byte-identical. The engine reseeks on the edit, so the + /// frame on screen repaints through the new grade; this only owes the flags + /// that reseek clears. + fn set_color(&mut self, params: ColorParams, cx: &mut Context) { + let Some((lane, idx)) = self.color_open else { + return; + }; + let Some(session) = &mut self.session else { + return; + }; + let grade = Some(params).filter(|p| !p.is_identity()); + if session.set_color(lane, idx, grade) { + self.reset_after_reseek(); + } + cx.notify(); + } + + /// Moves the picked slider by `steps` of [`COLOR_STEP`], clamped to that + /// band's range. One edit, so one undo step per press. + fn nudge_color(&mut self, steps: f32, cx: &mut Context) { + let mut params = self.color_params(); + let (_, low, high) = COLOR_BANDS[self.color_band]; + let value = band_mut(&mut params, self.color_band); + *value = (*value + steps * COLOR_STEP).clamp(low, high); + self.set_color(params, cx); + } + /// Whether a card owns the window. While one does the timeline under it is /// out of reach, so a right-click there opens no menu -- the same rule the /// key handler and the drop target already follow. fn modal(&self) -> bool { - self.keys_open || self.export_open || self.exporting().is_some() + self.keys_open + || self.export_open + || self.color_open.is_some() + || self.exporting().is_some() } /// Jumps the timeline. @@ -1259,6 +1365,26 @@ impl Render for Player { cx.notify(); return; } + // The colour card owns the keyboard the same way the export + // card does, and its keys mean nothing outside it: the arrows + // pick a slider and move it, and `r` takes the grade off. Not + // keymap bindings for exactly that reason -- see `FIXED`, where + // the keys menu still lists them. + if this.color_open.is_some() { + match color_key(key) { + Some(ColorKey::Close) => this.color_open = None, + Some(ColorKey::Band(step)) => { + this.color_band = (this.color_band + step) % COLOR_BANDS.len(); + } + Some(ColorKey::Nudge(steps)) => this.nudge_color(steps, cx), + Some(ColorKey::Reset) => { + this.set_color(ColorParams::default(), cx); + } + None => {} + } + cx.notify(); + return; + } // A clip menu names an index, and every edit below moves // indices -- so a stroke closes it before it acts. Escape means // that and nothing else, which is the `esc` the keys menu @@ -1387,6 +1513,7 @@ impl Render for Player { // column, and only one of the two is ever up. .children(self.keys_overlay(cx)) .children(self.export_card(cx)) + .children(self.color_card(cx)) } } @@ -2261,6 +2388,141 @@ impl Player { ) } + /// The colour card: a row per control, each showing where in its range it + /// stands and carrying the pair of buttons that move it -- the same move the + /// arrow keys make, because a control only the pointer can reach is not one + /// everyone can reach. Same scrim, surface and row shape as the other two + /// cards, and the same plain divs, so the root keeps the keyboard. + /// + /// The values are read from the project every render: what is drawn is what + /// the decoder is grading with, never a copy that could drift from it. + fn color_card(&self, cx: &mut Context) -> Option { + let (lane, idx) = self.color_open?; + let params = self.color_params(); + let rows: Vec<_> = COLOR_BANDS + .iter() + .enumerate() + .map(|(i, &(label, low, high))| { + let mut read = params; + let value = *band_mut(&mut read, i); + let frac = ((value - low) / (high - low)).clamp(0., 1.); + let picked = i == self.color_band; + // Both buttons of a row do what the arrows do, so there is one + // rule for what a press is worth and one place it is clamped. + let step = |name: &'static str, steps: f32| { + div() + .id((name, i)) + .w(px(CONTROL_H)) + .h(px(CONTROL_H)) + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(CHROME)) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.color_band = i; + this.nudge_color(steps, cx); + })) + .child(if steps < 0. { "–" } else { "+" }) + }; + div() + .id(("color-row", i)) + .flex() + .min_h(px(KEYS_ROW_H)) + .items_center() + .gap(px(8.)) + .px(px(6.)) + .rounded(px(3.)) + .cursor_pointer() + .when(picked, |d| d.bg(rgb(SELECTED))) + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.color_band = i; + cx.notify(); + })) + .child(div().flex_1().min_w(px(0.)).truncate().child(label)) + .child(step("color-down", -1.)) + .child( + div() + .w(px(COLOR_BAR_W)) + .h(px(4.)) + .rounded(px(2.)) + .bg(rgb(CHROME)) + .child( + div() + .h_full() + .w(relative(frac)) + .rounded(px(2.)) + .bg(rgb(ACCENT)), + ), + ) + .child(step("color-up", 1.)) + .child( + div() + .w(px(44.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child(format!("{value:.2}")), + ) + }) + .collect(); + Some( + div() + .absolute() + .inset_0() + .flex() + .justify_center() + .items_center() + .bg(rgba(0x101010cc)) + .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .child( + div() + .w(px(COLOR_W)) + .flex() + .flex_col() + .gap(px(2.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(SURFACE)) + .child(div().flex_none().px(px(6.)).child(format!( + "Colour — {} clip {}", + lane.label(), + idx + 1 + ))) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child("↑↓ picks a slider, ←→ moves it, r resets — esc closes"), + ) + .children(rows) + .child( + div() + .id("color-reset") + .mt(px(4.)) + .flex() + .h(px(CONTROL_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(SELECTED)) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.set_color(ColorParams::default(), cx); + })) + .child("Reset"), + ), + ), + ) + } + /// The menu a right-click on a clip opens: what that clip can be given, /// each item beside the stroke that does the very same thing, and a /// turn-over side that says what the clip *is*. An item that would do @@ -2336,7 +2598,7 @@ impl Player { } } else { for action in MENU_ITEMS { - let enabled = applicable(&clip, action, playhead); + let enabled = applicable(&clip, menu.lane, action, playhead); // The one item that is not about this clip says so, and says it // here rather than in the registry: the stroke is global too, // but its row in the keys menu is not sitting on a clip. @@ -2859,8 +3121,11 @@ fn frame_at(secs: f64, fps: f64) -> u32 { /// Whether the clip menu offers `action` on the clip it was opened on. Two of /// the items act on the *playhead* rather than on the clip, so a menu opened /// away from it dims them instead of looking broken when they are clicked. -fn applicable(clip: &Clip, action: ActionId, playhead: u32) -> bool { +fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool { match action { + // 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, // 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(), @@ -3151,6 +3416,42 @@ fn format_key(key: &str) -> Option { .map(|(format, _)| format) } +/// What one of the colour card's own strokes does. Its keys are card-local -- +/// they mean nothing outside it -- so they are a table here rather than keymap +/// bindings, exactly as the export card's format initials are. Listed in +/// `keymap::FIXED` all the same, which is how the keys menu still says so. +enum ColorKey { + Close, + /// Steps down the four sliders, wrapping. + Band(usize), + /// Moves the picked slider, in [`COLOR_STEP`]s. + Nudge(f32), + Reset, +} + +fn color_key(key: &str) -> Option { + Some(match key { + ESCAPE => ColorKey::Close, + "down" => ColorKey::Band(1), + "up" => ColorKey::Band(COLOR_BANDS.len() - 1), + "right" => ColorKey::Nudge(1.), + "left" => ColorKey::Nudge(-1.), + "r" => ColorKey::Reset, + _ => return None, + }) +} + +/// The band'th control of a grade, to read or to write. The order is +/// [`COLOR_BANDS`]', which is the order the card lists them in. +fn band_mut(params: &mut ColorParams, band: usize) -> &mut f32 { + match band { + 0 => &mut params.brightness, + 1 => &mut params.contrast, + 2 => &mut params.saturation, + _ => &mut params.tint, + } +} + /// The line under the rows: what the picked format really writes, in the terms /// a file is judged by afterwards. fn format_line(format: Format) -> &'static str { @@ -3808,21 +4109,25 @@ mod tests { }; assert_eq!(clip.end(), 90); // Cut splits from inside only: neither edge has anything to split off. - assert!(applicable(&clip, ActionId::Cut, 31)); - assert!(applicable(&clip, ActionId::Cut, 89)); - assert!(!applicable(&clip, ActionId::Cut, 30)); - assert!(!applicable(&clip, ActionId::Cut, 90)); - assert!(!applicable(&clip, ActionId::Cut, 200)); + assert!(applicable(&clip, Lane::V1, ActionId::Cut, 31)); + assert!(applicable(&clip, Lane::V1, ActionId::Cut, 89)); + assert!(!applicable(&clip, Lane::V1, ActionId::Cut, 30)); + assert!(!applicable(&clip, Lane::V1, ActionId::Cut, 90)); + assert!(!applicable(&clip, Lane::V1, ActionId::Cut, 200)); // Regroup is the other way round: only where this clip meets another. - assert!(applicable(&clip, ActionId::Regroup, 30)); - assert!(applicable(&clip, ActionId::Regroup, 90)); - assert!(!applicable(&clip, ActionId::Regroup, 60)); + assert!(applicable(&clip, Lane::V1, ActionId::Regroup, 30)); + assert!(applicable(&clip, Lane::V1, ActionId::Regroup, 90)); + assert!(!applicable(&clip, Lane::V1, ActionId::Regroup, 60)); // The rest act on the clip that was clicked, so they always mean // something -- the engine words its own refusals. for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] { - assert!(applicable(&clip, action, 0)); - assert!(applicable(&clip, action, 60)); + assert!(applicable(&clip, Lane::V1, action, 0)); + assert!(applicable(&clip, Lane::V1, action, 60)); } + // Except the grade, which is a picture setting: offered on a video + // clip wherever the playhead is, dimmed on a waveform. + assert!(applicable(&clip, Lane::V1, ActionId::Color, 0)); + assert!(!applicable(&clip, Lane::A1, ActionId::Color, 60)); // The playhead frame is the engine's own rule, boundary included. assert_eq!(frame_at(1.0, 30.), 30); assert_eq!(frame_at(0.0, 30.), 0); @@ -4834,6 +5139,8 @@ fn main() { keymap: keymap.clone(), keys_open: false, export_open: false, + color_open: None, + color_band: 0, // What an export is until someone says otherwise: the // bitrate the picture asks for. quality: Quality::Auto, diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index cea17e3..1188b8c 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -9,7 +9,8 @@ use std::thread; use rusty_h264::Decoder; -use crate::convert::i420_to_bgra; +use crate::color::ColorParams; +use crate::convert::i420_to_bgra_with; use crate::demux::{Codec, Demuxer, VideoMeta}; use crate::hw::HwSession; @@ -119,7 +120,10 @@ impl DecodeSession { start_frame: u32, end_frame: u32, ) -> crate::Result<(VideoMeta, Receiver, Arc)> { - let (meta, stream) = Self::open_worker(path, start_frame, end_frame)?; + // 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())?; // 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())) @@ -172,12 +176,20 @@ impl DecodeSession { } /// As [`DecodeSession::open_range`], but the caller gets the whole - /// [`Worker`] and can therefore *wait* for it. In-process only: a caller - /// that outlives its workers has to be able to join them at exit. + /// [`Worker`] and can therefore *wait* for it, and the range is graded by + /// `color` -- the clip's own setting, folded into the conversion the frames + /// go through anyway (see [`i420_to_bgra_with`]). It is captured here rather + /// than read per frame because a worker *is* one clip's range: a grade + /// changed while this one runs reaches the picture when the session reseeks + /// onto the new one, which every edit does. + /// + /// In-process only: a caller that outlives its workers has to be able to + /// join them at exit. pub(crate) fn open_worker( path: impl AsRef, start_frame: u32, end_frame: u32, + color: ColorParams, ) -> crate::Result<(VideoMeta, FrameStream)> { let path = path.as_ref().to_path_buf(); let (meta, demuxer) = Demuxer::open(&path)?; @@ -228,7 +240,7 @@ impl DecodeSession { return; } eprintln!("decode backend: hardware (VA-API plugin)"); - if run_hw(hw, &tx, start_frame, end_frame, &worker_cancel) { + if run_hw(hw, &tx, start_frame, end_frame, &color, &worker_cancel) { return; } // A driver that opens but cannot decode a single frame is @@ -242,7 +254,7 @@ impl DecodeSession { return; } eprintln!("decode backend: software (rusty_h264)"); - run(demuxer, tx, start_frame, end_frame, &worker_cancel) + run(demuxer, tx, start_frame, end_frame, &color, &worker_cancel) })?; Ok(( meta, @@ -277,6 +289,7 @@ fn run_hw( tx: &SyncSender, start_frame: u32, end_frame: u32, + color: &ColorParams, cancel: &AtomicBool, ) -> bool { let mut index = start_frame; @@ -290,7 +303,7 @@ fn run_hw( index, width, height, - bgra: i420_to_bgra(y, u, v, width as usize, height as usize), + bgra: i420_to_bgra_with(color, y, u, v, width as usize, height as usize), }; index += 1; if tx.send(frame).is_err() { @@ -335,8 +348,13 @@ mod tests { /// regression fails in ten seconds instead of hanging the suite forever. #[test] fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() { - let (_meta, stream) = - DecodeSession::open_worker(&asset("test_baseline.mp4"), 0, u32::MAX).expect("open"); + let (_meta, stream) = DecodeSession::open_worker( + &asset("test_baseline.mp4"), + 0, + u32::MAX, + ColorParams::default(), + ) + .expect("open"); // Nothing is ever received: two frames fill the channel and the next // send parks the decode thread, exactly as a refused project load does. thread::sleep(Duration::from_millis(500)); @@ -359,6 +377,7 @@ fn run( tx: SyncSender, start_frame: u32, end_frame: u32, + color: &ColorParams, cancel: &AtomicBool, ) { let mut decoder = Decoder::new(); @@ -398,7 +417,7 @@ fn run( index: index as u32, width: yuv.width as u32, height: yuv.height as u32, - bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height), + bgra: i420_to_bgra_with(color, &yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height), }; index += 1; if tx.send(frame).is_err() { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index c1f7136..8f3c30d 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -264,6 +264,13 @@ fn run( } None => None, }; + // What this span is graded by -- the same answer playback's decoder + // carries, so the export is the picture that was watched. `None` for a + // gap and for an ungraded clip, and that is the path where not a byte + // is touched. Scratch outside the frame loop: it is refilled per frame + // and its allocation survives the whole span. + let grade = project.composite_color_at(span.start).copied(); + let mut graded = (Vec::new(), Vec::new(), Vec::new()); for _ in 0..span.len { cancelled(shared)?; let picture = match &mut pictures { @@ -273,6 +280,24 @@ fn run( let Some((y, u, v, width, height)) = picture else { break; // source ran out early; the clip list outlives the file }; + // The planes are borrowed from the decoder (and `Black::picture` + // hands the same slice as both u and v), so a grade cannot be + // applied in place: it goes onto a copy, which the encoder then + // reads instead. + let (y, u, v) = match grade.filter(|p| !p.is_identity()) { + Some(params) => { + let (gy, gu, gv) = &mut graded; + 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(¶ms, gy, gu, gv); + (&gy[..], &gu[..], &gv[..]) + } + None => (y, u, v), + }; if let Some(au) = encoder.encode(y, u, v, width, height)? { write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?; } diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 8ebafef..54a52c8 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -21,6 +21,7 @@ use std::time::Duration; use crate::ao::AoSession; use crate::audio::{AudioChunk, AudioSession}; use crate::clock::{ClockSource, PlaybackClock}; +use crate::color::ColorParams; use crate::decode::{DecodeSession, Frame, Worker}; use crate::demux::{Demuxer, VideoMeta}; use crate::project::{Clip, Lane, LaneKind, Project, Source, Span}; @@ -138,7 +139,11 @@ impl PlaybackSession { } // `open_worker` rather than `open` purely for the worker handle: the // field has to exist from the start for the first seek to use it. - let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?; + // Ungraded: a file just opened has one clip per lane and nothing has + // graded it yet. Every later span is opened by `start_span`, which asks + // the project. + let (meta, stream) = + DecodeSession::open_worker(&path, 0, u32::MAX, ColorParams::default())?; // A file is opened on its first audio stream, like `Project::single` // names it: nothing has picked one yet. let (audio, audio_disabled) = open_audio(&path, 0); @@ -194,8 +199,12 @@ impl PlaybackSession { // locals drop in reverse declaration order -- a bare worker would join // its decode thread while the receiver next to it was still holding // that thread parked in `send`, which is a hang (see [`FrameStream`]). - let (meta, stream) = DecodeSession::open_worker(&first.path, 0, u32::MAX) - .map_err(|e| format!("source {}: {e}", first.path.display()))?; + // Ungraded, and superseded before a frame of it is shown: the `seek` at + // the end of this function reopens the playhead's span through + // `start_span`, which is where a saved grade reaches the picture. + let (meta, stream) = + DecodeSession::open_worker(&first.path, 0, u32::MAX, ColorParams::default()) + .map_err(|e| format!("source {}: {e}", first.path.display()))?; let first_audio = AudioSession::probe(&first.path, first.audio_stream)?; let mut counts = vec![meta.frame_count]; @@ -383,10 +392,17 @@ impl PlaybackSession { /// disconnected receiver carries the session on to the next span. fn start_span(&mut self, span: Span) { let opened = match span.from { + // The grade is the composite's at this frame -- the same clip the + // span itself came from -- and it is constant across the span, so + // the worker carries it and every frame it converts wears it. Some((source, in_frame)) => DecodeSession::open_worker( &self.project.sources()[source].path, in_frame, in_frame + span.len, + self.project + .composite_color_at(span.start) + .copied() + .unwrap_or_default(), ) .map(|(_, stream)| stream) .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)), @@ -493,6 +509,30 @@ impl PlaybackSession { self.edit(|p| p.lift(lane, idx)) } + /// The clip the picture is coming from at `timeline_secs`: the lane it sits + /// on and its index there, by the same topmost-lane-wins rule the decoder + /// follows. `None` over a gap and past the end. What a card that grades + /// "this clip" opens on when nothing has been clicked. + pub fn video_clip_at(&self, timeline_secs: f64) -> Option<(Lane, usize)> { + self.project + .composite_clip_at(secs_to_frame(timeline_secs, self.meta.frame_rate)) + } + + /// How the clip at `idx` of `lane` is graded, or `None` for one that plays + /// as it was shot -- what a colour card reads when it opens. + pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> { + self.project.color_of(lane, idx) + } + + /// Grades that clip, or takes the grade off with `None`. One undo step like + /// every other edit, and it reseeks like one too -- which is what puts the + /// new grade on the frame that is already on screen, paused or playing, + /// without the caller having to nudge the playhead itself. `false` for an + /// index that is not there and for a value that is not finite. + pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option) -> bool { + self.edit(|p| p.set_color(lane, idx, params)) + } + /// 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. diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 43e2fe5..474da38 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -757,11 +757,7 @@ impl Project { if timeline_frame >= total { return None; } - let video: Vec = self - .lanes() - .into_iter() - .filter(|l| l.kind == LaneKind::Video) - .collect(); + let video = self.video_lanes(); // The last covering lane is the winner; only the lanes above it can // interrupt what it shows. let winner = video @@ -794,6 +790,36 @@ impl Project { }) } + /// The video lanes in display order, topmost last -- the order the composite + /// rule counts in. + fn video_lanes(&self) -> Vec { + self.lanes() + .into_iter() + .filter(|l| l.kind == LaneKind::Video) + .collect() + } + + /// *Which* clip the composite shows at `timeline_frame`, named: the winner + /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its + /// index on that lane. `None` over a gap and past the end. What a front-end + /// asks to act on "the clip on screen" without re-deriving the rule. + pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> { + let video = self.video_lanes(); + let winner = video + .iter() + .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?; + Some((video[winner], at(self.lane(video[winner]), timeline_frame)?)) + } + + /// How the composite is graded at `timeline_frame`, so the picture playback + /// converts and the one an export encodes are graded from one answer. + /// `None` over a gap (black is black) and for a clip nobody has graded, + /// which is the byte-identical path everywhere. + pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> { + let (lane, idx) = self.composite_clip_at(timeline_frame)?; + self.color_of(lane, idx) + } + /// [`spans_from`](Project::spans_from) over the composite: every stretch the /// viewer sees from `timeline_frame` to the end, in order. What an export /// encodes and what playback walks at a clip boundary. diff --git a/crates/engine/tests/color.rs b/crates/engine/tests/color.rs new file mode 100644 index 0000000..866a426 --- /dev/null +++ b/crates/engine/tests/color.rs @@ -0,0 +1,183 @@ +//! A per-clip colour grade, end to end: what the renderer shows and what the +//! export writes have to be the same picture, and a clip nobody graded has to +//! come out of both untouched. +//! +//! `test_baseline.mp4` is colour bars (mean channel spread 249 of 255), so +//! saturation 0 is not a subtle claim: every pixel of a graded span is grey to +//! within the converter's own rounding, and every pixel outside it is not. +//! +//! ```text +//! cargo test -p engine --release --test color -- --nocapture --test-threads=1 +//! ``` + +use std::path::{Path, PathBuf}; +use std::thread::sleep; +use std::time::{Duration, Instant}; + +use engine::color::ColorParams; +use engine::export::ExportSettings; +use engine::project::Lane; +use engine::{DecodeSession, ExportHandle, PlaybackSession}; + +const FPS: f64 = 30.0; +/// Where the first clip ends and the ungraded one begins. +const CUT: u32 = 30; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Silent, like every other suite that plays a real file: the grade is a +/// picture setting and nothing here listens. +fn open(path: &Path) -> PlaybackSession { + let session = PlaybackSession::open(path).expect("open"); + session.set_gain(0.0); + session +} + +/// Two clips on `V1`, the first of them drained of all colour. +fn graded() -> PlaybackSession { + let mut session = open(&asset("test_baseline.mp4")); + assert!(session.cut_at(f64::from(CUT) / FPS), "cut at frame 30"); + assert!( + session.set_color( + Lane::V1, + 0, + Some(ColorParams { + saturation: 0.0, + ..Default::default() + }) + ), + "grade the first clip" + ); + session +} + +/// How far a BGRA frame is from grey: the mean spread between its channels, +/// which is 0 for a greyscale picture and ~250 for these colour bars. +fn spread(bgra: &[u8]) -> f64 { + let total: u64 = bgra + .chunks_exact(4) + .map(|px| u64::from(px[..3].iter().max().unwrap() - px[..3].iter().min().unwrap())) + .sum(); + total as f64 / (bgra.len() / 4) as f64 +} + +/// The next frame off a freshly seeked channel. +fn next_frame(session: &mut PlaybackSession, what: &str) -> engine::Frame { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Some(frame) = session.try_frame() { + return frame; + } + assert!(Instant::now() < deadline, "no frame after {what}"); + sleep(Duration::from_millis(4)); + } +} + +fn seek_and_show(session: &mut PlaybackSession, frame: u32) -> Vec { + session.seek(f64::from(frame) / FPS); + let shown = next_frame(session, "a seek"); + assert_eq!(shown.index, frame, "the seek landed elsewhere"); + shown.bgra +} + +/// The render half: the grade reaches the picture, and it stops at the clip's +/// own edge rather than colouring the whole timeline. +#[test] +fn a_graded_clip_renders_grey_and_the_next_one_does_not() { + let mut session = graded(); + for frame in [0, CUT - 1] { + let inside = spread(&seek_and_show(&mut session, frame)); + assert!( + inside <= 2.0, + "frame {frame} is graded and not grey: {inside}" + ); + } + for frame in [CUT, CUT + 15] { + let outside = spread(&seek_and_show(&mut session, frame)); + assert!( + outside > 100.0, + "frame {frame} is outside the graded clip and lost its colour: {outside}" + ); + } +} + +/// Live: a grade set while the session is up repaints what is on screen. The +/// engine reseeks on the edit, so the very next frame is the graded one -- no +/// scrub, no reopen by the caller. +#[test] +fn setting_a_grade_repaints_the_frame_that_is_already_up() { + let mut session = open(&asset("test_baseline.mp4")); + let before = spread(&seek_and_show(&mut session, 10)); + assert!(before > 100.0, "the fixture is not colour bars: {before}"); + + assert!(session.set_color( + Lane::V1, + 0, + Some(ColorParams { + saturation: 0.0, + ..Default::default() + }) + )); + let after = spread(&next_frame(&mut session, "a grade").bgra); + assert!(after <= 2.0, "the frame on screen kept its colour: {after}"); + + // And taking it off puts the colour back, on the same terms. + assert!(session.set_color(Lane::V1, 0, None)); + let back = spread(&next_frame(&mut session, "an ungrade").bgra); + assert!(back > 100.0, "ungrading left the picture grey: {back}"); +} + +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < limit, + "export did not finish in {limit:?}" + ); + sleep(Duration::from_millis(20)); + } + handle.result().expect("a finished export has an outcome") +} + +/// The export half, decoded back off disk: the same picture the renderer +/// showed, graded span for graded span. Software encoder, so it needs nothing +/// installed -- the same pin `tests/export.rs`'s default suite uses. +#[test] +fn an_exported_grade_is_the_one_that_was_watched() { + unsafe { + std::env::set_var("VE_SW", "1"); + std::env::set_var("VE_SW_ENC", "1"); + } + let mut session = graded(); + session.pause(); + let out = std::env::temp_dir().join(format!("ve_color_{}.mp4", std::process::id())); + let _ = std::fs::remove_file(&out); + let handle = session.export_to_with(&out, &ExportSettings::default()); + wait(&handle, Duration::from_secs(180)).expect("export"); + + let (_, frames) = DecodeSession::open(&out).expect("decode the export"); + let mut seen = 0; + for frame in frames { + let spread = spread(&frame.bgra); + if frame.index < CUT { + assert!( + spread <= 4.0, + "exported frame {} is inside the graded clip and kept its colour: {spread}", + frame.index + ); + } else { + assert!( + spread > 100.0, + "exported frame {} is outside the graded clip and lost its colour: {spread}", + frame.index + ); + } + seen += 1; + } + assert!(seen > CUT, "the export is shorter than the graded clip"); + let _ = std::fs::remove_file(&out); +}