forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-a4a9c4b2cd501908b'

Browse files at this commit

752a5670c9fae900b2a9cfeadfbccc0b44a7ff6eAhmet Kaan GümüşParent: e807bb98dd1c77
crates/engine/src/demux.rsmodified+34 -12
@@ -12,7 +12,7 @@ use std::fs::File;
1212 use std::io::{BufReader, Read, Seek, SeekFrom};
1313 use std::path::Path;
1414
15-use mp4::{MediaType, Mp4Reader, Mp4Track};
15+use mp4::{MediaType, Mp4Reader, Mp4Track, TrackType};
1616
1717 use crate::audio::{edit_media_time, packet_at, stts_pairs};
1818
@@ -144,7 +144,19 @@ impl Mp4Demuxer {
144144 Ok(MediaType::H264) => Some((t, Codec::H264)),
145145 Ok(MediaType::H265) => Some((t, Codec::Hevc)),
146146 Ok(MediaType::VP9) => Some((t, Codec::Vp9)),
147- _ => None,
147+ // `mp4 0.14`'s `stsd` parser knows only a `hev1` sample entry
148+ // (`stsd.rs:107`), so an `hvc1`-tagged HEVC track -- what Apple
149+ // and ffmpeg's mov muxer write in practice -- reports no media
150+ // type at all, and the file used to read back as having no
151+ // video. Its sample tables (`stts`/`stsz`/`stsc`/`stss`) are
152+ // parsed regardless of the entry the crate dropped, so only the
153+ // fourcc has to be read here by hand. hvc1 differs from hev1 in
154+ // that the parameter sets may not repeat in-band, which costs
155+ // nothing: they are re-injected out of `hvcC` ahead of every
156+ // sync sample either way.
157+ _ => (matches!(t.track_type(), Ok(TrackType::Video))
158+ && sample_entry(path, t.track_id()).is_ok_and(|(kind, _)| &kind == b"hvc1"))
159+ .then_some((t, Codec::Hevc)),
148160 })
149161 .ok_or("no H.264, HEVC or VP9 video track in file")?;
150162 let (track, codec) = track;
@@ -852,26 +864,36 @@ fn append_annex_b(mut src: &[u8], n: usize, out: &mut Vec<u8>) -> crate::Result<
852864 /// everything after it (`hev1.rs:193`), so the VPS/SPS/PPS an HEVC decoder
853865 /// cannot start without are unreachable through the crate.
854866 fn hvcc_record(path: &Path, track_id: u32) -> crate::Result<Vec<u8>> {
867+ let (_, entry) = sample_entry(path, track_id)?;
868+ // A VisualSampleEntry header is a fixed 78 bytes before the child boxes,
869+ // and `hvcC` sits there for `hev1` and `hvc1` alike.
870+ let hvcc = child(entry.get(78..).unwrap_or_default(), b"hvcC")
871+ .ok_or("no hvcC box in the HEVC sample entry")?;
872+ Ok(hvcc.to_vec())
873+}
874+
875+/// The four-character code of `track_id`'s first `stsd` sample entry and that
876+/// entry's payload. Read by hand for the same reason the record above is: the
877+/// crate keeps no fourcc for a sample entry it does not recognise, so this is
878+/// the only thing that can tell an `hvc1` track from a track in a codec nothing
879+/// here reads.
880+fn sample_entry(path: &Path, track_id: u32) -> crate::Result<([u8; 4], Vec<u8>)> {
855881 let moov = read_top_level(path, b"moov")?.ok_or("no moov box in file")?;
856882 let trak = boxes(&moov)
857883 .filter(|(kind, _)| *kind == b"trak")
858884 .find(|(_, payload)| child(payload, b"tkhd").and_then(tkhd_track_id) == Some(track_id))
859- .ok_or("the HEVC track has no trak box")?
885+ .ok_or("that track has no trak box")?
860886 .1;
861887 let stsd = child(trak, b"mdia")
862888 .and_then(|b| child(b, b"minf"))
863889 .and_then(|b| child(b, b"stbl"))
864890 .and_then(|b| child(b, b"stsd"))
865- .ok_or("the HEVC track has no stsd box")?;
866- // stsd is a FullBox (4) plus entry_count (4); then sample entries, whose
867- // VisualSampleEntry header is a fixed 78 bytes before the child boxes.
868- let entry = boxes(stsd.get(8..).unwrap_or_default())
891+ .ok_or("that track has no stsd box")?;
892+ // stsd is a FullBox (4) plus entry_count (4), then the sample entries.
893+ let (kind, payload) = boxes(stsd.get(8..).unwrap_or_default())
869894 .next()
870- .ok_or("empty stsd box")?
871- .1;
872- let hvcc = child(entry.get(78..).unwrap_or_default(), b"hvcC")
873- .ok_or("no hvcC box in the HEVC sample entry")?;
874- Ok(hvcc.to_vec())
895+ .ok_or("empty stsd box")?;
896+ Ok((*kind, payload.to_vec()))
875897 }
876898
877899 /// HEVCDecoderConfigurationRecord (ISO 14496-15 §8.3.3.1) -> the NAL length
crates/engine/tests/hevc_hvc1.rsadded+143 -0
@@ -0,0 +1,143 @@
1+//! `hvc1`-tagged HEVC: the same stream `tests/hevc.rs` reads, in the sample
2+//! entry Apple and ffmpeg's mov muxer actually write. `mp4 0.14` recognises only
3+//! `hev1`, so the crate reports no video track at all for these files and the
4+//! fourcc is read out of `stsd` by hand (`demux::sample_entry`).
5+//!
6+//! The container and refusal checks need nothing installed; the decode and
7+//! export twins need a built `libengine_hw.so` and a VA-API driver with an HEVC
8+//! decode entrypoint, so they are `#[ignore]`d -- same invocation as the `hevc`
9+//! suite:
10+//!
11+//! ```text
12+//! cargo build -p engine -p engine-hw --release
13+//! LD_LIBRARY_PATH=target/release \
14+//! cargo test -p engine --release --test hevc_hvc1 -- --include-ignored --test-threads=1
15+//! ```
16+
17+use std::path::PathBuf;
18+use std::time::{Duration, Instant};
19+
20+use engine::demux::{Codec, Demuxer};
21+use engine::export::ExportSettings;
22+use engine::{AudioSession, DecodeSession, PlaybackSession, Project};
23+
24+/// 1280x720@30, 2 s -- see `scripts/gen_fixtures.sh`.
25+const FRAMES: u32 = 60;
26+const HVC1: &str = "test_hevc_hvc1.mp4";
27+
28+fn asset(name: &str) -> PathBuf {
29+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
30+ .join("../../assets")
31+ .join(name)
32+}
33+
34+/// The gap this suite exists for: an hvc1 file used to read back as "no H.264,
35+/// HEVC or VP9 video track". It is described exactly as its hev1 twin now,
36+/// parameter sets included -- those come out of `hvcC`, which hvc1 carries just
37+/// as hev1 does.
38+#[test]
39+fn the_demuxer_reports_an_hvc1_track_as_hevc() {
40+ let (meta, mut demuxer) = Demuxer::open(&asset(HVC1)).expect("open the hvc1 fixture");
41+ assert_eq!(meta.codec, Codec::Hevc);
42+ assert_eq!((meta.width, meta.height), (1280, 720));
43+ assert!((meta.frame_rate - 30.0).abs() < 0.01, "{}", meta.frame_rate);
44+ assert_eq!(meta.frame_count, FRAMES);
45+
46+ let probe = AudioSession::probe(asset(HVC1), 0)
47+ .expect("probe")
48+ .expect("the fixture has an AAC track");
49+ assert_eq!((probe.sample_rate, probe.channels), (44_100, 2));
50+
51+ // The sample tables the mp4 crate parsed anyway are the ones being read: the
52+ // dropped sample entry costs nothing but the fourcc.
53+ let first = demuxer
54+ .next_access_unit()
55+ .expect("read")
56+ .expect("a first access unit");
57+ let types: Vec<u8> = first
58+ .windows(4)
59+ .enumerate()
60+ .filter(|(_, w)| *w == [0, 0, 0, 1])
61+ .map(|(i, _)| (first[i + 4] >> 1) & 0x3f)
62+ .collect();
63+ assert!(types.starts_with(&[32, 33, 34]), "VPS/SPS/PPS: {types:?}");
64+ let mut count = 1;
65+ while let Some(au) = demuxer.next_access_unit().expect("read") {
66+ assert_eq!(&au[..4], [0, 0, 0, 1], "sample {count} is not Annex-B");
67+ count += 1;
68+ }
69+ assert_eq!(count, FRAMES, "every sample came back out");
70+
71+ // The invariant: hev1 and the other codecs still say themselves.
72+ let (hev1, _) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4");
73+ assert_eq!(hev1.codec, Codec::Hevc);
74+ assert_eq!(hev1.frame_count, FRAMES);
75+ let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4");
76+ assert_eq!(h264.codec, Codec::H264);
77+ let (vp9, _) = Demuxer::open(&asset("test_vp9.mp4")).expect("open test_vp9.mp4");
78+ assert_eq!(vp9.codec, Codec::Vp9);
79+}
80+
81+/// Being found is not being decodable: there is no software HEVC decoder, so the
82+/// software path must refuse an hvc1 file by name too, out of `open` where a
83+/// caller can still show it.
84+///
85+/// `VE_SW` is process-wide, hence the suite's `--test-threads=1`.
86+#[test]
87+fn the_software_path_refuses_an_hvc1_file_by_name() {
88+ // SAFETY: the suite is documented to run with --test-threads=1.
89+ unsafe { std::env::set_var("VE_SW", "1") };
90+ let refused = DecodeSession::open(asset(HVC1)).expect_err("software must not accept HEVC");
91+ unsafe { std::env::remove_var("VE_SW") };
92+ let refused = refused.to_string();
93+ assert!(refused.contains("HEVC"), "{refused}");
94+ assert!(refused.contains("plugin"), "{refused}");
95+}
96+
97+/// The end-to-end user path: opening the file yields pictures, all of them,
98+/// through the plugin.
99+#[test]
100+#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"]
101+fn the_plugin_decodes_every_hvc1_frame() {
102+ let (meta, frames) = DecodeSession::open(asset(HVC1)).expect("open the hvc1 fixture");
103+ assert_eq!(meta.codec, Codec::Hevc);
104+ let frames: Vec<_> = frames.into_iter().collect();
105+ assert_eq!(frames.len() as u32, FRAMES, "every sample decoded");
106+ for (i, frame) in frames.iter().enumerate() {
107+ assert_eq!((frame.width, frame.height), (1280, 720), "frame {i} dims");
108+ assert_eq!(frame.index, i as u32, "frames arrive in display order");
109+ assert_eq!(frame.bgra.len(), 1280 * 720 * 4, "frame {i} size");
110+ }
111+ // A picture, not a flat surface: a driver handing back an untouched buffer
112+ // would satisfy every count above.
113+ let first = &frames[0].bgra;
114+ assert!(
115+ first.chunks_exact(4).any(|px| px != &first[..4]),
116+ "frame 0 is a single colour -- no picture was decoded"
117+ );
118+}
119+
120+/// Export re-encodes to H.264 whatever the source was tagged with.
121+#[test]
122+#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"]
123+fn an_hvc1_source_exports_as_h264() {
124+ let session = PlaybackSession::open(asset(HVC1)).expect("open the hvc1 fixture");
125+ let meta = *session.meta();
126+ let project = Project::single(asset(HVC1), meta.frame_count);
127+ let out = std::env::temp_dir().join(format!("ve_export_hvc1_{}.mp4", std::process::id()));
128+ let _ = std::fs::remove_file(&out);
129+
130+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
131+ let started = Instant::now();
132+ while !handle.is_finished() {
133+ assert!(started.elapsed() < Duration::from_secs(120), "export hung");
134+ std::thread::sleep(Duration::from_millis(20));
135+ }
136+ handle.result().expect("outcome").expect("export");
137+
138+ let (written, _) = Demuxer::open(&out).expect("reopen the export");
139+ assert_eq!(written.codec, Codec::H264, "exports are always H.264");
140+ assert_eq!(written.frame_count, FRAMES, "every timeline frame written");
141+ assert_eq!((written.width, written.height), (1280, 720));
142+ let _ = std::fs::remove_file(&out);
143+}
scripts/gen_fixtures.shmodified+11 -4
@@ -75,16 +75,23 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
7575 -map 0:v -map "[a]" -c:v libvpx-vp9 -b:v 2M -pix_fmt yuv420p \
7676 -c:a aac -b:a 128k assets/test_vp9.mp4
7777 # HEVC fixture: the same A/V shape again, so the tests measure the codec and
78-# nothing else. `-tag:v hev1` is not a preference: mp4 0.14 only recognises a
79-# hev1 sample entry, so an hvc1-tagged file would read back as no video track at
80-# all. 8-bit Main profile, because the plugin's NV12 read-back cannot carry
81-# Main 10.
78+# nothing else. 8-bit Main profile, because the plugin's NV12 read-back cannot
79+# carry Main 10.
8280 ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
8381 -f lavfi -i "sine=frequency=440:duration=2" \
8482 -f lavfi -i "sine=frequency=880:duration=2" \
8583 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
8684 -map 0:v -map "[a]" -c:v libx265 -tag:v hev1 -pix_fmt yuv420p \
8785 -c:a aac -b:a 128k assets/test_hevc.mp4
86+# The same HEVC stream tagged hvc1, which is what Apple and ffmpeg's mov muxer
87+# write in practice: mp4 0.14 recognises only a hev1 sample entry, so this one
88+# is found by demux.rs reading the stsd fourcc itself (`tests/hevc_hvc1.rs`).
89+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
90+ -f lavfi -i "sine=frequency=440:duration=2" \
91+ -f lavfi -i "sine=frequency=880:duration=2" \
92+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
93+ -map 0:v -map "[a]" -c:v libx265 -tag:v hvc1 -pix_fmt yuv420p \
94+ -c:a aac -b:a 128k assets/test_hevc_hvc1.mp4
8895 # AV1 fixture, and the only Matroska one: `mp4 0.14` has no `av01` sample entry
8996 # at all, so AV1 is read out of an mkv (`demux::MkvDemuxer`). Same A/V shape as
9097 # the others so the tests measure the codec and nothing else -- but `-g 30` is