🐎 Fill NVENC's input on the GPU
The NVIDIA arm read each encode source as host bytes and copied it with the
CPU into an NVENC input buffer; a source in a device cache went through a
staging copy first. The runtime device's GPU now copies the source's planes,
where they lie, into an exportable buffer that CUDA imports and NVENC
registers as input (nvEncRegisterResource, a CUDA device pointer, mapped for
each frame and unmapped once its bitstream is locked), as the VA-API arm
fills its input surfaces (cee727b5e). A frame whose copy is declined is
uploaded as before, with the reason logged once a session; a session whose
input CUDA or NVENC refuses uploads from then on.
NVENC codes the same bytes either way: the new hardware test
each_frame_filled_by_the_gpu_encodes_as_uploaded compares every access
unit of H.264 High and HEVC Main at 1080p, from pages and from a device
cache. The guest sees the same results sooner: on um870's RTX 3090,
VideoToolbox's H.264 encode of 300 frames went from 88.7 to 156.5 fps at
1080p (6 Mbit/s) and from 24.6 to 40.5 fps at 2160p (30 Mbit/s), each
stream byte-identical in size and in PSNR against the source.
This commit is contained in:
1 parent
4abaf91c85
commit
b448dbe667
12 files changed
+1252
-102
No files matched your search
@@ -11,7 +11,8 @@
|
||||
//! - [`Gpu`] is a GPU and its CUDA context; [`devices`] lists the host's.
|
||||
//! - [`decode_capabilities`] and [`encoder_report`] say what NVDEC and
|
||||
//! NVENC answer.
|
||||
//! - [`NvencEncoder`] encodes raw frames to H.264 or HEVC.
|
||||
//! - [`NvencEncoder`] encodes raw frames to H.264 or HEVC, from host bytes
|
||||
//! or from another API's device memory CUDA imported ([`ImportedBuffer`]).
|
||||
//! - [`AnnexBDecoder`] decodes whole Annex B access units, one picture
|
||||
//! each, for a device that says where each picture goes, as the
|
||||
//! reims-graphics device's video does.
|
||||
@@ -49,8 +50,8 @@ pub use error::Error;
|
||||
pub use external::ImportedBuffer;
|
||||
pub use nvdec::{ChromaFormat, DecodeCapabilities, NvdecCodec, SurfaceFormat, decode_capabilities};
|
||||
pub use nvenc::encoder::{
|
||||
Bitstream, EncodeParams, EncodeProfile, EncodeProfileSupport, EncodeRateControl, NvencEncoder,
|
||||
Packet, PictureType, RawFrame, Tuning, encode_profiles,
|
||||
Bitstream, DeviceFrame, EncodeParams, EncodeProfile, EncodeProfileSupport, EncodeRateControl,
|
||||
NvencEncoder, Packet, PictureType, RawFrame, Tuning, encode_profiles,
|
||||
};
|
||||
pub use nvenc::max_api_version;
|
||||
pub use probe::{EncodeCodecReport, EncoderReport, encoder_report};
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Another API's memory imported into CUDA ([`ImportedBuffer`]), for a picture to land in a
|
||||
//! device's own memory by one copy within the GPU ([`crate::nvidia::AnnexBPicture::write_into_device`]):
|
||||
//! device's own memory by one copy within the GPU ([`crate::nvidia::AnnexBPicture::write_into_device`]),
|
||||
//! and for NVENC to read a frame where the device's GPU wrote it
|
||||
//! ([`crate::nvidia::NvencEncoder::encode_device`]):
|
||||
//! a Vulkan device's buffer whose memory it exported as an opaque file descriptor
|
||||
//! (`VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT`), imported with `cuImportExternalMemory` and
|
||||
//! mapped whole with `cuExternalMemoryGetMappedBuffer`. The memory is the exporter's GPU's, so
|
||||
@@ -9,8 +11,10 @@
|
||||
//! file descriptor, and closes it where it fails. The mapping is freed (`cuMemFree`) and the
|
||||
//! import destroyed as the [`ImportedBuffer`] drops, with its GPU's context pushed. The exporter's
|
||||
//! buffer must outlive it: what the GPU writes through an import of freed memory lands nowhere
|
||||
//! anyone owns.
|
||||
//! anyone owns. An import may hold the exporter's buffer itself ([`ImportedBuffer::holding`]),
|
||||
//! which it lets go of only once the import is destroyed.
|
||||
|
||||
use std::any::Any;
|
||||
use std::os::fd::{IntoRawFd as _, OwnedFd};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -30,6 +34,8 @@ pub struct ImportedBuffer {
|
||||
address: CUdeviceptr,
|
||||
/// Its bytes.
|
||||
length: usize,
|
||||
/// What it holds until it is destroyed ([`ImportedBuffer::holding`]).
|
||||
owner: Option<Box<dyn Any + Send + Sync>>,
|
||||
}
|
||||
|
||||
// SAFETY: the import and the mapping are the driver's handles, which any thread may use with
|
||||
@@ -117,9 +123,19 @@ impl ImportedBuffer {
|
||||
memory,
|
||||
address,
|
||||
length,
|
||||
owner: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The import, holding `owner`, the exporter's buffer, until the import is destroyed, so
|
||||
/// that the memory outlives every use of the import (module docs). An import that cannot be
|
||||
/// destroyed as it drops (its GPU's context not to be had) never lets go of it.
|
||||
#[must_use]
|
||||
pub fn holding(mut self, owner: Box<dyn Any + Send + Sync>) -> Self {
|
||||
self.owner = Some(owner);
|
||||
self
|
||||
}
|
||||
|
||||
/// Its bytes.
|
||||
pub fn length(&self) -> usize {
|
||||
self.length
|
||||
@@ -144,6 +160,7 @@ impl Drop for ImportedBuffer {
|
||||
};
|
||||
let Ok(_current) = self.gpu.push() else {
|
||||
log::warn!("an imported buffer stays imported: its GPU's context is not to be had");
|
||||
std::mem::forget(self.owner.take());
|
||||
return;
|
||||
};
|
||||
// SAFETY: the mapping `cuExternalMemoryGetMappedBuffer` gave, freed once, as CUDA's
|
||||
|
||||
@@ -515,6 +515,15 @@ fn nvenc_checks(checks: &mut Checks) {
|
||||
layout!(checks, enc::NV_ENC_LOCK_INPUT_BUFFER, "NV_ENC_LOCK_INPUT_BUFFER" {
|
||||
version, inputBuffer, bufferDataPtr, pitch, reserved1, reserved2,
|
||||
});
|
||||
layout!(checks, enc::NV_ENC_REGISTER_RESOURCE, "NV_ENC_REGISTER_RESOURCE" {
|
||||
version, resourceType, width, height, pitch, subResourceIndex, resourceToRegister,
|
||||
registeredResource, bufferFormat, bufferUsage, pInputFencePoint, chromaOffset,
|
||||
chromaOffsetIn, reserved1, reserved2,
|
||||
});
|
||||
layout!(checks, enc::NV_ENC_MAP_INPUT_RESOURCE, "NV_ENC_MAP_INPUT_RESOURCE" {
|
||||
version, subResourceIndex, inputResource, registeredResource, mappedResource,
|
||||
mappedBufferFmt, reserved1, reserved2,
|
||||
});
|
||||
layout!(checks, enc::NV_ENC_SEQUENCE_PARAM_PAYLOAD, "NV_ENC_SEQUENCE_PARAM_PAYLOAD" {
|
||||
version, inBufferSize, spsId, ppsId, spsppsBuffer, outSPSPPSPayloadSize, reserved,
|
||||
reserved2,
|
||||
@@ -570,6 +579,14 @@ fn nvenc_checks(checks: &mut Checks) {
|
||||
"NV_ENC_LOCK_INPUT_BUFFER_VER",
|
||||
enc::NV_ENC_LOCK_INPUT_BUFFER_VER,
|
||||
),
|
||||
(
|
||||
"NV_ENC_REGISTER_RESOURCE_VER",
|
||||
enc::NV_ENC_REGISTER_RESOURCE_VER,
|
||||
),
|
||||
(
|
||||
"NV_ENC_MAP_INPUT_RESOURCE_VER",
|
||||
enc::NV_ENC_MAP_INPUT_RESOURCE_VER,
|
||||
),
|
||||
(
|
||||
"NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER",
|
||||
enc::NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER,
|
||||
@@ -609,6 +626,11 @@ fn nvenc_checks(checks: &mut Checks) {
|
||||
"NV_ENC_MEMORY_HEAP_AUTOSELECT",
|
||||
enc::NV_ENC_MEMORY_HEAP_AUTOSELECT,
|
||||
),
|
||||
(
|
||||
"NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR",
|
||||
enc::NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR,
|
||||
),
|
||||
("NV_ENC_INPUT_IMAGE", enc::NV_ENC_INPUT_IMAGE),
|
||||
(
|
||||
"NV_ENC_TUNING_INFO_HIGH_QUALITY",
|
||||
enc::NV_ENC_TUNING_INFO_HIGH_QUALITY,
|
||||
@@ -738,13 +760,11 @@ fn nvenc_checks(checks: &mut Checks) {
|
||||
// The entries taking structs this binding does not declare are passed
|
||||
// as `void *` here and never called; their places in the list are
|
||||
// checked above. reserved1 is not an entry point.
|
||||
const NOT_CALLED: [&str; 10] = [
|
||||
const NOT_CALLED: [&str; 8] = [
|
||||
"reserved1",
|
||||
"nvEncGetEncodeStats",
|
||||
"nvEncRegisterAsyncEvent",
|
||||
"nvEncUnregisterAsyncEvent",
|
||||
"nvEncMapInputResource",
|
||||
"nvEncRegisterResource",
|
||||
"nvEncCreateMVBuffer",
|
||||
"nvEncRunMotionEstimationOnly",
|
||||
"nvEncRestoreEncoderState",
|
||||
|
||||
@@ -16,6 +16,7 @@ use std::mem::MaybeUninit;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use crate::nvidia::cuda::Gpu;
|
||||
use crate::nvidia::cuda::ffi::CUdeviceptr;
|
||||
use crate::nvidia::dl::Library;
|
||||
use crate::nvidia::error::Error;
|
||||
use crate::nvidia::wait;
|
||||
@@ -142,7 +143,9 @@ pub(crate) fn check_status(
|
||||
///
|
||||
/// It keeps the buffers it makes ([`Session::create_input`] and the
|
||||
/// others), which its owner names by [`Buffer`], and destroys each once,
|
||||
/// before itself, as the header asks. The driver's handles never leave it:
|
||||
/// before itself, as the header asks; so too the device memory it
|
||||
/// registers as input ([`Session::register_input`]), unregistered once,
|
||||
/// after its last mapping is undone. The driver's handles never leave it:
|
||||
/// each call that names a buffer is made here, from the buffer's own
|
||||
/// handle, so that no other value reaches the driver as one.
|
||||
///
|
||||
@@ -166,6 +169,10 @@ pub(crate) struct Session {
|
||||
/// The output buffers submitted and not yet locked: what NVENC may
|
||||
/// still write, and what it may lock.
|
||||
submitted: RefCell<Submitted>,
|
||||
/// The registered inputs mapped for a picture submitted and not yet
|
||||
/// locked: each picture's output buffer, and the mapping, undone once
|
||||
/// the output is locked ([`Session::lock_bitstream`]).
|
||||
mapped: RefCell<Vec<(*mut c_void, *mut c_void)>>,
|
||||
/// Its lock thread, started with its first lock; `None` where no thread
|
||||
/// starts, or in a session finished on the thread of the session it
|
||||
/// was.
|
||||
@@ -199,15 +206,25 @@ enum BufferKind {
|
||||
},
|
||||
/// A bitstream buffer (`nvEncCreateBitstreamBuffer`).
|
||||
Bitstream,
|
||||
/// Device memory registered as input (`nvEncRegisterResource`), of
|
||||
/// frames of this size and format, rows `pitch` apart.
|
||||
Registered {
|
||||
width: u32,
|
||||
height: u32,
|
||||
format: ffi::NV_ENC_BUFFER_FORMAT,
|
||||
pitch: u32,
|
||||
},
|
||||
}
|
||||
|
||||
/// What [`Session::encode_picture`] submits.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) enum Submission {
|
||||
/// A frame from an input buffer, uploaded at `pitch`, into a bitstream
|
||||
/// buffer: `index` numbers it (`frameIdx`), `timestamp` comes back with
|
||||
/// its packet, and `idr` makes it an IDR picture with its parameter
|
||||
/// sets before it.
|
||||
/// A frame from an input buffer, uploaded at `pitch`, or from
|
||||
/// registered device memory, at its own pitch (`pitch` unread), mapped
|
||||
/// until the picture's output is locked, into a bitstream buffer:
|
||||
/// `index` numbers it (`frameIdx`), `timestamp` comes back with its
|
||||
/// packet, and `idr` makes it an IDR picture with its parameter sets
|
||||
/// before it.
|
||||
Frame {
|
||||
input: Buffer,
|
||||
output: Buffer,
|
||||
@@ -261,6 +278,7 @@ impl Session {
|
||||
config: None,
|
||||
buffers: Vec::new(),
|
||||
submitted: RefCell::new(Submitted::default()),
|
||||
mapped: RefCell::new(Vec::new()),
|
||||
locks: OnceCell::new(),
|
||||
stuck: RefCell::new(None),
|
||||
})
|
||||
@@ -363,6 +381,50 @@ impl Session {
|
||||
self.keep("nvEncCreateInputBuffer", input.inputBuffer, kind)
|
||||
}
|
||||
|
||||
/// Registers the device memory at `address`, on the session's GPU, as
|
||||
/// an input of `width` by `height` frames in `format`, rows `pitch`
|
||||
/// apart, the chroma's rows after the luma's `height` rows
|
||||
/// (`nvEncRegisterResource`, a CUDA device pointer). The memory must
|
||||
/// hold those rows for as long as the session lives.
|
||||
pub(crate) fn register_input(
|
||||
&mut self,
|
||||
address: CUdeviceptr,
|
||||
width: u32,
|
||||
height: u32,
|
||||
pitch: u32,
|
||||
format: ffi::NV_ENC_BUFFER_FORMAT,
|
||||
) -> Result<Buffer, Error> {
|
||||
let register = entry!(self.nvenc, nvEncRegisterResource)?;
|
||||
self.check_not_stalled()?;
|
||||
let address = usize::try_from(address)
|
||||
.map_err(|_| Error::Unsupported(format!("a device pointer of {address:#x}")))?;
|
||||
let mut resource = ffi::NV_ENC_REGISTER_RESOURCE::zeroed();
|
||||
resource.version = ffi::NV_ENC_REGISTER_RESOURCE_VER;
|
||||
resource.resourceType = ffi::NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
|
||||
resource.width = width;
|
||||
resource.height = height;
|
||||
resource.pitch = pitch;
|
||||
// The header: the device pointer itself, as the resource's handle.
|
||||
resource.resourceToRegister = std::ptr::with_exposed_provenance_mut(address);
|
||||
resource.bufferFormat = format;
|
||||
resource.bufferUsage = ffi::NV_ENC_INPUT_IMAGE;
|
||||
{
|
||||
let _current = self.gpu.push()?;
|
||||
// SAFETY: a live, initialised session; the parameters are live
|
||||
// and versioned, and name the caller's device memory.
|
||||
self.check("nvEncRegisterResource", unsafe {
|
||||
register(self.encoder, &raw mut resource)
|
||||
})?;
|
||||
}
|
||||
let kind = BufferKind::Registered {
|
||||
width,
|
||||
height,
|
||||
format,
|
||||
pitch,
|
||||
};
|
||||
self.keep("nvEncRegisterResource", resource.registeredResource, kind)
|
||||
}
|
||||
|
||||
/// Makes a bitstream buffer, of NVENC's own size.
|
||||
pub(crate) fn create_bitstream(&mut self) -> Result<Buffer, Error> {
|
||||
let create = entry!(self.nvenc, nvEncCreateBitstreamBuffer)?;
|
||||
@@ -418,6 +480,85 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a picture from `input` reads: an input buffer's handle and
|
||||
/// format, at the caller's pitch; or registered memory, mapped with the
|
||||
/// GPU's context current (the caller's), at its own pitch, and the
|
||||
/// mapping, which the caller undoes. Each with the frame's size.
|
||||
fn picture_input(&self, input: Buffer) -> Result<PictureInput, Error> {
|
||||
let Some(&Kept {
|
||||
handle,
|
||||
kind:
|
||||
BufferKind::Registered {
|
||||
width,
|
||||
height,
|
||||
pitch,
|
||||
..
|
||||
},
|
||||
}) = self.buffers.get(input.0)
|
||||
else {
|
||||
let (handle, width, height, format) = self.input(input)?;
|
||||
return Ok(PictureInput {
|
||||
handle,
|
||||
format,
|
||||
width,
|
||||
height,
|
||||
pitch: None,
|
||||
mapped: None,
|
||||
});
|
||||
};
|
||||
let map = entry!(self.nvenc, nvEncMapInputResource)?;
|
||||
let mut mapping = ffi::NV_ENC_MAP_INPUT_RESOURCE::zeroed();
|
||||
mapping.version = ffi::NV_ENC_MAP_INPUT_RESOURCE_VER;
|
||||
mapping.registeredResource = handle;
|
||||
// SAFETY: a live session and one of its registered resources; the
|
||||
// parameters are live and versioned.
|
||||
self.check("nvEncMapInputResource", unsafe {
|
||||
map(self.encoder, &raw mut mapping)
|
||||
})?;
|
||||
if mapping.mappedResource.is_null() {
|
||||
return Err(Error::Unsupported(
|
||||
"nvEncMapInputResource gave no input".to_owned(),
|
||||
));
|
||||
}
|
||||
Ok(PictureInput {
|
||||
handle: mapping.mappedResource,
|
||||
format: mapping.mappedBufferFmt,
|
||||
width,
|
||||
height,
|
||||
pitch: Some(pitch),
|
||||
mapped: Some(mapping.mappedResource),
|
||||
})
|
||||
}
|
||||
|
||||
/// Undoes `mapped`, a mapping of a registered input of the session's,
|
||||
/// with the GPU's context current (the caller's); what fails is
|
||||
/// logged.
|
||||
fn unmap(&self, mapped: *mut c_void) {
|
||||
let Some(unmap) = self.nvenc.api.nvEncUnmapInputResource else {
|
||||
return;
|
||||
};
|
||||
// SAFETY: a live session and one of its mappings, undone once.
|
||||
let status = unsafe { unmap(self.encoder, mapped) };
|
||||
if let Err(e) = self.check("nvEncUnmapInputResource", status) {
|
||||
log::warn!(kind:% = e; "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Undoes the mapping of the input of the picture submitted into
|
||||
/// `output`, if it read registered memory, once its output is locked.
|
||||
fn unmap_for(&self, output: *mut c_void) {
|
||||
let mapped = {
|
||||
let mut mapped = self.mapped.borrow_mut();
|
||||
let at = mapped.iter().position(|&(o, _)| o == output);
|
||||
at.map(|at| mapped.remove(at).1)
|
||||
};
|
||||
let Some(mapped) = mapped else { return };
|
||||
match self.gpu.push() {
|
||||
Ok(_current) => self.unmap(mapped),
|
||||
Err(e) => log::warn!(kind:% = e; "{e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `output`'s handle, where it is one of `kinds` of this session's.
|
||||
fn output(&self, output: Buffer, kinds: &[BufferKind]) -> Result<*mut c_void, Error> {
|
||||
match self.buffers.get(output.0) {
|
||||
@@ -509,8 +650,10 @@ impl Session {
|
||||
self.check_not_stalled()?;
|
||||
self.submitted.borrow().check_pending(output)?;
|
||||
let Lock { status, locked } = self.wait_for_lock(call, output)?;
|
||||
// Made, whatever it answers: a buffer is locked once a submission.
|
||||
// Made, whatever it answers: a buffer is locked once a submission,
|
||||
// and NVENC has done with the picture's input.
|
||||
self.submitted.borrow_mut().locked(output);
|
||||
self.unmap_for(output);
|
||||
self.check("nvEncLockBitstream", status)?;
|
||||
let _current = self.gpu.push()?;
|
||||
let guard = Locked::new(self, output, unlock, "nvEncUnlockBitstream");
|
||||
@@ -589,6 +732,7 @@ impl Session {
|
||||
}
|
||||
Err(e) => log::warn!(kind:% = e; "{e}"),
|
||||
}
|
||||
self.unmap_for(output);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -599,6 +743,10 @@ impl Session {
|
||||
pub(crate) fn encode_picture(&self, submission: Submission) -> Result<NVENCSTATUS, Error> {
|
||||
let encode = entry!(self.nvenc, nvEncEncodePicture)?;
|
||||
self.check_not_stalled()?;
|
||||
let _current = self.gpu.push()?;
|
||||
// The mapping of a registered input, and the output it is undone
|
||||
// with.
|
||||
let mut mapped = None;
|
||||
let mut picture = ffi::NV_ENC_PIC_PARAMS::zeroed();
|
||||
picture.version = ffi::NV_ENC_PIC_PARAMS_VER;
|
||||
match submission {
|
||||
@@ -610,15 +758,16 @@ impl Session {
|
||||
timestamp,
|
||||
idr,
|
||||
} => {
|
||||
let (input, width, height, format) = self.input(input)?;
|
||||
let output = self.output(output, &[BufferKind::Bitstream])?;
|
||||
self.submitted.borrow().check_free(output)?;
|
||||
picture.inputWidth = width;
|
||||
picture.inputHeight = height;
|
||||
picture.inputPitch = pitch;
|
||||
picture.inputBuffer = input;
|
||||
let input = self.picture_input(input)?;
|
||||
mapped = input.mapped.map(|mapped| (output, mapped));
|
||||
picture.inputWidth = input.width;
|
||||
picture.inputHeight = input.height;
|
||||
picture.inputPitch = input.pitch.unwrap_or(pitch);
|
||||
picture.inputBuffer = input.handle;
|
||||
picture.outputBitstream = output;
|
||||
picture.bufferFmt = format;
|
||||
picture.bufferFmt = input.format;
|
||||
picture.pictureStruct = ffi::NV_ENC_PIC_STRUCT_FRAME;
|
||||
picture.inputTimeStamp = timestamp;
|
||||
// The header: monotonically increasing from 0 where
|
||||
@@ -632,17 +781,26 @@ impl Session {
|
||||
}
|
||||
Submission::End => picture.encodePicFlags = ffi::NV_ENC_PIC_FLAG_EOS,
|
||||
}
|
||||
let _current = self.gpu.push()?;
|
||||
// SAFETY: a live session; the parameters are live and versioned,
|
||||
// and name two of this session's own buffers, not locked, or none
|
||||
// for the end.
|
||||
// and name two of this session's own buffers, not locked, or a
|
||||
// mapping of a registered input of its and one of its buffers, or
|
||||
// none for the end.
|
||||
let status = unsafe { encode(self.encoder, &raw mut picture) };
|
||||
if status != ffi::NV_ENC_ERR_NEED_MORE_INPUT {
|
||||
self.check("nvEncEncodePicture", status)?;
|
||||
if status != ffi::NV_ENC_ERR_NEED_MORE_INPUT
|
||||
&& let Err(e) = self.check("nvEncEncodePicture", status)
|
||||
{
|
||||
// Not taken: NVENC reads nothing of the input.
|
||||
if let Some((_, mapped)) = mapped {
|
||||
self.unmap(mapped);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
if !picture.outputBitstream.is_null() {
|
||||
self.submitted.borrow_mut().submit(picture.outputBitstream);
|
||||
}
|
||||
if let Some(mapped) = mapped {
|
||||
self.mapped.borrow_mut().push(mapped);
|
||||
}
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
@@ -829,12 +987,18 @@ impl Drop for Session {
|
||||
.push()
|
||||
.inspect_err(|e| log::warn!(kind:% = e; "{e}"));
|
||||
let api = &self.nvenc.api;
|
||||
// Its buffers first, as the header asks; none is locked, since each
|
||||
// lock is undone before the call that made it returns.
|
||||
// The mappings of registered inputs still standing, whose pictures
|
||||
// were never locked, then its buffers, as the header asks; none is
|
||||
// locked, since each lock is undone before the call that made it
|
||||
// returns.
|
||||
for (_, mapped) in self.mapped.take() {
|
||||
self.unmap(mapped);
|
||||
}
|
||||
for kept in &self.buffers {
|
||||
let destroy = match kept.kind {
|
||||
BufferKind::Input { .. } => api.nvEncDestroyInputBuffer,
|
||||
BufferKind::Bitstream => api.nvEncDestroyBitstreamBuffer,
|
||||
BufferKind::Registered { .. } => api.nvEncUnregisterResource,
|
||||
};
|
||||
let Some(destroy) = destroy else { continue };
|
||||
// SAFETY: a buffer of this live session, of the kind this entry
|
||||
@@ -876,6 +1040,7 @@ impl Session {
|
||||
config: self.config.take(),
|
||||
buffers: std::mem::take(&mut self.buffers),
|
||||
submitted: RefCell::new(submitted),
|
||||
mapped: RefCell::new(self.mapped.take()),
|
||||
locks: OnceCell::from(None),
|
||||
stuck: RefCell::new(None),
|
||||
};
|
||||
@@ -937,6 +1102,19 @@ impl Submitted {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a picture reads ([`Session::encode_picture`]): the input NVENC
|
||||
/// is given, its format and frame size, its own pitch where it has one,
|
||||
/// and the mapping to undo once the picture is locked, for registered
|
||||
/// memory.
|
||||
struct PictureInput {
|
||||
handle: *mut c_void,
|
||||
format: ffi::NV_ENC_BUFFER_FORMAT,
|
||||
width: u32,
|
||||
height: u32,
|
||||
pitch: Option<u32>,
|
||||
mapped: Option<*mut c_void>,
|
||||
}
|
||||
|
||||
/// The refusal of `buffer`, of another kind than a call takes.
|
||||
fn not_for_the_call(buffer: Buffer) -> Error {
|
||||
Error::Unsupported(format!(
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
//! NVENC decides each picture's type (`enablePTD`), writes its own
|
||||
//! parameter sets and slice headers, and keeps its own references; this
|
||||
//! module configures it from a preset, copies each frame into an input
|
||||
//! buffer of NVENC's, and reads each access unit back. A key frame is
|
||||
//! buffer of NVENC's, or has NVENC read it where another API's GPU wrote
|
||||
//! it, in memory CUDA imported ([`NvencEncoder::encode_device`]), and reads
|
||||
//! each access unit back. A key frame is
|
||||
//! forced where the caller asks for one; NVENC places the rest by its GOP
|
||||
//! length. B pictures are never references here, so a reference is encoded
|
||||
//! at most one frame ahead of its display order.
|
||||
@@ -16,6 +18,7 @@ use super::ffi::{self, GUID, Zeroed};
|
||||
use super::{Buffer, Session, Submission};
|
||||
use crate::nvidia::cuda::Gpu;
|
||||
use crate::nvidia::error::Error;
|
||||
use crate::nvidia::external::ImportedBuffer;
|
||||
|
||||
/// A profile NVENC is asked to encode.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -220,12 +223,42 @@ pub struct RawFrame<'a> {
|
||||
pub force_idr: bool,
|
||||
}
|
||||
|
||||
/// One raw frame in device memory another API's GPU wrote, imported on the
|
||||
/// encoder's GPU ([`NvencEncoder::encode_device`]): its luma's rows from
|
||||
/// the import's first byte, `pitch` apart, then its chroma's rows, half as
|
||||
/// many (rounded up), at the same pitch, at the profile's bit depth.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct DeviceFrame<'a> {
|
||||
/// The memory the frame lies in.
|
||||
pub input: &'a Arc<ImportedBuffer>,
|
||||
/// Bytes from one row to the next: a multiple of 4, as NVENC takes it.
|
||||
pub pitch: u32,
|
||||
/// The caller's index for the frame, given back with its packet; each
|
||||
/// later than the last.
|
||||
pub index: u64,
|
||||
/// Whether it must be an IDR picture.
|
||||
pub force_idr: bool,
|
||||
}
|
||||
|
||||
/// An input buffer and a bitstream buffer of the session.
|
||||
struct Slot {
|
||||
input: Buffer,
|
||||
output: Buffer,
|
||||
}
|
||||
|
||||
/// Device memory registered with the session as input
|
||||
/// ([`NvencEncoder::encode_device`]), at a pitch, and held while the
|
||||
/// session lives.
|
||||
struct DeviceInput {
|
||||
import: Arc<ImportedBuffer>,
|
||||
pitch: u32,
|
||||
registered: Buffer,
|
||||
}
|
||||
|
||||
/// Ours: the most device inputs a session registers. A caller writes its
|
||||
/// frames into a few memories in turn.
|
||||
const MOST_DEVICE_INPUTS: usize = 8;
|
||||
|
||||
/// An NVENC encoder.
|
||||
pub struct NvencEncoder {
|
||||
params: EncodeParams,
|
||||
@@ -240,7 +273,14 @@ pub struct NvencEncoder {
|
||||
submitted: u32,
|
||||
/// The parameter sets, Annex B, as `nvEncGetSequenceParams` gives them.
|
||||
sequence_parameters: Vec<u8>,
|
||||
/// The registered input each slot's pending frame reads, if it is
|
||||
/// device memory.
|
||||
slot_inputs: Vec<Option<Buffer>>,
|
||||
session: Session,
|
||||
/// The device memory registered as input. After the session, which
|
||||
/// unregisters it as it drops, so that the imports outlive their
|
||||
/// registrations.
|
||||
device_inputs: Vec<DeviceInput>,
|
||||
}
|
||||
|
||||
/// Ours: input and bitstream buffers beyond what NVENC holds, so that a
|
||||
@@ -287,7 +327,9 @@ impl NvencEncoder {
|
||||
held: params.b_frames,
|
||||
submitted: 0,
|
||||
sequence_parameters: Vec::new(),
|
||||
slot_inputs: Vec::new(),
|
||||
session,
|
||||
device_inputs: Vec::new(),
|
||||
};
|
||||
let count = usize::try_from(encoder.held).unwrap_or(0) + 1 + EXTRA_SLOTS;
|
||||
for _ in 0..count {
|
||||
@@ -300,6 +342,7 @@ impl NvencEncoder {
|
||||
output: encoder.session.create_bitstream()?,
|
||||
};
|
||||
encoder.slots.push(slot);
|
||||
encoder.slot_inputs.push(None);
|
||||
}
|
||||
encoder.sequence_parameters = encoder
|
||||
.session
|
||||
@@ -329,33 +372,143 @@ impl NvencEncoder {
|
||||
/// decode order, each with its own result. `Err` is a frame NVENC did
|
||||
/// not take.
|
||||
pub fn encode(&mut self, frame: &RawFrame<'_>) -> Result<Vec<Bitstream>, Error> {
|
||||
let slot_index = self.next;
|
||||
if self.pending.contains(&slot_index) {
|
||||
let slot_index = self.free_slot()?;
|
||||
let input = self.slots[slot_index].input;
|
||||
let pitch = self.session.upload(
|
||||
input,
|
||||
frame.luma,
|
||||
frame.chroma,
|
||||
self.row_bytes(),
|
||||
self.rows(),
|
||||
)?;
|
||||
self.submit(slot_index, input, pitch, frame.index, frame.force_idr)
|
||||
}
|
||||
|
||||
/// Encodes one frame NVENC reads where another API's GPU wrote it
|
||||
/// ([`DeviceFrame`]), as [`Self::encode`] encodes one it copies: the
|
||||
/// memory is registered with the session on its first frame at its
|
||||
/// pitch, and mapped for each frame until its packet comes out. The
|
||||
/// caller writes it, and waits for the writes, before the call, and not
|
||||
/// again until the frame's packet came out. `Err` is a frame NVENC did
|
||||
/// not take: memory of another GPU, too short or at a pitch NVENC does
|
||||
/// not take, or still read for a frame not out yet.
|
||||
pub fn encode_device(&mut self, frame: &DeviceFrame<'_>) -> Result<Vec<Bitstream>, Error> {
|
||||
let registered = self.device_input(frame.input, frame.pitch)?;
|
||||
let in_flight =
|
||||
(self.pending.iter()).any(|&slot| self.slot_inputs[slot] == Some(registered));
|
||||
if in_flight {
|
||||
return Err(Error::Unsupported(
|
||||
"NVENC holds more frames than it has buffers".to_owned(),
|
||||
"device memory NVENC still reads for a frame not out yet".to_owned(),
|
||||
));
|
||||
}
|
||||
let Slot { input, output } = self.slots[slot_index];
|
||||
let slot_index = self.free_slot()?;
|
||||
self.slot_inputs[slot_index] = Some(registered);
|
||||
self.submit(
|
||||
slot_index,
|
||||
registered,
|
||||
frame.pitch,
|
||||
frame.index,
|
||||
frame.force_idr,
|
||||
)
|
||||
}
|
||||
|
||||
/// The bytes of a frame's row: its width in samples of its bit depth.
|
||||
fn row_bytes(&self) -> usize {
|
||||
let bytes_per_sample = if self.params.profile.bit_depth() > 8 {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let row_bytes = usize::try_from(self.params.width)
|
||||
usize::try_from(self.params.width)
|
||||
.unwrap_or(0)
|
||||
.saturating_mul(bytes_per_sample);
|
||||
let rows = usize::try_from(self.params.height).unwrap_or(0);
|
||||
let pitch = self
|
||||
.session
|
||||
.upload(input, frame.luma, frame.chroma, row_bytes, rows)?;
|
||||
.saturating_mul(bytes_per_sample)
|
||||
}
|
||||
|
||||
/// A frame's luma rows.
|
||||
fn rows(&self) -> usize {
|
||||
usize::try_from(self.params.height).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The slot the next frame goes in, where its last frame is out.
|
||||
fn free_slot(&self) -> Result<usize, Error> {
|
||||
if self.pending.contains(&self.next) {
|
||||
return Err(Error::Unsupported(
|
||||
"NVENC holds more frames than it has buffers".to_owned(),
|
||||
));
|
||||
}
|
||||
Ok(self.next)
|
||||
}
|
||||
|
||||
/// `import`'s registration with the session at `pitch`: the one made
|
||||
/// for an earlier frame, else a new one, where the memory is the
|
||||
/// session's GPU's and holds a frame at that pitch.
|
||||
fn device_input(&mut self, import: &Arc<ImportedBuffer>, pitch: u32) -> Result<Buffer, Error> {
|
||||
let kept = (self.device_inputs.iter())
|
||||
.find(|d| Arc::ptr_eq(&d.import, import) && d.pitch == pitch);
|
||||
if let Some(kept) = kept {
|
||||
return Ok(kept.registered);
|
||||
}
|
||||
if !Arc::ptr_eq(import.gpu(), &self.session.gpu) {
|
||||
return Err(Error::Unsupported(
|
||||
"device memory imported on another GPU than the encoder's".to_owned(),
|
||||
));
|
||||
}
|
||||
let rows = self.rows();
|
||||
let wide = usize::try_from(pitch).unwrap_or(0);
|
||||
let needed = wide.checked_mul(rows + rows.div_ceil(2));
|
||||
if pitch % 4 != 0 || wide < self.row_bytes() || needed.is_none_or(|n| n > import.length()) {
|
||||
return Err(Error::Unsupported(format!(
|
||||
"device memory of {} bytes for {}x{} frames at a pitch of {pitch}",
|
||||
import.length(),
|
||||
self.params.width,
|
||||
self.params.height
|
||||
)));
|
||||
}
|
||||
if self.device_inputs.len() >= MOST_DEVICE_INPUTS {
|
||||
return Err(Error::Unsupported(format!(
|
||||
"more than {MOST_DEVICE_INPUTS} device memories as NVENC's input"
|
||||
)));
|
||||
}
|
||||
let registered = self.session.register_input(
|
||||
import.address_at(0),
|
||||
self.params.width,
|
||||
self.params.height,
|
||||
pitch,
|
||||
self.params.profile.buffer_format(),
|
||||
)?;
|
||||
self.device_inputs.push(DeviceInput {
|
||||
import: Arc::clone(import),
|
||||
pitch,
|
||||
registered,
|
||||
});
|
||||
Ok(registered)
|
||||
}
|
||||
|
||||
/// Submits the frame in `input` at `pitch` into `slot_index`'s
|
||||
/// bitstream buffer, and reads what comes out ([`Self::encode`]).
|
||||
fn submit(
|
||||
&mut self,
|
||||
slot_index: usize,
|
||||
input: Buffer,
|
||||
pitch: u32,
|
||||
index: u64,
|
||||
force_idr: bool,
|
||||
) -> Result<Vec<Bitstream>, Error> {
|
||||
let status = self.session.encode_picture(Submission::Frame {
|
||||
input,
|
||||
output,
|
||||
output: self.slots[slot_index].output,
|
||||
pitch,
|
||||
index: self.submitted,
|
||||
timestamp: frame.index,
|
||||
idr: frame.force_idr,
|
||||
})?;
|
||||
timestamp: index,
|
||||
idr: force_idr,
|
||||
});
|
||||
let status = match status {
|
||||
Ok(status) => status,
|
||||
Err(e) => {
|
||||
self.slot_inputs[slot_index] = None;
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
self.submitted = self.submitted.wrapping_add(1);
|
||||
self.next = (slot_index + 1) % self.slots.len();
|
||||
self.pending.push_back(slot_index);
|
||||
@@ -383,6 +536,7 @@ impl NvencEncoder {
|
||||
while let Some(slot_index) = self.pending.pop_front() {
|
||||
let output = self.slots[slot_index].output;
|
||||
bitstreams.push(self.read_bitstream(output));
|
||||
self.slot_inputs[slot_index] = None;
|
||||
}
|
||||
bitstreams
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! NVENC's declarations (`nvEncodeAPI.h`), the subset this crate uses, at
|
||||
//! NVENC API 13.1: the function list, sessions on a CUDA context, the codec,
|
||||
//! profile and preset GUIDs, caps, the configuration and initialisation,
|
||||
//! input and bitstream buffers, pictures, and the sequence parameters.
|
||||
//! input and bitstream buffers, CUDA memory registered and mapped as input,
|
||||
//! pictures, and the sequence parameters.
|
||||
//!
|
||||
//! Field names are the header's, so that `crate::nvidia::layout`'s test can check
|
||||
//! each size and offset against ffnvcodec's `nvEncodeAPI.h` (13.1.15.0).
|
||||
@@ -67,6 +68,8 @@ pub(crate) const NV_ENC_PRESET_CONFIG_VER: u32 = struct_version(5) | (1 << 31);
|
||||
pub(crate) const NV_ENC_PIC_PARAMS_VER: u32 = struct_version(7) | (1 << 31);
|
||||
pub(crate) const NV_ENC_LOCK_BITSTREAM_VER: u32 = struct_version(2) | (1 << 31);
|
||||
pub(crate) const NV_ENC_LOCK_INPUT_BUFFER_VER: u32 = struct_version(1);
|
||||
pub(crate) const NV_ENC_REGISTER_RESOURCE_VER: u32 = struct_version(5);
|
||||
pub(crate) const NV_ENC_MAP_INPUT_RESOURCE_VER: u32 = struct_version(4);
|
||||
pub(crate) const NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER: u32 = struct_version(1);
|
||||
pub(crate) const NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER: u32 = struct_version(1);
|
||||
pub(crate) const NV_ENCODE_API_FUNCTION_LIST_VER: u32 = struct_version(2);
|
||||
@@ -116,6 +119,11 @@ pub(crate) const NV_ENC_BUFFER_FORMAT_YUV420_10BIT: NV_ENC_BUFFER_FORMAT = 0x1_0
|
||||
|
||||
pub(crate) const NV_ENC_MEMORY_HEAP_AUTOSELECT: NvEncEnum = 0;
|
||||
|
||||
/// `NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR`: a CUDA device pointer.
|
||||
pub(crate) const NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR: NvEncEnum = 1;
|
||||
/// `NV_ENC_INPUT_IMAGE`: a registered resource used as an input picture.
|
||||
pub(crate) const NV_ENC_INPUT_IMAGE: NvEncEnum = 0;
|
||||
|
||||
pub(crate) const NV_ENC_TUNING_INFO_HIGH_QUALITY: NV_ENC_TUNING_INFO = 1;
|
||||
pub(crate) const NV_ENC_TUNING_INFO_LOW_LATENCY: NV_ENC_TUNING_INFO = 2;
|
||||
|
||||
@@ -763,6 +771,41 @@ pub(crate) struct NV_ENC_LOCK_INPUT_BUFFER {
|
||||
pub(crate) reserved2: [*mut c_void; 64],
|
||||
}
|
||||
|
||||
/// `NV_ENC_REGISTER_RESOURCE`.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct NV_ENC_REGISTER_RESOURCE {
|
||||
pub(crate) version: u32,
|
||||
pub(crate) resourceType: NvEncEnum,
|
||||
pub(crate) width: u32,
|
||||
pub(crate) height: u32,
|
||||
pub(crate) pitch: u32,
|
||||
pub(crate) subResourceIndex: u32,
|
||||
pub(crate) resourceToRegister: *mut c_void,
|
||||
pub(crate) registeredResource: *mut c_void,
|
||||
pub(crate) bufferFormat: NV_ENC_BUFFER_FORMAT,
|
||||
pub(crate) bufferUsage: NvEncEnum,
|
||||
pub(crate) pInputFencePoint: *mut c_void,
|
||||
pub(crate) chromaOffset: [u32; 2],
|
||||
pub(crate) chromaOffsetIn: [u32; 2],
|
||||
pub(crate) reserved1: [u32; 244],
|
||||
pub(crate) reserved2: [*mut c_void; 61],
|
||||
}
|
||||
|
||||
/// `NV_ENC_MAP_INPUT_RESOURCE`.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct NV_ENC_MAP_INPUT_RESOURCE {
|
||||
pub(crate) version: u32,
|
||||
pub(crate) subResourceIndex: u32,
|
||||
pub(crate) inputResource: *mut c_void,
|
||||
pub(crate) registeredResource: *mut c_void,
|
||||
pub(crate) mappedResource: *mut c_void,
|
||||
pub(crate) mappedBufferFmt: NV_ENC_BUFFER_FORMAT,
|
||||
pub(crate) reserved1: [u32; 251],
|
||||
pub(crate) reserved2: [*mut c_void; 63],
|
||||
}
|
||||
|
||||
/// `NV_ENC_SEQUENCE_PARAM_PAYLOAD`.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -904,13 +947,13 @@ function_list! {
|
||||
nvEncGetSequenceParams: fn(Encoder, *mut NV_ENC_SEQUENCE_PARAM_PAYLOAD) -> NVENCSTATUS;
|
||||
nvEncRegisterAsyncEvent: fn(Encoder, *mut c_void) -> NVENCSTATUS;
|
||||
nvEncUnregisterAsyncEvent: fn(Encoder, *mut c_void) -> NVENCSTATUS;
|
||||
nvEncMapInputResource: fn(Encoder, *mut c_void) -> NVENCSTATUS;
|
||||
nvEncMapInputResource: fn(Encoder, *mut NV_ENC_MAP_INPUT_RESOURCE) -> NVENCSTATUS;
|
||||
nvEncUnmapInputResource: fn(Encoder, *mut c_void) -> NVENCSTATUS;
|
||||
nvEncDestroyEncoder: fn(Encoder) -> NVENCSTATUS;
|
||||
nvEncInvalidateRefFrames: fn(Encoder, u64) -> NVENCSTATUS;
|
||||
nvEncOpenEncodeSessionEx: fn(*mut NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS, *mut Encoder)
|
||||
-> NVENCSTATUS;
|
||||
nvEncRegisterResource: fn(Encoder, *mut c_void) -> NVENCSTATUS;
|
||||
nvEncRegisterResource: fn(Encoder, *mut NV_ENC_REGISTER_RESOURCE) -> NVENCSTATUS;
|
||||
nvEncUnregisterResource: fn(Encoder, *mut c_void) -> NVENCSTATUS;
|
||||
nvEncReconfigureEncoder: fn(Encoder, *mut NV_ENC_RECONFIGURE_PARAMS) -> NVENCSTATUS;
|
||||
reserved1: fn() -> NVENCSTATUS;
|
||||
@@ -970,6 +1013,10 @@ unsafe impl Zeroed for NV_ENC_LOCK_BITSTREAM {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Zeroed for NV_ENC_LOCK_INPUT_BUFFER {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Zeroed for NV_ENC_REGISTER_RESOURCE {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Zeroed for NV_ENC_MAP_INPUT_RESOURCE {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Zeroed for NV_ENC_SEQUENCE_PARAM_PAYLOAD {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Zeroed for NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS {}
|
||||
@@ -996,6 +1043,8 @@ const _: () = {
|
||||
assert!(size_of::<NV_ENC_PIC_PARAMS>() == 3360);
|
||||
assert!(size_of::<NV_ENC_LOCK_BITSTREAM>() == 1544);
|
||||
assert!(size_of::<NV_ENC_LOCK_INPUT_BUFFER>() == 1544);
|
||||
assert!(size_of::<NV_ENC_REGISTER_RESOURCE>() == 1536);
|
||||
assert!(size_of::<NV_ENC_MAP_INPUT_RESOURCE>() == 1544);
|
||||
assert!(size_of::<NV_ENC_SEQUENCE_PARAM_PAYLOAD>() == 1544);
|
||||
assert!(size_of::<NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS>() == 1552);
|
||||
assert!(size_of::<NV_ENCODE_API_FUNCTION_LIST>() == 2552);
|
||||
|
||||
@@ -41,6 +41,8 @@
|
||||
//!
|
||||
//! Elsewhere, and where CUDA refuses the import or the view (logged once a session with why),
|
||||
//! the picture is read back into the decoder's staging memory and copied by the CPU.
|
||||
//! - **An encode's frame** is copied by the GPU into an exportable buffer CUDA imported, which
|
||||
//! NVENC reads, where CUDA imports the device's exportable buffers (`encode`'s module doc).
|
||||
//! - **A picture the GPU does not finish** by its deadline fails its landing, and every later
|
||||
//! picture of the decoder; its copy keeps the planes' mappings and CUDA's registrations of them
|
||||
//! until the GPU is done, but not the guest's buffers, so a copy that ends that late may write
|
||||
@@ -403,8 +405,22 @@ impl GraphicsVideo<VulkanPlatform> for Shared {
|
||||
if direction == RGFX_VIDEO_ENCODE {
|
||||
let entry = (video.encode.iter()).find(|c| c.codec == codec)?;
|
||||
let caps = encode::encode_caps(entry, &video.encoders);
|
||||
let encoder =
|
||||
encode::NvencHostEncoder::new(&video.gpu, codec, &video.encoders, entry, &caps);
|
||||
let filler = match video.imports {
|
||||
Some(_) => Ok(encode::Filler::new(
|
||||
&video.device,
|
||||
&video.gpu,
|
||||
&video.runtime,
|
||||
)),
|
||||
None => Err("CUDA imports no exportable buffer of the device".to_owned()),
|
||||
};
|
||||
let encoder = encode::NvencHostEncoder::new(
|
||||
&video.gpu,
|
||||
codec,
|
||||
&video.encoders,
|
||||
entry,
|
||||
&caps,
|
||||
filler,
|
||||
);
|
||||
let session =
|
||||
HostEncodeSession::new(&video.device, codec, ENCODE_NAME, Box::new(encoder))?;
|
||||
return Some(Arc::new(session));
|
||||
|
||||
@@ -18,11 +18,16 @@
|
||||
//! an IDR picture with its parameter sets; a change of the bitrates, QPs or frame rate goes to
|
||||
//! the encoder from the next frame. `min_qp`, `max_qp` and a change of `quality` alone are not
|
||||
//! taken, as the VA-API arm takes none of them.
|
||||
//! - **A frame** ([`NvencFrame`]) is read on the session's encode thread from the source's host
|
||||
//! bytes into NVENC's input buffer and encoded there. NVENC writes the access unit in Annex-B
|
||||
//! form, its parameter sets before each IDR picture (the crate's `repeatSPSPPS`), so it is
|
||||
//! written as it comes. One that does not fit the capacity is not written, and the next frame
|
||||
//! is made an IDR picture.
|
||||
//! - **A frame** ([`NvencFrame`]) reaches NVENC on the session's encode thread one of two ways.
|
||||
//! By the runtime device's GPU, where CUDA imports the device's exportable buffers
|
||||
//! (`super::imports_caches`): a copy of the source's planes, where they lie, in the surface's
|
||||
//! pages or its device caches, into memory NVENC registers as input ([`fill`]), so that no CPU
|
||||
//! copies the frame. Else, and where the copy or NVENC's read of it is declined (said once a
|
||||
//! session, with why, at info), from the source's host bytes, which NVENC's input buffer takes
|
||||
//! by the CPU's copy. NVENC encodes the same bytes either way. It writes the access unit in
|
||||
//! Annex-B form, its parameter sets before each IDR picture (the crate's `repeatSPSPPS`), so it
|
||||
//! is written as it comes. One that does not fit the capacity is not written, and the next
|
||||
//! frame is made an IDR picture.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -37,8 +42,8 @@ use reims_vgpu_graphics::wire::{
|
||||
RGFX_VIDEO_HEVC_MAIN, RGFX_VIDEO_HEVC_MAIN_10, RgfxVideoCodecCaps, RgfxVideoEncodeCaps,
|
||||
};
|
||||
use reims_vgpu_video::nvidia::{
|
||||
EncodeParams, EncodeProfile, EncodeProfileSupport, EncodeRateControl, Gpu, NvencEncoder,
|
||||
PictureType, RawFrame, Tuning,
|
||||
Bitstream, DeviceFrame, EncodeParams, EncodeProfile, EncodeProfileSupport, EncodeRateControl,
|
||||
Gpu, NvencEncoder, PictureType, RawFrame, Tuning,
|
||||
};
|
||||
use reims_vgpu_vulkan::core::platform::Platform;
|
||||
use reims_vgpu_vulkan::core::sync::Mutex;
|
||||
@@ -46,7 +51,11 @@ use reims_vgpu_vulkan::core::sync::Mutex;
|
||||
use super::super::video_host::{
|
||||
BackendError, EncodeFrame, Encoded, FrameSource, HostEncodedFrame, HostEncoder, SourcePlane,
|
||||
};
|
||||
use super::{H264_TOP_LEVEL, HEVC_TOP_LEVEL};
|
||||
use super::{ENCODE_NAME, H264_TOP_LEVEL, HEVC_TOP_LEVEL};
|
||||
use fill::Filled;
|
||||
pub(super) use fill::Filler;
|
||||
|
||||
mod fill;
|
||||
|
||||
/// Ours, as the VA-API arm's: a VBR's peak where the guest sets none, as a share of its
|
||||
/// average: 1.05.
|
||||
@@ -282,9 +291,32 @@ impl State {
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's GPU filler, its frames' to share, or why it has none; and the reasons a frame was
|
||||
/// uploaded instead, each said once.
|
||||
struct Fills<P: Platform> {
|
||||
filler: Result<Filler<P>, String>,
|
||||
said: Vec<String>,
|
||||
}
|
||||
|
||||
impl<P: Platform> Fills<P> {
|
||||
/// Says, once a session, and at info once per process (`kind`), why a frame was uploaded by
|
||||
/// the CPU.
|
||||
fn uploaded_because(&mut self, why: String) {
|
||||
if !self.said.contains(&why) {
|
||||
log::info!(
|
||||
kind:% = why;
|
||||
"hardware video: {ENCODE_NAME}: a frame uploaded by the CPU: {why}"
|
||||
);
|
||||
self.said.push(why);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's encoder on NVENC ([`HostEncoder`]).
|
||||
pub(super) struct NvencHostEncoder {
|
||||
pub(super) struct NvencHostEncoder<P: Platform> {
|
||||
state: Arc<Mutex<State>>,
|
||||
/// What writes its frames into memory NVENC reads, on the GPU (module doc).
|
||||
fills: Arc<Mutex<Fills<P>>>,
|
||||
/// The profiles NVENC encodes of the codec, which [`HostEncoder::check`] holds settings to.
|
||||
profiles: Vec<EncodeProfile>,
|
||||
/// The sizes the codec's entry gives.
|
||||
@@ -294,15 +326,17 @@ pub(super) struct NvencHostEncoder {
|
||||
rate_controls: u32,
|
||||
}
|
||||
|
||||
impl NvencHostEncoder {
|
||||
impl<P: Platform> NvencHostEncoder<P> {
|
||||
/// An encoder of `codec` on `gpu`, which encodes `supports`, as its entry `entry` and
|
||||
/// `encode` list them.
|
||||
/// `encode` list them, its frames written into memory NVENC reads by `filler` where it is
|
||||
/// given (or why not).
|
||||
pub(super) fn new(
|
||||
gpu: &Arc<Gpu>,
|
||||
codec: u32,
|
||||
supports: &[EncodeProfileSupport],
|
||||
entry: &RgfxVideoCodecCaps,
|
||||
encode: &RgfxVideoEncodeCaps,
|
||||
filler: Result<Filler<P>, String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
state: Arc::new(Mutex::new(State {
|
||||
@@ -312,6 +346,10 @@ impl NvencHostEncoder {
|
||||
settings: None,
|
||||
key_next: false,
|
||||
})),
|
||||
fills: Arc::new(Mutex::new(Fills {
|
||||
filler,
|
||||
said: Vec::new(),
|
||||
})),
|
||||
profiles: (supports.iter())
|
||||
.map(|s| s.profile)
|
||||
.filter(|p| wire_profile(*p).0 == codec)
|
||||
@@ -323,7 +361,7 @@ impl NvencHostEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> HostEncoder<P> for NvencHostEncoder {
|
||||
impl<P: Platform> HostEncoder<P> for NvencHostEncoder<P> {
|
||||
fn check(&self, settings: &RgfxVideoEncodeSettings) -> Result<(), BackendError> {
|
||||
let codec = self.state.lock().codec;
|
||||
let profile = encode_profile(codec, settings.profile)
|
||||
@@ -360,29 +398,34 @@ impl<P: Platform> HostEncoder<P> for NvencHostEncoder {
|
||||
fn encode(&mut self, frame: EncodeFrame) -> Result<Box<dyn HostEncodedFrame<P>>, BackendError> {
|
||||
Ok(Box::new(NvencFrame {
|
||||
state: Arc::clone(&self.state),
|
||||
fills: Arc::clone(&self.fills),
|
||||
frame,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame's encode on NVENC, which the session's encode thread finishes (module doc).
|
||||
struct NvencFrame {
|
||||
struct NvencFrame<P: Platform> {
|
||||
state: Arc<Mutex<State>>,
|
||||
fills: Arc<Mutex<Fills<P>>>,
|
||||
frame: EncodeFrame,
|
||||
}
|
||||
|
||||
impl<P: Platform> HostEncodedFrame<P> for NvencFrame {
|
||||
impl<P: Platform> HostEncodedFrame<P> for NvencFrame<P> {
|
||||
fn finish(
|
||||
self: Box<Self>,
|
||||
source: &mut FrameSource<'_, P>,
|
||||
out: &mut [u8],
|
||||
) -> Result<Encoded, BackendError> {
|
||||
let source = source.host()?;
|
||||
let mut state = self.state.lock();
|
||||
if let Some(settings) = &self.frame.settings {
|
||||
state.apply(settings)?;
|
||||
}
|
||||
let force_idr = self.frame.force_keyframe || state.key_next;
|
||||
if let Some(packets) = self.filled(&mut state, source, force_idr)? {
|
||||
return finish_packets(&mut state, packets, out);
|
||||
}
|
||||
let source = source.host()?;
|
||||
let encoder = state.encoder.as_mut().ok_or("an encode with no settings")?;
|
||||
let raw = RawFrame {
|
||||
luma: (plane(&source.luma)?, source.luma.bytes_per_row),
|
||||
@@ -390,42 +433,108 @@ impl<P: Platform> HostEncodedFrame<P> for NvencFrame {
|
||||
index: self.frame.frame_index,
|
||||
force_idr,
|
||||
};
|
||||
let mut packets = encoder.encode(&raw)?;
|
||||
let packet = match (packets.pop(), packets.len()) {
|
||||
(Some(Ok(packet)), 0) => packet,
|
||||
(Some(Err(error)), 0) => return Err(format!("the frame's access unit: {error}").into()),
|
||||
(None, _) => return Err("NVENC gave no access unit for the frame".into()),
|
||||
(Some(_), n) => return Err(format!("NVENC gave {} access units", n + 1).into()),
|
||||
};
|
||||
let keyframe = packet.picture_type == PictureType::Idr;
|
||||
let mut encoded = Encoded {
|
||||
size: packet.data.len() as u64,
|
||||
overflow: false,
|
||||
keyframe,
|
||||
// NVENC writes the parameter sets before each IDR picture (module doc).
|
||||
parameter_sets: keyframe,
|
||||
frame_index: packet.index,
|
||||
picture_type: match packet.picture_type {
|
||||
PictureType::Idr | PictureType::Intra => RGFX_VIDEO_PICTURE_I,
|
||||
PictureType::Predicted | PictureType::NonReferencePredicted => RGFX_VIDEO_PICTURE_P,
|
||||
PictureType::Bidirectional => RGFX_VIDEO_PICTURE_B,
|
||||
},
|
||||
};
|
||||
match out.get_mut(..packet.data.len()) {
|
||||
Some(to) => {
|
||||
to.copy_from_slice(&packet.data);
|
||||
state.key_next = false;
|
||||
}
|
||||
None => {
|
||||
// The frame is in the encoder's references: the next one starts afresh.
|
||||
encoded.overflow = true;
|
||||
state.key_next = true;
|
||||
}
|
||||
}
|
||||
Ok(encoded)
|
||||
let packets = encoder.encode(&raw)?;
|
||||
finish_packets(&mut state, packets, out)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> NvencFrame<P> {
|
||||
/// The frame's packets, encoded from `source`'s planes where they lie, copied by the GPU into
|
||||
/// memory NVENC reads (module doc); `None` where the copy or NVENC's read of it was declined,
|
||||
/// nothing encoded, which is said once a session. `Err` where the copy failed once on the
|
||||
/// GPU, or NVENC did not take the frame it read.
|
||||
fn filled(
|
||||
&self,
|
||||
state: &mut State,
|
||||
source: &FrameSource<'_, P>,
|
||||
force_idr: bool,
|
||||
) -> Result<Option<Vec<Bitstream>>, BackendError> {
|
||||
let mut fills = self.fills.lock();
|
||||
let declined = match &mut fills.filler {
|
||||
Ok(filler) => {
|
||||
let encoder = state.encoder.as_mut().ok_or("an encode with no settings")?;
|
||||
let [luma, chroma] = source.planes();
|
||||
let sample = if encoder.params().profile.bit_depth() > 8 {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
match filler.fill(luma, chroma, source.size(), sample) {
|
||||
Ok(Filled::Written { input, pitch }) => {
|
||||
let frame = DeviceFrame {
|
||||
input: &input,
|
||||
pitch,
|
||||
index: self.frame.frame_index,
|
||||
force_idr,
|
||||
};
|
||||
match encoder.encode_device(&frame) {
|
||||
Ok(packets) => return Ok(Some(packets)),
|
||||
// NVENC took nothing of the frame: it is uploaded, and so are the
|
||||
// session's frames from here on.
|
||||
Err(error) => {
|
||||
let why = format!("NVENC's read of the GPU's copy: {error}");
|
||||
fills.filler = Err(why.clone());
|
||||
why
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Filled::Declined(why)) => format!("the GPU's copy: {why}"),
|
||||
// The GPU may write the input still: the session's frames are uploaded from
|
||||
// here on.
|
||||
Err(error) => {
|
||||
fills.filler = Err(format!("the GPU's copy failed: {error}"));
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(why) => why.clone(),
|
||||
};
|
||||
fills.uploaded_because(declined);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the one access unit of `packets`, the frame's, into `out` where it fits (module doc),
|
||||
/// and answers what came of it.
|
||||
fn finish_packets(
|
||||
state: &mut State,
|
||||
mut packets: Vec<Bitstream>,
|
||||
out: &mut [u8],
|
||||
) -> Result<Encoded, BackendError> {
|
||||
let packet = match (packets.pop(), packets.len()) {
|
||||
(Some(Ok(packet)), 0) => packet,
|
||||
(Some(Err(error)), 0) => return Err(format!("the frame's access unit: {error}").into()),
|
||||
(None, _) => return Err("NVENC gave no access unit for the frame".into()),
|
||||
(Some(_), n) => return Err(format!("NVENC gave {} access units", n + 1).into()),
|
||||
};
|
||||
let keyframe = packet.picture_type == PictureType::Idr;
|
||||
let mut encoded = Encoded {
|
||||
size: packet.data.len() as u64,
|
||||
overflow: false,
|
||||
keyframe,
|
||||
// NVENC writes the parameter sets before each IDR picture (module doc).
|
||||
parameter_sets: keyframe,
|
||||
frame_index: packet.index,
|
||||
picture_type: match packet.picture_type {
|
||||
PictureType::Idr | PictureType::Intra => RGFX_VIDEO_PICTURE_I,
|
||||
PictureType::Predicted | PictureType::NonReferencePredicted => RGFX_VIDEO_PICTURE_P,
|
||||
PictureType::Bidirectional => RGFX_VIDEO_PICTURE_B,
|
||||
},
|
||||
};
|
||||
match out.get_mut(..packet.data.len()) {
|
||||
Some(to) => {
|
||||
to.copy_from_slice(&packet.data);
|
||||
state.key_next = false;
|
||||
}
|
||||
None => {
|
||||
// The frame is in the encoder's references: the next one starts afresh.
|
||||
encoded.overflow = true;
|
||||
state.key_next = true;
|
||||
}
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
/// The rows of `p` as NVENC's upload reads a plane: from its first row's first byte to its last
|
||||
/// row's last.
|
||||
fn plane(p: &SourcePlane) -> Result<&[u8], BackendError> {
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
//! An NVENC encode session's frames written by the runtime device's GPU into memory NVENC reads
|
||||
//! ([`Filler`]), as the VA-API arm's are written into its encoder's input surfaces: a buffer of
|
||||
//! the device's made exportable, its memory exported and imported on the session's CUDA GPU (the
|
||||
//! device's own, `super::super`'s module doc), which NVENC registers as input
|
||||
//! (`NvencEncoder::encode_device`).
|
||||
//!
|
||||
//! - **The input** is one buffer a session, made on its first frame: the frame's luma rows from
|
||||
//! its first byte, then its chroma rows, half as many, rounded up, at one pitch, as NVENC reads
|
||||
//! registered memory. The pitch is the source's own where its planes share one NVENC takes (a
|
||||
//! multiple of 4 that holds a row), so that each plane is one copy; else the row's bytes
|
||||
//! rounded up to 256, and each row is a copy of its own. A frame of another size, which only a
|
||||
//! new encoder takes, makes the input again. The import holds the buffer, so the memory
|
||||
//! outlives every registration of it. NVENC reads it one frame at a time: the encoder's frames
|
||||
//! come out before the next goes in (B-frames are none, `super`'s module doc).
|
||||
//! - **A frame** is copied from the source's planes, where they lie, in the surface's pages or
|
||||
//! its device caches, by a blit on a queue of the filler's own: each plane's rows of the
|
||||
//! frame's samples, as NVENC's upload copies them, so NVENC encodes the same bytes either way.
|
||||
//! The copy is waited for before NVENC maps the input, as the upload is.
|
||||
//! - **Refusals** ([`Filled::Declined`]) come before anything is submitted, and the frame is
|
||||
//! uploaded instead; an input the device or CUDA refuses to make is not tried again in the
|
||||
//! session. A copy that failed once submitted is an error: its input is kept out of
|
||||
//! use while the session lives, as the GPU may write it still.
|
||||
//!
|
||||
//! Each session logs at its end how many frames went this way, and the copies' times.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use reims_vgpu_video::core::runtime::Runtime;
|
||||
use reims_vgpu_video::nvidia::{Gpu, ImportedBuffer};
|
||||
use reims_vgpu_vulkan::core::platform::Handle as _;
|
||||
use reims_vgpu_vulkan::core::platform::Platform;
|
||||
use reims_vgpu_vulkan::core::platform::blit::{BlitCmd, BlitEncoder as _};
|
||||
use reims_vgpu_vulkan::core::platform::command::{CommandBuffer as _, CommandQueue as _};
|
||||
use reims_vgpu_vulkan::core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_vulkan::core::platform::resource::Buffer as _;
|
||||
use reims_vgpu_vulkan::core::platform::types::CommandBufferStatus;
|
||||
use reims_vgpu_vulkan::core::raise::OnFault;
|
||||
|
||||
use super::super::super::video_host::{BackendError, OutputPlane};
|
||||
use super::super::{ENCODE_NAME, STORAGE_PRIVATE};
|
||||
|
||||
/// The alignment of the input's rows where the source's pitch is not taken: 256 bytes.
|
||||
const PITCH_ALIGNMENT: u64 = 256;
|
||||
|
||||
/// What came of a frame's fill.
|
||||
pub(super) enum Filled {
|
||||
/// The frame lies in `input` at `pitch`, written and waited for.
|
||||
Written {
|
||||
input: Arc<ImportedBuffer>,
|
||||
pitch: u32,
|
||||
},
|
||||
/// Nothing was written, for the reason given: the frame is uploaded.
|
||||
Declined(String),
|
||||
}
|
||||
|
||||
/// One session's input, made as its first frame was filled.
|
||||
struct Input<P: Platform> {
|
||||
buffer: P::Buffer,
|
||||
/// Its import on the session's GPU, which holds the buffer.
|
||||
import: Arc<ImportedBuffer>,
|
||||
pitch: u64,
|
||||
/// The bytes of a row, and the luma rows, of the frames it was made for.
|
||||
row_bytes: u64,
|
||||
rows: u64,
|
||||
}
|
||||
|
||||
/// An encode session's fills of its frames into memory NVENC reads (module doc).
|
||||
pub(in super::super) struct Filler<P: Platform> {
|
||||
device: P::Device,
|
||||
gpu: Arc<Gpu>,
|
||||
queue: Option<P::CommandQueue>,
|
||||
input: Option<Input<P>>,
|
||||
/// Why no input is made, once a make was refused: the session's later frames are declined
|
||||
/// with it, and no make is tried again.
|
||||
refused: Option<String>,
|
||||
/// Inputs whose copy failed on the GPU, which may write them still.
|
||||
failed: Vec<Input<P>>,
|
||||
/// Frames filled, and the time of their copies from submission to their wait's end.
|
||||
filled: u64,
|
||||
/// The clock the copies are timed on: the video's runtime's.
|
||||
runtime: Arc<dyn Runtime>,
|
||||
total: Duration,
|
||||
longest: Duration,
|
||||
}
|
||||
|
||||
impl<P: Platform> Filler<P> {
|
||||
/// A filler of `device`'s, whose memory `gpu`, the device's own GPU, imports, its copies timed
|
||||
/// on `runtime`'s clock.
|
||||
pub(in super::super) fn new(
|
||||
device: &P::Device,
|
||||
gpu: &Arc<Gpu>,
|
||||
runtime: &Arc<dyn Runtime>,
|
||||
) -> Self {
|
||||
Self {
|
||||
device: device.clone_ref(),
|
||||
gpu: Arc::clone(gpu),
|
||||
queue: None,
|
||||
input: None,
|
||||
refused: None,
|
||||
failed: Vec::new(),
|
||||
filled: 0,
|
||||
runtime: Arc::clone(runtime),
|
||||
total: Duration::ZERO,
|
||||
longest: Duration::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
/// Frames filled so far.
|
||||
#[cfg(test)]
|
||||
pub(super) fn filled(&self) -> u64 {
|
||||
self.filled
|
||||
}
|
||||
|
||||
/// Writes the frame of `size`, of samples of `sample` bytes, in `luma` and `chroma` where
|
||||
/// they lie, into the session's input (module doc), and returns once the GPU wrote it.
|
||||
/// `Err` where the copy failed once submitted: the input is kept out of use, and the caller
|
||||
/// fills no more frames of the session.
|
||||
pub(super) fn fill(
|
||||
&mut self,
|
||||
luma: &OutputPlane<P>,
|
||||
chroma: &OutputPlane<P>,
|
||||
size: (u32, u32),
|
||||
sample: u32,
|
||||
) -> Result<Filled, BackendError> {
|
||||
let (width, height) = (u64::from(size.0), u64::from(size.1));
|
||||
let row_bytes = width * u64::from(sample);
|
||||
let chroma_rows = height.div_ceil(2);
|
||||
if row_bytes == 0 || height == 0 {
|
||||
return Ok(Filled::Declined("an empty frame".to_owned()));
|
||||
}
|
||||
for (plane, rows, which) in [(luma, height, "luma"), (chroma, chroma_rows, "chroma")] {
|
||||
if plane.row_bytes < row_bytes || plane.height < rows {
|
||||
return Ok(Filled::Declined(format!(
|
||||
"a {which} plane of {} rows of {} bytes for a frame of {rows} of {row_bytes}",
|
||||
plane.height, plane.row_bytes
|
||||
)));
|
||||
}
|
||||
}
|
||||
let input = match self.input_for(luma, chroma, row_bytes, height) {
|
||||
Ok(input) => input,
|
||||
Err(why) => return Ok(Filled::Declined(why)),
|
||||
};
|
||||
let (pitch, import) = (input.pitch, Arc::clone(&input.import));
|
||||
let Ok(pitch_u32) = u32::try_from(pitch) else {
|
||||
return Ok(Filled::Declined(format!("a pitch of {pitch}")));
|
||||
};
|
||||
let destination = input.buffer.clone_ref();
|
||||
let copies = [(luma, 0, height), (chroma, pitch * height, chroma_rows)];
|
||||
let start = self.runtime.now();
|
||||
match self.copy(&destination, &copies, pitch, row_bytes)? {
|
||||
Some(why) => return Ok(Filled::Declined(why)),
|
||||
None => {
|
||||
let took = self.runtime.elapsed_since(start);
|
||||
self.filled += 1;
|
||||
self.total += took;
|
||||
self.longest = self.longest.max(took);
|
||||
}
|
||||
}
|
||||
Ok(Filled::Written {
|
||||
input: import,
|
||||
pitch: pitch_u32,
|
||||
})
|
||||
}
|
||||
|
||||
/// The session's input for frames of `rows` rows of `row_bytes` from `luma` and `chroma`: the
|
||||
/// one made, where it holds them, else a new one (module doc). `Err` says why none is made.
|
||||
fn input_for(
|
||||
&mut self,
|
||||
luma: &OutputPlane<P>,
|
||||
chroma: &OutputPlane<P>,
|
||||
row_bytes: u64,
|
||||
rows: u64,
|
||||
) -> Result<&Input<P>, String> {
|
||||
if let Some(why) = &self.refused {
|
||||
return Err(why.clone());
|
||||
}
|
||||
let kept = self
|
||||
.input
|
||||
.take()
|
||||
.filter(|i| i.row_bytes == row_bytes && i.rows == rows);
|
||||
let input = match kept {
|
||||
Some(input) => input,
|
||||
None => match self.make_input(luma, chroma, row_bytes, rows) {
|
||||
Ok(input) => input,
|
||||
Err(why) => return Err(self.refused.insert(why).clone()),
|
||||
},
|
||||
};
|
||||
Ok(self.input.insert(input))
|
||||
}
|
||||
|
||||
/// A new input for frames of `rows` rows of `row_bytes`, at `luma`'s and `chroma`'s pitch
|
||||
/// where NVENC takes it.
|
||||
fn make_input(
|
||||
&self,
|
||||
luma: &OutputPlane<P>,
|
||||
chroma: &OutputPlane<P>,
|
||||
row_bytes: u64,
|
||||
rows: u64,
|
||||
) -> Result<Input<P>, String> {
|
||||
let source = luma.bytes_per_row;
|
||||
let pitch = if source == chroma.bytes_per_row && source % 4 == 0 && source >= row_bytes {
|
||||
source
|
||||
} else {
|
||||
row_bytes.next_multiple_of(PITCH_ALIGNMENT)
|
||||
};
|
||||
let length = (rows + rows.div_ceil(2))
|
||||
.checked_mul(pitch)
|
||||
.ok_or_else(|| format!("an input of {rows} rows at {pitch}"))?;
|
||||
let made = (self.device).new_exportable_buffer_of_length(
|
||||
OnFault::Return,
|
||||
length,
|
||||
STORAGE_PRIVATE,
|
||||
None,
|
||||
);
|
||||
let buffer = match made {
|
||||
Ok(Some(buffer)) => buffer,
|
||||
Ok(None) => return Err("the device makes no exportable buffer".to_owned()),
|
||||
Err(raise) => return Err(format!("an exportable buffer's make: {raise}")),
|
||||
};
|
||||
let exported = buffer.export_memory()?;
|
||||
let import = ImportedBuffer::import(
|
||||
&self.gpu,
|
||||
exported.fd,
|
||||
exported.allocation_size,
|
||||
exported.offset,
|
||||
exported.length,
|
||||
exported.dedicated,
|
||||
)
|
||||
.map_err(|error| format!("CUDA's import of an exportable buffer: {error}"))?;
|
||||
let import = Arc::new(import.holding(Box::new(buffer.clone_ref())));
|
||||
Ok(Input {
|
||||
buffer,
|
||||
import,
|
||||
pitch,
|
||||
row_bytes,
|
||||
rows,
|
||||
})
|
||||
}
|
||||
|
||||
/// Copies each of `copies`, a plane, the input's byte its first row goes to and its rows, into
|
||||
/// `destination`, rows `pitch` apart, `row_bytes` of each, on the filler's queue, and waits
|
||||
/// for the copy. `Some` says why nothing was submitted; `Err` is a copy that failed once
|
||||
/// submitted, whose input is kept out of use.
|
||||
fn copy(
|
||||
&mut self,
|
||||
destination: &P::Buffer,
|
||||
copies: &[(&OutputPlane<P>, u64, u64); 2],
|
||||
pitch: u64,
|
||||
row_bytes: u64,
|
||||
) -> Result<Option<String>, BackendError> {
|
||||
if self.queue.is_none() {
|
||||
let Some(queue) = self.device.new_command_queue() else {
|
||||
return Ok(Some("no command queue".to_owned()));
|
||||
};
|
||||
queue.set_label("reims-vgpu.graphics-video-fill");
|
||||
self.queue = Some(queue);
|
||||
}
|
||||
let Some(queue) = self.queue.as_ref() else {
|
||||
return Ok(Some("no command queue".to_owned()));
|
||||
};
|
||||
let cb = match queue.command_buffer(OnFault::Return) {
|
||||
Ok(Some(cb)) => cb,
|
||||
Ok(None) => return Ok(Some("no command buffer".to_owned())),
|
||||
Err(raise) => return Ok(Some(format!("its command buffer: {raise}"))),
|
||||
};
|
||||
let blit = match cb.blit_encoder(OnFault::Return) {
|
||||
Ok(Some(blit)) => blit,
|
||||
Ok(None) => return Ok(Some("no blit encoder".to_owned())),
|
||||
Err(raise) => return Ok(Some(format!("its blit encoder: {raise}"))),
|
||||
};
|
||||
for &(plane, at, rows) in copies {
|
||||
for (from, to, size) in row_copies(plane, at, rows, pitch, row_bytes) {
|
||||
let copy = BlitCmd::CopyBufferToBuffer {
|
||||
source_buffer: Some(&plane.buffer),
|
||||
source_offset: from,
|
||||
destination_buffer: Some(destination),
|
||||
destination_offset: to,
|
||||
size,
|
||||
};
|
||||
if let Err(raise) = blit.encode(OnFault::Return, copy) {
|
||||
return Ok(Some(format!("a copy: {raise}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(raise) = blit.encode(OnFault::Return, BlitCmd::EndEncoding) {
|
||||
return Ok(Some(format!("its end: {raise}")));
|
||||
}
|
||||
if let Err(raise) = cb.commit(OnFault::Return) {
|
||||
return Ok(Some(format!("its commit: {raise}")));
|
||||
}
|
||||
let failed = match cb.wait_until_completed(OnFault::Return) {
|
||||
Err(raise) => Some(format!("its wait: {raise}")),
|
||||
Ok(()) if cb.status() != CommandBufferStatus::COMPLETED => {
|
||||
let error = cb.error().map(|e| format!("{e:?}")).unwrap_or_default();
|
||||
Some(format!("the copy failed {error}"))
|
||||
}
|
||||
Ok(()) => None,
|
||||
};
|
||||
if let Some(failed) = failed {
|
||||
self.failed.extend(self.input.take());
|
||||
return Err(format!("the GPU's copy of a frame into NVENC's input: {failed}").into());
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// The copies of `rows` rows of `row_bytes` from `plane` into an input whose rows are `pitch`
|
||||
/// apart from its byte `at`, each (source offset, input offset, size): one where the plane's
|
||||
/// rows are `pitch` apart too, from its first row's first byte to its last row's last, else one a
|
||||
/// row.
|
||||
fn row_copies<P: Platform>(
|
||||
plane: &OutputPlane<P>,
|
||||
at: u64,
|
||||
rows: u64,
|
||||
pitch: u64,
|
||||
row_bytes: u64,
|
||||
) -> Vec<(u64, u64, u64)> {
|
||||
if plane.bytes_per_row == pitch {
|
||||
return vec![(plane.offset, at, pitch * (rows - 1) + row_bytes)];
|
||||
}
|
||||
(0..rows)
|
||||
.map(|row| {
|
||||
(
|
||||
plane.offset + row * plane.bytes_per_row,
|
||||
at + row * pitch,
|
||||
row_bytes,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl<P: Platform> Drop for Filler<P> {
|
||||
fn drop(&mut self) {
|
||||
if self.filled == 0 {
|
||||
return;
|
||||
}
|
||||
let ms = |d: Duration| d.as_secs_f64() * 1e3;
|
||||
let mean = self.total / u32::try_from(self.filled).unwrap_or(u32::MAX);
|
||||
log::info!(
|
||||
"hardware video: {ENCODE_NAME}: an encode session's frames copied by the GPU into \
|
||||
NVENC's input: {}, {:.3} ms each from submission to the wait's end, {:.3} ms at most",
|
||||
self.filled,
|
||||
ms(mean),
|
||||
ms(self.longest)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use reims_vgpu_vulkan::core::testkit::FakePlatform;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A plane of `bytes_per_row` at `offset`, of rows of 100 bytes, in a buffer of the fake's.
|
||||
fn plane(p: &FakePlatform, offset: u64, bytes_per_row: u64) -> OutputPlane<FakePlatform> {
|
||||
let buffer = (p.device().new_buffer_of_length(OnFault::Return, 1 << 16, 0))
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_else(|| unreachable!("the fake makes buffers"));
|
||||
OutputPlane {
|
||||
buffer,
|
||||
offset,
|
||||
bytes_per_row,
|
||||
row_bytes: 100,
|
||||
width: 100,
|
||||
height: 4,
|
||||
rows_held: 4,
|
||||
cached: false,
|
||||
host: None,
|
||||
pages: None,
|
||||
cache: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A plane at the input's pitch is one copy, from its first row to its last row's last byte;
|
||||
/// one at another pitch is a copy a row, of the row's bytes alone.
|
||||
#[test]
|
||||
fn a_plane_at_the_inputs_pitch_is_one_copy_else_one_a_row() {
|
||||
let p = FakePlatform::new();
|
||||
let same = plane(&p, 32, 128);
|
||||
assert_eq!(row_copies(&same, 0, 4, 128, 100), [(32, 0, 3 * 128 + 100)]);
|
||||
let other = plane(&p, 32, 192);
|
||||
assert_eq!(
|
||||
row_copies(&other, 512, 3, 128, 100),
|
||||
[(32, 512, 100), (224, 640, 100), (416, 768, 100)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -320,15 +320,27 @@ fn write_frame(
|
||||
pitch: usize,
|
||||
chroma_at: usize,
|
||||
n: usize,
|
||||
) {
|
||||
write_planes::<FakePlatform>(source, settings, [(0, pitch), (chroma_at, pitch)], n);
|
||||
}
|
||||
|
||||
/// Writes frame `n` of `settings`' size into `source`, a Shared buffer, its luma and its chroma
|
||||
/// each at its (first byte, bytes from one row to the next) in `planes`, at its format's bytes
|
||||
/// a sample (P010's high bits).
|
||||
fn write_planes<P: Platform>(
|
||||
source: &P::Buffer,
|
||||
settings: &RgfxVideoEncodeSettings,
|
||||
planes: [(usize, usize); 2],
|
||||
n: usize,
|
||||
) {
|
||||
let (w, h) = (settings.width as usize, settings.height as usize);
|
||||
let wide = settings.format == RGFX_VIDEO_FORMAT_P010;
|
||||
// SAFETY: the fake's Shared buffer holds the luma's and chroma's rows at `pitch` (the
|
||||
// SAFETY: the Shared buffer holds the luma's and chroma's rows at their pitches (the
|
||||
// caller's sizes), and nothing reads it until the encode that follows.
|
||||
let bytes = unsafe {
|
||||
std::slice::from_raw_parts_mut(source.contents().as_ptr::<u8>(), source.length() as usize)
|
||||
};
|
||||
for (plane, at, rows) in [(0, 0, h), (1, chroma_at, h / 2)] {
|
||||
for (plane, (at, pitch), rows) in [(0, planes[0], h), (1, planes[1], h / 2)] {
|
||||
for y in 0..rows {
|
||||
let row = &mut bytes[at + y * pitch..];
|
||||
for x in 0..w {
|
||||
@@ -405,7 +417,14 @@ fn each_profile_encodes_through_a_session_and_decodes_back_on_nvdec() {
|
||||
if bit == RGFX_VIDEO_H264_HIGH && entry.codec == RGFX_VIDEO_CODEC_H264 {
|
||||
s.level = 40;
|
||||
}
|
||||
let encoder = NvencHostEncoder::new(&gpu, entry.codec, &supports, entry, &caps);
|
||||
let encoder = NvencHostEncoder::<FakePlatform>::new(
|
||||
&gpu,
|
||||
entry.codec,
|
||||
&supports,
|
||||
entry,
|
||||
&caps,
|
||||
Err("the fake's buffers export nothing".to_owned()),
|
||||
);
|
||||
for refused in [
|
||||
RgfxVideoEncodeSettings { b_frames: 1, ..s },
|
||||
RgfxVideoEncodeSettings {
|
||||
@@ -564,3 +583,190 @@ fn each_profile_encodes_through_a_session_and_decodes_back_on_nvdec() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A layout of a frame's source in [`each_frame_filled_by_the_gpu_encodes_as_uploaded`]: where
|
||||
/// its planes lie and their pitches.
|
||||
struct Layout {
|
||||
what: &'static str,
|
||||
/// In a device cache (a Private buffer, written by a copy from a Shared one) rather than in
|
||||
/// pages.
|
||||
cached: bool,
|
||||
/// Each plane's (first byte, bytes from one row to the next).
|
||||
planes: [(usize, usize); 2],
|
||||
}
|
||||
|
||||
/// On the NVIDIA host, an encode session whose frames the runtime device's GPU copies into
|
||||
/// memory NVENC reads (`fill`'s module doc) writes the same access units, byte for byte, as one
|
||||
/// whose frames NVENC's input buffer takes by the CPU's copy: H.264 High and HEVC Main at
|
||||
/// 1920x1080, 12 frames of a moving picture at a constant QP with a forced IDR picture (frame
|
||||
/// 6), from a source in pages whose planes share a pitch NVENC takes (a copy a plane), and from
|
||||
/// one in a device cache whose planes do not (a copy a row). Every frame went the GPU's way.
|
||||
#[test]
|
||||
#[ignore = "needs an NVIDIA GPU: run on the NVIDIA host"]
|
||||
fn each_frame_filled_by_the_gpu_encodes_as_uploaded() {
|
||||
use reims_vgpu_vulkan::VulkanPlatform;
|
||||
use reims_vgpu_vulkan::core::platform::blit::{BlitCmd, BlitEncoder as _};
|
||||
use reims_vgpu_vulkan::core::platform::command::{CommandBuffer as _, CommandQueue as _};
|
||||
use reims_vgpu_vulkan::core::platform::types::CommandBufferStatus;
|
||||
|
||||
let platform = Arc::new(VulkanPlatform::new());
|
||||
crate::entry::run(|_| {
|
||||
let device = VulkanPlatform::system_default_device().expect("a Vulkan device");
|
||||
let runtime = crate::video::runtime::PlatformRuntime::of(&platform);
|
||||
let video = super::super::NvidiaVideo::new(&device, &runtime).expect("NVENC on the GPU");
|
||||
assert!(video.imports.is_some(), "CUDA imports no exportable buffer");
|
||||
let queue = device.new_command_queue().expect("a command queue");
|
||||
let (width, height) = (1920u32, 1080u32);
|
||||
let layouts = [
|
||||
Layout {
|
||||
what: "pages at one pitch",
|
||||
cached: false,
|
||||
planes: [(0x20, 2048), (0x20 + 2048 * 1080, 2048)],
|
||||
},
|
||||
Layout {
|
||||
what: "a device cache at two pitches",
|
||||
cached: true,
|
||||
planes: [(0, 1984), (1984 * 1080, 2112)],
|
||||
},
|
||||
];
|
||||
for (codec, profile) in [
|
||||
(RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_H264_HIGH),
|
||||
(RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_HEVC_MAIN),
|
||||
] {
|
||||
let entry = (video.encode.iter())
|
||||
.find(|e| e.codec == codec)
|
||||
.expect("an encode entry");
|
||||
let caps = encode_caps(entry, &video.encoders);
|
||||
let s = settings(codec, profile, width, height);
|
||||
for layout in &layouts {
|
||||
let what = format!("codec {codec} profile {profile:#x}, {}", layout.what);
|
||||
let [_, (chroma_at, chroma_pitch)] = layout.planes;
|
||||
let len = (chroma_at + chroma_pitch * height as usize / 2) as u64;
|
||||
let buffer = |len, options| {
|
||||
(device.new_buffer_of_length(OnFault::Return, len, options))
|
||||
.expect("no raise")
|
||||
.expect("a buffer")
|
||||
};
|
||||
let staging = buffer(len, SHARED);
|
||||
let cache = buffer(len, super::super::STORAGE_PRIVATE);
|
||||
let source = if layout.cached { &cache } else { &staging };
|
||||
let (bitstream, result) = (buffer(4 << 20, SHARED), buffer(64, SHARED));
|
||||
let plane = |(offset, pitch): (usize, usize), rows| VideoPlane {
|
||||
buffer: source,
|
||||
offset: offset as u64,
|
||||
bytes_per_row: pitch as u64,
|
||||
row_bytes: u64::from(width),
|
||||
width: u64::from(width),
|
||||
height: rows,
|
||||
cached: layout.cached,
|
||||
pages: None,
|
||||
cache: None,
|
||||
};
|
||||
let mut streams = Vec::new();
|
||||
for filled in [false, true] {
|
||||
let filler = if filled {
|
||||
Ok(Filler::new(&device, &video.gpu, &video.runtime))
|
||||
} else {
|
||||
Err("uploaded by the test".to_owned())
|
||||
};
|
||||
let encoder = NvencHostEncoder::<VulkanPlatform>::new(
|
||||
&video.gpu,
|
||||
codec,
|
||||
&video.encoders,
|
||||
entry,
|
||||
&caps,
|
||||
filler,
|
||||
);
|
||||
let fills = Arc::clone(&encoder.fills);
|
||||
let session =
|
||||
HostEncodeSession::new(&device, codec, "NVENC", Box::new(encoder))
|
||||
.expect("a session");
|
||||
let event = match session.event() {
|
||||
EventRef::Shared(event) => event,
|
||||
EventRef::Event(_) => panic!("a plain event"),
|
||||
};
|
||||
let mut units = Vec::new();
|
||||
for n in 0..12u64 {
|
||||
write_planes::<VulkanPlatform>(&staging, &s, layout.planes, n as usize);
|
||||
if layout.cached {
|
||||
let cb = (queue.command_buffer(OnFault::Return))
|
||||
.expect("no raise")
|
||||
.expect("a command buffer");
|
||||
let blit = (cb.blit_encoder(OnFault::Return))
|
||||
.expect("no raise")
|
||||
.expect("a blit encoder");
|
||||
let copy = BlitCmd::CopyBufferToBuffer {
|
||||
source_buffer: Some(&staging),
|
||||
source_offset: 0,
|
||||
destination_buffer: Some(&cache),
|
||||
destination_offset: 0,
|
||||
size: len,
|
||||
};
|
||||
blit.encode(OnFault::Return, copy).expect("the copy");
|
||||
(blit.encode(OnFault::Return, BlitCmd::EndEncoding)).expect("its end");
|
||||
cb.commit(OnFault::Return).expect("its commit");
|
||||
(cb.wait_until_completed(OnFault::Return)).expect("its wait");
|
||||
assert_eq!(cb.status(), CommandBufferStatus::COMPLETED);
|
||||
}
|
||||
let encode = VideoEncode {
|
||||
luma: plane(layout.planes[0], u64::from(height)),
|
||||
chroma: plane(layout.planes[1], u64::from(height / 2)),
|
||||
bitstream: &bitstream,
|
||||
bitstream_offset: 0,
|
||||
bitstream_capacity: 4 << 20,
|
||||
result: &result,
|
||||
result_offset: 0,
|
||||
frame_index: n,
|
||||
force_keyframe: n == 6,
|
||||
settings: (n == 0).then_some(s),
|
||||
};
|
||||
let value = session
|
||||
.encode(&encode)
|
||||
.expect("an encode the session takes");
|
||||
assert!(
|
||||
event.wait_until_signaled_value(value, 10_000),
|
||||
"{what} frame {n}"
|
||||
);
|
||||
// SAFETY: the Shared buffers hold their bytes, which the session wrote
|
||||
// before its signal and writes no more until the next encode.
|
||||
let (result_bytes, au) = unsafe {
|
||||
(
|
||||
std::slice::from_raw_parts(result.contents().as_ptr::<u8>(), 32),
|
||||
std::slice::from_raw_parts(
|
||||
bitstream.contents().as_ptr::<u8>(),
|
||||
4 << 20,
|
||||
),
|
||||
)
|
||||
};
|
||||
let r =
|
||||
RgfxVideoEncodeResult::read_from_bytes(result_bytes).expect("a result");
|
||||
assert_eq!(r.status, RGFX_VIDEO_ENCODE_OK, "{what} frame {n}: {r:?}");
|
||||
units.push(au[..r.bitstream_size as usize].to_vec());
|
||||
}
|
||||
drop(session);
|
||||
let fills = fills.lock();
|
||||
let count = fills.filler.as_ref().map(Filler::filled);
|
||||
if filled {
|
||||
assert_eq!(count, Ok(12), "{what}: frames the GPU filled");
|
||||
}
|
||||
streams.push(units);
|
||||
}
|
||||
let [uploaded, filled] = [&streams[0], &streams[1]];
|
||||
for (n, (up, gpu)) in uploaded.iter().zip(filled).enumerate() {
|
||||
let first = up.iter().zip(gpu.iter()).position(|(a, b)| a != b);
|
||||
assert!(
|
||||
up == gpu,
|
||||
"{what} frame {n}: {} bytes uploaded, {} filled, first differing at {first:?}",
|
||||
up.len(),
|
||||
gpu.len()
|
||||
);
|
||||
}
|
||||
eprintln!(
|
||||
"{what}: {} access units equal, {} bytes",
|
||||
filled.len(),
|
||||
filled.iter().map(Vec::len).sum::<usize>()
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -158,9 +158,13 @@ buffer of an encode session's process (reims-vgpu's `graphics/video_host/encode.
|
||||
a change of the bitrates, QPs or frame rate goes to the encoder from the next frame.
|
||||
`min_qp`, `max_qp` and a change of `quality` alone are not taken.
|
||||
- **The frame is encoded** on the session's encode thread (`reims-vgpu.graphics-video-encode`),
|
||||
in the order the encodes were taken, once the command buffer's waits are done: its two planes
|
||||
are read as host bytes, in the surface's pages, or, for a plane in a device cache, in a staging
|
||||
buffer the GPU copies it into first.
|
||||
in the order the encodes were taken, once the command buffer's waits are done. The runtime
|
||||
device's GPU copies its two planes, where they lie, in the surface's pages or its device
|
||||
caches, into the encoder's own input: a VA-API input surface exported as dma-bufs, or an
|
||||
exportable buffer CUDA imported, which NVENC registers and maps for the frame. Where the arm
|
||||
declines that copy (said once a session), the planes are read as host bytes, in the surface's
|
||||
pages, or, for a plane in a device cache, in a staging buffer the GPU copies it into first, and
|
||||
the encoder's upload copies them. The encoder codes the same bytes either way.
|
||||
- **The access unit is written** in Annex-B form into the bitstream buffer, a keyframe's with
|
||||
its parameter sets first, and the frame's `RgfxVideoEncodeResult` after it. One past the
|
||||
capacity is not written (`RGFX_VIDEO_ENCODE_OVERFLOW`, with the bytes it needed), and the
|
||||
|
||||
@@ -239,7 +239,13 @@ synchronous mode, the only one on Linux: raw 4:2:0 frames in, NV12 or P010,
|
||||
H.264 or HEVC access units out, in decode order.
|
||||
|
||||
- **Pictures in and out.** Each frame is copied into an NVENC input buffer
|
||||
and encoded with `frameIdx` counting from 0 in submission order;
|
||||
(`encode`), or read where another API's GPU wrote it, in memory CUDA
|
||||
imported (`encode_device`, a `DeviceFrame`): registered with the session
|
||||
at its pitch on its first frame (`nvEncRegisterResource`, a CUDA device
|
||||
pointer), mapped for each frame (`nvEncMapInputResource`) and unmapped
|
||||
once its output is locked, and unregistered as the session goes, before
|
||||
the import, which holds the exporter's buffer (`ImportedBuffer::holding`).
|
||||
Each is encoded with `frameIdx` counting from 0 in submission order;
|
||||
`NV_ENC_ERR_NEED_MORE_INPUT` means nothing yet, and after a success the
|
||||
pending output buffers are locked in submission order, each its picture
|
||||
in coding order. A flush sends a picture with the end-of-stream flag
|
||||
|
||||
Reference in new issue
Block a user