diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index ee63775..22d6f03 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -4139,8 +4139,13 @@ impl Player { if self.export.is_some() { return; } - let settings = + 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); let Some(session) = &mut self.session else { self.notice = Some("NOTHING TO EXPORT — open a file first".into()); cx.notify(); @@ -6394,6 +6399,27 @@ 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. + 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(), + false, + false, + ) + .into_any_element(), + ); let destination = entry( ("destination", 0), "d", @@ -10126,6 +10152,10 @@ fn export_settings( // badly, which is a thing about the machine and not about the output -- // `VE_SW_ENC` already says it, and to the whole run rather than once. force_sw: false, + // 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, } } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index c7853f7..4275969 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -62,9 +62,10 @@ use flacenc::error::Verify; use crate::audio::{AudioMeta, AudioSession}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; -use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, VideoParams}; +use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams}; use crate::project::{LaneKind, Project, Rate}; use crate::scale::Composer; +use crate::subtitle::{Cue, SubtitleTrack}; /// Progress is reported in permille: an atomic integer the render loop can read /// without a lock, fine enough for any progress bar. @@ -228,6 +229,16 @@ 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. + /// + /// 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, } struct Shared { @@ -525,6 +536,136 @@ 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. +fn export_subtitles( + project: &Project, + meta: &VideoMeta, + settings: &ExportSettings, +) -> Option { + if !matches!(settings.format, Format::Av1 | Format::Hevc) { + return None; + } + let track = project.subtitles().get(settings.subtitles?)?; + if track.refused.is_some() { + return None; + } + let cues = timeline_cues(project, track, meta.frame_rate); + (!cues.is_empty()).then(|| SubParams { + label: track.label.clone(), + cues, + }) +} + +/// The track's cues where the *exported* timeline puts them, which is the only +/// clock the file has: the export writes timeline frame 0 onwards and nothing +/// else, exactly as the sound is mixed from frame 0 and resized to the +/// timeline's own length ([`encode_audio`]). +/// +/// Which clock the cues arrive in is what the track itself says: +/// +/// * a track out of a *file* (`SubtitleTrack::track`) is timed against that +/// file, so each cue is carried through the spans that play it -- a cue over +/// a stretch that was cut out is gone, one straddling a cut keeps the half +/// that is still there, and one after a rippled delete moves back with the +/// picture it belongs to. The *edges* a cut clips to are frames -- that is +/// what a cut is -- but a cue nothing clipped keeps its own microseconds, so +/// an untouched timeline exports the times the source states. +/// * a *standalone* file (`subs.srt`) is timed against nothing else -- there is +/// no clip to hang it on and no offset in the project to shift it by -- so it +/// is the timeline's own clock, which is where it was drawn while editing +/// (`Player::subtitle_overlay`). Clipped to the exported length and no more. +/// +/// ponytail: the overlay draws *every* track on the timeline's clock, so on a +/// rippled timeline what the picture shows and what an embedded track exports +/// now disagree. The upgrade path is this function: the overlay should ask it +/// too, at which point both halves move together. It is left because the app is +/// another lane's file this week. +fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec { + let frames = project.timeline_frames(); + let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64; + let end = us(frames); + // The file the cues are timed against, when there is one on this timeline. + // A track whose media has since been dropped from the project has no span + // to be carried through and falls back to the timeline's clock, which is + // what it was drawn on. + // + // Through the same `canonical` a source is indexed by, or the two spellings + // of one file (an argv `../assets/film.mkv`, a symlinked folder) would read + // as two files and the cues would quietly fall back to the timeline's clock. + let source = track.track.and_then(|_| { + let path = crate::project::canonical(&track.path); + project.sources().iter().position(|s| s.path == path) + }); + let Some(source) = source else { + return track + .cues + .iter() + .filter_map(|cue| { + let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end)); + (end_us > start_us).then(|| Cue { + start_us, + end_us, + text: cue.text.clone(), + }) + }) + .collect(); + }; + let mut out = Vec::new(); + for span in project.composite_spans_from(0) { + let Some((_, in_frame)) = span.from.filter(|&(from, _)| from == source) else { + continue; + }; + // What of the file this span plays, as *time in the file*: a clip counts + // the timeline's frames whatever its file was shot at ([`Rate`]), which + // is what makes those frames the same seconds a cue is timed in. + let (first, last) = (us(in_frame), us(in_frame + span.source_len())); + // Where that lands, and how fast: a cue is carried by the same factor + // the pictures under it are, so a slowed clip stretches its subtitles + // with it instead of leaving them behind. + let start = us(span.start); + let onto = |t: i64| start + ((t - first) as f64 / span.speed.as_f64()).round() as i64; + for cue in &track.cues { + let (a, b) = (cue.start_us.max(first), cue.end_us.min(last)); + if b <= a { + continue; // wholly outside what this span kept + } + out.push(Cue { + start_us: onto(a), + end_us: onto(b).min(end), + text: cue.text.clone(), + }); + } + } + // The spans come in timeline order but a cue's *own* order across them does + // not: a Matroska muxer writes blocks as they come up. + out.sort_by_key(|cue| cue.start_us); + 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); + } + 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(), + } +} + /// What [`start`] would encode the picture with, probed the way the export /// probes it -- the very encoder is opened and closed again -- so this is a /// measurement and not a promise. `None` for a format that carries no picture. @@ -770,6 +911,10 @@ fn run( // Taken by the Matroska muxer at creation; the mp4 one writes its track // after the picture, so for that path this is still `Some` at the end. let mut packets = audio.map(|track| track.packets); + // ...and the cues with them, for the same reason: the subtitle track is + // declared in the header and its blocks are interleaved into the clusters, + // so the muxer needs the lot before the first picture is written. + let mut subs = export_subtitles(project, meta, settings); // One header parse per source, before any of them is decoded: what rate // each file was shot at against the timeline's ([`Rate`]), which is how the @@ -918,6 +1063,7 @@ fn run( settings, audio_params.as_ref(), &mut packets, + &mut subs, au, key, )?; @@ -938,6 +1084,7 @@ fn run( settings, audio_params.as_ref(), &mut packets, + &mut subs, au, key, )?; @@ -1232,6 +1379,7 @@ fn write_video( settings: &ExportSettings, audio: Option<&AudioParams>, packets: &mut Option>, + subs: &mut Option, au: &[u8], key: bool, ) -> crate::Result<()> { @@ -1259,6 +1407,7 @@ fn write_video( hvcc: &hvcc, }, sound, + subs.take(), )?)) else { unreachable!("just inserted a Matroska muxer") }; @@ -1315,6 +1464,7 @@ fn write_video( out, ¶ms(meta, au)?, sound, + subs.take(), )?)) else { unreachable!("just inserted a Matroska muxer") }; @@ -1969,6 +2119,102 @@ impl SwDecoder { mod tests { use super::*; + /// A track of three cues, in whichever clock `track` says: `Some(n)` is a + /// track of the media file, `None` a `.srt` beside it. + fn subtitles(path: &str, track: Option) -> SubtitleTrack { + SubtitleTrack { + path: path.into(), + track, + label: "eng".into(), + cues: vec![ + Cue { + start_us: 500_000, + end_us: 1_500_000, + text: "first".into(), + }, + Cue { + start_us: 2_000_000, + end_us: 3_250_000, + text: "second".into(), + }, + Cue { + start_us: 4_000_000, + end_us: 4_750_000, + text: "third".into(), + }, + ], + refused: None, + } + } + + /// A standalone subtitle file is timed against the timeline itself -- there + /// is no clip to hang it on -- so a cut moves the pictures and not it. What + /// it does get is the exported length: a cue past the end of the file would + /// otherwise be a block after the last picture. + /// + /// The pair of this, the embedded clock, is measured against a real exported + /// file in `tests/export_subs.rs`; both live in one function and this is the + /// half that needs no encoder. + #[test] + fn a_subtitle_file_beside_the_media_keeps_the_timelines_own_clock() { + // 5 seconds at 30, with `[0.5s, 2.5s)` cut out of it: 3 seconds left. + let mut project = Project::single("/nonexistent/film.mp4", 150); + let track = subtitles("/nonexistent/film.srt", None); + assert!(project.ripple_delete(15, 60)); + assert_eq!(project.timeline_frames(), 90); + let cues = timeline_cues(&project, &track, 30.0); + assert_eq!( + cues, + vec![ + Cue { + start_us: 500_000, + end_us: 1_500_000, + text: "first".into() + }, + // Clipped to the three seconds the export writes... + Cue { + start_us: 2_000_000, + end_us: 3_000_000, + text: "second".into() + }, + // ...and the one wholly past the end is not written at all. + ] + ); + // A track *of a file* the project no longer plays has no span to be + // carried through either, so it falls back to the same clock rather + // than exporting nothing. + let orphan = subtitles("/nonexistent/other.mkv", Some(2)); + assert_eq!(timeline_cues(&project, &orphan, 30.0).len(), 2); + } + + /// The embedded clock, without an encoder in it: the cut moves the cues with + /// the pictures, and a cue nothing clipped keeps its own microseconds. + #[test] + fn a_track_of_the_media_is_carried_through_the_cut() { + let mut project = Project::single("/nonexistent/film.mkv", 150); + let track = subtitles("/nonexistent/film.mkv", Some(2)); + assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out"); + let cues = timeline_cues(&project, &track, 30.0); + assert_eq!( + cues, + vec![ + // The first cue was wholly inside the cut. The second straddled + // its far edge and kept the 0.75s that is still there... + Cue { + start_us: 500_000, + end_us: 1_250_000, + text: "second".into() + }, + // ...and the third simply moves back the two seconds that went. + Cue { + start_us: 2_000_000, + end_us: 2_750_000, + text: "third".into() + }, + ] + ); + } + #[test] fn bitrate_clamps_at_both_ends() { let meta = |width, height, frame_rate| VideoMeta { diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 6d6db49..e6539c0 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -482,6 +482,11 @@ const CODEC_DELAY: u32 = 0x56AA; const CLUSTER: u32 = 0x1F43_B675; const CLUSTER_TIMESTAMP: u32 = 0xE7; const SIMPLE_BLOCK: u32 = 0xA3; +const TRACK_NAME: u32 = 0x536E; +const TRACK_LANGUAGE: u32 = 0x22B59C; +const BLOCK_GROUP: u32 = 0xA0; +const BLOCK: u32 = 0xA1; +const BLOCK_DURATION: u32 = 0x9B; /// One millisecond, the tick every Matroska muxer writes and this one's block /// timestamps are in. The *rate* is not derived from these -- `DefaultDuration` @@ -532,6 +537,34 @@ 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 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, + /// 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. +struct MkvSubs { + cues: Vec, + /// Cues already written. + next: usize, +} + /// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC /// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the /// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what @@ -562,6 +595,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 sound waiting to be interleaved into the clusters. @@ -588,6 +624,7 @@ impl MkvMuxer { path: &Path, video: &Av1Params, audio: Option<(&AudioParams, Vec)>, + subs: Option, ) -> crate::Result { if video.config.is_empty() { return Err("no AV1 sequence header for the track's CodecPrivate".into()); @@ -602,6 +639,7 @@ impl MkvMuxer { b"V_AV1", &av1c, audio, + subs, ) } @@ -616,6 +654,7 @@ impl MkvMuxer { path: &Path, video: &HevcParams, audio: Option<(&AudioParams, Vec)>, + subs: Option, ) -> crate::Result { if video.hvcc.is_empty() { return Err("no hvcC record for the track's CodecPrivate".into()); @@ -628,9 +667,11 @@ impl MkvMuxer { b"V_MPEGH/ISO/HEVC", video.hvcc, audio, + subs, ) } + #[allow(clippy::too_many_arguments)] fn open( path: &Path, width: u32, @@ -639,6 +680,7 @@ impl MkvMuxer { codec_id: &[u8], codec_private: &[u8], audio: Option<(&AudioParams, Vec)>, + subs: Option, ) -> crate::Result { if !frame_rate.is_finite() || frame_rate <= 0.0 { return Err(format!("bad frame rate {frame_rate}").into()); @@ -697,6 +739,12 @@ 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)); + } elem(&mut head, TRACKS, &tracks); let mut file = File::create(path)?; @@ -715,6 +763,10 @@ impl MkvMuxer { samples: 0, sample_rate: params.sample_rate.max(1), }), + subs: subs.map(|subs| MkvSubs { + cues: subs.cues, + next: 0, + }), }) } @@ -742,8 +794,10 @@ impl MkvMuxer { uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); } // The sound this picture plays under goes in first, into the cluster the - // picture opened: a player reads the two together. + // picture opened: a player reads the two together. The cue over it with + // them, for the same reason. self.drain_audio(ts)?; + self.drain_subs(ts)?; self.block(1, ts, key, obus); self.frames += 1; Ok(()) @@ -784,6 +838,41 @@ impl MkvMuxer { } } + /// Every cue that has come up by `until`, into the current cluster -- + /// [`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. + 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); + } + self.block_group(SUB_TRACK, ts, ms, text.as_bytes()); + } + } + /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC /// packet is a keyframe; a picture is one when the encoder said so. fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) { @@ -795,6 +884,24 @@ impl MkvMuxer { elem(&mut self.cluster, SIMPLE_BLOCK, &block); } + /// One `BlockGroup`: a `Block` and the `BlockDuration` beside it. That pair + /// is how a cue says when it goes away -- a `SimpleBlock` has nowhere to put + /// a duration, and a subtitle without one stays up until whatever a player + /// decides, which is what a subtitle must never do. + fn block_group(&mut self, track: u8, ts: i64, duration_ms: u64, payload: &[u8]) { + let mut block = Vec::with_capacity(payload.len() + 4); + block.push(0x80 | track); // the track number as a one-byte EBML integer + block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes()); + // No flags a text block can carry: not lacing, and "keyframe" is a + // `SimpleBlock` field that a plain `Block` does not have at all. + block.push(0); + block.extend_from_slice(payload); + let mut group = Vec::new(); + elem(&mut group, BLOCK, &block); + uint(&mut group, BLOCK_DURATION, duration_ms); + elem(&mut self.cluster, BLOCK_GROUP, &group); + } + fn flush(&mut self) -> crate::Result<()> { if self.cluster.is_empty() { return Ok(()); @@ -814,6 +921,7 @@ impl MkvMuxer { // Whatever sound outlasts the last picture, before the last cluster is // closed: a track cut short here is a file that goes silent at the end. self.drain_audio(i64::MAX)?; + self.drain_subs(i64::MAX)?; self.flush()?; if self.frames == 0 { return Err("no frames were written to the Matroska file".into()); @@ -878,6 +986,36 @@ 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; + +/// 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 { + 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_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) => {} + } + entry +} + /// The sequence header OBU of a coded temporal unit, for the track's /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe /// of a stream never may -- no decoder can start without it. @@ -1444,6 +1582,7 @@ mod tests { }, packets, )), + None, ) .unwrap(); // Half a second of picture under a second of sound: the tail of the @@ -1571,6 +1710,7 @@ mod tests { config, }, None, + None, ) .unwrap(); muxer.write_frame(&key, true).unwrap(); @@ -1614,6 +1754,7 @@ mod tests { config: &[], }, None, + None, ) .is_err() ); diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 1f6154e..909c764 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -752,6 +752,14 @@ impl PlaybackSession { crate::export::planned_audio(&self.project, format) } + /// What an export would do about the subtitle track at `pick` -- + /// [`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) + } + /// Why the sound's rate is not a choice for this timeline in this format -- /// [`crate::export::audio_rate_refusal`], asked of the project a front-end /// is holding, and pure for the same reason. diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index b9e6774..a04063d 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -3063,7 +3063,7 @@ fn open_room(clips: &mut Vec, at: u32, len: u32) { /// Absolute, symlink-resolved when the file is reachable; the path as given /// when it is not -- an unreadable path still deserves an index, it simply /// dedups by spelling. -fn canonical(path: &Path) -> PathBuf { +pub(crate) fn canonical(path: &Path) -> PathBuf { std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) } diff --git a/crates/engine/tests/export_subs.rs b/crates/engine/tests/export_subs.rs new file mode 100644 index 0000000..7c977b7 --- /dev/null +++ b/crates/engine/tests/export_subs.rs @@ -0,0 +1,295 @@ +//! 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. +//! +//! Two witnesses for every cue: this project's own Matroska reader +//! (`demux::matroska_subtitles`, the way an exported file comes back into a +//! project) and, where the box has it, ffmpeg -- which is what "it plays +//! elsewhere" means and the only thing that can say this file is not merely +//! self-consistent. +//! +//! ```text +//! cargo test -p engine --release --test export_subs -- --nocapture +//! ``` + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::Once; +use std::time::{Duration, Instant}; + +use engine::export::{ExportSettings, Format}; +use engine::project::Lane; +use engine::subtitle::{self, Cue, SubtitleTrack}; +use engine::{ExportHandle, Project}; + +/// The media fixture: five seconds at 30 fps, and a picture this box can decode +/// with nothing installed. +const MEDIA: &str = "test_av.mp4"; +const FRAMES: u32 = 150; +/// What a cue may be out by: the file's own tick, a millisecond. The mapping is +/// exact microseconds -- only the write rounds -- so nothing wider than this is +/// being allowed for. +const SLACK_US: i64 = 1_000; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn out_path(name: &str) -> PathBuf { + let path = + std::env::temp_dir().join(format!("ve_subs_export_{name}_{}.mkv", std::process::id())); + let _ = std::fs::remove_file(&path); + path +} + +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") +} + +/// The three cues the subtitle fixtures hold (`tests/subtitles.rs` pins them +/// against the real `.srt`, `.ass` and `.mkv`), on a timeline of the media they +/// are timed against. +/// +/// The track says it came out of *this* media file, which is what an embedded +/// track is and what makes its cues the file's own clock rather than the +/// timeline's. Written out here rather than read out of `test_subs.mkv` because +/// that fixture's picture is AV1 and there is no software AV1 decoder to export +/// it through; the cues are the same three either way. +fn track() -> SubtitleTrack { + SubtitleTrack { + path: asset(MEDIA), + track: Some(2), + label: "eng".into(), + cues: vec![ + Cue { + start_us: 500_000, + end_us: 1_500_000, + text: "first line".into(), + }, + Cue { + start_us: 2_000_000, + end_us: 3_250_000, + text: "second line\nwith a break".into(), + }, + Cue { + start_us: 4_000_000, + end_us: 4_750_000, + text: "third line".into(), + }, + ], + refused: None, + } +} + +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) -> (PathBuf, Vec) { + pin_software(); + let out = out_path(name); + 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: pick, + ..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()) + } + } +} + +/// 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 { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-map", "0:s:0", "-f", "srt", "-"]) + .output() + .ok()?; + assert!( + out.status.success(), + "ffmpeg refused the exported subtitles: {}", + String::from_utf8_lossy(&out.stderr) + ); + Some(String::from_utf8_lossy(&out.stdout).into_owned()) +} + +fn near(got: i64, want: i64, what: &str) { + assert!( + (got - want).abs() <= SLACK_US, + "{what}: {got} us is not within a frame of {want} us" + ); +} + +/// The whole timeline, untouched: the file comes back with the very cues the +/// source's track holds, at the times it holds them -- and ffmpeg reads the +/// same three lines out of it. +#[test] +fn an_mkv_export_carries_the_picked_subtitle_track() { + let (out, cues) = exported("plain", project(), Some(0)); + assert_eq!(cues.len(), 3, "three cues: {cues:?}"); + let want = [ + (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"), + ]; + for (cue, (start, end, text)) in cues.iter().zip(want) { + near(cue.start_us, start, "cue start"); + near(cue.end_us, end, "cue end"); + assert_eq!(cue.text, text, "the text travels, line breaks and all"); + } + // ...and the track is named the way it was named in the source, so the + // subtitle menu of whatever plays this says `eng` too. + let tracks = subtitle::of_matroska(&out).expect("read back"); + assert_eq!(tracks[0].label, "eng"); + let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element"); + 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) { + Some(srt) => { + println!("ffmpeg reads the exported track back as:\n{srt}"); + assert!(srt.contains("first line"), "{srt}"); + assert!(srt.contains("with a break"), "{srt}"); + assert!(srt.contains("00:00:00,500 --> 00:00:01,500"), "{srt}"); + assert!(srt.contains("00:00:04,000 --> 00:00:04,750"), "{srt}"); + } + None => println!("no ffmpeg on this box: our own reader is the only witness"), + } + std::fs::remove_file(&out).unwrap(); +} + +/// A cut timeline: `[0.5s, 2.5s)` rippled out of it, which is one cue gone +/// entirely, one that straddles the far edge and keeps the half still there, +/// and one that simply moves back with the picture. +#[test] +fn a_cut_moves_the_cues_with_the_pictures() { + let mut project = project(); + assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out"); + assert_eq!(project.timeline_frames(), 90, "three seconds are left"); + assert_eq!( + project.lane(Lane::V1).len(), + 2, + "the hole closed, over two placements of the one source" + ); + + let (out, cues) = exported("cut", project, Some(0)); + assert_eq!( + cues.len(), + 2, + "the cue inside the cut is gone, the other two are not: {cues:?}" + ); + // 2.0s..3.25s of the source, of which 2.5s on survived, landing where the + // cut left it: 0.5s..1.25s. + near( + cues[0].start_us, + 500_000, + "the straddling cue starts at the cut", + ); + near( + cues[0].end_us, + 1_250_000, + "...and keeps the rest of its length", + ); + assert_eq!(cues[0].text, "second line\nwith a break"); + // 4.0s..4.75s of the source, two seconds back. + near( + cues[1].start_us, + 2_000_000, + "the last cue moves back by the cut", + ); + 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) { + println!("ffmpeg reads the cut 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(); +} + +/// Nothing picked is nothing written -- the file every export of a timeline +/// without subtitles has always been. +#[test] +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()); + std::fs::remove_file(&out).unwrap(); +} + +/// What the card says before the button is pressed, which is where an mp4's +/// refusal has to land: the file is not the place to find out. +#[test] +fn the_plan_says_what_each_container_does_with_them() { + let project = project(); + 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"); + 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. + assert_eq!( + engine::export::planned_subtitles(&project, Format::Hevc, None), + "none" + ); + assert_eq!( + engine::export::planned_subtitles(&project, Format::Hevc, Some(9)), + "none" + ); + // 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" + ); +}