From b05a649de50bbcb500367f25e33e70784c1b6807 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 23:19:47 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(app,engine):=20pay=20debts?= =?UTF-8?q?=20=E2=80=94=20audio-only=20fallbacks,=20panic-proof=20proxy,?= =?UTF-8?q?=20.part=20sweep?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Twelve debts paid in one batch: - engine: NoVideoTrack fallback at every video door — open_stream, open_project scaffold, and import() now route a video-extension file whose header holds no picture to the audio-only path instead of refusing (argv open, saved-project reload, and library import). - engine: proxy/export worker wrapped in catch_unwind — a decoder panic settles the shared slot with Err instead of stranding Making/Cancelling. - vendor/cros-codecs: AV1 setup_shear multiplies checked — malformed warp params are a parse error, not a process abort (live-proven on an AV1 film: clean PROXY FAILED notice, slot released, app alive). - engine: startup sweep of orphan proxy .part files. - app: Player::has_video probe cache — lane_refuses gates drops on the probed kind, not the extension; Silences hidden on soundless clips; audio import toast names rate/channels/length; stale no-session proxy label cleared. - tests: audio-only mp4 fixture + gen_fixtures.sh line, 2 engine NoVideoTrack tests, toast/lane/view cases (246 bin + 14 audio_files). Harness-proven this batch (runs 20260826-2306..2315): split-at-playhead with undo, lane-remove mouse door, fade-out drag, argv audio-only open, AV1 proxy clean failure. --- crates/app/src/main.rs | 14 +++++ crates/app/src/oracle.rs | 7 +++ crates/app/src/player/actions.rs | 12 ++++ crates/app/src/player/export.rs | 45 +++++++++++++++ crates/app/src/player/library.rs | 26 +++++++-- crates/app/src/player/timeline_edit.rs | 2 +- crates/app/src/subs.rs | 22 ++++++++ crates/app/src/tests/editing.rs | 16 ++++++ crates/app/src/tests/media.rs | 17 +++++- crates/app/src/tests/view.rs | 24 +++++--- crates/app/src/timeline_math.rs | 8 ++- crates/engine/src/export.rs | 22 ++++++++ crates/engine/src/playback.rs | 66 ++++++++++++++++++---- crates/engine/src/proxy.rs | 58 +++++++++++++++++++ crates/engine/tests/audio_files.rs | 33 +++++++++++ scripts/gen_fixtures.sh | 6 ++ vendor/cros-codecs/src/codec/av1/parser.rs | 34 +++++++++-- 17 files changed, 381 insertions(+), 31 deletions(-) diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 7552995..557ae42 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -255,6 +255,14 @@ struct Player { /// `None` is a file with no picture to report (every source that is not an /// image, and one whose header would not read). sizes: HashMap>, + /// Whether a source's own header says it carries a picture at all, + /// probed once and kept: what [`Player::has_video`] reads for the lane a + /// drag may land on ([`timeline_math::lane_refuses`]). An extension can + /// lie -- a song muxed into an `.mp4` -- and only the header says the + /// truth (`engine::demux::NoVideoTrack`). Filled like `sizes`: presence + /// means "asked", and until the probe answers a file is read by its + /// extension, the same guess the ghost always made. + has_video: HashMap, /// Every frame of each source a decoder may be started from -- its sync /// points ([`engine::demux::sync_points`]), which are the frames a cut may /// be placed on for an export to *copy* the film instead of coding all of @@ -770,6 +778,11 @@ struct Player { mod tests; fn main() { + // What a killed editor left behind: `.part` proxies from an encode that + // never got to unlink its own half-written file. Run once, here, before + // anything in this process could claim one of its own -- every `.part` on + // disk at this instant belongs to nobody still running. + engine::proxy::sweep_stale_parts(); // A keymap file that cannot be read leaves the defaults in force, and takes // the notice slot ahead of an open or import refusal: it is about every key // the window has, and those refusals are on stderr either way. @@ -905,6 +918,7 @@ fn main() { thumbs: HashMap::new(), proxies: HashMap::new(), streams: HashMap::new(), + has_video: HashMap::new(), bitrates: HashMap::new(), sizes: HashMap::new(), syncs: HashMap::new(), diff --git a/crates/app/src/oracle.rs b/crates/app/src/oracle.rs index ca29d07..c1c3c77 100644 --- a/crates/app/src/oracle.rs +++ b/crates/app/src/oracle.rs @@ -61,6 +61,12 @@ pub(crate) struct Ctx { /// reach at all -- not the lane's business, because a still sits on a video /// lane exactly like a take whose sound is one lane down. pub(crate) image: bool, + /// The clip's source is known, from the probed stream table + /// ([`Player::streams`]), to carry no audio track at all -- a video shot + /// mute, not merely a video whose sound is quiet. `false` (the default) + /// covers both "has sound" and "not probed yet": a row nobody has asked + /// about is not one this hides a working action from. + pub(crate) no_sound: bool, pub(crate) playhead: u32, /// A timeline is open. pub(crate) timeline: bool, @@ -221,6 +227,7 @@ pub(crate) fn enable(action: ActionId, ctx: Ctx) -> Enable { // `unscannable` says after the fact, said before the row is drawn so // there is no row left to click. ActionId::Silence if ctx.image => Enable::Hidden("this clip is a still"), + ActionId::Silence if ctx.no_sound => Enable::Hidden("this clip has no sound"), // -- state: true of this clip now, and the next playhead click or the // next selection changes the answer. Splits this clip only from inside // it: at either edge there is nothing to split off -- and, on a speeded diff --git a/crates/app/src/player/actions.rs b/crates/app/src/player/actions.rs index 84cf61a..6f53aa1 100644 --- a/crates/app/src/player/actions.rs +++ b/crates/app/src/player/actions.rs @@ -370,6 +370,18 @@ impl Player { .get(clip.source) .is_some_and(|s| engine::is_image(&s.path)) }), + // The probed stream table again, this time asking the other + // question of it: an empty list is a silent file + // ([`Player::streams`]), and a clip cut from one has no sound to + // scan whatever lane it sits on -- said before the row is drawn + // rather than after the scan comes back empty + // ([`Player::start_silence_scan`]'s `Ok(None)` arm). + no_sound: clip.is_some_and(|(clip, _)| { + session + .sources() + .get(clip.source) + .is_some_and(|s| self.streams.get(&s.path).is_some_and(Vec::is_empty)) + }), playhead: frame_at(session.now(), self.fps), timeline: true, clipboard: !self.clipboard.is_empty(), diff --git a/crates/app/src/player/export.rs b/crates/app/src/player/export.rs index a978a92..db50050 100644 --- a/crates/app/src/player/export.rs +++ b/crates/app/src/player/export.rs @@ -4,6 +4,17 @@ use crate::*; impl Player { + /// What [`timeline_math::lane_refuses`] asks to decide a video lane's + /// refusal: the probed answer if `cache_media` has one yet, and the + /// extension's own guess -- the same one every door used before the + /// probe existed -- while it is still asking. + pub(crate) fn has_video(&self, path: &Path) -> bool { + self.has_video + .get(path) + .copied() + .unwrap_or_else(|| !engine::is_audio(path)) + } + /// Starts a peak decode -- and a stream probe -- for every source that has /// arrived since the last /// repaint. One call from the render rather than three at the doors, @@ -48,6 +59,40 @@ impl Player { }) .detach(); } + // Whether a file's own header carries a picture at all, for the lane + // a drag may land on ([`Player::has_video`]). The two kinds whose + // extension already tells the truth (`engine::is_audio`, + // `engine::is_image`) are answered inline; the rest is the one case + // an extension can lie about -- a song muxed into an `.mp4` -- so it + // costs the same header open [`engine::decode::probe`] pays and goes + // off the render thread for the same reason. + for path in unseen_paths(session.sources(), &self.has_video) { + if engine::is_audio(&path) { + self.has_video.insert(path, false); + continue; + } + if engine::is_image(&path) { + self.has_video.insert(path, true); + continue; + } + self.has_video.insert(path.clone(), true); + let probed = cx.background_executor().spawn({ + let path = path.clone(); + async move { + !matches!(engine::demux::Demuxer::open(&path), + Err(e) if engine::demux::NoVideoTrack::is_it(&e)) + } + }); + cx.spawn(async move |this, cx| { + let probed = probed.await; + this.update(cx, |this, cx| { + this.has_video.insert(path, probed); + cx.notify(); + }) + .ok(); + }) + .detach(); + } // What each file is coded at, for the card that says so. Header and // sample table only, but a Matroska indexes no samples and its open // walks every cluster header -- 6.7 s on a 12.9 GB film -- so this of diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 1652dd5..7994864 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -97,7 +97,7 @@ impl Player { // ([`lane_refuses`]). The Add button names no lane and so is never // refused here -- where a file goes when nobody says is the engine's // choice, in `place_stream_at`, not one made twice here. - if let Some(why) = onto.and_then(|lane| lane_refuses(path, lane)) { + if let Some(why) = onto.and_then(|lane| lane_refuses(path, lane, self.has_video(path))) { self.notify_user(why.into()); cx.notify(); return; @@ -325,6 +325,7 @@ impl Player { self.bitrates.clear(); self.sizes.clear(); self.syncs.clear(); + self.has_video.clear(); // Scanned off sources that are not in the library any more. self.silence_levels.clear(); // ...and every background read still chasing one of them: cancelled @@ -805,6 +806,13 @@ impl Player { /// library standing in are two different things to be looking at. Empty /// where no film here wants one, which is the ordinary case. pub(crate) fn proxy_tail(&self) -> String { + // No session, no library row could be making anything: a prior + // session's jobs (never cleared out of `self.proxies` on close, since + // a proxy is derived and re-checked from disk on next open rather + // than tracked per session) must not print as this one's progress. + if self.session.is_none() { + return String::new(); + } let making = self.proxies.values().filter_map(|p| match p { Proxy::Making(job) => Some(job.progress()), _ => None, @@ -1073,8 +1081,13 @@ impl Player { // ([`engine::PlaybackSession::import`]); a window whose timeline went // away while the worker read falls to the slow door below, which is the // one that can still open one. + // A refusal that only says "no picture" is not a refusal here: the + // slow door below re-reads the file and lands it as audio, the same + // fallback every other door in makes. + let no_video = matches!(&probe, Some(Err(e)) if engine::demux::NoVideoTrack::is_it(e)); let registered = match (self.session.as_mut(), probe) { (Some(session), Some(Ok(probe))) => Some(session.import_probed(path, probe)), + (Some(session), Some(Err(_))) if no_video => Some(session.import(path)), (Some(_), Some(Err(refused))) => Some(Err(refused)), (Some(session), None) => Some(session.import(path)), (None, _) => None, @@ -1091,8 +1104,9 @@ impl Player { .and_then(|session| subtitle_tail(session, subs)) .unwrap_or_default(); format!( - "IMPORTED {} to the library — drag it onto a lane to place it{tail}", - file_name(path) + "IMPORTED {} to the library — drag it onto a lane to place it{tail}{}", + file_name(path), + audio_import_tail(path, self.has_video(path) && !no_video) ) } // Named, because two files can fail in one launch and the queue now @@ -1186,7 +1200,11 @@ impl Player { format!("IMPORTED {name} to the library — drag it onto a lane to place it") } }; - format!("{what}{}{subs}", silent.unwrap_or_default()) + let audio = match place { + true => String::new(), + false => audio_import_tail(path, self.has_video(path)), + }; + format!("{what}{}{subs}{audio}", silent.unwrap_or_default()) } Err(e) => format!("OPEN FAILED: {e}"), } diff --git a/crates/app/src/player/timeline_edit.rs b/crates/app/src/player/timeline_edit.rs index afd8058..4559645 100644 --- a/crates/app/src/player/timeline_edit.rs +++ b/crates/app/src/player/timeline_edit.rs @@ -980,7 +980,7 @@ impl Player { // A path with no source entry has no colour of its own, and the // shadow wears the lane's own instead of borrowing another file's. tint: file_tint(self.sources(), path).unwrap_or(BG_RAISED()), - refused: lane_refuses(path, to).is_some(), + refused: lane_refuses(path, to, self.has_video(path)).is_some(), }; self.set_ghost(vec![ghost], cx); } diff --git a/crates/app/src/subs.rs b/crates/app/src/subs.rs index 6008276..337f4dd 100644 --- a/crates/app/src/subs.rs +++ b/crates/app/src/subs.rs @@ -243,6 +243,28 @@ pub(crate) fn read_ahead( Landed::Read(walk_subtitles(path), probe) } +/// The toast's own words for a standalone audio import -- rate, channel +/// count and rounded length -- appended after every other tail, so an +/// audio-only file's IMPORTED line reads the numbers a properties card would +/// otherwise take a click to open. `has_video` is the caller's probed answer +/// ([`Player::has_video`], or the import's own `NoVideoTrack` refusal): a +/// film's toast is unchanged, an audio-only container gets the numbers the +/// same as a song, and a song whose own small header read comes back empty +/// stays plain. +pub(crate) fn audio_import_tail(path: &std::path::Path, has_video: bool) -> String { + if has_video { + return String::new(); + } + let probe = engine::AudioSession::probe(path, 0).ok().flatten(); + let secs = engine::AudioSession::duration_secs(path).ok().flatten(); + match (probe, secs) { + (Some(p), Some(secs)) => { + format!(" — {} Hz, {} ch, {}s", p.sample_rate, p.channels, secs.round() as u64) + } + _ => String::new(), + } +} + /// Every subtitle track a file carries, cues and all -- the walk that costs, in /// the one place every door that pays it goes through. `Ok` and empty for a file /// with none to read, which is what a file that is neither a container we can diff --git a/crates/app/src/tests/editing.rs b/crates/app/src/tests/editing.rs index bba57d3..1f837e7 100644 --- a/crates/app/src/tests/editing.rs +++ b/crates/app/src/tests/editing.rs @@ -839,6 +839,22 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { ), Enable::Hidden(_) )); + // A video clip the probed stream table says has no audio track at all -- + // the row is hidden rather than offered and refused after a scan comes + // back with nothing to report (`Player::start_silence_scan`'s `Ok(None)`). + assert!(matches!( + enable( + ActionId::Silence, + Ctx { + clip: Some((clip, v1)), + no_sound: true, + playhead: 60, + timeline: true, + ..Ctx::default() + } + ), + Enable::Hidden(_) + )); // The editor as a whole, which is how the actions card asks: with no // timeline nothing is offered, an export leaves only its own cancel, // and the three that act on the marked clip say so when none is. diff --git a/crates/app/src/tests/media.rs b/crates/app/src/tests/media.rs index 5a6df85..aae29af 100644 --- a/crates/app/src/tests/media.rs +++ b/crates/app/src/tests/media.rs @@ -6,10 +6,25 @@ use crate::player::library::{ auto_proxies_pref_path, load_auto_proxies_pref, save_auto_proxies_pref, }; use crate::subs::{ - SUB_SIZE_RANGE, load_subtitle_style, save_subtitle_style, sub_line_h_for, subtitle_style_path, + SUB_SIZE_RANGE, audio_import_tail, load_subtitle_style, save_subtitle_style, sub_line_h_for, + subtitle_style_path, }; use crate::ui::preview::{bgra_to_rgba, screenshot_path}; +/// The toast tail an audio import earns: rate, channel count and rounded +/// length, in the words the IMPORTED line appends them in +/// ([`Player::take_import`], [`Player::install_media`]). A film gets none of +/// it -- the gate is the probed has-video answer, not the extension, so an +/// audio-only container wearing .mp4 reads its numbers too. +#[test] +fn an_audio_import_names_its_rate_channels_and_length() { + let tail = audio_import_tail(&asset("test_tone.mp3"), false); + assert_eq!(tail, " — 44100 Hz, 2 ch, 3s", "{tail}"); + assert_eq!(audio_import_tail(&asset("test_av.mp4"), true), ""); + let mp4 = audio_import_tail(&asset("test_audio_only.mp4"), false); + assert_eq!(mp4, " — 44100 Hz, 1 ch, 3s", "{mp4}"); +} + /// The import line's own state machine, driven the way a repaint drives /// it: the worker writes a stage, the poll notices it changed and restarts /// the stall clock, and the line's words change only when a stage has diff --git a/crates/app/src/tests/view.rs b/crates/app/src/tests/view.rs index a70857f..f2f8be7 100644 --- a/crates/app/src/tests/view.rs +++ b/crates/app/src/tests/view.rs @@ -110,26 +110,34 @@ fn a_lane_refuses_the_files_it_cannot_hold_before_the_release_says_so() { let still = Path::new("/media/card.png"); let movie = Path::new("/media/take.mp4"); assert_eq!( - lane_refuses(sound, video).as_deref(), + lane_refuses(sound, video, false).as_deref(), Some("NOT ON V1 — take.mp3 has no picture; drop it on an audio lane") ); assert_eq!( - lane_refuses(still, audio).as_deref(), + lane_refuses(still, audio, true).as_deref(), Some("NOT ON A1 — card.png is a still image; drop it on a video lane") ); // ...and every lane a file *can* go on says nothing at all, which is a // ghost drawn in the file's own colour. - assert_eq!(lane_refuses(sound, audio), None); - assert_eq!(lane_refuses(still, video), None); - assert_eq!(lane_refuses(movie, video), None); + assert_eq!(lane_refuses(sound, audio, false), None); + assert_eq!(lane_refuses(still, video, true), None); + assert_eq!(lane_refuses(movie, video, true), None); // A file with a picture is not refused by an audio lane here: the // engine takes its sound onto one, and the words for a video-only file // are its own. - assert_eq!(lane_refuses(movie, audio), None); + assert_eq!(lane_refuses(movie, audio, true), None); + // The extension lies and the probe corrects it: a song muxed into an + // `.mp4` still names a video lane refused, in the exact words the .mp3 + // twin above got -- `has_video` is what decides it now, not the suffix. + assert_eq!( + lane_refuses(movie, video, false).as_deref(), + Some("NOT ON V1 — take.mp4 has no picture; drop it on an audio lane") + ); // ...and a subtitle lane holds none of the three: a caption comes off the // Subtitles list, which is where the refusal points. - for file in [sound, still, movie] { - let why = lane_refuses(file, Lane::S1).expect("a subtitle lane takes no media"); + for (file, has_video) in [(sound, false), (still, true), (movie, true)] { + let why = + lane_refuses(file, Lane::S1, has_video).expect("a subtitle lane takes no media"); assert!(why.starts_with("NOT ON S1 — "), "{why}"); assert!(why.contains("Subtitles list"), "{why}"); } diff --git a/crates/app/src/timeline_math.rs b/crates/app/src/timeline_math.rs index aa27805..612dadb 100644 --- a/crates/app/src/timeline_math.rs +++ b/crates/app/src/timeline_math.rs @@ -651,11 +651,15 @@ pub(crate) fn landing( /// cannot go. Asked twice: by the ghost tinting itself as refused on the way /// down, and by the insert that commits ([`Player::insert_source`]), so what is /// shown as impossible is exactly what is refused. -pub(crate) fn lane_refuses(path: &Path, lane: Lane) -> Option { +/// +/// `has_video` is [`Player::has_video`]'s answer for `path`: the probed truth +/// where the header has been read, and an extension's guess otherwise -- never +/// `engine::is_audio` alone, which a song muxed into an `.mp4` lies to. +pub(crate) fn lane_refuses(path: &Path, lane: Lane, has_video: bool) -> Option { let name = file_name(path); let label = lane.label(); match lane.kind { - LaneKind::Video if engine::is_audio(path) => Some(format!( + LaneKind::Video if !has_video => Some(format!( "NOT ON {label} — {name} has no picture; drop it on an audio lane" )), LaneKind::Audio if engine::is_image(path) => Some(format!( diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 5bbe1b6..d99290c 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -494,6 +494,13 @@ pub fn start( encoders: Mutex::new(None), }); let worker = Arc::clone(&shared); + // A second handle to the same slot, held outside the caught body below -- + // what settles it if that body never gets to its own [`settle`] call at + // all, because a codec parser deep inside `run` panicked instead of + // returning the parse error it should have. Without this a panic there + // strands the slot: [`ExportHandle::is_finished`] never flips, and a + // proxy or export that hit a malformed frame sits in "Making" forever. + let panic_worker = Arc::clone(&worker); let out = out.to_path_buf(); // `.part`, appended rather than substituted: the temporary of // `a.export.mp4` is `a.export.mp4.part`, which no other export claims. @@ -501,6 +508,7 @@ pub fn start( part.push(".part"); let part = PathBuf::from(part); let spawned = thread::Builder::new().name("export".into()).spawn(move || { + let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { // Every file this export will read, named before a byte of one is. // These are the project's own sources and can be nothing else: a // stand-in ([`crate::proxy`]) is a substitution playback makes when it @@ -579,6 +587,20 @@ pub fn start( let _ = std::fs::remove_file(&part); } settle(&worker, result); + })); + if let Err(payload) = caught { + // The body above panicked before it could settle its own slot -- + // the panic message becomes the outcome, so a caller sees a + // failure and a notice rather than a bar that never moves again. + let message = payload + .downcast_ref::<&str>() + .map(ToString::to_string) + .or_else(|| payload.downcast_ref::().cloned()) + .unwrap_or_else(|| "unknown panic".to_string()); + if !panic_worker.finished.load(Ordering::Acquire) { + settle(&panic_worker, Err(format!("export worker panicked: {message}").into())); + } + } }); if let Err(e) = spawned { settle(&shared, Err(e.into())); diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 2c7ce84..7cb2811 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -24,7 +24,7 @@ use crate::clock::{ClockSource, PlaybackClock}; use crate::color::ColorParams; use crate::colorspace::{ColorDescription, ContentLight}; use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; -use crate::demux::{Codec, Demuxer, VideoMeta}; +use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta}; use crate::eq::EqParams; use crate::project::{ Clip, Edge, GapSweep, Lane, LaneKind, Project, Rate, Source, Span, Speed, SubClip, @@ -571,7 +571,7 @@ impl PlaybackSession { // Passthrough: a freshly opened file *is* the project resolution, so // there is nothing to place it on. Every later span goes through // `start_span`, which builds the canvas from the project. - let (meta, stream) = DecodeSession::open_worker( + let opened = DecodeSession::open_worker( &path, 0, u32::MAX, @@ -581,7 +581,17 @@ impl PlaybackSession { // The default rendition: a file just opened is a project nobody has // picked one for, exactly as it is a project nobody has graded. crate::tonemap::Preset::default(), - )?; + ); + // `is_audio` above is the extension's word, and an extension can lie: a + // song muxed into an `.mp4` reads as a film until the header is actually + // walked. The demuxer's own `NoVideoTrack` is that walk saying there was + // never a picture in it, and the fallback is the same audio-only door the + // extension check would have taken up front -- not a fault, a type. + let (meta, stream) = match opened { + Ok(opened) => opened, + Err(e) if NoVideoTrack::is_it(&e) => return Self::open_audio_only(&path, audio_stream), + Err(e) => return Err(e), + }; // A file is opened on its first audio stream by default, like // `Project::single` names it -- unless a caller through // `open_with_audio_stream` picked another. @@ -924,7 +934,13 @@ impl PlaybackSession { } else { Demuxer::open(&first.path).map(|(_, d)| d.light()).unwrap_or_default() }; - let (mut meta, stream) = match crate::is_audio(&first.path) { + // The extension's word, corrected below the moment the header disagrees + // with it (`NoVideoTrack`, the same fallback `open_stream` takes): every + // later question in this function about source 0 asks *this*, not + // `crate::is_audio` again, so a discovered song stays one for the rest + // of the scaffold. + let mut audio_only = crate::is_audio(&first.path); + let (mut meta, stream) = match audio_only { true => { let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS; let frame_rate = saved_fps.unwrap_or(canvas_fps); @@ -964,7 +980,7 @@ impl PlaybackSession { )?; (meta, stream) } - false => DecodeSession::open_worker( + false => match DecodeSession::open_worker( &first.path, 0, u32::MAX, @@ -975,8 +991,30 @@ impl PlaybackSession { // project (which is built below): this placeholder is what the // window shows until the `seek` at the end reopens the span. doc.tone, - ) - .map_err(|e| format!("source {}: {e}", first.path.display()))?, + ) { + Ok(opened) => opened, + // A saved source whose extension named a film but whose header + // names no picture: the same door a fresh open falls to + // (`open_stream`), so a project first cut around a song muxed + // into an `.mp4` reloads instead of refusing on a track that was + // never there to begin with. + Err(e) if NoVideoTrack::is_it(&e) => { + audio_only = true; + let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS; + let frame_rate = saved_fps.unwrap_or(canvas_fps); + let meta = VideoMeta { + width, + height, + frame_rate, + frame_count: audio_frames(&first.path, frame_rate) + .map_err(|e| format!("source {}: {e}", first.path.display()))?, + codec: Codec::H264, + color: ColorDescription::default(), + }; + (meta, DecodeSession::open_black(width, height, 1)) + } + Err(e) => return Err(format!("source {}: {e}", first.path.display()).into()), + }, }; // The project's own resolution, which is source 0's picture unless the // file says otherwise -- every dialect before v7 had no way to say it, @@ -994,7 +1032,7 @@ impl PlaybackSession { // ([`set_frame_rate`](Self::set_frame_rate)) comes back at it rather // than at the media's, which would leave every clip number counted in // frames the timeline no longer has. - let native_fps = match crate::is_audio(&first.path) { + let native_fps = match audio_only { true => AUDIO_ONLY_CANVAS.2, false if crate::is_image(&first.path) => IMAGE_ONLY_RATE, false => meta.frame_rate, @@ -1006,7 +1044,7 @@ impl PlaybackSession { // their length above was counted in the timeline's frames already, // whatever those are. A file with pictures is read through [`Rate`] like // any other source when the project is cut at another rate. - let made_up = crate::is_audio(&first.path) || crate::is_image(&first.path); + let made_up = audio_only || crate::is_image(&first.path); let scaffold_rate = match made_up || native_fps == meta.frame_rate { true => Rate::REAL_TIME, false => Rate::from_fps(native_fps, meta.frame_rate) @@ -3236,8 +3274,14 @@ impl PlaybackSession { // Both halves on this thread, which is what a caller with nothing else // to do wants; a front-end splits them across a worker instead // ([`probe_import`](Self::probe_import)). - let probe = Self::probe_import(self.import_gate(), path)?; - Ok(self.take_probe(path, probe)) + // A container with sound but no picture is a song wearing a video + // extension -- the same fallback `open_stream` and the project + // scaffold make, so every door in agrees on what the file is. + match Self::probe_import(self.import_gate(), path) { + Ok(probe) => Ok(self.take_probe(path, probe)), + Err(e) if crate::demux::NoVideoTrack::is_it(&e) => self.import_audio(path), + Err(e) => Err(e), + } } /// Everything an import is *checked against*, taken off this timeline in diff --git a/crates/engine/src/proxy.rs b/crates/engine/src/proxy.rs index a565b7d..b8b620f 100644 --- a/crates/engine/src/proxy.rs +++ b/crates/engine/src/proxy.rs @@ -217,6 +217,41 @@ fn sweep(dir: &Path, cap: u64) -> u64 { total } +/// Deletes every `.part` in `dir`: the leftover of an encoder that never got +/// to unlink its own half-written file, because the process holding it was +/// killed rather than let finish or cancel cleanly. +/// +/// Unlike the one removal in [`started`], which clears only *this film's* own +/// `.part` right before a new encode of it starts, this clears everyone +/// else's too -- which is safe to do only because nothing in this process has +/// claimed a `.part` yet at the point it runs ([`sweep_stale_parts`]). +fn sweep_parts(dir: &Path) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().is_some_and(|e| e == "part") && std::fs::remove_file(&path).is_ok() { + eprintln!("proxy cache: swept stale {}", path.display()); + } + } +} + +/// Run once, at launch, ahead of anything that could claim a stand-in for +/// itself: clears every orphan `.part` a killed editor left in the proxy +/// cache. "Stale" needs no age check here -- at launch [`IN_FLIGHT`] is empty +/// by construction, so *every* `.part` on disk belongs to nobody still +/// running. A no-op where the machine has no cache directory at all. +pub fn sweep_stale_parts() { + if let Some(dir) = crate::demux::cache_dir( + std::env::var_os("XDG_CACHE_HOME"), + std::env::var_os("HOME"), + "proxies", + ) { + sweep_parts(&dir); + } +} + /// The proxy of `source` if one has already been made, `None` otherwise. The /// answer a session asks at open: a hit costs one `stat`. pub fn cached(source: &Path) -> Option { @@ -661,6 +696,29 @@ mod tests { assert!(fresh.exists()); } + /// What a killed editor leaves behind piles up as `.part` files nothing + /// ever revisits (nothing but the one film's own next start clears its + /// own, [`started`]) -- the launch-time sweep takes every one of them, + /// and leaves the finished stand-ins beside them alone. + #[test] + fn the_launch_sweep_takes_every_orphan_part() { + let dir = crate::scratch::Scratch::dir("proxy-part-sweep"); + let write = |name: &str| { + let path = dir.join(name); + std::fs::write(&path, b"orphaned mid-encode").expect("write"); + path + }; + let orphan_a = write("aaaa.mp4.part"); + let orphan_b = write("bbbb.mp4.part"); + let finished = write("cccc.mp4"); + + sweep_parts(&dir); + + assert!(!orphan_a.exists(), "one orphan part survived the sweep"); + assert!(!orphan_b.exists(), "the other orphan part survived it"); + assert!(finished.exists(), "a finished stand-in was swept too"); + } + /// A song and a still are not films: they are answered `None` -- the same /// answer a 1080p H.264 film gets -- rather than opened, failed on and /// reported. The bug this pins said "NO PROXY for tone.wav" to a person who diff --git a/crates/engine/tests/audio_files.rs b/crates/engine/tests/audio_files.rs index 88990af..cd1eec5 100644 --- a/crates/engine/tests/audio_files.rs +++ b/crates/engine/tests/audio_files.rs @@ -578,3 +578,36 @@ fn a_pasted_song_never_lands_on_the_video_lane() { assert_eq!(reloaded.lane_clips(Lane::V1).len(), video_after.len()); let _ = std::fs::remove_dir_all(&dir); } + +/// A song muxed into an `.mp4` -- the extension names a film, the header names +/// no picture. `open` falls to the audio-only door on the demuxer's own +/// `NoVideoTrack` rather than refusing "no H.264, HEVC, VP9 or AV1 video track +/// in file", exactly as it would have if the file had been named `.mp3`. +#[test] +fn an_audio_only_file_wearing_an_mp4_extension_still_opens() { + let session = open(asset("test_audio_only.mp4")); + assert!(session.lane_clips(Lane::V1).is_empty(), "no picture anywhere"); + assert_eq!(session.lane_clips(Lane::A1).len(), 1); + assert!((session.timeline_duration() - 3.0).abs() < 0.1); +} + +/// The same fallback in [`PlaybackSession::open_project`]'s scaffold branch: a +/// project whose first source is one of these files reloads instead of failing +/// the open a save never had trouble with the first time. +#[test] +fn a_project_scaffolded_from_an_audio_only_mp4_reloads() { + let dir = Scratch::dir("ve_audio_only_mp4"); + let mp4 = asset("test_audio_only.mp4"); + let session = open(&mp4); + let project = dir.join("song_mp4.edith"); + session.save_project(&project).expect("save"); + drop(session); + let reloaded = + PlaybackSession::open_project(&project).expect("reload a project scaffolded from it"); + reloaded.set_gain(0.0); + assert!(reloaded.lane_clips(Lane::V1).is_empty()); + assert_eq!(reloaded.lane_clips(Lane::A1).len(), 1); + assert!((reloaded.timeline_duration() - 3.0).abs() < 0.1); + drop(reloaded); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 11734dd..1b4c5a2 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -526,4 +526,10 @@ ffmpeg -y -f lavfi -i "testsrc2=size=320x240:rate=30:duration=2" \ -f lavfi -i "sine=frequency=440:duration=60" \ -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ -c:a aac -b:a 64k assets/test_short_video_long_audio.mp4 +# A song wearing a film's extension: AAC audio, no video track, muxed into an +# `.mp4` -- the shape a phone's voice memo or a stripped remux takes, and the +# one `crate::is_audio` cannot see (`tests/audio_files.rs`). +ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \ + -c:a aac -b:a 128k assets/test_audio_only.mp4 + echo "fixtures written to assets/" diff --git a/vendor/cros-codecs/src/codec/av1/parser.rs b/vendor/cros-codecs/src/codec/av1/parser.rs index b059a22..9f920d6 100644 --- a/vendor/cros-codecs/src/codec/av1/parser.rs +++ b/vendor/cros-codecs/src/codec/av1/parser.rs @@ -2905,14 +2905,26 @@ impl Parser { let v = (v * i64::from(div_factor)) as i32; let gamma0 = helpers::clip3(-32678, 32767, helpers::round2signed(v, div_shift)?); - let w = warp_params[3] * warp_params[4]; + // --- edith patch: a malformed bitstream's warp params (Troy.mkv's + // AV1 track panicked here, "attempt to multiply with overflow") can + // put i32::MAX-adjacent values in warp_params[3]/[4]/div_factor -- + // upstream trusted a conformant encoder never to. A checked multiply + // turns that into the parse error this function already returns for + // every other malformed field, instead of taking the whole process + // down. --- + let w = warp_params[3] + .checked_mul(warp_params[4]) + .ok_or_else(|| "warp params overflow: w = warp_params[3] * warp_params[4]".to_string())?; + + let wd = w + .checked_mul(div_factor) + .ok_or_else(|| "warp params overflow: w * div_factor".to_string())?; + // --- end edith patch --- let delta0 = helpers::clip3( -32768, 32767, - warp_params[5] - - helpers::round2signed(w * div_factor, div_shift)? - - (1 << WARPEDMODEL_PREC_BITS), + warp_params[5] - helpers::round2signed(wd, div_shift)? - (1 << WARPEDMODEL_PREC_BITS), ); let alpha = @@ -4054,6 +4066,20 @@ mod tests { use super::ObuType; + /// Repro for the panic hit on Troy.Director's.Cut.2004...AV1.mkv: + /// `warp_params[3] * warp_params[4]` (and its `* div_factor` beside it) + /// overflowed an `i32` on a malformed global-motion syntax and took the + /// whole process down with it -- `setup_shear` must answer a parse error + /// instead, exactly as it already does for every other malformed field. + #[test] + fn overflowing_warp_params_are_a_parse_error_not_a_panic() { + let overflowing = [0, 0, i32::MAX, i32::MAX, i32::MAX, i32::MAX]; + assert!( + Parser::setup_shear(&overflowing).is_err(), + "a malformed global-motion syntax must fail the parse, not panic" + ); + } + /// Same as test-25fps.av1.ivf from Chromium const STREAM_TEST_25_FPS: &[u8] = include_bytes!("test_data/test-25fps.ivf.av1");