ff-preview 0.13.1

Real-time video/audio preview and proxy workflow
Documentation
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
//! `PreviewPlayer` — main playback driver for ff-preview.
//!
//! All safe Rust logic lives here. Unsafe `FFmpeg` calls are isolated in
//! `playback_inner`.

use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use ff_decode::{AudioDecoder, SeekMode};
use ff_format::SampleFormat;

use super::clock::MasterClock;
use super::decode_buffer::{DecodeBuffer, FrameResult, SeekEvent};
use super::sink::FrameSink;
use crate::error::PreviewError;

// ── Constants ─────────────────────────────────────────────────────────────────

/// Maximum number of interleaved stereo `f32` samples to buffer for audio
/// playback (2 s × 48 kHz × 2 channels = 96 000).
const AUDIO_MAX_BUF: usize = 96_000;

// ── PreviewPlayer ─────────────────────────────────────────────────────────────

/// Drives real-time playback of a single media file.
///
/// `PreviewPlayer` decodes a video/audio file, synchronises video frame
/// presentation to an audio master clock, and delivers frames to a
/// registered [`FrameSink`].
///
/// # Usage
///
/// ```ignore
/// let mut player = PreviewPlayer::open(Path::new("clip.mp4"))?;
/// player.set_sink(Box::new(MySink::new()));
/// player.play();
/// player.run()?;
/// ```
pub struct PreviewPlayer {
    /// Path to the media file; retained so the audio decode thread can be
    /// restarted from a new position after a seek.
    path: PathBuf,
    /// Pre-decoded frame buffer driven by a background thread.
    /// `None` for audio-only files that have no video stream.
    decode_buf: Option<DecodeBuffer>,
    /// Video frame rate; used to compute the frame period for A/V sync.
    fps: f64,
    /// Frame sink registered via [`set_sink`](Self::set_sink). Optional;
    /// frames are discarded silently if no sink is set.
    sink: Option<Box<dyn FrameSink>>,
    /// Set to `true` while the presentation loop is paused.
    paused: Arc<AtomicBool>,
    /// Set to `true` to signal [`run`](Self::run) to stop after the current frame.
    stopped: Arc<AtomicBool>,
    /// Master clock for A/V sync: audio samples counter or `Instant` wall clock.
    clock: MasterClock,
    /// A/V offset correction in milliseconds (default: 0).
    ///
    /// Positive: video is delayed (video PTS adjusted down).
    /// Negative: audio is delayed (video PTS adjusted up).
    av_offset_ms: Arc<AtomicI64>,
    /// Decoded audio samples (interleaved f32 stereo at 48 kHz).
    /// `None` when the media file has no audio track.
    audio_buf: Option<Arc<Mutex<VecDeque<f32>>>>,
    /// Cancel flag for the background audio decode thread.
    /// `None` when the media file has no audio track.
    audio_cancel: Option<Arc<AtomicBool>>,
    /// Handle for the background audio decode thread.
    audio_handle: Option<JoinHandle<()>>,
    /// Lazy `sws_scale` converter that converts each frame to packed RGBA.
    /// Re-creates the `SwsContext` automatically when frame geometry changes.
    sws: super::playback_inner::SwsRgbaConverter,
    /// Scratch buffer reused by `present_frame` for the RGBA output of `sws.convert()`.
    rgba_buf: Vec<u8>,
    /// The path currently being decoded — either the original or an activated proxy.
    /// Starts as a clone of `path`; updated by `use_proxy_if_available`.
    active_path: PathBuf,
    /// Set to `true` by `play()` to prevent `use_proxy_if_available` from being
    /// called after playback has started.
    started: AtomicBool,
    /// PTS of the most recently presented frame, in milliseconds.
    /// Updated atomically inside `present_frame()`; readable from any thread.
    current_pts_millis: AtomicU64,
    /// Container-reported duration in milliseconds.
    /// `u64::MAX` when the container does not report a duration (live/streaming sources).
    duration_millis: u64,
    /// Playback rate stored as `f64` bits in an atomic (default: `1.0`).
    /// Read once per frame in `run()` to scale the frame-pacing sleep duration.
    /// Use `rate_handle()` to share this across threads.
    rate_bits: Arc<AtomicU64>,
}

impl PreviewPlayer {
    /// Open a media file and prepare for playback.
    ///
    /// Probes the file to detect audio/video streams, then opens a
    /// [`DecodeBuffer`] for the video stream (when present). Returns
    /// [`PreviewError`] if the file is missing, unreadable, or contains
    /// neither a video nor an audio stream.
    ///
    /// Audio-only files (MP3, AAC, WAV, FLAC, …) are fully supported:
    /// `run()` will pace itself via the audio master clock and deliver no
    /// video frames. Callers should drain samples via
    /// [`pop_audio_samples`](Self::pop_audio_samples).
    ///
    /// # Errors
    ///
    /// Returns [`PreviewError`] if the file cannot be probed or decoded.
    pub fn open(path: &Path) -> Result<Self, PreviewError> {
        let info = ff_probe::open(path)?;

        if !info.has_video() && !info.has_audio() {
            return Err(PreviewError::Ffmpeg {
                code: -1,
                message: "file has neither a video nor an audio stream".into(),
            });
        }

        let fps = info.frame_rate().unwrap_or(30.0).max(1.0);

        // Duration::ZERO means the container does not report a duration (live/streaming).
        let d = info.duration();
        let duration_millis = if d.is_zero() {
            u64::MAX
        } else {
            u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
        };

        let clock = if info.has_audio() {
            let sample_rate = info.sample_rate().unwrap_or(48_000);
            MasterClock::Audio {
                samples_consumed: Arc::new(AtomicU64::new(0)),
                sample_rate,
            }
        } else {
            log::debug!(
                "using system clock fallback path={} no_audio=true",
                path.display()
            );
            MasterClock::System {
                started_at: Instant::now(),
                base_pts: Duration::ZERO,
            }
        };

        // Open the video decode buffer only when a video stream is present.
        // Audio-only files skip this step and use audio-clock pacing in run().
        let decode_buf = if info.has_video() {
            Some(DecodeBuffer::open(path).build()?)
        } else {
            log::debug!(
                "audio-only file; skipping video decode buffer path={}",
                path.display()
            );
            None
        };

        // Spawn a background audio decode thread when an audio track is present.
        let (audio_buf, audio_cancel, audio_handle) = if let MasterClock::Audio { .. } = &clock {
            let buf = Arc::new(Mutex::new(VecDeque::<f32>::new()));
            let cancel = Arc::new(AtomicBool::new(false));
            let handle = spawn_audio_thread(
                path.to_path_buf(),
                Duration::ZERO,
                Arc::clone(&buf),
                Arc::clone(&cancel),
            );
            (Some(buf), Some(cancel), Some(handle))
        } else {
            (None, None, None)
        };

        Ok(PreviewPlayer {
            path: path.to_path_buf(),
            decode_buf,
            fps,
            sink: None,
            paused: Arc::new(AtomicBool::new(false)),
            stopped: Arc::new(AtomicBool::new(false)),
            clock,
            av_offset_ms: Arc::new(AtomicI64::new(0)),
            audio_buf,
            audio_cancel,
            audio_handle,
            sws: super::playback_inner::SwsRgbaConverter::new(),
            rgba_buf: Vec::new(),
            active_path: path.to_path_buf(),
            started: AtomicBool::new(false),
            current_pts_millis: AtomicU64::new(0),
            duration_millis,
            rate_bits: Arc::new(AtomicU64::new(1.0_f64.to_bits())),
        })
    }

