From 80eea13d5d7436096e3108ff7c236243797de79d Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Fri, 27 Nov 2026 15:54:44 -0800 Subject: [PATCH] :new: Code an encode frame in place of the last one on the host A guest that drops a frame's access unit and has the same frame coded again had no way to say so: each encode was a new frame of the stream, coded after the dropped one and predicting from it. macOS's HEVC encoder plug-in does that over its data rate limit, at a higher QP, and the stream broke: gaps in its order counts and VideoToolbox decode errors -17694 on 151 and 166 of 300 frames (macOS 26.7.2 guest, RX 7900 XTX host, m3-max-77530). What the guest and host observe now: - the wire: an encode op's flag RGFX_VIDEO_ENCODE_IN_PLACE codes the frame in place of the session's last one, from the references the last one was coded from, with its order count and frame_index, at the QP the settings give now; the caps' RgfxVideoEncodeCaps::flags gains RGFX_VIDEO_ENCODE_CAP_IN_PLACE where the host does so (zero from an older host); - VA-API: every encode entry has the flag. The VA crate's encoder holds its last picture back from the accelerator's stream (Accelerator::keep) until the next frame or a flush, and codes a frame in place again into the same reconstructed surface (Encoder::encode_in_place); a stream without B pictures or our hard limit, which is every one the x86-64 guest makes; - NVENC: the flag where NVENC answers NV_ENC_CAPS_DISABLE_ENC_STATE_ADVANCE for every profile of the codec and a session of it with a state buffer codes a frame, the frame again in place and a frame after it at the device's start (checked_in_place); a driver that refuses either leaves it off. Such a session codes each frame without advancing NVENC's state and takes the state after it (nvEncRestoreEncoderState) as the next frame comes (NvencEncoder::new_in_place); - a frame that cannot be coded in place fails (RGFX_VIDEO_ENCODE_FAILED): with no frame to replace, with B pictures, with the VA crate's hard limit, of another frame_index, or asking a keyframe in place of a frame that is not one. No later frame predicts from the dropped one: on VA-API the next is an IDR picture, on NVENC it is coded from the state before the dropped one. A frame without the flag is coded as before; the VA crate keeps its last picture one frame later, which nothing outside it observes. No guest sends the flag yet: the x86-64 guest's HEVC route, next, does. Tests: the codec encoder's frames in place (the stream is the one without the retry but for its QP; twice in a row; after and of an IDR picture; each refusal, after which the next frame is an IDR picture), the session handing the flag to its backend, each arm's caps flag, and on the hardware, frames in place decoding back on the driver's own decoder (RX 7900 XTX, radeonsi, m3-max-77595) and on NVDEC above 35 dB (RTX 2080, m3-max-77597; RTX 3090, m3-max-77618), and the device-start check leaving no NVENC session on its GPU, which runs alone (.config/nextest.toml): it adds a median of 61.9 ms on the RTX 2080 and 56.9 ms on the RTX 3090, five checks each. --- .config/nextest.toml | 10 +- .../include/reims_graphics_wire.h | 24 +- crates/reims-vgpu-graphics/src/ops/video.rs | 15 +- crates/reims-vgpu-graphics/src/wire.rs | 8 +- .../src/codec/encode/encoder.rs | 472 +++++++++++++++++- crates/reims-vgpu-video/src/nvidia.rs | 2 +- crates/reims-vgpu-video/src/nvidia/layout.rs | 18 + crates/reims-vgpu-video/src/nvidia/nvenc.rs | 29 +- .../src/nvidia/nvenc/encoder.rs | 297 ++++++++++- .../reims-vgpu-video/src/nvidia/nvenc/ffi.rs | 26 +- .../reims-vgpu-video/src/vaapi/va/encoder.rs | 48 +- .../reims-vgpu/src/graphics/decode/video.rs | 9 +- crates/reims-vgpu/src/graphics/nvidia.rs | 2 +- .../reims-vgpu/src/graphics/nvidia/encode.rs | 140 +++++- .../src/graphics/nvidia/encode/guest.rs | 7 +- .../src/graphics/nvidia/encode/guest/tests.rs | 1 + .../src/graphics/nvidia/encode/tests.rs | 314 +++++++++++- .../reims-vgpu/src/graphics/vaapi/encode.rs | 96 +++- .../src/graphics/vaapi/encode/tests.rs | 186 ++++++- .../src/graphics/video_host/encode.rs | 5 + .../src/graphics/video_host/encode/tests.rs | 24 +- 21 files changed, 1639 insertions(+), 94 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index 14cb31b55..030527e6a 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -22,7 +22,9 @@ threads-required = "num-test-threads" # `graphics::nvidia::`, `video_host::` and `surface_cache::`, which take surface_cache's download # costs, failed 3 of 4 runs, and `graphics::nvidia::` beside the download costs alone 1 of 4, each # failure an NVDEC decode whose status was 8 (cuvidDecodeStatus_Error); the same filters without -# the download costs failed none of 8 (m3-max-53602, m3-max-53622, 2026-11-19). +# the download costs failed none of 8 (m3-max-53602, m3-max-53622, 2026-11-19). The NVENC +# in-place check's test counts its GPU's encoder sessions, which the tests beside it hold too: +# run with the NVIDIA tests, it counted 3 (m3-max-77594, 2026-11-27). [[profile.default.overrides]] filter = ''' (binary_id(reims-vgpu) & ( @@ -34,7 +36,8 @@ filter = ''' | test(=graphics::decode::close_cost::on_vulkan_close_cost) | test(=graphics::decode::composite_cost::on_rt_composite_cost) | test(=graphics::decode::dispatch_cost::on_rt_dispatch_cost) - | test(=graphics::decode::draw_cost::on_rt_draw_cost))) + | test(=graphics::decode::draw_cost::on_rt_draw_cost) + | test(=graphics::nvidia::encode::tests::the_in_place_check_leaves_no_nvenc_session))) ''' threads-required = "num-test-threads" @@ -68,7 +71,8 @@ filter = ''' | test(=graphics::decode::close_cost::on_vulkan_close_cost) | test(=graphics::decode::composite_cost::on_rt_composite_cost) | test(=graphics::decode::dispatch_cost::on_rt_dispatch_cost) - | test(=graphics::decode::draw_cost::on_rt_draw_cost))) + | test(=graphics::decode::draw_cost::on_rt_draw_cost) + | test(=graphics::nvidia::encode::tests::the_in_place_check_leaves_no_nvenc_session))) ''' test-group = "@global" diff --git a/crates/reims-vgpu-graphics/include/reims_graphics_wire.h b/crates/reims-vgpu-graphics/include/reims_graphics_wire.h index a709243e2..de9987f78 100644 --- a/crates/reims-vgpu-graphics/include/reims_graphics_wire.h +++ b/crates/reims-vgpu-graphics/include/reims_graphics_wire.h @@ -1002,6 +1002,20 @@ // [`RgfxVideoOpEncode::flags`]: the frame is a keyframe (an IDR picture, or HEVC's IRAP). #define RGFX_VIDEO_ENCODE_FORCE_KEYFRAME (1 << 0) +// [`RgfxVideoOpEncode::flags`]: the frame is coded in place of the session's last one, which the +// guest drops: from the references the last one was coded from, at the same place in the +// stream, so that the stream holds this frame where the last one was and no picture predicts +// from the dropped one. Its `frame_index` is the last one's. Taken from a host whose +// [`RgfxVideoEncodeCaps::flags`](crate::wire::RgfxVideoEncodeCaps) has +// [`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`](crate::wire::RGFX_VIDEO_ENCODE_CAP_IN_PLACE) for the +// codec. Where the host cannot, the encode fails ([`RGFX_VIDEO_ENCODE_FAILED`]), writes +// nothing, and no later frame predicts from the dropped one: the session holds no last frame +// to replace (none was coded since its settings made a new stream, or the last one failed), +// codes B pictures, or holds a hard limit ([`RGFX_VIDEO_ENCODE_HARD_LIMIT`]) by coding frames +// again itself; the `frame_index` is not the last one's; or the frame asks a keyframe in place +// of one that is not. +#define RGFX_VIDEO_ENCODE_IN_PLACE (1 << 1) + // [`RgfxVideoEncodeSettings::rate_control`]: a constant QP a picture type (`qp_i`, `qp_p`, // `qp_b`). #define RGFX_VIDEO_RATE_CQP 1 @@ -3427,6 +3441,11 @@ // where it landed. Without it, a picture lands in the surface's pages. #define RGFX_VIDEO_CAPS_OUTPUT_CACHED (1 << 0) +// [`RgfxVideoEncodeCaps::flags`]: the host codes a frame in place of a session's last one +// ([`RGFX_VIDEO_ENCODE_IN_PLACE`](crate::ops::video::RGFX_VIDEO_ENCODE_IN_PLACE)), a session of +// no B pictures. +#define RGFX_VIDEO_ENCODE_CAP_IN_PLACE (1 << 0) + // A pipeline reflection reply's status: the pipeline was created. #define RGFX_PIPELINE_OK 0 @@ -8603,7 +8622,8 @@ typedef struct { // The most consecutive B pictures an encode takes // ([`RgfxVideoEncodeSettings::b_frames`](crate::ops::video::RgfxVideoEncodeSettings)). uint32_t max_b_frames; - // Zero: reserved for intra refresh and the like. + // `RGFX_VIDEO_ENCODE_CAP_*`: [`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`]. Zero from a host older + // than these. uint32_t flags; // Zero. uint32_t reserved_0c; @@ -8796,7 +8816,7 @@ typedef struct { // The frame's place in display order, from 0; the result says which frame its access unit // holds. uint64_t frame_index; - // `RGFX_VIDEO_ENCODE_*`: [`RGFX_VIDEO_ENCODE_FORCE_KEYFRAME`]. + // `RGFX_VIDEO_ENCODE_*`: [`RGFX_VIDEO_ENCODE_FORCE_KEYFRAME`], [`RGFX_VIDEO_ENCODE_IN_PLACE`]. uint32_t flags; // The bytes of [`RgfxVideoEncodeSettings`] after this body; 0 where they are unchanged. uint32_t settings_size; diff --git a/crates/reims-vgpu-graphics/src/ops/video.rs b/crates/reims-vgpu-graphics/src/ops/video.rs index f1b5085c3..bb757fab7 100644 --- a/crates/reims-vgpu-graphics/src/ops/video.rs +++ b/crates/reims-vgpu-graphics/src/ops/video.rs @@ -144,6 +144,19 @@ pub const RGFX_OP_VIDEO_ENCODE_H265: u16 = 0x4003; /// [`RgfxVideoOpEncode::flags`]: the frame is a keyframe (an IDR picture, or HEVC's IRAP). pub const RGFX_VIDEO_ENCODE_FORCE_KEYFRAME: u32 = 1 << 0; +/// [`RgfxVideoOpEncode::flags`]: the frame is coded in place of the session's last one, which the +/// guest drops: from the references the last one was coded from, at the same place in the +/// stream, so that the stream holds this frame where the last one was and no picture predicts +/// from the dropped one. Its `frame_index` is the last one's. Taken from a host whose +/// [`RgfxVideoEncodeCaps::flags`](crate::wire::RgfxVideoEncodeCaps) has +/// [`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`](crate::wire::RGFX_VIDEO_ENCODE_CAP_IN_PLACE) for the +/// codec. Where the host cannot, the encode fails ([`RGFX_VIDEO_ENCODE_FAILED`]), writes +/// nothing, and no later frame predicts from the dropped one: the session holds no last frame +/// to replace (none was coded since its settings made a new stream, or the last one failed), +/// codes B pictures, or holds a hard limit ([`RGFX_VIDEO_ENCODE_HARD_LIMIT`]) by coding frames +/// again itself; the `frame_index` is not the last one's; or the frame asks a keyframe in place +/// of one that is not. +pub const RGFX_VIDEO_ENCODE_IN_PLACE: u32 = 1 << 1; /// The body of [`RGFX_OP_VIDEO_ENCODE_H264`] and [`RGFX_OP_VIDEO_ENCODE_H265`], followed by /// `settings_size` bytes of [`RgfxVideoEncodeSettings`] where the settings changed since the @@ -171,7 +184,7 @@ pub struct RgfxVideoOpEncode { /// The frame's place in display order, from 0; the result says which frame its access unit /// holds. pub frame_index: u64, - /// `RGFX_VIDEO_ENCODE_*`: [`RGFX_VIDEO_ENCODE_FORCE_KEYFRAME`]. + /// `RGFX_VIDEO_ENCODE_*`: [`RGFX_VIDEO_ENCODE_FORCE_KEYFRAME`], [`RGFX_VIDEO_ENCODE_IN_PLACE`]. pub flags: u32, /// The bytes of [`RgfxVideoEncodeSettings`] after this body; 0 where they are unchanged. pub settings_size: u32, diff --git a/crates/reims-vgpu-graphics/src/wire.rs b/crates/reims-vgpu-graphics/src/wire.rs index b58ab6f23..52bec070a 100644 --- a/crates/reims-vgpu-graphics/src/wire.rs +++ b/crates/reims-vgpu-graphics/src/wire.rs @@ -5130,12 +5130,18 @@ pub struct RgfxVideoEncodeCaps { /// The most consecutive B pictures an encode takes /// ([`RgfxVideoEncodeSettings::b_frames`](crate::ops::video::RgfxVideoEncodeSettings)). pub max_b_frames: u32, - /// Zero: reserved for intra refresh and the like. + /// `RGFX_VIDEO_ENCODE_CAP_*`: [`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`]. Zero from a host older + /// than these. pub flags: u32, /// Zero. pub reserved_0c: u32, } +/// [`RgfxVideoEncodeCaps::flags`]: the host codes a frame in place of a session's last one +/// ([`RGFX_VIDEO_ENCODE_IN_PLACE`](crate::ops::video::RGFX_VIDEO_ENCODE_IN_PLACE)), a session of +/// no B pictures. +pub const RGFX_VIDEO_ENCODE_CAP_IN_PLACE: u32 = 1 << 0; + /// What the host's hardware takes of one decode codec beside its [`RgfxVideoCodecCaps`], by the /// same index ([`RgfxVideoCaps::decode`]): the bounds of a picture the host refuses, which the /// guest's video driver checks before it schedules the picture. All zero for an encode entry, diff --git a/crates/reims-vgpu-video/src/codec/encode/encoder.rs b/crates/reims-vgpu-video/src/codec/encode/encoder.rs index 96a7f8928..8d822d4ad 100644 --- a/crates/reims-vgpu-video/src/codec/encode/encoder.rs +++ b/crates/reims-vgpu-video/src/codec/encode/encoder.rs @@ -5,6 +5,13 @@ //! the accelerator encodes into [`EncodedSample`]s in decode order. The //! accelerator ([`Accelerator`]) uploads frames and runs the hardware; //! VA-API's is the VA-API backend's. +//! +//! A stream without B pictures or a hard limit holds its last picture back +//! from the accelerator's stream ([`Accelerator::keep`]) until the next +//! frame or a flush, so that the caller can have it coded again in its +//! place ([`Encoder::encode_in_place`]): from the references it was coded +//! from, with the same order count and decode time, at the QP the settings +//! give then. use std::collections::VecDeque; use std::sync::Arc; @@ -283,6 +290,51 @@ pub struct Encoder { limit_rate: Option, /// Pictures kept since the last IDR picture, counting it. since_key: u32, + /// The last picture coded, held back from the accelerator's stream + /// (module doc). + held: Option, +} + +/// The last picture coded, not yet the accelerator's (module doc): where +/// it was planned, the encoder's state before it, and the picture as the +/// accelerator last coded it. +struct Held { + frame_type: FrameType, + order: u32, + reference: Option, + forward: Option, + backward: Option, + pts: i64, + before: Before, + picture: Unkept, +} + +/// The encoder's state before a picture: what coding it again starts from. +struct Before { + dpb: VecDeque, + frame_num: u32, + idr_pic_id: u32, + since_key: u32, + rate_control_changed: bool, + record: Record, +} + +/// A picture's [`PictureParams`] as the accelerator last coded it, without +/// the encoder's settings, headers and parameter sets, which +/// [`Accelerator::keep`] is given as they are then. +struct Unkept { + frame_type: FrameType, + poc: i32, + frame_num: u32, + reference: Option, + list0: Option, + list1: Option, + dpb: Vec, + retained: Vec, + slice_header: PackedUnit, + h264_slice: Option, + hevc_slice: Option, + rate_control_changed: bool, } /// `value` rounded up to a multiple of `to`, a power of two; none past a @@ -611,6 +663,7 @@ impl Encoder { restart: false, limit_rate, since_key: 0, + held: None, }) } @@ -675,6 +728,148 @@ impl Encoder { Ok(self.push(input, frame)) } + /// [`Self::encode`] of `frame` in place of the last picture coded, whose + /// sample the caller drops (module doc): the same frame again, with its + /// time stamp, coded with the same picture type, references, order count + /// and decode time stamp, at the QP the settings give now. Its one sample + /// comes out at once. `Err` is a frame not taken: where there is no last + /// picture held to code again (none was coded since the stream began or + /// a picture failed, or the stream has B pictures or a hard limit), its + /// time stamp is not the last one's, it demands a key frame and the last + /// picture is not one, or it does not upload. Then the last picture is + /// gone with it, and the next frame is coded as an IDR picture. + pub fn encode_in_place( + &mut self, + frame: &InputFrame<'_>, + ) -> Result>, A::Error> { + let held = self.held_for(frame)?; + match self.accelerator.upload(frame) { + Ok(input) => Ok(self.code_again(held, input, frame)), + Err(error) => { + self.start_again(); + Err(error) + } + } + } + + /// [`Self::encode_in_place`] of a frame another device already wrote into + /// `input`, an input of the accelerator's ([`Self::encode_input`]). + pub fn encode_input_in_place( + &mut self, + input: A::Input, + frame: &InputFrame<'_>, + ) -> Result>, A::Error> { + let held = self.held_for(frame)?; + Ok(self.code_again(held, input, frame)) + } + + /// The held picture `frame` is coded in place of; `Err` where it cannot + /// be ([`Self::encode_in_place`]), and the stream starts again. + fn held_for(&mut self, frame: &InputFrame<'_>) -> Result { + let why = match self.held.take() { + Some(held) if held.pts != frame.pts => format!( + "a frame of PTS {} coded in place of PTS {}", + frame.pts, held.pts + ), + Some(held) if frame.force_key_frame && held.frame_type != FrameType::Idr => { + "a key frame coded in place of a picture that is not one".to_owned() + } + Some(held) => return Ok(held), + None if self.b_frames > 0 => { + "a frame coded in place in a stream with B pictures".into() + } + None if self.limit_rate.is_some() => { + "a frame coded in place in a stream held to a hard limit".into() + } + None => "a frame coded in place of none".into(), + }; + self.start_again(); + Err(Unsupported(why).into()) + } + + /// Starts the stream again where the caller dropped the last picture's + /// sample: no picture is held to code in place, and the next frame is + /// coded as an IDR picture. + pub fn start_again(&mut self) { + self.held = None; + self.dpb.clear(); + self.restart = true; + } + + /// Codes `frame`, in `input`, in place of `held` (module doc). + fn code_again( + &mut self, + held: Held, + input: A::Input, + frame: &InputFrame<'_>, + ) -> Vec> { + let Held { + frame_type, + order, + reference, + forward, + backward, + pts, + before, + picture: _, + } = held; + self.dpb = before.dpb; + self.frame_num = before.frame_num; + self.idr_pic_id = before.idr_pic_id; + self.since_key = before.since_key; + self.record = before.record; + // Rate control goes with it again where it went with the last try, + // and where it changed since. + self.rate_control_changed |= before.rate_control_changed; + // Without B pictures a sample's DTS is its PTS, which the last try's + // took. + self.times.push(pts); + let planned = Planned { + frame: Pending { + input, + pts, + duration: frame.duration, + id: frame.id, + }, + frame_type, + order, + reference, + forward, + backward, + }; + self.encode_all(vec![planned]) + } + + /// Gives the accelerator the held picture as the stream's. + fn keep_held(&mut self) { + let Some(held) = self.held.take() else { + return; + }; + let p = held.picture; + let parameter_sets: &[PackedUnit] = if p.frame_type == FrameType::Idr { + &self.parameter_sets + } else { + &[] + }; + self.accelerator.keep(&PictureParams { + settings: &self.settings, + headers: &self.headers, + frame_type: p.frame_type, + poc: p.poc, + frame_num: p.frame_num, + reference: p.reference, + list0: p.list0, + list1: p.list1, + dpb: &p.dpb, + retained: &p.retained, + parameter_sets, + slice_header: &p.slice_header, + h264_slice: p.h264_slice.as_ref(), + hevc_slice: p.hevc_slice.as_ref(), + rate_control_changed: p.rate_control_changed, + }); + } + /// `Err` where `pts` does not follow the last frame's. fn follows(&self, pts: i64) -> Result<(), A::Error> { if let Some(last) = self.last_pts { @@ -685,6 +880,7 @@ impl Encoder { /// Takes `frame`, in `input`, and encodes what its plan gives. fn push(&mut self, input: A::Input, frame: &InputFrame<'_>) -> Vec> { + self.keep_held(); self.last_pts = Some(frame.pts); self.times.push(frame.pts); let pending = Pending { @@ -701,8 +897,10 @@ impl Encoder { } /// Encodes the frames still waiting and returns each with its own - /// result. Frames may follow: the next starts a new run. + /// result, and gives the accelerator the last picture held (module doc). + /// Frames may follow: the next starts a new run. pub fn flush(&mut self) -> Vec> { + self.keep_held(); let planned = self.planner.flush(); self.encode_all(planned) } @@ -729,8 +927,8 @@ impl Encoder { Ok(sample) => coded.push(Ok(sample)), Err(error) => { self.times.next_dts(); - self.dpb.clear(); - self.restart = true; + // A picture held before it failed is not the stream's. + self.start_again(); failed = true; coded.push(Err(FailedSample { id, @@ -940,6 +1138,16 @@ impl Encoder { forward, backward, } = planned; + // Held back from the accelerator's stream (module doc). + let hold = self.b_frames == 0 && self.limit_rate.is_none(); + let before = hold.then(|| Before { + dpb: self.dpb.clone(), + frame_num: self.frame_num, + idr_pic_id: self.idr_pic_id, + since_key: self.since_key, + rate_control_changed: self.rate_control_changed, + record: self.record.clone(), + }); if frame_type == FrameType::Idr { self.dpb.clear(); self.frame_num = 0; @@ -952,6 +1160,7 @@ impl Encoder { Some(rate) => rate.plan(frame_type, self.remaining(), dts), None => self.qp(frame_type), }; + let planned_order = order; // At most gop::MAX_ORDER, so within an i32. let order = i32::try_from(order).map_err(|_| Unsupported::overflow("a picture's order count"))?; @@ -988,7 +1197,7 @@ impl Encoder { }; // The tries after the first. let mut retries = 1..LIMIT_TRIES; - let coded = loop { + let (coded, unkept) = loop { let (_, h264_slice, hevc_slice, slice_header) = self.slice_header(&slice(qp))?; let picture = PictureParams { settings: &self.settings, @@ -1021,9 +1230,37 @@ impl Encoder { } rate.coded(frame_type, qp, bits, dts); } + if hold { + break (coded, Some((slice_header, h264_slice, hevc_slice))); + } self.accelerator.keep(&picture); - break coded; + break (coded, None); }; + if let (Some(before), Some((slice_header, h264_slice, hevc_slice))) = (before, unkept) { + self.held = Some(Held { + frame_type, + order: planned_order, + reference, + forward, + backward, + pts: frame.pts, + before, + picture: Unkept { + frame_type, + poc, + frame_num, + reference, + list0, + list1, + dpb, + retained, + slice_header, + h264_slice, + hevc_slice, + rate_control_changed: self.rate_control_changed, + }, + }); + } self.rate_control_changed = false; self.since_key = self.since_key.saturating_add(1); self.dpb = after; @@ -1521,6 +1758,8 @@ pub mod tests { for n in 1..5 { coded.extend(encoder.encode(&frame(n, false))?); } + // The last picture is the accelerator's once the stream is flushed. + coded.extend(encoder.flush()); let samples = samples(coded)?; let Encoder { accelerator, .. } = encoder; let types: Vec = samples.iter().map(|s| s.frame_type).collect(); @@ -1698,4 +1937,227 @@ pub mod tests { } Ok(()) } + + /// HEVC or H.264 at constant QPs with no B pictures, as the guest's + /// paravirtual encoders ask (each picture's QP its own). + fn in_place_settings(profile: Profile) -> EncoderSettings { + let mut settings = EncoderSettings::new(profile, 640, 360); + settings.rate_control = at_qp(30); + settings.key_frame_interval = Some(30); + settings.allow_frame_reordering = false; + settings + } + + fn at_qp(qp: u8) -> RateControl { + RateControl::ConstantQp { + intra: qp, + predicted: qp, + bidirectional: qp, + } + } + + /// What `frames` frames, each `(n, key, again)`, come out as through an + /// encoder of `settings`: frame `n` (a key frame where `key`), coded at + /// QP 30, then coded in place of itself at QP 33, 36 and so on as many + /// times as `again` says, each QP set as it changes. Each result, with + /// the fake once flushed. + fn coded_again( + settings: EncoderSettings, + frames: &[(u32, bool, u8)], + ) -> Result<(Vec>, Fake), Unsupported> { + let mut encoder = Encoder::new(Fake::default(), settings, &limits())?; + let mut coded = Vec::new(); + let mut qp = 30; + let mut set = |encoder: &mut Encoder, to: u8| { + let changed = qp != to; + qp = to; + if changed { + encoder.set_rate_control(at_qp(to)) + } else { + Ok(()) + } + }; + for &(n, key, again) in frames { + set(&mut encoder, 30)?; + coded.extend(encoder.encode(&frame(n, key))?); + for retry in 1..=again { + set(&mut encoder, 30 + 3 * retry)?; + coded.extend(encoder.encode_in_place(&frame(n, key))?); + } + } + coded.extend(encoder.flush()); + let Encoder { accelerator, .. } = encoder; + Ok((coded, accelerator)) + } + + /// A picture as the fake saw it (`Seen`), without whether rate control + /// went with it. + type Placed = (FrameType, i32, Option, Option, Vec); + + /// Each picture the fake kept, without whether rate control went with it. + fn placed(fake: &Fake) -> Vec { + (fake.pictures.iter()) + .map(|p| (p.0, p.1, p.2, p.3, p.4.clone())) + .collect() + } + + /// The frames' samples, last try of each, and the fake. + fn last_tries( + settings: EncoderSettings, + frames: &[(u32, bool, u8)], + ) -> Result<(Vec, Vec, Fake), Unsupported> { + let (coded, fake) = coded_again(settings, frames)?; + let all = samples(coded)?; + let mut last: Vec = Vec::new(); + for sample in &all { + match last.last_mut() { + Some(previous) if previous.id == sample.id => *previous = sample.clone(), + _ => last.push(sample.clone()), + } + } + Ok((all, last, fake)) + } + + #[test] + fn a_picture_coded_in_place_is_the_one_it_replaces_at_another_qp() -> Result<(), Unsupported> { + use FrameType::{Idr, P}; + for profile in [Profile::HevcMain, Profile::HevcMain10, Profile::H264Main] { + let settings = in_place_settings(profile); + let plain: Vec<_> = (0..5).map(|n| (n, false, 0)).collect(); + let (_, once, plain_fake) = last_tries(settings.clone(), &plain)?; + // Frame 2 coded again once in its place, at QP 33. + let again: Vec<_> = (0..5).map(|n| (n, false, u8::from(n == 2))).collect(); + let (all, last, fake) = last_tries(settings, &again)?; + assert_eq!(all.len(), 6, "{profile:?}"); + assert_eq!(fake.calls, 6, "{profile:?}"); + // The stream is the one without it but for the QP of picture 2, + // and the rate control sent with the QPs that changed: the same + // types, order counts, references and frame numbers, and the + // picture after it predicts from it. + assert_eq!(placed(&fake), placed(&plain_fake), "{profile:?}"); + assert_eq!(fake.lsbs, plain_fake.lsbs, "{profile:?}"); + assert_eq!(fake.qps, [30, 30, 33, 30, 30], "{profile:?}"); + let sent: Vec = fake.pictures.iter().map(|p| p.5).collect(); + assert_eq!(sent, [true, false, true, true, false], "{profile:?}"); + assert_eq!(fake.pictures[3].2, Some(fake.pictures[2].1), "{profile:?}"); + let types: Vec = last.iter().map(|s| s.frame_type).collect(); + assert_eq!(types, [Idr, P, P, P, P], "{profile:?}"); + // Each try of frame 2 has its time stamps. + let tries: Vec<(u64, i64, i64)> = (all.iter()) + .filter(|s| s.id == 2) + .map(|s| (s.id, s.pts, s.dts)) + .collect(); + assert_eq!(tries, [(2, 6000, 6000), (2, 6000, 6000)], "{profile:?}"); + let times = |samples: &[EncodedSample]| -> Vec<(i64, i64)> { + samples.iter().map(|s| (s.pts, s.dts)).collect() + }; + assert_eq!(times(&last), times(&once), "{profile:?}"); + } + Ok(()) + } + + #[test] + fn a_picture_coded_in_place_twice_in_a_row_keeps_its_place() -> Result<(), Unsupported> { + let settings = in_place_settings(Profile::HevcMain); + let plain: Vec<_> = (0..4).map(|n| (n, false, 0)).collect(); + let (_, _, plain_fake) = last_tries(settings.clone(), &plain)?; + let again: Vec<_> = (0..4) + .map(|n| (n, false, if n == 1 { 2 } else { 0 })) + .collect(); + let (all, last, fake) = last_tries(settings, &again)?; + let ids: Vec = all.iter().map(|s| s.id).collect(); + assert_eq!(ids, [0, 1, 1, 1, 2, 3]); + assert_eq!(fake.calls, 6); + assert_eq!(placed(&fake), placed(&plain_fake)); + assert_eq!(fake.qps, [30, 36, 30, 30]); + assert_eq!(last.len(), 4); + Ok(()) + } + + #[test] + fn a_picture_after_an_idr_picture_or_one_coded_in_place_of_it() -> Result<(), Unsupported> { + use FrameType::{Idr, P}; + let settings = in_place_settings(Profile::HevcMain); + // The IDR picture coded again in its place: an IDR picture, which + // carries the configuration record again, and the P picture after + // it predicts from it. + let (all, _, fake) = last_tries(settings.clone(), &[(0, true, 1), (1, false, 0)])?; + let types: Vec = all.iter().map(|s| s.frame_type).collect(); + assert_eq!(types, [Idr, Idr, P]); + assert!(all[0].configuration.is_some() && all[1].configuration.is_some()); + assert_eq!(all[1].configuration, all[0].configuration); + assert!(all[2].configuration.is_none()); + assert_eq!(fake.qps, [33, 30]); + assert_eq!(fake.pictures[1].2, Some(0)); + // The P picture right after the IDR picture coded again: it still + // predicts from the IDR picture. + let (all, _, fake) = last_tries(settings, &[(0, true, 0), (1, false, 1), (2, false, 0)])?; + let types: Vec = all.iter().map(|s| s.frame_type).collect(); + assert_eq!(types, [Idr, P, P, P]); + assert_eq!(fake.qps, [30, 33, 30]); + assert_eq!(fake.pictures[1].1, 1); + assert_eq!(fake.pictures[1].2, Some(0)); + assert_eq!(fake.pictures[2].2, Some(1)); + // All key frames: each coded again in its place is an IDR picture + // again, at its own place. + let keys: Vec<_> = (0..4).map(|n| (n, true, 1)).collect(); + let (all, last, fake) = last_tries(in_place_settings(Profile::HevcMain), &keys)?; + assert_eq!(all.len(), 8); + assert!(last.iter().all(|s| s.frame_type == Idr)); + assert_eq!(fake.pictures.len(), 4); + assert_eq!(fake.qps, [33, 33, 33, 33]); + Ok(()) + } + + #[test] + fn a_frame_not_coded_in_place_starts_the_stream_again() -> Result<(), Unsupported> { + use FrameType::{Idr, P}; + let refused = |encoder: &mut Encoder, frame: &InputFrame<'_>| { + encoder.encode_in_place(frame).is_err() + }; + // None coded yet; another PTS than the last frame's; a key frame in + // place of a P picture. Each is refused, and the frame after it is + // coded as an IDR picture. + let mut encoder = Encoder::new( + Fake::default(), + in_place_settings(Profile::HevcMain), + &limits(), + )?; + assert!(refused(&mut encoder, &frame(0, false))); + let mut coded = encoder.encode(&frame(0, false))?; + coded.extend(encoder.encode(&frame(1, false))?); + assert!(refused(&mut encoder, &frame(2, false))); + coded.extend(encoder.encode(&frame(2, false))?); + coded.extend(encoder.encode(&frame(3, false))?); + assert!(refused(&mut encoder, &frame(3, true))); + coded.extend(encoder.encode(&frame(4, false))?); + // Refused twice in a row: nothing is held after the first. + assert!(refused(&mut encoder, &frame(5, false))); + assert!(refused(&mut encoder, &frame(4, false))); + coded.extend(encoder.encode(&frame(5, false))?); + let types: Vec = samples(coded)?.iter().map(|s| s.frame_type).collect(); + assert_eq!(types, [Idr, P, Idr, P, Idr, Idr]); + // After a picture that failed. + let fake = Fake { + fail_call: Some(1), + ..Fake::default() + }; + let mut encoder = Encoder::new(fake, in_place_settings(Profile::HevcMain), &limits())?; + drop(encoder.encode(&frame(0, false))?); + assert!(encoder.encode(&frame(1, false))?[0].is_err()); + assert!(refused(&mut encoder, &frame(1, false))); + // With B pictures, and held to a hard limit: never. + let mut settings = in_place_settings(Profile::H264High); + settings.allow_frame_reordering = true; + let mut encoder = Encoder::new(Fake::default(), settings, &limits())?; + assert_eq!(encoder.b_frames(), 1); + for n in 0..4 { + drop(encoder.encode(&frame(n, false))?); + } + assert!(refused(&mut encoder, &frame(3, false))); + let mut encoder = Encoder::new(Fake::default(), limited(), &limits())?; + drop(encoder.encode(&frame(0, false))?); + assert!(refused(&mut encoder, &frame(0, false))); + Ok(()) + } } diff --git a/crates/reims-vgpu-video/src/nvidia.rs b/crates/reims-vgpu-video/src/nvidia.rs index ddf2c0430..ecb1d4f1b 100644 --- a/crates/reims-vgpu-video/src/nvidia.rs +++ b/crates/reims-vgpu-video/src/nvidia.rs @@ -51,7 +51,7 @@ pub use external::ImportedBuffer; pub use nvdec::{ChromaFormat, DecodeCapabilities, NvdecCodec, SurfaceFormat, decode_capabilities}; pub use nvenc::encoder::{ Bitstream, DeviceFrame, EncodeParams, EncodeProfile, EncodeProfileSupport, EncodeRateControl, - NvencEncoder, Packet, PictureType, RawFrame, Tuning, encode_profiles, + NvencEncoder, Packet, PictureType, RawFrame, Tuning, codes_in_place, encode_profiles, }; pub use nvenc::max_api_version; pub use probe::{EncodeCodecReport, EncoderReport, encoder_report}; diff --git a/crates/reims-vgpu-video/src/nvidia/layout.rs b/crates/reims-vgpu-video/src/nvidia/layout.rs index ce29fb5f1..4fcec1aab 100644 --- a/crates/reims-vgpu-video/src/nvidia/layout.rs +++ b/crates/reims-vgpu-video/src/nvidia/layout.rs @@ -603,6 +603,11 @@ fn nvenc_checks(checks: &mut Checks) { diffPicNumHint, alphaBuffer, meExternalSbHints, meSbHintsCount, stateBufferIdx, outputReconBuffer, reserved3, reserved6, }); + layout!(checks, enc::NV_ENC_RESTORE_ENCODER_STATE_PARAMS, + "NV_ENC_RESTORE_ENCODER_STATE_PARAMS" { + version, bufferIdx, state, reserved, outputBitstream, completionEvent, reserved1, + reserved2, + }); layout!(checks, enc::NV_ENC_LOCK_BITSTREAM, "NV_ENC_LOCK_BITSTREAM" { version, outputBitstream, sliceOffsets, frameIdx, hwEncodeStatus, numSlices, bitstreamSizeInBytes, outputTimeStamp, outputDuration, bitstreamBufferPtr, pictureType, @@ -700,6 +705,10 @@ fn nvenc_checks(checks: &mut Checks) { "NV_ENCODE_API_FUNCTION_LIST_VER", enc::NV_ENCODE_API_FUNCTION_LIST_VER, ), + ( + "NV_ENC_RESTORE_ENCODER_STATE_PARAMS_VER", + enc::NV_ENC_RESTORE_ENCODER_STATE_PARAMS_VER, + ), ("NVENC_INFINITE_GOPLENGTH", enc::NVENC_INFINITE_GOPLENGTH), ("NV_ENC_PIC_FLAG_FORCEIDR", enc::NV_ENC_PIC_FLAG_FORCEIDR), ( @@ -707,6 +716,10 @@ fn nvenc_checks(checks: &mut Checks) { enc::NV_ENC_PIC_FLAG_OUTPUT_SPSPPS, ), ("NV_ENC_PIC_FLAG_EOS", enc::NV_ENC_PIC_FLAG_EOS), + ( + "NV_ENC_PIC_FLAG_DISABLE_ENC_STATE_ADVANCE", + enc::NV_ENC_PIC_FLAG_DISABLE_ENC_STATE_ADVANCE, + ), ("NV_ENC_LEVEL_AUTOSELECT", enc::NV_ENC_LEVEL_AUTOSELECT), ] { checks.constant(name, value.into()); @@ -785,6 +798,11 @@ fn nvenc_checks(checks: &mut Checks) { "NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES", enc::caps::SUPPORT_MULTIPLE_REF_FRAMES, ), + ( + "NV_ENC_CAPS_DISABLE_ENC_STATE_ADVANCE", + enc::caps::DISABLE_ENC_STATE_ADVANCE, + ), + ("NV_ENC_STATE_RESTORE_FULL", enc::NV_ENC_STATE_RESTORE_FULL), ] { checks.constant(name, value.into()); } diff --git a/crates/reims-vgpu-video/src/nvidia/nvenc.rs b/crates/reims-vgpu-video/src/nvidia/nvenc.rs index 39769fa98..c7fa00d92 100644 --- a/crates/reims-vgpu-video/src/nvidia/nvenc.rs +++ b/crates/reims-vgpu-video/src/nvidia/nvenc.rs @@ -224,7 +224,9 @@ pub(crate) enum Submission { /// 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. + /// before it. `unadvanced` codes it without advancing the encoder's + /// state, which state buffer 0 then holds as it would be after it + /// ([`Session::restore_state`]). Frame { input: Buffer, output: Buffer, @@ -232,6 +234,7 @@ pub(crate) enum Submission { index: u32, timestamp: u64, idr: bool, + unadvanced: bool, }, /// The end of the stream: every frame NVENC holds comes out. End, @@ -351,6 +354,25 @@ impl Session { result } + /// Advances the encoder's state to the one state buffer 0 holds: as it is after the last + /// frame coded without advancing it (`nvEncRestoreEncoderState`, the whole state). NVENC is + /// done with every frame submitted before. + pub(crate) fn restore_state(&self) -> Result<(), Error> { + let call = entry!(self.nvenc, nvEncRestoreEncoderState)?; + self.check_not_stalled()?; + let mut params = ffi::NV_ENC_RESTORE_ENCODER_STATE_PARAMS::zeroed(); + params.version = ffi::NV_ENC_RESTORE_ENCODER_STATE_PARAMS_VER; + params.bufferIdx = 0; + params.state = ffi::NV_ENC_STATE_RESTORE_FULL; + let encoder = self.encoder; + self.gpu.push().and_then(|_current| { + // SAFETY: a live, initialised session; the parameters are live and versioned, and + // name no buffer. + let status = unsafe { call(encoder, &raw mut params) }; + check_status("nvEncRestoreEncoderState", status, Some(encoder)) + }) + } + /// Makes an input buffer of `width` by `height` frames in `format`. pub(crate) fn create_input( &mut self, @@ -757,6 +779,7 @@ impl Session { index, timestamp, idr, + unadvanced, } => { let output = self.output(output, &[BufferKind::Bitstream])?; self.submitted.borrow().check_free(output)?; @@ -778,6 +801,10 @@ impl Session { picture.encodePicFlags = ffi::NV_ENC_PIC_FLAG_FORCEIDR | ffi::NV_ENC_PIC_FLAG_OUTPUT_SPSPPS; } + if unadvanced { + picture.encodePicFlags |= ffi::NV_ENC_PIC_FLAG_DISABLE_ENC_STATE_ADVANCE; + picture.stateBufferIdx = 0; + } } Submission::End => picture.encodePicFlags = ffi::NV_ENC_PIC_FLAG_EOS, } diff --git a/crates/reims-vgpu-video/src/nvidia/nvenc/encoder.rs b/crates/reims-vgpu-video/src/nvidia/nvenc/encoder.rs index 841e436f8..20759c1e0 100644 --- a/crates/reims-vgpu-video/src/nvidia/nvenc/encoder.rs +++ b/crates/reims-vgpu-video/src/nvidia/nvenc/encoder.rs @@ -10,6 +10,14 @@ //! 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. +//! +//! A session made to code frames in place ([`NvencEncoder::new_in_place`]) +//! codes each frame without advancing NVENC's state, which a state buffer +//! keeps as it is after the frame, and advances it to that state +//! (`nvEncRestoreEncoderState`) only as the next frame comes, or the stream +//! ends ([`NvencEncoder::keep`]). Until then the frame can be coded again in +//! its place ([`NvencEncoder::encode_in_place`]), from NVENC's state before +//! it: the same place in the stream, at the rate control's settings then. use std::collections::VecDeque; use std::sync::Arc; @@ -276,6 +284,14 @@ pub struct NvencEncoder { /// The registered input each slot's pending frame reads, if it is /// device memory. slot_inputs: Vec>, + /// Whether each frame is coded without advancing NVENC's state (module + /// doc). + holds: bool, + /// The last frame coded so, while NVENC's state is the one before it. + unkept: Option, + /// The next frame is coded as an IDR picture: NVENC's state is not the + /// one after the last frame the caller has. + restart: bool, session: Session, /// The device memory registered as input. After the session, which /// unregisters it as it drops, so that the imports outlive their @@ -283,6 +299,20 @@ pub struct NvencEncoder { device_inputs: Vec, } +/// The last frame a session that codes frames in place coded (module doc): +/// what coding it again takes. +#[derive(Clone, Copy, Debug)] +struct Unkept { + /// The caller's index for it. + index: u64, + /// Its `frameIdx`. + frame_idx: u32, + /// Whether it was asked to be an IDR picture. + idr: bool, + /// What NVENC coded it as. + picture_type: PictureType, +} + /// Ours: input and bitstream buffers beyond what NVENC holds, so that a /// frame never waits for a buffer to come back. const EXTRA_SLOTS: usize = 3; @@ -290,6 +320,22 @@ const EXTRA_SLOTS: usize = 3; impl NvencEncoder { /// Opens a session on `gpu` and configures it for `params`. pub fn new(gpu: Arc, params: &EncodeParams) -> Result { + Self::open(gpu, params, false) + } + + /// [`Self::new`] of a session that codes frames in place (module doc), + /// with a state buffer: one without B pictures. `Err` where NVENC + /// refuses the state buffer. + pub fn new_in_place(gpu: Arc, params: &EncodeParams) -> Result { + if params.b_frames > 0 { + return Err(Error::Unsupported( + "frames coded in place in a stream with B pictures".to_owned(), + )); + } + Self::open(gpu, params, true) + } + + fn open(gpu: Arc, params: &EncodeParams, holds: bool) -> Result { let mut session = Session::open(gpu)?; let codec = params.profile.codec_guid(); check_params(&session, params, codec)?; @@ -318,6 +364,7 @@ impl NvencEncoder { init.maxEncodeWidth = params.width; init.maxEncodeHeight = params.height; init.tuningInfo = tuning; + init.numStateBuffers = u32::from(holds); session.initialize(init, config)?; let mut encoder = Self { params: params.clone(), @@ -328,6 +375,9 @@ impl NvencEncoder { submitted: 0, sequence_parameters: Vec::new(), slot_inputs: Vec::new(), + holds, + unkept: None, + restart: false, session, device_inputs: Vec::new(), }; @@ -384,6 +434,105 @@ impl NvencEncoder { self.submit(slot_index, input, pitch, frame.index, frame.force_idr) } + /// [`Self::encode`] of `frame` in place of the last frame coded, whose + /// packet the caller drops (module doc): the same frame again, its index + /// the last one's, coded from NVENC's state before the last one, at the + /// rate control's settings now. Its one packet comes out at once. `Err` + /// is a frame not taken: where the session codes no frame in place or + /// holds none to code again, the index is not the last frame's, or it + /// asks an IDR picture in place of a frame that is not one, the last + /// frame is gone with it, and the next frame is coded from NVENC's state + /// before it; where the frame does not reach NVENC, or NVENC does not + /// take it, the last frame stays, to code again in place. + pub fn encode_in_place(&mut self, frame: &RawFrame<'_>) -> Result, Error> { + let unkept = self.unkept_for(frame.index, frame.force_idr)?; + 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.code( + slot_index, + input, + pitch, + frame.index, + unkept.idr || frame.force_idr, + unkept.frame_idx, + ) + } + + /// [`Self::encode_in_place`] of a frame NVENC reads where another API's + /// GPU wrote it, as [`Self::encode_device`] takes it. + pub fn encode_device_in_place( + &mut self, + frame: &DeviceFrame<'_>, + ) -> Result, Error> { + let unkept = self.unkept_for(frame.index, frame.force_idr)?; + let (slot_index, registered) = self.device_slot(frame)?; + self.code( + slot_index, + registered, + frame.pitch, + frame.index, + unkept.idr || frame.force_idr, + unkept.frame_idx, + ) + } + + /// The last frame coded, which a frame of `index` is coded in place of, + /// asking an IDR picture where `force_idr` ([`Self::encode_in_place`]). + fn unkept_for(&mut self, index: u64, force_idr: bool) -> Result { + let why = match self.unkept { + Some(unkept) if unkept.index != index => { + format!("frame {index} coded in place of frame {}", unkept.index) + } + Some(unkept) if force_idr && unkept.picture_type != PictureType::Idr => { + "an IDR picture coded in place of a frame that is not one".to_owned() + } + Some(unkept) => return Ok(unkept), + None if !self.holds => { + "a frame coded in place in a session without a state buffer".into() + } + None => "a frame coded in place of none".into(), + }; + self.unkept = None; + Err(Error::Unsupported(why)) + } + + /// Takes the last frame coded as the stream's (module doc): NVENC's state + /// advances to the one after it. `Err` where NVENC refuses: then the + /// next frame is coded as an IDR picture. + pub fn keep(&mut self) -> Result<(), Error> { + if self.unkept.take().is_none() { + return Ok(()); + } + self.submitted = self.submitted.wrapping_add(1); + self.session + .restore_state() + .inspect_err(|_| self.restart = true) + } + + /// [`Self::keep`] as a frame or the end comes, which go on where NVENC + /// refuses, with a warning. + fn keep_going(&mut self) { + if let Err(e) = self.keep() { + log::warn!( + kind:% = e; + "NVENC's state after a frame: {e}; the next frame is an IDR picture" + ); + } + } + + /// Drops the last frame coded, whose packet the caller dropped: the next + /// frame is coded from NVENC's state before it. + pub fn drop_last(&mut self) { + self.unkept = None; + } + /// 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 @@ -393,6 +542,19 @@ impl NvencEncoder { /// 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, Error> { + let (slot_index, registered) = self.device_slot(frame)?; + self.submit( + slot_index, + registered, + frame.pitch, + frame.index, + frame.force_idr, + ) + } + + /// The slot `frame` goes in, and its memory's registration + /// ([`Self::encode_device`]). + fn device_slot(&mut self, frame: &DeviceFrame<'_>) -> Result<(usize, Buffer), Error> { let registered = self.device_input(frame.input, frame.pitch)?; let in_flight = (self.pending.iter()).any(|&slot| self.slot_inputs[slot] == Some(registered)); @@ -403,13 +565,7 @@ impl NvencEncoder { } 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, - ) + Ok((slot_index, registered)) } /// The bytes of a frame's row: its width in samples of its bit depth. @@ -485,7 +641,8 @@ impl NvencEncoder { } /// Submits the frame in `input` at `pitch` into `slot_index`'s - /// bitstream buffer, and reads what comes out ([`Self::encode`]). + /// bitstream buffer, after the last frame, and reads what comes out + /// ([`Self::encode`]). fn submit( &mut self, slot_index: usize, @@ -493,14 +650,39 @@ impl NvencEncoder { pitch: u32, index: u64, force_idr: bool, + ) -> Result, Error> { + self.keep_going(); + let frame_idx = self.submitted; + self.code( + slot_index, + input, + pitch, + index, + force_idr || self.restart, + frame_idx, + ) + } + + /// Codes the frame in `input` at `pitch` into `slot_index`'s bitstream + /// buffer as `frame_idx`, and reads what comes out; in a session that + /// codes frames in place, without advancing NVENC's state (module doc). + fn code( + &mut self, + slot_index: usize, + input: Buffer, + pitch: u32, + index: u64, + idr: bool, + frame_idx: u32, ) -> Result, Error> { let status = self.session.encode_picture(Submission::Frame { input, output: self.slots[slot_index].output, pitch, - index: self.submitted, + index: frame_idx, timestamp: index, - idr: force_idr, + idr, + unadvanced: self.holds, }); let status = match status { Ok(status) => status, @@ -509,18 +691,34 @@ impl NvencEncoder { return Err(e); } }; - self.submitted = self.submitted.wrapping_add(1); + if !self.holds { + self.submitted = self.submitted.wrapping_add(1); + } + self.restart = false; self.next = (slot_index + 1) % self.slots.len(); self.pending.push_back(slot_index); if status == ffi::NV_ENC_ERR_NEED_MORE_INPUT { return Ok(Vec::new()); } - Ok(self.drain()) + let bitstreams = self.drain(); + if self.holds + && let [Ok(packet)] = bitstreams.as_slice() + { + self.unkept = Some(Unkept { + index, + frame_idx, + idr, + picture_type: packet.picture_type, + }); + } + Ok(bitstreams) } - /// Ends the stream: every frame NVENC still holds comes out, each with - /// its own result. `Err` is an end NVENC did not take. + /// Ends the stream: the last frame coded is the stream's + /// ([`Self::keep`]), and every frame NVENC still holds comes out, each + /// with its own result. `Err` is an end NVENC did not take. pub fn flush(&mut self) -> Result, Error> { + self.keep_going(); if self.pending.is_empty() { return Ok(Vec::new()); } @@ -621,6 +819,11 @@ pub struct EncodeProfileSupport { /// (`NV_ENC_NUM_REF_FRAMES_7`), where NVENC takes several /// (`NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES`); 1 where it does not. pub max_references: u32, + /// Whether NVENC says it codes a frame without advancing its state + /// (`NV_ENC_CAPS_DISABLE_ENC_STATE_ADVANCE`), which a session that codes + /// frames in place takes ([`NvencEncoder::new_in_place`], + /// [`codes_in_place`]); false where it does not answer. + pub in_place: bool, } /// The most reference frames `numRefL0` names (`NV_ENC_NUM_REF_FRAMES_7`). @@ -674,11 +877,76 @@ pub fn encode_profiles(gpu: Arc) -> Result, Error } else { 1 }, + in_place: cap(ffi::caps::DISABLE_ENC_STATE_ADVANCE).is_ok_and(|v| v != 0), }); } Ok(supported) } +/// Whether NVENC on `gpu` codes frames of `profile` in place: a session of +/// it at `width` by `height` at a constant QP, with a state buffer +/// ([`NvencEncoder::new_in_place`]), codes a frame, the frame again in its +/// place at another QP, and a frame after it, each one access unit. `Err`, +/// with why, where it does not. +pub fn codes_in_place( + gpu: Arc, + profile: EncodeProfile, + width: u32, + height: u32, +) -> Result<(), Error> { + let at_qp = |qp| EncodeRateControl::ConstantQp { + intra: qp, + predicted: qp, + bidirectional: qp, + }; + let params = EncodeParams { + profile, + width, + height, + frame_rate: (30, 1), + rate_control: at_qp(30), + buffer_milliseconds: 1000, + gop_length: None, + b_frames: 0, + level: None, + cabac: None, + full_range: false, + colour: None, + display_aspect: None, + preset: 1, + tuning: Tuning::LowLatency, + }; + let mut encoder = NvencEncoder::new_in_place(gpu, ¶ms)?; + let sample = if profile.bit_depth() > 8 { 2 } else { 1 }; + let row = usize::try_from(width).unwrap_or(0) * sample; + let rows = usize::try_from(height).unwrap_or(0); + let luma = vec![0u8; row * rows]; + let chroma = vec![0u8; row * rows.div_ceil(2)]; + let frame = |index, force_idr| RawFrame { + luma: (&luma, row), + chroma: (&chroma, row), + index, + force_idr, + }; + let one = |bitstreams: Vec, index: u64| -> Result<(), Error> { + match bitstreams.as_slice() { + [Ok(packet)] if packet.index == index => Ok(()), + [Err(e)] => Err(e.clone()), + other => Err(Error::Unsupported(format!( + "{} access units for frame {index}", + other.len() + ))), + } + }; + one(encoder.encode(&frame(0, true))?, 0)?; + encoder.reconfigure(at_qp(33), params.frame_rate)?; + one(encoder.encode_in_place(&frame(0, true))?, 0)?; + encoder.keep()?; + encoder.reconfigure(at_qp(30), params.frame_rate)?; + one(encoder.encode(&frame(1, false))?, 1)?; + encoder.keep() +} + impl Drop for NvencEncoder { fn drop(&mut self) { // Frames NVENC still holds are ended and read first: destroying @@ -1023,6 +1291,7 @@ pub(crate) mod tests { index: n, timestamp: u64::from(n), idr: (n / 3) % 2 == 0, + unadvanced: false, })?; let submit = StdRuntime.elapsed_since(submitting).as_micros(); let handle = session.output(output, &[BufferKind::Bitstream])?; diff --git a/crates/reims-vgpu-video/src/nvidia/nvenc/ffi.rs b/crates/reims-vgpu-video/src/nvidia/nvenc/ffi.rs index 339c0fe09..edd7ac00e 100644 --- a/crates/reims-vgpu-video/src/nvidia/nvenc/ffi.rs +++ b/crates/reims-vgpu-video/src/nvidia/nvenc/ffi.rs @@ -73,6 +73,7 @@ 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); +pub(crate) const NV_ENC_RESTORE_ENCODER_STATE_PARAMS_VER: u32 = struct_version(2); /// `NVENC_INFINITE_GOPLENGTH`. pub(crate) const NVENC_INFINITE_GOPLENGTH: u32 = 0xffff_ffff; @@ -142,6 +143,11 @@ pub(crate) const NV_ENC_PIC_TYPE_NONREF_P: NV_ENC_PIC_TYPE = 0x7; pub(crate) const NV_ENC_PIC_FLAG_FORCEIDR: u32 = 0x2; pub(crate) const NV_ENC_PIC_FLAG_OUTPUT_SPSPPS: u32 = 0x4; pub(crate) const NV_ENC_PIC_FLAG_EOS: u32 = 0x8; +pub(crate) const NV_ENC_PIC_FLAG_DISABLE_ENC_STATE_ADVANCE: u32 = 0x10; + +/// `NV_ENC_STATE_RESTORE_TYPE`. +pub(crate) type NV_ENC_STATE_RESTORE_TYPE = c_int; +pub(crate) const NV_ENC_STATE_RESTORE_FULL: NV_ENC_STATE_RESTORE_TYPE = 0x01; pub(crate) const NV_ENC_H264_ENTROPY_CODING_MODE_CABAC: NvEncEnum = 0x1; pub(crate) const NV_ENC_H264_ENTROPY_CODING_MODE_CAVLC: NvEncEnum = 0x2; @@ -165,6 +171,7 @@ pub(crate) mod caps { pub(crate) const WIDTH_MIN: NV_ENC_CAPS = 45; pub(crate) const HEIGHT_MIN: NV_ENC_CAPS = 46; pub(crate) const SUPPORT_MULTIPLE_REF_FRAMES: NV_ENC_CAPS = 47; + pub(crate) const DISABLE_ENC_STATE_ADVANCE: NV_ENC_CAPS = 51; } /// `NV_ENC_CAPS`' names without their `NV_ENC_CAPS_` prefix, by value, @@ -719,6 +726,20 @@ pub(crate) struct NV_ENC_PIC_PARAMS { pub(crate) reserved6: [*mut c_void; 57], } +/// `NV_ENC_RESTORE_ENCODER_STATE_PARAMS`. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub(crate) struct NV_ENC_RESTORE_ENCODER_STATE_PARAMS { + pub(crate) version: u32, + pub(crate) bufferIdx: u32, + pub(crate) state: NV_ENC_STATE_RESTORE_TYPE, + pub(crate) reserved: u32, + pub(crate) outputBitstream: *mut c_void, + pub(crate) completionEvent: *mut c_void, + pub(crate) reserved1: [u32; 64], + pub(crate) reserved2: [*mut c_void; 64], +} + /// `NV_ENC_LOCK_BITSTREAM`. #[repr(C)] #[derive(Clone, Copy, Debug)] @@ -974,7 +995,8 @@ function_list! { *mut NV_ENC_INITIALIZE_PARAMS, *mut NV_ENC_SEQUENCE_PARAM_PAYLOAD, ) -> NVENCSTATUS; - nvEncRestoreEncoderState: fn(Encoder, *mut c_void) -> NVENCSTATUS; + nvEncRestoreEncoderState: fn(Encoder, *mut NV_ENC_RESTORE_ENCODER_STATE_PARAMS) + -> NVENCSTATUS; nvEncLookaheadPicture: fn(Encoder, *mut c_void) -> NVENCSTATUS; } reserved2: 275 @@ -999,6 +1021,8 @@ unsafe impl Zeroed for NV_ENC_CREATE_INPUT_BUFFER {} // SAFETY: as above. unsafe impl Zeroed for NV_ENC_CREATE_BITSTREAM_BUFFER {} // SAFETY: as above. +unsafe impl Zeroed for NV_ENC_RESTORE_ENCODER_STATE_PARAMS {} +// SAFETY: as above. unsafe impl Zeroed for NV_ENC_CONFIG {} // SAFETY: as above. unsafe impl Zeroed for NV_ENC_INITIALIZE_PARAMS {} diff --git a/crates/reims-vgpu-video/src/vaapi/va/encoder.rs b/crates/reims-vgpu-video/src/vaapi/va/encoder.rs index 338ba2169..9fde43e56 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/encoder.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/encoder.rs @@ -277,6 +277,22 @@ impl VideoEncoder { wait::by(&Deadline::default(), || self.inner.encode(frame)) } + /// [`Self::encode`] of `frame` in place of the last frame encoded, whose + /// sample the caller drops: the same frame again, coded as the last one + /// was, from the references it was coded from, at the QP the settings give + /// now ([`Encoder::encode_in_place`]). `Err` is a frame not taken, after + /// which the next frame is coded as an IDR picture. + pub fn encode_in_place(&mut self, frame: &InputFrame<'_>) -> Result>, Error> { + wait::by(&Deadline::default(), || self.inner.encode_in_place(frame)) + } + + /// Starts the stream again where the caller dropped the last frame's + /// sample ([`Encoder::start_again`]): the next frame is coded as an IDR + /// picture. + pub fn start_again(&mut self) { + self.inner.start_again(); + } + /// Encodes the frames still waiting, and returns each with its own /// result. More frames may follow. pub fn flush(&mut self) -> Vec> { @@ -433,6 +449,33 @@ impl VideoEncoder { input: &Target, frame: &InputFrame<'_>, ) -> Result>, Error> { + let input = self.input_of(input)?; + wait::by(&Deadline::default(), || { + self.inner.encode_input(input, frame) + }) + } + + /// [`Self::encode_in_place`] of the frame written into `input`, as + /// [`Self::encode_target`] takes it. + pub fn encode_target_in_place( + &mut self, + input: &Target, + frame: &InputFrame<'_>, + ) -> Result>, Error> { + let input = match self.input_of(input) { + Ok(input) => input, + Err(error) => { + self.inner.start_again(); + return Err(error); + } + }; + wait::by(&Deadline::default(), || { + self.inner.encode_input_in_place(input, frame) + }) + } + + /// `input` as the encoder takes it ([`Self::encode_target`]). + fn input_of(&self, input: &Target) -> Result { let shape = self.input_shape(); if !input.is_on(self.inner.accelerator().display()) || input.shape() != shape { return Err(Error::Unsupported(format!( @@ -445,10 +488,7 @@ impl VideoEncoder { } ))); } - let input = Input::Imported(input.clone()); - wait::by(&Deadline::default(), || { - self.inner.encode_input(input, frame) - }) + Ok(Input::Imported(input.clone())) } } diff --git a/crates/reims-vgpu/src/graphics/decode/video.rs b/crates/reims-vgpu/src/graphics/decode/video.rs index 141821de4..39f19226e 100644 --- a/crates/reims-vgpu/src/graphics/decode/video.rs +++ b/crates/reims-vgpu/src/graphics/decode/video.rs @@ -45,8 +45,9 @@ use std::sync::Arc; use reims_vgpu_graphics::ops::video::{ RGFX_OP_VIDEO_DECODE_H264, RGFX_OP_VIDEO_DECODE_H265, RGFX_OP_VIDEO_ENCODE_H264, - RGFX_OP_VIDEO_ENCODE_H265, RGFX_VIDEO_ENCODE_FORCE_KEYFRAME, RgfxVideoEncodeResult, - RgfxVideoEncodeSettings, RgfxVideoOpDecodeH264, RgfxVideoOpDecodeH265, RgfxVideoOpEncode, + RGFX_OP_VIDEO_ENCODE_H265, RGFX_VIDEO_ENCODE_FORCE_KEYFRAME, RGFX_VIDEO_ENCODE_IN_PLACE, + RgfxVideoEncodeResult, RgfxVideoEncodeSettings, RgfxVideoOpDecodeH264, RgfxVideoOpDecodeH265, + RgfxVideoOpEncode, }; use reims_vgpu_graphics::wire::{ RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_DECODE, RgfxSurfaceFacts, @@ -741,6 +742,9 @@ pub struct VideoEncode<'a, P: Platform> { pub frame_index: u64, /// Whether the frame must be a keyframe. pub force_keyframe: bool, + /// Whether the frame is coded in place of the session's last one + /// (`RGFX_VIDEO_ENCODE_IN_PLACE`). + pub in_place: bool, /// The settings from this frame on, where they changed since the session's last encode. pub settings: Option, } @@ -1089,6 +1093,7 @@ fn encode_op( result_offset: m.result_offset, frame_index: m.frame_index, force_keyframe: m.flags & RGFX_VIDEO_ENCODE_FORCE_KEYFRAME != 0, + in_place: m.flags & RGFX_VIDEO_ENCODE_IN_PLACE != 0, settings, }; // After the buffers of other queues its command buffer runs after: the writes of the diff --git a/crates/reims-vgpu/src/graphics/nvidia.rs b/crates/reims-vgpu/src/graphics/nvidia.rs index 69fa1b4a8..1e31bd99e 100644 --- a/crates/reims-vgpu/src/graphics/nvidia.rs +++ b/crates/reims-vgpu/src/graphics/nvidia.rs @@ -321,7 +321,7 @@ impl NvidiaVideo

