av1converter 3.0.0

Batch convert video files to AV1 with FFmpeg, from a terminal UI or a daemon with a web UI
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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
pub mod api;
pub mod lifecycle;
pub mod server;
pub mod service;
pub mod state;

use crate::analyzer::{self, AnalysisResult, HdrType, is_av1_codec};
use crate::config::{AppConfig, AudioMode};
use crate::error::AppError;
use crate::i18n::{Msg, t};
use crate::queue::{
    EncodingJob, JobStatus, WorkerJob, WorkerMessage, auto_select_tracks, make_output_paths_unique,
    run_worker,
};
use crate::utils::DependencyStatus;
use state::{DaemonState, EncodeSession, SharedState, is_terminal, lock};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use tracing::{info, warn};

/// How often the orchestrator wakes up when no analysis result arrives.
const TICK: Duration = Duration::from_millis(250);
/// How long shutdown waits for the worker to acknowledge cancellation.
const SHUTDOWN_GRACE: Duration = Duration::from_secs(10);
/// How long shutdown waits for in-flight HTTP requests before leaving their
/// threads detached.
const HTTP_JOIN_GRACE: Duration = Duration::from_secs(5);
/// Number of HTTP worker threads.
const SERVER_THREADS: usize = 4;

/// Bind the web server and append the bound address to `pid_path`.
fn start_server_at(
    listen: &str,
    pid_path: &std::path::Path,
) -> Result<tiny_http::Server, AppError> {
    let server = server::bind(listen)?;
    if let Some(bound) = server.server_addr().to_ip() {
        lifecycle::append_listen(pid_path, &bound.to_string()).map_err(|e| {
            AppError::CommandExecution(format!(
                "Failed to record the listen address in {}: {e}",
                pid_path.display()
            ))
        })?;
    }
    Ok(server)
}

/// Bind the web server and record the bound address `--status` reads.
fn start_server(listen: &str) -> Result<tiny_http::Server, AppError> {
    start_server_at(listen, &lifecycle::pid_file())
}

/// Stop the prober and kill tracked child processes after a startup failure.
fn abort_startup(shutdown: &Arc<AtomicBool>) {
    shutdown.store(true, Ordering::SeqCst);
    crate::utils::child::kill_all();
}

/// Run the headless daemon: web server + encoding orchestrator.
/// Blocks until SIGINT/SIGTERM.
#[allow(clippy::too_many_lines)]
pub fn run_daemon(config: AppConfig) -> Result<(), AppError> {
    let encoder_name = config.encoder.ffmpeg_name();
    let deps = state::Capabilities {
        ffmpeg: DependencyStatus::check(),
        vmaf: DependencyStatus::vmaf_available(),
        opus: DependencyStatus::libopus_available(),
        encoder: DependencyStatus::encoder_available(encoder_name),
    };
    if !deps.ffmpeg {
        warn!("ffmpeg or ffprobe was not found on PATH; encoding will fail");
    }
    if config.quality.vmaf_enabled && !deps.vmaf {
        warn!("VMAF is enabled but this FFmpeg build has no libvmaf; verification will fail");
    }
    if config.audio.default_mode == AudioMode::Opus && !deps.opus {
        warn!("Audio is set to Opus but this FFmpeg build has no libopus; encoding will fail");
    }
    if !deps.encoder {
        println!(
            "{} ({encoder_name})",
            t(config.language, Msg::EncoderUnavailable)
        );
        warn!("This FFmpeg build has no {encoder_name}; every encode will fail");
    }

    let lang = config.language;
    let listen = config.daemon.listen_address();

    // Plain HTTP: the token and media paths travel unencrypted.
    if config.daemon.refuses_public_bind() {
        return Err(AppError::CommandExecution(
            t(config.language, Msg::DaemonPublicHttpRefused).to_string(),
        ));
    }
    if config.daemon.binds_publicly() && config.daemon.browse_root.trim().is_empty() {
        return Err(AppError::CommandExecution(
            t(config.language, Msg::BrowseRootRequired).to_string(),
        ));
    }
    if config.daemon.binds_publicly() {
        warn!("Daemon is network-facing over plain HTTP; use HTTPS termination or a trusted LAN");
    }

    let queue_file = lifecycle::queue_file();
    let (mut state, reprobe) = restore_state(config, &queue_file);
    state.deps = deps;
    let shared: SharedState = Arc::new(Mutex::new(state));
    let (analysis_tx, analysis_rx) = mpsc::channel::<(u64, Result<AnalysisResult, AppError>)>();
    let (probe_tx, probe_rx) = mpsc::channel::<(u64, String)>();
    let (worker_tx, worker_rx) = mpsc::channel::<WorkerMessage>();
    // One channel for every disc run: the handlers start runs, this loop
    // applies what they report.
    let (disc_tx, disc_rx) = mpsc::channel::<crate::disc::worker::DiscEvent>();

    // One long-lived prober handles every add request, one file at a time. A
    // panic is caught, blamed on the file that caused it, and the next file
    // picked up.
    let shutdown = Arc::new(AtomicBool::new(false));
    lock(&shared).shutting_down = shutdown.clone();
    let analysis_handle = {
        let analysis_tx = analysis_tx.clone();
        let shutdown = shutdown.clone();
        let shared = shared.clone();
        thread::spawn(move || {
            for (id, path) in probe_rx {
                // Shutdown is read under the lock the shutdown path cancels
                // the current flag under.
                let cancel = {
                    let mut state = lock(&shared);
                    if shutdown.load(Ordering::SeqCst) {
                        break;
                    }
                    let Some(cancel) = claim_probe(&mut state, id) else {
                        continue;
                    };
                    cancel
                };
                let _span =
                    crate::queue::worker::job_span(id, std::path::Path::new(&path)).entered();
                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    analyzer::analyze(&path, &cancel)
                }))
                .unwrap_or_else(|_| Err(AppError::AnalysisPanicked(path.clone())));
                if analysis_tx.send((id, result)).is_err() {
                    break;
                }
            }
        })
    };

    // Now that the prober is listening, hand back the reloaded files that
    // never got analyzed.
    for request in reprobe {
        if probe_tx.send(request).is_err() {
            warn!("Analysis is not running; reloaded files will stay unanalyzed");
            break;
        }
    }

    let handler = {
        let shutdown = shutdown.clone();
        ctrlc::set_handler(move || {
            if shutdown.swap(true, Ordering::SeqCst) {
                // Second signal: kill every tracked ffmpeg/makemkvcon child
                // and exit.
                crate::utils::child::kill_all();
                std::process::exit(1);
            }
        })
        .map_err(|e| AppError::CommandExecution(format!("Failed to set signal handler: {e}")))
    };
    let server = Arc::new(match handler.and_then(|()| start_server(&listen)) {
        Ok(server) => server,
        Err(e) => {
            abort_startup(&shutdown);
            return Err(e);
        }
    });
    // The bare address, not `url()`: in background mode stdout is the daemon
    // log file, which carries no token. The tokenised URL is printed to the
    // terminal by whoever started this process.
    println!("{} http://{listen}", t(lang, Msg::DaemonListening));
    info!("Web UI listening on http://{listen}");
    let server_handles: Vec<_> = (0..SERVER_THREADS)
        .map(|_| {
            let server = server.clone();
            let shared = shared.clone();
            let probe_tx = probe_tx.clone();
            let disc_tx = disc_tx.clone();
            let shutdown = shutdown.clone();
            thread::spawn(move || server::serve(&server, &shared, &probe_tx, &disc_tx, &shutdown))
        })
        .collect();

    // Main orchestrator loop: owns analysis and worker result application.
    let mut last_saved = Vec::new();
    let mut last_save_warning = None;
    let mut disc_was_active = false;
    while !shutdown.load(Ordering::SeqCst) {
        match analysis_rx.recv_timeout(TICK) {
            Ok((id, result)) => apply_analysis_result(&shared, id, result),
            Err(mpsc::RecvTimeoutError::Timeout) => {}
            Err(mpsc::RecvTimeoutError::Disconnected) => break,
        }
        while let Ok((id, result)) = analysis_rx.try_recv() {
            apply_analysis_result(&shared, id, result);
        }

        while let Ok(msg) = worker_rx.try_recv() {
            apply_worker_message(&shared, msg);
        }

        while let Ok(event) = disc_rx.try_recv() {
            apply_disc_event(&shared, &probe_tx, event);
        }

        // Deletion runs with the lock released.
        let (released, root) = {
            let mut state = lock(&shared);
            (
                crate::disc::staging::release_finished(&mut state.queue.state.jobs),
                crate::disc::staging::staging_root(&state.config),
            )
        };
        for path in released {
            crate::disc::staging::discard_staged(&root, &path);
        }
        sweep_after_disc_run(
            &shared,
            &mut disc_was_active,
            crate::disc::staging::ACTIVE_RIP_WINDOW,
        );
        maybe_start_session(&shared, &worker_tx);
        persist_queue(
            &shared,
            &queue_file,
            &mut last_saved,
            &mut last_save_warning,
        );
    }

    // Probes and a drive listing wait on ffprobe and makemkvcon; both are
    // cancelled before the HTTP threads are joined.
    {
        let state = lock(&shared);
        state.analysis_cancel.store(true, Ordering::Release);
        state.disc.cancel();
    }

    // HTTP stops accepting once `shutdown` is set, and is joined before the
    // worker handles are taken: an in-flight rip is stored and then cancelled,
    // never spawned after `take()`. A thread still blocked on a stalled client
    // after `HTTP_JOIN_GRACE` is left detached.
    let http_joined = join_within(server_handles, HTTP_JOIN_GRACE);
    if !http_joined {
        warn!("HTTP requests still in flight after the shutdown grace; not waiting for them");
    }

    // Graceful shutdown: cancel any running encode and wait for the worker
    // to kill ffmpeg and acknowledge.
    let cancelling = {
        let state = lock(&shared);
        if let Some(session) = state.session.as_ref().filter(|_| state.encoding_active) {
            session.cancel_flag.store(true, Ordering::Release);
            true
        } else {
            false
        }
    };

    // A rip is waited out the same way; makemkvcon is a child of this
    // process.
    if lock(&shared).disc.active {
        lock(&shared).disc.cancel();
        println!("{}", t(lang, Msg::DaemonShuttingDown));
        let deadline = Instant::now() + SHUTDOWN_GRACE;
        while Instant::now() < deadline && lock(&shared).disc.active {
            match disc_rx.recv_timeout(Duration::from_millis(200)) {
                Ok(event) => apply_disc_event(&shared, &probe_tx, event),
                Err(mpsc::RecvTimeoutError::Timeout) => {}
                Err(mpsc::RecvTimeoutError::Disconnected) => break,
            }
        }
    }
    if cancelling {
        println!("{}", t(lang, Msg::DaemonShuttingDown));
        let deadline = Instant::now() + SHUTDOWN_GRACE;
        while Instant::now() < deadline {
            match worker_rx.recv_timeout(Duration::from_millis(200)) {
                Ok(msg) => {
                    let done = matches!(msg, WorkerMessage::Cancelled | WorkerMessage::Finished);
                    apply_worker_message(&shared, msg);
                    if done {
                        break;
                    }
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {}
                Err(mpsc::RecvTimeoutError::Disconnected) => break,
            }
        }
    }

    if lock(&shared).disc.active {
        warn!("shutdown grace elapsed; killing leftover child processes");
    }
    // Always reap child process groups: analysis-only ffprobe may still be
    // alive, and children run in their own PGID, which a parent exit does not
    // reap.
    crate::utils::child::kill_all();
    let (encode_worker, disc_worker) = {
        let mut state = lock(&shared);
        (state.encode_worker.take(), state.disc_worker.take())
    };
    let mut worker_handles = Vec::new();
    if let Some(handle) = encode_worker {
        worker_handles.push(handle);
    }
    if let Some(handle) = disc_worker {
        worker_handles.push(handle);
    }
    if !join_within(worker_handles, SHUTDOWN_GRACE) {
        warn!("encode/disc workers did not finish within the shutdown grace");
    }
    drain_shutdown_channels(&shared, &worker_rx, &disc_rx, &probe_tx);

    // The queue is saved as it stands; the next start settles unfinished jobs
    // with `queue::state::resume`.
    persist_queue(
        &shared,
        &queue_file,
        &mut last_saved,
        &mut last_save_warning,
    );
    // The analyzer owns ffprobe children; kill_all already reaped them.
    // Detached HTTP threads may still hold `probe_tx` clones, and the prober
    // is joined with a grace window.
    drop(probe_tx);
    if !join_within(vec![analysis_handle], HTTP_JOIN_GRACE) {
        warn!("analysis prober still running after shutdown grace; abandoning join");
    }
    crate::utils::remove_scratch_dir_if_empty();
    Ok(())
}

