diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 93759a9..c374a41 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -801,6 +801,13 @@ struct Player { /// while the sound is up; seeded by [`Player::session_swapped`], which every /// door that installs or drops a session already calls. audio_reason: Option, + /// The engine's last word on the *picture*, cached so a frame can tell a + /// reason that changed from one that was merely read again. Keyed to + /// `session_gen` for the same reason `audio_watch_gen` is: `pump` serves + /// the preview while one is up and the timeline otherwise, and an unkeyed + /// cache would read the other session's reason. + decode_reason_cache: Option, + decode_watch_gen: u64, /// Which session generation (`session_gen`) the cached reason above describes: /// the watch is keyed to the session it is a statement about, so a preview /// opening or closing seeds the cache instead of announcing the *other* @@ -1139,6 +1146,8 @@ fn main() { // it serves. audio_reason: None, audio_watch_gen: 0, + decode_reason_cache: None, + decode_watch_gen: 0, viz_slot: VizSlot::Main, viz_hex_edit: None, pending_viz: None, diff --git a/crates/app/src/notices.rs b/crates/app/src/notices.rs index 29e38a3..525b669 100644 --- a/crates/app/src/notices.rs +++ b/crates/app/src/notices.rs @@ -64,11 +64,30 @@ pub(crate) fn audio_lost_line(reason: &str) -> String { format!("AUDIO LOST{}", audio_tail(reason)) } -/// What a frame of the sound watch decides, as a pure value: the cache's own +/// A decode failure that arrives *after* a file was opened, said on its own +/// line: the same shape as [`audio_lost_line`] and for the same reason -- a +/// death mid-session has no open line to hang a tail off, so it leads with the +/// state word the strip reads first. +/// +/// The picture twin of the sound line above, and it exists because a decode +/// failure used to reach nobody at all: the worker printed it to stderr and +/// dropped the channel, and a closed channel is what a finished film looks like +/// from the app's side. A file with a damaged middle froze on its last good +/// picture and the transport said ENDED. The reason is the engine's own words, +/// verbatim -- the app spells none of them. +pub(crate) fn decode_failed_line(reason: &str) -> String { + format!("DECODE FAILED — {reason}") +} + +/// What a frame of a reason watch decides, as a pure value: the cache's own /// session generation against the frame's says whether the two are even talking /// about the same session, and only then what the reason did. +/// +/// One type for every reason the engine states, not one per source: the sound +/// device and the decode worker both write a string the app has to notice +/// changed, and the thing that decides is the same comparison in both cases. #[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub(crate) enum AudioStep { +pub(crate) enum ReasonStep { /// The cache describes the session *before* this one /// (`Player::session_swapped`): it is seeded and nothing is announced -- a /// preview that opens or closes is not a device that came back. @@ -81,7 +100,8 @@ pub(crate) enum AudioStep { Nothing, } -/// [`Player::watch_audio`]'s whole decision, pure: `cached_gen` is the session +/// [`Player::watch_audio`]'s and [`Player::watch_decode`]'s whole decision, +/// pure: `cached_gen` is the session /// generation the cache describes, `session_gen` the one the frame is serving, and /// two reasons are what the engine says the sound is (`None` for sound that is /// up). @@ -91,20 +111,20 @@ pub(crate) enum AudioStep { /// so a flip reads a reason that was never about the cached session at all -- a /// live device on one side and a dead one on the other is not a change, it is /// two different questions. -pub(crate) fn audio_step( +pub(crate) fn reason_step( cached_gen: u64, session_gen: u64, was: Option<&str>, now: Option<&str>, -) -> AudioStep { +) -> ReasonStep { if cached_gen != session_gen { - return AudioStep::Seed; + return ReasonStep::Seed; } match (was, now) { - (Some(was), Some(now)) if was == now => AudioStep::Nothing, - (_, Some(_)) => AudioStep::Push, - (Some(_), None) => AudioStep::Clear, - (None, None) => AudioStep::Nothing, + (Some(was), Some(now)) if was == now => ReasonStep::Nothing, + (_, Some(_)) => ReasonStep::Push, + (Some(_), None) => ReasonStep::Clear, + (None, None) => ReasonStep::Nothing, } } @@ -140,6 +160,32 @@ pub(crate) fn audio_change_notice( } } +/// What a *change* in the engine's **decode** reason does to the notice queue: +/// the line pushed when a reason arrives, the same line taken back when the +/// reason clears. [`audio_change_notice`]'s twin, step for step, because the +/// thing that changed is the same kind of thing -- a reason the engine started +/// or stopped stating between two frames. +/// +/// The retraction is what keeps this from becoming noise: a decode that fails, +/// is seeked away from and succeeds has to take its line back, or the strip +/// keeps saying DECODE FAILED over a film that plays. +pub(crate) fn decode_change_notice( + notices: &mut std::collections::VecDeque, + was: Option<&str>, + now: Option<&str>, +) { + match (was, now) { + (_, Some(reason)) if was != Some(reason) => { + push_notice(notices, decode_failed_line(reason).into()); + } + (Some(was), None) => { + let line = decode_failed_line(was); + notices.retain(|notice| notice.as_ref() != line.as_str()); + } + _ => {} + } +} + /// The strip's own width is finite and its message is one line: what a /// too-long line must never do is lose its *state* word, which sits at the /// front, or stop mid-word with nothing saying it stopped (user report, diff --git a/crates/app/src/player/transport.rs b/crates/app/src/player/transport.rs index 7f49623..299d16f 100644 --- a/crates/app/src/player/transport.rs +++ b/crates/app/src/player/transport.rs @@ -50,19 +50,19 @@ impl Player { /// without the key a preview opening or closing would read the *other* /// session's reason and announce a device loss that never happened. pub(crate) fn watch_audio(&mut self) { - let step = audio_step( + let step = reason_step( self.audio_watch_gen, self.session_gen, self.audio_reason.as_deref(), self.sound_reason(), ); - if step == AudioStep::Nothing { + if step == ReasonStep::Nothing { return; } let was = self.audio_reason.take(); self.audio_reason = self.sound_reason().map(str::to_owned); self.audio_watch_gen = self.session_gen; - if step == AudioStep::Seed { + if step == ReasonStep::Seed { // A session swap is not a change: the new session's own open line // carries its reason, so only a line left over from the session // before is taken back -- and only when this one's sound is up. @@ -82,6 +82,61 @@ impl Player { ); } + /// The engine's word on the *picture*, watched rather than asked once -- + /// [`Self::watch_audio`]'s twin, and the reason a damaged file stops being + /// indistinguishable from a finished one. + /// + /// `PlaybackSession::video_failure_reason` is the writer's side: a decode + /// worker that gave up on a broken packet used to print it to stderr and + /// drop the channel, and a closed channel is what a film reaching its own + /// end looks like from here -- so the transport said ENDED, the picture + /// froze on the last good frame, and nothing in the window said why. + /// + /// Keyed to the session exactly as the sound watch is, for the same reason: + /// `pump` serves the preview while one is up and the timeline otherwise, so + /// an unkeyed cache would read the other session's reason and announce a + /// failure that never happened. + pub(crate) fn watch_decode(&mut self) { + let now = self.decode_reason(); + let step = reason_step( + self.decode_watch_gen, + self.session_gen, + self.decode_reason_cache.as_deref(), + now.as_deref(), + ); + if step == ReasonStep::Nothing { + return; + } + let was = self.decode_reason_cache.take(); + self.decode_reason_cache = now; + self.decode_watch_gen = self.session_gen; + if step == ReasonStep::Seed { + // A session swap is not a change: the new session's own open line + // carries its reason, so only a line left over from the session + // before is taken back -- and only when this one is healthy. + if self.decode_reason_cache.is_none() + && let Some(was) = was + { + let line = decode_failed_line(&was); + self.notices + .retain(|notice| notice.as_ref() != line.as_str()); + } + return; + } + decode_change_notice( + &mut self.notices, + was.as_deref(), + self.decode_reason_cache.as_deref(), + ); + } + + /// The engine's word on the picture for the session the pump serves, read + /// off that session and no other -- the same rule as [`Self::sound_reason`]. + fn decode_reason(&self) -> Option { + self.active_session() + .and_then(PlaybackSession::video_failure_reason) + } + /// Catches the display up to the clock: everything already due is taken off /// 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`, and @@ -90,8 +145,10 @@ impl Player { pub(crate) fn pump(&mut self, window: &mut Window) { // Before the drain, on the one read that does not need the session // mutably: the sound can die at any point in a frame, and the notice it - // earns is owed to the frame it died in. + // earns is owed to the frame it died in. The picture can fail for the + // same reason and earns the same courtesy. self.watch_audio(); + self.watch_decode(); // 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(); diff --git a/crates/app/src/tests/media.rs b/crates/app/src/tests/media.rs index 6e58f91..09124d8 100644 --- a/crates/app/src/tests/media.rs +++ b/crates/app/src/tests/media.rs @@ -14,7 +14,76 @@ use crate::ui::preview::{bgra_to_rgba, screenshot_path}; /// The notice queue's own half of the sound watch, and the three words it is /// spelled with -- reached by name because the app's own glob does not carry /// them (`notices` is a private module re-exported for the window). -use crate::notices::{audio_change_notice, audio_lost_line, audio_tail}; +use crate::notices::{ + audio_change_notice, audio_lost_line, audio_tail, decode_change_notice, decode_failed_line, +}; + +/// The picture twin of the sound watch above, and the same shape for the same +/// reason: a decode failure that arrives between two frames used to reach no +/// consumer at all, because the worker printed it to stderr and dropped the +/// channel -- and a closed channel is what a finished film looks like from the +/// app's side, so the transport said ENDED over a frozen frame with nothing in +/// the window saying why. +/// +/// Driven through the queue step, because a test cannot make a decoder fail on +/// cue; the engine's writer is the decode worker's, and +/// `engine::tests::decode_failure` observes it end to end on the engine side. +#[test] +fn a_decode_that_fails_under_an_open_file_says_so_and_unsays_it() { + let mut notices: std::collections::VecDeque = + ["OPENED take.mp4".into()].into_iter().collect(); + let failed = decode_failed_line("decode error at access unit 130"); + assert!( + failed.starts_with("DECODE FAILED"), + "the line lost the state word the strip reads first: {failed}" + ); + // The file was fine, and then the picture stopped: the reason arrives + // between two frames. + decode_change_notice(&mut notices, None, Some("decode error at access unit 130")); + assert_eq!( + notices.back().map(|notice| &***notice), + Some(failed.as_str()), + "a decode failure that arrives mid-session is never pushed" + ); + // The same reason read again on the next frame is not news. + decode_change_notice( + &mut notices, + Some("decode error at access unit 130"), + Some("decode error at access unit 130"), + ); + assert_eq!(notices.len(), 2, "one failure was announced twice"); + // Seeked away from, and it decodes again: the line goes with it, or the + // strip keeps saying DECODE FAILED over a film that plays. + decode_change_notice(&mut notices, Some("decode error at access unit 130"), None); + assert_eq!( + notices.iter().map(|notice| &***notice).collect::>(), + vec!["OPENED take.mp4"], + "the DECODE FAILED line is still on the strip over a film that plays" + ); + // The sound line is a different line and is none of this step's business. + audio_change_notice(&mut notices, None, Some("AUDIO_LOST")); + decode_change_notice(&mut notices, None, Some("decode error at access unit 7")); + decode_change_notice(&mut notices, Some("decode error at access unit 7"), None); + assert_eq!( + notices.iter().map(|notice| &***notice).collect::>(), + vec!["OPENED take.mp4", audio_lost_line("AUDIO_LOST").as_str()], + "one reason's retraction took the other one's line with it" + ); + // The wiring: the pump is the one place every frame passes through, and a + // watcher nothing calls is a message nobody reads. + assert!( + fn_body("pump").contains("self.watch_decode();"), + "the pump stopped watching the engine's decode reason, so a corrupt \ + file is a silent freeze again" + ); + // ...and it reads the reason off the session the pump is serving, the same + // rule the sound watch follows. + assert!( + fn_body("decode_reason").contains("self.active_session()"), + "the decode watch reads a reason off a session the pump is not \ + serving, so a preview flip announces the other session's failure" + ); +} /// A reason that changes under a session that is already open says so, and stops /// saying so when it clears. This side is the *reader*: the writer of a reason is @@ -72,7 +141,7 @@ fn a_device_that_dies_under_an_open_file_says_so_and_unsays_it() { // cannot be answered as if it were the cached session's own change. let watch = fn_body("watch_audio"); let args = watch - .split_once("audio_step(") + .split_once("reason_step(") .expect( "the watch decides for itself instead of through the pure step the flip test drives", ) @@ -106,29 +175,41 @@ fn a_device_that_dies_under_an_open_file_says_so_and_unsays_it() { /// speaks. #[test] fn a_preview_flip_is_not_a_device_that_came_back() { - use crate::notices::{AudioStep, audio_step}; + use crate::notices::{ReasonStep, reason_step}; // A swap, every way round: seeded, never announced. - assert_eq!(audio_step(7, 8, None, Some("AUDIO_LOST")), AudioStep::Seed); - assert_eq!(audio_step(7, 8, Some("AUDIO_LOST"), None), AudioStep::Seed); assert_eq!( - audio_step(7, 8, Some("AUDIO_LOST"), Some("AUDIO_LOST")), - AudioStep::Seed, + reason_step(7, 8, None, Some("AUDIO_LOST")), + ReasonStep::Seed + ); + assert_eq!( + reason_step(7, 8, Some("AUDIO_LOST"), None), + ReasonStep::Seed + ); + assert_eq!( + reason_step(7, 8, Some("AUDIO_LOST"), Some("AUDIO_LOST")), + ReasonStep::Seed, "a flip whose reason reads the same on both sides is still a flip" ); // The same session, the reason arriving, changing, and going. - assert_eq!(audio_step(7, 7, None, Some("AUDIO_LOST")), AudioStep::Push); assert_eq!( - audio_step(7, 7, Some("AUDIO_LOST"), Some("device gone")), - AudioStep::Push + reason_step(7, 7, None, Some("AUDIO_LOST")), + ReasonStep::Push + ); + assert_eq!( + reason_step(7, 7, Some("AUDIO_LOST"), Some("device gone")), + ReasonStep::Push + ); + assert_eq!( + reason_step(7, 7, Some("AUDIO_LOST"), None), + ReasonStep::Clear ); - assert_eq!(audio_step(7, 7, Some("AUDIO_LOST"), None), AudioStep::Clear); assert_eq!( - audio_step(7, 7, Some("AUDIO_LOST"), Some("AUDIO_LOST")), - AudioStep::Nothing, + reason_step(7, 7, Some("AUDIO_LOST"), Some("AUDIO_LOST")), + ReasonStep::Nothing, "the same reason read again on the next frame is not news" ); - assert_eq!(audio_step(7, 7, None, None), AudioStep::Nothing); - assert_eq!(audio_step(0, 0, None, None), AudioStep::Nothing); + assert_eq!(reason_step(7, 7, None, None), ReasonStep::Nothing); + assert_eq!(reason_step(0, 0, None, None), ReasonStep::Nothing); } /// The toast tail an audio import earns: rate, channel count and rounded diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0b0a571..720a844 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -205,5 +205,7 @@ oxideav-sub-image = "0.0.7" [dev-dependencies] # The still-image suite compares what the timeline shows against the file's own -# pixels rather than against a constant. Already built for the engine itself. -image = { version = "0.25", default-features = false, features = ["png"] } +# pixels rather than against a constant, and the EXIF suite has to *write* one: +# no fixture in `assets/` carries an orientation tag, so the turned-still test +# builds its own JPEG here. Already built for the engine itself. +image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 57fe1ab..b11fb61 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -2,18 +2,19 @@ //! thread (the UI thread) never blocks on decode and memory stays capped. use std::path::{Path, PathBuf}; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}; +use std::sync::{Arc, Mutex}; use std::thread; -use ec_core::frame::VideoFrame; use ec_av1::encode::Picture as Av1Picture; use ec_av1::stream::decode_stream_with; -use ec_core::registry::{CodecId, CodecParameters}; +use ec_core::frame::VideoFrame; use ec_core::registry::Decoder as _; +use ec_core::registry::{CodecId, CodecParameters}; use ec_core::{Error as Av1Error, Packet, TimeBase}; use ec_h264::H264Decoder; +use image::ImageDecoder as _; use crate::color::ColorParams; use crate::colorspace::{ColorDescription, Matrix, Transfer}; @@ -407,6 +408,56 @@ pub(crate) struct FrameStream { /// What this stream's pictures are being decoded by. Dropped last and read /// by the caller, so it outlives nothing and blocks nothing. pub(crate) backend: BackendCell, + /// Why this stream stopped early, if it did -- the answer a closed channel + /// cannot give. Cloned into the worker, so it outlives the span that set it. + pub(crate) failure: DecodeFailure, +} + +/// Why a decode worker stopped **before** the end of its stream, if it did. +/// +/// The reason channel the sound path already has ([`crate::playback::Audio`]'s +/// `died` flag, read back as `audio_disabled_reason`), for the picture side. It +/// exists because a closed channel is not an answer: a worker that ran to the end +/// of the file and a worker that gave up on a corrupt packet both drop the +/// sender, and to a caller reading [`std::sync::mpsc::Receiver::try_recv`] +/// those are one event. The app read that as `Transport::Ended`, so a file with +/// a broken middle froze on its last good picture and said nothing -- identical +/// to the film finishing, with no notice and no banner. +/// +/// The **first** reason wins: a span that fails and is then reseeked keeps the +/// failure that stopped it until a span succeeds, which is what makes this a +/// statement about the file rather than about the last attempt. A clean +/// end-of-stream sets nothing at all -- silence is not a fault, and a notice +/// that fires on every film would be a notice nobody reads. +#[derive(Clone, Default)] +pub struct DecodeFailure(Arc>>); + +impl DecodeFailure { + /// The reason the last span failed, if one did. + pub fn reason(&self) -> Option { + self.0.lock().ok().and_then(|reason| reason.clone()) + } + + /// Records a failure and says so on stderr, which is where these used to go + /// and where they still belong: the stderr line is for whoever is reading a + /// log, and this cell is for whoever is looking at a window. + pub(crate) fn set(&self, reason: String) { + eprintln!("{reason}"); + let Ok(mut slot) = self.0.lock() else { + return; // poisoned by a panic elsewhere: the stderr line still stands + }; + if slot.is_none() { + *slot = Some(reason); + } + } + + /// Takes the reason back, for a caller that has read it: a fresh span that + /// gets all the way through its range has answered the question. + pub(crate) fn clear(&self) { + if let Ok(mut slot) = self.0.lock() { + slot.take(); + } + } } pub struct DecodeSession; @@ -482,6 +533,7 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::new(Backend::Gap), + failure: DecodeFailure::default(), }; } let worker_cancel = Arc::clone(&cancel); @@ -515,6 +567,7 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::new(Backend::Gap), + failure: DecodeFailure::default(), } } @@ -547,6 +600,10 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::new(Backend::Still), + // A still has no stream to fail in: `Still::open` raised + // anything that was wrong with the file at the door, before a + // worker existed. + failure: DecodeFailure::default(), }); } // The one conversion, on this thread: it is a few milliseconds and the @@ -560,7 +617,9 @@ impl DecodeSession { let first = Render::new( color, transform, - // A still has no display matrix: what the file holds is what it is. + // A still's own turn is already in these planes: `Still::open` made + // it before the conversion above, exactly where the video door + // makes a display matrix, so the render must not make it twice. Rotation::None, // ...and no sample aspect either: a still is authored square. PixelAspect::SQUARE, @@ -608,6 +667,7 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::new(Backend::Still), + failure: DecodeFailure::default(), }) } @@ -646,6 +706,9 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::new(Backend::Visualizer), + // A painted picture has no decoder to fail: an unreadable audio + // file is `VizEnvelope::Silent`, which is what silence looks like. + failure: DecodeFailure::default(), }); } // Painted at the canvas's own size, so the composite places nothing: @@ -684,7 +747,11 @@ impl DecodeSession { if worker_cancel.load(Ordering::Relaxed) { return; } - let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 }; + let fps = if fps.is_finite() && fps > 0.0 { + fps + } else { + 30.0 + }; // One frame's painting no longer allocates per strand per // frame: this thread lives for the span. let mut scratch = VizScratch::default(); @@ -711,9 +778,8 @@ impl DecodeSession { // the same thirty seconds, and no decode at all for the // rebuilds of a look edit. let view = envelope.view_at(t); - let (y, u, v) = visualizer_window_i420( - &mut scratch, &view, t, width, height, flags, paint, - ); + let (y, u, v) = + visualizer_window_i420(&mut scratch, &view, t, width, height, flags, paint); let frame = render.frame(start_frame + index, &y, &u, &v, width, height); if tx.send(frame).is_err() { return; // caller moved on @@ -729,6 +795,9 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::new(Backend::Visualizer), + // ...and nothing in the paint loop can fail either, for the same + // reason. + failure: DecodeFailure::default(), }) } @@ -762,6 +831,34 @@ impl DecodeSession { tone: tonemap::Preset, ) -> crate::Result<(VideoMeta, FrameStream)> { let path = path.as_ref().to_path_buf(); + // A still is not a stream: handing one to the mp4 demuxer answers "a + // box with a larger size than it", which is a true sentence about a + // container and nothing a person can act on -- and it made this door, + // the one a front-end opens a file through, refuse every picture + // outright. The still door answers with a meta of its own, so a poster + // thumbnail and a preview window get the same picture the timeline + // does, at the same size. No `tone` argument is passed on and none is + // wanted: a still is decoded into BT.601 SDR planes, so there is no + // map to build whichever rendition the project is watching. + if crate::is_image(&path) { + let still = Still::open(&path)?; + let meta = VideoMeta { + width: still.width, + height: still.height, + frame_rate: 1.0, + frame_count: 1, + codec: Codec::H264, + color: ColorDescription::default(), + // A still's own turn was made in `Still::open`, before these + // planes were written, so there is nothing left to state here. + rotation: Rotation::None, + coded_width: still.width, + coded_height: still.height, + pixel_aspect: PixelAspect::SQUARE, + }; + return Self::open_still(&path, start_frame, 1, color, transform, canvas) + .map(|stream| (meta, stream)); + } let (meta, demuxer) = Demuxer::open(&path)?; // No software HEVC, VP9 or VP8 decoder exists, so such a file the plugin will // not take is refused *here*, where the caller still has somewhere to @@ -789,6 +886,7 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::default(), + failure: DecodeFailure::default(), }, )); } @@ -885,6 +983,11 @@ fn span_worker( // what opened rather than what was hoped for -- and kept across the spans // that follow, since they are decoded by that very decoder. let backend = BackendCell::default(); + // One cell for the whole worker, not one per span: the thread outlives its + // spans (that is what a reseek costs nothing for), so the reason a span + // failed has to outlive the span too, and be visible to whoever opened this + // stream. + let failure = DecodeFailure::default(); let generation = Arc::new(AtomicU64::new(0)); // The playhead starts where the span does: nothing is behind it yet. let floor = Arc::new(AtomicU32::new(start_frame)); @@ -902,6 +1005,7 @@ fn span_worker( }; let worker_cancel = Arc::clone(&cancel); let worker_backend = backend.clone(); + let worker_failure = failure.clone(); let worker_generation = Arc::clone(&generation); let worker_floor = Arc::clone(&floor); let worker_path = path.clone(); @@ -923,7 +1027,14 @@ fn span_worker( // interrupt. A scrub abandons spans by the dozen and this is // where all but the last of them stop. if !abort.hit() { - run_span(&worker_path, &mut source, cmd, &abort, &worker_backend); + run_span( + &worker_path, + &mut source, + cmd, + &abort, + &worker_backend, + &worker_failure, + ); } // Parked between spans. A seek and a clip boundary arrive in // milliseconds and find the decoder still open, which is the @@ -975,6 +1086,7 @@ fn span_worker( }), }, backend, + failure, } } @@ -1049,7 +1161,9 @@ impl Source { fn position_hw(&mut self, path: &Path, start: u32) -> Option { if let Some(hw) = &mut self.hw { if hw.seek(start) { - eprintln!("decode backend: hardware (VA-API plugin, session kept, seek to {start})"); + eprintln!( + "decode backend: hardware (VA-API plugin, session kept, seek to {start})" + ); return Some(true); } // A plugin too old to reposition, or a decoder that would not @@ -1075,6 +1189,7 @@ fn run_span( cmd: SpanCmd, abort: &Abort, backend: &BackendCell, + worker_failure: &DecodeFailure, ) { let SpanCmd { start, @@ -1087,11 +1202,21 @@ fn run_span( tx, .. } = cmd; + // A span is a fresh question, so it starts from a clean answer: the + // failure that stopped the span before this one was already reported, and + // carrying it would keep saying a fault that this range may not have. Only + // a span that is actually going to run clears it -- a span superseded on its + // way through the queue decoded nothing and has nothing to say. + worker_failure.clear(); let opened = match source { Some(opened) => opened, None => { let Some(fresh) = Source::open(path) else { backend.set(Backend::Gap); + worker_failure.set(format!( + "{}: could not be opened for decoding", + path.display() + )); return; }; source.insert(fresh) @@ -1133,6 +1258,7 @@ fn run_span( &mut render, abort, speed, + worker_failure, ); // A *reused* session that produced nothing may simply be one this // reseek left where the driver would not follow; a session opened fresh @@ -1140,10 +1266,21 @@ fn run_span( // is a software fallback. Without this a single unfollowed seek would // collapse the rest of the file to software. if !decoded && reused { - eprintln!("hardware decode produced nothing after a reseek; reopening at frame {start}"); + eprintln!( + "hardware decode produced nothing after a reseek; reopening at frame {start}" + ); opened.hw = open_hw(path, start); if let Some(hw) = opened.hw.as_mut() { - decoded = run_hw(hw, &tx, start, end, &mut render, abort, speed); + decoded = run_hw( + hw, + &tx, + start, + end, + &mut render, + abort, + speed, + worker_failure, + ); } } if decoded { @@ -1162,12 +1299,30 @@ fn run_span( Codec::H264 => { eprintln!("decode backend: software (ec-h264)"); backend.set(Backend::Software); - run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed); + run( + &mut opened.demuxer, + &tx, + start, + end, + &mut render, + abort, + speed, + worker_failure, + ); } Codec::Av1 => { eprintln!("decode backend: software (ec-av1)"); backend.set(Backend::Software); - run_av1(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed); + run_av1( + &mut opened.demuxer, + &tx, + start, + end, + &mut render, + abort, + speed, + worker_failure, + ); } // Nothing decodes from here -- no software seat exists for this codec. // Say so: the cell was left claiming the hardware session that opened @@ -1175,7 +1330,7 @@ fn run_span( // was hoped for. other => { backend.set(Backend::Gap); - eprintln!("{}", other.needs_plugin()); + worker_failure.set(format!("{}: {}", path.display(), other.needs_plugin())); } } } @@ -1388,36 +1543,35 @@ impl Render { // picture a viewer is shown, so its brightness and saturation mean what // they say in the SDR the tone map just produced, not in the 10-stop // HDR the file was in. - let (y, u, v, desc) = if self.tone.is_some() - || (!skip_placement && !self.color.is_identity()) - { - let (gy, gu, gv) = &mut self.graded; - gy.clear(); - gy.extend_from_slice(y); - gu.clear(); - gu.extend_from_slice(u); - gv.clear(); - gv.extend_from_slice(v); - if let Some(tone) = &self.tone { - tone.map(gy, gu, gv, width as usize, height as usize); - } - // The same terms the branch was entered on: anywhere the fused - // conversion below will not apply the grade (a placement is - // happening, so the canvas conversion is plain), it lands here -- - // including the passthrough-sized clip a transform moves, whose - // grade used to be dropped on the floor between these two guards. - if !skip_placement && !self.color.is_identity() { - crate::color::apply_yuv(&self.color, gy, gu, gv); - } - let desc = if self.tone.is_some() { - TONE_MAPPED + let (y, u, v, desc) = + if self.tone.is_some() || (!skip_placement && !self.color.is_identity()) { + let (gy, gu, gv) = &mut self.graded; + gy.clear(); + gy.extend_from_slice(y); + gu.clear(); + gu.extend_from_slice(u); + gv.clear(); + gv.extend_from_slice(v); + if let Some(tone) = &self.tone { + tone.map(gy, gu, gv, width as usize, height as usize); + } + // The same terms the branch was entered on: anywhere the fused + // conversion below will not apply the grade (a placement is + // happening, so the canvas conversion is plain), it lands here -- + // including the passthrough-sized clip a transform moves, whose + // grade used to be dropped on the floor between these two guards. + if !skip_placement && !self.color.is_identity() { + crate::color::apply_yuv(&self.color, gy, gu, gv); + } + let desc = if self.tone.is_some() { + TONE_MAPPED + } else { + self.desc + }; + (&gy[..], &gu[..], &gv[..], desc) } else { - self.desc + (y, u, v, self.desc) }; - (&gy[..], &gu[..], &gv[..], desc) - } else { - (y, u, v, self.desc) - }; if skip_placement { return Frame { index, @@ -1435,11 +1589,17 @@ impl Render { }; } let (y, u, v, width, height) = if transform_active { - let (py, pu, pv, w, h) = self - .canvas - .place_transformed(y, u, v, width, height, &self.transform); + let (py, pu, pv, w, h) = + self.canvas + .place_transformed(y, u, v, width, height, &self.transform); self.placed = (py, pu, pv); - (&self.placed.0[..], &self.placed.1[..], &self.placed.2[..], w, h) + ( + &self.placed.0[..], + &self.placed.1[..], + &self.placed.2[..], + w, + h, + ) } else { self.canvas.place(y, u, v, width, height) }; @@ -1465,10 +1625,100 @@ pub(crate) struct Still { pub(crate) y: Vec, pub(crate) u: Vec, pub(crate) v: Vec, + /// The picture as it is *shown*, which for a phone's portrait photo is not + /// the picture as it was stored: the turn its EXIF block asks for was made + /// in [`Still::open`] before these planes were written, exactly where the + /// video doors make a display matrix, so the pair every reader takes is + /// the displayed one ([`crate::demux::Rotation`]'s own contract). pub(crate) width: u32, pub(crate) height: u32, } +/// A still whose EXIF orientation is not a quarter turn: values 2, 4, 5 and 7 +/// are mirrorings, and this engine has no flip anywhere in its pipeline -- not +/// in [`crate::scale::rotate_i420_90s`], not in [`Render`], not in an export's +/// `place_picture`. Refused **by name** at the door, for +/// [`crate::demux::UnsupportedRotation`]'s reason: showing a mirrored photo the +/// wrong way round is a wrong picture rather than a missing feature, and +/// quietly treating a mirror as a turn is exactly the bug this door exists to +/// stop. The `Display` is what a user is refused by. +#[derive(Debug)] +pub struct UnsupportedStillOrientation { + /// The EXIF value the file states, which is what the sentence names: the + /// eight legal values are 1 (upright) through 8, and the four mirrorings + /// are the even-odd pairs. + pub exif: u8, +} + +impl std::fmt::Display for UnsupportedStillOrientation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "this picture's EXIF orientation is {}, which is a mirror and not a turn; only \ + upright, 90°, 180° and 270° can be straightened here", + self.exif + ) + } +} + +impl std::error::Error for UnsupportedStillOrientation {} + +impl UnsupportedStillOrientation { + /// Whether `error` is one of these, however deep in a `Box` it is -- + /// [`crate::demux::UnsupportedRotation::is_it`]'s twin. + pub fn is_it(error: &crate::Error) -> bool { + error.downcast_ref::().is_some() + } +} + +/// The quarter turns an EXIF orientation asks for, as the one +/// [`Rotation`] every other door in this engine already uses -- no second +/// shape mechanism for a still, so the same turn is made by the same code +/// that makes a video's display matrix turn. +/// +/// EXIF 1, 6, 8 and 3 are the four quarter turns; **2, 4, 5 and 7 are +/// mirrorings** and are refused ([`UnsupportedStillOrientation`]) rather than +/// approximated by the nearest rotation. A value the standard does not define +/// (0, or above 8) states no orientation this can read, and is likewise +/// refused rather than guessed at. +fn rotation_of_exif(orientation: image::metadata::Orientation) -> crate::Result { + use image::metadata::Orientation as O; + Ok(match orientation { + O::NoTransforms => Rotation::None, + O::Rotate90 => Rotation::Cw90, + O::Rotate180 => Rotation::Cw180, + O::Rotate270 => Rotation::Cw270, + // The `image` crate keeps the raw number alongside: an orientation it + // could not read is `NoTransforms`, and saying "0" for a mirror would + // be a claim rather than a reading. + mirrored => { + return Err(UnsupportedStillOrientation { + exif: mirrored.to_exif(), + } + .into()); + } + }) +} + +/// What turn `path` asks for, read off its **header** alone -- what a library +/// row says about a file it has not placed anywhere, and what +/// [`image_size`] needs to report the size the picture is shown at. +/// +/// Header-only on purpose: the whole file is not decoded, exactly as +/// [`image_size`] has always been. `into_decoder` parses the container and +/// stops there; the pixels are never touched. +pub fn image_orientation(path: &Path) -> crate::Result { + let mut decoder = image::ImageReader::open(path)? + .with_guessed_format()? + .into_decoder() + .map_err(|e| format!("{}: {e}", path.display()))?; + // The refusal is handed on **unchanged**, not folded into a sentence with + // the file's name: a `String` is not an error a caller can downcast, and + // `is_it` is how a front-end tells this refusal from any other failure. + // The path is not lost -- every caller that has one puts it in front. + rotation_of_exif(decoder.orientation()?) +} + impl Still { /// Decodes `path`. Refused by name for a picture that is not one /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project @@ -1484,12 +1734,41 @@ impl Still { /// lands as a rectangle. Upgrade path is keeping the alpha plane here and /// giving `scale::Composer` a blend over the lane below. pub(crate) fn open(path: &Path) -> crate::Result { - let reader = image::ImageReader::open(path)?.with_guessed_format()?; - let rgb = reader - .decode() + // The turn is read and made **here**, once, before a single pair of + // numbers leaves this function: `image`'s decoder keeps an EXIF + // orientation in its own field and applies nothing, so a portrait + // phone photo arrived as landscape planes and every consumer below -- + // the `Render`, the `VideoMeta`, `image_size` -- reported the shape the + // camera stored rather than the one it was shot at. This is the same + // step the video doors make, at the same place in the pipeline + // (before the grade, the canvas and the conversion all see the + // picture), and it uses the same [`Rotation`]. + let mut decoder = image::ImageReader::open(path)? + .with_guessed_format()? + .into_decoder() + .map_err(|e| format!("{}: {e}", path.display()))?; + // Unchanged for the reason `image_orientation` gives: a caller has to + // be able to downcast this refusal, and a sentence with the file's name + // in it is not one. + let rotation = rotation_of_exif(decoder.orientation()?)?; + let rgb = image::DynamicImage::from_decoder(decoder) .map_err(|e| format!("{}: {e}", path.display()))? .to_rgb8(); - let (width, height) = rgb.dimensions(); + let (coded_width, coded_height) = rgb.dimensions(); + // Turned here rather than left to each consumer, so there is exactly + // one place the turn is made and no consumer can be forgotten: the + // planes handed out below are the *shown* picture, so the `Render`, the + // `VideoMeta`, an export's `place_picture` and `image_size` all agree + // without any of them re-deriving it. A file that states no turn takes + // the branch by a bool and not one byte is copied. + let (rgb, width, height) = match rotation.is_none() { + true => (rgb, coded_width, coded_height), + false => { + let turned = turn_rgb(&rgb, rotation.steps()); + let (width, height) = turned.dimensions(); + (turned, width, height) + } + }; if !crate::is_resolution(width, height) { return Err(format!( "{} is {width}x{height}, which is not a picture this engine composes", @@ -1508,19 +1787,49 @@ impl Still { } /// The planes as an export's decoder hands them over, so a still and a - /// decoded picture are the same value to `export::run`. + /// decoded picture are the same value to `export::run` -- and, for a + /// turned still, the same value in the only sense that matters: the turn + /// is already in them, so an export places what the preview showed without + /// being told a second time. pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) { (&self.y, &self.u, &self.v, self.width, self.height) } } -/// How big the picture in `path` is, from its header alone -- what a library row -/// says about a file it has not placed anywhere. The whole file is not decoded. +/// `steps` quarter turns clockwise over a packed RGB8 picture -- the same +/// direction and the same count [`crate::scale::rotate_i420_90s`] takes, on the +/// still's own buffer rather than on its planes: a still is turned exactly once +/// in its whole life, so there is no steady-state cost to make the allocating +/// call the one that happens. +fn turn_rgb(rgb: &image::RgbImage, steps: u8) -> image::RgbImage { + match steps % 4 { + 1 => image::imageops::rotate90(rgb), + 2 => image::imageops::rotate180(rgb), + 3 => image::imageops::rotate270(rgb), + _ => rgb.clone(), + } +} + +/// How big the picture in `path` is as it is **shown**, from its header alone -- +/// what a library row says about a file it has not placed anywhere. The whole +/// file is not decoded. +/// +/// The turn is applied to the answer for the same reason +/// [`DecodeSession::open_still`]'s is: a portrait phone photo stores landscape +/// and says so in its EXIF block, and a row that answered 4000x3000 for a +/// picture that is shown 3000x4000 states the wrong shape on the one surface +/// that exists before anything places the file. Header-only still -- +/// `into_decoder` parses the container and stops. pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> { - Ok(image::ImageReader::open(path)? + let rotation = image_orientation(path)?; + let (width, height) = image::ImageReader::open(path)? .with_guessed_format()? .into_dimensions() - .map_err(|e| format!("{}: {e}", path.display()))?) + .map_err(|e| format!("{}: {e}", path.display()))?; + Ok(match rotation.swaps_axes() { + true => (height, width), + false => (width, height), + }) } /// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse @@ -1599,11 +1908,7 @@ const VIZ_STRAND_SAT_SHIFT: u32 = 40; const VIZ_STRAND_CHOSEN: u64 = 1 << 63; pub fn viz_materialize(paint: u64) -> u64 { - if paint == 0 { - VIZ_PAINT_AZURE - } else { - paint - } + if paint == 0 { VIZ_PAINT_AZURE } else { paint } } pub fn viz_ink_from_paint(paint: u64) -> (u8, u8, u8) { @@ -1638,7 +1943,11 @@ pub fn with_viz_paint_glow(paint: u64, n: u8) -> u64 { } pub fn viz_hue_ui(paint: u64) -> u8 { - if paint == 0 { 150 } else { (paint & 0xFF) as u8 } + if paint == 0 { + 150 + } else { + (paint & 0xFF) as u8 + } } pub fn viz_sat_ui(paint: u64) -> u8 { @@ -1688,9 +1997,10 @@ pub fn with_viz_paint_strand_sat(paint: u64, sat: u8) -> u64 { /// Drop the chosen strand colour: the dual half of a ring goes back to the /// automatic complement, and both strand bytes go with the flag. pub fn viz_strand_clear(paint: u64) -> u64 { - paint & !(VIZ_STRAND_CHOSEN - | (0xFF_u64 << VIZ_STRAND_HUE_SHIFT) - | (0xFF_u64 << VIZ_STRAND_SAT_SHIFT)) + paint + & !(VIZ_STRAND_CHOSEN + | (0xFF_u64 << VIZ_STRAND_HUE_SHIFT) + | (0xFF_u64 << VIZ_STRAND_SAT_SHIFT)) } /// `#RRGGBB` for an ink, at the same fixed value the painter draws at, so @@ -1837,8 +2147,7 @@ fn viz_stamp( if x < 0 || row < 0 || x >= w as i32 || row >= h as i32 { return; } - let lum = - (f32::from(bg_y) + (f32::from(ink_y) - f32::from(bg_y)) * fall.clamp(0.0, 1.0)) as u8; + let lum = (f32::from(bg_y) + (f32::from(ink_y) - f32::from(bg_y)) * fall.clamp(0.0, 1.0)) as u8; let idx = row as usize * w + x as usize; if lum > y[idx] { y[idx] = lum; @@ -1871,7 +2180,9 @@ fn viz_span( ) { let (a, b) = if top <= bot { (top, bot) } else { (bot, top) }; for row in a..=b { - viz_stamp(y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v); + viz_stamp( + y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v, + ); } } @@ -1935,7 +2246,22 @@ fn viz_line( let d2 = (ox * ox + oy * oy) as f32; (-0.45 * d2 / (g * g).max(1) as f32).exp() }; - viz_stamp(y, u, v, w, h, cw, ch, x0 + ox, y0 + oy, fall, bg_y, ink_y, ink_u, ink_v); + viz_stamp( + y, + u, + v, + w, + h, + cw, + ch, + x0 + ox, + y0 + oy, + fall, + bg_y, + ink_y, + ink_u, + ink_v, + ); } } if x0 == x1 && y0 == y1 { @@ -2034,7 +2360,14 @@ fn viz_chain( ink_v: u8, glow: u8, ) { - let VizScratch { pts, chain, rows, cand, hull, .. } = scratch; + let VizScratch { + pts, + chain, + rows, + cand, + hull, + .. + } = scratch; chain.clear(); for pair in pts.windows(2) { viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, chain); @@ -2047,7 +2380,9 @@ fn viz_chain( // full ink -- which is exactly what the row/by/band machinery below // works out, one sort later. for &(x, row) in chain.iter() { - viz_stamp(y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v); + viz_stamp( + y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v, + ); } return; } @@ -2173,7 +2508,9 @@ fn viz_chain( } else { (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp() }; - viz_stamp(y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v); + viz_stamp( + y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v, + ); } } } @@ -2197,7 +2534,15 @@ pub(crate) fn visualizer_i420( flags: u8, paint: u64, ) -> (Vec, Vec, Vec) { - visualizer_window_i420(scratch, &VizView::whole(peaks), t_secs, width, height, flags, paint) + visualizer_window_i420( + scratch, + &VizView::whole(peaks), + t_secs, + width, + height, + flags, + paint, + ) } /// The envelope a visualizer frame is painted from: the whole file, or one @@ -2404,12 +2749,36 @@ pub(crate) fn visualizer_window_i420( for dy in 1..=glow { let fall = 0.5 / dy as f32; viz_stamp( - &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row - dy, fall, bg_y, - ink_y, ink_u, ink_v, + &mut y, + &mut u, + &mut v, + w, + h, + cw, + ch, + col as i32, + row - dy, + fall, + bg_y, + ink_y, + ink_u, + ink_v, ); viz_stamp( - &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row + dy, fall, bg_y, - ink_y, ink_u, ink_v, + &mut y, + &mut u, + &mut v, + w, + h, + cw, + ch, + col as i32, + row + dy, + fall, + bg_y, + ink_y, + ink_u, + ink_v, ); } } @@ -2474,9 +2843,10 @@ pub(crate) fn visualizer_window_i420( VIZ_STYLE_WAVE => { scratch.pts.clear(); for col in 0..w { - scratch - .pts - .push((col as i32, (center - scratch.sig[col] * half).round() as i32)); + scratch.pts.push(( + col as i32, + (center - scratch.sig[col] * half).round() as i32, + )); } let glow = viz_glow_of(paint); if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) { @@ -2488,8 +2858,7 @@ pub(crate) fn visualizer_window_i420( } } else { viz_chain( - &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v, - glow, + &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v, glow, ); } } @@ -2507,12 +2876,36 @@ pub(crate) fn visualizer_window_i420( for dy in 1..=glow { let fall = 0.55 / dy as f32; viz_stamp( - &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, top - dy, fall, bg_y, - ink_y, ink_u, ink_v, + &mut y, + &mut u, + &mut v, + w, + h, + cw, + ch, + col as i32, + top - dy, + fall, + bg_y, + ink_y, + ink_u, + ink_v, ); viz_stamp( - &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, bot + dy, fall, bg_y, - ink_y, ink_u, ink_v, + &mut y, + &mut u, + &mut v, + w, + h, + cw, + ch, + col as i32, + bot + dy, + fall, + bg_y, + ink_y, + ink_u, + ink_v, ); } } @@ -2567,6 +2960,7 @@ fn run_hw( render: &mut Render, abort: &Abort, speed: Speed, + failure: &DecodeFailure, ) -> bool { let mut index = start_frame; // Pictures dropped for being late since the last one handed over; see @@ -2606,10 +3000,15 @@ fn run_hw( } Ok(None) => return true, Err(e) => { + // Before the first picture this is not a failure to report but + // the signal that software should take over, and it is reported + // by the caller that does the falling back -- saying it here as + // well would put a fault on the strip for a span that is about + // to decode cleanly. if index == start_frame { return false; } - eprintln!("hardware decode error at frame {index}: {e}"); + failure.set(format!("hardware decode error at frame {index}: {e}")); return true; } } @@ -2695,7 +3094,10 @@ mod tests { "deferred open returned in {returned:?}, first frame at {first_frame:?}; \ sync open returned in {sync_returned:?}" ); - assert_eq!(frame.index, 0, "the deferred worker starts where it is told"); + assert_eq!( + frame.index, 0, + "the deferred worker starts where it is told" + ); assert!( returned < Duration::from_millis(10), "the caller waited {returned:?} -- something is still being read \ @@ -2848,7 +3250,10 @@ mod tests { let w = 320u32; let h = 180u32; let (y, _u, _v) = visualizer_i420(&mut VizScratch::default(), &[], 0.0, w, h, 1, 0); - assert_eq!((y.len(), _u.len(), _v.len()), (320 * 180, 160 * 90, 160 * 90)); + assert_eq!( + (y.len(), _u.len(), _v.len()), + (320 * 180, 160 * 90, 160 * 90) + ); // The ink's top and bottom row for a given peaks slice: one unbroken // band, and where it sits. let band = |peaks: &[(f32, f32)]| { @@ -3023,6 +3428,7 @@ mod tests { }; let (tx, rx) = sync_channel(2); let cell = BackendCell::new(Backend::Opening); + let failure = DecodeFailure::default(); run_span( &path, &mut source, @@ -3039,6 +3445,7 @@ mod tests { }, &abort, &cell, + &failure, ); assert_eq!( cell.get(), @@ -3049,6 +3456,11 @@ mod tests { rx.try_recv().is_err(), "a gap decodes nothing: no picture may come down the channel" ); + assert!( + failure.reason().is_some(), + "and it says why: a span that decoded nothing is the one case where \ + a closed channel is definitely not the end of the file" + ); } #[test] @@ -3059,10 +3471,14 @@ mod tests { *p = (-a.abs(), a.abs()); } let flags = 1u8; - let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0); + let (y, u, v) = + visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0); let ink = y.iter().filter(|&&p| p > 40).count(); assert!(ink > 200, "envelope missing: {ink}"); - assert!(ink < y.len() * 9 / 10, "solid frame, not an envelope: {ink}"); + assert!( + ink < y.len() * 9 / 10, + "solid frame, not an envelope: {ink}" + ); let mut blue = 0usize; for i in 0..u.len() { if u[i] > 145 && v[i] < 120 { @@ -3072,13 +3488,22 @@ mod tests { assert!(blue > 10, "default ink was not timeline blue: {blue}"); let ring = with_viz_style(flags, VIZ_STYLE_RING); - let (yr, _, _) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0); + let (yr, _, _) = + visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0); let ring_ink = yr.iter().filter(|&&p| p > 40).count(); assert!(ring_ink > 80, "ring missing: {ring_ink}"); assert!(ring_ink < ink, "ring should be a stroke, not a fill"); let hue_paint = with_viz_paint_hue(0, 40); - let (_, u2, v2) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 64, 32, flags, hue_paint); + let (_, u2, v2) = visualizer_i420( + &mut VizScratch::default(), + &peaks, + 1.0, + 64, + 32, + flags, + hue_paint, + ); let mut shifted = 0usize; for i in 0..u2.len() { if u2[i] < 120 && v2[i] > 130 { @@ -3175,7 +3600,15 @@ mod tests { } let ring = with_viz_style(1, VIZ_STYLE_RING); let auto = VIZ_PAINT_AZURE; - let (y0, u0, v0) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, auto); + let (y0, u0, v0) = visualizer_i420( + &mut VizScratch::default(), + &peaks, + 1.0, + 320, + 180, + ring, + auto, + ); // The automatic dual is half a wheel from the clip's hue at the // clip's own saturation; choosing exactly that colour changes @@ -3185,24 +3618,54 @@ mod tests { viz_sat_ui(auto), ); assert!(viz_strand_set(same)); - let (ys, us, vs) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, same); - assert_eq!(ys, y0, "the automatic complement, spelled out, is the same frame"); + let (ys, us, vs) = visualizer_i420( + &mut VizScratch::default(), + &peaks, + 1.0, + 320, + 180, + ring, + same, + ); + assert_eq!( + ys, y0, + "the automatic complement, spelled out, is the same frame" + ); assert_eq!(us, u0); assert_eq!(vs, v0); // A colour of its own repaints the dual strands in it. let red = with_viz_paint_strand_sat(with_viz_paint_strand_hue(auto, 0), 255); - let (_, u1, v1) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, red); - let red_px = (0..u1.len()).filter(|&i| u1[i] < 110 && v1[i] > 200).count(); - let auto_px = (0..u0.len()).filter(|&i| u0[i] < 110 && v0[i] > 200).count(); - assert!(red_px > 20, "the chosen colour did not reach the frame: {red_px}"); - assert_eq!(auto_px, 0, "the automatic ring already painted red: {auto_px}"); + let (_, u1, v1) = + visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, red); + let red_px = (0..u1.len()) + .filter(|&i| u1[i] < 110 && v1[i] > 200) + .count(); + let auto_px = (0..u0.len()) + .filter(|&i| u0[i] < 110 && v0[i] > 200) + .count(); + assert!( + red_px > 20, + "the chosen colour did not reach the frame: {red_px}" + ); + assert_eq!( + auto_px, 0, + "the automatic ring already painted red: {auto_px}" + ); // ...and the flag is what decides: strand bytes with it clear are // the unset picture, byte for byte. let stale = auto | (77u64 << 32) | (9u64 << 40); assert!(!viz_strand_set(stale)); - let (yt, ut, vt) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, stale); + let (yt, ut, vt) = visualizer_i420( + &mut VizScratch::default(), + &peaks, + 1.0, + 320, + 180, + ring, + stale, + ); assert_eq!(yt, y0, "an unset strand colour is the frame it always was"); assert_eq!(ut, u0); assert_eq!(vt, v0); @@ -3250,7 +3713,15 @@ mod tests { }; let flags = with_viz_style(1, style); let paint = with_viz_paint_glow(VIZ_PAINT_AZURE, glow); - let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 37.5, 1920, 1080, flags, paint); + let (y, u, v) = visualizer_i420( + &mut VizScratch::default(), + &peaks, + 37.5, + 1920, + 1080, + flags, + paint, + ); let mut hash = 0xcbf2_9ce4_8422_2325u64; for buf in [&y, &u, &v] { for &b in buf.iter() { @@ -3287,6 +3758,7 @@ fn run( render: &mut Render, abort: &Abort, speed: Speed, + failure: &DecodeFailure, ) { // A decoder per span, and cheap: it is a parameter-set map and a picture // buffer, while the *demuxer* -- whose index cost seconds to build -- is the @@ -3324,19 +3796,19 @@ fn run( Ok(Some(au)) => { let packet = Packet::new(0, TimeBase::new(1, 1), au); if let Err(e) = decoder.send_packet(&packet) { - eprintln!("decode error at access unit {index}: {e}"); + failure.set(format!("decode error at access unit {index}: {e}")); break; } } Ok(None) => { flushed = true; if let Err(e) = decoder.flush() { - eprintln!("decode error at end of stream: {e}"); + failure.set(format!("decode error at end of stream: {e}")); break; } } Err(e) => { - eprintln!("demux error: {e}"); + failure.set(format!("demux error: {e}")); break; } } @@ -3347,7 +3819,7 @@ fn run( Ok(pic) => pic, Err(e) if e.is_need_more() || e.is_eof() => break, Err(e) => { - eprintln!("decode error at access unit {index}: {e}"); + failure.set(format!("decode error at access unit {index}: {e}")); break; } }; @@ -3474,6 +3946,7 @@ fn run_av1( render: &mut Render, abort: &Abort, speed: Speed, + failure: &DecodeFailure, ) { // Signed, for the same reason [`run`]'s is: the landing sync sample can // sit inside what an mp4's edit list trims, i.e. before frame 0. @@ -3505,7 +3978,7 @@ fn run_av1( } Ok(None) => demux_dry = true, Err(e) => { - eprintln!("demux error: {e}"); + failure.set(format!("demux error: {e}")); return; } } @@ -3561,12 +4034,11 @@ fn run_av1( // the pictures decoded so far stand and the span ends. if let Err(e) = decode { if !done { - eprintln!("software AV1 decode failed at frame {index}: {e}"); + failure.set(format!("software AV1 decode failed at frame {index}: {e}")); done = true; } } } - } /// Converts one decoded picture and queues it. `true` when the consumer went diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 6b20c8d..dfbf328 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -62,8 +62,8 @@ use std::sync::{Arc, Mutex}; use std::thread; use ec_core::frame::VideoFrame; -use ec_core::registry::{CodecId, CodecParameters}; use ec_core::registry::Decoder as _; +use ec_core::registry::{CodecId, CodecParameters}; use ec_core::{Packet, TimeBase}; use ec_h264::{Encoder, EncoderConfig, H264Decoder, PictureView, Preset}; use ec_h265::encoder::{Encoder as HevcEncoder, EncoderConfig as HevcEncoderConfig, RateControl}; @@ -86,7 +86,7 @@ use crate::mux::{ AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, }; use crate::project::{Lane, LaneKind, Project, Rate}; -use crate::scale::{blend_i420, Composer}; +use crate::scale::{Composer, blend_i420}; use crate::subtitle::{Cue, SubtitleTrack}; use crate::tonemap::{self, ToneMapper}; use crate::transform::TransformParams; @@ -559,84 +559,84 @@ pub fn start( 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 - // opens a span, and nothing here knows such a thing exists. Printed so - // that "the delivery came off the film itself" is a grep rather than a - // belief. - for source in project.sources() { - eprintln!("export source: {}", source.path.display()); - } - // The rename is the last step and the only one that publishes a file - // under the name the caller asked for; it stays on the same directory, - // so it is atomic. - // - // An emptied timeline is a legal project and an illegal file: no - // picture, no sound, and a muxer that is never created because no coded - // frame arrives. Refused by name here -- before the format is even - // looked at, so an mp4 and a WAV refuse in the same words -- rather than - // left to write a file of no frames that nothing opens. Every caller of - // `start` comes through this, the app's own door - // (`PlaybackSession::is_empty`) being only the first fence. - // - // An audio-only timeline is the other legal project no mp4 can be made - // of: every frame of it is a gap, so the file would be black picture - // over the sound -- minutes of encoding for a video of nothing. Refused - // by name, with the two formats that *are* that timeline, rather than - // written; the app says the same on the format row before a destination - // is even picked (`mp4_refusal`). - let written = match settings.format { - _ if project.timeline_frames() == 0 => { - Err("the timeline is empty: there is nothing to export".into()) + // 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 + // opens a span, and nothing here knows such a thing exists. Printed so + // that "the delivery came off the film itself" is a grep rather than a + // belief. + for source in project.sources() { + eprintln!("export source: {}", source.path.display()); } - format if format.has_video() && !has_picture(&project) => Err(format!( - "the timeline has no picture: {} would be black. Export WAV, \ + // The rename is the last step and the only one that publishes a file + // under the name the caller asked for; it stays on the same directory, + // so it is atomic. + // + // An emptied timeline is a legal project and an illegal file: no + // picture, no sound, and a muxer that is never created because no coded + // frame arrives. Refused by name here -- before the format is even + // looked at, so an mp4 and a WAV refuse in the same words -- rather than + // left to write a file of no frames that nothing opens. Every caller of + // `start` comes through this, the app's own door + // (`PlaybackSession::is_empty`) being only the first fence. + // + // An audio-only timeline is the other legal project no mp4 can be made + // of: every frame of it is a gap, so the file would be black picture + // over the sound -- minutes of encoding for a video of nothing. Refused + // by name, with the two formats that *are* that timeline, rather than + // written; the app says the same on the format row before a destination + // is even picked (`mp4_refusal`). + let written = match settings.format { + _ if project.timeline_frames() == 0 => { + Err("the timeline is empty: there is nothing to export".into()) + } + format if format.has_video() && !has_picture(&project) => Err(format!( + "the timeline has no picture: {} would be black. Export WAV, \ FLAC or MP3, which are the sound itself", - format.name() - ) - .into()), - format if format.has_video() => { - let first = run(&project, &meta, &part, &worker, &settings, sample_rate); - match first { - // The hardware encoder's *process* died under the driver - // ([`crate::hwproc`]) -- the editor is still here, and the - // file is still owed. Written again by the software encoder - // for this codec, from the first frame: the pictures the - // dead seat coded are not ones this one may continue from. - // - // Not where a person picked the GPU by name: that export - // refuses in words, the same answer [`hw_seat`] already - // gives a machine with no seat at all, rather than quietly - // spending an hour in an encoder nobody chose. - Err(e) - if crate::hwproc::is_lost(&e) - && settings.seat != EncoderSeat::Hardware => - { - eprintln!("export video: {e}; writing it again in software"); - let _ = std::fs::remove_file(&part); - // The bar is *not* put back to zero: the rerun writes - // it with `fetch_max` like everything else - // ([`Shared::progress`]), so it holds where the dead - // seat left it and moves again once the software - // encoder passes that mark. A person whose GPU has just - // died is the last one who should also watch the bar - // run backwards. - let mut software = settings.clone(); - software.seat = EncoderSeat::Software; - run(&project, &meta, &part, &worker, &software, sample_rate) + format.name() + ) + .into()), + format if format.has_video() => { + let first = run(&project, &meta, &part, &worker, &settings, sample_rate); + match first { + // The hardware encoder's *process* died under the driver + // ([`crate::hwproc`]) -- the editor is still here, and the + // file is still owed. Written again by the software encoder + // for this codec, from the first frame: the pictures the + // dead seat coded are not ones this one may continue from. + // + // Not where a person picked the GPU by name: that export + // refuses in words, the same answer [`hw_seat`] already + // gives a machine with no seat at all, rather than quietly + // spending an hour in an encoder nobody chose. + Err(e) + if crate::hwproc::is_lost(&e) + && settings.seat != EncoderSeat::Hardware => + { + eprintln!("export video: {e}; writing it again in software"); + let _ = std::fs::remove_file(&part); + // The bar is *not* put back to zero: the rerun writes + // it with `fetch_max` like everything else + // ([`Shared::progress`]), so it holds where the dead + // seat left it and moves again once the software + // encoder passes that mark. A person whose GPU has just + // died is the last one who should also watch the bar + // run backwards. + let mut software = settings.clone(); + software.seat = EncoderSeat::Software; + run(&project, &meta, &part, &worker, &software, sample_rate) + } + other => other, } - other => other, } + _ => run_audio(&project, &meta, &part, &worker, &settings, sample_rate), + }; + let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); + if result.is_err() { + // The muxer -- and with it the file handle -- died with `run`. + let _ = std::fs::remove_file(&part); } - _ => run_audio(&project, &meta, &part, &worker, &settings, sample_rate), - }; - let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); - if result.is_err() { - // The muxer -- and with it the file handle -- died with `run`. - let _ = std::fs::remove_file(&part); - } - settle(&worker, result); + settle(&worker, result); })); if let Err(payload) = caught { // The body above panicked before it could settle its own slot -- @@ -654,7 +654,10 @@ pub fn start( // a panic never reaches. Done inside this branch only -- a body // that *did* settle has already renamed or deleted the file. let _ = std::fs::remove_file(&part); - settle(&panic_worker, Err(format!("export worker panicked: {message}").into())); + settle( + &panic_worker, + Err(format!("export worker panicked: {message}").into()), + ); } } }); @@ -710,10 +713,12 @@ fn mastered(project: &Project) -> bool { /// packet copy carries neither an equalizer nor a fade. An mp4 whose timeline /// has one is decoded and re-encoded so the fade actually reaches the file. fn faded(project: &Project) -> bool { - project - .audio_lanes() - .into_iter() - .any(|lane| project.lane(lane).iter().any(|c| c.fade_in > 0 || c.fade_out > 0)) + project.audio_lanes().into_iter().any(|lane| { + project + .lane(lane) + .iter() + .any(|c| c.fade_in > 0 || c.fade_out > 0) + }) } /// The bitrate an export codes at: the caller's number clamped into what an @@ -1439,7 +1444,10 @@ fn planned_lanes(project: &Project, format: Format, lanes: &[Lane]) -> String { // Drawn over the picture, written into no file -- the same sentence // a picked track gets, because it is the track and not the lane that // cannot be carried. - dropped.push(format!("{label} {} — pictures; drawn, not written", t.label)); + dropped.push(format!( + "{label} {} — pictures; drawn, not written", + t.label + )); } else if first.start >= end { dropped.push(format!("{label} {name}— past the last picture")); } else { @@ -1480,12 +1488,15 @@ fn planned_lanes(project: &Project, format: Format, lanes: &[Lane]) -> String { /// Costs that open (~100 ms here): ask it off a render thread and keep the /// answer until the format, the resolution or the bitrate changes. pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> { - settings.format.has_video().then(|| match hw_seat(meta, settings) { - Ok(hw) => video_label(settings.format, hw.is_some()), - // The seat the settings demand and this machine has not: the very - // refusal [`start`] would settle with, said on the card instead. - Err(_) => NO_HW_SEAT, - }) + settings + .format + .has_video() + .then(|| match hw_seat(meta, settings) { + Ok(hw) => video_label(settings.format, hw.is_some()), + // The seat the settings demand and this machine has not: the very + // refusal [`start`] would settle with, said on the card instead. + Err(_) => NO_HW_SEAT, + }) } /// What [`start`] would open for *this* timeline: the picture's seat -- or the @@ -1781,7 +1792,11 @@ struct CopyRegion { /// clip -- which the same format would carry exactly if the edit let it, so /// those six [`CopyPlan::of`] gates are named together rather than picked /// apart into six different sentences. -pub fn exact_refusal(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option { +pub fn exact_refusal( + project: &Project, + meta: &VideoMeta, + settings: &ExportSettings, +) -> Option { if !settings.exact || CopyPlan::of(project, meta, settings).is_some() { return None; } @@ -2246,9 +2261,9 @@ fn encode_audio( let out_frames = range.map_or(project.media_frames(), |(s, e)| { e.min(project.media_frames()).saturating_sub(s) }); - let total = - (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() as usize - * channels; + let total = (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() + as usize + * channels; let mut samples: Vec = Vec::with_capacity(total); for chunk in chunks { // The only place a cancelled export can be answered before the whole @@ -2567,9 +2582,15 @@ fn opus_fidelity( for w in 0..FIDELITY_WINDOWS { let at = w * step; let from = at.saturating_sub(FIDELITY_WARMUP); - let Some(fidelity) = - window_fidelity(packets, samples, pre_skip, channels, from, at, at + FIDELITY_WINDOW) - else { + let Some(fidelity) = window_fidelity( + packets, + samples, + pre_skip, + channels, + from, + at, + at + FIDELITY_WINDOW, + ) else { continue; // silence: nothing to correlate, and not a failure }; scores.push(fidelity); @@ -2758,9 +2779,9 @@ fn run( // The range's own length where one is marked, the media's otherwise -- // `export_spans` walks the same window, so `done` ends on this `total` // exactly as it always did. - let total = settings - .range - .map_or(project.media_frames(), |(s, e)| e.min(project.media_frames()).saturating_sub(s)); + let total = settings.range.map_or(project.media_frames(), |(s, e)| { + e.min(project.media_frames()).saturating_sub(s) + }); // The two preview switches are the H.264 mp4 pair's alone. Only that // container carries a colour of its own back out ([`write_video`] tags it // there), so asking any other for a source-space file would write pictures @@ -2807,12 +2828,8 @@ fn run( // of the two. On this project's own film that is 168 s of AC-3 that no // longer stands in front of 733 s of hardware H.264. let audio_job = { - let (project, meta, settings, shared) = ( - project.clone(), - *meta, - settings.clone(), - Arc::clone(shared), - ); + let (project, meta, settings, shared) = + (project.clone(), *meta, settings.clone(), Arc::clone(shared)); thread::Builder::new() .name("export-audio".into()) .spawn(move || { @@ -2955,7 +2972,15 @@ fn run( // it replaced -- and the sound says whether it was copied or encoded, which // only `copy_audio` knows and, on the overlapped path, does not know yet. let seat = encoder.label(); - publish_seats(shared, seat, project, settings, sound, opus, audio_job.running()); + publish_seats( + shared, + seat, + project, + settings, + sound, + opus, + audio_job.running(), + ); // When the picture started, so the stage line below can say where under it // the sound landed -- the one number that says whether the two passes // really overlapped, in the same voice as `encode_audio`'s own timers. @@ -2994,9 +3019,8 @@ fn run( // A's pixels on the CPU, so a dissolving span never asks for a GPU // buffer, not even outside its own window. let dissolve = dissolve_window(project, &span); - let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) = - match span.from - { + let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) = match span.from + { Some((source, in_frame)) => { let entry = sources .get(source) @@ -3046,7 +3070,15 @@ fn run( } else { ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)? }; - (Some(pictures), rate, in_frame, Some(color), mapper, rotation, pixel_aspect) + ( + Some(pictures), + rate, + in_frame, + Some(color), + mapper, + rotation, + pixel_aspect, + ) } // A gap's black is 16/128/128, which is black in every matrix here // and on every curve: nothing to remap and nothing to tone-map, @@ -3105,52 +3137,54 @@ fn run( // files together for exactly the frames the tail below blends, and // nothing else in this span ever touches it. let mut b = dissolve - .map(|(b_source, b_in_frame, window, b_start)| -> crate::Result<_> { - let entry = sources.get(b_source).ok_or_else(|| { - format!("clip names source {b_source} of {}", sources.len()) - })?; - let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source]; - let b_mapper = tone[b_source].as_ref(); - let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix); - Ok(Dissolve { - window, - tail_start: span.len - window, - decoder: if crate::is_audio(&entry.path) - || project.composite_visualizer_at(b_start) & 1 != 0 - { - ClipDecoder::visualizer( - &entry.path, - entry.audio_stream, - b_rate.source_at(b_in_frame), + .map( + |(b_source, b_in_frame, window, b_start)| -> crate::Result<_> { + let entry = sources.get(b_source).ok_or_else(|| { + format!("clip names source {b_source} of {}", sources.len()) + })?; + let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source]; + let b_mapper = tone[b_source].as_ref(); + let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix); + Ok(Dissolve { + window, + tail_start: span.len - window, + decoder: if crate::is_audio(&entry.path) + || project.composite_visualizer_at(b_start) & 1 != 0 + { + ClipDecoder::visualizer( + &entry.path, + entry.audio_stream, + b_rate.source_at(b_in_frame), + meta.width, + meta.height, + meta.frame_rate, + project.composite_visualizer_at(b_start), + project.composite_viz_paint_at(b_start), + )? + } else { + ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)? + }, + mapper: b_mapper, + remap: b_remap, + grade: project.composite_color_at(b_start).copied(), + transform: project + .composite_transform_at(b_start) + .copied() + .unwrap_or_default(), + rotation: b_rotation, + pixel_aspect: b_pixel_aspect, + canvas: Composer::new( meta.width, meta.height, - meta.frame_rate, - project.composite_visualizer_at(b_start), - project.composite_viz_paint_at(b_start), - )? - } else { - ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)? - }, - mapper: b_mapper, - remap: b_remap, - grade: project.composite_color_at(b_start).copied(), - transform: project - .composite_transform_at(b_start) - .copied() - .unwrap_or_default(), - rotation: b_rotation, - pixel_aspect: b_pixel_aspect, - canvas: Composer::new( - meta.width, - meta.height, - project.composite_fit_at(b_start), - ), - rotated: (Vec::new(), Vec::new(), Vec::new()), - stretched: (Vec::new(), Vec::new(), Vec::new()), - graded: (Vec::new(), Vec::new(), Vec::new()), - transformed: (Vec::new(), Vec::new(), Vec::new()), - }) - }) + project.composite_fit_at(b_start), + ), + rotated: (Vec::new(), Vec::new(), Vec::new()), + stretched: (Vec::new(), Vec::new(), Vec::new()), + graded: (Vec::new(), Vec::new(), Vec::new()), + transformed: (Vec::new(), Vec::new(), Vec::new()), + }) + }, + ) .transpose()?; // Timeline frames, taken a *source* frame at a time: at a rate other // than real time the two are not the same count, and the span says which @@ -3287,9 +3321,21 @@ fn run( } Some(Frame::Pixels(by, bu, bv, bw, bh)) => { let (by, bu, bv, _, _) = place_picture( - by, bu, bv, bw, bh, d.rotation, d.pixel_aspect, d.grade, - d.transform, d.remap, d.mapper, &mut d.rotated, - &mut d.stretched, &mut d.graded, &mut d.transformed, + by, + bu, + bv, + bw, + bh, + d.rotation, + d.pixel_aspect, + d.grade, + d.transform, + d.remap, + d.mapper, + &mut d.rotated, + &mut d.stretched, + &mut d.graded, + &mut d.transformed, &mut d.canvas, ); let idx_in_window = done_here + r - d.tail_start; @@ -3470,7 +3516,9 @@ fn place_picture<'a>( display_width.div_ceil(2) as usize, height.div_ceil(2) as usize, ); - stretched.0.resize(display_width as usize * height as usize, 0); + stretched + .0 + .resize(display_width as usize * height as usize, 0); stretched.1.resize(dcw * dch, 0); stretched.2.resize(dcw * dch, 0); crate::scale::scale_i420( @@ -3549,7 +3597,13 @@ fn place_picture<'a>( } else { let (py, pu, pv, w, h) = canvas.place_transformed(y, u, v, width, height, &transform); *transformed = (py, pu, pv); - (&transformed.0[..], &transformed.1[..], &transformed.2[..], w, h) + ( + &transformed.0[..], + &transformed.1[..], + &transformed.2[..], + w, + h, + ) } } @@ -3594,7 +3648,10 @@ fn source_rate( // `decode::rgb_to_i420` is the one matrix that turns its pixels into // planes. A song has no picture and the answer is never read. Neither // has a display matrix to be turned by, nor an aspect to be widened - // by: both are authored square. + // by: both are authored square. A still's *EXIF* turn is not in this + // arm either, and for a better reason -- `decode::Still::open` already + // made it before the planes were written, so `place_picture` is handed + // the picture the preview showed and must not be told to turn it again. return ( Rate::REAL_TIME, ColorDescription::default(), @@ -3694,9 +3751,8 @@ fn run_audio( }; // The picture path's line, for a file that is sound alone: there is sound // by the line above, so this names the encoder writing it. - *shared.encoders.lock().unwrap() = Some( - audio_label(project, format, true, None, settings.range.is_some()).to_string(), - ); + *shared.encoders.lock().unwrap() = + Some(audio_label(project, format, true, None, settings.range.is_some()).to_string()); let channels = usize::from(audio.channels); let out_frames = settings.range.map_or(project.media_frames(), |(s, e)| { e.min(project.media_frames()).saturating_sub(s) @@ -4516,9 +4572,7 @@ impl Enc { cfg.timing = Some((fps_den, fps_num)); cfg.video_signal_type = Some(video_signal_type(meta.height)); cfg.threads = per_lane; - lanes.push( - HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?, - ); + lanes.push(HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?); } Ok(Self::Hevc(HevcEnc { pending: Vec::new(), @@ -4579,7 +4633,9 @@ impl Enc { // them is a sync point -- said as a constant rather than parsed back // out of the bitstream, because it is this encoder's configuration // and not a driver's choice. - Self::HevcHw(hw) => Ok(hw.encode(y, u, v, width, height, true)?.map(|au| (au, true))), + Self::HevcHw(hw) => Ok(hw + .encode(y, u, v, width, height, true)? + .map(|au| (au, true))), Self::Hevc(hevc) => { // The display-size planes are kept as they came: `ec-h265` // pads to its own coded grid and crops back through the SPS @@ -4970,7 +5026,11 @@ impl ClipDecoder { .ok() .flatten() .unwrap_or_default(); - let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 }; + let fps = if fps.is_finite() && fps > 0.0 { + fps + } else { + 30.0 + }; Ok(Self::Visualizer { peaks, width, @@ -5236,9 +5296,7 @@ impl SwDecoder { // either answer means go back for the next access unit. Err(e) if e.is_eof() && self.flushed => return Ok(false), Err(e) if e.is_need_more() || e.is_eof() => {} - Err(e) => { - return Err(format!("decode at picture {}: {e}", self.index).into()) - } + Err(e) => return Err(format!("decode at picture {}: {e}", self.index).into()), } } } @@ -5767,7 +5825,11 @@ mod tests { // 1280 * 720 * 30 * 0.1 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); assert_eq!(bitrate_for(&meta(320, 240, 30.0)), 230_400, "tiny"); - assert_eq!(bitrate_for(&meta(160, 120, 15.0)), MIN_BITRATE, "tinier floors"); + assert_eq!( + bitrate_for(&meta(160, 120, 15.0)), + MIN_BITRATE, + "tinier floors" + ); assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge"); // A rate somebody typed goes through untouched to its own ceiling, which // is above where the derived one stops: the card offers 50 Mbps, and a @@ -5799,7 +5861,11 @@ mod tests { fn a_fade_forces_the_audio_to_be_re_encoded() { let mut project = Project::single("/nonexistent/film.mp4", 90); assert!(!forces_encode(&project, false), "flat, so a copy is fine"); - assert!(project.set_fade_in(crate::project::Lane::new(crate::project::LaneKind::Audio, 0), 0, 15)); + assert!(project.set_fade_in( + crate::project::Lane::new(crate::project::LaneKind::Audio, 0), + 0, + 15 + )); assert!( forces_encode(&project, false), "a fade-in on the only clip must force a re-encode" @@ -5908,7 +5974,11 @@ mod tests { /// B, and the window itself never quite repeats a hard cut's own instant. #[test] fn dissolve_weight_ramps_strictly_between_zero_and_one() { - assert_eq!(dissolve_weight(0, 1), 0.5, "a one-frame window is the midpoint"); + assert_eq!( + dissolve_weight(0, 1), + 0.5, + "a one-frame window is the midpoint" + ); assert_eq!(dissolve_weight(0, 4), 0.2); assert_eq!(dissolve_weight(1, 4), 0.4); assert_eq!(dissolve_weight(2, 4), 0.6); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 03f9b56..37ecb69 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -15,6 +15,7 @@ pub mod export; pub mod hw; pub mod hwproc; pub mod limiter; +pub(crate) mod map; pub mod mux; pub mod playback; pub mod project; @@ -23,11 +24,10 @@ pub mod real_library; pub mod scale; pub mod scratch; pub mod silence; +pub(crate) mod stretch; pub mod subtitle; -pub(crate) mod map; #[cfg(test)] mod sweep; -pub(crate) mod stretch; pub mod tonemap; pub mod transform; pub mod waveform; @@ -36,7 +36,9 @@ pub use audio::{ AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession, StreamInfo, }; pub use clock::PlaybackClock; -pub use decode::{DecodeSession, Frame, image_size}; +pub use decode::{ + DecodeFailure, DecodeSession, Frame, UnsupportedStillOrientation, image_orientation, image_size, +}; pub use demux::{Codec, MediaBitrate, Rotation, UnsupportedRotation, VideoMeta, probe_bitrate}; pub use export::ExportHandle; pub use mux::{AudioParams, Mp4Muxer, VideoParams}; @@ -72,7 +74,17 @@ pub fn is_audio(path: &std::path::Path) -> bool { path.extension().and_then(|e| e.to_str()).is_some_and(|e| { matches!( e.to_ascii_lowercase().as_str(), - "mp3" | "mpeg" | "mpg" | "wav" | "flac" | "ogg" | "oga" | "opus" | "mka" | "m4a" | "aac" + "mp3" + | "mpeg" + | "mpg" + | "wav" + | "flac" + | "ogg" + | "oga" + | "opus" + | "mka" + | "m4a" + | "aac" ) }) } @@ -130,18 +142,8 @@ mod tests { #[test] fn is_audio_admits_the_containers_the_decoder_reads() { for name in [ - "song.mp3", - "a.WAV", - "b.flac", - "c.ogg", - "d.oga", - "e.m4a", - "f.aac", - "g.opus", - "h.OPUS", - "i.mka", - "j.MPEG", - "k.mpg", + "song.mp3", "a.WAV", "b.flac", "c.ogg", "d.oga", "e.m4a", "f.aac", "g.opus", "h.OPUS", + "i.mka", "j.MPEG", "k.mpg", ] { assert!(super::is_audio(Path::new(name)), "{name}"); } diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 10f753d..5976994 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -375,6 +375,10 @@ pub struct PlaybackSession { /// Replaced with the stream at every seek, so it always describes the /// pictures currently arriving and never the clip before them. backend: BackendCell, + /// Why the current span stopped before the end of its range, if it did. + /// Replaced with the stream at every seek for the same reason `backend` is, + /// and read by [`video_failure_reason`](Self::video_failure_reason). + video_failure: crate::decode::DecodeFailure, /// Workers cancelled by a seek or a clip change, waiting to be reaped. /// Joining one inline costs whatever VA-API init it is still inside (98 ms /// measured worst case), which is a visible hitch on the caller's thread; @@ -662,6 +666,7 @@ impl PlaybackSession { frames: stream.frames, worker: stream.worker, backend: stream.backend, + video_failure: stream.failure, retired: Vec::new(), restarts: 0, clock: PlaybackClock::new(source), @@ -792,6 +797,7 @@ impl PlaybackSession { frames: stream.frames, worker: stream.worker, backend: stream.backend, + video_failure: stream.failure, retired: Vec::new(), restarts: 0, // The song keeps the clock, as a video's own sound does -- and wall @@ -846,6 +852,10 @@ impl PlaybackSession { frame_count: image_frames(IMAGE_ONLY_RATE), codec: Codec::H264, color: ColorDescription::default(), + // `Rotation::None` is honest, not a shrug: a still's own turn was + // made in `Still::open`, before these planes were written, so the + // pair below is already the displayed one and there is nothing left + // for a consumer to make. rotation: Rotation::None, // No container said anything about these: the picture this engine // decoded itself is square pixels at the size it was decoded at. @@ -898,6 +908,7 @@ impl PlaybackSession { frames: stream.frames, worker: stream.worker, backend: stream.backend, + video_failure: stream.failure, retired: Vec::new(), restarts: 0, clock: PlaybackClock::new(ClockSource::Wall), @@ -1040,6 +1051,9 @@ impl PlaybackSession { frame_count: image_frames(frame_rate), codec: Codec::H264, color: ColorDescription::default(), + // `Rotation::None` is honest, not a shrug: `Still::open` + // made the file's own turn before these planes were + // written, so the pair below is already the displayed one. rotation: Rotation::None, // No container said anything about these: the picture this // engine decoded itself is square pixels at its own size. @@ -1285,6 +1299,7 @@ impl PlaybackSession { frames: stream.frames, worker: stream.worker, backend: stream.backend, + video_failure: stream.failure, retired: Vec::new(), restarts: 0, clock: PlaybackClock::new(match audio { @@ -1411,6 +1426,25 @@ impl PlaybackSession { self.audio_disabled.as_deref() } + /// Why the picture stopped short of the end of its range, if it did -- the + /// video twin of [`Self::audio_disabled_reason`], and the reason a corrupt + /// file used to be indistinguishable from a finished one. + /// + /// A closed frame channel is not an answer: a span that ran to the end of + /// the file and a span that gave up on a broken packet both drop the + /// sender, and [`Self::try_frame`] returns `None` for either. The app read + /// that as end-of-stream, so a file with a damaged middle froze on its last + /// good picture and the transport said ENDED -- no notice, no banner, and + /// nothing on the screen to say the film had stopped being the film. + /// + /// `None` for a span that played its whole range, which is the ordinary + /// case and the one that must stay silent: a notice that fires on every + /// film is a notice nobody reads. The reason is the engine's own words, for + /// the same reason the sound one is. + pub fn video_failure_reason(&self) -> Option { + self.video_failure.reason() + } + /// The files this timeline plays from, index 0 first -- a caller needs it /// to name an export or a window after the media rather than the project. pub fn sources(&self) -> &[Source] { diff --git a/crates/engine/tests/decode_failure.rs b/crates/engine/tests/decode_failure.rs new file mode 100644 index 0000000..20ebd56 --- /dev/null +++ b/crates/engine/tests/decode_failure.rs @@ -0,0 +1,161 @@ +//! A decode failure reaches the user, the way a lost sound device already does. +//! +//! A worker that ran to the end of a file and a worker that gave up on a +//! corrupt packet both drop the sender, and `try_frame` returns `None` for +//! either. The app read that as end-of-stream, so a file with a damaged middle +//! froze on its last good picture and the transport said ENDED: no notice, no +//! banner, and nothing on screen to say the film had stopped being the film. +//! The sound path has had a reason channel for a device that dies mid-session +//! all along; this is that channel's picture-side twin. +//! +//! The fixture is **built here**: `test_av.mp4`'s `moov` sits *after* its `mdat`, +//! so truncating the file would take the index with it. What is done instead is +//! what a download that dies mid-transfer leaves behind -- the tail of the +//! sample data overwritten, the container index intact and still claiming every +//! frame. The header and the first seconds stay valid, so frames really do +//! arrive before the failure, which is the whole shape of the bug. +//! +//! ```text +//! cargo test -p engine --test decode_failure -- --test-threads=1 +//! ``` + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use engine::PlaybackSession; +use engine::scratch::Scratch; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Software everywhere, so the suite proves the path every machine has. +fn pin_software() { + static PIN: std::sync::Once = std::sync::Once::new(); + PIN.call_once(|| unsafe { + std::env::set_var("VE_SW", "1"); + std::env::set_var("VE_SW_ENC", "1"); + }); +} + +/// `test_av.mp4` with the last eighth of its **sample data** overwritten, and +/// the file otherwise untouched: `moov` still claims every frame the header +/// ever did, and the demuxer hands the decoder exactly what it always handed +/// it. +/// +/// The damage is bounded to the `mdat` payload on purpose. `moov` sits *after* +/// `mdat` in this fixture, so a damage that ran to the end of the file would +/// take the index with it and leave a file that will not open at all -- a +/// different defect, reached before a single frame is decoded and invisible to +/// the thing this test is about. +/// +/// Returns the scratch guard too, so the directory goes when the test ends. +fn damaged() -> (Scratch, PathBuf) { + let bytes = std::fs::read(asset("test_av.mp4")).expect("the fixture"); + let (start, end) = mdat_payload(&bytes).expect("an mdat payload"); + let mut damaged_bytes = bytes; + let tail = start + (end - start) * 7 / 8; + damaged_bytes[tail..end].fill(0); + let scratch = Scratch::file("ve_decode_failure", "mp4"); + let path = PathBuf::from(&*scratch); + std::fs::write(&path, &damaged_bytes).expect("write the damaged fixture"); + (scratch, path) +} + +/// The `mdat` box's payload, start and end: the walk a container parser does, +/// four bytes at a time, and the reason the fixture is damaged rather than +/// truncated. +fn mdat_payload(bytes: &[u8]) -> Option<(usize, usize)> { + let mut at = 0usize; + while at + 8 <= bytes.len() { + let size = u32::from_be_bytes(bytes[at..at + 4].try_into().ok()?) as usize; + let kind = &bytes[at + 4..at + 8]; + if size < 8 { + return None; + } + if kind == b"mdat" { + return Some((at + 8, (at + size).min(bytes.len()))); + } + at += size; + } + None +} + +/// Plays `path` to its end and answers what the transport would show and what +/// the session says went wrong. +fn play_to_the_end(path: &std::path::Path) -> (u32, Option) { + let mut session = PlaybackSession::open(path).expect("open the file"); + // A seek rather than a play: this wants the whole span decoded whatever the + // clock says, and a paused session still decodes -- which is what a scrub + // does, and is the same worker either way. + session.seek(0.0); + let started = Instant::now(); + let mut frames = 0u32; + // The loop runs on the session's own end-of-stream flag rather than on the + // frame channel, because **that is the bug**: a closed channel and a clean + // end of file are one event to a caller that only has the channel, and the + // app reads that event as the film finishing. Draining on the flag is what + // a fixed caller does, and the reason has to be found somewhere else. + while !session.is_eos() { + if let Some(frame) = session.try_frame() { + frames = frame.index + 1; + } + assert!( + started.elapsed() < Duration::from_secs(60), + "the session never reported an end of stream" + ); + std::thread::sleep(Duration::from_millis(1)); + } + // The worker sets the reason as it gives up, which can be a moment after + // the flag it also sets; a fixed caller waits for the answer rather than + // racing it. + let deadline = Instant::now() + Duration::from_secs(10); + while session.video_failure_reason().is_none() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + (frames, session.video_failure_reason()) +} + +/// The defect: a file whose middle is damaged produces real frames, then stops, +/// and says why. Before this the second half was silent -- the reason was an +/// `eprintln!` on a decode worker's stderr, and the only thing the caller could +/// see was a closed channel, which it read as the film finishing. +#[test] +fn a_damaged_file_says_why_it_stopped() { + pin_software(); + let (_scratch, path) = damaged(); + let (frames, reason) = play_to_the_end(&path); + + assert!( + frames > 0, + "the fixture must really decode before it fails, or this proves nothing \ + about a failure that happens mid-stream" + ); + let reason = reason.expect( + "a file that stopped short of its end has to say why: before this the \ + reason was an eprintln on a decode worker and the caller could only \ + see a closed channel", + ); + assert!( + !reason.is_empty(), + "an empty reason is not a reason a notice can print" + ); +} + +/// The other half, and the one that keeps the notice from becoming noise: a +/// file that plays all the way through says **nothing**. A reason channel that +/// fires on every film is a channel nobody reads, which is how the audio +/// device-loss notice earns its place on the strip. +#[test] +fn a_file_that_plays_to_its_end_says_nothing() { + pin_software(); + let path = asset("test_av.mp4"); + let (frames, reason) = play_to_the_end(&path); + assert!(frames > 0, "the control must actually play"); + assert_eq!( + reason, None, + "a film that reached its own end is not a failure" + ); +} diff --git a/crates/engine/tests/exif_orientation.rs b/crates/engine/tests/exif_orientation.rs new file mode 100644 index 0000000..c480cb4 --- /dev/null +++ b/crates/engine/tests/exif_orientation.rs @@ -0,0 +1,366 @@ +//! A still's own EXIF orientation, applied. +//! +//! A phone photographs a portrait picture and stores it as landscape plus a tag +//! saying which way up it is. Before this the engine read neither: the `image` +//! crate keeps the orientation in its decoder and applies nothing, so the +//! preview, the timeline clip box, the poster thumbnail, the canvas seed and an +//! export of that clip were all the stored shape -- a portrait photo on its +//! side, silently, in every one of them. +//! +//! The fixture is **built here**, because none of the ones in `assets/` carry +//! an orientation tag (`scripts/gen_fixtures.sh` writes PNG stills, and PNG has +//! no such tag). It is a real JPEG: four coloured quadrants, an APP1 segment +//! holding a TIFF IFD whose tag `0x0112` states the orientation. A single +//! sampled pixel per corner then names the layout, and a *wrong direction* +//! cannot pass -- 90 the other way, 180, or "ignore it" each produce a +//! different set of four corners. +//! +//! ```text +//! cargo test -p engine --test exif_orientation -- --test-threads=1 +//! ``` + +use std::path::PathBuf; + +use engine::scratch::Scratch; +use engine::{DecodeSession, PlaybackSession, Rotation, image_orientation, image_size}; + +/// A built fixture and the directory holding it, which is removed when the +/// guard drops -- [`Scratch`]'s own contract, so a run leaves nothing behind +/// and two runs cannot race for a name. +fn fixture(exif: u8) -> (Scratch, PathBuf) { + let scratch = Scratch::file(&format!("ve_exif_{exif}"), "jpg"); + let path = PathBuf::from(&*scratch); + std::fs::write(&path, build(exif)).expect("write the built fixture"); + (scratch, path) +} + +/// Which of the four colours a pixel is, by name. The quadrants are far enough +/// apart that a 4:2:0 chroma boundary cannot colour a sample taken deep inside +/// one, and JPEG's own chroma subsampling cannot either. +fn tint(rgb: [u8; 3]) -> &'static str { + let (r, g, b) = (rgb[0], rgb[1], rgb[2]); + match (r > 110, g > 90, b > 110) { + (true, true, false) => "yellow", + (true, false, false) => "red", + (false, true, false) => "green", + (false, false, true) => "blue", + other => panic!("a quadrant centre is not one of the four colours: {other:?}"), + } +} + +/// The four corners of one tightly packed BGRA picture, top-left first and +/// clockwise -- sampled deep enough inside each quadrant that no boundary can +/// colour the sample. +fn corners(width: u32, height: u32, bgra: &[u8]) -> [&'static str; 4] { + let at = |x: u32, y: u32| { + let index = ((y * width + x) * 4) as usize; + let (b, g, r) = (bgra[index], bgra[index + 1], bgra[index + 2]); + tint([r, g, b]) + }; + let (qx, qy) = (width / 4, height / 4); + [ + at(qx, qy), + at(3 * qx, qy), + at(3 * qx, 3 * qy), + at(qx, 3 * qy), + ] +} + +/// The quadrants of the picture as it is **written into the file**, in the same +/// order [`corners`] reads them. The file is landscape 64x32 whatever the +/// orientation says, because that is what a phone does: it stores the sensor's +/// own shape and says the rest in the tag. +const STORED: [&str; 4] = ["red", "green", "blue", "yellow"]; + +/// A 64x32 RGB picture of four coloured quadrants, encoded as a JPEG and given +/// an APP1/EXIF segment stating `exif` as the orientation. +/// +/// The EXIF is written by hand rather than through a crate: the segment is six +/// bytes of `Exif\0\0` followed by a little-endian TIFF header and one IFD +/// entry, which is the whole of what tag `0x0112` is, and writing it out is what +/// makes this a fixture rather than a dependency. +fn build(exif: u8) -> Vec { + let (width, height) = (64u32, 32u32); + let (red, green, blue, yellow) = ( + [220u8, 30, 30], + [30, 200, 40], + [40, 60, 220], + [230, 210, 40], + ); + let (qx, qy) = (width / 4, height / 4); + let mut rgb = image::RgbImage::new(width, height); + for y in 0..height { + for x in 0..width { + let colour = match (x >= 2 * qx, y >= 2 * qy) { + (false, false) => red, + (true, false) => green, + (true, true) => blue, + (false, true) => yellow, + }; + rgb.put_pixel(x, y, image::Rgb(colour)); + } + } + let mut jpeg = Vec::new(); + image::DynamicImage::ImageRgb8(rgb) + .write_to( + &mut std::io::Cursor::new(&mut jpeg), + image::ImageFormat::Jpeg, + ) + .expect("encode the JPEG"); + // Inserted straight after SOI, which is where a camera's APP1 sits and + // where a decoder's marker walk finds it first. + let app1 = exif_app1(exif); + let mut out = Vec::with_capacity(jpeg.len() + app1.len()); + out.extend_from_slice(&jpeg[..2]); + out.extend_from_slice(&app1); + out.extend_from_slice(&jpeg[2..]); + out +} + +/// A complete APP1 segment carrying `exif` as EXIF tag `0x0112`: the `Exif\0\0` +/// identifier, a little-endian TIFF header pointing its IFD0 at offset 8, one +/// entry (tag, type SHORT, count 1, the value), and a zero "next IFD" pointer. +fn exif_app1(exif: u8) -> Vec { + let mut tiff = Vec::new(); + tiff.extend_from_slice(b"II\x2a\x00"); // little-endian, magic 42 + tiff.extend_from_slice(&8u32.to_le_bytes()); // IFD0 at offset 8 + tiff.extend_from_slice(&1u16.to_le_bytes()); // one entry + tiff.extend_from_slice(&0x0112u16.to_le_bytes()); // Orientation + tiff.extend_from_slice(&3u16.to_le_bytes()); // type SHORT + tiff.extend_from_slice(&1u32.to_le_bytes()); // count 1 + tiff.extend_from_slice(&u16::from(exif).to_le_bytes()); + tiff.extend_from_slice(&[0, 0]); // the value's padding to an even offset + tiff.extend_from_slice(&0u32.to_le_bytes()); // no IFD1 + + let mut payload = b"Exif\x00\x00".to_vec(); + payload.extend_from_slice(&tiff); + + let mut segment = vec![0xff, 0xe1]; + // The length field counts itself and the two marker bytes. + segment.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes()); + segment.extend_from_slice(&payload); + segment +} + +/// One frame of `path` and the size it came out at -- the same funnel +/// `PlaybackSession` paints from, so this is what a poster thumbnail and the +/// preview would each hold. +fn first_frame(path: &std::path::Path) -> (u32, u32, Vec) { + let (_, frames, _) = DecodeSession::open_range(path, 0, 1).expect("open for a frame"); + let frame = frames.recv().expect("a first frame"); + (frame.width, frame.height, frame.bgra) +} + +/// Software everywhere, so the suite proves the path every machine has. +fn pin_software() { + static PIN: std::sync::Once = std::sync::Once::new(); + PIN.call_once(|| unsafe { + std::env::set_var("VE_SW", "1"); + std::env::set_var("VE_SW_ENC", "1"); + }); +} + +/// The whole of the defect, asserted through **both** doors that used to +/// disagree: the header-only size a library row reads before anything places +/// the file, and the first decoded frame a preview shows after. They are +/// separate code paths over the same tag, so a fix to one that skipped the +/// other would leave a file that is one shape in the library and another on the +/// timeline. +/// +/// EXIF 6 is the portrait case -- a quarter turn clockwise -- so the stored +/// 64x32 is shown 32x64, and each stored corner moves one place clockwise. +#[test] +fn a_portrait_photo_is_shown_the_way_it_was_photographed() { + pin_software(); + let (_scratch, path) = fixture(6); + + assert_eq!( + image_size(&path).expect("the header answers"), + (32, 64), + "a library row must describe the picture as it is shown, not as it is stored" + ); + assert_eq!( + image_orientation(&path).expect("the tag is readable"), + Rotation::Cw90, + "EXIF 6 is a quarter turn clockwise" + ); + + let (width, height, bgra) = first_frame(&path); + assert_eq!( + [width, height], + [32, 64], + "the decoded frame is the picture as it is shown" + ); + assert_eq!( + corners(width, height, &bgra), + ["yellow", "red", "green", "blue"], + "a quarter turn clockwise puts the stored bottom-left at the new top-left: \ + the file holds {STORED:?} top-left first" + ); +} + +/// The other quarter turns, so a fix that turned *something* rather than +/// turning *right* cannot pass: EXIF 3 is 180 (opposite corners swap), 8 is a +/// quarter turn anticlockwise (the other way round), and 1 states no turn. +/// +/// Each is asserted against the corners its own turn produces, indexed off the +/// stored layout rather than written out, so the expectation cannot drift away +/// from the fixture it describes. +#[test] +fn every_quarter_turn_is_made_in_its_own_direction() { + pin_software(); + // Which stored corner each read corner is, and whether the axes swap with + // the turn. A clockwise quarter turn walks the ring one place on, so the + // read corner at index `i` is the stored one at `i + 3`; anticlockwise is + // the other way round, and 180 is two places either way. + for (exif, swaps, ring) in [ + (3u8, false, [2usize, 3, 0, 1]), + (8, true, [1, 2, 3, 0]), + (1, false, [0, 1, 2, 3]), + ] { + let (_scratch, path) = fixture(exif); + let (stored_w, stored_h) = (64u32, 32u32); + let (want_w, want_h) = match swaps { + true => (stored_h, stored_w), + false => (stored_w, stored_h), + }; + assert_eq!( + image_size(&path).expect("the header answers"), + (want_w, want_h), + "EXIF {exif}: the shown pair is the stored one, turned" + ); + + let (width, height, bgra) = first_frame(&path); + assert_eq!( + [width, height], + [want_w, want_h], + "EXIF {exif}: the frame is the picture as it is shown" + ); + let want: Vec<&str> = ring.iter().map(|i| STORED[*i]).collect(); + assert_eq!( + corners(width, height, &bgra), + want[..], + "EXIF {exif}: the corners read the stored ones in the order {ring:?}" + ); + } +} + +/// A mirroring is not a turn, and this engine has no flip anywhere in its +/// pipeline -- not in the still's decode, not in `Render`, not in an export's +/// `place_picture`. So EXIF 2, 4, 5 and 7 are refused **by name** at the door, +/// the way a display matrix that is not a quarter turn is +/// (`engine::UnsupportedRotation`): a mirrored photo shown the wrong way round +/// is a wrong picture, not a missing feature, and quietly treating a mirror as +/// a rotation is exactly the bug this door exists to stop. +/// +/// All four values are checked, so a fix that refused only the first mirror is +/// caught. +#[test] +fn a_mirrored_photo_is_refused_by_name() { + pin_software(); + for exif in [2u8, 4, 5, 7] { + let (_scratch, path) = fixture(exif); + let error = match image_orientation(&path) { + Ok(rotation) => { + panic!("EXIF {exif} is a mirror, not a turn, and must not read as {rotation:?}") + } + Err(error) => error, + }; + assert!( + engine::UnsupportedStillOrientation::is_it(&error), + "EXIF {exif}: the refusal is the named one, not a generic failure: {error}" + ); + let said = error.to_string(); + assert!( + said.contains(&exif.to_string()) && said.contains("mirror"), + "EXIF {exif}: the refusal names what it cannot make: {said}" + ); + // ...and the door that places the picture refuses it too, rather than + // showing the file the wrong way round. + let error = match PlaybackSession::open(&path) { + Ok(_) => panic!("EXIF {exif} must not open as a timeline"), + Err(error) => error, + }; + assert!( + engine::UnsupportedStillOrientation::is_it(&error), + "EXIF {exif}: opening the timeline refuses it by name too: {error}" + ); + } +} + +/// A picture that states no turn is the whole of an ordinary library, and it +/// must come out the way it always did: the turn is a branch on a bool, and +/// this is the assertion that it stays one. +#[test] +fn an_upright_photo_is_untouched_by_the_turn_door() { + pin_software(); + let (_scratch, path) = fixture(1); + assert_eq!( + image_size(&path).expect("the header answers"), + (64, 32), + "a picture that states no turn is its own size" + ); + let (width, height, bgra) = first_frame(&path); + assert_eq!([width, height], [64, 32]); + assert_eq!( + corners(width, height, &bgra), + STORED, + "no turn means the stored quadrants, in the stored order" + ); +} + +/// The export, which is the door the turn was most expensive to get wrong: it +/// is a re-encode of the *coded* planes, so a still whose turn was applied +/// only on the preview side would be written out sideways and would then play +/// sideways in every player that is not this one, forever, with no matrix left +/// to correct it. +/// +/// The written file must therefore be portrait **and** state no matrix of its +/// own -- a file that kept the landscape pixels and declared a turn would +/// satisfy neither half. +#[test] +fn an_export_of_a_turned_photo_is_upright_and_portrait() { + pin_software(); + let (_scratch, path) = fixture(6); + let mut session = PlaybackSession::open(&path).expect("open the photo"); + session.pause(); + assert_eq!( + [session.meta().width, session.meta().height], + [32, 64], + "the timeline is the displayed shape, not the stored one" + ); + + let out = engine::scratch::Scratch::file("ve_exif_export", "mp4"); + let handle = session.export_to_with(&out, &engine::export::ExportSettings::default()); + let started = std::time::Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < std::time::Duration::from_secs(60), + "the export did not finish" + ); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + handle + .result() + .expect("a finished export has an outcome") + .expect("the export succeeded"); + + let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export"); + assert_eq!( + [meta.width, meta.height], + [32, 64], + "the written file is portrait" + ); + assert_eq!( + meta.rotation, + Rotation::None, + "and states no matrix of its own: the turn is in the pixels" + ); + let (width, height, bgra) = first_frame(&out); + assert_eq!([width, height], [32, 64]); + assert_eq!( + corners(width, height, &bgra), + ["yellow", "red", "green", "blue"], + "the exported pixels are the ones the preview showed" + ); +}