wallr-core 0.6.1

Core library for wallr - wallpaper engine, GPU transitions, theme provider dispatch, and video playback.
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
use crate::video::error::{VideoError, VideoResult};
use crate::video::scheduler::ScheduledFrame;
use crossbeam_channel::{Receiver, SendTimeoutError, Sender};
use ffmpeg_next as ffmpeg;
use std::ffi::{CString, c_char};
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::thread;
use std::time::Duration;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HwAccel {
    /// Try all hardware backends in priority order, then software
    Auto,
    Vaapi,
    Nvdec,
    VideoToolbox,
    Software,
}

impl HwAccel {
    pub fn name(&self) -> &'static str {
        match self {
            HwAccel::Auto => "Auto",
            HwAccel::Vaapi => "VAAPI",
            HwAccel::Nvdec => "NVDEC",
            HwAccel::VideoToolbox => "VideoToolbox",
            HwAccel::Software => "Software",
        }
    }

    const fn code(self) -> u8 {
        match self {
            HwAccel::Auto => 0,
            HwAccel::Software => 1,
            HwAccel::Vaapi => 2,
            HwAccel::Nvdec => 3,
            HwAccel::VideoToolbox => 4,
        }
    }

    const fn from_code(code: u8) -> HwAccel {
        match code {
            2 => HwAccel::Vaapi,
            3 => HwAccel::Nvdec,
            4 => HwAccel::VideoToolbox,
            1 => HwAccel::Software,
            _ => HwAccel::Auto,
        }
    }

    pub fn from_config(value: &str) -> HwAccel {
        match value.trim().to_ascii_lowercase().as_str() {
            "vaapi" => HwAccel::Vaapi,
            "nvdec" | "nvidia" | "cuda" => HwAccel::Nvdec,
            "software" | "none" | "off" => HwAccel::Software,
            _ => HwAccel::Auto,
        }
    }

    /// Hardware backends in priority order for auto-detection, matched to
    /// the GPU actually present. Probing NVDEC on an AMD or iGPU machine
    /// makes FFmpeg attempt to load `libcuda.so.1` first, fail, and print a
    /// scary CUDA warning before ever reaching VAAPI; only NVIDIA hardware
    /// should ever touch the NVDEC path.
    #[cfg(target_os = "linux")]
    fn auto_hardware_order() -> Vec<HwAccel> {
        let mut order = Vec::new();
        if nvidia_gpu_present() {
            order.push(HwAccel::Nvdec);
        }
        if vaapi_available() {
            order.push(HwAccel::Vaapi);
        }
        order
    }
}

#[derive(Debug, Clone)]
pub struct VideoMetadata {
    pub width: u32,
    pub height: u32,
    pub duration: Duration,
    pub fps: f64,
    pub codec: String,
    pub format: String,
    pub total_frames: u64,
}

#[derive(Debug)]
pub enum VideoFrameData {
    Rgba(Vec<u8>),
    Nv12 {
        y_plane: Vec<u8>,
        uv_plane: Vec<u8>,
        color: YuvColorInfo,
    },
}