/// Join `handles`, waiting at most `grace` for them to finish. Returns whether
/// every one was joined.
fn join_within(handles: Vec<thread::JoinHandle<()>>, grace: Duration) -> bool {
    let deadline = Instant::now() + grace;
    while Instant::now() < deadline && !handles.iter().all(thread::JoinHandle::is_finished) {
        thread::sleep(Duration::from_millis(50));
    }
    let mut joined = true;
    for handle in handles {
        if handle.is_finished() {
            let _ = handle.join();
        } else {
            joined = false;
        }
    }
    joined
}

/// Sweep orphaned staging directories once `disc.active` has gone false since
/// the last call. The sweep runs with the lock released.
fn sweep_after_disc_run(shared: &SharedState, was_active: &mut bool, min_age: Duration) {
    let snapshot = {
        let state = lock(shared);
        let settled = *was_active && !state.disc.active;
        *was_active = state.disc.active;
        settled.then(|| {
            let staged: Vec<EncodingJob> = state
                .queue
                .state
                .jobs
                .iter()
                .filter(|job| job.temporary)
                .cloned()
                .collect();
            (state.config.clone(), staged)
        })
    };
    if let Some((config, staged)) = snapshot {
        crate::disc::staging::sweep_orphans(&config, &staged, min_age);
    }
}

/// Apply leftover worker/disc messages after join, then settle anything still
/// in flight.
fn drain_shutdown_channels(
    shared: &SharedState,
    worker_rx: &Receiver<WorkerMessage>,
    disc_rx: &Receiver<crate::disc::worker::DiscEvent>,
    probe_tx: &Sender<(u64, String)>,
) {
    while let Ok(msg) = worker_rx.try_recv() {
        apply_worker_message(shared, msg);
    }
    while let Ok(event) = disc_rx.try_recv() {
        apply_disc_event(shared, probe_tx, event);
    }
    if lock(shared).encoding_active {
        apply_worker_message(shared, WorkerMessage::Cancelled);
    }
}

/// Build the starting state from the queue this daemon last wrote. Returns the
/// state to run with, and the reloaded files that were never analyzed, for the
/// caller to hand back to the prober.
fn restore_state(
    config: AppConfig,
    queue_file: &std::path::Path,
) -> (DaemonState, Vec<(u64, String)>) {
    let (mut restored, unreadable_queue) = crate::queue::state::load(queue_file);
    let browse_root = config.daemon.browse_root.clone();
    let root = if browse_root.is_empty() {
        None
    } else {
        match std::path::PathBuf::from(&browse_root).canonicalize() {
            Ok(root) => Some(root),
            Err(e) => {
                warn!(
                    "browse_root {browse_root} cannot be resolved ({e}); saved jobs are kept as they are"
                );
                None
            }
        }
    };
    if let Some(root) = root {
        // Missing files resolve through their deepest existing folder.
        let confine = |path: &std::path::Path| {
            api::resolve_through_existing(path).filter(|resolved| resolved.starts_with(&root))
        };
        for job in &mut restored.state.jobs {
            // Staged rips live in the staging directory, outside any browse root.
            let source = if job.temporary {
                Some(job.path.clone())
            } else {
                confine(&job.path)
            };
            let output = job
                .output_path
                .as_ref()
                .and_then(|output| Some(confine(output.parent()?)?.join(output.file_name()?)));
            if source.is_none() || (job.output_path.is_some() && output.is_none()) {
                // The queue API includes paths, so completed history is dropped
                // too when a newly tightened root excludes it.
                job.path = std::path::PathBuf::from("<outside browse_root>");
                job.output_path = None;
                if !is_terminal(&job.status) {
                    job.status = JobStatus::Error {
                        message: "Saved job is outside the configured browse root".to_string(),
                    };
                }
            } else if let Some(source) = source {
                // The resolved paths that passed confinement, not the spellings.
                job.path = source;
                if job.output_path.is_some() {
                    job.output_path = output;
                }
            }
        }
    }
    crate::queue::state::resume(&mut restored);
    let restored_jobs = restored.state.jobs.len();

    let reprobe: Vec<(u64, String)> = crate::queue::state::needs_analysis(&restored)
        .into_iter()
        .filter_map(|(index, path)| restored.ids.get(index).map(|&id| (id, path)))
        .collect();

    let mut state = DaemonState::new(config);
    state.queue = state::DaemonQueue::from_persisted(restored);
    state.unreadable_queue = unreadable_queue;
    // A rip cut short by a kill has nothing left tracking its file.
    crate::disc::staging::sweep_orphans(
        &state.config,
        &state.queue.state.jobs,
        crate::disc::staging::ACTIVE_RIP_WINDOW,
    );
    for (id, _) in &reprobe {
        if let Some(job) = state.queue.job_by_id_mut(*id) {
            job.status = JobStatus::Analyzing;
        }
    }
    if restored_jobs > 0 {
        info!(
            "Reloaded {restored_jobs} job(s) from {} ({} to re-analyze)",
            queue_file.display(),
            reprobe.len()
        );
    }
    (state, reprobe)
}

