av1converter 2.6.0

A terminal-based interactive tool to batch convert video files to the AV1 codec using FFmpeg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
use crate::analyzer::{self, AnalysisResult, DvMode, HdrType, is_av1_codec};
use crate::config::{AppConfig, Encoder};
use crate::error::AppError;
use crate::queue::{
    EncodingJob, JobStatus, QueueState, WorkerJob, WorkerMessage, auto_select_tracks,
    collect_video_files, is_video_file, run_worker,
};
use crate::utils::DependencyStatus;
use ratatui::widgets::ListState;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver};
use std::thread;
use std::time::Instant;
use tracing::info;

/// Application screens
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Screen {
    Home,
    FileExplorer { select_folder: bool },
    FileConfirm,
    TrackConfig,
    Queue,
    Finish,
    Configuration,
}

/// File selection mode
#[derive(Debug, Clone, PartialEq)]
pub enum SelectionMode {
    File,
    Folder,
    FolderRecursive,
}

/// Track configuration focus
#[derive(Debug, Clone, PartialEq)]
pub enum TrackFocus {
    Audio,
    Subtitle,
    Confirm,
}

/// Confirmation dialog action
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ConfirmAction {
    CancelEncoding,
    ExitApp,
    AbandonTrackConfig,
    DiscardConfigChanges,
    CancelAnalysis,
}

pub const HOME_MENU: &[&str] = &[
    "Open Video File",
    "Open Folder",
    "Open Folder (Recursive)",
    "Configuration",
    "Quit",
];

/// Main application state
pub struct App {
    pub current_screen: Screen,
    pub should_quit: bool,
    pub selection_mode: SelectionMode,

    // File explorer
    pub current_dir: PathBuf,
    pub dir_entries: Vec<PathBuf>,
    pub explorer_index: usize,
    pub explorer_list_state: ListState,
    // Queue state (replaces Vec<VideoFile>)
    pub queue: QueueState,
    pub queue_cursor: usize,
    pub queue_list_state: ListState,

    // Track config
    pub track_focus: TrackFocus,
    pub audio_cursor: usize,
    pub subtitle_cursor: usize,
    pub audio_list_state: ListState,
    pub subtitle_list_state: ListState,

    // Home menu
    pub home_index: usize,

    // Multi-file selection
    pub selected_files: Vec<PathBuf>,
    pub file_confirm_scroll: usize,
    pub file_confirm_list_state: ListState,

    // Encoding
    pub encoding_active: bool,
    pub progress_receiver: Option<Receiver<WorkerMessage>>,
    pub cancel_flag: Arc<AtomicBool>,

    // Background analysis
    pub analysis_receiver: Option<Receiver<Vec<Result<AnalysisResult, AppError>>>>,
    /// Ask the analysis thread to stop spawning new ffprobe calls
    pub analysis_cancel_flag: Arc<AtomicBool>,

    // Configuration
    pub config: AppConfig,
    pub deps: bool,

    // UI state
    pub message: Option<String>,
    pub message_expiry: Option<Instant>,
    pub confirm_dialog: Option<(ConfirmAction, bool)>,
    /// Dolby Vision mode dialog: selected option (0 = keep DV, 1 = HDR10)
    pub dv_dialog: Option<usize>,

    // Config screen state
    pub config_selected: usize,
    pub config_edit_buffer: Option<String>,
    pub config_snapshot: Option<AppConfig>,

    // Finish screen
    pub finish_cursor: usize,
    pub finish_list_state: ListState,
}

impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}

