forge
Explore
Log in

Don't you dare go Hollow

A still is shown the way its EXIF orientation says

Browse files at this commit

e600a6ef741a55bcfd9d16c967ad2f142f34137aAhmet Kaan GümüşParent: 0c9d76c
  • fix
    • a still is shown the way its EXIF orientation says
Show full message
fix(engine): a still is shown the way its EXIF orientation says

A phone photographs a portrait picture and stores it as landscape plus a
tag saying which way up it is. The `image` crate keeps that tag in its
decoder and applies nothing, so every still door read the *stored* shape:
the preview, the timeline clip box, the poster thumbnail, the library
row, the canvas seed and an export of that clip. A portrait phone photo
opened sideways in all of them, silently.

The turn is now read and made once, in `Still::open`, before the planes
are written -- the same step the video doors take for a display matrix,
at the same place in the pipeline, through the same `Rotation`. Because
the turn is in the planes, `Render`, the `VideoMeta` both still doors
mint, an export's `place_picture` and `image_size` all report the shown
pair without any of them re-deriving it, and no consumer can be
forgotten.

EXIF 2, 4, 5 and 7 are mirrorings and this engine has no flip anywhere
in its pipeline, so they are refused by name at the door
(`UnsupportedStillOrientation`, `is_it` and all) the way a display
matrix that is not a quarter turn is: a mirrored photo shown the wrong
way round is a wrong picture, not a missing feature. The refusal is
propagated unchanged rather than folded into a sentence with the file's
name, so a caller can still downcast it.

`DecodeSession::open_range` also reaches a still now. It handed one to
the mp4 demuxer, which answers "a box with a larger size than it" -- a
true sentence about a container and nothing a person can act on -- so
this door, the one a front-end opens a file through, refused every
picture outright, and the poster thumbnail was one of its callers.

