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