From bc8b82ec886ecf333b55eb26c2194d40a42a1dc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 19 Sep 2026 02:16:40 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(media):=20audio=20routing,?= =?UTF-8?q?=20session=20audio=20re-arm,=20hw=20trailing-zero=20NALs,=20dis?= =?UTF-8?q?play-matrix=20rotation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - is_audio admits .mpeg/.mpg so mp3-with-cover files import (was fed to Mp4Demuxer) - session audio walks past trackless leading sources and re-arms when a sounding file joins a silent timeline (fixes add/remove/add silence) - engine-hw pump clears trailing cabac_zero_word bytes instead of dying with code -2; export falls back to software decode before first frame - tkhd display matrix read for mp4; 90/180/270 turns baked into preview and export pixels; other angles refused by name (UnsupportedRotation) --- crates/app/src/player/library.rs | 6 + crates/engine-hw/src/lib.rs | 21 ++ crates/engine/src/audio.rs | 49 ++-- crates/engine/src/decode.rs | 58 ++++- crates/engine/src/demux.rs | 191 +++++++++++++++- crates/engine/src/export.rs | 141 +++++++++--- crates/engine/src/lib.rs | 19 +- crates/engine/src/playback.rs | 107 +++++++-- crates/engine/src/proxy.rs | 2 + crates/engine/src/scale.rs | 68 ++++-- crates/engine/tests/audio_export.rs | 6 +- crates/engine/tests/audio_files.rs | 46 +++- crates/engine/tests/export.rs | 3 +- crates/engine/tests/hw_decode.rs | 109 +++++++++ crates/engine/tests/rotation.rs | 252 +++++++++++++++++++++ crates/engine/tests/silent_first_source.rs | 153 +++++++++++++ scripts/gen_fixtures.sh | 60 +++++ 17 files changed, 1195 insertions(+), 96 deletions(-) create mode 100644 crates/engine/tests/rotation.rs create mode 100644 crates/engine/tests/silent_first_source.rs diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 83cdc53..b0d0290 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -1407,6 +1407,12 @@ impl Player { .as_mut() .and_then(|session| subtitle_tail(session, subs)) .unwrap_or_default(); + // A file with sound joining a session that opened silent is the + // one import that *arms* the audio device + // ([`engine::PlaybackSession::arm_audio`]); it comes up at full + // volume, so the player's own level and mute are pushed at it + // again here or a muted window would play. + self.apply_volume(); format!( "IMPORTED {} to the library{tail}{}", file_name(path), diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index ea37f4f..2ddd8ca 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -162,6 +162,15 @@ const DMA_HOLD: usize = 6; /// real seek wins. const FORWARD_SECS: f64 = 0.5; +/// Whether `data` still holds a NAL unit: the same `00 00 01` scan +/// cros-codecs' `Nalu::next`/`find_start_code` uses to frame Annex B. `false` +/// for the `trailing_zero_8bits` / `cabac_zero_word` that may trail the last +/// NAL of an access unit -- bytes that are part of the stream but not a unit +/// any decoder will parse. +fn has_start_code(data: &[u8]) -> bool { + data.windows(3).any(|w| w == [0x00, 0x00, 0x01]) +} + /// The forward reach in frames: [`FORWARD_SECS`] at the stream's own rate. /// `0` for a rate the stream does not really state, which is "never forward" /// -- exactly the flush every reposition did before this distinction existed. @@ -559,6 +568,18 @@ impl Session { Ok(0) => return Err("decoder consumed no input".into()), Ok(n) => { pending.drain(..n.min(pending.len())); + // cros-codecs reports the bytes of the NAL it consumed, and + // that length excludes the `trailing_zero_8bits` / + // `cabac_zero_word` an encoder may append after the *last* + // NAL of an access unit (H.264 7.4.1.2.3). Those leftovers + // are not a NAL: feeding them back makes `Nalu::next` fail + // with "No NAL found", which is a hard session failure for + // an otherwise decodable file -- measured on a phone-camera + // mp4 whose every sample ends in zero words. The access unit + // is consumed when no start code is left in it. + if !has_start_code(pending) { + pending.clear(); + } if pending.is_empty() { *timestamp += 1; } diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index b952326..1b7e35f 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -413,20 +413,41 @@ impl AudioSession { fps: f64, sample_rate: Option, ) -> crate::Result)>> { - // The first source that could have a track, which is not always index 0: - // a still image has none, and one at the front of the list (a save - // renumbers, a library removal moves indexes) would be opened as a - // broken audio file and take the whole timeline's sound down with it. - // The same rule `PlaybackSession` probes by (`audio_source_of`). - let Some((at, (path, stream))) = sources - .iter() - .enumerate() - .find(|(_, (path, _))| !crate::is_image(path)) - else { - return Ok(None); - }; - let Some(first) = Track::open(path, *stream)? else { - return Ok(None); + // The first source that really *opens* a track, which is not always + // index 0 and not always the first non-image one: a still image has no + // track by definition, and a video whose file carries none (a screen + // recording with no sound) has `Track::open` answer `None`. Pinning to + // the first non-image source regardless would return `Ok(None)` for a + // whole timeline whenever that one source happened to be silent, + // silencing every later clip that does have sound -- the very failure + // `PlaybackSession::open_project`'s device walk exists to prevent, and + // it has to hold here too or the walk is defeated at playback. + // + // A source that cannot be opened at all is skipped like a silent one, + // so a broken file at the head of the list cannot take a later clip's + // sound down with it; the last error is kept and returned only when + // *nothing* opens, which is today's answer for a timeline of one broken + // source. + let mut first: Option<(usize, Track)> = None; + let mut refused: Option = None; + for (at, (path, stream)) in sources.iter().enumerate() { + if crate::is_image(path) { + continue; + } + match Track::open(path, *stream) { + Ok(Some(track)) => { + first = Some((at, track)); + break; + } + Ok(None) => {} + Err(e) => refused = Some(e), + } + } + let Some((at, first)) = first else { + return match refused { + Some(e) => Err(e), + None => Ok(None), + }; }; // The timeline's meta is that source's: policy makes every other source // match it, and the checks below hold them to that. diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 67082af..afdafab 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -18,7 +18,7 @@ use ec_h264::H264Decoder; use crate::color::ColorParams; use crate::colorspace::{ColorDescription, Matrix, Transfer}; use crate::convert::{i420_to_bgra, i420_to_bgra_with}; -use crate::demux::{Codec, Demuxer, VideoMeta}; +use crate::demux::{Codec, Demuxer, Rotation, VideoMeta}; use crate::hw::HwSession; use crate::project::Speed; use crate::scale::Composer; @@ -561,6 +561,8 @@ impl DecodeSession { let first = Render::new( color, transform, + // A still has no display matrix: what the file holds is what it is. + Rotation::None, ColorDescription::default(), canvas, tonemap::Preset::default(), @@ -674,6 +676,8 @@ impl DecodeSession { let mut render = Render::new( color, transform, + // Painted here, at the canvas's own size: nothing turned it. + Rotation::None, ColorDescription::default(), canvas, tonemap::Preset::default(), @@ -1081,7 +1085,15 @@ fn run_span( // The stream's own colour and peak brightness: properties of the stream, so // neither can change while one range decodes -- but the grade, the canvas // and the rendition are the *span's*, so this is built per span. - let mut render = Render::new(color, transform, opened.meta.color, canvas, tone, opened.peak); + let mut render = Render::new( + color, + transform, + opened.meta.rotation, + opened.meta.color, + canvas, + tone, + opened.peak, + ); if let Some(reused) = opened.position_hw(path, start) { // Cancelled during the init (or the seek): leave without decoding. if abort.hit() { @@ -1152,6 +1164,13 @@ struct Render { /// This clip's placement, on top of whatever the canvas's own fit policy /// already does ([`crate::scale::Composer::place_transformed`]). transform: TransformParams, + /// How far the *file* asks its picture to be turned before anything else + /// happens to it ([`crate::demux::Rotation`]): the phone-portrait turn, + /// made here so the grade, the canvas and the preview's own renderer all + /// see the picture the way it is meant to be seen. [`Rotation::None`] for + /// every file that states no turn, which is the whole of an ordinary + /// library. + rotation: Rotation, /// What the source's samples mean -- the stream's own matrix and range, /// which is what the conversion below is done in rather than the BT.601 it /// used to assume of every file. @@ -1166,6 +1185,10 @@ struct Render { /// across the worker's whole range. Empty unless the clip needs one: it is /// tone-mapped in place, graded in place, or both. graded: (Vec, Vec, Vec), + /// The same, for the display-matrix turn above: empty for every file that + /// asks for none, and resized once for one that does -- a steady-state + /// buffer rather than three plane allocations per decoded frame. + turned: (Vec, Vec, Vec), /// Where [`Composer::place_transformed`]'s owned picture lands, so a /// transformed frame's planes live as long as `self` -- matching what /// [`Composer::place`] already hands back by borrowing `self.canvas`. @@ -1188,6 +1211,7 @@ impl Render { fn new( color: ColorParams, transform: TransformParams, + rotation: Rotation, desc: ColorDescription, canvas: Composer, preset: tonemap::Preset, @@ -1196,6 +1220,7 @@ impl Render { Self { color, transform, + rotation, desc, canvas, // corner-cut: the ceiling is that the map reads limited-range codes @@ -1209,6 +1234,7 @@ impl Render { Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)), }, graded: (Vec::new(), Vec::new(), Vec::new()), + turned: (Vec::new(), Vec::new(), Vec::new()), placed: (Vec::new(), Vec::new(), Vec::new()), } } @@ -1222,6 +1248,34 @@ impl Render { width: u32, height: u32, ) -> Frame { + // The file's own turn, before anything else: a phone's portrait video + // arrives as landscape planes, and the grade, the canvas and the + // conversion below all have to see the picture the way it is meant to + // be seen. Nothing here at all for the ordinary file that states no + // turn -- `Rotation::None` takes the planes by reference and not one + // byte is copied. + let (y, u, v, width, height) = match self.rotation.is_none() { + true => (y, u, v, width, height), + false => { + let steps = self.rotation.steps(); + let (rw, rh) = crate::scale::rotate_i420_90s_into( + y, + u, + v, + width, + height, + steps, + &mut self.turned, + ); + ( + &self.turned.0[..], + &self.turned.1[..], + &self.turned.2[..], + rw, + rh, + ) + } + }; let passthrough = self.canvas.is_passthrough(width, height); // A transform still has a picture to place even where the canvas // itself would hand this size back untouched -- moving, scaling, diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 96957a3..a030aa8 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -267,9 +267,102 @@ impl NoVideoTrack { } } +/// How far a container's display matrix says the picture must be turned to be +/// seen the way it was shot: quarter turns **clockwise**, the direction +/// [`crate::scale::rotate_i420_90s`] takes and the one a clip's own +/// [`TransformParams`](crate::transform::TransformParams) rotate is measured +/// in. +/// +/// This is metadata about the *pixels*, not a user's edit: an mp4's `tkhd` +/// matrix, a phone's 90-degree turn, and every consumer of this engine's +/// pictures -- the preview and the encoder alike -- has to make it, or the film +/// plays and exports sideways. [`VideoMeta::width`] and +/// [`VideoMeta::height`] are therefore the *displayed* size: the coded picture +/// is the swapped one, and every picture this engine hands out is turned to +/// match. A container asking for anything that is not a right angle is refused +/// at the door ([`UnsupportedRotation`]) rather than shown wrong. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Rotation { + #[default] + None, + Cw90, + Cw180, + Cw270, +} + +impl Rotation { + /// Quarter turns clockwise, the count + /// [`crate::scale::rotate_i420_90s`] applies. + pub fn steps(self) -> u8 { + match self { + Rotation::None => 0, + Rotation::Cw90 => 1, + Rotation::Cw180 => 2, + Rotation::Cw270 => 3, + } + } + + /// Whether the turned picture's width and height are the coded ones + /// swapped. + pub fn swaps_axes(self) -> bool { + matches!(self, Rotation::Cw90 | Rotation::Cw270) + } + + /// Whether there is anything to do at all, asked exactly as + /// [`TransformParams::is_identity`](crate::transform::TransformParams::is_identity) + /// is: the common case of a file that was shot the way it is stored. + pub fn is_none(self) -> bool { + matches!(self, Rotation::None) + } +} + +/// A container that asks for a turn this engine cannot make: a display matrix +/// that is not a pure right-angle rotation -- a mirror, a shear, or an angle +/// that is not a multiple of 90 degrees. +/// +/// Named and refused rather than ignored, for [`NoVideoTrack`]'s reason prose +/// might have to be reworded: a file whose picture is 45 degrees off has no +/// correct rendition here, and showing it sideways is a wrong picture rather +/// than a missing feature. The `Display` is what a user is refused by. +#[derive(Debug)] +pub struct UnsupportedRotation { + /// The angle the matrix states, where it states one at all -- `None` for a + /// mirror or a shear, which is not one -- for the sentence only. + pub degrees: Option, +} + +impl std::fmt::Display for UnsupportedRotation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.degrees { + Some(degrees) => write!( + f, + "this file carries a display matrix of {degrees:.1}°, which is not a quarter \ + turn; only 0°, 90°, 180° and 270° can be straightened here" + ), + None => f.write_str( + "this file's display matrix is not a rotation at all (a mirror or a shear); only \ + 0°, 90°, 180° and 270° can be straightened here", + ), + } + } +} + +impl std::error::Error for UnsupportedRotation {} + +impl UnsupportedRotation { + /// Whether `error` is one of these, however deep in a `Box` it is -- + /// [`NoVideoTrack::is_it`]'s twin. + pub fn is_it(error: &crate::Error) -> bool { + error.downcast_ref::().is_some() + } +} + #[derive(Debug, Clone, Copy, PartialEq)] pub struct VideoMeta { + /// The displayed width: the coded one, swapped where the file's display + /// matrix is a 90- or 270-degree turn (see [`Rotation`]). pub width: u32, + /// The displayed height; see [`VideoMeta::width`]. pub height: u32, pub frame_rate: f64, pub frame_count: u32, @@ -278,6 +371,14 @@ pub struct VideoMeta { /// which range -- resolved off the container's tags, the bitstream's, and /// the resolution, in that order. See [`crate::colorspace`]. pub color: ColorDescription, + /// How far the picture must be turned to be seen right, off the + /// container's display matrix. [`Rotation::None`] for everything whose + /// container states no turn, and for a Matroska file: only the mp4 half is + /// read today, because Matroska's own spelling (a `ProjectionPoseYaw` + /// element) is written by nobody in practice while the `tkhd` matrix is how + /// every phone records it. That is a known gap and not a silent one: + /// [`MkvDemuxer::open`] says where a reader for it would go. + pub rotation: Rotation, } /// What a file spends its bytes at, in bits per second -- the whole file, and @@ -730,15 +831,41 @@ impl Mp4Demuxer { .ok_or_else(|| mp4_no_video(path, &reader))?; let track_id = track.track_id(); + // The turn the file was shot at, off its `tkhd` display matrix -- how + // every phone records "this is portrait". `track.width()`/`height()` are + // the *coded* ones for an H.264 track (the `avc1` sample entry), so a + // quarter turn is what makes this file's displayed size the swapped one, + // and the whole engine reads these two as the picture's size. + let rotation = match reader + .moov + .traks + .iter() + .find(|trak| trak.tkhd.track_id == track_id) + { + // The values, not the type: `mp4`'s `tkhd` module is `pub(crate)`, + // so its `Matrix` cannot be named here -- but its fields are public + // and the four linear ones are all this needs. + Some(trak) => { + let m = &trak.tkhd.matrix; + rotation_of_matrix(m.a, m.b, m.c, m.d)? + } + None => Rotation::None, + }; + let (coded_w, coded_h) = (u32::from(track.width()), u32::from(track.height())); + let (width, height) = match rotation.swaps_axes() { + true => (coded_h, coded_w), + false => (coded_w, coded_h), + }; let meta = VideoMeta { - width: track.width() as u32, - height: track.height() as u32, + width, + height, frame_rate: frame_rate(track), frame_count: 0, codec, // Filled below, once the parameter sets the bitstream tier reads are // in hand. color: ColorDescription::default(), + rotation, }; let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track)); let mut parameter_sets = Vec::new(); @@ -1196,6 +1323,11 @@ impl MkvDemuxer { bitstream_tags(video.codec, &mkv.config), video.height, ), + // FLAG: Matroska's turn is not read yet -- see [`VideoMeta::rotation`]. + // Nothing in this tree writes a `ProjectionPoseYaw`, and the mkv + // tracks a phone or a camera app produces are mp4s; a `.mkv` that + // does carry one would play sideways until this is written. + rotation: Rotation::None, }; Ok((meta, mkv)) } @@ -2497,6 +2629,61 @@ fn parse_av1c(rec: &[u8]) -> crate::Result<(Vec, u8)> { Ok((rec.get(4..).unwrap_or_default().to_vec(), bit_depth)) } +/// The quarter turns an mp4 `tkhd` display matrix asks for, or an +/// [`UnsupportedRotation`] where it asks for something else. +/// +/// The matrix is the ISO 14496-12 §8.3.2 3x3 affine, stored as nine 16.16 +/// fixed-point values in the order `a b u c d v x y w`; only the four linear +/// ones matter here, and only as a rotation: the values are normalised by the +/// matrix's own scale so a differently-scaled copy of a quarter turn still +/// reads as one, and anything that is not a pure right-angle turn -- a mirror +/// (a negative determinant), a shear, a 45-degree phone quirk -- is refused by +/// name rather than shown sideways. +/// +/// The direction is this engine's: the linear part is `[[a, c], [b, d]]` (a +/// point maps to `(a*x + c*y, b*x + d*y)`), so `atan2(b, a)` is the clockwise +/// angle when `(a, b)` is the turned x-axis, and the quarter count it falls on +/// is exactly what [`crate::scale::rotate_i420_90s`] applies. Measured against +/// ffmpeg's own autorotate on the `test_rotation*.mp4` fixtures +/// (`scripts/gen_fixtures.sh`): a `tkhd` matrix of `a=0, b=-65536, c=65536, +/// d=0` -- what `-display_rotation 90` writes, and what a phone's portrait +/// video carries -- is [`Rotation::Cw270`] here, the quarter turn that puts the +/// coded left edge at the top. +fn rotation_of_matrix(a: i32, b: i32, c: i32, d: i32) -> crate::Result { + let fixed = |raw: i32| f64::from(raw) / 65536.0; + let (a, b, c, d) = (fixed(a), fixed(b), fixed(c), fixed(d)); + let scale = a.hypot(b); + let unsupported = || -> crate::Error { + crate::Error::from(UnsupportedRotation { + // The honest number where the matrix states one at all; a mirror or + // a shear has no angle, and 0.0 would be a claim rather than a + // reading. + degrees: (scale > 0.0).then(|| b.atan2(a).to_degrees()), + }) + }; + // Pure and isotropic: both columns the same length, and one the other's + // quarter turn (`d == a`, `-c == b` after normalising) -- no shear, no + // anisotropic scale. + if scale == 0.0 + || (scale - c.hypot(d)).abs() > 1e-3 + || ((a - d) / scale).abs() > 1e-3 + || ((b + c) / scale).abs() > 1e-3 + { + return Err(unsupported()); + } + let degrees = b.atan2(a).to_degrees(); + let steps = (degrees / 90.0).round(); + if (degrees - steps * 90.0).abs() > 0.5 { + return Err(unsupported()); + } + Ok(match steps.rem_euclid(4.0) as u8 { + 0 => Rotation::None, + 1 => Rotation::Cw90, + 2 => Rotation::Cw180, + _ => Rotation::Cw270, + }) +} + /// Why an mp4 came back with no picture, by the fourcc of the video track it /// does carry: `avc3` and `mp4v` are files with video in them, and telling their /// owner there is none sends them looking for a fault that is not in the file. diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 463fe68..4b96766 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -80,7 +80,7 @@ use oxideav_core::Muxer as _; use crate::audio::{AudioMeta, AudioSession}; use crate::colorspace::{ColorDescription, Matrix, Transfer}; -use crate::demux::{Codec, Demuxer, MkvDemuxer, VideoMeta}; +use crate::demux::{Codec, Demuxer, MkvDemuxer, Rotation, VideoMeta}; use crate::hw::{DmaFrame, DmaWant, HwEncoder, HwPicture, HwSession}; use crate::mux::{ AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, @@ -1174,7 +1174,13 @@ struct Dissolve<'a> { remap: Option<(Matrix, Matrix)>, grade: Option, transform: TransformParams, + /// B's own file's display-matrix turn, [`place_picture`]'s first stage; + /// B is a different file and may be turned differently from A. + rotation: Rotation, canvas: Composer, + /// The turn's, the grade's and the transform's scratch, exactly as A's + /// span keeps them: refilled per picture, allocated once. + rotated: (Vec, Vec, Vec), graded: (Vec, Vec, Vec), transformed: (Vec, Vec, Vec), } @@ -1801,7 +1807,14 @@ impl CopyPlan { // The stream this file would carry, at the size and the rate the // timeline is in: anything else is a picture that has to be // coded again to become this file's. - if source_meta.codec != codec + // + // A source whose display matrix asks for a turn is one of + // those: a copied packet is the source's own coded picture, and + // this export bakes the turn into the pixels -- so a copy would + // ship the file sideways. Re-encoding is the only honest + // answer here. + if !source_meta.rotation.is_none() + || source_meta.codec != codec || source_meta.width != meta.width || source_meta.height != meta.height || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()? @@ -2652,7 +2665,7 @@ fn run( // samples *mean* ([`ColorDescription`]), which is what decides whether they // are remapped on the way in. Real time for a still, a song and a // single-rate project, where every conversion below is the identity. - let rates: Vec<(Rate, ColorDescription, Option)> = sources + let rates: Vec<(Rate, ColorDescription, Option, Rotation)> = sources .iter() .map(|source| source_rate(&source.path, meta.frame_rate)) .collect(); @@ -2671,7 +2684,7 @@ fn run( let preset = project.tone(); let tone: Vec> = rates .iter() - .map(|(_, color, peak)| match color.transfer { + .map(|(_, color, peak, _)| match color.transfer { // A preview file keeps the film's own curve and is tone-mapped when // it is *shown* ([`ExportSettings::keep_source_colour`]), which is // both cheaper and the only way the preset can still be changed @@ -2734,12 +2747,12 @@ 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) = match span.from { + let (mut pictures, rate, in_frame, color, mapper, rotation) = match span.from { Some((source, in_frame)) => { let entry = sources .get(source) .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; - let (rate, color, _peak) = rates[source]; + let (rate, color, _peak, rotation) = rates[source]; let mapper = tone[source].as_ref(); // Nothing on the way from this span's decoder to the encoder // touches a sample: no tone map, no matrix remap, no grade -- @@ -2756,6 +2769,11 @@ fn run( && project .composite_transform_at(span.start) .is_none_or(|params| params.is_identity()) + // A file whose display matrix asks for a turn is *not* + // untouched, whatever else the timeline says: its pictures + // have to be turned, which is a read-back no GPU buffer + // survives. + && rotation.is_none() && dissolve.is_none(); let want = untouched.then(|| encoder.dma_want(meta)).flatten(); // Opened at the file's own frame, which is the only place the @@ -2775,12 +2793,13 @@ fn run( } else { ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)? }; - (Some(pictures), rate, in_frame, Some(color), mapper) + (Some(pictures), rate, in_frame, Some(color), mapper, rotation) } // 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, - // which is what `None` says. - None => (None, Rate::REAL_TIME, 0, None, None), + // which is what `None` says. A gap is no file either, so nothing + // turns it. + None => (None, Rate::REAL_TIME, 0, None, None, Rotation::None), }; // Mixed spaces on one timeline: a clip coded against another matrix than // the one this file declares is rewritten into it, *after* the grade -- @@ -2805,6 +2824,10 @@ fn run( .unwrap_or_default(); let mut graded = (Vec::new(), Vec::new(), Vec::new()); let mut transformed = (Vec::new(), Vec::new(), Vec::new()); + // ...and one more for the file's own display-matrix turn, which happens + // before all of those (see [`place_picture`]): empty for every source + // that states no turn. + let mut rotated = (Vec::new(), Vec::new(), Vec::new()); // ...and the canvas it is placed on, which is where a source of another // resolution becomes a picture at the project's. The same `Composer` // playback composes with, given the same policy, so an export is what @@ -2823,7 +2846,7 @@ fn run( let entry = sources.get(b_source).ok_or_else(|| { format!("clip names source {b_source} of {}", sources.len()) })?; - let (b_rate, b_color, _peak) = rates[b_source]; + let (b_rate, b_color, _peak, b_rotation) = 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 { @@ -2852,11 +2875,13 @@ fn run( .composite_transform_at(b_start) .copied() .unwrap_or_default(), + rotation: b_rotation, canvas: Composer::new( meta.width, meta.height, project.composite_fit_at(b_start), ), + rotated: (Vec::new(), Vec::new(), Vec::new()), graded: (Vec::new(), Vec::new(), Vec::new()), transformed: (Vec::new(), Vec::new(), Vec::new()), }) @@ -2946,10 +2971,12 @@ fn run( v, width, height, + rotation, grade, transform, remap, mapper, + &mut rotated, &mut graded, &mut transformed, &mut canvas, @@ -2979,9 +3006,9 @@ fn run( } Some(Frame::Pixels(by, bu, bv, bw, bh)) => { let (by, bu, bv, _, _) = place_picture( - by, bu, bv, bw, bh, d.grade, d.transform, d.remap, - d.mapper, &mut d.graded, &mut d.transformed, - &mut d.canvas, + by, bu, bv, bw, bh, d.rotation, d.grade, d.transform, + d.remap, d.mapper, &mut d.rotated, &mut d.graded, + &mut d.transformed, &mut d.canvas, ); let idx_in_window = done_here + r - d.tail_start; let t = dissolve_weight(idx_in_window, d.window); @@ -3111,12 +3138,16 @@ fn run( Ok(()) } -/// One decoded picture graded, tone-mapped, remapped and placed on the canvas -/// -- everything between a source's own samples and the ones an encoder is fed, -/// which is exactly the work a zero-copy span has none of. +/// One decoded picture turned, graded, tone-mapped, remapped and placed on the +/// canvas -- everything between a source's own samples and the ones an encoder +/// is fed, which is exactly the work a zero-copy span has none of. /// -/// `graded` and `canvas` are the span's scratch: the planes come back borrowed -/// from one of them, or from the picture itself where not a byte was touched. +/// `rotation` first, before the grade: it is the file's own display matrix, the +/// turn a player would make before showing the picture at all, and everything +/// after this -- the grade, the letterbox, the encoder -- is about the picture +/// as it is *meant* to be seen. `turned`, `graded` and `canvas` are the span's +/// scratch: the planes come back borrowed from one of them, or from the picture +/// itself where not a byte was touched. #[expect(clippy::too_many_arguments, reason = "one span's whole picture path")] fn place_picture<'a>( y: &'a [u8], @@ -3124,14 +3155,35 @@ fn place_picture<'a>( v: &'a [u8], width: u32, height: u32, + rotation: Rotation, grade: Option, transform: TransformParams, remap: Option<(Matrix, Matrix)>, mapper: Option<&ToneMapper>, + turned: &'a mut (Vec, Vec, Vec), graded: &'a mut (Vec, Vec, Vec), transformed: &'a mut (Vec, Vec, Vec), canvas: &'a mut Composer, ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) { + // The file's own turn, taken exactly as playback's decode funnel takes it + // ([`crate::decode`]): a phone's portrait video is landscape in the file, + // and the encoder must be fed what the preview showed. A file that states + // no turn skips this entirely -- the planes go on borrowed. + let (y, u, v, width, height) = match rotation.is_none() { + true => (y, u, v, width, height), + false => { + let (w, h) = crate::scale::rotate_i420_90s_into( + y, + u, + v, + width, + height, + rotation.steps(), + turned, + ); + (&turned.0[..], &turned.1[..], &turned.2[..], w, h) + } + }; // The planes are borrowed from the decoder (and `Black::picture` hands the // same slice as both u and v), so a grade cannot be applied in place: it // goes onto a copy, which the encoder then reads instead. @@ -3199,12 +3251,16 @@ fn remap_into( /// -- a still, a song -- and for one that will not open here: the decoder is /// opened a few lines later and fails the export by name, which is a better /// error than this one could raise. -fn source_rate(path: &Path, timeline_fps: f64) -> (Rate, ColorDescription, Option) { +fn source_rate( + path: &Path, + timeline_fps: f64, +) -> (Rate, ColorDescription, Option, Rotation) { if crate::is_image(path) || crate::is_audio(path) { // A still is BT.601 by construction whatever it was authored as: // `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. - return (Rate::REAL_TIME, ColorDescription::default(), None); + // planes. A song has no picture and the answer is never read. Neither + // has a display matrix to be turned by. + return (Rate::REAL_TIME, ColorDescription::default(), None, Rotation::None); } match Demuxer::open(path) { // ...and one whose rate cannot be named against the timeline's, which @@ -3218,10 +3274,13 @@ fn source_rate(path: &Path, timeline_fps: f64) -> (Rate, ColorDescription, Optio Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), meta.color, demuxer.light().peak(), + // The file's own turn, so the encoder is fed the picture the + // preview shows: the same header read, one more answer. + meta.rotation, ), // Unreadable here means unreadable below too, where the span dies with a // real message; the file's own space is the least of that. - Err(_) => (Rate::REAL_TIME, ColorDescription::default(), None), + Err(_) => (Rate::REAL_TIME, ColorDescription::default(), None, Rotation::None), } } @@ -4397,9 +4456,11 @@ fn pop_av1<'a>( /// which would cost two conversions and a generation of colour precision. /// /// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`, -/// which only speaks BGRA. Unlike playback there is no mid-clip fallback to -/// software: a hardware decode that fails after the first picture fails the -/// export, which then deletes the half-written file. +/// which only speaks BGRA. A hardware decode that fails *before* the first +/// picture falls back to software, exactly as playback's does -- nothing has +/// been encoded yet, so the span can be taken over cleanly. One that fails +/// after the first picture fails the export, which then deletes the +/// half-written file: a restart there would re-encode what the muxer holds. enum ClipDecoder { /// A stream, decoded on a thread of its own: the encode of picture *n* and /// the decode of picture *n + 1* are the two halves an export used to do in @@ -4628,9 +4689,9 @@ impl ClipDecoder { /// will have it, software otherwise) and send every picture until the encoder /// stops taking them. /// -/// Unlike playback there is no mid-clip fallback to software: a hardware decode -/// that fails after the first picture fails the export, which then deletes the -/// half-written file. +/// Hardware that fails before the first picture falls back to the software seat +/// (see the loop's `decoded == 0` arm); one that fails after it fails the +/// export, which then deletes the half-written file. /// /// Every way this returns says which way it was, down the channel: a picture, an /// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not @@ -4656,6 +4717,12 @@ fn decode_stream( } }, }; + // Pictures handed down the channel. Hardware that dies *before* the first + // one is the fallback playback already makes, and here nothing has been + // encoded yet, so the software seat can take the whole span with no frame + // repeated. Past one picture a restart would re-encode what the muxer + // already holds, which is why the export still fails there. + let mut decoded = 0u32; loop { let frame = match decoder.next(want) { Ok(Some(frame)) => frame, @@ -4664,6 +4731,21 @@ fn decode_stream( return; } Err(e) => { + if decoded == 0 && matches!(decoder, Pictures::Hw(_)) { + eprintln!( + "export decode: hardware failed before any frame ({e}); falling back to software" + ); + match SwDecoder::open(path, start_frame) { + Ok(sw) => { + decoder = Pictures::Sw(sw); + continue; + } + Err(sw_refusal) => { + let _ = tx.send(Err(sw_refusal)); + return; + } + } + } let _ = tx.send(Err(e)); return; } @@ -4673,6 +4755,7 @@ fn decode_stream( if tx.send(Ok(Some(frame))).is_err() { return; } + decoded += 1; } } @@ -5283,6 +5366,7 @@ mod tests { frame_count: 1, codec: crate::demux::Codec::H264, color: Default::default(), + rotation: Rotation::None, }; // 1280 * 720 * 30 * 0.1 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); @@ -5332,6 +5416,7 @@ mod tests { frame_count: 1, codec: crate::demux::Codec::H264, color: Default::default(), + rotation: Rotation::None, } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ca7b2b3..40356d5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -37,7 +37,7 @@ pub use audio::{ }; pub use clock::PlaybackClock; pub use decode::{DecodeSession, Frame, image_size}; -pub use demux::{Codec, MediaBitrate, VideoMeta, probe_bitrate}; +pub use demux::{Codec, MediaBitrate, Rotation, UnsupportedRotation, VideoMeta, probe_bitrate}; pub use export::ExportHandle; pub use mux::{AudioParams, Mp4Muxer, VideoParams}; pub use playback::{ImportGate, ImportProbe, PlaybackSession}; @@ -55,11 +55,24 @@ pub use project::{Clip, Project, Rate, Speed}; /// has. A `.dts` or a bare `.ac3` is refused by the same door that refuses a /// `.txt` -- there is no reader here that opens an elementary stream -- which is /// the honest answer. +/// +/// The `.mpeg` and `.mpg` spellings are on the list because an MPEG audio +/// stream has no container to name it and the file is whatever a recorder +/// called it: those two are the *standard's* name -- what a voice note or a +/// tagged download off the web wears -- where `.mp3` is the codec's. Symphonia's +/// `mp3` reader is what reads them, the same reader an `.mp3` goes through, and +/// it skips the ID3v2 tag and any cover picture muxed into one. A `.mpeg` that +/// is really an MPEG *program stream* with a picture in it is still no picture +/// here -- nothing demuxes one, and it is symphonia's refusal that says so +/// rather than the mp4 crate's. (MPEG's other two layers, `.mp1`/`.mp2`, are +/// deliberately absent: this build compiles the mp3 bundle without its `mp1`/ +/// `mp2` features, so a layer II stream is a codec nothing here decodes, and +/// admitting the spelling would be a promise the reader cannot keep.) 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" | "wav" | "flac" | "ogg" | "oga" | "opus" | "mka" | "m4a" | "aac" + "mp3" | "mpeg" | "mpg" | "wav" | "flac" | "ogg" | "oga" | "opus" | "mka" | "m4a" | "aac" ) }) } @@ -117,6 +130,8 @@ mod tests { "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 f718a18..be6c899 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -24,7 +24,7 @@ use crate::clock::{ClockSource, PlaybackClock}; use crate::color::ColorParams; use crate::colorspace::{ColorDescription, ContentLight}; use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; -use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta}; +use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta}; use crate::eq::EqParams; use crate::project::{ Clip, Edge, GapSweep, Lane, LaneKind, Project, Rate, Source, Span, Speed, SubClip, @@ -704,6 +704,7 @@ impl PlaybackSession { // A canvas this engine drew itself, not a stream that was read: // the default description is what it is drawn in. color: ColorDescription::default(), + rotation: Rotation::None, }; let (audio, audio_disabled) = open_audio(path, stream); // Through `from_parts` rather than `Project::single`, which is the @@ -801,6 +802,7 @@ impl PlaybackSession { frame_count: image_frames(IMAGE_ONLY_RATE), codec: Codec::H264, color: ColorDescription::default(), + rotation: Rotation::None, }; let clip = Clip { fade_in: 0, @@ -964,6 +966,7 @@ impl PlaybackSession { .map_err(|e| format!("source {}: {e}", first.path.display()))?, codec: Codec::H264, color: ColorDescription::default(), + rotation: Rotation::None, }; (meta, DecodeSession::open_black(width, height, 1)) } @@ -981,6 +984,7 @@ impl PlaybackSession { frame_count: image_frames(frame_rate), codec: Codec::H264, color: ColorDescription::default(), + rotation: Rotation::None, }; let stream = DecodeSession::open_still( &first.path, @@ -1022,6 +1026,7 @@ impl PlaybackSession { .map_err(|e| format!("source {}: {e}", first.path.display()))?, codec: Codec::H264, color: ColorDescription::default(), + rotation: Rotation::None, }; (meta, DecodeSession::open_black(width, height, 1)) } @@ -2646,6 +2651,43 @@ impl PlaybackSession { } debug_assert_eq!(self.counts.len(), self.project.sources().len()); debug_assert_eq!(self.rates.len(), self.counts.len()); + // A source just joined, which is the one moment the session's audio + // device may need arming ([`Self::arm_audio`]). + self.arm_audio(); + } + + /// Opens the audio device for the first source in the library that has a + /// track, when this session has none. + /// + /// A session opened silent -- its first file carried no sound, so + /// [`Self::open_library`]/[`Self::open`] had no track to open a device on + /// -- must not stay silent once a source *with* sound joins it: every later + /// clip's audio would go unheard for the rest of the session. That is + /// exactly what the walk [`Self::open_project`] makes at open prevents for + /// a loaded project (c581d41); this is the same walk at the add door, and + /// [`Self::note_frames`] is the one place a source joins. + /// + /// A no-op once a device is open, so it costs a scan of `is_some` on every + /// later import. The clock stays on wall time until the next seek + /// ([`Self::seek`]'s own `switch_to_audio`), which is the seek a front-end + /// makes as it places the file it just imported. + fn arm_audio(&mut self) { + if self.audio.is_some() { + return; + } + for source in self + .project + .sources() + .iter() + .filter(|s| !crate::is_image(&s.path)) + { + let (audio, disabled) = open_audio(&source.path, source.audio_stream); + if audio.is_some() { + self.audio = audio; + self.audio_disabled = disabled; + return; + } + } } /// The rate noted for whichever source plays `path`, by @@ -3511,10 +3553,10 @@ impl PlaybackSession { /// picture, so the length noted for it is its playing time rounded up to /// whole frames, which is the only frame count such a source has. /// - /// Refused in the same words as any other import when its rate or layout - /// disagrees with the timeline's -- one output device, one set of - /// parameters -- and refused outright on a silent timeline, which has no - /// device open at all. Nothing is changed by a refusal. + /// Refused in the same words as any other import when its layout disagrees + /// with the timeline's track -- one output device, one layout. A silent + /// timeline has no track to disagree with, so a song joins it and *is* its + /// sound ([`Self::arm_audio`]). Nothing is changed by a refusal. fn import_audio(&mut self, path: &Path) -> crate::Result { let first = self.first_audio()?; // Stream 0, and there is no other: a standalone audio file carries one @@ -4199,21 +4241,30 @@ fn matches_timeline( /// cannot do is be copied into an export, which is a refusal of its own, at /// export time (`AudioSession::copy_multi_streams`). /// What a timeline's audio is held to: the probe of the first source that could -/// have any. A still image is never it -- a picture defines no rate and no -/// layout, so a PNG at index 0 would otherwise be *probed* as a broken mp4 and -/// fail the open outright. +/// have any track. +/// +/// The probe of the first source that really **has a track**, walking forward +/// past a still (no track by definition) and past a source whose file carries +/// none (a screen recording with no sound). A silent leading source must not +/// pin the timeline's layout: pinned to it, a later file with sound could never +/// be admitted, and the layout a *following* file is held to would be the +/// silent source's `None`. This is the same walk +/// [`PlaybackSession::open_project`] makes when it opens the device -- the two +/// have to agree, so probing and opening can never name different sources. /// -/// `Ok(None)` for a timeline whose first such source is silent, and for one of -/// nothing but stills. That is a silent timeline, and a file with sound is -/// still refused by [`audio_matches`] in the words it always used ("the file -/// has audio, the timeline is silent") -- the device was opened on source 0's -/// track and there is none to open. This function widens which source is asked, -/// not what the answer means. +/// `Ok(None)` for a timeline with no track anywhere: nothing but stills, with +/// no file at all, or every non-still source silent. That is a silent timeline, +/// and a file with sound is admitted onto it -- it *becomes* the timeline's +/// sound ([`PlaybackSession::arm_audio`] opens the device for it), exactly the +/// c581d41 rule ("a later source with real audio must be heard") at the add +/// door. fn first_audio_of(sources: &[Source]) -> crate::Result> { - match audio_source_of(sources) { - Some(first) => AudioSession::probe(&first.path, first.audio_stream), - None => Ok(None), + for source in sources.iter().filter(|s| !crate::is_image(&s.path)) { + if let Some(probe) = AudioSession::probe(&source.path, source.audio_stream)? { + return Ok(Some(probe)); + } } + Ok(None) } /// *Which* source that is: the first one that is not a still. The single answer @@ -4268,13 +4319,21 @@ fn audio_matches_probed( let Some(probe) = probe else { return Ok(()); }; - Err(match first { - None => "the file has audio, the timeline is silent".to_string(), - Some(b) => format!( - "audio {} ch does not match the timeline's {} ch", - probe.channels, b.channels - ), - } + // The timeline has no track anywhere (nothing but stills, or every + // non-image source silent): there is no layout to disagree with, and the + // arriving file with sound *becomes* the timeline's sound -- + // [`PlaybackSession::arm_audio`] opens the device for it, exactly the walk + // [`PlaybackSession::open_project`] makes. Refusing here ("the file has + // audio, the timeline is silent") pinned the timeline to its silent first + // source for good: remove that file and add another, and the second file's + // sound could never be heard. + let Some(b) = first else { + return Ok(()); + }; + Err(format!( + "audio {} ch does not match the timeline's {} ch", + probe.channels, b.channels + ) .into()) } diff --git a/crates/engine/src/proxy.rs b/crates/engine/src/proxy.rs index 9e48396..85c72fb 100644 --- a/crates/engine/src/proxy.rs +++ b/crates/engine/src/proxy.rs @@ -615,6 +615,7 @@ fn started( mod tests { use super::*; use crate::colorspace::ColorDescription; + use crate::demux::Rotation; /// A cancel flag no test in this file is exercising, for the calls that /// have nothing to cancel. @@ -630,6 +631,7 @@ mod tests { frame_count: 240, codec, color: ColorDescription::default(), + rotation: Rotation::None, } } diff --git a/crates/engine/src/scale.rs b/crates/engine/src/scale.rs index fad3afc..cc780bd 100644 --- a/crates/engine/src/scale.rs +++ b/crates/engine/src/scale.rs @@ -459,48 +459,74 @@ pub fn rotate_i420_90s( h: u32, steps: u8, ) -> (Vec, Vec, Vec, u32, u32) { + let mut out = (Vec::new(), Vec::new(), Vec::new()); + let (rw, rh) = rotate_i420_90s_into(y, u, v, w, h, steps, &mut out); + (out.0, out.1, out.2, rw, rh) +} + +/// [`rotate_i420_90s`] into a caller's own buffers: the top-left of a phone +/// file's display matrix has to be made on **every decoded frame**, so the +/// three plane allocations are a steady-state cost to pay once rather than a +/// per-frame one. The output is exactly what the allocating form returns; the +/// scratch tuple is resized and refilled, never appended to. +pub fn rotate_i420_90s_into( + y: &[u8], + u: &[u8], + v: &[u8], + w: u32, + h: u32, + steps: u8, + out: &mut (Vec, Vec, Vec), +) -> (u32, u32) { let steps = steps % 4; if steps == 0 || w == 0 || h == 0 { - return (y.to_vec(), u.to_vec(), v.to_vec(), w, h); + out.0.clear(); + out.0.extend_from_slice(y); + out.1.clear(); + out.1.extend_from_slice(u); + out.2.clear(); + out.2.extend_from_slice(v); + return (w, h); } let (cw, ch) = chroma_dims(w as usize, h as usize); - let (ry, rw, rh) = rotate_plane(y, w as usize, h as usize, steps); - let (ru, ..) = rotate_plane(u, cw, ch, steps); - let (rv, ..) = rotate_plane(v, cw, ch, steps); - (ry, ru, rv, rw as u32, rh as u32) + rotate_plane_into(y, w as usize, h as usize, steps, &mut out.0); + rotate_plane_into(u, cw, ch, steps, &mut out.1); + rotate_plane_into(v, cw, ch, steps, &mut out.2); + if steps == 2 { + (w, h) + } else { + (h, w) + } } -/// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise. -fn rotate_plane(src: &[u8], w: usize, h: usize, steps: u8) -> (Vec, usize, usize) { +/// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise, +/// written into `out` -- resized to the turned size, which is the source's +/// swapped at 90 and 270 and its own at 180. +fn rotate_plane_into(src: &[u8], w: usize, h: usize, steps: u8, out: &mut Vec) { match steps { 1 => { - let (nw, nh) = (h, w); - let mut out = vec![0u8; nw * nh]; - for yp in 0..nh { - for xp in 0..nw { - out[yp * nw + xp] = src[(h - 1 - xp) * w + yp]; + out.resize(h * w, 0); + for yp in 0..w { + for xp in 0..h { + out[yp * h + xp] = src[(h - 1 - xp) * w + yp]; } } - (out, nw, nh) } 2 => { - let mut out = vec![0u8; w * h]; + out.resize(w * h, 0); for yp in 0..h { for xp in 0..w { out[yp * w + xp] = src[(h - 1 - yp) * w + (w - 1 - xp)]; } } - (out, w, h) } 3 => { - let (nw, nh) = (h, w); - let mut out = vec![0u8; nw * nh]; - for yp in 0..nh { - for xp in 0..nw { - out[yp * nw + xp] = src[xp * w + (w - 1 - yp)]; + out.resize(h * w, 0); + for yp in 0..w { + for xp in 0..h { + out[yp * h + xp] = src[xp * w + (w - 1 - yp)]; } } - (out, nw, nh) } _ => unreachable!("steps % 4 is 1, 2 or 3 here"), } diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index 5768258..2b44aec 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -22,7 +22,7 @@ use engine::export::{ExportSettings, Format}; use engine::project::{Lane, LaneKind, Source, Speed}; use engine::scale::FitPolicy; use engine::scratch::Scratch; -use engine::{AudioSession, Clip, ExportHandle, Project}; +use engine::{AudioSession, Clip, ExportHandle, Project, Rotation}; const RATE: u32 = 44_100; @@ -378,6 +378,7 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() { frame_count: 60, codec: engine::Codec::H264, color: Default::default(), + rotation: Rotation::None, }; let out = out_path("still_song", "mp4"); let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); @@ -704,6 +705,7 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { frame_count: 60, codec: engine::Codec::H264, color: Default::default(), + rotation: Rotation::None, }; for want in [128u32, 320] { let out = out_path(&format!("mp4_aac_{want}"), "mp4"); @@ -1001,6 +1003,7 @@ fn a_fade_in_reaches_the_exported_audio() { frame_count: 90, codec: engine::Codec::H264, color: Default::default(), + rotation: Rotation::None, }; let out = out_path("fadein", "wav"); let handle = engine::export::start( @@ -1097,6 +1100,7 @@ fn a_split_and_crossfaded_clip_has_no_muted_interior() { frame_count: 90, codec: engine::Codec::H264, color: Default::default(), + rotation: Rotation::None, }; let out = out_path("crossfade", "wav"); let handle = engine::export::start( diff --git a/crates/engine/tests/audio_files.rs b/crates/engine/tests/audio_files.rs index 06ef38c..7a8c00f 100644 --- a/crates/engine/tests/audio_files.rs +++ b/crates/engine/tests/audio_files.rs @@ -18,8 +18,11 @@ use engine::{AudioSession, Clip, PlaybackSession, Project}; /// The fixtures `scripts/gen_fixtures.sh` writes: 3 s of 440 Hz left / 880 Hz /// right at 44.1k stereo, under a 1 Hz volume pulse -- the same tone /// `test_av.mp4` carries, so a song and a video clip share one timeline. -const CONTAINERS: [&str; 6] = [ +/// `test_tone.mpg` is the same MPEG audio stream under the standard's spelling +/// rather than the codec's; the cover-carrying `.mpeg` has its own test below. +const CONTAINERS: [&str; 7] = [ "test_tone.mp3", + "test_tone.mpg", "test_tone.wav", "test_tone.flac", "test_tone.ogg", @@ -791,6 +794,47 @@ fn an_audio_only_file_wearing_an_mp4_extension_still_opens() { assert!((session.timeline_duration() - 3.0).abs() < 0.1); } +/// An MPEG audio stream wearing the *standard's* spelling -- `.mpeg`, what a +/// voice note or a tagged download off the web is called -- with a JPEG cover +/// muxed into its ID3v2 tag beside the sound. Two claims, and the first is the +/// bug: the spelling has to reach the audio door at all (`is_audio`, and with +/// it every lane decision and the import itself). While the extension list did +/// not admit it the file fell through to the mp4 demuxer and the library door +/// answered `IMPORT FAILED: — file contains a box with a larger size +/// than it`, this test's `import`/`open` failing in exactly those words. The +/// second is that the cover is not mistaken for a picture: symphonia skips the +/// ID3v2 tag, the file opens audio-only, and the tone decodes non-silent. +#[test] +fn an_mpeg_audio_file_with_a_cover_stream_opens_and_imports() { + let name = "test_tone_cover.mpeg"; + let path = asset(name); + assert!(engine::is_audio(&path), "{name} is sound"); + + // The open door: a song *is* a timeline, and no cover stream puts a clip on + // the video lane. + let session = open(&path); + assert!( + session.lane_clips(Lane::V1).is_empty(), + "{name}: the cover is not a picture source" + ); + assert_eq!(session.lane_clips(Lane::A1).len(), 1); + assert!((session.timeline_duration() - 3.0).abs() < 0.1, "{name}"); + drop(session); + + // The library door the message came from: an import into a session that + // already has a timeline. + let mut session = open(asset("test_tone.mp3")); + import_and_place(&mut session, &path); + drop(session); + + let (rate, channels, samples) = decode(&path); + assert_eq!((rate, channels), (44100, 2), "{name}"); + let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels); + assert!((secs - 3.0).abs() < 0.1, "{name}: {secs:.3} s of audio"); + let peak = samples.iter().fold(0.0f32, |m, s| m.max(s.abs())); + assert!(peak > 0.05, "{name}: decoded everything silent (peak {peak})"); +} + /// The same fallback in [`PlaybackSession::open_project`]'s scaffold branch: a /// project whose first source is one of these files reloads instead of failing /// the open a save never had trouble with the first time. diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 881ccd1..8f915bc 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -35,7 +35,7 @@ use engine::mux::{AudioParams, Mp4Muxer, VideoParams, parameter_sets}; use engine::project::{Lane, Source, Speed}; use engine::scale::FitPolicy; use engine::scratch::Scratch; -use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; +use engine::{DecodeSession, ExportHandle, PlaybackSession, Project, Rotation}; use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; use ec_core::{Packet, TimeBase}; use ec_h264::H264Decoder; @@ -277,6 +277,7 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() { frame_count: 20, codec: engine::Codec::H264, color: Default::default(), + rotation: Rotation::None, }; let out = out_path("mixed"); let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); diff --git a/crates/engine/tests/hw_decode.rs b/crates/engine/tests/hw_decode.rs index c876e95..174bee6 100644 --- a/crates/engine/tests/hw_decode.rs +++ b/crates/engine/tests/hw_decode.rs @@ -19,6 +19,7 @@ use engine::DecodeSession; use engine::colorspace::{ColorDescription, Matrix}; use engine::convert::i420_to_bgra; use engine::demux::{Codec, Demuxer}; +use engine::mux::{self, Mp4Muxer, VideoParams}; use engine::scratch::Scratch; use engine::hw::HwSession; use engine::tonemap::{ToneMapper, Transfer}; @@ -477,3 +478,111 @@ fn av1_ten_bit_hardware_matches_software_on_every_frame() { eprintln!("frame 30 differing bytes: {diff} / {}", sw_frame_30.len()); assert_eq!(diff, 0, "hardware and software 10-bit AV1 decode disagree"); } + +/// Annex-B NAL payloads (start codes stripped, trailing zeros trimmed). +fn nals(annex_b: &[u8]) -> Vec<&[u8]> { + let mut out = Vec::new(); + let mut start = None; + let mut i = 0; + while i + 2 < annex_b.len() { + if annex_b[i] == 0 && annex_b[i + 1] == 0 && annex_b[i + 2] == 1 { + if let Some(s) = start { + out.push(&annex_b[s..i]); + } + i += 3; + start = Some(i); + } else { + i += 1; + } + } + if let Some(s) = start { + out.push(&annex_b[s..]); + } + out +} + +/// One access unit as a length-prefixed AVCC sample with `cabac_zero_word` -- +/// `zeros` zero bytes -- inside the *last* coded NAL's declared length. That is +/// byte-for-byte what a phone-camera encoder writes, and what a decoder that +/// stops consuming at the last NAL leaves behind as "not a NAL". +fn sample_with_trailing_zeros(annex_b: &[u8], zeros: usize) -> (Vec, bool) { + let mut coded: Vec<&[u8]> = Vec::new(); + let mut key = false; + for nal in nals(annex_b) { + let end = nal.iter().rposition(|&b| b != 0).map_or(0, |p| p + 1); + let nal = &nal[..end]; + if nal.is_empty() { + continue; + } + match nal[0] & 0x1f { + 7 | 8 | 6 | 9 => continue, // parameter sets/SEI live in avcC or are dropped + 5 => key = true, + _ => {} + } + coded.push(nal); + } + let mut sample = Vec::new(); + let last = coded.len().saturating_sub(1); + for (i, nal) in coded.iter().enumerate() { + let len = nal.len() + if i == last { zeros } else { 0 }; + sample.extend_from_slice(&(len as u32).to_be_bytes()); + sample.extend_from_slice(nal); + if i == last { + sample.extend(std::iter::repeat_n(0u8, zeros)); + } + } + (sample, key) +} + +/// An mp4 cut from `test_baseline.mp4` whose every H.264 sample ends in four +/// zero bytes. +fn write_trailing_zero_fixture(src: &Path, out: &Path, frames: usize) { + let (meta, mut demuxer) = Demuxer::open(src).expect("open fixture source"); + let first = demuxer.next_access_unit().expect("read").expect("au"); + let (sps, pps) = mux::parameter_sets(&first).expect("parameter sets in the first au"); + let mut muxer = Mp4Muxer::create( + out, + &VideoParams { + width: meta.width, + height: meta.height, + frame_rate: meta.frame_rate, + sps, + pps, + }, + None, + ) + .expect("create fixture"); + let (sample, key) = sample_with_trailing_zeros(&first, 4); + muxer.write_coded_sample(&sample, key).expect("first sample"); + for _ in 1..frames { + let Some(au) = demuxer.next_access_unit().expect("read") else { + break; + }; + let (sample, key) = sample_with_trailing_zeros(&au, 4); + muxer.write_coded_sample(&sample, key).expect("sample"); + } + muxer.finish().expect("finish fixture"); +} + +/// A phone-camera mp4 ends its every coded sample in `cabac_zero_word`. The +/// plugin consumed each access unit only up to the last NAL cros-codecs +/// reported and fed the leftover zero bytes back as if they were the next unit; +/// `Nalu::next` refuses a buffer with no start code ("No NAL found"), so the +/// whole session failed with code -2 before the first picture -- the export's +/// `hardware decode failed (code -2)` on a file VA-API otherwise decodes. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver"] +fn hardware_decodes_samples_with_trailing_zero_words() { + let out = Scratch::file("ve_hw_trailing_zeros", "mp4"); + write_trailing_zero_fixture(&asset("test_baseline.mp4"), &out, 30); + let mut hw = open_hw(&out); + let mut count = 0usize; + while let Some((_, _, _, w, h)) = hw + .next_frame() + .expect("hardware decode of trailing-zero samples") + { + assert_eq!((w, h), (1280, 720), "frame {count} dims"); + count += 1; + } + assert_eq!(count, 30, "every picture decoded"); +} diff --git a/crates/engine/tests/rotation.rs b/crates/engine/tests/rotation.rs new file mode 100644 index 0000000..23ceb5a --- /dev/null +++ b/crates/engine/tests/rotation.rs @@ -0,0 +1,252 @@ +//! The display matrix: a file that says "turn me" is turned -- in the preview +//! and in the export, from the same numbers. +//! +//! A phone records a portrait video as a landscape picture plus a `tkhd` matrix +//! saying which way to turn it. Before this the engine read neither: the +//! preview showed a portrait clip on its side and an export re-coded the +//! landscape pixels with a unity matrix, so the file played sideways anywhere +//! -- the one rendition nobody ever wanted. +//! +//! `test_rotation90/180/270.mp4` (`scripts/gen_fixtures.sh`) are one 320x180 +//! source of four coloured quadrants written back out with a turn asked for, so +//! a single sampled pixel per corner names the layout and a *wrong direction* +//! cannot pass -- a 180-degree mix-up, a mirror, or "ignore it" each produce a +//! different set of four corners. The layouts asserted here are ffmpeg's own +//! autorotation of each file, measured rather than derived. +//! +//! `test_rotation45.mp4` is the other half of the contract: a matrix that is a +//! rotation but not a quarter turn has no correct rendition here, and it is +//! refused *by name* at the door rather than shown wrong. + +use std::path::{Path, PathBuf}; +use std::sync::Once; +use std::time::{Duration, Instant}; + +use engine::export::ExportSettings; +use engine::scratch::Scratch; +use engine::{DecodeSession, ExportHandle, PlaybackSession, Rotation}; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Which seat an export takes is decided by *process-wide* environment +/// variables, so a test binary that shares the machine has to borrow them +/// rather than assume: this pins both decode and encode to software, which is +/// the seat every machine has, and holds the borrow for the whole test binary. +static SEAT: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +type Shared = std::sync::RwLockReadGuard<'static, ()>; + +#[must_use = "the seat pin holds only while its guard is alive"] +fn pin_software() -> Shared { + let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner()); + static PIN: Once = Once::new(); + PIN.call_once(|| unsafe { + std::env::set_var("VE_SW", "1"); + std::env::set_var("VE_SW_ENC", "1"); + }); + borrowed +} + +fn out_path(name: &str) -> Scratch { + Scratch::file(&format!("ve_rotation_{name}"), "mp4") +} + +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < limit, + "export did not finish in {limit:?}" + ); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("a finished export has an outcome") +} + +/// What colour a decoded BGRA pixel is, by the quadrant it came from. ffmpeg's +/// `red`/`green`/`blue`/`yellow` are far apart enough that the chroma of a +/// 4:2:0 edge never reaches a quadrant's centre, and the labels are what the +/// fixture's own comment says it drew. +fn tint(bgra: &[u8]) -> &'static str { + let (b, g, r) = (bgra[0], bgra[1], bgra[2]); + let (r, g, b) = (r > 110, g > 90, b > 110); + match (r, g, b) { + (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 a 4:2:0 boundary +/// cannot 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; + tint(&bgra[index..index + 4]) + }; + let (qx, qy) = (width / 4, height / 4); + [at(qx, qy), at(3 * qx, qy), at(3 * qx, 3 * qy), at(qx, 3 * qy)] +} + +/// What the coded picture holds, before anything turns it: this is the layout +/// every expectation below is *not*. +const CODED: [&str; 4] = ["red", "green", "yellow", "blue"]; + +/// One frame of `path` and the size it came out at: the preview path exactly +/// ([`DecodeSession`] is the same funnel [`PlaybackSession`] paints from). +fn first_frame(path: &Path) -> (u32, u32, Vec) { + let (_, frames, _) = DecodeSession::open_at(path, 0).expect("open for a frame"); + let frame = frames.recv().expect("a first frame"); + (frame.width, frame.height, frame.bgra) +} + +/// The same four corners ffmpeg's own autorotation of each file produces -- +/// measured with `ffmpeg -i f.mp4 -f rawvideo -pix_fmt rgb24 -` on this +/// machine, which is the arbiter a display matrix is read against. +fn expected(file: &str) -> ([u32; 2], Rotation, [&'static str; 4]) { + match file { + "test_rotation90.mp4" => ( + [180, 320], + Rotation::Cw270, + ["green", "yellow", "blue", "red"], + ), + "test_rotation180.mp4" => ( + [320, 180], + Rotation::Cw180, + ["yellow", "blue", "red", "green"], + ), + "test_rotation270.mp4" => ( + [180, 320], + Rotation::Cw90, + ["blue", "red", "green", "yellow"], + ), + other => panic!("no expectation for {other}"), + } +} + +/// The header says which way the picture lies: a quarter turn swaps the +/// displayed size and names the turn, and a half turn does neither. +#[test] +fn a_display_matrix_is_read_as_a_quarter_turn() { + for file in [ + "test_rotation90.mp4", + "test_rotation180.mp4", + "test_rotation270.mp4", + ] { + let (size, rotation, _) = expected(file); + let (meta, _) = engine::demux::Demuxer::open(&asset(file)).expect("open a fixture"); + assert_eq!( + [meta.width, meta.height], + size, + "{file}: the *displayed* size is what the engine reports" + ); + assert_eq!(meta.rotation, rotation, "{file}: which turn the file asks for"); + assert_eq!( + rotation.swaps_axes(), + size == [180, 320], + "{file}: a swapped size and a swapping turn go together" + ); + } + // ...and the fixture's own coded picture is the layout none of these are, + // which is what makes the assertions above about the turn and not about the + // source. `test_rotation180.mp4` keeps its coded size, so the picture is + // where the turn is visible. + let (width, height, bgra) = first_frame(&asset("test_rotation180.mp4")); + assert_eq!((width, height), (320, 180)); + assert_ne!(corners(width, height, &bgra), CODED, "the turn was made"); +} + +/// The preview: the picture is turned before it is painted, at the size the +/// turn gives it. +#[test] +fn the_preview_shows_a_turned_file_upright() { + let _seat = pin_software(); + for file in [ + "test_rotation90.mp4", + "test_rotation180.mp4", + "test_rotation270.mp4", + ] { + let (size, _, corners_expected) = expected(file); + let (width, height, bgra) = first_frame(&asset(file)); + assert_eq!( + [width, height], + size, + "{file}: the painted picture is the displayed size" + ); + assert_eq!( + corners(width, height, &bgra), + corners_expected, + "{file}: every quadrant landed where the turn puts it" + ); + } +} + +/// The export: the turn is baked into the pixels, so the file plays upright +/// everywhere -- which means the output is portrait *and* declares no matrix of +/// its own. A file that kept the source's matrix and the source's landscape +/// pixels would satisfy neither half. +#[test] +fn an_export_of_a_turned_file_is_upright_and_portrait() { + let _seat = pin_software(); + let source = asset("test_rotation90.mp4"); + let mut session = PlaybackSession::open(&source).expect("open the fixture"); + session.pause(); + assert_eq!( + [session.meta().width, session.meta().height], + [180, 320], + "the timeline is the displayed shape, not the coded one" + ); + let out = out_path("upright"); + let handle = session.export_to_with(&out, &ExportSettings::default()); + wait(&handle, Duration::from_secs(60)).expect("export"); + + let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export"); + assert_eq!( + [meta.width, meta.height], + [180, 320], + "the written file is portrait" + ); + assert_eq!( + meta.rotation, + Rotation::None, + "and states no matrix: the turn is in the pixels" + ); + assert_eq!(meta.frame_count, 30, "every timeline frame was written"); + + let (width, height, bgra) = first_frame(&out); + assert_eq!([width, height], [180, 320]); + assert_eq!( + corners(width, height, &bgra), + ["green", "yellow", "blue", "red"], + "the exported pixels are the ones the preview showed" + ); +} + +/// A matrix that is not a quarter turn is refused by name at the door, with the +/// angle in the sentence -- the honest answer to a picture this engine has no +/// way to show right. The capability really is absent: nothing here turns by an +/// arbitrary angle ([`engine::scale::rotate_i420_90s`] takes whole quarters), +/// and the refusal is what says so instead of a sideways picture. +#[test] +fn a_matrix_that_is_not_a_quarter_turn_is_refused_by_name() { + let error = match engine::demux::Demuxer::open(&asset("test_rotation45.mp4")) { + Ok(_) => panic!("45 degrees is not a quarter turn, and opening it must not succeed"), + Err(error) => error, + }; + assert!( + engine::UnsupportedRotation::is_it(&error), + "the refusal is the named one, not a generic failure: {error}" + ); + let said = error.to_string(); + assert!( + said.contains("45.0°") && said.contains("quarter turn"), + "the refusal names the angle it cannot make: {said}" + ); +} diff --git a/crates/engine/tests/silent_first_source.rs b/crates/engine/tests/silent_first_source.rs new file mode 100644 index 0000000..af0de58 --- /dev/null +++ b/crates/engine/tests/silent_first_source.rs @@ -0,0 +1,153 @@ +//! A silent leading source must not silence the timeline for good. +//! +//! The reported sequence: (1) a video with no audio track is added to the +//! timeline, (2) it is removed, (3) another file -- one that *does* have audio +//! -- is added. The engine used to pin the session to its first source: the +//! device was opened (or, here, not opened) from that one file and never +//! re-armed, and the import door refused the newcomer outright ("the file has +//! audio, the timeline is silent"). So the second file's picture showed but its +//! audio was silent -- or the file could not join at all. +//! +//! Three seams held that pin, and each is covered here: +//! - the import gate (`audio_matches_probed` / `first_audio_of`) refused a file +//! with sound onto a timeline whose leading source has none; +//! - the session never opened a device when such a file did join +//! (`PlaybackSession::arm_audio`); +//! - playback itself re-picked the first non-image source and returned +//! `Ok(None)` -- silence -- however many later segments named a source with +//! audio (`AudioSession::open_multi_streams_speed_at_fade`). +//! +//! ```text +//! cargo test -p engine --test silent_first_source -- --nocapture +//! ``` + +use std::path::{Path, PathBuf}; +use std::thread::sleep; +use std::time::{Duration, Instant}; + +use engine::{AudioSession, PlaybackSession}; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// The real phone clip the report named, when it is on this machine: mono-ish +/// ambient at about -36 dBFS, so the "non-silent" bar is its own peak, not a +/// loud fixture's. Skipped (and the run says so) when the file is absent. +fn real_clip() -> Option { + let path = PathBuf::from("/home/tahinli/Downloads/real_clip.mp4"); + path.is_file().then_some(path) +} + +fn peak(session: &PlaybackSession) -> f32 { + session + .audio_tap() + .map(|(s, _)| s.iter().fold(0.0f32, |m, s| m.max(s.abs()))) + .unwrap_or(0.0) +} + +fn pump(session: &mut PlaybackSession, secs: f64) -> f32 { + let deadline = Instant::now() + Duration::from_secs_f64(secs); + let mut best = 0.0f32; + while Instant::now() < deadline { + session.tick(); + best = best.max(peak(session)); + sleep(Duration::from_millis(8)); + } + best +} + +fn remove_all_clips(session: &mut PlaybackSession) { + for lane in session.lanes() { + let mut i = session.lane_clips(lane).len(); + while i > 0 { + i -= 1; + session.delete_clip(lane, i); + } + } +} + +/// The app's own import door: the gate taken off the live session, the probe +/// read off it (what the worker does), then the registration. +fn app_import(session: &mut PlaybackSession, b: &Path) -> engine::Result { + let gate = session.import_gate(); + let probe = PlaybackSession::probe_import(gate, b)?; + session.import_probed(b, probe) +} + +/// The reported add/remove/add, end to end at the session level: a silent first +/// file, removed from the timeline, then a file with sound imported into the +/// *same* session and placed -- its audio must decode non-silent. +fn add_remove_add(a: &Path, b: &Path, loud: f32) { + let mut session = PlaybackSession::open_library(a).expect("open_library A"); + session.set_gain(0.0); + + // (1) A joins the timeline. Silent by nature: no track to open a device on. + let end = session.timeline_duration(); + assert!( + session.place_stream_at(end, a, 0, None).expect("place A"), + "A lands" + ); + session.play(); + let a_peak = pump(&mut session, 1.5); + assert!(a_peak < 0.01, "A must be silent, got {a_peak}"); + session.pause(); + session.seek(0.0); + + // (2) A comes off the timeline; the library keeps it. + remove_all_clips(&mut session); + + // (3) B joins the library through the app's own door, then the timeline. + app_import(&mut session, b).expect("B must be admitted onto a silent timeline"); + assert!( + session.audio_disabled_reason().is_none(), + "the device was not armed for B: {:?}", + session.audio_disabled_reason() + ); + let end = session.timeline_duration(); + assert!( + session.place_stream_at(end, b, 0, None).expect("place B"), + "B lands" + ); + session.play(); + let b_peak = pump(&mut session, 2.5); + assert!( + b_peak > loud, + "B's audio is silent after the sequence: peak {b_peak}" + ); +} + +#[test] +fn a_second_file_with_sound_is_heard_after_a_silent_first_file() { + add_remove_add(&asset("test_baseline.mp4"), &asset("test_av2.mp4"), 0.05); +} + +/// The same sequence with the report's own file as the second import. +#[test] +fn the_reports_second_file_is_heard_too() { + match real_clip() { + Some(real) => add_remove_add(&asset("test_baseline.mp4"), &real, 0.02), + None => eprintln!("SKIPPED: {} is not on this machine", "/home/tahinli/Downloads/real_clip.mp4"), + } +} + +/// The playback seam on its own: a segment naming the second source must decode +/// that source's samples even though the first source has no track. Pre-fix +/// this returned `Ok(None)` -- the whole timeline silent. +#[test] +fn playback_walks_past_a_trackless_leading_source() { + let sources = vec![(asset("test_baseline.mp4"), 0usize), (asset("test_av2.mp4"), 0usize)]; + let segs = vec![(Some(1usize), 0.0f64, f64::INFINITY)]; + let (_, rx) = AudioSession::open_multi_streams(&sources, &segs) + .expect("open the second source's audio") + .expect("the second source has a track"); + let (mut n, mut peak) = (0usize, 0.0f32); + for chunk in rx { + n += chunk.samples.len(); + peak = chunk.samples.iter().fold(peak, |m, s| m.max(s.abs())); + } + assert!(n > 0, "nothing decoded"); + assert!(peak > 0.05, "the second source's audio is silent: peak {peak}"); +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 60a2e27..8e287c5 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -572,6 +572,26 @@ for fmt in mp3 wav flac ogg m4a aac; do -filter_complex "$tone" -map "[a]" -ar 44100 "${codec[@]}" \ "assets/test_tone.$fmt" done +# ...and the same tone in the MPEG audio spellings an encoder names after the +# standard rather than the codec (`.mpeg`/`.mpg`), carrying a JPEG cover in its +# ID3v2 tag -- the shape a voice note or a tagged download has. `-f mp3` is what +# makes it an MPEG *audio* stream: left to the extension, ffmpeg would write an +# MPEG program stream instead, which is a different file that this engine has no +# demuxer for. `test_tone_cover.jpg` is the cover it muxes in; a reader that +# walked the file as an mp4 saw only `InvalidData("file contains a box with a +# larger size than it")` before `is_audio` admitted the spelling. +ffmpeg -y -f lavfi -i "color=c=blue:s=64x64:d=1" -frames:v 1 \ + "assets/test_tone_cover.jpg" +ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \ + -f lavfi -i "sine=frequency=880:duration=3" \ + -i "assets/test_tone_cover.jpg" \ + -filter_complex "$tone" -map "[a]" -map 2:v -ar 44100 \ + -c:a libmp3lame -b:a 128k -c:v mjpeg -disposition:v attached_pic \ + -id3v2_version 3 -f mp3 "assets/test_tone_cover.mpeg" +ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \ + -f lavfi -i "sine=frequency=880:duration=3" \ + -filter_complex "$tone" -map "[a]" -ar 44100 \ + -c:a libmp3lame -b:a 128k -id3v2_version 3 -f mp3 "assets/test_tone.mpg" # The two Opus fixtures, which cannot join the loop above: Opus decodes at 48 kHz # and nothing else, so these are the 48k twins of the tone rather than 44.1k ones. # First the standalone `.opus`, an Ogg file `crate::is_audio` now admits. @@ -672,4 +692,44 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=24:duration=2 \ -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ -c:a aac -b:a 96k -f mov assets/test_qt.mov +# The display matrix: `test_rotation*.mp4` are one 320x180 source -- four +# coloured quadrants, so a quarter turn is readable from a single sampled pixel +# per corner and a wrong direction cannot pass -- written back out with a +# rotation asked for. This is how a phone records a portrait video: the pixels +# stay landscape and the container says which way to turn them. +# +# The trap this recipe exists to avoid: `-metadata:s:v rotate=90`, the form +# every search result gives, writes **no display matrix at all** with this +# machine's ffmpeg (`ffprobe -show_streams` comes back with an empty side-data +# block, so a "rotated" fixture is really an unrotated one and the test passes +# against nothing). `-display_rotation` is a *muxer* option here and, being an +# input option, goes **before** the `-i` it applies to. +# +# The four quadrants are red, green, blue and yellow: +# +# coded -display_rotation 90 -display_rotation 180 +# red green green yellow yellow blue +# blue yellow red blue green red +# +# which is exactly ffmpeg's own autorotation of each file -- measured +# (`ffmpeg -i f.mp4 -f rawvideo -pix_fmt rgb24 -`) rather than derived, because +# which way a display matrix turns a picture is the one thing a reader has to be +# told rather than guess. `tests/rotation.rs` asserts those layouts. +# +# `-display_rotation 45` is the other half: a matrix that is a rotation and not +# a *quarter* turn, which this engine refuses by name (`demux::UnsupportedRotation`) +# instead of showing it sideways. +ffmpeg -y -f lavfi -i "color=c=red:s=160x90:d=1:r=30,format=yuv420p" \ + -f lavfi -i "color=c=green:s=160x90:d=1:r=30,format=yuv420p" \ + -f lavfi -i "color=c=blue:s=160x90:d=1:r=30,format=yuv420p" \ + -f lavfi -i "color=c=yellow:s=160x90:d=1:r=30,format=yuv420p" \ + -filter_complex "[0:v][1:v]hstack[top];[2:v][3:v]hstack[bot];[top][bot]vstack[v]" \ + -map "[v]" -frames:v 30 -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ + assets/.rotation_src.mp4 +for deg in 90 180 270 45; do + ffmpeg -y -display_rotation "$deg" -i assets/.rotation_src.mp4 \ + -c copy "assets/test_rotation$deg.mp4" +done +rm -f assets/.rotation_src.mp4 + echo "fixtures written to assets/"