forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

export.rs4072 lines, 205.0 KiBHistoryRawDownload
1//! Export tools: start, poll, and cancel exports.
2use std::path::{Path, PathBuf};
3use std::time::Instant;
4
5use engine::demux::Demuxer;
6use engine::export::{caption_title_clash, chroma_reduction_words, fit_picture_clips, planned_seats, planned_tone, EncoderSeat, NO_HW_SEAT, ExportSettings, FitOutcome, Format, HdrOutput, HdrTransfer, GifSettings, HevcSpeed, ProResProfile, AAC_MAX_KBPS, AUDIO_KBPS};
7use engine::project::LaneKind;
8use engine::scale::FitPolicy;
9use engine::captionanim::{CaptionAnim, CaptionStyle, MAX_WORDS_PER_LINE};
10use engine::text::{Outline, Place, TextStyle};
11use engine::PlaybackSession;
12use serde_json::{json, Map, Value};
13
14use crate::parse::{frame, session_end, session_fps, tc};
15use crate::server::{arg_str, opt_bool, opt_str, opt_u64, tri, FileLevels, Job, Pending, Reply, Server, Tool};
16
17const FORMAT_NAMES: &str = "mp4, av1, av1-mp4, hevc, hevc-mp4, webm, wav, flac, mp3, ogg, m4a, opus, prores, png_sequence, still, gif";
18/// How many finished exports an unasked status poll lists (the newest ones).
19const FINISHED_LISTED: usize = 5;
20
21/// The argument key of burned-in captions, shared with `frame` and `contact_sheet`.
22pub(crate) const BURN_KEY: &str = "burn_captions";
23const BURN_KEYS: [&str; 12] = ["track", "size", "outline", "boxed", "place", "family", "animation", "highlight", "box", "uppercase", "words_per_line", "native"];
24const BURN_DOC: &str = "Draw one subtitle track's text into the picture, so it shows in every \
25player and in WebM. Text cues only: a bitmap track (PGS) is refused. An .ass track is drawn as its script says unless native is false. Compare `subtitles`, which \
26adds soft tracks a player can switch off; WebM carries no soft subtitles, so burn there. \
27One track only: two speakers' captions burn together when they share a track, which auto_captions makes by merging a second speaker into the same caption lane (auto_captions {target:\"A2\", lane:\"S1\"}).";
28
29pub fn tools() -> Vec<Tool> {
30 vec![
31 Tool {
32 name: "export_start",
33 description: "Start exporting the open project to a file. Returns job:<n> at once; poll it with export_status. Refuses an existing file unless overwrite is true. Two ways to carry captions: `subtitles` adds soft tracks a player can switch off (WebM carries none); `burn_captions` draws one track's text into the picture, so every player and WebM shows it. With `burn_captions` and no `subtitles`, the file has no soft subtitle track at all, so the captions are not shown twice; name `subtitles` as well to add soft tracks beside the burned ones. The export keeps running while you do other things; if the client only closes this server's input it finishes before the server exits, but if the server is stopped by a signal (as most clients do when they quit) it is cancelled and its partial file removed — poll export_status until it finishes.",
34 schema: start_schema,
35 run: export_start,
36 },
37 Tool {
38 name: "export_presets",
39 description: "List the export presets export_start { preset: \"<id>\" } takes: id, label and the settings each sets (format, bitrate_kbps, audio_kbps, size, bit_depth, qp, keyframe_s, faststart, loudness). Explicit export_start arguments override the preset.",
40 schema: presets_schema,
41 run: export_presets,
42 },
43 Tool {
44 name: "export_captions",
45 description: "Write the timeline's captions (every cue on the subtitle lanes, in start order) to a text file: SRT or WebVTT. Picture cues and empty ones are left out. Writes nothing and says so when there are no captions. Refuses an existing file unless overwrite is true. chapters: true instead returns the chapter markers as the YouTube description listing (the text File > Copy chapters copies), with its warnings, and writes no file.",
46 schema: captions_schema,
47 run: export_captions,
48 },
49 Tool {
50 name: "export_status",
51 description: "Progress, elapsed time, ETA, encoder and outcome of one export (job), or with no job of every unfinished export and the last five finished ones (an older finished export is named by job:<n>). A stage before the encode (Measuring shake, while a stabilised clip is measured) is named with its own percent. Reports the file's size when done, its average bitrate for an HEVC or AV1 file, or the error when it failed.",
52 schema: status_schema,
53 run: export_status,
54 },
55 Tool {
56 name: "export_cancel",
57 description: "Cancel a running export. The worker stops at its next checkpoint and deletes the partial file. all: true cancels every unfinished export at once, the queued ones (which never start) and the running one; the same as the export queue's Cancel all.",
58 schema: cancel_schema,
59 run: export_cancel,
60 },
61 Tool {
62 name: "export_queue",
63 description: "Pause or start the export queue (export_start {queue:true}). pause: the running export finishes, and the queued ones stay queued until start. start: lifts the pause and starts the next queued export now, if nothing is running. status: whether the queue is paused, the running export and the queued ones in order. A direct export (no queue) is not held by a pause.",
64 schema: queue_schema,
65 run: export_queue,
66 },
67 ]
68}
69
70fn queue_schema() -> Value {
71 json!({
72 "type": "object",
73 "properties": {
74 "action": {
75 "type": "string",
76 "enum": ["pause", "start", "status"],
77 "description": "pause: queued exports stay queued after the running one ends. start: lifts the pause and starts the next queued export now if nothing is running. status (the default): whether the queue is paused, the running export and the queued ones in order."
78 }
79 },
80 "additionalProperties": false
81 })
82}
83
84/// The running job's index: one with a worker that has not finished (a waiting job has none).
85fn running_index(srv: &Server) -> Option<usize> {
86 srv.jobs.iter().position(|j| j.handle.is_some() && job_running(j))
87}
88
89/// `export_queue`: pauses the queue, lifts the pause, or reports the queue's state.
90fn export_queue(srv: &mut Server, args: &Value) -> Reply {
91 let action = opt_str(args, "action").unwrap_or("status");
92 let queued_list = |srv: &Server| -> String {
93 let waiting: Vec<String> = srv.jobs.iter().enumerate().filter(|(_, j)| j.waiting()).map(|(i, _)| format!("job:{}", i + 1)).collect();
94 if waiting.is_empty() { "none".to_string() } else { waiting.join(", ") }
95 };
96 match action {
97 "pause" => {
98 let was = srv.queue_paused;
99 srv.queue_paused = true;
100 let head = if was { "queue already paused" } else { "queue paused" };
101 let running = running_index(srv).map_or("no export is running".to_string(), |i| format!("job:{} keeps running and finishes", i + 1));
102 Reply::ok(format!(
103 "{head}: {running}; queued exports wait ({}) until export_queue {{action:\"start\"}}",
104 queued_list(srv)
105 ))
106 .with(json!({ "action": "pause", "paused": true, "queued": queued_list(srv) }))
107 }
108 "start" => {
109 let was = srv.queue_paused;
110 srv.queue_paused = false;
111 let next = srv.jobs.iter().position(|j| j.waiting());
112 advance(srv);
113 let started = next.is_some_and(|i| !srv.jobs[i].waiting());
114 let mut text = if was { "queue started".to_string() } else { "queue was not paused".to_string() };
115 match (started, running_index(srv), next) {
116 (true, _, Some(i)) => text.push_str(&format!(": job:{} started now", i + 1)),
117 (false, Some(r), Some(i)) => text.push_str(&format!(": job:{} is still running, and job:{} starts when it finishes", r + 1, i + 1)),
118 _ => text.push_str(": nothing is waiting"),
119 }
120 Reply::ok(text).with(json!({ "action": "start", "paused": false, "running": running_index(srv).map(|i| i + 1), "queued": queued_list(srv) }))
121 }
122 "status" => {
123 let running = running_index(srv).map(|i| {
124 let n = i + 1;
125 let pct = f64::from(srv.jobs[i].progress()).clamp(0.0, 1.0) * 100.0;
126 format!("job:{n} running {pct:.0}% → {}", srv.jobs[i].out.display())
127 });
128 let queued: Vec<String> = srv
129 .jobs
130 .iter()
131 .enumerate()
132 .filter(|(_, j)| j.waiting())
133 .enumerate()
134 .map(|(k, (i, j))| format!("{}. job:{} waiting → {}", k + 1, i + 1, j.out.display()))
135 .collect();
136 let state = if srv.queue_paused { "paused" } else { "running" };
137 let mut lines = vec![format!("queue {state}; {} queued", queued.len())];
138 lines.push(format!("running: {}", running.unwrap_or_else(|| "none".to_string())));
139 if queued.is_empty() {
140 lines.push("queued: none".to_string());
141 } else {
142 lines.push("queued, in order:".to_string());
143 lines.extend(queued);
144 }
145 if srv.queue_paused {
146 lines.push("The queue is paused: queued exports do not start until export_queue {action:\"start\"}.".to_string());
147 }
148 Reply::ok(lines.join("\n")).with(json!({ "action": "status", "paused": srv.queue_paused, "queued": queued_list(srv), "running": running_index(srv).map(|i| i + 1) }))
149 }
150 other => Reply::err(format!("export_queue action `{other}` is not one of pause, start, status")),
151 }
152}
153
154fn presets_schema() -> Value {
155 json!({ "type": "object", "properties": {} })
156}
157
158/// The JSON of one preset row, the settings in `export_start`'s own argument names.
159fn preset_json(p: &engine::export_presets::Preset) -> Value {
160 json!({
161 "id": p.id,
162 "label": p.label,
163 "description": p.description,
164 "category": format!("{:?}", p.target.category).to_lowercase(),
165 "output": if p.target.output == engine::export_presets::Output::Video { "video" } else { "audio" },
166 "format": format_name(p.format),
167 "bitrate_kbps": p.bitrate.map(|b| b / 1000),
168 "audio_kbps": p.audio_kbps,
169 "size": p.target.size.map(|(w, h)| format!("{w}x{h}")),
170 "bit_depth": p.video_bit_depth,
171 "qp": p.qp,
172 "keyframe_s": p.keyframe_s,
173 "faststart": p.faststart,
174 "prores_profile": p.prores_profile.map(prores_name),
175 "hdr": hdr_name(p.hdr),
176 "loudness": p.loudness.map(|l| json!({ "lufs": l.lufs, "true_peak_dbtp": l.true_peak_dbtp })),
177 })
178}
179
180fn export_presets(_srv: &mut Server, _args: &Value) -> Reply {
181 let rows: Vec<Value> = engine::export_presets::presets().iter().map(preset_json).collect();
182 let mut text = String::from("export presets (export_start { preset: id }; explicit arguments override):");
183 for p in engine::export_presets::presets() {
184 text.push_str(&format!("\n {} -- {}", p.id, p.description));
185 }
186 Reply::ok(text).with(json!({ "presets": rows }))
187}
188
189fn captions_schema() -> Value {
190 json!({
191 "type": "object",
192 "properties": {
193 "chapters": {"type": "boolean", "description": "true returns the timeline's chapter markers as the YouTube description listing (00:00 Intro, one line each) that File > Copy chapters copies. Writes no file; format and path are not used. The reply carries the text and the lines as JSON, plus any warnings the YouTube rules raise."},
194 "format": {"type": "string", "enum": ["srt", "vtt"], "description": "srt = SubRip (00:00:01,000); vtt = WebVTT with its WEBVTT header (00:00:01.000)."},
195 "path": {"type": "string", "description": "Path of the file to write. A leading ~/ is expanded; its folder must exist and its extension must match the format. Omitted: <first source's name> edit.<format> in the Videos folder (Untitled when there are no sources)."},
196 "overwrite": {"type": "boolean", "description": "Replace the file when it already exists. Default false."}
197 },
198 "additionalProperties": false
199 })
200}
201
202/// The chapter list as YouTube description text: what File > Copy chapters copies
203/// (`engine::playback::PlaybackSession::youtube_chapters`), returned rather than copied.
204fn chapter_list(srv: &Server) -> Reply {
205 let s = tri!(srv.session_ref());
206 let (text, warnings) = s.youtube_chapters();
207 if text.is_empty() {
208 return Reply::err("no chapters on the timeline: add a chapter marker first");
209 }
210 let lines: Vec<String> = text.lines().map(str::to_string).collect();
211 let mut shown = text.clone();
212 for w in &warnings {
213 shown.push_str(&format!("\nwarning: {w}"));
214 }
215 Reply::ok(shown).with(json!({"chapters": lines, "count": lines.len(), "text": text, "warnings": warnings}))
216}
217
218/// File > Export captions: the timeline's caption cues as SRT or WebVTT, written at `path`.
219/// With `chapters: true` it returns the YouTube chapter listing instead, writing nothing.
220fn export_captions(srv: &mut Server, args: &Value) -> Reply {
221 if opt_bool(args, "chapters").unwrap_or(false) {
222 return chapter_list(srv);
223 }
224 let format = match opt_str(args, "format") {
225 Some(f @ ("srt" | "vtt")) => f,
226 _ => return Reply::err("format is srt or vtt".to_string()),
227 };
228 let s = tri!(srv.session_ref());
229 let cues = s.caption_cues();
230 if cues.is_empty() {
231 return Reply::err("no captions on the timeline: add a caption on a subtitle lane first".to_string());
232 }
233 let path = match opt_str(args, "path") {
234 Some(raw) => crate::tools::project::expand_home(raw),
235 None => {
236 let stem = s.sources().first().and_then(|src| src.path.file_stem()).map_or_else(|| "Untitled".to_string(), |n| format!("{} edit", n.to_string_lossy()));
237 engine::export::default_export_folder(Path::new("")).join(format!("{stem}.{format}"))
238 }
239 };
240 if path.extension().and_then(|e| e.to_str()).is_none_or(|e| !e.eq_ignore_ascii_case(format)) {
241 return Reply::err(format!("path {} must end in .{format} for {format}", path.display()));
242 }
243 if !path.parent().is_some_and(|d| d.as_os_str().is_empty() || d.is_dir()) {
244 return Reply::err(format!("the folder of {} does not exist", path.display()));
245 }
246 if path.exists() && !opt_bool(args, "overwrite").unwrap_or(false) {
247 return Reply::err(format!("{} already exists: pass overwrite true to replace it, or choose another path", path.display()));
248 }
249 let text = if format == "srt" { engine::subtitle::write_srt(&cues) } else { engine::subtitle::write_vtt(&cues) };
250 if let Err(e) = std::fs::write(&path, text) {
251 return Reply::err(format!("could not write {}: {e}", path.display()));
252 }
253 Reply::ok(format!("wrote {} caption{} to {} ({format})", cues.len(), if cues.len() == 1 { "" } else { "s" }, path.display()))
254 .with(json!({"path": path.display().to_string(), "format": format, "cues": cues.len()}))
255}
256
257fn start_schema() -> Value {
258 json!({
259 "type": "object",
260 "properties": {
261 "sequence": super::sequence::prop(),
262 "preset": {
263 "type": "string",
264 "enum": engine::export_presets::presets().iter().map(|p| p.id).collect::<Vec<_>>(),
265 "description": "An export preset id (list them with export_presets): fills format, bitrate_kbps, audio_kbps, size, bit_depth, qp, keyframe_s, faststart and, for sound, a loudness target. Anything else you pass overrides the preset's value; `out`'s extension must match the preset's format."
266 },
267 "loudness": {
268 "type": "number",
269 "minimum": -30,
270 "maximum": -5,
271 "description": "Integrated loudness target in LUFS, any number from -30 to -5 (-14 is the usual streaming level, -16 the podcast preset). The whole mix takes one gain so it lands on this, and the true peak is held at the preset's ceiling or -1 dBTP; the gain is cut back, never a limiter. Omitted: the preset's target, or none."
272 },
273 "out": {
274 "type": "string",
275 "description": "Path of the file to write. A leading ~/ is expanded. Its folder must exist. Its extension names the format unless `format` is given: .mp4 is mp4, .mkv is av1, .webm, .wav, .flac, .mp3, .ogg, .m4a, .opus."
276 },
277 "format": {
278 "type": "string",
279 "enum": ["mp4", "av1", "av1-mp4", "hevc", "hevc-mp4", "webm", "wav", "flac", "mp3", "ogg", "m4a", "opus", "prores", "png_sequence", "still", "gif"],
280 "description": "png_sequence = a folder of PNG pictures, one per frame (name_00001.png ...), at the project size, no sound: `out` is the folder; still = one PNG, the frame at the start of `range` (the poster frame); gif = animated GIF of the range (see gif_width, gif_fps, gif_loop; at most 30 s and 720 px wide, no sound). mp4 = H.264 in mp4; av1 = AV1 in Matroska (.mkv); av1-mp4 = AV1 in mp4; hevc = HEVC in Matroska, I+P GOPs (.mkv); hevc-mp4 = HEVC in mp4; webm; wav/flac = audio only, lossless; mp3/ogg = audio only; m4a = AAC in an mp4 box, audio only; opus = Opus in Ogg, audio only, mixed at 48 kHz; prores = Apple ProRes in a QuickTime .mov with PCM sound (see prores_profile, audio_bit_depth). An mp4 of a timeline with no video clips is the sound alone (AAC in an mp4), so it is not refused. Default: inferred from the out extension."
281 },
282 "range": {
283 "type": "object",
284 "description": "Part of the timeline to write, from `from` up to but not including `to`. Times take the usual forms: 450f, 15.0s, 15 (seconds), 00:00:15:00, end. Omitted: the whole timeline.",
285 "properties": {
286 "from": { "description": "Start of the range." },
287 "to": { "description": "End of the range (exclusive); must come after `from` and not pass the timeline end." }
288 },
289 "required": ["from", "to"]
290 },
291 "gif_width": {
292 "type": "integer",
293 "minimum": 1,
294 "description": "GIF only: width in pixels; the height follows the project's aspect. Default 480."
295 },
296 "gif_fps": {
297 "type": "integer",
298 "minimum": 1,
299 "maximum": 60,
300 "description": "GIF only: frames a second, 1 to 60. Default 15."
301 },
302 "gif_loop": {
303 "type": "boolean",
304 "description": "GIF only: loop forever (true, the default) or play once (false)."
305 },
306 "size": {
307 "type": "string",
308 "description": "Picture size of this export only, e.g. 1280x720, or a height with p: 720p, 1080p, 2160p (16:9 at that height). Both sides even, at most 7680. Omitted: the project's resolution. The project is not changed: the export draws at this size and its clips refit by their fit mode, as they do when the project's resolution changes."
309 },
310 "fit": {
311 "type": "string",
312 "enum": ["keep", "fit", "fill"],
313 "description": "How every picture clip meets the export's canvas, for this export only (the project's clips keep their own fit). fill crops each picture to the whole canvas, so 16:9 footage fills a vertical 1080x1920; fit keeps the whole picture with bars; keep (the default) uses each clip's own fit. Captions and titles keep their place on the canvas."
314 },
315 "bitrate_kbps": {
316 "type": "integer",
317 "minimum": 1,
318 "description": "Video bitrate in kbps. Omitted: chosen from the picture size and frame rate. Ignored by audio-only formats. Not with qp."
319 },
320 "qp": {
321 "type": "integer",
322 "minimum": 0,
323 "maximum": 51,
324 "description": "Constant quantiser for the picture instead of a bitrate, 0 (best, largest) to 51. The hardware seat codes at it for H.264, HEVC and AV1 (AV1 scaled to its 0..255), and the software HEVC encoder too; the software H.264 and AV1 encoders refuse it. Video formats only (mp4, av1, av1-mp4, hevc, hevc-mp4, webm). Not with bitrate_kbps."
325 },
326 "keyframe_s": {
327 "type": "number",
328 "minimum": 0.1,
329 "maximum": 10,
330 "description": "Seconds between key frames of the picture (H.264, HEVC, AV1), instead of the encoder's own two. Rounded to whole pictures at the frame rate. Not with intra_only or a sound-only export. Software HEVC caps it at 256 pictures."
331 },
332 "faststart": {
333 "type": "boolean",
334 "description": "Lay an mp4 out so a player can start before the file is fully read (moov before mdat). Only mp4, hevc-mp4, av1-mp4 and m4a; refused for other formats. Default false, or the preset's."
335 },
336 "audio_kbps": {
337 "type": "integer",
338 "enum": [128, 192, 256, 320, 384],
339 "description": "Sound bitrate in kbps: 128, 192, 256 or 320, and 384 for AAC only (mp4, av1, av1-mp4, hevc, hevc-mp4, m4a). Refused where the sound's rate is not a choice (wav, flac, a timeline with no sound, and similar)."
340 },
341 "seat": {
342 "type": "string",
343 "enum": ["auto", "hardware", "software"],
344 "description": "Which encoder writes the picture. auto: hardware where this machine has one for the codec, software elsewhere. hardware: the GPU or nothing, no silent fallback. software: always the CPU."
345 },
346 "intra_only": {
347 "type": "boolean",
348 "description": "hevc and hevc-mp4: true codes every picture as an IDR (intra only, large files, every frame a cut point). false, the default, codes I+P GOPs (an IDR a second, P pictures between). h264 mp4 uses it the same way."
349 },
350 "subtitles": {
351 "anyOf": [
352 { "type": "boolean", "description": "true: every subtitle track as a soft track. false: none." },
353 { "type": "array", "items": { "type": "integer", "minimum": 0 }, "description": "Indices of the project's subtitle tracks to include as soft tracks, in the order given." }
354 ],
355 "description": "Soft subtitle tracks, opt-in: omitted, false or [] writes none, true writes every track, a list writes those indices. For captions every player shows, use burn_captions instead."
356 },
357 "burn_captions": burn_schema(),
358 "chapters": {
359 "type": ["boolean", "string"],
360 "description": "Write the project's chapter markers into the file. Default true. Written to mp4, av1-mp4, hevc-mp4, m4a, av1 (.mkv), hevc (.mkv), webm and opus (as CHAPTERxxx comments); the other formats say they are not written. false leaves them out. \"markers\" writes the comment markers (marker_add) as the chapter list instead of the chapters."
361 },
362 "bit_depth": {
363 "type": "integer",
364 "enum": [8, 10],
365 "description": "Sample depth of the picture: 10 writes a 10-bit AV1 or HEVC (Main 10) file (format av1, av1-mp4, hevc or hevc-mp4 only; H.264 and the rest refuse it). Omitted: 10-bit when the source is 10-bit, 8-bit otherwise. 8 forces 8-bit. Compositions (grades, titles, captions, transitions) are still composed at 8 bits and shifted up."
366 },
367 "prores_profile": {
368 "type": "string",
369 "enum": ["proxy", "lt", "standard", "hq", "4444", "4444xq"],
370 "description": "format prores only: the ProRes profile, which is the quality (the bitrate is the profile's own). proxy, lt, standard (422) and hq (the default, 422 HQ) are 4:2:2; 4444 and 4444xq are 4:4:4. ProRes is always 10-bit."
371 },
372 "hevc_speed": {
373 "type": "string",
374 "enum": ["default", "fast", "faster"],
375 "description": "hevc and hevc-mp4 only: the software encoder's speed preset. default (the default) is the full search; fast is about 1.2-1.6x quicker for 0-3% more bits at the same quality; faster is about 1.5-2x quicker for up to 27% more."
376 },
377 "hdr": {
378 "type": "string",
379 "enum": ["off", "pq", "hlg"],
380 "description": "hevc and hevc-mp4 only: tag the file HDR. pq is HDR10 (SMPTE ST 2084), hlg is ARIB STD-B67; both BT.2020, 10-bit (bit_depth 8 is refused), and HDR sources are not tone-mapped. off (the default) is the SDR file it always was."
381 },
382 "audio_bit_depth": {
383 "type": "integer",
384 "enum": [16, 24],
385 "description": "format prores only: bits per sample of the PCM sound. 24 is the default."
386 },
387 "overwrite": {
388 "type": "boolean",
389 "description": "Replace the file at `out` if it already exists. Default false."
390 },
391 "queue": {
392 "type": "boolean",
393 "description": "true: line this export up behind the others. It keeps its own copy of the timeline as it is now (later edits do not change it) and starts when every earlier export has finished, one encode at a time; export_status shows it as waiting. Default false: the export starts at once, beside any others running."
394 }
395 },
396 "required": ["out"]
397 })
398}
399
400fn status_schema() -> Value {
401 json!({
402 "type": "object",
403 "properties": {
404 "job": {
405 "type": "integer",
406 "minimum": 1,
407 "description": "The job number from export_start (job:<n>). Omitted: every export so far."
408 },
409 "out": {
410 "type": "string",
411 "description": "The file an export writes (the out path given to export_start). Use it for an export this session did not start: the reply says whether the file is there, its size and when it was written. A job this session started for that file is reported as its job."
412 }
413 }
414 })
415}
416
417fn cancel_schema() -> Value {
418 json!({
419 "type": "object",
420 "properties": {
421 "job": {
422 "type": "integer",
423 "minimum": 1,
424 "description": "The job number from export_start (job:<n>). A waiting (queued) job is removed from the queue and never starts; a running one stops and its partial file is deleted."
425 },
426 "all": {
427 "type": "boolean",
428 "description": "true cancels every unfinished export: waiting ones are removed, the running one stops and its partial file is deleted. Give either job or all."
429 }
430 }
431 })
432}
433
434// ---- formats and paths ----------------------------------------------------
435
436fn format_from_name(s: &str) -> Option<Format> {
437 Some(match s.trim().to_ascii_lowercase().as_str() {
438 "mp4" => Format::Mp4,
439 "av1" => Format::Av1,
440 "av1-mp4" => Format::Av1Mp4,
441 "hevc" => Format::Hevc,
442 "hevc-mp4" => Format::HevcMp4,
443 "webm" => Format::Webm,
444 "wav" => Format::Wav,
445 "flac" => Format::Flac,
446 "mp3" => Format::Mp3,
447 "ogg" => Format::Ogg,
448 "opus" => Format::Opus,
449 "m4a" => Format::M4a,
450 "prores" => Format::ProRes,
451 "png_sequence" => Format::PngSequence,
452 "still" => Format::Still,
453 "gif" => Format::Gif,
454 _ => return None,
455 })
456}
457
458pub(crate) fn parse_prores_profile(args: &Value, format: Format) -> Result<Option<ProResProfile>, String> {
459 let Some(name) = opt_str(args, "prores_profile") else { return Ok(None) };
460 let profile = match name.trim().to_ascii_lowercase().as_str() {
461 "proxy" => ProResProfile::Proxy,
462 "lt" => ProResProfile::Lt,
463 "standard" => ProResProfile::Standard,
464 "hq" => ProResProfile::Hq,
465 "4444" => ProResProfile::P4444,
466 "4444xq" => ProResProfile::P4444Xq,
467 other => return Err(format!("prores_profile `{other}` is not proxy, lt, standard, hq, 4444 or 4444xq")),
468 };
469 match format.is_prores() {
470 true => Ok(Some(profile)),
471 false => Err(format!("prores_profile is for format prores, not {}", format_name(format))),
472 }
473}
474
475pub(crate) fn parse_hevc_speed(args: &Value, format: Format) -> Result<Option<HevcSpeed>, String> {
476 let Some(name) = opt_str(args, "hevc_speed") else { return Ok(None) };
477 let speed = match name.trim().to_ascii_lowercase().as_str() {
478 "default" => HevcSpeed::Default,
479 "fast" => HevcSpeed::Fast,
480 "faster" => HevcSpeed::Faster,
481 other => return Err(format!("hevc_speed `{other}` is not default, fast or faster")),
482 };
483 match format.is_hevc() {
484 true => Ok(Some(speed)),
485 false => Err(format!("hevc_speed is for format hevc or hevc-mp4, not {}", format_name(format))),
486 }
487}
488
489pub(crate) fn parse_hdr(args: &Value, format: Format) -> Result<Option<HdrTransfer>, String> {
490 let Some(name) = opt_str(args, "hdr") else { return Ok(None) };
491 let transfer = match name.trim().to_ascii_lowercase().as_str() {
492 "off" => HdrTransfer::Sdr,
493 "pq" => HdrTransfer::Pq,
494 "hlg" => HdrTransfer::Hlg,
495 other => return Err(format!("hdr `{other}` is not off, pq or hlg")),
496 };
497 match transfer == HdrTransfer::Sdr || format.is_hevc() {
498 true => Ok(Some(transfer)),
499 false => Err(format!("hdr is for format hevc or hevc-mp4, not {}", format_name(format))),
500 }
501}
502
503pub(crate) fn parse_sound_bits(args: &Value, format: Format) -> Result<Option<u8>, String> {
504 let bits = match opt_u64(args, "audio_bit_depth") {
505 None => return Ok(None),
506 Some(b @ (16 | 24)) => b as u8,
507 Some(b) => return Err(format!("audio_bit_depth {b} is not 16 or 24")),
508 };
509 match format.is_prores() {
510 true => Ok(Some(bits)),
511 false => Err(format!("audio_bit_depth is for format prores, not {}", format_name(format))),
512 }
513}
514
515fn prores_name(p: ProResProfile) -> &'static str {
516 match p {
517 ProResProfile::Proxy => "proxy",
518 ProResProfile::Lt => "lt",
519 ProResProfile::Standard => "standard",
520 ProResProfile::Hq => "hq",
521 ProResProfile::P4444 => "4444",
522 ProResProfile::P4444Xq => "4444xq",
523 }
524}
525
526fn hdr_name(t: HdrTransfer) -> &'static str {
527 match t {
528 HdrTransfer::Sdr => "off",
529 HdrTransfer::Pq => "pq",
530 HdrTransfer::Hlg => "hlg",
531 }
532}
533
534fn format_name(f: Format) -> &'static str {
535 match f {
536 Format::Mp4 => "mp4",
537 Format::Av1 => "av1",
538 Format::Av1Mp4 => "av1-mp4",
539 Format::Hevc => "hevc",
540 Format::HevcMp4 => "hevc-mp4",
541 Format::Webm => "webm",
542 Format::Wav => "wav",
543 Format::Flac => "flac",
544 Format::Mp3 => "mp3",
545 Format::Ogg => "ogg",
546 Format::Opus => "opus",
547 Format::M4a => "m4a",
548 Format::ProRes => "prores",
549 Format::PngSequence => "png_sequence",
550 Format::Still => "still",
551 Format::Gif => "gif",
552 }
553}
554
555/// The format a bare extension implies when no format was named. `.mkv` is
556/// AV1, the default video format; HEVC needs its name.
557fn infer_format(ext: &str) -> Option<Format> {
558 Some(match ext {
559 "mp4" => Format::Mp4,
560 "mkv" => Format::Av1,
561 "webm" => Format::Webm,
562 "wav" => Format::Wav,
563 "flac" => Format::Flac,
564 "mp3" => Format::Mp3,
565 "ogg" => Format::Ogg,
566 "opus" => Format::Opus,
567 "m4a" => Format::M4a,
568 "mov" => Format::ProRes,
569 "png" => Format::Still,
570 "gif" => Format::Gif,
571 _ => return None,
572 })
573}
574
575fn expand_home(raw: &str) -> PathBuf {
576 if let Some(rest) = raw.strip_prefix("~/")
577 && let Some(home) = std::env::var_os("HOME")
578 {
579 return PathBuf::from(home).join(rest);
580 }
581 PathBuf::from(raw)
582}
583
584/// The path to write and the format it is written in. Refuses a named format
585/// whose extension the path does not carry.
586fn resolve_out(raw: &str, format: Option<&str>) -> Result<(PathBuf, Format), String> {
587 let path = expand_home(raw);
588 let ext = path
589 .extension()
590 .and_then(|e| e.to_str())
591 .map(|e| e.to_ascii_lowercase());
592 let named = match format {
593 Some(name) => Some(format_from_name(name).ok_or_else(|| {
594 format!("unknown format `{name}`: the formats are {FORMAT_NAMES}")
595 })?),
596 None => None,
597 };
598 match (named, ext) {
599 // A numbered run is written into a folder: the name is the folder's, with no extension added.
600 (Some(Format::PngSequence), _) => Ok((path, Format::PngSequence)),
601 (Some(f), None) => Ok((path.with_extension(f.ext()), f)),
602 (Some(f), Some(e)) if e == f.ext() => Ok((path, f)),
603 (Some(f), Some(e)) => Err(format!(
604 "`{}` ends in .{e}, but {} is written as .{}: name the file .{} or pick a format that writes .{e}",
605 path.display(),
606 format_name(f),
607 f.ext(),
608 f.ext()
609 )),
610 (None, Some(e)) => match infer_format(&e) {
611 Some(f) => Ok((path, f)),
612 None => Err(format!(
613 "can't tell the format from `.{e}`: name the file .mp4, .mkv, .webm, .wav, .flac, .mp3, .ogg, .m4a, .opus or .mov, or pass `format` ({FORMAT_NAMES})"
614 )),
615 },
616 (None, None) => Err(format!(
617 "`{}` has no extension, so the format is unknown: name the file with one (.mp4, .mkv, .webm, .wav, .flac, .mp3, .ogg, .m4a, .opus, .mov) or pass `format`",
618 path.display()
619 )),
620 }
621}
622
623/// Whether `path` may be written: not an existing file unless `overwrite`,
624/// not a folder, and in a folder that exists and takes a new file.
625fn check_out(path: &Path, overwrite: bool) -> Result<(), String> {
626 if path.is_dir() {
627 return Err(format!("`{}` is a folder: give the file a name inside it", path.display()));
628 }
629 if path.exists() && !overwrite {
630 return Err(format!(
631 "`{}` already exists: pass overwrite: true to replace it, or choose another name",
632 path.display()
633 ));
634 }
635 match path.parent() {
636 Some(p) if !p.as_os_str().is_empty() && !p.is_dir() => Err(format!(
637 "the folder `{}` does not exist: create it first or choose an existing folder",
638 p.display()
639 )),
640 Some(p) if !p.as_os_str().is_empty() => writable(p),
641 _ => writable(Path::new(".")),
642 }
643}
644
645/// Whether a picture run may be written into `folder`: not a file, and not a folder that already
646/// holds files unless `overwrite`, in a parent folder that exists. The run creates the folder.
647fn check_folder(folder: &Path, overwrite: bool) -> Result<(), String> {
648 if folder.exists() && !folder.is_dir() {
649 return Err(format!("`{}` is a file: name a folder for the picture run", folder.display()));
650 }
651 let occupied = folder.is_dir() && folder.read_dir().is_ok_and(|mut d| d.next().is_some());
652 if occupied && !overwrite {
653 return Err(format!(
654 "`{}` already holds files: pass overwrite: true to write the run into it, or choose another name",
655 folder.display()
656 ));
657 }
658 match folder.parent() {
659 Some(p) if !p.as_os_str().is_empty() && !p.is_dir() => Err(format!(
660 "the folder `{}` does not exist: create it first or choose an existing folder",
661 p.display()
662 )),
663 Some(p) if !p.as_os_str().is_empty() => writable(p),
664 _ => writable(Path::new(".")),
665 }
666}
667
668/// Proves a folder takes a new file by making one there and removing it: the mode
669/// bits lie about a read-only mount, a full disk or a `/proc` folder, so the answer
670/// is the attempt itself. Refused up front rather than after the job has run.
671fn writable(dir: &Path) -> Result<(), String> {
672 let probe = dir.join(format!(".edith-write-probe-{}", std::process::id()));
673 match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
674 Ok(_) => {
675 let _ = std::fs::remove_file(&probe);
676 Ok(())
677 }
678 Err(e) => Err(format!(
679 "cannot create files in `{}`: {e}. choose a file in a folder you can write to",
680 dir.display()
681 )),
682 }
683}
684
685/// The engine's rule for the sound a job reads, checked before the job starts so a
686/// mismatch is refused in these words rather than failing inside it. The timeline
687/// takes its width from its first audio source; a mono source joins a wider timeline
688/// (it is widened), a stereo pair folds down onto a mono timeline (it is averaged), and
689/// a silent one joins any. Anything else is refused here.
690fn channel_mismatch(s: &PlaybackSession, fps: f64) -> Option<String> {
691 let sources = s.sources();
692 let probe = |i: usize| -> Option<engine::AudioProbe> {
693 let src = sources.get(i)?;
694 if engine::is_image(&src.path) {
695 return None;
696 }
697 engine::AudioSession::probe(&src.path, src.audio_stream).ok().flatten()
698 };
699 let (first_at, timeline) = (0..sources.len()).find_map(|i| Some((i, probe(i)?)))?;
700 let width = timeline.channels;
701 let name = |i: usize| {
702 sources[i].path.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned())
703 };
704 for lane in s.lanes().into_iter().filter(|l| l.kind == LaneKind::Audio) {
705 for clip in s.lane_clips(lane) {
706 let Some(p) = probe(clip.source) else {
707 continue; // a silent source is silence, whatever the timeline is
708 };
709 // The engine's own gates ([`engine::audio`]'s export check): a mono
710 // source joins a wider timeline, a stereo pair folds onto a mono one.
711 if p.channels == width || (p.channels == 1 && width > 1) || (p.channels == 2 && width == 1) {
712 continue;
713 }
714 return Some(format!(
715 "{} at {} plays `{}` ({} ch), but the timeline is {width} ch, set by its first audio source `{}`: \
716an export would fail on it. Remove that clip, or remove `{}` with media_remove to let another source set the width",
717 crate::parse::lane_name(lane),
718 crate::parse::clock(clip.start, fps),
719 name(clip.source),
720 p.channels,
721 name(first_at),
722 name(first_at),
723 ));
724 }
725 }
726 None
727}
728
729/// The open project's folder, the one a relative `out` is resolved against.
730fn project_dir(srv: &Server) -> Option<PathBuf> {
731 let file = std::path::absolute(srv.path.as_ref()?).ok()?;
732 file.parent().map(Path::to_path_buf)
733}
734
735/// Makes `raw` absolute. A relative path is taken from the project's folder, never the
736/// server's working directory, and is refused when no project is open. Returns the path
737/// and, when it was resolved against the project, a note saying so.
738fn anchor_out(srv: &Server, raw: &str) -> Result<(String, Option<String>), String> {
739 let p = expand_home(raw);
740 if p.is_absolute() {
741 return Ok((p.display().to_string(), None));
742 }
743 let Some(dir) = project_dir(srv) else {
744 return Err(format!(
745 "out `{raw}` is a relative path and no project is open, so there is no folder to resolve it against: give an absolute path (such as ~/Videos/x.mp4), or open a project first"
746 ));
747 };
748 let note = format!(
749 "relative out `{raw}` resolved against the project folder {}",
750 dir.display()
751 );
752 Ok((dir.join(&p).display().to_string(), Some(note)))
753}
754
755/// The `.part` an export to `out` writes through (`out` with `.part` appended), when a
756/// killed process left one behind: it is deleted, and the note says so. `None` when there is none.
757fn stale_part_note(out: &Path) -> Option<String> {
758 let mut name = out.as_os_str().to_owned();
759 name.push(".part");
760 let part = PathBuf::from(name);
761 if !part.is_file() {
762 return None;
763 }
764 Some(match std::fs::remove_file(&part) {
765 Ok(()) => format!(
766 "an earlier export to {} did not finish: {} left behind — deleted",
767 out.display(),
768 part.display()
769 ),
770 Err(e) => format!(
771 "an earlier export to {} did not finish: {} left behind — could not delete it: {e}",
772 out.display(),
773 part.display()
774 ),
775 })
776}
777
778/// A warning when `out` lands inside a git working tree and not beside the project file:
779/// an export there shows up in `git status`. Does not refuse.
780fn repo_warning(out: &Path, project: Option<&Path>) -> Option<String> {
781 let parent = out.parent()?;
782 if project == Some(parent) {
783 return None;
784 }
785 let repo = parent.ancestors().find(|a| a.join(".git").exists())?;
786 Some(format!(
787 "warning: {} is inside the git working tree at {}, so the export will show up in git status; write exports outside the repo, or next to the project file",
788 out.display(),
789 repo.display()
790 ))
791}
792
793// ---- burned captions ------------------------------------------------------
794
795/// The schema of `burn_captions`, shared with `frame` and `contact_sheet`.
796pub(crate) fn burn_schema() -> Value {
797 json!({
798 "type": ["object", "boolean"],
799 "description": format!("{BURN_DOC} Pass true for the defaults, or false for no burn."),
800 "properties": {
801 "track": {
802 "type": "integer",
803 "minimum": 0,
804 "description": "Which subtitle track to burn, as in `subtitles` (its index). Default: the track placed on the first subtitle lane that has clips, else track 0."
805 },
806 "size": {
807 "type": "integer",
808 "minimum": 10,
809 "maximum": 200,
810 "description": "Text height as permille of the frame height: 50 (the default) is about 5% of the picture."
811 },
812 "outline": {
813 "type": "string",
814 "enum": ["none", "thin", "thick"],
815 "description": "Dark outline around each letter. Default thin."
816 },
817 "boxed": {
818 "type": "boolean",
819 "description": "Draw a translucent black box behind the caption. Default true."
820 },
821 "place": {
822 "type": "string",
823 "enum": ["bottom", "top", "centre"],
824 "description": "Where the caption sits in the picture. Default bottom."
825 },
826 "family": {
827 "type": "string",
828 "description": "The font family the caption is set in, by the name the GUI's font list shows (for example \"Noto Serif\"). Default: the bundled Archivo. A name the system does not have draws in the bundled face."
829 },
830 "animation": {
831 "type": "string",
832 "enum": ["none", "karaoke", "pop", "bounce", "word"],
833 "description": "Caption animation against the words' times. none: the static cue (default). karaoke: the whole chunk shown, the word being spoken in the highlight colour. pop: words appear as they are spoken, each popping from 125% to 100% in 120 ms. bounce: the word being spoken is raised and enlarged, easing down. word: one big word at a time. Default: the project's caption style (project_settings captions), else none."
834 },
835 "highlight": {
836 "type": "string",
837 "description": "Highlight colour as #rrggbb (or #rgb). Default #ffd600 yellow."
838 },
839 "box": {
840 "type": "boolean",
841 "description": "The highlight is a rounded box of the colour behind white text, not coloured text. Default false. (`boxed` is the black box behind the whole caption.)"
842 },
843 "uppercase": {
844 "type": "boolean",
845 "description": "Draw the text in capitals. Default false."
846 },
847 "words_per_line": {
848 "type": "integer",
849 "minimum": 0,
850 "maximum": 12,
851 "description": "At most this many words on screen at once; a longer cue is re-chunked by its word times (2 to 4 is the shorts style). 0 keeps each cue whole (default). The word animation is always one."
852 },
853 "native": {
854 "type": "boolean",
855 "description": "A track that is an .ass or .ssa file is drawn as its script says: its styles, positions, outline, shadow and fades. false draws it with the caption options above instead. Default true; other tracks ignore it."
856 }
857 },
858 "additionalProperties": false
859 })
860}
861
862/// The note a burn of `track` owes when a cue has a character no bundled face draws:
863/// `no glyph for: U+XXXX`, each named once. `None` when every character draws.
864fn missing_glyph_note(s: &PlaybackSession, track: usize) -> Option<String> {
865 let (project, meta) = s.export_snapshot();
866 let cues = engine::export::burn_cues(&project, track, meta.frame_rate).ok()?;
867 let lines: Vec<String> = cues.iter().filter(|c| c.image.is_none()).map(|c| c.text.clone()).collect();
868 let missing = engine::text::missing_glyphs(&lines);
869 if missing.is_empty() {
870 return None;
871 }
872 let codes: Vec<String> = missing.iter().map(|c| format!("U+{:04X}", *c as u32)).collect();
873 Some(format!("no glyph for: {} (drawn as an empty box)", codes.join(" ")))
874}
875
876/// The `burn_captions` argument checked against the open session: `None` when it is
877/// absent, else the subtitle track to draw (an index into `Project::subtitles`) and its
878/// style. Refuses a track that does not exist, a bitmap track, and a track with no text.
879/// Shared by `export_start`, `frame` and `contact_sheet`.
880pub(crate) fn parse_burn(args: &Value, s: &PlaybackSession) -> Result<Option<(usize, TextStyle)>, String> {
881 // `true` is the defaults, `{}`; `false` is off, as an absent key is.
882 let defaults = json!({});
883 let raw = match args.get(BURN_KEY) {
884 None | Some(Value::Null | Value::Bool(false)) => return Ok(None),
885 Some(Value::Bool(true)) => &defaults,
886 Some(v) => v,
887 };
888 let obj = raw
889 .as_object()
890 .ok_or("burn_captions must be an object or a boolean, e.g. {\"track\": 0, \"size\": 50} or true")?;
891 if let Some(key) = obj.keys().find(|k| !BURN_KEYS.contains(&k.as_str())) {
892 return Err(format!(
893 "burn_captions: unknown key `{key}`: the keys are track, size, outline, boxed, place, family, animation, highlight, box, uppercase, words_per_line, native"
894 ));
895 }
896 let subs = s.subtitles();
897 let track = match obj.get("track").filter(|v| !v.is_null()) {
898 Some(v) => {
899 let i = v
900 .as_u64()
901 .ok_or("burn_captions.track must be a whole-number track index, e.g. 0")?
902 as usize;
903 if i >= subs.len() {
904 return Err(format!(
905 "burn_captions: track {i} does not exist: this project has {} subtitle track(s)",
906 subs.len()
907 ));
908 }
909 i
910 }
911 None if subs.is_empty() => {
912 return Err(
913 "burn_captions: this project has no subtitle track to burn: import one first (subtitles_import)"
914 .to_string(),
915 )
916 }
917 None => placed_track(s),
918 };
919 let t = &subs[track];
920 if t.is_bitmap() {
921 return Err(format!(
922 "burn_captions: track {track} is pictures (PGS), not text, and only text cues can be burned: pick a text track"
923 ));
924 }
925 if let Some(why) = &t.refused {
926 return Err(format!("burn_captions: track {track} has no text to burn: {why}"));
927 }
928 if t.cues.is_empty() {
929 return Err(format!("burn_captions: track {track} has no cues to burn"));
930 }
931 let (project, meta) = s.export_snapshot();
932 let drawn = engine::export::burn_cues(&project, track, meta.frame_rate)
933 .map_err(|e| format!("burn_captions: {e}"))?;
934 if drawn.is_empty() {
935 return Err(format!(
936 "burn_captions: track {track} has no cue on the timeline to draw: its cues are cut away, past the picture, or on a hidden lane"
937 ));
938 }
939
940 let mut style = TextStyle {
941 outline: Outline::Thin,
942 caption: caption_from(obj, s.caption_style())?,
943 ..TextStyle::default()
944 };
945 if let Some(v) = obj.get("size").filter(|v| !v.is_null()) {
946 let n = v
947 .as_u64()
948 .filter(|n| (10..=200).contains(n))
949 .ok_or("burn_captions.size must be a whole number from 10 to 200 (permille of the frame height; 50 is about 5%)")?;
950 style.size = n as u32;
951 }
952 if let Some(v) = obj.get("outline").filter(|v| !v.is_null()) {
953 style.outline = match v.as_str() {
954 Some("none") => Outline::None,
955 Some("thin") => Outline::Thin,
956 Some("thick") => Outline::Thick,
957 _ => return Err("burn_captions.outline must be none, thin or thick".to_string()),
958 };
959 }
960 if let Some(v) = obj.get("boxed").filter(|v| !v.is_null()) {
961 style.boxed = v.as_bool().ok_or("burn_captions.boxed must be true or false")?;
962 }
963 if let Some(v) = obj.get("native").filter(|v| !v.is_null()) {
964 style.native = v.as_bool().ok_or("burn_captions.native must be true or false")?;
965 }
966 if let Some(v) = obj.get("place").filter(|v| !v.is_null()) {
967 style.place = match v.as_str() {
968 Some("bottom") => Place::Bottom,
969 Some("top") => Place::Top,
970 Some("centre") => Place::Centre,
971 _ => return Err("burn_captions.place must be bottom, top or centre".to_string()),
972 };
973 }
974 if let Some(v) = obj.get("family").filter(|v| !v.is_null()) {
975 let name = v.as_str().ok_or("burn_captions.family must be a font family name, e.g. \"Noto Serif\"")?;
976 style.family = Some(name.to_string());
977 }
978 Ok(Some((track, style)))
979}
980
981/// `base` with the caption keys of `obj` (`animation`, `highlight`, `box`, `uppercase`,
982/// `words_per_line`) laid over it. Shared by `burn_captions` and `project_settings captions`.
983pub(crate) fn caption_from(obj: &Map<String, Value>, base: CaptionStyle) -> Result<CaptionStyle, String> {
984 let mut cs = base;
985 let set = |key: &str| obj.get(key).filter(|v| !v.is_null());
986 if let Some(v) = set("animation") {
987 cs.anim = v
988 .as_str()
989 .and_then(CaptionAnim::from_name)
990 .ok_or("animation must be none, karaoke, pop, bounce or word")?;
991 }
992 if let Some(v) = set("highlight") {
993 let hex = v.as_str().map(|t| t.trim_start_matches('#')).unwrap_or("");
994 let digits: Option<Vec<u8>> = hex.chars().map(|c| c.to_digit(16).map(|d| d as u8)).collect();
995 cs.highlight = match digits.as_deref() {
996 Some([r, g, b]) => [r * 17, g * 17, b * 17],
997 Some([r1, r2, g1, g2, b1, b2]) => [r1 * 16 + r2, g1 * 16 + g2, b1 * 16 + b2],
998 _ => return Err("highlight must be a colour like #ffd600 or #fd0".to_string()),
999 };
1000 }
1001 if let Some(v) = set("box") {
1002 cs.hl_box = v.as_bool().ok_or("box must be true or false")?;
1003 }
1004 if let Some(v) = set("uppercase") {
1005 cs.uppercase = v.as_bool().ok_or("uppercase must be true or false")?;
1006 }
1007 if let Some(v) = set("words_per_line") {
1008 cs.words_per_line = v
1009 .as_u64()
1010 .filter(|&n| n <= u64::from(MAX_WORDS_PER_LINE))
1011 .ok_or_else(|| format!("words_per_line must be a whole number from 0 to {MAX_WORDS_PER_LINE}"))? as u8;
1012 }
1013 Ok(cs)
1014}
1015
1016/// The track on the first subtitle lane that has clips, or track 0 when no lane does.
1017/// A clip naming a track that is gone is skipped rather than trusted.
1018fn placed_track(s: &PlaybackSession) -> usize {
1019 let n = s.subtitles().len();
1020 s.subtitle_lanes()
1021 .into_iter()
1022 .find_map(|l| s.sub_lane(l).first().map(|c| c.track))
1023 .filter(|&t| t < n)
1024 .unwrap_or(0)
1025}
1026
1027// ---- argument helpers -----------------------------------------------------
1028
1029/// `range: {from, to}` as a half-open span of timeline frames, or `None`.
1030pub(crate) fn parse_range(args: &Value, fps: f64, end: u32, media: u32) -> Result<Option<(u32, u32)>, String> {
1031 let Some(r) = args.get("range") else { return Ok(None) };
1032 if r.is_null() {
1033 return Ok(None);
1034 }
1035 let from = r
1036 .get("from")
1037 .ok_or("`range` needs both `from` and `to`, e.g. {\"from\": \"0s\", \"to\": \"15s\"}")?;
1038 let to = r
1039 .get("to")
1040 .ok_or("`range` needs both `from` and `to`, e.g. {\"from\": \"0s\", \"to\": \"15s\"}")?;
1041 let from = frame(from, fps, end).map_err(|e| format!("range.from: {e}"))?;
1042 let to = frame(to, fps, end).map_err(|e| format!("range.to: {e}"))?;
1043 if from >= to {
1044 return Err(format!("range.from ({}) must come before range.to ({})", tc(from, fps), tc(to, fps)));
1045 }
1046 // A `to` past the picture and sound but inside the timeline is clipped to them by the
1047 // caller, and said; past the timeline itself it is refused, naming both ends.
1048 if to > end {
1049 return Err(format!(
1050 "range.to ({}) is past the end of the timeline ({}): the picture and sound end at {}",
1051 tc(to, fps),
1052 tc(end, fps),
1053 tc(media, fps)
1054 ));
1055 }
1056 Ok(Some((from, to)))
1057}
1058
1059fn parse_subtitles(args: &Value, count: usize) -> Result<Vec<usize>, String> {
1060 let arr = match args.get("subtitles") {
1061 None | Some(Value::Null) | Some(Value::Bool(false)) => return Ok(Vec::new()),
1062 Some(Value::Bool(true)) => return Ok((0..count).collect()),
1063 Some(Value::Array(arr)) => arr,
1064 Some(_) => return Err("subtitles must be true (every track) or a list of track indices, e.g. [0, 2]".to_string()),
1065 };
1066 let mut out = Vec::with_capacity(arr.len());
1067 for x in arr {
1068 let i = x
1069 .as_u64()
1070 .ok_or("subtitles must be whole-number track indices, e.g. [0, 2]")? as usize;
1071 if i >= count {
1072 return Err(format!(
1073 "subtitles: track {i} does not exist: this project has {count} subtitle track(s)"
1074 ));
1075 }
1076 out.push(i);
1077 }
1078 Ok(out)
1079}
1080
1081/// Why a hardware AV1 encode is refused: the VA-API AV1 encoder crashed the GPU on this
1082/// machine. WebM is seated as AV1 by the engine, so it is refused the same way.
1083const HW_AV1_REFUSAL: &str = "hardware AV1 encoding is disabled here (it has crashed the GPU on this machine); exporting with software AV1 (rav1e) — or pick h264/hevc for hardware";
1084
1085/// True when this export would put AV1 (or WebM) on the GPU. `auto` never does: the engine
1086/// seats AV1 in software unless the seat is asked for by name. Only `EDITH_ALLOW_HW_AV1=1`
1087/// lifts the refusal.
1088fn hw_av1_refused(format: Format, seat: EncoderSeat) -> bool {
1089 seat == EncoderSeat::Hardware
1090 && matches!(format, Format::Av1 | Format::Av1Mp4 | Format::Webm)
1091 && std::env::var("EDITH_ALLOW_HW_AV1").map_or(true, |v| v != "1")
1092}
1093
1094/// The note a request for soft subtitles owes when the file will have no picture: the sound
1095/// alone has no track to carry them, and the card would otherwise say only `none`, which
1096/// reads as if the export had been asked nothing. Said once, in the reply, before the job runs.
1097fn sound_only_subs_note(format: Format) -> String {
1098 if format.ext() == "mp4" {
1099 "subtitles not written: an mp4 with no picture is written as sound only; add a picture (a still image or a video clip) to carry them".to_string()
1100 } else {
1101 format!("subtitles not written: {} is the sound alone; add a picture to carry them", format_name(format))
1102 }
1103}
1104
1105/// The picture encoder a finished or running job used, from the engine's encoder line
1106/// (`seat · sound`); the planned seat when the engine has not published one yet.
1107/// The sound a job measured, as a reply's ` · audio: …` part; empty until the engine says.
1108fn sound_note(job: &Job) -> String {
1109 sound_words(job.picture.is_empty(), job.encoders().as_deref())
1110 .map_or_else(String::new, |s| format!(" · audio: {s}"))
1111}
1112
1113/// The pure half of [`sound_note`]. An audio-only job's engine line is the sound alone
1114/// (`AAC · SW encode (ec-aac)`, `AAC copy`, `PCM · SW (hound)`), with no picture part in front,
1115/// so its codec is the first part; a job with a picture skips that part.
1116fn sound_words(audio_only: bool, encoders: Option<&str>) -> Option<String> {
1117 if audio_only {
1118 encoders.map(plain_audio)
1119 } else {
1120 measured_sound(encoders)
1121 }
1122}
1123
1124fn picture_note(job: &Job) -> String {
1125 picture_label(job.encoders(), &job.picture, job.format)
1126}
1127
1128/// The pure half of [`picture_note`]: the seat named by the engine's line when it has one,
1129/// else the planned seat, in plain words. Empty when the export has no picture (`planned` is empty).
1130fn picture_label(encoders: Option<String>, planned: &str, format: Format) -> String {
1131 if planned.is_empty() {
1132 return String::new();
1133 }
1134 let seat = encoders
1135 .as_deref()
1136 .and_then(|e| e.split(" · ").next())
1137 .unwrap_or(planned);
1138 format!(" · video: {}", plain_video(format, seat))
1139}
1140
1141/// The sound a finished export says it wrote, in plain words, when the engine has measured it:
1142/// the part of the engine's line after the picture (`AAC · SW encode (ec-aac)` says `AAC`).
1143fn measured_sound(encoders: Option<&str>) -> Option<String> {
1144 let rest = encoders?.split(" · ").skip(1).collect::<Vec<_>>().join(" · ");
1145 (!rest.is_empty()).then(|| plain_audio(&rest))
1146}
1147
1148/// The picture's codec and seat in plain words, from the format and the engine's seat label:
1149/// `AV1 (software)`, `H.264 (hardware)`, `H.264 (copy)`.
1150fn plain_video(format: Format, seat: &str) -> String {
1151 let codec = match format {
1152 Format::Mp4 => "H.264",
1153 Format::Av1 | Format::Av1Mp4 | Format::Webm => "AV1",
1154 Format::Hevc | Format::HevcMp4 => "HEVC",
1155 _ => "video",
1156 };
1157 let how = if seat.starts_with("HW") {
1158 "hardware"
1159 } else if seat.starts_with("copy") {
1160 "copy"
1161 } else if seat == NO_HW_SEAT {
1162 "no hardware"
1163 } else {
1164 "software"
1165 };
1166 format!("{codec} ({how})")
1167}
1168
1169/// The sound's codec in plain words: `AAC`, `Opus`, `AAC (copy)`, `none`.
1170fn plain_audio(label: &str) -> String {
1171 if label.starts_with("no sound") {
1172 return "none".to_string();
1173 }
1174 let name = label.split(" · ").next().unwrap_or(label).trim();
1175 match name.strip_suffix(" copy") {
1176 Some(codec) => format!("{codec} (copy)"),
1177 None => name.to_string(),
1178 }
1179}
1180
1181/// The container in plain words: `MP4`, `WebM`, `Matroska`, `WAV`.
1182fn plain_container(format: Format) -> &'static str {
1183 match format {
1184 Format::Mp4 | Format::Av1Mp4 | Format::HevcMp4 => "MP4",
1185 Format::Av1 | Format::Hevc => "Matroska",
1186 Format::Webm => "WebM",
1187 Format::Wav => "WAV",
1188 Format::Flac => "FLAC",
1189 Format::Mp3 => "MP3",
1190 Format::Ogg => "Ogg",
1191 Format::Opus => "Ogg Opus",
1192 Format::M4a => "M4A",
1193 Format::ProRes => "QuickTime",
1194 Format::PngSequence => "PNG folder",
1195 Format::Still => "PNG",
1196 Format::Gif => "GIF",
1197 }
1198}
1199
1200/// What an export writes, in the words a start reply uses:
1201/// `video: AV1 (software), audio: Opus, container: WebM`, or `audio: PCM, container: WAV`.
1202/// `picture` is the planned seat, empty for an audio-only export.
1203fn av_words(format: Format, picture: &str, sound: &str) -> String {
1204 // A picture set writes pictures and no sound, so it names no audio codec at all.
1205 if matches!(format, Format::PngSequence | Format::Still | Format::Gif) {
1206 return format!("no sound, container: {}", plain_container(format));
1207 }
1208 let mut parts = Vec::new();
1209 if !picture.is_empty() {
1210 parts.push(format!("video: {}", plain_video(format, picture)));
1211 }
1212 // The sound is the codec the engine predicts from the sources' headers (a Matroska mix is
1213 // Opus at 48 kHz mono or stereo, AAC otherwise); the status line names the one measured.
1214 parts.push(format!("audio: {}", plain_audio(sound)));
1215 parts.push(format!("container: {}", plain_container(format)));
1216 parts.join(", ")
1217}
1218
1219/// The `size` of export_start: `WIDTHxHEIGHT` (`1280x720`), or a height with a `p` (`720p`),
1220/// which is 16:9 at that height. Both sides must be even and a picture size the engine takes,
1221/// so the picture has whole chroma samples. `None` when no size was asked for.
1222pub(crate) fn parse_size(args: &Value) -> Result<Option<(u32, u32)>, String> {
1223 let Some(raw) = args.get("size").filter(|v| !v.is_null()) else {
1224 return Ok(None);
1225 };
1226 let text = raw
1227 .as_str()
1228 .ok_or("size must be a string: WIDTHxHEIGHT such as 1280x720, or a height such as 720p")?
1229 .trim()
1230 .to_ascii_lowercase();
1231 let number = |part: &str| -> Result<u64, String> {
1232 part.trim()
1233 .parse::<u64>()
1234 .map_err(|_| format!("size `{text}`: write WIDTHxHEIGHT such as 1280x720, or a height such as 720p"))
1235 };
1236 let (w, h) = match text.strip_suffix('p') {
1237 Some(height) => {
1238 let h = number(height)?;
1239 // 16:9 at that height, the width rounded to the nearest even number.
1240 let w = (h * 16 / 9 + 1) & !1;
1241 (w, h)
1242 }
1243 None => match text.split_once('x') {
1244 Some((w, h)) => (number(w)?, number(h)?),
1245 None => return Err(format!("size `{text}`: write WIDTHxHEIGHT such as 1280x720, or a height such as 720p")),
1246 },
1247 };
1248 let max = u64::from(engine::MAX_RESOLUTION);
1249 if w == 0 || h == 0 || w > max || h > max {
1250 return Err(format!("size `{text}`: each side must be from 2 to {max} pixels"));
1251 }
1252 if w % 2 != 0 || h % 2 != 0 {
1253 return Err(format!("size `{text}`: both sides must be even (the picture is 4:2:0 coded)"));
1254 }
1255 Ok(Some((w as u32, h as u32)))
1256}
1257
1258/// The `fit` of export_start: `None` for `keep` (or no fit), which leaves every clip on its own
1259/// policy; `fit` or `fill` puts every picture clip on that policy in this export only.
1260pub(crate) fn parse_fit(args: &Value) -> Result<Option<FitPolicy>, String> {
1261 match opt_str(args, "fit").map(|s| s.trim().to_ascii_lowercase()) {
1262 None => Ok(None),
1263 Some(s) => match s.as_str() {
1264 "keep" => Ok(None),
1265 "fit" => Ok(Some(FitPolicy::Fit)),
1266 "fill" => Ok(Some(FitPolicy::Fill)),
1267 other => Err(format!("unknown fit `{other}`: write keep, fit or fill")),
1268 },
1269 }
1270}
1271
1272fn parse_seat(args: &Value) -> Result<EncoderSeat, String> {
1273 match opt_str(args, "seat").map(|s| s.trim().to_ascii_lowercase()) {
1274 None => Ok(EncoderSeat::Auto),
1275 Some(s) => match s.as_str() {
1276 "auto" => Ok(EncoderSeat::Auto),
1277 "hardware" => Ok(EncoderSeat::Hardware),
1278 "software" => Ok(EncoderSeat::Software),
1279 other => Err(format!("unknown seat `{other}`: write auto, hardware or software")),
1280 },
1281 }
1282}
1283
1284/// Index of `job:<n>` (1-based in text) into `srv.jobs`.
1285fn job_index(srv: &Server, n: u64) -> Result<usize, String> {
1286 let len = srv.jobs.len();
1287 if n >= 1 && n <= len as u64 {
1288 Ok(n as usize - 1)
1289 } else if len == 0 {
1290 Err(format!("no job:{n} — no export has been started yet (export_start makes one)"))
1291 } else {
1292 Err(format!("no job:{n} — the exports so far are job:1 to job:{len}"))
1293 }
1294}
1295
1296/// How long a finished job took: one decimal under ten seconds (`0.7 s`), else the clock form.
1297fn took_words(s: f64) -> String {
1298 if s < 10.0 {
1299 format!("{:.1} s", s.max(0.0))
1300 } else {
1301 clock_secs(s)
1302 }
1303}
1304
1305fn clock_secs(s: f64) -> String {
1306 let t = s.round().max(0.0) as u64;
1307 if t >= 3600 {
1308 format!("{}h{:02}m{:02}s", t / 3600, t % 3600 / 60, t % 60)
1309 } else if t >= 60 {
1310 format!("{}m{:02}s", t / 60, t % 60)
1311 } else {
1312 format!("{t}s")
1313 }
1314}
1315
1316/// The true-peak ceiling the mix is held to (dBTP), the default `true_peak` of the loudness tools.
1317const PEAK_CEILING_DBTP: f64 = -1.0;
1318
1319/// The smallest true peak that clips for text: the lowest value one decimal prints above 0 (+0.1).
1320const CLIP_DBTP: f64 = 0.05;
1321
1322/// A true peak above the ceiling for text: two decimals within 0.05 dB of it, since one decimal
1323/// would print the ceiling itself ("-1.0 dBTP is above the -1 dBTP ceiling").
1324fn ceiling_figure(p: f64) -> String {
1325 if (p - PEAK_CEILING_DBTP).abs() < 0.05 {
1326 format!("{p:+.2}")
1327 } else {
1328 format!("{p:+.1}")
1329 }
1330}
1331
1332/// The word a caption or title's place reads as in a reply.
1333pub(crate) fn place_word(place: Place) -> &'static str {
1334 match place {
1335 Place::Bottom => "bottom",
1336 Place::Top => "top",
1337 Place::Centre => "centre",
1338 }
1339}
1340
1341/// The note a burned caption and a title on screen together in the same place earn: when they
1342/// clash, and the place to move the captions to (or the title). `secs` is the moment they first
1343/// show together.
1344pub(crate) fn clash_note(secs: f64, title: &str, place: Place) -> String {
1345 let other = if place == Place::Bottom { "top" } else { "bottom" };
1346 format!(
1347 "at {secs:.1}s the caption overlaps title '{}' (both at the {}): burn_captions {{place:\"{other}\"}} or move the title",
1348 title.replace('\n', " / "),
1349 place_word(place)
1350 )
1351}
1352
1353/// The integrated loudness and true peak of an exported file's first sound track, decoded from
1354/// the file with the same measurement the `loudness` tool uses. A silent stretch measures -inf
1355/// on both (no block above the gate), which is kept as such. `None` when the file has no sound
1356/// or cannot be measured.
1357fn file_levels(path: &std::path::Path) -> Option<FileLevels> {
1358 engine::loudness::measure_file(path, 0, None)
1359 .ok()
1360 .flatten()
1361 .map(|l| FileLevels { lufs: l.integrated_lufs, true_peak_dbtp: l.true_peak_dbtp })
1362}
1363
1364/// The shortest sound integrated loudness is gated over: one 400 ms block.
1365const LOUDNESS_MIN_SECS: f64 = 0.4;
1366
1367/// `-14.0 LUFS`. A file with no block above the gate says why: `too short to measure loudness`
1368/// when its sound is under one 400 ms block, else `silent`.
1369fn lufs_text(lufs: f64, too_short: bool) -> String {
1370 if lufs.is_finite() {
1371 format!("{lufs:.1} LUFS")
1372 } else if too_short {
1373 format!("too short to measure loudness (under {LOUDNESS_MIN_SECS} s)")
1374 } else {
1375 "silent".to_string()
1376 }
1377}
1378
1379/// Whether the first sound track of the written file is shorter than one loudness block.
1380fn sound_too_short(path: &std::path::Path) -> bool {
1381 engine::AudioSession::stream_duration_secs(path, 0)
1382 .ok()
1383 .flatten()
1384 .is_some_and(|secs| secs < LOUDNESS_MIN_SECS)
1385}
1386
1387/// `-1.0 dBTP` or `+0.3 dBTP` (signed, as hear reads its figures), or `silent` for a file with no sound to peak.
1388fn peak_text(dbtp: f64) -> String {
1389 if dbtp.is_finite() { format!("{dbtp:+.1} dBTP") } else { "silent".to_string() }
1390}
1391
1392/// A size in decimal units (KB = 1000 bytes, MB = 10^6 bytes), the unit `media_probe` uses,
1393/// so one file reads the same in every reply.
1394fn human_bytes(n: u64) -> String {
1395 const MB: f64 = 1_000_000.0;
1396 if n < 1000 {
1397 format!("{n} B")
1398 } else if (n as f64) < MB {
1399 format!("{:.1} KB", n as f64 / 1000.0)
1400 } else {
1401 format!("{:.1} MB", n as f64 / MB)
1402 }
1403}
1404
1405// ---- tools ----------------------------------------------------------------
1406
1407fn export_start(srv: &mut Server, args: &Value) -> Reply {
1408 let out_raw = tri!(arg_str(args, "out"));
1409 let overwrite = opt_bool(args, "overwrite").unwrap_or(false);
1410 let (anchored, anchor_note) = match anchor_out(srv, out_raw) {
1411 Ok(v) => v,
1412 Err(e) => return Reply::err(e),
1413 };
1414 let preset = match opt_str(args, "preset") {
1415 None => None,
1416 Some(id) => match engine::export_presets::by_id(id) {
1417 Some(p) => Some(p),
1418 None => {
1419 let ids: Vec<&str> = engine::export_presets::presets().iter().map(|p| p.id).collect();
1420 return Reply::err(format!("unknown preset `{id}`: the presets are {} (export_presets lists them)", ids.join(", ")));
1421 }
1422 },
1423 };
1424 let (out, format) = match resolve_out(&anchored, opt_str(args, "format").or(preset.map(|p| format_name(p.format)))) {
1425 Ok(v) => v,
1426 Err(e) => return Reply::err(e),
1427 };
1428 let checked = match format {
1429 Format::PngSequence => check_folder(&out, overwrite),
1430 _ => check_out(&out, overwrite),
1431 };
1432 if let Err(e) = checked {
1433 return Reply::err(e);
1434 }
1435 let warning = repo_warning(&out, project_dir(srv).as_deref());
1436 // Two jobs on one file would write the same `.part` and race for the name, so a
1437 // running job on `out` refuses this one even when `overwrite` is set.
1438 if let Some((n, _)) = srv
1439 .jobs
1440 .iter()
1441 .enumerate()
1442 .find(|(_, j)| job_running(j) && j.out == out)
1443 {
1444 return Reply::err(format!(
1445 "job:{} is still writing {}: wait for it to finish or cancel it, or choose another out path",
1446 n + 1,
1447 out.display()
1448 ));
1449 }
1450
1451 let s = tri!(srv.session_ref());
1452 // A stabilised clip with no finished analysis is measured by the export itself,
1453 // which export_status shows as its "Measuring shake" stage.
1454 let fps = session_fps(s);
1455 let end = session_end(s);
1456 if end == 0 {
1457 return Reply::err("timeline is empty — nothing to export: place a clip first (edit place/append)");
1458 }
1459 if let Some(why) = channel_mismatch(s, fps) {
1460 return Reply::err(why);
1461 }
1462 // The engine refuses a picture format with no picture, but only once the job runs;
1463 // refuse it here, in the same words, so the agent learns it at the start.
1464 let has_picture = s
1465 .lanes()
1466 .into_iter()
1467 .any(|l| l.kind == LaneKind::Video && !s.lane_clips(l).is_empty());
1468 // An mp4 of a picture-less timeline is written as the sound alone (AAC in an mp4), as
1469 // the engine does; every other picture format would be black.
1470 let sound_only = !format.has_video() || (!has_picture && format.ext() == "mp4");
1471 // Named first in the reply: an mp4 of a picture-less timeline is the sound alone, so any caption
1472 // track is not written, and the words say what to use instead.
1473 let lead = (!has_picture && format.ext() == "mp4" && !s.subtitles().is_empty()).then(|| {
1474 "sound only: an mp4 with no picture is written as the sound alone, so the captions are not written. For sound alone use m4a; for a video with captions add a picture to the timeline (a still image is enough)".to_string()
1475 });
1476 if format.has_video() && !has_picture && format.ext() != "mp4" {
1477 return Reply::err(format!(
1478 "the timeline has no video clips, so {} would be black: export mp4 (the sound alone), m4a, wav, flac or mp3 instead",
1479 format_name(format)
1480 ));
1481 }
1482 // A whole-timeline export stops where the picture and sound stop (the engine's
1483 // `media_frames`): a caption hanging past that is not written, and neither is a range's
1484 // part past it. The reply reports the length the file really is, not the timeline's
1485 // (which counts the captions), and says why.
1486 let media = media_end(s);
1487 let (range, clipped) = match parse_range(args, fps, end, media) {
1488 Ok(Some((from, _))) if from >= media => {
1489 return Reply::err(format!(
1490 "range.from ({}) is at or past the picture and sound end ({}): captions alone are not written, so there is nothing to export there",
1491 tc(from, fps),
1492 tc(media, fps)
1493 ))
1494 }
1495 Ok(Some((from, to))) => (Some((from, to.min(media))), to > media),
1496 Ok(None) => (None, false),
1497 Err(e) => return Reply::err(e),
1498 };
1499 // An offline source is refused by name only when a clip this export reads uses it: a file
1500 // that only clips outside the range use does not stop the export (the GUI's export_missing).
1501 let missing = s.offline_in_span(range);
1502 if !missing.is_empty() {
1503 let names: Vec<String> = missing.iter().map(|(i, p)| format!("src:{i} {}", p.display())).collect();
1504 return Reply::err(format!(
1505 "export refused: {} source(s) offline (moved or deleted) inside the exported range: {}; media_relink each one, or project_open with search",
1506 missing.len(),
1507 names.join(", ")
1508 ));
1509 }
1510 let ranged = range.is_some();
1511 let captions_note = (range.is_none() && media < end).then(|| {
1512 format!(
1513 "captions run to {}s, past the picture and sound end at {}s: they are not exported (a range stops there too)",
1514 secs(end, fps),
1515 secs(media, fps)
1516 )
1517 });
1518 let range_note = clipped.then(|| {
1519 format!(
1520 "the range runs past the picture and sound end at {}s: the file stops there, and captions past it are not exported",
1521 secs(media, fps)
1522 )
1523 });
1524 if range.is_none() && media == 0 {
1525 return Reply::err("the picture and sound end at 0s, and only captions run past them: nothing to export");
1526 }
1527
1528 let subtitles = match parse_subtitles(args, s.subtitles().len()) {
1529 Ok(v) => v,
1530 Err(e) => return Reply::err(e),
1531 };
1532 let seat = match parse_seat(args) {
1533 Ok(v) => v,
1534 Err(e) => return Reply::err(e),
1535 };
1536 if hw_av1_refused(format, seat) {
1537 return Reply::err(HW_AV1_REFUSAL);
1538 }
1539 let burn = match parse_burn(args, s) {
1540 Ok(v) => v,
1541 Err(e) => return Reply::err(e),
1542 };
1543 if burn.is_some() && (!format.shows_picture() || (!has_picture && format.ext() == "mp4")) {
1544 return Reply::err(format!(
1545 "burn_captions draws into the picture, and {} is audio only: drop burn_captions, or export a video format",
1546 format_name(format)
1547 ));
1548 }
1549 let size = match parse_size(args) {
1550 Ok(v) => v,
1551 Err(e) => return Reply::err(e),
1552 };
1553 let fit = match parse_fit(args) {
1554 Ok(v) => v,
1555 Err(e) => return Reply::err(e),
1556 };
1557 let burned = burn.as_ref().map(|(track, _)| *track);
1558 let glyph_note = burned.and_then(|t| missing_glyph_note(s, t));
1559 let bitrate = match opt_u64(args, "bitrate_kbps") {
1560 Some(0) => return Reply::err("bitrate_kbps must be above 0"),
1561 Some(k) => Some(k.saturating_mul(1000)),
1562 None => None,
1563 };
1564 let intra_only = opt_bool(args, "intra_only").unwrap_or(false);
1565 let qp = match opt_u64(args, "qp") {
1566 None => preset.and_then(|p| p.qp).filter(|_| bitrate.is_none() && !sound_only),
1567 Some(q) if q <= 51 => Some(q as u32),
1568 Some(q) => return Reply::err(format!("qp {q} is not 0 to 51")),
1569 };
1570 if qp.is_some() && bitrate.is_some() {
1571 return Reply::err("qp and bitrate_kbps together: qp fixes the quantiser and bitrate_kbps the rate, so pass one");
1572 }
1573 if qp.is_some() && sound_only {
1574 return Reply::err("qp sets the picture's quantiser, and this export is the sound alone");
1575 }
1576 if qp.is_some() && !matches!(format, Format::Mp4 | Format::Av1 | Format::Av1Mp4 | Format::Hevc | Format::HevcMp4 | Format::Webm) {
1577 return Reply::err(format!(
1578 "qp sets the picture's quantiser: it needs an mp4, av1, av1-mp4, hevc, hevc-mp4 or webm export, not {}",
1579 format_name(format)
1580 ));
1581 }
1582 if qp.is_some() && format.is_av1() && seat != EncoderSeat::Hardware {
1583 return Reply::err("qp for AV1 needs seat hardware: auto and software code AV1 in software, which refuses a constant QP");
1584 }
1585 if qp.is_some() && seat == EncoderSeat::Software && !format.is_hevc() {
1586 return Reply::err("qp with seat software: only the software HEVC encoder writes a constant QP; use seat auto or hardware for H.264");
1587 }
1588 let keyframe_s = match args.get("keyframe_s") {
1589 None | Some(Value::Null) => preset.and_then(|p| p.keyframe_s).filter(|_| !intra_only && !sound_only),
1590 Some(v) => match v.as_f64() {
1591 Some(secs) if (0.1..=10.0).contains(&secs) => Some(secs),
1592 _ => return Reply::err("keyframe_s is a number of seconds, from 0.1 to 10"),
1593 },
1594 };
1595 if keyframe_s.is_some() && intra_only {
1596 return Reply::err("keyframe_s sets the key frame interval, and intra_only codes every picture a key frame: pass one");
1597 }
1598 if keyframe_s.is_some() && sound_only {
1599 return Reply::err("keyframe_s sets the picture's key frames, and this export is the sound alone");
1600 }
1601 let faststart = opt_bool(args, "faststart").unwrap_or(preset.is_some_and(|p| p.faststart));
1602 if faststart && !format.is_mp4_family() {
1603 return Reply::err(format!(
1604 "faststart lays out an mp4, and {} is not one: use mp4, hevc-mp4, av1-mp4 or m4a",
1605 format_name(format)
1606 ));
1607 }
1608 let audio_kbps = match opt_u64(args, "audio_kbps") {
1609 None => None,
1610 Some(k) => {
1611 let Some(k32) = u32::try_from(k).ok().filter(|v| AUDIO_KBPS.contains(v) || *v == AAC_MAX_KBPS) else {
1612 return Reply::err(format!(
1613 "audio_kbps {k} is not one of {}, or {AAC_MAX_KBPS} for AAC",
1614 AUDIO_KBPS.map(|v| v.to_string()).join(", ")
1615 ));
1616 };
1617 if let Some(why) = s.audio_rate_refusal(format, ranged, true) {
1618 return Reply::err(format!(
1619 "audio_kbps can't be chosen for {}: {why}",
1620 format_name(format)
1621 ));
1622 }
1623 if k32 == AAC_MAX_KBPS && !codes_aac(format) {
1624 return Reply::err(format!(
1625 "audio_kbps {k} is AAC only (mp4, av1, av1-mp4, hevc, hevc-mp4, m4a); {} codes at 320 at most",
1626 format_name(format)
1627 ));
1628 }
1629 Some(k32)
1630 }
1631 };
1632
1633 let video_bit_depth = match opt_u64(args, "bit_depth") {
1634 None => None,
1635 Some(8) => Some(8u8),
1636 Some(10) => Some(10u8),
1637 Some(b) => return Reply::err(format!("bit_depth {b} is not 8 or 10")),
1638 };
1639 // The preset fills what the arguments left out; an explicit argument wins.
1640 let preset_settings = preset.map(|p| engine::export_presets::apply(p, ExportSettings::default()));
1641 let bitrate = bitrate.or(preset_settings.as_ref().filter(|_| qp.is_none()).and_then(|a| a.bitrate));
1642 let audio_kbps = audio_kbps.or(preset_settings.as_ref().and_then(|a| a.audio_kbps));
1643 let size = size.or(preset_settings.as_ref().and_then(|a| a.size));
1644 let video_bit_depth = video_bit_depth.or(preset_settings.as_ref().and_then(|a| a.video_bit_depth));
1645 let hevc_speed = tri!(parse_hevc_speed(args, format).map_err(Reply::err));
1646 let prores_profile = tri!(parse_prores_profile(args, format).map_err(Reply::err))
1647 .or(preset_settings.as_ref().filter(|_| format.is_prores()).map(|a| a.prores_profile))
1648 .unwrap_or_default();
1649 let hdr_transfer = tri!(parse_hdr(args, format).map_err(Reply::err))
1650 .or(preset_settings.as_ref().filter(|_| format.is_hevc()).map(|a| a.hdr.transfer))
1651 .unwrap_or_default();
1652 let audio_bit_depth = tri!(parse_sound_bits(args, format).map_err(Reply::err));
1653 if hdr_transfer != HdrTransfer::Sdr && video_bit_depth == Some(8) {
1654 return Reply::err("an HDR export is 10-bit: bit_depth 8 is refused (PQ and HLG are not carried in 8 bits)".to_string());
1655 }
1656 // A loudness argument sets the target from -30 to -5 LUFS; its true-peak ceiling stays the preset's.
1657 let loudness = match args.get("loudness") {
1658 None | Some(Value::Null) => preset_settings.as_ref().and_then(|a| a.loudness),
1659 Some(v) => match v.as_f64() {
1660 Some(lufs) if (-30.0..=-5.0).contains(&lufs) => Some(engine::export::LoudnessTarget {
1661 lufs,
1662 true_peak_dbtp: preset_settings
1663 .as_ref()
1664 .and_then(|a| a.loudness)
1665 .map_or(PEAK_CEILING_DBTP, |l| l.true_peak_dbtp),
1666 }),
1667 _ => return Reply::err("loudness is a number of LUFS from -30 to -5 (-14 is the usual streaming level)".to_string()),
1668 },
1669 };
1670 let loudness_note = match loudness {
1671 Some(l) if args.get("loudness").is_some_and(|v| !v.is_null()) => format!("; loudness {} LUFS", l.lufs),
1672 _ => String::new(),
1673 };
1674 if video_bit_depth == Some(10) && !(format.is_av1() || format.is_hevc()) {
1675 return Reply::err(format!(
1676 "10-bit export is AV1 and HEVC only: format av1 (.mkv), av1-mp4, hevc (.mkv) or hevc-mp4, not {}",
1677 format_name(format)
1678 ));
1679 }
1680 // Chapters: the project's markers, measured from the range's start (the engine's own
1681 // clock, [`PlaybackSession::chapter_list_ns`]). Formats that cannot carry them get none.
1682 // `chapters: "markers"` writes the comment markers as the chapter list in place of the chapters.
1683 let from_markers = match args.get("chapters") {
1684 Some(Value::String(t)) if t.eq_ignore_ascii_case("markers") => true,
1685 Some(Value::String(t)) => {
1686 return Reply::err(format!("argument `chapters`: `{t}` is not true, false or \"markers\""));
1687 }
1688 _ => false,
1689 };
1690 let chapters_asked = from_markers || opt_bool(args, "chapters").unwrap_or(true);
1691 let chapter_format = matches!(
1692 format,
1693 Format::Mp4 | Format::Av1 | Format::Av1Mp4 | Format::Hevc | Format::HevcMp4 | Format::Webm | Format::M4a | Format::Opus
1694 );
1695 let chapters = match (chapters_asked && chapter_format, from_markers) {
1696 (false, _) => Vec::new(),
1697 (true, true) => s.marker_list_ns(range),
1698 (true, false) => s.chapter_list_ns(range),
1699 };
1700 let chapter_note = if (from_markers && s.markers().is_empty()) || (!from_markers && s.chapters().is_empty()) {
1701 None
1702 } else if !chapters_asked {
1703 Some("chapters: left out (chapters: false)".to_string())
1704 } else if !chapter_format {
1705 Some(format!(
1706 "chapters are not written: {} carries no chapter marks (mp4, m4a, mkv, webm and opus do)",
1707 format_name(format)
1708 ))
1709 } else {
1710 let from = if from_markers { " (from the markers)" } else { "" };
1711 Some(match chapters.len() {
1712 1 => format!("1 chapter{from}"),
1713 n => format!("{n} chapters{from}"),
1714 })
1715 };
1716
1717 // Soft subtitle tracks are opt-in: without `subtitles` the file carries none, even
1718 // when the timeline has captions placed on it (the engine writes those whenever it
1719 // is not told otherwise).
1720 let no_soft = subtitles.is_empty();
1721 let asked_subs = !subtitles.is_empty() || args.get("subtitles") == Some(&json!(true));
1722 let sub_note = if asked_subs && s.subtitles().is_empty() {
1723 "note: no subtitle tracks, so no soft track was written".to_string()
1724 } else if asked_subs && sound_only {
1725 sound_only_subs_note(format)
1726 } else if !subtitles.is_empty() {
1727 // The card is asked of the file as it will be written: the range drops a track with
1728 // no cue inside it, and a standalone ASS script's override tags are named as dropped.
1729 let (snap, snap_meta) = s.export_snapshot();
1730 let mut note = engine::export::planned_subtitles_in(
1731 &snap,
1732 format,
1733 subtitles.iter().copied(),
1734 range,
1735 snap_meta.frame_rate,
1736 );
1737 let styled = engine::export::stripped_styling(&snap, &subtitles);
1738 if !styled.is_empty() {
1739 note.push_str(&format!(
1740 "\nstyling not written: the ASS tags ({{\\i1}}, {{\\an8}}) in {} are dropped; the soft track carries the words only",
1741 styled.join(", ")
1742 ));
1743 }
1744 note
1745 } else if burn.is_some() {
1746 "subtitles: burned into the picture (no soft track)".to_string()
1747 } else if s.subtitles().is_empty() {
1748 String::new()
1749 } else if sound_only {
1750 format!("subtitles do not apply: {} is the sound alone", format_name(format))
1751 } else {
1752 "subtitles: none (no soft track; pass subtitles to add one)".to_string()
1753 };
1754 // The depth an AV1 or HEVC file is written at, said in the reply: a named depth as asked, else the
1755 // source's own (10 where any picture source is 10-bit, as the engine decides it).
1756 let depth = (format.is_av1() || format.is_hevc()).then(|| match video_bit_depth {
1757 _ if hdr_transfer != HdrTransfer::Sdr => (true, format!("output 10-bit, {}", hdr_name(hdr_transfer))),
1758 Some(b) => (b == 10, format!("output {b}-bit, as asked")),
1759 None if source_ten_bit(s) => (true, "output 10-bit, from the source".to_string()),
1760 None => (false, "output 8-bit".to_string()),
1761 });
1762 let depth_note = depth.as_ref().map(|(_, note)| note.clone());
1763 let chapters_written = chapters.len();
1764 let settings = ExportSettings {
1765 bitrate,
1766 qp,
1767 seat,
1768 format,
1769 intra_only,
1770 keyframe_s,
1771 faststart,
1772 audio_kbps,
1773 reencode_audio: audio_kbps.is_some(),
1774 subtitles,
1775 no_soft_subtitles: no_soft,
1776 range,
1777 burn_subtitles: burn,
1778 size,
1779 video_bit_depth,
1780 chapters,
1781 loudness,
1782 prores_profile,
1783 hdr: HdrOutput { transfer: hdr_transfer, ..HdrOutput::default() },
1784 audio_bit_depth,
1785 hevc_speed,
1786 gif: GifSettings {
1787 width: opt_u64(args, "gif_width").map_or(480, |w| w as u32),
1788 fps: opt_u64(args, "gif_fps").map_or(15, |f| f as u32),
1789 loop_forever: opt_bool(args, "gif_loop").unwrap_or(true),
1790 },
1791 ..Default::default()
1792 };
1793 // The picture's seat and the sound's codec as the engine will decide them for this
1794 // timeline (its own copy gates, so a Matroska source is never a sound copy). Asked
1795 // only for video: an audio-only file has no picture to name.
1796 let (picture, sound, tone, project_size, hevc_mode, av1_mode) = {
1797 let (project, meta) = s.export_snapshot();
1798 let (video, sound) = planned_seats(&project, &meta, &settings);
1799 let picture = if sound_only { String::new() } else { video.unwrap_or("none").to_string() };
1800 let tone = planned_tone(&project, &meta, &settings);
1801 let hevc_mode = engine::export::hevc_mode_words(&meta, &settings);
1802 let av1_mode = engine::export::av1_mode_words(&meta, &settings);
1803 (picture, sound, tone, (meta.width, meta.height), hevc_mode, av1_mode)
1804 };
1805 // A `.part` no running job of this server owns was left by a process that was killed
1806 // mid-export. This export is about to write the same name, so it is cleared here, and said.
1807 let stale = stale_part_note(&out);
1808 // The export's own copy of the timeline: a `fit` puts every picture clip on that policy in
1809 // this copy only, and the project keeps its clips.
1810 let (mut project, meta) = s.export_snapshot();
1811 // The export's copy drops the clips outside the range that read an offline file, as the GUI's
1812 // export does (`drop_offline_outside`); the project keeps them.
1813 if let Some(span) = range {
1814 project.drop_offline_outside(span, engine::source_present);
1815 }
1816 let fitted: Option<(FitPolicy, FitOutcome)> = fit.map(|f| (f, fit_picture_clips(&mut project, f)));
1817 // A caption burned where a title sits in the same place, on screen together: named before
1818 // the file is written, since the overlap is in the picture.
1819 let clash = settings.burn_subtitles.as_ref().and_then(|(track, style)| {
1820 let cues = engine::export::burn_cues(&project, *track, meta.frame_rate).ok()?;
1821 let (secs, i) = caption_title_clash(&cues, project.titles(), style.place, meta.frame_rate)?;
1822 Some(clash_note(secs, &project.titles()[i].text, style.place))
1823 });
1824 // An mp4 writes two overlapping cues as one stretch with both lines in it, so the cue
1825 // times in the file are not the timeline's; an mkv keeps each cue. Named here, once.
1826 let overlap = (format.ext() == "mp4")
1827 .then(|| engine::export::overlapping_subtitles(&project, &meta, &settings))
1828 .filter(|names| !names.is_empty())
1829 .map(|names| {
1830 format!(
1831 "overlapping cues are merged in mp4 ({}): where two overlap they show as one cue with both lines; mkv keeps them",
1832 names.join(", ")
1833 )
1834 });
1835 let chroma = chroma_notes(&project, &settings, range);
1836 let sample_rate = s.sample_rate();
1837 // `queue`: behind any job still running or waiting, this one holds its own copy of the
1838 // timeline and starts when they are done (`advance`). With nothing ahead it starts now.
1839 let queued = opt_bool(args, "queue").unwrap_or(false);
1840 let ahead = srv.jobs.iter().position(job_running).map(|i| i + 1);
1841 // A paused queue holds a queued export even with nothing ahead of it.
1842 let paused = srv.queue_paused;
1843 let (handle, pending) = if queued && (ahead.is_some() || paused) {
1844 let frames = settings.range.map_or(project.media_frames(), |(a, b)| b.min(project.media_frames()).saturating_sub(a));
1845 let length_secs = f64::from(frames) / meta.frame_rate;
1846 (None, Some(Box::new(Pending { project, meta, settings: settings.clone(), sample_rate, length_secs })))
1847 } else {
1848 (Some(engine::export::start(project, meta, &out, &settings, sample_rate)), None)
1849 };
1850 let waiting = pending.is_some();
1851
1852 let when = match range {
1853 Some((a, b)) => format!("range {} to {}", tc(a, fps), tc(b, fps)),
1854 None if media < end => format!("whole timeline, to {}", tc(media, fps)),
1855 None => "whole timeline".to_string(),
1856 };
1857 let job = srv.jobs.len() + 1;
1858 srv.jobs.push(Job {
1859 out: out.clone(),
1860 picture: picture.clone(),
1861 format,
1862 handle,
1863 pending,
1864 started: Instant::now(),
1865 outcome: None,
1866 measured: None,
1867 });
1868
1869 let captions = burned.map_or_else(String::new, |t| format!("; captions burned (track {t})"));
1870 let tone_note = tone.filter(|_| !sound_only).map(|t| format!(", picture: {t}")).unwrap_or_default();
1871 // The size named only when it differs from the project's: the reply says what the file is.
1872 let size_note = size.map_or_else(String::new, |(w, h)| {
1873 format!("; size {w}x{h} (project {}x{} kept)", project_size.0, project_size.1)
1874 });
1875 // The fit named with the lanes it went to: this export's copy only, the project's clips keep
1876 // theirs. Overlays keep their own fit and aspect, and the reply says so.
1877 let fit_note = fitted.as_ref().map_or_else(String::new, |(f, outcome)| fit_words(*f, outcome));
1878 let words = av_words(format, &picture, sound);
1879 let preset_note = preset.map_or_else(String::new, |p| format!("; preset {}", p.id));
1880 let verb = if waiting { "queued" } else { "started" };
1881 let mut text = format!("job:{job} {verb} → {} ({when}); {words}{captions}{tone_note}{size_note}{fit_note}{preset_note}{loudness_note}", out.display());
1882 if waiting && paused {
1883 text.push_str("\nWaiting: the export queue is paused, so this one starts only when export_queue {action:\"start\"} is sent, from the timeline as it is now (later edits do not change it). export_status shows the queue; export_cancel with its job removes it.");
1884 } else if waiting {
1885 text.push_str(&format!(
1886 "\nWaiting: it starts when job:{} and every export queued before it have finished, from the timeline as it is now (later edits do not change it). export_status shows it as waiting; export_cancel with its job removes it.",
1887 ahead.unwrap_or(1)
1888 ));
1889 }
1890 // An HEVC or AV1 export says in one line which encoder codes it and at what rate or quality.
1891 let seat = match picture.as_str() {
1892 p if p.starts_with("HW") => "hardware",
1893 NO_HW_SEAT => "no hardware",
1894 _ => "software",
1895 };
1896 if let Some(mode) = &hevc_mode {
1897 text.push_str(&format!("\nHEVC: {seat} encoder, {mode}"));
1898 }
1899 if let Some(mode) = &av1_mode {
1900 text.push_str(&format!("\nAV1: {seat} encoder, {mode}"));
1901 }
1902 if let (Some(q), false) = (qp, format.is_hevc() || format.is_av1()) {
1903 text.push_str(&format!("\nH.264: {seat} encoder, constant QP {q}"));
1904 }
1905 if !waiting { text.push_str("\nThe export keeps running while you do other things; if the client only closes this server's input it finishes before the server exits, but if the server is stopped by a signal (as most clients do when they quit) it is cancelled and its partial file removed — poll export_status until it finishes."); }
1906 if !sub_note.is_empty() {
1907 text.push('\n');
1908 text.push_str(&sub_note);
1909 }
1910 // A picture-less mp4 is the sound alone and drops the captions: said first, before the job.
1911 if let Some(lead) = &lead {
1912 text = format!("{lead}\n{text}");
1913 }
1914 for note in anchor_note
1915 .iter()
1916 .chain(stale.iter())
1917 .chain(warning.iter())
1918 .chain(captions_note.iter())
1919 .chain(range_note.iter())
1920 .chain(glyph_note.iter())
1921 .chain(clash.iter())
1922 .chain(overlap.iter())
1923 .chain(chroma.iter())
1924 .chain(chapter_note.iter())
1925 .chain(depth_note.iter())
1926 {
1927 text.push('\n');
1928 text.push_str(note);
1929 }
1930 Reply::ok(text).with(json!({
1931 "job": job,
1932 "queued": waiting,
1933 "out": out.display().to_string(),
1934 "size": size.map(|(w, h)| format!("{w}x{h}")),
1935 "preset": preset.map(|p| p.id),
1936 "fit": fitted.as_ref().map(|(f, _)| if *f == FitPolicy::Fill { "fill" } else { "fit" }),
1937 "captions_burned": burned,
1938 "warning": warning,
1939 "chapters": chapters_written,
1940 "bit_depth": depth.map(|(ten, _)| if ten { 10 } else { 8 }),
1941 }))
1942}
1943
1944/// Whether the format's sound is AAC, the only one that codes above 320 kbps.
1945fn codes_aac(format: Format) -> bool {
1946 matches!(format, Format::Mp4 | Format::Av1 | Format::Av1Mp4 | Format::Hevc | Format::HevcMp4 | Format::M4a)
1947}
1948
1949/// Whether any picture source the timeline reads is 10-bit: the same test the engine's AV1
1950/// seat makes ([`engine::export`]'s `av1_ten_bit`). Still images have no bit depth to read.
1951fn source_ten_bit(s: &PlaybackSession) -> bool {
1952 s.sources()
1953 .iter()
1954 .filter(|src| !engine::is_image(&src.path))
1955 .any(|src| Demuxer::open(&src.path).is_ok_and(|(_, d)| d.bit_depth() == 10))
1956}
1957
1958/// The reply's words for an export `fit`: which lanes' full-frame clips it put on the policy, and
1959/// that the overlays kept their own aspect. `fill` on V1 (1 clip); overlays keep their own aspect.
1960fn fit_words(fit: FitPolicy, outcome: &FitOutcome) -> String {
1961 let word = if fit == FitPolicy::Fill { "fill" } else { "fit" };
1962 let on = if outcome.lanes.is_empty() {
1963 "no full-frame picture clip".to_string()
1964 } else {
1965 let lanes: Vec<String> = outcome
1966 .lanes
1967 .iter()
1968 .map(|(lane, n)| format!("{} ({n} clip{})", lane.label(), if *n == 1 { "" } else { "s" }))
1969 .collect();
1970 format!("on {}", lanes.join(", "))
1971 };
1972 let overlays = if outcome.overlays > 0 { "; overlays keep their own aspect" } else { "" };
1973 format!("; fit {word} {on}{overlays}")
1974}
1975
1976/// The frame the picture and the sound end at, titles included: where a whole-timeline
1977/// export stops. The timeline's own end also counts captions, which can run past it.
1978fn media_end(s: &PlaybackSession) -> u32 {
1979 let clips = s
1980 .lanes()
1981 .into_iter()
1982 .filter(|l| l.kind != LaneKind::Subtitle)
1983 .filter_map(|l| s.lane_clips(l).iter().map(|c| c.end()).max())
1984 .max()
1985 .unwrap_or(0);
1986 let titles = s.titles().iter().map(|t| t.end()).max().unwrap_or(0);
1987 clips.max(titles)
1988}
1989
1990/// One line per distinct video source the export reads (a clip on a video lane that
1991/// overlaps `range`, or anywhere on the timeline when there is none), naming the chroma
1992/// the engine reduces on the way out, e.g. `src:2 clip444.webm: VP9 4:4:4 source: chroma
1993/// reduced to 4:2:0 for export`. Each source is opened once; one that will not open, a
1994/// still and a sound file are skipped without a word.
1995fn chroma_notes(project: &engine::project::Project, settings: &ExportSettings, range: Option<(u32, u32)>) -> Vec<String> {
1996 let (lo, hi) = range.unwrap_or((0, u32::MAX));
1997 let used: std::collections::BTreeSet<usize> = project
1998 .lanes()
1999 .into_iter()
2000 .filter(|l| l.kind == LaneKind::Video)
2001 .flat_map(|lane| project.lane(lane).iter().filter(|c| c.start < hi && c.end() > lo).map(|c| c.source).collect::<Vec<_>>())
2002 .collect();
2003 used.into_iter()
2004 .filter_map(|i| {
2005 let source = project.sources().get(i)?;
2006 if engine::is_image(&source.path) || engine::is_audio(&source.path) {
2007 return None;
2008 }
2009 let (meta, demux) = Demuxer::open(&source.path).ok()?;
2010 let words = chroma_reduction_words(meta.codec, demux.chroma()?, settings)?;
2011 let name = source.path.file_name().map_or_else(|| source.path.display().to_string(), |n| n.to_string_lossy().into_owned());
2012 Some(format!("src:{i} {name}: {words}"))
2013 })
2014 .collect()
2015}
2016
2017/// A frame count as seconds to the millisecond, the figure a reply's `(n.nnns)` shows, e.g. `18.000`.
2018fn secs(frames: u32, fps: f64) -> String {
2019 format!("{:.3}", f64::from(frames) / fps)
2020}
2021
2022/// Whether a job is still writing: no outcome recorded and the encoder not yet finished.
2023pub fn job_running(job: &Job) -> bool {
2024 job.outcome.is_none() && !job.is_finished()
2025}
2026
2027/// Moves the queue on: a waiting job whose cancel arrived is settled by `Job::cancel`; when no
2028/// worker is running, the first waiting job starts from its own copy of the timeline. One encode
2029/// at a time. A paused queue (`export_queue {action:"pause"}`) starts nothing new. Called on every
2030/// server tick, so a queue drains with no client polling.
2031pub fn advance(srv: &mut Server) {
2032 for job in srv.jobs.iter_mut() {
2033 settle(job);
2034 }
2035 if srv.queue_paused || srv.jobs.iter().any(|j| j.handle.is_some() && job_running(j)) {
2036 return;
2037 }
2038 if let Some(job) = srv.jobs.iter_mut().find(|j| j.outcome.is_none() && j.waiting())
2039 && let Some(p) = job.pending.take()
2040 {
2041 job.handle = Some(engine::export::start(p.project, p.meta, &job.out, &p.settings, p.sample_rate));
2042 job.started = Instant::now();
2043 }
2044}
2045
2046/// Records a finished job's outcome, once. Does nothing while it is still running.
2047pub fn settle(job: &mut Job) {
2048 if job.outcome.is_none() && job.is_finished() {
2049 job.outcome = job.result().map(|r| r.map_err(|e| e.to_string()));
2050 }
2051}
2052
2053fn export_status(srv: &mut Server, args: &Value) -> Reply {
2054 // `out` names an export by its file. A job this session started for it is reported as
2055 // its job; any other file is one an earlier session may have written, said as such.
2056 if let Some(raw) = opt_str(args, "out") {
2057 let anchored = match anchor_out(srv, raw) {
2058 Ok((p, _)) => PathBuf::from(p),
2059 Err(e) => return Reply::err(e),
2060 };
2061 return match srv.jobs.iter().position(|j| j.out == anchored) {
2062 Some(i) => export_status(srv, &json!({ "job": i + 1 })),
2063 None => Reply::ok(unknown_out_text(&anchored)).with(json!({"jobs": [], "finished": 0})),
2064 };
2065 }
2066 if srv.jobs.is_empty() && args.get("job").is_none() && !srv.queue_paused {
2067 return Reply::ok(
2068 "no exports in this session — export_start makes one. An export from an earlier session is not tracked here: pass out (its file path) to see whether its file is there",
2069 )
2070 .with(json!({"jobs": [], "finished": 0}));
2071 }
2072 // The jobs this poll measured: their true-peak warning is said on this poll, and only here.
2073 let mut measured_now = Vec::new();
2074 // The master limiter as it stands, so the advice never repeats the ceiling the project already holds.
2075 let limiter = srv.session.as_ref().map(|s| s.limiter()).filter(|l| l.on).map(|l| l.ceiling_db);
2076 for (i, job) in srv.jobs.iter_mut().enumerate() {
2077 settle(job);
2078 // Measured once, from the written file: the mix's own levels are not the file's.
2079 if matches!(job.outcome, Some(Ok(()))) && job.measured.is_none() {
2080 job.measured = Some(file_levels(&job.out));
2081 measured_now.push(i);
2082 }
2083 }
2084 let asked = args.get("job").is_some();
2085 let finished_total = srv.jobs.iter().filter(|j| j.outcome.is_some()).count();
2086 // One job when asked for; otherwise every unfinished job and the last few finished
2087 // ones. A finished job stays in `jobs`, so its result is reported on every poll.
2088 let (ids, hidden): (Vec<usize>, usize) = match opt_u64(args, "job") {
2089 Some(n) => match job_index(srv, n) {
2090 Ok(i) => (vec![i], 0),
2091 Err(e) => {
2092 return Reply::err(format!(
2093 "{e}; an export from an earlier session is not tracked here: pass out (its file path) to see whether its file is there"
2094 ))
2095 }
2096 },
2097 None => {
2098 let unfinished = (0..srv.jobs.len()).filter(|&i| srv.jobs[i].outcome.is_none());
2099 let finished: Vec<usize> = (0..srv.jobs.len())
2100 .filter(|&i| srv.jobs[i].outcome.is_some())
2101 .collect();
2102 let hidden = finished.len().saturating_sub(FINISHED_LISTED);
2103 let mut ids: Vec<usize> = unfinished.chain(finished.into_iter().skip(hidden)).collect();
2104 ids.sort_unstable();
2105 (ids, hidden)
2106 }
2107 };
2108
2109 let mut lines = Vec::new();
2110 let mut rows = Vec::new();
2111 if args.get("job").is_none() {
2112 let unfinished = srv.jobs.len() - finished_total;
2113 lines.push(format!("exports: {unfinished} unfinished, {finished_total} finished"));
2114 if srv.queue_paused {
2115 lines.push("queue paused: queued exports wait until export_queue {action:\"start\"}".to_string());
2116 }
2117 }
2118 for i in ids {
2119 let job = &srv.jobs[i];
2120 let n = i + 1;
2121 let out = job.out.display().to_string();
2122 let elapsed = if job.waiting() { 0.0 } else { job.started.elapsed().as_secs_f64() };
2123 let p = f64::from(job.progress()).clamp(0.0, 1.0);
2124
2125 let (state, line, bytes, eta, error, took) = match &job.outcome {
2126 Some(Ok(())) => {
2127 let bytes = std::fs::metadata(&job.out).map(|m| m.len()).ok();
2128 let size = bytes.map_or_else(|| "size unknown".to_string(), human_bytes);
2129 let took = took_secs(job);
2130 let took_text = took.map_or_else(String::new, |t| format!(" · took {}", took_words(t)));
2131 // An HEVC or AV1 file's average bitrate, measured from the written file.
2132 let rate_text = (job.format.is_hevc() || job.format.is_av1())
2133 .then(|| engine::demux::probe_bitrate(&job.out).total)
2134 .flatten()
2135 .map_or_else(String::new, |bps| format!(" · average bitrate {}", bitrate_text(bps)));
2136 let levels_text = job.measured.flatten().map_or_else(String::new, |m| {
2137 let short = !m.lufs.is_finite() && sound_too_short(&job.out);
2138 format!(" · integrated {} · true peak {}", lufs_text(m.lufs, short), peak_text(m.true_peak_dbtp))
2139 });
2140 (
2141 "done",
2142 format!("job:{n} done — {size} → {out}{took_text}{rate_text}{}{sound_text}{levels_text}", picture_note(job), sound_text = sound_note(job)),
2143 bytes,
2144 None,
2145 None,
2146 took,
2147 )
2148 }
2149 Some(Err(e)) => {
2150 let state = if e.to_ascii_lowercase().contains("cancel") { "cancelled" } else { "failed" };
2151 (state, format!("job:{n} {state} — {e} → {out}"), None, None, Some(e.clone()), None)
2152 }
2153 None => {
2154 let eta = if p > 0.01 { Some(elapsed * (1.0 - p) / p) } else { None };
2155 let enc = match job.encoders() {
2156 Some(_) => format!("{}{}", picture_note(job), sound_note(job)),
2157 None if !job.picture.is_empty() => format!(" · video: {} (planned)", plain_video(job.format, &job.picture)),
2158 None => String::new(),
2159 };
2160 let state = if job.waiting() {
2161 "waiting"
2162 } else if job.is_cancelling() {
2163 "cancelling"
2164 } else if job.is_finished() {
2165 "finishing"
2166 } else {
2167 "running"
2168 };
2169 let eta_text = eta.map_or_else(|| "unknown".to_string(), clock_secs);
2170 let ahead = srv.jobs[..i].iter().filter(|j| j.outcome.is_none()).count();
2171 let line = match job.stage() {
2172 _ if job.waiting() && srv.queue_paused => format!("job:{n} waiting (queue paused) · {ahead} export{} ahead → {out}", if ahead == 1 { "" } else { "s" }),
2173 _ if job.waiting() => format!("job:{n} waiting · {ahead} export{} ahead → {out}", if ahead == 1 { "" } else { "s" }),
2174 // A stage before the encode has its own percent; the encode's ETA
2175 // means nothing yet.
2176 Some((stage, f)) => format!(
2177 "job:{n} {state} · {stage} {:.0}% · elapsed {} · encoding {:.0}%{enc} → {out}",
2178 f * 100.0,
2179 clock_secs(elapsed),
2180 p * 100.0
2181 ),
2182 None => format!(
2183 "job:{n} {state} {:.0}% · elapsed {} · ETA {eta_text}{enc} → {out}",
2184 p * 100.0,
2185 clock_secs(elapsed)
2186 ),
2187 };
2188 (
2189 state,
2190 line,
2191 None,
2192 eta,
2193 None,
2194 None,
2195 )
2196 }
2197 };
2198 lines.push(line);
2199 let levels = job.measured.flatten();
2200 let peak = levels.map(|m| m.true_peak_dbtp);
2201 // Said once per job: on the poll that measured its file, or whenever it is asked for by number.
2202 let lossy = !matches!(job.format, engine::export::Format::Wav | engine::export::Format::Flac);
2203 if (asked || measured_now.contains(&i)) && let Some(w) = peak_warning(n, peak, lossy, limiter) {
2204 lines.push(w);
2205 }
2206 rows.push(json!({
2207 "job": n,
2208 "out": out,
2209 "state": state,
2210 "progress": p,
2211 "stage": job.stage().map(|(name, _)| name),
2212 "stage_progress": job.stage().map(|(_, f)| f),
2213 "elapsed_s": elapsed,
2214 "eta_s": eta,
2215 "duration_s": job.length_secs(),
2216 "took_s": took,
2217 "bytes": bytes,
2218 "error": error,
2219 "integrated_lufs": levels.map(|m| m.lufs),
2220 "true_peak_dbtp": peak,
2221 }));
2222 }
2223 if hidden > 0 {
2224 lines.push(format!(
2225 "({hidden} earlier finished export{} not shown; ask with job:<n>)",
2226 if hidden == 1 { "" } else { "s" }
2227 ));
2228 }
2229 if lines.is_empty() {
2230 lines.push("no exports to show".to_string());
2231 }
2232 Reply::ok(lines.join("\n")).with(json!({ "jobs": rows, "finished": finished_total, "queue_paused": srv.queue_paused }))
2233}
2234
2235/// The true-peak ceiling the advice names: -2 dBTP for a lossy file, whose encoder can add about a
2236/// dB of overshoot above the mix, and -1 dBTP for a lossless one. When the master limiter is already
2237/// on at that ceiling, the call the project has is the one advised, so the advice steps down a dB.
2238fn advised_ceiling(lossy: bool, limiter: Option<f32>) -> f64 {
2239 let base = if lossy { -2.0 } else { -1.0 };
2240 match limiter {
2241 Some(c) if (f64::from(c) - base).abs() < 0.05 => base - 1.0,
2242 _ => base,
2243 }
2244}
2245
2246/// The warning a finished file's true peak earns: over full scale (0 dBTP) the samples clip,
2247/// and the reply names the limiter setting and the gain that stop it; over the ceiling the
2248/// mix is held to, the normalize that holds it. `None` for a file that is under both, or silent.
2249fn peak_warning(n: usize, peak: Option<f64>, lossy: bool, limiter: Option<f32>) -> Option<String> {
2250 let p = peak?;
2251 let ceiling = advised_ceiling(lossy, limiter);
2252 // "The mix clips" only when the peak reads above 0 at the one decimal the reply prints:
2253 // a peak under +0.05 dBTP prints as +0.0 and is the ceiling case, not a clip.
2254 if p >= CLIP_DBTP {
2255 Some(format!(
2256 "warning: job:{n} true peak {p:+.1} dBTP: the mix clips, so the file has samples past full scale. turn the master limiter on with a {ceiling} dBTP ceiling: project_settings {{limiter:{{on:true, ceiling_db:{ceiling}}}}} (the same as the edit op limiter {{on:true, ceiling_db:{ceiling}}}), then export again; or lower the level with lane_gain {{lane, db}}"
2257 ))
2258 } else if p > PEAK_CEILING_DBTP {
2259 Some(format!(
2260 "warning: job:{n} true peak {} dBTP is above the -1 dBTP ceiling (clips on some players) the mix is held to; the file itself (decoded, with the encoder's overshoot) is what was measured. normalize {{target:\"mix\", allow_limiter:true, true_peak:{ceiling}}} holds the mix to the ceiling{}; then export again",
2261 ceiling_figure(p),
2262 if lossy { " (a lossy encode adds up to about 1 dB, so the ceiling sits under -1)" } else { "" }
2263 ))
2264 } else {
2265 None
2266 }
2267}
2268
2269/// `2026-10-17 05:57:03` in local time: when a file was written.
2270fn file_when(t: std::time::SystemTime) -> String {
2271 if t.duration_since(std::time::UNIX_EPOCH).is_err() {
2272 return "before 1970".to_string();
2273 }
2274 let when = chrono::DateTime::<chrono::Local>::from(t);
2275 when.format("%Y-%m-%d %H:%M:%S").to_string()
2276}
2277
2278/// The reply for an `out` that no job of this session writes: whether its file is there,
2279/// its size and when it was written, and that an earlier session's job (whose progress this
2280/// session cannot see) may have written it, or may still be writing its `.part`.
2281fn unknown_out_text(out: &Path) -> String {
2282 let head = format!(
2283 "no export to {} in this session, so its progress is not known here: a job for it ran in an earlier session, or never ran",
2284 out.display()
2285 );
2286 match std::fs::metadata(out) {
2287 Ok(m) => {
2288 let size = human_bytes(m.len());
2289 let when = m.modified().map_or_else(|_| "at an unknown time".to_string(), file_when);
2290 format!("{head}. The file is there: {size}, written {when}")
2291 }
2292 Err(_) => {
2293 let mut part = out.as_os_str().to_owned();
2294 part.push(".part");
2295 if Path::new(&part).exists() {
2296 format!("{head}. No file yet, but a partial {} is there: that export is still writing, or was killed", Path::new(&part).display())
2297 } else {
2298 format!("{head}. No file is there at that path")
2299 }
2300 }
2301 }
2302}
2303
2304/// How long a finished export took, from its job's start to the write of its file.
2305/// The file is written last, so its modification time is the finish. `None` when the
2306/// file is gone or the clock went backwards.
2307/// A file's average bitrate in bits a second, in the words a reply uses: `4.00 Mb/s`, or `850 kb/s` under a megabit.
2308fn bitrate_text(bps: u64) -> String {
2309 let kbps = bps / 1000;
2310 if kbps >= 1000 {
2311 format!("{:.2} Mb/s", kbps as f64 / 1000.0)
2312 } else {
2313 format!("{kbps} kb/s")
2314 }
2315}
2316
2317fn took_secs(job: &Job) -> Option<f64> {
2318 let finished = std::fs::metadata(&job.out).ok()?.modified().ok()?;
2319 let started = std::time::SystemTime::now().checked_sub(job.started.elapsed())?;
2320 finished.duration_since(started).ok().map(|d| d.as_secs_f64())
2321}
2322
2323fn export_cancel(srv: &mut Server, args: &Value) -> Reply {
2324 if opt_bool(args, "all").unwrap_or(false) {
2325 // The GUI queue's Cancel all: every unfinished job is cancelled through the same per-job cancel.
2326 let open: Vec<usize> = srv.jobs.iter().enumerate().filter(|(_, j)| j.outcome.is_none() && !j.is_finished()).map(|(i, _)| i).collect();
2327 if open.is_empty() {
2328 return Reply::ok("no export is unfinished: nothing to cancel");
2329 }
2330 let waiting = open.iter().filter(|&&i| srv.jobs[i].waiting()).count();
2331 for i in &open {
2332 srv.jobs[*i].cancel();
2333 }
2334 return Reply::ok(format!(
2335 "cancelled {} export{}: {waiting} waiting removed, {} running stopped (partial files deleted)",
2336 open.len(),
2337 if open.len() == 1 { "" } else { "s" },
2338 open.len() - waiting
2339 ));
2340 }
2341 let Some(n) = opt_u64(args, "job") else {
2342 return Reply::err("export_cancel needs `job`: the number from export_start (job:<n>), or all: true");
2343 };
2344 let i = match job_index(srv, n) {
2345 Ok(i) => i,
2346 Err(e) => return Reply::err(e),
2347 };
2348 let job = &mut srv.jobs[i];
2349 if job.outcome.is_some() || job.is_finished() {
2350 return Reply::ok(format!("job:{n} already finished — nothing to cancel"));
2351 }
2352 if job.waiting() {
2353 job.cancel();
2354 return Reply::ok(format!("job:{n} removed from the queue — it was waiting and never started"));
2355 }
2356 job.cancel();
2357 Reply::ok(format!(
2358 "job:{n} cancel requested — the worker stops at its next checkpoint and deletes the partial file"
2359 ))
2360}
2361
2362#[cfg(test)]
2363mod tests {
2364 use super::*;
2365 use crate::testutil::TestDir;
2366 use std::time::{Duration, Instant};
2367
2368 #[test]
2369 fn hardware_av1_is_refused_but_auto_and_software_are_not() {
2370 // The GPU crash: hardware AV1 (and WebM, which the engine seats as AV1) is refused.
2371 assert!(hw_av1_refused(Format::Av1, EncoderSeat::Hardware));
2372 assert!(hw_av1_refused(Format::Av1Mp4, EncoderSeat::Hardware));
2373 assert!(hw_av1_refused(Format::Webm, EncoderSeat::Hardware));
2374 // `auto` never reaches the GPU for AV1 (the engine seats it in software), and the
2375 // software seat is always allowed. Hardware H.264 is not this rule's business.
2376 assert!(!hw_av1_refused(Format::Av1, EncoderSeat::Auto));
2377 assert!(!hw_av1_refused(Format::Av1Mp4, EncoderSeat::Auto));
2378 assert!(!hw_av1_refused(Format::Av1, EncoderSeat::Software));
2379 assert!(!hw_av1_refused(Format::Mp4, EncoderSeat::Hardware));
2380 }
2381
2382 #[test]
2383 fn picture_label_names_the_engine_seat_then_the_plan_and_skips_audio_only() {
2384 let measured = Some("HW encode (GPU) · AAC · SW encode (ec-aac)".to_string());
2385 assert_eq!(picture_label(measured, "SW encode (rav1e)", Format::Mp4), " · video: H.264 (hardware)");
2386 assert_eq!(picture_label(None, "SW encode (ec-h264)", Format::Mp4), " · video: H.264 (software)");
2387 assert_eq!(picture_label(Some("copy · AAC".into()), "SW encode (ec-h264)", Format::Mp4), " · video: H.264 (copy)");
2388 assert_eq!(picture_label(None, "", Format::Mp4), "");
2389 assert_eq!(picture_label(None, "SW encode (rav1e)", Format::Webm), " · video: AV1 (software)");
2390 }
2391
2392 /// The codec and container words a start reply and a status line use, with no engine labels left.
2393 #[test]
2394 fn export_words_are_plain() {
2395 assert_eq!(
2396 av_words(Format::Webm, "SW encode (rav1e)", "Opus · SW encode (ec-opus)"),
2397 "video: AV1 (software), audio: Opus, container: WebM"
2398 );
2399 assert_eq!(
2400 av_words(Format::Mp4, "SW encode (ec-h264)", "AAC · SW encode (ec-aac)"),
2401 "video: H.264 (software), audio: AAC, container: MP4"
2402 );
2403 assert_eq!(av_words(Format::Mp4, "copy (source packets)", "AAC copy"), "video: H.264 (copy), audio: AAC (copy), container: MP4");
2404 assert_eq!(av_words(Format::Wav, "", "PCM · SW (hound)"), "audio: PCM, container: WAV");
2405 assert_eq!(av_words(Format::Gif, "", ""), "no sound, container: GIF");
2406 assert_eq!(av_words(Format::PngSequence, "", ""), "no sound, container: PNG folder");
2407 assert_eq!(measured_sound(Some("HW encode (GPU) · AAC · SW encode (ec-aac)")).as_deref(), Some("AAC"));
2408 assert_eq!(measured_sound(Some("SW encode (ec-h264)")), None);
2409 assert_eq!(measured_sound(None), None);
2410 assert_eq!(plain_audio("no sound to write"), "none");
2411 }
2412
2413 /// An audio-only job (an m4a, or an mp4 with no picture) reports its sound from the line's
2414 /// first part, which is the codec: `AAC · SW encode (ec-aac)` is the AAC the engine wrote
2415 /// by re-encoding, and `AAC copy` the source's own packets. A job with a picture still skips
2416 /// its picture seat to reach the sound.
2417 #[test]
2418 fn an_audio_only_job_reports_its_sound_from_the_codec_part() {
2419 assert_eq!(sound_words(true, Some("AAC · SW encode (ec-aac)")).as_deref(), Some("AAC"));
2420 assert_eq!(sound_words(true, Some("AAC copy")).as_deref(), Some("AAC (copy)"));
2421 assert_eq!(sound_words(true, Some("PCM · SW (hound)")).as_deref(), Some("PCM"));
2422 assert_eq!(sound_words(true, Some("no sound to write")).as_deref(), Some("none"));
2423 assert_eq!(sound_words(true, None), None);
2424 assert_eq!(sound_words(false, Some("SW encode (ec-h264) · AAC · SW encode (ec-aac)")).as_deref(), Some("AAC"));
2425 assert_eq!(sound_words(false, Some("SW encode (ec-h264)")), None);
2426 }
2427
2428 /// An Auto HEVC export says in its start reply which encoder codes it and in which GOP
2429 /// mode: I+P is software at its rate (or constant quality), intra-only says so.
2430 #[test]
2431 fn auto_hevc_start_line_names_the_seat_and_the_gop_mode() {
2432 engine::ao::set_silent_output();
2433 let root = env!("CARGO_MANIFEST_DIR");
2434 let src = format!("{root}/../../assets/test_av.mp4");
2435 let dir = scratch("hevc-start-line");
2436 let mut srv = Server::new();
2437 srv.session = Some(engine::PlaybackSession::open(Path::new(&src)).expect("open the source"));
2438 let range = json!({"from": 0, "to": 1});
2439
2440 let at_rate = export_start(&mut srv, &json!({
2441 "out": dir.join("rate.mp4").display().to_string(), "format": "hevc-mp4", "range": range, "bitrate_kbps": 4000
2442 }));
2443 assert!(!at_rate.is_error, "{}", at_rate.text);
2444 assert!(
2445 at_rate.text.contains("\nHEVC: software encoder, I+P GOP (1 s keyframes), 4 Mb/s")
2446 || at_rate.text.contains("\nHEVC: hardware encoder, I+P GOP (1 s keyframes), 4 Mb/s"),
2447 "the I+P line names the seat, the GOP and the rate: {}",
2448 at_rate.text
2449 );
2450
2451 let quality = export_start(&mut srv, &json!({
2452 "out": dir.join("quality.mp4").display().to_string(), "format": "hevc-mp4", "range": range
2453 }));
2454 assert!(!quality.is_error, "{}", quality.text);
2455 assert!(
2456 quality.text.contains("\nHEVC: software encoder, I+P GOP (1 s keyframes), constant quality")
2457 || quality.text.contains("\nHEVC: hardware encoder, I+P GOP (1 s keyframes), constant quality"),
2458 "the automatic row says constant quality: {}",
2459 quality.text
2460 );
2461
2462 // Auto takes the GPU for intra-only where there is one, so either seat is right here.
2463 let intra = export_start(&mut srv, &json!({
2464 "out": dir.join("intra.mp4").display().to_string(), "format": "hevc-mp4", "range": range, "intra_only": true
2465 }));
2466 assert!(!intra.is_error, "{}", intra.text);
2467 assert!(
2468 intra.text.contains("\nHEVC: software encoder, intra-only")
2469 || intra.text.contains("\nHEVC: hardware encoder, intra-only"),
2470 "intra-only is named with its seat: {}",
2471 intra.text
2472 );
2473 // Let the three jobs finish before the scratch directory goes.
2474 for _ in 0..600 {
2475 if srv.jobs.iter().all(|j| j.is_finished()) { break; }
2476 std::thread::sleep(std::time::Duration::from_millis(50));
2477 }
2478 }
2479
2480 /// A start reply echoes an absolute output path as given, and names the codecs and the
2481 /// container in plain words; the finished job says the same.
2482 #[test]
2483 fn start_reply_echoes_an_absolute_out_in_plain_words() {
2484 engine::ao::set_silent_output();
2485 let root = env!("CARGO_MANIFEST_DIR");
2486 let src = format!("{root}/../../assets/test_seek_chirp.mkv");
2487 let dir = scratch("words-start");
2488 let out = dir.join("highlight.wav");
2489 let mut srv = Server::new();
2490 srv.session = Some(engine::PlaybackSession::open(Path::new(&src)).expect("open the source"));
2491 let started = export_start(&mut srv, &json!({"out": out.display().to_string()}));
2492 assert!(!started.is_error, "{}", started.text);
2493 assert!(started.text.contains(&format!("started → {}", out.display())), "absolute out is echoed: {}", started.text);
2494 assert!(started.text.contains("container: WAV"), "{}", started.text);
2495 assert!(!started.text.contains("SW encode"), "no engine labels in the reply: {}", started.text);
2496 assert!(!started.text.contains("picture:"), "{}", started.text);
2497 let deadline = Instant::now() + Duration::from_secs(120);
2498 while srv.jobs[0].outcome.is_none() {
2499 assert!(Instant::now() < deadline, "export did not finish in 120s");
2500 export_status(&mut srv, &json!({ "job": 1 }));
2501 std::thread::sleep(Duration::from_millis(100));
2502 }
2503 }
2504
2505 /// A PQ (HDR) picture's export names the tone map it will apply, on the start line; a
2506 /// sound-only export names none.
2507 #[test]
2508 fn export_start_names_the_tone_map_of_an_hdr_picture() {
2509 let dir = scratch("tone");
2510 let src = format!("{}/../../assets/test_pq.mp4", env!("CARGO_MANIFEST_DIR"));
2511 let mut srv = Server::new();
2512 srv.session = Some(engine::PlaybackSession::open(Path::new(&src)).expect("open assets/test_pq.mp4"));
2513 let out = dir.join("pq.mp4");
2514 let started = export_start(&mut srv, &json!({"out": out.display().to_string()}));
2515 assert!(!started.is_error, "{}", started.text);
2516 // test_pq.mp4 is 320x240: standard definition, so the file is tagged BT.601.
2517 assert!(started.text.contains("picture: HDR (PQ) source tone-mapped to SDR BT.601"), "{}", started.text);
2518 let _ = export_cancel(&mut srv, &json!({ "job": 1 }));
2519 let wav = dir.join("pq.wav");
2520 let sound = export_start(&mut srv, &json!({"out": wav.display().to_string()}));
2521 assert!(!sound.text.contains("picture:"), "{}", sound.text);
2522 }
2523
2524 /// The chroma note: a 4:4:4 VP9 source is named once in the start reply, with the
2525 /// reduction the engine makes; a 4:2:0 source names nothing.
2526 #[test]
2527 fn export_start_names_the_chroma_reduction_of_a_444_source_once() {
2528 let dir = scratch("chroma");
2529 let src = dir.join("clip444.webm");
2530 let made = std::process::Command::new("ffmpeg")
2531 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=320x240:d=2"])
2532 .args(["-c:v", "libvpx-vp9", "-pix_fmt", "yuv444p", "-t", "2"])
2533 .arg(&src)
2534 .output()
2535 .expect("ffmpeg runs");
2536 assert!(made.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&made.stderr));
2537 let range = json!({"from": 0, "to": 1});
2538 let mut srv = Server::new();
2539 srv.session = Some(engine::PlaybackSession::open(&src).expect("open the 4:4:4 clip"));
2540 let started = export_start(&mut srv, &json!({"out": dir.join("c444.mp4").display().to_string(), "range": range}));
2541 assert!(!started.is_error, "{}", started.text);
2542 let note = "src:0 clip444.webm: VP9 4:4:4 source: chroma reduced to 4:2:0 for export";
2543 assert_eq!(started.text.matches(note).count(), 1, "{}", started.text);
2544 let _ = export_cancel(&mut srv, &json!({ "job": 1 }));
2545
2546 let mut plain = Server::new();
2547 plain.session = Some(engine::PlaybackSession::open(Path::new(&format!("{}/../../assets/test_speed_sync.mp4", env!("CARGO_MANIFEST_DIR")))).expect("open a 4:2:0 clip"));
2548 let quiet = export_start(&mut plain, &json!({"out": dir.join("c420.mp4").display().to_string(), "range": range}));
2549 assert!(!quiet.is_error, "{}", quiet.text);
2550 assert!(!quiet.text.contains("chroma reduced"), "{}", quiet.text);
2551 let _ = export_cancel(&mut plain, &json!({ "job": 1 }));
2552 }
2553
2554 /// The size words: WIDTHxHEIGHT and NNNp (16:9 at that height), even sides, within the
2555 /// engine's ceiling. Anything else is refused by name.
2556 #[test]
2557 fn size_reads_widths_by_height_and_refuses_what_no_picture_can_be() {
2558 let size = |v: Value| parse_size(&json!({ "size": v }));
2559 assert_eq!(parse_size(&json!({})), Ok(None));
2560 assert_eq!(size(json!("1280x720")), Ok(Some((1280, 720))));
2561 assert_eq!(size(json!(" 854X480 ")), Ok(Some((854, 480))));
2562 assert_eq!(size(json!("720p")), Ok(Some((1280, 720))));
2563 assert_eq!(size(json!("1080p")), Ok(Some((1920, 1080))));
2564 assert_eq!(size(json!("2160p")), Ok(Some((3840, 2160))));
2565 assert_eq!(size(json!("480p")), Ok(Some((854, 480))));
2566 for bad in ["1281x720", "1280x721", "0x720", "8192x4320", "720", "wide", "x720", "-2x720"] {
2567 let e = size(json!(bad)).expect_err(bad);
2568 assert!(e.contains("size"), "{bad}: {e}");
2569 }
2570 assert!(size(json!(7680)).is_err(), "a number is not a size");
2571 assert!(size(json!("7682p")).is_err(), "past the engine's ceiling");
2572 }
2573
2574 /// A `size` draws the file at that size and leaves the project alone: the reply names both,
2575 /// the project's resolution stays where it was, and the export's own settings carry it.
2576 #[test]
2577 fn export_size_is_the_files_canvas_and_the_project_keeps_its_own() {
2578 let dir = scratch("size");
2579 let src = format!("{}/../../assets/test_pq.mp4", env!("CARGO_MANIFEST_DIR"));
2580 let mut srv = Server::new();
2581 srv.session = Some(engine::PlaybackSession::open(Path::new(&src)).expect("open assets/test_pq.mp4"));
2582 let before = srv.session.as_ref().expect("a session").export_snapshot().1;
2583 let out = dir.join("small.mp4");
2584 let started = export_start(&mut srv, &json!({"out": out.display().to_string(), "size": "160x120"}));
2585 assert!(!started.is_error, "{}", started.text);
2586 assert!(started.text.contains("size 160x120 (project 320x240 kept)"), "{}", started.text);
2587 assert_eq!(started.structured.as_ref().and_then(|v| v.get("size")), Some(&json!("160x120")));
2588 let after = srv.session.as_ref().expect("a session").export_snapshot().1;
2589 assert_eq!((before.width, before.height), (after.width, after.height), "the project is not resized");
2590 let refused = export_start(&mut srv, &json!({"out": dir.join("odd.mp4").display().to_string(), "size": "161x120"}));
2591 assert!(refused.is_error && refused.text.contains("even"), "{}", refused.text);
2592 let _ = export_cancel(&mut srv, &json!({ "job": 1 }));
2593 }
2594
2595 /// `export_presets` lists every row of the engine's table, and `export_start { preset }` fills
2596 /// the settings from one while an explicit argument overrides it.
2597 #[test]
2598 fn export_presets_list_and_fill_export_start() {
2599 let mut srv = Server::new();
2600 let listed = export_presets(&mut srv, &json!({}));
2601 assert!(!listed.is_error, "{}", listed.text);
2602 let rows = listed.structured.as_ref().expect("structured")["presets"].as_array().expect("rows").clone();
2603 assert_eq!(rows.len(), engine::export_presets::presets().len());
2604 let podcast = rows.iter().find(|r| r["id"] == "podcast").expect("podcast row");
2605 assert_eq!(podcast["format"], "m4a");
2606 assert_eq!(podcast["loudness"]["lufs"], -16.0);
2607 assert_eq!(podcast["loudness"]["true_peak_dbtp"], -1.0);
2608 let archive = rows.iter().find(|r| r["id"] == "archive").expect("archive row");
2609 assert_eq!(archive["bit_depth"], 10);
2610 assert_eq!(archive["format"], "av1");
2611
2612 let dir = scratch("preset");
2613 let src = format!("{}/../../assets/test_pq.mp4", env!("CARGO_MANIFEST_DIR"));
2614 srv.session = Some(engine::PlaybackSession::open(Path::new(&src)).expect("open assets/test_pq.mp4"));
2615 let unknown = export_start(&mut srv, &json!({"out": dir.join("x.mp4").display().to_string(), "preset": "nope"}));
2616 assert!(unknown.is_error && unknown.text.contains("youtube_1080p"), "{}", unknown.text);
2617
2618 let out = dir.join("short.mp4");
2619 let started = export_start(&mut srv, &json!({"out": out.display().to_string(), "preset": "shorts_reels"}));
2620 assert!(!started.is_error, "{}", started.text);
2621 assert!(started.text.contains("size 1080x1920"), "{}", started.text);
2622 assert!(started.text.contains("preset shorts_reels"), "{}", started.text);
2623 let _ = export_cancel(&mut srv, &json!({ "job": 1 }));
2624
2625 let out = dir.join("short2.mp4");
2626 let started = export_start(&mut srv, &json!({"out": out.display().to_string(), "preset": "shorts_reels", "size": "160x120"}));
2627 assert!(!started.is_error, "{}", started.text);
2628 assert_eq!(started.structured.as_ref().and_then(|v| v.get("size")), Some(&json!("160x120")));
2629 let _ = export_cancel(&mut srv, &json!({ "job": 2 }));
2630
2631 let out = dir.join("pod.m4a");
2632 let started = export_start(&mut srv, &json!({"out": out.display().to_string(), "preset": "podcast"}));
2633 assert!(!started.is_error, "{}", started.text);
2634 assert_eq!(started.structured.as_ref().and_then(|v| v.get("preset")), Some(&json!("podcast")));
2635 let _ = export_cancel(&mut srv, &json!({ "job": 3 }));
2636 }
2637
2638 /// A Matroska export names the sound it will get: a 44.1 kHz AAC source is mixed to AAC, the
2639 /// codec its done line reports, rather than the Opus-or-AAC the start line used to say.
2640 #[test]
2641 fn a_matroska_start_line_names_aac_for_a_44k_mix() {
2642 let dir = scratch("mkv-start");
2643 let src = format!("{}/../../assets/test_av1.mkv", env!("CARGO_MANIFEST_DIR"));
2644 let mut srv = Server::new();
2645 srv.session = Some(engine::PlaybackSession::open(Path::new(&src)).expect("open assets/test_av1.mkv"));
2646 let started = export_start(&mut srv, &json!({"out": dir.join("av1.mkv").display().to_string()}));
2647 assert!(!started.is_error, "{}", started.text);
2648 assert!(started.text.contains("audio: AAC, container: Matroska"), "{}", started.text);
2649 assert!(!started.text.contains("as the mix decides"), "{}", started.text);
2650 let _ = export_cancel(&mut srv, &json!({ "job": 1 }));
2651 }
2652
2653 /// duration_s is the length of the file the export writes (its range, here one second), known
2654 /// from the start and the same on every poll. It is not how long the encode took, which is
2655 /// `took_s`: a 45 s timeline that encoded in 20 s reported 19.8 before this.
2656 #[test]
2657 fn export_status_duration_is_the_files_length_not_the_encode_time() {
2658 engine::ao::set_silent_output();
2659 let mut srv = Server::new();
2660 srv.session = Some(engine::PlaybackSession::open(small_clip()).expect("open assets/test_speed_sync.mp4"));
2661 let dir = scratch("duration");
2662 let out = dir.join("one.mp4");
2663 let args = json!({ "out": out.display().to_string(), "format": "mp4", "range": { "from": 0, "to": 1 } });
2664 assert!(!export_start(&mut srv, &args).is_error);
2665 let deadline = Instant::now() + Duration::from_secs(120);
2666 loop {
2667 let st = export_status(&mut srv, &json!({ "job": 1 }));
2668 if srv.jobs[0].outcome.is_some() {
2669 break;
2670 }
2671 assert!(Instant::now() < deadline, "export did not finish in 120s: {}", st.text);
2672 std::thread::sleep(Duration::from_millis(200));
2673 }
2674 let st = export_status(&mut srv, &json!({ "job": 1 }));
2675 let row = &st.structured.as_ref().unwrap()["jobs"][0];
2676 let duration = row["duration_s"].as_f64().expect("duration_s is a number");
2677 assert!((duration - 1.0).abs() < 0.05, "a one-second range: {duration}");
2678 assert!(row["took_s"].as_f64().is_some(), "the encode time is still reported: {row}");
2679 }
2680
2681 /// The three picture formats write their files through `export_start`: a numbered PNG run into
2682 /// the folder named, a PNG still of the frame at the range's start, and a GIF whose width and
2683 /// rate are the arguments given; a GIF past 720 px is refused by name.
2684 #[test]
2685 fn the_picture_formats_write_their_files() {
2686 let dir = scratch("pictures");
2687 let src = format!("{}/../../assets/test_25fps.mp4", env!("CARGO_MANIFEST_DIR"));
2688 let mut srv = Server::new();
2689 srv.session = Some(engine::PlaybackSession::open(Path::new(&src)).expect("open assets/test_25fps.mp4"));
2690
2691 let folder = dir.join("run");
2692 let started = export_start(&mut srv, &json!({"out": folder.display().to_string(), "format": "png_sequence", "range": { "from": "0f", "to": "25f" }}));
2693 assert!(!started.is_error, "{}", started.text);
2694 finish_job(&mut srv, 1);
2695 let mut names: Vec<String> = std::fs::read_dir(&folder)
2696 .expect("the folder the run is written into")
2697 .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
2698 .collect();
2699 names.sort();
2700 assert_eq!(names.len(), 25, "{names:?}");
2701 assert_eq!(names[0], "run_00001.png");
2702
2703 let still = dir.join("poster.png");
2704 let started = export_start(&mut srv, &json!({"out": still.display().to_string(), "range": { "from": "10f", "to": "11f" }}));
2705 assert!(!started.is_error, "{}", started.text);
2706 finish_job(&mut srv, 2);
2707 assert!(still.exists(), "the still was written");
2708
2709 let gif = dir.join("clip.gif");
2710 let started = export_start(&mut srv, &json!({"out": gif.display().to_string(), "range": { "from": "0f", "to": "25f" }, "gif_width": 320, "gif_fps": 10, "gif_loop": false}));
2711 assert!(!started.is_error, "{}", started.text);
2712 finish_job(&mut srv, 3);
2713 let bytes = std::fs::read(&gif).expect("the GIF was written");
2714 assert!(bytes.starts_with(b"GIF89a"), "a GIF file");
2715 // The logical screen's width is the header's little-endian u16 at byte 6.
2716 assert_eq!(u16::from_le_bytes([bytes[6], bytes[7]]), 320, "the width asked for");
2717
2718 // Refused by the engine when the export runs, so the job starts and then fails by name.
2719 let wide = export_start(&mut srv, &json!({"out": dir.join("wide.gif").display().to_string(), "gif_width": 1280}));
2720 assert!(!wide.is_error, "{}", wide.text);
2721 let deadline = Instant::now() + Duration::from_secs(120);
2722 while srv.jobs[3].outcome.is_none() {
2723 assert!(Instant::now() < deadline, "the refused GIF did not finish");
2724 export_status(&mut srv, &json!({ "job": 4 }));
2725 std::thread::sleep(Duration::from_millis(50));
2726 }
2727 let outcome = format!("{:?}", srv.jobs[3].outcome);
2728 assert!(outcome.contains("pixels wide"), "{outcome}");
2729 assert!(!dir.join("wide.gif").exists(), "a refused GIF leaves no file");
2730 }
2731
2732 /// A fresh folder for one test, removed when the test ends.
2733 fn scratch(name: &str) -> TestDir {
2734 TestDir::new(&format!("export-{name}"))
2735 }
2736
2737 /// The clip the job tests export from: 320x180 rather than the 1280x720
2738 /// `test_av.mp4`. These tests check the job lifecycle, not the picture, and a
2739 /// debug build encodes 16x fewer pixels in this one.
2740 fn small_clip() -> String {
2741 format!("{}/../../assets/test_speed_sync.mp4", env!("CARGO_MANIFEST_DIR"))
2742 }
2743
2744 #[test]
2745 fn format_inference() {
2746 assert_eq!(resolve_out("/x/a.mp4", None).unwrap().1, Format::Mp4);
2747 assert_eq!(resolve_out("/x/a.mkv", None).unwrap().1, Format::Av1);
2748 assert_eq!(resolve_out("/x/a.webm", None).unwrap().1, Format::Webm);
2749 assert_eq!(resolve_out("/x/a.wav", None).unwrap().1, Format::Wav);
2750 assert_eq!(resolve_out("/x/a.flac", None).unwrap().1, Format::Flac);
2751 assert_eq!(resolve_out("/x/a.mp3", None).unwrap().1, Format::Mp3);
2752 assert_eq!(resolve_out("/x/a.ogg", None).unwrap().1, Format::Ogg);
2753 assert_eq!(resolve_out("/x/a.m4a", None).unwrap().1, Format::M4a);
2754 assert_eq!(resolve_out("/x/a", Some("m4a")).unwrap().0, PathBuf::from("/x/a.m4a"));
2755 assert_eq!(format_from_name("M4A"), Some(Format::M4a));
2756 assert_eq!(format_name(Format::M4a), "m4a");
2757 assert_eq!(resolve_out("/x/a.mkv", Some("av1")).unwrap().1, Format::Av1);
2758 assert_eq!(resolve_out("/x/a.mp4", Some("hevc-mp4")).unwrap().1, Format::HevcMp4);
2759 assert_eq!(
2760 resolve_out("/x/a", Some("webm")).unwrap().0,
2761 PathBuf::from("/x/a.webm")
2762 );
2763 assert!(resolve_out("/x/a.mkv", Some("mp4")).is_err());
2764 assert!(resolve_out("/x/a.mp4", Some("av1-mp4")).is_ok());
2765 assert!(resolve_out("/x/a.xyz", None).is_err());
2766 assert!(resolve_out("/x/a", None).is_err());
2767 // A GIF is written now: the name follows the format, and a mismatched extension still refuses.
2768 assert_eq!(resolve_out("/x/a", Some("gif")).unwrap(), (PathBuf::from("/x/a.gif"), Format::Gif));
2769 assert!(resolve_out("/x/a.mp4", Some("gif")).is_err());
2770 }
2771
2772 #[test]
2773 fn prores_hdr_and_sound_depth_arguments_parse_and_name_what_they_are_for() {
2774 let prores = Format::ProRes;
2775 for (name, want) in [
2776 ("proxy", ProResProfile::Proxy),
2777 ("lt", ProResProfile::Lt),
2778 ("standard", ProResProfile::Standard),
2779 ("hq", ProResProfile::Hq),
2780 ("4444", ProResProfile::P4444),
2781 ("4444xq", ProResProfile::P4444Xq),
2782 ] {
2783 assert_eq!(parse_prores_profile(&json!({ "prores_profile": name }), prores), Ok(Some(want)), "{name}");
2784 assert_eq!(prores_name(want), name);
2785 }
2786 assert_eq!(parse_prores_profile(&json!({}), prores), Ok(None));
2787 assert!(parse_prores_profile(&json!({ "prores_profile": "max" }), prores).unwrap_err().contains("4444xq"));
2788 assert!(parse_prores_profile(&json!({ "prores_profile": "hq" }), Format::Mp4).unwrap_err().contains("format prores"));
2789 assert_eq!(parse_hevc_speed(&json!({ "hevc_speed": "fast" }), Format::Hevc), Ok(Some(HevcSpeed::Fast)));
2790 assert_eq!(parse_hevc_speed(&json!({}), Format::Hevc), Ok(None));
2791 assert!(parse_hevc_speed(&json!({ "hevc_speed": "fast" }), Format::Mp4).unwrap_err().contains("hevc"));
2792 assert!(parse_hevc_speed(&json!({ "hevc_speed": "max" }), Format::Hevc).unwrap_err().contains("faster"));
2793
2794 assert_eq!(parse_hdr(&json!({ "hdr": "pq" }), Format::HevcMp4), Ok(Some(HdrTransfer::Pq)));
2795 assert_eq!(parse_hdr(&json!({ "hdr": "HLG" }), Format::Hevc), Ok(Some(HdrTransfer::Hlg)));
2796 assert_eq!(parse_hdr(&json!({ "hdr": "off" }), Format::Mp4), Ok(Some(HdrTransfer::Sdr)));
2797 assert!(parse_hdr(&json!({ "hdr": "pq" }), Format::Mp4).unwrap_err().contains("hevc"));
2798 assert!(parse_hdr(&json!({ "hdr": "dolby" }), Format::Hevc).is_err());
2799
2800 assert_eq!(parse_sound_bits(&json!({ "audio_bit_depth": 16 }), prores), Ok(Some(16)));
2801 assert_eq!(parse_sound_bits(&json!({ "audio_bit_depth": 24 }), prores), Ok(Some(24)));
2802 assert_eq!(parse_sound_bits(&json!({}), Format::Wav), Ok(None));
2803 assert!(parse_sound_bits(&json!({ "audio_bit_depth": 20 }), prores).is_err());
2804 assert!(parse_sound_bits(&json!({ "audio_bit_depth": 16 }), Format::Wav).is_err());
2805
2806 assert_eq!(format_from_name("prores"), Some(Format::ProRes));
2807 assert_eq!(infer_format("mov"), Some(Format::ProRes));
2808 assert_eq!(resolve_out("/x/a.mov", None).map(|(_, f)| f), Ok(Format::ProRes));
2809 assert!(resolve_out("/x/a.mp4", Some("prores")).is_err(), "prores is written as .mov");
2810 }
2811
2812 #[test]
2813 fn the_prores_and_hdr_presets_are_listed_with_their_settings() {
2814 let rows: Vec<Value> = engine::export_presets::presets().iter().map(preset_json).collect();
2815 let master = rows.iter().find(|r| r["id"] == "archive_prores").expect("prores row");
2816 assert_eq!((master["format"].as_str(), master["prores_profile"].as_str()), (Some("prores"), Some("hq")));
2817 let hdr = rows.iter().find(|r| r["id"] == "hdr10_hevc").expect("hdr row");
2818 assert_eq!((hdr["hdr"].as_str(), hdr["bit_depth"].as_u64()), (Some("pq"), Some(10)));
2819 assert_eq!(rows[0]["hdr"], "off");
2820 }
2821
2822 /// A ProRes export through the tool writes a .mov of ProRes video and PCM sound.
2823 #[test]
2824 fn a_prores_export_writes_a_mov() {
2825 engine::ao::set_silent_output();
2826 let mut srv = Server::new();
2827 srv.session = Some(engine::PlaybackSession::open(small_clip()).expect("open assets/test_speed_sync.mp4"));
2828 let dir = scratch("prores");
2829 let out = dir.join("master.mov");
2830 std::fs::remove_file(&out).ok();
2831 let args = json!({
2832 "out": out.display().to_string(),
2833 "prores_profile": "lt",
2834 "audio_bit_depth": 16,
2835 "seat": "software",
2836 "range": { "from": 0, "to": 1 }
2837 });
2838 let started = export_start(&mut srv, &args);
2839 assert!(!started.is_error, "{}", started.text);
2840 let deadline = Instant::now() + Duration::from_secs(120);
2841 while srv.jobs[0].outcome.is_none() {
2842 let st = export_status(&mut srv, &json!({ "job": 1 }));
2843 assert!(!st.is_error, "{}", st.text);
2844 assert!(Instant::now() < deadline, "export did not finish in 120s: {}", st.text);
2845 std::thread::sleep(Duration::from_millis(200));
2846 }
2847 assert!(matches!(srv.jobs[0].outcome, Some(Ok(()))), "{:?}", srv.jobs[0].outcome);
2848 assert!(std::fs::metadata(&out).expect("output exists").len() > 0);
2849 let probe = std::process::Command::new("ffprobe")
2850 .args(["-v", "error", "-show_entries", "stream=codec_name", "-of", "csv=p=0"])
2851 .arg(&out)
2852 .output();
2853 if let Some(probe) = probe.ok().filter(|p| p.status.success()) {
2854 let names = String::from_utf8_lossy(&probe.stdout).to_string();
2855 assert!(names.contains("prores"), "{names}");
2856 }
2857 }
2858
2859 #[test]
2860 fn overwrite_refused() {
2861 let dir = scratch("overwrite");
2862 let f = dir.join("exists.mp4");
2863 std::fs::write(&f, b"x").unwrap();
2864 assert!(check_out(&f, false).unwrap_err().contains("overwrite"));
2865 assert!(check_out(&f, true).is_ok());
2866 assert!(check_out(&dir.join("missing").join("a.mp4"), false)
2867 .unwrap_err()
2868 .contains("does not exist"));
2869 }
2870
2871 #[test]
2872 fn short_real_export() {
2873 engine::ao::set_silent_output();
2874 let src = small_clip();
2875 let session = engine::PlaybackSession::open(&src).expect("open assets/test_speed_sync.mp4");
2876 let mut srv = Server::new();
2877 srv.session = Some(session);
2878
2879 let dir = scratch("real");
2880 let out = dir.join("short.mp4");
2881 std::fs::remove_file(&out).ok();
2882 let args = json!({
2883 "out": out.display().to_string(),
2884 "format": "mp4",
2885 "range": { "from": 0, "to": 1 }
2886 });
2887 let started = export_start(&mut srv, &args);
2888 assert!(!started.is_error, "{}", started.text);
2889
2890 let deadline = Instant::now() + Duration::from_secs(120);
2891 loop {
2892 let st = export_status(&mut srv, &json!({ "job": 1 }));
2893 assert!(!st.is_error, "{}", st.text);
2894 if srv.jobs[0].outcome.is_some() {
2895 break;
2896 }
2897 assert!(Instant::now() < deadline, "export did not finish in 120s: {}", st.text);
2898 std::thread::sleep(Duration::from_millis(200));
2899 }
2900 assert!(matches!(srv.jobs[0].outcome, Some(Ok(()))), "{:?}", srv.jobs[0].outcome);
2901 let size = std::fs::metadata(&out).expect("output exists").len();
2902 assert!(size > 0);
2903 // The done line names the file's integrated loudness and true peak, and the structured
2904 // reply carries both: the same measurement `loudness` reports for the file.
2905 let done = export_status(&mut srv, &json!({ "job": 1 }));
2906 assert!(done.text.contains("· integrated ") && done.text.contains("· true peak "), "{}", done.text);
2907 let direct = engine::loudness::measure_file(&out, 0, None).unwrap().unwrap();
2908 let row = &done.structured.as_ref().unwrap()["jobs"][0];
2909 if direct.integrated_lufs.is_finite() {
2910 let lufs = row["integrated_lufs"].as_f64().expect("integrated_lufs is a number");
2911 assert!((direct.integrated_lufs - lufs).abs() < 1e-9, "same measurement as loudness");
2912 } else {
2913 assert!(done.text.contains("integrated silent"), "{}", done.text);
2914 }
2915 }
2916
2917 /// A file whose sound is under one 400 ms block says it is too short to measure, not silent: a
2918 /// 0.1 s tone is real sound, and only the block length keeps it from a loudness figure.
2919 #[test]
2920 fn a_tenth_of_a_second_of_sound_is_too_short_to_measure_not_silent() {
2921 let dir = scratch("short-sound");
2922 let path = dir.join("short.wav");
2923 // 0.1 s of a 440 Hz tone at 48 kHz, mono 16-bit PCM.
2924 let frames = 4800u32;
2925 let mut wav = Vec::new();
2926 wav.extend_from_slice(b"RIFF");
2927 wav.extend_from_slice(&(36 + frames * 2).to_le_bytes());
2928 wav.extend_from_slice(b"WAVEfmt ");
2929 wav.extend_from_slice(&16u32.to_le_bytes());
2930 wav.extend_from_slice(&1u16.to_le_bytes());
2931 wav.extend_from_slice(&1u16.to_le_bytes());
2932 wav.extend_from_slice(&48000u32.to_le_bytes());
2933 wav.extend_from_slice(&96000u32.to_le_bytes());
2934 wav.extend_from_slice(&2u16.to_le_bytes());
2935 wav.extend_from_slice(&16u16.to_le_bytes());
2936 wav.extend_from_slice(b"data");
2937 wav.extend_from_slice(&(frames * 2).to_le_bytes());
2938 for i in 0..frames {
2939 let x = 0.5 * (2.0 * std::f64::consts::PI * 440.0 * f64::from(i) / 48000.0).sin();
2940 wav.extend_from_slice(&((x * 32767.0) as i16).to_le_bytes());
2941 }
2942 std::fs::write(&path, &wav).expect("write wav");
2943 assert!(sound_too_short(&path), "0.1 s is under one block");
2944 let measured = engine::loudness::measure_file(&path, 0, None).unwrap().unwrap();
2945 assert!(!measured.integrated_lufs.is_finite(), "no block above the gate in 0.1 s");
2946 assert!(measured.true_peak_dbtp.is_finite(), "the sound is real");
2947 assert!(lufs_text(measured.integrated_lufs, sound_too_short(&path)).starts_with("too short to measure loudness"));
2948 }
2949
2950 /// A file with sound measures to finite LUFS and dBTP figures, and the text names them.
2951 #[test]
2952 fn file_levels_are_the_loudness_of_the_written_file() {
2953 let src = format!("{}/../../assets/test_av.mp4", env!("CARGO_MANIFEST_DIR"));
2954 let levels = file_levels(Path::new(&src)).expect("a clip with sound measures");
2955 assert!(levels.lufs.is_finite() && levels.lufs < 0.0, "{levels:?}");
2956 assert!(levels.true_peak_dbtp.is_finite(), "{levels:?}");
2957 assert_eq!(lufs_text(-14.04, false), "-14.0 LUFS");
2958 // The figure rounds to one decimal, never truncates: -16.06 is -16.1, and -15.96 is -16.0.
2959 assert_eq!(lufs_text(-16.06, false), "-16.1 LUFS");
2960 assert_eq!(lufs_text(-15.96, false), "-16.0 LUFS");
2961 assert_eq!(lufs_text(f64::NEG_INFINITY, false), "silent");
2962 assert_eq!(lufs_text(f64::NEG_INFINITY, true), "too short to measure loudness (under 0.4 s)");
2963 assert_eq!(peak_text(-1.0), "-1.0 dBTP");
2964 assert_eq!(peak_text(0.3), "+0.3 dBTP");
2965 assert_eq!(peak_text(-3.4), "-3.4 dBTP");
2966 assert_eq!(peak_text(f64::NEG_INFINITY), "silent");
2967 }
2968
2969 /// A finished export keeps its result: every poll after it finished reports it, for
2970 /// one job or for all, and the text is never empty -- not even with no exports.
2971 #[test]
2972 fn a_finished_export_is_reported_on_every_poll() {
2973 engine::ao::set_silent_output();
2974 let mut srv = Server::new();
2975 let none = export_status(&mut srv, &json!({}));
2976 assert!(!none.is_error && !none.text.is_empty(), "{}", none.text);
2977
2978 let src = small_clip();
2979 srv.session = Some(engine::PlaybackSession::open(&src).expect("open assets/test_speed_sync.mp4"));
2980 let dir = scratch("status-twice");
2981 let out = dir.join("twice.mp4");
2982 std::fs::remove_file(&out).ok();
2983 let args = json!({"out": out.display().to_string(), "range": {"from": 0, "to": 1}});
2984 let started = export_start(&mut srv, &args);
2985 assert!(!started.is_error, "{}", started.text);
2986
2987 let deadline = Instant::now() + Duration::from_secs(120);
2988 while job_running(&srv.jobs[0]) {
2989 assert!(Instant::now() < deadline, "export did not finish in 120s");
2990 std::thread::sleep(Duration::from_millis(100));
2991 }
2992 let out_text = out.display().to_string();
2993 for args in [json!({}), json!({"job": 1}), json!({})] {
2994 let r = export_status(&mut srv, &args);
2995 assert!(!r.is_error && !r.text.is_empty(), "{}", r.text);
2996 assert!(r.text.contains("job:1 done"), "{}", r.text);
2997 assert!(r.text.contains(&out_text), "{}", r.text);
2998 }
2999 }
3000
3001 /// A start line says what the engine will decide, not what it might: an AV1 or HEVC
3002 /// Matroska sound is Opus or AAC by the mix, so it says both; WebM is always Opus.
3003 #[test]
3004 fn start_line_names_the_sound_codec_the_engine_predicts() {
3005 assert_eq!(
3006 av_words(Format::Av1, "copy (source packets)", "Opus · SW encode (ec-opus)"),
3007 "video: AV1 (copy), audio: Opus, container: Matroska"
3008 );
3009 assert_eq!(
3010 av_words(Format::Av1, "SW encode (rav1e)", "AAC · SW encode (ec-aac)"),
3011 "video: AV1 (software), audio: AAC, container: Matroska"
3012 );
3013 assert_eq!(
3014 av_words(Format::Hevc, "SW encode (ec-h265 GOP)", "AAC copy"),
3015 "video: HEVC (software), audio: AAC (copy), container: Matroska"
3016 );
3017 assert_eq!(
3018 av_words(Format::Webm, "SW encode (rav1e)", "Opus · SW encode (ec-opus)"),
3019 "video: AV1 (software), audio: Opus, container: WebM"
3020 );
3021 }
3022
3023 /// Over 0 dBTP the file clips and the warning names the limiter setting; above the -1 dBTP
3024 /// ceiling (exactly -1 is within spec) it is the normalize warning; otherwise, or silent, none.
3025 #[test]
3026 fn took_reads_one_decimal_under_ten_seconds() {
3027 assert_eq!(took_words(0.696), "0.7 s");
3028 assert_eq!(took_words(0.0), "0.0 s");
3029 assert_eq!(took_words(9.96), "10.0 s", "under ten, one decimal, rounded");
3030 assert_eq!(took_words(42.4), "42s");
3031 assert_eq!(took_words(125.0), "2m05s");
3032 }
3033
3034 #[test]
3035 fn fit_is_keep_fit_or_fill_and_refuses_the_rest() {
3036 assert_eq!(parse_fit(&json!({})), Ok(None));
3037 assert_eq!(parse_fit(&json!({"fit": "keep"})), Ok(None));
3038 assert_eq!(parse_fit(&json!({"fit": "Fill"})), Ok(Some(FitPolicy::Fill)));
3039 assert_eq!(parse_fit(&json!({"fit": "fit"})), Ok(Some(FitPolicy::Fit)));
3040 let e = parse_fit(&json!({"fit": "stretch"})).unwrap_err();
3041 assert!(e.contains("keep, fit or fill"), "{e}");
3042 }
3043
3044 #[test]
3045 fn clash_note_names_the_moment_the_title_and_the_place_to_move_to() {
3046 let note = clash_note(86.5, "EVENING, MIRADOURO", Place::Bottom);
3047 assert_eq!(
3048 note,
3049 "at 86.5s the caption overlaps title 'EVENING, MIRADOURO' (both at the bottom): burn_captions {place:\"top\"} or move the title"
3050 );
3051 assert!(clash_note(3.0, "A\nB", Place::Top).contains("title 'A / B' (both at the top): burn_captions {place:\"bottom\"}"));
3052 }
3053
3054 /// The clipping advice names the ceiling in plain words: "with a -2 dBTP ceiling" for a lossy
3055 /// file, -1 for a lossless one, never "under 0".
3056 #[test]
3057 fn the_clipping_advice_states_the_ceiling_in_plain_words() {
3058 let lossy = peak_warning(1, Some(0.43), true, None).expect("0.43 dBTP clips");
3059 assert!(lossy.contains("turn the master limiter on with a -2 dBTP ceiling: project_settings {limiter:{on:true, ceiling_db:-2}}"), "{lossy}");
3060 assert!(!lossy.contains("under 0"), "{lossy}");
3061 let lossless = peak_warning(1, Some(0.43), false, None).expect("0.43 dBTP clips");
3062 assert!(lossless.contains("with a -1 dBTP ceiling: project_settings {limiter:{on:true, ceiling_db:-1}}"), "{lossless}");
3063 }
3064
3065 /// A `to` past the timeline is refused naming both ends; inside the timeline it is accepted
3066 /// and the caller clips it to the picture.
3067 #[test]
3068 fn a_range_past_the_timeline_names_both_ends() {
3069 let r = |to: &str| json!({"range": {"from": "4s", "to": to}});
3070 let err = parse_range(&r("12s"), 25.0, 225, 150).expect_err("12 s is past the 9 s timeline");
3071 assert_eq!(
3072 err,
3073 "range.to (300f (12.000s)) is past the end of the timeline (225f (9.000s)): the picture and sound end at 150f (6.000s)"
3074 );
3075 assert_eq!(parse_range(&r("8s"), 25.0, 225, 150).unwrap(), Some((100, 200)), "inside the timeline is kept");
3076 assert_eq!(parse_range(&r("end"), 25.0, 225, 150).unwrap(), Some((100, 225)), "end is the timeline end");
3077 }
3078
3079 #[test]
3080 fn peak_warning_names_the_limiter_when_the_file_clips() {
3081 let clip = peak_warning(1, Some(0.43), false, None).expect("0.43 dBTP clips");
3082 assert!(clip.contains("the mix clips") && clip.contains("project_settings {limiter:{on:true, ceiling_db:-1}}"), "{clip}");
3083 assert!(clip.contains("lane_gain"), "{clip}");
3084 let ceiling = peak_warning(1, Some(-0.5), false, None).expect("-0.5 dBTP is above the ceiling");
3085 assert!(ceiling.contains("ceiling (clips on some players) the mix is held to") && !ceiling.contains("the mix clips"), "{ceiling}");
3086 assert!(ceiling.contains("true peak -0.5 dBTP is above the -1 dBTP ceiling"), "{ceiling}");
3087 assert!(clip.contains("true peak +0.4 dBTP"), "{clip}");
3088 // A value that one decimal would print as the ceiling itself shows two.
3089 let near = peak_warning(1, Some(-0.96), false, None).expect("-0.96 is above the ceiling");
3090 assert!(near.contains("true peak -0.96 dBTP is above the -1 dBTP ceiling"), "{near}");
3091 assert_eq!(peak_warning(1, Some(-1.0), false, None), None, "exactly -1 dBTP is within spec");
3092 assert!(peak_warning(1, Some(-0.99), false, None).is_some(), "just above -1 dBTP warns");
3093 assert_eq!(peak_warning(1, Some(f64::NEG_INFINITY), false, None), None);
3094 assert_eq!(peak_warning(1, None, false, None), None);
3095 }
3096
3097 /// On an mp4 (lossy) the peak reads as the printed decimal: only +0.1 and up is "the mix clips".
3098 /// A peak that prints as +0.0 (0.0 itself, or +0.04) is over the -1 ceiling and says so.
3099 #[test]
3100 fn an_mp4_peak_clips_only_from_plus_a_tenth_and_else_reads_as_the_ceiling() {
3101 assert_eq!(peak_warning(1, Some(-2.5), true, None), None, "-2.5 dBTP is within spec");
3102 assert_eq!(peak_warning(1, Some(-1.0), true, None), None, "exactly -1 dBTP is within spec");
3103 let zero = peak_warning(1, Some(0.0), true, None).expect("0.0 is over the ceiling");
3104 assert!(zero.contains("true peak +0.0 dBTP is above the -1 dBTP ceiling") && !zero.contains("the mix clips"), "{zero}");
3105 let tiny = peak_warning(1, Some(0.04), true, None).expect("+0.04 is over the ceiling");
3106 assert!(tiny.contains("true peak +0.0 dBTP is above the -1 dBTP ceiling") && !tiny.contains("the mix clips"), "{tiny}");
3107 let clip = peak_warning(1, Some(0.3), true, None).expect("+0.3 clips");
3108 assert!(clip.contains("the mix clips") && clip.contains("true peak +0.3 dBTP"), "{clip}");
3109 let edge = peak_warning(1, Some(0.05), true, None).expect("+0.05 prints as +0.1 and clips");
3110 assert!(edge.contains("the mix clips"), "{edge}");
3111 }
3112
3113 #[test]
3114 fn peak_advice_aims_lossy_files_at_minus_two_and_steps_past_the_ceiling_in_use() {
3115 let lossy = peak_warning(1, Some(-0.5), true, None).expect("-0.5 dBTP is above the ceiling");
3116 assert!(lossy.contains("true_peak:-2}") && lossy.contains("a lossy encode adds up to about 1 dB"), "{lossy}");
3117 let lossless = peak_warning(1, Some(-0.5), false, None).expect("-0.5 dBTP is above the ceiling");
3118 assert!(lossless.contains("true_peak:-1}") && !lossless.contains("lossy"), "{lossless}");
3119 // The master limiter already on at the advised -2 for a lossy file: the advice is the next ceiling down.
3120 let held = peak_warning(1, Some(-0.5), true, Some(-2.0)).expect("-0.5 dBTP is above the ceiling");
3121 assert!(held.contains("true_peak:-3}") && !held.contains("true_peak:-2}"), "{held}");
3122 // A limiter on at some other ceiling is not the call to avoid.
3123 let other = peak_warning(1, Some(-0.5), true, Some(-1.5)).expect("-0.5 dBTP is above the ceiling");
3124 assert!(other.contains("true_peak:-2}"), "{other}");
3125 // A clip on a lossless file whose limiter is on at -1 is told -2, not the -1 already in use.
3126 let clip = peak_warning(1, Some(0.43), false, Some(-1.0)).expect("0.43 dBTP clips");
3127 assert!(clip.contains("ceiling_db:-2}") && !clip.contains("ceiling_db:-1}"), "{clip}");
3128 }
3129
3130 /// An `out` no job of this session wrote says whether its file is there, with size and
3131 /// time, and that an earlier session may have run it; a missing file says so too.
3132 #[test]
3133 fn unknown_out_says_whether_the_file_is_there() {
3134 let dir = scratch("unknown-out");
3135 let there = dir.join("earlier.mp4");
3136 std::fs::write(&there, vec![0u8; 12_139]).unwrap();
3137 let text = unknown_out_text(&there);
3138 assert!(text.contains("earlier session") && text.contains("12.1 KB") && text.contains("written 20"), "{text}");
3139 let gone = dir.join("never.mp4");
3140 let text = unknown_out_text(&gone);
3141 assert!(text.contains("No file is there at that path") && !text.contains("partial"), "{text}");
3142 std::fs::write(dir.join("writing.mp4.part"), b"x").unwrap();
3143 let part = unknown_out_text(&dir.join("writing.mp4"));
3144 assert!(part.contains("a partial") && part.contains("still writing"), "{part}");
3145 }
3146
3147 /// Asking for a job or a file this session never started is answered, not a bare
3148 /// "no exports yet": the reply names the `out` route to the earlier export's file.
3149 #[test]
3150 fn status_for_an_unknown_job_or_an_empty_session_points_at_out() {
3151 let mut srv = Server::new();
3152 let empty = export_status(&mut srv, &json!({}));
3153 assert!(!empty.is_error && empty.text.contains("pass out"), "{}", empty.text);
3154 let job = export_status(&mut srv, &json!({"job": 3}));
3155 assert!(job.is_error && job.text.contains("pass out"), "{}", job.text);
3156 let dir = scratch("status-out-gone");
3157 let gone = dir.join("nothing.mp4");
3158 let r = export_status(&mut srv, &json!({"out": gone.display().to_string()}));
3159 assert!(!r.is_error && r.text.contains("No file is there at that path"), "{}", r.text);
3160 }
3161
3162 /// A relative `out` is resolved against the project's folder and refused without a
3163 /// project; a file inside a git tree outside the project folder gets a warning.
3164 #[test]
3165 fn relative_out_is_anchored_to_the_project_and_repo_is_warned() {
3166 let mut srv = Server::new();
3167 let r = export_start(&mut srv, &json!({"out": "clip.mp4"}));
3168 assert!(r.is_error && r.text.contains("no project is open"), "{}", r.text);
3169
3170 let dir = scratch("anchor");
3171 srv.path = Some(dir.join("proj.edith"));
3172 let (p, note) = anchor_out(&srv, "clip.mp4").expect("anchored");
3173 assert_eq!(PathBuf::from(&p), dir.join("clip.mp4"));
3174 assert!(note.is_some_and(|n| n.contains("resolved against the project folder")));
3175 let (p, note) = anchor_out(&srv, "/abs/x.mp4").expect("absolute kept");
3176 assert_eq!(PathBuf::from(&p), PathBuf::from("/abs/x.mp4"));
3177 assert!(note.is_none());
3178
3179 let repo = dir.join("repo");
3180 std::fs::create_dir_all(repo.join(".git")).unwrap();
3181 assert!(repo_warning(&repo.join("sub/x.mp4"), Some(dir.path())).is_some());
3182 assert!(repo_warning(&repo.join("x.mp4"), Some(&repo)).is_none(), "beside the project");
3183 assert!(repo_warning(&dir.join("x.mp4"), Some(dir.path())).is_none(), "outside any repo");
3184 }
3185
3186 #[test]
3187 fn empty_timeline_and_pictureless_video_are_refused_up_front() {
3188 engine::ao::set_silent_output();
3189 let dir = scratch("refuse");
3190 let mut srv = Server::new();
3191 srv.session = Some(engine::PlaybackSession::empty(1280, 720, 30.0).unwrap());
3192 let r = export_start(&mut srv, &json!({"out": dir.join("a.mp4").display().to_string()}));
3193 assert!(r.is_error);
3194 assert_eq!(r.text, "timeline is empty — nothing to export: place a clip first (edit place/append)");
3195
3196 let tone = format!("{}/../../assets/test_tone.wav", env!("CARGO_MANIFEST_DIR"));
3197 let session = engine::PlaybackSession::open(&tone).expect("open assets/test_tone.wav");
3198 srv.session = Some(session);
3199 // A Matroska file of it would be black: refused. An mp4 is the sound alone (below).
3200 let r = export_start(&mut srv, &json!({"out": dir.join("b.mkv").display().to_string()}));
3201 assert!(r.is_error, "{}", r.text);
3202 assert!(r.text.contains("no video clips"), "{}", r.text);
3203 assert!(srv.jobs.is_empty(), "a refused export starts no job");
3204 }
3205
3206 /// Runs `ffprobe` on a finished file and returns its `codec_name:codec_type` per stream.
3207 fn stream_codecs(path: &Path) -> Vec<String> {
3208 let out = std::process::Command::new("ffprobe")
3209 .args(["-v", "error", "-show_entries", "stream=codec_type,codec_name", "-of", "csv=p=0"])
3210 .arg(path)
3211 .output()
3212 .expect("run ffprobe");
3213 String::from_utf8_lossy(&out.stdout)
3214 .lines()
3215 .map(|l| l.replace(',', ":"))
3216 .collect()
3217 }
3218
3219 /// Waits for job `n` (1-based) to finish, and checks that it wrote its file.
3220 fn finish_job(srv: &mut Server, n: usize) {
3221 let deadline = Instant::now() + Duration::from_secs(120);
3222 while srv.jobs[n - 1].outcome.is_none() {
3223 assert!(Instant::now() < deadline, "export did not finish in 120s");
3224 export_status(srv, &json!({ "job": n }));
3225 std::thread::sleep(Duration::from_millis(100));
3226 }
3227 assert!(matches!(srv.jobs[n - 1].outcome, Some(Ok(()))), "{:?}", srv.jobs[n - 1].outcome);
3228 }
3229
3230 /// `m4a` writes the timeline's sound as AAC in an mp4 box, and an mp4 of the same
3231 /// audio-only timeline is the sound alone too: neither is refused, and neither has a picture.
3232 #[test]
3233 fn m4a_and_mp4_of_a_tone_timeline_are_the_sound_alone() {
3234 engine::ao::set_silent_output();
3235 let tone = format!("{}/../../assets/test_tone.wav", env!("CARGO_MANIFEST_DIR"));
3236 let dir = scratch("m4a");
3237 let mut srv = Server::new();
3238 srv.session = Some(engine::PlaybackSession::open(&tone).expect("open assets/test_tone.wav"));
3239
3240 let m4a = dir.join("tone.m4a");
3241 let started = export_start(&mut srv, &json!({"out": m4a.display().to_string(), "range": {"from": 0, "to": 1}}));
3242 assert!(!started.is_error, "{}", started.text);
3243 assert!(started.text.contains("container: M4A"), "{}", started.text);
3244 finish_job(&mut srv, 1);
3245 assert_eq!(stream_codecs(&m4a), ["aac:audio"], "one AAC stream and no picture");
3246
3247 let mp4 = dir.join("tone-sound.mp4");
3248 let started = export_start(&mut srv, &json!({"out": mp4.display().to_string(), "range": {"from": 0, "to": 1}}));
3249 assert!(!started.is_error, "{}", started.text);
3250 assert!(!started.text.contains("video:"), "no picture is named: {}", started.text);
3251 finish_job(&mut srv, 2);
3252 assert_eq!(stream_codecs(&mp4), ["aac:audio"], "an mp4 of a picture-less timeline is audio only");
3253 }
3254
3255 /// Subtitles asked for on a file with no picture say so in the reply, for `true` and for a
3256 /// list alike, and the export still runs: the sound is written, the captions are not.
3257 #[test]
3258 fn subtitles_asked_for_a_picture_less_mp4_are_named_as_not_written() {
3259 engine::ao::set_silent_output();
3260 let tone = format!("{}/../../assets/test_tone.wav", env!("CARGO_MANIFEST_DIR"));
3261 let srt = format!("{}/../engine/tests/data/test_subs.srt", env!("CARGO_MANIFEST_DIR"));
3262 let dir = scratch("sound-only-subs");
3263 let mut srv = Server::new();
3264 let mut s = engine::PlaybackSession::open(&tone).expect("open assets/test_tone.wav");
3265 s.import_subtitles(Path::new(&srt)).expect("import test_subs.srt");
3266 srv.session = Some(s);
3267 let out = dir.join("sound.mp4").display().to_string();
3268 for subtitles in [json!(true), json!([0])] {
3269 let r = export_start(&mut srv, &json!({"out": out, "range": {"from": 0, "to": 1}, "subtitles": subtitles, "overwrite": true}));
3270 assert!(!r.is_error, "the export is not refused: {}", r.text);
3271 assert!(
3272 r.text.contains("subtitles not written: an mp4 with no picture is written as sound only; add a picture"),
3273 "{}",
3274 r.text
3275 );
3276 assert!(!r.text.contains("none — a timeline"), "the bare card is replaced: {}", r.text);
3277 let n = srv.jobs.len();
3278 finish_job(&mut srv, n);
3279 }
3280 assert_eq!(stream_codecs(Path::new(&out)), ["aac:audio"], "the sound is written, no subtitle track");
3281 }
3282
3283 #[test]
3284 fn a_running_job_on_the_same_out_path_refuses_even_with_overwrite() {
3285 engine::ao::set_silent_output();
3286 let src = small_clip();
3287 let mut srv = Server::new();
3288 srv.session = Some(engine::PlaybackSession::open(&src).expect("open assets/test_speed_sync.mp4"));
3289 let dir = scratch("samepath");
3290 let out = dir.join("same.mp4");
3291 let args = json!({"out": out.display().to_string(), "overwrite": true});
3292 let first = export_start(&mut srv, &args);
3293 assert!(!first.is_error, "{}", first.text);
3294 let second = export_start(&mut srv, &args);
3295 if job_running(&srv.jobs[0]) {
3296 assert!(second.is_error, "{}", second.text);
3297 assert!(second.text.contains("still writing"), "{}", second.text);
3298 assert_eq!(srv.jobs.len(), 1, "a refused export starts no job");
3299 }
3300 // Cancelled, the first job stops running and the same path is allowed again.
3301 // Not waited for to finish: the encoder is slow on a loaded machine.
3302 srv.jobs[0].cancel();
3303 let deadline = Instant::now() + Duration::from_secs(120);
3304 while job_running(&srv.jobs[0]) {
3305 assert!(Instant::now() < deadline, "cancelled export did not stop");
3306 std::thread::sleep(Duration::from_millis(100));
3307 }
3308 let again = export_start(&mut srv, &args);
3309 assert!(!again.is_error, "{}", again.text);
3310 srv.jobs[1].cancel();
3311 }
3312
3313 /// `queue: true` lines exports up: the second waits with its own copy of the timeline until the
3314 /// first has finished, nothing is encoded twice at once, and both files land and probe.
3315 #[test]
3316 fn queued_exports_run_one_after_another_and_both_files_probe() {
3317 engine::ao::set_silent_output();
3318 let src = small_clip();
3319 let mut srv = Server::new();
3320 srv.session = Some(engine::PlaybackSession::open(&src).expect("open the clip"));
3321 let dir = scratch("queue-two");
3322 let a = dir.join("a.mp4");
3323 let b = dir.join("b.mp4");
3324 for out in [&a, &b] {
3325 let args = json!({"out": out.display().to_string(), "seat": "software", "queue": true, "range": {"from": 0, "to": 1}});
3326 let r = export_start(&mut srv, &args);
3327 assert!(!r.is_error, "{}", r.text);
3328 }
3329 assert_eq!(srv.jobs.len(), 2);
3330 if job_running(&srv.jobs[0]) {
3331 assert!(srv.jobs[1].waiting(), "the second export waits behind the first");
3332 let st = export_status(&mut srv, &json!({}));
3333 assert!(st.text.contains("job:2 waiting"), "{}", st.text);
3334 }
3335 let deadline = Instant::now() + Duration::from_secs(240);
3336 loop {
3337 advance(&mut srv);
3338 // One encode at a time: a waiting job has no worker.
3339 assert!(srv.jobs.iter().filter(|j| j.handle.is_some() && job_running(j)).count() <= 1);
3340 if srv.jobs.iter().all(|j| j.outcome.is_some()) {
3341 break;
3342 }
3343 assert!(Instant::now() < deadline, "queue did not finish in 240s");
3344 std::thread::sleep(Duration::from_millis(100));
3345 }
3346 for (i, out) in [&a, &b].into_iter().enumerate() {
3347 assert!(matches!(srv.jobs[i].outcome, Some(Ok(()))), "{:?}", srv.jobs[i].outcome);
3348 assert!(std::fs::metadata(out).is_ok_and(|m| m.len() > 0), "{} written", out.display());
3349 assert!(stream_codecs(out).iter().any(|c| c.starts_with("h264")), "{:?}", stream_codecs(out));
3350 }
3351 }
3352
3353 /// Pause sets the flag and status says so; start lifts it, with nothing waiting to start.
3354 #[test]
3355 fn queue_pause_and_start_set_the_flag_and_say_so() {
3356 let mut srv = Server::new();
3357 let paused = export_queue(&mut srv, &json!({"action": "pause"}));
3358 assert!(!paused.is_error && srv.queue_paused, "{}", paused.text);
3359 let status = export_queue(&mut srv, &json!({"action": "status"}));
3360 assert!(status.text.contains("queue paused") && status.text.contains("queued: none"), "{}", status.text);
3361 let started = export_queue(&mut srv, &json!({"action": "start"}));
3362 assert!(!srv.queue_paused && started.text.contains("nothing is waiting"), "{}", started.text);
3363 }
3364
3365 /// A waiting job cancelled by number never starts and writes nothing; the queue moves past it.
3366 #[test]
3367 fn a_waiting_job_can_be_cancelled_and_never_starts() {
3368 engine::ao::set_silent_output();
3369 let src = small_clip();
3370 let mut srv = Server::new();
3371 srv.session = Some(engine::PlaybackSession::open(&src).expect("open the clip"));
3372 let dir = scratch("queue-cancel");
3373 let a = dir.join("a.mp4");
3374 let b = dir.join("b.mp4");
3375 for out in [&a, &b] {
3376 let args = json!({"out": out.display().to_string(), "seat": "software", "queue": true});
3377 assert!(!export_start(&mut srv, &args).is_error);
3378 }
3379 if !srv.jobs[1].waiting() {
3380 // The first finished before the second was queued: nothing to cancel, nothing to check.
3381 srv.jobs[0].cancel();
3382 srv.jobs[1].cancel();
3383 return;
3384 }
3385 let r = export_cancel(&mut srv, &json!({"job": 2}));
3386 assert!(r.text.contains("removed from the queue"), "{}", r.text);
3387 assert!(matches!(&srv.jobs[1].outcome, Some(Err(e)) if e.contains("cancel")));
3388 srv.jobs[0].cancel();
3389 let deadline = Instant::now() + Duration::from_secs(120);
3390 while job_running(&srv.jobs[0]) {
3391 advance(&mut srv);
3392 assert!(Instant::now() < deadline, "cancelled export did not stop");
3393 std::thread::sleep(Duration::from_millis(100));
3394 }
3395 advance(&mut srv);
3396 assert!(srv.jobs[1].handle.is_none(), "a cancelled waiting job never got a worker");
3397 assert!(!b.exists(), "nothing written for the removed job");
3398 }
3399
3400 /// A caption past the picture end is not written by a whole-timeline export, and the
3401 /// reply says so and reports the picture's end, not the caption's.
3402 #[test]
3403 fn whole_timeline_export_stops_at_the_picture_and_says_so() {
3404 engine::ao::set_silent_output();
3405 let src = small_clip();
3406 let dir = scratch("picture-end");
3407 let mut srv = Server::new();
3408 srv.session = Some(engine::PlaybackSession::open(&src).expect("open the clip"));
3409 let picture = srv.session.as_ref().expect("session").timeline_duration();
3410 let past = picture + 2.5;
3411 let ms = (past * 1000.0) as u64;
3412 let srt = dir.join("late.srt");
3413 std::fs::write(
3414 &srt,
3415 format!(
3416 "1\n00:00:00,000 --> 00:00:01,000\nearly\n\n2\n00:{:02}:{:02},{:03} --> 00:{:02}:{:02},{:03}\nlate\n",
3417 ms / 60000,
3418 ms / 1000 % 60,
3419 ms % 1000,
3420 (ms + 1000) / 60000,
3421 (ms + 1000) / 1000 % 60,
3422 (ms + 1000) % 1000
3423 ),
3424 )
3425 .expect("write the srt");
3426 let s = srv.session.as_mut().expect("session");
3427 s.import_subtitles(&srt).expect("import the srt");
3428 // Placed on S1 so the captions count toward the timeline's end.
3429 let frames = (past * session_fps(s)).round() as u32;
3430 let sub = engine::project::SubClip { start: 0, frames, track: 0, in_us: 0, out_us: (past * 1e6) as i64, link: None };
3431 s.add_lane(LaneKind::Subtitle);
3432 s.place_sub(engine::project::Lane::new(LaneKind::Subtitle, 0), 0, sub).expect("place the captions");
3433 assert!(media_end(srv.session.as_ref().expect("session")) < session_end(srv.session.as_ref().expect("session")));
3434
3435 let out = dir.join("picture-end.mp4");
3436 let r = export_start(&mut srv, &json!({"out": out.display().to_string()}));
3437 assert!(!r.is_error, "{}", r.text);
3438 assert!(r.text.contains("captions run to"), "{}", r.text);
3439 assert!(r.text.contains("past the picture and sound end at 3.000s: they are not exported"), "{}", r.text);
3440 assert!(r.text.contains("whole timeline, to "), "{}", r.text);
3441 let deadline = Instant::now() + Duration::from_secs(240);
3442 for job in srv.jobs.iter_mut() {
3443 while job_running(job) {
3444 assert!(Instant::now() < deadline, "the export did not finish");
3445 std::thread::sleep(Duration::from_millis(200));
3446 }
3447 settle(job);
3448 assert!(matches!(job.outcome, Some(Ok(()))), "{:?}", job.outcome);
3449 }
3450 let s = srv.session.as_ref().expect("session");
3451 assert!(media_end(s) as f64 / session_fps(s) <= picture + 0.05);
3452 }
3453
3454 fn burn_session() -> Server {
3455 engine::ao::set_silent_output();
3456 let src = small_clip();
3457 let srt = format!("{}/../engine/tests/data/test_subs.srt", env!("CARGO_MANIFEST_DIR"));
3458 let mut srv = Server::new();
3459 srv.session = Some(engine::PlaybackSession::open(&src).expect("open assets/test_speed_sync.mp4"));
3460 srv.session
3461 .as_mut()
3462 .expect("session")
3463 .import_subtitles(Path::new(&srt))
3464 .expect("import test_subs.srt");
3465 srv
3466 }
3467
3468 #[test]
3469 fn a_burn_names_the_characters_no_face_draws_once_each() {
3470 let dir = scratch("burn_glyph");
3471 let srt = dir.join("odd.srt");
3472 // U+10FFFD is a private-use noncharacter no face has; the emoji is covered by the fallback.
3473 std::fs::write(&srt, "1\n00:00:01,000 --> 00:00:03,000\nHello \u{10FFFD} and \u{10FFFD} \u{1F3AC}\n\n")
3474 .expect("write the srt");
3475 let mut srv = burn_session();
3476 srv.session
3477 .as_mut()
3478 .expect("session")
3479 .import_subtitles(srt.as_path())
3480 .expect("import odd.srt");
3481 let s = srv.session.as_ref().expect("session");
3482 // burn_session imports test_subs.srt as track 0, so the odd file is track 1.
3483 assert_eq!(
3484 missing_glyph_note(s, 1).as_deref(),
3485 Some("no glyph for: U+10FFFD (drawn as an empty box)")
3486 );
3487 assert_eq!(missing_glyph_note(s, 0), None, "test_subs.srt draws every character");
3488 }
3489
3490 #[test]
3491 fn burn_captions_refuses_bad_settings_and_accepts_a_good_track() {
3492 let mut srv = burn_session();
3493 let dir = scratch("burn");
3494 let out = dir.join("burn.mp4").display().to_string();
3495
3496 let bad_track = export_start(&mut srv, &json!({"out": out, "burn_captions": {"track": 3}}));
3497 assert!(bad_track.is_error && bad_track.text.contains("does not exist"), "{}", bad_track.text);
3498 let bad_size = export_start(&mut srv, &json!({"out": out, "burn_captions": {"size": 500}}));
3499 assert!(bad_size.is_error && bad_size.text.contains("size"), "{}", bad_size.text);
3500 let bad_key = export_start(&mut srv, &json!({"out": out, "burn_captions": {"colour": "red"}}));
3501 assert!(bad_key.is_error && bad_key.text.contains("unknown key"), "{}", bad_key.text);
3502 let audio = export_start(
3503 &mut srv,
3504 &json!({"out": dir.join("a.wav").display().to_string(), "burn_captions": {}}),
3505 );
3506 assert!(audio.is_error && audio.text.contains("audio only"), "{}", audio.text);
3507 assert!(srv.jobs.is_empty(), "refused exports start no job");
3508
3509 let s = srv.session.as_ref().expect("session");
3510 let (track, style) = parse_burn(
3511 &json!({"burn_captions": {"size": 80, "outline": "thick", "place": "top", "boxed": false}}),
3512 s,
3513 )
3514 .expect("valid")
3515 .expect("present");
3516 assert_eq!(track, 0, "the default track is track 0 when no lane places one");
3517 assert_eq!(style.size, 80);
3518 assert_eq!(style.outline, Outline::Thick);
3519 assert_eq!(style.place, Place::Top);
3520 assert!(!style.boxed);
3521 let (_, style) = parse_burn(&json!({"burn_captions": {"family": "Noto Serif"}}), s)
3522 .expect("valid")
3523 .expect("present");
3524 assert_eq!(style.family.as_deref(), Some("Noto Serif"), "the family is the one named");
3525 assert!(parse_burn(&json!({"burn_captions": {"family": 3}}), s).is_err(), "a family is a name");
3526 assert!(parse_burn(&json!({}), s).expect("valid").is_none());
3527 assert!(parse_burn(&json!({"burn_captions": false}), s).expect("valid").is_none());
3528 let (track, style) = parse_burn(&json!({"burn_captions": true}), s)
3529 .expect("true is valid")
3530 .expect("true is on");
3531 assert_eq!((track, style.size, style.outline, style.place), (0, 50, Outline::Thin, Place::Bottom));
3532 assert!(parse_burn(&json!({"burn_captions": "yes"}), s).unwrap_err().contains("object or a boolean"));
3533
3534 // Under a second of picture, across the first cue (0.5 s to 1.5 s), burned in.
3535 let started = export_start(
3536 &mut srv,
3537 &json!({
3538 "out": out,
3539 "range": {"from": "0.4s", "to": "1.0s"},
3540 "burn_captions": {"track": 0}
3541 }),
3542 );
3543 assert!(!started.is_error, "{}", started.text);
3544 assert!(started.text.contains("captions burned (track 0)"), "{}", started.text);
3545 // A second of 320x180 picture: a few seconds in a debug build. The deadline is
3546 // generous for a loaded machine.
3547 let deadline = Instant::now() + Duration::from_secs(120);
3548 while job_running(&srv.jobs[0]) {
3549 assert!(Instant::now() < deadline, "burned export did not finish in 120s");
3550 std::thread::sleep(Duration::from_millis(200));
3551 }
3552 settle(&mut srv.jobs[0]);
3553 assert!(matches!(srv.jobs[0].outcome, Some(Ok(()))), "{:?}", srv.jobs[0].outcome);
3554 }
3555
3556 #[test]
3557 fn burn_captions_takes_the_animation_keys_and_defaults_them_from_the_project() {
3558 use engine::captionanim::CaptionAnim;
3559 let mut srv = burn_session();
3560 let burn = |srv: &Server, b: Value| parse_burn(&json!({"burn_captions": b}), srv.session.as_ref().unwrap());
3561 let (_, style) = burn(&srv, json!({
3562 "animation": "karaoke", "highlight": "#12ab9f", "box": true, "uppercase": true, "words_per_line": 3
3563 }))
3564 .expect("valid")
3565 .expect("present");
3566 let cs = style.caption;
3567 assert_eq!(cs.anim, CaptionAnim::Karaoke);
3568 assert_eq!(cs.highlight, [0x12, 0xab, 0x9f]);
3569 assert!(cs.hl_box && cs.uppercase);
3570 assert_eq!(cs.words_per_line, 3);
3571 let (_, style) = burn(&srv, json!({"highlight": "#f80"})).unwrap().unwrap();
3572 assert_eq!(style.caption.highlight, [0xff, 0x88, 0x00], "#rgb");
3573 assert!(burn(&srv, json!({})).unwrap().unwrap().1.caption.is_plain(), "static by default");
3574 for (bad, word) in [
3575 (json!({"animation": "spin"}), "animation"),
3576 (json!({"highlight": "yellow"}), "highlight"),
3577 (json!({"box": "yes"}), "box"),
3578 (json!({"words_per_line": 13}), "words_per_line"),
3579 (json!({"uppercase": 1}), "uppercase"),
3580 ] {
3581 let e = burn(&srv, bad).unwrap_err();
3582 assert!(e.contains(word), "{e}");
3583 }
3584 // The project's caption style is the default; a key overrides it; undo takes it back.
3585 let r = crate::tools::project::project_settings(
3586 &mut srv,
3587 &json!({"captions": {"animation": "pop", "words_per_line": 2}}),
3588 );
3589 assert!(!r.is_error, "{}", r.text);
3590 let (_, style) = burn(&srv, json!({"uppercase": true})).unwrap().unwrap();
3591 assert_eq!((style.caption.anim, style.caption.words_per_line, style.caption.uppercase), (CaptionAnim::Pop, 2, true));
3592 let r = crate::tools::project::project_settings(&mut srv, &json!({"captions": {"animation": "pop", "words_per_line": 2}}));
3593 assert!(r.text.contains("already"), "{}", r.text);
3594 let r = crate::tools::project::project_settings(&mut srv, &json!({"captions": {"animation": "wiggle"}}));
3595 assert!(r.is_error && r.text.contains("refused"), "{}", r.text);
3596 assert!(srv.session.as_mut().unwrap().undo());
3597 assert!(srv.session.as_ref().unwrap().caption_style().is_plain());
3598 }
3599
3600 #[test]
3601 fn burn_only_export_carries_no_soft_subtitle_track() {
3602 let mut srv = burn_session();
3603 let dir = scratch("burn-only");
3604 let burned = dir.join("burn-only.mp4");
3605 let both = dir.join("burn-and-soft.mp4");
3606 let common = json!({"range": {"from": "0.4s", "to": "1.0s"}, "burn_captions": {"track": 0}});
3607 let mut with_soft = common.clone();
3608 with_soft["subtitles"] = json!([0]);
3609 with_soft["out"] = json!(both.display().to_string());
3610 let mut only = common.clone();
3611 only["out"] = json!(burned.display().to_string());
3612 assert!(!export_start(&mut srv, &only).is_error);
3613 assert!(!export_start(&mut srv, &with_soft).is_error);
3614 let deadline = Instant::now() + Duration::from_secs(240);
3615 for job in srv.jobs.iter_mut() {
3616 while job_running(job) {
3617 assert!(Instant::now() < deadline, "burned exports did not finish");
3618 std::thread::sleep(Duration::from_millis(200));
3619 }
3620 settle(job);
3621 assert!(matches!(job.outcome, Some(Ok(()))), "{:?}", job.outcome);
3622 }
3623 let tracks = engine::subtitle::of_mp4(&burned).expect("read the burned export back");
3624 assert!(tracks.is_empty(), "a burn-only export carries soft tracks: {tracks:?}");
3625 let tracks = engine::subtitle::of_mp4(&both).expect("read the export back");
3626 assert_eq!(tracks.len(), 1, "an explicit subtitles pick still adds its track");
3627 }
3628
3629 /// Soft subtitle tracks are opt-in: a ranged export that names none carries none, even
3630 /// with captions placed on the timeline; `subtitles: true` carries every track.
3631 #[test]
3632 fn soft_subtitles_are_opt_in_and_true_means_every_track() {
3633 let mut srv = burn_session();
3634 let dir = scratch("soft-opt-in");
3635 let plain = dir.join("plain.mp4");
3636 let all = dir.join("all.mp4");
3637 let range = json!({"range": {"from": "0.4s", "to": "1.0s"}});
3638 let mut plain_args = range.clone();
3639 plain_args["out"] = json!(plain.display().to_string());
3640 let mut all_args = range.clone();
3641 all_args["subtitles"] = json!(true);
3642 all_args["out"] = json!(all.display().to_string());
3643 let mut bad = range.clone();
3644 bad["subtitles"] = json!("yes");
3645 bad["out"] = json!(dir.join("bad.mp4").display().to_string());
3646 assert!(export_start(&mut srv, &bad).is_error, "a string is not a subtitles value");
3647 assert!(!export_start(&mut srv, &plain_args).is_error);
3648 assert!(!export_start(&mut srv, &all_args).is_error);
3649 let deadline = Instant::now() + Duration::from_secs(240);
3650 for job in srv.jobs.iter_mut() {
3651 while job_running(job) {
3652 assert!(Instant::now() < deadline, "exports did not finish");
3653 std::thread::sleep(Duration::from_millis(200));
3654 }
3655 settle(job);
3656 assert!(matches!(job.outcome, Some(Ok(()))), "{:?}", job.outcome);
3657 }
3658 let tracks = engine::subtitle::of_mp4(&plain).expect("read the plain export back");
3659 assert!(tracks.is_empty(), "an export without `subtitles` carries soft tracks: {tracks:?}");
3660 let tracks = engine::subtitle::of_mp4(&all).expect("read the export back");
3661 assert_eq!(tracks.len(), 1, "`subtitles: true` carries every track");
3662 }
3663
3664 /// A picked track no caption lane places is written whole, beside the lanes, and the
3665 /// reply names it: the card and the file agree. A placed track keeps its lane and is
3666 /// never written twice. `subtitles: true` is every track.
3667 #[test]
3668 fn a_picked_track_no_lane_places_is_written_whole_and_named() {
3669 engine::ao::set_silent_output();
3670 let mkv = format!("{}/../../assets/test_subs.mkv", env!("CARGO_MANIFEST_DIR"));
3671 let dir = scratch("unplaced-pick");
3672 let mut srv = Server::new();
3673 srv.session = Some(PlaybackSession::open(small_clip()).expect("open the clip"));
3674 let s = srv.session.as_mut().expect("session");
3675 s.import_subtitles(Path::new(&mkv)).expect("import test_subs.mkv");
3676 // Track 0 is the English subrip, track 1 the French ass ("Signs"). Nothing is placed.
3677 let (fps, end) = (session_fps(s), session_end(s));
3678 let fra = dir.join("fra.mp4");
3679 let r = export_start(&mut srv, &json!({"out": fra.display().to_string(), "subtitles": [1], "overwrite": true}));
3680 assert!(!r.is_error, "{}", r.text);
3681 assert!(r.text.contains("fra — Signs → embedded"), "{}", r.text);
3682 finish_job(&mut srv, 1);
3683 let tracks = engine::subtitle::of_mp4(&fra).expect("read the mp4 back");
3684 assert_eq!(tracks.len(), 1, "the picked track is written: {tracks:?}");
3685 assert_eq!(tracks[0].language, "fra");
3686
3687 // Now track 0 is placed on S1: its lane is written at its placement, and the
3688 // unplaced French track beside it, once each.
3689 let s = srv.session.as_mut().expect("session");
3690 s.add_lane(LaneKind::Subtitle);
3691 let sub = engine::project::SubClip {
3692 start: 0,
3693 frames: end,
3694 track: 0,
3695 in_us: 0,
3696 out_us: (f64::from(end) / fps * 1e6) as i64,
3697 link: None,
3698 };
3699 s.place_sub(engine::project::Lane::new(LaneKind::Subtitle, 0), 0, sub).expect("place the English track");
3700 let all = dir.join("all.mkv");
3701 let r = export_start(&mut srv, &json!({"out": all.display().to_string(), "subtitles": true, "overwrite": true}));
3702 assert!(!r.is_error, "{}", r.text);
3703 assert!(r.text.contains("2 tracks → embedded (S1 eng, fra — Signs)"), "{}", r.text);
3704 finish_job(&mut srv, 2);
3705 let tracks = engine::subtitle::of_matroska(&all).expect("read the mkv back");
3706 assert_eq!(tracks.len(), 2, "one lane and one whole track, each once: {tracks:?}");
3707
3708 // A burn takes a placed track and an unplaced one alike: the same cues either way.
3709 for track in [0, 1] {
3710 let burn = dir.join(format!("burn{track}.mp4"));
3711 let r = export_start(&mut srv, &json!({"out": burn.display().to_string(), "burn_captions": {"track": track}, "overwrite": true}));
3712 assert!(!r.is_error, "burn of track {track} is refused: {}", r.text);
3713 finish_job(&mut srv, 3 + track);
3714 }
3715 }
3716
3717 /// An mp4 writes overlapping cues as one stretch with both lines, so the reply names the
3718 /// track; an mkv keeps every cue and is not named.
3719 #[test]
3720 fn overlapping_cues_are_named_as_merged_in_an_mp4_only() {
3721 engine::ao::set_silent_output();
3722 let dir = scratch("overlap-note");
3723 let srt = dir.join("overlap.srt");
3724 std::fs::write(&srt, "1\n00:00:00,100 --> 00:00:00,600\nfirst\n\n2\n00:00:00,300 --> 00:00:00,900\nsecond\n")
3725 .expect("write the srt");
3726 let mut srv = Server::new();
3727 srv.session = Some(PlaybackSession::open(small_clip()).expect("open the clip"));
3728 srv.session.as_mut().expect("session").import_subtitles(&srt).expect("import the srt");
3729 let mp4 = export_start(&mut srv, &json!({"out": dir.join("o.mp4").display().to_string(), "subtitles": [0], "overwrite": true}));
3730 assert!(!mp4.is_error, "{}", mp4.text);
3731 assert!(mp4.text.contains("overlapping cues are merged in mp4 ("), "{}", mp4.text);
3732 assert!(mp4.text.contains("mkv keeps them"), "{}", mp4.text);
3733 finish_job(&mut srv, 1);
3734 let mkv = export_start(&mut srv, &json!({"out": dir.join("o.mkv").display().to_string(), "subtitles": [0], "overwrite": true}));
3735 assert!(!mkv.is_error, "{}", mkv.text);
3736 assert!(!mkv.text.contains("merged in mp4"), "{}", mkv.text);
3737 finish_job(&mut srv, 2);
3738 }
3739
3740 /// A range that runs past the picture is clipped to it, and the reply says so: the
3741 /// length it names is the file's, and captions past the picture are not exported.
3742 #[test]
3743 fn a_range_past_the_picture_end_is_clipped_and_said() {
3744 engine::ao::set_silent_output();
3745 let dir = scratch("range-clip");
3746 let srt = dir.join("long.srt");
3747 std::fs::write(&srt, "1\n00:00:00,000 --> 00:00:30,000\nstays on screen\n").expect("write the srt");
3748 let mut srv = Server::new();
3749 srv.session = Some(PlaybackSession::open(small_clip()).expect("open the clip"));
3750 let s = srv.session.as_mut().expect("session");
3751 s.import_subtitles(&srt).expect("import the srt");
3752 let (fps, media) = (session_fps(s), media_end(s));
3753 // Placed to 30 s, so the timeline runs far past the picture and the range can reach it.
3754 s.add_lane(LaneKind::Subtitle);
3755 let sub = engine::project::SubClip { start: 0, frames: 30 * fps as u32, track: 0, in_us: 0, out_us: 30_000_000, link: None };
3756 s.place_sub(engine::project::Lane::new(LaneKind::Subtitle, 0), 0, sub).expect("place the captions");
3757 assert!(media < session_end(s), "the captions run past the picture");
3758 let want = format!("range 0f (0.000s) to {}", tc(media, fps));
3759 let r = export_start(&mut srv, &json!({"out": dir.join("r.mp4").display().to_string(), "range": {"from": "0s", "to": "30s"}, "overwrite": true}));
3760 assert!(!r.is_error, "{}", r.text);
3761 assert!(r.text.contains(&want), "the reply names the length the file is: {}", r.text);
3762 assert!(r.text.contains("the range runs past the picture and sound end at"), "{}", r.text);
3763 finish_job(&mut srv, 1);
3764 }
3765
3766 /// An audio-only export does not take subtitles: the reply says so, and does not offer
3767 /// `subtitles` as the way to add one.
3768 #[test]
3769 fn an_audio_only_export_says_subtitles_do_not_apply() {
3770 engine::ao::set_silent_output();
3771 let tone = format!("{}/../../assets/test_tone.wav", env!("CARGO_MANIFEST_DIR"));
3772 let srt = format!("{}/../engine/tests/data/test_subs.srt", env!("CARGO_MANIFEST_DIR"));
3773 let dir = scratch("audio-only-subs");
3774 let mut srv = Server::new();
3775 let mut s = PlaybackSession::open(&tone).expect("open assets/test_tone.wav");
3776 s.import_subtitles(Path::new(&srt)).expect("import test_subs.srt");
3777 srv.session = Some(s);
3778 let r = export_start(&mut srv, &json!({"out": dir.join("tone.m4a").display().to_string(), "range": {"from": 0, "to": 1}}));
3779 assert!(!r.is_error, "{}", r.text);
3780 assert!(r.text.contains("subtitles do not apply:"), "{}", r.text);
3781 assert!(!r.text.contains("pass subtitles to add one"), "{}", r.text);
3782 finish_job(&mut srv, 1);
3783 }
3784
3785 /// The fit reply names the lanes whose full-frame clips it refit and says the overlays kept
3786 /// their own aspect; a file's average bitrate is said in Mb/s or kb/s.
3787 #[test]
3788 fn fit_reply_names_the_lanes_and_the_overlays_keep_their_aspect() {
3789 use engine::export::FitOutcome;
3790 use engine::project::Lane;
3791 let outcome = FitOutcome { lanes: vec![(Lane::V1, 1)], overlays: 1 };
3792 assert_eq!(fit_words(FitPolicy::Fill, &outcome), "; fit fill on V1 (1 clip); overlays keep their own aspect");
3793 let two = FitOutcome { lanes: vec![(Lane::V1, 2), (Lane::new(engine::project::LaneKind::Video, 1), 1)], overlays: 0 };
3794 assert_eq!(fit_words(FitPolicy::Fit, &two), "; fit fit on V1 (2 clips), V2 (1 clip)");
3795 let none = FitOutcome { lanes: Vec::new(), overlays: 2 };
3796 assert_eq!(fit_words(FitPolicy::Fill, &none), "; fit fill no full-frame picture clip; overlays keep their own aspect");
3797 assert_eq!(bitrate_text(4_000_000), "4.00 Mb/s");
3798 assert_eq!(bitrate_text(850_000), "850 kb/s");
3799 }
3800
3801 /// A podcast with no picture exported to mp4 is the sound alone and drops its captions: the
3802 /// reply says so first, before the job line, and names m4a and a still picture as the way out.
3803 #[test]
3804 fn a_picture_less_mp4_with_captions_says_so_first() {
3805 engine::ao::set_silent_output();
3806 let tone = format!("{}/../../assets/test_tone.wav", env!("CARGO_MANIFEST_DIR"));
3807 let srt = format!("{}/../engine/tests/data/test_subs.srt", env!("CARGO_MANIFEST_DIR"));
3808 let dir = scratch("podcast-lead");
3809 let mut srv = Server::new();
3810 let mut s = PlaybackSession::open(&tone).expect("open assets/test_tone.wav");
3811 s.import_subtitles(Path::new(&srt)).expect("import test_subs.srt");
3812 srv.session = Some(s);
3813 let r = export_start(&mut srv, &json!({"out": dir.join("podcast.mp4").display().to_string(), "range": {"from": 0, "to": 1}}));
3814 assert!(!r.is_error, "{}", r.text);
3815 assert!(r.text.starts_with("sound only: an mp4 with no picture"), "{}", r.text);
3816 assert!(r.text.contains("For sound alone use m4a") && r.text.contains("a still image"), "{}", r.text);
3817 assert!(r.text.find("job:1 started").unwrap() > 0, "the job line follows: {}", r.text);
3818 finish_job(&mut srv, 1);
3819 }
3820
3821 /// An AV1 export says its seat and its average bitrate target in the start reply, like HEVC.
3822 #[test]
3823 fn auto_av1_start_line_names_the_seat_and_the_bitrate() {
3824 engine::ao::set_silent_output();
3825 let src = format!("{}/../../assets/test_av.mp4", env!("CARGO_MANIFEST_DIR"));
3826 let dir = scratch("av1-start-line");
3827 let mut srv = Server::new();
3828 srv.session = Some(PlaybackSession::open(Path::new(&src)).expect("open the source"));
3829 let r = export_start(&mut srv, &json!({
3830 "out": dir.join("av1.mp4").display().to_string(), "format": "av1-mp4", "range": {"from": 0, "to": 1}
3831 }));
3832 assert!(!r.is_error, "{}", r.text);
3833 assert!(r.text.contains("\nAV1: software encoder, average bitrate "), "{}", r.text);
3834 assert!(r.text.contains("pass bitrate_kbps for a fixed rate"), "{}", r.text);
3835 finish_job(&mut srv, 1);
3836 }
3837
3838 /// A cancelled export says `cancelling` for as long as its worker is still running, and
3839 /// `cancelled` once it has stopped.
3840 #[test]
3841 fn a_cancelled_export_says_cancelling_until_its_worker_stops() {
3842 engine::ao::set_silent_output();
3843 let dir = scratch("cancelling");
3844 let mut srv = Server::new();
3845 srv.session = Some(PlaybackSession::open(small_clip()).expect("open the clip"));
3846 let out = dir.join("c.mp4");
3847 let started = export_start(&mut srv, &json!({"out": out.display().to_string(), "overwrite": true}));
3848 assert!(!started.is_error, "{}", started.text);
3849 let c = export_cancel(&mut srv, &json!({"job": 1}));
3850 assert!(!c.is_error, "{}", c.text);
3851 let r = export_status(&mut srv, &json!({"job": 1}));
3852 assert!(r.text.contains("job:1 cancelling"), "{}", r.text);
3853 let deadline = Instant::now() + Duration::from_secs(120);
3854 while job_running(&srv.jobs[0]) {
3855 assert!(Instant::now() < deadline, "the cancelled export did not stop");
3856 std::thread::sleep(Duration::from_millis(50));
3857 }
3858 let r = export_status(&mut srv, &json!({"job": 1}));
3859 assert!(r.text.contains("job:1 cancelled"), "{}", r.text);
3860 }
3861
3862 #[test]
3863 fn burn_draws_the_edited_lanes_not_the_original_track() {
3864 use crate::tools::edit::run_edit;
3865 let mut srv = burn_session();
3866 let r = run_edit(&mut srv, &json!({"ops": [{"op": "captions_place", "track": 0}]}));
3867 assert!(!r.is_error, "{}", r.text);
3868 let r = run_edit(
3869 &mut srv,
3870 &json!({"ops": [{"op": "cue_text", "track": 0, "index": 0, "text": "Hello there"}]}),
3871 );
3872 assert!(!r.is_error, "{}", r.text);
3873
3874 // Cut the second cue's time out of the captions, as cut_regions does.
3875 let s = srv.session.as_mut().expect("session");
3876 let fps = session_fps(s);
3877 let lanes = s.subtitle_lanes();
3878 let (a, b, _, _) = s.sub_lane_cue_refs(lanes[0])[1];
3879 let cut_text = s.subtitles()[0].cues[1].text.clone();
3880 let from = (a as f64 * fps / 1e6).round() as u32;
3881 let len = ((b - a) as f64 * fps / 1e6).round().max(1.0) as u32;
3882 s.cut_regions(&[(from, len)], &lanes).expect("cut the second cue");
3883
3884 let s = srv.session.as_ref().expect("session");
3885 let (project, meta) = s.export_snapshot();
3886 let drawn = engine::export::burn_cues(&project, 0, meta.frame_rate).expect("track 0");
3887 let texts: Vec<&str> = drawn.iter().map(|c| c.text.as_str()).collect();
3888 assert!(texts.contains(&"Hello there"), "the retyped cue is not burned: {texts:?}");
3889 assert!(!texts.contains(&cut_text.as_str()), "the cut cue still burns: {texts:?}");
3890 assert!(drawn.windows(2).all(|w| w[0].start_us <= w[1].start_us), "cues out of order");
3891 }
3892
3893 /// A mono clip under a stereo clip: the mix takes the widest source's channel count, so
3894 /// a stereo clip makes the timeline stereo. The output is stereo and audible in both
3895 /// clips' spans (the mono clip first, the stereo clip one second in).
3896 #[test]
3897 fn a_stereo_clip_makes_the_timeline_stereo() {
3898 engine::ao::set_silent_output();
3899 let root = env!("CARGO_MANIFEST_DIR");
3900 let mono = format!("{root}/../../assets/test_seek_chirp.mkv");
3901 let stereo = format!("{root}/../../assets/test_av1_grain.mkv");
3902 let dir = scratch("channels");
3903 let out = dir.join("c.wav");
3904 let mut srv = Server::new();
3905 srv.session = Some(engine::PlaybackSession::open(&mono).expect("open the mono source"));
3906 let s = srv.session.as_mut().expect("session");
3907 s.import(Path::new(&stereo)).expect("import the stereo source");
3908 s.place_stream_at(0.0, Path::new(&stereo), 0, Some(engine::project::Lane::A1))
3909 .expect("place the stereo source on A1");
3910 let started = export_start(&mut srv, &json!({"out": out.display().to_string()}));
3911 assert!(!started.is_error, "{}", started.text);
3912
3913 let deadline = Instant::now() + Duration::from_secs(120);
3914 while srv.jobs[0].outcome.is_none() {
3915 assert!(Instant::now() < deadline, "export did not finish in 120s");
3916 export_status(&mut srv, &json!({ "job": 1 }));
3917 std::thread::sleep(Duration::from_millis(100));
3918 }
3919 assert!(matches!(srv.jobs[0].outcome, Some(Ok(()))), "{:?}", srv.jobs[0].outcome);
3920 let (audio, chunks) = engine::AudioSession::open(&out)
3921 .expect("reopen the export")
3922 .expect("the export has audio");
3923 assert_eq!(audio.channels, 2, "a stereo clip makes the timeline stereo");
3924 let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
3925 let rate = f64::from(audio.sample_rate) * f64::from(audio.channels);
3926 let rms = |from: f64, to: f64| {
3927 // Interleaved samples: `rate` counts every channel, so one second is `rate` samples.
3928 let at = |secs: f64| (secs * rate) as usize;
3929 let window = &samples[at(from).min(samples.len())..at(to).min(samples.len())];
3930 assert!(!window.is_empty(), "no samples in [{from}, {to})");
3931 (window.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>() / window.len() as f64)
3932 .sqrt()
3933 };
3934 let (mono_clip, stereo_clip) = (rms(0.05, 0.95), rms(1.05, 1.95));
3935 assert!(mono_clip > 0.01, "the mono clip is audible: {mono_clip}");
3936 assert!(stereo_clip > 0.01, "the stereo clip is audible: {stereo_clip}");
3937 }
3938
3939 #[test]
3940 fn an_out_folder_that_cannot_take_a_file_is_refused_up_front() {
3941 let mut srv = burn_session();
3942 let r = export_start(&mut srv, &json!({"out": "/proc/nope.mp4"}));
3943 assert!(r.is_error && r.text.contains("cannot create files in"), "{}", r.text);
3944 assert!(srv.jobs.is_empty(), "a refused export starts no job");
3945 }
3946
3947 /// The first stream's value of one ffprobe field, for a finished file.
3948 fn probe_field(path: &Path, section: &str, entry: &str) -> String {
3949 let out = std::process::Command::new("ffprobe")
3950 .args(["-v", "error", "-select_streams", "v:0", "-show_entries", &format!("{section}={entry}"), "-of", "csv=p=0"])
3951 .arg(path)
3952 .output()
3953 .expect("run ffprobe");
3954 String::from_utf8_lossy(&out.stdout).trim().to_string()
3955 }
3956
3957 #[test]
3958 fn chapters_are_written_counted_and_left_out_on_request() {
3959 engine::ao::set_silent_output();
3960 let src = small_clip();
3961 let dir = scratch("chapters");
3962 let mut srv = Server::new();
3963 let mut session = PlaybackSession::open(Path::new(&src)).expect("open the source");
3964 for (frame, title) in [(0, "Intro"), (10, "Middle"), (20, "End")] {
3965 session.add_chapter(frame, title).expect("add a chapter");
3966 }
3967 srv.session = Some(session);
3968 let out = dir.join("c.mp4");
3969 let r = export_start(&mut srv, &json!({"out": out.display().to_string(), "range": {"from": 0, "to": 1}}));
3970 assert!(!r.is_error, "{}", r.text);
3971 assert!(r.text.contains("\n3 chapters"), "{}", r.text);
3972 assert_eq!(r.structured.as_deref().unwrap()["chapters"], json!(3), "{}", r.text);
3973 finish_job(&mut srv, 1);
3974
3975 let off = dir.join("off.mp4");
3976 let r = export_start(&mut srv, &json!({"out": off.display().to_string(), "range": {"from": 0, "to": 1}, "chapters": false}));
3977 assert!(!r.is_error, "{}", r.text);
3978 assert!(r.text.contains("chapters: left out"), "{}", r.text);
3979 assert_eq!(r.structured.as_deref().unwrap()["chapters"], json!(0), "{}", r.text);
3980 finish_job(&mut srv, 2);
3981
3982 let wav = dir.join("tone.wav");
3983 let r = export_start(&mut srv, &json!({"out": wav.display().to_string(), "range": {"from": 0, "to": 1}}));
3984 assert!(!r.is_error, "{}", r.text);
3985 assert!(r.text.contains("chapters are not written"), "{}", r.text);
3986 }
3987
3988 #[test]
3989 fn chapters_markers_writes_the_comment_markers_as_the_chapter_list() {
3990 use engine::project::{Marker, MarkerColor};
3991 engine::ao::set_silent_output();
3992 let src = small_clip();
3993 let dir = scratch("marker-chapters");
3994 let mut srv = Server::new();
3995 let mut session = PlaybackSession::open(Path::new(&src)).expect("open the source");
3996 session.add_chapter(0, "Only chapter").expect("add a chapter");
3997 for (frame, name) in [(0, "Intro"), (0, "Same frame"), (10, "Middle")] {
3998 let m = Marker { frame, length: 0, name: name.into(), note: String::new(), color: MarkerColor::Red };
3999 session.add_marker(m).expect("add a marker");
4000 }
4001 // Two markers on one frame are one chapter: the first of them.
4002 assert_eq!(session.marker_list_ns(None).iter().map(|c| c.1.as_str()).collect::<Vec<_>>(), ["Intro", "Middle"]);
4003 srv.session = Some(session);
4004 let out = dir.join("m.mp4");
4005 let r = export_start(&mut srv, &json!({"out": out.display().to_string(), "range": {"from": 0, "to": 1}, "chapters": "markers"}));
4006 assert!(!r.is_error, "{}", r.text);
4007 assert!(r.text.contains("2 chapters (from the markers)"), "{}", r.text);
4008 finish_job(&mut srv, 1);
4009 let bad = export_start(&mut srv, &json!({"out": dir.join("x.mp4").display().to_string(), "chapters": "all"}));
4010 assert!(bad.is_error && bad.text.contains("not true, false or"), "{}", bad.text);
4011 }
4012
4013 #[test]
4014 fn bit_depth_ten_is_refused_outside_av1_and_hevc_and_named_in_words() {
4015 engine::ao::set_silent_output();
4016 let src = small_clip();
4017 let dir = scratch("bit-depth");
4018 let mut srv = Server::new();
4019 srv.session = Some(PlaybackSession::open(Path::new(&src)).expect("open the source"));
4020 let r = export_start(&mut srv, &json!({"out": dir.join("h.mp4").display().to_string(), "bit_depth": 10}));
4021 assert!(r.is_error, "{}", r.text);
4022 assert!(
4023 r.text.contains("10-bit export is AV1 and HEVC only: format av1 (.mkv), av1-mp4, hevc (.mkv) or hevc-mp4, not mp4"),
4024 "{}",
4025 r.text
4026 );
4027 assert!(srv.jobs.is_empty(), "a refused export starts no job");
4028
4029 let r = export_start(&mut srv, &json!({"out": dir.join("b.mp4").display().to_string(), "bit_depth": 9}));
4030 assert!(r.is_error && r.text.contains("bit_depth 9 is not 8 or 10"), "{}", r.text);
4031
4032 let out = dir.join("ten.mp4");
4033 let r = export_start(&mut srv, &json!({
4034 "out": out.display().to_string(), "format": "av1-mp4", "bit_depth": 10, "range": {"from": 0, "to": 1}
4035 }));
4036 assert!(!r.is_error, "{}", r.text);
4037 assert!(r.text.contains("output 10-bit, as asked"), "{}", r.text);
4038 assert_eq!(r.structured.as_deref().unwrap()["bit_depth"], json!(10), "{}", r.text);
4039 finish_job(&mut srv, 1);
4040 assert_eq!(probe_field(&out, "stream", "pix_fmt"), "yuv420p10le");
4041
4042 let hevc = dir.join("ten-hevc.mp4");
4043 let r = export_start(&mut srv, &json!({
4044 "out": hevc.display().to_string(), "format": "hevc-mp4", "bit_depth": 10, "seat": "software", "range": {"from": 0, "to": 1}
4045 }));
4046 assert!(!r.is_error, "{}", r.text);
4047 assert!(r.text.contains("output 10-bit, as asked"), "{}", r.text);
4048 assert_eq!(r.structured.as_deref().unwrap()["bit_depth"], json!(10), "{}", r.text);
4049 finish_job(&mut srv, 2);
4050 assert_eq!(probe_field(&hevc, "stream", "pix_fmt"), "yuv420p10le");
4051 assert_eq!(probe_field(&hevc, "stream", "profile"), "Main 10");
4052
4053 let r = export_start(&mut srv, &json!({"out": dir.join("h264.mp4").display().to_string(), "format": "mp4", "bit_depth": 10}));
4054 assert!(r.is_error && r.text.contains("AV1 and HEVC only"), "{}", r.text);
4055 }
4056}
4057
4058#[cfg(test)]
4059mod size_tests {
4060 use super::*;
4061
4062 /// Sizes are decimal (MB = 10^6 bytes), the unit media_probe prints, so one file reads the same
4063 /// in both replies: 12,139,083 bytes is 12.1 MB, not 11.6 MiB.
4064 #[test]
4065 fn export_sizes_use_decimal_units() {
4066 assert_eq!(human_bytes(12_139_083), "12.1 MB");
4067 assert_eq!(human_bytes(999), "999 B");
4068 assert_eq!(human_bytes(1_500), "1.5 KB");
4069 assert_eq!(human_bytes(1_000_000), "1.0 MB");
4070 }
4071
4072}