forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

export_ui.rs1056 lines, 43.3 KiBHistoryRawDownload
1//! What the export card offers and what it writes.
2
3use crate::*;
4
5/// The project resolutions [`Player::cycle_resolution`] offers, largest first.
6/// A short list of the sizes people name; the media's own is cycled in beside
7/// them, which is what makes the trip round come back to where it started.
8pub(crate) const RESOLUTIONS: [(u32, u32); 5] = [
9 (3840, 2160),
10 (2560, 1440),
11 (1920, 1080),
12 (1280, 720),
13 (854, 480),
14];
15
16/// The project frame rates the list offers, slowest first: the rates footage is
17/// actually shot and delivered at, the NTSC ones written as the ratios they are
18/// (`24000/1001`, not `23.976`) -- the engine conforms the timeline to the very
19/// number it is handed, so a rate rounded here would be a rate no timescale can
20/// name. The media's own is cycled in beside them
21/// ([`frame_rate_ladder`]), which is what keeps the way back on the list.
22pub(crate) const FRAME_RATES: [f64; 8] = [
23 24_000. / 1001.,
24 24.,
25 25.,
26 30_000. / 1001.,
27 30.,
28 50.,
29 60_000. / 1001.,
30 60.,
31];
32
33/// The project sound rates the list offers, slowest first. Unlike
34/// [`RESOLUTIONS`] and [`FRAME_RATES`] there is no media rate to cycle in
35/// beside them: a source's own rate is not a number this list has to name to
36/// offer it, since [`Choice::SampleRate`]`(None)` -- "source" -- already means
37/// exactly that, whatever the number turns out to be.
38pub(crate) const SAMPLE_RATES: [u32; 3] = [44_100, 48_000, 96_000];
39
40/// The sound-rate list's rows: "source" first -- the derived rate, and the
41/// row in force with nothing picked -- then every rate on offer, the one in
42/// force marked. The same rows serve [`Pick::SampleRate`] with a session and
43/// without one: `current` is [`PlaybackSession::sample_rate`] or
44/// [`Player::pending_settings`]`.2`, and `None` means the same thing either
45/// way -- nothing picked yet.
46pub(crate) fn sample_rate_choices(current: Option<u32>) -> Vec<ChoiceRow> {
47 let mut rows = vec![(
48 Choice::SampleRate(None),
49 "Source".into(),
50 "the first audio source's own rate".into(),
51 current.is_none(),
52 )];
53 rows.extend(SAMPLE_RATES.into_iter().map(|rate| {
54 (
55 Choice::SampleRate(Some(rate)),
56 format!("{rate} Hz").into(),
57 match rate {
58 48_000 => "video standard".to_string(),
59 44_100 => "CD/audio standard".to_string(),
60 _ => "high-resolution".to_string(),
61 }
62 .into(),
63 current == Some(rate),
64 )
65 }));
66 rows
67}
68
69/// What the export card offers, top to bottom. Bitrate is the only thing the
70/// encoder actually takes: the codec and the container are what this program
71/// can write and nothing else, so the card states them rather than offering
72/// them.
73#[derive(Clone, Copy, PartialEq, Debug)]
74pub(crate) enum Quality {
75 Auto,
76 Low,
77 Medium,
78 High,
79 Custom,
80}
81
82impl Quality {
83 pub(crate) const ALL: [Quality; 5] = [
84 Quality::Auto,
85 Quality::Low,
86 Quality::Medium,
87 Quality::High,
88 Quality::Custom,
89 ];
90
91 pub(crate) fn label(self) -> &'static str {
92 match self {
93 Quality::Auto => "Auto",
94 Quality::Low => "Low",
95 Quality::Medium => "Medium",
96 Quality::High => "High",
97 Quality::Custom => "Custom",
98 }
99 }
100
101 /// The figure the row stands for, said in the units the row is chosen by.
102 pub(crate) fn detail(self, custom_mbps: u32) -> String {
103 match self {
104 Quality::Auto => "from the picture size and frame rate".to_string(),
105 Quality::Custom => {
106 format!("{custom_mbps} Mbps — wheel or ± steps, n types one, {MBPS_MIN}–{MBPS_MAX}")
107 }
108 other => format!(
109 "{} Mbps",
110 export_settings(other, 0, Format::Mp4, DEFAULT_AUDIO_KBPS, EncoderSeat::Auto)
111 .bitrate
112 .unwrap_or_default()
113 / 1_000_000
114 ),
115 }
116 }
117}
118
119/// The primary pane's one row: the format-and-quality bundles most exports
120/// actually are, named the way a person asks for one rather than by codec and
121/// megabits apart. Every bundle is still exactly a [`Format`] and a
122/// [`Quality`] the Advanced pane's own rows already know how to set -- this
123/// is a shortcut to the pair, not a third setting kept beside them, so a
124/// bundle picked here and a codec picked below never disagree about what is
125/// in force. `Custom` sets nothing; it only opens the Advanced pane, for a
126/// combination none of the bundles name.
127#[derive(Clone, Copy, PartialEq, Debug)]
128pub(crate) enum ExportPreset {
129 Web,
130 Small,
131 Master,
132 AudioOnly,
133 Custom,
134}
135
136impl ExportPreset {
137 pub(crate) const ALL: [ExportPreset; 5] = [
138 ExportPreset::Web,
139 ExportPreset::Small,
140 ExportPreset::Master,
141 ExportPreset::AudioOnly,
142 ExportPreset::Custom,
143 ];
144
145 pub(crate) fn label(self) -> &'static str {
146 match self {
147 ExportPreset::Web => "Web",
148 ExportPreset::Small => "Small file",
149 ExportPreset::Master => "Master",
150 ExportPreset::AudioOnly => "Audio only",
151 ExportPreset::Custom => "Custom",
152 }
153 }
154
155 /// The key that picks this row, none of the sixteen the card's other rows
156 /// already own (`n`, the digits, the codec row's `m/a/h/w/f/p/o`, and
157 /// `c/q/b/e/d/g/r/s`): a letter out of the name itself where its initial is
158 /// one of those (`smaLl`, `masTer`, `aUdio`), and a free one where every
159 /// letter in the name already belongs to another row (`Web`'s w, e and b
160 /// all are). `Custom` shares Advanced's own `s` -- the row does exactly what
161 /// that key already does, not a second name for a third thing.
162 pub(crate) fn key(self) -> &'static str {
163 match self {
164 ExportPreset::Web => "v",
165 ExportPreset::Small => "l",
166 ExportPreset::Master => "t",
167 ExportPreset::AudioOnly => "u",
168 ExportPreset::Custom => "s",
169 }
170 }
171
172 pub(crate) fn detail(self) -> &'static str {
173 match self {
174 ExportPreset::Web => "H.264 · MP4 · medium quality — plays everywhere",
175 ExportPreset::Small => "AV1 · MP4 · low quality — smallest file",
176 ExportPreset::Master => "HEVC · MP4 · high quality — intra-only, for re-editing later",
177 ExportPreset::AudioOnly => "FLAC — lossless sound, no picture",
178 ExportPreset::Custom => "pick a codec, quality and the rest below",
179 }
180 }
181
182 /// The format and quality this bundle sets, or `None` for `Custom` --
183 /// which changes nothing itself, it only opens the pane where the two are
184 /// set apart.
185 pub(crate) fn bundle(self) -> Option<(Format, Quality)> {
186 match self {
187 ExportPreset::Web => Some((Format::Mp4, Quality::Medium)),
188 ExportPreset::Small => Some((Format::Av1Mp4, Quality::Low)),
189 // HEVC, not H.264: a master is for cutting again later, and HEVC's
190 // intra-only rows say why that is the one that keeps its promise --
191 // every frame already a cut point, where H.264's are not.
192 ExportPreset::Master => Some((Format::HevcMp4, Quality::High)),
193 ExportPreset::AudioOnly => Some((Format::Flac, Quality::Auto)),
194 ExportPreset::Custom => None,
195 }
196 }
197
198 /// Which bundle the card's current format and quality already are, or
199 /// `Custom` where they match none of them -- so the primary pane always
200 /// says something true about what is actually going to be written rather
201 /// than defaulting to a bundle nobody picked.
202 pub(crate) fn from_state(format: Format, quality: Quality) -> ExportPreset {
203 ExportPreset::ALL
204 .into_iter()
205 .find(|p| p.bundle() == Some((format, quality)))
206 .unwrap_or(ExportPreset::Custom)
207 }
208}
209
210/// The export card's format rows: the key that picks one, its name, and what it
211/// writes -- or, where this program cannot write it, the reason it cannot. A
212/// format with no entry at all would read as an oversight, and a menu of three
213/// as a claim that nothing else exists -- so the refusals are rows too, dimmed
214/// and unclickable.
215///
216/// `None` is exactly that kind of row, and there are two left. MP3 stopped
217/// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL
218/// `shine-rs` was the licence question, and it is not the only encoder any
219/// more), and HEVC stopped being one when OxideAV's pure-Rust H.265 gave it an
220/// encoder — an *intra-only* one, which the rows say rather than let a user
221/// find out from the size of the file. VP9 is the one this program still only
222/// *reads*: the plugin decodes it and there is no encoder for it here, so it is
223/// a row for the reason the refusals are rows at all — a codec that opens but
224/// never comes back out is exactly the gap a user would otherwise go looking
225/// for. AAC is not a row at all: it is what both containers' sound *is*, never a
226/// file of its own.
227///
228/// A codec is one row, and the boxes it can be written into are the row's
229/// containers: the same AV1 picture and the same AAC track go into a Matroska
230/// file or into an mp4, and which one a user needs is about what has to play
231/// the file, not about the encode. So the container is asked *once*, in a row
232/// of its own, and only where there is more than one to ask about -- five
233/// picture rows to read past were four of them saying the same codec twice.
234pub(crate) const FORMATS: [(&[Format], &str, &str, &str); 8] = [
235 (
236 &[Format::Mp4],
237 "m",
238 "H.264",
239 "plays everywhere · AAC sound · MP4 only",
240 ),
241 (
242 &[Format::Av1, Format::Av1Mp4],
243 "a",
244 "AV1",
245 "smallest file for the picture · AAC sound",
246 ),
247 (
248 &[Format::Hevc, Format::HevcMp4],
249 "h",
250 "HEVC",
251 "intra-only, every frame a cut point — large files",
252 ),
253 (&[Format::Wav], "w", "WAV", "16-bit PCM — audio only"),
254 (&[Format::Flac], "f", "FLAC", "lossless — audio only"),
255 (&[Format::Mp3], "p", "MP3", "MPEG-1 Layer III — audio only"),
256 (
257 &[Format::Ogg],
258 "o",
259 "OGG",
260 "Vorbis (rusty_vorbis) — quality-coded, stereo",
261 ),
262 (&[], "", "VP9", "AV1 above replaces it"),
263];
264
265/// The codec row a key picks, landed in the container already chosen: pressing
266/// `a` after an mp4 gives AV1 *in mp4*, because a box decided once is not a
267/// question again. A letter of the row's own name, spelled out in the table
268/// rather than taken from the initial (`MP4` and `MP3` share one). Never a
269/// digit -- those are the bitrate field's. `None` for every other stroke, the rows
270/// that cannot be picked included.
271pub(crate) fn format_key(key: &str, current: Format) -> Option<Format> {
272 FORMATS
273 .into_iter()
274 .filter(|(_, stroke, ..)| !stroke.is_empty() && stroke.eq_ignore_ascii_case(key))
275 .find_map(|(row, ..)| same_box(row, current))
276}
277
278/// The boxes one codec may be written into, in the order its container row
279/// cycles them. Empty for a codec this program cannot write at all.
280pub(crate) fn containers(format: Format) -> &'static [Format] {
281 FORMATS
282 .into_iter()
283 .map(|(row, ..)| row)
284 .find(|row| row.contains(&format))
285 .unwrap_or(&[])
286}
287
288/// This row's format under the container `current` is already in, or the row's
289/// first when it has no such box: an AV1 picked from a WAV lands in Matroska,
290/// and picked from an mp4 stays in the mp4.
291pub(crate) fn same_box(row: &[Format], current: Format) -> Option<Format> {
292 row.iter()
293 .copied()
294 .find(|f| f.ext() == current.ext())
295 .or_else(|| row.first().copied())
296}
297
298/// The next box for the same codec, wrapping -- what the container row's key
299/// does. The format itself for a codec with only one, so the stroke cannot
300/// change what it is not offering.
301pub(crate) fn next_container(format: Format) -> Format {
302 let row = containers(format);
303 let at = row.iter().position(|&f| f == format).unwrap_or(0);
304 row.get((at + 1) % row.len().max(1))
305 .copied()
306 .unwrap_or(format)
307}
308
309/// The next rate the Sound row offers, wrapping -- what its key does, and what
310/// the row itself names so the stroke is never a guess. [`next_container`]'s
311/// shape, for the same reason: one place decides what "next" means.
312pub(crate) fn next_audio_kbps(kbps: u32) -> u32 {
313 let at = AUDIO_KBPS.iter().position(|&k| k == kbps).unwrap_or(0);
314 AUDIO_KBPS[(at + 1) % AUDIO_KBPS.len()]
315}
316
317/// Why the quality rows say nothing about this format, or `None` where they
318/// decide the picture. Only a picture encoder is given a bitrate here: the two
319/// lossless audio formats have none to give and MP3 is written at one fixed
320/// figure, so a live row over either would be a control that changes nothing.
321pub(crate) fn bitrate_refusal(format: Format) -> Option<&'static str> {
322 match format {
323 Format::Wav | Format::Flac => Some("lossless audio — no bitrate to pick"),
324 Format::Mp3 => Some("sound only — its rate is the Sound row"),
325 // The guard is the question and not a list of names: an audio format
326 // added without a line of its own above would otherwise show live
327 // quality rows over a file that has no picture to spend a bitrate on.
328 // OGG is exactly that format -- and it wants this sentence rather than
329 // one of its own, because its *Sound* row already says the Vorbis half
330 // ("quality-coded — Vorbis holds no rate to pick") and two rows saying
331 // the same thing is one of them wasted.
332 _ if !format.has_video() => Some("sound only — no picture to spend a bitrate on"),
333 _ => None,
334 }
335}
336
337/// What one of the colour card's own strokes does. Its keys are card-local --
338/// they mean nothing outside it -- so they are a table here rather than keymap
339/// bindings, exactly as the export card's format initials are. Listed in
340/// `keymap::FIXED` all the same, which is how the keys menu still says so.
341pub(crate) enum ColorKey {
342 Close,
343 /// Steps down the four sliders, wrapping.
344 Band(usize),
345 /// Moves the picked slider, in [`COLOR_STEP`]s.
346 Nudge(f32),
347 Reset,
348}
349
350/// Why the silence card has nothing to scan on that clip, in its own voice: the
351/// lane and index the user picked, the file it is of, and which of the two
352/// soundless things it is. One place, because a still and a silent video are
353/// the same answer to the same question -- "a box with a larger size than it"
354/// is what the *demuxer* would say about a png, and it is not an answer.
355///
356/// Costs nothing: the scan reads a file and writes marks, so a refusal here
357/// leaves the project (and its undo history) exactly where it was.
358pub(crate) fn unscannable(lane: Lane, idx: usize, path: &Path) -> String {
359 let what = match engine::is_image(path) {
360 true => "is a picture",
361 false => "is silent",
362 };
363 format!(
364 "{} clip {} has no audio to scan — {} {what}",
365 lane.label(),
366 idx + 1,
367 file_name(path)
368 )
369}
370
371/// The half of a take whose *sound* the silence card scans: a link is one span
372/// on however many lanes, so a card opened on the picture opens on the sound it
373/// is grouped with. That is the lane the waveform is drawn on, and so the lane
374/// the marks have to land on to be read against it -- and the ranges agree,
375/// because a group is one span.
376///
377/// The clip itself for one already on an audio lane, for a detached picture,
378/// and for a take whose sound is not on any lane: there is nothing better to
379/// open on, and the refusal for a source with no audio at all is `scan`'s.
380pub(crate) fn audio_half(session: &PlaybackSession, (lane, idx): (Lane, usize)) -> (Lane, usize) {
381 if lane.kind == LaneKind::Audio {
382 return (lane, idx);
383 }
384 let Some(link) = session.lane_clips(lane).get(idx).and_then(|c| c.link) else {
385 return (lane, idx);
386 };
387 session
388 .lanes()
389 .into_iter()
390 .filter(|l| l.kind == LaneKind::Audio)
391 .find_map(|l| {
392 session
393 .lane_clips(l)
394 .iter()
395 .position(|c| c.link == Some(link))
396 .map(|i| (l, i))
397 })
398 .unwrap_or((lane, idx))
399}
400
401/// The member of a caption's group on a media lane of the wanted kind: what a
402/// card that is about media opens on when the hand is on the caption pinned to
403/// it. `None` for a caption in no group with clips -- there are no pictures or
404/// sound behind the words to be reaching at, and the card that opened anyway
405/// would be a card of settings nothing plays.
406pub(crate) fn caption_media_half(
407 session: &PlaybackSession,
408 (lane, idx): (Lane, usize),
409 kind: LaneKind,
410) -> Option<(Lane, usize)> {
411 let link = session.sub_lane(lane).get(idx).and_then(|s| s.link)?;
412 session
413 .lanes()
414 .into_iter()
415 .filter(|l| l.kind == kind)
416 .find_map(|l| {
417 session
418 .lane_clips(l)
419 .iter()
420 .position(|c| c.link == Some(link))
421 .map(|i| (l, i))
422 })
423}
424
425pub(crate) fn color_key(key: &str) -> Option<ColorKey> {
426 Some(match key {
427 ESCAPE => ColorKey::Close,
428 "down" => ColorKey::Band(1),
429 "up" => ColorKey::Band(COLOR_BANDS.len() - 1),
430 "right" => ColorKey::Nudge(1.),
431 "left" => ColorKey::Nudge(-1.),
432 "r" => ColorKey::Reset,
433 _ => return None,
434 })
435}
436
437/// The band'th control of a grade, to read or to write. The order is
438/// [`COLOR_BANDS`]', which is the order the card lists them in.
439pub(crate) fn band_mut(params: &mut ColorParams, band: usize) -> &mut f32 {
440 match band {
441 0 => &mut params.brightness,
442 1 => &mut params.contrast,
443 2 => &mut params.saturation,
444 _ => &mut params.tint,
445 }
446}
447
448/// The line under the rows: what the picked format really writes, in the terms
449/// a file is judged by afterwards.
450/// The next policy round the cycle, in the order the action's label reads.
451/// Every fit policy, in the order the list offers them -- which is the order
452/// [`next_fit`] steps through them, pinned by the test below: a list and a
453/// stroke that disagreed about what comes next would be two settings.
454pub(crate) const FITS: [FitPolicy; 4] = [
455 FitPolicy::Fit,
456 FitPolicy::Fill,
457 FitPolicy::Stretch,
458 FitPolicy::Center,
459];
460
461pub(crate) fn next_fit(fit: FitPolicy) -> FitPolicy {
462 match fit {
463 FitPolicy::Fit => FitPolicy::Fill,
464 FitPolicy::Fill => FitPolicy::Stretch,
465 FitPolicy::Stretch => FitPolicy::Center,
466 FitPolicy::Center => FitPolicy::Fit,
467 }
468}
469
470/// What a person calls one, said as what it does to the picture.
471pub(crate) fn fit_label(fit: FitPolicy) -> &'static str {
472 match fit {
473 FitPolicy::Fit => "fit (whole picture, bars)",
474 FitPolicy::Fill => "fill (cropped, no bars)",
475 FitPolicy::Stretch => "stretch (aspect broken)",
476 FitPolicy::Center => "centre (1:1, no resample)",
477 }
478}
479
480/// Every project resolution on offer, largest first: [`RESOLUTIONS`] with the
481/// media's own size cycled in at its place by size -- so a project already at a
482/// listed size does not see it twice, and the media's own shape, whatever it is,
483/// is always on the list. The one order both the stroke and the list use.
484pub(crate) fn resolution_ladder(native: (u32, u32)) -> Vec<(u32, u32)> {
485 let mut sizes: Vec<(u32, u32)> = RESOLUTIONS.to_vec();
486 if !sizes.contains(&native) {
487 // By area, descending, like the list itself: the cycle then reads as one
488 // ladder rather than a list with a stray rung at the end.
489 let at = sizes
490 .iter()
491 .position(|&(w, h)| {
492 u64::from(w) * u64::from(h) < u64::from(native.0) * u64::from(native.1)
493 })
494 .unwrap_or(sizes.len());
495 sizes.insert(at, native);
496 }
497 sizes
498}
499
500/// The resolution list's rows: every rung of the ladder, the media's own said
501/// so, and the one in force marked. A size is named by its height the way the
502/// button that opens the list names it, with the full figure beside it.
503pub(crate) fn resolution_choices(current: (u32, u32), native: (u32, u32)) -> Vec<ChoiceRow> {
504 resolution_ladder(native)
505 .into_iter()
506 .map(|(w, h)| {
507 (
508 Choice::Size(w, h),
509 format!("{h}p").into(),
510 match (w, h) == native {
511 // Short enough to sit beside the label inside `MENU_W`:
512 // the longer phrase lost its last word to the truncation.
513 true => format!("{w}x{h} · the media's own"),
514 false => format!("{w}x{h}"),
515 }
516 .into(),
517 (w, h) == current,
518 )
519 })
520 .collect()
521}
522
523/// The resolution list's rows before any file is open: [`RESOLUTIONS`] plain,
524/// with nothing marked unless a pick is already held
525/// ([`Player::pending_settings`]) -- there is no media size to cycle in
526/// beside them yet ([`resolution_choices`]'s `native`).
527pub(crate) fn pending_resolution_choices(pending: Option<(u32, u32)>) -> Vec<ChoiceRow> {
528 RESOLUTIONS
529 .into_iter()
530 .map(|(w, h)| {
531 (
532 Choice::Size(w, h),
533 format!("{h}p").into(),
534 format!("{w}x{h}").into(),
535 Some((w, h)) == pending,
536 )
537 })
538 .collect()
539}
540
541/// [`pending_resolution_choices`]'s sibling for the rate list.
542pub(crate) fn pending_fps_choices(pending: Option<f64>) -> Vec<ChoiceRow> {
543 FRAME_RATES
544 .into_iter()
545 .map(|fps| {
546 (
547 Choice::Fps(fps),
548 format!("{} fps", fps_label(fps)).into(),
549 match (fps - fps.round()).abs() < 0.001 {
550 true => String::new(),
551 false => "NTSC".to_string(),
552 }
553 .into(),
554 Some(fps) == pending,
555 )
556 })
557 .collect()
558}
559
560/// Every project frame rate on offer, slowest first: [`FRAME_RATES`] with the
561/// media's own cycled in at its place by speed, so a project already cut at a
562/// listed rate does not see it twice and the media's own rate -- the one a
563/// project moved off it has no other way back to -- is always there.
564/// [`resolution_ladder`]'s rule, for the other setting the project has of its
565/// own.
566pub(crate) fn frame_rate_ladder(native: f64) -> Vec<f64> {
567 let mut rates = FRAME_RATES.to_vec();
568 // Bit for bit: 23.976023976... is not 23.976, and a rate that read as
569 // "already listed" when it is not would take the media's own off the list.
570 if !rates.contains(&native) {
571 let at = rates
572 .iter()
573 .position(|&fps| fps > native)
574 .unwrap_or(rates.len());
575 rates.insert(at, native);
576 }
577 rates
578}
579
580/// The rate list's rows: every rung of the ladder, the media's own said so, and
581/// the one in force marked. Named as a person writes a rate ([`fps_label`]),
582/// with what it is for beside it -- short, or the row loses its tail to the
583/// truncation the resolution list already met.
584pub(crate) fn fps_choices(current: f64, native: f64) -> Vec<ChoiceRow> {
585 frame_rate_ladder(native)
586 .into_iter()
587 .map(|fps| {
588 (
589 Choice::Fps(fps),
590 format!("{} fps", fps_label(fps)).into(),
591 match fps == native {
592 true => "the media's own".to_string(),
593 // The rates that are a ratio are the ones nobody can tell
594 // from their neighbour by the label alone.
595 false => match (fps - fps.round()).abs() < 0.001 {
596 true => String::new(),
597 false => "NTSC".to_string(),
598 },
599 }
600 .into(),
601 fps == current,
602 )
603 })
604 .collect()
605}
606
607/// The fit list's rows: all four policies against the canvas they place a
608/// picture on, since the word alone ("fill") says nothing about the size it is
609/// filling -- which is the very thing the notice says after a stroke.
610pub(crate) fn fit_choices(lane: Lane, idx: usize, current: FitPolicy, (w, h): (u32, u32)) -> Vec<ChoiceRow> {
611 FITS.into_iter()
612 .map(|fit| {
613 (
614 Choice::Fit(lane, idx, fit),
615 fit_label(fit).into(),
616 // The canvas alone, worded as the resolution list words a size:
617 // the policy names are long and anything wordier here loses its
618 // tail to the truncation.
619 format!("{w}x{h}").into(),
620 fit == current,
621 )
622 })
623 .collect()
624}
625
626/// The sound-rate list's rows: every offered rate, the one in force marked, and
627/// what each buys said in the fewest words that fit beside the label (a longer
628/// phrase loses its tail to `MENU_W`'s truncation, as the two lists above say).
629pub(crate) fn audio_rate_choices(current: u32) -> Vec<ChoiceRow> {
630 AUDIO_KBPS
631 .into_iter()
632 .enumerate()
633 .map(|(n, kbps)| {
634 (
635 Choice::AudioRate(kbps),
636 format!("{kbps} kbps").into(),
637 match (kbps, n) {
638 (DEFAULT_AUDIO_KBPS, _) => "the default",
639 (_, 0) => "smallest file",
640 (k, _) if k < DEFAULT_AUDIO_KBPS => "smaller file",
641 _ => "better sound",
642 }
643 .into(),
644 kbps == current,
645 )
646 })
647 .collect()
648}
649
650/// How a seat is named where a person reads it: the card row, the notice and
651/// the list row all say the same word ([`engine::export::EncoderSeat`]).
652pub(crate) fn encoder_label(seat: EncoderSeat) -> &'static str {
653 match seat {
654 EncoderSeat::Auto => "Auto",
655 EncoderSeat::Hardware => "Hardware",
656 EncoderSeat::Software => "Software",
657 }
658}
659
660/// The encoder list's rows: all three seats, the one in force marked, and what
661/// each one *does* beside it -- in the fewest words that fit inside `MENU_W`,
662/// the truncation every list above already met. Always offered, whatever this
663/// machine has: a row that vanished with the plugin would be a setting nobody
664/// could find, and the answer to "is there a seat here?" is the planned line
665/// under the rows ([`engine::export::planned_video`]), which is measured.
666pub(crate) fn encoder_choices(current: EncoderSeat) -> Vec<ChoiceRow> {
667 EncoderSeat::ALL
668 .into_iter()
669 .map(|seat| {
670 (
671 Choice::Encoder(seat),
672 encoder_label(seat).into(),
673 match seat {
674 EncoderSeat::Auto => "the GPU if there is one",
675 EncoderSeat::Hardware => "the GPU or a refusal",
676 EncoderSeat::Software => "the CPU, always",
677 }
678 .into(),
679 seat == current,
680 )
681 })
682 .collect()
683}
684
685/// The row under the encoder one where -- and only where -- a person has asked
686/// for the GPU on an AV1 export: this project's own driver reset the GPU on the
687/// vendored AV1 encoder (2026-08-10), so the pick is theirs to make and the
688/// risk is theirs to be told about. `None` for every other pair, which is what
689/// keeps this from becoming a row nobody reads.
690pub(crate) fn av1_hw_warning(format: Format, seat: EncoderSeat) -> Option<&'static str> {
691 (seat == EncoderSeat::Hardware && matches!(format, Format::Av1 | Format::Av1Mp4)).then_some(
692 "AV1 on the GPU reset this machine's driver once — Software is the safe seat",
693 )
694}
695
696/// How a rendition is named where a person reads it: the panel button, the
697/// notice and the list row all say the same word ([`engine::tonemap::Preset`]).
698pub(crate) fn tone_label(preset: Preset) -> &'static str {
699 match preset {
700 Preset::Reference => "Reference",
701 Preset::Standard => "Standard",
702 Preset::Vivid => "Vivid",
703 }
704}
705
706/// The HDR list's rows: all three renditions, the one in force marked, and what
707/// each one *is* beside it -- in the fewest words that fit inside `MENU_W`, the
708/// truncation the three lists above already met. Always offered, whatever is on
709/// the timeline: a setting that appeared and vanished with the media would be a
710/// setting nobody could find, and the row says who it acts on instead.
711pub(crate) fn tone_choices(current: Preset) -> Vec<ChoiceRow> {
712 Preset::ALL
713 .into_iter()
714 .map(|preset| {
715 (
716 Choice::Tone(preset),
717 tone_label(preset).into(),
718 match preset {
719 Preset::Reference => "BT.2446-A, as published",
720 Preset::Standard => "brighter, player-like",
721 Preset::Vivid => "brightest, richer colour",
722 }
723 .into(),
724 preset == current,
725 )
726 })
727 .collect()
728}
729
730/// The next project resolution after `current`, over [`RESOLUTIONS`] with the
731/// media's own size cycled in at its place by size -- so the trip round always
732/// comes back to the media, whatever odd shape it is, and a project already at a
733/// listed size does not see it twice.
734pub(crate) fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) {
735 let sizes = resolution_ladder(native);
736 let at = sizes.iter().position(|&s| s == current);
737 // A project at a size nobody listed (a hand-edited file) joins the cycle at
738 // the top rather than being stuck.
739 sizes[at.map_or(0, |at| (at + 1) % sizes.len())]
740}
741
742/// The first of the two lines the card keeps above its button: what will be
743/// *inside* the file. [`format_line`]'s codec and box, then the project's own
744/// picture size and rate -- which is what a video export is written at however
745/// many sizes and rates the media on the timeline are -- and last what the
746/// sound will be, or that there is none. Every field here is one `ffprobe`
747/// reads back off the finished file, so the line is checkable rather than a
748/// promise.
749pub(crate) fn summary_head(format: Format, picture: Option<((u32, u32), f64)>, audio: &str) -> String {
750 let line = match picture.filter(|_| format.has_video()) {
751 Some(((w, h), fps)) => {
752 format!("{} · {w}x{h} · {} fps", format_line(format), fps_label(fps))
753 }
754 None => format_line(format).to_string(),
755 };
756 join_detail(&line, audio)
757}
758
759/// The second: where it lands, roughly how big, and what will encode the
760/// picture -- the seat as the probe found it (`…` until it lands, never a
761/// guess), which is what the running export then names on its progress line.
762pub(crate) fn summary_tail(path: &Path, bytes: Option<u64>, seat: Option<&'static str>, video: bool) -> String {
763 let size = bytes.map_or_else(String::new, |bytes| format!("≈ {}", size_label(bytes)));
764 let seat = match (video, seat) {
765 (true, Some(seat)) => seat,
766 (true, None) => "encoder …",
767 (false, _) => "",
768 };
769 join_detail(&join_detail(&file_name(path), &size), seat)
770}
771
772/// A frame rate as a person writes it: `30`, not `30.000`, and `23.976` for the
773/// rate that is a ratio.
774pub(crate) fn fps_label(fps: f64) -> String {
775 match (fps - fps.round()).abs() < 0.001 {
776 true => format!("{fps:.0}"),
777 false => format!("{fps:.3}")
778 .trim_end_matches('0')
779 .trim_end_matches('.')
780 .to_string(),
781 }
782}
783
784/// About how big a *chosen* bitrate makes the file: the picture's bits over the
785/// timeline's length, in bytes -- the unit the line is written in is
786/// [`size_label`]'s to pick. `None` for `Auto`, whose figure is the encoder's to
787/// decide, and for a format with no bitrate at all -- a number nobody picked is
788/// not an estimate. The sound and the container's own overhead are not in it,
789/// which is why the card says "≈".
790pub(crate) fn estimated_bytes(bitrate: Option<u64>, duration: f64) -> Option<u64> {
791 let bitrate = bitrate.filter(|&b| b > 0 && duration > 0.)?;
792 Some((bitrate as f64 * duration / 8.).round() as u64)
793}
794
795/// A size in the largest unit that can state it, [`rate_scale`]'s rule:
796/// megabytes for an export of any length, kilobytes below the one a whole
797/// megabyte rounds away. A three second clip at the floor bitrate really is
798/// 375 kB, and "≈ 0 MB" would be this line saying the file it is about to write
799/// is empty -- the one thing the size field is there to deny. Never "0 kB"
800/// either: an estimate that exists is at least a kilobyte of file.
801pub(crate) fn size_label(bytes: u64) -> String {
802 match (bytes as f64 / 1e6).round() as u64 {
803 0 => format!("{} kB", (bytes as f64 / 1e3).round().max(1.) as u64),
804 mb => format!("{mb} MB"),
805 }
806}
807
808/// What is in the file and what box it is in, which is the head of the summary.
809/// Terse on purpose: the fields after it (size, rate, sound) are what the line
810/// is *for*, and a head that spent its width on prose used to push the whole
811/// summary onto a second line -- what each codec means is on its row.
812pub(crate) fn format_line(format: Format) -> &'static str {
813 match format {
814 Format::Mp4 => "H.264 · MP4",
815 Format::Av1 => "AV1 · MKV",
816 Format::Av1Mp4 => "AV1 · MP4",
817 Format::Hevc => "HEVC intra · MKV",
818 Format::HevcMp4 => "HEVC intra · MP4",
819 // The three whose codec *is* their box: naming it twice would be the
820 // only field on this line that says nothing.
821 Format::Wav => "16-bit PCM · WAV",
822 Format::Flac => "FLAC · lossless",
823 Format::Mp3 => "MP3 · lossy",
824 Format::Ogg => "Vorbis · OGG",
825 }
826}
827
828/// The row a format is picked by, which is what a refusal calls it: the codec,
829/// since the container is a row of its own now -- `AV1`, not the `mkv` such a
830/// file is named with.
831pub(crate) fn format_label(format: Format) -> &'static str {
832 FORMATS
833 .iter()
834 .find(|(row, ..)| row.contains(&format))
835 .map_or("EXPORT", |(_, _, label, _)| *label)
836}
837
838/// The destination under a format: `take.export.mp4` becomes `take.export.wav`.
839/// The stem is untouched, so a name typed into the save dialog survives a
840/// change of mind about the format -- only the extension is the format's to say.
841pub(crate) fn retarget(path: &std::path::Path, format: Format) -> PathBuf {
842 let mut path = path.to_path_buf();
843 path.set_extension(format.ext());
844 path
845}
846
847/// The card's rows as the engine takes them. `Auto` leaves the bitrate to the
848/// exporter, which derives it from the picture; the fixed rows are figures that
849/// hold from 720p to 1080p, and a typed one is passed exactly as typed -- the
850/// engine clamps every explicit bitrate to 1..50 Mbps (`MAX_EXPLICIT_BITRATE`), so this
851/// must not clamp it a second time and disagree about where the edge is.
852///
853/// The bitrate travels even for an audio format, where the engine ignores it:
854/// one settings value, and a row the card has dimmed cannot have been changed.
855pub(crate) fn export_settings(
856 quality: Quality,
857 custom_mbps: u32,
858 format: Format,
859 audio_kbps: u32,
860 seat: EncoderSeat,
861) -> ExportSettings {
862 ExportSettings {
863 format,
864 // Always travels, exactly as the picture's bitrate does above: the
865 // engine ignores it where nothing encodes the sound, and a row the card
866 // has dimmed cannot have been changed.
867 audio_kbps: Some(audio_kbps),
868 bitrate: match quality {
869 Quality::Auto => None,
870 Quality::Low => Some(2_000_000),
871 Quality::Medium => Some(6_000_000),
872 Quality::High => Some(12_000_000),
873 Quality::Custom => Some(u64::from(custom_mbps) * 1_000_000),
874 },
875 // The card's own row now ([`encoder_choices`]), kept with the project:
876 // it was a `VE_SW_ENC` env pin and nothing else, which is a switch
877 // nobody exporting a film would ever find.
878 seat,
879 // The picked track is put on by `start_export`, which is the only
880 // caller that writes a file; the rest of them are asking about the
881 // bitrate and the format.
882 subtitles: Vec::new(),
883 // Neither is a delivery setting: both belong to the stand-ins
884 // [`engine::proxy`] writes -- every frame a key frame costs bits
885 // nobody delivering wants, and a file kept in its source's colour
886 // space is one for this editor to read back rather than to hand
887 // anybody.
888 intra_only: false,
889 keep_source_colour: false,
890 // Set by `start_export`, which knows the player's mark; this helper is
891 // also asked for the estimate alone, which has no range to give.
892 range: None,
893 }
894}
895
896/// What the engine will code an explicit bitrate at, in whole Mbps: outside
897/// this it clamps (`export.rs` `MIN_BITRATE`/`MAX_EXPLICIT_BITRATE`), so a
898/// number typed past either end would be written as a different one. The field
899/// refuses it instead of clamping quietly -- a card that changes the user's
900/// number without saying so is the one thing a field like this must never do.
901///
902/// The ceiling was 20, which was never a limit of any encoder here: it was the
903/// top of the range the exporter *derives* an automatic bitrate in, borrowed as
904/// the cap on a typed one. A 1080p master or a 4K edit wants more than that, so
905/// the asked-for rate has its own ceiling now and this is it.
906pub(crate) const MBPS_MIN: u32 = 1;
907pub(crate) const MBPS_MAX: u32 = 50;
908
909/// How many digits the field takes. Two reach the ceiling; the third is there so
910/// a number *past* it can be typed whole and refused in its own words, rather
911/// than being dropped keystroke by keystroke.
912pub(crate) const MBPS_DIGITS: usize = 3;
913
914/// A number being typed into a card row: the digits so far and, once a commit
915/// has been refused, why. Text-field semantics on a card that has no text field
916/// -- typing, backspace, arrows that step, enter that commits and escape that
917/// gives up -- held as state and driven by the root's key handler, since
918/// nothing in these cards takes gpui focus.
919#[derive(Clone, Debug, Default, PartialEq, Eq)]
920pub(crate) struct NumberEdit {
921 pub(crate) text: String,
922 pub(crate) refusal: Option<String>,
923}
924
925impl NumberEdit {
926 /// Starts on the number the row already carries, so backspace edits it
927 /// rather than the field opening empty over a value that is still in force.
928 /// Zero is no number at all -- it is what the card opens at, before anyone
929 /// has typed one.
930 pub(crate) fn new(value: u32) -> Self {
931 NumberEdit {
932 text: match value {
933 0 => String::new(),
934 v => v.to_string(),
935 },
936 refusal: None,
937 }
938 }
939
940 /// A digit against what is there. The one past [`MBPS_DIGITS`] is refused
941 /// *out loud*: a keystroke dropped in silence is how the old digit capture
942 /// left the card showing a number the user had already typed past.
943 pub(crate) fn digit(&mut self, digit: u32) {
944 if self.text.chars().count() >= MBPS_DIGITS {
945 self.refusal = Some(format!("{MBPS_DIGITS} digits is already past the ceiling"));
946 return;
947 }
948 match char::from_digit(digit, 10) {
949 Some(c) => {
950 self.text.push(c);
951 self.refusal = None;
952 }
953 None => self.refusal = Some("digits only".into()),
954 }
955 }
956
957 /// Erases the last digit, and the refusal with it: the number on screen has
958 /// changed, so the reason the old one was refused no longer describes it.
959 pub(crate) fn backspace(&mut self) {
960 self.text.pop();
961 self.refusal = None;
962 }
963
964 /// The arrows, which is how a number gets picked rather than typed. Steps
965 /// from what is in the field -- an empty one starts at the floor, so the
966 /// first press up is `MBPS_MIN` and not a jump to some remembered value --
967 /// and stays inside the range, because a step is a walk through the legal
968 /// numbers rather than a way out of them.
969 pub(crate) fn step(&mut self, by: i32) {
970 let at = self.text.parse::<i32>().unwrap_or(MBPS_MIN as i32 - by.signum());
971 self.text = (at + by)
972 .clamp(MBPS_MIN as i32, MBPS_MAX as i32)
973 .to_string();
974 self.refusal = None;
975 }
976
977 /// The number, or `None` with the reason recorded where the row will read
978 /// it. Never clamped: 45 committed as 20 is a number the user did not type.
979 pub(crate) fn commit(&mut self) -> Option<u32> {
980 match commit_mbps(&self.text) {
981 Ok(mbps) => Some(mbps),
982 Err(why) => {
983 self.refusal = Some(why);
984 None
985 }
986 }
987 }
988
989 /// What the row shows while it is being typed into: the digits, the caret
990 /// that says they are landing *here*, and either the refusal or the two
991 /// keys that end the edit.
992 pub(crate) fn detail(&self) -> String {
993 format!(
994 "{}▏ Mbps — {}",
995 self.text,
996 match &self.refusal {
997 Some(why) => why.as_str(),
998 None => "enter commits · esc cancels",
999 }
1000 )
1001 }
1002}
1003
1004/// A typed bitrate as the card takes it, or the reason it is not one. The words
1005/// are the row's: they are what the field shows in place of its hint.
1006pub(crate) fn commit_mbps(text: &str) -> Result<u32, String> {
1007 match text.parse::<u32>() {
1008 Ok(mbps) if (MBPS_MIN..=MBPS_MAX).contains(&mbps) => Ok(mbps),
1009 Ok(0) => Err(format!("0 is not a rate — {MBPS_MIN}–{MBPS_MAX} Mbps")),
1010 Ok(mbps) => Err(format!("{mbps} is past the {MBPS_MAX} Mbps ceiling")),
1011 Err(_) => Err(format!("type a number — {MBPS_MIN}–{MBPS_MAX} Mbps")),
1012 }
1013}
1014
1015/// Whether a stroke gets out of a running export. `ctrl+escape` does -- a chord
1016/// and not the bare key, which used to end an hour of encoding on the stroke a
1017/// hand reaches for to shut a menu it has already shut. Bare escape does nothing
1018/// at all here: the progress card is not dismissable, so there is nothing left
1019/// for it to mean. Whatever the keymap has on cancel works too, so rebinding it
1020/// adds a way rather than replacing this one -- and that binding is what the
1021/// card shows.
1022pub(crate) fn cancels_export(key: &str, ctrl: bool, action: Option<ActionId>) -> bool {
1023 (ctrl && key == ESCAPE) || action == Some(ActionId::CancelExport)
1024}
1025
1026/// A clip's share of the lane. A timeline with no length reads as one full-width
1027/// box rather than as NaN, which gpui would carry into layout.
1028/// Why this timeline cannot be written in `format`, if it cannot.
1029///
1030/// An audio-only timeline is the one both picture formats refuse: every frame of
1031/// it is a gap, so the file would be a black picture over the sound. The engine
1032/// refuses it too (`export::start`); this is what greys the row before a
1033/// destination has been picked.
1034///
1035/// It is the *only* reason left. A second audio lane, a speeded clip, a source
1036/// no mp4 sample table holds: each of those used to grey the MP4 row, because
1037/// the mp4 path could only *copy* an AAC track. It re-encodes where a copy
1038/// cannot say what the timeline says (`export::copy_audio`), so none of them is
1039/// a refusal any more -- and every video format carries the sound, so there is
1040/// nothing here that is one format's alone.
1041pub(crate) fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {
1042 if !format.has_video() {
1043 return None;
1044 }
1045 let picture = session
1046 .lanes()
1047 .into_iter()
1048 .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());
1049 match picture {
1050 true => None,
1051 false => Some(format!(
1052 "no picture — {} would be black; export WAV, FLAC, MP3 or OGG",
1053 format.name()
1054 )),
1055 }
1056}