impl App {
    pub fn new() -> Self {
        let current_dir = std::env::current_dir().unwrap_or_else(|_| {
            std::env::var_os("HOME")
                .or_else(|| std::env::var_os("USERPROFILE"))
                .map_or_else(
                    || {
                        if cfg!(windows) {
                            PathBuf::from("C:\\")
                        } else {
                            PathBuf::from("/")
                        }
                    },
                    PathBuf::from,
                )
        });
        let mut list_state = ListState::default();
        list_state.select(Some(0));
        let mut audio_list_state = ListState::default();
        audio_list_state.select(Some(0));
        let mut subtitle_list_state = ListState::default();
        subtitle_list_state.select(Some(0));
        let mut queue_list_state = ListState::default();
        queue_list_state.select(Some(0));
        let mut file_confirm_list_state = ListState::default();
        file_confirm_list_state.select(Some(0));
        let mut finish_list_state = ListState::default();
        finish_list_state.select(Some(0));

        let config = AppConfig::load();
        let deps = DependencyStatus::check();

        info!("Using encoder: {}", config.encoder);

        Self {
            current_screen: Screen::Home,
            should_quit: false,
            selection_mode: SelectionMode::File,
            current_dir,
            dir_entries: Vec::new(),
            explorer_index: 0,
            explorer_list_state: list_state,
            queue: QueueState::new(),
            queue_cursor: 0,
            queue_list_state,
            track_focus: TrackFocus::Audio,
            audio_cursor: 0,
            subtitle_cursor: 0,
            audio_list_state,
            subtitle_list_state,
            home_index: 0,
            selected_files: Vec::new(),
            file_confirm_scroll: 0,
            file_confirm_list_state,
            encoding_active: false,
            progress_receiver: None,
            cancel_flag: Arc::new(AtomicBool::new(false)),
            analysis_receiver: None,
            analysis_cancel_flag: Arc::new(AtomicBool::new(false)),
            config,
            deps,
            message: None,
            message_expiry: None,
            confirm_dialog: None,
            dv_dialog: None,
            config_selected: 0,
            config_edit_buffer: None,
            config_snapshot: None,
            finish_cursor: 0,
            finish_list_state,
        }
    }

    // Message handling

    pub fn set_message(&mut self, msg: &str) {
        self.message = Some(msg.to_string());
        self.message_expiry = None;
    }

    pub fn set_timed_message(&mut self, msg: &str, secs: u64) {
        self.message = Some(msg.to_string());
        self.message_expiry = Some(Instant::now() + std::time::Duration::from_secs(secs));
    }

    pub fn clear_message(&mut self) {
        self.message = None;
        self.message_expiry = None;
    }

    pub fn tick_message(&mut self) {
        if let Some(expiry) = self.message_expiry
            && Instant::now() >= expiry
        {
            self.message = None;
            self.message_expiry = None;
        }
    }

    // Navigation

    pub fn navigate_to_home(&mut self) {
        self.current_screen = Screen::Home;
        self.home_index = 0;
        self.selected_files.clear();
    }

    pub fn navigate_to_explorer(&mut self, select_folder: bool, recursive: bool) {
        self.selection_mode = if !select_folder {
            SelectionMode::File
        } else if recursive {
            SelectionMode::FolderRecursive
        } else {
            SelectionMode::Folder
        };
        self.refresh_dir_entries();
        self.current_screen = Screen::FileExplorer { select_folder };
    }

    pub fn navigate_to_track_config(&mut self) {
        self.reset_track_config_cursor();
        self.current_screen = Screen::TrackConfig;
    }

    // Dolby Vision dialog

    /// Open the DV-mode dialog if the job at `config_job_index` is a Dolby
    /// Vision source that still needs a decision. Hardware encoders cannot
    /// write the DV RPU, so those jobs are silently resolved to HDR10.
    pub fn maybe_open_dv_dialog(&mut self) {
        self.dv_dialog = None;

        let Some(job) = self.current_config_job() else {
            return;
        };
        let Some(meta) = job.metadata.as_ref() else {
            return;
        };
        if job.remux_only || job.dv_mode.is_some() || meta.hdr_type != HdrType::DolbyVision {
            return;
        }

        if self.config.encoder == Encoder::SvtAv1 {
            let recommended = DvMode::recommended_for(meta.dv_profile);
            self.dv_dialog = Some(dv_mode_index(recommended));
        } else if let Some(job) = self.current_config_job_mut() {
            job.dv_mode = Some(DvMode::ToHdr10);
        }
    }

