Skip to main content

alpha2_native/hwencode/
mod.rs

1//! Hardware video encode from renderer-packed planes.
2//!
3//! The contract every GPU-resident export backend implements, opened on the renderer's device and
4//! split across two threads:
5//!
6//! - [`HardwareEncodeInput`] (coordinator): hands out encoder surfaces, names the plane textures
7//!   the renderer packs into, and moves those planes into the surface on the GPU.
8//! - [`HardwareEncodeSession`] (encode worker): submits surfaces to the encoder and muxes the
9//!   packets, with audio, into a transactional output file.
10//!
11//! A surface moves `acquire -> begin -> (render) -> submit -> encode` and is reused only after
12//! every GPU access and codec reference is released. The backend enforces this; dropping the host's
13//! last handle does not mean nothing still reads the image.
14// Platforms without a backend compile the contract with nothing behind it, so the host
15// loop is the same everywhere.
16#![cfg_attr(
17    not(any(target_os = "linux", target_os = "macos", target_os = "windows")),
18    allow(dead_code, unused_variables, clippy::needless_pass_by_value)
19)]
20
21#[cfg(target_os = "windows")]
22mod d3d12va;
23#[cfg(target_os = "macos")]
24mod videotoolbox;
25#[cfg(target_os = "linux")]
26mod vulkan;
27
28use std::sync::atomic::{AtomicU64, Ordering};
29
30use alpha2_media::{ColorMetadata, EncodeError, VideoRateControl};
31use alpha2_time::{FrameRate, MediaTime};
32
33#[cfg(all(test, target_os = "windows"))]
34pub(crate) use d3d12va::encode_no_rate_control_frames;
35#[cfg(target_os = "windows")]
36pub(crate) use d3d12va::probe_d3d12va_rate_control;
37#[cfg(target_os = "windows")]
38pub use d3d12va::{
39    D3D12EncodeProbe, D3D12RateControlOpen, D3D12RateControlRunner, D3D12TestEncodeRunner,
40    D3D12VA_TEST_ENCODE_SIZE, d3d12va_busy, d3d12va_encoder, d3d12va_timeouts,
41    open_d3d12va_rate_control, probe_d3d12va_encode, set_d3d12va_rate_control_runner,
42    set_d3d12va_test_encode_runner,
43};
44#[cfg(target_os = "macos")]
45pub use videotoolbox::{VideoToolboxEncodeProbe, probe_videotoolbox_encode};
46#[cfg(target_os = "linux")]
47pub(crate) use vulkan::probe_vulkan_rate_control;
48#[cfg(target_os = "linux")]
49pub use vulkan::{VulkanEncodeProbe, probe_vulkan_encode};
50
51use crate::{EncodeStageTimings, NativeVideoCodec, NativeVideoEncoderSelection};
52
53/// The native API a hardware encode session drives.
54#[derive(Copy, Clone, Debug, Eq, PartialEq)]
55pub enum HardwareEncodeBackend {
56    /// `FFmpeg`'s Vulkan video encoders on the renderer's Vulkan device.
57    Vulkan,
58    /// `FFmpeg`'s `VideoToolbox` encoders reading `IOSurface`s the renderer's `Metal` device draws.
59    VideoToolbox,
60    /// `FFmpeg`'s D3D12 Video encoders on the renderer's D3D12 device.
61    D3D12Va,
62}
63
64impl HardwareEncodeBackend {
65    /// Stable identifier used by capability reports and export results.
66    #[must_use]
67    pub const fn as_str(self) -> &'static str {
68        match self {
69            Self::Vulkan => "vulkan",
70            Self::VideoToolbox => "videotoolbox",
71            Self::D3D12Va => "d3d12va",
72        }
73    }
74}
75
76/// How the pixels of an encoder-input surface are laid out.
77#[derive(Copy, Clone, Debug, Eq, PartialEq)]
78pub enum EncoderInputLayout {
79    /// 8-bit 4:2:0: a full-size luma plane and a half-size interleaved chroma plane.
80    Nv12,
81}
82
83impl EncoderInputLayout {
84    /// Stable identifier used by capability reports.
85    #[must_use]
86    pub const fn as_str(self) -> &'static str {
87        match self {
88            Self::Nv12 => "nv12",
89        }
90    }
91
92    /// Bytes one visible frame of this layout holds, without padding.
93    #[must_use]
94    pub const fn frame_bytes(self, width: u32, height: u32) -> u64 {
95        match self {
96            Self::Nv12 => {
97                let luma = width as u64 * height as u64;
98                luma + luma / 2
99            }
100        }
101    }
102}
103
104/// How a packed frame reaches the encoder's surface.
105#[derive(Copy, Clone, Debug, Eq, PartialEq)]
106pub enum EncoderInputHandoff {
107    /// The renderer packs into its own plane textures and a GPU copy moves them into the surface.
108    GpuCopy,
109    /// The renderer packs straight into the surface's planes, with no ring and no copy.
110    DirectTarget,
111}
112
113impl EncoderInputHandoff {
114    /// Stable identifier used by capability reports.
115    #[must_use]
116    pub const fn as_str(self) -> &'static str {
117        match self {
118            Self::GpuCopy => "gpu-copy",
119            Self::DirectTarget => "direct-target",
120        }
121    }
122}
123
124/// What one hardware encoder accepts on this device, read from the device.
125#[derive(Clone, Debug, Eq, PartialEq)]
126pub struct HardwareEncodeCapability {
127    /// The native API the session drives.
128    pub backend: HardwareEncodeBackend,
129    /// The `FFmpeg` encoder a session opens.
130    pub encoder: &'static str,
131    /// The codec it encodes.
132    pub codec: NativeVideoCodec,
133    /// Whether the encoder takes GPU frames only. Pinning such an encoder selects this path; one
134    /// the readback path can also feed (`h264_videotoolbox`) can be pinned on either.
135    pub gpu_input_only: bool,
136    /// The surface layout it takes.
137    pub input_layout: EncoderInputLayout,
138    /// How a packed frame reaches its surface.
139    pub handoff: EncoderInputHandoff,
140    /// Whether the encoder runs on the renderer's own device. Backends needing a cross-device copy
141    /// are not offered as GPU-resident.
142    pub shares_renderer_device: bool,
143    /// Smallest accepted coded width and height.
144    pub minimum: (u32, u32),
145    /// Largest accepted coded width and height.
146    pub maximum: (u32, u32),
147    /// Granularity the output size is aligned up to before the limits apply.
148    pub granularity: (u32, u32),
149    /// References a P picture may use, when the device reports it.
150    pub max_p_picture_l0_references: Option<u32>,
151    /// Forward references a B picture may use; zero with `max_l1_references` zero means no B
152    /// pictures. `None` when not reported.
153    pub max_b_picture_l0_references: Option<u32>,
154    /// Backward references a B picture may use, when the device reports it.
155    pub max_l1_references: Option<u32>,
156    /// The rate-control modes the device reports: `cbr`, `vbr`, `disabled` (constant
157    /// quantizer), and on D3D12 `qvbr`.
158    pub rate_control_modes: Vec<&'static str>,
159    /// Plane-texture pairs the renderer packs into, allocated for the whole session. Zero when it
160    /// packs into the surfaces themselves.
161    pub plane_ring_slots: usize,
162    /// Surfaces the handoff may still hold after the host released them (a copying backend keeps
163    /// each until its slot comes round). Allocated on top of the host's, so budgets count them.
164    pub handoff_retained_surfaces: usize,
165    /// Surfaces the encoder holds after accepting them, until consumed. Also on top of the host's.
166    pub codec_retained_surfaces: usize,
167    /// The default encode channel depth (`ALPHA2_ENCODE_QUEUE_DEPTH` overrides): the smallest depth
168    /// within 3 % of the best measured per-frame time on this backend.
169    pub default_channel_depth: usize,
170}
171
172impl HardwareEncodeCapability {
173    /// Every surface the pool may hold beyond those the host has leased.
174    #[must_use]
175    pub const fn retained_surfaces(&self) -> usize {
176        self.handoff_retained_surfaces
177            .saturating_add(self.codec_retained_surfaces)
178    }
179}
180
181impl HardwareEncodeCapability {
182    /// The coded extent an output of this size is encoded at.
183    #[must_use]
184    pub const fn coded(&self, width: u32, height: u32) -> (u32, u32) {
185        (
186            align_up(width, self.granularity.0),
187            align_up(height, self.granularity.1),
188        )
189    }
190
191    /// Whether an output of this size can be encoded, and if not, why.
192    ///
193    /// # Errors
194    /// Names the limit the size misses.
195    pub fn accepts(&self, width: u32, height: u32) -> Result<(), String> {
196        if !width.is_multiple_of(2) || !height.is_multiple_of(2) {
197            return Err(format!(
198                "a {width}x{height} output has no 4:2:0 chroma plane"
199            ));
200        }
201        let coded = self.coded(width, height);
202        if coded.0 < self.minimum.0
203            || coded.1 < self.minimum.1
204            || coded.0 > self.maximum.0
205            || coded.1 > self.maximum.1
206        {
207            return Err(format!(
208                "a {width}x{height} output codes as {}x{}, outside {}'s {}x{}..{}x{}",
209                coded.0,
210                coded.1,
211                self.encoder,
212                self.minimum.0,
213                self.minimum.1,
214                self.maximum.0,
215                self.maximum.1
216            ));
217        }
218        Ok(())
219    }
220}
221
222const fn align_up(value: u32, granularity: u32) -> u32 {
223    if granularity <= 1 {
224        return value;
225    }
226    value.div_ceil(granularity).saturating_mul(granularity)
227}
228
229/// The renderer's device, as a hardware encoder can use it.
230#[derive(Clone)]
231pub struct HardwareEncodeDevice {
232    #[cfg(target_os = "linux")]
233    vulkan: alpha2_native_gpu::SharedVulkanContext,
234    #[cfg(target_os = "macos")]
235    metal: alpha2_native_gpu::SharedMetalContext,
236    #[cfg(target_os = "windows")]
237    d3d12: alpha2_native_gpu::SharedD3D12Context,
238}
239
240impl std::fmt::Debug for HardwareEncodeDevice {
241    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242        formatter
243            .debug_struct("HardwareEncodeDevice")
244            .finish_non_exhaustive()
245    }
246}
247
248/// One export's encoder settings and output.
249#[derive(Clone, Debug)]
250pub struct HardwareEncodeRequest<'a> {
251    /// Output width, which must be even.
252    pub width: u32,
253    /// Output height, which must be even.
254    pub height: u32,
255    /// The codec to encode, one [`HardwareEncodeDevice::capability`] accepts.
256    pub codec: NativeVideoCodec,
257    /// The constant frame rate the stream is timed in.
258    pub frame_rate: FrameRate,
259    /// The resolved rate control.
260    pub rate_control: VideoRateControl,
261    /// The color the pack encodes and the stream is tagged with.
262    pub color: ColorMetadata,
263    /// Where the file goes and how an existing file is handled; a partial file sits
264    /// beside it until it finishes.
265    pub output: &'a crate::OutputTarget,
266    /// The file format, which must offer `codec` and the audio codec.
267    pub container: alpha2_media::Container,
268    /// The audio stream muxed beside the video, if any.
269    pub audio: Option<crate::AudioStreamConfig>,
270}
271
272/// A session's frame rate as `FFmpeg` takes it. Terms past `i32` are refused, as in the readback
273/// sinks, so the export falls back and fails there for the same reason.
274pub(crate) fn session_frame_rate(rate: FrameRate) -> Result<(i32, i32), EncodeError> {
275    match (
276        i32::try_from(rate.numerator()),
277        i32::try_from(rate.denominator()),
278    ) {
279        (Ok(numerator), Ok(denominator)) => Ok((numerator, denominator)),
280        _ => Err(EncodeError::Adapter(format!(
281            "frame rate {}/{} is out of range",
282            rate.numerator(),
283            rate.denominator()
284        ))),
285    }
286}
287
288/// A refusal of `encoder` to open, read from `error` and the lines it logged since `mark`; busy
289/// when its status says no session is free.
290#[cfg(any(target_os = "linux", target_os = "macos"))]
291fn open_refusal(
292    encoder: &str,
293    mark: alpha2_ffmpeg_bridge::LogMark,
294    error: &EncodeError,
295) -> HardwareEncodeOpenError {
296    let lines = alpha2_ffmpeg_bridge::log_since(mark, &[encoder]);
297    let error = error.to_string();
298    let reason = format!("{error}{}", alpha2_ffmpeg_bridge::log_detail(&lines));
299    match crate::capabilities::classify_open_failure(encoder, &error, &lines) {
300        alpha2_media::OpenFailureKind::Busy => HardwareEncodeOpenError::Busy(reason),
301        _ => HardwareEncodeOpenError::Refused(reason),
302    }
303}
304
305/// Why a hardware session did not open.
306#[derive(Debug)]
307pub enum HardwareEncodeOpenError {
308    /// The encoder refused before anything was written; another path can still take the export.
309    Refused(String),
310    /// The device has no session free (another export holds them), before anything was written.
311    /// Another path can still take the export, or this one once the other export ends.
312    Busy(String),
313    /// The output was being created when this failed; the export has failed.
314    Failed(EncodeError),
315}
316
317impl std::fmt::Display for HardwareEncodeOpenError {
318    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
319        match self {
320            Self::Refused(reason) | Self::Busy(reason) => formatter.write_str(reason),
321            Self::Failed(error) => write!(formatter, "{error}"),
322        }
323    }
324}
325
326impl HardwareEncodeDevice {
327    /// The shared Vulkan device the renderer runs on.
328    #[cfg(target_os = "linux")]
329    #[must_use]
330    pub const fn vulkan(context: alpha2_native_gpu::SharedVulkanContext) -> Self {
331        Self { vulkan: context }
332    }
333
334    /// The `Metal` device the renderer runs on.
335    #[cfg(target_os = "macos")]
336    #[must_use]
337    pub const fn metal(context: alpha2_native_gpu::SharedMetalContext) -> Self {
338        Self { metal: context }
339    }
340
341    /// The shared D3D12 device the renderer runs on.
342    #[cfg(target_os = "windows")]
343    #[must_use]
344    pub const fn d3d12(context: alpha2_native_gpu::SharedD3D12Context) -> Self {
345        Self { d3d12: context }
346    }
347
348    /// What this device's hardware encoder accepts for `codec`.
349    ///
350    /// Windows and Linux ask the device per codec; macOS has one hardware encoder, for H.264.
351    ///
352    /// # Errors
353    /// Says why this device has no usable hardware encoder for `codec`.
354    #[cfg_attr(
355        not(any(target_os = "linux", target_os = "macos", target_os = "windows")),
356        allow(clippy::unused_self)
357    )]
358    pub fn capability(&self, codec: NativeVideoCodec) -> Result<HardwareEncodeCapability, String> {
359        #[cfg(target_os = "windows")]
360        return d3d12va::capability(&self.d3d12, codec);
361        #[cfg(target_os = "linux")]
362        return vulkan::capability(&self.vulkan, codec);
363        #[cfg(target_os = "macos")]
364        {
365            let capability = self.preferred_capability()?;
366            if capability.codec == codec {
367                Ok(capability)
368            } else {
369                Err(format!(
370                    "{} encodes {}, not {}",
371                    capability.encoder,
372                    capability.codec.as_str(),
373                    codec.as_str()
374                ))
375            }
376        }
377        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
378        Err("this platform has no hardware encode backend yet".to_owned())
379    }
380
381    /// The capability a report leads with: the first of H.264, HEVC and AV1 the device encodes
382    /// (Windows, Linux), or the one encoder on macOS.
383    ///
384    /// # Errors
385    /// Says why this device has no usable hardware encoder at all.
386    #[cfg_attr(
387        not(any(target_os = "linux", target_os = "macos", target_os = "windows")),
388        allow(clippy::unused_self)
389    )]
390    pub fn preferred_capability(&self) -> Result<HardwareEncodeCapability, String> {
391        #[cfg(target_os = "linux")]
392        return vulkan::preferred_capability(&self.vulkan);
393        #[cfg(target_os = "macos")]
394        return videotoolbox::capability(&self.metal);
395        #[cfg(target_os = "windows")]
396        return d3d12va::preferred_capability(&self.d3d12);
397        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
398        Err("this platform has no hardware encode backend yet".to_owned())
399    }
400
401    /// Opens a session writing `request.output` and its input half.
402    ///
403    /// # Errors
404    /// [`HardwareEncodeOpenError::Refused`] before any output exists,
405    /// [`HardwareEncodeOpenError::Failed`] once creating it went wrong.
406    #[cfg_attr(
407        not(any(target_os = "linux", target_os = "macos", target_os = "windows")),
408        allow(clippy::unused_self)
409    )]
410    pub fn open(
411        &self,
412        request: &HardwareEncodeRequest<'_>,
413    ) -> Result<(HardwareEncodeSession, HardwareEncodeInput), HardwareEncodeOpenError> {
414        let generation = NEXT_POOL_GENERATION.fetch_add(1, Ordering::Relaxed);
415        // The D3D12VA backend checks the codec it is asked for itself.
416        #[cfg(any(target_os = "linux", target_os = "macos"))]
417        self.capability(request.codec)
418            .map_err(HardwareEncodeOpenError::Refused)?;
419        #[cfg(target_os = "linux")]
420        {
421            let (session, input) = vulkan::open(&self.vulkan, request, generation)?;
422            Ok((
423                HardwareEncodeSession(SessionBackend::Vulkan(session)),
424                HardwareEncodeInput {
425                    backend: InputBackend::Vulkan(input),
426                    generation,
427                },
428            ))
429        }
430        #[cfg(target_os = "macos")]
431        {
432            let (session, input) = videotoolbox::open(&self.metal, request, generation)?;
433            Ok((
434                HardwareEncodeSession(SessionBackend::VideoToolbox(session)),
435                HardwareEncodeInput {
436                    backend: InputBackend::VideoToolbox(input),
437                    generation,
438                },
439            ))
440        }
441        #[cfg(target_os = "windows")]
442        {
443            let (session, input) = d3d12va::open(&self.d3d12, request, generation)?;
444            Ok((
445                HardwareEncodeSession(SessionBackend::D3D12(session)),
446                HardwareEncodeInput {
447                    backend: InputBackend::D3D12(input),
448                    generation,
449                },
450            ))
451        }
452        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
453        {
454            let _ = (request, generation);
455            Err(HardwareEncodeOpenError::Refused(
456                "this platform has no hardware encode backend yet".to_owned(),
457            ))
458        }
459    }
460}
461
462/// Tags each pool so an old surface (after a cancel, resize or device loss) can
463/// never reach a new session.
464static NEXT_POOL_GENERATION: AtomicU64 = AtomicU64::new(1);
465
466/// What one encoder-input surface is, independent of its backing.
467#[derive(Copy, Clone, Debug, Eq, PartialEq)]
468pub struct EncoderSurfaceDescriptor {
469    /// The backend whose pool allocated it.
470    pub backend: HardwareEncodeBackend,
471    /// The session's pool; see [`HardwareEncodeInput::acquire_surface`].
472    pub pool_generation: u64,
473    /// Its pixel layout.
474    pub layout: EncoderInputLayout,
475    /// The picture's size.
476    pub visible: (u32, u32),
477    /// The color its pixels are encoded in.
478    pub color: ColorMetadata,
479}
480
481/// One encoder-input surface on loan from its session's pool.
482///
483/// Dropping it returns the backend's reference; the backend still decides
484/// when the backing is reusable.
485pub struct EncoderSurface {
486    descriptor: EncoderSurfaceDescriptor,
487    backing: SurfaceBacking,
488}
489
490enum SurfaceBacking {
491    #[cfg(target_os = "linux")]
492    Vulkan(vulkan::VulkanEncoderFrame),
493    #[cfg(target_os = "macos")]
494    VideoToolbox(videotoolbox::VideoToolboxEncoderFrame),
495    #[cfg(target_os = "windows")]
496    D3D12(d3d12va::D3D12EncoderFrame),
497    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
498    Unsupported(std::convert::Infallible),
499}
500
501impl EncoderSurface {
502    /// What this surface is.
503    #[must_use]
504    pub const fn descriptor(&self) -> &EncoderSurfaceDescriptor {
505        &self.descriptor
506    }
507}
508
509/// A begun frame whose planes belong to the renderer until [`HardwareEncodeInput::submit`].
510#[must_use = "a begun frame must be submitted, or its planes stay claimed"]
511pub struct InputFrame {
512    /// The plane pair of the copier's ring the frame is packed into.
513    #[cfg(any(target_os = "linux", target_os = "windows"))]
514    slot: usize,
515    /// The surface whose own planes the frame is packed into.
516    #[cfg(target_os = "macos")]
517    pixel_buffer: usize,
518}
519
520/// Surface-pool counters for one session.
521#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
522pub struct EncoderPoolStats {
523    /// Surfaces handed out.
524    pub acquired: u64,
525    /// Distinct backings allocated. Beyond the host's frames, this counts what the encoder and GPU
526    /// copy still referenced when the next surface was requested.
527    pub allocated: u64,
528    /// Handoffs into a surface: a plane copy each on a copying backend.
529    pub copy_operations: u64,
530    /// The bytes those handoffs moved.
531    pub copy_bytes: u64,
532}
533
534/// The coordinator's half of a hardware session.
535pub struct HardwareEncodeInput {
536    backend: InputBackend,
537    generation: u64,
538}
539
540enum InputBackend {
541    #[cfg(target_os = "linux")]
542    Vulkan(vulkan::VulkanEncodeInput),
543    #[cfg(target_os = "macos")]
544    VideoToolbox(videotoolbox::VideoToolboxEncodeInput),
545    #[cfg(target_os = "windows")]
546    D3D12(d3d12va::D3D12EncodeInput),
547    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
548    Unsupported(std::convert::Infallible),
549}
550
551impl HardwareEncodeInput {
552    /// Takes one surface from the session's pool.
553    ///
554    /// The pool allocates on demand, so its size is the peak outstanding; the caller bounds that.
555    ///
556    /// # Errors
557    /// Returns an adapter failure when the pool cannot allocate.
558    pub fn acquire_surface(&mut self) -> Result<EncoderSurface, EncodeError> {
559        match &mut self.backend {
560            #[cfg(target_os = "linux")]
561            InputBackend::Vulkan(input) => {
562                let frame = input.acquire_frame()?;
563                Ok(EncoderSurface {
564                    descriptor: input.descriptor(self.generation),
565                    backing: SurfaceBacking::Vulkan(frame),
566                })
567            }
568            #[cfg(target_os = "macos")]
569            InputBackend::VideoToolbox(input) => {
570                let frame = input.acquire_frame()?;
571                Ok(EncoderSurface {
572                    descriptor: input.descriptor(self.generation),
573                    backing: SurfaceBacking::VideoToolbox(frame),
574                })
575            }
576            #[cfg(target_os = "windows")]
577            InputBackend::D3D12(input) => {
578                let frame = input.acquire_frame()?;
579                Ok(EncoderSurface {
580                    descriptor: input.descriptor(self.generation),
581                    backing: SurfaceBacking::D3D12(frame),
582                })
583            }
584            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
585            InputBackend::Unsupported(never) => match *never {},
586        }
587    }
588
589    /// Begins a frame bound for `surface`, waiting until its planes are free. Call
590    /// it before recording the pack render into [`Self::planes`], and submit that
591    /// render before [`Self::submit`].
592    ///
593    /// # Errors
594    /// Returns an error for a surface from another pool, or when the wait fails.
595    pub fn begin_frame(&mut self, surface: &EncoderSurface) -> Result<InputFrame, EncodeError> {
596        self.check(surface)?;
597        match &mut self.backend {
598            #[cfg(target_os = "linux")]
599            InputBackend::Vulkan(input) => input.begin_frame(),
600            #[cfg(target_os = "macos")]
601            InputBackend::VideoToolbox(input) => match &surface.backing {
602                SurfaceBacking::VideoToolbox(backing) => input.begin_frame(backing),
603            },
604            #[cfg(target_os = "windows")]
605            InputBackend::D3D12(input) => input.begin_frame(),
606            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
607            InputBackend::Unsupported(never) => match *never {},
608        }
609    }
610
611    /// The luma and interleaved chroma textures `frame` is packed into.
612    #[must_use]
613    pub fn planes(&self, frame: &InputFrame) -> (&wgpu::Texture, &wgpu::Texture) {
614        match &self.backend {
615            #[cfg(target_os = "linux")]
616            InputBackend::Vulkan(input) => input.planes(frame),
617            #[cfg(target_os = "macos")]
618            InputBackend::VideoToolbox(input) => input.planes(frame),
619            #[cfg(target_os = "windows")]
620            InputBackend::D3D12(input) => input.planes(frame),
621            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
622            InputBackend::Unsupported(never) => match *never {},
623        }
624    }
625
626    /// Moves `frame`'s packed planes into `surface` on the GPU; the
627    /// encoder waits for it on the GPU.
628    ///
629    /// # Errors
630    /// Returns an error for a surface from another pool, or when the handoff cannot be submitted.
631    pub fn submit(
632        &mut self,
633        frame: InputFrame,
634        surface: &mut EncoderSurface,
635    ) -> Result<(), EncodeError> {
636        self.check(surface)?;
637        match (&mut self.backend, &mut surface.backing) {
638            #[cfg(target_os = "linux")]
639            (InputBackend::Vulkan(input), SurfaceBacking::Vulkan(backing)) => {
640                input.submit(frame, backing)
641            }
642            #[cfg(target_os = "macos")]
643            (InputBackend::VideoToolbox(input), SurfaceBacking::VideoToolbox(backing)) => {
644                input.submit(frame, backing)
645            }
646            #[cfg(target_os = "windows")]
647            (InputBackend::D3D12(input), SurfaceBacking::D3D12(backing)) => {
648                input.submit(frame, backing)
649            }
650            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
651            (InputBackend::Unsupported(never), _) => match *never {},
652        }
653    }
654
655    /// Stamps `surface` with its presentation time.
656    pub fn set_time(&self, surface: &mut EncoderSurface, time: MediaTime) {
657        match (&self.backend, &mut surface.backing) {
658            #[cfg(target_os = "linux")]
659            (InputBackend::Vulkan(input), SurfaceBacking::Vulkan(backing)) => {
660                backing.set_pts(input.timestamp(time));
661            }
662            #[cfg(target_os = "macos")]
663            (InputBackend::VideoToolbox(input), SurfaceBacking::VideoToolbox(backing)) => {
664                backing.set_pts(input.timestamp(time));
665            }
666            #[cfg(target_os = "windows")]
667            (InputBackend::D3D12(input), SurfaceBacking::D3D12(backing)) => {
668                backing.set_pts(input.timestamp(time));
669            }
670            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
671            (InputBackend::Unsupported(never), _) => match *never {},
672        }
673    }
674
675    /// This session's pool counters so far.
676    #[must_use]
677    pub fn stats(&self) -> EncoderPoolStats {
678        match &self.backend {
679            #[cfg(target_os = "linux")]
680            InputBackend::Vulkan(input) => input.stats(),
681            #[cfg(target_os = "macos")]
682            InputBackend::VideoToolbox(input) => input.stats(),
683            #[cfg(target_os = "windows")]
684            InputBackend::D3D12(input) => input.stats(),
685            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
686            InputBackend::Unsupported(never) => match *never {},
687        }
688    }
689
690    /// Waits for every in-flight handoff and releases the input resources.
691    ///
692    /// # Errors
693    /// On timeout or device loss, resources the GPU may still use are kept rather than freed.
694    pub fn finish(self) -> Result<(), EncodeError> {
695        match self.backend {
696            #[cfg(target_os = "linux")]
697            InputBackend::Vulkan(input) => input.finish(),
698            #[cfg(target_os = "macos")]
699            InputBackend::VideoToolbox(input) => input.finish(),
700            #[cfg(target_os = "windows")]
701            InputBackend::D3D12(input) => input.finish(),
702            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
703            InputBackend::Unsupported(never) => match never {},
704        }
705    }
706
707    fn check(&self, surface: &EncoderSurface) -> Result<(), EncodeError> {
708        if surface.descriptor.pool_generation == self.generation {
709            Ok(())
710        } else {
711            Err(EncodeError::Adapter(format!(
712                "encoder surface from pool {} reached pool {}",
713                surface.descriptor.pool_generation, self.generation
714            )))
715        }
716    }
717}
718
719/// The encode worker's half of a hardware session.
720pub struct HardwareEncodeSession(SessionBackend);
721
722enum SessionBackend {
723    #[cfg(target_os = "linux")]
724    Vulkan(vulkan::VulkanEncodeSession),
725    #[cfg(target_os = "macos")]
726    VideoToolbox(videotoolbox::VideoToolboxEncodeSession),
727    #[cfg(target_os = "windows")]
728    D3D12(d3d12va::D3D12EncodeSession),
729    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
730    Unsupported(std::convert::Infallible),
731}
732
733impl HardwareEncodeSession {
734    /// The encoder this session opened, reported like every other export path.
735    #[must_use]
736    pub fn selection(&self) -> &NativeVideoEncoderSelection {
737        match &self.0 {
738            #[cfg(target_os = "linux")]
739            SessionBackend::Vulkan(session) => session.selection(),
740            #[cfg(target_os = "macos")]
741            SessionBackend::VideoToolbox(session) => session.selection(),
742            #[cfg(target_os = "windows")]
743            SessionBackend::D3D12(session) => session.selection(),
744            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
745            SessionBackend::Unsupported(never) => match *never {},
746        }
747    }
748
749    /// Where this session's time has gone, split like the software sinks.
750    #[must_use]
751    pub fn stage_timings(&self) -> EncodeStageTimings {
752        match &self.0 {
753            #[cfg(target_os = "linux")]
754            SessionBackend::Vulkan(session) => session.stage_timings(),
755            #[cfg(target_os = "macos")]
756            SessionBackend::VideoToolbox(session) => session.stage_timings(),
757            #[cfg(target_os = "windows")]
758            SessionBackend::D3D12(session) => session.stage_timings(),
759            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
760            SessionBackend::Unsupported(never) => match *never {},
761        }
762    }
763
764    /// Submits `surface` and muxes whatever packets it produced.
765    ///
766    /// # Errors
767    /// Returns an adapter failure when the encoder rejects the frame or packets cannot be written.
768    pub fn encode(&mut self, surface: &EncoderSurface) -> Result<(), EncodeError> {
769        match (&mut self.0, &surface.backing) {
770            #[cfg(target_os = "linux")]
771            (SessionBackend::Vulkan(session), SurfaceBacking::Vulkan(frame)) => {
772                session.encode(surface.descriptor.pool_generation, frame)
773            }
774            #[cfg(target_os = "macos")]
775            (SessionBackend::VideoToolbox(session), SurfaceBacking::VideoToolbox(frame)) => {
776                session.encode(surface.descriptor.pool_generation, frame)
777            }
778            #[cfg(target_os = "windows")]
779            (SessionBackend::D3D12(session), SurfaceBacking::D3D12(frame)) => {
780                session.encode(surface.descriptor.pool_generation, frame)
781            }
782            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
783            (SessionBackend::Unsupported(never), _) => match *never {},
784        }
785    }
786
787    /// Buffers one audio block for the audio stream.
788    ///
789    /// # Errors
790    /// Returns an adapter failure for a format change, a non-monotonic block, or a failed encode.
791    pub fn write_audio(&mut self, block: &alpha2_media::AudioBlock) -> Result<(), EncodeError> {
792        match &mut self.0 {
793            #[cfg(target_os = "linux")]
794            SessionBackend::Vulkan(session) => session.write_audio(block),
795            #[cfg(target_os = "macos")]
796            SessionBackend::VideoToolbox(session) => session.write_audio(block),
797            #[cfg(target_os = "windows")]
798            SessionBackend::D3D12(session) => session.write_audio(block),
799            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
800            SessionBackend::Unsupported(never) => match *never {},
801        }
802    }
803
804    /// Flushes video and audio, writes the trailer, and publishes the output.
805    ///
806    /// # Errors
807    /// Returns an adapter failure from the flush or trailer; [`EncodeError::Publish`] when the
808    /// finished file was kept beside its target; [`EncodeError::Cancelled`] when `cancel`
809    /// stopped the publish retries.
810    pub fn finish(&mut self, cancel: &alpha2_media::CancelToken) -> Result<(), EncodeError> {
811        match &mut self.0 {
812            #[cfg(target_os = "linux")]
813            SessionBackend::Vulkan(session) => session.finish(cancel),
814            #[cfg(target_os = "macos")]
815            SessionBackend::VideoToolbox(session) => session.finish(cancel),
816            #[cfg(target_os = "windows")]
817            SessionBackend::D3D12(session) => session.finish(cancel),
818            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
819            SessionBackend::Unsupported(never) => match *never {},
820        }
821    }
822
823    /// How the finished file was published; `None` until [`Self::finish`] has published it.
824    #[must_use]
825    pub fn publish_report(&self) -> Option<crate::PublishReport> {
826        match &self.0 {
827            #[cfg(target_os = "linux")]
828            SessionBackend::Vulkan(session) => session.publish_report(),
829            #[cfg(target_os = "macos")]
830            SessionBackend::VideoToolbox(session) => session.publish_report(),
831            #[cfg(target_os = "windows")]
832            SessionBackend::D3D12(session) => session.publish_report(),
833            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
834            SessionBackend::Unsupported(never) => match *never {},
835        }
836    }
837
838    /// Discards the partial output.
839    pub fn abort(&mut self) {
840        match &mut self.0 {
841            #[cfg(target_os = "linux")]
842            SessionBackend::Vulkan(session) => session.abort(),
843            #[cfg(target_os = "macos")]
844            SessionBackend::VideoToolbox(session) => session.abort(),
845            #[cfg(target_os = "windows")]
846            SessionBackend::D3D12(session) => session.abort(),
847            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
848            SessionBackend::Unsupported(never) => match *never {},
849        }
850    }
851}