From 28e2853243cdd45d859f1d2819b21f41cef4c5aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 12 Aug 2026 19:51:44 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(subtitles):=20as=20many=20trac?= =?UTF-8?q?ks=20as=20you=20want,=20embedded=20in=20the=20export?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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). --- crates/app/src/keymap.rs | 25 +- crates/app/src/main.rs | 1283 +++++++++++++++++++++--- crates/engine/src/demux.rs | 606 ++++++++++- crates/engine/src/edith.rs | 2 + crates/engine/src/export.rs | 189 ++-- crates/engine/src/lib.rs | 2 +- crates/engine/src/mux.rs | 470 +++++++-- crates/engine/src/playback.rs | 83 +- crates/engine/src/project.rs | 24 + crates/engine/src/subtitle.rs | 165 ++- crates/engine/tests/bitrate.rs | 292 ++++++ crates/engine/tests/export_subs.rs | 513 +++++++++- crates/engine/tests/import_mp4_subs.rs | 231 +++++ crates/engine/tests/subtitles.rs | 186 ++++ scripts/gen_fixtures.sh | 37 + 15 files changed, 3733 insertions(+), 375 deletions(-) create mode 100644 crates/engine/tests/bitrate.rs create mode 100644 crates/engine/tests/import_mp4_subs.rs diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 7f181e0..09dc395 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -92,6 +92,8 @@ actions! { AddAudioLane, RemoveVideoLane, RemoveAudioLane, + AddSubtitleTrack, + RemoveSubtitleTrack, ToggleMute, VolumeUp, VolumeDown, @@ -146,6 +148,8 @@ impl ActionId { ActionId::AddAudioLane => "Add an audio track", ActionId::RemoveVideoLane => "Remove the last video track (it must be empty)", ActionId::RemoveAudioLane => "Remove the last audio track (it must be empty)", + ActionId::AddSubtitleTrack => "Add subtitles from a file…", + ActionId::RemoveSubtitleTrack => "Remove the picked subtitle track", ActionId::ToggleMute => "Mute / Unmute", ActionId::VolumeUp => "Volume up", ActionId::VolumeDown => "Volume down", @@ -195,6 +199,8 @@ impl ActionId { ActionId::AddAudioLane => "add-audio-lane", ActionId::RemoveVideoLane => "remove-video-lane", ActionId::RemoveAudioLane => "remove-audio-lane", + ActionId::AddSubtitleTrack => "add-subtitle-track", + ActionId::RemoveSubtitleTrack => "remove-subtitle-track", ActionId::ToggleMute => "toggle-mute", ActionId::VolumeUp => "volume-up", ActionId::VolumeDown => "volume-down", @@ -264,6 +270,12 @@ impl ActionId { // Not a view setting despite being a pointer aid: it decides where // a drag actually lands, which is an edit and not a magnification. | ActionId::ToggleSnap + // The subtitle pair is a track pair like the lanes above it: what + // they add is on the timeline and goes into the file an export + // writes, where the toggle two headings down only decides whether + // this window draws it. + | ActionId::AddSubtitleTrack + | ActionId::RemoveSubtitleTrack | ActionId::RemoveAudioLane => Category::Editing, ActionId::ToggleMute | ActionId::VolumeUp @@ -723,6 +735,13 @@ impl Keymap { // key beside it. b(ActionId::RemoveVideoLane, "b", true), b(ActionId::RemoveAudioLane, "a", true), + // The subtitle pair reads the same way: the unshifted initial + // adds one -- "s" is free, the save is the *ctrl* chord -- and a + // ctrl chord takes it back. Ctrl+s is that save, so the removal + // takes the other letter subtitles already answer to here: "t" + // shows and hides them, and ctrl+t takes one off the timeline. + b(ActionId::AddSubtitleTrack, "s", false), + b(ActionId::RemoveSubtitleTrack, "t", true), b(ActionId::ToggleMute, "m", false), // The unshifted pair, which is what gpui reports for those two // keys ("=" and "-", platform.rs:862): the volume keys every @@ -1023,7 +1042,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 44); + assert_eq!(k.entries().len(), 46); assert_eq!(k.lookup("f1", false), Some(ActionId::ShowActions)); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); // The seek keys: bare arrows a frame, ctrl arrows a second, and the two @@ -1062,6 +1081,10 @@ mod tests { // press. Ctrl+v is the paste, so the video one sits beside it. assert_eq!(k.lookup("b", true), Some(ActionId::RemoveVideoLane)); assert_eq!(k.lookup("a", true), Some(ActionId::RemoveAudioLane)); + // The subtitle pair, the third kind of track: the initial adds and the + // subtitle letter's chord takes it back. + assert_eq!(k.lookup("s", false), Some(ActionId::AddSubtitleTrack)); + assert_eq!(k.lookup("t", true), Some(ActionId::RemoveSubtitleTrack)); assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute)); assert_eq!(k.lookup("q", false), Some(ActionId::Equalizer)); // The volume pair is the unshifted one, so neither needs a modifier diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 64be848..ff6a30e 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -19,7 +19,7 @@ use engine::limiter::Limiter; use engine::project::{Edge, Lane, LaneKind, Source, Speed}; use engine::scale::FitPolicy; use engine::tonemap::Preset; -use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession}; +use engine::{Clip, Codec, ExportHandle, Frame, MediaBitrate, PlaybackSession}; use gpui::{ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, DragMoveEvent, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, @@ -222,6 +222,16 @@ const LIST_CHAR_W: f32 = 6.; /// The fewest characters a clipped name is cut to, however narrow the column /// gets: past this there is nothing on either side of the gap to read. const LIST_CLIP_MIN: usize = 5; +/// How long the export card's Subtitles line may get before it counts tracks +/// instead of naming them ([`subtitle_plan`]). Three lines of that row's value +/// box, at [`LIST_CHAR_W`] to a character: [`EXPORT_W`] less the row's padding +/// and gap, its tick and [`EXPORT_KEY_W`] key column, and the word "Subtitles" +/// in front of the value. Not a track count -- what walks the Destination row +/// off the bottom of the card is the *wrapping*, and thirty-five one-word +/// labels wrap less than three long ones. +const SUB_PLAN_CHARS: usize = (3. + * (EXPORT_W - 12. - 12. - (10. + 8. + EXPORT_KEY_W + 8. + 9. * LIST_CHAR_W)) + / LIST_CHAR_W) as usize; /// The one key name this file still spells out, and gpui's spelling of it: it /// is the way out of a capture and out of the overlay, and both have to work @@ -1153,6 +1163,12 @@ struct Player { /// presence means "asked" -- and an empty list is a silent file, which is /// exactly one row and no stream tags. streams: HashMap>, + /// What each source is coded at, read off its header once and kept: what a + /// properties card says about a file's rate. Filled like `streams` -- + /// presence means "asked" -- and the inner `None` is "asked, not answered + /// yet", which the card draws as an ellipsis: the probe walks a Matroska's + /// clusters, so a big film answers in seconds rather than at once. + bitrates: HashMap>, /// How big each still source's picture is, read from its header once and /// kept -- what a library row and its card say about a file that has no /// streams to describe. Filled like `streams`: presence means "asked", and @@ -1623,6 +1639,11 @@ impl Player { // through the × in its own header. ActionId::RemoveVideoLane => self.remove_last_lane(LaneKind::Video, cx), ActionId::RemoveAudioLane => self.remove_last_lane(LaneKind::Audio, cx), + // The same chooser the + S button opens, and the picked row -- the + // one the panel draws highlighted -- for the removal: the × on any + // other row is that row's own door, and both doors are one call. + ActionId::AddSubtitleTrack => self.pick_and_add_subtitles(cx), + ActionId::RemoveSubtitleTrack => self.remove_subtitle_track(self.sub_track, cx), ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx), ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx), ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx), @@ -2716,7 +2737,8 @@ impl Player { self.reset_after_reseek(); self.notice = Some( format!( - "{count} SILENCES CUT {reach} — {saved:.1}s shorter, {} takes it back", + "{count} SILENCES CUT {reach} — {} shorter, {} takes it back", + secs_label(saved), self.keymap.display(ActionId::Undo) ) .into(), @@ -3242,6 +3264,26 @@ impl Player { }) .detach(); } + // What each file is coded at, for the card that says so. Header and + // sample table only, but a Matroska indexes no samples and its open + // walks every cluster header -- 6.7 s on a 12.9 GB film -- so this of + // all of them cannot be on the render thread. + for path in unseen_paths(session.sources(), &self.bitrates) { + self.bitrates.insert(path.clone(), None); + let probed = cx.background_executor().spawn({ + let path = path.clone(); + async move { engine::probe_bitrate(&path) } + }); + cx.spawn(async move |this, cx| { + let probed = probed.await; + this.update(cx, |this, cx| { + this.bitrates.insert(path, Some(probed)); + cx.notify(); + }) + .ok(); + }) + .detach(); + } // Which decoder each file will run on, for the row that says so before // a frame of it plays. Off the render thread like the streams above: a // stream the plugin takes costs one VA-API init (~90 ms) to answer. @@ -3322,14 +3364,17 @@ impl Player { return; } let meta = *session.meta(); - let key = (settings, (meta.width, meta.height)); + // Cloned rather than copied: the settings carry the picked subtitle + // rows, which is a `Vec` ([`engine::export::ExportSettings`]). + let key = (settings.clone(), (meta.width, meta.height)); if self .export_seat - .is_some_and(|(asked, size, _)| (asked, size) == key) + .as_ref() + .is_some_and(|(asked, size, _)| (asked, size) == (&key.0, &key.1)) { return; } - self.export_seat = Some((key.0, key.1, None)); + self.export_seat = Some((key.0.clone(), key.1, None)); let probed = cx .background_executor() .spawn(async move { engine::export::planned_video(&meta, &settings) }); @@ -3341,7 +3386,7 @@ impl Player { if let Some(seat) = this .export_seat .as_mut() - .filter(|(asked, size, _)| (*asked, *size) == key) + .filter(|(asked, size, _)| (asked, size) == (&key.0, &key.1)) { seat.2 = probed; } @@ -3956,6 +4001,7 @@ impl Player { self.close_silence(); self.waves.clear(); self.streams.clear(); + self.bitrates.clear(); self.sizes.clear(); // Scanned off sources that are not in the library any more. self.silence_levels.clear(); @@ -4138,8 +4184,8 @@ impl Player { // All that is left here is to hang everything derived from it off the // window -- the clock, the title, where an export and a save go -- and // that is arithmetic, not a read. - match landed { - Landed::Read => {} + let subs = match landed { + Landed::Read(subs) => subs, what => { self.opening = None; match what { @@ -4150,7 +4196,7 @@ impl Player { self.notice = Some(text.into()); cx.notify(); } - Landed::Read => unreachable!("matched above"), + Landed::Read(_) => unreachable!("matched above"), } // The line a launch has always printed, now printed when the // file actually arrives: it is the mark that says the timeline @@ -4167,7 +4213,7 @@ impl Player { } return; } - } + }; // An empty window has no library to add to yet: the file opens one, and // the timeline under it stays empty, because an import is an import // whether or not a session was already up. A file *named at launch* is @@ -4178,44 +4224,27 @@ impl Player { // section shows and what the overlay draws. With no timeline open there // is nothing for the cues to be timed against, and it says so. if is_subtitle(path) { - let text = match self - .session - .as_mut() - .map(|session| session.import_subtitles(path)) - { - Some(Ok(0)) => format!("{} is already on the timeline", file_name(path)), - Some(Ok(_)) => format!( - "SUBTITLES {} — showing over the picture, {} hides them", - file_name(path), - self.keymap.display(ActionId::ToggleSubtitles) - ), - Some(Err(e)) => format!("SUBTITLE IMPORT FAILED: {e}"), - None => { - "NO SUBTITLES ADDED — open a file for them to run against first".to_string() - } - }; - eprintln!("{text}"); - self.notice = Some(text.into()); - cx.notify(); + self.take_subtitles(path, subs, cx); return; } let text = match self.session.as_mut().map(|session| session.import(path)) { Some(Ok(_)) => { // The file's own subtitle tracks with it, exactly as an open // takes them: an import is the other door the same file arrives - // through. - let subs = self + // through. The cues were read on the worker + // ([`read_ahead`]); what happens here is the push. + let tail = self .session .as_mut() - .and_then(|session| subtitle_notice(session, path)) + .and_then(|session| subtitle_tail(session, subs)) .unwrap_or_default(); format!( - "IMPORTED {} to the library — drag it onto a lane to place it{subs}", + "IMPORTED {} to the library — drag it onto a lane to place it{tail}", file_name(path) ) } Some(Err(e)) => format!("IMPORT FAILED: {e}"), - None => self.open_media(path, false), + None => self.open_media(path, false, subs), }; eprintln!("{text}"); self.notice = Some(text.into()); @@ -4231,8 +4260,8 @@ impl Player { /// `place` is the difference between the two doors that come here: a file /// *opened* is the timeline, one *imported* into an empty window fills the /// library and leaves the lanes empty for a drag. - fn open_media(&mut self, path: &std::path::Path, place: bool) -> String { - self.install_media(path, open_session(path, place), place) + fn open_media(&mut self, path: &std::path::Path, place: bool, subs: Subs) -> String { + self.install_media(path, open_session(path, place, subs), place) } /// The second half of it: everything the window derives from a session that @@ -4288,7 +4317,9 @@ impl Player { if self.exporting().is_some() { return; } - let picked = cx.background_executor().spawn(async { pick_file() }); + let picked = cx + .background_executor() + .spawn(async { pick_file("edith — import") }); cx.spawn(async move |this, cx| { let picked = picked.await; this.update(cx, |this, cx| match picked { @@ -4309,6 +4340,179 @@ impl Player { .detach(); } + /// The `+ S` button and its key: asks the desktop for a file and takes the + /// subtitle tracks out of it -- a standalone `.srt`/`.vtt`/`.ass` is one of + /// them, a Matroska however many are inside. Only the subtitles: the file + /// itself does not join the library, which is what the Import button beside + /// this one is for. + /// + /// The chooser is another process and the user may sit in it, so it runs on + /// a background thread, exactly as [`Player::pick_and_import`] does. + fn pick_and_add_subtitles(&mut self, cx: &mut Context) { + // What dims the `+ S` button, asked here as well so the key answers the + // same question -- and *before* the chooser rather than after it: a door + // that opens a dialog, waits for a file and only then says the timeline + // was never there is the second door disagreeing with the first. + if let Some(why) = self.enable(ActionId::AddSubtitleTrack, None).why() { + let text = format!("NO SUBTITLES ADDED — {why}"); + eprintln!("{text}"); + self.notice = Some(text.into()); + cx.notify(); + return; + } + let picked = cx + .background_executor() + .spawn(async { pick_file("edith — subtitles to add") }); + cx.spawn(async move |this, cx| { + let picked = picked.await; + this.update(cx, |this, cx| match picked { + Ok(Some(path)) => this.add_subtitles(&path, cx), + // Cancelled: the user already knows what happened. + Ok(None) => {} + Err(text) => { + eprintln!("{text}"); + this.notice = Some(text.into()); + cx.notify(); + } + }) + .ok(); + }) + .detach(); + } + + /// Takes a file's subtitle tracks onto the timeline, off the render thread. + /// The walk reads the whole container for its cues + /// (`engine::PlaybackSession::parse_subtitles`) -- ~200 ms on a two-hour 4K + /// remux and 1.3 s on a cold 3 GB one -- and a button that costs the window + /// that many frames is a button that freezes it. So the *parse* is the + /// worker's, whole, and the UI thread only pushes what came back + /// ([`PlaybackSession::add_subtitle_tracks`]): no borrow crosses the await, + /// because the parse is an associated fn that owns nothing. + fn add_subtitles(&mut self, path: &std::path::Path, cx: &mut Context) { + // Nothing to time the cues against: said now rather than after a walk + // of a 25 GB file that was never going to be kept. + if self.session.is_none() { + self.landed_subtitles(path, None, cx); + return; + } + self.notice = Some(format!("READING {} for subtitles…", file_name(path)).into()); + let parsed = cx.background_executor().spawn({ + let path = path.to_path_buf(); + async move { engine::PlaybackSession::parse_subtitles(&path) } + }); + let path = path.to_path_buf(); + cx.spawn(async move |this, cx| { + let parsed = parsed.await; + this.update(cx, |this, cx| { + // The dedupe lives inside the push, so a second `+ S` on the + // same file still answers 0 and still says so below. + let added = this + .session + .as_mut() + .map(|session| parsed.map(|tracks| session.add_subtitle_tracks(tracks))); + this.landed_subtitles(&path, added, cx); + }) + .ok(); + }) + .detach(); + cx.notify(); + } + + /// Every subtitle track a `.srt`/`.vtt`/`.ass` carries, onto the timeline + /// and nowhere else: they are not clips and land on no lane. The cues came + /// off the worker that read the file ([`read_ahead`]), like every other + /// door's do, and what is left here is the push. The engine dedupes by + /// (file, track), so the same `.srt` twice is one row and says so. + fn take_subtitles(&mut self, path: &std::path::Path, subs: Subs, cx: &mut Context) { + let added = self + .session + .as_mut() + .map(|session| subs.map(|tracks| session.add_subtitle_tracks(tracks))); + self.landed_subtitles(path, added, cx); + } + + /// What the timeline says once the tracks are on it, whichever worker did + /// the reading: the `+ S` button and its key ([`Self::add_subtitles`]), a + /// dropped or imported subtitle file ([`Self::take_subtitles`]), and a + /// window with nothing to time cues against all word the outcome here, + /// once, so no two doors can drift apart. + fn landed_subtitles( + &mut self, + path: &std::path::Path, + added: Option>, + cx: &mut Context, + ) { + let text = match added { + Some(Ok(0)) => format!("{} is already on the timeline", file_name(path)), + Some(Ok(n)) => format!( + "SUBTITLES {} — {n} track(s), showing over the picture, {} hides them", + file_name(path), + self.keymap.display(ActionId::ToggleSubtitles) + ), + Some(Err(e)) => format!("SUBTITLE IMPORT FAILED: {e}"), + None => "NO SUBTITLES ADDED — open a file for them to run against first".to_string(), + }; + eprintln!("{text}"); + self.notice = Some(text.into()); + cx.notify(); + } + + /// The × on a subtitle row, and the stroke that takes the picked one off: + /// the track leaves the timeline and the pick moves with it. Every index + /// past the one that went moves down + /// ([`engine::Project::remove_subtitles`]), so a pick left where it was + /// would name a *different* track -- and the pick is what an export writes + /// into the file. + /// + /// Not an undo step: subtitles are not on the history's snapshots, so the + /// way back is importing the file again. The notice says that rather than + /// promising a ctrl+z that would do nothing. + fn remove_subtitle_track(&mut self, track: usize, cx: &mut Context) { + // The one availability oracle, for the same reason the × on a row and + // the stroke are one call: an empty list is not a failure, it is an + // action with nothing to act on, and the engine's "there is no subtitle + // track 0" is an index nobody typed. A real removal that fails still + // says what the engine said, below. + if let Some(why) = self.enable(ActionId::RemoveSubtitleTrack, None).why() { + let text = format!("NO SUBTITLES REMOVED — {why}"); + eprintln!("{text}"); + self.notice = Some(text.into()); + cx.notify(); + return; + } + // Read before it goes: a notice naming an index names nothing. + let name = self + .session + .as_ref() + .and_then(|session| sub_pick_name(session.subtitles(), track)) + .unwrap_or_else(|| format!("subtitle track {track}")); + let text = match self + .session + .as_mut() + .map(|session| session.remove_subtitles(track)) + { + Some(Ok(())) => { + let left = self + .session + .as_ref() + .map_or(0, |session| session.subtitles().len()); + self.sub_track = sub_pick_after_removal(self.sub_track, track, left); + // The drawn cue is keyed by that index ([`Player::sub_picture`]) + // and the index now stands for another track. + // + // ponytail: its atlas tile is not released -- `close_session`'s + // note, for its reason and with its upgrade path. + self.sub_image = None; + format!("{name} REMOVED — importing the file again brings it back") + } + Some(Err(e)) => format!("NO SUBTITLES REMOVED — {e}"), + None => "NO SUBTITLES REMOVED — open a file first".to_string(), + }; + eprintln!("{text}"); + self.notice = Some(text.into()); + cx.notify(); + } + /// Swaps the whole timeline for one restored from a `.edith`. Like an /// import this arrives by drop and so checks the export guard for itself. /// The new session is built before anything is replaced, so a refusal is @@ -4766,6 +4970,46 @@ impl Player { .detach(); } + /// The subtitle tracks an export of this timeline carries: every one with a + /// cue left in the exported range ([`PlaybackSession::timeline_cues`], the + /// very map the file is written from), in the library's own order. + /// + /// Worked out from the cues each time rather than kept as a pick, which is + /// what makes it impossible to desync: a row added or taken off shifts every + /// index after it, and a stored list would then name tracks nobody chose. + /// `Player::sub_track` stays what it always was -- which track the *overlay* + /// draws -- and has no say here. + /// + /// The honest input and not the final answer: the engine filters it again + /// per track (a track that could not be read, a picture one) and says so in + /// the card's own words ([`engine::export::planned_subtitles`]). + fn export_subs(&self) -> Vec { + let Some(session) = self.session.as_ref() else { + return Vec::new(); + }; + (0..session.subtitles().len()) + .filter(|&i| !session.timeline_cues(i).is_empty()) + .collect() + } + + /// That list in the card's words ([`subtitle_plan`]): what travels, and the + /// reason beside every track that does not -- including the ones + /// [`Self::export_subs`] filtered out before the engine ever saw them. + fn subtitle_line(&self) -> String { + let Some(session) = self.session.as_ref() else { + return "none".to_string(); + }; + let picks = self.export_subs(); + let plan = session.planned_subtitles(self.format, picks.iter().copied()); + match self.format.has_video() { + true => subtitle_plan(plan, session.subtitles(), &picks), + // A format that is the sound alone has nowhere to put any of them + // and the engine says that once, about the file. Naming the cues of + // each track under it answers a question the format already closed. + false => plan, + } + } + /// Writes the edit list out, at the settings the card was left at. Playback /// stops first: the exporter opens its own decoder -- and, on the hardware /// path, an encoder -- so a running player would only compete with it for @@ -4778,11 +5022,11 @@ impl Player { } let mut settings = export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps); - // The track the library has picked is the one that travels -- the same - // row the overlay draws, so the file carries what was watched. Set here - // rather than inside `export_settings`, which the card also calls for - // the *estimate* and which nothing else needs a subtitle for. - settings.subtitles = Some(self.sub_track); + // Whatever is on the timeline travels -- every track with a cue in the + // exported range, not the one row the overlay happens to be drawing. + // Set here rather than inside `export_settings`, which the card also + // calls for the *estimate* and which nothing else needs a subtitle for. + settings.subtitles = self.export_subs(); let Some(session) = &mut self.session else { self.notice = Some("NOTHING TO EXPORT — open a file first".into()); cx.notify(); @@ -5894,6 +6138,11 @@ impl Player { true => format!("{} {}", row.label, row.number), false => row.label, }; + // A standalone `.srt` is named after its own file, so + // the file in front of it says the same word twice + // ("Legend.of.… · Legend.of.…"). [`sub_pick_name`]'s + // rule, on the row it is about. + let owned = several_files && !title.starts_with(name.as_str()); // The whole path, never clipped: the row says which // file, and the tooltip says which one on disk. let tip: SharedString = match &row.refused { @@ -5904,6 +6153,11 @@ impl Player { ), } .into(); + // Named, because a × is the same glyph on every row and + // the tooltip is what says which track it takes off. + let remove_tip: SharedString = + format!("Remove {title} — importing the file again brings it back") + .into(); div() // The *flat* index into the session's add-order // list, which is what a pick is and what a save @@ -5960,7 +6214,7 @@ impl Player { // truncates from the right: an // ownership word at the end is a // word the floor never shows. - .when(several_files, |d| { + .when(owned, |d| { d.child( div() .flex_none() @@ -5990,6 +6244,34 @@ impl Player { .child(row.detail), ), ) + // The way back off the timeline, on every row and on + // the last one too -- a list of subtitles is allowed + // to be empty, unlike a lane. A `HIT_MIN` target and + // never hidden, the lane header's ×, and it stops + // the click there: the row under it picks a track, + // and picking the track that has just gone would + // leave the pick naming nothing. + .child( + div() + .id(("subtitle-remove", track)) + .flex_none() + .w(px(HIT_MIN)) + .h_full() + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .tooltip(move |_, cx| cx.new(|_| Tip(remove_tip.clone())).into()) + .on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + cx.stop_propagation(); + this.remove_subtitle_track(track, cx); + }, + )) + .child("×"), + ) }) .collect(); div() @@ -6442,6 +6724,35 @@ impl Player { this.add_lane(LaneKind::Audio, cx) }), )) + // The third kind of track this timeline carries, and + // the only one that arrived through a drop alone: a + // subtitle file nobody thought to drag was a track + // the editor could not be asked for. What it opens is + // a chooser rather than an empty row -- a subtitle + // track is its file, and there is nothing to add + // before one is named. + .child(control( + "add-subtitle-track", + None, + "+ S", + // Dim, and saying why it is dim, out of the one + // oracle -- the very words the key answers with + // (`Player::pick_and_add_subtitles`), so the + // tooltip and the notice cannot come to differ. + match self.enable(ActionId::AddSubtitleTrack, None).why() { + Some(why) => { + format!("{} — {why}", key(ActionId::AddSubtitleTrack)) + } + None => format!( + "{} — adds every subtitle track in a file you pick", + key(ActionId::AddSubtitleTrack) + ), + }, + live, + cx.listener(|this, _: &ClickEvent, _, cx| { + this.pick_and_add_subtitles(cx) + }), + )) // With the transport, not the edit group: it changes what // the file sounds like, never what it is. Reads as its own // state, so muted is legible without a tooltip. @@ -7029,7 +7340,11 @@ impl Player { div() .flex() // The floor, not the height: a row that needed two lines - // would otherwise paint over the one under it. + // would otherwise paint over the one under it -- which it did + // anyway until this said `flex_none`, a row inside a capped + // scrolling list being shrunk to fit by default (the export + // card's rows had the same shape and the same overlap). + .flex_none() .min_h(px(KEYS_ROW_H)) .items_center() .justify_between() @@ -7282,7 +7597,13 @@ impl Player { .id(id) .flex() // The floor, not the height: the destination's path wraps on a - // long name and must not paint over the row under it. + // long name and must not paint over the row under it. Which it + // did: inside a capped, scrolling list a row shrinks to fit by + // default, so a wrapped detail was drawn over the row beneath + // it (the Sound row's "the source's own packets are copied…" + // over Subtitles). The list scrolls -- a row is as tall as what + // it has to say. + .flex_none() .min_h(px(KEYS_ROW_H)) .items_center() .justify_between() @@ -7511,22 +7832,29 @@ impl Player { })); } list.push(r.into_any_element()); - // What happens to the picked subtitle track, in one line: it is written - // into the file, or the reason it is not. Nothing to pick here -- which - // track is the library's row and the container is the format row above - // -- so the row says and does not answer, like the machine lines below. + // What happens to the subtitles on this timeline, in one line: how many + // are written into the file and under what names, or the reason each one + // is not. Which tracks travel is not a pick -- everything with a cue on + // the timeline goes ([`Player::export_subs`]) -- so the row says rather + // than offers, like the machine lines below. + // ...and the ones that do not travel are named here too, which they were + // not: `export_subs` had already filtered a track with no cue on *this* + // timeline out of the engine's sight, so the card said nothing about a + // row the list was still showing ([`subtitle_plan`]). + let plan = self.subtitle_line(); + // The row used to end in "click for in MKV" whenever the picture + // was going into an mp4, on the grounds that only Matroska carries a + // text track. An mp4 carries one now (`Mp4Muxer::write_subtitles` writes + // `tx3g`), so that was a refusal offering a way out of nothing: the + // container the card is already set to embeds them. The refusals left in + // `planned_subtitles` are the true ones -- a sound-only format has + // nowhere to put a track, and a PGS track is pictures whatever the box. list.push( entry( ("subtitles", 0), "", "Subtitles".into(), - self.session - .as_ref() - .map_or_else( - || "none".into(), - |s| s.planned_subtitles(self.format, Some(self.sub_track)), - ) - .into(), + plan.into(), false, false, ) @@ -7641,7 +7969,7 @@ impl Player { .map_or("", |s| s.planned_audio(self.format)); let settings = export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps); - let mb = estimated_mb( + let size = estimated_bytes( settings.bitrate.filter(|_| self.format.has_video()), self.session .as_ref() @@ -7650,8 +7978,8 @@ impl Player { let head = summary_head(self.format, picture, audio); let tail = summary_tail( &self.export_path, - mb, - self.export_seat.and_then(|(.., seat)| seat), + size, + self.export_seat.as_ref().and_then(|(.., seat)| *seat), self.format.has_video(), ); // The button says the refusal *before* it is pressed: the picked codec @@ -8732,8 +9060,8 @@ impl Player { ), None => match found { 0 => "nothing quiet enough for long enough".to_string(), - 1 => format!("1 silence, {secs:.1}s"), - n => format!("{n} silences, {secs:.1}s"), + 1 => format!("1 silence, {}", secs_label(secs)), + n => format!("{n} silences, {}", secs_label(secs)), }, }; let rows: Vec<_> = rows @@ -8947,6 +9275,13 @@ impl Player { info.map_or_else(|| "no track of its own".to_string(), stream_detail), ), }, + ( + "Bitrate", + bitrate_detail( + self.bitrates.get(&path).copied().flatten(), + self.streams.get(&path).map_or(0, Vec::len), + ), + ), match image { true => ( "Longest hold", @@ -9114,6 +9449,13 @@ impl Player { ("This clip", secs(clip.frames())), ("Speed", format!("{} (tape)", clip.speed)), ("Source duration", secs(session.file_frames(&source.path))), + ( + "Bitrate", + bitrate_detail( + self.bitrates.get(&source.path).copied().flatten(), + self.streams.get(&source.path).map_or(0, Vec::len), + ), + ), ] { rows.push( row(rows.len()) @@ -10249,11 +10591,18 @@ fn run_picker(pickers: [(&str, Vec); 2]) -> Option> { None } -fn pick_file() -> Result, &'static str> { +/// `title` is what the dialog calls itself: two buttons open this same chooser +/// for two different questions -- a file to import, a file to take subtitles out +/// of -- and a dialog titled "import" over the second one is the wrong question +/// answered. No extension filter on either: what can be read is the engine's +/// answer (`PlaybackSession::parse_subtitles` takes a container as readily as a +/// `.srt`), and a list of suffixes written here would hide a file edith would +/// have taken. +fn pick_file(title: &str) -> Result, &'static str> { run_picker([ ( "zenity", - vec!["--file-selection".into(), "--title=edith — import".into()], + vec!["--file-selection".into(), format!("--title={title}")], ), ("kdialog", vec!["--getopenfilename".into()]), ]) @@ -10333,31 +10682,51 @@ fn audio_notice(session: &PlaybackSession) -> Option { /// formats `engine::subtitle` parses, lowercased, for [`engine::is_audio`]'s /// reason -- the import door has to know which of the engine's two doors a file /// goes through before anything is opened. +/// +/// `.mks` is one of them, and it is the only Matroska extension that is: it is +/// the *subtitles alone*, so there is no source in it to import and a drop of +/// one used to be refused for having no video track -- while `+ S` on the same +/// bytes took it ([`PlaybackSession::parse_subtitles`] reads it as Matroska). +/// The other two are media and stay media: `.mka` is the sound alone, which +/// [`engine::is_audio`] already imports as a song, and `.mk3d` is a film. Both +/// may *carry* subtitles, which is [`carries_subtitles`] and not this. fn is_subtitle(path: &std::path::Path) -> bool { path.extension().and_then(|e| e.to_str()).is_some_and(|e| { matches!( e.to_ascii_lowercase().as_str(), - "srt" | "vtt" | "webvtt" | "ass" | "ssa" + "srt" | "vtt" | "webvtt" | "ass" | "ssa" | "mks" ) }) } /// Whether a media path is a container that can carry subtitle tracks *inside* -/// it -- the two Matroska extensions, which is what -/// [`PlaybackSession::import_subtitles`] walks for them. -fn is_matroska(path: &std::path::Path) -> bool { - path.extension() - .and_then(|e| e.to_str()) - .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "mkv" | "webm")) +/// it -- every Matroska extension and the three ISO-BMFF ones, which is the list +/// [`PlaybackSession::parse_subtitles`] walks (Matroska blocks and mp4 `tx3g` +/// alike). Named for what it gates and not for one of the two families, because +/// an mp4 answers `true` here now. +/// +/// Matroska's set is the standard's own and closed by it +/// (`engine::demux::is_matroska`), so it is copied whole rather than trimmed to +/// the two that carry a film: a `.mk3d` opened as media has its tracks walked +/// like the `.mkv` it is, and a `.mka` song can hold a lyric track. A suffix +/// wider than the engine's would be a file taken here and refused deeper down. +fn carries_subtitles(path: &std::path::Path) -> bool { + path.extension().and_then(|e| e.to_str()).is_some_and(|e| { + matches!( + e.to_ascii_lowercase().as_str(), + "mkv" | "mka" | "mks" | "mk3d" | "webm" | "mp4" | "m4v" | "mov" + ) + }) } /// What a worker hands back, which is the fork [`arrival`] made when it was /// started. An import is *read* and thrown away; the file argv named is opened /// outright, because nothing else is going to open it afterwards. enum Landed { - /// An import: pages warmed, nothing kept. [`Player::take_import`] opens the - /// file again, warm, and that second open is the 150 ms one. - Read, + /// An import: pages warmed, and the subtitle tracks the walk found *kept* -- + /// the walk is the expensive half and the worker is where it belongs, so + /// [`Player::take_import`] is left with a push ([`subtitle_tail`]). + Read(Subs), /// The media argv named, with the tail its subtitle tracks earn: a whole /// timeline, ready to be hung off the window, or the engine's refusal. Media(Result<(PlaybackSession, String), String>), @@ -10371,14 +10740,18 @@ enum Landed { /// /// `place` is which door: a file *opened* is the timeline, one *imported* into /// an empty window fills the library and leaves the lanes empty for a drag. -fn open_session(path: &std::path::Path, place: bool) -> Result<(PlaybackSession, String), String> { +fn open_session( + path: &std::path::Path, + place: bool, + subs: Subs, +) -> Result<(PlaybackSession, String), String> { let opened = match place { true => PlaybackSession::open(path), false => PlaybackSession::open_library(path), }; let mut session = opened.map_err(|e| e.to_string())?; - let subs = subtitle_notice(&mut session, path).unwrap_or_default(); - Ok((session, subs)) + let tail = subtitle_tail(&mut session, subs).unwrap_or_default(); + Ok((session, tail)) } /// The whole of what a queued file costs, off the UI thread. An import only @@ -10392,10 +10765,7 @@ fn open_ahead( ) -> Landed { use std::sync::atomic::Ordering::Relaxed; match what { - Landing::Import => { - read_ahead(path, stage); - Landed::Read - } + Landing::Import => Landed::Read(read_ahead(path, stage)), Landing::Project => { let opened = PlaybackSession::open_project(path).map_err(|e| e.to_string()); Landed::Project(opened) @@ -10414,24 +10784,33 @@ fn open_ahead( } /// Reads, off the UI thread, exactly what the import that follows is about to -/// read -- and throws every byte away. The point is the page cache: a cold -/// header walk of a 29 GB remux is 11 s and a warm one is 150 ms (measured, -/// `a real 4K HEVC film` 2160p h265), so this call is the eleven seconds and -/// [`Player::take_import`] is the hundred and fifty milliseconds. The window -/// keeps painting through the eleven. +/// read. The container's header is read for the page cache and thrown away: a +/// cold header walk of a 29 GB remux is 11 s and a warm one is 150 ms +/// (measured, `a real 4K HEVC film` 2160p h265), so this call is the eleven +/// seconds and [`Player::take_import`] is the hundred and fifty milliseconds. +/// The window keeps painting through the eleven. /// -/// Errors are dropped on purpose: a file that cannot be read is refused by the -/// engine a moment later, in the engine's own words, and a refusal read twice -/// is a refusal worded twice. +/// Header errors are dropped on purpose: a file that cannot be read is refused +/// by the engine a moment later, in the engine's own words, and a refusal read +/// twice is a refusal worded twice. The *subtitle* refusal is carried back +/// instead of dropped, for exactly that reason -- nothing walks those cues a +/// second time to re-word it. /// /// `stage` is what the line above the panel is naming while this runs. /// -/// ponytail: the cache is the whole handoff, so a machine that evicts those -/// pages between this read and the next frame pays the cold walk on the UI -/// thread after all. Ceiling: memory pressure inside one repaint of a 25 GB -/// file. The upgrade is an engine door that takes the header this already -/// parsed ([`PlaybackSession::import`] opens the demuxer again today). -fn read_ahead(path: &std::path::Path, stage: &std::sync::atomic::AtomicU8) { +/// The subtitle half is not thrown away: it is *the* answer, handed back for +/// [`Player::take_import`] to push ([`subtitle_tail`]) rather than walked a +/// second time on the render thread -- 234 ms of a warmed 25 GB remux and 1.3 s +/// of a cold 3 GB one, which is what a frozen window is made of. +/// +/// ponytail: only the subtitle half is handed over. The container's own header +/// is still merely *warmed* here, so [`PlaybackSession::import`] and +/// [`open_session`] walk it again on the UI thread -- 2.8 s of that same 25 GB +/// file. Ceiling: the media walk, not the subtitle one. The upgrade is the +/// engine door this comment has always named: one that takes the header this +/// already parsed, the way [`PlaybackSession::add_subtitle_tracks`] takes the +/// cues this already read. +fn read_ahead(path: &std::path::Path, stage: &std::sync::atomic::AtomicU8) -> Subs { use std::sync::atomic::Ordering::Relaxed; stage.store(ImportStage::Header as u8, Relaxed); // 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) { engine::demux::Demuxer::open(path).ok(); } stage.store(ImportStage::Subtitles as u8, Relaxed); - // ...and the tracks inside it, which `subtitle_notice` walks straight - // after. A standalone `.srt` is small enough to be nobody's wait. - if is_matroska(path) { - engine::subtitle::of_matroska(path).ok(); + // ...and the tracks inside it, kept. + walk_subtitles(path) +} + +/// Every subtitle track a file carries, cues and all -- the walk that costs, in +/// the one place every door that pays it goes through. `Ok` and empty for a file +/// with none to read, which is what a file that is neither a container we can +/// walk ([`carries_subtitles`]) nor a subtitle file is: the same answer +/// `add_subtitle_tracks` gives it, and nothing is opened to find that out. +/// +/// Nothing in here is a session, on purpose ([`PlaybackSession::parse_subtitles`] +/// is an associated fn): no borrow crosses the await, so this runs whole on a +/// worker while the window keeps painting. +fn walk_subtitles(path: &std::path::Path) -> Subs { + match carries_subtitles(path) || is_subtitle(path) { + true => PlaybackSession::parse_subtitles(path), + false => Ok(Vec::new()), } } /// The subtitle tracks a media file carries, taken into the session as it is -/// opened, and the tail the notice grows for them: an mkv with subtitles in it -/// arrives with its subtitles, because a track nobody imported is a track nobody -/// knows is there. Every other container answers `None` without being read. +/// opened, and the tail the notice grows for them: an mkv or an mp4 with +/// subtitles in it arrives with its subtitles, because a track nobody imported +/// is a track nobody knows is there. Every other container answers `None` +/// without being read. /// /// A refusal is a tail too, never a failure of the open: the picture and the /// sound of a film whose subtitle tracks cannot be walked are still the film. /// -/// The walk reads the whole file for its cues -/// (`engine::subtitle::of_matroska`) -- ~200 ms on a two-hour 4K remux, and an -/// *import* pays it on a worker first ([`read_ahead`]), so what happens here is -/// the warm second pass. A file *opened* at launch pays it cold and pays it -/// once -- this runs on the worker beside the open itself ([`open_ahead`]), -/// with the window already up and naming the read. +/// Both halves at once, which only a *worker* may do: the walk reads the whole +/// file for its cues (`engine::subtitle::of_matroska`) -- ~200 ms on a two-hour +/// 4K remux, 9.7 s on a cold 25 GB one. The one caller is the open beside which +/// this runs on the worker ([`open_ahead`]), never the render thread; an +/// import splits the two halves across the hop instead ([`read_ahead`] walks, +/// [`subtitle_tail`] pushes). fn subtitle_notice(session: &mut PlaybackSession, path: &std::path::Path) -> Option { - if !is_matroska(path) { - return None; - } - match session.import_subtitles(path) { - Ok(0) => None, - Ok(n) => Some(format!(" — {n} subtitle track(s) in the file")), + subtitle_tail(session, walk_subtitles(path)) +} + +/// What a subtitle walk ([`walk_subtitles`]) gave, on its way from whichever +/// thread paid for it to the timeline. `Send` all the way down (`sendable()`, +/// `engine/tests/subtitles.rs`), which is what lets the walk be a worker's. +type Subs = engine::Result>; + +/// The tail a file's own subtitle tracks earn on the notice that names it, and +/// the push that puts them on the timeline -- the second half of the walk, the +/// cheap one ([`PlaybackSession::add_subtitle_tracks`]: no open, no seek, no +/// decode). Every door that arrives with a *file* words it here, once: the file +/// argv named, an import, and an import into an empty window cannot say the same +/// thing differently, whichever thread read the cues. +/// +/// `None` for a file that gave none and for one whose tracks are on the timeline +/// already -- an import that adds nothing says nothing about subtitles. A +/// refusal is a tail too, never a failure of the import: the picture and the +/// sound of a film whose subtitle tracks cannot be walked are still the film. +fn subtitle_tail(session: &mut PlaybackSession, subs: Subs) -> Option { + match subs { + Ok(tracks) => match session.add_subtitle_tracks(tracks) { + 0 => None, + n => Some(format!(" — {n} subtitle track(s) in the file")), + }, Err(e) => Some(format!(" — SUBTITLES UNREAD: {e}")), } } @@ -10489,6 +10901,85 @@ fn subtitle_detail(track: &engine::subtitle::SubtitleTrack) -> String { } } +/// What the export card's Subtitles row says: the engine's own words for the +/// tracks an export carries (`plan`, [`engine::export::planned_subtitles`] asked +/// about `picks`) and, beside them, the rows it is carrying nothing of. +/// +/// `picks` is [`Player::export_subs`] -- every track with a cue left in the +/// exported range -- so a track sitting in the list with eighty-three cues +/// nowhere near a trimmed timeline never reaches the engine at all, and the card +/// said nothing about it while the list went on showing it. Which tracks have +/// cues *here* is this side's answer and nobody else's, so this side words it. +/// +/// Past [`SUB_PLAN_CHARS`] the line counts rather than names: every name is more +/// words in a value box `MENU_W` wide, and at 35 tracks the row wrapped to ten +/// lines and pushed the Destination row under the fold of the card. The names +/// are still one row each in the Subtitles list, with the cue count and the +/// reason under them ([`subtitle_detail`]) -- more than this line ever said. +/// +/// The counted split follows the engine's own order of reasons (`refused`, then +/// pictures, then no cues), with the last asked of the timeline instead of the +/// track. +/// +/// ponytail: that split reads the same public fields the list rows read +/// (`refused`, [`engine::subtitle::SubtitleTrack::is_bitmap`]) rather than the +/// engine's decision, so a *new* reason to drop a track would be counted here as +/// embedded until this follows it -- the named line, which is the engine's +/// string verbatim, would say it correctly meanwhile. Upgrade path: reasons out +/// of `planned_subtitles` as data rather than as one sentence, which is an +/// engine change. +fn subtitle_plan( + plan: String, + tracks: &[engine::subtitle::SubtitleTrack], + picks: &[usize], +) -> String { + let mut parts: Vec = Vec::new(); + // "none" is the engine's word for an empty pick list and would read as a + // verdict on the tracks named after it. + if !picks.is_empty() { + parts.push(plan); + } + parts.extend( + tracks + .iter() + .enumerate() + .filter(|(i, _)| !picks.contains(i)) + .map(|(_, track)| format!("{} — no cues here", track.label)), + ); + let named = parts.join("; "); + if named.chars().count() <= SUB_PLAN_CHARS { + return match named.is_empty() { + true => "none".to_string(), + false => named, + }; + } + let (mut embedded, mut unread, mut pictures, mut off) = (0, 0, 0, 0); + for (i, track) in tracks.iter().enumerate() { + match ( + track.refused.is_some(), + track.is_bitmap(), + picks.contains(&i), + ) { + (true, _, _) => unread += 1, + (_, true, _) => pictures += 1, + (_, _, false) => off += 1, + _ => embedded += 1, + } + } + let mut counted = vec![format!("{embedded} of {} → embedded", tracks.len())]; + counted.extend( + [ + (pictures, "pictures"), + (unread, "unread"), + (off, "no cues here"), + ] + .into_iter() + .filter(|(n, _)| *n > 0) + .map(|(n, why)| format!("{n} {why}")), + ); + counted.join("; ") +} + /// Every subtitle track one file gave, kept together. Plain data, planned /// before anything is drawn -- the grouping is the branchy part and it is the /// same answer whatever a styling puts around it. @@ -10531,6 +11022,32 @@ struct SubRow { bitmap: bool, } +/// What a subtitle row is called, off the two fields the container really +/// stated rather than out of the flattened +/// [`label`](engine::subtitle::SubtitleTrack::label). The pair is what an export +/// writes (`TRACK_LANGUAGE` and `TRACK_NAME` are two fields), and reading the +/// display string back apart is the very heuristic that sent every French track +/// out as English: `lang_human` on a whole "und — Signs" matches nothing and +/// names a language nobody speaks. +/// +/// The three shapes a track arrives in, all three of them real: a standalone +/// file states no language and is its own name, an embedded one states a +/// language and sometimes a title beside it, and a refused one states neither +/// and keeps the label it was refused under (`SubtitleTrack::refused`). +fn sub_title(sub: &engine::subtitle::SubtitleTrack) -> String { + match (sub.language.as_str(), sub.name.as_str()) { + ("", "") => sub.label.clone(), + ("", name) => name.to_string(), + // A track whose only name is the tag for "nobody said" says that in + // words rather than showing the tag itself. + (lang, "") => lang_human(lang).to_string(), + // ...and one that says "nobody said" *and* gives a title is the title: + // "unknown language — Signs" pads it with a word the file never said. + ("und", name) => name.to_string(), + (lang, name) => format!("{lang} — {name}"), + } +} + /// The subtitle list as rows under the file each came out of: one group per /// distinct path, in the order the files first appear, and each file's tracks /// in the order they were added. Two remuxes' tracks arriving interleaved -- @@ -10555,9 +11072,7 @@ fn subtitle_rows(tracks: &[engine::subtitle::SubtitleTrack]) -> Vec { group.rows.push(SubRow { track, number: group.rows.len() + 1, - // A track whose only name is the tag for "nobody said" says that - // in words, here, rather than showing the tag itself. - label: lang_human(&sub.label).to_string(), + label: sub_title(sub), detail: subtitle_detail(sub), refused: sub.refused.clone(), bitmap: sub.is_bitmap(), @@ -10581,6 +11096,27 @@ fn subtitle_rows(tracks: &[engine::subtitle::SubtitleTrack]) -> Vec { /// /// `None` for an index no track answers to, which is the silence /// [`Player::subtitle_track`] gives at the same moment. +/// Where the picked subtitle row lands once `removed` has been taken off a list +/// that is `left` long afterwards. The pick follows the list: the same *track* +/// while it is still there -- every index past the one that went moves down +/// ([`engine::Project::remove_subtitles`]) -- the row that slid into the empty +/// place when the picked one is what went, and the last row when that was the +/// last. Zero on an emptied list, which is the index the section is not drawn at +/// all. +/// +/// Its own function because the pick is what the overlay draws: left where it +/// was it would name a different track, and the plate over the picture would +/// change language on its own the moment a row above it went. What an export +/// writes is *not* this pick and cannot be desynced by a removal -- it is worked +/// out from the cues on the timeline each time ([`Player::export_subs`]). +fn sub_pick_after_removal(picked: usize, removed: usize, left: usize) -> usize { + let picked = match removed < picked { + true => picked - 1, + false => picked, + }; + picked.min(left.saturating_sub(1)) +} + fn sub_pick_name(tracks: &[engine::subtitle::SubtitleTrack], track: usize) -> Option { subtitle_rows(tracks).into_iter().find_map(|group| { let row = group.rows.iter().find(|row| row.track == track)?; @@ -10891,7 +11427,11 @@ fn enable(action: ActionId, ctx: Ctx) -> Enable { // Nothing to draw over the picture, so nothing to switch off: the // library says how subtitles arrive, and this row would flip a state // with no visible half either way. - ActionId::ToggleSubtitles if !ctx.subtitles => Enable::No("no subtitles yet"), + // ...and nothing to take off the timeline either, for the same reason: + // the row would name a track that is not there. + ActionId::ToggleSubtitles | ActionId::RemoveSubtitleTrack if !ctx.subtitles => { + Enable::No("no subtitles yet") + } ActionId::CancelExport => Enable::No("nothing is exporting"), // A rate applies to a clip of either kind and to its whole group, so // there is no lane it means nothing on, and the engine words the one @@ -11152,6 +11692,106 @@ fn stream_detail(info: &StreamInfo) -> String { parts.join(" ") } +/// What a file is coded at, for the properties cards: the rate of the whole +/// file, then each track's own beside it. A component the container does not +/// state is left out for `stream_detail`'s reason -- a fabricated `0` would be +/// saying something -- and a file that states none of the three says so rather +/// than showing an empty row. `None` is the probe still running, which is a +/// real wait: it walks a Matroska's clusters. +/// +/// The whole file's rate is the one that carries the unit and no word: named +/// "total" as well, the line loses its last component to `MENU_W`'s truncation +/// on an ordinary 1080p file -- and a rate cut to "0.13 soun" is a number the +/// card did not give. +/// +/// `tracks` is how many sound tracks the file has, from `probe_streams`. The +/// rate is the one track this engine plays -- the first, neither their sum nor +/// the biggest -- so a file with more says which of how many: a bare "0.16 +/// sound" on a file whose name says AC3.5.1 names a track without saying it is +/// one of two, and the card's Audio row above it may be describing the other. +/// +/// The marker costs the word "sound", the way the whole file's rate costs the +/// word "total" above, and for the same reason. Measured in Noto Sans 11 px +/// against the 186 px this value has beside a "Bitrate" label: "0.16 sound 1/2" +/// wants 192 px on a small film's 4.7 Mb/s and 205 on the 39.8 Mb/s remux -- +/// the marker is what gets cut, which is the one part of the line that is new. +/// Nothing that keeps the word fits the wide files -- the shortest, "snd 1/2", +/// still wants 188 px on that remux -- so the word goes and the number keeps +/// the answer: "0.16 1 of 2" wants 172 px, and 185 on the widest line a +/// library can produce (the 10.9 Mb/s three-track film). +fn bitrate_detail(rate: Option, tracks: usize) -> String { + let Some(rate) = rate else { + return "…".to_string(); + }; + let (per, unit) = rate_scale(rate); + let mut parts: Vec = Vec::new(); + if let Some(total) = rate.total { + // One unit for the three numbers, carried once, on the whole file's + // rate: the components are read against it. + parts.push(format!("{} {unit}", scaled(total, per))); + } + if let Some(video) = rate.video { + parts.push(format!("{} video", scaled(video, per))); + } + if let Some(audio) = rate.audio { + parts.push(match tracks > 1 { + true => format!("{} 1 of {tracks}", scaled(audio, per)), + false => format!("{} sound", scaled(audio, per)), + }); + } + match parts.is_empty() { + true => "not stated".to_string(), + false => parts.join(" · "), + } +} + +/// Below this a megabit's two decimals cannot state a rate, so the line is read +/// in kilobits instead. +const MB_FLOOR: u64 = 10_000; + +/// What the line counts in, and the name of it: the largest unit that can state +/// its *smallest* component, because that is the one a bigger unit rounds away. +/// Megabits for everything a real file produces -- the smallest component over +/// an 18-file sweep of a library was 0.13 Mb/s -- kilobits for the sub-32x32 +/// encodes below that. +/// +/// ponytail: one unit for the whole line, so a file mixing a multi-megabit +/// picture with a sub-10 kb/s sound track prints the picture as four or five +/// digits of kilobits and loses the line's tail to `MENU_W`. No such file +/// exists in a library, and both units at once ("0.01 Mb/s · 1.2 kb/s video · +/// 9.5 kb/s sound") wants 215 px of the 186 the row has. Upgrade path is a +/// suffix per component ("1.2k video"), which measures 177 px. +fn rate_scale(rate: MediaBitrate) -> (f64, &'static str) { + match [rate.total, rate.video, rate.audio] + .into_iter() + .flatten() + .min() + { + // A rate this small is a broken header rather than a track, but it is + // still a number the file stated, and bits state it. + Some(bits) if bits < 10 => (1., "b/s"), + Some(bits) if bits < MB_FLOOR => (1_000., "kb/s"), + _ => (1_000_000., "Mb/s"), + } +} + +/// A rate in the line's unit as a person reads it: one decimal above 1 of it, +/// two below -- a 128 kbps song rounded to one decimal is "0.1", which reads as +/// a guess where "0.13" reads as a measurement. +/// +/// Never `0.00`: [`rate_scale`] picks the unit off the smallest component, so +/// two decimals always reach it. Every rate that gets here is one the container +/// really stated (the probe leaves out what it does not state, it never zeroes +/// it), and a "0.00 sound" would be this card saying a track that plays is +/// silent. +fn scaled(bits: u64, per: f64) -> String { + let n = bits as f64 / per; + match n >= 1. { + true => format!("{n:.1}"), + false => format!("{n:.2}"), + } +} + /// A language tag as a person reads it. Everything a file writes is passed /// through untouched bar the one tag that is not a language: "und" is what a /// 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) /// The second: where it lands, roughly how big, and what will encode the /// picture -- the seat as the probe found it (`…` until it lands, never a /// guess), which is what the running export then names on its progress line. -fn summary_tail(path: &Path, mb: Option, seat: Option<&'static str>, video: bool) -> String { - let size = mb.map_or_else(String::new, |mb| format!("≈ {mb} MB")); +fn summary_tail(path: &Path, bytes: Option, seat: Option<&'static str>, video: bool) -> String { + let size = bytes.map_or_else(String::new, |bytes| format!("≈ {}", size_label(bytes))); let seat = match (video, seat) { (true, Some(seat)) => seat, (true, None) => "encoder …", @@ -11823,14 +12463,28 @@ fn fps_label(fps: f64) -> String { } } -/// About how big a *chosen* bitrate makes the file: the picture's megabits over -/// the timeline's length. `None` for `Auto`, whose figure is the encoder's to +/// About how big a *chosen* bitrate makes the file: the picture's bits over the +/// timeline's length, in bytes -- the unit the line is written in is +/// [`size_label`]'s to pick. `None` for `Auto`, whose figure is the encoder's to /// decide, and for a format with no bitrate at all -- a number nobody picked is /// not an estimate. The sound and the container's own overhead are not in it, /// which is why the card says "≈". -fn estimated_mb(bitrate: Option, duration: f64) -> Option { +fn estimated_bytes(bitrate: Option, duration: f64) -> Option { let bitrate = bitrate.filter(|&b| b > 0 && duration > 0.)?; - Some((bitrate as f64 * duration / 8e6).round() as u64) + Some((bitrate as f64 * duration / 8.).round() as u64) +} + +/// A size in the largest unit that can state it, [`rate_scale`]'s rule: +/// megabytes for an export of any length, kilobytes below the one a whole +/// megabyte rounds away. A three second clip at the floor bitrate really is +/// 375 kB, and "≈ 0 MB" would be this line saying the file it is about to write +/// is empty -- the one thing the size field is there to deny. Never "0 kB" +/// either: an estimate that exists is at least a kilobyte of file. +fn size_label(bytes: u64) -> String { + match (bytes as f64 / 1e6).round() as u64 { + 0 => format!("{} kB", (bytes as f64 / 1e3).round().max(1.) as u64), + mb => format!("{mb} MB"), + } } /// 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( // The picked track is put on by `start_export`, which is the only // caller that writes a file; the rest of them are asking about the // bitrate and the format. - subtitles: None, + subtitles: Vec::new(), } } @@ -12184,7 +12838,20 @@ fn span_label(span: f64) -> String { s if s >= 600. => format!("{:.0}m", s / 60.), s if s >= 60. => format!("{:.1}m", s / 60.), s if s >= 10. => format!("{s:.0}s"), - s => format!("{s:.1}s"), + s => secs_label(s), + } +} + +/// A span of seconds as a person reads it: one decimal above a second, two +/// below -- [`scaled`]'s rule, for its reason. The tightest zoom is +/// [`ZOOM_MIN_FRAMES`] across the bed, which on the 240 fps slow-motion a phone +/// writes is 0.03s, and a single frame of quiet at 60 fps is 0.02s: one decimal +/// prints both as "0.0s", a pill and a notice saying the thing they are about +/// has no length at all. +fn secs_label(secs: f64) -> String { + match secs >= 1. { + true => format!("{secs:.1}s"), + false => format!("{secs:.2}s"), } } @@ -13532,20 +14199,20 @@ mod tests { Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, - MBPS_DIGITS, MBPS_MAX, MBPS_MIN, MENU_W, NO_FILE, NumberEdit, PANEL_H, ROW_ITEMS, RowCtx, RowItem, + MBPS_DIGITS, MBPS_MAX, MBPS_MIN, MB_FLOOR, MENU_W, NO_FILE, NumberEdit, PANEL_H, ROW_ITEMS, RowCtx, RowItem, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, band_label, - bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, commit_mbps, + bitrate_detail, bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, commit_mbps, containers, enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y, - estimated_mb, export_path, export_settings, format_key, + estimated_bytes, export_path, export_settings, format_key, format_line, format_refusal, fps_choices, fps_label, frac_along, frac_down, frame_at, frame_rate_ladder, histogram, inserted_band, is_bare_modifier, is_project, keymap, keys_filter, keys_rows, lanes_h, marked, menu_at, menu_items, menu_rows_h, next_audio_kbps, next_container, normalise, nothing_to_play, panel_h, project_path, - retarget, row_enable, row_items, scrub_due, show_label, silence_rate, snap_cue, snap_marks, snapped, - source_tint, span_partner, speed_at, summary_head, summary_tail, timecode, transport, + retarget, row_enable, row_items, scrub_due, secs_label, show_label, silence_rate, size_label, snap_cue, snap_marks, snapped, + SUB_PLAN_CHARS, source_tint, span_partner, speed_at, sub_pick_after_removal, subtitle_plan, summary_head, summary_tail, timecode, transport, typed, unseen_paths, unseen_sources, whole_take, window_title, }; @@ -13565,9 +14232,9 @@ mod tests { use super::{ SUB_BOTTOM, SUB_CUE_MIN_W, SUB_HEAD_H, SUB_INK, SUB_LANE_H, SUB_LINE_H, SUB_ROWS_H, SUB_STEM_SHARE, SUB_TEXT, clip_middle, cue_box, - cues_at, file_tint, is_matroska, is_subtitle, lang_human, row_text_w, sub_headers_fit, - subtitle_detail, subtitle_notice, - sub_pick_name, subtitle_rows, subtitle_strip_h, + carries_subtitles, cues_at, file_tint, is_subtitle, lang_human, row_text_w, sub_headers_fit, + Subs, subtitle_detail, subtitle_notice, subtitle_tail, + sub_pick_name, subtitle_rows, subtitle_strip_h, walk_subtitles, }; /// What the file manager is handed: the parts a path keeps as they are, and @@ -15281,6 +15948,102 @@ mod tests { assert_eq!(snap_cue(false, 158, 40, 4, &marks), (158, None)); } + /// The card's rate row: every component the container states and no other, + /// so a track the header is silent about is absent from the line rather + /// than sitting in it as a zero. + #[test] + fn a_rate_row_says_only_what_the_container_stated() { + use super::MediaBitrate; + let all = MediaBitrate { + total: Some(8_432_000), + video: Some(7_918_000), + audio: Some(128_000), + }; + assert_eq!( + bitrate_detail(Some(all), 1), + "8.4 Mb/s · 7.9 video · 0.13 sound" + ); + // A Matroska states no audio rate of its own: the sound is dropped from + // the line, never drawn as "0". + assert_eq!( + bitrate_detail( + Some(MediaBitrate { + audio: None, + ..all + }), + 1 + ), + "8.4 Mb/s · 7.9 video" + ); + // A still, or anything that would not open: the probe answered, and the + // answer is that nobody said. + assert_eq!( + bitrate_detail(Some(MediaBitrate::default()), 0), + "not stated" + ); + // Asked, not answered yet -- a 12 GB film's walk takes seconds. + assert_eq!(bitrate_detail(None, 2), "…"); + // A dual-audio file: the number is the track that plays, and the line + // says so rather than letting it stand for the AC-3 beside it. + assert_eq!( + bitrate_detail(Some(all), 2), + "8.4 Mb/s · 7.9 video · 0.13 1 of 2" + ); + // Every component of a tiny file is stated, and small: the line changes + // unit, so not one of them reads as the zero it is not. In megabits + // this file was "0.00 Mb/s · 0.00 video · 0.00 sound". + assert_eq!( + bitrate_detail( + Some(MediaBitrate { + total: Some(4_998), + video: Some(113), + audio: Some(2_400), + }), + 1 + ), + "5.0 kb/s · 0.11 video · 2.4 sound" + ); + } + + /// The invariant under the row above, over every rate a container can + /// state: a component the file *does* state never renders as a zero. The + /// probe leaves out what is unstated, so a "0.00" on this card would be it + /// saying a track that plays is silent. + #[test] + fn a_stated_rate_never_renders_as_a_zero() { + use super::MediaBitrate; + // Every decade from 1 bit a second to a 100 Mb/s master, the rounding + // edges of each unit switch, and every pair of them in one line: the + // line's unit is picked off its smallest component, so the widest + // spread is the one that could round the biggest away. + let edges: Vec = (0..12) + .flat_map(|e| { + let decade = 10_u64.pow(e); + [decade, decade * 4, decade * 5, decade * 9] + }) + .chain([MB_FLOOR - 1, MB_FLOOR, 999_999, 4_998, 113, 2_400]) + .collect(); + for &small in &edges { + for &big in &edges { + let line = bitrate_detail( + Some(MediaBitrate { + total: Some(small.max(big)), + video: Some(big), + audio: Some(small), + }), + 2, + ); + for number in line + .split(" · ") + .filter_map(|part| part.split(' ').next()) + .filter_map(|n| n.parse::().ok()) + { + assert!(number > 0., "{small}/{big} bits a second rendered as {line:?}"); + } + } + } + } + #[test] fn timecode_counts_frames_inside_the_second() { assert_eq!(timecode(0., 30.), "00:00:00:00"); @@ -15734,6 +16497,18 @@ mod tests { // Before the first paint there is no bed and so no answer to give. assert_eq!(span_label(0.), "—"); assert_eq!(span_label(f64::NAN), "—"); + // A span under a second is a span: the tightest zoom is + // `ZOOM_MIN_FRAMES` across the bed, which on 240 fps slow-motion is + // 0.03s, and "0.0s" would be the pill saying nothing is on the bed. + for fps in [60., 120., 240., 1000.] { + let label = span_label(ZOOM_MIN_FRAMES / fps); + assert_ne!(label, "0.0s", "{fps} fps"); + assert_ne!(label, "0.00s", "{fps} fps"); + } + assert_eq!(span_label(ZOOM_MIN_FRAMES / 240.), "0.03s"); + // A frame of quiet at 60 fps, which the silence card says out loud. + assert_eq!(secs_label(1. / 60.), "0.02s"); + assert_eq!(secs_label(4.5), "4.5s"); } #[test] @@ -17366,7 +18141,11 @@ mod tests { let warmed = { let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); session.set_gain(0.0); - read_ahead(&asset("test_av2.mp4"), &stage); + let subs = read_ahead(&asset("test_av2.mp4"), &stage).expect("an mp4 is readable"); + // This mp4 is walked now (an mp4 can carry `tx3g`) and has no + // subtitle track in it, so the worker hands over an empty list -- + // the same thing the import lands with. + assert!(subs.is_empty()); session.import(&asset("test_av2.mp4")).expect("av2 matches"); ( session.sources().to_vec(), @@ -17385,7 +18164,7 @@ mod tests { // another rate is no more importable for having been read first. let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); session.set_gain(0.0); - read_ahead(&asset("test_25fps.mp4"), &stage); + drop(read_ahead(&asset("test_25fps.mp4"), &stage)); let warmed = session.import(&asset("test_25fps.mp4")); let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); session.set_gain(0.0); @@ -17396,8 +18175,53 @@ mod tests { .map_err(|e| e.to_string()) ); // A path nothing can read is the worker's business to survive, not to - // report: the engine says so a moment later, in its own words. - read_ahead(std::path::Path::new("/no/such/film.mkv"), &stage); + // report: the engine says so a moment later, in its own words. The + // subtitle half *is* carried back, because nothing walks it again to + // re-word it -- and it is a refusal, not a panic. + assert!( + read_ahead(std::path::Path::new("/no/such/film.mkv"), &stage).is_err(), + "an unreadable mkv comes back as the engine's refusal" + ); + } + + /// The import door's two halves, split across the worker hop: what + /// [`read_ahead`] walks is exactly what the render thread would have walked, + /// and pushing it says what walking it in place used to say. + #[test] + fn an_imports_subtitles_are_read_by_the_worker_and_only_pushed_here() { + use std::sync::atomic::AtomicU8; + let stage = AtomicU8::new(ImportStage::Header as u8); + let film = asset("test_subs.mkv"); + // The in-place walk (`subtitle_notice`) and the split one land the same + // tracks and the same tail on the same timeline. + let mut in_place = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + in_place.set_gain(0.0); + let said = subtitle_notice(&mut in_place, &film); + let mut split = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + split.set_gain(0.0); + let walked = read_ahead(&film, &stage).expect("the mkv is readable"); + assert_eq!(subtitle_tail(&mut split, Ok(walked)), said); + assert_eq!(split.subtitles().len(), in_place.subtitles().len()); + // The same file twice is still one row, and still says so: the dedupe + // lives in the push, which is the half that stayed here. + let again = read_ahead(&film, &stage).expect("the mkv is readable"); + assert_eq!(subtitle_tail(&mut split, Ok(again)), None); + // A standalone `.srt` is walked by the same worker: an import of one is + // not a door that reads on the render thread either. + let srt = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../engine/tests/data/test_subs.srt") + .canonicalize() + .expect("the subtitle fixture"); + assert_eq!( + read_ahead(&srt, &stage).expect("the srt is readable").len(), + 1 + ); + // ...and a refusal is worded as a tail, never as a failed import. + let unread: Subs = Err("nothing to read".into()); + assert_eq!( + subtitle_tail(&mut split, unread), + Some(" — SUBTITLES UNREAD: nothing to read".to_string()) + ); } #[test] @@ -17666,7 +18490,7 @@ mod tests { // never a guessed seat, and no seat at all for a format with no picture. let tail = summary_tail( Path::new("/a/take.export.mp4"), - Some(45), + Some(45_000_000), Some("VA-API"), true, ); @@ -17680,11 +18504,26 @@ mod tests { assert!(!summary_tail(Path::new("/a/x.wav"), None, None, false).contains("MB")); // 6 Mbps over a minute is 45 MB. `Auto` has no figure to estimate from // and an empty timeline no length: neither invents one. - assert_eq!(estimated_mb(Some(6_000_000), 60.), Some(45)); - assert_eq!(estimated_mb(Some(2_000_000), 90.), Some(23)); - assert_eq!(estimated_mb(None, 60.), None); - assert_eq!(estimated_mb(Some(6_000_000), 0.), None); - assert_eq!(estimated_mb(Some(0), 60.), None); + assert_eq!(estimated_bytes(Some(6_000_000), 60.), Some(45_000_000)); + assert_eq!(estimated_bytes(Some(2_000_000), 90.), Some(22_500_000)); + assert_eq!(estimated_bytes(None, 60.), None); + assert_eq!(estimated_bytes(Some(6_000_000), 0.), None); + assert_eq!(estimated_bytes(Some(0), 60.), None); + // ...and a short one is not nothing. Three seconds at the floor + // bitrate is 375 kB, which used to round to the "≈ 0 MB" this line + // exists to never say -- the shortest export a frame can make is + // still a real file with a real size. + let short = estimated_bytes(Some(1_000_000), 3.).expect("a rate and a length"); + assert_eq!(size_label(short), "375 kB"); + let frame = summary_tail(Path::new("/a/x.mp4"), estimated_bytes(Some(1_000_000), 1. / 60.), None, true); + assert!( + frame.contains("≈ 2 kB") && !frame.contains("0 MB") && !frame.contains("0 kB"), + "{frame}" + ); + // The boundary reads in the unit that can state it, either side. + assert_eq!(size_label(999_600), "1 MB"); + assert_eq!(size_label(499_000), "499 kB"); + assert_eq!(size_label(1), "1 kB"); } /// Which cue is on screen when: the whole of what the overlay decides, and @@ -17824,14 +18663,54 @@ mod tests { #[test] fn subtitles_arrive_beside_the_media_and_inside_it() { // Which door a path goes through is decided before anything is opened. - for name in ["subs.srt", "SUBS.SRT", "a.vtt", "a.ass", "a.ssa"] { + // ...and a `.mks` is one, the subtitles of a Matroska file alone: it has + // no source in it to import, so the drop door has to send it where `+ S` + // sends it. Its two siblings are media and must not come here -- a + // `.mka` is a song this would stop importing. + for name in ["subs.srt", "SUBS.SRT", "a.vtt", "a.ass", "a.ssa", "s.mks", "S.MKS"] { assert!(is_subtitle(Path::new(name)), "{name}"); } - for name in ["a.mp4", "a.mkv", "notes.txt", "a"] { + for name in ["a.mp4", "a.mkv", "song.mka", "film.mk3d", "notes.txt", "a"] { assert!(!is_subtitle(Path::new(name)), "{name}"); } - assert!(is_matroska(Path::new("film.MKV")) && is_matroska(Path::new("clip.webm"))); - assert!(!is_matroska(Path::new("clip.mp4"))); + // Every container the engine can walk for tracks inside it, Matroska + // and ISO-BMFF alike -- an mp4 carries `tx3g`, so the app has to ask it. + // The Matroska half is the engine's own closed set, extension for + // extension, so no file is walked here that it would refuse there. + for name in [ + "film.MKV", "clip.webm", "clip.mp4", "a.m4v", "a.MOV", "song.mka", "s.mks", "f.MK3D", + ] { + assert!(carries_subtitles(Path::new(name)), "{name}"); + assert!( + engine::demux::is_matroska(Path::new(name)) + || matches!( + Path::new(name) + .extension() + .and_then(|e| e.to_str()) + .map(str::to_ascii_lowercase) + .as_deref(), + Some("mp4" | "m4v" | "mov") + ), + "{name} is walked by the app but not by the engine" + ); + } + for name in ["song.wav", "still.png", "notes.txt", "a"] { + assert!(!carries_subtitles(Path::new(name)), "{name}"); + } + // The three doors, on the one file that used to split them: what the + // drop/argv door does with it ([`Player::take_import`] routes on + // `is_subtitle`), what the worker reads for it ([`walk_subtitles`]), and + // what `+ S` reads ([`Player::add_subtitles`] -> `parse_subtitles`) are + // the same walk of the same bytes. + let mks = asset("test_subs.mks"); + assert!(is_subtitle(&mks), "the drop door takes it as subtitles"); + let dropped = walk_subtitles(&mks).expect("the drop door's worker reads it"); + let plus_s = PlaybackSession::parse_subtitles(&mks).expect("`+ S` reads it"); + assert!(!dropped.is_empty(), "and there are tracks in it"); + assert_eq!( + dropped.iter().map(|t| &t.label).collect::>(), + plus_s.iter().map(|t| &t.label).collect::>(), + ); let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); session.set_gain(0.0); @@ -17886,7 +18765,8 @@ mod tests { assert_eq!(subtitle_detail(&session.subtitles()[1]), "3 cues"); // The same file twice adds nothing and says nothing. assert_eq!(subtitle_notice(&mut session, &asset("test_subs.mkv")), None); - // A container that cannot hold them is never even read. + // An mp4 is walked too (it can carry `tx3g`); this one holds none, so + // the notice grows no tail. assert_eq!(subtitle_notice(&mut session, &asset("test_av.mp4")), None); // A track that could not be read says why, where its cue count would @@ -17895,6 +18775,11 @@ mod tests { let refused = engine::subtitle::SubtitleTrack { path: PathBuf::from("/a/remux.mkv"), track: Some(1), + // Neither field, like `SubtitleTrack::refused` leaves them: what is + // refused is never written, and the row keeps the label it was + // refused under. + language: String::new(), + name: String::new(), label: "eng".into(), cues: Vec::new(), bitmap: false, @@ -18432,10 +19317,19 @@ mod tests { ); } + /// The two shapes the engine really builds: a track *of* a file states a + /// language and no title (`of_matroska`, `of_mp4`), and a standalone file + /// states no language and is its own name (`external`). fn sub(path: &str, track: Option, label: &str) -> engine::subtitle::SubtitleTrack { + let (language, name) = match track { + Some(_) => (label.to_string(), String::new()), + None => (String::new(), label.to_string()), + }; engine::subtitle::SubtitleTrack { path: PathBuf::from(path), track, + language, + name, label: label.to_string(), cues: Vec::new(), bitmap: false, @@ -18443,6 +19337,52 @@ mod tests { } } + /// A film's two ASS tracks with the timeline trimmed to twenty seconds: + /// one of them still has cues there and one has none, and the card said + /// nothing whatever about the second while the Subtitles list went on + /// showing it with its eighty-three cues. + /// + /// And the 25 GB remux's thirty-five: naming those wrapped the row to ten + /// lines and pushed Destination under the fold, so past the value box's + /// three lines the same line counts instead. + #[test] + fn the_card_names_the_subtitle_it_leaves_off_and_counts_them_when_it_cannot() { + let film = "/films/a-real-h264-dual-audio-film.mkv"; + let two = [ + sub(film, Some(1), "[ASS]"), + sub(film, Some(2), "[ASS] [FOR DUB]"), + ]; + // What the engine answers about the one pick that reached it, and what + // this side knows about the row that did not. + let named = subtitle_plan("[ASS] → embedded".to_string(), &two, &[0]); + assert_eq!(named, "[ASS] → embedded; [ASS] [FOR DUB] — no cues here"); + assert!( + named.chars().count() <= SUB_PLAN_CHARS, + "two tracks fit the value box: {named}" + ); + // Thirty-five off one file: twenty-two carry cues here, nine are + // pictures, one could not be read, three have nothing on this timeline. + let many: Vec<_> = (0..35) + .map(|i| { + let mut track = sub("/films/A Remux.mkv", Some(i), "eng — Subtitles"); + track.bitmap = (22..31).contains(&i); + track.refused = (i == 31).then(|| "VobSub is pictures".to_string()); + track + }) + .collect(); + // The picks are every track with a cue on the timeline: the twenty-two + // and the nine picture ones, which the engine drops itself. + let picks: Vec = (0..31usize).collect(); + let counted = subtitle_plan("22 tracks → embedded (…)".to_string(), &many, &picks); + assert_eq!(counted, "22 of 35 → embedded; 9 pictures; 1 unread; 3 no cues here"); + assert!( + counted.chars().count() <= SUB_PLAN_CHARS, + "thirty-five tracks still fit the value box: {counted}" + ); + // Nothing on the timeline at all is still the engine's word for it. + assert_eq!(subtitle_plan("none".to_string(), &[], &[]), "none"); + } + /// The list is in the order tracks were added, which is not the order a /// person reads it in: importing a second film puts its tracks after the /// first film's, and importing a third `.srt` for the first film puts that @@ -18565,6 +19505,28 @@ mod tests { assert_eq!(groups[0].rows[1].track, 2); } + /// The × on a row shifts every track after it down one, and the pick is + /// what an export writes into the file -- so a pick that stayed put would + /// silently change which track the next export carries. Every relation + /// between the pick and the row that went, on a list of three. + #[test] + fn removing_a_subtitle_row_carries_the_pick_with_it() { + // A row *before* the pick: the same track stays picked, one index down. + assert_eq!(sub_pick_after_removal(2, 0, 2), 1); + assert_eq!(sub_pick_after_removal(2, 1, 2), 1); + // A row *after* it: the pick has not moved and neither has its index. + assert_eq!(sub_pick_after_removal(0, 2, 2), 0); + assert_eq!(sub_pick_after_removal(1, 2, 2), 1); + // The picked row itself: the one that slid into its place... + assert_eq!(sub_pick_after_removal(1, 1, 2), 1); + // ...and the last row when the picked one was the last, since there is + // nothing after it to slide. + assert_eq!(sub_pick_after_removal(2, 2, 2), 1); + // The last row of all: an emptied list is legal for subtitles, and the + // section is not drawn at all at that point. + assert_eq!(sub_pick_after_removal(0, 0, 0), 0); + } + /// The same claim from the click's end, on the order imports actually /// arrive in: two films opened one after the other and an `.srt` dropped /// last interleave in the flat list, and the display reorders them. What a @@ -18621,6 +19583,30 @@ mod tests { // Reaching the subtitle rows too: a track whose only name was the tag. let groups = subtitle_rows(&[sub("/films/a.mkv", Some(1), "und")]); assert_eq!(groups[0].rows[0].label, "unknown language"); + // The pair, read as the pair: the row title comes off `language` and + // `name` and never out of the flattened label, which is what let an + // "und" beside a title through as a language nobody speaks. A refused + // track states neither and keeps its label. + let titled = |language: &str, name: &str, label: &str| engine::subtitle::SubtitleTrack { + path: PathBuf::from("/films/a.mkv"), + track: Some(1), + language: language.into(), + name: name.into(), + label: label.into(), + cues: Vec::new(), + bitmap: false, + refused: None, + }; + for (language, name, label, title) in [ + ("fra", "Signs", "fra — Signs", "fra — Signs"), + ("und", "Signs", "Signs", "Signs"), + ("und", "", "und", "unknown language"), + ("", "late.srt", "late.srt", "late.srt"), + ("", "", "eng", "eng"), + ] { + let rows = subtitle_rows(&[titled(language, name, label)]); + assert_eq!(rows[0].rows[0].label, title, "{language:?} {name:?}"); + } } /// The bug: an empty timeline is end-of-stream from its one black frame @@ -18823,6 +19809,7 @@ fn main() { selected_asset: None, waves: HashMap::new(), streams: HashMap::new(), + bitrates: HashMap::new(), sizes: HashMap::new(), decoders: HashMap::new(), export_seat: None, diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 26bc301..a436803 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -139,6 +139,214 @@ pub struct VideoMeta { pub color: ColorDescription, } +/// What a file spends its bytes at, in bits per second -- the whole file, and +/// what each of its streams costs inside it. +/// +/// The three are one budget split three ways, so all three are measured over +/// **the same seconds**: the container's own duration, not each track's. That +/// is what makes the line read as a breakdown -- `total` can never come out +/// below `video + audio`, because those are disjoint byte counts over a shared +/// denominator, and the leftover is the container's overhead. Dividing each +/// track by its own length is how a file with 2 s of picture and 60 s of sound +/// reports a total thirty times its real byte rate, under components that add +/// up to a thirtieth of it. +/// +/// Every field is `None` rather than `0` wherever the container does not state +/// the number and nothing here derives it. A properties row a header did not +/// give is left out rather than shown as a zero, and a fabricated `0 kbps` is +/// not a missing measurement, it is a wrong one. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct MediaBitrate { + /// Every byte of the file over its playing time -- both streams, the + /// container's overhead and all -- which is what "the bitrate of a file" + /// means to anyone reading it, and what `ffprobe` calls `format=bit_rate`. + pub total: Option, + /// The picture track's own bytes over that same time. + pub video: Option, + /// The bytes of the **one sound track this engine would play**, over that + /// same time -- first in file order, which is the rule + /// [`crate::audio::AudioSession::probe_streams`] hands out stream 0 by and + /// the one playback and export open. A dual-audio file has more, and this + /// number describes neither their sum nor the biggest of them; ask + /// `probe_streams` how many there are before calling this "the sound". + pub audio: Option, +} + +/// What `path` is coded at, from its header and its sample table alone -- +/// **no decoder is opened**, which is what lets a library probe run this over +/// every file it lists. +/// +/// The cost is one [`Demuxer::open`]: an mp4's boxes, or a Matroska segment's +/// element headers, both of which the caller's other per-file probes already +/// pay. Nothing here reads a block payload. +/// +/// Cheap is not instant, and the caller has to know which: measured over +/// `a local media folder`, every mp4 answered in single-digit milliseconds, and a +/// 12.9 GB 2160p AV1 Matroska took **seconds** cold and ~150 ms warm -- +/// Matroska indexes no samples, so its open walks every cluster header in the +/// file, and what that costs is disk, not arithmetic. Timings on that file +/// swing between ~150 ms and ~1.2 s run to run on the same build, so treat any +/// figure here as an order of magnitude and nothing finer. This belongs on +/// `background_executor` like every other open, never on a repaint. +/// +/// A file that will not open at all -- no video track, a codec nothing reads, +/// a still image, which has no playing time of its own -- comes back all +/// `None`. That is the answer, not an error: the cards this feeds show the +/// rows they have. +pub fn probe_bitrate(path: &Path) -> MediaBitrate { + let unstated = MediaBitrate::default(); + let Ok(bytes) = std::fs::metadata(path).map(|m| m.len()) else { + return unstated; + }; + // A still is as long as the clip is stretched to, so there is no per-second + // anything to state about the file. + if crate::is_image(path) { + return unstated; + } + // A standalone audio file's length is not a frame count; it is what the + // audio header says, exactly as `PlaybackSession::import` reads it. + // + // ponytail: `duration_secs` falls back to a decode for a stream whose + // header states no length (a bare mp3 with no Xing header), which is the + // one input here that is not header-only -- ~0.5 ms per source second, the + // same cost import already pays for that file. Upgrade path is a + // header-only variant that answers `None` instead of decoding. + if crate::is_audio(path) { + let Ok(Some(secs)) = crate::AudioSession::duration_secs(path) else { + return unstated; + }; + let total = bits_per_second(bytes, secs); + // One stream and nothing else in the file: what a second of it costs is + // what a second of its sound costs, give or take a header. + return MediaBitrate { + total, + video: None, + audio: total, + }; + } + let Ok((meta, demuxer)) = Demuxer::open(path) else { + return unstated; + }; + // How long the *file* plays, which on a well-made file is how long its + // picture plays and on a badly-made one is not: a 2 s clip carrying a 60 s + // commentary is 60 s of file, and dividing its bytes by 2 claims thirty + // times the byte rate it really has. Both containers state this outright -- + // an mp4 in the `mvhd` (the movie header, which spans every track), a + // Matroska in `Info.Duration` -- so it is read rather than derived. + // + // Where a file states none, the picture's own length is the fallback and + // the old answer: frame count over frame rate, the same length the timeline + // lays the clip out at. + let stated = match &demuxer { + Demuxer::Mkv(d) => d.container_secs, + Demuxer::Mp4(d) => { + let mvhd = &d.reader.moov.mvhd; + (mvhd.timescale > 0 && mvhd.duration > 0) + .then(|| mvhd.duration as f64 / f64::from(mvhd.timescale)) + } + }; + let secs = stated.unwrap_or(match meta.frame_rate > 0.0 { + true => f64::from(meta.frame_count) / meta.frame_rate, + false => 0.0, + }); + let (video, audio) = match &demuxer { + // Matroska indexes no samples, so what the open's one walk counted *is* + // the sample table: block bytes per track number ([`mkv_blocks`]), the + // sound's beside the picture's, neither of them costing a second pass. + Demuxer::Mkv(d) => { + let bytes_of = |number| { + d.track_bytes + .iter() + .find(|(n, _)| *n == number) + .map(|&(_, bytes)| bytes) + }; + ( + // The picture's blocks are indexed, so its size is that index. + // Measured, this is the same number `track_bytes` holds for the + // same track on every fixture and every file in `a local media folder`; + // the two can only part on a *laced* video track, where one + // block becomes several `Block`s over the frame bytes alone and + // the lace header is left out. Nothing here has ever produced + // one -- lacing is a sound-track trick -- so this is a + // difference of principle, not one anything has exercised. + bits_per_second(d.blocks.iter().map(|b| b.len as u64).sum(), secs), + // The sound's, from the raw block lengths, lace headers + // included: the two components are measured on slightly + // different bases for that reason, which is worth tens of bytes + // a block and nothing on the rate. + d.audio_number + .and_then(bytes_of) + .and_then(|bytes| bits_per_second(bytes, secs)), + ) + } + Demuxer::Mp4(d) => { + let tracks = d.reader.tracks(); + // In file order, out of `moov.traks`, for [`Mp4Demuxer::open`]'s + // reason and for `audio::audio_track_ids`': `tracks()` is a + // `HashMap`, so "the audio track" of a dual-audio file would + // otherwise be a different one per run. Deliberately the *same* + // first-in-file rule the audio path picks stream 0 by, so the + // bitrate row and the audio row of one card name one track -- see + // [`MediaBitrate::audio`], which says what that number is not. + let audio = d + .reader + .moov + .traks + .iter() + .map(|trak| trak.tkhd.track_id) + .find(|id| { + tracks + .get(id) + .is_some_and(|t| matches!(t.track_type(), Ok(TrackType::Audio))) + }); + let rate = |id| { + tracks + .get(id) + .map(mp4_track_bytes) + .and_then(|bytes| bits_per_second(bytes, secs)) + }; + (rate(&d.track_id), audio.as_ref().and_then(rate)) + } + }; + MediaBitrate { + total: bits_per_second(bytes, secs), + video, + audio, + } +} + +/// `bytes` over `secs`, in bits per second, or `None` where that is not a +/// number worth showing: nothing measured either side, or a rate that rounds to +/// zero. A `0` here would read as a real measurement, which is the one answer +/// this must never give. +fn bits_per_second(bytes: u64, secs: f64) -> Option { + (secs > 0.0) + .then(|| (bytes as f64 * 8.0 / secs) as u64) + .filter(|&bps| bps > 0) +} + +/// How many bytes of the file an mp4 track's samples are -- its share of the +/// `mdat`, which over the container's seconds is its share of the byte rate. +/// +/// Not `Mp4Track::bitrate`, deliberately, though that looks like the ready-made +/// answer. It divides by the track's *own* duration, which is the arithmetic +/// [`MediaBitrate`] exists to not do; it truncates that duration to whole +/// seconds (`mp4-0.14.0/src/track.rs:213`), so a file under a second comes back +/// `0`; and for an `mp4a` track it answers `esds.avg_bitrate` instead, a number +/// the encoder declared rather than one the file spends, which is `0` on any +/// `esds` that declared none. Bytes are what all three of these fields agree to +/// be measured in. +/// +/// `Mp4Track::total_sample_size` is private to that crate; this is it, off the +/// `stsz` fields that are not. +fn mp4_track_bytes(track: &Mp4Track) -> u64 { + let stsz = &track.trak.mdia.minf.stbl.stsz; + match stsz.sample_size { + 0 => stsz.sample_sizes.iter().map(|&n| u64::from(n)).sum(), + uniform => u64::from(uniform) * u64::from(track.sample_count()), + } +} + /// The file, whichever container it came in. Which one is decided by the /// extension at [`Demuxer::open`] and never again: everything downstream -- /// playback, export, the plugin -- speaks access units and display frames. @@ -279,10 +487,18 @@ impl Demuxer { /// the demuxer is what really decides, but the audio path has to know before it /// opens anything that this file's sound is read by symphonia's `mkv` reader /// and not by either mp4 one (see [`crate::audio::Track::open`]). +/// +/// *Every* extension Matroska states, not the two that carry a film: `.mka` is +/// the sound alone and `.mks` the subtitles alone -- the same bytes, the same +/// reader, so refusing them was this engine refusing a file it parses. The set +/// is the standard's own and closed by it. pub fn is_matroska(path: &Path) -> bool { - path.extension() - .and_then(|e| e.to_str()) - .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "mkv" | "webm")) + path.extension().and_then(|e| e.to_str()).is_some_and(|e| { + matches!( + e.to_ascii_lowercase().as_str(), + "mkv" | "mka" | "mks" | "mk3d" | "webm" + ) + }) } pub struct Mp4Demuxer { @@ -553,6 +769,18 @@ pub struct MkvDemuxer { /// What the track's `ContentEncodings` asks of every block; [`Unpack::None`] /// for a file that declares none, which is most of them. unpack: Unpack, + /// Block bytes per `TrackNumber`, counted by the one walk the open already + /// does -- the sound track's as well as the picture's. [`probe_bitrate`] is + /// the only reader; see [`mkv_blocks`] for why it is collected here rather + /// than by a pass of its own. + track_bytes: Vec<(u64, u64)>, + /// `TrackNumber` of the file's first audio track, the one + /// [`matroska_audio_codec`] also answers for; `None` for a silent file. + audio_number: Option, + /// What `Info.Duration` says the whole *file* plays for, in seconds -- + /// which is not the picture's length on a file whose sound outlasts it. + /// `None` for the rare file that states none. [`probe_bitrate`] only. + container_secs: Option, } impl MkvDemuxer { @@ -560,7 +788,7 @@ impl MkvDemuxer { let mut file = File::open(path)?; let end = file.metadata()?.len(); let segment = mkv_segment(&mut file, end)?; - let (video, _, other, _) = mkv_tracks(&mut file, segment)?; + let (video, audio, other, _, container_secs) = mkv_tracks(&mut file, segment)?; let video = match video { Some(video) => video, // Named, because "no video track" is a lie about a file that has one @@ -587,7 +815,7 @@ impl MkvDemuxer { if let Unpack::Refused(why) = &video.unpack { return Err(why.clone().into()); } - let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?; + let (blocks, span, track_bytes) = mkv_blocks(&mut file, segment, video.number)?; if blocks.is_empty() { return Err(format!( "the {} track in this Matroska file has no frames", @@ -646,6 +874,9 @@ impl MkvDemuxer { scratch: Vec::new(), next: 0, unpack: video.unpack, + track_bytes, + audio_number: audio.first().map(|t| t.number), + container_secs, }, )) } @@ -783,7 +1014,7 @@ impl MkvAudio { let mut file = File::open(path)?; let end = file.metadata()?.len(); let segment = mkv_segment(&mut file, end)?; - let (_, audio, _, timestamp_scale) = mkv_tracks(&mut file, segment)?; + let (_, audio, _, timestamp_scale, _) = mkv_tracks(&mut file, segment)?; let Some(MkvAudioTrack { number, codec, @@ -807,7 +1038,7 @@ impl MkvAudio { if let Unpack::Refused(why) = &unpack { return Err(why.clone().into()); } - let (blocks, _) = mkv_blocks(&mut file, segment, number)?; + let (blocks, _, _) = mkv_blocks(&mut file, segment, number)?; if blocks.is_empty() { return Err("the AC-3 track in this Matroska file has no blocks".into()); } @@ -992,6 +1223,7 @@ fn mkv_content_encoding(file: &mut File, body: u64, end: u64) -> crate::Result crate::Result<(u64, u64)> { fn mkv_tracks( file: &mut File, segment: (u64, u64), -) -> crate::Result<(Option, Vec, Option, u64)> { +) -> crate::Result<( + Option, + Vec, + Option, + u64, + Option, +)> { let (mut video, mut other) = (None, None); let mut audio = Vec::new(); let mut timestamp_scale = 1_000_000; + // `Info.Duration`, in `TimestampScale` ticks: how long the *file* is, which + // is not how long its picture is -- see [`probe_bitrate`], which divides by + // this. Written by every muxer in practice and optional by the spec, so the + // absence of it is a `None` and not a zero. + let mut duration = None; let mut at = segment.0; while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { match id { @@ -1069,8 +1316,10 @@ fn mkv_tracks( INFO => { let mut at = body; while let Some(e) = ebml_element(file, at, stop)? { - if e.0 == TIMESTAMP_SCALE { - timestamp_scale = ebml_uint(file, e.1, e.2)?.max(1); + match e.0 { + TIMESTAMP_SCALE => timestamp_scale = ebml_uint(file, e.1, e.2)?.max(1), + DURATION => duration = Some(ebml_float(file, e.1, e.2)?), + _ => {} } at = e.2; } @@ -1097,7 +1346,9 @@ fn mkv_tracks( } at = stop; } - Ok((video, audio, other, timestamp_scale)) + // Ticks to seconds: `TimestampScale` is nanoseconds a tick is worth. + let secs = duration.filter(|d| *d > 0.0).map(|d| d * timestamp_scale as f64 / 1e9); + Ok((video, audio, other, timestamp_scale, secs)) } /// What one `TrackEntry` turned out to be. @@ -1110,6 +1361,107 @@ enum MkvEntry { Other, } +/// What language a `TrackEntry` states, as the three-letter ISO 639-2 code the +/// rest of this engine speaks -- the one the muxer writes back into +/// `TRACK_LANGUAGE` and the one an mp4's `mdhd` packs into 16 bits. +/// +/// **`LanguageBCP47` wins**, which is the spec's own precedence and not a +/// preference: a modern file states its languages there and leaves the legacy +/// element out, so reading only the old one lost them. A +/// dual-language remux carries 37 `LanguageBCP47` elements against 33 legacy +/// ones and every English track of it is BCP-47 only -- they all used to come in +/// as `und` and export with no language at all. +/// +/// A tag is cut to its primary subtag and mapped by [`ISO_639_1_TO_2`], so `en` +/// and `en-US` are both `eng`: the region is not the language, and neither the +/// Matroska element nor the mp4 field can hold one. Three letters already +/// (`fil`, and every ISO 639-3 tag) are kept as they are. Anything else -- a +/// private `x-…` tag, a tag nothing maps -- falls back to the legacy element +/// rather than throwing the file's word away. +/// +/// `und` for a track that states neither. The spec's *default* is `eng` +/// (measured: ffmpeg 8.1.2 reports `eng` for a `TrackEntry` with no `Language` +/// element, and reads no `LanguageBCP47` at all), but writing English into a +/// track whose file never said so is this engine's claim and not the file's -- +/// a Japanese film's untitled track would export labelled English. What is +/// *stated* is kept; the default is left to the readers that want it. +fn mkv_language(legacy: &str, bcp47: &str) -> String { + let primary = bcp47 + .split('-') + .next() + .unwrap_or_default() + .to_ascii_lowercase(); + let mapped = match primary.len() { + 2 => ISO_639_1_TO_2 + .iter() + .find(|(two, _)| *two == primary) + .map(|(_, three)| (*three).to_owned()), + 3 => Some(primary), + _ => None, + }; + match mapped { + Some(code) => code, + None if !legacy.is_empty() => legacy.to_owned(), + None => "und".into(), + } +} + +/// Every ISO 639-1 code and the 639-2 (terminology) one it names the same +/// language with -- what [`mkv_language`] maps a BCP-47 primary subtag through. +/// +/// The whole standard and not the languages a test happened to use: generated +/// from `iso-codes`' own `iso_639-2.json`, so a Kannada track is as readable as +/// an English one. +#[rustfmt::skip] +const ISO_639_1_TO_2: &[(&str, &str)] = &[ + ("aa", "aar"), ("ab", "abk"), ("ae", "ave"), ("af", "afr"), + ("ak", "aka"), ("am", "amh"), ("an", "arg"), ("ar", "ara"), + ("as", "asm"), ("av", "ava"), ("ay", "aym"), ("az", "aze"), + ("ba", "bak"), ("be", "bel"), ("bg", "bul"), ("bi", "bis"), + ("bm", "bam"), ("bn", "ben"), ("bo", "bod"), ("br", "bre"), + ("bs", "bos"), ("ca", "cat"), ("ce", "che"), ("ch", "cha"), + ("co", "cos"), ("cr", "cre"), ("cs", "ces"), ("cu", "chu"), + ("cv", "chv"), ("cy", "cym"), ("da", "dan"), ("de", "deu"), + ("dv", "div"), ("dz", "dzo"), ("ee", "ewe"), ("el", "ell"), + ("en", "eng"), ("eo", "epo"), ("es", "spa"), ("et", "est"), + ("eu", "eus"), ("fa", "fas"), ("ff", "ful"), ("fi", "fin"), + ("fj", "fij"), ("fo", "fao"), ("fr", "fra"), ("fy", "fry"), + ("ga", "gle"), ("gd", "gla"), ("gl", "glg"), ("gn", "grn"), + ("gu", "guj"), ("gv", "glv"), ("ha", "hau"), ("he", "heb"), + ("hi", "hin"), ("ho", "hmo"), ("hr", "hrv"), ("ht", "hat"), + ("hu", "hun"), ("hy", "hye"), ("hz", "her"), ("ia", "ina"), + ("id", "ind"), ("ie", "ile"), ("ig", "ibo"), ("ii", "iii"), + ("ik", "ipk"), ("io", "ido"), ("is", "isl"), ("it", "ita"), + ("iu", "iku"), ("ja", "jpn"), ("jv", "jav"), ("ka", "kat"), + ("kg", "kon"), ("ki", "kik"), ("kj", "kua"), ("kk", "kaz"), + ("kl", "kal"), ("km", "khm"), ("kn", "kan"), ("ko", "kor"), + ("kr", "kau"), ("ks", "kas"), ("ku", "kur"), ("kv", "kom"), + ("kw", "cor"), ("ky", "kir"), ("la", "lat"), ("lb", "ltz"), + ("lg", "lug"), ("li", "lim"), ("ln", "lin"), ("lo", "lao"), + ("lt", "lit"), ("lu", "lub"), ("lv", "lav"), ("mg", "mlg"), + ("mh", "mah"), ("mi", "mri"), ("mk", "mkd"), ("ml", "mal"), + ("mn", "mon"), ("mr", "mar"), ("ms", "msa"), ("mt", "mlt"), + ("my", "mya"), ("na", "nau"), ("nb", "nob"), ("nd", "nde"), + ("ne", "nep"), ("ng", "ndo"), ("nl", "nld"), ("nn", "nno"), + ("no", "nor"), ("nr", "nbl"), ("nv", "nav"), ("ny", "nya"), + ("oc", "oci"), ("oj", "oji"), ("om", "orm"), ("or", "ori"), + ("os", "oss"), ("pa", "pan"), ("pi", "pli"), ("pl", "pol"), + ("ps", "pus"), ("pt", "por"), ("qu", "que"), ("rm", "roh"), + ("rn", "run"), ("ro", "ron"), ("ru", "rus"), ("rw", "kin"), + ("sa", "san"), ("sc", "srd"), ("sd", "snd"), ("se", "sme"), + ("sg", "sag"), ("si", "sin"), ("sk", "slk"), ("sl", "slv"), + ("sm", "smo"), ("sn", "sna"), ("so", "som"), ("sq", "sqi"), + ("sr", "srp"), ("ss", "ssw"), ("st", "sot"), ("su", "sun"), + ("sv", "swe"), ("sw", "swa"), ("ta", "tam"), ("te", "tel"), + ("tg", "tgk"), ("th", "tha"), ("ti", "tir"), ("tk", "tuk"), + ("tl", "tgl"), ("tn", "tsn"), ("to", "ton"), ("tr", "tur"), + ("ts", "tso"), ("tt", "tat"), ("tw", "twi"), ("ty", "tah"), + ("ug", "uig"), ("uk", "ukr"), ("ur", "urd"), ("uz", "uzb"), + ("ve", "ven"), ("vi", "vie"), ("vo", "vol"), ("wa", "wln"), + ("wo", "wol"), ("xh", "xho"), ("yi", "yid"), ("yo", "yor"), + ("za", "zha"), ("zh", "zho"), ("zu", "zul"), +]; + /// One `TrackEntry`, read for what it is. fn mkv_track_entry( file: &mut File, @@ -1119,7 +1471,7 @@ fn mkv_track_entry( ) -> crate::Result { let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); let (mut width, mut height, mut config) = (0, 0, Vec::new()); - let (mut language, mut name) = (String::new(), String::new()); + let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new()); let mut tags = Tags::default(); let mut light = ContentLight::default(); let mut unpack = Unpack::None; @@ -1130,6 +1482,7 @@ fn mkv_track_entry( CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?, TRACK_TYPE => kind = ebml_uint(file, body, stop)?, TRACK_LANGUAGE => language = string_of(file, body, stop)?, + TRACK_LANGUAGE_BCP47 => bcp47 = string_of(file, body, stop)?, TRACK_NAME => name = string_of(file, body, stop)?, DEFAULT_DURATION => { default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0) @@ -1214,13 +1567,10 @@ fn mkv_track_entry( return Ok(MkvEntry::Audio(MkvAudioTrack { number, codec, - // What a `TrackEntry` without a `Language` element means, by spec -- - // the same default the subtitle walk applies. - language: if language.is_empty() { - "und".into() - } else { - language - }, + // Whichever element the file states it in, and `und` for one that + // states neither ([`mkv_language`]) -- the same answer the subtitle + // walk gets, so a dual-audio remux and its subtitles agree. + language: mkv_language(&language, &bcp47), name, unpack, })); @@ -1440,7 +1790,14 @@ fn vp9_bit_depth(au: &[u8]) -> crate::Result> { /// Every block of track `number`, in storage order, with the presentation span /// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback -/// needs. +/// needs -- and, third, how many block bytes *every* track of the file spends, +/// `(TrackNumber, bytes)` in first-seen order. +/// +/// That third answer is why this is one pass and not two: a block's length is +/// already parsed out of its header here, on the way to deciding it belongs to +/// another track and skipping it, so the sound track's size costs a lookup in a +/// list of two or three rather than a second walk of the segment (six seconds of +/// one, on a 12 GB film). [`probe_bitrate`] is what reads it. /// /// Only element headers are read: a block's payload is seeked over and fetched /// later by [`MkvDemuxer::next_access_unit`], which is what keeps this an index @@ -1449,8 +1806,11 @@ fn mkv_blocks( file: &mut File, segment: (u64, u64), number: u64, -) -> crate::Result<(Vec, Option<(i64, i64)>)> { +) -> crate::Result<(Vec, Option<(i64, i64)>, Vec<(u64, u64)>)> { let mut blocks = Vec::new(); + // A file has a handful of tracks, so this is a shorter linear scan than a + // hash would be a hash. + let mut track_bytes: Vec<(u64, u64)> = Vec::new(); // Where each laced block's frames landed, so their timestamps can be spread // once the block after is known -- see the fixup below. let mut laced: Vec<(usize, usize)> = Vec::new(); @@ -1495,6 +1855,14 @@ fn mkv_blocks( } _ => continue, }; + // Before the track filter, so this counts the whole file: the block + // as it sits on disk, lace header included, which is what that track + // costs the container. No read is added -- `len` came out of the + // header that was parsed to get here. + match track_bytes.iter_mut().find(|(n, _)| *n == block.number) { + Some((_, bytes)) => *bytes += block.len as u64, + None => track_bytes.push((block.number, block.len as u64)), + } if block.number != number { continue; } @@ -1548,7 +1916,7 @@ fn mkv_blocks( .map(|b| b.ts) .min() .zip(blocks.iter().map(|b| b.ts).max()); - Ok((blocks, span)) + Ok((blocks, span, track_bytes)) } /// The frames inside a laced block: one `(offset, length)` each, in order. @@ -2127,10 +2495,9 @@ pub struct MkvCue { /// display sets, read by [`crate::subtitle`] as [`MkvCue`]s like any other. pub const PGS: &str = "S_HDMV/PGS"; -/// The subtitle tracks of a Matroska file, in file order. An mp4's are not read -/// (its `tx3g` is a different beast, and no file this project opens carries -/// one); anything that is not a Matroska file at all is an error, as it is for -/// [`matroska_audio_codec`]. +/// The subtitle tracks of a Matroska file, in file order. An mp4's are a +/// different beast and are read by [`mp4_subtitles`]; anything that is not a +/// Matroska file at all is an error, as it is for [`matroska_audio_codec`]. /// /// Two passes at most: the header walk stops at the first `Cluster`, and the /// cue pass runs only when there is a text track to fill. @@ -2178,11 +2545,133 @@ pub fn matroska_subtitles(path: &Path) -> crate::Result> { Ok(tracks) } +/// One timed-text subtitle track of an mp4 -- the `tx3g` sample entry ffmpeg +/// calls `mov_text` -- exactly as its `trak` declares it. The mp4 half of +/// [`MkvSubtitle`]: what the samples *mean* is [`crate::subtitle`]'s business, +/// this is the walk. +#[derive(Debug)] +pub struct Mp4Subtitle { + /// The `tkhd` track id, which is what a `.edith` row names the track by. + pub number: u64, + /// The `mdhd` language, ISO-639-2. `und` where the file states none, which + /// is the only thing that field can say -- an mp4 packs three letters into + /// sixteen bits and cannot leave them out. + pub language: String, + /// `trak/udta/name`, the title a muxer wrote (`Signs`), empty for the far + /// more common track that has none. The box ffmpeg reads and writes a + /// `-metadata:s:s:0 title=` in, and the one [`crate::mux`] patches in. + pub name: String, + /// Every sample of the track, in storage order. + pub samples: Vec, +} + +/// One timed-text sample: when it shows, when it stops, and the bytes. +#[derive(Debug)] +pub struct Mp4TextSample { + /// Microseconds from the start of the file -- the sample's decode time + /// scaled by the track's own `mdhd` timescale, which is milliseconds in + /// what this project writes and microseconds in what ffmpeg writes. + pub start_us: i64, + /// Where the next sample begins: a timed-text track states one sample per + /// instant and leaves no holes, so this is the sample's `stts` duration on + /// top of its start and not a guess ([`crate::subtitle`]'s Matroska side + /// has to guess -- see `end_of` there). + pub end_us: i64, + /// ISO/IEC 14496-17: the text's length in 16 bits, then the UTF-8 itself. + /// A payload of `00 00` is a sample of *no text*, which is the stretch + /// between two cues rather than a cue with nothing in it. + pub payload: Vec, +} + +/// The timed-text subtitle tracks of an mp4, in track-id order -- the reader +/// that makes an mp4 export of this project's own openable again, and reads a +/// `mov_text` track ffmpeg muxed just the same. +/// +/// The samples come out of the `mp4` crate, which walks `stts`/`stsz`/`stco` +/// for any track type; the *title* does not, because that crate's `TrakBox` has +/// no `udta` field at all -- so the one box carrying it is read by hand out of +/// the `moov`, the way [`sample_entry`] reads an `stsd` entry the crate drops. +/// +/// A file with no timed-text track comes back empty, never an error; a file that +/// is not an mp4 at all is an error, as [`matroska_subtitles`] is for a +/// non-Matroska. +pub fn mp4_subtitles(path: &Path) -> crate::Result> { + let file = File::open(path)?; + let size = file.metadata()?.len(); + let mut reader = Mp4Reader::read_header(BufReader::new(file), size)?; + let mut ids: Vec = reader + .tracks() + .iter() + .filter(|(_, track)| matches!(track.track_type(), Ok(TrackType::Subtitle))) + .map(|(id, _)| *id) + .collect(); + // By track id, which is the order the tracks were written in: a `HashMap` + // hands them over in whatever order it likes, and a row picks a track by + // its number out of a list a user saw. + ids.sort_unstable(); + let names = mp4_track_names(path)?; + let mut tracks = Vec::with_capacity(ids.len()); + for id in ids { + let track = &reader.tracks()[&id]; + // Off the borrow before the samples, which need the reader itself. + let language = track.language().to_owned(); + let timescale = i128::from(track.timescale().max(1)); + let count = track.sample_count(); + let mut samples = Vec::with_capacity(count as usize); + for i in 1..=count { + // Sample ids count from 1. A sample the tables cannot reach is + // skipped rather than raised: the other cues of the track are still + // the words a viewer needs. + let Some(sample) = reader.read_sample(id, i)? else { + continue; + }; + let us = |ticks: u64| (i128::from(ticks) * 1_000_000 / timescale) as i64; + samples.push(Mp4TextSample { + start_us: us(sample.start_time), + end_us: us(sample.start_time + u64::from(sample.duration)), + payload: sample.bytes.to_vec(), + }); + } + tracks.push(Mp4Subtitle { + number: u64::from(id), + language, + name: names + .iter() + .find(|(track_id, _)| *track_id == id) + .map(|(_, name)| name.clone()) + .unwrap_or_default(), + samples, + }); + } + Ok(tracks) +} + +/// Each `trak`'s `udta/name`, by track id, for the traks that have one -- an +/// mp4's word for what a track is *called*, beside the `mdhd` language it is +/// in. Read by hand for the reason [`mp4_subtitles`] gives. +fn mp4_track_names(path: &Path) -> crate::Result> { + let Some(moov) = read_top_level(path, b"moov")? else { + return Ok(Vec::new()); + }; + Ok(boxes(&moov) + .filter(|(kind, _)| *kind == b"trak") + .filter_map(|(_, trak)| { + let id = child(trak, b"tkhd").and_then(tkhd_track_id)?; + let name = child(trak, b"udta").and_then(|udta| child(udta, b"name"))?; + // Raw bytes, no version or flags -- and a writer that terminates the + // string is not lying about the title, it is padding it. + let name = String::from_utf8_lossy(name); + Some((id, name.trim_end_matches('\0').to_owned())) + }) + .collect()) +} + /// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles. fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result> { const SUBTITLE: u64 = 0x11; let (mut number, mut kind, mut codec) = (0, 0, String::new()); let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new()); + let mut bcp47 = String::new(); let mut unpack = Unpack::None; let mut at = body; 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 codec = string_of(file, body, stop)?, CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?, TRACK_LANGUAGE => language = string_of(file, body, stop)?, + TRACK_LANGUAGE_BCP47 => bcp47 = string_of(file, body, stop)?, TRACK_NAME => name = string_of(file, body, stop)?, _ => {} } @@ -2201,12 +2691,9 @@ fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result crate::Result { mod tests { use super::*; + /// What a `TrackEntry` states it is in, whichever of the two elements it + /// states it in -- [`mkv_language`]'s whole rule, as asserts. + #[test] + fn a_track_states_its_language_in_either_element() { + // The modern element wins over the legacy one, which is the spec's own + // precedence: some films carry a Bulgarian legacy code beside an English + // BCP-47 tag on different tracks, and the English ones state nothing + // else at all. + assert_eq!(mkv_language("", "en"), "eng"); + assert_eq!(mkv_language("bul", "en"), "eng"); + // A region is not a language: neither Matroska's legacy element nor an + // mp4's 16-bit field can hold one, so `en-US` is the English it is. + assert_eq!(mkv_language("", "en-US"), "eng"); + assert_eq!(mkv_language("", "pt-BR"), "por"); + assert_eq!(mkv_language("", "zh-Hans"), "zho"); + // ...and every other language of the table, not the ones a test used. + assert_eq!(mkv_language("", "kn"), "kan"); + assert_eq!(mkv_language("", "JA"), "jpn"); + // Three letters already: an ISO 639-3 tag is what the code is. + assert_eq!(mkv_language("", "fil"), "fil"); + // What nothing maps falls back to the file's other word rather than + // being thrown away, and `und` is only for a file that said neither. + assert_eq!(mkv_language("fra", "x-pig-latin"), "fra"); + assert_eq!(mkv_language("", "x-pig-latin"), "und"); + assert_eq!(mkv_language("fra", ""), "fra"); + assert_eq!(mkv_language("und", ""), "und"); + assert_eq!(mkv_language("", ""), "und"); + // The table is the standard's own: one entry per ISO 639-1 code, none + // of them doubled, every code the two and three letters it is. + let mut seen: Vec<&str> = ISO_639_1_TO_2.iter().map(|(two, _)| *two).collect(); + let count = seen.len(); + seen.sort_unstable(); + seen.dedup(); + assert_eq!(seen.len(), count, "a doubled ISO 639-1 code"); + for (two, three) in ISO_639_1_TO_2 { + assert!( + two.len() == 2 && three.len() == 3, + "{two} → {three} is not a 639-1 → 639-2 pair" + ); + } + } + + /// Every extension Matroska states, and nothing that is not one: `.mks` is + /// the subtitles alone and `.mka` the sound alone, both the same bytes the + /// `.mkv` reader already walks. + #[test] + fn every_matroska_extension_is_a_matroska() { + for name in ["a.mkv", "a.mka", "a.mks", "a.mk3d", "a.webm", "A.MKS"] { + assert!(is_matroska(Path::new(name)), "{name}"); + } + for name in ["a.mp4", "a.m4v", "a.mov", "a.srt", "a", "a.mk"] { + assert!(!is_matroska(Path::new(name)), "{name}"); + } + } + /// The capability matrix, as an assert: every codec the decoder layer can be /// handed is reachable from *both* container dispatches, and every gap is a /// row in [`UNSUPPORTED`] that is genuinely a gap. A codec wired into diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 2e0ebd9..a3e9b87 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -1087,6 +1087,8 @@ mod tests { SubtitleTrack { path: PathBuf::from(path), track, + language: String::new(), + name: String::new(), label: String::new(), cues: Vec::new(), bitmap: false, diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index ee3a361..873dbf6 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -226,7 +226,7 @@ impl Format { /// What the caller gets to decide about the output. The codec is not among it: /// [`Format`] names a container *and* what goes in it, because every pair we /// can write is a pair we can also read back. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct ExportSettings { /// Bits per second, clamped to the same sane range the automatic value uses. /// `None` picks it from the picture size and frame rate. Video only. @@ -244,16 +244,22 @@ pub struct ExportSettings { /// it used to. Means nothing to WAV and FLAC, which code no rate, and /// nothing to a *copied* AAC track, which carries its source's. pub audio_kbps: Option, - /// Which of the project's subtitle tracks travels with the file: an index - /// into [`Project::subtitles`], which is the same list a front-end picks a - /// row of. `None` writes none -- what every caller wrote before there was a - /// choice, so an export of a timeline without subtitles is the file it - /// always was, byte for byte. + /// Which of the project's subtitle tracks travel with the file: indices into + /// [`Project::subtitles`], which is the same list a front-end picks rows of. + /// As many as the timeline holds, in the order given -- the file declares + /// them in that order and a player's subtitle menu lists them in it. Empty + /// writes none -- what every caller wrote before there was a choice, so an + /// export of a timeline without subtitles is the file it always was, byte + /// for byte. /// - /// Only a Matroska container carries it: an mp4's `tx3g` is a different - /// beast and nothing here writes one, so an mp4 export says so - /// ([`planned_subtitles`]) rather than dropping the track in silence. - pub subtitles: Option, + /// Every container that carries picture carries them: Matroska as + /// `S_TEXT/UTF8` blocks, an mp4 as a `tx3g` timed-text track + /// ([`crate::mux::Mp4Muxer::write_subtitles`]). A Matroska block names its + /// track in one byte, so a Matroska file carries at most + /// [`crate::mux::MAX_SUB_TRACKS`] of them and asking for more is refused by + /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has + /// no such ceiling. + pub subtitles: Vec, } struct Shared { @@ -317,7 +323,7 @@ pub fn start( out: &Path, settings: &ExportSettings, ) -> ExportHandle { - let settings = *settings; + let settings = settings.clone(); let shared = Arc::new(Shared { progress: AtomicU32::new(0), cancel: AtomicBool::new(false), @@ -559,30 +565,48 @@ pub fn audio_rate_refusal(project: &Project, format: Format) -> Option<&'static } } -/// The track a Matroska export carries, or `None`: no pick, a pick nothing -/// answers, a track that could not be read, one with no cue left on the -/// exported timeline -- and every mp4, whose refusal [`planned_subtitles`] says -/// out loud before the button is pressed. +/// The tracks an export carries, in the order they were picked, and empty where +/// it carries none: no pick, a pick nothing answers, a track that could not be +/// read, one with no cue left on the exported timeline -- and every format that +/// is the sound alone, which has nowhere to put them. Filtered *per track*, so +/// one unusable pick costs its own row and not the others. +/// +/// Both containers, since the mp4 muxer gained its `tx3g` track: what the two +/// do with the very same [`SubParams`] is theirs to say +/// ([`crate::mux::Mp4Muxer::write_subtitles`], [`MkvMuxer`]), and nothing here +/// asks which one is being written. fn export_subtitles( project: &Project, meta: &VideoMeta, settings: &ExportSettings, -) -> Option { - if !matches!(settings.format, Format::Av1 | Format::Hevc) { - return None; +) -> Vec { + if !settings.format.has_video() { + return Vec::new(); } - let track = project.subtitles().get(settings.subtitles?)?; - // A picture is not a line: the muxer writes an `S_TEXT/UTF8` track and a - // PGS cue has no words to put in one. `planned_subtitles` says so before - // the button is pressed rather than the file coming out short. - if track.refused.is_some() || track.is_bitmap() { - return None; - } - let cues = timeline_cues(project, track, meta.frame_rate); - (!cues.is_empty()).then(|| SubParams { - label: track.label.clone(), - cues, - }) + settings + .subtitles + .iter() + .filter_map(|&pick| { + let track = project.subtitles().get(pick)?; + // A picture is not a line: the muxer writes an `S_TEXT/UTF8` track + // and a PGS cue has no words to put in one. `planned_subtitles` says + // so before the button is pressed rather than the file coming out + // short. + if track.refused.is_some() || track.is_bitmap() { + return None; + } + let cues = timeline_cues(project, track, meta.frame_rate); + // The container's own two fields, carried as two + // ([`SubtitleTrack::language`]): a `TrackEntry` with no `Language` + // means `eng` by spec, so a French track that arrives here as one + // flattened string leaves as an English one. + (!cues.is_empty()).then(|| SubParams { + language: track.language.clone(), + name: track.name.clone(), + cues, + }) + }) + .collect() } /// 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< out } -/// What [`start`] would do about the subtitles, in the words a card shows. -/// Pure, like [`planned_audio`]: no file is opened, so it may be asked per -/// repaint. -pub fn planned_subtitles(project: &Project, format: Format, pick: Option) -> String { - let Some(track) = pick.and_then(|i| project.subtitles().get(i)) else { - return "none".into(); - }; - if let Some(why) = &track.refused { - return format!("{} — {why}", track.label); - } - // Drawn over the picture, written into no file: the exported track is text - // and these cues are bitmaps. Said whatever the format, because it is the - // track and not the container that cannot be carried. - if track.is_bitmap() { - return format!("{} — pictures; drawn, not written", track.label); +/// What [`start`] would do about the subtitles, in the words a card shows: what +/// travels, and the reason beside every pick that does not. Pure, like +/// [`planned_audio`]: no file is opened, so it may be asked per repaint. +/// +/// `picks` is any run of indices into [`Project::subtitles`] -- an +/// [`ExportSettings::subtitles`] list (`picks.iter().copied()`) as much as a +/// single `Some(row)`, which is what a front-end holding one row still hands it. +pub fn planned_subtitles( + project: &Project, + format: Format, + picks: impl IntoIterator, +) -> String { + let mut embedded: Vec<&str> = Vec::new(); + let mut dropped: Vec = Vec::new(); + let picks: Vec = picks.into_iter().collect(); + // One statement about the *file*, said before any about a track: a format + // that is the sound alone has nowhere to put a single one of them, and the + // reason a pick would not have travelled anyway (a picture track, no cues) + // is not the reason it does not travel here. Nothing picked is "none" -- + // there is nothing to say a container cannot carry. + if !picks.is_empty() && !format.has_video() { + return "none — this format is the sound alone".into(); + } + for pick in picks { + // A pick the project has no row for: a caller holding an index the list + // no longer has (a removed row shifts every later one down). Every other + // reason a pick does not travel is named on this card, so this one is + // too -- a bug that says nothing is a bug found in the finished file. + let Some(track) = project.subtitles().get(pick) else { + dropped.push(format!("#{pick} — no such track")); + continue; + }; + if let Some(why) = &track.refused { + dropped.push(format!("{} — {why}", track.label)); + } else if track.is_bitmap() { + // Drawn over the picture, written into no file: the exported track + // is text and these cues are bitmaps. Said whatever the format, + // because it is the track and not the container that cannot be + // carried. + dropped.push(format!("{} — pictures; drawn, not written", track.label)); + } else if track.cues.is_empty() { + dropped.push(format!("{} — no cues", track.label)); + } else { + // Whichever container: a Matroska carries the track as + // `S_TEXT/UTF8` blocks and an mp4 as a `tx3g` timed-text track, and + // a pick travels either way. There is no container refusal left on + // this card -- the sound-alone one above is about the *file* and the + // ones beside it about the *track*. + embedded.push(&track.label); + } } - match format { - _ if track.cues.is_empty() => "none".into(), - Format::Av1 | Format::Hevc => format!("{} → embedded", track.label), - // Said before the export rather than after it: an mp4 carries text in - // `tx3g` and nothing here writes one, so the honest answer is the - // container that does. - format if format.has_video() => "mkv only — an mp4 carries none".into(), - _ => "none — this format is the sound alone".into(), + let mut parts = match embedded.len() { + 0 => Vec::new(), + 1 => vec![format!("{} → embedded", embedded[0])], + n => vec![format!("{n} tracks → embedded ({})", embedded.join(", "))], + }; + parts.extend(dropped); + match parts.is_empty() { + true => "none".into(), + false => parts.join("; "), } } @@ -1191,16 +1251,19 @@ fn run( let Some(muxer) = muxer else { return Err("export produced no coded pictures".into()); }; - // The mp4's audio track after its picture -- the Matroska one interleaved - // its own as it went and left `packets` empty behind it. - let muxer = match (muxer, packets) { - (Muxer::Mp4(mut mp4), Some(packets)) => { - for packet in packets { + // The mp4's audio and subtitle tracks after its picture -- the Matroska one + // interleaved its own as it went and left `packets` and `subs` empty behind + // it. The text last, so its samples are written knowing how long the picture + // turned out to be. + let muxer = match muxer { + Muxer::Mp4(mut mp4) => { + for packet in packets.into_iter().flatten() { mp4.write_audio_packet(&packet.bytes)?; } + mp4.write_subtitles(&subs)?; Muxer::Mp4(mp4) } - (muxer, _) => muxer, + muxer => muxer, }; cancelled(shared)?; muxer.finish()?; @@ -1674,7 +1737,7 @@ fn write_video( settings: &ExportSettings, audio: Option<&AudioParams>, packets: &mut Option>, - subs: &mut Option, + subs: &mut Vec, au: &[u8], key: bool, ) -> crate::Result<()> { @@ -1702,7 +1765,7 @@ fn write_video( hvcc: &hvcc, }, sound, - subs.take(), + std::mem::take(subs), )?)) else { unreachable!("just inserted a Matroska muxer") }; @@ -1759,7 +1822,7 @@ fn write_video( out, ¶ms(meta, au)?, sound, - subs.take(), + std::mem::take(subs), )?)) else { unreachable!("just inserted a Matroska muxer") }; @@ -2517,6 +2580,8 @@ mod tests { SubtitleTrack { path: path.into(), track, + language: "eng".into(), + name: String::new(), label: "eng".into(), bitmap: false, cues: vec![ diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 38afa24..6f493b7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,7 +29,7 @@ pub use audio::{ }; pub use clock::PlaybackClock; pub use decode::{DecodeSession, Frame, image_size}; -pub use demux::{Codec, VideoMeta}; +pub use demux::{Codec, MediaBitrate, VideoMeta, probe_bitrate}; pub use export::ExportHandle; pub use mux::{AudioParams, Mp4Muxer, VideoParams}; pub use playback::PlaybackSession; diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 9becbb0..6d74083 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -11,7 +11,9 @@ //! `avc1` entry and this patches that entry into the `av01` + `av1C` pair the //! spec asks for, which is the only box in a whole mp4 the crate cannot spell. //! Both containers carry the timeline's AAC, so no format here writes a picture -//! whose sound was silently left behind. +//! whose sound was silently left behind -- and both carry its subtitles, an mp4 +//! as the `tx3g` timed text `mp4 0.14` *can* spell ([`Mp4Muxer::write_subtitles`]) +//! and Matroska as `S_TEXT/UTF8` blocks, so neither is a file whose words were. use std::fs::{File, OpenOptions}; use std::io::{BufWriter, Read, Seek, SeekFrom, Write}; @@ -19,7 +21,7 @@ use std::path::{Path, PathBuf}; use mp4::{ AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config, - Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType, + Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType, TtxtConfig, }; use crate::colorspace::ColorDescription; @@ -35,6 +37,10 @@ const NTSC_TICKS: u32 = 1001; /// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the /// per-packet duration is this constant. const AAC_PACKET_SAMPLES: u32 = 1024; +/// The clock a `tx3g` track counts in: one millisecond, the very tick a Matroska +/// block's timestamp is written at ([`TIMESTAMP_SCALE_NS`]), so a cue lands on +/// the same instant whichever of the two containers carries it. +const SUB_TIMESCALE: u32 = 1_000; const NAL_IDR: u8 = 5; const NAL_SEI: u8 = 6; @@ -81,6 +87,17 @@ pub struct Mp4Muxer { /// Where the file is, for that patch: the writer owns the handle it wrote /// through and the patch reopens the finished file. path: PathBuf, + /// The video track's clock and how many pictures have been written on it -- + /// which is where the file *ends*, and a timed-text track is written out to + /// that instant ([`write_subtitles`](Mp4Muxer::write_subtitles)). + timescale: u32, + frames: u64, + /// What the subtitle tracks are *called*, in the order they were written: + /// an mp4 states a track's title in a `trak/udta/name` box, which `mp4 0.14` + /// has no field for, so it is patched in at [`finish`](Mp4Muxer::finish) + /// beside the sample entry. Empty where no track carries a title, which is + /// every file that has no subtitles at all. + sub_names: Vec, } /// A `ColourInformationBox` payload, ISO/IEC 14496-12 §12.1.5: the `nclx` tag @@ -270,6 +287,9 @@ impl Mp4Muxer { entry, colr: colr_nclx(ColorDescription::output(video.height)), path: path.to_path_buf(), + timescale, + frames: 0, + sub_names: Vec::new(), }) } @@ -287,6 +307,7 @@ impl Mp4Muxer { bytes: Bytes::from(bytes), }, )?; + self.frames += 1; Ok(()) } @@ -310,6 +331,7 @@ impl Mp4Muxer { bytes: Bytes::copy_from_slice(obus), }, )?; + self.frames += 1; Ok(()) } @@ -335,6 +357,80 @@ impl Mp4Muxer { Ok(()) } + /// The soft subtitle tracks this file carries, written after the picture and + /// the sound exactly as [`MkvMuxer`] writes its own into the clusters -- one + /// `tx3g` timed-text track per [`SubParams`], which is the text an mp4 says + /// a cue with and the one `ffmpeg` calls `mov_text`. Called once, before + /// [`finish`](Mp4Muxer::finish); an empty list writes nothing at all, which + /// is why an export with no pick is the file it always was, byte for byte. + /// + /// The samples are *continuous*: a timed-text track states one sample per + /// instant of the film and nothing between them, so the stretches with + /// nothing to say are empty samples (a 16-bit zero length and no text) and + /// not holes -- a hole is where a player keeps the last line on screen until + /// the next one arrives. The run is built out of the cue *boundaries*, so + /// cues that overlap are one sample of both their lines rather than one of + /// them dropped: a `tx3g` track shows one sample at a time where a Matroska + /// one may show two blocks at once, and joining them is what keeps the words + /// a viewer saw over the picture. + /// + /// ponytail: the `tx3g` sample entry is the one `mp4 0.14` writes and there + /// is no field to reach into it -- `MediaConfig::TtxtConfig` carries nothing + /// -- so its `data_reference_index` is the crate's 0 where §8.5.2 says an + /// index into `dref` counts from 1, and it holds no `ftab` font table. + /// ffmpeg and mpv both read the track (measured, 2026-08-12); a reader that + /// checks the index would not. The upgrade path is the trick the `av01` + /// entry already takes: rewrite the 46 fixed bytes of that entry in + /// [`patch_entry`] the way the video one is rewritten. + pub fn write_subtitles(&mut self, subs: &[SubParams]) -> crate::Result<()> { + if subs.is_empty() { + return Ok(()); + } + // Where the picture ends, in the text track's own tick: the last sample + // runs out to it, so the track covers the film rather than stopping at + // the last thing anybody says. + let end = (self.frames * u64::from(self.frame_duration) * u64::from(SUB_TIMESCALE) + / u64::from(self.timescale)) as i64; + // The picture is track 1 and the sound, where there is any, track 2: + // `mp4 0.14` numbers a track by the order it was added in, so the text + // starts after them and each further track is the next number up. + for (track_id, subs) in (2 + u32::from(self.has_audio)..).zip(subs) { + self.writer.add_track(&TrackConfig { + track_type: TrackType::Subtitle, + timescale: SUB_TIMESCALE, + // `und` and not an empty string where the source states no + // language: an mp4 packs the three letters into a 16-bit field + // and has no way to leave it out, and `und` is the code that + // says *undetermined* -- while three zero bits would spell a + // language nobody speaks. + language: match subs.language.is_empty() { + true => "und".to_string(), + false => subs.language.clone(), + }, + media_conf: MediaConfig::TtxtConfig(TtxtConfig {}), + })?; + for (bytes, duration) in timed_text(&subs.cues, end)? { + self.writer.write_sample( + track_id, + &Mp4Sample { + start_time: 0, // ignored by the writer, as everywhere here + duration, + rendering_offset: 0, + // Every text sample is one a player may start at, and + // saying so per-sample would emit an `stss` listing all + // of them where no `stss` means the same thing -- the + // audio track's reason, and what ffmpeg's own `tx3g` + // track does. + is_sync: false, + bytes: Bytes::from(bytes), + }, + )?; + } + } + self.sub_names = subs.iter().map(|subs| subs.name.clone()).collect(); + Ok(()) + } + pub fn finish(mut self) -> crate::Result<()> { self.writer.write_end()?; let Self { @@ -342,14 +438,83 @@ impl Mp4Muxer { entry, colr, path, + sub_names, .. } = self; // Not a `drop`: the buffered tail of `moov` has to be on disk before the // patch below reads it back, and a `BufWriter` swallows the error of // flushing it on drop. writer.into_writer().flush()?; - patch_entry(&path, entry.as_ref(), &colr) + patch_entry(&path, entry.as_ref(), &colr, &sub_names) + } +} + +/// The cues of one subtitle track as the run of `tx3g` samples an mp4 carries +/// them in -- `(payload, duration in milliseconds)`, from instant 0 to `end`, +/// with no instant left out. +/// +/// A sample's payload is the ISO/IEC 14496-17 one: the text's length in 16 bits +/// and then the UTF-8 itself, which is two zero bytes where there is nothing on +/// screen. The run is walked over the cue *boundaries* rather than over the cues, +/// which is what makes a gap an empty sample and an overlap one sample carrying +/// both lines -- the two things a track of samples has to say that a list of +/// cues does not. +/// +/// ponytail: the active set is looked for from the front of the list at every +/// boundary, so this is quadratic in the cues of one track (a 5 000-cue film +/// costs ~25 M compares once, at the end of an export that took minutes). The +/// upgrade path is a sweep holding the open cues in a heap keyed on their end. +fn timed_text(cues: &[crate::subtitle::Cue], end: i64) -> crate::Result, u32)>> { + // Milliseconds, the tick this track is written in -- and a cue that rounds + // onto its own start stays up for one of them rather than vanishing, which + // is what the Matroska writer's `BlockDuration` does with it. + let ms = |us: i64| (us + 500) / 1_000; + let spans: Vec<(i64, i64)> = cues + .iter() + .map(|cue| { + let start = ms(cue.start_us); + (start, ms(cue.end_us).max(start + 1)) + }) + .collect(); + let mut times: Vec = vec![0, end.max(0)]; + for &(start, stop) in &spans { + times.push(start); + times.push(stop); + } + times.sort_unstable(); + times.dedup(); + let mut out = Vec::with_capacity(times.len()); + for pair in times.windows(2) { + let (from, to) = (pair[0], pair[1]); + let mut text = String::new(); + for (span, cue) in spans.iter().zip(cues) { + // The cues arrive in start order (`export::timeline_cues` sorts + // them), so nothing past this one has opened yet. + if span.0 > from { + break; + } + if span.1 > from { + if !text.is_empty() { + text.push('\n'); + } + text.push_str(&cue.text); + } + } + let len = u16::try_from(text.len()).map_err(|_| { + format!( + "a subtitle cue of {} bytes: a tx3g sample states its text length in 16 bits, so \ + one cue carries at most {} -- export a Matroska, whose blocks state no length at \ + all", + text.len(), + u16::MAX + ) + })?; + let mut bytes = Vec::with_capacity(text.len() + 2); + bytes.extend_from_slice(&len.to_be_bytes()); + bytes.extend_from_slice(text.as_bytes()); + out.push((bytes, u32::try_from(to - from)?)); } + Ok(out) } /// Rewrites the finished file's one video sample entry: `colr` appended to it @@ -365,11 +530,13 @@ fn patch_entry( path: &Path, entry: Option<&([u8; 4], [u8; 4], Vec)>, colr: &[u8], + sub_names: &[String], ) -> crate::Result<()> { let mut file = OpenOptions::new().read(true).write(true).open(path)?; let end = file.metadata()?.len(); let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?; let patched = swap_entry(&payload, 0, entry, colr).ok_or("no avc1 sample entry to rewrite")?; + let patched = name_subtitles(patched, sub_names); let mut out = Vec::with_capacity(patched.len() + 8); push_box(&mut out, b"moov", &patched); file.seek(SeekFrom::Start(at))?; @@ -465,6 +632,54 @@ fn swap_entry( done.then_some(out) } +/// The title of each subtitle track into the `trak` that carries it, in the +/// order they were written: a `udta` holding a `name` box, which is where an mp4 +/// says what a track is *called* (`Signs`) beside the `mdhd` language it is in +/// -- the pair Matroska spells as `Name` and `Language`, and the very boxes +/// ffmpeg writes a `-metadata:s:s:0 title=` into and reads back out. +/// `mp4 0.14`'s `TrakBox` has no `udta` field at all, so it is appended here +/// beside the sample entry rewrite, on the same rebuilt `moov`. +/// +/// Untouched where no track has a title -- and returned as it came for a file +/// with no subtitles at all, which is every export that picked none. +fn name_subtitles(moov: Vec, names: &[String]) -> Vec { + if names.iter().all(|name| name.is_empty()) { + return moov; + } + let mut names = names.iter(); + let mut out = Vec::with_capacity(moov.len() + 32 * names.len()); + for (kind, child) in crate::demux::boxes(&moov) { + // A subtitle `trak` is the one whose media handler says `sbtl`, which is + // what `TrackType::Subtitle` wrote -- asked of the file rather than + // counted, so the picture's and the sound's `trak`s cannot be miscounted + // into. + let name = match kind == b"trak" && is_subtitle_trak(child) { + true => names.next().filter(|name| !name.is_empty()), + false => None, + }; + let Some(name) = name else { + push_box(&mut out, kind, child); + continue; + }; + let mut trak = child.to_vec(); + let mut udta = Vec::new(); + push_box(&mut udta, b"name", name.as_bytes()); + push_box(&mut trak, b"udta", &udta); + push_box(&mut out, kind, &trak); + } + out +} + +/// Whether a `trak` is a subtitle one: its `mdia`'s `hdlr` names the `sbtl` +/// handler, which sits after the box's version, flags and the four `pre_defined` +/// bytes. +fn is_subtitle_trak(trak: &[u8]) -> bool { + crate::demux::boxes(trak) + .filter(|(kind, _)| *kind == b"mdia") + .flat_map(|(_, mdia)| crate::demux::boxes(mdia)) + .any(|(kind, hdlr)| kind == b"hdlr" && hdlr.get(8..12) == Some(&b"sbtl"[..])) +} + /// One mp4 box: 32-bit size, four-character type, payload. Every box inside a /// `moov` fits that form -- the 64-bit one exists for `mdat`, which this never /// rewrites. @@ -572,32 +787,41 @@ pub struct HevcParams<'a> { pub hvcc: &'a [u8], } -/// The soft subtitle track a Matroska file carries beside the picture: text, -/// timed, still text in the file -- a player draws it and a user can turn it -/// off, which is what "soft" means and what burning it into the pixels is not. +/// The soft subtitle track a file carries beside the picture: text, timed, still +/// text in the file -- a player draws it and a user can turn it off, which is +/// what "soft" means and what burning it into the pixels is not. +/// +/// Both containers carry one: Matroska as an `S_TEXT/UTF8` track whose blocks +/// are the cues themselves ([`MkvMuxer`]), an mp4 as a `tx3g` timed-text track +/// whose samples run end to end over the film +/// ([`Mp4Muxer::write_subtitles`]). /// /// The cues are the *exported timeline's* (`export::timeline_cues` puts them /// there), because the file's clock is the timeline's; nothing here shifts /// anything. pub struct SubParams { - /// What the track is called in the file. A three-letter code goes in as - /// `Language`, which is what a player's subtitle menu reads; anything else - /// is a `Name`, which is what it shows when there is no language to show. - /// - /// ponytail: one string for both because a [`crate::subtitle::SubtitleTrack`] - /// carries one label and not a (language, name) pair. The upgrade path is to - /// keep the two apart from the demuxer down -- `MkvSubtitle` already has - /// them -- and it belongs to whoever needs a per-language export list. - pub label: String, + /// What language the track is in, as the three-letter code Matroska says it + /// with (`fra`, `tur`): the field a player's subtitle menu reads. Empty + /// where the source states none -- and *only* then, because a `TrackEntry` + /// without a `Language` means `eng` by spec, so a French track that leaves + /// this empty leaves as an English one. + pub language: String, + /// What the track is *called*, where it has a title of its own beside its + /// language (`Signs`, `Forced`). Empty where it has none. + pub name: String, /// In start order, which is the order they are written in. pub cues: Vec, } -/// The cues waiting to be interleaved into the clusters, [`MkvAudio`]'s twin. +/// The cues of one subtitle track waiting to be interleaved into the clusters, +/// [`MkvAudio`]'s twin. One of these per track the file carries. struct MkvSubs { cues: Vec, /// Cues already written. next: usize, + /// Which track its blocks name -- 3 for the first, one more for each after + /// it ([`SUB_TRACK_FIRST`]). + track_no: u8, } /// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC @@ -630,9 +854,9 @@ pub struct MkvMuxer { /// The AAC track, if the timeline has sound, and how far it has been /// written. audio: Option, - /// The subtitle track, if one travels with the file, and how far it has - /// been written. - subs: Option, + /// The subtitle tracks travelling with the file, in the order they were + /// declared, and how far each has been written. Empty where none does. + subs: Vec, } /// The sound waiting to be interleaved into the clusters. @@ -659,7 +883,7 @@ impl MkvMuxer { path: &Path, video: &Av1Params, audio: Option<(&AudioParams, Vec)>, - subs: Option, + subs: Vec, ) -> crate::Result { if video.config.is_empty() { return Err("no AV1 sequence header for the track's CodecPrivate".into()); @@ -689,7 +913,7 @@ impl MkvMuxer { path: &Path, video: &HevcParams, audio: Option<(&AudioParams, Vec)>, - subs: Option, + subs: Vec, ) -> crate::Result { if video.hvcc.is_empty() { return Err("no hvcC record for the track's CodecPrivate".into()); @@ -715,11 +939,22 @@ impl MkvMuxer { codec_id: &[u8], codec_private: &[u8], audio: Option<(&AudioParams, Vec)>, - subs: Option, + subs: Vec, ) -> crate::Result { if !frame_rate.is_finite() || frame_rate <= 0.0 { return Err(format!("bad frame rate {frame_rate}").into()); } + // Said before a byte is written, and by name: past this the block header + // could not hold the track number ([`MAX_SUB_TRACKS`]) and the file would + // be quietly wrong rather than absent. + if subs.len() > MAX_SUB_TRACKS { + return Err(format!( + "{} subtitle tracks: a Matroska block writes its track number in \ + one byte, so one file carries at most {MAX_SUB_TRACKS}", + subs.len() + ) + .into()); + } if width == 0 || height == 0 { return Err(format!("bad dimensions {width}x{height}").into()); } @@ -788,11 +1023,17 @@ impl MkvMuxer { if let Some((audio, _)) = &audio { elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?); } - // Declared even where the audio track is not: the numbers are fixed - // (1 picture, 2 sound, 3 text) rather than counted, so a file with - // subtitles and no sound still says track 3 in its blocks. - if let Some(subs) = &subs { - elem(&mut tracks, TRACK_ENTRY, &subtitle_track_entry(&subs.label)); + // Declared even where the audio track is not: the picture is always 1 + // and the sound always 2, so the text starts at 3 whether or not there + // is any sound -- and each further track is the next number up, which is + // the only counting in the file. + for (i, subs) in subs.iter().enumerate() { + let track_no = SUB_TRACK_FIRST + i as u8; + elem( + &mut tracks, + TRACK_ENTRY, + &subtitle_track_entry(&subs.language, &subs.name, track_no), + ); } elem(&mut head, TRACKS, &tracks); @@ -812,10 +1053,15 @@ impl MkvMuxer { samples: 0, sample_rate: params.sample_rate.max(1), }), - subs: subs.map(|subs| MkvSubs { - cues: subs.cues, - next: 0, - }), + subs: subs + .into_iter() + .enumerate() + .map(|(i, subs)| MkvSubs { + cues: subs.cues, + next: 0, + track_no: SUB_TRACK_FIRST + i as u8, + }) + .collect(), }) } @@ -891,35 +1137,38 @@ impl MkvMuxer { /// [`drain_audio`](MkvMuxer::drain_audio)'s twin, and `i64::MAX` at /// [`finish`](MkvMuxer::finish) writes what is left: a cue may still be on /// screen over the last picture, and one written nowhere is one a player - /// never shows. + /// never shows. Every track in turn, in the order they were declared. fn drain_subs(&mut self, until: i64) -> crate::Result<()> { - loop { - let Some(subs) = &mut self.subs else { - return Ok(()); - }; - let Some(cue) = subs.cues.get_mut(subs.next) else { - return Ok(()); - }; - // Milliseconds, the tick this file is written in: a cue is read for - // a second or more and no eye finds the half a tick it rounds by. - let ts = (cue.start_us + 500) / 1_000; - if ts > until { - return Ok(()); - } - // A cue that says it ends before it starts stays up for one tick - // rather than for a duration a reader would take as unsigned. - let ms = ((cue.end_us - cue.start_us + 500) / 1_000).max(1) as u64; - let text = std::mem::take(&mut cue.text); - subs.next += 1; - // A cluster of its own where the text has run past what a 16-bit - // relative timestamp reaches, exactly as the sound's drain does. - if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS { - self.flush()?; - self.cluster_ts = ts; - uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); + for track in 0..self.subs.len() { + loop { + let subs = &mut self.subs[track]; + let Some(cue) = subs.cues.get_mut(subs.next) else { + break; + }; + // Milliseconds, the tick this file is written in: a cue is read + // for a second or more and no eye finds the half a tick it + // rounds by. + let ts = (cue.start_us + 500) / 1_000; + if ts > until { + break; + } + // A cue that says it ends before it starts stays up for one tick + // rather than for a duration a reader would take as unsigned. + let ms = ((cue.end_us - cue.start_us + 500) / 1_000).max(1) as u64; + let text = std::mem::take(&mut cue.text); + subs.next += 1; + let track_no = subs.track_no; + // A cluster of its own where the text has run past what a 16-bit + // relative timestamp reaches, exactly as the sound's drain does. + if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS { + self.flush()?; + self.cluster_ts = ts; + uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); + } + self.block_group(track_no, ts, ms, text.as_bytes()); } - self.block_group(SUB_TRACK, ts, ms, text.as_bytes()); } + Ok(()) } /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC @@ -1035,32 +1284,49 @@ fn aac_track_entry(audio: &AudioParams) -> crate::Result> { Ok(entry) } -/// Which track a subtitle block names. Fixed, like the picture's 1 and the -/// sound's 2: a file with no audio track still writes its text on 3, so nothing -/// has to count tracks to read a block. -const SUB_TRACK: u8 = 3; +/// Which track the *first* subtitle block names, the picture's 1 and the sound's +/// 2 being fixed: a file with no audio track still writes its first text track +/// on 3, so nothing has to count the tracks before it to read a block. Each +/// further subtitle track is the next number up. +const SUB_TRACK_FIRST: u8 = 3; + +/// How many subtitle tracks one file may carry. A block writes its track number +/// as a one-byte EBML integer (`0x80 | track`, [`MkvMuxer::block`]), and 127 is +/// one number too far: its byte is `0xFF`, the all-ones variable-length integer +/// EBML spells *unknown* with, which this project's own reader hands back as +/// `u64::MAX` (`demux`'s `vint`) -- so track 127's blocks would match no track, +/// its cues would vanish on the way back in, and the file would be one edith +/// wrote and cannot read. The numbers therefore run `3..=126` and the count is +/// what is left of them -- derived from the encoding, so it cannot drift from +/// it. A file asking for more is refused by name in [`MkvMuxer::open`] rather +/// than written with a byte that means another track, or none. +pub const MAX_SUB_TRACKS: usize = 0x7F - SUB_TRACK_FIRST as usize; /// The `TrackEntry` of the subtitle track: type 0x11 (subtitles) and /// `S_TEXT/UTF8`, whose blocks are the cue's own UTF-8 text and whose timing is /// the block's -- the codec every player draws and the one this project's own /// reader parses back (`subtitle::cues_of`). /// -/// The label is a `Language` where it is one (`eng`, `tur`: three letters is -/// what ISO-639-2 is) and a `Name` otherwise, which is exactly what -/// [`crate::subtitle::of_matroska`] reads back out, so a track exported and -/// re-imported keeps the name it had. -fn subtitle_track_entry(label: &str) -> Vec { +/// The two names a track has are written as the two fields Matroska has for +/// them: `Language` is what a player's subtitle menu offers and what a "play +/// French" setting matches on, `Name` is the title beside it (`Signs`). Both +/// where the source has both -- a track carrying only a name is an *English* +/// track to every reader, that being the spec's default, which is how a +/// multi-language film used to export as several English ones. Either is left +/// out where it is empty, and [`crate::subtitle::of_matroska`] reads exactly +/// this back, so a track exported and re-imported keeps what it had. +fn subtitle_track_entry(language: &str, name: &str, track_no: u8) -> Vec { let mut entry = Vec::new(); - uint(&mut entry, TRACK_NUMBER, u64::from(SUB_TRACK)); - uint(&mut entry, TRACK_UID, u64::from(SUB_TRACK)); + uint(&mut entry, TRACK_NUMBER, u64::from(track_no)); + uint(&mut entry, TRACK_UID, u64::from(track_no)); uint(&mut entry, TRACK_TYPE, 0x11); uint(&mut entry, FLAG_LACING, 0); elem(&mut entry, CODEC_ID, b"S_TEXT/UTF8"); - let code = label.len() == 3 && label.bytes().all(|b| b.is_ascii_lowercase()); - match (code, label.is_empty()) { - (true, _) => elem(&mut entry, TRACK_LANGUAGE, label.as_bytes()), - (false, false) => elem(&mut entry, TRACK_NAME, label.as_bytes()), - (false, true) => {} + if !language.is_empty() { + elem(&mut entry, TRACK_LANGUAGE, language.as_bytes()); + } + if !name.is_empty() { + elem(&mut entry, TRACK_NAME, name.as_bytes()); } entry } @@ -1348,6 +1614,58 @@ mod tests { v } + fn cue(start_ms: i64, end_ms: i64, text: &str) -> crate::subtitle::Cue { + crate::subtitle::Cue { + start_us: start_ms * 1_000, + end_us: end_ms * 1_000, + text: text.into(), + image: None, + } + } + + /// What a `tx3g` track is made of: one sample per instant of the film and no + /// hole anywhere. The gaps -- before the first cue, between two, after the + /// last -- are empty samples (a 16-bit zero and nothing else), and the whole + /// run adds up to the length it was asked for, which is what stops a player + /// leaving the last line on screen over the rest of the film. + #[test] + fn a_timed_text_track_covers_every_instant() { + let cues = [cue(500, 1_500, "first"), cue(4_000, 4_750, "third")]; + let samples = timed_text(&cues, 5_000).unwrap(); + let times: Vec = samples.iter().map(|(_, ms)| *ms).collect(); + assert_eq!(times, [500, 1_000, 2_500, 750, 250], "{samples:?}"); + assert_eq!(times.iter().sum::(), 5_000, "the film, end to end"); + let texts: Vec<&[u8]> = samples.iter().map(|(bytes, _)| &bytes[..]).collect(); + assert_eq!(texts[0], b"\0\0", "nothing is said until 0.5 s"); + assert_eq!(texts[1], b"\0\x05first"); + assert_eq!(texts[2], b"\0\0", "...nor between the two cues"); + assert_eq!(texts[3], b"\0\x05third"); + assert_eq!(texts[4], b"\0\0", "...nor after the last one"); + } + + /// Two cues over one another: a Matroska file shows both blocks at once and + /// a `tx3g` track has one sample per instant, so the overlap is *one* sample + /// carrying both lines rather than one of them dropped -- the words a viewer + /// saw over the picture, which is what this file is a copy of. + #[test] + fn overlapping_cues_are_one_sample_of_both_lines() { + let cues = [cue(0, 2_000, "sign"), cue(1_000, 3_000, "dialogue")]; + let samples = timed_text(&cues, 3_000).unwrap(); + let got: Vec<(String, u32)> = samples + .iter() + .map(|(bytes, ms)| (String::from_utf8_lossy(&bytes[2..]).into_owned(), *ms)) + .collect(); + assert_eq!( + got, + [ + ("sign".into(), 1_000), + ("sign\ndialogue".into(), 1_000), + ("dialogue".into(), 1_000), + ], + "{samples:?}" + ); + } + #[test] fn splits_both_start_code_lengths() { let src = [ @@ -1633,7 +1951,7 @@ mod tests { }, packets, )), - None, + Vec::new(), ) .unwrap(); // Half a second of picture under a second of sound: the tail of the @@ -1761,7 +2079,7 @@ mod tests { config, }, None, - None, + Vec::new(), ) .unwrap(); muxer.write_frame(&key, true).unwrap(); @@ -1805,7 +2123,7 @@ mod tests { config: &[], }, None, - None, + Vec::new(), ) .is_err() ); diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 0e2c246..ec53d97 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -892,12 +892,19 @@ impl PlaybackSession { crate::export::planned_audio(&self.project, format) } - /// What an export would do about the subtitle track at `pick` -- + /// What an export would do about the tracks at `picks` -- /// [`crate::export::planned_subtitles`], asked of the project a front-end is - /// holding, and pure for the same reason. `pick` is a row of - /// [`subtitles`](Self::subtitles). - pub fn planned_subtitles(&self, format: crate::export::Format, pick: Option) -> String { - crate::export::planned_subtitles(&self.project, format, pick) + /// holding, and pure for the same reason. `picks` is any run of rows of + /// [`subtitles`](Self::subtitles): the whole + /// [`ExportSettings::subtitles`](crate::export::ExportSettings::subtitles) + /// list a card is about to send (`picks.iter().copied()`) as much as a + /// single `Some(row)`. + pub fn planned_subtitles( + &self, + format: crate::export::Format, + picks: impl IntoIterator, + ) -> String { + crate::export::planned_subtitles(&self.project, format, picks) } /// Where the cues of the track at `pick` land on *this* timeline -- @@ -959,11 +966,33 @@ impl PlaybackSession { /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves: /// subtitles are not clips and land on no lane. pub fn import_subtitles(&mut self, path: &Path) -> crate::Result { - let tracks = match path.extension().is_some_and(|e| { - let e = e.to_string_lossy().to_ascii_lowercase(); - e == "mkv" || e == "webm" - }) { - true => crate::subtitle::of_matroska(path)?, + Ok(self.add_subtitle_tracks(Self::parse_subtitles(path)?)) + } + + /// The reading half of [`import_subtitles`](Self::import_subtitles), with no + /// session in it: every subtitle track of a Matroska file, or the one track + /// a standalone `.srt`/`.vtt`/`.ass` is, cues and all. Same refusal rule. + /// + /// This is the half that costs -- a walk of the whole container, measured at + /// 210 ms on a 25 GB 35-track file and 1.3 s on a 3 GB one whose pages were + /// cold -- so a front-end runs *this* on its background executor and hands + /// what comes back to [`add_subtitle_tracks`](Self::add_subtitle_tracks), + /// which costs a push. Both doors are this one function, so the import + /// button and the background one cannot drift apart. + pub fn parse_subtitles(path: &Path) -> crate::Result> { + // The containers that carry subtitle tracks *inside* them: every + // Matroska one ([`crate::demux::is_matroska`], which is where `.mks` -- + // the subtitles alone -- comes in) and the mp4 family, whose `tx3g` + // timed text is what an mp4 export of this project's own writes, so a + // file edith wrote is a file edith imports back. + let tracks = match crate::demux::is_matroska(path) + || path.extension().is_some_and(|e| { + matches!( + e.to_string_lossy().to_ascii_lowercase().as_str(), + "mp4" | "m4v" | "mov" + ) + }) { + true => crate::subtitle::of_media(path)?, false => vec![crate::subtitle::open(path, None)], }; // A standalone file that could not be parsed is a refusal here rather @@ -975,10 +1004,40 @@ impl PlaybackSession { { return Err(why.clone().into()); } - Ok(tracks + Ok(tracks) + } + + /// Puts tracks already read by [`parse_subtitles`](Self::parse_subtitles) + /// on this timeline, in the order given. Hands back how many actually went + /// on: [`Project::add_subtitles`] drops the ones already here -- same file, + /// same track number -- so 0 is "this file's subtitles are on the timeline + /// already", which is the sentence a front-end says. + /// + /// The whole of what an import costs the thread that calls it, which is why + /// the parse is a separate door: nothing here opens, seeks or decodes. + /// Subtitles are not clips and land on no lane, so nothing playable changes + /// and no undo step is pushed ([`Project::remove_subtitles`] says why). + pub fn add_subtitle_tracks(&mut self, tracks: Vec) -> usize { + tracks .into_iter() .filter(|t| self.project.add_subtitles(t)) - .count()) + .count() + } + + /// Takes the track at `idx` off this timeline -- the door a subtitle row's + /// own remove goes through, the way [`import_subtitles`]( + /// Self::import_subtitles) is the door that puts one on. Refused in + /// [`Project::remove_subtitles`]'s words for a row this timeline does not + /// have. + /// + /// Nothing playable changes and no worker was opened against a cue, so + /// unlike [`remove_source`](Self::remove_source) this does not reseek. Rows + /// past `idx` move down by one: a caller holding a picked row (the export's + /// subtitle pick) has to fix it up or drop it. Not an undo step, for the + /// reason [`Project::remove_subtitles`] gives -- the inverse is a + /// re-import. + pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> { + self.project.remove_subtitles(idx) } /// Writes the timeline to `path` as a `.edith`, atomically (see diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index d2e1295..e1cab53 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -1226,6 +1226,30 @@ impl Project { true } + /// Takes the track at `idx` off the list -- what a row's own remove goes + /// through, so whatever an import added can be taken back out. Refused by + /// name for a row this project does not have, rather than a silent no-op: + /// a front-end holding a stale index has picked the wrong row and needs to + /// hear it. + /// + /// Every index past `idx` moves down by one, as [`remove_source`]( + /// Project::remove_source)'s do: a caller holding a picked row (an export's + /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop + /// it, or it names a different track afterwards. + /// + /// ponytail: not an undo step, for the reason the limiter is not -- the + /// history snapshots hold the lane list and subtitles are not on it + /// ([`Project::subtitles`]). The inverse is a re-import, not a ctrl+z, and + /// the upgrade path is the same one: a history entry holding the project's + /// own settings beside the lanes. + pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> { + if idx >= self.subtitles.len() { + return Err(format!("there is no subtitle track {idx} to remove").into()); + } + self.subtitles.remove(idx); + Ok(()) + } + /// What each of [`audio_segments_from`](Project::audio_segments_from)'s /// lanes is multiplied by on its way into the mix: the same lanes in the /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0` diff --git a/crates/engine/src/subtitle.rs b/crates/engine/src/subtitle.rs index d5fedce..e75c1b2 100644 --- a/crates/engine/src/subtitle.rs +++ b/crates/engine/src/subtitle.rs @@ -148,8 +148,23 @@ pub struct SubtitleTrack { /// Which track of `path`, for one embedded in a Matroska file. `None` when /// `path` *is* the subtitle file. pub track: Option, - /// What a list shows: a language, a muxer's name for the track, or the - /// file's own name for a standalone one. + /// What language the track is in, as the container states it (`eng`, `fra`, + /// `und` for a file that says nothing -- which is what both demuxers hand + /// over rather than an empty string). Empty only for a standalone file, + /// which states no language at all. + /// + /// Kept apart from [`name`](Self::name) because a container keeps them + /// apart: an export writes `TRACK_LANGUAGE` and `TRACK_NAME` as two fields + /// ([`crate::mux::SubParams`]), and a French track whose language is folded + /// into its title leaves as an English one. + pub language: String, + /// What the track is *called* beside its language (`Signs`, `Forced`), or + /// the file's own name for a standalone one. Empty where it has none. + pub name: String, + /// What a list shows: the [`language`](Self::language), the + /// [`name`](Self::name), or the pair ([`label_of`]) -- flattened here + /// because a row shows one string, and derived from the two rather than + /// being what they are derived from. pub label: String, /// In start order. Empty when [`refused`](Self::refused) says why. pub cues: Vec, @@ -173,10 +188,16 @@ impl SubtitleTrack { /// A track that is there and cannot be read, named and kept: a project /// re-saved after one of these still lists it, which is the difference /// between "your subtitles are missing" and losing them for good. + /// + /// No language and no name: what is refused is never *written* (an export + /// drops it before the muxer, [`crate::export::planned_subtitles`]), and the + /// row it leaves behind shows the `label` it was refused under. fn refused(path: &Path, track: Option, label: String, why: String) -> Self { Self { path: path.to_path_buf(), track, + language: String::new(), + name: String::new(), label, cues: Vec::new(), bitmap: false, @@ -194,7 +215,8 @@ impl SubtitleTrack { } /// The one door a saved subtitle line comes back in through: a standalone file -/// (`track` is `None`) or track `n` of a Matroska file. +/// (`track` is `None`) or track `n` of a media file, Matroska or mp4 +/// ([`of_media`]). /// /// Never an error, whatever is wrong: a deleted `.srt`, a media file that is /// 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)]) -> Vec { let label = format!("track {number}"); let tracks = walked .entry(path.as_path()) - .or_insert_with(|| of_matroska(path)); + .or_insert_with(|| of_media(path)); let tracks = match tracks { Ok(tracks) => tracks, Err(why) => return SubtitleTrack::refused(path, *track, label, why.to_string()), @@ -263,6 +285,11 @@ fn external(path: &Path) -> SubtitleTrack { Ok(cues) => SubtitleTrack { path: path.to_path_buf(), track: None, + // A file beside the media states no language of its own -- and its + // name is the only thing it does state, which is what an export + // writes it as. + language: String::new(), + name: label.clone(), label, cues, // Every format `parse_file` reads is text. @@ -273,22 +300,96 @@ fn external(path: &Path) -> SubtitleTrack { } } +/// Every subtitle track *inside* a media file, whichever container it is: a +/// Matroska's ([`of_matroska`]) or an mp4's timed text ([`of_mp4`]). +/// +/// The one door for it, so a project row, an import and an export's read-back +/// cannot disagree about what a file carries -- and so an mp4 this project +/// wrote comes back into it, which is the whole reason the mp4 reader exists: +/// mp4 is the default export format, and a file edith writes and cannot open +/// is not a round trip. +pub fn of_media(path: &Path) -> crate::Result> { + match crate::demux::is_matroska(path) { + true => of_matroska(path), + false => of_mp4(path), + } +} + +/// Every timed-text (`tx3g`) subtitle track of an mp4, in track order, with its +/// cues -- the mp4 twin of [`of_matroska`]. +/// +/// A `tx3g` track is *continuous*: it states one sample per instant of the film +/// and the stretches with nothing on screen are samples of no text, so those are +/// dropped here rather than kept as cues with an empty line +/// ([`crate::demux::Mp4TextSample::payload`]). What is left is the cues, timed +/// on the file's own clock, and a track whose samples are all empty comes back +/// with none rather than with one per instant. +/// +/// Never a bitmap: an mp4 carries no PGS track this reads, so the refusal +/// [`of_matroska`] has for one has no counterpart here. +pub fn of_mp4(path: &Path) -> crate::Result> { + Ok(crate::demux::mp4_subtitles(path)? + .into_iter() + .map(|t| SubtitleTrack { + path: path.to_path_buf(), + track: Some(t.number), + label: label_of(&t.language, &t.name), + language: t.language, + name: t.name, + cues: t.samples.iter().filter_map(tx3g_cue).collect(), + bitmap: false, + refused: None, + }) + .collect()) +} + +/// One `tx3g` sample as a cue, or `None` for the sample that is not one: the +/// empty one that says nothing is on screen between here and the next line, and +/// the truncated one whose declared length runs past its own bytes. +fn tx3g_cue(sample: &crate::demux::Mp4TextSample) -> Option { + let len = usize::from(u16::from_be_bytes([ + *sample.payload.first()?, + *sample.payload.get(1)?, + ])); + let text = String::from_utf8_lossy(sample.payload.get(2..2 + len)?); + (!text.is_empty()).then(|| Cue { + start_us: sample.start_us, + end_us: sample.end_us, + text: text.into_owned(), + image: None, + }) +} + +/// What a list row shows for a track a container declares: the language, the +/// muxer's title, or the pair. +/// +/// A row shows one string, so the two are flattened for it -- and *only* for it. +/// Both are kept on the track beside this +/// ([`SubtitleTrack::language`], [`SubtitleTrack::name`]), so an export writes +/// the container's own two fields rather than guessing them back out of this +/// string, which is what used to leave every French track marked English. +fn label_of(language: &str, name: &str) -> String { + match (name.is_empty(), language) { + (true, lang) => lang.to_owned(), + (false, "und") => name.to_owned(), + (false, lang) => format!("{lang} — {name}"), + } +} + /// Every subtitle track of a Matroska file, in file order -- the text ones with /// their cues, the bitmap ones refused by name (see the module docs). pub fn of_matroska(path: &Path) -> crate::Result> { Ok(crate::demux::matroska_subtitles(path)? .into_iter() .map(|mut t| { - let label = match (t.name.is_empty(), t.language.as_str()) { - (true, lang) => lang.to_owned(), - (false, "und") => t.name.clone(), - (false, lang) => format!("{lang} — {}", t.name), - }; + let label = label_of(&t.language, &t.name); let bitmap = t.codec == crate::demux::PGS; match cues_of(&mut t) { Ok(cues) => SubtitleTrack { path: path.to_path_buf(), track: Some(t.number), + language: t.language, + name: t.name, label, cues, bitmap, @@ -505,8 +606,14 @@ fn parse_file(path: &Path) -> crate::Result> { "vtt" | "webvtt" => oxideav_subtitle::webvtt::parse, "ass" | "ssa" => oxideav_ass::parse, other => { + // What is *genuinely* accepted, all of it: the subtitle files this + // parses and the containers [`of_media`] walks for the tracks + // inside them (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`, `.mp4`, + // `.m4v`, `.mov`). The old sentence named the four text formats + // alone and so refused a `.mks` this very binary reads. return Err(format!( - "{other:?} is not a subtitle format this reads — .srt, .vtt, .ass and .ssa are" + "{other:?} is not a subtitle format this reads — .srt, .vtt, .ass and .ssa are, \ + as are the subtitle tracks inside a Matroska or an mp4" ) .into()); } @@ -545,6 +652,44 @@ mod tests { assert_eq!(srt_body("two\nlines\n"), "two\nlines"); } + /// The sample that is not a cue: a `tx3g` track states one sample per + /// instant, so the stretches with nothing on screen are samples of no text + /// -- a track of nothing but those is a track with no cues, not one blank + /// cue per instant. + #[test] + fn an_empty_timed_text_sample_is_not_a_cue() { + let sample = |payload: Vec| crate::demux::Mp4TextSample { + start_us: 500_000, + end_us: 1_500_000, + payload, + }; + let mut text = vec![0, 5]; + text.extend_from_slice(b"lines"); + let cue = tx3g_cue(&sample(text)).expect("a sample with words is a cue"); + assert_eq!( + (cue.start_us, cue.end_us, &cue.text[..]), + (500_000, 1_500_000, "lines") + ); + // The empty sample, the one an export writes between two cues and past + // the last of them... + assert!(tx3g_cue(&sample(vec![0, 0])).is_none()); + // ...and the bytes that are not a sample: a length past the payload, + // and no length at all. + assert!(tx3g_cue(&sample(vec![0, 9, b'h', b'i'])).is_none()); + assert!(tx3g_cue(&sample(Vec::new())).is_none()); + } + + /// What a row shows, and what an export has to split back apart: the pair a + /// container states, flattened the one way both readers flatten it. + #[test] + fn a_label_is_the_language_the_title_or_the_two() { + assert_eq!(label_of("eng", ""), "eng"); + assert_eq!(label_of("fra", "Signs"), "fra — Signs"); + // An undetermined language is no language: the title stands alone. + assert_eq!(label_of("und", "Commentary"), "Commentary"); + assert_eq!(label_of("und", ""), "und"); + } + #[test] fn an_unknown_extension_is_refused_by_name_and_a_missing_file_is_kept() { let err = parse_file(Path::new("/nonexistent/notes.txt")) diff --git a/crates/engine/tests/bitrate.rs b/crates/engine/tests/bitrate.rs new file mode 100644 index 0000000..dfa47da --- /dev/null +++ b/crates/engine/tests/bitrate.rs @@ -0,0 +1,292 @@ +//! `probe_bitrate`: the number a properties card shows, and the two rules that +//! make it worth showing -- it is the file's real bytes over the file's real +//! seconds, and a field the container never stated is absent rather than zero. + +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use engine::{MediaBitrate, probe_bitrate}; + +fn asset(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// What the fixture generator asked ffmpeg for, in seconds -- `-duration`/ +/// `-t` in `scripts/gen_fixtures.sh`. The independent half of the check: the +/// probe derives its seconds from the container (frame count over frame rate, +/// or the audio header), and this derives them from nowhere but the script that +/// wrote the file. +const FIXTURES: &[(&str, f64)] = &[ + ("test_av.mp4", 5.0), + ("test_av1.mkv", 2.0), + ("test_hevc.mkv", 2.0), + ("test_tone_48k.wav", 3.0), +]; + +/// Every fixture with a container to read, well-shaped or not. The two rules +/// below are held over all of them rather than over the tidy ones. +const CONTAINERS: &[&str] = &[ + "test_av.mp4", + "test_av1.mkv", + "test_hevc.mkv", + "test_hevc10.mkv", + "test_multiaudio.mp4", + "test_multiaudio.mkv", + "test_ac3.mkv", + "test_eac3.mkv", + "test_subs.mkv", + "test_vp9.mp4", + "test_h264.mkv", + "test_tone_48k.wav", + "test_short_video_long_audio.mp4", +]; + +/// No field is ever `Some(0)`: a zero read off a card is a measurement, and +/// "the header did not say" is not one. Held over every field of every fixture, +/// including the ones with no bitrate at all. +fn no_field_is_zero(name: &str, rate: MediaBitrate) { + for (field, value) in [ + ("total", rate.total), + ("video", rate.video), + ("audio", rate.audio), + ] { + assert_ne!(value, Some(0), "{name}: {field} came back a fabricated zero"); + } +} + +#[test] +fn a_breakdown_adds_up() { + // The relation that makes the three numbers one line rather than three + // unrelated ones: they are disjoint byte counts over a shared denominator, + // so the parts cannot outweigh the whole and the whole cannot outweigh the + // file. Asserted over every container fixture, not trusted to the + // well-shaped ones -- a total *below* its own components is impossible, and + // a total above the file's byte rate means the denominator is too small, + // which is exactly what dividing by the video track used to do. + for &name in CONTAINERS { + let path = asset(name); + let bytes = std::fs::metadata(&path).expect(name).len(); + let rate = probe_bitrate(&path); + no_field_is_zero(name, rate); + let total = rate.total.unwrap_or_else(|| panic!("{name}: no total")); + let parts = rate.video.unwrap_or(0) + rate.audio.unwrap_or(0); + assert!( + total >= parts, + "{name}: total {total} is under its own parts {parts}" + ); + // The ceiling: no file plays in less than no time, so no rate can beat + // the whole file delivered over the shortest plausible duration. One + // second is that floor -- every fixture here is longer. + assert!( + total <= bytes * 8, + "{name}: total {total} exceeds the file's own {} bits", + bytes * 8 + ); + } +} + +#[test] +fn a_long_soundtrack_over_a_short_picture_divides_by_the_file() { + // The lopsided container (`gen_fixtures.sh`): 2 s of video under 60 s of + // audio. Dividing 574 222 bytes by the *picture's* 2 s claimed 4 181 048 bps + // -- thirty times the truth, and a "total" smaller than its own components + // when written out. `ffprobe -show_entries format=bit_rate` says 76 562, and + // the container states its own 60 s in the `mvhd` for anyone who asks. + let name = "test_short_video_long_audio.mp4"; + let path = asset(name); + let bytes = std::fs::metadata(&path).expect(name).len(); + let rate = probe_bitrate(&path); + no_field_is_zero(name, rate); + + let total = rate.total.expect("no total"); + let expected = bytes as f64 * 8.0 / 60.0; + let error = (total as f64 - expected).abs() / expected; + assert!( + error < 0.05, + "{name}: total {total} is {:.1} % off the file over its own 60 s ({expected:.0})", + error * 100.0 + ); + // The picture is a fifth of the sound here, which is the whole point: a + // component measured over the video's 2 s would come out above the total. + let video = rate.video.expect("no video rate"); + let audio = rate.audio.expect("no audio rate"); + assert!(video < audio, "{name}: video {video} >= audio {audio}"); + assert!( + video + audio <= total, + "{name}: parts {} beat the total {total}", + video + audio + ); +} + +#[test] +fn total_is_the_file_over_its_seconds() { + for &(name, secs) in FIXTURES { + let path = asset(name); + let bytes = std::fs::metadata(&path).expect(name).len(); + let expected = bytes as f64 * 8.0 / secs; + + let rate = probe_bitrate(&path); + no_field_is_zero(name, rate); + let total = rate.total.unwrap_or_else(|| panic!("{name}: no total")); + + let error = (total as f64 - expected).abs() / expected; + assert!( + error < 0.05, + "{name}: total {total} bps is {:.1} % off {expected:.0} bps \ + ({bytes} bytes over {secs} s)", + error * 100.0 + ); + } +} + +#[test] +fn a_stream_the_container_states_is_stated_and_no_stream_is_invented() { + // Every A/V fixture here has a picture, so the video row is a claim the + // container can always answer -- an mkv out of its own block index, an mp4 + // out of its sample table. It must be under the whole file's rate too: a + // track cannot cost more than the file it sits in. + for &(name, secs) in FIXTURES { + let rate = probe_bitrate(&asset(name)); + let total = rate.total.unwrap_or_else(|| panic!("{name}: no total")); + if name.ends_with(".wav") { + // One stream, no picture: the sound *is* the file, and there is no + // video row to state. + assert_eq!(rate.video, None, "{name}: a wav has no picture"); + assert_eq!(rate.audio, Some(total), "{name}"); + continue; + } + let video = rate.video.unwrap_or_else(|| panic!("{name}: no video rate")); + assert!(video < total, "{name}: video {video} >= file {total}"); + // Sanity on the units: 5 s of 1280x720 is neither 2 kbps nor 2 Gbps. + assert!( + (10_000..100_000_000).contains(&video), + "{name}: video {video} bps is not a plausible rate for {secs} s of 720p" + ); + if let Some(audio) = rate.audio { + assert!(audio < total, "{name}: audio {audio} >= file {total}"); + } + } +} + +#[test] +fn a_matroska_states_its_sound_too_and_its_picture_is_unchanged() { + // Both mkv fixtures carry `-c:a aac -b:a 128k` (`gen_fixtures.sh:158,223`), + // so an absent audio row here is a missing measurement, not a silent file -- + // and a film library is overwhelmingly Matroska, so this is the common case. + // + // The video numbers are pinned so that adding the sound track to the walk + // cannot move the picture. The numerator is the one `ffprobe + // -select_streams v -show_entries packet=size` sums independently -- 716 834 + // bytes for test_av1.mkv. The denominator is `Info.Duration`, **2.023 s**, + // not the picture's own 2.000 s: the AAC track outlasts the last frame by + // 23 ms and the file really is that long (`ffprobe format=duration` agrees). + // These were 2_867_336 / 2_086_260 while the divisor was the video track, + // i.e. 1.1 % high, which is the same defect the lopsided fixture shows at + // 30x. + for (name, video_bps) in [("test_av1.mkv", 2_834_736), ("test_hevc.mkv", 2_062_540)] { + let rate = probe_bitrate(&asset(name)); + no_field_is_zero(name, rate); + assert_eq!(rate.video, Some(video_bps), "{name}: picture moved"); + let audio = rate + .audio + .unwrap_or_else(|| panic!("{name}: no audio rate, and it has a 128k AAC track")); + assert!( + (100_000..170_000).contains(&audio), + "{name}: audio {audio} bps, asked for 128000" + ); + } +} + +#[test] +fn the_mp4_rows_are_what_the_encoder_was_asked_for() { + // `gen_fixtures.sh:18` writes test_av.mp4's sound at `-b:a 128k`. Nothing + // reads `esds.avg_bitrate` any more -- the sample table is what the track + // actually spends -- so this is the check that walking the `stsz` lands + // where the declared number did. `ffprobe` puts this track at 132 311 and + // the picture at 3 119 464, both over the same 5 s the `mvhd` states. + let rate = probe_bitrate(&asset("test_av.mp4")); + assert_eq!(rate.video, Some(3_119_464), "test_av.mp4: picture"); + let audio = rate.audio.expect("test_av.mp4: no audio rate"); + assert!( + (120_000..140_000).contains(&audio), + "test_av.mp4: audio {audio} bps, asked for 128000" + ); +} + +#[test] +fn a_dual_audio_file_names_the_track_it_would_play_and_says_there_are_others() { + // `test_multiaudio.mp4` is the shape an AC-3 5.1 mp4 has: + // an AAC stereo track and a fatter AC-3 one in the same file. Whichever the + // bitrate row names, it names *one* of three, and the danger is calling a + // 0.13 Mb/s stereo track "sound" on a file whose selling point is the AC-3. + // + // The pick is the first audio track in file order, which is the same rule + // `AudioSession::probe_streams` numbers stream 0 by and the same one + // playback and export open. Asserted against `probe_streams` itself rather + // than against a constant, so the two can never drift apart silently: the + // bitrate row and the audio row of one card describe one track. + let name = "test_multiaudio.mp4"; + let path = asset(name); + let streams = engine::AudioSession::probe_streams(&path).expect(name); + assert!( + streams.len() > 1, + "{name}: the fixture stopped being multi-audio, this test is now vacuous" + ); + let rate = probe_bitrate(&path); + let audio = rate.audio.expect("no audio rate"); + + // Stream 0 is the 44.1k AAC stereo one (`gen_fixtures.sh:41`); the AC-3 at + // 192k is stream 2. Naming the wrong one would land near 192000. + assert_eq!(streams[0].index, 0, "{name}: stream order moved"); + assert_eq!(streams[0].codec, "aac", "{name}: stream 0 is not the AAC one"); + assert!( + (110_000..145_000).contains(&audio), + "{name}: audio {audio} bps is not stream 0's ~127 kbps AAC -- the row \ + and the audio row now name different tracks" + ); + // And the signal that it is one of several: the caller has the count in + // hand from the same probe it already runs, so a card can say so. This + // asserts the count is *reachable*, which is what makes the single number + // honest rather than a silent pick. + assert_eq!(streams.len(), 3, "{name}"); +} + +#[test] +fn a_still_states_no_rate_at_all() { + // A still has no playing time of its own -- its length on the timeline is + // whatever the clip is stretched to -- so there is no per-second anything + // to divide 1507 bytes by. All three fields absent is the honest answer; + // any number here would be invented. + let rate = probe_bitrate(&asset("test_still.png")); + no_field_is_zero("test_still.png", rate); + assert_eq!(rate, MediaBitrate::default(), "test_still.png"); +} + +#[test] +fn a_file_that_will_not_open_states_no_rate_either() { + // Not an error and not a zero: a probe run over a whole library meets these + // and the card simply has no row. + let rate = probe_bitrate(Path::new("/nonexistent/nothing.mp4")); + assert_eq!(rate, MediaBitrate::default()); + no_field_is_zero("missing", rate); +} + +#[test] +fn no_decoder_is_opened() { + // The whole point of the probe: it is cheap enough to run over every file a + // library lists. Decoding one frame of 10-bit HEVC costs far more than this + // budget, so a wall clock is what proves no decoder was opened -- 2 s of + // 720p Main 10 through the header path is single-digit milliseconds. + let path = asset("test_hevc10.mkv"); + let started = Instant::now(); + let rate = probe_bitrate(&path); + let elapsed = started.elapsed(); + no_field_is_zero("test_hevc10.mkv", rate); + assert!(rate.total.is_some(), "test_hevc10.mkv: no total"); + assert!( + elapsed.as_millis() < 50, + "probe_bitrate took {elapsed:?}, which is decode territory" + ); +} diff --git a/crates/engine/tests/export_subs.rs b/crates/engine/tests/export_subs.rs index f951e52..38269b0 100644 --- a/crates/engine/tests/export_subs.rs +++ b/crates/engine/tests/export_subs.rs @@ -1,7 +1,7 @@ -//! Subtitles leave with the file: a Matroska export carries the picked track as -//! `S_TEXT/UTF8`, timed on the *exported* timeline -- so a cut moves the cues -//! with the pictures they belong to -- and an mp4 says it cannot rather than -//! dropping them in silence. +//! Subtitles leave with the file, whichever file: a Matroska export carries +//! every picked track as `S_TEXT/UTF8` and an mp4 carries it as `tx3g` timed +//! text, both timed on the *exported* timeline -- so a cut moves the cues with +//! the pictures they belong to in either container. //! //! Two witnesses for every cue: this project's own Matroska reader //! (`demux::matroska_subtitles`, the way an exported file comes back into a @@ -76,6 +76,8 @@ fn track() -> SubtitleTrack { SubtitleTrack { path: asset(MEDIA), track: Some(2), + language: "eng".into(), + name: String::new(), label: "eng".into(), bitmap: false, cues: vec![ @@ -106,9 +108,28 @@ fn project() -> Project { Project::single(asset(MEDIA), FRAMES).with_subtitles(vec![track()]) } -/// Exports `project` as an HEVC Matroska carrying subtitle track `pick`, and -/// hands back what our own reader finds in the file. -fn exported(name: &str, project: Project, pick: Option) -> (Scratch, Vec) { +/// The two subtitle tracks `assets/test_subs.mkv` really carries -- `eng` as +/// `S_TEXT/UTF8` and `fra` (titled `Signs`) as `S_TEXT/ASS`, the same three cues +/// twice -- read back out of it the way an import reads them, and repointed at +/// the media this box can encode: that fixture's own picture is AV1 and there is +/// no software AV1 decoder to export it through. +fn both_tracks() -> Vec { + let mut tracks = subtitle::of_matroska(&asset("test_subs.mkv")).expect("read the fixture"); + assert_eq!( + tracks.len(), + 2, + "the fixture carries two tracks: {tracks:?}" + ); + for track in &mut tracks { + track.path = asset(MEDIA); + } + tracks +} + +/// Exports `project` as an HEVC Matroska carrying the subtitle tracks `picks`, +/// and hands back what our own reader finds in the file -- one track per pick, +/// in the order they were picked. +fn exported(name: &str, project: Project, picks: &[usize]) -> (Scratch, Vec) { pin_software(); let out = out_path(name); let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media"); @@ -118,34 +139,54 @@ fn exported(name: &str, project: Project, pick: Option) -> (Scratch, Vec< &out, &ExportSettings { format: Format::Hevc, - subtitles: pick, + subtitles: picks.to_vec(), ..Default::default() }, ); wait(&handle, Duration::from_secs(300)).expect("the export finishes"); let tracks = subtitle::of_matroska(&out).expect("read the export back"); - match pick { - None => { - assert!(tracks.is_empty(), "no pick, no track: {tracks:?}"); - (out, Vec::new()) - } - Some(_) => { - assert_eq!(tracks.len(), 1, "exactly the picked track: {tracks:?}"); - assert_eq!(tracks[0].refused, None, "the track reads back as text"); - (out, tracks[0].cues.clone()) - } + assert_eq!( + tracks.len(), + picks.len(), + "exactly the picked tracks: {tracks:?}" + ); + for track in &tracks { + assert_eq!(track.refused, None, "the track reads back as text"); } + (out, tracks) +} + +/// The same, as an **mp4**: the picked tracks leave as `tx3g` timed text, which +/// is what an mp4 says a subtitle with. Nothing here reads the file back with +/// this project's own reader -- there is no mp4 subtitle reader to read it with +/// -- so ffmpeg is the witness and the caller asks it. +fn exported_mp4(name: &str, project: Project, picks: &[usize]) -> Scratch { + pin_software(); + let out = Scratch::file(&format!("ve_subs_export_{name}"), "mp4"); + let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media"); + let handle = engine::export::start( + project, + meta, + &out, + &ExportSettings { + format: Format::Mp4, + subtitles: picks.to_vec(), + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(300)).expect("the export finishes"); + out } /// What ffmpeg makes of the same file's subtitle track, as an SRT on stdout: /// a second implementation reading the bytes, which is the whole point of it. /// `None` where there is no ffmpeg on the box -- the test is not about this /// machine's packages. -fn ffmpeg_srt(path: &Path) -> Option { +fn ffmpeg_srt(path: &Path, which: usize) -> Option { let out = Command::new("ffmpeg") .args(["-v", "error", "-i"]) .arg(path) - .args(["-map", "0:s:0", "-f", "srt", "-"]) + .args(["-map", &format!("0:s:{which}"), "-f", "srt", "-"]) .output() .ok()?; assert!( @@ -156,6 +197,19 @@ fn ffmpeg_srt(path: &Path) -> Option { Some(String::from_utf8_lossy(&out.stdout).into_owned()) } +/// What streams ffmpeg lists in the file, as it prints them -- `ffmpeg -i` with +/// no output, whose exit status is an error by design, so only the stream lines +/// are read. That listing carries each track's *language* beside its type +/// (`Stream #0:3(fra): Subtitle: subrip`), which is the second implementation's +/// word on what language the file says it is in. `None` where there is no +/// ffmpeg on the box. +fn ffmpeg_streams(path: &Path) -> Option { + let out = Command::new("ffmpeg").arg("-i").arg(path).output().ok()?; + let listing = String::from_utf8_lossy(&out.stderr).into_owned(); + println!("ffmpeg sees:\n{listing}"); + Some(listing) +} + fn near(got: i64, want: i64, what: &str) { assert!( (got - want).abs() <= SLACK_US, @@ -168,7 +222,8 @@ fn near(got: i64, want: i64, what: &str) { /// same three lines out of it. #[test] fn an_mkv_export_carries_the_picked_subtitle_track() { - let (out, cues) = exported("plain", project(), Some(0)); + let (out, tracks) = exported("plain", project(), &[0]); + let cues = &tracks[0].cues; assert_eq!(cues.len(), 3, "three cues: {cues:?}"); let want = [ (500_000, 1_500_000, "first line"), @@ -188,7 +243,7 @@ fn an_mkv_export_carries_the_picked_subtitle_track() { assert_eq!(raw[0].codec, "S_TEXT/UTF8"); assert_eq!(raw[0].language, "eng", "the label went in as a language"); - match ffmpeg_srt(&out) { + match ffmpeg_srt(&out, 0) { Some(srt) => { println!("ffmpeg reads the exported track back as:\n{srt}"); assert!(srt.contains("first line"), "{srt}"); @@ -215,7 +270,8 @@ fn a_cut_moves_the_cues_with_the_pictures() { "the hole closed, over two placements of the one source" ); - let (out, cues) = exported("cut", project, Some(0)); + let (out, tracks) = exported("cut", project, &[0]); + let cues = &tracks[0].cues; assert_eq!( cues.len(), 2, @@ -243,7 +299,7 @@ fn a_cut_moves_the_cues_with_the_pictures() { near(cues[1].end_us, 2_750_000, "...end with it"); assert_eq!(cues[1].text, "third line"); - if let Some(srt) = ffmpeg_srt(&out) { + if let Some(srt) = ffmpeg_srt(&out, 0) { println!("ffmpeg reads the cut export back as:\n{srt}"); assert!( !srt.contains("first line"), @@ -262,8 +318,344 @@ fn a_cut_moves_the_cues_with_the_pictures() { fn an_export_with_no_pick_carries_no_subtitle_track() { // `exported` asserts the file has no subtitle track at all; this is the // pick being absent rather than the timeline having nothing to pick. - let (out, cues) = exported("none", project(), None); - assert_eq!(cues, Vec::new()); + let (out, tracks) = exported("none", project(), &[]); + assert!(tracks.is_empty()); + std::fs::remove_file(&out).unwrap(); +} + +/// As many tracks as the timeline holds, not one: both of a film's own subtitle +/// tracks go into the export, each numbered and named for itself, and a player +/// -- ffmpeg here -- offers the two of them. +#[test] +fn every_picked_track_travels_with_its_own_name() { + let project = Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks()); + let (out, tracks) = exported("both", project, &[0, 1]); + // The labels the fixture states: a language on one, a language and a muxer's + // title on the other, and neither is the other's. + assert_eq!(tracks[0].label, "eng"); + assert_eq!(tracks[1].label, "fra — Signs"); + for track in &tracks { + assert_eq!(track.cues.len(), 3, "three cues each: {track:?}"); + near(track.cues[0].start_us, 500_000, "cue start"); + near(track.cues[2].end_us, 4_750_000, "cue end"); + assert_eq!( + track.cues[2].text, "third line", + "the ASS markup is resolved to text, not carried into the file" + ); + } + + // In the file itself: two text tracks, numbered from 3 up, and the second + // one's number is what its blocks name -- the reason the cues above came + // back apart rather than doubled onto one track. + let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element"); + assert_eq!( + raw.iter().map(|t| t.number).collect::>(), + vec![3, 4], + "the picture is 1, the sound 2, the text 3 and 4" + ); + assert!( + raw.iter().all(|t| t.codec == "S_TEXT/UTF8"), + "both are written as text: {raw:?}" + ); + assert_eq!(raw[0].language, "eng", "a three-letter label is a language"); + // The language and the title are two fields, not one string: a track that + // says `fra` is what a player's "French" setting finds, and a track that + // says only `Signs` is an *English* track to every reader, Matroska's + // default language being `eng`. + assert_eq!(raw[1].language, "fra", "the French track says so in the file"); + assert_eq!(raw[1].name, "Signs", "...and keeps its own title beside it"); + assert_eq!(raw[1].codec, "S_TEXT/UTF8"); + + match ffmpeg_streams(&out) { + Some(listing) => { + let n = listing.matches("Subtitle:").count(); + assert_eq!(n, 2, "ffmpeg lists both subtitle streams"); + // The other implementation reads the same two languages -- this is + // the assertion that used to come back `(eng)` for the French one. + assert!( + listing.contains("(eng): Subtitle") && listing.contains("(fra): Subtitle"), + "ffmpeg sees one English and one French track: {listing}" + ); + let second = ffmpeg_srt(&out, 1).expect("ffmpeg is here"); + println!("ffmpeg reads the second track back as:\n{second}"); + assert!(second.contains("third line"), "{second}"); + assert!(second.contains("00:00:00,500 --> 00:00:01,500"), "{second}"); + } + None => println!("no ffmpeg on this box: our own reader is the only witness"), + } + std::fs::remove_file(&out).unwrap(); +} + +/// The mp4 half of [`every_picked_track_travels_with_its_own_name`]: the very +/// same two tracks into the container the export *defaults* to, where they used +/// to be dropped with a card saying an mp4 carried none. ffmpeg is the whole +/// witness here -- a second implementation reading the bytes -- and it reads two +/// `mov_text` streams, one English and one French, the French one still titled +/// `Signs`, with the three cues at the three times. +#[test] +fn an_mp4_export_carries_the_picked_tracks_as_timed_text() { + let project = Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks()); + let out = exported_mp4("mp4_both", project, &[0, 1]); + let Some(listing) = ffmpeg_streams(&out) else { + println!("no ffmpeg on this box: an mp4's tx3g has no other reader here"); + std::fs::remove_file(&out).unwrap(); + return; + }; + assert_eq!( + listing.matches("Subtitle: mov_text").count(), + 2, + "two timed-text streams, not none and not one: {listing}" + ); + // The language is the `mdhd` field of each track, which is what a player's + // subtitle menu offers -- the mp4 spelling of the Matroska `Language` the + // sibling test pins. + assert!( + listing.contains("(eng): Subtitle") && listing.contains("(fra): Subtitle"), + "one English and one French: {listing}" + ); + // ...and the title beside it, which an mp4 states in a `trak/udta/name` box + // that `mp4 0.14` has no field for and this project patches in. + assert!( + listing.contains("name : Signs"), + "the French track keeps its own title: {listing}" + ); + for which in 0..2 { + let srt = ffmpeg_srt(&out, which).expect("ffmpeg is here"); + println!("ffmpeg reads mp4 track {which} back as:\n{srt}"); + assert!(srt.contains("00:00:00,500 --> 00:00:01,500"), "{srt}"); + assert!(srt.contains("first line"), "{srt}"); + // The line break inside a cue survives a sample that states its length + // in bytes and nothing else. + assert!(srt.contains("with a break"), "{srt}"); + assert!(srt.contains("00:00:04,000 --> 00:00:04,750"), "{srt}"); + assert!(srt.contains("third line"), "{srt}"); + } + std::fs::remove_file(&out).unwrap(); +} + +/// The pair a container states, carried through as a *pair*, into both +/// containers: a track's language and its title are two fields at every step +/// from the demuxer to the muxer, and neither is derived from the other. +/// +/// The two tracks here are the shapes that used to be lost. `fra` titled `Signs` +/// is the one every multi-language export declared English -- the two were +/// flattened into one label and split back apart by guessing, and a title that +/// was not three lowercase letters took the language down with it. `und` titled +/// `Commentary` is the same fault from the other side: a track that states its +/// language is undetermined said nothing at all in the file, and a Matroska +/// track with no `Language` *is* an English one by spec. +/// +/// Read back with this project's own readers -- ffmpeg is no witness for `und`, +/// which both its demuxers drop from the listing rather than print. +#[test] +fn a_language_and_a_title_are_two_fields_in_both_containers() { + let named = |language: &str, name: &str| SubtitleTrack { + language: language.into(), + name: name.into(), + label: format!("{language} — {name}"), + ..track() + }; + let tracks = vec![named("fra", "Signs"), named("und", "Commentary")]; + let project = || Project::single(asset(MEDIA), FRAMES).with_subtitles(tracks.clone()); + + let (out, read) = exported("pair", project(), &[0, 1]); + let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element"); + assert_eq!( + raw.iter() + .map(|t| (&t.language[..], &t.name[..])) + .collect::>(), + vec![("fra", "Signs"), ("und", "Commentary")], + "the Matroska keeps both fields of both tracks" + ); + // ...and the label a row shows is built back out of them, not stored: + // an undetermined language is no language to a reader. + assert_eq!(read[0].label, "fra — Signs"); + assert_eq!(read[1].label, "Commentary"); + std::fs::remove_file(&out).unwrap(); + + let out = exported_mp4("mp4_pair", project(), &[0, 1]); + let read = subtitle::of_mp4(&out).expect("read the mp4 back"); + assert_eq!( + read.iter() + .map(|t| (&t.language[..], &t.name[..])) + .collect::>(), + vec![("fra", "Signs"), ("und", "Commentary")], + "and so does the mp4, in its `mdhd` and its `udta/name`" + ); + for track in &read { + assert_eq!(track.cues.len(), 3, "three cues each: {track:?}"); + } + std::fs::remove_file(&out).unwrap(); +} + +/// The other mp4: an HEVC one, whose *video* sample entry is rewritten by hand +/// after the file is closed (`mux::patch_entry` turns the crate's `avc1` into +/// `hvc1`) -- the same rebuild of `moov` the subtitle track's title is patched +/// into. The two patches are one walk, so this is the file that says they do not +/// tread on each other: ffmpeg reads an HEVC picture *and* the timed text. +#[test] +fn an_hevc_mp4_keeps_its_rewritten_entry_and_its_text() { + pin_software(); + let out = Scratch::file("ve_subs_export_hevc_mp4", "mp4"); + let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media"); + let handle = engine::export::start( + Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks()), + meta, + &out, + &ExportSettings { + format: Format::HevcMp4, + subtitles: vec![1], + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(300)).expect("the export finishes"); + let Some(listing) = ffmpeg_streams(&out) else { + println!("no ffmpeg on this box: an mp4's tx3g has no other reader here"); + std::fs::remove_file(&out).unwrap(); + return; + }; + assert!(listing.contains("Video: hevc"), "the entry patch held: {listing}"); + assert!( + listing.contains("(fra): Subtitle: mov_text"), + "...and the text track beside it: {listing}" + ); + let srt = ffmpeg_srt(&out, 0).expect("ffmpeg is here"); + assert!(srt.contains("00:00:00,500 --> 00:00:01,500"), "{srt}"); + assert!(srt.contains("third line"), "{srt}"); + std::fs::remove_file(&out).unwrap(); +} + +/// ...and the cut lands in an mp4 where it lands in a Matroska: the samples of a +/// timed-text track are timed by their own durations, so a cue that moved with +/// its pictures has to come out moved here too. +#[test] +fn a_cut_moves_the_mp4_cues_with_the_pictures() { + let mut project = project(); + assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out"); + let out = exported_mp4("mp4_cut", project, &[0]); + let Some(srt) = ffmpeg_srt(&out, 0) else { + println!("no ffmpeg on this box: an mp4's tx3g has no other reader here"); + std::fs::remove_file(&out).unwrap(); + return; + }; + println!("ffmpeg reads the cut mp4 export back as:\n{srt}"); + assert!(!srt.contains("first line"), "the cut cue is not there: {srt}"); + assert!(srt.contains("00:00:00,500 --> 00:00:01,250"), "{srt}"); + assert!(srt.contains("00:00:02,000 --> 00:00:02,750"), "{srt}"); + assert!(srt.contains("third line"), "{srt}"); + std::fs::remove_file(&out).unwrap(); +} + +/// The ceiling itself, from underneath: a file carrying exactly +/// `MAX_SUB_TRACKS` tracks comes back whole. The last of them is track 126, +/// whose block byte is `0xFE` -- one under the all-ones `0xFF` that EBML spells +/// *unknown* with, which is what a 127th track's blocks would say and why its +/// cues would come back nowhere. Read back with our own reader, so the file is +/// one edith can re-import and not merely write. +#[test] +fn the_last_numberable_track_keeps_its_cues() { + let full = engine::mux::MAX_SUB_TRACKS; + let picks: Vec = (0..full).collect(); + let project = + Project::single(asset(MEDIA), FRAMES).with_subtitles((0..full).map(|_| track()).collect()); + let (out, tracks) = exported("ceiling_at", project, &picks); + let empty: Vec = tracks + .iter() + .enumerate() + .filter(|(_, t)| t.cues.is_empty()) + .map(|(i, _)| i) + .collect(); + assert!( + empty.is_empty(), + "every one of the {full} tracks keeps its three cues; these came back with none: {empty:?}" + ); + let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element"); + assert_eq!( + raw.iter().map(|t| t.number).collect::>(), + (3..3 + full as u64).collect::>(), + "numbered 3 up to the last one a block byte can name" + ); + assert_eq!(raw.last().map(|t| t.number), Some(126)); + std::fs::remove_file(&out).unwrap(); +} + +/// The ceiling is said out loud: a Matroska block names its track in one byte, +/// so past `MAX_SUB_TRACKS` the export refuses by name instead of writing a byte +/// that means some other track -- and leaves no file behind. +#[test] +fn more_tracks_than_a_block_can_number_are_refused_by_name() { + pin_software(); + let over = engine::mux::MAX_SUB_TRACKS + 1; + let project = + Project::single(asset(MEDIA), FRAMES).with_subtitles((0..over).map(|_| track()).collect()); + let out = out_path("ceiling"); + let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media"); + let handle = engine::export::start( + project, + meta, + &out, + &ExportSettings { + format: Format::Hevc, + subtitles: (0..over).collect(), + ..Default::default() + }, + ); + let said = wait(&handle, Duration::from_secs(300)) + .expect_err("a file that cannot be numbered is not written") + .to_string(); + assert!( + said.contains(&format!("{over} subtitle tracks")) + && said.contains(&format!("at most {}", engine::mux::MAX_SUB_TRACKS)), + "the refusal says how many were asked for and how many fit: {said}" + ); + assert!(!out.exists(), "and no half-written file is left: {said}"); +} + +/// A language stated the modern way (`LanguageBCP47`, no legacy element) leaves +/// with the file, in the element every reader looks at. +/// +/// The loss used to survive the export: a 22-track Matroska listed +/// `2,subrip,English (UK) (SDH)` with an *empty* language field beside +/// neighbours that kept `ara` and `chi`, because the source stated `en` in an +/// element nothing here read. What is written is still the legacy element -- a +/// three-letter code is what Matroska's `Language` and an mp4's `mdhd` hold, and +/// ffmpeg 8.1.2 reads no `LanguageBCP47` at all. +#[test] +fn a_language_stated_the_modern_way_leaves_with_the_file() { + let mut tracks = + subtitle::of_matroska(&asset("test_subs_bcp47.mkv")).expect("read the fixture"); + assert_eq!( + tracks.len(), + 2, + "the fixture carries two tracks: {tracks:?}" + ); + for track in &mut tracks { + track.path = asset(MEDIA); + } + assert_eq!( + tracks.iter().map(|t| &*t.language).collect::>(), + ["eng", "fra"], + "`en` and `fr` are read as the codes an export writes" + ); + + let project = Project::single(asset(MEDIA), FRAMES).with_subtitles(tracks); + let (out, back) = exported("bcp47", project, &[0, 1]); + assert_eq!( + back.iter().map(|t| &*t.language).collect::>(), + ["eng", "fra"], + "and they are the codes the file states" + ); + let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element"); + assert_eq!( + raw[1].name, "Signs", + "the title travels beside the language" + ); + if let Some(listing) = ffmpeg_streams(&out) { + assert!( + listing.contains("(eng): Subtitle") && listing.contains("(fra): Subtitle"), + "a second implementation reads both languages: {listing}" + ); + } std::fs::remove_file(&out).unwrap(); } @@ -275,23 +667,78 @@ fn the_plan_says_what_each_container_does_with_them() { let plan = |format| engine::export::planned_subtitles(&project, format, Some(0)); assert_eq!(plan(Format::Hevc), "eng → embedded"); assert_eq!(plan(Format::Av1), "eng → embedded"); - assert_eq!(plan(Format::Mp4), "mkv only — an mp4 carries none"); - assert_eq!(plan(Format::HevcMp4), "mkv only — an mp4 carries none"); + // An mp4 carries them too, as `tx3g` -- so the card says what travels + // rather than which container to switch to. The refusal it used to print + // ("mkv only — an mp4 carries none") was a claim about the container that + // the container never made. + assert_eq!(plan(Format::Mp4), "eng → embedded"); + assert_eq!(plan(Format::HevcMp4), "eng → embedded"); + assert_eq!(plan(Format::Av1Mp4), "eng → embedded"); assert_eq!(plan(Format::Wav), "none — this format is the sound alone"); - // No pick, and a pick nothing answers, are both "none" rather than a panic - // or a lie. + // A track of *pictures* on a format that is the sound alone says what the + // file cannot do rather than what the track cannot: the per-track reason + // used to be pushed first, which left the sentence above unreachable for a + // pick that was all bitmaps -- an MP3 with a PGS track picked read + // "pictures; drawn, not written", a true sentence about the wrong thing. + let mut pictures = track(); + pictures.bitmap = true; + pictures.label = "PGS".into(); + let pgs = Project::single(asset(MEDIA), FRAMES).with_subtitles(vec![pictures]); + assert_eq!( + engine::export::planned_subtitles(&pgs, Format::Mp3, Some(0)), + "none — this format is the sound alone" + ); + // ...and on a container that carries text it is the *track* that cannot + // travel, which is the other sentence and just as true: both are reachable. + assert_eq!( + engine::export::planned_subtitles(&pgs, Format::Hevc, Some(0)), + "PGS — pictures; drawn, not written" + ); + // Nothing picked is "none" whatever the format -- there is no track for a + // container to have nowhere to put. + assert_eq!( + engine::export::planned_subtitles(&pgs, Format::Mp3, None), + "none" + ); + // No pick is "none" rather than a panic or a lie... assert_eq!( engine::export::planned_subtitles(&project, Format::Hevc, None), "none" ); + // ...and a pick the project has no row for is *named*, like every other + // reason a pick does not travel: an index nothing answers is a caller's bug + // and the card is where a bug is seen, not the finished file. assert_eq!( engine::export::planned_subtitles(&project, Format::Hevc, Some(9)), - "none" + "#9 — no such track" ); - // A timeline that never had subtitles says the same thing. let bare = Project::single(asset(MEDIA), FRAMES); assert_eq!( engine::export::planned_subtitles(&bare, Format::Hevc, Some(0)), - "none" + "#0 — no such track" + ); + // ...and it costs its own row and not the others': the tracks around it + // still travel, which is what made this one easy to miss. + assert_eq!( + engine::export::planned_subtitles(&project, Format::Hevc, [0, 99]), + "eng → embedded; #99 — no such track" + ); + + // Two picks are two tracks, named: the count first, because that is what the + // row is answering, and the names after it because that is what a menu will + // show. + let two = Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks()); + assert_eq!( + engine::export::planned_subtitles(&two, Format::Hevc, [0, 1]), + "2 tracks → embedded (eng, fra — Signs)" + ); + // ...and a pick that cannot travel costs its own row and not the other's: + // the empty track is dropped by name, the real one still goes. + let mut mixed = both_tracks(); + mixed[1].cues.clear(); + let mixed = Project::single(asset(MEDIA), FRAMES).with_subtitles(mixed); + assert_eq!( + engine::export::planned_subtitles(&mixed, Format::Hevc, [0, 1]), + "eng → embedded; fra — Signs — no cues" ); } diff --git a/crates/engine/tests/import_mp4_subs.rs b/crates/engine/tests/import_mp4_subs.rs new file mode 100644 index 0000000..d6b7b84 --- /dev/null +++ b/crates/engine/tests/import_mp4_subs.rs @@ -0,0 +1,231 @@ +//! An mp4's subtitles come back *in*: what `mux` writes as `tx3g` timed text, +//! `subtitle::of_mp4` reads, so the default export format round-trips -- a file +//! edith wrote is a file edith opens with its subtitle tracks still on it. +//! +//! Two witnesses again, the other way round from `export_subs.rs`: our own +//! writer's file read by our own reader (the round trip), and a file **ffmpeg** +//! muxed read by the same reader -- so what is pinned here is the format and +//! not this project agreeing with itself. +//! +//! ```text +//! cargo test -p engine --release --test import_mp4_subs -- --nocapture +//! ``` + +use std::path::PathBuf; +use std::process::Command; +use std::sync::Once; +use std::time::{Duration, Instant}; + +use engine::export::{ExportSettings, Format}; +use engine::scratch::Scratch; +use engine::subtitle::{self, SubtitleTrack}; +use engine::{ExportHandle, Project}; + +/// The media fixture: five seconds at 30 fps, a picture this box decodes and +/// encodes with nothing installed. +const MEDIA: &str = "test_av.mp4"; +const FRAMES: u32 = 150; +/// What a cue may be out by: the track's own tick, a millisecond. +const SLACK_US: i64 = 1_000; + +/// The three cues both fixtures carry, and the times an export puts them at. +const WANT: [(i64, i64, &str); 3] = [ + (500_000, 1_500_000, "first line"), + (2_000_000, 3_250_000, "second line\nwith a break"), + (4_000_000, 4_750_000, "third line"), +]; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn pin_software() { + static PIN: Once = Once::new(); + PIN.call_once(|| unsafe { + std::env::set_var("VE_SW", "1"); + std::env::set_var("VE_SW_ENC", "1"); + }); +} + +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < limit, + "export did not finish in {limit:?}" + ); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("a finished export has an outcome") +} + +fn near(got: i64, want: i64, what: &str) { + assert!( + (got - want).abs() <= SLACK_US, + "{what}: {got} us is not within a millisecond of {want} us" + ); +} + +/// The two tracks `assets/test_subs.mkv` carries -- `eng` as `S_TEXT/UTF8` and +/// `fra` titled `Signs` as `S_TEXT/ASS`, the same three cues twice -- repointed +/// at the media this box can encode, exactly as `export_subs.rs` does it. +fn both_tracks() -> Vec { + let mut tracks = subtitle::of_matroska(&asset("test_subs.mkv")).expect("read the fixture"); + assert_eq!( + tracks.len(), + 2, + "the fixture carries two tracks: {tracks:?}" + ); + for track in &mut tracks { + track.path = asset(MEDIA); + } + tracks +} + +/// An mp4 export of both tracks, on disk. +fn exported_mp4(name: &str) -> Scratch { + pin_software(); + let out = Scratch::file(&format!("ve_import_mp4_subs_{name}"), "mp4"); + let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media"); + let handle = engine::export::start( + Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks()), + meta, + &out, + &ExportSettings { + format: Format::Mp4, + subtitles: vec![0, 1], + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(300)).expect("the export finishes"); + out +} + +fn check_pair(tracks: &[SubtitleTrack], what: &str) { + for track in tracks { + println!( + "{what}: {} track {:?} {:?}", + track.label, + track.track, + track + .cues + .iter() + .map(|c| (c.start_us, c.end_us, &c.text)) + .collect::>() + ); + } + assert_eq!(tracks.len(), 2, "{what}: two tracks: {tracks:?}"); + // The language and the title, apart: `eng` is a language alone, `Signs` is + // a French track's own name -- the pair `mdhd` and `trak/udta/name` hold. + assert_eq!(tracks[0].label, "eng", "{what}"); + assert_eq!(tracks[1].label, "fra — Signs", "{what}"); + for track in tracks { + assert_eq!(track.refused, None, "{what}: the track reads"); + assert!(!track.is_bitmap(), "{what}: timed text is not pictures"); + assert_eq!( + track.cues.len(), + 3, + "{what}: the empty samples between the cues are not cues: {:?}", + track.cues + ); + for (cue, (start, end, text)) in track.cues.iter().zip(WANT) { + near(cue.start_us, start, &format!("{what}: cue start")); + near(cue.end_us, end, &format!("{what}: cue end")); + assert_eq!(cue.text, text, "{what}: the words travel, breaks and all"); + assert!(cue.image.is_none(), "{what}: text, not a picture"); + } + } +} + +/// The round trip: two tracks out as `tx3g`, the same two back in -- languages, +/// titles, words and times. +#[test] +fn an_mp4_export_comes_back_with_the_subtitles_it_left_with() { + let out = exported_mp4("round"); + let tracks = subtitle::of_mp4(&out).expect("read our own mp4 back"); + println!( + "our mp4 reads back as: {:?}", + tracks + .iter() + .map(|t| (&t.label, t.track, t.cues.len())) + .collect::>() + ); + check_pair(&tracks, "our own writer"); + // The picture is track 1 and the sound 2, so the text is 3 and 4 -- the + // numbers a `.edith` row names, which is what makes the row openable. + assert_eq!( + tracks.iter().map(|t| t.track).collect::>(), + vec![Some(3), Some(4)] + ); + + // ...and through the door a saved project comes back in by, which is the + // point of the numbers above. + let second = subtitle::open(&out, Some(4)); + assert_eq!(second.refused, None, "the saved row opens: {second:?}"); + assert_eq!(second.label, "fra — Signs"); + assert_eq!(second.cues.len(), 3); + std::fs::remove_file(&out).unwrap(); +} + +/// The same file read by the same door the *import button* goes through, which +/// is what makes this reachable rather than merely written. +#[test] +fn the_import_door_walks_an_mp4_for_its_subtitles() { + let out = exported_mp4("import"); + let tracks = + engine::PlaybackSession::parse_subtitles(&out).expect("the import door walks the mp4"); + check_pair(&tracks, "the import door"); + std::fs::remove_file(&out).unwrap(); +} + +/// A file with no timed-text track: no tracks, no refusal, nothing invented. +#[test] +fn an_mp4_without_subtitles_reads_as_no_tracks_at_all() { + let tracks = subtitle::of_mp4(&asset(MEDIA)).expect("the fixture opens"); + assert!(tracks.is_empty(), "nothing was invented: {tracks:?}"); + let raw = engine::demux::mp4_subtitles(&asset(MEDIA)).expect("the walk itself"); + assert!(raw.is_empty(), "{raw:?}"); +} + +/// The other implementation's file: what `ffmpeg -c:s mov_text` muxes, read by +/// this reader. Skipped where there is no ffmpeg on the box -- the test is not +/// about this machine's packages. +#[test] +fn an_ffmpeg_muxed_mov_text_track_reads_the_same_way() { + let out = Scratch::file("ve_import_mp4_subs_ffmpeg", "mp4"); + let made = Command::new("ffmpeg") + .args(["-y", "-v", "error", "-i"]) + .arg(asset("test_subs.mkv")) + .args([ + "-map", "0:v", "-map", "0:s", "-c:v", "copy", "-c:s", "mov_text", + ]) + .arg(&*out) + .status(); + let Ok(status) = made else { + println!("no ffmpeg on this box: the round trip is the only witness"); + return; + }; + assert!(status.success(), "ffmpeg refused to mux the fixture"); + + let tracks = subtitle::of_mp4(&out).expect("read ffmpeg's mp4"); + println!( + "ffmpeg's mp4 reads back as: {:?}", + tracks + .iter() + .map(|t| (&t.label, t.track, t.cues.len())) + .collect::>() + ); + // ffmpeg's timed-text tracks are timed in *microseconds* where ours are in + // milliseconds, and it writes the same `trak/udta/name` for the title: the + // two things a reader of one muxer's quirks would get wrong. + check_pair(&tracks, "ffmpeg's muxer"); + let raw = engine::demux::mp4_subtitles(&out).expect("the walk itself"); + assert_eq!( + raw[1].language, "fra", + "the language is the file's: {raw:?}" + ); + assert_eq!(raw[1].name, "Signs", "...and the title is beside it"); + std::fs::remove_file(&out).unwrap(); +} diff --git a/crates/engine/tests/subtitles.rs b/crates/engine/tests/subtitles.rs index 59163a3..31d4cba 100644 --- a/crates/engine/tests/subtitles.rs +++ b/crates/engine/tests/subtitles.rs @@ -291,6 +291,131 @@ fn a_project_keeps_its_subtitles_across_a_save() { ); } +/// The two-door import: the parse runs with no session in hand -- which is what +/// lets a front-end run it off the render thread -- and the tracks it hands back +/// go on the timeline for the cost of a push. Same dedupe as the one-call door, +/// so the same file twice is still one set of rows, and what lands is saved and +/// loaded as a reference exactly like an `import_subtitles` row. +#[test] +fn parsed_tracks_can_be_handed_to_a_session_without_it_reading_the_file() { + let dir = scratch("handoff"); + let media = dir.join("test_av.mp4"); + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); + let mkv = dir.join("test_subs.mkv"); + std::fs::copy(asset("test_subs.mkv"), &mkv).expect("copy the subtitle fixture"); + + // The door a background executor calls: no `&self`, so nothing about the + // session is borrowed while the container is walked. + let tracks = + engine::PlaybackSession::parse_subtitles(&mkv).expect("the mkv is walked off-thread"); + assert_eq!(tracks.len(), 2, "both tracks of the fixture"); + // Owned data all the way down, so the parse may run on a background task + // and its result be sent back: a track holding a handle would put the walk + // back on the thread that draws. + fn sendable(_: &T) {} + sendable(&tracks); + + let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); + session.set_gain(0.0); + assert_eq!(session.add_subtitle_tracks(tracks.clone()), 2, "both go on"); + // The same tracks again are the same subtitles: the (path, track) dedupe is + // what a front-end's "already on the timeline" line falls out of. + assert_eq!(session.add_subtitle_tracks(tracks), 0, "and no repeat rows"); + assert_eq!(session.subtitles().len(), 2); + // And the one-call door agrees with it, over the very same file. + assert_eq!(session.import_subtitles(&mkv).expect("no error"), 0); + assert_eq!(session.subtitles()[0].cues, expected()); + + let project = dir.join("cut.edith"); + session.save_project(&project).expect("save"); + let back = engine::PlaybackSession::open_project(&project).expect("open the project"); + assert_eq!( + back.subtitles().iter().map(|t| t.track).collect::>(), + session + .subtitles() + .iter() + .map(|t| t.track) + .collect::>(), + "a handed-over row is a reference like any other" + ); + assert_eq!(back.subtitles()[1].cues, expected()); +} + +/// Whatever an import added comes back off: three tracks go on, the middle one +/// is removed, and what is left is the other two *in the order they were added* +/// -- a save then writes exactly those two references and a load reads back +/// exactly them. The bad index is a refusal naming the index, not a silent +/// no-op, since a front-end holding a stale row has picked the wrong one. +#[test] +fn a_subtitle_row_can_be_removed_and_the_survivors_round_trip() { + let dir = scratch("remove"); + let media = dir.join("test_av.mp4"); + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); + // Three files rather than three tracks of one: `add_subtitles` dedupes by + // (path, track), so three names are three rows. + for name in ["a.srt", "b.srt", "c.srt"] { + std::fs::copy(data("test_subs.srt"), dir.join(name)).expect("copy the subtitle fixture"); + } + + let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); + session.set_gain(0.0); + for name in ["a.srt", "b.srt", "c.srt"] { + assert_eq!( + session + .import_subtitles(&dir.join(name)) + .expect("the .srt imports"), + 1 + ); + } + assert_eq!(session.subtitles().len(), 3); + + session.remove_subtitles(1).expect("the middle row goes"); + let names: Vec = session + .subtitles() + .iter() + .map(|t| { + t.path + .file_name() + .expect("a name") + .to_string_lossy() + .into_owned() + }) + .collect(); + assert_eq!(names, vec!["a.srt", "c.srt"], "the survivors keep their order"); + assert_eq!(session.subtitles()[0].cues, expected(), "and their cues"); + + let project = dir.join("cut.edith"); + session.save_project(&project).expect("save"); + let text = std::fs::read_to_string(&project).expect("read the project back"); + assert!( + text.contains("\nsubtitle - a.srt\n") && text.contains("\nsubtitle - c.srt\n"), + "the survivors are written, by reference: {text}" + ); + assert!( + !text.contains("b.srt"), + "and the removed one is not: {text}" + ); + + let back = engine::PlaybackSession::open_project(&project).expect("open the project"); + assert_eq!( + back.subtitles() + .iter() + .map(|t| t.path.file_name().expect("a name").to_string_lossy().into_owned()) + .collect::>(), + vec!["a.srt", "c.srt"], + "and a load is the same two, in the same order" + ); + assert_eq!(back.subtitles()[1].cues, expected()); + + // A row that is not there says so, naming the index a front-end passed. + let why = session + .remove_subtitles(9) + .expect_err("there is no row 9") + .to_string(); + assert!(why.contains('9') && why.contains("subtitle"), "{why}"); + assert_eq!(session.subtitles().len(), 2, "and nothing moved"); +} + /// A bitmap track survives a save the same way a text one does, and for the /// same reason: a `.edith` holds the file and the track number, never a cue, so /// 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() { assert_eq!(session.subtitles().len(), 0, "and nothing was added"); } +/// The Matroska that is the subtitles alone: `.mks`, what a subtitle release +/// ships beside the film, imported by the door an `.mkv` is imported by. +/// +/// The refusal it used to get -- *"mks" is not a subtitle format this reads* -- +/// was a claim about a container this very binary parses: the bytes are a +/// Matroska's and the same walk reads them, so only the extension list said no. +#[test] +fn a_matroska_that_is_the_subtitles_alone_imports_like_any_other() { + let dir = scratch("mks"); + let media = dir.join("test_av.mp4"); + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); + + let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); + session.set_gain(0.0); + let added = session + .import_subtitles(&asset("test_subs.mks")) + .expect("a .mks is a Matroska and imports as one"); + assert_eq!(added, 2, "both its tracks came in"); + let labels: Vec<&str> = session.subtitles().iter().map(|t| &*t.label).collect(); + assert_eq!(labels, ["eng", "fra — Signs"], "with their own names"); + for track in session.subtitles() { + assert_eq!(track.refused, None, "{} parses", track.label); + assert_eq!(track.cues, expected(), "{} holds the cues", track.label); + } +} + +/// A track that states its language the way a modern muxer states it -- +/// `LanguageBCP47` and no legacy `Language` element at all -- keeps that +/// language, where it used to come in as `und`. +/// +/// The shape of every English track of a dual-language remux and all four +/// of the 17-track library file ones: they read as `und` while the file said `en`, +/// and the loss survived into the exported file's track list. +#[test] +fn a_track_that_states_its_language_the_modern_way_keeps_it() { + // The fixture is what it claims to be: the modern element is in it and the + // legacy one is not, so what is being read is the new element and not a + // leftover of the old one. + let bytes = std::fs::read(asset("test_subs_bcp47.mkv")).expect("the fixture is there"); + assert!( + bytes.windows(3).any(|w| w == [0x22, 0xB5, 0x9D]), + "the fixture states LanguageBCP47" + ); + for legacy in [b"\x22\xb5\x9c\x83eng".as_slice(), b"\x22\xb5\x9c\x83fra"] { + assert!( + !bytes.windows(legacy.len()).any(|w| w == legacy), + "and states no legacy Language element for its subtitle tracks" + ); + } + + let tracks = subtitle::of_matroska(&asset("test_subs_bcp47.mkv")).expect("the mkv is walked"); + let languages: Vec<&str> = tracks.iter().map(|t| &*t.language).collect(); + assert_eq!(languages, ["eng", "fra"], "`en` is English, `fr` is French"); + // ...and the same file with the legacy element reads exactly the same, which + // is the point: which element a muxer chose is not something a row shows. + let legacy = subtitle::of_matroska(&asset("test_subs.mkv")).expect("the mkv is walked"); + let want: Vec<&str> = legacy.iter().map(|t| &*t.label).collect(); + let got: Vec<&str> = tracks.iter().map(|t| &*t.label).collect(); + assert_eq!(got, want, "the two files list the same two tracks"); +} + /// An EBML element: its id as it is written in the file, then an 8-byte /// length, which is always a legal encoding of one. fn element(id: &[u8], body: &[u8]) -> Vec { diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index c6a4fc0..7e2e18a 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -211,6 +211,33 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=5 \ -c:s:0 srt -metadata:s:s:0 language=eng \ -c:s:1 ass -metadata:s:s:1 language=fra -metadata:s:s:1 title=Signs \ assets/test_subs.mkv +# The same two tracks with no picture and no sound at all: `.mks`, the Matroska +# extension that is the subtitles alone (what a subtitle release ships beside +# the film). Refused by name until the container gate learned every Matroska +# extension rather than the two that carry a film -- the very reader that walks +# a `.mkv` walks this. +ffmpeg -y -i crates/engine/tests/data/test_subs.srt \ + -i crates/engine/tests/data/test_subs.ass -map 0:0 -map 1:0 \ + -c:s:0 srt -metadata:s:s:0 language=eng \ + -c:s:1 ass -metadata:s:s:1 language=fra -metadata:s:s:1 title=Signs \ + -f matroska assets/test_subs.mks +# ...and the same file stating its languages the way a modern muxer does: in +# `LanguageBCP47` (0x22B59D) and *not* in the legacy `Language` (0x22B59C), +# which is the shape of every English track of a dual-language remux and +# `a 17-track library file`. ffmpeg writes only the legacy element (8.1.2 does not read +# the BCP-47 one either), so the element is swapped in place afterwards: the +# 4-byte id, then the length as a two-byte VINT (`40 02`, a legal non-minimal +# encoding) so the tag is two bytes and the element stays the eight bytes it +# was -- every enclosing size in the file survives untouched. +python3 - <<'PATCH' +data = open("assets/test_subs.mkv", "rb").read() +size = len(data) +for legacy, tag in ((b"eng", b"en"), (b"fra", b"fr")): + data = data.replace(b"\x22\xb5\x9c\x83" + legacy, b"\x22\xb5\x9d\x40\x02" + tag) +assert len(data) == size, "the swap has to be size-for-size" +assert b"\x22\xb5\x9d" in data, "and it has to have happened" +open("assets/test_subs_bcp47.mkv", "wb").write(data) +PATCH # HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as # test_hevc.mp4 so the tests measure the container and nothing else, `-g 30` for # 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" \ -f lavfi -i "aevalsrc=sin(2*PI*(200*t+80*t*t)):s=48000:d=30" \ -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p -g 120 \ -c:a libopus -b:a 128k assets/test_seek_chirp.mkv +# The lopsided container: 2 s of picture under 60 s of sound, which is what a +# still with a song over it or a botched remux looks like from the outside. The +# point is the *denominator* -- a file 60 s long whose video track is 2 s long +# reports thirty times its real byte rate if the bitrate row divides by the +# picture rather than by the file (`crates/engine/tests/bitrate.rs`). Nothing +# else here has this shape, which is exactly why it is here. +ffmpeg -y -f lavfi -i "testsrc2=size=320x240:rate=30:duration=2" \ + -f lavfi -i "sine=frequency=440:duration=60" \ + -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ + -c:a aac -b:a 64k assets/test_short_video_long_audio.mp4 echo "fixtures written to assets/"