Audio routing, session audio re-arm, hw trailing-zero NALs, display-matrix rotation
Browse files at this commitbc8b82ec886ecf333b55eb26c2194d40a42a1dc3Parent: eecc8f5- fix
- audio routing, session audio re-arm, hw trailing-zero NALs, display-matrix rotation
17 changed files +1195 -96
- crates/app/src/player/library.rs +6 -0
- crates/engine-hw/src/lib.rs +21 -0
- crates/engine/src/audio.rs +35 -14
- crates/engine/src/decode.rs +56 -2
- crates/engine/src/demux.rs +189 -2
- crates/engine/src/export.rs +113 -28
- crates/engine/src/lib.rs +17 -2
- crates/engine/src/playback.rs +83 -24
- crates/engine/src/proxy.rs +2 -0
- crates/engine/src/scale.rs +47 -21
- crates/engine/tests/audio_export.rs +5 -1
- crates/engine/tests/audio_files.rs +45 -1
- crates/engine/tests/export.rs +2 -1
- crates/engine/tests/hw_decode.rs +109 -0
- crates/engine/tests/rotation.rs +252 -0
- crates/engine/tests/silent_first_source.rs +153 -0
- scripts/gen_fixtures.sh +60 -0
crates/app/src/player/library.rsmodified+6 -0
| @@ -1407,6 +1407,12 @@ impl Player { | |||
| 1407 | .as_mut() | 1407 | .as_mut() |
| 1408 | .and_then(|session| subtitle_tail(session, subs)) | 1408 | .and_then(|session| subtitle_tail(session, subs)) |
| 1409 | .unwrap_or_default(); | 1409 | .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(); | ||
| 1410 | format!( | 1416 | format!( |
| 1411 | "IMPORTED {} to the library{tail}{}", | 1417 | "IMPORTED {} to the library{tail}{}", |
| 1412 | file_name(path), | 1418 | file_name(path), |
crates/engine-hw/src/lib.rsmodified+21 -0
| @@ -162,6 +162,15 @@ const DMA_HOLD: usize = 6; | |||
| 162 | /// real seek wins. | 162 | /// real seek wins. |
| 163 | const FORWARD_SECS: f64 = 0.5; | 163 | const FORWARD_SECS: f64 = 0.5; |
| 164 | 164 | ||
| 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 | + | ||
| 165 | /// The forward reach in frames: [`FORWARD_SECS`] at the stream's own rate. | 174 | /// The forward reach in frames: [`FORWARD_SECS`] at the stream's own rate. |
| 166 | /// `0` for a rate the stream does not really state, which is "never forward" | 175 | /// `0` for a rate the stream does not really state, which is "never forward" |
| 167 | /// -- exactly the flush every reposition did before this distinction existed. | 176 | /// -- exactly the flush every reposition did before this distinction existed. |
| @@ -559,6 +568,18 @@ impl Session { | |||
| 559 | Ok(0) => return Err("decoder consumed no input".into()), | 568 | Ok(0) => return Err("decoder consumed no input".into()), |
| 560 | Ok(n) => { | 569 | Ok(n) => { |
| 561 | pending.drain(..n.min(pending.len())); | 570 | 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 | + } | ||
| 562 | if pending.is_empty() { | 583 | if pending.is_empty() { |
| 563 | *timestamp += 1; | 584 | *timestamp += 1; |
| 564 | } | 585 | } |
crates/engine/src/audio.rsmodified+35 -14
| @@ -413,20 +413,41 @@ impl AudioSession { | |||
| 413 | fps: f64, | 413 | fps: f64, |
| 414 | sample_rate: Option<u32>, | 414 | sample_rate: Option<u32>, |
| 415 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | 415 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { |
| 416 | - // The first source that could have a track, which is not always index 0: | 416 | + // The first source that really *opens* a track, which is not always |
| 417 | - // a still image has none, and one at the front of the list (a save | 417 | + // index 0 and not always the first non-image one: a still image has no |
| 418 | - // renumbers, a library removal moves indexes) would be opened as a | 418 | + // track by definition, and a video whose file carries none (a screen |
| 419 | - // broken audio file and take the whole timeline's sound down with it. | 419 | + // recording with no sound) has `Track::open` answer `None`. Pinning to |
| 420 | - // The same rule `PlaybackSession` probes by (`audio_source_of`). | 420 | + // the first non-image source regardless would return `Ok(None)` for a |
| 421 | - let Some((at, (path, stream))) = sources | 421 | + // whole timeline whenever that one source happened to be silent, |
| 422 | - .iter() | 422 | + // silencing every later clip that does have sound -- the very failure |
| 423 | - .enumerate() | 423 | + // `PlaybackSession::open_project`'s device walk exists to prevent, and |
| 424 | - .find(|(_, (path, _))| !crate::is_image(path)) | 424 | + // it has to hold here too or the walk is defeated at playback. |
| 425 | - else { | 425 | + // |
| 426 | - return Ok(None); | 426 | + // A source that cannot be opened at all is skipped like a silent one, |
| 427 | - }; | 427 | + // so a broken file at the head of the list cannot take a later clip's |
| 428 | - let Some(first) = Track::open(path, *stream)? else { | 428 | + // sound down with it; the last error is kept and returned only when |
| 429 | - return Ok(None); | 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 | + }; | ||
| 430 | }; | 451 | }; |
| 431 | // The timeline's meta is that source's: policy makes every other source | 452 | // The timeline's meta is that source's: policy makes every other source |
| 432 | // match it, and the checks below hold them to that. | 453 | // 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; | |||
| 18 | use crate::color::ColorParams; | 18 | use crate::color::ColorParams; |
| 19 | use crate::colorspace::{ColorDescription, Matrix, Transfer}; | 19 | use crate::colorspace::{ColorDescription, Matrix, Transfer}; |
| 20 | use crate::convert::{i420_to_bgra, i420_to_bgra_with}; | 20 | 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}; |
| 22 | use crate::hw::HwSession; | 22 | use crate::hw::HwSession; |
| 23 | use crate::project::Speed; | 23 | use crate::project::Speed; |
| 24 | use crate::scale::Composer; | 24 | use crate::scale::Composer; |
| @@ -561,6 +561,8 @@ impl DecodeSession { | |||
| 561 | let first = Render::new( | 561 | let first = Render::new( |
| 562 | color, | 562 | color, |
| 563 | transform, | 563 | transform, |
| 564 | + // A still has no display matrix: what the file holds is what it is. | ||
| 565 | + Rotation::None, | ||
| 564 | ColorDescription::default(), | 566 | ColorDescription::default(), |
| 565 | canvas, | 567 | canvas, |
| 566 | tonemap::Preset::default(), | 568 | tonemap::Preset::default(), |
| @@ -674,6 +676,8 @@ impl DecodeSession { | |||
| 674 | let mut render = Render::new( | 676 | let mut render = Render::new( |
| 675 | color, | 677 | color, |
| 676 | transform, | 678 | transform, |
| 679 | + // Painted here, at the canvas's own size: nothing turned it. | ||
| 680 | + Rotation::None, | ||
| 677 | ColorDescription::default(), | 681 | ColorDescription::default(), |
| 678 | canvas, | 682 | canvas, |
| 679 | tonemap::Preset::default(), | 683 | tonemap::Preset::default(), |
| @@ -1081,7 +1085,15 @@ fn run_span( | |||
| 1081 | // The stream's own colour and peak brightness: properties of the stream, so | 1085 | // The stream's own colour and peak brightness: properties of the stream, so |
| 1082 | // neither can change while one range decodes -- but the grade, the canvas | 1086 | // neither can change while one range decodes -- but the grade, the canvas |
| 1083 | // and the rendition are the *span's*, so this is built per span. | 1087 | // 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 | + ); | ||
| 1085 | if let Some(reused) = opened.position_hw(path, start) { | 1097 | if let Some(reused) = opened.position_hw(path, start) { |
| 1086 | // Cancelled during the init (or the seek): leave without decoding. | 1098 | // Cancelled during the init (or the seek): leave without decoding. |
| 1087 | if abort.hit() { | 1099 | if abort.hit() { |
| @@ -1152,6 +1164,13 @@ struct Render { | |||
| 1152 | /// This clip's placement, on top of whatever the canvas's own fit policy | 1164 | /// This clip's placement, on top of whatever the canvas's own fit policy |
| 1153 | /// already does ([`crate::scale::Composer::place_transformed`]). | 1165 | /// already does ([`crate::scale::Composer::place_transformed`]). |
| 1154 | transform: TransformParams, | 1166 | 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, | ||
| 1155 | /// What the source's samples mean -- the stream's own matrix and range, | 1174 | /// What the source's samples mean -- the stream's own matrix and range, |
| 1156 | /// which is what the conversion below is done in rather than the BT.601 it | 1175 | /// which is what the conversion below is done in rather than the BT.601 it |
| 1157 | /// used to assume of every file. | 1176 | /// used to assume of every file. |
| @@ -1166,6 +1185,10 @@ struct Render { | |||
| 1166 | /// across the worker's whole range. Empty unless the clip needs one: it is | 1185 | /// across the worker's whole range. Empty unless the clip needs one: it is |
| 1167 | /// tone-mapped in place, graded in place, or both. | 1186 | /// tone-mapped in place, graded in place, or both. |
| 1168 | graded: (Vec<u8>, Vec<u8>, Vec<u8>), | 1187 | 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>), | ||
| 1169 | /// Where [`Composer::place_transformed`]'s owned picture lands, so a | 1192 | /// Where [`Composer::place_transformed`]'s owned picture lands, so a |
| 1170 | /// transformed frame's planes live as long as `self` -- matching what | 1193 | /// transformed frame's planes live as long as `self` -- matching what |
| 1171 | /// [`Composer::place`] already hands back by borrowing `self.canvas`. | 1194 | /// [`Composer::place`] already hands back by borrowing `self.canvas`. |
| @@ -1188,6 +1211,7 @@ impl Render { | |||
| 1188 | fn new( | 1211 | fn new( |
| 1189 | color: ColorParams, | 1212 | color: ColorParams, |
| 1190 | transform: TransformParams, | 1213 | transform: TransformParams, |
| 1214 | + rotation: Rotation, | ||
| 1191 | desc: ColorDescription, | 1215 | desc: ColorDescription, |
| 1192 | canvas: Composer, | 1216 | canvas: Composer, |
| 1193 | preset: tonemap::Preset, | 1217 | preset: tonemap::Preset, |
| @@ -1196,6 +1220,7 @@ impl Render { | |||
| 1196 | Self { | 1220 | Self { |
| 1197 | color, | 1221 | color, |
| 1198 | transform, | 1222 | transform, |
| 1223 | + rotation, | ||
| 1199 | desc, | 1224 | desc, |
| 1200 | canvas, | 1225 | canvas, |
| 1201 | // corner-cut: the ceiling is that the map reads limited-range codes | 1226 | // corner-cut: the ceiling is that the map reads limited-range codes |
| @@ -1209,6 +1234,7 @@ impl Render { | |||
| 1209 | Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)), | 1234 | Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)), |
| 1210 | }, | 1235 | }, |
| 1211 | graded: (Vec::new(), Vec::new(), Vec::new()), | 1236 | graded: (Vec::new(), Vec::new(), Vec::new()), |
| 1237 | + turned: (Vec::new(), Vec::new(), Vec::new()), | ||
| 1212 | placed: (Vec::new(), Vec::new(), Vec::new()), | 1238 | placed: (Vec::new(), Vec::new(), Vec::new()), |
| 1213 | } | 1239 | } |
| 1214 | } | 1240 | } |
| @@ -1222,6 +1248,34 @@ impl Render { | |||
| 1222 | width: u32, | 1248 | width: u32, |
| 1223 | height: u32, | 1249 | height: u32, |
| 1224 | ) -> Frame { | 1250 | ) -> 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 | + }; | ||
| 1225 | let passthrough = self.canvas.is_passthrough(width, height); | 1279 | let passthrough = self.canvas.is_passthrough(width, height); |
| 1226 | // A transform still has a picture to place even where the canvas | 1280 | // A transform still has a picture to place even where the canvas |
| 1227 | // itself would hand this size back untouched -- moving, scaling, | 1281 | // itself would hand this size back untouched -- moving, scaling, |
crates/engine/src/demux.rsmodified+189 -2
| @@ -267,9 +267,102 @@ impl NoVideoTrack { | |||
| 267 | } | 267 | } |
| 268 | } | 268 | } |
| 269 | 269 | ||
| 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 | + | ||
| 270 | #[derive(Debug, Clone, Copy, PartialEq)] | 360 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 271 | pub struct VideoMeta { | 361 | 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`]). | ||
| 272 | pub width: u32, | 364 | pub width: u32, |
| 365 | + /// The displayed height; see [`VideoMeta::width`]. | ||
| 273 | pub height: u32, | 366 | pub height: u32, |
| 274 | pub frame_rate: f64, | 367 | pub frame_rate: f64, |
| 275 | pub frame_count: u32, | 368 | pub frame_count: u32, |
| @@ -278,6 +371,14 @@ pub struct VideoMeta { | |||
| 278 | /// which range -- resolved off the container's tags, the bitstream's, and | 371 | /// which range -- resolved off the container's tags, the bitstream's, and |
| 279 | /// the resolution, in that order. See [`crate::colorspace`]. | 372 | /// the resolution, in that order. See [`crate::colorspace`]. |
| 280 | pub color: ColorDescription, | 373 | 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, | ||
| 281 | } | 382 | } |
| 282 | 383 | ||
| 283 | /// What a file spends its bytes at, in bits per second -- the whole file, and | 384 | /// What a file spends its bytes at, in bits per second -- the whole file, and |
| @@ -730,15 +831,41 @@ impl Mp4Demuxer { | |||
| 730 | .ok_or_else(|| mp4_no_video(path, &reader))?; | 831 | .ok_or_else(|| mp4_no_video(path, &reader))?; |
| 731 | 832 | ||
| 732 | let track_id = track.track_id(); | 833 | 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 | + }; | ||
| 733 | let meta = VideoMeta { | 859 | let meta = VideoMeta { |
| 734 | - width: track.width() as u32, | 860 | + width, |
| 735 | - height: track.height() as u32, | 861 | + height, |
| 736 | frame_rate: frame_rate(track), | 862 | frame_rate: frame_rate(track), |
| 737 | frame_count: 0, | 863 | frame_count: 0, |
| 738 | codec, | 864 | codec, |
| 739 | // Filled below, once the parameter sets the bitstream tier reads are | 865 | // Filled below, once the parameter sets the bitstream tier reads are |
| 740 | // in hand. | 866 | // in hand. |
| 741 | color: ColorDescription::default(), | 867 | color: ColorDescription::default(), |
| 868 | + rotation, | ||
| 742 | }; | 869 | }; |
| 743 | let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track)); | 870 | let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track)); |
| 744 | let mut parameter_sets = Vec::new(); | 871 | let mut parameter_sets = Vec::new(); |
| @@ -1196,6 +1323,11 @@ impl MkvDemuxer { | |||
| 1196 | bitstream_tags(video.codec, &mkv.config), | 1323 | bitstream_tags(video.codec, &mkv.config), |
| 1197 | video.height, | 1324 | video.height, |
| 1198 | ), | 1325 | ), |
| 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, | ||
| 1199 | }; | 1331 | }; |
| 1200 | Ok((meta, mkv)) | 1332 | Ok((meta, mkv)) |
| 1201 | } | 1333 | } |
| @@ -2497,6 +2629,61 @@ fn parse_av1c(rec: &[u8]) -> crate::Result<(Vec<u8>, u8)> { | |||
| 2497 | Ok((rec.get(4..).unwrap_or_default().to_vec(), bit_depth)) | 2629 | Ok((rec.get(4..).unwrap_or_default().to_vec(), bit_depth)) |
| 2498 | } | 2630 | } |
| 2499 | 2631 | ||
| 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 | + | ||
| 2500 | /// Why an mp4 came back with no picture, by the fourcc of the video track it | 2687 | /// Why an mp4 came back with no picture, by the fourcc of the video track it |
| 2501 | /// does carry: `avc3` and `mp4v` are files with video in them, and telling their | 2688 | /// does carry: `avc3` and `mp4v` are files with video in them, and telling their |
| 2502 | /// owner there is none sends them looking for a fault that is not in the file. | 2689 | /// 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 _; | |||
| 80 | 80 | ||
| 81 | use crate::audio::{AudioMeta, AudioSession}; | 81 | use crate::audio::{AudioMeta, AudioSession}; |
| 82 | use crate::colorspace::{ColorDescription, Matrix, Transfer}; | 82 | use crate::colorspace::{ColorDescription, Matrix, Transfer}; |
| 83 | -use crate::demux::{Codec, Demuxer, MkvDemuxer, VideoMeta}; | 83 | +use crate::demux::{Codec, Demuxer, MkvDemuxer, Rotation, VideoMeta}; |
| 84 | use crate::hw::{DmaFrame, DmaWant, HwEncoder, HwPicture, HwSession}; | 84 | use crate::hw::{DmaFrame, DmaWant, HwEncoder, HwPicture, HwSession}; |
| 85 | use crate::mux::{ | 85 | use crate::mux::{ |
| 86 | AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, | 86 | AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, |
| @@ -1174,7 +1174,13 @@ struct Dissolve<'a> { | |||
| 1174 | remap: Option<(Matrix, Matrix)>, | 1174 | remap: Option<(Matrix, Matrix)>, |
| 1175 | grade: Option<crate::color::ColorParams>, | 1175 | grade: Option<crate::color::ColorParams>, |
| 1176 | transform: TransformParams, | 1176 | 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, | ||
| 1177 | canvas: Composer, | 1180 | 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>), | ||
| 1178 | graded: (Vec<u8>, Vec<u8>, Vec<u8>), | 1184 | graded: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 1179 | transformed: (Vec<u8>, Vec<u8>, Vec<u8>), | 1185 | transformed: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 1180 | } | 1186 | } |
| @@ -1801,7 +1807,14 @@ impl CopyPlan { | |||
| 1801 | // The stream this file would carry, at the size and the rate the | 1807 | // The stream this file would carry, at the size and the rate the |
| 1802 | // timeline is in: anything else is a picture that has to be | 1808 | // timeline is in: anything else is a picture that has to be |
| 1803 | // coded again to become this file's. | 1809 | // 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 | ||
| 1805 | || source_meta.width != meta.width | 1818 | || source_meta.width != meta.width |
| 1806 | || source_meta.height != meta.height | 1819 | || source_meta.height != meta.height |
| 1807 | || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()? | 1820 | || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()? |
| @@ -2652,7 +2665,7 @@ fn run( | |||
| 2652 | // samples *mean* ([`ColorDescription`]), which is what decides whether they | 2665 | // samples *mean* ([`ColorDescription`]), which is what decides whether they |
| 2653 | // are remapped on the way in. Real time for a still, a song and a | 2666 | // are remapped on the way in. Real time for a still, a song and a |
| 2654 | // single-rate project, where every conversion below is the identity. | 2667 | // 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 |
| 2656 | .iter() | 2669 | .iter() |
| 2657 | .map(|source| source_rate(&source.path, meta.frame_rate)) | 2670 | .map(|source| source_rate(&source.path, meta.frame_rate)) |
| 2658 | .collect(); | 2671 | .collect(); |
| @@ -2671,7 +2684,7 @@ fn run( | |||
| 2671 | let preset = project.tone(); | 2684 | let preset = project.tone(); |
| 2672 | let tone: Vec<Option<ToneMapper>> = rates | 2685 | let tone: Vec<Option<ToneMapper>> = rates |
| 2673 | .iter() | 2686 | .iter() |
| 2674 | - .map(|(_, color, peak)| match color.transfer { | 2687 | + .map(|(_, color, peak, _)| match color.transfer { |
| 2675 | // A preview file keeps the film's own curve and is tone-mapped when | 2688 | // A preview file keeps the film's own curve and is tone-mapped when |
| 2676 | // it is *shown* ([`ExportSettings::keep_source_colour`]), which is | 2689 | // it is *shown* ([`ExportSettings::keep_source_colour`]), which is |
| 2677 | // both cheaper and the only way the preset can still be changed | 2690 | // both cheaper and the only way the preset can still be changed |
| @@ -2734,12 +2747,12 @@ fn run( | |||
| 2734 | // A's pixels on the CPU, so a dissolving span never asks for a GPU | 2747 | // A's pixels on the CPU, so a dissolving span never asks for a GPU |
| 2735 | // buffer, not even outside its own window. | 2748 | // buffer, not even outside its own window. |
| 2736 | let dissolve = dissolve_window(project, &span); | 2749 | 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 { |
| 2738 | Some((source, in_frame)) => { | 2751 | Some((source, in_frame)) => { |
| 2739 | let entry = sources | 2752 | let entry = sources |
| 2740 | .get(source) | 2753 | .get(source) |
| 2741 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; | 2754 | .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]; |
| 2743 | let mapper = tone[source].as_ref(); | 2756 | let mapper = tone[source].as_ref(); |
| 2744 | // Nothing on the way from this span's decoder to the encoder | 2757 | // Nothing on the way from this span's decoder to the encoder |
| 2745 | // touches a sample: no tone map, no matrix remap, no grade -- | 2758 | // touches a sample: no tone map, no matrix remap, no grade -- |
| @@ -2756,6 +2769,11 @@ fn run( | |||
| 2756 | && project | 2769 | && project |
| 2757 | .composite_transform_at(span.start) | 2770 | .composite_transform_at(span.start) |
| 2758 | .is_none_or(|params| params.is_identity()) | 2771 | .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() | ||
| 2759 | && dissolve.is_none(); | 2777 | && dissolve.is_none(); |
| 2760 | let want = untouched.then(|| encoder.dma_want(meta)).flatten(); | 2778 | let want = untouched.then(|| encoder.dma_want(meta)).flatten(); |
| 2761 | // Opened at the file's own frame, which is the only place the | 2779 | // Opened at the file's own frame, which is the only place the |
| @@ -2775,12 +2793,13 @@ fn run( | |||
| 2775 | } else { | 2793 | } else { |
| 2776 | ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)? | 2794 | ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)? |
| 2777 | }; | 2795 | }; |
| 2778 | - (Some(pictures), rate, in_frame, Some(color), mapper) | 2796 | + (Some(pictures), rate, in_frame, Some(color), mapper, rotation) |
| 2779 | } | 2797 | } |
| 2780 | // A gap's black is 16/128/128, which is black in every matrix here | 2798 | // A gap's black is 16/128/128, which is black in every matrix here |
| 2781 | // and on every curve: nothing to remap and nothing to tone-map, | 2799 | // and on every curve: nothing to remap and nothing to tone-map, |
| 2782 | - // which is what `None` says. | 2800 | + // which is what `None` says. A gap is no file either, so nothing |
| 2783 | - None => (None, Rate::REAL_TIME, 0, None, None), | 2801 | + // turns it. |
| 2802 | + None => (None, Rate::REAL_TIME, 0, None, None, Rotation::None), | ||
| 2784 | }; | 2803 | }; |
| 2785 | // Mixed spaces on one timeline: a clip coded against another matrix than | 2804 | // Mixed spaces on one timeline: a clip coded against another matrix than |
| 2786 | // the one this file declares is rewritten into it, *after* the grade -- | 2805 | // the one this file declares is rewritten into it, *after* the grade -- |
| @@ -2805,6 +2824,10 @@ fn run( | |||
| 2805 | .unwrap_or_default(); | 2824 | .unwrap_or_default(); |
| 2806 | let mut graded = (Vec::new(), Vec::new(), Vec::new()); | 2825 | let mut graded = (Vec::new(), Vec::new(), Vec::new()); |
| 2807 | let mut transformed = (Vec::new(), Vec::new(), Vec::new()); | 2826 | 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()); | ||
| 2808 | // ...and the canvas it is placed on, which is where a source of another | 2831 | // ...and the canvas it is placed on, which is where a source of another |
| 2809 | // resolution becomes a picture at the project's. The same `Composer` | 2832 | // resolution becomes a picture at the project's. The same `Composer` |
| 2810 | // playback composes with, given the same policy, so an export is what | 2833 | // playback composes with, given the same policy, so an export is what |
| @@ -2823,7 +2846,7 @@ fn run( | |||
| 2823 | let entry = sources.get(b_source).ok_or_else(|| { | 2846 | let entry = sources.get(b_source).ok_or_else(|| { |
| 2824 | format!("clip names source {b_source} of {}", sources.len()) | 2847 | format!("clip names source {b_source} of {}", sources.len()) |
| 2825 | })?; | 2848 | })?; |
| 2826 | - let (b_rate, b_color, _peak) = rates[b_source]; | 2849 | + let (b_rate, b_color, _peak, b_rotation) = rates[b_source]; |
| 2827 | let b_mapper = tone[b_source].as_ref(); | 2850 | let b_mapper = tone[b_source].as_ref(); |
| 2828 | let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix); | 2851 | let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix); |
| 2829 | Ok(Dissolve { | 2852 | Ok(Dissolve { |
| @@ -2852,11 +2875,13 @@ fn run( | |||
| 2852 | .composite_transform_at(b_start) | 2875 | .composite_transform_at(b_start) |
| 2853 | .copied() | 2876 | .copied() |
| 2854 | .unwrap_or_default(), | 2877 | .unwrap_or_default(), |
| 2878 | + rotation: b_rotation, | ||
| 2855 | canvas: Composer::new( | 2879 | canvas: Composer::new( |
| 2856 | meta.width, | 2880 | meta.width, |
| 2857 | meta.height, | 2881 | meta.height, |
| 2858 | project.composite_fit_at(b_start), | 2882 | project.composite_fit_at(b_start), |
| 2859 | ), | 2883 | ), |
| 2884 | + rotated: (Vec::new(), Vec::new(), Vec::new()), | ||
| 2860 | graded: (Vec::new(), Vec::new(), Vec::new()), | 2885 | graded: (Vec::new(), Vec::new(), Vec::new()), |
| 2861 | transformed: (Vec::new(), Vec::new(), Vec::new()), | 2886 | transformed: (Vec::new(), Vec::new(), Vec::new()), |
| 2862 | }) | 2887 | }) |
| @@ -2946,10 +2971,12 @@ fn run( | |||
| 2946 | v, | 2971 | v, |
| 2947 | width, | 2972 | width, |
| 2948 | height, | 2973 | height, |
| 2974 | + rotation, | ||
| 2949 | grade, | 2975 | grade, |
| 2950 | transform, | 2976 | transform, |
| 2951 | remap, | 2977 | remap, |
| 2952 | mapper, | 2978 | mapper, |
| 2979 | + &mut rotated, | ||
| 2953 | &mut graded, | 2980 | &mut graded, |
| 2954 | &mut transformed, | 2981 | &mut transformed, |
| 2955 | &mut canvas, | 2982 | &mut canvas, |
| @@ -2979,9 +3006,9 @@ fn run( | |||
| 2979 | } | 3006 | } |
| 2980 | Some(Frame::Pixels(by, bu, bv, bw, bh)) => { | 3007 | Some(Frame::Pixels(by, bu, bv, bw, bh)) => { |
| 2981 | let (by, bu, bv, _, _) = place_picture( | 3008 | let (by, bu, bv, _, _) = place_picture( |
| 2982 | - by, bu, bv, bw, bh, d.grade, d.transform, d.remap, | 3009 | + by, bu, bv, bw, bh, d.rotation, d.grade, d.transform, |
| 2983 | - d.mapper, &mut d.graded, &mut d.transformed, | 3010 | + d.remap, d.mapper, &mut d.rotated, &mut d.graded, |
| 2984 | - &mut d.canvas, | 3011 | + &mut d.transformed, &mut d.canvas, |
| 2985 | ); | 3012 | ); |
| 2986 | let idx_in_window = done_here + r - d.tail_start; | 3013 | let idx_in_window = done_here + r - d.tail_start; |
| 2987 | let t = dissolve_weight(idx_in_window, d.window); | 3014 | let t = dissolve_weight(idx_in_window, d.window); |
| @@ -3111,12 +3138,16 @@ fn run( | |||
| 3111 | Ok(()) | 3138 | Ok(()) |
| 3112 | } | 3139 | } |
| 3113 | 3140 | ||
| 3114 | -/// One decoded picture graded, tone-mapped, remapped and placed on the canvas | 3141 | +/// One decoded picture turned, graded, tone-mapped, remapped and placed on the |
| 3115 | -/// -- everything between a source's own samples and the ones an encoder is fed, | 3142 | +/// canvas -- everything between a source's own samples and the ones an encoder |
| 3116 | -/// which is exactly the work a zero-copy span has none of. | 3143 | +/// is fed, which is exactly the work a zero-copy span has none of. |
| 3117 | /// | 3144 | /// |
| 3118 | -/// `graded` and `canvas` are the span's scratch: the planes come back borrowed | 3145 | +/// `rotation` first, before the grade: it is the file's own display matrix, the |
| 3119 | -/// from one of them, or from the picture itself where not a byte was touched. | 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. | ||
| 3120 | #[expect(clippy::too_many_arguments, reason = "one span's whole picture path")] | 3151 | #[expect(clippy::too_many_arguments, reason = "one span's whole picture path")] |
| 3121 | fn place_picture<'a>( | 3152 | fn place_picture<'a>( |
| 3122 | y: &'a [u8], | 3153 | y: &'a [u8], |
| @@ -3124,14 +3155,35 @@ fn place_picture<'a>( | |||
| 3124 | v: &'a [u8], | 3155 | v: &'a [u8], |
| 3125 | width: u32, | 3156 | width: u32, |
| 3126 | height: u32, | 3157 | height: u32, |
| 3158 | + rotation: Rotation, | ||
| 3127 | grade: Option<crate::color::ColorParams>, | 3159 | grade: Option<crate::color::ColorParams>, |
| 3128 | transform: TransformParams, | 3160 | transform: TransformParams, |
| 3129 | remap: Option<(Matrix, Matrix)>, | 3161 | remap: Option<(Matrix, Matrix)>, |
| 3130 | mapper: Option<&ToneMapper>, | 3162 | mapper: Option<&ToneMapper>, |
| 3163 | + turned: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), | ||
| 3131 | graded: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), | 3164 | graded: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3132 | transformed: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), | 3165 | transformed: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3133 | canvas: &'a mut Composer, | 3166 | canvas: &'a mut Composer, |
| 3134 | ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) { | 3167 | ) -> (&'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 | + }; | ||
| 3135 | // The planes are borrowed from the decoder (and `Black::picture` hands the | 3187 | // The planes are borrowed from the decoder (and `Black::picture` hands the |
| 3136 | // same slice as both u and v), so a grade cannot be applied in place: it | 3188 | // same slice as both u and v), so a grade cannot be applied in place: it |
| 3137 | // goes onto a copy, which the encoder then reads instead. | 3189 | // goes onto a copy, which the encoder then reads instead. |
| @@ -3199,12 +3251,16 @@ fn remap_into( | |||
| 3199 | /// -- a still, a song -- and for one that will not open here: the decoder is | 3251 | /// -- a still, a song -- and for one that will not open here: the decoder is |
| 3200 | /// opened a few lines later and fails the export by name, which is a better | 3252 | /// opened a few lines later and fails the export by name, which is a better |
| 3201 | /// error than this one could raise. | 3253 | /// 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) { | ||
| 3203 | if crate::is_image(path) || crate::is_audio(path) { | 3258 | if crate::is_image(path) || crate::is_audio(path) { |
| 3204 | // A still is BT.601 by construction whatever it was authored as: | 3259 | // A still is BT.601 by construction whatever it was authored as: |
| 3205 | // `decode::rgb_to_i420` is the one matrix that turns its pixels into | 3260 | // `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. | 3261 | + // planes. A song has no picture and the answer is never read. Neither |
| 3207 | - return (Rate::REAL_TIME, ColorDescription::default(), None); | 3262 | + // has a display matrix to be turned by. |
| 3263 | + return (Rate::REAL_TIME, ColorDescription::default(), None, Rotation::None); | ||
| 3208 | } | 3264 | } |
| 3209 | match Demuxer::open(path) { | 3265 | match Demuxer::open(path) { |
| 3210 | // ...and one whose rate cannot be named against the timeline's, which | 3266 | // ...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 | |||
| 3218 | Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), | 3274 | Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), |
| 3219 | meta.color, | 3275 | meta.color, |
| 3220 | demuxer.light().peak(), | 3276 | 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, | ||
| 3221 | ), | 3280 | ), |
| 3222 | // Unreadable here means unreadable below too, where the span dies with a | 3281 | // Unreadable here means unreadable below too, where the span dies with a |
| 3223 | // real message; the file's own space is the least of that. | 3282 | // 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), |
| 3225 | } | 3284 | } |
| 3226 | } | 3285 | } |
| 3227 | 3286 | ||
| @@ -4397,9 +4456,11 @@ fn pop_av1<'a>( | |||
| 4397 | /// which would cost two conversions and a generation of colour precision. | 4456 | /// which would cost two conversions and a generation of colour precision. |
| 4398 | /// | 4457 | /// |
| 4399 | /// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`, | 4458 | /// 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 | 4459 | +/// which only speaks BGRA. A hardware decode that fails *before* the first |
| 4401 | -/// software: a hardware decode that fails after the first picture fails the | 4460 | +/// picture falls back to software, exactly as playback's does -- nothing has |
| 4402 | -/// export, which then deletes the half-written file. | 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. | ||
| 4403 | enum ClipDecoder { | 4464 | enum ClipDecoder { |
| 4404 | /// A stream, decoded on a thread of its own: the encode of picture *n* and | 4465 | /// A stream, decoded on a thread of its own: the encode of picture *n* and |
| 4405 | /// the decode of picture *n + 1* are the two halves an export used to do in | 4466 | /// the decode of picture *n + 1* are the two halves an export used to do in |
| @@ -4628,9 +4689,9 @@ impl ClipDecoder { | |||
| 4628 | /// will have it, software otherwise) and send every picture until the encoder | 4689 | /// will have it, software otherwise) and send every picture until the encoder |
| 4629 | /// stops taking them. | 4690 | /// stops taking them. |
| 4630 | /// | 4691 | /// |
| 4631 | -/// Unlike playback there is no mid-clip fallback to software: a hardware decode | 4692 | +/// Hardware that fails before the first picture falls back to the software seat |
| 4632 | -/// that fails after the first picture fails the export, which then deletes the | 4693 | +/// (see the loop's `decoded == 0` arm); one that fails after it fails the |
| 4633 | -/// half-written file. | 4694 | +/// export, which then deletes the half-written file. |
| 4634 | /// | 4695 | /// |
| 4635 | /// Every way this returns says which way it was, down the channel: a picture, an | 4696 | /// Every way this returns says which way it was, down the channel: a picture, an |
| 4636 | /// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not | 4697 | /// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not |
| @@ -4656,6 +4717,12 @@ fn decode_stream( | |||
| 4656 | } | 4717 | } |
| 4657 | }, | 4718 | }, |
| 4658 | }; | 4719 | }; |
| 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; | ||
| 4659 | loop { | 4726 | loop { |
| 4660 | let frame = match decoder.next(want) { | 4727 | let frame = match decoder.next(want) { |
| 4661 | Ok(Some(frame)) => frame, | 4728 | Ok(Some(frame)) => frame, |
| @@ -4664,6 +4731,21 @@ fn decode_stream( | |||
| 4664 | return; | 4731 | return; |
| 4665 | } | 4732 | } |
| 4666 | Err(e) => { | 4733 | 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 | + } | ||
| 4667 | let _ = tx.send(Err(e)); | 4749 | let _ = tx.send(Err(e)); |
| 4668 | return; | 4750 | return; |
| 4669 | } | 4751 | } |
| @@ -4673,6 +4755,7 @@ fn decode_stream( | |||
| 4673 | if tx.send(Ok(Some(frame))).is_err() { | 4755 | if tx.send(Ok(Some(frame))).is_err() { |
| 4674 | return; | 4756 | return; |
| 4675 | } | 4757 | } |
| 4758 | + decoded += 1; | ||
| 4676 | } | 4759 | } |
| 4677 | } | 4760 | } |
| 4678 | 4761 | ||
| @@ -5283,6 +5366,7 @@ mod tests { | |||
| 5283 | frame_count: 1, | 5366 | frame_count: 1, |
| 5284 | codec: crate::demux::Codec::H264, | 5367 | codec: crate::demux::Codec::H264, |
| 5285 | color: Default::default(), | 5368 | color: Default::default(), |
| 5369 | + rotation: Rotation::None, | ||
| 5286 | }; | 5370 | }; |
| 5287 | // 1280 * 720 * 30 * 0.1 | 5371 | // 1280 * 720 * 30 * 0.1 |
| 5288 | assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); | 5372 | assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); |
| @@ -5332,6 +5416,7 @@ mod tests { | |||
| 5332 | frame_count: 1, | 5416 | frame_count: 1, |
| 5333 | codec: crate::demux::Codec::H264, | 5417 | codec: crate::demux::Codec::H264, |
| 5334 | color: Default::default(), | 5418 | color: Default::default(), |
| 5419 | + rotation: Rotation::None, | ||
| 5335 | } | 5420 | } |
| 5336 | } | 5421 | } |
| 5337 | 5422 | ||
crates/engine/src/lib.rsmodified+17 -2
| @@ -37,7 +37,7 @@ pub use audio::{ | |||
| 37 | }; | 37 | }; |
| 38 | pub use clock::PlaybackClock; | 38 | pub use clock::PlaybackClock; |
| 39 | pub use decode::{DecodeSession, Frame, image_size}; | 39 | 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}; |
| 41 | pub use export::ExportHandle; | 41 | pub use export::ExportHandle; |
| 42 | pub use mux::{AudioParams, Mp4Muxer, VideoParams}; | 42 | pub use mux::{AudioParams, Mp4Muxer, VideoParams}; |
| 43 | pub use playback::{ImportGate, ImportProbe, PlaybackSession}; | 43 | pub use playback::{ImportGate, ImportProbe, PlaybackSession}; |
| @@ -55,11 +55,24 @@ pub use project::{Clip, Project, Rate, Speed}; | |||
| 55 | /// has. A `.dts` or a bare `.ac3` is refused by the same door that refuses a | 55 | /// has. A `.dts` or a bare `.ac3` is refused by the same door that refuses a |
| 56 | /// `.txt` -- there is no reader here that opens an elementary stream -- which is | 56 | /// `.txt` -- there is no reader here that opens an elementary stream -- which is |
| 57 | /// the honest answer. | 57 | /// 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.) | ||
| 58 | pub fn is_audio(path: &std::path::Path) -> bool { | 71 | pub fn is_audio(path: &std::path::Path) -> bool { |
| 59 | path.extension().and_then(|e| e.to_str()).is_some_and(|e| { | 72 | path.extension().and_then(|e| e.to_str()).is_some_and(|e| { |
| 60 | matches!( | 73 | matches!( |
| 61 | e.to_ascii_lowercase().as_str(), | 74 | 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" |
| 63 | ) | 76 | ) |
| 64 | }) | 77 | }) |
| 65 | } | 78 | } |
| @@ -117,6 +130,8 @@ mod tests { | |||
| 117 | "g.opus", | 130 | "g.opus", |
| 118 | "h.OPUS", | 131 | "h.OPUS", |
| 119 | "i.mka", | 132 | "i.mka", |
| 133 | + "j.MPEG", | ||
| 134 | + "k.mpg", | ||
| 120 | ] { | 135 | ] { |
| 121 | assert!(super::is_audio(Path::new(name)), "{name}"); | 136 | assert!(super::is_audio(Path::new(name)), "{name}"); |
| 122 | } | 137 | } |
crates/engine/src/playback.rsmodified+83 -24
| @@ -24,7 +24,7 @@ use crate::clock::{ClockSource, PlaybackClock}; | |||
| 24 | use crate::color::ColorParams; | 24 | use crate::color::ColorParams; |
| 25 | use crate::colorspace::{ColorDescription, ContentLight}; | 25 | use crate::colorspace::{ColorDescription, ContentLight}; |
| 26 | use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; | 26 | use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; |
| 27 | -use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta}; | 27 | +use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta}; |
| 28 | use crate::eq::EqParams; | 28 | use crate::eq::EqParams; |
| 29 | use crate::project::{ | 29 | use crate::project::{ |
| 30 | Clip, Edge, GapSweep, Lane, LaneKind, Project, Rate, Source, Span, Speed, SubClip, | 30 | Clip, Edge, GapSweep, Lane, LaneKind, Project, Rate, Source, Span, Speed, SubClip, |
| @@ -704,6 +704,7 @@ impl PlaybackSession { | |||
| 704 | // A canvas this engine drew itself, not a stream that was read: | 704 | // A canvas this engine drew itself, not a stream that was read: |
| 705 | // the default description is what it is drawn in. | 705 | // the default description is what it is drawn in. |
| 706 | color: ColorDescription::default(), | 706 | color: ColorDescription::default(), |
| 707 | + rotation: Rotation::None, | ||
| 707 | }; | 708 | }; |
| 708 | let (audio, audio_disabled) = open_audio(path, stream); | 709 | let (audio, audio_disabled) = open_audio(path, stream); |
| 709 | // Through `from_parts` rather than `Project::single`, which is the | 710 | // Through `from_parts` rather than `Project::single`, which is the |
| @@ -801,6 +802,7 @@ impl PlaybackSession { | |||
| 801 | frame_count: image_frames(IMAGE_ONLY_RATE), | 802 | frame_count: image_frames(IMAGE_ONLY_RATE), |
| 802 | codec: Codec::H264, | 803 | codec: Codec::H264, |
| 803 | color: ColorDescription::default(), | 804 | color: ColorDescription::default(), |
| 805 | + rotation: Rotation::None, | ||
| 804 | }; | 806 | }; |
| 805 | let clip = Clip { | 807 | let clip = Clip { |
| 806 | fade_in: 0, | 808 | fade_in: 0, |
| @@ -964,6 +966,7 @@ impl PlaybackSession { | |||
| 964 | .map_err(|e| format!("source {}: {e}", first.path.display()))?, | 966 | .map_err(|e| format!("source {}: {e}", first.path.display()))?, |
| 965 | codec: Codec::H264, | 967 | codec: Codec::H264, |
| 966 | color: ColorDescription::default(), | 968 | color: ColorDescription::default(), |
| 969 | + rotation: Rotation::None, | ||
| 967 | }; | 970 | }; |
| 968 | (meta, DecodeSession::open_black(width, height, 1)) | 971 | (meta, DecodeSession::open_black(width, height, 1)) |
| 969 | } | 972 | } |
| @@ -981,6 +984,7 @@ impl PlaybackSession { | |||
| 981 | frame_count: image_frames(frame_rate), | 984 | frame_count: image_frames(frame_rate), |
| 982 | codec: Codec::H264, | 985 | codec: Codec::H264, |
| 983 | color: ColorDescription::default(), | 986 | color: ColorDescription::default(), |
| 987 | + rotation: Rotation::None, | ||
| 984 | }; | 988 | }; |
| 985 | let stream = DecodeSession::open_still( | 989 | let stream = DecodeSession::open_still( |
| 986 | &first.path, | 990 | &first.path, |
| @@ -1022,6 +1026,7 @@ impl PlaybackSession { | |||
| 1022 | .map_err(|e| format!("source {}: {e}", first.path.display()))?, | 1026 | .map_err(|e| format!("source {}: {e}", first.path.display()))?, |
| 1023 | codec: Codec::H264, | 1027 | codec: Codec::H264, |
| 1024 | color: ColorDescription::default(), | 1028 | color: ColorDescription::default(), |
| 1029 | + rotation: Rotation::None, | ||
| 1025 | }; | 1030 | }; |
| 1026 | (meta, DecodeSession::open_black(width, height, 1)) | 1031 | (meta, DecodeSession::open_black(width, height, 1)) |
| 1027 | } | 1032 | } |
| @@ -2646,6 +2651,43 @@ impl PlaybackSession { | |||
| 2646 | } | 2651 | } |
| 2647 | debug_assert_eq!(self.counts.len(), self.project.sources().len()); | 2652 | debug_assert_eq!(self.counts.len(), self.project.sources().len()); |
| 2648 | debug_assert_eq!(self.rates.len(), self.counts.len()); | 2653 | 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 | + } | ||
| 2649 | } | 2691 | } |
| 2650 | 2692 | ||
| 2651 | /// The rate noted for whichever source plays `path`, by | 2693 | /// The rate noted for whichever source plays `path`, by |
| @@ -3511,10 +3553,10 @@ impl PlaybackSession { | |||
| 3511 | /// picture, so the length noted for it is its playing time rounded up to | 3553 | /// picture, so the length noted for it is its playing time rounded up to |
| 3512 | /// whole frames, which is the only frame count such a source has. | 3554 | /// whole frames, which is the only frame count such a source has. |
| 3513 | /// | 3555 | /// |
| 3514 | - /// Refused in the same words as any other import when its rate or layout | 3556 | + /// Refused in the same words as any other import when its layout disagrees |
| 3515 | - /// disagrees with the timeline's -- one output device, one set of | 3557 | + /// with the timeline's track -- one output device, one layout. A silent |
| 3516 | - /// parameters -- and refused outright on a silent timeline, which has no | 3558 | + /// timeline has no track to disagree with, so a song joins it and *is* its |
| 3517 | - /// device open at all. Nothing is changed by a refusal. | 3559 | + /// sound ([`Self::arm_audio`]). Nothing is changed by a refusal. |
| 3518 | fn import_audio(&mut self, path: &Path) -> crate::Result<usize> { | 3560 | fn import_audio(&mut self, path: &Path) -> crate::Result<usize> { |
| 3519 | let first = self.first_audio()?; | 3561 | let first = self.first_audio()?; |
| 3520 | // Stream 0, and there is no other: a standalone audio file carries one | 3562 | // Stream 0, and there is no other: a standalone audio file carries one |
| @@ -4199,21 +4241,30 @@ fn matches_timeline( | |||
| 4199 | /// cannot do is be copied into an export, which is a refusal of its own, at | 4241 | /// cannot do is be copied into an export, which is a refusal of its own, at |
| 4200 | /// export time (`AudioSession::copy_multi_streams`). | 4242 | /// export time (`AudioSession::copy_multi_streams`). |
| 4201 | /// What a timeline's audio is held to: the probe of the first source that could | 4243 | /// 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 | 4244 | +/// have any track. |
| 4203 | -/// layout, so a PNG at index 0 would otherwise be *probed* as a broken mp4 and | 4245 | +/// |
| 4204 | -/// fail the open outright. | 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. | ||
| 4205 | /// | 4254 | /// |
| 4206 | -/// `Ok(None)` for a timeline whose first such source is silent, and for one of | 4255 | +/// `Ok(None)` for a timeline with no track anywhere: nothing but stills, with |
| 4207 | -/// nothing but stills. That is a silent timeline, and a file with sound is | 4256 | +/// no file at all, or every non-still source silent. That is a silent timeline, |
| 4208 | -/// still refused by [`audio_matches`] in the words it always used ("the file | 4257 | +/// and a file with sound is admitted onto it -- it *becomes* the timeline's |
| 4209 | -/// has audio, the timeline is silent") -- the device was opened on source 0's | 4258 | +/// sound ([`PlaybackSession::arm_audio`] opens the device for it), exactly the |
| 4210 | -/// track and there is none to open. This function widens which source is asked, | 4259 | +/// c581d41 rule ("a later source with real audio must be heard") at the add |
| 4211 | -/// not what the answer means. | 4260 | +/// door. |
| 4212 | fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> { | 4261 | fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> { |
| 4213 | - match audio_source_of(sources) { | 4262 | + for source in sources.iter().filter(|s| !crate::is_image(&s.path)) { |
| 4214 | - Some(first) => AudioSession::probe(&first.path, first.audio_stream), | 4263 | + if let Some(probe) = AudioSession::probe(&source.path, source.audio_stream)? { |
| 4215 | - None => Ok(None), | 4264 | + return Ok(Some(probe)); |
| 4265 | + } | ||
| 4216 | } | 4266 | } |
| 4267 | + Ok(None) | ||
| 4217 | } | 4268 | } |
| 4218 | 4269 | ||
| 4219 | /// *Which* source that is: the first one that is not a still. The single answer | 4270 | /// *Which* source that is: the first one that is not a still. The single answer |
| @@ -4268,13 +4319,21 @@ fn audio_matches_probed( | |||
| 4268 | let Some(probe) = probe else { | 4319 | let Some(probe) = probe else { |
| 4269 | return Ok(()); | 4320 | return Ok(()); |
| 4270 | }; | 4321 | }; |
| 4271 | - Err(match first { | 4322 | + // The timeline has no track anywhere (nothing but stills, or every |
| 4272 | - None => "the file has audio, the timeline is silent".to_string(), | 4323 | + // non-image source silent): there is no layout to disagree with, and the |
| 4273 | - Some(b) => format!( | 4324 | + // arriving file with sound *becomes* the timeline's sound -- |
| 4274 | - "audio {} ch does not match the timeline's {} ch", | 4325 | + // [`PlaybackSession::arm_audio`] opens the device for it, exactly the walk |
| 4275 | - probe.channels, b.channels | 4326 | + // [`PlaybackSession::open_project`] makes. Refusing here ("the file has |
| 4276 | - ), | 4327 | + // audio, the timeline is silent") pinned the timeline to its silent first |
| 4277 | - } | 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 | + ) | ||
| 4278 | .into()) | 4337 | .into()) |
| 4279 | } | 4338 | } |
| 4280 | 4339 | ||
crates/engine/src/proxy.rsmodified+2 -0
| @@ -615,6 +615,7 @@ fn started( | |||
| 615 | mod tests { | 615 | mod tests { |
| 616 | use super::*; | 616 | use super::*; |
| 617 | use crate::colorspace::ColorDescription; | 617 | use crate::colorspace::ColorDescription; |
| 618 | + use crate::demux::Rotation; | ||
| 618 | 619 | ||
| 619 | /// A cancel flag no test in this file is exercising, for the calls that | 620 | /// A cancel flag no test in this file is exercising, for the calls that |
| 620 | /// have nothing to cancel. | 621 | /// have nothing to cancel. |
| @@ -630,6 +631,7 @@ mod tests { | |||
| 630 | frame_count: 240, | 631 | frame_count: 240, |
| 631 | codec, | 632 | codec, |
| 632 | color: ColorDescription::default(), | 633 | color: ColorDescription::default(), |
| 634 | + rotation: Rotation::None, | ||
| 633 | } | 635 | } |
| 634 | } | 636 | } |
| 635 | 637 | ||
crates/engine/src/scale.rsmodified+47 -21
| @@ -459,48 +459,74 @@ pub fn rotate_i420_90s( | |||
| 459 | h: u32, | 459 | h: u32, |
| 460 | steps: u8, | 460 | steps: u8, |
| 461 | ) -> (Vec<u8>, Vec<u8>, Vec<u8>, u32, u32) { | 461 | ) -> (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) { | ||
| 462 | let steps = steps % 4; | 481 | let steps = steps % 4; |
| 463 | if steps == 0 || w == 0 || h == 0 { | 482 | 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); | ||
| 465 | } | 490 | } |
| 466 | let (cw, ch) = chroma_dims(w as usize, h as usize); | 491 | 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); | 492 | + rotate_plane_into(y, w as usize, h as usize, steps, &mut out.0); |
| 468 | - let (ru, ..) = rotate_plane(u, cw, ch, steps); | 493 | + rotate_plane_into(u, cw, ch, steps, &mut out.1); |
| 469 | - let (rv, ..) = rotate_plane(v, cw, ch, steps); | 494 | + rotate_plane_into(v, cw, ch, steps, &mut out.2); |
| 470 | - (ry, ru, rv, rw as u32, rh as u32) | 495 | + if steps == 2 { |
| 496 | + (w, h) | ||
| 497 | + } else { | ||
| 498 | + (h, w) | ||
| 499 | + } | ||
| 471 | } | 500 | } |
| 472 | 501 | ||
| 473 | -/// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise. | 502 | +/// 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) { | 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>) { | ||
| 475 | match steps { | 506 | match steps { |
| 476 | 1 => { | 507 | 1 => { |
| 477 | - let (nw, nh) = (h, w); | 508 | + out.resize(h * w, 0); |
| 478 | - let mut out = vec![0u8; nw * nh]; | 509 | + for yp in 0..w { |
| 479 | - for yp in 0..nh { | 510 | + for xp in 0..h { |
| 480 | - for xp in 0..nw { | 511 | + out[yp * h + xp] = src[(h - 1 - xp) * w + yp]; |
| 481 | - out[yp * nw + xp] = src[(h - 1 - xp) * w + yp]; | ||
| 482 | } | 512 | } |
| 483 | } | 513 | } |
| 484 | - (out, nw, nh) | ||
| 485 | } | 514 | } |
| 486 | 2 => { | 515 | 2 => { |
| 487 | - let mut out = vec![0u8; w * h]; | 516 | + out.resize(w * h, 0); |
| 488 | for yp in 0..h { | 517 | for yp in 0..h { |
| 489 | for xp in 0..w { | 518 | for xp in 0..w { |
| 490 | out[yp * w + xp] = src[(h - 1 - yp) * w + (w - 1 - xp)]; | 519 | out[yp * w + xp] = src[(h - 1 - yp) * w + (w - 1 - xp)]; |
| 491 | } | 520 | } |
| 492 | } | 521 | } |
| 493 | - (out, w, h) | ||
| 494 | } | 522 | } |
| 495 | 3 => { | 523 | 3 => { |
| 496 | - let (nw, nh) = (h, w); | 524 | + out.resize(h * w, 0); |
| 497 | - let mut out = vec![0u8; nw * nh]; | 525 | + for yp in 0..w { |
| 498 | - for yp in 0..nh { | 526 | + for xp in 0..h { |
| 499 | - for xp in 0..nw { | 527 | + out[yp * h + xp] = src[xp * w + (w - 1 - yp)]; |
| 500 | - out[yp * nw + xp] = src[xp * w + (w - 1 - yp)]; | ||
| 501 | } | 528 | } |
| 502 | } | 529 | } |
| 503 | - (out, nw, nh) | ||
| 504 | } | 530 | } |
| 505 | _ => unreachable!("steps % 4 is 1, 2 or 3 here"), | 531 | _ => unreachable!("steps % 4 is 1, 2 or 3 here"), |
| 506 | } | 532 | } |
crates/engine/tests/audio_export.rsmodified+5 -1
| @@ -22,7 +22,7 @@ use engine::export::{ExportSettings, Format}; | |||
| 22 | use engine::project::{Lane, LaneKind, Source, Speed}; | 22 | use engine::project::{Lane, LaneKind, Source, Speed}; |
| 23 | use engine::scale::FitPolicy; | 23 | use engine::scale::FitPolicy; |
| 24 | use engine::scratch::Scratch; | 24 | use engine::scratch::Scratch; |
| 25 | -use engine::{AudioSession, Clip, ExportHandle, Project}; | 25 | +use engine::{AudioSession, Clip, ExportHandle, Project, Rotation}; |
| 26 | 26 | ||
| 27 | const RATE: u32 = 44_100; | 27 | const RATE: u32 = 44_100; |
| 28 | 28 | ||
| @@ -378,6 +378,7 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() { | |||
| 378 | frame_count: 60, | 378 | frame_count: 60, |
| 379 | codec: engine::Codec::H264, | 379 | codec: engine::Codec::H264, |
| 380 | color: Default::default(), | 380 | color: Default::default(), |
| 381 | + rotation: Rotation::None, | ||
| 381 | }; | 382 | }; |
| 382 | let out = out_path("still_song", "mp4"); | 383 | let out = out_path("still_song", "mp4"); |
| 383 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); | 384 | 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() { | |||
| 704 | frame_count: 60, | 705 | frame_count: 60, |
| 705 | codec: engine::Codec::H264, | 706 | codec: engine::Codec::H264, |
| 706 | color: Default::default(), | 707 | color: Default::default(), |
| 708 | + rotation: Rotation::None, | ||
| 707 | }; | 709 | }; |
| 708 | for want in [128u32, 320] { | 710 | for want in [128u32, 320] { |
| 709 | let out = out_path(&format!("mp4_aac_{want}"), "mp4"); | 711 | let out = out_path(&format!("mp4_aac_{want}"), "mp4"); |
| @@ -1001,6 +1003,7 @@ fn a_fade_in_reaches_the_exported_audio() { | |||
| 1001 | frame_count: 90, | 1003 | frame_count: 90, |
| 1002 | codec: engine::Codec::H264, | 1004 | codec: engine::Codec::H264, |
| 1003 | color: Default::default(), | 1005 | color: Default::default(), |
| 1006 | + rotation: Rotation::None, | ||
| 1004 | }; | 1007 | }; |
| 1005 | let out = out_path("fadein", "wav"); | 1008 | let out = out_path("fadein", "wav"); |
| 1006 | let handle = engine::export::start( | 1009 | let handle = engine::export::start( |
| @@ -1097,6 +1100,7 @@ fn a_split_and_crossfaded_clip_has_no_muted_interior() { | |||
| 1097 | frame_count: 90, | 1100 | frame_count: 90, |
| 1098 | codec: engine::Codec::H264, | 1101 | codec: engine::Codec::H264, |
| 1099 | color: Default::default(), | 1102 | color: Default::default(), |
| 1103 | + rotation: Rotation::None, | ||
| 1100 | }; | 1104 | }; |
| 1101 | let out = out_path("crossfade", "wav"); | 1105 | let out = out_path("crossfade", "wav"); |
| 1102 | let handle = engine::export::start( | 1106 | let handle = engine::export::start( |
crates/engine/tests/audio_files.rsmodified+45 -1
| @@ -18,8 +18,11 @@ use engine::{AudioSession, Clip, PlaybackSession, Project}; | |||
| 18 | /// The fixtures `scripts/gen_fixtures.sh` writes: 3 s of 440 Hz left / 880 Hz | 18 | /// The fixtures `scripts/gen_fixtures.sh` writes: 3 s of 440 Hz left / 880 Hz |
| 19 | /// right at 44.1k stereo, under a 1 Hz volume pulse -- the same tone | 19 | /// right at 44.1k stereo, under a 1 Hz volume pulse -- the same tone |
| 20 | /// `test_av.mp4` carries, so a song and a video clip share one timeline. | 20 | /// `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] = [ | ||
| 22 | "test_tone.mp3", | 24 | "test_tone.mp3", |
| 25 | + "test_tone.mpg", | ||
| 23 | "test_tone.wav", | 26 | "test_tone.wav", |
| 24 | "test_tone.flac", | 27 | "test_tone.flac", |
| 25 | "test_tone.ogg", | 28 | "test_tone.ogg", |
| @@ -791,6 +794,47 @@ fn an_audio_only_file_wearing_an_mp4_extension_still_opens() { | |||
| 791 | assert!((session.timeline_duration() - 3.0).abs() < 0.1); | 794 | assert!((session.timeline_duration() - 3.0).abs() < 0.1); |
| 792 | } | 795 | } |
| 793 | 796 | ||
| 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 | + | ||
| 794 | /// The same fallback in [`PlaybackSession::open_project`]'s scaffold branch: a | 838 | /// The same fallback in [`PlaybackSession::open_project`]'s scaffold branch: a |
| 795 | /// project whose first source is one of these files reloads instead of failing | 839 | /// project whose first source is one of these files reloads instead of failing |
| 796 | /// the open a save never had trouble with the first time. | 840 | /// 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}; | |||
| 35 | use engine::project::{Lane, Source, Speed}; | 35 | use engine::project::{Lane, Source, Speed}; |
| 36 | use engine::scale::FitPolicy; | 36 | use engine::scale::FitPolicy; |
| 37 | use engine::scratch::Scratch; | 37 | use engine::scratch::Scratch; |
| 38 | -use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; | 38 | +use engine::{DecodeSession, ExportHandle, PlaybackSession, Project, Rotation}; |
| 39 | use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; | 39 | use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; |
| 40 | use ec_core::{Packet, TimeBase}; | 40 | use ec_core::{Packet, TimeBase}; |
| 41 | use ec_h264::H264Decoder; | 41 | use ec_h264::H264Decoder; |
| @@ -277,6 +277,7 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() { | |||
| 277 | frame_count: 20, | 277 | frame_count: 20, |
| 278 | codec: engine::Codec::H264, | 278 | codec: engine::Codec::H264, |
| 279 | color: Default::default(), | 279 | color: Default::default(), |
| 280 | + rotation: Rotation::None, | ||
| 280 | }; | 281 | }; |
| 281 | let out = out_path("mixed"); | 282 | let out = out_path("mixed"); |
| 282 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); | 283 | 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; | |||
| 19 | use engine::colorspace::{ColorDescription, Matrix}; | 19 | use engine::colorspace::{ColorDescription, Matrix}; |
| 20 | use engine::convert::i420_to_bgra; | 20 | use engine::convert::i420_to_bgra; |
| 21 | use engine::demux::{Codec, Demuxer}; | 21 | use engine::demux::{Codec, Demuxer}; |
| 22 | +use engine::mux::{self, Mp4Muxer, VideoParams}; | ||
| 22 | use engine::scratch::Scratch; | 23 | use engine::scratch::Scratch; |
| 23 | use engine::hw::HwSession; | 24 | use engine::hw::HwSession; |
| 24 | use engine::tonemap::{ToneMapper, Transfer}; | 25 | use engine::tonemap::{ToneMapper, Transfer}; |
| @@ -477,3 +478,111 @@ fn av1_ten_bit_hardware_matches_software_on_every_frame() { | |||
| 477 | eprintln!("frame 30 differing bytes: {diff} / {}", sw_frame_30.len()); | 478 | eprintln!("frame 30 differing bytes: {diff} / {}", sw_frame_30.len()); |
| 478 | assert_eq!(diff, 0, "hardware and software 10-bit AV1 decode disagree"); | 479 | assert_eq!(diff, 0, "hardware and software 10-bit AV1 decode disagree"); |
| 479 | } | 480 | } |
| 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 | |||
| 572 | -filter_complex "$tone" -map "[a]" -ar 44100 "${codec[@]}" \ | 572 | -filter_complex "$tone" -map "[a]" -ar 44100 "${codec[@]}" \ |
| 573 | "assets/test_tone.$fmt" | 573 | "assets/test_tone.$fmt" |
| 574 | done | 574 | 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" | ||
| 575 | # The two Opus fixtures, which cannot join the loop above: Opus decodes at 48 kHz | 595 | # The two Opus fixtures, which cannot join the loop above: Opus decodes at 48 kHz |
| 576 | # and nothing else, so these are the 48k twins of the tone rather than 44.1k ones. | 596 | # and nothing else, so these are the 48k twins of the tone rather than 44.1k ones. |
| 577 | # First the standalone `.opus`, an Ogg file `crate::is_audio` now admits. | 597 | # 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 \ | |||
| 672 | -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | 692 | -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ |
| 673 | -c:a aac -b:a 96k -f mov assets/test_qt.mov | 693 | -c:a aac -b:a 96k -f mov assets/test_qt.mov |
| 674 | 694 | ||
| 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 | + | ||
| 675 | echo "fixtures written to assets/" | 735 | echo "fixtures written to assets/" |