forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

export_software.rs197 lines, 7.1 KiBHistoryRawDownload
1//! Export of the sources that only the software seats decode: HEVC at 8 and 10
2//! bits, VP9 and VP8. Before `ec-h265`, `ec-vp9` and `ec-vp8` joined export's
3//! software path, each of these was refused by name on a machine with no VA-API
4//! plugin; now they are decoded by the same streams playback reads.
5//!
6//! Each source is trimmed to a span that starts off any sync sample and is
7//! exported as H.264 in mp4, so the picture goes through the decoder and the
8//! encoder both. The output is then read back, and held against ffmpeg's own
9//! decode of the source from the same frame on:
10//!
11//! - the frame count and the duration are the span's own;
12//! - the first and last frames are at least 30 dB PSNR from the source.
13//!
14//! ```text
15//! cargo test -p engine --release --test export_software -- --test-threads=1
16//! ```
17//!
18//! The PSNR half needs the `ffmpeg` CLI; without it the test says so and passes,
19//! as `tests/hevc_export.rs` does.
20
21use std::path::{Path, PathBuf};
22use std::process::Command;
23use std::time::{Duration, Instant};
24
25use engine::PlaybackSession;
26use engine::demux::{Codec, Demuxer};
27use engine::export::{ExportSettings, Format};
28use engine::project::Lane;
29use engine::scratch::Scratch;
30
31/// The first and last span frames must come out at least this close to ffmpeg's
32/// decode of the source.
33const MIN_PSNR_DB: f64 = 30.0;
34
35/// The span, in source frames: it starts off the sync grid of every fixture
36/// (their keyframes are every 30 or so, and frame 5 is on none of them).
37const SPAN: (u32, u32) = (5, 25);
38
39fn asset(name: &str) -> PathBuf {
40 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
41 .join("../../assets")
42 .join(name)
43}
44
45/// Runs an export to completion, failing on the deadline rather than hanging.
46fn export(session: &PlaybackSession, out: &Path) {
47 let settings = ExportSettings {
48 format: Format::Mp4,
49 ..Default::default()
50 };
51 let handle = session.export_to_with(out, &settings);
52 let started = Instant::now();
53 while !handle.is_finished() {
54 assert!(
55 started.elapsed() < Duration::from_secs(600),
56 "the export did not finish in 600 s"
57 );
58 std::thread::sleep(Duration::from_millis(20));
59 }
60 handle.result().expect("an outcome").expect("the export");
61 assert_eq!(handle.progress(), 1.0, "finished at full progress");
62}
63
64/// The source with everything outside `[from, to)` taken off the timeline. Both
65/// cuts are made on the timeline, so the export is what is left of it.
66fn trimmed(source: &Path, (from, to): (u32, u32)) -> PlaybackSession {
67 let mut session = PlaybackSession::open(source).expect("open the source");
68 let fps = session.meta().frame_rate;
69 assert!(session.cut_at(f64::from(to) / fps), "cut the tail");
70 assert!(session.delete_clip(Lane::V1, 1), "drop the tail");
71 assert!(session.cut_at(f64::from(from) / fps), "cut the head");
72 assert!(session.delete_clip(Lane::V1, 0), "drop the head");
73 session
74}
75
76/// Every frame of `path` as ffmpeg decodes it, planar 8-bit 4:2:0 at `width` x
77/// `height`, one `Vec` per frame in display order. `None` where ffmpeg is not
78/// installed or fails.
79fn decoded_frames(path: &Path, (width, height): (u32, u32)) -> Option<Vec<Vec<u8>>> {
80 let out = Command::new("ffmpeg")
81 .args(["-v", "error", "-i"])
82 .arg(path)
83 .args([
84 "-an",
85 "-fps_mode",
86 "passthrough",
87 "-f",
88 "rawvideo",
89 "-pix_fmt",
90 "yuv420p",
91 "-",
92 ])
93 .output()
94 .ok()?;
95 if !out.status.success() {
96 eprintln!("{}", String::from_utf8_lossy(&out.stderr));
97 return None;
98 }
99 let frame = (width * height * 3 / 2) as usize;
100 Some(out.stdout.chunks_exact(frame).map(<[u8]>::to_vec).collect())
101}
102
103/// PSNR between two frames of planar 8-bit I420, over every sample.
104fn psnr(a: &[u8], b: &[u8]) -> f64 {
105 let squares: u64 = a
106 .iter()
107 .zip(b)
108 .map(|(x, y)| {
109 let d = i64::from(*x) - i64::from(*y);
110 (d * d) as u64
111 })
112 .sum();
113 if squares == 0 {
114 return f64::INFINITY;
115 }
116 let mse = squares as f64 / a.len() as f64;
117 10.0 * (255.0f64 * 255.0 / mse).log10()
118}
119
120/// Exports `[SPAN)` of the fixture at `name` and checks the file that comes out.
121/// `codec` is what the fixture must be, so the test is about the decoder it
122/// names and not a fixture that quietly became another codec.
123fn reencodes_the_span(name: &str, codec: Codec) {
124 let source = asset(name);
125 let (meta, _) = Demuxer::open(&source).expect("open the fixture");
126 assert_eq!(meta.codec, codec, "{name} is {:?}", meta.codec);
127 let (from, to) = SPAN;
128 assert!(meta.frame_count >= to, "{name} is shorter than the span");
129
130 let session = trimmed(&source, SPAN);
131 let out = Scratch::file(&format!("ve_sw_{}", name.replace('.', "_")), "mp4");
132 export(&session, &out);
133
134 // The container: the span's own count, at the source's size, and the
135 // duration that count makes at the source's rate.
136 let (written, _) = Demuxer::open(&out).expect("reopen the export");
137 assert_eq!(
138 written.frame_count,
139 to - from,
140 "{name}: the span's frames are the export's frames"
141 );
142 assert_eq!(
143 (written.width, written.height),
144 (meta.width, meta.height),
145 "{name}: the export is at the source's size"
146 );
147 let duration = f64::from(written.frame_count) / written.frame_rate;
148 let want = f64::from(to - from) / meta.frame_rate;
149 assert!(
150 (duration - want).abs() <= 1.0 / meta.frame_rate,
151 "{name}: a {duration:.4} s export of a {want:.4} s span"
152 );
153
154 // The pictures: the first and the last frame against ffmpeg's decode of the
155 // source, the same frames in the same order.
156 let size = (meta.width, meta.height);
157 let (Some(source_frames), Some(out_frames)) =
158 (decoded_frames(&source, size), decoded_frames(&out, size))
159 else {
160 eprintln!("no ffmpeg: skipping the PSNR half of {name}");
161 return;
162 };
163 let want = &source_frames[from as usize..to as usize];
164 assert_eq!(
165 out_frames.len(),
166 want.len(),
167 "{name}: ffmpeg reads back every frame of the export"
168 );
169 let first = psnr(&out_frames[0], &want[0]);
170 let last = psnr(&out_frames[out_frames.len() - 1], &want[want.len() - 1]);
171 eprintln!(
172 "{name}: {} frames, PSNR first {first:.2} dB, last {last:.2} dB",
173 want.len()
174 );
175 assert!(first >= MIN_PSNR_DB, "{name}: first frame at {first:.2} dB");
176 assert!(last >= MIN_PSNR_DB, "{name}: last frame at {last:.2} dB");
177}
178
179#[test]
180fn an_hevc_8_bit_source_is_exported_through_the_software_decoder() {
181 reencodes_the_span("test_hevcsw_8.mkv", Codec::Hevc);
182}
183
184#[test]
185fn an_hevc_10_bit_source_is_exported_through_the_software_decoder() {
186 reencodes_the_span("test_hevcsw_10.mkv", Codec::Hevc);
187}
188
189#[test]
190fn a_vp9_source_is_exported_through_the_software_decoder() {
191 reencodes_the_span("test_vp9.webm", Codec::Vp9);
192}
193
194#[test]
195fn a_vp8_source_is_exported_through_the_software_decoder() {
196 reencodes_the_span("test_vp8.webm", Codec::Vp8);
197}