diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index dfa6474..e902c23 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -1151,6 +1151,28 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { ) .into()); } + // The width of that window, which the check above cannot see: + // it asks whether the window is *open*, never how wide it is, + // and a `sub` line is the one number in this format a hand (or + // a hostile actor) can set to `i64::MAX` and have accepted. + // Every cut, split, ripple and group trim re-derives the two + // halves of the window by proportion + // ([`crate::project::SubClip::window_at`]), a multiply that + // overflowed on the first frame inside the caption -- a panic + // on the UI thread the first time a hand ripple-deleted across + // it, and in a release build a silently wrapped clock. The + // same bound [`crate::is_resolution`] holds a `resolution` + // line to, and for the same reason: refused by name at the + // door rather than clamped into something nobody wrote. + if sub.out_us - sub.in_us > crate::project::MAX_WINDOW_US { + return Err(format!( + "line {n}: caption at {} is a {}us window, past the {}us a caption can hold", + sub.start, + sub.out_us - sub.in_us, + crate::project::MAX_WINDOW_US + ) + .into()); + } // The palette bound, which is a clip's source bound for words: // the `subtitle` lines are written before these and a caption // names one of them by position. @@ -2721,8 +2743,8 @@ mod tests { #[test] fn a_strand_colour_round_trips_and_a_v22_look_stays_32_bit() { use crate::decode::{ - viz_hue_ui, viz_sat_ui, viz_strand_set, with_viz_paint_strand_hue, - with_viz_paint_strand_sat, VIZ_PAINT_AZURE, + VIZ_PAINT_AZURE, viz_hue_ui, viz_sat_ui, viz_strand_set, with_viz_paint_strand_hue, + with_viz_paint_strand_sat, }; let (dir, sources, lanes) = doc(); let mut painted = lanes.clone(); @@ -3280,11 +3302,13 @@ mod tests { assert!(err.starts_with("line 4: clip at "), "{err}"); } // The lanes are independent, so a video line never crowds an audio one. - assert!(parse( - b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n", - &dir - ) - .is_ok()); + assert!( + parse( + b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n", + &dir + ) + .is_ok() + ); // ...and a lane may be empty as long as the other one is not. let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse"); assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty"); @@ -3487,10 +3511,12 @@ mod tests { parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes, two(Vec::new(), Vec::new()) ); - assert!(parse(b"edith 1\n", &dir) - .expect("a project of nothing") - .sources - .is_empty()); + assert!( + parse(b"edith 1\n", &dir) + .expect("a project of nothing") + .sources + .is_empty() + ); } /// Every truncation of a good file either parses or refuses; none panics. diff --git a/crates/engine/src/eq.rs b/crates/engine/src/eq.rs index 05352c3..bf792b5 100644 --- a/crates/engine/src/eq.rs +++ b/crates/engine/src/eq.rs @@ -91,16 +91,44 @@ struct Coeffs { a2: f32, } +/// How far a band's gain may go either side of flat, in dB: the bound +/// [`Coeffs::new`] holds the one field [`Band`]'s doc says is clamped for it. +/// +/// Deliberately far past anything a card offers -- the UI's own limit is a +/// card decision, not a project one, and a project is allowed to be more +/// extreme than the control that set it -- but bounded all the same, because +/// the gain is not a magnitude anywhere else in this struct: it enters as +/// `a = 10^(gain_db/40)`, and `a` drives the peak section's pole radius toward +/// the unit circle. A few hundred dB puts the poles *on* it, and a section +/// whose poles are on the unit circle does not decay, it rings -- growing the +/// samples without limit until the device clamp and the export's own [-1, 1] +/// turn the whole clip into a full-scale square. Past 10_000 dB `a` is not even +/// finite any more and the coefficients come out `inf`. +/// +/// 40 dB is the ceiling because it is where the arithmetic stays comfortably +/// inside f32 (a linear gain of 100) while being louder than any boost a +/// mixing console offers. Clamped, not refused: the struct's contract is that +/// a deserializer may hand this over unchecked, and a project that says +/// +400 dB gets +40 dB rather than a project that will not open. +pub const MAX_BAND_GAIN_DB: f32 = 40.0; +/// ...and the floor, the same distance the other way. Symmetric because a +/// wide cut and a wide boost are the same filter run at two gains. +pub const MIN_BAND_GAIN_DB: f32 = -40.0; + impl Coeffs { /// Cookbook peaking/shelving section for `band` at `sample_rate`. fn new(band: &Band, sample_rate: u32) -> Self { // A frequency at or past Nyquist has no cookbook answer (sin(w0) folds), - // and Q of zero divides by zero: clamp rather than reject, the caller's - // value came out of a text file. + // Q of zero divides by zero, and a gain of a few hundred dB walks the + // peak's poles onto the unit circle: clamp rather than reject, the + // caller's value came out of a text file. The gain is the fourth of + // these four clamps, and the one the struct's own doc promised. let fs = f64::from(sample_rate.max(1)); let f0 = f64::from(band.freq_hz).clamp(1.0, fs * 0.49); let q = f64::from(band.q).clamp(0.05, 40.0); - let a = 10f64.powf(f64::from(band.gain_db) / 40.0); + let gain = + f64::from(band.gain_db).clamp(f64::from(MIN_BAND_GAIN_DB), f64::from(MAX_BAND_GAIN_DB)); + let a = 10f64.powf(gain / 40.0); let w0 = 2.0 * PI * f0 / fs; let (sin_w0, cos_w0) = (w0.sin(), w0.cos()); let alpha = sin_w0 / (2.0 * q); @@ -428,4 +456,82 @@ mod tests { ); } } + + /// A gain a `.edith` line can name, and the pole radius that comes of it. + /// + /// The invariant [`Band`] documents is that out-of-range values are clamped + /// when the coefficients are built, so a deserializer may hand one over + /// unchecked -- and three of the four fields were clamped at + /// [`Coeffs::new`] while `gain_db` was not. `a = 10^(gain_db/40)` feeds the + /// peak's `sqrt(a2/a0)` pole radius straight to 1 as the gain grows, and at + /// a few hundred dB the f32 rounding puts the poles *exactly* on the unit + /// circle: a marginally-stable section that rings for seconds, blowing up + /// the samples until the device clamp turns the whole clip into a + /// full-scale square (in monitoring and in the export alike). This is an + /// arithmetic claim about the pole radius, not an audibility claim: nothing + /// here says what the filter sounds like, only that it is stable. + /// + /// The poles are solved off the normalized coefficients, so this is the + /// filter the sample loop actually runs rather than a restatement of the + /// formula that built it. + #[test] + fn a_gain_a_file_can_name_leaves_the_poles_strictly_inside_the_unit_circle() { + for gain in [ + 12.0f32, 40.0, 100.0, 200.0, 400.0, 10_000.0, -200.0, -10_000.0, + ] { + let c = super::Coeffs::new( + &Band { + freq_hz: 1000.0, + gain_db: gain, + q: 1.0, + kind: BandKind::Peak, + }, + FS, + ); + // The poles of `z^2 + a1 z + a2`, solved: the number the sample + // loop's homogeneous solution is actually made of, and the only + // place a section's stability is decided. `radius` is the larger + // of the two, so a section is stable exactly when it is `< 1`. + let (a1, a2) = (c.a1 as f64, c.a2 as f64); + let disc = (a1 * a1 - 4.0 * a2).max(0.0).sqrt(); + let radius = [(-a1 + disc) / 2.0, (-a1 - disc) / 2.0] + .into_iter() + .fold(0.0f64, |m, r| m.max(r.abs())); + assert!( + radius < 0.999, + "gain {gain} dB gives a pole radius of {radius:.9} -- \ + the section rings instead of decaying" + ); + assert!( + c.b0.is_finite() && c.b1.is_finite() && c.b2.is_finite(), + "gain {gain} dB produced non-finite coefficients {c:?}" + ); + } + } + + /// The same claim about the samples rather than the coefficients: a + /// full-scale burst through a band whose gain a file named, with the gain + /// far past the card's own 12 dB limit, has to come out at the gain the + /// clamp ceiling *is*. +40 dB is a linear gain of 100, so a full-scale + /// burst peaks at ~100 and that is the answer, not a fault; anything past + /// it is the section ringing rather than a band being loud. Pre-fix, 200 dB + /// and 400 dB are past it by orders of magnitude. + #[test] + fn a_gain_a_file_can_name_does_not_blow_the_samples_up() { + for gain in [40.0f32, 100.0, 200.0, 400.0, 10_000.0] { + let mut out = vec![0.0f32; 48_000 * 2]; + // A full-scale 1 kHz burst for a tenth of a second, then silence: + // whatever the section rings into is what shows up after it. + for i in 0..4_800 * 2 { + out[i] = (TAU * 1000.0 * (i / 2) as f32 / FS as f32).sin(); + } + EqState::new(&peak(1000.0, gain, 1.0), FS, 2).process(&mut out); + let peak = out.iter().fold(0.0f32, |m, v| m.max(v.abs())); + assert!( + peak.is_finite() && peak < 200.0, + "gain {gain} dB sent a full-scale burst to {peak}: the clamp ceiling is \ + +40 dB, a linear gain of 100, and 200x that is a section ringing, not a band" + ); + } + } } diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 2a8e096..9892c67 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -92,6 +92,53 @@ pub const MIN_GAIN_DB: f32 = -60.0; /// a mix bus can take before the limiter is doing all the work. pub const MAX_GAIN_DB: f32 = 12.0; +/// The longest `[in_us, out_us)` window a [`SubClip`] may show, in +/// microseconds: **30 days** of track. +/// +/// A window is a stretch of *source media*, not of the timeline, so its width +/// is the length of the recording a caption was cut from -- and that is not +/// bounded by anything a day. A two-day conference stream, a lecture archive, a +/// long interview session: all produce a palette row whose `out_us` is tens of +/// hours, and a ceiling that refuses those refuses the user's own media back at +/// them. The value is therefore "past any recording", and nothing more +/// sophisticated: 30 days is a round number four orders of magnitude above the +/// longest thing anybody captions and three orders below the point where a +/// typed number becomes plausible as a duration at all. +/// +/// What it has to clear, concretely, and the honest arithmetic for each: +/// +/// - **The i64 multiply in [`SubClip::window_at`].** `window_us() * into`, +/// where `into` is a `u32` frame offset, so at most 4.29e9. It is a +/// `saturating_mul`, so this is not about safety -- saturation is total -- +/// but about the result still *meaning* something: 30 days x 4.29e9 is +/// 1.1e22, which does NOT fit an i64. So the multiply saturates for any +/// window above `i64::MAX / u32::MAX` = 2.1e9 us (~35 minutes), and 30 days +/// is 1200x past that. The value is then finite but the proportion is not +/// exact, and `set_window`'s clamp on the answer keeps the result inside the +/// window rather than trusting it. That is the real precision cost, and it +/// is why this is not "unlimited": past 35 minutes the cut degrades, past +/// this it has degraded to "the far end of the window". +/// - **`sub_lane_cues`'s f64 mapping.** `(t - in_us) as f64 * per`, where `per` +/// is `frames / fps * 1e6 / window_us`. Here f64 exactness genuinely does +/// apply: an i64 is exact in f64 to 2^53 = 9.0e15, and 30 days is 2.6e12 -- +/// about 3.5 orders of magnitude inside it, so the cue mapping is exact and +/// not merely close. +/// - **Nothing else.** There is no allocation, no index and no length derived +/// from a window, so a wider value costs no memory. The ceiling is a claim +/// about meaning, not about resource. +/// +/// Past it, the value is not a caption any project holds -- a `.edith` a hand +/// edited (or a hostile actor wrote) reaches this with a line the never-empty +/// check at the parser cannot see past, because `out_us > in_us` says the +/// window is *open* and never how wide it is. Every door -- the parse, +/// [`Project::with_subs`], [`Project::place_sub`] -- refuses such a line by +/// name, next to every other range check a `.edith` line has to pass. Every +/// *composer* instead clamps to it through [`set_window`], which is the only +/// function that writes a window; a trim that ran out of window stops at the +/// window's end rather than failing, exactly like the frame walls it already +/// has. +pub const MAX_WINDOW_US: i64 = 30 * 24 * 60 * 60 * 1_000_000; + /// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it /// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for /// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly @@ -636,9 +683,10 @@ impl SubClip { } /// How much of its track it shows, in microseconds; `>= 1` by the - /// never-empty invariant. + /// never-empty invariant, and never more than [`MAX_WINDOW_US`] for one + /// that came through a door. pub fn window_us(&self) -> i64 { - self.out_us - self.in_us + self.out_us.saturating_sub(self.in_us) } /// Where in its window the timeline frame `frame` falls, in microseconds -- @@ -649,9 +697,19 @@ impl SubClip { /// before `frame` is the fraction of the microseconds before it. That is /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins /// without either of them learning an fps. + /// + /// Total arithmetic, and clamped to the window it is cutting: the + /// `saturating_mul` is what a `SubClip` built by a caller rather than a + /// door gets (a hand-built one, a unit test, a future door that forgot the + /// bound) -- a wrapped window would put a caption's clock *before* its own + /// start, and the split that produced it would then hand back two halves + /// whose windows do not meet. The clamp is the never-empty invariant + /// restated: the answer is a point inside `[in_us, out_us]` or nothing. fn window_at(&self, frame: u32) -> i64 { let into = i64::from(frame.saturating_sub(self.start)); - self.in_us + self.window_us() * into / i64::from(self.frames.max(1)) + let window = self.window_us().max(0); + let at = window.saturating_mul(into) / i64::from(self.frames.max(1)); + self.in_us.saturating_add(at.min(window)) } } @@ -1703,6 +1761,20 @@ impl Project { ) .into()); } + // The width of that window, which the check above cannot see: + // [`edith`](crate::edith) asks the same question at the parse + // and this repeats it, because `with_subs` is the door a + // hand-built `Project` comes through and a caller is not more + // trustworthy than a file. + if s.out_us - s.in_us > MAX_WINDOW_US { + return Err(format!( + "{name} caption at {} is a {}us window, past the {}us a caption can hold", + s.start, + s.out_us - s.in_us, + MAX_WINDOW_US + ) + .into()); + } if s.track >= palette { return Err(format!( "{name} caption at {} names subtitle track {} of {palette}", @@ -1969,6 +2041,19 @@ impl Project { ) .into()); } + // The width of that window, which the check above cannot see: the same + // bound the two file doors hold a placement to + // ([`edith`](crate::edith)'s parse and [`with_subs`]), asked here + // because this is the door a *dragged* caption comes through and the + // hand that dragged it builds the `SubClip` itself. + if sub.out_us - sub.in_us > MAX_WINDOW_US { + return Err(format!( + "that placement is a {}us window, past the {}us a caption can hold", + sub.out_us - sub.in_us, + MAX_WINDOW_US + ) + .into()); + } if sub.track >= self.subtitles.len() { return Err(format!( "it names subtitle track {} of {}", @@ -2197,17 +2282,31 @@ impl Project { // The words that stay are the words that were there, so the window // moves with the head -- a trim, not a slip. Edge::Start => { - // Clamped to a window that is still a window: the walls above - // are frames and the rounding between the two clocks is not - // exact, and neither is a caller's hand-built placement. - s.in_us = (s.in_us + us_of(i64::from(to) - i64::from(s.start), fps)) - .clamp(0, s.out_us - 1); + // The head moves and the words that stay are the words that + // were there, so `in_us` follows it -- a trim, not a slip. + // Falling `in_us` makes the window *wider* (the ceiling bounds + // a difference), which is the half of this nothing here can + // see: `set_window` is what puts the width back inside. + set_window( + s, + s.in_us + .saturating_add(us_of(i64::from(to) - i64::from(s.start), fps)), + s.out_us, + ); s.frames = s.end() - to; s.start = to; } Edge::End => { - s.out_us = - (s.out_us + us_of(i64::from(to) - i64::from(s.end()), fps)).max(s.in_us + 1); + // ...and the tail, for [`set_window`]'s reason: the End room + // is walled at the ceiling, but `set_window` is what holds it + // for every other composer too, including this one when a + // caller hands `trim_sub` a `to` past its own room. + set_window( + s, + s.in_us, + s.out_us + .saturating_add(us_of(i64::from(to) - i64::from(s.end()), fps)), + ); s.frames = to - s.start; } } @@ -2267,10 +2366,17 @@ impl Project { .get(s.track) .and_then(|t| t.cues.iter().map(|c| c.end_us).max()) .unwrap_or(s.out_us); + // ...and never past [`grow_window`]'s ceiling, which is the + // wall that matters here: a front-end asks this to draw the + // drag, then trims to whatever it is told. An engine that + // offers room its own trim would refuse is a drag that snaps + // back at the end of the gesture -- so the room stops where + // the window stops, and the two agree by construction. + let wall_us = track_end.min(s.in_us.saturating_add(MAX_WINDOW_US)); ( s.start + 1, s.start - .saturating_add(frames_of(track_end - s.in_us).max(1)) + .saturating_add(frames_of((wall_us - s.in_us).max(1))) .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)), ) } @@ -3395,7 +3501,15 @@ impl Project { for (data, sub) in self.lanes.iter_mut().zip(join_subs) { if let Some(idx) = sub { data.subs[idx].frames += data.subs[idx + 1].frames; - data.subs[idx].out_us = data.subs[idx + 1].out_us; + // The left half's `in_us`, the right half's `out_us` -- which + // is the SUM of two legal widths, because `sub_joinable` has + // just established that the two halves are consecutive in the + // *source* (`next.in_us == subs[idx].out_us`). Neither half + // broke the ceiling and the whole does, so this is a composer + // a per-arm check on one writer could never have found: + // `set_window` is what makes the closed set closed. + let (in_us, out_us) = (data.subs[idx].in_us, data.subs[idx + 1].out_us); + set_window(&mut data.subs[idx], in_us, out_us); data.subs.remove(idx + 1); debug_assert!(subs_sorted_disjoint(&data.subs)); } @@ -5608,6 +5722,56 @@ fn us_of(frames: i64, fps: f64) -> i64 { } } +/// **The one function in this file that writes a caption's window.** Every +/// composer -- a trim, a split, a ripple, a group follow, a rejoin -- routes +/// through it, and the invariant it holds is total: +/// +/// ```text +/// 0 <= in_us and in_us < out_us and out_us - in_us <= MAX_WINDOW_US +/// ``` +/// +/// which is the never-empty invariant plus the width ceiling, restated as one +/// shape both ends of it come from. Note that the ceiling bounds a +/// **difference**, which is why a per-arm check is not enough and this is: +/// +/// - Growing `out_us` (a tail trim) makes the width larger, so the *upper* +/// wall bites. +/// - Falling `in_us` (a head trim) makes the width larger too, from the other +/// side -- so bounding `in_us` alone, which is what a head trim's own clamp +/// (`in_us <= out_us - 1`) does, says nothing at all about the ceiling. +/// - A rejoin takes the left half's `in_us` and the right half's `out_us`, and +/// the two halves are consecutive in the *source* (that is what +/// [`sub_joinable`] requires), so the joined width is the **sum** of two +/// legal widths. Each half passes its own door; the whole does not. +/// +/// Three rounds of review each found one more composer this way, so the +/// function is the fix rather than any single call site: clamping a new +/// caller into shape is a two-line change, and forgetting one is silent. +/// `every_window_write_goes_through_set_window` (in the tests below) is the +/// other half of that promise -- it scans the file and fails if a write +/// appears anywhere else. +/// +/// **Why it clamps where the doors refuse.** The doors -- the parser, +/// [`Project::with_subs`], [`Project::place_sub`] -- see a value on the way +/// IN, from a file or a foreign caller, where nobody was mid-gesture, so a +/// value that wide is named and refused rather than quietly changed. Every +/// composer below is an edit a person is watching happen, so the same value is +/// clamped to the end of the window: a drag that stops, exactly like the frame +/// walls these trims already apply. +fn set_window(s: &mut SubClip, in_us: i64, out_us: i64) { + let in_us = in_us.max(0); + // The `+ 1` is the never-empty invariant: the window is open, always, so a + // composer that would otherwise clamp it shut lands on one microsecond. + let out_us = out_us.clamp(in_us + 1, in_us.saturating_add(MAX_WINDOW_US)); + s.in_us = in_us; + s.out_us = out_us; + debug_assert!( + s.in_us >= 0 && s.out_us > s.in_us && s.out_us - s.in_us <= MAX_WINDOW_US, + "set_window left an illegal window: {:?}", + (s.in_us, s.out_us) + ); +} + /// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`, /// dropping what is inside the hole, splitting what straddles it and trimming /// what overlaps an edge. The windows follow the cut by proportion @@ -5620,24 +5784,31 @@ fn sub_clear(subs: &mut Vec, start: u32, end: u32) { continue; } if s.start < start { - out.push(SubClip { + let cut = s.window_at(start); + let mut head = SubClip { frames: start - s.start, - out_us: s.window_at(start), // Both pieces lose the group id, for [`clear`]'s reason: one // id on two boxes of one lane is the one thing it may never // mean. link: None, ..s - }); + }; + // `window_at` already answers inside the window, and `set_window` + // is the shape that says so once, for every composer, rather than + // leaving each of them to re-derive it. + set_window(&mut head, s.in_us, cut); + out.push(head); } if s.end() > end { - out.push(SubClip { + let cut = s.window_at(end); + let mut tail = SubClip { start: end, frames: s.end() - end, - in_us: s.window_at(end), link: None, ..s - }); + }; + set_window(&mut tail, cut, s.out_us); + out.push(tail); } } *subs = out; @@ -5651,22 +5822,21 @@ fn sub_open_room(subs: &mut Vec, at: u32, len: u32) { if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) { let s = subs[idx]; let cut = s.window_at(at); - subs[idx] = SubClip { + let mut head = SubClip { frames: at - s.start, - out_us: cut, link: None, ..s }; - subs.insert( - idx + 1, - SubClip { - start: at, - frames: s.end() - at, - in_us: cut, - link: None, - ..s - }, - ); + set_window(&mut head, s.in_us, cut); + subs[idx] = head; + let mut tail = SubClip { + start: at, + frames: s.end() - at, + link: None, + ..s + }; + set_window(&mut tail, cut, s.out_us); + subs.insert(idx + 1, tail); } for s in subs.iter_mut().filter(|s| s.start >= at) { s.start += len; @@ -5704,15 +5874,21 @@ fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) { /// the window it already shows over the frames it already takes. fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) { let per_frame = s.window_us() / i64::from(s.frames.max(1)); + // The `saturating_mul` keeps a `SubClip` that reached here without a door + // behind it from wrapping the window negative; `set_window` is what keeps + // the result legal rather than merely finite. This is the group-follow twin + // of [`Project::trim_sub`], and it reaches the same field from both edges -- + // so a fix that only walled the primary trim's End arm left the head (and + // the whole group path) open. let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from)); match edge { Edge::Start => { - s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1); + set_window(s, s.in_us.saturating_add(by(s.start, to)), s.out_us); s.frames = s.end() - to; s.start = to; } Edge::End => { - s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1); + set_window(s, s.in_us, s.out_us.saturating_add(by(s.end(), to))); s.frames = to - s.start; } } @@ -10865,4 +11041,356 @@ mod tests { assert_eq!(p.subtitles()[0].label, "two"); assert_ne!(p.subtitles(), palette.as_slice(), "and it is not back"); } + + /// Finds every line that **writes** a caption's clock, in three forms: an + /// assignment through any operator (`.out_us = `, `.out_us += `, + /// `.out_us <<= `), a struct-literal field (`out_us: ...`) and the + /// shorthand form (`out_us,`). A `let` binding is skipped for the literal + /// forms only, so `let x: &mut SubClip = ..; (*x).in_us = 5;` is still + /// caught while `let out_us = s.out_us;` is not. + /// + /// The operator list is `=` plus one assignment operator each, and + /// deliberately excludes `<=`: the first version of this matcher counted + /// `s.out_us <= s.in_us` as a write, which would have flagged every + /// never-empty check in the file. + fn window_writes(text: &str) -> Vec<(usize, String)> { + const FIELDS: [&str; 2] = ["in_us", "out_us"]; + const OPS: [&str; 11] = [ + "=", "+=", "-=", "*=", "/=", "%=", "^=", "&=", "|=", "<<=", ">>=", + ]; + let mut found = Vec::new(); + for (n, raw) in text.lines().enumerate() { + let line = raw.trim(); + if line.starts_with("//") { + continue; + } + let is_binding = line.starts_with("let "); + // `let (a, b) = ..` is a tuple pattern, not a struct literal: the + // commas there bind names. `let half = SubClip { frames: n, in_us, + // out_us, ..s };` is the opposite -- the same commas are shorthand + // fields -- and what separates them is the paren, not the `let`. + let tuple_pattern = line.starts_with("let ("); + for field in FIELDS { + let access = format!(".{field}"); + if let Some(at) = line.find(&access) { + let after = &line[at + access.len()..]; + let after = after.trim_start(); + if OPS + .iter() + .any(|op| after.starts_with(op) && !after[op.len()..].starts_with('=')) + { + found.push((n + 1, line.to_owned())); + continue; + } + } + // A bare name: a literal field, a shorthand, or a local + // binding. Skipped when a `.` or an identifier character + // precedes it -- that is a read, not a field being set. + // + // The `let` exclusion is per-occurrence and keyed on what + // FOLLOWS, not on the line. `let out_us = s.out_us;` names a + // local, so the `=` form is skipped; but `let tail = SubClip { + // in_us: cut, out_us: s.out_us, ..s };` is a struct literal + // behind a `let`, and an earlier version of this matcher + // skipped the whole line for being a `let` -- so that shape, + // which is exactly what a plausible composer looks like, went + // through green. Keyed on the follower, a `let` hides nothing. + for (at, _) in line.match_indices(field) { + let preceded_by_name = line[..at] + .chars() + .next_back() + .is_some_and(|c| c == '.' || c.is_alphanumeric() || c == '_'); + if preceded_by_name { + continue; + } + let after = line[at + field.len()..].trim_start(); + let sets_a_field = + after.starts_with(':') || (after.starts_with(',') && !tuple_pattern); + let names_a_local = after.starts_with('=') && !after[1..].starts_with('='); + if sets_a_field || (names_a_local && !is_binding) { + found.push((n + 1, line.to_owned())); + break; + } + } + } + } + found + } + + /// A **heuristic guard**, not a proof. The honest reading of a green here + /// is the residual risk in this comment, not the green itself. + /// + /// Three rounds of review each found one more composer a per-arm check had + /// missed -- a tail trim, a head trim, a rejoin that SUMS two legal + /// widths -- and each produced the same failure: the editor wrote a + /// `.edith` its own loader then refused, with no in-app way back. The + /// invariant is now structural in the code (every composer calls + /// [`set_window`]); this is what keeps that structure from quietly losing + /// a caller. + /// + /// **Why this is a scan and not the compiler**, which is the better answer + /// and was priced rather than skipped: making `in_us`/`out_us` private to + /// this module turns every outside write into a compile error, which no + /// one-token edit can defeat. It costs 74 `SubClip` construction sites + /// (31 of them in this crate's own integration tests) plus a public + /// constructor, and it reaches `crates/app`'s `timeline_edit.rs` and + /// `timeline_math.rs`, which other lanes own. That is a refactor of a + /// door's public shape rather than a bound, and the wrong size for this + /// lane -- so the guard stands here with its limits written down instead. + /// + /// **Residual risk, by class, most likely first.** These are not all + /// equally hypothetical; the first is the one a real composer would reach + /// for, and it is the one this matcher cannot see at all: + /// + /// 1. **Field-less writes.** `*a = *b;`, `*a = other;`, + /// `std::mem::swap(a, b)`, `a.clone_from(b)`, and any macro that + /// expands to a field write (`bump!(s.out_us, by)`). None of these ever + /// spell `in_us` or `out_us` on the line, so `window_writes` returns + /// nothing for all of them. A *helper* that writes the field directly IS + /// caught; it is specifically the whole-struct and macro forms that go + /// through. This is the class most likely to be used, and it is + /// unmatched by construction rather than by oversight. + /// 2. **A rename.** The matcher keys on the literal strings `in_us` and + /// `out_us`. Renaming the fields silences it entirely while it stays + /// green -- the sharpest failure here, because the guard is supposed to + /// be the thing that notices a rule drifting. + /// 3. **A writer inside a test.** `/tests/` paths and `mod tests` blocks + /// are cut. A test cannot produce a file a user loses, so the line is + /// drawn there deliberately, not by omission. + /// 4. **A file the walk does not reach**: a path outside `crates/`, or one + /// under a directory named `target`, `.git` or `vendor`. + /// + /// What the matcher DOES now cover, after four rounds of it not doing so: + /// every assignment operator; struct-literal fields and the shorthand form, + /// including behind a `let`; writes through an indirect `&mut`; and every + /// `.rs` under `crates/` with no filter on what the file contains, so a + /// glob import or a type alias can no longer hide a module. + #[test] + fn every_window_write_outside_set_window_is_named() { + // `CARGO_MANIFEST_DIR`, not `file!()`: a test runs with the WORKSPACE + // root as its working directory, so `file!()`'s crate-relative path + // does not resolve from where the binary actually starts. + let workspace = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .and_then(std::path::Path::parent) + .expect("crates/engine sits two levels under the workspace root") + .to_path_buf(); + // Every line in the workspace that names a clock and is not a + // composer, each with its reason. A new entry is a claim someone has + // to defend in review, which is the point of writing the list out. + let allowed = [ + ("pub in_us: i64,", "the field declaration"), + ("pub out_us: i64,", "the field declaration"), + ( + "fn set_window(s: &mut SubClip, in_us: i64, out_us: i64) {", + "set_window's own signature", + ), + ("s.in_us = in_us;", "set_window"), + ("s.out_us = out_us;", "set_window"), + ( + "set_window(&mut data.subs[idx], in_us, out_us);", + "regroup naming the two values it is about to set", + ), + ("in_us: micros(f[3], n)?,", "edith.rs: the parse door"), + ("out_us: micros(f[4], n)?,", "edith.rs: the parse door"), + // Non-test helpers that build a value to hand `place_sub`, which is + // a door. Not composers: nobody was mid-gesture, which is exactly + // why a door refuses where a composer clamps. + ( + "in_us: 0,", + "sweep.rs caption helper, and timeline_edit.rs's palette row, -> place_sub", + ), + ( + "out_us: i64::from(frames) * 1_000_000,", + "sweep.rs caption helper -> place_sub", + ), + ( + "frames: frames_of_us(out_us, self.fps),", + "timeline_edit.rs's palette row -> place_sub", + ), + ( + "out_us,", + "timeline_edit.rs's palette row shorthand -> place_sub", + ), + ]; + + let mut found: Vec = Vec::new(); + let (mut files, mut lines) = (0usize, 0usize); + let mut seen_app = false; + for (file, text) in read_workspace_rust(&workspace) { + // Test code, by path or by module: a test builds `SubClip`s by hand + // and its value is not one the loader ever reads, so the 31 sites in + // `crates/engine/tests/` and three in `crates/app/src/tests/` are + // not composers. A real limit rather than a technicality -- the + // guard does not cover a writer hidden inside a test -- but a test + // cannot produce a file a user loses, so it is where the line goes. + let path = file.to_string_lossy().replace('\\', "/"); + if path.contains("/tests/") { + continue; + } + let code = match text.find("\n#[cfg(test)]\nmod tests {") { + Some(at) => &text[..at], + None => text.as_str(), + }; + lines += code.lines().count(); + files += 1; + seen_app |= path.contains("crates/app/"); + for (n, line) in window_writes(code) { + if !allowed.iter().any(|(text, _)| *text == line) { + let at = file.strip_prefix(&workspace).unwrap_or(&file); + found.push(format!("{}:{n}: {line}", at.display())); + } + } + } + // A floor, not a census: the walk now opens EVERY `.rs` under + // `crates/` that is not test code -- 86 files and ~77,600 lines today, + // which is 141 files and ~116,000 before `/tests/` and `mod tests` are + // cut. The point is only to catch a walk rooted in the wrong place, + // which reads a file or two. + // The `seen_app` half is the one that matters: the two-file version of + // this guard read `project.rs` and `edith.rs` and was silently + // certifying a claim about the app it had never opened, and the + // `contains("SubClip")` filter that came next + // was the same mistake wearing a derived hat -- a file that reached + // the type by glob import or alias was never opened either. + assert!( + lines > 70_000 && files >= 80 && seen_app, + "the walk read {lines} lines in {files} files (app reached: \ + {seen_app}) -- it is not covering the workspace, and a guard that \ + reads nothing is worse than no guard because it reads as one" + ); + // The assertion this whole test exists for. It was DELETED by a clumsy + // edit while the coverage floor above was being retuned, and for a + // moment the test reported green while `found` held a real offender -- + // the fourth version of this guard failing in the one way that looks + // exactly like success. If you retune anything here, check this line + // still exists. + assert!( + found.is_empty(), + "a caption window is written outside set_window:\n {}", + found.join("\n ") + ); + } + + /// The blind spot, pinned as cases. Every one of these is a write, and the + /// guard exists because each of its earlier versions caught none of them -- + /// `s.out_us += by(...)` being a one-token edit that made it green while a + /// grouped caption really did grow past the ceiling. A matcher that has + /// quietly stopped matching is the failure mode that looks most like a + /// pass, so it gets its own test rather than a comment. + /// + /// The last group is the opposite: the field-less forms that are a write + /// and that this matcher CANNOT see. They are asserted to be missed, on + /// purpose, so that the day someone can match them the test says so -- + /// and so nobody reads this file as claiming more than it does. + #[test] + fn the_window_write_matcher_catches_the_ways_a_composer_hides() { + for (what, code) in [ + ( + "the one-token compound assignment", + " s.out_us += by(s.end(), to);", + ), + ("a plain compound assignment", " s.in_us -= 1;"), + ("a shift-assign", " s.out_us <<= 1;"), + ( + "a write through a &mut the matcher cannot see past", + " let x: &mut SubClip = q; (*x).in_us = 5;", + ), + ( + "a struct literal", + " out.push(SubClip { in_us: 0, out_us: 1, ..s });", + ), + ( + "the shorthand form", + " SubClip { in_us, out_us, ..s }", + ), + ( + "a struct literal behind a `let`, which the old line-wide `let` \ + exclusion skipped whole", + " let tail = SubClip { in_us: cut, out_us: s.out_us, ..s };", + ), + ( + "a struct literal behind a `let` using the shorthand too", + " let half = SubClip { frames: n, in_us, out_us, ..s };", + ), + ] { + assert!( + !window_writes(code).is_empty(), + "the matcher misses {what}: {code:?}" + ); + } + // ...and the other side, so the allowlist is not padded with reads. + for quiet in [ + " if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {", + " debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);", + " let out_us = s.out_us;", + " (next.start == frame && next.in_us == subs[idx].out_us)", + " let total = s.out_us - s.in_us;", + ] { + assert!( + window_writes(quiet).is_empty(), + "the matcher flags a read as a write: {quiet:?}" + ); + } + // The class this matcher CANNOT see, asserted as missed. Each of these + // really does write a caption's window and none of them spell the field + // name, so a field matcher returns nothing -- that is a property of the + // approach, not a bug to be fixed here, and the test exists so the + // doc comment's residual-risk list cannot quietly grow a claim this + // matcher has not earned. If one of these ever starts matching, this + // test fails and asks which side of the line moved. + for unmatchable in [ + " *a = *b;", + " *a = other;", + " std::mem::swap(a, b);", + " a.clone_from(b);", + " bump!(s.out_us, by);", + ] { + assert!( + window_writes(unmatchable).is_empty(), + "the matcher now matches a field-less form it documented as \ + unmatched -- update the residual-risk list too: {unmatchable:?}" + ); + } + } + + /// Every `.rs` under the workspace, paired with its text. Recursive + /// because the set of files that can name `SubClip` is a fact about the + /// tree, and a hardcoded pair of names goes stale the moment a lane adds a + /// module -- which is how the two-file version of this guard came to + /// certify a claim about `crates/app` it had never read. + fn read_workspace_rust(root: &std::path::Path) -> Vec<(std::path::PathBuf, String)> { + let mut out = Vec::new(); + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + // `target` is not source and `vendor` is not ours to rule on. + let skip = path + .file_name() + .is_some_and(|n| n == "target" || n == ".git" || n == "vendor"); + if !skip { + stack.push(path); + } + // EVERY `.rs`, with no filter on what it contains. The filter + // that was here (`text.contains("SubClip")`) was a name-based + // guess about which files can reach the type, and a glob import + // or a type alias defeats it exactly as it defeats a + // hardcoded file list: a new module holding the struct behind + // `use engine::project::*;` was never opened, and stayed green. + // The scan is text-only and the tree is small, so the honest + // thing costs nothing here. + } else if path.extension().is_some_and(|e| e == "rs") + && let Ok(text) = std::fs::read_to_string(&path) + { + out.push((path, text)); + } + } + } + out + } } diff --git a/crates/engine/src/scale.rs b/crates/engine/src/scale.rs index cc780bd..add9d90 100644 --- a/crates/engine/src/scale.rs +++ b/crates/engine/src/scale.rs @@ -339,7 +339,12 @@ pub fn compose_i420( /// [`align`]'s reason. pub fn crop_rect(src_w: u32, src_h: u32, t: &TransformParams) -> Rect { if src_w == 0 || src_h == 0 { - return Rect { x: 0, y: 0, w: 0, h: 0 }; + return Rect { + x: 0, + y: 0, + w: 0, + h: 0, + }; } let (cl, cr) = (t.crop_l.clamp(0.0, 0.5), t.crop_r.clamp(0.0, 0.5)); let (ct, cb) = (t.crop_t.clamp(0.0, 0.5), t.crop_b.clamp(0.0, 0.5)); @@ -375,7 +380,12 @@ pub fn transformed_dst_rect( canvas_w: u32, canvas_h: u32, ) -> (Rect, Rect) { - let empty = Rect { x: 0, y: 0, w: 0, h: 0 }; + let empty = Rect { + x: 0, + y: 0, + w: 0, + h: 0, + }; if dst.is_empty() || src.is_empty() || canvas_w == 0 || canvas_h == 0 { return (dst, src); } @@ -390,10 +400,29 @@ pub fn transformed_dst_rect( let cap_h = i64::from(canvas_h.max(1)) * 1024; let new_w = ((f64::from(dst.w) * scale).round() as i64).clamp(1, cap_w); let new_h = ((f64::from(dst.h) * scale).round() as i64).clamp(1, cap_h); - let pos_x = if t.pos_x.is_finite() { f64::from(t.pos_x) } else { 0.0 }; - let pos_y = if t.pos_y.is_finite() { f64::from(t.pos_y) } else { 0.0 }; - let cx = i64::from(dst.x) + i64::from(dst.w) / 2 + (f64::from(canvas_w) * pos_x).round() as i64; - let cy = i64::from(dst.y) + i64::from(dst.h) / 2 + (f64::from(canvas_h) * pos_y).round() as i64; + // ...and the position, to the same ceiling, for the same reason. A + // `transform` line takes any finite `f32` for `pos_x`/`pos_y` (there is + // no per-field clamp at the parse, unlike `scale`'s use of the value), and + // `f64 as i64` *saturates* -- so a hostile 3e38 arrived here as `i64::MAX` + // and the additions below, not the cast, are what overflowed: a panic on + // the compositing thread in a debug build and a silently wrapped position + // in a release one. A cap in canvas fractions is the same 1024 the scale + // gets, and a box pushed that far off the canvas is long gone either way: + // it comes back as the two empty rects the function already answers with. + let pos_x = if t.pos_x.is_finite() { + f64::from(t.pos_x) + } else { + 0.0 + }; + let pos_y = if t.pos_y.is_finite() { + f64::from(t.pos_y) + } else { + 0.0 + }; + let cx = (i64::from(dst.x) + i64::from(dst.w) / 2) + .saturating_add((f64::from(canvas_w) * pos_x.clamp(-1024.0, 1024.0)).round() as i64); + let cy = (i64::from(dst.y) + i64::from(dst.h) / 2) + .saturating_add((f64::from(canvas_h) * pos_y.clamp(-1024.0, 1024.0)).round() as i64); // The full box the transform describes, unclamped -- it may start // negative or run past either edge, which is exactly what "moved off the // canvas" means. @@ -424,12 +453,30 @@ pub fn transformed_dst_rect( let src_bottom = i64::from(src.h) * bottom / new_h; let src_x = src.x + src_left as u32; let src_y = src.y + src_top as u32; - let (src_x, src_w_) = align(src_x, src.w.saturating_sub((src_left + src_right) as u32), src_w); - let (src_y, src_h_) = align(src_y, src.h.saturating_sub((src_top + src_bottom) as u32), src_h); + let (src_x, src_w_) = align( + src_x, + src.w.saturating_sub((src_left + src_right) as u32), + src_w, + ); + let (src_y, src_h_) = align( + src_y, + src.h.saturating_sub((src_top + src_bottom) as u32), + src_h, + ); ( - Rect { x: dst_x, y: dst_y, w: dst_w, h: dst_h }, - Rect { x: src_x, y: src_y, w: src_w_, h: src_h_ }, + Rect { + x: dst_x, + y: dst_y, + w: dst_w, + h: dst_h, + }, + Rect { + x: src_x, + y: src_y, + w: src_w_, + h: src_h_, + }, ) } @@ -492,11 +539,7 @@ pub fn rotate_i420_90s_into( rotate_plane_into(y, w as usize, h as usize, steps, &mut out.0); rotate_plane_into(u, cw, ch, steps, &mut out.1); rotate_plane_into(v, cw, ch, steps, &mut out.2); - if steps == 2 { - (w, h) - } else { - (h, w) - } + if steps == 2 { (w, h) } else { (h, w) } } /// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise, @@ -758,7 +801,13 @@ impl Composer { (cy, cu, cv, crop.w, crop.h) } else { rot_buf = rotate_i420_90s(cy, cu, cv, crop.w, crop.h, steps); - (&rot_buf.0[..], &rot_buf.1[..], &rot_buf.2[..], rot_buf.3, rot_buf.4) + ( + &rot_buf.0[..], + &rot_buf.1[..], + &rot_buf.2[..], + rot_buf.3, + rot_buf.4, + ) }; let (dst, src) = fit_rect(rw, rh, canvas_w, canvas_h, self.policy); @@ -783,7 +832,16 @@ impl Composer { scaled.1.resize(ccw * cch, 0); scaled.2.resize(ccw * cch, 0); scale_i420( - fy, fu, fv, sw, sh, &mut scaled.0, &mut scaled.1, &mut scaled.2, dw, dh, + fy, + fu, + fv, + sw, + sh, + &mut scaled.0, + &mut scaled.1, + &mut scaled.2, + dw, + dh, ); (&scaled.0[..], &scaled.1[..], &scaled.2[..]) }; @@ -811,7 +869,11 @@ impl Composer { /// backstop. `a`/`b`'s planes must be the same length pairwise (Y with Y, U /// with U, V with V); a mismatched pair panics rather than silently /// truncating a picture. -pub fn blend_i420(a: (&[u8], &[u8], &[u8]), b: (&[u8], &[u8], &[u8]), t: f32) -> (Vec, Vec, Vec) { +pub fn blend_i420( + a: (&[u8], &[u8], &[u8]), + b: (&[u8], &[u8], &[u8]), + t: f32, +) -> (Vec, Vec, Vec) { let t = t.clamp(0.0, 1.0); let plane = |a: &[u8], b: &[u8]| -> Vec { assert_eq!(a.len(), b.len(), "blend_i420: mismatched plane sizes"); @@ -1466,7 +1528,12 @@ mod tests { }; assert_eq!( crop_rect(100, 100, &t), - Rect { x: 10, y: 0, w: 70, h: 100 }, + Rect { + x: 10, + y: 0, + w: 70, + h: 100 + }, "10% off the left, 20% off the right, nothing off top or bottom" ); // Opposing crops clamp to 0.5 a side rather than meeting or crossing. @@ -1478,7 +1545,15 @@ mod tests { let r = crop_rect(100, 100, &extreme); assert!(r.w >= 2, "the smallest surviving rect is one chroma sample"); // A zero-sized source has nothing to crop. - assert_eq!(crop_rect(0, 100, &TransformParams::default()), Rect { x: 0, y: 0, w: 0, h: 0 }); + assert_eq!( + crop_rect(0, 100, &TransformParams::default()), + Rect { + x: 0, + y: 0, + w: 0, + h: 0 + } + ); } /// A placement moved by `pos_x`/`pos_y` (canvas fractions about its own @@ -1486,8 +1561,18 @@ mod tests { /// case here clips, so the source rect comes back untouched. #[test] fn transformed_dst_rect_at_pos_and_scale() { - let dst = Rect { x: 0, y: 0, w: 100, h: 100 }; - let src = Rect { x: 0, y: 0, w: 100, h: 100 }; + let dst = Rect { + x: 0, + y: 0, + w: 100, + h: 100, + }; + let src = Rect { + x: 0, + y: 0, + w: 100, + h: 100, + }; // Moved a quarter of the canvas to the right, untouched vertically. let moved = TransformParams { pos_x: 0.25, @@ -1495,19 +1580,40 @@ mod tests { }; assert_eq!( transformed_dst_rect(dst, src, 100, 100, &moved, 200, 200), - (Rect { x: 50, y: 0, w: 100, h: 100 }, src), + ( + Rect { + x: 50, + y: 0, + w: 100, + h: 100 + }, + src + ), "25% of a 200-wide canvas is 50 pixels, about the placement's own centre" ); // Doubled in place, box already centred on the canvas: the centre // stays, the box fills the canvas, nothing clips. - let centred_dst = Rect { x: 50, y: 50, w: 100, h: 100 }; + let centred_dst = Rect { + x: 50, + y: 50, + w: 100, + h: 100, + }; let grown = TransformParams { scale: 2.0, ..Default::default() }; assert_eq!( transformed_dst_rect(centred_dst, src, 100, 100, &grown, 200, 200), - (Rect { x: 0, y: 0, w: 200, h: 200 }, src), + ( + Rect { + x: 0, + y: 0, + w: 200, + h: 200 + }, + src + ), "a 100x100 box doubled about its own centre on a 200x200 canvas fills it" ); } @@ -1521,27 +1627,137 @@ mod tests { /// what `scale` alone gives it. #[test] fn transformed_dst_rect_clips_instead_of_squeezing() { - let dst = Rect { x: 0, y: 0, w: 100, h: 100 }; - let src = Rect { x: 0, y: 0, w: 100, h: 100 }; + let dst = Rect { + x: 0, + y: 0, + w: 100, + h: 100, + }; + let src = Rect { + x: 0, + y: 0, + w: 100, + h: 100, + }; // +30% of a 100-wide canvas: the box moves 30px right, half of it // (50px) falls off the right edge -- half the source is trimmed off // its right, not the whole source squeezed into 70px. - let pos = TransformParams { pos_x: 0.30, ..Default::default() }; + let pos = TransformParams { + pos_x: 0.30, + ..Default::default() + }; let (d, s) = transformed_dst_rect(dst, src, 100, 100, &pos, 100, 100); - assert_eq!(d, Rect { x: 30, y: 0, w: 70, h: 100 }, "dst size must not shrink below what clipping removes"); - assert_eq!(s, Rect { x: 0, y: 0, w: 70, h: 100 }, "src trims off its right, does not squeeze"); + assert_eq!( + d, + Rect { + x: 30, + y: 0, + w: 70, + h: 100 + }, + "dst size must not shrink below what clipping removes" + ); + assert_eq!( + s, + Rect { + x: 0, + y: 0, + w: 70, + h: 100 + }, + "src trims off its right, does not squeeze" + ); // -30%: symmetric on the left, and no longer identical to identity. - let neg = TransformParams { pos_x: -0.30, ..Default::default() }; + let neg = TransformParams { + pos_x: -0.30, + ..Default::default() + }; let (d, s) = transformed_dst_rect(dst, src, 100, 100, &neg, 100, 100); - assert_eq!(d, Rect { x: 0, y: 0, w: 70, h: 100 }); - assert_eq!(s, Rect { x: 30, y: 0, w: 70, h: 100 }, "src trims off its left"); - assert_ne!((d, s), (dst, src), "a negative offset must move the picture, not no-op"); + assert_eq!( + d, + Rect { + x: 0, + y: 0, + w: 70, + h: 100 + } + ); + assert_eq!( + s, + Rect { + x: 30, + y: 0, + w: 70, + h: 100 + }, + "src trims off its left" + ); + assert_ne!( + (d, s), + (dst, src), + "a negative offset must move the picture, not no-op" + ); // Fully off canvas: both rects empty. - let gone = TransformParams { pos_x: 2.0, ..Default::default() }; + let gone = TransformParams { + pos_x: 2.0, + ..Default::default() + }; let (d, s) = transformed_dst_rect(dst, src, 100, 100, &gone, 100, 100); - assert!(d.is_empty() && s.is_empty(), "wholly off-canvas has nothing to draw"); + assert!( + d.is_empty() && s.is_empty(), + "wholly off-canvas has nothing to draw" + ); + } + + /// `pos_x`/`pos_y` are canvas fractions and a `transform` line takes any + /// finite `f32`, so they are the one transform field with no bound on the + /// way in -- `float()` (edith.rs) refuses only inf/NaN, and unlike + /// `scale`, which this function caps at a thousand canvas widths precisely + /// so its own arithmetic cannot overflow, the position was multiplied by + /// the canvas and added to `dst.x` unchecked. Rust's `as i64` saturates, so + /// a hostile 3e38 became `i64::MAX` and the *add* is what overflowed: + /// a panic on the compositing thread in a debug build, a silently wrapped + /// position in a release one. A placement pushed off the canvas is already + /// a legal answer (the two empty rects above); a position past the point + /// where the picture is long gone must give that same answer. + #[test] + fn a_transform_position_a_file_can_name_does_not_overflow_the_centre() { + let dst = Rect { + x: 10, + y: 20, + w: 100, + h: 100, + }; + let src = Rect { + x: 0, + y: 0, + w: 100, + h: 100, + }; + for (pos_x, pos_y) in [ + (3.0e38f32, 0.0), + (-3.0e38, 0.0), + (0.0, 3.0e38), + (0.0, -3.0e38), + (3.0e38, 3.0e38), + (f32::MAX, f32::MIN), + ] { + let t = TransformParams { + pos_x, + pos_y, + ..Default::default() + }; + let (d, s) = transformed_dst_rect(dst, src, 100, 100, &t, 200, 200); + // The answer is "nothing to draw" -- the box is a thousand canvas + // widths off screen -- not an overflow and not a wrapped position + // that lands back on the canvas. + assert!( + d.is_empty() && s.is_empty(), + "pos ({pos_x}, {pos_y}) gave {d:?} / {s:?} rather than an empty rect pair" + ); + } } /// [`nearest_90_steps`] rounds to the closest quarter turn and folds a @@ -1572,10 +1788,18 @@ mod tests { let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 1); assert_eq!((rw, rh), (h as u32, w as u32), "dims swap at 90 degrees"); - assert_eq!(mark_at(&ry, rw, rw - 1, 0), 99, "top-left moves to top-right"); + assert_eq!( + mark_at(&ry, rw, rw - 1, 0), + 99, + "top-left moves to top-right" + ); let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 2); - assert_eq!((rw, rh), (w as u32, h as u32), "dims stay put at 180 degrees"); + assert_eq!( + (rw, rh), + (w as u32, h as u32), + "dims stay put at 180 degrees" + ); assert_eq!( mark_at(&ry, rw, rw - 1, rh - 1), 99, @@ -1592,22 +1816,33 @@ mod tests { // Zero steps, and four of them, are both the identity. let (ry, ru, rv, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 0); - assert_eq!((ry, ru, rv, rw, rh), (y.clone(), u.clone(), v.clone(), w as u32, h as u32)); + assert_eq!( + (ry, ru, rv, rw, rh), + (y.clone(), u.clone(), v.clone(), w as u32, h as u32) + ); let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 4); - assert_eq!((ry, rw, rh), (y, w as u32, h as u32), "four quarter turns is the identity"); + assert_eq!( + (ry, rw, rh), + (y, w as u32, h as u32), + "four quarter turns is the identity" + ); } /// A 64x64 Y plane split down the middle: columns 0..32 are 200, 32..64 /// are 40. A vertical edge to track through a horizontal move. fn vsplit_64() -> (Vec, Vec, Vec) { - let y = (0..64 * 64).map(|i| if i % 64 < 32 { 200u8 } else { 40u8 }).collect(); + let y = (0..64 * 64) + .map(|i| if i % 64 < 32 { 200u8 } else { 40u8 }) + .collect(); (y, vec![NEUTRAL_C; 32 * 32], vec![NEUTRAL_C; 32 * 32]) } /// Same split, but across rows: 0..32 are 200, 32..64 are 40 -- an edge /// to track through a vertical move. fn hsplit_64() -> (Vec, Vec, Vec) { - let y = (0..64 * 64).map(|i| if i / 64 < 32 { 200u8 } else { 40u8 }).collect(); + let y = (0..64 * 64) + .map(|i| if i / 64 < 32 { 200u8 } else { 40u8 }) + .collect(); (y, vec![NEUTRAL_C; 32 * 32], vec![NEUTRAL_C; 32 * 32]) } @@ -1625,40 +1860,68 @@ mod tests { let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit); // Identity: the source's own edge stays at column 32, everywhere. - let (iy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &TransformParams::default()); + let (iy, ..) = + canvas.place_transformed(&y, &u, &v, src_w, src_h, &TransformParams::default()); for row in 0..64 { let r = &iy[row * 64..][..64]; - assert!(r[..32].iter().all(|&p| p == 200) && r[32..].iter().all(|&p| p == 40), "row {row}: {r:?}"); + assert!( + r[..32].iter().all(|&p| p == 200) && r[32..].iter().all(|&p| p == 40), + "row {row}: {r:?}" + ); } // +25%: the box moves right by 16 and does NOT shrink -- content // width stays 64 (the source's own 32/32 split), clipped to what // still fits. The edge (originally at box-column 32) now sits at // canvas column 16 + 32 = 48, not squeezed inward. - let plus = TransformParams { pos_x: 0.25, ..Default::default() }; + let plus = TransformParams { + pos_x: 0.25, + ..Default::default() + }; let (py, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &plus); for row in 0..64 { let r = &py[row * 64..][..64]; - assert!(r[..16].iter().all(|&p| p == BLACK_Y), "row {row} left of box: {r:?}"); - assert!(r[16..48].iter().all(|&p| p == 200), "row {row} squeezed inward: {r:?}"); - assert!(r[48..].iter().all(|&p| p == 40), "row {row} edge moved: {r:?}"); + assert!( + r[..16].iter().all(|&p| p == BLACK_Y), + "row {row} left of box: {r:?}" + ); + assert!( + r[16..48].iter().all(|&p| p == 200), + "row {row} squeezed inward: {r:?}" + ); + assert!( + r[48..].iter().all(|&p| p == 40), + "row {row} edge moved: {r:?}" + ); } // -25%: mirror image -- this used to be pixel-identical to identity. - let minus = TransformParams { pos_x: -0.25, ..Default::default() }; + let minus = TransformParams { + pos_x: -0.25, + ..Default::default() + }; let (ny, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &minus); assert_ne!(ny, iy, "a negative offset must move the picture, not no-op"); for row in 0..64 { let r = &ny[row * 64..][..64]; assert!(r[..16].iter().all(|&p| p == 200), "row {row}: {r:?}"); assert!(r[16..48].iter().all(|&p| p == 40), "row {row}: {r:?}"); - assert!(r[48..].iter().all(|&p| p == BLACK_Y), "row {row} right of box: {r:?}"); + assert!( + r[48..].iter().all(|&p| p == BLACK_Y), + "row {row} right of box: {r:?}" + ); } // Wholly off-canvas: nothing to draw, all black. - let gone = TransformParams { pos_x: 2.0, ..Default::default() }; + let gone = TransformParams { + pos_x: 2.0, + ..Default::default() + }; let (gy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &gone); - assert!(gy.iter().all(|&p| p == BLACK_Y), "off-canvas must render background"); + assert!( + gy.iter().all(|&p| p == BLACK_Y), + "off-canvas must render background" + ); } /// The same defect on the vertical axis: `pos_y` moves content up/down, @@ -1669,19 +1932,35 @@ mod tests { let (y, u, v) = hsplit_64(); let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit); - let plus = TransformParams { pos_y: 0.25, ..Default::default() }; + let plus = TransformParams { + pos_y: 0.25, + ..Default::default() + }; let (py, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &plus); for row in 0..16 { - assert!(py[row * 64..][..64].iter().all(|&p| p == BLACK_Y), "row {row} above the box"); + assert!( + py[row * 64..][..64].iter().all(|&p| p == BLACK_Y), + "row {row} above the box" + ); } for row in 16..48 { - assert!(py[row * 64..][..64].iter().all(|&p| p == 200), "row {row} squeezed: {:?}", &py[row * 64..][..4]); + assert!( + py[row * 64..][..64].iter().all(|&p| p == 200), + "row {row} squeezed: {:?}", + &py[row * 64..][..4] + ); } for row in 48..64 { - assert!(py[row * 64..][..64].iter().all(|&p| p == 40), "row {row} edge moved"); + assert!( + py[row * 64..][..64].iter().all(|&p| p == 40), + "row {row} edge moved" + ); } - let minus = TransformParams { pos_y: -0.25, ..Default::default() }; + let minus = TransformParams { + pos_y: -0.25, + ..Default::default() + }; let (ny, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &minus); for row in 0..16 { assert!(ny[row * 64..][..64].iter().all(|&p| p == 200), "row {row}"); @@ -1690,7 +1969,10 @@ mod tests { assert!(ny[row * 64..][..64].iter().all(|&p| p == 40), "row {row}"); } for row in 48..64 { - assert!(ny[row * 64..][..64].iter().all(|&p| p == BLACK_Y), "row {row} below the box"); + assert!( + ny[row * 64..][..64].iter().all(|&p| p == BLACK_Y), + "row {row} below the box" + ); } } @@ -1705,7 +1987,11 @@ mod tests { // scale 0.5, pos_x +0.25: box becomes 32x32 at canvas (32, 16), // fully on-canvas. The source's column-32 edge, halved, sits at // box-local column 16, i.e. canvas column 32 + 16 = 48. - let t = TransformParams { scale: 0.5, pos_x: 0.25, ..Default::default() }; + let t = TransformParams { + scale: 0.5, + pos_x: 0.25, + ..Default::default() + }; let (sy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &t); for row in 0..64 { let r = &sy[row * 64..][..64]; @@ -1713,8 +1999,14 @@ mod tests { let want_bg = if inside { r[0] } else { BLACK_Y }; assert_eq!(want_bg, BLACK_Y, "row {row} col 0 outside the box: {r:?}"); if inside { - assert!(r[40].abs_diff(200) <= 1, "row {row} col 40 should be the left half: {r:?}"); - assert!(r[56].abs_diff(40) <= 1, "row {row} col 56 should be the right half: {r:?}"); + assert!( + r[40].abs_diff(200) <= 1, + "row {row} col 40 should be the left half: {r:?}" + ); + assert!( + r[56].abs_diff(40) <= 1, + "row {row} col 56 should be the right half: {r:?}" + ); } } } diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index 68993f3..80d2016 100644 --- a/crates/engine/tests/saveload.rs +++ b/crates/engine/tests/saveload.rs @@ -108,7 +108,10 @@ fn both_proxy_switches_survive_a_save_and_a_reopen() { let media = copy_in(&dir, "test_av.mp4"); let mut session = PlaybackSession::open(&media).expect("open the fixture"); session.set_gain(0.0); - assert!(session.auto_proxies(), "a fresh project makes them by itself"); + assert!( + session.auto_proxies(), + "a fresh project makes them by itself" + ); assert!(!session.proxies(), "and is cut on the film itself"); session.set_proxies(true); @@ -126,7 +129,10 @@ fn both_proxy_switches_survive_a_save_and_a_reopen() { session.set_auto_proxies(true); session.save_project(&path).expect("save"); let text = std::fs::read_to_string(&path).expect("read back"); - assert!(!text.contains("autoproxy"), "on is written by saying nothing"); + assert!( + !text.contains("autoproxy"), + "on is written by saying nothing" + ); assert!( PlaybackSession::open_project(&path) .expect("reopen") @@ -158,7 +164,10 @@ fn the_encoder_seat_survives_a_save_and_a_reopen() { session.set_encoder_seat(seat); session.save_project(&path).expect("save"); let text = std::fs::read_to_string(&path).expect("read back"); - assert!(text.contains(&format!("encoder {}\n", seat.name())), "{text}"); + assert!( + text.contains(&format!("encoder {}\n", seat.name())), + "{text}" + ); assert_eq!( PlaybackSession::open_project(&path) .expect("reopen") @@ -171,7 +180,10 @@ fn the_encoder_seat_survives_a_save_and_a_reopen() { session.set_encoder_seat(EncoderSeat::Auto); session.save_project(&path).expect("save"); let text = std::fs::read_to_string(&path).expect("read back"); - assert!(!text.contains("encoder"), "auto is written by saying nothing"); + assert!( + !text.contains("encoder"), + "auto is written by saying nothing" + ); assert_eq!( PlaybackSession::open_project(&path) .expect("reopen") @@ -959,3 +971,487 @@ fn a_song_only_project_comes_back_at_the_rate_it_names() { let loaded = PlaybackSession::open_project(&old).expect("a v8 song project opens"); assert_eq!(loaded.meta().frame_rate, 30.0, "the canvas rate, as before"); } + +/// A hand-edited `.edith` whose caption names a microsecond window no project +/// can hold: the whole load, the same edit a 30-second window survives, and the +/// refusal the loader owes for it. +/// +/// A caption's window is the one unbounded number this format takes. The +/// never-empty check at `edith.rs` asks whether `out_us > in_us` and never how +/// large either is, so `out_us = i64::MAX` was a legal line -- and every split, +/// ripple and group trim since cuts the window *by proportion* +/// (`SubClip::window_at`), a plain `window_us() * into` that overflows on the +/// first frame inside the caption. That is a panic on the UI thread the first +/// time a hand ripple-deletes across the caption, and in a release build the +/// same line wraps the caption's clock to a negative number instead. So the +/// window is bounded at the door, by name, and the arithmetic behind the cut +/// is made total as well. +#[test] +fn a_caption_window_no_project_can_hold_is_refused_by_name() { + let dir = scratch("caption_window"); + let media = copy_in(&dir, "test_av.mp4"); + let subs = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/data/test_subs.srt") + .canonicalize() + .expect("the subtitle fixture"); + + // The control first: a 30-second window over 30 frames, the shape every + // save writes, and the shape this file's whole edit path is proved on. + let ok = dir.join("window_ok.edith"); + std::fs::write( + &ok, + format!( + "edith 23\nplayhead 0\nresolution 1280 720\nsource 0 {}\nsubtitle - {}\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\ + sub 1 0 30 0 0 30000000\n", + media.display(), + subs.display(), + ), + ) + .expect("write"); + let mut control = PlaybackSession::open_project(&ok).expect("a 30s caption window opens"); + assert_eq!(control.sub_lane(Lane::S1)[0].out_us, 30_000_000); + // The edits the unbounded window used to survive: a split inside the + // caption and a ripple across it. Both cut the window by proportion. + assert!( + control.cut_at(0.5), + "the playhead splits the caption under it" + ); + assert_eq!( + control.sub_lane(Lane::S1).len(), + 2, + "the split cut the caption in two" + ); + control.undo(); + control + .cut_regions(&[(0, 10)], &[Lane::S1]) + .expect("a ripple across the caption, scoped to its own lane"); + let after = control.sub_lane(Lane::S1); + assert_eq!(after.len(), 1, "the caption's tail is still there"); + assert_eq!( + (after[0].start, after[0].frames), + (0, 20), + "and it closed the hole the cut left" + ); + + // The same file, the same lane, the same edit -- with a window no project + // can hold. This is the line that used to load and then panic. + let huge = dir.join("window_huge.edith"); + std::fs::write( + &huge, + format!( + "edith 23\nplayhead 0\nresolution 1280 720\nsource 0 {}\nsubtitle - {}\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\ + sub 1 0 30 0 0 9223372036854775807\n", + media.display(), + subs.display(), + ), + ) + .expect("write"); + let err = PlaybackSession::open_project(&huge) + .err() + .unwrap_or_else(|| { + panic!( + "a caption window of {}us loaded, and the first split across it \ + panics in SubClip::window_at", + i64::MAX + ) + }) + .to_string(); + assert!( + err.contains("window") && err.contains("9223372036854775807"), + "the refusal names the window it is refusing, and the value: {err}" + ); + assert!(err.starts_with("line 7"), "and which line said it: {err}"); + + // The same bound at the other two doors a caption comes through, because a + // caller is not more trustworthy than a file: the placement a hand drags + // out of the palette is a `SubClip` somebody built, and it goes through + // `place_sub` rather than the parse. + let mut session = PlaybackSession::open(&media).expect("open the fixture"); + session + .import_subtitles(&subs) + .expect("the fixture's one track"); + let s1 = session.add_lane(engine::project::LaneKind::Subtitle); + let err = session + .place_sub( + s1, + 0, + engine::project::SubClip { + start: 0, + frames: 30, + track: 0, + in_us: 0, + out_us: i64::MAX, + link: None, + }, + ) + .expect_err("a window no project can hold is refused by name, not clamped") + .to_string(); + assert!( + err.contains("window") && err.contains(&i64::MAX.to_string()), + "the placement refusal names the window and the value: {err}" + ); + assert!( + session.sub_lane(s1).is_empty(), + "and a refusal places nothing: {:?}", + session.sub_lane(s1) + ); +} + +/// A subtitle track whose last cue ends `hours` in, written into `dir`. +/// +/// A caption's window is a window into SOURCE media, so its width is however +/// long the recording was. Nothing in the format bounds that, and a lecture +/// archive or a conference stream is tens of hours -- which is what a ceiling +/// under a day refuses back at the user. The hour field is parsed as a plain +/// `u32` with no digit limit, so 960 is a legal 40 days. +fn long_srt(dir: &Path, hours: u32) -> PathBuf { + let path = dir.join(format!("subs_{hours}h.srt")); + std::fs::write( + &path, + format!( + "1\n00:00:00,500 --> 00:00:01,500\nfirst line\n\n\ + 2\n00:00:01,600 --> {hours}:00:00,000\nlast line of a long recording\n" + ), + ) + .expect("write a long subtitle track"); + path +} + +/// The round trip a trim has to survive: grow a caption's window to the room +/// the engine itself offers, save, and open the file that was just written. +/// +/// This is the hole a ceiling on its own leaves. Every door -- the parse, +/// `with_subs`, `place_sub` -- only ever sees a window on the way *in*, so a +/// project could load legally and then be trimmed past the ceiling: `save` +/// wrote the line and the loader refused it again, which is the user's own +/// saved work stopping, with no in-app way back (the trim is committed and the +/// undo does not survive a restart). So growth clamps (`grow_window`) and the +/// room the front-end drags against is walled by the same number, and the two +/// agree by construction rather than by luck. +#[test] +fn a_trim_grown_to_the_offered_room_saves_and_reopens() { + use engine::project::{Edge, MAX_WINDOW_US, SubClip}; + + let dir = scratch("caption_growth"); + let media = copy_in(&dir, "test_av.mp4"); + // 40 days of track, comfortably past the 30-day ceiling: only the growth + // clamp can keep this inside it, never the ceiling itself. + let subs = long_srt(&dir, 960); + + let mut session = PlaybackSession::open(&media).expect("open the fixture"); + session + .import_subtitles(&subs) + .expect("a 40-day subtitle track imports"); + let s1 = session.add_lane(engine::project::LaneKind::Subtitle); + session + .place_sub( + s1, + 60, + SubClip { + start: 0, + frames: 90, + track: 0, + in_us: 0, + out_us: 30_000_000, + link: None, + }, + ) + .expect("a 30s window places"); + + // The room the drag is drawn against. It must itself stop at the ceiling: + // an engine that offers a trim its own `trim_sub` would clamp is a drag + // that snaps back at the end of the gesture. + let (_, last) = session + .trim_sub_room(s1, 0, Edge::End) + .expect("a room for a caption that is there"); + session + .trim_sub(s1, 0, Edge::End, last) + .expect("the trim to its own offered room"); + + let grown = session.sub_lane(s1)[0]; + assert!( + (grown.out_us - grown.in_us) <= MAX_WINDOW_US, + "trimming to the offered room gave a {}us window, past the {}us ceiling", + grown.out_us - grown.in_us, + MAX_WINDOW_US + ); + + let saved = dir.join("grown.edith"); + session.save_project(&saved).expect("save"); + let reopened = PlaybackSession::open_project(&saved) + .expect("a project the editor wrote must open again -- that is the whole claim"); + let back = reopened.sub_lane(s1)[0]; + assert_eq!( + (back.in_us, back.out_us), + (grown.in_us, grown.out_us), + "and the window came back as it was saved" + ); +} + +/// The ceiling itself, against the case it was measured on: a 25-hour +/// recording. `place_sub` is the door a palette row's drag comes through +/// (`sub_of_track` builds the placement from the track's own last cue), so a +/// ceiling under the length of real media refuses the user's own file back at +/// them, with nothing placed. +#[test] +fn a_caption_over_a_day_of_track_places_and_round_trips() { + use engine::project::MAX_WINDOW_US; + + let dir = scratch("caption_long_track"); + let media = copy_in(&dir, "test_av.mp4"); + let subs = long_srt(&dir, 25); + let whole_track_us = 25i64 * 60 * 60 * 1_000_000; + assert!( + whole_track_us > 86_400_000_000, + "the fixture must really be over a day, or this test proves nothing" + ); + assert!( + whole_track_us < MAX_WINDOW_US, + "and comfortably under the ceiling, or the test is not about the ceiling" + ); + + let mut session = PlaybackSession::open(&media).expect("open the fixture"); + assert_eq!( + session + .import_subtitles(&subs) + .expect("a 25-hour track imports"), + 1, + "one track" + ); + let s1 = session.add_lane(engine::project::LaneKind::Subtitle); + // Exactly what `Player::sub_of_track` hands `place_sub` for palette row 0. + let fps = f64::from(session.meta().frame_rate); + session + .place_sub( + s1, + 0, + engine::project::SubClip { + start: 0, + frames: ((whole_track_us as f64) * fps / 1e6).round() as u32, + track: 0, + in_us: 0, + out_us: whole_track_us, + link: None, + }, + ) + .expect("a caption over a 25-hour recording places -- that is the claim"); + + let saved = dir.join("long.edith"); + session.save_project(&saved).expect("save"); + let reopened = PlaybackSession::open_project(&saved).expect("and reopens"); + assert_eq!( + reopened.sub_lane(s1)[0].out_us, + whole_track_us, + "the whole window survived the round trip" + ); +} + +/// The second writer, which is the one a primary-trim-only fix would miss. +/// +/// [`write_sub_edge`] carries a *sibling* in a group by the same delta as the +/// member that was dragged, and reaches the same `out_us`. `follow_group` +/// skips the dragged member, so the route here is a second caption in the +/// group on another lane: it is not the one whose `trim_sub` arm is fixed, so +/// nothing about the dragged caption's own clamp bounds it. +/// +/// The sibling starts deep into the track -- 20 days in -- so the same delta +/// that stops the dragged caption exactly at the ceiling carries the sibling +/// past it. Without the clamp on this writer the sibling is 20 days wider than +/// the ceiling when `save_project` runs, and the file it writes will not open. +#[test] +fn a_group_trim_carries_its_sibling_no_further_than_the_ceiling() { + use engine::project::{Edge, LaneKind, MAX_WINDOW_US, SubClip}; + + let dir = scratch("caption_group_growth"); + let media = copy_in(&dir, "test_av.mp4"); + let subs = long_srt(&dir, 960); + let day = 24 * 60 * 60 * 1_000_000i64; + + let mut session = PlaybackSession::open(&media).expect("open the fixture"); + session + .import_subtitles(&subs) + .expect("a 40-day track imports"); + let s1 = session.add_lane(LaneKind::Subtitle); + let s2 = session.add_lane(LaneKind::Subtitle); + let caption = |in_us| SubClip { + start: 0, + frames: 90, + track: 0, + in_us, + out_us: in_us + 30_000_000, + link: None, + }; + session + .place_sub(s1, 60, caption(0)) + .expect("the dragged caption places"); + session + .place_sub(s2, 60, caption(20 * day)) + .expect("its sibling, 20 days into the track"); + session + .group_all(&[(s1, 0), (s2, 0)]) + .expect("the two captions into one group"); + + // Drag the first caption's tail out to the room the engine offers it, which + // is a 40-day track so the room is the ceiling, not the track. + let (_, last) = session + .trim_sub_room(s1, 0, Edge::End) + .expect("a room for the dragged caption"); + session + .trim_sub(s1, 0, Edge::End, last) + .expect("the drag commits"); + + let dragged = session.sub_lane(s1)[0]; + assert_eq!( + dragged.out_us - dragged.in_us, + MAX_WINDOW_US, + "the dragged caption stops exactly at the ceiling, which is the room it was offered" + ); + let sibling = session.sub_lane(s2)[0]; + assert!( + (sibling.out_us - sibling.in_us) <= MAX_WINDOW_US, + "the group carried the sibling to a {}us window, past the {}us ceiling -- \ + the dragged caption's own clamp does not reach here", + sibling.out_us - sibling.in_us, + MAX_WINDOW_US + ); + + let saved = dir.join("group.edith"); + session.save_project(&saved).expect("save"); + PlaybackSession::open_project(&saved).expect("and the file the editor wrote reopens"); +} + +/// The composer that no per-arm check finds: a **rejoin** takes the left +/// half's `in_us` and the right half's `out_us`, and `sub_joinable` has just +/// established that the two halves are consecutive in the *source* -- so the +/// joined width is the SUM of two widths that each passed their own door. +/// +/// Neither half is illegal and the whole is. Two 20-day windows, one ordinary +/// undo-a-split keystroke, a 40-day window, and a file the editor writes and +/// cannot reopen. +#[test] +fn a_rejoin_of_two_legal_windows_stays_inside_the_ceiling() { + use engine::project::{MAX_WINDOW_US, SubClip}; + + let dir = scratch("caption_rejoin"); + let media = copy_in(&dir, "test_av.mp4"); + let subs = long_srt(&dir, 960); + let twenty_days = 20 * 24 * 60 * 60 * 1_000_000i64; + + let mut session = PlaybackSession::open(&media).expect("open the fixture"); + session + .import_subtitles(&subs) + .expect("a 40-day track imports"); + let s1 = session.add_lane(engine::project::LaneKind::Subtitle); + // Two adjacent halves, each a legal 20-day window, the second starting + // exactly where the first's window ends -- which is what `sub_joinable` + // requires, and what makes the join a sum. + for (at, frames, in_us) in [(0u32, 10_000u32, 0i64), (10_000, 10_000, twenty_days)] { + session + .place_sub( + s1, + at, + SubClip { + start: 0, + frames, + track: 0, + in_us, + out_us: in_us + twenty_days, + link: None, + }, + ) + .unwrap_or_else(|e| panic!("a 20-day half at {at} places: {e}")); + } + let halves: Vec = session + .sub_lane(s1) + .iter() + .map(|s| s.out_us - s.in_us) + .collect(); + assert!( + halves.iter().all(|&w| w <= MAX_WINDOW_US), + "both halves must be legal for this to be about the join: {halves:?}" + ); + + // `regroup_at` is in seconds, like every other front-end door; the + // boundary is the frame the second half starts on. + let at_secs = 10_000.0 / f64::from(session.meta().frame_rate); + assert!( + session.regroup_at(at_secs), + "the two halves rejoin -- the inverse of the split that made them" + ); + let joined = &session.sub_lane(s1)[0]; + assert!( + (joined.out_us - joined.in_us) <= MAX_WINDOW_US, + "the rejoin summed two {}us windows into {}us, past the {}us ceiling", + MAX_WINDOW_US / 2, + joined.out_us - joined.in_us, + MAX_WINDOW_US + ); + + let saved = dir.join("rejoined.edith"); + session.save_project(&saved).expect("save"); + PlaybackSession::open_project(&saved).expect("and the file the editor wrote reopens"); +} + +/// The other half of the ceiling: it bounds a **difference**, so a head trim +/// grows the width as surely as a tail trim does, and from the other side. +/// +/// A caption placed a year into its source with a 30-second window is legal. +/// One head drag pulling its start back by 200 days of frames makes the +/// window 200 days wide while `out_us` never moves -- so bounding `in_us` +/// from above, which is all the head arm's own clamp does, says nothing at all +/// about the ceiling. +#[test] +fn a_head_drag_no_further_than_the_ceiling() { + use engine::project::{Edge, MAX_WINDOW_US, SubClip}; + + let dir = scratch("caption_head_drag"); + let media = copy_in(&dir, "test_av.mp4"); + let subs = long_srt(&dir, 960); + let day = 24 * 60 * 60 * 1_000_000i64; + + let mut session = PlaybackSession::open(&media).expect("open the fixture"); + session + .import_subtitles(&subs) + .expect("a 40-day track imports"); + let s1 = session.add_lane(engine::project::LaneKind::Subtitle); + // A year into the source, 30 seconds of window: legal, and the only kind + // of caption a head drag can make enormous. + session + .place_sub( + s1, + 90_000_000, + SubClip { + start: 0, + frames: 900, + track: 0, + in_us: 365 * day, + out_us: 365 * day + 30_000_000, + link: None, + }, + ) + .expect("a year-deep caption places"); + + // The head room the engine offers, then the drag to its far end: 200 days + // of source at 30 fps, which the Start arm's own `in_us <= out_us - 1` + // clamp is perfectly happy with. + let (lo, _) = session + .trim_sub_room(s1, 0, Edge::Start) + .expect("a head room"); + session + .trim_sub(s1, 0, Edge::Start, lo) + .expect("the head drag commits"); + + let dragged = session.sub_lane(s1)[0]; + assert!( + (dragged.out_us - dragged.in_us) <= MAX_WINDOW_US, + "a head drag onto a year-deep caption gave a {}us window, past the {}us ceiling", + dragged.out_us - dragged.in_us, + MAX_WINDOW_US + ); + + let saved = dir.join("head.edith"); + session.save_project(&saved).expect("save"); + PlaybackSession::open_project(&saved).expect("and the file the editor wrote reopens"); +}