1use std::collections::HashSet;
7use std::ffi::CString;
8
9use alpha2_media::{ColorMetadata, EncodeError};
10use alpha2_time::MediaTime;
11use rsmpeg::avcodec::{AVCodec, AVCodecContext};
12use rsmpeg::avutil::{AVFrame, AVHWDeviceContext, AVHWFramesContext, AVRational, av_rescale_q, ra};
13use rsmpeg::error::RsmpegError;
14use rsmpeg::ffi;
15
16use super::{
17 EncoderInputHandoff, EncoderInputLayout, EncoderPoolStats, EncoderSurfaceDescriptor,
18 HardwareEncodeBackend, HardwareEncodeCapability, HardwareEncodeOpenError,
19 HardwareEncodeRequest, InputFrame,
20};
21use crate::NativeVideoCodec;
22use crate::bitstream::EncodedVideoFilter;
23use crate::convert::{encode_adapter_error, tick_base};
24use crate::encode::{EncodeStageTimings, timed};
25use crate::mux::Muxer;
26
27#[derive(Clone, Debug, Eq, PartialEq)]
29pub struct VulkanEncodeProbe {
30 pub encoder: String,
32 pub coded_size: (u32, u32),
34 pub frames_usage: u32,
37 pub images_per_frame: usize,
40 pub initial_layout: u32,
42 pub queue_family: u32,
44 pub has_timeline_semaphore: bool,
46 pub packets: u32,
48 pub packet_bytes: u32,
50}
51
52pub fn probe_vulkan_encode(
58 device: &AVHWDeviceContext,
59 width: u32,
60 height: u32,
61) -> Result<VulkanEncodeProbe, EncodeError> {
62 let encoder = AVCodec::find_encoder_by_name(c"h264_vulkan").ok_or_else(|| {
63 EncodeError::Adapter("this FFmpeg runtime has no h264_vulkan encoder".into())
64 })?;
65 let coded_width =
66 i32::try_from(width).map_err(|_| EncodeError::Adapter("width is out of range".into()))?;
67 let coded_height =
68 i32::try_from(height).map_err(|_| EncodeError::Adapter("height is out of range".into()))?;
69
70 let mut frames = vulkan_encode_frames(device, coded_width, coded_height)?;
71 let frames_usage = alpha2_ffmpeg_bridge::vulkan_frames_usage(&frames);
72
73 let mut context = AVCodecContext::new(&encoder);
74 context.set_width(coded_width);
75 context.set_height(coded_height);
76 context.set_pix_fmt(ffi::AV_PIX_FMT_VULKAN);
77 context.set_time_base(ra(1, 30));
80 context.set_framerate(ra(30, 1));
81 context.set_bit_rate(12_000_000);
82 context.set_gop_size(12);
83 context.set_max_b_frames(0);
84 context.set_hw_frames_ctx(frames.clone());
85 context
86 .open(None)
87 .map_err(|error| encode_adapter_error_at_open("h264_vulkan", &error))?;
88
89 let mut frame = AVFrame::new();
90 frames
91 .get_buffer(&mut frame)
92 .map_err(encode_adapter_error)?;
93 let descriptor =
94 alpha2_ffmpeg_bridge::vulkan_frame_info(&frame).map_err(encode_adapter_error)?;
95 frame.set_pts(0);
96
97 context
98 .send_frame(Some(&frame))
99 .map_err(encode_adapter_error)?;
100 context.send_frame(None).map_err(encode_adapter_error)?;
101 let mut packets = 0;
102 let mut packet_bytes = 0_u32;
103 loop {
104 match context.receive_packet() {
105 Ok(packet) => {
106 packets += 1;
107 packet_bytes = packet_bytes.saturating_add(packet.size.unsigned_abs());
108 }
109 Err(RsmpegError::EncoderDrainError | RsmpegError::EncoderFlushedError) => break,
110 Err(error) => return Err(encode_adapter_error(error)),
111 }
112 }
113 if packets == 0 {
114 return Err(EncodeError::Adapter(
115 "h264_vulkan opened but produced no packet".into(),
116 ));
117 }
118 Ok(VulkanEncodeProbe {
119 encoder: encoder.name().to_string_lossy().into_owned(),
120 coded_size: (
121 descriptor.coded_width.unsigned_abs(),
122 descriptor.coded_height.unsigned_abs(),
123 ),
124 frames_usage,
125 images_per_frame: descriptor.plane_count as usize,
126 initial_layout: descriptor.layouts[0],
127 queue_family: descriptor.queue_families[0],
128 has_timeline_semaphore: descriptor.semaphores[0] != 0,
129 packets,
130 packet_bytes,
131 })
132}
133
134pub(crate) fn probe_vulkan_rate_control(
140 encoder: &rsmpeg::avcodec::AVCodecRef<'static>,
141 width: u32,
142 height: u32,
143 request: &crate::rate_control::MechanismRequest,
144) -> Result<(u32, String), String> {
145 let pinned = alpha2_native_gpu::adapter_pinned();
149 let shared = alpha2_native_gpu::shared_device_index();
150 let candidates = match (pinned, shared) {
151 (true, Ok(index)) => vec![index.to_string()],
152 (true, Err(error)) => return Err(error.to_string()),
153 (false, shared) => {
154 let first = shared.ok();
155 first
156 .into_iter()
157 .chain((0..8).filter(|index| Some(*index) != first))
158 .map(|index| index.to_string())
159 .collect::<Vec<_>>()
160 }
161 };
162 let mut last = "no Vulkan device".to_owned();
163 for device in candidates {
164 match probe_vulkan_rate_control_on(encoder, &device, width, height, request) {
165 Ok(packets) => return Ok((packets, device)),
166 Err(VulkanProbeError::NoDevice(error)) => {
167 last = error;
168 break;
169 }
170 Err(VulkanProbeError::NoEncodeQueue(error)) if !pinned => last = error,
171 Err(VulkanProbeError::NoEncodeQueue(error) | VulkanProbeError::Refused(error)) => {
172 return Err(format!("on Vulkan device {device}: {error}"));
173 }
174 }
175 }
176 Err(last)
177}
178
179enum VulkanProbeError {
180 NoDevice(String),
182 NoEncodeQueue(String),
184 Refused(String),
186}
187
188fn probe_vulkan_rate_control_on(
189 encoder: &rsmpeg::avcodec::AVCodecRef<'static>,
190 device_name: &str,
191 width: u32,
192 height: u32,
193 request: &crate::rate_control::MechanismRequest,
194) -> Result<u32, VulkanProbeError> {
195 let device_name = CString::new(device_name)
196 .map_err(|_| VulkanProbeError::NoDevice("device name contains a NUL byte".to_owned()))?;
197 let extensions = rsmpeg::avutil::AVDictionary::new(
200 c"device_extensions",
201 c"VK_KHR_video_queue+VK_KHR_video_encode_queue+VK_KHR_video_encode_h264+VK_KHR_video_encode_h265+VK_KHR_video_encode_av1+VK_KHR_video_maintenance1",
202 0,
203 );
204 let device = AVHWDeviceContext::create(
205 ffi::AV_HWDEVICE_TYPE_VULKAN,
206 Some(&device_name),
207 Some(&extensions),
208 0,
209 )
210 .map_err(|error| VulkanProbeError::NoDevice(format!("no Vulkan device: {error}")))?;
211 let refused = |error: String| VulkanProbeError::Refused(error);
212 let coded_width =
213 i32::try_from(width).map_err(|_| refused("width is out of range".to_owned()))?;
214 let coded_height =
215 i32::try_from(height).map_err(|_| refused("height is out of range".to_owned()))?;
216 let mut frames = vulkan_encode_frames(&device, coded_width, coded_height)
217 .map_err(|error| VulkanProbeError::NoEncodeQueue(error.to_string()))?;
218 let mut context = AVCodecContext::new(encoder);
219 context.set_width(coded_width);
220 context.set_height(coded_height);
221 context.set_pix_fmt(ffi::AV_PIX_FMT_VULKAN);
222 context.set_time_base(ra(1, 30));
223 context.set_framerate(ra(30, 1));
224 context.set_bit_rate(request.bit_rate);
225 context.set_gop_size(12);
226 context.set_max_b_frames(0);
227 context.set_hw_frames_ctx(frames.clone());
228 let unused = alpha2_ffmpeg_bridge::open_codec_context(
229 &mut context,
230 request.dictionary(crate::convert::color_options(ColorMetadata::EXPORT)),
231 )
232 .map_err(|error| {
233 let message = error.to_string();
235 if matches!(error, RsmpegError::AVError(code) if code == -38) {
236 VulkanProbeError::NoEncodeQueue(message)
237 } else {
238 refused(message)
239 }
240 })?;
241 crate::convert::reject_unused_encode_options(unused)
242 .map_err(|error| refused(error.to_string()))?;
243 let mut frame = AVFrame::new();
244 frames
245 .get_buffer(&mut frame)
246 .map_err(|error| refused(error.to_string()))?;
247 frame.set_pts(0);
248 context
249 .send_frame(Some(&frame))
250 .map_err(|error| refused(error.to_string()))?;
251 context
252 .send_frame(None)
253 .map_err(|error| refused(error.to_string()))?;
254 let mut packets = 0;
255 loop {
256 match context.receive_packet() {
257 Ok(_) => packets += 1,
258 Err(RsmpegError::EncoderDrainError | RsmpegError::EncoderFlushedError) => break,
259 Err(error) => return Err(refused(error.to_string())),
260 }
261 }
262 if packets == 0 {
263 return Err(refused("opened but produced no packet".to_owned()));
264 }
265 Ok(packets)
266}
267
268const fn vulkan_encoder(codec: NativeVideoCodec) -> Option<(&'static str, &'static str)> {
270 match codec {
271 NativeVideoCodec::H264 => Some(("h264_vulkan", "h264")),
272 NativeVideoCodec::Hevc => Some(("hevc_vulkan", "hevc")),
273 _ => None,
274 }
275}
276
277pub(super) fn preferred_capability(
279 shared: &alpha2_native_gpu::SharedVulkanContext,
280) -> Result<HardwareEncodeCapability, String> {
281 capability(shared, NativeVideoCodec::H264)
282 .or_else(|h264| capability(shared, NativeVideoCodec::Hevc).map_err(|_| h264))
283}
284
285pub(super) fn capability(
287 shared: &alpha2_native_gpu::SharedVulkanContext,
288 codec: NativeVideoCodec,
289) -> Result<HardwareEncodeCapability, String> {
290 if shared.encode_codecs().is_empty() {
291 return Err("this Vulkan device has no video-encode queue".to_owned());
292 }
293 let Some((encoder, listed)) = vulkan_encoder(codec) else {
294 return Err(format!(
295 "Vulkan Video encodes h264 and hevc, not {}",
296 codec.as_str()
297 ));
298 };
299 if !shared.encode_codecs().contains(&listed) {
300 return Err(format!(
301 "this Vulkan device has no video encoder for {} (it encodes {})",
302 codec.as_str(),
303 shared.encode_codecs().join(", ")
304 ));
305 }
306 let extent = shared.encode_extent(listed).ok_or_else(|| {
307 format!(
308 "this device did not report its {} encode extents",
309 codec.as_str()
310 )
311 })?;
312 Ok(HardwareEncodeCapability {
313 backend: HardwareEncodeBackend::Vulkan,
314 encoder,
315 codec,
316 gpu_input_only: true,
317 input_layout: EncoderInputLayout::Nv12,
318 handoff: EncoderInputHandoff::GpuCopy,
319 shares_renderer_device: true,
320 minimum: extent.minimum,
321 maximum: extent.maximum,
322 granularity: extent.granularity,
323 max_p_picture_l0_references: Some(extent.max_p_picture_l0_references),
324 max_b_picture_l0_references: Some(extent.max_b_picture_l0_references),
325 max_l1_references: Some(extent.max_l1_references),
326 rate_control_modes: extent.rate_control_modes.clone(),
327 plane_ring_slots: alpha2_native_gpu::VulkanEncodeCopier::slots(),
328 handoff_retained_surfaces: alpha2_native_gpu::VulkanEncodeCopier::slots(),
330 codec_retained_surfaces: 0,
332 })
333}
334
335pub(super) fn open(
338 shared: &alpha2_native_gpu::SharedVulkanContext,
339 request: &HardwareEncodeRequest<'_>,
340 generation: u64,
341) -> Result<(VulkanEncodeSession, VulkanEncodeInput), HardwareEncodeOpenError> {
342 let refused = |error: EncodeError| HardwareEncodeOpenError::Refused(error.to_string());
343 let (width, height) = (request.width, request.height);
344 let frame_rate = super::session_frame_rate(request.frame_rate).map_err(refused)?;
345 let (encoder, _) = vulkan_encoder(request.codec).ok_or_else(|| {
346 HardwareEncodeOpenError::Refused(format!(
347 "Vulkan Video does not encode {}",
348 request.codec.as_str()
349 ))
350 })?;
351 let mark = alpha2_ffmpeg_bridge::log_mark();
352 let (frames, context, selection) = open_encoder(
353 &shared.ffmpeg_device(),
354 encoder,
355 width,
356 height,
357 request.rate_control,
358 frame_rate,
359 request.color,
360 )
361 .map_err(|error| super::open_refusal(encoder, mark, &error))?;
362 let time_base = ra(frame_rate.1, frame_rate.0);
363 let bitstream = (request.codec == NativeVideoCodec::Hevc)
367 .then(|| EncodedVideoFilter::in_band(&context.extract_codecpar(), request.color, time_base))
368 .transpose()
369 .map_err(refused)?;
370 let copier = alpha2_native_gpu::VulkanEncodeCopier::new(shared)
371 .map_err(|error| HardwareEncodeOpenError::Refused(format!("{error:?}")))?;
372 let gpu = shared.gpu();
373 let planes = (0..alpha2_native_gpu::VulkanEncodeCopier::slots())
376 .map(|_| {
377 super::Nv12Planes::new(
378 &plane_texture(
379 gpu.device(),
380 "alpha2 NV12 luma",
381 width,
382 height,
383 wgpu::TextureFormat::R8Unorm,
384 ),
385 &plane_texture(
386 gpu.device(),
387 "alpha2 NV12 chroma",
388 width / 2,
389 height / 2,
390 wgpu::TextureFormat::Rg8Unorm,
391 ),
392 )
393 })
394 .collect();
395 let input = VulkanEncodeInput {
396 copier,
397 planes,
398 frames,
399 size: (width, height),
400 time_base,
401 color: request.color,
402 stats: EncoderPoolStats::default(),
403 images: HashSet::new(),
404 };
405 let muxer = if bitstream.is_some() {
408 Muxer::open_deferred(
409 request.output,
410 request.container,
411 &context,
412 time_base,
413 request.audio,
414 )
415 } else {
416 Muxer::open(
417 request.output,
418 request.container,
419 &context,
420 time_base,
421 request.audio,
422 )
423 }
424 .map_err(HardwareEncodeOpenError::Failed)?;
425 Ok((
426 VulkanEncodeSession {
427 context,
428 time_base,
429 bitstream,
430 muxer,
431 stages: EncodeStageTimings::default(),
432 selection,
433 generation,
434 },
435 input,
436 ))
437}
438
439fn plane_texture(
443 device: &wgpu::Device,
444 label: &'static str,
445 width: u32,
446 height: u32,
447 format: wgpu::TextureFormat,
448) -> wgpu::Texture {
449 device.create_texture(&wgpu::TextureDescriptor {
450 label: Some(label),
451 size: wgpu::Extent3d {
452 width,
453 height,
454 depth_or_array_layers: 1,
455 },
456 mip_level_count: 1,
457 sample_count: 1,
458 dimension: wgpu::TextureDimension::D2,
459 format,
460 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
461 view_formats: &[],
462 })
463}
464
465fn open_encoder(
467 device: &AVHWDeviceContext,
468 encoder_name: &'static str,
469 width: u32,
470 height: u32,
471 rate_control: alpha2_media::VideoRateControl,
472 frame_rate: (i32, i32),
473 color: ColorMetadata,
474) -> Result<
475 (
476 AVHWFramesContext,
477 AVCodecContext,
478 crate::NativeVideoEncoderSelection,
479 ),
480 EncodeError,
481> {
482 let encoder = CString::new(encoder_name)
483 .ok()
484 .and_then(|name| AVCodec::find_encoder_by_name(&name))
485 .ok_or_else(|| {
486 EncodeError::Adapter(format!("this FFmpeg runtime has no {encoder_name} encoder"))
487 })?;
488 let coded_width =
489 i32::try_from(width).map_err(|_| EncodeError::Adapter("width is out of range".into()))?;
490 let coded_height =
491 i32::try_from(height).map_err(|_| EncodeError::Adapter("height is out of range".into()))?;
492 let frames = vulkan_encode_frames(device, coded_width, coded_height)?;
493 let rate = u32::try_from(frame_rate.0)
494 .ok()
495 .zip(u32::try_from(frame_rate.1).ok())
496 .and_then(|(num, den)| alpha2_time::FrameRate::new(num, den).ok())
497 .ok_or_else(|| EncodeError::Adapter("frame rate is out of range".into()))?;
498 let open = |quantized: Option<&crate::rate_control::MechanismRequest>| {
499 let mut context = AVCodecContext::new(&encoder);
500 context.set_width(coded_width);
501 context.set_height(coded_height);
502 context.set_pix_fmt(ffi::AV_PIX_FMT_VULKAN);
503 context.set_time_base(ra(frame_rate.1, frame_rate.0));
506 context.set_framerate(ra(frame_rate.0, frame_rate.1));
507 context.set_bit_rate(quantized.map_or_else(
508 || i64::try_from(rate_control.bitrate).unwrap_or(i64::MAX),
509 |quantized| quantized.bit_rate,
510 ));
511 context.set_gop_size(crate::capabilities::keyframe_interval(rate));
512 context.set_max_b_frames(0);
514 context.set_hw_frames_ctx(frames.clone());
515 context.set_flags(
517 context.flags | i32::try_from(ffi::AV_CODEC_FLAG_GLOBAL_HEADER).unwrap_or(0),
518 );
519 let color = crate::convert::color_options(color);
521 let options = match quantized {
522 Some(quantized) => quantized.dictionary(color),
523 None => crate::rate_control::rate_control_options(encoder_name, rate_control, color),
524 };
525 let unused = alpha2_ffmpeg_bridge::open_codec_context(&mut context, options)
526 .map_err(|error| encode_adapter_error_at_open(encoder_name, &error))?;
527 crate::convert::reject_unused_encode_options(unused)?;
528 if context.extradata_size <= 0 {
529 return Err(EncodeError::Adapter(format!(
530 "{encoder_name} opened without parameter-set extradata for the MP4 header"
531 )));
532 }
533 Ok::<_, EncodeError>(context)
534 };
535 let (context, applied, quantizer_refused) =
537 match crate::rate_control::quantizer_request(encoder_name, rate_control) {
538 Some(Ok(quantized)) => match open(Some(&quantized)) {
539 Ok(context) => (context, crate::AppliedRateControl::Quantizer, None),
540 Err(error) => (
541 open(None)?,
542 crate::AppliedRateControl::Bitrate,
543 Some(format!("{} refused: {error}", quantized.describe())),
544 ),
545 },
546 Some(Err(reason)) => (
547 open(None)?,
548 crate::AppliedRateControl::Bitrate,
549 Some(reason),
550 ),
551 None => (open(None)?, crate::AppliedRateControl::Bitrate, None),
552 };
553 if let Some(reason) = &quantizer_refused {
554 alpha2_os::diagnostic!(
555 "alpha2 native export: {encoder_name} runs the bitrate fallback: {reason}"
556 );
557 }
558 let selection = crate::NativeVideoEncoderSelection {
560 encoder_name: encoder_name.to_owned(),
561 class: crate::NativeEncoderClass::Hardware,
562 hardware_accelerated: true,
563 rejected: Vec::new(),
564 rate_control: applied,
565 quantizer_refused,
566 software_threads: None,
567 pixels: alpha2_media::PixelLayout::YUV420P,
568 };
569 Ok((frames, context, selection))
570}
571
572pub(super) struct VulkanEncodeSession {
574 context: AVCodecContext,
575 time_base: AVRational,
576 bitstream: Option<EncodedVideoFilter>,
578 muxer: Muxer,
579 stages: EncodeStageTimings,
580 selection: crate::NativeVideoEncoderSelection,
581 generation: u64,
582}
583
584pub(super) struct VulkanEncodeInput {
593 copier: alpha2_native_gpu::VulkanEncodeCopier,
594 planes: Vec<super::Nv12Planes>,
595 frames: AVHWFramesContext,
596 size: (u32, u32),
597 time_base: AVRational,
598 color: ColorMetadata,
599 stats: EncoderPoolStats,
600 images: HashSet<u64>,
602}
603
604pub(super) struct VulkanEncoderFrame(AVFrame);
606
607impl VulkanEncoderFrame {
608 pub(super) fn set_pts(&mut self, pts: i64) {
609 self.0.set_pts(pts);
610 }
611}
612
613impl VulkanEncodeInput {
614 pub(super) fn descriptor(&self, generation: u64) -> EncoderSurfaceDescriptor {
615 EncoderSurfaceDescriptor {
616 backend: HardwareEncodeBackend::Vulkan,
617 pool_generation: generation,
618 layout: EncoderInputLayout::Nv12,
619 visible: self.size,
620 color: self.color,
621 }
622 }
623
624 pub(super) fn acquire_frame(&mut self) -> Result<VulkanEncoderFrame, EncodeError> {
629 let mut frame = AVFrame::new();
630 self.frames
631 .get_buffer(&mut frame)
632 .map_err(encode_adapter_error)?;
633 let image = alpha2_ffmpeg_bridge::vulkan_frame_info(&frame)
634 .map_err(encode_adapter_error)?
635 .images[0];
636 self.images.insert(image);
637 self.stats.acquired = self.stats.acquired.saturating_add(1);
638 self.stats.allocated = u64::try_from(self.images.len()).unwrap_or(u64::MAX);
639 Ok(VulkanEncoderFrame(frame))
640 }
641
642 pub(super) fn begin_frame(&mut self) -> Result<InputFrame, EncodeError> {
645 let slot = self.copier.await_slot().map_err(encode_adapter_error)?;
646 if slot >= self.planes.len() {
647 return Err(EncodeError::Adapter(format!(
648 "encode copier reported slot {slot}"
649 )));
650 }
651 Ok(InputFrame { slot })
652 }
653
654 pub(super) fn planes(&self, frame: &InputFrame) -> (&wgpu::TextureView, &wgpu::TextureView) {
655 self.planes[frame.slot].views()
656 }
657
658 #[allow(clippy::needless_pass_by_value)]
662 pub(super) fn submit(
663 &mut self,
664 frame: InputFrame,
665 backing: &mut VulkanEncoderFrame,
666 ) -> Result<(), EncodeError> {
667 let InputFrame { slot } = frame;
668 let pair = &self.planes[slot];
669 let mut access = alpha2_ffmpeg_bridge::VulkanEncodeFrameAccess::begin(&mut backing.0)
670 .map_err(encode_adapter_error)?;
671 self.copier
672 .submit(
673 &mut access,
674 pair.luma.texture(),
675 pair.chroma.texture(),
676 self.size,
677 )
678 .map_err(encode_adapter_error)?;
679 self.stats.copy_operations = self.stats.copy_operations.saturating_add(2);
680 self.stats.copy_bytes = self
681 .stats
682 .copy_bytes
683 .saturating_add(EncoderInputLayout::Nv12.frame_bytes(self.size.0, self.size.1));
684 Ok(())
685 }
686
687 pub(super) fn timestamp(&self, time: MediaTime) -> i64 {
689 av_rescale_q(time.ticks(), tick_base(), self.time_base)
690 }
691
692 pub(super) const fn stats(&self) -> EncoderPoolStats {
693 self.stats
694 }
695
696 pub(super) fn finish(self) -> Result<(), EncodeError> {
698 let Self { copier, planes, .. } = self;
699 copier.finish().map_err(encode_adapter_error)?;
700 drop(planes);
701 Ok(())
702 }
703}
704
705impl VulkanEncodeSession {
706 pub(super) const fn selection(&self) -> &crate::NativeVideoEncoderSelection {
707 &self.selection
708 }
709
710 pub(super) fn stage_timings(&self) -> EncodeStageTimings {
711 self.muxer.with_audio_timings(self.stages)
712 }
713
714 pub(super) fn encode(
716 &mut self,
717 generation: u64,
718 frame: &VulkanEncoderFrame,
719 ) -> Result<(), EncodeError> {
720 if generation != self.generation {
721 return Err(EncodeError::Adapter(format!(
722 "encoder surface from pool {generation} reached session {}",
723 self.generation
724 )));
725 }
726 timed(&mut self.stages.video_send_frame, || {
727 self.context.send_frame(Some(&frame.0))
728 })
729 .map_err(encode_adapter_error)?;
730 self.drain()
731 }
732
733 pub(super) fn write_audio(
734 &mut self,
735 block: &alpha2_media::AudioBlock,
736 ) -> Result<(), EncodeError> {
737 self.muxer.write_audio(block, &mut self.stages)
738 }
739
740 pub(super) fn finish(&mut self, cancel: &alpha2_media::CancelToken) -> Result<(), EncodeError> {
743 self.muxer.finish_audio()?;
745 crate::encode::beat_encode_call();
746 self.context
747 .send_frame(None)
748 .map_err(encode_adapter_error)?;
749 self.drain()?;
750 if let Some(bitstream) = &mut self.bitstream {
751 for mut packet in bitstream.flush()? {
752 self.muxer.write_video(&mut packet, self.time_base)?;
753 }
754 }
755 self.muxer.write_ready_audio(true, &mut self.stages)?;
756 self.muxer.close(cancel)
757 }
758
759 pub(super) fn publish_report(&self) -> Option<crate::PublishReport> {
760 self.muxer.publish_report()
761 }
762
763 pub(super) fn abort(&mut self) {
764 self.muxer.abort();
765 }
766
767 fn drain(&mut self) -> Result<(), EncodeError> {
768 loop {
769 let received = timed(&mut self.stages.video_receive_packet, || {
770 self.context.receive_packet()
771 });
772 match received {
773 Ok(mut packet) => match &mut self.bitstream {
774 Some(bitstream) => {
775 for mut packet in bitstream.filter(packet)? {
776 self.muxer.write_video(&mut packet, self.time_base)?;
777 }
778 }
779 None => self.muxer.write_video(&mut packet, self.time_base)?,
780 },
781 Err(RsmpegError::EncoderDrainError | RsmpegError::EncoderFlushedError) => {
782 return self.muxer.write_ready_audio(false, &mut self.stages);
783 }
784 Err(error) => return Err(encode_adapter_error(error)),
785 }
786 }
787 }
788}
789
790fn vulkan_encode_frames(
796 device: &AVHWDeviceContext,
797 width: i32,
798 height: i32,
799) -> Result<AVHWFramesContext, EncodeError> {
800 let mut frames = device.hwframe_ctx_alloc();
801 {
802 let data = frames.data();
803 data.format = ffi::AV_PIX_FMT_VULKAN;
804 data.sw_format = ffi::AV_PIX_FMT_NV12;
805 data.width = width;
806 data.height = height;
807 data.initial_pool_size = 0;
808 }
809 alpha2_ffmpeg_bridge::vulkan_frames_add_usage(
810 &mut frames,
811 alpha2_ffmpeg_bridge::VULKAN_ENCODE_INPUT_USAGE,
812 )
813 .map_err(encode_adapter_error)?;
814 frames.init().map_err(encode_adapter_error)?;
815 Ok(frames)
816}
817
818fn encode_adapter_error_at_open(encoder: &str, error: &RsmpegError) -> EncodeError {
819 EncodeError::Adapter(format!("{encoder} session could not open: {error}"))
820}