forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

export.rs1860 lines, 83.2 KiBHistoryRawDownload
1//! What is cached about the media and the machine, and the export the
2//! two of them decide.
3
4use super::actions::open_in_default_player;
5use crate::*;
6use std::time::Instant;
7
8impl Player {
9 /// What [`timeline_math::lane_refuses`] asks to decide a video lane's
10 /// refusal: the probed answer if `cache_media` has one yet, and the
11 /// extension's own guess -- the same one every door used before the
12 /// probe existed -- while it is still asking.
13 pub(crate) fn has_video(&self, path: &Path) -> bool {
14 self.has_video
15 .get(path)
16 .copied()
17 .unwrap_or_else(|| !engine::is_audio(path))
18 }
19
20 /// Starts a peak decode -- and a stream probe -- for every source that has
21 /// arrived since the last
22 /// repaint. One call from the render rather than three at the doors,
23 /// because argv, an import and a project load are all doors and only this
24 /// one is guaranteed to run after each of them.
25 ///
26 /// The decode itself runs on a background thread, like the file chooser:
27 /// whole-file audio decode is ~1 s for a half-hour source, and on the render
28 /// path that is the window not painting for a second. The lane draws a bed
29 /// meanwhile and the repaint comes with the peaks. The entry is written
30 /// *before* the spawn, so the sixty repaints that happen while a decode runs
31 /// start no further ones.
32 pub(crate) fn cache_media(&mut self, cx: &mut Context<Self>) {
33 let Some(session) = &self.session else {
34 return;
35 };
36 // How big each still is, for the row that has to say so. Inline, unlike
37 // the two below: an image header is a few bytes off the front of the
38 // file, where a sample table is a parse and a decode is a second.
39 for path in unseen_paths(session.sources(), &self.sizes) {
40 let size = engine::is_image(&path)
41 .then(|| engine::image_size(&path).ok())
42 .flatten();
43 self.sizes.insert(path, size);
44 }
45 // Which audio streams each file has, for the library's rows. Header
46 // only, but a big file's sample tables are not free to parse, so it
47 // goes off the render thread like the peaks do.
48 for path in unseen_paths(session.sources(), &self.streams) {
49 self.streams.insert(path.clone(), Vec::new());
50 let probed = cx.background_executor().spawn({
51 let path = path.clone();
52 async move { engine::AudioSession::probe_streams(&path).unwrap_or_default() }
53 });
54 cx.spawn(async move |this, cx| {
55 let probed = probed.await;
56 this.update(cx, |this, cx| {
57 this.streams.insert(path, probed);
58 cx.notify();
59 })
60 .ok();
61 })
62 .detach();
63 }
64 // Whether a file's own header carries a picture at all, for the lane
65 // a drag may land on ([`Player::has_video`]). The two kinds whose
66 // extension already tells the truth (`engine::is_audio`,
67 // `engine::is_image`) are answered inline; the rest is the one case
68 // an extension can lie about -- a song muxed into an `.mp4` -- so it
69 // costs the same header open [`engine::decode::probe`] pays and goes
70 // off the render thread for the same reason.
71 for path in unseen_paths(session.sources(), &self.has_video) {
72 if engine::is_audio(&path) {
73 self.has_video.insert(path, false);
74 continue;
75 }
76 if engine::is_image(&path) {
77 self.has_video.insert(path, true);
78 continue;
79 }
80 self.has_video.insert(path.clone(), true);
81 let probed = cx.background_executor().spawn({
82 let path = path.clone();
83 async move {
84 !matches!(engine::demux::Demuxer::open(&path),
85 Err(e) if engine::demux::NoVideoTrack::is_it(&e))
86 }
87 });
88 cx.spawn(async move |this, cx| {
89 let probed = probed.await;
90 this.update(cx, |this, cx| {
91 this.has_video.insert(path, probed);
92 cx.notify();
93 })
94 .ok();
95 })
96 .detach();
97 }
98 // What each file is coded at, for the card that says so. Header and
99 // sample table only, but a Matroska indexes no samples and its open
100 // walks every cluster header -- 6.7 s on a 12.9 GB film -- so this of
101 // all of them cannot be on the render thread.
102 for path in unseen_paths(session.sources(), &self.bitrates) {
103 self.bitrates.insert(path.clone(), None);
104 let probed = cx.background_executor().spawn({
105 let path = path.clone();
106 async move { engine::probe_bitrate(&path) }
107 });
108 cx.spawn(async move |this, cx| {
109 let probed = probed.await;
110 this.update(cx, |this, cx| {
111 this.bitrates.insert(path, Some(probed));
112 cx.notify();
113 })
114 .ok();
115 })
116 .detach();
117 }
118 // Where this file's own groups of pictures begin, for the cut that
119 // wants to land on one ([`Player::sync_frames`]). The heaviest probe
120 // here -- a Matroska's whole cluster walk, seconds on a film -- and the
121 // one nothing waits for: until it answers, the snap is the clip-edge
122 // snap it always was.
123 for path in unseen_paths(session.sources(), &self.syncs) {
124 self.syncs.insert(path.clone(), Vec::new());
125 let probed = cx.background_executor().spawn({
126 let path = path.clone();
127 async move { engine::demux::sync_points(&path) }
128 });
129 cx.spawn(async move |this, cx| {
130 let probed = probed.await;
131 this.update(cx, |this, cx| {
132 this.syncs.insert(path, probed);
133 cx.notify();
134 })
135 .ok();
136 })
137 .detach();
138 }
139 // The bench's poster frame per file (`Thumb`, DESIGN §5's "real
140 // thumbnails across video clips"): one representative frame, decoded
141 // off the render thread like the peaks above through the same
142 // single-frame door `engine::decode::DecodeSession::open_range`
143 // already opens for a poster frame -- no second decode path invented.
144 // Filtered to files with a picture at all: an audio-only source has
145 // no frame to ask for, so it never enters this map (mirroring `Wave`'s
146 // own `Silent`, but as an absence rather than a state).
147 for path in unseen_paths(session.sources(), &self.thumbs)
148 .into_iter()
149 .filter(|p| !engine::is_audio(p))
150 {
151 self.thumbs.insert(path.clone(), Thumb::Loading);
152 let decoded = cx.background_executor().spawn({
153 let path = path.clone();
154 async move {
155 let (_, rx, _cancel) =
156 engine::decode::DecodeSession::open_range(&path, 0, 1).ok()?;
157 let frame = rx.recv().ok()?;
158 let buf = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra)?;
159 Some(std::sync::Arc::new(RenderImage::new(vec![
160 image::Frame::new(buf),
161 ])))
162 }
163 });
164 cx.spawn(async move |this, cx| {
165 let decoded = decoded.await;
166 this.update(cx, |this, cx| {
167 this.thumbs.insert(
168 path,
169 match decoded {
170 Some(image) => Thumb::Ready(image),
171 None => Thumb::Failed,
172 },
173 );
174 cx.notify();
175 })
176 .ok();
177 })
178 .detach();
179 }
180 // Which decoder each file will run on, for the row that says so before
181 // a frame of it plays. Off the render thread like the streams above: a
182 // stream the plugin takes costs one VA-API init (~90 ms) to answer.
183 for path in unseen_paths(session.sources(), &self.decoders) {
184 self.decoders.insert(path.clone(), Decoder::Pending);
185 let probed = cx.background_executor().spawn({
186 let path = path.clone();
187 // A refusal is kept in the decoder's own words, and the row
188 // shows them: a file this machine cannot decode is the one
189 // whose second line has to say so. A song is a different
190 // answer entirely -- it has no coded stream, and the probe
191 // says so by naming the still seat.
192 async move { Decoder::from(engine::decode::probe(&path)) }
193 });
194 cx.spawn(async move |this, cx| {
195 let probed = probed.await;
196 this.update(cx, |this, cx| {
197 this.decoders.insert(path, probed);
198 cx.notify();
199 })
200 .ok();
201 })
202 .detach();
203 }
204 // A stand-in for every film this machine cannot cut at speed, started
205 // the moment the file arrives and made while the editor keeps running
206 // ([`engine::proxy`]). Off the render thread for the reason the sync
207 // walk above is -- the decision reads the same header -- and the encode
208 // itself is the engine's own worker, so what comes back here is a
209 // handle to poll and not a wait.
210 //
211 // ...unless this project makes none by itself
212 // ([`engine::PlaybackSession::auto_proxies`]), and then the Proxies
213 // switch is the ask: turning it on brings the films that want a
214 // stand-in through here at the next repaint, which is the only door
215 // there is. Left unseen meanwhile, so nothing is missed by having been
216 // imported while the switch was off.
217 // Gathered here and started at the bottom of this function: the list is
218 // read off the session, and starting one takes the whole player
219 // ([`Player::start_proxy_for`], which the row's switch calls too), so
220 // the two cannot be the same statement.
221 let mut starting: Vec<PathBuf> = Vec::new();
222 for path in proxies_to_start(
223 session.auto_proxies(),
224 session.proxies(),
225 session.sources(),
226 &self.proxies,
227 ) {
228 // Two at a time, and the rest at the next repaint: a stand-in is a
229 // whole film re-encoded, and a library of ten dropped at once would
230 // otherwise start ten encodes fighting over the one hardware seat.
231 // The unstarted ones simply stay out of the map, which is what
232 // brings them back here ([`unseen_paths`]).
233 if self.in_flight_proxies() + starting.len() >= PROXIES_AT_ONCE {
234 break;
235 }
236 starting.push(path);
237 }
238 for key in unseen_sources(session.sources(), &self.waves, Instant::now()) {
239 self.waves.insert(key.clone(), Wave::Loading);
240 let decoded = cx.background_executor().spawn({
241 let (path, stream) = key.clone();
242 async move {
243 engine::waveform::peaks(&path, stream, WAVE_BPS)
244 .map(|peaks| peaks.map(|peaks| Arc::new(normalise(peaks))))
245 .inspect_err(|e| eprintln!("waveform: {}: {e}", path.display()))
246 }
247 });
248 cx.spawn(async move |this, cx| {
249 let decoded = decoded.await;
250 this.update(cx, |this, cx| {
251 this.waves.insert(
252 key,
253 match decoded {
254 Ok(Some(peaks)) => Wave::Peaks(peaks),
255 // No audio track: an answer, and not worth asking
256 // about again.
257 Ok(None) => Wave::Silent,
258 // A file whose sound we could not read is not a
259 // silent one, and a lane that drew it as silent is
260 // how a broken decode passes for a design choice.
261 // Stamped, and not an answer: a repaint past
262 // [`WAVE_RETRY`] asks again, so a failure whose
263 // cause went away (a file still being copied when
264 // it arrived) draws its envelope without a reopen.
265 Err(_) => Wave::Failed(Instant::now()),
266 },
267 );
268 cx.notify();
269 })
270 .ok();
271 })
272 .detach();
273 }
274 // The silence card's own decode, started here instead of at the card
275 // -- a whole source, off the render thread, the moment it arrives
276 // rather than the moment somebody opens the card on it
277 // ([`Player::start_silence_scan`] used to be the only door and cost
278 // the card its first fifty seconds). Landed under `full_scan_key` in
279 // the very map the card reads, so `scan_silences` finds it warm.
280 //
281 // A still has no sound to read, and `silence_bg`'s presence is the
282 // dedupe: a source already scanning, already scanned, or scanned and
283 // then removed mid-read (its entry stays until the scan notices the
284 // cancel) is not started twice. Gathered here, off `session`, for
285 // `starting`'s own reason: starting one below takes `self` mutably
286 // and `session` is a borrow of it.
287 let silence_starting: Vec<(PathBuf, usize)> = session
288 .sources()
289 .iter()
290 .map(|s| (s.path.clone(), s.audio_stream))
291 .filter(|key| {
292 !engine::is_image(&key.0)
293 && !self.silence_bg.contains_key(key)
294 && !self
295 .silence_levels
296 .contains_key(&full_scan_key(&key.0, key.1))
297 })
298 .collect();
299 for path in starting {
300 self.start_proxy_for(&path, cx);
301 }
302 for key in silence_starting {
303 let progress = Arc::new(engine::silence::Progress::default());
304 self.silence_bg.insert(key.clone(), Arc::clone(&progress));
305 let scan = cx.background_executor().spawn({
306 let (path, stream, progress) = (key.0.clone(), key.1, Arc::clone(&progress));
307 async move {
308 engine::silence::levels_with_progress(
309 &path,
310 stream,
311 (0., f64::INFINITY),
312 &progress,
313 )
314 }
315 });
316 cx.spawn(async move |this, cx| {
317 let landed = scan.await;
318 this.update(cx, |this, cx| {
319 this.silence_bg.remove(&key);
320 // Cancelled means the source was removed while this read
321 // was running: half a file's levels answer for a source
322 // that is not on the list any more.
323 if progress.cancel.load(std::sync::atomic::Ordering::Relaxed) {
324 return;
325 }
326 if let Ok(Some(levels)) = landed {
327 this.silence_levels
328 .insert(full_scan_key(&key.0, key.1), Arc::new(levels));
329 // A card already open and waiting on this very source
330 // draws its marks the moment they land, same as an
331 // on-demand scan does.
332 this.scan_silences();
333 cx.notify();
334 }
335 // `Ok(None)` (no audio track) and `Err` are left unrecorded:
336 // the card's own on-demand scan is what a person waiting on
337 // this file actually sees, and it gives the same answer
338 // (`unscannable`/`Scan failed`) when it is opened.
339 })
340 .ok();
341 })
342 .detach();
343 }
344 // What each file holds, for the properties plates. Last, because it
345 // needs `self` mutably and the session borrow above ends here.
346 self.cache_facts(cx);
347 }
348
349 /// Probes what an export would open, once per (settings, resolution, cuts)
350 /// and only while the export card is up -- it opens the very VA-API encoder
351 /// the export would and asks [`engine::export::planned_seats`] the very
352 /// question the export asks itself, which is what makes the card's line a
353 /// measurement instead of a promise, and also what makes it too slow for
354 /// the render thread. Written before the spawn, like the probes above, so
355 /// the repaints during it start no second one.
356 ///
357 /// The cuts are in the key because they are in the answer: moving one onto
358 /// a sync point is exactly what turns "SW encode" into "copy", and a card
359 /// that kept the old line would be lying about the file it is about to
360 /// write.
361 pub(crate) fn cache_export_seat(&mut self, cx: &mut Context<Self>) {
362 let Some(session) = &self.session else {
363 return;
364 };
365 let settings = probe_settings(self.format, self.audio_kbps, self.encoder_seat());
366 if !self.export_open {
367 return;
368 }
369 // A format with no picture has no seat to probe -- and the *last*
370 // format's is not its answer: cleared rather than left standing, or
371 // picking MP3 after AV1 would read "SW encode (rav1e) · MP3 · SW
372 // (ec-mp3)", which names an encoder that will not run.
373 if !settings.format.has_video() {
374 self.export_seat = None;
375 return;
376 }
377 // The timeline an export would be started with, owned so the probe can
378 // run on a worker -- and the clips beside it, which are what tells this
379 // that the question has changed.
380 let (project, meta) = session.export_snapshot();
381 let clips: Vec<Clip> = session
382 .lanes()
383 .into_iter()
384 .flat_map(|lane| session.lane_clips(lane).to_vec())
385 .collect();
386 // Cloned rather than copied: the settings carry the picked subtitle
387 // rows, which is a `Vec` ([`engine::export::ExportSettings`]).
388 let key = (settings.clone(), (meta.width, meta.height), clips);
389 if self
390 .export_seat
391 .as_ref()
392 .is_some_and(|(asked, size, cuts, _)| (asked, size, cuts) == (&key.0, &key.1, &key.2))
393 {
394 return;
395 }
396 self.export_seat = Some((key.0.clone(), key.1, key.2.clone(), None));
397 let probed = cx
398 .background_executor()
399 .spawn(async move { engine::export::planned_seats(&project, &meta, &settings) });
400 cx.spawn(async move |this, cx| {
401 let probed = probed.await;
402 this.update(cx, |this, cx| {
403 // Only if the card is still asking the same question: a format
404 // changed while the plugin opened has a probe of its own.
405 if let Some(seat) = this.export_seat.as_mut().filter(|(asked, size, cuts, _)| {
406 (asked, size, cuts) == (&key.0, &key.1, &key.2)
407 }) {
408 seat.3 = Some(probed);
409 }
410 cx.notify();
411 })
412 .ok();
413 })
414 .detach();
415 }
416
417 /// Asks the plugin what this machine's GPU can do, once, the first time the
418 /// export card is up to show it. Off the render thread for `cache_export_seat`'s
419 /// reason: the plugin initialises VA-API to answer, and a driver that is
420 /// slow to load must not be a frame the user waits for.
421 pub(crate) fn cache_hw_caps(&mut self, cx: &mut Context<Self>) {
422 if !self.export_open || self.hw_caps.is_some() {
423 return;
424 }
425 // Written before the spawn, exactly as the probes above are, so the
426 // repaints during it start no second one.
427 self.hw_caps = Some("asking the driver…".into());
428 let asked = cx
429 .background_executor()
430 .spawn(async move { engine::caps::hardware() });
431 cx.spawn(async move |this, cx| {
432 let line = asked.await;
433 this.update(cx, |this, cx| {
434 this.hw_caps = Some(line.into());
435 cx.notify();
436 })
437 .ok();
438 })
439 .detach();
440 }
441
442 /// The export that owns the UI, if any. A cancelled one does not: it has
443 /// its own copy of the edit list and owes only its own cleanup.
444 pub(crate) fn exporting(&self) -> Option<&ExportHandle> {
445 self.export.as_ref().filter(|_| !self.cancelling)
446 }
447
448 /// What the export action does now: opens the sheet, which is where the
449 /// preset, the range, the destination and the decision to write at all are.
450 /// Nothing is encoded until the button in it is pressed. While an export
451 /// runs, the same door brings its progress back.
452 pub(crate) fn open_export(&mut self, cx: &mut Context<Self>) {
453 // Nothing to write out, and a refusal rather than a card about it: the
454 // window is empty and the export path is not even chosen yet.
455 if self.session.is_none() {
456 self.notify_user("Nothing to export: no file open".into());
457 cx.notify();
458 return;
459 }
460 // A finished or failed face belongs to the export that made it; a
461 // sheet opened afterwards is a fresh one.
462 if self.export.is_none() {
463 self.export_sheet.done = None;
464 self.export_sheet.failed = None;
465 self.export_sheet.cancelled = false;
466 }
467 self.export_sheet.field = None;
468 self.export_sheet.note = None;
469 self.export_ask = false;
470 self.export_open = true;
471 self.transcript_open = false;
472 // One card at a time, and a waiting row must not outlive the card it
473 // was waiting in. Nor may a half-typed number: the card opens on the
474 // bitrate it will write, never on digits left behind by a closed one.
475 self.keys_open = false;
476 self.budget_edit = None;
477 cx.notify();
478 }
479
480 /// A format row, from Settings. The destination follows it at once -- a
481 /// WAV written to a path ending in `.mp4` is a file every player will lie
482 /// about -- keeping whatever stem the save dialog last left there.
483 /// `false` on a refusal, so a caller with more than the format to write
484 /// knows not to write the rest of it either.
485 pub(crate) fn set_format(&mut self, format: Format) -> bool {
486 // The one door both the row and its initial go through, so a format
487 // the room greys out cannot be picked by keyboard either.
488 if let Some(why) = self
489 .session
490 .as_ref()
491 .and_then(|session| format_refusal(session, format))
492 {
493 self.notify_user(format!("Not {} — {why}", format_label(format)).into());
494 return false;
495 }
496 self.format = format;
497 // Only an HEVC file carries an HDR tag; the engine refuses it on any other.
498 if !format.is_hevc() {
499 self.export_sheet.hdr = HdrTransfer::Sdr;
500 }
501 self.export_path = retarget(&self.export_path, format);
502 self.save_export_pick();
503 true
504 }
505
506 /// Writes the picture and sound this computer exports with, so the next
507 /// launch opens on them. A failed write is said once; the pick still holds
508 /// for this session.
509 pub(crate) fn save_export_pick(&mut self) {
510 // Under test the real ~/.config is never written: only a scratch
511 // XDG_CONFIG_HOME (the override the config round-trip tests set) is.
512 #[cfg(test)]
513 if crate::keymap::xdg_config_home().is_none_or(|v| v.is_empty()) {
514 return;
515 }
516 if crate::export_ui::save_export_prefs(&self.export_prefs()).is_err() {
517 self.notify_user(
518 "Could not save the export pick. Check that ~/.config/edith is writable.".into(),
519 );
520 }
521 }
522
523 /// The choices this computer keeps between launches.
524 pub(crate) fn export_prefs(&self) -> crate::export_ui::ExportPrefs {
525 crate::export_ui::ExportPrefs {
526 format: self.format,
527 audio_kbps: self.audio_kbps,
528 bps: self.custom_bps,
529 size: self.export_sheet.size,
530 depth: self.export_sheet.bit_depth,
531 prores: self.export_sheet.prores,
532 hdr: self.export_sheet.hdr,
533 hevc_speed: self.export_sheet.hevc_speed,
534 sound_bits: self.export_sheet.sound_bits,
535 }
536 }
537
538 /// A Quality chip: the budget it names, set as the lever would set it. Any
539 /// typed value is dropped with it, so the field cannot reopen on a stale one.
540 pub(crate) fn set_budget(&mut self, bps: u64) {
541 self.custom_bps = bps.clamp(BPS_MIN, BPS_MAX);
542 self.budget_edit = None;
543 self.save_export_pick();
544 }
545
546
547 /// Which encoder an export of this project would write the picture with
548 /// ([`engine::export::EncoderSeat`]). The session's, because it is saved
549 /// with the project -- there is no card-local copy to drift from it -- and
550 /// the default with no timeline open, where the card shows nothing anyway.
551 pub(crate) fn encoder_seat(&self) -> EncoderSeat {
552 self.session
553 .as_ref()
554 .map_or_else(EncoderSeat::default, PlaybackSession::encoder_seat)
555 }
556
557 /// Pick the seat. Said out loud like every other pick that changes what a
558 /// file will be written by -- and the card's planned line re-probes by
559 /// itself, since the settings it is keyed on have changed
560 /// ([`Self::cache_export_seat`]).
561 pub(crate) fn apply_encoder(&mut self, seat: EncoderSeat, cx: &mut Context<Self>) {
562 if let Some(session) = &mut self.session {
563 let was = session.encoder_seat();
564 session.set_encoder_seat(seat);
565 // The seat is written by a settings-row click, so nothing in
566 // [`Player::act`]'s list arms it -- and the engine's setter takes
567 // no answer back, so the arm rides the seat having moved.
568 let changed = session.encoder_seat() != was;
569 if changed {
570 self.mark_dirty();
571 }
572 self.notify_user(format!("Encoder: {}", encoder_label(seat)).into());
573 }
574 cx.notify();
575 }
576
577 /// Why the sound row is not a choice right now, the engine answering about
578 /// the very project it would export. No session is the same answer as no
579 /// sound: there is nothing to write either way.
580 pub(crate) fn audio_rate_refusal(&self) -> Option<&'static str> {
581 match &self.session {
582 Some(session) => session.audio_rate_refusal(self.format, self.export_span().is_some(), false),
583 None => Some("no sound to write"),
584 }
585 }
586
587 /// The budget in force: what was chosen, or -- before anybody has chosen
588 /// -- the engine's own automatic figure for the picture that is open
589 /// ([`auto_bps`], its `BITS_PER_PIXEL` rule). Never zero, which is the
590 /// whole point: the lever it feeds is a promise about the file.
591 pub(crate) fn budget_bps(&self) -> u64 {
592 if self.custom_bps > 0 {
593 return self.custom_bps;
594 }
595 self.session.as_ref().map_or(6_000_000, |s| {
596 let (w, h) = s.resolution();
597 auto_bps(w, h, s.meta().frame_rate)
598 })
599 }
600
601 /// What the sound costs over the same span, in bits per second -- the
602 /// other half of "how big is it": zero for a format that writes no sound
603 /// and for a timeline that has none.
604 pub(crate) fn audio_bps(&self) -> u64 {
605 match self.audio_rate_refusal().is_none() {
606 true => u64::from(self.audio_kbps) * 1_000,
607 false => 0,
608 }
609 }
610
611 /// How many seconds of film the export writes: the marked span where
612 /// there is one, the whole timeline otherwise. The size on the budget row
613 /// is this times the rate.
614 pub(crate) fn export_seconds(&self) -> f64 {
615 self.session.as_ref().map_or(0., |s| match self.export_span() {
616 Some((start, end)) => f64::from(end - start) / s.meta().frame_rate,
617 None => s.timeline_duration(),
618 })
619 }
620
621 /// The missing files the export would read: sources that are not on disk and that a clip
622 /// inside the chosen range uses. A file only clips outside the range use does not count.
623 pub(crate) fn export_missing(&self) -> Vec<PathBuf> {
624 let Some(session) = &self.session else { return Vec::new() };
625 session.offline_in_span(self.export_span()).into_iter().map(|(_, path)| path).collect()
626 }
627
628 /// Why the Export button is off, in a short plain phrase -- `None` when it can start.
629 pub(crate) fn export_block_reason(&self) -> Option<String> {
630 let Some(session) = &self.session else {
631 return Some("Nothing to export yet".to_string());
632 };
633 if let Some(why) = format_refusal(session, self.format) {
634 return Some(why.split(" \u{2014} ").next().unwrap_or("cannot export").to_string());
635 }
636 if self.export_seconds() <= 0. {
637 return Some("Nothing to export: the range is empty".to_string());
638 }
639 let missing = self.export_missing();
640 match missing.len() {
641 0 => None,
642 1 => Some("1 file is missing: relink it first".to_string()),
643 n => Some(format!("{n} files are missing: relink them first")),
644 }
645 }
646
647 /// The marked range as the export will really use it: cut to the timeline,
648 /// and `None` where nothing of it is left (marks left from before an edit
649 /// shortened the timeline) -- so a range that would write zero seconds is
650 /// never offered, and the export is the whole timeline, said so on the card.
651 pub(crate) fn export_range(&self) -> Option<(u32, u32)> {
652 let s = self.session.as_ref()?;
653 clamp_range(self.range?, crate::subs::frame_at(s.timeline_duration(), self.fps))
654 }
655
656 /// The range the export will write: the marks when they are valid and the
657 /// sheet's radio is on them, the whole timeline (`None`) otherwise.
658 pub(crate) fn export_span(&self) -> Option<(u32, u32)> {
659 self.export_range().filter(|_| !self.export_sheet.whole)
660 }
661
662 /// The settings a preset can change, as they stand.
663 pub(crate) fn picked(&self) -> Picked {
664 Picked {
665 format: self.format,
666 bps: self.custom_bps,
667 audio_kbps: self.audio_kbps,
668 size: self.export_sheet.size,
669 depth: self.export_sheet.bit_depth,
670 loudness: self.export_sheet.loudness,
671 prores: self.export_sheet.prores,
672 hdr: self.export_sheet.hdr,
673 }
674 }
675
676 /// The preset tile that describes the settings exactly, or `None` -- the
677 /// sheet's Custom.
678 pub(crate) fn current_preset(&self) -> Option<&'static engine::export_presets::Preset> {
679 matching_preset(self.picked(), self.export_sheet.preset).filter(|_| !self.export_sheet.custom)
680 }
681
682 /// The preset the box names: an engine preset the settings equal, else
683 /// "Match project" while they are exactly that, else `None` (Custom).
684 pub(crate) fn preset_now(&self) -> Option<&'static str> {
685 if self.export_sheet.custom {
686 return None;
687 }
688 if let Some(p) = self.current_preset() {
689 return Some(p.id);
690 }
691 let auto = self.session.as_ref().map_or(0, |s| {
692 let (w, h) = s.resolution();
693 auto_bps(w, h, s.meta().frame_rate)
694 });
695 let s = &self.export_sheet;
696 (self.format == Format::Mp4
697 && s.size.is_none()
698 && s.bit_depth.is_none()
699 && s.loudness.is_none()
700 && (self.custom_bps == 0 || self.custom_bps == auto)
701 && self.audio_kbps == DEFAULT_AUDIO_KBPS)
702 .then_some(MATCH_PROJECT)
703 }
704
705 /// A preset tile: every setting it names laid over the current ones by the
706 /// engine's own rule. A format this timeline cannot be written in is refused
707 /// by name and nothing changes.
708 pub(crate) fn choose_preset(&mut self, id: &str) {
709 if id == MATCH_PROJECT {
710 // H.264 MP4 at the project's own size and rate, the bitrate left
711 // automatic (the engine's figure for that size).
712 if !self.set_format(Format::Mp4) {
713 return;
714 }
715 self.audio_kbps = DEFAULT_AUDIO_KBPS;
716 self.custom_bps = 0;
717 self.export_sheet.size = None;
718 self.export_sheet.bit_depth = None;
719 self.export_sheet.loudness = None;
720 self.export_sheet.hdr = HdrTransfer::Sdr;
721 self.export_sheet.preset = Some(MATCH_PROJECT);
722 self.export_sheet.custom = false;
723 self.budget_edit = None;
724 self.save_export_pick();
725 return;
726 }
727 let Some(preset) = engine::export_presets::by_id(id) else {
728 return;
729 };
730 let next = picked_with(self.picked(), preset);
731 if next.format != self.format && !self.set_format(next.format) {
732 return;
733 }
734 self.audio_kbps = next.audio_kbps;
735 if next.bps > 0 {
736 self.custom_bps = next.bps.clamp(BPS_MIN, BPS_MAX);
737 }
738 self.export_sheet.size = next.size;
739 self.export_sheet.bit_depth = next.depth;
740 self.export_sheet.loudness = next.loudness;
741 self.export_sheet.prores = next.prores;
742 self.export_sheet.hdr = next.hdr;
743 self.export_sheet.preset = Some(preset.id);
744 self.export_sheet.custom = false;
745 self.budget_edit = None;
746 self.save_export_pick();
747 }
748
749 /// The rows of one Details list ([`Pick::Export`]), the one in force marked.
750 pub(crate) fn export_choices(&self, row: ExportRow) -> Vec<ChoiceRow> {
751 let pick = |p: ExportPick, label: String, detail: String, on: bool| -> ChoiceRow {
752 (Choice::Export(p), label.into(), detail.into(), on)
753 };
754 match row {
755 ExportRow::Preset => {
756 let project = self.session.as_ref().map(PlaybackSession::resolution);
757 let current = self.preset_now();
758 let mut rows: Vec<ChoiceRow> = vec![pick(
759 ExportPick::Preset(MATCH_PROJECT),
760 "Match project".into(),
761 "project size \u{b7} H.264 \u{b7} auto".into(),
762 current == Some(MATCH_PROJECT),
763 )];
764 rows.extend(engine::export_presets::presets()
765 .iter()
766 .map(|p| pick(ExportPick::Preset(p.id), p.label.into(), preset_spec(p, project), current == Some(p.id))));
767 rows.push(pick(ExportPick::Custom, "Custom".into(), "set in Details".into(), current.is_none()));
768 rows
769 }
770 ExportRow::Container => {
771 let mut rows: Vec<ChoiceRow> = Vec::new();
772 for &(c, _, f) in &COMBOS {
773 if rows.iter().any(|(_, l, ..)| l.as_ref() == c) {
774 continue;
775 }
776 let target = format_in_container(c, self.format).unwrap_or(f);
777 rows.push(pick(ExportPick::Format(target), c.into(), String::new(), container_word(self.format) == c));
778 }
779 rows
780 }
781 ExportRow::Codec => COMBOS
782 .iter()
783 .filter(|(c, ..)| *c == container_word(self.format))
784 .map(|&(_, k, f)| pick(ExportPick::Format(f), k.into(), String::new(), self.format == f))
785 .collect(),
786 ExportRow::Seat => ENCODER_SEATS
787 .into_iter()
788 .map(|s| (Choice::Encoder(s), encoder_label(s).into(), seat_plain(s).into(), self.encoder_seat() == s))
789 .collect(),
790 ExportRow::Bitrate => {
791 let budget = self.budget_bps();
792 let mut rows: Vec<ChoiceRow> = BITRATE_STEPS
793 .iter()
794 .map(|&m| pick(ExportPick::Bitrate(Some(m * 1_000_000)), format!("{m} Mb/s"), String::new(), budget == m * 1_000_000))
795 .collect();
796 if !BITRATE_STEPS.iter().any(|&m| budget == m * 1_000_000) {
797 rows.push(pick(ExportPick::Bitrate(Some(budget)), format!("{} Mb/s", rate_label(budget)), "now".into(), true));
798 }
799 rows.push(pick(ExportPick::Bitrate(None), "Type a value\u{2026}".into(), String::new(), false));
800 rows
801 }
802 ExportRow::Size => {
803 let project = self.session.as_ref().map(PlaybackSession::resolution);
804 let same = project.map_or("Same as project".to_string(), |(w, h)| format!("Same as project ({w}\u{d7}{h})"));
805 std::iter::once(pick(ExportPick::Size(None), same, String::new(), self.export_sheet.size.is_none()))
806 .chain(RESOLUTIONS.iter().map(|&(w, h)| {
807 pick(ExportPick::Size(Some((w, h))), format!("{w}\u{d7}{h}"), String::new(), self.export_sheet.size == Some((w, h)))
808 }))
809 .collect()
810 }
811 ExportRow::GifWidth => crate::export_ui::GIF_WIDTHS
812 .into_iter()
813 .map(|w| pick(ExportPick::GifWidth(w), format!("{w} px"), String::new(), self.export_sheet.gif.width == w))
814 .collect(),
815 ExportRow::GifFps => crate::export_ui::GIF_FPS
816 .into_iter()
817 .map(|f| pick(ExportPick::GifFps(f), format!("{f} fps"), String::new(), self.export_sheet.gif.fps == f))
818 .collect(),
819 ExportRow::GifLoop => [(true, "Loop forever"), (false, "Play once")]
820 .into_iter()
821 .map(|(on, l)| pick(ExportPick::GifLoop(on), l.into(), String::new(), self.export_sheet.gif.loop_forever == on))
822 .collect(),
823 ExportRow::Depth => [(None, "Same as source"), (Some(8), "8-bit"), (Some(10), "10-bit")]
824 .into_iter()
825 .map(|(d, l)| pick(ExportPick::Depth(d), l.into(), String::new(), self.export_sheet.bit_depth == d))
826 .collect(),
827 ExportRow::Profile => ProResProfile::ALL
828 .into_iter()
829 .map(|q| pick(ExportPick::Profile(q), q.name().into(), profile_plain(q).into(), self.export_sheet.prores == q))
830 .collect(),
831 ExportRow::Hdr => [
832 (HdrTransfer::Sdr, "Off", "standard picture"),
833 (HdrTransfer::Pq, "HDR10 (PQ)", "for HDR TVs and YouTube HDR"),
834 (HdrTransfer::Hlg, "HLG", "for broadcast HDR"),
835 ]
836 .into_iter()
837 .map(|(h, l, d)| pick(ExportPick::Hdr(h), l.into(), d.into(), self.export_sheet.hdr == h))
838 .collect(),
839 ExportRow::SoundDepth => [(Some(16), "16-bit", "smaller files"), (None, "24-bit", "studio quality")]
840 .into_iter()
841 .map(|(b, l, d)| pick(ExportPick::SoundBits(b), l.into(), d.into(), self.export_sheet.sound_bits == b))
842 .collect(),
843 ExportRow::Kbps => audio_rate_choices(self.audio_kbps),
844 ExportRow::Loudness => std::iter::once(pick(ExportPick::Loudness(None), "Off".into(), String::new(), self.export_sheet.loudness.is_none()))
845 .chain(LOUDNESS_CHOICES.iter().enumerate().map(|(n, &(label, lufs, peak))| {
846 let on = self.export_sheet.loudness == Some(engine::export::LoudnessTarget { lufs, true_peak_dbtp: peak });
847 pick(ExportPick::Loudness(Some(n)), label.into(), crate::export_ui::loudness_plain(lufs).into(), on)
848 }))
849 .collect(),
850 ExportRow::Captions => [(true, "Keep as a track", "when the file can"), (false, "Leave out", "")]
851 .into_iter()
852 .map(|(keep, l, d)| pick(ExportPick::Captions(keep), l.into(), d.into(), self.export_sheet.no_captions != keep))
853 .collect(),
854 }
855 }
856
857 /// Why a list row cannot be picked now (shown on hover, the row dimmed).
858 pub(crate) fn export_choice_refusal(&self, choice: Choice) -> Option<String> {
859 match choice {
860 Choice::Export(ExportPick::Format(f)) => self
861 .session
862 .as_ref()
863 .and_then(|s| format_refusal(s, f))
864 .map(|why| why.split(" \u{2014} ").next().unwrap_or("not available").to_string()),
865 _ => None,
866 }
867 }
868
869 /// A Details answer, through the same doors the old tiles and chips used.
870 /// Any detail flips the preset box to "Custom (from X)".
871 pub(crate) fn apply_export_pick(&mut self, pick: ExportPick, cx: &mut Context<Self>) {
872 match pick {
873 ExportPick::Preset(id) => {
874 self.choose_preset(id);
875 return cx.notify();
876 }
877 ExportPick::Custom => {
878 if self.folds.insert(EXPORT_MORE_FOLD.to_owned()) {
879 save_folds(&self.folds);
880 }
881 }
882 // Typing a rate in: the field commits it ([`Self::commit_budget`]).
883 ExportPick::Bitrate(None) => self.edit_budget(),
884 detail => {
885 self.export_sheet.custom = true;
886 match detail {
887 ExportPick::Format(f) => {
888 self.set_format(f);
889 }
890 ExportPick::Size(size) => self.set_export_size(size),
891 ExportPick::Bitrate(bps) => self.set_budget(bps.unwrap_or_default()),
892 ExportPick::Depth(d) => {
893 self.export_sheet.bit_depth = d;
894 // HDR is 10-bit only: asking for 8 bits turns it off.
895 if d == Some(8) {
896 self.export_sheet.hdr = HdrTransfer::Sdr;
897 }
898 }
899 ExportPick::Profile(q) => self.export_sheet.prores = q,
900 ExportPick::Hdr(h) => {
901 self.export_sheet.hdr = h;
902 if h != HdrTransfer::Sdr {
903 self.export_sheet.bit_depth = Some(10);
904 }
905 }
906 ExportPick::HevcSpeed(s) => self.export_sheet.hevc_speed = s,
907 ExportPick::SoundBits(b) => self.export_sheet.sound_bits = b,
908 ExportPick::Loudness(n) => {
909 self.export_sheet.loudness = n.map(|n| {
910 let (_, lufs, true_peak_dbtp) = LOUDNESS_CHOICES[n];
911 engine::export::LoudnessTarget { lufs, true_peak_dbtp }
912 })
913 }
914 ExportPick::Captions(keep) => self.export_sheet.no_captions = !keep,
915 ExportPick::GifWidth(w) => self.export_sheet.gif.width = w,
916 ExportPick::GifFps(f) => self.export_sheet.gif.fps = f,
917 ExportPick::GifLoop(on) => self.export_sheet.gif.loop_forever = on,
918 ExportPick::Preset(_) | ExportPick::Custom => {}
919 }
920 self.save_export_pick();
921 }
922 }
923 cx.notify();
924 }
925
926 /// The arrows on the tiles: the next preset in table order, wrapping.
927 pub(crate) fn step_preset(&mut self, delta: i32, cx: &mut Context<Self>) {
928 let table = engine::export_presets::presets();
929 let at = self
930 .preset_now()
931 .or(self.export_sheet.preset)
932 .and_then(|id| table.iter().position(|q| q.id == id));
933 let next = match at {
934 Some(at) => (at as i32 + delta).rem_euclid(table.len() as i32) as usize,
935 None => 0,
936 };
937 self.choose_preset(table[next].id);
938 cx.notify();
939 }
940
941 /// The canvas list: `None` follows the project.
942 pub(crate) fn set_export_size(&mut self, size: Option<(u32, u32)>) {
943 self.export_sheet.size = size;
944 }
945
946 /// The file's canvas as the export will draw it.
947 pub(crate) fn export_canvas(&self) -> (u32, u32) {
948 self.export_sheet
949 .size
950 .or_else(|| self.session.as_ref().map(PlaybackSession::resolution))
951 .unwrap_or((0, 0))
952 }
953
954 /// Whether the timeline carries any sound under this format and range.
955 pub(crate) fn export_has_sound(&self) -> bool {
956 self.session.as_ref().is_some_and(|s| {
957 let plan = s.planned_audio(self.format, self.export_span().is_some());
958 !plan.is_empty() && plan != "no sound to write"
959 })
960 }
961
962 /// Whether any video lane holds a clip.
963 pub(crate) fn export_has_picture(&self) -> bool {
964 self.session.as_ref().is_some_and(|s| {
965 s.lanes()
966 .into_iter()
967 .any(|l| l.kind == LaneKind::Video && !s.lane_clips(l).is_empty())
968 })
969 }
970
971 /// The lever by `steps` notches -- a tenth of a Mbps each, a whole Mbps
972 /// with shift. Clamped to the engine's own bounds, so the number on the
973 /// row is the number the encoder is given.
974 pub(crate) fn nudge_budget(&mut self, steps: i32, coarse: bool) {
975 // A video setting, like the field `n` opens: the sound-only moment
976 // draws no row for the lever, so nothing moves what it does not
977 // show -- the arrows, `+`/`-` and the wheel answer nothing there.
978 if !self.format.has_video() {
979 return;
980 }
981 let step = i64::from(steps)
982 * match coarse {
983 true => BPS_COARSE as i64,
984 false => BPS_FINE as i64,
985 };
986 let at = self.budget_bps() as i64 + step;
987 self.custom_bps = (at.max(0) as u64).clamp(BPS_MIN, BPS_MAX);
988 }
989
990 /// Opens the budget's field, empty: `n` is a way to *say* a budget
991 /// (`850k`, `6.5M`, `6.5`, `1.2G` of file), not a way to edit digits, and
992 /// the number in force is still on the row until enter takes the new one.
993 pub(crate) fn edit_budget(&mut self) {
994 // A video setting: the sound-only moment draws no row to type into,
995 // so its door opens nothing either -- the chord stays swallowed (the
996 // moment owns the keyboard) but no field opens under it.
997 if !self.format.has_video() {
998 return;
999 }
1000 self.budget_edit = Some(String::new());
1001 }
1002
1003 /// Takes what was typed, or says nothing and keeps the field open: a
1004 /// number that parses is clamped into the engine's range (and shown
1005 /// clamped, in the same keystroke), and one that does not is left to be
1006 /// fixed in place.
1007 pub(crate) fn commit_budget(&mut self) {
1008 let Some(text) = self.budget_edit.clone() else {
1009 return;
1010 };
1011 let (seconds, audio) = (self.export_seconds(), self.audio_bps());
1012 if let Some(bps) = parse_budget(&text, seconds, audio) {
1013 self.custom_bps = bps;
1014 self.budget_edit = None;
1015 self.export_sheet.custom = true;
1016 }
1017 }
1018
1019 /// Every stroke the sheet answers, and the reason it answers *all* of
1020 /// them: a chord this surface consumes must never also reach the room's
1021 /// keymap underneath it (the shipped defect where `n` opened the field
1022 /// *and* toggled the timeline snap). While the sheet is up it owns the
1023 /// keyboard -- `d`, `n`, `e`/`↵`, `←`/`→` on the tiles, `−`/`+`, escape do
1024 /// their thing, and everything else is swallowed rather than falling through.
1025 ///
1026 /// Escape retreats one step at a time (DESIGN.md:146): the question or the
1027 /// field first, the sheet second. A running export is not stopped by
1028 /// closing the sheet.
1029 pub(crate) fn export_moment_key(
1030 &mut self,
1031 key: &str,
1032 shift: bool,
1033 cx: &mut Context<Self>,
1034 ) -> bool {
1035 if !self.export_open {
1036 return false;
1037 }
1038 if self.export_ask {
1039 match key {
1040 "enter" => self.answer_overwrite(Overwrite::Replace, cx),
1041 "k" => self.answer_overwrite(Overwrite::KeepBoth, cx),
1042 ESCAPE => self.answer_overwrite(Overwrite::Cancel, cx),
1043 _ => {}
1044 }
1045 return true;
1046 }
1047 if let Some(text) = &mut self.budget_edit {
1048 match key {
1049 ESCAPE => self.budget_edit = None,
1050 "enter" => self.commit_budget(),
1051 "backspace" => {
1052 text.pop();
1053 }
1054 "up" | "right" => self.nudge_budget(1, shift),
1055 "down" | "left" => self.nudge_budget(-1, shift),
1056 // One character a stroke, which is all a rate is made of.
1057 k if k.chars().count() == 1 => text.push_str(k),
1058 _ => {}
1059 }
1060 return true;
1061 }
1062 // Running, finished or failed: the sheet shows that face, and its keys
1063 // are the way out of it.
1064 if self.export.is_some()
1065 || self.export_sheet.done.is_some()
1066 || self.export_sheet.failed.is_some()
1067 || self.export_sheet.cancelled
1068 {
1069 match key {
1070 // Escape never takes the tab away; it only closes a popup.
1071 ESCAPE => self.picker = None,
1072 "enter" if self.export.is_none() => self.leave_sheet_face(),
1073 _ => {}
1074 }
1075 return true;
1076 }
1077 match key {
1078 ESCAPE => self.picker = None,
1079 "d" => self.pick_destination(cx),
1080 // The budget lives under More settings: typing one opens it.
1081 "n" => {
1082 if self.format.has_video() && self.folds.insert(EXPORT_MORE_FOLD.to_owned()) {
1083 save_folds(&self.folds);
1084 }
1085 self.edit_budget();
1086 }
1087 "e" | "enter" => self.start_export(cx),
1088 "left" => self.step_preset(-1, cx),
1089 "right" => self.step_preset(1, cx),
1090 "up" => self.scroll_export(Some(48.)),
1091 "down" => self.scroll_export(Some(-48.)),
1092 "pageup" => self.scroll_export(Some(320.)),
1093 "pagedown" => self.scroll_export(Some(-320.)),
1094 "home" => self.scroll_export(None),
1095 "end" => self.scroll_export(Some(-1e6)),
1096 // corner-cut: the settings door answers a bare `,` as well as the
1097 // room's `^,` it wears, because `param_card_key` is handed shift
1098 // only -- ceiling: no modifier reaches a card's keys. Upgrade:
1099 // thread `Modifiers` through `ui::stance`'s handler.
1100 "," => self.open_settings(cx),
1101 "+" | "=" => self.nudge_budget(1, shift),
1102 "-" => self.nudge_budget(-1, shift),
1103 _ => {}
1104 }
1105 true
1106 }
1107
1108 /// Moves the export panel's body by `by` pixels (positive shows earlier
1109 /// rows), or back to the top for `None`; clamped to what there is.
1110 pub(crate) fn scroll_export(&self, by: Option<f32>) {
1111 let at = match by {
1112 Some(by) => (f32::from(self.export_scroll.offset().y) + by)
1113 .clamp(-f32::from(self.export_scroll.max_offset().height), 0.),
1114 None => 0.,
1115 };
1116 self.export_scroll.set_offset(point(px(0.), px(at)));
1117 }
1118
1119 /// Starts typing into a destination field, seeded with what it holds.
1120 pub(crate) fn begin_field(&mut self, field: SheetField) {
1121 let text = match field {
1122 SheetField::Name => self
1123 .export_path
1124 .file_stem()
1125 .map_or_else(String::new, |s| s.to_string_lossy().into_owned()),
1126 SheetField::Folder => dest_dir_text(&self.export_path),
1127 };
1128 self.export_sheet.field = Some((field, text));
1129 self.export_sheet.field_all = true;
1130 self.export_sheet.note = None;
1131 }
1132
1133 /// The keyboard while a destination field is being typed into (ahead of the
1134 /// sheet's own chords, as the cue editor is): enter takes it, escape gives
1135 /// it up, the rest is text. `key_char` is the character the layout made.
1136 pub(crate) fn export_field_key(
1137 &mut self,
1138 key: &str,
1139 ctrl: bool,
1140 alt: bool,
1141 key_char: Option<&str>,
1142 cx: &mut Context<Self>,
1143 ) {
1144 let all = &mut self.export_sheet.field_all;
1145 match key {
1146 ESCAPE => {
1147 self.export_sheet.field = None;
1148 self.export_sheet.note = None;
1149 self.export_sheet.field_all = false;
1150 }
1151 "enter" | "tab" => self.commit_field(),
1152 "a" if ctrl && !alt => *all = true,
1153 "backspace" => {
1154 if let Some((_, text)) = self.export_sheet.field.as_mut() {
1155 if *all {
1156 text.clear();
1157 } else {
1158 text.pop();
1159 }
1160 }
1161 *all = false;
1162 }
1163 _ => {
1164 if !ctrl
1165 && !alt
1166 && let Some((_, text)) = self.export_sheet.field.as_mut()
1167 && let Some(chars) = key_char
1168 {
1169 if *all {
1170 text.clear();
1171 }
1172 text.extend(chars.chars().filter(|c| !c.is_control()));
1173 *all = false;
1174 }
1175 }
1176 }
1177 cx.notify();
1178 }
1179
1180 /// Takes a destination edit still being typed before an export starts. A
1181 /// refused one stays open with its note, and the export does not start, so
1182 /// the file is never written somewhere other than what was typed.
1183 fn commit_pending_field(&mut self) -> bool {
1184 if self.export_sheet.field.is_some() {
1185 self.commit_field();
1186 }
1187 self.export_sheet.field.is_none()
1188 }
1189
1190 /// Leaves a finished, failed or cancelled face for the settings, with the
1191 /// sheet reset. The Export tab stays open.
1192 pub(crate) fn leave_sheet_face(&mut self) {
1193 self.export_sheet.done = None;
1194 self.export_sheet.failed = None;
1195 self.export_sheet.cancelled = false;
1196 self.export_sheet.field = None;
1197 self.export_sheet.note = None;
1198 self.cancel_armed = false;
1199 }
1200
1201 /// Whether `path` is one of the project's own source files.
1202 pub(crate) fn is_source_path(&self, path: &std::path::Path) -> bool {
1203 let Some(session) = self.session.as_ref() else {
1204 return false;
1205 };
1206 let sources: Vec<&std::path::Path> = session.sources().iter().map(|s| s.path.as_path()).collect();
1207 is_a_source(path, &sources)
1208 }
1209
1210 /// Takes the field's text: a refusal is said under the field in a plain
1211 /// sentence and the field stays open to be fixed.
1212 pub(crate) fn commit_field(&mut self) {
1213 let Some((field, text)) = self.export_sheet.field.clone() else {
1214 return;
1215 };
1216 let home = std::env::var("HOME").ok();
1217 let landed = match field {
1218 SheetField::Name => parse_stem(&text).map(|stem| {
1219 self.export_path
1220 .with_file_name(crate::export_ui::typed_name(&stem, self.format))
1221 }),
1222 SheetField::Folder => parse_folder(&text, home.as_deref()).map(|dir| {
1223 dir.join(
1224 self.export_path
1225 .file_name()
1226 .map_or_else(|| "export".into(), |n| n.to_owned()),
1227 )
1228 }),
1229 };
1230 // A name that is a source would write over the footage: refused here as
1231 // well as where it is typed, so no route can take it.
1232 let landed = landed.and_then(|path| match self.is_source_path(&path) {
1233 true => Err(SOURCE_NAME_TAKEN),
1234 false => Ok(path),
1235 });
1236 match landed {
1237 Ok(path) => {
1238 self.export_path = path;
1239 self.export_sheet.field = None;
1240 self.export_sheet.note = None;
1241 }
1242 Err(why) => self.export_sheet.note = Some(why.to_string()),
1243 }
1244 }
1245
1246 /// The answer to "that file already exists", from the sheet's buttons or
1247 /// its keys. Replace marks the target this window's own and goes back
1248 /// through the door; Keep both writes beside it under a new name.
1249 pub(crate) fn answer_overwrite(&mut self, answer: Overwrite, cx: &mut Context<Self>) {
1250 self.export_ask = false;
1251 match answer {
1252 Overwrite::Replace => {
1253 self.export_known = Some(self.export_path.clone());
1254 self.start_export(cx);
1255 }
1256 Overwrite::KeepBoth => {
1257 self.export_path = unique_path(&self.export_path, |p| p.exists());
1258 self.start_export(cx);
1259 }
1260 Overwrite::Cancel => {}
1261 }
1262 cx.notify();
1263 }
1264
1265 /// The sheet's Show in folder button.
1266 pub(crate) fn show_export_in_folder(&mut self, cx: &mut Context<Self>) {
1267 let Some(path) = self.export_sheet.done.as_ref().map(|d| d.path.clone()) else {
1268 return;
1269 };
1270 cx.background_executor()
1271 .spawn(async move { show_in_file_manager(&path) })
1272 .detach();
1273 }
1274
1275 /// The sheet's Play button: the desktop's own player, off the UI thread.
1276 pub(crate) fn play_export(&mut self, cx: &mut Context<Self>) {
1277 let Some(path) = self.export_sheet.done.as_ref().map(|d| d.path.clone()) else {
1278 return;
1279 };
1280 cx.background_executor()
1281 .spawn(async move { open_in_default_player(&path) })
1282 .detach();
1283 }
1284
1285 /// The measured pace for the format on the sheet: this codec's trial write
1286 /// if there was one, else what the last real export measured.
1287 pub(crate) fn sheet_pace(&self) -> Option<f64> {
1288 match self.export_sheet.paces.get(codec_word(self.format)) {
1289 Some(Some(pace)) => Some(*pace),
1290 _ => measured_pace(),
1291 }
1292 }
1293
1294 /// Whether the trial write for this format is still running or has not
1295 /// been tried: the time then reads "estimating…" and not a number.
1296 pub(crate) fn pace_pending(&self) -> bool {
1297 let key = codec_word(self.format);
1298 !self.export_sheet.paces.contains_key(key)
1299 }
1300
1301 /// Writes one second of this project in the sheet's format on the software
1302 /// seat (never the GPU) to a temporary file and times it, so the estimate is
1303 /// a measurement of this machine. Once per codec per session, on a worker,
1304 /// and only while the sheet is up and no real export is running.
1305 pub(crate) fn cache_export_pace(&mut self) {
1306 // Land a finished trial first, open sheet or not, so the loop that
1307 // waits on it stops.
1308 if let Some(bench) = &self.export_sheet.bench
1309 && let Some(result) = bench.handle.result()
1310 {
1311 let wall = bench.started.elapsed().as_secs_f64();
1312 let pace = result.ok().filter(|_| wall > 0.).map(|_| bench.media_secs / wall);
1313 let (landed, out) = (bench.key, bench.out.clone());
1314 self.export_sheet.paces.insert(landed, pace);
1315 self.export_sheet.bench = None;
1316 std::fs::remove_file(out).ok();
1317 }
1318 if !self.export_open || self.export.is_some() || self.export_ask {
1319 return;
1320 }
1321 let key = codec_word(self.format);
1322 if self.export_sheet.bench.is_some() || self.export_sheet.paces.contains_key(key) {
1323 return;
1324 }
1325 let Some(session) = &self.session else {
1326 return;
1327 };
1328 if session.is_empty() || session.timeline_duration() <= 0. {
1329 return;
1330 }
1331 let fps = session.meta().frame_rate;
1332 let media_secs = session.timeline_duration().min(1.);
1333 let frames = ((media_secs * fps).round() as u32).max(1);
1334 let settings = pace_bench_settings(
1335 self.budget_bps(),
1336 self.format,
1337 self.audio_kbps,
1338 self.export_sheet.size,
1339 self.export_sheet.bit_depth,
1340 frames,
1341 );
1342 let out = pace_bench_path(self.format);
1343 // `export::start` runs the encode on its own worker thread; this only
1344 // starts it, and the repaint loop lands it above.
1345 let handle = session.export_to_with(&out, &settings);
1346 self.export_sheet.bench = Some(PaceBench {
1347 key,
1348 handle,
1349 started: Instant::now(),
1350 media_secs: f64::from(frames) / fps,
1351 out,
1352 });
1353 }
1354
1355 /// The card's Destination row: the desktop's save dialog, on a background
1356 /// thread like the import chooser -- the user may sit in it and the window
1357 /// behind must not freeze. No chooser at all leaves the default path, which
1358 /// is what the refusal says.
1359 pub(crate) fn pick_destination(&mut self, cx: &mut Context<Self>) {
1360 let default = self.export_path.clone();
1361 let picked = cx
1362 .background_executor()
1363 .spawn(async move { pick_save(&default) });
1364 cx.spawn(async move |this, cx| {
1365 let picked = picked.await;
1366 this.update(cx, |this, cx| {
1367 // The dialog outlives the card: an export started meanwhile
1368 // took the old path and its notice must name what it wrote.
1369 if this.export.is_some() {
1370 return;
1371 }
1372 match picked {
1373 // The stem is the user's, the extension is the format's: a
1374 // FLAC named `.mp4` is a file every player lies about.
1375 Ok(Some(path)) => this.export_path = retarget(&path, this.format),
1376 // Cancelled: the default stands, as it did before.
1377 Ok(None) => {}
1378 Err(text) => {
1379 eprintln!("{text}");
1380 this.notify_user(text.into());
1381 }
1382 }
1383 cx.notify();
1384 })
1385 .ok();
1386 })
1387 .detach();
1388 }
1389
1390 /// The subtitle tracks an export of this timeline carries: every one a
1391 /// subtitle *lane* places, with a cue left in the exported range
1392 /// ([`PlaybackSession::timeline_cues`], the very map the file is written
1393 /// from), in the library's own order.
1394 ///
1395 /// On the timeline or not at all: a track sitting in the palette is a track
1396 /// nobody put anywhere, and one dropped off its lane is one somebody took
1397 /// away -- neither belongs in the file. Without the placement test they came
1398 /// back through the engine's palette door (`export::planned_subtitles` falls
1399 /// back to these picks when no lane holds anything), so emptying every
1400 /// subtitle lane and exporting wrote all three of them into the output.
1401 ///
1402 /// Worked out from the timeline each time rather than kept as a pick, which
1403 /// is what makes it impossible to desync: a row added or taken off shifts
1404 /// every index after it, and a stored list would then name tracks nobody
1405 /// chose. `Player::sub_track` stays what it always was -- which palette row
1406 /// the list *marks* -- and has no say here, and neither has the lane that is
1407 /// shown over the picture ([`Player::active_sub_lane`]): every lane travels.
1408 ///
1409 /// The honest input and not the final answer: the engine filters it again
1410 /// per track (a track that could not be read, a picture one) and says so in
1411 /// the card's own words ([`engine::export::planned_subtitles`]).
1412 /// Copies the chapters as YouTube description text ([`engine::playback::chapter_listing`]) and
1413 /// says so. Nothing happens with no chapters: the button is off then.
1414 pub(crate) fn copy_chapters(&mut self, cx: &mut Context<Self>) {
1415 let Some(session) = self.session.as_ref() else {
1416 return;
1417 };
1418 let (text, _) = session.youtube_chapters();
1419 if text.is_empty() {
1420 return;
1421 }
1422 let lines = text.lines().count();
1423 cx.write_to_clipboard(gpui::ClipboardItem::new_string(text));
1424 self.notify_user(format!("Copied {lines} chapter lines").into());
1425 cx.notify();
1426 }
1427
1428 pub(crate) fn export_subs(&self) -> Vec<usize> {
1429 let Some(session) = self.session.as_ref() else {
1430 return Vec::new();
1431 };
1432 let placed: Vec<usize> = session
1433 .subtitle_lanes()
1434 .into_iter()
1435 .flat_map(|lane| session.sub_lane(lane).iter().map(|sub| sub.track))
1436 .collect();
1437 (0..session.subtitles().len())
1438 .filter(|i| placed.contains(i))
1439 .filter(|&i| !session.timeline_cues(i).is_empty())
1440 .collect()
1441 }
1442
1443 /// That list in the card's words ([`subtitle_plan`]): what travels, and the
1444 /// reason beside every track that does not -- including the ones
1445 /// [`Self::export_subs`] filtered out before the engine ever saw them.
1446 #[allow(dead_code)] // shown by Settings now, not by the moment
1447 pub(crate) fn subtitle_line(&self) -> String {
1448 let Some(session) = self.session.as_ref() else {
1449 return "none".to_string();
1450 };
1451 let picks = self.export_subs();
1452 let plan = session.planned_subtitles(self.format, picks.iter().copied());
1453 match self.format.has_video() {
1454 true => subtitle_plan(plan, session.subtitles(), &picks),
1455 // A format that is the sound alone has nowhere to put any of them
1456 // and the engine says that once, about the file. Naming the cues of
1457 // each track under it answers a question the format already closed.
1458 false => plan,
1459 }
1460 }
1461
1462 /// Whether an export has to be answered instead of started: the target
1463 /// exists on disk and is not a file this window wrote (or had confirmed)
1464 /// -- the same rule the save door keeps, with `export_known` playing
1465 /// `autosave_armed`'s part (user 2026-09-11, "not just save but export
1466 /// too": exporting over an existing file must warn first).
1467 pub(crate) fn export_needs_answer(&self) -> bool {
1468 Self::export_asks(
1469 self.export_path.exists(),
1470 self.export_known.as_deref() == Some(self.export_path.as_path()),
1471 )
1472 }
1473
1474 /// The export question as a value: a target that is there and not ours.
1475 /// Split out of [`Player::export_needs_answer`] so the rule can be read
1476 /// and tested without a window or a session -- the same shape
1477 /// [`Player::save_asks`] keeps for Save.
1478 pub(crate) fn export_asks(target_exists: bool, known: bool) -> bool {
1479 target_exists && !known
1480 }
1481
1482 /// Writes the edit list out, at the settings the card was left at. Playback
1483 /// stops first: the exporter opens its own decoder -- and, on the hardware
1484 /// path, an encoder -- so a running player would only compete with it for
1485 /// the GPU. A cancelled export still winding down holds this off for the
1486 /// frame it takes to notice, which is what keeps its `remove_file` off the
1487 /// new output.
1488 pub(crate) fn start_export(&mut self, cx: &mut Context<Self>) {
1489 if self.export.is_some() {
1490 return;
1491 }
1492 if !self.commit_pending_field() {
1493 return cx.notify();
1494 }
1495 // One encode at a time: while the queue runs, a direct Export is one more job at its end.
1496 if self.queue.is_going() {
1497 self.enqueue_export(cx);
1498 return;
1499 }
1500 let settings = self.export_settings_now();
1501 // Asked here, before `session` borrows `self` mutably for the fences
1502 // below; nothing between here and the ask touches `export_path` or
1503 // `export_known`, so the answer cannot go stale on the way.
1504 let overwrite = self.export_needs_answer();
1505 let missing = self.export_missing();
1506 let Some(session) = &mut self.session else {
1507 self.notify_user("Nothing to export: no file open".into());
1508 cx.notify();
1509 return;
1510 };
1511 // An emptied timeline is a timeline; it is simply not a file. Refused by
1512 // name here rather than written as a project of no frames -- and the
1513 // engine refuses it again on the worker (`export::start`), so a caller
1514 // that is not this button cannot get past it either. Two fences on
1515 // purpose: this one is the one with a keystroke to blame.
1516 if session.is_empty() {
1517 self.notify_user("Nothing to export: the timeline is empty".into());
1518 cx.notify();
1519 return;
1520 }
1521 // A source the range reads that is not on disk is named before anything starts, not as a
1522 // bare "No such file" from the worker.
1523 if !missing.is_empty() {
1524 let names: Vec<String> = missing.iter().map(|p| file_name(p)).collect();
1525 self.notify_user(format!("Not exported — missing: {}", names.join(", ")).into());
1526 cx.notify();
1527 return;
1528 }
1529 // The format row can be refused *after* it was picked -- mp4 is the
1530 // default and an audio-only timeline (or a second audio lane) is one
1531 // edit away -- so the button asks again rather than starting a worker
1532 // that will only settle with the same refusal minutes later.
1533 if let Some(why) = format_refusal(session, self.format) {
1534 self.notify_user(format!("Not exported — {why}").into());
1535 cx.notify();
1536 return;
1537 }
1538 // The last fence, after every refusal so an export that cannot run
1539 // never asks: writing over a file this window did not write is a
1540 // question, not a default. The card closes with the asking -- the
1541 // plate rises where notices rise and the moment is an overlay over
1542 // exactly that strip, so the two may not be on screen together.
1543 // `enter` there ([`ui::stance`]'s root handler) marks the target
1544 // known and comes back through this door, which then passes.
1545 if overwrite {
1546 self.export_ask = true;
1547 cx.notify();
1548 return;
1549 }
1550 session.pause();
1551 // A trial write still running would fight the real one for the CPU.
1552 if let Some(bench) = self.export_sheet.bench.take() {
1553 bench.handle.cancel();
1554 std::fs::remove_file(&bench.out).ok();
1555 }
1556 self.export_sheet.done = None;
1557 self.export_sheet.failed = None;
1558 self.export_sheet.cancelled = false;
1559 self.export = Some(session.export_to_with(&self.export_path, &settings));
1560 // Ours from the first packet on: a re-export over this window's own
1561 // output is not a question (the plate's `enter` sets the same mark
1562 // before coming back through the door).
1563 self.export_known = Some(self.export_path.clone());
1564 // The clock starts with the worker, not with the first repaint that
1565 // happens to notice it.
1566 self.export_started = Some(Instant::now());
1567 self.export_marks.clear();
1568 // A confirm left armed by the *previous* export would open this one on
1569 // the pair, offering to cancel a job nobody has asked about yet.
1570 self.cancel_armed = false;
1571 // The sheet stays up and turns into the progress face; "Keep editing"
1572 // closes it and the export carries on under the Export chip.
1573 cx.notify();
1574 }
1575
1576 /// The settings the sheet is left at, as the exporter takes them.
1577 fn export_settings_now(&self) -> ExportSettings {
1578 let mut settings = export_settings(
1579 self.budget_bps(),
1580 self.format,
1581 self.audio_kbps,
1582 self.encoder_seat(),
1583 );
1584 // Whatever is on the timeline travels -- every track with a cue in the
1585 // exported range, not the one row the overlay happens to be drawing.
1586 // Set here rather than inside `export_settings`, which the card also
1587 // calls for the *estimate* and which nothing else needs a subtitle for.
1588 settings.subtitles = self.export_subs();
1589 settings.range = self.export_span();
1590 settings.size = self.export_sheet.size;
1591 settings.video_bit_depth = self.export_sheet.bit_depth;
1592 settings.loudness = self.export_sheet.loudness;
1593 settings.prores_profile = self.export_sheet.prores;
1594 settings.hdr = HdrOutput { transfer: self.export_sheet.hdr, ..HdrOutput::default() };
1595 settings.hevc_speed = (self.format.is_hevc() && self.export_sheet.hevc_speed != HevcSpeed::Default).then_some(self.export_sheet.hevc_speed);
1596 settings.audio_bit_depth = self.export_sheet.sound_bits;
1597 settings.no_soft_subtitles = self.export_sheet.no_captions;
1598 settings.gif = self.export_sheet.gif;
1599 // A still is the frame under the playhead, whatever the range was.
1600 if self.format == Format::Still {
1601 let at = self.session.as_ref().map_or(0, |s| (s.now() * self.fps).floor().max(0.0) as u32);
1602 settings.range = Some((at, at + 1));
1603 }
1604 settings
1605 }
1606
1607 /// "Add to queue": the sheet's settings and the timeline as it is now,
1608 /// kept as one more job. Nothing is encoded until the queue is started
1609 /// (or is already going). Refused for the same reasons a direct export is,
1610 /// and never asks about overwriting: a name already taken gets a number.
1611 pub(crate) fn enqueue_export(&mut self, cx: &mut Context<Self>) {
1612 if !self.commit_pending_field() {
1613 return cx.notify();
1614 }
1615 let missing = self.export_missing();
1616 let Some(session) = &self.session else {
1617 self.notify_user("Nothing to export: no file open".into());
1618 cx.notify();
1619 return;
1620 };
1621 let refusal = if session.is_empty() {
1622 Some("Nothing to export: the timeline is empty".to_string())
1623 } else if !missing.is_empty() {
1624 let names: Vec<String> = missing.iter().map(|p| file_name(p)).collect();
1625 Some(format!("Not exported \u{2014} missing: {}", names.join(", ")))
1626 } else {
1627 format_refusal(session, self.format).map(|why| format!("Not exported \u{2014} {why}"))
1628 };
1629 if let Some(why) = refusal {
1630 self.notify_user(why.into());
1631 cx.notify();
1632 return;
1633 }
1634 let mut settings = self.export_settings_now();
1635 if settings.chapters.is_empty() {
1636 settings.chapters = session.chapter_list_ns(settings.range);
1637 }
1638 let (mut project, meta) = session.export_snapshot();
1639 if let Some(range) = settings.range {
1640 project.drop_offline_outside(range, engine::source_present);
1641 }
1642 let snapshot = crate::export_queue::Snapshot { project, meta, settings, sample_rate: session.sample_rate() };
1643 let out = crate::export_queue::free_name(&self.export_path, |p| p.exists() || self.queue.claimed(p));
1644 let what = self.current_preset().map_or_else(|| sheet_format_name(self.format).to_string(), |p| p.label.to_string());
1645 let summary = format!("{what} \u{b7} {}", crate::ui::cards::length_words(self.export_seconds() as f32));
1646 self.queue.add(out, summary, snapshot);
1647 // The next one added starts from a clean sheet face, not the last result.
1648 self.export_sheet.done = None;
1649 self.export_sheet.failed = None;
1650 self.export_sheet.cancelled = false;
1651 let n = self.queue.unfinished();
1652 let text = match self.queue.is_going() {
1653 true => format!("Added to the queue \u{2014} {n} to go"),
1654 false => format!("Added to the queue ({n}). Start it when you are ready"),
1655 };
1656 self.notify_user(text.into());
1657 cx.notify();
1658 }
1659
1660 /// "Start queue": the jobs run one after another from here on.
1661 pub(crate) fn queue_start(&mut self, cx: &mut Context<Self>) {
1662 self.queue.start();
1663 cx.notify();
1664 }
1665
1666 /// "Pause after this job": the one writing now finishes, the rest wait.
1667 pub(crate) fn queue_pause(&mut self, cx: &mut Context<Self>) {
1668 self.queue.pause();
1669 cx.notify();
1670 }
1671
1672 pub(crate) fn queue_cancel(&mut self, id: u64, cx: &mut Context<Self>) {
1673 self.queue.cancel(id);
1674 cx.notify();
1675 }
1676
1677 pub(crate) fn queue_remove(&mut self, id: u64, cx: &mut Context<Self>) {
1678 self.queue.remove(id);
1679 cx.notify();
1680 }
1681
1682 pub(crate) fn queue_clear_finished(&mut self, cx: &mut Context<Self>) {
1683 self.queue.clear_finished();
1684 cx.notify();
1685 }
1686
1687 pub(crate) fn queue_show_in_folder(&mut self, id: u64, cx: &mut Context<Self>) {
1688 let Some(path) = self.queue.job(id).map(|j| j.out.clone()) else {
1689 return;
1690 };
1691 cx.background_executor()
1692 .spawn(async move { show_in_file_manager(&path) })
1693 .detach();
1694 }
1695
1696 /// Settles the queue's running job when its worker is done, and starts
1697 /// the next one when the queue is going and nothing else is encoding.
1698 pub(crate) fn poll_queue(&mut self) {
1699 if let Some(id) = self.queue.running_id() {
1700 let result = self
1701 .queue
1702 .job(id)
1703 .and_then(|j| j.handle.as_ref())
1704 .and_then(ExportHandle::result);
1705 if let Some(result) = result {
1706 let out = self.queue.job(id).map(|j| j.out.clone()).unwrap_or_default();
1707 let bytes = std::fs::metadata(&out).map_or(0, |m| m.len());
1708 let state = self.queue.settle(id, result.map_err(|e| e.to_string()), bytes);
1709 let name = file_name(&out);
1710 match state {
1711 Some(crate::export_queue::JobState::Done { .. }) => {
1712 eprintln!("{EXPORT_DONE}{name}");
1713 self.notify_user(format!("{EXPORT_DONE}{name}").into());
1714 }
1715 Some(crate::export_queue::JobState::Failed(why)) => {
1716 eprintln!("Export failed: {name}: {why}");
1717 self.notify_user(format!("Export failed: {name} \u{2014} {why}").into());
1718 }
1719 _ => {}
1720 }
1721 }
1722 }
1723 if let Some(id) = self.queue.next_ready(self.export.is_some())
1724 && let Some((snap, out)) = self.queue.begin(id)
1725 {
1726 if let Some(session) = &mut self.session {
1727 session.pause();
1728 }
1729 let handle = engine::export::start(snap.project, snap.meta, &out, &snap.settings, snap.sample_rate);
1730 self.queue.attach(id, handle);
1731 }
1732 }
1733
1734 /// The quit question's words about the queue, if it has work left.
1735 pub(crate) fn queue_quit_note(&self) -> Option<String> {
1736 let n = self.queue.unfinished();
1737 let running = self.queue.running_id().is_some();
1738 match (n, running) {
1739 (0, _) => None,
1740 (1, true) => Some("An export is still being written; closing stops it.".to_string()),
1741 (n, true) => Some(format!("{n} exports are in the queue, one is being written; closing stops them.")),
1742 (1, false) => Some("An export is waiting in the queue; closing drops it.".to_string()),
1743 (n, false) => Some(format!("{n} exports are waiting in the queue; closing drops them.")),
1744 }
1745 }
1746
1747 /// Gives the editor back at once and leaves the worker to stop at its next
1748 /// frame and delete what it has written.
1749 pub(crate) fn cancel_export(&mut self) {
1750 if let Some(export) = &self.export {
1751 export.cancel();
1752 self.cancelling = true;
1753 self.cancel_armed = false;
1754 self.notify_user("Export cancelled".into());
1755 }
1756 }
1757
1758 /// Takes the export's verdict once it has one. The only place the app
1759 /// touches the handle's completion side.
1760 pub(crate) fn poll_export(&mut self) {
1761 // Sampled here rather than while drawing: a repaint stays a repaint,
1762 // and this runs once per repaint either way.
1763 if let (Some(progress), Some(started)) = (
1764 self.exporting().map(ExportHandle::progress),
1765 self.export_started,
1766 ) {
1767 note_progress(
1768 &mut self.export_marks,
1769 started.elapsed().as_secs_f32(),
1770 progress,
1771 );
1772 }
1773 let Some(result) = self.export.as_ref().and_then(ExportHandle::result) else {
1774 return;
1775 };
1776 self.export = None;
1777 let wall = self
1778 .export_started
1779 .take()
1780 .map(|t| t.elapsed().as_secs_f64());
1781 // A cancel that landed is reported as an error: the sheet says it was
1782 // cancelled. A job that finished before the cancel took hold is a
1783 // finished export, and its done face is the one shown.
1784 let cancelled = std::mem::take(&mut self.cancelling);
1785 self.cancel_armed = false;
1786 if cancelled && result.is_err() {
1787 self.export_sheet.cancelled = true;
1788 return;
1789 }
1790 let text = match result {
1791 Ok(()) => {
1792 // The next time estimate is priced from this machine's own pace.
1793 if let Some(wall) = wall {
1794 crate::export_ui::note_pace(self.export_seconds(), wall);
1795 }
1796 // The sheet's done face: what landed, how big, how long.
1797 self.export_sheet.done = Some(ExportDone {
1798 path: self.export_path.clone(),
1799 bytes: std::fs::metadata(&self.export_path).map_or(0, |m| m.len()),
1800 wall_secs: wall.unwrap_or(0.),
1801 });
1802 // Written and still where it was written: the bar carries it
1803 // until some other notice takes the bar.
1804 self.exported = Some(self.export_path.clone());
1805 format!("{EXPORT_DONE}{}", file_name(&self.export_path))
1806 }
1807 Err(e) => {
1808 let mut why = e.to_string();
1809 // A bare "No such file or directory" says nothing: name the files that are gone.
1810 if why.contains("No such file") || why.contains("os error 2") {
1811 let gone: Vec<String> = self
1812 .session
1813 .as_ref()
1814 .map(|s| s.offline_sources().iter().map(|(_, p)| file_name(p)).collect())
1815 .unwrap_or_default();
1816 if !gone.is_empty() {
1817 why = format!("{why} \u{2014} missing: {}", gone.join(", "));
1818 }
1819 }
1820 self.export_sheet.failed = Some(why.clone());
1821 eprintln!("Export failed: {why}");
1822 format!(
1823 "Export failed: {}",
1824 crate::export_ui::failure_words(&why, &dest_dir_text(&self.export_path))
1825 )
1826 }
1827 };
1828 eprintln!("{text}");
1829 // The Export tab's own done/failed face says it; a toast on top of it
1830 // would be the same news twice.
1831 if !self.export_tab_visible() {
1832 self.notify_user(text.into());
1833 }
1834 }
1835
1836 /// Whether the dock is showing the Export tab right now.
1837 pub(crate) fn export_tab_visible(&self) -> bool {
1838 self.export_open && !self.keys_open
1839 }
1840}
1841
1842/// `range` cut to a timeline `len` frames long; `None` where nothing is left.
1843pub(crate) fn clamp_range((start, end): (u32, u32), len: u32) -> Option<(u32, u32)> {
1844 let end = end.min(len);
1845 (start < end).then_some((start, end))
1846}
1847
1848#[cfg(test)]
1849mod range_tests {
1850 use super::clamp_range;
1851
1852 #[test]
1853 fn stale_marks_never_make_a_zero_second_export() {
1854 assert_eq!(clamp_range((0, 1), 3120), Some((0, 1)));
1855 assert_eq!(clamp_range((100, 5000), 3120), Some((100, 3120)));
1856 // Marks left past the end of a since-shortened timeline: whole film.
1857 assert_eq!(clamp_range((3200, 3300), 3120), None);
1858 assert_eq!(clamp_range((3120, 3121), 3120), None);
1859 }
1860}