    /// Re-open the DV-mode dialog from the track config screen ('d' key).
    pub fn reopen_dv_dialog(&mut self) {
        let Some(meta) = self.current_config_job().and_then(|j| j.metadata.as_ref()) else {
            return;
        };
        if meta.hdr_type != HdrType::DolbyVision {
            return;
        }
        if self.config.encoder != Encoder::SvtAv1 {
            let msg = crate::i18n::t(self.config.language, crate::i18n::Msg::DvRequiresSvt);
            self.set_timed_message(msg, 3);
            return;
        }
        let current = self
            .current_config_job()
            .and_then(|j| j.dv_mode)
            .unwrap_or_else(|| DvMode::recommended_for(meta.dv_profile));
        self.dv_dialog = Some(dv_mode_index(current));
    }

    /// Apply the selected DV mode to the current job and close the dialog.
    pub fn confirm_dv_dialog(&mut self) {
        if let Some(sel) = self.dv_dialog.take()
            && let Some(job) = self.current_config_job_mut()
        {
            job.dv_mode = Some(if sel == 0 {
                DvMode::KeepDolbyVision
            } else {
                DvMode::ToHdr10
            });
        }
    }

    /// Close the dialog with the recommended default (Esc).
    pub fn dismiss_dv_dialog(&mut self) {
        if self.dv_dialog.take().is_some() {
            let profile = self
                .current_config_job()
                .and_then(|j| j.metadata.as_ref())
                .and_then(|m| m.dv_profile);
            if let Some(job) = self.current_config_job_mut() {
                job.dv_mode.get_or_insert(DvMode::recommended_for(profile));
            }
        }
    }

    /// Reset track focus/cursors to match the job now at `config_job_index`.
    fn reset_track_config_cursor(&mut self) {
        let audio_count = self
            .current_config_job()
            .map_or(0, |j| j.audio_tracks.len());
        let subtitle_count = self
            .current_config_job()
            .map_or(0, |j| j.subtitle_tracks.len());
        self.track_focus = if audio_count > 0 {
            TrackFocus::Audio
        } else if subtitle_count > 0 {
            TrackFocus::Subtitle
        } else {
            TrackFocus::Confirm
        };
        self.audio_cursor = 0;
        self.subtitle_cursor = 0;
        self.maybe_open_dv_dialog();
    }

    pub fn navigate_to_queue(&mut self) {
        self.queue_cursor = 0;
        self.current_screen = Screen::Queue;
    }

    pub fn navigate_to_finish(&mut self) {
        // Update output sizes for all jobs that produced an output file
        for job in &mut self.queue.jobs {
            if matches!(
                job.status,
                JobStatus::Done
                    | JobStatus::DoneWithVmaf { .. }
                    | JobStatus::DoneVmafFailed { .. }
                    | JobStatus::QualityWarning { .. }
            ) && let Some(ref output_path) = job.output_path
            {
                job.output_size = std::fs::metadata(output_path).ok().map(|m| m.len());
            }
        }
        self.finish_cursor = 0;
        self.current_screen = Screen::Finish;
    }

    pub fn navigate_to_configuration(&mut self) {
        self.config_selected = 0;
        self.config_snapshot = Some(self.config.clone());
        self.current_screen = Screen::Configuration;
    }

    /// Whether the live config has diverged from the snapshot taken on entry
    /// to the Configuration screen
    pub fn config_is_dirty(&self) -> bool {
        self.config_snapshot
            .as_ref()
            .is_some_and(|s| *s != self.config)
    }

    pub fn navigate_to_file_confirm(&mut self) {
        self.file_confirm_scroll = 0;
        self.current_screen = Screen::FileConfirm;
    }

