🐛 Code frames a guest sends in coding order at their places
What changes for the guest: both Linux arms now answer RGFX_VIDEO_ENCODE_CAP_REORDERED for H.264 and HEVC. A session whose settings carry RGFX_VIDEO_ENCODE_REORDERED has each frame coded as it comes, at its frame_index's place in display order. The arm makes a frame an IDR picture at the stream's first frame, a forced keyframe, the interval, or a place not past its IDR picture's. It makes a frame a reference P picture where its place is past every place since its IDR picture. Any other frame is a picture nothing predicts from: a B picture between the references either side of it where the profile has B slices, else a P picture. Each picture's order count is its place's (twice it for H.264), and the SPS says one frame may come out of display order, so a decoder shows the frames in their places. Before, every frame was coded in the order it came, and the stream showed each frame sent behind a later one after it. The VA crate's encoder plans such frames with CodingOrder (gop.rs, EncoderSettings::coding_order). NVENC's session plans them the same way with its picture type decision off, and sets each picture's type, order count and reference flag (EncodeParams::coding_order). Without the flag nothing changes. The tests that held the caps answer (in place alone) now expect the new flag too. Card tests cover both arms: on a radeonsi XTX, 30 frames in AppleGVA's order (0 2 1 4 3 ...) decode back with none out of order for H.264 Baseline, Main and High and HEVC Main and Main 10, where development shows every pair swapped. On an RTX 3090 they cover H.264 High and HEVC, and HEVC coded again in place in coding order. NVENC codes H.264 Baseline at POC type 2, which cannot place such a frame. No guest sends one, since Baseline has no B pictures; it is docs/video/bugs.md B103. The VideoToolbox arm, which serves arm64 guests, answers no such cap and is unchanged.
This commit is contained in:
1 parent
f81fcf163a
commit
db84a87a85
20 files changed
+1190
-100
No files matched your search
@@ -119,6 +119,7 @@ mod linux {
|
||||
buffer_milliseconds: 1000,
|
||||
gop_length: None,
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
level: None,
|
||||
cabac: None,
|
||||
full_range: false,
|
||||
|
||||
@@ -329,6 +329,13 @@ pub struct EncoderSettings {
|
||||
/// Consecutive B pictures between references when reordering is
|
||||
/// allowed: none for the encoder's choice.
|
||||
pub b_frames: Option<u32>,
|
||||
/// Whether frames come in the order they are coded, each at its own
|
||||
/// place in display order, their PTS that many durations from 0, as an
|
||||
/// encoder above this one plans its own B pictures and sends each
|
||||
/// reference before them (`gop`'s `CodingOrder`). Frames are not
|
||||
/// reordered then, whatever the settings above, and the SPS says one
|
||||
/// frame may come out of display order.
|
||||
pub coding_order: bool,
|
||||
/// The level as the bitstream numbers it (`level_idc`, or HEVC's
|
||||
/// `general_level_idc`); none to choose the lowest that fits.
|
||||
pub level: Option<u8>,
|
||||
@@ -364,6 +371,7 @@ impl EncoderSettings {
|
||||
allow_frame_reordering: true,
|
||||
max_frame_delay: None,
|
||||
b_frames: None,
|
||||
coding_order: false,
|
||||
level: None,
|
||||
entropy: None,
|
||||
quality_level: None,
|
||||
|
||||
@@ -6,6 +6,11 @@
|
||||
//! accelerator ([`Accelerator`]) uploads frames and runs the hardware;
|
||||
//! VA-API's is the VA-API backend's.
|
||||
//!
|
||||
//! Frames come in display order, or, where the settings say so
|
||||
//! ([`EncoderSettings::coding_order`]), in the order an encoder above this
|
||||
//! one codes them, each at its own place in display order, which
|
||||
//! [`super::gop`]'s `CodingOrder` plans as they come.
|
||||
//!
|
||||
//! 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
|
||||
@@ -16,7 +21,9 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::gop::{DecodeTimes, GopConfig, GopPlanner, Planned};
|
||||
use super::gop::{
|
||||
CODING_ORDER_REFERENCES, CodingOrder, DecodeTimes, GopConfig, GopPlanner, Planned,
|
||||
};
|
||||
use super::limit_rate::LimitRate;
|
||||
use super::record::Record;
|
||||
use super::{
|
||||
@@ -260,6 +267,8 @@ struct Pending<I> {
|
||||
#[derive(Clone, Copy)]
|
||||
struct SliceAt {
|
||||
frame_type: FrameType,
|
||||
/// Whether it is a reference.
|
||||
reference: bool,
|
||||
order: i32,
|
||||
frame_num: u32,
|
||||
idr_pic_id: u32,
|
||||
@@ -280,7 +289,13 @@ pub struct Encoder<A: Accelerator> {
|
||||
/// The configuration record, as the hardware's parameter sets make it.
|
||||
record: Record,
|
||||
planner: GopPlanner<Pending<A::Input>>,
|
||||
/// The planner of frames that come in coding order
|
||||
/// ([`EncoderSettings::coding_order`]), which then plans every frame.
|
||||
coding: Option<CodingOrder>,
|
||||
times: DecodeTimes,
|
||||
/// In coding order, the next sample's DTS: one duration after the
|
||||
/// last's, the first one duration before its PTS ([`Self::coded_dts`]).
|
||||
next_coded_dts: Option<i64>,
|
||||
dpb: VecDeque<ReferencePicture>,
|
||||
/// H.264's `frame_num` for the next picture, and the next IDR
|
||||
/// picture's `idr_pic_id`.
|
||||
@@ -311,6 +326,8 @@ struct Held {
|
||||
forward: Option<u64>,
|
||||
backward: Option<u64>,
|
||||
pts: i64,
|
||||
/// Its sample's DTS, which coding it again takes.
|
||||
dts: i64,
|
||||
before: Before,
|
||||
picture: Unkept,
|
||||
}
|
||||
@@ -508,10 +525,9 @@ impl<A: Accelerator> Encoder<A> {
|
||||
)
|
||||
},
|
||||
)?;
|
||||
let reorder = s.allow_frame_reordering
|
||||
&& s.profile.has_b_slices()
|
||||
&& limits.max_l1 >= 1
|
||||
&& limits.max_l0 >= 1;
|
||||
// Whether a picture may predict from references on both sides.
|
||||
let bidirectional = s.profile.has_b_slices() && limits.max_l1 >= 1 && limits.max_l0 >= 1;
|
||||
let reorder = s.allow_frame_reordering && bidirectional && !s.coding_order;
|
||||
let b_frames = if reorder {
|
||||
s.b_frames
|
||||
.unwrap_or(DEFAULT_B_FRAMES)
|
||||
@@ -520,9 +536,17 @@ impl<A: Accelerator> Encoder<A> {
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// Whether a frame may come out of display order: a B picture of
|
||||
// ours, or a frame in coding order sent after a later one.
|
||||
let reordered = b_frames > 0 || s.coding_order;
|
||||
// The references, and with the picture being coded, the pictures
|
||||
// the DPB holds.
|
||||
let (max_references, dpb_pictures): (u32, u32) = if b_frames > 0 { (2, 3) } else { (1, 2) };
|
||||
// the DPB holds: in coding order, CodingOrder's.
|
||||
let (max_references, dpb_pictures): (u32, u32) = if reordered {
|
||||
const _: () = assert!(CODING_ORDER_REFERENCES == 2);
|
||||
(2, 3)
|
||||
} else {
|
||||
(1, 2)
|
||||
};
|
||||
let peak = s.rate_control.peak_bits_per_second();
|
||||
let fps = s.frame_rate.as_f64();
|
||||
let intra_period = s.key_frame_interval.unwrap_or(0);
|
||||
@@ -571,7 +595,7 @@ impl<A: Accelerator> Encoder<A> {
|
||||
full_range: s.full_range,
|
||||
colour: s.colour,
|
||||
timing: timing(s.frame_rate, 2),
|
||||
max_num_reorder_frames: u32::from(b_frames > 0),
|
||||
max_num_reorder_frames: u32::from(reordered),
|
||||
max_dec_frame_buffering: max_references,
|
||||
},
|
||||
};
|
||||
@@ -623,7 +647,7 @@ impl<A: Accelerator> Encoder<A> {
|
||||
crop_right,
|
||||
crop_bottom,
|
||||
max_dec_pic_buffering_minus1: max_references,
|
||||
max_num_reorder_pics: u32::from(b_frames > 0),
|
||||
max_num_reorder_pics: u32::from(reordered),
|
||||
tools,
|
||||
vui: hevc::Vui {
|
||||
sample_aspect_ratio: s.sample_aspect_ratio,
|
||||
@@ -647,7 +671,9 @@ impl<A: Accelerator> Encoder<A> {
|
||||
settings: &settings,
|
||||
coded_width: coded_size.0,
|
||||
coded_height: coded_size.1,
|
||||
b_frames,
|
||||
// In coding order, the stream's B pictures run one at a time, and
|
||||
// nothing waits here.
|
||||
b_frames: if s.coding_order { 1 } else { b_frames },
|
||||
max_references,
|
||||
intra_period,
|
||||
picture_qp: limit_rate.is_some(),
|
||||
@@ -657,6 +683,13 @@ impl<A: Accelerator> Encoder<A> {
|
||||
key_frame_interval_duration: settings.key_frame_interval_duration,
|
||||
b_frames,
|
||||
});
|
||||
let coding = settings.coding_order.then(|| {
|
||||
CodingOrder::new(
|
||||
settings.key_frame_interval,
|
||||
settings.key_frame_interval_duration,
|
||||
bidirectional,
|
||||
)
|
||||
});
|
||||
Ok(Self {
|
||||
accelerator,
|
||||
settings,
|
||||
@@ -667,7 +700,9 @@ impl<A: Accelerator> Encoder<A> {
|
||||
max_references: max_references.to_usize(),
|
||||
record,
|
||||
planner,
|
||||
coding,
|
||||
times: DecodeTimes::new(),
|
||||
next_coded_dts: None,
|
||||
dpb: VecDeque::new(),
|
||||
frame_num: 0,
|
||||
idr_pic_id: 0,
|
||||
@@ -696,7 +731,8 @@ impl<A: Accelerator> Encoder<A> {
|
||||
self.coded_size
|
||||
}
|
||||
|
||||
/// B pictures in a run; 0 when frames keep their order.
|
||||
/// B pictures in a run of ours, which hold frames back; 0 when each
|
||||
/// frame's sample comes out as it goes in.
|
||||
pub fn b_frames(&self) -> u32 {
|
||||
self.b_frames
|
||||
}
|
||||
@@ -722,11 +758,12 @@ impl<A: Accelerator> Encoder<A> {
|
||||
/// Encodes one frame and returns each frame that comes out, in decode
|
||||
/// order, with its own result: none while it waits as a B picture, or
|
||||
/// several when it ends a run. `Err` is a frame not taken: one whose
|
||||
/// time stamp does not follow the last, or that does not upload.
|
||||
/// time stamp does not follow the last, or in coding order gives no
|
||||
/// place ([`Self::takes`]), or that does not upload.
|
||||
pub fn encode(&mut self, frame: &InputFrame<'_>) -> Result<Vec<Coded<A::Error>>, A::Error> {
|
||||
self.follows(frame.pts)?;
|
||||
let place = self.takes(frame)?;
|
||||
let input = self.accelerator.upload(frame)?;
|
||||
Ok(self.push(input, frame))
|
||||
Ok(self.push(input, frame, place))
|
||||
}
|
||||
|
||||
/// [`Self::encode`] of a frame another device already wrote into `input`, an input of the
|
||||
@@ -737,8 +774,8 @@ impl<A: Accelerator> Encoder<A> {
|
||||
input: A::Input,
|
||||
frame: &InputFrame<'_>,
|
||||
) -> Result<Vec<Coded<A::Error>>, A::Error> {
|
||||
self.follows(frame.pts)?;
|
||||
Ok(self.push(input, frame))
|
||||
let place = self.takes(frame)?;
|
||||
Ok(self.push(input, frame, place))
|
||||
}
|
||||
|
||||
/// [`Self::encode`] of `frame` in place of the last picture coded, whose
|
||||
@@ -823,6 +860,7 @@ impl<A: Accelerator> Encoder<A> {
|
||||
forward,
|
||||
backward,
|
||||
pts,
|
||||
dts,
|
||||
before,
|
||||
picture: _,
|
||||
} = held;
|
||||
@@ -834,9 +872,8 @@ impl<A: Accelerator> Encoder<A> {
|
||||
// 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);
|
||||
// The last try's DTS.
|
||||
self.times.push(dts);
|
||||
let planned = Planned {
|
||||
frame: Pending {
|
||||
input,
|
||||
@@ -883,29 +920,66 @@ impl<A: Accelerator> Encoder<A> {
|
||||
});
|
||||
}
|
||||
|
||||
/// `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 {
|
||||
check(pts > last, || format!("PTS {pts} does not follow {last}"))?;
|
||||
/// Whether `frame` is taken: in display order, where its time stamp
|
||||
/// follows the last frame's; in coding order, where its PTS is a whole
|
||||
/// number of its durations from 0, its place in display order, which
|
||||
/// this answers. `Err` where it is not.
|
||||
fn takes(&self, frame: &InputFrame<'_>) -> Result<Option<u64>, A::Error> {
|
||||
let pts = frame.pts;
|
||||
if self.coding.is_none() {
|
||||
if let Some(last) = self.last_pts {
|
||||
check(pts > last, || format!("PTS {pts} does not follow {last}"))?;
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(())
|
||||
let duration = frame.duration;
|
||||
let place = (duration > 0 && pts.checked_rem(duration) == Some(0))
|
||||
.then(|| u64::try_from(pts / duration).ok())
|
||||
.flatten();
|
||||
check(place.is_some(), || {
|
||||
format!("a frame in coding order at PTS {pts}, of duration {duration}, has no place")
|
||||
})?;
|
||||
Ok(place)
|
||||
}
|
||||
|
||||
/// Takes `frame`, in `input`, and encodes what its plan gives.
|
||||
fn push(&mut self, input: A::Input, frame: &InputFrame<'_>) -> Vec<Coded<A::Error>> {
|
||||
/// In coding order, the DTS of the sample of `frame`, the next frame in:
|
||||
/// one duration after the last sample's, the first one duration before
|
||||
/// its PTS, so that a reference sent one frame ahead of its place, as
|
||||
/// the SPS allows, decodes before it shows and a B picture after it its
|
||||
/// DTS comes no later than its PTS, as Apple's encoders stamp a stream
|
||||
/// that reorders one frame.
|
||||
fn coded_dts(&mut self, frame: &InputFrame<'_>) -> i64 {
|
||||
let dts = (self.next_coded_dts).unwrap_or_else(|| frame.pts.saturating_sub(frame.duration));
|
||||
self.next_coded_dts = Some(dts.saturating_add(frame.duration));
|
||||
dts
|
||||
}
|
||||
|
||||
/// Takes `frame`, in `input`, at `place` in display order where it
|
||||
/// comes in coding order, and encodes what its plan gives.
|
||||
fn push(
|
||||
&mut self,
|
||||
input: A::Input,
|
||||
frame: &InputFrame<'_>,
|
||||
place: Option<u64>,
|
||||
) -> Vec<Coded<A::Error>> {
|
||||
self.keep_held();
|
||||
self.last_pts = Some(frame.pts);
|
||||
self.times.push(frame.pts);
|
||||
let dts = match place {
|
||||
Some(_) => self.coded_dts(frame),
|
||||
None => frame.pts,
|
||||
};
|
||||
self.times.push(dts);
|
||||
let pending = Pending {
|
||||
input,
|
||||
pts: frame.pts,
|
||||
duration: frame.duration,
|
||||
id: frame.id,
|
||||
};
|
||||
let restart = core::mem::take(&mut self.restart);
|
||||
let planned = self
|
||||
.planner
|
||||
.push(pending, frame.pts, frame.force_key_frame || restart);
|
||||
let force = frame.force_key_frame || core::mem::take(&mut self.restart);
|
||||
let planned = match (&mut self.coding, place) {
|
||||
(Some(coding), Some(place)) => vec![coding.push(pending, place, frame.pts, force)],
|
||||
_ => self.planner.push(pending, frame.pts, force),
|
||||
};
|
||||
self.encode_all(planned)
|
||||
}
|
||||
|
||||
@@ -994,6 +1068,9 @@ impl<A: Accelerator> Encoder<A> {
|
||||
self.settings.key_frame_interval = frames;
|
||||
self.settings.key_frame_interval_duration = duration;
|
||||
self.planner.set_key_frame_interval(frames, duration);
|
||||
if let Some(coding) = &mut self.coding {
|
||||
coding.set_interval(frames, duration);
|
||||
}
|
||||
}
|
||||
|
||||
fn reference(&self, number: Option<u64>) -> Result<Option<ReferencePicture>, Unsupported> {
|
||||
@@ -1063,6 +1140,7 @@ impl<A: Accelerator> Encoder<A> {
|
||||
> {
|
||||
let SliceAt {
|
||||
frame_type,
|
||||
reference,
|
||||
order,
|
||||
frame_num,
|
||||
idr_pic_id,
|
||||
@@ -1090,10 +1168,12 @@ impl<A: Accelerator> Encoder<A> {
|
||||
FrameType::B => h264::SliceType::B,
|
||||
},
|
||||
idr: frame_type == FrameType::Idr,
|
||||
nal_ref_idc: match frame_type {
|
||||
FrameType::Idr => 3,
|
||||
FrameType::P => 2,
|
||||
FrameType::B => 0,
|
||||
// A B picture is never a reference; a P picture in
|
||||
// coding order may not be one.
|
||||
nal_ref_idc: match (frame_type, reference) {
|
||||
(_, false) => 0,
|
||||
(FrameType::Idr, true) => 3,
|
||||
(FrameType::P | FrameType::B, true) => 2,
|
||||
},
|
||||
frame_num,
|
||||
idr_pic_id,
|
||||
@@ -1181,6 +1261,7 @@ impl<A: Accelerator> Encoder<A> {
|
||||
let idr_pic_id = self.idr_pic_id;
|
||||
let slice = |qp| SliceAt {
|
||||
frame_type,
|
||||
reference: reference.is_some(),
|
||||
order,
|
||||
frame_num,
|
||||
idr_pic_id,
|
||||
@@ -1257,6 +1338,7 @@ impl<A: Accelerator> Encoder<A> {
|
||||
forward,
|
||||
backward,
|
||||
pts: frame.pts,
|
||||
dts,
|
||||
before,
|
||||
picture: Unkept {
|
||||
frame_type,
|
||||
@@ -1365,6 +1447,9 @@ pub mod tests {
|
||||
/// Each kept picture's `pic_order_cnt_lsb`, as its slice header
|
||||
/// says.
|
||||
lsbs: Vec<u32>,
|
||||
/// Each kept H.264 picture's `nal_ref_idc`, as its slice header
|
||||
/// says.
|
||||
ref_idcs: Vec<u8>,
|
||||
/// Whether the stream was configured for QPs the encoder picks.
|
||||
picture_qp: bool,
|
||||
}
|
||||
@@ -1422,6 +1507,9 @@ pub mod tests {
|
||||
_ => 0,
|
||||
};
|
||||
self.lsbs.push(lsb);
|
||||
if let Some(slice) = p.h264_slice {
|
||||
self.ref_idcs.push(slice.nal_ref_idc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1774,6 +1862,157 @@ pub mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Frames at `places` in display order, sent in the order given, with
|
||||
/// a key frame forced at the frames of `keys` (by their place in the
|
||||
/// list), through an encoder of `settings` in coding order: each result,
|
||||
/// and the fake once flushed.
|
||||
fn in_coding_order(
|
||||
mut settings: EncoderSettings,
|
||||
places: &[u32],
|
||||
keys: &[usize],
|
||||
) -> Result<(Vec<EncodedSample>, Fake), Unsupported> {
|
||||
settings.coding_order = true;
|
||||
let mut encoder = Encoder::new(Fake::default(), settings, &limits())?;
|
||||
let mut coded = Vec::new();
|
||||
for (n, &place) in places.iter().enumerate() {
|
||||
coded.extend(encoder.encode(&frame(place, keys.contains(&n)))?);
|
||||
}
|
||||
coded.extend(encoder.flush());
|
||||
let Encoder { accelerator, .. } = encoder;
|
||||
Ok((samples(coded)?, accelerator))
|
||||
}
|
||||
|
||||
/// AppleGVA's frames with reordering allowed, as its encoders send them:
|
||||
/// each reference before the B picture shown ahead of it (I0 P2 B1 P4
|
||||
/// B3 P6 B5 P7, measured on the Mac's own encoders, oracle job
|
||||
/// m3-max-86942). Each picture's order count follows its place in
|
||||
/// display order, each B picture between the references either side of
|
||||
/// it, which nothing predicts from; the SPS says one frame may come out
|
||||
/// of display order; and each sample comes out as its frame goes in,
|
||||
/// its DTS one frame after the last, the first one frame before its PTS.
|
||||
#[test]
|
||||
fn h264_frames_in_coding_order_keep_their_places() -> Result<(), Unsupported> {
|
||||
use FrameType::{B, Idr, P};
|
||||
let places = [0, 2, 1, 4, 3, 6, 5, 7];
|
||||
let mut settings = EncoderSettings::new(Profile::H264High, 640, 360);
|
||||
settings.key_frame_interval = None;
|
||||
let (samples, fake) = in_coding_order(settings, &places, &[])?;
|
||||
let ids: Vec<u64> = samples.iter().map(|s| s.id).collect();
|
||||
assert_eq!(ids, places.map(u64::from));
|
||||
let types: Vec<FrameType> = samples.iter().map(|s| s.frame_type).collect();
|
||||
assert_eq!(types, [Idr, P, B, P, B, P, B, P]);
|
||||
assert_eq!(fake.lsbs, places.map(|p| p * 2));
|
||||
assert_eq!(fake.ref_idcs, [3, 2, 0, 2, 0, 2, 0, 2]);
|
||||
// B picture 1 predicts from POCs 0 and 4; P picture 4 from 4.
|
||||
assert_eq!((fake.pictures[2].2, fake.pictures[2].3), (Some(0), Some(4)));
|
||||
assert_eq!((fake.pictures[3].2, fake.pictures[3].3), (Some(4), None));
|
||||
for s in &samples {
|
||||
assert_eq!(s.is_depended_on, s.frame_type != B);
|
||||
}
|
||||
let dts: Vec<i64> = samples.iter().map(|s| s.dts).collect();
|
||||
assert_eq!(dts, (-1..7).map(|n| n * 3000).collect::<Vec<_>>());
|
||||
assert!(samples.iter().all(|s| s.dts <= s.pts));
|
||||
let record = samples[0].configuration.clone().unwrap_or_default();
|
||||
let sps = crate::codec::h264::avcc::DecoderConfiguration::parse(&record)
|
||||
.ok()
|
||||
.and_then(|avcc| avcc.sequence_parameter_sets.first().copied())
|
||||
.and_then(|unit| crate::codec::h264::sps::Sps::parse(unit).ok())
|
||||
.ok_or_else(|| Unsupported("the record's SPS".into()))?;
|
||||
assert_eq!(sps.max_num_reorder_frames(), 1);
|
||||
assert_eq!(sps.max_num_ref_frames, 2);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`h264_frames_in_coding_order_keep_their_places`] for HEVC, whose
|
||||
/// order counts are the places themselves, and which codes no B slices
|
||||
/// ([`Profile::has_b_slices`]): a frame sent after a later one is a P
|
||||
/// picture nothing predicts from, predicting from the last reference.
|
||||
#[test]
|
||||
fn hevc_frames_in_coding_order_keep_their_places() -> Result<(), Unsupported> {
|
||||
use FrameType::{Idr, P};
|
||||
let places = [0, 2, 1, 4, 3, 5];
|
||||
let (samples, fake) = in_coding_order(
|
||||
EncoderSettings::new(Profile::HevcMain, 640, 360),
|
||||
&places,
|
||||
&[],
|
||||
)?;
|
||||
let types: Vec<FrameType> = samples.iter().map(|s| s.frame_type).collect();
|
||||
assert_eq!(types, [Idr, P, P, P, P, P]);
|
||||
let depended: Vec<bool> = samples.iter().map(|s| s.is_depended_on).collect();
|
||||
assert_eq!(depended, [true, true, false, true, false, true]);
|
||||
assert_eq!(fake.lsbs, places);
|
||||
assert_eq!((fake.pictures[2].2, fake.pictures[2].3), (Some(2), None));
|
||||
assert_eq!((fake.pictures[4].2, fake.pictures[4].3), (Some(4), None));
|
||||
let record = samples[0].configuration.clone().unwrap_or_default();
|
||||
let sps = crate::codec::hevc::hvcc::DecoderConfiguration::parse(&record)
|
||||
.ok()
|
||||
.and_then(|hvcc| {
|
||||
(hvcc.nal_units.into_iter())
|
||||
.find(|unit| unit.first().map(|b| (b >> 1) & 0x3f) == Some(33))
|
||||
})
|
||||
.and_then(|unit| crate::codec::hevc::sps::Sps::parse(unit).ok())
|
||||
.ok_or_else(|| Unsupported("the record's SPS".into()))?;
|
||||
assert_eq!(sps.highest_ordering().max_num_reorder_pics, 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// In coding order, a profile or driver without B slices codes a frame
|
||||
/// sent after a later one as a P picture nothing predicts from, from the
|
||||
/// last reference; frames that keep display order are all references; a
|
||||
/// key frame where one is forced, or at a place not past its key
|
||||
/// frame's or the last reference's, starts again from the frame's place.
|
||||
#[test]
|
||||
fn frames_in_coding_order_without_b_slices_and_key_frames() -> Result<(), Unsupported> {
|
||||
use FrameType::{Idr, P};
|
||||
let settings = EncoderSettings::new(Profile::H264ConstrainedBaseline, 640, 360);
|
||||
let (samples, fake) = in_coding_order(settings, &[0, 2, 1, 3, 4, 4, 3, 6, 5], &[4])?;
|
||||
let types: Vec<FrameType> = samples.iter().map(|s| s.frame_type).collect();
|
||||
// Frame 4 is forced; the next, at its place, and the one after, at
|
||||
// one before it, are key frames too.
|
||||
assert_eq!(types, [Idr, P, P, P, Idr, Idr, Idr, P, P]);
|
||||
assert_eq!(fake.ref_idcs, [3, 2, 0, 2, 3, 3, 3, 2, 0]);
|
||||
assert_eq!(fake.lsbs, [0, 4, 2, 6, 0, 0, 0, 6, 4]);
|
||||
// The P picture at place 1 predicts from place 2's.
|
||||
assert_eq!(fake.pictures[2].2, Some(4));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A frame in coding order is coded again in place of the last one as
|
||||
/// in display order, at its place, its DTS the last try's; a frame whose
|
||||
/// PTS is not a whole number of its durations has no place and is not
|
||||
/// taken.
|
||||
#[test]
|
||||
fn frames_in_coding_order_are_coded_again_in_place() -> Result<(), Unsupported> {
|
||||
let mut settings = in_place_settings(Profile::HevcMain);
|
||||
settings.coding_order = true;
|
||||
let mut encoder = Encoder::new(Fake::default(), settings, &limits())?;
|
||||
let mut coded = Vec::new();
|
||||
for place in [0, 2] {
|
||||
coded.extend(encoder.encode(&frame(place, false))?);
|
||||
}
|
||||
coded.extend(encoder.encode_in_place(&frame(2, false))?);
|
||||
coded.extend(encoder.encode(&frame(1, false))?);
|
||||
let mut odd = frame(3, false);
|
||||
odd.pts += 1;
|
||||
assert!(encoder.encode(&odd).is_err());
|
||||
coded.extend(encoder.flush());
|
||||
let Encoder { accelerator, .. } = encoder;
|
||||
let samples = samples(coded)?;
|
||||
let dts: Vec<i64> = samples.iter().map(|s| s.dts).collect();
|
||||
assert_eq!(dts, [-3000, 0, 0, 3000]);
|
||||
let types: Vec<FrameType> = samples.iter().map(|s| s.frame_type).collect();
|
||||
assert_eq!(
|
||||
types,
|
||||
[FrameType::Idr, FrameType::P, FrameType::P, FrameType::P]
|
||||
);
|
||||
// The kept pictures: the IDR picture, the second try at place 2,
|
||||
// and the picture at place 1, which predicts from it.
|
||||
assert_eq!(accelerator.lsbs, [0, 2, 1]);
|
||||
assert_eq!(accelerator.pictures[2].2, Some(2));
|
||||
assert!(!samples[3].is_depended_on);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hevc_predicts_from_the_last_picture_in_order() -> Result<(), Unsupported> {
|
||||
let mut settings = EncoderSettings::new(Profile::HevcMain10, 100, 50);
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
//! reference before it. B pictures still waiting when an IDR picture comes,
|
||||
//! or at a flush, end their run as x264 ends one: the last becomes a P
|
||||
//! picture, so that none predicts across the IDR picture.
|
||||
//!
|
||||
//! Frames that come in the order they are coded, each at its own place in
|
||||
//! display order, are planned by [`CodingOrder`] instead, as they come.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
@@ -264,6 +267,158 @@ impl<F> GopPlanner<F> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Plans frames that come in the order they are coded, each with its own
|
||||
/// place in display order, as an encoder above ours sends them (the
|
||||
/// guest's, which decides its own B pictures): one picture out for each
|
||||
/// frame in, at once. A frame is an IDR picture at the first frame, where
|
||||
/// one is forced, at the first frame past the key-frame interval in places
|
||||
/// or in time stamp ticks, at one whose order would pass [`MAX_ORDER`], and
|
||||
/// at one whose place is not past its IDR picture's, or is the last
|
||||
/// reference's. Its order is its place less its IDR picture's. Otherwise a
|
||||
/// frame whose order is past every order since its IDR picture is a P
|
||||
/// picture, a reference predicting from the last reference; and one whose
|
||||
/// order is not, a frame its encoder sent after a later one, is a picture
|
||||
/// nothing predicts from: a B picture between the closest references before
|
||||
/// and after it where `bidirectional` and one before it is held, else a P
|
||||
/// picture predicting from the last reference. The references held are the
|
||||
/// last two.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct CodingOrder {
|
||||
interval: Option<u32>,
|
||||
interval_duration: Option<i64>,
|
||||
/// Whether a picture that is not a reference may be a B picture.
|
||||
bidirectional: bool,
|
||||
/// The last IDR picture's place and time stamp; none before the first
|
||||
/// frame.
|
||||
key: Option<(u64, i64)>,
|
||||
/// The references held, oldest first: their numbers and orders.
|
||||
references: VecDeque<(u64, u32)>,
|
||||
/// The highest order planned since the last IDR picture.
|
||||
top: u32,
|
||||
next_reference: u64,
|
||||
}
|
||||
|
||||
/// The references [`CodingOrder`] holds: a P picture's and, for a B
|
||||
/// picture, the one before it.
|
||||
pub(crate) const CODING_ORDER_REFERENCES: usize = 2;
|
||||
|
||||
impl CodingOrder {
|
||||
/// A planner with key frames at most `interval` places or
|
||||
/// `interval_duration` ticks apart, where either is set, before the
|
||||
/// first frame.
|
||||
pub(crate) fn new(
|
||||
interval: Option<u32>,
|
||||
interval_duration: Option<i64>,
|
||||
bidirectional: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
interval,
|
||||
interval_duration,
|
||||
bidirectional,
|
||||
key: None,
|
||||
references: VecDeque::new(),
|
||||
top: 0,
|
||||
next_reference: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes the interval, from the next frame on.
|
||||
pub(crate) fn set_interval(&mut self, frames: Option<u32>, duration: Option<i64>) {
|
||||
self.interval = frames;
|
||||
self.interval_duration = duration;
|
||||
}
|
||||
|
||||
/// The order of a frame at `place`, time stamp `pts`, after the last
|
||||
/// IDR picture; none where it is an IDR picture (the type's doc): a
|
||||
/// place the last reference has would give two pictures one order
|
||||
/// count.
|
||||
fn order(&self, place: u64, pts: i64, force: bool) -> Option<u32> {
|
||||
let (key_place, key_pts) = self.key?;
|
||||
let order = u32::try_from(place.checked_sub(key_place)?).ok()?;
|
||||
let by_count = self
|
||||
.interval
|
||||
.is_some_and(|interval| order >= interval.max(1));
|
||||
let by_time = self
|
||||
.interval_duration
|
||||
.is_some_and(|duration| pts.saturating_sub(key_pts) >= duration.max(1));
|
||||
let key =
|
||||
force || by_count || by_time || order == 0 || order == self.top || order > MAX_ORDER;
|
||||
(!key).then_some(order)
|
||||
}
|
||||
|
||||
/// Takes the next frame in the order it is coded, at `place` in display
|
||||
/// order, with its time stamp and whether a key frame is forced there,
|
||||
/// and plans it.
|
||||
pub(crate) fn push<F>(&mut self, frame: F, place: u64, pts: i64, force: bool) -> Planned<F> {
|
||||
let Some(order) = self.order(place, pts, force) else {
|
||||
let reference = self.take_reference();
|
||||
self.key = Some((place, pts));
|
||||
self.references.clear();
|
||||
self.references.push_back((reference, 0));
|
||||
self.top = 0;
|
||||
return Planned {
|
||||
frame,
|
||||
frame_type: FrameType::Idr,
|
||||
order: 0,
|
||||
reference: Some(reference),
|
||||
forward: None,
|
||||
backward: None,
|
||||
};
|
||||
};
|
||||
let last = self.references.back().map(|&(number, _)| number);
|
||||
if order > self.top {
|
||||
let reference = self.take_reference();
|
||||
self.references.push_back((reference, order));
|
||||
while self.references.len() > CODING_ORDER_REFERENCES {
|
||||
self.references.pop_front();
|
||||
}
|
||||
self.top = order;
|
||||
return Planned {
|
||||
frame,
|
||||
frame_type: FrameType::P,
|
||||
order,
|
||||
reference: Some(reference),
|
||||
forward: last,
|
||||
backward: None,
|
||||
};
|
||||
}
|
||||
let before = (self.references.iter())
|
||||
.filter(|&&(_, o)| o < order)
|
||||
.max_by_key(|&&(_, o)| o)
|
||||
.map(|&(number, _)| number);
|
||||
let after = (self.references.iter())
|
||||
.filter(|&&(_, o)| o > order)
|
||||
.min_by_key(|&&(_, o)| o)
|
||||
.map(|&(number, _)| number);
|
||||
match (self.bidirectional, before, after) {
|
||||
(true, Some(before), Some(after)) => Planned {
|
||||
frame,
|
||||
frame_type: FrameType::B,
|
||||
order,
|
||||
reference: None,
|
||||
forward: Some(before),
|
||||
backward: Some(after),
|
||||
},
|
||||
_ => Planned {
|
||||
frame,
|
||||
frame_type: FrameType::P,
|
||||
order,
|
||||
reference: None,
|
||||
forward: last,
|
||||
backward: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// A new reference's number.
|
||||
fn take_reference(&mut self) -> u64 {
|
||||
let number = self.next_reference;
|
||||
// As GopPlanner::take_reference's.
|
||||
self.next_reference = self.next_reference.wrapping_add(1);
|
||||
number
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode time stamps for samples in decode order, from the frames' time
|
||||
/// stamps in the order they were sent, as Apple's encoders give them: the
|
||||
/// `k`th sample's DTS is the PTS of the `k`th frame sent. Apple's host
|
||||
@@ -419,6 +574,80 @@ mod tests {
|
||||
assert_eq!(planned[6].forward, planned[5].reference);
|
||||
}
|
||||
|
||||
/// Plans frames at `places`, sent in that order, under `planner`, a key
|
||||
/// frame forced at the frames of `forced` (by their place in the list).
|
||||
fn plan_coded(mut planner: CodingOrder, places: &[u32], forced: &[usize]) -> Vec<Planned<u32>> {
|
||||
(places.iter().enumerate())
|
||||
.map(|(n, &place)| {
|
||||
let pts = i64::from(place) * 3000;
|
||||
planner.push(place, u64::from(place), pts, forced.contains(&n))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_in_coding_order_are_planned_at_their_places() {
|
||||
let planned = plan_coded(CodingOrder::new(None, None, true), &[0, 2, 1, 4, 3, 5], &[]);
|
||||
assert_eq!(types(&planned), "I0 P2 B1 P4 B3 P5");
|
||||
let orders: Vec<u32> = planned.iter().map(|p| p.order).collect();
|
||||
assert_eq!(orders, [0, 2, 1, 4, 3, 5]);
|
||||
// B1 sits between I0 and P2, B3 between P2 and P4; P4 predicts
|
||||
// from P2, and P5 from P4.
|
||||
assert_eq!(planned[2].forward, planned[0].reference);
|
||||
assert_eq!(planned[2].backward, planned[1].reference);
|
||||
assert_eq!(planned[4].forward, planned[1].reference);
|
||||
assert_eq!(planned[4].backward, planned[3].reference);
|
||||
assert_eq!(planned[3].forward, planned[1].reference);
|
||||
assert_eq!(planned[5].forward, planned[3].reference);
|
||||
assert!(planned[2].reference.is_none() && planned[4].reference.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_in_coding_order_without_b_pictures_or_past_their_references() {
|
||||
// Without B pictures, a frame sent after a later one predicts from
|
||||
// the last reference, as nothing predicts from it.
|
||||
let planned = plan_coded(CodingOrder::new(None, None, false), &[0, 2, 1, 3], &[]);
|
||||
assert_eq!(types(&planned), "I0 P2 P1 P3");
|
||||
assert_eq!(planned[2].forward, planned[1].reference);
|
||||
assert_eq!(planned[2].reference, None);
|
||||
assert_eq!(planned[3].forward, planned[1].reference);
|
||||
// Two frames sent ahead of their place: the oldest reference is let
|
||||
// go, and the frame before both predicts from the last.
|
||||
let planned = plan_coded(CodingOrder::new(None, None, true), &[0, 3, 4, 1, 2], &[]);
|
||||
assert_eq!(types(&planned), "I0 P3 P4 P1 P2");
|
||||
assert_eq!(planned[3].forward, planned[2].reference);
|
||||
assert_eq!(planned[4].forward, planned[2].reference);
|
||||
assert_eq!(planned[4].backward, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_in_coding_order_start_again_at_key_frames() {
|
||||
// A forced key frame, a place not past the key frame's or the last
|
||||
// reference's, and the key-frame interval in places and in ticks.
|
||||
let planned = plan_coded(
|
||||
CodingOrder::new(Some(4), None, true),
|
||||
&[0, 2, 1, 3, 4, 4, 3, 6, 5, 7],
|
||||
&[3],
|
||||
);
|
||||
assert_eq!(types(&planned), "I0 P2 B1 I3 P4 I4 I3 P6 B5 I7");
|
||||
let orders: Vec<u32> = planned.iter().map(|p| p.order).collect();
|
||||
assert_eq!(orders, [0, 2, 1, 0, 1, 0, 0, 3, 2, 0]);
|
||||
let mut planner = CodingOrder::new(None, Some(3 * 3000), true);
|
||||
planner.set_interval(None, Some(2 * 3000));
|
||||
let planned = plan_coded(planner, &[0, 1, 2, 3], &[]);
|
||||
assert_eq!(types(&planned), "I0 P1 I2 P3");
|
||||
// A place past MAX_ORDER from its key frame.
|
||||
let far = MAX_ORDER + 1;
|
||||
let planned = plan_coded(CodingOrder::new(None, None, true), &[0, far - 1, far], &[]);
|
||||
assert_eq!(
|
||||
types(&planned)
|
||||
.split(' ')
|
||||
.map(|t| &t[..1])
|
||||
.collect::<String>(),
|
||||
"IPI"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_times_are_the_ptses_sent_in_order() {
|
||||
let config = GopConfig {
|
||||
|
||||
@@ -147,6 +147,7 @@ fn access_units_decode_in_place_and_land_by_the_gpu_as_they_read_back() {
|
||||
width,
|
||||
height,
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
..params(profile)
|
||||
};
|
||||
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), ¶ms).expect("an NVENC session");
|
||||
@@ -240,6 +241,7 @@ fn a_plane_past_its_registration_is_never_copied() {
|
||||
width,
|
||||
height,
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
..params(EncodeProfile::H264High)
|
||||
};
|
||||
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), ¶ms).expect("an NVENC session");
|
||||
@@ -319,6 +321,7 @@ fn a_stream_started_at_a_p_picture_answers_picture_errors_until_its_idr_picture(
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
..params(profile)
|
||||
};
|
||||
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), ¶ms).expect("an NVENC session");
|
||||
@@ -378,6 +381,7 @@ fn a_failed_picture_is_copied_and_decoded_on_from_or_refused() {
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
..params(profile)
|
||||
};
|
||||
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), ¶ms).expect("an NVENC session");
|
||||
@@ -464,6 +468,7 @@ fn the_pictures_after_one_that_does_not_decode_come_out() {
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
..params(EncodeProfile::H264High)
|
||||
};
|
||||
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), ¶ms).expect("an NVENC session");
|
||||
@@ -587,6 +592,7 @@ fn a_smaller_stream_on_a_kept_larger_decoder_decodes_as_on_its_own() {
|
||||
width,
|
||||
height,
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
..params(profile)
|
||||
};
|
||||
let small = encoded(&gpu, &sized(400, 258), 8);
|
||||
@@ -778,6 +784,7 @@ fn a_kept_decoder_short_of_surfaces_is_given_more_and_decodes_as_one_made() {
|
||||
width: 400,
|
||||
height: 258,
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
..params(profile)
|
||||
};
|
||||
let (sets, units) = encoded(&gpu, ¶ms, 16);
|
||||
|
||||
@@ -595,6 +595,26 @@ fn nvenc_checks(checks: &mut Checks) {
|
||||
"NV_ENC_CODEC_PIC_PARAMS",
|
||||
size_of::<enc::NV_ENC_CODEC_PIC_PARAMS>(),
|
||||
);
|
||||
checks.offset(
|
||||
"NV_ENC_PIC_PARAMS_H264",
|
||||
"displayPOCSyntax",
|
||||
enc::H264_DISPLAY_POC_SYNTAX,
|
||||
);
|
||||
checks.offset(
|
||||
"NV_ENC_PIC_PARAMS_H264",
|
||||
"refPicFlag",
|
||||
enc::H264_REF_PIC_FLAG,
|
||||
);
|
||||
checks.offset(
|
||||
"NV_ENC_PIC_PARAMS_HEVC",
|
||||
"displayPOCSyntax",
|
||||
enc::HEVC_DISPLAY_POC_SYNTAX,
|
||||
);
|
||||
checks.offset(
|
||||
"NV_ENC_PIC_PARAMS_HEVC",
|
||||
"refPicFlag",
|
||||
enc::HEVC_REF_PIC_FLAG,
|
||||
);
|
||||
layout!(checks, enc::NV_ENC_PIC_PARAMS, "NV_ENC_PIC_PARAMS" {
|
||||
version, inputWidth, inputHeight, inputPitch, encodePicFlags, frameIdx, inputTimeStamp,
|
||||
inputDuration, inputBuffer, outputBitstream, completionEvent, bufferFmt, pictureStruct,
|
||||
|
||||
@@ -226,7 +226,8 @@ pub(crate) enum Submission {
|
||||
/// packet, and `idr` makes it an IDR picture with its parameter sets
|
||||
/// 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`]).
|
||||
/// ([`Session::restore_state`]). `planned` is its plan in a session
|
||||
/// without picture type decision.
|
||||
Frame {
|
||||
input: Buffer,
|
||||
output: Buffer,
|
||||
@@ -235,11 +236,24 @@ pub(crate) enum Submission {
|
||||
timestamp: u64,
|
||||
idr: bool,
|
||||
unadvanced: bool,
|
||||
planned: Option<PicturePlan>,
|
||||
},
|
||||
/// The end of the stream: every frame NVENC holds comes out.
|
||||
End,
|
||||
}
|
||||
|
||||
/// A picture as a session without picture type decision (`enablePTD` 0)
|
||||
/// plans it: its type (`pictureType`), whether later pictures may predict
|
||||
/// from it (`refPicFlag`), and its order count in display order
|
||||
/// (`displayPOCSyntax`), of HEVC's member where `hevc`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct PicturePlan {
|
||||
pub(crate) picture_type: ffi::NV_ENC_PIC_TYPE,
|
||||
pub(crate) reference: bool,
|
||||
pub(crate) display_poc: u32,
|
||||
pub(crate) hevc: bool,
|
||||
}
|
||||
|
||||
// SAFETY: an NVENC session may be driven from any thread, one call at a
|
||||
// time; `&mut self` (or the caller's lock) gives that, since it is not
|
||||
// `Sync`. The pointers it keeps are the driver's handles and the kept
|
||||
@@ -780,6 +794,7 @@ impl Session {
|
||||
timestamp,
|
||||
idr,
|
||||
unadvanced,
|
||||
planned,
|
||||
} => {
|
||||
let output = self.output(output, &[BufferKind::Bitstream])?;
|
||||
self.submitted.borrow().check_free(output)?;
|
||||
@@ -805,6 +820,10 @@ impl Session {
|
||||
picture.encodePicFlags |= ffi::NV_ENC_PIC_FLAG_DISABLE_ENC_STATE_ADVANCE;
|
||||
picture.stateBufferIdx = 0;
|
||||
}
|
||||
if let Some(plan) = planned {
|
||||
picture.pictureType = plan.picture_type;
|
||||
(picture.codecPicParams).set_order(plan.hevc, plan.display_poc, plan.reference);
|
||||
}
|
||||
}
|
||||
Submission::End => picture.encodePicFlags = ffi::NV_ENC_PIC_FLAG_EOS,
|
||||
}
|
||||
|
||||
@@ -11,6 +11,13 @@
|
||||
//! length. B pictures are never references here, so a reference is encoded
|
||||
//! at most one frame ahead of its display order.
|
||||
//!
|
||||
//! A session in coding order ([`EncodeParams::coding_order`]) takes frames
|
||||
//! in the order an encoder above it codes them, each at its place in
|
||||
//! display order, and plans each picture itself, as the codec crate's
|
||||
//! encoder does (`gop`'s `CodingOrder`): NVENC's picture type decision is
|
||||
//! off, and each picture goes with its type, whether it is a reference and
|
||||
//! its order count in 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
|
||||
@@ -23,7 +30,9 @@ use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::ffi::{self, GUID, Zeroed};
|
||||
use super::{Buffer, Session, Submission};
|
||||
use super::{Buffer, PicturePlan, Session, Submission};
|
||||
use crate::codec::encode::FrameType;
|
||||
use crate::codec::encode::gop::CodingOrder;
|
||||
use crate::nvidia::cuda::Gpu;
|
||||
use crate::nvidia::error::Error;
|
||||
use crate::nvidia::external::ImportedBuffer;
|
||||
@@ -143,6 +152,12 @@ pub struct EncodeParams {
|
||||
pub gop_length: Option<u32>,
|
||||
/// The B pictures between references; 0 for none.
|
||||
pub b_frames: u32,
|
||||
/// Whether frames come in the order they are coded, each at its place
|
||||
/// in display order, its index (module doc): with no B pictures of
|
||||
/// NVENC's own (`b_frames` 0), a frame sent after a later one is a B
|
||||
/// picture where the profile and NVENC have them, else a P picture
|
||||
/// nothing predicts from.
|
||||
pub coding_order: bool,
|
||||
/// The level as the bitstream numbers it, or none for NVENC's choice.
|
||||
pub level: Option<u32>,
|
||||
/// H.264's entropy coder: true for CABAC, false for CAVLC, none for the
|
||||
@@ -225,7 +240,7 @@ pub struct RawFrame<'a> {
|
||||
/// The chroma plane and its bytes per row.
|
||||
pub chroma: (&'a [u8], usize),
|
||||
/// The caller's index for the frame, given back with its packet; each
|
||||
/// later than the last.
|
||||
/// later than the last, or in coding order its place in display order.
|
||||
pub index: u64,
|
||||
/// Whether it must be an IDR picture.
|
||||
pub force_idr: bool,
|
||||
@@ -242,7 +257,7 @@ pub struct DeviceFrame<'a> {
|
||||
/// Bytes from one row to the next: a multiple of 4, as NVENC takes it.
|
||||
pub pitch: u32,
|
||||
/// The caller's index for the frame, given back with its packet; each
|
||||
/// later than the last.
|
||||
/// later than the last, or in coding order its place in display order.
|
||||
pub index: u64,
|
||||
/// Whether it must be an IDR picture.
|
||||
pub force_idr: bool,
|
||||
@@ -292,6 +307,8 @@ pub struct NvencEncoder {
|
||||
/// 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,
|
||||
/// The planner of a session in coding order (module doc).
|
||||
coding: Option<CodingOrder>,
|
||||
session: Session,
|
||||
/// The device memory registered as input. After the session, which
|
||||
/// unregisters it as it drops, so that the imports outlive their
|
||||
@@ -311,6 +328,31 @@ struct Unkept {
|
||||
idr: bool,
|
||||
/// What NVENC coded it as.
|
||||
picture_type: PictureType,
|
||||
/// Its plan, in coding order.
|
||||
planned: Option<PicturePlan>,
|
||||
}
|
||||
|
||||
/// NVENC's plan of a picture `planned` in coding order (module doc), of an
|
||||
/// HEVC session where `hevc`: its type, a P picture nothing predicts from
|
||||
/// being NVENC's non-reference P, and its order count in display order,
|
||||
/// H.264's twice its order, as the codec crate's encoder counts it.
|
||||
fn plan_of(planned: crate::codec::encode::gop::Planned<()>, hevc: bool) -> PicturePlan {
|
||||
let reference = planned.reference.is_some();
|
||||
PicturePlan {
|
||||
picture_type: match (planned.frame_type, reference) {
|
||||
(FrameType::Idr, _) => ffi::NV_ENC_PIC_TYPE_IDR,
|
||||
(FrameType::P, true) => ffi::NV_ENC_PIC_TYPE_P,
|
||||
(FrameType::P, false) => ffi::NV_ENC_PIC_TYPE_NONREF_P,
|
||||
(FrameType::B, _) => ffi::NV_ENC_PIC_TYPE_B,
|
||||
},
|
||||
reference,
|
||||
display_poc: if hevc {
|
||||
planned.order
|
||||
} else {
|
||||
planned.order.saturating_mul(2)
|
||||
},
|
||||
hevc,
|
||||
}
|
||||
}
|
||||
|
||||
/// Ours: input and bitstream buffers beyond what NVENC holds, so that a
|
||||
@@ -345,7 +387,18 @@ impl NvencEncoder {
|
||||
Tuning::LowLatency => ffi::NV_ENC_TUNING_INFO_LOW_LATENCY,
|
||||
};
|
||||
let mut config = session.preset_config(codec, preset, tuning)?.presetCfg;
|
||||
configure(&mut config, params);
|
||||
// In coding order, B pictures one at a time where the profile and
|
||||
// NVENC have them (module doc), configured as NVENC's own would be.
|
||||
let bidirectional = params.coding_order
|
||||
&& params.profile.has_b_slices()
|
||||
&& session.capability(codec, ffi::caps::NUM_MAX_BFRAMES)? >= 1;
|
||||
configure(
|
||||
&mut config,
|
||||
&EncodeParams {
|
||||
b_frames: params.b_frames.max(u32::from(bidirectional)),
|
||||
..params.clone()
|
||||
},
|
||||
);
|
||||
let mut init = ffi::NV_ENC_INITIALIZE_PARAMS::zeroed();
|
||||
init.version = ffi::NV_ENC_INITIALIZE_PARAMS_VER;
|
||||
init.encodeGUID = codec;
|
||||
@@ -360,7 +413,7 @@ impl NvencEncoder {
|
||||
init.frameRateNum = params.frame_rate.0.max(1);
|
||||
init.frameRateDen = params.frame_rate.1.max(1);
|
||||
init.enableEncodeAsync = 0;
|
||||
init.enablePTD = 1;
|
||||
init.enablePTD = u32::from(!params.coding_order);
|
||||
init.maxEncodeWidth = params.width;
|
||||
init.maxEncodeHeight = params.height;
|
||||
init.tuningInfo = tuning;
|
||||
@@ -378,6 +431,9 @@ impl NvencEncoder {
|
||||
holds,
|
||||
unkept: None,
|
||||
restart: false,
|
||||
coding: params
|
||||
.coding_order
|
||||
.then(|| CodingOrder::new(params.gop_length, None, bidirectional)),
|
||||
session,
|
||||
device_inputs: Vec::new(),
|
||||
};
|
||||
@@ -461,7 +517,7 @@ impl NvencEncoder {
|
||||
pitch,
|
||||
frame.index,
|
||||
unkept.idr || frame.force_idr,
|
||||
unkept.frame_idx,
|
||||
(unkept.frame_idx, unkept.planned),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -479,7 +535,7 @@ impl NvencEncoder {
|
||||
frame.pitch,
|
||||
frame.index,
|
||||
unkept.idr || frame.force_idr,
|
||||
unkept.frame_idx,
|
||||
(unkept.frame_idx, unkept.planned),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -662,19 +718,21 @@ impl NvencEncoder {
|
||||
) -> Result<Vec<Bitstream>, Error> {
|
||||
self.keep_going();
|
||||
let frame_idx = self.submitted;
|
||||
self.code(
|
||||
slot_index,
|
||||
input,
|
||||
pitch,
|
||||
index,
|
||||
force_idr || self.restart,
|
||||
frame_idx,
|
||||
)
|
||||
let idr = force_idr || self.restart;
|
||||
let hevc = self.params.profile.is_hevc();
|
||||
let planned =
|
||||
(self.coding.as_mut()).map(|coding| plan_of(coding.push((), index, 0, idr), hevc));
|
||||
let idr = planned.map_or(idr, |plan| plan.picture_type == ffi::NV_ENC_PIC_TYPE_IDR);
|
||||
self.code(slot_index, input, pitch, index, idr, (frame_idx, planned))
|
||||
// In coding order the planner took the frame NVENC did not: the
|
||||
// next one starts again.
|
||||
.inspect_err(|_| self.restart |= self.coding.is_some())
|
||||
}
|
||||
|
||||
/// 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).
|
||||
/// buffer as `frame_idx`, with its plan in coding order, 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,
|
||||
@@ -682,7 +740,7 @@ impl NvencEncoder {
|
||||
pitch: u32,
|
||||
index: u64,
|
||||
idr: bool,
|
||||
frame_idx: u32,
|
||||
(frame_idx, planned): (u32, Option<PicturePlan>),
|
||||
) -> Result<Vec<Bitstream>, Error> {
|
||||
let status = self.session.encode_picture(Submission::Frame {
|
||||
input,
|
||||
@@ -692,6 +750,7 @@ impl NvencEncoder {
|
||||
timestamp: index,
|
||||
idr,
|
||||
unadvanced: self.holds,
|
||||
planned,
|
||||
});
|
||||
let status = match status {
|
||||
Ok(status) => status,
|
||||
@@ -718,6 +777,7 @@ impl NvencEncoder {
|
||||
frame_idx,
|
||||
idr,
|
||||
picture_type: packet.picture_type,
|
||||
planned,
|
||||
});
|
||||
}
|
||||
Ok(bitstreams)
|
||||
@@ -917,6 +977,7 @@ pub fn codes_in_place(
|
||||
buffer_milliseconds: 1000,
|
||||
gop_length: None,
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
level: None,
|
||||
cabac: None,
|
||||
full_range: false,
|
||||
@@ -1191,6 +1252,7 @@ pub(crate) mod tests {
|
||||
buffer_milliseconds: 1000,
|
||||
gop_length: Some(30),
|
||||
b_frames: 2,
|
||||
coding_order: false,
|
||||
level: None,
|
||||
cabac: None,
|
||||
full_range: true,
|
||||
@@ -1259,6 +1321,233 @@ pub(crate) mod tests {
|
||||
(luma, chroma, row)
|
||||
}
|
||||
|
||||
/// Each picture of an Annex-B access unit of `hevc` or H.264: whether
|
||||
/// it is a reference (H.264's `nal_ref_idc` above 0, HEVC's `TRAIL_R`
|
||||
/// or IRAP), its order count (its `pic_order_cnt_lsb`, or H.264's POC
|
||||
/// type 2's from its `frame_num`) and the count it wraps at; the
|
||||
/// stream's `max_num_reorder_frames` (HEVC's
|
||||
/// `sps_max_num_reorder_pics`); and H.264's `pic_order_cnt_type` (0 for
|
||||
/// HEVC), from the parameter sets the units before it carried, kept in
|
||||
/// `sets`.
|
||||
fn pictures_of(
|
||||
hevc: bool,
|
||||
au: &[u8],
|
||||
sets: &mut (Vec<Vec<u8>>, Vec<Vec<u8>>),
|
||||
) -> Result<Vec<(bool, u32, u32, usize, u8)>, Box<dyn std::error::Error>> {
|
||||
use crate::codec::{h264, hevc as h265};
|
||||
let mut out = Vec::new();
|
||||
for unit in crate::codec::encode::nal::split_annex_b(au) {
|
||||
let kind = if hevc {
|
||||
(unit[0] >> 1) & 0x3f
|
||||
} else {
|
||||
unit[0] & 0x1f
|
||||
};
|
||||
match (hevc, kind) {
|
||||
(false, 7) | (true, 33) => sets.0 = vec![unit.to_vec()],
|
||||
(false, 8) | (true, 34) => sets.1 = vec![unit.to_vec()],
|
||||
(false, 1 | 5) => {
|
||||
let sps = Arc::new(h264::sps::Sps::parse(&sets.0[0])?);
|
||||
let pps = Arc::new(h264::pps::Pps::parse(&sets.1[0], |_| {
|
||||
Some(Arc::clone(&sps))
|
||||
})?);
|
||||
let nal = h264::nal::NalUnit::new(unit)?;
|
||||
let slice = h264::slice::SliceHeader::parse(
|
||||
nal,
|
||||
|_| Some(Arc::clone(&pps)),
|
||||
|_| Some(Arc::clone(&sps)),
|
||||
)?;
|
||||
let reorder = sps.max_num_reorder_frames();
|
||||
let reference = slice.nal_ref_idc > 0;
|
||||
// POC type 2's count, from frame_num (8.2.1.3), the
|
||||
// pictures here being within frame_num's first wrap.
|
||||
let (count, wrap) = if sps.pic_order_cnt_type == 2 {
|
||||
let frames = 1u32 << (sps.log2_max_frame_num_minus4 + 4);
|
||||
let count = 2 * slice.frame_num - u32::from(!reference);
|
||||
(count, 2 * frames)
|
||||
} else {
|
||||
let wrap = 1 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
|
||||
(slice.pic_order_cnt_lsb, wrap)
|
||||
};
|
||||
out.push((reference, count, wrap, reorder, sps.pic_order_cnt_type));
|
||||
}
|
||||
(true, 0..=21) => {
|
||||
let sps = Arc::new(h265::sps::Sps::parse(&sets.0[0])?);
|
||||
let pps = Arc::new(h265::pps::Pps::parse(&sets.1[0])?);
|
||||
let nal = h265::nal::NalUnit::new(unit)?;
|
||||
let slice = h265::slice::SliceHeader::parse(
|
||||
nal,
|
||||
|_| Some(Arc::clone(&pps)),
|
||||
|_| Some(Arc::clone(&sps)),
|
||||
None,
|
||||
)?;
|
||||
let reorder = usize::from(sps.highest_ordering().max_num_reorder_pics);
|
||||
let wrap = 1 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
|
||||
let reference = kind % 2 == 1 || kind >= 16;
|
||||
out.push((reference, slice.slice_pic_order_cnt_lsb, wrap, reorder, 0));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A session in coding order ([`EncodeParams::coding_order`]) codes
|
||||
/// frames sent as AppleGVA's encoders send them with reordering allowed,
|
||||
/// each reference before the frame shown ahead of it (`0 2 1 4 3 ... 14
|
||||
/// 13 15`): each packet is its frame's, out as the frame goes in; a frame
|
||||
/// sent after a later one is a B picture, no reference; each picture's
|
||||
/// order count follows its place (H.264's twice it), and the SPS lets a
|
||||
/// frame come out of display order. H.264 High and HEVC Main. The same
|
||||
/// frames sent in display order with `coding_order` set code as
|
||||
/// references in order, at their places' order counts; Baseline's too,
|
||||
/// which NVENC codes at POC type 2, whose order counts follow the order
|
||||
/// frames are coded in, so a Baseline frame sent behind a later one would
|
||||
/// not be shown before it (docs/video/bugs.md, B103).
|
||||
#[test]
|
||||
#[ignore = "needs an NVIDIA GPU: run on the NVIDIA host"]
|
||||
fn frames_in_coding_order_keep_their_places() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let gpu = Arc::new(crate::nvidia::cuda::Gpu::open(
|
||||
&crate::nvidia::cuda::GpuSelector::First,
|
||||
)?);
|
||||
let mut reordered = vec![0u64];
|
||||
for pair in 0..7 {
|
||||
reordered.extend([pair * 2 + 2, pair * 2 + 1]);
|
||||
}
|
||||
reordered.push(15);
|
||||
let in_order: Vec<u64> = (0..16).collect();
|
||||
for (profile, places) in [
|
||||
(EncodeProfile::H264High, &reordered),
|
||||
(EncodeProfile::HevcMain, &reordered),
|
||||
(EncodeProfile::H264Baseline, &in_order),
|
||||
(EncodeProfile::H264High, &in_order),
|
||||
(EncodeProfile::HevcMain, &in_order),
|
||||
] {
|
||||
let what = format!("{profile:?} places {places:?}");
|
||||
let params = EncodeParams {
|
||||
b_frames: 0,
|
||||
coding_order: true,
|
||||
gop_length: None,
|
||||
cabac: None,
|
||||
..params(profile)
|
||||
};
|
||||
let hevc = profile.is_hevc();
|
||||
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), ¶ms)?;
|
||||
let mut sets = (Vec::new(), Vec::new());
|
||||
for (n, &place) in places.iter().enumerate() {
|
||||
let (luma, chroma, row) = noise(¶ms, place);
|
||||
let packets = encoder.encode(&RawFrame {
|
||||
luma: (&luma, row),
|
||||
chroma: (&chroma, row),
|
||||
index: place,
|
||||
force_idr: false,
|
||||
})?;
|
||||
assert_eq!(packets.len(), 1, "{what} frame {n}");
|
||||
let packet = packets.into_iter().next().unwrap()?;
|
||||
assert_eq!(packet.index, place, "{what} frame {n}");
|
||||
let pictures = pictures_of(hevc, &packet.data, &mut sets)?;
|
||||
assert_eq!(pictures.len(), 1, "{what} frame {n}");
|
||||
let (reference, lsb, wrap, reorder, poc_type) = pictures[0];
|
||||
// NVENC chooses H.264's POC type itself: 2 for Baseline, whose
|
||||
// order counts follow the order frames are coded in.
|
||||
assert_eq!(
|
||||
poc_type == 2,
|
||||
profile == EncodeProfile::H264Baseline,
|
||||
"{what} frame {n}: POC type {poc_type}"
|
||||
);
|
||||
let behind = n > 0 && place < places[n - 1];
|
||||
assert_eq!(reference, !behind, "{what} frame {n}");
|
||||
let scale = if hevc { 1 } else { 2 };
|
||||
assert_eq!(
|
||||
u64::from(lsb),
|
||||
place * scale % u64::from(wrap),
|
||||
"{what} frame {n}"
|
||||
);
|
||||
assert!(
|
||||
reorder >= 1 || !profile.has_b_slices(),
|
||||
"{what} frame {n}: the SPS's reorder {reorder}"
|
||||
);
|
||||
let want = match (n, behind, profile.has_b_slices()) {
|
||||
(0, _, _) => PictureType::Idr,
|
||||
(_, false, _) => PictureType::Predicted,
|
||||
(_, true, true) => PictureType::Bidirectional,
|
||||
(_, true, false) => PictureType::NonReferencePredicted,
|
||||
};
|
||||
assert_eq!(packet.picture_type, want, "{what} frame {n}");
|
||||
}
|
||||
assert!(encoder.flush()?.is_empty(), "{what}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A session in coding order that codes frames in place
|
||||
/// ([`NvencEncoder::new_in_place`]), as the guest's HEVC driver sends the
|
||||
/// plug-in's frames with reordering allowed (`0 2 1 4 3 6 5`), P picture
|
||||
/// 2 and B picture 1 each coded again in its place: each try is its
|
||||
/// frame's, of the first try's picture type, order count and reference
|
||||
/// flag, and the frames after it keep theirs. HEVC Main.
|
||||
#[test]
|
||||
#[ignore = "needs an NVIDIA GPU: run on the NVIDIA host"]
|
||||
fn frames_in_coding_order_are_coded_again_in_place() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let gpu = Arc::new(crate::nvidia::cuda::Gpu::open(
|
||||
&crate::nvidia::cuda::GpuSelector::First,
|
||||
)?);
|
||||
let params = EncodeParams {
|
||||
b_frames: 0,
|
||||
coding_order: true,
|
||||
gop_length: None,
|
||||
cabac: None,
|
||||
..params(EncodeProfile::HevcMain)
|
||||
};
|
||||
let mut encoder = NvencEncoder::new_in_place(Arc::clone(&gpu), ¶ms)?;
|
||||
let mut sets = (Vec::new(), Vec::new());
|
||||
let sends: [(u64, bool); 9] = [
|
||||
(0, false),
|
||||
(2, false),
|
||||
(2, true),
|
||||
(1, false),
|
||||
(1, true),
|
||||
(4, false),
|
||||
(3, false),
|
||||
(6, false),
|
||||
(5, false),
|
||||
];
|
||||
let mut tries: Vec<(PictureType, bool)> = Vec::new();
|
||||
for (n, &(place, again)) in sends.iter().enumerate() {
|
||||
let (luma, chroma, row) = noise(¶ms, place);
|
||||
let frame = RawFrame {
|
||||
luma: (&luma, row),
|
||||
chroma: (&chroma, row),
|
||||
index: place,
|
||||
force_idr: false,
|
||||
};
|
||||
let packets = if again {
|
||||
encoder.encode_in_place(&frame)?
|
||||
} else {
|
||||
encoder.encode(&frame)?
|
||||
};
|
||||
assert_eq!(packets.len(), 1, "try {n}");
|
||||
let packet = packets.into_iter().next().unwrap()?;
|
||||
assert_eq!(packet.index, place, "try {n}");
|
||||
let pictures = pictures_of(true, &packet.data, &mut sets)?;
|
||||
assert_eq!(pictures.len(), 1, "try {n}");
|
||||
let (reference, lsb, _, reorder, _) = pictures[0];
|
||||
assert_eq!(u64::from(lsb), place, "try {n}");
|
||||
assert_eq!(reference, place % 2 == 0, "try {n}");
|
||||
assert!(reorder >= 1, "try {n}: the SPS's reorder {reorder}");
|
||||
if again {
|
||||
assert_eq!(
|
||||
(packet.picture_type, reference),
|
||||
tries[n - 1],
|
||||
"try {n} against the first"
|
||||
);
|
||||
}
|
||||
tries.push((packet.picture_type, reference));
|
||||
}
|
||||
assert_eq!(tries[0].0, PictureType::Idr);
|
||||
assert!(encoder.flush()?.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What a raw `nvEncLockBitstream` answers for a 4K picture, in turn:
|
||||
/// with `doNotWait` as soon as the picture is submitted, with
|
||||
/// `doNotWait` 40 ms later, and waiting 40 ms later; each with how long
|
||||
@@ -1277,6 +1566,7 @@ pub(crate) mod tests {
|
||||
width: 3840,
|
||||
height: 2160,
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
..params(EncodeProfile::HevcMain)
|
||||
};
|
||||
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), ¶ms)?;
|
||||
@@ -1301,6 +1591,7 @@ pub(crate) mod tests {
|
||||
timestamp: u64::from(n),
|
||||
idr: (n / 3) % 2 == 0,
|
||||
unadvanced: false,
|
||||
planned: None,
|
||||
})?;
|
||||
let submit = StdRuntime.elapsed_since(submitting).as_micros();
|
||||
let handle = session.output(output, &[BufferKind::Bitstream])?;
|
||||
@@ -1378,6 +1669,7 @@ pub(crate) mod tests {
|
||||
width: 3840,
|
||||
height: 2160,
|
||||
b_frames: 2,
|
||||
coding_order: false,
|
||||
..params(EncodeProfile::HevcMain)
|
||||
};
|
||||
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), ¶ms)?;
|
||||
|
||||
@@ -681,14 +681,46 @@ pub(crate) struct NV_ENC_PRESET_CONFIG {
|
||||
pub(crate) reserved2: [*mut c_void; 64],
|
||||
}
|
||||
|
||||
/// `NV_ENC_CODEC_PIC_PARAMS`: the codecs' per-picture parameters, which a
|
||||
/// session with picture type decision leaves zero.
|
||||
/// `NV_ENC_CODEC_PIC_PARAMS`: the codecs' per-picture parameters, a union of
|
||||
/// `NV_ENC_PIC_PARAMS_H264` and `NV_ENC_PIC_PARAMS_HEVC` among others, which
|
||||
/// a session with picture type decision leaves zero, and one without sets
|
||||
/// the display order count and reference flag of ([`Self::set_order`]).
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct NV_ENC_CODEC_PIC_PARAMS {
|
||||
pub(crate) reserved: [u64; 193],
|
||||
}
|
||||
|
||||
/// Byte offsets in `NV_ENC_PIC_PARAMS_H264`, as `crate::nvidia::layout`'s
|
||||
/// test checks against the header: `displayPOCSyntax` and `refPicFlag`.
|
||||
pub(crate) const H264_DISPLAY_POC_SYNTAX: usize = 0;
|
||||
pub(crate) const H264_REF_PIC_FLAG: usize = 8;
|
||||
/// The same of `NV_ENC_PIC_PARAMS_HEVC`.
|
||||
pub(crate) const HEVC_DISPLAY_POC_SYNTAX: usize = 0;
|
||||
pub(crate) const HEVC_REF_PIC_FLAG: usize = 4;
|
||||
|
||||
impl NV_ENC_CODEC_PIC_PARAMS {
|
||||
/// Sets the codec's member's `displayPOCSyntax` to `display_poc` and its
|
||||
/// `refPicFlag` to `reference`: HEVC's where `hevc`, else H.264's.
|
||||
pub(crate) fn set_order(&mut self, hevc: bool, display_poc: u32, reference: bool) {
|
||||
let (poc, flag) = if hevc {
|
||||
(HEVC_DISPLAY_POC_SYNTAX, HEVC_REF_PIC_FLAG)
|
||||
} else {
|
||||
(H264_DISPLAY_POC_SYNTAX, H264_REF_PIC_FLAG)
|
||||
};
|
||||
self.put(poc, display_poc);
|
||||
self.put(flag, u32::from(reference));
|
||||
}
|
||||
|
||||
/// Writes `value` as the 32-bit word at byte `offset`, a multiple of 4.
|
||||
fn put(&mut self, offset: usize, value: u32) {
|
||||
let shift = (offset % 8) * 8;
|
||||
if let Some(word) = self.reserved.get_mut(offset / 8) {
|
||||
*word = (*word & !(0xffff_ffff_u64 << shift)) | (u64::from(value) << shift);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `NV_ENC_PIC_PARAMS`.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
|
||||
@@ -6,8 +6,12 @@
|
||||
//! encodes a profile (the NVIDIA crate's `encode_profiles`), with those profiles, NV12 sources
|
||||
//! (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. It codes a frame in place of the last one
|
||||
//! NVENC lists them, and no B-frames of its own: the encoder keeps frames in the order they
|
||||
//! come, a frame in and its access unit out. They come in display order, or in the order the
|
||||
//! guest codes them where its settings say so (`RGFX_VIDEO_ENCODE_CAP_REORDERED`), each at its
|
||||
//! place, its `frame_index`, which the NVIDIA crate's session codes in coding order, its
|
||||
//! picture type decision off (`EncodeParams::coding_order`). 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
|
||||
@@ -50,15 +54,15 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_graphics::ops::video::{
|
||||
RGFX_VIDEO_ENTROPY_CABAC, RGFX_VIDEO_ENTROPY_CAVLC, RGFX_VIDEO_PICTURE_B, RGFX_VIDEO_PICTURE_I,
|
||||
RGFX_VIDEO_PICTURE_P, RGFX_VIDEO_RATE_CBR, RGFX_VIDEO_RATE_CQP, RGFX_VIDEO_RATE_VBR,
|
||||
RgfxVideoEncodeSettings,
|
||||
RGFX_VIDEO_ENCODE_REORDERED, RGFX_VIDEO_ENTROPY_CABAC, RGFX_VIDEO_ENTROPY_CAVLC,
|
||||
RGFX_VIDEO_PICTURE_B, RGFX_VIDEO_PICTURE_I, RGFX_VIDEO_PICTURE_P, RGFX_VIDEO_RATE_CBR,
|
||||
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_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,
|
||||
RGFX_VIDEO_ENCODE_CAP_IN_PLACE, RGFX_VIDEO_ENCODE_CAP_REORDERED, 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,
|
||||
@@ -195,9 +199,9 @@ pub(super) fn checked_in_place(
|
||||
}
|
||||
|
||||
/// 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, no B-frames, and frames coded in
|
||||
/// place where every profile codes them ([`checked_in_place`]; module doc); all zero for a
|
||||
/// decode entry.
|
||||
/// and VBR where NVENC lists them for each of its profiles, no B-frames, frames in the guest's
|
||||
/// coding order, 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],
|
||||
@@ -217,11 +221,12 @@ pub(super) fn encode_caps(
|
||||
RgfxVideoEncodeCaps {
|
||||
rate_controls,
|
||||
max_b_frames: 0,
|
||||
flags: if in_place {
|
||||
RGFX_VIDEO_ENCODE_CAP_IN_PLACE
|
||||
} else {
|
||||
0
|
||||
},
|
||||
flags: RGFX_VIDEO_ENCODE_CAP_REORDERED
|
||||
| if in_place {
|
||||
RGFX_VIDEO_ENCODE_CAP_IN_PLACE
|
||||
} else {
|
||||
0
|
||||
},
|
||||
reserved_0c: 0,
|
||||
}
|
||||
}
|
||||
@@ -348,6 +353,7 @@ pub(super) fn params_of(
|
||||
},
|
||||
gop_length: (settings.key_frame_interval > 0).then_some(settings.key_frame_interval),
|
||||
b_frames: 0,
|
||||
coding_order: settings.flags & RGFX_VIDEO_ENCODE_REORDERED != 0,
|
||||
level: (settings.level > 0).then_some(settings.level),
|
||||
cabac: match settings.entropy {
|
||||
RGFX_VIDEO_ENTROPY_CAVLC => Some(false),
|
||||
@@ -364,13 +370,15 @@ pub(super) fn params_of(
|
||||
}
|
||||
|
||||
/// Whether `new` starts a new sequence after `old` (the wire's settings doc): another size,
|
||||
/// format, profile, level, entropy coder, B-frames, keyframe interval or colour.
|
||||
/// format, profile, level, entropy coder, B-frames, keyframe interval, colour or frame order
|
||||
/// (`RGFX_VIDEO_ENCODE_REORDERED`).
|
||||
fn new_sequence(old: &RgfxVideoEncodeSettings, new: &RgfxVideoEncodeSettings) -> bool {
|
||||
let sequence = |s: &RgfxVideoEncodeSettings| {
|
||||
(
|
||||
(s.width, s.height, s.format, s.profile, s.level),
|
||||
(s.entropy, s.b_frames, s.key_frame_interval),
|
||||
(s.color_primaries, s.transfer, s.matrix, s.full_range),
|
||||
s.flags & RGFX_VIDEO_ENCODE_REORDERED,
|
||||
)
|
||||
};
|
||||
sequence(old) != sequence(new)
|
||||
|
||||
@@ -141,6 +141,7 @@ fn params_of(config: &EncoderConfig) -> Result<EncodeParams, VideoError> {
|
||||
buffer_milliseconds: s.buffer_milliseconds,
|
||||
gop_length: None,
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
level: s.level.map(u32::from),
|
||||
cabac: (s.profile.codec() == EncodeCodec::H264).then(|| s.h264_entropy() == Entropy::Cabac),
|
||||
full_range: s.full_range,
|
||||
|
||||
@@ -104,6 +104,7 @@ fn the_nvenc_settings_of_a_guests() {
|
||||
buffer_milliseconds: 500,
|
||||
gop_length: None,
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
level: Some(42),
|
||||
cabac: Some(true),
|
||||
full_range: true,
|
||||
|
||||
@@ -75,21 +75,18 @@ fn frames_are_coded_in_place_where_every_profile_of_the_codec_is() {
|
||||
.map(|e| encode_caps(e, supports).flags)
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(flags(&supports), [RGFX_VIDEO_ENCODE_CAP_IN_PLACE, 0]);
|
||||
// Every encode entry takes frames in the guest's coding order.
|
||||
let both = RGFX_VIDEO_ENCODE_CAP_IN_PLACE | RGFX_VIDEO_ENCODE_CAP_REORDERED;
|
||||
let reordered = RGFX_VIDEO_ENCODE_CAP_REORDERED;
|
||||
assert_eq!(flags(&supports), [both, reordered]);
|
||||
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
|
||||
]
|
||||
);
|
||||
assert_eq!(flags(&all), [both, both]);
|
||||
let none = all.map(|s| EncodeProfileSupport {
|
||||
in_place: false,
|
||||
..s
|
||||
});
|
||||
assert_eq!(flags(&none), [0, 0]);
|
||||
assert_eq!(flags(&none), [reordered, reordered]);
|
||||
let decode = RgfxVideoCodecCaps {
|
||||
direction: RGFX_VIDEO_DECODE,
|
||||
..entries[0]
|
||||
@@ -190,6 +187,14 @@ fn the_nvenc_settings_of_the_wire_s() {
|
||||
(None, None, false)
|
||||
);
|
||||
assert_eq!((made.preset, made.tuning), (1, Tuning::HighQuality));
|
||||
assert!(!made.coding_order);
|
||||
let reordered = RgfxVideoEncodeSettings {
|
||||
flags: RGFX_VIDEO_ENCODE_REORDERED,
|
||||
..base
|
||||
};
|
||||
let made_reordered = params_of(RGFX_VIDEO_CODEC_H264, &reordered).unwrap();
|
||||
assert!(made_reordered.coding_order);
|
||||
assert_eq!(made_reordered.b_frames, 0);
|
||||
let made = params_of(
|
||||
RGFX_VIDEO_CODEC_H264,
|
||||
&RgfxVideoEncodeSettings {
|
||||
@@ -270,6 +275,10 @@ fn what_starts_a_new_sequence() {
|
||||
entropy: RGFX_VIDEO_ENTROPY_CAVLC,
|
||||
..old
|
||||
},
|
||||
RgfxVideoEncodeSettings {
|
||||
flags: RGFX_VIDEO_ENCODE_REORDERED,
|
||||
..old
|
||||
},
|
||||
] {
|
||||
assert!(new_sequence(&old, &new));
|
||||
}
|
||||
|
||||
@@ -63,6 +63,7 @@ fn params(profile: EncodeProfile, width: u32, height: u32) -> EncodeParams {
|
||||
buffer_milliseconds: 1000,
|
||||
gop_length: Some(30),
|
||||
b_frames: 0,
|
||||
coding_order: false,
|
||||
level: None,
|
||||
cabac: None,
|
||||
full_range: false,
|
||||
|
||||
@@ -8,8 +8,11 @@
|
||||
//! 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 for any of its profiles, and an encode's settings are held to their
|
||||
//! profile's own as they are checked ([`profile_takes_rate`]); no B-frames: the encoder keeps
|
||||
//! frames in display order. It codes a frame in place of the last one
|
||||
//! profile's own as they are checked ([`profile_takes_rate`]); no B-frames of its own: the
|
||||
//! encoder keeps frames in the order they come. They come in display order, or in the order the
|
||||
//! guest codes them where its settings say so (`RGFX_VIDEO_ENCODE_CAP_REORDERED`), each at its
|
||||
//! place, its `frame_index`, which the VA crate's encoder codes in coding order
|
||||
//! (`EncoderSettings::coding_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
|
||||
@@ -56,15 +59,15 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_graphics::ops::video::{
|
||||
RGFX_VIDEO_ENCODE_HARD_LIMIT, RGFX_VIDEO_ENTROPY_CABAC, RGFX_VIDEO_ENTROPY_CAVLC,
|
||||
RGFX_VIDEO_PICTURE_B, RGFX_VIDEO_PICTURE_I, RGFX_VIDEO_PICTURE_P, RGFX_VIDEO_RATE_CBR,
|
||||
RGFX_VIDEO_RATE_CQP, RGFX_VIDEO_RATE_VBR, RgfxVideoEncodeSettings,
|
||||
RGFX_VIDEO_ENCODE_HARD_LIMIT, RGFX_VIDEO_ENCODE_REORDERED, RGFX_VIDEO_ENTROPY_CABAC,
|
||||
RGFX_VIDEO_ENTROPY_CAVLC, RGFX_VIDEO_PICTURE_B, RGFX_VIDEO_PICTURE_I, RGFX_VIDEO_PICTURE_P,
|
||||
RGFX_VIDEO_RATE_CBR, 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_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,
|
||||
RGFX_VIDEO_ENCODE_CAP_IN_PLACE, RGFX_VIDEO_ENCODE_CAP_REORDERED, 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,
|
||||
@@ -217,7 +220,7 @@ pub(super) fn encode_caps(
|
||||
RgfxVideoEncodeCaps {
|
||||
rate_controls,
|
||||
max_b_frames: 0,
|
||||
flags: RGFX_VIDEO_ENCODE_CAP_IN_PLACE,
|
||||
flags: RGFX_VIDEO_ENCODE_CAP_IN_PLACE | RGFX_VIDEO_ENCODE_CAP_REORDERED,
|
||||
reserved_0c: 0,
|
||||
}
|
||||
}
|
||||
@@ -338,6 +341,7 @@ pub(super) fn settings_of(
|
||||
out.allow_frame_reordering = false;
|
||||
out.max_frame_delay = Some(0);
|
||||
out.b_frames = Some(0);
|
||||
out.coding_order = settings.flags & RGFX_VIDEO_ENCODE_REORDERED != 0;
|
||||
out.level = (settings.level > 0)
|
||||
.then(|| u8::try_from(settings.level).ok())
|
||||
.flatten();
|
||||
@@ -351,13 +355,15 @@ pub(super) fn settings_of(
|
||||
}
|
||||
|
||||
/// Whether `new` starts a new sequence after `old` (the wire's settings doc): another size,
|
||||
/// format, profile, level, entropy coder, B-frames, keyframe interval or colour.
|
||||
/// format, profile, level, entropy coder, B-frames, keyframe interval, colour or frame order
|
||||
/// (`RGFX_VIDEO_ENCODE_REORDERED`).
|
||||
fn new_sequence(old: &RgfxVideoEncodeSettings, new: &RgfxVideoEncodeSettings) -> bool {
|
||||
let sequence = |s: &RgfxVideoEncodeSettings| {
|
||||
(
|
||||
(s.width, s.height, s.format, s.profile, s.level),
|
||||
(s.entropy, s.b_frames, s.key_frame_interval),
|
||||
(s.color_primaries, s.transfer, s.matrix, s.full_range),
|
||||
s.flags & RGFX_VIDEO_ENCODE_REORDERED,
|
||||
)
|
||||
};
|
||||
sequence(old) != sequence(new)
|
||||
|
||||
@@ -203,6 +203,10 @@ fn what_starts_a_new_sequence() {
|
||||
entropy: RGFX_VIDEO_ENTROPY_CAVLC,
|
||||
..old
|
||||
},
|
||||
RgfxVideoEncodeSettings {
|
||||
flags: RGFX_VIDEO_ENCODE_REORDERED,
|
||||
..old
|
||||
},
|
||||
] {
|
||||
assert!(new_sequence(&old, &new));
|
||||
}
|
||||
@@ -218,6 +222,10 @@ fn what_starts_a_new_sequence() {
|
||||
average_bitrate: 1_000_000,
|
||||
..old
|
||||
},
|
||||
RgfxVideoEncodeSettings {
|
||||
flags: RGFX_VIDEO_ENCODE_HARD_LIMIT,
|
||||
..old
|
||||
},
|
||||
] {
|
||||
assert!(!new_sequence(&old, &new));
|
||||
}
|
||||
@@ -225,7 +233,8 @@ fn what_starts_a_new_sequence() {
|
||||
|
||||
/// The VA crate's settings of the wire's: the profile of each bit, the frame rate's numerator
|
||||
/// the clock (30 a second where it says none), the level, entropy, keyframe interval, colour
|
||||
/// and hard limit as given, and frames in display order.
|
||||
/// and hard limit as given, and no B-frames of its own: frames in display order, or in the
|
||||
/// guest's coding order where the settings say so.
|
||||
#[test]
|
||||
fn the_va_settings_of_the_wire_s() {
|
||||
let made = settings_of(
|
||||
@@ -266,6 +275,18 @@ fn the_va_settings_of_the_wire_s() {
|
||||
assert_eq!(made.quality_level, Some(1));
|
||||
assert!(!made.allow_frame_reordering);
|
||||
assert_eq!((made.b_frames, made.max_frame_delay), (Some(0), Some(0)));
|
||||
assert!(!made.coding_order);
|
||||
let reordered = settings_of(
|
||||
RGFX_VIDEO_CODEC_H264,
|
||||
&RgfxVideoEncodeSettings {
|
||||
flags: RGFX_VIDEO_ENCODE_REORDERED | RGFX_VIDEO_ENCODE_HARD_LIMIT,
|
||||
..settings(RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_H264_MAIN)
|
||||
},
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(reordered.coding_order && !reordered.allow_frame_reordering);
|
||||
assert_eq!(reordered.b_frames, Some(0));
|
||||
|
||||
let plain = settings_of(
|
||||
RGFX_VIDEO_CODEC_HEVC,
|
||||
@@ -296,8 +317,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; and it codes frames in place, H.264's and HEVC's alike. A decode entry lists
|
||||
/// none of it.
|
||||
/// configs list; and it codes frames in place and takes them in the guest's coding order,
|
||||
/// 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 {
|
||||
@@ -306,7 +327,7 @@ fn an_encode_entry_lists_its_configs_rate_controls() {
|
||||
..RgfxVideoCodecCaps::default()
|
||||
};
|
||||
let in_place = RgfxVideoEncodeCaps {
|
||||
flags: RGFX_VIDEO_ENCODE_CAP_IN_PLACE,
|
||||
flags: RGFX_VIDEO_ENCODE_CAP_IN_PLACE | RGFX_VIDEO_ENCODE_CAP_REORDERED,
|
||||
..RgfxVideoEncodeCaps::default()
|
||||
};
|
||||
assert_eq!(encode_caps(&entry, &[]), in_place);
|
||||
@@ -700,6 +721,154 @@ fn frames_coded_in_place_decode_back_in_their_places() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The places in display order of 30 frames as AppleGVA's encoders send them with reordering
|
||||
/// allowed: each reference before the frame shown ahead of it, `0 2 1 4 3 ... 28 27 29`.
|
||||
pub(super) fn coding_order_places() -> Vec<u64> {
|
||||
let mut places = vec![0];
|
||||
for pair in 0..14 {
|
||||
places.extend([pair * 2 + 2, pair * 2 + 1]);
|
||||
}
|
||||
places.push(29);
|
||||
places
|
||||
}
|
||||
|
||||
/// Which of the pictures `candidates` (by [`picture`] index) of `s` the decoded `frame` is: the
|
||||
/// one its luma is nearest, by the sum of absolute differences.
|
||||
fn nearest_picture(
|
||||
frame: &reims_vgpu_video::vaapi::Frame,
|
||||
s: &RgfxVideoEncodeSettings,
|
||||
candidates: &[u64],
|
||||
) -> u64 {
|
||||
let (w, h) = (s.width as usize, s.height as usize);
|
||||
let deep = s.format == RGFX_VIDEO_FORMAT_P010;
|
||||
let sample = if deep { 2 } else { 1 };
|
||||
let (mut y, mut uv) = (vec![0u8; w * h * sample], vec![0u8; w * h / 2 * sample]);
|
||||
if deep {
|
||||
frame.copy_p010_to(&mut y, w * 2, &mut uv, w * 2)
|
||||
} else {
|
||||
frame.copy_nv12_to(&mut y, w, &mut uv, w)
|
||||
}
|
||||
.expect("the frame's read back");
|
||||
let lumas = |plane: &[u8]| -> Vec<i64> {
|
||||
if deep {
|
||||
(plane.chunks_exact(2))
|
||||
.map(|b| i64::from(u16::from_le_bytes([b[0], b[1]]) >> 8))
|
||||
.collect()
|
||||
} else {
|
||||
plane.iter().map(|&b| i64::from(b)).collect()
|
||||
}
|
||||
};
|
||||
let decoded = lumas(&y);
|
||||
*(candidates.iter())
|
||||
.min_by_key(|&&k| {
|
||||
let (want, _) = picture(s, k);
|
||||
let want = lumas(&want);
|
||||
(decoded.iter().zip(&want))
|
||||
.map(|(a, b)| (a - b).abs())
|
||||
.sum::<i64>()
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// On the driver, each codec and profile it encodes, frames sent in the guest's coding order
|
||||
/// (`RGFX_VIDEO_ENCODE_REORDERED`) as AppleGVA's encoders send them with reordering allowed
|
||||
/// ([`coding_order_places`]): the pairs a guest's screen recording showed swapped, and the case
|
||||
/// whose stream decoded back with 28 frames out of order on an Iris Xe guest (2026-11-16). Each
|
||||
/// access unit is its frame's, a keyframe only first; the driver's own decoder gives each frame
|
||||
/// the order count of its place (H.264's twice it), and in order-count order each frame is its
|
||||
/// own picture, none before one it follows.
|
||||
/// Passes with a note where the driver lists no encoder (`listed_encoders`).
|
||||
#[test]
|
||||
#[ignore = "needs a VA-API GPU: run on the VA-API host"]
|
||||
fn frames_sent_in_coding_order_decode_back_in_display_order() {
|
||||
let display = display();
|
||||
let Some(supports) = listed_encoders(&display, &node()) else {
|
||||
return;
|
||||
};
|
||||
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 places = coding_order_places();
|
||||
let frames: Vec<(u64, bool, u32)> = places.iter().map(|&p| (p, false, 26)).collect();
|
||||
for entry in &entries {
|
||||
assert_ne!(
|
||||
encode_caps(entry, &supports).flags & RGFX_VIDEO_ENCODE_CAP_REORDERED,
|
||||
0
|
||||
);
|
||||
for bit in (0..32)
|
||||
.map(|b| 1u32 << b)
|
||||
.filter(|b| entry.profiles & b != 0)
|
||||
{
|
||||
let s = RgfxVideoEncodeSettings {
|
||||
flags: RGFX_VIDEO_ENCODE_REORDERED,
|
||||
..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::new();
|
||||
for (n, (try_, &place)) in coded.iter().zip(&places).enumerate() {
|
||||
let (encoded, au) = try_
|
||||
.as_ref()
|
||||
.unwrap_or_else(|e| panic!("{what} frame {n}: {e}"));
|
||||
assert_eq!(encoded.frame_index, place, "{what} frame {n}");
|
||||
assert!(!encoded.overflow, "{what} frame {n}");
|
||||
assert_eq!(encoded.keyframe, n == 0, "{what} frame {n}");
|
||||
units.push(au.clone());
|
||||
}
|
||||
let mut decoded = Vec::new();
|
||||
if entry.codec == RGFX_VIDEO_CODEC_H264 {
|
||||
let mut decoder = H264Decoder::new_annex_b(&display);
|
||||
for (id, au) in units.iter().enumerate() {
|
||||
decoded.extend(decoder.decode(au, id as u64).unwrap());
|
||||
}
|
||||
decoded.extend(decoder.flush().unwrap());
|
||||
} else {
|
||||
let mut decoder = HevcDecoder::new_annex_b(&display);
|
||||
for (id, au) in units.iter().enumerate() {
|
||||
decoded.extend(decoder.decode(au, id as u64).unwrap());
|
||||
}
|
||||
decoded.extend(decoder.flush().unwrap());
|
||||
}
|
||||
assert_eq!(decoded.len(), places.len(), "{what}");
|
||||
let scale = if entry.codec == RGFX_VIDEO_CODEC_H264 {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
for frame in &decoded {
|
||||
let place = places[frame.id() as usize];
|
||||
assert_eq!(
|
||||
frame.poc(),
|
||||
place as i32 * scale,
|
||||
"{what} sample {}",
|
||||
frame.id()
|
||||
);
|
||||
}
|
||||
decoded.sort_by_key(|frame| frame.poc());
|
||||
let shown: Vec<u64> = (decoded.iter())
|
||||
.map(|frame| {
|
||||
let place = places[frame.id() as usize];
|
||||
let near = [place.saturating_sub(1), place, place + 1];
|
||||
nearest_picture(frame, &s, &near)
|
||||
})
|
||||
.collect();
|
||||
let backwards = shown.windows(2).filter(|w| w[1] < w[0]).count();
|
||||
println!(
|
||||
"{what}: {} frames, {backwards} backwards in POC order",
|
||||
shown.len()
|
||||
);
|
||||
assert_eq!(
|
||||
shown,
|
||||
(0..places.len() as u64).collect::<Vec<_>>(),
|
||||
"{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
|
||||
|
||||
@@ -122,6 +122,13 @@ Everything known to be wrong, untested or put off in the reims-graphics device's
|
||||
- **Why it waits:** a measure-only run of the Mac host's order (3447). Playback, the owner's bar for video, keeps up.
|
||||
- **Fix:** pipelined decode, in the session and every arm's backend: several of the guest's asynchronous frames in flight, each frame's `Dbuf` sent as its `dfrm` comes, its copy and the copy's wait in flight while the next access units decode, and its `Demt` sent once its copy is done, in decode order, with no wait for each picture. The decode's one-at-a-time cost, the copy's wait and the round trips then add to one picture's latency rather than to each picture's time. The copy itself stays, counted as `video-vt-pictures-gpu-copied` (D29): no documented call has VideoToolbox decode into memory the host chooses (**read**, macOS 27.0 SDK). `kVTDecompressionPropertyKey_PixelBufferPool` is read-only (`VTDecompressionProperties.h`). `VTDecompressionSessionCreate` takes only what its emitted pixel buffers are to be (`destinationImageBufferAttributes`), and `VTDecompressionSessionDecodeFrame` takes no destination buffer (`VTDecompressionSession.h`). `IOSurfaceCreate`'s properties name no memory for the surface, only offsets into its own (`IOSurfaceRef.h`).
|
||||
|
||||
### B103. On NVENC, H.264 Baseline frames sent out of display order are shown in the order they came
|
||||
|
||||
- **What:** a stream in the guest's coding order (`RGFX_VIDEO_ENCODE_REORDERED`, [devices.md](devices.md), "An encode") has its frames placed by their order counts. NVENC chooses H.264's POC type itself, and codes Baseline, which has no B slices, at POC type 2, whose order counts follow `frame_num`, the order frames are coded in. So a Baseline frame sent behind a later one comes out after it. H.264 Main and High (with B pictures, at POC type 0), HEVC, and every profile on VA-API, which writes its own SPS at POC type 0, place such frames.
|
||||
- **Evidence:** **measured** on an RTX 3090 (gem10), 2026-12-04: in coding order, a Baseline session's frame sent second, at place 2, read a `pic_order_cnt_lsb` of 0 where 4 was asked (m3-max-87146); the Baseline stream's SPS says POC type 2, and H.264 High's 0 (m3-max-87165, `nvidia::nvenc::encoder::tests::frames_in_coding_order_keep_their_places`, which checks both and Baseline's frames in display order). **Read**: `NV_ENC_CONFIG_H264` has no POC type field (`crates/reims-vgpu-video/src/nvidia/nvenc/ffi.rs`).
|
||||
- **Why it waits:** no guest sends such a stream as far as known: AppleGVA's encoders send frames out of display order to code B pictures, which Baseline has none of, so a Baseline stream comes in display order, and NVENC codes that right. Not measured: no guest Baseline session with reordering allowed has been run.
|
||||
- **Fix, if a guest sends one:** NVENC takes no POC type, so the arm would refuse such a frame (`RGFX_VIDEO_ENCODE_FAILED`) rather than show it out of its place.
|
||||
|
||||
## Upstream bugs
|
||||
|
||||
Bugs in drivers, libraries and tools that our code or our checks work around.
|
||||
|
||||
+26
-4
@@ -386,9 +386,11 @@ the device info (`GraphicsDevice::with_platform`, in `graphics.rs`):
|
||||
`guest/bundle/src/RgfxVideoDriver.cpp`, `PixelRequirement`).
|
||||
- **What an encode entry takes**: an `RgfxVideoEncodeCaps` per entry (`encode`): the rate
|
||||
controls (a bit each of CQP, CBR and VBR, as the arm's API lists them for the codec's
|
||||
profiles), the most consecutive B pictures, 0 on both arms, whose encoders keep frames in
|
||||
display order, and in `flags`, `RGFX_VIDEO_ENCODE_CAP_IN_PLACE` where the arm codes a frame in
|
||||
place of the last one ("An encode", below): always on VA-API; on NVENC where NVENC says it
|
||||
profiles), the most consecutive B pictures, 0 on both arms, whose encoders make no B pictures
|
||||
of their own, and in `flags`: `RGFX_VIDEO_ENCODE_CAP_REORDERED` on both arms, which take
|
||||
frames in the order a guest's encoder codes them ("An encode", below); and
|
||||
`RGFX_VIDEO_ENCODE_CAP_IN_PLACE` where the arm codes a frame in
|
||||
place of the last one: always on VA-API; on NVENC where NVENC says it
|
||||
codes a frame without advancing its state (`NV_ENC_CAPS_DISABLE_ENC_STATE_ADVANCE`) for every
|
||||
profile of the codec, and a session of the codec with a state buffer coded a frame, the frame
|
||||
again in its place and a frame after it at the device's start (`checked_in_place`,
|
||||
@@ -569,7 +571,8 @@ buffer of an encode session's process (reims-vgpu's `graphics/video_host/encode.
|
||||
entry's sizes, and the buffers the access unit and its result go in. A refusal faults the
|
||||
command buffer.
|
||||
- **A change of settings** that makes a new sequence (the size, format, profile, level,
|
||||
entropy coder, B pictures, keyframe interval or colour) makes the arm a new encoder, whose
|
||||
entropy coder, B pictures, keyframe interval, colour or `RGFX_VIDEO_ENCODE_REORDERED`) makes
|
||||
the arm a new encoder, whose
|
||||
first access unit is a keyframe;
|
||||
a change of the bitrates, QPs or frame rate goes to the encoder from the next frame.
|
||||
`min_qp`, `max_qp` and a change of `quality` alone are not taken.
|
||||
@@ -584,6 +587,25 @@ buffer of an encode session's process (reims-vgpu's `graphics/video_host/encode.
|
||||
declines that copy (said once a session), the planes are read as host bytes, in the surface's
|
||||
pages, or, for a plane in a device cache, in a staging buffer the GPU copies it into first, and
|
||||
the encoder's upload copies them. The encoder codes the same bytes either way.
|
||||
- **Frames in coding order** (`RGFX_VIDEO_ENCODE_REORDERED` in the settings, from a guest that
|
||||
read the caps flag) come in the order the guest's encoder codes them, each at its place in
|
||||
display order, its `frame_index`, at most one frame ahead of its place. The x86-64 guest's
|
||||
driver sends a stream so where macOS's encoder codes B pictures (frame reordering allowed),
|
||||
its places from the order counts the encoder gives each picture
|
||||
([design.md](../graphics-kext/design.md), "Frames in coding order"). The arm codes each frame
|
||||
as it comes, at its place: an IDR picture at the stream's first frame, a forced keyframe, the
|
||||
keyframe interval, or a place not past its IDR picture's; a reference P picture where its place
|
||||
is past every place since its IDR picture; else a picture nothing predicts from, a B picture
|
||||
between the references before and after it where the profile codes B slices, or a P picture
|
||||
from the last reference (H.264 Baseline). Its order count is its place's (H.264's
|
||||
`pic_order_cnt_lsb` twice its distance from its IDR picture, HEVC's `PicOrderCntVal` that
|
||||
distance), and its SPS says one frame may come out of display order
|
||||
(`max_num_reorder_frames`, `sps_max_num_reorder_pics`), so a decoder puts the frames back in
|
||||
display order. The VA crate's encoder plans the pictures (`EncoderSettings::coding_order`,
|
||||
`CodingOrder` in `crates/reims-vgpu-video/src/codec/encode/gop.rs`); on NVENC the NVIDIA crate
|
||||
plans them the same way, and sets each picture's type, order count and reference flag with
|
||||
NVENC's picture type decision off (`EncodeParams::coding_order`). Without the flag the frames
|
||||
come in display order and the arms code them as before.
|
||||
- **A frame coded in place** (`RGFX_VIDEO_ENCODE_IN_PLACE`, from a guest that read the caps
|
||||
flag) replaces the last frame, whose access unit the guest drops: it is coded from the
|
||||
references the last one was coded from, with its order count, at the QP the settings give
|
||||
|
||||
@@ -378,6 +378,14 @@ H.264 or HEVC access units out, in decode order.
|
||||
lookahead off (below); `frameIntervalP` the B-frames plus 1, B-frames
|
||||
never references; NVENC decides each picture's type (`enablePTD`) by its
|
||||
GOP length, and an IDR picture is forced where the caller asks for one.
|
||||
Frames in coding order (`EncodeParams::coding_order`, each at its place,
|
||||
its `frameIdx`) turn NVENC's decision off: the session plans each picture
|
||||
as the VA crate's encoder does (`CodingOrder`, [vaapi.md](vaapi.md),
|
||||
"Shape"), and sets its type, its order count (`displayPOCSyntax`, twice
|
||||
the place for H.264) and whether it is a reference (`refPicFlag`), with
|
||||
`frameIntervalP` 2 where the profile has B slices. H.264 Baseline is
|
||||
coded at POC type 2, whose order counts follow the coding order
|
||||
([bugs.md](bugs.md), B103).
|
||||
NVENC writes its own parameter sets, before each IDR picture, and slice
|
||||
headers, and keeps its own references. The VBV holds the time asked at
|
||||
the peak rate; the VUI's colour and range are the caller's.
|
||||
|
||||
@@ -1551,6 +1551,17 @@ picture: the first sample carries the record it belongs with, and
|
||||
(`DEFAULT_B_FRAMES`) and at most 4, L0 two references and L1 one. A run
|
||||
of B pictures is closed with a P before an IDR. HEVC and Constrained
|
||||
Baseline are I and P only.
|
||||
- **Frames in coding order** (`EncoderSettings::coding_order`) come as an
|
||||
encoder above sends them, each at its own place (its PTS a whole number
|
||||
of frame durations from 0), and are planned as they come (`CodingOrder`):
|
||||
an IDR picture at the first frame, a forced key frame, the interval, or
|
||||
a place not past its IDR picture's; a reference P picture where the
|
||||
place is past every place since its IDR picture; else a picture nothing
|
||||
predicts from, a B picture between the references before and after it
|
||||
where the profile has B slices, or a P picture. Two references are held,
|
||||
and the SPS says one frame may come out of display order
|
||||
(`max_num_reorder_frames`, `sps_max_num_reorder_pics`). The samples'
|
||||
DTSes are a grid of frame durations from one before the first frame's.
|
||||
- **Time stamps.** Each sample's DTS is the PTS of the frame sent in its
|
||||
place: without reordering DTS equals PTS, and with it `I0 P2 B1` gets
|
||||
DTSes 0, 1 and 2 frames, so a B picture's is after its PTS. The DTSes
|
||||
|
||||
Reference in new issue
Block a user