Skip to main content

alpha2_native/hwencode/
vulkan.rs

1//! The Vulkan backend: `h264_vulkan` and `hevc_vulkan` on the renderer's shared device.
2//!
3//! The frames pool, its image usage, images per frame and owning queue family are decided by
4//! `FFmpeg` and must be observed, not assumed; the probes observe them on any device.
5
6use std::collections::HashSet;
7use std::ffi::CString;
8
9use alpha2_media::{ColorMetadata, EncodeError};
10use alpha2_time::MediaTime;
11use rsmpeg::avcodec::{AVCodec, AVCodecContext};
12use rsmpeg::avutil::{AVFrame, AVHWDeviceContext, AVHWFramesContext, AVRational, av_rescale_q, ra};
13use rsmpeg::error::RsmpegError;
14use rsmpeg::ffi;
15
16use super::{
17    EncoderInputHandoff, EncoderInputLayout, EncoderPoolStats, EncoderSurfaceDescriptor,
18    HardwareEncodeBackend, HardwareEncodeCapability, HardwareEncodeOpenError,
19    HardwareEncodeRequest, InputFrame,
20};
21use crate::NativeVideoCodec;
22use crate::bitstream::EncodedVideoFilter;
23use crate::convert::{encode_adapter_error, tick_base};
24use crate::encode::{EncodeStageTimings, timed};
25use crate::mux::Muxer;
26
27/// What one Vulkan encode session turned out to require and produce.
28#[derive(Clone, Debug, Eq, PartialEq)]
29pub struct VulkanEncodeProbe {
30    /// `FFmpeg` encoder that opened.
31    pub encoder: String,
32    /// Coded size the pool allocated.
33    pub coded_size: (u32, u32),
34    /// Image usage the pool was created with. `FFmpeg` keeps it as given; an unsupported flag fails
35    /// the pool or session rather than disappearing.
36    pub frames_usage: u32,
37    /// `VkImage` handles backing one frame. One means a single multi-planar
38    /// image and a per-plane copy.
39    pub images_per_frame: usize,
40    /// Initial layout `FFmpeg` left the frame in.
41    pub initial_layout: u32,
42    /// Queue family owning the frame, or `u32::MAX` for `VK_QUEUE_FAMILY_IGNORED`.
43    pub queue_family: u32,
44    /// Whether the frame exposes a timeline semaphore for the handoff.
45    pub has_timeline_semaphore: bool,
46    /// Packets drained from one submitted frame plus a flush.
47    pub packets: u32,
48    /// Bytes in those packets.
49    pub packet_bytes: u32,
50}
51
52/// Opens `h264_vulkan` against `device` and encodes one untouched pool frame.
53///
54/// # Errors
55/// Returns an adapter failure when the encoder is absent, the pool cannot be created, the session
56/// cannot open, or no packet is produced.
57pub fn probe_vulkan_encode(
58    device: &AVHWDeviceContext,
59    width: u32,
60    height: u32,
61) -> Result<VulkanEncodeProbe, EncodeError> {
62    let encoder = AVCodec::find_encoder_by_name(c"h264_vulkan").ok_or_else(|| {
63        EncodeError::Adapter("this FFmpeg runtime has no h264_vulkan encoder".into())
64    })?;
65    let coded_width =
66        i32::try_from(width).map_err(|_| EncodeError::Adapter("width is out of range".into()))?;
67    let coded_height =
68        i32::try_from(height).map_err(|_| EncodeError::Adapter("height is out of range".into()))?;
69
70    let mut frames = vulkan_encode_frames(device, coded_width, coded_height)?;
71    let frames_usage = alpha2_ffmpeg_bridge::vulkan_frames_usage(&frames);
72
73    let mut context = AVCodecContext::new(&encoder);
74    context.set_width(coded_width);
75    context.set_height(coded_height);
76    context.set_pix_fmt(ffi::AV_PIX_FMT_VULKAN);
77    // `ff_encode_preinit` copies the pool's `sw_format` into `sw_pix_fmt` and rejects a different
78    // caller-set value, so it stays unset.
79    context.set_time_base(ra(1, 30));
80    context.set_framerate(ra(30, 1));
81    context.set_bit_rate(12_000_000);
82    context.set_gop_size(12);
83    context.set_max_b_frames(0);
84    context.set_hw_frames_ctx(frames.clone());
85    context
86        .open(None)
87        .map_err(|error| encode_adapter_error_at_open("h264_vulkan", &error))?;
88
89    let mut frame = AVFrame::new();
90    frames
91        .get_buffer(&mut frame)
92        .map_err(encode_adapter_error)?;
93    let descriptor =
94        alpha2_ffmpeg_bridge::vulkan_frame_info(&frame).map_err(encode_adapter_error)?;
95    frame.set_pts(0);
96
97    context
98        .send_frame(Some(&frame))
99        .map_err(encode_adapter_error)?;
100    context.send_frame(None).map_err(encode_adapter_error)?;
101    let mut packets = 0;
102    let mut packet_bytes = 0_u32;
103    loop {
104        match context.receive_packet() {
105            Ok(packet) => {
106                packets += 1;
107                packet_bytes = packet_bytes.saturating_add(packet.size.unsigned_abs());
108            }
109            Err(RsmpegError::EncoderDrainError | RsmpegError::EncoderFlushedError) => break,
110            Err(error) => return Err(encode_adapter_error(error)),
111        }
112    }
113    if packets == 0 {
114        return Err(EncodeError::Adapter(
115            "h264_vulkan opened but produced no packet".into(),
116        ));
117    }
118    Ok(VulkanEncodeProbe {
119        encoder: encoder.name().to_string_lossy().into_owned(),
120        coded_size: (
121            descriptor.coded_width.unsigned_abs(),
122            descriptor.coded_height.unsigned_abs(),
123        ),
124        frames_usage,
125        images_per_frame: descriptor.plane_count as usize,
126        initial_layout: descriptor.layouts[0],
127        queue_family: descriptor.queue_families[0],
128        has_timeline_semaphore: descriptor.semaphores[0] != 0,
129        packets,
130        packet_bytes,
131    })
132}
133
134/// Opens a Vulkan encoder with one rate-control request and encodes one pool frame, on
135/// a device `FFmpeg` creates.
136///
137/// It passes if it opened, consumed every option and produced a packet. `FFmpeg` checks the mode
138/// against `VkVideoEncodeCapabilitiesKHR::rateControlModes` at open.
139pub(crate) fn probe_vulkan_rate_control(
140    encoder: &rsmpeg::avcodec::AVCodecRef<'static>,
141    width: u32,
142    height: u32,
143    request: &crate::rate_control::MechanismRequest,
144) -> Result<(u32, String), String> {
145    // Pass the pinned device by loader index: `FFmpeg` reads a leading digit as an index, so an
146    // `ALPHA2_GPU_ADAPTER` name cannot pass through. Without a pin, walk the indices until one
147    // accepts or refuses the mode, since only some devices have an encode queue.
148    let pinned = alpha2_native_gpu::adapter_pinned();
149    let shared = alpha2_native_gpu::shared_device_index();
150    let candidates = match (pinned, shared) {
151        (true, Ok(index)) => vec![index.to_string()],
152        (true, Err(error)) => return Err(error.to_string()),
153        (false, shared) => {
154            let first = shared.ok();
155            first
156                .into_iter()
157                .chain((0..8).filter(|index| Some(*index) != first))
158                .map(|index| index.to_string())
159                .collect::<Vec<_>>()
160        }
161    };
162    let mut last = "no Vulkan device".to_owned();
163    for device in candidates {
164        match probe_vulkan_rate_control_on(encoder, &device, width, height, request) {
165            Ok(packets) => return Ok((packets, device)),
166            Err(VulkanProbeError::NoDevice(error)) => {
167                last = error;
168                break;
169            }
170            Err(VulkanProbeError::NoEncodeQueue(error)) if !pinned => last = error,
171            Err(VulkanProbeError::NoEncodeQueue(error) | VulkanProbeError::Refused(error)) => {
172                return Err(format!("on Vulkan device {device}: {error}"));
173            }
174        }
175    }
176    Err(last)
177}
178
179enum VulkanProbeError {
180    /// No device at this index; the walk is over.
181    NoDevice(String),
182    /// The device has no video-encode queue; another one might.
183    NoEncodeQueue(String),
184    /// The device got as far as the encoder, which refused.
185    Refused(String),
186}
187
188fn probe_vulkan_rate_control_on(
189    encoder: &rsmpeg::avcodec::AVCodecRef<'static>,
190    device_name: &str,
191    width: u32,
192    height: u32,
193    request: &crate::rate_control::MechanismRequest,
194) -> Result<u32, VulkanProbeError> {
195    let device_name = CString::new(device_name)
196        .map_err(|_| VulkanProbeError::NoDevice("device name contains a NUL byte".to_owned()))?;
197    // `FFmpeg` enables video-encode extensions on its own device only when asked; the shared export
198    // device asks through wgpu.
199    let extensions = rsmpeg::avutil::AVDictionary::new(
200        c"device_extensions",
201        c"VK_KHR_video_queue+VK_KHR_video_encode_queue+VK_KHR_video_encode_h264+VK_KHR_video_encode_h265+VK_KHR_video_encode_av1+VK_KHR_video_maintenance1",
202        0,
203    );
204    let device = AVHWDeviceContext::create(
205        ffi::AV_HWDEVICE_TYPE_VULKAN,
206        Some(&device_name),
207        Some(&extensions),
208        0,
209    )
210    .map_err(|error| VulkanProbeError::NoDevice(format!("no Vulkan device: {error}")))?;
211    let refused = |error: String| VulkanProbeError::Refused(error);
212    let coded_width =
213        i32::try_from(width).map_err(|_| refused("width is out of range".to_owned()))?;
214    let coded_height =
215        i32::try_from(height).map_err(|_| refused("height is out of range".to_owned()))?;
216    let mut frames = vulkan_encode_frames(&device, coded_width, coded_height)
217        .map_err(|error| VulkanProbeError::NoEncodeQueue(error.to_string()))?;
218    let mut context = AVCodecContext::new(encoder);
219    context.set_width(coded_width);
220    context.set_height(coded_height);
221    context.set_pix_fmt(ffi::AV_PIX_FMT_VULKAN);
222    context.set_time_base(ra(1, 30));
223    context.set_framerate(ra(30, 1));
224    context.set_bit_rate(request.bit_rate);
225    context.set_gop_size(12);
226    context.set_max_b_frames(0);
227    context.set_hw_frames_ctx(frames.clone());
228    let unused = alpha2_ffmpeg_bridge::open_codec_context(
229        &mut context,
230        request.dictionary(crate::convert::color_options(ColorMetadata::EXPORT)),
231    )
232    .map_err(|error| {
233        // `ENOSYS` means no encode queue at all, which says nothing about the mode.
234        let message = error.to_string();
235        if matches!(error, RsmpegError::AVError(code) if code == -38) {
236            VulkanProbeError::NoEncodeQueue(message)
237        } else {
238            refused(message)
239        }
240    })?;
241    crate::convert::reject_unused_encode_options(unused)
242        .map_err(|error| refused(error.to_string()))?;
243    let mut frame = AVFrame::new();
244    frames
245        .get_buffer(&mut frame)
246        .map_err(|error| refused(error.to_string()))?;
247    frame.set_pts(0);
248    context
249        .send_frame(Some(&frame))
250        .map_err(|error| refused(error.to_string()))?;
251    context
252        .send_frame(None)
253        .map_err(|error| refused(error.to_string()))?;
254    let mut packets = 0;
255    loop {
256        match context.receive_packet() {
257            Ok(_) => packets += 1,
258            Err(RsmpegError::EncoderDrainError | RsmpegError::EncoderFlushedError) => break,
259            Err(error) => return Err(refused(error.to_string())),
260        }
261    }
262    if packets == 0 {
263        return Err(refused("opened but produced no packet".to_owned()));
264    }
265    Ok(packets)
266}
267
268/// The `FFmpeg` Vulkan encoder of `codec`, and the name the device's codec list gives it.
269const fn vulkan_encoder(codec: NativeVideoCodec) -> Option<(&'static str, &'static str)> {
270    match codec {
271        NativeVideoCodec::H264 => Some(("h264_vulkan", "h264")),
272        NativeVideoCodec::Hevc => Some(("hevc_vulkan", "hevc")),
273        _ => None,
274    }
275}
276
277/// The capability a report leads with: the first of H.264 and HEVC this device encodes.
278pub(super) fn preferred_capability(
279    shared: &alpha2_native_gpu::SharedVulkanContext,
280) -> Result<HardwareEncodeCapability, String> {
281    capability(shared, NativeVideoCodec::H264)
282        .or_else(|h264| capability(shared, NativeVideoCodec::Hevc).map_err(|_| h264))
283}
284
285/// What this device's Vulkan encoder of `codec` accepts, from the device's own answers.
286pub(super) fn capability(
287    shared: &alpha2_native_gpu::SharedVulkanContext,
288    codec: NativeVideoCodec,
289) -> Result<HardwareEncodeCapability, String> {
290    if shared.encode_codecs().is_empty() {
291        return Err("this Vulkan device has no video-encode queue".to_owned());
292    }
293    let Some((encoder, listed)) = vulkan_encoder(codec) else {
294        return Err(format!(
295            "Vulkan Video encodes h264 and hevc, not {}",
296            codec.as_str()
297        ));
298    };
299    if !shared.encode_codecs().contains(&listed) {
300        return Err(format!(
301            "this Vulkan device has no video encoder for {} (it encodes {})",
302            codec.as_str(),
303            shared.encode_codecs().join(", ")
304        ));
305    }
306    let extent = shared.encode_extent(listed).ok_or_else(|| {
307        format!(
308            "this device did not report its {} encode extents",
309            codec.as_str()
310        )
311    })?;
312    Ok(HardwareEncodeCapability {
313        backend: HardwareEncodeBackend::Vulkan,
314        encoder,
315        codec,
316        gpu_input_only: true,
317        input_layout: EncoderInputLayout::Nv12,
318        handoff: EncoderInputHandoff::GpuCopy,
319        shares_renderer_device: true,
320        minimum: extent.minimum,
321        maximum: extent.maximum,
322        granularity: extent.granularity,
323        max_p_picture_l0_references: Some(extent.max_p_picture_l0_references),
324        max_b_picture_l0_references: Some(extent.max_b_picture_l0_references),
325        max_l1_references: Some(extent.max_l1_references),
326        rate_control_modes: extent.rate_control_modes.clone(),
327        plane_ring_slots: alpha2_native_gpu::VulkanEncodeCopier::slots(),
328        // The copier keeps each copied frame until its slot is reused.
329        handoff_retained_surfaces: alpha2_native_gpu::VulkanEncodeCopier::slots(),
330        // Measured: the pool never exceeded the host's leases plus the copier's slots.
331        codec_retained_surfaces: 0,
332    })
333}
334
335/// Opens the Vulkan encoder of `request.codec` on the shared device, its input half, and the
336/// output.
337pub(super) fn open(
338    shared: &alpha2_native_gpu::SharedVulkanContext,
339    request: &HardwareEncodeRequest<'_>,
340    generation: u64,
341) -> Result<(VulkanEncodeSession, VulkanEncodeInput), HardwareEncodeOpenError> {
342    let refused = |error: EncodeError| HardwareEncodeOpenError::Refused(error.to_string());
343    let (width, height) = (request.width, request.height);
344    let frame_rate = super::session_frame_rate(request.frame_rate).map_err(refused)?;
345    let (encoder, _) = vulkan_encoder(request.codec).ok_or_else(|| {
346        HardwareEncodeOpenError::Refused(format!(
347            "Vulkan Video does not encode {}",
348            request.codec.as_str()
349        ))
350    })?;
351    let mark = alpha2_ffmpeg_bridge::log_mark();
352    let (frames, context, selection) = open_encoder(
353        &shared.ffmpeg_device(),
354        encoder,
355        width,
356        height,
357        request.rate_control,
358        frame_rate,
359        request.color,
360    )
361    .map_err(|error| super::open_refusal(encoder, mark, &error))?;
362    let time_base = ra(frame_rate.1, frame_rate.0);
363    // HEVC uses the bitstream filter chain: `hevc_metadata` writes the colour into every parameter
364    // set and `extract_extradata` keeps them out of the packets, as `hvc1` requires. H.264 keeps
365    // the session's own in-band and header parameter sets.
366    let bitstream = (request.codec == NativeVideoCodec::Hevc)
367        .then(|| EncodedVideoFilter::in_band(&context.extract_codecpar(), request.color, time_base))
368        .transpose()
369        .map_err(refused)?;
370    let copier = alpha2_native_gpu::VulkanEncodeCopier::new(shared)
371        .map_err(|error| HardwareEncodeOpenError::Refused(format!("{error:?}")))?;
372    let gpu = shared.gpu();
373    // One pair per copier slot: the coordinator runs ahead of the encoder, so one pair would let
374    // the next render overwrite planes a copy is still reading.
375    let planes = (0..alpha2_native_gpu::VulkanEncodeCopier::slots())
376        .map(|_| {
377            super::Nv12Planes::new(
378                &plane_texture(
379                    gpu.device(),
380                    "alpha2 NV12 luma",
381                    width,
382                    height,
383                    wgpu::TextureFormat::R8Unorm,
384                ),
385                &plane_texture(
386                    gpu.device(),
387                    "alpha2 NV12 chroma",
388                    width / 2,
389                    height / 2,
390                    wgpu::TextureFormat::Rg8Unorm,
391                ),
392            )
393        })
394        .collect();
395    let input = VulkanEncodeInput {
396        copier,
397        planes,
398        frames,
399        size: (width, height),
400        time_base,
401        color: request.color,
402        stats: EncoderPoolStats::default(),
403        images: HashSet::new(),
404    };
405    // From here a failure is the export's, since the partial output exists. A filtered stream's
406    // header waits for the parameter sets in its first packet.
407    let muxer = if bitstream.is_some() {
408        Muxer::open_deferred(
409            request.output,
410            request.container,
411            &context,
412            time_base,
413            request.audio,
414        )
415    } else {
416        Muxer::open(
417            request.output,
418            request.container,
419            &context,
420            time_base,
421            request.audio,
422        )
423    }
424    .map_err(HardwareEncodeOpenError::Failed)?;
425    Ok((
426        VulkanEncodeSession {
427            context,
428            time_base,
429            bitstream,
430            muxer,
431            stages: EncodeStageTimings::default(),
432            selection,
433            generation,
434        },
435        input,
436    ))
437}
438
439/// One renderer-owned NV12 plane target for the encode handoff.
440///
441/// `COPY_SRC` gives the image `VK_IMAGE_USAGE_TRANSFER_SRC` for the raw copy.
442fn plane_texture(
443    device: &wgpu::Device,
444    label: &'static str,
445    width: u32,
446    height: u32,
447    format: wgpu::TextureFormat,
448) -> wgpu::Texture {
449    device.create_texture(&wgpu::TextureDescriptor {
450        label: Some(label),
451        size: wgpu::Extent3d {
452            width,
453            height,
454            depth_or_array_layers: 1,
455        },
456        mip_level_count: 1,
457        sample_count: 1,
458        dimension: wgpu::TextureDimension::D2,
459        format,
460        usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
461        view_formats: &[],
462    })
463}
464
465/// Opens `encoder` (`h264_vulkan` or `hevc_vulkan`) on `device` with an NV12 encoder-input pool.
466fn open_encoder(
467    device: &AVHWDeviceContext,
468    encoder_name: &'static str,
469    width: u32,
470    height: u32,
471    rate_control: alpha2_media::VideoRateControl,
472    frame_rate: (i32, i32),
473    color: ColorMetadata,
474) -> Result<
475    (
476        AVHWFramesContext,
477        AVCodecContext,
478        crate::NativeVideoEncoderSelection,
479    ),
480    EncodeError,
481> {
482    let encoder = CString::new(encoder_name)
483        .ok()
484        .and_then(|name| AVCodec::find_encoder_by_name(&name))
485        .ok_or_else(|| {
486            EncodeError::Adapter(format!("this FFmpeg runtime has no {encoder_name} encoder"))
487        })?;
488    let coded_width =
489        i32::try_from(width).map_err(|_| EncodeError::Adapter("width is out of range".into()))?;
490    let coded_height =
491        i32::try_from(height).map_err(|_| EncodeError::Adapter("height is out of range".into()))?;
492    let frames = vulkan_encode_frames(device, coded_width, coded_height)?;
493    let rate = u32::try_from(frame_rate.0)
494        .ok()
495        .zip(u32::try_from(frame_rate.1).ok())
496        .and_then(|(num, den)| alpha2_time::FrameRate::new(num, den).ok())
497        .ok_or_else(|| EncodeError::Adapter("frame rate is out of range".into()))?;
498    let open = |quantized: Option<&crate::rate_control::MechanismRequest>| {
499        let mut context = AVCodecContext::new(&encoder);
500        context.set_width(coded_width);
501        context.set_height(coded_height);
502        context.set_pix_fmt(ffi::AV_PIX_FMT_VULKAN);
503        // `ff_encode_preinit` copies the pool's `sw_format` into `sw_pix_fmt` and rejects a
504        // different caller-set value.
505        context.set_time_base(ra(frame_rate.1, frame_rate.0));
506        context.set_framerate(ra(frame_rate.0, frame_rate.1));
507        context.set_bit_rate(quantized.map_or_else(
508            || i64::try_from(rate_control.bitrate).unwrap_or(i64::MAX),
509            |quantized| quantized.bit_rate,
510        ));
511        context.set_gop_size(crate::capabilities::keyframe_interval(rate));
512        // No B pictures: at a fixed rate two B frames cost up to about 0.6 dB PSNR-Y against none.
513        context.set_max_b_frames(0);
514        context.set_hw_frames_ctx(frames.clone());
515        // The flag is read at open, so set it first or the parameter sets travel in-band only.
516        context.set_flags(
517            context.flags | i32::try_from(ffi::AV_CODEC_FLAG_GLOBAL_HEADER).unwrap_or(0),
518        );
519        // Without these the stream has no VUI and decoders guess the colour.
520        let color = crate::convert::color_options(color);
521        let options = match quantized {
522            Some(quantized) => quantized.dictionary(color),
523            None => crate::rate_control::rate_control_options(encoder_name, rate_control, color),
524        };
525        let unused = alpha2_ffmpeg_bridge::open_codec_context(&mut context, options)
526            .map_err(|error| encode_adapter_error_at_open(encoder_name, &error))?;
527        crate::convert::reject_unused_encode_options(unused)?;
528        if context.extradata_size <= 0 {
529            return Err(EncodeError::Adapter(format!(
530                "{encoder_name} opened without parameter-set extradata for the MP4 header"
531            )));
532        }
533        Ok::<_, EncodeError>(context)
534    };
535    // A refused quantizer falls back to bitrate on the same encoder, and the selection reports it.
536    let (context, applied, quantizer_refused) =
537        match crate::rate_control::quantizer_request(encoder_name, rate_control) {
538            Some(Ok(quantized)) => match open(Some(&quantized)) {
539                Ok(context) => (context, crate::AppliedRateControl::Quantizer, None),
540                Err(error) => (
541                    open(None)?,
542                    crate::AppliedRateControl::Bitrate,
543                    Some(format!("{} refused: {error}", quantized.describe())),
544                ),
545            },
546            Some(Err(reason)) => (
547                open(None)?,
548                crate::AppliedRateControl::Bitrate,
549                Some(reason),
550            ),
551            None => (open(None)?, crate::AppliedRateControl::Bitrate, None),
552        };
553    if let Some(reason) = &quantizer_refused {
554        alpha2_os::diagnostic!(
555            "alpha2 native export: {encoder_name} runs the bitrate fallback: {reason}"
556        );
557    }
558    // No candidate list: the encoder was chosen from the device.
559    let selection = crate::NativeVideoEncoderSelection {
560        encoder_name: encoder_name.to_owned(),
561        class: crate::NativeEncoderClass::Hardware,
562        hardware_accelerated: true,
563        rejected: Vec::new(),
564        rate_control: applied,
565        quantizer_refused,
566        software_threads: None,
567        pixels: alpha2_media::PixelLayout::YUV420P,
568    };
569    Ok((frames, context, selection))
570}
571
572/// The encode worker's half of a Vulkan session: the codec and the muxer.
573pub(super) struct VulkanEncodeSession {
574    context: AVCodecContext,
575    time_base: AVRational,
576    /// The filter chain an HEVC stream's packets pass through before the muxer.
577    bitstream: Option<EncodedVideoFilter>,
578    muxer: Muxer,
579    stages: EncodeStageTimings,
580    selection: crate::NativeVideoEncoderSelection,
581    generation: u64,
582}
583
584/// The coordinator's half of a Vulkan session.
585///
586/// The copy stays on the thread that rendered the planes, which owns the wgpu textures and render
587/// signal. The encoder-input pool is reference counted, so frames stay valid across threads.
588///
589/// Fields drop in declaration order and the copier comes first: dropping it waits on every
590/// in-flight copy (wgpu cannot track these raw copies), retaining resources if the wait times out.
591/// Dropping the planes first would free them under a running copy.
592pub(super) struct VulkanEncodeInput {
593    copier: alpha2_native_gpu::VulkanEncodeCopier,
594    planes: Vec<super::Nv12Planes>,
595    frames: AVHWFramesContext,
596    size: (u32, u32),
597    time_base: AVRational,
598    color: ColorMetadata,
599    stats: EncoderPoolStats,
600    /// The distinct images the pool has handed out, which equals what it allocated.
601    images: HashSet<u64>,
602}
603
604/// One frame taken from a Vulkan encoder-input pool.
605pub(super) struct VulkanEncoderFrame(AVFrame);
606
607impl VulkanEncoderFrame {
608    pub(super) fn set_pts(&mut self, pts: i64) {
609        self.0.set_pts(pts);
610    }
611}
612
613impl VulkanEncodeInput {
614    pub(super) fn descriptor(&self, generation: u64) -> EncoderSurfaceDescriptor {
615        EncoderSurfaceDescriptor {
616            backend: HardwareEncodeBackend::Vulkan,
617            pool_generation: generation,
618            layout: EncoderInputLayout::Nv12,
619            visible: self.size,
620            color: self.color,
621        }
622    }
623
624    /// Takes one frame from the encoder-input pool.
625    ///
626    /// The pool recycles an image once the host, encoder and copier (which keeps each frame until
627    /// its slot comes round) have all dropped it.
628    pub(super) fn acquire_frame(&mut self) -> Result<VulkanEncoderFrame, EncodeError> {
629        let mut frame = AVFrame::new();
630        self.frames
631            .get_buffer(&mut frame)
632            .map_err(encode_adapter_error)?;
633        let image = alpha2_ffmpeg_bridge::vulkan_frame_info(&frame)
634            .map_err(encode_adapter_error)?
635            .images[0];
636        self.images.insert(image);
637        self.stats.acquired = self.stats.acquired.saturating_add(1);
638        self.stats.allocated = u64::try_from(self.images.len()).unwrap_or(u64::MAX);
639        Ok(VulkanEncoderFrame(frame))
640    }
641
642    /// Waits until the plane pair the next copy reads is free. Submitting the pack render before
643    /// [`Self::submit`]'s copy on the same queue is what orders the two.
644    pub(super) fn begin_frame(&mut self) -> Result<InputFrame, EncodeError> {
645        let slot = self.copier.await_slot().map_err(encode_adapter_error)?;
646        if slot >= self.planes.len() {
647            return Err(EncodeError::Adapter(format!(
648                "encode copier reported slot {slot}"
649            )));
650        }
651        Ok(InputFrame { slot })
652    }
653
654    pub(super) fn planes(&self, frame: &InputFrame) -> (&wgpu::TextureView, &wgpu::TextureView) {
655        self.planes[frame.slot].views()
656    }
657
658    /// Copies `frame`'s planes into `backing`, signalling the frame's timeline semaphore
659    /// for the encoder to wait on.
660    // Taking the token by value enforces one submit per begun frame.
661    #[allow(clippy::needless_pass_by_value)]
662    pub(super) fn submit(
663        &mut self,
664        frame: InputFrame,
665        backing: &mut VulkanEncoderFrame,
666    ) -> Result<(), EncodeError> {
667        let InputFrame { slot } = frame;
668        let pair = &self.planes[slot];
669        let mut access = alpha2_ffmpeg_bridge::VulkanEncodeFrameAccess::begin(&mut backing.0)
670            .map_err(encode_adapter_error)?;
671        self.copier
672            .submit(
673                &mut access,
674                pair.luma.texture(),
675                pair.chroma.texture(),
676                self.size,
677            )
678            .map_err(encode_adapter_error)?;
679        self.stats.copy_operations = self.stats.copy_operations.saturating_add(2);
680        self.stats.copy_bytes = self
681            .stats
682            .copy_bytes
683            .saturating_add(EncoderInputLayout::Nv12.frame_bytes(self.size.0, self.size.1));
684        Ok(())
685    }
686
687    /// Presentation timestamp for the frame at `time`, in encoder ticks.
688    pub(super) fn timestamp(&self, time: MediaTime) -> i64 {
689        av_rescale_q(time.ticks(), tick_base(), self.time_base)
690    }
691
692    pub(super) const fn stats(&self) -> EncoderPoolStats {
693        self.stats
694    }
695
696    /// Waits on every copy's fence before the plane textures it reads drop.
697    pub(super) fn finish(self) -> Result<(), EncodeError> {
698        let Self { copier, planes, .. } = self;
699        copier.finish().map_err(encode_adapter_error)?;
700        drop(planes);
701        Ok(())
702    }
703}
704
705impl VulkanEncodeSession {
706    pub(super) const fn selection(&self) -> &crate::NativeVideoEncoderSelection {
707        &self.selection
708    }
709
710    pub(super) fn stage_timings(&self) -> EncodeStageTimings {
711        self.muxer.with_audio_timings(self.stages)
712    }
713
714    /// Submits `frame` and muxes whatever packets it produced.
715    pub(super) fn encode(
716        &mut self,
717        generation: u64,
718        frame: &VulkanEncoderFrame,
719    ) -> Result<(), EncodeError> {
720        if generation != self.generation {
721            return Err(EncodeError::Adapter(format!(
722                "encoder surface from pool {generation} reached session {}",
723                self.generation
724            )));
725        }
726        timed(&mut self.stages.video_send_frame, || {
727            self.context.send_frame(Some(&frame.0))
728        })
729        .map_err(encode_adapter_error)?;
730        self.drain()
731    }
732
733    pub(super) fn write_audio(
734        &mut self,
735        block: &alpha2_media::AudioBlock,
736    ) -> Result<(), EncodeError> {
737        self.muxer.write_audio(block, &mut self.stages)
738    }
739
740    /// Flushes audio and encoder, then closes the output, which renames
741    /// the partial file into place.
742    pub(super) fn finish(&mut self, cancel: &alpha2_media::CancelToken) -> Result<(), EncodeError> {
743        // Every audio packet must exist before the muxer decides the final interleave.
744        self.muxer.finish_audio()?;
745        crate::encode::beat_encode_call();
746        self.context
747            .send_frame(None)
748            .map_err(encode_adapter_error)?;
749        self.drain()?;
750        if let Some(bitstream) = &mut self.bitstream {
751            for mut packet in bitstream.flush()? {
752                self.muxer.write_video(&mut packet, self.time_base)?;
753            }
754        }
755        self.muxer.write_ready_audio(true, &mut self.stages)?;
756        self.muxer.close(cancel)
757    }
758
759    pub(super) fn publish_report(&self) -> Option<crate::PublishReport> {
760        self.muxer.publish_report()
761    }
762
763    pub(super) fn abort(&mut self) {
764        self.muxer.abort();
765    }
766
767    fn drain(&mut self) -> Result<(), EncodeError> {
768        loop {
769            let received = timed(&mut self.stages.video_receive_packet, || {
770                self.context.receive_packet()
771            });
772            match received {
773                Ok(mut packet) => match &mut self.bitstream {
774                    Some(bitstream) => {
775                        for mut packet in bitstream.filter(packet)? {
776                            self.muxer.write_video(&mut packet, self.time_base)?;
777                        }
778                    }
779                    None => self.muxer.write_video(&mut packet, self.time_base)?,
780                },
781                Err(RsmpegError::EncoderDrainError | RsmpegError::EncoderFlushedError) => {
782                    return self.muxer.write_ready_audio(false, &mut self.stages);
783                }
784                Err(error) => return Err(encode_adapter_error(error)),
785            }
786        }
787    }
788}
789
790/// Builds the encoder-input pool.
791///
792/// `avcodec_get_hw_frames_parameters` answers `ENOENT` for encoders, so the pool is described here.
793/// The Vulkan encoder requests no image usage, so the pool gets the export's
794/// (`vulkan_frames_add_usage`) before init.
795fn vulkan_encode_frames(
796    device: &AVHWDeviceContext,
797    width: i32,
798    height: i32,
799) -> Result<AVHWFramesContext, EncodeError> {
800    let mut frames = device.hwframe_ctx_alloc();
801    {
802        let data = frames.data();
803        data.format = ffi::AV_PIX_FMT_VULKAN;
804        data.sw_format = ffi::AV_PIX_FMT_NV12;
805        data.width = width;
806        data.height = height;
807        data.initial_pool_size = 0;
808    }
809    alpha2_ffmpeg_bridge::vulkan_frames_add_usage(
810        &mut frames,
811        alpha2_ffmpeg_bridge::VULKAN_ENCODE_INPUT_USAGE,
812    )
813    .map_err(encode_adapter_error)?;
814    frames.init().map_err(encode_adapter_error)?;
815    Ok(frames)
816}
817
818fn encode_adapter_error_at_open(encoder: &str, error: &RsmpegError) -> EncodeError {
819    EncodeError::Adapter(format!("{encoder} session could not open: {error}"))
820}