    /// Move the queue list cursor up (`forward = false`) or down (`forward =
    /// true`), clamped within the job list bounds.
    pub fn queue_move_cursor(&mut self, forward: bool) {
        if forward {
            if self.queue_cursor < self.queue.jobs.len().saturating_sub(1) {
                self.queue_cursor += 1;
            }
        } else if self.queue_cursor > 0 {
            self.queue_cursor -= 1;
        }
    }

    /// Move the Finish screen results-list cursor up (`forward = false`) or
    /// down (`forward = true`), clamped within the job list bounds.
    pub fn finish_move_cursor(&mut self, forward: bool) {
        if forward {
            if self.finish_cursor < self.queue.jobs.len().saturating_sub(1) {
                self.finish_cursor += 1;
            }
        } else if self.finish_cursor > 0 {
            self.finish_cursor -= 1;
        }
    }

    // File explorer

    pub fn refresh_dir_entries(&mut self) {
        self.dir_entries.clear();

        // Add parent directory
        if let Some(parent) = self.current_dir.parent()
            && parent != self.current_dir
        {
            self.dir_entries.push(PathBuf::from(".."));
        }

        // Read directory contents
        if let Ok(entries) = std::fs::read_dir(&self.current_dir) {
            let mut paths: Vec<PathBuf> = entries
                .filter_map(Result::ok)
                .map(|e| e.path())
                .filter(|p| p.is_dir() || is_video_file(p))
                .collect();

            // Sort: directories first, then files
            paths.sort_by(|a, b| match (a.is_dir(), b.is_dir()) {
                (true, false) => std::cmp::Ordering::Less,
                (false, true) => std::cmp::Ordering::Greater,
                _ => a.file_name().cmp(&b.file_name()),
            });

            self.dir_entries.extend(paths);
        }

        self.explorer_index = 0;
        self.explorer_list_state.select(Some(0));
    }

    pub fn explorer_move_up(&mut self) {
        if self.explorer_index > 0 {
            self.explorer_index -= 1;
            self.explorer_list_state.select(Some(self.explorer_index));
        }
    }

    pub fn explorer_move_down(&mut self) {
        if self.explorer_index < self.dir_entries.len().saturating_sub(1) {
            self.explorer_index += 1;
            self.explorer_list_state.select(Some(self.explorer_index));
        }
    }

    /// Toggle a file in the multi-select list
    pub fn toggle_file_selection(&mut self) {
        if self.dir_entries.is_empty() {
            return;
        }

        let selected = self.dir_entries[self.explorer_index].clone();
        if selected == Path::new("..") || selected.is_dir() || !is_video_file(&selected) {
            return;
        }

        if let Some(pos) = self.selected_files.iter().position(|f| f == &selected) {
            self.selected_files.remove(pos);
        } else {
            self.selected_files.push(selected);
        }
    }

    /// Confirm the queued files from the confirmation screen and start analysis
    pub fn confirm_queued_files(&mut self) {
        self.selected_files.clear();
        self.analyze_jobs();
    }

    /// Navigate back from file confirm to the explorer
    pub fn cancel_file_confirm(&mut self) {
        if self.selection_mode == SelectionMode::File {
            self.selected_files = self.queue.jobs.iter().map(|j| j.path.clone()).collect();
        }
        self.queue.jobs.clear();
        let select_folder = self.selection_mode == SelectionMode::Folder;
        self.current_screen = Screen::FileExplorer { select_folder };
    }

    pub fn enter_directory(&mut self) {
        if self.dir_entries.is_empty() {
            return;
        }

        let selected = self.dir_entries[self.explorer_index].clone();

        if selected == Path::new("..") {
            if let Some(parent) = self.current_dir.parent() {
                self.current_dir = parent.to_path_buf();
                self.refresh_dir_entries();
            }
        } else if selected.is_dir() {
            self.current_dir = selected;
            self.refresh_dir_entries();
        }
    }