Witness (crates/engine/tests/exif_orientation.rs, 5 tests): a JPEG built
in-test with four coloured quadrants and a hand-written APP1/EXIF
segment carrying tag 0x0112, sampled a pixel per corner so a wrong
direction cannot pass. Red on the base: `image_size` (64, 32), frame
64x32, corners ["red","green","blue","yellow"] -- the stored layout,
orientation ignored. Green after: (32, 64) and ["yellow","red","green",
"blue"], with 180, anticlockwise and no-turn each asserted in its own
direction, all four mirrors refused by name, and the export portrait
with no matrix of its own. `cargo test -p engine --test images` 8/8.
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+455 -99
@@ -7,13 +7,14 @@ use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
7 use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};7 use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};
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};
@@ -560,7 +561,9 @@ impl DecodeSession {
560 let first = Render::new(561 let first = Render::new(
561 color,562 color,
562 transform,563 transform,
563- // A still has no display matrix: what the file holds is what it is.564+ // A still's own turn is already in these planes: `Still::open` made
565+ // it before the conversion above, exactly where the video door
566+ // makes a display matrix, so the render must not make it twice.
564 Rotation::None,567 Rotation::None,
565 // ...and no sample aspect either: a still is authored square.568 // ...and no sample aspect either: a still is authored square.
566 PixelAspect::SQUARE,569 PixelAspect::SQUARE,
@@ -684,7 +687,11 @@ impl DecodeSession {
684 if worker_cancel.load(Ordering::Relaxed) {687 if worker_cancel.load(Ordering::Relaxed) {
685 return;688 return;
686 }689 }
687- let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 };690+ let fps = if fps.is_finite() && fps > 0.0 {
691+ fps
692+ } else {
693+ 30.0
694+ };
688 // One frame's painting no longer allocates per strand per695 // One frame's painting no longer allocates per strand per
689 // frame: this thread lives for the span.696 // frame: this thread lives for the span.
690 let mut scratch = VizScratch::default();697 let mut scratch = VizScratch::default();
@@ -711,9 +718,8 @@ impl DecodeSession {
711 // the same thirty seconds, and no decode at all for the718 // the same thirty seconds, and no decode at all for the
712 // rebuilds of a look edit.719 // rebuilds of a look edit.
713 let view = envelope.view_at(t);720 let view = envelope.view_at(t);
714- let (y, u, v) = visualizer_window_i420(721+ let (y, u, v) =
715- &mut scratch, &view, t, width, height, flags, paint,722+ 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);723 let frame = render.frame(start_frame + index, &y, &u, &v, width, height);
718 if tx.send(frame).is_err() {724 if tx.send(frame).is_err() {
719 return; // caller moved on725 return; // caller moved on
@@ -762,6 +768,34 @@ impl DecodeSession {
762 tone: tonemap::Preset,768 tone: tonemap::Preset,
763 ) -> crate::Result<(VideoMeta, FrameStream)> {769 ) -> crate::Result<(VideoMeta, FrameStream)> {
764 let path = path.as_ref().to_path_buf();770 let path = path.as_ref().to_path_buf();
771+ // A still is not a stream: handing one to the mp4 demuxer answers "a
772+ // box with a larger size than it", which is a true sentence about a
773+ // container and nothing a person can act on -- and it made this door,
774+ // the one a front-end opens a file through, refuse every picture
775+ // outright. The still door answers with a meta of its own, so a poster
776+ // thumbnail and a preview window get the same picture the timeline
777+ // does, at the same size. No `tone` argument is passed on and none is
778+ // wanted: a still is decoded into BT.601 SDR planes, so there is no
779+ // map to build whichever rendition the project is watching.
780+ if crate::is_image(&path) {
781+ let still = Still::open(&path)?;
782+ let meta = VideoMeta {
783+ width: still.width,
784+ height: still.height,
785+ frame_rate: 1.0,
786+ frame_count: 1,
787+ codec: Codec::H264,
788+ color: ColorDescription::default(),
789+ // A still's own turn was made in `Still::open`, before these
790+ // planes were written, so there is nothing left to state here.
791+ rotation: Rotation::None,
792+ coded_width: still.width,
793+ coded_height: still.height,
794+ pixel_aspect: PixelAspect::SQUARE,
795+ };
796+ return Self::open_still(&path, start_frame, 1, color, transform, canvas)
797+ .map(|stream| (meta, stream));
798+ }
765 let (meta, demuxer) = Demuxer::open(&path)?;799 let (meta, demuxer) = Demuxer::open(&path)?;
766 // No software HEVC, VP9 or VP8 decoder exists, so such a file the plugin will800 // 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 to801 // not take is refused *here*, where the caller still has somewhere to
@@ -1049,7 +1083,9 @@ impl Source {
1049 fn position_hw(&mut self, path: &Path, start: u32) -> Option<bool> {1083 fn position_hw(&mut self, path: &Path, start: u32) -> Option<bool> {
1050 if let Some(hw) = &mut self.hw {1084 if let Some(hw) = &mut self.hw {
1051 if hw.seek(start) {1085 if hw.seek(start) {
1052- eprintln!("decode backend: hardware (VA-API plugin, session kept, seek to {start})");1086+ eprintln!(
1087+ "decode backend: hardware (VA-API plugin, session kept, seek to {start})"
1088+ );
1053 return Some(true);1089 return Some(true);
1054 }1090 }
1055 // A plugin too old to reposition, or a decoder that would not1091 // A plugin too old to reposition, or a decoder that would not
@@ -1140,7 +1176,9 @@ fn run_span(
1140 // is a software fallback. Without this a single unfollowed seek would1176 // is a software fallback. Without this a single unfollowed seek would
1141 // collapse the rest of the file to software.1177 // collapse the rest of the file to software.
1142 if !decoded && reused {1178 if !decoded && reused {
1143- eprintln!("hardware decode produced nothing after a reseek; reopening at frame {start}");1179+ eprintln!(
1180+ "hardware decode produced nothing after a reseek; reopening at frame {start}"
1181+ );
1144 opened.hw = open_hw(path, start);1182 opened.hw = open_hw(path, start);
1145 if let Some(hw) = opened.hw.as_mut() {1183 if let Some(hw) = opened.hw.as_mut() {
1146 decoded = run_hw(hw, &tx, start, end, &mut render, abort, speed);1184 decoded = run_hw(hw, &tx, start, end, &mut render, abort, speed);
@@ -1162,12 +1200,28 @@ fn run_span(
1162 Codec::H264 => {1200 Codec::H264 => {
1163 eprintln!("decode backend: software (ec-h264)");1201 eprintln!("decode backend: software (ec-h264)");
1164 backend.set(Backend::Software);1202 backend.set(Backend::Software);
1165- run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed);1203+ run(
1204+ &mut opened.demuxer,
1205+ &tx,
1206+ start,
1207+ end,
1208+ &mut render,
1209+ abort,
1210+ speed,
1211+ );
1166 }1212 }
1167 Codec::Av1 => {1213 Codec::Av1 => {
1168 eprintln!("decode backend: software (ec-av1)");1214 eprintln!("decode backend: software (ec-av1)");
1169 backend.set(Backend::Software);1215 backend.set(Backend::Software);
1170- run_av1(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed);1216+ run_av1(
1217+ &mut opened.demuxer,
1218+ &tx,
1219+ start,
1220+ end,
1221+ &mut render,
1222+ abort,
1223+ speed,
1224+ );
1171 }1225 }
1172 // Nothing decodes from here -- no software seat exists for this codec.1226 // Nothing decodes from here -- no software seat exists for this codec.
1173 // Say so: the cell was left claiming the hardware session that opened1227 // Say so: the cell was left claiming the hardware session that opened
@@ -1388,36 +1442,35 @@ impl Render {
1388 // picture a viewer is shown, so its brightness and saturation mean what1442 // 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-stop1443 // they say in the SDR the tone map just produced, not in the 10-stop
1390 // HDR the file was in.1444 // HDR the file was in.
1391- let (y, u, v, desc) = if self.tone.is_some()1445+ let (y, u, v, desc) =
1392- || (!skip_placement && !self.color.is_identity())1446+ if self.tone.is_some() || (!skip_placement && !self.color.is_identity()) {
1393- {1447+ let (gy, gu, gv) = &mut self.graded;
1394- let (gy, gu, gv) = &mut self.graded;1448+ gy.clear();
1395- gy.clear();1449+ gy.extend_from_slice(y);
1396- gy.extend_from_slice(y);1450+ gu.clear();
1397- gu.clear();1451+ gu.extend_from_slice(u);
1398- gu.extend_from_slice(u);1452+ gv.clear();
1399- gv.clear();1453+ gv.extend_from_slice(v);
1400- gv.extend_from_slice(v);1454+ if let Some(tone) = &self.tone {
1401- if let Some(tone) = &self.tone {1455+ tone.map(gy, gu, gv, width as usize, height as usize);
1402- tone.map(gy, gu, gv, width as usize, height as usize);1456+ }
1403- }1457+ // The same terms the branch was entered on: anywhere the fused
1404- // The same terms the branch was entered on: anywhere the fused1458+ // conversion below will not apply the grade (a placement is
1405- // conversion below will not apply the grade (a placement is1459+ // happening, so the canvas conversion is plain), it lands here --
1406- // happening, so the canvas conversion is plain), it lands here --1460+ // including the passthrough-sized clip a transform moves, whose
1407- // including the passthrough-sized clip a transform moves, whose1461+ // 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.1462+ if !skip_placement && !self.color.is_identity() {
1409- if !skip_placement && !self.color.is_identity() {1463+ crate::color::apply_yuv(&self.color, gy, gu, gv);
1410- crate::color::apply_yuv(&self.color, gy, gu, gv);1464+ }
1411- }1465+ let desc = if self.tone.is_some() {
1412- let desc = if self.tone.is_some() {1466+ TONE_MAPPED
1413- TONE_MAPPED1467+ } else {
1468+ self.desc
1469+ };
1470+ (&gy[..], &gu[..], &gv[..], desc)
1414 } else {1471 } else {
1415- self.desc1472+ (y, u, v, self.desc)
1416 };1473 };
1417- (&gy[..], &gu[..], &gv[..], desc)
1418- } else {
1419- (y, u, v, self.desc)
1420- };
1421 if skip_placement {1474 if skip_placement {
1422 return Frame {1475 return Frame {
1423 index,1476 index,
@@ -1435,11 +1488,17 @@ impl Render {
1435 };1488 };
1436 }1489 }
1437 let (y, u, v, width, height) = if transform_active {1490 let (y, u, v, width, height) = if transform_active {
1438- let (py, pu, pv, w, h) = self1491+ let (py, pu, pv, w, h) =
1439- .canvas1492+ self.canvas
1440- .place_transformed(y, u, v, width, height, &self.transform);1493+ .place_transformed(y, u, v, width, height, &self.transform);
1441 self.placed = (py, pu, pv);1494 self.placed = (py, pu, pv);
1442- (&self.placed.0[..], &self.placed.1[..], &self.placed.2[..], w, h)1495+ (
1496+ &self.placed.0[..],
1497+ &self.placed.1[..],
1498+ &self.placed.2[..],
1499+ w,
1500+ h,
1501+ )
1443 } else {1502 } else {
1444 self.canvas.place(y, u, v, width, height)1503 self.canvas.place(y, u, v, width, height)
1445 };1504 };
@@ -1465,10 +1524,100 @@ pub(crate) struct Still {
1465 pub(crate) y: Vec<u8>,1524 pub(crate) y: Vec<u8>,
1466 pub(crate) u: Vec<u8>,1525 pub(crate) u: Vec<u8>,
1467 pub(crate) v: Vec<u8>,1526 pub(crate) v: Vec<u8>,
1527+ /// The picture as it is *shown*, which for a phone's portrait photo is not
1528+ /// the picture as it was stored: the turn its EXIF block asks for was made
1529+ /// in [`Still::open`] before these planes were written, exactly where the
1530+ /// video doors make a display matrix, so the pair every reader takes is
1531+ /// the displayed one ([`crate::demux::Rotation`]'s own contract).
1468 pub(crate) width: u32,1532 pub(crate) width: u32,
1469 pub(crate) height: u32,1533 pub(crate) height: u32,
1470 }1534 }
1471 1535
1536+/// A still whose EXIF orientation is not a quarter turn: values 2, 4, 5 and 7
1537+/// are mirrorings, and this engine has no flip anywhere in its pipeline -- not
1538+/// in [`crate::scale::rotate_i420_90s`], not in [`Render`], not in an export's
1539+/// `place_picture`. Refused **by name** at the door, for
1540+/// [`crate::demux::UnsupportedRotation`]'s reason: showing a mirrored photo the
1541+/// wrong way round is a wrong picture rather than a missing feature, and
1542+/// quietly treating a mirror as a turn is exactly the bug this door exists to
1543+/// stop. The `Display` is what a user is refused by.
1544+#[derive(Debug)]
1545+pub struct UnsupportedStillOrientation {
1546+ /// The EXIF value the file states, which is what the sentence names: the
1547+ /// eight legal values are 1 (upright) through 8, and the four mirrorings
1548+ /// are the even-odd pairs.
1549+ pub exif: u8,
1550+}
1551+
1552+impl std::fmt::Display for UnsupportedStillOrientation {
1553+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1554+ write!(
1555+ f,
1556+ "this picture's EXIF orientation is {}, which is a mirror and not a turn; only \
1557+ upright, 90°, 180° and 270° can be straightened here",
1558+ self.exif
1559+ )
1560+ }
1561+}
1562+
1563+impl std::error::Error for UnsupportedStillOrientation {}
1564+
1565+impl UnsupportedStillOrientation {
1566+ /// Whether `error` is one of these, however deep in a `Box` it is --
1567+ /// [`crate::demux::UnsupportedRotation::is_it`]'s twin.
1568+ pub fn is_it(error: &crate::Error) -> bool {
1569+ error.downcast_ref::<Self>().is_some()
1570+ }
1571+}
1572+
1573+/// The quarter turns an EXIF orientation asks for, as the one
1574+/// [`Rotation`] every other door in this engine already uses -- no second
1575+/// shape mechanism for a still, so the same turn is made by the same code
1576+/// that makes a video's display matrix turn.
1577+///
1578+/// EXIF 1, 6, 8 and 3 are the four quarter turns; **2, 4, 5 and 7 are
1579+/// mirrorings** and are refused ([`UnsupportedStillOrientation`]) rather than
1580+/// approximated by the nearest rotation. A value the standard does not define
1581+/// (0, or above 8) states no orientation this can read, and is likewise
1582+/// refused rather than guessed at.
1583+fn rotation_of_exif(orientation: image::metadata::Orientation) -> crate::Result<Rotation> {
1584+ use image::metadata::Orientation as O;
1585+ Ok(match orientation {
1586+ O::NoTransforms => Rotation::None,
1587+ O::Rotate90 => Rotation::Cw90,
1588+ O::Rotate180 => Rotation::Cw180,
1589+ O::Rotate270 => Rotation::Cw270,
1590+ // The `image` crate keeps the raw number alongside: an orientation it
1591+ // could not read is `NoTransforms`, and saying "0" for a mirror would
1592+ // be a claim rather than a reading.
1593+ mirrored => {
1594+ return Err(UnsupportedStillOrientation {
1595+ exif: mirrored.to_exif(),
1596+ }
1597+ .into());
1598+ }
1599+ })
1600+}
1601+
1602+/// What turn `path` asks for, read off its **header** alone -- what a library
1603+/// row says about a file it has not placed anywhere, and what
1604+/// [`image_size`] needs to report the size the picture is shown at.
1605+///
1606+/// Header-only on purpose: the whole file is not decoded, exactly as
1607+/// [`image_size`] has always been. `into_decoder` parses the container and
1608+/// stops there; the pixels are never touched.
1609+pub fn image_orientation(path: &Path) -> crate::Result<Rotation> {
1610+ let mut decoder = image::ImageReader::open(path)?
1611+ .with_guessed_format()?
1612+ .into_decoder()
1613+ .map_err(|e| format!("{}: {e}", path.display()))?;
1614+ // The refusal is handed on **unchanged**, not folded into a sentence with
1615+ // the file's name: a `String` is not an error a caller can downcast, and
1616+ // `is_it` is how a front-end tells this refusal from any other failure.
1617+ // The path is not lost -- every caller that has one puts it in front.
1618+ rotation_of_exif(decoder.orientation()?)
1619+}
1620+
1472 impl Still {1621 impl Still {
1473 /// Decodes `path`. Refused by name for a picture that is not one1622 /// Decodes `path`. Refused by name for a picture that is not one
1474 /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project1623 /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project
@@ -1484,12 +1633,41 @@ impl Still {
1484 /// lands as a rectangle. Upgrade path is keeping the alpha plane here and1633 /// lands as a rectangle. Upgrade path is keeping the alpha plane here and
1485 /// giving `scale::Composer` a blend over the lane below.1634 /// giving `scale::Composer` a blend over the lane below.
1486 pub(crate) fn open(path: &Path) -> crate::Result<Self> {1635 pub(crate) fn open(path: &Path) -> crate::Result<Self> {
1487- let reader = image::ImageReader::open(path)?.with_guessed_format()?;1636+ // The turn is read and made **here**, once, before a single pair of
1488- let rgb = reader1637+ // numbers leaves this function: `image`'s decoder keeps an EXIF
1489- .decode()1638+ // orientation in its own field and applies nothing, so a portrait
1639+ // phone photo arrived as landscape planes and every consumer below --
1640+ // the `Render`, the `VideoMeta`, `image_size` -- reported the shape the
1641+ // camera stored rather than the one it was shot at. This is the same
1642+ // step the video doors make, at the same place in the pipeline
1643+ // (before the grade, the canvas and the conversion all see the
1644+ // picture), and it uses the same [`Rotation`].
1645+ let mut decoder = image::ImageReader::open(path)?
1646+ .with_guessed_format()?
1647+ .into_decoder()
1648+ .map_err(|e| format!("{}: {e}", path.display()))?;
1649+ // Unchanged for the reason `image_orientation` gives: a caller has to
1650+ // be able to downcast this refusal, and a sentence with the file's name
1651+ // in it is not one.
1652+ let rotation = rotation_of_exif(decoder.orientation()?)?;
1653+ let rgb = image::DynamicImage::from_decoder(decoder)
1490 .map_err(|e| format!("{}: {e}", path.display()))?1654 .map_err(|e| format!("{}: {e}", path.display()))?
1491 .to_rgb8();1655 .to_rgb8();
1492- let (width, height) = rgb.dimensions();1656+ let (coded_width, coded_height) = rgb.dimensions();
1657+ // Turned here rather than left to each consumer, so there is exactly
1658+ // one place the turn is made and no consumer can be forgotten: the
1659+ // planes handed out below are the *shown* picture, so the `Render`, the
1660+ // `VideoMeta`, an export's `place_picture` and `image_size` all agree
1661+ // without any of them re-deriving it. A file that states no turn takes
1662+ // the branch by a bool and not one byte is copied.
1663+ let (rgb, width, height) = match rotation.is_none() {
1664+ true => (rgb, coded_width, coded_height),
1665+ false => {
1666+ let turned = turn_rgb(&rgb, rotation.steps());
1667+ let (width, height) = turned.dimensions();
1668+ (turned, width, height)
1669+ }
1670+ };
1493 if !crate::is_resolution(width, height) {1671 if !crate::is_resolution(width, height) {
1494 return Err(format!(1672 return Err(format!(
1495 "{} is {width}x{height}, which is not a picture this engine composes",1673 "{} is {width}x{height}, which is not a picture this engine composes",
@@ -1508,19 +1686,49 @@ impl Still {
1508 }1686 }
1509 1687
1510 /// The planes as an export's decoder hands them over, so a still and a1688 /// 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`.1689+ /// decoded picture are the same value to `export::run` -- and, for a
1690+ /// turned still, the same value in the only sense that matters: the turn
1691+ /// is already in them, so an export places what the preview showed without
1692+ /// being told a second time.
1512 pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {1693 pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
1513 (&self.y, &self.u, &self.v, self.width, self.height)1694 (&self.y, &self.u, &self.v, self.width, self.height)
1514 }1695 }
1515 }1696 }
1516 1697
1517-/// How big the picture in `path` is, from its header alone -- what a library row1698+/// `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.1699+/// direction and the same count [`crate::scale::rotate_i420_90s`] takes, on the
1700+/// still's own buffer rather than on its planes: a still is turned exactly once
1701+/// in its whole life, so there is no steady-state cost to make the allocating
1702+/// call the one that happens.
1703+fn turn_rgb(rgb: &image::RgbImage, steps: u8) -> image::RgbImage {
1704+ match steps % 4 {
1705+ 1 => image::imageops::rotate90(rgb),
1706+ 2 => image::imageops::rotate180(rgb),
1707+ 3 => image::imageops::rotate270(rgb),
1708+ _ => rgb.clone(),
1709+ }
1710+}
1711+
1712+/// How big the picture in `path` is as it is **shown**, from its header alone --
1713+/// what a library row says about a file it has not placed anywhere. The whole
1714+/// file is not decoded.
1715+///
1716+/// The turn is applied to the answer for the same reason
1717+/// [`DecodeSession::open_still`]'s is: a portrait phone photo stores landscape
1718+/// and says so in its EXIF block, and a row that answered 4000x3000 for a
1719+/// picture that is shown 3000x4000 states the wrong shape on the one surface
1720+/// that exists before anything places the file. Header-only still --
1721+/// `into_decoder` parses the container and stops.
1519 pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {1722 pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {
1520- Ok(image::ImageReader::open(path)?1723+ let rotation = image_orientation(path)?;
1724+ let (width, height) = image::ImageReader::open(path)?
1521 .with_guessed_format()?1725 .with_guessed_format()?
1522 .into_dimensions()1726 .into_dimensions()
1523- .map_err(|e| format!("{}: {e}", path.display()))?)1727+ .map_err(|e| format!("{}: {e}", path.display()))?;
1728+ Ok(match rotation.swaps_axes() {
1729+ true => (height, width),
1730+ false => (width, height),
1731+ })
1524 }1732 }
1525 1733
1526 /// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse1734 /// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse
@@ -1599,11 +1807,7 @@ const VIZ_STRAND_SAT_SHIFT: u32 = 40;
1599 const VIZ_STRAND_CHOSEN: u64 = 1 << 63;1807 const VIZ_STRAND_CHOSEN: u64 = 1 << 63;
1600 1808
1601 pub fn viz_materialize(paint: u64) -> u64 {1809 pub fn viz_materialize(paint: u64) -> u64 {
1602- if paint == 0 {1810+ if paint == 0 { VIZ_PAINT_AZURE } else { paint }
1603- VIZ_PAINT_AZURE
1604- } else {
1605- paint
1606- }
1607 }1811 }
1608 1812
1609 pub fn viz_ink_from_paint(paint: u64) -> (u8, u8, u8) {1813 pub fn viz_ink_from_paint(paint: u64) -> (u8, u8, u8) {
@@ -1638,7 +1842,11 @@ pub fn with_viz_paint_glow(paint: u64, n: u8) -> u64 {
1638 }1842 }
1639 1843
1640 pub fn viz_hue_ui(paint: u64) -> u8 {1844 pub fn viz_hue_ui(paint: u64) -> u8 {
1641- if paint == 0 { 150 } else { (paint & 0xFF) as u8 }1845+ if paint == 0 {
1846+ 150
1847+ } else {
1848+ (paint & 0xFF) as u8
1849+ }
1642 }1850 }
1643 1851
1644 pub fn viz_sat_ui(paint: u64) -> u8 {1852 pub fn viz_sat_ui(paint: u64) -> u8 {
@@ -1688,9 +1896,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 the1896 /// 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.1897 /// automatic complement, and both strand bytes go with the flag.
1690 pub fn viz_strand_clear(paint: u64) -> u64 {1898 pub fn viz_strand_clear(paint: u64) -> u64 {
1691- paint & !(VIZ_STRAND_CHOSEN1899+ paint
1692- | (0xFF_u64 << VIZ_STRAND_HUE_SHIFT)1900+ & !(VIZ_STRAND_CHOSEN
1693- | (0xFF_u64 << VIZ_STRAND_SAT_SHIFT))1901+ | (0xFF_u64 << VIZ_STRAND_HUE_SHIFT)
1902+ | (0xFF_u64 << VIZ_STRAND_SAT_SHIFT))
1694 }1903 }
1695 1904
1696 /// `#RRGGBB` for an ink, at the same fixed value the painter draws at, so1905 /// `#RRGGBB` for an ink, at the same fixed value the painter draws at, so
@@ -1837,8 +2046,7 @@ fn viz_stamp(
1837 if x < 0 || row < 0 || x >= w as i32 || row >= h as i32 {2046 if x < 0 || row < 0 || x >= w as i32 || row >= h as i32 {
1838 return;2047 return;
1839 }2048 }
1840- let lum =2049+ 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;2050 let idx = row as usize * w + x as usize;
1843 if lum > y[idx] {2051 if lum > y[idx] {
1844 y[idx] = lum;2052 y[idx] = lum;
@@ -1871,7 +2079,9 @@ fn viz_span(
1871 ) {2079 ) {
1872 let (a, b) = if top <= bot { (top, bot) } else { (bot, top) };2080 let (a, b) = if top <= bot { (top, bot) } else { (bot, top) };
1873 for row in a..=b {2081 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);2082+ viz_stamp(
2083+ y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v,
2084+ );
1875 }2085 }
1876 }2086 }
1877 2087
@@ -1935,7 +2145,22 @@ fn viz_line(
1935 let d2 = (ox * ox + oy * oy) as f32;2145 let d2 = (ox * ox + oy * oy) as f32;
1936 (-0.45 * d2 / (g * g).max(1) as f32).exp()2146 (-0.45 * d2 / (g * g).max(1) as f32).exp()
1937 };2147 };
1938- viz_stamp(y, u, v, w, h, cw, ch, x0 + ox, y0 + oy, fall, bg_y, ink_y, ink_u, ink_v);2148+ viz_stamp(
2149+ y,
2150+ u,
2151+ v,
2152+ w,
2153+ h,
2154+ cw,
2155+ ch,
2156+ x0 + ox,
2157+ y0 + oy,
2158+ fall,
2159+ bg_y,
2160+ ink_y,
2161+ ink_u,
2162+ ink_v,
2163+ );
1939 }2164 }
1940 }2165 }
1941 if x0 == x1 && y0 == y1 {2166 if x0 == x1 && y0 == y1 {
@@ -2034,7 +2259,14 @@ fn viz_chain(
2034 ink_v: u8,2259 ink_v: u8,
2035 glow: u8,2260 glow: u8,
2036 ) {2261 ) {
2037- let VizScratch { pts, chain, rows, cand, hull, .. } = scratch;2262+ let VizScratch {
2263+ pts,
2264+ chain,
2265+ rows,
2266+ cand,
2267+ hull,
2268+ ..
2269+ } = scratch;
2038 chain.clear();2270 chain.clear();
2039 for pair in pts.windows(2) {2271 for pair in pts.windows(2) {
2040 viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, chain);2272 viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, chain);
@@ -2047,7 +2279,9 @@ fn viz_chain(
2047 // full ink -- which is exactly what the row/by/band machinery below2279 // full ink -- which is exactly what the row/by/band machinery below
2048 // works out, one sort later.2280 // works out, one sort later.
2049 for &(x, row) in chain.iter() {2281 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);2282+ viz_stamp(
2283+ y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v,
2284+ );
2051 }2285 }
2052 return;2286 return;
2053 }2287 }
@@ -2173,7 +2407,9 @@ fn viz_chain(
2173 } else {2407 } else {
2174 (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp()2408 (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp()
2175 };2409 };
2176- viz_stamp(y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v);2410+ viz_stamp(
2411+ y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v,
2412+ );
2177 }2413 }
2178 }2414 }
2179 }2415 }
@@ -2197,7 +2433,15 @@ pub(crate) fn visualizer_i420(
2197 flags: u8,2433 flags: u8,
2198 paint: u64,2434 paint: u64,
2199 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {2435 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
2200- visualizer_window_i420(scratch, &VizView::whole(peaks), t_secs, width, height, flags, paint)2436+ visualizer_window_i420(
2437+ scratch,
2438+ &VizView::whole(peaks),
2439+ t_secs,
2440+ width,
2441+ height,
2442+ flags,
2443+ paint,
2444+ )
2201 }2445 }
2202 2446
2203 /// The envelope a visualizer frame is painted from: the whole file, or one2447 /// The envelope a visualizer frame is painted from: the whole file, or one
@@ -2404,12 +2648,36 @@ pub(crate) fn visualizer_window_i420(
2404 for dy in 1..=glow {2648 for dy in 1..=glow {
2405 let fall = 0.5 / dy as f32;2649 let fall = 0.5 / dy as f32;
2406 viz_stamp(2650 viz_stamp(
2407- &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row - dy, fall, bg_y,2651+ &mut y,
2408- ink_y, ink_u, ink_v,2652+ &mut u,
2653+ &mut v,
2654+ w,
2655+ h,
2656+ cw,
2657+ ch,
2658+ col as i32,
2659+ row - dy,
2660+ fall,
2661+ bg_y,
2662+ ink_y,
2663+ ink_u,
2664+ ink_v,
2409 );2665 );
2410 viz_stamp(2666 viz_stamp(
2411- &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row + dy, fall, bg_y,2667+ &mut y,
2412- ink_y, ink_u, ink_v,2668+ &mut u,
2669+ &mut v,
2670+ w,
2671+ h,
2672+ cw,
2673+ ch,
2674+ col as i32,
2675+ row + dy,
2676+ fall,
2677+ bg_y,
2678+ ink_y,
2679+ ink_u,
2680+ ink_v,
2413 );2681 );
2414 }2682 }
2415 }2683 }
@@ -2474,9 +2742,10 @@ pub(crate) fn visualizer_window_i420(
2474 VIZ_STYLE_WAVE => {2742 VIZ_STYLE_WAVE => {
2475 scratch.pts.clear();2743 scratch.pts.clear();
2476 for col in 0..w {2744 for col in 0..w {
2477- scratch2745+ scratch.pts.push((
2478- .pts2746+ col as i32,
2479- .push((col as i32, (center - scratch.sig[col] * half).round() as i32));2747+ (center - scratch.sig[col] * half).round() as i32,
2748+ ));
2480 }2749 }
2481 let glow = viz_glow_of(paint);2750 let glow = viz_glow_of(paint);
2482 if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) {2751 if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) {
@@ -2488,8 +2757,7 @@ pub(crate) fn visualizer_window_i420(
2488 }2757 }
2489 } else {2758 } else {
2490 viz_chain(2759 viz_chain(
2491- &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v,2760+ &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v, glow,
2492- glow,
2493 );2761 );
2494 }2762 }
2495 }2763 }
@@ -2507,12 +2775,36 @@ pub(crate) fn visualizer_window_i420(
2507 for dy in 1..=glow {2775 for dy in 1..=glow {
2508 let fall = 0.55 / dy as f32;2776 let fall = 0.55 / dy as f32;
2509 viz_stamp(2777 viz_stamp(
2510- &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, top - dy, fall, bg_y,2778+ &mut y,
2511- ink_y, ink_u, ink_v,2779+ &mut u,
2780+ &mut v,
2781+ w,
2782+ h,
2783+ cw,
2784+ ch,
2785+ col as i32,
2786+ top - dy,
2787+ fall,
2788+ bg_y,
2789+ ink_y,
2790+ ink_u,
2791+ ink_v,
2512 );2792 );
2513 viz_stamp(2793 viz_stamp(
2514- &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, bot + dy, fall, bg_y,2794+ &mut y,
2515- ink_y, ink_u, ink_v,2795+ &mut u,
2796+ &mut v,
2797+ w,
2798+ h,
2799+ cw,
2800+ ch,
2801+ col as i32,
2802+ bot + dy,
2803+ fall,
2804+ bg_y,
2805+ ink_y,
2806+ ink_u,
2807+ ink_v,
2516 );2808 );
2517 }2809 }
2518 }2810 }
@@ -2695,7 +2987,10 @@ mod tests {
2695 "deferred open returned in {returned:?}, first frame at {first_frame:?}; \2987 "deferred open returned in {returned:?}, first frame at {first_frame:?}; \
2696 sync open returned in {sync_returned:?}"2988 sync open returned in {sync_returned:?}"
2697 );2989 );
2698- assert_eq!(frame.index, 0, "the deferred worker starts where it is told");2990+ assert_eq!(
2991+ frame.index, 0,
2992+ "the deferred worker starts where it is told"
2993+ );
2699 assert!(2994 assert!(
2700 returned < Duration::from_millis(10),2995 returned < Duration::from_millis(10),
2701 "the caller waited {returned:?} -- something is still being read \2996 "the caller waited {returned:?} -- something is still being read \
@@ -2848,7 +3143,10 @@ mod tests {
2848 let w = 320u32;3143 let w = 320u32;
2849 let h = 180u32;3144 let h = 180u32;
2850 let (y, _u, _v) = visualizer_i420(&mut VizScratch::default(), &[], 0.0, w, h, 1, 0);3145 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));3146+ assert_eq!(
3147+ (y.len(), _u.len(), _v.len()),
3148+ (320 * 180, 160 * 90, 160 * 90)
3149+ );
2852 // The ink's top and bottom row for a given peaks slice: one unbroken3150 // The ink's top and bottom row for a given peaks slice: one unbroken
2853 // band, and where it sits.3151 // band, and where it sits.
2854 let band = |peaks: &[(f32, f32)]| {3152 let band = |peaks: &[(f32, f32)]| {
@@ -3059,10 +3357,14 @@ mod tests {
3059 *p = (-a.abs(), a.abs());3357 *p = (-a.abs(), a.abs());
3060 }3358 }
3061 let flags = 1u8;3359 let flags = 1u8;
3062- let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0);3360+ let (y, u, v) =
3361+ visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0);
3063 let ink = y.iter().filter(|&&p| p > 40).count();3362 let ink = y.iter().filter(|&&p| p > 40).count();
3064 assert!(ink > 200, "envelope missing: {ink}");3363 assert!(ink > 200, "envelope missing: {ink}");
3065- assert!(ink < y.len() * 9 / 10, "solid frame, not an envelope: {ink}");3364+ assert!(
3365+ ink < y.len() * 9 / 10,
3366+ "solid frame, not an envelope: {ink}"
3367+ );
3066 let mut blue = 0usize;3368 let mut blue = 0usize;
3067 for i in 0..u.len() {3369 for i in 0..u.len() {
3068 if u[i] > 145 && v[i] < 120 {3370 if u[i] > 145 && v[i] < 120 {
@@ -3072,13 +3374,22 @@ mod tests {
3072 assert!(blue > 10, "default ink was not timeline blue: {blue}");3374 assert!(blue > 10, "default ink was not timeline blue: {blue}");
3073 3375
3074 let ring = with_viz_style(flags, VIZ_STYLE_RING);3376 let ring = with_viz_style(flags, VIZ_STYLE_RING);
3075- let (yr, _, _) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0);3377+ let (yr, _, _) =
3378+ visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0);
3076 let ring_ink = yr.iter().filter(|&&p| p > 40).count();3379 let ring_ink = yr.iter().filter(|&&p| p > 40).count();
3077 assert!(ring_ink > 80, "ring missing: {ring_ink}");3380 assert!(ring_ink > 80, "ring missing: {ring_ink}");
3078 assert!(ring_ink < ink, "ring should be a stroke, not a fill");3381 assert!(ring_ink < ink, "ring should be a stroke, not a fill");
3079 3382
3080 let hue_paint = with_viz_paint_hue(0, 40);3383 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);3384+ let (_, u2, v2) = visualizer_i420(
3385+ &mut VizScratch::default(),
3386+ &peaks,
3387+ 1.0,
3388+ 64,
3389+ 32,
3390+ flags,
3391+ hue_paint,
3392+ );
3082 let mut shifted = 0usize;3393 let mut shifted = 0usize;
3083 for i in 0..u2.len() {3394 for i in 0..u2.len() {
3084 if u2[i] < 120 && v2[i] > 130 {3395 if u2[i] < 120 && v2[i] > 130 {
@@ -3175,7 +3486,15 @@ mod tests {
3175 }3486 }
3176 let ring = with_viz_style(1, VIZ_STYLE_RING);3487 let ring = with_viz_style(1, VIZ_STYLE_RING);
3177 let auto = VIZ_PAINT_AZURE;3488 let auto = VIZ_PAINT_AZURE;
3178- let (y0, u0, v0) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, auto);3489+ let (y0, u0, v0) = visualizer_i420(
3490+ &mut VizScratch::default(),
3491+ &peaks,
3492+ 1.0,
3493+ 320,
3494+ 180,
3495+ ring,
3496+ auto,
3497+ );
3179 3498
3180 // The automatic dual is half a wheel from the clip's hue at the3499 // The automatic dual is half a wheel from the clip's hue at the
3181 // clip's own saturation; choosing exactly that colour changes3500 // clip's own saturation; choosing exactly that colour changes
@@ -3185,24 +3504,54 @@ mod tests {
3185 viz_sat_ui(auto),3504 viz_sat_ui(auto),
3186 );3505 );
3187 assert!(viz_strand_set(same));3506 assert!(viz_strand_set(same));
3188- let (ys, us, vs) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, same);3507+ let (ys, us, vs) = visualizer_i420(
3189- assert_eq!(ys, y0, "the automatic complement, spelled out, is the same frame");3508+ &mut VizScratch::default(),
3509+ &peaks,
3510+ 1.0,
3511+ 320,
3512+ 180,
3513+ ring,
3514+ same,
3515+ );
3516+ assert_eq!(
3517+ ys, y0,
3518+ "the automatic complement, spelled out, is the same frame"
3519+ );
3190 assert_eq!(us, u0);3520 assert_eq!(us, u0);
3191 assert_eq!(vs, v0);3521 assert_eq!(vs, v0);
3192 3522
3193 // A colour of its own repaints the dual strands in it.3523 // 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);3524 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);3525+ let (_, u1, v1) =
3196- let red_px = (0..u1.len()).filter(|&i| u1[i] < 110 && v1[i] > 200).count();3526+ 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();3527+ let red_px = (0..u1.len())
3198- assert!(red_px > 20, "the chosen colour did not reach the frame: {red_px}");3528+ .filter(|&i| u1[i] < 110 && v1[i] > 200)
3199- assert_eq!(auto_px, 0, "the automatic ring already painted red: {auto_px}");3529+ .count();
3530+ let auto_px = (0..u0.len())
3531+ .filter(|&i| u0[i] < 110 && v0[i] > 200)
3532+ .count();
3533+ assert!(
3534+ red_px > 20,
3535+ "the chosen colour did not reach the frame: {red_px}"
3536+ );
3537+ assert_eq!(
3538+ auto_px, 0,
3539+ "the automatic ring already painted red: {auto_px}"
3540+ );
3200 3541
3201 // ...and the flag is what decides: strand bytes with it clear are3542 // ...and the flag is what decides: strand bytes with it clear are
3202 // the unset picture, byte for byte.3543 // the unset picture, byte for byte.
3203 let stale = auto | (77u64 << 32) | (9u64 << 40);3544 let stale = auto | (77u64 << 32) | (9u64 << 40);
3204 assert!(!viz_strand_set(stale));3545 assert!(!viz_strand_set(stale));
3205- let (yt, ut, vt) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, stale);3546+ let (yt, ut, vt) = visualizer_i420(
3547+ &mut VizScratch::default(),
3548+ &peaks,
3549+ 1.0,
3550+ 320,
3551+ 180,
3552+ ring,
3553+ stale,
3554+ );
3206 assert_eq!(yt, y0, "an unset strand colour is the frame it always was");3555 assert_eq!(yt, y0, "an unset strand colour is the frame it always was");
3207 assert_eq!(ut, u0);3556 assert_eq!(ut, u0);
3208 assert_eq!(vt, v0);3557 assert_eq!(vt, v0);
@@ -3250,7 +3599,15 @@ mod tests {
3250 };3599 };
3251 let flags = with_viz_style(1, style);3600 let flags = with_viz_style(1, style);
3252 let paint = with_viz_paint_glow(VIZ_PAINT_AZURE, glow);3601 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);3602+ let (y, u, v) = visualizer_i420(
3603+ &mut VizScratch::default(),
3604+ &peaks,
3605+ 37.5,
3606+ 1920,
3607+ 1080,
3608+ flags,
3609+ paint,
3610+ );
3254 let mut hash = 0xcbf2_9ce4_8422_2325u64;3611 let mut hash = 0xcbf2_9ce4_8422_2325u64;
3255 for buf in [&y, &u, &v] {3612 for buf in [&y, &u, &v] {
3256 for &b in buf.iter() {3613 for &b in buf.iter() {
@@ -3566,7 +3923,6 @@ fn run_av1(
3566 }3923 }
3567 }3924 }
3568 }3925 }
3569-
3570 }3926 }
3571 3927
3572 /// Converts one decoded picture and queues it. `true` when the consumer went3928 /// 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 }
@@ -2134,9 +2149,9 @@ fn encode_audio(
2134 let out_frames = range.map_or(project.media_frames(), |(s, e)| {2149 let out_frames = range.map_or(project.media_frames(), |(s, e)| {
2135 e.min(project.media_frames()).saturating_sub(s)2150 e.min(project.media_frames()).saturating_sub(s)
2136 });2151 });
2137- let total =2152+ let total = (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round()
2138- (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() as usize2153+ as usize
2139- * channels;2154+ * channels;
2140 let mut samples: Vec<f32> = Vec::with_capacity(total);2155 let mut samples: Vec<f32> = Vec::with_capacity(total);
2141 for chunk in chunks {2156 for chunk in chunks {
2142 // The only place a cancelled export can be answered before the whole2157 // The only place a cancelled export can be answered before the whole
@@ -2455,9 +2470,15 @@ fn opus_fidelity(
2455 for w in 0..FIDELITY_WINDOWS {2470 for w in 0..FIDELITY_WINDOWS {
2456 let at = w * step;2471 let at = w * step;
2457 let from = at.saturating_sub(FIDELITY_WARMUP);2472 let from = at.saturating_sub(FIDELITY_WARMUP);
2458- let Some(fidelity) =2473+ let Some(fidelity) = window_fidelity(
2459- window_fidelity(packets, samples, pre_skip, channels, from, at, at + FIDELITY_WINDOW)2474+ packets,
2460- else {2475+ samples,
2476+ pre_skip,
2477+ channels,
2478+ from,
2479+ at,
2480+ at + FIDELITY_WINDOW,
2481+ ) else {
2461 continue; // silence: nothing to correlate, and not a failure2482 continue; // silence: nothing to correlate, and not a failure
2462 };2483 };
2463 scores.push(fidelity);2484 scores.push(fidelity);
@@ -2646,9 +2667,9 @@ fn run(
2646 // The range's own length where one is marked, the media's otherwise --2667 // The range's own length where one is marked, the media's otherwise --
2647 // `export_spans` walks the same window, so `done` ends on this `total`2668 // `export_spans` walks the same window, so `done` ends on this `total`
2648 // exactly as it always did.2669 // exactly as it always did.
2649- let total = settings2670+ let total = settings.range.map_or(project.media_frames(), |(s, e)| {
2650- .range2671+ e.min(project.media_frames()).saturating_sub(s)
2651- .map_or(project.media_frames(), |(s, e)| e.min(project.media_frames()).saturating_sub(s));2672+ });
2652 // The two preview switches are the H.264 mp4 pair's alone. Only that2673 // The two preview switches are the H.264 mp4 pair's alone. Only that
2653 // container carries a colour of its own back out ([`write_video`] tags it2674 // container carries a colour of its own back out ([`write_video`] tags it
2654 // there), so asking any other for a source-space file would write pictures2675 // there), so asking any other for a source-space file would write pictures
@@ -2695,12 +2716,8 @@ fn run(
2695 // of the two. On this project's own film that is 168 s of AC-3 that no2716 // of the two. On this project's own film that is 168 s of AC-3 that no
2696 // longer stands in front of 733 s of hardware H.264.2717 // longer stands in front of 733 s of hardware H.264.
2697 let audio_job = {2718 let audio_job = {
2698- let (project, meta, settings, shared) = (2719+ let (project, meta, settings, shared) =
2699- project.clone(),2720+ (project.clone(), *meta, settings.clone(), Arc::clone(shared));
2700- *meta,
2701- settings.clone(),
2702- Arc::clone(shared),
2703- );
2704 thread::Builder::new()2721 thread::Builder::new()
2705 .name("export-audio".into())2722 .name("export-audio".into())
2706 .spawn(move || {2723 .spawn(move || {
@@ -2843,7 +2860,15 @@ fn run(
2843 // it replaced -- and the sound says whether it was copied or encoded, which2860 // it replaced -- and the sound says whether it was copied or encoded, which
2844 // only `copy_audio` knows and, on the overlapped path, does not know yet.2861 // only `copy_audio` knows and, on the overlapped path, does not know yet.
2845 let seat = encoder.label();2862 let seat = encoder.label();
2846- publish_seats(shared, seat, project, settings, sound, opus, audio_job.running());2863+ publish_seats(
2864+ shared,
2865+ seat,
2866+ project,
2867+ settings,
2868+ sound,
2869+ opus,
2870+ audio_job.running(),
2871+ );
2847 // When the picture started, so the stage line below can say where under it2872 // When the picture started, so the stage line below can say where under it
2848 // the sound landed -- the one number that says whether the two passes2873 // the sound landed -- the one number that says whether the two passes
2849 // really overlapped, in the same voice as `encode_audio`'s own timers.2874 // really overlapped, in the same voice as `encode_audio`'s own timers.
@@ -2882,9 +2907,8 @@ fn run(
2882 // A's pixels on the CPU, so a dissolving span never asks for a GPU2907 // A's pixels on the CPU, so a dissolving span never asks for a GPU
2883 // buffer, not even outside its own window.2908 // buffer, not even outside its own window.
2884 let dissolve = dissolve_window(project, &span);2909 let dissolve = dissolve_window(project, &span);
2885- let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) =2910+ let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) = match span.from
2886- match span.from2911+ {
2887- {
2888 Some((source, in_frame)) => {2912 Some((source, in_frame)) => {
2889 let entry = sources2913 let entry = sources
2890 .get(source)2914 .get(source)
@@ -2934,7 +2958,15 @@ fn run(
2934 } else {2958 } else {
2935 ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)?2959 ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)?
2936 };2960 };
2937- (Some(pictures), rate, in_frame, Some(color), mapper, rotation, pixel_aspect)2961+ (
2962+ Some(pictures),
2963+ rate,
2964+ in_frame,
2965+ Some(color),
2966+ mapper,
2967+ rotation,
2968+ pixel_aspect,
2969+ )
2938 }2970 }
2939 // A gap's black is 16/128/128, which is black in every matrix here2971 // A gap's black is 16/128/128, which is black in every matrix here
2940 // and on every curve: nothing to remap and nothing to tone-map,2972 // and on every curve: nothing to remap and nothing to tone-map,
@@ -2993,52 +3025,54 @@ fn run(
2993 // files together for exactly the frames the tail below blends, and3025 // files together for exactly the frames the tail below blends, and
2994 // nothing else in this span ever touches it.3026 // nothing else in this span ever touches it.
2995 let mut b = dissolve3027 let mut b = dissolve
2996- .map(|(b_source, b_in_frame, window, b_start)| -> crate::Result<_> {3028+ .map(
2997- let entry = sources.get(b_source).ok_or_else(|| {3029+ |(b_source, b_in_frame, window, b_start)| -> crate::Result<_> {
2998- format!("clip names source {b_source} of {}", sources.len())3030+ let entry = sources.get(b_source).ok_or_else(|| {
2999- })?;3031+ format!("clip names source {b_source} of {}", sources.len())
3000- let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source];3032+ })?;
3001- let b_mapper = tone[b_source].as_ref();3033+ let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source];
3002- let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix);3034+ let b_mapper = tone[b_source].as_ref();
3003- Ok(Dissolve {3035+ let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix);
3004- window,3036+ Ok(Dissolve {
3005- tail_start: span.len - window,3037+ window,
3006- decoder: if crate::is_audio(&entry.path)3038+ tail_start: span.len - window,
3007- || project.composite_visualizer_at(b_start) & 1 != 03039+ decoder: if crate::is_audio(&entry.path)
3008- {3040+ || project.composite_visualizer_at(b_start) & 1 != 0
3009- ClipDecoder::visualizer(3041+ {
3010- &entry.path,3042+ ClipDecoder::visualizer(
3011- entry.audio_stream,3043+ &entry.path,
3012- b_rate.source_at(b_in_frame),3044+ entry.audio_stream,
3045+ b_rate.source_at(b_in_frame),
3046+ meta.width,
3047+ meta.height,
3048+ meta.frame_rate,
3049+ project.composite_visualizer_at(b_start),
3050+ project.composite_viz_paint_at(b_start),
3051+ )?
3052+ } else {
3053+ ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)?
3054+ },
3055+ mapper: b_mapper,
3056+ remap: b_remap,
3057+ grade: project.composite_color_at(b_start).copied(),
3058+ transform: project
3059+ .composite_transform_at(b_start)
3060+ .copied()
3061+ .unwrap_or_default(),
3062+ rotation: b_rotation,
3063+ pixel_aspect: b_pixel_aspect,
3064+ canvas: Composer::new(
3013 meta.width,3065 meta.width,
3014 meta.height,3066 meta.height,
3015- meta.frame_rate,3067+ project.composite_fit_at(b_start),
3016- project.composite_visualizer_at(b_start),3068+ ),
3017- project.composite_viz_paint_at(b_start),3069+ rotated: (Vec::new(), Vec::new(), Vec::new()),
3018- )?3070+ stretched: (Vec::new(), Vec::new(), Vec::new()),
3019- } else {3071+ graded: (Vec::new(), Vec::new(), Vec::new()),
3020- ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)?3072+ transformed: (Vec::new(), Vec::new(), Vec::new()),
3021- },3073+ })
3022- mapper: b_mapper,3074+ },
3023- remap: b_remap,3075+ )
3024- grade: project.composite_color_at(b_start).copied(),
3025- transform: project
3026- .composite_transform_at(b_start)
3027- .copied()
3028- .unwrap_or_default(),
3029- rotation: b_rotation,
3030- pixel_aspect: b_pixel_aspect,
3031- canvas: Composer::new(
3032- meta.width,
3033- meta.height,
3034- project.composite_fit_at(b_start),
3035- ),
3036- rotated: (Vec::new(), Vec::new(), Vec::new()),
3037- stretched: (Vec::new(), Vec::new(), Vec::new()),
3038- graded: (Vec::new(), Vec::new(), Vec::new()),
3039- transformed: (Vec::new(), Vec::new(), Vec::new()),
3040- })
3041- })
3042 .transpose()?;3076 .transpose()?;
3043 // Timeline frames, taken a *source* frame at a time: at a rate other3077 // Timeline frames, taken a *source* frame at a time: at a rate other
3044 // than real time the two are not the same count, and the span says which3078 // than real time the two are not the same count, and the span says which
@@ -3175,9 +3209,21 @@ fn run(
3175 }3209 }
3176 Some(Frame::Pixels(by, bu, bv, bw, bh)) => {3210 Some(Frame::Pixels(by, bu, bv, bw, bh)) => {
3177 let (by, bu, bv, _, _) = place_picture(3211 let (by, bu, bv, _, _) = place_picture(
3178- by, bu, bv, bw, bh, d.rotation, d.pixel_aspect, d.grade,3212+ by,
3179- d.transform, d.remap, d.mapper, &mut d.rotated,3213+ bu,
3180- &mut d.stretched, &mut d.graded, &mut d.transformed,3214+ bv,
3215+ bw,
3216+ bh,
3217+ d.rotation,
3218+ d.pixel_aspect,
3219+ d.grade,
3220+ d.transform,
3221+ d.remap,
3222+ d.mapper,
3223+ &mut d.rotated,
3224+ &mut d.stretched,
3225+ &mut d.graded,
3226+ &mut d.transformed,
3181 &mut d.canvas,3227 &mut d.canvas,
3182 );3228 );
3183 let idx_in_window = done_here + r - d.tail_start;3229 let idx_in_window = done_here + r - d.tail_start;
@@ -3358,7 +3404,9 @@ fn place_picture<'a>(
3358 display_width.div_ceil(2) as usize,3404 display_width.div_ceil(2) as usize,
3359 height.div_ceil(2) as usize,3405 height.div_ceil(2) as usize,
3360 );3406 );
3361- stretched.0.resize(display_width as usize * height as usize, 0);3407+ stretched
3408+ .0
3409+ .resize(display_width as usize * height as usize, 0);
3362 stretched.1.resize(dcw * dch, 0);3410 stretched.1.resize(dcw * dch, 0);
3363 stretched.2.resize(dcw * dch, 0);3411 stretched.2.resize(dcw * dch, 0);
3364 crate::scale::scale_i420(3412 crate::scale::scale_i420(
@@ -3437,7 +3485,13 @@ fn place_picture<'a>(
3437 } else {3485 } else {
3438 let (py, pu, pv, w, h) = canvas.place_transformed(y, u, v, width, height, &transform);3486 let (py, pu, pv, w, h) = canvas.place_transformed(y, u, v, width, height, &transform);
3439 *transformed = (py, pu, pv);3487 *transformed = (py, pu, pv);
3440- (&transformed.0[..], &transformed.1[..], &transformed.2[..], w, h)3488+ (
3489+ &transformed.0[..],
3490+ &transformed.1[..],
3491+ &transformed.2[..],
3492+ w,
3493+ h,
3494+ )
3441 }3495 }
3442 }3496 }
3443 3497
@@ -3482,7 +3536,10 @@ fn source_rate(
3482 // `decode::rgb_to_i420` is the one matrix that turns its pixels into3536 // `decode::rgb_to_i420` is the one matrix that turns its pixels into
3483 // planes. A song has no picture and the answer is never read. Neither3537 // planes. A song has no picture and the answer is never read. Neither
3484 // has a display matrix to be turned by, nor an aspect to be widened3538 // has a display matrix to be turned by, nor an aspect to be widened
3485- // by: both are authored square.3539+ // by: both are authored square. A still's *EXIF* turn is not in this
3540+ // arm either, and for a better reason -- `decode::Still::open` already
3541+ // made it before the planes were written, so `place_picture` is handed
3542+ // the picture the preview showed and must not be told to turn it again.
3486 return (3543 return (
3487 Rate::REAL_TIME,3544 Rate::REAL_TIME,
3488 ColorDescription::default(),3545 ColorDescription::default(),
@@ -3582,9 +3639,8 @@ fn run_audio(
3582 };3639 };
3583 // The picture path's line, for a file that is sound alone: there is sound3640 // The picture path's line, for a file that is sound alone: there is sound
3584 // by the line above, so this names the encoder writing it.3641 // by the line above, so this names the encoder writing it.
3585- *shared.encoders.lock().unwrap() = Some(3642+ *shared.encoders.lock().unwrap() =
3586- audio_label(project, format, true, None, settings.range.is_some()).to_string(),3643+ Some(audio_label(project, format, true, None, settings.range.is_some()).to_string());
3587- );
3588 let channels = usize::from(audio.channels);3644 let channels = usize::from(audio.channels);
3589 let out_frames = settings.range.map_or(project.media_frames(), |(s, e)| {3645 let out_frames = settings.range.map_or(project.media_frames(), |(s, e)| {
3590 e.min(project.media_frames()).saturating_sub(s)3646 e.min(project.media_frames()).saturating_sub(s)
@@ -4404,9 +4460,7 @@ impl Enc {
4404 cfg.timing = Some((fps_den, fps_num));4460 cfg.timing = Some((fps_den, fps_num));
4405 cfg.video_signal_type = Some(video_signal_type(meta.height));4461 cfg.video_signal_type = Some(video_signal_type(meta.height));
4406 cfg.threads = per_lane;4462 cfg.threads = per_lane;
4407- lanes.push(4463+ lanes.push(HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?);
4408- HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?,
4409- );
4410 }4464 }
4411 Ok(Self::Hevc(HevcEnc {4465 Ok(Self::Hevc(HevcEnc {
4412 pending: Vec::new(),4466 pending: Vec::new(),
@@ -4467,7 +4521,9 @@ impl Enc {
4467 // them is a sync point -- said as a constant rather than parsed back4521 // them is a sync point -- said as a constant rather than parsed back
4468 // out of the bitstream, because it is this encoder's configuration4522 // out of the bitstream, because it is this encoder's configuration
4469 // and not a driver's choice.4523 // and not a driver's choice.
4470- Self::HevcHw(hw) => Ok(hw.encode(y, u, v, width, height, true)?.map(|au| (au, true))),4524+ Self::HevcHw(hw) => Ok(hw
4525+ .encode(y, u, v, width, height, true)?
4526+ .map(|au| (au, true))),
4471 Self::Hevc(hevc) => {4527 Self::Hevc(hevc) => {
4472 // The display-size planes are kept as they came: `ec-h265`4528 // The display-size planes are kept as they came: `ec-h265`
4473 // pads to its own coded grid and crops back through the SPS4529 // pads to its own coded grid and crops back through the SPS
@@ -4858,7 +4914,11 @@ impl ClipDecoder {
4858 .ok()4914 .ok()
4859 .flatten()4915 .flatten()
4860 .unwrap_or_default();4916 .unwrap_or_default();
4861- let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 };4917+ let fps = if fps.is_finite() && fps > 0.0 {
4918+ fps
4919+ } else {
4920+ 30.0
4921+ };
4862 Ok(Self::Visualizer {4922 Ok(Self::Visualizer {
4863 peaks,4923 peaks,
4864 width,4924 width,
@@ -5124,9 +5184,7 @@ impl SwDecoder {
5124 // either answer means go back for the next access unit.5184 // either answer means go back for the next access unit.
5125 Err(e) if e.is_eof() && self.flushed => return Ok(false),5185 Err(e) if e.is_eof() && self.flushed => return Ok(false),
5126 Err(e) if e.is_need_more() || e.is_eof() => {}5186 Err(e) if e.is_need_more() || e.is_eof() => {}
5127- Err(e) => {5187+ Err(e) => return Err(format!("decode at picture {}: {e}", self.index).into()),
5128- return Err(format!("decode at picture {}: {e}", self.index).into())
5129- }
5130 }5188 }
5131 }5189 }
5132 }5190 }
@@ -5655,7 +5713,11 @@ mod tests {
5655 // 1280 * 720 * 30 * 0.15713 // 1280 * 720 * 30 * 0.1
5656 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);5714 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
5657 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), 230_400, "tiny");5715 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), 230_400, "tiny");
5658- assert_eq!(bitrate_for(&meta(160, 120, 15.0)), MIN_BITRATE, "tinier floors");5716+ assert_eq!(
5717+ bitrate_for(&meta(160, 120, 15.0)),
5718+ MIN_BITRATE,
5719+ "tinier floors"
5720+ );
5659 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");5721 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
5660 // A rate somebody typed goes through untouched to its own ceiling, which5722 // A rate somebody typed goes through untouched to its own ceiling, which
5661 // is above where the derived one stops: the card offers 50 Mbps, and a5723 // is above where the derived one stops: the card offers 50 Mbps, and a
@@ -5687,7 +5749,11 @@ mod tests {
5687 fn a_fade_forces_the_audio_to_be_re_encoded() {5749 fn a_fade_forces_the_audio_to_be_re_encoded() {
5688 let mut project = Project::single("/nonexistent/film.mp4", 90);5750 let mut project = Project::single("/nonexistent/film.mp4", 90);
5689 assert!(!forces_encode(&project, false), "flat, so a copy is fine");5751 assert!(!forces_encode(&project, false), "flat, so a copy is fine");
5690- assert!(project.set_fade_in(crate::project::Lane::new(crate::project::LaneKind::Audio, 0), 0, 15));5752+ assert!(project.set_fade_in(
5753+ crate::project::Lane::new(crate::project::LaneKind::Audio, 0),
5754+ 0,
5755+ 15
5756+ ));
5691 assert!(5757 assert!(
5692 forces_encode(&project, false),5758 forces_encode(&project, false),
5693 "a fade-in on the only clip must force a re-encode"5759 "a fade-in on the only clip must force a re-encode"
@@ -5796,7 +5862,11 @@ mod tests {
5796 /// B, and the window itself never quite repeats a hard cut's own instant.5862 /// B, and the window itself never quite repeats a hard cut's own instant.
5797 #[test]5863 #[test]
5798 fn dissolve_weight_ramps_strictly_between_zero_and_one() {5864 fn dissolve_weight_ramps_strictly_between_zero_and_one() {
5799- assert_eq!(dissolve_weight(0, 1), 0.5, "a one-frame window is the midpoint");5865+ assert_eq!(
5866+ dissolve_weight(0, 1),
5867+ 0.5,
5868+ "a one-frame window is the midpoint"
5869+ );
5800 assert_eq!(dissolve_weight(0, 4), 0.2);5870 assert_eq!(dissolve_weight(0, 4), 0.2);
5801 assert_eq!(dissolve_weight(1, 4), 0.4);5871 assert_eq!(dissolve_weight(1, 4), 0.4);
5802 assert_eq!(dissolve_weight(2, 4), 0.6);5872 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+ 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 }
@@ -120,18 +132,8 @@ mod tests {
120 #[test]132 #[test]
121 fn is_audio_admits_the_containers_the_decoder_reads() {133 fn is_audio_admits_the_containers_the_decoder_reads() {
122 for name in [134 for name in [
123- "song.mp3",135+ "song.mp3", "a.WAV", "b.flac", "c.ogg", "d.oga", "e.m4a", "f.aac", "g.opus", "h.OPUS",
124- "a.WAV",136+ "i.mka", "j.MPEG", "k.mpg",
125- "b.flac",
126- "c.ogg",
127- "d.oga",
128- "e.m4a",
129- "f.aac",
130- "g.opus",
131- "h.OPUS",
132- "i.mka",
133- "j.MPEG",
134- "k.mpg",
135 ] {137 ] {
136 assert!(super::is_audio(Path::new(name)), "{name}");138 assert!(super::is_audio(Path::new(name)), "{name}");
137 }139 }
crates/engine/src/playback.rsmodified+142 -85
@@ -26,8 +26,9 @@ use crate::colorspace::{ColorDescription, ContentLight};
26 use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker};26 use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker};
27 use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta};27 use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta};
28 use crate::eq::EqParams;28 use crate::eq::EqParams;
29-use crate::project::{ProjectSettings,29+use crate::project::{
30- Clip, Edge, GapSweep, Lane, LaneKind, Project, Rate, Source, Span, Speed, SubClip,30+ Clip, Edge, GapSweep, Lane, LaneKind, Project, ProjectSettings, Rate, Source, Span, Speed,
31+ SubClip,
31 };32 };
32 use crate::scale::{Composer, FitPolicy};33 use crate::scale::{Composer, FitPolicy};
33 use crate::transform::TransformParams;34 use crate::transform::TransformParams;
@@ -638,7 +639,9 @@ impl PlaybackSession {
638 // hands it back out. The same trade the audio header cache above this639 // hands it back out. The same trade the audio header cache above this
639 // makes -- a second container open, paid once at open rather than never640 // makes -- a second container open, paid once at open rather than never
640 // -- since nothing here decodes a single picture.641 // -- since nothing here decodes a single picture.
641- let content_light = Demuxer::open(&path).map(|(_, d)| d.light()).unwrap_or_default();642+ let content_light = Demuxer::open(&path)
643+ .map(|(_, d)| d.light())
644+ .unwrap_or_default();
642 Ok(Self {645 Ok(Self {
643 meta,646 meta,
644 content_light,647 content_light,
@@ -831,6 +834,10 @@ impl PlaybackSession {
831 frame_count: image_frames(IMAGE_ONLY_RATE),834 frame_count: image_frames(IMAGE_ONLY_RATE),
832 codec: Codec::H264,835 codec: Codec::H264,
833 color: ColorDescription::default(),836 color: ColorDescription::default(),
837+ // `Rotation::None` is honest, not a shrug: a still's own turn was
838+ // made in `Still::open`, before these planes were written, so the
839+ // pair below is already the displayed one and there is nothing left
840+ // for a consumer to make.
834 rotation: Rotation::None,841 rotation: Rotation::None,
835 // No container said anything about these: the picture this engine842 // No container said anything about these: the picture this engine
836 // decoded itself is square pixels at the size it was decoded at.843 // decoded itself is square pixels at the size it was decoded at.
@@ -980,7 +987,9 @@ impl PlaybackSession {
980 let content_light = if crate::is_audio(&first.path) || crate::is_image(&first.path) {987 let content_light = if crate::is_audio(&first.path) || crate::is_image(&first.path) {
981 ContentLight::default()988 ContentLight::default()
982 } else {989 } else {
983- Demuxer::open(&first.path).map(|(_, d)| d.light()).unwrap_or_default()990+ Demuxer::open(&first.path)
991+ .map(|(_, d)| d.light())
992+ .unwrap_or_default()
984 };993 };
985 // The extension's word, corrected below the moment the header disagrees994 // The extension's word, corrected below the moment the header disagrees
986 // with it (`NoVideoTrack`, the same fallback `open_stream` takes): every995 // with it (`NoVideoTrack`, the same fallback `open_stream` takes): every
@@ -1001,11 +1010,11 @@ impl PlaybackSession {
1001 codec: Codec::H264,1010 codec: Codec::H264,
1002 color: ColorDescription::default(),1011 color: ColorDescription::default(),
1003 rotation: Rotation::None,1012 rotation: Rotation::None,
1004- // No container said anything about these: the canvas this engine drew1013+ // No container said anything about these: the canvas this engine drew
1005- // itself is square pixels at the size it was drawn at.1014+ // itself is square pixels at the size it was drawn at.
1006- coded_width: width,1015+ coded_width: width,
1007- coded_height: height,1016+ coded_height: height,
1008- pixel_aspect: crate::demux::PixelAspect::SQUARE,1017+ pixel_aspect: crate::demux::PixelAspect::SQUARE,
1009 };1018 };
1010 (meta, DecodeSession::open_black(width, height, 1))1019 (meta, DecodeSession::open_black(width, height, 1))
1011 }1020 }
@@ -1023,6 +1032,9 @@ impl PlaybackSession {
1023 frame_count: image_frames(frame_rate),1032 frame_count: image_frames(frame_rate),
1024 codec: Codec::H264,1033 codec: Codec::H264,
1025 color: ColorDescription::default(),1034 color: ColorDescription::default(),
1035+ // `Rotation::None` is honest, not a shrug: `Still::open`
1036+ // made the file's own turn before these planes were
1037+ // written, so the pair below is already the displayed one.
1026 rotation: Rotation::None,1038 rotation: Rotation::None,
1027 // No container said anything about these: the picture this1039 // No container said anything about these: the picture this
1028 // engine decoded itself is square pixels at its own size.1040 // engine decoded itself is square pixels at its own size.
@@ -1071,11 +1083,11 @@ impl PlaybackSession {
1071 codec: Codec::H264,1083 codec: Codec::H264,
1072 color: ColorDescription::default(),1084 color: ColorDescription::default(),
1073 rotation: Rotation::None,1085 rotation: Rotation::None,
1074- // No container said anything about these: the canvas this engine drew1086+ // No container said anything about these: the canvas this engine drew
1075- // itself is square pixels at the size it was drawn at.1087+ // itself is square pixels at the size it was drawn at.
1076- coded_width: width,1088+ coded_width: width,
1077- coded_height: height,1089+ coded_height: height,
1078- pixel_aspect: crate::demux::PixelAspect::SQUARE,1090+ pixel_aspect: crate::demux::PixelAspect::SQUARE,
1079 };1091 };
1080 (meta, DecodeSession::open_black(width, height, 1))1092 (meta, DecodeSession::open_black(width, height, 1))
1081 }1093 }
@@ -1207,24 +1219,24 @@ impl PlaybackSession {
1207 let subtitles = crate::subtitle::open_all(&doc.subtitles);1219 let subtitles = crate::subtitle::open_all(&doc.subtitles);
1208 let project =1220 let project =
1209 Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)?1221 Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)?
1210- .with_mix(&doc.gains, doc.limiter)1222+ .with_mix(&doc.gains, doc.limiter)
1211- .with_tone(doc.tone)1223+ .with_tone(doc.tone)
1212- // The palette before what is placed on it: a caption names a row of1224+ // The palette before what is placed on it: a caption names a row of
1213- // it, and [`Project::with_subs`] refuses one naming a row that is1225+ // it, and [`Project::with_subs`] refuses one naming a row that is
1214- // not there.1226+ // not there.
1215- .with_subtitles(subtitles)1227+ .with_subtitles(subtitles)
1216- .with_subs(doc.subs)?1228+ .with_subs(doc.subs)?
1217- // The header a load puts back: the canvas and rate above, which a1229+ // The header a load puts back: the canvas and rate above, which a
1218- // save's own `resolution`/`fps` lines may have moved off the1230+ // save's own `resolution`/`fps` lines may have moved off the
1219- // scaffold's, and the switches the literal below carries -- handed1231+ // scaffold's, and the switches the literal below carries -- handed
1220- // in here because they are the project's own and a door that moved1232+ // in here because they are the project's own and a door that moved
1221- // one after this would snapshot whatever copy it holds, which until1233+ // one after this would snapshot whatever copy it holds, which until
1222- // this line is the placeholder's. No undo step for1234+ // this line is the placeholder's. No undo step for
1223- // [`Project::with_mix`]'s reason: a project that arrived one `z`1235+ // [`Project::with_mix`]'s reason: a project that arrived one `z`
1224- // from a state it was never in is a project whose first undo is a1236+ // from a state it was never in is a project whose first undo is a
1225- // surprise.1237+ // surprise.
1226- .with_canvas(meta.width, meta.height, meta.frame_rate)1238+ .with_canvas(meta.width, meta.height, meta.frame_rate)
1227- .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate);1239+ .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate);
1228 let span = project.composite_span_at(0);1240 let span = project.composite_span_at(0);
1229 // Last, because it is the one thing here that cannot be taken back: the1241 // Last, because it is the one thing here that cannot be taken back: the
1230 // feeder thread outlives the `Audio` value (it holds its own clones) and1242 // feeder thread outlives the `Audio` value (it holds its own clones) and
@@ -1248,7 +1260,11 @@ impl PlaybackSession {
1248 // source's silence is not worth reporting over an earlier one's).1260 // source's silence is not worth reporting over an earlier one's).
1249 let (audio, audio_disabled) = {1261 let (audio, audio_disabled) = {
1250 let mut opened = (None, None);1262 let mut opened = (None, None);
1251- for source in project.sources().iter().filter(|s| !crate::is_image(&s.path)) {1263+ for source in project
1264+ .sources()
1265+ .iter()
1266+ .filter(|s| !crate::is_image(&s.path))
1267+ {
1252 opened = open_audio(&source.path, source.audio_stream);1268 opened = open_audio(&source.path, source.audio_stream);
1253 if opened.0.is_some() {1269 if opened.0.is_some() {
1254 break;1270 break;
@@ -1713,8 +1729,10 @@ impl PlaybackSession {
1713 };1729 };
1714 let now = secs_to_frame(self.clock.now(), self.meta.frame_rate);1730 let now = secs_to_frame(self.clock.now(), self.meta.frame_rate);
1715 let offset = now.saturating_sub(span.start).min(span.len);1731 let offset = now.saturating_sub(span.start).min(span.len);
1716- self.worker1732+ self.worker.playhead(
1717- .playhead(self.span_rate.source_at(in_frame + span.speed.source_at(offset)));1733+ self.span_rate
1734+ .source_at(in_frame + span.speed.source_at(offset)),
1735+ );
1718 }1736 }
1719 1737
1720 /// Installs `replacement` as the decode worker, parking the outgoing one in1738 /// Installs `replacement` as the decode worker, parking the outgoing one in
@@ -1908,11 +1926,7 @@ impl PlaybackSession {
1908 .composite_transform_at(start)1926 .composite_transform_at(start)
1909 .copied()1927 .copied()
1910 .unwrap_or_default(),1928 .unwrap_or_default(),
1911- Composer::new(1929+ Composer::new(canvas_w, canvas_h, self.project.composite_fit_at(start)),
1912- canvas_w,
1913- canvas_h,
1914- self.project.composite_fit_at(start),
1915- ),
1916 )1930 )
1917 .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}"))1931 .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}"))
1918 }1932 }
@@ -1941,17 +1955,11 @@ impl PlaybackSession {
1941 .composite_transform_at(start)1955 .composite_transform_at(start)
1942 .copied()1956 .copied()
1943 .unwrap_or_default(),1957 .unwrap_or_default(),
1944- Composer::new(1958+ Composer::new(canvas_w, canvas_h, self.project.composite_fit_at(start)),
1945- canvas_w,
1946- canvas_h,
1947- self.project.composite_fit_at(start),
1948- ),
1949 self.project.composite_visualizer_at(start),1959 self.project.composite_visualizer_at(start),
1950 self.project.composite_viz_paint_at(start),1960 self.project.composite_viz_paint_at(start),
1951 )1961 )
1952- .inspect_err(|e| {1962+ .inspect_err(|e| eprintln!("timeline frame {start}: visualizer open failed: {e}"))
1953- eprintln!("timeline frame {start}: visualizer open failed: {e}")
1954- })
1955 }1963 }
1956 Some(Span {1964 Some(Span {
1957 start,1965 start,
@@ -2119,11 +2127,7 @@ impl PlaybackSession {
2119 .composite_transform_at(b_start)2127 .composite_transform_at(b_start)
2120 .copied()2128 .copied()
2121 .unwrap_or_default();2129 .unwrap_or_default();
2122- let canvas = Composer::new(2130+ let canvas = Composer::new(canvas_w, canvas_h, self.project.composite_fit_at(b_start));
2123- canvas_w,
2124- canvas_h,
2125- self.project.composite_fit_at(b_start),
2126- );
2127 let tone = self.project.tone();2131 let tone = self.project.tone();
2128 let stream = DecodeSession::open_worker_deferred(2132 let stream = DecodeSession::open_worker_deferred(
2129 &path,2133 &path,
@@ -2301,7 +2305,9 @@ impl PlaybackSession {
2301 /// changes only the words, which are drawn over whatever is decoded.2305 /// changes only the words, which are drawn over whatever is decoded.
2302 pub fn trim_sub(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> crate::Result<()> {2306 pub fn trim_sub(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> crate::Result<()> {
2303 let grouped = self.caption_grouped_with_clips(lane, idx);2307 let grouped = self.caption_grouped_with_clips(lane, idx);
2304- let trimmed = self.project.trim_sub(lane, idx, edge, to, self.meta.frame_rate);2308+ let trimmed = self
2309+ .project
2310+ .trim_sub(lane, idx, edge, to, self.meta.frame_rate);
2305 if trimmed.is_ok() && grouped {2311 if trimmed.is_ok() && grouped {
2306 self.invalidate(Dirty::Both);2312 self.invalidate(Dirty::Both);
2307 }2313 }
@@ -2312,7 +2318,8 @@ impl PlaybackSession {
2312 /// ([`Project::trim_sub_room`]) -- what a front-end drawing the box during2318 /// ([`Project::trim_sub_room`]) -- what a front-end drawing the box during
2313 /// a drag asks, at this timeline's rate.2319 /// a drag asks, at this timeline's rate.
2314 pub fn trim_sub_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {2320 pub fn trim_sub_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
2315- self.project.trim_sub_room(lane, idx, edge, self.meta.frame_rate)2321+ self.project
2322+ .trim_sub_room(lane, idx, edge, self.meta.frame_rate)
2316 }2323 }
2317 2324
2318 /// Takes one placement off a subtitle lane, leaving a gap2325 /// Takes one placement off a subtitle lane, leaving a gap
@@ -2390,7 +2397,11 @@ impl PlaybackSession {
2390 // one this dispatch needs; a caption carries a link at all only once2397 // one this dispatch needs; a caption carries a link at all only once
2391 // grouped (`place_sub` always starts one at `None`), so that alone is2398 // grouped (`place_sub` always starts one at `None`), so that alone is
2392 // "this delete ripples more than its own lane".2399 // "this delete ripples more than its own lane".
2393- match self.sub_lane(lane).get(idx).is_some_and(|s| s.link.is_some()) {2400+ match self
2401+ .sub_lane(lane)
2402+ .get(idx)
2403+ .is_some_and(|s| s.link.is_some())
2404+ {
2394 true => self.edit(Dirty::Both, |p| p.delete_sub_in(lane, idx)),2405 true => self.edit(Dirty::Both, |p| p.delete_sub_in(lane, idx)),
2395 // A caption in no group is the plain lift that touches nothing2406 // A caption in no group is the plain lift that touches nothing
2396 // else: no reseek owed.2407 // else: no reseek owed.
@@ -2555,7 +2566,9 @@ impl PlaybackSession {
2555 to: Lane,2566 to: Lane,
2556 start: u32,2567 start: u32,
2557 ) -> bool {2568 ) -> bool {
2558- self.edit(Dirty::Both, |p| p.move_selection(picks, from, idx, to, start))2569+ self.edit(Dirty::Both, |p| {
2570+ p.move_selection(picks, from, idx, to, start)
2571+ })
2559 }2572 }
2560 2573
2561 /// Drags one end of that clip to timeline frame `to`, changing how much of2574 /// Drags one end of that clip to timeline frame `to`, changing how much of
@@ -3267,8 +3280,8 @@ impl PlaybackSession {
3267 // end is an append, never a clip with black in front of it. The frame3280 // end is an append, never a clip with black in front of it. The frame
3268 // itself is honoured in [`Project::paste`], because a *drop* names a3281 // itself is honoured in [`Project::paste`], because a *drop* names a
3269 // place on the bed and means it.3282 // place on the bed and means it.
3270- let at = secs_to_frame(timeline_secs, self.meta.frame_rate)3283+ let at =
3271- .min(self.project.timeline_frames());3284+ secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames());
3272 self.edit(Dirty::Both, |p| p.paste(at, clip))3285 self.edit(Dirty::Both, |p| p.paste(at, clip))
3273 }3286 }
3274 3287
@@ -3277,8 +3290,8 @@ impl PlaybackSession {
3277 /// past the last frame lands there rather than carrying black in front of3290 /// past the last frame lands there rather than carrying black in front of
3278 /// it, exactly as a lone clip's paste does.3291 /// it, exactly as a lone clip's paste does.
3279 pub fn paste_set_at(&mut self, timeline_secs: f64, items: &[(Lane, Clip)]) -> bool {3292 pub fn paste_set_at(&mut self, timeline_secs: f64, items: &[(Lane, Clip)]) -> bool {
3280- let at = secs_to_frame(timeline_secs, self.meta.frame_rate)3293+ let at =
3281- .min(self.project.timeline_frames());3294+ secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames());
3282 self.edit(Dirty::Both, |p| p.paste_set(at, items))3295 self.edit(Dirty::Both, |p| p.paste_set(at, items))
3283 }3296 }
3284 3297
@@ -4828,8 +4841,8 @@ fn blend_bgra(a: &[u8], b: &[u8], t: f32) -> Vec<u8> {
4828 #[cfg(test)]4841 #[cfg(test)]
4829 mod tests {4842 mod tests {
4830 use super::{4843 use super::{
4831- Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of, blend_bgra, secs_to_frame,4844+ AUDIO_LOST, Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of,
4832- AUDIO_LOST,4845+ blend_bgra, secs_to_frame,
4833 };4846 };
4834 use std::path::PathBuf;4847 use std::path::PathBuf;
4835 use std::sync::atomic::Ordering;4848 use std::sync::atomic::Ordering;
@@ -4874,7 +4887,12 @@ mod tests {
4874 "a dead output went to wall time without a word"4887 "a dead output went to wall time without a word"
4875 );4888 );
4876 assert!(4889 assert!(
4877- session.audio.as_ref().expect("audio").died.load(Ordering::Acquire),4890+ session
4891+ .audio
4892+ .as_ref()
4893+ .expect("audio")
4894+ .died
4895+ .load(Ordering::Acquire),
4878 "a tick opened the output again inside the cooldown"4896 "a tick opened the output again inside the cooldown"
4879 );4897 );
4880 assert!(4898 assert!(
@@ -4900,7 +4918,12 @@ mod tests {
4900 "playing after a dead output fed nothing: the session cannot come back"4918 "playing after a dead output fed nothing: the session cannot come back"
4901 );4919 );
4902 assert!(4920 assert!(
4903- !session.audio.as_ref().expect("audio").died.load(Ordering::Acquire),4921+ !session
4922+ .audio
4923+ .as_ref()
4924+ .expect("audio")
4925+ .died
4926+ .load(Ordering::Acquire),
4904 "the death flag stood after the output was replaced"4927 "the death flag stood after the output was replaced"
4905 );4928 );
4906 assert_eq!(4929 assert_eq!(
@@ -4941,7 +4964,11 @@ mod tests {
4941 std::thread::sleep(std::time::Duration::from_millis(5));4964 std::thread::sleep(std::time::Duration::from_millis(5));
4942 }4965 }
4943 let frame = frame.unwrap_or_else(|| panic!("no frame from a {w}x{h} canvas"));4966 let frame = frame.unwrap_or_else(|| panic!("no frame from a {w}x{h} canvas"));
4944- assert_eq!((frame.width, frame.height), (w, h), "a frame at the canvas's own size");4967+ assert_eq!(
4968+ (frame.width, frame.height),
4969+ (w, h),
4970+ "a frame at the canvas's own size"
4971+ );
4945 }4972 }
4946 }4973 }
4947 4974
@@ -5026,18 +5053,27 @@ mod tests {
5026 let file = asset("test_av.mp4");5053 let file = asset("test_av.mp4");
5027 let sources = [(file, 0)];5054 let sources = [(file, 0)];
5028 let segs = [(Some(0), 0., 1.)];5055 let segs = [(Some(0), 0., 1.)];
5029- let derived = crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], None)5056+ let derived =
5030- .expect("open the fixture")5057+ crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], None)
5031- .expect("the fixture has sound")
5032- .0
5033- .sample_rate;
5034- let picked =
5035- crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], Some(32000))
5036 .expect("open the fixture")5058 .expect("open the fixture")
5037 .expect("the fixture has sound")5059 .expect("the fixture has sound")
5038 .05060 .0
5039 .sample_rate;5061 .sample_rate;
5040- assert_ne!(derived, 32000, "a fixture at the picked rate proves nothing");5062+ let picked = crate::AudioSession::open_multi_streams_speed_at(
5063+ &sources,
5064+ &segs,
5065+ &[],
5066+ &[],
5067+ Some(32000),
5068+ )
5069+ .expect("open the fixture")
5070+ .expect("the fixture has sound")
5071+ .0
5072+ .sample_rate;
5073+ assert_ne!(
5074+ derived, 32000,
5075+ "a fixture at the picked rate proves nothing"
5076+ );
5041 assert_eq!(picked, 32000);5077 assert_eq!(picked, 32000);
5042 }5078 }
5043 5079
@@ -5099,7 +5135,8 @@ mod tests {
5099 "an import must not move the project's own canvas size"5135 "an import must not move the project's own canvas size"
5100 );5136 );
5101 assert_eq!(5137 assert_eq!(
5102- session.meta().frame_rate, picked_fps,5138+ session.meta().frame_rate,
5139+ picked_fps,
5103 "an import must not move the project's own rate"5140 "an import must not move the project's own rate"
5104 );5141 );
5105 }5142 }
@@ -5216,9 +5253,11 @@ mod tests {
5216 let zero = PlaybackSession::open_with_audio_stream(&multi, 0).expect("stream 0 opens");5253 let zero = PlaybackSession::open_with_audio_stream(&multi, 0).expect("stream 0 opens");
5217 let one = PlaybackSession::open_with_audio_stream(&multi, 1).expect("stream 1 opens");5254 let one = PlaybackSession::open_with_audio_stream(&multi, 1).expect("stream 1 opens");
5218 let default = PlaybackSession::open(&multi).expect("default open");5255 let default = PlaybackSession::open(&multi).expect("default open");
5219- let (Some(a0), Some(a1), Some(ad)) =5256+ let (Some(a0), Some(a1), Some(ad)) = (
5220- (zero.audio.as_ref(), one.audio.as_ref(), default.audio.as_ref())5257+ zero.audio.as_ref(),
5221- else {5258+ one.audio.as_ref(),
5259+ default.audio.as_ref(),
5260+ ) else {
5222 // No audio device on this machine: nothing further to check --5261 // No audio device on this machine: nothing further to check --
5223 // the device is the machine's business, not this door's.5262 // the device is the machine's business, not this door's.
5224 return;5263 return;
@@ -5226,7 +5265,10 @@ mod tests {
5226 assert_eq!(a0.channels, 2, "stream 0 is the stereo pair");5265 assert_eq!(a0.channels, 2, "stream 0 is the stereo pair");
5227 assert_eq!(a1.channels, 1, "stream 1 is the mono track");5266 assert_eq!(a1.channels, 1, "stream 1 is the mono track");
5228 assert_ne!(a0.channels, a1.channels, "the two streams must differ");5267 assert_ne!(a0.channels, a1.channels, "the two streams must differ");
5229- assert_eq!(ad.channels, a0.channels, "open() still defaults to stream 0");5268+ assert_eq!(
5269+ ad.channels, a0.channels,
5270+ "open() still defaults to stream 0"
5271+ );
5230 }5272 }
5231 5273
5232 /// The bug this regression pins: a preview paused (or scrubbed) to a5274 /// The bug this regression pins: a preview paused (or scrubbed) to a
@@ -5260,7 +5302,10 @@ mod tests {
5260 5302
5261 let fps = on.meta().frame_rate;5303 let fps = on.meta().frame_rate;
5262 let clip0_len = on.lane_clips(Lane::V1)[0].len();5304 let clip0_len = on.lane_clips(Lane::V1)[0].len();
5263- assert!(clip0_len > window, "the fixture needs to outlast the window");5305+ assert!(
5306+ clip0_len > window,
5307+ "the fixture needs to outlast the window"
5308+ );
5264 let mid_of_window = clip0_len - window / 2;5309 let mid_of_window = clip0_len - window / 2;
5265 let t = f64::from(mid_of_window) / fps;5310 let t = f64::from(mid_of_window) / fps;
5266 5311
@@ -5276,7 +5321,10 @@ mod tests {
5276 if let Some(f) = s.try_frame() {5321 if let Some(f) = s.try_frame() {
5277 return f;5322 return f;
5278 }5323 }
5279- assert!(std::time::Instant::now() < deadline, "no frame within 20s of the seek");5324+ assert!(
5325+ std::time::Instant::now() < deadline,
5326+ "no frame within 20s of the seek"
5327+ );
5280 std::thread::sleep(std::time::Duration::from_millis(10));5328 std::thread::sleep(std::time::Duration::from_millis(10));
5281 }5329 }
5282 };5330 };
@@ -5337,11 +5385,21 @@ mod tests {
5337 scale: 1.2,5385 scale: 1.2,
5338 ..Default::default()5386 ..Default::default()
5339 };5387 };
5340- assert!(s.set_transform_live(clip.0, clip.1, Some(params)), "the edit took");5388+ assert!(
5389+ s.set_transform_live(clip.0, clip.1, Some(params)),
5390+ "the edit took"
5391+ );
5341 let next = poll(&mut s);5392 let next = poll(&mut s);
5342 5393
5343- assert_eq!(before, s.restarts(), "a live transform edit must reuse the worker");5394+ assert_eq!(
5344- assert_eq!(next.index, first.index, "paused: same timeline position before and after");5395+ before,
5396+ s.restarts(),
5397+ "a live transform edit must reuse the worker"
5398+ );
5399+ assert_eq!(
5400+ next.index, first.index,
5401+ "paused: same timeline position before and after"
5402+ );
5345 }5403 }
5346 5404
5347 /// A rate undo lands the picture where the playhead is, in the rate that5405 /// A rate undo lands the picture where the playhead is, in the rate that
@@ -5413,4 +5471,3 @@ mod tests {
5413 );5471 );
5414 }5472 }
5415 }5473 }
5416-
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+}