forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

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