    pub fn select_explorer_entry(&mut self) {
        if self.dir_entries.is_empty() {
            return;
        }

        let selected = self.dir_entries[self.explorer_index].clone();

        match self.selection_mode {
            SelectionMode::File => {
                if selected == Path::new("..") || selected.is_dir() {
                    self.enter_directory();
                } else if is_video_file(&selected) {
                    if self.selected_files.is_empty() {
                        // Single file
                        self.queue.reset();
                        self.queue.jobs.push(EncodingJob::new(selected));
                        self.analyze_jobs();
                    } else {
                        // Multi-file — include current file and go to confirmation
                        if !self.selected_files.contains(&selected) {
                            self.selected_files.push(selected);
                        }
                        self.queue.reset();
                        for path in &self.selected_files {
                            self.queue.jobs.push(EncodingJob::new(path.clone()));
                        }
                        self.navigate_to_file_confirm();
                    }
                }
            }
            SelectionMode::Folder | SelectionMode::FolderRecursive => {
                if selected == Path::new("..") || !selected.is_dir() {
                    self.enter_directory();
                } else {
                    let recursive = self.selection_mode == SelectionMode::FolderRecursive;
                    self.scan_folder(&selected, recursive);
                    if self.queue.jobs.is_empty() {
                        let msg =
                            crate::i18n::t(self.config.language, crate::i18n::Msg::NoVideoFiles);
                        self.set_message(msg);
                    } else if self.queue.jobs.len() == 1 {
                        // Single file in folder — proceed directly
                        self.analyze_jobs();
                    } else {
                        // Multiple files — show confirmation
                        self.navigate_to_file_confirm();
                    }
                }
            }
        }
    }

    pub fn scan_folder(&mut self, folder: &Path, recursive: bool) {
        self.queue.reset();

        if recursive {
            let mut paths: Vec<PathBuf> = Vec::new();
            collect_video_files(folder, &mut paths);
            paths.sort();
            for path in paths {
                self.queue.jobs.push(EncodingJob::new(path));
            }
        } else if let Ok(entries) = std::fs::read_dir(folder) {
            let mut paths: Vec<PathBuf> = entries
                .filter_map(Result::ok)
                .map(|e| e.path())
                .filter(|p| is_video_file(p))
                .collect();

            paths.sort();

            for path in paths {
                self.queue.jobs.push(EncodingJob::new(path));
            }
        }
    }

    fn analyze_jobs(&mut self) {
        // Pre-validate paths
        let mut paths: Vec<Result<String, AppError>> = Vec::new();
        for job in &mut self.queue.jobs {
            match job.path.to_string_lossy() {
                p if job.path.to_str().is_some() => {
                    paths.push(Ok(p.into_owned()));
                    job.status = JobStatus::Analyzing;
                }
                _ => {
                    // Path has non-UTF-8 bytes
                    job.status = JobStatus::Error {
                        message: "File path contains non-UTF-8 characters".to_string(),
                    };
                    self.queue.error_count += 1;
                    paths.push(Err(AppError::Analysis(
                        "File path contains non-UTF-8 characters".to_string(),
                    )));
                }
            }
        }

        self.analysis_cancel_flag = Arc::new(AtomicBool::new(false));
        let cancel_flag = self.analysis_cancel_flag.clone();

        let (tx, rx) = mpsc::channel();
        self.analysis_receiver = Some(rx);

        thread::spawn(move || {
            let results: Vec<Result<AnalysisResult, AppError>> = std::thread::scope(|s| {
                // Spawn one thread per valid path
                let handles: Vec<Option<_>> = paths
                    .iter()
                    .map(|pr| match pr {
                        Ok(p) => {
                            if cancel_flag.load(Ordering::Relaxed) {
                                None // skip remaining if already cancelled
                            } else {
                                let p = p.clone();
                                let flag = cancel_flag.clone();
                                Some(s.spawn(move || {
                                    if flag.load(Ordering::Relaxed) {
                                        Err(AppError::Analysis("Cancelled".to_string()))
                                    } else {
                                        analyzer::analyze(&p)
                                    }
                                }))
                            }
                        }
                        Err(_) => None,
                    })
                    .collect();

                handles
                    .into_iter()
                    .zip(paths.iter())
                    .map(|(handle, original)| match handle {
                        Some(h) => h.join().unwrap_or_else(|_| {
                            Err(AppError::Analysis("Analysis thread panicked".to_string()))
                        }),
                        None => match original {
                            Err(e) => Err(AppError::Analysis(e.to_string())),
                            Ok(_) => Err(AppError::Analysis("Cancelled".to_string())),
                        },
                    })
                    .collect()
            });
            let _ = tx.send(results);
        });

        self.navigate_to_queue();
    }

