From 8dd1c778cc316bc46bdb083da2b47be0c5c17eaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 10 Aug 2026 12:05:29 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(engine):=20hvc1-tagged=20HEV?= =?UTF-8?q?C=20files=20import=20too?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mp4 0.14 recognises only a hev1 sample entry, so an hvc1-tagged HEVC file -- what Apple and ffmpeg's mov muxer write -- read back as no video track at all. Its sample tables parse regardless of the entry the crate dropped, so the fourcc is read out of stsd by hand and the track is taken as HEVC; the parameter sets come from hvcC either way. --- crates/engine/src/demux.rs | 46 +++++++--- crates/engine/tests/hevc_hvc1.rs | 143 +++++++++++++++++++++++++++++++ scripts/gen_fixtures.sh | 15 +++- 3 files changed, 188 insertions(+), 16 deletions(-) create mode 100644 crates/engine/tests/hevc_hvc1.rs diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index aeda0a4..977b36a 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -12,7 +12,7 @@ use std::fs::File; use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path::Path; -use mp4::{MediaType, Mp4Reader, Mp4Track}; +use mp4::{MediaType, Mp4Reader, Mp4Track, TrackType}; use crate::audio::{edit_media_time, packet_at, stts_pairs}; @@ -144,7 +144,19 @@ impl Mp4Demuxer { Ok(MediaType::H264) => Some((t, Codec::H264)), Ok(MediaType::H265) => Some((t, Codec::Hevc)), Ok(MediaType::VP9) => Some((t, Codec::Vp9)), - _ => None, + // `mp4 0.14`'s `stsd` parser knows only a `hev1` sample entry + // (`stsd.rs:107`), so an `hvc1`-tagged HEVC track -- what Apple + // and ffmpeg's mov muxer write in practice -- reports no media + // type at all, and the file used to read back as having no + // video. Its sample tables (`stts`/`stsz`/`stsc`/`stss`) are + // parsed regardless of the entry the crate dropped, so only the + // fourcc has to be read here by hand. hvc1 differs from hev1 in + // that the parameter sets may not repeat in-band, which costs + // nothing: they are re-injected out of `hvcC` ahead of every + // sync sample either way. + _ => (matches!(t.track_type(), Ok(TrackType::Video)) + && sample_entry(path, t.track_id()).is_ok_and(|(kind, _)| &kind == b"hvc1")) + .then_some((t, Codec::Hevc)), }) .ok_or("no H.264, HEVC or VP9 video track in file")?; let (track, codec) = track; @@ -852,26 +864,36 @@ fn append_annex_b(mut src: &[u8], n: usize, out: &mut Vec) -> crate::Result< /// everything after it (`hev1.rs:193`), so the VPS/SPS/PPS an HEVC decoder /// cannot start without are unreachable through the crate. fn hvcc_record(path: &Path, track_id: u32) -> crate::Result> { + let (_, entry) = sample_entry(path, track_id)?; + // A VisualSampleEntry header is a fixed 78 bytes before the child boxes, + // and `hvcC` sits there for `hev1` and `hvc1` alike. + let hvcc = child(entry.get(78..).unwrap_or_default(), b"hvcC") + .ok_or("no hvcC box in the HEVC sample entry")?; + Ok(hvcc.to_vec()) +} + +/// The four-character code of `track_id`'s first `stsd` sample entry and that +/// entry's payload. Read by hand for the same reason the record above is: the +/// crate keeps no fourcc for a sample entry it does not recognise, so this is +/// the only thing that can tell an `hvc1` track from a track in a codec nothing +/// here reads. +fn sample_entry(path: &Path, track_id: u32) -> crate::Result<([u8; 4], Vec)> { let moov = read_top_level(path, b"moov")?.ok_or("no moov box in file")?; let trak = boxes(&moov) .filter(|(kind, _)| *kind == b"trak") .find(|(_, payload)| child(payload, b"tkhd").and_then(tkhd_track_id) == Some(track_id)) - .ok_or("the HEVC track has no trak box")? + .ok_or("that track has no trak box")? .1; let stsd = child(trak, b"mdia") .and_then(|b| child(b, b"minf")) .and_then(|b| child(b, b"stbl")) .and_then(|b| child(b, b"stsd")) - .ok_or("the HEVC track has no stsd box")?; - // stsd is a FullBox (4) plus entry_count (4); then sample entries, whose - // VisualSampleEntry header is a fixed 78 bytes before the child boxes. - let entry = boxes(stsd.get(8..).unwrap_or_default()) + .ok_or("that track has no stsd box")?; + // stsd is a FullBox (4) plus entry_count (4), then the sample entries. + let (kind, payload) = boxes(stsd.get(8..).unwrap_or_default()) .next() - .ok_or("empty stsd box")? - .1; - let hvcc = child(entry.get(78..).unwrap_or_default(), b"hvcC") - .ok_or("no hvcC box in the HEVC sample entry")?; - Ok(hvcc.to_vec()) + .ok_or("empty stsd box")?; + Ok((*kind, payload.to_vec())) } /// HEVCDecoderConfigurationRecord (ISO 14496-15 ยง8.3.3.1) -> the NAL length diff --git a/crates/engine/tests/hevc_hvc1.rs b/crates/engine/tests/hevc_hvc1.rs new file mode 100644 index 0000000..a278adf --- /dev/null +++ b/crates/engine/tests/hevc_hvc1.rs @@ -0,0 +1,143 @@ +//! `hvc1`-tagged HEVC: the same stream `tests/hevc.rs` reads, in the sample +//! entry Apple and ffmpeg's mov muxer actually write. `mp4 0.14` recognises only +//! `hev1`, so the crate reports no video track at all for these files and the +//! fourcc is read out of `stsd` by hand (`demux::sample_entry`). +//! +//! The container and refusal checks need nothing installed; the decode and +//! export twins need a built `libengine_hw.so` and a VA-API driver with an HEVC +//! decode entrypoint, so they are `#[ignore]`d -- same invocation as the `hevc` +//! suite: +//! +//! ```text +//! cargo build -p engine -p engine-hw --release +//! LD_LIBRARY_PATH=target/release \ +//! cargo test -p engine --release --test hevc_hvc1 -- --include-ignored --test-threads=1 +//! ``` + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use engine::demux::{Codec, Demuxer}; +use engine::export::ExportSettings; +use engine::{AudioSession, DecodeSession, PlaybackSession, Project}; + +/// 1280x720@30, 2 s -- see `scripts/gen_fixtures.sh`. +const FRAMES: u32 = 60; +const HVC1: &str = "test_hevc_hvc1.mp4"; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// The gap this suite exists for: an hvc1 file used to read back as "no H.264, +/// HEVC or VP9 video track". It is described exactly as its hev1 twin now, +/// parameter sets included -- those come out of `hvcC`, which hvc1 carries just +/// as hev1 does. +#[test] +fn the_demuxer_reports_an_hvc1_track_as_hevc() { + let (meta, mut demuxer) = Demuxer::open(&asset(HVC1)).expect("open the hvc1 fixture"); + assert_eq!(meta.codec, Codec::Hevc); + assert_eq!((meta.width, meta.height), (1280, 720)); + assert!((meta.frame_rate - 30.0).abs() < 0.01, "{}", meta.frame_rate); + assert_eq!(meta.frame_count, FRAMES); + + let probe = AudioSession::probe(asset(HVC1), 0) + .expect("probe") + .expect("the fixture has an AAC track"); + assert_eq!((probe.sample_rate, probe.channels), (44_100, 2)); + + // The sample tables the mp4 crate parsed anyway are the ones being read: the + // dropped sample entry costs nothing but the fourcc. + let first = demuxer + .next_access_unit() + .expect("read") + .expect("a first access unit"); + let types: Vec = first + .windows(4) + .enumerate() + .filter(|(_, w)| *w == [0, 0, 0, 1]) + .map(|(i, _)| (first[i + 4] >> 1) & 0x3f) + .collect(); + assert!(types.starts_with(&[32, 33, 34]), "VPS/SPS/PPS: {types:?}"); + let mut count = 1; + while let Some(au) = demuxer.next_access_unit().expect("read") { + assert_eq!(&au[..4], [0, 0, 0, 1], "sample {count} is not Annex-B"); + count += 1; + } + assert_eq!(count, FRAMES, "every sample came back out"); + + // The invariant: hev1 and the other codecs still say themselves. + let (hev1, _) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4"); + assert_eq!(hev1.codec, Codec::Hevc); + assert_eq!(hev1.frame_count, FRAMES); + let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4"); + assert_eq!(h264.codec, Codec::H264); + let (vp9, _) = Demuxer::open(&asset("test_vp9.mp4")).expect("open test_vp9.mp4"); + assert_eq!(vp9.codec, Codec::Vp9); +} + +/// Being found is not being decodable: there is no software HEVC decoder, so the +/// software path must refuse an hvc1 file by name too, out of `open` where a +/// caller can still show it. +/// +/// `VE_SW` is process-wide, hence the suite's `--test-threads=1`. +#[test] +fn the_software_path_refuses_an_hvc1_file_by_name() { + // SAFETY: the suite is documented to run with --test-threads=1. + unsafe { std::env::set_var("VE_SW", "1") }; + let refused = DecodeSession::open(asset(HVC1)).expect_err("software must not accept HEVC"); + unsafe { std::env::remove_var("VE_SW") }; + let refused = refused.to_string(); + assert!(refused.contains("HEVC"), "{refused}"); + assert!(refused.contains("plugin"), "{refused}"); +} + +/// The end-to-end user path: opening the file yields pictures, all of them, +/// through the plugin. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"] +fn the_plugin_decodes_every_hvc1_frame() { + let (meta, frames) = DecodeSession::open(asset(HVC1)).expect("open the hvc1 fixture"); + assert_eq!(meta.codec, Codec::Hevc); + let frames: Vec<_> = frames.into_iter().collect(); + assert_eq!(frames.len() as u32, FRAMES, "every sample decoded"); + for (i, frame) in frames.iter().enumerate() { + assert_eq!((frame.width, frame.height), (1280, 720), "frame {i} dims"); + assert_eq!(frame.index, i as u32, "frames arrive in display order"); + assert_eq!(frame.bgra.len(), 1280 * 720 * 4, "frame {i} size"); + } + // A picture, not a flat surface: a driver handing back an untouched buffer + // would satisfy every count above. + let first = &frames[0].bgra; + assert!( + first.chunks_exact(4).any(|px| px != &first[..4]), + "frame 0 is a single colour -- no picture was decoded" + ); +} + +/// Export re-encodes to H.264 whatever the source was tagged with. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"] +fn an_hvc1_source_exports_as_h264() { + let session = PlaybackSession::open(asset(HVC1)).expect("open the hvc1 fixture"); + let meta = *session.meta(); + let project = Project::single(asset(HVC1), meta.frame_count); + let out = std::env::temp_dir().join(format!("ve_export_hvc1_{}.mp4", std::process::id())); + let _ = std::fs::remove_file(&out); + + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let started = Instant::now(); + while !handle.is_finished() { + assert!(started.elapsed() < Duration::from_secs(120), "export hung"); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("outcome").expect("export"); + + let (written, _) = Demuxer::open(&out).expect("reopen the export"); + assert_eq!(written.codec, Codec::H264, "exports are always H.264"); + assert_eq!(written.frame_count, FRAMES, "every timeline frame written"); + assert_eq!((written.width, written.height), (1280, 720)); + let _ = std::fs::remove_file(&out); +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index b483b5d..51fab68 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -75,16 +75,23 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -map 0:v -map "[a]" -c:v libvpx-vp9 -b:v 2M -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_vp9.mp4 # HEVC fixture: the same A/V shape again, so the tests measure the codec and -# nothing else. `-tag:v hev1` is not a preference: mp4 0.14 only recognises a -# hev1 sample entry, so an hvc1-tagged file would read back as no video track at -# all. 8-bit Main profile, because the plugin's NV12 read-back cannot carry -# Main 10. +# nothing else. 8-bit Main profile, because the plugin's NV12 read-back cannot +# carry Main 10. ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -f lavfi -i "sine=frequency=440:duration=2" \ -f lavfi -i "sine=frequency=880:duration=2" \ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ -map 0:v -map "[a]" -c:v libx265 -tag:v hev1 -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_hevc.mp4 +# The same HEVC stream tagged hvc1, which is what Apple and ffmpeg's mov muxer +# write in practice: mp4 0.14 recognises only a hev1 sample entry, so this one +# is found by demux.rs reading the stsd fourcc itself (`tests/hevc_hvc1.rs`). +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ + -f lavfi -i "sine=frequency=440:duration=2" \ + -f lavfi -i "sine=frequency=880:duration=2" \ + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ + -map 0:v -map "[a]" -c:v libx265 -tag:v hvc1 -pix_fmt yuv420p \ + -c:a aac -b:a 128k assets/test_hevc_hvc1.mp4 # AV1 fixture, and the only Matroska one: `mp4 0.14` has no `av01` sample entry # at all, so AV1 is read out of an mkv (`demux::MkvDemuxer`). Same A/V shape as # the others so the tests measure the codec and nothing else -- but `-g 30` is