forge
Explore
Log in

Don't you dare go Hollow

Audio routing, session audio re-arm, hw trailing-zero NALs, display-matrix rotation

Browse files at this commit

bc8b82ec886ecf333b55eb26c2194d40a42a1dc3Ahmet Kaan GümüşParent: eecc8f5
  • fix
    • audio routing, session audio re-arm, hw trailing-zero NALs, display-matrix rotation
Show full message
🐛 fix(media): audio routing, session audio re-arm, hw trailing-zero NALs, display-matrix rotation

- 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.rsmodified+6 -0
@@ -1407,6 +1407,12 @@ impl Player {
14071407 .as_mut()
14081408 .and_then(|session| subtitle_tail(session, subs))
14091409 .unwrap_or_default();
1410+ // A file with sound joining a session that opened silent is the
1411+ // one import that *arms* the audio device
1412+ // ([`engine::PlaybackSession::arm_audio`]); it comes up at full
1413+ // volume, so the player's own level and mute are pushed at it
1414+ // again here or a muted window would play.
1415+ self.apply_volume();
14101416 format!(
14111417 "IMPORTED {} to the library{tail}{}",
14121418 file_name(path),
crates/engine-hw/src/lib.rsmodified+21 -0
@@ -162,6 +162,15 @@ const DMA_HOLD: usize = 6;
162162 /// real seek wins.
163163 const FORWARD_SECS: f64 = 0.5;
164164
165+/// Whether `data` still holds a NAL unit: the same `00 00 01` scan
166+/// cros-codecs' `Nalu::next`/`find_start_code` uses to frame Annex B. `false`
167+/// for the `trailing_zero_8bits` / `cabac_zero_word` that may trail the last
168+/// NAL of an access unit -- bytes that are part of the stream but not a unit
169+/// any decoder will parse.
170+fn has_start_code(data: &[u8]) -> bool {
171+ data.windows(3).any(|w| w == [0x00, 0x00, 0x01])
172+}
173+
165174 /// The forward reach in frames: [`FORWARD_SECS`] at the stream's own rate.
166175 /// `0` for a rate the stream does not really state, which is "never forward"
167176 /// -- exactly the flush every reposition did before this distinction existed.
@@ -559,6 +568,18 @@ impl Session {
559568 Ok(0) => return Err("decoder consumed no input".into()),
560569 Ok(n) => {
561570 pending.drain(..n.min(pending.len()));
571+ // cros-codecs reports the bytes of the NAL it consumed, and
572+ // that length excludes the `trailing_zero_8bits` /
573+ // `cabac_zero_word` an encoder may append after the *last*
574+ // NAL of an access unit (H.264 7.4.1.2.3). Those leftovers
575+ // are not a NAL: feeding them back makes `Nalu::next` fail
576+ // with "No NAL found", which is a hard session failure for
577+ // an otherwise decodable file -- measured on a phone-camera
578+ // mp4 whose every sample ends in zero words. The access unit
579+ // is consumed when no start code is left in it.
580+ if !has_start_code(pending) {
581+ pending.clear();
582+ }
562583 if pending.is_empty() {
563584 *timestamp += 1;
564585 }
crates/engine/src/audio.rsmodified+35 -14
@@ -413,20 +413,41 @@ impl AudioSession {
413413 fps: f64,
414414 sample_rate: Option<u32>,
415415 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
416- // The first source that could have a track, which is not always index 0:
417- // a still image has none, and one at the front of the list (a save
418- // renumbers, a library removal moves indexes) would be opened as a
419- // broken audio file and take the whole timeline's sound down with it.
420- // The same rule `PlaybackSession` probes by (`audio_source_of`).
421- let Some((at, (path, stream))) = sources
422- .iter()
423- .enumerate()
424- .find(|(_, (path, _))| !crate::is_image(path))
425- else {
426- return Ok(None);
427- };
428- let Some(first) = Track::open(path, *stream)? else {
429- return Ok(None);
416+ // The first source that really *opens* a track, which is not always
417+ // index 0 and not always the first non-image one: a still image has no
418+ // track by definition, and a video whose file carries none (a screen
419+ // recording with no sound) has `Track::open` answer `None`. Pinning to
420+ // the first non-image source regardless would return `Ok(None)` for a
421+ // whole timeline whenever that one source happened to be silent,
422+ // silencing every later clip that does have sound -- the very failure
423+ // `PlaybackSession::open_project`'s device walk exists to prevent, and
424+ // it has to hold here too or the walk is defeated at playback.
425+ //
426+ // A source that cannot be opened at all is skipped like a silent one,
427+ // so a broken file at the head of the list cannot take a later clip's
428+ // sound down with it; the last error is kept and returned only when
429+ // *nothing* opens, which is today's answer for a timeline of one broken
430+ // source.
431+ let mut first: Option<(usize, Track)> = None;
432+ let mut refused: Option<crate::Error> = None;
433+ for (at, (path, stream)) in sources.iter().enumerate() {
434+ if crate::is_image(path) {
435+ continue;
436+ }
437+ match Track::open(path, *stream) {
438+ Ok(Some(track)) => {
439+ first = Some((at, track));
440+ break;
441+ }
442+ Ok(None) => {}
443+ Err(e) => refused = Some(e),
444+ }
445+ }
446+ let Some((at, first)) = first else {
447+ return match refused {
448+ Some(e) => Err(e),
449+ None => Ok(None),
450+ };
430451 };
431452 // The timeline's meta is that source's: policy makes every other source
432453 // match it, and the checks below hold them to that.
crates/engine/src/decode.rsmodified+56 -2
@@ -18,7 +18,7 @@ use ec_h264::H264Decoder;
1818 use crate::color::ColorParams;
1919 use crate::colorspace::{ColorDescription, Matrix, Transfer};
2020 use crate::convert::{i420_to_bgra, i420_to_bgra_with};
21-use crate::demux::{Codec, Demuxer, VideoMeta};
21+use crate::demux::{Codec, Demuxer, Rotation, VideoMeta};
2222 use crate::hw::HwSession;
2323 use crate::project::Speed;
2424 use crate::scale::Composer;
@@ -561,6 +561,8 @@ impl DecodeSession {
561561 let first = Render::new(
562562 color,
563563 transform,
564+ // A still has no display matrix: what the file holds is what it is.
565+ Rotation::None,
564566 ColorDescription::default(),
565567 canvas,
566568 tonemap::Preset::default(),
@@ -674,6 +676,8 @@ impl DecodeSession {
674676 let mut render = Render::new(
675677 color,
676678 transform,
679+ // Painted here, at the canvas's own size: nothing turned it.
680+ Rotation::None,
677681 ColorDescription::default(),
678682 canvas,
679683 tonemap::Preset::default(),
@@ -1081,7 +1085,15 @@ fn run_span(
10811085 // The stream's own colour and peak brightness: properties of the stream, so
10821086 // neither can change while one range decodes -- but the grade, the canvas
10831087 // and the rendition are the *span's*, so this is built per span.
1084- let mut render = Render::new(color, transform, opened.meta.color, canvas, tone, opened.peak);
1088+ let mut render = Render::new(
1089+ color,
1090+ transform,
1091+ opened.meta.rotation,
1092+ opened.meta.color,
1093+ canvas,
1094+ tone,
1095+ opened.peak,
1096+ );
10851097 if let Some(reused) = opened.position_hw(path, start) {
10861098 // Cancelled during the init (or the seek): leave without decoding.
10871099 if abort.hit() {
@@ -1152,6 +1164,13 @@ struct Render {
11521164 /// This clip's placement, on top of whatever the canvas's own fit policy
11531165 /// already does ([`crate::scale::Composer::place_transformed`]).
11541166 transform: TransformParams,
1167+ /// How far the *file* asks its picture to be turned before anything else
1168+ /// happens to it ([`crate::demux::Rotation`]): the phone-portrait turn,
1169+ /// made here so the grade, the canvas and the preview's own renderer all
1170+ /// see the picture the way it is meant to be seen. [`Rotation::None`] for
1171+ /// every file that states no turn, which is the whole of an ordinary
1172+ /// library.
1173+ rotation: Rotation,
11551174 /// What the source's samples mean -- the stream's own matrix and range,
11561175 /// which is what the conversion below is done in rather than the BT.601 it
11571176 /// used to assume of every file.
@@ -1166,6 +1185,10 @@ struct Render {
11661185 /// across the worker's whole range. Empty unless the clip needs one: it is
11671186 /// tone-mapped in place, graded in place, or both.
11681187 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
1188+ /// The same, for the display-matrix turn above: empty for every file that
1189+ /// asks for none, and resized once for one that does -- a steady-state
1190+ /// buffer rather than three plane allocations per decoded frame.
1191+ turned: (Vec<u8>, Vec<u8>, Vec<u8>),
11691192 /// Where [`Composer::place_transformed`]'s owned picture lands, so a
11701193 /// transformed frame's planes live as long as `self` -- matching what
11711194 /// [`Composer::place`] already hands back by borrowing `self.canvas`.
@@ -1188,6 +1211,7 @@ impl Render {
11881211 fn new(
11891212 color: ColorParams,
11901213 transform: TransformParams,
1214+ rotation: Rotation,
11911215 desc: ColorDescription,
11921216 canvas: Composer,
11931217 preset: tonemap::Preset,
@@ -1196,6 +1220,7 @@ impl Render {
11961220 Self {
11971221 color,
11981222 transform,
1223+ rotation,
11991224 desc,
12001225 canvas,
12011226 // corner-cut: the ceiling is that the map reads limited-range codes
@@ -1209,6 +1234,7 @@ impl Render {
12091234 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)),
12101235 },
12111236 graded: (Vec::new(), Vec::new(), Vec::new()),
1237+ turned: (Vec::new(), Vec::new(), Vec::new()),
12121238 placed: (Vec::new(), Vec::new(), Vec::new()),
12131239 }
12141240 }
@@ -1222,6 +1248,34 @@ impl Render {
12221248 width: u32,
12231249 height: u32,
12241250 ) -> Frame {
1251+ // The file's own turn, before anything else: a phone's portrait video
1252+ // arrives as landscape planes, and the grade, the canvas and the
1253+ // conversion below all have to see the picture the way it is meant to
1254+ // be seen. Nothing here at all for the ordinary file that states no
1255+ // turn -- `Rotation::None` takes the planes by reference and not one
1256+ // byte is copied.
1257+ let (y, u, v, width, height) = match self.rotation.is_none() {
1258+ true => (y, u, v, width, height),
1259+ false => {
1260+ let steps = self.rotation.steps();
1261+ let (rw, rh) = crate::scale::rotate_i420_90s_into(
1262+ y,
1263+ u,
1264+ v,
1265+ width,
1266+ height,
1267+ steps,
1268+ &mut self.turned,
1269+ );
1270+ (
1271+ &self.turned.0[..],
1272+ &self.turned.1[..],
1273+ &self.turned.2[..],
1274+ rw,
1275+ rh,
1276+ )
1277+ }
1278+ };
12251279 let passthrough = self.canvas.is_passthrough(width, height);
12261280 // A transform still has a picture to place even where the canvas
12271281 // itself would hand this size back untouched -- moving, scaling,
crates/engine/src/demux.rsmodified+189 -2
@@ -267,9 +267,102 @@ impl NoVideoTrack {
267267 }
268268 }
269269
270+/// How far a container's display matrix says the picture must be turned to be
271+/// seen the way it was shot: quarter turns **clockwise**, the direction
272+/// [`crate::scale::rotate_i420_90s`] takes and the one a clip's own
273+/// [`TransformParams`](crate::transform::TransformParams) rotate is measured
274+/// in.
275+///
276+/// This is metadata about the *pixels*, not a user's edit: an mp4's `tkhd`
277+/// matrix, a phone's 90-degree turn, and every consumer of this engine's
278+/// pictures -- the preview and the encoder alike -- has to make it, or the film
279+/// plays and exports sideways. [`VideoMeta::width`] and
280+/// [`VideoMeta::height`] are therefore the *displayed* size: the coded picture
281+/// is the swapped one, and every picture this engine hands out is turned to
282+/// match. A container asking for anything that is not a right angle is refused
283+/// at the door ([`UnsupportedRotation`]) rather than shown wrong.
284+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
285+pub enum Rotation {
286+ #[default]
287+ None,
288+ Cw90,
289+ Cw180,
290+ Cw270,
291+}
292+
293+impl Rotation {
294+ /// Quarter turns clockwise, the count
295+ /// [`crate::scale::rotate_i420_90s`] applies.
296+ pub fn steps(self) -> u8 {
297+ match self {
298+ Rotation::None => 0,
299+ Rotation::Cw90 => 1,
300+ Rotation::Cw180 => 2,
301+ Rotation::Cw270 => 3,
302+ }
303+ }
304+
305+ /// Whether the turned picture's width and height are the coded ones
306+ /// swapped.
307+ pub fn swaps_axes(self) -> bool {
308+ matches!(self, Rotation::Cw90 | Rotation::Cw270)
309+ }
310+
311+ /// Whether there is anything to do at all, asked exactly as
312+ /// [`TransformParams::is_identity`](crate::transform::TransformParams::is_identity)
313+ /// is: the common case of a file that was shot the way it is stored.
314+ pub fn is_none(self) -> bool {
315+ matches!(self, Rotation::None)
316+ }
317+}
318+
319+/// A container that asks for a turn this engine cannot make: a display matrix
320+/// that is not a pure right-angle rotation -- a mirror, a shear, or an angle
321+/// that is not a multiple of 90 degrees.
322+///
323+/// Named and refused rather than ignored, for [`NoVideoTrack`]'s reason prose
324+/// might have to be reworded: a file whose picture is 45 degrees off has no
325+/// correct rendition here, and showing it sideways is a wrong picture rather
326+/// than a missing feature. The `Display` is what a user is refused by.
327+#[derive(Debug)]
328+pub struct UnsupportedRotation {
329+ /// The angle the matrix states, where it states one at all -- `None` for a
330+ /// mirror or a shear, which is not one -- for the sentence only.
331+ pub degrees: Option<f64>,
332+}
333+
334+impl std::fmt::Display for UnsupportedRotation {
335+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
336+ match self.degrees {
337+ Some(degrees) => write!(
338+ f,
339+ "this file carries a display matrix of {degrees:.1}°, which is not a quarter \
340+ turn; only 0°, 90°, 180° and 270° can be straightened here"
341+ ),
342+ None => f.write_str(
343+ "this file's display matrix is not a rotation at all (a mirror or a shear); only \
344+ 0°, 90°, 180° and 270° can be straightened here",
345+ ),
346+ }
347+ }
348+}
349+
350+impl std::error::Error for UnsupportedRotation {}
351+
352+impl UnsupportedRotation {
353+ /// Whether `error` is one of these, however deep in a `Box` it is --
354+ /// [`NoVideoTrack::is_it`]'s twin.
355+ pub fn is_it(error: &crate::Error) -> bool {
356+ error.downcast_ref::<Self>().is_some()
357+ }
358+}
359+
270360 #[derive(Debug, Clone, Copy, PartialEq)]
271361 pub struct VideoMeta {
362+ /// The displayed width: the coded one, swapped where the file's display
363+ /// matrix is a 90- or 270-degree turn (see [`Rotation`]).
272364 pub width: u32,
365+ /// The displayed height; see [`VideoMeta::width`].
273366 pub height: u32,
274367 pub frame_rate: f64,
275368 pub frame_count: u32,
@@ -278,6 +371,14 @@ pub struct VideoMeta {
278371 /// which range -- resolved off the container's tags, the bitstream's, and
279372 /// the resolution, in that order. See [`crate::colorspace`].
280373 pub color: ColorDescription,
374+ /// How far the picture must be turned to be seen right, off the
375+ /// container's display matrix. [`Rotation::None`] for everything whose
376+ /// container states no turn, and for a Matroska file: only the mp4 half is
377+ /// read today, because Matroska's own spelling (a `ProjectionPoseYaw`
378+ /// element) is written by nobody in practice while the `tkhd` matrix is how
379+ /// every phone records it. That is a known gap and not a silent one:
380+ /// [`MkvDemuxer::open`] says where a reader for it would go.
381+ pub rotation: Rotation,
281382 }
282383
283384 /// What a file spends its bytes at, in bits per second -- the whole file, and
@@ -730,15 +831,41 @@ impl Mp4Demuxer {
730831 .ok_or_else(|| mp4_no_video(path, &reader))?;
731832
732833 let track_id = track.track_id();
834+ // The turn the file was shot at, off its `tkhd` display matrix -- how
835+ // every phone records "this is portrait". `track.width()`/`height()` are
836+ // the *coded* ones for an H.264 track (the `avc1` sample entry), so a
837+ // quarter turn is what makes this file's displayed size the swapped one,
838+ // and the whole engine reads these two as the picture's size.
839+ let rotation = match reader
840+ .moov
841+ .traks
842+ .iter()
843+ .find(|trak| trak.tkhd.track_id == track_id)
844+ {
845+ // The values, not the type: `mp4`'s `tkhd` module is `pub(crate)`,
846+ // so its `Matrix` cannot be named here -- but its fields are public
847+ // and the four linear ones are all this needs.
848+ Some(trak) => {
849+ let m = &trak.tkhd.matrix;
850+ rotation_of_matrix(m.a, m.b, m.c, m.d)?
851+ }
852+ None => Rotation::None,
853+ };
854+ let (coded_w, coded_h) = (u32::from(track.width()), u32::from(track.height()));
855+ let (width, height) = match rotation.swaps_axes() {
856+ true => (coded_h, coded_w),
857+ false => (coded_w, coded_h),
858+ };
733859 let meta = VideoMeta {
734- width: track.width() as u32,
735- height: track.height() as u32,
860+ width,
861+ height,
736862 frame_rate: frame_rate(track),
737863 frame_count: 0,
738864 codec,
739865 // Filled below, once the parameter sets the bitstream tier reads are
740866 // in hand.
741867 color: ColorDescription::default(),
868+ rotation,
742869 };
743870 let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track));
744871 let mut parameter_sets = Vec::new();
@@ -1196,6 +1323,11 @@ impl MkvDemuxer {
11961323 bitstream_tags(video.codec, &mkv.config),
11971324 video.height,
11981325 ),
1326+ // FLAG: Matroska's turn is not read yet -- see [`VideoMeta::rotation`].
1327+ // Nothing in this tree writes a `ProjectionPoseYaw`, and the mkv
1328+ // tracks a phone or a camera app produces are mp4s; a `.mkv` that
1329+ // does carry one would play sideways until this is written.
1330+ rotation: Rotation::None,
11991331 };
12001332 Ok((meta, mkv))
12011333 }
@@ -2497,6 +2629,61 @@ fn parse_av1c(rec: &[u8]) -> crate::Result<(Vec<u8>, u8)> {
24972629 Ok((rec.get(4..).unwrap_or_default().to_vec(), bit_depth))
24982630 }
24992631
2632+/// The quarter turns an mp4 `tkhd` display matrix asks for, or an
2633+/// [`UnsupportedRotation`] where it asks for something else.
2634+///
2635+/// The matrix is the ISO 14496-12 §8.3.2 3x3 affine, stored as nine 16.16
2636+/// fixed-point values in the order `a b u c d v x y w`; only the four linear
2637+/// ones matter here, and only as a rotation: the values are normalised by the
2638+/// matrix's own scale so a differently-scaled copy of a quarter turn still
2639+/// reads as one, and anything that is not a pure right-angle turn -- a mirror
2640+/// (a negative determinant), a shear, a 45-degree phone quirk -- is refused by
2641+/// name rather than shown sideways.
2642+///
2643+/// The direction is this engine's: the linear part is `[[a, c], [b, d]]` (a
2644+/// point maps to `(a*x + c*y, b*x + d*y)`), so `atan2(b, a)` is the clockwise
2645+/// angle when `(a, b)` is the turned x-axis, and the quarter count it falls on
2646+/// is exactly what [`crate::scale::rotate_i420_90s`] applies. Measured against
2647+/// ffmpeg's own autorotate on the `test_rotation*.mp4` fixtures
2648+/// (`scripts/gen_fixtures.sh`): a `tkhd` matrix of `a=0, b=-65536, c=65536,
2649+/// d=0` -- what `-display_rotation 90` writes, and what a phone's portrait
2650+/// video carries -- is [`Rotation::Cw270`] here, the quarter turn that puts the
2651+/// coded left edge at the top.
2652+fn rotation_of_matrix(a: i32, b: i32, c: i32, d: i32) -> crate::Result<Rotation> {
2653+ let fixed = |raw: i32| f64::from(raw) / 65536.0;
2654+ let (a, b, c, d) = (fixed(a), fixed(b), fixed(c), fixed(d));
2655+ let scale = a.hypot(b);
2656+ let unsupported = || -> crate::Error {
2657+ crate::Error::from(UnsupportedRotation {
2658+ // The honest number where the matrix states one at all; a mirror or
2659+ // a shear has no angle, and 0.0 would be a claim rather than a
2660+ // reading.
2661+ degrees: (scale > 0.0).then(|| b.atan2(a).to_degrees()),
2662+ })
2663+ };
2664+ // Pure and isotropic: both columns the same length, and one the other's
2665+ // quarter turn (`d == a`, `-c == b` after normalising) -- no shear, no
2666+ // anisotropic scale.
2667+ if scale == 0.0
2668+ || (scale - c.hypot(d)).abs() > 1e-3
2669+ || ((a - d) / scale).abs() > 1e-3
2670+ || ((b + c) / scale).abs() > 1e-3
2671+ {
2672+ return Err(unsupported());
2673+ }
2674+ let degrees = b.atan2(a).to_degrees();
2675+ let steps = (degrees / 90.0).round();
2676+ if (degrees - steps * 90.0).abs() > 0.5 {
2677+ return Err(unsupported());
2678+ }
2679+ Ok(match steps.rem_euclid(4.0) as u8 {
2680+ 0 => Rotation::None,
2681+ 1 => Rotation::Cw90,
2682+ 2 => Rotation::Cw180,
2683+ _ => Rotation::Cw270,
2684+ })
2685+}
2686+
25002687 /// Why an mp4 came back with no picture, by the fourcc of the video track it
25012688 /// does carry: `avc3` and `mp4v` are files with video in them, and telling their
25022689 /// owner there is none sends them looking for a fault that is not in the file.
crates/engine/src/export.rsmodified+113 -28
@@ -80,7 +80,7 @@ use oxideav_core::Muxer as _;
8080
8181 use crate::audio::{AudioMeta, AudioSession};
8282 use crate::colorspace::{ColorDescription, Matrix, Transfer};
83-use crate::demux::{Codec, Demuxer, MkvDemuxer, VideoMeta};
83+use crate::demux::{Codec, Demuxer, MkvDemuxer, Rotation, VideoMeta};
8484 use crate::hw::{DmaFrame, DmaWant, HwEncoder, HwPicture, HwSession};
8585 use crate::mux::{
8686 AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams,
@@ -1174,7 +1174,13 @@ struct Dissolve<'a> {
11741174 remap: Option<(Matrix, Matrix)>,
11751175 grade: Option<crate::color::ColorParams>,
11761176 transform: TransformParams,
1177+ /// B's own file's display-matrix turn, [`place_picture`]'s first stage;
1178+ /// B is a different file and may be turned differently from A.
1179+ rotation: Rotation,
11771180 canvas: Composer,
1181+ /// The turn's, the grade's and the transform's scratch, exactly as A's
1182+ /// span keeps them: refilled per picture, allocated once.
1183+ rotated: (Vec<u8>, Vec<u8>, Vec<u8>),
11781184 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
11791185 transformed: (Vec<u8>, Vec<u8>, Vec<u8>),
11801186 }
@@ -1801,7 +1807,14 @@ impl CopyPlan {
18011807 // The stream this file would carry, at the size and the rate the
18021808 // timeline is in: anything else is a picture that has to be
18031809 // coded again to become this file's.
1804- if source_meta.codec != codec
1810+ //
1811+ // A source whose display matrix asks for a turn is one of
1812+ // those: a copied packet is the source's own coded picture, and
1813+ // this export bakes the turn into the pixels -- so a copy would
1814+ // ship the file sideways. Re-encoding is the only honest
1815+ // answer here.
1816+ if !source_meta.rotation.is_none()
1817+ || source_meta.codec != codec
18051818 || source_meta.width != meta.width
18061819 || source_meta.height != meta.height
18071820 || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()?
@@ -2652,7 +2665,7 @@ fn run(
26522665 // samples *mean* ([`ColorDescription`]), which is what decides whether they
26532666 // are remapped on the way in. Real time for a still, a song and a
26542667 // single-rate project, where every conversion below is the identity.
2655- let rates: Vec<(Rate, ColorDescription, Option<f32>)> = sources
2668+ let rates: Vec<(Rate, ColorDescription, Option<f32>, Rotation)> = sources
26562669 .iter()
26572670 .map(|source| source_rate(&source.path, meta.frame_rate))
26582671 .collect();
@@ -2671,7 +2684,7 @@ fn run(
26712684 let preset = project.tone();
26722685 let tone: Vec<Option<ToneMapper>> = rates
26732686 .iter()
2674- .map(|(_, color, peak)| match color.transfer {
2687+ .map(|(_, color, peak, _)| match color.transfer {
26752688 // A preview file keeps the film's own curve and is tone-mapped when
26762689 // it is *shown* ([`ExportSettings::keep_source_colour`]), which is
26772690 // both cheaper and the only way the preset can still be changed
@@ -2734,12 +2747,12 @@ fn run(
27342747 // A's pixels on the CPU, so a dissolving span never asks for a GPU
27352748 // buffer, not even outside its own window.
27362749 let dissolve = dissolve_window(project, &span);
2737- let (mut pictures, rate, in_frame, color, mapper) = match span.from {
2750+ let (mut pictures, rate, in_frame, color, mapper, rotation) = match span.from {
27382751 Some((source, in_frame)) => {
27392752 let entry = sources
27402753 .get(source)
27412754 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
2742- let (rate, color, _peak) = rates[source];
2755+ let (rate, color, _peak, rotation) = rates[source];
27432756 let mapper = tone[source].as_ref();
27442757 // Nothing on the way from this span's decoder to the encoder
27452758 // touches a sample: no tone map, no matrix remap, no grade --
@@ -2756,6 +2769,11 @@ fn run(
27562769 && project
27572770 .composite_transform_at(span.start)
27582771 .is_none_or(|params| params.is_identity())
2772+ // A file whose display matrix asks for a turn is *not*
2773+ // untouched, whatever else the timeline says: its pictures
2774+ // have to be turned, which is a read-back no GPU buffer
2775+ // survives.
2776+ && rotation.is_none()
27592777 && dissolve.is_none();
27602778 let want = untouched.then(|| encoder.dma_want(meta)).flatten();
27612779 // Opened at the file's own frame, which is the only place the
@@ -2775,12 +2793,13 @@ fn run(
27752793 } else {
27762794 ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)?
27772795 };
2778- (Some(pictures), rate, in_frame, Some(color), mapper)
2796+ (Some(pictures), rate, in_frame, Some(color), mapper, rotation)
27792797 }
27802798 // A gap's black is 16/128/128, which is black in every matrix here
27812799 // and on every curve: nothing to remap and nothing to tone-map,
2782- // which is what `None` says.
2783- None => (None, Rate::REAL_TIME, 0, None, None),
2800+ // which is what `None` says. A gap is no file either, so nothing
2801+ // turns it.
2802+ None => (None, Rate::REAL_TIME, 0, None, None, Rotation::None),
27842803 };
27852804 // Mixed spaces on one timeline: a clip coded against another matrix than
27862805 // the one this file declares is rewritten into it, *after* the grade --
@@ -2805,6 +2824,10 @@ fn run(
28052824 .unwrap_or_default();
28062825 let mut graded = (Vec::new(), Vec::new(), Vec::new());
28072826 let mut transformed = (Vec::new(), Vec::new(), Vec::new());
2827+ // ...and one more for the file's own display-matrix turn, which happens
2828+ // before all of those (see [`place_picture`]): empty for every source
2829+ // that states no turn.
2830+ let mut rotated = (Vec::new(), Vec::new(), Vec::new());
28082831 // ...and the canvas it is placed on, which is where a source of another
28092832 // resolution becomes a picture at the project's. The same `Composer`
28102833 // playback composes with, given the same policy, so an export is what
@@ -2823,7 +2846,7 @@ fn run(
28232846 let entry = sources.get(b_source).ok_or_else(|| {
28242847 format!("clip names source {b_source} of {}", sources.len())
28252848 })?;
2826- let (b_rate, b_color, _peak) = rates[b_source];
2849+ let (b_rate, b_color, _peak, b_rotation) = rates[b_source];
28272850 let b_mapper = tone[b_source].as_ref();
28282851 let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix);
28292852 Ok(Dissolve {
@@ -2852,11 +2875,13 @@ fn run(
28522875 .composite_transform_at(b_start)
28532876 .copied()
28542877 .unwrap_or_default(),
2878+ rotation: b_rotation,
28552879 canvas: Composer::new(
28562880 meta.width,
28572881 meta.height,
28582882 project.composite_fit_at(b_start),
28592883 ),
2884+ rotated: (Vec::new(), Vec::new(), Vec::new()),
28602885 graded: (Vec::new(), Vec::new(), Vec::new()),
28612886 transformed: (Vec::new(), Vec::new(), Vec::new()),
28622887 })
@@ -2946,10 +2971,12 @@ fn run(
29462971 v,
29472972 width,
29482973 height,
2974+ rotation,
29492975 grade,
29502976 transform,
29512977 remap,
29522978 mapper,
2979+ &mut rotated,
29532980 &mut graded,
29542981 &mut transformed,
29552982 &mut canvas,
@@ -2979,9 +3006,9 @@ fn run(
29793006 }
29803007 Some(Frame::Pixels(by, bu, bv, bw, bh)) => {
29813008 let (by, bu, bv, _, _) = place_picture(
2982- by, bu, bv, bw, bh, d.grade, d.transform, d.remap,
2983- d.mapper, &mut d.graded, &mut d.transformed,
2984- &mut d.canvas,
3009+ by, bu, bv, bw, bh, d.rotation, d.grade, d.transform,
3010+ d.remap, d.mapper, &mut d.rotated, &mut d.graded,
3011+ &mut d.transformed, &mut d.canvas,
29853012 );
29863013 let idx_in_window = done_here + r - d.tail_start;
29873014 let t = dissolve_weight(idx_in_window, d.window);
@@ -3111,12 +3138,16 @@ fn run(
31113138 Ok(())
31123139 }
31133140
3114-/// One decoded picture graded, tone-mapped, remapped and placed on the canvas
3115-/// -- everything between a source's own samples and the ones an encoder is fed,
3116-/// which is exactly the work a zero-copy span has none of.
3141+/// One decoded picture turned, graded, tone-mapped, remapped and placed on the
3142+/// canvas -- everything between a source's own samples and the ones an encoder
3143+/// is fed, which is exactly the work a zero-copy span has none of.
31173144 ///
3118-/// `graded` and `canvas` are the span's scratch: the planes come back borrowed
3119-/// from one of them, or from the picture itself where not a byte was touched.
3145+/// `rotation` first, before the grade: it is the file's own display matrix, the
3146+/// turn a player would make before showing the picture at all, and everything
3147+/// after this -- the grade, the letterbox, the encoder -- is about the picture
3148+/// as it is *meant* to be seen. `turned`, `graded` and `canvas` are the span's
3149+/// scratch: the planes come back borrowed from one of them, or from the picture
3150+/// itself where not a byte was touched.
31203151 #[expect(clippy::too_many_arguments, reason = "one span's whole picture path")]
31213152 fn place_picture<'a>(
31223153 y: &'a [u8],
@@ -3124,14 +3155,35 @@ fn place_picture<'a>(
31243155 v: &'a [u8],
31253156 width: u32,
31263157 height: u32,
3158+ rotation: Rotation,
31273159 grade: Option<crate::color::ColorParams>,
31283160 transform: TransformParams,
31293161 remap: Option<(Matrix, Matrix)>,
31303162 mapper: Option<&ToneMapper>,
3163+ turned: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>),
31313164 graded: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>),
31323165 transformed: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>),
31333166 canvas: &'a mut Composer,
31343167 ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) {
3168+ // The file's own turn, taken exactly as playback's decode funnel takes it
3169+ // ([`crate::decode`]): a phone's portrait video is landscape in the file,
3170+ // and the encoder must be fed what the preview showed. A file that states
3171+ // no turn skips this entirely -- the planes go on borrowed.
3172+ let (y, u, v, width, height) = match rotation.is_none() {
3173+ true => (y, u, v, width, height),
3174+ false => {
3175+ let (w, h) = crate::scale::rotate_i420_90s_into(
3176+ y,
3177+ u,
3178+ v,
3179+ width,
3180+ height,
3181+ rotation.steps(),
3182+ turned,
3183+ );
3184+ (&turned.0[..], &turned.1[..], &turned.2[..], w, h)
3185+ }
3186+ };
31353187 // The planes are borrowed from the decoder (and `Black::picture` hands the
31363188 // same slice as both u and v), so a grade cannot be applied in place: it
31373189 // goes onto a copy, which the encoder then reads instead.
@@ -3199,12 +3251,16 @@ fn remap_into(
31993251 /// -- a still, a song -- and for one that will not open here: the decoder is
32003252 /// opened a few lines later and fails the export by name, which is a better
32013253 /// error than this one could raise.
3202-fn source_rate(path: &Path, timeline_fps: f64) -> (Rate, ColorDescription, Option<f32>) {
3254+fn source_rate(
3255+ path: &Path,
3256+ timeline_fps: f64,
3257+) -> (Rate, ColorDescription, Option<f32>, Rotation) {
32033258 if crate::is_image(path) || crate::is_audio(path) {
32043259 // A still is BT.601 by construction whatever it was authored as:
32053260 // `decode::rgb_to_i420` is the one matrix that turns its pixels into
3206- // planes. A song has no picture and the answer is never read.
3207- return (Rate::REAL_TIME, ColorDescription::default(), None);
3261+ // planes. A song has no picture and the answer is never read. Neither
3262+ // has a display matrix to be turned by.
3263+ return (Rate::REAL_TIME, ColorDescription::default(), None, Rotation::None);
32083264 }
32093265 match Demuxer::open(path) {
32103266 // ...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
32183274 Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME),
32193275 meta.color,
32203276 demuxer.light().peak(),
3277+ // The file's own turn, so the encoder is fed the picture the
3278+ // preview shows: the same header read, one more answer.
3279+ meta.rotation,
32213280 ),
32223281 // Unreadable here means unreadable below too, where the span dies with a
32233282 // real message; the file's own space is the least of that.
3224- Err(_) => (Rate::REAL_TIME, ColorDescription::default(), None),
3283+ Err(_) => (Rate::REAL_TIME, ColorDescription::default(), None, Rotation::None),
32253284 }
32263285 }
32273286
@@ -4397,9 +4456,11 @@ fn pop_av1<'a>(
43974456 /// which would cost two conversions and a generation of colour precision.
43984457 ///
43994458 /// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`,
4400-/// which only speaks BGRA. Unlike playback there is no mid-clip fallback to
4401-/// software: a hardware decode that fails after the first picture fails the
4402-/// export, which then deletes the half-written file.
4459+/// which only speaks BGRA. A hardware decode that fails *before* the first
4460+/// picture falls back to software, exactly as playback's does -- nothing has
4461+/// been encoded yet, so the span can be taken over cleanly. One that fails
4462+/// after the first picture fails the export, which then deletes the
4463+/// half-written file: a restart there would re-encode what the muxer holds.
44034464 enum ClipDecoder {
44044465 /// A stream, decoded on a thread of its own: the encode of picture *n* and
44054466 /// the decode of picture *n + 1* are the two halves an export used to do in
@@ -4628,9 +4689,9 @@ impl ClipDecoder {
46284689 /// will have it, software otherwise) and send every picture until the encoder
46294690 /// stops taking them.
46304691 ///
4631-/// Unlike playback there is no mid-clip fallback to software: a hardware decode
4632-/// that fails after the first picture fails the export, which then deletes the
4633-/// half-written file.
4692+/// Hardware that fails before the first picture falls back to the software seat
4693+/// (see the loop's `decoded == 0` arm); one that fails after it fails the
4694+/// export, which then deletes the half-written file.
46344695 ///
46354696 /// Every way this returns says which way it was, down the channel: a picture, an
46364697 /// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not
@@ -4656,6 +4717,12 @@ fn decode_stream(
46564717 }
46574718 },
46584719 };
4720+ // Pictures handed down the channel. Hardware that dies *before* the first
4721+ // one is the fallback playback already makes, and here nothing has been
4722+ // encoded yet, so the software seat can take the whole span with no frame
4723+ // repeated. Past one picture a restart would re-encode what the muxer
4724+ // already holds, which is why the export still fails there.
4725+ let mut decoded = 0u32;
46594726 loop {
46604727 let frame = match decoder.next(want) {
46614728 Ok(Some(frame)) => frame,
@@ -4664,6 +4731,21 @@ fn decode_stream(
46644731 return;
46654732 }
46664733 Err(e) => {
4734+ if decoded == 0 && matches!(decoder, Pictures::Hw(_)) {
4735+ eprintln!(
4736+ "export decode: hardware failed before any frame ({e}); falling back to software"
4737+ );
4738+ match SwDecoder::open(path, start_frame) {
4739+ Ok(sw) => {
4740+ decoder = Pictures::Sw(sw);
4741+ continue;
4742+ }
4743+ Err(sw_refusal) => {
4744+ let _ = tx.send(Err(sw_refusal));
4745+ return;
4746+ }
4747+ }
4748+ }
46674749 let _ = tx.send(Err(e));
46684750 return;
46694751 }
@@ -4673,6 +4755,7 @@ fn decode_stream(
46734755 if tx.send(Ok(Some(frame))).is_err() {
46744756 return;
46754757 }
4758+ decoded += 1;
46764759 }
46774760 }
46784761
@@ -5283,6 +5366,7 @@ mod tests {
52835366 frame_count: 1,
52845367 codec: crate::demux::Codec::H264,
52855368 color: Default::default(),
5369+ rotation: Rotation::None,
52865370 };
52875371 // 1280 * 720 * 30 * 0.1
52885372 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
@@ -5332,6 +5416,7 @@ mod tests {
53325416 frame_count: 1,
53335417 codec: crate::demux::Codec::H264,
53345418 color: Default::default(),
5419+ rotation: Rotation::None,
53355420 }
53365421 }
53375422
crates/engine/src/lib.rsmodified+17 -2
@@ -37,7 +37,7 @@ pub use audio::{
3737 };
3838 pub use clock::PlaybackClock;
3939 pub use decode::{DecodeSession, Frame, image_size};
40-pub use demux::{Codec, MediaBitrate, VideoMeta, probe_bitrate};
40+pub use demux::{Codec, MediaBitrate, Rotation, UnsupportedRotation, VideoMeta, probe_bitrate};
4141 pub use export::ExportHandle;
4242 pub use mux::{AudioParams, Mp4Muxer, VideoParams};
4343 pub use playback::{ImportGate, ImportProbe, PlaybackSession};
@@ -55,11 +55,24 @@ pub use project::{Clip, Project, Rate, Speed};
5555 /// has. A `.dts` or a bare `.ac3` is refused by the same door that refuses a
5656 /// `.txt` -- there is no reader here that opens an elementary stream -- which is
5757 /// the honest answer.
58+///
59+/// The `.mpeg` and `.mpg` spellings are on the list because an MPEG audio
60+/// stream has no container to name it and the file is whatever a recorder
61+/// called it: those two are the *standard's* name -- what a voice note or a
62+/// tagged download off the web wears -- where `.mp3` is the codec's. Symphonia's
63+/// `mp3` reader is what reads them, the same reader an `.mp3` goes through, and
64+/// it skips the ID3v2 tag and any cover picture muxed into one. A `.mpeg` that
65+/// is really an MPEG *program stream* with a picture in it is still no picture
66+/// here -- nothing demuxes one, and it is symphonia's refusal that says so
67+/// rather than the mp4 crate's. (MPEG's other two layers, `.mp1`/`.mp2`, are
68+/// deliberately absent: this build compiles the mp3 bundle without its `mp1`/
69+/// `mp2` features, so a layer II stream is a codec nothing here decodes, and
70+/// admitting the spelling would be a promise the reader cannot keep.)
5871 pub fn is_audio(path: &std::path::Path) -> bool {
5972 path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
6073 matches!(
6174 e.to_ascii_lowercase().as_str(),
62- "mp3" | "wav" | "flac" | "ogg" | "oga" | "opus" | "mka" | "m4a" | "aac"
75+ "mp3" | "mpeg" | "mpg" | "wav" | "flac" | "ogg" | "oga" | "opus" | "mka" | "m4a" | "aac"
6376 )
6477 })
6578 }
@@ -117,6 +130,8 @@ mod tests {
117130 "g.opus",
118131 "h.OPUS",
119132 "i.mka",
133+ "j.MPEG",
134+ "k.mpg",
120135 ] {
121136 assert!(super::is_audio(Path::new(name)), "{name}");
122137 }
crates/engine/src/playback.rsmodified+83 -24
@@ -24,7 +24,7 @@ use crate::clock::{ClockSource, PlaybackClock};
2424 use crate::color::ColorParams;
2525 use crate::colorspace::{ColorDescription, ContentLight};
2626 use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker};
27-use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta};
27+use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta};
2828 use crate::eq::EqParams;
2929 use crate::project::{
3030 Clip, Edge, GapSweep, Lane, LaneKind, Project, Rate, Source, Span, Speed, SubClip,
@@ -704,6 +704,7 @@ impl PlaybackSession {
704704 // A canvas this engine drew itself, not a stream that was read:
705705 // the default description is what it is drawn in.
706706 color: ColorDescription::default(),
707+ rotation: Rotation::None,
707708 };
708709 let (audio, audio_disabled) = open_audio(path, stream);
709710 // Through `from_parts` rather than `Project::single`, which is the
@@ -801,6 +802,7 @@ impl PlaybackSession {
801802 frame_count: image_frames(IMAGE_ONLY_RATE),
802803 codec: Codec::H264,
803804 color: ColorDescription::default(),
805+ rotation: Rotation::None,
804806 };
805807 let clip = Clip {
806808 fade_in: 0,
@@ -964,6 +966,7 @@ impl PlaybackSession {
964966 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
965967 codec: Codec::H264,
966968 color: ColorDescription::default(),
969+ rotation: Rotation::None,
967970 };
968971 (meta, DecodeSession::open_black(width, height, 1))
969972 }
@@ -981,6 +984,7 @@ impl PlaybackSession {
981984 frame_count: image_frames(frame_rate),
982985 codec: Codec::H264,
983986 color: ColorDescription::default(),
987+ rotation: Rotation::None,
984988 };
985989 let stream = DecodeSession::open_still(
986990 &first.path,
@@ -1022,6 +1026,7 @@ impl PlaybackSession {
10221026 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
10231027 codec: Codec::H264,
10241028 color: ColorDescription::default(),
1029+ rotation: Rotation::None,
10251030 };
10261031 (meta, DecodeSession::open_black(width, height, 1))
10271032 }
@@ -2646,6 +2651,43 @@ impl PlaybackSession {
26462651 }
26472652 debug_assert_eq!(self.counts.len(), self.project.sources().len());
26482653 debug_assert_eq!(self.rates.len(), self.counts.len());
2654+ // A source just joined, which is the one moment the session's audio
2655+ // device may need arming ([`Self::arm_audio`]).
2656+ self.arm_audio();
2657+ }
2658+
2659+ /// Opens the audio device for the first source in the library that has a
2660+ /// track, when this session has none.
2661+ ///
2662+ /// A session opened silent -- its first file carried no sound, so
2663+ /// [`Self::open_library`]/[`Self::open`] had no track to open a device on
2664+ /// -- must not stay silent once a source *with* sound joins it: every later
2665+ /// clip's audio would go unheard for the rest of the session. That is
2666+ /// exactly what the walk [`Self::open_project`] makes at open prevents for
2667+ /// a loaded project (c581d41); this is the same walk at the add door, and
2668+ /// [`Self::note_frames`] is the one place a source joins.
2669+ ///
2670+ /// A no-op once a device is open, so it costs a scan of `is_some` on every
2671+ /// later import. The clock stays on wall time until the next seek
2672+ /// ([`Self::seek`]'s own `switch_to_audio`), which is the seek a front-end
2673+ /// makes as it places the file it just imported.
2674+ fn arm_audio(&mut self) {
2675+ if self.audio.is_some() {
2676+ return;
2677+ }
2678+ for source in self
2679+ .project
2680+ .sources()
2681+ .iter()
2682+ .filter(|s| !crate::is_image(&s.path))
2683+ {
2684+ let (audio, disabled) = open_audio(&source.path, source.audio_stream);
2685+ if audio.is_some() {
2686+ self.audio = audio;
2687+ self.audio_disabled = disabled;
2688+ return;
2689+ }
2690+ }
26492691 }
26502692
26512693 /// The rate noted for whichever source plays `path`, by
@@ -3511,10 +3553,10 @@ impl PlaybackSession {
35113553 /// picture, so the length noted for it is its playing time rounded up to
35123554 /// whole frames, which is the only frame count such a source has.
35133555 ///
3514- /// Refused in the same words as any other import when its rate or layout
3515- /// disagrees with the timeline's -- one output device, one set of
3516- /// parameters -- and refused outright on a silent timeline, which has no
3517- /// device open at all. Nothing is changed by a refusal.
3556+ /// Refused in the same words as any other import when its layout disagrees
3557+ /// with the timeline's track -- one output device, one layout. A silent
3558+ /// timeline has no track to disagree with, so a song joins it and *is* its
3559+ /// sound ([`Self::arm_audio`]). Nothing is changed by a refusal.
35183560 fn import_audio(&mut self, path: &Path) -> crate::Result<usize> {
35193561 let first = self.first_audio()?;
35203562 // Stream 0, and there is no other: a standalone audio file carries one
@@ -4199,21 +4241,30 @@ fn matches_timeline(
41994241 /// cannot do is be copied into an export, which is a refusal of its own, at
42004242 /// export time (`AudioSession::copy_multi_streams`).
42014243 /// What a timeline's audio is held to: the probe of the first source that could
4202-/// have any. A still image is never it -- a picture defines no rate and no
4203-/// layout, so a PNG at index 0 would otherwise be *probed* as a broken mp4 and
4204-/// fail the open outright.
4244+/// have any track.
4245+///
4246+/// The probe of the first source that really **has a track**, walking forward
4247+/// past a still (no track by definition) and past a source whose file carries
4248+/// none (a screen recording with no sound). A silent leading source must not
4249+/// pin the timeline's layout: pinned to it, a later file with sound could never
4250+/// be admitted, and the layout a *following* file is held to would be the
4251+/// silent source's `None`. This is the same walk
4252+/// [`PlaybackSession::open_project`] makes when it opens the device -- the two
4253+/// have to agree, so probing and opening can never name different sources.
42054254 ///
4206-/// `Ok(None)` for a timeline whose first such source is silent, and for one of
4207-/// nothing but stills. That is a silent timeline, and a file with sound is
4208-/// still refused by [`audio_matches`] in the words it always used ("the file
4209-/// has audio, the timeline is silent") -- the device was opened on source 0's
4210-/// track and there is none to open. This function widens which source is asked,
4211-/// not what the answer means.
4255+/// `Ok(None)` for a timeline with no track anywhere: nothing but stills, with
4256+/// no file at all, or every non-still source silent. That is a silent timeline,
4257+/// and a file with sound is admitted onto it -- it *becomes* the timeline's
4258+/// sound ([`PlaybackSession::arm_audio`] opens the device for it), exactly the
4259+/// c581d41 rule ("a later source with real audio must be heard") at the add
4260+/// door.
42124261 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
4213- match audio_source_of(sources) {
4214- Some(first) => AudioSession::probe(&first.path, first.audio_stream),
4215- None => Ok(None),
4262+ for source in sources.iter().filter(|s| !crate::is_image(&s.path)) {
4263+ if let Some(probe) = AudioSession::probe(&source.path, source.audio_stream)? {
4264+ return Ok(Some(probe));
4265+ }
42164266 }
4267+ Ok(None)
42174268 }
42184269
42194270 /// *Which* source that is: the first one that is not a still. The single answer
@@ -4268,13 +4319,21 @@ fn audio_matches_probed(
42684319 let Some(probe) = probe else {
42694320 return Ok(());
42704321 };
4271- Err(match first {
4272- None => "the file has audio, the timeline is silent".to_string(),
4273- Some(b) => format!(
4274- "audio {} ch does not match the timeline's {} ch",
4275- probe.channels, b.channels
4276- ),
4277- }
4322+ // The timeline has no track anywhere (nothing but stills, or every
4323+ // non-image source silent): there is no layout to disagree with, and the
4324+ // arriving file with sound *becomes* the timeline's sound --
4325+ // [`PlaybackSession::arm_audio`] opens the device for it, exactly the walk
4326+ // [`PlaybackSession::open_project`] makes. Refusing here ("the file has
4327+ // audio, the timeline is silent") pinned the timeline to its silent first
4328+ // source for good: remove that file and add another, and the second file's
4329+ // sound could never be heard.
4330+ let Some(b) = first else {
4331+ return Ok(());
4332+ };
4333+ Err(format!(
4334+ "audio {} ch does not match the timeline's {} ch",
4335+ probe.channels, b.channels
4336+ )
42784337 .into())
42794338 }
42804339
crates/engine/src/proxy.rsmodified+2 -0
@@ -615,6 +615,7 @@ fn started(
615615 mod tests {
616616 use super::*;
617617 use crate::colorspace::ColorDescription;
618+ use crate::demux::Rotation;
618619
619620 /// A cancel flag no test in this file is exercising, for the calls that
620621 /// have nothing to cancel.
@@ -630,6 +631,7 @@ mod tests {
630631 frame_count: 240,
631632 codec,
632633 color: ColorDescription::default(),
634+ rotation: Rotation::None,
633635 }
634636 }
635637
crates/engine/src/scale.rsmodified+47 -21
@@ -459,48 +459,74 @@ pub fn rotate_i420_90s(
459459 h: u32,
460460 steps: u8,
461461 ) -> (Vec<u8>, Vec<u8>, Vec<u8>, u32, u32) {
462+ let mut out = (Vec::new(), Vec::new(), Vec::new());
463+ let (rw, rh) = rotate_i420_90s_into(y, u, v, w, h, steps, &mut out);
464+ (out.0, out.1, out.2, rw, rh)
465+}
466+
467+/// [`rotate_i420_90s`] into a caller's own buffers: the top-left of a phone
468+/// file's display matrix has to be made on **every decoded frame**, so the
469+/// three plane allocations are a steady-state cost to pay once rather than a
470+/// per-frame one. The output is exactly what the allocating form returns; the
471+/// scratch tuple is resized and refilled, never appended to.
472+pub fn rotate_i420_90s_into(
473+ y: &[u8],
474+ u: &[u8],
475+ v: &[u8],
476+ w: u32,
477+ h: u32,
478+ steps: u8,
479+ out: &mut (Vec<u8>, Vec<u8>, Vec<u8>),
480+) -> (u32, u32) {
462481 let steps = steps % 4;
463482 if steps == 0 || w == 0 || h == 0 {
464- return (y.to_vec(), u.to_vec(), v.to_vec(), w, h);
483+ out.0.clear();
484+ out.0.extend_from_slice(y);
485+ out.1.clear();
486+ out.1.extend_from_slice(u);
487+ out.2.clear();
488+ out.2.extend_from_slice(v);
489+ return (w, h);
465490 }
466491 let (cw, ch) = chroma_dims(w as usize, h as usize);
467- let (ry, rw, rh) = rotate_plane(y, w as usize, h as usize, steps);
468- let (ru, ..) = rotate_plane(u, cw, ch, steps);
469- let (rv, ..) = rotate_plane(v, cw, ch, steps);
470- (ry, ru, rv, rw as u32, rh as u32)
492+ rotate_plane_into(y, w as usize, h as usize, steps, &mut out.0);
493+ rotate_plane_into(u, cw, ch, steps, &mut out.1);
494+ rotate_plane_into(v, cw, ch, steps, &mut out.2);
495+ if steps == 2 {
496+ (w, h)
497+ } else {
498+ (h, w)
499+ }
471500 }
472501
473-/// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise.
474-fn rotate_plane(src: &[u8], w: usize, h: usize, steps: u8) -> (Vec<u8>, usize, usize) {
502+/// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise,
503+/// written into `out` -- resized to the turned size, which is the source's
504+/// swapped at 90 and 270 and its own at 180.
505+fn rotate_plane_into(src: &[u8], w: usize, h: usize, steps: u8, out: &mut Vec<u8>) {
475506 match steps {
476507 1 => {
477- let (nw, nh) = (h, w);
478- let mut out = vec![0u8; nw * nh];
479- for yp in 0..nh {
480- for xp in 0..nw {
481- out[yp * nw + xp] = src[(h - 1 - xp) * w + yp];
508+ out.resize(h * w, 0);
509+ for yp in 0..w {
510+ for xp in 0..h {
511+ out[yp * h + xp] = src[(h - 1 - xp) * w + yp];
482512 }
483513 }
484- (out, nw, nh)
485514 }
486515 2 => {
487- let mut out = vec![0u8; w * h];
516+ out.resize(w * h, 0);
488517 for yp in 0..h {
489518 for xp in 0..w {
490519 out[yp * w + xp] = src[(h - 1 - yp) * w + (w - 1 - xp)];
491520 }
492521 }
493- (out, w, h)
494522 }
495523 3 => {
496- let (nw, nh) = (h, w);
497- let mut out = vec![0u8; nw * nh];
498- for yp in 0..nh {
499- for xp in 0..nw {
500- out[yp * nw + xp] = src[xp * w + (w - 1 - yp)];
524+ out.resize(h * w, 0);
525+ for yp in 0..w {
526+ for xp in 0..h {
527+ out[yp * h + xp] = src[xp * w + (w - 1 - yp)];
501528 }
502529 }
503- (out, nw, nh)
504530 }
505531 _ => unreachable!("steps % 4 is 1, 2 or 3 here"),
506532 }
crates/engine/tests/audio_export.rsmodified+5 -1
@@ -22,7 +22,7 @@ use engine::export::{ExportSettings, Format};
2222 use engine::project::{Lane, LaneKind, Source, Speed};
2323 use engine::scale::FitPolicy;
2424 use engine::scratch::Scratch;
25-use engine::{AudioSession, Clip, ExportHandle, Project};
25+use engine::{AudioSession, Clip, ExportHandle, Project, Rotation};
2626
2727 const RATE: u32 = 44_100;
2828
@@ -378,6 +378,7 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() {
378378 frame_count: 60,
379379 codec: engine::Codec::H264,
380380 color: Default::default(),
381+ rotation: Rotation::None,
381382 };
382383 let out = out_path("still_song", "mp4");
383384 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() {
704705 frame_count: 60,
705706 codec: engine::Codec::H264,
706707 color: Default::default(),
708+ rotation: Rotation::None,
707709 };
708710 for want in [128u32, 320] {
709711 let out = out_path(&format!("mp4_aac_{want}"), "mp4");
@@ -1001,6 +1003,7 @@ fn a_fade_in_reaches_the_exported_audio() {
10011003 frame_count: 90,
10021004 codec: engine::Codec::H264,
10031005 color: Default::default(),
1006+ rotation: Rotation::None,
10041007 };
10051008 let out = out_path("fadein", "wav");
10061009 let handle = engine::export::start(
@@ -1097,6 +1100,7 @@ fn a_split_and_crossfaded_clip_has_no_muted_interior() {
10971100 frame_count: 90,
10981101 codec: engine::Codec::H264,
10991102 color: Default::default(),
1103+ rotation: Rotation::None,
11001104 };
11011105 let out = out_path("crossfade", "wav");
11021106 let handle = engine::export::start(
crates/engine/tests/audio_files.rsmodified+45 -1
@@ -18,8 +18,11 @@ use engine::{AudioSession, Clip, PlaybackSession, Project};
1818 /// The fixtures `scripts/gen_fixtures.sh` writes: 3 s of 440 Hz left / 880 Hz
1919 /// right at 44.1k stereo, under a 1 Hz volume pulse -- the same tone
2020 /// `test_av.mp4` carries, so a song and a video clip share one timeline.
21-const CONTAINERS: [&str; 6] = [
21+/// `test_tone.mpg` is the same MPEG audio stream under the standard's spelling
22+/// rather than the codec's; the cover-carrying `.mpeg` has its own test below.
23+const CONTAINERS: [&str; 7] = [
2224 "test_tone.mp3",
25+ "test_tone.mpg",
2326 "test_tone.wav",
2427 "test_tone.flac",
2528 "test_tone.ogg",
@@ -791,6 +794,47 @@ fn an_audio_only_file_wearing_an_mp4_extension_still_opens() {
791794 assert!((session.timeline_duration() - 3.0).abs() < 0.1);
792795 }
793796
797+/// An MPEG audio stream wearing the *standard's* spelling -- `.mpeg`, what a
798+/// voice note or a tagged download off the web is called -- with a JPEG cover
799+/// muxed into its ID3v2 tag beside the sound. Two claims, and the first is the
800+/// bug: the spelling has to reach the audio door at all (`is_audio`, and with
801+/// it every lane decision and the import itself). While the extension list did
802+/// not admit it the file fell through to the mp4 demuxer and the library door
803+/// answered `IMPORT FAILED: <name> — file contains a box with a larger size
804+/// than it`, this test's `import`/`open` failing in exactly those words. The
805+/// second is that the cover is not mistaken for a picture: symphonia skips the
806+/// ID3v2 tag, the file opens audio-only, and the tone decodes non-silent.
807+#[test]
808+fn an_mpeg_audio_file_with_a_cover_stream_opens_and_imports() {
809+ let name = "test_tone_cover.mpeg";
810+ let path = asset(name);
811+ assert!(engine::is_audio(&path), "{name} is sound");
812+
813+ // The open door: a song *is* a timeline, and no cover stream puts a clip on
814+ // the video lane.
815+ let session = open(&path);
816+ assert!(
817+ session.lane_clips(Lane::V1).is_empty(),
818+ "{name}: the cover is not a picture source"
819+ );
820+ assert_eq!(session.lane_clips(Lane::A1).len(), 1);
821+ assert!((session.timeline_duration() - 3.0).abs() < 0.1, "{name}");
822+ drop(session);
823+
824+ // The library door the message came from: an import into a session that
825+ // already has a timeline.
826+ let mut session = open(asset("test_tone.mp3"));
827+ import_and_place(&mut session, &path);
828+ drop(session);
829+
830+ let (rate, channels, samples) = decode(&path);
831+ assert_eq!((rate, channels), (44100, 2), "{name}");
832+ let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels);
833+ assert!((secs - 3.0).abs() < 0.1, "{name}: {secs:.3} s of audio");
834+ let peak = samples.iter().fold(0.0f32, |m, s| m.max(s.abs()));
835+ assert!(peak > 0.05, "{name}: decoded everything silent (peak {peak})");
836+}
837+
794838 /// The same fallback in [`PlaybackSession::open_project`]'s scaffold branch: a
795839 /// project whose first source is one of these files reloads instead of failing
796840 /// the open a save never had trouble with the first time.
crates/engine/tests/export.rsmodified+2 -1
@@ -35,7 +35,7 @@ use engine::mux::{AudioParams, Mp4Muxer, VideoParams, parameter_sets};
3535 use engine::project::{Lane, Source, Speed};
3636 use engine::scale::FitPolicy;
3737 use engine::scratch::Scratch;
38-use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
38+use engine::{DecodeSession, ExportHandle, PlaybackSession, Project, Rotation};
3939 use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
4040 use ec_core::{Packet, TimeBase};
4141 use ec_h264::H264Decoder;
@@ -277,6 +277,7 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() {
277277 frame_count: 20,
278278 codec: engine::Codec::H264,
279279 color: Default::default(),
280+ rotation: Rotation::None,
280281 };
281282 let out = out_path("mixed");
282283 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
crates/engine/tests/hw_decode.rsmodified+109 -0
@@ -19,6 +19,7 @@ use engine::DecodeSession;
1919 use engine::colorspace::{ColorDescription, Matrix};
2020 use engine::convert::i420_to_bgra;
2121 use engine::demux::{Codec, Demuxer};
22+use engine::mux::{self, Mp4Muxer, VideoParams};
2223 use engine::scratch::Scratch;
2324 use engine::hw::HwSession;
2425 use engine::tonemap::{ToneMapper, Transfer};
@@ -477,3 +478,111 @@ fn av1_ten_bit_hardware_matches_software_on_every_frame() {
477478 eprintln!("frame 30 differing bytes: {diff} / {}", sw_frame_30.len());
478479 assert_eq!(diff, 0, "hardware and software 10-bit AV1 decode disagree");
479480 }
481+
482+/// Annex-B NAL payloads (start codes stripped, trailing zeros trimmed).
483+fn nals(annex_b: &[u8]) -> Vec<&[u8]> {
484+ let mut out = Vec::new();
485+ let mut start = None;
486+ let mut i = 0;
487+ while i + 2 < annex_b.len() {
488+ if annex_b[i] == 0 && annex_b[i + 1] == 0 && annex_b[i + 2] == 1 {
489+ if let Some(s) = start {
490+ out.push(&annex_b[s..i]);
491+ }
492+ i += 3;
493+ start = Some(i);
494+ } else {
495+ i += 1;
496+ }
497+ }
498+ if let Some(s) = start {
499+ out.push(&annex_b[s..]);
500+ }
501+ out
502+}
503+
504+/// One access unit as a length-prefixed AVCC sample with `cabac_zero_word` --
505+/// `zeros` zero bytes -- inside the *last* coded NAL's declared length. That is
506+/// byte-for-byte what a phone-camera encoder writes, and what a decoder that
507+/// stops consuming at the last NAL leaves behind as "not a NAL".
508+fn sample_with_trailing_zeros(annex_b: &[u8], zeros: usize) -> (Vec<u8>, bool) {
509+ let mut coded: Vec<&[u8]> = Vec::new();
510+ let mut key = false;
511+ for nal in nals(annex_b) {
512+ let end = nal.iter().rposition(|&b| b != 0).map_or(0, |p| p + 1);
513+ let nal = &nal[..end];
514+ if nal.is_empty() {
515+ continue;
516+ }
517+ match nal[0] & 0x1f {
518+ 7 | 8 | 6 | 9 => continue, // parameter sets/SEI live in avcC or are dropped
519+ 5 => key = true,
520+ _ => {}
521+ }
522+ coded.push(nal);
523+ }
524+ let mut sample = Vec::new();
525+ let last = coded.len().saturating_sub(1);
526+ for (i, nal) in coded.iter().enumerate() {
527+ let len = nal.len() + if i == last { zeros } else { 0 };
528+ sample.extend_from_slice(&(len as u32).to_be_bytes());
529+ sample.extend_from_slice(nal);
530+ if i == last {
531+ sample.extend(std::iter::repeat_n(0u8, zeros));
532+ }
533+ }
534+ (sample, key)
535+}
536+
537+/// An mp4 cut from `test_baseline.mp4` whose every H.264 sample ends in four
538+/// zero bytes.
539+fn write_trailing_zero_fixture(src: &Path, out: &Path, frames: usize) {
540+ let (meta, mut demuxer) = Demuxer::open(src).expect("open fixture source");
541+ let first = demuxer.next_access_unit().expect("read").expect("au");
542+ let (sps, pps) = mux::parameter_sets(&first).expect("parameter sets in the first au");
543+ let mut muxer = Mp4Muxer::create(
544+ out,
545+ &VideoParams {
546+ width: meta.width,
547+ height: meta.height,
548+ frame_rate: meta.frame_rate,
549+ sps,
550+ pps,
551+ },
552+ None,
553+ )
554+ .expect("create fixture");
555+ let (sample, key) = sample_with_trailing_zeros(&first, 4);
556+ muxer.write_coded_sample(&sample, key).expect("first sample");
557+ for _ in 1..frames {
558+ let Some(au) = demuxer.next_access_unit().expect("read") else {
559+ break;
560+ };
561+ let (sample, key) = sample_with_trailing_zeros(&au, 4);
562+ muxer.write_coded_sample(&sample, key).expect("sample");
563+ }
564+ muxer.finish().expect("finish fixture");
565+}
566+
567+/// A phone-camera mp4 ends its every coded sample in `cabac_zero_word`. The
568+/// plugin consumed each access unit only up to the last NAL cros-codecs
569+/// reported and fed the leftover zero bytes back as if they were the next unit;
570+/// `Nalu::next` refuses a buffer with no start code ("No NAL found"), so the
571+/// whole session failed with code -2 before the first picture -- the export's
572+/// `hardware decode failed (code -2)` on a file VA-API otherwise decodes.
573+#[test]
574+#[ignore = "needs libengine_hw.so and a VA-API driver"]
575+fn hardware_decodes_samples_with_trailing_zero_words() {
576+ let out = Scratch::file("ve_hw_trailing_zeros", "mp4");
577+ write_trailing_zero_fixture(&asset("test_baseline.mp4"), &out, 30);
578+ let mut hw = open_hw(&out);
579+ let mut count = 0usize;
580+ while let Some((_, _, _, w, h)) = hw
581+ .next_frame()
582+ .expect("hardware decode of trailing-zero samples")
583+ {
584+ assert_eq!((w, h), (1280, 720), "frame {count} dims");
585+ count += 1;
586+ }
587+ assert_eq!(count, 30, "every picture decoded");
588+}
crates/engine/tests/rotation.rsadded+252 -0
@@ -0,0 +1,252 @@
1+//! The display matrix: a file that says "turn me" is turned -- in the preview
2+//! and in the export, from the same numbers.
3+//!
4+//! A phone records a portrait video as a landscape picture plus a `tkhd` matrix
5+//! saying which way to turn it. Before this the engine read neither: the
6+//! preview showed a portrait clip on its side and an export re-coded the
7+//! landscape pixels with a unity matrix, so the file played sideways anywhere
8+//! -- the one rendition nobody ever wanted.
9+//!
10+//! `test_rotation90/180/270.mp4` (`scripts/gen_fixtures.sh`) are one 320x180
11+//! source of four coloured quadrants written back out with a turn asked for, so
12+//! a single sampled pixel per corner names the layout and a *wrong direction*
13+//! cannot pass -- a 180-degree mix-up, a mirror, or "ignore it" each produce a
14+//! different set of four corners. The layouts asserted here are ffmpeg's own
15+//! autorotation of each file, measured rather than derived.
16+//!
17+//! `test_rotation45.mp4` is the other half of the contract: a matrix that is a
18+//! rotation but not a quarter turn has no correct rendition here, and it is
19+//! refused *by name* at the door rather than shown wrong.
20+
21+use std::path::{Path, PathBuf};
22+use std::sync::Once;
23+use std::time::{Duration, Instant};
24+
25+use engine::export::ExportSettings;
26+use engine::scratch::Scratch;
27+use engine::{DecodeSession, ExportHandle, PlaybackSession, Rotation};
28+
29+fn asset(name: &str) -> PathBuf {
30+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
31+ .join("../../assets")
32+ .join(name)
33+}
34+
35+/// Which seat an export takes is decided by *process-wide* environment
36+/// variables, so a test binary that shares the machine has to borrow them
37+/// rather than assume: this pins both decode and encode to software, which is
38+/// the seat every machine has, and holds the borrow for the whole test binary.
39+static SEAT: std::sync::RwLock<()> = std::sync::RwLock::new(());
40+
41+type Shared = std::sync::RwLockReadGuard<'static, ()>;
42+
43+#[must_use = "the seat pin holds only while its guard is alive"]
44+fn pin_software() -> Shared {
45+ let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner());
46+ static PIN: Once = Once::new();
47+ PIN.call_once(|| unsafe {
48+ std::env::set_var("VE_SW", "1");
49+ std::env::set_var("VE_SW_ENC", "1");
50+ });
51+ borrowed
52+}
53+
54+fn out_path(name: &str) -> Scratch {
55+ Scratch::file(&format!("ve_rotation_{name}"), "mp4")
56+}
57+
58+fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
59+ let started = Instant::now();
60+ while !handle.is_finished() {
61+ assert!(
62+ started.elapsed() < limit,
63+ "export did not finish in {limit:?}"
64+ );
65+ std::thread::sleep(Duration::from_millis(20));
66+ }
67+ handle.result().expect("a finished export has an outcome")
68+}
69+
70+/// What colour a decoded BGRA pixel is, by the quadrant it came from. ffmpeg's
71+/// `red`/`green`/`blue`/`yellow` are far apart enough that the chroma of a
72+/// 4:2:0 edge never reaches a quadrant's centre, and the labels are what the
73+/// fixture's own comment says it drew.
74+fn tint(bgra: &[u8]) -> &'static str {
75+ let (b, g, r) = (bgra[0], bgra[1], bgra[2]);
76+ let (r, g, b) = (r > 110, g > 90, b > 110);
77+ match (r, g, b) {
78+ (true, true, false) => "yellow",
79+ (true, false, false) => "red",
80+ (false, true, false) => "green",
81+ (false, false, true) => "blue",
82+ other => panic!("a quadrant centre is not one of the four colours: {other:?}"),
83+ }
84+}
85+
86+/// The four corners of one tightly packed BGRA picture, top-left first and
87+/// clockwise -- sampled deep enough inside each quadrant that a 4:2:0 boundary
88+/// cannot colour the sample.
89+fn corners(width: u32, height: u32, bgra: &[u8]) -> [&'static str; 4] {
90+ let at = |x: u32, y: u32| {
91+ let index = ((y * width + x) * 4) as usize;
92+ tint(&bgra[index..index + 4])
93+ };
94+ let (qx, qy) = (width / 4, height / 4);
95+ [at(qx, qy), at(3 * qx, qy), at(3 * qx, 3 * qy), at(qx, 3 * qy)]
96+}
97+
98+/// What the coded picture holds, before anything turns it: this is the layout
99+/// every expectation below is *not*.
100+const CODED: [&str; 4] = ["red", "green", "yellow", "blue"];
101+
102+/// One frame of `path` and the size it came out at: the preview path exactly
103+/// ([`DecodeSession`] is the same funnel [`PlaybackSession`] paints from).
104+fn first_frame(path: &Path) -> (u32, u32, Vec<u8>) {
105+ let (_, frames, _) = DecodeSession::open_at(path, 0).expect("open for a frame");
106+ let frame = frames.recv().expect("a first frame");
107+ (frame.width, frame.height, frame.bgra)
108+}
109+
110+/// The same four corners ffmpeg's own autorotation of each file produces --
111+/// measured with `ffmpeg -i f.mp4 -f rawvideo -pix_fmt rgb24 -` on this
112+/// machine, which is the arbiter a display matrix is read against.
113+fn expected(file: &str) -> ([u32; 2], Rotation, [&'static str; 4]) {
114+ match file {
115+ "test_rotation90.mp4" => (
116+ [180, 320],
117+ Rotation::Cw270,
118+ ["green", "yellow", "blue", "red"],
119+ ),
120+ "test_rotation180.mp4" => (
121+ [320, 180],
122+ Rotation::Cw180,
123+ ["yellow", "blue", "red", "green"],
124+ ),
125+ "test_rotation270.mp4" => (
126+ [180, 320],
127+ Rotation::Cw90,
128+ ["blue", "red", "green", "yellow"],
129+ ),
130+ other => panic!("no expectation for {other}"),
131+ }
132+}
133+
134+/// The header says which way the picture lies: a quarter turn swaps the
135+/// displayed size and names the turn, and a half turn does neither.
136+#[test]
137+fn a_display_matrix_is_read_as_a_quarter_turn() {
138+ for file in [
139+ "test_rotation90.mp4",
140+ "test_rotation180.mp4",
141+ "test_rotation270.mp4",
142+ ] {
143+ let (size, rotation, _) = expected(file);
144+ let (meta, _) = engine::demux::Demuxer::open(&asset(file)).expect("open a fixture");
145+ assert_eq!(
146+ [meta.width, meta.height],
147+ size,
148+ "{file}: the *displayed* size is what the engine reports"
149+ );
150+ assert_eq!(meta.rotation, rotation, "{file}: which turn the file asks for");
151+ assert_eq!(
152+ rotation.swaps_axes(),
153+ size == [180, 320],
154+ "{file}: a swapped size and a swapping turn go together"
155+ );
156+ }
157+ // ...and the fixture's own coded picture is the layout none of these are,
158+ // which is what makes the assertions above about the turn and not about the
159+ // source. `test_rotation180.mp4` keeps its coded size, so the picture is
160+ // where the turn is visible.
161+ let (width, height, bgra) = first_frame(&asset("test_rotation180.mp4"));
162+ assert_eq!((width, height), (320, 180));
163+ assert_ne!(corners(width, height, &bgra), CODED, "the turn was made");
164+}
165+
166+/// The preview: the picture is turned before it is painted, at the size the
167+/// turn gives it.
168+#[test]
169+fn the_preview_shows_a_turned_file_upright() {
170+ let _seat = pin_software();
171+ for file in [
172+ "test_rotation90.mp4",
173+ "test_rotation180.mp4",
174+ "test_rotation270.mp4",
175+ ] {
176+ let (size, _, corners_expected) = expected(file);
177+ let (width, height, bgra) = first_frame(&asset(file));
178+ assert_eq!(
179+ [width, height],
180+ size,
181+ "{file}: the painted picture is the displayed size"
182+ );
183+ assert_eq!(
184+ corners(width, height, &bgra),
185+ corners_expected,
186+ "{file}: every quadrant landed where the turn puts it"
187+ );
188+ }
189+}
190+
191+/// The export: the turn is baked into the pixels, so the file plays upright
192+/// everywhere -- which means the output is portrait *and* declares no matrix of
193+/// its own. A file that kept the source's matrix and the source's landscape
194+/// pixels would satisfy neither half.
195+#[test]
196+fn an_export_of_a_turned_file_is_upright_and_portrait() {
197+ let _seat = pin_software();
198+ let source = asset("test_rotation90.mp4");
199+ let mut session = PlaybackSession::open(&source).expect("open the fixture");
200+ session.pause();
201+ assert_eq!(
202+ [session.meta().width, session.meta().height],
203+ [180, 320],
204+ "the timeline is the displayed shape, not the coded one"
205+ );
206+ let out = out_path("upright");
207+ let handle = session.export_to_with(&out, &ExportSettings::default());
208+ wait(&handle, Duration::from_secs(60)).expect("export");
209+
210+ let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
211+ assert_eq!(
212+ [meta.width, meta.height],
213+ [180, 320],
214+ "the written file is portrait"
215+ );
216+ assert_eq!(
217+ meta.rotation,
218+ Rotation::None,
219+ "and states no matrix: the turn is in the pixels"
220+ );
221+ assert_eq!(meta.frame_count, 30, "every timeline frame was written");
222+
223+ let (width, height, bgra) = first_frame(&out);
224+ assert_eq!([width, height], [180, 320]);
225+ assert_eq!(
226+ corners(width, height, &bgra),
227+ ["green", "yellow", "blue", "red"],
228+ "the exported pixels are the ones the preview showed"
229+ );
230+}
231+
232+/// A matrix that is not a quarter turn is refused by name at the door, with the
233+/// angle in the sentence -- the honest answer to a picture this engine has no
234+/// way to show right. The capability really is absent: nothing here turns by an
235+/// arbitrary angle ([`engine::scale::rotate_i420_90s`] takes whole quarters),
236+/// and the refusal is what says so instead of a sideways picture.
237+#[test]
238+fn a_matrix_that_is_not_a_quarter_turn_is_refused_by_name() {
239+ let error = match engine::demux::Demuxer::open(&asset("test_rotation45.mp4")) {
240+ Ok(_) => panic!("45 degrees is not a quarter turn, and opening it must not succeed"),
241+ Err(error) => error,
242+ };
243+ assert!(
244+ engine::UnsupportedRotation::is_it(&error),
245+ "the refusal is the named one, not a generic failure: {error}"
246+ );
247+ let said = error.to_string();
248+ assert!(
249+ said.contains("45.0°") && said.contains("quarter turn"),
250+ "the refusal names the angle it cannot make: {said}"
251+ );
252+}
crates/engine/tests/silent_first_source.rsadded+153 -0
@@ -0,0 +1,153 @@
1+//! A silent leading source must not silence the timeline for good.
2+//!
3+//! The reported sequence: (1) a video with no audio track is added to the
4+//! timeline, (2) it is removed, (3) another file -- one that *does* have audio
5+//! -- is added. The engine used to pin the session to its first source: the
6+//! device was opened (or, here, not opened) from that one file and never
7+//! re-armed, and the import door refused the newcomer outright ("the file has
8+//! audio, the timeline is silent"). So the second file's picture showed but its
9+//! audio was silent -- or the file could not join at all.
10+//!
11+//! Three seams held that pin, and each is covered here:
12+//! - the import gate (`audio_matches_probed` / `first_audio_of`) refused a file
13+//! with sound onto a timeline whose leading source has none;
14+//! - the session never opened a device when such a file did join
15+//! (`PlaybackSession::arm_audio`);
16+//! - playback itself re-picked the first non-image source and returned
17+//! `Ok(None)` -- silence -- however many later segments named a source with
18+//! audio (`AudioSession::open_multi_streams_speed_at_fade`).
19+//!
20+//! ```text
21+//! cargo test -p engine --test silent_first_source -- --nocapture
22+//! ```
23+
24+use std::path::{Path, PathBuf};
25+use std::thread::sleep;
26+use std::time::{Duration, Instant};
27+
28+use engine::{AudioSession, PlaybackSession};
29+
30+fn asset(name: &str) -> PathBuf {
31+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
32+ .join("../../assets")
33+ .join(name)
34+}
35+
36+/// The real phone clip the report named, when it is on this machine: mono-ish
37+/// ambient at about -36 dBFS, so the "non-silent" bar is its own peak, not a
38+/// loud fixture's. Skipped (and the run says so) when the file is absent.
39+fn real_clip() -> Option<PathBuf> {
40+ let path = PathBuf::from("/home/tahinli/Downloads/real_clip.mp4");
41+ path.is_file().then_some(path)
42+}
43+
44+fn peak(session: &PlaybackSession) -> f32 {
45+ session
46+ .audio_tap()
47+ .map(|(s, _)| s.iter().fold(0.0f32, |m, s| m.max(s.abs())))
48+ .unwrap_or(0.0)
49+}
50+
51+fn pump(session: &mut PlaybackSession, secs: f64) -> f32 {
52+ let deadline = Instant::now() + Duration::from_secs_f64(secs);
53+ let mut best = 0.0f32;
54+ while Instant::now() < deadline {
55+ session.tick();
56+ best = best.max(peak(session));
57+ sleep(Duration::from_millis(8));
58+ }
59+ best
60+}
61+
62+fn remove_all_clips(session: &mut PlaybackSession) {
63+ for lane in session.lanes() {
64+ let mut i = session.lane_clips(lane).len();
65+ while i > 0 {
66+ i -= 1;
67+ session.delete_clip(lane, i);
68+ }
69+ }
70+}
71+
72+/// The app's own import door: the gate taken off the live session, the probe
73+/// read off it (what the worker does), then the registration.
74+fn app_import(session: &mut PlaybackSession, b: &Path) -> engine::Result<usize> {
75+ let gate = session.import_gate();
76+ let probe = PlaybackSession::probe_import(gate, b)?;
77+ session.import_probed(b, probe)
78+}
79+
80+/// The reported add/remove/add, end to end at the session level: a silent first
81+/// file, removed from the timeline, then a file with sound imported into the
82+/// *same* session and placed -- its audio must decode non-silent.
83+fn add_remove_add(a: &Path, b: &Path, loud: f32) {
84+ let mut session = PlaybackSession::open_library(a).expect("open_library A");
85+ session.set_gain(0.0);
86+
87+ // (1) A joins the timeline. Silent by nature: no track to open a device on.
88+ let end = session.timeline_duration();
89+ assert!(
90+ session.place_stream_at(end, a, 0, None).expect("place A"),
91+ "A lands"
92+ );
93+ session.play();
94+ let a_peak = pump(&mut session, 1.5);
95+ assert!(a_peak < 0.01, "A must be silent, got {a_peak}");
96+ session.pause();
97+ session.seek(0.0);
98+
99+ // (2) A comes off the timeline; the library keeps it.
100+ remove_all_clips(&mut session);
101+
102+ // (3) B joins the library through the app's own door, then the timeline.
103+ app_import(&mut session, b).expect("B must be admitted onto a silent timeline");
104+ assert!(
105+ session.audio_disabled_reason().is_none(),
106+ "the device was not armed for B: {:?}",
107+ session.audio_disabled_reason()
108+ );
109+ let end = session.timeline_duration();
110+ assert!(
111+ session.place_stream_at(end, b, 0, None).expect("place B"),
112+ "B lands"
113+ );
114+ session.play();
115+ let b_peak = pump(&mut session, 2.5);
116+ assert!(
117+ b_peak > loud,
118+ "B's audio is silent after the sequence: peak {b_peak}"
119+ );
120+}
121+
122+#[test]
123+fn a_second_file_with_sound_is_heard_after_a_silent_first_file() {
124+ add_remove_add(&asset("test_baseline.mp4"), &asset("test_av2.mp4"), 0.05);
125+}
126+
127+/// The same sequence with the report's own file as the second import.
128+#[test]
129+fn the_reports_second_file_is_heard_too() {
130+ match real_clip() {
131+ Some(real) => add_remove_add(&asset("test_baseline.mp4"), &real, 0.02),
132+ None => eprintln!("SKIPPED: {} is not on this machine", "/home/tahinli/Downloads/real_clip.mp4"),
133+ }
134+}
135+
136+/// The playback seam on its own: a segment naming the second source must decode
137+/// that source's samples even though the first source has no track. Pre-fix
138+/// this returned `Ok(None)` -- the whole timeline silent.
139+#[test]
140+fn playback_walks_past_a_trackless_leading_source() {
141+ let sources = vec![(asset("test_baseline.mp4"), 0usize), (asset("test_av2.mp4"), 0usize)];
142+ let segs = vec![(Some(1usize), 0.0f64, f64::INFINITY)];
143+ let (_, rx) = AudioSession::open_multi_streams(&sources, &segs)
144+ .expect("open the second source's audio")
145+ .expect("the second source has a track");
146+ let (mut n, mut peak) = (0usize, 0.0f32);
147+ for chunk in rx {
148+ n += chunk.samples.len();
149+ peak = chunk.samples.iter().fold(peak, |m, s| m.max(s.abs()));
150+ }
151+ assert!(n > 0, "nothing decoded");
152+ assert!(peak > 0.05, "the second source's audio is silent: peak {peak}");
153+}
scripts/gen_fixtures.shmodified+60 -0
@@ -572,6 +572,26 @@ for fmt in mp3 wav flac ogg m4a aac; do
572572 -filter_complex "$tone" -map "[a]" -ar 44100 "${codec[@]}" \
573573 "assets/test_tone.$fmt"
574574 done
575+# ...and the same tone in the MPEG audio spellings an encoder names after the
576+# standard rather than the codec (`.mpeg`/`.mpg`), carrying a JPEG cover in its
577+# ID3v2 tag -- the shape a voice note or a tagged download has. `-f mp3` is what
578+# makes it an MPEG *audio* stream: left to the extension, ffmpeg would write an
579+# MPEG program stream instead, which is a different file that this engine has no
580+# demuxer for. `test_tone_cover.jpg` is the cover it muxes in; a reader that
581+# walked the file as an mp4 saw only `InvalidData("file contains a box with a
582+# larger size than it")` before `is_audio` admitted the spelling.
583+ffmpeg -y -f lavfi -i "color=c=blue:s=64x64:d=1" -frames:v 1 \
584+ "assets/test_tone_cover.jpg"
585+ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \
586+ -f lavfi -i "sine=frequency=880:duration=3" \
587+ -i "assets/test_tone_cover.jpg" \
588+ -filter_complex "$tone" -map "[a]" -map 2:v -ar 44100 \
589+ -c:a libmp3lame -b:a 128k -c:v mjpeg -disposition:v attached_pic \
590+ -id3v2_version 3 -f mp3 "assets/test_tone_cover.mpeg"
591+ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \
592+ -f lavfi -i "sine=frequency=880:duration=3" \
593+ -filter_complex "$tone" -map "[a]" -ar 44100 \
594+ -c:a libmp3lame -b:a 128k -id3v2_version 3 -f mp3 "assets/test_tone.mpg"
575595 # The two Opus fixtures, which cannot join the loop above: Opus decodes at 48 kHz
576596 # and nothing else, so these are the 48k twins of the tone rather than 44.1k ones.
577597 # 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 \
672692 -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
673693 -c:a aac -b:a 96k -f mov assets/test_qt.mov
674694
695+# The display matrix: `test_rotation*.mp4` are one 320x180 source -- four
696+# coloured quadrants, so a quarter turn is readable from a single sampled pixel
697+# per corner and a wrong direction cannot pass -- written back out with a
698+# rotation asked for. This is how a phone records a portrait video: the pixels
699+# stay landscape and the container says which way to turn them.
700+#
701+# The trap this recipe exists to avoid: `-metadata:s:v rotate=90`, the form
702+# every search result gives, writes **no display matrix at all** with this
703+# machine's ffmpeg (`ffprobe -show_streams` comes back with an empty side-data
704+# block, so a "rotated" fixture is really an unrotated one and the test passes
705+# against nothing). `-display_rotation` is a *muxer* option here and, being an
706+# input option, goes **before** the `-i` it applies to.
707+#
708+# The four quadrants are red, green, blue and yellow:
709+#
710+# coded -display_rotation 90 -display_rotation 180
711+# red green green yellow yellow blue
712+# blue yellow red blue green red
713+#
714+# which is exactly ffmpeg's own autorotation of each file -- measured
715+# (`ffmpeg -i f.mp4 -f rawvideo -pix_fmt rgb24 -`) rather than derived, because
716+# which way a display matrix turns a picture is the one thing a reader has to be
717+# told rather than guess. `tests/rotation.rs` asserts those layouts.
718+#
719+# `-display_rotation 45` is the other half: a matrix that is a rotation and not
720+# a *quarter* turn, which this engine refuses by name (`demux::UnsupportedRotation`)
721+# instead of showing it sideways.
722+ffmpeg -y -f lavfi -i "color=c=red:s=160x90:d=1:r=30,format=yuv420p" \
723+ -f lavfi -i "color=c=green:s=160x90:d=1:r=30,format=yuv420p" \
724+ -f lavfi -i "color=c=blue:s=160x90:d=1:r=30,format=yuv420p" \
725+ -f lavfi -i "color=c=yellow:s=160x90:d=1:r=30,format=yuv420p" \
726+ -filter_complex "[0:v][1:v]hstack[top];[2:v][3:v]hstack[bot];[top][bot]vstack[v]" \
727+ -map "[v]" -frames:v 30 -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
728+ assets/.rotation_src.mp4
729+for deg in 90 180 270 45; do
730+ ffmpeg -y -display_rotation "$deg" -i assets/.rotation_src.mp4 \
731+ -c copy "assets/test_rotation$deg.mp4"
732+done
733+rm -f assets/.rotation_src.mp4
734+
675735 echo "fixtures written to assets/"