forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

export_language.rs262 lines, 9.2 KiBHistoryRawDownload
1//! A Matroska export states its picture's and its sound's language on their
2//! tracks: the source's own when it names one, `und` when it names none. The
3//! Matroska default for a track with no `Language` is `eng`, so leaving the
4//! element out would tell every player an undetermined source is English.
5//!
6//! The sources are made here with ffmpeg, in this test's own scratch directory
7//! (never `assets/`), and the file that comes out is read back with ffprobe --
8//! the one reader that is not this project's own. Where there is no ffmpeg on
9//! the box the test says so and passes.
10//!
11//! ```text
12//! cargo test -p engine --release --test export_language -- --nocapture
13//! ```
14
15use std::path::{Path, PathBuf};
16use std::process::Command;
17use std::sync::Once;
18use std::time::{Duration, Instant};
19
20use engine::export::{ExportSettings, Format};
21use engine::scratch::Scratch;
22use engine::subtitle::{Cue, SubtitleTrack};
23use engine::{ExportHandle, Project};
24
25/// Thirty frames of picture and a second of sound: enough to be a real export
26/// and short enough that a software encoder is not the test's cost.
27const FRAMES: u32 = 30;
28
29fn pin_software() {
30 static PIN: Once = Once::new();
31 PIN.call_once(|| {
32 engine::envcfg::set("VE_SW", "1");
33 engine::envcfg::set("VE_SW_ENC", "1");
34 });
35}
36
37fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
38 let started = Instant::now();
39 while !handle.is_finished() {
40 assert!(
41 started.elapsed() < limit,
42 "export did not finish in {limit:?}"
43 );
44 std::thread::sleep(Duration::from_millis(20));
45 }
46 handle.result().expect("a finished export has an outcome")
47}
48
49/// A one-second H.264 and AAC Matroska source. `language` is written onto both
50/// of its tracks, or onto neither when it is `None`. `None` when ffmpeg cannot
51/// make one here, which the caller takes as "no witness on this box".
52fn source(name: &str, language: Option<&str>) -> Option<PathBuf> {
53 let path = Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("{name}-{}.mkv", std::process::id()));
54 let mut cmd = Command::new("ffmpeg");
55 cmd.args(["-y", "-v", "error", "-f", "lavfi", "-i"])
56 .arg(format!("testsrc=size=320x240:rate={FRAMES}"))
57 .args(["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000"])
58 .args([
59 "-t", "1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac",
60 ]);
61 if let Some(language) = language {
62 cmd.args(["-metadata:s:v:0", &format!("language={language}")])
63 .args(["-metadata:s:a:0", &format!("language={language}")]);
64 }
65 let ok = cmd.arg(&path).status().ok()?.success();
66 ok.then_some(path)
67}
68
69/// A subtitle track of `source` in `language` (`""` where it names none), with
70/// one cue. It is picked from the project the way an embedded track is.
71fn subtitle(source: &Path, language: &str) -> SubtitleTrack {
72 SubtitleTrack {
73 path: source.to_path_buf(),
74 track: Some(3),
75 language: language.into(),
76 name: String::new(),
77 label: if language.is_empty() {
78 "und".into()
79 } else {
80 language.into()
81 },
82 bitmap: false,
83 cues: vec![Cue {
84 start_us: 100_000,
85 end_us: 900_000,
86 text: "a line".into(),
87 image: None,
88 words: Vec::new(),
89 karaoke: Vec::new(),
90 }],
91 refused: None,
92 }
93}
94
95/// The export of `source` in `format`, with `sub` picked as its one subtitle
96/// track when it is given, and the language each track states as ffprobe reads
97/// them: `(codec_type, language)` in file order.
98fn exported_languages(
99 name: &str,
100 source: &Path,
101 format: Format,
102 sub: Option<&str>,
103) -> Vec<(String, String)> {
104 pin_software();
105 let (meta, _) = engine::demux::Demuxer::open(source).expect("probe the source");
106 let ext = match format {
107 Format::Mp4 => "mp4",
108 _ => "mkv",
109 };
110 let out = Scratch::file(&format!("ve_export_language_{name}"), ext);
111 let project = match sub {
112 Some(language) => {
113 Project::single(source, FRAMES).with_subtitles(vec![subtitle(source, language)])
114 }
115 None => Project::single(source, FRAMES),
116 };
117 let handle = engine::export::start(
118 project,
119 meta,
120 &out,
121 &ExportSettings {
122 format,
123 subtitles: if sub.is_some() { vec![0] } else { Vec::new() },
124 ..Default::default()
125 },
126 None,
127 );
128 wait(&handle, Duration::from_secs(900)).expect("the export finishes");
129 let printed = Command::new("ffprobe")
130 .args([
131 "-v",
132 "error",
133 "-show_entries",
134 "stream=codec_type:stream_tags=language",
135 ])
136 .args(["-of", "csv=p=0"])
137 .arg(&out)
138 .output()
139 .expect("ffprobe runs");
140 let text = String::from_utf8_lossy(&printed.stdout).into_owned();
141 println!("ffprobe reads the export as:\n{text}");
142 let kinds: Vec<String> = text
143 .lines()
144 .filter_map(|line| {
145 let kind = line.trim_end_matches(',').split(',').next()?.to_string();
146 matches!(kind.as_str(), "video" | "audio" | "subtitle").then_some(kind)
147 })
148 .collect();
149 // ffprobe prints no language for a Matroska track that says `und` (it reads
150 // the element and drops `und`), so a Matroska file's languages are read off
151 // its `Language` elements directly, in the same track order.
152 let langs: Vec<String> = match format {
153 Format::Mp4 => text
154 .lines()
155 .filter_map(|line| {
156 let mut fields = line.trim_end_matches(',').split(',');
157 let kind = fields.next()?;
158 matches!(kind, "video" | "audio" | "subtitle")
159 .then(|| fields.next().unwrap_or_default().to_string())
160 })
161 .collect(),
162 _ => matroska_languages(&out),
163 };
164 assert_eq!(
165 kinds.len(),
166 langs.len(),
167 "one language per track: {kinds:?} {langs:?}"
168 );
169 kinds.into_iter().zip(langs).collect()
170}
171
172/// The `Language` of every track entry in the Matroska `path`, in file order, read
173/// off the header's `TrackLanguage` elements (ID `0x22B59C`) before the first
174/// cluster. Every track of an export carries one, so none is skipped.
175fn matroska_languages(path: &Path) -> Vec<String> {
176 let bytes = std::fs::read(path).expect("read the export");
177 let header = bytes
178 .windows(4)
179 .position(|w| w == [0x1F, 0x43, 0xB6, 0x75])
180 .unwrap_or(bytes.len());
181 let mut out = Vec::new();
182 let mut at = 0;
183 while at + 4 <= header {
184 if bytes[at..at + 3] != [0x22, 0xB5, 0x9C] {
185 at += 1;
186 continue;
187 }
188 // An EBML size: the count of leading zero bits names its width.
189 let first = bytes[at + 3];
190 let width = first.leading_zeros() as usize + 1;
191 let mut size = usize::from(first) & ((1 << (8 - width)) - 1);
192 for &b in &bytes[at + 4..at + 3 + width] {
193 size = (size << 8) | usize::from(b);
194 }
195 let start = at + 3 + width;
196 out.push(String::from_utf8_lossy(&bytes[start..start + size]).into_owned());
197 at = start + size;
198 }
199 out
200}
201
202fn pair(kind: &str, lang: &str) -> (String, String) {
203 (kind.to_string(), lang.to_string())
204}
205
206#[test]
207fn a_source_with_no_language_exports_und_on_both_tracks() {
208 let Some(src) = source("lang_none", None) else {
209 println!("no ffmpeg on this box: the source cannot be made here");
210 return;
211 };
212 let tracks = exported_languages("und", &src, Format::Hevc, None);
213 assert_eq!(
214 tracks,
215 vec![pair("video", "und"), pair("audio", "und")],
216 "neither track names a language, so both say und"
217 );
218}
219
220#[test]
221fn a_source_language_is_the_language_of_both_exported_tracks() {
222 let Some(src) = source("lang_ger", Some("ger")) else {
223 println!("no ffmpeg on this box: the source cannot be made here");
224 return;
225 };
226 let tracks = exported_languages("ger", &src, Format::Hevc, None);
227 assert_eq!(
228 tracks,
229 vec![pair("video", "ger"), pair("audio", "ger")],
230 "both tracks carry the source's language"
231 );
232}
233
234#[test]
235fn a_subtitle_with_no_language_is_und_in_matroska() {
236 let Some(src) = source("lang_none_sub", None) else {
237 println!("no ffmpeg on this box: the source cannot be made here");
238 return;
239 };
240 let tracks = exported_languages("sub_und", &src, Format::Hevc, Some(""));
241 assert_eq!(
242 tracks.last(),
243 Some(&pair("subtitle", "und")),
244 "a track the source names no language for is und, not the default eng"
245 );
246}
247
248#[test]
249fn a_known_subtitle_language_is_stated_in_matroska_and_mp4() {
250 let Some(src) = source("lang_none_fre", None) else {
251 println!("no ffmpeg on this box: the source cannot be made here");
252 return;
253 };
254 let mkv = exported_languages("sub_fre_mkv", &src, Format::Hevc, Some("fre"));
255 assert_eq!(
256 mkv.last(),
257 Some(&pair("subtitle", "fre")),
258 "Matroska states fre"
259 );
260 let mp4 = exported_languages("sub_fre_mp4", &src, Format::Mp4, Some("fre"));
261 assert_eq!(mp4.last(), Some(&pair("subtitle", "fre")), "mp4 states fre");
262}