From 95fb78d690eccf802f5eb8e7a3ec9dc2783935f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 12 Aug 2026 00:57:00 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20perf(subtitle):=20a=20project=20nam?= =?UTF-8?q?ing=20many=20tracks=20of=20one=20file=20walks=20it=20once?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A saved subtitle row was read by walking its whole Matroska file and keeping one track of it, so a film whose project names thirty-five of them was thirty-five walks of a 25 GB file -- 7.5 s with the window stopped, since a project opens on the UI thread. open_all reads every saved row at once: one walk per distinct file, every row picked out of it, and the rows handed back in the order they were saved in -- a subtitle is picked by its place in that list, so a reordering would silently repoint what the user had picked. open now delegates to it, which keeps the refusal wording in one place. --- crates/engine/src/playback.rs | 14 ++--- crates/engine/src/subtitle.rs | 67 ++++++++++++++++++------ crates/engine/tests/subtitles.rs | 89 ++++++++++++++++++++++++++++++++ 3 files changed, 146 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index c48221c..4c4f3cc 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -782,13 +782,13 @@ impl PlaybackSession { // The subtitle files are read here rather than in the parser: a // `.edith` names them and holds no cues. One that has gone missing, or // whose track is a codec of pictures, comes back listed and refused by - // name ([`crate::subtitle::open`]) -- a project does not stop opening - // over a subtitle, and a re-save does not lose the row. - let subtitles = doc - .subtitles - .iter() - .map(|(path, track)| crate::subtitle::open(path, *track)) - .collect(); + // name ([`crate::subtitle::open_all`]) -- a project does not stop + // opening over a subtitle, and a re-save does not lose the row. + // + // All of them in one call, in saved order, because a file is walked + // whole to reach one track: a film whose project names many of its + // tracks is one walk here rather than one per row. + let subtitles = crate::subtitle::open_all(&doc.subtitles); let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)? .with_mix(&doc.gains, doc.limiter) .with_tone(doc.tone) diff --git a/crates/engine/src/subtitle.rs b/crates/engine/src/subtitle.rs index f57ea82..d5fedce 100644 --- a/crates/engine/src/subtitle.rs +++ b/crates/engine/src/subtitle.rs @@ -26,6 +26,7 @@ //! here reads, and a file carrying one opens with a row that says so instead of //! opening with an empty list. +use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -201,23 +202,55 @@ impl SubtitleTrack { /// because a project that opened yesterday has to open today -- a subtitle is /// not what a whole timeline should refuse over. pub fn open(path: &Path, track: Option) -> SubtitleTrack { - let Some(number) = track else { - return external(path); - }; - let label = format!("track {number}"); - let mut tracks = match of_matroska(path) { - Ok(tracks) => tracks, - Err(why) => return SubtitleTrack::refused(path, track, label, why.to_string()), - }; - match tracks.iter().position(|t| t.track == Some(number)) { - Some(i) => tracks.swap_remove(i), - None => SubtitleTrack::refused( - path, - track, - label, - format!("no subtitle track {number} in {} any more", path.display()), - ), - } + let mut one = open_all(std::slice::from_ref(&(path.to_path_buf(), track))); + one.remove(0) +} + +/// Every saved subtitle line of a project at once, back in the order they were +/// saved in -- which is the order they are picked by, so it is the row order +/// this hands back whatever it had to read. +/// +/// The reason this exists beside [`open`]: a Matroska file is walked whole to +/// reach *one* of its tracks, and a film whose project names thirty-five of them +/// was thirty-five walks of a 25 GB file -- seven seconds with the window +/// stopped, since a project opens on the UI thread. Each distinct file is walked +/// once here and every row that named it is picked out of that one walk. +pub fn open_all(rows: &[(PathBuf, Option)]) -> Vec { + // Keyed by path, so a second row naming the same file finds the walk rather + // than doing it again. The whole walk is kept until the last row is served: + // it is the tracks nobody asked for that are dropped at the end. + // + // ponytail: a track is *moved* out of its walk, so two rows naming the same + // file and the same track leave the second refused by name rather than + // holding the cues twice. No project edith saves has one -- a row is added + // by (file, track) and only once ([`crate::Project::add_subtitles`]) -- and + // a hand-written `.edith` with a doubled row still opens, with that row + // saying so. Clone the picked track instead if that ever has to hold. + let mut walked: HashMap<&Path, crate::Result>> = HashMap::new(); + rows.iter() + .map(|(path, track)| { + let Some(number) = *track else { + return external(path); + }; + let label = format!("track {number}"); + let tracks = walked + .entry(path.as_path()) + .or_insert_with(|| of_matroska(path)); + let tracks = match tracks { + Ok(tracks) => tracks, + Err(why) => return SubtitleTrack::refused(path, *track, label, why.to_string()), + }; + match tracks.iter().position(|t| t.track == Some(number)) { + Some(i) => tracks.swap_remove(i), + None => SubtitleTrack::refused( + path, + *track, + label, + format!("no subtitle track {number} in {} any more", path.display()), + ), + } + }) + .collect() } /// A standalone subtitle file, parsed by its extension. diff --git a/crates/engine/tests/subtitles.rs b/crates/engine/tests/subtitles.rs index b58c01f..59163a3 100644 --- a/crates/engine/tests/subtitles.rs +++ b/crates/engine/tests/subtitles.rs @@ -338,6 +338,95 @@ fn a_project_keeps_a_bitmap_track_as_a_reference_and_reads_its_pictures_back() { let image = track.cues[0].image.as_ref().expect("the picture is back"); assert_eq!((image.width, image.height), (8, 4)); assert_eq!(image.rgba().expect("it decodes").len(), 8 * 4 * 4); + + // Each row is the track it was saved as, in the order it was saved in: what + // a click picks is a place in this list, so a load that reordered the rows + // would repoint the picked track without saying anything. A re-save writing + // the same bytes is that order proved from both ends. + assert_eq!( + back.subtitles().iter().map(|t| t.track).collect::>(), + vec![Some(1), Some(2), Some(3), Some(4)] + ); + let again = dir.join("cut2.edith"); + back.save_project(&again).expect("save again"); + assert_eq!( + std::fs::read(&again).expect("read"), + std::fs::read(&project).expect("read"), + "a save, a load and a save again are the same file" + ); +} + +/// Bytes this process has asked the kernel for so far, which is what a walk of +/// a Matroska file costs and a page cache cannot hide: `rchar` counts what +/// `read` handed back, warm or cold. +fn read_bytes() -> u64 { + let io = std::fs::read_to_string("/proc/self/io").expect("Linux, like the rest of this suite"); + io.lines() + .find_map(|l| l.strip_prefix("rchar: ")) + .expect("rchar") + .trim() + .parse() + .expect("a number") +} + +/// A project naming four tracks of one file walks that file *once*, and hands +/// the rows back in the order they were saved in. +/// +/// The order is the invariant with teeth: a subtitle is picked by its place in +/// this list, so a reader that grouped the rows by file and handed them back +/// grouped would silently repoint what the user had picked. And the walk count +/// is the reason the grouping exists at all -- a saved film with thirty-five +/// tracks was thirty-five walks of a 25 GB file with the window stopped. +#[test] +fn a_project_naming_many_tracks_of_one_file_walks_it_once_and_keeps_its_order() { + let dir = scratch("one_walk"); + let media = dir.join("test_av.mp4"); + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); + let remux = dir.join("remux.mkv"); + std::fs::write(&remux, pgs_matroska(pgs_display_set())).expect("write the hand-made mkv"); + let subs = dir.join("test_subs.srt"); + std::fs::copy(data("test_subs.srt"), &subs).expect("copy the subtitle fixture"); + + // One walk, for the measurement below to be compared against. + let before = read_bytes(); + let all = subtitle::of_matroska(&remux).expect("the walk"); + let one_walk = read_bytes() - before; + assert_eq!(all.len(), 4); + assert!(one_walk > 0, "a walk reads something"); + + // The rows a `.edith` holds, deliberately out of file order and with the + // standalone file in the middle of them. + let rows: Vec<(PathBuf, Option)> = vec![ + (remux.clone(), Some(3)), + (remux.clone(), Some(1)), + (subs.clone(), None), + (remux.clone(), Some(4)), + (remux.clone(), Some(2)), + (remux.clone(), Some(9)), // gone: refused by name, still a row + ]; + let before = read_bytes(); + let opened = subtitle::open_all(&rows); + let cost = read_bytes() - before; + assert_eq!( + opened.iter().map(|t| (&t.path, t.track)).collect::>(), + rows.iter().map(|(p, n)| (p, *n)).collect::>(), + "every row comes back where it was saved" + ); + assert_eq!(opened[1].label, "eng", "and it is that file's track 1"); + assert_eq!(opened[2].cues, expected(), "the standalone row is untouched"); + assert!( + opened[5] + .refused + .as_deref() + .unwrap_or_default() + .contains("no subtitle track 9"), + "{:?}", + opened[5].refused + ); + assert!( + cost < one_walk * 2, + "four rows of one file is one walk of it: {cost} bytes read against {one_walk} for a walk" + ); } /// A refusal a front-end shows at the moment of the import, rather than a row