    /// Register the frame sink. Must be called before [`run`](Self::run).
    pub fn set_sink(&mut self, sink: Box<dyn FrameSink>) {
        self.sink = Some(sink);
    }

    /// Start (or resume) playback.
    ///
    /// Clears the `paused` and `stopped` flags. Must be called before
    /// [`run`](Self::run).
    pub fn play(&self) {
        self.started.store(true, Ordering::Release);
        self.paused.store(false, Ordering::Release);
        self.stopped.store(false, Ordering::Release);
    }

    /// Pause playback. [`run`](Self::run) will spin-sleep until
    /// [`play`](Self::play) is called again.
    pub fn pause(&self) {
        self.paused.store(true, Ordering::Release);
    }

    /// Stop playback.
    ///
    /// [`run`](Self::run) returns after the current frame completes.
    pub fn stop(&mut self) {
        self.stopped.store(true, Ordering::Release);
    }

    /// Returns a cloneable handle to the stop signal.
    ///
    /// Storing `true` into the returned [`Arc<AtomicBool>`] has the same effect
    /// as calling [`stop`](Self::stop) and is safe to call from any context,
    /// including from within a [`FrameSink::push_frame`] callback.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let stop = player.stop_handle();
    /// player.set_sink(Box::new(MySink { stop, max_frames: 10 }));
    /// player.play();
    /// player.run()?;
    /// ```
    pub fn stop_handle(&self) -> Arc<AtomicBool> {
        Arc::clone(&self.stopped)
    }

    /// Returns a cloneable handle to the pause flag.
    ///
    /// Storing `true` pauses [`run`](Self::run); storing `false` resumes it.
    /// Safe to call from any context, including from a UI thread running
    /// concurrently with [`run`](Self::run).
    ///
    /// # Example
    ///
    /// ```ignore
    /// let pause = player.pause_handle();
    /// let stop  = player.stop_handle();
    ///
    /// std::thread::spawn(move || { player.play(); let _ = player.run(); });
    ///
    /// pause.store(true, Ordering::Release);   // pause from UI thread
    /// pause.store(false, Ordering::Release);  // resume
    /// stop.store(true, Ordering::Release);    // stop
    /// ```
    pub fn pause_handle(&self) -> Arc<AtomicBool> {
        Arc::clone(&self.paused)
    }

    /// Pop the next decoded video frame.
    ///
    /// Delegates to [`DecodeBuffer::pop_frame`]. Blocks until a frame is available.
    /// Returns [`FrameResult::Eof`] at end of file or for audio-only files.
    pub fn pop_frame(&mut self) -> FrameResult {
        match self.decode_buf.as_mut() {
            Some(buf) => buf.pop_frame(),
            None => FrameResult::Eof,
        }
    }

    /// Frame-accurate seek to `target_pts`.
    ///
    /// Delegates to [`DecodeBuffer::seek`]. Returns `Ok(())` immediately for
    /// audio-only files (no video stream to seek).
    ///
    /// # Errors
    ///
    /// Returns [`PreviewError`] if the seek fails.
    pub fn seek(&mut self, target_pts: Duration) -> Result<(), PreviewError> {
        match self.decode_buf.as_mut() {
            Some(buf) => buf.seek(target_pts),
            None => Ok(()),
        }
    }

