forge
Explore
Log in

Don't you dare go Hollow

🐛 demux: close the block walk's unchecked add, and one mkv convention

Browse files at this commit

7a52aa1d53646c016ba7e2a3d62e977e823b3e86Ahmet Kaan GümüşParent: 9b42f9f
Four things the re-verification left behind, each either the same class as what
this lane already fixed or a promise its new text made.

The video block walk's own timestamp -- the one a copy reads -- was still
accumulated unchecked (`cluster_ts + i64::from(block.rel)`), one step before the
scale the subtitle walk widened: a crafted cluster near the top of what an `i64`
holds overflows the add before anything could refuse the product, and the block
is taken at a time that wrapped negative. Both walks now call one `block_ticks`,
and the unit test covers the add as well as both scales.

`VideoMeta::rotation`'s doc listed a spherical projection among the turns refused
at the door, but `projection_rotation` deliberately does not refuse those -- the
pose of a spherical projection is the sphere's orientation, not the picture's --
so the sentence says that instead of claiming a refusal no code makes.

The mkv door fed the *coded* height to the 720-line rule an untagged stream's
matrix is guessed from, where the mp4 door feeds the displayed one. That was
harmless until this lane made the two differ, and then an untagged turned `.mkv`
and its `.mp4` twin landed on different matrices: 1280x640 as stored, 640x1280 as
shown, so bt601 against bt709. Both doors now feed the height the picture is
*shown* at, and `test_rotation90tall.{mp4,mkv}` (generated, untagged in both
containers) pins it -- the assertion fails with the coded height, which was
verified by putting `video.height` back and watching it fail.

And the export test runs on the mkv twin too, because a turn reaches the export
through exactly one number (the source's `Rotation` in the export's rate table),
and only a both-doors test shows a door that reads its own spelling into that
number differently.

