forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB0563cbfTahinli2 months ago824 commits

export_ui.rs788 lines, 31.6 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 // A state word, the resolution list's rule: the six-word phrase this
51 // row wore ran past `MENU_W` and was cut mid-word like the size
52 // list's was. Nothing is resampled -- that is what the row means.
53 "unchanged".into(),
54 current.is_none(),
55 )];
56 rows.extend(SAMPLE_RATES.into_iter().map(|rate| {
57 (
58 Choice::SampleRate(Some(rate)),
59 format!("{rate} Hz").into(),
60 match rate {
61 48_000 => "video standard".to_string(),
62 44_100 => "CD/audio standard".to_string(),
63 _ => "high-resolution".to_string(),
64 }
65 .into(),
66 current == Some(rate),
67 )
68 }));
69 rows
70}
71
72/// The export card's format rows: the key that picks one, its name, and what it
73/// writes -- or, where this program cannot write it, the reason it cannot. A
74/// format with no entry at all would read as an oversight, and a menu of three
75/// as a claim that nothing else exists -- so the refusals are rows too, dimmed
76/// and unclickable.
77///
78/// `None` is exactly that kind of row, and there are two left. MP3 stopped
79/// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL
80/// `shine-rs` was the licence question, and it is not the only encoder any
81/// more), and HEVC stopped being one when OxideAV's pure-Rust H.265 gave it an
82/// encoder — an *intra-only* one, which the rows say rather than let a user
83/// find out from the size of the file. VP9 is the one this program still only
84/// *reads*: the plugin decodes it and there is no encoder for it here, so it is
85/// a row for the reason the refusals are rows at all — a codec that opens but
86/// never comes back out is exactly the gap a user would otherwise go looking
87/// for. AAC is not a row at all: it is what both containers' sound *is*, never a
88/// file of its own.
89///
90/// A codec is one row, and the boxes it can be written into are the row's
91/// containers: the same AV1 picture and the same AAC track go into a Matroska
92/// file or into an mp4, and which one a user needs is about what has to play
93/// the file, not about the encode. So the container is asked *once*, in a row
94/// of its own, and only where there is more than one to ask about -- five
95/// picture rows to read past were four of them saying the same codec twice.
96pub(crate) const FORMATS: [(&[Format], &str, &str, &str); 8] = [
97 (
98 &[Format::Mp4],
99 "m",
100 "H.264",
101 "plays everywhere · AAC sound · MP4 only",
102 ),
103 (
104 &[Format::Av1, Format::Av1Mp4],
105 "a",
106 "AV1",
107 "smallest file for the picture · AAC sound",
108 ),
109 (
110 &[Format::Hevc, Format::HevcMp4],
111 "h",
112 "HEVC",
113 "intra-only, every frame a cut point — large files",
114 ),
115 (&[Format::Wav], "w", "WAV", "16-bit PCM — audio only"),
116 (&[Format::Flac], "f", "FLAC", "lossless — audio only"),
117 (&[Format::Mp3], "p", "MP3", "MPEG-1 Layer III — audio only"),
118 (
119 &[Format::Ogg],
120 "o",
121 "OGG",
122 "Vorbis (rusty_vorbis) — quality-coded, stereo",
123 ),
124 (&[], "", "VP9", "AV1 above replaces it"),
125];
126
127/// The boxes one codec may be written into, in the order its container row
128/// cycles them. Empty for a codec this program cannot write at all.
129/// Not on the export moment any more: the Settings surface is what shows
130/// this (`ui::settings_stance`). Kept and named rather than deleted -- the
131/// state and its setter are the same ones the moment used to drive.
132#[allow(dead_code)]
133pub(crate) fn containers(format: Format) -> &'static [Format] {
134 FORMATS
135 .into_iter()
136 .map(|(row, ..)| row)
137 .find(|row| row.contains(&format))
138 .unwrap_or(&[])
139}
140
141/// This row's format under the container `current` is already in, or the row's
142/// first when it has no such box: an AV1 picked from a WAV lands in Matroska,
143/// and picked from an mp4 stays in the mp4.
144/// Not on the export moment any more: the Settings surface is what shows
145/// this (`ui::settings_stance`). Kept and named rather than deleted -- the
146/// state and its setter are the same ones the moment used to drive.
147#[allow(dead_code)]
148pub(crate) fn same_box(row: &[Format], current: Format) -> Option<Format> {
149 row.iter()
150 .copied()
151 .find(|f| f.ext() == current.ext())
152 .or_else(|| row.first().copied())
153}
154
155/// The next box for the same codec, wrapping -- what the container row's key
156/// does. The format itself for a codec with only one, so the stroke cannot
157/// change what it is not offering.
158/// Not on the export moment any more: the Settings surface is what shows
159/// this (`ui::settings_stance`). Kept and named rather than deleted -- the
160/// state and its setter are the same ones the moment used to drive.
161#[allow(dead_code)]
162pub(crate) fn next_container(format: Format) -> Format {
163 let row = containers(format);
164 let at = row.iter().position(|&f| f == format).unwrap_or(0);
165 row.get((at + 1) % row.len().max(1))
166 .copied()
167 .unwrap_or(format)
168}
169
170/// What one of the colour card's own strokes does. Its keys are card-local --
171/// they mean nothing outside it -- so they are a table here rather than keymap
172/// bindings, exactly as the export card's format initials are. Listed in
173/// `keymap::FIXED` all the same, which is how the keys menu still says so.
174pub(crate) enum ColorKey {
175 Close,
176 /// Steps down the four sliders, wrapping.
177 Band(usize),
178 /// Moves the picked slider, in [`COLOR_STEP`]s.
179 Nudge(f32),
180 Reset,
181}
182
183/// Why the silence card has nothing to scan on that clip, in its own voice: the
184/// lane and index the user picked, the file it is of, and which of the two
185/// soundless things it is. One place, because a still and a silent video are
186/// the same answer to the same question -- "a box with a larger size than it"
187/// is what the *demuxer* would say about a png, and it is not an answer.
188///
189/// Costs nothing: the scan reads a file and writes marks, so a refusal here
190/// leaves the project (and its undo history) exactly where it was.
191pub(crate) fn unscannable(lane: Lane, idx: usize, path: &Path) -> String {
192 let what = match engine::is_image(path) {
193 true => "is a picture",
194 false => "is silent",
195 };
196 format!(
197 "{} clip {} has no audio to scan — {} {what}",
198 lane.label(),
199 idx + 1,
200 file_name(path)
201 )
202}
203
204/// The half of a take whose *sound* the silence card scans: a link is one span
205/// on however many lanes, so a card opened on the picture opens on the sound it
206/// is grouped with. That is the lane the waveform is drawn on, and so the lane
207/// the marks have to land on to be read against it -- and the ranges agree,
208/// because a group is one span.
209///
210/// The clip itself for one already on an audio lane, for a detached picture,
211/// and for a take whose sound is not on any lane: there is nothing better to
212/// open on, and the refusal for a source with no audio at all is `scan`'s.
213pub(crate) fn audio_half(session: &PlaybackSession, (lane, idx): (Lane, usize)) -> (Lane, usize) {
214 if lane.kind == LaneKind::Audio {
215 return (lane, idx);
216 }
217 let Some(link) = session.lane_clips(lane).get(idx).and_then(|c| c.link) else {
218 return (lane, idx);
219 };
220 session
221 .lanes()
222 .into_iter()
223 .filter(|l| l.kind == LaneKind::Audio)
224 .find_map(|l| {
225 session
226 .lane_clips(l)
227 .iter()
228 .position(|c| c.link == Some(link))
229 .map(|i| (l, i))
230 })
231 .unwrap_or((lane, idx))
232}
233
234/// The member of a caption's group on a media lane of the wanted kind: what a
235/// card that is about media opens on when the hand is on the caption pinned to
236/// it. `None` for a caption in no group with clips -- there are no pictures or
237/// sound behind the words to be reaching at, and the card that opened anyway
238/// would be a card of settings nothing plays.
239pub(crate) fn caption_media_half(
240 session: &PlaybackSession,
241 (lane, idx): (Lane, usize),
242 kind: LaneKind,
243) -> Option<(Lane, usize)> {
244 let link = session.sub_lane(lane).get(idx).and_then(|s| s.link)?;
245 session
246 .lanes()
247 .into_iter()
248 .filter(|l| l.kind == kind)
249 .find_map(|l| {
250 session
251 .lane_clips(l)
252 .iter()
253 .position(|c| c.link == Some(link))
254 .map(|i| (l, i))
255 })
256}
257
258pub(crate) fn color_key(key: &str) -> Option<ColorKey> {
259 Some(match key {
260 ESCAPE => ColorKey::Close,
261 "down" => ColorKey::Band(1),
262 "up" => ColorKey::Band(COLOR_BANDS.len() - 1),
263 "right" => ColorKey::Nudge(1.),
264 "left" => ColorKey::Nudge(-1.),
265 "r" => ColorKey::Reset,
266 _ => return None,
267 })
268}
269
270/// The band'th control of a grade, to read or to write. The order is
271/// [`COLOR_BANDS`]', which is the order the card lists them in.
272pub(crate) fn band_mut(params: &mut ColorParams, band: usize) -> &mut f32 {
273 match band {
274 0 => &mut params.brightness,
275 1 => &mut params.contrast,
276 2 => &mut params.saturation,
277 _ => &mut params.tint,
278 }
279}
280
281/// The line under the rows: what the picked format really writes, in the terms
282/// a file is judged by afterwards.
283/// The next policy round the cycle, in the order the action's label reads.
284/// Every fit policy, in the order the list offers them -- which is the order
285/// [`next_fit`] steps through them, pinned by the test below: a list and a
286/// stroke that disagreed about what comes next would be two settings.
287pub(crate) const FITS: [FitPolicy; 4] = [
288 FitPolicy::Fit,
289 FitPolicy::Fill,
290 FitPolicy::Stretch,
291 FitPolicy::Center,
292];
293
294pub(crate) fn next_fit(fit: FitPolicy) -> FitPolicy {
295 match fit {
296 FitPolicy::Fit => FitPolicy::Fill,
297 FitPolicy::Fill => FitPolicy::Stretch,
298 FitPolicy::Stretch => FitPolicy::Center,
299 FitPolicy::Center => FitPolicy::Fit,
300 }
301}
302
303/// What a person calls one, said as what it does to the picture.
304pub(crate) fn fit_label(fit: FitPolicy) -> &'static str {
305 match fit {
306 FitPolicy::Fit => "fit (whole picture, bars)",
307 FitPolicy::Fill => "fill (cropped, no bars)",
308 FitPolicy::Stretch => "stretch (aspect broken)",
309 FitPolicy::Center => "centre (1:1, no resample)",
310 }
311}
312
313/// Every project resolution on offer, largest first: [`RESOLUTIONS`] with the
314/// media's own size cycled in at its place by size -- so a project already at a
315/// listed size does not see it twice, and the media's own shape, whatever it is,
316/// is always on the list. The one order both the stroke and the list use.
317pub(crate) fn resolution_ladder(native: (u32, u32)) -> Vec<(u32, u32)> {
318 let mut sizes: Vec<(u32, u32)> = RESOLUTIONS.to_vec();
319 if !sizes.contains(&native) {
320 // By area, descending, like the list itself: the cycle then reads as one
321 // ladder rather than a list with a stray rung at the end.
322 let at = sizes
323 .iter()
324 .position(|&(w, h)| {
325 u64::from(w) * u64::from(h) < u64::from(native.0) * u64::from(native.1)
326 })
327 .unwrap_or(sizes.len());
328 sizes.insert(at, native);
329 }
330 sizes
331}
332
333/// The resolution list's rows: every rung of the ladder, the media's own said
334/// so, and the one in force marked. A size is named by its height the way the
335/// button that opens the list names it, with the full figure beside it.
336pub(crate) fn resolution_choices(current: (u32, u32), native: (u32, u32)) -> Vec<ChoiceRow> {
337 resolution_ladder(native)
338 .into_iter()
339 .map(|(w, h)| {
340 (
341 Choice::Size(w, h),
342 format!("{h}p").into(),
343 match (w, h) == native {
344 // A state word, not prose (DESIGN §8): "· the media's own"
345 // lost its last word to `MENU_W` on the row a user read
346 // ("word cut"). `source` is the word the sample-rate list
347 // already says the same fact in.
348 true => format!("{w}x{h} source"),
349 false => format!("{w}x{h}"),
350 }
351 .into(),
352 (w, h) == current,
353 )
354 })
355 .collect()
356}
357
358/// The resolution list's rows before any file is open: [`RESOLUTIONS`] plain,
359/// with nothing marked unless a pick is already held
360/// ([`Player::pending_settings`]) -- there is no media size to cycle in
361/// beside them yet ([`resolution_choices`]'s `native`).
362pub(crate) fn pending_resolution_choices(pending: Option<(u32, u32)>) -> Vec<ChoiceRow> {
363 RESOLUTIONS
364 .into_iter()
365 .map(|(w, h)| {
366 (
367 Choice::Size(w, h),
368 format!("{h}p").into(),
369 format!("{w}x{h}").into(),
370 Some((w, h)) == pending,
371 )
372 })
373 .collect()
374}
375
376/// [`pending_resolution_choices`]'s sibling for the rate list.
377pub(crate) fn pending_fps_choices(pending: Option<f64>) -> Vec<ChoiceRow> {
378 FRAME_RATES
379 .into_iter()
380 .map(|fps| {
381 (
382 Choice::Fps(fps),
383 format!("{} fps", fps_label(fps)).into(),
384 match (fps - fps.round()).abs() < 0.001 {
385 true => String::new(),
386 false => "NTSC".to_string(),
387 }
388 .into(),
389 Some(fps) == pending,
390 )
391 })
392 .collect()
393}
394
395/// Every project frame rate on offer, slowest first: [`FRAME_RATES`] with the
396/// media's own cycled in at its place by speed, so a project already cut at a
397/// listed rate does not see it twice and the media's own rate -- the one a
398/// project moved off it has no other way back to -- is always there.
399/// [`resolution_ladder`]'s rule, for the other setting the project has of its
400/// own.
401pub(crate) fn frame_rate_ladder(native: f64) -> Vec<f64> {
402 let mut rates = FRAME_RATES.to_vec();
403 // Bit for bit: 23.976023976... is not 23.976, and a rate that read as
404 // "already listed" when it is not would take the media's own off the list.
405 if !rates.contains(&native) {
406 let at = rates
407 .iter()
408 .position(|&fps| fps > native)
409 .unwrap_or(rates.len());
410 rates.insert(at, native);
411 }
412 rates
413}
414
415/// The rate list's rows: every rung of the ladder, the media's own said so, and
416/// the one in force marked. Named as a person writes a rate ([`fps_label`]),
417/// with what it is for beside it -- short, or the row loses its tail to the
418/// truncation the resolution list already met.
419pub(crate) fn fps_choices(current: f64, native: f64) -> Vec<ChoiceRow> {
420 frame_rate_ladder(native)
421 .into_iter()
422 .map(|fps| {
423 (
424 Choice::Fps(fps),
425 format!("{} fps", fps_label(fps)).into(),
426 match fps == native {
427 true => "the media's own".to_string(),
428 // The rates that are a ratio are the ones nobody can tell
429 // from their neighbour by the label alone.
430 false => match (fps - fps.round()).abs() < 0.001 {
431 true => String::new(),
432 false => "NTSC".to_string(),
433 },
434 }
435 .into(),
436 fps == current,
437 )
438 })
439 .collect()
440}
441
442/// The fit list's rows: all four policies against the canvas they place a
443/// picture on, since the word alone ("fill") says nothing about the size it is
444/// filling -- which is the very thing the notice says after a stroke.
445pub(crate) fn fit_choices(
446 lane: Lane,
447 idx: usize,
448 current: FitPolicy,
449 (w, h): (u32, u32),
450) -> Vec<ChoiceRow> {
451 FITS.into_iter()
452 .map(|fit| {
453 (
454 Choice::Fit(lane, idx, fit),
455 fit_label(fit).into(),
456 // The canvas alone, worded as the resolution list words a size:
457 // the policy names are long and anything wordier here loses its
458 // tail to the truncation.
459 format!("{w}x{h}").into(),
460 fit == current,
461 )
462 })
463 .collect()
464}
465
466/// The sound-rate list's rows: every offered rate, the one in force marked, and
467/// what each buys said in the fewest words that fit beside the label (a longer
468/// phrase loses its tail to `MENU_W`'s truncation, as the two lists above say).
469pub(crate) fn audio_rate_choices(current: u32) -> Vec<ChoiceRow> {
470 AUDIO_KBPS
471 .into_iter()
472 .enumerate()
473 .map(|(n, kbps)| {
474 (
475 Choice::AudioRate(kbps),
476 format!("{kbps} kbps").into(),
477 match (kbps, n) {
478 (DEFAULT_AUDIO_KBPS, _) => "the default",
479 (_, 0) => "smallest file",
480 (k, _) if k < DEFAULT_AUDIO_KBPS => "smaller file",
481 _ => "better sound",
482 }
483 .into(),
484 kbps == current,
485 )
486 })
487 .collect()
488}
489
490/// How a seat is named where a person reads it: the card row, the notice and
491/// the list row all say the same word ([`engine::export::EncoderSeat`]).
492pub(crate) fn encoder_label(seat: EncoderSeat) -> &'static str {
493 match seat {
494 EncoderSeat::Auto => "Auto",
495 EncoderSeat::Hardware => "Hardware",
496 EncoderSeat::Software => "Software",
497 }
498}
499
500/// The encoder list's rows: all three seats, the one in force marked, and what
501/// each one *does* beside it -- in the fewest words that fit inside `MENU_W`,
502/// the truncation every list above already met. Always offered, whatever this
503/// machine has: a row that vanished with the plugin would be a setting nobody
504/// could find, and the answer to "is there a seat here?" is the planned line
505/// under the rows ([`engine::export::planned_video`]), which is measured.
506pub(crate) fn encoder_choices(current: EncoderSeat) -> Vec<ChoiceRow> {
507 EncoderSeat::ALL
508 .into_iter()
509 .map(|seat| {
510 (
511 Choice::Encoder(seat),
512 encoder_label(seat).into(),
513 match seat {
514 EncoderSeat::Auto => "the GPU if there is one",
515 EncoderSeat::Hardware => "the GPU or a refusal",
516 EncoderSeat::Software => "the CPU, always",
517 }
518 .into(),
519 seat == current,
520 )
521 })
522 .collect()
523}
524
525/// The row under the encoder one where -- and only where -- a person has asked
526/// for the GPU on an AV1 export: this project's own driver reset the GPU on the
527/// vendored AV1 encoder (2026-08-10), so the pick is theirs to make and the
528/// risk is theirs to be told about. `None` for every other pair, which is what
529/// keeps this from becoming a row nobody reads.
530/// Not on the export moment any more: the Settings surface is what shows
531/// this (`ui::settings_stance`). Kept and named rather than deleted -- the
532/// state and its setter are the same ones the moment used to drive.
533#[allow(dead_code)]
534pub(crate) fn av1_hw_warning(format: Format, seat: EncoderSeat) -> Option<&'static str> {
535 (seat == EncoderSeat::Hardware && matches!(format, Format::Av1 | Format::Av1Mp4))
536 .then_some("AV1 on the GPU reset this machine's driver once — Software is the safe seat")
537}
538
539/// How a rendition is named where a person reads it: the panel button, the
540/// notice and the list row all say the same word ([`engine::tonemap::Preset`]).
541pub(crate) fn tone_label(preset: Preset) -> &'static str {
542 match preset {
543 Preset::Reference => "Reference",
544 Preset::Standard => "Standard",
545 Preset::Vivid => "Vivid",
546 }
547}
548
549/// The HDR list's rows: all three renditions, the one in force marked, and what
550/// each one *is* beside it -- in the fewest words that fit inside `MENU_W`, the
551/// truncation the three lists above already met. Always offered, whatever is on
552/// the timeline: a setting that appeared and vanished with the media would be a
553/// setting nobody could find, and the row says who it acts on instead.
554pub(crate) fn tone_choices(current: Preset) -> Vec<ChoiceRow> {
555 Preset::ALL
556 .into_iter()
557 .map(|preset| {
558 (
559 Choice::Tone(preset),
560 tone_label(preset).into(),
561 match preset {
562 Preset::Reference => "BT.2446-A, as published",
563 Preset::Standard => "brighter, player-like",
564 Preset::Vivid => "brightest, richer colour",
565 }
566 .into(),
567 preset == current,
568 )
569 })
570 .collect()
571}
572
573/// The next project resolution after `current`, over [`RESOLUTIONS`] with the
574/// media's own size cycled in at its place by size -- so the trip round always
575/// comes back to the media, whatever odd shape it is, and a project already at a
576/// listed size does not see it twice.
577pub(crate) fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) {
578 let sizes = resolution_ladder(native);
579 let at = sizes.iter().position(|&s| s == current);
580 // A project at a size nobody listed (a hand-edited file) joins the cycle at
581 // the top rather than being stuck.
582 sizes[at.map_or(0, |at| (at + 1) % sizes.len())]
583}
584
585/// A frame rate as a person writes it: `30`, not `30.000`, and `23.976` for the
586/// rate that is a ratio.
587pub(crate) fn fps_label(fps: f64) -> String {
588 match (fps - fps.round()).abs() < 0.001 {
589 true => format!("{fps:.0}"),
590 false => format!("{fps:.3}")
591 .trim_end_matches('0')
592 .trim_end_matches('.')
593 .to_string(),
594 }
595}
596
597/// About how big the budget makes the file: every bit that is written --
598/// the picture's rate and the sound's -- over the exported range, in bytes.
599/// The container's own overhead is not in it, which is why the row says "≈".
600pub(crate) fn estimated_bytes(bps: u64, seconds: f64) -> u64 {
601 ((bps as f64) * seconds.max(0.) / 8.).round() as u64
602}
603
604/// A size as the budget row says it: gigabytes with two decimals once the
605/// file is one, whole megabytes under that. Never a decimal megabyte -- the
606/// estimate is an "≈" and a tenth of a megabyte is precision it does not have.
607pub(crate) fn size_label(bytes: u64) -> String {
608 match bytes >= 1_000_000_000 {
609 true => format!("{:.2} GB", bytes as f64 / 1e9),
610 false => format!("{} MB", (bytes as f64 / 1e6).round() as u64),
611 }
612}
613
614/// The budget itself, in Mbps to one decimal: the number the lever reads.
615pub(crate) fn rate_label(bps: u64) -> String {
616 format!("{:.1}", bps as f64 / 1e6)
617}
618
619/// The row a format is picked by, which is what a refusal calls it: the codec,
620/// since the container is a row of its own now -- `AV1`, not the `mkv` such a
621/// file is named with.
622pub(crate) fn format_label(format: Format) -> &'static str {
623 FORMATS
624 .iter()
625 .find(|(row, ..)| row.contains(&format))
626 .map_or("EXPORT", |(_, _, label, _)| *label)
627}
628
629/// The destination under a format: `take.export.mp4` becomes `take.export.wav`.
630/// The stem is untouched, so a name typed into the save dialog survives a
631/// change of mind about the format -- only the extension is the format's to say.
632pub(crate) fn retarget(path: &std::path::Path, format: Format) -> PathBuf {
633 let mut path = path.to_path_buf();
634 path.set_extension(format.ext());
635 path
636}
637
638/// The moment's one number as the engine takes it. The budget is always
639/// explicit now -- the lever opens on the engine's own automatic figure
640/// ([`auto_bps`]) rather than on nothing, so there is no "Auto" left to send
641/// as `None` -- and the engine clamps it to `MIN_BITRATE..MAX_EXPLICIT_BITRATE`
642/// exactly where [`BPS_MIN`]/[`BPS_MAX`] do, so neither can disagree about the
643/// edges.
644///
645/// The bitrate travels even for an audio format, where the engine ignores it:
646/// one settings value, and a row the moment does not show cannot have been
647/// changed.
648pub(crate) fn export_settings(
649 bitrate: u64,
650 format: Format,
651 audio_kbps: u32,
652 seat: EncoderSeat,
653) -> ExportSettings {
654 ExportSettings {
655 format,
656 audio_kbps: Some(audio_kbps),
657 bitrate: Some(bitrate),
658 // The copy path (the old `Quality::Exact`) is off this surface: the
659 // moment is one budget, and a copy is the absence of one.
660 // `engine::export` keeps the path and its own tests; nothing in the
661 // app asks for it.
662 exact: false,
663 seat,
664 subtitles: Vec::new(),
665 intra_only: false,
666 keep_source_colour: false,
667 range: None,
668 }
669}
670
671/// The same settings with the budget taken out -- what the seat probe is asked
672/// and keyed on ([`crate::Player::cache_export_seat`]). A bitrate does not
673/// decide whether this machine has a VA-API seat or whether the picture's
674/// packets can be copied; leaving it in the key meant every wheel notch on the
675/// budget row invalidated the answer and opened a real VA-API encoder to ask it
676/// again -- measured at ten opens for ten notches, 5-32 ms of GPU work each,
677/// against the player's own decoder, which is the "freezes a little" this row
678/// was reported for.
679pub(crate) fn probe_settings(format: Format, audio_kbps: u32, seat: EncoderSeat) -> ExportSettings {
680 ExportSettings {
681 bitrate: None,
682 ..export_settings(0, format, audio_kbps, seat)
683 }
684}
685
686/// The budget's bounds, the engine's own (`engine::export`'s `MIN_BITRATE`
687/// and `MAX_EXPLICIT_BITRATE`): a number outside them would be written as a
688/// different one, so the lever and the field clamp to exactly these.
689pub(crate) const BPS_MIN: u64 = 1_000_000;
690pub(crate) const BPS_MAX: u64 = 50_000_000;
691
692/// A wheel notch, and a notch with shift held: 0.1 and 1 Mbps. Fifty presses
693/// is not a way across this range, and a tenth is the smallest step the row's
694/// own readout can show.
695pub(crate) const BPS_FINE: u64 = 100_000;
696pub(crate) const BPS_COARSE: u64 = 1_000_000;
697
698/// The engine's automatic figure for a picture of this size and rate
699/// (`engine::export`'s `BITS_PER_PIXEL` rule and the range it clamps the
700/// derived number into), which is what the lever opens on before anybody has
701/// chosen: a budget row reading 0 Mbps -- the old `custom_mbps: 0` default --
702/// was a promise to write an empty file.
703const BITS_PER_PIXEL: f64 = 0.1;
704const BPS_AUTO_MAX: u64 = 20_000_000;
705
706pub(crate) fn auto_bps(width: u32, height: u32, fps: f64) -> u64 {
707 let raw = f64::from(width) * f64::from(height) * fps * BITS_PER_PIXEL;
708 (raw as u64).clamp(BPS_MIN, BPS_AUTO_MAX)
709}
710
711/// What was typed into the budget field, as a rate. Four ways to say one:
712/// `850k` and `6.5M` are rates in their own units, a bare `6.5` is Mbps (the
713/// unit the row reads in), and `1.2G` is a *file size* -- the one thing a
714/// person actually wants to hit -- converted through the exported range and
715/// the sound's own rate into the picture rate that lands there.
716///
717/// Clamped to the engine's bounds rather than refused: the moment shows the
718/// parsed number immediately, so a clamp is visible in the same keystroke.
719/// `None` is only ever "that is not a number".
720pub(crate) fn parse_budget(text: &str, seconds: f64, audio_bps: u64) -> Option<u64> {
721 let text = text.trim().to_ascii_lowercase();
722 let text = text.trim_end_matches("bps").trim_end_matches('b').trim_end();
723 let (digits, unit) = match text.chars().last()? {
724 c @ ('k' | 'm' | 'g') => (&text[..text.len() - c.len_utf8()], c),
725 _ => (text, 'm'),
726 };
727 let n: f64 = digits.trim().parse().ok()?;
728 if !n.is_finite() || n <= 0. {
729 return None;
730 }
731 let bps = match unit {
732 'k' => n * 1e3,
733 'm' => n * 1e6,
734 _ => {
735 if seconds <= 0. {
736 return None;
737 }
738 (n * 1e9 * 8. / seconds) - audio_bps as f64
739 }
740 };
741 Some((bps.max(0.) as u64).clamp(BPS_MIN, BPS_MAX))
742}
743
744/// The faintest line on the moment: what the export resolved to on its own --
745/// the codec, the sound, whether it is the whole film or the marked span, and
746/// which seat writes the picture. A readout, never a control: everything in it
747/// The span an export writes, in the words row 3 says it in: the marked
748/// range where there is one, the whole timeline otherwise -- and "sound only"
749/// for a file that carries no picture at all.
750pub(crate) fn range_word(marks: Option<&str>, has_video: bool) -> String {
751 match (marks, has_video) {
752 (Some(marks), _) => format!("marks {marks}"),
753 (None, true) => "whole film".to_string(),
754 (None, false) => "sound only".to_string(),
755 }
756}
757
758/// A clip's share of the lane. A timeline with no length reads as one full-width
759/// box rather than as NaN, which gpui would carry into layout.
760/// Why this timeline cannot be written in `format`, if it cannot.
761///
762/// An audio-only timeline is the one both picture formats refuse: every frame of
763/// it is a gap, so the file would be a black picture over the sound. The engine
764/// refuses it too (`export::start`); this is what greys the row before a
765/// destination has been picked.
766///
767/// It is the *only* reason left. A second audio lane, a speeded clip, a source
768/// no mp4 sample table holds: each of those used to grey the MP4 row, because
769/// the mp4 path could only *copy* an AAC track. It re-encodes where a copy
770/// cannot say what the timeline says (`export::copy_audio`), so none of them is
771/// a refusal any more -- and every video format carries the sound, so there is
772/// nothing here that is one format's alone.
773pub(crate) fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {
774 if !format.has_video() {
775 return None;
776 }
777 let picture = session
778 .lanes()
779 .into_iter()
780 .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());
781 match picture {
782 true => None,
783 false => Some(format!(
784 "no picture — {} would be black; export WAV, FLAC, MP3 or OGG",
785 format.name()
786 )),
787 }
788}