diff --git a/Cargo.lock b/Cargo.lock index bc63ce6..906603f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1003,6 +1003,12 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "compcol" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28b37ce533aa0fddc1e6820e331968ba72aa48b5c8bbb2bebdc03d48b6ed0f16" + [[package]] name = "compression-codecs" version = "0.4.38" @@ -1636,8 +1642,10 @@ dependencies = [ "libloading", "mp4", "oxideav-ac3", + "oxideav-ass", "oxideav-core", "oxideav-h265", + "oxideav-subtitle", "rav1e", "rusty_aac", "rusty_h264", @@ -3940,6 +3948,16 @@ dependencies = [ "oxideav-core", ] +[[package]] +name = "oxideav-ass" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d5a10750f54eb6913bf3ca295d17899006c9a9c6c94970741a5a7c0c49e3fa" +dependencies = [ + "oxideav-core", + "oxideav-subtitle", +] + [[package]] name = "oxideav-core" version = "0.1.34" @@ -3958,6 +3976,77 @@ dependencies = [ "oxideav-core", ] +[[package]] +name = "oxideav-otf" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "571c56414ce3138d3a4e7c833b402b3c69a96db707f54abd0f1ad85f3d5d1a0b" +dependencies = [ + "oxideav-core", +] + +[[package]] +name = "oxideav-pixfmt" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "868d5cd1d9cf3f4d527241b6ed85fcd628c65e303fe4efb2998e4d6104c7ce4b" +dependencies = [ + "oxideav-core", +] + +[[package]] +name = "oxideav-png" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c78483db4263204f6f9e2e63354b45f0fe2f83e0e08282f68c8a9647d537fa1f" +dependencies = [ + "compcol", + "oxideav-core", +] + +[[package]] +name = "oxideav-raster" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41beead01c28b23e6e997e8b2d3a38bb1b53cd37b6e8a72a10befa2fb57a6e06" +dependencies = [ + "oxideav-core", + "oxideav-pixfmt", +] + +[[package]] +name = "oxideav-scribe" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9aec36b356861de9e0e660a7990f14b428476638f7b2ba902c0cd7e1ffdac39" +dependencies = [ + "oxideav-core", + "oxideav-otf", + "oxideav-png", + "oxideav-ttf", +] + +[[package]] +name = "oxideav-subtitle" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88e41289024a95ea82051cd18af77885afd7be3c23a38255cb1edbe49872273a" +dependencies = [ + "oxideav-core", + "oxideav-pixfmt", + "oxideav-raster", + "oxideav-scribe", +] + +[[package]] +name = "oxideav-ttf" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c44d45518f6f4d749d2bf2c7cb3622fdb7ccc6147457545ed36aa8d241adea8e" +dependencies = [ + "oxideav-core", +] + [[package]] name = "parking" version = "2.2.1" diff --git a/Cargo.toml b/Cargo.toml index 2fb73a0..93e276b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,7 +23,10 @@ edition = "2024" # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per # term (the fast path in the same file serves the encoder only), # which is 4x slower than real time for 5.1 and therefore not -# playable at all; the patch caches the cosine matrix +# playable at all; the patch routes the IMDCT through the same +# N/4-point FFT the encoder's MDCT already uses (`dsp::dct4`), +# 40x the matrix version it started as -- 2 hours of 5.1 for a +# waveform in 2.4 minutes rather than an hour # oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and # refuses any dimension that is not a multiple of the 16-sample # CTB, so 1920x1080 could not be written at all; the patch adds diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 20be25f..d8e228b 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -260,6 +260,10 @@ enum Wave { Loading, /// The file has no audio track. An answer, not a miss. Silent, + /// The decode failed. Drawn as its own mark rather than as [`Self::Silent`]: + /// "this file's sound could not be read" and "this file has no sound" look + /// the same on a lane, and the first is a bug report waiting to happen. + Failed, Peaks(Arc>), } @@ -614,6 +618,48 @@ const HIST_H: f32 = 96.; /// counts, lightened enough to read on the dark box. const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0]; +/// Where the transport is. The one answer the button's glyph, its label, its +/// enablement, the play key and the repaint loop all read -- there is no play +/// flag anywhere else, because a second one is a second answer. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Transport { + /// No timeline open. Nothing to play and the transport is dimmed. + Stopped, + Playing, + Paused, + /// Played out: the last frame is on screen, the decoder is finished, and the + /// clock is still running past it -- which is exactly why "is the clock + /// going" is not the same question as "is this playing". + Ended, +} + +impl Transport { + /// The timeline is in motion: two bars on the button, and a repaint owed + /// every vsync. + fn is_playing(self) -> bool { + matches!(self, Transport::Playing) + } + + /// The play key and the transport button start over from the top rather + /// than toggling -- the end of a timeline is where every NLE does this, and + /// the button does it because the key already did. + fn restarts(self) -> bool { + matches!(self, Transport::Ended) + } +} + +/// What a session's own two answers mean: the clock, unless the timeline has +/// been played out -- `played_out` is the engine's end of stream with no frame +/// still waiting on the pump, and it wins, because past the end a running clock +/// is measuring wall time and not a picture. +fn transport(playing: bool, played_out: bool) -> Transport { + match (played_out, playing) { + (true, _) => Transport::Ended, + (_, true) => Transport::Playing, + (_, false) => Transport::Paused, + } +} + struct Player { /// The timeline, once there is one. A run with no file opens without it and /// waits: the first media import or project load is what fills it, and @@ -625,11 +671,10 @@ struct Player { name: SharedString, image: Option>, /// A frame that arrived before its time; shown on the tick it comes due. + /// The pump's buffer, not transport state -- but a frame waiting here is + /// what keeps a finished decoder from reading as [`Transport::Ended`] one + /// tick early. See [`Player::transport`]. held: Option, - /// The decoder's channel closed. Frames may still be waiting in `held`. - eos: bool, - /// Last frame shown; nothing left to animate. - done: bool, /// A seek is waiting for its frame. Keeps the repaint loop alive while /// paused, which is the only way the new still ever reaches the screen. pending_seek: bool, @@ -885,6 +930,9 @@ impl Player { /// the channel and only the last of them is shown, which *is* the /// drop-when-behind policy. A frame that is not due yet waits in `held`. fn pump(&mut self, window: &mut Window) { + // Where the transport was before this drain, so the crossing into + // `Ended` can be recognised as the one transition it is. + let was = self.transport(); // No timeline, nothing to catch up to: the window is showing its empty // state and there is no decoder to drain. let Some(session) = &mut self.session else { @@ -900,10 +948,7 @@ impl Player { // them apart -- `frame.index` is already a timeline index. None => match session.try_frame() { Some(frame) => frame, - None => { - self.eos = session.is_eos(); - break; - } + None => break, }, }; if f64::from(frame.index) <= target { @@ -938,29 +983,56 @@ impl Player { } } - if self.eos && self.held.is_none() && !self.done { - self.done = true; + if self.transport() == Transport::Ended { // A seek whose worker never produced a frame (vanished file) would - // otherwise repaint at vsync forever. + // otherwise repaint at vsync forever. Held true for as long as the + // state does, not just on the crossing: nothing else is coming. self.pending_seek = false; - let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64()); - eprintln!( - "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s", - self.displayed, - self.dropped, - session.now() - ); + if was != Transport::Ended { + // Ended is a *stopped* transport, so the clock stops with it, + // on the out point the timecode and the playhead have been + // showing all along. Nothing else ever stopped it: past the + // last frame wall time takes over and `now()` walks off the end + // of the timeline for as long as the window is left open -- and + // the playhead is what a cut, a paste, an insert and the + // analyser all act at, so every one of them was aiming into + // empty space (measured: a 5 s timeline recognised its end at + // clock 17.5 s under a slow renderer). End of stream is left + // set, so this is still `Ended` and the next press restarts. + if let Some(session) = &mut self.session { + session.halt_at_end(); + } + let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64()); + eprintln!( + "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s", + self.displayed, + self.dropped, + self.session.as_ref().map_or(0., PlaybackSession::now) + ); + } } } - /// Every end-of-stream flag is app state and the engine knows nothing about - /// it, so clearing them after a reseek is what stops the picture from - /// staying frozen on the old last frame. Edits reseek inside the engine and - /// still owe this. + /// Where the transport is, asked of the session rather than remembered: + /// end of stream is the engine's own flag (any seek clears it, which is why + /// an edit past the end revives the picture) and so is the clock. A held + /// frame is one still owed to the screen, so the end is not the end yet. + fn transport(&self) -> Transport { + let Some(session) = &self.session else { + return Transport::Stopped; + }; + transport( + session.is_playing(), + session.is_eos() && self.held.is_none(), + ) + } + + /// A frame owed to the screen after a reseek, and the buffered one dropped: + /// what stops the picture from staying frozen on the old last frame. The + /// end-of-stream flag itself is the engine's and its own seek clears it -- + /// edits reseek inside the engine and still owe this. fn reset_after_reseek(&mut self) { self.held = None; - self.eos = false; - self.done = false; self.pending_seek = true; // An edit moves the indices a drag in flight is holding -- a stroke // during one is exactly that -- and an edge committed against a moved @@ -1929,16 +2001,17 @@ impl Player { /// door a ruler click uses -- so a step while playing keeps playing, exactly /// as a click does. It starts from the frame the transport is showing, which /// past the end is the last one, and that is what lets a step back off EOS - /// revive the picture ([`Player::reset_after_reseek`] clears `done`). Both + /// revive the picture (the engine's seek leaves [`Transport::Ended`]). Both /// ends clamp, so the two go-to actions are this same step asked for more /// frames than the timeline has. Selection is untouched: a seek is not an /// edit, and nothing it does moves a clip index. fn step(&mut self, frames: i64, cx: &mut Context) { + let ended = self.transport() == Transport::Ended; let Some(session) = &self.session else { return; }; let last = ((session.timeline_duration() * self.fps).round() as i64 - 1).max(0); - let now = match self.done { + let now = match ended { true => last, false => i64::from(frame_at(session.now(), self.fps)), }; @@ -2178,9 +2251,8 @@ impl Player { let (path, stream) = key.clone(); async move { engine::waveform::peaks(&path, stream, WAVE_BPS) - .ok() - .flatten() - .map(|peaks| Arc::new(normalise(peaks))) + .map(|peaks| peaks.map(|peaks| Arc::new(normalise(peaks)))) + .inspect_err(|e| eprintln!("waveform: {}: {e}", path.display())) } }); cx.spawn(async move |this, cx| { @@ -2189,11 +2261,14 @@ impl Player { this.waves.insert( key, match decoded { - Some(peaks) => Wave::Peaks(peaks), - // Either no audio track or a file we could not read - // it from; both mean the lane has nothing to draw, - // and neither is worth asking about again. - None => Wave::Silent, + Ok(Some(peaks)) => Wave::Peaks(peaks), + // No audio track: an answer, and not worth asking + // about again. + Ok(None) => Wave::Silent, + // A file whose sound we could not read is not a + // silent one, and a lane that drew it as silent is + // how a broken decode passes for a design choice. + Err(_) => Wave::Failed, }, ); cx.notify(); @@ -2548,12 +2623,11 @@ impl Player { } } - /// Where the playhead is, as the panel draws it. The clock keeps running - /// after the last frame (wall time takes over at audio EOF) while the - /// picture is frozen, so what the UI shows is the clamped one, pinned to - /// the out-point once playback is done. + /// Where the playhead is, as the panel draws it: pinned to the out point + /// once playback is done, and clamped to the drawn duration otherwise -- a + /// tail being dragged draws past the timeline it is about to become. fn playhead(&self, duration: f64) -> f64 { - if self.done { + if self.transport() == Transport::Ended { duration } else { self.session @@ -2748,11 +2822,11 @@ impl Player { self.export_path = PathBuf::new(); self.project_path = PathBuf::new(); self.fps = 30.; - // No decoder to wait for a frame from: the hint is what shows. + // No decoder to wait for a frame from: the hint is what shows. The + // transport reads `Stopped` from the session being gone, so there is no + // end-of-stream state left to clear here. self.reset_after_reseek(); self.pending_seek = false; - self.eos = false; - self.done = false; } /// One item of a library row's menu, done. Every one of them closes the @@ -3168,11 +3242,11 @@ impl Player { return; } // Nothing to play is a message, not a transport state. An empty - // timeline is `done` from its one black frame onward, so the restart - // below would start a clock against a zero-length timeline -- and it is - // `done` again by the next repaint, so no later press could ever stop - // it: the button would read "Pause" and never pause. A delete can empty - // the timeline mid-play, and that press must still stop it. + // timeline is [`Transport::Ended`] from its one black frame onward, so + // the restart below would start a clock against a zero-length timeline + // -- and it is Ended again by the next repaint, so no later press could + // ever stop it: the button would read "Pause" and never pause. A delete + // can empty the timeline mid-play, and that press must still stop it. if nothing_to_play(self.session.as_ref()) { match self.session.as_mut().filter(|s| s.is_playing()) { Some(session) => session.pause(), @@ -3181,15 +3255,25 @@ impl Player { cx.notify(); return; } - if self.done { - self.seek(0., cx); - if let Some(session) = &mut self.session { - session.play(); + match self.transport() { + // Nothing open: the button is dimmed and the key says nothing. + Transport::Stopped => {} + // Back to the top and away, for the key and the button alike -- + // whichever asked, the transport was showing Play. + state if state.restarts() => { + self.seek(0., cx); + if let Some(session) = &mut self.session { + session.play(); + } + } + _ => { + if let Some(session) = &mut self.session { + session.toggle(); + // A paused timeline animates nothing; this is the repaint + // that puts the new glyph up. + cx.notify(); + } } - } else if let Some(session) = &mut self.session { - session.toggle(); - // Past EOF nothing else asks for a repaint. - cx.notify(); } } @@ -3406,11 +3490,9 @@ impl Render for Player { window.set_window_title(&title); self.titled = title; } - // No shadow flag: the clock is the only truth about play state. - let playing = self - .session - .as_ref() - .is_some_and(PlaybackSession::is_playing); + // No shadow flag: the session is the only truth about play state, and + // [`Player::transport`] is the one place it is read. + let state = self.transport(); // A paused timeline has nothing to animate; the toggle handlers notify, // which is what starts the loop again. A paused seek keeps the loop // running by itself until `pump` has the frame it asked for. An export @@ -3418,7 +3500,7 @@ impl Render for Player { // the screen on a repaint. A notice does not: it waits to be dismissed // rather than for a clock, so keeping the loop alive for it would spin // the GPU until someone answered it. - if (playing && !self.done) || self.pending_seek || self.export.is_some() { + if state.is_playing() || self.pending_seek || self.export.is_some() { window.request_animation_frame(); } @@ -3883,7 +3965,7 @@ impl Render for Player { // Above the panel and only when there is one to show, so it costs // the picture nothing the rest of the time. .children(self.notice_bar(cx)) - .child(self.panel(position, duration, playing, cx)) + .child(self.panel(position, duration, state, cx)) // Over the panel it was opened on, and under the cards: it is only // ever up while neither of them is (`modal`). .children(self.context_card(window.viewport_size(), cx)) @@ -4204,7 +4286,7 @@ impl Player { &self, position: f64, duration: f64, - playing: bool, + state: Transport, cx: &mut Context, ) -> impl IntoElement { // Where the playhead is *on the bed*, which at the fit is where along @@ -4218,7 +4300,7 @@ impl Player { let exporting = self.exporting().is_some(); // Everything but Import and Keys needs a timeline to act on: with none // open they are dimmed rather than silently doing nothing. - let live = self.session.is_some() && !exporting; + let live = state != Transport::Stopped && !exporting; // The project's own picture size, for the button that cycles it: read // per render like everything else here, so a cycle shows on the button // that made it. @@ -4264,7 +4346,7 @@ impl Player { // of this line is what a narrow window truncates. ( join_detail( - &self.live_decode(position, playing), + &self.live_decode(position, state.is_playing()), &format!( "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \ import", @@ -4303,9 +4385,9 @@ impl Player { .overflow_x_scroll() .child(control( "transport", - Some(transport_glyph(playing).into_any_element()), - if playing { "Pause" } else { "Play" }, - if nothing_to_play(self.session.as_ref()) && !playing { + Some(transport_glyph(state).into_any_element()), + if state.is_playing() { "Pause" } else { "Play" }, + if nothing_to_play(self.session.as_ref()) && !state.is_playing() { format!("{} — put a clip on a lane first", key(ActionId::Play)) } else { key(ActionId::Play) @@ -4315,7 +4397,7 @@ impl Player { // against nothing (the key press answers with the // notice). Still live while it *is* playing: a delete // can empty the timeline mid-play and that has to stop. - live && (playing || !nothing_to_play(self.session.as_ref())), + live && (state.is_playing() || !nothing_to_play(self.session.as_ref())), cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)), )) .child(separator()) @@ -6915,6 +6997,20 @@ impl Player { .into_any_element(), // No audio track: nothing, never a fake. Wave::Silent => return None, + // Could not be read: a band that says so in + // words, because the empty band a silent + // file draws would claim this file has no + // sound. The reason itself went to the log. + Wave::Failed => div() + .h_full() + .flex() + .items_center() + .justify_center() + .truncate() + .text_size(px(9.)) + .text_color(rgb(INK_DIM)) + .child("audio unreadable") + .into_any_element(), }; Some( div() @@ -8794,9 +8890,12 @@ fn empty_hint() -> impl IntoElement { ) } -/// Two bars while playing, a triangle while paused. Drawn, so there is no icon -/// font and no glyph coverage to depend on. -fn transport_glyph(playing: bool) -> impl IntoElement { +/// Two bars while playing, a triangle in every other state -- paused, nothing +/// open, and played out, where the button's next act is to start over rather +/// than to stop something. Drawn, so there is no icon font and no glyph +/// coverage to depend on. +fn transport_glyph(state: Transport) -> impl IntoElement { + let playing = state.is_playing(); div() .flex() .items_center() @@ -8852,15 +8951,15 @@ mod tests { KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, - SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, VOLUME_W, Volume, WAVE_BPS, - WAVE_COL, Wave, applicable, band_label, bitrate_refusal, can_add, cancels_export, + SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, Transport, VOLUME_W, Volume, + WAVE_BPS, WAVE_COL, Wave, applicable, band_label, bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, containers, envelope, eq_spectrum, eq_x, eq_y, estimated_mb, export_path, export_settings, format_key, format_line, format_refusal, fps_label, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, menu_at, next_container, normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due, show_label, silence_rate, snapped, - source_tint, span_partner, speed_at, summary_head, summary_tail, timecode, unseen_paths, - unseen_sources, whole_take, width_frac, window_title, + source_tint, span_partner, speed_at, summary_head, summary_tail, timecode, transport, + unseen_paths, unseen_sources, whole_take, width_frac, window_title, }; use super::{ LaneKind, Repeat, View, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, library_rows, @@ -8889,7 +8988,7 @@ mod tests { use gpui::{Bounds, Pixels, point, px, size}; use std::collections::HashMap; use std::path::{Path, PathBuf}; - use std::time::Duration; + use std::time::{Duration, Instant}; fn asset(name: &str) -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")) @@ -10742,6 +10841,95 @@ mod tests { assert_eq!(volume.gain(), 0.75); } + /// The whole transport in one place: the clock keeps running past the last + /// frame (wall time takes over at audio EOF), so "the clock is going" is + /// not "this is playing" -- and a button that read the clock showed Pause + /// on a timeline that had stopped moving. Ended is its own state, it draws + /// Play, and the next press starts over from the top. + #[test] + fn a_played_out_timeline_is_not_playing_and_the_next_press_starts_it_over() { + assert_eq!(transport(true, false), Transport::Playing); + assert_eq!(transport(false, false), Transport::Paused); + // The transition the bug was about: the clock is still running and the + // decoder is finished. Played out wins, however the clock reads. + assert_eq!(transport(true, true), Transport::Ended); + assert_eq!(transport(false, true), Transport::Ended); + + // What the button draws, in each state. Two bars only while it moves. + assert!(Transport::Playing.is_playing()); + for state in [Transport::Paused, Transport::Ended, Transport::Stopped] { + assert!(!state.is_playing(), "{state:?} must draw the Play triangle"); + } + + // And what a press does: start over at the end, plain toggle before it, + // nothing with no timeline. Same answer for the key and the button -- + // both come through `Player::toggle_or_restart`. + assert!(Transport::Ended.restarts()); + for state in [Transport::Playing, Transport::Paused, Transport::Stopped] { + assert!(!state.restarts(), "{state:?} must toggle, not reseek"); + } + } + + /// The half of `Ended` the eye cannot see: the clock. Wall time takes over + /// at the last frame and nothing used to stop it, so the playhead walked off + /// the end of the timeline in real time -- and the playhead is what a cut, a + /// paste, an insert and the analyser all act at. `pump` pauses on the + /// crossing; this is the engine contract that rests on, driven exactly as + /// the pump drives it. + #[test] + fn the_clock_stops_where_the_timeline_does_and_the_end_still_restarts() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + // Start a breath short of the end: the tail is what this is about, and + // playing the whole five seconds would say nothing more. + session.seek(4.8); + session.play(); + + // The pump's own loop -- tick, drain, ask where the transport is -- + // with a deadline so a fixture that will not decode fails as a failure + // rather than as a hang. + let deadline = Instant::now() + Duration::from_secs(20); + let mut state = transport(session.is_playing(), session.is_eos()); + while state != Transport::Ended { + assert!(Instant::now() < deadline, "never reached the end of a 5s file"); + session.tick(); + while session.try_frame().is_some() {} + state = transport(session.is_playing(), session.is_eos()); + } + + // What `pump` does on the crossing, and the whole point of it: the + // position holds still afterwards instead of counting on past the end, + // and it holds still *on the out point* -- where the timecode and the + // playhead have been showing it. The clock at the moment the end is + // recognised is not that: a slow renderer reaches EOF with the clock + // seconds past the timeline, which is why this repositions rather than + // only freezing. + session.halt_at_end(); + let stopped_at = session.now(); + assert_eq!(stopped_at, session.timeline_duration()); + std::thread::sleep(Duration::from_millis(250)); + assert_eq!(session.now(), stopped_at, "the clock kept running past EOF"); + // And it is still the end: pausing must not spend the state the glyph + // and the restart both read. + assert!(session.is_eos()); + assert_eq!( + transport(session.is_playing(), session.is_eos()), + Transport::Ended + ); + + // The restart path off that frozen end, which is what the button and + // the play key do from `Ended`: back to the top, and running. + session.seek(0.); + session.play(); + assert!(!session.is_eos(), "a seek revives the session"); + assert!(session.now() < 1.0); + assert_eq!( + transport(session.is_playing(), session.is_eos()), + Transport::Playing + ); + session.pause(); + } + /// Both ends hold under a key held down: the ABI only accepts `0.0..=1.0`, /// and a wrapped step count would hand it something else. #[test] @@ -11705,8 +11893,6 @@ fn main() { name: name.clone(), image: None, held: None, - eos: false, - done: false, ruler: Rc::default(), // The whole timeline across the bed, which is where a // project opens: zooming is something the user asks for. diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 418d61b..959a6c3 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -66,6 +66,16 @@ symphonia = { version = "0.6", default-features = false, features = [ ] } oxideav-ac3 = "=0.0.10" oxideav-core = "0.1.34" +# The subtitle parsers: SRT and WebVTT here, ASS/SSA in the sibling crate -- +# `oxideav-subtitle` hosts the shared IR and hands ASS to `oxideav-ass`, which +# is why both names are needed for the three formats. MIT, pure Rust, and both +# asked for without their default features: nothing here *draws* a cue yet (see +# `crate::subtitle`), so the rendering stacks are dead weight. Only `oxideav-ass` +# actually loses one -- it depends on `oxideav-subtitle` with defaults on, so +# that crate's `text` feature (the bitmap font and rasterizer) is unified back +# in whatever this line says. Nothing here calls into it. +oxideav-subtitle = { version = "0.1.2", default-features = false } +oxideav-ass = { version = "0.0.9", default-features = false } # The software AV1 encoder, and the only new name in this list that was already # in the lock file: `ravif` pulls the very same rav1e 0.8.1 in through the image # crate, so this links what the build already compiled. BSD-2 with the AOM diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index a705a26..c891e19 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -1000,12 +1000,26 @@ impl Track { if stream > 0 { return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); } - if let Ok(Some(track)) = MkvAc3Track::open(path) { - return Ok(Some(Self::Mkv(track))); + match MkvAc3Track::open(path) { + Ok(Some(track)) => return Ok(Some(Self::Mkv(track))), + Ok(None) => {} + // Named on the way past for the same reason symphonia's failure + // is, below: an AC-3 track that broke is a bug, not a codec we + // never had. + Err(e) => eprintln!("matroska audio: {}: {e}", path.display()), } + // Logged on the way past: "silent" here covers both a codec nothing + // decodes and a track that genuinely broke, and only the second is a + // bug -- with no trace at all it reaches the user as a lane that + // drew no waveform and nothing else to go on. return Ok(SymTrack::open(path) + .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display())) .ok() - .filter(|t| t.decoder().is_ok()) + .filter(|t| { + t.decoder() + .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display())) + .is_ok() + }) .map(Self::Sym)); } let audio_file = crate::is_audio(path); diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 7e7c8d0..f3f08ed 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -340,7 +340,7 @@ struct Block { ts: i64, } -/// AV1 or HEVC out of a Matroska file (`.mkv`/`.webm`). +/// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`). /// /// The whole segment is walked once at open -- element *headers* only, the block /// payloads are seeked over -- because Matroska carries no sample table: the @@ -358,10 +358,11 @@ pub struct MkvDemuxer { /// /// For HEVC this is the Annex-B VPS/SPS/PPS off the `CodecPrivate`, which is /// an `hvcC` record verbatim -- the same blob, re-injected for the same - /// reason, as the one [`Mp4Demuxer`] carries. + /// reason, as the one [`Mp4Demuxer`] carries; for H.264 the SPS/PPS off the + /// `avcC` beside it, which is that record's H.264 twin. config: Vec, - /// Bytes of the NAL length prefix an HEVC block is written with; unused by - /// AV1, whose block is one temporal unit and carries no prefixes. + /// Bytes of the NAL length prefix an HEVC or H.264 block is written with; + /// unused by AV1, whose block is one temporal unit and carries no prefixes. nal_length: usize, /// Bits per luma sample; see [`Demuxer::bit_depth`]. bit_depth: u8, @@ -385,7 +386,7 @@ impl MkvDemuxer { None => { return Err(match other { Some(codec) => format!( - "{codec} video in a Matroska file is not supported — AV1 and HEVC are" + "{codec} video in a Matroska file is not supported — AV1, HEVC and H.264 are" ), None => "this Matroska file has no video track".to_string(), } @@ -737,6 +738,13 @@ fn mkv_track_entry( let (nal_length, sets, bit_depth) = parse_hvcc(&config)?; (Codec::Hevc, nal_length, sets, bit_depth) } + // The `avcC` beside them, and the same story: length-prefixed blocks and + // the SPS/PPS out of the record. Taken as 8-bit, which is what the whole + // H.264 path here assumes of an mp4's `avc1` too. + (1, "V_MPEG4/ISO/AVC") => { + let (nal_length, sets) = parse_avcc(&config)?; + (Codec::H264, nal_length, sets, 8) + } (1, _) => return Ok(MkvEntry::OtherVideo(codec)), (2, _) => return Ok(MkvEntry::Audio(number, codec)), _ => return Ok(MkvEntry::Other), @@ -754,6 +762,48 @@ fn mkv_track_entry( })) } +/// AVCDecoderConfigurationRecord (ISO 14496-15 §5.3.3.1) -> the NAL length +/// prefix width and the SPS/PPS as one Annex-B blob, which is [`parse_hvcc`]'s +/// job for HEVC. The mp4 path gets both out of `mp4 0.14`'s `AvcCBox`; a +/// Matroska file carries the identical record in `CodecPrivate`, unparsed. +fn parse_avcc(rec: &[u8]) -> crate::Result<(usize, Vec)> { + // 0 configurationVersion .. 4 lengthSizeMinusOne, 5 numOfSequenceParameterSets. + let (&flags, &sps_count) = rec + .get(4) + .zip(rec.get(5)) + .ok_or("avcC record shorter than its fixed header")?; + let mut sets = Vec::new(); + let mut src = &rec[6..]; + // The SPS array, whose count is the low 5 bits of byte 5, and then the PPS + // array, whose count is a byte of its own. + let mut count = usize::from(sps_count & 0x1f); + for array in 0..2 { + if array == 1 { + let (&pps_count, rest) = src + .split_first() + .ok_or("avcC record ends before its PPS count")?; + count = usize::from(pps_count); + src = rest; + } + for _ in 0..count { + let len = usize::from(u16::from_be_bytes( + src.get(..2) + .ok_or("avcC NAL length past the record")? + .try_into() + .unwrap(), + )); + let nal = src.get(2..2 + len).ok_or("avcC NAL past the record")?; + sets.extend_from_slice(&START_CODE); + sets.extend_from_slice(nal); + src = &src[2 + len..]; + } + } + if sets.is_empty() { + return Err("avcC record carries no SPS/PPS".into()); + } + Ok((usize::from(flags & 0x3) + 1, sets)) +} + /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF /// §2.3.3): four fixed bytes, then the sequence header OBU in the same /// low-overhead format the blocks are in, so it needs no reframing. @@ -1239,6 +1289,216 @@ fn tkhd_track_id(payload: &[u8]) -> Option { )) } +/// One subtitle track of a Matroska file, exactly as its `TrackEntry` declares +/// it. What the cues *mean* is [`crate::subtitle`]'s business; this is the +/// walk, and it reads every track type 0x11 the file has -- including the ones +/// nothing here can render, which is how a caller names what it is leaving out +/// instead of quietly opening a film with no subtitles in the list. +#[derive(Debug)] +pub struct MkvSubtitle { + pub number: u64, + /// The Matroska codec id: `S_TEXT/UTF8`, `S_TEXT/ASS`, `S_HDMV/PGS`, ... + pub codec: String, + /// `Language`, ISO-639-2, `und` when the file says nothing. + pub language: String, + /// `Name`, the human label a muxer wrote, often empty. + pub name: String, + /// `CodecPrivate`: the ASS script header (`[Script Info]` through the + /// `[Events]` `Format:` line) for `S_TEXT/ASS`, empty for `S_TEXT/UTF8`. + pub private: Vec, + /// Every cue block, in storage order -- but only for the `S_TEXT/*` codecs. + /// A bitmap track (PGS, VobSub) comes back declared and empty: its blocks + /// are megabytes of pictures, and nothing here can draw one. + pub cues: Vec, +} + +/// One subtitle block: when it shows and the bytes it shows. +#[derive(Debug)] +pub struct MkvCue { + /// Microseconds from the start of the file -- the block timestamp scaled by + /// the segment's `TimestampScale`, which is the unit + /// [`crate::subtitle::Cue`] keeps. + pub start_us: i64, + /// `BlockDuration`, microseconds. `None` for a block that declares none, + /// which leaves how long the cue stays up to the caller. + pub duration_us: Option, + /// The block's own bytes: the text for `S_TEXT/UTF8`, the comma-separated + /// `Dialogue` fields (`ReadOrder` first, no timing) for `S_TEXT/ASS`. + pub payload: Vec, +} + +/// The subtitle tracks of a Matroska file, in file order. An mp4's are not read +/// (its `tx3g` is a different beast, and no file this project opens carries +/// one); anything that is not a Matroska file at all is an error, as it is for +/// [`matroska_audio_codec`]. +/// +/// Two passes at most: the header walk stops at the first `Cluster`, and the +/// cue pass runs only when there is a text track to fill. +pub fn matroska_subtitles(path: &Path) -> crate::Result> { + let mut file = File::open(path)?; + let end = file.metadata()?.len(); + let segment = mkv_segment(&mut file, end)?; + let mut tracks: Vec = Vec::new(); + let mut timestamp_scale = 1_000_000; + let mut at = segment.0; + while let Some((id, body, stop)) = ebml_element(&mut file, at, segment.1)? { + match id { + CLUSTER => break, + INFO => { + let mut at = body; + while let Some(e) = ebml_element(&mut file, at, stop)? { + if e.0 == TIMESTAMP_SCALE { + timestamp_scale = ebml_uint(&mut file, e.1, e.2)?.max(1); + } + at = e.2; + } + } + TRACKS => { + let mut at = body; + while let Some(e) = ebml_element(&mut file, at, stop)? { + if e.0 == TRACK_ENTRY { + tracks.extend(mkv_subtitle_entry(&mut file, e.1, e.2)?); + } + at = e.2; + } + } + _ => {} + } + at = stop; + } + // The text tracks only: see `MkvSubtitle::cues`. + let wanted: Vec = tracks + .iter() + .filter(|t| t.codec.starts_with("S_TEXT")) + .map(|t| t.number) + .collect(); + if !wanted.is_empty() { + mkv_subtitle_blocks(&mut file, segment, timestamp_scale, &wanted, &mut tracks)?; + } + Ok(tracks) +} + +/// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles. +fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result> { + const TRACK_LANGUAGE: u32 = 0x22B59C; + const TRACK_NAME: u32 = 0x536E; + const SUBTITLE: u64 = 0x11; + let (mut number, mut kind, mut codec) = (0, 0, String::new()); + let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new()); + let mut at = body; + while let Some((id, body, stop)) = ebml_element(file, at, end)? { + match id { + TRACK_NUMBER => number = ebml_uint(file, body, stop)?, + TRACK_TYPE => kind = ebml_uint(file, body, stop)?, + CODEC_ID => codec = string_of(file, body, stop)?, + CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?, + TRACK_LANGUAGE => language = string_of(file, body, stop)?, + TRACK_NAME => name = string_of(file, body, stop)?, + _ => {} + } + at = stop; + } + Ok((kind == SUBTITLE).then(|| MkvSubtitle { + number, + codec, + // What a `TrackEntry` without a `Language` element means, by spec. + language: if language.is_empty() { + "und".into() + } else { + language + }, + name, + private, + cues: Vec::new(), + })) +} + +/// Every block of the `wanted` tracks, appended to their entries in `tracks`. +/// +/// A second cluster walk rather than a widening of [`mkv_blocks`]: that one +/// indexes *one* video track and reads no payloads, and a subtitle needs every +/// track at once, the bytes, and the `BlockDuration` beside them. +fn mkv_subtitle_blocks( + file: &mut File, + segment: (u64, u64), + timestamp_scale: u64, + wanted: &[u64], + tracks: &mut [MkvSubtitle], +) -> crate::Result<()> { + const BLOCK_DURATION: u32 = 0x9B; + // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is + // nanoseconds per tick and is a millisecond in every file anything writes. + let us = |ticks: i64| ticks * timestamp_scale as i64 / 1_000; + let mut at = segment.0; + while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { + at = stop; + if id != CLUSTER { + continue; + } + let mut cluster_ts = 0i64; + let mut child = body; + while let Some((id, body, stop)) = ebml_element(file, child, stop)? { + child = stop; + let (block, duration) = match id { + CLUSTER_TIMESTAMP => { + cluster_ts = ebml_uint(file, body, stop)? as i64; + continue; + } + SIMPLE_BLOCK => (mkv_block(file, body, stop)?, None), + BLOCK_GROUP => { + let (mut found, mut duration) = (None, None); + let mut child = body; + while let Some(e) = ebml_element(file, child, stop)? { + match e.0 { + BLOCK => found = Some(mkv_block(file, e.1, e.2)?), + BLOCK_DURATION => duration = Some(ebml_uint(file, e.1, e.2)? as i64), + _ => {} + } + child = e.2; + } + match found { + Some(block) => (block, duration), + None => continue, + } + } + _ => continue, + }; + if !wanted.contains(&block.number) { + continue; + } + // As for a video block: guessing at the boundaries inside a laced + // one is not something to do silently. No muxer laces subtitles. + if block.flags & 0x06 != 0 { + return Err("laced subtitle blocks are not supported".into()); + } + // A megabyte of *text* in one cue is a corrupt file, not a subtitle, + // and a crafted length may not reach an allocation through here. + if block.len > 1 << 20 { + return Err("a Matroska subtitle block larger than a megabyte".into()); + } + let mut payload = vec![0u8; block.len]; + read_exact_at(file, block.at, &mut payload)?; + let Some(track) = tracks.iter_mut().find(|t| t.number == block.number) else { + continue; + }; + track.cues.push(MkvCue { + start_us: us(cluster_ts + i64::from(block.rel)), + duration_us: duration.map(us), + payload, + }); + } + } + Ok(()) +} + +/// A string element, without the trailing NULs a `Name` may be padded with. +fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result { + let bytes = ebml_bytes(file, body, stop)?; + Ok(String::from_utf8_lossy(&bytes) + .trim_end_matches('\0') + .to_owned()) +} + #[cfg(test)] mod tests { use super::*; @@ -1296,6 +1556,37 @@ mod tests { assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err()); } + /// The `avcC` parse: prefix width out of byte 4, and both arrays -- the SPS + /// count is five bits of byte 5, the PPS count a byte of its own, and taking + /// the second for the first is the mistake this checks against. + #[test] + fn reads_parameter_sets_out_of_an_avcc_record() { + let mut rec = vec![1, 0x42, 0x00, 0x1f, 0xfc | 0x1, 0xe0 | 2]; + for (kind, nal) in [(7u8, 0xAAu8), (7, 0xBB)] { + rec.extend_from_slice(&2u16.to_be_bytes()); + rec.extend_from_slice(&[kind, nal]); + } + rec.push(1); // numOfPictureParameterSets + rec.extend_from_slice(&2u16.to_be_bytes()); + rec.extend_from_slice(&[8, 0xCC]); + + let (len, sets) = parse_avcc(&rec).unwrap(); + assert_eq!(len, 2, "lengthSizeMinusOne == 1"); + assert_eq!( + sets, + [ + 0, 0, 0, 1, 7, 0xAA, // SPS + 0, 0, 0, 1, 7, 0xBB, // the second SPS, which a one-array read loses + 0, 0, 0, 1, 8, 0xCC, // PPS + ] + ); + // Nothing is read past the end of a truncated record, and a Matroska + // file with no `CodecPrivate` at all is refused rather than started. + assert!(parse_avcc(&rec[..5]).is_err()); + assert!(parse_avcc(&rec[..rec.len() - 1]).is_err()); + assert!(parse_avcc(&[]).is_err()); + } + /// EBML's variable-length integers, which every Matroska read starts with: /// the leading zeros of the first byte are the length, an *id* keeps its /// marker bit and a *size* loses it, and an all-ones size is "unknown". diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 52461ef..0a8890c 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -1,13 +1,15 @@ //! The project file: a line of text per thing, and nothing else. //! //! ```text -//! edith 9 +//! edith 10 //! playhead 90 //! resolution 1920 1080 //! fps 30.0 //! limiter -1.0 on //! source 0 test_av.mp4 //! source 1 /elsewhere/test_av2.mp4 +//! subtitle - subs.srt +//! subtitle 3 test_av.mp4 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk //! color 0.1:1.2:0.9:-0.3 //! video 1 0 0 120 0 0 0 0 fit 1000 @@ -23,6 +25,15 @@ //! is an answer only a project holding a video has //! ([`crate::PlaybackSession::open_project`]). //! +//! A `subtitle` line is `subtitle `: which track of that file the +//! cues are in -- a Matroska track number, or `-` when the path *is* a subtitle +//! file ([`crate::subtitle`]) -- and then the path, last and escaped for the +//! reason a source's is. Only the reference is written: the cues themselves are +//! read back out of the file on the way in, exactly as a clip's pictures are, so +//! a project file stays an edit list. A subtitle file that has gone missing +//! since the save comes back listed and refused by name rather than dropped, +//! which is what keeps a re-save from losing it. +//! //! The `limiter` line is the master limiter over the whole mix //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit, //! spelled `on` or `off`. Left out when it is the default, which is off. @@ -79,7 +90,9 @@ //! is the only way an empty lane could still be there on the way back. A lane //! number may not skip one of its kind. //! -//! **Version 8** was this without the `fps` and `limiter` lines and without +//! **Version 9** was this without the `subtitle` lines: such a project shows no +//! subtitles, which is all any project could do. +//! **Version 8** was that without the `fps` and `limiter` lines and without //! the `gain` ones: such a project mixes every lane at unity, limits nothing, //! and comes back at the rate its scaffolding source runs at. //! **Version 7** was that without the clip's speed field -- every clip of such @@ -97,8 +110,8 @@ //! cumulatively and copied onto both lanes as one group each, which is exactly //! what a v1 timeline meant, and an older file simply equalizes and grades //! nothing, and an older one plays everything at real time, and an older one -//! mixes flat -- and saving any of them writes v9. An older reader refuses a -//! newer file by name. +//! mixes flat, and an older one shows no subtitles -- and saving any of them +//! writes v10. An older reader refuses a newer file by name. //! //! Text because an edit list is a few integers and a path, and a path is //! *bytes* on this platform -- a JSON string would have to lossily decode one. @@ -129,10 +142,12 @@ use crate::eq::{Band, BandKind, EqParams}; use crate::limiter::Limiter; use crate::project::{Clip, Lane, LaneKind, Source, Speed}; use crate::scale::FitPolicy; +use crate::subtitle::SubtitleTrack; /// What [`save`] writes. Read support goes back to `edith 1`; see the module /// docs for what those dialects looked like. -const MAGIC: &[u8] = b"edith 9"; +const MAGIC: &[u8] = b"edith 10"; +const MAGIC_V9: &[u8] = b"edith 9"; const MAGIC_V8: &[u8] = b"edith 8"; const MAGIC_V7: &[u8] = b"edith 7"; const MAGIC_V6: &[u8] = b"edith 6"; @@ -169,6 +184,11 @@ pub struct Document { /// The master limiter. Off for every dialect before v9, and for a v9 file /// that leaves the line out. pub limiter: Limiter, + /// The subtitle tracks, as the file names them: the path the cues are in + /// and which track of it, which is what [`crate::subtitle::open`] takes. + /// Reading them is the loader's business, not this module's -- a `.edith` + /// holds no cues. Empty for every dialect before v10. + pub subtitles: Vec<(PathBuf, Option)>, /// The timeline's frame rate. `None` for every dialect before v9 and for a /// v9 file that leaves it out, which both mean "whatever the scaffolding /// source runs at" -- the inference a project of nothing but stills and @@ -188,6 +208,7 @@ pub fn save( sources: &[Source], lanes: &[(LaneKind, Vec)], gains: &[f32], + subtitles: &[SubtitleTrack], eq: &[EqParams], color: &[ColorParams], resolution: (u32, u32), @@ -206,7 +227,8 @@ pub fn save( let result = std::fs::File::create(&part) .and_then(|mut f| { f.write_all(&emit( - &dir, sources, lanes, gains, eq, color, resolution, fps, limiter, playhead, + &dir, sources, lanes, gains, subtitles, eq, color, resolution, fps, limiter, + playhead, ))?; f.sync_all() }) @@ -243,6 +265,7 @@ fn emit( sources: &[Source], lanes: &[(LaneKind, Vec)], gains: &[f32], + subtitles: &[SubtitleTrack], eq: &[EqParams], color: &[ColorParams], resolution: (u32, u32), @@ -280,6 +303,16 @@ fn emit( escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out); out.push(b'\n'); } + // The subtitle tracks, by reference: which track of which file, and never + // the cues (see the module docs). Beside the sources because that is what + // they are -- a file this project reads from -- although nothing indexes + // them and their order is only the order they were added in. + for t in subtitles { + let track = t.track.map_or("-".to_string(), |n| n.to_string()); + out.extend_from_slice(format!("subtitle {track} ").as_bytes()); + escape(t.path.strip_prefix(dir).unwrap_or(&t.path), &mut out); + out.push(b'\n'); + } // Before the clips, for the reason the sources are: a clip names one by the // position of its line, so the line has to be there first. for params in eq { @@ -379,9 +412,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // The dialects that wrote a source line without its stream field. Reading // one is the whole of what "an old project still opens" means here. let streamless = v1 || first == MAGIC_V2; - // The one that carries the mix -- lane volumes, the master limiter and the - // rate the timeline was cut at... - let v9 = first == MAGIC; + // The one that carries subtitle tracks... + let v10 = first == MAGIC; + // ...the ones that carry the mix -- lane volumes, the master limiter and + // the rate the timeline was cut at... + let v9 = v10 || first == MAGIC_V9; // ...the ones that carry a per-clip speed... let v8 = v9 || first == MAGIC_V8; // ...the ones that carry a project resolution and per-clip fit policies... @@ -418,6 +453,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // ...and nothing before v9 carries a mix or a rate: every lane at unity, // no limiter, and the rate inferred from the scaffold as it always was. gains: Vec::new(), + // Nothing before v10 shows a subtitle. + subtitles: Vec::new(), limiter: Limiter::default(), fps: None, playhead: 0, @@ -528,6 +565,31 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { doc.gains.resize(doc.lanes.len(), 0.0); doc.gains[at] = float(f[2], n)?; } + // Beside the source lines and read the same way: fields first, the + // path last, because a path runs to the end of the line. + b"subtitle" if v10 => { + let at = rest + .iter() + .position(|&b| b == b' ') + .ok_or_else(|| format!("line {n}: subtitle without a path"))?; + let track = match &rest[..at] { + b"-" => None, + field => Some(u64::from(number(field, n)?)), + }; + let path = unescape(&rest[at + 1..], n)?; + if path.as_os_str().is_empty() { + return Err(format!("line {n}: subtitle without a path").into()); + } + doc.subtitles.push(( + // Relative to the project file, as a source path is. + if path.is_absolute() { + path + } else { + dir.join(path) + }, + track, + )); + } b"source" => { if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { return Err(format!("line {n}: source after a clip").into()); @@ -963,6 +1025,7 @@ mod tests { sources, lanes, &[], + &[], eq, color, resolution, @@ -972,6 +1035,84 @@ mod tests { ) } + /// A subtitle track as a save hands one over: the cues are not written and + /// so are not here either. + fn subtitle(path: &str, track: Option) -> SubtitleTrack { + SubtitleTrack { + path: PathBuf::from(path), + track, + label: String::new(), + cues: Vec::new(), + refused: None, + } + } + + /// The v10 line: which track of which file, written beside the sources and + /// read back as the pair a load opens. And what a v9 file is -- one with no + /// subtitles at all, which still opens and re-saves as v10. + #[test] + fn subtitles_round_trip_as_references_and_a_v9_file_has_none() { + let dir = PathBuf::from("/proj"); + let (_, sources, lanes) = doc(); + let tracks = [ + subtitle("/proj/subs.srt", None), + subtitle("/proj/a.mp4", Some(3)), + subtitle("/elsewhere/od d name.ass", None), + ]; + let bytes = super::emit( + &dir, + &sources, + &lanes, + &[], + &tracks, + &[], + &[], + (1280, 720), + None, + Limiter::default(), + 0, + ); + let text = String::from_utf8_lossy(&bytes); + assert!( + text.contains( + "subtitle - subs.srt\n\ + subtitle 3 a.mp4\n\ + subtitle - /elsewhere/od d name.ass\n" + ), + "the path is relative where it can be, and runs to the end of its \ + line, spaces and all: {text}" + ); + let back = parse(&bytes, &dir).expect("v10 parses"); + assert_eq!( + back.subtitles, + vec![ + (PathBuf::from("/proj/subs.srt"), None), + (PathBuf::from("/proj/a.mp4"), Some(3)), + (PathBuf::from("/elsewhere/od d name.ass"), None), + ] + ); + + // A v9 file is a project with no subtitles, and re-saving it writes v10. + let v9 = b"edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000\n"; + let old = parse(v9, &dir).expect("v9 still loads"); + assert_eq!(old.subtitles, Vec::new()); + assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 10\n")); + // ...and the line itself is not a v9 line: a dialect may not be mixed. + let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir) + .unwrap_err() + .to_string(); + assert_eq!(mixed, "line 3: unknown keyword \"subtitle\""); + // A subtitle line with no path is refused, as a source with none is. + for line in ["subtitle -\n", "subtitle - \n", "subtitle x subs.srt\n"] { + let file = format!("edith 10\nsource 0 a.mp4\n{line}"); + assert!( + parse(file.as_bytes(), &dir).is_err(), + "{line:?} is not a subtitle line" + ); + } + } + fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option) -> Clip { Clip { start, @@ -1032,7 +1173,7 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 12); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n", @@ -1069,7 +1210,7 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 7); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", "an empty lane is a line of its own; everything else is its clips" @@ -1177,7 +1318,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 16777215.0:-0.1:3.918315e-39:hs\n\ eq\n\ @@ -1281,7 +1422,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ color 0.1:1.2:0.9:-0.3\n\ color -1e-7:16777215.0:3.918315e-39:-0.0\n\ color 0.0:1.0:1.0:0.0\n\ @@ -1346,7 +1487,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" ); @@ -1384,7 +1525,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ audio 1 0 0 30 0 - - - fit 2000\n", "the rate is the clip line's last field, in thousandths" @@ -1413,7 +1554,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" ); // A rate outside what the editor can set is a corrupt line, by name. @@ -1450,6 +1591,7 @@ mod tests { &[0.0, 3.0, -6.5], &[], &[], + &[], (1280, 720), Some(23.976023976023978), limiter, @@ -1457,7 +1599,7 @@ mod tests { ); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ limiter -1.5 on\nsource 0 a.mp4\n\ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\ audio 2 0 0 30 0 - - - fit 1000\n\ @@ -1489,7 +1631,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" ); @@ -1653,7 +1795,7 @@ mod tests { assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); assert_eq!( String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), - "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n" @@ -1706,7 +1848,7 @@ mod tests { let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); assert_eq!( String::from_utf8_lossy(&v5), - "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 0 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n", @@ -1738,7 +1880,7 @@ mod tests { // Saved again it is the current version, which round-trips to the // same document. let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); - assert!(v5.starts_with(b"edith 9\n")); + assert!(v5.starts_with(b"edith 10\n")); let again = parse(&v5, &dir).expect("v5 parses"); assert_eq!(again.lanes, back.lanes); // A dialect may not be mixed: lane lines under v1, `clip` under v2. @@ -1834,6 +1976,7 @@ mod tests { &[], &[], &[], + &[], (1280, 720), None, Limiter::default(), @@ -1843,7 +1986,7 @@ mod tests { let bytes = std::fs::read(&path).expect("read back"); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 9\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" ); // Loading rejoins the *given* directory, so the file is reached by the @@ -1888,10 +2031,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 10\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) + let err = parse(b"edith 11\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 10"); + assert_eq!(err, "line 1: unsupported version 11"); for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { assert_eq!( parse(junk, &dir).unwrap_err().to_string(), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index afca436..0e3a706 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -17,6 +17,7 @@ pub mod playback; pub mod project; pub mod scale; pub mod silence; +pub mod subtitle; pub mod waveform; pub use audio::{ diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 12b149d..0fe9192 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -673,8 +673,19 @@ impl PlaybackSession { } let playhead = doc.playhead; + // The subtitle files are read here rather than in the parser: a + // `.edith` names them and holds no cues. One that has gone missing, or + // whose track is a codec of pictures, comes back listed and refused by + // name ([`crate::subtitle::open`]) -- a project does not stop opening + // over a subtitle, and a re-save does not lose the row. + let subtitles = doc + .subtitles + .iter() + .map(|(path, track)| crate::subtitle::open(path, *track)) + .collect(); let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)? - .with_mix(&doc.gains, doc.limiter); + .with_mix(&doc.gains, doc.limiter) + .with_subtitles(subtitles); let span = project.composite_span_at(0); // Last, because it is the one thing here that cannot be taken back: the // feeder thread outlives the `Audio` value (it holds its own clones) and @@ -755,6 +766,47 @@ impl PlaybackSession { self.project.sources() } + /// The subtitle tracks on this timeline, in the order they were added: what + /// a front-end lists and what [`save_project`](Self::save_project) writes. + /// A track that could not be read is *in* this list, saying why + /// ([`crate::subtitle::SubtitleTrack::refused`]) -- listed and skipped, not + /// dropped. + pub fn subtitles(&self) -> &[crate::subtitle::SubtitleTrack] { + self.project.subtitles() + } + + /// Adds subtitles from `path`: every subtitle track of a Matroska file, or + /// the one track a standalone `.srt`/`.vtt`/`.ass` is. Hands back how many + /// were added -- 0 for a file whose tracks are all on the timeline already, + /// since importing the same file twice is the same subtitles. + /// + /// An error only when the file cannot be read *at all*; a track this cannot + /// parse is added refused by name, for the reason + /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves: + /// subtitles are not clips and land on no lane. + pub fn import_subtitles(&mut self, path: &Path) -> crate::Result { + let tracks = match path.extension().is_some_and(|e| { + let e = e.to_string_lossy().to_ascii_lowercase(); + e == "mkv" || e == "webm" + }) { + true => crate::subtitle::of_matroska(path)?, + false => vec![crate::subtitle::open(path, None)], + }; + // A standalone file that could not be parsed is a refusal here rather + // than a row nobody asked for: the import is the moment to say so, and + // the load is the moment to keep it. + if let [one] = &tracks[..] + && one.track.is_none() + && let Some(why) = &one.refused + { + return Err(why.clone().into()); + } + Ok(tracks + .into_iter() + .filter(|t| self.project.add_subtitles(t)) + .count()) + } + /// Writes the timeline to `path` as a `.edith`, atomically (see /// [`crate::edith`]). Sources no clip plays from are left out, and the /// playhead is saved with it so a reopened project resumes where it stood. @@ -780,6 +832,9 @@ impl PlaybackSession { // project's, not this machine's (the monitoring volume is not // written and never will be). &self.project.lane_gains(), + // The subtitle tracks with them, by reference: which file the cues + // are in, never the cues (see [`crate::edith`]). + self.project.subtitles(), &eq, &color, (self.meta.width, self.meta.height), @@ -1732,6 +1787,25 @@ impl PlaybackSession { } } + /// Stops the transport where the timeline stops: the clock is paused and put + /// on the out point. + /// + /// Playing past the last frame is wall time counting on past the end of the + /// media -- there is no picture left to pace it -- so a session left at EOF + /// reports a `now()` that walks off the end of the timeline in real time, + /// and a caller that reads the playhead (a cut, a paste, an insert) then + /// acts at a position no clip is at. How far off depends only on how long + /// the window was left open, so no clamp in a caller is worth writing. + /// + /// End of stream is deliberately left set: the picture is still the last + /// frame and this is still the end. That is what makes it safe to call on + /// the crossing into it -- the state the transport shows does not change, + /// only the running clock stops. + pub fn halt_at_end(&mut self) { + self.pause(); + self.clock.seek_to(self.timeline_duration()); + } + /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0: /// one knob, because muting and turning it down are the same thing to the /// device, and *which* the user meant is a question only the UI can answer diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 818741e..b9e6774 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -68,6 +68,7 @@ use crate::color::ColorParams; use crate::eq::EqParams; use crate::limiter::{Limiter, db_to_linear}; use crate::scale::FitPolicy; +use crate::subtitle::SubtitleTrack; /// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]). /// -60 dB is a thousandth of the amplitude -- a track that is out of the mix @@ -618,6 +619,12 @@ pub struct Project { /// Never rolled back by an undo: an id retired by an undone split must not /// come back and group two clips that were never together. next_link: u32, + /// The subtitle tracks this timeline shows, in the order they were added. + /// Not in the lane list and not in the history snapshots, for the reason + /// the limiter is not: which subtitles a project carries is a setting on + /// it, and it is saved as a *reference* to the file the cues came out of + /// ([`crate::subtitle`]). + subtitles: Vec, /// The master limiter every lane's sound is summed *through* /// ([`Project::limiter`]). Off by default, and not in the lane list, which /// is what the history snapshots hold: it is a setting on the mix, like the @@ -652,6 +659,7 @@ impl Project { color: Vec::new(), history: Vec::new(), next_link: 1, + subtitles: Vec::new(), limiter: Limiter::default(), } } @@ -760,6 +768,7 @@ impl Project { color, history: Vec::new(), next_link, + subtitles: Vec::new(), limiter: Limiter::default(), }) } @@ -1128,6 +1137,35 @@ impl Project { self } + /// The subtitle tracks a *load* puts back, in the order they were saved -- + /// the same door [`with_mix`](Project::with_mix) is, and no undo step for + /// the same reason. + pub fn with_subtitles(mut self, tracks: Vec) -> Self { + self.subtitles = tracks; + self + } + + /// What this timeline shows over the picture, in the order they were added: + /// what a front-end lists and what a save writes. + pub fn subtitles(&self) -> &[SubtitleTrack] { + &self.subtitles + } + + /// Adds a track, unless the very same one -- same file, same track number + /// inside it -- is already on the list. `false` for that repeat: importing + /// the same `.srt` twice is one subtitle track, not two identical ones. + pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool { + if self + .subtitles + .iter() + .any(|t| t.path == track.path && t.track == track.track) + { + return false; + } + self.subtitles.push(track.clone()); + true + } + /// What each of [`audio_segments_from`](Project::audio_segments_from)'s /// lanes is multiplied by on its way into the mix: the same lanes in the /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0` diff --git a/crates/engine/src/subtitle.rs b/crates/engine/src/subtitle.rs new file mode 100644 index 0000000..27d1f20 --- /dev/null +++ b/crates/engine/src/subtitle.rs @@ -0,0 +1,344 @@ +//! Subtitles: a list of cues with a time on them, out of a file beside the +//! media (`.srt`, `.vtt`, `.ass`) or out of a track inside it. +//! +//! One model for both, because a timeline cannot care which it was: a +//! [`SubtitleTrack`] is where it came from -- a path, and the Matroska track +//! number when it is one of several inside that path -- plus the [`Cue`]s. That +//! pair is also all a `.edith` writes ([`crate::edith`]): the cues are read +//! back out of the file on the way in, exactly as a clip's *pictures* are, so a +//! project file stays an edit list and not a copy of the subtitles. +//! +//! Parsing is `oxideav-subtitle` (SRT, WebVTT) and `oxideav-ass` (ASS/SSA) -- +//! the markup, the override tags and the encoding quirks of a dozen dialects +//! are not this project's to re-derive. What comes back here is plain text: the +//! renderer is a later thing, and a cue nobody can draw yet is still a cue that +//! has to be listed, timed and saved. +//! +//! What is *refused* is refused by name rather than by omission +//! ([`SubtitleTrack::refused`]): the bitmap subtitle formats -- PGS off a +//! BluRay remux, VobSub off a DVD -- are pictures, and a film carrying four of +//! them opens with four rows that say so instead of opening with an empty list. + +use std::path::{Path, PathBuf}; + +use oxideav_subtitle::ir::plain_text; + +/// One line of subtitle: on screen from `start_us` to `end_us`, microseconds +/// from the start of the media, which is the unit every parser here speaks. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Cue { + pub start_us: i64, + pub end_us: i64, + /// Plain text, `\n` between the lines of a multi-line cue. The markup is + /// resolved and dropped: `` from an SRT, `{\an8}` and `\N` from an ASS. + /// + /// ponytail: bold/italic/colour and ASS positioning are parsed by the crate + /// and thrown away here, because nothing draws a cue yet. The upgrade path + /// is to keep `oxideav_core::Segment` beside this string -- the parsers + /// already hand it over -- and it belongs to whoever writes the renderer. + pub text: String, +} + +/// A subtitle track: where it came from and what it says. +#[derive(Clone, Debug)] +pub struct SubtitleTrack { + /// The file it was read out of: a standalone subtitle file, or the media + /// file whose track number is below. + pub path: PathBuf, + /// Which track of `path`, for one embedded in a Matroska file. `None` when + /// `path` *is* the subtitle file. + pub track: Option, + /// What a list shows: a language, a muxer's name for the track, or the + /// file's own name for a standalone one. + pub label: String, + /// In start order. Empty when [`refused`](Self::refused) says why. + pub cues: Vec, + /// Why this track has no cues, when it has none: a codec that is pictures + /// rather than text, a file that has gone missing since the project was + /// saved. `None` for one that parsed -- which a track with genuinely no + /// cues in it also is. + pub refused: Option, +} + +impl SubtitleTrack { + /// A track that is there and cannot be read, named and kept: a project + /// re-saved after one of these still lists it, which is the difference + /// between "your subtitles are missing" and losing them for good. + fn refused(path: &Path, track: Option, label: String, why: String) -> Self { + Self { + path: path.to_path_buf(), + track, + label, + cues: Vec::new(), + refused: Some(why), + } + } +} + +/// The one door a saved subtitle line comes back in through: a standalone file +/// (`track` is `None`) or track `n` of a Matroska file. +/// +/// Never an error, whatever is wrong: a deleted `.srt`, a media file that is +/// not there any more, a track number the file no longer has, a codec of +/// pictures. All of them come back [`refused`](SubtitleTrack::refused) by name, +/// because a project that opened yesterday has to open today -- a subtitle is +/// not what a whole timeline should refuse over. +pub fn open(path: &Path, track: Option) -> SubtitleTrack { + let Some(number) = track else { + return external(path); + }; + let label = format!("track {number}"); + let mut tracks = match of_matroska(path) { + Ok(tracks) => tracks, + Err(why) => return SubtitleTrack::refused(path, track, label, why.to_string()), + }; + match tracks.iter().position(|t| t.track == Some(number)) { + Some(i) => tracks.swap_remove(i), + None => SubtitleTrack::refused( + path, + track, + label, + format!("no subtitle track {number} in {} any more", path.display()), + ), + } +} + +/// A standalone subtitle file, parsed by its extension. +fn external(path: &Path) -> SubtitleTrack { + let label = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + match parse_file(path) { + Ok(cues) => SubtitleTrack { + path: path.to_path_buf(), + track: None, + label, + cues, + refused: None, + }, + Err(why) => SubtitleTrack::refused(path, None, label, why.to_string()), + } +} + +/// Every subtitle track of a Matroska file, in file order -- the text ones with +/// their cues, the bitmap ones refused by name (see the module docs). +pub fn of_matroska(path: &Path) -> crate::Result> { + Ok(crate::demux::matroska_subtitles(path)? + .into_iter() + .map(|t| { + let label = match (t.name.is_empty(), t.language.as_str()) { + (true, lang) => lang.to_owned(), + (false, "und") => t.name.clone(), + (false, lang) => format!("{lang} — {}", t.name), + }; + match cues_of(&t) { + Ok(cues) => SubtitleTrack { + path: path.to_path_buf(), + track: Some(t.number), + label, + cues, + refused: None, + }, + Err(why) => SubtitleTrack::refused(path, Some(t.number), label, why), + } + }) + .collect()) +} + +/// The cues of one Matroska subtitle track, or why it has none. +/// +/// A Matroska text track carries the *timing* on the block and the *text* in +/// it, so neither codec is parsed as its own file would be: `S_TEXT/UTF8` is +/// one SRT cue's body per block, `S_TEXT/ASS` is one `Dialogue` line per block +/// with the `Start` and `End` fields cut out and the `[Script Info]` header +/// filed away in `CodecPrivate`. Both are put back into the shape their parser +/// reads -- rather than the markup being re-derived here -- which is also what +/// makes an embedded track and the standalone file it was muxed from come back +/// as the same cues. +fn cues_of(track: &crate::demux::MkvSubtitle) -> Result, String> { + let cues = match track.codec.as_str() { + "S_TEXT/UTF8" | "S_TEXT/ASCII" => track + .cues + .iter() + .map(|c| Cue { + start_us: c.start_us, + end_us: end_of(track, c), + text: srt_body(&String::from_utf8_lossy(&c.payload)), + }) + .collect(), + "S_TEXT/ASS" | "S_TEXT/SSA" => ass_cues(track)?, + codec => { + return Err(format!( + "{codec} subtitles are pictures, not text — this track is listed, not read" + )); + } + }; + Ok(cues) +} + +/// When a cue goes away: its `BlockDuration`, or -- for the muxer that writes +/// none -- when the next one arrives, and [`NO_DURATION_US`] for the last. +fn end_of(track: &crate::demux::MkvSubtitle, cue: &crate::demux::MkvCue) -> i64 { + /// How long a cue with nothing to say about it stays up: two seconds, a + /// read of one line. + const NO_DURATION_US: i64 = 2_000_000; + match cue.duration_us { + Some(d) => cue.start_us + d, + None => track + .cues + .iter() + .map(|c| c.start_us) + .find(|&s| s > cue.start_us) + .unwrap_or(cue.start_us + NO_DURATION_US), + } +} + +/// The text of one `S_TEXT/UTF8` block with its markup resolved: through the +/// SRT parser, around a timing line this then throws away, because SRT markup +/// is exactly what such a block holds and a second implementation of it here +/// would be a second set of bugs. +fn srt_body(text: &str) -> String { + let doc = format!("1\n00:00:00,000 --> 00:00:01,000\n{}\n", text.trim_end()); + match oxideav_subtitle::srt::parse(doc.as_bytes()) { + Ok(track) => track + .cues + .first() + .map(|c| plain_text(&c.segments)) + .unwrap_or_default(), + // The parser refuses nothing an SRT body can hold; if it ever does, + // the bytes themselves are a better answer than an empty cue. + Err(_) => text.trim_end().to_owned(), + } +} + +/// The cues of an `S_TEXT/ASS` track: the script header out of `CodecPrivate` +/// with every block put back as a `Dialogue` line under it, parsed once as the +/// `.ass` file it came from. +fn ass_cues(track: &crate::demux::MkvSubtitle) -> Result, String> { + let mut doc = String::from_utf8_lossy(&track.private).into_owned(); + if !doc.ends_with('\n') { + doc.push('\n'); + } + for cue in &track.cues { + let fields = String::from_utf8_lossy(&cue.payload); + // `ReadOrder,Layer,`: the two the + // block adds go, and the timing the block *is* takes their place. The + // field order is the one the header's `Format:` line declares, which + // is the order a demuxer strips them out of. + let mut rest = fields.trim_end().splitn(3, ','); + let (_read_order, layer, rest) = match (rest.next(), rest.next(), rest.next()) { + (Some(r), Some(l), Some(t)) => (r, l, t), + _ => continue, + }; + doc.push_str(&format!( + "Dialogue: {layer},{},{},{rest}\n", + timestamp(cue.start_us), + timestamp(end_of(track, cue)) + )); + } + let parsed = oxideav_ass::parse(doc.as_bytes()).map_err(|e| e.to_string())?; + // The timings above are centiseconds, which is all an ASS line can say; + // the blocks are microseconds. So the text comes from the parse and the + // timing from the block -- unless a line was dropped as unparsable, when + // the pairing is no longer sound and the parse answers for both. + let exact = parsed.cues.len() == track.cues.len(); + Ok(parsed + .cues + .iter() + .enumerate() + .map(|(i, c)| Cue { + start_us: if exact { + track.cues[i].start_us + } else { + c.start_us + }, + end_us: if exact { + end_of(track, &track.cues[i]) + } else { + c.end_us + }, + text: plain_text(&c.segments), + }) + .collect()) +} + +/// Microseconds as ASS writes a time: `H:MM:SS.cc`. +fn timestamp(us: i64) -> String { + let cs = (us.max(0) + 5_000) / 10_000; + format!( + "{}:{:02}:{:02}.{:02}", + cs / 360_000, + cs / 6_000 % 60, + cs / 100 % 60, + cs % 100 + ) +} + +/// A standalone subtitle file, by extension: the formats this engine reads at +/// all. Anything else is refused by name, as an unknown media file is. +fn parse_file(path: &Path) -> crate::Result> { + let ext = path + .extension() + .map(|e| e.to_string_lossy().to_ascii_lowercase()) + .unwrap_or_default(); + // The extension before the read: a `.txt` is refused for what it is, not + // for whether it happens to be there. + type Parse = fn(&[u8]) -> oxideav_core::Result; + let parse: Parse = match ext.as_str() { + "srt" => oxideav_subtitle::srt::parse, + "vtt" | "webvtt" => oxideav_subtitle::webvtt::parse, + "ass" | "ssa" => oxideav_ass::parse, + other => { + return Err(format!( + "{other:?} is not a subtitle format this reads — .srt, .vtt, .ass and .ssa are" + ) + .into()); + } + }; + let track = parse(&std::fs::read(path)?); + let track = track.map_err(|e| format!("{}: {e}", path.display()))?; + Ok(track + .cues + .iter() + .map(|c| Cue { + start_us: c.start_us, + end_us: c.end_us, + text: plain_text(&c.segments), + }) + .collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ass_timestamps_are_written_the_way_ass_reads_them() { + assert_eq!(timestamp(0), "0:00:00.00"); + assert_eq!(timestamp(500_000), "0:00:00.50"); + assert_eq!(timestamp(3_250_000), "0:00:03.25"); + // An hour, a minute and a second, and a negative time is not one. + assert_eq!(timestamp(3_661_000_000), "1:01:01.00"); + assert_eq!(timestamp(-1), "0:00:00.00"); + } + + #[test] + fn srt_markup_is_resolved_not_carried() { + assert_eq!(srt_body("tilted and plain"), "tilted and plain"); + assert_eq!(srt_body("two\nlines\n"), "two\nlines"); + } + + #[test] + fn an_unknown_extension_is_refused_by_name_and_a_missing_file_is_kept() { + let err = parse_file(Path::new("/nonexistent/notes.txt")) + .unwrap_err() + .to_string(); + assert!(err.contains("txt"), "{err}"); + // ...and a `.srt` that is not there comes back as a track that says so + // rather than as no track at all, so a re-save does not lose it. + let gone = external(Path::new("/nonexistent/subs.srt")); + assert!(gone.refused.is_some()); + assert_eq!(gone.label, "subs.srt"); + } +} diff --git a/crates/engine/src/waveform.rs b/crates/engine/src/waveform.rs index 5c23923..14e06aa 100644 --- a/crates/engine/src/waveform.rs +++ b/crates/engine/src/waveform.rs @@ -15,10 +15,18 @@ use crate::AudioSession; /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always /// straddles zero, so silence draws as a flat line. /// -/// Decoding the whole file runs at ~1700x realtime, but it is still linear in -/// source length: callers cache the result per source *and stream* — two -/// streams of one file are two different envelopes, and a cache keyed on the -/// path alone would draw the first one under both. +/// Decoding the whole file runs at ~1700x realtime for an mp4's stereo AAC and +/// ~50x for a film's 5.1 AAC in an mkv (six channels through `rusty_aac`), but +/// it is linear in source length either way: callers cache the result per source +/// *and stream* — two streams of one file are two different envelopes, and a +/// cache keyed on the path alone would draw the first one under both. Memory is +/// flat in it, though: chunks are consumed as they arrive and only the buckets +/// are kept (2 hours at 10/s is 70k pairs). +/// +/// ponytail: that 50x is 2.4 minutes of background decode for a two-hour film +/// before its lane has a waveform. The upgrade path is decoding the source in +/// segments on several threads — `open_multi_streams` already takes a window per +/// call — and stitching the buckets, which the fold to one envelope makes safe. pub fn peaks( path: impl AsRef, stream: usize, @@ -141,6 +149,33 @@ mod tests { assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}"); } + /// The shape the ask came from: a film in an mkv with a 5.1 AAC track, + /// which no symphonia decoder takes (`aac: aac too complex`) and which + /// therefore reaches the lane through `rusty_aac` and the stereo fold. A + /// clip of one draws a waveform like any other -- an envelope that is not + /// flat -- rather than the empty band a silent file makes. + #[test] + fn a_five_one_aac_mkv_draws_an_envelope() { + let peaks = peaks(asset("test_hevc10.mkv"), 0, BPS) + .expect("the 5.1 AAC track decodes") + .expect("test_hevc10.mkv has an audio track"); + let want = 2 * BPS as usize; // 2 s of tones + assert!( + peaks.len().abs_diff(want) <= 2, + "{} buckets, want {want} +/-2", + peaks.len() + ); + // Six tones, one per channel, folded to stereo: every bucket carries + // signal, and a decode that came out silent (or clipped to a rail) is + // exactly what this refuses. + for (i, &(lo, hi)) in peaks.iter().enumerate() { + assert!( + (0.02..2.0).contains(&(hi - lo)), + "bucket {i} is ({lo}, {hi})" + ); + } + } + #[test] fn video_only_source_has_no_peaks() { assert!( diff --git a/crates/engine/tests/data/test_subs.ass b/crates/engine/tests/data/test_subs.ass new file mode 100644 index 0000000..d6c0c93 --- /dev/null +++ b/crates/engine/tests/data/test_subs.ass @@ -0,0 +1,14 @@ +[Script Info] +ScriptType: v4.00+ +PlayResX: 384 +PlayResY: 288 + +[V4+ Styles] +Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding +Style: Default,Arial,16,&Hffffff,&Hffffff,&H0,&H0,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,1 + +[Events] +Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text +Dialogue: 0,0:00:00.50,0:00:01.50,Default,,0,0,0,,first line +Dialogue: 0,0:00:02.00,0:00:03.25,Default,,0,0,0,,second line\Nwith a break +Dialogue: 0,0:00:04.00,0:00:04.75,Default,,0,0,0,,{\i1}third{\i0} line diff --git a/crates/engine/tests/data/test_subs.srt b/crates/engine/tests/data/test_subs.srt new file mode 100644 index 0000000..f75aabc --- /dev/null +++ b/crates/engine/tests/data/test_subs.srt @@ -0,0 +1,12 @@ +1 +00:00:00,500 --> 00:00:01,500 +first line + +2 +00:00:02,000 --> 00:00:03,250 +second line +with a break + +3 +00:00:04,000 --> 00:00:04,750 +third line diff --git a/crates/engine/tests/h264_mkv.rs b/crates/engine/tests/h264_mkv.rs new file mode 100644 index 0000000..098a888 --- /dev/null +++ b/crates/engine/tests/h264_mkv.rs @@ -0,0 +1,149 @@ +//! H.264 in Matroska: the codec this project has always decoded, in the +//! container that used to refuse it by name. Nothing new decodes here -- the +//! demuxer reframes the `avcC`-prefixed blocks to Annex-B and hands them to the +//! same dispatch an mp4's samples go to -- so the whole file runs with nothing +//! installed, on `rusty_h264` if the plugin is absent. +//! +//! ```text +//! cargo test -p engine --test h264_mkv +//! ``` + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use engine::demux::{Codec, Demuxer}; +use engine::{AudioSession, PlaybackSession}; + +/// 1280x720@30, 2 s, keyframes 30 apart -- see `scripts/gen_fixtures.sh`. +const FRAMES: u32 = 60; +const KEYFRAME: u32 = 30; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// The Annex-B NAL types of an access unit, in order: `nal_unit_type` is the low +/// 5 bits of the byte after each start code. +fn nal_types(au: &[u8]) -> Vec { + au.windows(4) + .enumerate() + .filter(|(_, w)| *w == [0, 0, 0, 1]) + .filter_map(|(i, _)| au.get(i + 4).map(|b| b & 0x1f)) + .collect() +} + +/// The container half, and the refusal this slice exists to delete: the file +/// opens, and it says H.264 rather than "not supported". +#[test] +fn the_demuxer_reports_an_h264_track_in_matroska() { + let (meta, _) = Demuxer::open(&asset("test_h264.mkv")).expect("open test_h264.mkv"); + assert_eq!(meta.codec, Codec::H264); + assert_eq!((meta.width, meta.height), (1280, 720)); + assert!( + (meta.frame_rate - 30.0).abs() < 1e-6, + "DefaultDuration must not truncate: {}", + meta.frame_rate + ); + assert_eq!(meta.frame_count, FRAMES); + + // The invariant, stated as an assert: the other containers and codecs read + // back exactly as they did before this arm existed. + let (av1, _) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv"); + assert_eq!(av1.codec, Codec::Av1); + assert_eq!(av1.frame_count, FRAMES); + let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4"); + assert_eq!(h264.codec, Codec::H264); +} + +/// Matroska stores H.264 in `avcC` framing -- length prefixes, and the SPS/PPS +/// out of band in `CodecPrivate` -- so an access unit is only decodable if both +/// were handled: reframed to Annex-B, parameter sets ahead of every keyframe. +#[test] +fn keyframes_carry_the_parameter_sets_and_every_block_comes_back() { + let (_, mut demuxer) = Demuxer::open(&asset("test_h264.mkv")).expect("open test_h264.mkv"); + let first = demuxer + .next_access_unit() + .expect("read") + .expect("a first access unit"); + assert_eq!(first[..4], [0, 0, 0, 1], "Annex-B, not a length prefix"); + let types = nal_types(&first); + assert_eq!( + &types[..2], + &[7, 8], + "the keyframe leads with SPS and PPS: {types:?}" + ); + assert!(types.contains(&5), "and then the IDR picture: {types:?}"); + + let second = demuxer.next_access_unit().expect("read").expect("a unit"); + let types = nal_types(&second); + assert!( + !types.contains(&7) && types.contains(&1), + "a non-keyframe is a plain slice: {types:?}" + ); + + let mut count = 2; + while demuxer.next_access_unit().expect("read").is_some() { + count += 1; + } + assert_eq!(count, FRAMES, "every block came back out"); + + // Keyed every 30 frames, and a seek may only land on one. + assert_eq!( + demuxer.seek_to_sync_at_or_before(KEYFRAME + 15), + i64::from(KEYFRAME) + ); + assert_eq!(demuxer.seek_to_sync_at_or_before(KEYFRAME - 1), 0); + // The unit after a seek carries the parameter sets too: a decoder restarted + // mid-file needs them exactly as much as one started at frame 0. + let after = demuxer.next_access_unit().expect("read").expect("a unit"); + assert_eq!(&nal_types(&after)[..2], &[7, 8]); +} + +/// The user-facing end of it, through the very call the window's open door makes +/// (`app/src/main.rs:2242`): the file becomes a timeline and that timeline shows +/// a picture. No plugin is required -- H.264 is the one codec with a software +/// decoder here -- so this is what says the reframed access units are really +/// decodable and not just well-shaped. +#[test] +fn opening_an_h264_matroska_file_shows_frames() { + let mut session = PlaybackSession::open(asset("test_h264.mkv")).expect("open test_h264.mkv"); + assert_eq!(session.meta().codec, Codec::H264); + assert_eq!(session.meta().frame_count, FRAMES); + + // The decoder is a thread behind the door, so a frame is waited for exactly + // as the window's own pump waits for one. + let deadline = Instant::now() + Duration::from_secs(60); + let frame = loop { + if let Some(frame) = session.try_frame() { + break frame; + } + assert!(Instant::now() < deadline, "no frame in 60 s"); + std::thread::sleep(Duration::from_millis(10)); + }; + assert_eq!((frame.width, frame.height), (1280, 720)); + // A picture, not a flat surface: a decoder handed garbage would satisfy + // every count above. + assert!( + frame.bgra.chunks_exact(4).any(|px| px != &frame.bgra[..4]), + "the first frame is a single colour -- no picture was decoded" + ); +} + +/// The sound comes with it: a Matroska file's audio is read whatever its picture +/// is coded with, so nothing is left for the "cannot be decoded" notice to name. +#[test] +fn the_matroska_audio_path_takes_this_file_too() { + let stereo = AudioSession::probe(asset("test_h264.mkv"), 0) + .expect("probe") + .expect("the fixture has an AAC track"); + assert_eq!((stereo.sample_rate, stereo.channels), (44_100, 2)); + // ...and it really opens, which is what says the sound plays rather than + // merely being described. + assert!( + AudioSession::open(asset("test_h264.mkv")) + .expect("open") + .is_some() + ); +} diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index 314f8e9..d393d80 100644 --- a/crates/engine/tests/saveload.rs +++ b/crates/engine/tests/saveload.rs @@ -209,7 +209,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() { let v2 = dir.join("new.edith"); loaded.save_project(&v2).expect("save"); let text = std::fs::read_to_string(&v2).expect("read back"); - assert!(text.starts_with("edith 9\n"), "{text}"); + assert!(text.starts_with("edith 10\n"), "{text}"); assert!( text.contains("\nresolution 1280 720\n"), "a project with no resolution of its own is saved at source 0's: {text}" @@ -297,7 +297,7 @@ fn a_version_4_project_holds_more_than_two_lanes() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\ video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n", "a four-lane project is written as it was read, three versions on" @@ -327,7 +327,7 @@ fn a_version_5_project_carries_per_clip_equalizers() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 12000.0:6.25:0.5:hs\n\ video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\ @@ -362,7 +362,7 @@ fn a_version_6_project_carries_per_clip_colours() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ + "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ color 0.1:1.2:0.9:-0.3\n\ color -0.25:1.0:0.0:0.5\n\ @@ -412,7 +412,7 @@ fn a_version_7_project_carries_a_resolution_and_fit_policies() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 9\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\ + "edith 10\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\ video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\ audio 1 0 0 60 0 - - - fit 1000\n", "a v7 project is written back as the v8 it now is: the same clips, each \ @@ -670,7 +670,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() { for (text, want) in [ ( - "edith 10\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", + "edith 11\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", "line 1", ), // An eq index the table does not hold, and a band shape there is none. @@ -806,7 +806,7 @@ fn a_song_only_project_comes_back_at_the_rate_it_names() { let path = dir.join("song.edith"); std::fs::write( &path, - "edith 9\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\ + "edith 10\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\ video 1\naudio 1 0 0 24 0 - - - fit 1000\n", ) .expect("write a v9 song project"); diff --git a/crates/engine/tests/silence.rs b/crates/engine/tests/silence.rs index 735a2d6..2175308 100644 --- a/crates/engine/tests/silence.rs +++ b/crates/engine/tests/silence.rs @@ -365,6 +365,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() { &sources, &lanes, &p.lane_gains(), + p.subtitles(), &eq, &color, (1920, 1080), @@ -375,7 +376,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() { .expect("save"); let text = std::fs::read_to_string(&file).expect("read it back"); assert!( - text.starts_with("edith 9"), + text.starts_with("edith 10"), "{:?}", &text[..16.min(text.len())] ); diff --git a/crates/engine/tests/subtitles.rs b/crates/engine/tests/subtitles.rs new file mode 100644 index 0000000..e10bea5 --- /dev/null +++ b/crates/engine/tests/subtitles.rs @@ -0,0 +1,237 @@ +//! Subtitles: the cues of a file beside the media and of a track inside it are +//! the same cues, a project keeps them across a save, and the formats that are +//! pictures rather than text are listed and skipped by name rather than +//! silently dropped. +//! +//! ```text +//! cargo test -p engine --release --test subtitles -- --nocapture +//! ``` + +use std::path::PathBuf; + +use engine::subtitle::{self, Cue}; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn data(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/data") + .join(name) +} + +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ve_subs_{name}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + std::fs::canonicalize(&dir).expect("canonical scratch dir") +} + +/// The three cues both hand-written fixtures hold, with the markup resolved: +/// the italics of the `.ass` third line are not text, and the `\N` of its +/// second one is a line break like the `.srt`'s. +fn expected() -> Vec { + vec![ + Cue { + start_us: 500_000, + end_us: 1_500_000, + text: "first line".into(), + }, + Cue { + start_us: 2_000_000, + end_us: 3_250_000, + text: "second line\nwith a break".into(), + }, + Cue { + start_us: 4_000_000, + end_us: 4_750_000, + text: "third line".into(), + }, + ] +} + +/// The whole of the parse half: four routes to the same three cues -- an +/// `.srt`, an `.ass` with override tags in it, and the two tracks of the +/// Matroska file both were muxed into, whose timing lives on the block and +/// whose text lives in it. +#[test] +fn a_file_beside_the_media_and_a_track_inside_it_read_the_same() { + let srt = subtitle::open(&data("test_subs.srt"), None); + assert_eq!(srt.refused, None, "the .srt parses"); + assert_eq!(srt.cues, expected()); + assert_eq!(srt.label, "test_subs.srt"); + + let ass = subtitle::open(&data("test_subs.ass"), None); + assert_eq!(ass.refused, None, "the .ass parses"); + assert_eq!(ass.cues, expected(), "the override tags are resolved"); + + let embedded = subtitle::of_matroska(&asset("test_subs.mkv")).expect("the mkv is walked"); + let text: Vec<_> = embedded.iter().map(|t| (&t.label, &t.cues)).collect(); + assert_eq!(embedded.len(), 2, "two subtitle tracks: {text:?}"); + for track in &embedded { + assert_eq!(track.refused, None, "{} parses", track.label); + assert_eq!( + track.cues, + expected(), + "{} holds the same cues", + track.label + ); + } + // ...and each is named by what the file says about it, so a list has + // something to show but the track number. + assert_eq!(embedded[0].label, "eng"); + assert_eq!(embedded[1].label, "fra — Signs"); + assert_eq!(embedded[0].track, Some(2)); + assert_eq!(embedded[1].track, Some(3)); + + // The one door a saved line comes back through reaches the same track. + let one = subtitle::open(&asset("test_subs.mkv"), Some(3)); + assert_eq!(one.cues, expected()); + // A track number the file does not have is refused by name, not an error: + // the project it was saved in still opens. + let gone = subtitle::open(&asset("test_subs.mkv"), Some(9)); + assert!( + gone.refused.as_deref().unwrap_or_default().contains("9"), + "{:?}", + gone.refused + ); +} + +/// A subtitle track this cannot read is a row that says why -- never an error +/// that takes the whole file down with it. The repro is a BluRay remux +/// carrying four PGS tracks: opening it lists four subtitles it cannot draw, +/// and the picture and the sound come up regardless. +/// +/// Written here rather than muxed by the fixture script because ffmpeg cannot +/// encode text subtitles into pictures; the bytes below are the `Tracks` +/// element of such a file and nothing else. +#[test] +fn bitmap_subtitles_are_listed_and_skipped_by_name() { + let dir = scratch("pgs"); + let file = dir.join("remux.mkv"); + std::fs::write(&file, pgs_matroska()).expect("write the hand-made mkv"); + + let tracks = subtitle::of_matroska(&file).expect("the walk does not fail over them"); + assert_eq!(tracks.len(), 4, "every PGS track is listed"); + for (i, track) in tracks.iter().enumerate() { + assert_eq!(track.track, Some(i as u64 + 1)); + assert_eq!(track.cues, Vec::new(), "no cues to have"); + let why = track.refused.clone().unwrap_or_default(); + assert!( + why.contains("S_HDMV/PGS") && why.contains("pictures"), + "the refusal names the codec: {why:?}" + ); + } + // The language is what a list shows, and `und` is what the spec says a + // track that names none is. + assert_eq!(tracks[0].label, "eng"); + assert_eq!(tracks[3].label, "und"); +} + +/// A saved project comes back with its subtitles: the `.edith` names the file +/// and the track, and the cues are read out of them again on the way in. The +/// engine's own door for both halves -- import, save, open -- since that is +/// what a front-end will drive. +#[test] +fn a_project_keeps_its_subtitles_across_a_save() { + let dir = scratch("save"); + let media = dir.join("test_av.mp4"); + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); + // Beside the media, which is where a subtitle file lives: the project then + // writes it relative, and the whole folder stays movable. + let subs = dir.join("test_subs.srt"); + std::fs::copy(data("test_subs.srt"), &subs).expect("copy the subtitle fixture"); + + let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); + session.set_gain(0.0); // silent like the rest of the suites + assert_eq!(session.subtitles().len(), 0, "nothing to start with"); + assert_eq!( + session.import_subtitles(&subs).expect("the .srt imports"), + 1 + ); + // The same file twice is the same subtitles, not two rows of them. + assert_eq!(session.import_subtitles(&subs).expect("no error"), 0); + assert_eq!(session.subtitles()[0].cues, expected()); + + let project = dir.join("cut.edith"); + session.save_project(&project).expect("save"); + let text = std::fs::read_to_string(&project).expect("read the project back"); + assert!(text.starts_with("edith 10\n"), "{text}"); + assert!( + text.contains("\nsubtitle - test_subs.srt\n"), + "the reference is written relative, and no cue is: {text}" + ); + + let back = engine::PlaybackSession::open_project(&project).expect("open the project"); + assert_eq!(back.subtitles().len(), 1); + assert_eq!(back.subtitles()[0].cues, expected()); + assert_eq!(back.subtitles()[0].track, None); + drop(back); + + // A subtitle file that has gone missing is listed, refused by name, and + // written out again: the project still opens and the row is not lost. + std::fs::remove_file(&subs).expect("take the subtitles away"); + let gone = engine::PlaybackSession::open_project(&project).expect("the project still opens"); + assert_eq!(gone.subtitles().len(), 1); + assert!(gone.subtitles()[0].refused.is_some()); + let again = dir.join("cut2.edith"); + gone.save_project(&again).expect("save again"); + assert!( + std::fs::read_to_string(&again) + .expect("read") + .contains("\nsubtitle - test_subs.srt\n"), + "a re-save keeps the row" + ); +} + +/// A refusal a front-end shows at the moment of the import, rather than a row +/// nobody asked for: a file that is not a subtitle format at all. +#[test] +fn importing_something_that_is_not_a_subtitle_says_so() { + let dir = scratch("refuse"); + let media = dir.join("test_av.mp4"); + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); + let notes = dir.join("notes.txt"); + std::fs::write(¬es, "not a subtitle").expect("write"); + + let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); + session.set_gain(0.0); + let err = session + .import_subtitles(¬es) + .expect_err("a .txt is not a subtitle") + .to_string(); + assert!(err.contains("txt"), "{err}"); + assert_eq!(session.subtitles().len(), 0, "and nothing was added"); +} + +/// The `Tracks` element of a Matroska file carrying four PGS subtitle tracks +/// and nothing else -- enough for the walk, which stops at the first `Cluster` +/// and there is none. +fn pgs_matroska() -> Vec { + /// An EBML element: its id as it is written in the file, then an 8-byte + /// length, which is always a legal encoding of one. + fn element(id: &[u8], body: &[u8]) -> Vec { + let mut out = id.to_vec(); + let mut len = (body.len() as u64).to_be_bytes(); + len[0] |= 0x01; // the 8-byte length marker + out.extend_from_slice(&len); + out.extend_from_slice(body); + out + } + let mut tracks = Vec::new(); + for (number, language) in [(1u8, "eng"), (2, "fra"), (3, "spa"), (4, "")] { + let mut entry = Vec::new(); + entry.extend(element(&[0xD7], &[number])); // TrackNumber + entry.extend(element(&[0x83], &[0x11])); // TrackType: subtitle + entry.extend(element(&[0x86], b"S_HDMV/PGS")); // CodecID + if !language.is_empty() { + entry.extend(element(&[0x22, 0xB5, 0x9C], language.as_bytes())); + } + tracks.extend(element(&[0xAE], &entry)); // TrackEntry + } + let segment = element(&[0x16, 0x54, 0xAE, 0x6B], &tracks); // Tracks + element(&[0x18, 0x53, 0x80, 0x67], &segment) // Segment +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index a09fec4..e849eba 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -113,6 +113,34 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_av1.mkv +# H.264 in Matroska: the same stream the mp4 fixtures carry, in the container +# that used to refuse it. Baseline profile so `rusty_h264` reads it with nothing +# installed, `-g 30` for the second keyframe the sync index is checked against, +# and the AAC track for the sound an mkv's audio path reads back. +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ + -f lavfi -i "sine=frequency=440:duration=2" \ + -f lavfi -i "sine=frequency=880:duration=2" \ + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ + -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ + -c:a aac -b:a 128k assets/test_h264.mkv +# Subtitles in Matroska: the two text codecs a film carries, muxed out of the +# hand-written files the tests also parse standalone +# (`crates/engine/tests/data/`), so the embedded cues and the external ones can +# be compared to each other and both to the source. Track 2 is S_TEXT/UTF8 and +# track 3 is S_TEXT/ASS -- the same three cues, one of them with markup, which +# is what makes "the markup is resolved, not carried" measurable. +# +# No bitmap track here: ffmpeg cannot encode text subtitles into pictures, so +# the PGS refusal is checked against a Matroska file the test writes itself +# (`crates/engine/tests/subtitles.rs`). +ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=5 \ + -i crates/engine/tests/data/test_subs.srt \ + -i crates/engine/tests/data/test_subs.ass \ + -map 0:v -map 1:0 -map 2:0 \ + -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ + -c:s:0 srt -metadata:s:s:0 language=eng \ + -c:s:1 ass -metadata:s:s:1 language=fra -metadata:s:s:1 title=Signs \ + assets/test_subs.mkv # HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as # test_hevc.mp4 so the tests measure the container and nothing else, `-g 30` for # the same reason test_av1.mkv has it (a second keyframe to seek to), and the @@ -144,16 +172,18 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ # **5.1 E-AC-3** for Annex E -- the shape a remux has, and the one that must # come down to stereo through the same A/52 7.8 downmix the mp4 path uses. # 48 kHz both, which is the only rate E-AC-3 is written at in practice. Small -# picture on purpose: these two are about the sound. +# H.264 picture on purpose: these two are about the sound, and the software +# decoder reads that one, so an audio test needs no VA-API plugin to open a +# session on them. ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ -f lavfi -i "sine=frequency=880:duration=2:sample_rate=48000" \ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a]" \ - -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ + -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ -c:a ac3 -b:a 192k assets/test_ac3.mkv ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ - -map 0:v -map 1:a -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ + -map 0:v -map 1:a -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ -ac 6 -c:a eac3 -b:a 384k assets/test_eac3.mkv # Sync fixture: one flash and one beep, at the same instant. Black picture with # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that diff --git a/vendor/rusty_aac/src/dsp.rs b/vendor/rusty_aac/src/dsp.rs index b35cd4d..b22a28a 100644 --- a/vendor/rusty_aac/src/dsp.rs +++ b/vendor/rusty_aac/src/dsp.rs @@ -35,20 +35,45 @@ pub fn imdct(spec: &[f32]) -> Vec { if n == 0 { return Vec::new(); } - // LOCAL PATCH: the AAC block sizes take the cached cosine matrix below -- - // the same numbers, looked up instead of called for. - if let Some(matrix) = imdct_matrix(n) { - let mut out = vec![0f32; n]; - for (i, o) in out.iter_mut().enumerate() { - let row = &matrix[i * half..(i + 1) * half]; - let mut acc = 0f32; - for (k, &s) in spec.iter().enumerate() { - acc += s * row[k]; + // LOCAL PATCH: O(N log N) instead of the O(N^2) sum below. With `n0 = N/4 + + // 1/2` the kernel is exactly a DCT-IV of length L = N/2 read at `j = i + + // L/2` -- the same DCT-IV [`mdct_fast`] already runs as one N/4-point FFT -- + // so the transform is that one call plus a sign-and-mirror walk (DCT-IV is + // even about `j = -1/2`, odd about `j = L - 1/2`, and negates every 2L). + if half >= 2 && half.is_power_of_two() { + let owned; + let tw = match mdct_twiddles(n) { + Some(t) => t, + None => { + owned = MdctTwiddles::build(n); + &owned } - *o = acc; - } - return out; + }; + let d = dct4(half, |k| spec[k] as f64, tw); + let scale = 2.0 / n as f64; + let (l, l2) = (half, half / 2); + return (0..n) + .map(|i| { + let j = i + l2; + let v = if j < l { + d[j] + } else if j < 2 * l { + -d[2 * l - 1 - j] + } else { + -d[j - 2 * l] + }; + (scale * v) as f32 + }) + .collect(); } + imdct_direct(spec) +} + +/// The direct O(N^2) transform [`imdct`] is defined as, kept as the oracle its +/// test measures against and as the path for sizes the fast one does not take. +fn imdct_direct(spec: &[f32]) -> Vec { + let half = spec.len(); + let n = half * 2; let n0 = (n / 2 + 1) as f64 / 2.0; // N/4 + 1/2 let scale = 2.0 / n as f64; let w = 2.0 * PI / n as f64; @@ -64,36 +89,6 @@ pub fn imdct(spec: &[f32]) -> Vec { out } -/// LOCAL PATCH: `(2/N)·cos((2π/N)(i+n0)(k+½))` for every `(i, k)` of one block -/// size, built once. The direct transform above spends its whole time in `cos` -/// -- ~63 ms for one 1024-coefficient channel, three times slower than real -/// time, which is what made a 5.1 stream unplayable. The matrix is 8 MB for the -/// long block and 128 kB for the short one, and each output sample becomes a -/// dot product a compiler can vectorise. -fn imdct_matrix(n: usize) -> Option<&'static [f32]> { - static LONG: OnceLock> = OnceLock::new(); - static SHORT: OnceLock> = OnceLock::new(); - fn build(n: usize) -> Vec { - let half = n / 2; - let n0 = (n / 2 + 1) as f64 / 2.0; - let scale = 2.0 / n as f64; - let w = 2.0 * PI / n as f64; - let mut m = vec![0f32; n * half]; - for i in 0..n { - let a = w * (i as f64 + n0); - for k in 0..half { - m[i * half + k] = (scale * (a * (k as f64 + 0.5)).cos()) as f32; - } - } - m - } - match n { - 2048 => Some(LONG.get_or_init(|| build(2048))), - 256 => Some(SHORT.get_or_init(|| build(256))), - _ => None, - } -} - /// Forward MDCT — the analysis transform paired with [`imdct`]. Used to validate /// the IMDCT via perfect reconstruction (and useful for an eventual encoder). /// `N` time samples → `N/2` coefficients. @@ -236,7 +231,7 @@ pub fn mdct_fast(x: &[f32]) -> Vec { if n < 4 { return mdct(x); // tiny sizes: fall back to the direct oracle } - let (l, m) = (n / 2, n / 4); + let l = n / 2; let owned; let tw = match mdct_twiddles(n) { Some(t) => t, @@ -254,20 +249,32 @@ pub fn mdct_fast(x: &[f32]) -> Vec { (x[mm - l2] as f64) - (x[l32 - 1 - mm] as f64) } }; - // Pack + pre-rotate into M complex: v[p] = (y[2p] + i·y[L-1-2p])·e^{-iπ(4p+1)/4L}. + // Output scaled ×2: that factor is [`mdct`]'s, not the DCT-IV's. + dct4(l, fold, tw).iter().map(|&v| (2.0 * v) as f32).collect() +} + +/// DCT-IV of length `l`: `out[k] = Σ_j y(j)·cos((π/L)(j+½)(k+½))`, as one +/// `L/2`-point complex FFT — pack + pre-rotate `v[p] = (y[2p] + i·y[L-1-2p]) +/// ·e^{-iπ(4p+1)/4L}`, transform, post-rotate `W = V·e^{-iπp/L}`, and read +/// `out[2p] = Re(W)`, `out[L-1-2p] = -Im(W)`. +/// +/// `y` is a closure because the forward MDCT folds its input on the fly and the +/// inverse reads a spectrum straight out; `tw` is the block-size table both +/// directions share ([`MdctTwiddles`], built for `N = 2L`). +fn dct4(l: usize, y: impl Fn(usize) -> f64, tw: &MdctTwiddles) -> Vec { + let m = l / 2; let (mut re, mut im) = (vec![0f64; m], vec![0f64; m]); for p in 0..m { - let (yr, yi) = (fold(2 * p), fold(l - 1 - 2 * p)); + let (yr, yi) = (y(2 * p), y(l - 1 - 2 * p)); re[p] = yr * tw.pre_c[p] + yi * tw.pre_s[p]; im[p] = yi * tw.pre_c[p] - yr * tw.pre_s[p]; } fft(&mut re, &mut im, &tw.fft_c, &tw.fft_s); - // Post-rotate W = V·e^{-iπp/L}; X[2p]=Re(W), X[L-1-2p]=-Im(W); output scaled ×2. - let mut out = vec![0f32; l]; + let mut out = vec![0f64; l]; for p in 0..m { let (vr, vi) = (re[p], im[p]); - out[2 * p] = (2.0 * (vr * tw.post_c[p] + vi * tw.post_s[p])) as f32; - out[l - 1 - 2 * p] = (2.0 * (vr * tw.post_s[p] - vi * tw.post_c[p])) as f32; + out[2 * p] = vr * tw.post_c[p] + vi * tw.post_s[p]; + out[l - 1 - 2 * p] = vr * tw.post_s[p] - vi * tw.post_c[p]; } out } @@ -346,6 +353,37 @@ mod tests { } } + /// LOCAL PATCH: the fast IMDCT against the direct sum it replaced, at both + /// AAC block sizes plus one the twiddle cache does not hold (512, built on + /// the spot) and one the fast path declines (a 3-coefficient spectrum), on + /// raw and decoder-scale (×32768) input. Every output sample, because the + /// index remap is where a DCT-IV-based inverse goes wrong: a sign or a + /// mirror off by one is silent in the first half and audible in the second. + #[test] + fn imdct_matches_direct() { + for &half in &[3usize, 128, 256, 1024] { + for &scale in &[1.0f32, 32768.0] { + let spec: Vec = (0..half) + .map(|k| { + scale + * (0.4 * (k as f64 * 0.037).sin() + 0.25 * (k as f64 * 0.011).cos()) + as f32 + }) + .collect(); + let (a, b) = (imdct_direct(&spec), imdct(&spec)); + let tol = 2e-4 * scale.max(1.0); + for i in 0..half * 2 { + assert!( + (a[i] - b[i]).abs() < tol, + "half={half} scale={scale} i={i}: {} vs {}", + a[i], + b[i] + ); + } + } + } + } + #[test] fn dequant_matches_spec_curve() { assert_eq!(dequant(0), 0.0);