Skip to main content

alpha2_native/
hwdecode.rs

1//! Standalone Linux Vulkan hardware-decode probe for the CLI.
2
3use alpha2_host_core::remote::SourceLocation;
4use std::collections::HashSet;
5use std::ffi::CString;
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    source: impl Into<SourceLocation>,
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 source = source.into();
79    let mut input = open_input(&source)?;
80    let selected = probe_context(&input, &source)?
81        .selected_video
82        .ok_or_else(|| DecodeError::Unsupported("source has no video stream".into()))?;
83    input.discard_all_but(selected);
84    let parameters = input
85        .streams()
86        .get(selected)
87        .ok_or(DecodeError::OutOfRange)?
88        .codecpar();
89    let preferred = AVCodec::find_decoder(parameters.codec_id)
90        .ok_or_else(|| DecodeError::Unsupported("selected video codec has no decoder".into()))?;
91    crate::decode::allowed_decoder(&preferred)?;
92    // The preferred decoder may be software (libdav1d for AV1); the Vulkan configuration lives on
93    // `FFmpeg`'s own decoder for the codec.
94    let (codec, config) = crate::decode::registered_video_decoders(parameters.codec_id)
95        .find_map(|codec| {
96            let config = (0..)
97                .map_while(|index| codec.hw_config(index))
98                .find(|config| {
99                    config.device_type == ffi::AV_HWDEVICE_TYPE_VULKAN
100                        && config.pix_fmt == ffi::AV_PIX_FMT_VULKAN
101                        && crate::decode::has_hw_config_method(
102                            config.methods,
103                            ffi::AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX,
104                        )
105                })?;
106            Some((codec, config))
107        })
108        .ok_or_else(|| {
109            DecodeError::Unsupported(format!(
110                "decoder {} has no Vulkan HW_DEVICE_CTX configuration",
111                preferred.name().to_string_lossy()
112            ))
113        })?;
114    debug_assert_eq!(config.pix_fmt, ffi::AV_PIX_FMT_VULKAN);
115    alpha2_ffmpeg_bridge::check_hardware_interop()
116        .map_err(|error| DecodeError::Unsupported(error.to_string()))?;
117
118    // Pass the device by loader index: `FFmpeg` reads a leading digit as an index, so an
119    // `ALPHA2_GPU_ADAPTER` name passed unchanged could select another device.
120    let requested_device = CString::new(
121        alpha2_native_gpu::shared_device_index()
122            .map_err(|error| DecodeError::Unsupported(error.to_string()))?
123            .to_string(),
124    )
125    .map_err(|_| DecodeError::Unsupported("a device index held a NUL byte".into()))?;
126    let device = AVHWDeviceContext::create(
127        ffi::AV_HWDEVICE_TYPE_VULKAN,
128        Some(&requested_device),
129        None,
130        0,
131    )
132    .map_err(adapter_error)?;
133    let mut decoder = AVCodecContext::new(&codec);
134    decoder.apply_codecpar(&parameters).map_err(adapter_error)?;
135    drop(parameters);
136    decoder.set_pkt_timebase(input.streams()[selected].time_base);
137    decoder.set_get_format(Some(alpha2_ffmpeg_bridge::vulkan_get_format_callback()));
138    decoder.set_hw_device_ctx(device);
139    decoder.open(None).map_err(adapter_error)?;
140
141    let mut demux_eof = false;
142    let mut flushed = false;
143    let mut images = HashSet::new();
144    let mut reuse = 0_u64;
145    let mut first_info = None;
146    let mut all_sampled = true;
147    let mut all_synchronized = true;
148    let mut max_plane_images = 0;
149    let mut frames = 0_u64;
150    while frames < frame_limit as u64 {
151        let Some(frame) = decode_next_raw(
152            &mut input,
153            &mut decoder,
154            selected,
155            &mut demux_eof,
156            &mut flushed,
157        )?
158        else {
159            break;
160        };
161        let lease = VulkanFrameLease::new(frame);
162        let info = validate_frame(&lease, first_info.as_ref())?;
163        probe_vulkan_submission(&lease).map_err(adapter_error)?;
164        let primary = info
165            .images
166            .iter()
167            .copied()
168            .find(|image| *image != 0)
169            .ok_or_else(|| DecodeError::Adapter("Vulkan frame has no image".into()))?;
170        if !images.insert(primary) {
171            reuse += 1;
172        }
173        all_sampled &= info.sampled;
174        all_synchronized &= synchronized(&info);
175        max_plane_images = max_plane_images.max(info.plane_count);
176        first_info.get_or_insert(info);
177        frames += 1;
178    }
179    let first_info = first_info.ok_or_else(|| {
180        DecodeError::Unsupported("decoder returned no Vulkan hardware frame".into())
181    })?;
182    if !all_sampled {
183        return Err(DecodeError::Unsupported(
184            "decoded Vulkan image is not sampleable".into(),
185        ));
186    }
187    if !all_synchronized {
188        return Err(DecodeError::Adapter(
189            "decoded Vulkan image has no ready timeline semaphore".into(),
190        ));
191    }
192
193    input
194        .seek(
195            i32::try_from(selected).map_err(|_| DecodeError::OutOfRange)?,
196            0,
197            ffi::AVSEEK_FLAG_BACKWARD.cast_signed(),
198        )
199        .map_err(adapter_error)?;
200    decoder.flush_buffers();
201    demux_eof = false;
202    flushed = false;
203    let seek_frame = decode_next_raw(
204        &mut input,
205        &mut decoder,
206        selected,
207        &mut demux_eof,
208        &mut flushed,
209    )?
210    .ok_or_else(|| DecodeError::Adapter("no Vulkan frame after seek".into()))?;
211    let seek_lease = VulkanFrameLease::new(seek_frame);
212    validate_frame(&seek_lease, Some(&first_info))?;
213    probe_vulkan_submission(&seek_lease).map_err(adapter_error)?;
214
215    Ok(VulkanDecodeProbe {
216        decoder: codec.name().to_string_lossy().into_owned(),
217        hardware_format: format_name(first_info.hardware_format),
218        software_format: format_name(first_info.software_format),
219        display_size: (first_info.width, first_info.height),
220        coded_size: (first_info.coded_width, first_info.coded_height),
221        hardware_frames: frames,
222        unique_images: images.len(),
223        reused_images: reuse,
224        all_images_sampled: all_sampled,
225        all_images_synchronized: all_synchronized,
226        seek_frames: 1,
227        device: first_info.device,
228        physical_device: first_info.physical_device,
229        max_plane_images,
230        interop_submissions: frames + 1,
231        source_cpu_plane_copy_bytes: 0,
232        source_upload_bytes: 0,
233        source_download_bytes: 0,
234    })
235}
236
237fn decode_next_raw(
238    input: &mut alpha2_ffmpeg_bridge::DemuxInput,
239    decoder: &mut AVCodecContext,
240    stream_index: usize,
241    demux_eof: &mut bool,
242    flushed: &mut bool,
243) -> Result<Option<AVFrame>, DecodeError> {
244    loop {
245        match decoder.receive_frame() {
246            Ok(frame) => return Ok(Some(frame)),
247            Err(RsmpegError::DecoderDrainError) => {}
248            Err(RsmpegError::DecoderFlushedError) => return Ok(None),
249            Err(error) => return Err(adapter_error(error)),
250        }
251        if *demux_eof {
252            if !*flushed {
253                decoder.send_packet(None).map_err(adapter_error)?;
254                *flushed = true;
255                continue;
256            }
257            return Ok(None);
258        }
259        let Some(packet) = input
260            .read_packet()
261            .map_err(|error| crate::decode::demux_error(input, error))?
262        else {
263            *demux_eof = true;
264            continue;
265        };
266        if usize::try_from(packet.stream_index).ok() == Some(stream_index) {
267            decoder.send_packet(Some(&packet)).map_err(adapter_error)?;
268        }
269    }
270}
271
272fn validate_frame(
273    frame: &VulkanFrameLease,
274    expected: Option<&VulkanFrameInfo>,
275) -> Result<VulkanFrameInfo, DecodeError> {
276    let info = frame.info().map_err(adapter_error)?;
277    if info.hardware_format != ffi::AV_PIX_FMT_VULKAN {
278        return Err(DecodeError::Adapter(format!(
279            "decoder returned {} instead of vulkan",
280            format_name(info.hardware_format)
281        )));
282    }
283    if let Some(expected) = expected {
284        if info.device != expected.device || info.physical_device != expected.physical_device {
285            return Err(DecodeError::Adapter(
286                "Vulkan decoder changed device while probing".into(),
287            ));
288        }
289        if info.software_format != expected.software_format {
290            return Err(DecodeError::Adapter(
291                "Vulkan decoder changed surface format while probing".into(),
292            ));
293        }
294        if info.coded_width != expected.coded_width || info.coded_height != expected.coded_height {
295            return Err(DecodeError::Adapter(
296                "Vulkan decoder changed surface extent while probing".into(),
297            ));
298        }
299    }
300    // Presentation normalizes against the allocated extent, so a smaller surface
301    // would rescale every sample.
302    if info.coded_width < info.width || info.coded_height < info.height {
303        return Err(DecodeError::Adapter(
304            "Vulkan surface is smaller than the frame it carries".into(),
305        ));
306    }
307    Ok(info)
308}
309
310fn synchronized(info: &VulkanFrameInfo) -> bool {
311    info.images
312        .iter()
313        .enumerate()
314        .filter(|(_, image)| **image != 0)
315        .all(|(index, _)| info.semaphores[index] != 0)
316}
317
318fn format_name(format: ffi::AVPixelFormat) -> String {
319    pixel_format_name(format).unwrap_or_else(|| format!("unknown({format})"))
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    #[test]
327    fn synchronization_ignores_unused_plane_slots() {
328        let info = VulkanFrameInfo {
329            hardware_format: ffi::AV_PIX_FMT_VULKAN,
330            software_format: ffi::AV_PIX_FMT_NV12,
331            width: 16,
332            height: 16,
333            coded_width: 16,
334            coded_height: 16,
335            plane_count: 1,
336            sampled: true,
337            instance: 1,
338            physical_device: 2,
339            device: 3,
340            images: [4, 0, 0, 0, 0, 0, 0, 0],
341            formats: [1; 8],
342            layouts: [0; 8],
343            access: [0; 8],
344            semaphores: [5, 0, 0, 0, 0, 0, 0, 0],
345            semaphore_values: [0; 8],
346            queue_families: [0; 8],
347        };
348        assert!(synchronized(&info));
349    }
350}