forge
Explore
Log in

Don't you dare go Hollow

As many tracks as you want, embedded in the export

Browse files at this commit

28e2853243cdd45d859f1d2819b21f41cef4c5aaAhmet Kaan GümüşParent: 702501a
  • feat
    • as many tracks as you want, embedded in the export
Show full message
✨ feat(subtitles): as many tracks as you want, embedded in the export

Subtitle tracks now work the way audio and video tracks do: add as many
as you like, remove any of them, and every track with cues on the
timeline is written into the exported file.

Add and remove
- "+ S" beside "+ V"/"+ A" imports every subtitle track in a picked
  file; each row carries its own "x". Pointer and keyboard doors share
  one implementation and refuse identically, before any chooser opens.
- Project::remove_subtitles / PlaybackSession::remove_subtitles, with
  the index fixup in one place so a removal cannot repoint the overlay.

Embedded in the output
- ExportSettings.subtitles is a list; the Matroska muxer writes N tracks
  from number 3 up, ceiling derived from the encoding (0x7F -
  SUB_TRACK_FIRST) because track 127 is the all-ones VINT our own reader
  maps to "unknown" and would silently lose.
- mp4 carries them too, as real tx3g timed text. The old "an mp4 carries
  none" was a false refusal: mp4 0.14 has MediaConfig::TtxtConfig all
  along. Samples are built from cue boundaries, so gaps are empty
  samples and the track spans the film.
- of_mp4 reads them back, so edith re-imports its own output. Verified
  against a file ffmpeg muxed, which writes mdhd in microseconds where
  we write milliseconds.
- The export set is derived from timeline_cues per call, so it cannot
  desync; the card names a track it leaves off, and counts past the
  width budget rather than eating the card.

Language and title
- SubtitleTrack carries language and name apart; the guess-them-back
  heuristic is gone. LanguageBCP47 is read and mapped to a 3-letter code
  (ffmpeg reads no BCP-47 at all, so writing it would have made the
  language invisible). A 17-track subtitle library file and a
  dual-language one no longer read "und".

Media bitrate in properties
- engine::probe_bitrate opens no decoder; all three numbers share the
  container's duration, so total >= video + audio holds by construction.
  Within 0.004% of ffprobe across the library.
- Both properties cards show it; a dual-audio file says which of how
  many. The line picks one unit off its smallest stated component, so a
  real value never renders as 0.00.

Off the render thread
- The subtitle walk moved to the background executor at every door:
  1324ms -> 0.1ms on a 3.1GB film, 234ms -> 5.0ms on a 25.4GB/35-track
  one. (The media walk is still on the render thread; separate slice.)

False refusals removed
- .mks and .mka were refused while the compiled-in Matroska reader
  parses them; is_matroska now takes the standard's closed set.
- The audio-only "sound alone" sentence was unreachable when every pick
  was a bitmap track.

Subtitle-free exports stay byte-identical: 294a8b0c (hevc mkv),
8c16b8b1 (default mp4).

15 changed files +3733 -375

