forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(edithloader): the .edith door bounds the caption window, band gain and transform position

Browse files at this commit

2c809fd99f35d789f1d3e40857e792d91e51d608Ahmet Kaan GümüşParent: a72b5b104265e9
# Conflicts:
#	crates/engine/src/project.rs
crates/engine/src/edith.rsmodified+37 -11
@@ -1151,6 +1151,28 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
1151 )1151 )
1152 .into());1152 .into());
1153 }1153 }
1154+ // The width of that window, which the check above cannot see:
1155+ // it asks whether the window is *open*, never how wide it is,
1156+ // and a `sub` line is the one number in this format a hand (or
1157+ // a hostile actor) can set to `i64::MAX` and have accepted.
1158+ // Every cut, split, ripple and group trim re-derives the two
1159+ // halves of the window by proportion
1160+ // ([`crate::project::SubClip::window_at`]), a multiply that
1161+ // overflowed on the first frame inside the caption -- a panic
1162+ // on the UI thread the first time a hand ripple-deleted across
1163+ // it, and in a release build a silently wrapped clock. The
1164+ // same bound [`crate::is_resolution`] holds a `resolution`
1165+ // line to, and for the same reason: refused by name at the
1166+ // door rather than clamped into something nobody wrote.
1167+ if sub.out_us - sub.in_us > crate::project::MAX_WINDOW_US {
1168+ return Err(format!(
1169+ "line {n}: caption at {} is a {}us window, past the {}us a caption can hold",
1170+ sub.start,
1171+ sub.out_us - sub.in_us,
1172+ crate::project::MAX_WINDOW_US
1173+ )
1174+ .into());
1175+ }
1154 // The palette bound, which is a clip's source bound for words:1176 // The palette bound, which is a clip's source bound for words:
1155 // the `subtitle` lines are written before these and a caption1177 // the `subtitle` lines are written before these and a caption
1156 // names one of them by position.1178 // names one of them by position.
@@ -2721,8 +2743,8 @@ mod tests {
2721 #[test]2743 #[test]
2722 fn a_strand_colour_round_trips_and_a_v22_look_stays_32_bit() {2744 fn a_strand_colour_round_trips_and_a_v22_look_stays_32_bit() {
2723 use crate::decode::{2745 use crate::decode::{
2724- viz_hue_ui, viz_sat_ui, viz_strand_set, with_viz_paint_strand_hue,2746+ VIZ_PAINT_AZURE, viz_hue_ui, viz_sat_ui, viz_strand_set, with_viz_paint_strand_hue,
2725- with_viz_paint_strand_sat, VIZ_PAINT_AZURE,2747+ with_viz_paint_strand_sat,
2726 };2748 };
2727 let (dir, sources, lanes) = doc();2749 let (dir, sources, lanes) = doc();
2728 let mut painted = lanes.clone();2750 let mut painted = lanes.clone();
@@ -3280,11 +3302,13 @@ mod tests {
3280 assert!(err.starts_with("line 4: clip at "), "{err}");3302 assert!(err.starts_with("line 4: clip at "), "{err}");
3281 }3303 }
3282 // The lanes are independent, so a video line never crowds an audio one.3304 // The lanes are independent, so a video line never crowds an audio one.
3283- assert!(parse(3305+ assert!(
3284- b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n",3306+ parse(
3285- &dir3307+ b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n",
3286- )3308+ &dir
3287- .is_ok());3309+ )
3310+ .is_ok()
3311+ );
3288 // ...and a lane may be empty as long as the other one is not.3312 // ...and a lane may be empty as long as the other one is not.
3289 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");3313 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");
3290 assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty");3314 assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty");
@@ -3487,10 +3511,12 @@ mod tests {
3487 parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes,3511 parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes,
3488 two(Vec::new(), Vec::new())3512 two(Vec::new(), Vec::new())
3489 );3513 );
3490- assert!(parse(b"edith 1\n", &dir)3514+ assert!(
3491- .expect("a project of nothing")3515+ parse(b"edith 1\n", &dir)
3492- .sources3516+ .expect("a project of nothing")
3493- .is_empty());3517+ .sources
3518+ .is_empty()
3519+ );
3494 }3520 }
3495 3521
3496 /// Every truncation of a good file either parses or refuses; none panics.3522 /// Every truncation of a good file either parses or refuses; none panics.
crates/engine/src/eq.rsmodified+109 -3
@@ -91,16 +91,44 @@ struct Coeffs {
91 a2: f32,91 a2: f32,
92 }92 }
93 93
94+/// How far a band's gain may go either side of flat, in dB: the bound
95+/// [`Coeffs::new`] holds the one field [`Band`]'s doc says is clamped for it.
96+///
97+/// Deliberately far past anything a card offers -- the UI's own limit is a
98+/// card decision, not a project one, and a project is allowed to be more
99+/// extreme than the control that set it -- but bounded all the same, because
100+/// the gain is not a magnitude anywhere else in this struct: it enters as
101+/// `a = 10^(gain_db/40)`, and `a` drives the peak section's pole radius toward
102+/// the unit circle. A few hundred dB puts the poles *on* it, and a section
103+/// whose poles are on the unit circle does not decay, it rings -- growing the
104+/// samples without limit until the device clamp and the export's own [-1, 1]
105+/// turn the whole clip into a full-scale square. Past 10_000 dB `a` is not even
106+/// finite any more and the coefficients come out `inf`.
107+///
108+/// 40 dB is the ceiling because it is where the arithmetic stays comfortably
109+/// inside f32 (a linear gain of 100) while being louder than any boost a
110+/// mixing console offers. Clamped, not refused: the struct's contract is that
111+/// a deserializer may hand this over unchecked, and a project that says
112+/// +400 dB gets +40 dB rather than a project that will not open.
113+pub const MAX_BAND_GAIN_DB: f32 = 40.0;
114+/// ...and the floor, the same distance the other way. Symmetric because a
115+/// wide cut and a wide boost are the same filter run at two gains.
116+pub const MIN_BAND_GAIN_DB: f32 = -40.0;
117+
94 impl Coeffs {118 impl Coeffs {
95 /// Cookbook peaking/shelving section for `band` at `sample_rate`.119 /// Cookbook peaking/shelving section for `band` at `sample_rate`.
96 fn new(band: &Band, sample_rate: u32) -> Self {120 fn new(band: &Band, sample_rate: u32) -> Self {
97 // A frequency at or past Nyquist has no cookbook answer (sin(w0) folds),121 // A frequency at or past Nyquist has no cookbook answer (sin(w0) folds),
98- // and Q of zero divides by zero: clamp rather than reject, the caller's122+ // Q of zero divides by zero, and a gain of a few hundred dB walks the
99- // value came out of a text file.123+ // peak's poles onto the unit circle: clamp rather than reject, the
124+ // caller's value came out of a text file. The gain is the fourth of
125+ // these four clamps, and the one the struct's own doc promised.
100 let fs = f64::from(sample_rate.max(1));126 let fs = f64::from(sample_rate.max(1));
101 let f0 = f64::from(band.freq_hz).clamp(1.0, fs * 0.49);127 let f0 = f64::from(band.freq_hz).clamp(1.0, fs * 0.49);
102 let q = f64::from(band.q).clamp(0.05, 40.0);128 let q = f64::from(band.q).clamp(0.05, 40.0);
103- let a = 10f64.powf(f64::from(band.gain_db) / 40.0);129+ let gain =
130+ f64::from(band.gain_db).clamp(f64::from(MIN_BAND_GAIN_DB), f64::from(MAX_BAND_GAIN_DB));
131+ let a = 10f64.powf(gain / 40.0);
104 let w0 = 2.0 * PI * f0 / fs;132 let w0 = 2.0 * PI * f0 / fs;
105 let (sin_w0, cos_w0) = (w0.sin(), w0.cos());133 let (sin_w0, cos_w0) = (w0.sin(), w0.cos());
106 let alpha = sin_w0 / (2.0 * q);134 let alpha = sin_w0 / (2.0 * q);
@@ -428,4 +456,82 @@ mod tests {
428 );456 );
429 }457 }
430 }458 }
459+
460+ /// A gain a `.edith` line can name, and the pole radius that comes of it.
461+ ///
462+ /// The invariant [`Band`] documents is that out-of-range values are clamped
463+ /// when the coefficients are built, so a deserializer may hand one over
464+ /// unchecked -- and three of the four fields were clamped at
465+ /// [`Coeffs::new`] while `gain_db` was not. `a = 10^(gain_db/40)` feeds the
466+ /// peak's `sqrt(a2/a0)` pole radius straight to 1 as the gain grows, and at
467+ /// a few hundred dB the f32 rounding puts the poles *exactly* on the unit
468+ /// circle: a marginally-stable section that rings for seconds, blowing up
469+ /// the samples until the device clamp turns the whole clip into a
470+ /// full-scale square (in monitoring and in the export alike). This is an
471+ /// arithmetic claim about the pole radius, not an audibility claim: nothing
472+ /// here says what the filter sounds like, only that it is stable.
473+ ///
474+ /// The poles are solved off the normalized coefficients, so this is the
475+ /// filter the sample loop actually runs rather than a restatement of the
476+ /// formula that built it.
477+ #[test]
478+ fn a_gain_a_file_can_name_leaves_the_poles_strictly_inside_the_unit_circle() {
479+ for gain in [
480+ 12.0f32, 40.0, 100.0, 200.0, 400.0, 10_000.0, -200.0, -10_000.0,
481+ ] {
482+ let c = super::Coeffs::new(
483+ &Band {
484+ freq_hz: 1000.0,
485+ gain_db: gain,
486+ q: 1.0,
487+ kind: BandKind::Peak,
488+ },
489+ FS,
490+ );
491+ // The poles of `z^2 + a1 z + a2`, solved: the number the sample
492+ // loop's homogeneous solution is actually made of, and the only
493+ // place a section's stability is decided. `radius` is the larger
494+ // of the two, so a section is stable exactly when it is `< 1`.
495+ let (a1, a2) = (c.a1 as f64, c.a2 as f64);
496+ let disc = (a1 * a1 - 4.0 * a2).max(0.0).sqrt();
497+ let radius = [(-a1 + disc) / 2.0, (-a1 - disc) / 2.0]
498+ .into_iter()
499+ .fold(0.0f64, |m, r| m.max(r.abs()));
500+ assert!(
501+ radius < 0.999,
502+ "gain {gain} dB gives a pole radius of {radius:.9} -- \
503+ the section rings instead of decaying"
504+ );
505+ assert!(
506+ c.b0.is_finite() && c.b1.is_finite() && c.b2.is_finite(),
507+ "gain {gain} dB produced non-finite coefficients {c:?}"
508+ );
509+ }
510+ }
511+
512+ /// The same claim about the samples rather than the coefficients: a
513+ /// full-scale burst through a band whose gain a file named, with the gain
514+ /// far past the card's own 12 dB limit, has to come out at the gain the
515+ /// clamp ceiling *is*. +40 dB is a linear gain of 100, so a full-scale
516+ /// burst peaks at ~100 and that is the answer, not a fault; anything past
517+ /// it is the section ringing rather than a band being loud. Pre-fix, 200 dB
518+ /// and 400 dB are past it by orders of magnitude.
519+ #[test]
520+ fn a_gain_a_file_can_name_does_not_blow_the_samples_up() {
521+ for gain in [40.0f32, 100.0, 200.0, 400.0, 10_000.0] {
522+ let mut out = vec![0.0f32; 48_000 * 2];
523+ // A full-scale 1 kHz burst for a tenth of a second, then silence:
524+ // whatever the section rings into is what shows up after it.
525+ for i in 0..4_800 * 2 {
526+ out[i] = (TAU * 1000.0 * (i / 2) as f32 / FS as f32).sin();
527+ }
528+ EqState::new(&peak(1000.0, gain, 1.0), FS, 2).process(&mut out);
529+ let peak = out.iter().fold(0.0f32, |m, v| m.max(v.abs()));
530+ assert!(
531+ peak.is_finite() && peak < 200.0,
532+ "gain {gain} dB sent a full-scale burst to {peak}: the clamp ceiling is \
533+ +40 dB, a linear gain of 100, and 200x that is a section ringing, not a band"
534+ );
535+ }
536+ }
431 }537 }
crates/engine/src/project.rsmodified+560 -32
@@ -92,6 +92,53 @@ pub const MIN_GAIN_DB: f32 = -60.0;
92 /// a mix bus can take before the limiter is doing all the work.92 /// a mix bus can take before the limiter is doing all the work.
93 pub const MAX_GAIN_DB: f32 = 12.0;93 pub const MAX_GAIN_DB: f32 = 12.0;
94 94
95+/// The longest `[in_us, out_us)` window a [`SubClip`] may show, in
96+/// microseconds: **30 days** of track.
97+///
98+/// A window is a stretch of *source media*, not of the timeline, so its width
99+/// is the length of the recording a caption was cut from -- and that is not
100+/// bounded by anything a day. A two-day conference stream, a lecture archive, a
101+/// long interview session: all produce a palette row whose `out_us` is tens of
102+/// hours, and a ceiling that refuses those refuses the user's own media back at
103+/// them. The value is therefore "past any recording", and nothing more
104+/// sophisticated: 30 days is a round number four orders of magnitude above the
105+/// longest thing anybody captions and three orders below the point where a
106+/// typed number becomes plausible as a duration at all.
107+///
108+/// What it has to clear, concretely, and the honest arithmetic for each:
109+///
110+/// - **The i64 multiply in [`SubClip::window_at`].** `window_us() * into`,
111+/// where `into` is a `u32` frame offset, so at most 4.29e9. It is a
112+/// `saturating_mul`, so this is not about safety -- saturation is total --
113+/// but about the result still *meaning* something: 30 days x 4.29e9 is
114+/// 1.1e22, which does NOT fit an i64. So the multiply saturates for any
115+/// window above `i64::MAX / u32::MAX` = 2.1e9 us (~35 minutes), and 30 days
116+/// is 1200x past that. The value is then finite but the proportion is not
117+/// exact, and `set_window`'s clamp on the answer keeps the result inside the
118+/// window rather than trusting it. That is the real precision cost, and it
119+/// is why this is not "unlimited": past 35 minutes the cut degrades, past
120+/// this it has degraded to "the far end of the window".
121+/// - **`sub_lane_cues`'s f64 mapping.** `(t - in_us) as f64 * per`, where `per`
122+/// is `frames / fps * 1e6 / window_us`. Here f64 exactness genuinely does
123+/// apply: an i64 is exact in f64 to 2^53 = 9.0e15, and 30 days is 2.6e12 --
124+/// about 3.5 orders of magnitude inside it, so the cue mapping is exact and
125+/// not merely close.
126+/// - **Nothing else.** There is no allocation, no index and no length derived
127+/// from a window, so a wider value costs no memory. The ceiling is a claim
128+/// about meaning, not about resource.
129+///
130+/// Past it, the value is not a caption any project holds -- a `.edith` a hand
131+/// edited (or a hostile actor wrote) reaches this with a line the never-empty
132+/// check at the parser cannot see past, because `out_us > in_us` says the
133+/// window is *open* and never how wide it is. Every door -- the parse,
134+/// [`Project::with_subs`], [`Project::place_sub`] -- refuses such a line by
135+/// name, next to every other range check a `.edith` line has to pass. Every
136+/// *composer* instead clamps to it through [`set_window`], which is the only
137+/// function that writes a window; a trim that ran out of window stops at the
138+/// window's end rather than failing, exactly like the frame walls it already
139+/// has.
140+pub const MAX_WINDOW_US: i64 = 30 * 24 * 60 * 60 * 1_000_000;
141+
95 /// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it142 /// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
96 /// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for143 /// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
97 /// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly144 /// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
@@ -636,9 +683,10 @@ impl SubClip {
636 }683 }
637 684
638 /// How much of its track it shows, in microseconds; `>= 1` by the685 /// How much of its track it shows, in microseconds; `>= 1` by the
639- /// never-empty invariant.686+ /// never-empty invariant, and never more than [`MAX_WINDOW_US`] for one
687+ /// that came through a door.
640 pub fn window_us(&self) -> i64 {688 pub fn window_us(&self) -> i64 {
641- self.out_us - self.in_us689+ self.out_us.saturating_sub(self.in_us)
642 }690 }
643 691
644 /// Where in its window the timeline frame `frame` falls, in microseconds --692 /// Where in its window the timeline frame `frame` falls, in microseconds --
@@ -649,9 +697,19 @@ impl SubClip {
649 /// before `frame` is the fraction of the microseconds before it. That is697 /// before `frame` is the fraction of the microseconds before it. That is
650 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins698 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins
651 /// without either of them learning an fps.699 /// without either of them learning an fps.
700+ ///
701+ /// Total arithmetic, and clamped to the window it is cutting: the
702+ /// `saturating_mul` is what a `SubClip` built by a caller rather than a
703+ /// door gets (a hand-built one, a unit test, a future door that forgot the
704+ /// bound) -- a wrapped window would put a caption's clock *before* its own
705+ /// start, and the split that produced it would then hand back two halves
706+ /// whose windows do not meet. The clamp is the never-empty invariant
707+ /// restated: the answer is a point inside `[in_us, out_us]` or nothing.
652 fn window_at(&self, frame: u32) -> i64 {708 fn window_at(&self, frame: u32) -> i64 {
653 let into = i64::from(frame.saturating_sub(self.start));709 let into = i64::from(frame.saturating_sub(self.start));
654- self.in_us + self.window_us() * into / i64::from(self.frames.max(1))710+ let window = self.window_us().max(0);
711+ let at = window.saturating_mul(into) / i64::from(self.frames.max(1));
712+ self.in_us.saturating_add(at.min(window))
655 }713 }
656 }714 }
657 715
@@ -1703,6 +1761,20 @@ impl Project {
1703 )1761 )
1704 .into());1762 .into());
1705 }1763 }
1764+ // The width of that window, which the check above cannot see:
1765+ // [`edith`](crate::edith) asks the same question at the parse
1766+ // and this repeats it, because `with_subs` is the door a
1767+ // hand-built `Project` comes through and a caller is not more
1768+ // trustworthy than a file.
1769+ if s.out_us - s.in_us > MAX_WINDOW_US {
1770+ return Err(format!(
1771+ "{name} caption at {} is a {}us window, past the {}us a caption can hold",
1772+ s.start,
1773+ s.out_us - s.in_us,
1774+ MAX_WINDOW_US
1775+ )
1776+ .into());
1777+ }
1706 if s.track >= palette {1778 if s.track >= palette {
1707 return Err(format!(1779 return Err(format!(
1708 "{name} caption at {} names subtitle track {} of {palette}",1780 "{name} caption at {} names subtitle track {} of {palette}",
@@ -1969,6 +2041,19 @@ impl Project {
1969 )2041 )
1970 .into());2042 .into());
1971 }2043 }
2044+ // The width of that window, which the check above cannot see: the same
2045+ // bound the two file doors hold a placement to
2046+ // ([`edith`](crate::edith)'s parse and [`with_subs`]), asked here
2047+ // because this is the door a *dragged* caption comes through and the
2048+ // hand that dragged it builds the `SubClip` itself.
2049+ if sub.out_us - sub.in_us > MAX_WINDOW_US {
2050+ return Err(format!(
2051+ "that placement is a {}us window, past the {}us a caption can hold",
2052+ sub.out_us - sub.in_us,
2053+ MAX_WINDOW_US
2054+ )
2055+ .into());
2056+ }
1972 if sub.track >= self.subtitles.len() {2057 if sub.track >= self.subtitles.len() {
1973 return Err(format!(2058 return Err(format!(
1974 "it names subtitle track {} of {}",2059 "it names subtitle track {} of {}",
@@ -2197,17 +2282,31 @@ impl Project {
2197 // The words that stay are the words that were there, so the window2282 // The words that stay are the words that were there, so the window
2198 // moves with the head -- a trim, not a slip.2283 // moves with the head -- a trim, not a slip.
2199 Edge::Start => {2284 Edge::Start => {
2200- // Clamped to a window that is still a window: the walls above2285+ // The head moves and the words that stay are the words that
2201- // are frames and the rounding between the two clocks is not2286+ // were there, so `in_us` follows it -- a trim, not a slip.
2202- // exact, and neither is a caller's hand-built placement.2287+ // Falling `in_us` makes the window *wider* (the ceiling bounds
2203- s.in_us = (s.in_us + us_of(i64::from(to) - i64::from(s.start), fps))2288+ // a difference), which is the half of this nothing here can
2204- .clamp(0, s.out_us - 1);2289+ // see: `set_window` is what puts the width back inside.
2290+ set_window(
2291+ s,
2292+ s.in_us
2293+ .saturating_add(us_of(i64::from(to) - i64::from(s.start), fps)),
2294+ s.out_us,
2295+ );
2205 s.frames = s.end() - to;2296 s.frames = s.end() - to;
2206 s.start = to;2297 s.start = to;
2207 }2298 }
2208 Edge::End => {2299 Edge::End => {
2209- s.out_us =2300+ // ...and the tail, for [`set_window`]'s reason: the End room
2210- (s.out_us + us_of(i64::from(to) - i64::from(s.end()), fps)).max(s.in_us + 1);2301+ // is walled at the ceiling, but `set_window` is what holds it
2302+ // for every other composer too, including this one when a
2303+ // caller hands `trim_sub` a `to` past its own room.
2304+ set_window(
2305+ s,
2306+ s.in_us,
2307+ s.out_us
2308+ .saturating_add(us_of(i64::from(to) - i64::from(s.end()), fps)),
2309+ );
2211 s.frames = to - s.start;2310 s.frames = to - s.start;
2212 }2311 }
2213 }2312 }
@@ -2267,10 +2366,17 @@ impl Project {
2267 .get(s.track)2366 .get(s.track)
2268 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())2367 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
2269 .unwrap_or(s.out_us);2368 .unwrap_or(s.out_us);
2369+ // ...and never past [`grow_window`]'s ceiling, which is the
2370+ // wall that matters here: a front-end asks this to draw the
2371+ // drag, then trims to whatever it is told. An engine that
2372+ // offers room its own trim would refuse is a drag that snaps
2373+ // back at the end of the gesture -- so the room stops where
2374+ // the window stops, and the two agree by construction.
2375+ let wall_us = track_end.min(s.in_us.saturating_add(MAX_WINDOW_US));
2270 (2376 (
2271 s.start + 1,2377 s.start + 1,
2272 s.start2378 s.start
2273- .saturating_add(frames_of(track_end - s.in_us).max(1))2379+ .saturating_add(frames_of((wall_us - s.in_us).max(1)))
2274 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),2380 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
2275 )2381 )
2276 }2382 }
@@ -3395,7 +3501,15 @@ impl Project {
3395 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {3501 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
3396 if let Some(idx) = sub {3502 if let Some(idx) = sub {
3397 data.subs[idx].frames += data.subs[idx + 1].frames;3503 data.subs[idx].frames += data.subs[idx + 1].frames;
3398- data.subs[idx].out_us = data.subs[idx + 1].out_us;3504+ // The left half's `in_us`, the right half's `out_us` -- which
3505+ // is the SUM of two legal widths, because `sub_joinable` has
3506+ // just established that the two halves are consecutive in the
3507+ // *source* (`next.in_us == subs[idx].out_us`). Neither half
3508+ // broke the ceiling and the whole does, so this is a composer
3509+ // a per-arm check on one writer could never have found:
3510+ // `set_window` is what makes the closed set closed.
3511+ let (in_us, out_us) = (data.subs[idx].in_us, data.subs[idx + 1].out_us);
3512+ set_window(&mut data.subs[idx], in_us, out_us);
3399 data.subs.remove(idx + 1);3513 data.subs.remove(idx + 1);
3400 debug_assert!(subs_sorted_disjoint(&data.subs));3514 debug_assert!(subs_sorted_disjoint(&data.subs));
3401 }3515 }
@@ -5608,6 +5722,56 @@ fn us_of(frames: i64, fps: f64) -> i64 {
5608 }5722 }
5609 }5723 }
5610 5724
5725+/// **The one function in this file that writes a caption's window.** Every
5726+/// composer -- a trim, a split, a ripple, a group follow, a rejoin -- routes
5727+/// through it, and the invariant it holds is total:
5728+///
5729+/// ```text
5730+/// 0 <= in_us and in_us < out_us and out_us - in_us <= MAX_WINDOW_US
5731+/// ```
5732+///
5733+/// which is the never-empty invariant plus the width ceiling, restated as one
5734+/// shape both ends of it come from. Note that the ceiling bounds a
5735+/// **difference**, which is why a per-arm check is not enough and this is:
5736+///
5737+/// - Growing `out_us` (a tail trim) makes the width larger, so the *upper*
5738+/// wall bites.
5739+/// - Falling `in_us` (a head trim) makes the width larger too, from the other
5740+/// side -- so bounding `in_us` alone, which is what a head trim's own clamp
5741+/// (`in_us <= out_us - 1`) does, says nothing at all about the ceiling.
5742+/// - A rejoin takes the left half's `in_us` and the right half's `out_us`, and
5743+/// the two halves are consecutive in the *source* (that is what
5744+/// [`sub_joinable`] requires), so the joined width is the **sum** of two
5745+/// legal widths. Each half passes its own door; the whole does not.
5746+///
5747+/// Three rounds of review each found one more composer this way, so the
5748+/// function is the fix rather than any single call site: clamping a new
5749+/// caller into shape is a two-line change, and forgetting one is silent.
5750+/// `every_window_write_goes_through_set_window` (in the tests below) is the
5751+/// other half of that promise -- it scans the file and fails if a write
5752+/// appears anywhere else.
5753+///
5754+/// **Why it clamps where the doors refuse.** The doors -- the parser,
5755+/// [`Project::with_subs`], [`Project::place_sub`] -- see a value on the way
5756+/// IN, from a file or a foreign caller, where nobody was mid-gesture, so a
5757+/// value that wide is named and refused rather than quietly changed. Every
5758+/// composer below is an edit a person is watching happen, so the same value is
5759+/// clamped to the end of the window: a drag that stops, exactly like the frame
5760+/// walls these trims already apply.
5761+fn set_window(s: &mut SubClip, in_us: i64, out_us: i64) {
5762+ let in_us = in_us.max(0);
5763+ // The `+ 1` is the never-empty invariant: the window is open, always, so a
5764+ // composer that would otherwise clamp it shut lands on one microsecond.
5765+ let out_us = out_us.clamp(in_us + 1, in_us.saturating_add(MAX_WINDOW_US));
5766+ s.in_us = in_us;
5767+ s.out_us = out_us;
5768+ debug_assert!(
5769+ s.in_us >= 0 && s.out_us > s.in_us && s.out_us - s.in_us <= MAX_WINDOW_US,
5770+ "set_window left an illegal window: {:?}",
5771+ (s.in_us, s.out_us)
5772+ );
5773+}
5774+
5611 /// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,5775 /// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
5612 /// dropping what is inside the hole, splitting what straddles it and trimming5776 /// dropping what is inside the hole, splitting what straddles it and trimming
5613 /// what overlaps an edge. The windows follow the cut by proportion5777 /// what overlaps an edge. The windows follow the cut by proportion
@@ -5620,24 +5784,31 @@ fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
5620 continue;5784 continue;
5621 }5785 }
5622 if s.start < start {5786 if s.start < start {
5623- out.push(SubClip {5787+ let cut = s.window_at(start);
5788+ let mut head = SubClip {
5624 frames: start - s.start,5789 frames: start - s.start,
5625- out_us: s.window_at(start),
5626 // Both pieces lose the group id, for [`clear`]'s reason: one5790 // Both pieces lose the group id, for [`clear`]'s reason: one
5627 // id on two boxes of one lane is the one thing it may never5791 // id on two boxes of one lane is the one thing it may never
5628 // mean.5792 // mean.
5629 link: None,5793 link: None,
5630 ..s5794 ..s
5631- });5795+ };
5796+ // `window_at` already answers inside the window, and `set_window`
5797+ // is the shape that says so once, for every composer, rather than
5798+ // leaving each of them to re-derive it.
5799+ set_window(&mut head, s.in_us, cut);
5800+ out.push(head);
5632 }5801 }
5633 if s.end() > end {5802 if s.end() > end {
5634- out.push(SubClip {5803+ let cut = s.window_at(end);
5804+ let mut tail = SubClip {
5635 start: end,5805 start: end,
5636 frames: s.end() - end,5806 frames: s.end() - end,
5637- in_us: s.window_at(end),
5638 link: None,5807 link: None,
5639 ..s5808 ..s
5640- });5809+ };
5810+ set_window(&mut tail, cut, s.out_us);
5811+ out.push(tail);
5641 }5812 }
5642 }5813 }
5643 *subs = out;5814 *subs = out;
@@ -5651,22 +5822,21 @@ fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
5651 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {5822 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
5652 let s = subs[idx];5823 let s = subs[idx];
5653 let cut = s.window_at(at);5824 let cut = s.window_at(at);
5654- subs[idx] = SubClip {5825+ let mut head = SubClip {
5655 frames: at - s.start,5826 frames: at - s.start,
5656- out_us: cut,
5657 link: None,5827 link: None,
5658 ..s5828 ..s
5659 };5829 };
5660- subs.insert(5830+ set_window(&mut head, s.in_us, cut);
5661- idx + 1,5831+ subs[idx] = head;
5662- SubClip {5832+ let mut tail = SubClip {
5663- start: at,5833+ start: at,
5664- frames: s.end() - at,5834+ frames: s.end() - at,
5665- in_us: cut,5835+ link: None,
5666- link: None,5836+ ..s
5667- ..s5837+ };
5668- },5838+ set_window(&mut tail, cut, s.out_us);
5669- );5839+ subs.insert(idx + 1, tail);
5670 }5840 }
5671 for s in subs.iter_mut().filter(|s| s.start >= at) {5841 for s in subs.iter_mut().filter(|s| s.start >= at) {
5672 s.start += len;5842 s.start += len;
@@ -5704,15 +5874,21 @@ fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
5704 /// the window it already shows over the frames it already takes.5874 /// the window it already shows over the frames it already takes.
5705 fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {5875 fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
5706 let per_frame = s.window_us() / i64::from(s.frames.max(1));5876 let per_frame = s.window_us() / i64::from(s.frames.max(1));
5877+ // The `saturating_mul` keeps a `SubClip` that reached here without a door
5878+ // behind it from wrapping the window negative; `set_window` is what keeps
5879+ // the result legal rather than merely finite. This is the group-follow twin
5880+ // of [`Project::trim_sub`], and it reaches the same field from both edges --
5881+ // so a fix that only walled the primary trim's End arm left the head (and
5882+ // the whole group path) open.
5707 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));5883 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
5708 match edge {5884 match edge {
5709 Edge::Start => {5885 Edge::Start => {
5710- s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1);5886+ set_window(s, s.in_us.saturating_add(by(s.start, to)), s.out_us);
5711 s.frames = s.end() - to;5887 s.frames = s.end() - to;
5712 s.start = to;5888 s.start = to;
5713 }5889 }
5714 Edge::End => {5890 Edge::End => {
5715- s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1);5891+ set_window(s, s.in_us, s.out_us.saturating_add(by(s.end(), to)));
5716 s.frames = to - s.start;5892 s.frames = to - s.start;
5717 }5893 }
5718 }5894 }
@@ -10865,4 +11041,356 @@ mod tests {
10865 assert_eq!(p.subtitles()[0].label, "two");11041 assert_eq!(p.subtitles()[0].label, "two");
10866 assert_ne!(p.subtitles(), palette.as_slice(), "and it is not back");11042 assert_ne!(p.subtitles(), palette.as_slice(), "and it is not back");
10867 }11043 }
11044+
11045+ /// Finds every line that **writes** a caption's clock, in three forms: an
11046+ /// assignment through any operator (`.out_us = `, `.out_us += `,
11047+ /// `.out_us <<= `), a struct-literal field (`out_us: ...`) and the
11048+ /// shorthand form (`out_us,`). A `let` binding is skipped for the literal
11049+ /// forms only, so `let x: &mut SubClip = ..; (*x).in_us = 5;` is still
11050+ /// caught while `let out_us = s.out_us;` is not.
11051+ ///
11052+ /// The operator list is `=` plus one assignment operator each, and
11053+ /// deliberately excludes `<=`: the first version of this matcher counted
11054+ /// `s.out_us <= s.in_us` as a write, which would have flagged every
11055+ /// never-empty check in the file.
11056+ fn window_writes(text: &str) -> Vec<(usize, String)> {
11057+ const FIELDS: [&str; 2] = ["in_us", "out_us"];
11058+ const OPS: [&str; 11] = [
11059+ "=", "+=", "-=", "*=", "/=", "%=", "^=", "&=", "|=", "<<=", ">>=",
11060+ ];
11061+ let mut found = Vec::new();
11062+ for (n, raw) in text.lines().enumerate() {
11063+ let line = raw.trim();
11064+ if line.starts_with("//") {
11065+ continue;
11066+ }
11067+ let is_binding = line.starts_with("let ");
11068+ // `let (a, b) = ..` is a tuple pattern, not a struct literal: the
11069+ // commas there bind names. `let half = SubClip { frames: n, in_us,
11070+ // out_us, ..s };` is the opposite -- the same commas are shorthand
11071+ // fields -- and what separates them is the paren, not the `let`.
11072+ let tuple_pattern = line.starts_with("let (");
11073+ for field in FIELDS {
11074+ let access = format!(".{field}");
11075+ if let Some(at) = line.find(&access) {
11076+ let after = &line[at + access.len()..];
11077+ let after = after.trim_start();
11078+ if OPS
11079+ .iter()
11080+ .any(|op| after.starts_with(op) && !after[op.len()..].starts_with('='))
11081+ {
11082+ found.push((n + 1, line.to_owned()));
11083+ continue;
11084+ }
11085+ }
11086+ // A bare name: a literal field, a shorthand, or a local
11087+ // binding. Skipped when a `.` or an identifier character
11088+ // precedes it -- that is a read, not a field being set.
11089+ //
11090+ // The `let` exclusion is per-occurrence and keyed on what
11091+ // FOLLOWS, not on the line. `let out_us = s.out_us;` names a
11092+ // local, so the `=` form is skipped; but `let tail = SubClip {
11093+ // in_us: cut, out_us: s.out_us, ..s };` is a struct literal
11094+ // behind a `let`, and an earlier version of this matcher
11095+ // skipped the whole line for being a `let` -- so that shape,
11096+ // which is exactly what a plausible composer looks like, went
11097+ // through green. Keyed on the follower, a `let` hides nothing.
11098+ for (at, _) in line.match_indices(field) {
11099+ let preceded_by_name = line[..at]
11100+ .chars()
11101+ .next_back()
11102+ .is_some_and(|c| c == '.' || c.is_alphanumeric() || c == '_');
11103+ if preceded_by_name {
11104+ continue;
11105+ }
11106+ let after = line[at + field.len()..].trim_start();
11107+ let sets_a_field =
11108+ after.starts_with(':') || (after.starts_with(',') && !tuple_pattern);
11109+ let names_a_local = after.starts_with('=') && !after[1..].starts_with('=');
11110+ if sets_a_field || (names_a_local && !is_binding) {
11111+ found.push((n + 1, line.to_owned()));
11112+ break;
11113+ }
11114+ }
11115+ }
11116+ }
11117+ found
11118+ }
11119+
11120+ /// A **heuristic guard**, not a proof. The honest reading of a green here
11121+ /// is the residual risk in this comment, not the green itself.
11122+ ///
11123+ /// Three rounds of review each found one more composer a per-arm check had
11124+ /// missed -- a tail trim, a head trim, a rejoin that SUMS two legal
11125+ /// widths -- and each produced the same failure: the editor wrote a
11126+ /// `.edith` its own loader then refused, with no in-app way back. The
11127+ /// invariant is now structural in the code (every composer calls
11128+ /// [`set_window`]); this is what keeps that structure from quietly losing
11129+ /// a caller.
11130+ ///
11131+ /// **Why this is a scan and not the compiler**, which is the better answer
11132+ /// and was priced rather than skipped: making `in_us`/`out_us` private to
11133+ /// this module turns every outside write into a compile error, which no
11134+ /// one-token edit can defeat. It costs 74 `SubClip` construction sites
11135+ /// (31 of them in this crate's own integration tests) plus a public
11136+ /// constructor, and it reaches `crates/app`'s `timeline_edit.rs` and
11137+ /// `timeline_math.rs`, which other lanes own. That is a refactor of a
11138+ /// door's public shape rather than a bound, and the wrong size for this
11139+ /// lane -- so the guard stands here with its limits written down instead.
11140+ ///
11141+ /// **Residual risk, by class, most likely first.** These are not all
11142+ /// equally hypothetical; the first is the one a real composer would reach
11143+ /// for, and it is the one this matcher cannot see at all:
11144+ ///
11145+ /// 1. **Field-less writes.** `*a = *b;`, `*a = other;`,
11146+ /// `std::mem::swap(a, b)`, `a.clone_from(b)`, and any macro that
11147+ /// expands to a field write (`bump!(s.out_us, by)`). None of these ever
11148+ /// spell `in_us` or `out_us` on the line, so `window_writes` returns
11149+ /// nothing for all of them. A *helper* that writes the field directly IS
11150+ /// caught; it is specifically the whole-struct and macro forms that go
11151+ /// through. This is the class most likely to be used, and it is
11152+ /// unmatched by construction rather than by oversight.
11153+ /// 2. **A rename.** The matcher keys on the literal strings `in_us` and
11154+ /// `out_us`. Renaming the fields silences it entirely while it stays
11155+ /// green -- the sharpest failure here, because the guard is supposed to
11156+ /// be the thing that notices a rule drifting.
11157+ /// 3. **A writer inside a test.** `/tests/` paths and `mod tests` blocks
11158+ /// are cut. A test cannot produce a file a user loses, so the line is
11159+ /// drawn there deliberately, not by omission.
11160+ /// 4. **A file the walk does not reach**: a path outside `crates/`, or one
11161+ /// under a directory named `target`, `.git` or `vendor`.
11162+ ///
11163+ /// What the matcher DOES now cover, after four rounds of it not doing so:
11164+ /// every assignment operator; struct-literal fields and the shorthand form,
11165+ /// including behind a `let`; writes through an indirect `&mut`; and every
11166+ /// `.rs` under `crates/` with no filter on what the file contains, so a
11167+ /// glob import or a type alias can no longer hide a module.
11168+ #[test]
11169+ fn every_window_write_outside_set_window_is_named() {
11170+ // `CARGO_MANIFEST_DIR`, not `file!()`: a test runs with the WORKSPACE
11171+ // root as its working directory, so `file!()`'s crate-relative path
11172+ // does not resolve from where the binary actually starts.
11173+ let workspace = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
11174+ .parent()
11175+ .and_then(std::path::Path::parent)
11176+ .expect("crates/engine sits two levels under the workspace root")
11177+ .to_path_buf();
11178+ // Every line in the workspace that names a clock and is not a
11179+ // composer, each with its reason. A new entry is a claim someone has
11180+ // to defend in review, which is the point of writing the list out.
11181+ let allowed = [
11182+ ("pub in_us: i64,", "the field declaration"),
11183+ ("pub out_us: i64,", "the field declaration"),
11184+ (
11185+ "fn set_window(s: &mut SubClip, in_us: i64, out_us: i64) {",
11186+ "set_window's own signature",
11187+ ),
11188+ ("s.in_us = in_us;", "set_window"),
11189+ ("s.out_us = out_us;", "set_window"),
11190+ (
11191+ "set_window(&mut data.subs[idx], in_us, out_us);",
11192+ "regroup naming the two values it is about to set",
11193+ ),
11194+ ("in_us: micros(f[3], n)?,", "edith.rs: the parse door"),
11195+ ("out_us: micros(f[4], n)?,", "edith.rs: the parse door"),
11196+ // Non-test helpers that build a value to hand `place_sub`, which is
11197+ // a door. Not composers: nobody was mid-gesture, which is exactly
11198+ // why a door refuses where a composer clamps.
11199+ (
11200+ "in_us: 0,",
11201+ "sweep.rs caption helper, and timeline_edit.rs's palette row, -> place_sub",
11202+ ),
11203+ (
11204+ "out_us: i64::from(frames) * 1_000_000,",
11205+ "sweep.rs caption helper -> place_sub",
11206+ ),
11207+ (
11208+ "frames: frames_of_us(out_us, self.fps),",
11209+ "timeline_edit.rs's palette row -> place_sub",
11210+ ),
11211+ (
11212+ "out_us,",
11213+ "timeline_edit.rs's palette row shorthand -> place_sub",
11214+ ),
11215+ ];
11216+
11217+ let mut found: Vec<String> = Vec::new();
11218+ let (mut files, mut lines) = (0usize, 0usize);
11219+ let mut seen_app = false;
11220+ for (file, text) in read_workspace_rust(&workspace) {
11221+ // Test code, by path or by module: a test builds `SubClip`s by hand
11222+ // and its value is not one the loader ever reads, so the 31 sites in
11223+ // `crates/engine/tests/` and three in `crates/app/src/tests/` are
11224+ // not composers. A real limit rather than a technicality -- the
11225+ // guard does not cover a writer hidden inside a test -- but a test
11226+ // cannot produce a file a user loses, so it is where the line goes.
11227+ let path = file.to_string_lossy().replace('\\', "/");
11228+ if path.contains("/tests/") {
11229+ continue;
11230+ }
11231+ let code = match text.find("\n#[cfg(test)]\nmod tests {") {
11232+ Some(at) => &text[..at],
11233+ None => text.as_str(),
11234+ };
11235+ lines += code.lines().count();
11236+ files += 1;
11237+ seen_app |= path.contains("crates/app/");
11238+ for (n, line) in window_writes(code) {
11239+ if !allowed.iter().any(|(text, _)| *text == line) {
11240+ let at = file.strip_prefix(&workspace).unwrap_or(&file);
11241+ found.push(format!("{}:{n}: {line}", at.display()));
11242+ }
11243+ }
11244+ }
11245+ // A floor, not a census: the walk now opens EVERY `.rs` under
11246+ // `crates/` that is not test code -- 86 files and ~77,600 lines today,
11247+ // which is 141 files and ~116,000 before `/tests/` and `mod tests` are
11248+ // cut. The point is only to catch a walk rooted in the wrong place,
11249+ // which reads a file or two.
11250+ // The `seen_app` half is the one that matters: the two-file version of
11251+ // this guard read `project.rs` and `edith.rs` and was silently
11252+ // certifying a claim about the app it had never opened, and the
11253+ // `contains("SubClip")` filter that came next
11254+ // was the same mistake wearing a derived hat -- a file that reached
11255+ // the type by glob import or alias was never opened either.
11256+ assert!(
11257+ lines > 70_000 && files >= 80 && seen_app,
11258+ "the walk read {lines} lines in {files} files (app reached: \
11259+ {seen_app}) -- it is not covering the workspace, and a guard that \
11260+ reads nothing is worse than no guard because it reads as one"
11261+ );
11262+ // The assertion this whole test exists for. It was DELETED by a clumsy
11263+ // edit while the coverage floor above was being retuned, and for a
11264+ // moment the test reported green while `found` held a real offender --
11265+ // the fourth version of this guard failing in the one way that looks
11266+ // exactly like success. If you retune anything here, check this line
11267+ // still exists.
11268+ assert!(
11269+ found.is_empty(),
11270+ "a caption window is written outside set_window:\n {}",
11271+ found.join("\n ")
11272+ );
11273+ }
11274+
11275+ /// The blind spot, pinned as cases. Every one of these is a write, and the
11276+ /// guard exists because each of its earlier versions caught none of them --
11277+ /// `s.out_us += by(...)` being a one-token edit that made it green while a
11278+ /// grouped caption really did grow past the ceiling. A matcher that has
11279+ /// quietly stopped matching is the failure mode that looks most like a
11280+ /// pass, so it gets its own test rather than a comment.
11281+ ///
11282+ /// The last group is the opposite: the field-less forms that are a write
11283+ /// and that this matcher CANNOT see. They are asserted to be missed, on
11284+ /// purpose, so that the day someone can match them the test says so --
11285+ /// and so nobody reads this file as claiming more than it does.
11286+ #[test]
11287+ fn the_window_write_matcher_catches_the_ways_a_composer_hides() {
11288+ for (what, code) in [
11289+ (
11290+ "the one-token compound assignment",
11291+ " s.out_us += by(s.end(), to);",
11292+ ),
11293+ ("a plain compound assignment", " s.in_us -= 1;"),
11294+ ("a shift-assign", " s.out_us <<= 1;"),
11295+ (
11296+ "a write through a &mut the matcher cannot see past",
11297+ " let x: &mut SubClip = q; (*x).in_us = 5;",
11298+ ),
11299+ (
11300+ "a struct literal",
11301+ " out.push(SubClip { in_us: 0, out_us: 1, ..s });",
11302+ ),
11303+ (
11304+ "the shorthand form",
11305+ " SubClip { in_us, out_us, ..s }",
11306+ ),
11307+ (
11308+ "a struct literal behind a `let`, which the old line-wide `let` \
11309+ exclusion skipped whole",
11310+ " let tail = SubClip { in_us: cut, out_us: s.out_us, ..s };",
11311+ ),
11312+ (
11313+ "a struct literal behind a `let` using the shorthand too",
11314+ " let half = SubClip { frames: n, in_us, out_us, ..s };",
11315+ ),
11316+ ] {
11317+ assert!(
11318+ !window_writes(code).is_empty(),
11319+ "the matcher misses {what}: {code:?}"
11320+ );
11321+ }
11322+ // ...and the other side, so the allowlist is not padded with reads.
11323+ for quiet in [
11324+ " if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {",
11325+ " debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);",
11326+ " let out_us = s.out_us;",
11327+ " (next.start == frame && next.in_us == subs[idx].out_us)",
11328+ " let total = s.out_us - s.in_us;",
11329+ ] {
11330+ assert!(
11331+ window_writes(quiet).is_empty(),
11332+ "the matcher flags a read as a write: {quiet:?}"
11333+ );
11334+ }
11335+ // The class this matcher CANNOT see, asserted as missed. Each of these
11336+ // really does write a caption's window and none of them spell the field
11337+ // name, so a field matcher returns nothing -- that is a property of the
11338+ // approach, not a bug to be fixed here, and the test exists so the
11339+ // doc comment's residual-risk list cannot quietly grow a claim this
11340+ // matcher has not earned. If one of these ever starts matching, this
11341+ // test fails and asks which side of the line moved.
11342+ for unmatchable in [
11343+ " *a = *b;",
11344+ " *a = other;",
11345+ " std::mem::swap(a, b);",
11346+ " a.clone_from(b);",
11347+ " bump!(s.out_us, by);",
11348+ ] {
11349+ assert!(
11350+ window_writes(unmatchable).is_empty(),
11351+ "the matcher now matches a field-less form it documented as \
11352+ unmatched -- update the residual-risk list too: {unmatchable:?}"
11353+ );
11354+ }
11355+ }
11356+
11357+ /// Every `.rs` under the workspace, paired with its text. Recursive
11358+ /// because the set of files that can name `SubClip` is a fact about the
11359+ /// tree, and a hardcoded pair of names goes stale the moment a lane adds a
11360+ /// module -- which is how the two-file version of this guard came to
11361+ /// certify a claim about `crates/app` it had never read.
11362+ fn read_workspace_rust(root: &std::path::Path) -> Vec<(std::path::PathBuf, String)> {
11363+ let mut out = Vec::new();
11364+ let mut stack = vec![root.to_path_buf()];
11365+ while let Some(dir) = stack.pop() {
11366+ let Ok(entries) = std::fs::read_dir(&dir) else {
11367+ continue;
11368+ };
11369+ for entry in entries.flatten() {
11370+ let path = entry.path();
11371+ if path.is_dir() {
11372+ // `target` is not source and `vendor` is not ours to rule on.
11373+ let skip = path
11374+ .file_name()
11375+ .is_some_and(|n| n == "target" || n == ".git" || n == "vendor");
11376+ if !skip {
11377+ stack.push(path);
11378+ }
11379+ // EVERY `.rs`, with no filter on what it contains. The filter
11380+ // that was here (`text.contains("SubClip")`) was a name-based
11381+ // guess about which files can reach the type, and a glob import
11382+ // or a type alias defeats it exactly as it defeats a
11383+ // hardcoded file list: a new module holding the struct behind
11384+ // `use engine::project::*;` was never opened, and stayed green.
11385+ // The scan is text-only and the tree is small, so the honest
11386+ // thing costs nothing here.
11387+ } else if path.extension().is_some_and(|e| e == "rs")
11388+ && let Ok(text) = std::fs::read_to_string(&path)
11389+ {
11390+ out.push((path, text));
11391+ }
11392+ }
11393+ }
11394+ out
11395+ }
10868 }11396 }
crates/engine/src/scale.rsmodified+353 -61
@@ -339,7 +339,12 @@ pub fn compose_i420(
339 /// [`align`]'s reason.339 /// [`align`]'s reason.
340 pub fn crop_rect(src_w: u32, src_h: u32, t: &TransformParams) -> Rect {340 pub fn crop_rect(src_w: u32, src_h: u32, t: &TransformParams) -> Rect {
341 if src_w == 0 || src_h == 0 {341 if src_w == 0 || src_h == 0 {
342- return Rect { x: 0, y: 0, w: 0, h: 0 };342+ return Rect {
343+ x: 0,
344+ y: 0,
345+ w: 0,
346+ h: 0,
347+ };
343 }348 }
344 let (cl, cr) = (t.crop_l.clamp(0.0, 0.5), t.crop_r.clamp(0.0, 0.5));349 let (cl, cr) = (t.crop_l.clamp(0.0, 0.5), t.crop_r.clamp(0.0, 0.5));
345 let (ct, cb) = (t.crop_t.clamp(0.0, 0.5), t.crop_b.clamp(0.0, 0.5));350 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(
375 canvas_w: u32,380 canvas_w: u32,
376 canvas_h: u32,381 canvas_h: u32,
377 ) -> (Rect, Rect) {382 ) -> (Rect, Rect) {
378- let empty = Rect { x: 0, y: 0, w: 0, h: 0 };383+ let empty = Rect {
384+ x: 0,
385+ y: 0,
386+ w: 0,
387+ h: 0,
388+ };
379 if dst.is_empty() || src.is_empty() || canvas_w == 0 || canvas_h == 0 {389 if dst.is_empty() || src.is_empty() || canvas_w == 0 || canvas_h == 0 {
380 return (dst, src);390 return (dst, src);
381 }391 }
@@ -390,10 +400,29 @@ pub fn transformed_dst_rect(
390 let cap_h = i64::from(canvas_h.max(1)) * 1024;400 let cap_h = i64::from(canvas_h.max(1)) * 1024;
391 let new_w = ((f64::from(dst.w) * scale).round() as i64).clamp(1, cap_w);401 let new_w = ((f64::from(dst.w) * scale).round() as i64).clamp(1, cap_w);
392 let new_h = ((f64::from(dst.h) * scale).round() as i64).clamp(1, cap_h);402 let new_h = ((f64::from(dst.h) * scale).round() as i64).clamp(1, cap_h);
393- let pos_x = if t.pos_x.is_finite() { f64::from(t.pos_x) } else { 0.0 };403+ // ...and the position, to the same ceiling, for the same reason. A
394- let pos_y = if t.pos_y.is_finite() { f64::from(t.pos_y) } else { 0.0 };404+ // `transform` line takes any finite `f32` for `pos_x`/`pos_y` (there is
395- let cx = i64::from(dst.x) + i64::from(dst.w) / 2 + (f64::from(canvas_w) * pos_x).round() as i64;405+ // no per-field clamp at the parse, unlike `scale`'s use of the value), and
396- let cy = i64::from(dst.y) + i64::from(dst.h) / 2 + (f64::from(canvas_h) * pos_y).round() as i64;406+ // `f64 as i64` *saturates* -- so a hostile 3e38 arrived here as `i64::MAX`
407+ // and the additions below, not the cast, are what overflowed: a panic on
408+ // the compositing thread in a debug build and a silently wrapped position
409+ // in a release one. A cap in canvas fractions is the same 1024 the scale
410+ // gets, and a box pushed that far off the canvas is long gone either way:
411+ // it comes back as the two empty rects the function already answers with.
412+ let pos_x = if t.pos_x.is_finite() {
413+ f64::from(t.pos_x)
414+ } else {
415+ 0.0
416+ };
417+ let pos_y = if t.pos_y.is_finite() {
418+ f64::from(t.pos_y)
419+ } else {
420+ 0.0
421+ };
422+ let cx = (i64::from(dst.x) + i64::from(dst.w) / 2)
423+ .saturating_add((f64::from(canvas_w) * pos_x.clamp(-1024.0, 1024.0)).round() as i64);
424+ let cy = (i64::from(dst.y) + i64::from(dst.h) / 2)
425+ .saturating_add((f64::from(canvas_h) * pos_y.clamp(-1024.0, 1024.0)).round() as i64);
397 // The full box the transform describes, unclamped -- it may start426 // The full box the transform describes, unclamped -- it may start
398 // negative or run past either edge, which is exactly what "moved off the427 // negative or run past either edge, which is exactly what "moved off the
399 // canvas" means.428 // canvas" means.
@@ -424,12 +453,30 @@ pub fn transformed_dst_rect(
424 let src_bottom = i64::from(src.h) * bottom / new_h;453 let src_bottom = i64::from(src.h) * bottom / new_h;
425 let src_x = src.x + src_left as u32;454 let src_x = src.x + src_left as u32;
426 let src_y = src.y + src_top as u32;455 let src_y = src.y + src_top as u32;
427- let (src_x, src_w_) = align(src_x, src.w.saturating_sub((src_left + src_right) as u32), src_w);456+ let (src_x, src_w_) = align(
428- let (src_y, src_h_) = align(src_y, src.h.saturating_sub((src_top + src_bottom) as u32), src_h);457+ src_x,
458+ src.w.saturating_sub((src_left + src_right) as u32),
459+ src_w,
460+ );
461+ let (src_y, src_h_) = align(
462+ src_y,
463+ src.h.saturating_sub((src_top + src_bottom) as u32),
464+ src_h,
465+ );
429 466
430 (467 (
431- Rect { x: dst_x, y: dst_y, w: dst_w, h: dst_h },468+ Rect {
432- Rect { x: src_x, y: src_y, w: src_w_, h: src_h_ },469+ x: dst_x,
470+ y: dst_y,
471+ w: dst_w,
472+ h: dst_h,
473+ },
474+ Rect {
475+ x: src_x,
476+ y: src_y,
477+ w: src_w_,
478+ h: src_h_,
479+ },
433 )480 )
434 }481 }
435 482
@@ -492,11 +539,7 @@ pub fn rotate_i420_90s_into(
492 rotate_plane_into(y, w as usize, h as usize, steps, &mut out.0);539 rotate_plane_into(y, w as usize, h as usize, steps, &mut out.0);
493 rotate_plane_into(u, cw, ch, steps, &mut out.1);540 rotate_plane_into(u, cw, ch, steps, &mut out.1);
494 rotate_plane_into(v, cw, ch, steps, &mut out.2);541 rotate_plane_into(v, cw, ch, steps, &mut out.2);
495- if steps == 2 {542+ if steps == 2 { (w, h) } else { (h, w) }
496- (w, h)
497- } else {
498- (h, w)
499- }
500 }543 }
501 544
502 /// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise,545 /// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise,
@@ -758,7 +801,13 @@ impl Composer {
758 (cy, cu, cv, crop.w, crop.h)801 (cy, cu, cv, crop.w, crop.h)
759 } else {802 } else {
760 rot_buf = rotate_i420_90s(cy, cu, cv, crop.w, crop.h, steps);803 rot_buf = rotate_i420_90s(cy, cu, cv, crop.w, crop.h, steps);
761- (&rot_buf.0[..], &rot_buf.1[..], &rot_buf.2[..], rot_buf.3, rot_buf.4)804+ (
805+ &rot_buf.0[..],
806+ &rot_buf.1[..],
807+ &rot_buf.2[..],
808+ rot_buf.3,
809+ rot_buf.4,
810+ )
762 };811 };
763 812
764 let (dst, src) = fit_rect(rw, rh, canvas_w, canvas_h, self.policy);813 let (dst, src) = fit_rect(rw, rh, canvas_w, canvas_h, self.policy);
@@ -783,7 +832,16 @@ impl Composer {
783 scaled.1.resize(ccw * cch, 0);832 scaled.1.resize(ccw * cch, 0);
784 scaled.2.resize(ccw * cch, 0);833 scaled.2.resize(ccw * cch, 0);
785 scale_i420(834 scale_i420(
786- fy, fu, fv, sw, sh, &mut scaled.0, &mut scaled.1, &mut scaled.2, dw, dh,835+ fy,
836+ fu,
837+ fv,
838+ sw,
839+ sh,
840+ &mut scaled.0,
841+ &mut scaled.1,
842+ &mut scaled.2,
843+ dw,
844+ dh,
787 );845 );
788 (&scaled.0[..], &scaled.1[..], &scaled.2[..])846 (&scaled.0[..], &scaled.1[..], &scaled.2[..])
789 };847 };
@@ -811,7 +869,11 @@ impl Composer {
811 /// backstop. `a`/`b`'s planes must be the same length pairwise (Y with Y, U869 /// backstop. `a`/`b`'s planes must be the same length pairwise (Y with Y, U
812 /// with U, V with V); a mismatched pair panics rather than silently870 /// with U, V with V); a mismatched pair panics rather than silently
813 /// truncating a picture.871 /// truncating a picture.
814-pub fn blend_i420(a: (&[u8], &[u8], &[u8]), b: (&[u8], &[u8], &[u8]), t: f32) -> (Vec<u8>, Vec<u8>, Vec<u8>) {872+pub fn blend_i420(
873+ a: (&[u8], &[u8], &[u8]),
874+ b: (&[u8], &[u8], &[u8]),
875+ t: f32,
876+) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
815 let t = t.clamp(0.0, 1.0);877 let t = t.clamp(0.0, 1.0);
816 let plane = |a: &[u8], b: &[u8]| -> Vec<u8> {878 let plane = |a: &[u8], b: &[u8]| -> Vec<u8> {
817 assert_eq!(a.len(), b.len(), "blend_i420: mismatched plane sizes");879 assert_eq!(a.len(), b.len(), "blend_i420: mismatched plane sizes");
@@ -1466,7 +1528,12 @@ mod tests {
1466 };1528 };
1467 assert_eq!(1529 assert_eq!(
1468 crop_rect(100, 100, &t),1530 crop_rect(100, 100, &t),
1469- Rect { x: 10, y: 0, w: 70, h: 100 },1531+ Rect {
1532+ x: 10,
1533+ y: 0,
1534+ w: 70,
1535+ h: 100
1536+ },
1470 "10% off the left, 20% off the right, nothing off top or bottom"1537 "10% off the left, 20% off the right, nothing off top or bottom"
1471 );1538 );
1472 // Opposing crops clamp to 0.5 a side rather than meeting or crossing.1539 // Opposing crops clamp to 0.5 a side rather than meeting or crossing.
@@ -1478,7 +1545,15 @@ mod tests {
1478 let r = crop_rect(100, 100, &extreme);1545 let r = crop_rect(100, 100, &extreme);
1479 assert!(r.w >= 2, "the smallest surviving rect is one chroma sample");1546 assert!(r.w >= 2, "the smallest surviving rect is one chroma sample");
1480 // A zero-sized source has nothing to crop.1547 // A zero-sized source has nothing to crop.
1481- assert_eq!(crop_rect(0, 100, &TransformParams::default()), Rect { x: 0, y: 0, w: 0, h: 0 });1548+ assert_eq!(
1549+ crop_rect(0, 100, &TransformParams::default()),
1550+ Rect {
1551+ x: 0,
1552+ y: 0,
1553+ w: 0,
1554+ h: 0
1555+ }
1556+ );
1482 }1557 }
1483 1558
1484 /// A placement moved by `pos_x`/`pos_y` (canvas fractions about its own1559 /// A placement moved by `pos_x`/`pos_y` (canvas fractions about its own
@@ -1486,8 +1561,18 @@ mod tests {
1486 /// case here clips, so the source rect comes back untouched.1561 /// case here clips, so the source rect comes back untouched.
1487 #[test]1562 #[test]
1488 fn transformed_dst_rect_at_pos_and_scale() {1563 fn transformed_dst_rect_at_pos_and_scale() {
1489- let dst = Rect { x: 0, y: 0, w: 100, h: 100 };1564+ let dst = Rect {
1490- let src = Rect { x: 0, y: 0, w: 100, h: 100 };1565+ x: 0,
1566+ y: 0,
1567+ w: 100,
1568+ h: 100,
1569+ };
1570+ let src = Rect {
1571+ x: 0,
1572+ y: 0,
1573+ w: 100,
1574+ h: 100,
1575+ };
1491 // Moved a quarter of the canvas to the right, untouched vertically.1576 // Moved a quarter of the canvas to the right, untouched vertically.
1492 let moved = TransformParams {1577 let moved = TransformParams {
1493 pos_x: 0.25,1578 pos_x: 0.25,
@@ -1495,19 +1580,40 @@ mod tests {
1495 };1580 };
1496 assert_eq!(1581 assert_eq!(
1497 transformed_dst_rect(dst, src, 100, 100, &moved, 200, 200),1582 transformed_dst_rect(dst, src, 100, 100, &moved, 200, 200),
1498- (Rect { x: 50, y: 0, w: 100, h: 100 }, src),1583+ (
1584+ Rect {
1585+ x: 50,
1586+ y: 0,
1587+ w: 100,
1588+ h: 100
1589+ },
1590+ src
1591+ ),
1499 "25% of a 200-wide canvas is 50 pixels, about the placement's own centre"1592 "25% of a 200-wide canvas is 50 pixels, about the placement's own centre"
1500 );1593 );
1501 // Doubled in place, box already centred on the canvas: the centre1594 // Doubled in place, box already centred on the canvas: the centre
1502 // stays, the box fills the canvas, nothing clips.1595 // stays, the box fills the canvas, nothing clips.
1503- let centred_dst = Rect { x: 50, y: 50, w: 100, h: 100 };1596+ let centred_dst = Rect {
1597+ x: 50,
1598+ y: 50,
1599+ w: 100,
1600+ h: 100,
1601+ };
1504 let grown = TransformParams {1602 let grown = TransformParams {
1505 scale: 2.0,1603 scale: 2.0,
1506 ..Default::default()1604 ..Default::default()
1507 };1605 };
1508 assert_eq!(1606 assert_eq!(
1509 transformed_dst_rect(centred_dst, src, 100, 100, &grown, 200, 200),1607 transformed_dst_rect(centred_dst, src, 100, 100, &grown, 200, 200),
1510- (Rect { x: 0, y: 0, w: 200, h: 200 }, src),1608+ (
1609+ Rect {
1610+ x: 0,
1611+ y: 0,
1612+ w: 200,
1613+ h: 200
1614+ },
1615+ src
1616+ ),
1511 "a 100x100 box doubled about its own centre on a 200x200 canvas fills it"1617 "a 100x100 box doubled about its own centre on a 200x200 canvas fills it"
1512 );1618 );
1513 }1619 }
@@ -1521,27 +1627,137 @@ mod tests {
1521 /// what `scale` alone gives it.1627 /// what `scale` alone gives it.
1522 #[test]1628 #[test]
1523 fn transformed_dst_rect_clips_instead_of_squeezing() {1629 fn transformed_dst_rect_clips_instead_of_squeezing() {
1524- let dst = Rect { x: 0, y: 0, w: 100, h: 100 };1630+ let dst = Rect {
1525- let src = Rect { x: 0, y: 0, w: 100, h: 100 };1631+ x: 0,
1632+ y: 0,
1633+ w: 100,
1634+ h: 100,
1635+ };
1636+ let src = Rect {
1637+ x: 0,
1638+ y: 0,
1639+ w: 100,
1640+ h: 100,
1641+ };
1526 // +30% of a 100-wide canvas: the box moves 30px right, half of it1642 // +30% of a 100-wide canvas: the box moves 30px right, half of it
1527 // (50px) falls off the right edge -- half the source is trimmed off1643 // (50px) falls off the right edge -- half the source is trimmed off
1528 // its right, not the whole source squeezed into 70px.1644 // its right, not the whole source squeezed into 70px.
1529- let pos = TransformParams { pos_x: 0.30, ..Default::default() };1645+ let pos = TransformParams {
1646+ pos_x: 0.30,
1647+ ..Default::default()
1648+ };
1530 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &pos, 100, 100);1649 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &pos, 100, 100);
1531- assert_eq!(d, Rect { x: 30, y: 0, w: 70, h: 100 }, "dst size must not shrink below what clipping removes");1650+ assert_eq!(
1532- assert_eq!(s, Rect { x: 0, y: 0, w: 70, h: 100 }, "src trims off its right, does not squeeze");1651+ d,
1652+ Rect {
1653+ x: 30,
1654+ y: 0,
1655+ w: 70,
1656+ h: 100
1657+ },
1658+ "dst size must not shrink below what clipping removes"
1659+ );
1660+ assert_eq!(
1661+ s,
1662+ Rect {
1663+ x: 0,
1664+ y: 0,
1665+ w: 70,
1666+ h: 100
1667+ },
1668+ "src trims off its right, does not squeeze"
1669+ );
1533 1670
1534 // -30%: symmetric on the left, and no longer identical to identity.1671 // -30%: symmetric on the left, and no longer identical to identity.
1535- let neg = TransformParams { pos_x: -0.30, ..Default::default() };1672+ let neg = TransformParams {
1673+ pos_x: -0.30,
1674+ ..Default::default()
1675+ };
1536 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &neg, 100, 100);1676 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &neg, 100, 100);
1537- assert_eq!(d, Rect { x: 0, y: 0, w: 70, h: 100 });1677+ assert_eq!(
1538- assert_eq!(s, Rect { x: 30, y: 0, w: 70, h: 100 }, "src trims off its left");1678+ d,
1539- assert_ne!((d, s), (dst, src), "a negative offset must move the picture, not no-op");1679+ Rect {
1680+ x: 0,
1681+ y: 0,
1682+ w: 70,
1683+ h: 100
1684+ }
1685+ );
1686+ assert_eq!(
1687+ s,
1688+ Rect {
1689+ x: 30,
1690+ y: 0,
1691+ w: 70,
1692+ h: 100
1693+ },
1694+ "src trims off its left"
1695+ );
1696+ assert_ne!(
1697+ (d, s),
1698+ (dst, src),
1699+ "a negative offset must move the picture, not no-op"
1700+ );
1540 1701
1541 // Fully off canvas: both rects empty.1702 // Fully off canvas: both rects empty.
1542- let gone = TransformParams { pos_x: 2.0, ..Default::default() };1703+ let gone = TransformParams {
1704+ pos_x: 2.0,
1705+ ..Default::default()
1706+ };
1543 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &gone, 100, 100);1707 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &gone, 100, 100);
1544- assert!(d.is_empty() && s.is_empty(), "wholly off-canvas has nothing to draw");1708+ assert!(
1709+ d.is_empty() && s.is_empty(),
1710+ "wholly off-canvas has nothing to draw"
1711+ );
1712+ }
1713+
1714+ /// `pos_x`/`pos_y` are canvas fractions and a `transform` line takes any
1715+ /// finite `f32`, so they are the one transform field with no bound on the
1716+ /// way in -- `float()` (edith.rs) refuses only inf/NaN, and unlike
1717+ /// `scale`, which this function caps at a thousand canvas widths precisely
1718+ /// so its own arithmetic cannot overflow, the position was multiplied by
1719+ /// the canvas and added to `dst.x` unchecked. Rust's `as i64` saturates, so
1720+ /// a hostile 3e38 became `i64::MAX` and the *add* is what overflowed:
1721+ /// a panic on the compositing thread in a debug build, a silently wrapped
1722+ /// position in a release one. A placement pushed off the canvas is already
1723+ /// a legal answer (the two empty rects above); a position past the point
1724+ /// where the picture is long gone must give that same answer.
1725+ #[test]
1726+ fn a_transform_position_a_file_can_name_does_not_overflow_the_centre() {
1727+ let dst = Rect {
1728+ x: 10,
1729+ y: 20,
1730+ w: 100,
1731+ h: 100,
1732+ };
1733+ let src = Rect {
1734+ x: 0,
1735+ y: 0,
1736+ w: 100,
1737+ h: 100,
1738+ };
1739+ for (pos_x, pos_y) in [
1740+ (3.0e38f32, 0.0),
1741+ (-3.0e38, 0.0),
1742+ (0.0, 3.0e38),
1743+ (0.0, -3.0e38),
1744+ (3.0e38, 3.0e38),
1745+ (f32::MAX, f32::MIN),
1746+ ] {
1747+ let t = TransformParams {
1748+ pos_x,
1749+ pos_y,
1750+ ..Default::default()
1751+ };
1752+ let (d, s) = transformed_dst_rect(dst, src, 100, 100, &t, 200, 200);
1753+ // The answer is "nothing to draw" -- the box is a thousand canvas
1754+ // widths off screen -- not an overflow and not a wrapped position
1755+ // that lands back on the canvas.
1756+ assert!(
1757+ d.is_empty() && s.is_empty(),
1758+ "pos ({pos_x}, {pos_y}) gave {d:?} / {s:?} rather than an empty rect pair"
1759+ );
1760+ }
1545 }1761 }
1546 1762
1547 /// [`nearest_90_steps`] rounds to the closest quarter turn and folds a1763 /// [`nearest_90_steps`] rounds to the closest quarter turn and folds a
@@ -1572,10 +1788,18 @@ mod tests {
1572 1788
1573 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 1);1789 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 1);
1574 assert_eq!((rw, rh), (h as u32, w as u32), "dims swap at 90 degrees");1790 assert_eq!((rw, rh), (h as u32, w as u32), "dims swap at 90 degrees");
1575- assert_eq!(mark_at(&ry, rw, rw - 1, 0), 99, "top-left moves to top-right");1791+ assert_eq!(
1792+ mark_at(&ry, rw, rw - 1, 0),
1793+ 99,
1794+ "top-left moves to top-right"
1795+ );
1576 1796
1577 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 2);1797 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 2);
1578- assert_eq!((rw, rh), (w as u32, h as u32), "dims stay put at 180 degrees");1798+ assert_eq!(
1799+ (rw, rh),
1800+ (w as u32, h as u32),
1801+ "dims stay put at 180 degrees"
1802+ );
1579 assert_eq!(1803 assert_eq!(
1580 mark_at(&ry, rw, rw - 1, rh - 1),1804 mark_at(&ry, rw, rw - 1, rh - 1),
1581 99,1805 99,
@@ -1592,22 +1816,33 @@ mod tests {
1592 1816
1593 // Zero steps, and four of them, are both the identity.1817 // Zero steps, and four of them, are both the identity.
1594 let (ry, ru, rv, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 0);1818 let (ry, ru, rv, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 0);
1595- assert_eq!((ry, ru, rv, rw, rh), (y.clone(), u.clone(), v.clone(), w as u32, h as u32));1819+ assert_eq!(
1820+ (ry, ru, rv, rw, rh),
1821+ (y.clone(), u.clone(), v.clone(), w as u32, h as u32)
1822+ );
1596 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 4);1823 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 4);
1597- assert_eq!((ry, rw, rh), (y, w as u32, h as u32), "four quarter turns is the identity");1824+ assert_eq!(
1825+ (ry, rw, rh),
1826+ (y, w as u32, h as u32),
1827+ "four quarter turns is the identity"
1828+ );
1598 }1829 }
1599 1830
1600 /// A 64x64 Y plane split down the middle: columns 0..32 are 200, 32..641831 /// A 64x64 Y plane split down the middle: columns 0..32 are 200, 32..64
1601 /// are 40. A vertical edge to track through a horizontal move.1832 /// are 40. A vertical edge to track through a horizontal move.
1602 fn vsplit_64() -> (Vec<u8>, Vec<u8>, Vec<u8>) {1833 fn vsplit_64() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1603- let y = (0..64 * 64).map(|i| if i % 64 < 32 { 200u8 } else { 40u8 }).collect();1834+ let y = (0..64 * 64)
1835+ .map(|i| if i % 64 < 32 { 200u8 } else { 40u8 })
1836+ .collect();
1604 (y, vec![NEUTRAL_C; 32 * 32], vec![NEUTRAL_C; 32 * 32])1837 (y, vec![NEUTRAL_C; 32 * 32], vec![NEUTRAL_C; 32 * 32])
1605 }1838 }
1606 1839
1607 /// Same split, but across rows: 0..32 are 200, 32..64 are 40 -- an edge1840 /// Same split, but across rows: 0..32 are 200, 32..64 are 40 -- an edge
1608 /// to track through a vertical move.1841 /// to track through a vertical move.
1609 fn hsplit_64() -> (Vec<u8>, Vec<u8>, Vec<u8>) {1842 fn hsplit_64() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1610- let y = (0..64 * 64).map(|i| if i / 64 < 32 { 200u8 } else { 40u8 }).collect();1843+ let y = (0..64 * 64)
1844+ .map(|i| if i / 64 < 32 { 200u8 } else { 40u8 })
1845+ .collect();
1611 (y, vec![NEUTRAL_C; 32 * 32], vec![NEUTRAL_C; 32 * 32])1846 (y, vec![NEUTRAL_C; 32 * 32], vec![NEUTRAL_C; 32 * 32])
1612 }1847 }
1613 1848
@@ -1625,40 +1860,68 @@ mod tests {
1625 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);1860 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);
1626 1861
1627 // Identity: the source's own edge stays at column 32, everywhere.1862 // Identity: the source's own edge stays at column 32, everywhere.
1628- let (iy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &TransformParams::default());1863+ let (iy, ..) =
1864+ canvas.place_transformed(&y, &u, &v, src_w, src_h, &TransformParams::default());
1629 for row in 0..64 {1865 for row in 0..64 {
1630 let r = &iy[row * 64..][..64];1866 let r = &iy[row * 64..][..64];
1631- assert!(r[..32].iter().all(|&p| p == 200) && r[32..].iter().all(|&p| p == 40), "row {row}: {r:?}");1867+ assert!(
1868+ r[..32].iter().all(|&p| p == 200) && r[32..].iter().all(|&p| p == 40),
1869+ "row {row}: {r:?}"
1870+ );
1632 }1871 }
1633 1872
1634 // +25%: the box moves right by 16 and does NOT shrink -- content1873 // +25%: the box moves right by 16 and does NOT shrink -- content
1635 // width stays 64 (the source's own 32/32 split), clipped to what1874 // width stays 64 (the source's own 32/32 split), clipped to what
1636 // still fits. The edge (originally at box-column 32) now sits at1875 // still fits. The edge (originally at box-column 32) now sits at
1637 // canvas column 16 + 32 = 48, not squeezed inward.1876 // canvas column 16 + 32 = 48, not squeezed inward.
1638- let plus = TransformParams { pos_x: 0.25, ..Default::default() };1877+ let plus = TransformParams {
1878+ pos_x: 0.25,
1879+ ..Default::default()
1880+ };
1639 let (py, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &plus);1881 let (py, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &plus);
1640 for row in 0..64 {1882 for row in 0..64 {
1641 let r = &py[row * 64..][..64];1883 let r = &py[row * 64..][..64];
1642- assert!(r[..16].iter().all(|&p| p == BLACK_Y), "row {row} left of box: {r:?}");1884+ assert!(
1643- assert!(r[16..48].iter().all(|&p| p == 200), "row {row} squeezed inward: {r:?}");1885+ r[..16].iter().all(|&p| p == BLACK_Y),
1644- assert!(r[48..].iter().all(|&p| p == 40), "row {row} edge moved: {r:?}");1886+ "row {row} left of box: {r:?}"
1887+ );
1888+ assert!(
1889+ r[16..48].iter().all(|&p| p == 200),
1890+ "row {row} squeezed inward: {r:?}"
1891+ );
1892+ assert!(
1893+ r[48..].iter().all(|&p| p == 40),
1894+ "row {row} edge moved: {r:?}"
1895+ );
1645 }1896 }
1646 1897
1647 // -25%: mirror image -- this used to be pixel-identical to identity.1898 // -25%: mirror image -- this used to be pixel-identical to identity.
1648- let minus = TransformParams { pos_x: -0.25, ..Default::default() };1899+ let minus = TransformParams {
1900+ pos_x: -0.25,
1901+ ..Default::default()
1902+ };
1649 let (ny, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &minus);1903 let (ny, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &minus);
1650 assert_ne!(ny, iy, "a negative offset must move the picture, not no-op");1904 assert_ne!(ny, iy, "a negative offset must move the picture, not no-op");
1651 for row in 0..64 {1905 for row in 0..64 {
1652 let r = &ny[row * 64..][..64];1906 let r = &ny[row * 64..][..64];
1653 assert!(r[..16].iter().all(|&p| p == 200), "row {row}: {r:?}");1907 assert!(r[..16].iter().all(|&p| p == 200), "row {row}: {r:?}");
1654 assert!(r[16..48].iter().all(|&p| p == 40), "row {row}: {r:?}");1908 assert!(r[16..48].iter().all(|&p| p == 40), "row {row}: {r:?}");
1655- assert!(r[48..].iter().all(|&p| p == BLACK_Y), "row {row} right of box: {r:?}");1909+ assert!(
1910+ r[48..].iter().all(|&p| p == BLACK_Y),
1911+ "row {row} right of box: {r:?}"
1912+ );
1656 }1913 }
1657 1914
1658 // Wholly off-canvas: nothing to draw, all black.1915 // Wholly off-canvas: nothing to draw, all black.
1659- let gone = TransformParams { pos_x: 2.0, ..Default::default() };1916+ let gone = TransformParams {
1917+ pos_x: 2.0,
1918+ ..Default::default()
1919+ };
1660 let (gy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &gone);1920 let (gy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &gone);
1661- assert!(gy.iter().all(|&p| p == BLACK_Y), "off-canvas must render background");1921+ assert!(
1922+ gy.iter().all(|&p| p == BLACK_Y),
1923+ "off-canvas must render background"
1924+ );
1662 }1925 }
1663 1926
1664 /// The same defect on the vertical axis: `pos_y` moves content up/down,1927 /// The same defect on the vertical axis: `pos_y` moves content up/down,
@@ -1669,19 +1932,35 @@ mod tests {
1669 let (y, u, v) = hsplit_64();1932 let (y, u, v) = hsplit_64();
1670 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);1933 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);
1671 1934
1672- let plus = TransformParams { pos_y: 0.25, ..Default::default() };1935+ let plus = TransformParams {
1936+ pos_y: 0.25,
1937+ ..Default::default()
1938+ };
1673 let (py, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &plus);1939 let (py, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &plus);
1674 for row in 0..16 {1940 for row in 0..16 {
1675- assert!(py[row * 64..][..64].iter().all(|&p| p == BLACK_Y), "row {row} above the box");1941+ assert!(
1942+ py[row * 64..][..64].iter().all(|&p| p == BLACK_Y),
1943+ "row {row} above the box"
1944+ );
1676 }1945 }
1677 for row in 16..48 {1946 for row in 16..48 {
1678- assert!(py[row * 64..][..64].iter().all(|&p| p == 200), "row {row} squeezed: {:?}", &py[row * 64..][..4]);1947+ assert!(
1948+ py[row * 64..][..64].iter().all(|&p| p == 200),
1949+ "row {row} squeezed: {:?}",
1950+ &py[row * 64..][..4]
1951+ );
1679 }1952 }
1680 for row in 48..64 {1953 for row in 48..64 {
1681- assert!(py[row * 64..][..64].iter().all(|&p| p == 40), "row {row} edge moved");1954+ assert!(
1955+ py[row * 64..][..64].iter().all(|&p| p == 40),
1956+ "row {row} edge moved"
1957+ );
1682 }1958 }
1683 1959
1684- let minus = TransformParams { pos_y: -0.25, ..Default::default() };1960+ let minus = TransformParams {
1961+ pos_y: -0.25,
1962+ ..Default::default()
1963+ };
1685 let (ny, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &minus);1964 let (ny, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &minus);
1686 for row in 0..16 {1965 for row in 0..16 {
1687 assert!(ny[row * 64..][..64].iter().all(|&p| p == 200), "row {row}");1966 assert!(ny[row * 64..][..64].iter().all(|&p| p == 200), "row {row}");
@@ -1690,7 +1969,10 @@ mod tests {
1690 assert!(ny[row * 64..][..64].iter().all(|&p| p == 40), "row {row}");1969 assert!(ny[row * 64..][..64].iter().all(|&p| p == 40), "row {row}");
1691 }1970 }
1692 for row in 48..64 {1971 for row in 48..64 {
1693- assert!(ny[row * 64..][..64].iter().all(|&p| p == BLACK_Y), "row {row} below the box");1972+ assert!(
1973+ ny[row * 64..][..64].iter().all(|&p| p == BLACK_Y),
1974+ "row {row} below the box"
1975+ );
1694 }1976 }
1695 }1977 }
1696 1978
@@ -1705,7 +1987,11 @@ mod tests {
1705 // scale 0.5, pos_x +0.25: box becomes 32x32 at canvas (32, 16),1987 // scale 0.5, pos_x +0.25: box becomes 32x32 at canvas (32, 16),
1706 // fully on-canvas. The source's column-32 edge, halved, sits at1988 // fully on-canvas. The source's column-32 edge, halved, sits at
1707 // box-local column 16, i.e. canvas column 32 + 16 = 48.1989 // box-local column 16, i.e. canvas column 32 + 16 = 48.
1708- let t = TransformParams { scale: 0.5, pos_x: 0.25, ..Default::default() };1990+ let t = TransformParams {
1991+ scale: 0.5,
1992+ pos_x: 0.25,
1993+ ..Default::default()
1994+ };
1709 let (sy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &t);1995 let (sy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &t);
1710 for row in 0..64 {1996 for row in 0..64 {
1711 let r = &sy[row * 64..][..64];1997 let r = &sy[row * 64..][..64];
@@ -1713,8 +1999,14 @@ mod tests {
1713 let want_bg = if inside { r[0] } else { BLACK_Y };1999 let want_bg = if inside { r[0] } else { BLACK_Y };
1714 assert_eq!(want_bg, BLACK_Y, "row {row} col 0 outside the box: {r:?}");2000 assert_eq!(want_bg, BLACK_Y, "row {row} col 0 outside the box: {r:?}");
1715 if inside {2001 if inside {
1716- assert!(r[40].abs_diff(200) <= 1, "row {row} col 40 should be the left half: {r:?}");2002+ assert!(
1717- assert!(r[56].abs_diff(40) <= 1, "row {row} col 56 should be the right half: {r:?}");2003+ r[40].abs_diff(200) <= 1,
2004+ "row {row} col 40 should be the left half: {r:?}"
2005+ );
2006+ assert!(
2007+ r[56].abs_diff(40) <= 1,
2008+ "row {row} col 56 should be the right half: {r:?}"
2009+ );
1718 }2010 }
1719 }2011 }
1720 }2012 }
crates/engine/tests/saveload.rsmodified+500 -4
@@ -108,7 +108,10 @@ fn both_proxy_switches_survive_a_save_and_a_reopen() {
108 let media = copy_in(&dir, "test_av.mp4");108 let media = copy_in(&dir, "test_av.mp4");
109 let mut session = PlaybackSession::open(&media).expect("open the fixture");109 let mut session = PlaybackSession::open(&media).expect("open the fixture");
110 session.set_gain(0.0);110 session.set_gain(0.0);
111- assert!(session.auto_proxies(), "a fresh project makes them by itself");111+ assert!(
112+ session.auto_proxies(),
113+ "a fresh project makes them by itself"
114+ );
112 assert!(!session.proxies(), "and is cut on the film itself");115 assert!(!session.proxies(), "and is cut on the film itself");
113 116
114 session.set_proxies(true);117 session.set_proxies(true);
@@ -126,7 +129,10 @@ fn both_proxy_switches_survive_a_save_and_a_reopen() {
126 session.set_auto_proxies(true);129 session.set_auto_proxies(true);
127 session.save_project(&path).expect("save");130 session.save_project(&path).expect("save");
128 let text = std::fs::read_to_string(&path).expect("read back");131 let text = std::fs::read_to_string(&path).expect("read back");
129- assert!(!text.contains("autoproxy"), "on is written by saying nothing");132+ assert!(
133+ !text.contains("autoproxy"),
134+ "on is written by saying nothing"
135+ );
130 assert!(136 assert!(
131 PlaybackSession::open_project(&path)137 PlaybackSession::open_project(&path)
132 .expect("reopen")138 .expect("reopen")
@@ -158,7 +164,10 @@ fn the_encoder_seat_survives_a_save_and_a_reopen() {
158 session.set_encoder_seat(seat);164 session.set_encoder_seat(seat);
159 session.save_project(&path).expect("save");165 session.save_project(&path).expect("save");
160 let text = std::fs::read_to_string(&path).expect("read back");166 let text = std::fs::read_to_string(&path).expect("read back");
161- assert!(text.contains(&format!("encoder {}\n", seat.name())), "{text}");167+ assert!(
168+ text.contains(&format!("encoder {}\n", seat.name())),
169+ "{text}"
170+ );
162 assert_eq!(171 assert_eq!(
163 PlaybackSession::open_project(&path)172 PlaybackSession::open_project(&path)
164 .expect("reopen")173 .expect("reopen")
@@ -171,7 +180,10 @@ fn the_encoder_seat_survives_a_save_and_a_reopen() {
171 session.set_encoder_seat(EncoderSeat::Auto);180 session.set_encoder_seat(EncoderSeat::Auto);
172 session.save_project(&path).expect("save");181 session.save_project(&path).expect("save");
173 let text = std::fs::read_to_string(&path).expect("read back");182 let text = std::fs::read_to_string(&path).expect("read back");
174- assert!(!text.contains("encoder"), "auto is written by saying nothing");183+ assert!(
184+ !text.contains("encoder"),
185+ "auto is written by saying nothing"
186+ );
175 assert_eq!(187 assert_eq!(
176 PlaybackSession::open_project(&path)188 PlaybackSession::open_project(&path)
177 .expect("reopen")189 .expect("reopen")
@@ -959,3 +971,487 @@ fn a_song_only_project_comes_back_at_the_rate_it_names() {
959 let loaded = PlaybackSession::open_project(&old).expect("a v8 song project opens");971 let loaded = PlaybackSession::open_project(&old).expect("a v8 song project opens");
960 assert_eq!(loaded.meta().frame_rate, 30.0, "the canvas rate, as before");972 assert_eq!(loaded.meta().frame_rate, 30.0, "the canvas rate, as before");
961 }973 }
974+
975+/// A hand-edited `.edith` whose caption names a microsecond window no project
976+/// can hold: the whole load, the same edit a 30-second window survives, and the
977+/// refusal the loader owes for it.
978+///
979+/// A caption's window is the one unbounded number this format takes. The
980+/// never-empty check at `edith.rs` asks whether `out_us > in_us` and never how
981+/// large either is, so `out_us = i64::MAX` was a legal line -- and every split,
982+/// ripple and group trim since cuts the window *by proportion*
983+/// (`SubClip::window_at`), a plain `window_us() * into` that overflows on the
984+/// first frame inside the caption. That is a panic on the UI thread the first
985+/// time a hand ripple-deletes across the caption, and in a release build the
986+/// same line wraps the caption's clock to a negative number instead. So the
987+/// window is bounded at the door, by name, and the arithmetic behind the cut
988+/// is made total as well.
989+#[test]
990+fn a_caption_window_no_project_can_hold_is_refused_by_name() {
991+ let dir = scratch("caption_window");
992+ let media = copy_in(&dir, "test_av.mp4");
993+ let subs = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
994+ .join("tests/data/test_subs.srt")
995+ .canonicalize()
996+ .expect("the subtitle fixture");
997+
998+ // The control first: a 30-second window over 30 frames, the shape every
999+ // save writes, and the shape this file's whole edit path is proved on.
1000+ let ok = dir.join("window_ok.edith");
1001+ std::fs::write(
1002+ &ok,
1003+ format!(
1004+ "edith 23\nplayhead 0\nresolution 1280 720\nsource 0 {}\nsubtitle - {}\n\
1005+ video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
1006+ sub 1 0 30 0 0 30000000\n",
1007+ media.display(),
1008+ subs.display(),
1009+ ),
1010+ )
1011+ .expect("write");
1012+ let mut control = PlaybackSession::open_project(&ok).expect("a 30s caption window opens");
1013+ assert_eq!(control.sub_lane(Lane::S1)[0].out_us, 30_000_000);
1014+ // The edits the unbounded window used to survive: a split inside the
1015+ // caption and a ripple across it. Both cut the window by proportion.
1016+ assert!(
1017+ control.cut_at(0.5),
1018+ "the playhead splits the caption under it"
1019+ );
1020+ assert_eq!(
1021+ control.sub_lane(Lane::S1).len(),
1022+ 2,
1023+ "the split cut the caption in two"
1024+ );
1025+ control.undo();
1026+ control
1027+ .cut_regions(&[(0, 10)], &[Lane::S1])
1028+ .expect("a ripple across the caption, scoped to its own lane");
1029+ let after = control.sub_lane(Lane::S1);
1030+ assert_eq!(after.len(), 1, "the caption's tail is still there");
1031+ assert_eq!(
1032+ (after[0].start, after[0].frames),
1033+ (0, 20),
1034+ "and it closed the hole the cut left"
1035+ );
1036+
1037+ // The same file, the same lane, the same edit -- with a window no project
1038+ // can hold. This is the line that used to load and then panic.
1039+ let huge = dir.join("window_huge.edith");
1040+ std::fs::write(
1041+ &huge,
1042+ format!(
1043+ "edith 23\nplayhead 0\nresolution 1280 720\nsource 0 {}\nsubtitle - {}\n\
1044+ video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
1045+ sub 1 0 30 0 0 9223372036854775807\n",
1046+ media.display(),
1047+ subs.display(),
1048+ ),
1049+ )
1050+ .expect("write");
1051+ let err = PlaybackSession::open_project(&huge)
1052+ .err()
1053+ .unwrap_or_else(|| {
1054+ panic!(
1055+ "a caption window of {}us loaded, and the first split across it \
1056+ panics in SubClip::window_at",
1057+ i64::MAX
1058+ )
1059+ })
1060+ .to_string();
1061+ assert!(
1062+ err.contains("window") && err.contains("9223372036854775807"),
1063+ "the refusal names the window it is refusing, and the value: {err}"
1064+ );
1065+ assert!(err.starts_with("line 7"), "and which line said it: {err}");
1066+
1067+ // The same bound at the other two doors a caption comes through, because a
1068+ // caller is not more trustworthy than a file: the placement a hand drags
1069+ // out of the palette is a `SubClip` somebody built, and it goes through
1070+ // `place_sub` rather than the parse.
1071+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
1072+ session
1073+ .import_subtitles(&subs)
1074+ .expect("the fixture's one track");
1075+ let s1 = session.add_lane(engine::project::LaneKind::Subtitle);
1076+ let err = session
1077+ .place_sub(
1078+ s1,
1079+ 0,
1080+ engine::project::SubClip {
1081+ start: 0,
1082+ frames: 30,
1083+ track: 0,
1084+ in_us: 0,
1085+ out_us: i64::MAX,
1086+ link: None,
1087+ },
1088+ )
1089+ .expect_err("a window no project can hold is refused by name, not clamped")
1090+ .to_string();
1091+ assert!(
1092+ err.contains("window") && err.contains(&i64::MAX.to_string()),
1093+ "the placement refusal names the window and the value: {err}"
1094+ );
1095+ assert!(
1096+ session.sub_lane(s1).is_empty(),
1097+ "and a refusal places nothing: {:?}",
1098+ session.sub_lane(s1)
1099+ );
1100+}
1101+
1102+/// A subtitle track whose last cue ends `hours` in, written into `dir`.
1103+///
1104+/// A caption's window is a window into SOURCE media, so its width is however
1105+/// long the recording was. Nothing in the format bounds that, and a lecture
1106+/// archive or a conference stream is tens of hours -- which is what a ceiling
1107+/// under a day refuses back at the user. The hour field is parsed as a plain
1108+/// `u32` with no digit limit, so 960 is a legal 40 days.
1109+fn long_srt(dir: &Path, hours: u32) -> PathBuf {
1110+ let path = dir.join(format!("subs_{hours}h.srt"));
1111+ std::fs::write(
1112+ &path,
1113+ format!(
1114+ "1\n00:00:00,500 --> 00:00:01,500\nfirst line\n\n\
1115+ 2\n00:00:01,600 --> {hours}:00:00,000\nlast line of a long recording\n"
1116+ ),
1117+ )
1118+ .expect("write a long subtitle track");
1119+ path
1120+}
1121+
1122+/// The round trip a trim has to survive: grow a caption's window to the room
1123+/// the engine itself offers, save, and open the file that was just written.
1124+///
1125+/// This is the hole a ceiling on its own leaves. Every door -- the parse,
1126+/// `with_subs`, `place_sub` -- only ever sees a window on the way *in*, so a
1127+/// project could load legally and then be trimmed past the ceiling: `save`
1128+/// wrote the line and the loader refused it again, which is the user's own
1129+/// saved work stopping, with no in-app way back (the trim is committed and the
1130+/// undo does not survive a restart). So growth clamps (`grow_window`) and the
1131+/// room the front-end drags against is walled by the same number, and the two
1132+/// agree by construction rather than by luck.
1133+#[test]
1134+fn a_trim_grown_to_the_offered_room_saves_and_reopens() {
1135+ use engine::project::{Edge, MAX_WINDOW_US, SubClip};
1136+
1137+ let dir = scratch("caption_growth");
1138+ let media = copy_in(&dir, "test_av.mp4");
1139+ // 40 days of track, comfortably past the 30-day ceiling: only the growth
1140+ // clamp can keep this inside it, never the ceiling itself.
1141+ let subs = long_srt(&dir, 960);
1142+
1143+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
1144+ session
1145+ .import_subtitles(&subs)
1146+ .expect("a 40-day subtitle track imports");
1147+ let s1 = session.add_lane(engine::project::LaneKind::Subtitle);
1148+ session
1149+ .place_sub(
1150+ s1,
1151+ 60,
1152+ SubClip {
1153+ start: 0,
1154+ frames: 90,
1155+ track: 0,
1156+ in_us: 0,
1157+ out_us: 30_000_000,
1158+ link: None,
1159+ },
1160+ )
1161+ .expect("a 30s window places");
1162+
1163+ // The room the drag is drawn against. It must itself stop at the ceiling:
1164+ // an engine that offers a trim its own `trim_sub` would clamp is a drag
1165+ // that snaps back at the end of the gesture.
1166+ let (_, last) = session
1167+ .trim_sub_room(s1, 0, Edge::End)
1168+ .expect("a room for a caption that is there");
1169+ session
1170+ .trim_sub(s1, 0, Edge::End, last)
1171+ .expect("the trim to its own offered room");
1172+
1173+ let grown = session.sub_lane(s1)[0];
1174+ assert!(
1175+ (grown.out_us - grown.in_us) <= MAX_WINDOW_US,
1176+ "trimming to the offered room gave a {}us window, past the {}us ceiling",
1177+ grown.out_us - grown.in_us,
1178+ MAX_WINDOW_US
1179+ );
1180+
1181+ let saved = dir.join("grown.edith");
1182+ session.save_project(&saved).expect("save");
1183+ let reopened = PlaybackSession::open_project(&saved)
1184+ .expect("a project the editor wrote must open again -- that is the whole claim");
1185+ let back = reopened.sub_lane(s1)[0];
1186+ assert_eq!(
1187+ (back.in_us, back.out_us),
1188+ (grown.in_us, grown.out_us),
1189+ "and the window came back as it was saved"
1190+ );
1191+}
1192+
1193+/// The ceiling itself, against the case it was measured on: a 25-hour
1194+/// recording. `place_sub` is the door a palette row's drag comes through
1195+/// (`sub_of_track` builds the placement from the track's own last cue), so a
1196+/// ceiling under the length of real media refuses the user's own file back at
1197+/// them, with nothing placed.
1198+#[test]
1199+fn a_caption_over_a_day_of_track_places_and_round_trips() {
1200+ use engine::project::MAX_WINDOW_US;
1201+
1202+ let dir = scratch("caption_long_track");
1203+ let media = copy_in(&dir, "test_av.mp4");
1204+ let subs = long_srt(&dir, 25);
1205+ let whole_track_us = 25i64 * 60 * 60 * 1_000_000;
1206+ assert!(
1207+ whole_track_us > 86_400_000_000,
1208+ "the fixture must really be over a day, or this test proves nothing"
1209+ );
1210+ assert!(
1211+ whole_track_us < MAX_WINDOW_US,
1212+ "and comfortably under the ceiling, or the test is not about the ceiling"
1213+ );
1214+
1215+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
1216+ assert_eq!(
1217+ session
1218+ .import_subtitles(&subs)
1219+ .expect("a 25-hour track imports"),
1220+ 1,
1221+ "one track"
1222+ );
1223+ let s1 = session.add_lane(engine::project::LaneKind::Subtitle);
1224+ // Exactly what `Player::sub_of_track` hands `place_sub` for palette row 0.
1225+ let fps = f64::from(session.meta().frame_rate);
1226+ session
1227+ .place_sub(
1228+ s1,
1229+ 0,
1230+ engine::project::SubClip {
1231+ start: 0,
1232+ frames: ((whole_track_us as f64) * fps / 1e6).round() as u32,
1233+ track: 0,
1234+ in_us: 0,
1235+ out_us: whole_track_us,
1236+ link: None,
1237+ },
1238+ )
1239+ .expect("a caption over a 25-hour recording places -- that is the claim");
1240+
1241+ let saved = dir.join("long.edith");
1242+ session.save_project(&saved).expect("save");
1243+ let reopened = PlaybackSession::open_project(&saved).expect("and reopens");
1244+ assert_eq!(
1245+ reopened.sub_lane(s1)[0].out_us,
1246+ whole_track_us,
1247+ "the whole window survived the round trip"
1248+ );
1249+}
1250+
1251+/// The second writer, which is the one a primary-trim-only fix would miss.
1252+///
1253+/// [`write_sub_edge`] carries a *sibling* in a group by the same delta as the
1254+/// member that was dragged, and reaches the same `out_us`. `follow_group`
1255+/// skips the dragged member, so the route here is a second caption in the
1256+/// group on another lane: it is not the one whose `trim_sub` arm is fixed, so
1257+/// nothing about the dragged caption's own clamp bounds it.
1258+///
1259+/// The sibling starts deep into the track -- 20 days in -- so the same delta
1260+/// that stops the dragged caption exactly at the ceiling carries the sibling
1261+/// past it. Without the clamp on this writer the sibling is 20 days wider than
1262+/// the ceiling when `save_project` runs, and the file it writes will not open.
1263+#[test]
1264+fn a_group_trim_carries_its_sibling_no_further_than_the_ceiling() {
1265+ use engine::project::{Edge, LaneKind, MAX_WINDOW_US, SubClip};
1266+
1267+ let dir = scratch("caption_group_growth");
1268+ let media = copy_in(&dir, "test_av.mp4");
1269+ let subs = long_srt(&dir, 960);
1270+ let day = 24 * 60 * 60 * 1_000_000i64;
1271+
1272+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
1273+ session
1274+ .import_subtitles(&subs)
1275+ .expect("a 40-day track imports");
1276+ let s1 = session.add_lane(LaneKind::Subtitle);
1277+ let s2 = session.add_lane(LaneKind::Subtitle);
1278+ let caption = |in_us| SubClip {
1279+ start: 0,
1280+ frames: 90,
1281+ track: 0,
1282+ in_us,
1283+ out_us: in_us + 30_000_000,
1284+ link: None,
1285+ };
1286+ session
1287+ .place_sub(s1, 60, caption(0))
1288+ .expect("the dragged caption places");
1289+ session
1290+ .place_sub(s2, 60, caption(20 * day))
1291+ .expect("its sibling, 20 days into the track");
1292+ session
1293+ .group_all(&[(s1, 0), (s2, 0)])
1294+ .expect("the two captions into one group");
1295+
1296+ // Drag the first caption's tail out to the room the engine offers it, which
1297+ // is a 40-day track so the room is the ceiling, not the track.
1298+ let (_, last) = session
1299+ .trim_sub_room(s1, 0, Edge::End)
1300+ .expect("a room for the dragged caption");
1301+ session
1302+ .trim_sub(s1, 0, Edge::End, last)
1303+ .expect("the drag commits");
1304+
1305+ let dragged = session.sub_lane(s1)[0];
1306+ assert_eq!(
1307+ dragged.out_us - dragged.in_us,
1308+ MAX_WINDOW_US,
1309+ "the dragged caption stops exactly at the ceiling, which is the room it was offered"
1310+ );
1311+ let sibling = session.sub_lane(s2)[0];
1312+ assert!(
1313+ (sibling.out_us - sibling.in_us) <= MAX_WINDOW_US,
1314+ "the group carried the sibling to a {}us window, past the {}us ceiling -- \
1315+ the dragged caption's own clamp does not reach here",
1316+ sibling.out_us - sibling.in_us,
1317+ MAX_WINDOW_US
1318+ );
1319+
1320+ let saved = dir.join("group.edith");
1321+ session.save_project(&saved).expect("save");
1322+ PlaybackSession::open_project(&saved).expect("and the file the editor wrote reopens");
1323+}
1324+
1325+/// The composer that no per-arm check finds: a **rejoin** takes the left
1326+/// half's `in_us` and the right half's `out_us`, and `sub_joinable` has just
1327+/// established that the two halves are consecutive in the *source* -- so the
1328+/// joined width is the SUM of two widths that each passed their own door.
1329+///
1330+/// Neither half is illegal and the whole is. Two 20-day windows, one ordinary
1331+/// undo-a-split keystroke, a 40-day window, and a file the editor writes and
1332+/// cannot reopen.
1333+#[test]
1334+fn a_rejoin_of_two_legal_windows_stays_inside_the_ceiling() {
1335+ use engine::project::{MAX_WINDOW_US, SubClip};
1336+
1337+ let dir = scratch("caption_rejoin");
1338+ let media = copy_in(&dir, "test_av.mp4");
1339+ let subs = long_srt(&dir, 960);
1340+ let twenty_days = 20 * 24 * 60 * 60 * 1_000_000i64;
1341+
1342+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
1343+ session
1344+ .import_subtitles(&subs)
1345+ .expect("a 40-day track imports");
1346+ let s1 = session.add_lane(engine::project::LaneKind::Subtitle);
1347+ // Two adjacent halves, each a legal 20-day window, the second starting
1348+ // exactly where the first's window ends -- which is what `sub_joinable`
1349+ // requires, and what makes the join a sum.
1350+ for (at, frames, in_us) in [(0u32, 10_000u32, 0i64), (10_000, 10_000, twenty_days)] {
1351+ session
1352+ .place_sub(
1353+ s1,
1354+ at,
1355+ SubClip {
1356+ start: 0,
1357+ frames,
1358+ track: 0,
1359+ in_us,
1360+ out_us: in_us + twenty_days,
1361+ link: None,
1362+ },
1363+ )
1364+ .unwrap_or_else(|e| panic!("a 20-day half at {at} places: {e}"));
1365+ }
1366+ let halves: Vec<i64> = session
1367+ .sub_lane(s1)
1368+ .iter()
1369+ .map(|s| s.out_us - s.in_us)
1370+ .collect();
1371+ assert!(
1372+ halves.iter().all(|&w| w <= MAX_WINDOW_US),
1373+ "both halves must be legal for this to be about the join: {halves:?}"
1374+ );
1375+
1376+ // `regroup_at` is in seconds, like every other front-end door; the
1377+ // boundary is the frame the second half starts on.
1378+ let at_secs = 10_000.0 / f64::from(session.meta().frame_rate);
1379+ assert!(
1380+ session.regroup_at(at_secs),
1381+ "the two halves rejoin -- the inverse of the split that made them"
1382+ );
1383+ let joined = &session.sub_lane(s1)[0];
1384+ assert!(
1385+ (joined.out_us - joined.in_us) <= MAX_WINDOW_US,
1386+ "the rejoin summed two {}us windows into {}us, past the {}us ceiling",
1387+ MAX_WINDOW_US / 2,
1388+ joined.out_us - joined.in_us,
1389+ MAX_WINDOW_US
1390+ );
1391+
1392+ let saved = dir.join("rejoined.edith");
1393+ session.save_project(&saved).expect("save");
1394+ PlaybackSession::open_project(&saved).expect("and the file the editor wrote reopens");
1395+}
1396+
1397+/// The other half of the ceiling: it bounds a **difference**, so a head trim
1398+/// grows the width as surely as a tail trim does, and from the other side.
1399+///
1400+/// A caption placed a year into its source with a 30-second window is legal.
1401+/// One head drag pulling its start back by 200 days of frames makes the
1402+/// window 200 days wide while `out_us` never moves -- so bounding `in_us`
1403+/// from above, which is all the head arm's own clamp does, says nothing at all
1404+/// about the ceiling.
1405+#[test]
1406+fn a_head_drag_no_further_than_the_ceiling() {
1407+ use engine::project::{Edge, MAX_WINDOW_US, SubClip};
1408+
1409+ let dir = scratch("caption_head_drag");
1410+ let media = copy_in(&dir, "test_av.mp4");
1411+ let subs = long_srt(&dir, 960);
1412+ let day = 24 * 60 * 60 * 1_000_000i64;
1413+
1414+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
1415+ session
1416+ .import_subtitles(&subs)
1417+ .expect("a 40-day track imports");
1418+ let s1 = session.add_lane(engine::project::LaneKind::Subtitle);
1419+ // A year into the source, 30 seconds of window: legal, and the only kind
1420+ // of caption a head drag can make enormous.
1421+ session
1422+ .place_sub(
1423+ s1,
1424+ 90_000_000,
1425+ SubClip {
1426+ start: 0,
1427+ frames: 900,
1428+ track: 0,
1429+ in_us: 365 * day,
1430+ out_us: 365 * day + 30_000_000,
1431+ link: None,
1432+ },
1433+ )
1434+ .expect("a year-deep caption places");
1435+
1436+ // The head room the engine offers, then the drag to its far end: 200 days
1437+ // of source at 30 fps, which the Start arm's own `in_us <= out_us - 1`
1438+ // clamp is perfectly happy with.
1439+ let (lo, _) = session
1440+ .trim_sub_room(s1, 0, Edge::Start)
1441+ .expect("a head room");
1442+ session
1443+ .trim_sub(s1, 0, Edge::Start, lo)
1444+ .expect("the head drag commits");
1445+
1446+ let dragged = session.sub_lane(s1)[0];
1447+ assert!(
1448+ (dragged.out_us - dragged.in_us) <= MAX_WINDOW_US,
1449+ "a head drag onto a year-deep caption gave a {}us window, past the {}us ceiling",
1450+ dragged.out_us - dragged.in_us,
1451+ MAX_WINDOW_US
1452+ );
1453+
1454+ let saved = dir.join("head.edith");
1455+ session.save_project(&saved).expect("save");
1456+ PlaybackSession::open_project(&saved).expect("and the file the editor wrote reopens");
1457+}