    /// Apply completed analysis results and advance to the next screen.
    fn apply_analysis_results(&mut self, results: Vec<Result<AnalysisResult, AppError>>) {
        let output_config = self.config.output.clone();
        let track_config = self.config.tracks.clone();

        for (job, result) in self.queue.jobs.iter_mut().zip(results) {
            match result {
                Ok(analysis) => {
                    let is_av1 = is_av1_codec(&analysis.metadata.codec_name);
                    job.metadata = Some(analysis.metadata);
                    job.audio_tracks = analysis.audio_tracks;
                    job.subtitle_tracks = analysis.subtitle_tracks;
                    job.remux_only = is_av1;
                    auto_select_tracks(job, &track_config);
                    job.generate_output_path(&output_config);
                    job.status = JobStatus::AwaitingConfig;
                }
                Err(ref e) if e.to_string().contains("Cancelled") => {
                    if matches!(job.status, JobStatus::Analyzing) {
                        job.status = JobStatus::Skipped {
                            reason: "Cancelled".to_string(),
                        };
                        self.queue.skipped_count += 1;
                    }
                }
                Err(e) => {
                    job.status = JobStatus::Error {
                        message: e.to_string(),
                    };
                    self.queue.error_count += 1;
                }
            }
        }

        // Find first job awaiting config
        self.queue.config_job_index = self
            .queue
            .jobs
            .iter()
            .position(|j| matches!(j.status, JobStatus::AwaitingConfig))
            .unwrap_or(0);

        if self
            .queue
            .jobs
            .iter()
            .any(|j| matches!(j.status, JobStatus::AwaitingConfig))
        {
            self.navigate_to_track_config();
        } else {
            self.navigate_to_finish();
        }
    }

    /// Poll the analysis channel; called every frame from the main loop.
    pub fn process_analysis_messages(&mut self) {
        let results = if let Some(ref rx) = self.analysis_receiver {
            rx.try_recv().ok()
        } else {
            return;
        };

        if let Some(results) = results {
            self.analysis_receiver = None;
            self.apply_analysis_results(results);
        }
    }

    /// Cancel an in-progress analysis and return to the home screen.
    pub fn cancel_analysis(&mut self) {
        // Signal the analysis thread to stop spawning new ffprobe calls
        self.analysis_cancel_flag.store(true, Ordering::Relaxed);
        self.analysis_receiver = None;
        self.queue.reset();
        self.navigate_to_home();
    }

    // Track configuration

    pub fn current_config_job(&self) -> Option<&EncodingJob> {
        self.queue.jobs.get(self.queue.config_job_index)
    }

    pub fn current_config_job_mut(&mut self) -> Option<&mut EncodingJob> {
        self.queue.jobs.get_mut(self.queue.config_job_index)
    }

    pub fn confirm_track_config(&mut self) {
        if let Some(job) = self.queue.jobs.get_mut(self.queue.config_job_index) {
            job.status = JobStatus::Ready;
        }

        // Find next job awaiting config
        let next_index = self
            .queue
            .jobs
            .iter()
            .skip(self.queue.config_job_index + 1)
            .position(|j| matches!(j.status, JobStatus::AwaitingConfig))
            .map(|i| i + self.queue.config_job_index + 1);

        if let Some(idx) = next_index {
            self.queue.config_job_index = idx;
            self.reset_track_config_cursor();
        } else {
            self.start_encoding();
        }
    }