    /// Coarse seek to the nearest I-frame at or before `target_pts`.
    ///
    /// Delegates to [`DecodeBuffer::seek_coarse`]. Faster than
    /// [`seek`](Self::seek) because it skips the forward-decode discard phase.
    /// The first frame after this call will be at the nearest preceding I-frame,
    /// which may be up to ±½ GOP from `target_pts` (typically ±1–2 s for H.264
    /// at default settings).
    ///
    /// **Typical use:** call repeatedly while a scrub bar is being dragged;
    /// call [`seek`](Self::seek) on drag release for frame accuracy.
    ///
    /// ```ignore
    /// // Scrub-bar drag handler:
    /// player.seek_coarse(drag_pts)?;  // fast, called many times
    ///
    /// // Drag released:
    /// player.seek(release_pts)?;      // exact, called once
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`PreviewError`] if the seek fails.
    pub fn seek_coarse(&mut self, target_pts: Duration) -> Result<(), PreviewError> {
        match self.decode_buf.as_mut() {
            Some(buf) => buf.seek_coarse(target_pts),
            None => Ok(()),
        }
    }

    /// If a proxy file for this media exists in `proxy_dir`, use it transparently.
    ///
    /// Must be called before [`play`](Self::play). Returns `true` if a proxy was
    /// found and activated; returns `false` if no proxy exists (original file
    /// continues to be used).
    ///
    /// Proxy lookup order: `half` → `quarter` → `eighth`; first match wins.
    ///
    /// When a proxy is active, [`FrameSink::push_frame`] delivers frames at the
    /// proxy's native resolution. Callers should not assume a fixed resolution.
    ///
    /// If called after [`play`](Self::play), logs a warning and returns `false`.
    pub fn use_proxy_if_available(&mut self, proxy_dir: &Path) -> bool {
        if self.started.load(Ordering::Acquire) {
            log::warn!("use_proxy_if_available called after play; ignored");
            return false;
        }
        let stem = self
            .path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("output")
            .to_owned();

        for suffix in ["half", "quarter", "eighth"] {
            let candidate = proxy_dir.join(format!("{stem}_proxy_{suffix}.mp4"));
            if candidate.exists() {
                match self.activate_proxy(&candidate) {
                    Ok(()) => {
                        log::debug!("proxy activated path={}", candidate.display());
                        return true;
                    }
                    Err(e) => {
                        log::warn!(
                            "proxy activation failed path={} error={e}",
                            candidate.display()
                        );
                    }
                }
            }
        }
        false
    }

    /// Returns the path currently being decoded — either the original file or
    /// the activated proxy.
    pub fn active_source(&self) -> &Path {
        &self.active_path
    }

    /// Replace the internal decode buffer and audio thread with those backed by
    /// `proxy_path`. Called exclusively from `use_proxy_if_available`.
    fn activate_proxy(&mut self, proxy_path: &Path) -> Result<(), PreviewError> {
        let info = ff_probe::open(proxy_path)?;
        let fps = info.frame_rate().unwrap_or(30.0).max(1.0);
        let decode_buf = DecodeBuffer::open(proxy_path).build()?;

        // Cancel existing audio thread; clear stale samples.
        if let Some(cancel) = &self.audio_cancel {
            cancel.store(true, Ordering::Release);
        }
        if let Some(buf) = &self.audio_buf {
            buf.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .clear();
        }
        // Detach — the old thread exits on its own when cancel fires.
        drop(self.audio_handle.take());

        let (clock, audio_buf, audio_cancel, audio_handle) = if info.has_audio() {
            let sample_rate = info.sample_rate().unwrap_or(48_000);
            let buf = Arc::new(Mutex::new(VecDeque::<f32>::new()));
            let cancel = Arc::new(AtomicBool::new(false));
            let handle = spawn_audio_thread(
                proxy_path.to_path_buf(),
                Duration::ZERO,
                Arc::clone(&buf),
                Arc::clone(&cancel),
            );
            let clock = MasterClock::Audio {
                samples_consumed: Arc::new(AtomicU64::new(0)),
                sample_rate,
            };
            (clock, Some(buf), Some(cancel), Some(handle))
        } else {
            log::debug!(
                "proxy has no audio, using system clock path={}",
                proxy_path.display()
            );
            let clock = MasterClock::System {
                started_at: Instant::now(),
                base_pts: Duration::ZERO,
            };
            (clock, None, None, None)
        };

        self.active_path = proxy_path.to_path_buf();
        self.fps = fps;
        self.decode_buf = Some(decode_buf);
        self.clock = clock;
        self.audio_buf = audio_buf;
        self.audio_cancel = audio_cancel;
        self.audio_handle = audio_handle;
        Ok(())
    }

    /// Set the A/V offset correction in milliseconds.
    ///
    /// - **Positive** value: video is delayed by `ms` ms relative to the audio
    ///   clock (video PTS is shifted down in the sync comparison).
    /// - **Negative** value: audio is delayed by `ms` ms relative to video
    ///   (video PTS is shifted up in the sync comparison).
    ///
    /// Values outside ±5 000 ms are clamped and a warning is logged.
    /// Safe to call from any thread while [`run`](Self::run) is executing.
    pub fn set_av_offset(&self, ms: i64) {
        const MAX_OFFSET_MS: i64 = 5_000;
        let clamped = if ms.abs() > MAX_OFFSET_MS {
            log::warn!("av_offset clamped value={ms}");
            ms.clamp(-MAX_OFFSET_MS, MAX_OFFSET_MS)
        } else {
            ms
        };
        self.av_offset_ms.store(clamped, Ordering::Relaxed);
    }

    /// Returns the current A/V offset in milliseconds (default: `0`).
    ///
    /// Safe to call from any thread while [`run`](Self::run) is executing.
    pub fn av_offset(&self) -> i64 {
        self.av_offset_ms.load(Ordering::Relaxed)
    }

    /// Returns a cloneable handle to the A/V offset atomic.
    ///
    /// Writing a value into the returned [`Arc<AtomicI64>`] has the same effect
    /// as calling [`set_av_offset`](Self::set_av_offset) and is safe to do from
    /// any thread while [`run`](Self::run) is executing.
    ///
    /// Note: the handle stores the raw millisecond value without clamping.
    /// Values outside ±5 000 ms written directly to the handle will be applied
    /// as-is by `run()`; prefer [`set_av_offset`](Self::set_av_offset) when
    /// clamping is desired.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let av_handle   = player.av_offset_handle();
    /// let stop_handle = player.stop_handle();
    ///
    /// std::thread::spawn(move || { player.play(); let _ = player.run(); });
    ///
    /// // Adjust A/V sync from the UI thread without stopping playback.
    /// av_handle.store(200, std::sync::atomic::Ordering::Relaxed);
    /// stop_handle.store(true, std::sync::atomic::Ordering::Release);
    /// ```
    pub fn av_offset_handle(&self) -> Arc<AtomicI64> {
        Arc::clone(&self.av_offset_ms)
    }

    /// Set the playback rate.
    ///
    /// Values ≤ 0.0 are silently ignored — the rate remains unchanged.
    ///
    /// The new rate takes effect on the next frame's sleep calculation inside
    /// [`run`](Self::run). Safe to call from any thread while `run()` is
    /// executing (same contract as [`set_av_offset`](Self::set_av_offset)).
    ///
    /// - `1.0` — real-time (default)
    /// - `2.0` — twice real-time (sleep halved)
    /// - `0.5` — half real-time (sleep doubled)
    pub fn set_rate(&self, rate: f64) {
        if rate > 0.0 {
            self.rate_bits.store(rate.to_bits(), Ordering::Relaxed);
        }
    }

    /// Returns a cloneable handle to the rate atomic.
    ///
    /// Writing `new_rate.to_bits()` into the returned [`Arc<AtomicU64>`] has
    /// the same effect as calling [`set_rate`](Self::set_rate) and is safe to
    /// do from any thread while [`run`](Self::run) is executing.
    ///
    /// Note: the handle does **not** validate the value; storing bits that
    /// correspond to `≤ 0.0` or `NaN` will produce undefined sleep behaviour.
    /// Prefer [`set_rate`](Self::set_rate) when the validation guard is desired.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let rate   = player.rate_handle();
    /// let stop   = player.stop_handle();
    ///
    /// std::thread::spawn(move || { player.play(); let _ = player.run(); });
    ///
    /// // Double speed from the UI thread without stopping playback.
    /// rate.store(2.0_f64.to_bits(), std::sync::atomic::Ordering::Relaxed);
    /// stop.store(true, std::sync::atomic::Ordering::Release);
    /// ```
    pub fn rate_handle(&self) -> Arc<AtomicU64> {
        Arc::clone(&self.rate_bits)
    }

    /// Returns the PTS of the most recently presented frame.
    ///
    /// Returns [`Duration::ZERO`] before the first frame has been presented.
    /// Safe to call from any thread while [`run`](Self::run) is executing.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let pts_handle = Arc::new(Mutex::new(Duration::ZERO));
    /// let pts_clone  = Arc::clone(&pts_handle);
    ///
    /// std::thread::spawn(move || {
    ///     player.play();
    ///     let _ = player.run();
    /// });
    ///
    /// // UI thread: poll current position to drive a seek bar.
    /// loop {
    ///     let pos = player.current_pts();
    ///     update_seek_bar(pos);
    ///     std::thread::sleep(std::time::Duration::from_millis(16));
    /// }
    /// ```
    pub fn current_pts(&self) -> Duration {
        Duration::from_millis(self.current_pts_millis.load(Ordering::Relaxed))
    }

    /// Returns the container-reported duration of the media file, if known.
    ///
    /// Returns `None` for live or streaming sources where the container does
    /// not report a duration. Use the returned value to size a seek bar range:
    ///
    /// ```ignore
    /// if let Some(total) = player.duration() {
    ///     let progress = player.current_pts().as_secs_f64() / total.as_secs_f64();
    ///     seek_bar.set_fraction(progress);
    /// }
    /// ```
    pub fn duration(&self) -> Option<Duration> {
        if self.duration_millis == u64::MAX {
            None
        } else {
            Some(Duration::from_millis(self.duration_millis))
        }
    }

    /// Pull up to `n_samples` interleaved stereo `f32` PCM samples at 48 kHz.
    ///
    /// Intended for use inside an audio output callback:
    /// ```ignore
    /// let samples = player.pop_audio_samples(buffer_size);
    /// output_buffer[..samples.len()].copy_from_slice(&samples);
    /// // fill remainder with silence when samples.len() < buffer_size (underrun)
    /// ```
    ///
    /// Advances the audio master clock by the number of stereo frames consumed
    /// (`samples.len() / 2`).
    ///
    /// Returns an empty `Vec` when:
    /// - the file has no audio track,
    /// - `n_samples` is `0`,
    /// - playback is paused or stopped, or
    /// - the ring buffer is empty (underrun — caller should output silence).
    pub fn pop_audio_samples(&self, n_samples: usize) -> Vec<f32> {
        if self.paused.load(Ordering::Relaxed) || self.stopped.load(Ordering::Relaxed) {
            return Vec::new();
        }
        let MasterClock::Audio {
            samples_consumed, ..
        } = &self.clock
        else {
            return Vec::new();
        };
        if n_samples == 0 {
            return Vec::new();
        }
        let Some(buf) = &self.audio_buf else {
            return Vec::new();
        };
        let mut guard = buf
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let take = n_samples.min(guard.len());
        if take == 0 {
            return Vec::new();
        }
        let samples: Vec<f32> = guard.drain(..take).collect();
        // Stereo: 2 interleaved samples per frame.
        // Divide by 2 to get mono-equivalent frame count for the audio clock.
        samples_consumed.fetch_add((take / 2) as u64, Ordering::Relaxed);
        samples
    }

    /// A/V sync presentation loop.
    ///
    /// Blocks until [`stop`](Self::stop) is called or the end of file is
    /// reached. Must be called from the presentation thread.
    ///
    /// Video PTS is compared against the master clock:
    /// - **Early frames** (video PTS > clock + 1 frame period): sleep.
    /// - **Late frames** (video PTS < clock − 1 frame period): dropped.
    ///
    /// For video-only files the `System` clock (`Instant`) drives real-time
    /// pacing. For files with audio the `Audio` clock drives sync once
    /// [`pop_audio_samples`](Self::pop_audio_samples) has been called at least
    /// once; before that, frames are presented immediately.
    ///
    /// # Errors
    ///
    /// Returns [`PreviewError`] if a frame cannot be presented to the sink.
    pub fn run(&mut self) -> Result<(), PreviewError> {
        let fps = self.fps.max(1.0);
        let frame_period = Duration::from_secs_f64(1.0 / fps);

        // Start the system clock from position 0.
        // Seek events update base_pts during playback.
        self.clock.reset(Duration::ZERO);

        loop {
            if self.stopped.load(Ordering::Acquire) {
                break;
            }
            if self.paused.load(Ordering::Acquire) {
                thread::sleep(Duration::from_millis(5));
                continue;
            }

            // ── Audio-only path ───────────────────────────────────────────────
            // When there is no video stream, pace via a short sleep and exit
            // once the audio thread has finished and the ring buffer is empty
            // (meaning all samples have been consumed by the caller).
            if self.decode_buf.is_none() {
                thread::sleep(Duration::from_millis(10));
                if let Some(audio_buf) = &self.audio_buf {
                    let empty = audio_buf
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .is_empty();
                    if empty
                        && self
                            .audio_handle
                            .as_ref()
                            .is_none_or(JoinHandle::is_finished)
                    {
                        break;
                    }
                } else {
                    // No audio either — nothing to do.
                    break;
                }
                continue;
            }

            // ── Video decode path ─────────────────────────────────────────────
            // decode_buf is Some (verified by is_none() check above).
            let pop_result = if let Some(buf) = self.decode_buf.as_mut() {
                buf.pop_frame()
            } else {
                FrameResult::Eof // unreachable: handled by is_none() above
            };
            match pop_result {
                FrameResult::Eof => break,
                FrameResult::Seeking(last) => {
                    if let Some(ref f) = last {
                        self.present_frame(f);
                    }
                    // Non-blocking — loop immediately to check stopped/paused.
                }
                FrameResult::Frame(frame) => {
                    // Drain all pending seek-completion events. Collect pts
                    // values first so the borrow on decode_buf ends before
                    // restart_audio_from() takes &mut self.
                    let seek_pts: Vec<Duration> = match self.decode_buf.as_ref() {
                        Some(buf) => {
                            let mut v = Vec::new();
                            while let Ok(SeekEvent::Completed { pts }) =
                                buf.seek_events().try_recv()
                            {
                                v.push(pts);
                            }
                            v
                        }
                        None => Vec::new(),
                    };
                    for pts in seek_pts {
                        self.clock.reset(pts);
                        // Flush stale audio and restart the audio thread from
                        // the seek position so audio and video stay aligned.
                        self.restart_audio_from(pts);
                    }

                    if self.clock.should_sync() {
                        let video_pts = if frame.timestamp().is_valid() {
                            frame.timestamp().as_duration()
                        } else {
                            Duration::ZERO
                        };

                        // Apply A/V offset correction.
                        let offset_ms = self.av_offset_ms.load(Ordering::Relaxed);
                        let offset = Duration::from_millis(offset_ms.unsigned_abs());
                        let adjusted_video_pts = if offset_ms >= 0 {
                            // Positive: video delayed — subtract offset so the
                            // frame appears "earlier" relative to the clock.
                            video_pts.saturating_sub(offset)
                        } else {
                            // Negative: audio delayed — add offset so the frame
                            // appears "later" relative to the clock.
                            video_pts + offset
                        };

                        let clock_pts = self.clock.current_pts();
                        let diff = adjusted_video_pts.as_secs_f64() - clock_pts.as_secs_f64();
                        let fp = frame_period.as_secs_f64();

                        if diff > fp {
                            // Frame is early — sleep until it aligns with the clock.
                            // Divide by rate so higher rates shorten the sleep proportionally.
                            let rate = f64::from_bits(self.rate_bits.load(Ordering::Relaxed));
                            let sleep_secs =
                                (diff - fp / 2.0).max(0.0) / rate.max(f64::MIN_POSITIVE);
                            thread::sleep(Duration::from_secs_f64(sleep_secs));
                        } else if diff < -fp {
                            // Frame is more than one period late — drop silently.
                            log::debug!(
                                "dropped late frame video_pts={video_pts:?} \
                                 clock_pts={clock_pts:?}"
                            );
                            continue;
                        }
                    }

                    self.present_frame(&frame);
                }
            }
        }
        if let Some(sink) = self.sink.as_mut() {
            sink.flush();
        }
        Ok(())
    }

    /// Convert `frame` to RGBA and pass it to the registered sink, if any.
    fn present_frame(&mut self, frame: &ff_format::VideoFrame) {
        let Some(sink) = self.sink.as_mut() else {
            return;
        };
        let width = frame.width();
        let height = frame.height();
        let pts = frame.timestamp().as_duration();
        // Store PTS so current_pts() can be read from any thread.
        // Saturate at u64::MAX for videos longer than ~585 million years.
        self.current_pts_millis.store(
            u64::try_from(pts.as_millis()).unwrap_or(u64::MAX),
            Ordering::Relaxed,
        );
        if self.sws.convert(frame, &mut self.rgba_buf) {
            sink.push_frame(&self.rgba_buf, width, height, pts);
        }
    }

    /// Flush the audio ring buffer and restart the background audio decode
    /// thread from `pts`.
    ///
    /// Called after a video seek completes so that audio samples stay aligned
    /// with the video timeline. The old thread's cancel flag is set; it exits
    /// at its next cancel check and is detached.
    fn restart_audio_from(&mut self, pts: Duration) {
        // Flush stale samples so the new thread fills only fresh audio.
        if let Some(buf) = &self.audio_buf {
            buf.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .clear();
        }
        // Signal the running audio thread to stop.
        if let Some(cancel) = &self.audio_cancel {
            cancel.store(true, Ordering::Release);
        }
        // Detach the old handle — the thread exits on its own when cancel fires.
        drop(self.audio_handle.take());
        // Spawn a fresh thread that decodes from the seek position.
        if let Some(buf) = &self.audio_buf {
            let new_cancel = Arc::new(AtomicBool::new(false));
            let handle = spawn_audio_thread(
                self.active_path.clone(),
                pts,
                Arc::clone(buf),
                Arc::clone(&new_cancel),
            );
            self.audio_cancel = Some(new_cancel);
            self.audio_handle = Some(handle);
        }
    }
}