/// The size of a freshly ripped title's file, read outside the state lock.
fn ripped_size(event: &crate::disc::worker::DiscEvent) -> Option<u64> {
    match event {
        crate::disc::worker::DiscEvent::TitleReady { path, .. } => {
            std::fs::metadata(path).ok().map(|m| m.len())
        }
        _ => None,
    }
}

/// Apply one event from a disc run, and hand each extracted file straight to
/// the prober: the drive moves on to the next title while this one is probed.
fn apply_disc_event(
    shared: &SharedState,
    probe_tx: &Sender<(u64, String)>,
    event: crate::disc::worker::DiscEvent,
) {
    use crate::disc::worker::DiscEvent;

    let ripped_size = ripped_size(&event);
    let mut ready = None;
    {
        let mut state = lock(shared);
        let lang = state.config.language;
        match event {
            DiscEvent::TitlesFound(scan) => {
                state.disc.disc_type = scan.disc_type;
                // A scan that settles with zero titles reports as an error.
                if scan.titles.is_empty() {
                    state.disc.error = Some(t(lang, Msg::DiscNoTitles).to_string());
                }
                state.disc.titles = scan.titles;
                state.disc.settle();
            }
            DiscEvent::Ripping { index, progress } => {
                if let Some(id) = state.disc.job_ids.get(index).copied()
                    && let Some(job) = state.queue.job_by_id_mut(id)
                    && matches!(job.status, JobStatus::Ripping { .. })
                {
                    job.status = JobStatus::Ripping { progress };
                }
            }
            DiscEvent::TitleReady { index, path } => {
                if let Some(id) = state.disc.job_ids.get(index).copied()
                    && let Some(job) = state.queue.job_by_id_mut(id)
                    && matches!(job.status, JobStatus::Ripping { .. })
                {
                    job.source_size = ripped_size;
                    if let Some(text) = path.to_str().map(str::to_string) {
                        job.path = path;
                        job.status = JobStatus::Analyzing;
                        ready = Some((id, text));
                    } else {
                        // A path the queue file cannot carry is kept in its
                        // lossy form, which every later save can write.
                        job.path = std::path::PathBuf::from(path.to_string_lossy().into_owned());
                        job.status = JobStatus::Error {
                            message: "File path contains non-UTF-8 characters".to_string(),
                        };
                        state.queue.state.error_count += 1;
                    }
                }
            }
            DiscEvent::Error { index, error } => {
                let message = error.message(lang);
                info!("Disc run stopped: {message}");
                let ids = state.disc.job_ids.clone();
                for (position, id) in ids.into_iter().enumerate() {
                    let failed = position == index;
                    let Some(job) = state.queue.job_by_id_mut(id) else {
                        continue;
                    };
                    if !matches!(job.status, JobStatus::Ripping { .. }) {
                        continue;
                    }
                    job.status = if failed {
                        JobStatus::Error {
                            message: message.clone(),
                        }
                    } else {
                        JobStatus::Skipped {
                            reason: message.clone(),
                        }
                    };
                    if failed {
                        state.queue.state.error_count += 1;
                    } else {
                        state.queue.state.skipped_count += 1;
                    }
                }
                state.disc.error = Some(message);
                state.disc.settle();
            }
            DiscEvent::Cancelled => {
                let ids = state.disc.job_ids.clone();
                for id in ids {
                    if let Some(job) = state.queue.job_by_id_mut(id)
                        && matches!(job.status, JobStatus::Ripping { .. })
                    {
                        job.status = JobStatus::Skipped {
                            reason: "Cancelled".to_string(),
                        };
                        state.queue.state.count_cancelled(1);
                    }
                }
                state.disc.settle();
            }
            DiscEvent::Finished => state.disc.settle(),
        }
    }

    if let Some((id, path)) = ready
        && probe_tx.send((id, path)).is_err()
    {
        let mut state = lock(shared);
        if let Some(job) = state.queue.job_by_id_mut(id) {
            job.status = JobStatus::Error {
                message: "Analysis is not running".to_string(),
            };
        }
        state.queue.state.error_count += 1;
    }
}

/// Write the queue out if its serialized form changed since the last write.
/// The only save call site: handlers and worker messages mutate the queue
/// behind the mutex without saving. `JobStatus::Encoding` does not persist its
/// percentage, and a running encode does not churn the file.
///
/// The comparison re-serializes the queue once per tick.
fn persist_queue(
    shared: &SharedState,
    path: &std::path::Path,
    last_saved: &mut Vec<u8>,
    last_warning: &mut Option<Instant>,
) {
    let json = {
        let state = lock(shared);
        let snapshot = state.queue.as_persistable();
        match serde_json::to_vec_pretty(&snapshot) {
            Ok(json) => json,
            Err(e) => {
                if last_warning.is_none_or(|at| at.elapsed() >= Duration::from_mins(1)) {
                    warn!("The queue cannot be written: {e}");
                    *last_warning = Some(Instant::now());
                }
                return;
            }
        }
    };
    if json == *last_saved {
        return;
    }
    match crate::queue::state::save_serialized(path, &json) {
        Ok(()) => {
            *last_saved = json;
            *last_warning = None;
        }
        // Retried every tick, but logged only once per outage.
        Err(e) => {
            if last_warning.is_none_or(|at| at.elapsed() >= Duration::from_mins(1)) {
                warn!("Could not save the queue to {}: {e}", path.display());
                *last_warning = Some(Instant::now());
            }
        }
    }
}

/// Install a fresh analysis cancel flag for probing job `id`, or `None` when
/// the job was removed or no longer awaits analysis.
fn claim_probe(state: &mut DaemonState, id: u64) -> Option<Arc<AtomicBool>> {
    if !state
        .queue
        .job_by_id(id)
        .is_some_and(|job| job.status.awaits_analysis())
    {
        return None;
    }
    let cancel = Arc::new(AtomicBool::new(false));
    state.analysis_cancel = cancel.clone();
    Some(cancel)
}

/// Queue new files and hand them to the prober.
///
/// Returns `(added, duplicates, filtered)` where `filtered` covers paths
/// rejected for reasons other than already being queued (e.g. outside the
/// live browse root).
#[allow(clippy::too_many_lines)]
fn add_paths(
    shared: &SharedState,
    probe_tx: &Sender<(u64, String)>,
    paths: Vec<std::path::PathBuf>,
    browse_root: &str,
) -> (usize, usize, usize) {
    let mut added: usize = 0;
    let mut duplicates: usize = 0;
    let mut filtered: usize = 0;
    let mut to_analyze: Vec<(u64, String)> = Vec::new();
    let requested = paths.len();

    // Canonicalization and identity reads touch the filesystem and run with
    // no lock held. Under the lock we also compare filesystem identities so
    // two spellings of the same inode cannot both queue.
    let queued_paths: Vec<std::path::PathBuf> = lock(shared)
        .queue
        .jobs_with_ids()
        .filter(|(_, job)| !is_terminal(&job.status))
        .map(|(_, job)| job.path.clone())
        .collect();
    let mut existing: std::collections::HashSet<std::path::PathBuf> = queued_paths
        .iter()
        .map(|path| path.canonicalize().unwrap_or_else(|_| path.clone()))
        .collect();
    let mut existing_ids: std::collections::HashSet<crate::queue::SourceIdentity> = queued_paths
        .iter()
        .filter_map(|path| crate::queue::SourceIdentity::from_path(path).ok())
        .collect();
    let canonical_paths: Vec<(
        std::path::PathBuf,
        std::path::PathBuf,
        Option<crate::queue::SourceIdentity>,
    )> = paths
        .into_iter()
        .map(|path| {
            let canonical = path.canonicalize().unwrap_or_else(|_| path.clone());
            let identity = crate::queue::SourceIdentity::from_path(&canonical).ok();
            (canonical, path, identity)
        })
        .collect();

    {
        let mut state = lock(shared);
        if state
            .shutting_down
            .load(std::sync::atomic::Ordering::SeqCst)
        {
            return (0, 0, requested);
        }
        state.queue.state.reset_session_if_finished();
        for (_, job) in state
            .queue
            .jobs_with_ids()
            .filter(|(_, job)| !is_terminal(&job.status))
        {
            if !queued_paths.contains(&job.path) {
                existing.insert(job.path.clone());
                if let Ok(identity) = crate::queue::SourceIdentity::from_path(&job.path) {
                    existing_ids.insert(identity);
                }
            }
        }

        // `paths` were confined against `browse_root`. A live root that differs
        // was stored resolved by the settings API and is compared by prefix.
        let live_root = std::path::PathBuf::from(&state.config.daemon.browse_root);
        let root_changed = state.config.daemon.browse_root != browse_root;

        for (canonical, path, identity) in canonical_paths {
            if root_changed
                && !live_root.as_os_str().is_empty()
                && !canonical.starts_with(&live_root)
            {
                filtered += 1;
                continue;
            }
            let path_dup = !existing.insert(canonical);
            let id_dup = identity
                .as_ref()
                .is_some_and(|id| !existing_ids.insert(id.clone()));
            if path_dup || id_dup {
                duplicates += 1;
                continue;
            }
            let mut job = EncodingJob::new(path);
            if let Some(p) = job.path.to_str() {
                let p = p.to_string();
                job.status = JobStatus::Analyzing;
                let id = state.queue.push(job);
                to_analyze.push((id, p));
                added += 1;
            } else {
                job.status = JobStatus::Error {
                    message: "File path contains non-UTF-8 characters".to_string(),
                };
                state.queue.state.error_count += 1;
                state.queue.push(job);
                added += 1;
            }
        }
    }

    // A dead prober is reported on the jobs themselves; they leave the
    // non-terminal `Analyzing` state, which blocks re-adds of the same file.
    let mut orphaned: Vec<u64> = Vec::new();
    let mut requests = to_analyze.into_iter();
    for request in requests.by_ref() {
        if let Err(e) = probe_tx.send(request) {
            orphaned.push(e.0.0);
            break;
        }
    }
    orphaned.extend(requests.map(|(id, _)| id));

    if !orphaned.is_empty() {
        warn!(
            "Analysis is not running; {} file(s) rejected",
            orphaned.len()
        );
        let mut state = lock(shared);
        for id in orphaned {
            if let Some(job) = state.queue.job_by_id_mut(id) {
                job.status = JobStatus::Error {
                    message: "Analysis is not running".to_string(),
                };
                state.queue.state.error_count += 1;
                added = added.saturating_sub(1);
                filtered += 1;
            }
        }
    }

    (added, duplicates, filtered)
}