impl VideoFrameData {
    pub fn len(&self) -> usize {
        match self {
            Self::Rgba(data) => data.len(),
            Self::Nv12 {
                y_plane, uv_plane, ..
            } => y_plane.len() + uv_plane.len(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct YuvColorInfo {
    pub matrix: YuvMatrix,
    pub range: YuvRange,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum YuvMatrix {
    Bt601,
    Bt709,
    Bt2020,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum YuvRange {
    Limited,
    Full,
}

#[derive(Debug)]
pub struct VideoFrame {
    pub data: VideoFrameData,
    pub width: u32,
    pub height: u32,
    pub pts: Duration,
    pub index: u64,
}

impl VideoFrame {
    /// Move-only conversion into the scheduler representation. No frame
    /// bytes are cloned: ownership of the decoded planes transfers.
    pub fn into_scheduled(self) -> ScheduledFrame {
        ScheduledFrame::new(self.data, self.width, self.height, self.pts, self.index)
    }
}

#[derive(Debug, Clone)]
pub struct DecoderInfo {
    pub codec_name: String,
    pub hardware_accel: Option<String>,
    pub pixel_format: String,
}

#[derive(Debug, Clone, Copy)]
enum DecoderControl {
    Pause,
    Resume,
    Seek(Duration, u64),
}

pub struct VideoDecoder {
    metadata: VideoMetadata,
    frame_rx: Receiver<VideoFrame>,
    control_tx: Sender<DecoderControl>,
    stop_flag: Arc<AtomicBool>,
    seek_epoch: Arc<AtomicU64>,
    hw_in_use: Arc<AtomicU8>,
    decode_thread: Option<thread::JoinHandle<()>>,
}

impl VideoDecoder {
    pub fn new<P: AsRef<Path>>(path: P, hw_accel: HwAccel) -> VideoResult<Self> {
        Self::with_preload(path, hw_accel, 2, true)
    }

    pub fn with_preload<P: AsRef<Path>>(
        path: P,
        hw_accel: HwAccel,
        preload_frames: usize,
        loop_video: bool,
    ) -> VideoResult<Self> {
        let path = path.as_ref().to_path_buf();

        ensure_ffmpeg_init()?;

        let metadata = Self::extract_metadata(&path)?;

        tracing::info!(
            "Opened video: {}x{} @ {:.2} fps, duration: {:?}, codec: {}",
            metadata.width,
            metadata.height,
            metadata.fps,
            metadata.duration,
            metadata.codec
        );

        // Aggressively bounded decoded-frame queue: wallpaper playback never
        // needs a backlog. At most `preload` frames are in flight, plus one
        // pending frame in `VideoPlayback`. Stale frames are dropped by the
        // scheduler rather than preserved. All transfers are moves.
        let preload = preload_frames.clamp(1, 3);
        let (frame_tx, frame_rx) = crossbeam_channel::bounded(preload);
        let (control_tx, control_rx) = crossbeam_channel::unbounded();

        let stop_flag = Arc::new(AtomicBool::new(false));
        let stop_flag_clone = stop_flag.clone();
        let seek_epoch = Arc::new(AtomicU64::new(0));
        let seek_epoch_clone = seek_epoch.clone();
        let hw_in_use = Arc::new(AtomicU8::new(0));
        let hw_in_use_clone = hw_in_use.clone();

        let decode_thread = thread::Builder::new()
            .name("wallr-video-decoder".to_string())
            .spawn(move || {
                let used = Self::decode_loop(
                    path,
                    hw_accel,
                    frame_tx,
                    control_rx,
                    stop_flag_clone,
                    seek_epoch_clone,
                    hw_in_use_clone.clone(),
                    loop_video,
                );
                let used = match used {
                    Ok(used) => used,
                    Err(e) => {
                        tracing::error!("Video decode loop: {}", e);
                        HwAccel::Software
                    }
                };
                tracing::info!("Decode thread exited (backend: {})", used.name());
                // Update again on exit in case it wasn't set during init
                hw_in_use_clone.store(used.code(), Ordering::Relaxed);
            })
            .map_err(|e| VideoError::SoftwareDecoderInit(e.into()))?;

        Ok(Self {
            metadata,
            frame_rx,
            control_tx,
            stop_flag,
            seek_epoch,
            hw_in_use,
            decode_thread: Some(decode_thread),
        })
    }

    fn extract_metadata(path: &Path) -> VideoResult<VideoMetadata> {
        let ictx = ffmpeg::format::input(&path).map_err(|e| VideoError::FileOpen {
            path: path.to_path_buf(),
            source: std::io::Error::other(e.to_string()),
        })?;

        let stream = ictx
            .streams()
            .best(ffmpeg::media::Type::Video)
            .ok_or_else(|| VideoError::NoVideoStream(path.to_path_buf()))?;

        let decoder = ffmpeg::codec::context::Context::from_parameters(stream.parameters())
            .and_then(|ctx| ctx.decoder().video())
            .map_err(|e| VideoError::SoftwareDecoderInit(e.into()))?;

        let width = decoder.width();
        let height = decoder.height();
        let codec = decoder
            .codec()
            .map(|c| c.name().to_string())
            .unwrap_or_else(|| "unknown".to_string());

        let frame_rate = stream.avg_frame_rate();
        let fps = if frame_rate.numerator() > 0 {
            frame_rate.numerator() as f64 / frame_rate.denominator() as f64
        } else {
            30.0
        };

        let duration = {
            let duration_ts = stream.duration();
            let time_base = stream.time_base();
            if duration_ts > 0 {
                Duration::from_secs_f64(
                    duration_ts as f64 * time_base.numerator() as f64
                        / time_base.denominator() as f64,
                )
            } else {
                let container_duration = ictx.duration() as f64 / ffmpeg::ffi::AV_TIME_BASE as f64;
                Duration::from_secs_f64(container_duration)
            }
        };

        let total_frames = if fps > 0.0 {
            (duration.as_secs_f64() * fps) as u64
        } else {
            0
        };

        Ok(VideoMetadata {
            width,
            height,
            duration,
            fps,
            codec,
            format: ictx.format().name().to_string(),
            total_frames,
        })
    }

    fn init_hw_device(hw_accel: HwAccel) -> Option<(*mut ffmpeg::ffi::AVBufferRef, &'static str)> {
        // VA-API render nodes are enumerated instead of hardcoding
        // renderD128 so multi-GPU systems use the first working node and
        // stay on the same physical GPU as the compositor where possible.
        // NVDEC keeps its device index; VideoToolbox needs no device string.
        if hw_accel == HwAccel::Vaapi {
            return Self::init_vaapi_device();
        }
        let (type_name, device) = match hw_accel {
            HwAccel::Nvdec => ("cuda", Some(c"0")),
            HwAccel::VideoToolbox => ("videotoolbox", None),
            HwAccel::Software | HwAccel::Auto | HwAccel::Vaapi => return None,
        };

        let type_name_c = CString::new(type_name).ok()?;

        // SAFETY: C strings passed to FFmpeg; returned device ctx owned by codec context.
        unsafe {
            let hw_type = ffmpeg::ffi::av_hwdevice_find_type_by_name(type_name_c.as_ptr());
            if hw_type == ffmpeg::ffi::AVHWDeviceType::AV_HWDEVICE_TYPE_NONE {
                tracing::warn!("{} hardware type unavailable", hw_accel.name());
                return None;
            }

            let mut device_ctx: *mut ffmpeg::ffi::AVBufferRef = std::ptr::null_mut();
            let device_ptr: *const c_char = device.map(|d| d.as_ptr()).unwrap_or(std::ptr::null());
            let ret = ffmpeg::ffi::av_hwdevice_ctx_create(
                &mut device_ctx,
                hw_type,
                device_ptr,
                std::ptr::null_mut(),
                0,
            );
            if ret < 0 || device_ctx.is_null() {
                tracing::warn!("{} device init failed ({})", hw_accel.name(), ret);
                return None;
            }
            Some((device_ctx, type_name))
        }
    }

    fn init_vaapi_device() -> Option<(*mut ffmpeg::ffi::AVBufferRef, &'static str)> {
        let type_name_c = CString::new("vaapi").ok()?;
        // SAFETY: read-only FFmpeg type lookup with a valid C string.
        let hw_type = unsafe { ffmpeg::ffi::av_hwdevice_find_type_by_name(type_name_c.as_ptr()) };
        if hw_type == ffmpeg::ffi::AVHWDeviceType::AV_HWDEVICE_TYPE_NONE {
            tracing::warn!("VAAPI hardware type unavailable");
            return None;
        }
        for candidate in vaapi_device_candidates() {
            // SAFETY: candidate is a valid NUL-terminated path; the returned
            // device ctx is owned by the codec context on success.
            let result = unsafe {
                let mut device_ctx: *mut ffmpeg::ffi::AVBufferRef = std::ptr::null_mut();
                let ret = ffmpeg::ffi::av_hwdevice_ctx_create(
                    &mut device_ctx,
                    hw_type,
                    candidate.as_ptr(),
                    std::ptr::null_mut(),
                    0,
                );
                if ret < 0 || device_ctx.is_null() {
                    None
                } else {
                    Some((device_ctx, "vaapi"))
                }
            };
            if result.is_some() {
                return result;
            }
        }
        tracing::warn!("VAAPI device init failed on all render nodes");
        None
    }

    /// Try to build a decoder with a hardware device context attached.
    fn try_hw_decoder(
        stream: &ffmpeg::format::stream::Stream,
        hw_accel: HwAccel,
    ) -> Option<(ffmpeg::codec::decoder::Video, HwAccel)> {
        let (device_ctx, _) = Self::init_hw_device(hw_accel)?;

        let mut context =
            ffmpeg::codec::context::Context::from_parameters(stream.parameters()).ok()?;

        // SAFETY: device_ctx is a valid FFmpeg allocation; the codec context
        // unrefs it when dropped.
        unsafe {
            (*context.as_mut_ptr()).hw_device_ctx = device_ctx;
        }

        match context.decoder().video() {
            Ok(decoder) => {
                tracing::info!("Hardware decode active: {}", hw_accel.name());
                Some((decoder, hw_accel))
            }
            Err(e) => {
                tracing::warn!("{} decode init failed: {}", hw_accel.name(), e);
                None
            }
        }
    }

    /// Build a decoder with appropriate hardware acceleration fallback.
    ///
    /// - Auto: Try all hardware backends in priority order, then software
    /// - Explicit backend (Vaapi, Nvdec, VideoToolbox): Try that backend, then software
    /// - Software: Use software decoder only (no hardware attempts)
    fn build_decoder(
        stream: &ffmpeg::format::stream::Stream,
        hw_accel: HwAccel,
    ) -> (ffmpeg::codec::decoder::Video, HwAccel) {
        match hw_accel {
            HwAccel::Auto => {
                // Probe only what this machine can actually use, in
                // vendor-matched priority: NVDEC for NVIDIA hardware, VAAPI
                // for everything else with a render node. Never probe NVDEC
                // on AMD/iGPU machines (that makes FFmpeg try to load
                // libcuda.so.1, print a CUDA error, then fall through).
                let mut tried = 0;
                for backend in HwAccel::auto_hardware_order() {
                    tried += 1;
                    if let Some(result) = Self::try_hw_decoder(stream, backend) {
                        return result;
                    }
                }
                if tried == 0 {
                    tracing::info!("No hardware decoder present, using software decoder");
                } else {
                    tracing::info!("Hardware decoders failed, using software decoder");
                }
            }
            HwAccel::Software => {
                // Explicit software request: skip hardware entirely
                tracing::info!("Software decoder explicitly requested");
            }
            specific => {
                // Try the requested hardware backend first
                if let Some(result) = Self::try_hw_decoder(stream, specific) {
                    return result;
                }
                // Fall back to software
                tracing::info!(
                    "{} hardware decoder failed, falling back to software",
                    specific.name()
                );
            }
        }

        // Software fallback.
        let decoder = ffmpeg::codec::context::Context::from_parameters(stream.parameters())
            .and_then(|ctx| ctx.decoder().video())
            .expect("software decoder must be available");
        (decoder, HwAccel::Software)
    }

    #[allow(clippy::too_many_arguments)]
    fn decode_loop(
        path: std::path::PathBuf,
        hw_accel: HwAccel,
        frame_tx: Sender<VideoFrame>,
        control_rx: Receiver<DecoderControl>,
        stop_flag: Arc<AtomicBool>,
        seek_epoch: Arc<AtomicU64>,
        hw_in_use: Arc<AtomicU8>,
        loop_video: bool,
    ) -> VideoResult<HwAccel> {
        let mut ictx = ffmpeg::format::input(&path).map_err(|e| VideoError::FileOpen {
            path: path.clone(),
            source: std::io::Error::other(e.to_string()),
        })?;

        let stream = ictx
            .streams()
            .best(ffmpeg::media::Type::Video)
            .ok_or_else(|| VideoError::NoVideoStream(path.clone()))?;

        let video_stream_index = stream.index();
        let time_base = stream.time_base();

        let (mut decoder, used_hw) = Self::build_decoder(&stream, hw_accel);
        tracing::info!("Decoder in use: {}", used_hw.name());

        // Report the active backend immediately after successful initialization
        hw_in_use.store(used_hw.code(), Ordering::Relaxed);

        let mut scaler: Option<ffmpeg::software::scaling::Context> = None;
        let mut scaler_src: Option<ffmpeg::format::Pixel> = None;

        let mut paused = false;
        let mut pending_seek: Option<(Duration, u64)> = None;
        let mut applied_seek_epoch = 0;
        let mut frame_index = 0u64;
        let mut decoded_frame = ffmpeg::frame::Video::empty();
        let mut sw_frame = ffmpeg::frame::Video::empty();
        let mut rgb_frame = ffmpeg::frame::Video::empty();

        'outer: loop {
            if stop_flag.load(Ordering::Relaxed) {
                break;
            }

            while let Ok(control) = control_rx.try_recv() {
                match control {
                    DecoderControl::Pause => paused = true,
                    DecoderControl::Resume => paused = false,
                    DecoderControl::Seek(ts, epoch) => pending_seek = Some((ts, epoch)),
                }
            }

            if let Some((ts, epoch)) = pending_seek.take() {
                Self::apply_seek(&mut ictx, &mut decoder, time_base, ts);
                applied_seek_epoch = epoch;
            }

            if paused {
                thread::sleep(Duration::from_millis(10));
                continue;
            }

            for (stream, packet) in ictx.packets() {
                if stop_flag.load(Ordering::Relaxed) {
                    break 'outer;
                }

                while let Ok(control) = control_rx.try_recv() {
                    match control {
                        DecoderControl::Pause => paused = true,
                        DecoderControl::Resume => paused = false,
                        DecoderControl::Seek(ts, epoch) => pending_seek = Some((ts, epoch)),
                    }
                }
                if paused || pending_seek.is_some() {
                    break;
                }

                if stream.index() != video_stream_index {
                    continue;
                }

                // A corrupt or transiently unreadable packet must not end
                // wallpaper playback: skip it and keep decoding. Previously a
                // single `send_packet` error terminated the thread, silently
                // freezing the video forever.
                if let Err(e) = decoder.send_packet(&packet) {
                    tracing::warn!("video packet skipped: {e}");
                    continue;
                }

                while decoder.receive_frame(&mut decoded_frame).is_ok() {
                    if stop_flag.load(Ordering::Relaxed) {
                        break 'outer;
                    }

                    // Apply backpressure before GPU readback and color
                    // conversion, retaining this decoded frame across pause.
                    let mut interrupted = false;
                    loop {
                        if stop_flag.load(Ordering::Relaxed) {
                            break 'outer;
                        }
                        while let Ok(control) = control_rx.try_recv() {
                            match control {
                                DecoderControl::Pause => paused = true,
                                DecoderControl::Resume => paused = false,
                                DecoderControl::Seek(ts, epoch) => {
                                    pending_seek = Some((ts, epoch));
                                }
                            }
                        }
                        if pending_seek.is_some()
                            || seek_epoch.load(Ordering::Acquire) != applied_seek_epoch
                        {
                            interrupted = true;
                            break;
                        }
                        if !paused && !frame_tx.is_full() {
                            break;
                        }
                        // The queue is intentionally bounded. Avoid a 1 ms
                        // busy-poll when the consumer/GPU is behind or when
                        // playback is paused; 2 ms still keeps seek/pause
                        // control responsive while cutting wakeups in half.
                        thread::sleep(Duration::from_millis(2));
                    }
                    if interrupted {
                        break;
                    }

                    let is_hw_frame = unsafe { !(*decoded_frame.as_ptr()).hw_frames_ctx.is_null() };

                    let src_frame = if is_hw_frame {
                        let ret = unsafe {
                            ffmpeg::ffi::av_frame_unref(sw_frame.as_mut_ptr());
                            ffmpeg::ffi::av_hwframe_transfer_data(
                                sw_frame.as_mut_ptr(),
                                decoded_frame.as_ptr(),
                                0,
                            )
                        };
                        if ret < 0 {
                            tracing::warn!("hwframe transfer failed: {ret}");
                            continue;
                        }
                        &sw_frame
                    } else {
                        &decoded_frame
                    };

                    let pts_duration = if let Some(pts) = decoded_frame.timestamp() {
                        Duration::from_secs_f64(
                            pts as f64 * time_base.numerator() as f64
                                / time_base.denominator() as f64,
                        )
                    } else {
                        Duration::from_secs_f64(frame_index as f64 / 30.0)
                    };

                    let width = src_frame.width();
                    let height = src_frame.height();
                    // Conversion failures (unexpected pixel format, hardware
                    // readback hiccup) skip the frame instead of killing the
                    // decode thread. Previous behavior froze playback forever
                    // on the first hiccup.
                    let data = match convert_frame(
                        src_frame,
                        &decoded_frame,
                        &mut scaler,
                        &mut scaler_src,
                        &mut rgb_frame,
                        width,
                        height,
                        &decoder,
                    ) {
                        Ok(data) => data,
                        Err(e) => {
                            tracing::warn!("video frame conversion skipped: {e}");
                            continue;
                        }
                    };

                    let video_frame = VideoFrame {
                        data,
                        width,
                        height,
                        pts: pts_duration,
                        index: frame_index,
                    };
                    frame_index = frame_index.wrapping_add(1);

                    match frame_tx.send_timeout(video_frame, Duration::from_millis(20)) {
                        Ok(()) => {}
                        Err(SendTimeoutError::Timeout(_)) => break,
                        Err(SendTimeoutError::Disconnected(_)) => {
                            tracing::warn!("Frame queue disconnected, ending decode loop");
                            return Ok(used_hw);
                        }
                    }
                }
            }

            tracing::debug!("End of stream after {} frames, looping", frame_index);
            while decoder.receive_frame(&mut decoded_frame).is_ok() {
                if stop_flag.load(Ordering::Relaxed) {
                    break 'outer;
                }
            }
            if stop_flag.load(Ordering::Relaxed) {
                break;
            }
            if loop_video && !paused {
                ictx.seek(0, ..)
                    .map_err(|e| VideoError::SeekFailed(Duration::ZERO, e.into()))?;
                decoder.flush();
            } else if !paused {
                // Reached the end without looping (single play-through).
                // Stay parked so pause/seek/stop still work, and a later
                // seek restarts the stream from the requested position.
                thread::sleep(Duration::from_millis(50));
            }
        }

        Ok(used_hw)
    }

    fn apply_seek(
        ictx: &mut ffmpeg::format::context::Input,
        decoder: &mut ffmpeg::codec::decoder::Video,
        time_base: ffmpeg::Rational,
        ts: Duration,
    ) {
        let tb_sec = time_base.numerator() as f64 / time_base.denominator() as f64;
        let ts_tb = if tb_sec > 0.0 {
            (ts.as_secs_f64() / tb_sec) as i64
        } else {
            0
        };
        match ictx.seek(ts_tb, ..) {
            Ok(()) => {
                decoder.flush();
                let mut drain = ffmpeg::frame::Video::empty();
                while decoder.receive_frame(&mut drain).is_ok() {}
                tracing::info!("Seeked to {:?}", ts);
            }
            Err(e) => tracing::warn!("Seek to {:?} failed: {}", ts, e),
        }
    }

    pub fn next_frame(&self) -> Option<VideoFrame> {
        self.frame_rx.try_recv().ok()
    }

    pub fn metadata(&self) -> &VideoMetadata {
        &self.metadata
    }

    pub fn decoder_info(&self) -> DecoderInfo {
        DecoderInfo {
            codec_name: self.metadata.codec.clone(),
            hardware_accel: if self.hw_accel_in_use() != HwAccel::Software {
                Some(self.hw_accel_in_use().name().to_string())
            } else {
                None
            },
            pixel_format: "NV12/RGBA".to_string(),
        }
    }

    pub fn hw_accel_in_use(&self) -> HwAccel {
        for _ in 0..50 {
            let code = self.hw_in_use.load(Ordering::Relaxed);
            if code != 0 {
                return HwAccel::from_code(code);
            }
            std::thread::sleep(Duration::from_millis(5));
        }
        HwAccel::Software
    }

    pub fn pause(&self) {
        let _ = self.control_tx.send(DecoderControl::Pause);
    }

    pub fn resume(&self) {
        let _ = self.control_tx.send(DecoderControl::Resume);
    }

    pub fn seek(&self, timestamp: Duration) {
        let epoch = self.seek_epoch.fetch_add(1, Ordering::AcqRel) + 1;
        let _ = self.control_tx.send(DecoderControl::Seek(timestamp, epoch));
    }

    pub fn drain(&mut self) {
        while self.frame_rx.try_recv().is_ok() {}
    }

    pub fn is_video_file<P: AsRef<Path>>(path: P) -> bool {
        path.as_ref()
            .extension()
            .and_then(|e| e.to_str())
            .is_some_and(|ext| {
                matches!(
                    ext.to_lowercase().as_str(),
                    "mp4" | "webm" | "mkv" | "mov" | "avi" | "m4v"
                )
            })
    }
}

fn ensure_ffmpeg_init() -> VideoResult<()> {
    use std::sync::OnceLock;
    static INIT: OnceLock<Result<(), String>> = OnceLock::new();
    let result = INIT.get_or_init(|| {
        ffmpeg::init().map_err(|e| format!("FFmpeg init: {e}"))?;
        // Metadata extraction opens the input once on the calling thread so
        // a failed video never replaces active playback; the decode thread
        // then opens it a second time for the actual stream. The two opens
        // are intentional: the first validates cheaply before committing.
        Ok(())
    });
    result
        .as_ref()
        .map_err(|e| VideoError::SoftwareDecoderInit(anyhow::anyhow!(e.clone())))
        .map(|_| ())
}

/// True when any `/sys/class/drm/card*` sibling reports NVIDIA vendor 0x10de.
fn nvidia_gpu_present() -> bool {
    any_nvidia_card(std::path::Path::new("/sys/class/drm"))
}

fn any_nvidia_card(root: &std::path::Path) -> bool {
    let Ok(entries) = std::fs::read_dir(root) else {
        return false;
    };
    entries.filter_map(|e| e.ok()).any(|entry| {
        let name = entry.file_name().to_string_lossy().into_owned();
        if !name.starts_with("card") {
            return false;
        }
        std::fs::read_to_string(entry.path().join("device/vendor"))
            .is_ok_and(|vendor| vendor.trim().eq_ignore_ascii_case("0x10de"))
    })
}

/// True when a usable DRM render node exists (`/dev/dri/renderD*`).
fn vaapi_available() -> bool {
    any_render_node(std::path::Path::new("/dev/dri"))
}

fn any_render_node(root: &std::path::Path) -> bool {
    let Ok(entries) = std::fs::read_dir(root) else {
        return false;
    };
    entries
        .filter_map(|e| e.ok())
        .any(|entry| entry.file_name().to_string_lossy().starts_with("renderD"))
}

/// VA-API render-node candidates in probe order. Enumerates
/// `/dev/dri/renderD*` so hybrid/multi-GPU systems try every node instead
/// of assuming renderD128; falls back to renderD128 when enumeration fails.
fn vaapi_device_candidates() -> Vec<CString> {
    let mut candidates = Vec::new();
    if let Ok(entries) = std::fs::read_dir("/dev/dri") {
        let mut nodes: Vec<String> = entries
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|n| n.starts_with("renderD"))
            .collect();
        nodes.sort();
        for node in nodes {
            let path = format!("/dev/dri/{node}");
            if let Ok(c) = CString::new(path) {
                candidates.push(c);
            }
        }
    }
    if candidates.is_empty()
        && let Ok(fallback) = CString::new("/dev/dri/renderD128")
    {
        candidates.push(fallback);
    }
    candidates
}

fn copy_packed_rows(source: &[u8], stride: usize, row_bytes: usize, height: usize) -> Vec<u8> {
    let mut packed = Vec::with_capacity(row_bytes * height);
    for row in source.chunks(stride).take(height) {
        packed.extend_from_slice(&row[..row_bytes]);
    }
    packed
}

/// Converts a decoded frame into `VideoFrameData`, keeping NV12 on the GPU
/// path when the decoder produced it natively and falling back to a software
/// RGBA conversion for anything else.
#[allow(clippy::too_many_arguments)]
fn convert_frame(
    src_frame: &ffmpeg::frame::Video,
    decoded_frame: &ffmpeg::frame::Video,
    scaler: &mut Option<ffmpeg::software::scaling::Context>,
    scaler_src: &mut Option<ffmpeg::format::Pixel>,
    rgb_frame: &mut ffmpeg::frame::Video,
    width: u32,
    height: u32,
    decoder: &ffmpeg::codec::decoder::Video,
) -> VideoResult<VideoFrameData> {
    if src_frame.format() == ffmpeg::format::Pixel::NV12 {
        let color_space = match decoded_frame.color_space() {
            ffmpeg::color::Space::Unspecified => decoder.color_space(),
            value => value,
        };
        let color_range = match decoded_frame.color_range() {
            ffmpeg::color::Range::Unspecified => decoder.color_range(),
            value => value,
        };
        let color = select_yuv_color(color_space, color_range, width, height);
        let (y_plane, uv_plane) = copy_nv12_planes(src_frame);
        Ok(VideoFrameData::Nv12 {
            y_plane,
            uv_plane,
            color,
        })
    } else {
        let src_format = src_frame.format();
        if *scaler_src != Some(src_format) {
            *scaler = Some(
                ffmpeg::software::scaling::context::Context::get(
                    src_format,
                    width,
                    height,
                    ffmpeg::format::Pixel::RGBA,
                    width,
                    height,
                    ffmpeg::software::scaling::Flags::BILINEAR,
                )
                .map_err(|e| VideoError::FormatConversionFailed(e.into()))?,
            );
            *scaler_src = Some(src_format);
        }

        scaler
            .as_mut()
            .expect("scaler initialized above")
            .run(src_frame, rgb_frame)
            .map_err(|e| VideoError::FormatConversionFailed(e.into()))?;
        Ok(VideoFrameData::Rgba(copy_packed_rows(
            rgb_frame.data(0),
            rgb_frame.stride(0),
            rgb_frame.width() as usize * 4,
            rgb_frame.height() as usize,
        )))
    }
}

fn copy_nv12_planes(frame: &ffmpeg::frame::Video) -> (Vec<u8>, Vec<u8>) {
    copy_nv12_data(
        frame.data(0),
        frame.stride(0),
        frame.data(1),
        frame.stride(1),
        frame.width() as usize,
        frame.height() as usize,
    )
}

fn copy_nv12_data(
    y_source: &[u8],
    y_stride: usize,
    uv_source: &[u8],
    uv_stride: usize,
    width: usize,
    height: usize,
) -> (Vec<u8>, Vec<u8>) {
    let chroma_width = width.div_ceil(2);
    let chroma_height = height.div_ceil(2);
    (
        copy_packed_rows(y_source, y_stride, width, height),
        copy_packed_rows(uv_source, uv_stride, chroma_width * 2, chroma_height),
    )
}

fn select_yuv_color(
    space: ffmpeg::color::Space,
    range: ffmpeg::color::Range,
    width: u32,
    height: u32,
) -> YuvColorInfo {
    let matrix = match space {
        ffmpeg::color::Space::BT470BG | ffmpeg::color::Space::SMPTE170M => YuvMatrix::Bt601,
        ffmpeg::color::Space::BT709 => YuvMatrix::Bt709,
        ffmpeg::color::Space::BT2020NCL => YuvMatrix::Bt2020,
        _ if width >= 1280 || height > 576 => YuvMatrix::Bt709,
        _ => YuvMatrix::Bt601,
    };
    let range = match range {
        ffmpeg::color::Range::JPEG => YuvRange::Full,
        ffmpeg::color::Range::MPEG | ffmpeg::color::Range::Unspecified => YuvRange::Limited,
    };
    YuvColorInfo { matrix, range }
}

impl Drop for VideoDecoder {
    fn drop(&mut self) {
        self.stop_flag.store(true, Ordering::Relaxed);
        if let Some(thread) = self.decode_thread.take() {
            let _ = thread.join();
        }
    }
}

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

    #[test]
    fn nvidia_probe_detects_vendor_via_sysfs_layout() {
        let temp = tempfile::tempdir().expect("tempdir");
        let card0 = temp.path().join("card0");
        let card1 = temp.path().join("card1");

        std::fs::create_dir_all(card0.join("device")).expect("dirs");
        std::fs::create_dir_all(card1.join("device")).expect("dirs");
        assert!(!any_nvidia_card(temp.path()));

        std::fs::write(card1.join("device/vendor"), "0x10de\n").expect("vendor");
        assert!(any_nvidia_card(temp.path()));

        std::fs::write(card1.join("device/vendor"), "0x1002\n").expect("vendor");
        assert!(!any_nvidia_card(temp.path()));
    }

    #[test]
    fn render_node_probe_detects_render_entries() {
        let temp = tempfile::tempdir().expect("tempdir");
        assert!(!any_render_node(temp.path()));
        std::fs::create_dir_all(temp.path().join("renderD128")).expect("create");
        assert!(any_render_node(temp.path()));
    }

    #[test]
    fn test_is_video_file() {
        assert!(VideoDecoder::is_video_file("test.mp4"));
        assert!(VideoDecoder::is_video_file("test.MP4"));
        assert!(VideoDecoder::is_video_file("test.webm"));
        assert!(VideoDecoder::is_video_file("test.mkv"));
        assert!(VideoDecoder::is_video_file("test.mov"));
        assert!(!VideoDecoder::is_video_file("test.jpg"));
        assert!(!VideoDecoder::is_video_file("test.gif"));
        assert!(!VideoDecoder::is_video_file("test.png"));
    }

    #[test]
    fn test_hwaccel_names() {
        assert_eq!(HwAccel::Vaapi.name(), "VAAPI");
        assert_eq!(HwAccel::Nvdec.name(), "NVDEC");
        assert_eq!(HwAccel::Software.name(), "Software");
    }

    #[test]
    fn test_hwaccel_codes_roundtrip() {
        for accel in [
            HwAccel::Software,
            HwAccel::Vaapi,
            HwAccel::Nvdec,
            HwAccel::VideoToolbox,
        ] {
            assert_eq!(HwAccel::from_code(accel.code()), accel);
        }
    }

    #[test]
    fn test_hwaccel_from_config() {
        assert_eq!(HwAccel::from_config("vaapi"), HwAccel::Vaapi);
        assert_eq!(HwAccel::from_config("nvdec"), HwAccel::Nvdec);
        assert_eq!(HwAccel::from_config("software"), HwAccel::Software);
        assert_eq!(HwAccel::from_config("auto"), HwAccel::Auto);
        assert_eq!(HwAccel::from_config("unknown"), HwAccel::Auto);
    }

    #[test]
    fn packs_strided_rows() {
        let y = [1, 2, 3, 99, 99, 4, 5, 6, 99, 99, 7, 8, 9, 99, 99];
        let uv = [10, 11, 12, 13, 99, 99, 14, 15, 16, 17, 99, 99];
        let (packed_y, packed_uv) = copy_nv12_data(&y, 5, &uv, 6, 3, 3);
        assert_eq!(packed_y, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
        assert_eq!(packed_uv, [10, 11, 12, 13, 14, 15, 16, 17]);
    }

    #[test]
    fn selects_yuv_matrix_and_range() {
        assert_eq!(
            select_yuv_color(
                ffmpeg::color::Space::BT2020NCL,
                ffmpeg::color::Range::JPEG,
                3840,
                2160,
            ),
            YuvColorInfo {
                matrix: YuvMatrix::Bt2020,
                range: YuvRange::Full,
            }
        );
        assert_eq!(
            select_yuv_color(
                ffmpeg::color::Space::Unspecified,
                ffmpeg::color::Range::Unspecified,
                1920,
                1080,
            ),
            YuvColorInfo {
                matrix: YuvMatrix::Bt709,
                range: YuvRange::Limited,
            }
        );
        assert_eq!(
            select_yuv_color(
                ffmpeg::color::Space::Unspecified,
                ffmpeg::color::Range::MPEG,
                720,
                576,
            ),
            YuvColorInfo {
                matrix: YuvMatrix::Bt601,
                range: YuvRange::Limited,
            }
        );
    }
}