    /// Abandon the whole batch and return to Home, discarding the queue.
    pub fn cancel_track_config(&mut self) {
        self.queue.reset();
        self.navigate_to_home();
    }

    /// Move to the previous (`forward = false`) or next (`forward = true`)
    /// configurable job in the batch, skipping jobs that never get a track
    /// config step (errored or skipped during analysis). No-op at either end.
    pub fn step_track_config_job(&mut self, forward: bool) {
        let len = self.queue.jobs.len();
        if len == 0 {
            return;
        }

        let mut idx = self.queue.config_job_index;
        loop {
            let next = if forward {
                idx.checked_add(1)
            } else {
                idx.checked_sub(1)
            };
            let Some(next) = next.filter(|&i| i < len) else {
                return;
            };
            idx = next;

            let configurable = self.queue.jobs.get(idx).is_some_and(|j| {
                !matches!(
                    j.status,
                    JobStatus::Error { .. } | JobStatus::Skipped { .. }
                )
            });
            if configurable {
                self.queue.config_job_index = idx;
                self.reset_track_config_cursor();
                return;
            }
        }
    }

    // Encoding

    pub fn start_encoding(&mut self) {
        info!("Starting encoding process");
        self.navigate_to_queue();
        self.encoding_active = true;
        self.queue.current_job_index = 0;
        self.cancel_flag = Arc::new(AtomicBool::new(false));

        let (tx, rx) = mpsc::channel();
        self.progress_receiver = Some(rx);

        let output_config = self.config.output.clone();

        // Collect jobs to encode
        let worker_jobs: Vec<WorkerJob> = self
            .queue
            .jobs
            .iter()
            .enumerate()
            .filter(|(_, j)| matches!(j.status, JobStatus::Ready))
            .filter_map(|(i, j)| {
                let metadata = j.metadata.clone()?;
                let output = j.output_path.clone().unwrap_or_else(|| {
                    let stem = j.path.file_stem().unwrap_or_default().to_string_lossy();
                    let parent = j.path.parent().unwrap_or(std::path::Path::new("."));
                    parent.join(format!(
                        "{}{}.{}",
                        stem, output_config.suffix, output_config.container
                    ))
                });
                Some(WorkerJob {
                    index: i,
                    input: j.path.clone(),
                    output,
                    metadata,
                    tracks: j.track_selection.clone(),
                    dv_mode: j.dv_mode.unwrap_or_default(),
                    remux_only: j.remux_only,
                })
            })
            .collect();

        info!("Jobs to encode: {}", worker_jobs.len());

        self.queue.start_time = Some(std::time::Instant::now());
        self.queue.total_jobs_to_encode = worker_jobs.len();

        // Mark jobs as pending
        for wj in &worker_jobs {
            if let Some(j) = self.queue.jobs.get_mut(wj.index) {
                j.status = JobStatus::Pending;
            }
        }

        let cancel_flag = self.cancel_flag.clone();
        let config = self.config.clone();

        thread::spawn(move || {
            run_worker(worker_jobs, &config, &cancel_flag, &tx);
        });
    }

    pub fn cancel_encoding(&mut self) {
        self.cancel_flag.store(true, Ordering::Relaxed);
    }

