From f4b5fd8bc8492921e38552c1ebbdf97ab3b1eae6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 11 Aug 2026 08:24:27 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20subtitles=20come=20?= =?UTF-8?q?in=20with=20the=20film=20or=20beside=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A subtitle track was a track this engine walked past: the Matroska track walk kept video and audio and dropped type 0x11, and a `.srt` next to the media was a file with no door. Now both arrive as the same thing -- a list of timed cues -- and a project keeps them. `subtitle`: the cue model plus the two ways in. Standalone `.srt`, `.vtt` and `.ass`/`.ssa` go through `oxideav-subtitle` and `oxideav-ass` rather than through a fresh parser here; an embedded track carries its timing on the block and its text in it, so each codec is put back into the shape its own parser reads -- which is what makes an embedded track and the file it was muxed from come back as the same cues. What cannot be read is refused by name and still listed: the four PGS tracks of a BluRay remux are four rows saying they are pictures, not an empty list and not a file that would not open. A `.srt` that has gone missing since the save is the same story, and a re-save keeps its row. `.edith` 10 writes `subtitle ` -- the reference only, the cues stay in the file they came from. v9 and every older dialect load as the projects with no subtitles that they are. --- Cargo.lock | 89 +++++++ crates/engine/Cargo.toml | 10 + crates/engine/src/demux.rs | 210 +++++++++++++++ crates/engine/src/edith.rs | 191 ++++++++++++-- crates/engine/src/lib.rs | 1 + crates/engine/src/playback.rs | 57 +++- crates/engine/src/project.rs | 38 +++ crates/engine/src/subtitle.rs | 344 +++++++++++++++++++++++++ crates/engine/tests/data/test_subs.ass | 14 + crates/engine/tests/data/test_subs.srt | 12 + crates/engine/tests/saveload.rs | 14 +- crates/engine/tests/silence.rs | 3 +- crates/engine/tests/subtitles.rs | 237 +++++++++++++++++ scripts/gen_fixtures.sh | 18 ++ 14 files changed, 1205 insertions(+), 33 deletions(-) create mode 100644 crates/engine/src/subtitle.rs create mode 100644 crates/engine/tests/data/test_subs.ass create mode 100644 crates/engine/tests/data/test_subs.srt create mode 100644 crates/engine/tests/subtitles.rs diff --git a/Cargo.lock b/Cargo.lock index bc63ce6..906603f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1003,6 +1003,12 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "compcol" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28b37ce533aa0fddc1e6820e331968ba72aa48b5c8bbb2bebdc03d48b6ed0f16" + [[package]] name = "compression-codecs" version = "0.4.38" @@ -1636,8 +1642,10 @@ dependencies = [ "libloading", "mp4", "oxideav-ac3", + "oxideav-ass", "oxideav-core", "oxideav-h265", + "oxideav-subtitle", "rav1e", "rusty_aac", "rusty_h264", @@ -3940,6 +3948,16 @@ dependencies = [ "oxideav-core", ] +[[package]] +name = "oxideav-ass" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d5a10750f54eb6913bf3ca295d17899006c9a9c6c94970741a5a7c0c49e3fa" +dependencies = [ + "oxideav-core", + "oxideav-subtitle", +] + [[package]] name = "oxideav-core" version = "0.1.34" @@ -3958,6 +3976,77 @@ dependencies = [ "oxideav-core", ] +[[package]] +name = "oxideav-otf" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "571c56414ce3138d3a4e7c833b402b3c69a96db707f54abd0f1ad85f3d5d1a0b" +dependencies = [ + "oxideav-core", +] + +[[package]] +name = "oxideav-pixfmt" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "868d5cd1d9cf3f4d527241b6ed85fcd628c65e303fe4efb2998e4d6104c7ce4b" +dependencies = [ + "oxideav-core", +] + +[[package]] +name = "oxideav-png" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c78483db4263204f6f9e2e63354b45f0fe2f83e0e08282f68c8a9647d537fa1f" +dependencies = [ + "compcol", + "oxideav-core", +] + +[[package]] +name = "oxideav-raster" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41beead01c28b23e6e997e8b2d3a38bb1b53cd37b6e8a72a10befa2fb57a6e06" +dependencies = [ + "oxideav-core", + "oxideav-pixfmt", +] + +[[package]] +name = "oxideav-scribe" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9aec36b356861de9e0e660a7990f14b428476638f7b2ba902c0cd7e1ffdac39" +dependencies = [ + "oxideav-core", + "oxideav-otf", + "oxideav-png", + "oxideav-ttf", +] + +[[package]] +name = "oxideav-subtitle" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88e41289024a95ea82051cd18af77885afd7be3c23a38255cb1edbe49872273a" +dependencies = [ + "oxideav-core", + "oxideav-pixfmt", + "oxideav-raster", + "oxideav-scribe", +] + +[[package]] +name = "oxideav-ttf" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c44d45518f6f4d749d2bf2c7cb3622fdb7ccc6147457545ed36aa8d241adea8e" +dependencies = [ + "oxideav-core", +] + [[package]] name = "parking" version = "2.2.1" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 418d61b..959a6c3 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -66,6 +66,16 @@ symphonia = { version = "0.6", default-features = false, features = [ ] } oxideav-ac3 = "=0.0.10" oxideav-core = "0.1.34" +# The subtitle parsers: SRT and WebVTT here, ASS/SSA in the sibling crate -- +# `oxideav-subtitle` hosts the shared IR and hands ASS to `oxideav-ass`, which +# is why both names are needed for the three formats. MIT, pure Rust, and both +# asked for without their default features: nothing here *draws* a cue yet (see +# `crate::subtitle`), so the rendering stacks are dead weight. Only `oxideav-ass` +# actually loses one -- it depends on `oxideav-subtitle` with defaults on, so +# that crate's `text` feature (the bitmap font and rasterizer) is unified back +# in whatever this line says. Nothing here calls into it. +oxideav-subtitle = { version = "0.1.2", default-features = false } +oxideav-ass = { version = "0.0.9", default-features = false } # The software AV1 encoder, and the only new name in this list that was already # in the lock file: `ravif` pulls the very same rav1e 0.8.1 in through the image # crate, so this links what the build already compiled. BSD-2 with the AOM diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index caed1c6..c21ab6e 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -1138,6 +1138,216 @@ fn tkhd_track_id(payload: &[u8]) -> Option { )) } +/// One subtitle track of a Matroska file, exactly as its `TrackEntry` declares +/// it. What the cues *mean* is [`crate::subtitle`]'s business; this is the +/// walk, and it reads every track type 0x11 the file has -- including the ones +/// nothing here can render, which is how a caller names what it is leaving out +/// instead of quietly opening a film with no subtitles in the list. +#[derive(Debug)] +pub struct MkvSubtitle { + pub number: u64, + /// The Matroska codec id: `S_TEXT/UTF8`, `S_TEXT/ASS`, `S_HDMV/PGS`, ... + pub codec: String, + /// `Language`, ISO-639-2, `und` when the file says nothing. + pub language: String, + /// `Name`, the human label a muxer wrote, often empty. + pub name: String, + /// `CodecPrivate`: the ASS script header (`[Script Info]` through the + /// `[Events]` `Format:` line) for `S_TEXT/ASS`, empty for `S_TEXT/UTF8`. + pub private: Vec, + /// Every cue block, in storage order -- but only for the `S_TEXT/*` codecs. + /// A bitmap track (PGS, VobSub) comes back declared and empty: its blocks + /// are megabytes of pictures, and nothing here can draw one. + pub cues: Vec, +} + +/// One subtitle block: when it shows and the bytes it shows. +#[derive(Debug)] +pub struct MkvCue { + /// Microseconds from the start of the file -- the block timestamp scaled by + /// the segment's `TimestampScale`, which is the unit + /// [`crate::subtitle::Cue`] keeps. + pub start_us: i64, + /// `BlockDuration`, microseconds. `None` for a block that declares none, + /// which leaves how long the cue stays up to the caller. + pub duration_us: Option, + /// The block's own bytes: the text for `S_TEXT/UTF8`, the comma-separated + /// `Dialogue` fields (`ReadOrder` first, no timing) for `S_TEXT/ASS`. + pub payload: Vec, +} + +/// 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`]. +/// +/// 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. +pub fn matroska_subtitles(path: &Path) -> crate::Result> { + let mut file = File::open(path)?; + let end = file.metadata()?.len(); + let segment = mkv_segment(&mut file, end)?; + let mut tracks: Vec = Vec::new(); + let mut timestamp_scale = 1_000_000; + let mut at = segment.0; + while let Some((id, body, stop)) = ebml_element(&mut file, at, segment.1)? { + match id { + CLUSTER => break, + INFO => { + let mut at = body; + while let Some(e) = ebml_element(&mut file, at, stop)? { + if e.0 == TIMESTAMP_SCALE { + timestamp_scale = ebml_uint(&mut file, e.1, e.2)?.max(1); + } + at = e.2; + } + } + TRACKS => { + let mut at = body; + while let Some(e) = ebml_element(&mut file, at, stop)? { + if e.0 == TRACK_ENTRY { + tracks.extend(mkv_subtitle_entry(&mut file, e.1, e.2)?); + } + at = e.2; + } + } + _ => {} + } + at = stop; + } + // The text tracks only: see `MkvSubtitle::cues`. + let wanted: Vec = tracks + .iter() + .filter(|t| t.codec.starts_with("S_TEXT")) + .map(|t| t.number) + .collect(); + if !wanted.is_empty() { + mkv_subtitle_blocks(&mut file, segment, timestamp_scale, &wanted, &mut tracks)?; + } + Ok(tracks) +} + +/// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles. +fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result> { + const TRACK_LANGUAGE: u32 = 0x22B59C; + const TRACK_NAME: u32 = 0x536E; + 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 at = body; + while let Some((id, body, stop)) = ebml_element(file, at, end)? { + match id { + TRACK_NUMBER => number = ebml_uint(file, body, stop)?, + TRACK_TYPE => kind = ebml_uint(file, body, stop)?, + CODEC_ID => codec = string_of(file, body, stop)?, + CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?, + TRACK_LANGUAGE => language = string_of(file, body, stop)?, + TRACK_NAME => name = string_of(file, body, stop)?, + _ => {} + } + at = stop; + } + Ok((kind == SUBTITLE).then(|| MkvSubtitle { + number, + codec, + // What a `TrackEntry` without a `Language` element means, by spec. + language: if language.is_empty() { + "und".into() + } else { + language + }, + name, + private, + cues: Vec::new(), + })) +} + +/// Every block of the `wanted` tracks, appended to their entries in `tracks`. +/// +/// A second cluster walk rather than a widening of [`mkv_blocks`]: that one +/// indexes *one* video track and reads no payloads, and a subtitle needs every +/// track at once, the bytes, and the `BlockDuration` beside them. +fn mkv_subtitle_blocks( + file: &mut File, + segment: (u64, u64), + timestamp_scale: u64, + wanted: &[u64], + tracks: &mut [MkvSubtitle], +) -> crate::Result<()> { + const BLOCK_DURATION: u32 = 0x9B; + // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is + // nanoseconds per tick and is a millisecond in every file anything writes. + let us = |ticks: i64| ticks * timestamp_scale as i64 / 1_000; + let mut at = segment.0; + while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { + at = stop; + if id != CLUSTER { + continue; + } + let mut cluster_ts = 0i64; + let mut child = body; + while let Some((id, body, stop)) = ebml_element(file, child, stop)? { + child = stop; + let (block, duration) = match id { + CLUSTER_TIMESTAMP => { + cluster_ts = ebml_uint(file, body, stop)? as i64; + continue; + } + SIMPLE_BLOCK => (mkv_block(file, body, stop)?, None), + BLOCK_GROUP => { + let (mut found, mut duration) = (None, None); + let mut child = body; + while let Some(e) = ebml_element(file, child, stop)? { + match e.0 { + BLOCK => found = Some(mkv_block(file, e.1, e.2)?), + BLOCK_DURATION => duration = Some(ebml_uint(file, e.1, e.2)? as i64), + _ => {} + } + child = e.2; + } + match found { + Some(block) => (block, duration), + None => continue, + } + } + _ => continue, + }; + if !wanted.contains(&block.number) { + continue; + } + // As for a video block: guessing at the boundaries inside a laced + // one is not something to do silently. No muxer laces subtitles. + if block.flags & 0x06 != 0 { + return Err("laced subtitle blocks are not supported".into()); + } + // A megabyte of *text* in one cue is a corrupt file, not a subtitle, + // and a crafted length may not reach an allocation through here. + if block.len > 1 << 20 { + return Err("a Matroska subtitle block larger than a megabyte".into()); + } + let mut payload = vec![0u8; block.len]; + read_exact_at(file, block.at, &mut payload)?; + let Some(track) = tracks.iter_mut().find(|t| t.number == block.number) else { + continue; + }; + track.cues.push(MkvCue { + start_us: us(cluster_ts + i64::from(block.rel)), + duration_us: duration.map(us), + payload, + }); + } + } + Ok(()) +} + +/// A string element, without the trailing NULs a `Name` may be padded with. +fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result { + let bytes = ebml_bytes(file, body, stop)?; + Ok(String::from_utf8_lossy(&bytes) + .trim_end_matches('\0') + .to_owned()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 52461ef..0a8890c 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -1,13 +1,15 @@ //! The project file: a line of text per thing, and nothing else. //! //! ```text -//! edith 9 +//! edith 10 //! playhead 90 //! resolution 1920 1080 //! fps 30.0 //! limiter -1.0 on //! source 0 test_av.mp4 //! source 1 /elsewhere/test_av2.mp4 +//! subtitle - subs.srt +//! subtitle 3 test_av.mp4 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk //! color 0.1:1.2:0.9:-0.3 //! video 1 0 0 120 0 0 0 0 fit 1000 @@ -23,6 +25,15 @@ //! is an answer only a project holding a video has //! ([`crate::PlaybackSession::open_project`]). //! +//! A `subtitle` line is `subtitle `: which track of that file the +//! cues are in -- a Matroska track number, or `-` when the path *is* a subtitle +//! file ([`crate::subtitle`]) -- and then the path, last and escaped for the +//! reason a source's is. Only the reference is written: the cues themselves are +//! read back out of the file on the way in, exactly as a clip's pictures are, so +//! a project file stays an edit list. A subtitle file that has gone missing +//! since the save comes back listed and refused by name rather than dropped, +//! which is what keeps a re-save from losing it. +//! //! The `limiter` line is the master limiter over the whole mix //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit, //! spelled `on` or `off`. Left out when it is the default, which is off. @@ -79,7 +90,9 @@ //! is the only way an empty lane could still be there on the way back. A lane //! number may not skip one of its kind. //! -//! **Version 8** was this without the `fps` and `limiter` lines and without +//! **Version 9** was this without the `subtitle` lines: such a project shows no +//! subtitles, which is all any project could do. +//! **Version 8** was that without the `fps` and `limiter` lines and without //! the `gain` ones: such a project mixes every lane at unity, limits nothing, //! and comes back at the rate its scaffolding source runs at. //! **Version 7** was that without the clip's speed field -- every clip of such @@ -97,8 +110,8 @@ //! cumulatively and copied onto both lanes as one group each, which is exactly //! what a v1 timeline meant, and an older file simply equalizes and grades //! nothing, and an older one plays everything at real time, and an older one -//! mixes flat -- and saving any of them writes v9. An older reader refuses a -//! newer file by name. +//! mixes flat, and an older one shows no subtitles -- and saving any of them +//! writes v10. An older reader refuses a newer file by name. //! //! Text because an edit list is a few integers and a path, and a path is //! *bytes* on this platform -- a JSON string would have to lossily decode one. @@ -129,10 +142,12 @@ use crate::eq::{Band, BandKind, EqParams}; use crate::limiter::Limiter; use crate::project::{Clip, Lane, LaneKind, Source, Speed}; use crate::scale::FitPolicy; +use crate::subtitle::SubtitleTrack; /// What [`save`] writes. Read support goes back to `edith 1`; see the module /// docs for what those dialects looked like. -const MAGIC: &[u8] = b"edith 9"; +const MAGIC: &[u8] = b"edith 10"; +const MAGIC_V9: &[u8] = b"edith 9"; const MAGIC_V8: &[u8] = b"edith 8"; const MAGIC_V7: &[u8] = b"edith 7"; const MAGIC_V6: &[u8] = b"edith 6"; @@ -169,6 +184,11 @@ pub struct Document { /// The master limiter. Off for every dialect before v9, and for a v9 file /// that leaves the line out. pub limiter: Limiter, + /// The subtitle tracks, as the file names them: the path the cues are in + /// and which track of it, which is what [`crate::subtitle::open`] takes. + /// Reading them is the loader's business, not this module's -- a `.edith` + /// holds no cues. Empty for every dialect before v10. + pub subtitles: Vec<(PathBuf, Option)>, /// The timeline's frame rate. `None` for every dialect before v9 and for a /// v9 file that leaves it out, which both mean "whatever the scaffolding /// source runs at" -- the inference a project of nothing but stills and @@ -188,6 +208,7 @@ pub fn save( sources: &[Source], lanes: &[(LaneKind, Vec)], gains: &[f32], + subtitles: &[SubtitleTrack], eq: &[EqParams], color: &[ColorParams], resolution: (u32, u32), @@ -206,7 +227,8 @@ pub fn save( let result = std::fs::File::create(&part) .and_then(|mut f| { f.write_all(&emit( - &dir, sources, lanes, gains, eq, color, resolution, fps, limiter, playhead, + &dir, sources, lanes, gains, subtitles, eq, color, resolution, fps, limiter, + playhead, ))?; f.sync_all() }) @@ -243,6 +265,7 @@ fn emit( sources: &[Source], lanes: &[(LaneKind, Vec)], gains: &[f32], + subtitles: &[SubtitleTrack], eq: &[EqParams], color: &[ColorParams], resolution: (u32, u32), @@ -280,6 +303,16 @@ fn emit( escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out); out.push(b'\n'); } + // The subtitle tracks, by reference: which track of which file, and never + // the cues (see the module docs). Beside the sources because that is what + // they are -- a file this project reads from -- although nothing indexes + // them and their order is only the order they were added in. + for t in subtitles { + let track = t.track.map_or("-".to_string(), |n| n.to_string()); + out.extend_from_slice(format!("subtitle {track} ").as_bytes()); + escape(t.path.strip_prefix(dir).unwrap_or(&t.path), &mut out); + out.push(b'\n'); + } // Before the clips, for the reason the sources are: a clip names one by the // position of its line, so the line has to be there first. for params in eq { @@ -379,9 +412,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // The dialects that wrote a source line without its stream field. Reading // one is the whole of what "an old project still opens" means here. let streamless = v1 || first == MAGIC_V2; - // The one that carries the mix -- lane volumes, the master limiter and the - // rate the timeline was cut at... - let v9 = first == MAGIC; + // The one that carries subtitle tracks... + let v10 = first == MAGIC; + // ...the ones that carry the mix -- lane volumes, the master limiter and + // the rate the timeline was cut at... + let v9 = v10 || first == MAGIC_V9; // ...the ones that carry a per-clip speed... let v8 = v9 || first == MAGIC_V8; // ...the ones that carry a project resolution and per-clip fit policies... @@ -418,6 +453,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // ...and nothing before v9 carries a mix or a rate: every lane at unity, // no limiter, and the rate inferred from the scaffold as it always was. gains: Vec::new(), + // Nothing before v10 shows a subtitle. + subtitles: Vec::new(), limiter: Limiter::default(), fps: None, playhead: 0, @@ -528,6 +565,31 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { doc.gains.resize(doc.lanes.len(), 0.0); doc.gains[at] = float(f[2], n)?; } + // Beside the source lines and read the same way: fields first, the + // path last, because a path runs to the end of the line. + b"subtitle" if v10 => { + let at = rest + .iter() + .position(|&b| b == b' ') + .ok_or_else(|| format!("line {n}: subtitle without a path"))?; + let track = match &rest[..at] { + b"-" => None, + field => Some(u64::from(number(field, n)?)), + }; + let path = unescape(&rest[at + 1..], n)?; + if path.as_os_str().is_empty() { + return Err(format!("line {n}: subtitle without a path").into()); + } + doc.subtitles.push(( + // Relative to the project file, as a source path is. + if path.is_absolute() { + path + } else { + dir.join(path) + }, + track, + )); + } b"source" => { if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { return Err(format!("line {n}: source after a clip").into()); @@ -963,6 +1025,7 @@ mod tests { sources, lanes, &[], + &[], eq, color, resolution, @@ -972,6 +1035,84 @@ mod tests { ) } + /// A subtitle track as a save hands one over: the cues are not written and + /// so are not here either. + fn subtitle(path: &str, track: Option) -> SubtitleTrack { + SubtitleTrack { + path: PathBuf::from(path), + track, + label: String::new(), + cues: Vec::new(), + refused: None, + } + } + + /// The v10 line: which track of which file, written beside the sources and + /// read back as the pair a load opens. And what a v9 file is -- one with no + /// subtitles at all, which still opens and re-saves as v10. + #[test] + fn subtitles_round_trip_as_references_and_a_v9_file_has_none() { + let dir = PathBuf::from("/proj"); + let (_, sources, lanes) = doc(); + let tracks = [ + subtitle("/proj/subs.srt", None), + subtitle("/proj/a.mp4", Some(3)), + subtitle("/elsewhere/od d name.ass", None), + ]; + let bytes = super::emit( + &dir, + &sources, + &lanes, + &[], + &tracks, + &[], + &[], + (1280, 720), + None, + Limiter::default(), + 0, + ); + let text = String::from_utf8_lossy(&bytes); + assert!( + text.contains( + "subtitle - subs.srt\n\ + subtitle 3 a.mp4\n\ + subtitle - /elsewhere/od d name.ass\n" + ), + "the path is relative where it can be, and runs to the end of its \ + line, spaces and all: {text}" + ); + let back = parse(&bytes, &dir).expect("v10 parses"); + assert_eq!( + back.subtitles, + vec![ + (PathBuf::from("/proj/subs.srt"), None), + (PathBuf::from("/proj/a.mp4"), Some(3)), + (PathBuf::from("/elsewhere/od d name.ass"), None), + ] + ); + + // A v9 file is a project with no subtitles, and re-saving it writes v10. + let v9 = b"edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000\n"; + let old = parse(v9, &dir).expect("v9 still loads"); + assert_eq!(old.subtitles, Vec::new()); + assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 10\n")); + // ...and the line itself is not a v9 line: a dialect may not be mixed. + let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir) + .unwrap_err() + .to_string(); + assert_eq!(mixed, "line 3: unknown keyword \"subtitle\""); + // A subtitle line with no path is refused, as a source with none is. + for line in ["subtitle -\n", "subtitle - \n", "subtitle x subs.srt\n"] { + let file = format!("edith 10\nsource 0 a.mp4\n{line}"); + assert!( + parse(file.as_bytes(), &dir).is_err(), + "{line:?} is not a subtitle line" + ); + } + } + fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option) -> Clip { Clip { start, @@ -1032,7 +1173,7 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 12); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n", @@ -1069,7 +1210,7 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 7); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", "an empty lane is a line of its own; everything else is its clips" @@ -1177,7 +1318,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 16777215.0:-0.1:3.918315e-39:hs\n\ eq\n\ @@ -1281,7 +1422,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ color 0.1:1.2:0.9:-0.3\n\ color -1e-7:16777215.0:3.918315e-39:-0.0\n\ color 0.0:1.0:1.0:0.0\n\ @@ -1346,7 +1487,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" ); @@ -1384,7 +1525,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ audio 1 0 0 30 0 - - - fit 2000\n", "the rate is the clip line's last field, in thousandths" @@ -1413,7 +1554,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" ); // A rate outside what the editor can set is a corrupt line, by name. @@ -1450,6 +1591,7 @@ mod tests { &[0.0, 3.0, -6.5], &[], &[], + &[], (1280, 720), Some(23.976023976023978), limiter, @@ -1457,7 +1599,7 @@ mod tests { ); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ limiter -1.5 on\nsource 0 a.mp4\n\ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\ audio 2 0 0 30 0 - - - fit 1000\n\ @@ -1489,7 +1631,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" ); @@ -1653,7 +1795,7 @@ mod tests { assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); assert_eq!( String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), - "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n" @@ -1706,7 +1848,7 @@ mod tests { let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); assert_eq!( String::from_utf8_lossy(&v5), - "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 0 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n", @@ -1738,7 +1880,7 @@ mod tests { // Saved again it is the current version, which round-trips to the // same document. let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); - assert!(v5.starts_with(b"edith 9\n")); + assert!(v5.starts_with(b"edith 10\n")); let again = parse(&v5, &dir).expect("v5 parses"); assert_eq!(again.lanes, back.lanes); // A dialect may not be mixed: lane lines under v1, `clip` under v2. @@ -1834,6 +1976,7 @@ mod tests { &[], &[], &[], + &[], (1280, 720), None, Limiter::default(), @@ -1843,7 +1986,7 @@ mod tests { let bytes = std::fs::read(&path).expect("read back"); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" ); // Loading rejoins the *given* directory, so the file is reached by the @@ -1888,10 +2031,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 10\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) + let err = parse(b"edith 11\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 10"); + assert_eq!(err, "line 1: unsupported version 11"); for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { assert_eq!( parse(junk, &dir).unwrap_err().to_string(), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index afca436..0e3a706 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -17,6 +17,7 @@ pub mod playback; pub mod project; pub mod scale; pub mod silence; +pub mod subtitle; pub mod waveform; pub use audio::{ diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 12b149d..c15aaac 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -673,8 +673,19 @@ impl PlaybackSession { } let playhead = doc.playhead; + // The subtitle files are read here rather than in the parser: a + // `.edith` names them and holds no cues. One that has gone missing, or + // whose track is a codec of pictures, comes back listed and refused by + // name ([`crate::subtitle::open`]) -- a project does not stop opening + // over a subtitle, and a re-save does not lose the row. + let subtitles = doc + .subtitles + .iter() + .map(|(path, track)| crate::subtitle::open(path, *track)) + .collect(); let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)? - .with_mix(&doc.gains, doc.limiter); + .with_mix(&doc.gains, doc.limiter) + .with_subtitles(subtitles); let span = project.composite_span_at(0); // Last, because it is the one thing here that cannot be taken back: the // feeder thread outlives the `Audio` value (it holds its own clones) and @@ -755,6 +766,47 @@ impl PlaybackSession { self.project.sources() } + /// The subtitle tracks on this timeline, in the order they were added: what + /// a front-end lists and what [`save_project`](Self::save_project) writes. + /// A track that could not be read is *in* this list, saying why + /// ([`crate::subtitle::SubtitleTrack::refused`]) -- listed and skipped, not + /// dropped. + pub fn subtitles(&self) -> &[crate::subtitle::SubtitleTrack] { + self.project.subtitles() + } + + /// Adds subtitles from `path`: every subtitle track of a Matroska file, or + /// the one track a standalone `.srt`/`.vtt`/`.ass` is. Hands back how many + /// were added -- 0 for a file whose tracks are all on the timeline already, + /// since importing the same file twice is the same subtitles. + /// + /// An error only when the file cannot be read *at all*; a track this cannot + /// parse is added refused by name, for the reason + /// [`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)?, + false => vec![crate::subtitle::open(path, None)], + }; + // A standalone file that could not be parsed is a refusal here rather + // than a row nobody asked for: the import is the moment to say so, and + // the load is the moment to keep it. + if let [one] = &tracks[..] + && one.track.is_none() + && let Some(why) = &one.refused + { + return Err(why.clone().into()); + } + Ok(tracks + .into_iter() + .filter(|t| self.project.add_subtitles(t)) + .count()) + } + /// Writes the timeline to `path` as a `.edith`, atomically (see /// [`crate::edith`]). Sources no clip plays from are left out, and the /// playhead is saved with it so a reopened project resumes where it stood. @@ -780,6 +832,9 @@ impl PlaybackSession { // project's, not this machine's (the monitoring volume is not // written and never will be). &self.project.lane_gains(), + // The subtitle tracks with them, by reference: which file the cues + // are in, never the cues (see [`crate::edith`]). + self.project.subtitles(), &eq, &color, (self.meta.width, self.meta.height), diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 818741e..b9e6774 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -68,6 +68,7 @@ use crate::color::ColorParams; use crate::eq::EqParams; use crate::limiter::{Limiter, db_to_linear}; use crate::scale::FitPolicy; +use crate::subtitle::SubtitleTrack; /// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]). /// -60 dB is a thousandth of the amplitude -- a track that is out of the mix @@ -618,6 +619,12 @@ pub struct Project { /// Never rolled back by an undo: an id retired by an undone split must not /// come back and group two clips that were never together. next_link: u32, + /// The subtitle tracks this timeline shows, in the order they were added. + /// Not in the lane list and not in the history snapshots, for the reason + /// the limiter is not: which subtitles a project carries is a setting on + /// it, and it is saved as a *reference* to the file the cues came out of + /// ([`crate::subtitle`]). + subtitles: Vec, /// The master limiter every lane's sound is summed *through* /// ([`Project::limiter`]). Off by default, and not in the lane list, which /// is what the history snapshots hold: it is a setting on the mix, like the @@ -652,6 +659,7 @@ impl Project { color: Vec::new(), history: Vec::new(), next_link: 1, + subtitles: Vec::new(), limiter: Limiter::default(), } } @@ -760,6 +768,7 @@ impl Project { color, history: Vec::new(), next_link, + subtitles: Vec::new(), limiter: Limiter::default(), }) } @@ -1128,6 +1137,35 @@ impl Project { self } + /// The subtitle tracks a *load* puts back, in the order they were saved -- + /// the same door [`with_mix`](Project::with_mix) is, and no undo step for + /// the same reason. + pub fn with_subtitles(mut self, tracks: Vec) -> Self { + self.subtitles = tracks; + self + } + + /// What this timeline shows over the picture, in the order they were added: + /// what a front-end lists and what a save writes. + pub fn subtitles(&self) -> &[SubtitleTrack] { + &self.subtitles + } + + /// Adds a track, unless the very same one -- same file, same track number + /// inside it -- is already on the list. `false` for that repeat: importing + /// the same `.srt` twice is one subtitle track, not two identical ones. + pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool { + if self + .subtitles + .iter() + .any(|t| t.path == track.path && t.track == track.track) + { + return false; + } + self.subtitles.push(track.clone()); + true + } + /// 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 new file mode 100644 index 0000000..27d1f20 --- /dev/null +++ b/crates/engine/src/subtitle.rs @@ -0,0 +1,344 @@ +//! Subtitles: a list of cues with a time on them, out of a file beside the +//! media (`.srt`, `.vtt`, `.ass`) or out of a track inside it. +//! +//! One model for both, because a timeline cannot care which it was: a +//! [`SubtitleTrack`] is where it came from -- a path, and the Matroska track +//! number when it is one of several inside that path -- plus the [`Cue`]s. That +//! pair is also all a `.edith` writes ([`crate::edith`]): the cues are read +//! back out of the file on the way in, exactly as a clip's *pictures* are, so a +//! project file stays an edit list and not a copy of the subtitles. +//! +//! Parsing is `oxideav-subtitle` (SRT, WebVTT) and `oxideav-ass` (ASS/SSA) -- +//! the markup, the override tags and the encoding quirks of a dozen dialects +//! are not this project's to re-derive. What comes back here is plain text: the +//! renderer is a later thing, and a cue nobody can draw yet is still a cue that +//! has to be listed, timed and saved. +//! +//! What is *refused* is refused by name rather than by omission +//! ([`SubtitleTrack::refused`]): the bitmap subtitle formats -- PGS off a +//! BluRay remux, VobSub off a DVD -- are pictures, and a film carrying four of +//! them opens with four rows that say so instead of opening with an empty list. + +use std::path::{Path, PathBuf}; + +use oxideav_subtitle::ir::plain_text; + +/// One line of subtitle: on screen from `start_us` to `end_us`, microseconds +/// from the start of the media, which is the unit every parser here speaks. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Cue { + pub start_us: i64, + pub end_us: i64, + /// Plain text, `\n` between the lines of a multi-line cue. The markup is + /// resolved and dropped: `` from an SRT, `{\an8}` and `\N` from an ASS. + /// + /// ponytail: bold/italic/colour and ASS positioning are parsed by the crate + /// and thrown away here, because nothing draws a cue yet. The upgrade path + /// is to keep `oxideav_core::Segment` beside this string -- the parsers + /// already hand it over -- and it belongs to whoever writes the renderer. + pub text: String, +} + +/// A subtitle track: where it came from and what it says. +#[derive(Clone, Debug)] +pub struct SubtitleTrack { + /// The file it was read out of: a standalone subtitle file, or the media + /// file whose track number is below. + pub path: PathBuf, + /// 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. + pub label: String, + /// In start order. Empty when [`refused`](Self::refused) says why. + pub cues: Vec, + /// Why this track has no cues, when it has none: a codec that is pictures + /// rather than text, a file that has gone missing since the project was + /// saved. `None` for one that parsed -- which a track with genuinely no + /// cues in it also is. + pub refused: Option, +} + +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. + fn refused(path: &Path, track: Option, label: String, why: String) -> Self { + Self { + path: path.to_path_buf(), + track, + label, + cues: Vec::new(), + refused: Some(why), + } + } +} + +/// The one door a saved subtitle line comes back in through: a standalone file +/// (`track` is `None`) or track `n` of a Matroska file. +/// +/// 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 +/// pictures. All of them come back [`refused`](SubtitleTrack::refused) by name, +/// because a project that opened yesterday has to open today -- a subtitle is +/// not what a whole timeline should refuse over. +pub fn open(path: &Path, track: Option) -> SubtitleTrack { + let Some(number) = track else { + return external(path); + }; + let label = format!("track {number}"); + let mut tracks = match of_matroska(path) { + Ok(tracks) => tracks, + Err(why) => return SubtitleTrack::refused(path, track, label, why.to_string()), + }; + match tracks.iter().position(|t| t.track == Some(number)) { + Some(i) => tracks.swap_remove(i), + None => SubtitleTrack::refused( + path, + track, + label, + format!("no subtitle track {number} in {} any more", path.display()), + ), + } +} + +/// A standalone subtitle file, parsed by its extension. +fn external(path: &Path) -> SubtitleTrack { + let label = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + match parse_file(path) { + Ok(cues) => SubtitleTrack { + path: path.to_path_buf(), + track: None, + label, + cues, + refused: None, + }, + Err(why) => SubtitleTrack::refused(path, None, label, why.to_string()), + } +} + +/// 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(|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), + }; + match cues_of(&t) { + Ok(cues) => SubtitleTrack { + path: path.to_path_buf(), + track: Some(t.number), + label, + cues, + refused: None, + }, + Err(why) => SubtitleTrack::refused(path, Some(t.number), label, why), + } + }) + .collect()) +} + +/// The cues of one Matroska subtitle track, or why it has none. +/// +/// A Matroska text track carries the *timing* on the block and the *text* in +/// it, so neither codec is parsed as its own file would be: `S_TEXT/UTF8` is +/// one SRT cue's body per block, `S_TEXT/ASS` is one `Dialogue` line per block +/// with the `Start` and `End` fields cut out and the `[Script Info]` header +/// filed away in `CodecPrivate`. Both are put back into the shape their parser +/// reads -- rather than the markup being re-derived here -- which is also what +/// makes an embedded track and the standalone file it was muxed from come back +/// as the same cues. +fn cues_of(track: &crate::demux::MkvSubtitle) -> Result, String> { + let cues = match track.codec.as_str() { + "S_TEXT/UTF8" | "S_TEXT/ASCII" => track + .cues + .iter() + .map(|c| Cue { + start_us: c.start_us, + end_us: end_of(track, c), + text: srt_body(&String::from_utf8_lossy(&c.payload)), + }) + .collect(), + "S_TEXT/ASS" | "S_TEXT/SSA" => ass_cues(track)?, + codec => { + return Err(format!( + "{codec} subtitles are pictures, not text — this track is listed, not read" + )); + } + }; + Ok(cues) +} + +/// When a cue goes away: its `BlockDuration`, or -- for the muxer that writes +/// none -- when the next one arrives, and [`NO_DURATION_US`] for the last. +fn end_of(track: &crate::demux::MkvSubtitle, cue: &crate::demux::MkvCue) -> i64 { + /// How long a cue with nothing to say about it stays up: two seconds, a + /// read of one line. + const NO_DURATION_US: i64 = 2_000_000; + match cue.duration_us { + Some(d) => cue.start_us + d, + None => track + .cues + .iter() + .map(|c| c.start_us) + .find(|&s| s > cue.start_us) + .unwrap_or(cue.start_us + NO_DURATION_US), + } +} + +/// The text of one `S_TEXT/UTF8` block with its markup resolved: through the +/// SRT parser, around a timing line this then throws away, because SRT markup +/// is exactly what such a block holds and a second implementation of it here +/// would be a second set of bugs. +fn srt_body(text: &str) -> String { + let doc = format!("1\n00:00:00,000 --> 00:00:01,000\n{}\n", text.trim_end()); + match oxideav_subtitle::srt::parse(doc.as_bytes()) { + Ok(track) => track + .cues + .first() + .map(|c| plain_text(&c.segments)) + .unwrap_or_default(), + // The parser refuses nothing an SRT body can hold; if it ever does, + // the bytes themselves are a better answer than an empty cue. + Err(_) => text.trim_end().to_owned(), + } +} + +/// The cues of an `S_TEXT/ASS` track: the script header out of `CodecPrivate` +/// with every block put back as a `Dialogue` line under it, parsed once as the +/// `.ass` file it came from. +fn ass_cues(track: &crate::demux::MkvSubtitle) -> Result, String> { + let mut doc = String::from_utf8_lossy(&track.private).into_owned(); + if !doc.ends_with('\n') { + doc.push('\n'); + } + for cue in &track.cues { + let fields = String::from_utf8_lossy(&cue.payload); + // `ReadOrder,Layer,`: the two the + // block adds go, and the timing the block *is* takes their place. The + // field order is the one the header's `Format:` line declares, which + // is the order a demuxer strips them out of. + let mut rest = fields.trim_end().splitn(3, ','); + let (_read_order, layer, rest) = match (rest.next(), rest.next(), rest.next()) { + (Some(r), Some(l), Some(t)) => (r, l, t), + _ => continue, + }; + doc.push_str(&format!( + "Dialogue: {layer},{},{},{rest}\n", + timestamp(cue.start_us), + timestamp(end_of(track, cue)) + )); + } + let parsed = oxideav_ass::parse(doc.as_bytes()).map_err(|e| e.to_string())?; + // The timings above are centiseconds, which is all an ASS line can say; + // the blocks are microseconds. So the text comes from the parse and the + // timing from the block -- unless a line was dropped as unparsable, when + // the pairing is no longer sound and the parse answers for both. + let exact = parsed.cues.len() == track.cues.len(); + Ok(parsed + .cues + .iter() + .enumerate() + .map(|(i, c)| Cue { + start_us: if exact { + track.cues[i].start_us + } else { + c.start_us + }, + end_us: if exact { + end_of(track, &track.cues[i]) + } else { + c.end_us + }, + text: plain_text(&c.segments), + }) + .collect()) +} + +/// Microseconds as ASS writes a time: `H:MM:SS.cc`. +fn timestamp(us: i64) -> String { + let cs = (us.max(0) + 5_000) / 10_000; + format!( + "{}:{:02}:{:02}.{:02}", + cs / 360_000, + cs / 6_000 % 60, + cs / 100 % 60, + cs % 100 + ) +} + +/// A standalone subtitle file, by extension: the formats this engine reads at +/// all. Anything else is refused by name, as an unknown media file is. +fn parse_file(path: &Path) -> crate::Result> { + let ext = path + .extension() + .map(|e| e.to_string_lossy().to_ascii_lowercase()) + .unwrap_or_default(); + // The extension before the read: a `.txt` is refused for what it is, not + // for whether it happens to be there. + type Parse = fn(&[u8]) -> oxideav_core::Result; + let parse: Parse = match ext.as_str() { + "srt" => oxideav_subtitle::srt::parse, + "vtt" | "webvtt" => oxideav_subtitle::webvtt::parse, + "ass" | "ssa" => oxideav_ass::parse, + other => { + return Err(format!( + "{other:?} is not a subtitle format this reads — .srt, .vtt, .ass and .ssa are" + ) + .into()); + } + }; + let track = parse(&std::fs::read(path)?); + let track = track.map_err(|e| format!("{}: {e}", path.display()))?; + Ok(track + .cues + .iter() + .map(|c| Cue { + start_us: c.start_us, + end_us: c.end_us, + text: plain_text(&c.segments), + }) + .collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ass_timestamps_are_written_the_way_ass_reads_them() { + assert_eq!(timestamp(0), "0:00:00.00"); + assert_eq!(timestamp(500_000), "0:00:00.50"); + assert_eq!(timestamp(3_250_000), "0:00:03.25"); + // An hour, a minute and a second, and a negative time is not one. + assert_eq!(timestamp(3_661_000_000), "1:01:01.00"); + assert_eq!(timestamp(-1), "0:00:00.00"); + } + + #[test] + fn srt_markup_is_resolved_not_carried() { + assert_eq!(srt_body("tilted and plain"), "tilted and plain"); + assert_eq!(srt_body("two\nlines\n"), "two\nlines"); + } + + #[test] + fn an_unknown_extension_is_refused_by_name_and_a_missing_file_is_kept() { + let err = parse_file(Path::new("/nonexistent/notes.txt")) + .unwrap_err() + .to_string(); + assert!(err.contains("txt"), "{err}"); + // ...and a `.srt` that is not there comes back as a track that says so + // rather than as no track at all, so a re-save does not lose it. + let gone = external(Path::new("/nonexistent/subs.srt")); + assert!(gone.refused.is_some()); + assert_eq!(gone.label, "subs.srt"); + } +} diff --git a/crates/engine/tests/data/test_subs.ass b/crates/engine/tests/data/test_subs.ass new file mode 100644 index 0000000..d6c0c93 --- /dev/null +++ b/crates/engine/tests/data/test_subs.ass @@ -0,0 +1,14 @@ +[Script Info] +ScriptType: v4.00+ +PlayResX: 384 +PlayResY: 288 + +[V4+ Styles] +Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding +Style: Default,Arial,16,&Hffffff,&Hffffff,&H0,&H0,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,1 + +[Events] +Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text +Dialogue: 0,0:00:00.50,0:00:01.50,Default,,0,0,0,,first line +Dialogue: 0,0:00:02.00,0:00:03.25,Default,,0,0,0,,second line\Nwith a break +Dialogue: 0,0:00:04.00,0:00:04.75,Default,,0,0,0,,{\i1}third{\i0} line diff --git a/crates/engine/tests/data/test_subs.srt b/crates/engine/tests/data/test_subs.srt new file mode 100644 index 0000000..f75aabc --- /dev/null +++ b/crates/engine/tests/data/test_subs.srt @@ -0,0 +1,12 @@ +1 +00:00:00,500 --> 00:00:01,500 +first line + +2 +00:00:02,000 --> 00:00:03,250 +second line +with a break + +3 +00:00:04,000 --> 00:00:04,750 +third line diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index 314f8e9..d393d80 100644 --- a/crates/engine/tests/saveload.rs +++ b/crates/engine/tests/saveload.rs @@ -209,7 +209,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() { let v2 = dir.join("new.edith"); loaded.save_project(&v2).expect("save"); let text = std::fs::read_to_string(&v2).expect("read back"); - assert!(text.starts_with("edith 9\n"), "{text}"); + assert!(text.starts_with("edith 10\n"), "{text}"); assert!( text.contains("\nresolution 1280 720\n"), "a project with no resolution of its own is saved at source 0's: {text}" @@ -297,7 +297,7 @@ fn a_version_4_project_holds_more_than_two_lanes() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\ video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n", "a four-lane project is written as it was read, three versions on" @@ -327,7 +327,7 @@ fn a_version_5_project_carries_per_clip_equalizers() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 12000.0:6.25:0.5:hs\n\ video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\ @@ -362,7 +362,7 @@ fn a_version_6_project_carries_per_clip_colours() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ color 0.1:1.2:0.9:-0.3\n\ color -0.25:1.0:0.0:0.5\n\ @@ -412,7 +412,7 @@ fn a_version_7_project_carries_a_resolution_and_fit_policies() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 9\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\ + "edith 10\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\ video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\ audio 1 0 0 60 0 - - - fit 1000\n", "a v7 project is written back as the v8 it now is: the same clips, each \ @@ -670,7 +670,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() { for (text, want) in [ ( - "edith 10\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", + "edith 11\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", "line 1", ), // An eq index the table does not hold, and a band shape there is none. @@ -806,7 +806,7 @@ fn a_song_only_project_comes_back_at_the_rate_it_names() { let path = dir.join("song.edith"); std::fs::write( &path, - "edith 9\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\ + "edith 10\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\ video 1\naudio 1 0 0 24 0 - - - fit 1000\n", ) .expect("write a v9 song project"); diff --git a/crates/engine/tests/silence.rs b/crates/engine/tests/silence.rs index 735a2d6..2175308 100644 --- a/crates/engine/tests/silence.rs +++ b/crates/engine/tests/silence.rs @@ -365,6 +365,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() { &sources, &lanes, &p.lane_gains(), + p.subtitles(), &eq, &color, (1920, 1080), @@ -375,7 +376,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() { .expect("save"); let text = std::fs::read_to_string(&file).expect("read it back"); assert!( - text.starts_with("edith 9"), + text.starts_with("edith 10"), "{:?}", &text[..16.min(text.len())] ); diff --git a/crates/engine/tests/subtitles.rs b/crates/engine/tests/subtitles.rs new file mode 100644 index 0000000..e10bea5 --- /dev/null +++ b/crates/engine/tests/subtitles.rs @@ -0,0 +1,237 @@ +//! Subtitles: the cues of a file beside the media and of a track inside it are +//! the same cues, a project keeps them across a save, and the formats that are +//! pictures rather than text are listed and skipped by name rather than +//! silently dropped. +//! +//! ```text +//! cargo test -p engine --release --test subtitles -- --nocapture +//! ``` + +use std::path::PathBuf; + +use engine::subtitle::{self, Cue}; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn data(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/data") + .join(name) +} + +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ve_subs_{name}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + std::fs::canonicalize(&dir).expect("canonical scratch dir") +} + +/// The three cues both hand-written fixtures hold, with the markup resolved: +/// the italics of the `.ass` third line are not text, and the `\N` of its +/// second one is a line break like the `.srt`'s. +fn expected() -> Vec { + 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(), + }, + ] +} + +/// The whole of the parse half: four routes to the same three cues -- an +/// `.srt`, an `.ass` with override tags in it, and the two tracks of the +/// Matroska file both were muxed into, whose timing lives on the block and +/// whose text lives in it. +#[test] +fn a_file_beside_the_media_and_a_track_inside_it_read_the_same() { + let srt = subtitle::open(&data("test_subs.srt"), None); + assert_eq!(srt.refused, None, "the .srt parses"); + assert_eq!(srt.cues, expected()); + assert_eq!(srt.label, "test_subs.srt"); + + let ass = subtitle::open(&data("test_subs.ass"), None); + assert_eq!(ass.refused, None, "the .ass parses"); + assert_eq!(ass.cues, expected(), "the override tags are resolved"); + + let embedded = subtitle::of_matroska(&asset("test_subs.mkv")).expect("the mkv is walked"); + let text: Vec<_> = embedded.iter().map(|t| (&t.label, &t.cues)).collect(); + assert_eq!(embedded.len(), 2, "two subtitle tracks: {text:?}"); + for track in &embedded { + assert_eq!(track.refused, None, "{} parses", track.label); + assert_eq!( + track.cues, + expected(), + "{} holds the same cues", + track.label + ); + } + // ...and each is named by what the file says about it, so a list has + // something to show but the track number. + assert_eq!(embedded[0].label, "eng"); + assert_eq!(embedded[1].label, "fra — Signs"); + assert_eq!(embedded[0].track, Some(2)); + assert_eq!(embedded[1].track, Some(3)); + + // The one door a saved line comes back through reaches the same track. + let one = subtitle::open(&asset("test_subs.mkv"), Some(3)); + assert_eq!(one.cues, expected()); + // A track number the file does not have is refused by name, not an error: + // the project it was saved in still opens. + let gone = subtitle::open(&asset("test_subs.mkv"), Some(9)); + assert!( + gone.refused.as_deref().unwrap_or_default().contains("9"), + "{:?}", + gone.refused + ); +} + +/// A subtitle track this cannot read is a row that says why -- never an error +/// that takes the whole file down with it. The repro is a BluRay remux +/// carrying four PGS tracks: opening it lists four subtitles it cannot draw, +/// and the picture and the sound come up regardless. +/// +/// Written here rather than muxed by the fixture script because ffmpeg cannot +/// encode text subtitles into pictures; the bytes below are the `Tracks` +/// element of such a file and nothing else. +#[test] +fn bitmap_subtitles_are_listed_and_skipped_by_name() { + let dir = scratch("pgs"); + let file = dir.join("remux.mkv"); + std::fs::write(&file, pgs_matroska()).expect("write the hand-made mkv"); + + let tracks = subtitle::of_matroska(&file).expect("the walk does not fail over them"); + assert_eq!(tracks.len(), 4, "every PGS track is listed"); + for (i, track) in tracks.iter().enumerate() { + assert_eq!(track.track, Some(i as u64 + 1)); + assert_eq!(track.cues, Vec::new(), "no cues to have"); + let why = track.refused.clone().unwrap_or_default(); + assert!( + why.contains("S_HDMV/PGS") && why.contains("pictures"), + "the refusal names the codec: {why:?}" + ); + } + // The language is what a list shows, and `und` is what the spec says a + // track that names none is. + assert_eq!(tracks[0].label, "eng"); + assert_eq!(tracks[3].label, "und"); +} + +/// A saved project comes back with its subtitles: the `.edith` names the file +/// and the track, and the cues are read out of them again on the way in. The +/// engine's own door for both halves -- import, save, open -- since that is +/// what a front-end will drive. +#[test] +fn a_project_keeps_its_subtitles_across_a_save() { + let dir = scratch("save"); + let media = dir.join("test_av.mp4"); + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); + // Beside the media, which is where a subtitle file lives: the project then + // writes it relative, and the whole folder stays movable. + let subs = dir.join("test_subs.srt"); + std::fs::copy(data("test_subs.srt"), &subs).expect("copy the subtitle fixture"); + + let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); + session.set_gain(0.0); // silent like the rest of the suites + assert_eq!(session.subtitles().len(), 0, "nothing to start with"); + assert_eq!( + session.import_subtitles(&subs).expect("the .srt imports"), + 1 + ); + // The same file twice is the same subtitles, not two rows of them. + assert_eq!(session.import_subtitles(&subs).expect("no error"), 0); + assert_eq!(session.subtitles()[0].cues, expected()); + + 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.starts_with("edith 10\n"), "{text}"); + assert!( + text.contains("\nsubtitle - test_subs.srt\n"), + "the reference is written relative, and no cue is: {text}" + ); + + let back = engine::PlaybackSession::open_project(&project).expect("open the project"); + assert_eq!(back.subtitles().len(), 1); + assert_eq!(back.subtitles()[0].cues, expected()); + assert_eq!(back.subtitles()[0].track, None); + drop(back); + + // A subtitle file that has gone missing is listed, refused by name, and + // written out again: the project still opens and the row is not lost. + std::fs::remove_file(&subs).expect("take the subtitles away"); + let gone = engine::PlaybackSession::open_project(&project).expect("the project still opens"); + assert_eq!(gone.subtitles().len(), 1); + assert!(gone.subtitles()[0].refused.is_some()); + let again = dir.join("cut2.edith"); + gone.save_project(&again).expect("save again"); + assert!( + std::fs::read_to_string(&again) + .expect("read") + .contains("\nsubtitle - test_subs.srt\n"), + "a re-save keeps the row" + ); +} + +/// A refusal a front-end shows at the moment of the import, rather than a row +/// nobody asked for: a file that is not a subtitle format at all. +#[test] +fn importing_something_that_is_not_a_subtitle_says_so() { + let dir = scratch("refuse"); + let media = dir.join("test_av.mp4"); + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); + let notes = dir.join("notes.txt"); + std::fs::write(¬es, "not a subtitle").expect("write"); + + let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); + session.set_gain(0.0); + let err = session + .import_subtitles(¬es) + .expect_err("a .txt is not a subtitle") + .to_string(); + assert!(err.contains("txt"), "{err}"); + assert_eq!(session.subtitles().len(), 0, "and nothing was added"); +} + +/// The `Tracks` element of a Matroska file carrying four PGS subtitle tracks +/// and nothing else -- enough for the walk, which stops at the first `Cluster` +/// and there is none. +fn pgs_matroska() -> Vec { + /// 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 { + let mut out = id.to_vec(); + let mut len = (body.len() as u64).to_be_bytes(); + len[0] |= 0x01; // the 8-byte length marker + out.extend_from_slice(&len); + out.extend_from_slice(body); + out + } + let mut tracks = Vec::new(); + for (number, language) in [(1u8, "eng"), (2, "fra"), (3, "spa"), (4, "")] { + let mut entry = Vec::new(); + entry.extend(element(&[0xD7], &[number])); // TrackNumber + entry.extend(element(&[0x83], &[0x11])); // TrackType: subtitle + entry.extend(element(&[0x86], b"S_HDMV/PGS")); // CodecID + if !language.is_empty() { + entry.extend(element(&[0x22, 0xB5, 0x9C], language.as_bytes())); + } + tracks.extend(element(&[0xAE], &entry)); // TrackEntry + } + let segment = element(&[0x16, 0x54, 0xAE, 0x6B], &tracks); // Tracks + element(&[0x18, 0x53, 0x80, 0x67], &segment) // Segment +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index b121be0..0640982 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -113,6 +113,24 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_av1.mkv +# Subtitles in Matroska: the two text codecs a film carries, muxed out of the +# hand-written files the tests also parse standalone +# (`crates/engine/tests/data/`), so the embedded cues and the external ones can +# be compared to each other and both to the source. Track 2 is S_TEXT/UTF8 and +# track 3 is S_TEXT/ASS -- the same three cues, one of them with markup, which +# is what makes "the markup is resolved, not carried" measurable. +# +# No bitmap track here: ffmpeg cannot encode text subtitles into pictures, so +# the PGS refusal is checked against a Matroska file the test writes itself +# (`crates/engine/tests/subtitles.rs`). +ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=5 \ + -i crates/engine/tests/data/test_subs.srt \ + -i crates/engine/tests/data/test_subs.ass \ + -map 0:v -map 1:0 -map 2:0 \ + -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ + -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 # 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