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