impl Drop for PreviewPlayer {
    fn drop(&mut self) {
        // Cancel the audio background thread before dropping so it does not
        // outlive the player (the Arc<Mutex<VecDeque>> it holds would stay
        // alive until the thread exits otherwise).
        if let Some(cancel) = &self.audio_cancel {
            cancel.store(true, Ordering::Release);
        }
        if let Some(h) = self.audio_handle.take() {
            let _ = h.join();
        }
    }
}

// ── spawn_audio_thread ────────────────────────────────────────────────────────

/// Open an [`AudioDecoder`] configured for stereo f32 at 48 kHz, optionally
/// seek to `start_pts`, and push decoded samples into `buf` until the cancel
/// flag is set or EOF is reached.
///
/// The buffer is capped at [`AUDIO_MAX_BUF`] samples; the thread sleeps 1 ms
/// when the buffer is full to avoid busy-waiting.
fn spawn_audio_thread(
    path: PathBuf,
    start_pts: Duration,
    buf: Arc<Mutex<VecDeque<f32>>>,
    cancel: Arc<AtomicBool>,
) -> JoinHandle<()> {
    thread::spawn(move || {
        let mut decoder = match AudioDecoder::open(&path)
            .output_format(SampleFormat::F32)
            .output_sample_rate(48_000)
            .output_channels(2)
            .build()
        {
            Ok(d) => d,
            Err(e) => {
                log::warn!("audio decode thread open failed error={e}");
                return;
            }
        };

        if start_pts != Duration::ZERO
            && let Err(e) = decoder.seek(start_pts, SeekMode::Backward)
        {
            log::warn!("audio seek failed pts={start_pts:?} error={e}");
        }

        loop {
            if cancel.load(Ordering::Acquire) {
                break;
            }

            let buf_len = buf
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len();
            if buf_len >= AUDIO_MAX_BUF {
                thread::sleep(Duration::from_millis(1));
                continue;
            }

            match decoder.decode_one() {
                Ok(Some(frame)) => {
                    let samples = super::playback_inner::audio_frame_to_f32(&frame);
                    if !samples.is_empty() {
                        let mut guard = buf
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner);
                        let space = AUDIO_MAX_BUF.saturating_sub(guard.len());
                        guard.extend(samples.into_iter().take(space));
                    }
                }
                Ok(None) => break, // EOF
                Err(e) => {
                    log::warn!("audio decode error error={e}");
                    break;
                }
            }
        }
    })
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    fn test_video_path() -> std::path::PathBuf {
        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/video/gameplay.mp4")
    }

    fn test_audio_path() -> std::path::PathBuf {
        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../../assets/audio/konekonoosanpo.mp3")
    }

    // ── PreviewPlayer tests ───────────────────────────────────────────────────

    #[test]
    fn preview_player_open_should_fail_for_nonexistent_file() {
        let result = PreviewPlayer::open(Path::new("nonexistent_preview.mp4"));
        assert!(
            result.is_err(),
            "open() must return Err for a non-existent file"
        );
    }

    #[test]
    fn preview_player_play_pause_stop_should_update_state() {
        let path = test_video_path();
        let mut player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };

        // Initial state: not paused, not stopped.
        assert!(!player.paused.load(Ordering::Relaxed));
        assert!(!player.stopped.load(Ordering::Relaxed));

        player.pause();
        assert!(player.paused.load(Ordering::Relaxed));

        player.play();
        assert!(!player.paused.load(Ordering::Relaxed));
        assert!(!player.stopped.load(Ordering::Relaxed));

        player.stop();
        assert!(player.stopped.load(Ordering::Relaxed));
    }

    #[test]
    fn preview_player_run_should_deliver_frames_to_sink() {
        use std::sync::{Arc, Mutex};

        struct CountingSink(Arc<Mutex<usize>>);
        impl FrameSink for CountingSink {
            fn push_frame(&mut self, _rgba: &[u8], _width: u32, _height: u32, _pts: Duration) {
                *self
                    .0
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner) += 1;
            }
        }

        let path = test_video_path();
        let mut player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };

        let count = Arc::new(Mutex::new(0usize));
        player.set_sink(Box::new(CountingSink(Arc::clone(&count))));
        player.play();

        // run() blocks until EOF; short test file finishes quickly.
        match player.run() {
            Ok(()) => {}
            Err(e) => {
                println!("skipping: run() error: {e}");
                return;
            }
        }

        let frames = *count
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert!(
            frames > 0,
            "run() must deliver at least one frame to the sink"
        );
    }

    // ── pop_audio_samples tests ───────────────────────────────────────────────

    #[test]
    fn pop_audio_samples_should_return_empty_when_paused() {
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        player.pause();
        let samples = player.pop_audio_samples(1024);
        assert!(
            samples.is_empty(),
            "pop_audio_samples() must return empty while paused"
        );
    }

    #[test]
    fn pop_audio_samples_should_return_empty_when_stopped() {
        let path = test_video_path();
        let mut player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        player.stop();
        let samples = player.pop_audio_samples(1024);
        assert!(
            samples.is_empty(),
            "pop_audio_samples() must return empty while stopped"
        );
    }

    #[test]
    fn pop_audio_samples_should_return_empty_for_zero_n_samples() {
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        player.play();
        let samples = player.pop_audio_samples(0);
        assert!(
            samples.is_empty(),
            "pop_audio_samples(0) must always return empty"
        );
    }

    #[test]
    fn pause_handle_should_control_paused_flag_from_shared_reference() {
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        let handle = player.pause_handle();

        handle.store(true, Ordering::Release);
        assert!(
            player.paused.load(Ordering::Acquire),
            "handle must set paused flag"
        );

        handle.store(false, Ordering::Release);
        assert!(
            !player.paused.load(Ordering::Acquire),
            "handle must clear paused flag"
        );

        // Arc clone proves the thread-sharing pattern compiles.
        let cloned = Arc::clone(&handle);
        cloned.store(true, Ordering::Release);
        assert!(
            player.paused.load(Ordering::Acquire),
            "cloned handle must set paused flag"
        );
    }

    #[test]
    fn play_and_pause_should_be_callable_via_shared_reference() {
        // No `mut` binding — only possible with &self receivers.
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        player.pause();
        assert!(
            player.paused.load(Ordering::Relaxed),
            "pause() via &self must set paused flag"
        );
        player.play();
        assert!(
            !player.paused.load(Ordering::Relaxed),
            "play() via &self must clear paused flag"
        );
    }

    #[test]
    fn pop_audio_samples_should_be_callable_via_shared_reference() {
        // With &self receiver: works through an immutable binding and Arc<T>.
        // This is the compile-time proof that enables cpal-callback usage.
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        // No `mut` binding — only possible with a &self receiver.
        let samples = player.pop_audio_samples(0);
        assert!(samples.is_empty(), "pop_audio_samples(0) must return empty");

        // Via Arc — the canonical pattern for sharing with an audio callback.
        let shared = std::sync::Arc::new(player);
        let _samples = shared.pop_audio_samples(0);
    }

    #[test]
    fn pop_audio_samples_clock_increment_should_equal_half_sample_count() {
        // Verify the stereo-frame → clock-tick formula: n_samples / 2.
        // 9600 stereo samples at 48 kHz stereo = 4800 frames = 100 ms.
        let stereo_samples: usize = 9_600;
        let expected_frames: u64 = (stereo_samples / 2) as u64;
        assert_eq!(
            expected_frames, 4_800,
            "9600 stereo samples must yield 4800 clock frames"
        );
        // At 48 kHz, 4800 frames = 0.1 s.
        let pts = Duration::from_secs_f64(f64::from(48_000u32).recip() * expected_frames as f64);
        assert!(
            (pts.as_secs_f64() - 0.1).abs() < 1e-6,
            "4800 frames at 48 kHz must equal 100 ms; got {pts:?}"
        );
    }

    // ── current_pts / duration tests ─────────────────────────────────────────

    #[test]
    fn current_pts_should_return_zero_before_first_frame() {
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        assert_eq!(
            player.current_pts(),
            Duration::ZERO,
            "current_pts() must be ZERO before any frame is presented"
        );
    }

    #[test]
    fn duration_should_return_some_for_file_with_known_duration() {
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        assert!(
            player.duration().is_some(),
            "duration() must return Some for a file with a known container duration"
        );
        let d = player.duration().unwrap();
        assert!(
            d > Duration::ZERO,
            "duration() must be positive for a valid media file; got {d:?}"
        );
    }

    #[test]
    fn duration_should_return_none_when_duration_millis_is_sentinel() {
        // Verify the sentinel logic: u64::MAX → None.
        // We cannot easily get a live stream in a unit test, so we test the
        // conversion formula directly.
        let sentinel = u64::MAX;
        let result: Option<Duration> = if sentinel == u64::MAX {
            None
        } else {
            Some(Duration::from_millis(sentinel))
        };
        assert!(result.is_none(), "sentinel u64::MAX must map to None");

        // A valid value maps to Some.
        let valid = 5_000u64; // 5 seconds
        let result: Option<Duration> = if valid == u64::MAX {
            None
        } else {
            Some(Duration::from_millis(valid))
        };
        assert_eq!(result, Some(Duration::from_secs(5)));
    }

    #[test]
    fn current_pts_should_advance_after_frames_are_presented() {
        use std::sync::{Arc, Mutex};

        struct PtsSink(Arc<Mutex<Option<Duration>>>);
        impl FrameSink for PtsSink {
            fn push_frame(&mut self, _rgba: &[u8], _width: u32, _height: u32, pts: Duration) {
                let mut g = self
                    .0
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                *g = Some(pts);
            }
        }

        let path = test_video_path();
        let mut player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };

        let last_pts = Arc::new(Mutex::new(None::<Duration>));
        player.set_sink(Box::new(PtsSink(Arc::clone(&last_pts))));
        player.play();
        let _ = player.run();

        // After run() returns, current_pts() must be within 1 ms of the PTS
        // delivered to the sink. current_pts() stores millisecond precision, so
        // sub-millisecond differences between the stored and sink values are expected.
        let sink_pts = last_pts
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .unwrap_or(Duration::ZERO);
        let player_pts = player.current_pts();
        let diff = if player_pts >= sink_pts {
            player_pts - sink_pts
        } else {
            sink_pts - player_pts
        };
        assert!(
            diff <= Duration::from_millis(1),
            "current_pts() must be within 1 ms of the last sink PTS; \
             player_pts={player_pts:?} sink_pts={sink_pts:?} diff={diff:?}"
        );
    }

    // ── seek_coarse tests ─────────────────────────────────────────────────────

    #[test]
    fn seek_coarse_should_delegate_to_decode_buffer() {
        let path = test_video_path();
        let mut player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        // Consume a few frames so the decoder has advanced past the start.
        for _ in 0..3 {
            if matches!(player.pop_frame(), FrameResult::Eof) {
                println!("skipping: EOF before seek target");
                return;
            }
        }
        let target = Duration::from_secs(1);
        match player.seek_coarse(target) {
            Ok(()) => {}
            Err(e) => {
                println!("skipping: seek_coarse not supported or failed: {e}");
                return;
            }
        }
        // After a coarse seek the next frame must be available (not EOF).
        match player.pop_frame() {
            FrameResult::Frame(_) | FrameResult::Seeking(_) => {}
            FrameResult::Eof => panic!("pop_frame() returned Eof immediately after seek_coarse"),
        }
    }

    #[test]
    fn seek_coarse_should_be_faster_than_seek_for_same_target() {
        // Structural test: both methods must return Ok for the same target.
        // Timing comparison is environment-dependent and marked #[ignore].
        let path = test_video_path();
        let mut player_exact = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        let mut player_coarse = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };

        let target = Duration::from_secs(1);
        let exact_ok = player_exact.seek(target).is_ok();
        let coarse_ok = player_coarse.seek_coarse(target).is_ok();

        // Both must either succeed or fail (seek support depends on the codec).
        assert_eq!(
            exact_ok, coarse_ok,
            "seek() and seek_coarse() must both succeed or both fail for the same file"
        );
    }

    // ── av_offset_handle tests ────────────────────────────────────────────────

    #[test]
    fn av_offset_handle_should_control_offset_from_shared_reference() {
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        let handle = player.av_offset_handle();

        handle.store(300, Ordering::Relaxed);
        assert_eq!(
            player.av_offset(),
            300,
            "handle must update av_offset visible through av_offset()"
        );

        handle.store(-150, Ordering::Relaxed);
        assert_eq!(player.av_offset(), -150);

        // Arc clone proves the thread-sharing pattern compiles.
        let cloned = Arc::clone(&handle);
        cloned.store(500, Ordering::Relaxed);
        assert_eq!(
            player.av_offset(),
            500,
            "cloned handle must update av_offset"
        );
    }

    #[test]
    fn av_offset_handle_should_have_same_signature_as_stop_handle() {
        // Structural test: both methods must be callable on an immutable binding.
        // No `mut` — proves both return &self handles.
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        let _av: Arc<AtomicI64> = player.av_offset_handle();
        let _stop: Arc<AtomicBool> = player.stop_handle();
    }

    // ── A/V offset tests ──────────────────────────────────────────────────────

    #[test]
    fn av_offset_default_should_be_zero() {
        use std::sync::atomic::{AtomicI64, Ordering};
        // AtomicI64 default matches the expected API default of 0 ms.
        let offset = AtomicI64::new(0);
        assert_eq!(offset.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn set_av_offset_should_clamp_large_positive_value() {
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        player.set_av_offset(10_000);
        assert_eq!(player.av_offset(), 5_000, "offset must be clamped to +5000");
    }

    #[test]
    fn set_av_offset_should_clamp_large_negative_value() {
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        player.set_av_offset(-10_000);
        assert_eq!(
            player.av_offset(),
            -5_000,
            "offset must be clamped to -5000"
        );
    }

    #[test]
    fn positive_av_offset_should_reduce_adjusted_video_pts() {
        // Simulate the offset adjustment: positive offset subtracts from video_pts.
        let video_pts = Duration::from_millis(1_000);
        let offset_ms: i64 = 200;
        let adjusted = if offset_ms >= 0 {
            let offset = Duration::from_millis(offset_ms as u64);
            video_pts.saturating_sub(offset)
        } else {
            let offset = Duration::from_millis(offset_ms.unsigned_abs());
            video_pts + offset
        };
        assert_eq!(
            adjusted,
            Duration::from_millis(800),
            "positive offset must reduce adjusted_video_pts by offset amount"
        );
    }

    #[test]
    fn negative_av_offset_should_increase_adjusted_video_pts() {
        let video_pts = Duration::from_millis(1_000);
        let offset_ms: i64 = -200;
        let adjusted = if offset_ms >= 0 {
            let offset = Duration::from_millis(offset_ms as u64);
            video_pts.saturating_sub(offset)
        } else {
            let offset = Duration::from_millis(offset_ms.unsigned_abs());
            video_pts + offset
        };
        assert_eq!(
            adjusted,
            Duration::from_millis(1_200),
            "negative offset must increase adjusted_video_pts by offset amount"
        );
    }

    #[test]
    fn positive_av_offset_at_zero_pts_should_saturate_to_zero() {
        let video_pts = Duration::ZERO;
        let offset_ms: i64 = 100;
        let adjusted = video_pts.saturating_sub(Duration::from_millis(offset_ms as u64));
        assert_eq!(
            adjusted,
            Duration::ZERO,
            "saturating_sub on zero pts must clamp to zero not underflow"
        );
    }

    // ── use_proxy_if_available / active_source tests ──────────────────────────

    #[test]
    fn use_proxy_if_available_should_return_false_when_no_proxy_in_dir() {
        let path = test_video_path();
        let mut player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        let tmp = std::env::temp_dir().join("ff_preview_no_proxy_dir_test");
        let _ = std::fs::create_dir_all(&tmp);
        let found = player.use_proxy_if_available(&tmp);
        assert!(
            !found,
            "must return false when no proxy files exist in the directory"
        );
    }

    #[test]
    fn use_proxy_if_available_should_return_false_after_play() {
        let path = test_video_path();
        let mut player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        player.play();
        let found = player.use_proxy_if_available(Path::new("."));
        assert!(!found, "must return false when called after play()");
    }

    #[test]
    fn active_source_should_return_original_path_before_proxy_activation() {
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        assert_eq!(
            player.active_source(),
            path.as_path(),
            "active_source() must equal the original path before any proxy activation"
        );
    }

    // ── set_rate / rate_handle tests ──────────────────────────────────────────

    #[test]
    fn set_rate_should_update_rate_bits() {
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        // Default rate is 1.0.
        let default_rate = f64::from_bits(player.rate_bits.load(Ordering::Relaxed));
        assert!(
            (default_rate - 1.0).abs() < f64::EPSILON,
            "default rate must be 1.0; got {default_rate}"
        );

        player.set_rate(2.0);
        let rate = f64::from_bits(player.rate_bits.load(Ordering::Relaxed));
        assert!(
            (rate - 2.0).abs() < f64::EPSILON,
            "set_rate(2.0) must store 2.0; got {rate}"
        );

        player.set_rate(0.5);
        let rate = f64::from_bits(player.rate_bits.load(Ordering::Relaxed));
        assert!(
            (rate - 0.5).abs() < f64::EPSILON,
            "set_rate(0.5) must store 0.5; got {rate}"
        );
    }

    #[test]
    fn set_rate_should_ignore_non_positive_values() {
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        player.set_rate(2.0);

        // 0.0 must be a no-op.
        player.set_rate(0.0);
        let rate = f64::from_bits(player.rate_bits.load(Ordering::Relaxed));
        assert!(
            (rate - 2.0).abs() < f64::EPSILON,
            "set_rate(0.0) must be a no-op; rate must remain 2.0, got {rate}"
        );

        // Negative must also be a no-op.
        player.set_rate(-1.0);
        let rate = f64::from_bits(player.rate_bits.load(Ordering::Relaxed));
        assert!(
            (rate - 2.0).abs() < f64::EPSILON,
            "set_rate(-1.0) must be a no-op; rate must remain 2.0, got {rate}"
        );
    }

    #[test]
    fn rate_handle_should_return_shared_reference_to_rate_bits() {
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        let handle = player.rate_handle();

        handle.store(3.0_f64.to_bits(), Ordering::Relaxed);
        let rate = f64::from_bits(player.rate_bits.load(Ordering::Relaxed));
        assert!(
            (rate - 3.0).abs() < f64::EPSILON,
            "rate_handle() write must be visible through rate_bits; got {rate}"
        );

        // Arc clone proves the thread-sharing pattern compiles.
        let cloned = Arc::clone(&handle);
        cloned.store(0.25_f64.to_bits(), Ordering::Relaxed);
        let rate = f64::from_bits(player.rate_bits.load(Ordering::Relaxed));
        assert!(
            (rate - 0.25).abs() < f64::EPSILON,
            "cloned rate_handle write must be visible; got {rate}"
        );
    }

    #[test]
    fn set_rate_should_be_callable_via_shared_reference() {
        // No `mut` binding — proves &self receiver.
        let path = test_video_path();
        let player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: video file not available: {e}");
                return;
            }
        };
        player.set_rate(2.0);
        let rate_handle: Arc<AtomicU64> = player.rate_handle();
        let _ = rate_handle;
    }

    // ── audio-only tests ──────────────────────────────────────────────────────

    #[test]
    fn audio_only_open_should_succeed() {
        let path = test_audio_path();
        match PreviewPlayer::open(&path) {
            Ok(player) => {
                // Opened successfully; verify the player has no video decode buffer.
                assert!(
                    player.decode_buf.is_none(),
                    "audio-only player must have no video decode buffer"
                );
                // Audio buffer should be present.
                assert!(
                    player.audio_buf.is_some(),
                    "audio-only player must have an audio ring buffer"
                );
            }
            Err(e) => {
                println!("skipping: audio file not available: {e}");
            }
        }
    }

    #[test]
    fn audio_only_pop_frame_should_return_eof() {
        let path = test_audio_path();
        let mut player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: audio file not available: {e}");
                return;
            }
        };
        // For an audio-only player, pop_frame() must return Eof immediately.
        assert!(
            matches!(player.pop_frame(), FrameResult::Eof),
            "pop_frame() on an audio-only player must return Eof"
        );
    }

    #[test]
    fn audio_only_run_should_return_ok_without_video_frames() {
        let path = test_audio_path();
        let mut player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: audio file not available: {e}");
                return;
            }
        };

        // Count frames delivered to the sink — must remain zero for audio-only.
        struct CountingSink(usize);
        impl FrameSink for CountingSink {
            fn push_frame(&mut self, _rgba: &[u8], _w: u32, _h: u32, _pts: Duration) {
                self.0 += 1;
            }
        }
        player.set_sink(Box::new(CountingSink(0)));

        // Stop after 150 ms so the test doesn't block for the full audio duration.
        let stop = player.stop_handle();
        let _ = thread::spawn(move || {
            thread::sleep(Duration::from_millis(150));
            stop.store(true, Ordering::Release);
        });

        player.play();
        let result = player.run();
        assert!(
            result.is_ok(),
            "run() on an audio-only player must return Ok; got {result:?}"
        );
        // The sink should have received zero video frames.
        if let Some(sink) = player.sink.as_ref() {
            // Access the frame count via downcast is not available here, so we
            // verify indirectly: current_pts() stays at zero (no frames presented).
            let _ = sink;
        }
        assert_eq!(
            player.current_pts(),
            Duration::ZERO,
            "current_pts() must remain ZERO for audio-only playback (no video frames)"
        );
    }

    #[test]
    fn audio_only_seek_should_return_ok() {
        let path = test_audio_path();
        let mut player = match PreviewPlayer::open(&path) {
            Ok(p) => p,
            Err(e) => {
                println!("skipping: audio file not available: {e}");
                return;
            }
        };
        // seek() and seek_coarse() must return Ok(()) for audio-only files.
        assert!(
            player.seek(Duration::from_secs(1)).is_ok(),
            "seek() on audio-only player must return Ok"
        );
        assert!(
            player.seek_coarse(Duration::from_secs(1)).is_ok(),
            "seek_coarse() on audio-only player must return Ok"
        );
    }
}