forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

hevc.rs289 lines, 11.9 KiBHistoryRawDownload
1//! HEVC import: the second source codec that is not H.264, and the first whose
2//! parameter sets have to be dug out of the container by hand (`mp4 0.14` reads
3//! one byte of `hvcC` and skips the rest).
4//!
5//! The container and refusal checks need nothing installed. The decode and
6//! export twins need a built `libengine_hw.so` and a VA-API driver with an HEVC
7//! decode entrypoint (`vainfo | grep HEVC`), so they are `#[ignore]`d:
8//!
9//! ```text
10//! cargo build -p engine -p engine-hw --release
11//! LD_LIBRARY_PATH=target/release \
12//! cargo test -p engine --release --test hevc -- --include-ignored --nocapture --test-threads=1
13//! ```
14//!
15//! `VE_SW` is process-wide: every test that pins a seat takes it through
16//! `support/seat.rs`, so the software and hardware tests here never see each
17//! other's pin, with or without `--test-threads=1`.
18
19use crate::seat;
20
21use std::path::PathBuf;
22use std::time::{Duration, Instant};
23
24use engine::demux::{Codec, Demuxer};
25use engine::export::ExportSettings;
26use engine::scratch::Scratch;
27use engine::{AudioSession, DecodeSession, PlaybackSession, Project};
28
29/// 1280x720@30, 2 s -- see `scripts/gen_fixtures.sh`.
30const FRAMES: u32 = 60;
31
32fn asset(name: &str) -> PathBuf {
33 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
34 .join("../../assets")
35 .join(name)
36}
37
38/// The container half: a hev1 track is found, described and named as HEVC, and
39/// its AAC track is read exactly as any other file's.
40#[test]
41fn the_demuxer_reports_an_hevc_track() {
42 let (meta, _) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4");
43 assert_eq!(meta.codec, Codec::Hevc);
44 assert_eq!((meta.width, meta.height), (1280, 720));
45 assert!((meta.frame_rate - 30.0).abs() < 0.01, "{}", meta.frame_rate);
46 assert_eq!(meta.frame_count, FRAMES);
47
48 let probe = AudioSession::probe(asset("test_hevc.mp4"), 0)
49 .expect("probe")
50 .expect("the fixture has an AAC track");
51 assert_eq!(
52 (probe.sample_rate, probe.channels),
53 (44_100, 2),
54 "audio is read the same whatever the picture is coded with"
55 );
56
57 // The invariant, stated as an assert: the older codecs still say themselves.
58 let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4");
59 assert_eq!(h264.codec, Codec::H264);
60 let (vp9, _) = Demuxer::open(&asset("test_vp9.mp4")).expect("open test_vp9.mp4");
61 assert_eq!(vp9.codec, Codec::Vp9);
62}
63
64/// The part `mp4 0.14` cannot do: every access unit is Annex-B framed, and the
65/// sync ones carry the VPS, SPS and PPS read out of `hvcC` by hand. Without
66/// those three a hardware decoder has nothing to configure itself from, so this
67/// is the check that says the box was really parsed and not merely found.
68#[test]
69fn every_sync_sample_carries_annex_b_vps_sps_and_pps() {
70 let (_, mut demuxer) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4");
71 let first = demuxer
72 .next_access_unit()
73 .expect("read")
74 .expect("a first access unit");
75
76 // NAL types out of the two-byte HEVC NAL header: bits 6..1 of the first byte.
77 let types: Vec<u8> = first
78 .windows(4)
79 .enumerate()
80 .filter(|(_, w)| *w == [0, 0, 0, 1])
81 .map(|(i, _)| (first[i + 4] >> 1) & 0x3f)
82 .collect();
83 assert!(types.starts_with(&[32, 33, 34]), "{types:?}");
84 assert!(
85 types.iter().any(|&t| (16..=21).contains(&t)),
86 "the first sample must also carry an IRAP slice: {types:?}"
87 );
88
89 let mut count = 1;
90 while let Some(au) = demuxer.next_access_unit().expect("read") {
91 assert_eq!(&au[..4], [0, 0, 0, 1], "sample {count} is not Annex-B");
92 count += 1;
93 }
94 assert_eq!(count, FRAMES, "every sample came back out");
95}
96
97/// HEVC has a software seat of its own (`ec-h265`), so with the plugin forced off
98/// the file opens on it and its first picture comes down the channel -- no refusal
99/// naming the plugin. The decode itself is checked against ffmpeg in `hevc_sw`.
100#[test]
101fn the_software_path_opens_hevc() {
102 let _seat = seat::software();
103 let opened = match DecodeSession::open(asset("test_hevc.mp4")) {
104 Ok((meta, rx)) => (meta, rx.into_iter().next().is_some()),
105 Err(e) => panic!("software HEVC must open: {e}"),
106 };
107
108 let (meta, first) = opened;
109 assert_eq!(meta.codec, Codec::Hevc);
110 assert!(first, "the software seat delivers a first picture");
111 // H.264 is untouched by all of this.
112 let h264 = DecodeSession::open(asset("test_baseline.mp4")).is_ok();
113 assert!(h264, "software H.264 decode still opens");
114}
115
116/// A timeline is *not* refused a source coded differently -- every clip opens
117/// its own decoder, so H.264 and HEVC share one timeline. What survives is the
118/// reason the codec gate existed: a file no decoder here can take is refused at
119/// the door, by the decoder's own name, rather than becoming a clip of black
120/// frames. HEVC is taken on the software seat with the plugin forced off; 4:4:4
121/// is no seat's, so it is the one refused.
122#[test]
123fn a_timeline_takes_the_other_codec_or_names_the_refusal() {
124 let _seat = seat::software();
125 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
126 let scratch = std::env::temp_dir().join(format!("hevc444-timeline-{}.mp4", std::process::id()));
127 let status = std::process::Command::new("ffmpeg")
128 .args([
129 "-v",
130 "error",
131 "-y",
132 "-f",
133 "lavfi",
134 "-i",
135 "testsrc2=size=64x64:rate=30:duration=0.1",
136 ])
137 .args([
138 "-frames:v",
139 "3",
140 "-c:v",
141 "libx265",
142 "-pix_fmt",
143 "yuv444p",
144 "-x265-params",
145 "log-level=error",
146 ])
147 .arg(&scratch)
148 .status()
149 .expect("ffmpeg runs");
150 assert!(status.success(), "ffmpeg could not make the clip");
151 // Mark it profile 5 (high throughput), which ec-h265 does not decode.
152 let mut bytes = std::fs::read(&scratch).expect("read the clip");
153 let at = bytes.windows(4).position(|w| w == b"hvcC").expect("an hvcC box");
154 bytes[at + 5] = (bytes[at + 5] & 0xe0) | 5;
155 std::fs::write(&scratch, bytes).expect("write the patched clip");
156 let refused = session
157 .import(&scratch)
158 .expect_err("profile 5 is no seat's to decode")
159 .to_string();
160 let _ = std::fs::remove_file(&scratch);
161 assert!(refused.contains("profile 5"), "{refused}");
162 assert!(
163 !refused.contains("H.264"),
164 "the timeline's own codec is no longer a reason: {refused}"
165 );
166 assert_eq!(session.sources().len(), 1, "a refusal left no row");
167
168 let joined = session.import(&asset("test_hevc.mp4"));
169 if let Err(e) = joined {
170 panic!("HEVC joins the timeline on the software seat: {e}");
171 }
172 assert_eq!(session.sources().len(), 2, "HEVC beside H.264");
173}
174
175/// The end-to-end user path: opening the file yields pictures, all of them,
176/// through the plugin.
177#[test]
178#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"]
179fn the_plugin_decodes_every_hevc_frame() {
180 let _seat = seat::hardware();
181 let start = Instant::now();
182 let (meta, frames) = DecodeSession::open(asset("test_hevc.mp4")).expect("open test_hevc.mp4");
183 assert_eq!(meta.codec, Codec::Hevc);
184 let frames: Vec<_> = frames.into_iter().collect();
185 eprintln!(
186 "test_hevc.mp4: {} frames in {:?}",
187 frames.len(),
188 start.elapsed()
189 );
190
191 assert_eq!(frames.len() as u32, FRAMES, "every sample decoded");
192 for (i, frame) in frames.iter().enumerate() {
193 assert_eq!((frame.width, frame.height), (1280, 720), "frame {i} dims");
194 assert_eq!(frame.index, i as u32, "frames arrive in display order");
195 assert_eq!(frame.bgra.len(), 1280 * 720 * 4, "frame {i} size");
196 }
197 // A picture, not a flat surface: a driver handing back an untouched buffer
198 // would satisfy every count above.
199 let first = &frames[0].bgra;
200 assert!(
201 first.as_chunks::<4>().0.iter().any(|px| px != &first[..4]),
202 "frame 0 is a single colour -- no picture was decoded"
203 );
204}
205
206/// The mixed-codec timeline, end to end: an H.264 take joins an HEVC one, both
207/// spans really decode (a decoder each, opened at the span), and the export --
208/// which re-encodes -- writes every frame of both. The refusal that used to
209/// stand here would have made this whole timeline impossible.
210#[test]
211#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"]
212fn an_h264_take_plays_and_exports_on_an_hevc_timeline() {
213 let _seat = seat::hardware();
214 let hevc = asset("test_hevc.mp4");
215 let h264 = asset("test_av.mp4");
216 let mut session = PlaybackSession::open(&hevc).expect("open test_hevc.mp4");
217 session.set_gain(0.0);
218 session.import(&h264).expect("H.264 joins an HEVC timeline");
219 let end = session.timeline_duration();
220 assert!(
221 session
222 .place_stream_at(end, &h264, 0, None)
223 .expect("a file just imported is on this timeline"),
224 "drag it onto the end"
225 );
226 assert_eq!(session.clip_spans().len(), 2, "two takes, two codecs");
227
228 // One picture out of each span, which is one decoder each: the HEVC clip
229 // through the plugin, the H.264 one through either backend.
230 for (at, what) in [(1.0, "the HEVC take"), (end + 1.0, "the H.264 take")] {
231 session.seek(at);
232 let deadline = Instant::now() + Duration::from_secs(10);
233 let frame = loop {
234 if let Some(frame) = session.try_frame() {
235 break frame;
236 }
237 assert!(Instant::now() < deadline, "no frame from {what}");
238 std::thread::sleep(Duration::from_millis(4));
239 };
240 assert_eq!(
241 (frame.width, frame.height),
242 session.resolution(),
243 "{what} came out at the project size"
244 );
245 }
246
247 // ...and the export -- the one a front-end starts, off the session itself --
248 // re-encodes both to one H.264 track.
249 let frames =
250 (session.timeline_duration() * f64::from(session.meta().frame_rate as f32)).round() as u32;
251 let out = Scratch::file("ve_export_mixed", "mp4");
252 let handle = session.export_to_with(&out, &ExportSettings::default());
253 let started = Instant::now();
254 while !handle.is_finished() {
255 assert!(started.elapsed() < Duration::from_secs(240), "export hung");
256 std::thread::sleep(Duration::from_millis(20));
257 }
258 handle.result().expect("outcome").expect("the mixed export");
259 let (written, _) = Demuxer::open(&out).expect("reopen the export");
260 assert_eq!(written.codec, Codec::H264, "exports are always H.264");
261 assert_eq!(written.frame_count, frames, "both takes were written");
262 let _ = std::fs::remove_file(&out);
263}
264
265/// Export re-encodes to H.264 whatever the source was coded with: the packet
266/// copy path is audio-only, so no HEVC byte can reach an `avc1` track.
267#[test]
268#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"]
269fn an_hevc_source_exports_as_h264() {
270 let _seat = seat::hardware();
271 let session = PlaybackSession::open(asset("test_hevc.mp4")).expect("open test_hevc.mp4");
272 let meta = *session.meta();
273 let project = Project::single(asset("test_hevc.mp4"), meta.frame_count);
274 let out = Scratch::file("ve_export_hevc", "mp4");
275
276 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
277 let started = Instant::now();
278 while !handle.is_finished() {
279 assert!(started.elapsed() < Duration::from_secs(120), "export hung");
280 std::thread::sleep(Duration::from_millis(20));
281 }
282 handle.result().expect("outcome").expect("export");
283
284 let (written, _) = Demuxer::open(&out).expect("reopen the export");
285 assert_eq!(written.codec, Codec::H264, "exports are always H.264");
286 assert_eq!(written.frame_count, FRAMES, "every timeline frame written");
287 assert_eq!((written.width, written.height), (1280, 720));
288 let _ = std::fs::remove_file(&out);
289}