    #[allow(clippy::too_many_lines)]
    pub fn process_progress_messages(&mut self) {
        let messages: Vec<WorkerMessage> = if let Some(ref rx) = self.progress_receiver {
            let mut msgs = Vec::new();
            while let Ok(msg) = rx.try_recv() {
                msgs.push(msg);
            }
            msgs
        } else {
            return;
        };

        let mut should_finish = false;

        for msg in messages {
            match msg {
                WorkerMessage::Progress(idx, progress) => {
                    if let Some(job) = self.queue.jobs.get_mut(idx) {
                        job.status = JobStatus::Encoding { progress };
                        // Keep the cursor following the active job unless the
                        // user has manually scrolled it elsewhere.
                        if self.queue_cursor == self.queue.current_job_index {
                            self.queue_cursor = idx;
                        }
                        self.queue.current_job_index = idx;
                    }
                }
                WorkerMessage::Done(idx) => {
                    if let Some(job) = self.queue.jobs.get_mut(idx) {
                        job.status = JobStatus::Done;
                        self.queue.converted_count += 1;
                        self.queue.encoding_progress_done += 1;
                    }
                    if self.queue.all_completed() {
                        self.encoding_active = false;
                        should_finish = true;
                    }
                }
                WorkerMessage::DoneWithVmaf(idx, score) => {
                    if let Some(job) = self.queue.jobs.get_mut(idx) {
                        job.status = JobStatus::DoneWithVmaf { score };
                        self.queue.converted_count += 1;
                        self.queue.encoding_progress_done += 1;
                    }
                    if self.queue.all_completed() {
                        self.encoding_active = false;
                        should_finish = true;
                    }
                }
                WorkerMessage::Error(idx, msg) => {
                    if let Some(job) = self.queue.jobs.get_mut(idx) {
                        job.status = JobStatus::Error { message: msg };
                        self.queue.error_count += 1;
                        self.queue.encoding_progress_done += 1;
                    }
                    if self.queue.all_completed() {
                        self.encoding_active = false;
                        should_finish = true;
                    }
                }
                WorkerMessage::QualityWarning(idx, vmaf, threshold) => {
                    if let Some(job) = self.queue.jobs.get_mut(idx) {
                        job.status = JobStatus::QualityWarning { vmaf, threshold };
                        self.queue.converted_count += 1;
                        self.queue.encoding_progress_done += 1;
                    }
                    if self.queue.all_completed() {
                        self.encoding_active = false;
                        should_finish = true;
                    }
                }
                WorkerMessage::Verifying(idx) => {
                    if let Some(job) = self.queue.jobs.get_mut(idx) {
                        job.status = JobStatus::Verifying;
                    }
                }
                WorkerMessage::DoneVmafFailed(idx, reason) => {
                    if let Some(job) = self.queue.jobs.get_mut(idx) {
                        job.status = JobStatus::DoneVmafFailed { reason };
                        self.queue.converted_count += 1;
                        self.queue.encoding_progress_done += 1;
                    }
                    if self.queue.all_completed() {
                        self.encoding_active = false;
                        should_finish = true;
                    }
                }
                WorkerMessage::SourceDeleted(idx) => {
                    if let Some(job) = self.queue.jobs.get_mut(idx) {
                        job.source_deleted = true;
                    }
                }
                WorkerMessage::SourceKeptLowVmaf(idx, vmaf) => {
                    if let Some(job) = self.queue.jobs.get_mut(idx) {
                        job.source_kept_vmaf = Some(vmaf);
                    }
                }
                WorkerMessage::Cancelled => {
                    for job in &mut self.queue.jobs {
                        if matches!(
                            job.status,
                            JobStatus::Pending
                                | JobStatus::Ready
                                | JobStatus::Encoding { .. }
                                | JobStatus::Verifying
                        ) {
                            job.status = JobStatus::Skipped {
                                reason: "Cancelled".to_string(),
                            };
                            self.queue.skipped_count += 1;
                        }
                    }
                    self.encoding_active = false;
                    should_finish = true;
                }
            }
        }

        if should_finish {
            self.queue.end_time = Some(std::time::Instant::now());
            self.navigate_to_finish();
        }
    }

    pub fn reset(&mut self) {
        self.queue.reset();
        self.encoding_active = false;
        self.selected_files.clear();
        self.progress_receiver = None;
        self.navigate_to_home();
    }
}

/// Dialog option index for a DV mode (0 = keep DV, 1 = HDR10)
fn dv_mode_index(mode: DvMode) -> usize {
    match mode {
        DvMode::KeepDolbyVision => 0,
        DvMode::ToHdr10 => 1,
    }
}