forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

export_ui.rs2112 lines, 80.4 KiBHistoryRawDownload
1//! What the export card offers and what it writes.
2
3use crate::*;
4
5/// The project resolutions the project-resolution list offers, largest area
6/// first. A short list of the sizes people name, landscape and the two
7/// phone-and-square shapes ([`NEW_SIZES`] offers the same ones on a new
8/// project); the media's own is cycled in beside them, which is what makes the
9/// trip round come back to where it started.
10pub(crate) const RESOLUTIONS: [(u32, u32); 7] = [
11 (3840, 2160),
12 (2560, 1440),
13 (1920, 1080),
14 (1080, 1920),
15 (1080, 1080),
16 (1280, 720),
17 (854, 480),
18];
19
20/// A size's name in the list, plain words: the height for a landscape frame
21/// (`1080p`), the two numbers for a tall or square one (`1080×1920`), which a
22/// `p` would misname.
23pub(crate) fn size_name(w: u32, h: u32) -> String {
24 match w > h {
25 true => format!("{h}p"),
26 false => format!("{w}\u{d7}{h}"),
27 }
28}
29
30/// A size's row label in the list: [`size_name`], with the shape said for a
31/// tall or square frame -- `1080×1920 (vertical 9:16)`, `1080×1080 (square)`.
32pub(crate) fn size_row_label(w: u32, h: u32) -> String {
33 match (w > h, w == h, w * 16 == h * 9) {
34 (true, _, _) => size_name(w, h),
35 (_, true, _) => format!("{w}\u{d7}{h} (square)"),
36 (_, _, true) => format!("{w}\u{d7}{h} (vertical 9:16)"),
37 _ => format!("{w}\u{d7}{h} (vertical)"),
38 }
39}
40
41/// The project frame rates the list offers, slowest first: the rates footage is
42/// actually shot and delivered at, the NTSC ones written as the ratios they are
43/// (`24000/1001`, not `23.976`) -- the engine conforms the timeline to the very
44/// number it is handed, so a rate rounded here would be a rate no timescale can
45/// name. The media's own is cycled in beside them
46/// ([`frame_rate_ladder`]), which is what keeps the way back on the list.
47pub(crate) const FRAME_RATES: [f64; 8] = [
48 24_000. / 1001.,
49 24.,
50 25.,
51 30_000. / 1001.,
52 30.,
53 50.,
54 60_000. / 1001.,
55 60.,
56];
57
58/// The project sound rates the list offers, slowest first. Unlike
59/// [`RESOLUTIONS`] and [`FRAME_RATES`] there is no media rate to cycle in
60/// beside them: a source's own rate is not a number this list has to name to
61/// offer it, since [`Choice::SampleRate`]`(None)` -- "source" -- already means
62/// exactly that, whatever the number turns out to be.
63pub(crate) use engine::playback::SAMPLE_RATES;
64
65/// The sound-rate list's rows: "source" first -- the derived rate, and the
66/// row in force with nothing picked -- then every rate on offer, the one in
67/// force marked. The same rows serve [`Pick::SampleRate`] with a session and
68/// without one: `current` is [`PlaybackSession::sample_rate`] or
69/// [`Player::pending_settings`]`.2`, and `None` means the same thing either
70/// way -- nothing picked yet.
71pub(crate) fn sample_rate_choices(current: Option<u32>) -> Vec<ChoiceRow> {
72 let mut rows = vec![(
73 Choice::SampleRate(None),
74 "Match source".into(),
75 // A state word, the resolution list's rule: the six-word phrase this
76 // row wore ran past `MENU_W` and was cut mid-word like the size
77 // list's was. Nothing is resampled -- that is what the row means.
78 "unchanged".into(),
79 current.is_none(),
80 )];
81 rows.extend(SAMPLE_RATES.into_iter().map(|rate| {
82 (
83 Choice::SampleRate(Some(rate)),
84 format!("{rate} Hz").into(),
85 match rate {
86 48_000 => "video standard".to_string(),
87 44_100 => "CD/audio standard".to_string(),
88 _ => "high-resolution".to_string(),
89 }
90 .into(),
91 current == Some(rate),
92 )
93 }));
94 rows
95}
96
97/// The export card's format rows: the key that picks one, its name, and what it
98/// writes -- or, where this program cannot write it, the reason it cannot. A
99/// format with no entry at all would read as an oversight, and a menu of three
100/// as a claim that nothing else exists -- so the refusals are rows too, dimmed
101/// and unclickable.
102///
103/// `None` is exactly that kind of row, and there are two left. MP3 stopped
104/// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL
105/// `shine-rs` was the licence question, and it is not the only encoder any
106/// more), and HEVC stopped being one when this project gained a pure-Rust
107/// H.265 encoder — an *intra-only* one, which the rows say rather than let a
108/// user find out from the size of the file. VP9 and VP8 are the ones this program
109/// still only *reads*: the plugin decodes them and there is no encoder for
110/// either here, so they are rows for the reason the refusals are rows at all —
111/// a codec that opens but never comes back out is exactly the gap a user
112/// would otherwise go looking for. AAC is not a row at all: it is what both
113/// containers' sound *is*, never a file of its own.
114///
115/// A codec is one row, and the boxes it can be written into are the row's
116/// containers: the same AV1 picture and the same AAC track go into a Matroska
117/// file or into an mp4, and which one a user needs is about what has to play
118/// the file, not about the encode. So the container is asked *once*, in a row
119/// of its own, and only where there is more than one to ask about -- five
120/// picture rows to read past were four of them saying the same codec twice.
121pub(crate) const FORMATS: [(&[Format], &str, &str, &str); 12] = [
122 (
123 &[Format::Mp4],
124 "m",
125 "H.264",
126 "plays everywhere · AAC sound · MP4 only",
127 ),
128 (
129 &[Format::Av1, Format::Av1Mp4],
130 "a",
131 "AV1",
132 "smallest file for the picture · AAC sound",
133 ),
134 (
135 &[Format::Hevc, Format::HevcMp4],
136 "h",
137 "HEVC",
138 "I+P GOPs in software — far smaller than intra-only",
139 ),
140 (&[Format::Wav], "w", "WAV", "16-bit PCM — audio only"),
141 (&[Format::Flac], "f", "FLAC", "lossless — audio only"),
142 (&[Format::Mp3], "p", "MP3", "MPEG-1 Layer III — audio only"),
143 (
144 &[Format::Ogg],
145 "o",
146 "Ogg",
147 "Vorbis — variable quality, stereo",
148 ),
149 (
150 &[Format::Opus],
151 "u",
152 "Opus",
153 "Opus in an Ogg file — voice and podcasts, small",
154 ),
155 (&[Format::Still, Format::PngSequence], "s", "PNG", "lossless pictures · no sound"),
156 (&[Format::Gif], "i", "GIF", "animated · 256 colours · no sound"),
157 (&[], "", "VP9", "AV1 above replaces it"),
158 (&[], "", "VP8", "AV1 above replaces it"),
159];
160
161/// The boxes one codec may be written into, in the order its container row
162/// cycles them. Empty for a codec this program cannot write at all.
163/// Not on the export moment any more: the Settings surface is what shows
164/// this (`ui::settings_stance`). Kept and named rather than deleted -- the
165/// state and its setter are the same ones the moment used to drive.
166#[allow(dead_code)]
167pub(crate) fn containers(format: Format) -> &'static [Format] {
168 FORMATS
169 .into_iter()
170 .map(|(row, ..)| row)
171 .find(|row| row.contains(&format))
172 .unwrap_or(&[])
173}
174
175/// This row's format under the container `current` is already in, or the row's
176/// first when it has no such box: an AV1 picked from a WAV lands in Matroska,
177/// and picked from an mp4 stays in the mp4.
178/// Not on the export moment any more: the Settings surface is what shows
179/// this (`ui::settings_stance`). Kept and named rather than deleted -- the
180/// state and its setter are the same ones the moment used to drive.
181#[allow(dead_code)]
182pub(crate) fn same_box(row: &[Format], current: Format) -> Option<Format> {
183 row.iter()
184 .copied()
185 .find(|f| f.ext() == current.ext())
186 .or_else(|| row.first().copied())
187}
188
189/// The next box for the same codec, wrapping -- what the container row's key
190/// does. The format itself for a codec with only one, so the stroke cannot
191/// change what it is not offering.
192/// Not on the export moment any more: the Settings surface is what shows
193/// this (`ui::settings_stance`). Kept and named rather than deleted -- the
194/// state and its setter are the same ones the moment used to drive.
195#[allow(dead_code)]
196pub(crate) fn next_container(format: Format) -> Format {
197 let row = containers(format);
198 let at = row.iter().position(|&f| f == format).unwrap_or(0);
199 row.get((at + 1) % row.len().max(1))
200 .copied()
201 .unwrap_or(format)
202}
203
204/// What one of the colour card's own strokes does. Its keys are card-local --
205/// they mean nothing outside it -- so they are a table here rather than keymap
206/// bindings, exactly as the export card's format initials are. Listed in
207/// `keymap::FIXED` all the same, which is how the keys menu still says so.
208pub(crate) enum ColorKey {
209 Close,
210 /// Steps down the four sliders, wrapping.
211 Band(usize),
212 /// Moves the picked slider, in [`COLOR_STEP`]s.
213 Nudge(f32),
214 Reset,
215}
216
217/// Why the silence card has nothing to scan on that clip, in its own voice: the
218/// lane and index the user picked, the file it is of, and which of the two
219/// soundless things it is. One place, because a still and a silent video are
220/// the same answer to the same question -- "a box with a larger size than it"
221/// is what the *demuxer* would say about a png, and it is not an answer.
222///
223/// Costs nothing: the scan reads a file and writes marks, so a refusal here
224/// leaves the project (and its undo history) exactly where it was.
225pub(crate) fn unscannable(lane: Lane, idx: usize, path: &Path) -> String {
226 let what = match engine::is_image(path) {
227 true => "is a picture",
228 false => "is silent",
229 };
230 format!(
231 "{} clip {} has no audio to scan — {} {what}",
232 lane.label(),
233 idx + 1,
234 file_name(path)
235 )
236}
237
238/// The half of a take whose *sound* the silence card scans: a link is one span
239/// on however many lanes, so a card opened on the picture opens on the sound it
240/// is grouped with. That is the lane the waveform is drawn on, and so the lane
241/// the marks have to land on to be read against it -- and the ranges agree,
242/// because a group is one span.
243///
244/// The clip itself for one already on an audio lane, for a detached picture,
245/// and for a take whose sound is not on any lane: there is nothing better to
246/// open on, and the refusal for a source with no audio at all is `scan`'s.
247pub(crate) fn audio_half(session: &PlaybackSession, (lane, idx): (Lane, usize)) -> (Lane, usize) {
248 if lane.kind == LaneKind::Audio {
249 return (lane, idx);
250 }
251 let Some(link) = session.lane_clips(lane).get(idx).and_then(|c| c.link) else {
252 return (lane, idx);
253 };
254 session
255 .lanes()
256 .into_iter()
257 .filter(|l| l.kind == LaneKind::Audio)
258 .find_map(|l| {
259 session
260 .lane_clips(l)
261 .iter()
262 .position(|c| c.link == Some(link))
263 .map(|i| (l, i))
264 })
265 .unwrap_or((lane, idx))
266}
267
268/// The member of a caption's group on a media lane of the wanted kind: what a
269/// card that is about media opens on when the hand is on the caption pinned to
270/// it. `None` for a caption in no group with clips -- there are no pictures or
271/// sound behind the words to be reaching at, and the card that opened anyway
272/// would be a card of settings nothing plays.
273pub(crate) fn caption_media_half(
274 session: &PlaybackSession,
275 (lane, idx): (Lane, usize),
276 kind: LaneKind,
277) -> Option<(Lane, usize)> {
278 let link = session.sub_lane(lane).get(idx).and_then(|s| s.link)?;
279 session
280 .lanes()
281 .into_iter()
282 .filter(|l| l.kind == kind)
283 .find_map(|l| {
284 session
285 .lane_clips(l)
286 .iter()
287 .position(|c| c.link == Some(link))
288 .map(|i| (l, i))
289 })
290}
291
292pub(crate) fn color_key(key: &str) -> Option<ColorKey> {
293 Some(match key {
294 ESCAPE => ColorKey::Close,
295 "down" => ColorKey::Band(1),
296 "up" => ColorKey::Band(COLOR_BANDS.len() - 1),
297 "right" => ColorKey::Nudge(1.),
298 "left" => ColorKey::Nudge(-1.),
299 "r" => ColorKey::Reset,
300 _ => return None,
301 })
302}
303
304/// The band'th control of a grade, to read or to write. The order is
305/// [`COLOR_BANDS`]', which is the order the card lists them in.
306pub(crate) fn band_mut(params: &mut ColorParams, band: usize) -> &mut f32 {
307 match band {
308 0 => &mut params.brightness,
309 1 => &mut params.contrast,
310 2 => &mut params.saturation,
311 _ => &mut params.tint,
312 }
313}
314
315/// Every fit policy, in the order the list offers them.
316pub(crate) const FITS: [FitPolicy; 4] = [
317 FitPolicy::Fit,
318 FitPolicy::Fill,
319 FitPolicy::Stretch,
320 FitPolicy::Center,
321];
322
323/// What the easing list calls one: the words an editor uses for the curve.
324pub(crate) fn ease_label(ease: engine::transform::KeyEase) -> &'static str {
325 use engine::transform::KeyEase;
326 match ease {
327 KeyEase::Linear => "Linear",
328 KeyEase::EaseIn => "Ease in",
329 KeyEase::EaseOut => "Ease out",
330 KeyEase::Ease => "Ease in-out",
331 KeyEase::Hold => "Hold",
332 KeyEase::Bezier(_) => "Custom curve",
333 }
334}
335
336/// What a person calls one, said as what it does to the picture.
337pub(crate) fn fit_label(fit: FitPolicy) -> &'static str {
338 match fit {
339 FitPolicy::Fit => "fit (whole picture, bars)",
340 FitPolicy::Fill => "fill (cropped, no bars)",
341 FitPolicy::Stretch => "stretch (aspect broken)",
342 FitPolicy::Center => "centre (1:1, no resample)",
343 }
344}
345
346/// Every project resolution on offer, largest first: [`RESOLUTIONS`] with the
347/// media's own size cycled in at its place by size -- so a project already at a
348/// listed size does not see it twice, and the media's own shape, whatever it is,
349/// is always on the list. The one order both the stroke and the list use.
350pub(crate) fn resolution_ladder(native: (u32, u32)) -> Vec<(u32, u32)> {
351 let mut sizes: Vec<(u32, u32)> = RESOLUTIONS.to_vec();
352 if !sizes.contains(&native) {
353 // By area, descending, like the list itself: the cycle then reads as one
354 // ladder rather than a list with a stray rung at the end.
355 let at = sizes
356 .iter()
357 .position(|&(w, h)| {
358 u64::from(w) * u64::from(h) < u64::from(native.0) * u64::from(native.1)
359 })
360 .unwrap_or(sizes.len());
361 sizes.insert(at, native);
362 }
363 sizes
364}
365
366/// The resolution list's rows: every rung of the ladder, the media's own said
367/// so, and the one in force marked. A size is named by its height the way the
368/// button that opens the list names it, with the full figure beside it.
369pub(crate) fn resolution_choices(current: (u32, u32), native: (u32, u32)) -> Vec<ChoiceRow> {
370 resolution_ladder(native)
371 .into_iter()
372 .map(|(w, h)| {
373 (
374 Choice::Size(w, h),
375 size_row_label(w, h).into(),
376 match (w > h, (w, h) == native) {
377 // Plain words (DESIGN §8): a landscape row's size is its
378 // detail, and the media's own size says what it matches. A
379 // tall or square row already names its shape in its label.
380 (true, true) => format!("{w}\u{d7}{h} (matches your media)"),
381 (true, false) => format!("{w}\u{d7}{h}"),
382 (false, true) => "matches your media".to_string(),
383 (false, false) => String::new(),
384 }
385 .into(),
386 (w, h) == current,
387 )
388 })
389 .collect()
390}
391
392/// The resolution list's rows before any file is open: [`RESOLUTIONS`] plain,
393/// with nothing marked unless a pick is already held
394/// ([`Player::pending_settings`]) -- there is no media size to cycle in
395/// beside them yet ([`resolution_choices`]'s `native`).
396pub(crate) fn pending_resolution_choices(pending: Option<(u32, u32)>) -> Vec<ChoiceRow> {
397 RESOLUTIONS
398 .into_iter()
399 .map(|(w, h)| {
400 (
401 Choice::Size(w, h),
402 size_row_label(w, h).into(),
403 match w > h {
404 true => format!("{w}x{h}"),
405 false => String::new(),
406 }
407 .into(),
408 Some((w, h)) == pending,
409 )
410 })
411 .collect()
412}
413
414/// [`pending_resolution_choices`]'s sibling for the rate list.
415pub(crate) fn pending_fps_choices(pending: Option<f64>) -> Vec<ChoiceRow> {
416 FRAME_RATES
417 .into_iter()
418 .map(|fps| {
419 (
420 Choice::Fps(fps),
421 fps_row_label(fps).into(),
422 String::new().into(),
423 Some(fps) == pending,
424 )
425 })
426 .collect()
427}
428
429/// Every project frame rate on offer, slowest first: [`FRAME_RATES`] with the
430/// media's own cycled in at its place by speed, so a project already cut at a
431/// listed rate does not see it twice and the media's own rate -- the one a
432/// project moved off it has no other way back to -- is always there.
433/// [`resolution_ladder`]'s rule, for the other setting the project has of its
434/// own.
435pub(crate) fn frame_rate_ladder(native: f64) -> Vec<f64> {
436 let mut rates = FRAME_RATES.to_vec();
437 // Bit for bit: 23.976023976... is not 23.976, and a rate that read as
438 // "already listed" when it is not would take the media's own off the list.
439 if !rates.contains(&native) {
440 let at = rates
441 .iter()
442 .position(|&fps| fps > native)
443 .unwrap_or(rates.len());
444 rates.insert(at, native);
445 }
446 rates
447}
448
449/// The rate list's rows: every rung of the ladder, the media's own said so, and
450/// the one in force marked. Named as a person writes a rate ([`fps_label`]),
451/// with what it is for beside it -- short, or the row loses its tail to the
452/// truncation the resolution list already met.
453pub(crate) fn fps_choices(current: f64, native: f64) -> Vec<ChoiceRow> {
454 frame_rate_ladder(native)
455 .into_iter()
456 .map(|fps| {
457 (
458 Choice::Fps(fps),
459 fps_row_label(fps).into(),
460 match fps == native {
461 true => "Match the media".to_string(),
462 false => String::new(),
463 }
464 .into(),
465 fps == current,
466 )
467 })
468 .collect()
469}
470
471/// The fit list's rows: all four policies against the canvas they place a
472/// picture on, since the word alone ("fill") says nothing about the size it is
473/// filling -- which is the very thing the notice says after a stroke.
474pub(crate) fn fit_choices(
475 lane: Lane,
476 idx: usize,
477 current: FitPolicy,
478 (w, h): (u32, u32),
479) -> Vec<ChoiceRow> {
480 FITS.into_iter()
481 .map(|fit| {
482 (
483 Choice::Fit(lane, idx, fit),
484 fit_label(fit).into(),
485 // The canvas alone, worded as the resolution list words a size:
486 // the policy names are long and anything wordier here loses its
487 // tail to the truncation.
488 format!("{w}x{h}").into(),
489 fit == current,
490 )
491 })
492 .collect()
493}
494
495/// The sound-rate list's rows: every offered rate, the one in force marked, and
496/// what each buys said in the fewest words that fit beside the label (a longer
497/// phrase loses its tail to `MENU_W`'s truncation, as the two lists above say).
498pub(crate) fn audio_rate_choices(current: u32) -> Vec<ChoiceRow> {
499 AUDIO_KBPS
500 .into_iter()
501 .enumerate()
502 .map(|(n, kbps)| {
503 (
504 Choice::AudioRate(kbps),
505 format!("{kbps} kb/s").into(),
506 match (kbps, n) {
507 (DEFAULT_AUDIO_KBPS, _) => "the default",
508 (_, 0) => "smallest file",
509 (k, _) if k < DEFAULT_AUDIO_KBPS => "smaller file",
510 _ => "better sound",
511 }
512 .into(),
513 kbps == current,
514 )
515 })
516 .collect()
517}
518
519/// The seats in the order every list and chip row shows them: Software first,
520/// the GUI's default seat, then the two that may open the GPU encoder.
521pub(crate) const ENCODER_SEATS: [EncoderSeat; 3] =
522 [EncoderSeat::Software, EncoderSeat::Auto, EncoderSeat::Hardware];
523
524/// How a seat is named where a person reads it: the export sheet's rows,
525/// Settings' chips and the notice all say the same word
526/// ([`engine::export::EncoderSeat`]), and [`encoder_note`] says what it does.
527pub(crate) fn encoder_label(seat: EncoderSeat) -> &'static str {
528 match seat {
529 EncoderSeat::Auto => "Auto",
530 EncoderSeat::Hardware => "Hardware",
531 EncoderSeat::Software => "Software",
532 }
533}
534
535/// What a seat does, in the fewest words: the same note beside the export
536/// sheet's row and under Settings' chips.
537pub(crate) fn encoder_note(seat: EncoderSeat) -> &'static str {
538 match seat {
539 EncoderSeat::Auto => "GPU encoder if any",
540 EncoderSeat::Hardware => "GPU encoder or fail",
541 EncoderSeat::Software => "software encoder, always",
542 }
543}
544
545/// The encoder list's rows: all three seats, the one in force marked, and what
546/// each one *does* beside it -- in the fewest words that fit inside `MENU_W`,
547/// the truncation every list above already met. Always offered, whatever this
548/// machine has: a row that vanished with the plugin would be a setting nobody
549/// could find, and the answer to "is there a seat here?" is the planned line
550/// under the rows ([`engine::export::planned_video`]), which is measured.
551pub(crate) fn encoder_choices(current: EncoderSeat) -> Vec<ChoiceRow> {
552 EncoderSeat::ALL
553 .into_iter()
554 .map(|seat| {
555 (
556 Choice::Encoder(seat),
557 encoder_label(seat).into(),
558 encoder_note(seat).into(),
559 seat == current,
560 )
561 })
562 .collect()
563}
564
565/// The row under the encoder one where -- and only where -- a person has asked
566/// for the GPU on an AV1 export: this project's own driver reset the GPU on the
567/// vendored AV1 encoder (2026-08-10), so the pick is theirs to make and the
568/// risk is theirs to be told about. `None` for every other pair, which is what
569/// keeps this from becoming a row nobody reads.
570/// Not on the export moment any more: the Settings surface is what shows
571/// this (`ui::settings_stance`). Kept and named rather than deleted -- the
572/// state and its setter are the same ones the moment used to drive.
573#[allow(dead_code)]
574pub(crate) fn av1_hw_warning(format: Format, seat: EncoderSeat) -> Option<&'static str> {
575 (seat == EncoderSeat::Hardware && matches!(format, Format::Av1 | Format::Av1Mp4))
576 .then_some("AV1 on the GPU reset this machine's driver once — Software is the safe choice")
577}
578
579/// How a rendition is named where a person reads it: the panel button, the
580/// notice and the list row all say the same word ([`engine::tonemap::Preset`]).
581pub(crate) fn tone_label(preset: Preset) -> &'static str {
582 match preset {
583 Preset::Reference => "Faithful",
584 Preset::Standard => "Balanced",
585 Preset::Vivid => "Bright",
586 }
587}
588
589/// The HDR list's rows: all three renditions, the one in force marked, and what
590/// each one *is* beside it -- in the fewest words that fit inside `MENU_W`, the
591/// truncation the three lists above already met. Always offered, whatever is on
592/// the timeline: a setting that appeared and vanished with the media would be a
593/// setting nobody could find, and the row says who it acts on instead.
594pub(crate) fn tone_choices(current: Preset) -> Vec<ChoiceRow> {
595 Preset::ALL
596 .into_iter()
597 .map(|preset| {
598 (
599 Choice::Tone(preset),
600 tone_label(preset).into(),
601 match preset {
602 Preset::Reference => "true to the standard",
603 Preset::Standard => "like a normal player",
604 Preset::Vivid => "brightest, richer colour",
605 }
606 .into(),
607 preset == current,
608 )
609 })
610 .collect()
611}
612
613/// A frame rate as a person writes it: `30`, not `30.000`, and `23.976` for the
614/// rate that is a ratio.
615/// A rate's row label as a person names it: the number and "fps", and for the
616/// NTSC ratios (23.976, 29.97, 59.94) what the rate is for -- "29.97 fps (NTSC
617/// video)" -- so the ratio is never a bare number nobody can place.
618pub(crate) fn fps_row_label(fps: f64) -> String {
619 let base = format!("{} fps", fps_label(fps));
620 match (fps - fps.round()).abs() < 0.001 {
621 true => base,
622 false => match fps < 25. {
623 true => format!("{base} (NTSC film)"),
624 false => format!("{base} (NTSC video)"),
625 },
626 }
627}
628
629pub(crate) fn fps_label(fps: f64) -> String {
630 match (fps - fps.round()).abs() < 0.001 {
631 true => format!("{fps:.0}"),
632 false => format!("{fps:.3}")
633 .trim_end_matches('0')
634 .trim_end_matches('.')
635 .to_string(),
636 }
637}
638
639/// The budget itself, in Mbps to one decimal: the number the lever reads.
640pub(crate) fn rate_label(bps: u64) -> String {
641 format!("{:.1}", bps as f64 / 1e6)
642}
643
644/// How fast this computer last wrote a file, in media seconds per wall second.
645/// Kept in memory for this session only. Zero until one export has landed.
646static MEASURED_PACE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
647
648/// Remembers the pace of a finished export. A cancelled or failed one says
649/// nothing about the machine, so the caller passes only the ones that landed.
650pub(crate) fn note_pace(media_seconds: f64, wall_seconds: f64) {
651 if media_seconds > 0. && wall_seconds > 0. {
652 let pace = media_seconds / wall_seconds;
653 MEASURED_PACE.store(pace.to_bits(), std::sync::atomic::Ordering::Relaxed);
654 }
655}
656
657/// The pace the last finished export measured, if one has: the time estimate
658/// never invents one (a guess of "real time" was off by 5x either way).
659pub(crate) fn measured_pace() -> Option<f64> {
660 match MEASURED_PACE.load(std::sync::atomic::Ordering::Relaxed) {
661 0 => None,
662 bits => Some(f64::from_bits(bits)),
663 }
664}
665
666/// How long writing `media_seconds` of film is expected to take at a measured
667/// `pace`, in words a person plans around. Never "0 s": a job that rounds to
668/// nothing says "about 1 s". `None` pace is "estimating…", not a number.
669pub(crate) fn time_words(media_seconds: f64, pace: Option<f64>) -> String {
670 let Some(pace) = pace.filter(|p| *p > 0. && p.is_finite()) else {
671 return "estimating\u{2026}".to_string();
672 };
673 let secs = (media_seconds.max(0.) / pace).round().max(1.) as u64;
674 match secs {
675 0..90 => format!("about {secs} s"),
676 90..600 => {
677 let r = secs.div_ceil(5) * 5;
678 format!("about {} min {} s", r / 60, r % 60)
679 }
680 _ => format!("about {} min", (secs as f64 / 60.).round() as u64),
681 }
682}
683
684/// What a name that is a source of the project says, under the field and on the
685/// Export button.
686pub(crate) const SOURCE_NAME_TAKEN: &str = "A source file already has this name.";
687
688/// Whether `target` is one of the project's own source files, by name or by
689/// what it resolves to on disk. Writing an export over a source would destroy
690/// the footage the timeline plays from, so the sheet refuses that outright
691/// rather than asking to replace it.
692pub(crate) fn is_a_source(target: &std::path::Path, sources: &[&std::path::Path]) -> bool {
693 let same_file = |a: &std::path::Path| match (std::fs::canonicalize(a), std::fs::canonicalize(target)) {
694 (Ok(a), Ok(b)) => a == b,
695 _ => a == target,
696 };
697 sources.iter().any(|&source| same_file(source))
698}
699
700/// The row a format is picked by, which is what a refusal calls it: the codec,
701/// since the container is a row of its own now -- `AV1`, not the `mkv` such a
702/// file is named with.
703pub(crate) fn format_label(format: Format) -> &'static str {
704 FORMATS
705 .iter()
706 .find(|(row, ..)| row.contains(&format))
707 .map_or("Export", |(_, _, label, _)| *label)
708}
709
710/// The file name a typed stem lands as under a format: `stem.ext`, or the bare folder name for a
711/// numbered run, which is written into a folder named as the stem.
712pub(crate) fn typed_name(stem: &str, format: Format) -> String {
713 if format == Format::PngSequence {
714 stem.to_string()
715 } else {
716 format!("{stem}.{}", format.ext())
717 }
718}
719
720/// The destination under a format: `take.export.mp4` becomes `take.export.wav`.
721/// The stem is untouched, so a name typed into the save dialog survives a
722/// change of mind about the format -- only the extension is the format's to say.
723pub(crate) fn retarget(path: &std::path::Path, format: Format) -> PathBuf {
724 let mut path = path.to_path_buf();
725 // A numbered run is written into a folder named as the destination, so it has no extension.
726 if format == Format::PngSequence {
727 path.set_extension("");
728 return path;
729 }
730 path.set_extension(format.ext());
731 path
732}
733
734/// The moment's one number as the engine takes it. The budget is always
735/// explicit now -- the lever opens on the engine's own automatic figure
736/// ([`auto_bps`]) rather than on nothing, so there is no "Auto" left to send
737/// as `None` -- and the engine clamps it to `MIN_BITRATE..MAX_EXPLICIT_BITRATE`
738/// exactly where [`BPS_MIN`]/[`BPS_MAX`] do, so neither can disagree about the
739/// edges.
740///
741/// The bitrate travels even for an audio format, where the engine ignores it:
742/// one settings value, and a row the moment does not show cannot have been
743/// changed.
744pub(crate) fn export_settings(
745 bitrate: u64,
746 format: Format,
747 audio_kbps: u32,
748 seat: EncoderSeat,
749) -> ExportSettings {
750 ExportSettings {
751 format,
752 // Filled by the session's export path from its chapter markers, which this
753 // free function cannot see; an empty list means "use the project's chapters".
754 chapters: Vec::new(),
755 audio_kbps: Some(audio_kbps),
756 reencode_audio: false,
757 audio_bit_depth: None,
758 bitrate: Some(bitrate),
759 // The copy path (the old `Quality::Exact`) is off this surface: the
760 // moment is one budget, and a copy is the absence of one.
761 // `engine::export` keeps the path and its own tests; nothing in the
762 // app asks for it.
763 exact: false,
764 seat,
765 subtitles: Vec::new(),
766 no_soft_subtitles: false,
767 intra_only: false,
768 keep_source_colour: false,
769 range: None,
770 burn_subtitles: None,
771 size: None,
772 video_bit_depth: None,
773 loudness: None,
774 prores_profile: ProResProfile::default(),
775 hdr: HdrOutput::default(),
776 hevc_speed: None,
777 gif: GifSettings::default(),
778 qp: None,
779 keyframe_s: None,
780 faststart: false,
781 }
782}
783
784/// The same settings with the budget taken out -- what the seat probe is asked
785/// and keyed on ([`crate::Player::cache_export_seat`]). A bitrate does not
786/// decide whether this machine has a VA-API seat or whether the picture's
787/// packets can be copied; leaving it in the key meant every wheel notch on the
788/// budget row invalidated the answer and opened a real VA-API encoder to ask it
789/// again -- measured at ten opens for ten notches, 5-32 ms of GPU work each,
790/// against the player's own decoder, which is the "freezes a little" this row
791/// was reported for.
792pub(crate) fn probe_settings(format: Format, audio_kbps: u32, seat: EncoderSeat) -> ExportSettings {
793 ExportSettings {
794 bitrate: None,
795 ..export_settings(0, format, audio_kbps, seat)
796 }
797}
798
799/// The budget's bounds, the engine's own (`engine::export`'s `MIN_BITRATE`
800/// and `MAX_EXPLICIT_BITRATE`): a number outside them would be written as a
801/// different one, so the lever and the field clamp to exactly these. The floor
802/// is 100 kbps, not a megabit: a sub-Mbps delivery is an export too, and at a
803/// megabit this row could not say `0.6` at all.
804pub(crate) const BPS_MIN: u64 = 100_000;
805pub(crate) const BPS_MAX: u64 = 50_000_000;
806
807/// A wheel notch, and a notch with shift held: 0.1 and 1 Mbps. Five hundred
808/// tenths is not a way across this range, and a tenth is the smallest step
809/// the row's own readout can show.
810pub(crate) const BPS_FINE: u64 = 100_000;
811pub(crate) const BPS_COARSE: u64 = 1_000_000;
812
813/// The engine's automatic figure for a picture of this size and rate
814/// (`engine::export`'s `BITS_PER_PIXEL` rule and the range it clamps the
815/// derived number into), which is what the lever opens on before anybody has
816/// chosen: a budget row reading 0 Mbps -- the old `custom_mbps: 0` default --
817/// was a promise to write an empty file.
818const BITS_PER_PIXEL: f64 = 0.1;
819const BPS_AUTO_MAX: u64 = 20_000_000;
820
821pub(crate) fn auto_bps(width: u32, height: u32, fps: f64) -> u64 {
822 let raw = f64::from(width) * f64::from(height) * fps * BITS_PER_PIXEL;
823 (raw as u64).clamp(BPS_MIN, BPS_AUTO_MAX)
824}
825
826/// What was typed into the budget field, as a rate. Four ways to say one:
827/// `850k` and `6.5M` are rates in their own units, a bare `6.5` is Mbps (the
828/// unit the row reads in), and `1.2G` is a *file size* -- the one thing a
829/// person actually wants to hit -- converted through the exported range and
830/// the sound's own rate into the picture rate that lands there.
831///
832/// Clamped to the engine's bounds rather than refused: the moment shows the
833/// parsed number immediately, so a clamp is visible in the same keystroke.
834/// `None` is only ever "that is not a number".
835pub(crate) fn parse_budget(text: &str, seconds: f64, audio_bps: u64) -> Option<u64> {
836 let text = text.trim().to_ascii_lowercase();
837 let text = text
838 .trim_end_matches("bps")
839 .trim_end_matches('b')
840 .trim_end();
841 let (digits, unit) = match text.chars().last()? {
842 c @ ('k' | 'm' | 'g') => (&text[..text.len() - c.len_utf8()], c),
843 _ => (text, 'm'),
844 };
845 let n: f64 = digits.trim().parse().ok()?;
846 if !n.is_finite() || n <= 0. {
847 return None;
848 }
849 let bps = match unit {
850 'k' => n * 1e3,
851 'm' => n * 1e6,
852 _ => {
853 if seconds <= 0. {
854 return None;
855 }
856 (n * 1e9 * 8. / seconds) - audio_bps as f64
857 }
858 };
859 Some((bps.max(0.) as u64).clamp(BPS_MIN, BPS_MAX))
860}
861
862/// The faintest line on the moment: what the export resolved to on its own --
863/// the codec, the sound, whether it is the whole film or the marked span, and
864/// which seat writes the picture. A readout, never a control: everything in it
865/// The span an export writes, in the words row 3 says it in: the marked
866/// range where there is one, the whole timeline otherwise -- and "sound only"
867/// for a file that carries no picture at all.
868/// How long a marked span is, said so a sliver cannot pass for a range: a
869/// single frame is "1 frame", under a second is frames, then seconds, then
870/// minutes and seconds.
871pub(crate) fn span_word(frames: u32, fps: f64) -> String {
872 let secs = f64::from(frames) / fps;
873 match frames {
874 1 => "1 frame".to_string(),
875 _ if secs < 1. => format!("{frames} frames"),
876 _ if secs < 60. => format!("{} s", secs.round() as u64),
877 _ => format!("{} min {} s", (secs / 60.) as u64, (secs % 60.).round() as u64),
878 }
879}
880
881/// A point on the timeline in the same plain words as [`span_word`]: "2 s",
882/// "1.5 s", "1 min 5 s" -- a timecode is for the transport, not a summary.
883pub(crate) fn point_word(frame: u32, fps: f64) -> String {
884 let secs = f64::from(frame) / fps;
885 let tenths = (secs * 10.).round() / 10.;
886 match secs {
887 _ if secs < 60. && (tenths - tenths.round()).abs() < 1e-9 => format!("{} s", tenths as u64),
888 _ if secs < 60. => format!("{tenths:.1} s"),
889 _ => format!("{} min {} s", (secs / 60.) as u64, (secs % 60.).round() as u64),
890 }
891}
892
893/// The seat a window opens a project with. `Auto` can resolve to VA-API
894/// encode, which has crashed this machine's GPU, so the GUI starts on
895/// software -- also for a project saved with `Auto`, which is what every
896/// project saved before this carries. `Hardware` is only ever a pick.
897pub(crate) fn gui_default_seat(session: &mut engine::PlaybackSession) {
898 if session.encoder_seat() == EncoderSeat::Auto {
899 // A default the load applies, not a pick: it leaves no undo step behind.
900 session.default_encoder_seat(EncoderSeat::Software);
901 }
902}
903
904/// A clip's share of the lane. A timeline with no length reads as one full-width
905/// box rather than as NaN, which gpui would carry into layout.
906/// Why this timeline cannot be written in `format`, if it cannot.
907///
908/// An audio-only timeline is one the picture formats refuse: every frame of it
909/// is a gap, so a Matroska or WebM file would be a black picture over the sound.
910/// The engine refuses those too (`export::start`); this is what greys the row
911/// before a destination has been picked.
912///
913/// An mp4 of it is not refused: the engine writes it as the sound alone (AAC in
914/// an mp4, `export::run_aac`), so the mp4 rows stay open.
915///
916/// It is the *only* reason left. A second audio lane, a speeded clip, a source
917/// no mp4 sample table holds: each of those used to grey the MP4 row, because
918/// the mp4 path could only *copy* an AAC track. It re-encodes where a copy
919/// cannot say what the timeline says (`export::copy_audio`), so none of them is
920/// a refusal any more -- and every video format carries the sound, so there is
921/// nothing here that is one format's alone.
922pub(crate) fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {
923 // A picture file is refused on a timeline with no picture too, as a video file is.
924 if (!format.has_video() && !is_picture_set(format)) || format.ext() == "mp4" {
925 return None;
926 }
927 let picture = session
928 .lanes()
929 .into_iter()
930 .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());
931 match picture {
932 true => None,
933 false => Some(format!(
934 "no picture — {} would be black; export an mp4, M4A, WAV, FLAC, MP3 or Ogg",
935 format.name()
936 )),
937 }
938}
939
940// ---------------------------------------------------------------------------
941// The export sheet (DESIGN §9): the model behind the centred sheet, kept as
942// plain values and functions so every behaviour on it is a test and none of
943// them needs a window.
944// ---------------------------------------------------------------------------
945
946use engine::export::{GifSettings, LoudnessTarget};
947use engine::export_presets as presets;
948use std::collections::HashMap;
949
950/// The sheet's open/closed state for the "More settings" disclosure, in the
951/// same `folds` file every other fold lives in.
952pub(crate) const EXPORT_MORE_FOLD: &str = "export-more";
953
954/// Which of the two destination fields is being typed into.
955#[derive(Debug, Clone, Copy, PartialEq, Eq)]
956pub(crate) enum SheetField {
957 Name,
958 Folder,
959}
960
961/// What a finished export left behind, for the sheet's "done" face.
962#[derive(Debug, Clone)]
963pub(crate) struct ExportDone {
964 pub path: PathBuf,
965 pub bytes: u64,
966 pub wall_secs: f64,
967}
968
969/// A one-second trial write, run when the sheet opens so the time estimate is
970/// a measurement of this machine and this format rather than a guess.
971pub(crate) struct PaceBench {
972 pub key: &'static str,
973 pub handle: ExportHandle,
974 pub started: std::time::Instant,
975 pub media_secs: f64,
976 pub out: PathBuf,
977}
978
979/// Everything the sheet keeps beside the settings the player already holds
980/// (`format`, `audio_kbps`, `custom_bps`, the encoder seat).
981#[derive(Default)]
982pub(crate) struct ExportSheet {
983 /// The user picked "whole timeline" although there are marks.
984 pub whole: bool,
985 /// The file's canvas; `None` follows the project.
986 pub size: Option<(u32, u32)>,
987 /// AV1 sample depth; `None` follows the source.
988 pub bit_depth: Option<u8>,
989 /// Sound levelling target; `None` leaves the mix as it is.
990 pub loudness: Option<LoudnessTarget>,
991 /// The ProRes profile of a ProRes file.
992 pub prores: ProResProfile,
993 /// The HDR transfer of an HEVC file; SDR is none.
994 pub hdr: HdrTransfer,
995 /// The software HEVC encoder's speed preset.
996 pub hevc_speed: HevcSpeed,
997 /// Bits per sample of a ProRes file's sound: `Some(16)`, else 24.
998 pub sound_bits: Option<u8>,
999 /// Captions are left out of the file (`false` keeps the tracks).
1000 pub no_captions: bool,
1001 /// The GIF's width, frame rate and looping ([`Format::Gif`]).
1002 pub gif: GifSettings,
1003 /// A Details row was changed since the last preset was picked: the preset
1004 /// box says "Custom (from X)" even if the settings happen to equal another preset.
1005 pub custom: bool,
1006 /// The preset tile last picked: the tie-break when two presets would
1007 /// describe the settings equally. Whether it still *applies* is derived
1008 /// ([`matching_preset`]), which is what makes "Custom" automatic.
1009 pub preset: Option<&'static str>,
1010 /// The destination field being typed into, and its text.
1011 pub field: Option<(SheetField, String)>,
1012 /// The destination field's text is selected whole: the next letter replaces it (Ctrl+A, or
1013 /// the field just opened on its name).
1014 pub field_all: bool,
1015 /// A plain sentence about the last field edit that was refused.
1016 pub note: Option<String>,
1017 pub done: Option<ExportDone>,
1018 pub failed: Option<String>,
1019 /// The export was cancelled and the cancel landed: the sheet says so.
1020 pub cancelled: bool,
1021 /// Measured pace per codec family; `None` is "tried and could not tell".
1022 pub paces: HashMap<&'static str, Option<f64>>,
1023 pub bench: Option<PaceBench>,
1024}
1025
1026/// The settings a preset can change, as the player holds them.
1027#[derive(Debug, Clone, Copy, PartialEq)]
1028pub(crate) struct Picked {
1029 pub format: Format,
1030 /// The picture's budget; zero is "automatic".
1031 pub bps: u64,
1032 pub audio_kbps: u32,
1033 pub size: Option<(u32, u32)>,
1034 pub depth: Option<u8>,
1035 pub loudness: Option<LoudnessTarget>,
1036 pub prores: ProResProfile,
1037 pub hdr: HdrTransfer,
1038}
1039
1040impl Picked {
1041 fn settings(&self) -> ExportSettings {
1042 ExportSettings {
1043 format: self.format,
1044 bitrate: (self.bps > 0).then_some(self.bps),
1045 audio_kbps: Some(self.audio_kbps),
1046 size: self.size,
1047 video_bit_depth: self.depth,
1048 loudness: self.loudness,
1049 prores_profile: self.prores,
1050 hdr: HdrOutput { transfer: self.hdr, ..HdrOutput::default() },
1051 ..ExportSettings::default()
1052 }
1053 }
1054}
1055
1056/// `base` with a preset laid over it by the engine's own rule
1057/// ([`presets::apply`]): the GUI holds no copy of the table.
1058pub(crate) fn picked_with(base: Picked, preset: &presets::Preset) -> Picked {
1059 let s = presets::apply(preset, base.settings());
1060 Picked {
1061 format: s.format,
1062 bps: s.bitrate.unwrap_or(base.bps),
1063 audio_kbps: clamp_audio_kbps(s.audio_kbps.unwrap_or(base.audio_kbps)),
1064 size: s.size,
1065 depth: s.video_bit_depth,
1066 loudness: s.loudness,
1067 prores: s.prores_profile,
1068 hdr: s.hdr.transfer,
1069 }
1070}
1071
1072/// The sound rates the engine writes are [`AUDIO_KBPS`]; a preset that asks for
1073/// more (AAC 384) gets the top of the list, which is what the engine clamps it to.
1074pub(crate) fn clamp_audio_kbps(kbps: u32) -> u32 {
1075 AUDIO_KBPS
1076 .iter()
1077 .copied()
1078 .filter(|&k| k <= kbps)
1079 .max()
1080 .unwrap_or(AUDIO_KBPS[0])
1081}
1082
1083/// Whether laying `preset` over `picked` would change nothing.
1084pub(crate) fn preset_applies(picked: Picked, preset: &presets::Preset) -> bool {
1085 picked_with(picked, preset) == picked
1086}
1087
1088/// The preset the settings are exactly, preferring `prefer` -- or `None`,
1089/// which the sheet calls Custom.
1090pub(crate) fn matching_preset(
1091 picked: Picked,
1092 prefer: Option<&str>,
1093) -> Option<&'static presets::Preset> {
1094 let table = presets::presets();
1095 prefer
1096 .and_then(presets::by_id)
1097 .filter(|p| preset_applies(picked, p))
1098 .or_else(|| table.iter().find(|p| preset_applies(picked, p)))
1099}
1100
1101/// The codec in the words a person uses, and the key a measured pace is kept
1102/// under (every file of a codec is written at about the same pace).
1103pub(crate) fn codec_word(format: Format) -> &'static str {
1104 match format {
1105 Format::Mp4 => "H.264",
1106 Format::Av1 | Format::Av1Mp4 | Format::Webm => "AV1",
1107 Format::Hevc | Format::HevcMp4 => "HEVC",
1108 Format::Wav => "WAV",
1109 Format::Flac => "FLAC",
1110 Format::Mp3 => "MP3",
1111 Format::Ogg => "Vorbis",
1112 Format::Opus => "Opus",
1113 Format::M4a => "AAC",
1114 Format::ProRes => "ProRes",
1115 Format::Still => "Still image",
1116 Format::PngSequence => "Numbered pictures",
1117 Format::Gif => "GIF",
1118 }
1119}
1120
1121/// Every file the sheet's format list offers: the format, its name and a
1122/// plain-words reason to choose it. Video first, then sound alone.
1123pub(crate) const SHEET_FORMATS: [(Format, &str, &str); 15] = [
1124 (Format::Mp4, "MP4 \u{b7} H.264", "plays everywhere"),
1125 (Format::Av1Mp4, "MP4 \u{b7} AV1", "smaller files, newer players"),
1126 (Format::Av1, "MKV \u{b7} AV1", "smaller files, newer players"),
1127 (Format::HevcMp4, "MP4 \u{b7} HEVC", "small files, phones and TVs"),
1128 (Format::Hevc, "MKV \u{b7} HEVC", "small files, editing friendly"),
1129 (Format::Webm, "WebM \u{b7} AV1", "for web pages"),
1130 (Format::M4a, "M4A", "sound only, plays everywhere"),
1131 (Format::Mp3, "MP3", "sound only, plays on anything"),
1132 (Format::Ogg, "Ogg", "sound only, free format"),
1133 (Format::Opus, "Opus", "sound only, small, for voice"),
1134 (Format::Flac, "FLAC", "sound only, lossless"),
1135 (Format::Wav, "WAV", "sound only, uncompressed"),
1136 (Format::Still, "PNG \u{b7} still", "one picture, no sound"),
1137 (Format::PngSequence, "PNG \u{b7} sequence", "one picture per frame, no sound"),
1138 (Format::Gif, "GIF", "animated, no sound"),
1139];
1140
1141/// A format's name as the sheet's list writes it.
1142pub(crate) fn sheet_format_name(format: Format) -> &'static str {
1143 SHEET_FORMATS
1144 .iter()
1145 .find(|(f, ..)| *f == format)
1146 .map_or("File", |(_, name, _)| *name)
1147}
1148
1149/// What a preset tile says it makes: the canvas and codec for a picture, the
1150/// file and rate for sound. `project` is the size a preset with none keeps.
1151pub(crate) fn preset_result(preset: &presets::Preset, project: Option<(u32, u32)>) -> String {
1152 match preset.target.output {
1153 presets::Output::AudioOnly => format!(
1154 "{} \u{b7} {}",
1155 sheet_format_name(preset.format),
1156 match preset.format {
1157 Format::Wav | Format::Flac => "lossless".to_string(),
1158 _ => format!("{} kbps", preset.audio_kbps),
1159 }
1160 ),
1161 presets::Output::Video => {
1162 let size = match preset.target.size.or(project) {
1163 Some((w, h)) => format!("{w}\u{d7}{h}"),
1164 None => "project size".to_string(),
1165 };
1166 format!("{size} \u{b7} {}", codec_word(preset.format))
1167 }
1168 }
1169}
1170
1171/// The two radio rows of the range: the whole timeline and the marks, each
1172/// with its duration, and why the marks are off when they are.
1173#[derive(Debug, Clone, PartialEq)]
1174pub(crate) struct RangeOptions {
1175 pub whole: String,
1176 pub marks: Option<String>,
1177 pub marks_off: Option<&'static str>,
1178}
1179
1180/// `valid` is the marked span as the export would really use it
1181/// ([`Player::export_range`]); `raw` is whether any marks are set at all, so
1182/// a stale pair is told apart from none.
1183pub(crate) fn range_options(
1184 valid: Option<(u32, u32)>,
1185 raw: bool,
1186 timeline_frames: u32,
1187 fps: f64,
1188) -> RangeOptions {
1189 RangeOptions {
1190 // One decimal, so the whole timeline reads as a length beside the segments.
1191 whole: format!("{:.1} s long", f64::from(timeline_frames) / fps.max(1.)),
1192 marks: valid.map(|(start, end)| {
1193 format!(
1194 "{} \u{2013} {} \u{b7} {} long",
1195 point_word(start, fps),
1196 point_word(end, fps),
1197 span_word(end - start, fps)
1198 )
1199 }),
1200 marks_off: match (valid, raw) {
1201 (Some(_), _) => None,
1202 (None, true) => Some("marks are past the end"),
1203 (None, false) => Some("Set In and Out on the timeline first"),
1204 },
1205 }
1206}
1207
1208/// How big the file may come out, in bytes: a single figure where the bits are
1209/// fixed by the settings, a span where a quality-driven encoder decides.
1210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1211pub(crate) struct SizeEstimate {
1212 pub low: u64,
1213 pub high: u64,
1214}
1215
1216/// What a file of `seconds` is expected to weigh. `video_fixed` is false for
1217/// an encoder that works to a quality and not to the budget (the GPU's AV1),
1218/// which makes the picture's part a span. Sound formats follow their own maths:
1219/// PCM is arithmetic, FLAC a typical 50-75 % of it, Vorbis is quality coded.
1220pub(crate) fn size_estimate(
1221 format: Format,
1222 video_bps: u64,
1223 audio_kbps: u32,
1224 sound: bool,
1225 seconds: f64,
1226 sample_rate: u32,
1227 video_fixed: bool,
1228) -> SizeEstimate {
1229 let secs = seconds.max(0.);
1230 let bytes = |bps: f64| (bps * secs / 8.).round() as u64;
1231 let audio = f64::from(audio_kbps) * 1_000.;
1232 let pcm = f64::from(sample_rate) * 2. * 16.;
1233 let (low, high) = match format {
1234 Format::Wav => (pcm * 0.995, pcm * 1.005),
1235 Format::Flac => (pcm * 0.5, pcm * 0.75),
1236 Format::Ogg => (80_000., 160_000.),
1237 Format::Mp3 | Format::M4a | Format::Opus => (audio * 0.98, audio * 1.04),
1238 _ => {
1239 let a = if sound { audio } else { 0. };
1240 let v = video_bps as f64;
1241 match video_fixed {
1242 // A budget is an average the encoder lands near, plus the
1243 // container's own bookkeeping.
1244 true => ((v + a) * 0.97, (v + a) * 1.04),
1245 false => (v * 0.35 + a, v * 1.1 + a),
1246 }
1247 }
1248 };
1249 let (low, high) = (bytes(low), bytes(high));
1250 // A job with something to write is never "0 MB".
1251 let floor = u64::from(secs > 0.) * 1_000;
1252 SizeEstimate {
1253 low: low.max(floor),
1254 high: high.max(floor),
1255 }
1256}
1257
1258/// A byte count as a person reads it: KB under a megabyte, one decimal under
1259/// ten, whole megabytes, then gigabytes with two decimals.
1260pub(crate) fn bytes_words(bytes: u64) -> String {
1261 let b = bytes as f64;
1262 match bytes {
1263 0..1_000_000 => format!("{} KB", ((b / 1e3).round() as u64).max(1)),
1264 1_000_000..10_000_000 => format!("{:.1} MB", b / 1e6),
1265 10_000_000..1_000_000_000 => format!("{} MB", (b / 1e6).round() as u64),
1266 _ => format!("{:.2} GB", b / 1e9),
1267 }
1268}
1269
1270/// The estimate as a sentence part: "about 38 MB" when it is tight, a span
1271/// ("about 20 to 60 MB") when it cannot be known closer.
1272pub(crate) fn size_words(est: SizeEstimate) -> String {
1273 let (low, high) = (bytes_words(est.low), bytes_words(est.high));
1274 match (est.high as f64) <= (est.low as f64) * 1.15 || low == high {
1275 true => format!("about {}", bytes_words((est.low + est.high) / 2)),
1276 false => {
1277 // "20 to 60 MB": the unit once when both ends share it.
1278 let (n_low, u_low) = low.split_once(' ').unwrap_or((&low, ""));
1279 let (_, u_high) = high.split_once(' ').unwrap_or((&high, ""));
1280 match u_low == u_high {
1281 true => format!("about {n_low} to {high}"),
1282 false => format!("about {low} to {high}"),
1283 }
1284 }
1285 }
1286}
1287
1288/// What the warnings look at.
1289pub(crate) struct WarnCtx {
1290 pub format: Format,
1291 /// The canvas the file is drawn at.
1292 pub target: (u32, u32),
1293 /// The project's own canvas.
1294 pub project: (u32, u32),
1295 pub fps: f64,
1296 pub video_bps: u64,
1297 pub timeline_has_picture: bool,
1298 pub timeline_has_sound: bool,
1299 pub seconds: f64,
1300}
1301
1302/// A picture rate below this many bits per pixel per frame looks blocky.
1303const LOW_BITS_PER_PIXEL: f64 = 0.03;
1304
1305/// The things worth saying before the button is pressed, in plain words.
1306pub(crate) fn warnings(ctx: &WarnCtx) -> Vec<String> {
1307 let mut out = Vec::new();
1308 if ctx.seconds <= 0. {
1309 out.push("Range is empty: nothing to export".to_string());
1310 return out;
1311 }
1312 let pixels = |(w, h): (u32, u32)| u64::from(w) * u64::from(h);
1313 if ctx.format.has_video() {
1314 if pixels(ctx.target) > pixels(ctx.project) {
1315 out.push(format!(
1316 "Stretched up from {}\u{d7}{} \u{2014} won't look sharper",
1317 ctx.project.0, ctx.project.1
1318 ));
1319 }
1320 let per_pixel = ctx.video_bps as f64 / (pixels(ctx.target) as f64 * ctx.fps).max(1.);
1321 if per_pixel < LOW_BITS_PER_PIXEL {
1322 out.push(format!(
1323 "Low bitrate for {}\u{d7}{}: may look blocky",
1324 ctx.target.0,
1325 ctx.target.1
1326 ));
1327 }
1328 if !ctx.timeline_has_sound {
1329 out.push("No sound on the timeline: the file is silent".to_string());
1330 }
1331 } else if !is_picture_set(ctx.format) {
1332 // A picture set writes no sound, so the sound warnings do not apply to it.
1333 if ctx.timeline_has_picture {
1334 out.push("Sound only: the picture is left out".to_string());
1335 }
1336 if !ctx.timeline_has_sound {
1337 out.push("No sound on the timeline: nothing to write".to_string());
1338 }
1339 }
1340 out
1341}
1342
1343/// The container a format is written into, as a person names the file kind.
1344pub(crate) fn container_word(format: Format) -> &'static str {
1345 match format {
1346 Format::Mp4 | Format::Av1Mp4 | Format::HevcMp4 => "MP4",
1347 Format::Av1 | Format::Hevc => "MKV",
1348 Format::Webm => "WebM",
1349 Format::M4a => "M4A",
1350 Format::Mp3 => "MP3",
1351 Format::Ogg => "Ogg",
1352 Format::Opus => "Opus",
1353 Format::Flac => "FLAC",
1354 Format::Wav => "WAV",
1355 Format::ProRes => "MOV",
1356 Format::Still | Format::PngSequence => "PNG",
1357 Format::Gif => "GIF",
1358 }
1359}
1360
1361/// The sound codec a format writes beside (or instead of) its picture.
1362pub(crate) fn sound_codec_word(format: Format) -> &'static str {
1363 match format {
1364 Format::Webm | Format::Opus => "Opus",
1365 Format::Ogg => "Vorbis",
1366 Format::Mp3 => "MP3",
1367 Format::Flac => "FLAC",
1368 Format::Wav | Format::ProRes => "PCM",
1369 _ => "AAC",
1370 }
1371}
1372
1373/// Every (container, codec) pair the export writes, in the order the two
1374/// Details lists show them. The format is the engine's one value for the pair.
1375pub(crate) const COMBOS: [(&str, &str, Format); 16] = [
1376 ("MP4", "H.264", Format::Mp4),
1377 ("MP4", "HEVC", Format::HevcMp4),
1378 ("MP4", "AV1", Format::Av1Mp4),
1379 ("MKV", "HEVC", Format::Hevc),
1380 ("MKV", "AV1", Format::Av1),
1381 ("WebM", "AV1", Format::Webm),
1382 ("M4A", "AAC", Format::M4a),
1383 ("MP3", "MP3", Format::Mp3),
1384 ("Ogg", "Vorbis", Format::Ogg),
1385 ("Opus", "Opus", Format::Opus),
1386 ("FLAC", "FLAC", Format::Flac),
1387 ("WAV", "PCM", Format::Wav),
1388 ("PNG", "Still image", Format::Still),
1389 ("PNG", "Numbered pictures", Format::PngSequence),
1390 ("GIF", "GIF", Format::Gif),
1391 ("MOV", "ProRes", Format::ProRes),
1392];
1393
1394/// The format for picking `container`, keeping the codec in force where that
1395/// container has it (MP4 to MKV keeps AV1), else the container's first.
1396pub(crate) fn format_in_container(container: &str, current: Format) -> Option<Format> {
1397 let codec = codec_word(current);
1398 COMBOS
1399 .iter()
1400 .find(|(c, k, _)| *c == container && (*k == codec || (*k == "PCM" && codec == "WAV")))
1401 .or_else(|| COMBOS.iter().find(|(c, ..)| *c == container))
1402 .map(|(.., f)| *f)
1403}
1404
1405/// What a seat is, in a plain half line: the Details list's note.
1406pub(crate) fn seat_plain(seat: EncoderSeat) -> &'static str {
1407 match seat {
1408 EncoderSeat::Software => "CPU; slower, works everywhere",
1409 EncoderSeat::Hardware => "GPU; faster, needs support",
1410 EncoderSeat::Auto => "Picks the best encoder on this computer",
1411 }
1412}
1413
1414/// What the summary reads off the settings.
1415pub(crate) struct SummaryIn<'a> {
1416 pub format: Format,
1417 pub target: (u32, u32),
1418 pub fps: f64,
1419 pub bps: u64,
1420 pub audio_kbps: u32,
1421 pub sound: bool,
1422 pub seat: EncoderSeat,
1423 pub depth: Option<u8>,
1424 pub prores: ProResProfile,
1425 pub hdr: HdrTransfer,
1426 pub hevc_speed: HevcSpeed,
1427 pub sound_bits: Option<u8>,
1428 pub size: &'a str,
1429 /// What a GIF asks for ([`Format::Gif`]); the other formats ignore it.
1430 pub gif: GifSettings,
1431}
1432
1433/// The three summary lines, each with its fixed label, read off the current
1434/// settings and short enough not to wrap in the dock:
1435/// `Video H.264 . 1920x1080 . 25 fps . 12 Mb/s`,
1436/// `Audio AAC stereo . 320 kb/s`,
1437/// `File MP4 . Software . ~3.1 MB . ~1 s`.
1438/// `time` is the export-time words ("" for none).
1439pub(crate) fn summary_rows(i: &SummaryIn, time: &str) -> [(&'static str, String); 3] {
1440 let dot = " \u{b7} ";
1441 let (container, codec) = (container_word(i.format), codec_word(i.format));
1442 let nb = |n: String, unit: &str| format!("{n}\u{a0}{unit}");
1443 let (video, audio) = if is_picture_set(i.format) {
1444 // Pictures and no sound: the file's own size, and its rate for a GIF.
1445 let picture = match i.format {
1446 Format::Gif => {
1447 let w = i.gif.width.min(i.target.0.max(1));
1448 let h = (f64::from(i.target.1) * f64::from(w) / f64::from(i.target.0.max(1))).round() as u32;
1449 let loops = if i.gif.loop_forever { "loops" } else { "plays once" };
1450 format!("GIF{dot}{w}\u{d7}{h}{dot}{}{dot}{loops}", nb(i.gif.fps.to_string(), "fps"))
1451 }
1452 Format::PngSequence => format!("PNG{dot}{}\u{d7}{}{dot}one per frame", i.target.0, i.target.1),
1453 _ => format!("PNG{dot}{}\u{d7}{}", i.target.0, i.target.1),
1454 };
1455 (picture, "None".to_string())
1456 } else if i.format.has_video() {
1457 let prores = i.format == Format::ProRes;
1458 let hdr = i.format.is_hevc() && i.hdr != HdrTransfer::Sdr;
1459 let mut v = vec![match i.depth.filter(|_| matches!(i.format, Format::Av1 | Format::Av1Mp4 | Format::Webm) || (i.format.is_hevc() && !hdr)) {
1460 _ if prores => i.prores.name().to_string(),
1461 _ if hdr => hdr_word(i.hdr).to_string(),
1462 Some(d) => format!("{codec} {d}-bit"),
1463 None => codec.to_string(),
1464 }];
1465 v.push(format!("{}\u{d7}{}", i.target.0, i.target.1));
1466 v.push(nb(fps_label(i.fps), "fps"));
1467 // A ProRes profile is its own rate; no budget to quote.
1468 if !prores {
1469 v.push(nb(rate_label(i.bps).trim_end_matches(".0").to_string(), "Mb/s"));
1470 }
1471
1472 let a = match (i.sound, prores) {
1473 (true, true) => format!("PCM stereo{dot}{}-bit", i.sound_bits.unwrap_or(24)),
1474 (true, false) => format!("{} stereo{dot}{}", sound_codec_word(i.format), nb(i.audio_kbps.to_string(), "kb/s")),
1475 (false, _) => "None".to_string(),
1476 };
1477 (v.join(dot), a)
1478 } else {
1479 let spec = match i.format {
1480 Format::Wav => "16-bit".to_string(),
1481 Format::Flac => "lossless".to_string(),
1482 Format::Ogg => "variable quality".to_string(),
1483 _ => nb(i.audio_kbps.to_string(), "kb/s"),
1484 };
1485 let a = match i.sound {
1486 true => format!("{} stereo{dot}{spec}", sound_codec_word(i.format)),
1487 false => "None".to_string(),
1488 };
1489 ("Sound only".to_string(), a)
1490 };
1491 let size = i.size.replacen("about ", "~", 1);
1492 let mut file = vec![container.to_string()];
1493 if i.format.has_video() {
1494 file.push(seat_short(i.seat).to_string());
1495 // The default search says nothing; a quicker preset is named. Only the
1496 // software encoder has one.
1497 if i.format.is_hevc() && i.seat != EncoderSeat::Hardware && i.hevc_speed != HevcSpeed::Default {
1498 file.push(hevc_speed_label(i.hevc_speed).to_string());
1499 }
1500 }
1501 // A picture set's size is not the bitrate's estimate, and one still is not a length of time.
1502 if !is_picture_set(i.format) {
1503 file.push(size);
1504 }
1505 if !time.is_empty() && i.format != Format::Still {
1506 file.push(time.to_string());
1507 }
1508 [("Video", video), ("Audio", audio), ("File", file.join(dot))]
1509}
1510
1511/// The HDR choice as a person names it.
1512pub(crate) fn hdr_word(hdr: HdrTransfer) -> &'static str {
1513 match hdr {
1514 HdrTransfer::Sdr => "Off",
1515 HdrTransfer::Pq => "HDR10",
1516 HdrTransfer::Hlg => "HLG",
1517 }
1518}
1519
1520/// The three encoding speeds as the Details row names them.
1521pub(crate) const HEVC_SPEEDS: [HevcSpeed; 3] = [HevcSpeed::Default, HevcSpeed::Fast, HevcSpeed::Faster];
1522
1523pub(crate) fn hevc_speed_label(s: HevcSpeed) -> &'static str {
1524 match s {
1525 HevcSpeed::Default => "Best quality",
1526 HevcSpeed::Fast => "Faster",
1527 HevcSpeed::Faster => "Fastest",
1528 }
1529}
1530
1531/// What a speed costs, in plain words: the line under the row.
1532pub(crate) fn hevc_speed_plain(s: HevcSpeed) -> &'static str {
1533 match s {
1534 HevcSpeed::Default => "Thorough search: the smallest file for the quality.",
1535 HevcSpeed::Fast => "About 1.5\u{d7} quicker; the file is up to 3% bigger.",
1536 HevcSpeed::Faster => "About 2\u{d7} quicker; the file can be a quarter bigger.",
1537 }
1538}
1539
1540fn hevc_speed_key(s: HevcSpeed) -> &'static str {
1541 match s {
1542 HevcSpeed::Default => "default",
1543 HevcSpeed::Fast => "fast",
1544 HevcSpeed::Faster => "faster",
1545 }
1546}
1547
1548/// The HDR row's value in full words.
1549pub(crate) fn hdr_row_word(hdr: HdrTransfer) -> &'static str {
1550 match hdr {
1551 HdrTransfer::Sdr => "Off",
1552 HdrTransfer::Pq => "HDR10 (PQ)",
1553 HdrTransfer::Hlg => "HLG",
1554 }
1555}
1556
1557/// The ProRes profile in a half line: what it is for.
1558pub(crate) fn profile_plain(profile: ProResProfile) -> &'static str {
1559 match profile {
1560 ProResProfile::Proxy => "smallest, for rough edits",
1561 ProResProfile::Lt => "light, small files",
1562 ProResProfile::Standard => "good for most work",
1563 ProResProfile::Hq => "high-quality master",
1564 ProResProfile::P4444 => "full colour, can carry alpha",
1565 ProResProfile::P4444Xq => "highest quality, huge files",
1566 }
1567}
1568
1569/// The encoder seat in one short word for the summary's File line.
1570pub(crate) fn seat_short(seat: EncoderSeat) -> &'static str {
1571 match seat {
1572 EncoderSeat::Software => "Software",
1573 EncoderSeat::Hardware => "Hardware",
1574 EncoderSeat::Auto => "Auto",
1575 }
1576}
1577
1578/// The export time in the few words the File line has room for.
1579pub(crate) fn time_short(words: &str) -> String {
1580 match words.strip_suffix(" to export") {
1581 Some(t) => t.replacen("about ", "~", 1),
1582 None if words.starts_with("estimating") => "estimating\u{2026}".to_string(),
1583 None => String::new(),
1584 }
1585}
1586
1587/// The id of the UI's own first preset: H.264 MP4 at the project's size and rate.
1588pub(crate) const MATCH_PROJECT: &str = "match_project";
1589
1590/// What a preset row says it makes, in one line: "1080p · H.264 · 8 Mb/s" for
1591/// a picture (the project's size when the preset keeps it), the file and rate
1592/// for sound.
1593pub(crate) fn preset_spec(preset: &presets::Preset, project: Option<(u32, u32)>) -> String {
1594 match preset.target.output {
1595 presets::Output::AudioOnly => preset_result(preset, project),
1596 presets::Output::Video => {
1597 let size = match preset.target.size.or(project) {
1598 Some((w, h)) => format!("{w}\u{d7}{h}"),
1599 None => "project size".to_string(),
1600 };
1601 let rate = match preset.bitrate {
1602 _ if preset.format == Format::ProRes => "10-bit".to_string(),
1603 Some(bps) if preset.hdr != HdrTransfer::Sdr => format!("{} Mb/s HDR", rate_label(bps).trim_end_matches(".0")),
1604 Some(bps) => format!("{} Mb/s", rate_label(bps).trim_end_matches(".0")),
1605 None => "auto rate".to_string(),
1606 };
1607 format!("{size} \u{b7} {} \u{b7} {rate}", codec_word(preset.format))
1608 }
1609 }
1610}
1611
1612/// Whether a scrolled body has content under its bottom edge: `offset_y` is
1613/// gpui's (zero at the top, negative going down), `max_y` the furthest it
1614/// goes. Half a pixel of slack so a body scrolled to its end reads as ended.
1615pub(crate) fn more_below_shows(offset_y: f32, max_y: f32) -> bool {
1616 max_y > 0.5 && -offset_y < max_y - 0.5
1617}
1618
1619/// The path with a number in its name until nothing is there: "Keep both".
1620pub(crate) fn unique_path(path: &Path, exists: impl Fn(&Path) -> bool) -> PathBuf {
1621 if !exists(path) {
1622 return path.to_path_buf();
1623 }
1624 let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned());
1625 let ext = path.extension().map(|e| e.to_string_lossy().into_owned());
1626 (2..)
1627 .map(|n| {
1628 let name = match &ext {
1629 Some(ext) => format!("{stem} ({n}).{ext}"),
1630 None => format!("{stem} ({n})"),
1631 };
1632 path.with_file_name(name)
1633 })
1634 .find(|candidate| !exists(candidate))
1635 .unwrap_or_else(|| path.to_path_buf())
1636}
1637
1638/// The three answers to "that file already exists".
1639#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1640pub(crate) enum Overwrite {
1641 Replace,
1642 KeepBoth,
1643 Cancel,
1644}
1645
1646/// The folder field's text as a directory: `~` is home, and it has to exist.
1647pub(crate) fn parse_folder(text: &str, home: Option<&str>) -> Result<PathBuf, &'static str> {
1648 let text = text.trim();
1649 let path = match (text.strip_prefix('~'), home) {
1650 (Some(rest), Some(home)) => PathBuf::from(format!("{home}{rest}")),
1651 _ => PathBuf::from(text),
1652 };
1653 match (text.is_empty(), path.is_dir()) {
1654 (true, _) => Err("Type a folder to save into."),
1655 (_, false) => Err("That folder does not exist."),
1656 _ => Ok(path),
1657 }
1658}
1659
1660/// The name field's text as a file name stem: no folders in it, not empty.
1661pub(crate) fn parse_stem(text: &str) -> Result<String, &'static str> {
1662 let stem = text.trim().trim_end_matches('.');
1663 match (stem.is_empty(), stem.contains(['/', '\\', '\0'])) {
1664 (true, _) => Err("Give the file a name."),
1665 (_, true) => Err("A file name cannot contain a slash."),
1666 _ => Ok(stem.to_string()),
1667 }
1668}
1669
1670/// Opens or closes a fold in the folds set, returning whether it is now open.
1671pub(crate) fn toggle_fold(folds: &mut std::collections::BTreeSet<String>, id: &str) -> bool {
1672 match folds.remove(id) {
1673 true => false,
1674 false => {
1675 folds.insert(id.to_owned());
1676 true
1677 }
1678 }
1679}
1680
1681/// The loudness targets the sheet offers beside "Off": name, LUFS, ceiling.
1682pub(crate) const LOUDNESS_CHOICES: [(&str, f64, f64); 3] = [
1683 ("Podcast (\u{2212}16)", -16., -1.),
1684 ("Streaming (\u{2212}14)", -14., -1.),
1685 ("Broadcast (\u{2212}23)", -23., -1.),
1686];
1687
1688/// What a loudness target is for, in a plain half line; the LUFS figure is the detail, not the name.
1689pub(crate) fn loudness_plain(lufs: f64) -> &'static str {
1690 match lufs {
1691 -14. => "YouTube, Spotify \u{b7} LUFS",
1692 -16. => "podcasts and voice \u{b7} LUFS",
1693 _ => "TV and radio \u{b7} LUFS",
1694 }
1695}
1696
1697/// An audio-rate refusal from the engine, said as the sound row's plain caption.
1698pub(crate) fn audio_rate_words(refusal: &str) -> String {
1699 match refusal {
1700 r if r.contains("copied") => "Sound is copied as it is, so its rate can't change",
1701 r if r.contains("lossless") => "Lossless sound, so its rate can't change",
1702 r if r.contains("quality-coded") => "Ogg sound is set by quality, not by a rate",
1703 r if r.contains("no sound") => "There is no sound to write",
1704 _ => "Sound has no rate to pick here",
1705 }
1706 .to_string()
1707}
1708
1709/// A failed export in plain words, from the raw error and the folder it was
1710/// writing to. The raw text stays for the tooltip; the sheet reads this.
1711pub(crate) fn failure_words(raw: &str, folder: &str) -> String {
1712 let low = raw.to_ascii_lowercase();
1713 if low.contains("permission denied") || low.contains("os error 13") {
1714 format!("edith can't write to {folder}. Pick another folder.")
1715 } else if low.contains("no space left") || low.contains("os error 28") {
1716 "The disk is full.".to_string()
1717 } else if let Some((_, names)) = raw.split_once(" \u{2014} missing: ") {
1718 format!("A file is missing: {names}.")
1719 } else if low.contains("no such file") || low.contains("os error 2") {
1720 format!("The folder {folder} no longer exists.")
1721 } else {
1722 "Something went wrong while writing the file.".to_string()
1723 }
1724}
1725
1726/// The folder field's text: the destination's directory, `~` for home.
1727pub(crate) fn dest_dir_text(path: &Path) -> String {
1728 let dir = path.parent().unwrap_or(path).to_string_lossy().to_string();
1729 match std::env::var("HOME") {
1730 Ok(home) if !home.is_empty() && dir.starts_with(&home) => format!("~{}", &dir[home.len()..]),
1731 _ => dir,
1732 }
1733}
1734
1735/// The time part of the summary. A measured pace prices it ("about 1 min 40 s
1736/// to export"); with none there is no time at all, rather than a guess or a
1737/// word that waits on a measurement that may never come.
1738pub(crate) fn export_time_words(media_seconds: f64, pace: Option<f64>, _pending: bool) -> String {
1739 // No measured pace, no time: a trial write still running is not a number
1740 // yet, and "estimating" waiting on it would stick when the trial fails.
1741 match pace {
1742 Some(_) => format!("{} to export", time_words(media_seconds, pace)),
1743 None => String::new(),
1744 }
1745}
1746
1747/// The settings of the sheet's one-second trial write. Always the software
1748/// seat, whatever the sheet's encoder says: a GPU encode once took this
1749/// machine down, and a trial nobody asked for must never open one. The range
1750/// is the first `frames` frames only.
1751pub(crate) fn pace_bench_settings(
1752 bps: u64,
1753 format: Format,
1754 audio_kbps: u32,
1755 size: Option<(u32, u32)>,
1756 depth: Option<u8>,
1757 frames: u32,
1758) -> ExportSettings {
1759 ExportSettings {
1760 range: Some((0, frames)),
1761 size,
1762 video_bit_depth: depth,
1763 ..export_settings(bps, format, audio_kbps, EncoderSeat::Software)
1764 }
1765}
1766
1767/// Where the trial write goes: the system's temporary folder, never the
1768/// user's export folder. Deleted as soon as it lands or is cancelled.
1769pub(crate) fn pace_bench_path(format: Format) -> PathBuf {
1770 std::env::temp_dir().join(format!("edith-pace-{}.{}", std::process::id(), format.ext()))
1771}
1772
1773/// The Details rows that open a list ([`crate::Pick::Export`]).
1774#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1775pub(crate) enum ExportRow {
1776 Preset,
1777 Profile,
1778 Hdr,
1779 SoundDepth,
1780 Container,
1781 Codec,
1782 Seat,
1783 Bitrate,
1784 Size,
1785 Depth,
1786 Kbps,
1787 Loudness,
1788 Captions,
1789 GifWidth,
1790 GifFps,
1791 GifLoop,
1792}
1793
1794/// One answer from those lists. A pair is picked as the engine's one [`Format`].
1795#[derive(Clone, Copy, PartialEq, Debug)]
1796pub(crate) enum ExportPick {
1797 Preset(&'static str),
1798 /// "Custom": opens Details, where the settings are.
1799 Custom,
1800 Format(Format),
1801 Size(Option<(u32, u32)>),
1802 /// `None` types a value in.
1803 Bitrate(Option<u64>),
1804 Depth(Option<u8>),
1805 Profile(ProResProfile),
1806 Hdr(HdrTransfer),
1807 HevcSpeed(HevcSpeed),
1808 /// `Some(16)`; `None` is the 24-bit default.
1809 SoundBits(Option<u8>),
1810 /// An index into [`LOUDNESS_CHOICES`]; `None` is off.
1811 Loudness(Option<usize>),
1812 /// `true` keeps the timeline's caption tracks in the file.
1813 Captions(bool),
1814 /// A GIF's width in pixels.
1815 GifWidth(u32),
1816 /// A GIF's frame rate.
1817 GifFps(u32),
1818 /// `true` loops the GIF forever.
1819 GifLoop(bool),
1820}
1821
1822/// The widths a GIF is offered at, in pixels.
1823pub(crate) const GIF_WIDTHS: [u32; 4] = [320, 480, 640, 720];
1824/// The frame rates a GIF is offered at.
1825pub(crate) const GIF_FPS: [u32; 4] = [10, 15, 20, 30];
1826
1827/// The bitrates the Details list offers, in Mb/s.
1828pub(crate) const BITRATE_STEPS: [u64; 11] = [1, 2, 4, 6, 8, 12, 16, 20, 30, 40, 50];
1829
1830/// The preset box's text: its name, or "Custom" once a detail moved.
1831pub(crate) fn preset_box_text(current: Option<&str>, _last: Option<&str>) -> String {
1832 let label = |id: &str| match id {
1833 MATCH_PROJECT => Some("Match project"),
1834 _ => presets::by_id(id).map(|p| p.label),
1835 };
1836 current.and_then(label).map_or_else(|| "Custom".to_string(), str::to_string)
1837}
1838
1839// ---------------------------------------------------------------------------
1840// What the Export tab remembers on this computer.
1841// ---------------------------------------------------------------------------
1842
1843/// Every format the file can name. Kept beside [`format_key`], whose match is
1844/// exhaustive, so a new format cannot be written without a name.
1845const ALL_FORMATS: [Format; 16] = [
1846 Format::Mp4,
1847 Format::Av1Mp4,
1848 Format::Av1,
1849 Format::Hevc,
1850 Format::HevcMp4,
1851 Format::Webm,
1852 Format::ProRes,
1853 Format::Wav,
1854 Format::Flac,
1855 Format::Mp3,
1856 Format::Ogg,
1857 Format::M4a,
1858 Format::Opus,
1859 Format::Still,
1860 Format::PngSequence,
1861 Format::Gif,
1862];
1863
1864/// The name a format is saved under. Stable words, not the labels the page
1865/// shows -- a label may be reworded, and a saved file must keep reading.
1866fn format_key(format: Format) -> &'static str {
1867 match format {
1868 Format::Mp4 => "mp4",
1869 Format::Av1Mp4 => "av1-mp4",
1870 Format::Av1 => "av1",
1871 Format::Hevc => "hevc",
1872 Format::HevcMp4 => "hevc-mp4",
1873 Format::Webm => "webm",
1874 Format::Wav => "wav",
1875 Format::Flac => "flac",
1876 Format::Mp3 => "mp3",
1877 Format::Ogg => "ogg",
1878 Format::M4a => "m4a",
1879 Format::Opus => "opus",
1880 Format::ProRes => "prores",
1881 Format::Still => "still",
1882 Format::PngSequence => "png-sequence",
1883 Format::Gif => "gif",
1884 }
1885}
1886
1887/// Whether a format writes pictures and no sound, and no encoder runs: a PNG, a run of them, or a
1888/// GIF. Asked wherever a video format and a sound-only one would be told apart.
1889pub(crate) fn is_picture_set(format: Format) -> bool {
1890 matches!(format, Format::Still | Format::PngSequence | Format::Gif)
1891}
1892
1893fn prores_key(p: ProResProfile) -> &'static str {
1894 match p {
1895 ProResProfile::Proxy => "proxy",
1896 ProResProfile::Lt => "lt",
1897 ProResProfile::Standard => "standard",
1898 ProResProfile::Hq => "hq",
1899 ProResProfile::P4444 => "4444",
1900 ProResProfile::P4444Xq => "4444xq",
1901 }
1902}
1903
1904fn hdr_key(h: HdrTransfer) -> &'static str {
1905 match h {
1906 HdrTransfer::Sdr => "sdr",
1907 HdrTransfer::Pq => "pq",
1908 HdrTransfer::Hlg => "hlg",
1909 }
1910}
1911
1912/// The export choices this computer keeps between launches. The encoder is
1913/// not among them: it is the project's, saved in its `.edith`.
1914#[derive(Debug, Clone, Copy, PartialEq)]
1915pub(crate) struct ExportPrefs {
1916 pub format: Format,
1917 pub audio_kbps: u32,
1918 /// The picture's budget; zero is automatic.
1919 pub bps: u64,
1920 pub size: Option<(u32, u32)>,
1921 pub depth: Option<u8>,
1922 pub prores: ProResProfile,
1923 pub hdr: HdrTransfer,
1924 pub hevc_speed: HevcSpeed,
1925 pub sound_bits: Option<u8>,
1926}
1927
1928impl Default for ExportPrefs {
1929 fn default() -> Self {
1930 ExportPrefs {
1931 format: Format::default(),
1932 audio_kbps: DEFAULT_AUDIO_KBPS,
1933 bps: 0,
1934 size: None,
1935 depth: None,
1936 prores: ProResProfile::default(),
1937 hdr: HdrTransfer::Sdr,
1938 hevc_speed: HevcSpeed::Default,
1939 sound_bits: None,
1940 }
1941 }
1942}
1943
1944/// Beside the keybindings, like the theme and the proxy switches.
1945fn export_defaults_path() -> PathBuf {
1946 crate::keymap::Keymap::config_path().with_file_name("export-defaults")
1947}
1948
1949/// What the last session left, or the defaults: missing or garbled is not
1950/// worth a message, since a preference file is not the user's work.
1951pub(crate) fn load_export_prefs() -> ExportPrefs {
1952 match std::fs::read_to_string(export_defaults_path()) {
1953 Ok(text) => parse_export_prefs(&text),
1954 Err(_) => ExportPrefs::default(),
1955 }
1956}
1957
1958/// Line one is the format's name, line two the audio kbps (the file's first
1959/// shape, still read), then `key value` lines. Each line is read on its own:
1960/// one that does not parse leaves that value at its default.
1961pub(crate) fn parse_export_prefs(text: &str) -> ExportPrefs {
1962 let mut prefs = ExportPrefs::default();
1963 let mut lines = text.lines();
1964 if let Some(f) = lines
1965 .next()
1966 .and_then(|line| ALL_FORMATS.into_iter().find(|&f| format_key(f) == line.trim()))
1967 {
1968 prefs.format = f;
1969 }
1970 if let Some(k) = lines
1971 .next()
1972 .and_then(|line| line.trim().parse::<u32>().ok())
1973 .filter(|k| AUDIO_KBPS.contains(k))
1974 {
1975 prefs.audio_kbps = k;
1976 }
1977 for line in lines {
1978 let Some((key, value)) = line.trim().split_once(' ') else { continue };
1979 let value = value.trim();
1980 match key {
1981 "bitrate" => {
1982 if let Ok(b) = value.parse::<u64>()
1983 && (b == 0 || (BPS_MIN..=BPS_MAX).contains(&b))
1984 {
1985 prefs.bps = b;
1986 }
1987 }
1988 "size" => {
1989 if let Some((w, h)) = value.split_once('x')
1990 && let (Ok(w), Ok(h)) = (w.parse::<u32>(), h.parse::<u32>())
1991 && (16..=16_384).contains(&w)
1992 && (16..=16_384).contains(&h)
1993 {
1994 prefs.size = Some((w, h));
1995 }
1996 }
1997 "depth" => {
1998 prefs.depth = match value {
1999 "8" => Some(8),
2000 "10" => Some(10),
2001 _ => None,
2002 }
2003 }
2004 "prores" => {
2005 if let Some(p) = ProResProfile::ALL.into_iter().find(|&p| prores_key(p) == value) {
2006 prefs.prores = p;
2007 }
2008 }
2009 "hdr" => {
2010 if let Some(h) = [HdrTransfer::Sdr, HdrTransfer::Pq, HdrTransfer::Hlg]
2011 .into_iter()
2012 .find(|&h| hdr_key(h) == value)
2013 {
2014 prefs.hdr = h;
2015 }
2016 }
2017 "hevc-speed" => {
2018 if let Some(s) = HEVC_SPEEDS.into_iter().find(|&s| hevc_speed_key(s) == value) {
2019 prefs.hevc_speed = s;
2020 }
2021 }
2022 "sound-bits" => {
2023 prefs.sound_bits = match value {
2024 "16" => Some(16),
2025 _ => None,
2026 }
2027 }
2028 _ => {}
2029 }
2030 }
2031 // An HDR tag lives on an HEVC file only; the engine refuses it elsewhere.
2032 if !prefs.format.is_hevc() {
2033 prefs.hdr = HdrTransfer::Sdr;
2034 }
2035 prefs
2036}
2037
2038pub(crate) fn render_export_prefs(p: &ExportPrefs) -> String {
2039 let mut out = format!("{}\n{}\n", format_key(p.format), p.audio_kbps);
2040 out.push_str(&format!("bitrate {}\n", p.bps));
2041 if let Some((w, h)) = p.size {
2042 out.push_str(&format!("size {w}x{h}\n"));
2043 }
2044 if let Some(d) = p.depth {
2045 out.push_str(&format!("depth {d}\n"));
2046 }
2047 out.push_str(&format!("prores {}\nhdr {}\n", prores_key(p.prores), hdr_key(p.hdr)));
2048 if p.hevc_speed != HevcSpeed::Default {
2049 out.push_str(&format!("hevc-speed {}\n", hevc_speed_key(p.hevc_speed)));
2050 }
2051 if let Some(b) = p.sound_bits {
2052 out.push_str(&format!("sound-bits {b}\n"));
2053 }
2054 out
2055}
2056
2057/// Writes the choices whole, the way the proxy switches' files are.
2058pub(crate) fn save_export_prefs(prefs: &ExportPrefs) -> std::io::Result<()> {
2059 let path = export_defaults_path();
2060 if let Some(dir) = path.parent() {
2061 std::fs::create_dir_all(dir)?;
2062 }
2063 std::fs::write(path, render_export_prefs(prefs))
2064}
2065
2066#[cfg(test)]
2067mod prefs_tests {
2068 use super::*;
2069
2070 #[test]
2071 fn every_format_is_saved_under_a_name_that_reads_back_as_itself() {
2072 let mut names = Vec::new();
2073 for f in ALL_FORMATS {
2074 let key = format_key(f);
2075 assert!(!names.contains(&key), "{key} names two formats");
2076 names.push(key);
2077 let p = ExportPrefs { format: f, ..ExportPrefs::default() };
2078 assert_eq!(parse_export_prefs(&render_export_prefs(&p)).format, f);
2079 }
2080 }
2081
2082 #[test]
2083 fn all_the_choices_round_trip() {
2084 let p = ExportPrefs {
2085 format: Format::HevcMp4,
2086 audio_kbps: 256,
2087 bps: 8_000_000,
2088 size: Some((1280, 720)),
2089 depth: Some(10),
2090 prores: ProResProfile::P4444,
2091 hdr: HdrTransfer::Pq,
2092 hevc_speed: HevcSpeed::Fast,
2093 sound_bits: Some(16),
2094 };
2095 assert_eq!(parse_export_prefs(&render_export_prefs(&p)), p);
2096 }
2097
2098 #[test]
2099 fn old_and_garbled_files_read_as_defaults_line_by_line() {
2100 // The first shape: two lines only.
2101 let old = parse_export_prefs("av1-mp4\n128\n");
2102 assert_eq!((old.format, old.audio_kbps), (Format::Av1Mp4, 128));
2103 assert_eq!(old.bps, 0);
2104 assert_eq!(parse_export_prefs(""), ExportPrefs::default());
2105 // A rate the encoder does not offer is not a rate: the default stands.
2106 assert_eq!(parse_export_prefs("wav\n999\n").audio_kbps, DEFAULT_AUDIO_KBPS);
2107 assert_eq!(parse_export_prefs("wav\n999\n").format, Format::Wav);
2108 assert_eq!(parse_export_prefs("no-such\n999\nbitrate x\nsize 1\nhdr what\n"), ExportPrefs::default());
2109 // HDR on a non-HEVC file is dropped.
2110 assert_eq!(parse_export_prefs("mp4\n192\nhdr pq\n").hdr, HdrTransfer::Sdr);
2111 }
2112}