/// Apply one finished analysis: mirror the TUI's `apply_analysis_results`,
/// then resolve the Dolby Vision mode non-interactively and wait for the `WebUI`
/// track confirmation.
fn apply_analysis_result(shared: &SharedState, id: u64, result: Result<AnalysisResult, AppError>) {
    let mut state = lock(shared);
    let output_config = state.config.output.clone();
    let track_config = state.config.tracks.clone();
    let audio_config = state.config.audio.clone();
    let encoder = state.config.encoder;
    let lang = state.config.language;
    let shutting_down = state.shutting_down.load(Ordering::SeqCst);

    // The job may have been removed while analysis was running
    let Some(job) = state.queue.job_by_id_mut(id) else {
        return;
    };
    if !job.status.awaits_analysis() {
        return;
    }

    match result {
        Ok(analysis) => {
            let is_av1 = is_av1_codec(&analysis.metadata.codec_name);
            let hdr_type = analysis.metadata.hdr_type;
            let dv_profile = analysis.metadata.dv_profile;
            job.source_size = Some(analysis.source_identity.size_bytes());
            job.source_identity = Some(analysis.source_identity);
            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, &audio_config);
            job.generate_output_path(&output_config);
            if job.temporary && job.output_path.is_none() {
                job.status = JobStatus::Error {
                    message: crate::disc::DiscError::NoDestination.message(lang),
                };
                state.queue.state.error_count += 1;
                return;
            }
            // Mirrors `App::maybe_open_dv_dialog`, shared with the web API.
            if !is_av1 && hdr_type == HdrType::DolbyVision {
                job.dv_mode = Some(api::resolved_dv_mode(encoder, dv_profile));
            }
            job.status = JobStatus::AwaitingConfig;
            info!("Analyzed {}", job.path.display());
            make_output_paths_unique(&mut state.queue.state.jobs);
        }
        // A daemon stop leaves the job analysing; `queue::state::resume`
        // probes it again on the next start.
        Err(AppError::Cancelled) if shutting_down => {}
        Err(AppError::Cancelled) => {
            job.status = JobStatus::Skipped {
                reason: "Cancelled".to_string(),
            };
            state.queue.state.count_cancelled(1);
        }
        Err(e) => {
            job.status = JobStatus::Error {
                message: e.message(lang),
            };
            state.queue.state.error_count += 1;
        }
    }
}

/// Start a new encode session if idle and jobs are ready.
#[allow(clippy::too_many_lines)]
fn maybe_start_session(shared: &SharedState, worker_tx: &Sender<WorkerMessage>) {
    let mut state = lock(shared);
    if state.encoding_active {
        return;
    }

    let output_config = state.config.output.clone();
    let audio_config = state.config.audio.clone();
    let mut job_ids: Vec<u64> = Vec::new();
    let mut worker_jobs: Vec<WorkerJob> = Vec::new();
    let mut without_destination: Vec<u64> = Vec::new();
    for (id, job) in state.queue.jobs_with_ids() {
        if !matches!(job.status, JobStatus::Ready) {
            continue;
        }
        let Some(metadata) = job.metadata.clone() else {
            continue;
        };
        let Some(source_identity) = job.source_identity.clone() else {
            continue;
        };
        // A ripped file has no next-to-the-source fallback: that is the staging
        // directory.
        let output = match job.output_path.clone() {
            Some(output) => output,
            None if job.temporary => {
                without_destination.push(id);
                continue;
            }
            None => {
                let stem = job.path.file_stem().unwrap_or_default().to_string_lossy();
                let parent = job.path.parent().unwrap_or(std::path::Path::new("."));
                parent.join(format!(
                    "{}{}.{}",
                    stem, output_config.suffix, output_config.container
                ))
            }
        };
        let selected_subs = crate::tracks::selected_subtitles(
            &job.subtitle_tracks,
            &job.track_selection.subtitle_indices,
        );
        worker_jobs.push(WorkerJob {
            index: worker_jobs.len(),
            subtitle_codecs: crate::tracks::subtitle_codecs_for(&output, &selected_subs),
            tracks: job
                .track_selection
                .resolve_for(&job.audio_tracks, &audio_config, &output),
            input: job.path.clone(),
            output,
            source_identity,
            metadata,
            dv_mode: job.dv_mode.unwrap_or_default(),
            remux_only: job.remux_only,
        });
        job_ids.push(id);
        break;
    }

    let lang = state.config.language;
    for id in without_destination {
        if let Some(job) = state.queue.job_by_id_mut(id) {
            job.status = JobStatus::Error {
                message: crate::disc::DiscError::NoDestination.message(lang),
            };
            state.queue.state.error_count += 1;
        }
    }

    if worker_jobs.is_empty() {
        return;
    }
    info!("Starting encode session with one job");

    let ready = state
        .queue
        .state
        .jobs
        .iter()
        .filter(|job| matches!(job.status, JobStatus::Ready))
        .count();
    state.queue.state.total_jobs_to_encode = state.queue.state.encoding_progress_done + ready;
    // The elapsed clock counts encoding time only; the idle gap since the
    // last session ended is shifted out of it.
    let now = Instant::now();
    match (state.queue.state.start_time, state.queue.state.end_time) {
        (Some(start), Some(end)) => {
            state.queue.state.start_time = Some(start + now.duration_since(end));
        }
        (None, _) => state.queue.state.start_time = Some(now),
        (Some(_), None) => {}
    }
    state.queue.state.end_time = None;
    if let Some(&id) = job_ids.first() {
        if let Some(index) = state.queue.index_of(id) {
            state.queue.state.current_job_index = index;
        }
        if let Some(job) = state.queue.job_by_id_mut(id) {
            job.status = JobStatus::Encoding { progress: 0.0 };
        }
    }

    let cancel_flag = Arc::new(AtomicBool::new(false));
    state.session = Some(EncodeSession {
        job_ids,
        cancel_flag: cancel_flag.clone(),
    });
    state.encoding_active = true;

    let config = state.config.clone();
    let tx = worker_tx.clone();
    state.encode_worker = Some(thread::spawn(move || {
        // `run_worker` catches a panic per job; this covers one outside any
        // job. The channel never reports it: this daemon holds its own sender
        // alive, and a dead worker stops talking without disconnecting.
        if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            run_worker(worker_jobs, &config, &cancel_flag, &tx);
        }))
        .is_err()
        {
            warn!("Encode worker panicked; ending the session");
            let _ = tx.send(WorkerMessage::Cancelled);
        }
    }));
}

