forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(A5): main (dfd4ffe) into the import-policy branch

Browse files at this commit

cbb0f6236d084822eaa0669653b2b69596831f47Ahmet Kaan GümüşParent: d17f345364c821
No conflicts: A6's waveform/demux work and the subtitle lane do not touch
the import gate.

20 changed files +1618 -101

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"
Cargo.tomlmodified+4 -1
@@ -23,7 +23,10 @@ edition = "2024"
23 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per23 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per
24 # term (the fast path in the same file serves the encoder only),24 # term (the fast path in the same file serves the encoder only),
25 # which is 4x slower than real time for 5.1 and therefore not25 # which is 4x slower than real time for 5.1 and therefore not
26-# playable at all; the patch caches the cosine matrix26+# playable at all; the patch routes the IMDCT through the same
27+# N/4-point FFT the encoder's MDCT already uses (`dsp::dct4`),
28+# 40x the matrix version it started as -- 2 hours of 5.1 for a
29+# waveform in 2.4 minutes rather than an hour
27 # oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and30 # oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and
28 # refuses any dimension that is not a multiple of the 16-sample31 # refuses any dimension that is not a multiple of the 16-sample
29 # CTB, so 1920x1080 could not be written at all; the patch adds32 # CTB, so 1920x1080 could not be written at all; the patch adds
crates/app/src/main.rsmodified+28 -8
@@ -260,6 +260,10 @@ enum Wave {
260 Loading,260 Loading,
261 /// The file has no audio track. An answer, not a miss.261 /// The file has no audio track. An answer, not a miss.
262 Silent,262 Silent,
263+ /// The decode failed. Drawn as its own mark rather than as [`Self::Silent`]:
264+ /// "this file's sound could not be read" and "this file has no sound" look
265+ /// the same on a lane, and the first is a bug report waiting to happen.
266+ Failed,
263 Peaks(Arc<Vec<(f32, f32)>>),267 Peaks(Arc<Vec<(f32, f32)>>),
264 }268 }
265 269
@@ -2178,9 +2182,8 @@ impl Player {
2178 let (path, stream) = key.clone();2182 let (path, stream) = key.clone();
2179 async move {2183 async move {
2180 engine::waveform::peaks(&path, stream, WAVE_BPS)2184 engine::waveform::peaks(&path, stream, WAVE_BPS)
2181- .ok()2185+ .map(|peaks| peaks.map(|peaks| Arc::new(normalise(peaks))))
2182- .flatten()2186+ .inspect_err(|e| eprintln!("waveform: {}: {e}", path.display()))
2183- .map(|peaks| Arc::new(normalise(peaks)))
2184 }2187 }
2185 });2188 });
2186 cx.spawn(async move |this, cx| {2189 cx.spawn(async move |this, cx| {
@@ -2189,11 +2192,14 @@ impl Player {
2189 this.waves.insert(2192 this.waves.insert(
2190 key,2193 key,
2191 match decoded {2194 match decoded {
2192- Some(peaks) => Wave::Peaks(peaks),2195+ Ok(Some(peaks)) => Wave::Peaks(peaks),
2193- // Either no audio track or a file we could not read2196+ // No audio track: an answer, and not worth asking
2194- // it from; both mean the lane has nothing to draw,2197+ // about again.
2195- // and neither is worth asking about again.2198+ Ok(None) => Wave::Silent,
2196- None => Wave::Silent,2199+ // A file whose sound we could not read is not a
2200+ // silent one, and a lane that drew it as silent is
2201+ // how a broken decode passes for a design choice.
2202+ Err(_) => Wave::Failed,
2197 },2203 },
2198 );2204 );
2199 cx.notify();2205 cx.notify();
@@ -6915,6 +6921,20 @@ impl Player {
6915 .into_any_element(),6921 .into_any_element(),
6916 // No audio track: nothing, never a fake.6922 // No audio track: nothing, never a fake.
6917 Wave::Silent => return None,6923 Wave::Silent => return None,
6924+ // Could not be read: a band that says so in
6925+ // words, because the empty band a silent
6926+ // file draws would claim this file has no
6927+ // sound. The reason itself went to the log.
6928+ Wave::Failed => div()
6929+ .h_full()
6930+ .flex()
6931+ .items_center()
6932+ .justify_center()
6933+ .truncate()
6934+ .text_size(px(9.))
6935+ .text_color(rgb(INK_DIM))
6936+ .child("audio unreadable")
6937+ .into_any_element(),
6918 };6938 };
6919 Some(6939 Some(
6920 div()6940 div()
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 already79 # 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 image80 # 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 AOM81 # crate, so this links what the build already compiled. BSD-2 with the AOM
crates/engine/src/audio.rsmodified+10 -1
@@ -1006,9 +1006,18 @@ impl Track {
1006 if stream > 0 {1006 if stream > 0 {
1007 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());1007 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
1008 }1008 }
1009+ // Logged on the way past: "silent" here covers both a codec nothing
1010+ // decodes and a track that genuinely broke, and only the second is a
1011+ // bug -- with no trace at all it reaches the user as a lane that
1012+ // drew no waveform and nothing else to go on.
1009 return Ok(SymTrack::open(path)1013 return Ok(SymTrack::open(path)
1014+ .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display()))
1010 .ok()1015 .ok()
1011- .filter(|t| t.decoder().is_ok())1016+ .filter(|t| {
1017+ t.decoder()
1018+ .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display()))
1019+ .is_ok()
1020+ })
1012 .map(Self::Sym));1021 .map(Self::Sym));
1013 }1022 }
1014 let audio_file = crate::is_audio(path);1023 let audio_file = crate::is_audio(path);
crates/engine/src/demux.rsmodified+296 -5
@@ -337,7 +337,7 @@ struct Block {
337 key: bool,337 key: bool,
338 }338 }
339 339
340-/// AV1 or HEVC out of a Matroska file (`.mkv`/`.webm`).340+/// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`).
341 ///341 ///
342 /// The whole segment is walked once at open -- element *headers* only, the block342 /// The whole segment is walked once at open -- element *headers* only, the block
343 /// payloads are seeked over -- because Matroska carries no sample table: the343 /// payloads are seeked over -- because Matroska carries no sample table: the
@@ -355,10 +355,11 @@ pub struct MkvDemuxer {
355 ///355 ///
356 /// For HEVC this is the Annex-B VPS/SPS/PPS off the `CodecPrivate`, which is356 /// For HEVC this is the Annex-B VPS/SPS/PPS off the `CodecPrivate`, which is
357 /// an `hvcC` record verbatim -- the same blob, re-injected for the same357 /// an `hvcC` record verbatim -- the same blob, re-injected for the same
358- /// reason, as the one [`Mp4Demuxer`] carries.358+ /// reason, as the one [`Mp4Demuxer`] carries; for H.264 the SPS/PPS off the
359+ /// `avcC` beside it, which is that record's H.264 twin.
359 config: Vec<u8>,360 config: Vec<u8>,
360- /// Bytes of the NAL length prefix an HEVC block is written with; unused by361+ /// Bytes of the NAL length prefix an HEVC or H.264 block is written with;
361- /// AV1, whose block is one temporal unit and carries no prefixes.362+ /// unused by AV1, whose block is one temporal unit and carries no prefixes.
362 nal_length: usize,363 nal_length: usize,
363 /// Bits per luma sample; see [`Demuxer::bit_depth`].364 /// Bits per luma sample; see [`Demuxer::bit_depth`].
364 bit_depth: u8,365 bit_depth: u8,
@@ -382,7 +383,7 @@ impl MkvDemuxer {
382 None => {383 None => {
383 return Err(match other {384 return Err(match other {
384 Some(codec) => format!(385 Some(codec) => format!(
385- "{codec} video in a Matroska file is not supported — AV1 and HEVC are"386+ "{codec} video in a Matroska file is not supported — AV1, HEVC and H.264 are"
386 ),387 ),
387 None => "this Matroska file has no video track".to_string(),388 None => "this Matroska file has no video track".to_string(),
388 }389 }
@@ -643,6 +644,13 @@ fn mkv_track_entry(
643 let (nal_length, sets, bit_depth) = parse_hvcc(&config)?;644 let (nal_length, sets, bit_depth) = parse_hvcc(&config)?;
644 (Codec::Hevc, nal_length, sets, bit_depth)645 (Codec::Hevc, nal_length, sets, bit_depth)
645 }646 }
647+ // The `avcC` beside them, and the same story: length-prefixed blocks and
648+ // the SPS/PPS out of the record. Taken as 8-bit, which is what the whole
649+ // H.264 path here assumes of an mp4's `avc1` too.
650+ (1, "V_MPEG4/ISO/AVC") => {
651+ let (nal_length, sets) = parse_avcc(&config)?;
652+ (Codec::H264, nal_length, sets, 8)
653+ }
646 (1, _) => return Ok(MkvEntry::OtherVideo(codec)),654 (1, _) => return Ok(MkvEntry::OtherVideo(codec)),
647 (2, _) => return Ok(MkvEntry::Audio(codec)),655 (2, _) => return Ok(MkvEntry::Audio(codec)),
648 _ => return Ok(MkvEntry::Other),656 _ => return Ok(MkvEntry::Other),
@@ -660,6 +668,48 @@ fn mkv_track_entry(
660 }))668 }))
661 }669 }
662 670
671+/// AVCDecoderConfigurationRecord (ISO 14496-15 §5.3.3.1) -> the NAL length
672+/// prefix width and the SPS/PPS as one Annex-B blob, which is [`parse_hvcc`]'s
673+/// job for HEVC. The mp4 path gets both out of `mp4 0.14`'s `AvcCBox`; a
674+/// Matroska file carries the identical record in `CodecPrivate`, unparsed.
675+fn parse_avcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> {
676+ // 0 configurationVersion .. 4 lengthSizeMinusOne, 5 numOfSequenceParameterSets.
677+ let (&flags, &sps_count) = rec
678+ .get(4)
679+ .zip(rec.get(5))
680+ .ok_or("avcC record shorter than its fixed header")?;
681+ let mut sets = Vec::new();
682+ let mut src = &rec[6..];
683+ // The SPS array, whose count is the low 5 bits of byte 5, and then the PPS
684+ // array, whose count is a byte of its own.
685+ let mut count = usize::from(sps_count & 0x1f);
686+ for array in 0..2 {
687+ if array == 1 {
688+ let (&pps_count, rest) = src
689+ .split_first()
690+ .ok_or("avcC record ends before its PPS count")?;
691+ count = usize::from(pps_count);
692+ src = rest;
693+ }
694+ for _ in 0..count {
695+ let len = usize::from(u16::from_be_bytes(
696+ src.get(..2)
697+ .ok_or("avcC NAL length past the record")?
698+ .try_into()
699+ .unwrap(),
700+ ));
701+ let nal = src.get(2..2 + len).ok_or("avcC NAL past the record")?;
702+ sets.extend_from_slice(&START_CODE);
703+ sets.extend_from_slice(nal);
704+ src = &src[2 + len..];
705+ }
706+ }
707+ if sets.is_empty() {
708+ return Err("avcC record carries no SPS/PPS".into());
709+ }
710+ Ok((usize::from(flags & 0x3) + 1, sets))
711+}
712+
663 /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF713 /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF
664 /// §2.3.3): four fixed bytes, then the sequence header OBU in the same714 /// §2.3.3): four fixed bytes, then the sequence header OBU in the same
665 /// low-overhead format the blocks are in, so it needs no reframing.715 /// low-overhead format the blocks are in, so it needs no reframing.
@@ -1138,6 +1188,216 @@ fn tkhd_track_id(payload: &[u8]) -> Option<u32> {
1138 ))1188 ))
1139 }1189 }
1140 1190
1191+/// One subtitle track of a Matroska file, exactly as its `TrackEntry` declares
1192+/// it. What the cues *mean* is [`crate::subtitle`]'s business; this is the
1193+/// walk, and it reads every track type 0x11 the file has -- including the ones
1194+/// nothing here can render, which is how a caller names what it is leaving out
1195+/// instead of quietly opening a film with no subtitles in the list.
1196+#[derive(Debug)]
1197+pub struct MkvSubtitle {
1198+ pub number: u64,
1199+ /// The Matroska codec id: `S_TEXT/UTF8`, `S_TEXT/ASS`, `S_HDMV/PGS`, ...
1200+ pub codec: String,
1201+ /// `Language`, ISO-639-2, `und` when the file says nothing.
1202+ pub language: String,
1203+ /// `Name`, the human label a muxer wrote, often empty.
1204+ pub name: String,
1205+ /// `CodecPrivate`: the ASS script header (`[Script Info]` through the
1206+ /// `[Events]` `Format:` line) for `S_TEXT/ASS`, empty for `S_TEXT/UTF8`.
1207+ pub private: Vec<u8>,
1208+ /// Every cue block, in storage order -- but only for the `S_TEXT/*` codecs.
1209+ /// A bitmap track (PGS, VobSub) comes back declared and empty: its blocks
1210+ /// are megabytes of pictures, and nothing here can draw one.
1211+ pub cues: Vec<MkvCue>,
1212+}
1213+
1214+/// One subtitle block: when it shows and the bytes it shows.
1215+#[derive(Debug)]
1216+pub struct MkvCue {
1217+ /// Microseconds from the start of the file -- the block timestamp scaled by
1218+ /// the segment's `TimestampScale`, which is the unit
1219+ /// [`crate::subtitle::Cue`] keeps.
1220+ pub start_us: i64,
1221+ /// `BlockDuration`, microseconds. `None` for a block that declares none,
1222+ /// which leaves how long the cue stays up to the caller.
1223+ pub duration_us: Option<i64>,
1224+ /// The block's own bytes: the text for `S_TEXT/UTF8`, the comma-separated
1225+ /// `Dialogue` fields (`ReadOrder` first, no timing) for `S_TEXT/ASS`.
1226+ pub payload: Vec<u8>,
1227+}
1228+
1229+/// The subtitle tracks of a Matroska file, in file order. An mp4's are not read
1230+/// (its `tx3g` is a different beast, and no file this project opens carries
1231+/// one); anything that is not a Matroska file at all is an error, as it is for
1232+/// [`matroska_audio_codec`].
1233+///
1234+/// Two passes at most: the header walk stops at the first `Cluster`, and the
1235+/// cue pass runs only when there is a text track to fill.
1236+pub fn matroska_subtitles(path: &Path) -> crate::Result<Vec<MkvSubtitle>> {
1237+ let mut file = File::open(path)?;
1238+ let end = file.metadata()?.len();
1239+ let segment = mkv_segment(&mut file, end)?;
1240+ let mut tracks: Vec<MkvSubtitle> = Vec::new();
1241+ let mut timestamp_scale = 1_000_000;
1242+ let mut at = segment.0;
1243+ while let Some((id, body, stop)) = ebml_element(&mut file, at, segment.1)? {
1244+ match id {
1245+ CLUSTER => break,
1246+ INFO => {
1247+ let mut at = body;
1248+ while let Some(e) = ebml_element(&mut file, at, stop)? {
1249+ if e.0 == TIMESTAMP_SCALE {
1250+ timestamp_scale = ebml_uint(&mut file, e.1, e.2)?.max(1);
1251+ }
1252+ at = e.2;
1253+ }
1254+ }
1255+ TRACKS => {
1256+ let mut at = body;
1257+ while let Some(e) = ebml_element(&mut file, at, stop)? {
1258+ if e.0 == TRACK_ENTRY {
1259+ tracks.extend(mkv_subtitle_entry(&mut file, e.1, e.2)?);
1260+ }
1261+ at = e.2;
1262+ }
1263+ }
1264+ _ => {}
1265+ }
1266+ at = stop;
1267+ }
1268+ // The text tracks only: see `MkvSubtitle::cues`.
1269+ let wanted: Vec<u64> = tracks
1270+ .iter()
1271+ .filter(|t| t.codec.starts_with("S_TEXT"))
1272+ .map(|t| t.number)
1273+ .collect();
1274+ if !wanted.is_empty() {
1275+ mkv_subtitle_blocks(&mut file, segment, timestamp_scale, &wanted, &mut tracks)?;
1276+ }
1277+ Ok(tracks)
1278+}
1279+
1280+/// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles.
1281+fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Option<MkvSubtitle>> {
1282+ const TRACK_LANGUAGE: u32 = 0x22B59C;
1283+ const TRACK_NAME: u32 = 0x536E;
1284+ const SUBTITLE: u64 = 0x11;
1285+ let (mut number, mut kind, mut codec) = (0, 0, String::new());
1286+ let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new());
1287+ let mut at = body;
1288+ while let Some((id, body, stop)) = ebml_element(file, at, end)? {
1289+ match id {
1290+ TRACK_NUMBER => number = ebml_uint(file, body, stop)?,
1291+ TRACK_TYPE => kind = ebml_uint(file, body, stop)?,
1292+ CODEC_ID => codec = string_of(file, body, stop)?,
1293+ CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?,
1294+ TRACK_LANGUAGE => language = string_of(file, body, stop)?,
1295+ TRACK_NAME => name = string_of(file, body, stop)?,
1296+ _ => {}
1297+ }
1298+ at = stop;
1299+ }
1300+ Ok((kind == SUBTITLE).then(|| MkvSubtitle {
1301+ number,
1302+ codec,
1303+ // What a `TrackEntry` without a `Language` element means, by spec.
1304+ language: if language.is_empty() {
1305+ "und".into()
1306+ } else {
1307+ language
1308+ },
1309+ name,
1310+ private,
1311+ cues: Vec::new(),
1312+ }))
1313+}
1314+
1315+/// Every block of the `wanted` tracks, appended to their entries in `tracks`.
1316+///
1317+/// A second cluster walk rather than a widening of [`mkv_blocks`]: that one
1318+/// indexes *one* video track and reads no payloads, and a subtitle needs every
1319+/// track at once, the bytes, and the `BlockDuration` beside them.
1320+fn mkv_subtitle_blocks(
1321+ file: &mut File,
1322+ segment: (u64, u64),
1323+ timestamp_scale: u64,
1324+ wanted: &[u64],
1325+ tracks: &mut [MkvSubtitle],
1326+) -> crate::Result<()> {
1327+ const BLOCK_DURATION: u32 = 0x9B;
1328+ // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is
1329+ // nanoseconds per tick and is a millisecond in every file anything writes.
1330+ let us = |ticks: i64| ticks * timestamp_scale as i64 / 1_000;
1331+ let mut at = segment.0;
1332+ while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
1333+ at = stop;
1334+ if id != CLUSTER {
1335+ continue;
1336+ }
1337+ let mut cluster_ts = 0i64;
1338+ let mut child = body;
1339+ while let Some((id, body, stop)) = ebml_element(file, child, stop)? {
1340+ child = stop;
1341+ let (block, duration) = match id {
1342+ CLUSTER_TIMESTAMP => {
1343+ cluster_ts = ebml_uint(file, body, stop)? as i64;
1344+ continue;
1345+ }
1346+ SIMPLE_BLOCK => (mkv_block(file, body, stop)?, None),
1347+ BLOCK_GROUP => {
1348+ let (mut found, mut duration) = (None, None);
1349+ let mut child = body;
1350+ while let Some(e) = ebml_element(file, child, stop)? {
1351+ match e.0 {
1352+ BLOCK => found = Some(mkv_block(file, e.1, e.2)?),
1353+ BLOCK_DURATION => duration = Some(ebml_uint(file, e.1, e.2)? as i64),
1354+ _ => {}
1355+ }
1356+ child = e.2;
1357+ }
1358+ match found {
1359+ Some(block) => (block, duration),
1360+ None => continue,
1361+ }
1362+ }
1363+ _ => continue,
1364+ };
1365+ if !wanted.contains(&block.number) {
1366+ continue;
1367+ }
1368+ // As for a video block: guessing at the boundaries inside a laced
1369+ // one is not something to do silently. No muxer laces subtitles.
1370+ if block.flags & 0x06 != 0 {
1371+ return Err("laced subtitle blocks are not supported".into());
1372+ }
1373+ // A megabyte of *text* in one cue is a corrupt file, not a subtitle,
1374+ // and a crafted length may not reach an allocation through here.
1375+ if block.len > 1 << 20 {
1376+ return Err("a Matroska subtitle block larger than a megabyte".into());
1377+ }
1378+ let mut payload = vec![0u8; block.len];
1379+ read_exact_at(file, block.at, &mut payload)?;
1380+ let Some(track) = tracks.iter_mut().find(|t| t.number == block.number) else {
1381+ continue;
1382+ };
1383+ track.cues.push(MkvCue {
1384+ start_us: us(cluster_ts + i64::from(block.rel)),
1385+ duration_us: duration.map(us),
1386+ payload,
1387+ });
1388+ }
1389+ }
1390+ Ok(())
1391+}
1392+
1393+/// A string element, without the trailing NULs a `Name` may be padded with.
1394+fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> {
1395+ let bytes = ebml_bytes(file, body, stop)?;
1396+ Ok(String::from_utf8_lossy(&bytes)
1397+ .trim_end_matches('\0')
1398+ .to_owned())
1399+}
1400+
1141 #[cfg(test)]1401 #[cfg(test)]
1142 mod tests {1402 mod tests {
1143 use super::*;1403 use super::*;
@@ -1195,6 +1455,37 @@ mod tests {
1195 assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());1455 assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());
1196 }1456 }
1197 1457
1458+ /// The `avcC` parse: prefix width out of byte 4, and both arrays -- the SPS
1459+ /// count is five bits of byte 5, the PPS count a byte of its own, and taking
1460+ /// the second for the first is the mistake this checks against.
1461+ #[test]
1462+ fn reads_parameter_sets_out_of_an_avcc_record() {
1463+ let mut rec = vec![1, 0x42, 0x00, 0x1f, 0xfc | 0x1, 0xe0 | 2];
1464+ for (kind, nal) in [(7u8, 0xAAu8), (7, 0xBB)] {
1465+ rec.extend_from_slice(&2u16.to_be_bytes());
1466+ rec.extend_from_slice(&[kind, nal]);
1467+ }
1468+ rec.push(1); // numOfPictureParameterSets
1469+ rec.extend_from_slice(&2u16.to_be_bytes());
1470+ rec.extend_from_slice(&[8, 0xCC]);
1471+
1472+ let (len, sets) = parse_avcc(&rec).unwrap();
1473+ assert_eq!(len, 2, "lengthSizeMinusOne == 1");
1474+ assert_eq!(
1475+ sets,
1476+ [
1477+ 0, 0, 0, 1, 7, 0xAA, // SPS
1478+ 0, 0, 0, 1, 7, 0xBB, // the second SPS, which a one-array read loses
1479+ 0, 0, 0, 1, 8, 0xCC, // PPS
1480+ ]
1481+ );
1482+ // Nothing is read past the end of a truncated record, and a Matroska
1483+ // file with no `CodecPrivate` at all is refused rather than started.
1484+ assert!(parse_avcc(&rec[..5]).is_err());
1485+ assert!(parse_avcc(&rec[..rec.len() - 1]).is_err());
1486+ assert!(parse_avcc(&[]).is_err());
1487+ }
1488+
1198 /// EBML's variable-length integers, which every Matroska read starts with:1489 /// EBML's variable-length integers, which every Matroska read starts with:
1199 /// the leading zeros of the first byte are the length, an *id* keeps its1490 /// the leading zeros of the first byte are the length, an *id* keeps its
1200 /// marker bit and a *size* loses it, and an all-ones size is "unknown".1491 /// marker bit and a *size* loses it, and an all-ones size is "unknown".
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 //! ```text3 //! ```text
4-//! edith 94+//! edith 10
5 //! playhead 905 //! playhead 90
6 //! resolution 1920 10806 //! resolution 1920 1080
7 //! fps 30.07 //! fps 30.0
8 //! limiter -1.0 on8 //! limiter -1.0 on
9 //! source 0 test_av.mp49 //! source 0 test_av.mp4
10 //! source 1 /elsewhere/test_av2.mp410 //! 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:pk13 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
12 //! color 0.1:1.2:0.9:-0.314 //! color 0.1:1.2:0.9:-0.3
13 //! video 1 0 0 120 0 0 0 0 fit 100015 //! 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 has25 //! 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 mix37 //! 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 lane90 //! 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 without93+//! **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 such98 //! **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 exactly110 //! 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 grades111 //! 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 one112 //! 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 a113+//! 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 is116 //! 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 module147 /// 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 file184 /// 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 a192 /// 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 scaffolding193 /// v9 file that leaves it out, which both mean "whatever the scaffolding
174 /// source runs at" -- the inference a project of nothing but stills and194 /// 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 the316 // 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. Reading412 // 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 the415+ // 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.playhead1488 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.playhead1555 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.playhead1632 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 the1880 // 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 the1992 // 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: the690 // 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) and691 // 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 (see810 /// Writes the timeline to `path` as a `.edith`, atomically (see
759 /// [`crate::edith`]). Sources no clip plays from are left out, and the811 /// [`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 not832 // 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 mix74 /// -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 not619 /// 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, which629 /// ([`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 the630 /// 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 self1137 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)'s1169 /// 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 the1170 /// 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/src/waveform.rsmodified+39 -4
@@ -15,10 +15,18 @@ use crate::AudioSession;
15 /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always15 /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always
16 /// straddles zero, so silence draws as a flat line.16 /// straddles zero, so silence draws as a flat line.
17 ///17 ///
18-/// Decoding the whole file runs at ~1700x realtime, but it is still linear in18+/// Decoding the whole file runs at ~1700x realtime for an mp4's stereo AAC and
19-/// source length: callers cache the result per source *and stream* — two19+/// ~50x for a film's 5.1 AAC in an mkv (six channels through `rusty_aac`), but
20-/// streams of one file are two different envelopes, and a cache keyed on the20+/// it is linear in source length either way: callers cache the result per source
21-/// path alone would draw the first one under both.21+/// *and stream* — two streams of one file are two different envelopes, and a
22+/// cache keyed on the path alone would draw the first one under both. Memory is
23+/// flat in it, though: chunks are consumed as they arrive and only the buckets
24+/// are kept (2 hours at 10/s is 70k pairs).
25+///
26+/// ponytail: that 50x is 2.4 minutes of background decode for a two-hour film
27+/// before its lane has a waveform. The upgrade path is decoding the source in
28+/// segments on several threads — `open_multi_streams` already takes a window per
29+/// call — and stitching the buckets, which the fold to one envelope makes safe.
22 pub fn peaks(30 pub fn peaks(
23 path: impl AsRef<Path>,31 path: impl AsRef<Path>,
24 stream: usize,32 stream: usize,
@@ -141,6 +149,33 @@ mod tests {
141 assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}");149 assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}");
142 }150 }
143 151
152+ /// The shape the ask came from: a film in an mkv with a 5.1 AAC track,
153+ /// which no symphonia decoder takes (`aac: aac too complex`) and which
154+ /// therefore reaches the lane through `rusty_aac` and the stereo fold. A
155+ /// clip of one draws a waveform like any other -- an envelope that is not
156+ /// flat -- rather than the empty band a silent file makes.
157+ #[test]
158+ fn a_five_one_aac_mkv_draws_an_envelope() {
159+ let peaks = peaks(asset("test_hevc10.mkv"), 0, BPS)
160+ .expect("the 5.1 AAC track decodes")
161+ .expect("test_hevc10.mkv has an audio track");
162+ let want = 2 * BPS as usize; // 2 s of tones
163+ assert!(
164+ peaks.len().abs_diff(want) <= 2,
165+ "{} buckets, want {want} +/-2",
166+ peaks.len()
167+ );
168+ // Six tones, one per channel, folded to stereo: every bucket carries
169+ // signal, and a decode that came out silent (or clipped to a rail) is
170+ // exactly what this refuses.
171+ for (i, &(lo, hi)) in peaks.iter().enumerate() {
172+ assert!(
173+ (0.02..2.0).contains(&(hi - lo)),
174+ "bucket {i} is ({lo}, {hi})"
175+ );
176+ }
177+ }
178+
144 #[test]179 #[test]
145 fn video_only_source_has_no_peaks() {180 fn video_only_source_has_no_peaks() {
146 assert!(181 assert!(
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/h264_mkv.rsadded+149 -0
@@ -0,0 +1,149 @@
1+//! H.264 in Matroska: the codec this project has always decoded, in the
2+//! container that used to refuse it by name. Nothing new decodes here -- the
3+//! demuxer reframes the `avcC`-prefixed blocks to Annex-B and hands them to the
4+//! same dispatch an mp4's samples go to -- so the whole file runs with nothing
5+//! installed, on `rusty_h264` if the plugin is absent.
6+//!
7+//! ```text
8+//! cargo test -p engine --test h264_mkv
9+//! ```
10+
11+use std::path::PathBuf;
12+use std::time::{Duration, Instant};
13+
14+use engine::demux::{Codec, Demuxer};
15+use engine::{AudioSession, PlaybackSession};
16+
17+/// 1280x720@30, 2 s, keyframes 30 apart -- see `scripts/gen_fixtures.sh`.
18+const FRAMES: u32 = 60;
19+const KEYFRAME: u32 = 30;
20+
21+fn asset(name: &str) -> PathBuf {
22+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
23+ .join("../../assets")
24+ .join(name)
25+}
26+
27+/// The Annex-B NAL types of an access unit, in order: `nal_unit_type` is the low
28+/// 5 bits of the byte after each start code.
29+fn nal_types(au: &[u8]) -> Vec<u8> {
30+ au.windows(4)
31+ .enumerate()
32+ .filter(|(_, w)| *w == [0, 0, 0, 1])
33+ .filter_map(|(i, _)| au.get(i + 4).map(|b| b & 0x1f))
34+ .collect()
35+}
36+
37+/// The container half, and the refusal this slice exists to delete: the file
38+/// opens, and it says H.264 rather than "not supported".
39+#[test]
40+fn the_demuxer_reports_an_h264_track_in_matroska() {
41+ let (meta, _) = Demuxer::open(&asset("test_h264.mkv")).expect("open test_h264.mkv");
42+ assert_eq!(meta.codec, Codec::H264);
43+ assert_eq!((meta.width, meta.height), (1280, 720));
44+ assert!(
45+ (meta.frame_rate - 30.0).abs() < 1e-6,
46+ "DefaultDuration must not truncate: {}",
47+ meta.frame_rate
48+ );
49+ assert_eq!(meta.frame_count, FRAMES);
50+
51+ // The invariant, stated as an assert: the other containers and codecs read
52+ // back exactly as they did before this arm existed.
53+ let (av1, _) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv");
54+ assert_eq!(av1.codec, Codec::Av1);
55+ assert_eq!(av1.frame_count, FRAMES);
56+ let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4");
57+ assert_eq!(h264.codec, Codec::H264);
58+}
59+
60+/// Matroska stores H.264 in `avcC` framing -- length prefixes, and the SPS/PPS
61+/// out of band in `CodecPrivate` -- so an access unit is only decodable if both
62+/// were handled: reframed to Annex-B, parameter sets ahead of every keyframe.
63+#[test]
64+fn keyframes_carry_the_parameter_sets_and_every_block_comes_back() {
65+ let (_, mut demuxer) = Demuxer::open(&asset("test_h264.mkv")).expect("open test_h264.mkv");
66+ let first = demuxer
67+ .next_access_unit()
68+ .expect("read")
69+ .expect("a first access unit");
70+ assert_eq!(first[..4], [0, 0, 0, 1], "Annex-B, not a length prefix");
71+ let types = nal_types(&first);
72+ assert_eq!(
73+ &types[..2],
74+ &[7, 8],
75+ "the keyframe leads with SPS and PPS: {types:?}"
76+ );
77+ assert!(types.contains(&5), "and then the IDR picture: {types:?}");
78+
79+ let second = demuxer.next_access_unit().expect("read").expect("a unit");
80+ let types = nal_types(&second);
81+ assert!(
82+ !types.contains(&7) && types.contains(&1),
83+ "a non-keyframe is a plain slice: {types:?}"
84+ );
85+
86+ let mut count = 2;
87+ while demuxer.next_access_unit().expect("read").is_some() {
88+ count += 1;
89+ }
90+ assert_eq!(count, FRAMES, "every block came back out");
91+
92+ // Keyed every 30 frames, and a seek may only land on one.
93+ assert_eq!(
94+ demuxer.seek_to_sync_at_or_before(KEYFRAME + 15),
95+ i64::from(KEYFRAME)
96+ );
97+ assert_eq!(demuxer.seek_to_sync_at_or_before(KEYFRAME - 1), 0);
98+ // The unit after a seek carries the parameter sets too: a decoder restarted
99+ // mid-file needs them exactly as much as one started at frame 0.
100+ let after = demuxer.next_access_unit().expect("read").expect("a unit");
101+ assert_eq!(&nal_types(&after)[..2], &[7, 8]);
102+}
103+
104+/// The user-facing end of it, through the very call the window's open door makes
105+/// (`app/src/main.rs:2242`): the file becomes a timeline and that timeline shows
106+/// a picture. No plugin is required -- H.264 is the one codec with a software
107+/// decoder here -- so this is what says the reframed access units are really
108+/// decodable and not just well-shaped.
109+#[test]
110+fn opening_an_h264_matroska_file_shows_frames() {
111+ let mut session = PlaybackSession::open(asset("test_h264.mkv")).expect("open test_h264.mkv");
112+ assert_eq!(session.meta().codec, Codec::H264);
113+ assert_eq!(session.meta().frame_count, FRAMES);
114+
115+ // The decoder is a thread behind the door, so a frame is waited for exactly
116+ // as the window's own pump waits for one.
117+ let deadline = Instant::now() + Duration::from_secs(60);
118+ let frame = loop {
119+ if let Some(frame) = session.try_frame() {
120+ break frame;
121+ }
122+ assert!(Instant::now() < deadline, "no frame in 60 s");
123+ std::thread::sleep(Duration::from_millis(10));
124+ };
125+ assert_eq!((frame.width, frame.height), (1280, 720));
126+ // A picture, not a flat surface: a decoder handed garbage would satisfy
127+ // every count above.
128+ assert!(
129+ frame.bgra.chunks_exact(4).any(|px| px != &frame.bgra[..4]),
130+ "the first frame is a single colour -- no picture was decoded"
131+ );
132+}
133+
134+/// The sound comes with it: a Matroska file's audio is read whatever its picture
135+/// is coded with, so nothing is left for the "cannot be decoded" notice to name.
136+#[test]
137+fn the_matroska_audio_path_takes_this_file_too() {
138+ let stereo = AudioSession::probe(asset("test_h264.mkv"), 0)
139+ .expect("probe")
140+ .expect("the fixture has an AAC track");
141+ assert_eq!((stereo.sample_rate, stereo.channels), (44_100, 2));
142+ // ...and it really opens, which is what says the sound plays rather than
143+ // merely being described.
144+ assert!(
145+ AudioSession::open(asset("test_h264.mkv"))
146+ .expect("open")
147+ .is_some()
148+ );
149+}
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.
@@ -809,7 +809,7 @@ fn a_song_only_project_comes_back_at_the_rate_it_names() {
809 let path = dir.join("song.edith");809 let path = dir.join("song.edith");
810 std::fs::write(810 std::fs::write(
811 &path,811 &path,
812- "edith 9\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\812+ "edith 10\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\
813 video 1\naudio 1 0 0 24 0 - - - fit 1000\n",813 video 1\naudio 1 0 0 24 0 - - - fit 1000\n",
814 )814 )
815 .expect("write a v9 song project");815 .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(&notes, "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(&notes)
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+28 -0
@@ -113,6 +113,34 @@ 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.mkv115 -c:a aac -b:a 128k assets/test_av1.mkv
116+# H.264 in Matroska: the same stream the mp4 fixtures carry, in the container
117+# that used to refuse it. Baseline profile so `rusty_h264` reads it with nothing
118+# installed, `-g 30` for the second keyframe the sync index is checked against,
119+# and the AAC track for the sound an mkv's audio path reads back.
120+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
121+ -f lavfi -i "sine=frequency=440:duration=2" \
122+ -f lavfi -i "sine=frequency=880:duration=2" \
123+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
124+ -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \
125+ -c:a aac -b:a 128k assets/test_h264.mkv
126+# Subtitles in Matroska: the two text codecs a film carries, muxed out of the
127+# hand-written files the tests also parse standalone
128+# (`crates/engine/tests/data/`), so the embedded cues and the external ones can
129+# be compared to each other and both to the source. Track 2 is S_TEXT/UTF8 and
130+# track 3 is S_TEXT/ASS -- the same three cues, one of them with markup, which
131+# is what makes "the markup is resolved, not carried" measurable.
132+#
133+# No bitmap track here: ffmpeg cannot encode text subtitles into pictures, so
134+# the PGS refusal is checked against a Matroska file the test writes itself
135+# (`crates/engine/tests/subtitles.rs`).
136+ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=5 \
137+ -i crates/engine/tests/data/test_subs.srt \
138+ -i crates/engine/tests/data/test_subs.ass \
139+ -map 0:v -map 1:0 -map 2:0 \
140+ -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
141+ -c:s:0 srt -metadata:s:s:0 language=eng \
142+ -c:s:1 ass -metadata:s:s:1 language=fra -metadata:s:s:1 title=Signs \
143+ assets/test_subs.mkv
116 # HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as144 # 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` for145 # 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 the146 # the same reason test_av1.mkv has it (a second keyframe to seek to), and the
vendor/rusty_aac/src/dsp.rsmodified+87 -49
@@ -35,20 +35,45 @@ pub fn imdct(spec: &[f32]) -> Vec<f32> {
35 if n == 0 {35 if n == 0 {
36 return Vec::new();36 return Vec::new();
37 }37 }
38- // LOCAL PATCH: the AAC block sizes take the cached cosine matrix below --38+ // LOCAL PATCH: O(N log N) instead of the O(N^2) sum below. With `n0 = N/4 +
39- // the same numbers, looked up instead of called for.39+ // 1/2` the kernel is exactly a DCT-IV of length L = N/2 read at `j = i +
40- if let Some(matrix) = imdct_matrix(n) {40+ // L/2` -- the same DCT-IV [`mdct_fast`] already runs as one N/4-point FFT --
41- let mut out = vec![0f32; n];41+ // so the transform is that one call plus a sign-and-mirror walk (DCT-IV is
42- for (i, o) in out.iter_mut().enumerate() {42+ // even about `j = -1/2`, odd about `j = L - 1/2`, and negates every 2L).
43- let row = &matrix[i * half..(i + 1) * half];43+ if half >= 2 && half.is_power_of_two() {
44- let mut acc = 0f32;44+ let owned;
45- for (k, &s) in spec.iter().enumerate() {45+ let tw = match mdct_twiddles(n) {
46- acc += s * row[k];46+ Some(t) => t,
47+ None => {
48+ owned = MdctTwiddles::build(n);
49+ &owned
47 }50 }
48- *o = acc;51+ };
49- }52+ let d = dct4(half, |k| spec[k] as f64, tw);
50- return out;53+ let scale = 2.0 / n as f64;
54+ let (l, l2) = (half, half / 2);
55+ return (0..n)
56+ .map(|i| {
57+ let j = i + l2;
58+ let v = if j < l {
59+ d[j]
60+ } else if j < 2 * l {
61+ -d[2 * l - 1 - j]
62+ } else {
63+ -d[j - 2 * l]
64+ };
65+ (scale * v) as f32
66+ })
67+ .collect();
51 }68 }
69+ imdct_direct(spec)
70+}
71+
72+/// The direct O(N^2) transform [`imdct`] is defined as, kept as the oracle its
73+/// test measures against and as the path for sizes the fast one does not take.
74+fn imdct_direct(spec: &[f32]) -> Vec<f32> {
75+ let half = spec.len();
76+ let n = half * 2;
52 let n0 = (n / 2 + 1) as f64 / 2.0; // N/4 + 1/277 let n0 = (n / 2 + 1) as f64 / 2.0; // N/4 + 1/2
53 let scale = 2.0 / n as f64;78 let scale = 2.0 / n as f64;
54 let w = 2.0 * PI / n as f64;79 let w = 2.0 * PI / n as f64;
@@ -64,36 +89,6 @@ pub fn imdct(spec: &[f32]) -> Vec<f32> {
64 out89 out
65 }90 }
66 91
67-/// LOCAL PATCH: `(2/N)·cos((2π/N)(i+n0)(k+½))` for every `(i, k)` of one block
68-/// size, built once. The direct transform above spends its whole time in `cos`
69-/// -- ~63 ms for one 1024-coefficient channel, three times slower than real
70-/// time, which is what made a 5.1 stream unplayable. The matrix is 8 MB for the
71-/// long block and 128 kB for the short one, and each output sample becomes a
72-/// dot product a compiler can vectorise.
73-fn imdct_matrix(n: usize) -> Option<&'static [f32]> {
74- static LONG: OnceLock<Vec<f32>> = OnceLock::new();
75- static SHORT: OnceLock<Vec<f32>> = OnceLock::new();
76- fn build(n: usize) -> Vec<f32> {
77- let half = n / 2;
78- let n0 = (n / 2 + 1) as f64 / 2.0;
79- let scale = 2.0 / n as f64;
80- let w = 2.0 * PI / n as f64;
81- let mut m = vec![0f32; n * half];
82- for i in 0..n {
83- let a = w * (i as f64 + n0);
84- for k in 0..half {
85- m[i * half + k] = (scale * (a * (k as f64 + 0.5)).cos()) as f32;
86- }
87- }
88- m
89- }
90- match n {
91- 2048 => Some(LONG.get_or_init(|| build(2048))),
92- 256 => Some(SHORT.get_or_init(|| build(256))),
93- _ => None,
94- }
95-}
96-
97 /// Forward MDCT — the analysis transform paired with [`imdct`]. Used to validate92 /// Forward MDCT — the analysis transform paired with [`imdct`]. Used to validate
98 /// the IMDCT via perfect reconstruction (and useful for an eventual encoder).93 /// the IMDCT via perfect reconstruction (and useful for an eventual encoder).
99 /// `N` time samples → `N/2` coefficients.94 /// `N` time samples → `N/2` coefficients.
@@ -236,7 +231,7 @@ pub fn mdct_fast(x: &[f32]) -> Vec<f32> {
236 if n < 4 {231 if n < 4 {
237 return mdct(x); // tiny sizes: fall back to the direct oracle232 return mdct(x); // tiny sizes: fall back to the direct oracle
238 }233 }
239- let (l, m) = (n / 2, n / 4);234+ let l = n / 2;
240 let owned;235 let owned;
241 let tw = match mdct_twiddles(n) {236 let tw = match mdct_twiddles(n) {
242 Some(t) => t,237 Some(t) => t,
@@ -254,20 +249,32 @@ pub fn mdct_fast(x: &[f32]) -> Vec<f32> {
254 (x[mm - l2] as f64) - (x[l32 - 1 - mm] as f64)249 (x[mm - l2] as f64) - (x[l32 - 1 - mm] as f64)
255 }250 }
256 };251 };
257- // Pack + pre-rotate into M complex: v[p] = (y[2p] + i·y[L-1-2p])·e^{-iπ(4p+1)/4L}.252+ // Output scaled ×2: that factor is [`mdct`]'s, not the DCT-IV's.
253+ dct4(l, fold, tw).iter().map(|&v| (2.0 * v) as f32).collect()
254+}
255+
256+/// DCT-IV of length `l`: `out[k] = Σ_j y(j)·cos((π/L)(j+½)(k+½))`, as one
257+/// `L/2`-point complex FFT — pack + pre-rotate `v[p] = (y[2p] + i·y[L-1-2p])
258+/// ·e^{-iπ(4p+1)/4L}`, transform, post-rotate `W = V·e^{-iπp/L}`, and read
259+/// `out[2p] = Re(W)`, `out[L-1-2p] = -Im(W)`.
260+///
261+/// `y` is a closure because the forward MDCT folds its input on the fly and the
262+/// inverse reads a spectrum straight out; `tw` is the block-size table both
263+/// directions share ([`MdctTwiddles`], built for `N = 2L`).
264+fn dct4(l: usize, y: impl Fn(usize) -> f64, tw: &MdctTwiddles) -> Vec<f64> {
265+ let m = l / 2;
258 let (mut re, mut im) = (vec![0f64; m], vec![0f64; m]);266 let (mut re, mut im) = (vec![0f64; m], vec![0f64; m]);
259 for p in 0..m {267 for p in 0..m {
260- let (yr, yi) = (fold(2 * p), fold(l - 1 - 2 * p));268+ let (yr, yi) = (y(2 * p), y(l - 1 - 2 * p));
261 re[p] = yr * tw.pre_c[p] + yi * tw.pre_s[p];269 re[p] = yr * tw.pre_c[p] + yi * tw.pre_s[p];
262 im[p] = yi * tw.pre_c[p] - yr * tw.pre_s[p];270 im[p] = yi * tw.pre_c[p] - yr * tw.pre_s[p];
263 }271 }
264 fft(&mut re, &mut im, &tw.fft_c, &tw.fft_s);272 fft(&mut re, &mut im, &tw.fft_c, &tw.fft_s);
265- // Post-rotate W = V·e^{-iπp/L}; X[2p]=Re(W), X[L-1-2p]=-Im(W); output scaled ×2.273+ let mut out = vec![0f64; l];
266- let mut out = vec![0f32; l];
267 for p in 0..m {274 for p in 0..m {
268 let (vr, vi) = (re[p], im[p]);275 let (vr, vi) = (re[p], im[p]);
269- out[2 * p] = (2.0 * (vr * tw.post_c[p] + vi * tw.post_s[p])) as f32;276+ out[2 * p] = vr * tw.post_c[p] + vi * tw.post_s[p];
270- out[l - 1 - 2 * p] = (2.0 * (vr * tw.post_s[p] - vi * tw.post_c[p])) as f32;277+ out[l - 1 - 2 * p] = vr * tw.post_s[p] - vi * tw.post_c[p];
271 }278 }
272 out279 out
273 }280 }
@@ -346,6 +353,37 @@ mod tests {
346 }353 }
347 }354 }
348 355
356+ /// LOCAL PATCH: the fast IMDCT against the direct sum it replaced, at both
357+ /// AAC block sizes plus one the twiddle cache does not hold (512, built on
358+ /// the spot) and one the fast path declines (a 3-coefficient spectrum), on
359+ /// raw and decoder-scale (×32768) input. Every output sample, because the
360+ /// index remap is where a DCT-IV-based inverse goes wrong: a sign or a
361+ /// mirror off by one is silent in the first half and audible in the second.
362+ #[test]
363+ fn imdct_matches_direct() {
364+ for &half in &[3usize, 128, 256, 1024] {
365+ for &scale in &[1.0f32, 32768.0] {
366+ let spec: Vec<f32> = (0..half)
367+ .map(|k| {
368+ scale
369+ * (0.4 * (k as f64 * 0.037).sin() + 0.25 * (k as f64 * 0.011).cos())
370+ as f32
371+ })
372+ .collect();
373+ let (a, b) = (imdct_direct(&spec), imdct(&spec));
374+ let tol = 2e-4 * scale.max(1.0);
375+ for i in 0..half * 2 {
376+ assert!(
377+ (a[i] - b[i]).abs() < tol,
378+ "half={half} scale={scale} i={i}: {} vs {}",
379+ a[i],
380+ b[i]
381+ );
382+ }
383+ }
384+ }
385+ }
386+
349 #[test]387 #[test]
350 fn dequant_matches_spec_curve() {388 fn dequant_matches_spec_curve() {
351 assert_eq!(dequant(0), 0.0);389 assert_eq!(dequant(0), 0.0);