forge
Explore
Log in

Don't you dare go Hollow

Per-clip color grade is live in render and export

Browse files at this commit

bd89527f631c61a78423286cb249abde6f42a0c6Ahmet Kaan GümüşParent: b128a34
  • feat
    • per-clip color grade is live in render and export
Show full message
✨ feat(video): per-clip color grade is live in render and export

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.rsmodified+35 -5
@@ -47,6 +47,7 @@ pub enum ActionId {
47 Regroup,47 Regroup,
48 Delete,48 Delete,
49 Lift,49 Lift,
50+ Color,
50 Undo,51 Undo,
51 AddVideoLane,52 AddVideoLane,
52 AddAudioLane,53 AddAudioLane,
@@ -59,7 +60,7 @@ pub enum ActionId {
59 impl ActionId {60 impl ActionId {
60 /// Display order everywhere -- the editor lists them in it and61 /// Display order everywhere -- the editor lists them in it and
61 /// [`Keymap::defaults`] binds them in it.62 /// [`Keymap::defaults`] binds them in it.
62- pub const ALL: [ActionId; 16] = [63+ pub const ALL: [ActionId; 17] = [
63 ActionId::Play,64 ActionId::Play,
64 ActionId::Export,65 ActionId::Export,
65 ActionId::Save,66 ActionId::Save,
@@ -69,6 +70,7 @@ impl ActionId {
69 ActionId::Regroup,70 ActionId::Regroup,
70 ActionId::Delete,71 ActionId::Delete,
71 ActionId::Lift,72 ActionId::Lift,
73+ ActionId::Color,
72 ActionId::Undo,74 ActionId::Undo,
73 ActionId::AddVideoLane,75 ActionId::AddVideoLane,
74 ActionId::AddAudioLane,76 ActionId::AddAudioLane,
@@ -90,6 +92,7 @@ impl ActionId {
90 ActionId::Regroup => "Regroup",92 ActionId::Regroup => "Regroup",
91 ActionId::Delete => "Delete",93 ActionId::Delete => "Delete",
92 ActionId::Lift => "Lift (leave a gap)",94 ActionId::Lift => "Lift (leave a gap)",
95+ ActionId::Color => "Colour…",
93 ActionId::Undo => "Undo",96 ActionId::Undo => "Undo",
94 ActionId::AddVideoLane => "Add a video track",97 ActionId::AddVideoLane => "Add a video track",
95 ActionId::AddAudioLane => "Add an audio track",98 ActionId::AddAudioLane => "Add an audio track",
@@ -113,6 +116,7 @@ impl ActionId {
113 ActionId::Regroup => "regroup",116 ActionId::Regroup => "regroup",
114 ActionId::Delete => "delete",117 ActionId::Delete => "delete",
115 ActionId::Lift => "lift",118 ActionId::Lift => "lift",
119+ ActionId::Color => "color",
116 ActionId::Undo => "undo",120 ActionId::Undo => "undo",
117 ActionId::AddVideoLane => "add-video-lane",121 ActionId::AddVideoLane => "add-video-lane",
118 ActionId::AddAudioLane => "add-audio-lane",122 ActionId::AddAudioLane => "add-audio-lane",
@@ -133,7 +137,11 @@ impl ActionId {
133 pub fn category(self) -> Category {137 pub fn category(self) -> Category {
134 match self {138 match self {
135 ActionId::Play => Category::Playback,139 ActionId::Play => Category::Playback,
136- ActionId::Copy | ActionId::Paste | ActionId::Delete | ActionId::Lift => Category::Clips,140+ ActionId::Copy
141+ | ActionId::Paste
142+ | ActionId::Delete
143+ | ActionId::Lift
144+ | ActionId::Color => Category::Clips,
137 ActionId::Cut145 ActionId::Cut
138 | ActionId::Regroup146 | ActionId::Regroup
139 | ActionId::Undo147 | ActionId::Undo
@@ -191,7 +199,7 @@ pub struct Fixed {
191 pub category: Category,199 pub category: Category,
192 }200 }
193 201
194-pub const FIXED: [Fixed; 5] = [202+pub const FIXED: [Fixed; 8] = [
195 Fixed {203 Fixed {
196 chord: "esc",204 chord: "esc",
197 label: "Close this card or clip menu, or cancel a capture",205 label: "Close this card or clip menu, or cancel a capture",
@@ -217,6 +225,23 @@ pub const FIXED: [Fixed; 5] = [
217 label: "Erase a bitrate digit",225 label: "Erase a bitrate digit",
218 category: Category::File,226 category: Category::File,
219 },227 },
228+ // The colour card's own three, which mean nothing outside it -- the same
229+ // card-local input the export card's digits are.
230+ Fixed {
231+ chord: "↑ / ↓",
232+ label: "Pick a colour slider",
233+ category: Category::Clips,
234+ },
235+ Fixed {
236+ chord: "← / →",
237+ label: "Move the picked colour slider",
238+ category: Category::Clips,
239+ },
240+ Fixed {
241+ chord: "r",
242+ label: "Take the colour grade off the clip",
243+ category: Category::Clips,
244+ },
220 ];245 ];
221 246
222 /// A stroke as the key handler sees it: gpui's key name plus the one modifier247 /// A stroke as the key handler sees it: gpui's key name plus the one modifier
@@ -320,6 +345,10 @@ impl Keymap {
320 b(ActionId::Delete, "x", false),345 b(ActionId::Delete, "x", false),
321 b(ActionId::Delete, "delete", false),346 b(ActionId::Delete, "delete", false),
322 b(ActionId::Lift, "l", false),347 b(ActionId::Lift, "l", false),
348+ // The c of colour is Cut and ctrl+c is Copy, so the grade takes
349+ // k: free, next to nothing that edits, and one press like the
350+ // rest of the clip keys.
351+ b(ActionId::Color, "k", false),
323 b(ActionId::Undo, "z", false),352 b(ActionId::Undo, "z", false),
324 b(ActionId::Undo, "z", true),353 b(ActionId::Undo, "z", true),
325 // The unshifted initials of what they add. Both were free --354 // The unshifted initials of what they add. Both were free --
@@ -559,7 +588,7 @@ mod tests {
559 #[test]588 #[test]
560 fn every_default_stroke_reaches_its_action() {589 fn every_default_stroke_reaches_its_action() {
561 let k = Keymap::defaults();590 let k = Keymap::defaults();
562- assert_eq!(k.entries().len(), 18);591+ assert_eq!(k.entries().len(), 19);
563 assert_eq!(k.lookup("space", false), Some(ActionId::Play));592 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
564 assert_eq!(k.lookup("e", false), Some(ActionId::Export));593 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
565 assert_eq!(k.lookup("s", true), Some(ActionId::Save));594 assert_eq!(k.lookup("s", true), Some(ActionId::Save));
@@ -570,6 +599,7 @@ mod tests {
570 assert_eq!(k.lookup("x", false), Some(ActionId::Delete));599 assert_eq!(k.lookup("x", false), Some(ActionId::Delete));
571 assert_eq!(k.lookup("delete", false), Some(ActionId::Delete));600 assert_eq!(k.lookup("delete", false), Some(ActionId::Delete));
572 assert_eq!(k.lookup("l", false), Some(ActionId::Lift));601 assert_eq!(k.lookup("l", false), Some(ActionId::Lift));
602+ assert_eq!(k.lookup("k", false), Some(ActionId::Color));
573 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));603 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));
574 assert_eq!(k.lookup("z", true), Some(ActionId::Undo));604 assert_eq!(k.lookup("z", true), Some(ActionId::Undo));
575 // The track keys are the bare letters; the ctrl ones stay copy/paste.605 // The track keys are the bare letters; the ctrl ones stay copy/paste.
@@ -709,7 +739,7 @@ mod tests {
709 );739 );
710 // The label is the editor's column, and never the file's word for it.740 // The label is the editor's column, and never the file's word for it.
711 assert_eq!(ActionId::CancelExport.label(), "Cancel export");741 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
712- assert_eq!(ActionId::ALL.len(), 16);742+ assert_eq!(ActionId::ALL.len(), 17);
713 }743 }
714 744
715 #[test]745 #[test]
crates/app/src/main.rsmodified+321 -14
@@ -10,6 +10,7 @@ use std::sync::Arc;
10 use std::time::{Duration, Instant};10 use std::time::{Duration, Instant};
11 11
12 use engine::audio::StreamInfo;12 use engine::audio::StreamInfo;
13+use engine::color::ColorParams;
13 use engine::export::{ExportSettings, Format};14 use engine::export::{ExportSettings, Format};
14 use engine::project::{Lane, LaneKind, Source};15 use engine::project::{Lane, LaneKind, Source};
15 use engine::{Clip, ExportHandle, Frame, PlaybackSession};16 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
@@ -219,14 +220,36 @@ struct ContextMenu {
219 /// action a stroke already reaches -- the menu is a second way *to* the actions220 /// action a stroke already reaches -- the menu is a second way *to* the actions
220 /// and never a second version of them -- so both the label and the hint come221 /// and never a second version of them -- so both the label and the hint come
221 /// out of the keymap registry and the two can never disagree.222 /// out of the keymap registry and the two can never disagree.
222-const MENU_ITEMS: [ActionId; 5] = [223+const MENU_ITEMS: [ActionId; 6] = [
223 ActionId::Cut,224 ActionId::Cut,
224 ActionId::Delete,225 ActionId::Delete,
225 ActionId::Lift,226 ActionId::Lift,
226 ActionId::Regroup,227 ActionId::Regroup,
228+ ActionId::Color,
227 ActionId::ToggleMute,229 ActionId::ToggleMute,
228 ];230 ];
229 231
232+/// The colour card's four controls, in the order it lists them: what each is
233+/// called and the range it moves in. The order is `ColorParams`' own, which is
234+/// what [`color_band`] indexes.
235+const COLOR_BANDS: [(&str, f32, f32); 4] = [
236+ ("Brightness", -1., 1.),
237+ ("Contrast", 0., 2.),
238+ ("Saturation", 0., 2.),
239+ ("Tint (cool–warm)", -1., 1.),
240+];
241+
242+/// A press of a nudge key or button: a fortieth of a band's range, so a slider
243+/// crosses it in forty presses and every stop is a number the file can write.
244+const COLOR_STEP: f32 = 0.05;
245+
246+/// The card's width: a slider row is a label, two buttons, the bar and the
247+/// value, and the longest label has to fit beside all four without truncating
248+/// (measured against "Tint (cool–warm)" at 460).
249+const COLOR_W: f32 = 460.;
250+/// How much of a slider row the bar itself gets.
251+const COLOR_BAR_W: f32 = 140.;
252+
230 struct Player {253 struct Player {
231 /// The timeline, once there is one. A run with no file opens without it and254 /// The timeline, once there is one. A run with no file opens without it and
232 /// waits: the first media import or project load is what fills it, and255 /// waits: the first media import or project load is what fills it, and
@@ -321,6 +344,13 @@ struct Player {
321 /// Which file the card will write. Kept across closes like the quality, and344 /// Which file the card will write. Kept across closes like the quality, and
322 /// what [`Player::export_path`](Player) is named after.345 /// what [`Player::export_path`](Player) is named after.
323 format: Format,346 format: Format,
347+ /// The colour card is up on this clip -- the lane it is on and its index
348+ /// there. `None` when it is closed, which is the only place that state
349+ /// lives: the grade itself is the project's.
350+ color_open: Option<(Lane, usize)>,
351+ /// Which of the card's four sliders the arrow keys and the buttons move.
352+ /// The card's own focus, since nothing in it takes gpui's (ledger:182).
353+ color_band: usize,
324 /// The action whose row is waiting for a stroke. The next key that is354 /// The action whose row is waiting for a stroke. The next key that is
325 /// neither escape nor a lone modifier becomes the whole of what reaches it.355 /// neither escape nor a lone modifier becomes the whole of what reaches it.
326 rebinding: Option<ActionId>,356 rebinding: Option<ActionId>,
@@ -431,6 +461,7 @@ impl Player {
431 ActionId::Regroup => self.regroup(cx),461 ActionId::Regroup => self.regroup(cx),
432 ActionId::Delete => self.delete_selected(cx),462 ActionId::Delete => self.delete_selected(cx),
433 ActionId::Lift => self.lift_selected(cx),463 ActionId::Lift => self.lift_selected(cx),
464+ ActionId::Color => self.open_color(cx),
434 ActionId::Undo => self.undo(cx),465 ActionId::Undo => self.undo(cx),
435 ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx),466 ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx),
436 ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx),467 ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx),
@@ -443,11 +474,86 @@ impl Player {
443 }474 }
444 }475 }
445 476
477+ /// Opens the colour card on the clip a grade would go on: the clip that was
478+ /// clicked when it is a video one, and otherwise the clip the picture is
479+ /// coming from -- the one the engine's own compositing rule picks, which is
480+ /// what a person means by "this shot". That fallback is also what makes the
481+ /// card reachable with no pointer at all: clip selection is a click and
482+ /// nothing else (ledger:182).
483+ fn open_color(&mut self, cx: &mut Context<Self>) {
484+ if self.exporting().is_some() {
485+ return;
486+ }
487+ let Some(session) = &self.session else {
488+ self.notice = Some("no timeline to grade — open a file first".into());
489+ cx.notify();
490+ return;
491+ };
492+ let target = self
493+ .selected
494+ .filter(|(lane, _)| lane.kind == LaneKind::Video)
495+ .or_else(|| session.video_clip_at(session.now()));
496+ match target {
497+ Some(clip) => {
498+ self.color_open = Some(clip);
499+ self.color_band = 0;
500+ // One card at a time, the rule both the others already follow.
501+ self.keys_open = false;
502+ self.export_open = false;
503+ self.context_menu = None;
504+ }
505+ None => self.notice = Some("no clip under the playhead to grade".into()),
506+ }
507+ cx.notify();
508+ }
509+
510+ /// What the card's clip is graded by right now -- the identity for one
511+ /// nobody has graded, which is what the sliders start at.
512+ fn color_params(&self) -> ColorParams {
513+ self.color_open
514+ .zip(self.session.as_ref())
515+ .and_then(|((lane, idx), session)| session.color_of(lane, idx).copied())
516+ .unwrap_or_default()
517+ }
518+
519+ /// Puts `params` on the card's clip, or takes the grade off when they are
520+ /// the identity -- a slider walked back to the middle leaves the clip
521+ /// ungraded rather than carrying a do-nothing entry, which is what keeps an
522+ /// untouched project byte-identical. The engine reseeks on the edit, so the
523+ /// frame on screen repaints through the new grade; this only owes the flags
524+ /// that reseek clears.
525+ fn set_color(&mut self, params: ColorParams, cx: &mut Context<Self>) {
526+ let Some((lane, idx)) = self.color_open else {
527+ return;
528+ };
529+ let Some(session) = &mut self.session else {
530+ return;
531+ };
532+ let grade = Some(params).filter(|p| !p.is_identity());
533+ if session.set_color(lane, idx, grade) {
534+ self.reset_after_reseek();
535+ }
536+ cx.notify();
537+ }
538+
539+ /// Moves the picked slider by `steps` of [`COLOR_STEP`], clamped to that
540+ /// band's range. One edit, so one undo step per press.
541+ fn nudge_color(&mut self, steps: f32, cx: &mut Context<Self>) {
542+ let mut params = self.color_params();
543+ let (_, low, high) = COLOR_BANDS[self.color_band];
544+ let value = band_mut(&mut params, self.color_band);
545+ *value = (*value + steps * COLOR_STEP).clamp(low, high);
546+ self.set_color(params, cx);
547+ }
548+
446 /// Whether a card owns the window. While one does the timeline under it is549 /// Whether a card owns the window. While one does the timeline under it is
447 /// out of reach, so a right-click there opens no menu -- the same rule the550 /// out of reach, so a right-click there opens no menu -- the same rule the
448 /// key handler and the drop target already follow.551 /// key handler and the drop target already follow.
449 fn modal(&self) -> bool {552 fn modal(&self) -> bool {
450- self.keys_open || self.export_open || self.exporting().is_some()553+ self.keys_open
554+ || self.export_open
555+ || self.color_open.is_some()
556+ || self.exporting().is_some()
451 }557 }
452 558
453 /// Jumps the timeline.559 /// Jumps the timeline.
@@ -1259,6 +1365,26 @@ impl Render for Player {
1259 cx.notify();1365 cx.notify();
1260 return;1366 return;
1261 }1367 }
1368+ // The colour card owns the keyboard the same way the export
1369+ // card does, and its keys mean nothing outside it: the arrows
1370+ // pick a slider and move it, and `r` takes the grade off. Not
1371+ // keymap bindings for exactly that reason -- see `FIXED`, where
1372+ // the keys menu still lists them.
1373+ if this.color_open.is_some() {
1374+ match color_key(key) {
1375+ Some(ColorKey::Close) => this.color_open = None,
1376+ Some(ColorKey::Band(step)) => {
1377+ this.color_band = (this.color_band + step) % COLOR_BANDS.len();
1378+ }
1379+ Some(ColorKey::Nudge(steps)) => this.nudge_color(steps, cx),
1380+ Some(ColorKey::Reset) => {
1381+ this.set_color(ColorParams::default(), cx);
1382+ }
1383+ None => {}
1384+ }
1385+ cx.notify();
1386+ return;
1387+ }
1262 // A clip menu names an index, and every edit below moves1388 // A clip menu names an index, and every edit below moves
1263 // indices -- so a stroke closes it before it acts. Escape means1389 // indices -- so a stroke closes it before it acts. Escape means
1264 // that and nothing else, which is the `esc` the keys menu1390 // that and nothing else, which is the `esc` the keys menu
@@ -1387,6 +1513,7 @@ impl Render for Player {
1387 // column, and only one of the two is ever up.1513 // column, and only one of the two is ever up.
1388 .children(self.keys_overlay(cx))1514 .children(self.keys_overlay(cx))
1389 .children(self.export_card(cx))1515 .children(self.export_card(cx))
1516+ .children(self.color_card(cx))
1390 }1517 }
1391 }1518 }
1392 1519
@@ -2261,6 +2388,141 @@ impl Player {
2261 )2388 )
2262 }2389 }
2263 2390
2391+ /// The colour card: a row per control, each showing where in its range it
2392+ /// stands and carrying the pair of buttons that move it -- the same move the
2393+ /// arrow keys make, because a control only the pointer can reach is not one
2394+ /// everyone can reach. Same scrim, surface and row shape as the other two
2395+ /// cards, and the same plain divs, so the root keeps the keyboard.
2396+ ///
2397+ /// The values are read from the project every render: what is drawn is what
2398+ /// the decoder is grading with, never a copy that could drift from it.
2399+ fn color_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2400+ let (lane, idx) = self.color_open?;
2401+ let params = self.color_params();
2402+ let rows: Vec<_> = COLOR_BANDS
2403+ .iter()
2404+ .enumerate()
2405+ .map(|(i, &(label, low, high))| {
2406+ let mut read = params;
2407+ let value = *band_mut(&mut read, i);
2408+ let frac = ((value - low) / (high - low)).clamp(0., 1.);
2409+ let picked = i == self.color_band;
2410+ // Both buttons of a row do what the arrows do, so there is one
2411+ // rule for what a press is worth and one place it is clamped.
2412+ let step = |name: &'static str, steps: f32| {
2413+ div()
2414+ .id((name, i))
2415+ .w(px(CONTROL_H))
2416+ .h(px(CONTROL_H))
2417+ .flex()
2418+ .items_center()
2419+ .justify_center()
2420+ .rounded(px(3.))
2421+ .bg(rgb(CHROME))
2422+ .cursor_pointer()
2423+ .hover(|s| s.bg(rgb(HOVER)))
2424+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2425+ this.color_band = i;
2426+ this.nudge_color(steps, cx);
2427+ }))
2428+ .child(if steps < 0. { "–" } else { "+" })
2429+ };
2430+ div()
2431+ .id(("color-row", i))
2432+ .flex()
2433+ .min_h(px(KEYS_ROW_H))
2434+ .items_center()
2435+ .gap(px(8.))
2436+ .px(px(6.))
2437+ .rounded(px(3.))
2438+ .cursor_pointer()
2439+ .when(picked, |d| d.bg(rgb(SELECTED)))
2440+ .hover(|s| s.bg(rgb(HOVER)))
2441+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2442+ this.color_band = i;
2443+ cx.notify();
2444+ }))
2445+ .child(div().flex_1().min_w(px(0.)).truncate().child(label))
2446+ .child(step("color-down", -1.))
2447+ .child(
2448+ div()
2449+ .w(px(COLOR_BAR_W))
2450+ .h(px(4.))
2451+ .rounded(px(2.))
2452+ .bg(rgb(CHROME))
2453+ .child(
2454+ div()
2455+ .h_full()
2456+ .w(relative(frac))
2457+ .rounded(px(2.))
2458+ .bg(rgb(ACCENT)),
2459+ ),
2460+ )
2461+ .child(step("color-up", 1.))
2462+ .child(
2463+ div()
2464+ .w(px(44.))
2465+ .text_size(px(11.))
2466+ .text_color(rgb(INK_DIM))
2467+ .child(format!("{value:.2}")),
2468+ )
2469+ })
2470+ .collect();
2471+ Some(
2472+ div()
2473+ .absolute()
2474+ .inset_0()
2475+ .flex()
2476+ .justify_center()
2477+ .items_center()
2478+ .bg(rgba(0x101010cc))
2479+ .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
2480+ cx.stop_propagation()
2481+ })
2482+ .child(
2483+ div()
2484+ .w(px(COLOR_W))
2485+ .flex()
2486+ .flex_col()
2487+ .gap(px(2.))
2488+ .p(px(12.))
2489+ .rounded(px(6.))
2490+ .bg(rgb(SURFACE))
2491+ .child(div().flex_none().px(px(6.)).child(format!(
2492+ "Colour — {} clip {}",
2493+ lane.label(),
2494+ idx + 1
2495+ )))
2496+ .child(
2497+ div()
2498+ .flex_none()
2499+ .px(px(6.))
2500+ .text_size(px(11.))
2501+ .text_color(rgb(INK_DIM))
2502+ .child("↑↓ picks a slider, ←→ moves it, r resets — esc closes"),
2503+ )
2504+ .children(rows)
2505+ .child(
2506+ div()
2507+ .id("color-reset")
2508+ .mt(px(4.))
2509+ .flex()
2510+ .h(px(CONTROL_H))
2511+ .items_center()
2512+ .justify_center()
2513+ .rounded(px(3.))
2514+ .bg(rgb(SELECTED))
2515+ .cursor_pointer()
2516+ .hover(|s| s.bg(rgb(HOVER)))
2517+ .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
2518+ this.set_color(ColorParams::default(), cx);
2519+ }))
2520+ .child("Reset"),
2521+ ),
2522+ ),
2523+ )
2524+ }
2525+
2264 /// The menu a right-click on a clip opens: what that clip can be given,2526 /// The menu a right-click on a clip opens: what that clip can be given,
2265 /// each item beside the stroke that does the very same thing, and a2527 /// each item beside the stroke that does the very same thing, and a
2266 /// turn-over side that says what the clip *is*. An item that would do2528 /// turn-over side that says what the clip *is*. An item that would do
@@ -2336,7 +2598,7 @@ impl Player {
2336 }2598 }
2337 } else {2599 } else {
2338 for action in MENU_ITEMS {2600 for action in MENU_ITEMS {
2339- let enabled = applicable(&clip, action, playhead);2601+ let enabled = applicable(&clip, menu.lane, action, playhead);
2340 // The one item that is not about this clip says so, and says it2602 // The one item that is not about this clip says so, and says it
2341 // here rather than in the registry: the stroke is global too,2603 // here rather than in the registry: the stroke is global too,
2342 // but its row in the keys menu is not sitting on a clip.2604 // 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 {
2859 /// Whether the clip menu offers `action` on the clip it was opened on. Two of3121 /// Whether the clip menu offers `action` on the clip it was opened on. Two of
2860 /// the items act on the *playhead* rather than on the clip, so a menu opened3122 /// the items act on the *playhead* rather than on the clip, so a menu opened
2861 /// away from it dims them instead of looking broken when they are clicked.3123 /// away from it dims them instead of looking broken when they are clicked.
2862-fn applicable(clip: &Clip, action: ActionId, playhead: u32) -> bool {3124+fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool {
2863 match action {3125 match action {
3126+ // A grade is a picture setting and an audio clip has no picture: the
3127+ // item is there on every clip, and dimmed where it would mean nothing.
3128+ ActionId::Color => lane.kind == LaneKind::Video,
2864 // Splits this clip only from inside it: at either edge there is nothing3129 // Splits this clip only from inside it: at either edge there is nothing
2865 // to split off (project.rs `splittable`).3130 // to split off (project.rs `splittable`).
2866 ActionId::Cut => clip.start < playhead && playhead < clip.end(),3131 ActionId::Cut => clip.start < playhead && playhead < clip.end(),
@@ -3151,6 +3416,42 @@ fn format_key(key: &str) -> Option<Format> {
3151 .map(|(format, _)| format)3416 .map(|(format, _)| format)
3152 }3417 }
3153 3418
3419+/// What one of the colour card's own strokes does. Its keys are card-local --
3420+/// they mean nothing outside it -- so they are a table here rather than keymap
3421+/// bindings, exactly as the export card's format initials are. Listed in
3422+/// `keymap::FIXED` all the same, which is how the keys menu still says so.
3423+enum ColorKey {
3424+ Close,
3425+ /// Steps down the four sliders, wrapping.
3426+ Band(usize),
3427+ /// Moves the picked slider, in [`COLOR_STEP`]s.
3428+ Nudge(f32),
3429+ Reset,
3430+}
3431+
3432+fn color_key(key: &str) -> Option<ColorKey> {
3433+ Some(match key {
3434+ ESCAPE => ColorKey::Close,
3435+ "down" => ColorKey::Band(1),
3436+ "up" => ColorKey::Band(COLOR_BANDS.len() - 1),
3437+ "right" => ColorKey::Nudge(1.),
3438+ "left" => ColorKey::Nudge(-1.),
3439+ "r" => ColorKey::Reset,
3440+ _ => return None,
3441+ })
3442+}
3443+
3444+/// The band'th control of a grade, to read or to write. The order is
3445+/// [`COLOR_BANDS`]', which is the order the card lists them in.
3446+fn band_mut(params: &mut ColorParams, band: usize) -> &mut f32 {
3447+ match band {
3448+ 0 => &mut params.brightness,
3449+ 1 => &mut params.contrast,
3450+ 2 => &mut params.saturation,
3451+ _ => &mut params.tint,
3452+ }
3453+}
3454+
3154 /// The line under the rows: what the picked format really writes, in the terms3455 /// The line under the rows: what the picked format really writes, in the terms
3155 /// a file is judged by afterwards.3456 /// a file is judged by afterwards.
3156 fn format_line(format: Format) -> &'static str {3457 fn format_line(format: Format) -> &'static str {
@@ -3808,21 +4109,25 @@ mod tests {
3808 };4109 };
3809 assert_eq!(clip.end(), 90);4110 assert_eq!(clip.end(), 90);
3810 // Cut splits from inside only: neither edge has anything to split off.4111 // Cut splits from inside only: neither edge has anything to split off.
3811- assert!(applicable(&clip, ActionId::Cut, 31));4112+ assert!(applicable(&clip, Lane::V1, ActionId::Cut, 31));
3812- assert!(applicable(&clip, ActionId::Cut, 89));4113+ assert!(applicable(&clip, Lane::V1, ActionId::Cut, 89));
3813- assert!(!applicable(&clip, ActionId::Cut, 30));4114+ assert!(!applicable(&clip, Lane::V1, ActionId::Cut, 30));
3814- assert!(!applicable(&clip, ActionId::Cut, 90));4115+ assert!(!applicable(&clip, Lane::V1, ActionId::Cut, 90));
3815- assert!(!applicable(&clip, ActionId::Cut, 200));4116+ assert!(!applicable(&clip, Lane::V1, ActionId::Cut, 200));
3816 // Regroup is the other way round: only where this clip meets another.4117 // Regroup is the other way round: only where this clip meets another.
3817- assert!(applicable(&clip, ActionId::Regroup, 30));4118+ assert!(applicable(&clip, Lane::V1, ActionId::Regroup, 30));
3818- assert!(applicable(&clip, ActionId::Regroup, 90));4119+ assert!(applicable(&clip, Lane::V1, ActionId::Regroup, 90));
3819- assert!(!applicable(&clip, ActionId::Regroup, 60));4120+ assert!(!applicable(&clip, Lane::V1, ActionId::Regroup, 60));
3820 // The rest act on the clip that was clicked, so they always mean4121 // The rest act on the clip that was clicked, so they always mean
3821 // something -- the engine words its own refusals.4122 // something -- the engine words its own refusals.
3822 for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] {4123 for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] {
3823- assert!(applicable(&clip, action, 0));4124+ assert!(applicable(&clip, Lane::V1, action, 0));
3824- assert!(applicable(&clip, action, 60));4125+ assert!(applicable(&clip, Lane::V1, action, 60));
3825 }4126 }
4127+ // Except the grade, which is a picture setting: offered on a video
4128+ // clip wherever the playhead is, dimmed on a waveform.
4129+ assert!(applicable(&clip, Lane::V1, ActionId::Color, 0));
4130+ assert!(!applicable(&clip, Lane::A1, ActionId::Color, 60));
3826 // The playhead frame is the engine's own rule, boundary included.4131 // The playhead frame is the engine's own rule, boundary included.
3827 assert_eq!(frame_at(1.0, 30.), 30);4132 assert_eq!(frame_at(1.0, 30.), 30);
3828 assert_eq!(frame_at(0.0, 30.), 0);4133 assert_eq!(frame_at(0.0, 30.), 0);
@@ -4834,6 +5139,8 @@ fn main() {
4834 keymap: keymap.clone(),5139 keymap: keymap.clone(),
4835 keys_open: false,5140 keys_open: false,
4836 export_open: false,5141 export_open: false,
5142+ color_open: None,
5143+ color_band: 0,
4837 // What an export is until someone says otherwise: the5144 // What an export is until someone says otherwise: the
4838 // bitrate the picture asks for.5145 // bitrate the picture asks for.
4839 quality: Quality::Auto,5146 quality: Quality::Auto,
crates/engine/src/decode.rsmodified+29 -10
@@ -9,7 +9,8 @@ use std::thread;
9 9
10 use rusty_h264::Decoder;10 use rusty_h264::Decoder;
11 11
12-use crate::convert::i420_to_bgra;12+use crate::color::ColorParams;
13+use crate::convert::i420_to_bgra_with;
13 use crate::demux::{Codec, Demuxer, VideoMeta};14 use crate::demux::{Codec, Demuxer, VideoMeta};
14 use crate::hw::HwSession;15 use crate::hw::HwSession;
15 16
@@ -119,7 +120,10 @@ impl DecodeSession {
119 start_frame: u32,120 start_frame: u32,
120 end_frame: u32,121 end_frame: u32,
121 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {122 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
122- let (meta, stream) = Self::open_worker(path, start_frame, end_frame)?;123+ // Ungraded: the public API opens a *file*, and a colour grade belongs to
124+ // a clip of a timeline. `PlaybackSession` is what has one to pass.
125+ let (meta, stream) =
126+ Self::open_worker(path, start_frame, end_frame, ColorParams::default())?;
123 // The public API hands out the flag alone, so the worker is detached and127 // The public API hands out the flag alone, so the worker is detached and
124 // the receiver goes to the caller: nothing here joins anything.128 // the receiver goes to the caller: nothing here joins anything.
125 Ok((meta, stream.frames, stream.worker.detach()))129 Ok((meta, stream.frames, stream.worker.detach()))
@@ -172,12 +176,20 @@ impl DecodeSession {
172 }176 }
173 177
174 /// As [`DecodeSession::open_range`], but the caller gets the whole178 /// As [`DecodeSession::open_range`], but the caller gets the whole
175- /// [`Worker`] and can therefore *wait* for it. In-process only: a caller179+ /// [`Worker`] and can therefore *wait* for it, and the range is graded by
176- /// that outlives its workers has to be able to join them at exit.180+ /// `color` -- the clip's own setting, folded into the conversion the frames
181+ /// go through anyway (see [`i420_to_bgra_with`]). It is captured here rather
182+ /// than read per frame because a worker *is* one clip's range: a grade
183+ /// changed while this one runs reaches the picture when the session reseeks
184+ /// onto the new one, which every edit does.
185+ ///
186+ /// In-process only: a caller that outlives its workers has to be able to
187+ /// join them at exit.
177 pub(crate) fn open_worker(188 pub(crate) fn open_worker(
178 path: impl AsRef<Path>,189 path: impl AsRef<Path>,
179 start_frame: u32,190 start_frame: u32,
180 end_frame: u32,191 end_frame: u32,
192+ color: ColorParams,
181 ) -> crate::Result<(VideoMeta, FrameStream)> {193 ) -> crate::Result<(VideoMeta, FrameStream)> {
182 let path = path.as_ref().to_path_buf();194 let path = path.as_ref().to_path_buf();
183 let (meta, demuxer) = Demuxer::open(&path)?;195 let (meta, demuxer) = Demuxer::open(&path)?;
@@ -228,7 +240,7 @@ impl DecodeSession {
228 return;240 return;
229 }241 }
230 eprintln!("decode backend: hardware (VA-API plugin)");242 eprintln!("decode backend: hardware (VA-API plugin)");
231- if run_hw(hw, &tx, start_frame, end_frame, &worker_cancel) {243+ if run_hw(hw, &tx, start_frame, end_frame, &color, &worker_cancel) {
232 return;244 return;
233 }245 }
234 // A driver that opens but cannot decode a single frame is246 // A driver that opens but cannot decode a single frame is
@@ -242,7 +254,7 @@ impl DecodeSession {
242 return;254 return;
243 }255 }
244 eprintln!("decode backend: software (rusty_h264)");256 eprintln!("decode backend: software (rusty_h264)");
245- run(demuxer, tx, start_frame, end_frame, &worker_cancel)257+ run(demuxer, tx, start_frame, end_frame, &color, &worker_cancel)
246 })?;258 })?;
247 Ok((259 Ok((
248 meta,260 meta,
@@ -277,6 +289,7 @@ fn run_hw(
277 tx: &SyncSender<Frame>,289 tx: &SyncSender<Frame>,
278 start_frame: u32,290 start_frame: u32,
279 end_frame: u32,291 end_frame: u32,
292+ color: &ColorParams,
280 cancel: &AtomicBool,293 cancel: &AtomicBool,
281 ) -> bool {294 ) -> bool {
282 let mut index = start_frame;295 let mut index = start_frame;
@@ -290,7 +303,7 @@ fn run_hw(
290 index,303 index,
291 width,304 width,
292 height,305 height,
293- bgra: i420_to_bgra(y, u, v, width as usize, height as usize),306+ bgra: i420_to_bgra_with(color, y, u, v, width as usize, height as usize),
294 };307 };
295 index += 1;308 index += 1;
296 if tx.send(frame).is_err() {309 if tx.send(frame).is_err() {
@@ -335,8 +348,13 @@ mod tests {
335 /// regression fails in ten seconds instead of hanging the suite forever.348 /// regression fails in ten seconds instead of hanging the suite forever.
336 #[test]349 #[test]
337 fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {350 fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {
338- let (_meta, stream) =351+ let (_meta, stream) = DecodeSession::open_worker(
339- DecodeSession::open_worker(&asset("test_baseline.mp4"), 0, u32::MAX).expect("open");352+ &asset("test_baseline.mp4"),
353+ 0,
354+ u32::MAX,
355+ ColorParams::default(),
356+ )
357+ .expect("open");
340 // Nothing is ever received: two frames fill the channel and the next358 // Nothing is ever received: two frames fill the channel and the next
341 // send parks the decode thread, exactly as a refused project load does.359 // send parks the decode thread, exactly as a refused project load does.
342 thread::sleep(Duration::from_millis(500));360 thread::sleep(Duration::from_millis(500));
@@ -359,6 +377,7 @@ fn run(
359 tx: SyncSender<Frame>,377 tx: SyncSender<Frame>,
360 start_frame: u32,378 start_frame: u32,
361 end_frame: u32,379 end_frame: u32,
380+ color: &ColorParams,
362 cancel: &AtomicBool,381 cancel: &AtomicBool,
363 ) {382 ) {
364 let mut decoder = Decoder::new();383 let mut decoder = Decoder::new();
@@ -398,7 +417,7 @@ fn run(
398 index: index as u32,417 index: index as u32,
399 width: yuv.width as u32,418 width: yuv.width as u32,
400 height: yuv.height as u32,419 height: yuv.height as u32,
401- bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height),420+ bgra: i420_to_bgra_with(color, &yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height),
402 };421 };
403 index += 1;422 index += 1;
404 if tx.send(frame).is_err() {423 if tx.send(frame).is_err() {
crates/engine/src/export.rsmodified+25 -0
@@ -264,6 +264,13 @@ fn run(
264 }264 }
265 None => None,265 None => None,
266 };266 };
267+ // What this span is graded by -- the same answer playback's decoder
268+ // carries, so the export is the picture that was watched. `None` for a
269+ // gap and for an ungraded clip, and that is the path where not a byte
270+ // is touched. Scratch outside the frame loop: it is refilled per frame
271+ // and its allocation survives the whole span.
272+ let grade = project.composite_color_at(span.start).copied();
273+ let mut graded = (Vec::new(), Vec::new(), Vec::new());
267 for _ in 0..span.len {274 for _ in 0..span.len {
268 cancelled(shared)?;275 cancelled(shared)?;
269 let picture = match &mut pictures {276 let picture = match &mut pictures {
@@ -273,6 +280,24 @@ fn run(
273 let Some((y, u, v, width, height)) = picture else {280 let Some((y, u, v, width, height)) = picture else {
274 break; // source ran out early; the clip list outlives the file281 break; // source ran out early; the clip list outlives the file
275 };282 };
283+ // The planes are borrowed from the decoder (and `Black::picture`
284+ // hands the same slice as both u and v), so a grade cannot be
285+ // applied in place: it goes onto a copy, which the encoder then
286+ // reads instead.
287+ let (y, u, v) = match grade.filter(|p| !p.is_identity()) {
288+ Some(params) => {
289+ let (gy, gu, gv) = &mut graded;
290+ gy.clear();
291+ gy.extend_from_slice(y);
292+ gu.clear();
293+ gu.extend_from_slice(u);
294+ gv.clear();
295+ gv.extend_from_slice(v);
296+ crate::color::apply_yuv(&params, gy, gu, gv);
297+ (&gy[..], &gu[..], &gv[..])
298+ }
299+ None => (y, u, v),
300+ };
276 if let Some(au) = encoder.encode(y, u, v, width, height)? {301 if let Some(au) = encoder.encode(y, u, v, width, height)? {
277 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;302 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;
278 }303 }
crates/engine/src/playback.rsmodified+43 -3
@@ -21,6 +21,7 @@ use std::time::Duration;
21 use crate::ao::AoSession;21 use crate::ao::AoSession;
22 use crate::audio::{AudioChunk, AudioSession};22 use crate::audio::{AudioChunk, AudioSession};
23 use crate::clock::{ClockSource, PlaybackClock};23 use crate::clock::{ClockSource, PlaybackClock};
24+use crate::color::ColorParams;
24 use crate::decode::{DecodeSession, Frame, Worker};25 use crate::decode::{DecodeSession, Frame, Worker};
25 use crate::demux::{Demuxer, VideoMeta};26 use crate::demux::{Demuxer, VideoMeta};
26 use crate::project::{Clip, Lane, LaneKind, Project, Source, Span};27 use crate::project::{Clip, Lane, LaneKind, Project, Source, Span};
@@ -138,7 +139,11 @@ impl PlaybackSession {
138 }139 }
139 // `open_worker` rather than `open` purely for the worker handle: the140 // `open_worker` rather than `open` purely for the worker handle: the
140 // field has to exist from the start for the first seek to use it.141 // field has to exist from the start for the first seek to use it.
141- let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?;142+ // Ungraded: a file just opened has one clip per lane and nothing has
143+ // graded it yet. Every later span is opened by `start_span`, which asks
144+ // the project.
145+ let (meta, stream) =
146+ DecodeSession::open_worker(&path, 0, u32::MAX, ColorParams::default())?;
142 // A file is opened on its first audio stream, like `Project::single`147 // A file is opened on its first audio stream, like `Project::single`
143 // names it: nothing has picked one yet.148 // names it: nothing has picked one yet.
144 let (audio, audio_disabled) = open_audio(&path, 0);149 let (audio, audio_disabled) = open_audio(&path, 0);
@@ -194,8 +199,12 @@ impl PlaybackSession {
194 // locals drop in reverse declaration order -- a bare worker would join199 // locals drop in reverse declaration order -- a bare worker would join
195 // its decode thread while the receiver next to it was still holding200 // its decode thread while the receiver next to it was still holding
196 // that thread parked in `send`, which is a hang (see [`FrameStream`]).201 // that thread parked in `send`, which is a hang (see [`FrameStream`]).
197- let (meta, stream) = DecodeSession::open_worker(&first.path, 0, u32::MAX)202+ // Ungraded, and superseded before a frame of it is shown: the `seek` at
198- .map_err(|e| format!("source {}: {e}", first.path.display()))?;203+ // the end of this function reopens the playhead's span through
204+ // `start_span`, which is where a saved grade reaches the picture.
205+ let (meta, stream) =
206+ DecodeSession::open_worker(&first.path, 0, u32::MAX, ColorParams::default())
207+ .map_err(|e| format!("source {}: {e}", first.path.display()))?;
199 let first_audio = AudioSession::probe(&first.path, first.audio_stream)?;208 let first_audio = AudioSession::probe(&first.path, first.audio_stream)?;
200 209
201 let mut counts = vec![meta.frame_count];210 let mut counts = vec![meta.frame_count];
@@ -383,10 +392,17 @@ impl PlaybackSession {
383 /// disconnected receiver carries the session on to the next span.392 /// disconnected receiver carries the session on to the next span.
384 fn start_span(&mut self, span: Span) {393 fn start_span(&mut self, span: Span) {
385 let opened = match span.from {394 let opened = match span.from {
395+ // The grade is the composite's at this frame -- the same clip the
396+ // span itself came from -- and it is constant across the span, so
397+ // the worker carries it and every frame it converts wears it.
386 Some((source, in_frame)) => DecodeSession::open_worker(398 Some((source, in_frame)) => DecodeSession::open_worker(
387 &self.project.sources()[source].path,399 &self.project.sources()[source].path,
388 in_frame,400 in_frame,
389 in_frame + span.len,401 in_frame + span.len,
402+ self.project
403+ .composite_color_at(span.start)
404+ .copied()
405+ .unwrap_or_default(),
390 )406 )
391 .map(|(_, stream)| stream)407 .map(|(_, stream)| stream)
392 .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)),408 .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)),
@@ -493,6 +509,30 @@ impl PlaybackSession {
493 self.edit(|p| p.lift(lane, idx))509 self.edit(|p| p.lift(lane, idx))
494 }510 }
495 511
512+ /// The clip the picture is coming from at `timeline_secs`: the lane it sits
513+ /// on and its index there, by the same topmost-lane-wins rule the decoder
514+ /// follows. `None` over a gap and past the end. What a card that grades
515+ /// "this clip" opens on when nothing has been clicked.
516+ pub fn video_clip_at(&self, timeline_secs: f64) -> Option<(Lane, usize)> {
517+ self.project
518+ .composite_clip_at(secs_to_frame(timeline_secs, self.meta.frame_rate))
519+ }
520+
521+ /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
522+ /// as it was shot -- what a colour card reads when it opens.
523+ pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
524+ self.project.color_of(lane, idx)
525+ }
526+
527+ /// Grades that clip, or takes the grade off with `None`. One undo step like
528+ /// every other edit, and it reseeks like one too -- which is what puts the
529+ /// new grade on the frame that is already on screen, paused or playing,
530+ /// without the caller having to nudge the playhead itself. `false` for an
531+ /// index that is not there and for a value that is not finite.
532+ pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
533+ self.edit(|p| p.set_color(lane, idx, params))
534+ }
535+
496 /// The clip at `idx` -- what a caller copies. It is a pair of source frame536 /// The clip at `idx` -- what a caller copies. It is a pair of source frame
497 /// numbers and nothing else, so a copy stays valid after the clip it came537 /// numbers and nothing else, so a copy stays valid after the clip it came
498 /// from is deleted. `None` past the end.538 /// from is deleted. `None` past the end.
crates/engine/src/project.rsmodified+31 -5
@@ -757,11 +757,7 @@ impl Project {
757 if timeline_frame >= total {757 if timeline_frame >= total {
758 return None;758 return None;
759 }759 }
760- let video: Vec<Lane> = self760+ let video = self.video_lanes();
761- .lanes()
762- .into_iter()
763- .filter(|l| l.kind == LaneKind::Video)
764- .collect();
765 // The last covering lane is the winner; only the lanes above it can761 // The last covering lane is the winner; only the lanes above it can
766 // interrupt what it shows.762 // interrupt what it shows.
767 let winner = video763 let winner = video
@@ -794,6 +790,36 @@ impl Project {
794 })790 })
795 }791 }
796 792
793+ /// The video lanes in display order, topmost last -- the order the composite
794+ /// rule counts in.
795+ fn video_lanes(&self) -> Vec<Lane> {
796+ self.lanes()
797+ .into_iter()
798+ .filter(|l| l.kind == LaneKind::Video)
799+ .collect()
800+ }
801+
802+ /// *Which* clip the composite shows at `timeline_frame`, named: the winner
803+ /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
804+ /// index on that lane. `None` over a gap and past the end. What a front-end
805+ /// asks to act on "the clip on screen" without re-deriving the rule.
806+ pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
807+ let video = self.video_lanes();
808+ let winner = video
809+ .iter()
810+ .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
811+ Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
812+ }
813+
814+ /// How the composite is graded at `timeline_frame`, so the picture playback
815+ /// converts and the one an export encodes are graded from one answer.
816+ /// `None` over a gap (black is black) and for a clip nobody has graded,
817+ /// which is the byte-identical path everywhere.
818+ pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
819+ let (lane, idx) = self.composite_clip_at(timeline_frame)?;
820+ self.color_of(lane, idx)
821+ }
822+
797 /// [`spans_from`](Project::spans_from) over the composite: every stretch the823 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
798 /// viewer sees from `timeline_frame` to the end, in order. What an export824 /// viewer sees from `timeline_frame` to the end, in order. What an export
799 /// encodes and what playback walks at a clip boundary.825 /// encodes and what playback walks at a clip boundary.
crates/engine/tests/color.rsadded+183 -0
@@ -0,0 +1,183 @@
1+//! A per-clip colour grade, end to end: what the renderer shows and what the
2+//! export writes have to be the same picture, and a clip nobody graded has to
3+//! come out of both untouched.
4+//!
5+//! `test_baseline.mp4` is colour bars (mean channel spread 249 of 255), so
6+//! saturation 0 is not a subtle claim: every pixel of a graded span is grey to
7+//! within the converter's own rounding, and every pixel outside it is not.
8+//!
9+//! ```text
10+//! cargo test -p engine --release --test color -- --nocapture --test-threads=1
11+//! ```
12+
13+use std::path::{Path, PathBuf};
14+use std::thread::sleep;
15+use std::time::{Duration, Instant};
16+
17+use engine::color::ColorParams;
18+use engine::export::ExportSettings;
19+use engine::project::Lane;
20+use engine::{DecodeSession, ExportHandle, PlaybackSession};
21+
22+const FPS: f64 = 30.0;
23+/// Where the first clip ends and the ungraded one begins.
24+const CUT: u32 = 30;
25+
26+fn asset(name: &str) -> PathBuf {
27+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
28+ .join("../../assets")
29+ .join(name)
30+}
31+
32+/// Silent, like every other suite that plays a real file: the grade is a
33+/// picture setting and nothing here listens.
34+fn open(path: &Path) -> PlaybackSession {
35+ let session = PlaybackSession::open(path).expect("open");
36+ session.set_gain(0.0);
37+ session
38+}
39+
40+/// Two clips on `V1`, the first of them drained of all colour.
41+fn graded() -> PlaybackSession {
42+ let mut session = open(&asset("test_baseline.mp4"));
43+ assert!(session.cut_at(f64::from(CUT) / FPS), "cut at frame 30");
44+ assert!(
45+ session.set_color(
46+ Lane::V1,
47+ 0,
48+ Some(ColorParams {
49+ saturation: 0.0,
50+ ..Default::default()
51+ })
52+ ),
53+ "grade the first clip"
54+ );
55+ session
56+}
57+
58+/// How far a BGRA frame is from grey: the mean spread between its channels,
59+/// which is 0 for a greyscale picture and ~250 for these colour bars.
60+fn spread(bgra: &[u8]) -> f64 {
61+ let total: u64 = bgra
62+ .chunks_exact(4)
63+ .map(|px| u64::from(px[..3].iter().max().unwrap() - px[..3].iter().min().unwrap()))
64+ .sum();
65+ total as f64 / (bgra.len() / 4) as f64
66+}
67+
68+/// The next frame off a freshly seeked channel.
69+fn next_frame(session: &mut PlaybackSession, what: &str) -> engine::Frame {
70+ let deadline = Instant::now() + Duration::from_secs(10);
71+ loop {
72+ if let Some(frame) = session.try_frame() {
73+ return frame;
74+ }
75+ assert!(Instant::now() < deadline, "no frame after {what}");
76+ sleep(Duration::from_millis(4));
77+ }
78+}
79+
80+fn seek_and_show(session: &mut PlaybackSession, frame: u32) -> Vec<u8> {
81+ session.seek(f64::from(frame) / FPS);
82+ let shown = next_frame(session, "a seek");
83+ assert_eq!(shown.index, frame, "the seek landed elsewhere");
84+ shown.bgra
85+}
86+
87+/// The render half: the grade reaches the picture, and it stops at the clip's
88+/// own edge rather than colouring the whole timeline.
89+#[test]
90+fn a_graded_clip_renders_grey_and_the_next_one_does_not() {
91+ let mut session = graded();
92+ for frame in [0, CUT - 1] {
93+ let inside = spread(&seek_and_show(&mut session, frame));
94+ assert!(
95+ inside <= 2.0,
96+ "frame {frame} is graded and not grey: {inside}"
97+ );
98+ }
99+ for frame in [CUT, CUT + 15] {
100+ let outside = spread(&seek_and_show(&mut session, frame));
101+ assert!(
102+ outside > 100.0,
103+ "frame {frame} is outside the graded clip and lost its colour: {outside}"
104+ );
105+ }
106+}
107+
108+/// Live: a grade set while the session is up repaints what is on screen. The
109+/// engine reseeks on the edit, so the very next frame is the graded one -- no
110+/// scrub, no reopen by the caller.
111+#[test]
112+fn setting_a_grade_repaints_the_frame_that_is_already_up() {
113+ let mut session = open(&asset("test_baseline.mp4"));
114+ let before = spread(&seek_and_show(&mut session, 10));
115+ assert!(before > 100.0, "the fixture is not colour bars: {before}");
116+
117+ assert!(session.set_color(
118+ Lane::V1,
119+ 0,
120+ Some(ColorParams {
121+ saturation: 0.0,
122+ ..Default::default()
123+ })
124+ ));
125+ let after = spread(&next_frame(&mut session, "a grade").bgra);
126+ assert!(after <= 2.0, "the frame on screen kept its colour: {after}");
127+
128+ // And taking it off puts the colour back, on the same terms.
129+ assert!(session.set_color(Lane::V1, 0, None));
130+ let back = spread(&next_frame(&mut session, "an ungrade").bgra);
131+ assert!(back > 100.0, "ungrading left the picture grey: {back}");
132+}
133+
134+fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
135+ let started = Instant::now();
136+ while !handle.is_finished() {
137+ assert!(
138+ started.elapsed() < limit,
139+ "export did not finish in {limit:?}"
140+ );
141+ sleep(Duration::from_millis(20));
142+ }
143+ handle.result().expect("a finished export has an outcome")
144+}
145+
146+/// The export half, decoded back off disk: the same picture the renderer
147+/// showed, graded span for graded span. Software encoder, so it needs nothing
148+/// installed -- the same pin `tests/export.rs`'s default suite uses.
149+#[test]
150+fn an_exported_grade_is_the_one_that_was_watched() {
151+ unsafe {
152+ std::env::set_var("VE_SW", "1");
153+ std::env::set_var("VE_SW_ENC", "1");
154+ }
155+ let mut session = graded();
156+ session.pause();
157+ let out = std::env::temp_dir().join(format!("ve_color_{}.mp4", std::process::id()));
158+ let _ = std::fs::remove_file(&out);
159+ let handle = session.export_to_with(&out, &ExportSettings::default());
160+ wait(&handle, Duration::from_secs(180)).expect("export");
161+
162+ let (_, frames) = DecodeSession::open(&out).expect("decode the export");
163+ let mut seen = 0;
164+ for frame in frames {
165+ let spread = spread(&frame.bgra);
166+ if frame.index < CUT {
167+ assert!(
168+ spread <= 4.0,
169+ "exported frame {} is inside the graded clip and kept its colour: {spread}",
170+ frame.index
171+ );
172+ } else {
173+ assert!(
174+ spread > 100.0,
175+ "exported frame {} is outside the graded clip and lost its colour: {spread}",
176+ frame.index
177+ );
178+ }
179+ seen += 1;
180+ }
181+ assert!(seen > CUT, "the export is shorter than the graded clip");
182+ let _ = std::fs::remove_file(&out);
183+}