/// Apply one worker message: mirrors the TUI's `process_progress_messages`,
/// but translates the session-local index to a stable job id first.
#[allow(clippy::too_many_lines)]
fn apply_worker_message(shared: &SharedState, msg: WorkerMessage) {
    let mut state = lock(shared);
    let Some(session_ids) = state.session.as_ref().map(|s| s.job_ids.clone()) else {
        return; // Late message from an already-finished session
    };
    let id_for = |idx: usize| session_ids.get(idx).copied();

    let mut pending_size: Option<(u64, std::path::PathBuf)> = None;
    match msg {
        WorkerMessage::Progress(idx, progress) => {
            if let Some(id) = id_for(idx) {
                if let Some(index) = state.queue.index_of(id) {
                    state.queue.state.current_job_index = index;
                }
                if let Some(job) = state.queue.job_by_id_mut(id)
                    && matches!(job.status, JobStatus::Encoding { .. })
                {
                    job.status = JobStatus::Encoding { progress };
                }
            }
        }
        WorkerMessage::Verifying(idx) => {
            if let Some(job) = id_for(idx).and_then(|id| state.queue.job_by_id_mut(id)) {
                job.status = JobStatus::Verifying;
            }
        }
        WorkerMessage::Done(idx) => {
            pending_size = finish_job(&mut state, id_for(idx), JobStatus::Done);
        }
        WorkerMessage::DoneWithVmaf(idx, score) => {
            pending_size = finish_job(&mut state, id_for(idx), JobStatus::DoneWithVmaf { score });
        }
        WorkerMessage::DoneVmafFailed(idx, reason) => {
            pending_size = finish_job(
                &mut state,
                id_for(idx),
                JobStatus::DoneVmafFailed { reason },
            );
        }
        WorkerMessage::QualityWarning(idx, vmaf, min_score, threshold) => {
            pending_size = finish_job(
                &mut state,
                id_for(idx),
                JobStatus::QualityWarning {
                    vmaf,
                    min_score,
                    threshold,
                },
            );
        }
        WorkerMessage::Error(idx, message) => {
            if let Some(job) = id_for(idx).and_then(|id| state.queue.job_by_id_mut(id)) {
                job.status = JobStatus::Error { message };
                state.queue.state.error_count += 1;
                state.queue.state.encoding_progress_done += 1;
            }
        }
        WorkerMessage::SourceDeleted(idx) => {
            if let Some(job) = id_for(idx).and_then(|id| state.queue.job_by_id_mut(id)) {
                job.source_deleted = true;
            }
        }
        WorkerMessage::SourceKeptLowVmaf(idx, vmaf, _min) => {
            if let Some(job) = id_for(idx).and_then(|id| state.queue.job_by_id_mut(id)) {
                job.source_kept_vmaf = Some(vmaf);
            }
        }
        WorkerMessage::SourceKept(idx, reason) => {
            if let Some(job) = id_for(idx).and_then(|id| state.queue.job_by_id_mut(id)) {
                job.source_kept_reason = Some(reason);
            }
        }
        // A daemon stop leaves session jobs as they are; `queue::state::resume`
        // settles them on the next start.
        WorkerMessage::Cancelled if state.shutting_down.load(Ordering::SeqCst) => {}
        WorkerMessage::Cancelled => {
            for &id in &session_ids {
                if let Some(job) = state.queue.job_by_id_mut(id)
                    && !is_terminal(&job.status)
                {
                    job.status = JobStatus::Skipped {
                        reason: "Cancelled".to_string(),
                    };
                    state.queue.state.count_cancelled(1);
                    // A cancelled job counts as done for the session.
                    state.queue.state.encoding_progress_done += 1;
                }
            }
        }
        WorkerMessage::Finished => {}
    }

    // Session over when every job in it reached a terminal state
    let all_done = session_ids.iter().all(|&id| {
        state
            .queue
            .job_by_id(id)
            .is_none_or(|job| is_terminal(&job.status))
    });
    let encode_worker = if all_done {
        state.encoding_active = false;
        state.session = None;
        // Set on every session end, not only a fully settled queue.
        state.queue.state.end_time = Some(Instant::now());
        info!("Encode job finished");
        state.encode_worker.take()
    } else {
        None
    };
    drop(state);

    if let Some((id, path)) = pending_size {
        let size = std::fs::metadata(&path).ok().map(|m| m.len());
        if let Some(job) = lock(shared).queue.job_by_id_mut(id) {
            job.output_size = size;
        }
    }
    if let Some(handle) = encode_worker {
        let _ = handle.join();
    }
}

