The subtitles leave with the file
Browse files at this commitdf924588ba27f5631c5d249e96d29e8678f49b27Parent: 863eb63- feat
- the subtitles leave with the file
6 changed files +724 -4
- crates/app/src/main.rs +31 -1
- crates/engine/src/export.rs +247 -1
- crates/engine/src/mux.rs +142 -1
- crates/engine/src/playback.rs +8 -0
- crates/engine/src/project.rs +1 -1
- crates/engine/tests/export_subs.rs +295 -0
crates/app/src/main.rsmodified+31 -1
| @@ -4139,8 +4139,13 @@ impl Player { | |||
| 4139 | if self.export.is_some() { | 4139 | if self.export.is_some() { |
| 4140 | return; | 4140 | return; |
| 4141 | } | 4141 | } |
| 4142 | - let settings = | 4142 | + let mut settings = |
| 4143 | export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps); | 4143 | export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps); |
| 4144 | + // The track the library has picked is the one that travels -- the same | ||
| 4145 | + // row the overlay draws, so the file carries what was watched. Set here | ||
| 4146 | + // rather than inside `export_settings`, which the card also calls for | ||
| 4147 | + // the *estimate* and which nothing else needs a subtitle for. | ||
| 4148 | + settings.subtitles = Some(self.sub_track); | ||
| 4144 | let Some(session) = &mut self.session else { | 4149 | let Some(session) = &mut self.session else { |
| 4145 | self.notice = Some("NOTHING TO EXPORT — open a file first".into()); | 4150 | self.notice = Some("NOTHING TO EXPORT — open a file first".into()); |
| 4146 | cx.notify(); | 4151 | cx.notify(); |
| @@ -6394,6 +6399,27 @@ impl Player { | |||
| 6394 | })); | 6399 | })); |
| 6395 | } | 6400 | } |
| 6396 | list.push(r.into_any_element()); | 6401 | list.push(r.into_any_element()); |
| 6402 | + // What happens to the picked subtitle track, in one line: it is written | ||
| 6403 | + // into the file, or the reason it is not. Nothing to pick here -- which | ||
| 6404 | + // track is the library's row and the container is the format row above | ||
| 6405 | + // -- so the row says and does not answer, like the machine lines below. | ||
| 6406 | + list.push( | ||
| 6407 | + entry( | ||
| 6408 | + ("subtitles", 0), | ||
| 6409 | + "", | ||
| 6410 | + "Subtitles".into(), | ||
| 6411 | + self.session | ||
| 6412 | + .as_ref() | ||
| 6413 | + .map_or_else( | ||
| 6414 | + || "none".into(), | ||
| 6415 | + |s| s.planned_subtitles(self.format, Some(self.sub_track)), | ||
| 6416 | + ) | ||
| 6417 | + .into(), | ||
| 6418 | + false, | ||
| 6419 | + false, | ||
| 6420 | + ) | ||
| 6421 | + .into_any_element(), | ||
| 6422 | + ); | ||
| 6397 | let destination = entry( | 6423 | let destination = entry( |
| 6398 | ("destination", 0), | 6424 | ("destination", 0), |
| 6399 | "d", | 6425 | "d", |
| @@ -10126,6 +10152,10 @@ fn export_settings( | |||
| 10126 | // badly, which is a thing about the machine and not about the output -- | 10152 | // badly, which is a thing about the machine and not about the output -- |
| 10127 | // `VE_SW_ENC` already says it, and to the whole run rather than once. | 10153 | // `VE_SW_ENC` already says it, and to the whole run rather than once. |
| 10128 | force_sw: false, | 10154 | force_sw: false, |
| 10155 | + // The picked track is put on by `start_export`, which is the only | ||
| 10156 | + // caller that writes a file; the rest of them are asking about the | ||
| 10157 | + // bitrate and the format. | ||
| 10158 | + subtitles: None, | ||
| 10129 | } | 10159 | } |
| 10130 | } | 10160 | } |
| 10131 | 10161 | ||
crates/engine/src/export.rsmodified+247 -1
| @@ -62,9 +62,10 @@ use flacenc::error::Verify; | |||
| 62 | use crate::audio::{AudioMeta, AudioSession}; | 62 | use crate::audio::{AudioMeta, AudioSession}; |
| 63 | use crate::demux::{Demuxer, VideoMeta}; | 63 | use crate::demux::{Demuxer, VideoMeta}; |
| 64 | use crate::hw::{HwEncoder, HwSession}; | 64 | use crate::hw::{HwEncoder, HwSession}; |
| 65 | -use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, VideoParams}; | 65 | +use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams}; |
| 66 | use crate::project::{LaneKind, Project, Rate}; | 66 | use crate::project::{LaneKind, Project, Rate}; |
| 67 | use crate::scale::Composer; | 67 | use crate::scale::Composer; |
| 68 | +use crate::subtitle::{Cue, SubtitleTrack}; | ||
| 68 | 69 | ||
| 69 | /// Progress is reported in permille: an atomic integer the render loop can read | 70 | /// Progress is reported in permille: an atomic integer the render loop can read |
| 70 | /// without a lock, fine enough for any progress bar. | 71 | /// without a lock, fine enough for any progress bar. |
| @@ -228,6 +229,16 @@ pub struct ExportSettings { | |||
| 228 | /// it used to. Means nothing to WAV and FLAC, which code no rate, and | 229 | /// it used to. Means nothing to WAV and FLAC, which code no rate, and |
| 229 | /// nothing to a *copied* AAC track, which carries its source's. | 230 | /// nothing to a *copied* AAC track, which carries its source's. |
| 230 | pub audio_kbps: Option<u32>, | 231 | pub audio_kbps: Option<u32>, |
| 232 | + /// Which of the project's subtitle tracks travels with the file: an index | ||
| 233 | + /// into [`Project::subtitles`], which is the same list a front-end picks a | ||
| 234 | + /// row of. `None` writes none -- what every caller wrote before there was a | ||
| 235 | + /// choice, so an export of a timeline without subtitles is the file it | ||
| 236 | + /// always was, byte for byte. | ||
| 237 | + /// | ||
| 238 | + /// Only a Matroska container carries it: an mp4's `tx3g` is a different | ||
| 239 | + /// beast and nothing here writes one, so an mp4 export says so | ||
| 240 | + /// ([`planned_subtitles`]) rather than dropping the track in silence. | ||
| 241 | + pub subtitles: Option<usize>, | ||
| 231 | } | 242 | } |
| 232 | 243 | ||
| 233 | struct Shared { | 244 | struct Shared { |
| @@ -525,6 +536,136 @@ pub fn audio_rate_refusal(project: &Project, format: Format) -> Option<&'static | |||
| 525 | } | 536 | } |
| 526 | } | 537 | } |
| 527 | 538 | ||
| 539 | +/// The track a Matroska export carries, or `None`: no pick, a pick nothing | ||
| 540 | +/// answers, a track that could not be read, one with no cue left on the | ||
| 541 | +/// exported timeline -- and every mp4, whose refusal [`planned_subtitles`] says | ||
| 542 | +/// out loud before the button is pressed. | ||
| 543 | +fn export_subtitles( | ||
| 544 | + project: &Project, | ||
| 545 | + meta: &VideoMeta, | ||
| 546 | + settings: &ExportSettings, | ||
| 547 | +) -> Option<SubParams> { | ||
| 548 | + if !matches!(settings.format, Format::Av1 | Format::Hevc) { | ||
| 549 | + return None; | ||
| 550 | + } | ||
| 551 | + let track = project.subtitles().get(settings.subtitles?)?; | ||
| 552 | + if track.refused.is_some() { | ||
| 553 | + return None; | ||
| 554 | + } | ||
| 555 | + let cues = timeline_cues(project, track, meta.frame_rate); | ||
| 556 | + (!cues.is_empty()).then(|| SubParams { | ||
| 557 | + label: track.label.clone(), | ||
| 558 | + cues, | ||
| 559 | + }) | ||
| 560 | +} | ||
| 561 | + | ||
| 562 | +/// The track's cues where the *exported* timeline puts them, which is the only | ||
| 563 | +/// clock the file has: the export writes timeline frame 0 onwards and nothing | ||
| 564 | +/// else, exactly as the sound is mixed from frame 0 and resized to the | ||
| 565 | +/// timeline's own length ([`encode_audio`]). | ||
| 566 | +/// | ||
| 567 | +/// Which clock the cues arrive in is what the track itself says: | ||
| 568 | +/// | ||
| 569 | +/// * a track out of a *file* (`SubtitleTrack::track`) is timed against that | ||
| 570 | +/// file, so each cue is carried through the spans that play it -- a cue over | ||
| 571 | +/// a stretch that was cut out is gone, one straddling a cut keeps the half | ||
| 572 | +/// that is still there, and one after a rippled delete moves back with the | ||
| 573 | +/// picture it belongs to. The *edges* a cut clips to are frames -- that is | ||
| 574 | +/// what a cut is -- but a cue nothing clipped keeps its own microseconds, so | ||
| 575 | +/// an untouched timeline exports the times the source states. | ||
| 576 | +/// * a *standalone* file (`subs.srt`) is timed against nothing else -- there is | ||
| 577 | +/// no clip to hang it on and no offset in the project to shift it by -- so it | ||
| 578 | +/// is the timeline's own clock, which is where it was drawn while editing | ||
| 579 | +/// (`Player::subtitle_overlay`). Clipped to the exported length and no more. | ||
| 580 | +/// | ||
| 581 | +/// ponytail: the overlay draws *every* track on the timeline's clock, so on a | ||
| 582 | +/// rippled timeline what the picture shows and what an embedded track exports | ||
| 583 | +/// now disagree. The upgrade path is this function: the overlay should ask it | ||
| 584 | +/// too, at which point both halves move together. It is left because the app is | ||
| 585 | +/// another lane's file this week. | ||
| 586 | +fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<Cue> { | ||
| 587 | + let frames = project.timeline_frames(); | ||
| 588 | + let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64; | ||
| 589 | + let end = us(frames); | ||
| 590 | + // The file the cues are timed against, when there is one on this timeline. | ||
| 591 | + // A track whose media has since been dropped from the project has no span | ||
| 592 | + // to be carried through and falls back to the timeline's clock, which is | ||
| 593 | + // what it was drawn on. | ||
| 594 | + // | ||
| 595 | + // Through the same `canonical` a source is indexed by, or the two spellings | ||
| 596 | + // of one file (an argv `../assets/film.mkv`, a symlinked folder) would read | ||
| 597 | + // as two files and the cues would quietly fall back to the timeline's clock. | ||
| 598 | + let source = track.track.and_then(|_| { | ||
| 599 | + let path = crate::project::canonical(&track.path); | ||
| 600 | + project.sources().iter().position(|s| s.path == path) | ||
| 601 | + }); | ||
| 602 | + let Some(source) = source else { | ||
| 603 | + return track | ||
| 604 | + .cues | ||
| 605 | + .iter() | ||
| 606 | + .filter_map(|cue| { | ||
| 607 | + let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end)); | ||
| 608 | + (end_us > start_us).then(|| Cue { | ||
| 609 | + start_us, | ||
| 610 | + end_us, | ||
| 611 | + text: cue.text.clone(), | ||
| 612 | + }) | ||
| 613 | + }) | ||
| 614 | + .collect(); | ||
| 615 | + }; | ||
| 616 | + let mut out = Vec::new(); | ||
| 617 | + for span in project.composite_spans_from(0) { | ||
| 618 | + let Some((_, in_frame)) = span.from.filter(|&(from, _)| from == source) else { | ||
| 619 | + continue; | ||
| 620 | + }; | ||
| 621 | + // What of the file this span plays, as *time in the file*: a clip counts | ||
| 622 | + // the timeline's frames whatever its file was shot at ([`Rate`]), which | ||
| 623 | + // is what makes those frames the same seconds a cue is timed in. | ||
| 624 | + let (first, last) = (us(in_frame), us(in_frame + span.source_len())); | ||
| 625 | + // Where that lands, and how fast: a cue is carried by the same factor | ||
| 626 | + // the pictures under it are, so a slowed clip stretches its subtitles | ||
| 627 | + // with it instead of leaving them behind. | ||
| 628 | + let start = us(span.start); | ||
| 629 | + let onto = |t: i64| start + ((t - first) as f64 / span.speed.as_f64()).round() as i64; | ||
| 630 | + for cue in &track.cues { | ||
| 631 | + let (a, b) = (cue.start_us.max(first), cue.end_us.min(last)); | ||
| 632 | + if b <= a { | ||
| 633 | + continue; // wholly outside what this span kept | ||
| 634 | + } | ||
| 635 | + out.push(Cue { | ||
| 636 | + start_us: onto(a), | ||
| 637 | + end_us: onto(b).min(end), | ||
| 638 | + text: cue.text.clone(), | ||
| 639 | + }); | ||
| 640 | + } | ||
| 641 | + } | ||
| 642 | + // The spans come in timeline order but a cue's *own* order across them does | ||
| 643 | + // not: a Matroska muxer writes blocks as they come up. | ||
| 644 | + out.sort_by_key(|cue| cue.start_us); | ||
| 645 | + out | ||
| 646 | +} | ||
| 647 | + | ||
| 648 | +/// What [`start`] would do about the subtitles, in the words a card shows. | ||
| 649 | +/// Pure, like [`planned_audio`]: no file is opened, so it may be asked per | ||
| 650 | +/// repaint. | ||
| 651 | +pub fn planned_subtitles(project: &Project, format: Format, pick: Option<usize>) -> String { | ||
| 652 | + let Some(track) = pick.and_then(|i| project.subtitles().get(i)) else { | ||
| 653 | + return "none".into(); | ||
| 654 | + }; | ||
| 655 | + if let Some(why) = &track.refused { | ||
| 656 | + return format!("{} — {why}", track.label); | ||
| 657 | + } | ||
| 658 | + match format { | ||
| 659 | + _ if track.cues.is_empty() => "none".into(), | ||
| 660 | + Format::Av1 | Format::Hevc => format!("{} → embedded", track.label), | ||
| 661 | + // Said before the export rather than after it: an mp4 carries text in | ||
| 662 | + // `tx3g` and nothing here writes one, so the honest answer is the | ||
| 663 | + // container that does. | ||
| 664 | + format if format.has_video() => "mkv only — an mp4 carries none".into(), | ||
| 665 | + _ => "none — this format is the sound alone".into(), | ||
| 666 | + } | ||
| 667 | +} | ||
| 668 | + | ||
| 528 | /// What [`start`] would encode the picture with, probed the way the export | 669 | /// What [`start`] would encode the picture with, probed the way the export |
| 529 | /// probes it -- the very encoder is opened and closed again -- so this is a | 670 | /// probes it -- the very encoder is opened and closed again -- so this is a |
| 530 | /// measurement and not a promise. `None` for a format that carries no picture. | 671 | /// measurement and not a promise. `None` for a format that carries no picture. |
| @@ -770,6 +911,10 @@ fn run( | |||
| 770 | // Taken by the Matroska muxer at creation; the mp4 one writes its track | 911 | // Taken by the Matroska muxer at creation; the mp4 one writes its track |
| 771 | // after the picture, so for that path this is still `Some` at the end. | 912 | // after the picture, so for that path this is still `Some` at the end. |
| 772 | let mut packets = audio.map(|track| track.packets); | 913 | let mut packets = audio.map(|track| track.packets); |
| 914 | + // ...and the cues with them, for the same reason: the subtitle track is | ||
| 915 | + // declared in the header and its blocks are interleaved into the clusters, | ||
| 916 | + // so the muxer needs the lot before the first picture is written. | ||
| 917 | + let mut subs = export_subtitles(project, meta, settings); | ||
| 773 | 918 | ||
| 774 | // One header parse per source, before any of them is decoded: what rate | 919 | // One header parse per source, before any of them is decoded: what rate |
| 775 | // each file was shot at against the timeline's ([`Rate`]), which is how the | 920 | // each file was shot at against the timeline's ([`Rate`]), which is how the |
| @@ -918,6 +1063,7 @@ fn run( | |||
| 918 | settings, | 1063 | settings, |
| 919 | audio_params.as_ref(), | 1064 | audio_params.as_ref(), |
| 920 | &mut packets, | 1065 | &mut packets, |
| 1066 | + &mut subs, | ||
| 921 | au, | 1067 | au, |
| 922 | key, | 1068 | key, |
| 923 | )?; | 1069 | )?; |
| @@ -938,6 +1084,7 @@ fn run( | |||
| 938 | settings, | 1084 | settings, |
| 939 | audio_params.as_ref(), | 1085 | audio_params.as_ref(), |
| 940 | &mut packets, | 1086 | &mut packets, |
| 1087 | + &mut subs, | ||
| 941 | au, | 1088 | au, |
| 942 | key, | 1089 | key, |
| 943 | )?; | 1090 | )?; |
| @@ -1232,6 +1379,7 @@ fn write_video( | |||
| 1232 | settings: &ExportSettings, | 1379 | settings: &ExportSettings, |
| 1233 | audio: Option<&AudioParams>, | 1380 | audio: Option<&AudioParams>, |
| 1234 | packets: &mut Option<Vec<crate::AacPacket>>, | 1381 | packets: &mut Option<Vec<crate::AacPacket>>, |
| 1382 | + subs: &mut Option<SubParams>, | ||
| 1235 | au: &[u8], | 1383 | au: &[u8], |
| 1236 | key: bool, | 1384 | key: bool, |
| 1237 | ) -> crate::Result<()> { | 1385 | ) -> crate::Result<()> { |
| @@ -1259,6 +1407,7 @@ fn write_video( | |||
| 1259 | hvcc: &hvcc, | 1407 | hvcc: &hvcc, |
| 1260 | }, | 1408 | }, |
| 1261 | sound, | 1409 | sound, |
| 1410 | + subs.take(), | ||
| 1262 | )?)) else { | 1411 | )?)) else { |
| 1263 | unreachable!("just inserted a Matroska muxer") | 1412 | unreachable!("just inserted a Matroska muxer") |
| 1264 | }; | 1413 | }; |
| @@ -1315,6 +1464,7 @@ fn write_video( | |||
| 1315 | out, | 1464 | out, |
| 1316 | ¶ms(meta, au)?, | 1465 | ¶ms(meta, au)?, |
| 1317 | sound, | 1466 | sound, |
| 1467 | + subs.take(), | ||
| 1318 | )?)) else { | 1468 | )?)) else { |
| 1319 | unreachable!("just inserted a Matroska muxer") | 1469 | unreachable!("just inserted a Matroska muxer") |
| 1320 | }; | 1470 | }; |
| @@ -1969,6 +2119,102 @@ impl SwDecoder { | |||
| 1969 | mod tests { | 2119 | mod tests { |
| 1970 | use super::*; | 2120 | use super::*; |
| 1971 | 2121 | ||
| 2122 | + /// A track of three cues, in whichever clock `track` says: `Some(n)` is a | ||
| 2123 | + /// track of the media file, `None` a `.srt` beside it. | ||
| 2124 | + fn subtitles(path: &str, track: Option<u64>) -> SubtitleTrack { | ||
| 2125 | + SubtitleTrack { | ||
| 2126 | + path: path.into(), | ||
| 2127 | + track, | ||
| 2128 | + label: "eng".into(), | ||
| 2129 | + cues: vec![ | ||
| 2130 | + Cue { | ||
| 2131 | + start_us: 500_000, | ||
| 2132 | + end_us: 1_500_000, | ||
| 2133 | + text: "first".into(), | ||
| 2134 | + }, | ||
| 2135 | + Cue { | ||
| 2136 | + start_us: 2_000_000, | ||
| 2137 | + end_us: 3_250_000, | ||
| 2138 | + text: "second".into(), | ||
| 2139 | + }, | ||
| 2140 | + Cue { | ||
| 2141 | + start_us: 4_000_000, | ||
| 2142 | + end_us: 4_750_000, | ||
| 2143 | + text: "third".into(), | ||
| 2144 | + }, | ||
| 2145 | + ], | ||
| 2146 | + refused: None, | ||
| 2147 | + } | ||
| 2148 | + } | ||
| 2149 | + | ||
| 2150 | + /// A standalone subtitle file is timed against the timeline itself -- there | ||
| 2151 | + /// is no clip to hang it on -- so a cut moves the pictures and not it. What | ||
| 2152 | + /// it does get is the exported length: a cue past the end of the file would | ||
| 2153 | + /// otherwise be a block after the last picture. | ||
| 2154 | + /// | ||
| 2155 | + /// The pair of this, the embedded clock, is measured against a real exported | ||
| 2156 | + /// file in `tests/export_subs.rs`; both live in one function and this is the | ||
| 2157 | + /// half that needs no encoder. | ||
| 2158 | + #[test] | ||
| 2159 | + fn a_subtitle_file_beside_the_media_keeps_the_timelines_own_clock() { | ||
| 2160 | + // 5 seconds at 30, with `[0.5s, 2.5s)` cut out of it: 3 seconds left. | ||
| 2161 | + let mut project = Project::single("/nonexistent/film.mp4", 150); | ||
| 2162 | + let track = subtitles("/nonexistent/film.srt", None); | ||
| 2163 | + assert!(project.ripple_delete(15, 60)); | ||
| 2164 | + assert_eq!(project.timeline_frames(), 90); | ||
| 2165 | + let cues = timeline_cues(&project, &track, 30.0); | ||
| 2166 | + assert_eq!( | ||
| 2167 | + cues, | ||
| 2168 | + vec![ | ||
| 2169 | + Cue { | ||
| 2170 | + start_us: 500_000, | ||
| 2171 | + end_us: 1_500_000, | ||
| 2172 | + text: "first".into() | ||
| 2173 | + }, | ||
| 2174 | + // Clipped to the three seconds the export writes... | ||
| 2175 | + Cue { | ||
| 2176 | + start_us: 2_000_000, | ||
| 2177 | + end_us: 3_000_000, | ||
| 2178 | + text: "second".into() | ||
| 2179 | + }, | ||
| 2180 | + // ...and the one wholly past the end is not written at all. | ||
| 2181 | + ] | ||
| 2182 | + ); | ||
| 2183 | + // A track *of a file* the project no longer plays has no span to be | ||
| 2184 | + // carried through either, so it falls back to the same clock rather | ||
| 2185 | + // than exporting nothing. | ||
| 2186 | + let orphan = subtitles("/nonexistent/other.mkv", Some(2)); | ||
| 2187 | + assert_eq!(timeline_cues(&project, &orphan, 30.0).len(), 2); | ||
| 2188 | + } | ||
| 2189 | + | ||
| 2190 | + /// The embedded clock, without an encoder in it: the cut moves the cues with | ||
| 2191 | + /// the pictures, and a cue nothing clipped keeps its own microseconds. | ||
| 2192 | + #[test] | ||
| 2193 | + fn a_track_of_the_media_is_carried_through_the_cut() { | ||
| 2194 | + let mut project = Project::single("/nonexistent/film.mkv", 150); | ||
| 2195 | + let track = subtitles("/nonexistent/film.mkv", Some(2)); | ||
| 2196 | + assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out"); | ||
| 2197 | + let cues = timeline_cues(&project, &track, 30.0); | ||
| 2198 | + assert_eq!( | ||
| 2199 | + cues, | ||
| 2200 | + vec![ | ||
| 2201 | + // The first cue was wholly inside the cut. The second straddled | ||
| 2202 | + // its far edge and kept the 0.75s that is still there... | ||
| 2203 | + Cue { | ||
| 2204 | + start_us: 500_000, | ||
| 2205 | + end_us: 1_250_000, | ||
| 2206 | + text: "second".into() | ||
| 2207 | + }, | ||
| 2208 | + // ...and the third simply moves back the two seconds that went. | ||
| 2209 | + Cue { | ||
| 2210 | + start_us: 2_000_000, | ||
| 2211 | + end_us: 2_750_000, | ||
| 2212 | + text: "third".into() | ||
| 2213 | + }, | ||
| 2214 | + ] | ||
| 2215 | + ); | ||
| 2216 | + } | ||
| 2217 | + | ||
| 1972 | #[test] | 2218 | #[test] |
| 1973 | fn bitrate_clamps_at_both_ends() { | 2219 | fn bitrate_clamps_at_both_ends() { |
| 1974 | let meta = |width, height, frame_rate| VideoMeta { | 2220 | let meta = |width, height, frame_rate| VideoMeta { |
crates/engine/src/mux.rsmodified+142 -1
| @@ -482,6 +482,11 @@ const CODEC_DELAY: u32 = 0x56AA; | |||
| 482 | const CLUSTER: u32 = 0x1F43_B675; | 482 | const CLUSTER: u32 = 0x1F43_B675; |
| 483 | const CLUSTER_TIMESTAMP: u32 = 0xE7; | 483 | const CLUSTER_TIMESTAMP: u32 = 0xE7; |
| 484 | const SIMPLE_BLOCK: u32 = 0xA3; | 484 | const SIMPLE_BLOCK: u32 = 0xA3; |
| 485 | +const TRACK_NAME: u32 = 0x536E; | ||
| 486 | +const TRACK_LANGUAGE: u32 = 0x22B59C; | ||
| 487 | +const BLOCK_GROUP: u32 = 0xA0; | ||
| 488 | +const BLOCK: u32 = 0xA1; | ||
| 489 | +const BLOCK_DURATION: u32 = 0x9B; | ||
| 485 | 490 | ||
| 486 | /// One millisecond, the tick every Matroska muxer writes and this one's block | 491 | /// One millisecond, the tick every Matroska muxer writes and this one's block |
| 487 | /// timestamps are in. The *rate* is not derived from these -- `DefaultDuration` | 492 | /// timestamps are in. The *rate* is not derived from these -- `DefaultDuration` |
| @@ -532,6 +537,34 @@ pub struct HevcParams<'a> { | |||
| 532 | pub hvcc: &'a [u8], | 537 | pub hvcc: &'a [u8], |
| 533 | } | 538 | } |
| 534 | 539 | ||
| 540 | +/// The soft subtitle track a Matroska file carries beside the picture: text, | ||
| 541 | +/// timed, still text in the file -- a player draws it and a user can turn it | ||
| 542 | +/// off, which is what "soft" means and what burning it into the pixels is not. | ||
| 543 | +/// | ||
| 544 | +/// The cues are the *exported timeline's* (`export::timeline_cues` puts them | ||
| 545 | +/// there), because the file's clock is the timeline's; nothing here shifts | ||
| 546 | +/// anything. | ||
| 547 | +pub struct SubParams { | ||
| 548 | + /// What the track is called in the file. A three-letter code goes in as | ||
| 549 | + /// `Language`, which is what a player's subtitle menu reads; anything else | ||
| 550 | + /// is a `Name`, which is what it shows when there is no language to show. | ||
| 551 | + /// | ||
| 552 | + /// ponytail: one string for both because a [`crate::subtitle::SubtitleTrack`] | ||
| 553 | + /// carries one label and not a (language, name) pair. The upgrade path is to | ||
| 554 | + /// keep the two apart from the demuxer down -- `MkvSubtitle` already has | ||
| 555 | + /// them -- and it belongs to whoever needs a per-language export list. | ||
| 556 | + pub label: String, | ||
| 557 | + /// In start order, which is the order they are written in. | ||
| 558 | + pub cues: Vec<crate::subtitle::Cue>, | ||
| 559 | +} | ||
| 560 | + | ||
| 561 | +/// The cues waiting to be interleaved into the clusters, [`MkvAudio`]'s twin. | ||
| 562 | +struct MkvSubs { | ||
| 563 | + cues: Vec<crate::subtitle::Cue>, | ||
| 564 | + /// Cues already written. | ||
| 565 | + next: usize, | ||
| 566 | +} | ||
| 567 | + | ||
| 535 | /// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC | 568 | /// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC |
| 536 | /// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the | 569 | /// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the |
| 537 | /// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what | 570 | /// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what |
| @@ -562,6 +595,9 @@ pub struct MkvMuxer { | |||
| 562 | /// The AAC track, if the timeline has sound, and how far it has been | 595 | /// The AAC track, if the timeline has sound, and how far it has been |
| 563 | /// written. | 596 | /// written. |
| 564 | audio: Option<MkvAudio>, | 597 | audio: Option<MkvAudio>, |
| 598 | + /// The subtitle track, if one travels with the file, and how far it has | ||
| 599 | + /// been written. | ||
| 600 | + subs: Option<MkvSubs>, | ||
| 565 | } | 601 | } |
| 566 | 602 | ||
| 567 | /// The sound waiting to be interleaved into the clusters. | 603 | /// The sound waiting to be interleaved into the clusters. |
| @@ -588,6 +624,7 @@ impl MkvMuxer { | |||
| 588 | path: &Path, | 624 | path: &Path, |
| 589 | video: &Av1Params, | 625 | video: &Av1Params, |
| 590 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | 626 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, |
| 627 | + subs: Option<SubParams>, | ||
| 591 | ) -> crate::Result<Self> { | 628 | ) -> crate::Result<Self> { |
| 592 | if video.config.is_empty() { | 629 | if video.config.is_empty() { |
| 593 | return Err("no AV1 sequence header for the track's CodecPrivate".into()); | 630 | return Err("no AV1 sequence header for the track's CodecPrivate".into()); |
| @@ -602,6 +639,7 @@ impl MkvMuxer { | |||
| 602 | b"V_AV1", | 639 | b"V_AV1", |
| 603 | &av1c, | 640 | &av1c, |
| 604 | audio, | 641 | audio, |
| 642 | + subs, | ||
| 605 | ) | 643 | ) |
| 606 | } | 644 | } |
| 607 | 645 | ||
| @@ -616,6 +654,7 @@ impl MkvMuxer { | |||
| 616 | path: &Path, | 654 | path: &Path, |
| 617 | video: &HevcParams, | 655 | video: &HevcParams, |
| 618 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | 656 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, |
| 657 | + subs: Option<SubParams>, | ||
| 619 | ) -> crate::Result<Self> { | 658 | ) -> crate::Result<Self> { |
| 620 | if video.hvcc.is_empty() { | 659 | if video.hvcc.is_empty() { |
| 621 | return Err("no hvcC record for the track's CodecPrivate".into()); | 660 | return Err("no hvcC record for the track's CodecPrivate".into()); |
| @@ -628,9 +667,11 @@ impl MkvMuxer { | |||
| 628 | b"V_MPEGH/ISO/HEVC", | 667 | b"V_MPEGH/ISO/HEVC", |
| 629 | video.hvcc, | 668 | video.hvcc, |
| 630 | audio, | 669 | audio, |
| 670 | + subs, | ||
| 631 | ) | 671 | ) |
| 632 | } | 672 | } |
| 633 | 673 | ||
| 674 | + #[allow(clippy::too_many_arguments)] | ||
| 634 | fn open( | 675 | fn open( |
| 635 | path: &Path, | 676 | path: &Path, |
| 636 | width: u32, | 677 | width: u32, |
| @@ -639,6 +680,7 @@ impl MkvMuxer { | |||
| 639 | codec_id: &[u8], | 680 | codec_id: &[u8], |
| 640 | codec_private: &[u8], | 681 | codec_private: &[u8], |
| 641 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | 682 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, |
| 683 | + subs: Option<SubParams>, | ||
| 642 | ) -> crate::Result<Self> { | 684 | ) -> crate::Result<Self> { |
| 643 | if !frame_rate.is_finite() || frame_rate <= 0.0 { | 685 | if !frame_rate.is_finite() || frame_rate <= 0.0 { |
| 644 | return Err(format!("bad frame rate {frame_rate}").into()); | 686 | return Err(format!("bad frame rate {frame_rate}").into()); |
| @@ -697,6 +739,12 @@ impl MkvMuxer { | |||
| 697 | if let Some((audio, _)) = &audio { | 739 | if let Some((audio, _)) = &audio { |
| 698 | elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?); | 740 | elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?); |
| 699 | } | 741 | } |
| 742 | + // Declared even where the audio track is not: the numbers are fixed | ||
| 743 | + // (1 picture, 2 sound, 3 text) rather than counted, so a file with | ||
| 744 | + // subtitles and no sound still says track 3 in its blocks. | ||
| 745 | + if let Some(subs) = &subs { | ||
| 746 | + elem(&mut tracks, TRACK_ENTRY, &subtitle_track_entry(&subs.label)); | ||
| 747 | + } | ||
| 700 | elem(&mut head, TRACKS, &tracks); | 748 | elem(&mut head, TRACKS, &tracks); |
| 701 | 749 | ||
| 702 | let mut file = File::create(path)?; | 750 | let mut file = File::create(path)?; |
| @@ -715,6 +763,10 @@ impl MkvMuxer { | |||
| 715 | samples: 0, | 763 | samples: 0, |
| 716 | sample_rate: params.sample_rate.max(1), | 764 | sample_rate: params.sample_rate.max(1), |
| 717 | }), | 765 | }), |
| 766 | + subs: subs.map(|subs| MkvSubs { | ||
| 767 | + cues: subs.cues, | ||
| 768 | + next: 0, | ||
| 769 | + }), | ||
| 718 | }) | 770 | }) |
| 719 | } | 771 | } |
| 720 | 772 | ||
| @@ -742,8 +794,10 @@ impl MkvMuxer { | |||
| 742 | uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); | 794 | uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); |
| 743 | } | 795 | } |
| 744 | // The sound this picture plays under goes in first, into the cluster the | 796 | // The sound this picture plays under goes in first, into the cluster the |
| 745 | - // picture opened: a player reads the two together. | 797 | + // picture opened: a player reads the two together. The cue over it with |
| 798 | + // them, for the same reason. | ||
| 746 | self.drain_audio(ts)?; | 799 | self.drain_audio(ts)?; |
| 800 | + self.drain_subs(ts)?; | ||
| 747 | self.block(1, ts, key, obus); | 801 | self.block(1, ts, key, obus); |
| 748 | self.frames += 1; | 802 | self.frames += 1; |
| 749 | Ok(()) | 803 | Ok(()) |
| @@ -784,6 +838,41 @@ impl MkvMuxer { | |||
| 784 | } | 838 | } |
| 785 | } | 839 | } |
| 786 | 840 | ||
| 841 | + /// Every cue that has come up by `until`, into the current cluster -- | ||
| 842 | + /// [`drain_audio`](MkvMuxer::drain_audio)'s twin, and `i64::MAX` at | ||
| 843 | + /// [`finish`](MkvMuxer::finish) writes what is left: a cue may still be on | ||
| 844 | + /// screen over the last picture, and one written nowhere is one a player | ||
| 845 | + /// never shows. | ||
| 846 | + fn drain_subs(&mut self, until: i64) -> crate::Result<()> { | ||
| 847 | + loop { | ||
| 848 | + let Some(subs) = &mut self.subs else { | ||
| 849 | + return Ok(()); | ||
| 850 | + }; | ||
| 851 | + let Some(cue) = subs.cues.get_mut(subs.next) else { | ||
| 852 | + return Ok(()); | ||
| 853 | + }; | ||
| 854 | + // Milliseconds, the tick this file is written in: a cue is read for | ||
| 855 | + // a second or more and no eye finds the half a tick it rounds by. | ||
| 856 | + let ts = (cue.start_us + 500) / 1_000; | ||
| 857 | + if ts > until { | ||
| 858 | + return Ok(()); | ||
| 859 | + } | ||
| 860 | + // A cue that says it ends before it starts stays up for one tick | ||
| 861 | + // rather than for a duration a reader would take as unsigned. | ||
| 862 | + let ms = ((cue.end_us - cue.start_us + 500) / 1_000).max(1) as u64; | ||
| 863 | + let text = std::mem::take(&mut cue.text); | ||
| 864 | + subs.next += 1; | ||
| 865 | + // A cluster of its own where the text has run past what a 16-bit | ||
| 866 | + // relative timestamp reaches, exactly as the sound's drain does. | ||
| 867 | + if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS { | ||
| 868 | + self.flush()?; | ||
| 869 | + self.cluster_ts = ts; | ||
| 870 | + uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); | ||
| 871 | + } | ||
| 872 | + self.block_group(SUB_TRACK, ts, ms, text.as_bytes()); | ||
| 873 | + } | ||
| 874 | + } | ||
| 875 | + | ||
| 787 | /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC | 876 | /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC |
| 788 | /// packet is a keyframe; a picture is one when the encoder said so. | 877 | /// packet is a keyframe; a picture is one when the encoder said so. |
| 789 | fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) { | 878 | fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) { |
| @@ -795,6 +884,24 @@ impl MkvMuxer { | |||
| 795 | elem(&mut self.cluster, SIMPLE_BLOCK, &block); | 884 | elem(&mut self.cluster, SIMPLE_BLOCK, &block); |
| 796 | } | 885 | } |
| 797 | 886 | ||
| 887 | + /// One `BlockGroup`: a `Block` and the `BlockDuration` beside it. That pair | ||
| 888 | + /// is how a cue says when it goes away -- a `SimpleBlock` has nowhere to put | ||
| 889 | + /// a duration, and a subtitle without one stays up until whatever a player | ||
| 890 | + /// decides, which is what a subtitle must never do. | ||
| 891 | + fn block_group(&mut self, track: u8, ts: i64, duration_ms: u64, payload: &[u8]) { | ||
| 892 | + let mut block = Vec::with_capacity(payload.len() + 4); | ||
| 893 | + block.push(0x80 | track); // the track number as a one-byte EBML integer | ||
| 894 | + block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes()); | ||
| 895 | + // No flags a text block can carry: not lacing, and "keyframe" is a | ||
| 896 | + // `SimpleBlock` field that a plain `Block` does not have at all. | ||
| 897 | + block.push(0); | ||
| 898 | + block.extend_from_slice(payload); | ||
| 899 | + let mut group = Vec::new(); | ||
| 900 | + elem(&mut group, BLOCK, &block); | ||
| 901 | + uint(&mut group, BLOCK_DURATION, duration_ms); | ||
| 902 | + elem(&mut self.cluster, BLOCK_GROUP, &group); | ||
| 903 | + } | ||
| 904 | + | ||
| 798 | fn flush(&mut self) -> crate::Result<()> { | 905 | fn flush(&mut self) -> crate::Result<()> { |
| 799 | if self.cluster.is_empty() { | 906 | if self.cluster.is_empty() { |
| 800 | return Ok(()); | 907 | return Ok(()); |
| @@ -814,6 +921,7 @@ impl MkvMuxer { | |||
| 814 | // Whatever sound outlasts the last picture, before the last cluster is | 921 | // Whatever sound outlasts the last picture, before the last cluster is |
| 815 | // closed: a track cut short here is a file that goes silent at the end. | 922 | // closed: a track cut short here is a file that goes silent at the end. |
| 816 | self.drain_audio(i64::MAX)?; | 923 | self.drain_audio(i64::MAX)?; |
| 924 | + self.drain_subs(i64::MAX)?; | ||
| 817 | self.flush()?; | 925 | self.flush()?; |
| 818 | if self.frames == 0 { | 926 | if self.frames == 0 { |
| 819 | return Err("no frames were written to the Matroska file".into()); | 927 | return Err("no frames were written to the Matroska file".into()); |
| @@ -878,6 +986,36 @@ fn aac_track_entry(audio: &AudioParams) -> crate::Result<Vec<u8>> { | |||
| 878 | Ok(entry) | 986 | Ok(entry) |
| 879 | } | 987 | } |
| 880 | 988 | ||
| 989 | +/// Which track a subtitle block names. Fixed, like the picture's 1 and the | ||
| 990 | +/// sound's 2: a file with no audio track still writes its text on 3, so nothing | ||
| 991 | +/// has to count tracks to read a block. | ||
| 992 | +const SUB_TRACK: u8 = 3; | ||
| 993 | + | ||
| 994 | +/// The `TrackEntry` of the subtitle track: type 0x11 (subtitles) and | ||
| 995 | +/// `S_TEXT/UTF8`, whose blocks are the cue's own UTF-8 text and whose timing is | ||
| 996 | +/// the block's -- the codec every player draws and the one this project's own | ||
| 997 | +/// reader parses back (`subtitle::cues_of`). | ||
| 998 | +/// | ||
| 999 | +/// The label is a `Language` where it is one (`eng`, `tur`: three letters is | ||
| 1000 | +/// what ISO-639-2 is) and a `Name` otherwise, which is exactly what | ||
| 1001 | +/// [`crate::subtitle::of_matroska`] reads back out, so a track exported and | ||
| 1002 | +/// re-imported keeps the name it had. | ||
| 1003 | +fn subtitle_track_entry(label: &str) -> Vec<u8> { | ||
| 1004 | + let mut entry = Vec::new(); | ||
| 1005 | + uint(&mut entry, TRACK_NUMBER, u64::from(SUB_TRACK)); | ||
| 1006 | + uint(&mut entry, TRACK_UID, u64::from(SUB_TRACK)); | ||
| 1007 | + uint(&mut entry, TRACK_TYPE, 0x11); | ||
| 1008 | + uint(&mut entry, FLAG_LACING, 0); | ||
| 1009 | + elem(&mut entry, CODEC_ID, b"S_TEXT/UTF8"); | ||
| 1010 | + let code = label.len() == 3 && label.bytes().all(|b| b.is_ascii_lowercase()); | ||
| 1011 | + match (code, label.is_empty()) { | ||
| 1012 | + (true, _) => elem(&mut entry, TRACK_LANGUAGE, label.as_bytes()), | ||
| 1013 | + (false, false) => elem(&mut entry, TRACK_NAME, label.as_bytes()), | ||
| 1014 | + (false, true) => {} | ||
| 1015 | + } | ||
| 1016 | + entry | ||
| 1017 | +} | ||
| 1018 | + | ||
| 881 | /// The sequence header OBU of a coded temporal unit, for the track's | 1019 | /// The sequence header OBU of a coded temporal unit, for the track's |
| 882 | /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe | 1020 | /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe |
| 883 | /// of a stream never may -- no decoder can start without it. | 1021 | /// of a stream never may -- no decoder can start without it. |
| @@ -1444,6 +1582,7 @@ mod tests { | |||
| 1444 | }, | 1582 | }, |
| 1445 | packets, | 1583 | packets, |
| 1446 | )), | 1584 | )), |
| 1585 | + None, | ||
| 1447 | ) | 1586 | ) |
| 1448 | .unwrap(); | 1587 | .unwrap(); |
| 1449 | // Half a second of picture under a second of sound: the tail of the | 1588 | // Half a second of picture under a second of sound: the tail of the |
| @@ -1571,6 +1710,7 @@ mod tests { | |||
| 1571 | config, | 1710 | config, |
| 1572 | }, | 1711 | }, |
| 1573 | None, | 1712 | None, |
| 1713 | + None, | ||
| 1574 | ) | 1714 | ) |
| 1575 | .unwrap(); | 1715 | .unwrap(); |
| 1576 | muxer.write_frame(&key, true).unwrap(); | 1716 | muxer.write_frame(&key, true).unwrap(); |
| @@ -1614,6 +1754,7 @@ mod tests { | |||
| 1614 | config: &[], | 1754 | config: &[], |
| 1615 | }, | 1755 | }, |
| 1616 | None, | 1756 | None, |
| 1757 | + None, | ||
| 1617 | ) | 1758 | ) |
| 1618 | .is_err() | 1759 | .is_err() |
| 1619 | ); | 1760 | ); |
crates/engine/src/playback.rsmodified+8 -0
| @@ -752,6 +752,14 @@ impl PlaybackSession { | |||
| 752 | crate::export::planned_audio(&self.project, format) | 752 | crate::export::planned_audio(&self.project, format) |
| 753 | } | 753 | } |
| 754 | 754 | ||
| 755 | + /// What an export would do about the subtitle track at `pick` -- | ||
| 756 | + /// [`crate::export::planned_subtitles`], asked of the project a front-end is | ||
| 757 | + /// holding, and pure for the same reason. `pick` is a row of | ||
| 758 | + /// [`subtitles`](Self::subtitles). | ||
| 759 | + pub fn planned_subtitles(&self, format: crate::export::Format, pick: Option<usize>) -> String { | ||
| 760 | + crate::export::planned_subtitles(&self.project, format, pick) | ||
| 761 | + } | ||
| 762 | + | ||
| 755 | /// Why the sound's rate is not a choice for this timeline in this format -- | 763 | /// Why the sound's rate is not a choice for this timeline in this format -- |
| 756 | /// [`crate::export::audio_rate_refusal`], asked of the project a front-end | 764 | /// [`crate::export::audio_rate_refusal`], asked of the project a front-end |
| 757 | /// is holding, and pure for the same reason. | 765 | /// is holding, and pure for the same reason. |
crates/engine/src/project.rsmodified+1 -1
| @@ -3063,7 +3063,7 @@ fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) { | |||
| 3063 | /// Absolute, symlink-resolved when the file is reachable; the path as given | 3063 | /// Absolute, symlink-resolved when the file is reachable; the path as given |
| 3064 | /// when it is not -- an unreadable path still deserves an index, it simply | 3064 | /// when it is not -- an unreadable path still deserves an index, it simply |
| 3065 | /// dedups by spelling. | 3065 | /// dedups by spelling. |
| 3066 | -fn canonical(path: &Path) -> PathBuf { | 3066 | +pub(crate) fn canonical(path: &Path) -> PathBuf { |
| 3067 | std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) | 3067 | std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) |
| 3068 | } | 3068 | } |
| 3069 | 3069 | ||
crates/engine/tests/export_subs.rsadded+295 -0
| @@ -0,0 +1,295 @@ | |||
| 1 | +//! Subtitles leave with the file: a Matroska export carries the picked track as | ||
| 2 | +//! `S_TEXT/UTF8`, timed on the *exported* timeline -- so a cut moves the cues | ||
| 3 | +//! with the pictures they belong to -- and an mp4 says it cannot rather than | ||
| 4 | +//! dropping them in silence. | ||
| 5 | +//! | ||
| 6 | +//! Two witnesses for every cue: this project's own Matroska reader | ||
| 7 | +//! (`demux::matroska_subtitles`, the way an exported file comes back into a | ||
| 8 | +//! project) and, where the box has it, ffmpeg -- which is what "it plays | ||
| 9 | +//! elsewhere" means and the only thing that can say this file is not merely | ||
| 10 | +//! self-consistent. | ||
| 11 | +//! | ||
| 12 | +//! ```text | ||
| 13 | +//! cargo test -p engine --release --test export_subs -- --nocapture | ||
| 14 | +//! ``` | ||
| 15 | + | ||
| 16 | +use std::path::{Path, PathBuf}; | ||
| 17 | +use std::process::Command; | ||
| 18 | +use std::sync::Once; | ||
| 19 | +use std::time::{Duration, Instant}; | ||
| 20 | + | ||
| 21 | +use engine::export::{ExportSettings, Format}; | ||
| 22 | +use engine::project::Lane; | ||
| 23 | +use engine::subtitle::{self, Cue, SubtitleTrack}; | ||
| 24 | +use engine::{ExportHandle, Project}; | ||
| 25 | + | ||
| 26 | +/// The media fixture: five seconds at 30 fps, and a picture this box can decode | ||
| 27 | +/// with nothing installed. | ||
| 28 | +const MEDIA: &str = "test_av.mp4"; | ||
| 29 | +const FRAMES: u32 = 150; | ||
| 30 | +/// What a cue may be out by: the file's own tick, a millisecond. The mapping is | ||
| 31 | +/// exact microseconds -- only the write rounds -- so nothing wider than this is | ||
| 32 | +/// being allowed for. | ||
| 33 | +const SLACK_US: i64 = 1_000; | ||
| 34 | + | ||
| 35 | +fn asset(name: &str) -> PathBuf { | ||
| 36 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 37 | + .join("../../assets") | ||
| 38 | + .join(name) | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +fn out_path(name: &str) -> PathBuf { | ||
| 42 | + let path = | ||
| 43 | + std::env::temp_dir().join(format!("ve_subs_export_{name}_{}.mkv", std::process::id())); | ||
| 44 | + let _ = std::fs::remove_file(&path); | ||
| 45 | + path | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +fn pin_software() { | ||
| 49 | + static PIN: Once = Once::new(); | ||
| 50 | + PIN.call_once(|| unsafe { | ||
| 51 | + std::env::set_var("VE_SW", "1"); | ||
| 52 | + std::env::set_var("VE_SW_ENC", "1"); | ||
| 53 | + }); | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { | ||
| 57 | + let started = Instant::now(); | ||
| 58 | + while !handle.is_finished() { | ||
| 59 | + assert!( | ||
| 60 | + started.elapsed() < limit, | ||
| 61 | + "export did not finish in {limit:?}" | ||
| 62 | + ); | ||
| 63 | + std::thread::sleep(Duration::from_millis(20)); | ||
| 64 | + } | ||
| 65 | + handle.result().expect("a finished export has an outcome") | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/// The three cues the subtitle fixtures hold (`tests/subtitles.rs` pins them | ||
| 69 | +/// against the real `.srt`, `.ass` and `.mkv`), on a timeline of the media they | ||
| 70 | +/// are timed against. | ||
| 71 | +/// | ||
| 72 | +/// The track says it came out of *this* media file, which is what an embedded | ||
| 73 | +/// track is and what makes its cues the file's own clock rather than the | ||
| 74 | +/// timeline's. Written out here rather than read out of `test_subs.mkv` because | ||
| 75 | +/// that fixture's picture is AV1 and there is no software AV1 decoder to export | ||
| 76 | +/// it through; the cues are the same three either way. | ||
| 77 | +fn track() -> SubtitleTrack { | ||
| 78 | + SubtitleTrack { | ||
| 79 | + path: asset(MEDIA), | ||
| 80 | + track: Some(2), | ||
| 81 | + label: "eng".into(), | ||
| 82 | + cues: vec![ | ||
| 83 | + Cue { | ||
| 84 | + start_us: 500_000, | ||
| 85 | + end_us: 1_500_000, | ||
| 86 | + text: "first line".into(), | ||
| 87 | + }, | ||
| 88 | + Cue { | ||
| 89 | + start_us: 2_000_000, | ||
| 90 | + end_us: 3_250_000, | ||
| 91 | + text: "second line\nwith a break".into(), | ||
| 92 | + }, | ||
| 93 | + Cue { | ||
| 94 | + start_us: 4_000_000, | ||
| 95 | + end_us: 4_750_000, | ||
| 96 | + text: "third line".into(), | ||
| 97 | + }, | ||
| 98 | + ], | ||
| 99 | + refused: None, | ||
| 100 | + } | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +fn project() -> Project { | ||
| 104 | + Project::single(asset(MEDIA), FRAMES).with_subtitles(vec![track()]) | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// Exports `project` as an HEVC Matroska carrying subtitle track `pick`, and | ||
| 108 | +/// hands back what our own reader finds in the file. | ||
| 109 | +fn exported(name: &str, project: Project, pick: Option<usize>) -> (PathBuf, Vec<Cue>) { | ||
| 110 | + pin_software(); | ||
| 111 | + let out = out_path(name); | ||
| 112 | + let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media"); | ||
| 113 | + let handle = engine::export::start( | ||
| 114 | + project, | ||
| 115 | + meta, | ||
| 116 | + &out, | ||
| 117 | + &ExportSettings { | ||
| 118 | + format: Format::Hevc, | ||
| 119 | + subtitles: pick, | ||
| 120 | + ..Default::default() | ||
| 121 | + }, | ||
| 122 | + ); | ||
| 123 | + wait(&handle, Duration::from_secs(300)).expect("the export finishes"); | ||
| 124 | + let tracks = subtitle::of_matroska(&out).expect("read the export back"); | ||
| 125 | + match pick { | ||
| 126 | + None => { | ||
| 127 | + assert!(tracks.is_empty(), "no pick, no track: {tracks:?}"); | ||
| 128 | + (out, Vec::new()) | ||
| 129 | + } | ||
| 130 | + Some(_) => { | ||
| 131 | + assert_eq!(tracks.len(), 1, "exactly the picked track: {tracks:?}"); | ||
| 132 | + assert_eq!(tracks[0].refused, None, "the track reads back as text"); | ||
| 133 | + (out, tracks[0].cues.clone()) | ||
| 134 | + } | ||
| 135 | + } | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +/// What ffmpeg makes of the same file's subtitle track, as an SRT on stdout: | ||
| 139 | +/// a second implementation reading the bytes, which is the whole point of it. | ||
| 140 | +/// `None` where there is no ffmpeg on the box -- the test is not about this | ||
| 141 | +/// machine's packages. | ||
| 142 | +fn ffmpeg_srt(path: &Path) -> Option<String> { | ||
| 143 | + let out = Command::new("ffmpeg") | ||
| 144 | + .args(["-v", "error", "-i"]) | ||
| 145 | + .arg(path) | ||
| 146 | + .args(["-map", "0:s:0", "-f", "srt", "-"]) | ||
| 147 | + .output() | ||
| 148 | + .ok()?; | ||
| 149 | + assert!( | ||
| 150 | + out.status.success(), | ||
| 151 | + "ffmpeg refused the exported subtitles: {}", | ||
| 152 | + String::from_utf8_lossy(&out.stderr) | ||
| 153 | + ); | ||
| 154 | + Some(String::from_utf8_lossy(&out.stdout).into_owned()) | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +fn near(got: i64, want: i64, what: &str) { | ||
| 158 | + assert!( | ||
| 159 | + (got - want).abs() <= SLACK_US, | ||
| 160 | + "{what}: {got} us is not within a frame of {want} us" | ||
| 161 | + ); | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +/// The whole timeline, untouched: the file comes back with the very cues the | ||
| 165 | +/// source's track holds, at the times it holds them -- and ffmpeg reads the | ||
| 166 | +/// same three lines out of it. | ||
| 167 | +#[test] | ||
| 168 | +fn an_mkv_export_carries_the_picked_subtitle_track() { | ||
| 169 | + let (out, cues) = exported("plain", project(), Some(0)); | ||
| 170 | + assert_eq!(cues.len(), 3, "three cues: {cues:?}"); | ||
| 171 | + let want = [ | ||
| 172 | + (500_000, 1_500_000, "first line"), | ||
| 173 | + (2_000_000, 3_250_000, "second line\nwith a break"), | ||
| 174 | + (4_000_000, 4_750_000, "third line"), | ||
| 175 | + ]; | ||
| 176 | + for (cue, (start, end, text)) in cues.iter().zip(want) { | ||
| 177 | + near(cue.start_us, start, "cue start"); | ||
| 178 | + near(cue.end_us, end, "cue end"); | ||
| 179 | + assert_eq!(cue.text, text, "the text travels, line breaks and all"); | ||
| 180 | + } | ||
| 181 | + // ...and the track is named the way it was named in the source, so the | ||
| 182 | + // subtitle menu of whatever plays this says `eng` too. | ||
| 183 | + let tracks = subtitle::of_matroska(&out).expect("read back"); | ||
| 184 | + assert_eq!(tracks[0].label, "eng"); | ||
| 185 | + let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element"); | ||
| 186 | + assert_eq!(raw[0].codec, "S_TEXT/UTF8"); | ||
| 187 | + assert_eq!(raw[0].language, "eng", "the label went in as a language"); | ||
| 188 | + | ||
| 189 | + match ffmpeg_srt(&out) { | ||
| 190 | + Some(srt) => { | ||
| 191 | + println!("ffmpeg reads the exported track back as:\n{srt}"); | ||
| 192 | + assert!(srt.contains("first line"), "{srt}"); | ||
| 193 | + assert!(srt.contains("with a break"), "{srt}"); | ||
| 194 | + assert!(srt.contains("00:00:00,500 --> 00:00:01,500"), "{srt}"); | ||
| 195 | + assert!(srt.contains("00:00:04,000 --> 00:00:04,750"), "{srt}"); | ||
| 196 | + } | ||
| 197 | + None => println!("no ffmpeg on this box: our own reader is the only witness"), | ||
| 198 | + } | ||
| 199 | + std::fs::remove_file(&out).unwrap(); | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +/// A cut timeline: `[0.5s, 2.5s)` rippled out of it, which is one cue gone | ||
| 203 | +/// entirely, one that straddles the far edge and keeps the half still there, | ||
| 204 | +/// and one that simply moves back with the picture. | ||
| 205 | +#[test] | ||
| 206 | +fn a_cut_moves_the_cues_with_the_pictures() { | ||
| 207 | + let mut project = project(); | ||
| 208 | + assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out"); | ||
| 209 | + assert_eq!(project.timeline_frames(), 90, "three seconds are left"); | ||
| 210 | + assert_eq!( | ||
| 211 | + project.lane(Lane::V1).len(), | ||
| 212 | + 2, | ||
| 213 | + "the hole closed, over two placements of the one source" | ||
| 214 | + ); | ||
| 215 | + | ||
| 216 | + let (out, cues) = exported("cut", project, Some(0)); | ||
| 217 | + assert_eq!( | ||
| 218 | + cues.len(), | ||
| 219 | + 2, | ||
| 220 | + "the cue inside the cut is gone, the other two are not: {cues:?}" | ||
| 221 | + ); | ||
| 222 | + // 2.0s..3.25s of the source, of which 2.5s on survived, landing where the | ||
| 223 | + // cut left it: 0.5s..1.25s. | ||
| 224 | + near( | ||
| 225 | + cues[0].start_us, | ||
| 226 | + 500_000, | ||
| 227 | + "the straddling cue starts at the cut", | ||
| 228 | + ); | ||
| 229 | + near( | ||
| 230 | + cues[0].end_us, | ||
| 231 | + 1_250_000, | ||
| 232 | + "...and keeps the rest of its length", | ||
| 233 | + ); | ||
| 234 | + assert_eq!(cues[0].text, "second line\nwith a break"); | ||
| 235 | + // 4.0s..4.75s of the source, two seconds back. | ||
| 236 | + near( | ||
| 237 | + cues[1].start_us, | ||
| 238 | + 2_000_000, | ||
| 239 | + "the last cue moves back by the cut", | ||
| 240 | + ); | ||
| 241 | + near(cues[1].end_us, 2_750_000, "...end with it"); | ||
| 242 | + assert_eq!(cues[1].text, "third line"); | ||
| 243 | + | ||
| 244 | + if let Some(srt) = ffmpeg_srt(&out) { | ||
| 245 | + println!("ffmpeg reads the cut export back as:\n{srt}"); | ||
| 246 | + assert!( | ||
| 247 | + !srt.contains("first line"), | ||
| 248 | + "the cut cue is not there: {srt}" | ||
| 249 | + ); | ||
| 250 | + assert!(srt.contains("00:00:00,500 --> 00:00:01,250"), "{srt}"); | ||
| 251 | + assert!(srt.contains("00:00:02,000 --> 00:00:02,750"), "{srt}"); | ||
| 252 | + assert!(srt.contains("third line"), "{srt}"); | ||
| 253 | + } | ||
| 254 | + std::fs::remove_file(&out).unwrap(); | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +/// Nothing picked is nothing written -- the file every export of a timeline | ||
| 258 | +/// without subtitles has always been. | ||
| 259 | +#[test] | ||
| 260 | +fn an_export_with_no_pick_carries_no_subtitle_track() { | ||
| 261 | + // `exported` asserts the file has no subtitle track at all; this is the | ||
| 262 | + // pick being absent rather than the timeline having nothing to pick. | ||
| 263 | + let (out, cues) = exported("none", project(), None); | ||
| 264 | + assert_eq!(cues, Vec::new()); | ||
| 265 | + std::fs::remove_file(&out).unwrap(); | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +/// What the card says before the button is pressed, which is where an mp4's | ||
| 269 | +/// refusal has to land: the file is not the place to find out. | ||
| 270 | +#[test] | ||
| 271 | +fn the_plan_says_what_each_container_does_with_them() { | ||
| 272 | + let project = project(); | ||
| 273 | + let plan = |format| engine::export::planned_subtitles(&project, format, Some(0)); | ||
| 274 | + assert_eq!(plan(Format::Hevc), "eng → embedded"); | ||
| 275 | + assert_eq!(plan(Format::Av1), "eng → embedded"); | ||
| 276 | + assert_eq!(plan(Format::Mp4), "mkv only — an mp4 carries none"); | ||
| 277 | + assert_eq!(plan(Format::HevcMp4), "mkv only — an mp4 carries none"); | ||
| 278 | + assert_eq!(plan(Format::Wav), "none — this format is the sound alone"); | ||
| 279 | + // No pick, and a pick nothing answers, are both "none" rather than a panic | ||
| 280 | + // or a lie. | ||
| 281 | + assert_eq!( | ||
| 282 | + engine::export::planned_subtitles(&project, Format::Hevc, None), | ||
| 283 | + "none" | ||
| 284 | + ); | ||
| 285 | + assert_eq!( | ||
| 286 | + engine::export::planned_subtitles(&project, Format::Hevc, Some(9)), | ||
| 287 | + "none" | ||
| 288 | + ); | ||
| 289 | + // A timeline that never had subtitles says the same thing. | ||
| 290 | + let bare = Project::single(asset(MEDIA), FRAMES); | ||
| 291 | + assert_eq!( | ||
| 292 | + engine::export::planned_subtitles(&bare, Format::Hevc, Some(0)), | ||
| 293 | + "none" | ||
| 294 | + ); | ||
| 295 | +} | ||