Skip to main content

wallr_core/video/
decoder.rs

1use crate::video::error::{VideoError, VideoResult};
2use crate::video::scheduler::ScheduledFrame;
3use crossbeam_channel::{Receiver, SendTimeoutError, Sender};
4use ffmpeg_next as ffmpeg;
5use std::ffi::{CString, c_char};
6use std::path::Path;
7use std::sync::Arc;
8use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
9use std::thread;
10use std::time::Duration;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum HwAccel {
14    /// Try all hardware backends in priority order, then software
15    Auto,
16    Vaapi,
17    Nvdec,
18    VideoToolbox,
19    Software,
20}
21
22impl HwAccel {
23    pub fn name(&self) -> &'static str {
24        match self {
25            HwAccel::Auto => "Auto",
26            HwAccel::Vaapi => "VAAPI",
27            HwAccel::Nvdec => "NVDEC",
28            HwAccel::VideoToolbox => "VideoToolbox",
29            HwAccel::Software => "Software",
30        }
31    }
32
33    const fn code(self) -> u8 {
34        match self {
35            HwAccel::Auto => 0,
36            HwAccel::Software => 1,
37            HwAccel::Vaapi => 2,
38            HwAccel::Nvdec => 3,
39            HwAccel::VideoToolbox => 4,
40        }
41    }
42
43    const fn from_code(code: u8) -> HwAccel {
44        match code {
45            2 => HwAccel::Vaapi,
46            3 => HwAccel::Nvdec,
47            4 => HwAccel::VideoToolbox,
48            1 => HwAccel::Software,
49            _ => HwAccel::Auto,
50        }
51    }
52
53    pub fn from_config(value: &str) -> HwAccel {
54        match value.trim().to_ascii_lowercase().as_str() {
55            "vaapi" => HwAccel::Vaapi,
56            "nvdec" | "nvidia" | "cuda" => HwAccel::Nvdec,
57            "software" | "none" | "off" => HwAccel::Software,
58            _ => HwAccel::Auto,
59        }
60    }
61
62    /// All hardware backends in priority order for auto-detection fallback.
63    /// NVDEC preferred on Linux (common primary GPU on hybrid systems),
64    /// then VAAPI, then VideoToolbox on macOS.
65    fn all_hardware() -> &'static [HwAccel] {
66        &[HwAccel::Nvdec, HwAccel::Vaapi, HwAccel::VideoToolbox]
67    }
68}
69
70#[derive(Debug, Clone)]
71pub struct VideoMetadata {
72    pub width: u32,
73    pub height: u32,
74    pub duration: Duration,
75    pub fps: f64,
76    pub codec: String,
77    pub format: String,
78    pub total_frames: u64,
79}
80
81#[derive(Debug, Clone)]
82pub struct VideoFrame {
83    pub data: Vec<u8>,
84    pub width: u32,
85    pub height: u32,
86    pub pts: Duration,
87    pub index: u64,
88}
89
90impl VideoFrame {
91    pub fn into_scheduled(self) -> ScheduledFrame {
92        ScheduledFrame::new(self.data, self.width, self.height, self.pts, self.index)
93    }
94}
95
96#[derive(Debug, Clone)]
97pub struct DecoderInfo {
98    pub codec_name: String,
99    pub hardware_accel: Option<String>,
100    pub pixel_format: String,
101}
102
103#[derive(Debug, Clone, Copy)]
104enum DecoderControl {
105    Pause,
106    Resume,
107    Seek(Duration),
108}
109
110pub struct VideoDecoder {
111    metadata: VideoMetadata,
112    frame_rx: Receiver<VideoFrame>,
113    control_tx: Sender<DecoderControl>,
114    stop_flag: Arc<AtomicBool>,
115    hw_in_use: Arc<AtomicU8>,
116    decode_thread: Option<thread::JoinHandle<()>>,
117}
118
119impl VideoDecoder {
120    pub fn new<P: AsRef<Path>>(path: P, hw_accel: HwAccel) -> VideoResult<Self> {
121        let path = path.as_ref().to_path_buf();
122
123        ffmpeg::init()
124            .map_err(|e| VideoError::SoftwareDecoderInit(anyhow::anyhow!("FFmpeg init: {}", e)))?;
125
126        let metadata = Self::extract_metadata(&path)?;
127
128        tracing::info!(
129            "Opened video: {}x{} @ {:.2} fps, duration: {:?}, codec: {}",
130            metadata.width,
131            metadata.height,
132            metadata.fps,
133            metadata.duration,
134            metadata.codec
135        );
136
137        let (frame_tx, frame_rx) = crossbeam_channel::bounded(3);
138        let (control_tx, control_rx) = crossbeam_channel::unbounded();
139
140        let stop_flag = Arc::new(AtomicBool::new(false));
141        let stop_flag_clone = stop_flag.clone();
142        let hw_in_use = Arc::new(AtomicU8::new(0));
143        let hw_in_use_clone = hw_in_use.clone();
144
145        let decode_thread = thread::Builder::new()
146            .name("wallr-video-decoder".to_string())
147            .spawn(move || {
148                let used = Self::decode_loop(path, hw_accel, frame_tx, control_rx, stop_flag_clone, hw_in_use_clone.clone());
149                let used = match used {
150                    Ok(used) => used,
151                    Err(e) => {
152                        tracing::error!("Video decode loop: {}", e);
153                        HwAccel::Software
154                    }
155                };
156                tracing::info!("Decode thread exited (backend: {})", used.name());
157                // Update again on exit in case it wasn't set during init
158                hw_in_use_clone.store(used.code(), Ordering::Relaxed);
159            })
160            .map_err(|e| VideoError::SoftwareDecoderInit(e.into()))?;
161
162        Ok(Self {
163            metadata,
164            frame_rx,
165            control_tx,
166            stop_flag,
167            hw_in_use,
168            decode_thread: Some(decode_thread),
169        })
170    }
171
172    fn extract_metadata(path: &Path) -> VideoResult<VideoMetadata> {
173        let ictx = ffmpeg::format::input(&path).map_err(|e| VideoError::FileOpen {
174            path: path.to_path_buf(),
175            source: std::io::Error::other(e.to_string()),
176        })?;
177
178        let stream = ictx
179            .streams()
180            .best(ffmpeg::media::Type::Video)
181            .ok_or_else(|| VideoError::NoVideoStream(path.to_path_buf()))?;
182
183        let decoder = ffmpeg::codec::context::Context::from_parameters(stream.parameters())
184            .and_then(|ctx| ctx.decoder().video())
185            .map_err(|e| VideoError::SoftwareDecoderInit(e.into()))?;
186
187        let width = decoder.width();
188        let height = decoder.height();
189        let codec = decoder
190            .codec()
191            .map(|c| c.name().to_string())
192            .unwrap_or_else(|| "unknown".to_string());
193
194        let frame_rate = stream.avg_frame_rate();
195        let fps = if frame_rate.numerator() > 0 {
196            frame_rate.numerator() as f64 / frame_rate.denominator() as f64
197        } else {
198            30.0
199        };
200
201        let duration = {
202            let duration_ts = stream.duration();
203            let time_base = stream.time_base();
204            if duration_ts > 0 {
205                Duration::from_secs_f64(
206                    duration_ts as f64 * time_base.numerator() as f64
207                        / time_base.denominator() as f64,
208                )
209            } else {
210                let container_duration = ictx.duration() as f64 / ffmpeg::ffi::AV_TIME_BASE as f64;
211                Duration::from_secs_f64(container_duration)
212            }
213        };
214
215        let total_frames = if fps > 0.0 {
216            (duration.as_secs_f64() * fps) as u64
217        } else {
218            0
219        };
220
221        Ok(VideoMetadata {
222            width,
223            height,
224            duration,
225            fps,
226            codec,
227            format: ictx.format().name().to_string(),
228            total_frames,
229        })
230    }
231
232    fn init_hw_device(hw_accel: HwAccel) -> Option<(*mut ffmpeg::ffi::AVBufferRef, &'static str)> {
233        let (type_name, device) = match hw_accel {
234            HwAccel::Vaapi => ("vaapi", Some(c"/dev/dri/renderD128")),
235            HwAccel::Nvdec => ("cuda", Some(c"0")),
236            HwAccel::VideoToolbox => ("videotoolbox", None),
237            HwAccel::Software | HwAccel::Auto => return None,
238        };
239
240        let type_name_c = CString::new(type_name).ok()?;
241
242        // SAFETY: C strings passed to FFmpeg; returned device ctx owned by codec context.
243        unsafe {
244            let hw_type = ffmpeg::ffi::av_hwdevice_find_type_by_name(type_name_c.as_ptr());
245            if hw_type == ffmpeg::ffi::AVHWDeviceType::AV_HWDEVICE_TYPE_NONE {
246                tracing::warn!("{} hardware type unavailable", hw_accel.name());
247                return None;
248            }
249
250            let mut device_ctx: *mut ffmpeg::ffi::AVBufferRef = std::ptr::null_mut();
251            let device_ptr: *const c_char = device.map(|d| d.as_ptr()).unwrap_or(std::ptr::null());
252            let ret = ffmpeg::ffi::av_hwdevice_ctx_create(
253                &mut device_ctx,
254                hw_type,
255                device_ptr,
256                std::ptr::null_mut(),
257                0,
258            );
259            if ret < 0 || device_ctx.is_null() {
260                tracing::warn!("{} device init failed ({})", hw_accel.name(), ret);
261                return None;
262            }
263            Some((device_ctx, type_name))
264        }
265    }
266
267    /// Try to build a decoder with a hardware device context attached.
268    fn try_hw_decoder(
269        stream: &ffmpeg::format::stream::Stream,
270        hw_accel: HwAccel,
271    ) -> Option<(ffmpeg::codec::decoder::Video, HwAccel)> {
272        let (device_ctx, _) = Self::init_hw_device(hw_accel)?;
273
274        let mut context =
275            ffmpeg::codec::context::Context::from_parameters(stream.parameters()).ok()?;
276
277        // SAFETY: device_ctx is a valid FFmpeg allocation; the codec context
278        // unrefs it when dropped.
279        unsafe {
280            (*context.as_mut_ptr()).hw_device_ctx = device_ctx;
281        }
282
283        match context.decoder().video() {
284            Ok(decoder) => {
285                tracing::info!("Hardware decode active: {}", hw_accel.name());
286                Some((decoder, hw_accel))
287            }
288            Err(e) => {
289                tracing::warn!("{} decode init failed: {}", hw_accel.name(), e);
290                None
291            }
292        }
293    }
294
295    /// Build a decoder with appropriate hardware acceleration fallback.
296    /// 
297    /// - Auto: Try all hardware backends in priority order, then software
298    /// - Explicit backend (Vaapi, Nvdec, VideoToolbox): Try that backend, then software
299    /// - Software: Use software decoder only (no hardware attempts)
300    fn build_decoder(
301        stream: &ffmpeg::format::stream::Stream,
302        hw_accel: HwAccel,
303    ) -> (ffmpeg::codec::decoder::Video, HwAccel) {
304        match hw_accel {
305            HwAccel::Auto => {
306                // Try all hardware backends in priority order
307                for &backend in HwAccel::all_hardware() {
308                    if let Some(result) = Self::try_hw_decoder(stream, backend) {
309                        return result;
310                    }
311                }
312                // Fall back to software
313                tracing::info!("All hardware backends failed, using software decoder");
314            }
315            HwAccel::Software => {
316                // Explicit software request: skip hardware entirely
317                tracing::info!("Software decoder explicitly requested");
318            }
319            specific => {
320                // Try the requested hardware backend first
321                if let Some(result) = Self::try_hw_decoder(stream, specific) {
322                    return result;
323                }
324                // Fall back to software
325                tracing::info!(
326                    "{} hardware decoder failed, falling back to software",
327                    specific.name()
328                );
329            }
330        }
331
332        // Software fallback.
333        let decoder = ffmpeg::codec::context::Context::from_parameters(stream.parameters())
334            .and_then(|ctx| ctx.decoder().video())
335            .expect("software decoder must be available");
336        (decoder, HwAccel::Software)
337    }
338
339    #[allow(clippy::too_many_arguments)]
340    fn decode_loop(
341        path: std::path::PathBuf,
342        hw_accel: HwAccel,
343        frame_tx: Sender<VideoFrame>,
344        control_rx: Receiver<DecoderControl>,
345        stop_flag: Arc<AtomicBool>,
346        hw_in_use: Arc<AtomicU8>,
347    ) -> VideoResult<HwAccel> {
348        let mut ictx = ffmpeg::format::input(&path).map_err(|e| VideoError::FileOpen {
349            path: path.clone(),
350            source: std::io::Error::other(e.to_string()),
351        })?;
352
353        let stream = ictx
354            .streams()
355            .best(ffmpeg::media::Type::Video)
356            .ok_or_else(|| VideoError::NoVideoStream(path.clone()))?;
357
358        let video_stream_index = stream.index();
359        let time_base = stream.time_base();
360
361        let (mut decoder, used_hw) = Self::build_decoder(&stream, hw_accel);
362        tracing::info!("Decoder in use: {}", used_hw.name());
363        
364        // Report the active backend immediately after successful initialization
365        hw_in_use.store(used_hw.code(), Ordering::Relaxed);
366
367        let mut scaler: Option<ffmpeg::software::scaling::Context> = None;
368        let mut scaler_src: Option<ffmpeg::format::Pixel> = None;
369
370        let mut paused = false;
371        let mut pending_seek: Option<Duration> = None;
372        let mut frame_index = 0u64;
373        let mut decoded_frame = ffmpeg::frame::Video::empty();
374        let mut sw_frame = ffmpeg::frame::Video::empty();
375        let mut rgb_frame = ffmpeg::frame::Video::empty();
376
377        'outer: loop {
378            if stop_flag.load(Ordering::Relaxed) {
379                break;
380            }
381
382            while let Ok(control) = control_rx.try_recv() {
383                match control {
384                    DecoderControl::Pause => paused = true,
385                    DecoderControl::Resume => paused = false,
386                    DecoderControl::Seek(ts) => pending_seek = Some(ts),
387                }
388            }
389
390            if let Some(ts) = pending_seek.take() {
391                Self::apply_seek(&mut ictx, &mut decoder, time_base, ts);
392            }
393
394            if paused {
395                thread::sleep(Duration::from_millis(10));
396                continue;
397            }
398
399            for (stream, packet) in ictx.packets() {
400                if stop_flag.load(Ordering::Relaxed) {
401                    break 'outer;
402                }
403
404                while let Ok(control) = control_rx.try_recv() {
405                    match control {
406                        DecoderControl::Pause => paused = true,
407                        DecoderControl::Resume => paused = false,
408                        DecoderControl::Seek(ts) => pending_seek = Some(ts),
409                    }
410                }
411                if paused || pending_seek.is_some() {
412                    break;
413                }
414
415                if stream.index() != video_stream_index {
416                    continue;
417                }
418
419                decoder
420                    .send_packet(&packet)
421                    .map_err(|e| VideoError::DecodeFailed(anyhow::anyhow!("send_packet: {}", e)))?;
422
423                while decoder.receive_frame(&mut decoded_frame).is_ok() {
424                    if stop_flag.load(Ordering::Relaxed) {
425                        break 'outer;
426                    }
427
428                    let is_hw_frame = unsafe { (*decoded_frame.as_ptr()).data[0].is_null() };
429
430                    let src_frame = if is_hw_frame {
431                        let ret = unsafe {
432                            ffmpeg::ffi::av_hwframe_transfer_data(
433                                sw_frame.as_mut_ptr(),
434                                decoded_frame.as_ptr(),
435                                0,
436                            )
437                        };
438                        if ret < 0 {
439                            tracing::warn!("hwframe transfer failed: {ret}");
440                            continue;
441                        }
442                        &sw_frame
443                    } else {
444                        &decoded_frame
445                    };
446
447                    let src_format = src_frame.format();
448                    if scaler_src != Some(src_format) {
449                        scaler = Some(
450                            ffmpeg::software::scaling::context::Context::get(
451                                src_format,
452                                src_frame.width(),
453                                src_frame.height(),
454                                ffmpeg::format::Pixel::RGBA,
455                                src_frame.width(),
456                                src_frame.height(),
457                                ffmpeg::software::scaling::Flags::BILINEAR,
458                            )
459                            .map_err(|e| VideoError::FormatConversionFailed(e.into()))?,
460                        );
461                        scaler_src = Some(src_format);
462                    }
463
464                    scaler
465                        .as_mut()
466                        .expect("scaler initialized above")
467                        .run(src_frame, &mut rgb_frame)
468                        .map_err(|e| VideoError::FormatConversionFailed(e.into()))?;
469
470                    let pts_duration = if let Some(pts) = decoded_frame.timestamp() {
471                        Duration::from_secs_f64(
472                            pts as f64 * time_base.numerator() as f64
473                                / time_base.denominator() as f64,
474                        )
475                    } else {
476                        Duration::from_secs_f64(frame_index as f64 / 30.0)
477                    };
478
479                    let video_frame = VideoFrame {
480                        data: rgb_frame.data(0).to_vec(),
481                        width: rgb_frame.width(),
482                        height: rgb_frame.height(),
483                        pts: pts_duration,
484                        index: frame_index,
485                    };
486                    frame_index = frame_index.wrapping_add(1);
487
488                    match frame_tx.send_timeout(video_frame, Duration::from_millis(20)) {
489                        Ok(()) => {}
490                        Err(SendTimeoutError::Timeout(_)) => break,
491                        Err(SendTimeoutError::Disconnected(_)) => {
492                            tracing::warn!("Frame queue disconnected, ending decode loop");
493                            return Ok(used_hw);
494                        }
495                    }
496                }
497            }
498
499            tracing::debug!("End of stream after {} frames, looping", frame_index);
500            while decoder.receive_frame(&mut decoded_frame).is_ok() {
501                if stop_flag.load(Ordering::Relaxed) {
502                    break 'outer;
503                }
504            }
505            if stop_flag.load(Ordering::Relaxed) {
506                break;
507            }
508            if !paused {
509                ictx.seek(0, ..)
510                    .map_err(|e| VideoError::SeekFailed(Duration::ZERO, e.into()))?;
511                decoder.flush();
512            }
513        }
514
515        Ok(used_hw)
516    }
517
518    fn apply_seek(
519        ictx: &mut ffmpeg::format::context::Input,
520        decoder: &mut ffmpeg::codec::decoder::Video,
521        time_base: ffmpeg::Rational,
522        ts: Duration,
523    ) {
524        let tb_sec = time_base.numerator() as f64 / time_base.denominator() as f64;
525        let ts_tb = if tb_sec > 0.0 {
526            (ts.as_secs_f64() / tb_sec) as i64
527        } else {
528            0
529        };
530        match ictx.seek(ts_tb, ..) {
531            Ok(()) => {
532                decoder.flush();
533                let mut drain = ffmpeg::frame::Video::empty();
534                while decoder.receive_frame(&mut drain).is_ok() {}
535                tracing::info!("Seeked to {:?}", ts);
536            }
537            Err(e) => tracing::warn!("Seek to {:?} failed: {}", ts, e),
538        }
539    }
540
541    pub fn next_frame(&self) -> Option<VideoFrame> {
542        self.frame_rx.try_recv().ok()
543    }
544
545    pub fn metadata(&self) -> &VideoMetadata {
546        &self.metadata
547    }
548
549    pub fn decoder_info(&self) -> DecoderInfo {
550        DecoderInfo {
551            codec_name: self.metadata.codec.clone(),
552            hardware_accel: if self.hw_accel_in_use() != HwAccel::Software {
553                Some(self.hw_accel_in_use().name().to_string())
554            } else {
555                None
556            },
557            pixel_format: "RGBA".to_string(),
558        }
559    }
560
561    pub fn hw_accel_in_use(&self) -> HwAccel {
562        for _ in 0..50 {
563            let code = self.hw_in_use.load(Ordering::Relaxed);
564            if code != 0 {
565                return HwAccel::from_code(code);
566            }
567            std::thread::sleep(Duration::from_millis(5));
568        }
569        HwAccel::Software
570    }
571
572    pub fn pause(&self) {
573        let _ = self.control_tx.send(DecoderControl::Pause);
574    }
575
576    pub fn resume(&self) {
577        let _ = self.control_tx.send(DecoderControl::Resume);
578    }
579
580    pub fn seek(&self, timestamp: Duration) {
581        let _ = self.control_tx.send(DecoderControl::Seek(timestamp));
582    }
583
584    pub fn drain(&mut self) {
585        while self.frame_rx.try_recv().is_ok() {}
586    }
587
588    pub fn is_video_file<P: AsRef<Path>>(path: P) -> bool {
589        path.as_ref()
590            .extension()
591            .and_then(|e| e.to_str())
592            .is_some_and(|ext| {
593                matches!(
594                    ext.to_lowercase().as_str(),
595                    "mp4" | "webm" | "mkv" | "mov" | "avi" | "m4v"
596                )
597            })
598    }
599}
600
601impl Drop for VideoDecoder {
602    fn drop(&mut self) {
603        self.stop_flag.store(true, Ordering::Relaxed);
604        if let Some(thread) = self.decode_thread.take() {
605            let _ = thread.join();
606        }
607    }
608}
609
610#[cfg(test)]
611mod tests {
612    use super::*;
613
614    #[test]
615    fn test_is_video_file() {
616        assert!(VideoDecoder::is_video_file("test.mp4"));
617        assert!(VideoDecoder::is_video_file("test.MP4"));
618        assert!(VideoDecoder::is_video_file("test.webm"));
619        assert!(VideoDecoder::is_video_file("test.mkv"));
620        assert!(VideoDecoder::is_video_file("test.mov"));
621        assert!(!VideoDecoder::is_video_file("test.jpg"));
622        assert!(!VideoDecoder::is_video_file("test.gif"));
623        assert!(!VideoDecoder::is_video_file("test.png"));
624    }
625
626    #[test]
627    fn test_hwaccel_names() {
628        assert_eq!(HwAccel::Vaapi.name(), "VAAPI");
629        assert_eq!(HwAccel::Nvdec.name(), "NVDEC");
630        assert_eq!(HwAccel::Software.name(), "Software");
631    }
632
633    #[test]
634    fn test_hwaccel_codes_roundtrip() {
635        for accel in [
636            HwAccel::Software,
637            HwAccel::Vaapi,
638            HwAccel::Nvdec,
639            HwAccel::VideoToolbox,
640        ] {
641            assert_eq!(HwAccel::from_code(accel.code()), accel);
642        }
643    }
644
645    #[test]
646    fn test_hwaccel_from_config() {
647        assert_eq!(HwAccel::from_config("vaapi"), HwAccel::Vaapi);
648        assert_eq!(HwAccel::from_config("nvdec"), HwAccel::Nvdec);
649        assert_eq!(HwAccel::from_config("software"), HwAccel::Software);
650        assert_eq!(HwAccel::from_config("auto"), HwAccel::Auto);
651        assert_eq!(HwAccel::from_config("unknown"), HwAccel::Auto);
652    }
653}