diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0b0a571..720a844 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -205,5 +205,7 @@ oxideav-sub-image = "0.0.7" [dev-dependencies] # The still-image suite compares what the timeline shows against the file's own -# pixels rather than against a constant. Already built for the engine itself. -image = { version = "0.25", default-features = false, features = ["png"] } +# pixels rather than against a constant, and the EXIF suite has to *write* one: +# no fixture in `assets/` carries an orientation tag, so the turned-still test +# builds its own JPEG here. Already built for the engine itself. +image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 57fe1ab..5339563 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -7,13 +7,14 @@ use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}; use std::thread; -use ec_core::frame::VideoFrame; use ec_av1::encode::Picture as Av1Picture; use ec_av1::stream::decode_stream_with; -use ec_core::registry::{CodecId, CodecParameters}; +use ec_core::frame::VideoFrame; use ec_core::registry::Decoder as _; +use ec_core::registry::{CodecId, CodecParameters}; use ec_core::{Error as Av1Error, Packet, TimeBase}; use ec_h264::H264Decoder; +use image::ImageDecoder as _; use crate::color::ColorParams; use crate::colorspace::{ColorDescription, Matrix, Transfer}; @@ -560,7 +561,9 @@ impl DecodeSession { let first = Render::new( color, transform, - // A still has no display matrix: what the file holds is what it is. + // A still's own turn is already in these planes: `Still::open` made + // it before the conversion above, exactly where the video door + // makes a display matrix, so the render must not make it twice. Rotation::None, // ...and no sample aspect either: a still is authored square. PixelAspect::SQUARE, @@ -684,7 +687,11 @@ impl DecodeSession { if worker_cancel.load(Ordering::Relaxed) { return; } - let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 }; + let fps = if fps.is_finite() && fps > 0.0 { + fps + } else { + 30.0 + }; // One frame's painting no longer allocates per strand per // frame: this thread lives for the span. let mut scratch = VizScratch::default(); @@ -711,9 +718,8 @@ impl DecodeSession { // the same thirty seconds, and no decode at all for the // rebuilds of a look edit. let view = envelope.view_at(t); - let (y, u, v) = visualizer_window_i420( - &mut scratch, &view, t, width, height, flags, paint, - ); + let (y, u, v) = + visualizer_window_i420(&mut scratch, &view, t, width, height, flags, paint); let frame = render.frame(start_frame + index, &y, &u, &v, width, height); if tx.send(frame).is_err() { return; // caller moved on @@ -762,6 +768,34 @@ impl DecodeSession { tone: tonemap::Preset, ) -> crate::Result<(VideoMeta, FrameStream)> { let path = path.as_ref().to_path_buf(); + // A still is not a stream: handing one to the mp4 demuxer answers "a + // box with a larger size than it", which is a true sentence about a + // container and nothing a person can act on -- and it made this door, + // the one a front-end opens a file through, refuse every picture + // outright. The still door answers with a meta of its own, so a poster + // thumbnail and a preview window get the same picture the timeline + // does, at the same size. No `tone` argument is passed on and none is + // wanted: a still is decoded into BT.601 SDR planes, so there is no + // map to build whichever rendition the project is watching. + if crate::is_image(&path) { + let still = Still::open(&path)?; + let meta = VideoMeta { + width: still.width, + height: still.height, + frame_rate: 1.0, + frame_count: 1, + codec: Codec::H264, + color: ColorDescription::default(), + // A still's own turn was made in `Still::open`, before these + // planes were written, so there is nothing left to state here. + rotation: Rotation::None, + coded_width: still.width, + coded_height: still.height, + pixel_aspect: PixelAspect::SQUARE, + }; + return Self::open_still(&path, start_frame, 1, color, transform, canvas) + .map(|stream| (meta, stream)); + } let (meta, demuxer) = Demuxer::open(&path)?; // No software HEVC, VP9 or VP8 decoder exists, so such a file the plugin will // not take is refused *here*, where the caller still has somewhere to @@ -1049,7 +1083,9 @@ impl Source { fn position_hw(&mut self, path: &Path, start: u32) -> Option { if let Some(hw) = &mut self.hw { if hw.seek(start) { - eprintln!("decode backend: hardware (VA-API plugin, session kept, seek to {start})"); + eprintln!( + "decode backend: hardware (VA-API plugin, session kept, seek to {start})" + ); return Some(true); } // A plugin too old to reposition, or a decoder that would not @@ -1140,7 +1176,9 @@ fn run_span( // is a software fallback. Without this a single unfollowed seek would // collapse the rest of the file to software. if !decoded && reused { - eprintln!("hardware decode produced nothing after a reseek; reopening at frame {start}"); + eprintln!( + "hardware decode produced nothing after a reseek; reopening at frame {start}" + ); opened.hw = open_hw(path, start); if let Some(hw) = opened.hw.as_mut() { decoded = run_hw(hw, &tx, start, end, &mut render, abort, speed); @@ -1162,12 +1200,28 @@ fn run_span( Codec::H264 => { eprintln!("decode backend: software (ec-h264)"); backend.set(Backend::Software); - run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed); + run( + &mut opened.demuxer, + &tx, + start, + end, + &mut render, + abort, + speed, + ); } Codec::Av1 => { eprintln!("decode backend: software (ec-av1)"); backend.set(Backend::Software); - run_av1(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed); + run_av1( + &mut opened.demuxer, + &tx, + start, + end, + &mut render, + abort, + speed, + ); } // Nothing decodes from here -- no software seat exists for this codec. // Say so: the cell was left claiming the hardware session that opened @@ -1388,36 +1442,35 @@ impl Render { // picture a viewer is shown, so its brightness and saturation mean what // they say in the SDR the tone map just produced, not in the 10-stop // HDR the file was in. - let (y, u, v, desc) = if self.tone.is_some() - || (!skip_placement && !self.color.is_identity()) - { - let (gy, gu, gv) = &mut self.graded; - gy.clear(); - gy.extend_from_slice(y); - gu.clear(); - gu.extend_from_slice(u); - gv.clear(); - gv.extend_from_slice(v); - if let Some(tone) = &self.tone { - tone.map(gy, gu, gv, width as usize, height as usize); - } - // The same terms the branch was entered on: anywhere the fused - // conversion below will not apply the grade (a placement is - // happening, so the canvas conversion is plain), it lands here -- - // including the passthrough-sized clip a transform moves, whose - // grade used to be dropped on the floor between these two guards. - if !skip_placement && !self.color.is_identity() { - crate::color::apply_yuv(&self.color, gy, gu, gv); - } - let desc = if self.tone.is_some() { - TONE_MAPPED + let (y, u, v, desc) = + if self.tone.is_some() || (!skip_placement && !self.color.is_identity()) { + let (gy, gu, gv) = &mut self.graded; + gy.clear(); + gy.extend_from_slice(y); + gu.clear(); + gu.extend_from_slice(u); + gv.clear(); + gv.extend_from_slice(v); + if let Some(tone) = &self.tone { + tone.map(gy, gu, gv, width as usize, height as usize); + } + // The same terms the branch was entered on: anywhere the fused + // conversion below will not apply the grade (a placement is + // happening, so the canvas conversion is plain), it lands here -- + // including the passthrough-sized clip a transform moves, whose + // grade used to be dropped on the floor between these two guards. + if !skip_placement && !self.color.is_identity() { + crate::color::apply_yuv(&self.color, gy, gu, gv); + } + let desc = if self.tone.is_some() { + TONE_MAPPED + } else { + self.desc + }; + (&gy[..], &gu[..], &gv[..], desc) } else { - self.desc + (y, u, v, self.desc) }; - (&gy[..], &gu[..], &gv[..], desc) - } else { - (y, u, v, self.desc) - }; if skip_placement { return Frame { index, @@ -1435,11 +1488,17 @@ impl Render { }; } let (y, u, v, width, height) = if transform_active { - let (py, pu, pv, w, h) = self - .canvas - .place_transformed(y, u, v, width, height, &self.transform); + let (py, pu, pv, w, h) = + self.canvas + .place_transformed(y, u, v, width, height, &self.transform); self.placed = (py, pu, pv); - (&self.placed.0[..], &self.placed.1[..], &self.placed.2[..], w, h) + ( + &self.placed.0[..], + &self.placed.1[..], + &self.placed.2[..], + w, + h, + ) } else { self.canvas.place(y, u, v, width, height) }; @@ -1465,10 +1524,100 @@ pub(crate) struct Still { pub(crate) y: Vec, pub(crate) u: Vec, pub(crate) v: Vec, + /// The picture as it is *shown*, which for a phone's portrait photo is not + /// the picture as it was stored: the turn its EXIF block asks for was made + /// in [`Still::open`] before these planes were written, exactly where the + /// video doors make a display matrix, so the pair every reader takes is + /// the displayed one ([`crate::demux::Rotation`]'s own contract). pub(crate) width: u32, pub(crate) height: u32, } +/// A still whose EXIF orientation is not a quarter turn: values 2, 4, 5 and 7 +/// are mirrorings, and this engine has no flip anywhere in its pipeline -- not +/// in [`crate::scale::rotate_i420_90s`], not in [`Render`], not in an export's +/// `place_picture`. Refused **by name** at the door, for +/// [`crate::demux::UnsupportedRotation`]'s reason: showing a mirrored photo the +/// wrong way round is a wrong picture rather than a missing feature, and +/// quietly treating a mirror as a turn is exactly the bug this door exists to +/// stop. The `Display` is what a user is refused by. +#[derive(Debug)] +pub struct UnsupportedStillOrientation { + /// The EXIF value the file states, which is what the sentence names: the + /// eight legal values are 1 (upright) through 8, and the four mirrorings + /// are the even-odd pairs. + pub exif: u8, +} + +impl std::fmt::Display for UnsupportedStillOrientation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "this picture's EXIF orientation is {}, which is a mirror and not a turn; only \ + upright, 90°, 180° and 270° can be straightened here", + self.exif + ) + } +} + +impl std::error::Error for UnsupportedStillOrientation {} + +impl UnsupportedStillOrientation { + /// Whether `error` is one of these, however deep in a `Box` it is -- + /// [`crate::demux::UnsupportedRotation::is_it`]'s twin. + pub fn is_it(error: &crate::Error) -> bool { + error.downcast_ref::().is_some() + } +} + +/// The quarter turns an EXIF orientation asks for, as the one +/// [`Rotation`] every other door in this engine already uses -- no second +/// shape mechanism for a still, so the same turn is made by the same code +/// that makes a video's display matrix turn. +/// +/// EXIF 1, 6, 8 and 3 are the four quarter turns; **2, 4, 5 and 7 are +/// mirrorings** and are refused ([`UnsupportedStillOrientation`]) rather than +/// approximated by the nearest rotation. A value the standard does not define +/// (0, or above 8) states no orientation this can read, and is likewise +/// refused rather than guessed at. +fn rotation_of_exif(orientation: image::metadata::Orientation) -> crate::Result { + use image::metadata::Orientation as O; + Ok(match orientation { + O::NoTransforms => Rotation::None, + O::Rotate90 => Rotation::Cw90, + O::Rotate180 => Rotation::Cw180, + O::Rotate270 => Rotation::Cw270, + // The `image` crate keeps the raw number alongside: an orientation it + // could not read is `NoTransforms`, and saying "0" for a mirror would + // be a claim rather than a reading. + mirrored => { + return Err(UnsupportedStillOrientation { + exif: mirrored.to_exif(), + } + .into()); + } + }) +} + +/// What turn `path` asks for, read off its **header** alone -- what a library +/// row says about a file it has not placed anywhere, and what +/// [`image_size`] needs to report the size the picture is shown at. +/// +/// Header-only on purpose: the whole file is not decoded, exactly as +/// [`image_size`] has always been. `into_decoder` parses the container and +/// stops there; the pixels are never touched. +pub fn image_orientation(path: &Path) -> crate::Result { + let mut decoder = image::ImageReader::open(path)? + .with_guessed_format()? + .into_decoder() + .map_err(|e| format!("{}: {e}", path.display()))?; + // The refusal is handed on **unchanged**, not folded into a sentence with + // the file's name: a `String` is not an error a caller can downcast, and + // `is_it` is how a front-end tells this refusal from any other failure. + // The path is not lost -- every caller that has one puts it in front. + rotation_of_exif(decoder.orientation()?) +} + impl Still { /// Decodes `path`. Refused by name for a picture that is not one /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project @@ -1484,12 +1633,41 @@ impl Still { /// lands as a rectangle. Upgrade path is keeping the alpha plane here and /// giving `scale::Composer` a blend over the lane below. pub(crate) fn open(path: &Path) -> crate::Result { - let reader = image::ImageReader::open(path)?.with_guessed_format()?; - let rgb = reader - .decode() + // The turn is read and made **here**, once, before a single pair of + // numbers leaves this function: `image`'s decoder keeps an EXIF + // orientation in its own field and applies nothing, so a portrait + // phone photo arrived as landscape planes and every consumer below -- + // the `Render`, the `VideoMeta`, `image_size` -- reported the shape the + // camera stored rather than the one it was shot at. This is the same + // step the video doors make, at the same place in the pipeline + // (before the grade, the canvas and the conversion all see the + // picture), and it uses the same [`Rotation`]. + let mut decoder = image::ImageReader::open(path)? + .with_guessed_format()? + .into_decoder() + .map_err(|e| format!("{}: {e}", path.display()))?; + // Unchanged for the reason `image_orientation` gives: a caller has to + // be able to downcast this refusal, and a sentence with the file's name + // in it is not one. + let rotation = rotation_of_exif(decoder.orientation()?)?; + let rgb = image::DynamicImage::from_decoder(decoder) .map_err(|e| format!("{}: {e}", path.display()))? .to_rgb8(); - let (width, height) = rgb.dimensions(); + let (coded_width, coded_height) = rgb.dimensions(); + // Turned here rather than left to each consumer, so there is exactly + // one place the turn is made and no consumer can be forgotten: the + // planes handed out below are the *shown* picture, so the `Render`, the + // `VideoMeta`, an export's `place_picture` and `image_size` all agree + // without any of them re-deriving it. A file that states no turn takes + // the branch by a bool and not one byte is copied. + let (rgb, width, height) = match rotation.is_none() { + true => (rgb, coded_width, coded_height), + false => { + let turned = turn_rgb(&rgb, rotation.steps()); + let (width, height) = turned.dimensions(); + (turned, width, height) + } + }; if !crate::is_resolution(width, height) { return Err(format!( "{} is {width}x{height}, which is not a picture this engine composes", @@ -1508,19 +1686,49 @@ impl Still { } /// The planes as an export's decoder hands them over, so a still and a - /// decoded picture are the same value to `export::run`. + /// decoded picture are the same value to `export::run` -- and, for a + /// turned still, the same value in the only sense that matters: the turn + /// is already in them, so an export places what the preview showed without + /// being told a second time. pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) { (&self.y, &self.u, &self.v, self.width, self.height) } } -/// How big the picture in `path` is, from its header alone -- what a library row -/// says about a file it has not placed anywhere. The whole file is not decoded. +/// `steps` quarter turns clockwise over a packed RGB8 picture -- the same +/// direction and the same count [`crate::scale::rotate_i420_90s`] takes, on the +/// still's own buffer rather than on its planes: a still is turned exactly once +/// in its whole life, so there is no steady-state cost to make the allocating +/// call the one that happens. +fn turn_rgb(rgb: &image::RgbImage, steps: u8) -> image::RgbImage { + match steps % 4 { + 1 => image::imageops::rotate90(rgb), + 2 => image::imageops::rotate180(rgb), + 3 => image::imageops::rotate270(rgb), + _ => rgb.clone(), + } +} + +/// How big the picture in `path` is as it is **shown**, from its header alone -- +/// what a library row says about a file it has not placed anywhere. The whole +/// file is not decoded. +/// +/// The turn is applied to the answer for the same reason +/// [`DecodeSession::open_still`]'s is: a portrait phone photo stores landscape +/// and says so in its EXIF block, and a row that answered 4000x3000 for a +/// picture that is shown 3000x4000 states the wrong shape on the one surface +/// that exists before anything places the file. Header-only still -- +/// `into_decoder` parses the container and stops. pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> { - Ok(image::ImageReader::open(path)? + let rotation = image_orientation(path)?; + let (width, height) = image::ImageReader::open(path)? .with_guessed_format()? .into_dimensions() - .map_err(|e| format!("{}: {e}", path.display()))?) + .map_err(|e| format!("{}: {e}", path.display()))?; + Ok(match rotation.swaps_axes() { + true => (height, width), + false => (width, height), + }) } /// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse @@ -1599,11 +1807,7 @@ const VIZ_STRAND_SAT_SHIFT: u32 = 40; const VIZ_STRAND_CHOSEN: u64 = 1 << 63; pub fn viz_materialize(paint: u64) -> u64 { - if paint == 0 { - VIZ_PAINT_AZURE - } else { - paint - } + if paint == 0 { VIZ_PAINT_AZURE } else { paint } } pub fn viz_ink_from_paint(paint: u64) -> (u8, u8, u8) { @@ -1638,7 +1842,11 @@ pub fn with_viz_paint_glow(paint: u64, n: u8) -> u64 { } pub fn viz_hue_ui(paint: u64) -> u8 { - if paint == 0 { 150 } else { (paint & 0xFF) as u8 } + if paint == 0 { + 150 + } else { + (paint & 0xFF) as u8 + } } pub fn viz_sat_ui(paint: u64) -> u8 { @@ -1688,9 +1896,10 @@ pub fn with_viz_paint_strand_sat(paint: u64, sat: u8) -> u64 { /// Drop the chosen strand colour: the dual half of a ring goes back to the /// automatic complement, and both strand bytes go with the flag. pub fn viz_strand_clear(paint: u64) -> u64 { - paint & !(VIZ_STRAND_CHOSEN - | (0xFF_u64 << VIZ_STRAND_HUE_SHIFT) - | (0xFF_u64 << VIZ_STRAND_SAT_SHIFT)) + paint + & !(VIZ_STRAND_CHOSEN + | (0xFF_u64 << VIZ_STRAND_HUE_SHIFT) + | (0xFF_u64 << VIZ_STRAND_SAT_SHIFT)) } /// `#RRGGBB` for an ink, at the same fixed value the painter draws at, so @@ -1837,8 +2046,7 @@ fn viz_stamp( if x < 0 || row < 0 || x >= w as i32 || row >= h as i32 { return; } - let lum = - (f32::from(bg_y) + (f32::from(ink_y) - f32::from(bg_y)) * fall.clamp(0.0, 1.0)) as u8; + let lum = (f32::from(bg_y) + (f32::from(ink_y) - f32::from(bg_y)) * fall.clamp(0.0, 1.0)) as u8; let idx = row as usize * w + x as usize; if lum > y[idx] { y[idx] = lum; @@ -1871,7 +2079,9 @@ fn viz_span( ) { let (a, b) = if top <= bot { (top, bot) } else { (bot, top) }; for row in a..=b { - viz_stamp(y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v); + viz_stamp( + y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v, + ); } } @@ -1935,7 +2145,22 @@ fn viz_line( let d2 = (ox * ox + oy * oy) as f32; (-0.45 * d2 / (g * g).max(1) as f32).exp() }; - viz_stamp(y, u, v, w, h, cw, ch, x0 + ox, y0 + oy, fall, bg_y, ink_y, ink_u, ink_v); + viz_stamp( + y, + u, + v, + w, + h, + cw, + ch, + x0 + ox, + y0 + oy, + fall, + bg_y, + ink_y, + ink_u, + ink_v, + ); } } if x0 == x1 && y0 == y1 { @@ -2034,7 +2259,14 @@ fn viz_chain( ink_v: u8, glow: u8, ) { - let VizScratch { pts, chain, rows, cand, hull, .. } = scratch; + let VizScratch { + pts, + chain, + rows, + cand, + hull, + .. + } = scratch; chain.clear(); for pair in pts.windows(2) { viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, chain); @@ -2047,7 +2279,9 @@ fn viz_chain( // full ink -- which is exactly what the row/by/band machinery below // works out, one sort later. for &(x, row) in chain.iter() { - viz_stamp(y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v); + viz_stamp( + y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v, + ); } return; } @@ -2173,7 +2407,9 @@ fn viz_chain( } else { (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp() }; - viz_stamp(y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v); + viz_stamp( + y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v, + ); } } } @@ -2197,7 +2433,15 @@ pub(crate) fn visualizer_i420( flags: u8, paint: u64, ) -> (Vec, Vec, Vec) { - visualizer_window_i420(scratch, &VizView::whole(peaks), t_secs, width, height, flags, paint) + visualizer_window_i420( + scratch, + &VizView::whole(peaks), + t_secs, + width, + height, + flags, + paint, + ) } /// The envelope a visualizer frame is painted from: the whole file, or one @@ -2404,12 +2648,36 @@ pub(crate) fn visualizer_window_i420( for dy in 1..=glow { let fall = 0.5 / dy as f32; viz_stamp( - &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row - dy, fall, bg_y, - ink_y, ink_u, ink_v, + &mut y, + &mut u, + &mut v, + w, + h, + cw, + ch, + col as i32, + row - dy, + fall, + bg_y, + ink_y, + ink_u, + ink_v, ); viz_stamp( - &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row + dy, fall, bg_y, - ink_y, ink_u, ink_v, + &mut y, + &mut u, + &mut v, + w, + h, + cw, + ch, + col as i32, + row + dy, + fall, + bg_y, + ink_y, + ink_u, + ink_v, ); } } @@ -2474,9 +2742,10 @@ pub(crate) fn visualizer_window_i420( VIZ_STYLE_WAVE => { scratch.pts.clear(); for col in 0..w { - scratch - .pts - .push((col as i32, (center - scratch.sig[col] * half).round() as i32)); + scratch.pts.push(( + col as i32, + (center - scratch.sig[col] * half).round() as i32, + )); } let glow = viz_glow_of(paint); if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) { @@ -2488,8 +2757,7 @@ pub(crate) fn visualizer_window_i420( } } else { viz_chain( - &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v, - glow, + &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v, glow, ); } } @@ -2507,12 +2775,36 @@ pub(crate) fn visualizer_window_i420( for dy in 1..=glow { let fall = 0.55 / dy as f32; viz_stamp( - &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, top - dy, fall, bg_y, - ink_y, ink_u, ink_v, + &mut y, + &mut u, + &mut v, + w, + h, + cw, + ch, + col as i32, + top - dy, + fall, + bg_y, + ink_y, + ink_u, + ink_v, ); viz_stamp( - &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, bot + dy, fall, bg_y, - ink_y, ink_u, ink_v, + &mut y, + &mut u, + &mut v, + w, + h, + cw, + ch, + col as i32, + bot + dy, + fall, + bg_y, + ink_y, + ink_u, + ink_v, ); } } @@ -2695,7 +2987,10 @@ mod tests { "deferred open returned in {returned:?}, first frame at {first_frame:?}; \ sync open returned in {sync_returned:?}" ); - assert_eq!(frame.index, 0, "the deferred worker starts where it is told"); + assert_eq!( + frame.index, 0, + "the deferred worker starts where it is told" + ); assert!( returned < Duration::from_millis(10), "the caller waited {returned:?} -- something is still being read \ @@ -2848,7 +3143,10 @@ mod tests { let w = 320u32; let h = 180u32; let (y, _u, _v) = visualizer_i420(&mut VizScratch::default(), &[], 0.0, w, h, 1, 0); - assert_eq!((y.len(), _u.len(), _v.len()), (320 * 180, 160 * 90, 160 * 90)); + assert_eq!( + (y.len(), _u.len(), _v.len()), + (320 * 180, 160 * 90, 160 * 90) + ); // The ink's top and bottom row for a given peaks slice: one unbroken // band, and where it sits. let band = |peaks: &[(f32, f32)]| { @@ -3059,10 +3357,14 @@ mod tests { *p = (-a.abs(), a.abs()); } let flags = 1u8; - let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0); + let (y, u, v) = + visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0); let ink = y.iter().filter(|&&p| p > 40).count(); assert!(ink > 200, "envelope missing: {ink}"); - assert!(ink < y.len() * 9 / 10, "solid frame, not an envelope: {ink}"); + assert!( + ink < y.len() * 9 / 10, + "solid frame, not an envelope: {ink}" + ); let mut blue = 0usize; for i in 0..u.len() { if u[i] > 145 && v[i] < 120 { @@ -3072,13 +3374,22 @@ mod tests { assert!(blue > 10, "default ink was not timeline blue: {blue}"); let ring = with_viz_style(flags, VIZ_STYLE_RING); - let (yr, _, _) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0); + let (yr, _, _) = + visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0); let ring_ink = yr.iter().filter(|&&p| p > 40).count(); assert!(ring_ink > 80, "ring missing: {ring_ink}"); assert!(ring_ink < ink, "ring should be a stroke, not a fill"); let hue_paint = with_viz_paint_hue(0, 40); - let (_, u2, v2) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 64, 32, flags, hue_paint); + let (_, u2, v2) = visualizer_i420( + &mut VizScratch::default(), + &peaks, + 1.0, + 64, + 32, + flags, + hue_paint, + ); let mut shifted = 0usize; for i in 0..u2.len() { if u2[i] < 120 && v2[i] > 130 { @@ -3175,7 +3486,15 @@ mod tests { } let ring = with_viz_style(1, VIZ_STYLE_RING); let auto = VIZ_PAINT_AZURE; - let (y0, u0, v0) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, auto); + let (y0, u0, v0) = visualizer_i420( + &mut VizScratch::default(), + &peaks, + 1.0, + 320, + 180, + ring, + auto, + ); // The automatic dual is half a wheel from the clip's hue at the // clip's own saturation; choosing exactly that colour changes @@ -3185,24 +3504,54 @@ mod tests { viz_sat_ui(auto), ); assert!(viz_strand_set(same)); - let (ys, us, vs) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, same); - assert_eq!(ys, y0, "the automatic complement, spelled out, is the same frame"); + let (ys, us, vs) = visualizer_i420( + &mut VizScratch::default(), + &peaks, + 1.0, + 320, + 180, + ring, + same, + ); + assert_eq!( + ys, y0, + "the automatic complement, spelled out, is the same frame" + ); assert_eq!(us, u0); assert_eq!(vs, v0); // A colour of its own repaints the dual strands in it. let red = with_viz_paint_strand_sat(with_viz_paint_strand_hue(auto, 0), 255); - let (_, u1, v1) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, red); - let red_px = (0..u1.len()).filter(|&i| u1[i] < 110 && v1[i] > 200).count(); - let auto_px = (0..u0.len()).filter(|&i| u0[i] < 110 && v0[i] > 200).count(); - assert!(red_px > 20, "the chosen colour did not reach the frame: {red_px}"); - assert_eq!(auto_px, 0, "the automatic ring already painted red: {auto_px}"); + let (_, u1, v1) = + visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, red); + let red_px = (0..u1.len()) + .filter(|&i| u1[i] < 110 && v1[i] > 200) + .count(); + let auto_px = (0..u0.len()) + .filter(|&i| u0[i] < 110 && v0[i] > 200) + .count(); + assert!( + red_px > 20, + "the chosen colour did not reach the frame: {red_px}" + ); + assert_eq!( + auto_px, 0, + "the automatic ring already painted red: {auto_px}" + ); // ...and the flag is what decides: strand bytes with it clear are // the unset picture, byte for byte. let stale = auto | (77u64 << 32) | (9u64 << 40); assert!(!viz_strand_set(stale)); - let (yt, ut, vt) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, stale); + let (yt, ut, vt) = visualizer_i420( + &mut VizScratch::default(), + &peaks, + 1.0, + 320, + 180, + ring, + stale, + ); assert_eq!(yt, y0, "an unset strand colour is the frame it always was"); assert_eq!(ut, u0); assert_eq!(vt, v0); @@ -3250,7 +3599,15 @@ mod tests { }; let flags = with_viz_style(1, style); let paint = with_viz_paint_glow(VIZ_PAINT_AZURE, glow); - let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 37.5, 1920, 1080, flags, paint); + let (y, u, v) = visualizer_i420( + &mut VizScratch::default(), + &peaks, + 37.5, + 1920, + 1080, + flags, + paint, + ); let mut hash = 0xcbf2_9ce4_8422_2325u64; for buf in [&y, &u, &v] { for &b in buf.iter() { @@ -3566,7 +3923,6 @@ fn run_av1( } } } - } /// Converts one decoded picture and queues it. `true` when the consumer went diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 562dbdf..1b9c0f0 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -62,8 +62,8 @@ use std::sync::{Arc, Mutex}; use std::thread; use ec_core::frame::VideoFrame; -use ec_core::registry::{CodecId, CodecParameters}; use ec_core::registry::Decoder as _; +use ec_core::registry::{CodecId, CodecParameters}; use ec_core::{Packet, TimeBase}; use ec_h264::{Encoder, EncoderConfig, H264Decoder, PictureView, Preset}; use ec_h265::encoder::{Encoder as HevcEncoder, EncoderConfig as HevcEncoderConfig, RateControl}; @@ -86,7 +86,7 @@ use crate::mux::{ AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, }; use crate::project::{Lane, LaneKind, Project, Rate}; -use crate::scale::{blend_i420, Composer}; +use crate::scale::{Composer, blend_i420}; use crate::subtitle::{Cue, SubtitleTrack}; use crate::tonemap::{self, ToneMapper}; use crate::transform::TransformParams; @@ -559,84 +559,84 @@ pub fn start( let part = PathBuf::from(part); let spawned = thread::Builder::new().name("export".into()).spawn(move || { let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - // Every file this export will read, named before a byte of one is. - // These are the project's own sources and can be nothing else: a - // stand-in ([`crate::proxy`]) is a substitution playback makes when it - // opens a span, and nothing here knows such a thing exists. Printed so - // that "the delivery came off the film itself" is a grep rather than a - // belief. - for source in project.sources() { - eprintln!("export source: {}", source.path.display()); - } - // The rename is the last step and the only one that publishes a file - // under the name the caller asked for; it stays on the same directory, - // so it is atomic. - // - // An emptied timeline is a legal project and an illegal file: no - // picture, no sound, and a muxer that is never created because no coded - // frame arrives. Refused by name here -- before the format is even - // looked at, so an mp4 and a WAV refuse in the same words -- rather than - // left to write a file of no frames that nothing opens. Every caller of - // `start` comes through this, the app's own door - // (`PlaybackSession::is_empty`) being only the first fence. - // - // An audio-only timeline is the other legal project no mp4 can be made - // of: every frame of it is a gap, so the file would be black picture - // over the sound -- minutes of encoding for a video of nothing. Refused - // by name, with the two formats that *are* that timeline, rather than - // written; the app says the same on the format row before a destination - // is even picked (`mp4_refusal`). - let written = match settings.format { - _ if project.timeline_frames() == 0 => { - Err("the timeline is empty: there is nothing to export".into()) + // Every file this export will read, named before a byte of one is. + // These are the project's own sources and can be nothing else: a + // stand-in ([`crate::proxy`]) is a substitution playback makes when it + // opens a span, and nothing here knows such a thing exists. Printed so + // that "the delivery came off the film itself" is a grep rather than a + // belief. + for source in project.sources() { + eprintln!("export source: {}", source.path.display()); } - format if format.has_video() && !has_picture(&project) => Err(format!( - "the timeline has no picture: {} would be black. Export WAV, \ + // The rename is the last step and the only one that publishes a file + // under the name the caller asked for; it stays on the same directory, + // so it is atomic. + // + // An emptied timeline is a legal project and an illegal file: no + // picture, no sound, and a muxer that is never created because no coded + // frame arrives. Refused by name here -- before the format is even + // looked at, so an mp4 and a WAV refuse in the same words -- rather than + // left to write a file of no frames that nothing opens. Every caller of + // `start` comes through this, the app's own door + // (`PlaybackSession::is_empty`) being only the first fence. + // + // An audio-only timeline is the other legal project no mp4 can be made + // of: every frame of it is a gap, so the file would be black picture + // over the sound -- minutes of encoding for a video of nothing. Refused + // by name, with the two formats that *are* that timeline, rather than + // written; the app says the same on the format row before a destination + // is even picked (`mp4_refusal`). + let written = match settings.format { + _ if project.timeline_frames() == 0 => { + Err("the timeline is empty: there is nothing to export".into()) + } + format if format.has_video() && !has_picture(&project) => Err(format!( + "the timeline has no picture: {} would be black. Export WAV, \ FLAC or MP3, which are the sound itself", - format.name() - ) - .into()), - format if format.has_video() => { - let first = run(&project, &meta, &part, &worker, &settings, sample_rate); - match first { - // The hardware encoder's *process* died under the driver - // ([`crate::hwproc`]) -- the editor is still here, and the - // file is still owed. Written again by the software encoder - // for this codec, from the first frame: the pictures the - // dead seat coded are not ones this one may continue from. - // - // Not where a person picked the GPU by name: that export - // refuses in words, the same answer [`hw_seat`] already - // gives a machine with no seat at all, rather than quietly - // spending an hour in an encoder nobody chose. - Err(e) - if crate::hwproc::is_lost(&e) - && settings.seat != EncoderSeat::Hardware => - { - eprintln!("export video: {e}; writing it again in software"); - let _ = std::fs::remove_file(&part); - // The bar is *not* put back to zero: the rerun writes - // it with `fetch_max` like everything else - // ([`Shared::progress`]), so it holds where the dead - // seat left it and moves again once the software - // encoder passes that mark. A person whose GPU has just - // died is the last one who should also watch the bar - // run backwards. - let mut software = settings.clone(); - software.seat = EncoderSeat::Software; - run(&project, &meta, &part, &worker, &software, sample_rate) + format.name() + ) + .into()), + format if format.has_video() => { + let first = run(&project, &meta, &part, &worker, &settings, sample_rate); + match first { + // The hardware encoder's *process* died under the driver + // ([`crate::hwproc`]) -- the editor is still here, and the + // file is still owed. Written again by the software encoder + // for this codec, from the first frame: the pictures the + // dead seat coded are not ones this one may continue from. + // + // Not where a person picked the GPU by name: that export + // refuses in words, the same answer [`hw_seat`] already + // gives a machine with no seat at all, rather than quietly + // spending an hour in an encoder nobody chose. + Err(e) + if crate::hwproc::is_lost(&e) + && settings.seat != EncoderSeat::Hardware => + { + eprintln!("export video: {e}; writing it again in software"); + let _ = std::fs::remove_file(&part); + // The bar is *not* put back to zero: the rerun writes + // it with `fetch_max` like everything else + // ([`Shared::progress`]), so it holds where the dead + // seat left it and moves again once the software + // encoder passes that mark. A person whose GPU has just + // died is the last one who should also watch the bar + // run backwards. + let mut software = settings.clone(); + software.seat = EncoderSeat::Software; + run(&project, &meta, &part, &worker, &software, sample_rate) + } + other => other, } - other => other, } + _ => run_audio(&project, &meta, &part, &worker, &settings, sample_rate), + }; + let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); + if result.is_err() { + // The muxer -- and with it the file handle -- died with `run`. + let _ = std::fs::remove_file(&part); } - _ => run_audio(&project, &meta, &part, &worker, &settings, sample_rate), - }; - let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); - if result.is_err() { - // The muxer -- and with it the file handle -- died with `run`. - let _ = std::fs::remove_file(&part); - } - settle(&worker, result); + settle(&worker, result); })); if let Err(payload) = caught { // The body above panicked before it could settle its own slot -- @@ -654,7 +654,10 @@ pub fn start( // a panic never reaches. Done inside this branch only -- a body // that *did* settle has already renamed or deleted the file. let _ = std::fs::remove_file(&part); - settle(&panic_worker, Err(format!("export worker panicked: {message}").into())); + settle( + &panic_worker, + Err(format!("export worker panicked: {message}").into()), + ); } } }); @@ -710,10 +713,12 @@ fn mastered(project: &Project) -> bool { /// packet copy carries neither an equalizer nor a fade. An mp4 whose timeline /// has one is decoded and re-encoded so the fade actually reaches the file. fn faded(project: &Project) -> bool { - project - .audio_lanes() - .into_iter() - .any(|lane| project.lane(lane).iter().any(|c| c.fade_in > 0 || c.fade_out > 0)) + project.audio_lanes().into_iter().any(|lane| { + project + .lane(lane) + .iter() + .any(|c| c.fade_in > 0 || c.fade_out > 0) + }) } /// The bitrate an export codes at: the caller's number clamped into what an @@ -1439,7 +1444,10 @@ fn planned_lanes(project: &Project, format: Format, lanes: &[Lane]) -> String { // Drawn over the picture, written into no file -- the same sentence // a picked track gets, because it is the track and not the lane that // cannot be carried. - dropped.push(format!("{label} {} — pictures; drawn, not written", t.label)); + dropped.push(format!( + "{label} {} — pictures; drawn, not written", + t.label + )); } else if first.start >= end { dropped.push(format!("{label} {name}— past the last picture")); } else { @@ -1480,12 +1488,15 @@ fn planned_lanes(project: &Project, format: Format, lanes: &[Lane]) -> String { /// Costs that open (~100 ms here): ask it off a render thread and keep the /// answer until the format, the resolution or the bitrate changes. pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> { - settings.format.has_video().then(|| match hw_seat(meta, settings) { - Ok(hw) => video_label(settings.format, hw.is_some()), - // The seat the settings demand and this machine has not: the very - // refusal [`start`] would settle with, said on the card instead. - Err(_) => NO_HW_SEAT, - }) + settings + .format + .has_video() + .then(|| match hw_seat(meta, settings) { + Ok(hw) => video_label(settings.format, hw.is_some()), + // The seat the settings demand and this machine has not: the very + // refusal [`start`] would settle with, said on the card instead. + Err(_) => NO_HW_SEAT, + }) } /// What [`start`] would open for *this* timeline: the picture's seat -- or the @@ -1781,7 +1792,11 @@ struct CopyRegion { /// clip -- which the same format would carry exactly if the edit let it, so /// those six [`CopyPlan::of`] gates are named together rather than picked /// apart into six different sentences. -pub fn exact_refusal(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option { +pub fn exact_refusal( + project: &Project, + meta: &VideoMeta, + settings: &ExportSettings, +) -> Option { if !settings.exact || CopyPlan::of(project, meta, settings).is_some() { return None; } @@ -2134,9 +2149,9 @@ fn encode_audio( let out_frames = range.map_or(project.media_frames(), |(s, e)| { e.min(project.media_frames()).saturating_sub(s) }); - let total = - (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() as usize - * channels; + let total = (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() + as usize + * channels; let mut samples: Vec = Vec::with_capacity(total); for chunk in chunks { // The only place a cancelled export can be answered before the whole @@ -2455,9 +2470,15 @@ fn opus_fidelity( for w in 0..FIDELITY_WINDOWS { let at = w * step; let from = at.saturating_sub(FIDELITY_WARMUP); - let Some(fidelity) = - window_fidelity(packets, samples, pre_skip, channels, from, at, at + FIDELITY_WINDOW) - else { + let Some(fidelity) = window_fidelity( + packets, + samples, + pre_skip, + channels, + from, + at, + at + FIDELITY_WINDOW, + ) else { continue; // silence: nothing to correlate, and not a failure }; scores.push(fidelity); @@ -2646,9 +2667,9 @@ fn run( // The range's own length where one is marked, the media's otherwise -- // `export_spans` walks the same window, so `done` ends on this `total` // exactly as it always did. - let total = settings - .range - .map_or(project.media_frames(), |(s, e)| e.min(project.media_frames()).saturating_sub(s)); + let total = settings.range.map_or(project.media_frames(), |(s, e)| { + e.min(project.media_frames()).saturating_sub(s) + }); // The two preview switches are the H.264 mp4 pair's alone. Only that // container carries a colour of its own back out ([`write_video`] tags it // there), so asking any other for a source-space file would write pictures @@ -2695,12 +2716,8 @@ fn run( // of the two. On this project's own film that is 168 s of AC-3 that no // longer stands in front of 733 s of hardware H.264. let audio_job = { - let (project, meta, settings, shared) = ( - project.clone(), - *meta, - settings.clone(), - Arc::clone(shared), - ); + let (project, meta, settings, shared) = + (project.clone(), *meta, settings.clone(), Arc::clone(shared)); thread::Builder::new() .name("export-audio".into()) .spawn(move || { @@ -2843,7 +2860,15 @@ fn run( // it replaced -- and the sound says whether it was copied or encoded, which // only `copy_audio` knows and, on the overlapped path, does not know yet. let seat = encoder.label(); - publish_seats(shared, seat, project, settings, sound, opus, audio_job.running()); + publish_seats( + shared, + seat, + project, + settings, + sound, + opus, + audio_job.running(), + ); // When the picture started, so the stage line below can say where under it // the sound landed -- the one number that says whether the two passes // really overlapped, in the same voice as `encode_audio`'s own timers. @@ -2882,9 +2907,8 @@ fn run( // A's pixels on the CPU, so a dissolving span never asks for a GPU // buffer, not even outside its own window. let dissolve = dissolve_window(project, &span); - let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) = - match span.from - { + let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) = match span.from + { Some((source, in_frame)) => { let entry = sources .get(source) @@ -2934,7 +2958,15 @@ fn run( } else { ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)? }; - (Some(pictures), rate, in_frame, Some(color), mapper, rotation, pixel_aspect) + ( + Some(pictures), + rate, + in_frame, + Some(color), + mapper, + rotation, + pixel_aspect, + ) } // A gap's black is 16/128/128, which is black in every matrix here // and on every curve: nothing to remap and nothing to tone-map, @@ -2993,52 +3025,54 @@ fn run( // files together for exactly the frames the tail below blends, and // nothing else in this span ever touches it. let mut b = dissolve - .map(|(b_source, b_in_frame, window, b_start)| -> crate::Result<_> { - let entry = sources.get(b_source).ok_or_else(|| { - format!("clip names source {b_source} of {}", sources.len()) - })?; - let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source]; - let b_mapper = tone[b_source].as_ref(); - let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix); - Ok(Dissolve { - window, - tail_start: span.len - window, - decoder: if crate::is_audio(&entry.path) - || project.composite_visualizer_at(b_start) & 1 != 0 - { - ClipDecoder::visualizer( - &entry.path, - entry.audio_stream, - b_rate.source_at(b_in_frame), + .map( + |(b_source, b_in_frame, window, b_start)| -> crate::Result<_> { + let entry = sources.get(b_source).ok_or_else(|| { + format!("clip names source {b_source} of {}", sources.len()) + })?; + let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source]; + let b_mapper = tone[b_source].as_ref(); + let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix); + Ok(Dissolve { + window, + tail_start: span.len - window, + decoder: if crate::is_audio(&entry.path) + || project.composite_visualizer_at(b_start) & 1 != 0 + { + ClipDecoder::visualizer( + &entry.path, + entry.audio_stream, + b_rate.source_at(b_in_frame), + meta.width, + meta.height, + meta.frame_rate, + project.composite_visualizer_at(b_start), + project.composite_viz_paint_at(b_start), + )? + } else { + ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)? + }, + mapper: b_mapper, + remap: b_remap, + grade: project.composite_color_at(b_start).copied(), + transform: project + .composite_transform_at(b_start) + .copied() + .unwrap_or_default(), + rotation: b_rotation, + pixel_aspect: b_pixel_aspect, + canvas: Composer::new( meta.width, meta.height, - meta.frame_rate, - project.composite_visualizer_at(b_start), - project.composite_viz_paint_at(b_start), - )? - } else { - ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)? - }, - mapper: b_mapper, - remap: b_remap, - grade: project.composite_color_at(b_start).copied(), - transform: project - .composite_transform_at(b_start) - .copied() - .unwrap_or_default(), - rotation: b_rotation, - pixel_aspect: b_pixel_aspect, - canvas: Composer::new( - meta.width, - meta.height, - project.composite_fit_at(b_start), - ), - rotated: (Vec::new(), Vec::new(), Vec::new()), - stretched: (Vec::new(), Vec::new(), Vec::new()), - graded: (Vec::new(), Vec::new(), Vec::new()), - transformed: (Vec::new(), Vec::new(), Vec::new()), - }) - }) + project.composite_fit_at(b_start), + ), + rotated: (Vec::new(), Vec::new(), Vec::new()), + stretched: (Vec::new(), Vec::new(), Vec::new()), + graded: (Vec::new(), Vec::new(), Vec::new()), + transformed: (Vec::new(), Vec::new(), Vec::new()), + }) + }, + ) .transpose()?; // Timeline frames, taken a *source* frame at a time: at a rate other // than real time the two are not the same count, and the span says which @@ -3175,9 +3209,21 @@ fn run( } Some(Frame::Pixels(by, bu, bv, bw, bh)) => { let (by, bu, bv, _, _) = place_picture( - by, bu, bv, bw, bh, d.rotation, d.pixel_aspect, d.grade, - d.transform, d.remap, d.mapper, &mut d.rotated, - &mut d.stretched, &mut d.graded, &mut d.transformed, + by, + bu, + bv, + bw, + bh, + d.rotation, + d.pixel_aspect, + d.grade, + d.transform, + d.remap, + d.mapper, + &mut d.rotated, + &mut d.stretched, + &mut d.graded, + &mut d.transformed, &mut d.canvas, ); let idx_in_window = done_here + r - d.tail_start; @@ -3358,7 +3404,9 @@ fn place_picture<'a>( display_width.div_ceil(2) as usize, height.div_ceil(2) as usize, ); - stretched.0.resize(display_width as usize * height as usize, 0); + stretched + .0 + .resize(display_width as usize * height as usize, 0); stretched.1.resize(dcw * dch, 0); stretched.2.resize(dcw * dch, 0); crate::scale::scale_i420( @@ -3437,7 +3485,13 @@ fn place_picture<'a>( } else { let (py, pu, pv, w, h) = canvas.place_transformed(y, u, v, width, height, &transform); *transformed = (py, pu, pv); - (&transformed.0[..], &transformed.1[..], &transformed.2[..], w, h) + ( + &transformed.0[..], + &transformed.1[..], + &transformed.2[..], + w, + h, + ) } } @@ -3482,7 +3536,10 @@ fn source_rate( // `decode::rgb_to_i420` is the one matrix that turns its pixels into // planes. A song has no picture and the answer is never read. Neither // has a display matrix to be turned by, nor an aspect to be widened - // by: both are authored square. + // by: both are authored square. A still's *EXIF* turn is not in this + // arm either, and for a better reason -- `decode::Still::open` already + // made it before the planes were written, so `place_picture` is handed + // the picture the preview showed and must not be told to turn it again. return ( Rate::REAL_TIME, ColorDescription::default(), @@ -3582,9 +3639,8 @@ fn run_audio( }; // The picture path's line, for a file that is sound alone: there is sound // by the line above, so this names the encoder writing it. - *shared.encoders.lock().unwrap() = Some( - audio_label(project, format, true, None, settings.range.is_some()).to_string(), - ); + *shared.encoders.lock().unwrap() = + Some(audio_label(project, format, true, None, settings.range.is_some()).to_string()); let channels = usize::from(audio.channels); let out_frames = settings.range.map_or(project.media_frames(), |(s, e)| { e.min(project.media_frames()).saturating_sub(s) @@ -4404,9 +4460,7 @@ impl Enc { cfg.timing = Some((fps_den, fps_num)); cfg.video_signal_type = Some(video_signal_type(meta.height)); cfg.threads = per_lane; - lanes.push( - HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?, - ); + lanes.push(HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?); } Ok(Self::Hevc(HevcEnc { pending: Vec::new(), @@ -4467,7 +4521,9 @@ impl Enc { // them is a sync point -- said as a constant rather than parsed back // out of the bitstream, because it is this encoder's configuration // and not a driver's choice. - Self::HevcHw(hw) => Ok(hw.encode(y, u, v, width, height, true)?.map(|au| (au, true))), + Self::HevcHw(hw) => Ok(hw + .encode(y, u, v, width, height, true)? + .map(|au| (au, true))), Self::Hevc(hevc) => { // The display-size planes are kept as they came: `ec-h265` // pads to its own coded grid and crops back through the SPS @@ -4858,7 +4914,11 @@ impl ClipDecoder { .ok() .flatten() .unwrap_or_default(); - let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 }; + let fps = if fps.is_finite() && fps > 0.0 { + fps + } else { + 30.0 + }; Ok(Self::Visualizer { peaks, width, @@ -5124,9 +5184,7 @@ impl SwDecoder { // either answer means go back for the next access unit. Err(e) if e.is_eof() && self.flushed => return Ok(false), Err(e) if e.is_need_more() || e.is_eof() => {} - Err(e) => { - return Err(format!("decode at picture {}: {e}", self.index).into()) - } + Err(e) => return Err(format!("decode at picture {}: {e}", self.index).into()), } } } @@ -5655,7 +5713,11 @@ mod tests { // 1280 * 720 * 30 * 0.1 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); assert_eq!(bitrate_for(&meta(320, 240, 30.0)), 230_400, "tiny"); - assert_eq!(bitrate_for(&meta(160, 120, 15.0)), MIN_BITRATE, "tinier floors"); + assert_eq!( + bitrate_for(&meta(160, 120, 15.0)), + MIN_BITRATE, + "tinier floors" + ); assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge"); // A rate somebody typed goes through untouched to its own ceiling, which // is above where the derived one stops: the card offers 50 Mbps, and a @@ -5687,7 +5749,11 @@ mod tests { fn a_fade_forces_the_audio_to_be_re_encoded() { let mut project = Project::single("/nonexistent/film.mp4", 90); assert!(!forces_encode(&project, false), "flat, so a copy is fine"); - assert!(project.set_fade_in(crate::project::Lane::new(crate::project::LaneKind::Audio, 0), 0, 15)); + assert!(project.set_fade_in( + crate::project::Lane::new(crate::project::LaneKind::Audio, 0), + 0, + 15 + )); assert!( forces_encode(&project, false), "a fade-in on the only clip must force a re-encode" @@ -5796,7 +5862,11 @@ mod tests { /// B, and the window itself never quite repeats a hard cut's own instant. #[test] fn dissolve_weight_ramps_strictly_between_zero_and_one() { - assert_eq!(dissolve_weight(0, 1), 0.5, "a one-frame window is the midpoint"); + assert_eq!( + dissolve_weight(0, 1), + 0.5, + "a one-frame window is the midpoint" + ); assert_eq!(dissolve_weight(0, 4), 0.2); assert_eq!(dissolve_weight(1, 4), 0.4); assert_eq!(dissolve_weight(2, 4), 0.6); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 40356d5..199a270 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -15,6 +15,7 @@ pub mod export; pub mod hw; pub mod hwproc; pub mod limiter; +pub(crate) mod map; pub mod mux; pub mod playback; pub mod project; @@ -23,11 +24,10 @@ pub mod real_library; pub mod scale; pub mod scratch; pub mod silence; +pub(crate) mod stretch; pub mod subtitle; -pub(crate) mod map; #[cfg(test)] mod sweep; -pub(crate) mod stretch; pub mod tonemap; pub mod transform; pub mod waveform; @@ -36,7 +36,9 @@ pub use audio::{ AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession, StreamInfo, }; pub use clock::PlaybackClock; -pub use decode::{DecodeSession, Frame, image_size}; +pub use decode::{ + DecodeSession, Frame, UnsupportedStillOrientation, image_orientation, image_size, +}; pub use demux::{Codec, MediaBitrate, Rotation, UnsupportedRotation, VideoMeta, probe_bitrate}; pub use export::ExportHandle; pub use mux::{AudioParams, Mp4Muxer, VideoParams}; @@ -72,7 +74,17 @@ pub fn is_audio(path: &std::path::Path) -> bool { path.extension().and_then(|e| e.to_str()).is_some_and(|e| { matches!( e.to_ascii_lowercase().as_str(), - "mp3" | "mpeg" | "mpg" | "wav" | "flac" | "ogg" | "oga" | "opus" | "mka" | "m4a" | "aac" + "mp3" + | "mpeg" + | "mpg" + | "wav" + | "flac" + | "ogg" + | "oga" + | "opus" + | "mka" + | "m4a" + | "aac" ) }) } @@ -120,18 +132,8 @@ mod tests { #[test] fn is_audio_admits_the_containers_the_decoder_reads() { for name in [ - "song.mp3", - "a.WAV", - "b.flac", - "c.ogg", - "d.oga", - "e.m4a", - "f.aac", - "g.opus", - "h.OPUS", - "i.mka", - "j.MPEG", - "k.mpg", + "song.mp3", "a.WAV", "b.flac", "c.ogg", "d.oga", "e.m4a", "f.aac", "g.opus", "h.OPUS", + "i.mka", "j.MPEG", "k.mpg", ] { assert!(super::is_audio(Path::new(name)), "{name}"); } diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 338db52..3df09d8 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -26,8 +26,9 @@ use crate::colorspace::{ColorDescription, ContentLight}; use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta}; use crate::eq::EqParams; -use crate::project::{ProjectSettings, - Clip, Edge, GapSweep, Lane, LaneKind, Project, Rate, Source, Span, Speed, SubClip, +use crate::project::{ + Clip, Edge, GapSweep, Lane, LaneKind, Project, ProjectSettings, Rate, Source, Span, Speed, + SubClip, }; use crate::scale::{Composer, FitPolicy}; use crate::transform::TransformParams; @@ -638,7 +639,9 @@ impl PlaybackSession { // hands it back out. The same trade the audio header cache above this // makes -- a second container open, paid once at open rather than never // -- since nothing here decodes a single picture. - let content_light = Demuxer::open(&path).map(|(_, d)| d.light()).unwrap_or_default(); + let content_light = Demuxer::open(&path) + .map(|(_, d)| d.light()) + .unwrap_or_default(); Ok(Self { meta, content_light, @@ -831,6 +834,10 @@ impl PlaybackSession { frame_count: image_frames(IMAGE_ONLY_RATE), codec: Codec::H264, color: ColorDescription::default(), + // `Rotation::None` is honest, not a shrug: a still's own turn was + // made in `Still::open`, before these planes were written, so the + // pair below is already the displayed one and there is nothing left + // for a consumer to make. rotation: Rotation::None, // No container said anything about these: the picture this engine // decoded itself is square pixels at the size it was decoded at. @@ -980,7 +987,9 @@ impl PlaybackSession { let content_light = if crate::is_audio(&first.path) || crate::is_image(&first.path) { ContentLight::default() } else { - Demuxer::open(&first.path).map(|(_, d)| d.light()).unwrap_or_default() + Demuxer::open(&first.path) + .map(|(_, d)| d.light()) + .unwrap_or_default() }; // The extension's word, corrected below the moment the header disagrees // with it (`NoVideoTrack`, the same fallback `open_stream` takes): every @@ -1001,11 +1010,11 @@ impl PlaybackSession { codec: Codec::H264, color: ColorDescription::default(), rotation: Rotation::None, - // No container said anything about these: the canvas this engine drew - // itself is square pixels at the size it was drawn at. - coded_width: width, - coded_height: height, - pixel_aspect: crate::demux::PixelAspect::SQUARE, + // No container said anything about these: the canvas this engine drew + // itself is square pixels at the size it was drawn at. + coded_width: width, + coded_height: height, + pixel_aspect: crate::demux::PixelAspect::SQUARE, }; (meta, DecodeSession::open_black(width, height, 1)) } @@ -1023,6 +1032,9 @@ impl PlaybackSession { frame_count: image_frames(frame_rate), codec: Codec::H264, color: ColorDescription::default(), + // `Rotation::None` is honest, not a shrug: `Still::open` + // made the file's own turn before these planes were + // written, so the pair below is already the displayed one. rotation: Rotation::None, // No container said anything about these: the picture this // engine decoded itself is square pixels at its own size. @@ -1071,11 +1083,11 @@ impl PlaybackSession { codec: Codec::H264, color: ColorDescription::default(), rotation: Rotation::None, - // No container said anything about these: the canvas this engine drew - // itself is square pixels at the size it was drawn at. - coded_width: width, - coded_height: height, - pixel_aspect: crate::demux::PixelAspect::SQUARE, + // No container said anything about these: the canvas this engine drew + // itself is square pixels at the size it was drawn at. + coded_width: width, + coded_height: height, + pixel_aspect: crate::demux::PixelAspect::SQUARE, }; (meta, DecodeSession::open_black(width, height, 1)) } @@ -1207,24 +1219,24 @@ impl PlaybackSession { let subtitles = crate::subtitle::open_all(&doc.subtitles); let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)? - .with_mix(&doc.gains, doc.limiter) - .with_tone(doc.tone) - // The palette before what is placed on it: a caption names a row of - // it, and [`Project::with_subs`] refuses one naming a row that is - // not there. - .with_subtitles(subtitles) - .with_subs(doc.subs)? - // The header a load puts back: the canvas and rate above, which a - // save's own `resolution`/`fps` lines may have moved off the - // scaffold's, and the switches the literal below carries -- handed - // in here because they are the project's own and a door that moved - // one after this would snapshot whatever copy it holds, which until - // this line is the placeholder's. No undo step for - // [`Project::with_mix`]'s reason: a project that arrived one `z` - // from a state it was never in is a project whose first undo is a - // surprise. - .with_canvas(meta.width, meta.height, meta.frame_rate) - .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate); + .with_mix(&doc.gains, doc.limiter) + .with_tone(doc.tone) + // The palette before what is placed on it: a caption names a row of + // it, and [`Project::with_subs`] refuses one naming a row that is + // not there. + .with_subtitles(subtitles) + .with_subs(doc.subs)? + // The header a load puts back: the canvas and rate above, which a + // save's own `resolution`/`fps` lines may have moved off the + // scaffold's, and the switches the literal below carries -- handed + // in here because they are the project's own and a door that moved + // one after this would snapshot whatever copy it holds, which until + // this line is the placeholder's. No undo step for + // [`Project::with_mix`]'s reason: a project that arrived one `z` + // from a state it was never in is a project whose first undo is a + // surprise. + .with_canvas(meta.width, meta.height, meta.frame_rate) + .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate); let span = project.composite_span_at(0); // Last, because it is the one thing here that cannot be taken back: the // feeder thread outlives the `Audio` value (it holds its own clones) and @@ -1248,7 +1260,11 @@ impl PlaybackSession { // source's silence is not worth reporting over an earlier one's). let (audio, audio_disabled) = { let mut opened = (None, None); - for source in project.sources().iter().filter(|s| !crate::is_image(&s.path)) { + for source in project + .sources() + .iter() + .filter(|s| !crate::is_image(&s.path)) + { opened = open_audio(&source.path, source.audio_stream); if opened.0.is_some() { break; @@ -1713,8 +1729,10 @@ impl PlaybackSession { }; let now = secs_to_frame(self.clock.now(), self.meta.frame_rate); let offset = now.saturating_sub(span.start).min(span.len); - self.worker - .playhead(self.span_rate.source_at(in_frame + span.speed.source_at(offset))); + self.worker.playhead( + self.span_rate + .source_at(in_frame + span.speed.source_at(offset)), + ); } /// Installs `replacement` as the decode worker, parking the outgoing one in @@ -1908,11 +1926,7 @@ impl PlaybackSession { .composite_transform_at(start) .copied() .unwrap_or_default(), - Composer::new( - canvas_w, - canvas_h, - self.project.composite_fit_at(start), - ), + Composer::new(canvas_w, canvas_h, self.project.composite_fit_at(start)), ) .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}")) } @@ -1941,17 +1955,11 @@ impl PlaybackSession { .composite_transform_at(start) .copied() .unwrap_or_default(), - Composer::new( - canvas_w, - canvas_h, - self.project.composite_fit_at(start), - ), + Composer::new(canvas_w, canvas_h, self.project.composite_fit_at(start)), self.project.composite_visualizer_at(start), self.project.composite_viz_paint_at(start), ) - .inspect_err(|e| { - eprintln!("timeline frame {start}: visualizer open failed: {e}") - }) + .inspect_err(|e| eprintln!("timeline frame {start}: visualizer open failed: {e}")) } Some(Span { start, @@ -2119,11 +2127,7 @@ impl PlaybackSession { .composite_transform_at(b_start) .copied() .unwrap_or_default(); - let canvas = Composer::new( - canvas_w, - canvas_h, - self.project.composite_fit_at(b_start), - ); + let canvas = Composer::new(canvas_w, canvas_h, self.project.composite_fit_at(b_start)); let tone = self.project.tone(); let stream = DecodeSession::open_worker_deferred( &path, @@ -2301,7 +2305,9 @@ impl PlaybackSession { /// changes only the words, which are drawn over whatever is decoded. pub fn trim_sub(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> crate::Result<()> { let grouped = self.caption_grouped_with_clips(lane, idx); - let trimmed = self.project.trim_sub(lane, idx, edge, to, self.meta.frame_rate); + let trimmed = self + .project + .trim_sub(lane, idx, edge, to, self.meta.frame_rate); if trimmed.is_ok() && grouped { self.invalidate(Dirty::Both); } @@ -2312,7 +2318,8 @@ impl PlaybackSession { /// ([`Project::trim_sub_room`]) -- what a front-end drawing the box during /// a drag asks, at this timeline's rate. pub fn trim_sub_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> { - self.project.trim_sub_room(lane, idx, edge, self.meta.frame_rate) + self.project + .trim_sub_room(lane, idx, edge, self.meta.frame_rate) } /// Takes one placement off a subtitle lane, leaving a gap @@ -2390,7 +2397,11 @@ impl PlaybackSession { // one this dispatch needs; a caption carries a link at all only once // grouped (`place_sub` always starts one at `None`), so that alone is // "this delete ripples more than its own lane". - match self.sub_lane(lane).get(idx).is_some_and(|s| s.link.is_some()) { + match self + .sub_lane(lane) + .get(idx) + .is_some_and(|s| s.link.is_some()) + { true => self.edit(Dirty::Both, |p| p.delete_sub_in(lane, idx)), // A caption in no group is the plain lift that touches nothing // else: no reseek owed. @@ -2555,7 +2566,9 @@ impl PlaybackSession { to: Lane, start: u32, ) -> bool { - self.edit(Dirty::Both, |p| p.move_selection(picks, from, idx, to, start)) + self.edit(Dirty::Both, |p| { + p.move_selection(picks, from, idx, to, start) + }) } /// Drags one end of that clip to timeline frame `to`, changing how much of @@ -3267,8 +3280,8 @@ impl PlaybackSession { // end is an append, never a clip with black in front of it. The frame // itself is honoured in [`Project::paste`], because a *drop* names a // place on the bed and means it. - let at = secs_to_frame(timeline_secs, self.meta.frame_rate) - .min(self.project.timeline_frames()); + let at = + secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames()); self.edit(Dirty::Both, |p| p.paste(at, clip)) } @@ -3277,8 +3290,8 @@ impl PlaybackSession { /// past the last frame lands there rather than carrying black in front of /// it, exactly as a lone clip's paste does. pub fn paste_set_at(&mut self, timeline_secs: f64, items: &[(Lane, Clip)]) -> bool { - let at = secs_to_frame(timeline_secs, self.meta.frame_rate) - .min(self.project.timeline_frames()); + let at = + secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames()); self.edit(Dirty::Both, |p| p.paste_set(at, items)) } @@ -4828,8 +4841,8 @@ fn blend_bgra(a: &[u8], b: &[u8], t: f32) -> Vec { #[cfg(test)] mod tests { use super::{ - Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of, blend_bgra, secs_to_frame, - AUDIO_LOST, + AUDIO_LOST, Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of, + blend_bgra, secs_to_frame, }; use std::path::PathBuf; use std::sync::atomic::Ordering; @@ -4874,7 +4887,12 @@ mod tests { "a dead output went to wall time without a word" ); assert!( - session.audio.as_ref().expect("audio").died.load(Ordering::Acquire), + session + .audio + .as_ref() + .expect("audio") + .died + .load(Ordering::Acquire), "a tick opened the output again inside the cooldown" ); assert!( @@ -4900,7 +4918,12 @@ mod tests { "playing after a dead output fed nothing: the session cannot come back" ); assert!( - !session.audio.as_ref().expect("audio").died.load(Ordering::Acquire), + !session + .audio + .as_ref() + .expect("audio") + .died + .load(Ordering::Acquire), "the death flag stood after the output was replaced" ); assert_eq!( @@ -4941,7 +4964,11 @@ mod tests { std::thread::sleep(std::time::Duration::from_millis(5)); } let frame = frame.unwrap_or_else(|| panic!("no frame from a {w}x{h} canvas")); - assert_eq!((frame.width, frame.height), (w, h), "a frame at the canvas's own size"); + assert_eq!( + (frame.width, frame.height), + (w, h), + "a frame at the canvas's own size" + ); } } @@ -5026,18 +5053,27 @@ mod tests { let file = asset("test_av.mp4"); let sources = [(file, 0)]; let segs = [(Some(0), 0., 1.)]; - let derived = crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], None) - .expect("open the fixture") - .expect("the fixture has sound") - .0 - .sample_rate; - let picked = - crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], Some(32000)) + let derived = + crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], None) .expect("open the fixture") .expect("the fixture has sound") .0 .sample_rate; - assert_ne!(derived, 32000, "a fixture at the picked rate proves nothing"); + let picked = crate::AudioSession::open_multi_streams_speed_at( + &sources, + &segs, + &[], + &[], + Some(32000), + ) + .expect("open the fixture") + .expect("the fixture has sound") + .0 + .sample_rate; + assert_ne!( + derived, 32000, + "a fixture at the picked rate proves nothing" + ); assert_eq!(picked, 32000); } @@ -5099,7 +5135,8 @@ mod tests { "an import must not move the project's own canvas size" ); assert_eq!( - session.meta().frame_rate, picked_fps, + session.meta().frame_rate, + picked_fps, "an import must not move the project's own rate" ); } @@ -5216,9 +5253,11 @@ mod tests { let zero = PlaybackSession::open_with_audio_stream(&multi, 0).expect("stream 0 opens"); let one = PlaybackSession::open_with_audio_stream(&multi, 1).expect("stream 1 opens"); let default = PlaybackSession::open(&multi).expect("default open"); - let (Some(a0), Some(a1), Some(ad)) = - (zero.audio.as_ref(), one.audio.as_ref(), default.audio.as_ref()) - else { + let (Some(a0), Some(a1), Some(ad)) = ( + zero.audio.as_ref(), + one.audio.as_ref(), + default.audio.as_ref(), + ) else { // No audio device on this machine: nothing further to check -- // the device is the machine's business, not this door's. return; @@ -5226,7 +5265,10 @@ mod tests { assert_eq!(a0.channels, 2, "stream 0 is the stereo pair"); assert_eq!(a1.channels, 1, "stream 1 is the mono track"); assert_ne!(a0.channels, a1.channels, "the two streams must differ"); - assert_eq!(ad.channels, a0.channels, "open() still defaults to stream 0"); + assert_eq!( + ad.channels, a0.channels, + "open() still defaults to stream 0" + ); } /// The bug this regression pins: a preview paused (or scrubbed) to a @@ -5260,7 +5302,10 @@ mod tests { let fps = on.meta().frame_rate; let clip0_len = on.lane_clips(Lane::V1)[0].len(); - assert!(clip0_len > window, "the fixture needs to outlast the window"); + assert!( + clip0_len > window, + "the fixture needs to outlast the window" + ); let mid_of_window = clip0_len - window / 2; let t = f64::from(mid_of_window) / fps; @@ -5276,7 +5321,10 @@ mod tests { if let Some(f) = s.try_frame() { return f; } - assert!(std::time::Instant::now() < deadline, "no frame within 20s of the seek"); + assert!( + std::time::Instant::now() < deadline, + "no frame within 20s of the seek" + ); std::thread::sleep(std::time::Duration::from_millis(10)); } }; @@ -5337,11 +5385,21 @@ mod tests { scale: 1.2, ..Default::default() }; - assert!(s.set_transform_live(clip.0, clip.1, Some(params)), "the edit took"); + assert!( + s.set_transform_live(clip.0, clip.1, Some(params)), + "the edit took" + ); let next = poll(&mut s); - assert_eq!(before, s.restarts(), "a live transform edit must reuse the worker"); - assert_eq!(next.index, first.index, "paused: same timeline position before and after"); + assert_eq!( + before, + s.restarts(), + "a live transform edit must reuse the worker" + ); + assert_eq!( + next.index, first.index, + "paused: same timeline position before and after" + ); } /// A rate undo lands the picture where the playhead is, in the rate that @@ -5413,4 +5471,3 @@ mod tests { ); } } - diff --git a/crates/engine/tests/exif_orientation.rs b/crates/engine/tests/exif_orientation.rs new file mode 100644 index 0000000..c480cb4 --- /dev/null +++ b/crates/engine/tests/exif_orientation.rs @@ -0,0 +1,366 @@ +//! A still's own EXIF orientation, applied. +//! +//! A phone photographs a portrait picture and stores it as landscape plus a tag +//! saying which way up it is. Before this the engine read neither: the `image` +//! crate keeps the orientation in its decoder and applies nothing, so the +//! preview, the timeline clip box, the poster thumbnail, the canvas seed and an +//! export of that clip were all the stored shape -- a portrait photo on its +//! side, silently, in every one of them. +//! +//! The fixture is **built here**, because none of the ones in `assets/` carry +//! an orientation tag (`scripts/gen_fixtures.sh` writes PNG stills, and PNG has +//! no such tag). It is a real JPEG: four coloured quadrants, an APP1 segment +//! holding a TIFF IFD whose tag `0x0112` states the orientation. A single +//! sampled pixel per corner then names the layout, and a *wrong direction* +//! cannot pass -- 90 the other way, 180, or "ignore it" each produce a +//! different set of four corners. +//! +//! ```text +//! cargo test -p engine --test exif_orientation -- --test-threads=1 +//! ``` + +use std::path::PathBuf; + +use engine::scratch::Scratch; +use engine::{DecodeSession, PlaybackSession, Rotation, image_orientation, image_size}; + +/// A built fixture and the directory holding it, which is removed when the +/// guard drops -- [`Scratch`]'s own contract, so a run leaves nothing behind +/// and two runs cannot race for a name. +fn fixture(exif: u8) -> (Scratch, PathBuf) { + let scratch = Scratch::file(&format!("ve_exif_{exif}"), "jpg"); + let path = PathBuf::from(&*scratch); + std::fs::write(&path, build(exif)).expect("write the built fixture"); + (scratch, path) +} + +/// Which of the four colours a pixel is, by name. The quadrants are far enough +/// apart that a 4:2:0 chroma boundary cannot colour a sample taken deep inside +/// one, and JPEG's own chroma subsampling cannot either. +fn tint(rgb: [u8; 3]) -> &'static str { + let (r, g, b) = (rgb[0], rgb[1], rgb[2]); + match (r > 110, g > 90, b > 110) { + (true, true, false) => "yellow", + (true, false, false) => "red", + (false, true, false) => "green", + (false, false, true) => "blue", + other => panic!("a quadrant centre is not one of the four colours: {other:?}"), + } +} + +/// The four corners of one tightly packed BGRA picture, top-left first and +/// clockwise -- sampled deep enough inside each quadrant that no boundary can +/// colour the sample. +fn corners(width: u32, height: u32, bgra: &[u8]) -> [&'static str; 4] { + let at = |x: u32, y: u32| { + let index = ((y * width + x) * 4) as usize; + let (b, g, r) = (bgra[index], bgra[index + 1], bgra[index + 2]); + tint([r, g, b]) + }; + let (qx, qy) = (width / 4, height / 4); + [ + at(qx, qy), + at(3 * qx, qy), + at(3 * qx, 3 * qy), + at(qx, 3 * qy), + ] +} + +/// The quadrants of the picture as it is **written into the file**, in the same +/// order [`corners`] reads them. The file is landscape 64x32 whatever the +/// orientation says, because that is what a phone does: it stores the sensor's +/// own shape and says the rest in the tag. +const STORED: [&str; 4] = ["red", "green", "blue", "yellow"]; + +/// A 64x32 RGB picture of four coloured quadrants, encoded as a JPEG and given +/// an APP1/EXIF segment stating `exif` as the orientation. +/// +/// The EXIF is written by hand rather than through a crate: the segment is six +/// bytes of `Exif\0\0` followed by a little-endian TIFF header and one IFD +/// entry, which is the whole of what tag `0x0112` is, and writing it out is what +/// makes this a fixture rather than a dependency. +fn build(exif: u8) -> Vec { + let (width, height) = (64u32, 32u32); + let (red, green, blue, yellow) = ( + [220u8, 30, 30], + [30, 200, 40], + [40, 60, 220], + [230, 210, 40], + ); + let (qx, qy) = (width / 4, height / 4); + let mut rgb = image::RgbImage::new(width, height); + for y in 0..height { + for x in 0..width { + let colour = match (x >= 2 * qx, y >= 2 * qy) { + (false, false) => red, + (true, false) => green, + (true, true) => blue, + (false, true) => yellow, + }; + rgb.put_pixel(x, y, image::Rgb(colour)); + } + } + let mut jpeg = Vec::new(); + image::DynamicImage::ImageRgb8(rgb) + .write_to( + &mut std::io::Cursor::new(&mut jpeg), + image::ImageFormat::Jpeg, + ) + .expect("encode the JPEG"); + // Inserted straight after SOI, which is where a camera's APP1 sits and + // where a decoder's marker walk finds it first. + let app1 = exif_app1(exif); + let mut out = Vec::with_capacity(jpeg.len() + app1.len()); + out.extend_from_slice(&jpeg[..2]); + out.extend_from_slice(&app1); + out.extend_from_slice(&jpeg[2..]); + out +} + +/// A complete APP1 segment carrying `exif` as EXIF tag `0x0112`: the `Exif\0\0` +/// identifier, a little-endian TIFF header pointing its IFD0 at offset 8, one +/// entry (tag, type SHORT, count 1, the value), and a zero "next IFD" pointer. +fn exif_app1(exif: u8) -> Vec { + let mut tiff = Vec::new(); + tiff.extend_from_slice(b"II\x2a\x00"); // little-endian, magic 42 + tiff.extend_from_slice(&8u32.to_le_bytes()); // IFD0 at offset 8 + tiff.extend_from_slice(&1u16.to_le_bytes()); // one entry + tiff.extend_from_slice(&0x0112u16.to_le_bytes()); // Orientation + tiff.extend_from_slice(&3u16.to_le_bytes()); // type SHORT + tiff.extend_from_slice(&1u32.to_le_bytes()); // count 1 + tiff.extend_from_slice(&u16::from(exif).to_le_bytes()); + tiff.extend_from_slice(&[0, 0]); // the value's padding to an even offset + tiff.extend_from_slice(&0u32.to_le_bytes()); // no IFD1 + + let mut payload = b"Exif\x00\x00".to_vec(); + payload.extend_from_slice(&tiff); + + let mut segment = vec![0xff, 0xe1]; + // The length field counts itself and the two marker bytes. + segment.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes()); + segment.extend_from_slice(&payload); + segment +} + +/// One frame of `path` and the size it came out at -- the same funnel +/// `PlaybackSession` paints from, so this is what a poster thumbnail and the +/// preview would each hold. +fn first_frame(path: &std::path::Path) -> (u32, u32, Vec) { + let (_, frames, _) = DecodeSession::open_range(path, 0, 1).expect("open for a frame"); + let frame = frames.recv().expect("a first frame"); + (frame.width, frame.height, frame.bgra) +} + +/// Software everywhere, so the suite proves the path every machine has. +fn pin_software() { + static PIN: std::sync::Once = std::sync::Once::new(); + PIN.call_once(|| unsafe { + std::env::set_var("VE_SW", "1"); + std::env::set_var("VE_SW_ENC", "1"); + }); +} + +/// The whole of the defect, asserted through **both** doors that used to +/// disagree: the header-only size a library row reads before anything places +/// the file, and the first decoded frame a preview shows after. They are +/// separate code paths over the same tag, so a fix to one that skipped the +/// other would leave a file that is one shape in the library and another on the +/// timeline. +/// +/// EXIF 6 is the portrait case -- a quarter turn clockwise -- so the stored +/// 64x32 is shown 32x64, and each stored corner moves one place clockwise. +#[test] +fn a_portrait_photo_is_shown_the_way_it_was_photographed() { + pin_software(); + let (_scratch, path) = fixture(6); + + assert_eq!( + image_size(&path).expect("the header answers"), + (32, 64), + "a library row must describe the picture as it is shown, not as it is stored" + ); + assert_eq!( + image_orientation(&path).expect("the tag is readable"), + Rotation::Cw90, + "EXIF 6 is a quarter turn clockwise" + ); + + let (width, height, bgra) = first_frame(&path); + assert_eq!( + [width, height], + [32, 64], + "the decoded frame is the picture as it is shown" + ); + assert_eq!( + corners(width, height, &bgra), + ["yellow", "red", "green", "blue"], + "a quarter turn clockwise puts the stored bottom-left at the new top-left: \ + the file holds {STORED:?} top-left first" + ); +} + +/// The other quarter turns, so a fix that turned *something* rather than +/// turning *right* cannot pass: EXIF 3 is 180 (opposite corners swap), 8 is a +/// quarter turn anticlockwise (the other way round), and 1 states no turn. +/// +/// Each is asserted against the corners its own turn produces, indexed off the +/// stored layout rather than written out, so the expectation cannot drift away +/// from the fixture it describes. +#[test] +fn every_quarter_turn_is_made_in_its_own_direction() { + pin_software(); + // Which stored corner each read corner is, and whether the axes swap with + // the turn. A clockwise quarter turn walks the ring one place on, so the + // read corner at index `i` is the stored one at `i + 3`; anticlockwise is + // the other way round, and 180 is two places either way. + for (exif, swaps, ring) in [ + (3u8, false, [2usize, 3, 0, 1]), + (8, true, [1, 2, 3, 0]), + (1, false, [0, 1, 2, 3]), + ] { + let (_scratch, path) = fixture(exif); + let (stored_w, stored_h) = (64u32, 32u32); + let (want_w, want_h) = match swaps { + true => (stored_h, stored_w), + false => (stored_w, stored_h), + }; + assert_eq!( + image_size(&path).expect("the header answers"), + (want_w, want_h), + "EXIF {exif}: the shown pair is the stored one, turned" + ); + + let (width, height, bgra) = first_frame(&path); + assert_eq!( + [width, height], + [want_w, want_h], + "EXIF {exif}: the frame is the picture as it is shown" + ); + let want: Vec<&str> = ring.iter().map(|i| STORED[*i]).collect(); + assert_eq!( + corners(width, height, &bgra), + want[..], + "EXIF {exif}: the corners read the stored ones in the order {ring:?}" + ); + } +} + +/// A mirroring is not a turn, and this engine has no flip anywhere in its +/// pipeline -- not in the still's decode, not in `Render`, not in an export's +/// `place_picture`. So EXIF 2, 4, 5 and 7 are refused **by name** at the door, +/// the way a display matrix that is not a quarter turn is +/// (`engine::UnsupportedRotation`): a mirrored photo shown the wrong way round +/// is a wrong picture, not a missing feature, and quietly treating a mirror as +/// a rotation is exactly the bug this door exists to stop. +/// +/// All four values are checked, so a fix that refused only the first mirror is +/// caught. +#[test] +fn a_mirrored_photo_is_refused_by_name() { + pin_software(); + for exif in [2u8, 4, 5, 7] { + let (_scratch, path) = fixture(exif); + let error = match image_orientation(&path) { + Ok(rotation) => { + panic!("EXIF {exif} is a mirror, not a turn, and must not read as {rotation:?}") + } + Err(error) => error, + }; + assert!( + engine::UnsupportedStillOrientation::is_it(&error), + "EXIF {exif}: the refusal is the named one, not a generic failure: {error}" + ); + let said = error.to_string(); + assert!( + said.contains(&exif.to_string()) && said.contains("mirror"), + "EXIF {exif}: the refusal names what it cannot make: {said}" + ); + // ...and the door that places the picture refuses it too, rather than + // showing the file the wrong way round. + let error = match PlaybackSession::open(&path) { + Ok(_) => panic!("EXIF {exif} must not open as a timeline"), + Err(error) => error, + }; + assert!( + engine::UnsupportedStillOrientation::is_it(&error), + "EXIF {exif}: opening the timeline refuses it by name too: {error}" + ); + } +} + +/// A picture that states no turn is the whole of an ordinary library, and it +/// must come out the way it always did: the turn is a branch on a bool, and +/// this is the assertion that it stays one. +#[test] +fn an_upright_photo_is_untouched_by_the_turn_door() { + pin_software(); + let (_scratch, path) = fixture(1); + assert_eq!( + image_size(&path).expect("the header answers"), + (64, 32), + "a picture that states no turn is its own size" + ); + let (width, height, bgra) = first_frame(&path); + assert_eq!([width, height], [64, 32]); + assert_eq!( + corners(width, height, &bgra), + STORED, + "no turn means the stored quadrants, in the stored order" + ); +} + +/// The export, which is the door the turn was most expensive to get wrong: it +/// is a re-encode of the *coded* planes, so a still whose turn was applied +/// only on the preview side would be written out sideways and would then play +/// sideways in every player that is not this one, forever, with no matrix left +/// to correct it. +/// +/// The written file must therefore be portrait **and** state no matrix of its +/// own -- a file that kept the landscape pixels and declared a turn would +/// satisfy neither half. +#[test] +fn an_export_of_a_turned_photo_is_upright_and_portrait() { + pin_software(); + let (_scratch, path) = fixture(6); + let mut session = PlaybackSession::open(&path).expect("open the photo"); + session.pause(); + assert_eq!( + [session.meta().width, session.meta().height], + [32, 64], + "the timeline is the displayed shape, not the stored one" + ); + + let out = engine::scratch::Scratch::file("ve_exif_export", "mp4"); + let handle = session.export_to_with(&out, &engine::export::ExportSettings::default()); + let started = std::time::Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < std::time::Duration::from_secs(60), + "the export did not finish" + ); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + handle + .result() + .expect("a finished export has an outcome") + .expect("the export succeeded"); + + let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export"); + assert_eq!( + [meta.width, meta.height], + [32, 64], + "the written file is portrait" + ); + assert_eq!( + meta.rotation, + Rotation::None, + "and states no matrix of its own: the turn is in the pixels" + ); + let (width, height, bgra) = first_frame(&out); + assert_eq!([width, height], [32, 64]); + assert_eq!( + corners(width, height, &bgra), + ["yellow", "red", "green", "blue"], + "the exported pixels are the ones the preview showed" + ); +}