/// Mark a session job as successfully finished. Returns `(id, path)` so the
/// caller can `metadata` the output without holding the daemon mutex.
fn finish_job(
    state: &mut DaemonState,
    id: Option<u64>,
    status: JobStatus,
) -> Option<(u64, std::path::PathBuf)> {
    let id = id?;
    let job = state.queue.job_by_id_mut(id)?;
    let output_path = job.output_path.clone();
    job.status = status;
    state.queue.state.converted_count += 1;
    state.queue.state.encoding_progress_done += 1;
    output_path.map(|path| (id, path))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A ripped file whose name is not UTF-8 does not stop the queue from
    /// being saved.
    #[cfg(unix)]
    #[test]
    fn a_non_utf8_ripped_path_still_lets_the_queue_be_saved() {
        use std::os::unix::ffi::OsStringExt;

        let shared: SharedState = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        let (probe_tx, _probe_rx) = mpsc::channel();
        let id = {
            let mut state = lock(&shared);
            let mut job = EncodingJob::new(std::path::PathBuf::from("Title 0"));
            job.status = JobStatus::Ripping { progress: 0.0 };
            job.temporary = true;
            let id = state.queue.push(job);
            state.disc.job_ids = vec![id];
            state.disc.active = true;
            id
        };

        apply_disc_event(
            &shared,
            &probe_tx,
            crate::disc::worker::DiscEvent::TitleReady {
                index: 0,
                path: std::path::PathBuf::from(std::ffi::OsString::from_vec(vec![0xff])),
            },
        );

        let state = lock(&shared);
        assert!(matches!(
            state.queue.job_by_id(id).unwrap().status,
            JobStatus::Error { .. }
        ));
        let snapshot = state.queue.as_persistable();
        assert!(
            serde_json::to_vec_pretty(&snapshot).is_ok(),
            "the queue must stay writable"
        );
    }

    /// A shutdown leaves a running rip as it is, for `resume` to settle.
    #[test]
    fn a_shutdown_leaves_a_running_rip_for_the_next_start() {
        let shared: SharedState = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        let (probe_tx, _probe_rx) = mpsc::channel();
        let (_worker_tx, worker_rx) = mpsc::channel();
        let (_disc_tx, disc_rx) = mpsc::channel();
        let id = {
            let mut state = lock(&shared);
            let mut job = EncodingJob::new(std::path::PathBuf::from("Title 0"));
            job.status = JobStatus::Ripping { progress: 40.0 };
            job.temporary = true;
            let id = state.queue.push(job);
            state.disc.job_ids = vec![id];
            state.disc.active = true;
            id
        };

        drain_shutdown_channels(&shared, &worker_rx, &disc_rx, &probe_tx);

        let state = lock(&shared);
        let job = state.queue.job_by_id(id).unwrap();
        let JobStatus::Ripping { progress } = job.status else {
            panic!("a rip stays a rip across a shutdown");
        };
        assert!((progress - 40.0).abs() < f64::EPSILON);
        assert!(job.temporary);
        assert_eq!(state.queue.state.cancelled_count, 0);
    }

    /// A listen address already in use fails startup.
    #[test]
    fn a_busy_address_fails_startup() {
        let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let busy = held.local_addr().unwrap().to_string();
        let dir = std::env::temp_dir().join(format!("av1c_startup_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let pid_path = dir.join("daemon.pid");
        std::fs::write(&pid_path, format!("{}", std::process::id())).unwrap();

        let Err(refused) = start_server_at(&busy, &pid_path) else {
            panic!("a busy address must not bind");
        };

        assert!(matches!(refused, AppError::CommandExecution(_)));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A bound address that cannot be recorded fails startup instead of
    /// leaving the parent without a port to read.
    #[test]
    fn an_unrecordable_listen_address_fails_startup() {
        let dir = std::env::temp_dir().join(format!("av1c_record_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let missing = dir.join("daemon.pid");

        let Err(refused) = start_server_at("127.0.0.1:0", &missing) else {
            panic!("an unrecordable address must not start");
        };

        assert!(matches!(refused, AppError::CommandExecution(_)));

        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(&missing, format!("{}", std::process::id())).unwrap();
        let Ok(server) = start_server_at("127.0.0.1:0", &missing) else {
            panic!("a free address with a writable PID file starts");
        };
        let recorded = std::fs::read_to_string(&missing).unwrap();
        assert_eq!(
            recorded.lines().nth(1).unwrap(),
            server.server_addr().to_ip().unwrap().to_string()
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A failed startup kills the children the prober already spawned.
    #[test]
    fn a_failed_startup_kills_tracked_children() {
        let mut command = std::process::Command::new("sleep");
        command.arg("30");
        let Ok((mut child, guard)) = crate::utils::child::spawn(&mut command) else {
            eprintln!("skipping: sleep is not available");
            return;
        };
        let shutdown = Arc::new(AtomicBool::new(false));

        abort_startup(&shutdown);

        assert!(shutdown.load(Ordering::SeqCst));
        let mut exit = None;
        for _ in 0..100 {
            match child.try_wait() {
                Ok(Some(status)) => {
                    exit = Some(status);
                    break;
                }
                _ => thread::sleep(Duration::from_millis(20)),
            }
        }
        let killed = exit.is_some();
        let _ = child.kill();
        let _ = child.wait();
        drop(guard);
        assert!(killed, "the sleeping child outlived the failed startup");
    }

    /// A kept source with a reason reaches the queue rows the web UI reads.
    #[test]
    fn a_kept_source_reason_reaches_the_queue_rows() {
        let mut state = DaemonState::new(AppConfig::default());
        let mut job = EncodingJob::new(std::path::PathBuf::from("kept.mkv"));
        job.status = JobStatus::Encoding { progress: 90.0 };
        let id = state.queue.push(job);
        state.session = Some(EncodeSession {
            job_ids: vec![id],
            cancel_flag: Arc::new(AtomicBool::new(false)),
        });
        state.encoding_active = true;
        let shared = Arc::new(Mutex::new(state));

        apply_worker_message(
            &shared,
            WorkerMessage::SourceKept(0, crate::encoder::KeepReason::Symlink),
        );

        assert_eq!(
            lock(&shared).queue.state.jobs[0].source_kept_reason,
            Some(crate::encoder::KeepReason::Symlink)
        );
        assert_eq!(
            crate::daemon::api::queue(&shared)["jobs"][0]["source_kept_reason"],
            "the source is a symbolic link"
        );
    }

    #[test]
    fn a_finished_job_leaves_the_run_open_for_the_next_ready_job() {
        let mut state = DaemonState::new(AppConfig::default());
        let mut active = EncodingJob::new(std::path::PathBuf::from("active.mkv"));
        active.status = JobStatus::Encoding { progress: 50.0 };
        let active_id = state.queue.push(active);
        let mut waiting = EncodingJob::new(std::path::PathBuf::from("waiting.mkv"));
        waiting.status = JobStatus::Ready;
        state.queue.push(waiting);
        state.queue.state.total_jobs_to_encode = 2;
        state.session = Some(EncodeSession {
            job_ids: vec![active_id],
            cancel_flag: Arc::new(AtomicBool::new(false)),
        });
        state.encoding_active = true;
        let shared = Arc::new(Mutex::new(state));

        apply_worker_message(&shared, WorkerMessage::Done(0));

        let state = lock(&shared);
        assert!(!state.encoding_active);
        // The pause marker is set; the next session start clears it and
        // subtracts the gap from the elapsed clock.
        assert!(state.queue.state.end_time.is_some());
        assert_eq!(state.queue.state.encoding_progress_done, 1);
        assert!(matches!(state.queue.state.jobs[1].status, JobStatus::Ready));
    }

    /// The dashboard reads `current_job_index` from the moment a session
    /// starts, before the first progress line arrives.
    #[test]
    fn a_started_session_points_current_job_at_the_encoding_job() {
        let dir = std::env::temp_dir().join(format!("av1c_session_start_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let source = dir.join("ready.mkv");
        std::fs::write(&source, b"source").unwrap();

        let shared = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        let (worker_tx, _worker_rx) = mpsc::channel();
        {
            let mut state = lock(&shared);
            let mut done = EncodingJob::new(std::path::PathBuf::from("done.mkv"));
            done.status = JobStatus::Done;
            state.queue.push(done);
            let mut ready = EncodingJob::new(source.clone());
            ready.status = JobStatus::Ready;
            ready.metadata = Some(crate::analyzer::VideoMetadata {
                width: 1920,
                height: 1080,
                hdr_type: crate::analyzer::HdrType::Sdr,
                dv_profile: None,
                dv_bl_compat: None,
                hdr10_static: None,
                codec_name: "hevc".to_string(),
                frame_rate_num: 24,
                frame_rate_den: 1,
                duration_secs: 1.0,
            });
            // An identity taken from the directory does not match the file;
            // the worker thread reports an error at once.
            ready.source_identity = Some(crate::queue::SourceIdentity::from_metadata(
                &std::fs::metadata(&dir).unwrap(),
            ));
            state.queue.push(ready);
        }

        maybe_start_session(&shared, &worker_tx);

        let state = lock(&shared);
        assert!(state.encoding_active);
        assert_eq!(state.queue.state.current_job_index, 1);
        assert!(matches!(
            state.queue.state.jobs[1].status,
            JobStatus::Encoding { .. }
        ));
        drop(state);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_ready_rip_without_an_output_path_fails_instead_of_waiting() {
        let shared = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        let (worker_tx, _worker_rx) = mpsc::channel();
        let id = {
            let mut state = lock(&shared);
            let mut rip =
                EncodingJob::new(std::path::PathBuf::from("/staging/rip-1-a/DISC_t00.mkv"));
            rip.status = JobStatus::Ready;
            rip.temporary = true;
            rip.metadata = Some(crate::analyzer::VideoMetadata {
                width: 1920,
                height: 1080,
                hdr_type: crate::analyzer::HdrType::Sdr,
                dv_profile: None,
                dv_bl_compat: None,
                hdr10_static: None,
                codec_name: "hevc".to_string(),
                frame_rate_num: 24,
                frame_rate_den: 1,
                duration_secs: 1.0,
            });
            rip.source_identity = Some(crate::queue::SourceIdentity::from_metadata(
                &std::fs::metadata(std::env::temp_dir()).unwrap(),
            ));
            state.queue.push(rip)
        };

        maybe_start_session(&shared, &worker_tx);

        let state = lock(&shared);
        assert!(!state.encoding_active);
        assert!(matches!(
            state.queue.job_by_id(id).unwrap().status,
            JobStatus::Error { .. }
        ));
        assert_eq!(state.queue.state.error_count, 1);
    }

    #[test]
    fn a_probe_holds_the_flag_cancel_sets_and_skips_settled_jobs() {
        let mut state = DaemonState::new(AppConfig::default());
        let mut waiting = EncodingJob::new(std::path::PathBuf::from("a.mkv"));
        waiting.status = JobStatus::Analyzing;
        let waiting = state.queue.push(waiting);
        let mut cancelled = EncodingJob::new(std::path::PathBuf::from("b.mkv"));
        cancelled.status = JobStatus::Skipped {
            reason: "Cancelled".to_string(),
        };
        let cancelled = state.queue.push(cancelled);
        state.analysis_cancel.store(true, Ordering::Release);

        let cancel = claim_probe(&mut state, waiting).expect("an analyzing job is probed");
        assert!(!cancel.load(Ordering::Relaxed));
        state.analysis_cancel.store(true, Ordering::Release);
        assert!(
            cancel.load(Ordering::Relaxed),
            "cancel reaches the running probe"
        );
        assert!(claim_probe(&mut state, cancelled).is_none());
        assert!(claim_probe(&mut state, 999).is_none());
    }

    #[cfg(unix)]
    #[test]
    fn a_ripped_title_with_a_non_utf8_path_is_marked_error() {
        use crate::disc::worker::DiscEvent;
        use std::os::unix::ffi::OsStringExt;

        let shared = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        let (probe_tx, probe_rx) = mpsc::channel();
        let id = {
            let mut state = lock(&shared);
            let mut job = EncodingJob::new(std::path::PathBuf::from("Title 0"));
            job.status = JobStatus::Ripping { progress: 0.0 };
            job.temporary = true;
            let id = state.queue.push(job);
            state.disc.job_ids = vec![id];
            state.disc.active = true;
            id
        };

        apply_disc_event(
            &shared,
            &probe_tx,
            DiscEvent::TitleReady {
                index: 0,
                path: std::path::PathBuf::from(std::ffi::OsString::from_vec(vec![0xff])),
            },
        );

        let state = lock(&shared);
        assert!(matches!(
            state.queue.job_by_id(id).unwrap().status,
            JobStatus::Error { .. }
        ));
        assert_eq!(state.queue.state.error_count, 1);
        assert!(probe_rx.try_recv().is_err());
    }

    #[test]
    fn a_run_stopped_by_an_error_does_not_count_its_titles_as_cancelled() {
        use crate::disc::DiscError;
        use crate::disc::worker::DiscEvent;

        let shared = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        let (probe_tx, _probe_rx) = mpsc::channel();
        let ids: Vec<u64> = {
            let mut state = lock(&shared);
            let ids = ["Title 0", "Title 1", "Title 2"]
                .iter()
                .map(|name| {
                    let mut job = EncodingJob::new(std::path::PathBuf::from(*name));
                    job.status = JobStatus::Ripping { progress: 0.0 };
                    job.temporary = true;
                    state.queue.push(job)
                })
                .collect();
            state.disc.job_ids = ids;
            state.disc.active = true;
            state.disc.job_ids.clone()
        };

        apply_disc_event(
            &shared,
            &probe_tx,
            DiscEvent::Error {
                index: 0,
                error: DiscError::DiscChanged,
            },
        );

        let state = lock(&shared);
        let message = DiscError::DiscChanged.message(state.config.language);
        assert!(matches!(
            state.queue.job_by_id(ids[0]).unwrap().status,
            JobStatus::Error { .. }
        ));
        for id in &ids[1..] {
            assert!(matches!(
                &state.queue.job_by_id(*id).unwrap().status,
                JobStatus::Skipped { reason } if *reason == message
            ));
        }
        assert_eq!(state.queue.state.cancelled_count, 0);
        assert_eq!(state.queue.state.skipped_count, 2);
    }

    /// An extracted title is repointed at its file and handed to the prober
    /// right away, while the drive carries on with the next one.
    #[test]
    fn a_ripped_title_goes_straight_to_the_prober() {
        use crate::disc::worker::DiscEvent;

        let shared = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        let (probe_tx, probe_rx) = mpsc::channel();
        let ids: Vec<u64> = {
            let mut state = lock(&shared);
            let ids = ["Title 0", "Title 1"]
                .iter()
                .map(|name| {
                    let mut job = EncodingJob::new(std::path::PathBuf::from(*name));
                    job.status = JobStatus::Ripping { progress: 0.0 };
                    job.temporary = true;
                    state.queue.push(job)
                })
                .collect();
            state.disc.job_ids = ids;
            state.disc.active = true;
            state.disc.job_ids.clone()
        };

        apply_disc_event(
            &shared,
            &probe_tx,
            DiscEvent::Ripping {
                index: 0,
                progress: 42.0,
            },
        );
        assert!(matches!(
            lock(&shared).queue.job_by_id(ids[0]).unwrap().status,
            JobStatus::Ripping { progress } if (progress - 42.0).abs() < f64::EPSILON
        ));

        apply_disc_event(
            &shared,
            &probe_tx,
            DiscEvent::TitleReady {
                index: 0,
                path: std::path::PathBuf::from("/staging/rip-a/DISC_t00.mkv"),
            },
        );
        assert_eq!(
            probe_rx.try_recv().unwrap(),
            (ids[0], "/staging/rip-a/DISC_t00.mkv".to_string())
        );
        assert!(matches!(
            lock(&shared).queue.job_by_id(ids[0]).unwrap().status,
            JobStatus::Analyzing
        ));
        apply_disc_event(
            &shared,
            &probe_tx,
            DiscEvent::Ripping {
                index: 0,
                progress: 99.0,
            },
        );
        assert!(
            matches!(
                lock(&shared).queue.job_by_id(ids[0]).unwrap().status,
                JobStatus::Analyzing
            ),
            "late rip progress must not overwrite a title that already extracted"
        );
        // The run is not over: the second title is still to come.
        assert!(lock(&shared).disc.active);

        apply_disc_event(
            &shared,
            &probe_tx,
            DiscEvent::Error {
                index: 1,
                error: crate::disc::DiscError::UnreadableDisc,
            },
        );
        let state = lock(&shared);
        assert!(matches!(
            state.queue.job_by_id(ids[1]).unwrap().status,
            JobStatus::Error { .. }
        ));
        assert!(!state.disc.active, "a failure ends the run");
        assert!(state.disc.error.is_some());
        assert_eq!(state.queue.state.error_count, 1);
        // A title that never became a file is not left waiting to be encoded
        // from one: only the extracted title is still in flight, at the prober.
        assert!(
            state.queue.state.jobs.iter().all(|job| !matches!(
                job.status,
                JobStatus::Ripping { .. } | JobStatus::Ready | JobStatus::Pending
            )),
            "a failed extraction left a job queued against a file that was never written"
        );
    }

    #[test]
    fn add_paths_reserves_each_source_once() {
        let dir = std::env::temp_dir().join(format!("av1c_daemon_add_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("movie.mkv");
        std::fs::write(&path, b"not a real video").unwrap();

        let shared = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        let (tx, _rx) = mpsc::channel();
        assert_eq!(
            add_paths(
                &shared,
                &tx,
                vec![path.clone(), dir.join(".").join("movie.mkv")],
                ""
            ),
            (1, 1, 0)
        );
        assert_eq!(add_paths(&shared, &tx, vec![path], ""), (0, 1, 0));
        assert_eq!(lock(&shared).queue.state.jobs.len(), 1);

        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn adding_after_finished_queue_starts_fresh_totals() {
        let dir = std::env::temp_dir().join(format!("av1c_daemon_fresh_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("new.mkv");
        std::fs::write(&path, b"not a real video").unwrap();

        let shared = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        {
            let mut state = lock(&shared);
            let mut old = EncodingJob::new(std::path::PathBuf::from("/tmp/old.mkv"));
            old.status = JobStatus::Error {
                message: "old failure".to_string(),
            };
            state.queue.push(old);
            state.queue.state.converted_count = 7;
            state.queue.state.skipped_count = 9;
            state.queue.state.error_count = 3;
        }
        let (tx, _rx) = mpsc::channel();

        assert_eq!(add_paths(&shared, &tx, vec![path], ""), (1, 0, 0));
        let state = lock(&shared);
        assert_eq!(state.queue.state.converted_count, 0);
        assert_eq!(state.queue.state.skipped_count, 0);
        assert_eq!(state.queue.state.error_count, 0);

        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn restored_jobs_outside_the_new_root_are_never_resumed() {
        let base = std::env::temp_dir().join(format!("av1c_restore_root_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let root = base.join("root");
        let outside = base.join("outside");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::create_dir_all(&outside).unwrap();
        let source = outside.join("movie.mkv");
        let output = outside.join("movie_av1.mkv");
        let partial = outside.join("movie_av1.part.123_4.mkv");
        std::fs::write(&source, b"source").unwrap();
        std::fs::write(&partial, b"partial").unwrap();

        let staged = outside.join("DISC_t00.mkv");
        std::fs::write(&staged, b"staged").unwrap();

        let mut queue = crate::queue::QueueState::new();
        let mut job = EncodingJob::new(source);
        job.output_path = Some(output);
        job.status = JobStatus::Encoding { progress: 50.0 };
        queue.jobs.push(job);
        let mut rip = EncodingJob::new(staged.clone());
        rip.status = JobStatus::Ready;
        rip.temporary = true;
        rip.metadata = Some(crate::analyzer::VideoMetadata {
            width: 1920,
            height: 1080,
            hdr_type: crate::analyzer::HdrType::Sdr,
            dv_profile: None,
            dv_bl_compat: None,
            hdr10_static: None,
            codec_name: "hevc".to_string(),
            frame_rate_num: 24,
            frame_rate_den: 1,
            duration_secs: 1.0,
        });
        rip.source_identity = Some(crate::queue::SourceIdentity::from_metadata(
            &std::fs::metadata(&staged).unwrap(),
        ));
        queue.jobs.push(rip);
        let queue_file = base.join("queue.json");
        crate::queue::state::save(
            &queue_file,
            &crate::queue::QueueRef {
                state: &queue,
                ids: &[1, 2],
                next_id: 3,
            },
        )
        .unwrap();
        let config = AppConfig {
            daemon: crate::config::DaemonConfig {
                browse_root: root.to_string_lossy().into_owned(),
                ..crate::config::DaemonConfig::default()
            },
            disc: crate::config::DiscConfig {
                staging_directory: Some(base.join("staging").to_string_lossy().into_owned()),
                ..crate::config::DiscConfig::default()
            },
            ..AppConfig::default()
        };

        let (state, reprobe) = restore_state(config, &queue_file);
        assert!(matches!(
            state.queue.state.jobs[0].status,
            JobStatus::Error { .. }
        ));
        assert!(reprobe.is_empty());
        assert!(
            partial.exists(),
            "resume must not delete files outside browse_root"
        );
        assert!(matches!(state.queue.state.jobs[1].status, JobStatus::Ready));
        assert_eq!(state.queue.state.jobs[1].path, staged);
        assert!(staged.exists());
        let _ = std::fs::remove_dir_all(base);
    }

    #[test]
    fn an_unreadable_queue_file_is_reported_in_the_status() {
        let base = std::env::temp_dir().join(format!("av1c_restore_bad_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).unwrap();
        let queue_file = base.join("queue.json");
        std::fs::write(&queue_file, b"{not json").unwrap();
        let config = AppConfig {
            disc: crate::config::DiscConfig {
                staging_directory: Some(base.join("staging").to_string_lossy().into_owned()),
                ..crate::config::DiscConfig::default()
            },
            ..AppConfig::default()
        };

        let (state, _) = restore_state(config, &queue_file);
        let kept = state.unreadable_queue.clone().expect("the file is kept");
        assert_eq!(std::fs::read(&kept).unwrap(), b"{not json");
        let shared: SharedState = Arc::new(Mutex::new(state));
        assert_eq!(
            api::status(&shared)["unreadable_queue"],
            serde_json::json!(kept.display().to_string())
        );
        let _ = std::fs::remove_dir_all(base);
    }

    #[test]
    fn restored_jobs_whose_files_are_gone_keep_their_paths() {
        let base = std::env::temp_dir().join(format!("av1c_restore_gone_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let root = base.join("root");
        std::fs::create_dir_all(&root).unwrap();
        let output = root.join("movie_av1.mkv");
        std::fs::write(&output, b"encoded").unwrap();

        let mut queue = crate::queue::QueueState::new();
        let mut done = EncodingJob::new(root.join("movie.mkv"));
        done.output_path = Some(output);
        done.status = JobStatus::Done;
        queue.jobs.push(done);
        let mut pending = EncodingJob::new(root.join("gone").join("other.mkv"));
        pending.status = JobStatus::Pending;
        queue.jobs.push(pending);
        let queue_file = base.join("queue.json");
        crate::queue::state::save(
            &queue_file,
            &crate::queue::QueueRef {
                state: &queue,
                ids: &[1, 2],
                next_id: 3,
            },
        )
        .unwrap();
        let config_with_root = |browse_root: &std::path::Path| AppConfig {
            daemon: crate::config::DaemonConfig {
                browse_root: browse_root.to_string_lossy().into_owned(),
                ..crate::config::DaemonConfig::default()
            },
            disc: crate::config::DiscConfig {
                staging_directory: Some(base.join("staging").to_string_lossy().into_owned()),
                ..crate::config::DiscConfig::default()
            },
            ..AppConfig::default()
        };

        let (state, reprobe) = restore_state(config_with_root(&root), &queue_file);
        let jobs = &state.queue.state.jobs;
        assert!(matches!(jobs[0].status, JobStatus::Done));
        assert_eq!(jobs[0].path, root.canonicalize().unwrap().join("movie.mkv"));
        assert!(jobs[0].output_path.is_some());
        assert!(matches!(jobs[1].status, JobStatus::Analyzing));
        assert!(reprobe.iter().any(|(id, _)| *id == 2));

        // A root that is not mounted leaves every saved job as it was.
        let (state, _) = restore_state(config_with_root(&base.join("unmounted")), &queue_file);
        let jobs = &state.queue.state.jobs;
        assert!(matches!(jobs[0].status, JobStatus::Done));
        assert_eq!(jobs[0].path, root.join("movie.mkv"));
        let _ = std::fs::remove_dir_all(base);
    }

    #[test]
    fn a_stopped_daemon_saves_the_session_for_the_next_start() {
        let dir =
            std::env::temp_dir().join(format!("av1c_shutdown_persist_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let queue_file = dir.join("queue.json");

        let shared = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        {
            let mut state = lock(&shared);
            let id = state
                .queue
                .push(EncodingJob::new(std::path::PathBuf::from("/tmp/movie.mkv")));
            state.queue.job_by_id_mut(id).unwrap().status = JobStatus::Pending;
            state.session = Some(EncodeSession {
                job_ids: vec![id],
                cancel_flag: Arc::new(AtomicBool::new(true)),
            });
            state.encoding_active = true;
            state.shutting_down.store(true, Ordering::SeqCst);
        }

        apply_worker_message(&shared, WorkerMessage::Cancelled);
        let mut last_saved = Vec::new();
        let mut last_warning = None;
        persist_queue(&shared, &queue_file, &mut last_saved, &mut last_warning);

        let (mut saved, _) = crate::queue::state::load(&queue_file);
        assert!(matches!(saved.state.jobs[0].status, JobStatus::Pending));
        crate::queue::state::resume(&mut saved);
        assert!(!is_terminal(&saved.state.jobs[0].status));
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn a_late_analysis_error_does_not_overwrite_a_failed_job() {
        let shared = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        let id = {
            let mut state = lock(&shared);
            let mut job = EncodingJob::new(std::path::PathBuf::from("gone.mkv"));
            job.status = JobStatus::Error {
                message: "probe failed".to_string(),
            };
            state.queue.push(job)
        };
        apply_analysis_result(&shared, id, Err(AppError::Analysis("late".to_string())));
        let state = lock(&shared);
        assert!(matches!(
            &state.queue.job_by_id(id).unwrap().status,
            JobStatus::Error { message } if message == "probe failed"
        ));
        assert_eq!(state.queue.state.error_count, 0);
    }

    #[cfg(unix)]
    #[test]
    fn a_settled_disc_run_sweeps_orphaned_staging_directories() {
        let root = std::env::temp_dir().join(format!("av1c_settle_sweep_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let orphan = crate::disc::staging::staged_rip(&root, u32::MAX);

        let mut config = AppConfig::default();
        config.disc.staging_directory = Some(root.to_string_lossy().into_owned());
        let shared = Arc::new(Mutex::new(DaemonState::new(config)));
        let mut was_active = false;

        sweep_after_disc_run(&shared, &mut was_active, Duration::ZERO);
        assert!(orphan.exists(), "no run has settled yet");
        lock(&shared).disc.active = true;
        sweep_after_disc_run(&shared, &mut was_active, Duration::ZERO);
        assert!(orphan.exists(), "the run is still going");
        lock(&shared).disc.settle();
        sweep_after_disc_run(&shared, &mut was_active, Duration::ZERO);
        assert!(!orphan.exists());

        let _ = std::fs::remove_dir_all(root);
    }

    #[test]
    fn joining_http_threads_gives_up_after_the_grace() {
        let quick = thread::spawn(|| {});
        let stuck = thread::spawn(|| thread::sleep(Duration::from_secs(2)));
        assert!(!join_within(vec![quick, stuck], Duration::from_millis(200)));
        assert!(join_within(
            vec![thread::spawn(|| {})],
            Duration::from_secs(1)
        ));
    }

    #[test]
    fn draining_a_daemon_stop_leaves_an_encoding_job_for_resume() {
        let shared = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        let id = {
            let mut state = lock(&shared);
            let mut job = EncodingJob::new(std::path::PathBuf::from("movie.mkv"));
            job.status = JobStatus::Encoding { progress: 40.0 };
            let id = state.queue.push(job);
            state.session = Some(EncodeSession {
                job_ids: vec![id],
                cancel_flag: Arc::new(AtomicBool::new(true)),
            });
            state.encoding_active = true;
            state.shutting_down.store(true, Ordering::SeqCst);
            id
        };
        let (worker_tx, worker_rx) = mpsc::channel();
        drop(worker_tx);
        let (disc_tx, disc_rx) = mpsc::channel();
        drop(disc_tx);
        let (probe_tx, _probe_rx) = mpsc::channel();

        drain_shutdown_channels(&shared, &worker_rx, &disc_rx, &probe_tx);

        assert!(matches!(
            lock(&shared).queue.job_by_id(id).unwrap().status,
            JobStatus::Encoding { .. }
        ));
    }

    #[test]
    fn a_stop_during_analysis_leaves_the_job_for_resume() {
        let shared = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        let id = {
            let mut state = lock(&shared);
            let mut job = EncodingJob::new(std::path::PathBuf::from("movie.mkv"));
            job.status = JobStatus::Analyzing;
            state.shutting_down.store(true, Ordering::SeqCst);
            state.queue.push(job)
        };
        apply_analysis_result(&shared, id, Err(AppError::Cancelled));
        assert!(matches!(
            lock(&shared).queue.job_by_id(id).unwrap().status,
            JobStatus::Analyzing
        ));
    }

    #[test]
    fn draining_shutdown_skips_a_job_still_marked_encoding() {
        let shared = Arc::new(Mutex::new(DaemonState::new(AppConfig::default())));
        let id = {
            let mut state = lock(&shared);
            let mut job = EncodingJob::new(std::path::PathBuf::from("movie.mkv"));
            job.status = JobStatus::Encoding { progress: 40.0 };
            let id = state.queue.push(job);
            state.session = Some(EncodeSession {
                job_ids: vec![id],
                cancel_flag: Arc::new(AtomicBool::new(true)),
            });
            state.encoding_active = true;
            id
        };
        let (worker_tx, worker_rx) = mpsc::channel();
        drop(worker_tx);
        let (disc_tx, disc_rx) = mpsc::channel();
        drop(disc_tx);
        let (probe_tx, _probe_rx) = mpsc::channel();

        drain_shutdown_channels(&shared, &worker_rx, &disc_rx, &probe_tx);

        let state = lock(&shared);
        assert!(matches!(
            &state.queue.job_by_id(id).unwrap().status,
            JobStatus::Skipped { reason } if reason == "Cancelled"
        ));
        assert!(!state.encoding_active);
    }
}