forge
Explore
Log in

Don't you dare go Hollow

Offset-preserving groups over clips and captions

Browse files at this commit

48cacb671eb3a476c4fd5b1b7137d7b86306e78aAhmet Kaan GümüşParent: 888f39d
  • feat
    • offset-preserving groups over clips and captions
Show full message
✨ feat(engine): offset-preserving groups over clips and captions

The engine half of manual clip grouping: SubClip gains a link id, the
group invariant becomes one-placement-per-lane (span equality dropped),
group_all builds a hand group over clips and captions with mates riding
along, splits keep the left group and share one fresh id on the right
(captions included), deletes ripple each media member's own span on its
own lane and lift caption members, grouped caption drags and group
trims move every member by one delta clamped to each member's own
walls, and the save format grows an optional 6th sub field as v16.

App half (Selection refactor, ctrl+click, ctrl+A, oracle/menu, marks)
follows.
crates/engine/src/edith.rsmodified+54 -25
@@ -143,11 +143,13 @@
143 //! track 3 of a two-track palette is refused here, as a clip naming a source143 //! track 3 of a two-track palette is refused here, as a clip naming a source
144 //! that is not there is.144 //! that is not there is.
145 //!145 //!
146-//! **Version 14** was this without the `sub` lines: such a project holds no146+//! **Version 15** was this without the caption's group field: such a project
147+//! holds captions no hand ever grouped, which is every caption there could be.
148+//! **Version 14** was that without the `sub` lines: such a project holds no
147 //! subtitle lane at all -- its `subtitle` lines are the palette, and where the149 //! subtitle lane at all -- its `subtitle` lines are the palette, and where the
148 //! words of it were shown was nowhere in the file.150 //! words of it were shown was nowhere in the file.
149-//! **Version 13** was that without the `encoder` line: an export of such a151+//! **Version 13** was that without the `encoder` line: such a project takes the
150-//! project takes the hardware seat where there is one and the software encoder152+//! hardware seat where there is one and the software encoder
151 //! everywhere else, which is the only choice those projects had.153 //! everywhere else, which is the only choice those projects had.
152 //! **Version 12** was that without the `autoproxy` line: such a project makes a154 //! **Version 12** was that without the `autoproxy` line: such a project makes a
153 //! stand-in for every film that wants one the moment it arrives, which is all155 //! stand-in for every film that wants one the moment it arrives, which is all
@@ -178,7 +180,7 @@
178 //! nothing, and an older one plays everything at real time, and an older one180 //! nothing, and an older one plays everything at real time, and an older one
179 //! mixes flat, and an older one shows no subtitles, and an older one is shown181 //! mixes flat, and an older one shows no subtitles, and an older one is shown
180 //! in the reference rendition, and an older one places none of the words it182 //! in the reference rendition, and an older one places none of the words it
181-//! names -- and saving any of them writes v15. An older183+//! names -- and saving any of them writes v16. An older
182 //! reader refuses a newer file by name.184 //! reader refuses a newer file by name.
183 //!185 //!
184 //! Text because an edit list is a few integers and a path, and a path is186 //! Text because an edit list is a few integers and a path, and a path is
@@ -214,7 +216,8 @@ use crate::subtitle::SubtitleTrack;
214 216
215 /// What [`save`] writes. Read support goes back to `edith 1`; see the module217 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
216 /// docs for what those dialects looked like.218 /// docs for what those dialects looked like.
217-const MAGIC: &[u8] = b"edith 15";219+const MAGIC: &[u8] = b"edith 16";
220+const MAGIC_V15: &[u8] = b"edith 15";
218 const MAGIC_V14: &[u8] = b"edith 14";221 const MAGIC_V14: &[u8] = b"edith 14";
219 const MAGIC_V13: &[u8] = b"edith 13";222 const MAGIC_V13: &[u8] = b"edith 13";
220 const MAGIC_V12: &[u8] = b"edith 12";223 const MAGIC_V12: &[u8] = b"edith 12";
@@ -503,9 +506,13 @@ fn emit(
503 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());506 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
504 }507 }
505 for s in placed {508 for s in placed {
509+ // The group field only when the caption is in one, for the
510+ // clip line's reason: a project nobody grouped a caption in is
511+ // the same bytes it was in v15.
512+ let link = s.link.map_or(String::new(), |l| format!(" {l}"));
506 out.extend_from_slice(513 out.extend_from_slice(
507 format!(514 format!(
508- "{keyword} {ord} {} {} {} {} {}\n",515+ "{keyword} {ord} {} {} {} {} {}{link}\n",
509 s.start, s.frames, s.track, s.in_us, s.out_us516 s.start, s.frames, s.track, s.in_us, s.out_us
510 )517 )
511 .as_bytes(),518 .as_bytes(),
@@ -573,8 +580,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
573 // The dialects that wrote a source line without its stream field. Reading580 // The dialects that wrote a source line without its stream field. Reading
574 // one is the whole of what "an old project still opens" means here.581 // one is the whole of what "an old project still opens" means here.
575 let streamless = v1 || first == MAGIC_V2;582 let streamless = v1 || first == MAGIC_V2;
576- // The one that places the words it names...583+ // The one whose captions may carry a group id...
577- let v15 = first == MAGIC;584+ let v16 = first == MAGIC;
585+ // ...the one that places the words it names...
586+ let v15 = v16 || first == MAGIC_V15;
578 // ...the ones that say which encoder an export takes...587 // ...the ones that say which encoder an export takes...
579 let v14 = v15 || first == MAGIC_V14;588 let v14 = v15 || first == MAGIC_V14;
580 // ...the ones that say whether the stand-ins are made by themselves...589 // ...the ones that say whether the stand-ins are made by themselves...
@@ -948,13 +957,33 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
948 if rest.is_empty() {957 if rest.is_empty() {
949 continue;958 continue;
950 }959 }
951- let f = fields(rest, 5, "sub", n)?;960+ // v16 on may carry a sixth field -- the caption's group id, the
961+ // same spelling a clip's link takes (`-` for none). A v15 line
962+ // stops at five, and a sixth field in one is a file this parser
963+ // never wrote.
964+ let all: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
965+ let ok = all.len() == 5 || (v16 && all.len() == 6);
966+ if !ok {
967+ return Err(format!(
968+ "line {n}: sub wants {} fields, found {}",
969+ if v16 { "5 or 6" } else { "5" },
970+ all.len()
971+ )
972+ .into());
973+ }
974+ let link = match all.get(5) {
975+ None => None,
976+ Some(f) if *f == b"-" => None,
977+ Some(f) => Some(number(f, n)?),
978+ };
979+ let f = &all;
952 let sub = SubClip {980 let sub = SubClip {
953 start: number(f[0], n)?,981 start: number(f[0], n)?,
954 frames: number(f[1], n)?,982 frames: number(f[1], n)?,
955 track: number(f[2], n)? as usize,983 track: number(f[2], n)? as usize,
956 in_us: micros(f[3], n)?,984 in_us: micros(f[3], n)?,
957 out_us: micros(f[4], n)?,985 out_us: micros(f[4], n)?,
986+ link,
958 };987 };
959 // The never-empty invariant at both clocks, which is what988 // The never-empty invariant at both clocks, which is what
960 // [`crate::Project::place_sub`] refuses on the live timeline.989 // [`crate::Project::place_sub`] refuses on the live timeline.
@@ -1440,7 +1469,7 @@ mod tests {
1440 video 1 0 0 30 0 - - - fit 1000\n";1469 video 1 0 0 30 0 - - - fit 1000\n";
1441 let old = parse(v9, &dir).expect("v9 still loads");1470 let old = parse(v9, &dir).expect("v9 still loads");
1442 assert_eq!(old.subtitles, Vec::new());1471 assert_eq!(old.subtitles, Vec::new());
1443- assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 15\n"));1472+ assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 16\n"));
1444 // ...and the line itself is not a v9 line: a dialect may not be mixed.1473 // ...and the line itself is not a v9 line: a dialect may not be mixed.
1445 let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir)1474 let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir)
1446 .unwrap_err()1475 .unwrap_err()
@@ -1773,7 +1802,7 @@ mod tests {
1773 let bytes = flat(&dir, &sources, &lanes, 12);1802 let bytes = flat(&dir, &sources, &lanes, 12);
1774 assert_eq!(1803 assert_eq!(
1775 String::from_utf8_lossy(&bytes),1804 String::from_utf8_lossy(&bytes),
1776- "edith 15\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\1805+ "edith 16\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1777 source 2 /elsewhere/b.mp4\n\1806 source 2 /elsewhere/b.mp4\n\
1778 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\1807 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1779 audio 1 0 0 30 0 0 - - fit 1000\n",1808 audio 1 0 0 30 0 0 - - fit 1000\n",
@@ -1810,7 +1839,7 @@ mod tests {
1810 let bytes = flat(&dir, &sources, &lanes, 7);1839 let bytes = flat(&dir, &sources, &lanes, 7);
1811 assert_eq!(1840 assert_eq!(
1812 String::from_utf8_lossy(&bytes),1841 String::from_utf8_lossy(&bytes),
1813- "edith 15\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\1842+ "edith 16\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
1814 video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\1843 video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\
1815 video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",1844 video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",
1816 "an empty lane is a line of its own; everything else is its clips"1845 "an empty lane is a line of its own; everything else is its clips"
@@ -1918,7 +1947,7 @@ mod tests {
1918 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);1947 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
1919 assert_eq!(1948 assert_eq!(
1920 String::from_utf8_lossy(&bytes),1949 String::from_utf8_lossy(&bytes),
1921- "edith 15\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\1950+ "edith 16\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1922 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\1951 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
1923 eq 16777215.0:-0.1:3.918315e-39:hs\n\1952 eq 16777215.0:-0.1:3.918315e-39:hs\n\
1924 eq\n\1953 eq\n\
@@ -2022,7 +2051,7 @@ mod tests {
2022 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);2051 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
2023 assert_eq!(2052 assert_eq!(
2024 String::from_utf8_lossy(&bytes),2053 String::from_utf8_lossy(&bytes),
2025- "edith 15\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\2054+ "edith 16\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
2026 color 0.1:1.2:0.9:-0.3\n\2055 color 0.1:1.2:0.9:-0.3\n\
2027 color -1e-7:16777215.0:3.918315e-39:-0.0\n\2056 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
2028 color 0.0:1.0:1.0:0.0\n\2057 color 0.0:1.0:1.0:0.0\n\
@@ -2087,7 +2116,7 @@ mod tests {
2087 (1280, 720),2116 (1280, 720),
2088 old.playhead2117 old.playhead
2089 )),2118 )),
2090- "edith 15\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\2119+ "edith 16\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
2091 eq 80.0:-3.0:0.707:ls\n\2120 eq 80.0:-3.0:0.707:ls\n\
2092 video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"2121 video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
2093 );2122 );
@@ -2125,7 +2154,7 @@ mod tests {
2125 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);2154 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
2126 assert_eq!(2155 assert_eq!(
2127 String::from_utf8_lossy(&bytes),2156 String::from_utf8_lossy(&bytes),
2128- "edith 15\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\2157+ "edith 16\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
2129 video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\2158 video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\
2130 audio 1 0 0 30 0 - - - fit 2000\n",2159 audio 1 0 0 30 0 - - - fit 2000\n",
2131 "the rate is the clip line's last field, in thousandths"2160 "the rate is the clip line's last field, in thousandths"
@@ -2154,7 +2183,7 @@ mod tests {
2154 (1280, 720),2183 (1280, 720),
2155 old.playhead2184 old.playhead
2156 )),2185 )),
2157- "edith 15\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\2186+ "edith 16\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
2158 video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"2187 video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
2159 );2188 );
2160 // A rate outside what the editor can set is a corrupt line, by name.2189 // A rate outside what the editor can set is a corrupt line, by name.
@@ -2204,7 +2233,7 @@ mod tests {
2204 );2233 );
2205 assert_eq!(2234 assert_eq!(
2206 String::from_utf8_lossy(&bytes),2235 String::from_utf8_lossy(&bytes),
2207- "edith 15\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\2236+ "edith 16\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\
2208 limiter -1.5 on\nsource 0 a.mp4\n\2237 limiter -1.5 on\nsource 0 a.mp4\n\
2209 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\2238 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\
2210 audio 2 0 0 30 0 - - - fit 1000\n\2239 audio 2 0 0 30 0 - - - fit 1000\n\
@@ -2236,7 +2265,7 @@ mod tests {
2236 (1280, 720),2265 (1280, 720),
2237 old.playhead2266 old.playhead
2238 )),2267 )),
2239- "edith 15\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\2268+ "edith 16\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
2240 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"2269 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
2241 );2270 );
2242 2271
@@ -2400,7 +2429,7 @@ mod tests {
2400 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");2429 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
2401 assert_eq!(2430 assert_eq!(
2402 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),2431 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
2403- "edith 15\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\2432+ "edith 16\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
2404 source 2 /elsewhere/b.mp4\n\2433 source 2 /elsewhere/b.mp4\n\
2405 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\2434 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
2406 audio 1 0 0 30 0 0 - - fit 1000\n"2435 audio 1 0 0 30 0 0 - - fit 1000\n"
@@ -2453,7 +2482,7 @@ mod tests {
2453 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);2482 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
2454 assert_eq!(2483 assert_eq!(
2455 String::from_utf8_lossy(&v5),2484 String::from_utf8_lossy(&v5),
2456- "edith 15\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\2485+ "edith 16\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
2457 source 0 /elsewhere/b.mp4\n\2486 source 0 /elsewhere/b.mp4\n\
2458 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\2487 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
2459 audio 1 0 0 30 0 0 - - fit 1000\n",2488 audio 1 0 0 30 0 0 - - fit 1000\n",
@@ -2485,7 +2514,7 @@ mod tests {
2485 // Saved again it is the current version, which round-trips to the2514 // Saved again it is the current version, which round-trips to the
2486 // same document.2515 // same document.
2487 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);2516 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
2488- assert!(v5.starts_with(b"edith 15\n"));2517+ assert!(v5.starts_with(b"edith 16\n"));
2489 let again = parse(&v5, &dir).expect("v5 parses");2518 let again = parse(&v5, &dir).expect("v5 parses");
2490 assert_eq!(again.lanes, back.lanes);2519 assert_eq!(again.lanes, back.lanes);
2491 // A dialect may not be mixed: lane lines under v1, `clip` under v2.2520 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
@@ -2594,7 +2623,7 @@ mod tests {
2594 let bytes = std::fs::read(&path).expect("read back");2623 let bytes = std::fs::read(&path).expect("read back");
2595 assert_eq!(2624 assert_eq!(
2596 String::from_utf8_lossy(&bytes),2625 String::from_utf8_lossy(&bytes),
2597- "edith 15\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\2626+ "edith 16\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
2598 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"2627 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
2599 );2628 );
2600 // Loading rejoins the *given* directory, so the file is reached by the2629 // Loading rejoins the *given* directory, so the file is reached by the
@@ -2639,10 +2668,10 @@ mod tests {
2639 #[test]2668 #[test]
2640 fn a_wrong_first_line_is_refused_by_name() {2669 fn a_wrong_first_line_is_refused_by_name() {
2641 let dir = PathBuf::from("/proj");2670 let dir = PathBuf::from("/proj");
2642- let err = parse(b"edith 16\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)2671+ let err = parse(b"edith 17\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
2643 .unwrap_err()2672 .unwrap_err()
2644 .to_string();2673 .to_string();
2645- assert_eq!(err, "line 1: unsupported version 16");2674+ assert_eq!(err, "line 1: unsupported version 17");
2646 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {2675 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
2647 assert_eq!(2676 assert_eq!(
2648 parse(junk, &dir).unwrap_err().to_string(),2677 parse(junk, &dir).unwrap_err().to_string(),
crates/engine/src/playback.rsmodified+36 -0
@@ -1825,6 +1825,42 @@ impl PlaybackSession {
1825 self.project.group(a, a_idx, b, b_idx)1825 self.project.group(a, a_idx, b, b_idx)
1826 }1826 }
1827 1827
1828+ /// Puts every placement the picks name into one group
1829+ /// ([`Project::group_all`]) -- the ctrl-click selection's own door, which
1830+ /// may name clips and captions alike. Metadata only like the pair above:
1831+ /// no reseek, one undo step, and the error says why when it refuses.
1832+ pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
1833+ self.project.group_all(picks)
1834+ }
1835+
1836+ /// [`delete_clip`](Self::delete_clip) for the caption the pick named: a
1837+ /// caption in no group lifts exactly as [`lift_sub`](Self::lift_sub) lifts
1838+ /// it -- no reseek, because nothing that plays has changed -- and a caption
1839+ /// in a group takes the group with it, which ripples the media members and
1840+ /// reseeks like a delete. `false` for a bad index.
1841+ pub fn delete_sub(&mut self, lane: Lane, idx: usize) -> bool {
1842+ // Which of the two, asked before anything moves: the reseek a grouped
1843+ // delete owes is the whole difference between the paths.
1844+ let grouped = self
1845+ .project
1846+ .sub_lane(lane)
1847+ .get(idx)
1848+ .and_then(|s| s.link)
1849+ .is_some_and(|id| {
1850+ self.project
1851+ .lanes()
1852+ .into_iter()
1853+ .any(|l| l != lane && self.project.lane(l).iter().any(|c| c.link == Some(id)))
1854+ });
1855+ match grouped {
1856+ true => self.edit(Dirty::Both, |p| p.delete_sub_in(lane, idx)),
1857+ // A caption in no group -- or one grouped only with other captions,
1858+ // which lift and move nothing that plays -- is the lift it always
1859+ // was.
1860+ false => self.project.delete_sub_in(lane, idx),
1861+ }
1862+ }
1863+
1828 /// What the clip at `idx` of `lane` is equalized with, or `None` for one1864 /// What the clip at `idx` of `lane` is equalized with, or `None` for one
1829 /// that plays flat -- what a card shows before it lets anyone drag a band.1865 /// that plays flat -- what a card shows before it lets anyone drag a band.
1830 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {1866 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
crates/engine/src/project.rsmodified+1038 -348
@@ -561,6 +561,12 @@ pub struct SubClip {
561 /// keeps it.561 /// keeps it.
562 pub in_us: i64,562 pub in_us: i64,
563 pub out_us: i64,563 pub out_us: i64,
564+ /// Group id: `Some` exactly when a hand put this caption in a group with
565+ /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in
566+ /// no group, and what a cut cuts apart loses the one it had
567+ /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a
568+ /// clip is what makes the caption move, trim and delete with it.
569+ pub link: Option<u32>,
564 }570 }
565 571
566 impl SubClip {572 impl SubClip {
@@ -634,6 +640,25 @@ impl LaneData {
634 }640 }
635 }641 }
636 642
643+/// The placements one group id names, split by the two lists a lane holds:
644+/// what a drag, a trim and a delete each have to walk, now that a group may
645+/// hold a caption beside its clips ([`Project::group_all`]). A clip and a
646+/// caption of one group never share a lane -- a subtitle lane holds no `Clip`
647+/// -- so the pairs are `(lane storage index, index into that lane's list)`.
648+#[derive(Default)]
649+struct Members {
650+ clips: Vec<(usize, usize)>,
651+ subs: Vec<(usize, usize)>,
652+}
653+
654+impl Members {
655+ /// Whether the group is the one placement and no more: what a lift leaves
656+ /// behind, and what every whole-group question answers "not one" for.
657+ fn alone(&self) -> bool {
658+ self.clips.len() + self.subs.len() < 2
659+ }
660+}
661+
637 /// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.662 /// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
638 #[derive(Clone, Copy, PartialEq, Eq, Debug)]663 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
639 pub enum Edge {664 pub enum Edge {
@@ -1639,7 +1664,14 @@ impl Project {
1639 )1664 )
1640 .into());1665 .into());
1641 }1666 }
1642- let sub = SubClip { start: at, ..sub };1667+ // The placement belongs to no group, for [`place`]'s reason: a caption
1668+ // dragged out of the palette arrives alone, and grouping it with what
1669+ // is under it is a hand's decision ([`Project::group_all`]).
1670+ let sub = SubClip {
1671+ start: at,
1672+ link: None,
1673+ ..sub
1674+ };
1643 if at.checked_add(sub.frames).is_none() {1675 if at.checked_add(sub.frames).is_none() {
1644 return Err(format!("a placement at frame {at} runs past the last frame there is").into());1676 return Err(format!("a placement at frame {at} runs past the last frame there is").into());
1645 }1677 }
@@ -1667,11 +1699,16 @@ impl Project {
1667 }1699 }
1668 1700
1669 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`1701 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
1670- /// -- [`move_clip`](Project::move_clip)'s twin, and refusing an overlap1702+ /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
1671- /// where that one clamps to it, for [`place_sub`](Project::place_sub)'s1703+ /// refused an overlap where that one clamps to it, for
1672- /// reason: there is no group to hold a subtitle still and no picture under1704+ /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
1673- /// it that a landing would hide, so "as far as it goes" would silently be a1705+ /// still and no picture under it that a landing would hide, so "as far as
1674- /// frame nobody named.1706+ /// it goes" would silently be a frame nobody named.
1707+ ///
1708+ /// A caption *in* a group drags the group: one delta for every member --
1709+ /// its clips and its other captions -- clamped to the room each of them
1710+ /// has, exactly as a clip's drag always has. That is the point of putting
1711+ /// a caption in a group: the words go where the picture goes.
1675 ///1712 ///
1676 /// The window travels untouched: a caption dragged later says the same1713 /// The window travels untouched: a caption dragged later says the same
1677 /// words later, exactly as a clip dragged later plays the same pictures1714 /// words later, exactly as a clip dragged later plays the same pictures
@@ -1679,9 +1716,10 @@ impl Project {
1679 ///1716 ///
1680 /// One undo step on success; nothing changed and no step on a refusal --1717 /// One undo step on success; nothing changed and no step on a refusal --
1681 /// an index that is not there, a lane that is not a subtitle lane or is not1718 /// an index that is not there, a lane that is not a subtitle lane or is not
1682- /// there, and an overlap. A drop that changes neither lane nor frame is1719+ /// there, and (for a caption in no group) an overlap. A drop that changes
1683- /// `Ok` and no step: a hand that picked a caption up and put it back has1720+ /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
1684- /// done nothing wrong, and a front-end showing every `Err` would say so.1721+ /// up and put it back has done nothing wrong, and a front-end showing every
1722+ /// `Err` would say so.
1685 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {1723 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
1686 let Some(sub) = self.sub_lane(from).get(idx).copied() else {1724 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
1687 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());1725 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
@@ -1707,6 +1745,51 @@ impl Project {
1707 format!("a placement at frame {start} runs past the last frame there is").into(),1745 format!("a placement at frame {start} runs past the last frame there is").into(),
1708 );1746 );
1709 }1747 }
1748+ // A grouped caption carries its group, clamped to the room the whole
1749+ // group has rather than refused ([`Project::move_room]) -- one drag, one
1750+ // delta, one undo step.
1751+ let members = self.group_of(from, idx).expect("the subtitle was found");
1752+ if !members.alone() {
1753+ if members
1754+ .subs
1755+ .iter()
1756+ .any(|&(l, i)| l == dest && (l, i) != (here, idx))
1757+ {
1758+ return Err(format!(
1759+ "a group is one caption per track: {} already carries this group",
1760+ to.label()
1761+ )
1762+ .into());
1763+ }
1764+ let want = i64::from(start) - i64::from(sub.start);
1765+ let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start))) else {
1766+ return Err(format!(
1767+ "another placement already covers those frames on {}",
1768+ to.label()
1769+ )
1770+ .into());
1771+ };
1772+ let delta = want.clamp(lo, hi);
1773+ self.snapshot();
1774+ for &(l, i) in &members.clips {
1775+ let c = &mut self.lanes[l].clips[i];
1776+ c.start = (i64::from(c.start) + delta) as u32;
1777+ }
1778+ for &(l, i) in &members.subs {
1779+ let s = &mut self.lanes[l].subs[i];
1780+ s.start = (i64::from(s.start) + delta) as u32;
1781+ }
1782+ let moved = self.lanes[here].subs.remove(idx);
1783+ let subs = &mut self.lanes[dest].subs;
1784+ let at = subs.partition_point(|o| o.start < moved.start);
1785+ subs.insert(at, moved);
1786+ debug_assert!(subs_sorted_disjoint(subs));
1787+ debug_assert!(members
1788+ .clips
1789+ .iter()
1790+ .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips)));
1791+ return Ok(());
1792+ }
1710 let moved = SubClip { start, ..sub };1793 let moved = SubClip { start, ..sub };
1711 if let Some(other) = self.lanes[dest]1794 if let Some(other) = self.lanes[dest]
1712 .subs1795 .subs
@@ -1790,6 +1873,7 @@ impl Project {
1790 return Ok(());1873 return Ok(());
1791 }1874 }
1792 self.snapshot();1875 self.snapshot();
1876+ let members = self.group_of(lane, idx).expect("the subtitle was found");
1793 let i = self.index(lane).expect("the subtitle was found on it");1877 let i = self.index(lane).expect("the subtitle was found on it");
1794 let s = &mut self.lanes[i].subs[idx];1878 let s = &mut self.lanes[i].subs[idx];
1795 match edge {1879 match edge {
@@ -1812,6 +1896,11 @@ impl Project {
1812 }1896 }
1813 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);1897 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
1814 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));1898 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
1899+ // A caption in a group drags its group's edge with it, exactly as a
1900+ // clip's trim does: one delta, each member clamped to its own room.
1901+ // No source table to grow by, which only tightens how far a member may
1902+ // follow -- never whether it may.
1903+ self.follow_group(&members, &(i, idx), edge, i64::from(to) - i64::from(at), &[]);
1815 Ok(())1904 Ok(())
1816 }1905 }
1817 1906
@@ -2107,8 +2196,9 @@ impl Project {
2107 return Err(format!("there is no clip {idx} on {}", lane.label()).into());2196 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2108 };2197 };
2109 let labels = handles(&self.lanes);2198 let labels = handles(&self.lanes);
2110- let mut span: Option<(Lane, u32, u32)> = None;2199+ // Media members only: a caption has no rate to change, and what the
2111- for &(l, i) in &members {2200+ // id binds it to -- a move, a trim, a delete -- travels by frames.
2201+ for &(l, i) in &members.clips {
2112 let clips = &self.lanes[l].clips;2202 let clips = &self.lanes[l].clips;
2113 let mut moved = clips[i];2203 let mut moved = clips[i];
2114 moved.speed = speed;2204 moved.speed = speed;
@@ -2124,34 +2214,11 @@ impl Project {
2124 )2214 )
2125 .into());2215 .into());
2126 }2216 }
2127- // A link is **one span on however many lanes**
2128- // ([`links_are_consistent`]), and one rate over two halves does not
2129- // guarantee that: two clips of *different source lengths* can occupy
2130- // the same timeline frames at their old rates (rounding collapses
2131- // neighbouring lengths onto one footprint at 4x), and re-rating them
2132- // pulls those footprints apart. Refused by name rather than written
2133- // -- a group whose halves disagree about their span is a project
2134- // that would not load again.
2135- match span {
2136- None => span = Some((labels[l], moved.start, moved.end())),
2137- Some((first, start, end)) if (start, end) != (moved.start, moved.end()) => {
2138- return Err(format!(
2139- "at {speed} the {} half would cover [{}, {}) and the {} half [{start}, {end}): \
2140- they are one take and a take is one span -- detach them first",
2141- labels[l].label(),
2142- moved.start,
2143- moved.end(),
2144- first.label()
2145- )
2146- .into());
2147- }
2148- Some(_) => {}
2149- }
2150 }2217 }
2151 if snapshot {2218 if snapshot {
2152 self.snapshot();2219 self.snapshot();
2153 }2220 }
2154- for (l, i) in members {2221+ for (l, i) in members.clips {
2155 self.lanes[l].clips[i].speed = speed;2222 self.lanes[l].clips[i].speed = speed;
2156 debug_assert!(sorted_disjoint(&self.lanes[l].clips));2223 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
2157 }2224 }
@@ -2507,6 +2574,24 @@ impl Project {
2507 on.contains(&i) && l.subs.iter().any(|s| s.start < timeline_frame && timeline_frame < s.end())2574 on.contains(&i) && l.subs.iter().any(|s| s.start < timeline_frame && timeline_frame < s.end())
2508 })2575 })
2509 .collect();2576 .collect();
2577+ // The links the captions carry, read before the room is opened below
2578+ // -- `sub_open_room` takes the id off both halves, exactly as
2579+ // `open_room` does for a clip, and the split hands the halves theirs
2580+ // back afterwards.
2581+ let sub_orig: Vec<Option<u32>> = self
2582+ .lanes
2583+ .iter()
2584+ .zip(&cut_subs)
2585+ .map(|(l, &cut)| {
2586+ cut.then(|| {
2587+ l.subs
2588+ .iter()
2589+ .find(|s| s.start < timeline_frame && timeline_frame < s.end())
2590+ .and_then(|s| s.link)
2591+ })
2592+ .flatten()
2593+ })
2594+ .collect();
2510 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {2595 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
2511 return false;2596 return false;
2512 }2597 }
@@ -2524,22 +2609,42 @@ impl Project {
2524 sub_open_room(&mut data.subs, timeline_frame, 0);2609 sub_open_room(&mut data.subs, timeline_frame, 0);
2525 debug_assert!(subs_sorted_disjoint(&data.subs));2610 debug_assert!(subs_sorted_disjoint(&data.subs));
2526 }2611 }
2527- // Each side is its own question: two clips may start together and end2612+ // Each side is its own question, and the answer is the group the clip
2528- // apart, and every lane whose halves do line up stays one take.2613+ // already carried: the left half *keeps* its take's id -- the take the
2529- let starts: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.start)).collect();2614+ // frames before the cut still are -- and the right halves of one take
2530- let ends: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.end())).collect();2615+ // share one fresh id of their own, clips and captions alike. A lane
2531- let left = self.group_ids(&starts);2616+ // holding no group (a `place`ment, a caption nobody grouped) comes out
2532- let right = self.group_ids(&ends);2617+ // of the cut holding none, which is what it went in with. The captions'
2533- for (((data, left), right), cut) in self2618+ // own links were drawn above, before the room opened.
2534- .lanes2619+ let orig: Vec<Option<u32>> = cut.iter().map(|c| c.and_then(|c| c.link)).collect();
2535- .iter_mut()2620+ let mut distinct: Vec<u32> = Vec::new();
2536- .zip(left)2621+ for id in orig.iter().chain(&sub_orig).flatten() {
2537- .zip(right)2622+ if !distinct.contains(id) {
2538- .zip(cut.iter().map(Option::is_some))2623+ distinct.push(*id);
2539- {2624+ }
2625+ }
2626+ let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
2627+ let right_of =
2628+ |link: Option<u32>| link.and_then(|id| distinct.iter().position(|&d| d == id)).map(|at| fresh[at]);
2629+ for (l, data) in self.lanes.iter_mut().enumerate() {
2630+ if !cut_subs[l] {
2631+ continue;
2632+ }
2633+ // The pair the razor just made: they touch at the frame it cut.
2634+ if let Some(idx) = data
2635+ .subs
2636+ .iter()
2637+ .position(|s| s.end() == timeline_frame)
2638+ .filter(|&idx| data.subs.get(idx + 1).is_some_and(|n| n.start == timeline_frame))
2639+ {
2640+ data.subs[idx].link = sub_orig[l];
2641+ data.subs[idx + 1].link = right_of(sub_orig[l]);
2642+ }
2643+ }
2644+ for (data_i, data) in self.lanes.iter_mut().enumerate() {
2540 // The lanes this call was not scoped to are not cut, whatever their2645 // The lanes this call was not scoped to are not cut, whatever their
2541 // own clips would allow.2646 // own clips would allow.
2542- let Some(idx) = splittable(&data.clips, timeline_frame).filter(|_| cut) else {2647+ let Some(idx) = splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some()) else {
2543 continue;2648 continue;
2544 };2649 };
2545 let mut tail = data.clips[idx];2650 let mut tail = data.clips[idx];
@@ -2549,9 +2654,9 @@ impl Project {
2549 // the two would not add up to the one being cut.2654 // the two would not add up to the one being cut.
2550 tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");2655 tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");
2551 tail.start = timeline_frame;2656 tail.start = timeline_frame;
2552- tail.link = right;2657+ tail.link = right_of(orig[data_i]);
2553 data.clips[idx].out_frame = tail.in_frame;2658 data.clips[idx].out_frame = tail.in_frame;
2554- data.clips[idx].link = left;2659+ data.clips[idx].link = orig[data_i];
2555 data.clips.insert(idx + 1, tail);2660 data.clips.insert(idx + 1, tail);
2556 }2661 }
2557 true2662 true
@@ -2562,9 +2667,9 @@ impl Project {
2562 /// Only what a split could have produced is rejoined -- the two sides must2667 /// Only what a split could have produced is rejoined -- the two sides must
2563 /// touch on the timeline *and* be consecutive frames of the same source --2668 /// touch on the timeline *and* be consecutive frames of the same source --
2564 /// so the clip list comes back exactly as it was and traversal with it.2669 /// so the clip list comes back exactly as it was and traversal with it.
2565- /// `false` when no lane has such a pair. The rejoined clips share one id2670+ /// `false` when no lane has such a pair. The rejoined placement keeps the
2566- /// only when they rejoin into the same span, for [`split`](Project::split)'s2671+ /// **left** half's id, which is the take the split left on it: rejoining a
2567- /// reason.2672+ /// cut take puts the take back, id and all.
2568 pub fn regroup(&mut self, timeline_frame: u32) -> bool {2673 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
2569 // What each lane would end up covering, if it joins here at all.2674 // What each lane would end up covering, if it joins here at all.
2570 let joined: Vec<Option<(u32, u32)>> = self2675 let joined: Vec<Option<(u32, u32)>> = self
@@ -2585,8 +2690,7 @@ impl Project {
2585 return false;2690 return false;
2586 }2691 }
2587 self.snapshot();2692 self.snapshot();
2588- let ids = self.group_ids(&joined);2693+ for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
2589- for ((data, link), sub) in self.lanes.iter_mut().zip(ids).zip(join_subs) {
2590 if let Some(idx) = sub {2694 if let Some(idx) = sub {
2591 data.subs[idx].frames += data.subs[idx + 1].frames;2695 data.subs[idx].frames += data.subs[idx + 1].frames;
2592 data.subs[idx].out_us = data.subs[idx + 1].out_us;2696 data.subs[idx].out_us = data.subs[idx + 1].out_us;
@@ -2597,16 +2701,17 @@ impl Project {
2597 continue;2701 continue;
2598 };2702 };
2599 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;2703 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
2600- data.clips[idx].link = link;
2601 data.clips.remove(idx + 1);2704 data.clips.remove(idx + 1);
2602 }2705 }
2603 true2706 true
2604 }2707 }
2605 2708
2606- /// Take the clip at `idx` of `lane` out of its group: every clip carrying2709+ /// Take the placement at `idx` of `lane` out of its group: every clip and
2607- /// its id -- on however many lanes -- is handed an id of its own, so from2710+ /// every caption carrying its id -- on however many lanes -- is handed an
2608- /// here on each half moves, trims and is deleted alone. The music video2711+ /// id of its own, so from here on each half moves, trims and is deleted
2609- /// whose sound is to be cut against its picture starts here.2712+ /// alone. The music video whose sound is to be cut against its picture
2713+ /// starts here, and so does the caption that has to come off the picture it
2714+ /// was pinned to.
2610 ///2715 ///
2611 /// An id of its own rather than none at all: a half no other lane is grouped2716 /// An id of its own rather than none at all: a half no other lane is grouped
2612 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal2717 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
@@ -2617,30 +2722,36 @@ impl Project {
2617 /// Metadata only, like a [`split`](Project::split): no mapping changes, so2722 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
2618 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts2723 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
2619 /// the group back. Refused (`false`, nothing changed) for an index that is2724 /// the group back. Refused (`false`, nothing changed) for an index that is
2620- /// not there, a clip in no group at all, and one whose group has no other2725+ /// not there, a placement in no group at all, and one whose group has no
2621- /// half -- that one is already detached, and a refusal must not cost an undo2726+ /// other half -- that one is already detached, and a refusal must not cost
2622- /// step.2727+ /// an undo step.
2623 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {2728 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
2624- let Some(id) = self.lane(lane).get(idx).and_then(|c| c.link) else {2729+ let Some(members) = self.group_of(lane, idx) else {
2625 return false;2730 return false;
2626 };2731 };
2627- let members = self2732+ if members.alone() {
2628- .lanes
2629- .iter()
2630- .flat_map(|l| &l.clips)
2631- .filter(|c| c.link == Some(id))
2632- .count();
2633- if members < 2 {
2634 return false;2733 return false;
2635 }2734 }
2735+ let Some(id) = self
2736+ .lane(lane)
2737+ .get(idx)
2738+ .and_then(|c| c.link)
2739+ .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
2740+ else {
2741+ return false;
2742+ };
2636 self.snapshot();2743 self.snapshot();
2637 // Drawn before the walk: `new_link` takes the whole project, and the2744 // Drawn before the walk: `new_link` takes the whole project, and the
2638 // walk holds the lanes.2745 // walk holds the lanes.
2639- let mut fresh = (0..members).map(|_| self.new_link()).collect::<Vec<_>>();2746+ let count = members.clips.len() + members.subs.len();
2747+ let mut fresh = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
2640 for data in &mut self.lanes {2748 for data in &mut self.lanes {
2641 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {2749 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
2642 c.link = fresh.pop();2750 c.link = fresh.pop();
2643 }2751 }
2752+ for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
2753+ s.link = fresh.pop();
2754+ }
2644 }2755 }
2645 debug_assert!(links_are_consistent(&self.lanes).is_ok());2756 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2646 true2757 true
@@ -2712,6 +2823,103 @@ impl Project {
2712 Ok(())2823 Ok(())
2713 }2824 }
2714 2825
2826+ /// Put every placement the picks name into one group -- the group a hand
2827+ /// builds with ctrl-click and a menu: the picture, its sound and the
2828+ /// caption over it, on as many lanes as the picks name. What any of them
2829+ /// was already grouped with rides along (one group, not two sharing a
2830+ /// member), and the members keep their own spans: a group is one id over
2831+ /// one placement per lane, and the offsets between them are what the group
2832+ /// preserves -- a drag, a trim and a delete all move the members *by the
2833+ /// same distance*, not to the same frames.
2834+ ///
2835+ /// No two picks may name one lane -- that is the one clip-per-lane rule,
2836+ /// and the refusal says which lane -- and a pick that names nothing is
2837+ /// refused with its own words. At least two picks, or there is nothing to
2838+ /// group.
2839+ ///
2840+ /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
2841+ /// apart again. None of the refusals changes anything or costs an undo
2842+ /// step.
2843+ pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
2844+ if picks.len() < 2 {
2845+ return Err("a group is two placements or more: pick another one first".into());
2846+ }
2847+ let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
2848+ for &(lane, idx) in picks {
2849+ if seen.contains(&lane) {
2850+ return Err(format!(
2851+ "a group is one placement per lane: {} is picked twice -- keep one clip per \
2852+ track",
2853+ lane.label()
2854+ )
2855+ .into());
2856+ }
2857+ seen.push(lane);
2858+ let there = if lane.kind == LaneKind::Subtitle {
2859+ idx < self.sub_lane(lane).len()
2860+ } else {
2861+ idx < self.lane(lane).len()
2862+ };
2863+ if !there {
2864+ let what = if lane.kind == LaneKind::Subtitle {
2865+ "subtitle"
2866+ } else {
2867+ "clip"
2868+ };
2869+ return Err(
2870+ format!("there is no {what} {idx} on {}", lane.label()).into()
2871+ );
2872+ }
2873+ }
2874+ let links: Vec<Option<u32>> = picks
2875+ .iter()
2876+ .map(|&(lane, idx)| {
2877+ if lane.kind == LaneKind::Subtitle {
2878+ self.sub_lane(lane)[idx].link
2879+ } else {
2880+ self.lane(lane)[idx].link
2881+ }
2882+ })
2883+ .collect();
2884+ self.snapshot();
2885+ let id = self.new_link();
2886+ // Whatever any pick was grouped with comes along, for [`group`]'s
2887+ // reason -- one id over the lot, not two groups sharing a member.
2888+ for data in &mut self.lanes {
2889+ for c in data.clips.iter_mut() {
2890+ if c.link.is_some() && links.contains(&c.link) {
2891+ c.link = Some(id);
2892+ }
2893+ }
2894+ for s in data.subs.iter_mut() {
2895+ if s.link.is_some() && links.contains(&s.link) {
2896+ s.link = Some(id);
2897+ }
2898+ }
2899+ }
2900+ // And the picks themselves, which a `place` may have left in no group.
2901+ // The lane seats are read before the walk, which holds the lanes.
2902+ let seats: Vec<(usize, bool)> = picks
2903+ .iter()
2904+ .map(|&(lane, _)| {
2905+ (
2906+ self.index(lane).expect("checked above"),
2907+ lane.kind == LaneKind::Subtitle,
2908+ )
2909+ })
2910+ .collect();
2911+ for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
2912+ let _ = lane;
2913+ if sub {
2914+ self.lanes[at].subs[idx].link = Some(id);
2915+ } else {
2916+ self.lanes[at].clips[idx].link = Some(id);
2917+ }
2918+ }
2919+ debug_assert!(links_are_consistent(&self.lanes).is_ok());
2920+ Ok(())
2921+ }
2922+
2715 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it2923 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
2716 /// lands on and leaving every other clip exactly where it is -- the2924 /// lands on and leaving every other clip exactly where it is -- the
2717 /// per-lane paste. Anything already there is trimmed away (and split in two2925 /// per-lane paste. Anything already there is trimmed away (and split in two
@@ -2841,40 +3049,23 @@ impl Project {
2841 // is the one thing a link may never mean. Refused rather than clamped:3049 // is the one thing a link may never mean. Refused rather than clamped:
2842 // the partner moves the same distance, so there is no room for it3050 // the partner moves the same distance, so there is no room for it
2843 // anywhere on that lane.3051 // anywhere on that lane.
2844- if dest != held && members.iter().any(|&(l, _)| l == dest) {3052+ if dest != held
3053+ && members
3054+ .clips
3055+ .iter()
3056+ .chain(&members.subs)
3057+ .any(|&(l, _)| l == dest)
3058+ {
2845 return false;3059 return false;
2846 }3060 }
2847 let want = i64::from(start) - i64::from(clip.start);3061 let want = i64::from(start) - i64::from(clip.start);
2848 // How far the group may travel, in timeline frames and signed: every3062 // How far the group may travel, in timeline frames and signed: every
2849- // member narrows it to the gap it is landing in, and what is left is3063+ // member -- the clips and any caption grouped with them -- narrows it
2850- // what the pointer is clamped to.3064+ // to the gap it is landing in, and what is left is what the pointer is
2851- let (mut lo, mut hi) = (i64::MIN, i64::MAX);3065+ // clamped to.
2852- for &(l, i) in &members {3066+ let Some((lo, hi)) = self.move_room(&members, Some((held, idx, dest, start))) else {
2853- let c = self.lanes[l].clips[i];3067+ return false;
2854- let land = if (l, i) == (held, idx) { dest } else { l };3068+ };
2855- // Which gap this member's walls are read off: its own place on the
2856- // lane it stays on, and the frame the pointer named on the lane it
2857- // is let go over.
2858- let at = if land == l { c.start } else { start };
2859- let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
2860- for (j, other) in self.lanes[land].clips.iter().enumerate() {
2861- if members.contains(&(land, j)) {
2862- continue;
2863- }
2864- if other.start <= at && at < other.end() {
2865- return false;
2866- }
2867- match other.end() <= at {
2868- true => wall_lo = wall_lo.max(other.end()),
2869- false => wall_hi = wall_hi.min(other.start),
2870- }
2871- }
2872- if wall_hi - wall_lo < c.frames() {
2873- return false;
2874- }
2875- lo = lo.max(i64::from(wall_lo) - i64::from(c.start));
2876- hi = hi.min(i64::from(wall_hi - c.frames()) - i64::from(c.start));
2877- }
2878 if lo > hi {3069 if lo > hi {
2879 return false;3070 return false;
2880 }3071 }
@@ -2883,11 +3074,15 @@ impl Project {
2883 return false;3074 return false;
2884 }3075 }
2885 self.snapshot();3076 self.snapshot();
2886- for &(l, i) in &members {3077+ for &(l, i) in &members.clips {
2887 let c = &mut self.lanes[l].clips[i];3078 let c = &mut self.lanes[l].clips[i];
2888 // In range by the walls above, which are `u32` frames throughout.3079 // In range by the walls above, which are `u32` frames throughout.
2889 c.start = (i64::from(c.start) + delta) as u32;3080 c.start = (i64::from(c.start) + delta) as u32;
2890 }3081 }
3082+ for &(l, i) in &members.subs {
3083+ let s = &mut self.lanes[l].subs[i];
3084+ s.start = (i64::from(s.start) + delta) as u32;
3085+ }
2891 if dest != held {3086 if dest != held {
2892 let clip = self.lanes[held].clips.remove(idx);3087 let clip = self.lanes[held].clips.remove(idx);
2893 let clips = &mut self.lanes[dest].clips;3088 let clips = &mut self.lanes[dest].clips;
@@ -2895,14 +3090,93 @@ impl Project {
2895 clips.insert(at, clip);3090 clips.insert(at, clip);
2896 }3091 }
2897 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));3092 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
2898- debug_assert!(3093+ debug_assert!(members
2899- members3094+ .clips
2900- .iter()3095+ .iter()
2901- .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips))3096+ .chain(&members.subs)
2902- );3097+ .all(|&(l, _)| {
3098+ sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
3099+ }));
2903 true3100 true
2904 }3101 }
2905 3102
3103+ /// How far a group drag may travel, `(least, most)` in timeline frames and
3104+ /// signed: every member narrows the range to the gap it is landing in --
3105+ /// the clips against their lanes' clips and the captions against their
3106+ /// lanes' captions -- and what is left is what the pointer is clamped to.
3107+ /// `travelling` names the one member that changes lane, if any: the clip a
3108+ /// hand is carrying onto another track, whose walls are read on the lane it
3109+ /// is let go over at the frame the pointer named. `None` when a member has
3110+ /// no gap to land in at all.
3111+ fn move_room(
3112+ &self,
3113+ members: &Members,
3114+ travelling: Option<(usize, usize, usize, u32)>,
3115+ ) -> Option<(i64, i64)> {
3116+ let (mut lo, mut hi) = (i64::MIN, i64::MAX);
3117+ for &(l, i) in members.clips.iter().chain(&members.subs) {
3118+ let sub = members.subs.contains(&(l, i));
3119+ let (start, frames) = match self.lanes[l]
3120+ .clips
3121+ .get(i)
3122+ .filter(|_| !sub)
3123+ .map(|c| (c.start, c.frames()))
3124+ {
3125+ Some(pair) => pair,
3126+ None => {
3127+ let s = self.lanes[l].subs.get(i)?;
3128+ (s.start, s.frames)
3129+ }
3130+ };
3131+ let land = travelling
3132+ .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
3133+ .map_or(l, |(_, _, dest, _)| dest);
3134+ // Which gap this member's walls are read off: its own place on the
3135+ // lane it stays on, and the frame the pointer named on the lane it
3136+ // is let go over. A clip's neighbours are the clips of the lane it
3137+ // lands on and a caption's are its captions -- the two lists of one
3138+ // lane never meet.
3139+ let at = match travelling {
3140+ Some((fl, fi, _, asked)) if (fl, fi) == (l, i) && land != l => asked,
3141+ _ => start,
3142+ };
3143+ let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
3144+ let neighbours: Vec<(u32, u32)> = if sub {
3145+ self.lanes[land]
3146+ .subs
3147+ .iter()
3148+ .map(|s| (s.start, s.end()))
3149+ .collect()
3150+ } else {
3151+ self.lanes[land]
3152+ .clips
3153+ .iter()
3154+ .map(|c| (c.start, c.end()))
3155+ .collect()
3156+ };
3157+ for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
3158+ if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
3159+ continue;
3160+ }
3161+ if *other_start <= at && at < *other_end {
3162+ // A head let go inside another placement, which a clamp
3163+ // has no answer for: the drop is refused.
3164+ return None;
3165+ }
3166+ match other_end <= &at {
3167+ true => wall_lo = wall_lo.max(*other_end),
3168+ false => wall_hi = wall_hi.min(*other_start),
3169+ }
3170+ }
3171+ if wall_hi - wall_lo < frames {
3172+ return None;
3173+ }
3174+ lo = lo.max(i64::from(wall_lo) - i64::from(start));
3175+ hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
3176+ }
3177+ Some((lo, hi))
3178+ }
3179+
2906 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --3180 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
2907 /// the drag on a clip's end that makes it play more or less of its source.3181 /// the drag on a clip's end that makes it play more or less of its source.
2908 /// The rest of the lane stays exactly where it is (nothing ripples), so what3182 /// The rest of the lane stays exactly where it is (nothing ripples), so what
@@ -2926,10 +3200,10 @@ impl Project {
2926 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry3200 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
2927 /// there may not grow at all.3201 /// there may not grow at all.
2928 ///3202 ///
2929- /// Linked clips trim *together*, to one clamped edge: a link is one span on3203+ /// Linked placements trim *together*, by one delta: every member's same
2930- /// however many lanes ([`links_are_consistent`]), so a picture trimmed away3204+ /// edge moves the distance the dragged one did, clamped to the room its
2931- /// from its sound would be a group no save could load. The room is therefore3205+ /// own walls leave -- offsets between the members of a hand-built group
2932- /// what every member of the group has -- the tightest wall wins.3206+ /// survive the trim, exactly as they survive a drag.
2933 ///3207 ///
2934 /// `false`, changing nothing and costing no undo step, for an index that is3208 /// `false`, changing nothing and costing no undo step, for an index that is
2935 /// not there and for an edge that is already where it was asked to go.3209 /// not there and for an edge that is already where it was asked to go.
@@ -2956,64 +3230,130 @@ impl Project {
2956 return false;3230 return false;
2957 }3231 }
2958 // Worked out before anything moves: at a slow rate a room can be too3232 // Worked out before anything moves: at a slow rate a room can be too
2959- // narrow to hold even one source frame ([`Speed::fit`]), and a member3233+ // narrow to hold even one source frame ([`Speed::fit`]), and the
2960- // that cannot fit must refuse the whole gesture rather than be given a3234+ // dragged clip refusing to fit must refuse the whole gesture rather
2961- // range wider than its room -- which is the overlap the lane invariant3235+ // than be given a range wider than its room -- which is the overlap
2962- // exists to forbid. The walls below leave that room, so this is the3236+ // the lane invariant exists to forbid. The walls below leave that room,
2963- // backstop for a project that came in through another door.3237+ // so this is the backstop for a project that came in through another
3238+ // door.
3239+ let room = match edge {
3240+ // The frames that stay play what they played, so what survives is
3241+ // measured from the *end*.
3242+ Edge::Start => clip.end() - to,
3243+ Edge::End => to - clip.start,
3244+ };
3245+ let Some(keep) = clip.speed.fit(room) else {
3246+ return false;
3247+ };
2964 let members = self.group_of(lane, idx).expect("checked above");3248 let members = self.group_of(lane, idx).expect("checked above");
2965- let mut fitted = Vec::with_capacity(members.len());3249+ self.snapshot();
2966- for &(l, i) in &members {3250+ let still = self.is_still(&clip);
3251+ let held = self.index(lane).expect("checked above");
3252+ let c = &mut self.lanes[held].clips[idx];
3253+ match edge {
3254+ // A still has no earlier frame to walk an in-point back to --
3255+ // every frame of it is the same picture -- so its head grows
3256+ // *forward*: the range it plays is however long the new room is,
3257+ // anchored at the source's frame 0. Bounded by `lo`, which is where
3258+ // the cap in `source_frames` is applied.
3259+ Edge::Start if still => {
3260+ c.in_frame = 0;
3261+ c.out_frame = keep;
3262+ c.start = to;
3263+ }
3264+ Edge::Start => {
3265+ // Non-negative by `lo`, which is what keeps the in-point on the
3266+ // source.
3267+ c.in_frame = c.out_frame - keep.min(c.out_frame);
3268+ c.start = to;
3269+ }
3270+ // Never wider than the room the edge was clamped to: see
3271+ // [`Speed::fit`].
3272+ Edge::End => c.out_frame = c.in_frame + keep,
3273+ }
3274+ debug_assert!(sorted_disjoint(&self.lanes[held].clips));
3275+ self.follow_group(&members, &(held, idx), edge, i64::from(to) - i64::from(at), source_frames);
3276+ true
3277+ }
3278+
3279+ /// The rest of a group after one member's `edge` has moved by `delta`:
3280+ /// every other member's same edge moves the same distance, clamped to the
3281+ /// room its own walls leave -- a clip's against its lane and its source,
3282+ /// a caption's against its own lane, its window following by the
3283+ /// placement's own proportion. The undo step is the caller's: this is the
3284+ // second half of one edit, not an edit of its own.
3285+ fn follow_group(
3286+ &mut self,
3287+ members: &Members,
3288+ dragged: &(usize, usize),
3289+ edge: Edge,
3290+ delta: i64,
3291+ source_frames: &[u32],
3292+ ) {
3293+ for &(l, i) in &members.clips {
3294+ if (l, i) == *dragged {
3295+ continue;
3296+ }
2967 let c = self.lanes[l].clips[i];3297 let c = self.lanes[l].clips[i];
3298+ let at = match edge {
3299+ Edge::Start => c.start,
3300+ Edge::End => c.end(),
3301+ };
3302+ let (lo, hi) = self.clip_room(l, i, edge, source_frames);
3303+ let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3304+ if to == at {
3305+ continue;
3306+ }
2968 let room = match edge {3307 let room = match edge {
2969- // The frames that stay play what they played, so what survives
2970- // is measured from the *end*.
2971 Edge::Start => c.end() - to,3308 Edge::Start => c.end() - to,
2972 Edge::End => to - c.start,3309 Edge::End => to - c.start,
2973 };3310 };
2974- match c.speed.fit(room) {3311+ let Some(keep) = c.speed.fit(room) else {
2975- // Not clamped to the clip's current length: an out-point trim3312+ continue;
2976- // *grows* the range, and the source wall in `hi` is what bounds3313+ };
2977- // that. The in-point's own clamp is at the write below.
2978- Some(keep) => fitted.push(keep),
2979- None => return false,
2980- }
2981- }
2982- self.snapshot();
2983- for (&(l, i), keep) in members.iter().zip(fitted) {
2984 let still = self.is_still(&self.lanes[l].clips[i]);3314 let still = self.is_still(&self.lanes[l].clips[i]);
2985 let c = &mut self.lanes[l].clips[i];3315 let c = &mut self.lanes[l].clips[i];
2986 match edge {3316 match edge {
2987- // A still has no earlier frame to walk an in-point back to --
2988- // every frame of it is the same picture -- so its head grows
2989- // *forward*: the range it plays is however long the new room
2990- // is, anchored at the source's frame 0. Bounded by `lo`, which
2991- // is where the cap in `source_frames` is applied.
2992 Edge::Start if still => {3317 Edge::Start if still => {
2993 c.in_frame = 0;3318 c.in_frame = 0;
2994 c.out_frame = keep;3319 c.out_frame = keep;
2995 c.start = to;3320 c.start = to;
2996 }3321 }
2997 Edge::Start => {3322 Edge::Start => {
2998- // Non-negative by `lo`, which is what keeps the in-point on
2999- // the source.
3000 c.in_frame = c.out_frame - keep.min(c.out_frame);3323 c.in_frame = c.out_frame - keep.min(c.out_frame);
3001 c.start = to;3324 c.start = to;
3002 }3325 }
3003- // Never wider than the room the edge was clamped to: see
3004- // [`Speed::fit`].
3005 Edge::End => c.out_frame = c.in_frame + keep,3326 Edge::End => c.out_frame = c.in_frame + keep,
3006 }3327 }
3007 debug_assert!(sorted_disjoint(&self.lanes[l].clips));3328 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
3008 }3329 }
3009- true3330+ for &(l, i) in &members.subs {
3331+ if (l, i) == *dragged {
3332+ continue;
3333+ }
3334+ let s = self.lanes[l].subs[i];
3335+ let at = match edge {
3336+ Edge::Start => s.start,
3337+ Edge::End => s.end(),
3338+ };
3339+ let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
3340+ let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3341+ if to == at {
3342+ continue;
3343+ }
3344+ write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
3345+ debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
3346+ }
3010 }3347 }
3011 3348
3012 /// How far that edge may travel, `(first, last)` timeline frame inclusive --3349 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
3013 /// the walls [`trim`](Project::trim) clamps to, without moving anything.3350 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
3014 /// What a front-end drawing the box *during* a drag asks, so the live width3351 /// What a front-end drawing the box *during* a drag asks, so the live width
3015 /// is the width the release will commit and an edge stops under the pointer3352 /// is the width the release will commit and an edge stops under the pointer
3016- /// rather than snapping back. `None` for an index that is not there.3353+ /// rather than snapping back. The **clip's own** walls: the rest of its
3354+ /// group follows by the same delta within their own ([`follow_group`]), so
3355+ /// what is drawn for the dragged edge is what its own clip will commit.
3356+ /// `None` for an index that is not there.
3017 pub fn trim_room(3357 pub fn trim_room(
3018 &self,3358 &self,
3019 lane: Lane,3359 lane: Lane,
@@ -3021,71 +3361,80 @@ impl Project {
3021 edge: Edge,3361 edge: Edge,
3022 source_frames: &[u32],3362 source_frames: &[u32],
3023 ) -> Option<(u32, u32)> {3363 ) -> Option<(u32, u32)> {
3024- let (mut lo, mut hi) = (u32::MIN, u32::MAX);3364+ let l = self.index(lane)?;
3025- for (l, i) in self.group_of(lane, idx)? {3365+ (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, source_frames))
3026- let clips = &self.lanes[l].clips;3366+ }
3027- let c = clips[i];3367+
3028- let (member_lo, member_hi) = match edge {3368+ /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
3029- Edge::Start => (3369+ /// its lane's storage index: the one wall computation, asked for the clip
3030- // Back to the source's own first frame -- as many *timeline*3370+ /// itself and for each member a group trim carries.
3031- // frames as that head is worth at the clip's rate, which at3371+ fn clip_room(
3032- // real time is the head itself -- and never over the clip in3372+ &self,
3033- // front of it. Saturating because a clip may hold *more*3373+ l: usize,
3034- // head than the timeline has room for -- a ripple delete3374+ i: usize,
3035- // slides a clip back to frame 0 with its in-point wherever3375+ edge: Edge,
3036- // the cut left it -- and frame 0 is the other wall.3376+ source_frames: &[u32],
3037- //3377+ ) -> (u32, u32) {
3038- // A still is measured from its *tail* instead: it has no3378+ let clips = &self.lanes[l].clips;
3039- // in-point worth the name (every frame the same picture), so3379+ let c = clips[i];
3040- // its head reaches exactly as far as its tail does -- out to3380+ let (lo, hi) = match edge {
3041- // the length the caller's table gives it, whole. Measured3381+ Edge::Start => (
3042- // from the in-point it would have no head room at all, which3382+ // Back to the source's own first frame -- as many *timeline*
3043- // is a placed picture whose left edge cannot be dragged out.3383+ // frames as that head is worth at the clip's rate, which at
3044- // No entry in the table means no growth, as it does at the3384+ // real time is the head itself -- and never over the clip in
3045- // other end.3385+ // front of it. Saturating because a clip may hold *more*
3046- if self.is_still(&c) {3386+ // head than the timeline has room for -- a ripple delete
3047- c.end().saturating_sub(3387+ // slides a clip back to frame 0 with its in-point wherever
3048- c.speed3388+ // the cut left it -- and frame 0 is the other wall.
3049- .room(source_frames.get(c.source).copied().unwrap_or(c.len())),3389+ //
3050- )3390+ // A still is measured from its *tail* instead: it has no
3051- } else {3391+ // in-point worth the name (every frame the same picture), so
3052- c.start.saturating_sub(c.speed.room(c.in_frame))3392+ // its head reaches exactly as far as its tail does -- out to
3053- }3393+ // the length the caller's table gives it, whole. Measured
3054- .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),3394+ // from the in-point it would have no head room at all, which
3055- // One *frame of clip* always survives, and at a rate below3395+ // is a placed picture whose left edge cannot be dragged out.
3056- // real time one frame of clip is several frames of timeline3396+ // No entry in the table means no growth, as it does at the
3057- // ([`Speed::room`]): an edge dragged closer than that would3397+ // other end.
3058- // ask for a range no source frame fits in. At real time this3398+ if self.is_still(&c) {
3059- // is `end - 1`, unchanged.3399+ c.end().saturating_sub(
3060- c.end() - c.speed.room(1),3400+ c.speed
3061- ),3401+ .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
3062- Edge::End => (3402+ )
3063- // ...and the same wall from the other end: the shortest this3403+ } else {
3064- // clip can be is the room one source frame of it takes.3404+ c.start.saturating_sub(c.speed.room(c.in_frame))
3065- c.start + c.speed.room(1),3405+ }
3066- // Out to whatever is left of the source -- again in timeline3406+ .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
3067- // frames, at this clip's rate -- and never over the clip3407+ // One *frame of clip* always survives, and at a rate below
3068- // behind it.3408+ // real time one frame of clip is several frames of timeline
3069- c.start3409+ // ([`Speed::room`]): an edge dragged closer than that would
3070- .saturating_add(3410+ // ask for a range no source frame fits in. At real time this
3071- c.speed.room(3411+ // is `end - 1`, unchanged.
3072- source_frames3412+ c.end() - c.speed.room(1),
3073- .get(c.source)3413+ ),
3074- .copied()3414+ Edge::End => (
3075- .unwrap_or(c.out_frame)3415+ // ...and the same wall from the other end: the shortest this
3076- .saturating_sub(c.in_frame),3416+ // clip can be is the room one source frame of it takes.
3077- ),3417+ c.start + c.speed.room(1),
3078- )3418+ // Out to whatever is left of the source -- again in timeline
3079- .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),3419+ // frames, at this clip's rate -- and never over the clip
3080- ),3420+ // behind it.
3081- };3421+ c.start
3082- lo = lo.max(member_lo);3422+ .saturating_add(
3083- hi = hi.min(member_hi);3423+ c.speed.room(
3084- }3424+ source_frames
3425+ .get(c.source)
3426+ .copied()
3427+ .unwrap_or(c.out_frame)
3428+ .saturating_sub(c.in_frame),
3429+ ),
3430+ )
3431+ .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
3432+ ),
3433+ };
3085 // `hi.max(lo)`: for a clip the invariants hold for, the range always3434 // `hi.max(lo)`: for a clip the invariants hold for, the range always
3086 // contains the edge's own place, and a caller's wrong `source_frames`3435 // contains the edge's own place, and a caller's wrong `source_frames`
3087 // must not become an empty range (or a panicking `clamp`) here.3436 // must not become an empty range (or a panicking `clamp`) here.
3088- Some((lo, hi.max(lo)))3437+ (lo, hi.max(lo))
3089 }3438 }
3090 3439
3091 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose3440 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
@@ -3098,22 +3447,38 @@ impl Project {
3098 .is_some_and(|s| crate::is_image(&s.path))3447 .is_some_and(|s| crate::is_image(&s.path))
3099 }3448 }
3100 3449
3101- /// The clips that move as one with the clip at `idx` of `lane` -- itself and3450+ /// The placements that move as one with the one at `idx` of `lane` --
3102- /// whatever carries its link on the other lanes -- as `(lane storage index,3451+ /// itself and whatever carries its link, on the media lanes and the
3103- /// clip index)` pairs. `None` for an index that is not there.3452+ /// subtitle ones alike. `None` for an index that is not there.
3104- fn group_of(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {3453+ fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
3105- let clip = *self.lane(lane).get(idx)?;3454+ let sub = lane.kind == LaneKind::Subtitle;
3106- Some(match clip.link {3455+ let link = if sub {
3107- Some(link) => self3456+ self.sub_lane(lane).get(idx)?.link
3108- .lanes3457+ } else {
3109- .iter()3458+ self.lane(lane).get(idx)?.link
3110- .enumerate()3459+ };
3111- .filter_map(|(l, data)| {3460+ let mut members = Members::default();
3112- Some((l, data.clips.iter().position(|c| c.link == Some(link))?))3461+ match link {
3113- })3462+ Some(link) => {
3114- .collect(),3463+ for (l, data) in self.lanes.iter().enumerate() {
3115- None => vec![(self.index(lane).expect("the clip was found on it"), idx)],3464+ if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
3116- })3465+ members.clips.push((l, i));
3466+ }
3467+ if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
3468+ members.subs.push((l, i));
3469+ }
3470+ }
3471+ }
3472+ None => {
3473+ let l = self.index(lane).expect("the placement was found on it");
3474+ if sub {
3475+ members.subs.push((l, idx));
3476+ } else {
3477+ members.clips.push((l, idx));
3478+ }
3479+ }
3480+ }
3481+ Some(members)
3117 }3482 }
3118 3483
3119 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one3484 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
@@ -3322,10 +3687,10 @@ impl Project {
3322 }3687 }
3323 }3688 }
3324 3689
3325- /// The law a scoped ripple lives under: **a link is one span on however3690+ /// The law a scoped ripple lives under: **a group travels as one**, so a
3326- /// many lanes**, so a batch that moves one half of a take and not the other3691+ /// batch that moves one half of a take and not the other would leave the
3327- /// would leave a group whose halves disagree -- a project no save could3692+ /// halves disagreeing about where they stand -- an offset no hand asked
3328- /// load ([`links_are_consistent`]).3693+ /// for, and the reason the take's lanes have to be scoped together.
3329 ///3694 ///
3330 /// Refused by name rather than widened silently. Widening would edit a3695 /// Refused by name rather than widened silently. Widening would edit a
3331 /// track the user did not scope, which is exactly the surprise scoping3696 /// track the user did not scope, which is exactly the surprise scoping
@@ -3511,17 +3876,66 @@ impl Project {
3511 self.delete_in(Lane::V1, idx)3876 self.delete_in(Lane::V1, idx)
3512 }3877 }
3513 3878
3514- /// [`delete`](Project::delete) for the lane the clip was picked on: the3879+ /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
3515- /// clip's own span is cut out of *every* lane, so a take deletes whole from3880+ /// in no group (or a group of one, which is the same thing to a delete) is
3516- /// whichever half of it was clicked. `false` for a bad index, and for a lane3881+ /// what it always was: its own span cut out of *every* lane, so the
3517- /// that is not there.3882+ /// timeline closes up under it. A clip in a group takes the group with it,
3883+ /// each member by its **own** span and on its **own** lane -- the members
3884+ /// keep their offsets, so their spans may disagree, and the lanes may end
3885+ /// up out of step with each other, which is inherent to a hand-built group
3886+ /// and one undo away. The caption members lift rather than ripple, for the
3887+ /// reason a caption's own delete always lifted: a subtitle lane never
3888+ /// slides, or the words after the cut would stop matching the ones before
3889+ /// it. One snapshot for the whole group, so one [`Project::undo`] puts it
3890+ /// back. `false` for a bad index, and for a lane that is not there.
3891+ /// Changes the mapping: the caller must reseek.
3518 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {3892 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
3893+ let Some(members) = self.group_of(lane, idx) else {
3894+ return false;
3895+ };
3896+ if !members.alone() {
3897+ return self.delete_members(&members);
3898+ }
3519 let Some(clip) = self.lane(lane).get(idx).copied() else {3899 let Some(clip) = self.lane(lane).get(idx).copied() else {
3520 return false;3900 return false;
3521 };3901 };
3522 self.ripple_delete(clip.start, clip.frames())3902 self.ripple_delete(clip.start, clip.frames())
3523 }3903 }
3524 3904
3905+ /// [`delete_in`](Project::delete_in) for the caption the pick named: a
3906+ /// caption in no group lifts, exactly as its own key always made it
3907+ /// ([`Project::lift_sub`]), and a caption in a group takes the group with
3908+ /// it by [`delete_in`](Project::delete_in)'s rule -- the media members'
3909+ /// spans out of their own lanes, the other captions lifted. `false` for a
3910+ /// bad index.
3911+ pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
3912+ let Some(members) = self.group_of(lane, idx) else {
3913+ return false;
3914+ };
3915+ if !members.alone() {
3916+ return self.delete_members(&members);
3917+ }
3918+ self.lift_sub(lane, idx)
3919+ }
3920+
3921+ /// The one whole-group delete both doors land in: every media member's own
3922+ /// span cut out of its own lane and the hole closed there -- and nothing
3923+ /// else on another lane moves, which is what keeps one member's ripple from
3924+ /// dragging another member's lane out from under it -- and every caption
3925+ /// member lifted. One snapshot, one undo step.
3926+ fn delete_members(&mut self, members: &Members) -> bool {
3927+ self.snapshot();
3928+ for &(l, i) in &members.clips {
3929+ let c = self.lanes[l].clips[i];
3930+ ripple(&mut self.lanes, &[l], c.start, c.frames());
3931+ }
3932+ for &(l, i) in members.subs.iter().rev() {
3933+ self.lanes[l].subs.remove(i);
3934+ }
3935+ debug_assert!(links_are_consistent(&self.lanes).is_ok());
3936+ true
3937+ }
3938+
3525 /// Restore every lane from before the last successful edit -- the clips and3939 /// Restore every lane from before the last successful edit -- the clips and
3526 /// the lane list both. `false` when there is nothing left to undo.3940 /// the lane list both. `false` when there is nothing left to undo.
3527 pub fn undo(&mut self) -> bool {3941 pub fn undo(&mut self) -> bool {
@@ -3732,31 +4146,6 @@ impl Project {
3732 id4146 id
3733 }4147 }
3734 4148
3735- /// One fresh group id per *distinct* key, in lane order, and `None` where a
3736- /// lane has no key -- how [`split`](Project::split) and
3737- /// [`regroup`](Project::regroup) hand out ids across however many lanes.
3738- /// Lanes sharing a key end up sharing an id, which is exactly the rule
3739- /// [`links_are_consistent`] enforces: one id, one span.
3740- fn group_ids<K: PartialEq>(&mut self, keys: &[Option<K>]) -> Vec<Option<u32>> {
3741- // Linear, over a handful of lanes: a hash of a lane list would cost
3742- // more than it saves and would not be deterministic for free.
3743- let mut seen: Vec<(&K, u32)> = Vec::new();
3744- let mut out = Vec::with_capacity(keys.len());
3745- for key in keys {
3746- out.push(
3747- key.as_ref()
3748- .map(|k| match seen.iter().find(|(other, _)| *other == k) {
3749- Some(&(_, id)) => id,
3750- None => {
3751- let id = self.new_link();
3752- seen.push((k, id));
3753- id
3754- }
3755- }),
3756- );
3757- }
3758- out
3759- }
3760 }4149 }
3761 4150
3762 /// The handle of every lane, in storage order -- the one definition of what4151 /// The handle of every lane, in storage order -- the one definition of what
@@ -3898,6 +4287,10 @@ fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
3898 out.push(SubClip {4287 out.push(SubClip {
3899 frames: start - s.start,4288 frames: start - s.start,
3900 out_us: s.window_at(start),4289 out_us: s.window_at(start),
4290+ // Both pieces lose the group id, for [`clear`]'s reason: one
4291+ // id on two boxes of one lane is the one thing it may never
4292+ // mean.
4293+ link: None,
3901 ..s4294 ..s
3902 });4295 });
3903 }4296 }
@@ -3906,6 +4299,7 @@ fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
3906 start: end,4299 start: end,
3907 frames: s.end() - end,4300 frames: s.end() - end,
3908 in_us: s.window_at(end),4301 in_us: s.window_at(end),
4302+ link: None,
3909 ..s4303 ..s
3910 });4304 });
3911 }4305 }
@@ -3924,6 +4318,7 @@ fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
3924 subs[idx] = SubClip {4318 subs[idx] = SubClip {
3925 frames: at - s.start,4319 frames: at - s.start,
3926 out_us: cut,4320 out_us: cut,
4321+ link: None,
3927 ..s4322 ..s
3928 };4323 };
3929 subs.insert(4324 subs.insert(
@@ -3932,6 +4327,7 @@ fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
3932 start: at,4327 start: at,
3933 frames: s.end() - at,4328 frames: s.end() - at,
3934 in_us: cut,4329 in_us: cut,
4330+ link: None,
3935 ..s4331 ..s
3936 },4332 },
3937 );4333 );
@@ -3952,15 +4348,56 @@ fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
3952 .then_some(idx)4348 .then_some(idx)
3953 }4349 }
3954 4350
4351+/// How far one `edge` of the caption at `idx` may travel against its own lane's
4352+/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
4353+/// rate, which a caption *following* a group's trim does not have to be exact
4354+/// about -- its own walls, its own one surviving frame, and nothing that needs
4355+/// a clock.
4356+fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
4357+ let s = &subs[idx];
4358+ match edge {
4359+ Edge::Start => (
4360+ idx.checked_sub(1).map_or(0, |p| subs[p].end()),
4361+ s.end() - 1,
4362+ ),
4363+ Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
4364+ }
4365+}
4366+
4367+/// Move one `edge` of `s` to timeline frame `to`, its window following by the
4368+/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
4369+/// forwards and backwards. The caption a group's trim is carrying has no rate
4370+/// of its own and needs none: what one frame of it is worth in microseconds is
4371+/// the window it already shows over the frames it already takes.
4372+fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
4373+ let per_frame = s.window_us() / i64::from(s.frames.max(1));
4374+ let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
4375+ match edge {
4376+ Edge::Start => {
4377+ s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1);
4378+ s.frames = s.end() - to;
4379+ s.start = to;
4380+ }
4381+ Edge::End => {
4382+ s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1);
4383+ s.frames = to - s.start;
4384+ }
4385+ }
4386+ debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
4387+}
4388+
3955 /// The grouping invariant, checked in release at [`Project::from_parts`] and4389 /// The grouping invariant, checked in release at [`Project::from_parts`] and
3956-/// asserted by the tests after every edit: a link id names **at most one** clip4390+/// asserted by the tests after every edit: a link id names **at most one**
3957-/// per lane, and every clip carrying it covers the same timeline span -- that is4391+/// placement per lane -- a clip on a media lane or a caption on a subtitle
3958-/// all "these move together" can mean.4392+/// one, whichever carries it. That is all "these move together" can mean now
4393+/// that a group is assembled by hand: the members keep their own spans and
4394+/// their own offsets, and what binds them is the id alone.
3959 ///4395 ///
3960-/// Deliberately *not* a pairing of two lanes: with N lanes a take may run on4396+/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
3961-/// `V1`, `V2` and `A1` at once, and the rule that makes an id meaningful is span4397+/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
3962-/// identity, not which lane (or which `ord`) the partner sits on. Two lanes are4398+/// placements of one group may cover different frames -- the offset-preserving
3963-/// the case where it reads as "the picture and its sound".4399+/// group a hand builds with [`Project::group_all`], which a drag moves by one
4400+/// delta rather than by one span.
3964 ///4401 ///
3965 /// A link no other lane carries is legal and is not an error: lifting one half4402 /// A link no other lane carries is legal and is not an error: lifting one half
3966 /// of a group ([`Project::lift`]) leaves exactly that, and a save of that4403 /// of a group ([`Project::lift`]) leaves exactly that, and a save of that
@@ -3976,26 +4413,17 @@ fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
3976 );4413 );
3977 }4414 }
3978 }4415 }
3979- }4416+ // ...and the same for the captions, in their own list on the same lane:
3980- // First lane to carry an id fixes the span every other lane must agree on.4417+ // a subtitle lane holds no `Clip`, so this is the only list a caption's
3981- let mut seen: Vec<(u32, Lane, u32, u32)> = Vec::new();4418+ // id could be doubled on.
3982- for (data, &lane) in lanes.iter().zip(&handles) {4419+ for (i, s) in data.subs.iter().enumerate() {
3983- for c in &data.clips {4420+ let Some(id) = s.link else { continue };
3984- let Some(id) = c.link else { continue };4421+ if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
3985- match seen.iter().find(|(other, ..)| *other == id) {4422+ return Err(format!(
3986- Some(&(_, first, start, end)) => {4423+ "link {id} names two captions in the {} lane",
3987- if (start, end) != (c.start, c.end()) {4424+ lane.label()
3988- return Err(format!(4425+ )
3989- "link {id} covers [{start}, {end}) in {} and [{}, {}) in {}",4426+ .into());
3990- first.label(),
3991- c.start,
3992- c.end(),
3993- lane.label()
3994- )
3995- .into());
3996- }
3997- }
3998- None => seen.push((id, lane, c.start, c.end())),
3999 }4427 }
4000 }4428 }
4001 }4429 }
@@ -4374,6 +4802,258 @@ mod tests {
4374 assert_eq!(shape(&p), before);4802 assert_eq!(shape(&p), before);
4375 }4803 }
4376 4804
4805+ /// The caption a hand groups: `group_all` over clips *and* a caption, the
4806+ /// mates riding along, the offsets kept, the refusals in words.
4807+ #[test]
4808+ fn a_hand_built_group_holds_clips_and_a_caption() {
4809+ let caption = |start: u32, frames: u32| SubClip {
4810+ start,
4811+ frames,
4812+ track: 0,
4813+ in_us: 0,
4814+ out_us: i64::from(frames) * 1_000_000,
4815+ link: None,
4816+ };
4817+ let track = || SubtitleTrack {
4818+ path: FILE.into(),
4819+ track: None,
4820+ language: "eng".into(),
4821+ name: String::new(),
4822+ label: "eng".into(),
4823+ cues: Vec::new(),
4824+ bitmap: false,
4825+ refused: None,
4826+ };
4827+ let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
4828+ let v2 = p.add_lane(LaneKind::Video);
4829+ let s1 = p.add_lane(LaneKind::Subtitle);
4830+ // A layer at its own offset, and a caption over the head of the take.
4831+ assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
4832+ p.place_sub(s1, 0, caption(0, 6)).expect("placed");
4833+
4834+ // Too few, one lane twice, and an index that is not there: words, no
4835+ // snapshot.
4836+ let history = p.history.len();
4837+ assert!(p.group_all(&[]).unwrap_err().to_string().contains("two placements or more"));
4838+ assert!(p
4839+ .group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
4840+ .unwrap_err()
4841+ .to_string()
4842+ .contains("V1 is picked twice"));
4843+ assert!(p
4844+ .group_all(&[(Lane::V1, 0), (s1, 9)])
4845+ .unwrap_err()
4846+ .to_string()
4847+ .contains("no subtitle 9"));
4848+ assert_eq!(p.history.len(), history, "refusals cost no undo step");
4849+
4850+ // The group: the picture, the layer, and the caption -- and the sound
4851+ // the picture was already grouped with comes along unasked.
4852+ p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
4853+ .expect("three picks, three lanes");
4854+ let id = p.lane(Lane::V1)[0].link.expect("grouped");
4855+ for lane in [Lane::V1, Lane::A1, v2] {
4856+ assert_eq!(p.lane(lane)[0].link, Some(id), "{} rides along", lane.label());
4857+ }
4858+ assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
4859+ assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
4860+ assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
4861+ assert!(links_are_consistent(&p.lanes).is_ok());
4862+ assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
4863+
4864+ // ...and one undo takes it apart again.
4865+ assert!(p.undo());
4866+ assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
4867+
4868+ // Detach names a caption like it names a clip: every member an id of
4869+ // its own, which is never `None` (see `ungroup`).
4870+ p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
4871+ assert!(p.ungroup(s1, 0));
4872+ let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
4873+ assert!(loose_sub.is_some() && loose_clip.is_some());
4874+ assert_ne!(loose_sub, loose_clip);
4875+ assert!(links_are_consistent(&p.lanes).is_ok());
4876+ }
4877+
4878+ /// A split hands the caption of a group the same ids it hands the clips:
4879+ /// the left halves keep the group, the right halves share a fresh one.
4880+ #[test]
4881+ fn a_split_cuts_a_grouped_caption_with_its_clips() {
4882+ let caption = |start: u32, frames: u32| SubClip {
4883+ start,
4884+ frames,
4885+ track: 0,
4886+ in_us: 0,
4887+ out_us: i64::from(frames) * 1_000_000,
4888+ link: None,
4889+ };
4890+ let track = || SubtitleTrack {
4891+ path: FILE.into(),
4892+ track: None,
4893+ language: "eng".into(),
4894+ name: String::new(),
4895+ label: "eng".into(),
4896+ cues: Vec::new(),
4897+ bitmap: false,
4898+ refused: None,
4899+ };
4900+ let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
4901+ let s1 = p.add_lane(LaneKind::Subtitle);
4902+ p.place_sub(s1, 0, caption(0, 9)).expect("placed");
4903+ p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
4904+ let take = p.lane(Lane::V1)[0].link.expect("the group id");
4905+
4906+ assert!(p.split(4));
4907+ let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
4908+ assert_eq!(left.link, Some(take), "the caption's head keeps the group");
4909+ assert_eq!(left.frames, 4);
4910+ assert_eq!(
4911+ right.link,
4912+ p.lane(Lane::V1)[1].link,
4913+ "the caption's tail shares the clips' fresh id"
4914+ );
4915+ assert_ne!(right.link, Some(take));
4916+ assert!(links_are_consistent(&p.lanes).is_ok());
4917+
4918+ // Regroup at the seam restores the take, caption included.
4919+ assert!(p.regroup(4));
4920+ assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
4921+ assert_eq!(p.sub_lane(s1)[0].link, Some(take));
4922+ }
4923+
4924+ /// Deleting a member of a hand-built group takes the group: each media
4925+ /// member's own span out of its own lane, the captions lifted -- the lanes
4926+ /// may end up out of step, which is what one undo restores together.
4927+ #[test]
4928+ fn deleting_a_grouped_clip_ripples_each_lane_alone_and_lifts_the_captions() {
4929+ let caption = |start: u32, frames: u32| SubClip {
4930+ start,
4931+ frames,
4932+ track: 0,
4933+ in_us: 0,
4934+ out_us: i64::from(frames) * 1_000_000,
4935+ link: None,
4936+ };
4937+ let track = || SubtitleTrack {
4938+ path: FILE.into(),
4939+ track: None,
4940+ language: "eng".into(),
4941+ name: String::new(),
4942+ label: "eng".into(),
4943+ cues: Vec::new(),
4944+ bitmap: false,
4945+ refused: None,
4946+ };
4947+ let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
4948+ let s1 = p.add_lane(LaneKind::Subtitle);
4949+ p.place_sub(s1, 2, caption(2, 4)).expect("placed");
4950+ p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
4951+ // A neighbour on a lane the group does not touch.
4952+ let v2 = p.add_lane(LaneKind::Video);
4953+ assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
4954+
4955+ // By the picture or by the caption, the same whole-group delete.
4956+ assert!(p.delete_sub_in(s1, 0));
4957+ assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
4958+ assert!(p.sub_lane(s1).is_empty(), "the caption lifted");
4959+ assert_eq!(p.lane(v2)[0].start, 10, "a lane the group does not touch stays");
4960+ assert!(links_are_consistent(&p.lanes).is_ok());
4961+ assert!(p.undo(), "one step puts the group back");
4962+ assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
4963+ }
4964+
4965+ /// Dragging a grouped caption carries its clips, one delta for all of them
4966+ /// -- and a caption in no group refuses an overlap exactly as it always did.
4967+ #[test]
4968+ fn dragging_a_grouped_caption_carries_its_group() {
4969+ let caption = |start: u32, frames: u32| SubClip {
4970+ start,
4971+ frames,
4972+ track: 0,
4973+ in_us: 0,
4974+ out_us: i64::from(frames) * 1_000_000,
4975+ link: None,
4976+ };
4977+ let track = || SubtitleTrack {
4978+ path: FILE.into(),
4979+ track: None,
4980+ language: "eng".into(),
4981+ name: String::new(),
4982+ label: "eng".into(),
4983+ cues: Vec::new(),
4984+ bitmap: false,
4985+ refused: None,
4986+ };
4987+ let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
4988+ let s1 = p.add_lane(LaneKind::Subtitle);
4989+ p.place_sub(s1, 2, caption(2, 4)).expect("placed");
4990+ p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
4991+
4992+ // Same lane, further along: everyone moves by the same eight frames.
4993+ p.move_sub(s1, 0, s1, 10).expect("room for all of it");
4994+ assert_eq!(p.sub_lane(s1)[0].start, 10);
4995+ assert_eq!(p.lane(Lane::V1)[0].start, 8, "the clip follows by the delta");
4996+ assert!(links_are_consistent(&p.lanes).is_ok());
4997+
4998+ // ...and an ungrouped caption is the caption it always was.
4999+ assert!(p.ungroup(s1, 0));
5000+ let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
5001+ let s1 = q.add_lane(LaneKind::Subtitle);
5002+ q.place_sub(s1, 0, caption(0, 4)).expect("placed");
5003+ q.place_sub(s1, 5, caption(5, 4)).expect("placed");
5004+ assert!(q
5005+ .move_sub(s1, 0, s1, 3)
5006+ .unwrap_err()
5007+ .to_string()
5008+ .contains("already covers"));
5009+ }
5010+
5011+ /// A trim carries a group's caption by the same delta as its clips, clamped
5012+ /// to the caption's own walls -- the offsets between the members survive.
5013+ #[test]
5014+ fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
5015+ let caption = |start: u32, frames: u32| SubClip {
5016+ start,
5017+ frames,
5018+ track: 0,
5019+ in_us: 0,
5020+ out_us: i64::from(frames) * 1_000_000,
5021+ link: None,
5022+ };
5023+ let track = || SubtitleTrack {
5024+ path: FILE.into(),
5025+ track: None,
5026+ language: "eng".into(),
5027+ name: String::new(),
5028+ label: "eng".into(),
5029+ cues: Vec::new(),
5030+ bitmap: false,
5031+ refused: None,
5032+ };
5033+ let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
5034+ let s1 = p.add_lane(LaneKind::Subtitle);
5035+ // The caption sits two frames into the take and ends one early. The
5036+ // source runs past the clip, or there is no tail to pull out.
5037+ let src = &[20];
5038+ p.place_sub(s1, 2, caption(2, 6)).expect("placed");
5039+ p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5040+
5041+ // The tail goes out by three: the clip to 12, the caption to 11.
5042+ assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
5043+ assert_eq!(p.lane(Lane::V1)[0].end(), 12);
5044+ assert_eq!(
5045+ (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
5046+ (2, 11),
5047+ "the caption follows by the delta"
5048+ );
5049+ assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
5050+
5051+ // The head comes in by two: everyone's start moves two along.
5052+ assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
5053+ assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
5054+ assert!(links_are_consistent(&p.lanes).is_ok());
5055+ }
5056+
4377 #[test]5057 #[test]
4378 fn split_refused_at_zero_boundary_end_and_in_a_gap() {5058 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
4379 let mut p = three();5059 let mut p = three();
@@ -5944,13 +6624,15 @@ mod tests {
5944 }6624 }
5945 6625
5946 /// The grouping rules, at the untrusted door and after every edit that can6626 /// The grouping rules, at the untrusted door and after every edit that can
5947- /// touch a link. A link id is at most one clip per lane and, wherever it is6627+ /// touch a link. A link id is at most one placement per lane -- a clip or a
5948- /// carried, one span -- and no sequence of edits may produce otherwise,6628+ /// caption, whichever carries it -- and no sequence of edits may produce
5949- /// because what an edit produces is what a save writes and a load reads.6629+ /// otherwise, because what an edit produces is what a save writes and a load
6630+ /// reads.
5950 ///6631 ///
5951- /// Amended for the lane model: the two errors name their lane `V1`/`A1`6632+ /// Amended for the offset-preserving group: the members keep their own
5952- /// rather than "video"/"audio", because with N lanes "the video lane" is no6633+ /// spans, so two placements of one id covering different frames is *legal*
5953- /// longer a lane. Same causes, same door, same claim.6634+ /// -- it is what a hand-built group is -- and the only refusal left is the
6635+ /// doubled id inside one lane.
5954 #[test]6636 #[test]
5955 fn a_link_id_is_never_two_clips_of_one_lane() {6637 fn a_link_id_is_never_two_clips_of_one_lane() {
5956 let sources = vec![Source::new(FILE, 0)];6638 let sources = vec![Source::new(FILE, 0)];
@@ -5966,7 +6648,7 @@ mod tests {
5966 speed: Speed::NORMAL,6648 speed: Speed::NORMAL,
5967 };6649 };
5968 6650
5969- // The door: named errors, one per cause.6651+ // The door: a doubled id inside one lane, refused by name.
5970 let err = |video: Vec<Clip>, audio: Vec<Clip>| {6652 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
5971 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new())6653 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new())
5972 .expect_err("refused")6654 .expect_err("refused")
@@ -5977,11 +6659,34 @@ mod tests {
5977 .contains("link 7 names two clips in the V1 lane"),6659 .contains("link 7 names two clips in the V1 lane"),
5978 "a duplicate id inside one lane is refused by name"6660 "a duplicate id inside one lane is refused by name"
5979 );6661 );
5980- assert!(6662+ // ...and the same doubling on a subtitle lane, in its own words: a
5981- err(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)])6663+ // caption is the other placement an id may name.
5982- .contains("link 2 covers [0, 5) in V1 and [0, 3) in A1"),6664+ let caption = |start: u32, frames: u32, link| SubClip {
5983- "a pair that does not cover one span is refused by name"6665+ start,
6666+ frames,
6667+ track: 0,
6668+ in_us: 0,
6669+ out_us: i64::from(frames) * 1_000_000,
6670+ link: Some(link),
6671+ };
6672+ let subs = LaneData {
6673+ clips: Vec::new(),
6674+ subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
6675+ ..LaneData::new(LaneKind::Subtitle, Vec::new())
6676+ };
6677+ assert_eq!(
6678+ links_are_consistent(&[subs]).unwrap_err().to_string(),
6679+ "link 7 names two captions in the S1 lane"
6680+ );
6681+ // A pair covering *different* frames is legal now: the members of a
6682+ // hand-built group keep their own spans, and what binds them is the id.
6683+ let apart = Project::from_parts(
6684+ sources.clone(),
6685+ two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
6686+ Vec::new(),
6687+ Vec::new(),
5984 );6688 );
6689+ assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
5985 // A one-sided link is *not* an error: it is what a lift leaves behind.6690 // A one-sided link is *not* an error: it is what a lift leaves behind.
5986 let mut p = Project::single(FILE, 9);6691 let mut p = Project::single(FILE, 9);
5987 assert!(p.lift(Lane::A1, 0));6692 assert!(p.lift(Lane::A1, 0));
@@ -6646,81 +7351,65 @@ mod tests {
6646 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);7351 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
6647 }7352 }
6648 7353
6649- /// The grouping rule across more than two lanes: a link id is one *span*,7354+ /// The grouping rule across more than two lanes, under the offset model: a
6650- /// on however many lanes carry it -- not a video/audio pair and not a7355+ /// split *keeps* the group on the left halves and hands the right halves of
6651- /// pairing by `ord`. So a split shares an id with every lane whose half7356+ /// that group one fresh id of their own -- a clip in no group comes out of
6652- /// lines up, and gives its own to every lane whose half does not.7357+ /// the cut in none. So a take cut apart is two takes, one per side, and a
7358+ /// lane that was never part of it stays out of both.
6653 #[test]7359 #[test]
6654- fn a_group_id_is_one_span_across_every_lane() {7360+ fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
6655 let mut p = Project::single(FILE, 9);7361 let mut p = Project::single(FILE, 9);
7362+ let take = p.clips()[0].link.expect("a fresh project is one take");
6656 let v2 = p.add_lane(LaneKind::Video);7363 let v2 = p.add_lane(LaneKind::Video);
6657- assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "three lanes, one span");7364+ assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "a placement joins no group");
6658 assert!(p.split(4));7365 assert!(p.split(4));
6659 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {7366 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
6660 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()7367 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
6661 };7368 };
6662 let (left, right) = (side(&p, 0), side(&p, 1));7369 let (left, right) = (side(&p, 0), side(&p, 1));
6663- assert!(7370+ // The lanes in order are V1, A1, V2: the take's two keep its id on the
6664- left[0].is_some() && left.iter().all(|id| *id == left[0]),7371+ // left, and the placed clip never had one for the cut to keep.
6665- "one id for three left halves: {left:?}"7372+ assert_eq!(
7373+ left,
7374+ vec![Some(take), Some(take), None],
7375+ "the left halves keep the take"
6666 );7376 );
6667- assert!(right.iter().all(|id| *id == right[0]), "{right:?}");7377+ // ...and the right halves of that take are one fresh group.
6668- assert_ne!(left[0], right[0], "the halves are no longer one take");7378+ assert_eq!(right[0], right[1]);
7379+ assert_ne!(right[0], Some(take));
7380+ assert_eq!(right[2], None, "an unlinked lane stays unlinked");
6669 invariants_hold(&p, "split across three lanes");7381 invariants_hold(&p, "split across three lanes");
6670 7382
6671- // V2 ends early: same start, so the left halves are one take; different7383+ // V2 ends early: the left halves still keep what each clip carried --
6672- // end, so the right halves cannot be.7384+ // the take on V1 and A1, nothing on V2 -- and the fresh right id is
7385+ // shared by exactly the take's lanes.
6673 let mut p = Project::single(FILE, 9);7386 let mut p = Project::single(FILE, 9);
6674 let v2 = p.add_lane(LaneKind::Video);7387 let v2 = p.add_lane(LaneKind::Video);
6675 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));7388 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
6676 assert!(p.split(3));7389 assert!(p.split(3));
6677- assert_eq!(p.lane(Lane::V1)[0].link, p.lane(v2)[0].link, "same [0, 3)");7390+ assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
6678- assert_ne!(7391+ assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
6679- p.lane(Lane::V1)[1].link,
6680- p.lane(v2)[1].link,
6681- "[3,9) vs [3,6)"
6682- );
6683 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);7392 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
7393+ assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
6684 invariants_hold(&p, "split where one lane ends early");7394 invariants_hold(&p, "split where one lane ends early");
6685 7395
6686- // The inverse rejoins all three, and groups them the same way.7396+ // The inverse rejoins each lane into the group its left half kept.
6687 assert!(p.regroup(3));7397 assert!(p.regroup(3));
6688 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);7398 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
6689- assert_ne!(7399+ assert_eq!(
6690 p.lane(Lane::V1)[0].link,7400 p.lane(Lane::V1)[0].link,
6691- p.lane(v2)[0].link,7401+ Some(take),
6692- "V2 rejoins into a span of its own"7402+ "the take's id is back, not a fresh one"
6693 );7403 );
7404+ assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
6694 invariants_hold(&p, "regroup across three lanes");7405 invariants_hold(&p, "regroup across three lanes");
6695-
6696- // ...and the rule is enforced, not merely produced: two video lanes
6697- // carrying one id over two spans is refused, by lane name.
6698- let linked = |out_frame, link| Clip {
6699- start: 0,
6700- in_frame: 0,
6701- out_frame,
6702- source: 0,
6703- link: Some(link),
6704- eq: None,
6705- color: None,
6706- fit: FitPolicy::default(),
6707- speed: Speed::NORMAL,
6708- };
6709- let lanes = vec![
6710- LaneData::new(LaneKind::Video, vec![linked(3, 4)]),
6711- LaneData::new(LaneKind::Video, vec![linked(5, 4)]),
6712- ];
6713- assert_eq!(
6714- links_are_consistent(&lanes).unwrap_err().to_string(),
6715- "link 4 covers [0, 3) in V1 and [0, 5) in V2"
6716- );
6717 }7406 }
6718 7407
6719- /// A group is a set of clips over one span, at most one per lane: a picture7408+ /// A group is one placement per lane, on however many lanes carry the id --
6720- /// may be grouped with sound in *any* audio lane -- there is no paired ord,7409+ /// not a video/audio pair and not a pairing by `ord` -- and the members may
6721- /// and the lanes in between may be empty -- and the two ways to break that7410+ /// cover whatever frames they cover: the offset between them is what a
6722- /// name the lane they broke it on. Lanes built by hand, because the rule is7411+ /// hand-built group keeps. Lanes built by hand, because the rule is checked
6723- /// checked at the untrusted door and no edit can produce these.7412+ /// at the untrusted door and no edit can produce the one thing it refuses.
6724 #[test]7413 #[test]
6725 fn a_group_may_span_any_lane() {7414 fn a_group_may_span_any_lane() {
6726 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);7415 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
@@ -6751,13 +7440,14 @@ mod tests {
6751 // way a lifted half is legal.7440 // way a lifted half is legal.
6752 let across = build([take(), Vec::new(), Vec::new(), take()]);7441 let across = build([take(), Vec::new(), Vec::new(), take()]);
6753 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");7442 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
6754- // Disagreeing about the span is not, and the message names both lanes.7443+ // ...and so is a group whose members disagree about their spans: the
6755- let apart = build([take(), Vec::new(), Vec::new(), vec![one(0, 6, 7)]]);7444+ // offset between them is the hand's business, not the loader's.
6756- assert_eq!(7445+ let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
6757- links_are_consistent(&apart).unwrap_err().to_string(),7446+ assert!(
6758- "link 7 covers [0, 4) in V1 and [0, 6) in A2"7447+ links_are_consistent(&apart).is_ok(),
7448+ "[0, 4) on V1 and [2, 6) on A2 are one group"
6759 );7449 );
6760- // ...and one id twice in one lane is still that lane's error, by name.7450+ // One id twice in one lane is still that lane's error, by name.
6761 let twice = build([7451 let twice = build([
6762 Vec::new(),7452 Vec::new(),
6763 Vec::new(),7453 Vec::new(),