crates/app/src/keymap.rsmodified+24 -1
@@ -92,6 +92,8 @@ actions! {
92 AddAudioLane,92 AddAudioLane,
93 RemoveVideoLane,93 RemoveVideoLane,
94 RemoveAudioLane,94 RemoveAudioLane,
95+ AddSubtitleTrack,
96+ RemoveSubtitleTrack,
95 ToggleMute,97 ToggleMute,
96 VolumeUp,98 VolumeUp,
97 VolumeDown,99 VolumeDown,
@@ -146,6 +148,8 @@ impl ActionId {
146 ActionId::AddAudioLane => "Add an audio track",148 ActionId::AddAudioLane => "Add an audio track",
147 ActionId::RemoveVideoLane => "Remove the last video track (it must be empty)",149 ActionId::RemoveVideoLane => "Remove the last video track (it must be empty)",
148 ActionId::RemoveAudioLane => "Remove the last audio track (it must be empty)",150 ActionId::RemoveAudioLane => "Remove the last audio track (it must be empty)",
151+ ActionId::AddSubtitleTrack => "Add subtitles from a file…",
152+ ActionId::RemoveSubtitleTrack => "Remove the picked subtitle track",
149 ActionId::ToggleMute => "Mute / Unmute",153 ActionId::ToggleMute => "Mute / Unmute",
150 ActionId::VolumeUp => "Volume up",154 ActionId::VolumeUp => "Volume up",
151 ActionId::VolumeDown => "Volume down",155 ActionId::VolumeDown => "Volume down",
@@ -195,6 +199,8 @@ impl ActionId {
195 ActionId::AddAudioLane => "add-audio-lane",199 ActionId::AddAudioLane => "add-audio-lane",
196 ActionId::RemoveVideoLane => "remove-video-lane",200 ActionId::RemoveVideoLane => "remove-video-lane",
197 ActionId::RemoveAudioLane => "remove-audio-lane",201 ActionId::RemoveAudioLane => "remove-audio-lane",
202+ ActionId::AddSubtitleTrack => "add-subtitle-track",
203+ ActionId::RemoveSubtitleTrack => "remove-subtitle-track",
198 ActionId::ToggleMute => "toggle-mute",204 ActionId::ToggleMute => "toggle-mute",
199 ActionId::VolumeUp => "volume-up",205 ActionId::VolumeUp => "volume-up",
200 ActionId::VolumeDown => "volume-down",206 ActionId::VolumeDown => "volume-down",
@@ -264,6 +270,12 @@ impl ActionId {
264 // Not a view setting despite being a pointer aid: it decides where270 // Not a view setting despite being a pointer aid: it decides where
265 // a drag actually lands, which is an edit and not a magnification.271 // a drag actually lands, which is an edit and not a magnification.
266 | ActionId::ToggleSnap272 | ActionId::ToggleSnap
273+ // The subtitle pair is a track pair like the lanes above it: what
274+ // they add is on the timeline and goes into the file an export
275+ // writes, where the toggle two headings down only decides whether
276+ // this window draws it.
277+ | ActionId::AddSubtitleTrack
278+ | ActionId::RemoveSubtitleTrack
267 | ActionId::RemoveAudioLane => Category::Editing,279 | ActionId::RemoveAudioLane => Category::Editing,
268 ActionId::ToggleMute280 ActionId::ToggleMute
269 | ActionId::VolumeUp281 | ActionId::VolumeUp
@@ -723,6 +735,13 @@ impl Keymap {
723 // key beside it.735 // key beside it.
724 b(ActionId::RemoveVideoLane, "b", true),736 b(ActionId::RemoveVideoLane, "b", true),
725 b(ActionId::RemoveAudioLane, "a", true),737 b(ActionId::RemoveAudioLane, "a", true),
738+ // The subtitle pair reads the same way: the unshifted initial
739+ // adds one -- "s" is free, the save is the *ctrl* chord -- and a
740+ // ctrl chord takes it back. Ctrl+s is that save, so the removal
741+ // takes the other letter subtitles already answer to here: "t"
742+ // shows and hides them, and ctrl+t takes one off the timeline.
743+ b(ActionId::AddSubtitleTrack, "s", false),
744+ b(ActionId::RemoveSubtitleTrack, "t", true),
726 b(ActionId::ToggleMute, "m", false),745 b(ActionId::ToggleMute, "m", false),
727 // The unshifted pair, which is what gpui reports for those two746 // The unshifted pair, which is what gpui reports for those two
728 // keys ("=" and "-", platform.rs:862): the volume keys every747 // keys ("=" and "-", platform.rs:862): the volume keys every
@@ -1023,7 +1042,7 @@ mod tests {
1023 #[test]1042 #[test]
1024 fn every_default_stroke_reaches_its_action() {1043 fn every_default_stroke_reaches_its_action() {
1025 let k = Keymap::defaults();1044 let k = Keymap::defaults();
1026- assert_eq!(k.entries().len(), 44);1045+ assert_eq!(k.entries().len(), 46);
1027 assert_eq!(k.lookup("f1", false), Some(ActionId::ShowActions));1046 assert_eq!(k.lookup("f1", false), Some(ActionId::ShowActions));
1028 assert_eq!(k.lookup("space", false), Some(ActionId::Play));1047 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
1029 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two1048 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
@@ -1062,6 +1081,10 @@ mod tests {
1062 // press. Ctrl+v is the paste, so the video one sits beside it.1081 // press. Ctrl+v is the paste, so the video one sits beside it.
1063 assert_eq!(k.lookup("b", true), Some(ActionId::RemoveVideoLane));1082 assert_eq!(k.lookup("b", true), Some(ActionId::RemoveVideoLane));
1064 assert_eq!(k.lookup("a", true), Some(ActionId::RemoveAudioLane));1083 assert_eq!(k.lookup("a", true), Some(ActionId::RemoveAudioLane));
1084+ // The subtitle pair, the third kind of track: the initial adds and the
1085+ // subtitle letter's chord takes it back.
1086+ assert_eq!(k.lookup("s", false), Some(ActionId::AddSubtitleTrack));
1087+ assert_eq!(k.lookup("t", true), Some(ActionId::RemoveSubtitleTrack));
1065 assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute));1088 assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute));
1066 assert_eq!(k.lookup("q", false), Some(ActionId::Equalizer));1089 assert_eq!(k.lookup("q", false), Some(ActionId::Equalizer));
1067 // The volume pair is the unshifted one, so neither needs a modifier1090 // The volume pair is the unshifted one, so neither needs a modifier
crates/app/src/main.rsmodified+1135 -148
@@ -19,7 +19,7 @@ use engine::limiter::Limiter;
19 use engine::project::{Edge, Lane, LaneKind, Source, Speed};19 use engine::project::{Edge, Lane, LaneKind, Source, Speed};
20 use engine::scale::FitPolicy;20 use engine::scale::FitPolicy;
21 use engine::tonemap::Preset;21 use engine::tonemap::Preset;
22-use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};22+use engine::{Clip, Codec, ExportHandle, Frame, MediaBitrate, PlaybackSession};
23 use gpui::{23 use gpui::{
24 AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, DragMoveEvent,24 AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, DragMoveEvent,
25 FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,25 FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
@@ -222,6 +222,16 @@ const LIST_CHAR_W: f32 = 6.;
222 /// The fewest characters a clipped name is cut to, however narrow the column222 /// The fewest characters a clipped name is cut to, however narrow the column
223 /// gets: past this there is nothing on either side of the gap to read.223 /// gets: past this there is nothing on either side of the gap to read.
224 const LIST_CLIP_MIN: usize = 5;224 const LIST_CLIP_MIN: usize = 5;
225+/// How long the export card's Subtitles line may get before it counts tracks
226+/// instead of naming them ([`subtitle_plan`]). Three lines of that row's value
227+/// box, at [`LIST_CHAR_W`] to a character: [`EXPORT_W`] less the row's padding
228+/// and gap, its tick and [`EXPORT_KEY_W`] key column, and the word "Subtitles"
229+/// in front of the value. Not a track count -- what walks the Destination row
230+/// off the bottom of the card is the *wrapping*, and thirty-five one-word
231+/// labels wrap less than three long ones.
232+const SUB_PLAN_CHARS: usize = (3.
233+ * (EXPORT_W - 12. - 12. - (10. + 8. + EXPORT_KEY_W + 8. + 9. * LIST_CHAR_W))
234+ / LIST_CHAR_W) as usize;
225 235
226 /// The one key name this file still spells out, and gpui's spelling of it: it236 /// The one key name this file still spells out, and gpui's spelling of it: it
227 /// is the way out of a capture and out of the overlay, and both have to work237 /// is the way out of a capture and out of the overlay, and both have to work
@@ -1153,6 +1163,12 @@ struct Player {
1153 /// presence means "asked" -- and an empty list is a silent file, which is1163 /// presence means "asked" -- and an empty list is a silent file, which is
1154 /// exactly one row and no stream tags.1164 /// exactly one row and no stream tags.
1155 streams: HashMap<PathBuf, Vec<StreamInfo>>,1165 streams: HashMap<PathBuf, Vec<StreamInfo>>,
1166+ /// What each source is coded at, read off its header once and kept: what a
1167+ /// properties card says about a file's rate. Filled like `streams` --
1168+ /// presence means "asked" -- and the inner `None` is "asked, not answered
1169+ /// yet", which the card draws as an ellipsis: the probe walks a Matroska's
1170+ /// clusters, so a big film answers in seconds rather than at once.
1171+ bitrates: HashMap<PathBuf, Option<MediaBitrate>>,
1156 /// How big each still source's picture is, read from its header once and1172 /// How big each still source's picture is, read from its header once and
1157 /// kept -- what a library row and its card say about a file that has no1173 /// kept -- what a library row and its card say about a file that has no
1158 /// streams to describe. Filled like `streams`: presence means "asked", and1174 /// streams to describe. Filled like `streams`: presence means "asked", and
@@ -1623,6 +1639,11 @@ impl Player {
1623 // through the × in its own header.1639 // through the × in its own header.
1624 ActionId::RemoveVideoLane => self.remove_last_lane(LaneKind::Video, cx),1640 ActionId::RemoveVideoLane => self.remove_last_lane(LaneKind::Video, cx),
1625 ActionId::RemoveAudioLane => self.remove_last_lane(LaneKind::Audio, cx),1641 ActionId::RemoveAudioLane => self.remove_last_lane(LaneKind::Audio, cx),
1642+ // The same chooser the + S button opens, and the picked row -- the
1643+ // one the panel draws highlighted -- for the removal: the × on any
1644+ // other row is that row's own door, and both doors are one call.
1645+ ActionId::AddSubtitleTrack => self.pick_and_add_subtitles(cx),
1646+ ActionId::RemoveSubtitleTrack => self.remove_subtitle_track(self.sub_track, cx),
1626 ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx),1647 ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx),
1627 ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx),1648 ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx),
1628 ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),1649 ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),
@@ -2716,7 +2737,8 @@ impl Player {
2716 self.reset_after_reseek();2737 self.reset_after_reseek();
2717 self.notice = Some(2738 self.notice = Some(
2718 format!(2739 format!(
2719- "{count} SILENCES CUT {reach} — {saved:.1}s shorter, {} takes it back",2740+ "{count} SILENCES CUT {reach} — {} shorter, {} takes it back",
2741+ secs_label(saved),
2720 self.keymap.display(ActionId::Undo)2742 self.keymap.display(ActionId::Undo)
2721 )2743 )
2722 .into(),2744 .into(),
@@ -3242,6 +3264,26 @@ impl Player {
3242 })3264 })
3243 .detach();3265 .detach();
3244 }3266 }
3267+ // What each file is coded at, for the card that says so. Header and
3268+ // sample table only, but a Matroska indexes no samples and its open
3269+ // walks every cluster header -- 6.7 s on a 12.9 GB film -- so this of
3270+ // all of them cannot be on the render thread.
3271+ for path in unseen_paths(session.sources(), &self.bitrates) {
3272+ self.bitrates.insert(path.clone(), None);
3273+ let probed = cx.background_executor().spawn({
3274+ let path = path.clone();
3275+ async move { engine::probe_bitrate(&path) }
3276+ });
3277+ cx.spawn(async move |this, cx| {
3278+ let probed = probed.await;
3279+ this.update(cx, |this, cx| {
3280+ this.bitrates.insert(path, Some(probed));
3281+ cx.notify();
3282+ })
3283+ .ok();
3284+ })
3285+ .detach();
3286+ }
3245 // Which decoder each file will run on, for the row that says so before3287 // Which decoder each file will run on, for the row that says so before
3246 // a frame of it plays. Off the render thread like the streams above: a3288 // a frame of it plays. Off the render thread like the streams above: a
3247 // stream the plugin takes costs one VA-API init (~90 ms) to answer.3289 // stream the plugin takes costs one VA-API init (~90 ms) to answer.
@@ -3322,14 +3364,17 @@ impl Player {
3322 return;3364 return;
3323 }3365 }
3324 let meta = *session.meta();3366 let meta = *session.meta();
3325- let key = (settings, (meta.width, meta.height));3367+ // Cloned rather than copied: the settings carry the picked subtitle
3368+ // rows, which is a `Vec` ([`engine::export::ExportSettings`]).
3369+ let key = (settings.clone(), (meta.width, meta.height));
3326 if self3370 if self
3327 .export_seat3371 .export_seat
3328- .is_some_and(|(asked, size, _)| (asked, size) == key)3372+ .as_ref()
3373+ .is_some_and(|(asked, size, _)| (asked, size) == (&key.0, &key.1))
3329 {3374 {
3330 return;3375 return;
3331 }3376 }
3332- self.export_seat = Some((key.0, key.1, None));3377+ self.export_seat = Some((key.0.clone(), key.1, None));
3333 let probed = cx3378 let probed = cx
3334 .background_executor()3379 .background_executor()
3335 .spawn(async move { engine::export::planned_video(&meta, &settings) });3380 .spawn(async move { engine::export::planned_video(&meta, &settings) });
@@ -3341,7 +3386,7 @@ impl Player {
3341 if let Some(seat) = this3386 if let Some(seat) = this
3342 .export_seat3387 .export_seat
3343 .as_mut()3388 .as_mut()
3344- .filter(|(asked, size, _)| (*asked, *size) == key)3389+ .filter(|(asked, size, _)| (asked, size) == (&key.0, &key.1))
3345 {3390 {
3346 seat.2 = probed;3391 seat.2 = probed;
3347 }3392 }
@@ -3956,6 +4001,7 @@ impl Player {
3956 self.close_silence();4001 self.close_silence();
3957 self.waves.clear();4002 self.waves.clear();
3958 self.streams.clear();4003 self.streams.clear();
4004+ self.bitrates.clear();
3959 self.sizes.clear();4005 self.sizes.clear();
3960 // Scanned off sources that are not in the library any more.4006 // Scanned off sources that are not in the library any more.
3961 self.silence_levels.clear();4007 self.silence_levels.clear();
@@ -4138,8 +4184,8 @@ impl Player {
4138 // All that is left here is to hang everything derived from it off the4184 // All that is left here is to hang everything derived from it off the
4139 // window -- the clock, the title, where an export and a save go -- and4185 // window -- the clock, the title, where an export and a save go -- and
4140 // that is arithmetic, not a read.4186 // that is arithmetic, not a read.
4141- match landed {4187+ let subs = match landed {
4142- Landed::Read => {}4188+ Landed::Read(subs) => subs,
4143 what => {4189 what => {
4144 self.opening = None;4190 self.opening = None;
4145 match what {4191 match what {
@@ -4150,7 +4196,7 @@ impl Player {
4150 self.notice = Some(text.into());4196 self.notice = Some(text.into());
4151 cx.notify();4197 cx.notify();
4152 }4198 }
4153- Landed::Read => unreachable!("matched above"),4199+ Landed::Read(_) => unreachable!("matched above"),
4154 }4200 }
4155 // The line a launch has always printed, now printed when the4201 // The line a launch has always printed, now printed when the
4156 // file actually arrives: it is the mark that says the timeline4202 // file actually arrives: it is the mark that says the timeline
@@ -4167,7 +4213,7 @@ impl Player {
4167 }4213 }
4168 return;4214 return;
4169 }4215 }
4170- }4216+ };
4171 // An empty window has no library to add to yet: the file opens one, and4217 // An empty window has no library to add to yet: the file opens one, and
4172 // the timeline under it stays empty, because an import is an import4218 // the timeline under it stays empty, because an import is an import
4173 // whether or not a session was already up. A file *named at launch* is4219 // whether or not a session was already up. A file *named at launch* is
@@ -4178,44 +4224,27 @@ impl Player {
4178 // section shows and what the overlay draws. With no timeline open there4224 // section shows and what the overlay draws. With no timeline open there
4179 // is nothing for the cues to be timed against, and it says so.4225 // is nothing for the cues to be timed against, and it says so.
4180 if is_subtitle(path) {4226 if is_subtitle(path) {
4181- let text = match self4227+ self.take_subtitles(path, subs, cx);
4182- .session
4183- .as_mut()
4184- .map(|session| session.import_subtitles(path))
4185- {
4186- Some(Ok(0)) => format!("{} is already on the timeline", file_name(path)),
4187- Some(Ok(_)) => format!(
4188- "SUBTITLES {} — showing over the picture, {} hides them",
4189- file_name(path),
4190- self.keymap.display(ActionId::ToggleSubtitles)
4191- ),
4192- Some(Err(e)) => format!("SUBTITLE IMPORT FAILED: {e}"),
4193- None => {
4194- "NO SUBTITLES ADDED — open a file for them to run against first".to_string()
4195- }
4196- };
4197- eprintln!("{text}");
4198- self.notice = Some(text.into());
4199- cx.notify();
4200 return;4228 return;
4201 }4229 }
4202 let text = match self.session.as_mut().map(|session| session.import(path)) {4230 let text = match self.session.as_mut().map(|session| session.import(path)) {
4203 Some(Ok(_)) => {4231 Some(Ok(_)) => {
4204 // The file's own subtitle tracks with it, exactly as an open4232 // The file's own subtitle tracks with it, exactly as an open
4205 // takes them: an import is the other door the same file arrives4233 // takes them: an import is the other door the same file arrives
4206- // through.4234+ // through. The cues were read on the worker
4207- let subs = self4235+ // ([`read_ahead`]); what happens here is the push.
4236+ let tail = self
4208 .session4237 .session
4209 .as_mut()4238 .as_mut()
4210- .and_then(|session| subtitle_notice(session, path))4239+ .and_then(|session| subtitle_tail(session, subs))
4211 .unwrap_or_default();4240 .unwrap_or_default();
4212 format!(4241 format!(
4213- "IMPORTED {} to the library — drag it onto a lane to place it{subs}",4242+ "IMPORTED {} to the library — drag it onto a lane to place it{tail}",
4214 file_name(path)4243 file_name(path)
4215 )4244 )
4216 }4245 }
4217 Some(Err(e)) => format!("IMPORT FAILED: {e}"),4246 Some(Err(e)) => format!("IMPORT FAILED: {e}"),
4218- None => self.open_media(path, false),4247+ None => self.open_media(path, false, subs),
4219 };4248 };
4220 eprintln!("{text}");4249 eprintln!("{text}");
4221 self.notice = Some(text.into());4250 self.notice = Some(text.into());
@@ -4231,8 +4260,8 @@ impl Player {
4231 /// `place` is the difference between the two doors that come here: a file4260 /// `place` is the difference between the two doors that come here: a file
4232 /// *opened* is the timeline, one *imported* into an empty window fills the4261 /// *opened* is the timeline, one *imported* into an empty window fills the
4233 /// library and leaves the lanes empty for a drag.4262 /// library and leaves the lanes empty for a drag.
4234- fn open_media(&mut self, path: &std::path::Path, place: bool) -> String {4263+ fn open_media(&mut self, path: &std::path::Path, place: bool, subs: Subs) -> String {
4235- self.install_media(path, open_session(path, place), place)4264+ self.install_media(path, open_session(path, place, subs), place)
4236 }4265 }
4237 4266
4238 /// The second half of it: everything the window derives from a session that4267 /// The second half of it: everything the window derives from a session that
@@ -4288,7 +4317,9 @@ impl Player {
4288 if self.exporting().is_some() {4317 if self.exporting().is_some() {
4289 return;4318 return;
4290 }4319 }
4291- let picked = cx.background_executor().spawn(async { pick_file() });4320+ let picked = cx
4321+ .background_executor()
4322+ .spawn(async { pick_file("edith — import") });
4292 cx.spawn(async move |this, cx| {4323 cx.spawn(async move |this, cx| {
4293 let picked = picked.await;4324 let picked = picked.await;
4294 this.update(cx, |this, cx| match picked {4325 this.update(cx, |this, cx| match picked {
@@ -4309,6 +4340,179 @@ impl Player {
4309 .detach();4340 .detach();
4310 }4341 }
4311 4342
4343+ /// The `+ S` button and its key: asks the desktop for a file and takes the
4344+ /// subtitle tracks out of it -- a standalone `.srt`/`.vtt`/`.ass` is one of
4345+ /// them, a Matroska however many are inside. Only the subtitles: the file
4346+ /// itself does not join the library, which is what the Import button beside
4347+ /// this one is for.
4348+ ///
4349+ /// The chooser is another process and the user may sit in it, so it runs on
4350+ /// a background thread, exactly as [`Player::pick_and_import`] does.
4351+ fn pick_and_add_subtitles(&mut self, cx: &mut Context<Self>) {
4352+ // What dims the `+ S` button, asked here as well so the key answers the
4353+ // same question -- and *before* the chooser rather than after it: a door
4354+ // that opens a dialog, waits for a file and only then says the timeline
4355+ // was never there is the second door disagreeing with the first.
4356+ if let Some(why) = self.enable(ActionId::AddSubtitleTrack, None).why() {
4357+ let text = format!("NO SUBTITLES ADDED — {why}");
4358+ eprintln!("{text}");
4359+ self.notice = Some(text.into());
4360+ cx.notify();
4361+ return;
4362+ }
4363+ let picked = cx
4364+ .background_executor()
4365+ .spawn(async { pick_file("edith — subtitles to add") });
4366+ cx.spawn(async move |this, cx| {
4367+ let picked = picked.await;
4368+ this.update(cx, |this, cx| match picked {
4369+ Ok(Some(path)) => this.add_subtitles(&path, cx),
4370+ // Cancelled: the user already knows what happened.
4371+ Ok(None) => {}
4372+ Err(text) => {
4373+ eprintln!("{text}");
4374+ this.notice = Some(text.into());
4375+ cx.notify();
4376+ }
4377+ })
4378+ .ok();
4379+ })
4380+ .detach();
4381+ }
4382+
4383+ /// Takes a file's subtitle tracks onto the timeline, off the render thread.
4384+ /// The walk reads the whole container for its cues
4385+ /// (`engine::PlaybackSession::parse_subtitles`) -- ~200 ms on a two-hour 4K
4386+ /// remux and 1.3 s on a cold 3 GB one -- and a button that costs the window
4387+ /// that many frames is a button that freezes it. So the *parse* is the
4388+ /// worker's, whole, and the UI thread only pushes what came back
4389+ /// ([`PlaybackSession::add_subtitle_tracks`]): no borrow crosses the await,
4390+ /// because the parse is an associated fn that owns nothing.
4391+ fn add_subtitles(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
4392+ // Nothing to time the cues against: said now rather than after a walk
4393+ // of a 25 GB file that was never going to be kept.
4394+ if self.session.is_none() {
4395+ self.landed_subtitles(path, None, cx);
4396+ return;
4397+ }
4398+ self.notice = Some(format!("READING {} for subtitles…", file_name(path)).into());
4399+ let parsed = cx.background_executor().spawn({
4400+ let path = path.to_path_buf();
4401+ async move { engine::PlaybackSession::parse_subtitles(&path) }
4402+ });
4403+ let path = path.to_path_buf();
4404+ cx.spawn(async move |this, cx| {
4405+ let parsed = parsed.await;
4406+ this.update(cx, |this, cx| {
4407+ // The dedupe lives inside the push, so a second `+ S` on the
4408+ // same file still answers 0 and still says so below.
4409+ let added = this
4410+ .session
4411+ .as_mut()
4412+ .map(|session| parsed.map(|tracks| session.add_subtitle_tracks(tracks)));
4413+ this.landed_subtitles(&path, added, cx);
4414+ })
4415+ .ok();
4416+ })
4417+ .detach();
4418+ cx.notify();
4419+ }
4420+
4421+ /// Every subtitle track a `.srt`/`.vtt`/`.ass` carries, onto the timeline
4422+ /// and nowhere else: they are not clips and land on no lane. The cues came
4423+ /// off the worker that read the file ([`read_ahead`]), like every other
4424+ /// door's do, and what is left here is the push. The engine dedupes by
4425+ /// (file, track), so the same `.srt` twice is one row and says so.
4426+ fn take_subtitles(&mut self, path: &std::path::Path, subs: Subs, cx: &mut Context<Self>) {
4427+ let added = self
4428+ .session
4429+ .as_mut()
4430+ .map(|session| subs.map(|tracks| session.add_subtitle_tracks(tracks)));
4431+ self.landed_subtitles(path, added, cx);
4432+ }
4433+
4434+ /// What the timeline says once the tracks are on it, whichever worker did
4435+ /// the reading: the `+ S` button and its key ([`Self::add_subtitles`]), a
4436+ /// dropped or imported subtitle file ([`Self::take_subtitles`]), and a
4437+ /// window with nothing to time cues against all word the outcome here,
4438+ /// once, so no two doors can drift apart.
4439+ fn landed_subtitles(
4440+ &mut self,
4441+ path: &std::path::Path,
4442+ added: Option<engine::Result<usize>>,
4443+ cx: &mut Context<Self>,
4444+ ) {
4445+ let text = match added {
4446+ Some(Ok(0)) => format!("{} is already on the timeline", file_name(path)),
4447+ Some(Ok(n)) => format!(
4448+ "SUBTITLES {} — {n} track(s), showing over the picture, {} hides them",
4449+ file_name(path),
4450+ self.keymap.display(ActionId::ToggleSubtitles)
4451+ ),
4452+ Some(Err(e)) => format!("SUBTITLE IMPORT FAILED: {e}"),
4453+ None => "NO SUBTITLES ADDED — open a file for them to run against first".to_string(),
4454+ };
4455+ eprintln!("{text}");
4456+ self.notice = Some(text.into());
4457+ cx.notify();
4458+ }
4459+
4460+ /// The × on a subtitle row, and the stroke that takes the picked one off:
4461+ /// the track leaves the timeline and the pick moves with it. Every index
4462+ /// past the one that went moves down
4463+ /// ([`engine::Project::remove_subtitles`]), so a pick left where it was
4464+ /// would name a *different* track -- and the pick is what an export writes
4465+ /// into the file.
4466+ ///
4467+ /// Not an undo step: subtitles are not on the history's snapshots, so the
4468+ /// way back is importing the file again. The notice says that rather than
4469+ /// promising a ctrl+z that would do nothing.
4470+ fn remove_subtitle_track(&mut self, track: usize, cx: &mut Context<Self>) {
4471+ // The one availability oracle, for the same reason the × on a row and
4472+ // the stroke are one call: an empty list is not a failure, it is an
4473+ // action with nothing to act on, and the engine's "there is no subtitle
4474+ // track 0" is an index nobody typed. A real removal that fails still
4475+ // says what the engine said, below.
4476+ if let Some(why) = self.enable(ActionId::RemoveSubtitleTrack, None).why() {
4477+ let text = format!("NO SUBTITLES REMOVED — {why}");
4478+ eprintln!("{text}");
4479+ self.notice = Some(text.into());
4480+ cx.notify();
4481+ return;
4482+ }
4483+ // Read before it goes: a notice naming an index names nothing.
4484+ let name = self
4485+ .session
4486+ .as_ref()
4487+ .and_then(|session| sub_pick_name(session.subtitles(), track))
4488+ .unwrap_or_else(|| format!("subtitle track {track}"));
4489+ let text = match self
4490+ .session
4491+ .as_mut()
4492+ .map(|session| session.remove_subtitles(track))
4493+ {
4494+ Some(Ok(())) => {
4495+ let left = self
4496+ .session
4497+ .as_ref()
4498+ .map_or(0, |session| session.subtitles().len());
4499+ self.sub_track = sub_pick_after_removal(self.sub_track, track, left);
4500+ // The drawn cue is keyed by that index ([`Player::sub_picture`])
4501+ // and the index now stands for another track.
4502+ //
4503+ // ponytail: its atlas tile is not released -- `close_session`'s
4504+ // note, for its reason and with its upgrade path.
4505+ self.sub_image = None;
4506+ format!("{name} REMOVED — importing the file again brings it back")
4507+ }
4508+ Some(Err(e)) => format!("NO SUBTITLES REMOVED — {e}"),
4509+ None => "NO SUBTITLES REMOVED — open a file first".to_string(),
4510+ };
4511+ eprintln!("{text}");
4512+ self.notice = Some(text.into());
4513+ cx.notify();
4514+ }
4515+
4312 /// Swaps the whole timeline for one restored from a `.edith`. Like an4516 /// Swaps the whole timeline for one restored from a `.edith`. Like an
4313 /// import this arrives by drop and so checks the export guard for itself.4517 /// import this arrives by drop and so checks the export guard for itself.
4314 /// The new session is built before anything is replaced, so a refusal is4518 /// The new session is built before anything is replaced, so a refusal is
@@ -4766,6 +4970,46 @@ impl Player {
4766 .detach();4970 .detach();
4767 }4971 }
4768 4972
4973+ /// The subtitle tracks an export of this timeline carries: every one with a
4974+ /// cue left in the exported range ([`PlaybackSession::timeline_cues`], the
4975+ /// very map the file is written from), in the library's own order.
4976+ ///
4977+ /// Worked out from the cues each time rather than kept as a pick, which is
4978+ /// what makes it impossible to desync: a row added or taken off shifts every
4979+ /// index after it, and a stored list would then name tracks nobody chose.
4980+ /// `Player::sub_track` stays what it always was -- which track the *overlay*
4981+ /// draws -- and has no say here.
4982+ ///
4983+ /// The honest input and not the final answer: the engine filters it again
4984+ /// per track (a track that could not be read, a picture one) and says so in
4985+ /// the card's own words ([`engine::export::planned_subtitles`]).
4986+ fn export_subs(&self) -> Vec<usize> {
4987+ let Some(session) = self.session.as_ref() else {
4988+ return Vec::new();
4989+ };
4990+ (0..session.subtitles().len())
4991+ .filter(|&i| !session.timeline_cues(i).is_empty())
4992+ .collect()
4993+ }
4994+
4995+ /// That list in the card's words ([`subtitle_plan`]): what travels, and the
4996+ /// reason beside every track that does not -- including the ones
4997+ /// [`Self::export_subs`] filtered out before the engine ever saw them.
4998+ fn subtitle_line(&self) -> String {
4999+ let Some(session) = self.session.as_ref() else {
5000+ return "none".to_string();
5001+ };
5002+ let picks = self.export_subs();
5003+ let plan = session.planned_subtitles(self.format, picks.iter().copied());
5004+ match self.format.has_video() {
5005+ true => subtitle_plan(plan, session.subtitles(), &picks),
5006+ // A format that is the sound alone has nowhere to put any of them
5007+ // and the engine says that once, about the file. Naming the cues of
5008+ // each track under it answers a question the format already closed.
5009+ false => plan,
5010+ }
5011+ }
5012+
4769 /// Writes the edit list out, at the settings the card was left at. Playback5013 /// Writes the edit list out, at the settings the card was left at. Playback
4770 /// stops first: the exporter opens its own decoder -- and, on the hardware5014 /// stops first: the exporter opens its own decoder -- and, on the hardware
4771 /// path, an encoder -- so a running player would only compete with it for5015 /// path, an encoder -- so a running player would only compete with it for
@@ -4778,11 +5022,11 @@ impl Player {
4778 }5022 }
4779 let mut settings =5023 let mut settings =
4780 export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps);5024 export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps);
4781- // The track the library has picked is the one that travels -- the same5025+ // Whatever is on the timeline travels -- every track with a cue in the
4782- // row the overlay draws, so the file carries what was watched. Set here5026+ // exported range, not the one row the overlay happens to be drawing.
4783- // rather than inside `export_settings`, which the card also calls for5027+ // Set here rather than inside `export_settings`, which the card also
4784- // the *estimate* and which nothing else needs a subtitle for.5028+ // calls for the *estimate* and which nothing else needs a subtitle for.
4785- settings.subtitles = Some(self.sub_track);5029+ settings.subtitles = self.export_subs();
4786 let Some(session) = &mut self.session else {5030 let Some(session) = &mut self.session else {
4787 self.notice = Some("NOTHING TO EXPORT — open a file first".into());5031 self.notice = Some("NOTHING TO EXPORT — open a file first".into());
4788 cx.notify();5032 cx.notify();
@@ -5894,6 +6138,11 @@ impl Player {
5894 true => format!("{} {}", row.label, row.number),6138 true => format!("{} {}", row.label, row.number),
5895 false => row.label,6139 false => row.label,
5896 };6140 };
6141+ // A standalone `.srt` is named after its own file, so
6142+ // the file in front of it says the same word twice
6143+ // ("Legend.of.… · Legend.of.…"). [`sub_pick_name`]'s
6144+ // rule, on the row it is about.
6145+ let owned = several_files && !title.starts_with(name.as_str());
5897 // The whole path, never clipped: the row says which6146 // The whole path, never clipped: the row says which
5898 // file, and the tooltip says which one on disk.6147 // file, and the tooltip says which one on disk.
5899 let tip: SharedString = match &row.refused {6148 let tip: SharedString = match &row.refused {
@@ -5904,6 +6153,11 @@ impl Player {
5904 ),6153 ),
5905 }6154 }
5906 .into();6155 .into();
6156+ // Named, because a × is the same glyph on every row and
6157+ // the tooltip is what says which track it takes off.
6158+ let remove_tip: SharedString =
6159+ format!("Remove {title} — importing the file again brings it back")
6160+ .into();
5907 div()6161 div()
5908 // The *flat* index into the session's add-order6162 // The *flat* index into the session's add-order
5909 // list, which is what a pick is and what a save6163 // list, which is what a pick is and what a save
@@ -5960,7 +6214,7 @@ impl Player {
5960 // truncates from the right: an6214 // truncates from the right: an
5961 // ownership word at the end is a6215 // ownership word at the end is a
5962 // word the floor never shows.6216 // word the floor never shows.
5963- .when(several_files, |d| {6217+ .when(owned, |d| {
5964 d.child(6218 d.child(
5965 div()6219 div()
5966 .flex_none()6220 .flex_none()
@@ -5990,6 +6244,34 @@ impl Player {
5990 .child(row.detail),6244 .child(row.detail),
5991 ),6245 ),
5992 )6246 )
6247+ // The way back off the timeline, on every row and on
6248+ // the last one too -- a list of subtitles is allowed
6249+ // to be empty, unlike a lane. A `HIT_MIN` target and
6250+ // never hidden, the lane header's ×, and it stops
6251+ // the click there: the row under it picks a track,
6252+ // and picking the track that has just gone would
6253+ // leave the pick naming nothing.
6254+ .child(
6255+ div()
6256+ .id(("subtitle-remove", track))
6257+ .flex_none()
6258+ .w(px(HIT_MIN))
6259+ .h_full()
6260+ .flex()
6261+ .items_center()
6262+ .justify_center()
6263+ .rounded(px(3.))
6264+ .cursor_pointer()
6265+ .hover(|s| s.bg(rgb(HOVER)))
6266+ .tooltip(move |_, cx| cx.new(|_| Tip(remove_tip.clone())).into())
6267+ .on_click(cx.listener(
6268+ move |this, _: &ClickEvent, _, cx| {
6269+ cx.stop_propagation();
6270+ this.remove_subtitle_track(track, cx);
6271+ },
6272+ ))
6273+ .child("×"),
6274+ )
5993 })6275 })
5994 .collect();6276 .collect();
5995 div()6277 div()
@@ -6442,6 +6724,35 @@ impl Player {
6442 this.add_lane(LaneKind::Audio, cx)6724 this.add_lane(LaneKind::Audio, cx)
6443 }),6725 }),
6444 ))6726 ))
6727+ // The third kind of track this timeline carries, and
6728+ // the only one that arrived through a drop alone: a
6729+ // subtitle file nobody thought to drag was a track
6730+ // the editor could not be asked for. What it opens is
6731+ // a chooser rather than an empty row -- a subtitle
6732+ // track is its file, and there is nothing to add
6733+ // before one is named.
6734+ .child(control(
6735+ "add-subtitle-track",
6736+ None,
6737+ "+ S",
6738+ // Dim, and saying why it is dim, out of the one
6739+ // oracle -- the very words the key answers with
6740+ // (`Player::pick_and_add_subtitles`), so the
6741+ // tooltip and the notice cannot come to differ.
6742+ match self.enable(ActionId::AddSubtitleTrack, None).why() {
6743+ Some(why) => {
6744+ format!("{} — {why}", key(ActionId::AddSubtitleTrack))
6745+ }
6746+ None => format!(
6747+ "{} — adds every subtitle track in a file you pick",
6748+ key(ActionId::AddSubtitleTrack)
6749+ ),
6750+ },
6751+ live,
6752+ cx.listener(|this, _: &ClickEvent, _, cx| {
6753+ this.pick_and_add_subtitles(cx)
6754+ }),
6755+ ))
6445 // With the transport, not the edit group: it changes what6756 // With the transport, not the edit group: it changes what
6446 // the file sounds like, never what it is. Reads as its own6757 // the file sounds like, never what it is. Reads as its own
6447 // state, so muted is legible without a tooltip.6758 // state, so muted is legible without a tooltip.
@@ -7029,7 +7340,11 @@ impl Player {
7029 div()7340 div()
7030 .flex()7341 .flex()
7031 // The floor, not the height: a row that needed two lines7342 // The floor, not the height: a row that needed two lines
7032- // would otherwise paint over the one under it.7343+ // would otherwise paint over the one under it -- which it did
7344+ // anyway until this said `flex_none`, a row inside a capped
7345+ // scrolling list being shrunk to fit by default (the export
7346+ // card's rows had the same shape and the same overlap).
7347+ .flex_none()
7033 .min_h(px(KEYS_ROW_H))7348 .min_h(px(KEYS_ROW_H))
7034 .items_center()7349 .items_center()
7035 .justify_between()7350 .justify_between()
@@ -7282,7 +7597,13 @@ impl Player {
7282 .id(id)7597 .id(id)
7283 .flex()7598 .flex()
7284 // The floor, not the height: the destination's path wraps on a7599 // The floor, not the height: the destination's path wraps on a
7285- // long name and must not paint over the row under it.7600+ // long name and must not paint over the row under it. Which it
7601+ // did: inside a capped, scrolling list a row shrinks to fit by
7602+ // default, so a wrapped detail was drawn over the row beneath
7603+ // it (the Sound row's "the source's own packets are copied…"
7604+ // over Subtitles). The list scrolls -- a row is as tall as what
7605+ // it has to say.
7606+ .flex_none()
7286 .min_h(px(KEYS_ROW_H))7607 .min_h(px(KEYS_ROW_H))
7287 .items_center()7608 .items_center()
7288 .justify_between()7609 .justify_between()
@@ -7511,22 +7832,29 @@ impl Player {
7511 }));7832 }));
7512 }7833 }
7513 list.push(r.into_any_element());7834 list.push(r.into_any_element());
7514- // What happens to the picked subtitle track, in one line: it is written7835+ // What happens to the subtitles on this timeline, in one line: how many
7515- // into the file, or the reason it is not. Nothing to pick here -- which7836+ // are written into the file and under what names, or the reason each one
7516- // track is the library's row and the container is the format row above7837+ // is not. Which tracks travel is not a pick -- everything with a cue on
7517- // -- so the row says and does not answer, like the machine lines below.7838+ // the timeline goes ([`Player::export_subs`]) -- so the row says rather
7839+ // than offers, like the machine lines below.
7840+ // ...and the ones that do not travel are named here too, which they were
7841+ // not: `export_subs` had already filtered a track with no cue on *this*
7842+ // timeline out of the engine's sight, so the card said nothing about a
7843+ // row the list was still showing ([`subtitle_plan`]).
7844+ let plan = self.subtitle_line();
7845+ // The row used to end in "click for <fmt> in MKV" whenever the picture
7846+ // was going into an mp4, on the grounds that only Matroska carries a
7847+ // text track. An mp4 carries one now (`Mp4Muxer::write_subtitles` writes
7848+ // `tx3g`), so that was a refusal offering a way out of nothing: the
7849+ // container the card is already set to embeds them. The refusals left in
7850+ // `planned_subtitles` are the true ones -- a sound-only format has
7851+ // nowhere to put a track, and a PGS track is pictures whatever the box.
7518 list.push(7852 list.push(
7519 entry(7853 entry(
7520 ("subtitles", 0),7854 ("subtitles", 0),
7521 "",7855 "",
7522 "Subtitles".into(),7856 "Subtitles".into(),
7523- self.session7857+ plan.into(),
7524- .as_ref()
7525- .map_or_else(
7526- || "none".into(),
7527- |s| s.planned_subtitles(self.format, Some(self.sub_track)),
7528- )
7529- .into(),
7530 false,7858 false,
7531 false,7859 false,
7532 )7860 )
@@ -7641,7 +7969,7 @@ impl Player {
7641 .map_or("", |s| s.planned_audio(self.format));7969 .map_or("", |s| s.planned_audio(self.format));
7642 let settings =7970 let settings =
7643 export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps);7971 export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps);
7644- let mb = estimated_mb(7972+ let size = estimated_bytes(
7645 settings.bitrate.filter(|_| self.format.has_video()),7973 settings.bitrate.filter(|_| self.format.has_video()),
7646 self.session7974 self.session
7647 .as_ref()7975 .as_ref()
@@ -7650,8 +7978,8 @@ impl Player {
7650 let head = summary_head(self.format, picture, audio);7978 let head = summary_head(self.format, picture, audio);
7651 let tail = summary_tail(7979 let tail = summary_tail(
7652 &self.export_path,7980 &self.export_path,
7653- mb,7981+ size,
7654- self.export_seat.and_then(|(.., seat)| seat),7982+ self.export_seat.as_ref().and_then(|(.., seat)| *seat),
7655 self.format.has_video(),7983 self.format.has_video(),
7656 );7984 );
7657 // The button says the refusal *before* it is pressed: the picked codec7985 // The button says the refusal *before* it is pressed: the picked codec
@@ -8732,8 +9060,8 @@ impl Player {
8732 ),9060 ),
8733 None => match found {9061 None => match found {
8734 0 => "nothing quiet enough for long enough".to_string(),9062 0 => "nothing quiet enough for long enough".to_string(),
8735- 1 => format!("1 silence, {secs:.1}s"),9063+ 1 => format!("1 silence, {}", secs_label(secs)),
8736- n => format!("{n} silences, {secs:.1}s"),9064+ n => format!("{n} silences, {}", secs_label(secs)),
8737 },9065 },
8738 };9066 };
8739 let rows: Vec<_> = rows9067 let rows: Vec<_> = rows
@@ -8947,6 +9275,13 @@ impl Player {
8947 info.map_or_else(|| "no track of its own".to_string(), stream_detail),9275 info.map_or_else(|| "no track of its own".to_string(), stream_detail),
8948 ),9276 ),
8949 },9277 },
9278+ (
9279+ "Bitrate",
9280+ bitrate_detail(
9281+ self.bitrates.get(&path).copied().flatten(),
9282+ self.streams.get(&path).map_or(0, Vec::len),
9283+ ),
9284+ ),
8950 match image {9285 match image {
8951 true => (9286 true => (
8952 "Longest hold",9287 "Longest hold",
@@ -9114,6 +9449,13 @@ impl Player {
9114 ("This clip", secs(clip.frames())),9449 ("This clip", secs(clip.frames())),
9115 ("Speed", format!("{} (tape)", clip.speed)),9450 ("Speed", format!("{} (tape)", clip.speed)),
9116 ("Source duration", secs(session.file_frames(&source.path))),9451 ("Source duration", secs(session.file_frames(&source.path))),
9452+ (
9453+ "Bitrate",
9454+ bitrate_detail(
9455+ self.bitrates.get(&source.path).copied().flatten(),
9456+ self.streams.get(&source.path).map_or(0, Vec::len),
9457+ ),
9458+ ),
9117 ] {9459 ] {
9118 rows.push(9460 rows.push(
9119 row(rows.len())9461 row(rows.len())
@@ -10249,11 +10591,18 @@ fn run_picker(pickers: [(&str, Vec<String>); 2]) -> Option<Option<PathBuf>> {
10249 None10591 None
10250 }10592 }
10251 10593
10252-fn pick_file() -> Result<Option<PathBuf>, &'static str> {10594+/// `title` is what the dialog calls itself: two buttons open this same chooser
10595+/// for two different questions -- a file to import, a file to take subtitles out
10596+/// of -- and a dialog titled "import" over the second one is the wrong question
10597+/// answered. No extension filter on either: what can be read is the engine's
10598+/// answer (`PlaybackSession::parse_subtitles` takes a container as readily as a
10599+/// `.srt`), and a list of suffixes written here would hide a file edith would
10600+/// have taken.
10601+fn pick_file(title: &str) -> Result<Option<PathBuf>, &'static str> {
10253 run_picker([10602 run_picker([
10254 (10603 (
10255 "zenity",10604 "zenity",
10256- vec!["--file-selection".into(), "--title=edith — import".into()],10605+ vec!["--file-selection".into(), format!("--title={title}")],
10257 ),10606 ),
10258 ("kdialog", vec!["--getopenfilename".into()]),10607 ("kdialog", vec!["--getopenfilename".into()]),
10259 ])10608 ])
@@ -10333,31 +10682,51 @@ fn audio_notice(session: &PlaybackSession) -> Option<String> {
10333 /// formats `engine::subtitle` parses, lowercased, for [`engine::is_audio`]'s10682 /// formats `engine::subtitle` parses, lowercased, for [`engine::is_audio`]'s
10334 /// reason -- the import door has to know which of the engine's two doors a file10683 /// reason -- the import door has to know which of the engine's two doors a file
10335 /// goes through before anything is opened.10684 /// goes through before anything is opened.
10685+///
10686+/// `.mks` is one of them, and it is the only Matroska extension that is: it is
10687+/// the *subtitles alone*, so there is no source in it to import and a drop of
10688+/// one used to be refused for having no video track -- while `+ S` on the same
10689+/// bytes took it ([`PlaybackSession::parse_subtitles`] reads it as Matroska).
10690+/// The other two are media and stay media: `.mka` is the sound alone, which
10691+/// [`engine::is_audio`] already imports as a song, and `.mk3d` is a film. Both
10692+/// may *carry* subtitles, which is [`carries_subtitles`] and not this.
10336 fn is_subtitle(path: &std::path::Path) -> bool {10693 fn is_subtitle(path: &std::path::Path) -> bool {
10337 path.extension().and_then(|e| e.to_str()).is_some_and(|e| {10694 path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
10338 matches!(10695 matches!(
10339 e.to_ascii_lowercase().as_str(),10696 e.to_ascii_lowercase().as_str(),
10340- "srt" | "vtt" | "webvtt" | "ass" | "ssa"10697+ "srt" | "vtt" | "webvtt" | "ass" | "ssa" | "mks"
10341 )10698 )
10342 })10699 })
10343 }10700 }
10344 10701
10345 /// Whether a media path is a container that can carry subtitle tracks *inside*10702 /// Whether a media path is a container that can carry subtitle tracks *inside*
10346-/// it -- the two Matroska extensions, which is what10703+/// it -- every Matroska extension and the three ISO-BMFF ones, which is the list
10347-/// [`PlaybackSession::import_subtitles`] walks for them.10704+/// [`PlaybackSession::parse_subtitles`] walks (Matroska blocks and mp4 `tx3g`
10348-fn is_matroska(path: &std::path::Path) -> bool {10705+/// alike). Named for what it gates and not for one of the two families, because
10349- path.extension()10706+/// an mp4 answers `true` here now.
10350- .and_then(|e| e.to_str())10707+///
10351- .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "mkv" | "webm"))10708+/// Matroska's set is the standard's own and closed by it
10709+/// (`engine::demux::is_matroska`), so it is copied whole rather than trimmed to
10710+/// the two that carry a film: a `.mk3d` opened as media has its tracks walked
10711+/// like the `.mkv` it is, and a `.mka` song can hold a lyric track. A suffix
10712+/// wider than the engine's would be a file taken here and refused deeper down.
10713+fn carries_subtitles(path: &std::path::Path) -> bool {
10714+ path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
10715+ matches!(
10716+ e.to_ascii_lowercase().as_str(),
10717+ "mkv" | "mka" | "mks" | "mk3d" | "webm" | "mp4" | "m4v" | "mov"
10718+ )
10719+ })
10352 }10720 }
10353 10721
10354 /// What a worker hands back, which is the fork [`arrival`] made when it was10722 /// What a worker hands back, which is the fork [`arrival`] made when it was
10355 /// started. An import is *read* and thrown away; the file argv named is opened10723 /// started. An import is *read* and thrown away; the file argv named is opened
10356 /// outright, because nothing else is going to open it afterwards.10724 /// outright, because nothing else is going to open it afterwards.
10357 enum Landed {10725 enum Landed {
10358- /// An import: pages warmed, nothing kept. [`Player::take_import`] opens the10726+ /// An import: pages warmed, and the subtitle tracks the walk found *kept* --
10359- /// file again, warm, and that second open is the 150 ms one.10727+ /// the walk is the expensive half and the worker is where it belongs, so
10360- Read,10728+ /// [`Player::take_import`] is left with a push ([`subtitle_tail`]).
10729+ Read(Subs),
10361 /// The media argv named, with the tail its subtitle tracks earn: a whole10730 /// The media argv named, with the tail its subtitle tracks earn: a whole
10362 /// timeline, ready to be hung off the window, or the engine's refusal.10731 /// timeline, ready to be hung off the window, or the engine's refusal.
10363 Media(Result<(PlaybackSession, String), String>),10732 Media(Result<(PlaybackSession, String), String>),
@@ -10371,14 +10740,18 @@ enum Landed {
10371 ///10740 ///
10372 /// `place` is which door: a file *opened* is the timeline, one *imported* into10741 /// `place` is which door: a file *opened* is the timeline, one *imported* into
10373 /// an empty window fills the library and leaves the lanes empty for a drag.10742 /// an empty window fills the library and leaves the lanes empty for a drag.
10374-fn open_session(path: &std::path::Path, place: bool) -> Result<(PlaybackSession, String), String> {10743+fn open_session(
10744+ path: &std::path::Path,
10745+ place: bool,
10746+ subs: Subs,
10747+) -> Result<(PlaybackSession, String), String> {
10375 let opened = match place {10748 let opened = match place {
10376 true => PlaybackSession::open(path),10749 true => PlaybackSession::open(path),
10377 false => PlaybackSession::open_library(path),10750 false => PlaybackSession::open_library(path),
10378 };10751 };
10379 let mut session = opened.map_err(|e| e.to_string())?;10752 let mut session = opened.map_err(|e| e.to_string())?;
10380- let subs = subtitle_notice(&mut session, path).unwrap_or_default();10753+ let tail = subtitle_tail(&mut session, subs).unwrap_or_default();
10381- Ok((session, subs))10754+ Ok((session, tail))
10382 }10755 }
10383 10756
10384 /// The whole of what a queued file costs, off the UI thread. An import only10757 /// The whole of what a queued file costs, off the UI thread. An import only
@@ -10392,10 +10765,7 @@ fn open_ahead(
10392 ) -> Landed {10765 ) -> Landed {
10393 use std::sync::atomic::Ordering::Relaxed;10766 use std::sync::atomic::Ordering::Relaxed;
10394 match what {10767 match what {
10395- Landing::Import => {10768+ Landing::Import => Landed::Read(read_ahead(path, stage)),
10396- read_ahead(path, stage);
10397- Landed::Read
10398- }
10399 Landing::Project => {10769 Landing::Project => {
10400 let opened = PlaybackSession::open_project(path).map_err(|e| e.to_string());10770 let opened = PlaybackSession::open_project(path).map_err(|e| e.to_string());
10401 Landed::Project(opened)10771 Landed::Project(opened)
@@ -10414,24 +10784,33 @@ fn open_ahead(
10414 }10784 }
10415 10785
10416 /// Reads, off the UI thread, exactly what the import that follows is about to10786 /// Reads, off the UI thread, exactly what the import that follows is about to
10417-/// read -- and throws every byte away. The point is the page cache: a cold10787+/// read. The container's header is read for the page cache and thrown away: a
10418-/// header walk of a 29 GB remux is 11 s and a warm one is 150 ms (measured,10788+/// cold header walk of a 29 GB remux is 11 s and a warm one is 150 ms
10419-/// `a real 4K HEVC film` 2160p h265), so this call is the eleven seconds and10789+/// (measured, `a real 4K HEVC film` 2160p h265), so this call is the eleven
10420-/// [`Player::take_import`] is the hundred and fifty milliseconds. The window10790+/// seconds and [`Player::take_import`] is the hundred and fifty milliseconds.
10421-/// keeps painting through the eleven.10791+/// The window keeps painting through the eleven.
10422 ///10792 ///
10423-/// Errors are dropped on purpose: a file that cannot be read is refused by the10793+/// Header errors are dropped on purpose: a file that cannot be read is refused
10424-/// engine a moment later, in the engine's own words, and a refusal read twice10794+/// by the engine a moment later, in the engine's own words, and a refusal read
10425-/// is a refusal worded twice.10795+/// twice is a refusal worded twice. The *subtitle* refusal is carried back
10796+/// instead of dropped, for exactly that reason -- nothing walks those cues a
10797+/// second time to re-word it.
10426 ///10798 ///
10427 /// `stage` is what the line above the panel is naming while this runs.10799 /// `stage` is what the line above the panel is naming while this runs.
10428 ///10800 ///
10429-/// ponytail: the cache is the whole handoff, so a machine that evicts those10801+/// The subtitle half is not thrown away: it is *the* answer, handed back for
10430-/// pages between this read and the next frame pays the cold walk on the UI10802+/// [`Player::take_import`] to push ([`subtitle_tail`]) rather than walked a
10431-/// thread after all. Ceiling: memory pressure inside one repaint of a 25 GB10803+/// second time on the render thread -- 234 ms of a warmed 25 GB remux and 1.3 s
10432-/// file. The upgrade is an engine door that takes the header this already10804+/// of a cold 3 GB one, which is what a frozen window is made of.
10433-/// parsed ([`PlaybackSession::import`] opens the demuxer again today).10805+///
10434-fn read_ahead(path: &std::path::Path, stage: &std::sync::atomic::AtomicU8) {10806+/// ponytail: only the subtitle half is handed over. The container's own header
10807+/// is still merely *warmed* here, so [`PlaybackSession::import`] and
10808+/// [`open_session`] walk it again on the UI thread -- 2.8 s of that same 25 GB
10809+/// file. Ceiling: the media walk, not the subtitle one. The upgrade is the
10810+/// engine door this comment has always named: one that takes the header this
10811+/// already parsed, the way [`PlaybackSession::add_subtitle_tracks`] takes the
10812+/// cues this already read.
10813+fn read_ahead(path: &std::path::Path, stage: &std::sync::atomic::AtomicU8) -> Subs {
10435 use std::sync::atomic::Ordering::Relaxed;10814 use std::sync::atomic::Ordering::Relaxed;
10436 stage.store(ImportStage::Header as u8, Relaxed);10815 stage.store(ImportStage::Header as u8, Relaxed);
10437 // The three doors an import goes through, each warmed by the call the10816 // The three doors an import goes through, each warmed by the call the
@@ -10443,34 +10822,67 @@ fn read_ahead(path: &std::path::Path, stage: &std::sync::atomic::AtomicU8) {
10443 engine::demux::Demuxer::open(path).ok();10822 engine::demux::Demuxer::open(path).ok();
10444 }10823 }
10445 stage.store(ImportStage::Subtitles as u8, Relaxed);10824 stage.store(ImportStage::Subtitles as u8, Relaxed);
10446- // ...and the tracks inside it, which `subtitle_notice` walks straight10825+ // ...and the tracks inside it, kept.
10447- // after. A standalone `.srt` is small enough to be nobody's wait.10826+ walk_subtitles(path)
10448- if is_matroska(path) {10827+}
10449- engine::subtitle::of_matroska(path).ok();10828+
10829+/// Every subtitle track a file carries, cues and all -- the walk that costs, in
10830+/// the one place every door that pays it goes through. `Ok` and empty for a file
10831+/// with none to read, which is what a file that is neither a container we can
10832+/// walk ([`carries_subtitles`]) nor a subtitle file is: the same answer
10833+/// `add_subtitle_tracks` gives it, and nothing is opened to find that out.
10834+///
10835+/// Nothing in here is a session, on purpose ([`PlaybackSession::parse_subtitles`]
10836+/// is an associated fn): no borrow crosses the await, so this runs whole on a
10837+/// worker while the window keeps painting.
10838+fn walk_subtitles(path: &std::path::Path) -> Subs {
10839+ match carries_subtitles(path) || is_subtitle(path) {
10840+ true => PlaybackSession::parse_subtitles(path),
10841+ false => Ok(Vec::new()),
10450 }10842 }
10451 }10843 }
10452 10844
10453 /// The subtitle tracks a media file carries, taken into the session as it is10845 /// The subtitle tracks a media file carries, taken into the session as it is
10454-/// opened, and the tail the notice grows for them: an mkv with subtitles in it10846+/// opened, and the tail the notice grows for them: an mkv or an mp4 with
10455-/// arrives with its subtitles, because a track nobody imported is a track nobody10847+/// subtitles in it arrives with its subtitles, because a track nobody imported
10456-/// knows is there. Every other container answers `None` without being read.10848+/// is a track nobody knows is there. Every other container answers `None`
10849+/// without being read.
10457 ///10850 ///
10458 /// A refusal is a tail too, never a failure of the open: the picture and the10851 /// A refusal is a tail too, never a failure of the open: the picture and the
10459 /// sound of a film whose subtitle tracks cannot be walked are still the film.10852 /// sound of a film whose subtitle tracks cannot be walked are still the film.
10460 ///10853 ///
10461-/// The walk reads the whole file for its cues10854+/// Both halves at once, which only a *worker* may do: the walk reads the whole
10462-/// (`engine::subtitle::of_matroska`) -- ~200 ms on a two-hour 4K remux, and an10855+/// file for its cues (`engine::subtitle::of_matroska`) -- ~200 ms on a two-hour
10463-/// *import* pays it on a worker first ([`read_ahead`]), so what happens here is10856+/// 4K remux, 9.7 s on a cold 25 GB one. The one caller is the open beside which
10464-/// the warm second pass. A file *opened* at launch pays it cold and pays it10857+/// this runs on the worker ([`open_ahead`]), never the render thread; an
10465-/// once -- this runs on the worker beside the open itself ([`open_ahead`]),10858+/// import splits the two halves across the hop instead ([`read_ahead`] walks,
10466-/// with the window already up and naming the read.10859+/// [`subtitle_tail`] pushes).
10467 fn subtitle_notice(session: &mut PlaybackSession, path: &std::path::Path) -> Option<String> {10860 fn subtitle_notice(session: &mut PlaybackSession, path: &std::path::Path) -> Option<String> {
10468- if !is_matroska(path) {10861+ subtitle_tail(session, walk_subtitles(path))
10469- return None;10862+}
10470- }10863+
10471- match session.import_subtitles(path) {10864+/// What a subtitle walk ([`walk_subtitles`]) gave, on its way from whichever
10472- Ok(0) => None,10865+/// thread paid for it to the timeline. `Send` all the way down (`sendable()`,
10473- Ok(n) => Some(format!(" — {n} subtitle track(s) in the file")),10866+/// `engine/tests/subtitles.rs`), which is what lets the walk be a worker's.
10867+type Subs = engine::Result<Vec<engine::subtitle::SubtitleTrack>>;
10868+
10869+/// The tail a file's own subtitle tracks earn on the notice that names it, and
10870+/// the push that puts them on the timeline -- the second half of the walk, the
10871+/// cheap one ([`PlaybackSession::add_subtitle_tracks`]: no open, no seek, no
10872+/// decode). Every door that arrives with a *file* words it here, once: the file
10873+/// argv named, an import, and an import into an empty window cannot say the same
10874+/// thing differently, whichever thread read the cues.
10875+///
10876+/// `None` for a file that gave none and for one whose tracks are on the timeline
10877+/// already -- an import that adds nothing says nothing about subtitles. A
10878+/// refusal is a tail too, never a failure of the import: the picture and the
10879+/// sound of a film whose subtitle tracks cannot be walked are still the film.
10880+fn subtitle_tail(session: &mut PlaybackSession, subs: Subs) -> Option<String> {
10881+ match subs {
10882+ Ok(tracks) => match session.add_subtitle_tracks(tracks) {
10883+ 0 => None,
10884+ n => Some(format!(" — {n} subtitle track(s) in the file")),
10885+ },
10474 Err(e) => Some(format!(" — SUBTITLES UNREAD: {e}")),10886 Err(e) => Some(format!(" — SUBTITLES UNREAD: {e}")),
10475 }10887 }
10476 }10888 }
@@ -10489,6 +10901,85 @@ fn subtitle_detail(track: &engine::subtitle::SubtitleTrack) -> String {
10489 }10901 }
10490 }10902 }
10491 10903
10904+/// What the export card's Subtitles row says: the engine's own words for the
10905+/// tracks an export carries (`plan`, [`engine::export::planned_subtitles`] asked
10906+/// about `picks`) and, beside them, the rows it is carrying nothing of.
10907+///
10908+/// `picks` is [`Player::export_subs`] -- every track with a cue left in the
10909+/// exported range -- so a track sitting in the list with eighty-three cues
10910+/// nowhere near a trimmed timeline never reaches the engine at all, and the card
10911+/// said nothing about it while the list went on showing it. Which tracks have
10912+/// cues *here* is this side's answer and nobody else's, so this side words it.
10913+///
10914+/// Past [`SUB_PLAN_CHARS`] the line counts rather than names: every name is more
10915+/// words in a value box `MENU_W` wide, and at 35 tracks the row wrapped to ten
10916+/// lines and pushed the Destination row under the fold of the card. The names
10917+/// are still one row each in the Subtitles list, with the cue count and the
10918+/// reason under them ([`subtitle_detail`]) -- more than this line ever said.
10919+///
10920+/// The counted split follows the engine's own order of reasons (`refused`, then
10921+/// pictures, then no cues), with the last asked of the timeline instead of the
10922+/// track.
10923+///
10924+/// ponytail: that split reads the same public fields the list rows read
10925+/// (`refused`, [`engine::subtitle::SubtitleTrack::is_bitmap`]) rather than the
10926+/// engine's decision, so a *new* reason to drop a track would be counted here as
10927+/// embedded until this follows it -- the named line, which is the engine's
10928+/// string verbatim, would say it correctly meanwhile. Upgrade path: reasons out
10929+/// of `planned_subtitles` as data rather than as one sentence, which is an
10930+/// engine change.
10931+fn subtitle_plan(
10932+ plan: String,
10933+ tracks: &[engine::subtitle::SubtitleTrack],
10934+ picks: &[usize],
10935+) -> String {
10936+ let mut parts: Vec<String> = Vec::new();
10937+ // "none" is the engine's word for an empty pick list and would read as a
10938+ // verdict on the tracks named after it.
10939+ if !picks.is_empty() {
10940+ parts.push(plan);
10941+ }
10942+ parts.extend(
10943+ tracks
10944+ .iter()
10945+ .enumerate()
10946+ .filter(|(i, _)| !picks.contains(i))
10947+ .map(|(_, track)| format!("{} — no cues here", track.label)),
10948+ );
10949+ let named = parts.join("; ");
10950+ if named.chars().count() <= SUB_PLAN_CHARS {
10951+ return match named.is_empty() {
10952+ true => "none".to_string(),
10953+ false => named,
10954+ };
10955+ }
10956+ let (mut embedded, mut unread, mut pictures, mut off) = (0, 0, 0, 0);
10957+ for (i, track) in tracks.iter().enumerate() {
10958+ match (
10959+ track.refused.is_some(),
10960+ track.is_bitmap(),
10961+ picks.contains(&i),
10962+ ) {
10963+ (true, _, _) => unread += 1,
10964+ (_, true, _) => pictures += 1,
10965+ (_, _, false) => off += 1,
10966+ _ => embedded += 1,
10967+ }
10968+ }
10969+ let mut counted = vec![format!("{embedded} of {} → embedded", tracks.len())];
10970+ counted.extend(
10971+ [
10972+ (pictures, "pictures"),
10973+ (unread, "unread"),
10974+ (off, "no cues here"),
10975+ ]
10976+ .into_iter()
10977+ .filter(|(n, _)| *n > 0)
10978+ .map(|(n, why)| format!("{n} {why}")),
10979+ );
10980+ counted.join("; ")
10981+}
10982+
10492 /// Every subtitle track one file gave, kept together. Plain data, planned10983 /// Every subtitle track one file gave, kept together. Plain data, planned
10493 /// before anything is drawn -- the grouping is the branchy part and it is the10984 /// before anything is drawn -- the grouping is the branchy part and it is the
10494 /// same answer whatever a styling puts around it.10985 /// same answer whatever a styling puts around it.
@@ -10531,6 +11022,32 @@ struct SubRow {
10531 bitmap: bool,11022 bitmap: bool,
10532 }11023 }
10533 11024
11025+/// What a subtitle row is called, off the two fields the container really
11026+/// stated rather than out of the flattened
11027+/// [`label`](engine::subtitle::SubtitleTrack::label). The pair is what an export
11028+/// writes (`TRACK_LANGUAGE` and `TRACK_NAME` are two fields), and reading the
11029+/// display string back apart is the very heuristic that sent every French track
11030+/// out as English: `lang_human` on a whole "und — Signs" matches nothing and
11031+/// names a language nobody speaks.
11032+///
11033+/// The three shapes a track arrives in, all three of them real: a standalone
11034+/// file states no language and is its own name, an embedded one states a
11035+/// language and sometimes a title beside it, and a refused one states neither
11036+/// and keeps the label it was refused under (`SubtitleTrack::refused`).
11037+fn sub_title(sub: &engine::subtitle::SubtitleTrack) -> String {
11038+ match (sub.language.as_str(), sub.name.as_str()) {
11039+ ("", "") => sub.label.clone(),
11040+ ("", name) => name.to_string(),
11041+ // A track whose only name is the tag for "nobody said" says that in
11042+ // words rather than showing the tag itself.
11043+ (lang, "") => lang_human(lang).to_string(),
11044+ // ...and one that says "nobody said" *and* gives a title is the title:
11045+ // "unknown language — Signs" pads it with a word the file never said.
11046+ ("und", name) => name.to_string(),
11047+ (lang, name) => format!("{lang} — {name}"),
11048+ }
11049+}
11050+
10534 /// The subtitle list as rows under the file each came out of: one group per11051 /// The subtitle list as rows under the file each came out of: one group per
10535 /// distinct path, in the order the files first appear, and each file's tracks11052 /// distinct path, in the order the files first appear, and each file's tracks
10536 /// in the order they were added. Two remuxes' tracks arriving interleaved --11053 /// in the order they were added. Two remuxes' tracks arriving interleaved --
@@ -10555,9 +11072,7 @@ fn subtitle_rows(tracks: &[engine::subtitle::SubtitleTrack]) -> Vec<SubGroup> {
10555 group.rows.push(SubRow {11072 group.rows.push(SubRow {
10556 track,11073 track,
10557 number: group.rows.len() + 1,11074 number: group.rows.len() + 1,
10558- // A track whose only name is the tag for "nobody said" says that11075+ label: sub_title(sub),
10559- // in words, here, rather than showing the tag itself.
10560- label: lang_human(&sub.label).to_string(),
10561 detail: subtitle_detail(sub),11076 detail: subtitle_detail(sub),
10562 refused: sub.refused.clone(),11077 refused: sub.refused.clone(),
10563 bitmap: sub.is_bitmap(),11078 bitmap: sub.is_bitmap(),
@@ -10581,6 +11096,27 @@ fn subtitle_rows(tracks: &[engine::subtitle::SubtitleTrack]) -> Vec<SubGroup> {
10581 ///11096 ///
10582 /// `None` for an index no track answers to, which is the silence11097 /// `None` for an index no track answers to, which is the silence
10583 /// [`Player::subtitle_track`] gives at the same moment.11098 /// [`Player::subtitle_track`] gives at the same moment.
11099+/// Where the picked subtitle row lands once `removed` has been taken off a list
11100+/// that is `left` long afterwards. The pick follows the list: the same *track*
11101+/// while it is still there -- every index past the one that went moves down
11102+/// ([`engine::Project::remove_subtitles`]) -- the row that slid into the empty
11103+/// place when the picked one is what went, and the last row when that was the
11104+/// last. Zero on an emptied list, which is the index the section is not drawn at
11105+/// all.
11106+///
11107+/// Its own function because the pick is what the overlay draws: left where it
11108+/// was it would name a different track, and the plate over the picture would
11109+/// change language on its own the moment a row above it went. What an export
11110+/// writes is *not* this pick and cannot be desynced by a removal -- it is worked
11111+/// out from the cues on the timeline each time ([`Player::export_subs`]).
11112+fn sub_pick_after_removal(picked: usize, removed: usize, left: usize) -> usize {
11113+ let picked = match removed < picked {
11114+ true => picked - 1,
11115+ false => picked,
11116+ };
11117+ picked.min(left.saturating_sub(1))
11118+}
11119+
10584 fn sub_pick_name(tracks: &[engine::subtitle::SubtitleTrack], track: usize) -> Option<String> {11120 fn sub_pick_name(tracks: &[engine::subtitle::SubtitleTrack], track: usize) -> Option<String> {
10585 subtitle_rows(tracks).into_iter().find_map(|group| {11121 subtitle_rows(tracks).into_iter().find_map(|group| {
10586 let row = group.rows.iter().find(|row| row.track == track)?;11122 let row = group.rows.iter().find(|row| row.track == track)?;
@@ -10891,7 +11427,11 @@ fn enable(action: ActionId, ctx: Ctx) -> Enable {
10891 // Nothing to draw over the picture, so nothing to switch off: the11427 // Nothing to draw over the picture, so nothing to switch off: the
10892 // library says how subtitles arrive, and this row would flip a state11428 // library says how subtitles arrive, and this row would flip a state
10893 // with no visible half either way.11429 // with no visible half either way.
10894- ActionId::ToggleSubtitles if !ctx.subtitles => Enable::No("no subtitles yet"),11430+ // ...and nothing to take off the timeline either, for the same reason:
11431+ // the row would name a track that is not there.
11432+ ActionId::ToggleSubtitles | ActionId::RemoveSubtitleTrack if !ctx.subtitles => {
11433+ Enable::No("no subtitles yet")
11434+ }
10895 ActionId::CancelExport => Enable::No("nothing is exporting"),11435 ActionId::CancelExport => Enable::No("nothing is exporting"),
10896 // A rate applies to a clip of either kind and to its whole group, so11436 // A rate applies to a clip of either kind and to its whole group, so
10897 // there is no lane it means nothing on, and the engine words the one11437 // there is no lane it means nothing on, and the engine words the one
@@ -11152,6 +11692,106 @@ fn stream_detail(info: &StreamInfo) -> String {
11152 parts.join(" ")11692 parts.join(" ")
11153 }11693 }
11154 11694
11695+/// What a file is coded at, for the properties cards: the rate of the whole
11696+/// file, then each track's own beside it. A component the container does not
11697+/// state is left out for `stream_detail`'s reason -- a fabricated `0` would be
11698+/// saying something -- and a file that states none of the three says so rather
11699+/// than showing an empty row. `None` is the probe still running, which is a
11700+/// real wait: it walks a Matroska's clusters.
11701+///
11702+/// The whole file's rate is the one that carries the unit and no word: named
11703+/// "total" as well, the line loses its last component to `MENU_W`'s truncation
11704+/// on an ordinary 1080p file -- and a rate cut to "0.13 soun" is a number the
11705+/// card did not give.
11706+///
11707+/// `tracks` is how many sound tracks the file has, from `probe_streams`. The
11708+/// rate is the one track this engine plays -- the first, neither their sum nor
11709+/// the biggest -- so a file with more says which of how many: a bare "0.16
11710+/// sound" on a file whose name says AC3.5.1 names a track without saying it is
11711+/// one of two, and the card's Audio row above it may be describing the other.
11712+///
11713+/// The marker costs the word "sound", the way the whole file's rate costs the
11714+/// word "total" above, and for the same reason. Measured in Noto Sans 11 px
11715+/// against the 186 px this value has beside a "Bitrate" label: "0.16 sound 1/2"
11716+/// wants 192 px on a small film's 4.7 Mb/s and 205 on the 39.8 Mb/s remux --
11717+/// the marker is what gets cut, which is the one part of the line that is new.
11718+/// Nothing that keeps the word fits the wide files -- the shortest, "snd 1/2",
11719+/// still wants 188 px on that remux -- so the word goes and the number keeps
11720+/// the answer: "0.16 1 of 2" wants 172 px, and 185 on the widest line a
11721+/// library can produce (the 10.9 Mb/s three-track film).
11722+fn bitrate_detail(rate: Option<MediaBitrate>, tracks: usize) -> String {
11723+ let Some(rate) = rate else {
11724+ return "…".to_string();
11725+ };
11726+ let (per, unit) = rate_scale(rate);
11727+ let mut parts: Vec<String> = Vec::new();
11728+ if let Some(total) = rate.total {
11729+ // One unit for the three numbers, carried once, on the whole file's
11730+ // rate: the components are read against it.
11731+ parts.push(format!("{} {unit}", scaled(total, per)));
11732+ }
11733+ if let Some(video) = rate.video {
11734+ parts.push(format!("{} video", scaled(video, per)));
11735+ }
11736+ if let Some(audio) = rate.audio {
11737+ parts.push(match tracks > 1 {
11738+ true => format!("{} 1 of {tracks}", scaled(audio, per)),
11739+ false => format!("{} sound", scaled(audio, per)),
11740+ });
11741+ }
11742+ match parts.is_empty() {
11743+ true => "not stated".to_string(),
11744+ false => parts.join(" · "),
11745+ }
11746+}
11747+
11748+/// Below this a megabit's two decimals cannot state a rate, so the line is read
11749+/// in kilobits instead.
11750+const MB_FLOOR: u64 = 10_000;
11751+
11752+/// What the line counts in, and the name of it: the largest unit that can state
11753+/// its *smallest* component, because that is the one a bigger unit rounds away.
11754+/// Megabits for everything a real file produces -- the smallest component over
11755+/// an 18-file sweep of a library was 0.13 Mb/s -- kilobits for the sub-32x32
11756+/// encodes below that.
11757+///
11758+/// ponytail: one unit for the whole line, so a file mixing a multi-megabit
11759+/// picture with a sub-10 kb/s sound track prints the picture as four or five
11760+/// digits of kilobits and loses the line's tail to `MENU_W`. No such file
11761+/// exists in a library, and both units at once ("0.01 Mb/s · 1.2 kb/s video ·
11762+/// 9.5 kb/s sound") wants 215 px of the 186 the row has. Upgrade path is a
11763+/// suffix per component ("1.2k video"), which measures 177 px.
11764+fn rate_scale(rate: MediaBitrate) -> (f64, &'static str) {
11765+ match [rate.total, rate.video, rate.audio]
11766+ .into_iter()
11767+ .flatten()
11768+ .min()
11769+ {
11770+ // A rate this small is a broken header rather than a track, but it is
11771+ // still a number the file stated, and bits state it.
11772+ Some(bits) if bits < 10 => (1., "b/s"),
11773+ Some(bits) if bits < MB_FLOOR => (1_000., "kb/s"),
11774+ _ => (1_000_000., "Mb/s"),
11775+ }
11776+}
11777+
11778+/// A rate in the line's unit as a person reads it: one decimal above 1 of it,
11779+/// two below -- a 128 kbps song rounded to one decimal is "0.1", which reads as
11780+/// a guess where "0.13" reads as a measurement.
11781+///
11782+/// Never `0.00`: [`rate_scale`] picks the unit off the smallest component, so
11783+/// two decimals always reach it. Every rate that gets here is one the container
11784+/// really stated (the probe leaves out what it does not state, it never zeroes
11785+/// it), and a "0.00 sound" would be this card saying a track that plays is
11786+/// silent.
11787+fn scaled(bits: u64, per: f64) -> String {
11788+ let n = bits as f64 / per;
11789+ match n >= 1. {
11790+ true => format!("{n:.1}"),
11791+ false => format!("{n:.2}"),
11792+ }
11793+}
11794+
11155 /// A language tag as a person reads it. Everything a file writes is passed11795 /// A language tag as a person reads it. Everything a file writes is passed
11156 /// through untouched bar the one tag that is not a language: "und" is what a11796 /// through untouched bar the one tag that is not a language: "und" is what a
11157 /// muxer writes when nobody said, and a row showing it verbatim names a11797 /// muxer writes when nobody said, and a row showing it verbatim names a
@@ -11801,8 +12441,8 @@ fn summary_head(format: Format, picture: Option<((u32, u32), f64)>, audio: &str)
11801 /// The second: where it lands, roughly how big, and what will encode the12441 /// The second: where it lands, roughly how big, and what will encode the
11802 /// picture -- the seat as the probe found it (`…` until it lands, never a12442 /// picture -- the seat as the probe found it (`…` until it lands, never a
11803 /// guess), which is what the running export then names on its progress line.12443 /// guess), which is what the running export then names on its progress line.
11804-fn summary_tail(path: &Path, mb: Option<u64>, seat: Option<&'static str>, video: bool) -> String {12444+fn summary_tail(path: &Path, bytes: Option<u64>, seat: Option<&'static str>, video: bool) -> String {
11805- let size = mb.map_or_else(String::new, |mb| format!("≈ {mb} MB"));12445+ let size = bytes.map_or_else(String::new, |bytes| format!("≈ {}", size_label(bytes)));
11806 let seat = match (video, seat) {12446 let seat = match (video, seat) {
11807 (true, Some(seat)) => seat,12447 (true, Some(seat)) => seat,
11808 (true, None) => "encoder …",12448 (true, None) => "encoder …",
@@ -11823,14 +12463,28 @@ fn fps_label(fps: f64) -> String {
11823 }12463 }
11824 }12464 }
11825 12465
11826-/// About how big a *chosen* bitrate makes the file: the picture's megabits over12466+/// About how big a *chosen* bitrate makes the file: the picture's bits over the
11827-/// the timeline's length. `None` for `Auto`, whose figure is the encoder's to12467+/// timeline's length, in bytes -- the unit the line is written in is
12468+/// [`size_label`]'s to pick. `None` for `Auto`, whose figure is the encoder's to
11828 /// decide, and for a format with no bitrate at all -- a number nobody picked is12469 /// decide, and for a format with no bitrate at all -- a number nobody picked is
11829 /// not an estimate. The sound and the container's own overhead are not in it,12470 /// not an estimate. The sound and the container's own overhead are not in it,
11830 /// which is why the card says "≈".12471 /// which is why the card says "≈".
11831-fn estimated_mb(bitrate: Option<u64>, duration: f64) -> Option<u64> {12472+fn estimated_bytes(bitrate: Option<u64>, duration: f64) -> Option<u64> {
11832 let bitrate = bitrate.filter(|&b| b > 0 && duration > 0.)?;12473 let bitrate = bitrate.filter(|&b| b > 0 && duration > 0.)?;
11833- Some((bitrate as f64 * duration / 8e6).round() as u64)12474+ Some((bitrate as f64 * duration / 8.).round() as u64)
12475+}
12476+
12477+/// A size in the largest unit that can state it, [`rate_scale`]'s rule:
12478+/// megabytes for an export of any length, kilobytes below the one a whole
12479+/// megabyte rounds away. A three second clip at the floor bitrate really is
12480+/// 375 kB, and "≈ 0 MB" would be this line saying the file it is about to write
12481+/// is empty -- the one thing the size field is there to deny. Never "0 kB"
12482+/// either: an estimate that exists is at least a kilobyte of file.
12483+fn size_label(bytes: u64) -> String {
12484+ match (bytes as f64 / 1e6).round() as u64 {
12485+ 0 => format!("{} kB", (bytes as f64 / 1e3).round().max(1.) as u64),
12486+ mb => format!("{mb} MB"),
12487+ }
11834 }12488 }
11835 12489
11836 /// What is in the file and what box it is in, which is the head of the summary.12490 /// What is in the file and what box it is in, which is the head of the summary.
@@ -11906,7 +12560,7 @@ fn export_settings(
11906 // The picked track is put on by `start_export`, which is the only12560 // The picked track is put on by `start_export`, which is the only
11907 // caller that writes a file; the rest of them are asking about the12561 // caller that writes a file; the rest of them are asking about the
11908 // bitrate and the format.12562 // bitrate and the format.
11909- subtitles: None,12563+ subtitles: Vec::new(),
11910 }12564 }
11911 }12565 }
11912 12566
@@ -12184,7 +12838,20 @@ fn span_label(span: f64) -> String {
12184 s if s >= 600. => format!("{:.0}m", s / 60.),12838 s if s >= 600. => format!("{:.0}m", s / 60.),
12185 s if s >= 60. => format!("{:.1}m", s / 60.),12839 s if s >= 60. => format!("{:.1}m", s / 60.),
12186 s if s >= 10. => format!("{s:.0}s"),12840 s if s >= 10. => format!("{s:.0}s"),
12187- s => format!("{s:.1}s"),12841+ s => secs_label(s),
12842+ }
12843+}
12844+
12845+/// A span of seconds as a person reads it: one decimal above a second, two
12846+/// below -- [`scaled`]'s rule, for its reason. The tightest zoom is
12847+/// [`ZOOM_MIN_FRAMES`] across the bed, which on the 240 fps slow-motion a phone
12848+/// writes is 0.03s, and a single frame of quiet at 60 fps is 0.02s: one decimal
12849+/// prints both as "0.0s", a pill and a notice saying the thing they are about
12850+/// has no length at all.
12851+fn secs_label(secs: f64) -> String {
12852+ match secs >= 1. {
12853+ true => format!("{secs:.1}s"),
12854+ false => format!("{secs:.2}s"),
12188 }12855 }
12189 }12856 }
12190 12857
@@ -13532,20 +14199,20 @@ mod tests {
13532 Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK,14199 Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK,
13533 INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX,14200 INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX,
13534 LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H,14201 LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H,
13535- MBPS_DIGITS, MBPS_MAX, MBPS_MIN, MENU_W, NO_FILE, NumberEdit, PANEL_H, ROW_ITEMS, RowCtx, RowItem,14202+ MBPS_DIGITS, MBPS_MAX, MBPS_MIN, MB_FLOOR, MENU_W, NO_FILE, NumberEdit, PANEL_H, ROW_ITEMS, RowCtx, RowItem,
13536 Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS,14203 Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS,
13537 SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo,14204 SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo,
13538 Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, band_label,14205 Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, band_label,
13539- bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, commit_mbps,14206+ bitrate_detail, bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, commit_mbps,
13540 containers,14207 containers,
13541 enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y,14208 enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y,
13542- estimated_mb, export_path, export_settings, format_key,14209+ estimated_bytes, export_path, export_settings, format_key,
13543 format_line, format_refusal, fps_choices, fps_label, frac_along, frac_down, frame_at,14210 format_line, format_refusal, fps_choices, fps_label, frac_along, frac_down, frame_at,
13544 frame_rate_ladder, histogram,14211 frame_rate_ladder, histogram,
13545 inserted_band, is_bare_modifier, is_project, keymap, keys_filter, keys_rows, lanes_h,14212 inserted_band, is_bare_modifier, is_project, keymap, keys_filter, keys_rows, lanes_h,
13546 marked, menu_at, menu_items, menu_rows_h, next_audio_kbps, next_container, normalise, nothing_to_play, panel_h, project_path,14213 marked, menu_at, menu_items, menu_rows_h, next_audio_kbps, next_container, normalise, nothing_to_play, panel_h, project_path,
13547- retarget, row_enable, row_items, scrub_due, show_label, silence_rate, snap_cue, snap_marks, snapped,14214+ retarget, row_enable, row_items, scrub_due, secs_label, show_label, silence_rate, size_label, snap_cue, snap_marks, snapped,
13548- source_tint, span_partner, speed_at, summary_head, summary_tail, timecode, transport,14215+ SUB_PLAN_CHARS, source_tint, span_partner, speed_at, sub_pick_after_removal, subtitle_plan, summary_head, summary_tail, timecode, transport,
13549 typed, unseen_paths, unseen_sources,14216 typed, unseen_paths, unseen_sources,
13550 whole_take, window_title,14217 whole_take, window_title,
13551 };14218 };
@@ -13565,9 +14232,9 @@ mod tests {
13565 use super::{14232 use super::{
13566 SUB_BOTTOM, SUB_CUE_MIN_W, SUB_HEAD_H, SUB_INK, SUB_LANE_H, SUB_LINE_H, SUB_ROWS_H,14233 SUB_BOTTOM, SUB_CUE_MIN_W, SUB_HEAD_H, SUB_INK, SUB_LANE_H, SUB_LINE_H, SUB_ROWS_H,
13567 SUB_STEM_SHARE, SUB_TEXT, clip_middle, cue_box,14234 SUB_STEM_SHARE, SUB_TEXT, clip_middle, cue_box,
13568- cues_at, file_tint, is_matroska, is_subtitle, lang_human, row_text_w, sub_headers_fit,14235+ carries_subtitles, cues_at, file_tint, is_subtitle, lang_human, row_text_w, sub_headers_fit,
13569- subtitle_detail, subtitle_notice,14236+ Subs, subtitle_detail, subtitle_notice, subtitle_tail,
13570- sub_pick_name, subtitle_rows, subtitle_strip_h,14237+ sub_pick_name, subtitle_rows, subtitle_strip_h, walk_subtitles,
13571 };14238 };
13572 14239
13573 /// What the file manager is handed: the parts a path keeps as they are, and14240 /// What the file manager is handed: the parts a path keeps as they are, and
@@ -15281,6 +15948,102 @@ mod tests {
15281 assert_eq!(snap_cue(false, 158, 40, 4, &marks), (158, None));15948 assert_eq!(snap_cue(false, 158, 40, 4, &marks), (158, None));
15282 }15949 }
15283 15950
15951+ /// The card's rate row: every component the container states and no other,
15952+ /// so a track the header is silent about is absent from the line rather
15953+ /// than sitting in it as a zero.
15954+ #[test]
15955+ fn a_rate_row_says_only_what_the_container_stated() {
15956+ use super::MediaBitrate;
15957+ let all = MediaBitrate {
15958+ total: Some(8_432_000),
15959+ video: Some(7_918_000),
15960+ audio: Some(128_000),
15961+ };
15962+ assert_eq!(
15963+ bitrate_detail(Some(all), 1),
15964+ "8.4 Mb/s · 7.9 video · 0.13 sound"
15965+ );
15966+ // A Matroska states no audio rate of its own: the sound is dropped from
15967+ // the line, never drawn as "0".
15968+ assert_eq!(
15969+ bitrate_detail(
15970+ Some(MediaBitrate {
15971+ audio: None,
15972+ ..all
15973+ }),
15974+ 1
15975+ ),
15976+ "8.4 Mb/s · 7.9 video"
15977+ );
15978+ // A still, or anything that would not open: the probe answered, and the
15979+ // answer is that nobody said.
15980+ assert_eq!(
15981+ bitrate_detail(Some(MediaBitrate::default()), 0),
15982+ "not stated"
15983+ );
15984+ // Asked, not answered yet -- a 12 GB film's walk takes seconds.
15985+ assert_eq!(bitrate_detail(None, 2), "…");
15986+ // A dual-audio file: the number is the track that plays, and the line
15987+ // says so rather than letting it stand for the AC-3 beside it.
15988+ assert_eq!(
15989+ bitrate_detail(Some(all), 2),
15990+ "8.4 Mb/s · 7.9 video · 0.13 1 of 2"
15991+ );
15992+ // Every component of a tiny file is stated, and small: the line changes
15993+ // unit, so not one of them reads as the zero it is not. In megabits
15994+ // this file was "0.00 Mb/s · 0.00 video · 0.00 sound".
15995+ assert_eq!(
15996+ bitrate_detail(
15997+ Some(MediaBitrate {
15998+ total: Some(4_998),
15999+ video: Some(113),
16000+ audio: Some(2_400),
16001+ }),
16002+ 1
16003+ ),
16004+ "5.0 kb/s · 0.11 video · 2.4 sound"
16005+ );
16006+ }
16007+
16008+ /// The invariant under the row above, over every rate a container can
16009+ /// state: a component the file *does* state never renders as a zero. The
16010+ /// probe leaves out what is unstated, so a "0.00" on this card would be it
16011+ /// saying a track that plays is silent.
16012+ #[test]
16013+ fn a_stated_rate_never_renders_as_a_zero() {
16014+ use super::MediaBitrate;
16015+ // Every decade from 1 bit a second to a 100 Mb/s master, the rounding
16016+ // edges of each unit switch, and every pair of them in one line: the
16017+ // line's unit is picked off its smallest component, so the widest
16018+ // spread is the one that could round the biggest away.
16019+ let edges: Vec<u64> = (0..12)
16020+ .flat_map(|e| {
16021+ let decade = 10_u64.pow(e);
16022+ [decade, decade * 4, decade * 5, decade * 9]
16023+ })
16024+ .chain([MB_FLOOR - 1, MB_FLOOR, 999_999, 4_998, 113, 2_400])
16025+ .collect();
16026+ for &small in &edges {
16027+ for &big in &edges {
16028+ let line = bitrate_detail(
16029+ Some(MediaBitrate {
16030+ total: Some(small.max(big)),
16031+ video: Some(big),
16032+ audio: Some(small),
16033+ }),
16034+ 2,
16035+ );
16036+ for number in line
16037+ .split(" · ")
16038+ .filter_map(|part| part.split(' ').next())
16039+ .filter_map(|n| n.parse::<f64>().ok())
16040+ {
16041+ assert!(number > 0., "{small}/{big} bits a second rendered as {line:?}");
16042+ }
16043+ }
16044+ }
16045+ }
16046+
15284 #[test]16047 #[test]
15285 fn timecode_counts_frames_inside_the_second() {16048 fn timecode_counts_frames_inside_the_second() {
15286 assert_eq!(timecode(0., 30.), "00:00:00:00");16049 assert_eq!(timecode(0., 30.), "00:00:00:00");
@@ -15734,6 +16497,18 @@ mod tests {
15734 // Before the first paint there is no bed and so no answer to give.16497 // Before the first paint there is no bed and so no answer to give.
15735 assert_eq!(span_label(0.), "—");16498 assert_eq!(span_label(0.), "—");
15736 assert_eq!(span_label(f64::NAN), "—");16499 assert_eq!(span_label(f64::NAN), "—");
16500+ // A span under a second is a span: the tightest zoom is
16501+ // `ZOOM_MIN_FRAMES` across the bed, which on 240 fps slow-motion is
16502+ // 0.03s, and "0.0s" would be the pill saying nothing is on the bed.
16503+ for fps in [60., 120., 240., 1000.] {
16504+ let label = span_label(ZOOM_MIN_FRAMES / fps);
16505+ assert_ne!(label, "0.0s", "{fps} fps");
16506+ assert_ne!(label, "0.00s", "{fps} fps");
16507+ }
16508+ assert_eq!(span_label(ZOOM_MIN_FRAMES / 240.), "0.03s");
16509+ // A frame of quiet at 60 fps, which the silence card says out loud.
16510+ assert_eq!(secs_label(1. / 60.), "0.02s");
16511+ assert_eq!(secs_label(4.5), "4.5s");
15737 }16512 }
15738 16513
15739 #[test]16514 #[test]
@@ -17366,7 +18141,11 @@ mod tests {
17366 let warmed = {18141 let warmed = {
17367 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");18142 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
17368 session.set_gain(0.0);18143 session.set_gain(0.0);
17369- read_ahead(&asset("test_av2.mp4"), &stage);18144+ let subs = read_ahead(&asset("test_av2.mp4"), &stage).expect("an mp4 is readable");
18145+ // This mp4 is walked now (an mp4 can carry `tx3g`) and has no
18146+ // subtitle track in it, so the worker hands over an empty list --
18147+ // the same thing the import lands with.
18148+ assert!(subs.is_empty());
17370 session.import(&asset("test_av2.mp4")).expect("av2 matches");18149 session.import(&asset("test_av2.mp4")).expect("av2 matches");
17371 (18150 (
17372 session.sources().to_vec(),18151 session.sources().to_vec(),
@@ -17385,7 +18164,7 @@ mod tests {
17385 // another rate is no more importable for having been read first.18164 // another rate is no more importable for having been read first.
17386 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");18165 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
17387 session.set_gain(0.0);18166 session.set_gain(0.0);
17388- read_ahead(&asset("test_25fps.mp4"), &stage);18167+ drop(read_ahead(&asset("test_25fps.mp4"), &stage));
17389 let warmed = session.import(&asset("test_25fps.mp4"));18168 let warmed = session.import(&asset("test_25fps.mp4"));
17390 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");18169 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
17391 session.set_gain(0.0);18170 session.set_gain(0.0);
@@ -17396,8 +18175,53 @@ mod tests {
17396 .map_err(|e| e.to_string())18175 .map_err(|e| e.to_string())
17397 );18176 );
17398 // A path nothing can read is the worker's business to survive, not to18177 // A path nothing can read is the worker's business to survive, not to
17399- // report: the engine says so a moment later, in its own words.18178+ // report: the engine says so a moment later, in its own words. The
17400- read_ahead(std::path::Path::new("/no/such/film.mkv"), &stage);18179+ // subtitle half *is* carried back, because nothing walks it again to
18180+ // re-word it -- and it is a refusal, not a panic.
18181+ assert!(
18182+ read_ahead(std::path::Path::new("/no/such/film.mkv"), &stage).is_err(),
18183+ "an unreadable mkv comes back as the engine's refusal"
18184+ );
18185+ }
18186+
18187+ /// The import door's two halves, split across the worker hop: what
18188+ /// [`read_ahead`] walks is exactly what the render thread would have walked,
18189+ /// and pushing it says what walking it in place used to say.
18190+ #[test]
18191+ fn an_imports_subtitles_are_read_by_the_worker_and_only_pushed_here() {
18192+ use std::sync::atomic::AtomicU8;
18193+ let stage = AtomicU8::new(ImportStage::Header as u8);
18194+ let film = asset("test_subs.mkv");
18195+ // The in-place walk (`subtitle_notice`) and the split one land the same
18196+ // tracks and the same tail on the same timeline.
18197+ let mut in_place = PlaybackSession::open(asset("test_av.mp4")).expect("open");
18198+ in_place.set_gain(0.0);
18199+ let said = subtitle_notice(&mut in_place, &film);
18200+ let mut split = PlaybackSession::open(asset("test_av.mp4")).expect("open");
18201+ split.set_gain(0.0);
18202+ let walked = read_ahead(&film, &stage).expect("the mkv is readable");
18203+ assert_eq!(subtitle_tail(&mut split, Ok(walked)), said);
18204+ assert_eq!(split.subtitles().len(), in_place.subtitles().len());
18205+ // The same file twice is still one row, and still says so: the dedupe
18206+ // lives in the push, which is the half that stayed here.
18207+ let again = read_ahead(&film, &stage).expect("the mkv is readable");
18208+ assert_eq!(subtitle_tail(&mut split, Ok(again)), None);
18209+ // A standalone `.srt` is walked by the same worker: an import of one is
18210+ // not a door that reads on the render thread either.
18211+ let srt = Path::new(env!("CARGO_MANIFEST_DIR"))
18212+ .join("../engine/tests/data/test_subs.srt")
18213+ .canonicalize()
18214+ .expect("the subtitle fixture");
18215+ assert_eq!(
18216+ read_ahead(&srt, &stage).expect("the srt is readable").len(),
18217+ 1
18218+ );
18219+ // ...and a refusal is worded as a tail, never as a failed import.
18220+ let unread: Subs = Err("nothing to read".into());
18221+ assert_eq!(
18222+ subtitle_tail(&mut split, unread),
18223+ Some(" — SUBTITLES UNREAD: nothing to read".to_string())
18224+ );
17401 }18225 }
17402 18226
17403 #[test]18227 #[test]
@@ -17666,7 +18490,7 @@ mod tests {
17666 // never a guessed seat, and no seat at all for a format with no picture.18490 // never a guessed seat, and no seat at all for a format with no picture.
17667 let tail = summary_tail(18491 let tail = summary_tail(
17668 Path::new("/a/take.export.mp4"),18492 Path::new("/a/take.export.mp4"),
17669- Some(45),18493+ Some(45_000_000),
17670 Some("VA-API"),18494 Some("VA-API"),
17671 true,18495 true,
17672 );18496 );
@@ -17680,11 +18504,26 @@ mod tests {
17680 assert!(!summary_tail(Path::new("/a/x.wav"), None, None, false).contains("MB"));18504 assert!(!summary_tail(Path::new("/a/x.wav"), None, None, false).contains("MB"));
17681 // 6 Mbps over a minute is 45 MB. `Auto` has no figure to estimate from18505 // 6 Mbps over a minute is 45 MB. `Auto` has no figure to estimate from
17682 // and an empty timeline no length: neither invents one.18506 // and an empty timeline no length: neither invents one.
17683- assert_eq!(estimated_mb(Some(6_000_000), 60.), Some(45));18507+ assert_eq!(estimated_bytes(Some(6_000_000), 60.), Some(45_000_000));
17684- assert_eq!(estimated_mb(Some(2_000_000), 90.), Some(23));18508+ assert_eq!(estimated_bytes(Some(2_000_000), 90.), Some(22_500_000));
17685- assert_eq!(estimated_mb(None, 60.), None);18509+ assert_eq!(estimated_bytes(None, 60.), None);
17686- assert_eq!(estimated_mb(Some(6_000_000), 0.), None);18510+ assert_eq!(estimated_bytes(Some(6_000_000), 0.), None);
17687- assert_eq!(estimated_mb(Some(0), 60.), None);18511+ assert_eq!(estimated_bytes(Some(0), 60.), None);
18512+ // ...and a short one is not nothing. Three seconds at the floor
18513+ // bitrate is 375 kB, which used to round to the "≈ 0 MB" this line
18514+ // exists to never say -- the shortest export a frame can make is
18515+ // still a real file with a real size.
18516+ let short = estimated_bytes(Some(1_000_000), 3.).expect("a rate and a length");
18517+ assert_eq!(size_label(short), "375 kB");
18518+ let frame = summary_tail(Path::new("/a/x.mp4"), estimated_bytes(Some(1_000_000), 1. / 60.), None, true);
18519+ assert!(
18520+ frame.contains("≈ 2 kB") && !frame.contains("0 MB") && !frame.contains("0 kB"),
18521+ "{frame}"
18522+ );
18523+ // The boundary reads in the unit that can state it, either side.
18524+ assert_eq!(size_label(999_600), "1 MB");
18525+ assert_eq!(size_label(499_000), "499 kB");
18526+ assert_eq!(size_label(1), "1 kB");
17688 }18527 }
17689 18528
17690 /// Which cue is on screen when: the whole of what the overlay decides, and18529 /// Which cue is on screen when: the whole of what the overlay decides, and
@@ -17824,14 +18663,54 @@ mod tests {
17824 #[test]18663 #[test]
17825 fn subtitles_arrive_beside_the_media_and_inside_it() {18664 fn subtitles_arrive_beside_the_media_and_inside_it() {
17826 // Which door a path goes through is decided before anything is opened.18665 // Which door a path goes through is decided before anything is opened.
17827- for name in ["subs.srt", "SUBS.SRT", "a.vtt", "a.ass", "a.ssa"] {18666+ // ...and a `.mks` is one, the subtitles of a Matroska file alone: it has
18667+ // no source in it to import, so the drop door has to send it where `+ S`
18668+ // sends it. Its two siblings are media and must not come here -- a
18669+ // `.mka` is a song this would stop importing.
18670+ for name in ["subs.srt", "SUBS.SRT", "a.vtt", "a.ass", "a.ssa", "s.mks", "S.MKS"] {
17828 assert!(is_subtitle(Path::new(name)), "{name}");18671 assert!(is_subtitle(Path::new(name)), "{name}");
17829 }18672 }
17830- for name in ["a.mp4", "a.mkv", "notes.txt", "a"] {18673+ for name in ["a.mp4", "a.mkv", "song.mka", "film.mk3d", "notes.txt", "a"] {
17831 assert!(!is_subtitle(Path::new(name)), "{name}");18674 assert!(!is_subtitle(Path::new(name)), "{name}");
17832 }18675 }
17833- assert!(is_matroska(Path::new("film.MKV")) && is_matroska(Path::new("clip.webm")));18676+ // Every container the engine can walk for tracks inside it, Matroska
17834- assert!(!is_matroska(Path::new("clip.mp4")));18677+ // and ISO-BMFF alike -- an mp4 carries `tx3g`, so the app has to ask it.
18678+ // The Matroska half is the engine's own closed set, extension for
18679+ // extension, so no file is walked here that it would refuse there.
18680+ for name in [
18681+ "film.MKV", "clip.webm", "clip.mp4", "a.m4v", "a.MOV", "song.mka", "s.mks", "f.MK3D",
18682+ ] {
18683+ assert!(carries_subtitles(Path::new(name)), "{name}");
18684+ assert!(
18685+ engine::demux::is_matroska(Path::new(name))
18686+ || matches!(
18687+ Path::new(name)
18688+ .extension()
18689+ .and_then(|e| e.to_str())
18690+ .map(str::to_ascii_lowercase)
18691+ .as_deref(),
18692+ Some("mp4" | "m4v" | "mov")
18693+ ),
18694+ "{name} is walked by the app but not by the engine"
18695+ );
18696+ }
18697+ for name in ["song.wav", "still.png", "notes.txt", "a"] {
18698+ assert!(!carries_subtitles(Path::new(name)), "{name}");
18699+ }
18700+ // The three doors, on the one file that used to split them: what the
18701+ // drop/argv door does with it ([`Player::take_import`] routes on
18702+ // `is_subtitle`), what the worker reads for it ([`walk_subtitles`]), and
18703+ // what `+ S` reads ([`Player::add_subtitles`] -> `parse_subtitles`) are
18704+ // the same walk of the same bytes.
18705+ let mks = asset("test_subs.mks");
18706+ assert!(is_subtitle(&mks), "the drop door takes it as subtitles");
18707+ let dropped = walk_subtitles(&mks).expect("the drop door's worker reads it");
18708+ let plus_s = PlaybackSession::parse_subtitles(&mks).expect("`+ S` reads it");
18709+ assert!(!dropped.is_empty(), "and there are tracks in it");
18710+ assert_eq!(
18711+ dropped.iter().map(|t| &t.label).collect::<Vec<_>>(),
18712+ plus_s.iter().map(|t| &t.label).collect::<Vec<_>>(),
18713+ );
17835 18714
17836 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");18715 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
17837 session.set_gain(0.0);18716 session.set_gain(0.0);
@@ -17886,7 +18765,8 @@ mod tests {
17886 assert_eq!(subtitle_detail(&session.subtitles()[1]), "3 cues");18765 assert_eq!(subtitle_detail(&session.subtitles()[1]), "3 cues");
17887 // The same file twice adds nothing and says nothing.18766 // The same file twice adds nothing and says nothing.
17888 assert_eq!(subtitle_notice(&mut session, &asset("test_subs.mkv")), None);18767 assert_eq!(subtitle_notice(&mut session, &asset("test_subs.mkv")), None);
17889- // A container that cannot hold them is never even read.18768+ // An mp4 is walked too (it can carry `tx3g`); this one holds none, so
18769+ // the notice grows no tail.
17890 assert_eq!(subtitle_notice(&mut session, &asset("test_av.mp4")), None);18770 assert_eq!(subtitle_notice(&mut session, &asset("test_av.mp4")), None);
17891 18771
17892 // A track that could not be read says why, where its cue count would18772 // A track that could not be read says why, where its cue count would
@@ -17895,6 +18775,11 @@ mod tests {
17895 let refused = engine::subtitle::SubtitleTrack {18775 let refused = engine::subtitle::SubtitleTrack {
17896 path: PathBuf::from("/a/remux.mkv"),18776 path: PathBuf::from("/a/remux.mkv"),
17897 track: Some(1),18777 track: Some(1),
18778+ // Neither field, like `SubtitleTrack::refused` leaves them: what is
18779+ // refused is never written, and the row keeps the label it was
18780+ // refused under.
18781+ language: String::new(),
18782+ name: String::new(),
17898 label: "eng".into(),18783 label: "eng".into(),
17899 cues: Vec::new(),18784 cues: Vec::new(),
17900 bitmap: false,18785 bitmap: false,
@@ -18432,10 +19317,19 @@ mod tests {
18432 );19317 );
18433 }19318 }
18434 19319
19320+ /// The two shapes the engine really builds: a track *of* a file states a
19321+ /// language and no title (`of_matroska`, `of_mp4`), and a standalone file
19322+ /// states no language and is its own name (`external`).
18435 fn sub(path: &str, track: Option<u64>, label: &str) -> engine::subtitle::SubtitleTrack {19323 fn sub(path: &str, track: Option<u64>, label: &str) -> engine::subtitle::SubtitleTrack {
19324+ let (language, name) = match track {
19325+ Some(_) => (label.to_string(), String::new()),
19326+ None => (String::new(), label.to_string()),
19327+ };
18436 engine::subtitle::SubtitleTrack {19328 engine::subtitle::SubtitleTrack {
18437 path: PathBuf::from(path),19329 path: PathBuf::from(path),
18438 track,19330 track,
19331+ language,
19332+ name,
18439 label: label.to_string(),19333 label: label.to_string(),
18440 cues: Vec::new(),19334 cues: Vec::new(),
18441 bitmap: false,19335 bitmap: false,
@@ -18443,6 +19337,52 @@ mod tests {
18443 }19337 }
18444 }19338 }
18445 19339
19340+ /// A film's two ASS tracks with the timeline trimmed to twenty seconds:
19341+ /// one of them still has cues there and one has none, and the card said
19342+ /// nothing whatever about the second while the Subtitles list went on
19343+ /// showing it with its eighty-three cues.
19344+ ///
19345+ /// And the 25 GB remux's thirty-five: naming those wrapped the row to ten
19346+ /// lines and pushed Destination under the fold, so past the value box's
19347+ /// three lines the same line counts instead.
19348+ #[test]
19349+ fn the_card_names_the_subtitle_it_leaves_off_and_counts_them_when_it_cannot() {
19350+ let film = "/films/a-real-h264-dual-audio-film.mkv";
19351+ let two = [
19352+ sub(film, Some(1), "[ASS]"),
19353+ sub(film, Some(2), "[ASS] [FOR DUB]"),
19354+ ];
19355+ // What the engine answers about the one pick that reached it, and what
19356+ // this side knows about the row that did not.
19357+ let named = subtitle_plan("[ASS] → embedded".to_string(), &two, &[0]);
19358+ assert_eq!(named, "[ASS] → embedded; [ASS] [FOR DUB] — no cues here");
19359+ assert!(
19360+ named.chars().count() <= SUB_PLAN_CHARS,
19361+ "two tracks fit the value box: {named}"
19362+ );
19363+ // Thirty-five off one file: twenty-two carry cues here, nine are
19364+ // pictures, one could not be read, three have nothing on this timeline.
19365+ let many: Vec<_> = (0..35)
19366+ .map(|i| {
19367+ let mut track = sub("/films/A Remux.mkv", Some(i), "eng — Subtitles");
19368+ track.bitmap = (22..31).contains(&i);
19369+ track.refused = (i == 31).then(|| "VobSub is pictures".to_string());
19370+ track
19371+ })
19372+ .collect();
19373+ // The picks are every track with a cue on the timeline: the twenty-two
19374+ // and the nine picture ones, which the engine drops itself.
19375+ let picks: Vec<usize> = (0..31usize).collect();
19376+ let counted = subtitle_plan("22 tracks → embedded (…)".to_string(), &many, &picks);
19377+ assert_eq!(counted, "22 of 35 → embedded; 9 pictures; 1 unread; 3 no cues here");
19378+ assert!(
19379+ counted.chars().count() <= SUB_PLAN_CHARS,
19380+ "thirty-five tracks still fit the value box: {counted}"
19381+ );
19382+ // Nothing on the timeline at all is still the engine's word for it.
19383+ assert_eq!(subtitle_plan("none".to_string(), &[], &[]), "none");
19384+ }
19385+
18446 /// The list is in the order tracks were added, which is not the order a19386 /// The list is in the order tracks were added, which is not the order a
18447 /// person reads it in: importing a second film puts its tracks after the19387 /// person reads it in: importing a second film puts its tracks after the
18448 /// first film's, and importing a third `.srt` for the first film puts that19388 /// first film's, and importing a third `.srt` for the first film puts that
@@ -18565,6 +19505,28 @@ mod tests {
18565 assert_eq!(groups[0].rows[1].track, 2);19505 assert_eq!(groups[0].rows[1].track, 2);
18566 }19506 }
18567 19507
19508+ /// The × on a row shifts every track after it down one, and the pick is
19509+ /// what an export writes into the file -- so a pick that stayed put would
19510+ /// silently change which track the next export carries. Every relation
19511+ /// between the pick and the row that went, on a list of three.
19512+ #[test]
19513+ fn removing_a_subtitle_row_carries_the_pick_with_it() {
19514+ // A row *before* the pick: the same track stays picked, one index down.
19515+ assert_eq!(sub_pick_after_removal(2, 0, 2), 1);
19516+ assert_eq!(sub_pick_after_removal(2, 1, 2), 1);
19517+ // A row *after* it: the pick has not moved and neither has its index.
19518+ assert_eq!(sub_pick_after_removal(0, 2, 2), 0);
19519+ assert_eq!(sub_pick_after_removal(1, 2, 2), 1);
19520+ // The picked row itself: the one that slid into its place...
19521+ assert_eq!(sub_pick_after_removal(1, 1, 2), 1);
19522+ // ...and the last row when the picked one was the last, since there is
19523+ // nothing after it to slide.
19524+ assert_eq!(sub_pick_after_removal(2, 2, 2), 1);
19525+ // The last row of all: an emptied list is legal for subtitles, and the
19526+ // section is not drawn at all at that point.
19527+ assert_eq!(sub_pick_after_removal(0, 0, 0), 0);
19528+ }
19529+
18568 /// The same claim from the click's end, on the order imports actually19530 /// The same claim from the click's end, on the order imports actually
18569 /// arrive in: two films opened one after the other and an `.srt` dropped19531 /// arrive in: two films opened one after the other and an `.srt` dropped
18570 /// last interleave in the flat list, and the display reorders them. What a19532 /// last interleave in the flat list, and the display reorders them. What a
@@ -18621,6 +19583,30 @@ mod tests {
18621 // Reaching the subtitle rows too: a track whose only name was the tag.19583 // Reaching the subtitle rows too: a track whose only name was the tag.
18622 let groups = subtitle_rows(&[sub("/films/a.mkv", Some(1), "und")]);19584 let groups = subtitle_rows(&[sub("/films/a.mkv", Some(1), "und")]);
18623 assert_eq!(groups[0].rows[0].label, "unknown language");19585 assert_eq!(groups[0].rows[0].label, "unknown language");
19586+ // The pair, read as the pair: the row title comes off `language` and
19587+ // `name` and never out of the flattened label, which is what let an
19588+ // "und" beside a title through as a language nobody speaks. A refused
19589+ // track states neither and keeps its label.
19590+ let titled = |language: &str, name: &str, label: &str| engine::subtitle::SubtitleTrack {
19591+ path: PathBuf::from("/films/a.mkv"),
19592+ track: Some(1),
19593+ language: language.into(),
19594+ name: name.into(),
19595+ label: label.into(),
19596+ cues: Vec::new(),
19597+ bitmap: false,
19598+ refused: None,
19599+ };
19600+ for (language, name, label, title) in [
19601+ ("fra", "Signs", "fra — Signs", "fra — Signs"),
19602+ ("und", "Signs", "Signs", "Signs"),
19603+ ("und", "", "und", "unknown language"),
19604+ ("", "late.srt", "late.srt", "late.srt"),
19605+ ("", "", "eng", "eng"),
19606+ ] {
19607+ let rows = subtitle_rows(&[titled(language, name, label)]);
19608+ assert_eq!(rows[0].rows[0].label, title, "{language:?} {name:?}");
19609+ }
18624 }19610 }
18625 19611
18626 /// The bug: an empty timeline is end-of-stream from its one black frame19612 /// The bug: an empty timeline is end-of-stream from its one black frame
@@ -18823,6 +19809,7 @@ fn main() {
18823 selected_asset: None,19809 selected_asset: None,
18824 waves: HashMap::new(),19810 waves: HashMap::new(),
18825 streams: HashMap::new(),19811 streams: HashMap::new(),
19812+ bitrates: HashMap::new(),
18826 sizes: HashMap::new(),19813 sizes: HashMap::new(),
18827 decoders: HashMap::new(),19814 decoders: HashMap::new(),
18828 export_seat: None,19815 export_seat: None,
crates/engine/src/demux.rsmodified+574 -32
@@ -139,6 +139,214 @@ pub struct VideoMeta {
139 pub color: ColorDescription,139 pub color: ColorDescription,
140 }140 }
141 141
142+/// What a file spends its bytes at, in bits per second -- the whole file, and
143+/// what each of its streams costs inside it.
144+///
145+/// The three are one budget split three ways, so all three are measured over
146+/// **the same seconds**: the container's own duration, not each track's. That
147+/// is what makes the line read as a breakdown -- `total` can never come out
148+/// below `video + audio`, because those are disjoint byte counts over a shared
149+/// denominator, and the leftover is the container's overhead. Dividing each
150+/// track by its own length is how a file with 2 s of picture and 60 s of sound
151+/// reports a total thirty times its real byte rate, under components that add
152+/// up to a thirtieth of it.
153+///
154+/// Every field is `None` rather than `0` wherever the container does not state
155+/// the number and nothing here derives it. A properties row a header did not
156+/// give is left out rather than shown as a zero, and a fabricated `0 kbps` is
157+/// not a missing measurement, it is a wrong one.
158+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
159+pub struct MediaBitrate {
160+ /// Every byte of the file over its playing time -- both streams, the
161+ /// container's overhead and all -- which is what "the bitrate of a file"
162+ /// means to anyone reading it, and what `ffprobe` calls `format=bit_rate`.
163+ pub total: Option<u64>,
164+ /// The picture track's own bytes over that same time.
165+ pub video: Option<u64>,
166+ /// The bytes of the **one sound track this engine would play**, over that
167+ /// same time -- first in file order, which is the rule
168+ /// [`crate::audio::AudioSession::probe_streams`] hands out stream 0 by and
169+ /// the one playback and export open. A dual-audio file has more, and this
170+ /// number describes neither their sum nor the biggest of them; ask
171+ /// `probe_streams` how many there are before calling this "the sound".
172+ pub audio: Option<u64>,
173+}
174+
175+/// What `path` is coded at, from its header and its sample table alone --
176+/// **no decoder is opened**, which is what lets a library probe run this over
177+/// every file it lists.
178+///
179+/// The cost is one [`Demuxer::open`]: an mp4's boxes, or a Matroska segment's
180+/// element headers, both of which the caller's other per-file probes already
181+/// pay. Nothing here reads a block payload.
182+///
183+/// Cheap is not instant, and the caller has to know which: measured over
184+/// `a local media folder`, every mp4 answered in single-digit milliseconds, and a
185+/// 12.9 GB 2160p AV1 Matroska took **seconds** cold and ~150 ms warm --
186+/// Matroska indexes no samples, so its open walks every cluster header in the
187+/// file, and what that costs is disk, not arithmetic. Timings on that file
188+/// swing between ~150 ms and ~1.2 s run to run on the same build, so treat any
189+/// figure here as an order of magnitude and nothing finer. This belongs on
190+/// `background_executor` like every other open, never on a repaint.
191+///
192+/// A file that will not open at all -- no video track, a codec nothing reads,
193+/// a still image, which has no playing time of its own -- comes back all
194+/// `None`. That is the answer, not an error: the cards this feeds show the
195+/// rows they have.
196+pub fn probe_bitrate(path: &Path) -> MediaBitrate {
197+ let unstated = MediaBitrate::default();
198+ let Ok(bytes) = std::fs::metadata(path).map(|m| m.len()) else {
199+ return unstated;
200+ };
201+ // A still is as long as the clip is stretched to, so there is no per-second
202+ // anything to state about the file.
203+ if crate::is_image(path) {
204+ return unstated;
205+ }
206+ // A standalone audio file's length is not a frame count; it is what the
207+ // audio header says, exactly as `PlaybackSession::import` reads it.
208+ //
209+ // ponytail: `duration_secs` falls back to a decode for a stream whose
210+ // header states no length (a bare mp3 with no Xing header), which is the
211+ // one input here that is not header-only -- ~0.5 ms per source second, the
212+ // same cost import already pays for that file. Upgrade path is a
213+ // header-only variant that answers `None` instead of decoding.
214+ if crate::is_audio(path) {
215+ let Ok(Some(secs)) = crate::AudioSession::duration_secs(path) else {
216+ return unstated;
217+ };
218+ let total = bits_per_second(bytes, secs);
219+ // One stream and nothing else in the file: what a second of it costs is
220+ // what a second of its sound costs, give or take a header.
221+ return MediaBitrate {
222+ total,
223+ video: None,
224+ audio: total,
225+ };
226+ }
227+ let Ok((meta, demuxer)) = Demuxer::open(path) else {
228+ return unstated;
229+ };
230+ // How long the *file* plays, which on a well-made file is how long its
231+ // picture plays and on a badly-made one is not: a 2 s clip carrying a 60 s
232+ // commentary is 60 s of file, and dividing its bytes by 2 claims thirty
233+ // times the byte rate it really has. Both containers state this outright --
234+ // an mp4 in the `mvhd` (the movie header, which spans every track), a
235+ // Matroska in `Info.Duration` -- so it is read rather than derived.
236+ //
237+ // Where a file states none, the picture's own length is the fallback and
238+ // the old answer: frame count over frame rate, the same length the timeline
239+ // lays the clip out at.
240+ let stated = match &demuxer {
241+ Demuxer::Mkv(d) => d.container_secs,
242+ Demuxer::Mp4(d) => {
243+ let mvhd = &d.reader.moov.mvhd;
244+ (mvhd.timescale > 0 && mvhd.duration > 0)
245+ .then(|| mvhd.duration as f64 / f64::from(mvhd.timescale))
246+ }
247+ };
248+ let secs = stated.unwrap_or(match meta.frame_rate > 0.0 {
249+ true => f64::from(meta.frame_count) / meta.frame_rate,
250+ false => 0.0,
251+ });
252+ let (video, audio) = match &demuxer {
253+ // Matroska indexes no samples, so what the open's one walk counted *is*
254+ // the sample table: block bytes per track number ([`mkv_blocks`]), the
255+ // sound's beside the picture's, neither of them costing a second pass.
256+ Demuxer::Mkv(d) => {
257+ let bytes_of = |number| {
258+ d.track_bytes
259+ .iter()
260+ .find(|(n, _)| *n == number)
261+ .map(|&(_, bytes)| bytes)
262+ };
263+ (
264+ // The picture's blocks are indexed, so its size is that index.
265+ // Measured, this is the same number `track_bytes` holds for the
266+ // same track on every fixture and every file in `a local media folder`;
267+ // the two can only part on a *laced* video track, where one
268+ // block becomes several `Block`s over the frame bytes alone and
269+ // the lace header is left out. Nothing here has ever produced
270+ // one -- lacing is a sound-track trick -- so this is a
271+ // difference of principle, not one anything has exercised.
272+ bits_per_second(d.blocks.iter().map(|b| b.len as u64).sum(), secs),
273+ // The sound's, from the raw block lengths, lace headers
274+ // included: the two components are measured on slightly
275+ // different bases for that reason, which is worth tens of bytes
276+ // a block and nothing on the rate.
277+ d.audio_number
278+ .and_then(bytes_of)
279+ .and_then(|bytes| bits_per_second(bytes, secs)),
280+ )
281+ }
282+ Demuxer::Mp4(d) => {
283+ let tracks = d.reader.tracks();
284+ // In file order, out of `moov.traks`, for [`Mp4Demuxer::open`]'s
285+ // reason and for `audio::audio_track_ids`': `tracks()` is a
286+ // `HashMap`, so "the audio track" of a dual-audio file would
287+ // otherwise be a different one per run. Deliberately the *same*
288+ // first-in-file rule the audio path picks stream 0 by, so the
289+ // bitrate row and the audio row of one card name one track -- see
290+ // [`MediaBitrate::audio`], which says what that number is not.
291+ let audio = d
292+ .reader
293+ .moov
294+ .traks
295+ .iter()
296+ .map(|trak| trak.tkhd.track_id)
297+ .find(|id| {
298+ tracks
299+ .get(id)
300+ .is_some_and(|t| matches!(t.track_type(), Ok(TrackType::Audio)))
301+ });
302+ let rate = |id| {
303+ tracks
304+ .get(id)
305+ .map(mp4_track_bytes)
306+ .and_then(|bytes| bits_per_second(bytes, secs))
307+ };
308+ (rate(&d.track_id), audio.as_ref().and_then(rate))
309+ }
310+ };
311+ MediaBitrate {
312+ total: bits_per_second(bytes, secs),
313+ video,
314+ audio,
315+ }
316+}
317+
318+/// `bytes` over `secs`, in bits per second, or `None` where that is not a
319+/// number worth showing: nothing measured either side, or a rate that rounds to
320+/// zero. A `0` here would read as a real measurement, which is the one answer
321+/// this must never give.
322+fn bits_per_second(bytes: u64, secs: f64) -> Option<u64> {
323+ (secs > 0.0)
324+ .then(|| (bytes as f64 * 8.0 / secs) as u64)
325+ .filter(|&bps| bps > 0)
326+}
327+
328+/// How many bytes of the file an mp4 track's samples are -- its share of the
329+/// `mdat`, which over the container's seconds is its share of the byte rate.
330+///
331+/// Not `Mp4Track::bitrate`, deliberately, though that looks like the ready-made
332+/// answer. It divides by the track's *own* duration, which is the arithmetic
333+/// [`MediaBitrate`] exists to not do; it truncates that duration to whole
334+/// seconds (`mp4-0.14.0/src/track.rs:213`), so a file under a second comes back
335+/// `0`; and for an `mp4a` track it answers `esds.avg_bitrate` instead, a number
336+/// the encoder declared rather than one the file spends, which is `0` on any
337+/// `esds` that declared none. Bytes are what all three of these fields agree to
338+/// be measured in.
339+///
340+/// `Mp4Track::total_sample_size` is private to that crate; this is it, off the
341+/// `stsz` fields that are not.
342+fn mp4_track_bytes(track: &Mp4Track) -> u64 {
343+ let stsz = &track.trak.mdia.minf.stbl.stsz;
344+ match stsz.sample_size {
345+ 0 => stsz.sample_sizes.iter().map(|&n| u64::from(n)).sum(),
346+ uniform => u64::from(uniform) * u64::from(track.sample_count()),
347+ }
348+}
349+
142 /// The file, whichever container it came in. Which one is decided by the350 /// The file, whichever container it came in. Which one is decided by the
143 /// extension at [`Demuxer::open`] and never again: everything downstream --351 /// extension at [`Demuxer::open`] and never again: everything downstream --
144 /// playback, export, the plugin -- speaks access units and display frames.352 /// playback, export, the plugin -- speaks access units and display frames.
@@ -279,10 +487,18 @@ impl Demuxer {
279 /// the demuxer is what really decides, but the audio path has to know before it487 /// the demuxer is what really decides, but the audio path has to know before it
280 /// opens anything that this file's sound is read by symphonia's `mkv` reader488 /// opens anything that this file's sound is read by symphonia's `mkv` reader
281 /// and not by either mp4 one (see [`crate::audio::Track::open`]).489 /// and not by either mp4 one (see [`crate::audio::Track::open`]).
490+///
491+/// *Every* extension Matroska states, not the two that carry a film: `.mka` is
492+/// the sound alone and `.mks` the subtitles alone -- the same bytes, the same
493+/// reader, so refusing them was this engine refusing a file it parses. The set
494+/// is the standard's own and closed by it.
282 pub fn is_matroska(path: &Path) -> bool {495 pub fn is_matroska(path: &Path) -> bool {
283- path.extension()496+ path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
284- .and_then(|e| e.to_str())497+ matches!(
285- .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "mkv" | "webm"))498+ e.to_ascii_lowercase().as_str(),
499+ "mkv" | "mka" | "mks" | "mk3d" | "webm"
500+ )
501+ })
286 }502 }
287 503
288 pub struct Mp4Demuxer {504 pub struct Mp4Demuxer {
@@ -553,6 +769,18 @@ pub struct MkvDemuxer {
553 /// What the track's `ContentEncodings` asks of every block; [`Unpack::None`]769 /// What the track's `ContentEncodings` asks of every block; [`Unpack::None`]
554 /// for a file that declares none, which is most of them.770 /// for a file that declares none, which is most of them.
555 unpack: Unpack,771 unpack: Unpack,
772+ /// Block bytes per `TrackNumber`, counted by the one walk the open already
773+ /// does -- the sound track's as well as the picture's. [`probe_bitrate`] is
774+ /// the only reader; see [`mkv_blocks`] for why it is collected here rather
775+ /// than by a pass of its own.
776+ track_bytes: Vec<(u64, u64)>,
777+ /// `TrackNumber` of the file's first audio track, the one
778+ /// [`matroska_audio_codec`] also answers for; `None` for a silent file.
779+ audio_number: Option<u64>,
780+ /// What `Info.Duration` says the whole *file* plays for, in seconds --
781+ /// which is not the picture's length on a file whose sound outlasts it.
782+ /// `None` for the rare file that states none. [`probe_bitrate`] only.
783+ container_secs: Option<f64>,
556 }784 }
557 785
558 impl MkvDemuxer {786 impl MkvDemuxer {
@@ -560,7 +788,7 @@ impl MkvDemuxer {
560 let mut file = File::open(path)?;788 let mut file = File::open(path)?;
561 let end = file.metadata()?.len();789 let end = file.metadata()?.len();
562 let segment = mkv_segment(&mut file, end)?;790 let segment = mkv_segment(&mut file, end)?;
563- let (video, _, other, _) = mkv_tracks(&mut file, segment)?;791+ let (video, audio, other, _, container_secs) = mkv_tracks(&mut file, segment)?;
564 let video = match video {792 let video = match video {
565 Some(video) => video,793 Some(video) => video,
566 // Named, because "no video track" is a lie about a file that has one794 // Named, because "no video track" is a lie about a file that has one
@@ -587,7 +815,7 @@ impl MkvDemuxer {
587 if let Unpack::Refused(why) = &video.unpack {815 if let Unpack::Refused(why) = &video.unpack {
588 return Err(why.clone().into());816 return Err(why.clone().into());
589 }817 }
590- let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?;818+ let (blocks, span, track_bytes) = mkv_blocks(&mut file, segment, video.number)?;
591 if blocks.is_empty() {819 if blocks.is_empty() {
592 return Err(format!(820 return Err(format!(
593 "the {} track in this Matroska file has no frames",821 "the {} track in this Matroska file has no frames",
@@ -646,6 +874,9 @@ impl MkvDemuxer {
646 scratch: Vec::new(),874 scratch: Vec::new(),
647 next: 0,875 next: 0,
648 unpack: video.unpack,876 unpack: video.unpack,
877+ track_bytes,
878+ audio_number: audio.first().map(|t| t.number),
879+ container_secs,
649 },880 },
650 ))881 ))
651 }882 }
@@ -783,7 +1014,7 @@ impl MkvAudio {
783 let mut file = File::open(path)?;1014 let mut file = File::open(path)?;
784 let end = file.metadata()?.len();1015 let end = file.metadata()?.len();
785 let segment = mkv_segment(&mut file, end)?;1016 let segment = mkv_segment(&mut file, end)?;
786- let (_, audio, _, timestamp_scale) = mkv_tracks(&mut file, segment)?;1017+ let (_, audio, _, timestamp_scale, _) = mkv_tracks(&mut file, segment)?;
787 let Some(MkvAudioTrack {1018 let Some(MkvAudioTrack {
788 number,1019 number,
789 codec,1020 codec,
@@ -807,7 +1038,7 @@ impl MkvAudio {
807 if let Unpack::Refused(why) = &unpack {1038 if let Unpack::Refused(why) = &unpack {
808 return Err(why.clone().into());1039 return Err(why.clone().into());
809 }1040 }
810- let (blocks, _) = mkv_blocks(&mut file, segment, number)?;1041+ let (blocks, _, _) = mkv_blocks(&mut file, segment, number)?;
811 if blocks.is_empty() {1042 if blocks.is_empty() {
812 return Err("the AC-3 track in this Matroska file has no blocks".into());1043 return Err("the AC-3 track in this Matroska file has no blocks".into());
813 }1044 }
@@ -992,6 +1223,7 @@ fn mkv_content_encoding(file: &mut File, body: u64, end: u64) -> crate::Result<U
992 const SEGMENT: u32 = 0x1853_8067;1223 const SEGMENT: u32 = 0x1853_8067;
993 const INFO: u32 = 0x1549_A966;1224 const INFO: u32 = 0x1549_A966;
994 const TIMESTAMP_SCALE: u32 = 0x2AD7B1;1225 const TIMESTAMP_SCALE: u32 = 0x2AD7B1;
1226+const DURATION: u32 = 0x4489;
995 const TRACKS: u32 = 0x1654_AE6B;1227 const TRACKS: u32 = 0x1654_AE6B;
996 const TRACK_ENTRY: u32 = 0xAE;1228 const TRACK_ENTRY: u32 = 0xAE;
997 const TRACK_NUMBER: u32 = 0xD7;1229 const TRACK_NUMBER: u32 = 0xD7;
@@ -1019,6 +1251,10 @@ const MASTERING_METADATA: u32 = 0x55D0;
1019 const LUMINANCE_MAX: u32 = 0x55D9;1251 const LUMINANCE_MAX: u32 = 0x55D9;
1020 const LUMINANCE_MIN: u32 = 0x55DA;1252 const LUMINANCE_MIN: u32 = 0x55DA;
1021 const TRACK_LANGUAGE: u32 = 0x22B59C;1253 const TRACK_LANGUAGE: u32 = 0x22B59C;
1254+/// What a modern muxer states a language with instead ([`mkv_language`]): the
1255+/// legacy element above holds an ISO 639-2 code and nothing else, this one a
1256+/// whole BCP-47 tag (`en`, `pt-BR`, `zh-Hans`).
1257+const TRACK_LANGUAGE_BCP47: u32 = 0x22B59D;
1022 const TRACK_NAME: u32 = 0x536E;1258 const TRACK_NAME: u32 = 0x536E;
1023 const CONTENT_ENCODINGS: u32 = 0x6D80;1259 const CONTENT_ENCODINGS: u32 = 0x6D80;
1024 const CONTENT_ENCODING: u32 = 0x6240;1260 const CONTENT_ENCODING: u32 = 0x6240;
@@ -1058,10 +1294,21 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> {
1058 fn mkv_tracks(1294 fn mkv_tracks(
1059 file: &mut File,1295 file: &mut File,
1060 segment: (u64, u64),1296 segment: (u64, u64),
1061-) -> crate::Result<(Option<MkvVideo>, Vec<MkvAudioTrack>, Option<String>, u64)> {1297+) -> crate::Result<(
1298+ Option<MkvVideo>,
1299+ Vec<MkvAudioTrack>,
1300+ Option<String>,
1301+ u64,
1302+ Option<f64>,
1303+)> {
1062 let (mut video, mut other) = (None, None);1304 let (mut video, mut other) = (None, None);
1063 let mut audio = Vec::new();1305 let mut audio = Vec::new();
1064 let mut timestamp_scale = 1_000_000;1306 let mut timestamp_scale = 1_000_000;
1307+ // `Info.Duration`, in `TimestampScale` ticks: how long the *file* is, which
1308+ // is not how long its picture is -- see [`probe_bitrate`], which divides by
1309+ // this. Written by every muxer in practice and optional by the spec, so the
1310+ // absence of it is a `None` and not a zero.
1311+ let mut duration = None;
1065 let mut at = segment.0;1312 let mut at = segment.0;
1066 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {1313 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
1067 match id {1314 match id {
@@ -1069,8 +1316,10 @@ fn mkv_tracks(
1069 INFO => {1316 INFO => {
1070 let mut at = body;1317 let mut at = body;
1071 while let Some(e) = ebml_element(file, at, stop)? {1318 while let Some(e) = ebml_element(file, at, stop)? {
1072- if e.0 == TIMESTAMP_SCALE {1319+ match e.0 {
1073- timestamp_scale = ebml_uint(file, e.1, e.2)?.max(1);1320+ TIMESTAMP_SCALE => timestamp_scale = ebml_uint(file, e.1, e.2)?.max(1),
1321+ DURATION => duration = Some(ebml_float(file, e.1, e.2)?),
1322+ _ => {}
1074 }1323 }
1075 at = e.2;1324 at = e.2;
1076 }1325 }
@@ -1097,7 +1346,9 @@ fn mkv_tracks(
1097 }1346 }
1098 at = stop;1347 at = stop;
1099 }1348 }
1100- Ok((video, audio, other, timestamp_scale))1349+ // Ticks to seconds: `TimestampScale` is nanoseconds a tick is worth.
1350+ let secs = duration.filter(|d| *d > 0.0).map(|d| d * timestamp_scale as f64 / 1e9);
1351+ Ok((video, audio, other, timestamp_scale, secs))
1101 }1352 }
1102 1353
1103 /// What one `TrackEntry` turned out to be.1354 /// What one `TrackEntry` turned out to be.
@@ -1110,6 +1361,107 @@ enum MkvEntry {
1110 Other,1361 Other,
1111 }1362 }
1112 1363
1364+/// What language a `TrackEntry` states, as the three-letter ISO 639-2 code the
1365+/// rest of this engine speaks -- the one the muxer writes back into
1366+/// `TRACK_LANGUAGE` and the one an mp4's `mdhd` packs into 16 bits.
1367+///
1368+/// **`LanguageBCP47` wins**, which is the spec's own precedence and not a
1369+/// preference: a modern file states its languages there and leaves the legacy
1370+/// element out, so reading only the old one lost them. A
1371+/// dual-language remux carries 37 `LanguageBCP47` elements against 33 legacy
1372+/// ones and every English track of it is BCP-47 only -- they all used to come in
1373+/// as `und` and export with no language at all.
1374+///
1375+/// A tag is cut to its primary subtag and mapped by [`ISO_639_1_TO_2`], so `en`
1376+/// and `en-US` are both `eng`: the region is not the language, and neither the
1377+/// Matroska element nor the mp4 field can hold one. Three letters already
1378+/// (`fil`, and every ISO 639-3 tag) are kept as they are. Anything else -- a
1379+/// private `x-…` tag, a tag nothing maps -- falls back to the legacy element
1380+/// rather than throwing the file's word away.
1381+///
1382+/// `und` for a track that states neither. The spec's *default* is `eng`
1383+/// (measured: ffmpeg 8.1.2 reports `eng` for a `TrackEntry` with no `Language`
1384+/// element, and reads no `LanguageBCP47` at all), but writing English into a
1385+/// track whose file never said so is this engine's claim and not the file's --
1386+/// a Japanese film's untitled track would export labelled English. What is
1387+/// *stated* is kept; the default is left to the readers that want it.
1388+fn mkv_language(legacy: &str, bcp47: &str) -> String {
1389+ let primary = bcp47
1390+ .split('-')
1391+ .next()
1392+ .unwrap_or_default()
1393+ .to_ascii_lowercase();
1394+ let mapped = match primary.len() {
1395+ 2 => ISO_639_1_TO_2
1396+ .iter()
1397+ .find(|(two, _)| *two == primary)
1398+ .map(|(_, three)| (*three).to_owned()),
1399+ 3 => Some(primary),
1400+ _ => None,
1401+ };
1402+ match mapped {
1403+ Some(code) => code,
1404+ None if !legacy.is_empty() => legacy.to_owned(),
1405+ None => "und".into(),
1406+ }
1407+}
1408+
1409+/// Every ISO 639-1 code and the 639-2 (terminology) one it names the same
1410+/// language with -- what [`mkv_language`] maps a BCP-47 primary subtag through.
1411+///
1412+/// The whole standard and not the languages a test happened to use: generated
1413+/// from `iso-codes`' own `iso_639-2.json`, so a Kannada track is as readable as
1414+/// an English one.
1415+#[rustfmt::skip]
1416+const ISO_639_1_TO_2: &[(&str, &str)] = &[
1417+ ("aa", "aar"), ("ab", "abk"), ("ae", "ave"), ("af", "afr"),
1418+ ("ak", "aka"), ("am", "amh"), ("an", "arg"), ("ar", "ara"),
1419+ ("as", "asm"), ("av", "ava"), ("ay", "aym"), ("az", "aze"),
1420+ ("ba", "bak"), ("be", "bel"), ("bg", "bul"), ("bi", "bis"),
1421+ ("bm", "bam"), ("bn", "ben"), ("bo", "bod"), ("br", "bre"),
1422+ ("bs", "bos"), ("ca", "cat"), ("ce", "che"), ("ch", "cha"),
1423+ ("co", "cos"), ("cr", "cre"), ("cs", "ces"), ("cu", "chu"),
1424+ ("cv", "chv"), ("cy", "cym"), ("da", "dan"), ("de", "deu"),
1425+ ("dv", "div"), ("dz", "dzo"), ("ee", "ewe"), ("el", "ell"),
1426+ ("en", "eng"), ("eo", "epo"), ("es", "spa"), ("et", "est"),
1427+ ("eu", "eus"), ("fa", "fas"), ("ff", "ful"), ("fi", "fin"),
1428+ ("fj", "fij"), ("fo", "fao"), ("fr", "fra"), ("fy", "fry"),
1429+ ("ga", "gle"), ("gd", "gla"), ("gl", "glg"), ("gn", "grn"),
1430+ ("gu", "guj"), ("gv", "glv"), ("ha", "hau"), ("he", "heb"),
1431+ ("hi", "hin"), ("ho", "hmo"), ("hr", "hrv"), ("ht", "hat"),
1432+ ("hu", "hun"), ("hy", "hye"), ("hz", "her"), ("ia", "ina"),
1433+ ("id", "ind"), ("ie", "ile"), ("ig", "ibo"), ("ii", "iii"),
1434+ ("ik", "ipk"), ("io", "ido"), ("is", "isl"), ("it", "ita"),
1435+ ("iu", "iku"), ("ja", "jpn"), ("jv", "jav"), ("ka", "kat"),
1436+ ("kg", "kon"), ("ki", "kik"), ("kj", "kua"), ("kk", "kaz"),
1437+ ("kl", "kal"), ("km", "khm"), ("kn", "kan"), ("ko", "kor"),
1438+ ("kr", "kau"), ("ks", "kas"), ("ku", "kur"), ("kv", "kom"),
1439+ ("kw", "cor"), ("ky", "kir"), ("la", "lat"), ("lb", "ltz"),
1440+ ("lg", "lug"), ("li", "lim"), ("ln", "lin"), ("lo", "lao"),
1441+ ("lt", "lit"), ("lu", "lub"), ("lv", "lav"), ("mg", "mlg"),
1442+ ("mh", "mah"), ("mi", "mri"), ("mk", "mkd"), ("ml", "mal"),
1443+ ("mn", "mon"), ("mr", "mar"), ("ms", "msa"), ("mt", "mlt"),
1444+ ("my", "mya"), ("na", "nau"), ("nb", "nob"), ("nd", "nde"),
1445+ ("ne", "nep"), ("ng", "ndo"), ("nl", "nld"), ("nn", "nno"),
1446+ ("no", "nor"), ("nr", "nbl"), ("nv", "nav"), ("ny", "nya"),
1447+ ("oc", "oci"), ("oj", "oji"), ("om", "orm"), ("or", "ori"),
1448+ ("os", "oss"), ("pa", "pan"), ("pi", "pli"), ("pl", "pol"),
1449+ ("ps", "pus"), ("pt", "por"), ("qu", "que"), ("rm", "roh"),
1450+ ("rn", "run"), ("ro", "ron"), ("ru", "rus"), ("rw", "kin"),
1451+ ("sa", "san"), ("sc", "srd"), ("sd", "snd"), ("se", "sme"),
1452+ ("sg", "sag"), ("si", "sin"), ("sk", "slk"), ("sl", "slv"),
1453+ ("sm", "smo"), ("sn", "sna"), ("so", "som"), ("sq", "sqi"),
1454+ ("sr", "srp"), ("ss", "ssw"), ("st", "sot"), ("su", "sun"),
1455+ ("sv", "swe"), ("sw", "swa"), ("ta", "tam"), ("te", "tel"),
1456+ ("tg", "tgk"), ("th", "tha"), ("ti", "tir"), ("tk", "tuk"),
1457+ ("tl", "tgl"), ("tn", "tsn"), ("to", "ton"), ("tr", "tur"),
1458+ ("ts", "tso"), ("tt", "tat"), ("tw", "twi"), ("ty", "tah"),
1459+ ("ug", "uig"), ("uk", "ukr"), ("ur", "urd"), ("uz", "uzb"),
1460+ ("ve", "ven"), ("vi", "vie"), ("vo", "vol"), ("wa", "wln"),
1461+ ("wo", "wol"), ("xh", "xho"), ("yi", "yid"), ("yo", "yor"),
1462+ ("za", "zha"), ("zh", "zho"), ("zu", "zul"),
1463+];
1464+
1113 /// One `TrackEntry`, read for what it is.1465 /// One `TrackEntry`, read for what it is.
1114 fn mkv_track_entry(1466 fn mkv_track_entry(
1115 file: &mut File,1467 file: &mut File,
@@ -1119,7 +1471,7 @@ fn mkv_track_entry(
1119 ) -> crate::Result<MkvEntry> {1471 ) -> crate::Result<MkvEntry> {
1120 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);1472 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
1121 let (mut width, mut height, mut config) = (0, 0, Vec::new());1473 let (mut width, mut height, mut config) = (0, 0, Vec::new());
1122- let (mut language, mut name) = (String::new(), String::new());1474+ let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new());
1123 let mut tags = Tags::default();1475 let mut tags = Tags::default();
1124 let mut light = ContentLight::default();1476 let mut light = ContentLight::default();
1125 let mut unpack = Unpack::None;1477 let mut unpack = Unpack::None;
@@ -1130,6 +1482,7 @@ fn mkv_track_entry(
1130 CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?,1482 CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?,
1131 TRACK_TYPE => kind = ebml_uint(file, body, stop)?,1483 TRACK_TYPE => kind = ebml_uint(file, body, stop)?,
1132 TRACK_LANGUAGE => language = string_of(file, body, stop)?,1484 TRACK_LANGUAGE => language = string_of(file, body, stop)?,
1485+ TRACK_LANGUAGE_BCP47 => bcp47 = string_of(file, body, stop)?,
1133 TRACK_NAME => name = string_of(file, body, stop)?,1486 TRACK_NAME => name = string_of(file, body, stop)?,
1134 DEFAULT_DURATION => {1487 DEFAULT_DURATION => {
1135 default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0)1488 default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0)
@@ -1214,13 +1567,10 @@ fn mkv_track_entry(
1214 return Ok(MkvEntry::Audio(MkvAudioTrack {1567 return Ok(MkvEntry::Audio(MkvAudioTrack {
1215 number,1568 number,
1216 codec,1569 codec,
1217- // What a `TrackEntry` without a `Language` element means, by spec --1570+ // Whichever element the file states it in, and `und` for one that
1218- // the same default the subtitle walk applies.1571+ // states neither ([`mkv_language`]) -- the same answer the subtitle
1219- language: if language.is_empty() {1572+ // walk gets, so a dual-audio remux and its subtitles agree.
1220- "und".into()1573+ language: mkv_language(&language, &bcp47),
1221- } else {
1222- language
1223- },
1224 name,1574 name,
1225 unpack,1575 unpack,
1226 }));1576 }));
@@ -1440,7 +1790,14 @@ fn vp9_bit_depth(au: &[u8]) -> crate::Result<Option<u8>> {
1440 1790
1441 /// Every block of track `number`, in storage order, with the presentation span1791 /// Every block of track `number`, in storage order, with the presentation span
1442 /// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback1792 /// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback
1443-/// needs.1793+/// needs -- and, third, how many block bytes *every* track of the file spends,
1794+/// `(TrackNumber, bytes)` in first-seen order.
1795+///
1796+/// That third answer is why this is one pass and not two: a block's length is
1797+/// already parsed out of its header here, on the way to deciding it belongs to
1798+/// another track and skipping it, so the sound track's size costs a lookup in a
1799+/// list of two or three rather than a second walk of the segment (six seconds of
1800+/// one, on a 12 GB film). [`probe_bitrate`] is what reads it.
1444 ///1801 ///
1445 /// Only element headers are read: a block's payload is seeked over and fetched1802 /// Only element headers are read: a block's payload is seeked over and fetched
1446 /// later by [`MkvDemuxer::next_access_unit`], which is what keeps this an index1803 /// later by [`MkvDemuxer::next_access_unit`], which is what keeps this an index
@@ -1449,8 +1806,11 @@ fn mkv_blocks(
1449 file: &mut File,1806 file: &mut File,
1450 segment: (u64, u64),1807 segment: (u64, u64),
1451 number: u64,1808 number: u64,
1452-) -> crate::Result<(Vec<Block>, Option<(i64, i64)>)> {1809+) -> crate::Result<(Vec<Block>, Option<(i64, i64)>, Vec<(u64, u64)>)> {
1453 let mut blocks = Vec::new();1810 let mut blocks = Vec::new();
1811+ // A file has a handful of tracks, so this is a shorter linear scan than a
1812+ // hash would be a hash.
1813+ let mut track_bytes: Vec<(u64, u64)> = Vec::new();
1454 // Where each laced block's frames landed, so their timestamps can be spread1814 // Where each laced block's frames landed, so their timestamps can be spread
1455 // once the block after is known -- see the fixup below.1815 // once the block after is known -- see the fixup below.
1456 let mut laced: Vec<(usize, usize)> = Vec::new();1816 let mut laced: Vec<(usize, usize)> = Vec::new();
@@ -1495,6 +1855,14 @@ fn mkv_blocks(
1495 }1855 }
1496 _ => continue,1856 _ => continue,
1497 };1857 };
1858+ // Before the track filter, so this counts the whole file: the block
1859+ // as it sits on disk, lace header included, which is what that track
1860+ // costs the container. No read is added -- `len` came out of the
1861+ // header that was parsed to get here.
1862+ match track_bytes.iter_mut().find(|(n, _)| *n == block.number) {
1863+ Some((_, bytes)) => *bytes += block.len as u64,
1864+ None => track_bytes.push((block.number, block.len as u64)),
1865+ }
1498 if block.number != number {1866 if block.number != number {
1499 continue;1867 continue;
1500 }1868 }
@@ -1548,7 +1916,7 @@ fn mkv_blocks(
1548 .map(|b| b.ts)1916 .map(|b| b.ts)
1549 .min()1917 .min()
1550 .zip(blocks.iter().map(|b| b.ts).max());1918 .zip(blocks.iter().map(|b| b.ts).max());
1551- Ok((blocks, span))1919+ Ok((blocks, span, track_bytes))
1552 }1920 }
1553 1921
1554 /// The frames inside a laced block: one `(offset, length)` each, in order.1922 /// The frames inside a laced block: one `(offset, length)` each, in order.
@@ -2127,10 +2495,9 @@ pub struct MkvCue {
2127 /// display sets, read by [`crate::subtitle`] as [`MkvCue`]s like any other.2495 /// display sets, read by [`crate::subtitle`] as [`MkvCue`]s like any other.
2128 pub const PGS: &str = "S_HDMV/PGS";2496 pub const PGS: &str = "S_HDMV/PGS";
2129 2497
2130-/// The subtitle tracks of a Matroska file, in file order. An mp4's are not read2498+/// The subtitle tracks of a Matroska file, in file order. An mp4's are a
2131-/// (its `tx3g` is a different beast, and no file this project opens carries2499+/// different beast and are read by [`mp4_subtitles`]; anything that is not a
2132-/// one); anything that is not a Matroska file at all is an error, as it is for2500+/// Matroska file at all is an error, as it is for [`matroska_audio_codec`].
2133-/// [`matroska_audio_codec`].
2134 ///2501 ///
2135 /// Two passes at most: the header walk stops at the first `Cluster`, and the2502 /// Two passes at most: the header walk stops at the first `Cluster`, and the
2136 /// cue pass runs only when there is a text track to fill.2503 /// cue pass runs only when there is a text track to fill.
@@ -2178,11 +2545,133 @@ pub fn matroska_subtitles(path: &Path) -> crate::Result<Vec<MkvSubtitle>> {
2178 Ok(tracks)2545 Ok(tracks)
2179 }2546 }
2180 2547
2548+/// One timed-text subtitle track of an mp4 -- the `tx3g` sample entry ffmpeg
2549+/// calls `mov_text` -- exactly as its `trak` declares it. The mp4 half of
2550+/// [`MkvSubtitle`]: what the samples *mean* is [`crate::subtitle`]'s business,
2551+/// this is the walk.
2552+#[derive(Debug)]
2553+pub struct Mp4Subtitle {
2554+ /// The `tkhd` track id, which is what a `.edith` row names the track by.
2555+ pub number: u64,
2556+ /// The `mdhd` language, ISO-639-2. `und` where the file states none, which
2557+ /// is the only thing that field can say -- an mp4 packs three letters into
2558+ /// sixteen bits and cannot leave them out.
2559+ pub language: String,
2560+ /// `trak/udta/name`, the title a muxer wrote (`Signs`), empty for the far
2561+ /// more common track that has none. The box ffmpeg reads and writes a
2562+ /// `-metadata:s:s:0 title=` in, and the one [`crate::mux`] patches in.
2563+ pub name: String,
2564+ /// Every sample of the track, in storage order.
2565+ pub samples: Vec<Mp4TextSample>,
2566+}
2567+
2568+/// One timed-text sample: when it shows, when it stops, and the bytes.
2569+#[derive(Debug)]
2570+pub struct Mp4TextSample {
2571+ /// Microseconds from the start of the file -- the sample's decode time
2572+ /// scaled by the track's own `mdhd` timescale, which is milliseconds in
2573+ /// what this project writes and microseconds in what ffmpeg writes.
2574+ pub start_us: i64,
2575+ /// Where the next sample begins: a timed-text track states one sample per
2576+ /// instant and leaves no holes, so this is the sample's `stts` duration on
2577+ /// top of its start and not a guess ([`crate::subtitle`]'s Matroska side
2578+ /// has to guess -- see `end_of` there).
2579+ pub end_us: i64,
2580+ /// ISO/IEC 14496-17: the text's length in 16 bits, then the UTF-8 itself.
2581+ /// A payload of `00 00` is a sample of *no text*, which is the stretch
2582+ /// between two cues rather than a cue with nothing in it.
2583+ pub payload: Vec<u8>,
2584+}
2585+
2586+/// The timed-text subtitle tracks of an mp4, in track-id order -- the reader
2587+/// that makes an mp4 export of this project's own openable again, and reads a
2588+/// `mov_text` track ffmpeg muxed just the same.
2589+///
2590+/// The samples come out of the `mp4` crate, which walks `stts`/`stsz`/`stco`
2591+/// for any track type; the *title* does not, because that crate's `TrakBox` has
2592+/// no `udta` field at all -- so the one box carrying it is read by hand out of
2593+/// the `moov`, the way [`sample_entry`] reads an `stsd` entry the crate drops.
2594+///
2595+/// A file with no timed-text track comes back empty, never an error; a file that
2596+/// is not an mp4 at all is an error, as [`matroska_subtitles`] is for a
2597+/// non-Matroska.
2598+pub fn mp4_subtitles(path: &Path) -> crate::Result<Vec<Mp4Subtitle>> {
2599+ let file = File::open(path)?;
2600+ let size = file.metadata()?.len();
2601+ let mut reader = Mp4Reader::read_header(BufReader::new(file), size)?;
2602+ let mut ids: Vec<u32> = reader
2603+ .tracks()
2604+ .iter()
2605+ .filter(|(_, track)| matches!(track.track_type(), Ok(TrackType::Subtitle)))
2606+ .map(|(id, _)| *id)
2607+ .collect();
2608+ // By track id, which is the order the tracks were written in: a `HashMap`
2609+ // hands them over in whatever order it likes, and a row picks a track by
2610+ // its number out of a list a user saw.
2611+ ids.sort_unstable();
2612+ let names = mp4_track_names(path)?;
2613+ let mut tracks = Vec::with_capacity(ids.len());
2614+ for id in ids {
2615+ let track = &reader.tracks()[&id];
2616+ // Off the borrow before the samples, which need the reader itself.
2617+ let language = track.language().to_owned();
2618+ let timescale = i128::from(track.timescale().max(1));
2619+ let count = track.sample_count();
2620+ let mut samples = Vec::with_capacity(count as usize);
2621+ for i in 1..=count {
2622+ // Sample ids count from 1. A sample the tables cannot reach is
2623+ // skipped rather than raised: the other cues of the track are still
2624+ // the words a viewer needs.
2625+ let Some(sample) = reader.read_sample(id, i)? else {
2626+ continue;
2627+ };
2628+ let us = |ticks: u64| (i128::from(ticks) * 1_000_000 / timescale) as i64;
2629+ samples.push(Mp4TextSample {
2630+ start_us: us(sample.start_time),
2631+ end_us: us(sample.start_time + u64::from(sample.duration)),
2632+ payload: sample.bytes.to_vec(),
2633+ });
2634+ }
2635+ tracks.push(Mp4Subtitle {
2636+ number: u64::from(id),
2637+ language,
2638+ name: names
2639+ .iter()
2640+ .find(|(track_id, _)| *track_id == id)
2641+ .map(|(_, name)| name.clone())
2642+ .unwrap_or_default(),
2643+ samples,
2644+ });
2645+ }
2646+ Ok(tracks)
2647+}
2648+
2649+/// Each `trak`'s `udta/name`, by track id, for the traks that have one -- an
2650+/// mp4's word for what a track is *called*, beside the `mdhd` language it is
2651+/// in. Read by hand for the reason [`mp4_subtitles`] gives.
2652+fn mp4_track_names(path: &Path) -> crate::Result<Vec<(u32, String)>> {
2653+ let Some(moov) = read_top_level(path, b"moov")? else {
2654+ return Ok(Vec::new());
2655+ };
2656+ Ok(boxes(&moov)
2657+ .filter(|(kind, _)| *kind == b"trak")
2658+ .filter_map(|(_, trak)| {
2659+ let id = child(trak, b"tkhd").and_then(tkhd_track_id)?;
2660+ let name = child(trak, b"udta").and_then(|udta| child(udta, b"name"))?;
2661+ // Raw bytes, no version or flags -- and a writer that terminates the
2662+ // string is not lying about the title, it is padding it.
2663+ let name = String::from_utf8_lossy(name);
2664+ Some((id, name.trim_end_matches('\0').to_owned()))
2665+ })
2666+ .collect())
2667+}
2668+
2181 /// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles.2669 /// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles.
2182 fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Option<MkvSubtitle>> {2670 fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Option<MkvSubtitle>> {
2183 const SUBTITLE: u64 = 0x11;2671 const SUBTITLE: u64 = 0x11;
2184 let (mut number, mut kind, mut codec) = (0, 0, String::new());2672 let (mut number, mut kind, mut codec) = (0, 0, String::new());
2185 let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new());2673 let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new());
2674+ let mut bcp47 = String::new();
2186 let mut unpack = Unpack::None;2675 let mut unpack = Unpack::None;
2187 let mut at = body;2676 let mut at = body;
2188 while let Some((id, body, stop)) = ebml_element(file, at, end)? {2677 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
@@ -2193,6 +2682,7 @@ fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Opt
2193 CODEC_ID => codec = string_of(file, body, stop)?,2682 CODEC_ID => codec = string_of(file, body, stop)?,
2194 CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?,2683 CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?,
2195 TRACK_LANGUAGE => language = string_of(file, body, stop)?,2684 TRACK_LANGUAGE => language = string_of(file, body, stop)?,
2685+ TRACK_LANGUAGE_BCP47 => bcp47 = string_of(file, body, stop)?,
2196 TRACK_NAME => name = string_of(file, body, stop)?,2686 TRACK_NAME => name = string_of(file, body, stop)?,
2197 _ => {}2687 _ => {}
2198 }2688 }
@@ -2201,12 +2691,9 @@ fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Opt
2201 Ok((kind == SUBTITLE).then(|| MkvSubtitle {2691 Ok((kind == SUBTITLE).then(|| MkvSubtitle {
2202 number,2692 number,
2203 codec,2693 codec,
2204- // What a `TrackEntry` without a `Language` element means, by spec.2694+ // Whichever element the file states it in, `und` for a track that states
2205- language: if language.is_empty() {2695+ // neither -- [`mkv_language`] says why that is not the spec's `eng`.
2206- "und".into()2696+ language: mkv_language(&language, &bcp47),
2207- } else {
2208- language
2209- },
2210 name,2697 name,
2211 private,2698 private,
2212 cues: Vec::new(),2699 cues: Vec::new(),
@@ -2315,6 +2802,61 @@ fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> {
2315 mod tests {2802 mod tests {
2316 use super::*;2803 use super::*;
2317 2804
2805+ /// What a `TrackEntry` states it is in, whichever of the two elements it
2806+ /// states it in -- [`mkv_language`]'s whole rule, as asserts.
2807+ #[test]
2808+ fn a_track_states_its_language_in_either_element() {
2809+ // The modern element wins over the legacy one, which is the spec's own
2810+ // precedence: some films carry a Bulgarian legacy code beside an English
2811+ // BCP-47 tag on different tracks, and the English ones state nothing
2812+ // else at all.
2813+ assert_eq!(mkv_language("", "en"), "eng");
2814+ assert_eq!(mkv_language("bul", "en"), "eng");
2815+ // A region is not a language: neither Matroska's legacy element nor an
2816+ // mp4's 16-bit field can hold one, so `en-US` is the English it is.
2817+ assert_eq!(mkv_language("", "en-US"), "eng");
2818+ assert_eq!(mkv_language("", "pt-BR"), "por");
2819+ assert_eq!(mkv_language("", "zh-Hans"), "zho");
2820+ // ...and every other language of the table, not the ones a test used.
2821+ assert_eq!(mkv_language("", "kn"), "kan");
2822+ assert_eq!(mkv_language("", "JA"), "jpn");
2823+ // Three letters already: an ISO 639-3 tag is what the code is.
2824+ assert_eq!(mkv_language("", "fil"), "fil");
2825+ // What nothing maps falls back to the file's other word rather than
2826+ // being thrown away, and `und` is only for a file that said neither.
2827+ assert_eq!(mkv_language("fra", "x-pig-latin"), "fra");
2828+ assert_eq!(mkv_language("", "x-pig-latin"), "und");
2829+ assert_eq!(mkv_language("fra", ""), "fra");
2830+ assert_eq!(mkv_language("und", ""), "und");
2831+ assert_eq!(mkv_language("", ""), "und");
2832+ // The table is the standard's own: one entry per ISO 639-1 code, none
2833+ // of them doubled, every code the two and three letters it is.
2834+ let mut seen: Vec<&str> = ISO_639_1_TO_2.iter().map(|(two, _)| *two).collect();
2835+ let count = seen.len();
2836+ seen.sort_unstable();
2837+ seen.dedup();
2838+ assert_eq!(seen.len(), count, "a doubled ISO 639-1 code");
2839+ for (two, three) in ISO_639_1_TO_2 {
2840+ assert!(
2841+ two.len() == 2 && three.len() == 3,
2842+ "{two} → {three} is not a 639-1 → 639-2 pair"
2843+ );
2844+ }
2845+ }
2846+
2847+ /// Every extension Matroska states, and nothing that is not one: `.mks` is
2848+ /// the subtitles alone and `.mka` the sound alone, both the same bytes the
2849+ /// `.mkv` reader already walks.
2850+ #[test]
2851+ fn every_matroska_extension_is_a_matroska() {
2852+ for name in ["a.mkv", "a.mka", "a.mks", "a.mk3d", "a.webm", "A.MKS"] {
2853+ assert!(is_matroska(Path::new(name)), "{name}");
2854+ }
2855+ for name in ["a.mp4", "a.m4v", "a.mov", "a.srt", "a", "a.mk"] {
2856+ assert!(!is_matroska(Path::new(name)), "{name}");
2857+ }
2858+ }
2859+
2318 /// The capability matrix, as an assert: every codec the decoder layer can be2860 /// The capability matrix, as an assert: every codec the decoder layer can be
2319 /// handed is reachable from *both* container dispatches, and every gap is a2861 /// handed is reachable from *both* container dispatches, and every gap is a
2320 /// row in [`UNSUPPORTED`] that is genuinely a gap. A codec wired into2862 /// row in [`UNSUPPORTED`] that is genuinely a gap. A codec wired into
crates/engine/src/edith.rsmodified+2 -0
@@ -1087,6 +1087,8 @@ mod tests {
1087 SubtitleTrack {1087 SubtitleTrack {
1088 path: PathBuf::from(path),1088 path: PathBuf::from(path),
1089 track,1089 track,
1090+ language: String::new(),
1091+ name: String::new(),
1090 label: String::new(),1092 label: String::new(),
1091 cues: Vec::new(),1093 cues: Vec::new(),
1092 bitmap: false,1094 bitmap: false,
crates/engine/src/export.rsmodified+127 -62
@@ -226,7 +226,7 @@ impl Format {
226 /// What the caller gets to decide about the output. The codec is not among it:226 /// What the caller gets to decide about the output. The codec is not among it:
227 /// [`Format`] names a container *and* what goes in it, because every pair we227 /// [`Format`] names a container *and* what goes in it, because every pair we
228 /// can write is a pair we can also read back.228 /// can write is a pair we can also read back.
229-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]229+#[derive(Debug, Clone, Default, PartialEq, Eq)]
230 pub struct ExportSettings {230 pub struct ExportSettings {
231 /// Bits per second, clamped to the same sane range the automatic value uses.231 /// Bits per second, clamped to the same sane range the automatic value uses.
232 /// `None` picks it from the picture size and frame rate. Video only.232 /// `None` picks it from the picture size and frame rate. Video only.
@@ -244,16 +244,22 @@ pub struct ExportSettings {
244 /// it used to. Means nothing to WAV and FLAC, which code no rate, and244 /// it used to. Means nothing to WAV and FLAC, which code no rate, and
245 /// nothing to a *copied* AAC track, which carries its source's.245 /// nothing to a *copied* AAC track, which carries its source's.
246 pub audio_kbps: Option<u32>,246 pub audio_kbps: Option<u32>,
247- /// Which of the project's subtitle tracks travels with the file: an index247+ /// Which of the project's subtitle tracks travel with the file: indices into
248- /// into [`Project::subtitles`], which is the same list a front-end picks a248+ /// [`Project::subtitles`], which is the same list a front-end picks rows of.
249- /// row of. `None` writes none -- what every caller wrote before there was a249+ /// As many as the timeline holds, in the order given -- the file declares
250- /// choice, so an export of a timeline without subtitles is the file it250+ /// them in that order and a player's subtitle menu lists them in it. Empty
251- /// always was, byte for byte.251+ /// writes none -- what every caller wrote before there was a choice, so an
252+ /// export of a timeline without subtitles is the file it always was, byte
253+ /// for byte.
252 ///254 ///
253- /// Only a Matroska container carries it: an mp4's `tx3g` is a different255+ /// Every container that carries picture carries them: Matroska as
254- /// beast and nothing here writes one, so an mp4 export says so256+ /// `S_TEXT/UTF8` blocks, an mp4 as a `tx3g` timed-text track
255- /// ([`planned_subtitles`]) rather than dropping the track in silence.257+ /// ([`crate::mux::Mp4Muxer::write_subtitles`]). A Matroska block names its
256- pub subtitles: Option<usize>,258+ /// track in one byte, so a Matroska file carries at most
259+ /// [`crate::mux::MAX_SUB_TRACKS`] of them and asking for more is refused by
260+ /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has
261+ /// no such ceiling.
262+ pub subtitles: Vec<usize>,
257 }263 }
258 264
259 struct Shared {265 struct Shared {
@@ -317,7 +323,7 @@ pub fn start(
317 out: &Path,323 out: &Path,
318 settings: &ExportSettings,324 settings: &ExportSettings,
319 ) -> ExportHandle {325 ) -> ExportHandle {
320- let settings = *settings;326+ let settings = settings.clone();
321 let shared = Arc::new(Shared {327 let shared = Arc::new(Shared {
322 progress: AtomicU32::new(0),328 progress: AtomicU32::new(0),
323 cancel: AtomicBool::new(false),329 cancel: AtomicBool::new(false),
@@ -559,30 +565,48 @@ pub fn audio_rate_refusal(project: &Project, format: Format) -> Option<&'static
559 }565 }
560 }566 }
561 567
562-/// The track a Matroska export carries, or `None`: no pick, a pick nothing568+/// The tracks an export carries, in the order they were picked, and empty where
563-/// answers, a track that could not be read, one with no cue left on the569+/// it carries none: no pick, a pick nothing answers, a track that could not be
564-/// exported timeline -- and every mp4, whose refusal [`planned_subtitles`] says570+/// read, one with no cue left on the exported timeline -- and every format that
565-/// out loud before the button is pressed.571+/// is the sound alone, which has nowhere to put them. Filtered *per track*, so
572+/// one unusable pick costs its own row and not the others.
573+///
574+/// Both containers, since the mp4 muxer gained its `tx3g` track: what the two
575+/// do with the very same [`SubParams`] is theirs to say
576+/// ([`crate::mux::Mp4Muxer::write_subtitles`], [`MkvMuxer`]), and nothing here
577+/// asks which one is being written.
566 fn export_subtitles(578 fn export_subtitles(
567 project: &Project,579 project: &Project,
568 meta: &VideoMeta,580 meta: &VideoMeta,
569 settings: &ExportSettings,581 settings: &ExportSettings,
570-) -> Option<SubParams> {582+) -> Vec<SubParams> {
571- if !matches!(settings.format, Format::Av1 | Format::Hevc) {583+ if !settings.format.has_video() {
572- return None;584+ return Vec::new();
573 }585 }
574- let track = project.subtitles().get(settings.subtitles?)?;586+ settings
575- // A picture is not a line: the muxer writes an `S_TEXT/UTF8` track and a587+ .subtitles
576- // PGS cue has no words to put in one. `planned_subtitles` says so before588+ .iter()
577- // the button is pressed rather than the file coming out short.589+ .filter_map(|&pick| {
578- if track.refused.is_some() || track.is_bitmap() {590+ let track = project.subtitles().get(pick)?;
579- return None;591+ // A picture is not a line: the muxer writes an `S_TEXT/UTF8` track
580- }592+ // and a PGS cue has no words to put in one. `planned_subtitles` says
581- let cues = timeline_cues(project, track, meta.frame_rate);593+ // so before the button is pressed rather than the file coming out
582- (!cues.is_empty()).then(|| SubParams {594+ // short.
583- label: track.label.clone(),595+ if track.refused.is_some() || track.is_bitmap() {
584- cues,596+ return None;
585- })597+ }
598+ let cues = timeline_cues(project, track, meta.frame_rate);
599+ // The container's own two fields, carried as two
600+ // ([`SubtitleTrack::language`]): a `TrackEntry` with no `Language`
601+ // means `eng` by spec, so a French track that arrives here as one
602+ // flattened string leaves as an English one.
603+ (!cues.is_empty()).then(|| SubParams {
604+ language: track.language.clone(),
605+ name: track.name.clone(),
606+ cues,
607+ })
608+ })
609+ .collect()
586 }610 }
587 611
588 /// The track's cues where the *exported* timeline puts them, which is the only612 /// The track's cues where the *exported* timeline puts them, which is the only
@@ -676,30 +700,66 @@ pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<
676 out700 out
677 }701 }
678 702
679-/// What [`start`] would do about the subtitles, in the words a card shows.703+/// What [`start`] would do about the subtitles, in the words a card shows: what
680-/// Pure, like [`planned_audio`]: no file is opened, so it may be asked per704+/// travels, and the reason beside every pick that does not. Pure, like
681-/// repaint.705+/// [`planned_audio`]: no file is opened, so it may be asked per repaint.
682-pub fn planned_subtitles(project: &Project, format: Format, pick: Option<usize>) -> String {706+///
683- let Some(track) = pick.and_then(|i| project.subtitles().get(i)) else {707+/// `picks` is any run of indices into [`Project::subtitles`] -- an
684- return "none".into();708+/// [`ExportSettings::subtitles`] list (`picks.iter().copied()`) as much as a
685- };709+/// single `Some(row)`, which is what a front-end holding one row still hands it.
686- if let Some(why) = &track.refused {710+pub fn planned_subtitles(
687- return format!("{} — {why}", track.label);711+ project: &Project,
688- }712+ format: Format,
689- // Drawn over the picture, written into no file: the exported track is text713+ picks: impl IntoIterator<Item = usize>,
690- // and these cues are bitmaps. Said whatever the format, because it is the714+) -> String {
691- // track and not the container that cannot be carried.715+ let mut embedded: Vec<&str> = Vec::new();
692- if track.is_bitmap() {716+ let mut dropped: Vec<String> = Vec::new();
693- return format!("{} — pictures; drawn, not written", track.label);717+ let picks: Vec<usize> = picks.into_iter().collect();
718+ // One statement about the *file*, said before any about a track: a format
719+ // that is the sound alone has nowhere to put a single one of them, and the
720+ // reason a pick would not have travelled anyway (a picture track, no cues)
721+ // is not the reason it does not travel here. Nothing picked is "none" --
722+ // there is nothing to say a container cannot carry.
723+ if !picks.is_empty() && !format.has_video() {
724+ return "none — this format is the sound alone".into();
725+ }
726+ for pick in picks {
727+ // A pick the project has no row for: a caller holding an index the list
728+ // no longer has (a removed row shifts every later one down). Every other
729+ // reason a pick does not travel is named on this card, so this one is
730+ // too -- a bug that says nothing is a bug found in the finished file.
731+ let Some(track) = project.subtitles().get(pick) else {
732+ dropped.push(format!("#{pick} — no such track"));
733+ continue;
734+ };
735+ if let Some(why) = &track.refused {
736+ dropped.push(format!("{} — {why}", track.label));
737+ } else if track.is_bitmap() {
738+ // Drawn over the picture, written into no file: the exported track
739+ // is text and these cues are bitmaps. Said whatever the format,
740+ // because it is the track and not the container that cannot be
741+ // carried.
742+ dropped.push(format!("{} — pictures; drawn, not written", track.label));
743+ } else if track.cues.is_empty() {
744+ dropped.push(format!("{} — no cues", track.label));
745+ } else {
746+ // Whichever container: a Matroska carries the track as
747+ // `S_TEXT/UTF8` blocks and an mp4 as a `tx3g` timed-text track, and
748+ // a pick travels either way. There is no container refusal left on
749+ // this card -- the sound-alone one above is about the *file* and the
750+ // ones beside it about the *track*.
751+ embedded.push(&track.label);
752+ }
694 }753 }
695- match format {754+ let mut parts = match embedded.len() {
696- _ if track.cues.is_empty() => "none".into(),755+ 0 => Vec::new(),
697- Format::Av1 | Format::Hevc => format!("{} → embedded", track.label),756+ 1 => vec![format!("{} → embedded", embedded[0])],
698- // Said before the export rather than after it: an mp4 carries text in757+ n => vec![format!("{n} tracks → embedded ({})", embedded.join(", "))],
699- // `tx3g` and nothing here writes one, so the honest answer is the758+ };
700- // container that does.759+ parts.extend(dropped);
701- format if format.has_video() => "mkv only — an mp4 carries none".into(),760+ match parts.is_empty() {
702- _ => "none — this format is the sound alone".into(),761+ true => "none".into(),
762+ false => parts.join("; "),
703 }763 }
704 }764 }
705 765
@@ -1191,16 +1251,19 @@ fn run(
1191 let Some(muxer) = muxer else {1251 let Some(muxer) = muxer else {
1192 return Err("export produced no coded pictures".into());1252 return Err("export produced no coded pictures".into());
1193 };1253 };
1194- // The mp4's audio track after its picture -- the Matroska one interleaved1254+ // The mp4's audio and subtitle tracks after its picture -- the Matroska one
1195- // its own as it went and left `packets` empty behind it.1255+ // interleaved its own as it went and left `packets` and `subs` empty behind
1196- let muxer = match (muxer, packets) {1256+ // it. The text last, so its samples are written knowing how long the picture
1197- (Muxer::Mp4(mut mp4), Some(packets)) => {1257+ // turned out to be.
1198- for packet in packets {1258+ let muxer = match muxer {
1259+ Muxer::Mp4(mut mp4) => {
1260+ for packet in packets.into_iter().flatten() {
1199 mp4.write_audio_packet(&packet.bytes)?;1261 mp4.write_audio_packet(&packet.bytes)?;
1200 }1262 }
1263+ mp4.write_subtitles(&subs)?;
1201 Muxer::Mp4(mp4)1264 Muxer::Mp4(mp4)
1202 }1265 }
1203- (muxer, _) => muxer,1266+ muxer => muxer,
1204 };1267 };
1205 cancelled(shared)?;1268 cancelled(shared)?;
1206 muxer.finish()?;1269 muxer.finish()?;
@@ -1674,7 +1737,7 @@ fn write_video(
1674 settings: &ExportSettings,1737 settings: &ExportSettings,
1675 audio: Option<&AudioParams>,1738 audio: Option<&AudioParams>,
1676 packets: &mut Option<Vec<crate::AacPacket>>,1739 packets: &mut Option<Vec<crate::AacPacket>>,
1677- subs: &mut Option<SubParams>,1740+ subs: &mut Vec<SubParams>,
1678 au: &[u8],1741 au: &[u8],
1679 key: bool,1742 key: bool,
1680 ) -> crate::Result<()> {1743 ) -> crate::Result<()> {
@@ -1702,7 +1765,7 @@ fn write_video(
1702 hvcc: &hvcc,1765 hvcc: &hvcc,
1703 },1766 },
1704 sound,1767 sound,
1705- subs.take(),1768+ std::mem::take(subs),
1706 )?)) else {1769 )?)) else {
1707 unreachable!("just inserted a Matroska muxer")1770 unreachable!("just inserted a Matroska muxer")
1708 };1771 };
@@ -1759,7 +1822,7 @@ fn write_video(
1759 out,1822 out,
1760 &params(meta, au)?,1823 &params(meta, au)?,
1761 sound,1824 sound,
1762- subs.take(),1825+ std::mem::take(subs),
1763 )?)) else {1826 )?)) else {
1764 unreachable!("just inserted a Matroska muxer")1827 unreachable!("just inserted a Matroska muxer")
1765 };1828 };
@@ -2517,6 +2580,8 @@ mod tests {
2517 SubtitleTrack {2580 SubtitleTrack {
2518 path: path.into(),2581 path: path.into(),
2519 track,2582 track,
2583+ language: "eng".into(),
2584+ name: String::new(),
2520 label: "eng".into(),2585 label: "eng".into(),
2521 bitmap: false,2586 bitmap: false,
2522 cues: vec![2587 cues: vec![
crates/engine/src/lib.rsmodified+1 -1
@@ -29,7 +29,7 @@ pub use audio::{
29 };29 };
30 pub use clock::PlaybackClock;30 pub use clock::PlaybackClock;
31 pub use decode::{DecodeSession, Frame, image_size};31 pub use decode::{DecodeSession, Frame, image_size};
32-pub use demux::{Codec, VideoMeta};32+pub use demux::{Codec, MediaBitrate, VideoMeta, probe_bitrate};
33 pub use export::ExportHandle;33 pub use export::ExportHandle;
34 pub use mux::{AudioParams, Mp4Muxer, VideoParams};34 pub use mux::{AudioParams, Mp4Muxer, VideoParams};
35 pub use playback::PlaybackSession;35 pub use playback::PlaybackSession;
crates/engine/src/mux.rsmodified+394 -76
@@ -11,7 +11,9 @@
11 //! `avc1` entry and this patches that entry into the `av01` + `av1C` pair the11 //! `avc1` entry and this patches that entry into the `av01` + `av1C` pair the
12 //! spec asks for, which is the only box in a whole mp4 the crate cannot spell.12 //! spec asks for, which is the only box in a whole mp4 the crate cannot spell.
13 //! Both containers carry the timeline's AAC, so no format here writes a picture13 //! Both containers carry the timeline's AAC, so no format here writes a picture
14-//! whose sound was silently left behind.14+//! whose sound was silently left behind -- and both carry its subtitles, an mp4
15+//! as the `tx3g` timed text `mp4 0.14` *can* spell ([`Mp4Muxer::write_subtitles`])
16+//! and Matroska as `S_TEXT/UTF8` blocks, so neither is a file whose words were.
15 17
16 use std::fs::{File, OpenOptions};18 use std::fs::{File, OpenOptions};
17 use std::io::{BufWriter, Read, Seek, SeekFrom, Write};19 use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
@@ -19,7 +21,7 @@ use std::path::{Path, PathBuf};
19 21
20 use mp4::{22 use mp4::{
21 AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config,23 AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config,
22- Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType,24+ Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType, TtxtConfig,
23 };25 };
24 26
25 use crate::colorspace::ColorDescription;27 use crate::colorspace::ColorDescription;
@@ -35,6 +37,10 @@ const NTSC_TICKS: u32 = 1001;
35 /// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the37 /// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the
36 /// per-packet duration is this constant.38 /// per-packet duration is this constant.
37 const AAC_PACKET_SAMPLES: u32 = 1024;39 const AAC_PACKET_SAMPLES: u32 = 1024;
40+/// The clock a `tx3g` track counts in: one millisecond, the very tick a Matroska
41+/// block's timestamp is written at ([`TIMESTAMP_SCALE_NS`]), so a cue lands on
42+/// the same instant whichever of the two containers carries it.
43+const SUB_TIMESCALE: u32 = 1_000;
38 44
39 const NAL_IDR: u8 = 5;45 const NAL_IDR: u8 = 5;
40 const NAL_SEI: u8 = 6;46 const NAL_SEI: u8 = 6;
@@ -81,6 +87,17 @@ pub struct Mp4Muxer {
81 /// Where the file is, for that patch: the writer owns the handle it wrote87 /// Where the file is, for that patch: the writer owns the handle it wrote
82 /// through and the patch reopens the finished file.88 /// through and the patch reopens the finished file.
83 path: PathBuf,89 path: PathBuf,
90+ /// The video track's clock and how many pictures have been written on it --
91+ /// which is where the file *ends*, and a timed-text track is written out to
92+ /// that instant ([`write_subtitles`](Mp4Muxer::write_subtitles)).
93+ timescale: u32,
94+ frames: u64,
95+ /// What the subtitle tracks are *called*, in the order they were written:
96+ /// an mp4 states a track's title in a `trak/udta/name` box, which `mp4 0.14`
97+ /// has no field for, so it is patched in at [`finish`](Mp4Muxer::finish)
98+ /// beside the sample entry. Empty where no track carries a title, which is
99+ /// every file that has no subtitles at all.
100+ sub_names: Vec<String>,
84 }101 }
85 102
86 /// A `ColourInformationBox` payload, ISO/IEC 14496-12 §12.1.5: the `nclx` tag103 /// A `ColourInformationBox` payload, ISO/IEC 14496-12 §12.1.5: the `nclx` tag
@@ -270,6 +287,9 @@ impl Mp4Muxer {
270 entry,287 entry,
271 colr: colr_nclx(ColorDescription::output(video.height)),288 colr: colr_nclx(ColorDescription::output(video.height)),
272 path: path.to_path_buf(),289 path: path.to_path_buf(),
290+ timescale,
291+ frames: 0,
292+ sub_names: Vec::new(),
273 })293 })
274 }294 }
275 295
@@ -287,6 +307,7 @@ impl Mp4Muxer {
287 bytes: Bytes::from(bytes),307 bytes: Bytes::from(bytes),
288 },308 },
289 )?;309 )?;
310+ self.frames += 1;
290 Ok(())311 Ok(())
291 }312 }
292 313
@@ -310,6 +331,7 @@ impl Mp4Muxer {
310 bytes: Bytes::copy_from_slice(obus),331 bytes: Bytes::copy_from_slice(obus),
311 },332 },
312 )?;333 )?;
334+ self.frames += 1;
313 Ok(())335 Ok(())
314 }336 }
315 337
@@ -335,6 +357,80 @@ impl Mp4Muxer {
335 Ok(())357 Ok(())
336 }358 }
337 359
360+ /// The soft subtitle tracks this file carries, written after the picture and
361+ /// the sound exactly as [`MkvMuxer`] writes its own into the clusters -- one
362+ /// `tx3g` timed-text track per [`SubParams`], which is the text an mp4 says
363+ /// a cue with and the one `ffmpeg` calls `mov_text`. Called once, before
364+ /// [`finish`](Mp4Muxer::finish); an empty list writes nothing at all, which
365+ /// is why an export with no pick is the file it always was, byte for byte.
366+ ///
367+ /// The samples are *continuous*: a timed-text track states one sample per
368+ /// instant of the film and nothing between them, so the stretches with
369+ /// nothing to say are empty samples (a 16-bit zero length and no text) and
370+ /// not holes -- a hole is where a player keeps the last line on screen until
371+ /// the next one arrives. The run is built out of the cue *boundaries*, so
372+ /// cues that overlap are one sample of both their lines rather than one of
373+ /// them dropped: a `tx3g` track shows one sample at a time where a Matroska
374+ /// one may show two blocks at once, and joining them is what keeps the words
375+ /// a viewer saw over the picture.
376+ ///
377+ /// ponytail: the `tx3g` sample entry is the one `mp4 0.14` writes and there
378+ /// is no field to reach into it -- `MediaConfig::TtxtConfig` carries nothing
379+ /// -- so its `data_reference_index` is the crate's 0 where §8.5.2 says an
380+ /// index into `dref` counts from 1, and it holds no `ftab` font table.
381+ /// ffmpeg and mpv both read the track (measured, 2026-08-12); a reader that
382+ /// checks the index would not. The upgrade path is the trick the `av01`
383+ /// entry already takes: rewrite the 46 fixed bytes of that entry in
384+ /// [`patch_entry`] the way the video one is rewritten.
385+ pub fn write_subtitles(&mut self, subs: &[SubParams]) -> crate::Result<()> {
386+ if subs.is_empty() {
387+ return Ok(());
388+ }
389+ // Where the picture ends, in the text track's own tick: the last sample
390+ // runs out to it, so the track covers the film rather than stopping at
391+ // the last thing anybody says.
392+ let end = (self.frames * u64::from(self.frame_duration) * u64::from(SUB_TIMESCALE)
393+ / u64::from(self.timescale)) as i64;
394+ // The picture is track 1 and the sound, where there is any, track 2:
395+ // `mp4 0.14` numbers a track by the order it was added in, so the text
396+ // starts after them and each further track is the next number up.
397+ for (track_id, subs) in (2 + u32::from(self.has_audio)..).zip(subs) {
398+ self.writer.add_track(&TrackConfig {
399+ track_type: TrackType::Subtitle,
400+ timescale: SUB_TIMESCALE,
401+ // `und` and not an empty string where the source states no
402+ // language: an mp4 packs the three letters into a 16-bit field
403+ // and has no way to leave it out, and `und` is the code that
404+ // says *undetermined* -- while three zero bits would spell a
405+ // language nobody speaks.
406+ language: match subs.language.is_empty() {
407+ true => "und".to_string(),
408+ false => subs.language.clone(),
409+ },
410+ media_conf: MediaConfig::TtxtConfig(TtxtConfig {}),
411+ })?;
412+ for (bytes, duration) in timed_text(&subs.cues, end)? {
413+ self.writer.write_sample(
414+ track_id,
415+ &Mp4Sample {
416+ start_time: 0, // ignored by the writer, as everywhere here
417+ duration,
418+ rendering_offset: 0,
419+ // Every text sample is one a player may start at, and
420+ // saying so per-sample would emit an `stss` listing all
421+ // of them where no `stss` means the same thing -- the
422+ // audio track's reason, and what ffmpeg's own `tx3g`
423+ // track does.
424+ is_sync: false,
425+ bytes: Bytes::from(bytes),
426+ },
427+ )?;
428+ }
429+ }
430+ self.sub_names = subs.iter().map(|subs| subs.name.clone()).collect();
431+ Ok(())
432+ }
433+
338 pub fn finish(mut self) -> crate::Result<()> {434 pub fn finish(mut self) -> crate::Result<()> {
339 self.writer.write_end()?;435 self.writer.write_end()?;
340 let Self {436 let Self {
@@ -342,14 +438,83 @@ impl Mp4Muxer {
342 entry,438 entry,
343 colr,439 colr,
344 path,440 path,
441+ sub_names,
345 ..442 ..
346 } = self;443 } = self;
347 // Not a `drop`: the buffered tail of `moov` has to be on disk before the444 // Not a `drop`: the buffered tail of `moov` has to be on disk before the
348 // patch below reads it back, and a `BufWriter` swallows the error of445 // patch below reads it back, and a `BufWriter` swallows the error of
349 // flushing it on drop.446 // flushing it on drop.
350 writer.into_writer().flush()?;447 writer.into_writer().flush()?;
351- patch_entry(&path, entry.as_ref(), &colr)448+ patch_entry(&path, entry.as_ref(), &colr, &sub_names)
449+ }
450+}
451+
452+/// The cues of one subtitle track as the run of `tx3g` samples an mp4 carries
453+/// them in -- `(payload, duration in milliseconds)`, from instant 0 to `end`,
454+/// with no instant left out.
455+///
456+/// A sample's payload is the ISO/IEC 14496-17 one: the text's length in 16 bits
457+/// and then the UTF-8 itself, which is two zero bytes where there is nothing on
458+/// screen. The run is walked over the cue *boundaries* rather than over the cues,
459+/// which is what makes a gap an empty sample and an overlap one sample carrying
460+/// both lines -- the two things a track of samples has to say that a list of
461+/// cues does not.
462+///
463+/// ponytail: the active set is looked for from the front of the list at every
464+/// boundary, so this is quadratic in the cues of one track (a 5 000-cue film
465+/// costs ~25 M compares once, at the end of an export that took minutes). The
466+/// upgrade path is a sweep holding the open cues in a heap keyed on their end.
467+fn timed_text(cues: &[crate::subtitle::Cue], end: i64) -> crate::Result<Vec<(Vec<u8>, u32)>> {
468+ // Milliseconds, the tick this track is written in -- and a cue that rounds
469+ // onto its own start stays up for one of them rather than vanishing, which
470+ // is what the Matroska writer's `BlockDuration` does with it.
471+ let ms = |us: i64| (us + 500) / 1_000;
472+ let spans: Vec<(i64, i64)> = cues
473+ .iter()
474+ .map(|cue| {
475+ let start = ms(cue.start_us);
476+ (start, ms(cue.end_us).max(start + 1))
477+ })
478+ .collect();
479+ let mut times: Vec<i64> = vec![0, end.max(0)];
480+ for &(start, stop) in &spans {
481+ times.push(start);
482+ times.push(stop);
483+ }
484+ times.sort_unstable();
485+ times.dedup();
486+ let mut out = Vec::with_capacity(times.len());
487+ for pair in times.windows(2) {
488+ let (from, to) = (pair[0], pair[1]);
489+ let mut text = String::new();
490+ for (span, cue) in spans.iter().zip(cues) {
491+ // The cues arrive in start order (`export::timeline_cues` sorts
492+ // them), so nothing past this one has opened yet.
493+ if span.0 > from {
494+ break;
495+ }
496+ if span.1 > from {
497+ if !text.is_empty() {
498+ text.push('\n');
499+ }
500+ text.push_str(&cue.text);
501+ }
502+ }
503+ let len = u16::try_from(text.len()).map_err(|_| {
504+ format!(
505+ "a subtitle cue of {} bytes: a tx3g sample states its text length in 16 bits, so \
506+ one cue carries at most {} -- export a Matroska, whose blocks state no length at \
507+ all",
508+ text.len(),
509+ u16::MAX
510+ )
511+ })?;
512+ let mut bytes = Vec::with_capacity(text.len() + 2);
513+ bytes.extend_from_slice(&len.to_be_bytes());
514+ bytes.extend_from_slice(text.as_bytes());
515+ out.push((bytes, u32::try_from(to - from)?));
352 }516 }
517+ Ok(out)
353 }518 }
354 519
355 /// Rewrites the finished file's one video sample entry: `colr` appended to it520 /// Rewrites the finished file's one video sample entry: `colr` appended to it
@@ -365,11 +530,13 @@ fn patch_entry(
365 path: &Path,530 path: &Path,
366 entry: Option<&([u8; 4], [u8; 4], Vec<u8>)>,531 entry: Option<&([u8; 4], [u8; 4], Vec<u8>)>,
367 colr: &[u8],532 colr: &[u8],
533+ sub_names: &[String],
368 ) -> crate::Result<()> {534 ) -> crate::Result<()> {
369 let mut file = OpenOptions::new().read(true).write(true).open(path)?;535 let mut file = OpenOptions::new().read(true).write(true).open(path)?;
370 let end = file.metadata()?.len();536 let end = file.metadata()?.len();
371 let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?;537 let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?;
372 let patched = swap_entry(&payload, 0, entry, colr).ok_or("no avc1 sample entry to rewrite")?;538 let patched = swap_entry(&payload, 0, entry, colr).ok_or("no avc1 sample entry to rewrite")?;
539+ let patched = name_subtitles(patched, sub_names);
373 let mut out = Vec::with_capacity(patched.len() + 8);540 let mut out = Vec::with_capacity(patched.len() + 8);
374 push_box(&mut out, b"moov", &patched);541 push_box(&mut out, b"moov", &patched);
375 file.seek(SeekFrom::Start(at))?;542 file.seek(SeekFrom::Start(at))?;
@@ -465,6 +632,54 @@ fn swap_entry(
465 done.then_some(out)632 done.then_some(out)
466 }633 }
467 634
635+/// The title of each subtitle track into the `trak` that carries it, in the
636+/// order they were written: a `udta` holding a `name` box, which is where an mp4
637+/// says what a track is *called* (`Signs`) beside the `mdhd` language it is in
638+/// -- the pair Matroska spells as `Name` and `Language`, and the very boxes
639+/// ffmpeg writes a `-metadata:s:s:0 title=` into and reads back out.
640+/// `mp4 0.14`'s `TrakBox` has no `udta` field at all, so it is appended here
641+/// beside the sample entry rewrite, on the same rebuilt `moov`.
642+///
643+/// Untouched where no track has a title -- and returned as it came for a file
644+/// with no subtitles at all, which is every export that picked none.
645+fn name_subtitles(moov: Vec<u8>, names: &[String]) -> Vec<u8> {
646+ if names.iter().all(|name| name.is_empty()) {
647+ return moov;
648+ }
649+ let mut names = names.iter();
650+ let mut out = Vec::with_capacity(moov.len() + 32 * names.len());
651+ for (kind, child) in crate::demux::boxes(&moov) {
652+ // A subtitle `trak` is the one whose media handler says `sbtl`, which is
653+ // what `TrackType::Subtitle` wrote -- asked of the file rather than
654+ // counted, so the picture's and the sound's `trak`s cannot be miscounted
655+ // into.
656+ let name = match kind == b"trak" && is_subtitle_trak(child) {
657+ true => names.next().filter(|name| !name.is_empty()),
658+ false => None,
659+ };
660+ let Some(name) = name else {
661+ push_box(&mut out, kind, child);
662+ continue;
663+ };
664+ let mut trak = child.to_vec();
665+ let mut udta = Vec::new();
666+ push_box(&mut udta, b"name", name.as_bytes());
667+ push_box(&mut trak, b"udta", &udta);
668+ push_box(&mut out, kind, &trak);
669+ }
670+ out
671+}
672+
673+/// Whether a `trak` is a subtitle one: its `mdia`'s `hdlr` names the `sbtl`
674+/// handler, which sits after the box's version, flags and the four `pre_defined`
675+/// bytes.
676+fn is_subtitle_trak(trak: &[u8]) -> bool {
677+ crate::demux::boxes(trak)
678+ .filter(|(kind, _)| *kind == b"mdia")
679+ .flat_map(|(_, mdia)| crate::demux::boxes(mdia))
680+ .any(|(kind, hdlr)| kind == b"hdlr" && hdlr.get(8..12) == Some(&b"sbtl"[..]))
681+}
682+
468 /// One mp4 box: 32-bit size, four-character type, payload. Every box inside a683 /// One mp4 box: 32-bit size, four-character type, payload. Every box inside a
469 /// `moov` fits that form -- the 64-bit one exists for `mdat`, which this never684 /// `moov` fits that form -- the 64-bit one exists for `mdat`, which this never
470 /// rewrites.685 /// rewrites.
@@ -572,32 +787,41 @@ pub struct HevcParams<'a> {
572 pub hvcc: &'a [u8],787 pub hvcc: &'a [u8],
573 }788 }
574 789
575-/// The soft subtitle track a Matroska file carries beside the picture: text,790+/// The soft subtitle track a file carries beside the picture: text, timed, still
576-/// timed, still text in the file -- a player draws it and a user can turn it791+/// text in the file -- a player draws it and a user can turn it off, which is
577-/// off, which is what "soft" means and what burning it into the pixels is not.792+/// what "soft" means and what burning it into the pixels is not.
793+///
794+/// Both containers carry one: Matroska as an `S_TEXT/UTF8` track whose blocks
795+/// are the cues themselves ([`MkvMuxer`]), an mp4 as a `tx3g` timed-text track
796+/// whose samples run end to end over the film
797+/// ([`Mp4Muxer::write_subtitles`]).
578 ///798 ///
579 /// The cues are the *exported timeline's* (`export::timeline_cues` puts them799 /// The cues are the *exported timeline's* (`export::timeline_cues` puts them
580 /// there), because the file's clock is the timeline's; nothing here shifts800 /// there), because the file's clock is the timeline's; nothing here shifts
581 /// anything.801 /// anything.
582 pub struct SubParams {802 pub struct SubParams {
583- /// What the track is called in the file. A three-letter code goes in as803+ /// What language the track is in, as the three-letter code Matroska says it
584- /// `Language`, which is what a player's subtitle menu reads; anything else804+ /// with (`fra`, `tur`): the field a player's subtitle menu reads. Empty
585- /// is a `Name`, which is what it shows when there is no language to show.805+ /// where the source states none -- and *only* then, because a `TrackEntry`
586- ///806+ /// without a `Language` means `eng` by spec, so a French track that leaves
587- /// ponytail: one string for both because a [`crate::subtitle::SubtitleTrack`]807+ /// this empty leaves as an English one.
588- /// carries one label and not a (language, name) pair. The upgrade path is to808+ pub language: String,
589- /// keep the two apart from the demuxer down -- `MkvSubtitle` already has809+ /// What the track is *called*, where it has a title of its own beside its
590- /// them -- and it belongs to whoever needs a per-language export list.810+ /// language (`Signs`, `Forced`). Empty where it has none.
591- pub label: String,811+ pub name: String,
592 /// In start order, which is the order they are written in.812 /// In start order, which is the order they are written in.
593 pub cues: Vec<crate::subtitle::Cue>,813 pub cues: Vec<crate::subtitle::Cue>,
594 }814 }
595 815
596-/// The cues waiting to be interleaved into the clusters, [`MkvAudio`]'s twin.816+/// The cues of one subtitle track waiting to be interleaved into the clusters,
817+/// [`MkvAudio`]'s twin. One of these per track the file carries.
597 struct MkvSubs {818 struct MkvSubs {
598 cues: Vec<crate::subtitle::Cue>,819 cues: Vec<crate::subtitle::Cue>,
599 /// Cues already written.820 /// Cues already written.
600 next: usize,821 next: usize,
822+ /// Which track its blocks name -- 3 for the first, one more for each after
823+ /// it ([`SUB_TRACK_FIRST`]).
824+ track_no: u8,
601 }825 }
602 826
603 /// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC827 /// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC
@@ -630,9 +854,9 @@ pub struct MkvMuxer {
630 /// The AAC track, if the timeline has sound, and how far it has been854 /// The AAC track, if the timeline has sound, and how far it has been
631 /// written.855 /// written.
632 audio: Option<MkvAudio>,856 audio: Option<MkvAudio>,
633- /// The subtitle track, if one travels with the file, and how far it has857+ /// The subtitle tracks travelling with the file, in the order they were
634- /// been written.858+ /// declared, and how far each has been written. Empty where none does.
635- subs: Option<MkvSubs>,859+ subs: Vec<MkvSubs>,
636 }860 }
637 861
638 /// The sound waiting to be interleaved into the clusters.862 /// The sound waiting to be interleaved into the clusters.
@@ -659,7 +883,7 @@ impl MkvMuxer {
659 path: &Path,883 path: &Path,
660 video: &Av1Params,884 video: &Av1Params,
661 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,885 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
662- subs: Option<SubParams>,886+ subs: Vec<SubParams>,
663 ) -> crate::Result<Self> {887 ) -> crate::Result<Self> {
664 if video.config.is_empty() {888 if video.config.is_empty() {
665 return Err("no AV1 sequence header for the track's CodecPrivate".into());889 return Err("no AV1 sequence header for the track's CodecPrivate".into());
@@ -689,7 +913,7 @@ impl MkvMuxer {
689 path: &Path,913 path: &Path,
690 video: &HevcParams,914 video: &HevcParams,
691 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,915 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
692- subs: Option<SubParams>,916+ subs: Vec<SubParams>,
693 ) -> crate::Result<Self> {917 ) -> crate::Result<Self> {
694 if video.hvcc.is_empty() {918 if video.hvcc.is_empty() {
695 return Err("no hvcC record for the track's CodecPrivate".into());919 return Err("no hvcC record for the track's CodecPrivate".into());
@@ -715,11 +939,22 @@ impl MkvMuxer {
715 codec_id: &[u8],939 codec_id: &[u8],
716 codec_private: &[u8],940 codec_private: &[u8],
717 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,941 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
718- subs: Option<SubParams>,942+ subs: Vec<SubParams>,
719 ) -> crate::Result<Self> {943 ) -> crate::Result<Self> {
720 if !frame_rate.is_finite() || frame_rate <= 0.0 {944 if !frame_rate.is_finite() || frame_rate <= 0.0 {
721 return Err(format!("bad frame rate {frame_rate}").into());945 return Err(format!("bad frame rate {frame_rate}").into());
722 }946 }
947+ // Said before a byte is written, and by name: past this the block header
948+ // could not hold the track number ([`MAX_SUB_TRACKS`]) and the file would
949+ // be quietly wrong rather than absent.
950+ if subs.len() > MAX_SUB_TRACKS {
951+ return Err(format!(
952+ "{} subtitle tracks: a Matroska block writes its track number in \
953+ one byte, so one file carries at most {MAX_SUB_TRACKS}",
954+ subs.len()
955+ )
956+ .into());
957+ }
723 if width == 0 || height == 0 {958 if width == 0 || height == 0 {
724 return Err(format!("bad dimensions {width}x{height}").into());959 return Err(format!("bad dimensions {width}x{height}").into());
725 }960 }
@@ -788,11 +1023,17 @@ impl MkvMuxer {
788 if let Some((audio, _)) = &audio {1023 if let Some((audio, _)) = &audio {
789 elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?);1024 elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?);
790 }1025 }
791- // Declared even where the audio track is not: the numbers are fixed1026+ // Declared even where the audio track is not: the picture is always 1
792- // (1 picture, 2 sound, 3 text) rather than counted, so a file with1027+ // and the sound always 2, so the text starts at 3 whether or not there
793- // subtitles and no sound still says track 3 in its blocks.1028+ // is any sound -- and each further track is the next number up, which is
794- if let Some(subs) = &subs {1029+ // the only counting in the file.
795- elem(&mut tracks, TRACK_ENTRY, &subtitle_track_entry(&subs.label));1030+ for (i, subs) in subs.iter().enumerate() {
1031+ let track_no = SUB_TRACK_FIRST + i as u8;
1032+ elem(
1033+ &mut tracks,
1034+ TRACK_ENTRY,
1035+ &subtitle_track_entry(&subs.language, &subs.name, track_no),
1036+ );
796 }1037 }
797 elem(&mut head, TRACKS, &tracks);1038 elem(&mut head, TRACKS, &tracks);
798 1039
@@ -812,10 +1053,15 @@ impl MkvMuxer {
812 samples: 0,1053 samples: 0,
813 sample_rate: params.sample_rate.max(1),1054 sample_rate: params.sample_rate.max(1),
814 }),1055 }),
815- subs: subs.map(|subs| MkvSubs {1056+ subs: subs
816- cues: subs.cues,1057+ .into_iter()
817- next: 0,1058+ .enumerate()
818- }),1059+ .map(|(i, subs)| MkvSubs {
1060+ cues: subs.cues,
1061+ next: 0,
1062+ track_no: SUB_TRACK_FIRST + i as u8,
1063+ })
1064+ .collect(),
819 })1065 })
820 }1066 }
821 1067
@@ -891,35 +1137,38 @@ impl MkvMuxer {
891 /// [`drain_audio`](MkvMuxer::drain_audio)'s twin, and `i64::MAX` at1137 /// [`drain_audio`](MkvMuxer::drain_audio)'s twin, and `i64::MAX` at
892 /// [`finish`](MkvMuxer::finish) writes what is left: a cue may still be on1138 /// [`finish`](MkvMuxer::finish) writes what is left: a cue may still be on
893 /// screen over the last picture, and one written nowhere is one a player1139 /// screen over the last picture, and one written nowhere is one a player
894- /// never shows.1140+ /// never shows. Every track in turn, in the order they were declared.
895 fn drain_subs(&mut self, until: i64) -> crate::Result<()> {1141 fn drain_subs(&mut self, until: i64) -> crate::Result<()> {
896- loop {1142+ for track in 0..self.subs.len() {
897- let Some(subs) = &mut self.subs else {1143+ loop {
898- return Ok(());1144+ let subs = &mut self.subs[track];
899- };1145+ let Some(cue) = subs.cues.get_mut(subs.next) else {
900- let Some(cue) = subs.cues.get_mut(subs.next) else {1146+ break;
901- return Ok(());1147+ };
902- };1148+ // Milliseconds, the tick this file is written in: a cue is read
903- // Milliseconds, the tick this file is written in: a cue is read for1149+ // for a second or more and no eye finds the half a tick it
904- // a second or more and no eye finds the half a tick it rounds by.1150+ // rounds by.
905- let ts = (cue.start_us + 500) / 1_000;1151+ let ts = (cue.start_us + 500) / 1_000;
906- if ts > until {1152+ if ts > until {
907- return Ok(());1153+ break;
908- }1154+ }
909- // A cue that says it ends before it starts stays up for one tick1155+ // A cue that says it ends before it starts stays up for one tick
910- // rather than for a duration a reader would take as unsigned.1156+ // rather than for a duration a reader would take as unsigned.
911- let ms = ((cue.end_us - cue.start_us + 500) / 1_000).max(1) as u64;1157+ let ms = ((cue.end_us - cue.start_us + 500) / 1_000).max(1) as u64;
912- let text = std::mem::take(&mut cue.text);1158+ let text = std::mem::take(&mut cue.text);
913- subs.next += 1;1159+ subs.next += 1;
914- // A cluster of its own where the text has run past what a 16-bit1160+ let track_no = subs.track_no;
915- // relative timestamp reaches, exactly as the sound's drain does.1161+ // A cluster of its own where the text has run past what a 16-bit
916- if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS {1162+ // relative timestamp reaches, exactly as the sound's drain does.
917- self.flush()?;1163+ if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS {
918- self.cluster_ts = ts;1164+ self.flush()?;
919- uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64);1165+ self.cluster_ts = ts;
1166+ uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64);
1167+ }
1168+ self.block_group(track_no, ts, ms, text.as_bytes());
920 }1169 }
921- self.block_group(SUB_TRACK, ts, ms, text.as_bytes());
922 }1170 }
1171+ Ok(())
923 }1172 }
924 1173
925 /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC1174 /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC
@@ -1035,32 +1284,49 @@ fn aac_track_entry(audio: &AudioParams) -> crate::Result<Vec<u8>> {
1035 Ok(entry)1284 Ok(entry)
1036 }1285 }
1037 1286
1038-/// Which track a subtitle block names. Fixed, like the picture's 1 and the1287+/// Which track the *first* subtitle block names, the picture's 1 and the sound's
1039-/// sound's 2: a file with no audio track still writes its text on 3, so nothing1288+/// 2 being fixed: a file with no audio track still writes its first text track
1040-/// has to count tracks to read a block.1289+/// on 3, so nothing has to count the tracks before it to read a block. Each
1041-const SUB_TRACK: u8 = 3;1290+/// further subtitle track is the next number up.
1291+const SUB_TRACK_FIRST: u8 = 3;
1292+
1293+/// How many subtitle tracks one file may carry. A block writes its track number
1294+/// as a one-byte EBML integer (`0x80 | track`, [`MkvMuxer::block`]), and 127 is
1295+/// one number too far: its byte is `0xFF`, the all-ones variable-length integer
1296+/// EBML spells *unknown* with, which this project's own reader hands back as
1297+/// `u64::MAX` (`demux`'s `vint`) -- so track 127's blocks would match no track,
1298+/// its cues would vanish on the way back in, and the file would be one edith
1299+/// wrote and cannot read. The numbers therefore run `3..=126` and the count is
1300+/// what is left of them -- derived from the encoding, so it cannot drift from
1301+/// it. A file asking for more is refused by name in [`MkvMuxer::open`] rather
1302+/// than written with a byte that means another track, or none.
1303+pub const MAX_SUB_TRACKS: usize = 0x7F - SUB_TRACK_FIRST as usize;
1042 1304
1043 /// The `TrackEntry` of the subtitle track: type 0x11 (subtitles) and1305 /// The `TrackEntry` of the subtitle track: type 0x11 (subtitles) and
1044 /// `S_TEXT/UTF8`, whose blocks are the cue's own UTF-8 text and whose timing is1306 /// `S_TEXT/UTF8`, whose blocks are the cue's own UTF-8 text and whose timing is
1045 /// the block's -- the codec every player draws and the one this project's own1307 /// the block's -- the codec every player draws and the one this project's own
1046 /// reader parses back (`subtitle::cues_of`).1308 /// reader parses back (`subtitle::cues_of`).
1047 ///1309 ///
1048-/// The label is a `Language` where it is one (`eng`, `tur`: three letters is1310+/// The two names a track has are written as the two fields Matroska has for
1049-/// what ISO-639-2 is) and a `Name` otherwise, which is exactly what1311+/// them: `Language` is what a player's subtitle menu offers and what a "play
1050-/// [`crate::subtitle::of_matroska`] reads back out, so a track exported and1312+/// French" setting matches on, `Name` is the title beside it (`Signs`). Both
1051-/// re-imported keeps the name it had.1313+/// where the source has both -- a track carrying only a name is an *English*
1052-fn subtitle_track_entry(label: &str) -> Vec<u8> {1314+/// track to every reader, that being the spec's default, which is how a
1315+/// multi-language film used to export as several English ones. Either is left
1316+/// out where it is empty, and [`crate::subtitle::of_matroska`] reads exactly
1317+/// this back, so a track exported and re-imported keeps what it had.
1318+fn subtitle_track_entry(language: &str, name: &str, track_no: u8) -> Vec<u8> {
1053 let mut entry = Vec::new();1319 let mut entry = Vec::new();
1054- uint(&mut entry, TRACK_NUMBER, u64::from(SUB_TRACK));1320+ uint(&mut entry, TRACK_NUMBER, u64::from(track_no));
1055- uint(&mut entry, TRACK_UID, u64::from(SUB_TRACK));1321+ uint(&mut entry, TRACK_UID, u64::from(track_no));
1056 uint(&mut entry, TRACK_TYPE, 0x11);1322 uint(&mut entry, TRACK_TYPE, 0x11);
1057 uint(&mut entry, FLAG_LACING, 0);1323 uint(&mut entry, FLAG_LACING, 0);
1058 elem(&mut entry, CODEC_ID, b"S_TEXT/UTF8");1324 elem(&mut entry, CODEC_ID, b"S_TEXT/UTF8");
1059- let code = label.len() == 3 && label.bytes().all(|b| b.is_ascii_lowercase());1325+ if !language.is_empty() {
1060- match (code, label.is_empty()) {1326+ elem(&mut entry, TRACK_LANGUAGE, language.as_bytes());
1061- (true, _) => elem(&mut entry, TRACK_LANGUAGE, label.as_bytes()),1327+ }
1062- (false, false) => elem(&mut entry, TRACK_NAME, label.as_bytes()),1328+ if !name.is_empty() {
1063- (false, true) => {}1329+ elem(&mut entry, TRACK_NAME, name.as_bytes());
1064 }1330 }
1065 entry1331 entry
1066 }1332 }
@@ -1348,6 +1614,58 @@ mod tests {
1348 v1614 v
1349 }1615 }
1350 1616
1617+ fn cue(start_ms: i64, end_ms: i64, text: &str) -> crate::subtitle::Cue {
1618+ crate::subtitle::Cue {
1619+ start_us: start_ms * 1_000,
1620+ end_us: end_ms * 1_000,
1621+ text: text.into(),
1622+ image: None,
1623+ }
1624+ }
1625+
1626+ /// What a `tx3g` track is made of: one sample per instant of the film and no
1627+ /// hole anywhere. The gaps -- before the first cue, between two, after the
1628+ /// last -- are empty samples (a 16-bit zero and nothing else), and the whole
1629+ /// run adds up to the length it was asked for, which is what stops a player
1630+ /// leaving the last line on screen over the rest of the film.
1631+ #[test]
1632+ fn a_timed_text_track_covers_every_instant() {
1633+ let cues = [cue(500, 1_500, "first"), cue(4_000, 4_750, "third")];
1634+ let samples = timed_text(&cues, 5_000).unwrap();
1635+ let times: Vec<u32> = samples.iter().map(|(_, ms)| *ms).collect();
1636+ assert_eq!(times, [500, 1_000, 2_500, 750, 250], "{samples:?}");
1637+ assert_eq!(times.iter().sum::<u32>(), 5_000, "the film, end to end");
1638+ let texts: Vec<&[u8]> = samples.iter().map(|(bytes, _)| &bytes[..]).collect();
1639+ assert_eq!(texts[0], b"\0\0", "nothing is said until 0.5 s");
1640+ assert_eq!(texts[1], b"\0\x05first");
1641+ assert_eq!(texts[2], b"\0\0", "...nor between the two cues");
1642+ assert_eq!(texts[3], b"\0\x05third");
1643+ assert_eq!(texts[4], b"\0\0", "...nor after the last one");
1644+ }
1645+
1646+ /// Two cues over one another: a Matroska file shows both blocks at once and
1647+ /// a `tx3g` track has one sample per instant, so the overlap is *one* sample
1648+ /// carrying both lines rather than one of them dropped -- the words a viewer
1649+ /// saw over the picture, which is what this file is a copy of.
1650+ #[test]
1651+ fn overlapping_cues_are_one_sample_of_both_lines() {
1652+ let cues = [cue(0, 2_000, "sign"), cue(1_000, 3_000, "dialogue")];
1653+ let samples = timed_text(&cues, 3_000).unwrap();
1654+ let got: Vec<(String, u32)> = samples
1655+ .iter()
1656+ .map(|(bytes, ms)| (String::from_utf8_lossy(&bytes[2..]).into_owned(), *ms))
1657+ .collect();
1658+ assert_eq!(
1659+ got,
1660+ [
1661+ ("sign".into(), 1_000),
1662+ ("sign\ndialogue".into(), 1_000),
1663+ ("dialogue".into(), 1_000),
1664+ ],
1665+ "{samples:?}"
1666+ );
1667+ }
1668+
1351 #[test]1669 #[test]
1352 fn splits_both_start_code_lengths() {1670 fn splits_both_start_code_lengths() {
1353 let src = [1671 let src = [
@@ -1633,7 +1951,7 @@ mod tests {
1633 },1951 },
1634 packets,1952 packets,
1635 )),1953 )),
1636- None,1954+ Vec::new(),
1637 )1955 )
1638 .unwrap();1956 .unwrap();
1639 // Half a second of picture under a second of sound: the tail of the1957 // Half a second of picture under a second of sound: the tail of the
@@ -1761,7 +2079,7 @@ mod tests {
1761 config,2079 config,
1762 },2080 },
1763 None,2081 None,
1764- None,2082+ Vec::new(),
1765 )2083 )
1766 .unwrap();2084 .unwrap();
1767 muxer.write_frame(&key, true).unwrap();2085 muxer.write_frame(&key, true).unwrap();
@@ -1805,7 +2123,7 @@ mod tests {
1805 config: &[],2123 config: &[],
1806 },2124 },
1807 None,2125 None,
1808- None,2126+ Vec::new(),
1809 )2127 )
1810 .is_err()2128 .is_err()
1811 );2129 );
crates/engine/src/playback.rsmodified+71 -12
@@ -892,12 +892,19 @@ impl PlaybackSession {
892 crate::export::planned_audio(&self.project, format)892 crate::export::planned_audio(&self.project, format)
893 }893 }
894 894
895- /// What an export would do about the subtitle track at `pick` --895+ /// What an export would do about the tracks at `picks` --
896 /// [`crate::export::planned_subtitles`], asked of the project a front-end is896 /// [`crate::export::planned_subtitles`], asked of the project a front-end is
897- /// holding, and pure for the same reason. `pick` is a row of897+ /// holding, and pure for the same reason. `picks` is any run of rows of
898- /// [`subtitles`](Self::subtitles).898+ /// [`subtitles`](Self::subtitles): the whole
899- pub fn planned_subtitles(&self, format: crate::export::Format, pick: Option<usize>) -> String {899+ /// [`ExportSettings::subtitles`](crate::export::ExportSettings::subtitles)
900- crate::export::planned_subtitles(&self.project, format, pick)900+ /// list a card is about to send (`picks.iter().copied()`) as much as a
901+ /// single `Some(row)`.
902+ pub fn planned_subtitles(
903+ &self,
904+ format: crate::export::Format,
905+ picks: impl IntoIterator<Item = usize>,
906+ ) -> String {
907+ crate::export::planned_subtitles(&self.project, format, picks)
901 }908 }
902 909
903 /// Where the cues of the track at `pick` land on *this* timeline --910 /// Where the cues of the track at `pick` land on *this* timeline --
@@ -959,11 +966,33 @@ impl PlaybackSession {
959 /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves:966 /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves:
960 /// subtitles are not clips and land on no lane.967 /// subtitles are not clips and land on no lane.
961 pub fn import_subtitles(&mut self, path: &Path) -> crate::Result<usize> {968 pub fn import_subtitles(&mut self, path: &Path) -> crate::Result<usize> {
962- let tracks = match path.extension().is_some_and(|e| {969+ Ok(self.add_subtitle_tracks(Self::parse_subtitles(path)?))
963- let e = e.to_string_lossy().to_ascii_lowercase();970+ }
964- e == "mkv" || e == "webm"971+
965- }) {972+ /// The reading half of [`import_subtitles`](Self::import_subtitles), with no
966- true => crate::subtitle::of_matroska(path)?,973+ /// session in it: every subtitle track of a Matroska file, or the one track
974+ /// a standalone `.srt`/`.vtt`/`.ass` is, cues and all. Same refusal rule.
975+ ///
976+ /// This is the half that costs -- a walk of the whole container, measured at
977+ /// 210 ms on a 25 GB 35-track file and 1.3 s on a 3 GB one whose pages were
978+ /// cold -- so a front-end runs *this* on its background executor and hands
979+ /// what comes back to [`add_subtitle_tracks`](Self::add_subtitle_tracks),
980+ /// which costs a push. Both doors are this one function, so the import
981+ /// button and the background one cannot drift apart.
982+ pub fn parse_subtitles(path: &Path) -> crate::Result<Vec<crate::subtitle::SubtitleTrack>> {
983+ // The containers that carry subtitle tracks *inside* them: every
984+ // Matroska one ([`crate::demux::is_matroska`], which is where `.mks` --
985+ // the subtitles alone -- comes in) and the mp4 family, whose `tx3g`
986+ // timed text is what an mp4 export of this project's own writes, so a
987+ // file edith wrote is a file edith imports back.
988+ let tracks = match crate::demux::is_matroska(path)
989+ || path.extension().is_some_and(|e| {
990+ matches!(
991+ e.to_string_lossy().to_ascii_lowercase().as_str(),
992+ "mp4" | "m4v" | "mov"
993+ )
994+ }) {
995+ true => crate::subtitle::of_media(path)?,
967 false => vec![crate::subtitle::open(path, None)],996 false => vec![crate::subtitle::open(path, None)],
968 };997 };
969 // A standalone file that could not be parsed is a refusal here rather998 // A standalone file that could not be parsed is a refusal here rather
@@ -975,10 +1004,40 @@ impl PlaybackSession {
975 {1004 {
976 return Err(why.clone().into());1005 return Err(why.clone().into());
977 }1006 }
978- Ok(tracks1007+ Ok(tracks)
1008+ }
1009+
1010+ /// Puts tracks already read by [`parse_subtitles`](Self::parse_subtitles)
1011+ /// on this timeline, in the order given. Hands back how many actually went
1012+ /// on: [`Project::add_subtitles`] drops the ones already here -- same file,
1013+ /// same track number -- so 0 is "this file's subtitles are on the timeline
1014+ /// already", which is the sentence a front-end says.
1015+ ///
1016+ /// The whole of what an import costs the thread that calls it, which is why
1017+ /// the parse is a separate door: nothing here opens, seeks or decodes.
1018+ /// Subtitles are not clips and land on no lane, so nothing playable changes
1019+ /// and no undo step is pushed ([`Project::remove_subtitles`] says why).
1020+ pub fn add_subtitle_tracks(&mut self, tracks: Vec<crate::subtitle::SubtitleTrack>) -> usize {
1021+ tracks
979 .into_iter()1022 .into_iter()
980 .filter(|t| self.project.add_subtitles(t))1023 .filter(|t| self.project.add_subtitles(t))
981- .count())1024+ .count()
1025+ }
1026+
1027+ /// Takes the track at `idx` off this timeline -- the door a subtitle row's
1028+ /// own remove goes through, the way [`import_subtitles`](
1029+ /// Self::import_subtitles) is the door that puts one on. Refused in
1030+ /// [`Project::remove_subtitles`]'s words for a row this timeline does not
1031+ /// have.
1032+ ///
1033+ /// Nothing playable changes and no worker was opened against a cue, so
1034+ /// unlike [`remove_source`](Self::remove_source) this does not reseek. Rows
1035+ /// past `idx` move down by one: a caller holding a picked row (the export's
1036+ /// subtitle pick) has to fix it up or drop it. Not an undo step, for the
1037+ /// reason [`Project::remove_subtitles`] gives -- the inverse is a
1038+ /// re-import.
1039+ pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1040+ self.project.remove_subtitles(idx)
982 }1041 }
983 1042
984 /// Writes the timeline to `path` as a `.edith`, atomically (see1043 /// Writes the timeline to `path` as a `.edith`, atomically (see
crates/engine/src/project.rsmodified+24 -0
@@ -1226,6 +1226,30 @@ impl Project {
1226 true1226 true
1227 }1227 }
1228 1228
1229+ /// Takes the track at `idx` off the list -- what a row's own remove goes
1230+ /// through, so whatever an import added can be taken back out. Refused by
1231+ /// name for a row this project does not have, rather than a silent no-op:
1232+ /// a front-end holding a stale index has picked the wrong row and needs to
1233+ /// hear it.
1234+ ///
1235+ /// Every index past `idx` moves down by one, as [`remove_source`](
1236+ /// Project::remove_source)'s do: a caller holding a picked row (an export's
1237+ /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
1238+ /// it, or it names a different track afterwards.
1239+ ///
1240+ /// ponytail: not an undo step, for the reason the limiter is not -- the
1241+ /// history snapshots hold the lane list and subtitles are not on it
1242+ /// ([`Project::subtitles`]). The inverse is a re-import, not a ctrl+z, and
1243+ /// the upgrade path is the same one: a history entry holding the project's
1244+ /// own settings beside the lanes.
1245+ pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1246+ if idx >= self.subtitles.len() {
1247+ return Err(format!("there is no subtitle track {idx} to remove").into());
1248+ }
1249+ self.subtitles.remove(idx);
1250+ Ok(())
1251+ }
1252+
1229 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s1253 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
1230 /// lanes is multiplied by on its way into the mix: the same lanes in the1254 /// lanes is multiplied by on its way into the mix: the same lanes in the
1231 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`1255 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
crates/engine/src/subtitle.rsmodified+155 -10
@@ -148,8 +148,23 @@ pub struct SubtitleTrack {
148 /// Which track of `path`, for one embedded in a Matroska file. `None` when148 /// Which track of `path`, for one embedded in a Matroska file. `None` when
149 /// `path` *is* the subtitle file.149 /// `path` *is* the subtitle file.
150 pub track: Option<u64>,150 pub track: Option<u64>,
151- /// What a list shows: a language, a muxer's name for the track, or the151+ /// What language the track is in, as the container states it (`eng`, `fra`,
152- /// file's own name for a standalone one.152+ /// `und` for a file that says nothing -- which is what both demuxers hand
153+ /// over rather than an empty string). Empty only for a standalone file,
154+ /// which states no language at all.
155+ ///
156+ /// Kept apart from [`name`](Self::name) because a container keeps them
157+ /// apart: an export writes `TRACK_LANGUAGE` and `TRACK_NAME` as two fields
158+ /// ([`crate::mux::SubParams`]), and a French track whose language is folded
159+ /// into its title leaves as an English one.
160+ pub language: String,
161+ /// What the track is *called* beside its language (`Signs`, `Forced`), or
162+ /// the file's own name for a standalone one. Empty where it has none.
163+ pub name: String,
164+ /// What a list shows: the [`language`](Self::language), the
165+ /// [`name`](Self::name), or the pair ([`label_of`]) -- flattened here
166+ /// because a row shows one string, and derived from the two rather than
167+ /// being what they are derived from.
153 pub label: String,168 pub label: String,
154 /// In start order. Empty when [`refused`](Self::refused) says why.169 /// In start order. Empty when [`refused`](Self::refused) says why.
155 pub cues: Vec<Cue>,170 pub cues: Vec<Cue>,
@@ -173,10 +188,16 @@ impl SubtitleTrack {
173 /// A track that is there and cannot be read, named and kept: a project188 /// A track that is there and cannot be read, named and kept: a project
174 /// re-saved after one of these still lists it, which is the difference189 /// re-saved after one of these still lists it, which is the difference
175 /// between "your subtitles are missing" and losing them for good.190 /// between "your subtitles are missing" and losing them for good.
191+ ///
192+ /// No language and no name: what is refused is never *written* (an export
193+ /// drops it before the muxer, [`crate::export::planned_subtitles`]), and the
194+ /// row it leaves behind shows the `label` it was refused under.
176 fn refused(path: &Path, track: Option<u64>, label: String, why: String) -> Self {195 fn refused(path: &Path, track: Option<u64>, label: String, why: String) -> Self {
177 Self {196 Self {
178 path: path.to_path_buf(),197 path: path.to_path_buf(),
179 track,198 track,
199+ language: String::new(),
200+ name: String::new(),
180 label,201 label,
181 cues: Vec::new(),202 cues: Vec::new(),
182 bitmap: false,203 bitmap: false,
@@ -194,7 +215,8 @@ impl SubtitleTrack {
194 }215 }
195 216
196 /// The one door a saved subtitle line comes back in through: a standalone file217 /// The one door a saved subtitle line comes back in through: a standalone file
197-/// (`track` is `None`) or track `n` of a Matroska file.218+/// (`track` is `None`) or track `n` of a media file, Matroska or mp4
219+/// ([`of_media`]).
198 ///220 ///
199 /// Never an error, whatever is wrong: a deleted `.srt`, a media file that is221 /// Never an error, whatever is wrong: a deleted `.srt`, a media file that is
200 /// not there any more, a track number the file no longer has, a codec of222 /// not there any more, a track number the file no longer has, a codec of
@@ -235,7 +257,7 @@ pub fn open_all(rows: &[(PathBuf, Option<u64>)]) -> Vec<SubtitleTrack> {
235 let label = format!("track {number}");257 let label = format!("track {number}");
236 let tracks = walked258 let tracks = walked
237 .entry(path.as_path())259 .entry(path.as_path())
238- .or_insert_with(|| of_matroska(path));260+ .or_insert_with(|| of_media(path));
239 let tracks = match tracks {261 let tracks = match tracks {
240 Ok(tracks) => tracks,262 Ok(tracks) => tracks,
241 Err(why) => return SubtitleTrack::refused(path, *track, label, why.to_string()),263 Err(why) => return SubtitleTrack::refused(path, *track, label, why.to_string()),
@@ -263,6 +285,11 @@ fn external(path: &Path) -> SubtitleTrack {
263 Ok(cues) => SubtitleTrack {285 Ok(cues) => SubtitleTrack {
264 path: path.to_path_buf(),286 path: path.to_path_buf(),
265 track: None,287 track: None,
288+ // A file beside the media states no language of its own -- and its
289+ // name is the only thing it does state, which is what an export
290+ // writes it as.
291+ language: String::new(),
292+ name: label.clone(),
266 label,293 label,
267 cues,294 cues,
268 // Every format `parse_file` reads is text.295 // Every format `parse_file` reads is text.
@@ -273,22 +300,96 @@ fn external(path: &Path) -> SubtitleTrack {
273 }300 }
274 }301 }
275 302
303+/// Every subtitle track *inside* a media file, whichever container it is: a
304+/// Matroska's ([`of_matroska`]) or an mp4's timed text ([`of_mp4`]).
305+///
306+/// The one door for it, so a project row, an import and an export's read-back
307+/// cannot disagree about what a file carries -- and so an mp4 this project
308+/// wrote comes back into it, which is the whole reason the mp4 reader exists:
309+/// mp4 is the default export format, and a file edith writes and cannot open
310+/// is not a round trip.
311+pub fn of_media(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
312+ match crate::demux::is_matroska(path) {
313+ true => of_matroska(path),
314+ false => of_mp4(path),
315+ }
316+}
317+
318+/// Every timed-text (`tx3g`) subtitle track of an mp4, in track order, with its
319+/// cues -- the mp4 twin of [`of_matroska`].
320+///
321+/// A `tx3g` track is *continuous*: it states one sample per instant of the film
322+/// and the stretches with nothing on screen are samples of no text, so those are
323+/// dropped here rather than kept as cues with an empty line
324+/// ([`crate::demux::Mp4TextSample::payload`]). What is left is the cues, timed
325+/// on the file's own clock, and a track whose samples are all empty comes back
326+/// with none rather than with one per instant.
327+///
328+/// Never a bitmap: an mp4 carries no PGS track this reads, so the refusal
329+/// [`of_matroska`] has for one has no counterpart here.
330+pub fn of_mp4(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
331+ Ok(crate::demux::mp4_subtitles(path)?
332+ .into_iter()
333+ .map(|t| SubtitleTrack {
334+ path: path.to_path_buf(),
335+ track: Some(t.number),
336+ label: label_of(&t.language, &t.name),
337+ language: t.language,
338+ name: t.name,
339+ cues: t.samples.iter().filter_map(tx3g_cue).collect(),
340+ bitmap: false,
341+ refused: None,
342+ })
343+ .collect())
344+}
345+
346+/// One `tx3g` sample as a cue, or `None` for the sample that is not one: the
347+/// empty one that says nothing is on screen between here and the next line, and
348+/// the truncated one whose declared length runs past its own bytes.
349+fn tx3g_cue(sample: &crate::demux::Mp4TextSample) -> Option<Cue> {
350+ let len = usize::from(u16::from_be_bytes([
351+ *sample.payload.first()?,
352+ *sample.payload.get(1)?,
353+ ]));
354+ let text = String::from_utf8_lossy(sample.payload.get(2..2 + len)?);
355+ (!text.is_empty()).then(|| Cue {
356+ start_us: sample.start_us,
357+ end_us: sample.end_us,
358+ text: text.into_owned(),
359+ image: None,
360+ })
361+}
362+
363+/// What a list row shows for a track a container declares: the language, the
364+/// muxer's title, or the pair.
365+///
366+/// A row shows one string, so the two are flattened for it -- and *only* for it.
367+/// Both are kept on the track beside this
368+/// ([`SubtitleTrack::language`], [`SubtitleTrack::name`]), so an export writes
369+/// the container's own two fields rather than guessing them back out of this
370+/// string, which is what used to leave every French track marked English.
371+fn label_of(language: &str, name: &str) -> String {
372+ match (name.is_empty(), language) {
373+ (true, lang) => lang.to_owned(),
374+ (false, "und") => name.to_owned(),
375+ (false, lang) => format!("{lang} — {name}"),
376+ }
377+}
378+
276 /// Every subtitle track of a Matroska file, in file order -- the text ones with379 /// Every subtitle track of a Matroska file, in file order -- the text ones with
277 /// their cues, the bitmap ones refused by name (see the module docs).380 /// their cues, the bitmap ones refused by name (see the module docs).
278 pub fn of_matroska(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {381 pub fn of_matroska(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
279 Ok(crate::demux::matroska_subtitles(path)?382 Ok(crate::demux::matroska_subtitles(path)?
280 .into_iter()383 .into_iter()
281 .map(|mut t| {384 .map(|mut t| {
282- let label = match (t.name.is_empty(), t.language.as_str()) {385+ let label = label_of(&t.language, &t.name);
283- (true, lang) => lang.to_owned(),
284- (false, "und") => t.name.clone(),
285- (false, lang) => format!("{lang} — {}", t.name),
286- };
287 let bitmap = t.codec == crate::demux::PGS;386 let bitmap = t.codec == crate::demux::PGS;
288 match cues_of(&mut t) {387 match cues_of(&mut t) {
289 Ok(cues) => SubtitleTrack {388 Ok(cues) => SubtitleTrack {
290 path: path.to_path_buf(),389 path: path.to_path_buf(),
291 track: Some(t.number),390 track: Some(t.number),
391+ language: t.language,
392+ name: t.name,
292 label,393 label,
293 cues,394 cues,
294 bitmap,395 bitmap,
@@ -505,8 +606,14 @@ fn parse_file(path: &Path) -> crate::Result<Vec<Cue>> {
505 "vtt" | "webvtt" => oxideav_subtitle::webvtt::parse,606 "vtt" | "webvtt" => oxideav_subtitle::webvtt::parse,
506 "ass" | "ssa" => oxideav_ass::parse,607 "ass" | "ssa" => oxideav_ass::parse,
507 other => {608 other => {
609+ // What is *genuinely* accepted, all of it: the subtitle files this
610+ // parses and the containers [`of_media`] walks for the tracks
611+ // inside them (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`, `.mp4`,
612+ // `.m4v`, `.mov`). The old sentence named the four text formats
613+ // alone and so refused a `.mks` this very binary reads.
508 return Err(format!(614 return Err(format!(
509- "{other:?} is not a subtitle format this reads — .srt, .vtt, .ass and .ssa are"615+ "{other:?} is not a subtitle format this reads — .srt, .vtt, .ass and .ssa are, \
616+ as are the subtitle tracks inside a Matroska or an mp4"
510 )617 )
511 .into());618 .into());
512 }619 }
@@ -545,6 +652,44 @@ mod tests {
545 assert_eq!(srt_body("two\nlines\n"), "two\nlines");652 assert_eq!(srt_body("two\nlines\n"), "two\nlines");
546 }653 }
547 654
655+ /// The sample that is not a cue: a `tx3g` track states one sample per
656+ /// instant, so the stretches with nothing on screen are samples of no text
657+ /// -- a track of nothing but those is a track with no cues, not one blank
658+ /// cue per instant.
659+ #[test]
660+ fn an_empty_timed_text_sample_is_not_a_cue() {
661+ let sample = |payload: Vec<u8>| crate::demux::Mp4TextSample {
662+ start_us: 500_000,
663+ end_us: 1_500_000,
664+ payload,
665+ };
666+ let mut text = vec![0, 5];
667+ text.extend_from_slice(b"lines");
668+ let cue = tx3g_cue(&sample(text)).expect("a sample with words is a cue");
669+ assert_eq!(
670+ (cue.start_us, cue.end_us, &cue.text[..]),
671+ (500_000, 1_500_000, "lines")
672+ );
673+ // The empty sample, the one an export writes between two cues and past
674+ // the last of them...
675+ assert!(tx3g_cue(&sample(vec![0, 0])).is_none());
676+ // ...and the bytes that are not a sample: a length past the payload,
677+ // and no length at all.
678+ assert!(tx3g_cue(&sample(vec![0, 9, b'h', b'i'])).is_none());
679+ assert!(tx3g_cue(&sample(Vec::new())).is_none());
680+ }
681+
682+ /// What a row shows, and what an export has to split back apart: the pair a
683+ /// container states, flattened the one way both readers flatten it.
684+ #[test]
685+ fn a_label_is_the_language_the_title_or_the_two() {
686+ assert_eq!(label_of("eng", ""), "eng");
687+ assert_eq!(label_of("fra", "Signs"), "fra — Signs");
688+ // An undetermined language is no language: the title stands alone.
689+ assert_eq!(label_of("und", "Commentary"), "Commentary");
690+ assert_eq!(label_of("und", ""), "und");
691+ }
692+
548 #[test]693 #[test]
549 fn an_unknown_extension_is_refused_by_name_and_a_missing_file_is_kept() {694 fn an_unknown_extension_is_refused_by_name_and_a_missing_file_is_kept() {
550 let err = parse_file(Path::new("/nonexistent/notes.txt"))695 let err = parse_file(Path::new("/nonexistent/notes.txt"))
crates/engine/tests/bitrate.rsadded+292 -0
@@ -0,0 +1,292 @@
1+//! `probe_bitrate`: the number a properties card shows, and the two rules that
2+//! make it worth showing -- it is the file's real bytes over the file's real
3+//! seconds, and a field the container never stated is absent rather than zero.
4+
5+use std::path::{Path, PathBuf};
6+use std::time::Instant;
7+
8+use engine::{MediaBitrate, probe_bitrate};
9+
10+fn asset(name: &str) -> PathBuf {
11+ Path::new(env!("CARGO_MANIFEST_DIR"))
12+ .join("../../assets")
13+ .join(name)
14+}
15+
16+/// What the fixture generator asked ffmpeg for, in seconds -- `-duration`/
17+/// `-t` in `scripts/gen_fixtures.sh`. The independent half of the check: the
18+/// probe derives its seconds from the container (frame count over frame rate,
19+/// or the audio header), and this derives them from nowhere but the script that
20+/// wrote the file.
21+const FIXTURES: &[(&str, f64)] = &[
22+ ("test_av.mp4", 5.0),
23+ ("test_av1.mkv", 2.0),
24+ ("test_hevc.mkv", 2.0),
25+ ("test_tone_48k.wav", 3.0),
26+];
27+
28+/// Every fixture with a container to read, well-shaped or not. The two rules
29+/// below are held over all of them rather than over the tidy ones.
30+const CONTAINERS: &[&str] = &[
31+ "test_av.mp4",
32+ "test_av1.mkv",
33+ "test_hevc.mkv",
34+ "test_hevc10.mkv",
35+ "test_multiaudio.mp4",
36+ "test_multiaudio.mkv",
37+ "test_ac3.mkv",
38+ "test_eac3.mkv",
39+ "test_subs.mkv",
40+ "test_vp9.mp4",
41+ "test_h264.mkv",
42+ "test_tone_48k.wav",
43+ "test_short_video_long_audio.mp4",
44+];
45+
46+/// No field is ever `Some(0)`: a zero read off a card is a measurement, and
47+/// "the header did not say" is not one. Held over every field of every fixture,
48+/// including the ones with no bitrate at all.
49+fn no_field_is_zero(name: &str, rate: MediaBitrate) {
50+ for (field, value) in [
51+ ("total", rate.total),
52+ ("video", rate.video),
53+ ("audio", rate.audio),
54+ ] {
55+ assert_ne!(value, Some(0), "{name}: {field} came back a fabricated zero");
56+ }
57+}
58+
59+#[test]
60+fn a_breakdown_adds_up() {
61+ // The relation that makes the three numbers one line rather than three
62+ // unrelated ones: they are disjoint byte counts over a shared denominator,
63+ // so the parts cannot outweigh the whole and the whole cannot outweigh the
64+ // file. Asserted over every container fixture, not trusted to the
65+ // well-shaped ones -- a total *below* its own components is impossible, and
66+ // a total above the file's byte rate means the denominator is too small,
67+ // which is exactly what dividing by the video track used to do.
68+ for &name in CONTAINERS {
69+ let path = asset(name);
70+ let bytes = std::fs::metadata(&path).expect(name).len();
71+ let rate = probe_bitrate(&path);
72+ no_field_is_zero(name, rate);
73+ let total = rate.total.unwrap_or_else(|| panic!("{name}: no total"));
74+ let parts = rate.video.unwrap_or(0) + rate.audio.unwrap_or(0);
75+ assert!(
76+ total >= parts,
77+ "{name}: total {total} is under its own parts {parts}"
78+ );
79+ // The ceiling: no file plays in less than no time, so no rate can beat
80+ // the whole file delivered over the shortest plausible duration. One
81+ // second is that floor -- every fixture here is longer.
82+ assert!(
83+ total <= bytes * 8,
84+ "{name}: total {total} exceeds the file's own {} bits",
85+ bytes * 8
86+ );
87+ }
88+}
89+
90+#[test]
91+fn a_long_soundtrack_over_a_short_picture_divides_by_the_file() {
92+ // The lopsided container (`gen_fixtures.sh`): 2 s of video under 60 s of
93+ // audio. Dividing 574 222 bytes by the *picture's* 2 s claimed 4 181 048 bps
94+ // -- thirty times the truth, and a "total" smaller than its own components
95+ // when written out. `ffprobe -show_entries format=bit_rate` says 76 562, and
96+ // the container states its own 60 s in the `mvhd` for anyone who asks.
97+ let name = "test_short_video_long_audio.mp4";
98+ let path = asset(name);
99+ let bytes = std::fs::metadata(&path).expect(name).len();
100+ let rate = probe_bitrate(&path);
101+ no_field_is_zero(name, rate);
102+
103+ let total = rate.total.expect("no total");
104+ let expected = bytes as f64 * 8.0 / 60.0;
105+ let error = (total as f64 - expected).abs() / expected;
106+ assert!(
107+ error < 0.05,
108+ "{name}: total {total} is {:.1} % off the file over its own 60 s ({expected:.0})",
109+ error * 100.0
110+ );
111+ // The picture is a fifth of the sound here, which is the whole point: a
112+ // component measured over the video's 2 s would come out above the total.
113+ let video = rate.video.expect("no video rate");
114+ let audio = rate.audio.expect("no audio rate");
115+ assert!(video < audio, "{name}: video {video} >= audio {audio}");
116+ assert!(
117+ video + audio <= total,
118+ "{name}: parts {} beat the total {total}",
119+ video + audio
120+ );
121+}
122+
123+#[test]
124+fn total_is_the_file_over_its_seconds() {
125+ for &(name, secs) in FIXTURES {
126+ let path = asset(name);
127+ let bytes = std::fs::metadata(&path).expect(name).len();
128+ let expected = bytes as f64 * 8.0 / secs;
129+
130+ let rate = probe_bitrate(&path);
131+ no_field_is_zero(name, rate);
132+ let total = rate.total.unwrap_or_else(|| panic!("{name}: no total"));
133+
134+ let error = (total as f64 - expected).abs() / expected;
135+ assert!(
136+ error < 0.05,
137+ "{name}: total {total} bps is {:.1} % off {expected:.0} bps \
138+ ({bytes} bytes over {secs} s)",
139+ error * 100.0
140+ );
141+ }
142+}
143+
144+#[test]
145+fn a_stream_the_container_states_is_stated_and_no_stream_is_invented() {
146+ // Every A/V fixture here has a picture, so the video row is a claim the
147+ // container can always answer -- an mkv out of its own block index, an mp4
148+ // out of its sample table. It must be under the whole file's rate too: a
149+ // track cannot cost more than the file it sits in.
150+ for &(name, secs) in FIXTURES {
151+ let rate = probe_bitrate(&asset(name));
152+ let total = rate.total.unwrap_or_else(|| panic!("{name}: no total"));
153+ if name.ends_with(".wav") {
154+ // One stream, no picture: the sound *is* the file, and there is no
155+ // video row to state.
156+ assert_eq!(rate.video, None, "{name}: a wav has no picture");
157+ assert_eq!(rate.audio, Some(total), "{name}");
158+ continue;
159+ }
160+ let video = rate.video.unwrap_or_else(|| panic!("{name}: no video rate"));
161+ assert!(video < total, "{name}: video {video} >= file {total}");
162+ // Sanity on the units: 5 s of 1280x720 is neither 2 kbps nor 2 Gbps.
163+ assert!(
164+ (10_000..100_000_000).contains(&video),
165+ "{name}: video {video} bps is not a plausible rate for {secs} s of 720p"
166+ );
167+ if let Some(audio) = rate.audio {
168+ assert!(audio < total, "{name}: audio {audio} >= file {total}");
169+ }
170+ }
171+}
172+
173+#[test]
174+fn a_matroska_states_its_sound_too_and_its_picture_is_unchanged() {
175+ // Both mkv fixtures carry `-c:a aac -b:a 128k` (`gen_fixtures.sh:158,223`),
176+ // so an absent audio row here is a missing measurement, not a silent file --
177+ // and a film library is overwhelmingly Matroska, so this is the common case.
178+ //
179+ // The video numbers are pinned so that adding the sound track to the walk
180+ // cannot move the picture. The numerator is the one `ffprobe
181+ // -select_streams v -show_entries packet=size` sums independently -- 716 834
182+ // bytes for test_av1.mkv. The denominator is `Info.Duration`, **2.023 s**,
183+ // not the picture's own 2.000 s: the AAC track outlasts the last frame by
184+ // 23 ms and the file really is that long (`ffprobe format=duration` agrees).
185+ // These were 2_867_336 / 2_086_260 while the divisor was the video track,
186+ // i.e. 1.1 % high, which is the same defect the lopsided fixture shows at
187+ // 30x.
188+ for (name, video_bps) in [("test_av1.mkv", 2_834_736), ("test_hevc.mkv", 2_062_540)] {
189+ let rate = probe_bitrate(&asset(name));
190+ no_field_is_zero(name, rate);
191+ assert_eq!(rate.video, Some(video_bps), "{name}: picture moved");
192+ let audio = rate
193+ .audio
194+ .unwrap_or_else(|| panic!("{name}: no audio rate, and it has a 128k AAC track"));
195+ assert!(
196+ (100_000..170_000).contains(&audio),
197+ "{name}: audio {audio} bps, asked for 128000"
198+ );
199+ }
200+}
201+
202+#[test]
203+fn the_mp4_rows_are_what_the_encoder_was_asked_for() {
204+ // `gen_fixtures.sh:18` writes test_av.mp4's sound at `-b:a 128k`. Nothing
205+ // reads `esds.avg_bitrate` any more -- the sample table is what the track
206+ // actually spends -- so this is the check that walking the `stsz` lands
207+ // where the declared number did. `ffprobe` puts this track at 132 311 and
208+ // the picture at 3 119 464, both over the same 5 s the `mvhd` states.
209+ let rate = probe_bitrate(&asset("test_av.mp4"));
210+ assert_eq!(rate.video, Some(3_119_464), "test_av.mp4: picture");
211+ let audio = rate.audio.expect("test_av.mp4: no audio rate");
212+ assert!(
213+ (120_000..140_000).contains(&audio),
214+ "test_av.mp4: audio {audio} bps, asked for 128000"
215+ );
216+}
217+
218+#[test]
219+fn a_dual_audio_file_names_the_track_it_would_play_and_says_there_are_others() {
220+ // `test_multiaudio.mp4` is the shape an AC-3 5.1 mp4 has:
221+ // an AAC stereo track and a fatter AC-3 one in the same file. Whichever the
222+ // bitrate row names, it names *one* of three, and the danger is calling a
223+ // 0.13 Mb/s stereo track "sound" on a file whose selling point is the AC-3.
224+ //
225+ // The pick is the first audio track in file order, which is the same rule
226+ // `AudioSession::probe_streams` numbers stream 0 by and the same one
227+ // playback and export open. Asserted against `probe_streams` itself rather
228+ // than against a constant, so the two can never drift apart silently: the
229+ // bitrate row and the audio row of one card describe one track.
230+ let name = "test_multiaudio.mp4";
231+ let path = asset(name);
232+ let streams = engine::AudioSession::probe_streams(&path).expect(name);
233+ assert!(
234+ streams.len() > 1,
235+ "{name}: the fixture stopped being multi-audio, this test is now vacuous"
236+ );
237+ let rate = probe_bitrate(&path);
238+ let audio = rate.audio.expect("no audio rate");
239+
240+ // Stream 0 is the 44.1k AAC stereo one (`gen_fixtures.sh:41`); the AC-3 at
241+ // 192k is stream 2. Naming the wrong one would land near 192000.
242+ assert_eq!(streams[0].index, 0, "{name}: stream order moved");
243+ assert_eq!(streams[0].codec, "aac", "{name}: stream 0 is not the AAC one");
244+ assert!(
245+ (110_000..145_000).contains(&audio),
246+ "{name}: audio {audio} bps is not stream 0's ~127 kbps AAC -- the row \
247+ and the audio row now name different tracks"
248+ );
249+ // And the signal that it is one of several: the caller has the count in
250+ // hand from the same probe it already runs, so a card can say so. This
251+ // asserts the count is *reachable*, which is what makes the single number
252+ // honest rather than a silent pick.
253+ assert_eq!(streams.len(), 3, "{name}");
254+}
255+
256+#[test]
257+fn a_still_states_no_rate_at_all() {
258+ // A still has no playing time of its own -- its length on the timeline is
259+ // whatever the clip is stretched to -- so there is no per-second anything
260+ // to divide 1507 bytes by. All three fields absent is the honest answer;
261+ // any number here would be invented.
262+ let rate = probe_bitrate(&asset("test_still.png"));
263+ no_field_is_zero("test_still.png", rate);
264+ assert_eq!(rate, MediaBitrate::default(), "test_still.png");
265+}
266+
267+#[test]
268+fn a_file_that_will_not_open_states_no_rate_either() {
269+ // Not an error and not a zero: a probe run over a whole library meets these
270+ // and the card simply has no row.
271+ let rate = probe_bitrate(Path::new("/nonexistent/nothing.mp4"));
272+ assert_eq!(rate, MediaBitrate::default());
273+ no_field_is_zero("missing", rate);
274+}
275+
276+#[test]
277+fn no_decoder_is_opened() {
278+ // The whole point of the probe: it is cheap enough to run over every file a
279+ // library lists. Decoding one frame of 10-bit HEVC costs far more than this
280+ // budget, so a wall clock is what proves no decoder was opened -- 2 s of
281+ // 720p Main 10 through the header path is single-digit milliseconds.
282+ let path = asset("test_hevc10.mkv");
283+ let started = Instant::now();
284+ let rate = probe_bitrate(&path);
285+ let elapsed = started.elapsed();
286+ no_field_is_zero("test_hevc10.mkv", rate);
287+ assert!(rate.total.is_some(), "test_hevc10.mkv: no total");
288+ assert!(
289+ elapsed.as_millis() < 50,
290+ "probe_bitrate took {elapsed:?}, which is decode territory"
291+ );
292+}
crates/engine/tests/export_subs.rsmodified+480 -33
@@ -1,7 +1,7 @@
1-//! Subtitles leave with the file: a Matroska export carries the picked track as1+//! Subtitles leave with the file, whichever file: a Matroska export carries
2-//! `S_TEXT/UTF8`, timed on the *exported* timeline -- so a cut moves the cues2+//! every picked track as `S_TEXT/UTF8` and an mp4 carries it as `tx3g` timed
3-//! with the pictures they belong to -- and an mp4 says it cannot rather than3+//! text, both timed on the *exported* timeline -- so a cut moves the cues with
4-//! dropping them in silence.4+//! the pictures they belong to in either container.
5 //!5 //!
6 //! Two witnesses for every cue: this project's own Matroska reader6 //! Two witnesses for every cue: this project's own Matroska reader
7 //! (`demux::matroska_subtitles`, the way an exported file comes back into a7 //! (`demux::matroska_subtitles`, the way an exported file comes back into a
@@ -76,6 +76,8 @@ fn track() -> SubtitleTrack {
76 SubtitleTrack {76 SubtitleTrack {
77 path: asset(MEDIA),77 path: asset(MEDIA),
78 track: Some(2),78 track: Some(2),
79+ language: "eng".into(),
80+ name: String::new(),
79 label: "eng".into(),81 label: "eng".into(),
80 bitmap: false,82 bitmap: false,
81 cues: vec![83 cues: vec![
@@ -106,9 +108,28 @@ fn project() -> Project {
106 Project::single(asset(MEDIA), FRAMES).with_subtitles(vec![track()])108 Project::single(asset(MEDIA), FRAMES).with_subtitles(vec![track()])
107 }109 }
108 110
109-/// Exports `project` as an HEVC Matroska carrying subtitle track `pick`, and111+/// The two subtitle tracks `assets/test_subs.mkv` really carries -- `eng` as
110-/// hands back what our own reader finds in the file.112+/// `S_TEXT/UTF8` and `fra` (titled `Signs`) as `S_TEXT/ASS`, the same three cues
111-fn exported(name: &str, project: Project, pick: Option<usize>) -> (Scratch, Vec<Cue>) {113+/// twice -- read back out of it the way an import reads them, and repointed at
114+/// the media this box can encode: that fixture's own picture is AV1 and there is
115+/// no software AV1 decoder to export it through.
116+fn both_tracks() -> Vec<SubtitleTrack> {
117+ let mut tracks = subtitle::of_matroska(&asset("test_subs.mkv")).expect("read the fixture");
118+ assert_eq!(
119+ tracks.len(),
120+ 2,
121+ "the fixture carries two tracks: {tracks:?}"
122+ );
123+ for track in &mut tracks {
124+ track.path = asset(MEDIA);
125+ }
126+ tracks
127+}
128+
129+/// Exports `project` as an HEVC Matroska carrying the subtitle tracks `picks`,
130+/// and hands back what our own reader finds in the file -- one track per pick,
131+/// in the order they were picked.
132+fn exported(name: &str, project: Project, picks: &[usize]) -> (Scratch, Vec<SubtitleTrack>) {
112 pin_software();133 pin_software();
113 let out = out_path(name);134 let out = out_path(name);
114 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");135 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
@@ -118,34 +139,54 @@ fn exported(name: &str, project: Project, pick: Option<usize>) -> (Scratch, Vec<
118 &out,139 &out,
119 &ExportSettings {140 &ExportSettings {
120 format: Format::Hevc,141 format: Format::Hevc,
121- subtitles: pick,142+ subtitles: picks.to_vec(),
122 ..Default::default()143 ..Default::default()
123 },144 },
124 );145 );
125 wait(&handle, Duration::from_secs(300)).expect("the export finishes");146 wait(&handle, Duration::from_secs(300)).expect("the export finishes");
126 let tracks = subtitle::of_matroska(&out).expect("read the export back");147 let tracks = subtitle::of_matroska(&out).expect("read the export back");
127- match pick {148+ assert_eq!(
128- None => {149+ tracks.len(),
129- assert!(tracks.is_empty(), "no pick, no track: {tracks:?}");150+ picks.len(),
130- (out, Vec::new())151+ "exactly the picked tracks: {tracks:?}"
131- }152+ );
132- Some(_) => {153+ for track in &tracks {
133- assert_eq!(tracks.len(), 1, "exactly the picked track: {tracks:?}");154+ assert_eq!(track.refused, None, "the track reads back as text");
134- assert_eq!(tracks[0].refused, None, "the track reads back as text");
135- (out, tracks[0].cues.clone())
136- }
137 }155 }
156+ (out, tracks)
157+}
158+
159+/// The same, as an **mp4**: the picked tracks leave as `tx3g` timed text, which
160+/// is what an mp4 says a subtitle with. Nothing here reads the file back with
161+/// this project's own reader -- there is no mp4 subtitle reader to read it with
162+/// -- so ffmpeg is the witness and the caller asks it.
163+fn exported_mp4(name: &str, project: Project, picks: &[usize]) -> Scratch {
164+ pin_software();
165+ let out = Scratch::file(&format!("ve_subs_export_{name}"), "mp4");
166+ let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
167+ let handle = engine::export::start(
168+ project,
169+ meta,
170+ &out,
171+ &ExportSettings {
172+ format: Format::Mp4,
173+ subtitles: picks.to_vec(),
174+ ..Default::default()
175+ },
176+ );
177+ wait(&handle, Duration::from_secs(300)).expect("the export finishes");
178+ out
138 }179 }
139 180
140 /// What ffmpeg makes of the same file's subtitle track, as an SRT on stdout:181 /// What ffmpeg makes of the same file's subtitle track, as an SRT on stdout:
141 /// a second implementation reading the bytes, which is the whole point of it.182 /// a second implementation reading the bytes, which is the whole point of it.
142 /// `None` where there is no ffmpeg on the box -- the test is not about this183 /// `None` where there is no ffmpeg on the box -- the test is not about this
143 /// machine's packages.184 /// machine's packages.
144-fn ffmpeg_srt(path: &Path) -> Option<String> {185+fn ffmpeg_srt(path: &Path, which: usize) -> Option<String> {
145 let out = Command::new("ffmpeg")186 let out = Command::new("ffmpeg")
146 .args(["-v", "error", "-i"])187 .args(["-v", "error", "-i"])
147 .arg(path)188 .arg(path)
148- .args(["-map", "0:s:0", "-f", "srt", "-"])189+ .args(["-map", &format!("0:s:{which}"), "-f", "srt", "-"])
149 .output()190 .output()
150 .ok()?;191 .ok()?;
151 assert!(192 assert!(
@@ -156,6 +197,19 @@ fn ffmpeg_srt(path: &Path) -> Option<String> {
156 Some(String::from_utf8_lossy(&out.stdout).into_owned())197 Some(String::from_utf8_lossy(&out.stdout).into_owned())
157 }198 }
158 199
200+/// What streams ffmpeg lists in the file, as it prints them -- `ffmpeg -i` with
201+/// no output, whose exit status is an error by design, so only the stream lines
202+/// are read. That listing carries each track's *language* beside its type
203+/// (`Stream #0:3(fra): Subtitle: subrip`), which is the second implementation's
204+/// word on what language the file says it is in. `None` where there is no
205+/// ffmpeg on the box.
206+fn ffmpeg_streams(path: &Path) -> Option<String> {
207+ let out = Command::new("ffmpeg").arg("-i").arg(path).output().ok()?;
208+ let listing = String::from_utf8_lossy(&out.stderr).into_owned();
209+ println!("ffmpeg sees:\n{listing}");
210+ Some(listing)
211+}
212+
159 fn near(got: i64, want: i64, what: &str) {213 fn near(got: i64, want: i64, what: &str) {
160 assert!(214 assert!(
161 (got - want).abs() <= SLACK_US,215 (got - want).abs() <= SLACK_US,
@@ -168,7 +222,8 @@ fn near(got: i64, want: i64, what: &str) {
168 /// same three lines out of it.222 /// same three lines out of it.
169 #[test]223 #[test]
170 fn an_mkv_export_carries_the_picked_subtitle_track() {224 fn an_mkv_export_carries_the_picked_subtitle_track() {
171- let (out, cues) = exported("plain", project(), Some(0));225+ let (out, tracks) = exported("plain", project(), &[0]);
226+ let cues = &tracks[0].cues;
172 assert_eq!(cues.len(), 3, "three cues: {cues:?}");227 assert_eq!(cues.len(), 3, "three cues: {cues:?}");
173 let want = [228 let want = [
174 (500_000, 1_500_000, "first line"),229 (500_000, 1_500_000, "first line"),
@@ -188,7 +243,7 @@ fn an_mkv_export_carries_the_picked_subtitle_track() {
188 assert_eq!(raw[0].codec, "S_TEXT/UTF8");243 assert_eq!(raw[0].codec, "S_TEXT/UTF8");
189 assert_eq!(raw[0].language, "eng", "the label went in as a language");244 assert_eq!(raw[0].language, "eng", "the label went in as a language");
190 245
191- match ffmpeg_srt(&out) {246+ match ffmpeg_srt(&out, 0) {
192 Some(srt) => {247 Some(srt) => {
193 println!("ffmpeg reads the exported track back as:\n{srt}");248 println!("ffmpeg reads the exported track back as:\n{srt}");
194 assert!(srt.contains("first line"), "{srt}");249 assert!(srt.contains("first line"), "{srt}");
@@ -215,7 +270,8 @@ fn a_cut_moves_the_cues_with_the_pictures() {
215 "the hole closed, over two placements of the one source"270 "the hole closed, over two placements of the one source"
216 );271 );
217 272
218- let (out, cues) = exported("cut", project, Some(0));273+ let (out, tracks) = exported("cut", project, &[0]);
274+ let cues = &tracks[0].cues;
219 assert_eq!(275 assert_eq!(
220 cues.len(),276 cues.len(),
221 2,277 2,
@@ -243,7 +299,7 @@ fn a_cut_moves_the_cues_with_the_pictures() {
243 near(cues[1].end_us, 2_750_000, "...end with it");299 near(cues[1].end_us, 2_750_000, "...end with it");
244 assert_eq!(cues[1].text, "third line");300 assert_eq!(cues[1].text, "third line");
245 301
246- if let Some(srt) = ffmpeg_srt(&out) {302+ if let Some(srt) = ffmpeg_srt(&out, 0) {
247 println!("ffmpeg reads the cut export back as:\n{srt}");303 println!("ffmpeg reads the cut export back as:\n{srt}");
248 assert!(304 assert!(
249 !srt.contains("first line"),305 !srt.contains("first line"),
@@ -262,8 +318,344 @@ fn a_cut_moves_the_cues_with_the_pictures() {
262 fn an_export_with_no_pick_carries_no_subtitle_track() {318 fn an_export_with_no_pick_carries_no_subtitle_track() {
263 // `exported` asserts the file has no subtitle track at all; this is the319 // `exported` asserts the file has no subtitle track at all; this is the
264 // pick being absent rather than the timeline having nothing to pick.320 // pick being absent rather than the timeline having nothing to pick.
265- let (out, cues) = exported("none", project(), None);321+ let (out, tracks) = exported("none", project(), &[]);
266- assert_eq!(cues, Vec::new());322+ assert!(tracks.is_empty());
323+ std::fs::remove_file(&out).unwrap();
324+}
325+
326+/// As many tracks as the timeline holds, not one: both of a film's own subtitle
327+/// tracks go into the export, each numbered and named for itself, and a player
328+/// -- ffmpeg here -- offers the two of them.
329+#[test]
330+fn every_picked_track_travels_with_its_own_name() {
331+ let project = Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks());
332+ let (out, tracks) = exported("both", project, &[0, 1]);
333+ // The labels the fixture states: a language on one, a language and a muxer's
334+ // title on the other, and neither is the other's.
335+ assert_eq!(tracks[0].label, "eng");
336+ assert_eq!(tracks[1].label, "fra — Signs");
337+ for track in &tracks {
338+ assert_eq!(track.cues.len(), 3, "three cues each: {track:?}");
339+ near(track.cues[0].start_us, 500_000, "cue start");
340+ near(track.cues[2].end_us, 4_750_000, "cue end");
341+ assert_eq!(
342+ track.cues[2].text, "third line",
343+ "the ASS markup is resolved to text, not carried into the file"
344+ );
345+ }
346+
347+ // In the file itself: two text tracks, numbered from 3 up, and the second
348+ // one's number is what its blocks name -- the reason the cues above came
349+ // back apart rather than doubled onto one track.
350+ let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element");
351+ assert_eq!(
352+ raw.iter().map(|t| t.number).collect::<Vec<_>>(),
353+ vec![3, 4],
354+ "the picture is 1, the sound 2, the text 3 and 4"
355+ );
356+ assert!(
357+ raw.iter().all(|t| t.codec == "S_TEXT/UTF8"),
358+ "both are written as text: {raw:?}"
359+ );
360+ assert_eq!(raw[0].language, "eng", "a three-letter label is a language");
361+ // The language and the title are two fields, not one string: a track that
362+ // says `fra` is what a player's "French" setting finds, and a track that
363+ // says only `Signs` is an *English* track to every reader, Matroska's
364+ // default language being `eng`.
365+ assert_eq!(raw[1].language, "fra", "the French track says so in the file");
366+ assert_eq!(raw[1].name, "Signs", "...and keeps its own title beside it");
367+ assert_eq!(raw[1].codec, "S_TEXT/UTF8");
368+
369+ match ffmpeg_streams(&out) {
370+ Some(listing) => {
371+ let n = listing.matches("Subtitle:").count();
372+ assert_eq!(n, 2, "ffmpeg lists both subtitle streams");
373+ // The other implementation reads the same two languages -- this is
374+ // the assertion that used to come back `(eng)` for the French one.
375+ assert!(
376+ listing.contains("(eng): Subtitle") && listing.contains("(fra): Subtitle"),
377+ "ffmpeg sees one English and one French track: {listing}"
378+ );
379+ let second = ffmpeg_srt(&out, 1).expect("ffmpeg is here");
380+ println!("ffmpeg reads the second track back as:\n{second}");
381+ assert!(second.contains("third line"), "{second}");
382+ assert!(second.contains("00:00:00,500 --> 00:00:01,500"), "{second}");
383+ }
384+ None => println!("no ffmpeg on this box: our own reader is the only witness"),
385+ }
386+ std::fs::remove_file(&out).unwrap();
387+}
388+
389+/// The mp4 half of [`every_picked_track_travels_with_its_own_name`]: the very
390+/// same two tracks into the container the export *defaults* to, where they used
391+/// to be dropped with a card saying an mp4 carried none. ffmpeg is the whole
392+/// witness here -- a second implementation reading the bytes -- and it reads two
393+/// `mov_text` streams, one English and one French, the French one still titled
394+/// `Signs`, with the three cues at the three times.
395+#[test]
396+fn an_mp4_export_carries_the_picked_tracks_as_timed_text() {
397+ let project = Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks());
398+ let out = exported_mp4("mp4_both", project, &[0, 1]);
399+ let Some(listing) = ffmpeg_streams(&out) else {
400+ println!("no ffmpeg on this box: an mp4's tx3g has no other reader here");
401+ std::fs::remove_file(&out).unwrap();
402+ return;
403+ };
404+ assert_eq!(
405+ listing.matches("Subtitle: mov_text").count(),
406+ 2,
407+ "two timed-text streams, not none and not one: {listing}"
408+ );
409+ // The language is the `mdhd` field of each track, which is what a player's
410+ // subtitle menu offers -- the mp4 spelling of the Matroska `Language` the
411+ // sibling test pins.
412+ assert!(
413+ listing.contains("(eng): Subtitle") && listing.contains("(fra): Subtitle"),
414+ "one English and one French: {listing}"
415+ );
416+ // ...and the title beside it, which an mp4 states in a `trak/udta/name` box
417+ // that `mp4 0.14` has no field for and this project patches in.
418+ assert!(
419+ listing.contains("name : Signs"),
420+ "the French track keeps its own title: {listing}"
421+ );
422+ for which in 0..2 {
423+ let srt = ffmpeg_srt(&out, which).expect("ffmpeg is here");
424+ println!("ffmpeg reads mp4 track {which} back as:\n{srt}");
425+ assert!(srt.contains("00:00:00,500 --> 00:00:01,500"), "{srt}");
426+ assert!(srt.contains("first line"), "{srt}");
427+ // The line break inside a cue survives a sample that states its length
428+ // in bytes and nothing else.
429+ assert!(srt.contains("with a break"), "{srt}");
430+ assert!(srt.contains("00:00:04,000 --> 00:00:04,750"), "{srt}");
431+ assert!(srt.contains("third line"), "{srt}");
432+ }
433+ std::fs::remove_file(&out).unwrap();
434+}
435+
436+/// The pair a container states, carried through as a *pair*, into both
437+/// containers: a track's language and its title are two fields at every step
438+/// from the demuxer to the muxer, and neither is derived from the other.
439+///
440+/// The two tracks here are the shapes that used to be lost. `fra` titled `Signs`
441+/// is the one every multi-language export declared English -- the two were
442+/// flattened into one label and split back apart by guessing, and a title that
443+/// was not three lowercase letters took the language down with it. `und` titled
444+/// `Commentary` is the same fault from the other side: a track that states its
445+/// language is undetermined said nothing at all in the file, and a Matroska
446+/// track with no `Language` *is* an English one by spec.
447+///
448+/// Read back with this project's own readers -- ffmpeg is no witness for `und`,
449+/// which both its demuxers drop from the listing rather than print.
450+#[test]
451+fn a_language_and_a_title_are_two_fields_in_both_containers() {
452+ let named = |language: &str, name: &str| SubtitleTrack {
453+ language: language.into(),
454+ name: name.into(),
455+ label: format!("{language} — {name}"),
456+ ..track()
457+ };
458+ let tracks = vec![named("fra", "Signs"), named("und", "Commentary")];
459+ let project = || Project::single(asset(MEDIA), FRAMES).with_subtitles(tracks.clone());
460+
461+ let (out, read) = exported("pair", project(), &[0, 1]);
462+ let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element");
463+ assert_eq!(
464+ raw.iter()
465+ .map(|t| (&t.language[..], &t.name[..]))
466+ .collect::<Vec<_>>(),
467+ vec![("fra", "Signs"), ("und", "Commentary")],
468+ "the Matroska keeps both fields of both tracks"
469+ );
470+ // ...and the label a row shows is built back out of them, not stored:
471+ // an undetermined language is no language to a reader.
472+ assert_eq!(read[0].label, "fra — Signs");
473+ assert_eq!(read[1].label, "Commentary");
474+ std::fs::remove_file(&out).unwrap();
475+
476+ let out = exported_mp4("mp4_pair", project(), &[0, 1]);
477+ let read = subtitle::of_mp4(&out).expect("read the mp4 back");
478+ assert_eq!(
479+ read.iter()
480+ .map(|t| (&t.language[..], &t.name[..]))
481+ .collect::<Vec<_>>(),
482+ vec![("fra", "Signs"), ("und", "Commentary")],
483+ "and so does the mp4, in its `mdhd` and its `udta/name`"
484+ );
485+ for track in &read {
486+ assert_eq!(track.cues.len(), 3, "three cues each: {track:?}");
487+ }
488+ std::fs::remove_file(&out).unwrap();
489+}
490+
491+/// The other mp4: an HEVC one, whose *video* sample entry is rewritten by hand
492+/// after the file is closed (`mux::patch_entry` turns the crate's `avc1` into
493+/// `hvc1`) -- the same rebuild of `moov` the subtitle track's title is patched
494+/// into. The two patches are one walk, so this is the file that says they do not
495+/// tread on each other: ffmpeg reads an HEVC picture *and* the timed text.
496+#[test]
497+fn an_hevc_mp4_keeps_its_rewritten_entry_and_its_text() {
498+ pin_software();
499+ let out = Scratch::file("ve_subs_export_hevc_mp4", "mp4");
500+ let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
501+ let handle = engine::export::start(
502+ Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks()),
503+ meta,
504+ &out,
505+ &ExportSettings {
506+ format: Format::HevcMp4,
507+ subtitles: vec![1],
508+ ..Default::default()
509+ },
510+ );
511+ wait(&handle, Duration::from_secs(300)).expect("the export finishes");
512+ let Some(listing) = ffmpeg_streams(&out) else {
513+ println!("no ffmpeg on this box: an mp4's tx3g has no other reader here");
514+ std::fs::remove_file(&out).unwrap();
515+ return;
516+ };
517+ assert!(listing.contains("Video: hevc"), "the entry patch held: {listing}");
518+ assert!(
519+ listing.contains("(fra): Subtitle: mov_text"),
520+ "...and the text track beside it: {listing}"
521+ );
522+ let srt = ffmpeg_srt(&out, 0).expect("ffmpeg is here");
523+ assert!(srt.contains("00:00:00,500 --> 00:00:01,500"), "{srt}");
524+ assert!(srt.contains("third line"), "{srt}");
525+ std::fs::remove_file(&out).unwrap();
526+}
527+
528+/// ...and the cut lands in an mp4 where it lands in a Matroska: the samples of a
529+/// timed-text track are timed by their own durations, so a cue that moved with
530+/// its pictures has to come out moved here too.
531+#[test]
532+fn a_cut_moves_the_mp4_cues_with_the_pictures() {
533+ let mut project = project();
534+ assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out");
535+ let out = exported_mp4("mp4_cut", project, &[0]);
536+ let Some(srt) = ffmpeg_srt(&out, 0) else {
537+ println!("no ffmpeg on this box: an mp4's tx3g has no other reader here");
538+ std::fs::remove_file(&out).unwrap();
539+ return;
540+ };
541+ println!("ffmpeg reads the cut mp4 export back as:\n{srt}");
542+ assert!(!srt.contains("first line"), "the cut cue is not there: {srt}");
543+ assert!(srt.contains("00:00:00,500 --> 00:00:01,250"), "{srt}");
544+ assert!(srt.contains("00:00:02,000 --> 00:00:02,750"), "{srt}");
545+ assert!(srt.contains("third line"), "{srt}");
546+ std::fs::remove_file(&out).unwrap();
547+}
548+
549+/// The ceiling itself, from underneath: a file carrying exactly
550+/// `MAX_SUB_TRACKS` tracks comes back whole. The last of them is track 126,
551+/// whose block byte is `0xFE` -- one under the all-ones `0xFF` that EBML spells
552+/// *unknown* with, which is what a 127th track's blocks would say and why its
553+/// cues would come back nowhere. Read back with our own reader, so the file is
554+/// one edith can re-import and not merely write.
555+#[test]
556+fn the_last_numberable_track_keeps_its_cues() {
557+ let full = engine::mux::MAX_SUB_TRACKS;
558+ let picks: Vec<usize> = (0..full).collect();
559+ let project =
560+ Project::single(asset(MEDIA), FRAMES).with_subtitles((0..full).map(|_| track()).collect());
561+ let (out, tracks) = exported("ceiling_at", project, &picks);
562+ let empty: Vec<usize> = tracks
563+ .iter()
564+ .enumerate()
565+ .filter(|(_, t)| t.cues.is_empty())
566+ .map(|(i, _)| i)
567+ .collect();
568+ assert!(
569+ empty.is_empty(),
570+ "every one of the {full} tracks keeps its three cues; these came back with none: {empty:?}"
571+ );
572+ let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element");
573+ assert_eq!(
574+ raw.iter().map(|t| t.number).collect::<Vec<_>>(),
575+ (3..3 + full as u64).collect::<Vec<_>>(),
576+ "numbered 3 up to the last one a block byte can name"
577+ );
578+ assert_eq!(raw.last().map(|t| t.number), Some(126));
579+ std::fs::remove_file(&out).unwrap();
580+}
581+
582+/// The ceiling is said out loud: a Matroska block names its track in one byte,
583+/// so past `MAX_SUB_TRACKS` the export refuses by name instead of writing a byte
584+/// that means some other track -- and leaves no file behind.
585+#[test]
586+fn more_tracks_than_a_block_can_number_are_refused_by_name() {
587+ pin_software();
588+ let over = engine::mux::MAX_SUB_TRACKS + 1;
589+ let project =
590+ Project::single(asset(MEDIA), FRAMES).with_subtitles((0..over).map(|_| track()).collect());
591+ let out = out_path("ceiling");
592+ let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
593+ let handle = engine::export::start(
594+ project,
595+ meta,
596+ &out,
597+ &ExportSettings {
598+ format: Format::Hevc,
599+ subtitles: (0..over).collect(),
600+ ..Default::default()
601+ },
602+ );
603+ let said = wait(&handle, Duration::from_secs(300))
604+ .expect_err("a file that cannot be numbered is not written")
605+ .to_string();
606+ assert!(
607+ said.contains(&format!("{over} subtitle tracks"))
608+ && said.contains(&format!("at most {}", engine::mux::MAX_SUB_TRACKS)),
609+ "the refusal says how many were asked for and how many fit: {said}"
610+ );
611+ assert!(!out.exists(), "and no half-written file is left: {said}");
612+}
613+
614+/// A language stated the modern way (`LanguageBCP47`, no legacy element) leaves
615+/// with the file, in the element every reader looks at.
616+///
617+/// The loss used to survive the export: a 22-track Matroska listed
618+/// `2,subrip,English (UK) (SDH)` with an *empty* language field beside
619+/// neighbours that kept `ara` and `chi`, because the source stated `en` in an
620+/// element nothing here read. What is written is still the legacy element -- a
621+/// three-letter code is what Matroska's `Language` and an mp4's `mdhd` hold, and
622+/// ffmpeg 8.1.2 reads no `LanguageBCP47` at all.
623+#[test]
624+fn a_language_stated_the_modern_way_leaves_with_the_file() {
625+ let mut tracks =
626+ subtitle::of_matroska(&asset("test_subs_bcp47.mkv")).expect("read the fixture");
627+ assert_eq!(
628+ tracks.len(),
629+ 2,
630+ "the fixture carries two tracks: {tracks:?}"
631+ );
632+ for track in &mut tracks {
633+ track.path = asset(MEDIA);
634+ }
635+ assert_eq!(
636+ tracks.iter().map(|t| &*t.language).collect::<Vec<_>>(),
637+ ["eng", "fra"],
638+ "`en` and `fr` are read as the codes an export writes"
639+ );
640+
641+ let project = Project::single(asset(MEDIA), FRAMES).with_subtitles(tracks);
642+ let (out, back) = exported("bcp47", project, &[0, 1]);
643+ assert_eq!(
644+ back.iter().map(|t| &*t.language).collect::<Vec<_>>(),
645+ ["eng", "fra"],
646+ "and they are the codes the file states"
647+ );
648+ let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element");
649+ assert_eq!(
650+ raw[1].name, "Signs",
651+ "the title travels beside the language"
652+ );
653+ if let Some(listing) = ffmpeg_streams(&out) {
654+ assert!(
655+ listing.contains("(eng): Subtitle") && listing.contains("(fra): Subtitle"),
656+ "a second implementation reads both languages: {listing}"
657+ );
658+ }
267 std::fs::remove_file(&out).unwrap();659 std::fs::remove_file(&out).unwrap();
268 }660 }
269 661
@@ -275,23 +667,78 @@ fn the_plan_says_what_each_container_does_with_them() {
275 let plan = |format| engine::export::planned_subtitles(&project, format, Some(0));667 let plan = |format| engine::export::planned_subtitles(&project, format, Some(0));
276 assert_eq!(plan(Format::Hevc), "eng → embedded");668 assert_eq!(plan(Format::Hevc), "eng → embedded");
277 assert_eq!(plan(Format::Av1), "eng → embedded");669 assert_eq!(plan(Format::Av1), "eng → embedded");
278- assert_eq!(plan(Format::Mp4), "mkv only — an mp4 carries none");670+ // An mp4 carries them too, as `tx3g` -- so the card says what travels
279- assert_eq!(plan(Format::HevcMp4), "mkv only — an mp4 carries none");671+ // rather than which container to switch to. The refusal it used to print
672+ // ("mkv only — an mp4 carries none") was a claim about the container that
673+ // the container never made.
674+ assert_eq!(plan(Format::Mp4), "eng → embedded");
675+ assert_eq!(plan(Format::HevcMp4), "eng → embedded");
676+ assert_eq!(plan(Format::Av1Mp4), "eng → embedded");
280 assert_eq!(plan(Format::Wav), "none — this format is the sound alone");677 assert_eq!(plan(Format::Wav), "none — this format is the sound alone");
281- // No pick, and a pick nothing answers, are both "none" rather than a panic678+ // A track of *pictures* on a format that is the sound alone says what the
282- // or a lie.679+ // file cannot do rather than what the track cannot: the per-track reason
680+ // used to be pushed first, which left the sentence above unreachable for a
681+ // pick that was all bitmaps -- an MP3 with a PGS track picked read
682+ // "pictures; drawn, not written", a true sentence about the wrong thing.
683+ let mut pictures = track();
684+ pictures.bitmap = true;
685+ pictures.label = "PGS".into();
686+ let pgs = Project::single(asset(MEDIA), FRAMES).with_subtitles(vec![pictures]);
687+ assert_eq!(
688+ engine::export::planned_subtitles(&pgs, Format::Mp3, Some(0)),
689+ "none — this format is the sound alone"
690+ );
691+ // ...and on a container that carries text it is the *track* that cannot
692+ // travel, which is the other sentence and just as true: both are reachable.
693+ assert_eq!(
694+ engine::export::planned_subtitles(&pgs, Format::Hevc, Some(0)),
695+ "PGS — pictures; drawn, not written"
696+ );
697+ // Nothing picked is "none" whatever the format -- there is no track for a
698+ // container to have nowhere to put.
699+ assert_eq!(
700+ engine::export::planned_subtitles(&pgs, Format::Mp3, None),
701+ "none"
702+ );
703+ // No pick is "none" rather than a panic or a lie...
283 assert_eq!(704 assert_eq!(
284 engine::export::planned_subtitles(&project, Format::Hevc, None),705 engine::export::planned_subtitles(&project, Format::Hevc, None),
285 "none"706 "none"
286 );707 );
708+ // ...and a pick the project has no row for is *named*, like every other
709+ // reason a pick does not travel: an index nothing answers is a caller's bug
710+ // and the card is where a bug is seen, not the finished file.
287 assert_eq!(711 assert_eq!(
288 engine::export::planned_subtitles(&project, Format::Hevc, Some(9)),712 engine::export::planned_subtitles(&project, Format::Hevc, Some(9)),
289- "none"713+ "#9 — no such track"
290 );714 );
291- // A timeline that never had subtitles says the same thing.
292 let bare = Project::single(asset(MEDIA), FRAMES);715 let bare = Project::single(asset(MEDIA), FRAMES);
293 assert_eq!(716 assert_eq!(
294 engine::export::planned_subtitles(&bare, Format::Hevc, Some(0)),717 engine::export::planned_subtitles(&bare, Format::Hevc, Some(0)),
295- "none"718+ "#0 — no such track"
719+ );
720+ // ...and it costs its own row and not the others': the tracks around it
721+ // still travel, which is what made this one easy to miss.
722+ assert_eq!(
723+ engine::export::planned_subtitles(&project, Format::Hevc, [0, 99]),
724+ "eng → embedded; #99 — no such track"
725+ );
726+
727+ // Two picks are two tracks, named: the count first, because that is what the
728+ // row is answering, and the names after it because that is what a menu will
729+ // show.
730+ let two = Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks());
731+ assert_eq!(
732+ engine::export::planned_subtitles(&two, Format::Hevc, [0, 1]),
733+ "2 tracks → embedded (eng, fra — Signs)"
734+ );
735+ // ...and a pick that cannot travel costs its own row and not the other's:
736+ // the empty track is dropped by name, the real one still goes.
737+ let mut mixed = both_tracks();
738+ mixed[1].cues.clear();
739+ let mixed = Project::single(asset(MEDIA), FRAMES).with_subtitles(mixed);
740+ assert_eq!(
741+ engine::export::planned_subtitles(&mixed, Format::Hevc, [0, 1]),
742+ "eng → embedded; fra — Signs — no cues"
296 );743 );
297 }744 }
crates/engine/tests/import_mp4_subs.rsadded+231 -0
@@ -0,0 +1,231 @@
1+//! An mp4's subtitles come back *in*: what `mux` writes as `tx3g` timed text,
2+//! `subtitle::of_mp4` reads, so the default export format round-trips -- a file
3+//! edith wrote is a file edith opens with its subtitle tracks still on it.
4+//!
5+//! Two witnesses again, the other way round from `export_subs.rs`: our own
6+//! writer's file read by our own reader (the round trip), and a file **ffmpeg**
7+//! muxed read by the same reader -- so what is pinned here is the format and
8+//! not this project agreeing with itself.
9+//!
10+//! ```text
11+//! cargo test -p engine --release --test import_mp4_subs -- --nocapture
12+//! ```
13+
14+use std::path::PathBuf;
15+use std::process::Command;
16+use std::sync::Once;
17+use std::time::{Duration, Instant};
18+
19+use engine::export::{ExportSettings, Format};
20+use engine::scratch::Scratch;
21+use engine::subtitle::{self, SubtitleTrack};
22+use engine::{ExportHandle, Project};
23+
24+/// The media fixture: five seconds at 30 fps, a picture this box decodes and
25+/// encodes with nothing installed.
26+const MEDIA: &str = "test_av.mp4";
27+const FRAMES: u32 = 150;
28+/// What a cue may be out by: the track's own tick, a millisecond.
29+const SLACK_US: i64 = 1_000;
30+
31+/// The three cues both fixtures carry, and the times an export puts them at.
32+const WANT: [(i64, i64, &str); 3] = [
33+ (500_000, 1_500_000, "first line"),
34+ (2_000_000, 3_250_000, "second line\nwith a break"),
35+ (4_000_000, 4_750_000, "third line"),
36+];
37+
38+fn asset(name: &str) -> PathBuf {
39+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
40+ .join("../../assets")
41+ .join(name)
42+}
43+
44+fn pin_software() {
45+ static PIN: Once = Once::new();
46+ PIN.call_once(|| unsafe {
47+ std::env::set_var("VE_SW", "1");
48+ std::env::set_var("VE_SW_ENC", "1");
49+ });
50+}
51+
52+fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
53+ let started = Instant::now();
54+ while !handle.is_finished() {
55+ assert!(
56+ started.elapsed() < limit,
57+ "export did not finish in {limit:?}"
58+ );
59+ std::thread::sleep(Duration::from_millis(20));
60+ }
61+ handle.result().expect("a finished export has an outcome")
62+}
63+
64+fn near(got: i64, want: i64, what: &str) {
65+ assert!(
66+ (got - want).abs() <= SLACK_US,
67+ "{what}: {got} us is not within a millisecond of {want} us"
68+ );
69+}
70+
71+/// The two tracks `assets/test_subs.mkv` carries -- `eng` as `S_TEXT/UTF8` and
72+/// `fra` titled `Signs` as `S_TEXT/ASS`, the same three cues twice -- repointed
73+/// at the media this box can encode, exactly as `export_subs.rs` does it.
74+fn both_tracks() -> Vec<SubtitleTrack> {
75+ let mut tracks = subtitle::of_matroska(&asset("test_subs.mkv")).expect("read the fixture");
76+ assert_eq!(
77+ tracks.len(),
78+ 2,
79+ "the fixture carries two tracks: {tracks:?}"
80+ );
81+ for track in &mut tracks {
82+ track.path = asset(MEDIA);
83+ }
84+ tracks
85+}
86+
87+/// An mp4 export of both tracks, on disk.
88+fn exported_mp4(name: &str) -> Scratch {
89+ pin_software();
90+ let out = Scratch::file(&format!("ve_import_mp4_subs_{name}"), "mp4");
91+ let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
92+ let handle = engine::export::start(
93+ Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks()),
94+ meta,
95+ &out,
96+ &ExportSettings {
97+ format: Format::Mp4,
98+ subtitles: vec![0, 1],
99+ ..Default::default()
100+ },
101+ );
102+ wait(&handle, Duration::from_secs(300)).expect("the export finishes");
103+ out
104+}
105+
106+fn check_pair(tracks: &[SubtitleTrack], what: &str) {
107+ for track in tracks {
108+ println!(
109+ "{what}: {} track {:?} {:?}",
110+ track.label,
111+ track.track,
112+ track
113+ .cues
114+ .iter()
115+ .map(|c| (c.start_us, c.end_us, &c.text))
116+ .collect::<Vec<_>>()
117+ );
118+ }
119+ assert_eq!(tracks.len(), 2, "{what}: two tracks: {tracks:?}");
120+ // The language and the title, apart: `eng` is a language alone, `Signs` is
121+ // a French track's own name -- the pair `mdhd` and `trak/udta/name` hold.
122+ assert_eq!(tracks[0].label, "eng", "{what}");
123+ assert_eq!(tracks[1].label, "fra — Signs", "{what}");
124+ for track in tracks {
125+ assert_eq!(track.refused, None, "{what}: the track reads");
126+ assert!(!track.is_bitmap(), "{what}: timed text is not pictures");
127+ assert_eq!(
128+ track.cues.len(),
129+ 3,
130+ "{what}: the empty samples between the cues are not cues: {:?}",
131+ track.cues
132+ );
133+ for (cue, (start, end, text)) in track.cues.iter().zip(WANT) {
134+ near(cue.start_us, start, &format!("{what}: cue start"));
135+ near(cue.end_us, end, &format!("{what}: cue end"));
136+ assert_eq!(cue.text, text, "{what}: the words travel, breaks and all");
137+ assert!(cue.image.is_none(), "{what}: text, not a picture");
138+ }
139+ }
140+}
141+
142+/// The round trip: two tracks out as `tx3g`, the same two back in -- languages,
143+/// titles, words and times.
144+#[test]
145+fn an_mp4_export_comes_back_with_the_subtitles_it_left_with() {
146+ let out = exported_mp4("round");
147+ let tracks = subtitle::of_mp4(&out).expect("read our own mp4 back");
148+ println!(
149+ "our mp4 reads back as: {:?}",
150+ tracks
151+ .iter()
152+ .map(|t| (&t.label, t.track, t.cues.len()))
153+ .collect::<Vec<_>>()
154+ );
155+ check_pair(&tracks, "our own writer");
156+ // The picture is track 1 and the sound 2, so the text is 3 and 4 -- the
157+ // numbers a `.edith` row names, which is what makes the row openable.
158+ assert_eq!(
159+ tracks.iter().map(|t| t.track).collect::<Vec<_>>(),
160+ vec![Some(3), Some(4)]
161+ );
162+
163+ // ...and through the door a saved project comes back in by, which is the
164+ // point of the numbers above.
165+ let second = subtitle::open(&out, Some(4));
166+ assert_eq!(second.refused, None, "the saved row opens: {second:?}");
167+ assert_eq!(second.label, "fra — Signs");
168+ assert_eq!(second.cues.len(), 3);
169+ std::fs::remove_file(&out).unwrap();
170+}
171+
172+/// The same file read by the same door the *import button* goes through, which
173+/// is what makes this reachable rather than merely written.
174+#[test]
175+fn the_import_door_walks_an_mp4_for_its_subtitles() {
176+ let out = exported_mp4("import");
177+ let tracks =
178+ engine::PlaybackSession::parse_subtitles(&out).expect("the import door walks the mp4");
179+ check_pair(&tracks, "the import door");
180+ std::fs::remove_file(&out).unwrap();
181+}
182+
183+/// A file with no timed-text track: no tracks, no refusal, nothing invented.
184+#[test]
185+fn an_mp4_without_subtitles_reads_as_no_tracks_at_all() {
186+ let tracks = subtitle::of_mp4(&asset(MEDIA)).expect("the fixture opens");
187+ assert!(tracks.is_empty(), "nothing was invented: {tracks:?}");
188+ let raw = engine::demux::mp4_subtitles(&asset(MEDIA)).expect("the walk itself");
189+ assert!(raw.is_empty(), "{raw:?}");
190+}
191+
192+/// The other implementation's file: what `ffmpeg -c:s mov_text` muxes, read by
193+/// this reader. Skipped where there is no ffmpeg on the box -- the test is not
194+/// about this machine's packages.
195+#[test]
196+fn an_ffmpeg_muxed_mov_text_track_reads_the_same_way() {
197+ let out = Scratch::file("ve_import_mp4_subs_ffmpeg", "mp4");
198+ let made = Command::new("ffmpeg")
199+ .args(["-y", "-v", "error", "-i"])
200+ .arg(asset("test_subs.mkv"))
201+ .args([
202+ "-map", "0:v", "-map", "0:s", "-c:v", "copy", "-c:s", "mov_text",
203+ ])
204+ .arg(&*out)
205+ .status();
206+ let Ok(status) = made else {
207+ println!("no ffmpeg on this box: the round trip is the only witness");
208+ return;
209+ };
210+ assert!(status.success(), "ffmpeg refused to mux the fixture");
211+
212+ let tracks = subtitle::of_mp4(&out).expect("read ffmpeg's mp4");
213+ println!(
214+ "ffmpeg's mp4 reads back as: {:?}",
215+ tracks
216+ .iter()
217+ .map(|t| (&t.label, t.track, t.cues.len()))
218+ .collect::<Vec<_>>()
219+ );
220+ // ffmpeg's timed-text tracks are timed in *microseconds* where ours are in
221+ // milliseconds, and it writes the same `trak/udta/name` for the title: the
222+ // two things a reader of one muxer's quirks would get wrong.
223+ check_pair(&tracks, "ffmpeg's muxer");
224+ let raw = engine::demux::mp4_subtitles(&out).expect("the walk itself");
225+ assert_eq!(
226+ raw[1].language, "fra",
227+ "the language is the file's: {raw:?}"
228+ );
229+ assert_eq!(raw[1].name, "Signs", "...and the title is beside it");
230+ std::fs::remove_file(&out).unwrap();
231+}
crates/engine/tests/subtitles.rsmodified+186 -0
@@ -291,6 +291,131 @@ fn a_project_keeps_its_subtitles_across_a_save() {
291 );291 );
292 }292 }
293 293
294+/// The two-door import: the parse runs with no session in hand -- which is what
295+/// lets a front-end run it off the render thread -- and the tracks it hands back
296+/// go on the timeline for the cost of a push. Same dedupe as the one-call door,
297+/// so the same file twice is still one set of rows, and what lands is saved and
298+/// loaded as a reference exactly like an `import_subtitles` row.
299+#[test]
300+fn parsed_tracks_can_be_handed_to_a_session_without_it_reading_the_file() {
301+ let dir = scratch("handoff");
302+ let media = dir.join("test_av.mp4");
303+ std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
304+ let mkv = dir.join("test_subs.mkv");
305+ std::fs::copy(asset("test_subs.mkv"), &mkv).expect("copy the subtitle fixture");
306+
307+ // The door a background executor calls: no `&self`, so nothing about the
308+ // session is borrowed while the container is walked.
309+ let tracks =
310+ engine::PlaybackSession::parse_subtitles(&mkv).expect("the mkv is walked off-thread");
311+ assert_eq!(tracks.len(), 2, "both tracks of the fixture");
312+ // Owned data all the way down, so the parse may run on a background task
313+ // and its result be sent back: a track holding a handle would put the walk
314+ // back on the thread that draws.
315+ fn sendable<T: Send + 'static>(_: &T) {}
316+ sendable(&tracks);
317+
318+ let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");
319+ session.set_gain(0.0);
320+ assert_eq!(session.add_subtitle_tracks(tracks.clone()), 2, "both go on");
321+ // The same tracks again are the same subtitles: the (path, track) dedupe is
322+ // what a front-end's "already on the timeline" line falls out of.
323+ assert_eq!(session.add_subtitle_tracks(tracks), 0, "and no repeat rows");
324+ assert_eq!(session.subtitles().len(), 2);
325+ // And the one-call door agrees with it, over the very same file.
326+ assert_eq!(session.import_subtitles(&mkv).expect("no error"), 0);
327+ assert_eq!(session.subtitles()[0].cues, expected());
328+
329+ let project = dir.join("cut.edith");
330+ session.save_project(&project).expect("save");
331+ let back = engine::PlaybackSession::open_project(&project).expect("open the project");
332+ assert_eq!(
333+ back.subtitles().iter().map(|t| t.track).collect::<Vec<_>>(),
334+ session
335+ .subtitles()
336+ .iter()
337+ .map(|t| t.track)
338+ .collect::<Vec<_>>(),
339+ "a handed-over row is a reference like any other"
340+ );
341+ assert_eq!(back.subtitles()[1].cues, expected());
342+}
343+
344+/// Whatever an import added comes back off: three tracks go on, the middle one
345+/// is removed, and what is left is the other two *in the order they were added*
346+/// -- a save then writes exactly those two references and a load reads back
347+/// exactly them. The bad index is a refusal naming the index, not a silent
348+/// no-op, since a front-end holding a stale row has picked the wrong one.
349+#[test]
350+fn a_subtitle_row_can_be_removed_and_the_survivors_round_trip() {
351+ let dir = scratch("remove");
352+ let media = dir.join("test_av.mp4");
353+ std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
354+ // Three files rather than three tracks of one: `add_subtitles` dedupes by
355+ // (path, track), so three names are three rows.
356+ for name in ["a.srt", "b.srt", "c.srt"] {
357+ std::fs::copy(data("test_subs.srt"), dir.join(name)).expect("copy the subtitle fixture");
358+ }
359+
360+ let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");
361+ session.set_gain(0.0);
362+ for name in ["a.srt", "b.srt", "c.srt"] {
363+ assert_eq!(
364+ session
365+ .import_subtitles(&dir.join(name))
366+ .expect("the .srt imports"),
367+ 1
368+ );
369+ }
370+ assert_eq!(session.subtitles().len(), 3);
371+
372+ session.remove_subtitles(1).expect("the middle row goes");
373+ let names: Vec<String> = session
374+ .subtitles()
375+ .iter()
376+ .map(|t| {
377+ t.path
378+ .file_name()
379+ .expect("a name")
380+ .to_string_lossy()
381+ .into_owned()
382+ })
383+ .collect();
384+ assert_eq!(names, vec!["a.srt", "c.srt"], "the survivors keep their order");
385+ assert_eq!(session.subtitles()[0].cues, expected(), "and their cues");
386+
387+ let project = dir.join("cut.edith");
388+ session.save_project(&project).expect("save");
389+ let text = std::fs::read_to_string(&project).expect("read the project back");
390+ assert!(
391+ text.contains("\nsubtitle - a.srt\n") && text.contains("\nsubtitle - c.srt\n"),
392+ "the survivors are written, by reference: {text}"
393+ );
394+ assert!(
395+ !text.contains("b.srt"),
396+ "and the removed one is not: {text}"
397+ );
398+
399+ let back = engine::PlaybackSession::open_project(&project).expect("open the project");
400+ assert_eq!(
401+ back.subtitles()
402+ .iter()
403+ .map(|t| t.path.file_name().expect("a name").to_string_lossy().into_owned())
404+ .collect::<Vec<_>>(),
405+ vec!["a.srt", "c.srt"],
406+ "and a load is the same two, in the same order"
407+ );
408+ assert_eq!(back.subtitles()[1].cues, expected());
409+
410+ // A row that is not there says so, naming the index a front-end passed.
411+ let why = session
412+ .remove_subtitles(9)
413+ .expect_err("there is no row 9")
414+ .to_string();
415+ assert!(why.contains('9') && why.contains("subtitle"), "{why}");
416+ assert_eq!(session.subtitles().len(), 2, "and nothing moved");
417+}
418+
294 /// A bitmap track survives a save the same way a text one does, and for the419 /// A bitmap track survives a save the same way a text one does, and for the
295 /// same reason: a `.edith` holds the file and the track number, never a cue, so420 /// same reason: a `.edith` holds the file and the track number, never a cue, so
296 /// what comes back is what the file still says. The pictures are read out of421 /// what comes back is what the file still says. The pictures are read out of
@@ -449,6 +574,67 @@ fn importing_something_that_is_not_a_subtitle_says_so() {
449 assert_eq!(session.subtitles().len(), 0, "and nothing was added");574 assert_eq!(session.subtitles().len(), 0, "and nothing was added");
450 }575 }
451 576
577+/// The Matroska that is the subtitles alone: `.mks`, what a subtitle release
578+/// ships beside the film, imported by the door an `.mkv` is imported by.
579+///
580+/// The refusal it used to get -- *"mks" is not a subtitle format this reads* --
581+/// was a claim about a container this very binary parses: the bytes are a
582+/// Matroska's and the same walk reads them, so only the extension list said no.
583+#[test]
584+fn a_matroska_that_is_the_subtitles_alone_imports_like_any_other() {
585+ let dir = scratch("mks");
586+ let media = dir.join("test_av.mp4");
587+ std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
588+
589+ let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");
590+ session.set_gain(0.0);
591+ let added = session
592+ .import_subtitles(&asset("test_subs.mks"))
593+ .expect("a .mks is a Matroska and imports as one");
594+ assert_eq!(added, 2, "both its tracks came in");
595+ let labels: Vec<&str> = session.subtitles().iter().map(|t| &*t.label).collect();
596+ assert_eq!(labels, ["eng", "fra — Signs"], "with their own names");
597+ for track in session.subtitles() {
598+ assert_eq!(track.refused, None, "{} parses", track.label);
599+ assert_eq!(track.cues, expected(), "{} holds the cues", track.label);
600+ }
601+}
602+
603+/// A track that states its language the way a modern muxer states it --
604+/// `LanguageBCP47` and no legacy `Language` element at all -- keeps that
605+/// language, where it used to come in as `und`.
606+///
607+/// The shape of every English track of a dual-language remux and all four
608+/// of the 17-track library file ones: they read as `und` while the file said `en`,
609+/// and the loss survived into the exported file's track list.
610+#[test]
611+fn a_track_that_states_its_language_the_modern_way_keeps_it() {
612+ // The fixture is what it claims to be: the modern element is in it and the
613+ // legacy one is not, so what is being read is the new element and not a
614+ // leftover of the old one.
615+ let bytes = std::fs::read(asset("test_subs_bcp47.mkv")).expect("the fixture is there");
616+ assert!(
617+ bytes.windows(3).any(|w| w == [0x22, 0xB5, 0x9D]),
618+ "the fixture states LanguageBCP47"
619+ );
620+ for legacy in [b"\x22\xb5\x9c\x83eng".as_slice(), b"\x22\xb5\x9c\x83fra"] {
621+ assert!(
622+ !bytes.windows(legacy.len()).any(|w| w == legacy),
623+ "and states no legacy Language element for its subtitle tracks"
624+ );
625+ }
626+
627+ let tracks = subtitle::of_matroska(&asset("test_subs_bcp47.mkv")).expect("the mkv is walked");
628+ let languages: Vec<&str> = tracks.iter().map(|t| &*t.language).collect();
629+ assert_eq!(languages, ["eng", "fra"], "`en` is English, `fr` is French");
630+ // ...and the same file with the legacy element reads exactly the same, which
631+ // is the point: which element a muxer chose is not something a row shows.
632+ let legacy = subtitle::of_matroska(&asset("test_subs.mkv")).expect("the mkv is walked");
633+ let want: Vec<&str> = legacy.iter().map(|t| &*t.label).collect();
634+ let got: Vec<&str> = tracks.iter().map(|t| &*t.label).collect();
635+ assert_eq!(got, want, "the two files list the same two tracks");
636+}
637+
452 /// An EBML element: its id as it is written in the file, then an 8-byte638 /// An EBML element: its id as it is written in the file, then an 8-byte
453 /// length, which is always a legal encoding of one.639 /// length, which is always a legal encoding of one.
454 fn element(id: &[u8], body: &[u8]) -> Vec<u8> {640 fn element(id: &[u8], body: &[u8]) -> Vec<u8> {
scripts/gen_fixtures.shmodified+37 -0
@@ -211,6 +211,33 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=5 \
211 -c:s:0 srt -metadata:s:s:0 language=eng \211 -c:s:0 srt -metadata:s:s:0 language=eng \
212 -c:s:1 ass -metadata:s:s:1 language=fra -metadata:s:s:1 title=Signs \212 -c:s:1 ass -metadata:s:s:1 language=fra -metadata:s:s:1 title=Signs \
213 assets/test_subs.mkv213 assets/test_subs.mkv
214+# The same two tracks with no picture and no sound at all: `.mks`, the Matroska
215+# extension that is the subtitles alone (what a subtitle release ships beside
216+# the film). Refused by name until the container gate learned every Matroska
217+# extension rather than the two that carry a film -- the very reader that walks
218+# a `.mkv` walks this.
219+ffmpeg -y -i crates/engine/tests/data/test_subs.srt \
220+ -i crates/engine/tests/data/test_subs.ass -map 0:0 -map 1:0 \
221+ -c:s:0 srt -metadata:s:s:0 language=eng \
222+ -c:s:1 ass -metadata:s:s:1 language=fra -metadata:s:s:1 title=Signs \
223+ -f matroska assets/test_subs.mks
224+# ...and the same file stating its languages the way a modern muxer does: in
225+# `LanguageBCP47` (0x22B59D) and *not* in the legacy `Language` (0x22B59C),
226+# which is the shape of every English track of a dual-language remux and
227+# `a 17-track library file`. ffmpeg writes only the legacy element (8.1.2 does not read
228+# the BCP-47 one either), so the element is swapped in place afterwards: the
229+# 4-byte id, then the length as a two-byte VINT (`40 02`, a legal non-minimal
230+# encoding) so the tag is two bytes and the element stays the eight bytes it
231+# was -- every enclosing size in the file survives untouched.
232+python3 - <<'PATCH'
233+data = open("assets/test_subs.mkv", "rb").read()
234+size = len(data)
235+for legacy, tag in ((b"eng", b"en"), (b"fra", b"fr")):
236+ data = data.replace(b"\x22\xb5\x9c\x83" + legacy, b"\x22\xb5\x9d\x40\x02" + tag)
237+assert len(data) == size, "the swap has to be size-for-size"
238+assert b"\x22\xb5\x9d" in data, "and it has to have happened"
239+open("assets/test_subs_bcp47.mkv", "wb").write(data)
240+PATCH
214 # HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as241 # HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as
215 # test_hevc.mp4 so the tests measure the container and nothing else, `-g 30` for242 # test_hevc.mp4 so the tests measure the container and nothing else, `-g 30` for
216 # the same reason test_av1.mkv has it (a second keyframe to seek to), and the243 # the same reason test_av1.mkv has it (a second keyframe to seek to), and the
@@ -475,4 +502,14 @@ ffmpeg -y -f lavfi -i "testsrc2=size=320x180:rate=24:duration=30" \
475 -f lavfi -i "aevalsrc=sin(2*PI*(200*t+80*t*t)):s=48000:d=30" \502 -f lavfi -i "aevalsrc=sin(2*PI*(200*t+80*t*t)):s=48000:d=30" \
476 -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p -g 120 \503 -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p -g 120 \
477 -c:a libopus -b:a 128k assets/test_seek_chirp.mkv504 -c:a libopus -b:a 128k assets/test_seek_chirp.mkv
505+# The lopsided container: 2 s of picture under 60 s of sound, which is what a
506+# still with a song over it or a botched remux looks like from the outside. The
507+# point is the *denominator* -- a file 60 s long whose video track is 2 s long
508+# reports thirty times its real byte rate if the bitrate row divides by the
509+# picture rather than by the file (`crates/engine/tests/bitrate.rs`). Nothing
510+# else here has this shape, which is exactly why it is here.
511+ffmpeg -y -f lavfi -i "testsrc2=size=320x240:rate=30:duration=2" \
512+ -f lavfi -i "sine=frequency=440:duration=60" \
513+ -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
514+ -c:a aac -b:a 64k assets/test_short_video_long_audio.mp4
478 echo "fixtures written to assets/"515 echo "fixtures written to assets/"