Subtitles come in with the film or beside it
Browse files at this commitf4b5fd8bc8492921e38552c1ebbdf97ab3b1eae6Parent: dea8a27- feat
- subtitles come in with the film or beside it
14 changed files +1205 -33
- Cargo.lock +89 -0
- crates/engine/Cargo.toml +10 -0
- crates/engine/src/demux.rs +210 -0
- crates/engine/src/edith.rs +167 -24
- crates/engine/src/lib.rs +1 -0
- crates/engine/src/playback.rs +56 -1
- crates/engine/src/project.rs +38 -0
- crates/engine/src/subtitle.rs +344 -0
- crates/engine/tests/data/test_subs.ass +14 -0
- crates/engine/tests/data/test_subs.srt +12 -0
- crates/engine/tests/saveload.rs +7 -7
- crates/engine/tests/silence.rs +2 -1
- crates/engine/tests/subtitles.rs +237 -0
- scripts/gen_fixtures.sh +18 -0
Cargo.lockmodified+89 -0
| @@ -1003,6 +1003,12 @@ dependencies = [ | |||
| 1003 | "thiserror 2.0.20", | 1003 | "thiserror 2.0.20", |
| 1004 | ] | 1004 | ] |
| 1005 | 1005 | ||
| 1006 | +[[package]] | ||
| 1007 | +name = "compcol" | ||
| 1008 | +version = "0.6.8" | ||
| 1009 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1010 | +checksum = "28b37ce533aa0fddc1e6820e331968ba72aa48b5c8bbb2bebdc03d48b6ed0f16" | ||
| 1011 | + | ||
| 1006 | [[package]] | 1012 | [[package]] |
| 1007 | name = "compression-codecs" | 1013 | name = "compression-codecs" |
| 1008 | version = "0.4.38" | 1014 | version = "0.4.38" |
| @@ -1636,8 +1642,10 @@ dependencies = [ | |||
| 1636 | "libloading", | 1642 | "libloading", |
| 1637 | "mp4", | 1643 | "mp4", |
| 1638 | "oxideav-ac3", | 1644 | "oxideav-ac3", |
| 1645 | + "oxideav-ass", | ||
| 1639 | "oxideav-core", | 1646 | "oxideav-core", |
| 1640 | "oxideav-h265", | 1647 | "oxideav-h265", |
| 1648 | + "oxideav-subtitle", | ||
| 1641 | "rav1e", | 1649 | "rav1e", |
| 1642 | "rusty_aac", | 1650 | "rusty_aac", |
| 1643 | "rusty_h264", | 1651 | "rusty_h264", |
| @@ -3940,6 +3948,16 @@ dependencies = [ | |||
| 3940 | "oxideav-core", | 3948 | "oxideav-core", |
| 3941 | ] | 3949 | ] |
| 3942 | 3950 | ||
| 3951 | +[[package]] | ||
| 3952 | +name = "oxideav-ass" | ||
| 3953 | +version = "0.0.9" | ||
| 3954 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3955 | +checksum = "b9d5a10750f54eb6913bf3ca295d17899006c9a9c6c94970741a5a7c0c49e3fa" | ||
| 3956 | +dependencies = [ | ||
| 3957 | + "oxideav-core", | ||
| 3958 | + "oxideav-subtitle", | ||
| 3959 | +] | ||
| 3960 | + | ||
| 3943 | [[package]] | 3961 | [[package]] |
| 3944 | name = "oxideav-core" | 3962 | name = "oxideav-core" |
| 3945 | version = "0.1.34" | 3963 | version = "0.1.34" |
| @@ -3958,6 +3976,77 @@ dependencies = [ | |||
| 3958 | "oxideav-core", | 3976 | "oxideav-core", |
| 3959 | ] | 3977 | ] |
| 3960 | 3978 | ||
| 3979 | +[[package]] | ||
| 3980 | +name = "oxideav-otf" | ||
| 3981 | +version = "0.1.3" | ||
| 3982 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3983 | +checksum = "571c56414ce3138d3a4e7c833b402b3c69a96db707f54abd0f1ad85f3d5d1a0b" | ||
| 3984 | +dependencies = [ | ||
| 3985 | + "oxideav-core", | ||
| 3986 | +] | ||
| 3987 | + | ||
| 3988 | +[[package]] | ||
| 3989 | +name = "oxideav-pixfmt" | ||
| 3990 | +version = "0.1.7" | ||
| 3991 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3992 | +checksum = "868d5cd1d9cf3f4d527241b6ed85fcd628c65e303fe4efb2998e4d6104c7ce4b" | ||
| 3993 | +dependencies = [ | ||
| 3994 | + "oxideav-core", | ||
| 3995 | +] | ||
| 3996 | + | ||
| 3997 | +[[package]] | ||
| 3998 | +name = "oxideav-png" | ||
| 3999 | +version = "0.1.8" | ||
| 4000 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4001 | +checksum = "c78483db4263204f6f9e2e63354b45f0fe2f83e0e08282f68c8a9647d537fa1f" | ||
| 4002 | +dependencies = [ | ||
| 4003 | + "compcol", | ||
| 4004 | + "oxideav-core", | ||
| 4005 | +] | ||
| 4006 | + | ||
| 4007 | +[[package]] | ||
| 4008 | +name = "oxideav-raster" | ||
| 4009 | +version = "0.1.2" | ||
| 4010 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4011 | +checksum = "41beead01c28b23e6e997e8b2d3a38bb1b53cd37b6e8a72a10befa2fb57a6e06" | ||
| 4012 | +dependencies = [ | ||
| 4013 | + "oxideav-core", | ||
| 4014 | + "oxideav-pixfmt", | ||
| 4015 | +] | ||
| 4016 | + | ||
| 4017 | +[[package]] | ||
| 4018 | +name = "oxideav-scribe" | ||
| 4019 | +version = "0.1.9" | ||
| 4020 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4021 | +checksum = "a9aec36b356861de9e0e660a7990f14b428476638f7b2ba902c0cd7e1ffdac39" | ||
| 4022 | +dependencies = [ | ||
| 4023 | + "oxideav-core", | ||
| 4024 | + "oxideav-otf", | ||
| 4025 | + "oxideav-png", | ||
| 4026 | + "oxideav-ttf", | ||
| 4027 | +] | ||
| 4028 | + | ||
| 4029 | +[[package]] | ||
| 4030 | +name = "oxideav-subtitle" | ||
| 4031 | +version = "0.1.2" | ||
| 4032 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4033 | +checksum = "88e41289024a95ea82051cd18af77885afd7be3c23a38255cb1edbe49872273a" | ||
| 4034 | +dependencies = [ | ||
| 4035 | + "oxideav-core", | ||
| 4036 | + "oxideav-pixfmt", | ||
| 4037 | + "oxideav-raster", | ||
| 4038 | + "oxideav-scribe", | ||
| 4039 | +] | ||
| 4040 | + | ||
| 4041 | +[[package]] | ||
| 4042 | +name = "oxideav-ttf" | ||
| 4043 | +version = "0.1.7" | ||
| 4044 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4045 | +checksum = "c44d45518f6f4d749d2bf2c7cb3622fdb7ccc6147457545ed36aa8d241adea8e" | ||
| 4046 | +dependencies = [ | ||
| 4047 | + "oxideav-core", | ||
| 4048 | +] | ||
| 4049 | + | ||
| 3961 | [[package]] | 4050 | [[package]] |
| 3962 | name = "parking" | 4051 | name = "parking" |
| 3963 | version = "2.2.1" | 4052 | version = "2.2.1" |
crates/engine/Cargo.tomlmodified+10 -0
| @@ -66,6 +66,16 @@ symphonia = { version = "0.6", default-features = false, features = [ | |||
| 66 | ] } | 66 | ] } |
| 67 | oxideav-ac3 = "=0.0.10" | 67 | oxideav-ac3 = "=0.0.10" |
| 68 | oxideav-core = "0.1.34" | 68 | oxideav-core = "0.1.34" |
| 69 | +# The subtitle parsers: SRT and WebVTT here, ASS/SSA in the sibling crate -- | ||
| 70 | +# `oxideav-subtitle` hosts the shared IR and hands ASS to `oxideav-ass`, which | ||
| 71 | +# is why both names are needed for the three formats. MIT, pure Rust, and both | ||
| 72 | +# asked for without their default features: nothing here *draws* a cue yet (see | ||
| 73 | +# `crate::subtitle`), so the rendering stacks are dead weight. Only `oxideav-ass` | ||
| 74 | +# actually loses one -- it depends on `oxideav-subtitle` with defaults on, so | ||
| 75 | +# that crate's `text` feature (the bitmap font and rasterizer) is unified back | ||
| 76 | +# in whatever this line says. Nothing here calls into it. | ||
| 77 | +oxideav-subtitle = { version = "0.1.2", default-features = false } | ||
| 78 | +oxideav-ass = { version = "0.0.9", default-features = false } | ||
| 69 | # The software AV1 encoder, and the only new name in this list that was already | 79 | # The software AV1 encoder, and the only new name in this list that was already |
| 70 | # in the lock file: `ravif` pulls the very same rav1e 0.8.1 in through the image | 80 | # in the lock file: `ravif` pulls the very same rav1e 0.8.1 in through the image |
| 71 | # crate, so this links what the build already compiled. BSD-2 with the AOM | 81 | # crate, so this links what the build already compiled. BSD-2 with the AOM |
crates/engine/src/demux.rsmodified+210 -0
| @@ -1138,6 +1138,216 @@ fn tkhd_track_id(payload: &[u8]) -> Option<u32> { | |||
| 1138 | )) | 1138 | )) |
| 1139 | } | 1139 | } |
| 1140 | 1140 | ||
| 1141 | +/// One subtitle track of a Matroska file, exactly as its `TrackEntry` declares | ||
| 1142 | +/// it. What the cues *mean* is [`crate::subtitle`]'s business; this is the | ||
| 1143 | +/// walk, and it reads every track type 0x11 the file has -- including the ones | ||
| 1144 | +/// nothing here can render, which is how a caller names what it is leaving out | ||
| 1145 | +/// instead of quietly opening a film with no subtitles in the list. | ||
| 1146 | +#[derive(Debug)] | ||
| 1147 | +pub struct MkvSubtitle { | ||
| 1148 | + pub number: u64, | ||
| 1149 | + /// The Matroska codec id: `S_TEXT/UTF8`, `S_TEXT/ASS`, `S_HDMV/PGS`, ... | ||
| 1150 | + pub codec: String, | ||
| 1151 | + /// `Language`, ISO-639-2, `und` when the file says nothing. | ||
| 1152 | + pub language: String, | ||
| 1153 | + /// `Name`, the human label a muxer wrote, often empty. | ||
| 1154 | + pub name: String, | ||
| 1155 | + /// `CodecPrivate`: the ASS script header (`[Script Info]` through the | ||
| 1156 | + /// `[Events]` `Format:` line) for `S_TEXT/ASS`, empty for `S_TEXT/UTF8`. | ||
| 1157 | + pub private: Vec<u8>, | ||
| 1158 | + /// Every cue block, in storage order -- but only for the `S_TEXT/*` codecs. | ||
| 1159 | + /// A bitmap track (PGS, VobSub) comes back declared and empty: its blocks | ||
| 1160 | + /// are megabytes of pictures, and nothing here can draw one. | ||
| 1161 | + pub cues: Vec<MkvCue>, | ||
| 1162 | +} | ||
| 1163 | + | ||
| 1164 | +/// One subtitle block: when it shows and the bytes it shows. | ||
| 1165 | +#[derive(Debug)] | ||
| 1166 | +pub struct MkvCue { | ||
| 1167 | + /// Microseconds from the start of the file -- the block timestamp scaled by | ||
| 1168 | + /// the segment's `TimestampScale`, which is the unit | ||
| 1169 | + /// [`crate::subtitle::Cue`] keeps. | ||
| 1170 | + pub start_us: i64, | ||
| 1171 | + /// `BlockDuration`, microseconds. `None` for a block that declares none, | ||
| 1172 | + /// which leaves how long the cue stays up to the caller. | ||
| 1173 | + pub duration_us: Option<i64>, | ||
| 1174 | + /// The block's own bytes: the text for `S_TEXT/UTF8`, the comma-separated | ||
| 1175 | + /// `Dialogue` fields (`ReadOrder` first, no timing) for `S_TEXT/ASS`. | ||
| 1176 | + pub payload: Vec<u8>, | ||
| 1177 | +} | ||
| 1178 | + | ||
| 1179 | +/// The subtitle tracks of a Matroska file, in file order. An mp4's are not read | ||
| 1180 | +/// (its `tx3g` is a different beast, and no file this project opens carries | ||
| 1181 | +/// one); anything that is not a Matroska file at all is an error, as it is for | ||
| 1182 | +/// [`matroska_audio_codec`]. | ||
| 1183 | +/// | ||
| 1184 | +/// Two passes at most: the header walk stops at the first `Cluster`, and the | ||
| 1185 | +/// cue pass runs only when there is a text track to fill. | ||
| 1186 | +pub fn matroska_subtitles(path: &Path) -> crate::Result<Vec<MkvSubtitle>> { | ||
| 1187 | + let mut file = File::open(path)?; | ||
| 1188 | + let end = file.metadata()?.len(); | ||
| 1189 | + let segment = mkv_segment(&mut file, end)?; | ||
| 1190 | + let mut tracks: Vec<MkvSubtitle> = Vec::new(); | ||
| 1191 | + let mut timestamp_scale = 1_000_000; | ||
| 1192 | + let mut at = segment.0; | ||
| 1193 | + while let Some((id, body, stop)) = ebml_element(&mut file, at, segment.1)? { | ||
| 1194 | + match id { | ||
| 1195 | + CLUSTER => break, | ||
| 1196 | + INFO => { | ||
| 1197 | + let mut at = body; | ||
| 1198 | + while let Some(e) = ebml_element(&mut file, at, stop)? { | ||
| 1199 | + if e.0 == TIMESTAMP_SCALE { | ||
| 1200 | + timestamp_scale = ebml_uint(&mut file, e.1, e.2)?.max(1); | ||
| 1201 | + } | ||
| 1202 | + at = e.2; | ||
| 1203 | + } | ||
| 1204 | + } | ||
| 1205 | + TRACKS => { | ||
| 1206 | + let mut at = body; | ||
| 1207 | + while let Some(e) = ebml_element(&mut file, at, stop)? { | ||
| 1208 | + if e.0 == TRACK_ENTRY { | ||
| 1209 | + tracks.extend(mkv_subtitle_entry(&mut file, e.1, e.2)?); | ||
| 1210 | + } | ||
| 1211 | + at = e.2; | ||
| 1212 | + } | ||
| 1213 | + } | ||
| 1214 | + _ => {} | ||
| 1215 | + } | ||
| 1216 | + at = stop; | ||
| 1217 | + } | ||
| 1218 | + // The text tracks only: see `MkvSubtitle::cues`. | ||
| 1219 | + let wanted: Vec<u64> = tracks | ||
| 1220 | + .iter() | ||
| 1221 | + .filter(|t| t.codec.starts_with("S_TEXT")) | ||
| 1222 | + .map(|t| t.number) | ||
| 1223 | + .collect(); | ||
| 1224 | + if !wanted.is_empty() { | ||
| 1225 | + mkv_subtitle_blocks(&mut file, segment, timestamp_scale, &wanted, &mut tracks)?; | ||
| 1226 | + } | ||
| 1227 | + Ok(tracks) | ||
| 1228 | +} | ||
| 1229 | + | ||
| 1230 | +/// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles. | ||
| 1231 | +fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Option<MkvSubtitle>> { | ||
| 1232 | + const TRACK_LANGUAGE: u32 = 0x22B59C; | ||
| 1233 | + const TRACK_NAME: u32 = 0x536E; | ||
| 1234 | + const SUBTITLE: u64 = 0x11; | ||
| 1235 | + let (mut number, mut kind, mut codec) = (0, 0, String::new()); | ||
| 1236 | + let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new()); | ||
| 1237 | + let mut at = body; | ||
| 1238 | + while let Some((id, body, stop)) = ebml_element(file, at, end)? { | ||
| 1239 | + match id { | ||
| 1240 | + TRACK_NUMBER => number = ebml_uint(file, body, stop)?, | ||
| 1241 | + TRACK_TYPE => kind = ebml_uint(file, body, stop)?, | ||
| 1242 | + CODEC_ID => codec = string_of(file, body, stop)?, | ||
| 1243 | + CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?, | ||
| 1244 | + TRACK_LANGUAGE => language = string_of(file, body, stop)?, | ||
| 1245 | + TRACK_NAME => name = string_of(file, body, stop)?, | ||
| 1246 | + _ => {} | ||
| 1247 | + } | ||
| 1248 | + at = stop; | ||
| 1249 | + } | ||
| 1250 | + Ok((kind == SUBTITLE).then(|| MkvSubtitle { | ||
| 1251 | + number, | ||
| 1252 | + codec, | ||
| 1253 | + // What a `TrackEntry` without a `Language` element means, by spec. | ||
| 1254 | + language: if language.is_empty() { | ||
| 1255 | + "und".into() | ||
| 1256 | + } else { | ||
| 1257 | + language | ||
| 1258 | + }, | ||
| 1259 | + name, | ||
| 1260 | + private, | ||
| 1261 | + cues: Vec::new(), | ||
| 1262 | + })) | ||
| 1263 | +} | ||
| 1264 | + | ||
| 1265 | +/// Every block of the `wanted` tracks, appended to their entries in `tracks`. | ||
| 1266 | +/// | ||
| 1267 | +/// A second cluster walk rather than a widening of [`mkv_blocks`]: that one | ||
| 1268 | +/// indexes *one* video track and reads no payloads, and a subtitle needs every | ||
| 1269 | +/// track at once, the bytes, and the `BlockDuration` beside them. | ||
| 1270 | +fn mkv_subtitle_blocks( | ||
| 1271 | + file: &mut File, | ||
| 1272 | + segment: (u64, u64), | ||
| 1273 | + timestamp_scale: u64, | ||
| 1274 | + wanted: &[u64], | ||
| 1275 | + tracks: &mut [MkvSubtitle], | ||
| 1276 | +) -> crate::Result<()> { | ||
| 1277 | + const BLOCK_DURATION: u32 = 0x9B; | ||
| 1278 | + // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is | ||
| 1279 | + // nanoseconds per tick and is a millisecond in every file anything writes. | ||
| 1280 | + let us = |ticks: i64| ticks * timestamp_scale as i64 / 1_000; | ||
| 1281 | + let mut at = segment.0; | ||
| 1282 | + while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { | ||
| 1283 | + at = stop; | ||
| 1284 | + if id != CLUSTER { | ||
| 1285 | + continue; | ||
| 1286 | + } | ||
| 1287 | + let mut cluster_ts = 0i64; | ||
| 1288 | + let mut child = body; | ||
| 1289 | + while let Some((id, body, stop)) = ebml_element(file, child, stop)? { | ||
| 1290 | + child = stop; | ||
| 1291 | + let (block, duration) = match id { | ||
| 1292 | + CLUSTER_TIMESTAMP => { | ||
| 1293 | + cluster_ts = ebml_uint(file, body, stop)? as i64; | ||
| 1294 | + continue; | ||
| 1295 | + } | ||
| 1296 | + SIMPLE_BLOCK => (mkv_block(file, body, stop)?, None), | ||
| 1297 | + BLOCK_GROUP => { | ||
| 1298 | + let (mut found, mut duration) = (None, None); | ||
| 1299 | + let mut child = body; | ||
| 1300 | + while let Some(e) = ebml_element(file, child, stop)? { | ||
| 1301 | + match e.0 { | ||
| 1302 | + BLOCK => found = Some(mkv_block(file, e.1, e.2)?), | ||
| 1303 | + BLOCK_DURATION => duration = Some(ebml_uint(file, e.1, e.2)? as i64), | ||
| 1304 | + _ => {} | ||
| 1305 | + } | ||
| 1306 | + child = e.2; | ||
| 1307 | + } | ||
| 1308 | + match found { | ||
| 1309 | + Some(block) => (block, duration), | ||
| 1310 | + None => continue, | ||
| 1311 | + } | ||
| 1312 | + } | ||
| 1313 | + _ => continue, | ||
| 1314 | + }; | ||
| 1315 | + if !wanted.contains(&block.number) { | ||
| 1316 | + continue; | ||
| 1317 | + } | ||
| 1318 | + // As for a video block: guessing at the boundaries inside a laced | ||
| 1319 | + // one is not something to do silently. No muxer laces subtitles. | ||
| 1320 | + if block.flags & 0x06 != 0 { | ||
| 1321 | + return Err("laced subtitle blocks are not supported".into()); | ||
| 1322 | + } | ||
| 1323 | + // A megabyte of *text* in one cue is a corrupt file, not a subtitle, | ||
| 1324 | + // and a crafted length may not reach an allocation through here. | ||
| 1325 | + if block.len > 1 << 20 { | ||
| 1326 | + return Err("a Matroska subtitle block larger than a megabyte".into()); | ||
| 1327 | + } | ||
| 1328 | + let mut payload = vec![0u8; block.len]; | ||
| 1329 | + read_exact_at(file, block.at, &mut payload)?; | ||
| 1330 | + let Some(track) = tracks.iter_mut().find(|t| t.number == block.number) else { | ||
| 1331 | + continue; | ||
| 1332 | + }; | ||
| 1333 | + track.cues.push(MkvCue { | ||
| 1334 | + start_us: us(cluster_ts + i64::from(block.rel)), | ||
| 1335 | + duration_us: duration.map(us), | ||
| 1336 | + payload, | ||
| 1337 | + }); | ||
| 1338 | + } | ||
| 1339 | + } | ||
| 1340 | + Ok(()) | ||
| 1341 | +} | ||
| 1342 | + | ||
| 1343 | +/// A string element, without the trailing NULs a `Name` may be padded with. | ||
| 1344 | +fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> { | ||
| 1345 | + let bytes = ebml_bytes(file, body, stop)?; | ||
| 1346 | + Ok(String::from_utf8_lossy(&bytes) | ||
| 1347 | + .trim_end_matches('\0') | ||
| 1348 | + .to_owned()) | ||
| 1349 | +} | ||
| 1350 | + | ||
| 1141 | #[cfg(test)] | 1351 | #[cfg(test)] |
| 1142 | mod tests { | 1352 | mod tests { |
| 1143 | use super::*; | 1353 | use super::*; |
crates/engine/src/edith.rsmodified+167 -24
| @@ -1,13 +1,15 @@ | |||
| 1 | //! The project file: a line of text per thing, and nothing else. | 1 | //! The project file: a line of text per thing, and nothing else. |
| 2 | //! | 2 | //! |
| 3 | //! ```text | 3 | //! ```text |
| 4 | -//! edith 9 | 4 | +//! edith 10 |
| 5 | //! playhead 90 | 5 | //! playhead 90 |
| 6 | //! resolution 1920 1080 | 6 | //! resolution 1920 1080 |
| 7 | //! fps 30.0 | 7 | //! fps 30.0 |
| 8 | //! limiter -1.0 on | 8 | //! limiter -1.0 on |
| 9 | //! source 0 test_av.mp4 | 9 | //! source 0 test_av.mp4 |
| 10 | //! source 1 /elsewhere/test_av2.mp4 | 10 | //! source 1 /elsewhere/test_av2.mp4 |
| 11 | +//! subtitle - subs.srt | ||
| 12 | +//! subtitle 3 test_av.mp4 | ||
| 11 | //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk | 13 | //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk |
| 12 | //! color 0.1:1.2:0.9:-0.3 | 14 | //! color 0.1:1.2:0.9:-0.3 |
| 13 | //! video 1 0 0 120 0 0 0 0 fit 1000 | 15 | //! video 1 0 0 120 0 0 0 0 fit 1000 |
| @@ -23,6 +25,15 @@ | |||
| 23 | //! is an answer only a project holding a video has | 25 | //! is an answer only a project holding a video has |
| 24 | //! ([`crate::PlaybackSession::open_project`]). | 26 | //! ([`crate::PlaybackSession::open_project`]). |
| 25 | //! | 27 | //! |
| 28 | +//! A `subtitle` line is `subtitle <track> <path>`: which track of that file the | ||
| 29 | +//! cues are in -- a Matroska track number, or `-` when the path *is* a subtitle | ||
| 30 | +//! file ([`crate::subtitle`]) -- and then the path, last and escaped for the | ||
| 31 | +//! reason a source's is. Only the reference is written: the cues themselves are | ||
| 32 | +//! read back out of the file on the way in, exactly as a clip's pictures are, so | ||
| 33 | +//! a project file stays an edit list. A subtitle file that has gone missing | ||
| 34 | +//! since the save comes back listed and refused by name rather than dropped, | ||
| 35 | +//! which is what keeps a re-save from losing it. | ||
| 36 | +//! | ||
| 26 | //! The `limiter` line is the master limiter over the whole mix | 37 | //! The `limiter` line is the master limiter over the whole mix |
| 27 | //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit, | 38 | //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit, |
| 28 | //! spelled `on` or `off`. Left out when it is the default, which is off. | 39 | //! spelled `on` or `off`. Left out when it is the default, which is off. |
| @@ -79,7 +90,9 @@ | |||
| 79 | //! is the only way an empty lane could still be there on the way back. A lane | 90 | //! is the only way an empty lane could still be there on the way back. A lane |
| 80 | //! number may not skip one of its kind. | 91 | //! number may not skip one of its kind. |
| 81 | //! | 92 | //! |
| 82 | -//! **Version 8** was this without the `fps` and `limiter` lines and without | 93 | +//! **Version 9** was this without the `subtitle` lines: such a project shows no |
| 94 | +//! subtitles, which is all any project could do. | ||
| 95 | +//! **Version 8** was that without the `fps` and `limiter` lines and without | ||
| 83 | //! the `gain` ones: such a project mixes every lane at unity, limits nothing, | 96 | //! the `gain` ones: such a project mixes every lane at unity, limits nothing, |
| 84 | //! and comes back at the rate its scaffolding source runs at. | 97 | //! and comes back at the rate its scaffolding source runs at. |
| 85 | //! **Version 7** was that without the clip's speed field -- every clip of such | 98 | //! **Version 7** was that without the clip's speed field -- every clip of such |
| @@ -97,8 +110,8 @@ | |||
| 97 | //! cumulatively and copied onto both lanes as one group each, which is exactly | 110 | //! cumulatively and copied onto both lanes as one group each, which is exactly |
| 98 | //! what a v1 timeline meant, and an older file simply equalizes and grades | 111 | //! what a v1 timeline meant, and an older file simply equalizes and grades |
| 99 | //! nothing, and an older one plays everything at real time, and an older one | 112 | //! nothing, and an older one plays everything at real time, and an older one |
| 100 | -//! mixes flat -- and saving any of them writes v9. An older reader refuses a | 113 | +//! mixes flat, and an older one shows no subtitles -- and saving any of them |
| 101 | -//! newer file by name. | 114 | +//! writes v10. An older reader refuses a newer file by name. |
| 102 | //! | 115 | //! |
| 103 | //! Text because an edit list is a few integers and a path, and a path is | 116 | //! Text because an edit list is a few integers and a path, and a path is |
| 104 | //! *bytes* on this platform -- a JSON string would have to lossily decode one. | 117 | //! *bytes* on this platform -- a JSON string would have to lossily decode one. |
| @@ -129,10 +142,12 @@ use crate::eq::{Band, BandKind, EqParams}; | |||
| 129 | use crate::limiter::Limiter; | 142 | use crate::limiter::Limiter; |
| 130 | use crate::project::{Clip, Lane, LaneKind, Source, Speed}; | 143 | use crate::project::{Clip, Lane, LaneKind, Source, Speed}; |
| 131 | use crate::scale::FitPolicy; | 144 | use crate::scale::FitPolicy; |
| 145 | +use crate::subtitle::SubtitleTrack; | ||
| 132 | 146 | ||
| 133 | /// What [`save`] writes. Read support goes back to `edith 1`; see the module | 147 | /// What [`save`] writes. Read support goes back to `edith 1`; see the module |
| 134 | /// docs for what those dialects looked like. | 148 | /// docs for what those dialects looked like. |
| 135 | -const MAGIC: &[u8] = b"edith 9"; | 149 | +const MAGIC: &[u8] = b"edith 10"; |
| 150 | +const MAGIC_V9: &[u8] = b"edith 9"; | ||
| 136 | const MAGIC_V8: &[u8] = b"edith 8"; | 151 | const MAGIC_V8: &[u8] = b"edith 8"; |
| 137 | const MAGIC_V7: &[u8] = b"edith 7"; | 152 | const MAGIC_V7: &[u8] = b"edith 7"; |
| 138 | const MAGIC_V6: &[u8] = b"edith 6"; | 153 | const MAGIC_V6: &[u8] = b"edith 6"; |
| @@ -169,6 +184,11 @@ pub struct Document { | |||
| 169 | /// The master limiter. Off for every dialect before v9, and for a v9 file | 184 | /// The master limiter. Off for every dialect before v9, and for a v9 file |
| 170 | /// that leaves the line out. | 185 | /// that leaves the line out. |
| 171 | pub limiter: Limiter, | 186 | pub limiter: Limiter, |
| 187 | + /// The subtitle tracks, as the file names them: the path the cues are in | ||
| 188 | + /// and which track of it, which is what [`crate::subtitle::open`] takes. | ||
| 189 | + /// Reading them is the loader's business, not this module's -- a `.edith` | ||
| 190 | + /// holds no cues. Empty for every dialect before v10. | ||
| 191 | + pub subtitles: Vec<(PathBuf, Option<u64>)>, | ||
| 172 | /// The timeline's frame rate. `None` for every dialect before v9 and for a | 192 | /// The timeline's frame rate. `None` for every dialect before v9 and for a |
| 173 | /// v9 file that leaves it out, which both mean "whatever the scaffolding | 193 | /// v9 file that leaves it out, which both mean "whatever the scaffolding |
| 174 | /// source runs at" -- the inference a project of nothing but stills and | 194 | /// source runs at" -- the inference a project of nothing but stills and |
| @@ -188,6 +208,7 @@ pub fn save( | |||
| 188 | sources: &[Source], | 208 | sources: &[Source], |
| 189 | lanes: &[(LaneKind, Vec<Clip>)], | 209 | lanes: &[(LaneKind, Vec<Clip>)], |
| 190 | gains: &[f32], | 210 | gains: &[f32], |
| 211 | + subtitles: &[SubtitleTrack], | ||
| 191 | eq: &[EqParams], | 212 | eq: &[EqParams], |
| 192 | color: &[ColorParams], | 213 | color: &[ColorParams], |
| 193 | resolution: (u32, u32), | 214 | resolution: (u32, u32), |
| @@ -206,7 +227,8 @@ pub fn save( | |||
| 206 | let result = std::fs::File::create(&part) | 227 | let result = std::fs::File::create(&part) |
| 207 | .and_then(|mut f| { | 228 | .and_then(|mut f| { |
| 208 | f.write_all(&emit( | 229 | f.write_all(&emit( |
| 209 | - &dir, sources, lanes, gains, eq, color, resolution, fps, limiter, playhead, | 230 | + &dir, sources, lanes, gains, subtitles, eq, color, resolution, fps, limiter, |
| 231 | + playhead, | ||
| 210 | ))?; | 232 | ))?; |
| 211 | f.sync_all() | 233 | f.sync_all() |
| 212 | }) | 234 | }) |
| @@ -243,6 +265,7 @@ fn emit( | |||
| 243 | sources: &[Source], | 265 | sources: &[Source], |
| 244 | lanes: &[(LaneKind, Vec<Clip>)], | 266 | lanes: &[(LaneKind, Vec<Clip>)], |
| 245 | gains: &[f32], | 267 | gains: &[f32], |
| 268 | + subtitles: &[SubtitleTrack], | ||
| 246 | eq: &[EqParams], | 269 | eq: &[EqParams], |
| 247 | color: &[ColorParams], | 270 | color: &[ColorParams], |
| 248 | resolution: (u32, u32), | 271 | resolution: (u32, u32), |
| @@ -280,6 +303,16 @@ fn emit( | |||
| 280 | escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out); | 303 | escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out); |
| 281 | out.push(b'\n'); | 304 | out.push(b'\n'); |
| 282 | } | 305 | } |
| 306 | + // The subtitle tracks, by reference: which track of which file, and never | ||
| 307 | + // the cues (see the module docs). Beside the sources because that is what | ||
| 308 | + // they are -- a file this project reads from -- although nothing indexes | ||
| 309 | + // them and their order is only the order they were added in. | ||
| 310 | + for t in subtitles { | ||
| 311 | + let track = t.track.map_or("-".to_string(), |n| n.to_string()); | ||
| 312 | + out.extend_from_slice(format!("subtitle {track} ").as_bytes()); | ||
| 313 | + escape(t.path.strip_prefix(dir).unwrap_or(&t.path), &mut out); | ||
| 314 | + out.push(b'\n'); | ||
| 315 | + } | ||
| 283 | // Before the clips, for the reason the sources are: a clip names one by the | 316 | // Before the clips, for the reason the sources are: a clip names one by the |
| 284 | // position of its line, so the line has to be there first. | 317 | // position of its line, so the line has to be there first. |
| 285 | for params in eq { | 318 | for params in eq { |
| @@ -379,9 +412,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 379 | // The dialects that wrote a source line without its stream field. Reading | 412 | // The dialects that wrote a source line without its stream field. Reading |
| 380 | // one is the whole of what "an old project still opens" means here. | 413 | // one is the whole of what "an old project still opens" means here. |
| 381 | let streamless = v1 || first == MAGIC_V2; | 414 | let streamless = v1 || first == MAGIC_V2; |
| 382 | - // The one that carries the mix -- lane volumes, the master limiter and the | 415 | + // The one that carries subtitle tracks... |
| 383 | - // rate the timeline was cut at... | 416 | + let v10 = first == MAGIC; |
| 384 | - let v9 = first == MAGIC; | 417 | + // ...the ones that carry the mix -- lane volumes, the master limiter and |
| 418 | + // the rate the timeline was cut at... | ||
| 419 | + let v9 = v10 || first == MAGIC_V9; | ||
| 385 | // ...the ones that carry a per-clip speed... | 420 | // ...the ones that carry a per-clip speed... |
| 386 | let v8 = v9 || first == MAGIC_V8; | 421 | let v8 = v9 || first == MAGIC_V8; |
| 387 | // ...the ones that carry a project resolution and per-clip fit policies... | 422 | // ...the ones that carry a project resolution and per-clip fit policies... |
| @@ -418,6 +453,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 418 | // ...and nothing before v9 carries a mix or a rate: every lane at unity, | 453 | // ...and nothing before v9 carries a mix or a rate: every lane at unity, |
| 419 | // no limiter, and the rate inferred from the scaffold as it always was. | 454 | // no limiter, and the rate inferred from the scaffold as it always was. |
| 420 | gains: Vec::new(), | 455 | gains: Vec::new(), |
| 456 | + // Nothing before v10 shows a subtitle. | ||
| 457 | + subtitles: Vec::new(), | ||
| 421 | limiter: Limiter::default(), | 458 | limiter: Limiter::default(), |
| 422 | fps: None, | 459 | fps: None, |
| 423 | playhead: 0, | 460 | playhead: 0, |
| @@ -528,6 +565,31 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 528 | doc.gains.resize(doc.lanes.len(), 0.0); | 565 | doc.gains.resize(doc.lanes.len(), 0.0); |
| 529 | doc.gains[at] = float(f[2], n)?; | 566 | doc.gains[at] = float(f[2], n)?; |
| 530 | } | 567 | } |
| 568 | + // Beside the source lines and read the same way: fields first, the | ||
| 569 | + // path last, because a path runs to the end of the line. | ||
| 570 | + b"subtitle" if v10 => { | ||
| 571 | + let at = rest | ||
| 572 | + .iter() | ||
| 573 | + .position(|&b| b == b' ') | ||
| 574 | + .ok_or_else(|| format!("line {n}: subtitle without a path"))?; | ||
| 575 | + let track = match &rest[..at] { | ||
| 576 | + b"-" => None, | ||
| 577 | + field => Some(u64::from(number(field, n)?)), | ||
| 578 | + }; | ||
| 579 | + let path = unescape(&rest[at + 1..], n)?; | ||
| 580 | + if path.as_os_str().is_empty() { | ||
| 581 | + return Err(format!("line {n}: subtitle without a path").into()); | ||
| 582 | + } | ||
| 583 | + doc.subtitles.push(( | ||
| 584 | + // Relative to the project file, as a source path is. | ||
| 585 | + if path.is_absolute() { | ||
| 586 | + path | ||
| 587 | + } else { | ||
| 588 | + dir.join(path) | ||
| 589 | + }, | ||
| 590 | + track, | ||
| 591 | + )); | ||
| 592 | + } | ||
| 531 | b"source" => { | 593 | b"source" => { |
| 532 | if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { | 594 | if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { |
| 533 | return Err(format!("line {n}: source after a clip").into()); | 595 | return Err(format!("line {n}: source after a clip").into()); |
| @@ -963,6 +1025,7 @@ mod tests { | |||
| 963 | sources, | 1025 | sources, |
| 964 | lanes, | 1026 | lanes, |
| 965 | &[], | 1027 | &[], |
| 1028 | + &[], | ||
| 966 | eq, | 1029 | eq, |
| 967 | color, | 1030 | color, |
| 968 | resolution, | 1031 | resolution, |
| @@ -972,6 +1035,84 @@ mod tests { | |||
| 972 | ) | 1035 | ) |
| 973 | } | 1036 | } |
| 974 | 1037 | ||
| 1038 | + /// A subtitle track as a save hands one over: the cues are not written and | ||
| 1039 | + /// so are not here either. | ||
| 1040 | + fn subtitle(path: &str, track: Option<u64>) -> SubtitleTrack { | ||
| 1041 | + SubtitleTrack { | ||
| 1042 | + path: PathBuf::from(path), | ||
| 1043 | + track, | ||
| 1044 | + label: String::new(), | ||
| 1045 | + cues: Vec::new(), | ||
| 1046 | + refused: None, | ||
| 1047 | + } | ||
| 1048 | + } | ||
| 1049 | + | ||
| 1050 | + /// The v10 line: which track of which file, written beside the sources and | ||
| 1051 | + /// read back as the pair a load opens. And what a v9 file is -- one with no | ||
| 1052 | + /// subtitles at all, which still opens and re-saves as v10. | ||
| 1053 | + #[test] | ||
| 1054 | + fn subtitles_round_trip_as_references_and_a_v9_file_has_none() { | ||
| 1055 | + let dir = PathBuf::from("/proj"); | ||
| 1056 | + let (_, sources, lanes) = doc(); | ||
| 1057 | + let tracks = [ | ||
| 1058 | + subtitle("/proj/subs.srt", None), | ||
| 1059 | + subtitle("/proj/a.mp4", Some(3)), | ||
| 1060 | + subtitle("/elsewhere/od d name.ass", None), | ||
| 1061 | + ]; | ||
| 1062 | + let bytes = super::emit( | ||
| 1063 | + &dir, | ||
| 1064 | + &sources, | ||
| 1065 | + &lanes, | ||
| 1066 | + &[], | ||
| 1067 | + &tracks, | ||
| 1068 | + &[], | ||
| 1069 | + &[], | ||
| 1070 | + (1280, 720), | ||
| 1071 | + None, | ||
| 1072 | + Limiter::default(), | ||
| 1073 | + 0, | ||
| 1074 | + ); | ||
| 1075 | + let text = String::from_utf8_lossy(&bytes); | ||
| 1076 | + assert!( | ||
| 1077 | + text.contains( | ||
| 1078 | + "subtitle - subs.srt\n\ | ||
| 1079 | + subtitle 3 a.mp4\n\ | ||
| 1080 | + subtitle - /elsewhere/od d name.ass\n" | ||
| 1081 | + ), | ||
| 1082 | + "the path is relative where it can be, and runs to the end of its \ | ||
| 1083 | + line, spaces and all: {text}" | ||
| 1084 | + ); | ||
| 1085 | + let back = parse(&bytes, &dir).expect("v10 parses"); | ||
| 1086 | + assert_eq!( | ||
| 1087 | + back.subtitles, | ||
| 1088 | + vec![ | ||
| 1089 | + (PathBuf::from("/proj/subs.srt"), None), | ||
| 1090 | + (PathBuf::from("/proj/a.mp4"), Some(3)), | ||
| 1091 | + (PathBuf::from("/elsewhere/od d name.ass"), None), | ||
| 1092 | + ] | ||
| 1093 | + ); | ||
| 1094 | + | ||
| 1095 | + // A v9 file is a project with no subtitles, and re-saving it writes v10. | ||
| 1096 | + let v9 = b"edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ | ||
| 1097 | + video 1 0 0 30 0 - - - fit 1000\n"; | ||
| 1098 | + let old = parse(v9, &dir).expect("v9 still loads"); | ||
| 1099 | + assert_eq!(old.subtitles, Vec::new()); | ||
| 1100 | + assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 10\n")); | ||
| 1101 | + // ...and the line itself is not a v9 line: a dialect may not be mixed. | ||
| 1102 | + let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir) | ||
| 1103 | + .unwrap_err() | ||
| 1104 | + .to_string(); | ||
| 1105 | + assert_eq!(mixed, "line 3: unknown keyword \"subtitle\""); | ||
| 1106 | + // A subtitle line with no path is refused, as a source with none is. | ||
| 1107 | + for line in ["subtitle -\n", "subtitle - \n", "subtitle x subs.srt\n"] { | ||
| 1108 | + let file = format!("edith 10\nsource 0 a.mp4\n{line}"); | ||
| 1109 | + assert!( | ||
| 1110 | + parse(file.as_bytes(), &dir).is_err(), | ||
| 1111 | + "{line:?} is not a subtitle line" | ||
| 1112 | + ); | ||
| 1113 | + } | ||
| 1114 | + } | ||
| 1115 | + | ||
| 975 | fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip { | 1116 | fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip { |
| 976 | Clip { | 1117 | Clip { |
| 977 | start, | 1118 | start, |
| @@ -1032,7 +1173,7 @@ mod tests { | |||
| 1032 | let bytes = flat(&dir, &sources, &lanes, 12); | 1173 | let bytes = flat(&dir, &sources, &lanes, 12); |
| 1033 | assert_eq!( | 1174 | assert_eq!( |
| 1034 | String::from_utf8_lossy(&bytes), | 1175 | String::from_utf8_lossy(&bytes), |
| 1035 | - "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ | 1176 | + "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1036 | source 2 /elsewhere/b.mp4\n\ | 1177 | source 2 /elsewhere/b.mp4\n\ |
| 1037 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ | 1178 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ |
| 1038 | audio 1 0 0 30 0 0 - - fit 1000\n", | 1179 | audio 1 0 0 30 0 0 - - fit 1000\n", |
| @@ -1069,7 +1210,7 @@ mod tests { | |||
| 1069 | let bytes = flat(&dir, &sources, &lanes, 7); | 1210 | let bytes = flat(&dir, &sources, &lanes, 7); |
| 1070 | assert_eq!( | 1211 | assert_eq!( |
| 1071 | String::from_utf8_lossy(&bytes), | 1212 | String::from_utf8_lossy(&bytes), |
| 1072 | - "edith 9\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ | 1213 | + "edith 10\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1073 | video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ | 1214 | video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ |
| 1074 | video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", | 1215 | video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", |
| 1075 | "an empty lane is a line of its own; everything else is its clips" | 1216 | "an empty lane is a line of its own; everything else is its clips" |
| @@ -1177,7 +1318,7 @@ mod tests { | |||
| 1177 | let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); | 1318 | let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); |
| 1178 | assert_eq!( | 1319 | assert_eq!( |
| 1179 | String::from_utf8_lossy(&bytes), | 1320 | String::from_utf8_lossy(&bytes), |
| 1180 | - "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ | 1321 | + "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1181 | eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ | 1322 | eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ |
| 1182 | eq 16777215.0:-0.1:3.918315e-39:hs\n\ | 1323 | eq 16777215.0:-0.1:3.918315e-39:hs\n\ |
| 1183 | eq\n\ | 1324 | eq\n\ |
| @@ -1281,7 +1422,7 @@ mod tests { | |||
| 1281 | let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); | 1422 | let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); |
| 1282 | assert_eq!( | 1423 | assert_eq!( |
| 1283 | String::from_utf8_lossy(&bytes), | 1424 | String::from_utf8_lossy(&bytes), |
| 1284 | - "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ | 1425 | + "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1285 | color 0.1:1.2:0.9:-0.3\n\ | 1426 | color 0.1:1.2:0.9:-0.3\n\ |
| 1286 | color -1e-7:16777215.0:3.918315e-39:-0.0\n\ | 1427 | color -1e-7:16777215.0:3.918315e-39:-0.0\n\ |
| 1287 | color 0.0:1.0:1.0:0.0\n\ | 1428 | color 0.0:1.0:1.0:0.0\n\ |
| @@ -1346,7 +1487,7 @@ mod tests { | |||
| 1346 | (1280, 720), | 1487 | (1280, 720), |
| 1347 | old.playhead | 1488 | old.playhead |
| 1348 | )), | 1489 | )), |
| 1349 | - "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ | 1490 | + "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1350 | eq 80.0:-3.0:0.707:ls\n\ | 1491 | eq 80.0:-3.0:0.707:ls\n\ |
| 1351 | video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" | 1492 | video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" |
| 1352 | ); | 1493 | ); |
| @@ -1384,7 +1525,7 @@ mod tests { | |||
| 1384 | let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); | 1525 | let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); |
| 1385 | assert_eq!( | 1526 | assert_eq!( |
| 1386 | String::from_utf8_lossy(&bytes), | 1527 | String::from_utf8_lossy(&bytes), |
| 1387 | - "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ | 1528 | + "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1388 | video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ | 1529 | video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ |
| 1389 | audio 1 0 0 30 0 - - - fit 2000\n", | 1530 | audio 1 0 0 30 0 - - - fit 2000\n", |
| 1390 | "the rate is the clip line's last field, in thousandths" | 1531 | "the rate is the clip line's last field, in thousandths" |
| @@ -1413,7 +1554,7 @@ mod tests { | |||
| 1413 | (1280, 720), | 1554 | (1280, 720), |
| 1414 | old.playhead | 1555 | old.playhead |
| 1415 | )), | 1556 | )), |
| 1416 | - "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ | 1557 | + "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1417 | video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" | 1558 | video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" |
| 1418 | ); | 1559 | ); |
| 1419 | // A rate outside what the editor can set is a corrupt line, by name. | 1560 | // A rate outside what the editor can set is a corrupt line, by name. |
| @@ -1450,6 +1591,7 @@ mod tests { | |||
| 1450 | &[0.0, 3.0, -6.5], | 1591 | &[0.0, 3.0, -6.5], |
| 1451 | &[], | 1592 | &[], |
| 1452 | &[], | 1593 | &[], |
| 1594 | + &[], | ||
| 1453 | (1280, 720), | 1595 | (1280, 720), |
| 1454 | Some(23.976023976023978), | 1596 | Some(23.976023976023978), |
| 1455 | limiter, | 1597 | limiter, |
| @@ -1457,7 +1599,7 @@ mod tests { | |||
| 1457 | ); | 1599 | ); |
| 1458 | assert_eq!( | 1600 | assert_eq!( |
| 1459 | String::from_utf8_lossy(&bytes), | 1601 | String::from_utf8_lossy(&bytes), |
| 1460 | - "edith 9\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ | 1602 | + "edith 10\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ |
| 1461 | limiter -1.5 on\nsource 0 a.mp4\n\ | 1603 | limiter -1.5 on\nsource 0 a.mp4\n\ |
| 1462 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\ | 1604 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\ |
| 1463 | audio 2 0 0 30 0 - - - fit 1000\n\ | 1605 | audio 2 0 0 30 0 - - - fit 1000\n\ |
| @@ -1489,7 +1631,7 @@ mod tests { | |||
| 1489 | (1280, 720), | 1631 | (1280, 720), |
| 1490 | old.playhead | 1632 | old.playhead |
| 1491 | )), | 1633 | )), |
| 1492 | - "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ | 1634 | + "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1493 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" | 1635 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" |
| 1494 | ); | 1636 | ); |
| 1495 | 1637 | ||
| @@ -1653,7 +1795,7 @@ mod tests { | |||
| 1653 | assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); | 1795 | assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); |
| 1654 | assert_eq!( | 1796 | assert_eq!( |
| 1655 | String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), | 1797 | String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), |
| 1656 | - "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ | 1798 | + "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1657 | source 2 /elsewhere/b.mp4\n\ | 1799 | source 2 /elsewhere/b.mp4\n\ |
| 1658 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ | 1800 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ |
| 1659 | audio 1 0 0 30 0 0 - - fit 1000\n" | 1801 | audio 1 0 0 30 0 0 - - fit 1000\n" |
| @@ -1706,7 +1848,7 @@ mod tests { | |||
| 1706 | let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); | 1848 | let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); |
| 1707 | assert_eq!( | 1849 | assert_eq!( |
| 1708 | String::from_utf8_lossy(&v5), | 1850 | String::from_utf8_lossy(&v5), |
| 1709 | - "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ | 1851 | + "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1710 | source 0 /elsewhere/b.mp4\n\ | 1852 | source 0 /elsewhere/b.mp4\n\ |
| 1711 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ | 1853 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ |
| 1712 | audio 1 0 0 30 0 0 - - fit 1000\n", | 1854 | audio 1 0 0 30 0 0 - - fit 1000\n", |
| @@ -1738,7 +1880,7 @@ mod tests { | |||
| 1738 | // Saved again it is the current version, which round-trips to the | 1880 | // Saved again it is the current version, which round-trips to the |
| 1739 | // same document. | 1881 | // same document. |
| 1740 | let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); | 1882 | let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); |
| 1741 | - assert!(v5.starts_with(b"edith 9\n")); | 1883 | + assert!(v5.starts_with(b"edith 10\n")); |
| 1742 | let again = parse(&v5, &dir).expect("v5 parses"); | 1884 | let again = parse(&v5, &dir).expect("v5 parses"); |
| 1743 | assert_eq!(again.lanes, back.lanes); | 1885 | assert_eq!(again.lanes, back.lanes); |
| 1744 | // A dialect may not be mixed: lane lines under v1, `clip` under v2. | 1886 | // A dialect may not be mixed: lane lines under v1, `clip` under v2. |
| @@ -1834,6 +1976,7 @@ mod tests { | |||
| 1834 | &[], | 1976 | &[], |
| 1835 | &[], | 1977 | &[], |
| 1836 | &[], | 1978 | &[], |
| 1979 | + &[], | ||
| 1837 | (1280, 720), | 1980 | (1280, 720), |
| 1838 | None, | 1981 | None, |
| 1839 | Limiter::default(), | 1982 | Limiter::default(), |
| @@ -1843,7 +1986,7 @@ mod tests { | |||
| 1843 | let bytes = std::fs::read(&path).expect("read back"); | 1986 | let bytes = std::fs::read(&path).expect("read back"); |
| 1844 | assert_eq!( | 1987 | assert_eq!( |
| 1845 | String::from_utf8_lossy(&bytes), | 1988 | String::from_utf8_lossy(&bytes), |
| 1846 | - "edith 9\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ | 1989 | + "edith 10\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ |
| 1847 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" | 1990 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" |
| 1848 | ); | 1991 | ); |
| 1849 | // Loading rejoins the *given* directory, so the file is reached by the | 1992 | // Loading rejoins the *given* directory, so the file is reached by the |
| @@ -1888,10 +2031,10 @@ mod tests { | |||
| 1888 | #[test] | 2031 | #[test] |
| 1889 | fn a_wrong_first_line_is_refused_by_name() { | 2032 | fn a_wrong_first_line_is_refused_by_name() { |
| 1890 | let dir = PathBuf::from("/proj"); | 2033 | let dir = PathBuf::from("/proj"); |
| 1891 | - let err = parse(b"edith 10\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) | 2034 | + let err = parse(b"edith 11\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) |
| 1892 | .unwrap_err() | 2035 | .unwrap_err() |
| 1893 | .to_string(); | 2036 | .to_string(); |
| 1894 | - assert_eq!(err, "line 1: unsupported version 10"); | 2037 | + assert_eq!(err, "line 1: unsupported version 11"); |
| 1895 | for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { | 2038 | for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { |
| 1896 | assert_eq!( | 2039 | assert_eq!( |
| 1897 | parse(junk, &dir).unwrap_err().to_string(), | 2040 | parse(junk, &dir).unwrap_err().to_string(), |
crates/engine/src/lib.rsmodified+1 -0
| @@ -17,6 +17,7 @@ pub mod playback; | |||
| 17 | pub mod project; | 17 | pub mod project; |
| 18 | pub mod scale; | 18 | pub mod scale; |
| 19 | pub mod silence; | 19 | pub mod silence; |
| 20 | +pub mod subtitle; | ||
| 20 | pub mod waveform; | 21 | pub mod waveform; |
| 21 | 22 | ||
| 22 | pub use audio::{ | 23 | pub use audio::{ |
crates/engine/src/playback.rsmodified+56 -1
| @@ -673,8 +673,19 @@ impl PlaybackSession { | |||
| 673 | } | 673 | } |
| 674 | 674 | ||
| 675 | let playhead = doc.playhead; | 675 | let playhead = doc.playhead; |
| 676 | + // The subtitle files are read here rather than in the parser: a | ||
| 677 | + // `.edith` names them and holds no cues. One that has gone missing, or | ||
| 678 | + // whose track is a codec of pictures, comes back listed and refused by | ||
| 679 | + // name ([`crate::subtitle::open`]) -- a project does not stop opening | ||
| 680 | + // over a subtitle, and a re-save does not lose the row. | ||
| 681 | + let subtitles = doc | ||
| 682 | + .subtitles | ||
| 683 | + .iter() | ||
| 684 | + .map(|(path, track)| crate::subtitle::open(path, *track)) | ||
| 685 | + .collect(); | ||
| 676 | let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)? | 686 | let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)? |
| 677 | - .with_mix(&doc.gains, doc.limiter); | 687 | + .with_mix(&doc.gains, doc.limiter) |
| 688 | + .with_subtitles(subtitles); | ||
| 678 | let span = project.composite_span_at(0); | 689 | let span = project.composite_span_at(0); |
| 679 | // Last, because it is the one thing here that cannot be taken back: the | 690 | // Last, because it is the one thing here that cannot be taken back: the |
| 680 | // feeder thread outlives the `Audio` value (it holds its own clones) and | 691 | // feeder thread outlives the `Audio` value (it holds its own clones) and |
| @@ -755,6 +766,47 @@ impl PlaybackSession { | |||
| 755 | self.project.sources() | 766 | self.project.sources() |
| 756 | } | 767 | } |
| 757 | 768 | ||
| 769 | + /// The subtitle tracks on this timeline, in the order they were added: what | ||
| 770 | + /// a front-end lists and what [`save_project`](Self::save_project) writes. | ||
| 771 | + /// A track that could not be read is *in* this list, saying why | ||
| 772 | + /// ([`crate::subtitle::SubtitleTrack::refused`]) -- listed and skipped, not | ||
| 773 | + /// dropped. | ||
| 774 | + pub fn subtitles(&self) -> &[crate::subtitle::SubtitleTrack] { | ||
| 775 | + self.project.subtitles() | ||
| 776 | + } | ||
| 777 | + | ||
| 778 | + /// Adds subtitles from `path`: every subtitle track of a Matroska file, or | ||
| 779 | + /// the one track a standalone `.srt`/`.vtt`/`.ass` is. Hands back how many | ||
| 780 | + /// were added -- 0 for a file whose tracks are all on the timeline already, | ||
| 781 | + /// since importing the same file twice is the same subtitles. | ||
| 782 | + /// | ||
| 783 | + /// An error only when the file cannot be read *at all*; a track this cannot | ||
| 784 | + /// parse is added refused by name, for the reason | ||
| 785 | + /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves: | ||
| 786 | + /// subtitles are not clips and land on no lane. | ||
| 787 | + pub fn import_subtitles(&mut self, path: &Path) -> crate::Result<usize> { | ||
| 788 | + let tracks = match path.extension().is_some_and(|e| { | ||
| 789 | + let e = e.to_string_lossy().to_ascii_lowercase(); | ||
| 790 | + e == "mkv" || e == "webm" | ||
| 791 | + }) { | ||
| 792 | + true => crate::subtitle::of_matroska(path)?, | ||
| 793 | + false => vec![crate::subtitle::open(path, None)], | ||
| 794 | + }; | ||
| 795 | + // A standalone file that could not be parsed is a refusal here rather | ||
| 796 | + // than a row nobody asked for: the import is the moment to say so, and | ||
| 797 | + // the load is the moment to keep it. | ||
| 798 | + if let [one] = &tracks[..] | ||
| 799 | + && one.track.is_none() | ||
| 800 | + && let Some(why) = &one.refused | ||
| 801 | + { | ||
| 802 | + return Err(why.clone().into()); | ||
| 803 | + } | ||
| 804 | + Ok(tracks | ||
| 805 | + .into_iter() | ||
| 806 | + .filter(|t| self.project.add_subtitles(t)) | ||
| 807 | + .count()) | ||
| 808 | + } | ||
| 809 | + | ||
| 758 | /// Writes the timeline to `path` as a `.edith`, atomically (see | 810 | /// Writes the timeline to `path` as a `.edith`, atomically (see |
| 759 | /// [`crate::edith`]). Sources no clip plays from are left out, and the | 811 | /// [`crate::edith`]). Sources no clip plays from are left out, and the |
| 760 | /// playhead is saved with it so a reopened project resumes where it stood. | 812 | /// playhead is saved with it so a reopened project resumes where it stood. |
| @@ -780,6 +832,9 @@ impl PlaybackSession { | |||
| 780 | // project's, not this machine's (the monitoring volume is not | 832 | // project's, not this machine's (the monitoring volume is not |
| 781 | // written and never will be). | 833 | // written and never will be). |
| 782 | &self.project.lane_gains(), | 834 | &self.project.lane_gains(), |
| 835 | + // The subtitle tracks with them, by reference: which file the cues | ||
| 836 | + // are in, never the cues (see [`crate::edith`]). | ||
| 837 | + self.project.subtitles(), | ||
| 783 | &eq, | 838 | &eq, |
| 784 | &color, | 839 | &color, |
| 785 | (self.meta.width, self.meta.height), | 840 | (self.meta.width, self.meta.height), |
crates/engine/src/project.rsmodified+38 -0
| @@ -68,6 +68,7 @@ use crate::color::ColorParams; | |||
| 68 | use crate::eq::EqParams; | 68 | use crate::eq::EqParams; |
| 69 | use crate::limiter::{Limiter, db_to_linear}; | 69 | use crate::limiter::{Limiter, db_to_linear}; |
| 70 | use crate::scale::FitPolicy; | 70 | use crate::scale::FitPolicy; |
| 71 | +use crate::subtitle::SubtitleTrack; | ||
| 71 | 72 | ||
| 72 | /// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]). | 73 | /// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]). |
| 73 | /// -60 dB is a thousandth of the amplitude -- a track that is out of the mix | 74 | /// -60 dB is a thousandth of the amplitude -- a track that is out of the mix |
| @@ -618,6 +619,12 @@ pub struct Project { | |||
| 618 | /// Never rolled back by an undo: an id retired by an undone split must not | 619 | /// Never rolled back by an undo: an id retired by an undone split must not |
| 619 | /// come back and group two clips that were never together. | 620 | /// come back and group two clips that were never together. |
| 620 | next_link: u32, | 621 | next_link: u32, |
| 622 | + /// The subtitle tracks this timeline shows, in the order they were added. | ||
| 623 | + /// Not in the lane list and not in the history snapshots, for the reason | ||
| 624 | + /// the limiter is not: which subtitles a project carries is a setting on | ||
| 625 | + /// it, and it is saved as a *reference* to the file the cues came out of | ||
| 626 | + /// ([`crate::subtitle`]). | ||
| 627 | + subtitles: Vec<SubtitleTrack>, | ||
| 621 | /// The master limiter every lane's sound is summed *through* | 628 | /// The master limiter every lane's sound is summed *through* |
| 622 | /// ([`Project::limiter`]). Off by default, and not in the lane list, which | 629 | /// ([`Project::limiter`]). Off by default, and not in the lane list, which |
| 623 | /// is what the history snapshots hold: it is a setting on the mix, like the | 630 | /// is what the history snapshots hold: it is a setting on the mix, like the |
| @@ -652,6 +659,7 @@ impl Project { | |||
| 652 | color: Vec::new(), | 659 | color: Vec::new(), |
| 653 | history: Vec::new(), | 660 | history: Vec::new(), |
| 654 | next_link: 1, | 661 | next_link: 1, |
| 662 | + subtitles: Vec::new(), | ||
| 655 | limiter: Limiter::default(), | 663 | limiter: Limiter::default(), |
| 656 | } | 664 | } |
| 657 | } | 665 | } |
| @@ -760,6 +768,7 @@ impl Project { | |||
| 760 | color, | 768 | color, |
| 761 | history: Vec::new(), | 769 | history: Vec::new(), |
| 762 | next_link, | 770 | next_link, |
| 771 | + subtitles: Vec::new(), | ||
| 763 | limiter: Limiter::default(), | 772 | limiter: Limiter::default(), |
| 764 | }) | 773 | }) |
| 765 | } | 774 | } |
| @@ -1128,6 +1137,35 @@ impl Project { | |||
| 1128 | self | 1137 | self |
| 1129 | } | 1138 | } |
| 1130 | 1139 | ||
| 1140 | + /// The subtitle tracks a *load* puts back, in the order they were saved -- | ||
| 1141 | + /// the same door [`with_mix`](Project::with_mix) is, and no undo step for | ||
| 1142 | + /// the same reason. | ||
| 1143 | + pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self { | ||
| 1144 | + self.subtitles = tracks; | ||
| 1145 | + self | ||
| 1146 | + } | ||
| 1147 | + | ||
| 1148 | + /// What this timeline shows over the picture, in the order they were added: | ||
| 1149 | + /// what a front-end lists and what a save writes. | ||
| 1150 | + pub fn subtitles(&self) -> &[SubtitleTrack] { | ||
| 1151 | + &self.subtitles | ||
| 1152 | + } | ||
| 1153 | + | ||
| 1154 | + /// Adds a track, unless the very same one -- same file, same track number | ||
| 1155 | + /// inside it -- is already on the list. `false` for that repeat: importing | ||
| 1156 | + /// the same `.srt` twice is one subtitle track, not two identical ones. | ||
| 1157 | + pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool { | ||
| 1158 | + if self | ||
| 1159 | + .subtitles | ||
| 1160 | + .iter() | ||
| 1161 | + .any(|t| t.path == track.path && t.track == track.track) | ||
| 1162 | + { | ||
| 1163 | + return false; | ||
| 1164 | + } | ||
| 1165 | + self.subtitles.push(track.clone()); | ||
| 1166 | + true | ||
| 1167 | + } | ||
| 1168 | + | ||
| 1131 | /// What each of [`audio_segments_from`](Project::audio_segments_from)'s | 1169 | /// What each of [`audio_segments_from`](Project::audio_segments_from)'s |
| 1132 | /// lanes is multiplied by on its way into the mix: the same lanes in the | 1170 | /// lanes is multiplied by on its way into the mix: the same lanes in the |
| 1133 | /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0` | 1171 | /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0` |
crates/engine/src/subtitle.rsadded+344 -0
| @@ -0,0 +1,344 @@ | |||
| 1 | +//! Subtitles: a list of cues with a time on them, out of a file beside the | ||
| 2 | +//! media (`.srt`, `.vtt`, `.ass`) or out of a track inside it. | ||
| 3 | +//! | ||
| 4 | +//! One model for both, because a timeline cannot care which it was: a | ||
| 5 | +//! [`SubtitleTrack`] is where it came from -- a path, and the Matroska track | ||
| 6 | +//! number when it is one of several inside that path -- plus the [`Cue`]s. That | ||
| 7 | +//! pair is also all a `.edith` writes ([`crate::edith`]): the cues are read | ||
| 8 | +//! back out of the file on the way in, exactly as a clip's *pictures* are, so a | ||
| 9 | +//! project file stays an edit list and not a copy of the subtitles. | ||
| 10 | +//! | ||
| 11 | +//! Parsing is `oxideav-subtitle` (SRT, WebVTT) and `oxideav-ass` (ASS/SSA) -- | ||
| 12 | +//! the markup, the override tags and the encoding quirks of a dozen dialects | ||
| 13 | +//! are not this project's to re-derive. What comes back here is plain text: the | ||
| 14 | +//! renderer is a later thing, and a cue nobody can draw yet is still a cue that | ||
| 15 | +//! has to be listed, timed and saved. | ||
| 16 | +//! | ||
| 17 | +//! What is *refused* is refused by name rather than by omission | ||
| 18 | +//! ([`SubtitleTrack::refused`]): the bitmap subtitle formats -- PGS off a | ||
| 19 | +//! BluRay remux, VobSub off a DVD -- are pictures, and a film carrying four of | ||
| 20 | +//! them opens with four rows that say so instead of opening with an empty list. | ||
| 21 | + | ||
| 22 | +use std::path::{Path, PathBuf}; | ||
| 23 | + | ||
| 24 | +use oxideav_subtitle::ir::plain_text; | ||
| 25 | + | ||
| 26 | +/// One line of subtitle: on screen from `start_us` to `end_us`, microseconds | ||
| 27 | +/// from the start of the media, which is the unit every parser here speaks. | ||
| 28 | +#[derive(Clone, Debug, PartialEq, Eq)] | ||
| 29 | +pub struct Cue { | ||
| 30 | + pub start_us: i64, | ||
| 31 | + pub end_us: i64, | ||
| 32 | + /// Plain text, `\n` between the lines of a multi-line cue. The markup is | ||
| 33 | + /// resolved and dropped: `<i>` from an SRT, `{\an8}` and `\N` from an ASS. | ||
| 34 | + /// | ||
| 35 | + /// ponytail: bold/italic/colour and ASS positioning are parsed by the crate | ||
| 36 | + /// and thrown away here, because nothing draws a cue yet. The upgrade path | ||
| 37 | + /// is to keep `oxideav_core::Segment` beside this string -- the parsers | ||
| 38 | + /// already hand it over -- and it belongs to whoever writes the renderer. | ||
| 39 | + pub text: String, | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +/// A subtitle track: where it came from and what it says. | ||
| 43 | +#[derive(Clone, Debug)] | ||
| 44 | +pub struct SubtitleTrack { | ||
| 45 | + /// The file it was read out of: a standalone subtitle file, or the media | ||
| 46 | + /// file whose track number is below. | ||
| 47 | + pub path: PathBuf, | ||
| 48 | + /// Which track of `path`, for one embedded in a Matroska file. `None` when | ||
| 49 | + /// `path` *is* the subtitle file. | ||
| 50 | + pub track: Option<u64>, | ||
| 51 | + /// What a list shows: a language, a muxer's name for the track, or the | ||
| 52 | + /// file's own name for a standalone one. | ||
| 53 | + pub label: String, | ||
| 54 | + /// In start order. Empty when [`refused`](Self::refused) says why. | ||
| 55 | + pub cues: Vec<Cue>, | ||
| 56 | + /// Why this track has no cues, when it has none: a codec that is pictures | ||
| 57 | + /// rather than text, a file that has gone missing since the project was | ||
| 58 | + /// saved. `None` for one that parsed -- which a track with genuinely no | ||
| 59 | + /// cues in it also is. | ||
| 60 | + pub refused: Option<String>, | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +impl SubtitleTrack { | ||
| 64 | + /// A track that is there and cannot be read, named and kept: a project | ||
| 65 | + /// re-saved after one of these still lists it, which is the difference | ||
| 66 | + /// between "your subtitles are missing" and losing them for good. | ||
| 67 | + fn refused(path: &Path, track: Option<u64>, label: String, why: String) -> Self { | ||
| 68 | + Self { | ||
| 69 | + path: path.to_path_buf(), | ||
| 70 | + track, | ||
| 71 | + label, | ||
| 72 | + cues: Vec::new(), | ||
| 73 | + refused: Some(why), | ||
| 74 | + } | ||
| 75 | + } | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// The one door a saved subtitle line comes back in through: a standalone file | ||
| 79 | +/// (`track` is `None`) or track `n` of a Matroska file. | ||
| 80 | +/// | ||
| 81 | +/// Never an error, whatever is wrong: a deleted `.srt`, a media file that is | ||
| 82 | +/// not there any more, a track number the file no longer has, a codec of | ||
| 83 | +/// pictures. All of them come back [`refused`](SubtitleTrack::refused) by name, | ||
| 84 | +/// because a project that opened yesterday has to open today -- a subtitle is | ||
| 85 | +/// not what a whole timeline should refuse over. | ||
| 86 | +pub fn open(path: &Path, track: Option<u64>) -> SubtitleTrack { | ||
| 87 | + let Some(number) = track else { | ||
| 88 | + return external(path); | ||
| 89 | + }; | ||
| 90 | + let label = format!("track {number}"); | ||
| 91 | + let mut tracks = match of_matroska(path) { | ||
| 92 | + Ok(tracks) => tracks, | ||
| 93 | + Err(why) => return SubtitleTrack::refused(path, track, label, why.to_string()), | ||
| 94 | + }; | ||
| 95 | + match tracks.iter().position(|t| t.track == Some(number)) { | ||
| 96 | + Some(i) => tracks.swap_remove(i), | ||
| 97 | + None => SubtitleTrack::refused( | ||
| 98 | + path, | ||
| 99 | + track, | ||
| 100 | + label, | ||
| 101 | + format!("no subtitle track {number} in {} any more", path.display()), | ||
| 102 | + ), | ||
| 103 | + } | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// A standalone subtitle file, parsed by its extension. | ||
| 107 | +fn external(path: &Path) -> SubtitleTrack { | ||
| 108 | + let label = path | ||
| 109 | + .file_name() | ||
| 110 | + .map(|n| n.to_string_lossy().into_owned()) | ||
| 111 | + .unwrap_or_default(); | ||
| 112 | + match parse_file(path) { | ||
| 113 | + Ok(cues) => SubtitleTrack { | ||
| 114 | + path: path.to_path_buf(), | ||
| 115 | + track: None, | ||
| 116 | + label, | ||
| 117 | + cues, | ||
| 118 | + refused: None, | ||
| 119 | + }, | ||
| 120 | + Err(why) => SubtitleTrack::refused(path, None, label, why.to_string()), | ||
| 121 | + } | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// Every subtitle track of a Matroska file, in file order -- the text ones with | ||
| 125 | +/// their cues, the bitmap ones refused by name (see the module docs). | ||
| 126 | +pub fn of_matroska(path: &Path) -> crate::Result<Vec<SubtitleTrack>> { | ||
| 127 | + Ok(crate::demux::matroska_subtitles(path)? | ||
| 128 | + .into_iter() | ||
| 129 | + .map(|t| { | ||
| 130 | + let label = match (t.name.is_empty(), t.language.as_str()) { | ||
| 131 | + (true, lang) => lang.to_owned(), | ||
| 132 | + (false, "und") => t.name.clone(), | ||
| 133 | + (false, lang) => format!("{lang} — {}", t.name), | ||
| 134 | + }; | ||
| 135 | + match cues_of(&t) { | ||
| 136 | + Ok(cues) => SubtitleTrack { | ||
| 137 | + path: path.to_path_buf(), | ||
| 138 | + track: Some(t.number), | ||
| 139 | + label, | ||
| 140 | + cues, | ||
| 141 | + refused: None, | ||
| 142 | + }, | ||
| 143 | + Err(why) => SubtitleTrack::refused(path, Some(t.number), label, why), | ||
| 144 | + } | ||
| 145 | + }) | ||
| 146 | + .collect()) | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +/// The cues of one Matroska subtitle track, or why it has none. | ||
| 150 | +/// | ||
| 151 | +/// A Matroska text track carries the *timing* on the block and the *text* in | ||
| 152 | +/// it, so neither codec is parsed as its own file would be: `S_TEXT/UTF8` is | ||
| 153 | +/// one SRT cue's body per block, `S_TEXT/ASS` is one `Dialogue` line per block | ||
| 154 | +/// with the `Start` and `End` fields cut out and the `[Script Info]` header | ||
| 155 | +/// filed away in `CodecPrivate`. Both are put back into the shape their parser | ||
| 156 | +/// reads -- rather than the markup being re-derived here -- which is also what | ||
| 157 | +/// makes an embedded track and the standalone file it was muxed from come back | ||
| 158 | +/// as the same cues. | ||
| 159 | +fn cues_of(track: &crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> { | ||
| 160 | + let cues = match track.codec.as_str() { | ||
| 161 | + "S_TEXT/UTF8" | "S_TEXT/ASCII" => track | ||
| 162 | + .cues | ||
| 163 | + .iter() | ||
| 164 | + .map(|c| Cue { | ||
| 165 | + start_us: c.start_us, | ||
| 166 | + end_us: end_of(track, c), | ||
| 167 | + text: srt_body(&String::from_utf8_lossy(&c.payload)), | ||
| 168 | + }) | ||
| 169 | + .collect(), | ||
| 170 | + "S_TEXT/ASS" | "S_TEXT/SSA" => ass_cues(track)?, | ||
| 171 | + codec => { | ||
| 172 | + return Err(format!( | ||
| 173 | + "{codec} subtitles are pictures, not text — this track is listed, not read" | ||
| 174 | + )); | ||
| 175 | + } | ||
| 176 | + }; | ||
| 177 | + Ok(cues) | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +/// When a cue goes away: its `BlockDuration`, or -- for the muxer that writes | ||
| 181 | +/// none -- when the next one arrives, and [`NO_DURATION_US`] for the last. | ||
| 182 | +fn end_of(track: &crate::demux::MkvSubtitle, cue: &crate::demux::MkvCue) -> i64 { | ||
| 183 | + /// How long a cue with nothing to say about it stays up: two seconds, a | ||
| 184 | + /// read of one line. | ||
| 185 | + const NO_DURATION_US: i64 = 2_000_000; | ||
| 186 | + match cue.duration_us { | ||
| 187 | + Some(d) => cue.start_us + d, | ||
| 188 | + None => track | ||
| 189 | + .cues | ||
| 190 | + .iter() | ||
| 191 | + .map(|c| c.start_us) | ||
| 192 | + .find(|&s| s > cue.start_us) | ||
| 193 | + .unwrap_or(cue.start_us + NO_DURATION_US), | ||
| 194 | + } | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +/// The text of one `S_TEXT/UTF8` block with its markup resolved: through the | ||
| 198 | +/// SRT parser, around a timing line this then throws away, because SRT markup | ||
| 199 | +/// is exactly what such a block holds and a second implementation of it here | ||
| 200 | +/// would be a second set of bugs. | ||
| 201 | +fn srt_body(text: &str) -> String { | ||
| 202 | + let doc = format!("1\n00:00:00,000 --> 00:00:01,000\n{}\n", text.trim_end()); | ||
| 203 | + match oxideav_subtitle::srt::parse(doc.as_bytes()) { | ||
| 204 | + Ok(track) => track | ||
| 205 | + .cues | ||
| 206 | + .first() | ||
| 207 | + .map(|c| plain_text(&c.segments)) | ||
| 208 | + .unwrap_or_default(), | ||
| 209 | + // The parser refuses nothing an SRT body can hold; if it ever does, | ||
| 210 | + // the bytes themselves are a better answer than an empty cue. | ||
| 211 | + Err(_) => text.trim_end().to_owned(), | ||
| 212 | + } | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +/// The cues of an `S_TEXT/ASS` track: the script header out of `CodecPrivate` | ||
| 216 | +/// with every block put back as a `Dialogue` line under it, parsed once as the | ||
| 217 | +/// `.ass` file it came from. | ||
| 218 | +fn ass_cues(track: &crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> { | ||
| 219 | + let mut doc = String::from_utf8_lossy(&track.private).into_owned(); | ||
| 220 | + if !doc.ends_with('\n') { | ||
| 221 | + doc.push('\n'); | ||
| 222 | + } | ||
| 223 | + for cue in &track.cues { | ||
| 224 | + let fields = String::from_utf8_lossy(&cue.payload); | ||
| 225 | + // `ReadOrder,Layer,<the Format fields from Style on>`: the two the | ||
| 226 | + // block adds go, and the timing the block *is* takes their place. The | ||
| 227 | + // field order is the one the header's `Format:` line declares, which | ||
| 228 | + // is the order a demuxer strips them out of. | ||
| 229 | + let mut rest = fields.trim_end().splitn(3, ','); | ||
| 230 | + let (_read_order, layer, rest) = match (rest.next(), rest.next(), rest.next()) { | ||
| 231 | + (Some(r), Some(l), Some(t)) => (r, l, t), | ||
| 232 | + _ => continue, | ||
| 233 | + }; | ||
| 234 | + doc.push_str(&format!( | ||
| 235 | + "Dialogue: {layer},{},{},{rest}\n", | ||
| 236 | + timestamp(cue.start_us), | ||
| 237 | + timestamp(end_of(track, cue)) | ||
| 238 | + )); | ||
| 239 | + } | ||
| 240 | + let parsed = oxideav_ass::parse(doc.as_bytes()).map_err(|e| e.to_string())?; | ||
| 241 | + // The timings above are centiseconds, which is all an ASS line can say; | ||
| 242 | + // the blocks are microseconds. So the text comes from the parse and the | ||
| 243 | + // timing from the block -- unless a line was dropped as unparsable, when | ||
| 244 | + // the pairing is no longer sound and the parse answers for both. | ||
| 245 | + let exact = parsed.cues.len() == track.cues.len(); | ||
| 246 | + Ok(parsed | ||
| 247 | + .cues | ||
| 248 | + .iter() | ||
| 249 | + .enumerate() | ||
| 250 | + .map(|(i, c)| Cue { | ||
| 251 | + start_us: if exact { | ||
| 252 | + track.cues[i].start_us | ||
| 253 | + } else { | ||
| 254 | + c.start_us | ||
| 255 | + }, | ||
| 256 | + end_us: if exact { | ||
| 257 | + end_of(track, &track.cues[i]) | ||
| 258 | + } else { | ||
| 259 | + c.end_us | ||
| 260 | + }, | ||
| 261 | + text: plain_text(&c.segments), | ||
| 262 | + }) | ||
| 263 | + .collect()) | ||
| 264 | +} | ||
| 265 | + | ||
| 266 | +/// Microseconds as ASS writes a time: `H:MM:SS.cc`. | ||
| 267 | +fn timestamp(us: i64) -> String { | ||
| 268 | + let cs = (us.max(0) + 5_000) / 10_000; | ||
| 269 | + format!( | ||
| 270 | + "{}:{:02}:{:02}.{:02}", | ||
| 271 | + cs / 360_000, | ||
| 272 | + cs / 6_000 % 60, | ||
| 273 | + cs / 100 % 60, | ||
| 274 | + cs % 100 | ||
| 275 | + ) | ||
| 276 | +} | ||
| 277 | + | ||
| 278 | +/// A standalone subtitle file, by extension: the formats this engine reads at | ||
| 279 | +/// all. Anything else is refused by name, as an unknown media file is. | ||
| 280 | +fn parse_file(path: &Path) -> crate::Result<Vec<Cue>> { | ||
| 281 | + let ext = path | ||
| 282 | + .extension() | ||
| 283 | + .map(|e| e.to_string_lossy().to_ascii_lowercase()) | ||
| 284 | + .unwrap_or_default(); | ||
| 285 | + // The extension before the read: a `.txt` is refused for what it is, not | ||
| 286 | + // for whether it happens to be there. | ||
| 287 | + type Parse = fn(&[u8]) -> oxideav_core::Result<oxideav_subtitle::ir::SubtitleTrack>; | ||
| 288 | + let parse: Parse = match ext.as_str() { | ||
| 289 | + "srt" => oxideav_subtitle::srt::parse, | ||
| 290 | + "vtt" | "webvtt" => oxideav_subtitle::webvtt::parse, | ||
| 291 | + "ass" | "ssa" => oxideav_ass::parse, | ||
| 292 | + other => { | ||
| 293 | + return Err(format!( | ||
| 294 | + "{other:?} is not a subtitle format this reads — .srt, .vtt, .ass and .ssa are" | ||
| 295 | + ) | ||
| 296 | + .into()); | ||
| 297 | + } | ||
| 298 | + }; | ||
| 299 | + let track = parse(&std::fs::read(path)?); | ||
| 300 | + let track = track.map_err(|e| format!("{}: {e}", path.display()))?; | ||
| 301 | + Ok(track | ||
| 302 | + .cues | ||
| 303 | + .iter() | ||
| 304 | + .map(|c| Cue { | ||
| 305 | + start_us: c.start_us, | ||
| 306 | + end_us: c.end_us, | ||
| 307 | + text: plain_text(&c.segments), | ||
| 308 | + }) | ||
| 309 | + .collect()) | ||
| 310 | +} | ||
| 311 | + | ||
| 312 | +#[cfg(test)] | ||
| 313 | +mod tests { | ||
| 314 | + use super::*; | ||
| 315 | + | ||
| 316 | + #[test] | ||
| 317 | + fn ass_timestamps_are_written_the_way_ass_reads_them() { | ||
| 318 | + assert_eq!(timestamp(0), "0:00:00.00"); | ||
| 319 | + assert_eq!(timestamp(500_000), "0:00:00.50"); | ||
| 320 | + assert_eq!(timestamp(3_250_000), "0:00:03.25"); | ||
| 321 | + // An hour, a minute and a second, and a negative time is not one. | ||
| 322 | + assert_eq!(timestamp(3_661_000_000), "1:01:01.00"); | ||
| 323 | + assert_eq!(timestamp(-1), "0:00:00.00"); | ||
| 324 | + } | ||
| 325 | + | ||
| 326 | + #[test] | ||
| 327 | + fn srt_markup_is_resolved_not_carried() { | ||
| 328 | + assert_eq!(srt_body("<i>tilted</i> and plain"), "tilted and plain"); | ||
| 329 | + assert_eq!(srt_body("two\nlines\n"), "two\nlines"); | ||
| 330 | + } | ||
| 331 | + | ||
| 332 | + #[test] | ||
| 333 | + fn an_unknown_extension_is_refused_by_name_and_a_missing_file_is_kept() { | ||
| 334 | + let err = parse_file(Path::new("/nonexistent/notes.txt")) | ||
| 335 | + .unwrap_err() | ||
| 336 | + .to_string(); | ||
| 337 | + assert!(err.contains("txt"), "{err}"); | ||
| 338 | + // ...and a `.srt` that is not there comes back as a track that says so | ||
| 339 | + // rather than as no track at all, so a re-save does not lose it. | ||
| 340 | + let gone = external(Path::new("/nonexistent/subs.srt")); | ||
| 341 | + assert!(gone.refused.is_some()); | ||
| 342 | + assert_eq!(gone.label, "subs.srt"); | ||
| 343 | + } | ||
| 344 | +} | ||
crates/engine/tests/data/test_subs.assadded+14 -0
| @@ -0,0 +1,14 @@ | |||
| 1 | +[Script Info] | ||
| 2 | +ScriptType: v4.00+ | ||
| 3 | +PlayResX: 384 | ||
| 4 | +PlayResY: 288 | ||
| 5 | + | ||
| 6 | +[V4+ Styles] | ||
| 7 | +Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding | ||
| 8 | +Style: Default,Arial,16,&Hffffff,&Hffffff,&H0,&H0,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,1 | ||
| 9 | + | ||
| 10 | +[Events] | ||
| 11 | +Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text | ||
| 12 | +Dialogue: 0,0:00:00.50,0:00:01.50,Default,,0,0,0,,first line | ||
| 13 | +Dialogue: 0,0:00:02.00,0:00:03.25,Default,,0,0,0,,second line\Nwith a break | ||
| 14 | +Dialogue: 0,0:00:04.00,0:00:04.75,Default,,0,0,0,,{\i1}third{\i0} line | ||
crates/engine/tests/data/test_subs.srtadded+12 -0
| @@ -0,0 +1,12 @@ | |||
| 1 | +1 | ||
| 2 | +00:00:00,500 --> 00:00:01,500 | ||
| 3 | +first line | ||
| 4 | + | ||
| 5 | +2 | ||
| 6 | +00:00:02,000 --> 00:00:03,250 | ||
| 7 | +second line | ||
| 8 | +with a break | ||
| 9 | + | ||
| 10 | +3 | ||
| 11 | +00:00:04,000 --> 00:00:04,750 | ||
| 12 | +third line | ||
crates/engine/tests/saveload.rsmodified+7 -7
| @@ -209,7 +209,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() { | |||
| 209 | let v2 = dir.join("new.edith"); | 209 | let v2 = dir.join("new.edith"); |
| 210 | loaded.save_project(&v2).expect("save"); | 210 | loaded.save_project(&v2).expect("save"); |
| 211 | let text = std::fs::read_to_string(&v2).expect("read back"); | 211 | let text = std::fs::read_to_string(&v2).expect("read back"); |
| 212 | - assert!(text.starts_with("edith 9\n"), "{text}"); | 212 | + assert!(text.starts_with("edith 10\n"), "{text}"); |
| 213 | assert!( | 213 | assert!( |
| 214 | text.contains("\nresolution 1280 720\n"), | 214 | text.contains("\nresolution 1280 720\n"), |
| 215 | "a project with no resolution of its own is saved at source 0's: {text}" | 215 | "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() { | |||
| 297 | loaded.save_project(&again).expect("save"); | 297 | loaded.save_project(&again).expect("save"); |
| 298 | assert_eq!( | 298 | assert_eq!( |
| 299 | std::fs::read_to_string(&again).expect("read back"), | 299 | std::fs::read_to_string(&again).expect("read back"), |
| 300 | - "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ | 300 | + "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ |
| 301 | video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\ | 301 | video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\ |
| 302 | video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n", | 302 | video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n", |
| 303 | "a four-lane project is written as it was read, three versions on" | 303 | "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() { | |||
| 327 | loaded.save_project(&again).expect("save"); | 327 | loaded.save_project(&again).expect("save"); |
| 328 | assert_eq!( | 328 | assert_eq!( |
| 329 | std::fs::read_to_string(&again).expect("read back"), | 329 | std::fs::read_to_string(&again).expect("read back"), |
| 330 | - "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ | 330 | + "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ |
| 331 | eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ | 331 | eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ |
| 332 | eq 12000.0:6.25:0.5:hs\n\ | 332 | eq 12000.0:6.25:0.5:hs\n\ |
| 333 | video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\ | 333 | 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() { | |||
| 362 | loaded.save_project(&again).expect("save"); | 362 | loaded.save_project(&again).expect("save"); |
| 363 | assert_eq!( | 363 | assert_eq!( |
| 364 | std::fs::read_to_string(&again).expect("read back"), | 364 | std::fs::read_to_string(&again).expect("read back"), |
| 365 | - "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ | 365 | + "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ |
| 366 | eq 80.0:-3.0:0.707:ls\n\ | 366 | eq 80.0:-3.0:0.707:ls\n\ |
| 367 | color 0.1:1.2:0.9:-0.3\n\ | 367 | color 0.1:1.2:0.9:-0.3\n\ |
| 368 | color -0.25:1.0:0.0:0.5\n\ | 368 | 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() { | |||
| 412 | loaded.save_project(&again).expect("save"); | 412 | loaded.save_project(&again).expect("save"); |
| 413 | assert_eq!( | 413 | assert_eq!( |
| 414 | std::fs::read_to_string(&again).expect("read back"), | 414 | std::fs::read_to_string(&again).expect("read back"), |
| 415 | - "edith 9\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\ | 415 | + "edith 10\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\ |
| 416 | video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\ | 416 | video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\ |
| 417 | audio 1 0 0 60 0 - - - fit 1000\n", | 417 | audio 1 0 0 60 0 - - - fit 1000\n", |
| 418 | "a v7 project is written back as the v8 it now is: the same clips, each \ | 418 | "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() { | |||
| 670 | 670 | ||
| 671 | for (text, want) in [ | 671 | for (text, want) in [ |
| 672 | ( | 672 | ( |
| 673 | - "edith 10\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", | 673 | + "edith 11\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", |
| 674 | "line 1", | 674 | "line 1", |
| 675 | ), | 675 | ), |
| 676 | // An eq index the table does not hold, and a band shape there is none. | 676 | // 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() { | |||
| 806 | let path = dir.join("song.edith"); | 806 | let path = dir.join("song.edith"); |
| 807 | std::fs::write( | 807 | std::fs::write( |
| 808 | &path, | 808 | &path, |
| 809 | - "edith 9\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\ | 809 | + "edith 10\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\ |
| 810 | video 1\naudio 1 0 0 24 0 - - - fit 1000\n", | 810 | video 1\naudio 1 0 0 24 0 - - - fit 1000\n", |
| 811 | ) | 811 | ) |
| 812 | .expect("write a v9 song project"); | 812 | .expect("write a v9 song project"); |
crates/engine/tests/silence.rsmodified+2 -1
| @@ -365,6 +365,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() { | |||
| 365 | &sources, | 365 | &sources, |
| 366 | &lanes, | 366 | &lanes, |
| 367 | &p.lane_gains(), | 367 | &p.lane_gains(), |
| 368 | + p.subtitles(), | ||
| 368 | &eq, | 369 | &eq, |
| 369 | &color, | 370 | &color, |
| 370 | (1920, 1080), | 371 | (1920, 1080), |
| @@ -375,7 +376,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() { | |||
| 375 | .expect("save"); | 376 | .expect("save"); |
| 376 | let text = std::fs::read_to_string(&file).expect("read it back"); | 377 | let text = std::fs::read_to_string(&file).expect("read it back"); |
| 377 | assert!( | 378 | assert!( |
| 378 | - text.starts_with("edith 9"), | 379 | + text.starts_with("edith 10"), |
| 379 | "{:?}", | 380 | "{:?}", |
| 380 | &text[..16.min(text.len())] | 381 | &text[..16.min(text.len())] |
| 381 | ); | 382 | ); |
crates/engine/tests/subtitles.rsadded+237 -0
| @@ -0,0 +1,237 @@ | |||
| 1 | +//! Subtitles: the cues of a file beside the media and of a track inside it are | ||
| 2 | +//! the same cues, a project keeps them across a save, and the formats that are | ||
| 3 | +//! pictures rather than text are listed and skipped by name rather than | ||
| 4 | +//! silently dropped. | ||
| 5 | +//! | ||
| 6 | +//! ```text | ||
| 7 | +//! cargo test -p engine --release --test subtitles -- --nocapture | ||
| 8 | +//! ``` | ||
| 9 | + | ||
| 10 | +use std::path::PathBuf; | ||
| 11 | + | ||
| 12 | +use engine::subtitle::{self, Cue}; | ||
| 13 | + | ||
| 14 | +fn asset(name: &str) -> PathBuf { | ||
| 15 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 16 | + .join("../../assets") | ||
| 17 | + .join(name) | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +fn data(name: &str) -> PathBuf { | ||
| 21 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 22 | + .join("tests/data") | ||
| 23 | + .join(name) | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +fn scratch(name: &str) -> PathBuf { | ||
| 27 | + let dir = std::env::temp_dir().join(format!("ve_subs_{name}_{}", std::process::id())); | ||
| 28 | + let _ = std::fs::remove_dir_all(&dir); | ||
| 29 | + std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 30 | + std::fs::canonicalize(&dir).expect("canonical scratch dir") | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +/// The three cues both hand-written fixtures hold, with the markup resolved: | ||
| 34 | +/// the italics of the `.ass` third line are not text, and the `\N` of its | ||
| 35 | +/// second one is a line break like the `.srt`'s. | ||
| 36 | +fn expected() -> Vec<Cue> { | ||
| 37 | + vec![ | ||
| 38 | + Cue { | ||
| 39 | + start_us: 500_000, | ||
| 40 | + end_us: 1_500_000, | ||
| 41 | + text: "first line".into(), | ||
| 42 | + }, | ||
| 43 | + Cue { | ||
| 44 | + start_us: 2_000_000, | ||
| 45 | + end_us: 3_250_000, | ||
| 46 | + text: "second line\nwith a break".into(), | ||
| 47 | + }, | ||
| 48 | + Cue { | ||
| 49 | + start_us: 4_000_000, | ||
| 50 | + end_us: 4_750_000, | ||
| 51 | + text: "third line".into(), | ||
| 52 | + }, | ||
| 53 | + ] | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +/// The whole of the parse half: four routes to the same three cues -- an | ||
| 57 | +/// `.srt`, an `.ass` with override tags in it, and the two tracks of the | ||
| 58 | +/// Matroska file both were muxed into, whose timing lives on the block and | ||
| 59 | +/// whose text lives in it. | ||
| 60 | +#[test] | ||
| 61 | +fn a_file_beside_the_media_and_a_track_inside_it_read_the_same() { | ||
| 62 | + let srt = subtitle::open(&data("test_subs.srt"), None); | ||
| 63 | + assert_eq!(srt.refused, None, "the .srt parses"); | ||
| 64 | + assert_eq!(srt.cues, expected()); | ||
| 65 | + assert_eq!(srt.label, "test_subs.srt"); | ||
| 66 | + | ||
| 67 | + let ass = subtitle::open(&data("test_subs.ass"), None); | ||
| 68 | + assert_eq!(ass.refused, None, "the .ass parses"); | ||
| 69 | + assert_eq!(ass.cues, expected(), "the override tags are resolved"); | ||
| 70 | + | ||
| 71 | + let embedded = subtitle::of_matroska(&asset("test_subs.mkv")).expect("the mkv is walked"); | ||
| 72 | + let text: Vec<_> = embedded.iter().map(|t| (&t.label, &t.cues)).collect(); | ||
| 73 | + assert_eq!(embedded.len(), 2, "two subtitle tracks: {text:?}"); | ||
| 74 | + for track in &embedded { | ||
| 75 | + assert_eq!(track.refused, None, "{} parses", track.label); | ||
| 76 | + assert_eq!( | ||
| 77 | + track.cues, | ||
| 78 | + expected(), | ||
| 79 | + "{} holds the same cues", | ||
| 80 | + track.label | ||
| 81 | + ); | ||
| 82 | + } | ||
| 83 | + // ...and each is named by what the file says about it, so a list has | ||
| 84 | + // something to show but the track number. | ||
| 85 | + assert_eq!(embedded[0].label, "eng"); | ||
| 86 | + assert_eq!(embedded[1].label, "fra — Signs"); | ||
| 87 | + assert_eq!(embedded[0].track, Some(2)); | ||
| 88 | + assert_eq!(embedded[1].track, Some(3)); | ||
| 89 | + | ||
| 90 | + // The one door a saved line comes back through reaches the same track. | ||
| 91 | + let one = subtitle::open(&asset("test_subs.mkv"), Some(3)); | ||
| 92 | + assert_eq!(one.cues, expected()); | ||
| 93 | + // A track number the file does not have is refused by name, not an error: | ||
| 94 | + // the project it was saved in still opens. | ||
| 95 | + let gone = subtitle::open(&asset("test_subs.mkv"), Some(9)); | ||
| 96 | + assert!( | ||
| 97 | + gone.refused.as_deref().unwrap_or_default().contains("9"), | ||
| 98 | + "{:?}", | ||
| 99 | + gone.refused | ||
| 100 | + ); | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +/// A subtitle track this cannot read is a row that says why -- never an error | ||
| 104 | +/// that takes the whole file down with it. The repro is a BluRay remux | ||
| 105 | +/// carrying four PGS tracks: opening it lists four subtitles it cannot draw, | ||
| 106 | +/// and the picture and the sound come up regardless. | ||
| 107 | +/// | ||
| 108 | +/// Written here rather than muxed by the fixture script because ffmpeg cannot | ||
| 109 | +/// encode text subtitles into pictures; the bytes below are the `Tracks` | ||
| 110 | +/// element of such a file and nothing else. | ||
| 111 | +#[test] | ||
| 112 | +fn bitmap_subtitles_are_listed_and_skipped_by_name() { | ||
| 113 | + let dir = scratch("pgs"); | ||
| 114 | + let file = dir.join("remux.mkv"); | ||
| 115 | + std::fs::write(&file, pgs_matroska()).expect("write the hand-made mkv"); | ||
| 116 | + | ||
| 117 | + let tracks = subtitle::of_matroska(&file).expect("the walk does not fail over them"); | ||
| 118 | + assert_eq!(tracks.len(), 4, "every PGS track is listed"); | ||
| 119 | + for (i, track) in tracks.iter().enumerate() { | ||
| 120 | + assert_eq!(track.track, Some(i as u64 + 1)); | ||
| 121 | + assert_eq!(track.cues, Vec::new(), "no cues to have"); | ||
| 122 | + let why = track.refused.clone().unwrap_or_default(); | ||
| 123 | + assert!( | ||
| 124 | + why.contains("S_HDMV/PGS") && why.contains("pictures"), | ||
| 125 | + "the refusal names the codec: {why:?}" | ||
| 126 | + ); | ||
| 127 | + } | ||
| 128 | + // The language is what a list shows, and `und` is what the spec says a | ||
| 129 | + // track that names none is. | ||
| 130 | + assert_eq!(tracks[0].label, "eng"); | ||
| 131 | + assert_eq!(tracks[3].label, "und"); | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// A saved project comes back with its subtitles: the `.edith` names the file | ||
| 135 | +/// and the track, and the cues are read out of them again on the way in. The | ||
| 136 | +/// engine's own door for both halves -- import, save, open -- since that is | ||
| 137 | +/// what a front-end will drive. | ||
| 138 | +#[test] | ||
| 139 | +fn a_project_keeps_its_subtitles_across_a_save() { | ||
| 140 | + let dir = scratch("save"); | ||
| 141 | + let media = dir.join("test_av.mp4"); | ||
| 142 | + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); | ||
| 143 | + // Beside the media, which is where a subtitle file lives: the project then | ||
| 144 | + // writes it relative, and the whole folder stays movable. | ||
| 145 | + let subs = dir.join("test_subs.srt"); | ||
| 146 | + std::fs::copy(data("test_subs.srt"), &subs).expect("copy the subtitle fixture"); | ||
| 147 | + | ||
| 148 | + let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); | ||
| 149 | + session.set_gain(0.0); // silent like the rest of the suites | ||
| 150 | + assert_eq!(session.subtitles().len(), 0, "nothing to start with"); | ||
| 151 | + assert_eq!( | ||
| 152 | + session.import_subtitles(&subs).expect("the .srt imports"), | ||
| 153 | + 1 | ||
| 154 | + ); | ||
| 155 | + // The same file twice is the same subtitles, not two rows of them. | ||
| 156 | + assert_eq!(session.import_subtitles(&subs).expect("no error"), 0); | ||
| 157 | + assert_eq!(session.subtitles()[0].cues, expected()); | ||
| 158 | + | ||
| 159 | + let project = dir.join("cut.edith"); | ||
| 160 | + session.save_project(&project).expect("save"); | ||
| 161 | + let text = std::fs::read_to_string(&project).expect("read the project back"); | ||
| 162 | + assert!(text.starts_with("edith 10\n"), "{text}"); | ||
| 163 | + assert!( | ||
| 164 | + text.contains("\nsubtitle - test_subs.srt\n"), | ||
| 165 | + "the reference is written relative, and no cue is: {text}" | ||
| 166 | + ); | ||
| 167 | + | ||
| 168 | + let back = engine::PlaybackSession::open_project(&project).expect("open the project"); | ||
| 169 | + assert_eq!(back.subtitles().len(), 1); | ||
| 170 | + assert_eq!(back.subtitles()[0].cues, expected()); | ||
| 171 | + assert_eq!(back.subtitles()[0].track, None); | ||
| 172 | + drop(back); | ||
| 173 | + | ||
| 174 | + // A subtitle file that has gone missing is listed, refused by name, and | ||
| 175 | + // written out again: the project still opens and the row is not lost. | ||
| 176 | + std::fs::remove_file(&subs).expect("take the subtitles away"); | ||
| 177 | + let gone = engine::PlaybackSession::open_project(&project).expect("the project still opens"); | ||
| 178 | + assert_eq!(gone.subtitles().len(), 1); | ||
| 179 | + assert!(gone.subtitles()[0].refused.is_some()); | ||
| 180 | + let again = dir.join("cut2.edith"); | ||
| 181 | + gone.save_project(&again).expect("save again"); | ||
| 182 | + assert!( | ||
| 183 | + std::fs::read_to_string(&again) | ||
| 184 | + .expect("read") | ||
| 185 | + .contains("\nsubtitle - test_subs.srt\n"), | ||
| 186 | + "a re-save keeps the row" | ||
| 187 | + ); | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +/// A refusal a front-end shows at the moment of the import, rather than a row | ||
| 191 | +/// nobody asked for: a file that is not a subtitle format at all. | ||
| 192 | +#[test] | ||
| 193 | +fn importing_something_that_is_not_a_subtitle_says_so() { | ||
| 194 | + let dir = scratch("refuse"); | ||
| 195 | + let media = dir.join("test_av.mp4"); | ||
| 196 | + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); | ||
| 197 | + let notes = dir.join("notes.txt"); | ||
| 198 | + std::fs::write(¬es, "not a subtitle").expect("write"); | ||
| 199 | + | ||
| 200 | + let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); | ||
| 201 | + session.set_gain(0.0); | ||
| 202 | + let err = session | ||
| 203 | + .import_subtitles(¬es) | ||
| 204 | + .expect_err("a .txt is not a subtitle") | ||
| 205 | + .to_string(); | ||
| 206 | + assert!(err.contains("txt"), "{err}"); | ||
| 207 | + assert_eq!(session.subtitles().len(), 0, "and nothing was added"); | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +/// The `Tracks` element of a Matroska file carrying four PGS subtitle tracks | ||
| 211 | +/// and nothing else -- enough for the walk, which stops at the first `Cluster` | ||
| 212 | +/// and there is none. | ||
| 213 | +fn pgs_matroska() -> Vec<u8> { | ||
| 214 | + /// An EBML element: its id as it is written in the file, then an 8-byte | ||
| 215 | + /// length, which is always a legal encoding of one. | ||
| 216 | + fn element(id: &[u8], body: &[u8]) -> Vec<u8> { | ||
| 217 | + let mut out = id.to_vec(); | ||
| 218 | + let mut len = (body.len() as u64).to_be_bytes(); | ||
| 219 | + len[0] |= 0x01; // the 8-byte length marker | ||
| 220 | + out.extend_from_slice(&len); | ||
| 221 | + out.extend_from_slice(body); | ||
| 222 | + out | ||
| 223 | + } | ||
| 224 | + let mut tracks = Vec::new(); | ||
| 225 | + for (number, language) in [(1u8, "eng"), (2, "fra"), (3, "spa"), (4, "")] { | ||
| 226 | + let mut entry = Vec::new(); | ||
| 227 | + entry.extend(element(&[0xD7], &[number])); // TrackNumber | ||
| 228 | + entry.extend(element(&[0x83], &[0x11])); // TrackType: subtitle | ||
| 229 | + entry.extend(element(&[0x86], b"S_HDMV/PGS")); // CodecID | ||
| 230 | + if !language.is_empty() { | ||
| 231 | + entry.extend(element(&[0x22, 0xB5, 0x9C], language.as_bytes())); | ||
| 232 | + } | ||
| 233 | + tracks.extend(element(&[0xAE], &entry)); // TrackEntry | ||
| 234 | + } | ||
| 235 | + let segment = element(&[0x16, 0x54, 0xAE, 0x6B], &tracks); // Tracks | ||
| 236 | + element(&[0x18, 0x53, 0x80, 0x67], &segment) // Segment | ||
| 237 | +} | ||
scripts/gen_fixtures.shmodified+18 -0
| @@ -113,6 +113,24 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | |||
| 113 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | 113 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ |
| 114 | -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ | 114 | -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ |
| 115 | -c:a aac -b:a 128k assets/test_av1.mkv | 115 | -c:a aac -b:a 128k assets/test_av1.mkv |
| 116 | +# Subtitles in Matroska: the two text codecs a film carries, muxed out of the | ||
| 117 | +# hand-written files the tests also parse standalone | ||
| 118 | +# (`crates/engine/tests/data/`), so the embedded cues and the external ones can | ||
| 119 | +# be compared to each other and both to the source. Track 2 is S_TEXT/UTF8 and | ||
| 120 | +# track 3 is S_TEXT/ASS -- the same three cues, one of them with markup, which | ||
| 121 | +# is what makes "the markup is resolved, not carried" measurable. | ||
| 122 | +# | ||
| 123 | +# No bitmap track here: ffmpeg cannot encode text subtitles into pictures, so | ||
| 124 | +# the PGS refusal is checked against a Matroska file the test writes itself | ||
| 125 | +# (`crates/engine/tests/subtitles.rs`). | ||
| 126 | +ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=5 \ | ||
| 127 | + -i crates/engine/tests/data/test_subs.srt \ | ||
| 128 | + -i crates/engine/tests/data/test_subs.ass \ | ||
| 129 | + -map 0:v -map 1:0 -map 2:0 \ | ||
| 130 | + -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ | ||
| 131 | + -c:s:0 srt -metadata:s:s:0 language=eng \ | ||
| 132 | + -c:s:1 ass -metadata:s:s:1 language=fra -metadata:s:s:1 title=Signs \ | ||
| 133 | + assets/test_subs.mkv | ||
| 116 | # HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as | 134 | # HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as |
| 117 | # test_hevc.mp4 so the tests measure the container and nothing else, `-g 30` for | 135 | # test_hevc.mp4 so the tests measure the container and nothing else, `-g 30` for |
| 118 | # the same reason test_av1.mkv has it (a second keyframe to seek to), and the | 136 | # the same reason test_av1.mkv has it (a second keyframe to seek to), and the |