forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-a4e03161e173cd524'

Browse files at this commit

cd9f0dfbf7444bda0cb0ee87110e4acc70248e7eAhmet Kaan GümüşParent: a2ebaac19e294a

14 changed files +1256 -121

crates/app/src/keymap.rsmodified+25 -4
@@ -48,6 +48,8 @@ pub enum ActionId {
4848 Delete,
4949 Lift,
5050 Color,
51+ Fit,
52+ Resolution,
5153 Undo,
5254 AddVideoLane,
5355 AddAudioLane,
@@ -61,7 +63,7 @@ pub enum ActionId {
6163 impl ActionId {
6264 /// Display order everywhere -- the editor lists them in it and
6365 /// [`Keymap::defaults`] binds them in it.
64- pub const ALL: [ActionId; 18] = [
66+ pub const ALL: [ActionId; 20] = [
6567 ActionId::Play,
6668 ActionId::Export,
6769 ActionId::Save,
@@ -72,6 +74,8 @@ impl ActionId {
7274 ActionId::Delete,
7375 ActionId::Lift,
7476 ActionId::Color,
77+ ActionId::Fit,
78+ ActionId::Resolution,
7579 ActionId::Undo,
7680 ActionId::AddVideoLane,
7781 ActionId::AddAudioLane,
@@ -95,6 +99,8 @@ impl ActionId {
9599 ActionId::Delete => "Delete",
96100 ActionId::Lift => "Lift (leave a gap)",
97101 ActionId::Color => "Colour…",
102+ ActionId::Fit => "Fit policy: fit → fill → stretch → centre",
103+ ActionId::Resolution => "Project resolution: source → 2160p → 1080p → 720p → 480p",
98104 ActionId::Undo => "Undo",
99105 ActionId::AddVideoLane => "Add a video track",
100106 ActionId::AddAudioLane => "Add an audio track",
@@ -120,6 +126,8 @@ impl ActionId {
120126 ActionId::Delete => "delete",
121127 ActionId::Lift => "lift",
122128 ActionId::Color => "color",
129+ ActionId::Fit => "fit",
130+ ActionId::Resolution => "resolution",
123131 ActionId::Undo => "undo",
124132 ActionId::AddVideoLane => "add-video-lane",
125133 ActionId::AddAudioLane => "add-audio-lane",
@@ -145,7 +153,11 @@ impl ActionId {
145153 | ActionId::Paste
146154 | ActionId::Delete
147155 | ActionId::Lift
148- | ActionId::Color => Category::Clips,
156+ | ActionId::Color
157+ | ActionId::Fit => Category::Clips,
158+ // The project's own picture size is not a clip's business, and not
159+ // a file operation either: it is what the viewer is looking at.
160+ ActionId::Resolution => Category::View,
149161 ActionId::Cut
150162 | ActionId::Regroup
151163 | ActionId::Undo
@@ -379,6 +391,13 @@ impl Keymap {
379391 // k: free, next to nothing that edits, and one press like the
380392 // rest of the clip keys.
381393 b(ActionId::Color, "k", false),
394+ // The fit policy is a clip key like the grade beside it: "p" for
395+ // policy, free, and one press like the rest of them. The project
396+ // resolution is not a clip key and takes a ctrl chord, next to
397+ // nothing that edits and out of the way of a stray press --
398+ // it changes what every clip is composed onto.
399+ b(ActionId::Fit, "p", false),
400+ b(ActionId::Resolution, "r", true),
382401 b(ActionId::Undo, "z", false),
383402 b(ActionId::Undo, "z", true),
384403 // The unshifted initials of what they add. Both were free --
@@ -621,7 +640,7 @@ mod tests {
621640 #[test]
622641 fn every_default_stroke_reaches_its_action() {
623642 let k = Keymap::defaults();
624- assert_eq!(k.entries().len(), 20);
643+ assert_eq!(k.entries().len(), 22);
625644 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
626645 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
627646 assert_eq!(k.lookup("s", true), Some(ActionId::Save));
@@ -633,6 +652,8 @@ mod tests {
633652 assert_eq!(k.lookup("delete", false), Some(ActionId::Delete));
634653 assert_eq!(k.lookup("l", false), Some(ActionId::Lift));
635654 assert_eq!(k.lookup("k", false), Some(ActionId::Color));
655+ assert_eq!(k.lookup("p", false), Some(ActionId::Fit));
656+ assert_eq!(k.lookup("r", true), Some(ActionId::Resolution));
636657 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));
637658 assert_eq!(k.lookup("z", true), Some(ActionId::Undo));
638659 // The track keys are the bare letters; the ctrl ones stay copy/paste.
@@ -773,7 +794,7 @@ mod tests {
773794 );
774795 // The label is the editor's column, and never the file's word for it.
775796 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
776- assert_eq!(ActionId::ALL.len(), 18);
797+ assert_eq!(ActionId::ALL.len(), 20);
777798 }
778799
779800 #[test]
crates/app/src/main.rsmodified+140 -6
@@ -14,6 +14,7 @@ use engine::color::ColorParams;
1414 use engine::eq::{Band, BandKind, EqParams};
1515 use engine::export::{ExportSettings, Format};
1616 use engine::project::{Lane, LaneKind, Source};
17+use engine::scale::FitPolicy;
1718 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
1819 use gpui::{
1920 AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent,
@@ -221,16 +222,22 @@ struct ContextMenu {
221222 /// action a stroke already reaches -- the menu is a second way *to* the actions
222223 /// and never a second version of them -- so both the label and the hint come
223224 /// out of the keymap registry and the two can never disagree.
224-const MENU_ITEMS: [ActionId; 7] = [
225+const MENU_ITEMS: [ActionId; 8] = [
225226 ActionId::Cut,
226227 ActionId::Delete,
227228 ActionId::Lift,
228229 ActionId::Regroup,
229230 ActionId::Equalizer,
230231 ActionId::Color,
232+ ActionId::Fit,
231233 ActionId::ToggleMute,
232234 ];
233235
236+/// The project resolutions [`Player::cycle_resolution`] offers, largest first.
237+/// A short list of the sizes people name; the media's own is cycled in beside
238+/// them, which is what makes the trip round come back to where it started.
239+const RESOLUTIONS: [(u32, u32); 4] = [(3840, 2160), (1920, 1080), (1280, 720), (854, 480)];
240+
234241 /// How far a band may be pushed either way, in dB. The engine clamps nothing
235242 /// here -- it will filter whatever it is given -- so this is a UI decision:
236243 /// past about this a peaking band stops sounding like tone and starts sounding
@@ -497,6 +504,8 @@ impl Player {
497504 ActionId::Delete => self.delete_selected(cx),
498505 ActionId::Lift => self.lift_selected(cx),
499506 ActionId::Color => self.open_color(cx),
507+ ActionId::Fit => self.cycle_fit(cx),
508+ ActionId::Resolution => self.cycle_resolution(cx),
500509 ActionId::Undo => self.undo(cx),
501510 ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx),
502511 ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx),
@@ -510,6 +519,64 @@ impl Player {
510519 }
511520 }
512521
522+ /// Cycles the fit policy of the clip the picture is coming from -- the
523+ /// clicked one when it is a video clip, else the composite's own, exactly as
524+ /// the colour card picks its target. A whole card for one four-valued
525+ /// setting would be a card to close; a stroke that cycles it and says what
526+ /// it landed on is the same setting with nothing to dismiss.
527+ ///
528+ /// Only means anything when the clip is not the project's size -- a clip
529+ /// that already fills the canvas looks the same under all four -- so the
530+ /// notice says the size it is placing, not just the word.
531+ fn cycle_fit(&mut self, cx: &mut Context<Self>) {
532+ if self.exporting().is_some() {
533+ return;
534+ }
535+ let Some(session) = &mut self.session else {
536+ self.notice = Some("no timeline to fit — open a file first".into());
537+ cx.notify();
538+ return;
539+ };
540+ let target = self
541+ .selected
542+ .filter(|(lane, _)| lane.kind == LaneKind::Video)
543+ .or_else(|| session.video_clip_at(session.now()));
544+ let Some((lane, idx)) = target else {
545+ self.notice = Some("no clip under the playhead to fit".into());
546+ cx.notify();
547+ return;
548+ };
549+ let next = next_fit(session.fit_of(lane, idx));
550+ if session.set_fit(lane, idx, next) {
551+ let (w, h) = session.resolution();
552+ self.notice = Some(format!("FIT POLICY: {} on {w}x{h}", fit_label(next)).into());
553+ self.reset_after_reseek();
554+ }
555+ cx.notify();
556+ }
557+
558+ /// Cycles the *project's* resolution through [`RESOLUTIONS`], starting from
559+ /// the media's own -- the one size that must stay reachable, since a project
560+ /// moved off it has no other way back (the resolution is not an undo step).
561+ /// Every clip is recomposed onto it, so this is what makes "the project
562+ /// resolution and the media's are different things" a thing a user can see.
563+ fn cycle_resolution(&mut self, cx: &mut Context<Self>) {
564+ if self.exporting().is_some() {
565+ return;
566+ }
567+ let Some(session) = &mut self.session else {
568+ self.notice = Some("no timeline to resize — open a file first".into());
569+ cx.notify();
570+ return;
571+ };
572+ let (width, height) = next_resolution(session.resolution(), session.native_resolution());
573+ if session.set_resolution(width, height) {
574+ self.notice = Some(format!("PROJECT: {width}x{height}").into());
575+ self.reset_after_reseek();
576+ }
577+ cx.notify();
578+ }
579+
513580 /// Opens the colour card on the clip a grade would go on: the clip that was
514581 /// clicked when it is a video one, and otherwise the clip the picture is
515582 /// coming from -- the one the engine's own compositing rule picks, which is
@@ -2546,14 +2613,18 @@ impl Player {
25462613 )
25472614 // What the picked row really writes. `moov` last is the
25482615 // muxer's own shape -- an mp4 is playable only once it
2549- // is finished.
2616+ // is finished. The project's resolution is on the same
2617+ // line because it *is* what the file comes out at,
2618+ // whatever size the media on the timeline are: this is
2619+ // the one place the number is shown, and ctrl+r is what
2620+ // changes it.
25502621 .child(
25512622 div()
25522623 .flex_none()
25532624 .px(px(6.))
25542625 .text_size(px(11.))
25552626 .text_color(rgb(INK_DIM))
2556- .child(format_line(self.format)),
2627+ .child(export_line(self.format, self.session.as_ref())),
25572628 )
25582629 .child(
25592630 div()
@@ -3500,7 +3571,8 @@ fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool
35003571 ActionId::Equalizer => lane.kind == LaneKind::Audio,
35013572 // A grade is a picture setting and an audio clip has no picture: the
35023573 // item is there on every clip, and dimmed where it would mean nothing.
3503- ActionId::Color => lane.kind == LaneKind::Video,
3574+ // A fit policy is a picture setting for the same reason.
3575+ ActionId::Color | ActionId::Fit => lane.kind == LaneKind::Video,
35043576 // Splits this clip only from inside it: at either edge there is nothing
35053577 // to split off (project.rs `splittable`).
35063578 ActionId::Cut => clip.start < playhead && playhead < clip.end(),
@@ -3829,6 +3901,63 @@ fn band_mut(params: &mut ColorParams, band: usize) -> &mut f32 {
38293901
38303902 /// The line under the rows: what the picked format really writes, in the terms
38313903 /// a file is judged by afterwards.
3904+/// The next policy round the cycle, in the order the action's label reads.
3905+fn next_fit(fit: FitPolicy) -> FitPolicy {
3906+ match fit {
3907+ FitPolicy::Fit => FitPolicy::Fill,
3908+ FitPolicy::Fill => FitPolicy::Stretch,
3909+ FitPolicy::Stretch => FitPolicy::Center,
3910+ FitPolicy::Center => FitPolicy::Fit,
3911+ }
3912+}
3913+
3914+/// What a person calls one, said as what it does to the picture.
3915+fn fit_label(fit: FitPolicy) -> &'static str {
3916+ match fit {
3917+ FitPolicy::Fit => "fit (whole picture, bars)",
3918+ FitPolicy::Fill => "fill (cropped, no bars)",
3919+ FitPolicy::Stretch => "stretch (aspect broken)",
3920+ FitPolicy::Center => "centre (1:1, no resample)",
3921+ }
3922+}
3923+
3924+/// The next project resolution after `current`, over [`RESOLUTIONS`] with the
3925+/// media's own size cycled in at its place by size -- so the trip round always
3926+/// comes back to the media, whatever odd shape it is, and a project already at a
3927+/// listed size does not see it twice.
3928+fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) {
3929+ let mut sizes: Vec<(u32, u32)> = RESOLUTIONS.to_vec();
3930+ if !sizes.contains(&native) {
3931+ // By area, descending, like the list itself: the cycle then reads as one
3932+ // ladder rather than a list with a stray rung at the end.
3933+ let at = sizes
3934+ .iter()
3935+ .position(|&(w, h)| {
3936+ u64::from(w) * u64::from(h) < u64::from(native.0) * u64::from(native.1)
3937+ })
3938+ .unwrap_or(sizes.len());
3939+ sizes.insert(at, native);
3940+ }
3941+ let at = sizes.iter().position(|&s| s == current);
3942+ // A project at a size nobody listed (a hand-edited file) joins the cycle at
3943+ // the top rather than being stuck.
3944+ sizes[at.map_or(0, |at| (at + 1) % sizes.len())]
3945+}
3946+
3947+/// [`format_line`] plus the project's resolution, which is what a video export
3948+/// is written at however many sizes the media on the timeline are. Only for the
3949+/// formats that carry a picture -- a WAV has no resolution to state.
3950+fn export_line(format: Format, session: Option<&PlaybackSession>) -> String {
3951+ let line = format_line(format);
3952+ match session.filter(|_| format.has_video()) {
3953+ Some(session) => {
3954+ let (w, h) = session.resolution();
3955+ format!("{line} · project {w}x{h}")
3956+ }
3957+ None => line.to_string(),
3958+ }
3959+}
3960+
38323961 fn format_line(format: Format) -> &'static str {
38333962 match format {
38343963 Format::Mp4 => "H.264 · MP4 · moov at end",
@@ -4269,6 +4398,7 @@ mod tests {
42694398 };
42704399 use super::{file_name, library_rows};
42714400 use engine::PlaybackSession;
4401+ use engine::scale::FitPolicy;
42724402 use gpui::{Bounds, Pixels, point, px, size};
42734403 use std::collections::HashMap;
42744404 use std::path::{Path, PathBuf};
@@ -4291,6 +4421,7 @@ mod tests {
42914421 link: None,
42924422 eq: None,
42934423 color: None,
4424+ fit: FitPolicy::default(),
42944425 }
42954426 }
42964427
@@ -4482,6 +4613,7 @@ mod tests {
44824613 link: None,
44834614 eq: None,
44844615 color: None,
4616+ fit: FitPolicy::default(),
44854617 };
44864618 assert_eq!(clip.end(), 90);
44874619 // Cut splits from inside only: neither edge has anything to split off.
@@ -4546,11 +4678,13 @@ mod tests {
45464678 // Silent like the engine suite: this opens the real device.
45474679 session.set_gain(0.0);
45484680 assert_eq!(session.sources().len(), 1);
4681+ // 640x360 would join now (the project canvas places it); this file is
4682+ // also silent, and a silent file cannot join a timeline with sound.
45494683 let refusal = session
45504684 .import(&asset("test_mismatch.mp4"))
4551- .expect_err("640x360 must not join a 1280x720 timeline")
4685+ .expect_err("a silent file must not join a timeline with audio")
45524686 .to_string();
4553- assert!(refusal.contains("640"), "refusal must name it: {refusal}");
4687+ assert!(refusal.contains("audio"), "refusal must name it: {refusal}");
45544688 assert_eq!(session.sources().len(), 1, "a refusal added a row");
45554689 // An accepted one does add a row, and it reads as the whole file: 4 s
45564690 // at 30 fps, exactly what was appended.
crates/engine/src/decode.rsmodified+110 -19
@@ -10,9 +10,10 @@ use std::thread;
1010 use rusty_h264::Decoder;
1111
1212 use crate::color::ColorParams;
13-use crate::convert::i420_to_bgra_with;
13+use crate::convert::{i420_to_bgra, i420_to_bgra_with};
1414 use crate::demux::{Codec, Demuxer, VideoMeta};
1515 use crate::hw::HwSession;
16+use crate::scale::Composer;
1617
1718 /// One decoded picture, ready to hand to a renderer.
1819 pub struct Frame {
@@ -122,8 +123,15 @@ impl DecodeSession {
122123 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
123124 // Ungraded: the public API opens a *file*, and a colour grade belongs to
124125 // 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())?;
126+ let (meta, stream) = Self::open_worker(
127+ path,
128+ start_frame,
129+ end_frame,
130+ ColorParams::default(),
131+ // No project, no canvas: the file-level API hands back the
132+ // pictures the file holds, at the size it holds them.
133+ Composer::passthrough(),
134+ )?;
127135 // The public API hands out the flag alone, so the worker is detached and
128136 // the receiver goes to the caller: nothing here joins anything.
129137 Ok((meta, stream.frames, stream.worker.detach()))
@@ -185,11 +193,17 @@ impl DecodeSession {
185193 ///
186194 /// In-process only: a caller that outlives its workers has to be able to
187195 /// join them at exit.
196+ ///
197+ /// `canvas` is the project's own resolution and this clip's fit policy: the
198+ /// frames come out at *that* size, whatever the file's is. A
199+ /// [`Composer::passthrough`] (or one already the source's size) leaves every
200+ /// picture exactly as it was decoded.
188201 pub(crate) fn open_worker(
189202 path: impl AsRef<Path>,
190203 start_frame: u32,
191204 end_frame: u32,
192205 color: ColorParams,
206+ canvas: Composer,
193207 ) -> crate::Result<(VideoMeta, FrameStream)> {
194208 let path = path.as_ref().to_path_buf();
195209 let (meta, demuxer) = Demuxer::open(&path)?;
@@ -231,6 +245,7 @@ impl DecodeSession {
231245 if worker_cancel.load(Ordering::Relaxed) {
232246 return;
233247 }
248+ let mut render = Render::new(color, canvas);
234249 // The plugin has to be opened on the thread that uses it: its
235250 // VA-API state is not `Send`-safe across a later hand-off.
236251 if let Some(hw) = open_hw(&path, start_frame) {
@@ -240,7 +255,7 @@ impl DecodeSession {
240255 return;
241256 }
242257 eprintln!("decode backend: hardware (VA-API plugin)");
243- if run_hw(hw, &tx, start_frame, end_frame, &color, &worker_cancel) {
258+ if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) {
244259 return;
245260 }
246261 // A driver that opens but cannot decode a single frame is
@@ -254,7 +269,14 @@ impl DecodeSession {
254269 return;
255270 }
256271 eprintln!("decode backend: software (rusty_h264)");
257- run(demuxer, tx, start_frame, end_frame, &color, &worker_cancel)
272+ run(
273+ demuxer,
274+ tx,
275+ start_frame,
276+ end_frame,
277+ &mut render,
278+ &worker_cancel,
279+ )
258280 })?;
259281 Ok((
260282 meta,
@@ -269,6 +291,77 @@ impl DecodeSession {
269291 }
270292 }
271293
294+/// One clip's pictures on their way to the renderer: graded, placed on the
295+/// project canvas, converted. Both decode loops go through it, so hardware and
296+/// software cannot show two different pictures.
297+///
298+/// The order is grade, then place (see [`Composer`]): a grade is the clip's own,
299+/// applied at the resolution it was shot at, and the letterbox bars around it
300+/// are not the clip -- a brightness grade must not lift them off black.
301+///
302+/// A project at the media's own resolution never reaches any of that: it takes
303+/// the fused graded conversion, the one path this engine had before there was a
304+/// project resolution, byte for byte and allocation for allocation.
305+struct Render {
306+ color: ColorParams,
307+ canvas: Composer,
308+ /// The graded copy of the source planes, refilled per frame and kept across
309+ /// the worker's whole range. Empty unless the clip is both graded *and*
310+ /// placed, which is the only case that needs it.
311+ graded: (Vec<u8>, Vec<u8>, Vec<u8>),
312+}
313+
314+impl Render {
315+ fn new(color: ColorParams, canvas: Composer) -> Self {
316+ Self {
317+ color,
318+ canvas,
319+ graded: (Vec::new(), Vec::new(), Vec::new()),
320+ }
321+ }
322+
323+ fn frame(
324+ &mut self,
325+ index: u32,
326+ y: &[u8],
327+ u: &[u8],
328+ v: &[u8],
329+ width: u32,
330+ height: u32,
331+ ) -> Frame {
332+ if self.canvas.is_passthrough(width, height) {
333+ return Frame {
334+ index,
335+ width,
336+ height,
337+ bgra: i420_to_bgra_with(&self.color, y, u, v, width as usize, height as usize),
338+ };
339+ }
340+ let (gy, gu, gv) = &mut self.graded;
341+ let (y, u, v) = if self.color.is_identity() {
342+ (y, u, v)
343+ } else {
344+ gy.clear();
345+ gy.extend_from_slice(y);
346+ gu.clear();
347+ gu.extend_from_slice(u);
348+ gv.clear();
349+ gv.extend_from_slice(v);
350+ crate::color::apply_yuv(&self.color, gy, gu, gv);
351+ (&gy[..], &gu[..], &gv[..])
352+ };
353+ let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height);
354+ Frame {
355+ index,
356+ width,
357+ height,
358+ // Ungraded on purpose: the grade is already in the pixels above and
359+ // the canvas around them must stay the black it was filled with.
360+ bgra: i420_to_bgra(y, u, v, width as usize, height as usize),
361+ }
362+ }
363+}
364+
272365 /// `None` when the software path must be used: forced by `VE_SW=1`, or the
273366 /// plugin is absent/broken/unable to open this particular file.
274367 fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> {
@@ -289,7 +382,7 @@ fn run_hw(
289382 tx: &SyncSender<Frame>,
290383 start_frame: u32,
291384 end_frame: u32,
292- color: &ColorParams,
385+ render: &mut Render,
293386 cancel: &AtomicBool,
294387 ) -> bool {
295388 let mut index = start_frame;
@@ -299,12 +392,7 @@ fn run_hw(
299392 }
300393 match hw.next_frame() {
301394 Ok(Some((y, u, v, width, height))) => {
302- let frame = Frame {
303- index,
304- width,
305- height,
306- bgra: i420_to_bgra_with(color, y, u, v, width as usize, height as usize),
307- };
395+ let frame = render.frame(index, y, u, v, width, height);
308396 index += 1;
309397 if tx.send(frame).is_err() {
310398 return true; // consumer went away
@@ -353,6 +441,7 @@ mod tests {
353441 0,
354442 u32::MAX,
355443 ColorParams::default(),
444+ Composer::passthrough(),
356445 )
357446 .expect("open");
358447 // Nothing is ever received: two frames fill the channel and the next
@@ -377,7 +466,7 @@ fn run(
377466 tx: SyncSender<Frame>,
378467 start_frame: u32,
379468 end_frame: u32,
380- color: &ColorParams,
469+ render: &mut Render,
381470 cancel: &AtomicBool,
382471 ) {
383472 let mut decoder = Decoder::new();
@@ -413,12 +502,14 @@ fn run(
413502 index += 1;
414503 continue;
415504 }
416- let frame = Frame {
417- index: index as u32,
418- width: yuv.width as u32,
419- height: yuv.height as u32,
420- bgra: i420_to_bgra_with(color, &yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height),
421- };
505+ let frame = render.frame(
506+ index as u32,
507+ &yuv.y,
508+ &yuv.u,
509+ &yuv.v,
510+ yuv.width as u32,
511+ yuv.height as u32,
512+ );
422513 index += 1;
423514 if tx.send(frame).is_err() {
424515 break; // consumer went away
crates/engine/src/edith.rsmodified+160 -50
@@ -1,18 +1,25 @@
11 //! The project file: a line of text per thing, and nothing else.
22 //!
33 //! ```text
4-//! edith 6
4+//! edith 7
55 //! playhead 90
6+//! resolution 1920 1080
67 //! source 0 test_av.mp4
78 //! source 1 /elsewhere/test_av2.mp4
89 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
910 //! color 0.1:1.2:0.9:-0.3
10-//! video 1 0 0 120 0 0 0 0
11-//! audio 1 0 0 120 0 0 0 -
12-//! video 2 120 0 120 1 - - -
11+//! video 1 0 0 120 0 0 0 0 fit
12+//! audio 1 0 0 120 0 0 0 - fit
13+//! video 2 120 0 120 1 - - - fill
1314 //! audio 2
1415 //! ```
1516 //!
17+//! The `resolution` line is the **project's** picture size, which is a
18+//! different thing from any source's: media of other sizes are placed on it.
19+//! It belongs once, beside the playhead, and a file without one (every dialect
20+//! before v7) means "source 0's own picture", which is what such a project
21+//! always was.
22+//!
1623 //! A source line is `source <audio stream> <path>`: which of the file's audio
1724 //! tracks that source plays, in the file order
1825 //! [`crate::AudioSession::probe_streams`] numbers, and then the path -- the
@@ -32,20 +39,25 @@
3239 //! -- the first colour line is color 0 -- printed and refused by the same rules.
3340 //!
3441 //! A lane line is `<kind> <lane> <start> <in> <out> <source> <link> <eq>
35-//! <color>`: which lane the clip is on -- its kind and its 1-based number among
36-//! the lanes of that kind, the [`crate::project::Lane::label`] a header column
37-//! shows -- then where the clip sits on the timeline, the half-open source range
38-//! it plays, the file it plays from, its group id, the eq line it plays through
39-//! and the colour line it is graded by (`-` for none of them). Timeline
40-//! placement is explicit, so a *gap* is simply a stretch no line covers -- there
41-//! is nothing to write for one, and nothing that can disagree about its length.
42+//! <color> <fit>`: which lane the clip is on -- its kind and its 1-based number
43+//! among the lanes of that kind, the [`crate::project::Lane::label`] a header
44+//! column shows -- then where the clip sits on the timeline, the half-open
45+//! source range it plays, the file it plays from, its group id, the eq line it
46+//! plays through, the colour line it is graded by (`-` for none of those three)
47+//! and how it meets a project canvas of another shape, spelled `fit`, `fill`,
48+//! `stretch` or `center` ([`crate::scale::FitPolicy`]). Timeline placement is
49+//! explicit, so a *gap* is simply a stretch no line covers -- there is nothing
50+//! to write for one, and nothing that can disagree about its length.
4251 //!
4352 //! A lane is declared by the clips on it, in the order the lanes are displayed
4453 //! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
4554 //! is the only way an empty lane could still be there on the way back. A lane
4655 //! number may not skip one of its kind.
4756 //!
48-//! **Version 5** was this without the colour lines and without the clip's colour
57+//! **Version 6** was this without the `resolution` line and without the clip's
58+//! fit field -- such a project is the size of its first source and letterboxes
59+//! nothing, because nothing on it could differ in size. **Version 5** was that
60+//! without the colour lines and without the clip's colour
4961 //! field. **Version 4** was that without the eq lines and without the clip's eq
5062 //! field. **Version 3** was that without the lane number, and held one video
5163 //! lane and one audio lane, no more. **Version 2** wrote `source <path>` as
@@ -54,7 +66,7 @@
5466 //! <in> <out> <source>`. All five still load -- a v1 file's clips are laid out
5567 //! cumulatively and copied onto both lanes as one group each, which is exactly
5668 //! what a v1 timeline meant, and an older file simply equalizes and grades
57-//! nothing -- and saving any of them writes v6. An older reader refuses a newer
69+//! nothing -- and saving any of them writes v7. An older reader refuses a newer
5870 //! file by name.
5971 //!
6072 //! Text because an edit list is a few integers and a path, and a path is
@@ -84,10 +96,12 @@ use std::path::{Path, PathBuf};
8496 use crate::color::ColorParams;
8597 use crate::eq::{Band, BandKind, EqParams};
8698 use crate::project::{Clip, Lane, LaneKind, Source};
99+use crate::scale::FitPolicy;
87100
88101 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
89102 /// docs for what those dialects looked like.
90-const MAGIC: &[u8] = b"edith 6";
103+const MAGIC: &[u8] = b"edith 7";
104+const MAGIC_V6: &[u8] = b"edith 6";
91105 const MAGIC_V5: &[u8] = b"edith 5";
92106 const MAGIC_V4: &[u8] = b"edith 4";
93107 const MAGIC_V3: &[u8] = b"edith 3";
@@ -111,6 +125,9 @@ pub struct Document {
111125 /// The colour table [`Clip::color`] indexes into, in file order. Empty for
112126 /// every dialect before v6.
113127 pub color: Vec<ColorParams>,
128+ /// The project's own picture size. `None` for every dialect before v7 and
129+ /// for a v7 file that leaves it out, which both mean "source 0's picture".
130+ pub resolution: Option<(u32, u32)>,
114131 pub playhead: u32,
115132 }
116133
@@ -122,6 +139,7 @@ pub fn save(
122139 lanes: &[(LaneKind, Vec<Clip>)],
123140 eq: &[EqParams],
124141 color: &[ColorParams],
142+ resolution: (u32, u32),
125143 playhead: u32,
126144 ) -> crate::Result<()> {
127145 let dir = project_dir(path);
@@ -134,7 +152,7 @@ pub fn save(
134152 // the second one puts the name itself there.
135153 let result = std::fs::File::create(&part)
136154 .and_then(|mut f| {
137- f.write_all(&emit(&dir, sources, lanes, eq, color, playhead))?;
155+ f.write_all(&emit(&dir, sources, lanes, eq, color, resolution, playhead))?;
138156 f.sync_all()
139157 })
140158 .and_then(|()| std::fs::rename(&part, path))
@@ -170,12 +188,14 @@ fn emit(
170188 lanes: &[(LaneKind, Vec<Clip>)],
171189 eq: &[EqParams],
172190 color: &[ColorParams],
191+ resolution: (u32, u32),
173192 playhead: u32,
174193 ) -> Vec<u8> {
175194 let mut out = Vec::new();
176195 out.extend_from_slice(MAGIC);
177196 out.push(b'\n');
178197 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());
198+ out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes());
179199 for s in sources {
180200 out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes());
181201 escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);
@@ -236,8 +256,12 @@ fn emit(
236256 let color = c.color.map_or("-".to_string(), |e| e.to_string());
237257 out.extend_from_slice(
238258 format!(
239- "{keyword} {ord} {} {} {} {} {link} {eq} {color}\n",
240- c.start, c.in_frame, c.out_frame, c.source
259+ "{keyword} {ord} {} {} {} {} {link} {eq} {color} {}\n",
260+ c.start,
261+ c.in_frame,
262+ c.out_frame,
263+ c.source,
264+ fit_name(c.fit)
241265 )
242266 .as_bytes(),
243267 );
@@ -256,8 +280,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
256280 // The dialects that wrote a source line without its stream field. Reading
257281 // one is the whole of what "an old project still opens" means here.
258282 let streamless = v1 || first == MAGIC_V2;
259- // The one that carries colour grades...
260- let v6 = first == MAGIC;
283+ // The one that carries a project resolution and per-clip fit policies...
284+ let v7 = first == MAGIC;
285+ // ...the ones that carry colour grades...
286+ let v6 = v7 || first == MAGIC_V6;
261287 // ...the ones that carry equalizer settings...
262288 let v5 = v6 || first == MAGIC_V5;
263289 // ...and the ones that number their lanes. Every older one held two.
@@ -282,6 +308,9 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
282308 // Nothing before v5 equalizes anything, and nothing before v6 grades.
283309 eq: Vec::new(),
284310 color: Vec::new(),
311+ // Nothing before v7 has a resolution of its own: source 0's picture is
312+ // what those projects were, and `None` is how the loader is told so.
313+ resolution: None,
285314 playhead: 0,
286315 };
287316 let mut playhead_seen = false;
@@ -304,6 +333,19 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
304333 doc.playhead = number(rest, n)?;
305334 playhead_seen = true;
306335 }
336+ b"resolution" if v7 => {
337+ if doc.resolution.is_some() || !doc.sources.is_empty() {
338+ return Err(
339+ format!("line {n}: resolution belongs once, before the sources").into(),
340+ );
341+ }
342+ let f = fields(rest, 2, "resolution", n)?;
343+ let (width, height) = (number(f[0], n)?, number(f[1], n)?);
344+ if width == 0 || height == 0 {
345+ return Err(format!("line {n}: {width}x{height} is not a picture").into());
346+ }
347+ doc.resolution = Some((width, height));
348+ }
307349 b"source" => {
308350 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
309351 return Err(format!("line {n}: source after a clip").into());
@@ -384,6 +426,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
384426 link: Some(doc.lanes[0].1.len() as u32),
385427 eq: None,
386428 color: None,
429+ fit: FitPolicy::default(),
387430 },
388431 &doc,
389432 n,
@@ -413,9 +456,9 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
413456 if numbered && rest.is_empty() {
414457 continue;
415458 }
416- // v6 grew the colour field and v5 the eq one; every older
417- // dialect ends at the link.
418- let want = 5 + usize::from(v5) + usize::from(v6);
459+ // v7 grew the fit field, v6 the colour one and v5 the eq one;
460+ // every older dialect ends at the link.
461+ let want = 5 + usize::from(v5) + usize::from(v6) + usize::from(v7);
419462 let f = fields(rest, want, "clip", n)?;
420463 let clip = check(
421464 Clip {
@@ -429,6 +472,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
429472 },
430473 eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?,
431474 color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?,
475+ fit: fit_policy(f.get(7).copied(), n)?,
432476 },
433477 &doc,
434478 n,
@@ -544,6 +588,37 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
544588 Ok(clip)
545589 }
546590
591+/// How a fit policy is spelled in the file. One word each, so a clip line stays
592+/// readable, and the same word the parser takes back.
593+fn fit_name(fit: FitPolicy) -> &'static str {
594+ match fit {
595+ FitPolicy::Fit => "fit",
596+ FitPolicy::Fill => "fill",
597+ FitPolicy::Stretch => "stretch",
598+ FitPolicy::Center => "center",
599+ }
600+}
601+
602+/// A clip's `<fit>` field. A dialect that has no such field at all means the
603+/// default -- those projects held one resolution, so no clip of theirs was ever
604+/// placed on anything.
605+fn fit_policy(field: Option<&[u8]>, line: usize) -> crate::Result<FitPolicy> {
606+ let Some(field) = field else {
607+ return Ok(FitPolicy::default());
608+ };
609+ match field {
610+ b"fit" => Ok(FitPolicy::Fit),
611+ b"fill" => Ok(FitPolicy::Fill),
612+ b"stretch" => Ok(FitPolicy::Stretch),
613+ b"center" => Ok(FitPolicy::Center),
614+ other => Err(format!(
615+ "line {line}: {:?} is not a fit policy",
616+ String::from_utf8_lossy(other)
617+ )
618+ .into()),
619+ }
620+}
621+
547622 /// A clip's `<eq>` or `<color>` field: `-` (or a dialect that has no such field
548623 /// at all), or a line of a table that is already declared. Refused by the name
549624 /// of what it points at, so the message reads as the file does.
@@ -667,6 +742,7 @@ mod tests {
667742 link,
668743 eq: None,
669744 color: None,
745+ fit: FitPolicy::default(),
670746 }
671747 }
672748
@@ -678,7 +754,7 @@ mod tests {
678754 lanes: &[(LaneKind, Vec<Clip>)],
679755 playhead: u32,
680756 ) -> Vec<u8> {
681- emit(dir, sources, lanes, &[], &[], playhead)
757+ emit(dir, sources, lanes, &[], &[], (1280, 720), playhead)
682758 }
683759
684760 /// Two sources, one under the project's own directory and one not, a clip
@@ -716,8 +792,10 @@ mod tests {
716792 let bytes = flat(&dir, &sources, &lanes, 12);
717793 assert_eq!(
718794 String::from_utf8_lossy(&bytes),
719- "edith 6\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
720- video 1 0 0 30 0 0 - -\nvideo 1 30 10 20 1 1 - -\naudio 1 0 0 30 0 0 - -\n",
795+ "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
796+ source 2 /elsewhere/b.mp4\n\
797+ video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\
798+ audio 1 0 0 30 0 0 - - fit\n",
721799 "the file under the project directory is written relative to it, \
722800 each with the audio stream it plays"
723801 );
@@ -751,8 +829,9 @@ mod tests {
751829 let bytes = flat(&dir, &sources, &lanes, 7);
752830 assert_eq!(
753831 String::from_utf8_lossy(&bytes),
754- "edith 6\nplayhead 7\nsource 0 a.mp4\n\
755- video 1 0 0 30 0 4 - -\naudio 1\nvideo 2 40 0 10 0 - - -\naudio 2 0 0 30 0 4 - -\n",
832+ "edith 7\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
833+ video 1 0 0 30 0 4 - - fit\naudio 1\n\
834+ video 2 40 0 10 0 - - - fit\naudio 2 0 0 30 0 4 - - fit\n",
756835 "an empty lane is a line of its own; everything else is its clips"
757836 );
758837 let back = parse(&bytes, &dir).expect("parse");
@@ -858,15 +937,15 @@ mod tests {
858937 },
859938 ],
860939 );
861- let bytes = emit(&dir, &sources, &lanes, &eq, &[], 0);
940+ let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
862941 assert_eq!(
863942 String::from_utf8_lossy(&bytes),
864- "edith 6\nplayhead 0\nsource 0 a.mp4\n\
943+ "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
865944 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
866945 eq 16777215.0:-0.1:3.918315e-39:hs\n\
867946 eq\n\
868- video 1 0 0 30 0 0 0 -\nvideo 1 30 10 20 0 - 1 -\n\
869- audio 1 0 0 30 0 0 0 -\naudio 1 30 0 10 0 - 2 -\n",
947+ video 1 0 0 30 0 0 0 - fit\nvideo 1 30 10 20 0 - 1 - fit\n\
948+ audio 1 0 0 30 0 0 0 - fit\naudio 1 30 0 10 0 - 2 - fit\n",
870949 "the table comes before the clips, and a clip names a line of it"
871950 );
872951
@@ -893,7 +972,15 @@ mod tests {
893972 }
894973 assert_eq!(back.eq.len(), 3, "the empty cascade is an entry of its own");
895974 assert_eq!(
896- emit(&dir, &back.sources, &back.lanes, &back.eq, &back.color, 0),
975+ emit(
976+ &dir,
977+ &back.sources,
978+ &back.lanes,
979+ &back.eq,
980+ &back.color,
981+ (1280, 720),
982+ 0
983+ ),
897984 bytes
898985 );
899986 }
@@ -928,33 +1015,37 @@ mod tests {
9281015 vec![
9291016 Clip {
9301017 color: Some(0),
1018+ fit: FitPolicy::default(),
9311019 ..clip(0, 0, 30, 0, Some(0))
9321020 },
9331021 Clip {
9341022 color: Some(1),
1023+ fit: FitPolicy::default(),
9351024 ..clip(30, 10, 20, 0, None)
9361025 },
9371026 ],
9381027 vec![
9391028 Clip {
9401029 color: Some(0),
1030+ fit: FitPolicy::default(),
9411031 ..clip(0, 0, 30, 0, Some(0))
9421032 },
9431033 Clip {
9441034 color: Some(2),
1035+ fit: FitPolicy::default(),
9451036 ..clip(30, 0, 10, 0, None)
9461037 },
9471038 ],
9481039 );
949- let bytes = emit(&dir, &sources, &lanes, &[], &color, 0);
1040+ let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
9501041 assert_eq!(
9511042 String::from_utf8_lossy(&bytes),
952- "edith 6\nplayhead 0\nsource 0 a.mp4\n\
1043+ "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
9531044 color 0.1:1.2:0.9:-0.3\n\
9541045 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
9551046 color 0.0:1.0:1.0:0.0\n\
956- video 1 0 0 30 0 0 - 0\nvideo 1 30 10 20 0 - - 1\n\
957- audio 1 0 0 30 0 0 - 0\naudio 1 30 0 10 0 - - 2\n",
1047+ video 1 0 0 30 0 0 - 0 fit\nvideo 1 30 10 20 0 - - 1 fit\n\
1048+ audio 1 0 0 30 0 0 - 0 fit\naudio 1 30 0 10 0 - - 2 fit\n",
9581049 "the table comes before the clips, and a clip names a line of it"
9591050 );
9601051
@@ -979,7 +1070,15 @@ mod tests {
9791070 }
9801071 assert_eq!(back.color.len(), 3);
9811072 assert_eq!(
982- emit(&dir, &back.sources, &back.lanes, &back.eq, &back.color, 0),
1073+ emit(
1074+ &dir,
1075+ &back.sources,
1076+ &back.lanes,
1077+ &back.eq,
1078+ &back.color,
1079+ (1280, 720),
1080+ 0
1081+ ),
9831082 bytes
9841083 );
9851084 }
@@ -1003,10 +1102,12 @@ mod tests {
10031102 &old.lanes,
10041103 &old.eq,
10051104 &old.color,
1105+ (1280, 720),
10061106 old.playhead
10071107 )),
1008- "edith 6\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\
1009- video 1 0 0 30 0 0 0 -\naudio 1 0 0 30 0 0 - -\n"
1108+ "edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1109+ eq 80.0:-3.0:0.707:ls\n\
1110+ video 1 0 0 30 0 0 0 - fit\naudio 1 0 0 30 0 0 - - fit\n"
10101111 );
10111112 }
10121113
@@ -1015,6 +1116,8 @@ mod tests {
10151116 fn a_malformed_colour_names_its_line() {
10161117 let dir = PathBuf::from("/proj");
10171118 let head = "edith 6\nsource 0 a.mp4\n";
1119+ // v6, deliberately: the colour grammar is the same one v7 inherits, and
1120+ // a v6 clip line is one field shorter.
10181121 for (file, want) in [
10191122 (
10201123 format!("{head}color 0.0:1.0:1.0\nvideo 1 0 0 5 0 - - 0\n"),
@@ -1138,8 +1241,10 @@ mod tests {
11381241 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
11391242 assert_eq!(
11401243 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
1141- "edith 6\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
1142- video 1 0 0 30 0 0 - -\nvideo 1 30 10 20 1 1 - -\naudio 1 0 0 30 0 0 - -\n"
1244+ "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1245+ source 2 /elsewhere/b.mp4\n\
1246+ video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\
1247+ audio 1 0 0 30 0 0 - - fit\n"
11431248 );
11441249 // An empty lane's line is still the whole of that lane, eq or no eq.
11451250 let empty = parse(
@@ -1189,8 +1294,10 @@ mod tests {
11891294 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
11901295 assert_eq!(
11911296 String::from_utf8_lossy(&v5),
1192- "edith 6\nplayhead 12\nsource 0 a.mp4\nsource 0 /elsewhere/b.mp4\n\
1193- video 1 0 0 30 0 0 - -\nvideo 1 30 10 20 1 1 - -\naudio 1 0 0 30 0 0 - -\n",
1297+ "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1298+ source 0 /elsewhere/b.mp4\n\
1299+ video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\
1300+ audio 1 0 0 30 0 0 - - fit\n",
11941301 "a re-saved v2 project differs only by its version, the lane \
11951302 numbers, the streams it always meant and an equalizer it has none of"
11961303 );
@@ -1216,9 +1323,10 @@ mod tests {
12161323 "one take per clip, on both lanes"
12171324 );
12181325 assert_eq!(back.playhead, 5);
1219- // Saved again it is v5, and that round-trips to the same document.
1326+ // Saved again it is the current version, which round-trips to the
1327+ // same document.
12201328 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1221- assert!(v5.starts_with(b"edith 6\n"));
1329+ assert!(v5.starts_with(b"edith 7\n"));
12221330 let again = parse(&v5, &dir).expect("v5 parses");
12231331 assert_eq!(again.lanes, back.lanes);
12241332 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
@@ -1313,13 +1421,15 @@ mod tests {
13131421 &two(one.to_vec(), one.to_vec()),
13141422 &[],
13151423 &[],
1424+ (1280, 720),
13161425 0,
13171426 )
13181427 .expect("save");
13191428 let bytes = std::fs::read(&path).expect("read back");
13201429 assert_eq!(
13211430 String::from_utf8_lossy(&bytes),
1322- "edith 6\nplayhead 0\nsource 1 a.mp4\nvideo 1 0 0 30 0 - - -\naudio 1 0 0 30 0 - - -\n"
1431+ "edith 7\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
1432+ video 1 0 0 30 0 - - - fit\naudio 1 0 0 30 0 - - - fit\n"
13231433 );
13241434 // Loading rejoins the *given* directory, so the file is reached by the
13251435 // way the project was opened -- the same file, through the link, still
@@ -1350,9 +1460,9 @@ mod tests {
13501460 );
13511461 assert_eq!(
13521462 bytes.iter().filter(|&&b| b == b'\n').count(),
1353- 5,
1463+ 6,
13541464 "the escaped newline must not become a line break: magic, playhead, \
1355- source, the clip, and the empty audio lane's own line"
1465+ resolution, source, the clip, and the empty audio lane's own line"
13561466 );
13571467 let back = parse(&bytes, &dir).expect("parse");
13581468 // The spaces in it are the reason the stream field leads rather than
@@ -1363,10 +1473,10 @@ mod tests {
13631473 #[test]
13641474 fn a_wrong_first_line_is_refused_by_name() {
13651475 let dir = PathBuf::from("/proj");
1366- let err = parse(b"edith 7\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
1476+ let err = parse(b"edith 8\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
13671477 .unwrap_err()
13681478 .to_string();
1369- assert_eq!(err, "line 1: unsupported version 7");
1479+ assert_eq!(err, "line 1: unsupported version 8");
13701480 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
13711481 assert_eq!(
13721482 parse(junk, &dir).unwrap_err().to_string(),
crates/engine/src/export.rsmodified+14 -0
@@ -32,6 +32,7 @@ use crate::demux::{Demuxer, VideoMeta};
3232 use crate::hw::{HwEncoder, HwSession};
3333 use crate::mux::{AudioParams, Mp4Muxer, VideoParams};
3434 use crate::project::Project;
35+use crate::scale::Composer;
3536
3637 /// Progress is reported in permille: an atomic integer the render loop can read
3738 /// without a lock, fine enough for any progress bar.
@@ -293,6 +294,16 @@ fn run(
293294 // and its allocation survives the whole span.
294295 let grade = project.composite_color_at(span.start).copied();
295296 let mut graded = (Vec::new(), Vec::new(), Vec::new());
297+ // ...and the canvas it is placed on, which is where a source of another
298+ // resolution becomes a picture at the project's. The same `Composer`
299+ // playback composes with, given the same policy, so an export is what
300+ // was watched down to the letterbox; a clip already the project's size
301+ // passes through it untouched.
302+ let mut canvas = Composer::new(
303+ meta.width,
304+ meta.height,
305+ project.composite_fit_at(span.start),
306+ );
296307 for _ in 0..span.len {
297308 cancelled(shared)?;
298309 let picture = match &mut pictures {
@@ -320,6 +331,9 @@ fn run(
320331 }
321332 None => (y, u, v),
322333 };
334+ // Grade first, place second: the grade is the clip's own pixels
335+ // and the bars around them are not the clip (see `scale::Composer`).
336+ let (y, u, v, width, height) = canvas.place(y, u, v, width, height);
323337 if let Some(au) = encoder.encode(y, u, v, width, height)? {
324338 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;
325339 }
crates/engine/src/playback.rsmodified+123 -21
@@ -26,6 +26,7 @@ use crate::decode::{DecodeSession, Frame, Worker};
2626 use crate::demux::{Demuxer, VideoMeta};
2727 use crate::eq::EqParams;
2828 use crate::project::{Clip, Lane, LaneKind, Project, Source, Span};
29+use crate::scale::{Composer, FitPolicy};
2930
3031 /// How long the feeder waits out a full ring. The ring holds a second, so this
3132 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.
@@ -84,7 +85,17 @@ impl Audio {
8485
8586 /// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`].
8687 pub struct PlaybackSession {
88+ /// The *timeline's* parameters, not any one file's: its frame rate and codec
89+ /// come from source 0 and are what every other source is held to, while
90+ /// `width`/`height` are the **project resolution** -- source 0's picture to
91+ /// begin with, and whatever [`PlaybackSession::set_resolution`] or a saved
92+ /// `resolution` line makes it after that. Every clip is composed onto it, so
93+ /// a file of another size is a placed picture rather than a refusal.
8794 meta: VideoMeta,
95+ /// Source 0's own picture, kept from the open: the project resolution
96+ /// starts here, and a caller offering sizes to pick from needs the media's
97+ /// own among them or a project moved off it could never come back.
98+ native: (u32, u32),
8899 frames: Receiver<Frame>,
89100 /// The current decode worker.
90101 worker: Worker,
@@ -143,8 +154,16 @@ impl PlaybackSession {
143154 // Ungraded: a file just opened has one clip per lane and nothing has
144155 // graded it yet. Every later span is opened by `start_span`, which asks
145156 // the project.
146- let (meta, stream) =
147- DecodeSession::open_worker(&path, 0, u32::MAX, ColorParams::default())?;
157+ // Passthrough: a freshly opened file *is* the project resolution, so
158+ // there is nothing to place it on. Every later span goes through
159+ // `start_span`, which builds the canvas from the project.
160+ let (meta, stream) = DecodeSession::open_worker(
161+ &path,
162+ 0,
163+ u32::MAX,
164+ ColorParams::default(),
165+ Composer::passthrough(),
166+ )?;
148167 // A file is opened on its first audio stream, like `Project::single`
149168 // names it: nothing has picked one yet.
150169 let (audio, audio_disabled) = open_audio(&path, 0);
@@ -158,6 +177,7 @@ impl PlaybackSession {
158177 let span = project.composite_span_at(0).expect("never empty");
159178 Ok(Self {
160179 meta,
180+ native: (meta.width, meta.height),
161181 frames: stream.frames,
162182 worker: stream.worker,
163183 retired: Vec::new(),
@@ -203,9 +223,22 @@ impl PlaybackSession {
203223 // Ungraded, and superseded before a frame of it is shown: the `seek` at
204224 // the end of this function reopens the playhead's span through
205225 // `start_span`, which is where a saved grade reaches the picture.
206- let (meta, stream) =
207- DecodeSession::open_worker(&first.path, 0, u32::MAX, ColorParams::default())
208- .map_err(|e| format!("source {}: {e}", first.path.display()))?;
226+ let (mut meta, stream) = DecodeSession::open_worker(
227+ &first.path,
228+ 0,
229+ u32::MAX,
230+ ColorParams::default(),
231+ Composer::passthrough(),
232+ )
233+ .map_err(|e| format!("source {}: {e}", first.path.display()))?;
234+ // The project's own resolution, which is source 0's picture unless the
235+ // file says otherwise -- every dialect before v7 had no way to say it,
236+ // and that default is exactly what those projects meant.
237+ let native = (meta.width, meta.height);
238+ if let Some((width, height)) = doc.resolution {
239+ meta.width = width;
240+ meta.height = height;
241+ }
209242 let first_audio = AudioSession::probe(&first.path, first.audio_stream)?;
210243
211244 let mut counts = vec![meta.frame_count];
@@ -266,6 +299,7 @@ impl PlaybackSession {
266299 let (audio, audio_disabled) = open_audio(&first.path, first.audio_stream);
267300 let mut session = Self {
268301 meta,
302+ native,
269303 frames: stream.frames,
270304 worker: stream.worker,
271305 retired: Vec::new(),
@@ -313,7 +347,15 @@ impl PlaybackSession {
313347 let (sources, lanes, eq, color) = self.project.without_orphan_sources();
314348 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
315349 .min(self.project.timeline_frames().saturating_sub(1));
316- crate::edith::save(path, &sources, &lanes, &eq, &color, playhead)
350+ crate::edith::save(
351+ path,
352+ &sources,
353+ &lanes,
354+ &eq,
355+ &color,
356+ (self.meta.width, self.meta.height),
357+ playhead,
358+ )
317359 }
318360
319361 /// The next decoded frame, its `index` rewritten from a source frame to a
@@ -404,6 +446,14 @@ impl PlaybackSession {
404446 .composite_color_at(span.start)
405447 .copied()
406448 .unwrap_or_default(),
449+ // ...and the canvas it is placed on: the project's resolution
450+ // and this clip's own fit policy, constant across the span for
451+ // the reason the grade is.
452+ Composer::new(
453+ self.meta.width,
454+ self.meta.height,
455+ self.project.composite_fit_at(span.start),
456+ ),
407457 )
408458 .map(|(_, stream)| stream)
409459 .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)),
@@ -555,6 +605,56 @@ impl PlaybackSession {
555605 self.edit(|p| p.set_color(lane, idx, params))
556606 }
557607
608+ /// The project's resolution: what every clip is composed onto, what the
609+ /// window is sized to and what an export writes -- *not* any one file's.
610+ /// It starts as source 0's picture, which is what a project meant before it
611+ /// could have a resolution of its own.
612+ pub fn resolution(&self) -> (u32, u32) {
613+ (self.meta.width, self.meta.height)
614+ }
615+
616+ /// Source 0's own picture size -- what the project resolution started as,
617+ /// and the one size a caller offering a list of them must not leave out.
618+ pub fn native_resolution(&self) -> (u32, u32) {
619+ self.native
620+ }
621+
622+ /// Sets it. Reseeks like an edit, so the frame on screen is recomposed at
623+ /// the new size at once, paused or playing. `false` for a size that is not a
624+ /// picture -- zero either way, or past 8K, which is where the per-frame
625+ /// buffers stop being a sane thing to allocate from a keystroke.
626+ ///
627+ /// ponytail: not an undo step. The project resolution is not in the lane
628+ /// snapshots [`Project::undo`] restores, so cycling it back is one more
629+ /// keypress rather than a `z`. Upgrade path is snapshotting it beside the
630+ /// lanes, which every existing snapshot site would then have to carry.
631+ pub fn set_resolution(&mut self, width: u32, height: u32) -> bool {
632+ const MAX: u32 = 7680;
633+ if width == 0 || height == 0 || width > MAX || height > MAX {
634+ return false;
635+ }
636+ if (width, height) == (self.meta.width, self.meta.height) {
637+ return false;
638+ }
639+ self.meta.width = width;
640+ self.meta.height = height;
641+ let now = self.now();
642+ self.seek(now);
643+ true
644+ }
645+
646+ /// How the clip at `idx` of `lane` meets a project canvas of another shape.
647+ pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
648+ self.project.fit_of(lane, idx)
649+ }
650+
651+ /// Sets that clip's fit policy. One undo step and a reseek, exactly like a
652+ /// grade: the picture on screen is recomposed through the new policy without
653+ /// the caller nudging the playhead. `false` for an index that is not there.
654+ pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
655+ self.edit(|p| p.set_fit(lane, idx, fit))
656+ }
657+
558658 /// The clip at `idx` -- what a caller copies. It is a pair of source frame
559659 /// numbers and nothing else, so a copy stays valid after the clip it came
560660 /// from is deleted. `None` past the end.
@@ -619,6 +719,7 @@ impl PlaybackSession {
619719 link: None,
620720 eq: None,
621721 color: None,
722+ fit: FitPolicy::default(),
622723 };
623724 // Which lane a source may land on is decided here and only here, so a
624725 // front-end never has to make the same call twice: a file with no
@@ -683,11 +784,11 @@ impl PlaybackSession {
683784 /// Appends the whole of `path` to the end of the timeline. One undo step,
684785 /// and the file becomes a source only if it is not one already.
685786 ///
686- /// Refused unless it matches the timeline exactly -- same dimensions, same
687- /// frame rate, same audio parameters or both silent -- because one timeline
688- /// this slice means one set of encoder/device parameters; the `Err` names
689- /// the property that disagrees, for a caller to show. Nothing is changed by
690- /// a refusal.
787+ /// Refused unless it can join the timeline -- same codec, same frame rate,
788+ /// same audio parameters or both silent; the `Err` names the property that
789+ /// disagrees, for a caller to show. Nothing is changed by a refusal. A
790+ /// *resolution* of its own is not a refusal: the clip is placed on the
791+ /// project canvas by its fit policy ([`PlaybackSession::set_fit`]).
691792 pub fn import(&mut self, path: &Path) -> crate::Result<()> {
692793 if crate::is_audio(path) {
693794 return self.import_audio(path);
@@ -745,6 +846,7 @@ impl PlaybackSession {
745846 link: None,
746847 eq: None,
747848 color: None,
849+ fit: FitPolicy::default(),
748850 },
749851 );
750852 // Same reason as a video import: the running audio worker's segment
@@ -989,9 +1091,16 @@ impl Drop for PlaybackSession {
9891091 }
9901092
9911093 /// Whether `path`, already demuxed to `meta`, may join a timeline whose
992-/// parameters are `timeline` and whose audio probes as `first`: same
993-/// dimensions, same frame rate, same audio parameters or both silent -- one
994-/// timeline this slice means one set of encoder/device parameters.
1094+/// parameters are `timeline` and whose audio probes as `first`: same codec,
1095+/// same frame rate, same audio parameters or both silent.
1096+///
1097+/// *Not* the same size any more. A project has its own resolution
1098+/// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its
1099+/// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a
1100+/// letterboxed clip rather than a refusal. The frame rate stays refused on
1101+/// purpose: mixing rates means resampling the *timeline*, which is a different
1102+/// problem from resampling a picture, and a refusal is the honest answer until
1103+/// it is solved.
9951104 ///
9961105 /// The `Err` names the property that disagrees, and those strings are what a
9971106 /// front-end shows verbatim; [`PlaybackSession::import`] and
@@ -1015,13 +1124,6 @@ fn matches_timeline(
10151124 )
10161125 .into());
10171126 }
1018- if (meta.width, meta.height) != (timeline.width, timeline.height) {
1019- return Err(format!(
1020- "{}x{} does not match the timeline's {}x{}",
1021- meta.width, meta.height, timeline.width, timeline.height
1022- )
1023- .into());
1024- }
10251127 // Container frame rates are computed from timescales, so never `==`.
10261128 if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 {
10271129 return Err(format!(
crates/engine/src/project.rsmodified+62 -0
@@ -66,6 +66,7 @@ use std::path::{Path, PathBuf};
6666
6767 use crate::color::ColorParams;
6868 use crate::eq::EqParams;
69+use crate::scale::FitPolicy;
6970
7071 /// A half-open `[in_frame, out_frame)` range of frames of source
7172 /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
@@ -95,6 +96,13 @@ pub struct Clip {
9596 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
9697 /// promises: `Copy`, append-only within a session, never dangling.
9798 pub color: Option<u16>,
99+ /// How this clip's picture meets a project canvas of another shape
100+ /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
101+ /// two above: it is one byte with no parameters, so there is nothing for a
102+ /// table to share, and a clip that is the project's own size never consults
103+ /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
104+ /// where the aspect does not agree.
105+ pub fit: FitPolicy,
98106 }
99107
100108 impl Clip {
@@ -270,6 +278,7 @@ impl Project {
270278 link: Some(0),
271279 eq: None,
272280 color: None,
281+ fit: FitPolicy::default(),
273282 };
274283 Self {
275284 // A file is opened on its first audio stream: nothing has picked
@@ -491,6 +500,7 @@ impl Project {
491500 link: Some(self.new_link()),
492501 eq: None,
493502 color: None,
503+ fit: FitPolicy::default(),
494504 };
495505 for data in &mut self.lanes {
496506 data.clips.push(clip);
@@ -650,6 +660,27 @@ impl Project {
650660 true
651661 }
652662
663+ /// How the clip at `idx` of `lane` meets a project canvas of another shape.
664+ /// [`FitPolicy::Fit`] for an index that is not there, which is the default
665+ /// every clip starts at anyway.
666+ pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
667+ self.lane(lane)
668+ .get(idx)
669+ .map_or(FitPolicy::default(), |c| c.fit)
670+ }
671+
672+ /// Sets it. One undo step like every other edit, and `false` (with no
673+ /// history) for an index that is not there. Unlike an eq or a grade there is
674+ /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
675+ pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
676+ if idx >= self.lane(lane).len() {
677+ return false;
678+ }
679+ self.snapshot();
680+ self.lane_mut(lane).expect("checked above")[idx].fit = fit;
681+ true
682+ }
683+
653684 /// Length of the timeline in frames: where the *last* lane runs out. A lane
654685 /// that ends early is a trailing gap in that lane, not a shorter timeline.
655686 pub fn timeline_frames(&self) -> u32 {
@@ -820,6 +851,14 @@ impl Project {
820851 self.color_of(lane, idx)
821852 }
822853
854+ /// How the composite meets the project canvas at `timeline_frame`, so the
855+ /// picture playback composes and the one an export encodes are placed from
856+ /// one answer. `Fit` over a gap, where black is already the canvas.
857+ pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
858+ self.composite_clip_at(timeline_frame)
859+ .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
860+ }
861+
823862 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
824863 /// viewer sees from `timeline_frame` to the end, in order. What an export
825864 /// encodes and what playback walks at a clip boundary.
@@ -1427,6 +1466,7 @@ mod tests {
14271466 link: None,
14281467 eq: None,
14291468 color: None,
1469+ fit: FitPolicy::default(),
14301470 }
14311471 }
14321472
@@ -1621,6 +1661,23 @@ mod tests {
16211661 assert_eq!(p.span_at(Lane::V1, 9), None);
16221662 }
16231663
1664+ /// The fit policy is one byte *in* the clip rather than an index into a
1665+ /// table like the eq and the grade: there is nothing for a table to share.
1666+ /// It costs the clip nothing at all -- the fields before it (a `usize`
1667+ /// source and two `Option<u16>`s) already left the struct padded to 40
1668+ /// bytes, and the byte landed in that padding. This is the assert that says
1669+ /// so: a clip that grew a word grew every undo snapshot and every clipboard
1670+ /// copy with it.
1671+ #[test]
1672+ fn a_fit_policy_costs_the_clip_no_word() {
1673+ assert_eq!(
1674+ std::mem::size_of::<Clip>(),
1675+ 40,
1676+ "Clip changed size: {} bytes",
1677+ std::mem::size_of::<Clip>()
1678+ );
1679+ }
1680+
16241681 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
16251682 /// anything in `three()` so it is recognisable wherever it lands.
16261683 const PASTED: Clip = Clip {
@@ -1631,6 +1688,7 @@ mod tests {
16311688 link: None,
16321689 eq: None,
16331690 color: None,
1691+ fit: FitPolicy::Fit,
16341692 };
16351693
16361694 #[test]
@@ -2392,6 +2450,7 @@ mod tests {
23922450 let graded = |i: u16| {
23932451 vec![Clip {
23942452 color: Some(i),
2453+ fit: FitPolicy::default(),
23952454 ..video[0]
23962455 }]
23972456 };
@@ -2452,6 +2511,7 @@ mod tests {
24522511 link: Some(link),
24532512 eq: None,
24542513 color: None,
2514+ fit: FitPolicy::default(),
24552515 };
24562516
24572517 // The door: named errors, one per cause.
@@ -2799,6 +2859,7 @@ mod tests {
27992859 link: Some(link),
28002860 eq: None,
28012861 color: None,
2862+ fit: FitPolicy::default(),
28022863 };
28032864 let lanes = vec![
28042865 LaneData {
@@ -2832,6 +2893,7 @@ mod tests {
28322893 link: Some(link),
28332894 eq: None,
28342895 color: None,
2896+ fit: FitPolicy::default(),
28352897 };
28362898 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
28372899 let kinds = [
crates/engine/src/scale.rsmodified+323 -0
@@ -330,6 +330,164 @@ pub fn compose_i420(
330330 }
331331 }
332332
333+/// One clip's pictures placed on the project canvas: the geometry, plus the
334+/// buffers it composes into so a frame costs no allocation.
335+///
336+/// This is the *one* definition of what a mixed-resolution timeline looks like:
337+/// playback ([`crate::decode`]) and export ([`crate::export`]) both hand their
338+/// decoded planes to [`place`](Composer::place), so what is watched and what is
339+/// written cannot drift apart.
340+///
341+/// **Order against the colour grade: grade first, place second.** A grade
342+/// belongs to the clip's own pixels -- it is graded at the resolution it was
343+/// shot at, which is also the cheaper end of a downscale -- and, decisively, the
344+/// letterbox bars are *not* the clip: a brightness grade that reached them would
345+/// lift the black frame around the picture. Callers therefore grade the source
346+/// planes and place the result; the bars stay exactly [`black_i420`].
347+///
348+/// A canvas of the picture's own size is a pass-through: [`place`](Composer::place)
349+/// hands the caller's own planes straight back, allocates nothing and touches no
350+/// byte, which is what keeps a project at its media's resolution the byte-for-byte
351+/// path it was before there was a project resolution at all.
352+///
353+/// [`place`]: Composer::place
354+pub struct Composer {
355+ width: u32,
356+ height: u32,
357+ policy: FitPolicy,
358+ /// The `src` rect of [`fit_rect`], gathered tightly packed. Only `Fill` and
359+ /// `Center` ever crop, so this stays empty for a letterboxed project.
360+ crop: (Vec<u8>, Vec<u8>, Vec<u8>),
361+ /// The crop resampled to the placement rect.
362+ scaled: (Vec<u8>, Vec<u8>, Vec<u8>),
363+ /// The canvas itself, refilled with black every frame -- a memset against a
364+ /// decode, and the only way a policy change cannot leave last frame's bars
365+ /// showing through.
366+ canvas: (Vec<u8>, Vec<u8>, Vec<u8>),
367+}
368+
369+impl Composer {
370+ pub fn new(width: u32, height: u32, policy: FitPolicy) -> Self {
371+ let empty = || (Vec::new(), Vec::new(), Vec::new());
372+ Self {
373+ width,
374+ height,
375+ policy,
376+ crop: empty(),
377+ scaled: empty(),
378+ canvas: empty(),
379+ }
380+ }
381+
382+ /// A composer that places nothing: every picture passes through at its own
383+ /// size. What the file-level decode API opens with, where there is no
384+ /// project and therefore no canvas.
385+ pub fn passthrough() -> Self {
386+ Self::new(0, 0, FitPolicy::Fit)
387+ }
388+
389+ /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this
390+ /// composer would hand it back untouched. What lets a caller keep a fused
391+ /// fast path (the graded conversion) for the common case.
392+ pub fn is_passthrough(&self, src_w: u32, src_h: u32) -> bool {
393+ self.width == 0 || self.height == 0 || (src_w, src_h) == (self.width, self.height)
394+ }
395+
396+ /// The picture as the project sees it: `(y, u, v, width, height)`, either the
397+ /// caller's own planes (pass-through) or the canvas with the fitted picture
398+ /// composed onto it. The dimensions come back because those two differ.
399+ ///
400+ /// Panics on a plane that is not exactly `src_w` x `src_h` (chroma at
401+ /// `(w + 1) / 2`), as [`scale_i420`] does and for its reason.
402+ pub fn place<'a>(
403+ &'a mut self,
404+ y: &'a [u8],
405+ u: &'a [u8],
406+ v: &'a [u8],
407+ src_w: u32,
408+ src_h: u32,
409+ ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) {
410+ if self.is_passthrough(src_w, src_h) {
411+ return (y, u, v, src_w, src_h);
412+ }
413+ let (dst, src) = fit_rect(src_w, src_h, self.width, self.height, self.policy);
414+ let (sw, sh) = (src_w as usize, src_h as usize);
415+
416+ // Crop first, so the scaler only ever sees a tightly packed plane. Fit
417+ // and Stretch never crop, which is the whole cost of the common case.
418+ let (src_y, src_u, src_v) = if (src.w, src.h) == (src_w, src_h) {
419+ (y, u, v)
420+ } else {
421+ crop_i420(&mut self.crop, y, u, v, sw, sh, src);
422+ (&self.crop.0[..], &self.crop.1[..], &self.crop.2[..])
423+ };
424+ // ...then resample it to the placement, unless it already is that size
425+ // (`Center` never resamples, and neither does an exact-fit upscale).
426+ let (cw, ch) = (src.w as usize, src.h as usize);
427+ let (dw, dh) = (dst.w as usize, dst.h as usize);
428+ let (pic_y, pic_u, pic_v) = if (cw, ch) == (dw, dh) {
429+ (src_y, src_u, src_v)
430+ } else {
431+ let (ccw, cch) = chroma_dims(dw, dh);
432+ let (sy, su, sv) = &mut self.scaled;
433+ sy.resize(dw * dh, 0);
434+ su.resize(ccw * cch, 0);
435+ sv.resize(ccw * cch, 0);
436+ scale_i420(src_y, src_u, src_v, cw, ch, sy, su, sv, dw, dh);
437+ (&sy[..], &su[..], &sv[..])
438+ };
439+
440+ let (w, h) = (self.width as usize, self.height as usize);
441+ let (canvas_cw, canvas_ch) = chroma_dims(w, h);
442+ let (ky, ku, kv) = &mut self.canvas;
443+ fill(ky, w * h, BLACK_Y);
444+ fill(ku, canvas_cw * canvas_ch, NEUTRAL_C);
445+ fill(kv, canvas_cw * canvas_ch, NEUTRAL_C);
446+ compose_i420(ky, ku, kv, w, h, pic_y, pic_u, pic_v, dst);
447+ (ky, ku, kv, self.width, self.height)
448+ }
449+}
450+
451+/// Resizes `plane` to `len` and sets every byte to `value` -- a canvas reused
452+/// across frames is refilled, not reallocated.
453+fn fill(plane: &mut Vec<u8>, len: usize, value: u8) {
454+ plane.clear();
455+ plane.resize(len, value);
456+}
457+
458+/// Gathers `rect` out of a tightly packed I420 frame into another tightly packed
459+/// one. `rect` comes from [`fit_rect`], so its offsets are even and the chroma
460+/// crop is exactly half of it.
461+fn crop_i420(
462+ out: &mut (Vec<u8>, Vec<u8>, Vec<u8>),
463+ y: &[u8],
464+ u: &[u8],
465+ v: &[u8],
466+ src_w: usize,
467+ src_h: usize,
468+ rect: Rect,
469+) {
470+ let (w, h) = (rect.w as usize, rect.h as usize);
471+ let (x, cy0) = (rect.x as usize, rect.y as usize);
472+ let (src_cw, _) = chroma_dims(src_w, src_h);
473+ let (cw, ch) = chroma_dims(w, h);
474+ let (oy, ou, ov) = out;
475+ oy.clear();
476+ ou.clear();
477+ ov.clear();
478+ for row in 0..h {
479+ oy.extend_from_slice(&y[(cy0 + row) * src_w + x..][..w]);
480+ }
481+ let (cx, cy0) = (x / 2, cy0 / 2);
482+ for row in 0..ch {
483+ let at = (cy0 + row) * src_cw + cx;
484+ ou.extend_from_slice(&u[at..][..cw]);
485+ ov.extend_from_slice(&v[at..][..cw]);
486+ }
487+ debug_assert_eq!(oy.len(), w * h);
488+ debug_assert_eq!(ou.len(), cw * ch);
489+}
490+
333491 #[cfg(test)]
334492 mod tests {
335493 use super::*;
@@ -714,6 +872,155 @@ mod tests {
714872 );
715873 }
716874
875+ /// The wiring invariant: a project at its media's own resolution hands the
876+ /// decoder's own slices back, not a copy that happens to be equal. Asserted
877+ /// on the pointer, because "identical bytes" is cheap and "no work at all"
878+ /// is what the common case is promised.
879+ #[test]
880+ fn a_canvas_of_the_source_size_is_a_pass_through() {
881+ let (w, h) = (64usize, 48usize);
882+ let src = gradient(w, h);
883+ for mut canvas in [
884+ Composer::new(w as u32, h as u32, FitPolicy::Fit),
885+ Composer::new(w as u32, h as u32, FitPolicy::Fill),
886+ Composer::new(w as u32, h as u32, FitPolicy::Center),
887+ Composer::passthrough(),
888+ ] {
889+ let (y, u, v, cw, ch) = canvas.place(&src.0, &src.1, &src.2, w as u32, h as u32);
890+ assert_eq!(y.as_ptr(), src.0.as_ptr(), "luma was copied");
891+ assert_eq!(u.as_ptr(), src.1.as_ptr());
892+ assert_eq!(v.as_ptr(), src.2.as_ptr());
893+ assert_eq!((cw, ch), (w as u32, h as u32));
894+ }
895+ }
896+
897+ /// 4:3 media on a 16:9 project: the picture lands where `fit_rect` says and
898+ /// the pillarbox columns are limited-range black, exactly -- a bar that is
899+ /// merely dark is a bar the grade reached.
900+ #[test]
901+ fn fit_pillarboxes_with_exact_black_bars() {
902+ let (sw, sh) = (640u32, 480u32);
903+ let (dw, dh) = (1920u32, 1080u32);
904+ let src = (
905+ vec![200u8; (sw * sh) as usize],
906+ vec![70u8; (sw * sh / 4) as usize],
907+ vec![30u8; (sw * sh / 4) as usize],
908+ );
909+ let mut canvas = Composer::new(dw, dh, FitPolicy::Fit);
910+ let (y, u, v, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
911+ assert_eq!((w, h), (dw, dh));
912+ let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Fit);
913+ assert_eq!(
914+ rect,
915+ Rect {
916+ x: 240,
917+ y: 0,
918+ w: 1440,
919+ h: 1080
920+ },
921+ "geometry moved"
922+ );
923+ let (w, h) = (w as usize, h as usize);
924+ let row = &y[(h / 2) * w..][..w];
925+ let x = rect.x as usize;
926+ assert!(row[..x].iter().all(|&s| s == BLACK_Y), "left bar not black");
927+ assert!(
928+ row[x + rect.w as usize..].iter().all(|&s| s == BLACK_Y),
929+ "right bar not black"
930+ );
931+ assert!(
932+ row[x..x + rect.w as usize].iter().all(|&s| s == 200),
933+ "picture"
934+ );
935+ // ...and the bars are neutral in chroma too, or they would be a colour.
936+ let (cw, _) = chroma_dims(w, h);
937+ let crow = &u[(h / 4) * cw..][..cw];
938+ assert!(
939+ crow[..x / 2].iter().all(|&s| s == NEUTRAL_C),
940+ "bar has colour"
941+ );
942+ assert!(crow[x / 2 + 8].abs_diff(70) <= 1, "picture chroma");
943+ assert_eq!(v[(h / 4) * cw], NEUTRAL_C);
944+ }
945+
946+ /// The other three policies, on the same pair: `Fill` and `Stretch` cover
947+ /// the canvas (no bar anywhere), `Center` pads without resampling.
948+ #[test]
949+ fn fill_and_stretch_leave_no_bars_and_center_pads_1_to_1() {
950+ let (sw, sh) = (640u32, 480u32);
951+ let (dw, dh) = (1920u32, 1080u32);
952+ let src = (
953+ vec![200u8; (sw * sh) as usize],
954+ vec![70u8; (sw * sh / 4) as usize],
955+ vec![30u8; (sw * sh / 4) as usize],
956+ );
957+ for policy in [FitPolicy::Fill, FitPolicy::Stretch] {
958+ let mut canvas = Composer::new(dw, dh, policy);
959+ let (y, ..) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
960+ assert!(
961+ y.iter().all(|&s| s == 200),
962+ "{policy:?} left a bar: the canvas is not covered"
963+ );
964+ }
965+ let mut canvas = Composer::new(dw, dh, FitPolicy::Center);
966+ let (y, _, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
967+ let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Center);
968+ assert_eq!(rect.w, sw, "Center resampled the picture");
969+ let (w, h) = (w as usize, h as usize);
970+ let row = &y[(h / 2) * w..][..w];
971+ assert!(row[..rect.x as usize].iter().all(|&s| s == BLACK_Y));
972+ assert!(
973+ row[rect.x as usize..][..sw as usize]
974+ .iter()
975+ .all(|&s| s == 200)
976+ );
977+ }
978+
979+ /// A crop (`Fill` on a wider source) must gather the *middle* of the
980+ /// picture, chroma with it: a marked band at a known column has to come out
981+ /// at the column the geometry puts it at.
982+ #[test]
983+ fn fill_crops_about_the_centre() {
984+ let (sw, sh) = (32usize, 8usize);
985+ let (dw, dh) = (8u32, 8u32);
986+ // Column 16 (the centre) is bright, everything else is dark.
987+ let y: Vec<u8> = (0..sw * sh)
988+ .map(|i| if i % sw == 16 { 240 } else { 40 })
989+ .collect();
990+ let (cw, ch) = chroma_dims(sw, sh);
991+ let src = (y, vec![100u8; cw * ch], vec![150u8; cw * ch]);
992+ let mut canvas = Composer::new(dw, dh, FitPolicy::Fill);
993+ let (y, u, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw as u32, sh as u32);
994+ assert_eq!((w, h), (dw, dh));
995+ let (dst, crop) = fit_rect(sw as u32, sh as u32, dw, dh, FitPolicy::Fill);
996+ assert_eq!(
997+ dst,
998+ Rect {
999+ x: 0,
1000+ y: 0,
1001+ w: 8,
1002+ h: 8
1003+ },
1004+ "Fill must cover"
1005+ );
1006+ assert_eq!(
1007+ crop,
1008+ Rect {
1009+ x: 12,
1010+ y: 0,
1011+ w: 8,
1012+ h: 8
1013+ },
1014+ "crop off centre"
1015+ );
1016+ // The bright column is crop-relative column 4 of 8, untouched by the
1017+ // 1:1 scale, and no sample of the canvas is black: nothing is a bar.
1018+ let row = &y[..8];
1019+ assert_eq!(row[4], 240, "the marked column moved: {row:?}");
1020+ assert!(y.iter().all(|&s| s != BLACK_Y), "Fill left a bar");
1021+ assert!(u.iter().all(|&s| s == 100), "chroma crop lost its plane");
1022+ }
1023+
7171024 /// Not asserted: only the release number means anything. Run with
7181025 /// `cargo test -p engine --release scale::tests::perf -- --nocapture`.
7191026 #[test]
@@ -735,4 +1042,20 @@ mod tests {
7351042 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
7361043 println!("scale::scale_i420 1280x720 -> 1920x1080: {ms:.3} ms/frame");
7371044 }
1045+
1046+ /// The whole per-frame cost of a mixed-resolution timeline -- black fill,
1047+ /// scale and blit -- which is what the playback budget has to hold. Printed,
1048+ /// not asserted, like every other perf test here.
1049+ #[test]
1050+ fn perf_compose_720p_onto_1080p() {
1051+ let src = gradient(1280, 720);
1052+ let mut canvas = Composer::new(1920, 1080, FitPolicy::Fit);
1053+ let runs = 30;
1054+ let t = std::time::Instant::now();
1055+ for _ in 0..runs {
1056+ std::hint::black_box(canvas.place(&src.0, &src.1, &src.2, 1280, 720));
1057+ }
1058+ let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1059+ println!("scale::Composer::place 1280x720 onto 1920x1080 Fit: {ms:.3} ms/frame");
1060+ }
7381061 }
crates/engine/tests/audio_export.rsmodified+3 -0
@@ -17,6 +17,7 @@ use std::time::{Duration, Instant};
1717 use engine::export::{ExportSettings, Format};
1818 use engine::project::LaneKind;
1919 use engine::project::Source;
20+use engine::scale::FitPolicy;
2021 use engine::{AudioSession, Clip, ExportHandle, Project};
2122
2223 const RATE: u32 = 44_100;
@@ -66,6 +67,7 @@ fn mixed_project() -> Project {
6667 link: None,
6768 eq: None,
6869 color: None,
70+ fit: FitPolicy::default(),
6971 };
7072 Project::from_parts(
7173 vec![
@@ -86,6 +88,7 @@ fn mixed_project() -> Project {
8688 link: None,
8789 eq: None,
8890 color: None,
91+ fit: FitPolicy::default(),
8992 }],
9093 ),
9194 (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]),
crates/engine/tests/eq_audio.rsmodified+2 -0
@@ -24,6 +24,7 @@ use std::time::{Duration, Instant};
2424 use engine::eq::{Band, BandKind, EqParams};
2525 use engine::export::{ExportSettings, Format};
2626 use engine::project::{Lane, LaneKind, Source};
27+use engine::scale::FitPolicy;
2728 use engine::{AudioSession, Clip, ExportHandle, Project};
2829
2930 const RATE: u32 = 44_100;
@@ -59,6 +60,7 @@ fn clip(start: u32, source: usize, frames: u32) -> Clip {
5960 link: None,
6061 eq: None,
6162 color: None,
63+ fit: FitPolicy::default(),
6264 }
6365 }
6466
crates/engine/tests/export.rsmodified+82 -0
@@ -24,6 +24,7 @@ use engine::hw::HwEncoder;
2424 use engine::mux::{Mp4Muxer, VideoParams, parameter_sets};
2525 use engine::project::Lane;
2626 use engine::project::Source;
27+use engine::scale::FitPolicy;
2728 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
2829
2930 const FPS: f64 = 30.0;
@@ -175,6 +176,86 @@ fn exports_an_edited_timeline_in_hardware() {
175176 round_trip("hw", Duration::from_secs(60));
176177 }
177178
179+/// An export is written at the **project's** resolution, whatever sizes the
180+/// media on the timeline are -- and with the same geometry that was watched.
181+///
182+/// 1280x720 and 640x360 clips on a 960x720 (4:3) project: every frame comes out
183+/// 960x720, and both clips are letterboxed with 90 rows of bar at each edge,
184+/// which is exactly what `scale::fit_rect` places and what playback shows
185+/// (`playback.rs: a_fitted_clip_is_letterboxed_and_a_filled_one_is_not`).
186+#[test]
187+fn exports_at_the_project_resolution_with_the_watched_geometry() {
188+ pin_software();
189+ let clip = |source: usize, start: u32| engine::Clip {
190+ start,
191+ in_frame: 0,
192+ out_frame: 10,
193+ source,
194+ link: Some(source as u32),
195+ eq: None,
196+ color: None,
197+ fit: FitPolicy::default(),
198+ };
199+ let clips = vec![clip(0, 0), clip(1, 10)];
200+ let project = Project::from_parts(
201+ vec![
202+ Source::new(asset("test_baseline.mp4"), 0),
203+ Source::new(asset("test_mismatch.mp4"), 0),
204+ ],
205+ vec![
206+ (engine::project::LaneKind::Video, clips.clone()),
207+ (engine::project::LaneKind::Audio, clips),
208+ ],
209+ Vec::new(),
210+ Vec::new(),
211+ )
212+ .expect("a two-source project");
213+ // The project's own resolution, which is neither source's: this is the
214+ // value `PlaybackSession` keeps in its meta and hands the exporter.
215+ let meta = engine::VideoMeta {
216+ width: 960,
217+ height: 720,
218+ frame_rate: FPS,
219+ frame_count: 20,
220+ codec: engine::Codec::H264,
221+ };
222+ let out = out_path("mixed");
223+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
224+ wait(&handle, Duration::from_secs(120)).expect("export");
225+
226+ let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen export");
227+ assert_eq!(
228+ (written.width, written.height),
229+ (960, 720),
230+ "an export is the project's size, not any source's"
231+ );
232+ assert_eq!(written.frame_count, 20);
233+
234+ let frames = decode_all(&out);
235+ assert_eq!(frames.len(), 20);
236+ // Lossy: a bar is black plus whatever the encoder left, so the bars are
237+ // asserted as *flat and dark* rather than as byte 0, and the picture rows
238+ // as neither.
239+ let mean = |frame: &[u8], y: usize| {
240+ frame[y * 960 * 4..][..960 * 4]
241+ .chunks_exact(4)
242+ .flat_map(|px| [px[0], px[1], px[2]])
243+ .map(f64::from)
244+ .sum::<f64>()
245+ / (960.0 * 3.0)
246+ };
247+ for (at, what) in [(5usize, "the 1280x720 clip"), (15, "the 640x360 clip")] {
248+ let frame = &frames[at];
249+ assert!(mean(frame, 2) < 8.0, "{what}: top bar is not black");
250+ assert!(mean(frame, 717) < 8.0, "{what}: bottom bar is not black");
251+ assert!(
252+ mean(frame, 360) > 20.0,
253+ "{what}: the picture area is black, so nothing was composed"
254+ );
255+ }
256+ std::fs::remove_file(&out).unwrap();
257+}
258+
178259 /// The trap this slice exists to close: a timeline playing a file's *second*
179260 /// audio stream must export that stream's packets. Playing one stream and
180261 /// exporting another is a file that sounds nothing like what was edited, and
@@ -193,6 +274,7 @@ fn exports_the_audio_stream_the_timeline_plays() {
193274 link: Some(0),
194275 eq: None,
195276 color: None,
277+ fit: FitPolicy::default(),
196278 };
197279 // Stream 1 is the 22.05 kHz mono French track; stream 0 is 44.1 kHz
198280 // stereo. A project may only hold streams that agree, so this timeline is
crates/engine/tests/lanes.rsmodified+3 -0
@@ -15,6 +15,7 @@ use std::time::{Duration, Instant};
1515
1616 use engine::export::{ExportSettings, Format};
1717 use engine::project::{Clip, LaneKind, Source};
18+use engine::scale::FitPolicy;
1819 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
1920
2021 const FPS: f64 = 30.0;
@@ -237,6 +238,7 @@ fn the_mp4_copy_follows_the_lane_that_holds_the_sound() {
237238 link: None,
238239 eq: None,
239240 color: None,
241+ fit: FitPolicy::default(),
240242 };
241243 let project = Project::from_parts(
242244 vec![Source::new(&source, 0)],
@@ -296,6 +298,7 @@ fn two_audio_lanes_are_summed() {
296298 link: None,
297299 eq: None,
298300 color: None,
301+ fit: FitPolicy::default(),
299302 };
300303 let a2 = project.add_lane(LaneKind::Audio);
301304 assert!(project.place(a2, TOP_IN, doubled), "place the second lane");
crates/engine/tests/playback.rsmodified+106 -2
@@ -726,11 +726,24 @@ fn import_appends_a_second_source_and_plays_across_the_join() {
726726 fn import_refuses_what_does_not_match() {
727727 let mut session = open(asset("test_av.mp4"));
728728
729+ // A different *codec* cannot join: one timeline is one kind of source.
730+ let err = session
731+ .import(&asset("test_vp9.mp4"))
732+ .expect_err("VP9 must be refused")
733+ .to_string();
734+ assert!(err.contains("VP9"), "refusal must name the codec: {err}");
735+
736+ // A different resolution is no longer among the refusals -- it is placed on
737+ // the project canvas instead -- but this file is also silent, and that is.
729738 let err = session
730739 .import(&asset("test_mismatch.mp4"))
731- .expect_err("640x360 must be refused")
740+ .expect_err("a silent file must be refused")
732741 .to_string();
733- assert!(err.contains("640x360"), "refusal must name the size: {err}");
742+ assert!(err.contains("audio"), "refusal must name the audio: {err}");
743+ assert!(
744+ !err.contains("640x360"),
745+ "a resolution of its own is not a refusal any more: {err}"
746+ );
734747
735748 // Same size and rate, no audio track: the timeline has one.
736749 let err = session
@@ -755,6 +768,97 @@ fn import_refuses_what_does_not_match() {
755768 assert!(err.contains("audio"), "refusal must name the audio: {err}");
756769 }
757770
771+/// The user-facing point of a project resolution: media of two sizes on one
772+/// timeline, each composed onto the project's own canvas.
773+///
774+/// 640x360 joins a 1280x720 timeline (it would have been refused before this
775+/// slice), and both clips come out of `try_frame` at the project's size --
776+/// which is what makes the export, the window and the renderer one shape.
777+#[test]
778+fn media_of_two_resolutions_share_one_timeline() {
779+ let mut session = open(asset("test_baseline.mp4"));
780+ assert_eq!(session.resolution(), (1280, 720), "source 0's picture");
781+ assert_eq!(session.native_resolution(), (1280, 720));
782+ session
783+ .import(&asset("test_mismatch.mp4"))
784+ .expect("640x360 must join a 1280x720 timeline");
785+ // 150 frames of the first file, then 60 of the second, at 30 fps.
786+ assert_eq!(session.clip_spans().len(), 2);
787+ assert!((session.timeline_duration() - 7.0).abs() < 1e-9);
788+
789+ for (at, what) in [(1.0, "the 1280x720 clip"), (6.0, "the 640x360 clip")] {
790+ session.seek(at);
791+ let frame = next_frame(&mut session, what);
792+ assert_eq!(
793+ (frame.width, frame.height),
794+ (1280, 720),
795+ "{what} did not come out at the project resolution"
796+ );
797+ assert_eq!(frame.bgra.len(), 1280 * 720 * 4);
798+ }
799+}
800+
801+/// The geometry, asserted on the pixels: on a canvas whose aspect the media does
802+/// not share, a `Fit` clip is letterboxed -- bars exactly black, picture where
803+/// `scale::fit_rect` puts it -- and `Fill` crops the bars away.
804+#[test]
805+fn a_fitted_clip_is_letterboxed_and_a_filled_one_is_not() {
806+ let mut session = open(asset("test_baseline.mp4"));
807+ session
808+ .import(&asset("test_mismatch.mp4"))
809+ .expect("640x360 joins");
810+ // A 4:3 project: both clips are 16:9, so both are letterboxed on it. 960x720
811+ // holds the whole 640x360 picture as 960x540 with 90 rows of bar either way
812+ // (fit_rect's own arithmetic, asserted in scale.rs).
813+ assert!(session.set_resolution(960, 720), "4:3 project");
814+ session.seek(6.0);
815+ let frame = next_frame(&mut session, "the 640x360 clip on a 4:3 canvas");
816+ assert_eq!((frame.width, frame.height), (960, 720));
817+ let row = |frame: &Frame, y: usize| {
818+ frame.bgra[y * 960 * 4..][..960 * 4]
819+ .chunks_exact(4)
820+ .map(|px| (px[0], px[1], px[2]))
821+ .collect::<Vec<_>>()
822+ };
823+ let black = |row: &[(u8, u8, u8)]| row.iter().all(|&px| px == (0, 0, 0));
824+ assert!(black(&row(&frame, 0)), "top bar is not black");
825+ assert!(black(&row(&frame, 89)), "the bar stops one row early");
826+ assert!(black(&row(&frame, 719)), "bottom bar is not black");
827+ assert!(
828+ !black(&row(&frame, 360)),
829+ "the picture area is black: nothing was composed"
830+ );
831+ // Same clip, filled: the canvas is covered, so no row is a bar.
832+ let (lane, idx) = session.video_clip_at(6.0).expect("a clip at 6 s");
833+ assert!(session.set_fit(lane, idx, engine::scale::FitPolicy::Fill));
834+ session.seek(6.0);
835+ let filled = next_frame(&mut session, "the same clip filled");
836+ assert_eq!((filled.width, filled.height), (960, 720));
837+ assert!(!black(&row(&filled, 0)), "Fill left a top bar");
838+ assert!(!black(&row(&filled, 719)), "Fill left a bottom bar");
839+ assert_ne!(
840+ row(&frame, 360),
841+ row(&filled, 360),
842+ "Fill showed the same pixels as Fit: the crop did nothing"
843+ );
844+}
845+
846+/// The clip that pays nothing: a project at its media's own size must hand the
847+/// decoder's bytes through untouched, not merely equal ones. Same frame, same
848+/// bytes, whether or not the composition path exists.
849+#[test]
850+fn a_project_at_the_media_size_is_the_decoder_untouched() {
851+ let mut session = open(asset("test_baseline.mp4"));
852+ session.seek(1.0);
853+ let frame = next_frame(&mut session, "seek to 1 s");
854+ assert_eq!((frame.width, frame.height), (1280, 720));
855+ assert_eq!(
856+ frame.bgra,
857+ source_frame(&asset("test_baseline.mp4"), frame.index),
858+ "the pass-through path changed a byte"
859+ );
860+}
861+
758862 /// The same file twice is two clips of one source -- a source index is handed
759863 /// out once and reused, which is what keeps clipboard clips valid forever.
760864 #[test]
crates/engine/tests/saveload.rsmodified+103 -19
@@ -129,9 +129,9 @@ fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec<Source>, f64
129129
130130 /// The version-1 promise: a file written before the lanes existed still opens,
131131 /// as one grouped video+audio pair per clip laid end to end, and saving it
132-/// again writes version 6 -- which reopens as the same timeline.
132+/// again writes version 7 -- which reopens as the same timeline.
133133 #[test]
134-fn a_version_1_project_loads_fully_grouped_and_saves_as_version_6() {
134+fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() {
135135 let dir = scratch("v1");
136136 copy_in(&dir, "test_av.mp4");
137137 let path = dir.join("old.edith");
@@ -159,11 +159,15 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_6() {
159159 "playhead kept"
160160 );
161161
162- // Saved again it is v6, and v6 round-trips to the same timeline.
162+ // Saved again it is v7, and v7 round-trips to the same timeline.
163163 let v2 = dir.join("new.edith");
164164 loaded.save_project(&v2).expect("save");
165165 let text = std::fs::read_to_string(&v2).expect("read back");
166- assert!(text.starts_with("edith 6\n"), "{text}");
166+ assert!(text.starts_with("edith 7\n"), "{text}");
167+ assert!(
168+ text.contains("\nresolution 1280 720\n"),
169+ "a project with no resolution of its own is saved at source 0's: {text}"
170+ );
167171 assert_eq!(
168172 text.lines().filter(|l| l.starts_with("video ")).count(),
169173 2,
@@ -240,16 +244,17 @@ fn a_version_4_project_holds_more_than_two_lanes() {
240244 );
241245 assert_eq!(loaded.timeline_duration(), 60.0 / loaded.meta().frame_rate);
242246
243- // ...and saving it writes the v6 twin of what it read: the lane list, its
244- // order and the empty lane all survive, each clip now saying it plays flat
245- // and ungraded.
247+ // ...and saving it writes the v7 twin of what it read: the lane list, its
248+ // order and the empty lane all survive, each clip now saying it plays flat,
249+ // ungraded and fitted, under a project resolution taken from the media.
246250 let again = dir.join("again.edith");
247251 loaded.save_project(&again).expect("save");
248252 assert_eq!(
249253 std::fs::read_to_string(&again).expect("read back"),
250- "edith 6\nplayhead 0\nsource 0 test_av.mp4\n\
251- video 1 0 0 30 0 3 - -\naudio 1\nvideo 2 40 0 20 0 - - -\naudio 2 0 0 30 0 3 - -\n",
252- "a four-lane project is written as it was read, two versions on"
254+ "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\
255+ video 1 0 0 30 0 3 - - fit\naudio 1\n\
256+ video 2 40 0 20 0 - - - fit\naudio 2 0 0 30 0 3 - - fit\n",
257+ "a four-lane project is written as it was read, three versions on"
253258 );
254259 }
255260
@@ -276,18 +281,20 @@ fn a_version_5_project_carries_per_clip_equalizers() {
276281 loaded.save_project(&again).expect("save");
277282 assert_eq!(
278283 std::fs::read_to_string(&again).expect("read back"),
279- "edith 6\nplayhead 0\nsource 0 test_av.mp4\n\
284+ "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\
280285 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
281286 eq 12000.0:6.25:0.5:hs\n\
282- video 1 0 0 30 0 - 0 -\nvideo 1 30 30 60 0 - 1 -\n\
283- audio 1 0 0 30 0 - 0 -\naudio 1 30 30 60 0 - - -\n",
287+ video 1 0 0 30 0 - 0 - fit\nvideo 1 30 30 60 0 - 1 - fit\n\
288+ audio 1 0 0 30 0 - 0 - fit\naudio 1 30 30 60 0 - - - fit\n",
284289 "the equalizer table and every clip's index survive a round trip"
285290 );
286291 }
287292
288293 /// What version 6 is for, the same claim one version on: a clip carries a
289-/// colour grade beside its equalizer, the file names each once for however many
290-/// clips share it, and the whole thing comes back out byte for byte.
294+/// colour grade beside its equalizer and the file names each once for however
295+/// many clips share it. A format bump necessarily rewrites the file, so what is
296+/// asserted here is the v7 twin of what was read; the byte-identity claim lives
297+/// in `a_version_7_project_carries_a_resolution_and_fit_policies` below.
291298 #[test]
292299 fn a_version_6_project_carries_per_clip_colours() {
293300 let dir = scratch("v6_color");
@@ -309,9 +316,84 @@ fn a_version_6_project_carries_per_clip_colours() {
309316 loaded.save_project(&again).expect("save");
310317 assert_eq!(
311318 std::fs::read_to_string(&again).expect("read back"),
312- text,
319+ "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\
320+ eq 80.0:-3.0:0.707:ls\n\
321+ color 0.1:1.2:0.9:-0.3\n\
322+ color -0.25:1.0:0.0:0.5\n\
323+ video 1 0 0 30 0 - 0 0 fit\nvideo 1 30 30 60 0 - - 1 fit\n\
324+ audio 1 0 0 30 0 - - 0 fit\naudio 1 30 30 60 0 - - - fit\n",
313325 "the colour table and every clip's index survive a round trip"
314326 );
327+ // A dialect that could not say either one means the defaults, and those are
328+ // what such a project always was: the media's own size, nothing letterboxed.
329+ assert_eq!(loaded.resolution(), (1280, 720));
330+ assert_eq!(
331+ loaded.fit_of(engine::project::Lane::V1, 0),
332+ engine::scale::FitPolicy::Fit
333+ );
334+}
335+
336+/// What version 7 is for: the project's picture size is its own, not source 0's,
337+/// and each clip says how it meets it. Both survive the engine's door byte for
338+/// byte -- and a project whose resolution is nobody's media size is exactly the
339+/// case that could not be written down before.
340+#[test]
341+fn a_version_7_project_carries_a_resolution_and_fit_policies() {
342+ let dir = scratch("v7_resolution");
343+ copy_in(&dir, "test_av.mp4");
344+ let path = dir.join("mixed.edith");
345+ let text = "edith 7\nplayhead 0\nresolution 960 720\nsource 0 test_av.mp4\n\
346+ video 1 0 0 30 0 - - - fill\nvideo 1 30 30 60 0 - - - center\n\
347+ audio 1 0 0 60 0 - - - fit\n";
348+ std::fs::write(&path, text).expect("write a v7 file");
349+
350+ let loaded = PlaybackSession::open_project(&path).expect("a v7 project opens");
351+ assert_eq!(
352+ loaded.resolution(),
353+ (960, 720),
354+ "the project's own size, which is not the media's 1280x720"
355+ );
356+ assert_eq!(
357+ loaded.native_resolution(),
358+ (1280, 720),
359+ "...and the media's own size is still known"
360+ );
361+ let v1 = engine::project::Lane::V1;
362+ assert_eq!(loaded.fit_of(v1, 0), engine::scale::FitPolicy::Fill);
363+ assert_eq!(loaded.fit_of(v1, 1), engine::scale::FitPolicy::Center);
364+
365+ let again = dir.join("again.edith");
366+ loaded.save_project(&again).expect("save");
367+ assert_eq!(
368+ std::fs::read_to_string(&again).expect("read back"),
369+ text,
370+ "a v7 project is written exactly as it was read"
371+ );
372+
373+ // The refusals the new grammar adds, each naming its line.
374+ for (bad, want) in [
375+ (
376+ "edith 7\nresolution 0 720\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n",
377+ "0x720 is not a picture",
378+ ),
379+ (
380+ "edith 7\nresolution 960 720\nresolution 960 720\nsource 0 test_av.mp4\n\
381+ video 1 0 0 30 0 - - - fit\n",
382+ "resolution belongs once",
383+ ),
384+ (
385+ "edith 7\nresolution 960 720\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - squish\n",
386+ "not a fit policy",
387+ ),
388+ ] {
389+ let path = dir.join("bad.edith");
390+ std::fs::write(&path, bad).expect("write");
391+ let err = PlaybackSession::open_project(&path)
392+ .err()
393+ .expect("a malformed v7 file must be refused")
394+ .to_string();
395+ assert!(err.contains(want), "wanted {want:?}, got {err:?}");
396+ }
315397 }
316398
317399 #[test]
@@ -525,7 +607,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() {
525607
526608 for (text, want) in [
527609 (
528- "edith 7\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - -\n",
610+ "edith 8\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n",
529611 "line 1",
530612 ),
531613 // An eq index the table does not hold, and a band shape there is none.
@@ -599,11 +681,13 @@ fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() {
599681 .err()
600682 .expect("a source that stopped matching must not open")
601683 .to_string();
602- // The suffix is `import`'s own refusal, word for word.
684+ // The suffix is `import`'s own refusal, word for word. The substitute is
685+ // 640x360 *and* silent; only the second of those is a refusal now -- a
686+ // resolution of its own is placed on the project canvas.
603687 assert_eq!(
604688 err,
605689 format!(
606- "source {}: 640x360 does not match the timeline's 1280x720",
690+ "source {}: the file is silent, the timeline has audio",
607691 dir.join("test_av2.mp4").display()
608692 )
609693 );