cargo check -p engine --all-targets: 0 warnings. cargo test -p engine --test
rotation: 5 passed. subtitles: 22 passed. cargo test -p engine --lib: 392 passed,
0 failed. rustfmt --edition 2024 reports the same nine pre-existing hunks on
demux.rs as base, none in the added code, and none on the test file.
crates/engine/src/demux.rsmodified+45 -13
@@ -374,10 +374,14 @@ pub struct VideoMeta {
374 /// How far the picture must be turned to be seen right, off the container's374 /// How far the picture must be turned to be seen right, off the container's
375 /// display matrix: an mp4 `tkhd` matrix, or a Matroska `Projection` roll on375 /// display matrix: an mp4 `tkhd` matrix, or a Matroska `Projection` roll on
376 /// a rectangular projection -- the same quarter turns read off either.376 /// a rectangular projection -- the same quarter turns read off either.
377- /// [`Rotation::None`] for everything whose container states no turn, and a377+ /// [`Rotation::None`] for everything whose container states no turn, and for
378- /// turn that is not a quarter turn (or a mirror, a shear, a spherical378+ /// a projection that is not rectangular: on a spherical or cubemap one those
379- /// projection) is refused at the door ([`UnsupportedRotation`]) rather than379+ /// same pose elements describe how the *sphere* is oriented, which is no turn
380- /// shown wrong.380+ /// of the picture, so the pose is deliberately not applied and the file
381+ /// paints as a flat frame -- what every player does with a 360 clip, and
382+ /// cheaper than a refusal that would cost a file that plays. A turn that is
383+ /// not a quarter turn -- a mirror, a shear, an angle in between -- is refused
384+ /// at the door ([`UnsupportedRotation`]) rather than shown wrong.
381 pub rotation: Rotation,385 pub rotation: Rotation,
382 }386 }
383 387
@@ -1326,10 +1330,15 @@ impl MkvDemuxer {
1326 // `config` is the parameter sets by now -- Annex-B for H.264 and1330 // `config` is the parameter sets by now -- Annex-B for H.264 and
1327 // HEVC, the sequence header OBU for AV1 -- which is what the1331 // HEVC, the sequence header OBU for AV1 -- which is what the
1328 // bitstream tier reads.1332 // bitstream tier reads.
1333+ // The height the picture is *shown* at, which is what the mp4 door
1334+ // feeds here and the whole reason both doors resolve their size the
1335+ // same way: the 720-line rule below is a guess about the material, and
1336+ // the material is the picture as displayed -- a device-held `.mkv` is
1337+ // 640 coded but 1280 shown, and the two sides of that rule disagree.
1329 color: ColorDescription::resolve(1338 color: ColorDescription::resolve(
1330 video.tags,1339 video.tags,
1331 bitstream_tags(video.codec, &mkv.config),1340 bitstream_tags(video.codec, &mkv.config),
1332- video.height,1341+ height,
1333 ),1342 ),
1334 // The turn off the track's `Projection` element ([`projection_rotation`]),1343 // The turn off the track's `Projection` element ([`projection_rotation`]),
1335 // which is where a Matroska muxer states what an mp4 states with its1344 // which is where a Matroska muxer states what an mp4 states with its
@@ -3223,7 +3232,7 @@ fn mkv_cluster(
3223 if block.number != number {3232 if block.number != number {
3224 continue;3233 continue;
3225 }3234 }
3226- let ts = cluster_ts + i64::from(block.rel);3235+ let ts = block_ticks(cluster_ts, block.rel)?;
3227 if block.flags & 0x06 == 0 {3236 if block.flags & 0x06 == 0 {
3228 blocks.push(Block {3237 blocks.push(Block {
3229 at: block.at,3238 at: block.at,
@@ -4497,13 +4506,12 @@ fn mkv_subtitle_blocks(
4497 read_exact_at(file, at, &mut payload)?;4506 read_exact_at(file, at, &mut payload)?;
4498 track.unpack.frame(&mut payload)?;4507 track.unpack.frame(&mut payload)?;
4499 track.cues.push(MkvCue {4508 track.cues.push(MkvCue {
4500- // The cluster's timestamp plus the block's own signed offset,4509+ // The cluster's timestamp plus the block's own signed
4501- // checked: the pair is where a corrupt file's two numbers can4510+ // offset, checked by [`block_ticks`]: the pair is where a
4502- // still overflow what an `i64` holds, one step before the4511+ // corrupt file's two numbers can still overflow what an
4503- // scale above would refuse the result.4512+ // `i64` holds, one step before the scale above would refuse
4504- start_us: us(cluster_ts4513+ // the result.
4505- .checked_add(i64::from(block.rel))4514+ start_us: us(block_ticks(cluster_ts, block.rel)?)?,
4506- .ok_or("a Matroska subtitle block at no timestamp a clock can hold")?)?,
4507 duration_us: duration.map(us).transpose()?,4515 duration_us: duration.map(us).transpose()?,
4508 payload,4516 payload,
4509 });4517 });
@@ -4513,6 +4521,20 @@ fn mkv_subtitle_blocks(
4513 Ok(())4521 Ok(())
4514 }4522 }
4515 4523
4524+/// A block's absolute timestamp in ticks: the cluster's own, plus the block's
4525+/// signed offset from it -- refused where the sum leaves what an `i64` holds.
4526+///
4527+/// Both walks need it: the video block index a copy reads and the subtitle cues.
4528+/// Both get `cluster_ts` from an EBML uint the file writes with no bound this
4529+/// reader applies, so a crafted cluster near `i64::MAX` overflows the add one
4530+/// step *before* [`ticks_scaled`] could refuse the product -- and the block would
4531+/// be taken at a time that wrapped negative.
4532+fn block_ticks(cluster_ts: i64, rel: i16) -> crate::Result<i64> {
4533+ cluster_ts
4534+ .checked_add(i64::from(rel))
4535+ .ok_or_else(|| "a Matroska block at no timestamp a clock can hold".into())
4536+}
4537+
4516 /// A tick count scaled out of the file's own clock, or the refusal a corrupt one4538 /// A tick count scaled out of the file's own clock, or the refusal a corrupt one
4517 /// earns: `ticks * TimestampScale / per_tick`, which is microseconds for the4539 /// earns: `ticks * TimestampScale / per_tick`, which is microseconds for the
4518 /// subtitle walk (`per_tick` 1_000) and nanoseconds for the block walk a copy4540 /// subtitle walk (`per_tick` 1_000) and nanoseconds for the block walk a copy
@@ -4567,6 +4589,16 @@ mod tests {
4567 "the subtitle walk's product must not wrap into a negative cue time"4589 "the subtitle walk's product must not wrap into a negative cue time"
4568 );4590 );
4569 assert!(ticks_scaled(i64::MIN, 1_000_000_000, 1_000).is_err());4591 assert!(ticks_scaled(i64::MIN, 1_000_000_000, 1_000).is_err());
4592+ // ...and the add that comes before either scale: a cluster timestamp near
4593+ // the top of what an `i64` holds plus a block's own offset still has to
4594+ // fit before any product is computed at all.
4595+ assert_eq!(block_ticks(1_000, -5).unwrap(), 995);
4596+ assert_eq!(block_ticks(0, 32_767).unwrap(), 32_767);
4597+ assert!(
4598+ block_ticks(i64::MAX, 1).is_err(),
4599+ "the add must not wrap negative"
4600+ );
4601+ assert!(block_ticks(i64::MIN, -1).is_err());
4570 }4602 }
4571 4603
4572 fn asset(name: &str) -> std::path::PathBuf {4604 fn asset(name: &str) -> std::path::PathBuf {
crates/engine/tests/rotation.rsmodified+69 -30
@@ -219,38 +219,48 @@ fn the_preview_shows_a_turned_file_upright() {
219 #[test]219 #[test]
220 fn an_export_of_a_turned_file_is_upright_and_portrait() {220 fn an_export_of_a_turned_file_is_upright_and_portrait() {
221 let _seat = pin_software();221 let _seat = pin_software();
222- let source = asset("test_rotation90.mp4");222+ // Both doors, because the turn reaches the export through exactly one number
223- let mut session = PlaybackSession::open(&source).expect("open the fixture");223+ // -- the source's `Rotation` in the export's rate table -- and an mkv states
224- session.pause();224+ // it with a `Projection` roll where an mp4 states a `tkhd` matrix: a door
225- assert_eq!(225+ // that read its own spelling into that number differently would bake a
226- [session.meta().width, session.meta().height],226+ // different turn into the pixels, and nothing but this test would show it.
227- [180, 320],227+ for file in ["test_rotation90.mp4", "test_rotation90.mkv"] {
228- "the timeline is the displayed shape, not the coded one"228+ let source = asset(file);
229- );229+ let mut session = PlaybackSession::open(&source).expect("open the fixture");
230- let out = out_path("upright");230+ session.pause();
231- let handle = session.export_to_with(&out, &ExportSettings::default());231+ assert_eq!(
232- wait(&handle, Duration::from_secs(60)).expect("export");232+ [session.meta().width, session.meta().height],
233+ [180, 320],
234+ "{file}: the timeline is the displayed shape, not the coded one"
235+ );
236+ let out = out_path(&file.replace('.', "_"));
237+ let handle = session.export_to_with(&out, &ExportSettings::default());
238+ wait(&handle, Duration::from_secs(60)).expect("export");
233 239
234- let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");240+ let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
235- assert_eq!(241+ assert_eq!(
236- [meta.width, meta.height],242+ [meta.width, meta.height],
237- [180, 320],243+ [180, 320],
238- "the written file is portrait"244+ "{file}: the written file is portrait"
239- );245+ );
240- assert_eq!(246+ assert_eq!(
241- meta.rotation,247+ meta.rotation,
242- Rotation::None,248+ Rotation::None,
243- "and states no matrix: the turn is in the pixels"249+ "{file}: and states no matrix: the turn is in the pixels"
244- );250+ );
245- assert_eq!(meta.frame_count, 30, "every timeline frame was written");251+ assert_eq!(
252+ meta.frame_count, 30,
253+ "{file}: every timeline frame was written"
254+ );
246 255
247- let (width, height, bgra) = first_frame(&out);256+ let (width, height, bgra) = first_frame(&out);
248- assert_eq!([width, height], [180, 320]);257+ assert_eq!([width, height], [180, 320]);
249- assert_eq!(258+ assert_eq!(
250- corners(width, height, &bgra),259+ corners(width, height, &bgra),
251- ["green", "yellow", "blue", "red"],260+ ["green", "yellow", "blue", "red"],
252- "the exported pixels are the ones the preview showed"261+ "{file}: the exported pixels are the ones the preview showed"
253- );262+ );
263+ }
254 }264 }
255 265
256 /// A turn that is not a quarter turn is refused by name at the door, with the266 /// A turn that is not a quarter turn is refused by name at the door, with the
@@ -283,3 +293,32 @@ fn a_turn_that_is_not_a_quarter_turn_is_refused_by_name() {
283 );293 );
284 }294 }
285 }295 }
296+
297+/// A rotated file whose *coded* height and *displayed* height sit on opposite
298+/// sides of the 720-line rule an untagged stream's matrix is guessed from
299+/// ([`engine::colorspace::ColorDescription::resolve`]): `test_rotation90tall` is
300+/// 1280x640 as stored and 640x1280 as shown, and neither container tags it (the
301+/// mkv's `Colour` element carries only chroma siting, the mp4 has no `colr`
302+/// box), so that guess is the only thing deciding bt601 against bt709.
303+///
304+/// Both doors must feed the height the picture is *shown* at -- bt709 here -- and
305+/// this is the assertion that fails if a door reads the coded height instead
306+/// (`video.height`, 640, is bt601). The two doors agreeing is the whole point of
307+/// resolving the size the same way in both.
308+#[test]
309+fn a_turned_file_guesses_its_matrix_from_the_height_it_is_shown_at() {
310+ for file in ["test_rotation90tall.mp4", "test_rotation90tall.mkv"] {
311+ let (meta, _) = engine::demux::Demuxer::open(&asset(file)).expect("open a fixture");
312+ assert_eq!(
313+ [meta.width, meta.height],
314+ [640, 1280],
315+ "{file}: the shown shape -- 1280x640 as stored, turned by the file"
316+ );
317+ assert_eq!(
318+ meta.color.matrix,
319+ engine::colorspace::Matrix::Bt709,
320+ "{file}: the 1280-line *displayed* height is HD material; the 640-line coded one \
321+ would guess bt601, so this is the coded-height bug showing"
322+ );
323+ }
324+}
scripts/gen_fixtures.shmodified+19 -0
@@ -750,5 +750,24 @@ for deg in 90 180 270 45; do
750 done750 done
751 rm -f assets/.rotation_src.mp4751 rm -f assets/.rotation_src.mp4
752 752
753+# The one fixture where the coded and the displayed height disagree about what the
754+# material is: `test_rotation90tall` is 1280x640 as stored and 640x1280 as shown,
755+# and neither container tags its colour (the mkv's `Colour` element carries only
756+# chroma siting, the mp4 has no `colr` box), so the 720-line rule an untagged
757+# stream's matrix is guessed from reads a different side of itself depending on
758+# which height a door feeds it.
759+ffmpeg -y -f lavfi -i "color=c=red:s=640x320:d=1:r=30,format=yuv420p" \
760+ -f lavfi -i "color=c=green:s=640x320:d=1:r=30,format=yuv420p" \
761+ -f lavfi -i "color=c=blue:s=640x320:d=1:r=30,format=yuv420p" \
762+ -f lavfi -i "color=c=yellow:s=640x320:d=1:r=30,format=yuv420p" \
763+ -filter_complex "[0:v][1:v]hstack[top];[2:v][3:v]hstack[bot];[top][bot]vstack[v]" \
764+ -map "[v]" -frames:v 30 -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
765+ assets/.rotation_tall_src.mp4
766+for ext in mp4 mkv; do
767+ ffmpeg -y -display_rotation 90 -i assets/.rotation_tall_src.mp4 \
768+ -c copy "assets/test_rotation90tall.$ext"
769+done
770+rm -f assets/.rotation_tall_src.mp4
771+
753 772
754 echo "fixtures written to assets/"773 echo "fixtures written to assets/"