forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

exif_orientation.rs344 lines, 13.8 KiBHistoryRawDownload
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
22use std::path::PathBuf;
23
24use engine::scratch::Scratch;
25use 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.
30fn 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.
40fn 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.
54fn 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.
73const STORED: [&str; 4] = ["red", "green", "blue", "yellow"];
74
75/// The stored picture, as a JPEG with no orientation tag: 64x32, four coloured
76/// quadrants (`tests/data/quadrants_64x32.jpg`, written once with a JPEG
77/// encoder and checked in, so this suite needs no encoder at run time).
78const BASE_JPEG: &[u8] = include_bytes!("data/quadrants_64x32.jpg");
79
80/// The fixture with an APP1/EXIF segment stating `exif` as the orientation.
81///
82/// The EXIF is written by hand rather than through a crate: the segment is six
83/// bytes of `Exif\0\0` followed by a little-endian TIFF header and one IFD
84/// entry, which is the whole of what tag `0x0112` is, and writing it out is what
85/// makes this a fixture rather than a dependency.
86fn build(exif: u8) -> Vec<u8> {
87 let jpeg = BASE_JPEG;
88 // Inserted straight after SOI, which is where a camera's APP1 sits and
89 // where a decoder's marker walk finds it first.
90 let app1 = exif_app1(exif);
91 let mut out = Vec::with_capacity(jpeg.len() + app1.len());
92 out.extend_from_slice(&jpeg[..2]);
93 out.extend_from_slice(&app1);
94 out.extend_from_slice(&jpeg[2..]);
95 out
96}
97
98/// A complete APP1 segment carrying `exif` as EXIF tag `0x0112`: the `Exif\0\0`
99/// identifier, a little-endian TIFF header pointing its IFD0 at offset 8, one
100/// entry (tag, type SHORT, count 1, the value), and a zero "next IFD" pointer.
101fn exif_app1(exif: u8) -> Vec<u8> {
102 let mut tiff = Vec::new();
103 tiff.extend_from_slice(b"II\x2a\x00"); // little-endian, magic 42
104 tiff.extend_from_slice(&8u32.to_le_bytes()); // IFD0 at offset 8
105 tiff.extend_from_slice(&1u16.to_le_bytes()); // one entry
106 tiff.extend_from_slice(&0x0112u16.to_le_bytes()); // Orientation
107 tiff.extend_from_slice(&3u16.to_le_bytes()); // type SHORT
108 tiff.extend_from_slice(&1u32.to_le_bytes()); // count 1
109 tiff.extend_from_slice(&u16::from(exif).to_le_bytes());
110 tiff.extend_from_slice(&[0, 0]); // the value's padding to an even offset
111 tiff.extend_from_slice(&0u32.to_le_bytes()); // no IFD1
112
113 let mut payload = b"Exif\x00\x00".to_vec();
114 payload.extend_from_slice(&tiff);
115
116 let mut segment = vec![0xff, 0xe1];
117 // The length field counts itself and the two marker bytes.
118 segment.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
119 segment.extend_from_slice(&payload);
120 segment
121}
122
123/// One frame of `path` and the size it came out at -- the same funnel
124/// `PlaybackSession` paints from, so this is what a poster thumbnail and the
125/// preview would each hold.
126fn first_frame(path: &std::path::Path) -> (u32, u32, Vec<u8>) {
127 let (_, frames, _) = DecodeSession::open_range(path, 0, 1).expect("open for a frame");
128 let frame = frames.recv().expect("a first frame");
129 (frame.width, frame.height, frame.bgra)
130}
131
132/// Software everywhere, so the suite proves the path every machine has.
133fn pin_software() {
134 static PIN: std::sync::Once = std::sync::Once::new();
135 PIN.call_once(|| {
136 engine::envcfg::set("VE_SW", "1");
137 engine::envcfg::set("VE_SW_ENC", "1");
138 });
139}
140
141/// The whole of the defect, asserted through **both** doors that used to
142/// disagree: the header-only size a library row reads before anything places
143/// the file, and the first decoded frame a preview shows after. They are
144/// separate code paths over the same tag, so a fix to one that skipped the
145/// other would leave a file that is one shape in the library and another on the
146/// timeline.
147///
148/// EXIF 6 is the portrait case -- a quarter turn clockwise -- so the stored
149/// 64x32 is shown 32x64, and each stored corner moves one place clockwise.
150#[test]
151fn a_portrait_photo_is_shown_the_way_it_was_photographed() {
152 pin_software();
153 let (_scratch, path) = fixture(6);
154
155 assert_eq!(
156 image_size(&path).expect("the header answers"),
157 (32, 64),
158 "a library row must describe the picture as it is shown, not as it is stored"
159 );
160 assert_eq!(
161 image_orientation(&path).expect("the tag is readable"),
162 Rotation::Cw90,
163 "EXIF 6 is a quarter turn clockwise"
164 );
165
166 let (width, height, bgra) = first_frame(&path);
167 assert_eq!(
168 [width, height],
169 [32, 64],
170 "the decoded frame is the picture as it is shown"
171 );
172 assert_eq!(
173 corners(width, height, &bgra),
174 ["yellow", "red", "green", "blue"],
175 "a quarter turn clockwise puts the stored bottom-left at the new top-left: \
176 the file holds {STORED:?} top-left first"
177 );
178}
179
180/// The other quarter turns, so a fix that turned *something* rather than
181/// turning *right* cannot pass: EXIF 3 is 180 (opposite corners swap), 8 is a
182/// quarter turn anticlockwise (the other way round), and 1 states no turn.
183///
184/// Each is asserted against the corners its own turn produces, indexed off the
185/// stored layout rather than written out, so the expectation cannot drift away
186/// from the fixture it describes.
187#[test]
188fn every_quarter_turn_is_made_in_its_own_direction() {
189 pin_software();
190 // Which stored corner each read corner is, and whether the axes swap with
191 // the turn. A clockwise quarter turn walks the ring one place on, so the
192 // read corner at index `i` is the stored one at `i + 3`; anticlockwise is
193 // the other way round, and 180 is two places either way.
194 for (exif, swaps, ring) in [
195 (3u8, false, [2usize, 3, 0, 1]),
196 (8, true, [1, 2, 3, 0]),
197 (1, false, [0, 1, 2, 3]),
198 ] {
199 let (_scratch, path) = fixture(exif);
200 let (stored_w, stored_h) = (64u32, 32u32);
201 let (want_w, want_h) = match swaps {
202 true => (stored_h, stored_w),
203 false => (stored_w, stored_h),
204 };
205 assert_eq!(
206 image_size(&path).expect("the header answers"),
207 (want_w, want_h),
208 "EXIF {exif}: the shown pair is the stored one, turned"
209 );
210
211 let (width, height, bgra) = first_frame(&path);
212 assert_eq!(
213 [width, height],
214 [want_w, want_h],
215 "EXIF {exif}: the frame is the picture as it is shown"
216 );
217 let want: Vec<&str> = ring.iter().map(|i| STORED[*i]).collect();
218 assert_eq!(
219 corners(width, height, &bgra),
220 want[..],
221 "EXIF {exif}: the corners read the stored ones in the order {ring:?}"
222 );
223 }
224}
225
226/// A mirroring is not a turn, and this engine has no flip anywhere in its
227/// pipeline -- not in the still's decode, not in `Render`, not in an export's
228/// `place_picture`. So EXIF 2, 4, 5 and 7 are refused **by name** at the door,
229/// the way a display matrix that is not a quarter turn is
230/// (`engine::UnsupportedRotation`): a mirrored photo shown the wrong way round
231/// is a wrong picture, not a missing feature, and quietly treating a mirror as
232/// a rotation is exactly the bug this door exists to stop.
233///
234/// All four values are checked, so a fix that refused only the first mirror is
235/// caught.
236#[test]
237fn a_mirrored_photo_is_refused_by_name() {
238 pin_software();
239 for exif in [2u8, 4, 5, 7] {
240 let (_scratch, path) = fixture(exif);
241 let error = match image_orientation(&path) {
242 Ok(rotation) => {
243 panic!("EXIF {exif} is a mirror, not a turn, and must not read as {rotation:?}")
244 }
245 Err(error) => error,
246 };
247 assert!(
248 engine::UnsupportedStillOrientation::is_it(&error),
249 "EXIF {exif}: the refusal is the named one, not a generic failure: {error}"
250 );
251 let said = error.to_string();
252 assert!(
253 said.contains(&exif.to_string()) && said.contains("mirror"),
254 "EXIF {exif}: the refusal names what it cannot make: {said}"
255 );
256 // ...and the door that places the picture refuses it too, rather than
257 // showing the file the wrong way round.
258 let error = match PlaybackSession::open(&path) {
259 Ok(_) => panic!("EXIF {exif} must not open as a timeline"),
260 Err(error) => error,
261 };
262 assert!(
263 engine::UnsupportedStillOrientation::is_it(&error),
264 "EXIF {exif}: opening the timeline refuses it by name too: {error}"
265 );
266 }
267}
268
269/// A picture that states no turn is the whole of an ordinary library, and it
270/// must come out the way it always did: the turn is a branch on a bool, and
271/// this is the assertion that it stays one.
272#[test]
273fn an_upright_photo_is_untouched_by_the_turn_door() {
274 pin_software();
275 let (_scratch, path) = fixture(1);
276 assert_eq!(
277 image_size(&path).expect("the header answers"),
278 (64, 32),
279 "a picture that states no turn is its own size"
280 );
281 let (width, height, bgra) = first_frame(&path);
282 assert_eq!([width, height], [64, 32]);
283 assert_eq!(
284 corners(width, height, &bgra),
285 STORED,
286 "no turn means the stored quadrants, in the stored order"
287 );
288}
289
290/// The export, which is the door the turn was most expensive to get wrong: it
291/// is a re-encode of the *coded* planes, so a still whose turn was applied
292/// only on the preview side would be written out sideways and would then play
293/// sideways in every player that is not this one, forever, with no matrix left
294/// to correct it.
295///
296/// The written file must therefore be portrait **and** state no matrix of its
297/// own -- a file that kept the landscape pixels and declared a turn would
298/// satisfy neither half.
299#[test]
300fn an_export_of_a_turned_photo_is_upright_and_portrait() {
301 pin_software();
302 let (_scratch, path) = fixture(6);
303 let mut session = PlaybackSession::open(&path).expect("open the photo");
304 session.pause();
305 assert_eq!(
306 [session.meta().width, session.meta().height],
307 [32, 64],
308 "the timeline is the displayed shape, not the stored one"
309 );
310
311 let out = engine::scratch::Scratch::file("ve_exif_export", "mp4");
312 let handle = session.export_to_with(&out, &engine::export::ExportSettings::default());
313 let started = std::time::Instant::now();
314 while !handle.is_finished() {
315 assert!(
316 started.elapsed() < std::time::Duration::from_secs(60),
317 "the export did not finish"
318 );
319 std::thread::sleep(std::time::Duration::from_millis(20));
320 }
321 handle
322 .result()
323 .expect("a finished export has an outcome")
324 .expect("the export succeeded");
325
326 let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
327 assert_eq!(
328 [meta.width, meta.height],
329 [32, 64],
330 "the written file is portrait"
331 );
332 assert_eq!(
333 meta.rotation,
334 Rotation::None,
335 "and states no matrix of its own: the turn is in the pixels"
336 );
337 let (width, height, bgra) = first_frame(&out);
338 assert_eq!([width, height], [32, 64]);
339 assert_eq!(
340 corners(width, height, &bgra),
341 ["yellow", "red", "green", "blue"],
342 "the exported pixels are the ones the preview showed"
343 );
344}