forge
Explore
Log in

Don't you dare go Hollow

Merge remote-tracking branch 'origin/main' into worktree-agent-ab6959260e5ee211c

Browse files at this commit

0776b4689099884fccd41b702616072d710b969aAhmet Kaan GümüşParent: 1e8c454d9fd7cf
# Conflicts:
#	crates/engine/src/audio.rs

20 changed files +1886 -177

Cargo.lockmodified+89 -0
@@ -1003,6 +1003,12 @@ dependencies = [
10031003 "thiserror 2.0.20",
10041004 ]
10051005
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+
10061012 [[package]]
10071013 name = "compression-codecs"
10081014 version = "0.4.38"
@@ -1636,8 +1642,10 @@ dependencies = [
16361642 "libloading",
16371643 "mp4",
16381644 "oxideav-ac3",
1645+ "oxideav-ass",
16391646 "oxideav-core",
16401647 "oxideav-h265",
1648+ "oxideav-subtitle",
16411649 "rav1e",
16421650 "rusty_aac",
16431651 "rusty_h264",
@@ -3940,6 +3948,16 @@ dependencies = [
39403948 "oxideav-core",
39413949 ]
39423950
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+
39433961 [[package]]
39443962 name = "oxideav-core"
39453963 version = "0.1.34"
@@ -3958,6 +3976,77 @@ dependencies = [
39583976 "oxideav-core",
39593977 ]
39603978
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+
39614050 [[package]]
39624051 name = "parking"
39634052 version = "2.2.1"
Cargo.tomlmodified+4 -1
@@ -23,7 +23,10 @@ edition = "2024"
2323 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per
2424 # term (the fast path in the same file serves the encoder only),
2525 # which is 4x slower than real time for 5.1 and therefore not
26-# playable at all; the patch caches the cosine matrix
26+# 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
2730 # oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and
2831 # refuses any dimension that is not a multiple of the 16-sample
2932 # CTB, so 1920x1080 could not be written at all; the patch adds
crates/app/src/main.rsmodified+265 -79
@@ -260,6 +260,10 @@ enum Wave {
260260 Loading,
261261 /// The file has no audio track. An answer, not a miss.
262262 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,
263267 Peaks(Arc<Vec<(f32, f32)>>),
264268 }
265269
@@ -614,6 +618,48 @@ const HIST_H: f32 = 96.;
614618 /// counts, lightened enough to read on the dark box.
615619 const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0];
616620
621+/// Where the transport is. The one answer the button's glyph, its label, its
622+/// enablement, the play key and the repaint loop all read -- there is no play
623+/// flag anywhere else, because a second one is a second answer.
624+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
625+enum Transport {
626+ /// No timeline open. Nothing to play and the transport is dimmed.
627+ Stopped,
628+ Playing,
629+ Paused,
630+ /// Played out: the last frame is on screen, the decoder is finished, and the
631+ /// clock is still running past it -- which is exactly why "is the clock
632+ /// going" is not the same question as "is this playing".
633+ Ended,
634+}
635+
636+impl Transport {
637+ /// The timeline is in motion: two bars on the button, and a repaint owed
638+ /// every vsync.
639+ fn is_playing(self) -> bool {
640+ matches!(self, Transport::Playing)
641+ }
642+
643+ /// The play key and the transport button start over from the top rather
644+ /// than toggling -- the end of a timeline is where every NLE does this, and
645+ /// the button does it because the key already did.
646+ fn restarts(self) -> bool {
647+ matches!(self, Transport::Ended)
648+ }
649+}
650+
651+/// What a session's own two answers mean: the clock, unless the timeline has
652+/// been played out -- `played_out` is the engine's end of stream with no frame
653+/// still waiting on the pump, and it wins, because past the end a running clock
654+/// is measuring wall time and not a picture.
655+fn transport(playing: bool, played_out: bool) -> Transport {
656+ match (played_out, playing) {
657+ (true, _) => Transport::Ended,
658+ (_, true) => Transport::Playing,
659+ (_, false) => Transport::Paused,
660+ }
661+}
662+
617663 struct Player {
618664 /// The timeline, once there is one. A run with no file opens without it and
619665 /// waits: the first media import or project load is what fills it, and
@@ -625,11 +671,10 @@ struct Player {
625671 name: SharedString,
626672 image: Option<Arc<RenderImage>>,
627673 /// A frame that arrived before its time; shown on the tick it comes due.
674+ /// The pump's buffer, not transport state -- but a frame waiting here is
675+ /// what keeps a finished decoder from reading as [`Transport::Ended`] one
676+ /// tick early. See [`Player::transport`].
628677 held: Option<Frame>,
629- /// The decoder's channel closed. Frames may still be waiting in `held`.
630- eos: bool,
631- /// Last frame shown; nothing left to animate.
632- done: bool,
633678 /// A seek is waiting for its frame. Keeps the repaint loop alive while
634679 /// paused, which is the only way the new still ever reaches the screen.
635680 pending_seek: bool,
@@ -885,6 +930,9 @@ impl Player {
885930 /// the channel and only the last of them is shown, which *is* the
886931 /// drop-when-behind policy. A frame that is not due yet waits in `held`.
887932 fn pump(&mut self, window: &mut Window) {
933+ // Where the transport was before this drain, so the crossing into
934+ // `Ended` can be recognised as the one transition it is.
935+ let was = self.transport();
888936 // No timeline, nothing to catch up to: the window is showing its empty
889937 // state and there is no decoder to drain.
890938 let Some(session) = &mut self.session else {
@@ -900,10 +948,7 @@ impl Player {
900948 // them apart -- `frame.index` is already a timeline index.
901949 None => match session.try_frame() {
902950 Some(frame) => frame,
903- None => {
904- self.eos = session.is_eos();
905- break;
906- }
951+ None => break,
907952 },
908953 };
909954 if f64::from(frame.index) <= target {
@@ -938,29 +983,56 @@ impl Player {
938983 }
939984 }
940985
941- if self.eos && self.held.is_none() && !self.done {
942- self.done = true;
986+ if self.transport() == Transport::Ended {
943987 // A seek whose worker never produced a frame (vanished file) would
944- // otherwise repaint at vsync forever.
988+ // otherwise repaint at vsync forever. Held true for as long as the
989+ // state does, not just on the crossing: nothing else is coming.
945990 self.pending_seek = false;
946- let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
947- eprintln!(
948- "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
949- self.displayed,
950- self.dropped,
951- session.now()
952- );
991+ if was != Transport::Ended {
992+ // Ended is a *stopped* transport, so the clock stops with it,
993+ // on the out point the timecode and the playhead have been
994+ // showing all along. Nothing else ever stopped it: past the
995+ // last frame wall time takes over and `now()` walks off the end
996+ // of the timeline for as long as the window is left open -- and
997+ // the playhead is what a cut, a paste, an insert and the
998+ // analyser all act at, so every one of them was aiming into
999+ // empty space (measured: a 5 s timeline recognised its end at
1000+ // clock 17.5 s under a slow renderer). End of stream is left
1001+ // set, so this is still `Ended` and the next press restarts.
1002+ if let Some(session) = &mut self.session {
1003+ session.halt_at_end();
1004+ }
1005+ let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
1006+ eprintln!(
1007+ "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
1008+ self.displayed,
1009+ self.dropped,
1010+ self.session.as_ref().map_or(0., PlaybackSession::now)
1011+ );
1012+ }
9531013 }
9541014 }
9551015
956- /// Every end-of-stream flag is app state and the engine knows nothing about
957- /// it, so clearing them after a reseek is what stops the picture from
958- /// staying frozen on the old last frame. Edits reseek inside the engine and
959- /// still owe this.
1016+ /// Where the transport is, asked of the session rather than remembered:
1017+ /// end of stream is the engine's own flag (any seek clears it, which is why
1018+ /// an edit past the end revives the picture) and so is the clock. A held
1019+ /// frame is one still owed to the screen, so the end is not the end yet.
1020+ fn transport(&self) -> Transport {
1021+ let Some(session) = &self.session else {
1022+ return Transport::Stopped;
1023+ };
1024+ transport(
1025+ session.is_playing(),
1026+ session.is_eos() && self.held.is_none(),
1027+ )
1028+ }
1029+
1030+ /// A frame owed to the screen after a reseek, and the buffered one dropped:
1031+ /// what stops the picture from staying frozen on the old last frame. The
1032+ /// end-of-stream flag itself is the engine's and its own seek clears it --
1033+ /// edits reseek inside the engine and still owe this.
9601034 fn reset_after_reseek(&mut self) {
9611035 self.held = None;
962- self.eos = false;
963- self.done = false;
9641036 self.pending_seek = true;
9651037 // An edit moves the indices a drag in flight is holding -- a stroke
9661038 // during one is exactly that -- and an edge committed against a moved
@@ -1929,16 +2001,17 @@ impl Player {
19292001 /// door a ruler click uses -- so a step while playing keeps playing, exactly
19302002 /// as a click does. It starts from the frame the transport is showing, which
19312003 /// past the end is the last one, and that is what lets a step back off EOS
1932- /// revive the picture ([`Player::reset_after_reseek`] clears `done`). Both
2004+ /// revive the picture (the engine's seek leaves [`Transport::Ended`]). Both
19332005 /// ends clamp, so the two go-to actions are this same step asked for more
19342006 /// frames than the timeline has. Selection is untouched: a seek is not an
19352007 /// edit, and nothing it does moves a clip index.
19362008 fn step(&mut self, frames: i64, cx: &mut Context<Self>) {
2009+ let ended = self.transport() == Transport::Ended;
19372010 let Some(session) = &self.session else {
19382011 return;
19392012 };
19402013 let last = ((session.timeline_duration() * self.fps).round() as i64 - 1).max(0);
1941- let now = match self.done {
2014+ let now = match ended {
19422015 true => last,
19432016 false => i64::from(frame_at(session.now(), self.fps)),
19442017 };
@@ -2178,9 +2251,8 @@ impl Player {
21782251 let (path, stream) = key.clone();
21792252 async move {
21802253 engine::waveform::peaks(&path, stream, WAVE_BPS)
2181- .ok()
2182- .flatten()
2183- .map(|peaks| Arc::new(normalise(peaks)))
2254+ .map(|peaks| peaks.map(|peaks| Arc::new(normalise(peaks))))
2255+ .inspect_err(|e| eprintln!("waveform: {}: {e}", path.display()))
21842256 }
21852257 });
21862258 cx.spawn(async move |this, cx| {
@@ -2189,11 +2261,14 @@ impl Player {
21892261 this.waves.insert(
21902262 key,
21912263 match decoded {
2192- Some(peaks) => Wave::Peaks(peaks),
2193- // Either no audio track or a file we could not read
2194- // it from; both mean the lane has nothing to draw,
2195- // and neither is worth asking about again.
2196- None => Wave::Silent,
2264+ Ok(Some(peaks)) => Wave::Peaks(peaks),
2265+ // No audio track: an answer, and not worth asking
2266+ // about again.
2267+ Ok(None) => Wave::Silent,
2268+ // A file whose sound we could not read is not a
2269+ // silent one, and a lane that drew it as silent is
2270+ // how a broken decode passes for a design choice.
2271+ Err(_) => Wave::Failed,
21972272 },
21982273 );
21992274 cx.notify();
@@ -2548,12 +2623,11 @@ impl Player {
25482623 }
25492624 }
25502625
2551- /// Where the playhead is, as the panel draws it. The clock keeps running
2552- /// after the last frame (wall time takes over at audio EOF) while the
2553- /// picture is frozen, so what the UI shows is the clamped one, pinned to
2554- /// the out-point once playback is done.
2626+ /// Where the playhead is, as the panel draws it: pinned to the out point
2627+ /// once playback is done, and clamped to the drawn duration otherwise -- a
2628+ /// tail being dragged draws past the timeline it is about to become.
25552629 fn playhead(&self, duration: f64) -> f64 {
2556- if self.done {
2630+ if self.transport() == Transport::Ended {
25572631 duration
25582632 } else {
25592633 self.session
@@ -2748,11 +2822,11 @@ impl Player {
27482822 self.export_path = PathBuf::new();
27492823 self.project_path = PathBuf::new();
27502824 self.fps = 30.;
2751- // No decoder to wait for a frame from: the hint is what shows.
2825+ // No decoder to wait for a frame from: the hint is what shows. The
2826+ // transport reads `Stopped` from the session being gone, so there is no
2827+ // end-of-stream state left to clear here.
27522828 self.reset_after_reseek();
27532829 self.pending_seek = false;
2754- self.eos = false;
2755- self.done = false;
27562830 }
27572831
27582832 /// One item of a library row's menu, done. Every one of them closes the
@@ -3168,11 +3242,11 @@ impl Player {
31683242 return;
31693243 }
31703244 // Nothing to play is a message, not a transport state. An empty
3171- // timeline is `done` from its one black frame onward, so the restart
3172- // below would start a clock against a zero-length timeline -- and it is
3173- // `done` again by the next repaint, so no later press could ever stop
3174- // it: the button would read "Pause" and never pause. A delete can empty
3175- // the timeline mid-play, and that press must still stop it.
3245+ // timeline is [`Transport::Ended`] from its one black frame onward, so
3246+ // the restart below would start a clock against a zero-length timeline
3247+ // -- and it is Ended again by the next repaint, so no later press could
3248+ // ever stop it: the button would read "Pause" and never pause. A delete
3249+ // can empty the timeline mid-play, and that press must still stop it.
31763250 if nothing_to_play(self.session.as_ref()) {
31773251 match self.session.as_mut().filter(|s| s.is_playing()) {
31783252 Some(session) => session.pause(),
@@ -3181,15 +3255,25 @@ impl Player {
31813255 cx.notify();
31823256 return;
31833257 }
3184- if self.done {
3185- self.seek(0., cx);
3186- if let Some(session) = &mut self.session {
3187- session.play();
3258+ match self.transport() {
3259+ // Nothing open: the button is dimmed and the key says nothing.
3260+ Transport::Stopped => {}
3261+ // Back to the top and away, for the key and the button alike --
3262+ // whichever asked, the transport was showing Play.
3263+ state if state.restarts() => {
3264+ self.seek(0., cx);
3265+ if let Some(session) = &mut self.session {
3266+ session.play();
3267+ }
3268+ }
3269+ _ => {
3270+ if let Some(session) = &mut self.session {
3271+ session.toggle();
3272+ // A paused timeline animates nothing; this is the repaint
3273+ // that puts the new glyph up.
3274+ cx.notify();
3275+ }
31883276 }
3189- } else if let Some(session) = &mut self.session {
3190- session.toggle();
3191- // Past EOF nothing else asks for a repaint.
3192- cx.notify();
31933277 }
31943278 }
31953279
@@ -3406,11 +3490,9 @@ impl Render for Player {
34063490 window.set_window_title(&title);
34073491 self.titled = title;
34083492 }
3409- // No shadow flag: the clock is the only truth about play state.
3410- let playing = self
3411- .session
3412- .as_ref()
3413- .is_some_and(PlaybackSession::is_playing);
3493+ // No shadow flag: the session is the only truth about play state, and
3494+ // [`Player::transport`] is the one place it is read.
3495+ let state = self.transport();
34143496 // A paused timeline has nothing to animate; the toggle handlers notify,
34153497 // which is what starts the loop again. A paused seek keeps the loop
34163498 // running by itself until `pump` has the frame it asked for. An export
@@ -3418,7 +3500,7 @@ impl Render for Player {
34183500 // the screen on a repaint. A notice does not: it waits to be dismissed
34193501 // rather than for a clock, so keeping the loop alive for it would spin
34203502 // the GPU until someone answered it.
3421- if (playing && !self.done) || self.pending_seek || self.export.is_some() {
3503+ if state.is_playing() || self.pending_seek || self.export.is_some() {
34223504 window.request_animation_frame();
34233505 }
34243506
@@ -3883,7 +3965,7 @@ impl Render for Player {
38833965 // Above the panel and only when there is one to show, so it costs
38843966 // the picture nothing the rest of the time.
38853967 .children(self.notice_bar(cx))
3886- .child(self.panel(position, duration, playing, cx))
3968+ .child(self.panel(position, duration, state, cx))
38873969 // Over the panel it was opened on, and under the cards: it is only
38883970 // ever up while neither of them is (`modal`).
38893971 .children(self.context_card(window.viewport_size(), cx))
@@ -4204,7 +4286,7 @@ impl Player {
42044286 &self,
42054287 position: f64,
42064288 duration: f64,
4207- playing: bool,
4289+ state: Transport,
42084290 cx: &mut Context<Self>,
42094291 ) -> impl IntoElement {
42104292 // Where the playhead is *on the bed*, which at the fit is where along
@@ -4218,7 +4300,7 @@ impl Player {
42184300 let exporting = self.exporting().is_some();
42194301 // Everything but Import and Keys needs a timeline to act on: with none
42204302 // open they are dimmed rather than silently doing nothing.
4221- let live = self.session.is_some() && !exporting;
4303+ let live = state != Transport::Stopped && !exporting;
42224304 // The project's own picture size, for the button that cycles it: read
42234305 // per render like everything else here, so a cycle shows on the button
42244306 // that made it.
@@ -4264,7 +4346,7 @@ impl Player {
42644346 // of this line is what a narrow window truncates.
42654347 (
42664348 join_detail(
4267- &self.live_decode(position, playing),
4349+ &self.live_decode(position, state.is_playing()),
42684350 &format!(
42694351 "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \
42704352 import",
@@ -4303,9 +4385,9 @@ impl Player {
43034385 .overflow_x_scroll()
43044386 .child(control(
43054387 "transport",
4306- Some(transport_glyph(playing).into_any_element()),
4307- if playing { "Pause" } else { "Play" },
4308- if nothing_to_play(self.session.as_ref()) && !playing {
4388+ Some(transport_glyph(state).into_any_element()),
4389+ if state.is_playing() { "Pause" } else { "Play" },
4390+ if nothing_to_play(self.session.as_ref()) && !state.is_playing() {
43094391 format!("{} — put a clip on a lane first", key(ActionId::Play))
43104392 } else {
43114393 key(ActionId::Play)
@@ -4315,7 +4397,7 @@ impl Player {
43154397 // against nothing (the key press answers with the
43164398 // notice). Still live while it *is* playing: a delete
43174399 // can empty the timeline mid-play and that has to stop.
4318- live && (playing || !nothing_to_play(self.session.as_ref())),
4400+ live && (state.is_playing() || !nothing_to_play(self.session.as_ref())),
43194401 cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)),
43204402 ))
43214403 .child(separator())
@@ -6915,6 +6997,20 @@ impl Player {
69156997 .into_any_element(),
69166998 // No audio track: nothing, never a fake.
69176999 Wave::Silent => return None,
7000+ // Could not be read: a band that says so in
7001+ // words, because the empty band a silent
7002+ // file draws would claim this file has no
7003+ // sound. The reason itself went to the log.
7004+ Wave::Failed => div()
7005+ .h_full()
7006+ .flex()
7007+ .items_center()
7008+ .justify_center()
7009+ .truncate()
7010+ .text_size(px(9.))
7011+ .text_color(rgb(INK_DIM))
7012+ .child("audio unreadable")
7013+ .into_any_element(),
69187014 };
69197015 Some(
69207016 div()
@@ -8794,9 +8890,12 @@ fn empty_hint() -> impl IntoElement {
87948890 )
87958891 }
87968892
8797-/// Two bars while playing, a triangle while paused. Drawn, so there is no icon
8798-/// font and no glyph coverage to depend on.
8799-fn transport_glyph(playing: bool) -> impl IntoElement {
8893+/// Two bars while playing, a triangle in every other state -- paused, nothing
8894+/// open, and played out, where the button's next act is to start over rather
8895+/// than to stop something. Drawn, so there is no icon font and no glyph
8896+/// coverage to depend on.
8897+fn transport_glyph(state: Transport) -> impl IntoElement {
8898+ let playing = state.is_playing();
88008899 div()
88018900 .flex()
88028901 .items_center()
@@ -8852,15 +8951,15 @@ mod tests {
88528951 KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W,
88538952 LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, MENU_ROWS_H, MENU_W, NO_FILE,
88548953 PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS,
8855- SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, VOLUME_W, Volume, WAVE_BPS,
8856- WAVE_COL, Wave, applicable, band_label, bitrate_refusal, can_add, cancels_export,
8954+ SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, Transport, VOLUME_W, Volume,
8955+ WAVE_BPS, WAVE_COL, Wave, applicable, band_label, bitrate_refusal, can_add, cancels_export,
88578956 clipboard_after_remove, color_snap, containers, envelope, eq_spectrum, eq_x, eq_y,
88588957 estimated_mb, export_path, export_settings, format_key, format_line, format_refusal,
88598958 fps_label, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project,
88608959 keymap, lanes_h, marked, menu_at, next_container, normalise, nothing_to_play, panel_h,
88618960 project_path, push_digit, retarget, scrub_due, show_label, silence_rate, snapped,
8862- source_tint, span_partner, speed_at, summary_head, summary_tail, timecode, unseen_paths,
8863- unseen_sources, whole_take, width_frac, window_title,
8961+ source_tint, span_partner, speed_at, summary_head, summary_tail, timecode, transport,
8962+ unseen_paths, unseen_sources, whole_take, width_frac, window_title,
88648963 };
88658964 use super::{
88668965 LaneKind, Repeat, View, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, library_rows,
@@ -8889,7 +8988,7 @@ mod tests {
88898988 use gpui::{Bounds, Pixels, point, px, size};
88908989 use std::collections::HashMap;
88918990 use std::path::{Path, PathBuf};
8892- use std::time::Duration;
8991+ use std::time::{Duration, Instant};
88938992
88948993 fn asset(name: &str) -> PathBuf {
88958994 Path::new(env!("CARGO_MANIFEST_DIR"))
@@ -10742,6 +10841,95 @@ mod tests {
1074210841 assert_eq!(volume.gain(), 0.75);
1074310842 }
1074410843
10844+ /// The whole transport in one place: the clock keeps running past the last
10845+ /// frame (wall time takes over at audio EOF), so "the clock is going" is
10846+ /// not "this is playing" -- and a button that read the clock showed Pause
10847+ /// on a timeline that had stopped moving. Ended is its own state, it draws
10848+ /// Play, and the next press starts over from the top.
10849+ #[test]
10850+ fn a_played_out_timeline_is_not_playing_and_the_next_press_starts_it_over() {
10851+ assert_eq!(transport(true, false), Transport::Playing);
10852+ assert_eq!(transport(false, false), Transport::Paused);
10853+ // The transition the bug was about: the clock is still running and the
10854+ // decoder is finished. Played out wins, however the clock reads.
10855+ assert_eq!(transport(true, true), Transport::Ended);
10856+ assert_eq!(transport(false, true), Transport::Ended);
10857+
10858+ // What the button draws, in each state. Two bars only while it moves.
10859+ assert!(Transport::Playing.is_playing());
10860+ for state in [Transport::Paused, Transport::Ended, Transport::Stopped] {
10861+ assert!(!state.is_playing(), "{state:?} must draw the Play triangle");
10862+ }
10863+
10864+ // And what a press does: start over at the end, plain toggle before it,
10865+ // nothing with no timeline. Same answer for the key and the button --
10866+ // both come through `Player::toggle_or_restart`.
10867+ assert!(Transport::Ended.restarts());
10868+ for state in [Transport::Playing, Transport::Paused, Transport::Stopped] {
10869+ assert!(!state.restarts(), "{state:?} must toggle, not reseek");
10870+ }
10871+ }
10872+
10873+ /// The half of `Ended` the eye cannot see: the clock. Wall time takes over
10874+ /// at the last frame and nothing used to stop it, so the playhead walked off
10875+ /// the end of the timeline in real time -- and the playhead is what a cut, a
10876+ /// paste, an insert and the analyser all act at. `pump` pauses on the
10877+ /// crossing; this is the engine contract that rests on, driven exactly as
10878+ /// the pump drives it.
10879+ #[test]
10880+ fn the_clock_stops_where_the_timeline_does_and_the_end_still_restarts() {
10881+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
10882+ session.set_gain(0.0);
10883+ // Start a breath short of the end: the tail is what this is about, and
10884+ // playing the whole five seconds would say nothing more.
10885+ session.seek(4.8);
10886+ session.play();
10887+
10888+ // The pump's own loop -- tick, drain, ask where the transport is --
10889+ // with a deadline so a fixture that will not decode fails as a failure
10890+ // rather than as a hang.
10891+ let deadline = Instant::now() + Duration::from_secs(20);
10892+ let mut state = transport(session.is_playing(), session.is_eos());
10893+ while state != Transport::Ended {
10894+ assert!(Instant::now() < deadline, "never reached the end of a 5s file");
10895+ session.tick();
10896+ while session.try_frame().is_some() {}
10897+ state = transport(session.is_playing(), session.is_eos());
10898+ }
10899+
10900+ // What `pump` does on the crossing, and the whole point of it: the
10901+ // position holds still afterwards instead of counting on past the end,
10902+ // and it holds still *on the out point* -- where the timecode and the
10903+ // playhead have been showing it. The clock at the moment the end is
10904+ // recognised is not that: a slow renderer reaches EOF with the clock
10905+ // seconds past the timeline, which is why this repositions rather than
10906+ // only freezing.
10907+ session.halt_at_end();
10908+ let stopped_at = session.now();
10909+ assert_eq!(stopped_at, session.timeline_duration());
10910+ std::thread::sleep(Duration::from_millis(250));
10911+ assert_eq!(session.now(), stopped_at, "the clock kept running past EOF");
10912+ // And it is still the end: pausing must not spend the state the glyph
10913+ // and the restart both read.
10914+ assert!(session.is_eos());
10915+ assert_eq!(
10916+ transport(session.is_playing(), session.is_eos()),
10917+ Transport::Ended
10918+ );
10919+
10920+ // The restart path off that frozen end, which is what the button and
10921+ // the play key do from `Ended`: back to the top, and running.
10922+ session.seek(0.);
10923+ session.play();
10924+ assert!(!session.is_eos(), "a seek revives the session");
10925+ assert!(session.now() < 1.0);
10926+ assert_eq!(
10927+ transport(session.is_playing(), session.is_eos()),
10928+ Transport::Playing
10929+ );
10930+ session.pause();
10931+ }
10932+
1074510933 /// Both ends hold under a key held down: the ABI only accepts `0.0..=1.0`,
1074610934 /// and a wrapped step count would hand it something else.
1074710935 #[test]
@@ -11705,8 +11893,6 @@ fn main() {
1170511893 name: name.clone(),
1170611894 image: None,
1170711895 held: None,
11708- eos: false,
11709- done: false,
1171011896 ruler: Rc::default(),
1171111897 // The whole timeline across the bed, which is where a
1171211898 // project opens: zooming is something the user asks for.
crates/engine/Cargo.tomlmodified+10 -0
@@ -66,6 +66,16 @@ symphonia = { version = "0.6", default-features = false, features = [
6666 ] }
6767 oxideav-ac3 = "=0.0.10"
6868 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 }
6979 # The software AV1 encoder, and the only new name in this list that was already
7080 # in the lock file: `ravif` pulls the very same rav1e 0.8.1 in through the image
7181 # crate, so this links what the build already compiled. BSD-2 with the AOM
crates/engine/src/audio.rsmodified+17 -3
@@ -1000,12 +1000,26 @@ impl Track {
10001000 if stream > 0 {
10011001 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
10021002 }
1003- if let Ok(Some(track)) = MkvAc3Track::open(path) {
1004- return Ok(Some(Self::Mkv(track)));
1003+ match MkvAc3Track::open(path) {
1004+ Ok(Some(track)) => return Ok(Some(Self::Mkv(track))),
1005+ Ok(None) => {}
1006+ // Named on the way past for the same reason symphonia's failure
1007+ // is, below: an AC-3 track that broke is a bug, not a codec we
1008+ // never had.
1009+ Err(e) => eprintln!("matroska audio: {}: {e}", path.display()),
10051010 }
1011+ // Logged on the way past: "silent" here covers both a codec nothing
1012+ // decodes and a track that genuinely broke, and only the second is a
1013+ // bug -- with no trace at all it reaches the user as a lane that
1014+ // drew no waveform and nothing else to go on.
10061015 return Ok(SymTrack::open(path)
1016+ .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display()))
10071017 .ok()
1008- .filter(|t| t.decoder().is_ok())
1018+ .filter(|t| {
1019+ t.decoder()
1020+ .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display()))
1021+ .is_ok()
1022+ })
10091023 .map(Self::Sym));
10101024 }
10111025 let audio_file = crate::is_audio(path);
crates/engine/src/demux.rsmodified+296 -5
@@ -340,7 +340,7 @@ struct Block {
340340 ts: i64,
341341 }
342342
343-/// AV1 or HEVC out of a Matroska file (`.mkv`/`.webm`).
343+/// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`).
344344 ///
345345 /// The whole segment is walked once at open -- element *headers* only, the block
346346 /// payloads are seeked over -- because Matroska carries no sample table: the
@@ -358,10 +358,11 @@ pub struct MkvDemuxer {
358358 ///
359359 /// For HEVC this is the Annex-B VPS/SPS/PPS off the `CodecPrivate`, which is
360360 /// an `hvcC` record verbatim -- the same blob, re-injected for the same
361- /// reason, as the one [`Mp4Demuxer`] carries.
361+ /// reason, as the one [`Mp4Demuxer`] carries; for H.264 the SPS/PPS off the
362+ /// `avcC` beside it, which is that record's H.264 twin.
362363 config: Vec<u8>,
363- /// Bytes of the NAL length prefix an HEVC block is written with; unused by
364- /// AV1, whose block is one temporal unit and carries no prefixes.
364+ /// Bytes of the NAL length prefix an HEVC or H.264 block is written with;
365+ /// unused by AV1, whose block is one temporal unit and carries no prefixes.
365366 nal_length: usize,
366367 /// Bits per luma sample; see [`Demuxer::bit_depth`].
367368 bit_depth: u8,
@@ -385,7 +386,7 @@ impl MkvDemuxer {
385386 None => {
386387 return Err(match other {
387388 Some(codec) => format!(
388- "{codec} video in a Matroska file is not supported — AV1 and HEVC are"
389+ "{codec} video in a Matroska file is not supported — AV1, HEVC and H.264 are"
389390 ),
390391 None => "this Matroska file has no video track".to_string(),
391392 }
@@ -737,6 +738,13 @@ fn mkv_track_entry(
737738 let (nal_length, sets, bit_depth) = parse_hvcc(&config)?;
738739 (Codec::Hevc, nal_length, sets, bit_depth)
739740 }
741+ // The `avcC` beside them, and the same story: length-prefixed blocks and
742+ // the SPS/PPS out of the record. Taken as 8-bit, which is what the whole
743+ // H.264 path here assumes of an mp4's `avc1` too.
744+ (1, "V_MPEG4/ISO/AVC") => {
745+ let (nal_length, sets) = parse_avcc(&config)?;
746+ (Codec::H264, nal_length, sets, 8)
747+ }
740748 (1, _) => return Ok(MkvEntry::OtherVideo(codec)),
741749 (2, _) => return Ok(MkvEntry::Audio(number, codec)),
742750 _ => return Ok(MkvEntry::Other),
@@ -754,6 +762,48 @@ fn mkv_track_entry(
754762 }))
755763 }
756764
765+/// AVCDecoderConfigurationRecord (ISO 14496-15 §5.3.3.1) -> the NAL length
766+/// prefix width and the SPS/PPS as one Annex-B blob, which is [`parse_hvcc`]'s
767+/// job for HEVC. The mp4 path gets both out of `mp4 0.14`'s `AvcCBox`; a
768+/// Matroska file carries the identical record in `CodecPrivate`, unparsed.
769+fn parse_avcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> {
770+ // 0 configurationVersion .. 4 lengthSizeMinusOne, 5 numOfSequenceParameterSets.
771+ let (&flags, &sps_count) = rec
772+ .get(4)
773+ .zip(rec.get(5))
774+ .ok_or("avcC record shorter than its fixed header")?;
775+ let mut sets = Vec::new();
776+ let mut src = &rec[6..];
777+ // The SPS array, whose count is the low 5 bits of byte 5, and then the PPS
778+ // array, whose count is a byte of its own.
779+ let mut count = usize::from(sps_count & 0x1f);
780+ for array in 0..2 {
781+ if array == 1 {
782+ let (&pps_count, rest) = src
783+ .split_first()
784+ .ok_or("avcC record ends before its PPS count")?;
785+ count = usize::from(pps_count);
786+ src = rest;
787+ }
788+ for _ in 0..count {
789+ let len = usize::from(u16::from_be_bytes(
790+ src.get(..2)
791+ .ok_or("avcC NAL length past the record")?
792+ .try_into()
793+ .unwrap(),
794+ ));
795+ let nal = src.get(2..2 + len).ok_or("avcC NAL past the record")?;
796+ sets.extend_from_slice(&START_CODE);
797+ sets.extend_from_slice(nal);
798+ src = &src[2 + len..];
799+ }
800+ }
801+ if sets.is_empty() {
802+ return Err("avcC record carries no SPS/PPS".into());
803+ }
804+ Ok((usize::from(flags & 0x3) + 1, sets))
805+}
806+
757807 /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF
758808 /// §2.3.3): four fixed bytes, then the sequence header OBU in the same
759809 /// low-overhead format the blocks are in, so it needs no reframing.
@@ -1239,6 +1289,216 @@ fn tkhd_track_id(payload: &[u8]) -> Option<u32> {
12391289 ))
12401290 }
12411291
1292+/// One subtitle track of a Matroska file, exactly as its `TrackEntry` declares
1293+/// it. What the cues *mean* is [`crate::subtitle`]'s business; this is the
1294+/// walk, and it reads every track type 0x11 the file has -- including the ones
1295+/// nothing here can render, which is how a caller names what it is leaving out
1296+/// instead of quietly opening a film with no subtitles in the list.
1297+#[derive(Debug)]
1298+pub struct MkvSubtitle {
1299+ pub number: u64,
1300+ /// The Matroska codec id: `S_TEXT/UTF8`, `S_TEXT/ASS`, `S_HDMV/PGS`, ...
1301+ pub codec: String,
1302+ /// `Language`, ISO-639-2, `und` when the file says nothing.
1303+ pub language: String,
1304+ /// `Name`, the human label a muxer wrote, often empty.
1305+ pub name: String,
1306+ /// `CodecPrivate`: the ASS script header (`[Script Info]` through the
1307+ /// `[Events]` `Format:` line) for `S_TEXT/ASS`, empty for `S_TEXT/UTF8`.
1308+ pub private: Vec<u8>,
1309+ /// Every cue block, in storage order -- but only for the `S_TEXT/*` codecs.
1310+ /// A bitmap track (PGS, VobSub) comes back declared and empty: its blocks
1311+ /// are megabytes of pictures, and nothing here can draw one.
1312+ pub cues: Vec<MkvCue>,
1313+}
1314+
1315+/// One subtitle block: when it shows and the bytes it shows.
1316+#[derive(Debug)]
1317+pub struct MkvCue {
1318+ /// Microseconds from the start of the file -- the block timestamp scaled by
1319+ /// the segment's `TimestampScale`, which is the unit
1320+ /// [`crate::subtitle::Cue`] keeps.
1321+ pub start_us: i64,
1322+ /// `BlockDuration`, microseconds. `None` for a block that declares none,
1323+ /// which leaves how long the cue stays up to the caller.
1324+ pub duration_us: Option<i64>,
1325+ /// The block's own bytes: the text for `S_TEXT/UTF8`, the comma-separated
1326+ /// `Dialogue` fields (`ReadOrder` first, no timing) for `S_TEXT/ASS`.
1327+ pub payload: Vec<u8>,
1328+}
1329+
1330+/// The subtitle tracks of a Matroska file, in file order. An mp4's are not read
1331+/// (its `tx3g` is a different beast, and no file this project opens carries
1332+/// one); anything that is not a Matroska file at all is an error, as it is for
1333+/// [`matroska_audio_codec`].
1334+///
1335+/// Two passes at most: the header walk stops at the first `Cluster`, and the
1336+/// cue pass runs only when there is a text track to fill.
1337+pub fn matroska_subtitles(path: &Path) -> crate::Result<Vec<MkvSubtitle>> {
1338+ let mut file = File::open(path)?;
1339+ let end = file.metadata()?.len();
1340+ let segment = mkv_segment(&mut file, end)?;
1341+ let mut tracks: Vec<MkvSubtitle> = Vec::new();
1342+ let mut timestamp_scale = 1_000_000;
1343+ let mut at = segment.0;
1344+ while let Some((id, body, stop)) = ebml_element(&mut file, at, segment.1)? {
1345+ match id {
1346+ CLUSTER => break,
1347+ INFO => {
1348+ let mut at = body;
1349+ while let Some(e) = ebml_element(&mut file, at, stop)? {
1350+ if e.0 == TIMESTAMP_SCALE {
1351+ timestamp_scale = ebml_uint(&mut file, e.1, e.2)?.max(1);
1352+ }
1353+ at = e.2;
1354+ }
1355+ }
1356+ TRACKS => {
1357+ let mut at = body;
1358+ while let Some(e) = ebml_element(&mut file, at, stop)? {
1359+ if e.0 == TRACK_ENTRY {
1360+ tracks.extend(mkv_subtitle_entry(&mut file, e.1, e.2)?);
1361+ }
1362+ at = e.2;
1363+ }
1364+ }
1365+ _ => {}
1366+ }
1367+ at = stop;
1368+ }
1369+ // The text tracks only: see `MkvSubtitle::cues`.
1370+ let wanted: Vec<u64> = tracks
1371+ .iter()
1372+ .filter(|t| t.codec.starts_with("S_TEXT"))
1373+ .map(|t| t.number)
1374+ .collect();
1375+ if !wanted.is_empty() {
1376+ mkv_subtitle_blocks(&mut file, segment, timestamp_scale, &wanted, &mut tracks)?;
1377+ }
1378+ Ok(tracks)
1379+}
1380+
1381+/// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles.
1382+fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Option<MkvSubtitle>> {
1383+ const TRACK_LANGUAGE: u32 = 0x22B59C;
1384+ const TRACK_NAME: u32 = 0x536E;
1385+ const SUBTITLE: u64 = 0x11;
1386+ let (mut number, mut kind, mut codec) = (0, 0, String::new());
1387+ let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new());
1388+ let mut at = body;
1389+ while let Some((id, body, stop)) = ebml_element(file, at, end)? {
1390+ match id {
1391+ TRACK_NUMBER => number = ebml_uint(file, body, stop)?,
1392+ TRACK_TYPE => kind = ebml_uint(file, body, stop)?,
1393+ CODEC_ID => codec = string_of(file, body, stop)?,
1394+ CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?,
1395+ TRACK_LANGUAGE => language = string_of(file, body, stop)?,
1396+ TRACK_NAME => name = string_of(file, body, stop)?,
1397+ _ => {}
1398+ }
1399+ at = stop;
1400+ }
1401+ Ok((kind == SUBTITLE).then(|| MkvSubtitle {
1402+ number,
1403+ codec,
1404+ // What a `TrackEntry` without a `Language` element means, by spec.
1405+ language: if language.is_empty() {
1406+ "und".into()
1407+ } else {
1408+ language
1409+ },
1410+ name,
1411+ private,
1412+ cues: Vec::new(),
1413+ }))
1414+}
1415+
1416+/// Every block of the `wanted` tracks, appended to their entries in `tracks`.
1417+///
1418+/// A second cluster walk rather than a widening of [`mkv_blocks`]: that one
1419+/// indexes *one* video track and reads no payloads, and a subtitle needs every
1420+/// track at once, the bytes, and the `BlockDuration` beside them.
1421+fn mkv_subtitle_blocks(
1422+ file: &mut File,
1423+ segment: (u64, u64),
1424+ timestamp_scale: u64,
1425+ wanted: &[u64],
1426+ tracks: &mut [MkvSubtitle],
1427+) -> crate::Result<()> {
1428+ const BLOCK_DURATION: u32 = 0x9B;
1429+ // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is
1430+ // nanoseconds per tick and is a millisecond in every file anything writes.
1431+ let us = |ticks: i64| ticks * timestamp_scale as i64 / 1_000;
1432+ let mut at = segment.0;
1433+ while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
1434+ at = stop;
1435+ if id != CLUSTER {
1436+ continue;
1437+ }
1438+ let mut cluster_ts = 0i64;
1439+ let mut child = body;
1440+ while let Some((id, body, stop)) = ebml_element(file, child, stop)? {
1441+ child = stop;
1442+ let (block, duration) = match id {
1443+ CLUSTER_TIMESTAMP => {
1444+ cluster_ts = ebml_uint(file, body, stop)? as i64;
1445+ continue;
1446+ }
1447+ SIMPLE_BLOCK => (mkv_block(file, body, stop)?, None),
1448+ BLOCK_GROUP => {
1449+ let (mut found, mut duration) = (None, None);
1450+ let mut child = body;
1451+ while let Some(e) = ebml_element(file, child, stop)? {
1452+ match e.0 {
1453+ BLOCK => found = Some(mkv_block(file, e.1, e.2)?),
1454+ BLOCK_DURATION => duration = Some(ebml_uint(file, e.1, e.2)? as i64),
1455+ _ => {}
1456+ }
1457+ child = e.2;
1458+ }
1459+ match found {
1460+ Some(block) => (block, duration),
1461+ None => continue,
1462+ }
1463+ }
1464+ _ => continue,
1465+ };
1466+ if !wanted.contains(&block.number) {
1467+ continue;
1468+ }
1469+ // As for a video block: guessing at the boundaries inside a laced
1470+ // one is not something to do silently. No muxer laces subtitles.
1471+ if block.flags & 0x06 != 0 {
1472+ return Err("laced subtitle blocks are not supported".into());
1473+ }
1474+ // A megabyte of *text* in one cue is a corrupt file, not a subtitle,
1475+ // and a crafted length may not reach an allocation through here.
1476+ if block.len > 1 << 20 {
1477+ return Err("a Matroska subtitle block larger than a megabyte".into());
1478+ }
1479+ let mut payload = vec![0u8; block.len];
1480+ read_exact_at(file, block.at, &mut payload)?;
1481+ let Some(track) = tracks.iter_mut().find(|t| t.number == block.number) else {
1482+ continue;
1483+ };
1484+ track.cues.push(MkvCue {
1485+ start_us: us(cluster_ts + i64::from(block.rel)),
1486+ duration_us: duration.map(us),
1487+ payload,
1488+ });
1489+ }
1490+ }
1491+ Ok(())
1492+}
1493+
1494+/// A string element, without the trailing NULs a `Name` may be padded with.
1495+fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> {
1496+ let bytes = ebml_bytes(file, body, stop)?;
1497+ Ok(String::from_utf8_lossy(&bytes)
1498+ .trim_end_matches('\0')
1499+ .to_owned())
1500+}
1501+
12421502 #[cfg(test)]
12431503 mod tests {
12441504 use super::*;
@@ -1296,6 +1556,37 @@ mod tests {
12961556 assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());
12971557 }
12981558
1559+ /// The `avcC` parse: prefix width out of byte 4, and both arrays -- the SPS
1560+ /// count is five bits of byte 5, the PPS count a byte of its own, and taking
1561+ /// the second for the first is the mistake this checks against.
1562+ #[test]
1563+ fn reads_parameter_sets_out_of_an_avcc_record() {
1564+ let mut rec = vec![1, 0x42, 0x00, 0x1f, 0xfc | 0x1, 0xe0 | 2];
1565+ for (kind, nal) in [(7u8, 0xAAu8), (7, 0xBB)] {
1566+ rec.extend_from_slice(&2u16.to_be_bytes());
1567+ rec.extend_from_slice(&[kind, nal]);
1568+ }
1569+ rec.push(1); // numOfPictureParameterSets
1570+ rec.extend_from_slice(&2u16.to_be_bytes());
1571+ rec.extend_from_slice(&[8, 0xCC]);
1572+
1573+ let (len, sets) = parse_avcc(&rec).unwrap();
1574+ assert_eq!(len, 2, "lengthSizeMinusOne == 1");
1575+ assert_eq!(
1576+ sets,
1577+ [
1578+ 0, 0, 0, 1, 7, 0xAA, // SPS
1579+ 0, 0, 0, 1, 7, 0xBB, // the second SPS, which a one-array read loses
1580+ 0, 0, 0, 1, 8, 0xCC, // PPS
1581+ ]
1582+ );
1583+ // Nothing is read past the end of a truncated record, and a Matroska
1584+ // file with no `CodecPrivate` at all is refused rather than started.
1585+ assert!(parse_avcc(&rec[..5]).is_err());
1586+ assert!(parse_avcc(&rec[..rec.len() - 1]).is_err());
1587+ assert!(parse_avcc(&[]).is_err());
1588+ }
1589+
12991590 /// EBML's variable-length integers, which every Matroska read starts with:
13001591 /// the leading zeros of the first byte are the length, an *id* keeps its
13011592 /// 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 @@
11 //! The project file: a line of text per thing, and nothing else.
22 //!
33 //! ```text
4-//! edith 9
4+//! edith 10
55 //! playhead 90
66 //! resolution 1920 1080
77 //! fps 30.0
88 //! limiter -1.0 on
99 //! source 0 test_av.mp4
1010 //! source 1 /elsewhere/test_av2.mp4
11+//! subtitle - subs.srt
12+//! subtitle 3 test_av.mp4
1113 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
1214 //! color 0.1:1.2:0.9:-0.3
1315 //! video 1 0 0 120 0 0 0 0 fit 1000
@@ -23,6 +25,15 @@
2325 //! is an answer only a project holding a video has
2426 //! ([`crate::PlaybackSession::open_project`]).
2527 //!
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+//!
2637 //! The `limiter` line is the master limiter over the whole mix
2738 //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit,
2839 //! spelled `on` or `off`. Left out when it is the default, which is off.
@@ -79,7 +90,9 @@
7990 //! is the only way an empty lane could still be there on the way back. A lane
8091 //! number may not skip one of its kind.
8192 //!
82-//! **Version 8** was this without the `fps` and `limiter` lines and without
93+//! **Version 9** was this without the `subtitle` lines: such a project shows no
94+//! subtitles, which is all any project could do.
95+//! **Version 8** was that without the `fps` and `limiter` lines and without
8396 //! the `gain` ones: such a project mixes every lane at unity, limits nothing,
8497 //! and comes back at the rate its scaffolding source runs at.
8598 //! **Version 7** was that without the clip's speed field -- every clip of such
@@ -97,8 +110,8 @@
97110 //! cumulatively and copied onto both lanes as one group each, which is exactly
98111 //! what a v1 timeline meant, and an older file simply equalizes and grades
99112 //! nothing, and an older one plays everything at real time, and an older one
100-//! mixes flat -- and saving any of them writes v9. An older reader refuses a
101-//! newer file by name.
113+//! mixes flat, and an older one shows no subtitles -- and saving any of them
114+//! writes v10. An older reader refuses a newer file by name.
102115 //!
103116 //! Text because an edit list is a few integers and a path, and a path is
104117 //! *bytes* on this platform -- a JSON string would have to lossily decode one.
@@ -129,10 +142,12 @@ use crate::eq::{Band, BandKind, EqParams};
129142 use crate::limiter::Limiter;
130143 use crate::project::{Clip, Lane, LaneKind, Source, Speed};
131144 use crate::scale::FitPolicy;
145+use crate::subtitle::SubtitleTrack;
132146
133147 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
134148 /// 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";
136151 const MAGIC_V8: &[u8] = b"edith 8";
137152 const MAGIC_V7: &[u8] = b"edith 7";
138153 const MAGIC_V6: &[u8] = b"edith 6";
@@ -169,6 +184,11 @@ pub struct Document {
169184 /// The master limiter. Off for every dialect before v9, and for a v9 file
170185 /// that leaves the line out.
171186 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>)>,
172192 /// The timeline's frame rate. `None` for every dialect before v9 and for a
173193 /// v9 file that leaves it out, which both mean "whatever the scaffolding
174194 /// source runs at" -- the inference a project of nothing but stills and
@@ -188,6 +208,7 @@ pub fn save(
188208 sources: &[Source],
189209 lanes: &[(LaneKind, Vec<Clip>)],
190210 gains: &[f32],
211+ subtitles: &[SubtitleTrack],
191212 eq: &[EqParams],
192213 color: &[ColorParams],
193214 resolution: (u32, u32),
@@ -206,7 +227,8 @@ pub fn save(
206227 let result = std::fs::File::create(&part)
207228 .and_then(|mut f| {
208229 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,
210232 ))?;
211233 f.sync_all()
212234 })
@@ -243,6 +265,7 @@ fn emit(
243265 sources: &[Source],
244266 lanes: &[(LaneKind, Vec<Clip>)],
245267 gains: &[f32],
268+ subtitles: &[SubtitleTrack],
246269 eq: &[EqParams],
247270 color: &[ColorParams],
248271 resolution: (u32, u32),
@@ -280,6 +303,16 @@ fn emit(
280303 escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);
281304 out.push(b'\n');
282305 }
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+ }
283316 // Before the clips, for the reason the sources are: a clip names one by the
284317 // position of its line, so the line has to be there first.
285318 for params in eq {
@@ -379,9 +412,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
379412 // The dialects that wrote a source line without its stream field. Reading
380413 // one is the whole of what "an old project still opens" means here.
381414 let streamless = v1 || first == MAGIC_V2;
382- // The one that carries the mix -- lane volumes, the master limiter and the
383- // rate the timeline was cut at...
384- let v9 = first == MAGIC;
415+ // The one that carries subtitle tracks...
416+ let v10 = 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;
385420 // ...the ones that carry a per-clip speed...
386421 let v8 = v9 || first == MAGIC_V8;
387422 // ...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> {
418453 // ...and nothing before v9 carries a mix or a rate: every lane at unity,
419454 // no limiter, and the rate inferred from the scaffold as it always was.
420455 gains: Vec::new(),
456+ // Nothing before v10 shows a subtitle.
457+ subtitles: Vec::new(),
421458 limiter: Limiter::default(),
422459 fps: None,
423460 playhead: 0,
@@ -528,6 +565,31 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
528565 doc.gains.resize(doc.lanes.len(), 0.0);
529566 doc.gains[at] = float(f[2], n)?;
530567 }
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+ }
531593 b"source" => {
532594 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
533595 return Err(format!("line {n}: source after a clip").into());
@@ -963,6 +1025,7 @@ mod tests {
9631025 sources,
9641026 lanes,
9651027 &[],
1028+ &[],
9661029 eq,
9671030 color,
9681031 resolution,
@@ -972,6 +1035,84 @@ mod tests {
9721035 )
9731036 }
9741037
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+
9751116 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {
9761117 Clip {
9771118 start,
@@ -1032,7 +1173,7 @@ mod tests {
10321173 let bytes = flat(&dir, &sources, &lanes, 12);
10331174 assert_eq!(
10341175 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\
10361177 source 2 /elsewhere/b.mp4\n\
10371178 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
10381179 audio 1 0 0 30 0 0 - - fit 1000\n",
@@ -1069,7 +1210,7 @@ mod tests {
10691210 let bytes = flat(&dir, &sources, &lanes, 7);
10701211 assert_eq!(
10711212 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\
10731214 video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\
10741215 video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",
10751216 "an empty lane is a line of its own; everything else is its clips"
@@ -1177,7 +1318,7 @@ mod tests {
11771318 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
11781319 assert_eq!(
11791320 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\
11811322 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
11821323 eq 16777215.0:-0.1:3.918315e-39:hs\n\
11831324 eq\n\
@@ -1281,7 +1422,7 @@ mod tests {
12811422 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
12821423 assert_eq!(
12831424 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\
12851426 color 0.1:1.2:0.9:-0.3\n\
12861427 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
12871428 color 0.0:1.0:1.0:0.0\n\
@@ -1346,7 +1487,7 @@ mod tests {
13461487 (1280, 720),
13471488 old.playhead
13481489 )),
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\
13501491 eq 80.0:-3.0:0.707:ls\n\
13511492 video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
13521493 );
@@ -1384,7 +1525,7 @@ mod tests {
13841525 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
13851526 assert_eq!(
13861527 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\
13881529 video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\
13891530 audio 1 0 0 30 0 - - - fit 2000\n",
13901531 "the rate is the clip line's last field, in thousandths"
@@ -1413,7 +1554,7 @@ mod tests {
14131554 (1280, 720),
14141555 old.playhead
14151556 )),
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\
14171558 video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
14181559 );
14191560 // A rate outside what the editor can set is a corrupt line, by name.
@@ -1450,6 +1591,7 @@ mod tests {
14501591 &[0.0, 3.0, -6.5],
14511592 &[],
14521593 &[],
1594+ &[],
14531595 (1280, 720),
14541596 Some(23.976023976023978),
14551597 limiter,
@@ -1457,7 +1599,7 @@ mod tests {
14571599 );
14581600 assert_eq!(
14591601 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\
14611603 limiter -1.5 on\nsource 0 a.mp4\n\
14621604 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\
14631605 audio 2 0 0 30 0 - - - fit 1000\n\
@@ -1489,7 +1631,7 @@ mod tests {
14891631 (1280, 720),
14901632 old.playhead
14911633 )),
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\
14931635 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
14941636 );
14951637
@@ -1653,7 +1795,7 @@ mod tests {
16531795 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
16541796 assert_eq!(
16551797 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\
16571799 source 2 /elsewhere/b.mp4\n\
16581800 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
16591801 audio 1 0 0 30 0 0 - - fit 1000\n"
@@ -1706,7 +1848,7 @@ mod tests {
17061848 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
17071849 assert_eq!(
17081850 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\
17101852 source 0 /elsewhere/b.mp4\n\
17111853 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
17121854 audio 1 0 0 30 0 0 - - fit 1000\n",
@@ -1738,7 +1880,7 @@ mod tests {
17381880 // Saved again it is the current version, which round-trips to the
17391881 // same document.
17401882 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"));
17421884 let again = parse(&v5, &dir).expect("v5 parses");
17431885 assert_eq!(again.lanes, back.lanes);
17441886 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
@@ -1834,6 +1976,7 @@ mod tests {
18341976 &[],
18351977 &[],
18361978 &[],
1979+ &[],
18371980 (1280, 720),
18381981 None,
18391982 Limiter::default(),
@@ -1843,7 +1986,7 @@ mod tests {
18431986 let bytes = std::fs::read(&path).expect("read back");
18441987 assert_eq!(
18451988 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\
18471990 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
18481991 );
18491992 // Loading rejoins the *given* directory, so the file is reached by the
@@ -1888,10 +2031,10 @@ mod tests {
18882031 #[test]
18892032 fn a_wrong_first_line_is_refused_by_name() {
18902033 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)
18922035 .unwrap_err()
18932036 .to_string();
1894- assert_eq!(err, "line 1: unsupported version 10");
2037+ assert_eq!(err, "line 1: unsupported version 11");
18952038 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
18962039 assert_eq!(
18972040 parse(junk, &dir).unwrap_err().to_string(),
crates/engine/src/lib.rsmodified+1 -0
@@ -17,6 +17,7 @@ pub mod playback;
1717 pub mod project;
1818 pub mod scale;
1919 pub mod silence;
20+pub mod subtitle;
2021 pub mod waveform;
2122
2223 pub use audio::{
crates/engine/src/playback.rsmodified+75 -1
@@ -673,8 +673,19 @@ impl PlaybackSession {
673673 }
674674
675675 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();
676686 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);
678689 let span = project.composite_span_at(0);
679690 // Last, because it is the one thing here that cannot be taken back: the
680691 // feeder thread outlives the `Audio` value (it holds its own clones) and
@@ -755,6 +766,47 @@ impl PlaybackSession {
755766 self.project.sources()
756767 }
757768
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+
758810 /// Writes the timeline to `path` as a `.edith`, atomically (see
759811 /// [`crate::edith`]). Sources no clip plays from are left out, and the
760812 /// playhead is saved with it so a reopened project resumes where it stood.
@@ -780,6 +832,9 @@ impl PlaybackSession {
780832 // project's, not this machine's (the monitoring volume is not
781833 // written and never will be).
782834 &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(),
783838 &eq,
784839 &color,
785840 (self.meta.width, self.meta.height),
@@ -1732,6 +1787,25 @@ impl PlaybackSession {
17321787 }
17331788 }
17341789
1790+ /// Stops the transport where the timeline stops: the clock is paused and put
1791+ /// on the out point.
1792+ ///
1793+ /// Playing past the last frame is wall time counting on past the end of the
1794+ /// media -- there is no picture left to pace it -- so a session left at EOF
1795+ /// reports a `now()` that walks off the end of the timeline in real time,
1796+ /// and a caller that reads the playhead (a cut, a paste, an insert) then
1797+ /// acts at a position no clip is at. How far off depends only on how long
1798+ /// the window was left open, so no clamp in a caller is worth writing.
1799+ ///
1800+ /// End of stream is deliberately left set: the picture is still the last
1801+ /// frame and this is still the end. That is what makes it safe to call on
1802+ /// the crossing into it -- the state the transport shows does not change,
1803+ /// only the running clock stops.
1804+ pub fn halt_at_end(&mut self) {
1805+ self.pause();
1806+ self.clock.seek_to(self.timeline_duration());
1807+ }
1808+
17351809 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:
17361810 /// one knob, because muting and turning it down are the same thing to the
17371811 /// device, and *which* the user meant is a question only the UI can answer
crates/engine/src/project.rsmodified+38 -0
@@ -68,6 +68,7 @@ use crate::color::ColorParams;
6868 use crate::eq::EqParams;
6969 use crate::limiter::{Limiter, db_to_linear};
7070 use crate::scale::FitPolicy;
71+use crate::subtitle::SubtitleTrack;
7172
7273 /// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
7374 /// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
@@ -618,6 +619,12 @@ pub struct Project {
618619 /// Never rolled back by an undo: an id retired by an undone split must not
619620 /// come back and group two clips that were never together.
620621 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>,
621628 /// The master limiter every lane's sound is summed *through*
622629 /// ([`Project::limiter`]). Off by default, and not in the lane list, which
623630 /// is what the history snapshots hold: it is a setting on the mix, like the
@@ -652,6 +659,7 @@ impl Project {
652659 color: Vec::new(),
653660 history: Vec::new(),
654661 next_link: 1,
662+ subtitles: Vec::new(),
655663 limiter: Limiter::default(),
656664 }
657665 }
@@ -760,6 +768,7 @@ impl Project {
760768 color,
761769 history: Vec::new(),
762770 next_link,
771+ subtitles: Vec::new(),
763772 limiter: Limiter::default(),
764773 })
765774 }
@@ -1128,6 +1137,35 @@ impl Project {
11281137 self
11291138 }
11301139
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+
11311169 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
11321170 /// lanes is multiplied by on its way into the mix: the same lanes in the
11331171 /// 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;
1515 /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always
1616 /// straddles zero, so silence draws as a flat line.
1717 ///
18-/// Decoding the whole file runs at ~1700x realtime, but it is still linear in
19-/// source length: callers cache the result per source *and stream* — two
20-/// streams of one file are two different envelopes, and a cache keyed on the
21-/// path alone would draw the first one under both.
18+/// Decoding the whole file runs at ~1700x realtime for an mp4's stereo AAC and
19+/// ~50x for a film's 5.1 AAC in an mkv (six channels through `rusty_aac`), but
20+/// it is linear in source length either way: callers cache the result per source
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.
2230 pub fn peaks(
2331 path: impl AsRef<Path>,
2432 stream: usize,
@@ -141,6 +149,33 @@ mod tests {
141149 assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}");
142150 }
143151
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+
144179 #[test]
145180 fn video_only_source_has_no_peaks() {
146181 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() {
209209 let v2 = dir.join("new.edith");
210210 loaded.save_project(&v2).expect("save");
211211 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}");
213213 assert!(
214214 text.contains("\nresolution 1280 720\n"),
215215 "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() {
297297 loaded.save_project(&again).expect("save");
298298 assert_eq!(
299299 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\
301301 video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\
302302 video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n",
303303 "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() {
327327 loaded.save_project(&again).expect("save");
328328 assert_eq!(
329329 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\
331331 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
332332 eq 12000.0:6.25:0.5:hs\n\
333333 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() {
362362 loaded.save_project(&again).expect("save");
363363 assert_eq!(
364364 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\
366366 eq 80.0:-3.0:0.707:ls\n\
367367 color 0.1:1.2:0.9:-0.3\n\
368368 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() {
412412 loaded.save_project(&again).expect("save");
413413 assert_eq!(
414414 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\
416416 video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\
417417 audio 1 0 0 60 0 - - - fit 1000\n",
418418 "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() {
670670
671671 for (text, want) in [
672672 (
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",
674674 "line 1",
675675 ),
676676 // An eq index the table does not hold, and a band shape there is none.
@@ -806,7 +806,7 @@ fn a_song_only_project_comes_back_at_the_rate_it_names() {
806806 let path = dir.join("song.edith");
807807 std::fs::write(
808808 &path,
809- "edith 9\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\
809+ "edith 10\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\
810810 video 1\naudio 1 0 0 24 0 - - - fit 1000\n",
811811 )
812812 .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() {
365365 &sources,
366366 &lanes,
367367 &p.lane_gains(),
368+ p.subtitles(),
368369 &eq,
369370 &color,
370371 (1920, 1080),
@@ -375,7 +376,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() {
375376 .expect("save");
376377 let text = std::fs::read_to_string(&file).expect("read it back");
377378 assert!(
378- text.starts_with("edith 9"),
379+ text.starts_with("edith 10"),
379380 "{:?}",
380381 &text[..16.min(text.len())]
381382 );
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+33 -3
@@ -113,6 +113,34 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
113113 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
114114 -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
115115 -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
116144 # HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as
117145 # test_hevc.mp4 so the tests measure the container and nothing else, `-g 30` for
118146 # the same reason test_av1.mkv has it (a second keyframe to seek to), and the
@@ -144,16 +172,18 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
144172 # **5.1 E-AC-3** for Annex E -- the shape a remux has, and the one that must
145173 # come down to stereo through the same A/52 7.8 downmix the mp4 path uses.
146174 # 48 kHz both, which is the only rate E-AC-3 is written at in practice. Small
147-# picture on purpose: these two are about the sound.
175+# H.264 picture on purpose: these two are about the sound, and the software
176+# decoder reads that one, so an audio test needs no VA-API plugin to open a
177+# session on them.
148178 ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \
149179 -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \
150180 -f lavfi -i "sine=frequency=880:duration=2:sample_rate=48000" \
151181 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a]" \
152- -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
182+ -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \
153183 -c:a ac3 -b:a 192k assets/test_ac3.mkv
154184 ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \
155185 -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \
156- -map 0:v -map 1:a -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
186+ -map 0:v -map 1:a -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \
157187 -ac 6 -c:a eac3 -b:a 384k assets/test_eac3.mkv
158188 # Sync fixture: one flash and one beep, at the same instant. Black picture with
159189 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that
vendor/rusty_aac/src/dsp.rsmodified+87 -49
@@ -35,20 +35,45 @@ pub fn imdct(spec: &[f32]) -> Vec<f32> {
3535 if n == 0 {
3636 return Vec::new();
3737 }
38- // LOCAL PATCH: the AAC block sizes take the cached cosine matrix below --
39- // the same numbers, looked up instead of called for.
40- if let Some(matrix) = imdct_matrix(n) {
41- let mut out = vec![0f32; n];
42- for (i, o) in out.iter_mut().enumerate() {
43- let row = &matrix[i * half..(i + 1) * half];
44- let mut acc = 0f32;
45- for (k, &s) in spec.iter().enumerate() {
46- acc += s * row[k];
38+ // LOCAL PATCH: O(N log N) instead of the O(N^2) sum below. With `n0 = N/4 +
39+ // 1/2` the kernel is exactly a DCT-IV of length L = N/2 read at `j = i +
40+ // L/2` -- the same DCT-IV [`mdct_fast`] already runs as one N/4-point FFT --
41+ // so the transform is that one call plus a sign-and-mirror walk (DCT-IV is
42+ // even about `j = -1/2`, odd about `j = L - 1/2`, and negates every 2L).
43+ if half >= 2 && half.is_power_of_two() {
44+ let owned;
45+ let tw = match mdct_twiddles(n) {
46+ Some(t) => t,
47+ None => {
48+ owned = MdctTwiddles::build(n);
49+ &owned
4750 }
48- *o = acc;
49- }
50- return out;
51+ };
52+ let d = dct4(half, |k| spec[k] as f64, tw);
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();
5168 }
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;
5277 let n0 = (n / 2 + 1) as f64 / 2.0; // N/4 + 1/2
5378 let scale = 2.0 / n as f64;
5479 let w = 2.0 * PI / n as f64;
@@ -64,36 +89,6 @@ pub fn imdct(spec: &[f32]) -> Vec<f32> {
6489 out
6590 }
6691
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-
9792 /// Forward MDCT — the analysis transform paired with [`imdct`]. Used to validate
9893 /// the IMDCT via perfect reconstruction (and useful for an eventual encoder).
9994 /// `N` time samples → `N/2` coefficients.
@@ -236,7 +231,7 @@ pub fn mdct_fast(x: &[f32]) -> Vec<f32> {
236231 if n < 4 {
237232 return mdct(x); // tiny sizes: fall back to the direct oracle
238233 }
239- let (l, m) = (n / 2, n / 4);
234+ let l = n / 2;
240235 let owned;
241236 let tw = match mdct_twiddles(n) {
242237 Some(t) => t,
@@ -254,20 +249,32 @@ pub fn mdct_fast(x: &[f32]) -> Vec<f32> {
254249 (x[mm - l2] as f64) - (x[l32 - 1 - mm] as f64)
255250 }
256251 };
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;
258266 let (mut re, mut im) = (vec![0f64; m], vec![0f64; m]);
259267 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));
261269 re[p] = yr * tw.pre_c[p] + yi * tw.pre_s[p];
262270 im[p] = yi * tw.pre_c[p] - yr * tw.pre_s[p];
263271 }
264272 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.
266- let mut out = vec![0f32; l];
273+ let mut out = vec![0f64; l];
267274 for p in 0..m {
268275 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;
270- out[l - 1 - 2 * p] = (2.0 * (vr * tw.post_s[p] - vi * tw.post_c[p])) as f32;
276+ out[2 * p] = vr * tw.post_c[p] + vi * tw.post_s[p];
277+ out[l - 1 - 2 * p] = vr * tw.post_s[p] - vi * tw.post_c[p];
271278 }
272279 out
273280 }
@@ -346,6 +353,37 @@ mod tests {
346353 }
347354 }
348355
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+
349387 #[test]
350388 fn dequant_matches_spec_curve() {
351389 assert_eq!(dequant(0), 0.0);