{ }); let vp9 = vp9_caps(asked(NvdecCodec::Vp9, 8), asked(NvdecCodec::Vp9, 10)); let encoders = match encode_profiles(Arc::clone(&gpu)) { - Ok(encoders) => encoders, + Ok(encoders) => encode::checked_in_place(&gpu, encoders), Err(error) => { log::info!("hardware video: no {ENCODE_NAME} at {address}: {error}"); Vec::new() diff --git a/crates/reims-vgpu/src/graphics/nvidia/encode.rs b/crates/reims-vgpu/src/graphics/nvidia/encode.rs index f9e0f6a1b..c844a7a9a 100644 --- a/crates/reims-vgpu/src/graphics/nvidia/encode.rs +++ b/crates/reims-vgpu/src/graphics/nvidia/encode.rs @@ -7,7 +7,15 @@ //! (and P010 for HEVC Main 10), the least of their sizes, the codec's top level, and the //! references NVENC takes. Its rate controls ([`encode_caps`]) are CQP, and CBR and VBR where //! NVENC lists them, and no B-frames: the encoder keeps frames in display order, a frame in and -//! its access unit out. +//! its access unit out. It codes a frame in place of the last one +//! (`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`) where NVENC says it codes a frame without advancing its +//! state for every profile of the codec, and a session of the codec with a state buffer did +//! so at the device's start ([`checked_in_place`]); a driver that refuses either leaves the +//! flag off. A session then codes each frame without advancing NVENC's state, and advances it +//! (`nvEncRestoreEncoderState`) as the next frame comes: a frame coded in place is coded from +//! the state before the last one (the NVIDIA crate's `NvencEncoder::new_in_place`). A frame +//! coded in place that fails, or is refused, drops the last one: the next frame is coded from +//! the state before it. //! - **The settings** ([`params_of`]) map onto the NVIDIA crate's: the profile, size, level, //! entropy coder and colour; a VBR with no peak peaks at 1.05 times its average, as the VA-API //! arm's does; `quality` 0 to 100 onto NVENC's presets ([`preset_of`]): P1 (the fastest) up @@ -41,13 +49,14 @@ use reims_vgpu_graphics::ops::video::{ RgfxVideoEncodeSettings, }; use reims_vgpu_graphics::wire::{ - RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_ENCODE, RGFX_VIDEO_FORMAT_NV12, - RGFX_VIDEO_FORMAT_P010, RGFX_VIDEO_H264_BASELINE, RGFX_VIDEO_H264_HIGH, RGFX_VIDEO_H264_MAIN, - RGFX_VIDEO_HEVC_MAIN, RGFX_VIDEO_HEVC_MAIN_10, RgfxVideoCodecCaps, RgfxVideoEncodeCaps, + RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_ENCODE, + RGFX_VIDEO_ENCODE_CAP_IN_PLACE, RGFX_VIDEO_FORMAT_NV12, RGFX_VIDEO_FORMAT_P010, + RGFX_VIDEO_H264_BASELINE, RGFX_VIDEO_H264_HIGH, RGFX_VIDEO_H264_MAIN, RGFX_VIDEO_HEVC_MAIN, + RGFX_VIDEO_HEVC_MAIN_10, RgfxVideoCodecCaps, RgfxVideoEncodeCaps, }; use reims_vgpu_video::nvidia::{ Bitstream, DeviceFrame, EncodeParams, EncodeProfile, EncodeProfileSupport, EncodeRateControl, - Gpu, NvencEncoder, PictureType, RawFrame, Tuning, + Gpu, NvencEncoder, PictureType, RawFrame, Tuning, codes_in_place, }; use reims_vgpu_vulkan::core::platform::Platform; use reims_vgpu_vulkan::core::sync::Mutex; @@ -144,9 +153,45 @@ pub(super) fn encode_caps_of(supports: &[EncodeProfileSupport]) -> Vec, + mut supports: Vec, +) -> Vec { + for codec in [RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC] { + let of_codec = |s: &EncodeProfileSupport| wire_profile(s.profile).0 == codec; + let Some(first) = supports.iter().find(|s| of_codec(s)).copied() else { + continue; + }; + let size = |min: u32, max: u32| min.max(256).min(max) & !1; + let checked = if supports.iter().filter(|s| of_codec(s)).all(|s| s.in_place) { + let (width, height) = ( + size(first.min_width, first.max_width), + size(first.min_height, first.max_height), + ); + codes_in_place(Arc::clone(gpu), first.profile, width, height).map_err(|e| e.to_string()) + } else { + Err("NVENC does not say it codes a frame without advancing its state".to_owned()) + }; + if let Err(why) = checked { + log::info!( + "hardware video: {ENCODE_NAME} codes no frame of {codec:#x} in place: {why}" + ); + for support in supports.iter_mut().filter(|s| of_codec(s)) { + support.in_place = false; + } + } + } + supports +} + /// What an encode of `codec`, an entry [`encode_caps_of`] made, takes beyond it: CQP, and CBR -/// and VBR where NVENC lists them for each of its profiles, and no B-frames (module doc); all -/// zero for a decode entry. +/// and VBR where NVENC lists them for each of its profiles, no B-frames, and frames coded in +/// place where every profile codes them ([`checked_in_place`]; module doc); all zero for a +/// decode entry. pub(super) fn encode_caps( codec: &RgfxVideoCodecCaps, supports: &[EncodeProfileSupport], @@ -162,10 +207,15 @@ pub(super) fn encode_caps( if profiles().all(|s| s.variable_bit_rate) { rate_controls |= 1 << RGFX_VIDEO_RATE_VBR; } + let in_place = profiles().next().is_some() && profiles().all(|s| s.in_place); RgfxVideoEncodeCaps { rate_controls, max_b_frames: 0, - flags: 0, + flags: if in_place { + RGFX_VIDEO_ENCODE_CAP_IN_PLACE + } else { + 0 + }, reserved_0c: 0, } } @@ -302,6 +352,8 @@ struct State { settings: Option, /// Whether the next frame is made an IDR picture: the last one did not fit. key_next: bool, + /// Whether its encoders code frames in place (module doc). + in_place: bool, } impl State { @@ -317,7 +369,12 @@ impl State { _ => { let params = params_of(self.codec, settings)?; self.encoder = None; - self.encoder = Some(NvencEncoder::new(Arc::clone(&self.gpu), ¶ms)?); + let gpu = Arc::clone(&self.gpu); + self.encoder = Some(if self.in_place { + NvencEncoder::new_in_place(gpu, ¶ms)? + } else { + NvencEncoder::new(gpu, ¶ms)? + }); } } self.settings = Some(*settings); @@ -355,8 +412,7 @@ impl Fills

{ encoder: &mut NvencEncoder, [luma, chroma]: [&OutputPlane

; 2], size: (u32, u32), - index: u64, - force_idr: bool, + (index, force_idr, in_place): (u64, bool, bool), ) -> Result>, BackendError> { let declined = match &mut self.filler { Ok(filler) => { @@ -373,7 +429,12 @@ impl Fills

{ index, force_idr, }; - match encoder.encode_device(&frame) { + let encoded = if in_place { + encoder.encode_device_in_place(&frame) + } else { + encoder.encode_device(&frame) + }; + match encoded { 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. @@ -406,6 +467,7 @@ pub(super) struct NvencHostEncoder { /// What writes its frames into memory NVENC reads, on the GPU (module doc). fills: Arc>>, /// The profiles NVENC encodes of the codec, which [`HostEncoder::check`] holds settings to. + /// They code frames in place where `encode` says so. profiles: Vec, /// The sizes the codec's entry gives. min_size: [u32; 2], @@ -433,6 +495,7 @@ impl NvencHostEncoder

{ encoder: None, settings: None, key_next: false, + in_place: encode.flags & RGFX_VIDEO_ENCODE_CAP_IN_PLACE != 0, })), fills: Arc::new(Mutex::new(Fills { filler, @@ -506,12 +569,46 @@ impl HostEncodedFrame

for NvencFrame

{ out: &mut [u8], ) -> Result { let mut state = self.state.lock(); + let encoded = self.encode_into(&mut state, source, out); + // The guest dropped the frame this one was to replace: the next frame is coded from + // NVENC's state before it. + if self.frame.in_place + && encoded.is_err() + && let Some(encoder) = state.encoder.as_mut() + { + encoder.drop_last(); + } + encoded + } +} + +impl NvencFrame

{ + /// [`HostEncodedFrame::finish`] on the locked `state`. A new frame first takes the last one + /// as the stream's, before its settings change NVENC's (module doc); a frame coded in place + /// replaces the last one, which may be one that did not fit. + fn encode_into( + &self, + state: &mut State, + source: &mut FrameSource<'_, P>, + out: &mut [u8], + ) -> Result { + let in_place = self.frame.in_place; + if !in_place + && let Some(encoder) = state.encoder.as_mut() + && let Err(e) = encoder.keep() + { + log::warn!( + kind:% = e; + "hardware video: {ENCODE_NAME}: NVENC's state after a frame: {e}; the next frame \ + is an IDR picture" + ); + } 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 force_idr = self.frame.force_keyframe || (state.key_next && !in_place); + if let Some(packets) = self.filled(state, source, force_idr)? { + return finish_packets(state, packets, out); } let source = source.host()?; let encoder = state.encoder.as_mut().ok_or("an encode with no settings")?; @@ -521,12 +618,14 @@ impl HostEncodedFrame

for NvencFrame

{ index: self.frame.frame_index, force_idr, }; - let packets = encoder.encode(&raw)?; - finish_packets(&mut state, packets, out) + let packets = if in_place { + encoder.encode_in_place(&raw)? + } else { + encoder.encode(&raw)? + }; + finish_packets(state, packets, out) } -} -impl NvencFrame

{ /// 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 @@ -542,8 +641,7 @@ impl NvencFrame

{ encoder, source.planes(), source.size(), - self.frame.frame_index, - force_idr, + (self.frame.frame_index, force_idr, self.frame.in_place), ) } } diff --git a/crates/reims-vgpu/src/graphics/nvidia/encode/guest.rs b/crates/reims-vgpu/src/graphics/nvidia/encode/guest.rs index c5d098e38..0db68e64a 100644 --- a/crates/reims-vgpu/src/graphics/nvidia/encode/guest.rs +++ b/crates/reims-vgpu/src/graphics/nvidia/encode/guest.rs @@ -294,7 +294,12 @@ impl NvGuestEncoder

{ let sample = u32::try_from(sample).unwrap_or(0); let [luma, chroma] = buffer_planes(buffer, &planes, size, sample); let filled = (self.fills) - .encode_filled(&mut self.encoder, [&luma, &chroma], size, index, force_idr) + .encode_filled( + &mut self.encoder, + [&luma, &chroma], + size, + (index, force_idr, false), + ) .map_err(|error| VideoError::Malfunction(error.to_string()))?; if let Some(bitstreams) = filled { return Ok(bitstreams); diff --git a/crates/reims-vgpu/src/graphics/nvidia/encode/guest/tests.rs b/crates/reims-vgpu/src/graphics/nvidia/encode/guest/tests.rs index 9b5260ea7..b61bc1e02 100644 --- a/crates/reims-vgpu/src/graphics/nvidia/encode/guest/tests.rs +++ b/crates/reims-vgpu/src/graphics/nvidia/encode/guest/tests.rs @@ -27,6 +27,7 @@ fn support(profile: EncodeProfile, max_width: u32, max_height: u32) -> EncodePro constant_bit_rate: true, variable_bit_rate: true, max_references: 7, + in_place: false, } } diff --git a/crates/reims-vgpu/src/graphics/nvidia/encode/tests.rs b/crates/reims-vgpu/src/graphics/nvidia/encode/tests.rs index 7e1a52796..e8d09a608 100644 --- a/crates/reims-vgpu/src/graphics/nvidia/encode/tests.rs +++ b/crates/reims-vgpu/src/graphics/nvidia/encode/tests.rs @@ -39,8 +39,8 @@ fn settings(codec: u32, profile: u32, width: u32, height: u32) -> RgfxVideoEncod } } -/// NVENC's answer for `profile`: `min` to `max` pictures, CBR and VBR as given, and several -/// references. +/// NVENC's answer for `profile`: `min` to `max` pictures, CBR and VBR as given, several +/// references, and frames coded without advancing its state. fn support(profile: EncodeProfile, min: u32, max: u32, cbr: bool) -> EncodeProfileSupport { EncodeProfileSupport { profile, @@ -52,9 +52,51 @@ fn support(profile: EncodeProfile, min: u32, max: u32, cbr: bool) -> EncodeProfi constant_bit_rate: cbr, variable_bit_rate: true, max_references: 7, + in_place: true, } } +/// An encode entry codes frames in place where every profile of its codec does: where NVENC +/// refuses it for one (its caps, or the session `checked_in_place` makes), the codec's flag is +/// off, and the device answers no frame coded in place for it. +#[test] +fn frames_are_coded_in_place_where_every_profile_of_the_codec_is() { + let mut main10 = support(EncodeProfile::HevcMain10, 129, 8192, true); + main10.in_place = false; + let supports = [ + support(EncodeProfile::H264Main, 145, 4096, true), + support(EncodeProfile::H264High, 145, 4096, true), + support(EncodeProfile::HevcMain, 129, 8192, true), + main10, + ]; + let entries = encode_caps_of(&supports); + let flags = |supports: &[EncodeProfileSupport]| -> Vec { + (entries.iter()) + .map(|e| encode_caps(e, supports).flags) + .collect() + }; + assert_eq!(flags(&supports), [RGFX_VIDEO_ENCODE_CAP_IN_PLACE, 0]); + let mut all = supports; + all[3].in_place = true; + assert_eq!( + flags(&all), + [ + RGFX_VIDEO_ENCODE_CAP_IN_PLACE, + RGFX_VIDEO_ENCODE_CAP_IN_PLACE + ] + ); + let none = all.map(|s| EncodeProfileSupport { + in_place: false, + ..s + }); + assert_eq!(flags(&none), [0, 0]); + let decode = RgfxVideoCodecCaps { + direction: RGFX_VIDEO_DECODE, + ..entries[0] + }; + assert_eq!(encode_caps(&decode, &all).flags, 0); +} + /// An entry for each codec: its profiles, its formats, the least of their sizes and /// references, and the codec's top level. #[test] @@ -505,6 +547,7 @@ fn each_profile_encodes_through_a_session_and_decodes_back_on_nvdec() { result_offset: 0, frame_index: n, force_keyframe: n == 10, + in_place: false, settings: frame_settings, }; let value = session @@ -588,6 +631,272 @@ fn each_profile_encodes_through_a_session_and_decodes_back_on_nvdec() { } } +/// On the NVIDIA host, the device-start check of frames coded in place (`checked_in_place`) leaves +/// no NVENC session open on its GPU once it is done (where `nvidia-smi` answers the GPU's encoder +/// sessions), and says, five times over, how long it took. The count is the GPU's, every +/// process's sessions on it, so the test runs alone (`.config/nextest.toml`). +#[test] +#[ignore = "needs an NVIDIA GPU, and a measurement: run it alone on the NVIDIA host"] +#[allow(clippy::disallowed_methods)] // a measurement: the wall clock's time +fn the_in_place_check_leaves_no_nvenc_session() { + let gpu = Arc::new(Gpu::open(&GpuSelector::First).expect("an NVIDIA GPU")); + let supports = encode_profiles(Arc::clone(&gpu)).expect("NVENC's profiles"); + let mut took = Vec::new(); + for _ in 0..5 { + let start = std::time::Instant::now(); + let checked = checked_in_place(&gpu, supports.clone()); + took.push(start.elapsed().as_secs_f64() * 1000.0); + assert!(checked.iter().all(|s| s.in_place), "{checked:?}"); + } + took.sort_by(f64::total_cmp); + eprintln!( + "the in-place check took {took:.1?} ms, median {:.1} ms", + took[2] + ); + let sessions = std::process::Command::new("nvidia-smi") + .args([ + "--query-gpu=pci.bus_id,encoder.stats.sessionCount", + "--format=csv,noheader", + ]) + .output(); + match sessions { + Ok(out) => { + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + eprintln!("NVENC sessions after it, by GPU: {}", text.trim()); + // CUDA's bus ID has a 4-digit domain and nvidia-smi's an 8-digit one: the bus, + // device and function after it name the GPU. + let ours = |id: &str| { + id.split_once(':') + .map(|(_, rest)| rest.trim().to_ascii_lowercase()) + }; + let bus = ours(&gpu.info().pci_bus_id); + let line = text + .lines() + .find(|line| ours(line.split(',').next().unwrap_or_default()) == bus) + .expect("nvidia-smi lists the GPU opened"); + let count = line.rsplit(',').next().map(str::trim); + assert_eq!(count, Some("0"), "{line}"); + } + Err(e) => eprintln!("no nvidia-smi to count NVENC sessions: {e}"), + } +} + +/// On the NVIDIA host, each codec and profile NVENC encodes, which codes frames in place there +/// (`checked_in_place`; the test fails where it does not), through an encode session of the +/// arm's, 1280x720 at a constant QP: frames coded again in place of the last at a higher QP, as +/// AppleGVA's limiter codes them (the IDR picture once more, frame 5 twice and frame 9 once), +/// each try its frame's, of its picture type. The last try of each frame makes the stream, +/// which decodes back on NVDEC, every frame to a picture whose planes reach [`LEAST_PSNR`] +/// against it. A frame coded in place of another frame is refused, the guest drops the frame it +/// was to replace, and the next frame is coded from NVENC's state before that one. +#[test] +#[ignore = "needs an NVIDIA GPU: run on the NVIDIA host"] +fn frames_coded_in_place_decode_back_on_nvdec() { + let gpu = Arc::new(Gpu::open(&GpuSelector::First).expect("an NVIDIA GPU")); + let runtime: Arc = StdRuntime::shared(); + let supports = checked_in_place( + &gpu, + encode_profiles(Arc::clone(&gpu)).expect("NVENC's profiles"), + ); + let entries = encode_caps_of(&supports); + let p = FakePlatform::new(); + let (width, height) = (1280u32, 720u32); + // (frame, in place, QP) of each try, and the frame refused in place of frame 11. + let tries: Vec<(u64, bool, u32)> = vec![ + (0, false, 22), + (0, true, 24), + (1, false, 22), + (2, false, 22), + (3, false, 22), + (4, false, 22), + (5, false, 22), + (5, true, 24), + (5, true, 26), + (6, false, 22), + (7, false, 22), + (8, false, 22), + (9, false, 22), + (9, true, 24), + (10, false, 22), + (11, false, 22), + (12, true, 22), + (12, false, 22), + (13, false, 22), + ]; + for entry in &entries { + let caps = encode_caps(entry, &supports); + assert_ne!(caps.flags & RGFX_VIDEO_ENCODE_CAP_IN_PLACE, 0, "{entry:?}"); + for bit in (0..32) + .map(|b| 1u32 << b) + .filter(|b| entry.profiles & b != 0) + { + let what = format!("codec {} profile {bit:#x}", entry.codec); + let s = settings(entry.codec, bit, width, height); + let encoder = NvencHostEncoder::::new( + &gpu, + entry.codec, + &supports, + entry, + &caps, + Err("the fake's buffers export nothing".to_owned()), + ); + let session = HostEncodeSession::::new( + &p.device(), + entry.codec, + "NVENC", + Box::new(encoder), + ) + .expect("a session"); + let event = match session.event() { + EventRef::Shared(event) => event, + EventRef::Event(_) => panic!("a plain event"), + }; + let wide = s.format == RGFX_VIDEO_FORMAT_P010; + let row = width as usize * if wide { 2 } else { 1 }; + let pitch = row.next_multiple_of(256); + let chroma_at = pitch * height as usize; + let len = (chroma_at + pitch * height as usize / 2) as u64; + let buffer = |len| { + (p.device() + .new_buffer_of_length(OnFault::Return, len, SHARED)) + .expect("no raise") + .expect("a buffer") + }; + let source = buffer(len); + let (bitstream, result) = (buffer(4 << 20), buffer(64)); + let plane = |offset, rows| VideoPlane { + buffer: &source, + offset, + bytes_per_row: pitch as u64, + row_bytes: row as u64, + width: u64::from(width), + height: rows, + cached: false, + pages: None, + cache: None, + rows_room: None, + #[cfg(unix)] + surface: None, + }; + let mut qp = None; + // The last try of each frame: its access unit. + let mut stream: Vec<(u64, Vec)> = Vec::new(); + for (n, &(index, in_place, at)) in tries.iter().enumerate() { + write_frame(&source, &s, pitch, chroma_at, index as usize); + let changed = qp != Some(at); + qp = Some(at); + let encode = VideoEncode { + luma: plane(0, u64::from(height)), + chroma: plane(chroma_at as u64, u64::from(height / 2)), + bitstream: &bitstream, + bitstream_offset: 0, + bitstream_capacity: 4 << 20, + result: &result, + result_offset: 0, + frame_index: index, + force_keyframe: false, + in_place, + settings: changed.then_some(RgfxVideoEncodeSettings { + qp_i: at, + qp_p: at, + ..s + }), + }; + let value = session + .encode(&encode) + .expect("an encode the session takes"); + assert!( + event.wait_until_signaled_value(value, 10_000), + "{what} try {n}" + ); + // SAFETY: the fake's 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::(), 32), + std::slice::from_raw_parts(bitstream.contents().as_ptr::(), 4 << 20), + ) + }; + let r = RgfxVideoEncodeResult::read_from_bytes(result_bytes).expect("a result"); + let what = format!("{what} try {n}: {r:?}"); + if index == 12 && in_place { + // Refused: the guest has dropped frame 11, which it asked to replace, and + // frame 12 is coded from NVENC's state before it. + assert_ne!(r.status, RGFX_VIDEO_ENCODE_OK, "{what}"); + assert_eq!(stream.pop().map(|(index, _)| index), Some(11), "{what}"); + continue; + } + assert_eq!(r.status, RGFX_VIDEO_ENCODE_OK, "{what}"); + assert_eq!(r.frame_index, index, "{what}"); + let key = index == 0; + assert_eq!( + r.picture_type, + if key { + RGFX_VIDEO_PICTURE_I + } else { + RGFX_VIDEO_PICTURE_P + }, + "{what}" + ); + let au = au[..r.bitstream_size as usize].to_vec(); + if in_place { + let last = stream.last_mut().expect("a frame before"); + assert_eq!(last.0, index, "{what}"); + last.1 = au; + } else { + stream.push((index, au)); + } + } + drop(session); + assert_eq!(stream.len(), 13, "{what}"); + let mut decoder = AnnexBDecoder::new( + &gpu, + if entry.codec == RGFX_VIDEO_CODEC_H264 { + AnnexBCodec::H264 + } else { + AnnexBCodec::Hevc + }, + &runtime, + ); + let sets = parameter_set_types(entry.codec); + let mut parameter_sets = Vec::new(); + for (_, unit) in nal_units(entry.codec, &stream[0].1) + .iter() + .filter(|(t, _)| sets.contains(t)) + { + parameter_sets.extend_from_slice(&START_CODE); + parameter_sets.extend_from_slice(unit); + } + decoder + .parameter_sets(¶meter_sets) + .expect("the parameter sets"); + let mut least = f64::INFINITY; + for (index, au) in &stream { + let picture = (decoder.decode(au)).expect("a decode").expect("a picture"); + let read = picture.read_back((width, height)).expect("a read back"); + for (plane, read) in read.planes().iter().enumerate() { + let rows = read.rows as usize; + let db = psnr( + read.bytes, + read.bytes_per_row, + plane, + *index as usize, + width as usize, + rows, + wide, + ); + least = least.min(db); + assert!( + db >= LEAST_PSNR, + "{what} frame {index}: plane {plane} at {db:.1} dB" + ); + } + } + eprintln!("{what}: the least PSNR of a plane {least:.1} dB"); + } + } +} + /// 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 { @@ -735,6 +1044,7 @@ fn frames_filled_by_the_gpu_encode_as_uploaded( result_offset: 0, frame_index: n, force_keyframe: n == 6, + in_place: false, settings: (n == 0).then_some(s), }; let value = session diff --git a/crates/reims-vgpu/src/graphics/vaapi/encode.rs b/crates/reims-vgpu/src/graphics/vaapi/encode.rs index b34d3875e..1df88e2fd 100644 --- a/crates/reims-vgpu/src/graphics/vaapi/encode.rs +++ b/crates/reims-vgpu/src/graphics/vaapi/encode.rs @@ -7,7 +7,11 @@ //! it encodes a profile (the VA crate's `encoder_support`), with those profiles, the sizes their //! configs and surfaces give, NV12 sources (and P010 for HEVC Main 10), and the references //! their configs take. Its rate controls ([`encode_caps`]) are those `VAConfigAttribRateControl` -//! lists of CQP, CBR and VBR, and no B-frames: the encoder keeps frames in display order. +//! lists of CQP, CBR and VBR, and no B-frames: the encoder keeps frames in display order. It +//! codes a frame in place of the last one (`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`): the VA crate's +//! encoder holds its last picture back from its stream until the next frame, and codes the +//! frame again in its place (`VideoEncoder::encode_in_place`). A frame coded in place that +//! fails, or is refused, starts the stream again: the next frame is an IDR picture. //! - **The settings** ([`settings_of`]) map onto the VA crate's: the profile, size and colour; a //! VBR with no peak peaks at 1.05 times its average; `quality` 0 to 100 onto `VAConfigAttribEncQualityRange`'s levels, the fastest to //! 1, the best. A change of what makes a new sequence makes a new encoder, whose first access @@ -49,9 +53,10 @@ use reims_vgpu_graphics::ops::video::{ RGFX_VIDEO_RATE_CQP, RGFX_VIDEO_RATE_VBR, RgfxVideoEncodeSettings, }; use reims_vgpu_graphics::wire::{ - RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_ENCODE, RGFX_VIDEO_FORMAT_NV12, - RGFX_VIDEO_FORMAT_P010, RGFX_VIDEO_H264_BASELINE, RGFX_VIDEO_H264_HIGH, RGFX_VIDEO_H264_MAIN, - RGFX_VIDEO_HEVC_MAIN, RGFX_VIDEO_HEVC_MAIN_10, RgfxVideoCodecCaps, RgfxVideoEncodeCaps, + RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_ENCODE, + RGFX_VIDEO_ENCODE_CAP_IN_PLACE, RGFX_VIDEO_FORMAT_NV12, RGFX_VIDEO_FORMAT_P010, + RGFX_VIDEO_H264_BASELINE, RGFX_VIDEO_H264_HIGH, RGFX_VIDEO_H264_MAIN, RGFX_VIDEO_HEVC_MAIN, + RGFX_VIDEO_HEVC_MAIN_10, RgfxVideoCodecCaps, RgfxVideoEncodeCaps, }; use reims_vgpu_video::codec::encode::{ Coded, ColourDescription, EncoderSettings, Entropy, FailedSample, FrameRate, FrameType, @@ -173,8 +178,8 @@ pub(super) fn encode_caps_of( } /// What an encode of `codec`, an entry [`encode_caps_of`] made, takes beyond it: the rate -/// controls the configs of its profiles list, and no B-frames (module doc); all zero for a decode -/// entry. +/// controls the configs of its profiles list, no B-frames, and frames coded in place (module +/// doc); all zero for a decode entry. pub(super) fn encode_caps( codec: &RgfxVideoCodecCaps, supports: &[EncoderSupport], @@ -198,7 +203,7 @@ pub(super) fn encode_caps( RgfxVideoEncodeCaps { rate_controls, max_b_frames: 0, - flags: 0, + flags: RGFX_VIDEO_ENCODE_CAP_IN_PLACE, reserved_0c: 0, } } @@ -548,20 +553,43 @@ impl HostEncodedFrame

for VaFrame

{ out: &mut [u8], ) -> Result { let mut state = self.state.lock(); - if let Some(settings) = &self.frame.settings { - state.apply(settings)?; - } - let input = self.times(&state)?; - if let Some(encoded) = self.filled(&mut state, &input, source, out)? { - return Ok(encoded); - } - self.fills.lock().uploaded += 1; - let host = source.host()?; - encode_host(&mut state, &input, &host, out) + let encoded = self.encode_into(&mut state, source, out); + self.failed_in_place(&mut state, &encoded); + encoded } } impl VaFrame

{ + /// [`HostEncodedFrame::finish`] on the locked `state`. + fn encode_into( + &self, + state: &mut State, + source: &mut FrameSource<'_, P>, + out: &mut [u8], + ) -> Result { + if let Some(settings) = &self.frame.settings { + state.apply(settings)?; + } + let input = self.times(state)?; + if let Some(encoded) = self.filled(state, &input, source, out)? { + return Ok(encoded); + } + self.fills.lock().uploaded += 1; + let host = source.host()?; + encode_host(state, &input, &host, out, self.frame.in_place) + } + + /// Where the frame was to be coded in place and was not (`encoded`), the guest has dropped + /// the frame it replaces: the stream starts again, its next frame an IDR picture. + fn failed_in_place(&self, state: &mut State, encoded: &Result) { + if self.frame.in_place + && encoded.is_err() + && let Some(encoder) = state.encoder.as_mut() + { + encoder.start_again(); + } + } + /// The frame encoded from `source`'s planes where they lie, written by the GPU into an input /// of the encoder's (module doc), into `out`; `None` where the write was declined, nothing /// written, which is said once a session. `Err` where the encode failed, or the write @@ -578,7 +606,11 @@ impl VaFrame

{ let Some(target) = self.fills.lock().fill(encoder, luma, chroma)? else { return Ok(None); }; - let coded = encoder.encode_target(&target, input)?; + let coded = if self.frame.in_place { + encoder.encode_target_in_place(&target, input)? + } else { + encoder.encode_target(&target, input)? + }; finish_coded(state, coded, out).map(Some) } @@ -591,14 +623,19 @@ impl VaFrame

{ out: &mut [u8], ) -> Result { let mut state = self.state.lock(); - if let Some(settings) = &self.frame.settings { - state.apply(settings)?; - } - let input = self.times(&state)?; - encode_host(&mut state, &input, source, out) + let encoded = (|| { + if let Some(settings) = &self.frame.settings { + state.apply(settings)?; + } + let input = self.times(&state)?; + encode_host(&mut state, &input, source, out, self.frame.in_place) + })(); + self.failed_in_place(&mut state, &encoded); + encoded } - /// The frame's times, key-frame demand and tag as the encoder takes them, with no planes. + /// The frame's times, key-frame demand and tag as the encoder takes them, with no planes. A + /// frame coded in place replaces the last one, which may be one that did not fit. fn times(&self, state: &State) -> Result, BackendError> { let encoder = state.encoder.as_ref().ok_or("an encode with no settings")?; let duration = i64::from(encoder.settings().frame_rate.denominator); @@ -611,26 +648,31 @@ impl VaFrame

{ planes: [none, none], pts: index.saturating_mul(duration), duration, - force_key_frame: self.frame.force_keyframe || state.key_next, + force_key_frame: self.frame.force_keyframe || (state.key_next && !self.frame.in_place), id: self.frame.frame_index, }) } } /// Encodes the frame of `input`'s times from `source`'s host bytes, which the encoder uploads, -/// into `out`. +/// into `out`: in place of the last one where `in_place`. fn encode_host( state: &mut State, input: &InputFrame<'_>, source: &EncodeSource, out: &mut [u8], + in_place: bool, ) -> Result { let encoder = state.encoder.as_mut().ok_or("an encode with no settings")?; let input = InputFrame { planes: [plane(&source.luma)?, plane(&source.chroma)?], ..*input }; - let coded = encoder.encode(&input)?; + let coded = if in_place { + encoder.encode_in_place(&input)? + } else { + encoder.encode(&input)? + }; finish_coded(state, coded, out) } diff --git a/crates/reims-vgpu/src/graphics/vaapi/encode/tests.rs b/crates/reims-vgpu/src/graphics/vaapi/encode/tests.rs index 3626e4803..a099f59bb 100644 --- a/crates/reims-vgpu/src/graphics/vaapi/encode/tests.rs +++ b/crates/reims-vgpu/src/graphics/vaapi/encode/tests.rs @@ -296,7 +296,8 @@ fn the_va_settings_of_the_wire_s() { } /// The rate controls an encode entry lists: the wire's bit of each `VA_RC_*` its profiles' -/// configs list; a decode entry lists none. +/// configs list; and it codes frames in place, H.264's and HEVC's alike. A decode entry lists +/// none of it. #[test] fn an_encode_entry_lists_its_configs_rate_controls() { let entry = RgfxVideoCodecCaps { @@ -304,7 +305,16 @@ fn an_encode_entry_lists_its_configs_rate_controls() { direction: RGFX_VIDEO_ENCODE, ..RgfxVideoCodecCaps::default() }; - assert_eq!(encode_caps(&entry, &[]), RgfxVideoEncodeCaps::default()); + let in_place = RgfxVideoEncodeCaps { + flags: RGFX_VIDEO_ENCODE_CAP_IN_PLACE, + ..RgfxVideoEncodeCaps::default() + }; + assert_eq!(encode_caps(&entry, &[]), in_place); + let hevc = RgfxVideoCodecCaps { + codec: RGFX_VIDEO_CODEC_HEVC, + ..entry + }; + assert_eq!(encode_caps(&hevc, &[]), in_place); let decode = RgfxVideoCodecCaps { direction: RGFX_VIDEO_DECODE, ..entry @@ -418,6 +428,7 @@ fn each_profile_encodes_on_the_driver_and_decodes_back() { settings: (index == 0).then_some(s), frame_index: index, force_keyframe: false, + in_place: false, }; let frame = encoder.frame(frame); let (luma, chroma) = picture(&s, index); @@ -495,6 +506,177 @@ fn each_profile_encodes_on_the_driver_and_decodes_back() { } } +/// Each frame of `frames`, `(index, in_place, qp)`, through an encoder of `codec`'s `entry` +/// on the driver, from the host bytes of [`picture`] `index`, at constant QP `qp` (settings +/// sent where it changes): each one's [`Encoded`], and its access unit where it was written. +fn encode_frames( + display: &Display, + supports: &Arc<[EncoderSupport]>, + entry: &RgfxVideoCodecCaps, + s: &RgfxVideoEncodeSettings, + frames: &[(u64, bool, u32)], +) -> Vec), BackendError>> { + let rates = encode_caps(entry, supports); + let encoder = VaEncoder::::new( + display, + entry.codec, + Arc::clone(supports), + entry, + &rates, + Err("the test copies none by the GPU".to_owned()), + ); + let mut qp = None; + let mut out = Vec::new(); + for &(index, in_place, at) in frames { + let settings = RgfxVideoEncodeSettings { + qp_i: at, + qp_p: at, + qp_b: at, + ..*s + }; + let changed = qp != Some(at); + qp = Some(at); + let frame = EncodeFrame { + settings: changed.then_some(settings), + frame_index: index, + force_keyframe: false, + in_place, + }; + let frame = encoder.frame(frame); + let (luma, chroma) = picture(s, index); + let row = luma.len() / s.height as usize; + let source = EncodeSource { + luma: SourcePlane { + at: luma.as_ptr(), + bytes_per_row: row, + row_bytes: row, + rows: s.height as usize, + }, + chroma: SourcePlane { + at: chroma.as_ptr(), + bytes_per_row: row, + row_bytes: row, + rows: s.height as usize / 2, + }, + width: s.width, + height: s.height, + }; + let mut bytes = vec![0u8; 1 << 20]; + let encoded = frame.finish_from_host(&source, &mut bytes); + out.push(encoded.map(|e| { + bytes.truncate(e.size as usize); + (e, bytes) + })); + } + out +} + +/// On the driver, each codec and profile it encodes, frames coded again in place of the last +/// (as AppleGVA's limiter codes a frame again at a higher QP): the key frame twice, frame 2 +/// three times and frame 4 once more, then frames to 7. Each try is its frame's, of its picture +/// type; the last try of each frame makes the stream, which the driver's own decoder decodes +/// whole, every frame of it. A frame coded in place with none held is refused, and the frame +/// after it is a keyframe. +#[test] +#[ignore = "needs a VA-API GPU: run on the VA-API host"] +fn frames_coded_in_place_decode_back_in_their_places() { + let display = display(); + let supports: Arc<[EncoderSupport]> = encoder_support(&display).into(); + let caps = display.capabilities().unwrap(); + let entries = encode_caps_of(&supports, &caps); + assert!( + !entries.is_empty(), + "the driver encodes neither H.264 nor HEVC" + ); + let frames = [ + (0, false, 26), + (0, true, 29), + (1, false, 26), + (2, false, 26), + (2, true, 29), + (2, true, 32), + (3, false, 26), + (4, false, 26), + (4, true, 29), + (5, false, 26), + (6, false, 26), + (7, false, 26), + ]; + for entry in &entries { + assert_ne!( + encode_caps(entry, &supports).flags & RGFX_VIDEO_ENCODE_CAP_IN_PLACE, + 0 + ); + for bit in (0..32) + .map(|b| 1u32 << b) + .filter(|b| entry.profiles & b != 0) + { + let s = settings(entry.codec, bit); + let what = format!("codec {} profile {bit:#x}", entry.codec); + let coded = encode_frames(&display, &supports, entry, &s, &frames); + let mut units: Vec> = Vec::new(); + let mut last = None; + for (n, (try_, &(index, in_place, _))) in coded.iter().zip(&frames).enumerate() { + let (encoded, au) = try_ + .as_ref() + .unwrap_or_else(|e| panic!("{what} try {n}: {e}")); + assert_eq!(encoded.frame_index, index, "{what} try {n}"); + assert!(!encoded.overflow, "{what} try {n}"); + let key = index == 0; + assert_eq!(encoded.keyframe, key, "{what} try {n}"); + assert_eq!( + encoded.picture_type, + if key { + RGFX_VIDEO_PICTURE_I + } else { + RGFX_VIDEO_PICTURE_P + }, + "{what} try {n}" + ); + if in_place { + assert_eq!(last, Some(index), "{what} try {n}"); + *units.last_mut().unwrap() = au.clone(); + } else { + units.push(au.clone()); + } + last = Some(index); + } + assert_eq!(units.len(), 8, "{what}"); + let mut decoded = 0; + if entry.codec == RGFX_VIDEO_CODEC_H264 { + let mut decoder = H264Decoder::new_annex_b(&display); + for (id, au) in units.iter().enumerate() { + decoded += decoder.decode(au, id as u64).unwrap().len(); + } + decoded += decoder.flush().unwrap().len(); + } else { + let mut decoder = HevcDecoder::new_annex_b(&display); + for (id, au) in units.iter().enumerate() { + decoded += decoder.decode(au, id as u64).unwrap().len(); + } + decoded += decoder.flush().unwrap().len(); + } + assert_eq!(decoded, 8, "{what}"); + // Refused: in place of none, then a new frame is a keyframe. + let refused = encode_frames( + &display, + &supports, + entry, + &s, + &[ + (0, false, 26), + (1, false, 26), + (5, true, 26), + (2, false, 26), + ], + ); + assert!(refused[2].is_err(), "{what}"); + let (encoded, _) = refused[3].as_ref().unwrap(); + assert!(encoded.keyframe, "{what}"); + } + } +} + /// A frame the runtime device's GPU writes into an input of the encoder's (`fill`'s filler) /// encodes as the same frame uploaded by the CPU, byte for byte: on the driver of the rt device's /// GPU, which the arm runs on (`video_choice::tested_gpu::check_rt`), for each codec and profile diff --git a/crates/reims-vgpu/src/graphics/video_host/encode.rs b/crates/reims-vgpu/src/graphics/video_host/encode.rs index cbca2eda5..06d9d36a8 100644 --- a/crates/reims-vgpu/src/graphics/video_host/encode.rs +++ b/crates/reims-vgpu/src/graphics/video_host/encode.rs @@ -67,6 +67,10 @@ pub(crate) struct EncodeFrame { pub(crate) frame_index: u64, /// Whether it must be a keyframe. pub(crate) force_keyframe: bool, + /// Whether it is coded in place of the last frame taken, which the guest drops + /// (`RGFX_VIDEO_ENCODE_IN_PLACE`): from the references that frame was coded from. A backend + /// that cannot (no frame held, B pictures) fails the frame's encode. + pub(crate) in_place: bool, } /// A backend's encoder of one codec, whose session is a [`HostEncodeSession`]. Its calls run on @@ -501,6 +505,7 @@ impl GraphicsVideoSession

for HostEncodeSession

{ settings: encode.settings, frame_index: encode.frame_index, force_keyframe: encode.force_keyframe, + in_place: encode.in_place, }; let frame = state.encoder.encode(frame).map_err(encode_fault)?; let value = state.value + 1; diff --git a/crates/reims-vgpu/src/graphics/video_host/encode/tests.rs b/crates/reims-vgpu/src/graphics/video_host/encode/tests.rs index 57a50ac3b..4f9d5ee93 100644 --- a/crates/reims-vgpu/src/graphics/video_host/encode/tests.rs +++ b/crates/reims-vgpu/src/graphics/video_host/encode/tests.rs @@ -57,9 +57,9 @@ fn settings() -> RgfxVideoEncodeSettings { /// What the encoder and its frames saw, in order. #[derive(Debug, Clone, PartialEq, Eq)] enum Seen { - /// A frame taken: its index, whether it carried settings, and whether it was forced a - /// keyframe. - Took(u64, bool, bool), + /// A frame taken: its index, whether it carried settings, whether it was forced a keyframe, + /// and whether it is coded in place of the last. + Took(u64, bool, bool, bool), /// A frame finished: its index, its source's first luma byte and chroma byte, and the /// capacity it had. Finished(u64, u8, u8, usize), @@ -96,6 +96,7 @@ impl HostEncoder

for Encoder { frame.frame_index, frame.settings.is_some(), frame.force_keyframe, + frame.in_place, )); let answer = self.answers.pop_front().unwrap_or(Answer::Unit(10)); Ok(Box::new(Frame { @@ -199,6 +200,7 @@ fn encode<'a>( result_offset: 1024, frame_index: index, force_keyframe: false, + in_place: false, settings, } } @@ -241,7 +243,14 @@ fn an_encode_writes_its_access_unit_then_its_result_then_signals() { 1 ); assert_eq!(s.encode(&encode(&src, &second, 1, None)).unwrap(), 2); - assert!(event_of(&s).wait_until_signaled_value(2, 10_000)); + // Frame 1 again, in place of the last: the backend is told so. + let again = buffer(&p, 4096, SHARED); + let in_place = VideoEncode { + in_place: true, + ..encode(&src, &again, 1, None) + }; + assert_eq!(s.encode(&in_place).unwrap(), 3); + assert!(event_of(&s).wait_until_signaled_value(3, 10_000)); let b = bytes(&first); assert!(b[..256].iter().all(|&x| x == UNTOUCHED)); assert!(b[256..276].iter().all(|&x| x == 0)); @@ -270,13 +279,18 @@ fn an_encode_writes_its_access_unit_then_its_result_then_signals() { (log.lock().iter().cloned()).partition(|seen| matches!(seen, Seen::Took(..))); assert_eq!( took, - [Seen::Took(0, true, false), Seen::Took(1, false, false)] + [ + Seen::Took(0, true, false, false), + Seen::Took(1, false, false, false), + Seen::Took(1, false, false, true), + ] ); assert_eq!( finished, [ Seen::Finished(0, 0x11, 0x22, 512), Seen::Finished(1, 0x11, 0x22, 512), + Seen::Finished(1, 0x11, 0x22, 512), ] ); drop(s);