forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

hevc_mkv.rs248 lines, 10.2 KiBHistoryRawDownload
1//! HEVC in Matroska, 8- and 10-bit, sound included: the shape a film off a disc
2//! arrives in, and the one the AV1 walk was written for one codec too early.
3//!
4//! Three things meet here and each is checked on its own: the demuxer reads an
5//! `hvcC` out of a `CodecPrivate` and reframes Matroska blocks to Annex-B, the
6//! plugin decodes Main 10 through a P010 surface pool, and the sound -- 5.1 AAC
7//! at 48 kHz -- is read by symphonia's mkv reader, decoded by `ec-aac` and
8//! folded to the stereo one output device carries.
9//!
10//! The container and audio checks need nothing installed. The decode twins need
11//! a built `libengine_hw.so` and a VA-API driver with an HEVC decode entrypoint
12//! (`vainfo | grep HEVC`), so they are `#[ignore]`d:
13//!
14//! ```text
15//! cargo build -p engine -p engine-hw --release
16//! LD_LIBRARY_PATH=target/release \
17//! cargo test -p engine --release --test hevc_mkv -- --include-ignored --nocapture
18//! ```
19
20use crate::hwchild;
21
22use std::path::PathBuf;
23
24use engine::demux::{Codec, Demuxer};
25use engine::hw::HwSession;
26use engine::{AudioSession, DecodeSession};
27
28/// 1280x720@30, 2 s, keyed twice -- see `scripts/gen_fixtures.sh`.
29const FRAMES: u32 = 60;
30
31fn asset(name: &str) -> PathBuf {
32 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
33 .join("../../assets")
34 .join(name)
35}
36
37/// The container half: an HEVC track in an mkv is found, named, measured, and
38/// its blocks come back as Annex-B access units with the parameter sets in
39/// front of every keyframe. Matroska indexes nothing, so all four numbers come
40/// out of the walk.
41#[test]
42fn the_demuxer_reads_hevc_out_of_a_matroska_file() {
43 for (name, depth) in [("test_hevc.mkv", 8), ("test_hevc10.mkv", 10)] {
44 let (meta, mut demuxer) = Demuxer::open(&asset(name)).unwrap_or_else(|e| panic!("{name}: {e}"));
45 assert_eq!(meta.codec, Codec::Hevc, "{name}");
46 assert_eq!((meta.width, meta.height), (1280, 720), "{name}");
47 assert!((meta.frame_rate - 30.0).abs() < 1e-6, "{name}: {}", meta.frame_rate);
48 assert_eq!(meta.frame_count, FRAMES, "{name}");
49 // What picks the P010 surface pool over the NV12 one.
50 assert_eq!(demuxer.bit_depth(), depth, "{name}");
51
52 let first = demuxer
53 .next_access_unit()
54 .expect("read")
55 .expect("a first access unit");
56 // A Matroska block is length-prefixed NALs, exactly as an mp4 sample is,
57 // and what a decoder has to be handed is Annex-B with the VPS (NAL type
58 // 32) out of the `CodecPrivate` in front.
59 assert_eq!(&first[..4], [0, 0, 0, 1], "{name}: Annex-B start code");
60 assert_eq!(
61 (first[4] >> 1) & 0x3f,
62 32,
63 "{name}: the keyframe leads with the VPS off the CodecPrivate"
64 );
65 let mut count = 1;
66 while demuxer.next_access_unit().expect("read").is_some() {
67 count += 1;
68 }
69 assert_eq!(count, FRAMES, "{name}: every block came back out");
70
71 // The fixture is keyed twice (`-g 30`), and a seek may only ever land on
72 // a keyframe. *Which* block that is, is the encoder's business: an HEVC
73 // stream with B-frames is stored in decode order and the second IDR
74 // lands a couple of blocks before the display frame it shows, so the
75 // check is on the rule rather than on the number.
76 let second = demuxer.seek_to_sync_at_or_before(FRAMES - 1);
77 assert!(
78 second > 0 && second < i64::from(FRAMES),
79 "{name}: a second keyframe, at {second}"
80 );
81 assert_eq!(
82 demuxer.seek_to_sync_at_or_before(second as u32),
83 second,
84 "{name}: landing on a keyframe stays on it"
85 );
86 assert_eq!(
87 demuxer.seek_to_sync_at_or_before(second as u32 - 1),
88 0,
89 "{name}: one block earlier there is only the first keyframe"
90 );
91 }
92
93 // The invariant: the AV1 mkv and the HEVC mp4 still read as themselves.
94 let (av1, _) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv");
95 assert_eq!(av1.codec, Codec::Av1);
96 let (mp4, hevc) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4");
97 assert_eq!(mp4.codec, Codec::Hevc);
98 assert_eq!(hevc.bit_depth(), 8);
99}
100
101/// A Matroska file's sound is read now, and a 5.1 track joins the timeline as
102/// the stereo source the fold makes of it.
103#[test]
104fn matroska_audio_is_read_and_five_one_arrives_as_stereo() {
105 let stereo = AudioSession::probe(asset("test_hevc.mkv"), 0)
106 .expect("probe")
107 .expect("the fixture has an AAC track");
108 assert_eq!((stereo.sample_rate, stereo.channels), (44_100, 2));
109
110 let wide = AudioSession::probe(asset("test_hevc10.mkv"), 0)
111 .expect("probe")
112 .expect("the fixture has a 5.1 AAC track");
113 assert_eq!(
114 (wide.sample_rate, wide.channels),
115 (48_000, 2),
116 "5.1 is folded to the layout one output device carries"
117 );
118
119 // The picker's row, which is what a user chooses a stream from.
120 let streams = AudioSession::probe_streams(asset("test_hevc10.mkv")).expect("streams");
121 assert_eq!(streams.len(), 1);
122 assert_eq!(streams[0].codec, "aac");
123 assert_eq!(streams[0].channels, 2);
124 assert!(streams[0].decodable);
125
126 // ...and nothing is left to explain away: a file whose sound plays is not
127 // one the "cannot be decoded" notice may name.
128 assert!(
129 AudioSession::open(asset("test_hevc10.mkv"))
130 .expect("open")
131 .is_some()
132 );
133}
134
135/// The fold, measured on the tones the fixture puts one per channel: every
136/// channel but the LFE reaches the stereo pair, the surrounds and the centre at
137/// -3 dB of the fronts, and nothing crosses sides.
138///
139/// Which tone is which *position* is the encoder's business (ffmpeg's AAC
140/// encoder does not keep the order they were written in), so the check is on
141/// the shape: two full-weight tones, one per side; one tone in both at -3 dB;
142/// two more at -3 dB, one per side; and the 60 Hz LFE nowhere.
143#[test]
144fn the_five_one_fold_keeps_every_channel_but_the_lfe() {
145 let (meta, rx) = AudioSession::open(asset("test_hevc10.mkv"))
146 .expect("open")
147 .expect("the fixture has sound");
148 assert_eq!((meta.sample_rate, meta.channels), (48_000, 2));
149 let mut left = Vec::new();
150 let mut right = Vec::new();
151 for chunk in rx {
152 for pair in chunk.samples.as_chunks::<2>().0 {
153 left.push(pair[0]);
154 right.push(pair[1]);
155 }
156 }
157 // Past the encoder priming, and a whole number of cycles of every tone.
158 let (left, right) = (&left[9_600..57_600], &right[9_600..57_600]);
159 let tones = [60.0, 220.0, 440.0, 880.0, 1320.0, 1760.0];
160 let l: Vec<f32> = tones.iter().map(|f| tone(left, *f)).collect();
161 let r: Vec<f32> = tones.iter().map(|f| tone(right, *f)).collect();
162
163 // The source tones are at 0.125 (lavfi's `sine`), and the fold divides by
164 // the sum of its own coefficients so a full-scale source cannot clip.
165 let norm = 1.0 / (1.0 + 2.0 * std::f32::consts::FRAC_1_SQRT_2);
166 let full = 0.125 * norm;
167 let quiet = full * std::f32::consts::FRAC_1_SQRT_2;
168 let near = |got: f32, want: f32| (got - want).abs() < 0.01;
169
170 assert!(
171 near(l[0], 0.0) && near(r[0], 0.0),
172 "the LFE is dropped: {} {}",
173 l[0],
174 r[0]
175 );
176 let both = tones
177 .iter()
178 .enumerate()
179 .filter(|(i, _)| near(l[*i], quiet) && near(r[*i], quiet))
180 .count();
181 assert_eq!(both, 1, "exactly the centre reaches both sides: {l:?} {r:?}");
182 let fronts = tones
183 .iter()
184 .enumerate()
185 .filter(|(i, _)| near(l[*i], full) != near(r[*i], full))
186 .count();
187 assert_eq!(fronts, 2, "one front channel per side: {l:?} {r:?}");
188 let surrounds = tones
189 .iter()
190 .enumerate()
191 .filter(|(i, _)| {
192 (near(l[*i], quiet) && near(r[*i], 0.0)) || (near(r[*i], quiet) && near(l[*i], 0.0))
193 })
194 .count();
195 assert_eq!(surrounds, 2, "one surround per side, at -3 dB: {l:?} {r:?}");
196}
197
198/// Amplitude of one frequency in `x` (Goertzel), which is what "this channel
199/// reached that output" is measured with.
200fn tone(x: &[f32], freq: f32) -> f32 {
201 let w = 2.0 * std::f32::consts::PI * freq / 48_000.0;
202 let (cos, sin) = (w.cos(), w.sin());
203 let (mut s1, mut s2) = (0.0f32, 0.0f32);
204 for &v in x {
205 let s0 = v + 2.0 * cos * s1 - s2;
206 s2 = s1;
207 s1 = s0;
208 }
209 let (re, im) = (s1 - s2 * cos, s2 * sin);
210 2.0 * (re * re + im * im).sqrt() / x.len() as f32
211}
212
213/// The picture, on the hardware that decodes it: every frame of both files, at
214/// the size the container declared. Main 10 goes through the P010 pool and is
215/// read back to the same 8-bit I420 the 8-bit path hands out, so the only thing
216/// this can tell them apart by is that neither errors.
217#[test]
218#[ignore = "needs libengine_hw.so and a VA-API driver with an HEVC entrypoint"]
219fn the_plugin_decodes_hevc_in_matroska_at_both_depths() {
220 hwchild::require();
221 for name in ["test_hevc.mkv", "test_hevc10.mkv"] {
222 let mut hw = HwSession::open(&asset(name)).expect("no hardware decode plugin available");
223 let mut count = 0;
224 let mut lit = 0;
225 while let Some((y, _, _, w, h)) = hw.next_frame().expect("hardware decode") {
226 assert_eq!((w, h), (1280, 720), "{name} frame {count}");
227 // Not a black frame: the fixture is a colour pattern, and a P010
228 // surface read back through the NV12 path would come out as noise
229 // or as nothing at all.
230 if y.iter().any(|&s| s > 32) {
231 lit += 1;
232 }
233 count += 1;
234 }
235 assert_eq!(count, FRAMES as usize, "{name}");
236 assert_eq!(lit, count, "{name}: every frame carries picture");
237 }
238}
239
240/// ...and the same file through the session a clip actually plays from, which
241/// is where a codec that only the plugin can decode is refused if it cannot.
242#[test]
243#[ignore = "needs libengine_hw.so and a VA-API driver with an HEVC entrypoint"]
244fn a_ten_bit_matroska_clip_decodes_through_the_ordinary_session() {
245 let (meta, frames) = DecodeSession::open(asset("test_hevc10.mkv")).expect("open");
246 assert_eq!(meta.codec, Codec::Hevc);
247 assert_eq!(frames.iter().count(), FRAMES as usize);
248}