Skip to main content

alpha2_native/
hwdecode.rs

1//! Standalone Linux Vulkan hardware-decode probe for the CLI.
2
3use std::collections::HashSet;
4use std::ffi::CString;
5use std::path::Path;
6
7use alpha2_ffmpeg_bridge::{VulkanFrameInfo, VulkanFrameLease, pixel_format_name};
8use alpha2_media::DecodeError;
9use alpha2_native_gpu::probe_vulkan_submission;
10use rsmpeg::avcodec::{AVCodec, AVCodecContext};
11use rsmpeg::avutil::{AVFrame, AVHWDeviceContext};
12use rsmpeg::error::RsmpegError;
13use rsmpeg::ffi;
14
15use crate::convert::adapter_error;
16use crate::decode::{open_input, probe_context};
17
18/// Result of a bounded Vulkan hardware decode and surface probe.
19#[derive(Clone, Debug, Eq, PartialEq)]
20pub struct VulkanDecodeProbe {
21    /// `FFmpeg` decoder implementation.
22    pub decoder: String,
23    /// Selected opaque hardware pixel format.
24    pub hardware_format: String,
25    /// Actual decoded surface layout.
26    pub software_format: String,
27    /// Display size reported by the decoded frames.
28    pub display_size: (i32, i32),
29    /// Allocated surface extent, padded to whole macroblocks by the codec.
30    pub coded_size: (i32, i32),
31    /// Number of hardware frames received before the bound.
32    pub hardware_frames: u64,
33    /// Number of distinct `VkImage` identities observed.
34    pub unique_images: usize,
35    /// Frames whose primary image had already appeared (pool reuse).
36    pub reused_images: u64,
37    /// Whether every decoded image included sampled-image usage.
38    pub all_images_sampled: bool,
39    /// Whether every image exposed a ready timeline semaphore.
40    pub all_images_synchronized: bool,
41    /// Number of hardware frames received after seeking back to the start.
42    pub seek_frames: u64,
43    /// Device identity shared by all observed surfaces.
44    pub device: u64,
45    /// Physical-device identity shared by all observed surfaces.
46    pub physical_device: u64,
47    /// Maximum number of Vulkan images backing one decoded frame.
48    pub max_plane_images: u32,
49    /// GPU-only synchronization/layout submissions completed by the probe.
50    pub interop_submissions: u64,
51    /// CPU source-plane copies performed by this probe.
52    pub source_cpu_plane_copy_bytes: u64,
53    /// CPU-to-GPU uploads performed by this probe.
54    pub source_upload_bytes: u64,
55    /// GPU-to-CPU downloads performed by this probe.
56    pub source_download_bytes: u64,
57}
58
59/// Decodes Vulkan frames without mapping, downloading, or uploading their planes.
60///
61/// Checks image, layout and timeline state, pool reuse, and decode after a seek. It opens
62/// its own device and decoder instead of [`crate::NativeExportDecoder`] to observe
63/// `FFmpeg`'s surfaces directly.
64///
65/// # Errors
66/// Returns an error if Vulkan decode is unavailable or a frame breaks
67/// the resident-surface contract.
68#[allow(clippy::too_many_lines)]
69pub fn probe_vulkan_decode(
70    path: impl AsRef<Path>,
71    frame_limit: usize,
72) -> Result<VulkanDecodeProbe, DecodeError> {
73    if frame_limit < 2 {
74        return Err(DecodeError::Unsupported(
75            "Vulkan decode probe requires at least two frames".into(),
76        ));
77    }
78    let mut input = open_input(path.as_ref())?;
79    let selected = probe_context(&input, path.as_ref())?
80        .selected_video
81        .ok_or_else(|| DecodeError::Unsupported("source has no video stream".into()))?;
82    input.discard_all_but(selected);
83    let parameters = input
84        .streams()
85        .get(selected)
86        .ok_or(DecodeError::OutOfRange)?
87        .codecpar();
88    let preferred = AVCodec::find_decoder(parameters.codec_id)
89        .ok_or_else(|| DecodeError::Unsupported("selected video codec has no decoder".into()))?;
90    crate::decode::allowed_decoder(&preferred)?;
91    // The preferred decoder may be software (libdav1d for AV1); the Vulkan configuration lives on
92    // `FFmpeg`'s own decoder for the codec.
93    let (codec, config) = crate::decode::registered_video_decoders(parameters.codec_id)
94        .find_map(|codec| {
95            let config = (0..)
96                .map_while(|index| codec.hw_config(index))
97                .find(|config| {
98                    config.device_type == ffi::AV_HWDEVICE_TYPE_VULKAN
99                        && config.pix_fmt == ffi::AV_PIX_FMT_VULKAN
100                        && crate::decode::has_hw_config_method(
101                            config.methods,
102                            ffi::AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX,
103                        )
104                })?;
105            Some((codec, config))
106        })
107        .ok_or_else(|| {
108            DecodeError::Unsupported(format!(
109                "decoder {} has no Vulkan HW_DEVICE_CTX configuration",
110                preferred.name().to_string_lossy()
111            ))
112        })?;
113    debug_assert_eq!(config.pix_fmt, ffi::AV_PIX_FMT_VULKAN);
114    alpha2_ffmpeg_bridge::check_hardware_interop()
115        .map_err(|error| DecodeError::Unsupported(error.to_string()))?;
116
117    // Pass the device by loader index: `FFmpeg` reads a leading digit as an index, so an
118    // `ALPHA2_GPU_ADAPTER` name passed unchanged could select another device.
119    let requested_device = CString::new(
120        alpha2_native_gpu::shared_device_index()
121            .map_err(|error| DecodeError::Unsupported(error.to_string()))?
122            .to_string(),
123    )
124    .map_err(|_| DecodeError::Unsupported("a device index held a NUL byte".into()))?;
125    let device = AVHWDeviceContext::create(
126        ffi::AV_HWDEVICE_TYPE_VULKAN,
127        Some(&requested_device),
128        None,
129        0,
130    )
131    .map_err(adapter_error)?;
132    let mut decoder = AVCodecContext::new(&codec);
133    decoder.apply_codecpar(&parameters).map_err(adapter_error)?;
134    drop(parameters);
135    decoder.set_pkt_timebase(input.streams()[selected].time_base);
136    decoder.set_get_format(Some(alpha2_ffmpeg_bridge::vulkan_get_format_callback()));
137    decoder.set_hw_device_ctx(device);
138    decoder.open(None).map_err(adapter_error)?;
139
140    let mut demux_eof = false;
141    let mut flushed = false;
142    let mut images = HashSet::new();
143    let mut reuse = 0_u64;
144    let mut first_info = None;
145    let mut all_sampled = true;
146    let mut all_synchronized = true;
147    let mut max_plane_images = 0;
148    let mut frames = 0_u64;
149    while frames < frame_limit as u64 {
150        let Some(frame) = decode_next_raw(
151            &mut input,
152            &mut decoder,
153            selected,
154            &mut demux_eof,
155            &mut flushed,
156        )?
157        else {
158            break;
159        };
160        let lease = VulkanFrameLease::new(frame);
161        let info = validate_frame(&lease, first_info.as_ref())?;
162        probe_vulkan_submission(&lease).map_err(adapter_error)?;
163        let primary = info
164            .images
165            .iter()
166            .copied()
167            .find(|image| *image != 0)
168            .ok_or_else(|| DecodeError::Adapter("Vulkan frame has no image".into()))?;
169        if !images.insert(primary) {
170            reuse += 1;
171        }
172        all_sampled &= info.sampled;
173        all_synchronized &= synchronized(&info);
174        max_plane_images = max_plane_images.max(info.plane_count);
175        first_info.get_or_insert(info);
176        frames += 1;
177    }
178    let first_info = first_info.ok_or_else(|| {
179        DecodeError::Unsupported("decoder returned no Vulkan hardware frame".into())
180    })?;
181    if !all_sampled {
182        return Err(DecodeError::Unsupported(
183            "decoded Vulkan image is not sampleable".into(),
184        ));
185    }
186    if !all_synchronized {
187        return Err(DecodeError::Adapter(
188            "decoded Vulkan image has no ready timeline semaphore".into(),
189        ));
190    }
191
192    input
193        .seek(
194            i32::try_from(selected).map_err(|_| DecodeError::OutOfRange)?,
195            0,
196            ffi::AVSEEK_FLAG_BACKWARD.cast_signed(),
197        )
198        .map_err(adapter_error)?;
199    decoder.flush_buffers();
200    demux_eof = false;
201    flushed = false;
202    let seek_frame = decode_next_raw(
203        &mut input,
204        &mut decoder,
205        selected,
206        &mut demux_eof,
207        &mut flushed,
208    )?
209    .ok_or_else(|| DecodeError::Adapter("no Vulkan frame after seek".into()))?;
210    let seek_lease = VulkanFrameLease::new(seek_frame);
211    validate_frame(&seek_lease, Some(&first_info))?;
212    probe_vulkan_submission(&seek_lease).map_err(adapter_error)?;
213
214    Ok(VulkanDecodeProbe {
215        decoder: codec.name().to_string_lossy().into_owned(),
216        hardware_format: format_name(first_info.hardware_format),
217        software_format: format_name(first_info.software_format),
218        display_size: (first_info.width, first_info.height),
219        coded_size: (first_info.coded_width, first_info.coded_height),
220        hardware_frames: frames,
221        unique_images: images.len(),
222        reused_images: reuse,
223        all_images_sampled: all_sampled,
224        all_images_synchronized: all_synchronized,
225        seek_frames: 1,
226        device: first_info.device,
227        physical_device: first_info.physical_device,
228        max_plane_images,
229        interop_submissions: frames + 1,
230        source_cpu_plane_copy_bytes: 0,
231        source_upload_bytes: 0,
232        source_download_bytes: 0,
233    })
234}
235
236fn decode_next_raw(
237    input: &mut alpha2_ffmpeg_bridge::DemuxInput,
238    decoder: &mut AVCodecContext,
239    stream_index: usize,
240    demux_eof: &mut bool,
241    flushed: &mut bool,
242) -> Result<Option<AVFrame>, DecodeError> {
243    loop {
244        match decoder.receive_frame() {
245            Ok(frame) => return Ok(Some(frame)),
246            Err(RsmpegError::DecoderDrainError) => {}
247            Err(RsmpegError::DecoderFlushedError) => return Ok(None),
248            Err(error) => return Err(adapter_error(error)),
249        }
250        if *demux_eof {
251            if !*flushed {
252                decoder.send_packet(None).map_err(adapter_error)?;
253                *flushed = true;
254                continue;
255            }
256            return Ok(None);
257        }
258        let Some(packet) = input.read_packet().map_err(adapter_error)? else {
259            *demux_eof = true;
260            continue;
261        };
262        if usize::try_from(packet.stream_index).ok() == Some(stream_index) {
263            decoder.send_packet(Some(&packet)).map_err(adapter_error)?;
264        }
265    }
266}
267
268fn validate_frame(
269    frame: &VulkanFrameLease,
270    expected: Option<&VulkanFrameInfo>,
271) -> Result<VulkanFrameInfo, DecodeError> {
272    let info = frame.info().map_err(adapter_error)?;
273    if info.hardware_format != ffi::AV_PIX_FMT_VULKAN {
274        return Err(DecodeError::Adapter(format!(
275            "decoder returned {} instead of vulkan",
276            format_name(info.hardware_format)
277        )));
278    }
279    if let Some(expected) = expected {
280        if info.device != expected.device || info.physical_device != expected.physical_device {
281            return Err(DecodeError::Adapter(
282                "Vulkan decoder changed device while probing".into(),
283            ));
284        }
285        if info.software_format != expected.software_format {
286            return Err(DecodeError::Adapter(
287                "Vulkan decoder changed surface format while probing".into(),
288            ));
289        }
290        if info.coded_width != expected.coded_width || info.coded_height != expected.coded_height {
291            return Err(DecodeError::Adapter(
292                "Vulkan decoder changed surface extent while probing".into(),
293            ));
294        }
295    }
296    // Presentation normalizes against the allocated extent, so a smaller surface
297    // would rescale every sample.
298    if info.coded_width < info.width || info.coded_height < info.height {
299        return Err(DecodeError::Adapter(
300            "Vulkan surface is smaller than the frame it carries".into(),
301        ));
302    }
303    Ok(info)
304}
305
306fn synchronized(info: &VulkanFrameInfo) -> bool {
307    info.images
308        .iter()
309        .enumerate()
310        .filter(|(_, image)| **image != 0)
311        .all(|(index, _)| info.semaphores[index] != 0)
312}
313
314fn format_name(format: ffi::AVPixelFormat) -> String {
315    pixel_format_name(format).unwrap_or_else(|| format!("unknown({format})"))
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    #[test]
323    fn synchronization_ignores_unused_plane_slots() {
324        let info = VulkanFrameInfo {
325            hardware_format: ffi::AV_PIX_FMT_VULKAN,
326            software_format: ffi::AV_PIX_FMT_NV12,
327            width: 16,
328            height: 16,
329            coded_width: 16,
330            coded_height: 16,
331            plane_count: 1,
332            sampled: true,
333            instance: 1,
334            physical_device: 2,
335            device: 3,
336            images: [4, 0, 0, 0, 0, 0, 0, 0],
337            formats: [1; 8],
338            layouts: [0; 8],
339            access: [0; 8],
340            semaphores: [5, 0, 0, 0, 0, 0, 0, 0],
341            semaphore_values: [0; 8],
342            queue_families: [0; 8],
343        };
344        assert!(synchronized(&info));
345    }
346}