forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(decode): EXIF orientation is shown, and a decode failure says why it stopped

Browse files at this commit

a72b5b16173e336fe5c09e2971d7b4d4340ec739Ahmet Kaan GümüşParent: 2d4c4b45dd4f36
# Conflicts:
#	crates/app/src/tests/media.rs

11 changed files +1629 -329

crates/app/src/main.rsmodified+9 -0
@@ -801,6 +801,13 @@ struct Player {
801 /// while the sound is up; seeded by [`Player::session_swapped`], which every801 /// while the sound is up; seeded by [`Player::session_swapped`], which every
802 /// door that installs or drops a session already calls.802 /// door that installs or drops a session already calls.
803 audio_reason: Option<String>,803 audio_reason: Option<String>,
804+ /// The engine's last word on the *picture*, cached so a frame can tell a
805+ /// reason that changed from one that was merely read again. Keyed to
806+ /// `session_gen` for the same reason `audio_watch_gen` is: `pump` serves
807+ /// the preview while one is up and the timeline otherwise, and an unkeyed
808+ /// cache would read the other session's reason.
809+ decode_reason_cache: Option<String>,
810+ decode_watch_gen: u64,
804 /// Which session generation (`session_gen`) the cached reason above describes:811 /// Which session generation (`session_gen`) the cached reason above describes:
805 /// the watch is keyed to the session it is a statement about, so a preview812 /// the watch is keyed to the session it is a statement about, so a preview
806 /// opening or closing seeds the cache instead of announcing the *other*813 /// opening or closing seeds the cache instead of announcing the *other*
@@ -1139,6 +1146,8 @@ fn main() {
1139 // it serves.1146 // it serves.
1140 audio_reason: None,1147 audio_reason: None,
1141 audio_watch_gen: 0,1148 audio_watch_gen: 0,
1149+ decode_reason_cache: None,
1150+ decode_watch_gen: 0,
1142 viz_slot: VizSlot::Main,1151 viz_slot: VizSlot::Main,
1143 viz_hex_edit: None,1152 viz_hex_edit: None,
1144 pending_viz: None,1153 pending_viz: None,
crates/app/src/notices.rsmodified+56 -10
@@ -64,11 +64,30 @@ pub(crate) fn audio_lost_line(reason: &str) -> String {
64 format!("AUDIO LOST{}", audio_tail(reason))64 format!("AUDIO LOST{}", audio_tail(reason))
65 }65 }
66 66
67-/// What a frame of the sound watch decides, as a pure value: the cache's own67+/// A decode failure that arrives *after* a file was opened, said on its own
68+/// line: the same shape as [`audio_lost_line`] and for the same reason -- a
69+/// death mid-session has no open line to hang a tail off, so it leads with the
70+/// state word the strip reads first.
71+///
72+/// The picture twin of the sound line above, and it exists because a decode
73+/// failure used to reach nobody at all: the worker printed it to stderr and
74+/// dropped the channel, and a closed channel is what a finished film looks like
75+/// from the app's side. A file with a damaged middle froze on its last good
76+/// picture and the transport said ENDED. The reason is the engine's own words,
77+/// verbatim -- the app spells none of them.
78+pub(crate) fn decode_failed_line(reason: &str) -> String {
79+ format!("DECODE FAILED — {reason}")
80+}
81+
82+/// What a frame of a reason watch decides, as a pure value: the cache's own
68 /// session generation against the frame's says whether the two are even talking83 /// session generation against the frame's says whether the two are even talking
69 /// about the same session, and only then what the reason did.84 /// about the same session, and only then what the reason did.
85+///
86+/// One type for every reason the engine states, not one per source: the sound
87+/// device and the decode worker both write a string the app has to notice
88+/// changed, and the thing that decides is the same comparison in both cases.
70 #[derive(Clone, Copy, PartialEq, Eq, Debug)]89 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
71-pub(crate) enum AudioStep {90+pub(crate) enum ReasonStep {
72 /// The cache describes the session *before* this one91 /// The cache describes the session *before* this one
73 /// (`Player::session_swapped`): it is seeded and nothing is announced -- a92 /// (`Player::session_swapped`): it is seeded and nothing is announced -- a
74 /// preview that opens or closes is not a device that came back.93 /// preview that opens or closes is not a device that came back.
@@ -81,7 +100,8 @@ pub(crate) enum AudioStep {
81 Nothing,100 Nothing,
82 }101 }
83 102
84-/// [`Player::watch_audio`]'s whole decision, pure: `cached_gen` is the session103+/// [`Player::watch_audio`]'s and [`Player::watch_decode`]'s whole decision,
104+/// pure: `cached_gen` is the session
85 /// generation the cache describes, `session_gen` the one the frame is serving, and105 /// generation the cache describes, `session_gen` the one the frame is serving, and
86 /// two reasons are what the engine says the sound is (`None` for sound that is106 /// two reasons are what the engine says the sound is (`None` for sound that is
87 /// up).107 /// up).
@@ -91,20 +111,20 @@ pub(crate) enum AudioStep {
91 /// so a flip reads a reason that was never about the cached session at all -- a111 /// so a flip reads a reason that was never about the cached session at all -- a
92 /// live device on one side and a dead one on the other is not a change, it is112 /// live device on one side and a dead one on the other is not a change, it is
93 /// two different questions.113 /// two different questions.
94-pub(crate) fn audio_step(114+pub(crate) fn reason_step(
95 cached_gen: u64,115 cached_gen: u64,
96 session_gen: u64,116 session_gen: u64,
97 was: Option<&str>,117 was: Option<&str>,
98 now: Option<&str>,118 now: Option<&str>,
99-) -> AudioStep {119+) -> ReasonStep {
100 if cached_gen != session_gen {120 if cached_gen != session_gen {
101- return AudioStep::Seed;121+ return ReasonStep::Seed;
102 }122 }
103 match (was, now) {123 match (was, now) {
104- (Some(was), Some(now)) if was == now => AudioStep::Nothing,124+ (Some(was), Some(now)) if was == now => ReasonStep::Nothing,
105- (_, Some(_)) => AudioStep::Push,125+ (_, Some(_)) => ReasonStep::Push,
106- (Some(_), None) => AudioStep::Clear,126+ (Some(_), None) => ReasonStep::Clear,
107- (None, None) => AudioStep::Nothing,127+ (None, None) => ReasonStep::Nothing,
108 }128 }
109 }129 }
110 130
@@ -140,6 +160,32 @@ pub(crate) fn audio_change_notice(
140 }160 }
141 }161 }
142 162
163+/// What a *change* in the engine's **decode** reason does to the notice queue:
164+/// the line pushed when a reason arrives, the same line taken back when the
165+/// reason clears. [`audio_change_notice`]'s twin, step for step, because the
166+/// thing that changed is the same kind of thing -- a reason the engine started
167+/// or stopped stating between two frames.
168+///
169+/// The retraction is what keeps this from becoming noise: a decode that fails,
170+/// is seeked away from and succeeds has to take its line back, or the strip
171+/// keeps saying DECODE FAILED over a film that plays.
172+pub(crate) fn decode_change_notice(
173+ notices: &mut std::collections::VecDeque<SharedString>,
174+ was: Option<&str>,
175+ now: Option<&str>,
176+) {
177+ match (was, now) {
178+ (_, Some(reason)) if was != Some(reason) => {
179+ push_notice(notices, decode_failed_line(reason).into());
180+ }
181+ (Some(was), None) => {
182+ let line = decode_failed_line(was);
183+ notices.retain(|notice| notice.as_ref() != line.as_str());
184+ }
185+ _ => {}
186+ }
187+}
188+
143 /// The strip's own width is finite and its message is one line: what a189 /// The strip's own width is finite and its message is one line: what a
144 /// too-long line must never do is lose its *state* word, which sits at the190 /// too-long line must never do is lose its *state* word, which sits at the
145 /// front, or stop mid-word with nothing saying it stopped (user report,191 /// front, or stop mid-word with nothing saying it stopped (user report,
crates/app/src/player/transport.rsmodified+61 -4
@@ -50,19 +50,19 @@ impl Player {
50 /// without the key a preview opening or closing would read the *other*50 /// without the key a preview opening or closing would read the *other*
51 /// session's reason and announce a device loss that never happened.51 /// session's reason and announce a device loss that never happened.
52 pub(crate) fn watch_audio(&mut self) {52 pub(crate) fn watch_audio(&mut self) {
53- let step = audio_step(53+ let step = reason_step(
54 self.audio_watch_gen,54 self.audio_watch_gen,
55 self.session_gen,55 self.session_gen,
56 self.audio_reason.as_deref(),56 self.audio_reason.as_deref(),
57 self.sound_reason(),57 self.sound_reason(),
58 );58 );
59- if step == AudioStep::Nothing {59+ if step == ReasonStep::Nothing {
60 return;60 return;
61 }61 }
62 let was = self.audio_reason.take();62 let was = self.audio_reason.take();
63 self.audio_reason = self.sound_reason().map(str::to_owned);63 self.audio_reason = self.sound_reason().map(str::to_owned);
64 self.audio_watch_gen = self.session_gen;64 self.audio_watch_gen = self.session_gen;
65- if step == AudioStep::Seed {65+ if step == ReasonStep::Seed {
66 // A session swap is not a change: the new session's own open line66 // A session swap is not a change: the new session's own open line
67 // carries its reason, so only a line left over from the session67 // carries its reason, so only a line left over from the session
68 // before is taken back -- and only when this one's sound is up.68 // before is taken back -- and only when this one's sound is up.
@@ -82,6 +82,61 @@ impl Player {
82 );82 );
83 }83 }
84 84
85+ /// The engine's word on the *picture*, watched rather than asked once --
86+ /// [`Self::watch_audio`]'s twin, and the reason a damaged file stops being
87+ /// indistinguishable from a finished one.
88+ ///
89+ /// `PlaybackSession::video_failure_reason` is the writer's side: a decode
90+ /// worker that gave up on a broken packet used to print it to stderr and
91+ /// drop the channel, and a closed channel is what a film reaching its own
92+ /// end looks like from here -- so the transport said ENDED, the picture
93+ /// froze on the last good frame, and nothing in the window said why.
94+ ///
95+ /// Keyed to the session exactly as the sound watch is, for the same reason:
96+ /// `pump` serves the preview while one is up and the timeline otherwise, so
97+ /// an unkeyed cache would read the other session's reason and announce a
98+ /// failure that never happened.
99+ pub(crate) fn watch_decode(&mut self) {
100+ let now = self.decode_reason();
101+ let step = reason_step(
102+ self.decode_watch_gen,
103+ self.session_gen,
104+ self.decode_reason_cache.as_deref(),
105+ now.as_deref(),
106+ );
107+ if step == ReasonStep::Nothing {
108+ return;
109+ }
110+ let was = self.decode_reason_cache.take();
111+ self.decode_reason_cache = now;
112+ self.decode_watch_gen = self.session_gen;
113+ if step == ReasonStep::Seed {
114+ // A session swap is not a change: the new session's own open line
115+ // carries its reason, so only a line left over from the session
116+ // before is taken back -- and only when this one is healthy.
117+ if self.decode_reason_cache.is_none()
118+ && let Some(was) = was
119+ {
120+ let line = decode_failed_line(&was);
121+ self.notices
122+ .retain(|notice| notice.as_ref() != line.as_str());
123+ }
124+ return;
125+ }
126+ decode_change_notice(
127+ &mut self.notices,
128+ was.as_deref(),
129+ self.decode_reason_cache.as_deref(),
130+ );
131+ }
132+
133+ /// The engine's word on the picture for the session the pump serves, read
134+ /// off that session and no other -- the same rule as [`Self::sound_reason`].
135+ fn decode_reason(&self) -> Option<String> {
136+ self.active_session()
137+ .and_then(PlaybackSession::video_failure_reason)
138+ }
139+
85 /// Catches the display up to the clock: everything already due is taken off140 /// Catches the display up to the clock: everything already due is taken off
86 /// the channel and only the last of them is shown, which *is* the141 /// the channel and only the last of them is shown, which *is* the
87 /// drop-when-behind policy. A frame that is not due yet waits in `held`, and142 /// drop-when-behind policy. A frame that is not due yet waits in `held`, and
@@ -90,8 +145,10 @@ impl Player {
90 pub(crate) fn pump(&mut self, window: &mut Window) {145 pub(crate) fn pump(&mut self, window: &mut Window) {
91 // Before the drain, on the one read that does not need the session146 // Before the drain, on the one read that does not need the session
92 // mutably: the sound can die at any point in a frame, and the notice it147 // mutably: the sound can die at any point in a frame, and the notice it
93- // earns is owed to the frame it died in.148+ // earns is owed to the frame it died in. The picture can fail for the
149+ // same reason and earns the same courtesy.
94 self.watch_audio();150 self.watch_audio();
151+ self.watch_decode();
95 // Where the transport was before this drain, so the crossing into152 // Where the transport was before this drain, so the crossing into
96 // `Ended` can be recognised as the one transition it is.153 // `Ended` can be recognised as the one transition it is.
97 let was = self.transport();154 let was = self.transport();
crates/app/src/tests/media.rsmodified+96 -15
@@ -14,7 +14,76 @@ use crate::ui::preview::{bgra_to_rgba, screenshot_path};
14 /// The notice queue's own half of the sound watch, and the three words it is14 /// The notice queue's own half of the sound watch, and the three words it is
15 /// spelled with -- reached by name because the app's own glob does not carry15 /// spelled with -- reached by name because the app's own glob does not carry
16 /// them (`notices` is a private module re-exported for the window).16 /// them (`notices` is a private module re-exported for the window).
17-use crate::notices::{audio_change_notice, audio_lost_line, audio_tail};17+use crate::notices::{
18+ audio_change_notice, audio_lost_line, audio_tail, decode_change_notice, decode_failed_line,
19+};
20+
21+/// The picture twin of the sound watch above, and the same shape for the same
22+/// reason: a decode failure that arrives between two frames used to reach no
23+/// consumer at all, because the worker printed it to stderr and dropped the
24+/// channel -- and a closed channel is what a finished film looks like from the
25+/// app's side, so the transport said ENDED over a frozen frame with nothing in
26+/// the window saying why.
27+///
28+/// Driven through the queue step, because a test cannot make a decoder fail on
29+/// cue; the engine's writer is the decode worker's, and
30+/// `engine::tests::decode_failure` observes it end to end on the engine side.
31+#[test]
32+fn a_decode_that_fails_under_an_open_file_says_so_and_unsays_it() {
33+ let mut notices: std::collections::VecDeque<gpui::SharedString> =
34+ ["OPENED take.mp4".into()].into_iter().collect();
35+ let failed = decode_failed_line("decode error at access unit 130");
36+ assert!(
37+ failed.starts_with("DECODE FAILED"),
38+ "the line lost the state word the strip reads first: {failed}"
39+ );
40+ // The file was fine, and then the picture stopped: the reason arrives
41+ // between two frames.
42+ decode_change_notice(&mut notices, None, Some("decode error at access unit 130"));
43+ assert_eq!(
44+ notices.back().map(|notice| &***notice),
45+ Some(failed.as_str()),
46+ "a decode failure that arrives mid-session is never pushed"
47+ );
48+ // The same reason read again on the next frame is not news.
49+ decode_change_notice(
50+ &mut notices,
51+ Some("decode error at access unit 130"),
52+ Some("decode error at access unit 130"),
53+ );
54+ assert_eq!(notices.len(), 2, "one failure was announced twice");
55+ // Seeked away from, and it decodes again: the line goes with it, or the
56+ // strip keeps saying DECODE FAILED over a film that plays.
57+ decode_change_notice(&mut notices, Some("decode error at access unit 130"), None);
58+ assert_eq!(
59+ notices.iter().map(|notice| &***notice).collect::<Vec<_>>(),
60+ vec!["OPENED take.mp4"],
61+ "the DECODE FAILED line is still on the strip over a film that plays"
62+ );
63+ // The sound line is a different line and is none of this step's business.
64+ audio_change_notice(&mut notices, None, Some("AUDIO_LOST"));
65+ decode_change_notice(&mut notices, None, Some("decode error at access unit 7"));
66+ decode_change_notice(&mut notices, Some("decode error at access unit 7"), None);
67+ assert_eq!(
68+ notices.iter().map(|notice| &***notice).collect::<Vec<_>>(),
69+ vec!["OPENED take.mp4", audio_lost_line("AUDIO_LOST").as_str()],
70+ "one reason's retraction took the other one's line with it"
71+ );
72+ // The wiring: the pump is the one place every frame passes through, and a
73+ // watcher nothing calls is a message nobody reads.
74+ assert!(
75+ fn_body("pump").contains("self.watch_decode();"),
76+ "the pump stopped watching the engine's decode reason, so a corrupt \
77+ file is a silent freeze again"
78+ );
79+ // ...and it reads the reason off the session the pump is serving, the same
80+ // rule the sound watch follows.
81+ assert!(
82+ fn_body("decode_reason").contains("self.active_session()"),
83+ "the decode watch reads a reason off a session the pump is not \
84+ serving, so a preview flip announces the other session's failure"
85+ );
86+}
18 87
19 /// A reason that changes under a session that is already open says so, and stops88 /// A reason that changes under a session that is already open says so, and stops
20 /// saying so when it clears. This side is the *reader*: the writer of a reason is89 /// 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() {
72 // cannot be answered as if it were the cached session's own change.141 // cannot be answered as if it were the cached session's own change.
73 let watch = fn_body("watch_audio");142 let watch = fn_body("watch_audio");
74 let args = watch143 let args = watch
75- .split_once("audio_step(")144+ .split_once("reason_step(")
76 .expect(145 .expect(
77 "the watch decides for itself instead of through the pure step the flip test drives",146 "the watch decides for itself instead of through the pure step the flip test drives",
78 )147 )
@@ -106,29 +175,41 @@ fn a_device_that_dies_under_an_open_file_says_so_and_unsays_it() {
106 /// speaks.175 /// speaks.
107 #[test]176 #[test]
108 fn a_preview_flip_is_not_a_device_that_came_back() {177 fn a_preview_flip_is_not_a_device_that_came_back() {
109- use crate::notices::{AudioStep, audio_step};178+ use crate::notices::{ReasonStep, reason_step};
110 // A swap, every way round: seeded, never announced.179 // A swap, every way round: seeded, never announced.
111- assert_eq!(audio_step(7, 8, None, Some("AUDIO_LOST")), AudioStep::Seed);
112- assert_eq!(audio_step(7, 8, Some("AUDIO_LOST"), None), AudioStep::Seed);
113 assert_eq!(180 assert_eq!(
114- audio_step(7, 8, Some("AUDIO_LOST"), Some("AUDIO_LOST")),181+ reason_step(7, 8, None, Some("AUDIO_LOST")),
115- AudioStep::Seed,182+ ReasonStep::Seed
183+ );
184+ assert_eq!(
185+ reason_step(7, 8, Some("AUDIO_LOST"), None),
186+ ReasonStep::Seed
187+ );
188+ assert_eq!(
189+ reason_step(7, 8, Some("AUDIO_LOST"), Some("AUDIO_LOST")),
190+ ReasonStep::Seed,
116 "a flip whose reason reads the same on both sides is still a flip"191 "a flip whose reason reads the same on both sides is still a flip"
117 );192 );
118 // The same session, the reason arriving, changing, and going.193 // The same session, the reason arriving, changing, and going.
119- assert_eq!(audio_step(7, 7, None, Some("AUDIO_LOST")), AudioStep::Push);
120 assert_eq!(194 assert_eq!(
121- audio_step(7, 7, Some("AUDIO_LOST"), Some("device gone")),195+ reason_step(7, 7, None, Some("AUDIO_LOST")),
122- AudioStep::Push196+ ReasonStep::Push
197+ );
198+ assert_eq!(
199+ reason_step(7, 7, Some("AUDIO_LOST"), Some("device gone")),
200+ ReasonStep::Push
201+ );
202+ assert_eq!(
203+ reason_step(7, 7, Some("AUDIO_LOST"), None),
204+ ReasonStep::Clear
123 );205 );
124- assert_eq!(audio_step(7, 7, Some("AUDIO_LOST"), None), AudioStep::Clear);
125 assert_eq!(206 assert_eq!(
126- audio_step(7, 7, Some("AUDIO_LOST"), Some("AUDIO_LOST")),207+ reason_step(7, 7, Some("AUDIO_LOST"), Some("AUDIO_LOST")),
127- AudioStep::Nothing,208+ ReasonStep::Nothing,
128 "the same reason read again on the next frame is not news"209 "the same reason read again on the next frame is not news"
129 );210 );
130- assert_eq!(audio_step(7, 7, None, None), AudioStep::Nothing);211+ assert_eq!(reason_step(7, 7, None, None), ReasonStep::Nothing);
131- assert_eq!(audio_step(0, 0, None, None), AudioStep::Nothing);212+ assert_eq!(reason_step(0, 0, None, None), ReasonStep::Nothing);
132 }213 }
133 214
134 /// The toast tail an audio import earns: rate, channel count and rounded215 /// The toast tail an audio import earns: rate, channel count and rounded
crates/engine/Cargo.tomlmodified+4 -2
@@ -205,5 +205,7 @@ oxideav-sub-image = "0.0.7"
205 205
206 [dev-dependencies]206 [dev-dependencies]
207 # The still-image suite compares what the timeline shows against the file's own207 # The still-image suite compares what the timeline shows against the file's own
208-# pixels rather than against a constant. Already built for the engine itself.208+# pixels rather than against a constant, and the EXIF suite has to *write* one:
209-image = { version = "0.25", default-features = false, features = ["png"] }209+# no fixture in `assets/` carries an orientation tag, so the turned-still test
210+# builds its own JPEG here. Already built for the engine itself.
211+image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
crates/engine/src/decode.rsmodified+582 -110
@@ -2,18 +2,19 @@
2 //! thread (the UI thread) never blocks on decode and memory stays capped.2 //! thread (the UI thread) never blocks on decode and memory stays capped.
3 3
4 use std::path::{Path, PathBuf};4 use std::path::{Path, PathBuf};
5-use std::sync::Arc;
6 use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};5 use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
7 use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};6 use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};
7+use std::sync::{Arc, Mutex};
8 use std::thread;8 use std::thread;
9 9
10-use ec_core::frame::VideoFrame;
11 use ec_av1::encode::Picture as Av1Picture;10 use ec_av1::encode::Picture as Av1Picture;
12 use ec_av1::stream::decode_stream_with;11 use ec_av1::stream::decode_stream_with;
13-use ec_core::registry::{CodecId, CodecParameters};12+use ec_core::frame::VideoFrame;
14 use ec_core::registry::Decoder as _;13 use ec_core::registry::Decoder as _;
14+use ec_core::registry::{CodecId, CodecParameters};
15 use ec_core::{Error as Av1Error, Packet, TimeBase};15 use ec_core::{Error as Av1Error, Packet, TimeBase};
16 use ec_h264::H264Decoder;16 use ec_h264::H264Decoder;
17+use image::ImageDecoder as _;
17 18
18 use crate::color::ColorParams;19 use crate::color::ColorParams;
19 use crate::colorspace::{ColorDescription, Matrix, Transfer};20 use crate::colorspace::{ColorDescription, Matrix, Transfer};
@@ -407,6 +408,56 @@ pub(crate) struct FrameStream {
407 /// What this stream's pictures are being decoded by. Dropped last and read408 /// What this stream's pictures are being decoded by. Dropped last and read
408 /// by the caller, so it outlives nothing and blocks nothing.409 /// by the caller, so it outlives nothing and blocks nothing.
409 pub(crate) backend: BackendCell,410 pub(crate) backend: BackendCell,
411+ /// Why this stream stopped early, if it did -- the answer a closed channel
412+ /// cannot give. Cloned into the worker, so it outlives the span that set it.
413+ pub(crate) failure: DecodeFailure,
414+}
415+
416+/// Why a decode worker stopped **before** the end of its stream, if it did.
417+///
418+/// The reason channel the sound path already has ([`crate::playback::Audio`]'s
419+/// `died` flag, read back as `audio_disabled_reason`), for the picture side. It
420+/// exists because a closed channel is not an answer: a worker that ran to the end
421+/// of the file and a worker that gave up on a corrupt packet both drop the
422+/// sender, and to a caller reading [`std::sync::mpsc::Receiver::try_recv`]
423+/// those are one event. The app read that as `Transport::Ended`, so a file with
424+/// a broken middle froze on its last good picture and said nothing -- identical
425+/// to the film finishing, with no notice and no banner.
426+///
427+/// The **first** reason wins: a span that fails and is then reseeked keeps the
428+/// failure that stopped it until a span succeeds, which is what makes this a
429+/// statement about the file rather than about the last attempt. A clean
430+/// end-of-stream sets nothing at all -- silence is not a fault, and a notice
431+/// that fires on every film would be a notice nobody reads.
432+#[derive(Clone, Default)]
433+pub struct DecodeFailure(Arc<Mutex<Option<String>>>);
434+
435+impl DecodeFailure {
436+ /// The reason the last span failed, if one did.
437+ pub fn reason(&self) -> Option<String> {
438+ self.0.lock().ok().and_then(|reason| reason.clone())
439+ }
440+
441+ /// Records a failure and says so on stderr, which is where these used to go
442+ /// and where they still belong: the stderr line is for whoever is reading a
443+ /// log, and this cell is for whoever is looking at a window.
444+ pub(crate) fn set(&self, reason: String) {
445+ eprintln!("{reason}");
446+ let Ok(mut slot) = self.0.lock() else {
447+ return; // poisoned by a panic elsewhere: the stderr line still stands
448+ };
449+ if slot.is_none() {
450+ *slot = Some(reason);
451+ }
452+ }
453+
454+ /// Takes the reason back, for a caller that has read it: a fresh span that
455+ /// gets all the way through its range has answered the question.
456+ pub(crate) fn clear(&self) {
457+ if let Ok(mut slot) = self.0.lock() {
458+ slot.take();
459+ }
460+ }
410 }461 }
411 462
412 pub struct DecodeSession;463 pub struct DecodeSession;
@@ -482,6 +533,7 @@ impl DecodeSession {
482 reuse: None,533 reuse: None,
483 },534 },
484 backend: BackendCell::new(Backend::Gap),535 backend: BackendCell::new(Backend::Gap),
536+ failure: DecodeFailure::default(),
485 };537 };
486 }538 }
487 let worker_cancel = Arc::clone(&cancel);539 let worker_cancel = Arc::clone(&cancel);
@@ -515,6 +567,7 @@ impl DecodeSession {
515 reuse: None,567 reuse: None,
516 },568 },
517 backend: BackendCell::new(Backend::Gap),569 backend: BackendCell::new(Backend::Gap),
570+ failure: DecodeFailure::default(),
518 }571 }
519 }572 }
520 573
@@ -547,6 +600,10 @@ impl DecodeSession {
547 reuse: None,600 reuse: None,
548 },601 },
549 backend: BackendCell::new(Backend::Still),602 backend: BackendCell::new(Backend::Still),
603+ // A still has no stream to fail in: `Still::open` raised
604+ // anything that was wrong with the file at the door, before a
605+ // worker existed.
606+ failure: DecodeFailure::default(),
550 });607 });
551 }608 }
552 // The one conversion, on this thread: it is a few milliseconds and the609 // The one conversion, on this thread: it is a few milliseconds and the
@@ -560,7 +617,9 @@ impl DecodeSession {
560 let first = Render::new(617 let first = Render::new(
561 color,618 color,
562 transform,619 transform,
563- // A still has no display matrix: what the file holds is what it is.620+ // A still's own turn is already in these planes: `Still::open` made
621+ // it before the conversion above, exactly where the video door
622+ // makes a display matrix, so the render must not make it twice.
564 Rotation::None,623 Rotation::None,
565 // ...and no sample aspect either: a still is authored square.624 // ...and no sample aspect either: a still is authored square.
566 PixelAspect::SQUARE,625 PixelAspect::SQUARE,
@@ -608,6 +667,7 @@ impl DecodeSession {
608 reuse: None,667 reuse: None,
609 },668 },
610 backend: BackendCell::new(Backend::Still),669 backend: BackendCell::new(Backend::Still),
670+ failure: DecodeFailure::default(),
611 })671 })
612 }672 }
613 673
@@ -646,6 +706,9 @@ impl DecodeSession {
646 reuse: None,706 reuse: None,
647 },707 },
648 backend: BackendCell::new(Backend::Visualizer),708 backend: BackendCell::new(Backend::Visualizer),
709+ // A painted picture has no decoder to fail: an unreadable audio
710+ // file is `VizEnvelope::Silent`, which is what silence looks like.
711+ failure: DecodeFailure::default(),
649 });712 });
650 }713 }
651 // Painted at the canvas's own size, so the composite places nothing:714 // Painted at the canvas's own size, so the composite places nothing:
@@ -684,7 +747,11 @@ impl DecodeSession {
684 if worker_cancel.load(Ordering::Relaxed) {747 if worker_cancel.load(Ordering::Relaxed) {
685 return;748 return;
686 }749 }
687- let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 };750+ let fps = if fps.is_finite() && fps > 0.0 {
751+ fps
752+ } else {
753+ 30.0
754+ };
688 // One frame's painting no longer allocates per strand per755 // One frame's painting no longer allocates per strand per
689 // frame: this thread lives for the span.756 // frame: this thread lives for the span.
690 let mut scratch = VizScratch::default();757 let mut scratch = VizScratch::default();
@@ -711,9 +778,8 @@ impl DecodeSession {
711 // the same thirty seconds, and no decode at all for the778 // the same thirty seconds, and no decode at all for the
712 // rebuilds of a look edit.779 // rebuilds of a look edit.
713 let view = envelope.view_at(t);780 let view = envelope.view_at(t);
714- let (y, u, v) = visualizer_window_i420(781+ let (y, u, v) =
715- &mut scratch, &view, t, width, height, flags, paint,782+ visualizer_window_i420(&mut scratch, &view, t, width, height, flags, paint);
716- );
717 let frame = render.frame(start_frame + index, &y, &u, &v, width, height);783 let frame = render.frame(start_frame + index, &y, &u, &v, width, height);
718 if tx.send(frame).is_err() {784 if tx.send(frame).is_err() {
719 return; // caller moved on785 return; // caller moved on
@@ -729,6 +795,9 @@ impl DecodeSession {
729 reuse: None,795 reuse: None,
730 },796 },
731 backend: BackendCell::new(Backend::Visualizer),797 backend: BackendCell::new(Backend::Visualizer),
798+ // ...and nothing in the paint loop can fail either, for the same
799+ // reason.
800+ failure: DecodeFailure::default(),
732 })801 })
733 }802 }
734 803
@@ -762,6 +831,34 @@ impl DecodeSession {
762 tone: tonemap::Preset,831 tone: tonemap::Preset,
763 ) -> crate::Result<(VideoMeta, FrameStream)> {832 ) -> crate::Result<(VideoMeta, FrameStream)> {
764 let path = path.as_ref().to_path_buf();833 let path = path.as_ref().to_path_buf();
834+ // A still is not a stream: handing one to the mp4 demuxer answers "a
835+ // box with a larger size than it", which is a true sentence about a
836+ // container and nothing a person can act on -- and it made this door,
837+ // the one a front-end opens a file through, refuse every picture
838+ // outright. The still door answers with a meta of its own, so a poster
839+ // thumbnail and a preview window get the same picture the timeline
840+ // does, at the same size. No `tone` argument is passed on and none is
841+ // wanted: a still is decoded into BT.601 SDR planes, so there is no
842+ // map to build whichever rendition the project is watching.
843+ if crate::is_image(&path) {
844+ let still = Still::open(&path)?;
845+ let meta = VideoMeta {
846+ width: still.width,
847+ height: still.height,
848+ frame_rate: 1.0,
849+ frame_count: 1,
850+ codec: Codec::H264,
851+ color: ColorDescription::default(),
852+ // A still's own turn was made in `Still::open`, before these
853+ // planes were written, so there is nothing left to state here.
854+ rotation: Rotation::None,
855+ coded_width: still.width,
856+ coded_height: still.height,
857+ pixel_aspect: PixelAspect::SQUARE,
858+ };
859+ return Self::open_still(&path, start_frame, 1, color, transform, canvas)
860+ .map(|stream| (meta, stream));
861+ }
765 let (meta, demuxer) = Demuxer::open(&path)?;862 let (meta, demuxer) = Demuxer::open(&path)?;
766 // No software HEVC, VP9 or VP8 decoder exists, so such a file the plugin will863 // No software HEVC, VP9 or VP8 decoder exists, so such a file the plugin will
767 // not take is refused *here*, where the caller still has somewhere to864 // not take is refused *here*, where the caller still has somewhere to
@@ -789,6 +886,7 @@ impl DecodeSession {
789 reuse: None,886 reuse: None,
790 },887 },
791 backend: BackendCell::default(),888 backend: BackendCell::default(),
889+ failure: DecodeFailure::default(),
792 },890 },
793 ));891 ));
794 }892 }
@@ -885,6 +983,11 @@ fn span_worker(
885 // what opened rather than what was hoped for -- and kept across the spans983 // what opened rather than what was hoped for -- and kept across the spans
886 // that follow, since they are decoded by that very decoder.984 // that follow, since they are decoded by that very decoder.
887 let backend = BackendCell::default();985 let backend = BackendCell::default();
986+ // One cell for the whole worker, not one per span: the thread outlives its
987+ // spans (that is what a reseek costs nothing for), so the reason a span
988+ // failed has to outlive the span too, and be visible to whoever opened this
989+ // stream.
990+ let failure = DecodeFailure::default();
888 let generation = Arc::new(AtomicU64::new(0));991 let generation = Arc::new(AtomicU64::new(0));
889 // The playhead starts where the span does: nothing is behind it yet.992 // The playhead starts where the span does: nothing is behind it yet.
890 let floor = Arc::new(AtomicU32::new(start_frame));993 let floor = Arc::new(AtomicU32::new(start_frame));
@@ -902,6 +1005,7 @@ fn span_worker(
902 };1005 };
903 let worker_cancel = Arc::clone(&cancel);1006 let worker_cancel = Arc::clone(&cancel);
904 let worker_backend = backend.clone();1007 let worker_backend = backend.clone();
1008+ let worker_failure = failure.clone();
905 let worker_generation = Arc::clone(&generation);1009 let worker_generation = Arc::clone(&generation);
906 let worker_floor = Arc::clone(&floor);1010 let worker_floor = Arc::clone(&floor);
907 let worker_path = path.clone();1011 let worker_path = path.clone();
@@ -923,7 +1027,14 @@ fn span_worker(
923 // interrupt. A scrub abandons spans by the dozen and this is1027 // interrupt. A scrub abandons spans by the dozen and this is
924 // where all but the last of them stop.1028 // where all but the last of them stop.
925 if !abort.hit() {1029 if !abort.hit() {
926- run_span(&worker_path, &mut source, cmd, &abort, &worker_backend);1030+ run_span(
1031+ &worker_path,
1032+ &mut source,
1033+ cmd,
1034+ &abort,
1035+ &worker_backend,
1036+ &worker_failure,
1037+ );
927 }1038 }
928 // Parked between spans. A seek and a clip boundary arrive in1039 // Parked between spans. A seek and a clip boundary arrive in
929 // milliseconds and find the decoder still open, which is the1040 // milliseconds and find the decoder still open, which is the
@@ -975,6 +1086,7 @@ fn span_worker(
975 }),1086 }),
976 },1087 },
977 backend,1088 backend,
1089+ failure,
978 }1090 }
979 }1091 }
980 1092
@@ -1049,7 +1161,9 @@ impl Source {
1049 fn position_hw(&mut self, path: &Path, start: u32) -> Option<bool> {1161 fn position_hw(&mut self, path: &Path, start: u32) -> Option<bool> {
1050 if let Some(hw) = &mut self.hw {1162 if let Some(hw) = &mut self.hw {
1051 if hw.seek(start) {1163 if hw.seek(start) {
1052- eprintln!("decode backend: hardware (VA-API plugin, session kept, seek to {start})");1164+ eprintln!(
1165+ "decode backend: hardware (VA-API plugin, session kept, seek to {start})"
1166+ );
1053 return Some(true);1167 return Some(true);
1054 }1168 }
1055 // A plugin too old to reposition, or a decoder that would not1169 // A plugin too old to reposition, or a decoder that would not
@@ -1075,6 +1189,7 @@ fn run_span(
1075 cmd: SpanCmd,1189 cmd: SpanCmd,
1076 abort: &Abort,1190 abort: &Abort,
1077 backend: &BackendCell,1191 backend: &BackendCell,
1192+ worker_failure: &DecodeFailure,
1078 ) {1193 ) {
1079 let SpanCmd {1194 let SpanCmd {
1080 start,1195 start,
@@ -1087,11 +1202,21 @@ fn run_span(
1087 tx,1202 tx,
1088 ..1203 ..
1089 } = cmd;1204 } = cmd;
1205+ // A span is a fresh question, so it starts from a clean answer: the
1206+ // failure that stopped the span before this one was already reported, and
1207+ // carrying it would keep saying a fault that this range may not have. Only
1208+ // a span that is actually going to run clears it -- a span superseded on its
1209+ // way through the queue decoded nothing and has nothing to say.
1210+ worker_failure.clear();
1090 let opened = match source {1211 let opened = match source {
1091 Some(opened) => opened,1212 Some(opened) => opened,
1092 None => {1213 None => {
1093 let Some(fresh) = Source::open(path) else {1214 let Some(fresh) = Source::open(path) else {
1094 backend.set(Backend::Gap);1215 backend.set(Backend::Gap);
1216+ worker_failure.set(format!(
1217+ "{}: could not be opened for decoding",
1218+ path.display()
1219+ ));
1095 return;1220 return;
1096 };1221 };
1097 source.insert(fresh)1222 source.insert(fresh)
@@ -1133,6 +1258,7 @@ fn run_span(
1133 &mut render,1258 &mut render,
1134 abort,1259 abort,
1135 speed,1260 speed,
1261+ worker_failure,
1136 );1262 );
1137 // A *reused* session that produced nothing may simply be one this1263 // A *reused* session that produced nothing may simply be one this
1138 // reseek left where the driver would not follow; a session opened fresh1264 // reseek left where the driver would not follow; a session opened fresh
@@ -1140,10 +1266,21 @@ fn run_span(
1140 // is a software fallback. Without this a single unfollowed seek would1266 // is a software fallback. Without this a single unfollowed seek would
1141 // collapse the rest of the file to software.1267 // collapse the rest of the file to software.
1142 if !decoded && reused {1268 if !decoded && reused {
1143- eprintln!("hardware decode produced nothing after a reseek; reopening at frame {start}");1269+ eprintln!(
1270+ "hardware decode produced nothing after a reseek; reopening at frame {start}"
1271+ );
1144 opened.hw = open_hw(path, start);1272 opened.hw = open_hw(path, start);
1145 if let Some(hw) = opened.hw.as_mut() {1273 if let Some(hw) = opened.hw.as_mut() {
1146- decoded = run_hw(hw, &tx, start, end, &mut render, abort, speed);1274+ decoded = run_hw(
1275+ hw,
1276+ &tx,
1277+ start,
1278+ end,
1279+ &mut render,
1280+ abort,
1281+ speed,
1282+ worker_failure,
1283+ );
1147 }1284 }
1148 }1285 }
1149 if decoded {1286 if decoded {
@@ -1162,12 +1299,30 @@ fn run_span(
1162 Codec::H264 => {1299 Codec::H264 => {
1163 eprintln!("decode backend: software (ec-h264)");1300 eprintln!("decode backend: software (ec-h264)");
1164 backend.set(Backend::Software);1301 backend.set(Backend::Software);
1165- run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed);1302+ run(
1303+ &mut opened.demuxer,
1304+ &tx,
1305+ start,
1306+ end,
1307+ &mut render,
1308+ abort,
1309+ speed,
1310+ worker_failure,
1311+ );
1166 }1312 }
1167 Codec::Av1 => {1313 Codec::Av1 => {
1168 eprintln!("decode backend: software (ec-av1)");1314 eprintln!("decode backend: software (ec-av1)");
1169 backend.set(Backend::Software);1315 backend.set(Backend::Software);
1170- run_av1(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed);1316+ run_av1(
1317+ &mut opened.demuxer,
1318+ &tx,
1319+ start,
1320+ end,
1321+ &mut render,
1322+ abort,
1323+ speed,
1324+ worker_failure,
1325+ );
1171 }1326 }
1172 // Nothing decodes from here -- no software seat exists for this codec.1327 // Nothing decodes from here -- no software seat exists for this codec.
1173 // Say so: the cell was left claiming the hardware session that opened1328 // Say so: the cell was left claiming the hardware session that opened
@@ -1175,7 +1330,7 @@ fn run_span(
1175 // was hoped for.1330 // was hoped for.
1176 other => {1331 other => {
1177 backend.set(Backend::Gap);1332 backend.set(Backend::Gap);
1178- eprintln!("{}", other.needs_plugin());1333+ worker_failure.set(format!("{}: {}", path.display(), other.needs_plugin()));
1179 }1334 }
1180 }1335 }
1181 }1336 }
@@ -1388,36 +1543,35 @@ impl Render {
1388 // picture a viewer is shown, so its brightness and saturation mean what1543 // picture a viewer is shown, so its brightness and saturation mean what
1389 // they say in the SDR the tone map just produced, not in the 10-stop1544 // they say in the SDR the tone map just produced, not in the 10-stop
1390 // HDR the file was in.1545 // HDR the file was in.
1391- let (y, u, v, desc) = if self.tone.is_some()1546+ let (y, u, v, desc) =
1392- || (!skip_placement && !self.color.is_identity())1547+ if self.tone.is_some() || (!skip_placement && !self.color.is_identity()) {
1393- {1548+ let (gy, gu, gv) = &mut self.graded;
1394- let (gy, gu, gv) = &mut self.graded;1549+ gy.clear();
1395- gy.clear();1550+ gy.extend_from_slice(y);
1396- gy.extend_from_slice(y);1551+ gu.clear();
1397- gu.clear();1552+ gu.extend_from_slice(u);
1398- gu.extend_from_slice(u);1553+ gv.clear();
1399- gv.clear();1554+ gv.extend_from_slice(v);
1400- gv.extend_from_slice(v);1555+ if let Some(tone) = &self.tone {
1401- if let Some(tone) = &self.tone {1556+ tone.map(gy, gu, gv, width as usize, height as usize);
1402- tone.map(gy, gu, gv, width as usize, height as usize);1557+ }
1403- }1558+ // The same terms the branch was entered on: anywhere the fused
1404- // The same terms the branch was entered on: anywhere the fused1559+ // conversion below will not apply the grade (a placement is
1405- // conversion below will not apply the grade (a placement is1560+ // happening, so the canvas conversion is plain), it lands here --
1406- // happening, so the canvas conversion is plain), it lands here --1561+ // including the passthrough-sized clip a transform moves, whose
1407- // including the passthrough-sized clip a transform moves, whose1562+ // grade used to be dropped on the floor between these two guards.
1408- // grade used to be dropped on the floor between these two guards.1563+ if !skip_placement && !self.color.is_identity() {
1409- if !skip_placement && !self.color.is_identity() {1564+ crate::color::apply_yuv(&self.color, gy, gu, gv);
1410- crate::color::apply_yuv(&self.color, gy, gu, gv);1565+ }
1411- }1566+ let desc = if self.tone.is_some() {
1412- let desc = if self.tone.is_some() {1567+ TONE_MAPPED
1413- TONE_MAPPED1568+ } else {
1569+ self.desc
1570+ };
1571+ (&gy[..], &gu[..], &gv[..], desc)
1414 } else {1572 } else {
1415- self.desc1573+ (y, u, v, self.desc)
1416 };1574 };
1417- (&gy[..], &gu[..], &gv[..], desc)
1418- } else {
1419- (y, u, v, self.desc)
1420- };
1421 if skip_placement {1575 if skip_placement {
1422 return Frame {1576 return Frame {
1423 index,1577 index,
@@ -1435,11 +1589,17 @@ impl Render {
1435 };1589 };
1436 }1590 }
1437 let (y, u, v, width, height) = if transform_active {1591 let (y, u, v, width, height) = if transform_active {
1438- let (py, pu, pv, w, h) = self1592+ let (py, pu, pv, w, h) =
1439- .canvas1593+ self.canvas
1440- .place_transformed(y, u, v, width, height, &self.transform);1594+ .place_transformed(y, u, v, width, height, &self.transform);
1441 self.placed = (py, pu, pv);1595 self.placed = (py, pu, pv);
1442- (&self.placed.0[..], &self.placed.1[..], &self.placed.2[..], w, h)1596+ (
1597+ &self.placed.0[..],
1598+ &self.placed.1[..],
1599+ &self.placed.2[..],
1600+ w,
1601+ h,
1602+ )
1443 } else {1603 } else {
1444 self.canvas.place(y, u, v, width, height)1604 self.canvas.place(y, u, v, width, height)
1445 };1605 };
@@ -1465,10 +1625,100 @@ pub(crate) struct Still {
1465 pub(crate) y: Vec<u8>,1625 pub(crate) y: Vec<u8>,
1466 pub(crate) u: Vec<u8>,1626 pub(crate) u: Vec<u8>,
1467 pub(crate) v: Vec<u8>,1627 pub(crate) v: Vec<u8>,
1628+ /// The picture as it is *shown*, which for a phone's portrait photo is not
1629+ /// the picture as it was stored: the turn its EXIF block asks for was made
1630+ /// in [`Still::open`] before these planes were written, exactly where the
1631+ /// video doors make a display matrix, so the pair every reader takes is
1632+ /// the displayed one ([`crate::demux::Rotation`]'s own contract).
1468 pub(crate) width: u32,1633 pub(crate) width: u32,
1469 pub(crate) height: u32,1634 pub(crate) height: u32,
1470 }1635 }
1471 1636
1637+/// A still whose EXIF orientation is not a quarter turn: values 2, 4, 5 and 7
1638+/// are mirrorings, and this engine has no flip anywhere in its pipeline -- not
1639+/// in [`crate::scale::rotate_i420_90s`], not in [`Render`], not in an export's
1640+/// `place_picture`. Refused **by name** at the door, for
1641+/// [`crate::demux::UnsupportedRotation`]'s reason: showing a mirrored photo the
1642+/// wrong way round is a wrong picture rather than a missing feature, and
1643+/// quietly treating a mirror as a turn is exactly the bug this door exists to
1644+/// stop. The `Display` is what a user is refused by.
1645+#[derive(Debug)]
1646+pub struct UnsupportedStillOrientation {
1647+ /// The EXIF value the file states, which is what the sentence names: the
1648+ /// eight legal values are 1 (upright) through 8, and the four mirrorings
1649+ /// are the even-odd pairs.
1650+ pub exif: u8,
1651+}
1652+
1653+impl std::fmt::Display for UnsupportedStillOrientation {
1654+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1655+ write!(
1656+ f,
1657+ "this picture's EXIF orientation is {}, which is a mirror and not a turn; only \
1658+ upright, 90°, 180° and 270° can be straightened here",
1659+ self.exif
1660+ )
1661+ }
1662+}
1663+
1664+impl std::error::Error for UnsupportedStillOrientation {}
1665+
1666+impl UnsupportedStillOrientation {
1667+ /// Whether `error` is one of these, however deep in a `Box` it is --
1668+ /// [`crate::demux::UnsupportedRotation::is_it`]'s twin.
1669+ pub fn is_it(error: &crate::Error) -> bool {
1670+ error.downcast_ref::<Self>().is_some()
1671+ }
1672+}
1673+
1674+/// The quarter turns an EXIF orientation asks for, as the one
1675+/// [`Rotation`] every other door in this engine already uses -- no second
1676+/// shape mechanism for a still, so the same turn is made by the same code
1677+/// that makes a video's display matrix turn.
1678+///
1679+/// EXIF 1, 6, 8 and 3 are the four quarter turns; **2, 4, 5 and 7 are
1680+/// mirrorings** and are refused ([`UnsupportedStillOrientation`]) rather than
1681+/// approximated by the nearest rotation. A value the standard does not define
1682+/// (0, or above 8) states no orientation this can read, and is likewise
1683+/// refused rather than guessed at.
1684+fn rotation_of_exif(orientation: image::metadata::Orientation) -> crate::Result<Rotation> {
1685+ use image::metadata::Orientation as O;
1686+ Ok(match orientation {
1687+ O::NoTransforms => Rotation::None,
1688+ O::Rotate90 => Rotation::Cw90,
1689+ O::Rotate180 => Rotation::Cw180,
1690+ O::Rotate270 => Rotation::Cw270,
1691+ // The `image` crate keeps the raw number alongside: an orientation it
1692+ // could not read is `NoTransforms`, and saying "0" for a mirror would
1693+ // be a claim rather than a reading.
1694+ mirrored => {
1695+ return Err(UnsupportedStillOrientation {
1696+ exif: mirrored.to_exif(),
1697+ }
1698+ .into());
1699+ }
1700+ })
1701+}
1702+
1703+/// What turn `path` asks for, read off its **header** alone -- what a library
1704+/// row says about a file it has not placed anywhere, and what
1705+/// [`image_size`] needs to report the size the picture is shown at.
1706+///
1707+/// Header-only on purpose: the whole file is not decoded, exactly as
1708+/// [`image_size`] has always been. `into_decoder` parses the container and
1709+/// stops there; the pixels are never touched.
1710+pub fn image_orientation(path: &Path) -> crate::Result<Rotation> {
1711+ let mut decoder = image::ImageReader::open(path)?
1712+ .with_guessed_format()?
1713+ .into_decoder()
1714+ .map_err(|e| format!("{}: {e}", path.display()))?;
1715+ // The refusal is handed on **unchanged**, not folded into a sentence with
1716+ // the file's name: a `String` is not an error a caller can downcast, and
1717+ // `is_it` is how a front-end tells this refusal from any other failure.
1718+ // The path is not lost -- every caller that has one puts it in front.
1719+ rotation_of_exif(decoder.orientation()?)
1720+}
1721+
1472 impl Still {1722 impl Still {
1473 /// Decodes `path`. Refused by name for a picture that is not one1723 /// Decodes `path`. Refused by name for a picture that is not one
1474 /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project1724 /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project
@@ -1484,12 +1734,41 @@ impl Still {
1484 /// lands as a rectangle. Upgrade path is keeping the alpha plane here and1734 /// lands as a rectangle. Upgrade path is keeping the alpha plane here and
1485 /// giving `scale::Composer` a blend over the lane below.1735 /// giving `scale::Composer` a blend over the lane below.
1486 pub(crate) fn open(path: &Path) -> crate::Result<Self> {1736 pub(crate) fn open(path: &Path) -> crate::Result<Self> {
1487- let reader = image::ImageReader::open(path)?.with_guessed_format()?;1737+ // The turn is read and made **here**, once, before a single pair of
1488- let rgb = reader1738+ // numbers leaves this function: `image`'s decoder keeps an EXIF
1489- .decode()1739+ // orientation in its own field and applies nothing, so a portrait
1740+ // phone photo arrived as landscape planes and every consumer below --
1741+ // the `Render`, the `VideoMeta`, `image_size` -- reported the shape the
1742+ // camera stored rather than the one it was shot at. This is the same
1743+ // step the video doors make, at the same place in the pipeline
1744+ // (before the grade, the canvas and the conversion all see the
1745+ // picture), and it uses the same [`Rotation`].
1746+ let mut decoder = image::ImageReader::open(path)?
1747+ .with_guessed_format()?
1748+ .into_decoder()
1749+ .map_err(|e| format!("{}: {e}", path.display()))?;
1750+ // Unchanged for the reason `image_orientation` gives: a caller has to
1751+ // be able to downcast this refusal, and a sentence with the file's name
1752+ // in it is not one.
1753+ let rotation = rotation_of_exif(decoder.orientation()?)?;
1754+ let rgb = image::DynamicImage::from_decoder(decoder)
1490 .map_err(|e| format!("{}: {e}", path.display()))?1755 .map_err(|e| format!("{}: {e}", path.display()))?
1491 .to_rgb8();1756 .to_rgb8();
1492- let (width, height) = rgb.dimensions();1757+ let (coded_width, coded_height) = rgb.dimensions();
1758+ // Turned here rather than left to each consumer, so there is exactly
1759+ // one place the turn is made and no consumer can be forgotten: the
1760+ // planes handed out below are the *shown* picture, so the `Render`, the
1761+ // `VideoMeta`, an export's `place_picture` and `image_size` all agree
1762+ // without any of them re-deriving it. A file that states no turn takes
1763+ // the branch by a bool and not one byte is copied.
1764+ let (rgb, width, height) = match rotation.is_none() {
1765+ true => (rgb, coded_width, coded_height),
1766+ false => {
1767+ let turned = turn_rgb(&rgb, rotation.steps());
1768+ let (width, height) = turned.dimensions();
1769+ (turned, width, height)
1770+ }
1771+ };
1493 if !crate::is_resolution(width, height) {1772 if !crate::is_resolution(width, height) {
1494 return Err(format!(1773 return Err(format!(
1495 "{} is {width}x{height}, which is not a picture this engine composes",1774 "{} is {width}x{height}, which is not a picture this engine composes",
@@ -1508,19 +1787,49 @@ impl Still {
1508 }1787 }
1509 1788
1510 /// The planes as an export's decoder hands them over, so a still and a1789 /// The planes as an export's decoder hands them over, so a still and a
1511- /// decoded picture are the same value to `export::run`.1790+ /// decoded picture are the same value to `export::run` -- and, for a
1791+ /// turned still, the same value in the only sense that matters: the turn
1792+ /// is already in them, so an export places what the preview showed without
1793+ /// being told a second time.
1512 pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {1794 pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
1513 (&self.y, &self.u, &self.v, self.width, self.height)1795 (&self.y, &self.u, &self.v, self.width, self.height)
1514 }1796 }
1515 }1797 }
1516 1798
1517-/// How big the picture in `path` is, from its header alone -- what a library row1799+/// `steps` quarter turns clockwise over a packed RGB8 picture -- the same
1518-/// says about a file it has not placed anywhere. The whole file is not decoded.1800+/// direction and the same count [`crate::scale::rotate_i420_90s`] takes, on the
1801+/// still's own buffer rather than on its planes: a still is turned exactly once
1802+/// in its whole life, so there is no steady-state cost to make the allocating
1803+/// call the one that happens.
1804+fn turn_rgb(rgb: &image::RgbImage, steps: u8) -> image::RgbImage {
1805+ match steps % 4 {
1806+ 1 => image::imageops::rotate90(rgb),
1807+ 2 => image::imageops::rotate180(rgb),
1808+ 3 => image::imageops::rotate270(rgb),
1809+ _ => rgb.clone(),
1810+ }
1811+}
1812+
1813+/// How big the picture in `path` is as it is **shown**, from its header alone --
1814+/// what a library row says about a file it has not placed anywhere. The whole
1815+/// file is not decoded.
1816+///
1817+/// The turn is applied to the answer for the same reason
1818+/// [`DecodeSession::open_still`]'s is: a portrait phone photo stores landscape
1819+/// and says so in its EXIF block, and a row that answered 4000x3000 for a
1820+/// picture that is shown 3000x4000 states the wrong shape on the one surface
1821+/// that exists before anything places the file. Header-only still --
1822+/// `into_decoder` parses the container and stops.
1519 pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {1823 pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {
1520- Ok(image::ImageReader::open(path)?1824+ let rotation = image_orientation(path)?;
1825+ let (width, height) = image::ImageReader::open(path)?
1521 .with_guessed_format()?1826 .with_guessed_format()?
1522 .into_dimensions()1827 .into_dimensions()
1523- .map_err(|e| format!("{}: {e}", path.display()))?)1828+ .map_err(|e| format!("{}: {e}", path.display()))?;
1829+ Ok(match rotation.swaps_axes() {
1830+ true => (height, width),
1831+ false => (width, height),
1832+ })
1524 }1833 }
1525 1834
1526 /// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse1835 /// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse
@@ -1599,11 +1908,7 @@ const VIZ_STRAND_SAT_SHIFT: u32 = 40;
1599 const VIZ_STRAND_CHOSEN: u64 = 1 << 63;1908 const VIZ_STRAND_CHOSEN: u64 = 1 << 63;
1600 1909
1601 pub fn viz_materialize(paint: u64) -> u64 {1910 pub fn viz_materialize(paint: u64) -> u64 {
1602- if paint == 0 {1911+ if paint == 0 { VIZ_PAINT_AZURE } else { paint }
1603- VIZ_PAINT_AZURE
1604- } else {
1605- paint
1606- }
1607 }1912 }
1608 1913
1609 pub fn viz_ink_from_paint(paint: u64) -> (u8, u8, u8) {1914 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 {
1638 }1943 }
1639 1944
1640 pub fn viz_hue_ui(paint: u64) -> u8 {1945 pub fn viz_hue_ui(paint: u64) -> u8 {
1641- if paint == 0 { 150 } else { (paint & 0xFF) as u8 }1946+ if paint == 0 {
1947+ 150
1948+ } else {
1949+ (paint & 0xFF) as u8
1950+ }
1642 }1951 }
1643 1952
1644 pub fn viz_sat_ui(paint: u64) -> u8 {1953 pub fn viz_sat_ui(paint: u64) -> u8 {
@@ -1688,9 +1997,10 @@ pub fn with_viz_paint_strand_sat(paint: u64, sat: u8) -> u64 {
1688 /// Drop the chosen strand colour: the dual half of a ring goes back to the1997 /// Drop the chosen strand colour: the dual half of a ring goes back to the
1689 /// automatic complement, and both strand bytes go with the flag.1998 /// automatic complement, and both strand bytes go with the flag.
1690 pub fn viz_strand_clear(paint: u64) -> u64 {1999 pub fn viz_strand_clear(paint: u64) -> u64 {
1691- paint & !(VIZ_STRAND_CHOSEN2000+ paint
1692- | (0xFF_u64 << VIZ_STRAND_HUE_SHIFT)2001+ & !(VIZ_STRAND_CHOSEN
1693- | (0xFF_u64 << VIZ_STRAND_SAT_SHIFT))2002+ | (0xFF_u64 << VIZ_STRAND_HUE_SHIFT)
2003+ | (0xFF_u64 << VIZ_STRAND_SAT_SHIFT))
1694 }2004 }
1695 2005
1696 /// `#RRGGBB` for an ink, at the same fixed value the painter draws at, so2006 /// `#RRGGBB` for an ink, at the same fixed value the painter draws at, so
@@ -1837,8 +2147,7 @@ fn viz_stamp(
1837 if x < 0 || row < 0 || x >= w as i32 || row >= h as i32 {2147 if x < 0 || row < 0 || x >= w as i32 || row >= h as i32 {
1838 return;2148 return;
1839 }2149 }
1840- let lum =2150+ let lum = (f32::from(bg_y) + (f32::from(ink_y) - f32::from(bg_y)) * fall.clamp(0.0, 1.0)) as u8;
1841- (f32::from(bg_y) + (f32::from(ink_y) - f32::from(bg_y)) * fall.clamp(0.0, 1.0)) as u8;
1842 let idx = row as usize * w + x as usize;2151 let idx = row as usize * w + x as usize;
1843 if lum > y[idx] {2152 if lum > y[idx] {
1844 y[idx] = lum;2153 y[idx] = lum;
@@ -1871,7 +2180,9 @@ fn viz_span(
1871 ) {2180 ) {
1872 let (a, b) = if top <= bot { (top, bot) } else { (bot, top) };2181 let (a, b) = if top <= bot { (top, bot) } else { (bot, top) };
1873 for row in a..=b {2182 for row in a..=b {
1874- viz_stamp(y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v);2183+ viz_stamp(
2184+ y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v,
2185+ );
1875 }2186 }
1876 }2187 }
1877 2188
@@ -1935,7 +2246,22 @@ fn viz_line(
1935 let d2 = (ox * ox + oy * oy) as f32;2246 let d2 = (ox * ox + oy * oy) as f32;
1936 (-0.45 * d2 / (g * g).max(1) as f32).exp()2247 (-0.45 * d2 / (g * g).max(1) as f32).exp()
1937 };2248 };
1938- viz_stamp(y, u, v, w, h, cw, ch, x0 + ox, y0 + oy, fall, bg_y, ink_y, ink_u, ink_v);2249+ viz_stamp(
2250+ y,
2251+ u,
2252+ v,
2253+ w,
2254+ h,
2255+ cw,
2256+ ch,
2257+ x0 + ox,
2258+ y0 + oy,
2259+ fall,
2260+ bg_y,
2261+ ink_y,
2262+ ink_u,
2263+ ink_v,
2264+ );
1939 }2265 }
1940 }2266 }
1941 if x0 == x1 && y0 == y1 {2267 if x0 == x1 && y0 == y1 {
@@ -2034,7 +2360,14 @@ fn viz_chain(
2034 ink_v: u8,2360 ink_v: u8,
2035 glow: u8,2361 glow: u8,
2036 ) {2362 ) {
2037- let VizScratch { pts, chain, rows, cand, hull, .. } = scratch;2363+ let VizScratch {
2364+ pts,
2365+ chain,
2366+ rows,
2367+ cand,
2368+ hull,
2369+ ..
2370+ } = scratch;
2038 chain.clear();2371 chain.clear();
2039 for pair in pts.windows(2) {2372 for pair in pts.windows(2) {
2040 viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, chain);2373 viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, chain);
@@ -2047,7 +2380,9 @@ fn viz_chain(
2047 // full ink -- which is exactly what the row/by/band machinery below2380 // full ink -- which is exactly what the row/by/band machinery below
2048 // works out, one sort later.2381 // works out, one sort later.
2049 for &(x, row) in chain.iter() {2382 for &(x, row) in chain.iter() {
2050- viz_stamp(y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v);2383+ viz_stamp(
2384+ y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v,
2385+ );
2051 }2386 }
2052 return;2387 return;
2053 }2388 }
@@ -2173,7 +2508,9 @@ fn viz_chain(
2173 } else {2508 } else {
2174 (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp()2509 (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp()
2175 };2510 };
2176- viz_stamp(y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v);2511+ viz_stamp(
2512+ y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v,
2513+ );
2177 }2514 }
2178 }2515 }
2179 }2516 }
@@ -2197,7 +2534,15 @@ pub(crate) fn visualizer_i420(
2197 flags: u8,2534 flags: u8,
2198 paint: u64,2535 paint: u64,
2199 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {2536 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
2200- visualizer_window_i420(scratch, &VizView::whole(peaks), t_secs, width, height, flags, paint)2537+ visualizer_window_i420(
2538+ scratch,
2539+ &VizView::whole(peaks),
2540+ t_secs,
2541+ width,
2542+ height,
2543+ flags,
2544+ paint,
2545+ )
2201 }2546 }
2202 2547
2203 /// The envelope a visualizer frame is painted from: the whole file, or one2548 /// The envelope a visualizer frame is painted from: the whole file, or one
@@ -2404,12 +2749,36 @@ pub(crate) fn visualizer_window_i420(
2404 for dy in 1..=glow {2749 for dy in 1..=glow {
2405 let fall = 0.5 / dy as f32;2750 let fall = 0.5 / dy as f32;
2406 viz_stamp(2751 viz_stamp(
2407- &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row - dy, fall, bg_y,2752+ &mut y,
2408- ink_y, ink_u, ink_v,2753+ &mut u,
2754+ &mut v,
2755+ w,
2756+ h,
2757+ cw,
2758+ ch,
2759+ col as i32,
2760+ row - dy,
2761+ fall,
2762+ bg_y,
2763+ ink_y,
2764+ ink_u,
2765+ ink_v,
2409 );2766 );
2410 viz_stamp(2767 viz_stamp(
2411- &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row + dy, fall, bg_y,2768+ &mut y,
2412- ink_y, ink_u, ink_v,2769+ &mut u,
2770+ &mut v,
2771+ w,
2772+ h,
2773+ cw,
2774+ ch,
2775+ col as i32,
2776+ row + dy,
2777+ fall,
2778+ bg_y,
2779+ ink_y,
2780+ ink_u,
2781+ ink_v,
2413 );2782 );
2414 }2783 }
2415 }2784 }
@@ -2474,9 +2843,10 @@ pub(crate) fn visualizer_window_i420(
2474 VIZ_STYLE_WAVE => {2843 VIZ_STYLE_WAVE => {
2475 scratch.pts.clear();2844 scratch.pts.clear();
2476 for col in 0..w {2845 for col in 0..w {
2477- scratch2846+ scratch.pts.push((
2478- .pts2847+ col as i32,
2479- .push((col as i32, (center - scratch.sig[col] * half).round() as i32));2848+ (center - scratch.sig[col] * half).round() as i32,
2849+ ));
2480 }2850 }
2481 let glow = viz_glow_of(paint);2851 let glow = viz_glow_of(paint);
2482 if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) {2852 if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) {
@@ -2488,8 +2858,7 @@ pub(crate) fn visualizer_window_i420(
2488 }2858 }
2489 } else {2859 } else {
2490 viz_chain(2860 viz_chain(
2491- &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v,2861+ &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v, glow,
2492- glow,
2493 );2862 );
2494 }2863 }
2495 }2864 }
@@ -2507,12 +2876,36 @@ pub(crate) fn visualizer_window_i420(
2507 for dy in 1..=glow {2876 for dy in 1..=glow {
2508 let fall = 0.55 / dy as f32;2877 let fall = 0.55 / dy as f32;
2509 viz_stamp(2878 viz_stamp(
2510- &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, top - dy, fall, bg_y,2879+ &mut y,
2511- ink_y, ink_u, ink_v,2880+ &mut u,
2881+ &mut v,
2882+ w,
2883+ h,
2884+ cw,
2885+ ch,
2886+ col as i32,
2887+ top - dy,
2888+ fall,
2889+ bg_y,
2890+ ink_y,
2891+ ink_u,
2892+ ink_v,
2512 );2893 );
2513 viz_stamp(2894 viz_stamp(
2514- &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, bot + dy, fall, bg_y,2895+ &mut y,
2515- ink_y, ink_u, ink_v,2896+ &mut u,
2897+ &mut v,
2898+ w,
2899+ h,
2900+ cw,
2901+ ch,
2902+ col as i32,
2903+ bot + dy,
2904+ fall,
2905+ bg_y,
2906+ ink_y,
2907+ ink_u,
2908+ ink_v,
2516 );2909 );
2517 }2910 }
2518 }2911 }
@@ -2567,6 +2960,7 @@ fn run_hw(
2567 render: &mut Render,2960 render: &mut Render,
2568 abort: &Abort,2961 abort: &Abort,
2569 speed: Speed,2962 speed: Speed,
2963+ failure: &DecodeFailure,
2570 ) -> bool {2964 ) -> bool {
2571 let mut index = start_frame;2965 let mut index = start_frame;
2572 // Pictures dropped for being late since the last one handed over; see2966 // Pictures dropped for being late since the last one handed over; see
@@ -2606,10 +3000,15 @@ fn run_hw(
2606 }3000 }
2607 Ok(None) => return true,3001 Ok(None) => return true,
2608 Err(e) => {3002 Err(e) => {
3003+ // Before the first picture this is not a failure to report but
3004+ // the signal that software should take over, and it is reported
3005+ // by the caller that does the falling back -- saying it here as
3006+ // well would put a fault on the strip for a span that is about
3007+ // to decode cleanly.
2609 if index == start_frame {3008 if index == start_frame {
2610 return false;3009 return false;
2611 }3010 }
2612- eprintln!("hardware decode error at frame {index}: {e}");3011+ failure.set(format!("hardware decode error at frame {index}: {e}"));
2613 return true;3012 return true;
2614 }3013 }
2615 }3014 }
@@ -2695,7 +3094,10 @@ mod tests {
2695 "deferred open returned in {returned:?}, first frame at {first_frame:?}; \3094 "deferred open returned in {returned:?}, first frame at {first_frame:?}; \
2696 sync open returned in {sync_returned:?}"3095 sync open returned in {sync_returned:?}"
2697 );3096 );
2698- assert_eq!(frame.index, 0, "the deferred worker starts where it is told");3097+ assert_eq!(
3098+ frame.index, 0,
3099+ "the deferred worker starts where it is told"
3100+ );
2699 assert!(3101 assert!(
2700 returned < Duration::from_millis(10),3102 returned < Duration::from_millis(10),
2701 "the caller waited {returned:?} -- something is still being read \3103 "the caller waited {returned:?} -- something is still being read \
@@ -2848,7 +3250,10 @@ mod tests {
2848 let w = 320u32;3250 let w = 320u32;
2849 let h = 180u32;3251 let h = 180u32;
2850 let (y, _u, _v) = visualizer_i420(&mut VizScratch::default(), &[], 0.0, w, h, 1, 0);3252 let (y, _u, _v) = visualizer_i420(&mut VizScratch::default(), &[], 0.0, w, h, 1, 0);
2851- assert_eq!((y.len(), _u.len(), _v.len()), (320 * 180, 160 * 90, 160 * 90));3253+ assert_eq!(
3254+ (y.len(), _u.len(), _v.len()),
3255+ (320 * 180, 160 * 90, 160 * 90)
3256+ );
2852 // The ink's top and bottom row for a given peaks slice: one unbroken3257 // The ink's top and bottom row for a given peaks slice: one unbroken
2853 // band, and where it sits.3258 // band, and where it sits.
2854 let band = |peaks: &[(f32, f32)]| {3259 let band = |peaks: &[(f32, f32)]| {
@@ -3023,6 +3428,7 @@ mod tests {
3023 };3428 };
3024 let (tx, rx) = sync_channel(2);3429 let (tx, rx) = sync_channel(2);
3025 let cell = BackendCell::new(Backend::Opening);3430 let cell = BackendCell::new(Backend::Opening);
3431+ let failure = DecodeFailure::default();
3026 run_span(3432 run_span(
3027 &path,3433 &path,
3028 &mut source,3434 &mut source,
@@ -3039,6 +3445,7 @@ mod tests {
3039 },3445 },
3040 &abort,3446 &abort,
3041 &cell,3447 &cell,
3448+ &failure,
3042 );3449 );
3043 assert_eq!(3450 assert_eq!(
3044 cell.get(),3451 cell.get(),
@@ -3049,6 +3456,11 @@ mod tests {
3049 rx.try_recv().is_err(),3456 rx.try_recv().is_err(),
3050 "a gap decodes nothing: no picture may come down the channel"3457 "a gap decodes nothing: no picture may come down the channel"
3051 );3458 );
3459+ assert!(
3460+ failure.reason().is_some(),
3461+ "and it says why: a span that decoded nothing is the one case where \
3462+ a closed channel is definitely not the end of the file"
3463+ );
3052 }3464 }
3053 3465
3054 #[test]3466 #[test]
@@ -3059,10 +3471,14 @@ mod tests {
3059 *p = (-a.abs(), a.abs());3471 *p = (-a.abs(), a.abs());
3060 }3472 }
3061 let flags = 1u8;3473 let flags = 1u8;
3062- let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0);3474+ let (y, u, v) =
3475+ visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0);
3063 let ink = y.iter().filter(|&&p| p > 40).count();3476 let ink = y.iter().filter(|&&p| p > 40).count();
3064 assert!(ink > 200, "envelope missing: {ink}");3477 assert!(ink > 200, "envelope missing: {ink}");
3065- assert!(ink < y.len() * 9 / 10, "solid frame, not an envelope: {ink}");3478+ assert!(
3479+ ink < y.len() * 9 / 10,
3480+ "solid frame, not an envelope: {ink}"
3481+ );
3066 let mut blue = 0usize;3482 let mut blue = 0usize;
3067 for i in 0..u.len() {3483 for i in 0..u.len() {
3068 if u[i] > 145 && v[i] < 120 {3484 if u[i] > 145 && v[i] < 120 {
@@ -3072,13 +3488,22 @@ mod tests {
3072 assert!(blue > 10, "default ink was not timeline blue: {blue}");3488 assert!(blue > 10, "default ink was not timeline blue: {blue}");
3073 3489
3074 let ring = with_viz_style(flags, VIZ_STYLE_RING);3490 let ring = with_viz_style(flags, VIZ_STYLE_RING);
3075- let (yr, _, _) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0);3491+ let (yr, _, _) =
3492+ visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0);
3076 let ring_ink = yr.iter().filter(|&&p| p > 40).count();3493 let ring_ink = yr.iter().filter(|&&p| p > 40).count();
3077 assert!(ring_ink > 80, "ring missing: {ring_ink}");3494 assert!(ring_ink > 80, "ring missing: {ring_ink}");
3078 assert!(ring_ink < ink, "ring should be a stroke, not a fill");3495 assert!(ring_ink < ink, "ring should be a stroke, not a fill");
3079 3496
3080 let hue_paint = with_viz_paint_hue(0, 40);3497 let hue_paint = with_viz_paint_hue(0, 40);
3081- let (_, u2, v2) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 64, 32, flags, hue_paint);3498+ let (_, u2, v2) = visualizer_i420(
3499+ &mut VizScratch::default(),
3500+ &peaks,
3501+ 1.0,
3502+ 64,
3503+ 32,
3504+ flags,
3505+ hue_paint,
3506+ );
3082 let mut shifted = 0usize;3507 let mut shifted = 0usize;
3083 for i in 0..u2.len() {3508 for i in 0..u2.len() {
3084 if u2[i] < 120 && v2[i] > 130 {3509 if u2[i] < 120 && v2[i] > 130 {
@@ -3175,7 +3600,15 @@ mod tests {
3175 }3600 }
3176 let ring = with_viz_style(1, VIZ_STYLE_RING);3601 let ring = with_viz_style(1, VIZ_STYLE_RING);
3177 let auto = VIZ_PAINT_AZURE;3602 let auto = VIZ_PAINT_AZURE;
3178- let (y0, u0, v0) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, auto);3603+ let (y0, u0, v0) = visualizer_i420(
3604+ &mut VizScratch::default(),
3605+ &peaks,
3606+ 1.0,
3607+ 320,
3608+ 180,
3609+ ring,
3610+ auto,
3611+ );
3179 3612
3180 // The automatic dual is half a wheel from the clip's hue at the3613 // The automatic dual is half a wheel from the clip's hue at the
3181 // clip's own saturation; choosing exactly that colour changes3614 // clip's own saturation; choosing exactly that colour changes
@@ -3185,24 +3618,54 @@ mod tests {
3185 viz_sat_ui(auto),3618 viz_sat_ui(auto),
3186 );3619 );
3187 assert!(viz_strand_set(same));3620 assert!(viz_strand_set(same));
3188- let (ys, us, vs) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, same);3621+ let (ys, us, vs) = visualizer_i420(
3189- assert_eq!(ys, y0, "the automatic complement, spelled out, is the same frame");3622+ &mut VizScratch::default(),
3623+ &peaks,
3624+ 1.0,
3625+ 320,
3626+ 180,
3627+ ring,
3628+ same,
3629+ );
3630+ assert_eq!(
3631+ ys, y0,
3632+ "the automatic complement, spelled out, is the same frame"
3633+ );
3190 assert_eq!(us, u0);3634 assert_eq!(us, u0);
3191 assert_eq!(vs, v0);3635 assert_eq!(vs, v0);
3192 3636
3193 // A colour of its own repaints the dual strands in it.3637 // A colour of its own repaints the dual strands in it.
3194 let red = with_viz_paint_strand_sat(with_viz_paint_strand_hue(auto, 0), 255);3638 let red = with_viz_paint_strand_sat(with_viz_paint_strand_hue(auto, 0), 255);
3195- let (_, u1, v1) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, red);3639+ let (_, u1, v1) =
3196- let red_px = (0..u1.len()).filter(|&i| u1[i] < 110 && v1[i] > 200).count();3640+ visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, red);
3197- let auto_px = (0..u0.len()).filter(|&i| u0[i] < 110 && v0[i] > 200).count();3641+ let red_px = (0..u1.len())
3198- assert!(red_px > 20, "the chosen colour did not reach the frame: {red_px}");3642+ .filter(|&i| u1[i] < 110 && v1[i] > 200)
3199- assert_eq!(auto_px, 0, "the automatic ring already painted red: {auto_px}");3643+ .count();
3644+ let auto_px = (0..u0.len())
3645+ .filter(|&i| u0[i] < 110 && v0[i] > 200)
3646+ .count();
3647+ assert!(
3648+ red_px > 20,
3649+ "the chosen colour did not reach the frame: {red_px}"
3650+ );
3651+ assert_eq!(
3652+ auto_px, 0,
3653+ "the automatic ring already painted red: {auto_px}"
3654+ );
3200 3655
3201 // ...and the flag is what decides: strand bytes with it clear are3656 // ...and the flag is what decides: strand bytes with it clear are
3202 // the unset picture, byte for byte.3657 // the unset picture, byte for byte.
3203 let stale = auto | (77u64 << 32) | (9u64 << 40);3658 let stale = auto | (77u64 << 32) | (9u64 << 40);
3204 assert!(!viz_strand_set(stale));3659 assert!(!viz_strand_set(stale));
3205- let (yt, ut, vt) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, stale);3660+ let (yt, ut, vt) = visualizer_i420(
3661+ &mut VizScratch::default(),
3662+ &peaks,
3663+ 1.0,
3664+ 320,
3665+ 180,
3666+ ring,
3667+ stale,
3668+ );
3206 assert_eq!(yt, y0, "an unset strand colour is the frame it always was");3669 assert_eq!(yt, y0, "an unset strand colour is the frame it always was");
3207 assert_eq!(ut, u0);3670 assert_eq!(ut, u0);
3208 assert_eq!(vt, v0);3671 assert_eq!(vt, v0);
@@ -3250,7 +3713,15 @@ mod tests {
3250 };3713 };
3251 let flags = with_viz_style(1, style);3714 let flags = with_viz_style(1, style);
3252 let paint = with_viz_paint_glow(VIZ_PAINT_AZURE, glow);3715 let paint = with_viz_paint_glow(VIZ_PAINT_AZURE, glow);
3253- let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 37.5, 1920, 1080, flags, paint);3716+ let (y, u, v) = visualizer_i420(
3717+ &mut VizScratch::default(),
3718+ &peaks,
3719+ 37.5,
3720+ 1920,
3721+ 1080,
3722+ flags,
3723+ paint,
3724+ );
3254 let mut hash = 0xcbf2_9ce4_8422_2325u64;3725 let mut hash = 0xcbf2_9ce4_8422_2325u64;
3255 for buf in [&y, &u, &v] {3726 for buf in [&y, &u, &v] {
3256 for &b in buf.iter() {3727 for &b in buf.iter() {
@@ -3287,6 +3758,7 @@ fn run(
3287 render: &mut Render,3758 render: &mut Render,
3288 abort: &Abort,3759 abort: &Abort,
3289 speed: Speed,3760 speed: Speed,
3761+ failure: &DecodeFailure,
3290 ) {3762 ) {
3291 // A decoder per span, and cheap: it is a parameter-set map and a picture3763 // A decoder per span, and cheap: it is a parameter-set map and a picture
3292 // buffer, while the *demuxer* -- whose index cost seconds to build -- is the3764 // buffer, while the *demuxer* -- whose index cost seconds to build -- is the
@@ -3324,19 +3796,19 @@ fn run(
3324 Ok(Some(au)) => {3796 Ok(Some(au)) => {
3325 let packet = Packet::new(0, TimeBase::new(1, 1), au);3797 let packet = Packet::new(0, TimeBase::new(1, 1), au);
3326 if let Err(e) = decoder.send_packet(&packet) {3798 if let Err(e) = decoder.send_packet(&packet) {
3327- eprintln!("decode error at access unit {index}: {e}");3799+ failure.set(format!("decode error at access unit {index}: {e}"));
3328 break;3800 break;
3329 }3801 }
3330 }3802 }
3331 Ok(None) => {3803 Ok(None) => {
3332 flushed = true;3804 flushed = true;
3333 if let Err(e) = decoder.flush() {3805 if let Err(e) = decoder.flush() {
3334- eprintln!("decode error at end of stream: {e}");3806+ failure.set(format!("decode error at end of stream: {e}"));
3335 break;3807 break;
3336 }3808 }
3337 }3809 }
3338 Err(e) => {3810 Err(e) => {
3339- eprintln!("demux error: {e}");3811+ failure.set(format!("demux error: {e}"));
3340 break;3812 break;
3341 }3813 }
3342 }3814 }
@@ -3347,7 +3819,7 @@ fn run(
3347 Ok(pic) => pic,3819 Ok(pic) => pic,
3348 Err(e) if e.is_need_more() || e.is_eof() => break,3820 Err(e) if e.is_need_more() || e.is_eof() => break,
3349 Err(e) => {3821 Err(e) => {
3350- eprintln!("decode error at access unit {index}: {e}");3822+ failure.set(format!("decode error at access unit {index}: {e}"));
3351 break;3823 break;
3352 }3824 }
3353 };3825 };
@@ -3474,6 +3946,7 @@ fn run_av1(
3474 render: &mut Render,3946 render: &mut Render,
3475 abort: &Abort,3947 abort: &Abort,
3476 speed: Speed,3948 speed: Speed,
3949+ failure: &DecodeFailure,
3477 ) {3950 ) {
3478 // Signed, for the same reason [`run`]'s is: the landing sync sample can3951 // Signed, for the same reason [`run`]'s is: the landing sync sample can
3479 // sit inside what an mp4's edit list trims, i.e. before frame 0.3952 // sit inside what an mp4's edit list trims, i.e. before frame 0.
@@ -3505,7 +3978,7 @@ fn run_av1(
3505 }3978 }
3506 Ok(None) => demux_dry = true,3979 Ok(None) => demux_dry = true,
3507 Err(e) => {3980 Err(e) => {
3508- eprintln!("demux error: {e}");3981+ failure.set(format!("demux error: {e}"));
3509 return;3982 return;
3510 }3983 }
3511 }3984 }
@@ -3561,12 +4034,11 @@ fn run_av1(
3561 // the pictures decoded so far stand and the span ends.4034 // the pictures decoded so far stand and the span ends.
3562 if let Err(e) = decode {4035 if let Err(e) = decode {
3563 if !done {4036 if !done {
3564- eprintln!("software AV1 decode failed at frame {index}: {e}");4037+ failure.set(format!("software AV1 decode failed at frame {index}: {e}"));
3565 done = true;4038 done = true;
3566 }4039 }
3567 }4040 }
3568 }4041 }
3569-
3570 }4042 }
3571 4043
3572 /// Converts one decoded picture and queues it. `true` when the consumer went4044 /// Converts one decoded picture and queues it. `true` when the consumer went
crates/engine/src/export.rsmodified+242 -172
@@ -62,8 +62,8 @@ use std::sync::{Arc, Mutex};
62 use std::thread;62 use std::thread;
63 63
64 use ec_core::frame::VideoFrame;64 use ec_core::frame::VideoFrame;
65-use ec_core::registry::{CodecId, CodecParameters};
66 use ec_core::registry::Decoder as _;65 use ec_core::registry::Decoder as _;
66+use ec_core::registry::{CodecId, CodecParameters};
67 use ec_core::{Packet, TimeBase};67 use ec_core::{Packet, TimeBase};
68 use ec_h264::{Encoder, EncoderConfig, H264Decoder, PictureView, Preset};68 use ec_h264::{Encoder, EncoderConfig, H264Decoder, PictureView, Preset};
69 use ec_h265::encoder::{Encoder as HevcEncoder, EncoderConfig as HevcEncoderConfig, RateControl};69 use ec_h265::encoder::{Encoder as HevcEncoder, EncoderConfig as HevcEncoderConfig, RateControl};
@@ -86,7 +86,7 @@ use crate::mux::{
86 AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams,86 AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams,
87 };87 };
88 use crate::project::{Lane, LaneKind, Project, Rate};88 use crate::project::{Lane, LaneKind, Project, Rate};
89-use crate::scale::{blend_i420, Composer};89+use crate::scale::{Composer, blend_i420};
90 use crate::subtitle::{Cue, SubtitleTrack};90 use crate::subtitle::{Cue, SubtitleTrack};
91 use crate::tonemap::{self, ToneMapper};91 use crate::tonemap::{self, ToneMapper};
92 use crate::transform::TransformParams;92 use crate::transform::TransformParams;
@@ -559,84 +559,84 @@ pub fn start(
559 let part = PathBuf::from(part);559 let part = PathBuf::from(part);
560 let spawned = thread::Builder::new().name("export".into()).spawn(move || {560 let spawned = thread::Builder::new().name("export".into()).spawn(move || {
561 let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {561 let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
562- // Every file this export will read, named before a byte of one is.562+ // Every file this export will read, named before a byte of one is.
563- // These are the project's own sources and can be nothing else: a563+ // These are the project's own sources and can be nothing else: a
564- // stand-in ([`crate::proxy`]) is a substitution playback makes when it564+ // stand-in ([`crate::proxy`]) is a substitution playback makes when it
565- // opens a span, and nothing here knows such a thing exists. Printed so565+ // opens a span, and nothing here knows such a thing exists. Printed so
566- // that "the delivery came off the film itself" is a grep rather than a566+ // that "the delivery came off the film itself" is a grep rather than a
567- // belief.567+ // belief.
568- for source in project.sources() {568+ for source in project.sources() {
569- eprintln!("export source: {}", source.path.display());569+ eprintln!("export source: {}", source.path.display());
570- }
571- // The rename is the last step and the only one that publishes a file
572- // under the name the caller asked for; it stays on the same directory,
573- // so it is atomic.
574- //
575- // An emptied timeline is a legal project and an illegal file: no
576- // picture, no sound, and a muxer that is never created because no coded
577- // frame arrives. Refused by name here -- before the format is even
578- // looked at, so an mp4 and a WAV refuse in the same words -- rather than
579- // left to write a file of no frames that nothing opens. Every caller of
580- // `start` comes through this, the app's own door
581- // (`PlaybackSession::is_empty`) being only the first fence.
582- //
583- // An audio-only timeline is the other legal project no mp4 can be made
584- // of: every frame of it is a gap, so the file would be black picture
585- // over the sound -- minutes of encoding for a video of nothing. Refused
586- // by name, with the two formats that *are* that timeline, rather than
587- // written; the app says the same on the format row before a destination
588- // is even picked (`mp4_refusal`).
589- let written = match settings.format {
590- _ if project.timeline_frames() == 0 => {
591- Err("the timeline is empty: there is nothing to export".into())
592 }570 }
593- format if format.has_video() && !has_picture(&project) => Err(format!(571+ // The rename is the last step and the only one that publishes a file
594- "the timeline has no picture: {} would be black. Export WAV, \572+ // under the name the caller asked for; it stays on the same directory,
573+ // so it is atomic.
574+ //
575+ // An emptied timeline is a legal project and an illegal file: no
576+ // picture, no sound, and a muxer that is never created because no coded
577+ // frame arrives. Refused by name here -- before the format is even
578+ // looked at, so an mp4 and a WAV refuse in the same words -- rather than
579+ // left to write a file of no frames that nothing opens. Every caller of
580+ // `start` comes through this, the app's own door
581+ // (`PlaybackSession::is_empty`) being only the first fence.
582+ //
583+ // An audio-only timeline is the other legal project no mp4 can be made
584+ // of: every frame of it is a gap, so the file would be black picture
585+ // over the sound -- minutes of encoding for a video of nothing. Refused
586+ // by name, with the two formats that *are* that timeline, rather than
587+ // written; the app says the same on the format row before a destination
588+ // is even picked (`mp4_refusal`).
589+ let written = match settings.format {
590+ _ if project.timeline_frames() == 0 => {
591+ Err("the timeline is empty: there is nothing to export".into())
592+ }
593+ format if format.has_video() && !has_picture(&project) => Err(format!(
594+ "the timeline has no picture: {} would be black. Export WAV, \
595 FLAC or MP3, which are the sound itself",595 FLAC or MP3, which are the sound itself",
596- format.name()596+ format.name()
597- )597+ )
598- .into()),598+ .into()),
599- format if format.has_video() => {599+ format if format.has_video() => {
600- let first = run(&project, &meta, &part, &worker, &settings, sample_rate);600+ let first = run(&project, &meta, &part, &worker, &settings, sample_rate);
601- match first {601+ match first {
602- // The hardware encoder's *process* died under the driver602+ // The hardware encoder's *process* died under the driver
603- // ([`crate::hwproc`]) -- the editor is still here, and the603+ // ([`crate::hwproc`]) -- the editor is still here, and the
604- // file is still owed. Written again by the software encoder604+ // file is still owed. Written again by the software encoder
605- // for this codec, from the first frame: the pictures the605+ // for this codec, from the first frame: the pictures the
606- // dead seat coded are not ones this one may continue from.606+ // dead seat coded are not ones this one may continue from.
607- //607+ //
608- // Not where a person picked the GPU by name: that export608+ // Not where a person picked the GPU by name: that export
609- // refuses in words, the same answer [`hw_seat`] already609+ // refuses in words, the same answer [`hw_seat`] already
610- // gives a machine with no seat at all, rather than quietly610+ // gives a machine with no seat at all, rather than quietly
611- // spending an hour in an encoder nobody chose.611+ // spending an hour in an encoder nobody chose.
612- Err(e)612+ Err(e)
613- if crate::hwproc::is_lost(&e)613+ if crate::hwproc::is_lost(&e)
614- && settings.seat != EncoderSeat::Hardware =>614+ && settings.seat != EncoderSeat::Hardware =>
615- {615+ {
616- eprintln!("export video: {e}; writing it again in software");616+ eprintln!("export video: {e}; writing it again in software");
617- let _ = std::fs::remove_file(&part);617+ let _ = std::fs::remove_file(&part);
618- // The bar is *not* put back to zero: the rerun writes618+ // The bar is *not* put back to zero: the rerun writes
619- // it with `fetch_max` like everything else619+ // it with `fetch_max` like everything else
620- // ([`Shared::progress`]), so it holds where the dead620+ // ([`Shared::progress`]), so it holds where the dead
621- // seat left it and moves again once the software621+ // seat left it and moves again once the software
622- // encoder passes that mark. A person whose GPU has just622+ // encoder passes that mark. A person whose GPU has just
623- // died is the last one who should also watch the bar623+ // died is the last one who should also watch the bar
624- // run backwards.624+ // run backwards.
625- let mut software = settings.clone();625+ let mut software = settings.clone();
626- software.seat = EncoderSeat::Software;626+ software.seat = EncoderSeat::Software;
627- run(&project, &meta, &part, &worker, &software, sample_rate)627+ run(&project, &meta, &part, &worker, &software, sample_rate)
628+ }
629+ other => other,
628 }630 }
629- other => other,
630 }631 }
632+ _ => run_audio(&project, &meta, &part, &worker, &settings, sample_rate),
633+ };
634+ let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));
635+ if result.is_err() {
636+ // The muxer -- and with it the file handle -- died with `run`.
637+ let _ = std::fs::remove_file(&part);
631 }638 }
632- _ => run_audio(&project, &meta, &part, &worker, &settings, sample_rate),639+ settle(&worker, result);
633- };
634- let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));
635- if result.is_err() {
636- // The muxer -- and with it the file handle -- died with `run`.
637- let _ = std::fs::remove_file(&part);
638- }
639- settle(&worker, result);
640 }));640 }));
641 if let Err(payload) = caught {641 if let Err(payload) = caught {
642 // The body above panicked before it could settle its own slot --642 // The body above panicked before it could settle its own slot --
@@ -654,7 +654,10 @@ pub fn start(
654 // a panic never reaches. Done inside this branch only -- a body654 // a panic never reaches. Done inside this branch only -- a body
655 // that *did* settle has already renamed or deleted the file.655 // that *did* settle has already renamed or deleted the file.
656 let _ = std::fs::remove_file(&part);656 let _ = std::fs::remove_file(&part);
657- settle(&panic_worker, Err(format!("export worker panicked: {message}").into()));657+ settle(
658+ &panic_worker,
659+ Err(format!("export worker panicked: {message}").into()),
660+ );
658 }661 }
659 }662 }
660 });663 });
@@ -710,10 +713,12 @@ fn mastered(project: &Project) -> bool {
710 /// packet copy carries neither an equalizer nor a fade. An mp4 whose timeline713 /// packet copy carries neither an equalizer nor a fade. An mp4 whose timeline
711 /// has one is decoded and re-encoded so the fade actually reaches the file.714 /// has one is decoded and re-encoded so the fade actually reaches the file.
712 fn faded(project: &Project) -> bool {715 fn faded(project: &Project) -> bool {
713- project716+ project.audio_lanes().into_iter().any(|lane| {
714- .audio_lanes()717+ project
715- .into_iter()718+ .lane(lane)
716- .any(|lane| project.lane(lane).iter().any(|c| c.fade_in > 0 || c.fade_out > 0))719+ .iter()
720+ .any(|c| c.fade_in > 0 || c.fade_out > 0)
721+ })
717 }722 }
718 723
719 /// The bitrate an export codes at: the caller's number clamped into what an724 /// 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 {
1439 // Drawn over the picture, written into no file -- the same sentence1444 // Drawn over the picture, written into no file -- the same sentence
1440 // a picked track gets, because it is the track and not the lane that1445 // a picked track gets, because it is the track and not the lane that
1441 // cannot be carried.1446 // cannot be carried.
1442- dropped.push(format!("{label} {} — pictures; drawn, not written", t.label));1447+ dropped.push(format!(
1448+ "{label} {} — pictures; drawn, not written",
1449+ t.label
1450+ ));
1443 } else if first.start >= end {1451 } else if first.start >= end {
1444 dropped.push(format!("{label} {name}— past the last picture"));1452 dropped.push(format!("{label} {name}— past the last picture"));
1445 } else {1453 } else {
@@ -1480,12 +1488,15 @@ fn planned_lanes(project: &Project, format: Format, lanes: &[Lane]) -> String {
1480 /// Costs that open (~100 ms here): ask it off a render thread and keep the1488 /// Costs that open (~100 ms here): ask it off a render thread and keep the
1481 /// answer until the format, the resolution or the bitrate changes.1489 /// answer until the format, the resolution or the bitrate changes.
1482 pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> {1490 pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> {
1483- settings.format.has_video().then(|| match hw_seat(meta, settings) {1491+ settings
1484- Ok(hw) => video_label(settings.format, hw.is_some()),1492+ .format
1485- // The seat the settings demand and this machine has not: the very1493+ .has_video()
1486- // refusal [`start`] would settle with, said on the card instead.1494+ .then(|| match hw_seat(meta, settings) {
1487- Err(_) => NO_HW_SEAT,1495+ Ok(hw) => video_label(settings.format, hw.is_some()),
1488- })1496+ // The seat the settings demand and this machine has not: the very
1497+ // refusal [`start`] would settle with, said on the card instead.
1498+ Err(_) => NO_HW_SEAT,
1499+ })
1489 }1500 }
1490 1501
1491 /// What [`start`] would open for *this* timeline: the picture's seat -- or the1502 /// What [`start`] would open for *this* timeline: the picture's seat -- or the
@@ -1781,7 +1792,11 @@ struct CopyRegion {
1781 /// clip -- which the same format would carry exactly if the edit let it, so1792 /// clip -- which the same format would carry exactly if the edit let it, so
1782 /// those six [`CopyPlan::of`] gates are named together rather than picked1793 /// those six [`CopyPlan::of`] gates are named together rather than picked
1783 /// apart into six different sentences.1794 /// apart into six different sentences.
1784-pub fn exact_refusal(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option<String> {1795+pub fn exact_refusal(
1796+ project: &Project,
1797+ meta: &VideoMeta,
1798+ settings: &ExportSettings,
1799+) -> Option<String> {
1785 if !settings.exact || CopyPlan::of(project, meta, settings).is_some() {1800 if !settings.exact || CopyPlan::of(project, meta, settings).is_some() {
1786 return None;1801 return None;
1787 }1802 }
@@ -2246,9 +2261,9 @@ fn encode_audio(
2246 let out_frames = range.map_or(project.media_frames(), |(s, e)| {2261 let out_frames = range.map_or(project.media_frames(), |(s, e)| {
2247 e.min(project.media_frames()).saturating_sub(s)2262 e.min(project.media_frames()).saturating_sub(s)
2248 });2263 });
2249- let total =2264+ let total = (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round()
2250- (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() as usize2265+ as usize
2251- * channels;2266+ * channels;
2252 let mut samples: Vec<f32> = Vec::with_capacity(total);2267 let mut samples: Vec<f32> = Vec::with_capacity(total);
2253 for chunk in chunks {2268 for chunk in chunks {
2254 // The only place a cancelled export can be answered before the whole2269 // The only place a cancelled export can be answered before the whole
@@ -2567,9 +2582,15 @@ fn opus_fidelity(
2567 for w in 0..FIDELITY_WINDOWS {2582 for w in 0..FIDELITY_WINDOWS {
2568 let at = w * step;2583 let at = w * step;
2569 let from = at.saturating_sub(FIDELITY_WARMUP);2584 let from = at.saturating_sub(FIDELITY_WARMUP);
2570- let Some(fidelity) =2585+ let Some(fidelity) = window_fidelity(
2571- window_fidelity(packets, samples, pre_skip, channels, from, at, at + FIDELITY_WINDOW)2586+ packets,
2572- else {2587+ samples,
2588+ pre_skip,
2589+ channels,
2590+ from,
2591+ at,
2592+ at + FIDELITY_WINDOW,
2593+ ) else {
2573 continue; // silence: nothing to correlate, and not a failure2594 continue; // silence: nothing to correlate, and not a failure
2574 };2595 };
2575 scores.push(fidelity);2596 scores.push(fidelity);
@@ -2758,9 +2779,9 @@ fn run(
2758 // The range's own length where one is marked, the media's otherwise --2779 // The range's own length where one is marked, the media's otherwise --
2759 // `export_spans` walks the same window, so `done` ends on this `total`2780 // `export_spans` walks the same window, so `done` ends on this `total`
2760 // exactly as it always did.2781 // exactly as it always did.
2761- let total = settings2782+ let total = settings.range.map_or(project.media_frames(), |(s, e)| {
2762- .range2783+ e.min(project.media_frames()).saturating_sub(s)
2763- .map_or(project.media_frames(), |(s, e)| e.min(project.media_frames()).saturating_sub(s));2784+ });
2764 // The two preview switches are the H.264 mp4 pair's alone. Only that2785 // The two preview switches are the H.264 mp4 pair's alone. Only that
2765 // container carries a colour of its own back out ([`write_video`] tags it2786 // container carries a colour of its own back out ([`write_video`] tags it
2766 // there), so asking any other for a source-space file would write pictures2787 // there), so asking any other for a source-space file would write pictures
@@ -2807,12 +2828,8 @@ fn run(
2807 // of the two. On this project's own film that is 168 s of AC-3 that no2828 // of the two. On this project's own film that is 168 s of AC-3 that no
2808 // longer stands in front of 733 s of hardware H.264.2829 // longer stands in front of 733 s of hardware H.264.
2809 let audio_job = {2830 let audio_job = {
2810- let (project, meta, settings, shared) = (2831+ let (project, meta, settings, shared) =
2811- project.clone(),2832+ (project.clone(), *meta, settings.clone(), Arc::clone(shared));
2812- *meta,
2813- settings.clone(),
2814- Arc::clone(shared),
2815- );
2816 thread::Builder::new()2833 thread::Builder::new()
2817 .name("export-audio".into())2834 .name("export-audio".into())
2818 .spawn(move || {2835 .spawn(move || {
@@ -2955,7 +2972,15 @@ fn run(
2955 // it replaced -- and the sound says whether it was copied or encoded, which2972 // it replaced -- and the sound says whether it was copied or encoded, which
2956 // only `copy_audio` knows and, on the overlapped path, does not know yet.2973 // only `copy_audio` knows and, on the overlapped path, does not know yet.
2957 let seat = encoder.label();2974 let seat = encoder.label();
2958- publish_seats(shared, seat, project, settings, sound, opus, audio_job.running());2975+ publish_seats(
2976+ shared,
2977+ seat,
2978+ project,
2979+ settings,
2980+ sound,
2981+ opus,
2982+ audio_job.running(),
2983+ );
2959 // When the picture started, so the stage line below can say where under it2984 // When the picture started, so the stage line below can say where under it
2960 // the sound landed -- the one number that says whether the two passes2985 // the sound landed -- the one number that says whether the two passes
2961 // really overlapped, in the same voice as `encode_audio`'s own timers.2986 // really overlapped, in the same voice as `encode_audio`'s own timers.
@@ -2994,9 +3019,8 @@ fn run(
2994 // A's pixels on the CPU, so a dissolving span never asks for a GPU3019 // A's pixels on the CPU, so a dissolving span never asks for a GPU
2995 // buffer, not even outside its own window.3020 // buffer, not even outside its own window.
2996 let dissolve = dissolve_window(project, &span);3021 let dissolve = dissolve_window(project, &span);
2997- let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) =3022+ let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) = match span.from
2998- match span.from3023+ {
2999- {
3000 Some((source, in_frame)) => {3024 Some((source, in_frame)) => {
3001 let entry = sources3025 let entry = sources
3002 .get(source)3026 .get(source)
@@ -3046,7 +3070,15 @@ fn run(
3046 } else {3070 } else {
3047 ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)?3071 ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)?
3048 };3072 };
3049- (Some(pictures), rate, in_frame, Some(color), mapper, rotation, pixel_aspect)3073+ (
3074+ Some(pictures),
3075+ rate,
3076+ in_frame,
3077+ Some(color),
3078+ mapper,
3079+ rotation,
3080+ pixel_aspect,
3081+ )
3050 }3082 }
3051 // A gap's black is 16/128/128, which is black in every matrix here3083 // A gap's black is 16/128/128, which is black in every matrix here
3052 // and on every curve: nothing to remap and nothing to tone-map,3084 // and on every curve: nothing to remap and nothing to tone-map,
@@ -3105,52 +3137,54 @@ fn run(
3105 // files together for exactly the frames the tail below blends, and3137 // files together for exactly the frames the tail below blends, and
3106 // nothing else in this span ever touches it.3138 // nothing else in this span ever touches it.
3107 let mut b = dissolve3139 let mut b = dissolve
3108- .map(|(b_source, b_in_frame, window, b_start)| -> crate::Result<_> {3140+ .map(
3109- let entry = sources.get(b_source).ok_or_else(|| {3141+ |(b_source, b_in_frame, window, b_start)| -> crate::Result<_> {
3110- format!("clip names source {b_source} of {}", sources.len())3142+ let entry = sources.get(b_source).ok_or_else(|| {
3111- })?;3143+ format!("clip names source {b_source} of {}", sources.len())
3112- let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source];3144+ })?;
3113- let b_mapper = tone[b_source].as_ref();3145+ let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source];
3114- let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix);3146+ let b_mapper = tone[b_source].as_ref();
3115- Ok(Dissolve {3147+ let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix);
3116- window,3148+ Ok(Dissolve {
3117- tail_start: span.len - window,3149+ window,
3118- decoder: if crate::is_audio(&entry.path)3150+ tail_start: span.len - window,
3119- || project.composite_visualizer_at(b_start) & 1 != 03151+ decoder: if crate::is_audio(&entry.path)
3120- {3152+ || project.composite_visualizer_at(b_start) & 1 != 0
3121- ClipDecoder::visualizer(3153+ {
3122- &entry.path,3154+ ClipDecoder::visualizer(
3123- entry.audio_stream,3155+ &entry.path,
3124- b_rate.source_at(b_in_frame),3156+ entry.audio_stream,
3157+ b_rate.source_at(b_in_frame),
3158+ meta.width,
3159+ meta.height,
3160+ meta.frame_rate,
3161+ project.composite_visualizer_at(b_start),
3162+ project.composite_viz_paint_at(b_start),
3163+ )?
3164+ } else {
3165+ ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)?
3166+ },
3167+ mapper: b_mapper,
3168+ remap: b_remap,
3169+ grade: project.composite_color_at(b_start).copied(),
3170+ transform: project
3171+ .composite_transform_at(b_start)
3172+ .copied()
3173+ .unwrap_or_default(),
3174+ rotation: b_rotation,
3175+ pixel_aspect: b_pixel_aspect,
3176+ canvas: Composer::new(
3125 meta.width,3177 meta.width,
3126 meta.height,3178 meta.height,
3127- meta.frame_rate,3179+ project.composite_fit_at(b_start),
3128- project.composite_visualizer_at(b_start),3180+ ),
3129- project.composite_viz_paint_at(b_start),3181+ rotated: (Vec::new(), Vec::new(), Vec::new()),
3130- )?3182+ stretched: (Vec::new(), Vec::new(), Vec::new()),
3131- } else {3183+ graded: (Vec::new(), Vec::new(), Vec::new()),
3132- ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)?3184+ transformed: (Vec::new(), Vec::new(), Vec::new()),
3133- },3185+ })
3134- mapper: b_mapper,3186+ },
3135- remap: b_remap,3187+ )
3136- grade: project.composite_color_at(b_start).copied(),
3137- transform: project
3138- .composite_transform_at(b_start)
3139- .copied()
3140- .unwrap_or_default(),
3141- rotation: b_rotation,
3142- pixel_aspect: b_pixel_aspect,
3143- canvas: Composer::new(
3144- meta.width,
3145- meta.height,
3146- project.composite_fit_at(b_start),
3147- ),
3148- rotated: (Vec::new(), Vec::new(), Vec::new()),
3149- stretched: (Vec::new(), Vec::new(), Vec::new()),
3150- graded: (Vec::new(), Vec::new(), Vec::new()),
3151- transformed: (Vec::new(), Vec::new(), Vec::new()),
3152- })
3153- })
3154 .transpose()?;3188 .transpose()?;
3155 // Timeline frames, taken a *source* frame at a time: at a rate other3189 // Timeline frames, taken a *source* frame at a time: at a rate other
3156 // than real time the two are not the same count, and the span says which3190 // than real time the two are not the same count, and the span says which
@@ -3287,9 +3321,21 @@ fn run(
3287 }3321 }
3288 Some(Frame::Pixels(by, bu, bv, bw, bh)) => {3322 Some(Frame::Pixels(by, bu, bv, bw, bh)) => {
3289 let (by, bu, bv, _, _) = place_picture(3323 let (by, bu, bv, _, _) = place_picture(
3290- by, bu, bv, bw, bh, d.rotation, d.pixel_aspect, d.grade,3324+ by,
3291- d.transform, d.remap, d.mapper, &mut d.rotated,3325+ bu,
3292- &mut d.stretched, &mut d.graded, &mut d.transformed,3326+ bv,
3327+ bw,
3328+ bh,
3329+ d.rotation,
3330+ d.pixel_aspect,
3331+ d.grade,
3332+ d.transform,
3333+ d.remap,
3334+ d.mapper,
3335+ &mut d.rotated,
3336+ &mut d.stretched,
3337+ &mut d.graded,
3338+ &mut d.transformed,
3293 &mut d.canvas,3339 &mut d.canvas,
3294 );3340 );
3295 let idx_in_window = done_here + r - d.tail_start;3341 let idx_in_window = done_here + r - d.tail_start;
@@ -3470,7 +3516,9 @@ fn place_picture<'a>(
3470 display_width.div_ceil(2) as usize,3516 display_width.div_ceil(2) as usize,
3471 height.div_ceil(2) as usize,3517 height.div_ceil(2) as usize,
3472 );3518 );
3473- stretched.0.resize(display_width as usize * height as usize, 0);3519+ stretched
3520+ .0
3521+ .resize(display_width as usize * height as usize, 0);
3474 stretched.1.resize(dcw * dch, 0);3522 stretched.1.resize(dcw * dch, 0);
3475 stretched.2.resize(dcw * dch, 0);3523 stretched.2.resize(dcw * dch, 0);
3476 crate::scale::scale_i420(3524 crate::scale::scale_i420(
@@ -3549,7 +3597,13 @@ fn place_picture<'a>(
3549 } else {3597 } else {
3550 let (py, pu, pv, w, h) = canvas.place_transformed(y, u, v, width, height, &transform);3598 let (py, pu, pv, w, h) = canvas.place_transformed(y, u, v, width, height, &transform);
3551 *transformed = (py, pu, pv);3599 *transformed = (py, pu, pv);
3552- (&transformed.0[..], &transformed.1[..], &transformed.2[..], w, h)3600+ (
3601+ &transformed.0[..],
3602+ &transformed.1[..],
3603+ &transformed.2[..],
3604+ w,
3605+ h,
3606+ )
3553 }3607 }
3554 }3608 }
3555 3609
@@ -3594,7 +3648,10 @@ fn source_rate(
3594 // `decode::rgb_to_i420` is the one matrix that turns its pixels into3648 // `decode::rgb_to_i420` is the one matrix that turns its pixels into
3595 // planes. A song has no picture and the answer is never read. Neither3649 // planes. A song has no picture and the answer is never read. Neither
3596 // has a display matrix to be turned by, nor an aspect to be widened3650 // has a display matrix to be turned by, nor an aspect to be widened
3597- // by: both are authored square.3651+ // by: both are authored square. A still's *EXIF* turn is not in this
3652+ // arm either, and for a better reason -- `decode::Still::open` already
3653+ // made it before the planes were written, so `place_picture` is handed
3654+ // the picture the preview showed and must not be told to turn it again.
3598 return (3655 return (
3599 Rate::REAL_TIME,3656 Rate::REAL_TIME,
3600 ColorDescription::default(),3657 ColorDescription::default(),
@@ -3694,9 +3751,8 @@ fn run_audio(
3694 };3751 };
3695 // The picture path's line, for a file that is sound alone: there is sound3752 // The picture path's line, for a file that is sound alone: there is sound
3696 // by the line above, so this names the encoder writing it.3753 // by the line above, so this names the encoder writing it.
3697- *shared.encoders.lock().unwrap() = Some(3754+ *shared.encoders.lock().unwrap() =
3698- audio_label(project, format, true, None, settings.range.is_some()).to_string(),3755+ Some(audio_label(project, format, true, None, settings.range.is_some()).to_string());
3699- );
3700 let channels = usize::from(audio.channels);3756 let channels = usize::from(audio.channels);
3701 let out_frames = settings.range.map_or(project.media_frames(), |(s, e)| {3757 let out_frames = settings.range.map_or(project.media_frames(), |(s, e)| {
3702 e.min(project.media_frames()).saturating_sub(s)3758 e.min(project.media_frames()).saturating_sub(s)
@@ -4516,9 +4572,7 @@ impl Enc {
4516 cfg.timing = Some((fps_den, fps_num));4572 cfg.timing = Some((fps_den, fps_num));
4517 cfg.video_signal_type = Some(video_signal_type(meta.height));4573 cfg.video_signal_type = Some(video_signal_type(meta.height));
4518 cfg.threads = per_lane;4574 cfg.threads = per_lane;
4519- lanes.push(4575+ lanes.push(HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?);
4520- HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?,
4521- );
4522 }4576 }
4523 Ok(Self::Hevc(HevcEnc {4577 Ok(Self::Hevc(HevcEnc {
4524 pending: Vec::new(),4578 pending: Vec::new(),
@@ -4579,7 +4633,9 @@ impl Enc {
4579 // them is a sync point -- said as a constant rather than parsed back4633 // them is a sync point -- said as a constant rather than parsed back
4580 // out of the bitstream, because it is this encoder's configuration4634 // out of the bitstream, because it is this encoder's configuration
4581 // and not a driver's choice.4635 // and not a driver's choice.
4582- Self::HevcHw(hw) => Ok(hw.encode(y, u, v, width, height, true)?.map(|au| (au, true))),4636+ Self::HevcHw(hw) => Ok(hw
4637+ .encode(y, u, v, width, height, true)?
4638+ .map(|au| (au, true))),
4583 Self::Hevc(hevc) => {4639 Self::Hevc(hevc) => {
4584 // The display-size planes are kept as they came: `ec-h265`4640 // The display-size planes are kept as they came: `ec-h265`
4585 // pads to its own coded grid and crops back through the SPS4641 // pads to its own coded grid and crops back through the SPS
@@ -4970,7 +5026,11 @@ impl ClipDecoder {
4970 .ok()5026 .ok()
4971 .flatten()5027 .flatten()
4972 .unwrap_or_default();5028 .unwrap_or_default();
4973- let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 };5029+ let fps = if fps.is_finite() && fps > 0.0 {
5030+ fps
5031+ } else {
5032+ 30.0
5033+ };
4974 Ok(Self::Visualizer {5034 Ok(Self::Visualizer {
4975 peaks,5035 peaks,
4976 width,5036 width,
@@ -5236,9 +5296,7 @@ impl SwDecoder {
5236 // either answer means go back for the next access unit.5296 // either answer means go back for the next access unit.
5237 Err(e) if e.is_eof() && self.flushed => return Ok(false),5297 Err(e) if e.is_eof() && self.flushed => return Ok(false),
5238 Err(e) if e.is_need_more() || e.is_eof() => {}5298 Err(e) if e.is_need_more() || e.is_eof() => {}
5239- Err(e) => {5299+ Err(e) => return Err(format!("decode at picture {}: {e}", self.index).into()),
5240- return Err(format!("decode at picture {}: {e}", self.index).into())
5241- }
5242 }5300 }
5243 }5301 }
5244 }5302 }
@@ -5767,7 +5825,11 @@ mod tests {
5767 // 1280 * 720 * 30 * 0.15825 // 1280 * 720 * 30 * 0.1
5768 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);5826 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
5769 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), 230_400, "tiny");5827 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), 230_400, "tiny");
5770- assert_eq!(bitrate_for(&meta(160, 120, 15.0)), MIN_BITRATE, "tinier floors");5828+ assert_eq!(
5829+ bitrate_for(&meta(160, 120, 15.0)),
5830+ MIN_BITRATE,
5831+ "tinier floors"
5832+ );
5771 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");5833 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
5772 // A rate somebody typed goes through untouched to its own ceiling, which5834 // A rate somebody typed goes through untouched to its own ceiling, which
5773 // is above where the derived one stops: the card offers 50 Mbps, and a5835 // is above where the derived one stops: the card offers 50 Mbps, and a
@@ -5799,7 +5861,11 @@ mod tests {
5799 fn a_fade_forces_the_audio_to_be_re_encoded() {5861 fn a_fade_forces_the_audio_to_be_re_encoded() {
5800 let mut project = Project::single("/nonexistent/film.mp4", 90);5862 let mut project = Project::single("/nonexistent/film.mp4", 90);
5801 assert!(!forces_encode(&project, false), "flat, so a copy is fine");5863 assert!(!forces_encode(&project, false), "flat, so a copy is fine");
5802- assert!(project.set_fade_in(crate::project::Lane::new(crate::project::LaneKind::Audio, 0), 0, 15));5864+ assert!(project.set_fade_in(
5865+ crate::project::Lane::new(crate::project::LaneKind::Audio, 0),
5866+ 0,
5867+ 15
5868+ ));
5803 assert!(5869 assert!(
5804 forces_encode(&project, false),5870 forces_encode(&project, false),
5805 "a fade-in on the only clip must force a re-encode"5871 "a fade-in on the only clip must force a re-encode"
@@ -5908,7 +5974,11 @@ mod tests {
5908 /// B, and the window itself never quite repeats a hard cut's own instant.5974 /// B, and the window itself never quite repeats a hard cut's own instant.
5909 #[test]5975 #[test]
5910 fn dissolve_weight_ramps_strictly_between_zero_and_one() {5976 fn dissolve_weight_ramps_strictly_between_zero_and_one() {
5911- assert_eq!(dissolve_weight(0, 1), 0.5, "a one-frame window is the midpoint");5977+ assert_eq!(
5978+ dissolve_weight(0, 1),
5979+ 0.5,
5980+ "a one-frame window is the midpoint"
5981+ );
5912 assert_eq!(dissolve_weight(0, 4), 0.2);5982 assert_eq!(dissolve_weight(0, 4), 0.2);
5913 assert_eq!(dissolve_weight(1, 4), 0.4);5983 assert_eq!(dissolve_weight(1, 4), 0.4);
5914 assert_eq!(dissolve_weight(2, 4), 0.6);5984 assert_eq!(dissolve_weight(2, 4), 0.6);
crates/engine/src/lib.rsmodified+18 -16
@@ -15,6 +15,7 @@ pub mod export;
15 pub mod hw;15 pub mod hw;
16 pub mod hwproc;16 pub mod hwproc;
17 pub mod limiter;17 pub mod limiter;
18+pub(crate) mod map;
18 pub mod mux;19 pub mod mux;
19 pub mod playback;20 pub mod playback;
20 pub mod project;21 pub mod project;
@@ -23,11 +24,10 @@ pub mod real_library;
23 pub mod scale;24 pub mod scale;
24 pub mod scratch;25 pub mod scratch;
25 pub mod silence;26 pub mod silence;
27+pub(crate) mod stretch;
26 pub mod subtitle;28 pub mod subtitle;
27-pub(crate) mod map;
28 #[cfg(test)]29 #[cfg(test)]
29 mod sweep;30 mod sweep;
30-pub(crate) mod stretch;
31 pub mod tonemap;31 pub mod tonemap;
32 pub mod transform;32 pub mod transform;
33 pub mod waveform;33 pub mod waveform;
@@ -36,7 +36,9 @@ pub use audio::{
36 AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession, StreamInfo,36 AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession, StreamInfo,
37 };37 };
38 pub use clock::PlaybackClock;38 pub use clock::PlaybackClock;
39-pub use decode::{DecodeSession, Frame, image_size};39+pub use decode::{
40+ DecodeFailure, DecodeSession, Frame, UnsupportedStillOrientation, image_orientation, image_size,
41+};
40 pub use demux::{Codec, MediaBitrate, Rotation, UnsupportedRotation, VideoMeta, probe_bitrate};42 pub use demux::{Codec, MediaBitrate, Rotation, UnsupportedRotation, VideoMeta, probe_bitrate};
41 pub use export::ExportHandle;43 pub use export::ExportHandle;
42 pub use mux::{AudioParams, Mp4Muxer, VideoParams};44 pub use mux::{AudioParams, Mp4Muxer, VideoParams};
@@ -72,7 +74,17 @@ pub fn is_audio(path: &std::path::Path) -> bool {
72 path.extension().and_then(|e| e.to_str()).is_some_and(|e| {74 path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
73 matches!(75 matches!(
74 e.to_ascii_lowercase().as_str(),76 e.to_ascii_lowercase().as_str(),
75- "mp3" | "mpeg" | "mpg" | "wav" | "flac" | "ogg" | "oga" | "opus" | "mka" | "m4a" | "aac"77+ "mp3"
78+ | "mpeg"
79+ | "mpg"
80+ | "wav"
81+ | "flac"
82+ | "ogg"
83+ | "oga"
84+ | "opus"
85+ | "mka"
86+ | "m4a"
87+ | "aac"
76 )88 )
77 })89 })
78 }90 }
@@ -130,18 +142,8 @@ mod tests {
130 #[test]142 #[test]
131 fn is_audio_admits_the_containers_the_decoder_reads() {143 fn is_audio_admits_the_containers_the_decoder_reads() {
132 for name in [144 for name in [
133- "song.mp3",145+ "song.mp3", "a.WAV", "b.flac", "c.ogg", "d.oga", "e.m4a", "f.aac", "g.opus", "h.OPUS",
134- "a.WAV",146+ "i.mka", "j.MPEG", "k.mpg",
135- "b.flac",
136- "c.ogg",
137- "d.oga",
138- "e.m4a",
139- "f.aac",
140- "g.opus",
141- "h.OPUS",
142- "i.mka",
143- "j.MPEG",
144- "k.mpg",
145 ] {147 ] {
146 assert!(super::is_audio(Path::new(name)), "{name}");148 assert!(super::is_audio(Path::new(name)), "{name}");
147 }149 }
crates/engine/src/playback.rsmodified+34 -0
@@ -375,6 +375,10 @@ pub struct PlaybackSession {
375 /// Replaced with the stream at every seek, so it always describes the375 /// Replaced with the stream at every seek, so it always describes the
376 /// pictures currently arriving and never the clip before them.376 /// pictures currently arriving and never the clip before them.
377 backend: BackendCell,377 backend: BackendCell,
378+ /// Why the current span stopped before the end of its range, if it did.
379+ /// Replaced with the stream at every seek for the same reason `backend` is,
380+ /// and read by [`video_failure_reason`](Self::video_failure_reason).
381+ video_failure: crate::decode::DecodeFailure,
378 /// Workers cancelled by a seek or a clip change, waiting to be reaped.382 /// Workers cancelled by a seek or a clip change, waiting to be reaped.
379 /// Joining one inline costs whatever VA-API init it is still inside (98 ms383 /// Joining one inline costs whatever VA-API init it is still inside (98 ms
380 /// measured worst case), which is a visible hitch on the caller's thread;384 /// measured worst case), which is a visible hitch on the caller's thread;
@@ -662,6 +666,7 @@ impl PlaybackSession {
662 frames: stream.frames,666 frames: stream.frames,
663 worker: stream.worker,667 worker: stream.worker,
664 backend: stream.backend,668 backend: stream.backend,
669+ video_failure: stream.failure,
665 retired: Vec::new(),670 retired: Vec::new(),
666 restarts: 0,671 restarts: 0,
667 clock: PlaybackClock::new(source),672 clock: PlaybackClock::new(source),
@@ -792,6 +797,7 @@ impl PlaybackSession {
792 frames: stream.frames,797 frames: stream.frames,
793 worker: stream.worker,798 worker: stream.worker,
794 backend: stream.backend,799 backend: stream.backend,
800+ video_failure: stream.failure,
795 retired: Vec::new(),801 retired: Vec::new(),
796 restarts: 0,802 restarts: 0,
797 // The song keeps the clock, as a video's own sound does -- and wall803 // The song keeps the clock, as a video's own sound does -- and wall
@@ -846,6 +852,10 @@ impl PlaybackSession {
846 frame_count: image_frames(IMAGE_ONLY_RATE),852 frame_count: image_frames(IMAGE_ONLY_RATE),
847 codec: Codec::H264,853 codec: Codec::H264,
848 color: ColorDescription::default(),854 color: ColorDescription::default(),
855+ // `Rotation::None` is honest, not a shrug: a still's own turn was
856+ // made in `Still::open`, before these planes were written, so the
857+ // pair below is already the displayed one and there is nothing left
858+ // for a consumer to make.
849 rotation: Rotation::None,859 rotation: Rotation::None,
850 // No container said anything about these: the picture this engine860 // No container said anything about these: the picture this engine
851 // decoded itself is square pixels at the size it was decoded at.861 // decoded itself is square pixels at the size it was decoded at.
@@ -898,6 +908,7 @@ impl PlaybackSession {
898 frames: stream.frames,908 frames: stream.frames,
899 worker: stream.worker,909 worker: stream.worker,
900 backend: stream.backend,910 backend: stream.backend,
911+ video_failure: stream.failure,
901 retired: Vec::new(),912 retired: Vec::new(),
902 restarts: 0,913 restarts: 0,
903 clock: PlaybackClock::new(ClockSource::Wall),914 clock: PlaybackClock::new(ClockSource::Wall),
@@ -1040,6 +1051,9 @@ impl PlaybackSession {
1040 frame_count: image_frames(frame_rate),1051 frame_count: image_frames(frame_rate),
1041 codec: Codec::H264,1052 codec: Codec::H264,
1042 color: ColorDescription::default(),1053 color: ColorDescription::default(),
1054+ // `Rotation::None` is honest, not a shrug: `Still::open`
1055+ // made the file's own turn before these planes were
1056+ // written, so the pair below is already the displayed one.
1043 rotation: Rotation::None,1057 rotation: Rotation::None,
1044 // No container said anything about these: the picture this1058 // No container said anything about these: the picture this
1045 // engine decoded itself is square pixels at its own size.1059 // engine decoded itself is square pixels at its own size.
@@ -1285,6 +1299,7 @@ impl PlaybackSession {
1285 frames: stream.frames,1299 frames: stream.frames,
1286 worker: stream.worker,1300 worker: stream.worker,
1287 backend: stream.backend,1301 backend: stream.backend,
1302+ video_failure: stream.failure,
1288 retired: Vec::new(),1303 retired: Vec::new(),
1289 restarts: 0,1304 restarts: 0,
1290 clock: PlaybackClock::new(match audio {1305 clock: PlaybackClock::new(match audio {
@@ -1411,6 +1426,25 @@ impl PlaybackSession {
1411 self.audio_disabled.as_deref()1426 self.audio_disabled.as_deref()
1412 }1427 }
1413 1428
1429+ /// Why the picture stopped short of the end of its range, if it did -- the
1430+ /// video twin of [`Self::audio_disabled_reason`], and the reason a corrupt
1431+ /// file used to be indistinguishable from a finished one.
1432+ ///
1433+ /// A closed frame channel is not an answer: a span that ran to the end of
1434+ /// the file and a span that gave up on a broken packet both drop the
1435+ /// sender, and [`Self::try_frame`] returns `None` for either. The app read
1436+ /// that as end-of-stream, so a file with a damaged middle froze on its last
1437+ /// good picture and the transport said ENDED -- no notice, no banner, and
1438+ /// nothing on the screen to say the film had stopped being the film.
1439+ ///
1440+ /// `None` for a span that played its whole range, which is the ordinary
1441+ /// case and the one that must stay silent: a notice that fires on every
1442+ /// film is a notice nobody reads. The reason is the engine's own words, for
1443+ /// the same reason the sound one is.
1444+ pub fn video_failure_reason(&self) -> Option<String> {
1445+ self.video_failure.reason()
1446+ }
1447+
1414 /// The files this timeline plays from, index 0 first -- a caller needs it1448 /// The files this timeline plays from, index 0 first -- a caller needs it
1415 /// to name an export or a window after the media rather than the project.1449 /// to name an export or a window after the media rather than the project.
1416 pub fn sources(&self) -> &[Source] {1450 pub fn sources(&self) -> &[Source] {
crates/engine/tests/decode_failure.rsadded+161 -0
@@ -0,0 +1,161 @@
1+//! A decode failure reaches the user, the way a lost sound device already does.
2+//!
3+//! A worker that ran to the end of a file and a worker that gave up on a
4+//! corrupt packet both drop the sender, and `try_frame` returns `None` for
5+//! either. The app read that as end-of-stream, so a file with a damaged middle
6+//! froze on its last good picture and the transport said ENDED: no notice, no
7+//! banner, and nothing on screen to say the film had stopped being the film.
8+//! The sound path has had a reason channel for a device that dies mid-session
9+//! all along; this is that channel's picture-side twin.
10+//!
11+//! The fixture is **built here**: `test_av.mp4`'s `moov` sits *after* its `mdat`,
12+//! so truncating the file would take the index with it. What is done instead is
13+//! what a download that dies mid-transfer leaves behind -- the tail of the
14+//! sample data overwritten, the container index intact and still claiming every
15+//! frame. The header and the first seconds stay valid, so frames really do
16+//! arrive before the failure, which is the whole shape of the bug.
17+//!
18+//! ```text
19+//! cargo test -p engine --test decode_failure -- --test-threads=1
20+//! ```
21+
22+use std::path::PathBuf;
23+use std::time::{Duration, Instant};
24+
25+use engine::PlaybackSession;
26+use engine::scratch::Scratch;
27+
28+fn asset(name: &str) -> PathBuf {
29+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
30+ .join("../../assets")
31+ .join(name)
32+}
33+
34+/// Software everywhere, so the suite proves the path every machine has.
35+fn pin_software() {
36+ static PIN: std::sync::Once = std::sync::Once::new();
37+ PIN.call_once(|| unsafe {
38+ std::env::set_var("VE_SW", "1");
39+ std::env::set_var("VE_SW_ENC", "1");
40+ });
41+}
42+
43+/// `test_av.mp4` with the last eighth of its **sample data** overwritten, and
44+/// the file otherwise untouched: `moov` still claims every frame the header
45+/// ever did, and the demuxer hands the decoder exactly what it always handed
46+/// it.
47+///
48+/// The damage is bounded to the `mdat` payload on purpose. `moov` sits *after*
49+/// `mdat` in this fixture, so a damage that ran to the end of the file would
50+/// take the index with it and leave a file that will not open at all -- a
51+/// different defect, reached before a single frame is decoded and invisible to
52+/// the thing this test is about.
53+///
54+/// Returns the scratch guard too, so the directory goes when the test ends.
55+fn damaged() -> (Scratch, PathBuf) {
56+ let bytes = std::fs::read(asset("test_av.mp4")).expect("the fixture");
57+ let (start, end) = mdat_payload(&bytes).expect("an mdat payload");
58+ let mut damaged_bytes = bytes;
59+ let tail = start + (end - start) * 7 / 8;
60+ damaged_bytes[tail..end].fill(0);
61+ let scratch = Scratch::file("ve_decode_failure", "mp4");
62+ let path = PathBuf::from(&*scratch);
63+ std::fs::write(&path, &damaged_bytes).expect("write the damaged fixture");
64+ (scratch, path)
65+}
66+
67+/// The `mdat` box's payload, start and end: the walk a container parser does,
68+/// four bytes at a time, and the reason the fixture is damaged rather than
69+/// truncated.
70+fn mdat_payload(bytes: &[u8]) -> Option<(usize, usize)> {
71+ let mut at = 0usize;
72+ while at + 8 <= bytes.len() {
73+ let size = u32::from_be_bytes(bytes[at..at + 4].try_into().ok()?) as usize;
74+ let kind = &bytes[at + 4..at + 8];
75+ if size < 8 {
76+ return None;
77+ }
78+ if kind == b"mdat" {
79+ return Some((at + 8, (at + size).min(bytes.len())));
80+ }
81+ at += size;
82+ }
83+ None
84+}
85+
86+/// Plays `path` to its end and answers what the transport would show and what
87+/// the session says went wrong.
88+fn play_to_the_end(path: &std::path::Path) -> (u32, Option<String>) {
89+ let mut session = PlaybackSession::open(path).expect("open the file");
90+ // A seek rather than a play: this wants the whole span decoded whatever the
91+ // clock says, and a paused session still decodes -- which is what a scrub
92+ // does, and is the same worker either way.
93+ session.seek(0.0);
94+ let started = Instant::now();
95+ let mut frames = 0u32;
96+ // The loop runs on the session's own end-of-stream flag rather than on the
97+ // frame channel, because **that is the bug**: a closed channel and a clean
98+ // end of file are one event to a caller that only has the channel, and the
99+ // app reads that event as the film finishing. Draining on the flag is what
100+ // a fixed caller does, and the reason has to be found somewhere else.
101+ while !session.is_eos() {
102+ if let Some(frame) = session.try_frame() {
103+ frames = frame.index + 1;
104+ }
105+ assert!(
106+ started.elapsed() < Duration::from_secs(60),
107+ "the session never reported an end of stream"
108+ );
109+ std::thread::sleep(Duration::from_millis(1));
110+ }
111+ // The worker sets the reason as it gives up, which can be a moment after
112+ // the flag it also sets; a fixed caller waits for the answer rather than
113+ // racing it.
114+ let deadline = Instant::now() + Duration::from_secs(10);
115+ while session.video_failure_reason().is_none() && Instant::now() < deadline {
116+ std::thread::sleep(Duration::from_millis(5));
117+ }
118+ (frames, session.video_failure_reason())
119+}
120+
121+/// The defect: a file whose middle is damaged produces real frames, then stops,
122+/// and says why. Before this the second half was silent -- the reason was an
123+/// `eprintln!` on a decode worker's stderr, and the only thing the caller could
124+/// see was a closed channel, which it read as the film finishing.
125+#[test]
126+fn a_damaged_file_says_why_it_stopped() {
127+ pin_software();
128+ let (_scratch, path) = damaged();
129+ let (frames, reason) = play_to_the_end(&path);
130+
131+ assert!(
132+ frames > 0,
133+ "the fixture must really decode before it fails, or this proves nothing \
134+ about a failure that happens mid-stream"
135+ );
136+ let reason = reason.expect(
137+ "a file that stopped short of its end has to say why: before this the \
138+ reason was an eprintln on a decode worker and the caller could only \
139+ see a closed channel",
140+ );
141+ assert!(
142+ !reason.is_empty(),
143+ "an empty reason is not a reason a notice can print"
144+ );
145+}
146+
147+/// The other half, and the one that keeps the notice from becoming noise: a
148+/// file that plays all the way through says **nothing**. A reason channel that
149+/// fires on every film is a channel nobody reads, which is how the audio
150+/// device-loss notice earns its place on the strip.
151+#[test]
152+fn a_file_that_plays_to_its_end_says_nothing() {
153+ pin_software();
154+ let path = asset("test_av.mp4");
155+ let (frames, reason) = play_to_the_end(&path);
156+ assert!(frames > 0, "the control must actually play");
157+ assert_eq!(
158+ reason, None,
159+ "a film that reached its own end is not a failure"
160+ );
161+}
crates/engine/tests/exif_orientation.rsadded+366 -0
@@ -0,0 +1,366 @@
1+//! A still's own EXIF orientation, applied.
2+//!
3+//! A phone photographs a portrait picture and stores it as landscape plus a tag
4+//! saying which way up it is. Before this the engine read neither: the `image`
5+//! crate keeps the orientation in its decoder and applies nothing, so the
6+//! preview, the timeline clip box, the poster thumbnail, the canvas seed and an
7+//! export of that clip were all the stored shape -- a portrait photo on its
8+//! side, silently, in every one of them.
9+//!
10+//! The fixture is **built here**, because none of the ones in `assets/` carry
11+//! an orientation tag (`scripts/gen_fixtures.sh` writes PNG stills, and PNG has
12+//! no such tag). It is a real JPEG: four coloured quadrants, an APP1 segment
13+//! holding a TIFF IFD whose tag `0x0112` states the orientation. A single
14+//! sampled pixel per corner then names the layout, and a *wrong direction*
15+//! cannot pass -- 90 the other way, 180, or "ignore it" each produce a
16+//! different set of four corners.
17+//!
18+//! ```text
19+//! cargo test -p engine --test exif_orientation -- --test-threads=1
20+//! ```
21+
22+use std::path::PathBuf;
23+
24+use engine::scratch::Scratch;
25+use engine::{DecodeSession, PlaybackSession, Rotation, image_orientation, image_size};
26+
27+/// A built fixture and the directory holding it, which is removed when the
28+/// guard drops -- [`Scratch`]'s own contract, so a run leaves nothing behind
29+/// and two runs cannot race for a name.
30+fn fixture(exif: u8) -> (Scratch, PathBuf) {
31+ let scratch = Scratch::file(&format!("ve_exif_{exif}"), "jpg");
32+ let path = PathBuf::from(&*scratch);
33+ std::fs::write(&path, build(exif)).expect("write the built fixture");
34+ (scratch, path)
35+}
36+
37+/// Which of the four colours a pixel is, by name. The quadrants are far enough
38+/// apart that a 4:2:0 chroma boundary cannot colour a sample taken deep inside
39+/// one, and JPEG's own chroma subsampling cannot either.
40+fn tint(rgb: [u8; 3]) -> &'static str {
41+ let (r, g, b) = (rgb[0], rgb[1], rgb[2]);
42+ match (r > 110, g > 90, b > 110) {
43+ (true, true, false) => "yellow",
44+ (true, false, false) => "red",
45+ (false, true, false) => "green",
46+ (false, false, true) => "blue",
47+ other => panic!("a quadrant centre is not one of the four colours: {other:?}"),
48+ }
49+}
50+
51+/// The four corners of one tightly packed BGRA picture, top-left first and
52+/// clockwise -- sampled deep enough inside each quadrant that no boundary can
53+/// colour the sample.
54+fn corners(width: u32, height: u32, bgra: &[u8]) -> [&'static str; 4] {
55+ let at = |x: u32, y: u32| {
56+ let index = ((y * width + x) * 4) as usize;
57+ let (b, g, r) = (bgra[index], bgra[index + 1], bgra[index + 2]);
58+ tint([r, g, b])
59+ };
60+ let (qx, qy) = (width / 4, height / 4);
61+ [
62+ at(qx, qy),
63+ at(3 * qx, qy),
64+ at(3 * qx, 3 * qy),
65+ at(qx, 3 * qy),
66+ ]
67+}
68+
69+/// The quadrants of the picture as it is **written into the file**, in the same
70+/// order [`corners`] reads them. The file is landscape 64x32 whatever the
71+/// orientation says, because that is what a phone does: it stores the sensor's
72+/// own shape and says the rest in the tag.
73+const STORED: [&str; 4] = ["red", "green", "blue", "yellow"];
74+
75+/// A 64x32 RGB picture of four coloured quadrants, encoded as a JPEG and given
76+/// an APP1/EXIF segment stating `exif` as the orientation.
77+///
78+/// The EXIF is written by hand rather than through a crate: the segment is six
79+/// bytes of `Exif\0\0` followed by a little-endian TIFF header and one IFD
80+/// entry, which is the whole of what tag `0x0112` is, and writing it out is what
81+/// makes this a fixture rather than a dependency.
82+fn build(exif: u8) -> Vec<u8> {
83+ let (width, height) = (64u32, 32u32);
84+ let (red, green, blue, yellow) = (
85+ [220u8, 30, 30],
86+ [30, 200, 40],
87+ [40, 60, 220],
88+ [230, 210, 40],
89+ );
90+ let (qx, qy) = (width / 4, height / 4);
91+ let mut rgb = image::RgbImage::new(width, height);
92+ for y in 0..height {
93+ for x in 0..width {
94+ let colour = match (x >= 2 * qx, y >= 2 * qy) {
95+ (false, false) => red,
96+ (true, false) => green,
97+ (true, true) => blue,
98+ (false, true) => yellow,
99+ };
100+ rgb.put_pixel(x, y, image::Rgb(colour));
101+ }
102+ }
103+ let mut jpeg = Vec::new();
104+ image::DynamicImage::ImageRgb8(rgb)
105+ .write_to(
106+ &mut std::io::Cursor::new(&mut jpeg),
107+ image::ImageFormat::Jpeg,
108+ )
109+ .expect("encode the JPEG");
110+ // Inserted straight after SOI, which is where a camera's APP1 sits and
111+ // where a decoder's marker walk finds it first.
112+ let app1 = exif_app1(exif);
113+ let mut out = Vec::with_capacity(jpeg.len() + app1.len());
114+ out.extend_from_slice(&jpeg[..2]);
115+ out.extend_from_slice(&app1);
116+ out.extend_from_slice(&jpeg[2..]);
117+ out
118+}
119+
120+/// A complete APP1 segment carrying `exif` as EXIF tag `0x0112`: the `Exif\0\0`
121+/// identifier, a little-endian TIFF header pointing its IFD0 at offset 8, one
122+/// entry (tag, type SHORT, count 1, the value), and a zero "next IFD" pointer.
123+fn exif_app1(exif: u8) -> Vec<u8> {
124+ let mut tiff = Vec::new();
125+ tiff.extend_from_slice(b"II\x2a\x00"); // little-endian, magic 42
126+ tiff.extend_from_slice(&8u32.to_le_bytes()); // IFD0 at offset 8
127+ tiff.extend_from_slice(&1u16.to_le_bytes()); // one entry
128+ tiff.extend_from_slice(&0x0112u16.to_le_bytes()); // Orientation
129+ tiff.extend_from_slice(&3u16.to_le_bytes()); // type SHORT
130+ tiff.extend_from_slice(&1u32.to_le_bytes()); // count 1
131+ tiff.extend_from_slice(&u16::from(exif).to_le_bytes());
132+ tiff.extend_from_slice(&[0, 0]); // the value's padding to an even offset
133+ tiff.extend_from_slice(&0u32.to_le_bytes()); // no IFD1
134+
135+ let mut payload = b"Exif\x00\x00".to_vec();
136+ payload.extend_from_slice(&tiff);
137+
138+ let mut segment = vec![0xff, 0xe1];
139+ // The length field counts itself and the two marker bytes.
140+ segment.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
141+ segment.extend_from_slice(&payload);
142+ segment
143+}
144+
145+/// One frame of `path` and the size it came out at -- the same funnel
146+/// `PlaybackSession` paints from, so this is what a poster thumbnail and the
147+/// preview would each hold.
148+fn first_frame(path: &std::path::Path) -> (u32, u32, Vec<u8>) {
149+ let (_, frames, _) = DecodeSession::open_range(path, 0, 1).expect("open for a frame");
150+ let frame = frames.recv().expect("a first frame");
151+ (frame.width, frame.height, frame.bgra)
152+}
153+
154+/// Software everywhere, so the suite proves the path every machine has.
155+fn pin_software() {
156+ static PIN: std::sync::Once = std::sync::Once::new();
157+ PIN.call_once(|| unsafe {
158+ std::env::set_var("VE_SW", "1");
159+ std::env::set_var("VE_SW_ENC", "1");
160+ });
161+}
162+
163+/// The whole of the defect, asserted through **both** doors that used to
164+/// disagree: the header-only size a library row reads before anything places
165+/// the file, and the first decoded frame a preview shows after. They are
166+/// separate code paths over the same tag, so a fix to one that skipped the
167+/// other would leave a file that is one shape in the library and another on the
168+/// timeline.
169+///
170+/// EXIF 6 is the portrait case -- a quarter turn clockwise -- so the stored
171+/// 64x32 is shown 32x64, and each stored corner moves one place clockwise.
172+#[test]
173+fn a_portrait_photo_is_shown_the_way_it_was_photographed() {
174+ pin_software();
175+ let (_scratch, path) = fixture(6);
176+
177+ assert_eq!(
178+ image_size(&path).expect("the header answers"),
179+ (32, 64),
180+ "a library row must describe the picture as it is shown, not as it is stored"
181+ );
182+ assert_eq!(
183+ image_orientation(&path).expect("the tag is readable"),
184+ Rotation::Cw90,
185+ "EXIF 6 is a quarter turn clockwise"
186+ );
187+
188+ let (width, height, bgra) = first_frame(&path);
189+ assert_eq!(
190+ [width, height],
191+ [32, 64],
192+ "the decoded frame is the picture as it is shown"
193+ );
194+ assert_eq!(
195+ corners(width, height, &bgra),
196+ ["yellow", "red", "green", "blue"],
197+ "a quarter turn clockwise puts the stored bottom-left at the new top-left: \
198+ the file holds {STORED:?} top-left first"
199+ );
200+}
201+
202+/// The other quarter turns, so a fix that turned *something* rather than
203+/// turning *right* cannot pass: EXIF 3 is 180 (opposite corners swap), 8 is a
204+/// quarter turn anticlockwise (the other way round), and 1 states no turn.
205+///
206+/// Each is asserted against the corners its own turn produces, indexed off the
207+/// stored layout rather than written out, so the expectation cannot drift away
208+/// from the fixture it describes.
209+#[test]
210+fn every_quarter_turn_is_made_in_its_own_direction() {
211+ pin_software();
212+ // Which stored corner each read corner is, and whether the axes swap with
213+ // the turn. A clockwise quarter turn walks the ring one place on, so the
214+ // read corner at index `i` is the stored one at `i + 3`; anticlockwise is
215+ // the other way round, and 180 is two places either way.
216+ for (exif, swaps, ring) in [
217+ (3u8, false, [2usize, 3, 0, 1]),
218+ (8, true, [1, 2, 3, 0]),
219+ (1, false, [0, 1, 2, 3]),
220+ ] {
221+ let (_scratch, path) = fixture(exif);
222+ let (stored_w, stored_h) = (64u32, 32u32);
223+ let (want_w, want_h) = match swaps {
224+ true => (stored_h, stored_w),
225+ false => (stored_w, stored_h),
226+ };
227+ assert_eq!(
228+ image_size(&path).expect("the header answers"),
229+ (want_w, want_h),
230+ "EXIF {exif}: the shown pair is the stored one, turned"
231+ );
232+
233+ let (width, height, bgra) = first_frame(&path);
234+ assert_eq!(
235+ [width, height],
236+ [want_w, want_h],
237+ "EXIF {exif}: the frame is the picture as it is shown"
238+ );
239+ let want: Vec<&str> = ring.iter().map(|i| STORED[*i]).collect();
240+ assert_eq!(
241+ corners(width, height, &bgra),
242+ want[..],
243+ "EXIF {exif}: the corners read the stored ones in the order {ring:?}"
244+ );
245+ }
246+}
247+
248+/// A mirroring is not a turn, and this engine has no flip anywhere in its
249+/// pipeline -- not in the still's decode, not in `Render`, not in an export's
250+/// `place_picture`. So EXIF 2, 4, 5 and 7 are refused **by name** at the door,
251+/// the way a display matrix that is not a quarter turn is
252+/// (`engine::UnsupportedRotation`): a mirrored photo shown the wrong way round
253+/// is a wrong picture, not a missing feature, and quietly treating a mirror as
254+/// a rotation is exactly the bug this door exists to stop.
255+///
256+/// All four values are checked, so a fix that refused only the first mirror is
257+/// caught.
258+#[test]
259+fn a_mirrored_photo_is_refused_by_name() {
260+ pin_software();
261+ for exif in [2u8, 4, 5, 7] {
262+ let (_scratch, path) = fixture(exif);
263+ let error = match image_orientation(&path) {
264+ Ok(rotation) => {
265+ panic!("EXIF {exif} is a mirror, not a turn, and must not read as {rotation:?}")
266+ }
267+ Err(error) => error,
268+ };
269+ assert!(
270+ engine::UnsupportedStillOrientation::is_it(&error),
271+ "EXIF {exif}: the refusal is the named one, not a generic failure: {error}"
272+ );
273+ let said = error.to_string();
274+ assert!(
275+ said.contains(&exif.to_string()) && said.contains("mirror"),
276+ "EXIF {exif}: the refusal names what it cannot make: {said}"
277+ );
278+ // ...and the door that places the picture refuses it too, rather than
279+ // showing the file the wrong way round.
280+ let error = match PlaybackSession::open(&path) {
281+ Ok(_) => panic!("EXIF {exif} must not open as a timeline"),
282+ Err(error) => error,
283+ };
284+ assert!(
285+ engine::UnsupportedStillOrientation::is_it(&error),
286+ "EXIF {exif}: opening the timeline refuses it by name too: {error}"
287+ );
288+ }
289+}
290+
291+/// A picture that states no turn is the whole of an ordinary library, and it
292+/// must come out the way it always did: the turn is a branch on a bool, and
293+/// this is the assertion that it stays one.
294+#[test]
295+fn an_upright_photo_is_untouched_by_the_turn_door() {
296+ pin_software();
297+ let (_scratch, path) = fixture(1);
298+ assert_eq!(
299+ image_size(&path).expect("the header answers"),
300+ (64, 32),
301+ "a picture that states no turn is its own size"
302+ );
303+ let (width, height, bgra) = first_frame(&path);
304+ assert_eq!([width, height], [64, 32]);
305+ assert_eq!(
306+ corners(width, height, &bgra),
307+ STORED,
308+ "no turn means the stored quadrants, in the stored order"
309+ );
310+}
311+
312+/// The export, which is the door the turn was most expensive to get wrong: it
313+/// is a re-encode of the *coded* planes, so a still whose turn was applied
314+/// only on the preview side would be written out sideways and would then play
315+/// sideways in every player that is not this one, forever, with no matrix left
316+/// to correct it.
317+///
318+/// The written file must therefore be portrait **and** state no matrix of its
319+/// own -- a file that kept the landscape pixels and declared a turn would
320+/// satisfy neither half.
321+#[test]
322+fn an_export_of_a_turned_photo_is_upright_and_portrait() {
323+ pin_software();
324+ let (_scratch, path) = fixture(6);
325+ let mut session = PlaybackSession::open(&path).expect("open the photo");
326+ session.pause();
327+ assert_eq!(
328+ [session.meta().width, session.meta().height],
329+ [32, 64],
330+ "the timeline is the displayed shape, not the stored one"
331+ );
332+
333+ let out = engine::scratch::Scratch::file("ve_exif_export", "mp4");
334+ let handle = session.export_to_with(&out, &engine::export::ExportSettings::default());
335+ let started = std::time::Instant::now();
336+ while !handle.is_finished() {
337+ assert!(
338+ started.elapsed() < std::time::Duration::from_secs(60),
339+ "the export did not finish"
340+ );
341+ std::thread::sleep(std::time::Duration::from_millis(20));
342+ }
343+ handle
344+ .result()
345+ .expect("a finished export has an outcome")
346+ .expect("the export succeeded");
347+
348+ let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
349+ assert_eq!(
350+ [meta.width, meta.height],
351+ [32, 64],
352+ "the written file is portrait"
353+ );
354+ assert_eq!(
355+ meta.rotation,
356+ Rotation::None,
357+ "and states no matrix of its own: the turn is in the pixels"
358+ );
359+ let (width, height, bgra) = first_frame(&out);
360+ assert_eq!([width, height], [32, 64]);
361+ assert_eq!(
362+ corners(width, height, &bgra),
363+ ["yellow", "red", "green", "blue"],
364+ "the exported pixels are the ones the preview showed"
365+ );
366+}