🆕 Decode an arm64 guest's HEIC tiles on the host's VA-API
An arm64 guest's CMPhoto decodes a HEIC image's grid through a VTTileDecompressionSession, whose paravirtual decoder sends the host dsts, dtil and dtfi. The host answered each kVTUnimplementedErr, so ImageIO decoded every HEIC in software (a 6016x6016 desktop picture took 218 s under TCG). A decoder session now starts a tile session where the arm lands a part of a picture: it sends TDrs (the output buffers' attributes and the tiles it decodes: the arm's sizes, and the alignments Apple's hardware decoder asks, measured on an M3 Max on macOS 27.0.1) and answers noErr. Each dtil decodes its tile and lands the ,tcd columns and rows from ,tco at ,obp of the surface it lends, emits it (TDem: ,til, status, info, ,uiu) and is answered noErr; dtfi has no tile left to finish. On VA-API the frame's crop narrows to the region (Frame::crop_within), which then lands as a whole picture does, by the driver's video processing in place or the CPU's copy. NVDEC lands no parts yet and keeps answering kVTUnimplementedErr, which leaves its guests on the software decode.
This commit is contained in:
1 parent
8f8e14af00
commit
d3372a8d1d
9 files changed
+969
-41
No files matched your search
@@ -43,7 +43,7 @@ pub mod sample_buffer;
|
||||
mod session;
|
||||
pub mod status;
|
||||
|
||||
pub use decoder::{Backend, BackendDecoder, Decoded, DecoderConfig};
|
||||
pub use decoder::{Backend, BackendDecoder, Decoded, DecoderConfig, TileLimits, TileRegion};
|
||||
pub use encoder::{BackendEncoder, Encoder, EncoderBackend, EncoderConfig, SourceFrame};
|
||||
pub use host::{Answer, Codec, Decoder, Host};
|
||||
pub use session::{LentSurface, Link, surface_release};
|
||||
|
||||
@@ -26,11 +26,21 @@
|
||||
//! `dinv`) it answers [`NO_DECODER`] and sends nothing else.
|
||||
//! - A sample buffer whose format description carries another configuration record reopens the
|
||||
//! decoder from that sample.
|
||||
//! - **Tiles** (a `VTTileDecompressionSession`'s, such as CMPhoto's for a HEIC image's grid):
|
||||
//! `dsts` starts a tile session on its format description (`,fds`) where the backend decodes
|
||||
//! tiles into regions ([`BackendDecoder::tile_limits`]), sending `TDrs` first: the attributes
|
||||
//! the guest's output buffers are to have (`,cba`) and the tiles it decodes (`,trd`); else it
|
||||
//! answers `kVTUnimplementedErr`, and the guest's VideoToolbox decodes the image in software.
|
||||
//! `dtil` decodes one tile's sample (`,sbf`, in fragments as `dfrm`'s) into the one surface it
|
||||
//! lends: the `,tcd` columns and rows of the tile's picture from `,tco` land at `,obp` in it
|
||||
//! ([`TileRegion`]). The host emits the tile (`TDem`: its `,til`, status, info flags and the
|
||||
//! buffer's `,uiu`, waiting [`EMIT_REPLY_WAIT`]) before the reply, which says noErr, and lets
|
||||
//! go of the surface. Tiles decode in order, one a `dtil`, so `dtfi` has none left to finish.
|
||||
//! - **The rest**: `dsup` lists `UsingHardwareAcceleratedVideoDecoder` (true, read-only),
|
||||
//! `RealTime` and `MaximizePowerEfficiency` (taken); `dcop` and `dset` answer them;
|
||||
//! `Paravirtualized` is the guest's own, and a `dset` of it gets no reply; `dcan` answers
|
||||
//! whether the decoder goes on with another format description; `dinv` drops the decoder;
|
||||
//! `dfin`, `dmul`, `dsav`, `dtfi`, `dsts` and `dtil` answer `kVTUnimplementedErr`.
|
||||
//! `dfin`, `dmul` and `dsav` answer `kVTUnimplementedErr`.
|
||||
//!
|
||||
//! A message for a surface the session does not hold, and a surface lent with a message that
|
||||
//! takes none, is let go of at once (`rels`): the guest's kext holds each surface it lent until
|
||||
@@ -51,7 +61,9 @@ use crate::core::runtime::Runtime;
|
||||
use crate::paravirt::WireError;
|
||||
use crate::paravirt::host::Codec;
|
||||
use crate::paravirt::image_description::{AVC_CONFIGURATION, HEVC_CONFIGURATION, ImageDescription};
|
||||
use crate::paravirt::message::{GuestUuid, Message, MessageFlags, MessageHeader, MessageWriter};
|
||||
use crate::paravirt::message::{
|
||||
GuestUuid, Message, MessageFlags, MessageHeader, MessageWriter, ValueType,
|
||||
};
|
||||
use crate::paravirt::names;
|
||||
use crate::paravirt::plist::Value;
|
||||
use crate::paravirt::sample_buffer::{SampleBuffer, SerializedFormatDescription};
|
||||
@@ -77,6 +89,17 @@ const INFO_ASYNCHRONOUS: u32 = 1 << 0;
|
||||
/// `kVTDecodeInfo_FrameDropped`.
|
||||
const INFO_FRAME_DROPPED: u32 = 1 << 1;
|
||||
|
||||
/// The alignment a tile session asks of its tiles (`TileWidthPixelAlignment`,
|
||||
/// `TileHeightPixelAlignment`): Apple's hardware decoder's, measured on an M3 Max on macOS 27.0.1,
|
||||
/// which the guest's CMPhoto meets. A tile lands where its place in its output buffer is a
|
||||
/// multiple of it, which keeps every region on 4:2:0's even rows and columns.
|
||||
pub const TILE_PIXEL_ALIGNMENT: u32 = 8;
|
||||
/// A tile's first byte in its output buffer is a multiple of this: Apple's hardware decoder's
|
||||
/// `TileByteAlignment`, measured as [`TILE_PIXEL_ALIGNMENT`] was.
|
||||
pub const TILE_BYTE_ALIGNMENT: u32 = 64;
|
||||
/// The bytes of a 10-bit sample, which bound an output buffer's row by the widest tile.
|
||||
const WIDEST_SAMPLE_BYTES: u32 = 2;
|
||||
|
||||
/// The property the guest's VideoToolbox keeps for itself.
|
||||
const PARAVIRTUALIZED: &str = "Paravirtualized";
|
||||
/// `kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder`.
|
||||
@@ -114,6 +137,36 @@ pub enum Decoded {
|
||||
Skipped,
|
||||
}
|
||||
|
||||
/// The part of a tile's picture a `dtil` lands, and where in its output buffer, in luma samples.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct TileRegion {
|
||||
/// The picture's first column and row that land (`,tco`).
|
||||
pub source_x: u32,
|
||||
/// See `source_x`.
|
||||
pub source_y: u32,
|
||||
/// The columns that land (`,tcd`).
|
||||
pub width: u32,
|
||||
/// The rows that land (`,tcd`).
|
||||
pub height: u32,
|
||||
/// The output buffer's column they land at (`,obp`).
|
||||
pub x: u32,
|
||||
/// The output buffer's row they land at (`,obp`).
|
||||
pub y: u32,
|
||||
}
|
||||
|
||||
/// The tiles a backend decoder decodes into regions: the largest and smallest picture.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct TileLimits {
|
||||
/// The widest.
|
||||
pub max_width: u32,
|
||||
/// The tallest.
|
||||
pub max_height: u32,
|
||||
/// The narrowest.
|
||||
pub min_width: u32,
|
||||
/// The shortest.
|
||||
pub min_height: u32,
|
||||
}
|
||||
|
||||
/// The host's video arm, as the decoder sessions take it.
|
||||
pub trait Backend: Send + Sync {
|
||||
/// A decoder of `config`, on the session's thread at its `dsta`, or the status the guest sees
|
||||
@@ -132,6 +185,26 @@ pub trait BackendDecoder: Send {
|
||||
access_unit: &[u8],
|
||||
output: &dyn LentSurface,
|
||||
) -> Result<Decoded, OsStatus>;
|
||||
|
||||
/// The tiles it decodes into regions of an output ([`BackendDecoder::decode_tile`]); `None`,
|
||||
/// the default, where it decodes none, and a tile session is refused.
|
||||
fn tile_limits(&self) -> Option<TileLimits> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Decodes `access_unit` as [`BackendDecoder::decode`] does, and lands `region` of its
|
||||
/// picture in `output`, the rest of `output` left as it was; `kVTUnimplementedErr`, the
|
||||
/// default, where it decodes no tiles.
|
||||
fn decode_tile(
|
||||
&mut self,
|
||||
parameter_sets: &[u8],
|
||||
access_unit: &[u8],
|
||||
output: &dyn LentSurface,
|
||||
region: TileRegion,
|
||||
) -> Result<Decoded, OsStatus> {
|
||||
let _ = (parameter_sets, access_unit, output, region);
|
||||
Err(status::UNIMPLEMENTED)
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a decoder session of `codec` for `uuid`, its thread on `runtime`, decoding on
|
||||
@@ -159,6 +232,7 @@ pub(crate) fn start(
|
||||
properties: Vec::new(),
|
||||
fragments: Vec::new(),
|
||||
discarding: false,
|
||||
tiles: None,
|
||||
}
|
||||
.run();
|
||||
})
|
||||
@@ -172,6 +246,15 @@ struct FrameReply {
|
||||
info: u32,
|
||||
}
|
||||
|
||||
/// A tile session's decoder, and what it reads its samples with.
|
||||
struct TileSession {
|
||||
decoder: Box<dyn BackendDecoder>,
|
||||
/// The bytes before each NAL unit of the tiles' samples.
|
||||
length_size: u8,
|
||||
/// The configuration's parameter sets in Annex-B form, for its first decode; empty after it.
|
||||
parameter_sets: Vec<u8>,
|
||||
}
|
||||
|
||||
/// An output buffer the guest lent for a frame.
|
||||
struct GuestBuffer {
|
||||
uuid: GuestUuid,
|
||||
@@ -201,12 +284,14 @@ struct Worker {
|
||||
fragments: Vec<u8>,
|
||||
/// Whether the fragments of a `dfrm` past [`MAX_FRAME_MESSAGE_BYTES`] are being dropped.
|
||||
discarding: bool,
|
||||
/// The tile session a `dsts` started.
|
||||
tiles: Option<TileSession>,
|
||||
}
|
||||
|
||||
impl Worker {
|
||||
fn run(mut self) {
|
||||
while let Ok(job) = self.jobs.recv() {
|
||||
if let Err(error) = self.handle(&job.bytes) {
|
||||
if let Err(error) = self.handle(&job.bytes, &job.surfaces) {
|
||||
log::warn!("hardware video: a VideoToolbox message the host cannot read: {error}");
|
||||
}
|
||||
// A session's own messages lend nothing it keeps.
|
||||
@@ -234,7 +319,7 @@ impl Worker {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle(&mut self, bytes: &[u8]) -> Handled {
|
||||
fn handle(&mut self, bytes: &[u8], surfaces: &[Arc<dyn LentSurface>]) -> Handled {
|
||||
let message = Message::parse(bytes)?;
|
||||
let kind = message.header().message_type;
|
||||
match &kind.to_be_bytes() {
|
||||
@@ -249,9 +334,10 @@ impl Worker {
|
||||
self.decoder = None;
|
||||
self.reply_status(&message, status::NO_ERROR)
|
||||
}
|
||||
b"dfin" | b"dsav" | b"dtfi" | b"dsts" | b"dtil" => {
|
||||
self.reply_status(&message, status::UNIMPLEMENTED)
|
||||
}
|
||||
b"dsts" => self.start_tiles(&message),
|
||||
b"dtil" => self.decode_tile(bytes, message.header(), surfaces),
|
||||
b"dtfi" => self.reply_status(&message, status::NO_ERROR),
|
||||
b"dfin" | b"dsav" => self.reply_status(&message, status::UNIMPLEMENTED),
|
||||
_ => {
|
||||
log::warn!("hardware video: an unknown decoder message {kind}");
|
||||
self.reply_status(&message, status::UNIMPLEMENTED)
|
||||
@@ -298,12 +384,7 @@ impl Worker {
|
||||
/// lands in, the description's size, IOSurface backing, which the host needs to reach them,
|
||||
/// and the row and plane alignments and cache mode a hardware decoder's buffers have.
|
||||
fn send_buffer_attributes(&self, config: &DecoderConfig, record: &Record) {
|
||||
let format = match (record.ten_bit, record.full_range) {
|
||||
(false, false) => *b"420v",
|
||||
(false, true) => *b"420f",
|
||||
(true, false) => *b"x420",
|
||||
(true, true) => *b"xf20",
|
||||
};
|
||||
let format = pixel_format(record);
|
||||
let attributes = Value::dictionary([
|
||||
(
|
||||
"PixelFormatType",
|
||||
@@ -333,29 +414,8 @@ impl Worker {
|
||||
/// whose reply goes to the last fragment's header. A message past
|
||||
/// [`MAX_FRAME_MESSAGE_BYTES`] is dropped, its fragments up to the last too, with no reply.
|
||||
fn decode_frame(&mut self, bytes: &[u8], last: MessageHeader) -> Handled {
|
||||
let more = last.flags.contains(MessageFlags::MORE_FRAGMENTS);
|
||||
if !self.discarding
|
||||
&& self.fragments.len().saturating_add(bytes.len()) > MAX_FRAME_MESSAGE_BYTES
|
||||
{
|
||||
self.fragments = Vec::new();
|
||||
self.discarding = true;
|
||||
}
|
||||
if self.discarding {
|
||||
self.discarding = more;
|
||||
return Err(WireError::Malformed(
|
||||
"a frame message past the host's bound",
|
||||
));
|
||||
}
|
||||
if more {
|
||||
self.fragments.extend_from_slice(bytes);
|
||||
let Some(whole) = self.gather(bytes, last)? else {
|
||||
return Ok(());
|
||||
}
|
||||
let whole = if self.fragments.is_empty() {
|
||||
bytes.to_vec()
|
||||
} else {
|
||||
let mut whole = std::mem::take(&mut self.fragments);
|
||||
whole.extend_from_slice(bytes);
|
||||
whole
|
||||
};
|
||||
let message = Message::parse(&whole)?;
|
||||
let frame = message.s64(names::FRAME)?.unwrap_or(0);
|
||||
@@ -384,6 +444,226 @@ impl Worker {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A `dfrm`'s or `dtil`'s fragment: kept where flagged with more to come (`None`), else the
|
||||
/// whole message, this fragment last. A message past [`MAX_FRAME_MESSAGE_BYTES`] is dropped,
|
||||
/// its fragments up to the last too.
|
||||
fn gather(&mut self, bytes: &[u8], last: MessageHeader) -> Result<Option<Vec<u8>>, WireError> {
|
||||
let more = last.flags.contains(MessageFlags::MORE_FRAGMENTS);
|
||||
if !self.discarding
|
||||
&& self.fragments.len().saturating_add(bytes.len()) > MAX_FRAME_MESSAGE_BYTES
|
||||
{
|
||||
self.fragments = Vec::new();
|
||||
self.discarding = true;
|
||||
}
|
||||
if self.discarding {
|
||||
self.discarding = more;
|
||||
return Err(WireError::Malformed(
|
||||
"a frame message past the host's bound",
|
||||
));
|
||||
}
|
||||
if more {
|
||||
self.fragments.extend_from_slice(bytes);
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(if self.fragments.is_empty() {
|
||||
bytes.to_vec()
|
||||
} else {
|
||||
let mut whole = std::mem::take(&mut self.fragments);
|
||||
whole.extend_from_slice(bytes);
|
||||
whole
|
||||
}))
|
||||
}
|
||||
|
||||
/// `dsts`: starts a tile session on the format description, or answers why not (the module
|
||||
/// doc).
|
||||
fn start_tiles(&mut self, message: &Message<'_>) -> Handled {
|
||||
let description = message
|
||||
.image_description(names::FORMAT_DESCRIPTION)?
|
||||
.ok_or(WireError::Malformed("no format description"))?;
|
||||
let description = ImageDescription::parse(description)?;
|
||||
let config = config_from_description(&description).filter(|c| c.codec == self.codec);
|
||||
let status = match config {
|
||||
Some(config) => match self.open_tiles(&config) {
|
||||
Ok(()) => NO_ERROR,
|
||||
Err(status) => status,
|
||||
},
|
||||
None => status::VIDEO_DECODER_UNSUPPORTED_DATA_FORMAT,
|
||||
};
|
||||
self.reply_status(message, status)
|
||||
}
|
||||
|
||||
/// Opens a tile session's decoder of `config`, sending `TDrs`, or the status it is refused
|
||||
/// with: `kVTUnimplementedErr` where the backend decodes no tiles.
|
||||
fn open_tiles(&mut self, config: &DecoderConfig) -> Result<(), OsStatus> {
|
||||
self.tiles = None;
|
||||
let record = read_record(config)?;
|
||||
let decoder = self.backend.open(config)?;
|
||||
let limits = decoder.tile_limits().ok_or(status::UNIMPLEMENTED)?;
|
||||
self.send_tile_requirements(&record, limits);
|
||||
self.tiles = Some(TileSession {
|
||||
decoder,
|
||||
length_size: record.length_size,
|
||||
parameter_sets: record.parameter_sets,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `TDrs`: the attributes the guest's output buffers are to have (the format the tiles land
|
||||
/// in, IOSurface backing, and a hardware decoder's row and plane alignments), and the tiles
|
||||
/// the session decodes: the backend's largest and smallest picture, [`TILE_PIXEL_ALIGNMENT`],
|
||||
/// [`TILE_BYTE_ALIGNMENT`], and rows of an output buffer up to the widest tile's.
|
||||
fn send_tile_requirements(&self, record: &Record, limits: TileLimits) {
|
||||
let attributes = Value::dictionary([
|
||||
(
|
||||
"PixelFormatType",
|
||||
Value::Array(vec![Value::Integer(i64::from(u32::from_be_bytes(
|
||||
pixel_format(record),
|
||||
)))]),
|
||||
),
|
||||
("IOSurfaceProperties", Value::Dictionary(Vec::new())),
|
||||
("BytesPerRowAlignment", Value::Integer(64)),
|
||||
("PlaneAlignment", Value::Integer(256)),
|
||||
]);
|
||||
let widest_row = limits
|
||||
.max_width
|
||||
.saturating_mul(WIDEST_SAMPLE_BYTES)
|
||||
.next_multiple_of(TILE_BYTE_ALIGNMENT);
|
||||
let requirements = Value::dictionary([
|
||||
(
|
||||
"MaximumCanvasRowBytes",
|
||||
Value::Integer(i64::from(widest_row)),
|
||||
),
|
||||
(
|
||||
"MaximumTileHeight",
|
||||
Value::Integer(i64::from(limits.max_height)),
|
||||
),
|
||||
(
|
||||
"MaximumTileWidth",
|
||||
Value::Integer(i64::from(limits.max_width)),
|
||||
),
|
||||
(
|
||||
"MinimumDecodableHeight",
|
||||
Value::Integer(i64::from(limits.min_height)),
|
||||
),
|
||||
(
|
||||
"MinimumDecodableWidth",
|
||||
Value::Integer(i64::from(limits.min_width)),
|
||||
),
|
||||
(
|
||||
"MinimumTileHeight",
|
||||
Value::Integer(i64::from(limits.min_height)),
|
||||
),
|
||||
(
|
||||
"MinimumTileWidth",
|
||||
Value::Integer(i64::from(limits.min_width)),
|
||||
),
|
||||
(
|
||||
"TileByteAlignment",
|
||||
Value::Integer(i64::from(TILE_BYTE_ALIGNMENT)),
|
||||
),
|
||||
(
|
||||
"TileHeightPixelAlignment",
|
||||
Value::Integer(i64::from(TILE_PIXEL_ALIGNMENT)),
|
||||
),
|
||||
(
|
||||
"TileWidthPixelAlignment",
|
||||
Value::Integer(i64::from(TILE_PIXEL_ALIGNMENT)),
|
||||
),
|
||||
]);
|
||||
let mut message = MessageWriter::new(
|
||||
names::SET_TILE_DECODE_REQUIREMENTS,
|
||||
MessageFlags::NONE,
|
||||
Some(self.shared.uuid),
|
||||
0,
|
||||
);
|
||||
message.property_list(names::TILE_BUFFER_ATTRIBUTES, Some(&attributes));
|
||||
message.property_list(names::TILE_REQUIREMENTS, Some(&requirements));
|
||||
self.send(&message.finish());
|
||||
}
|
||||
|
||||
/// `dtil`: decodes one tile into the surface it lends, emits it, then replies (the module
|
||||
/// doc). Fragments are kept as `dfrm`'s.
|
||||
fn decode_tile(
|
||||
&mut self,
|
||||
bytes: &[u8],
|
||||
last: MessageHeader,
|
||||
surfaces: &[Arc<dyn LentSurface>],
|
||||
) -> Handled {
|
||||
let Some(whole) = self.gather(bytes, last)? else {
|
||||
return Ok(());
|
||||
};
|
||||
let message = Message::parse(&whole)?;
|
||||
let tile = message.s64(names::TILE)?.unwrap_or(0);
|
||||
let origin =
|
||||
(message.i32_pair(names::TILE_SOURCE_ORIGIN, ValueType::Point)?).unwrap_or((0, 0));
|
||||
let size = (message.i32_pair(names::TILE_SOURCE_SIZE, ValueType::Size)?)
|
||||
.ok_or(WireError::Malformed("no tile size"))?;
|
||||
let at = (message.i32_pair(names::TILE_OUTPUT_POINT, ValueType::Point)?).unwrap_or((0, 0));
|
||||
let buffer = message.uuid(names::TILE_BUFFER_UUID)?;
|
||||
let serialization = message
|
||||
.sample_buffer(names::SAMPLE_BUFFER)?
|
||||
.ok_or(WireError::Malformed("no sample buffer"))?;
|
||||
let sample = SampleBuffer::parse(&serialization)?;
|
||||
let status = match tile_region(origin, size, at) {
|
||||
Some(region) => self.land_tile(&sample, region, surfaces.first()),
|
||||
None => status::PARAMETER,
|
||||
};
|
||||
self.emit_tile(tile, status, buffer);
|
||||
let mut reply = MessageWriter::reply_to(&last, MessageFlags::REPLY_TO_GUEST);
|
||||
reply.s32(names::ERROR, status::NO_ERROR);
|
||||
reply.u32(names::INFO_FLAGS, 0);
|
||||
self.send(&reply.finish());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decodes `sample`, a tile, and lands `region` of it in `output`: the status its `TDem`
|
||||
/// carries.
|
||||
fn land_tile(
|
||||
&mut self,
|
||||
sample: &SampleBuffer,
|
||||
region: TileRegion,
|
||||
output: Option<&Arc<dyn LentSurface>>,
|
||||
) -> OsStatus {
|
||||
let Some(tiles) = self.tiles.as_mut() else {
|
||||
return NO_DECODER;
|
||||
};
|
||||
let Some(output) = output else {
|
||||
return status::PARAMETER;
|
||||
};
|
||||
let access_unit = (sample.data.as_deref())
|
||||
.ok_or(status::VIDEO_DECODER_BAD_DATA)
|
||||
.and_then(|data| annex_b(data, tiles.length_size));
|
||||
let parameter_sets = std::mem::take(&mut tiles.parameter_sets);
|
||||
let decoded = access_unit
|
||||
.and_then(|au| (tiles.decoder).decode_tile(¶meter_sets, &au, &**output, region));
|
||||
match decoded {
|
||||
Ok(Decoded::Landed) => NO_ERROR,
|
||||
// A tile is a picture of its own: one its decode skips landed nothing.
|
||||
Ok(Decoded::Skipped) => status::VIDEO_DECODER_BAD_DATA,
|
||||
Err(status) => {
|
||||
// The next tile gets the parameter sets this one did not land with.
|
||||
tiles.parameter_sets = parameter_sets;
|
||||
status
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `TDem`: the tile's status, and its output buffer; the guest's answer is waited for and not
|
||||
/// read.
|
||||
fn emit_tile(&mut self, tile: i64, status: OsStatus, buffer: Option<GuestUuid>) {
|
||||
let sent = self.request(names::EMIT_DECODED_TILE, EMIT_REPLY_WAIT, |message| {
|
||||
message.s64(names::TILE, tile);
|
||||
message.s32(names::ERROR, status);
|
||||
message.u32(names::INFO_FLAGS, 0);
|
||||
if let Some(uuid) = buffer {
|
||||
message.uuid(names::TILE_BUFFER_UUID, uuid);
|
||||
}
|
||||
});
|
||||
if let Ok(reply) = sent {
|
||||
self.shared.let_go(&reply.surfaces);
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes `sample`, frame `frame`, into a buffer the guest lends, and emits it.
|
||||
fn decode_sample(&mut self, frame: i64, sample: &SampleBuffer, reply: &mut FrameReply) {
|
||||
let reopened = sample
|
||||
@@ -677,6 +957,34 @@ fn config_from_format(format: &SerializedFormatDescription) -> Option<DecoderCon
|
||||
})
|
||||
}
|
||||
|
||||
/// The CoreVideo format a configuration's pictures land in: 8 or 10 bits, video or full range.
|
||||
fn pixel_format(record: &Record) -> [u8; 4] {
|
||||
match (record.ten_bit, record.full_range) {
|
||||
(false, false) => *b"420v",
|
||||
(false, true) => *b"420f",
|
||||
(true, false) => *b"x420",
|
||||
(true, true) => *b"xf20",
|
||||
}
|
||||
}
|
||||
|
||||
/// A `dtil`'s region from its `,tco`, `,tcd` and `,obp`: `None` for a negative or empty one, one
|
||||
/// from an odd column or row of the picture, or one off [`TILE_PIXEL_ALIGNMENT`] in its output. Its
|
||||
/// width and height may be odd, as an image's last column and row of tiles' are.
|
||||
fn tile_region(origin: (i32, i32), size: (i32, i32), at: (i32, i32)) -> Option<TileRegion> {
|
||||
let value = |v: i32| u32::try_from(v).ok();
|
||||
let region = TileRegion {
|
||||
source_x: value(origin.0)?,
|
||||
source_y: value(origin.1)?,
|
||||
width: value(size.0)?,
|
||||
height: value(size.1)?,
|
||||
x: value(at.0)?,
|
||||
y: value(at.1)?,
|
||||
};
|
||||
let even = (region.source_x | region.source_y) & 1 == 0;
|
||||
let aligned = (region.x | region.y).is_multiple_of(TILE_PIXEL_ALIGNMENT);
|
||||
(even && aligned && region.width != 0 && region.height != 0).then_some(region)
|
||||
}
|
||||
|
||||
/// What the host reads of a configuration record.
|
||||
struct Record {
|
||||
length_size: u8,
|
||||
|
||||
@@ -58,21 +58,30 @@ impl LentSurface for Surface {
|
||||
/// output's ID, a decode each.
|
||||
type Calls = Arc<Mutex<Vec<(Vec<u8>, Vec<u8>, u64)>>>;
|
||||
|
||||
/// The regions the fake backend's decoders landed tiles in, a tile each.
|
||||
type Regions = Arc<Mutex<Vec<TileRegion>>>;
|
||||
|
||||
struct FakeBackend {
|
||||
calls: Calls,
|
||||
regions: Regions,
|
||||
result: Result<Decoded, OsStatus>,
|
||||
tiles: Option<TileLimits>,
|
||||
}
|
||||
|
||||
struct FakeDecoder {
|
||||
calls: Calls,
|
||||
regions: Regions,
|
||||
result: Result<Decoded, OsStatus>,
|
||||
tiles: Option<TileLimits>,
|
||||
}
|
||||
|
||||
impl Backend for FakeBackend {
|
||||
fn open(&self, _config: &DecoderConfig) -> Result<Box<dyn BackendDecoder>, OsStatus> {
|
||||
Ok(Box::new(FakeDecoder {
|
||||
calls: Arc::clone(&self.calls),
|
||||
regions: Arc::clone(&self.regions),
|
||||
result: self.result,
|
||||
tiles: self.tiles,
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -89,6 +98,24 @@ impl BackendDecoder for FakeDecoder {
|
||||
.push((parameter_sets.to_vec(), access_unit.to_vec(), output.id()));
|
||||
self.result
|
||||
}
|
||||
|
||||
fn tile_limits(&self) -> Option<TileLimits> {
|
||||
self.tiles
|
||||
}
|
||||
|
||||
fn decode_tile(
|
||||
&mut self,
|
||||
parameter_sets: &[u8],
|
||||
access_unit: &[u8],
|
||||
output: &dyn LentSurface,
|
||||
region: TileRegion,
|
||||
) -> Result<Decoded, OsStatus> {
|
||||
if self.tiles.is_none() {
|
||||
return Err(status::UNIMPLEMENTED);
|
||||
}
|
||||
self.regions.lock().push(region);
|
||||
self.decode(parameter_sets, access_unit, output)
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's side of one session: the host, the messages it sent, and the session's UUID.
|
||||
@@ -98,14 +125,23 @@ struct Guest {
|
||||
sent: mpsc::Receiver<Vec<u8>>,
|
||||
uuid: GuestUuid,
|
||||
calls: Calls,
|
||||
regions: Regions,
|
||||
}
|
||||
|
||||
impl Guest {
|
||||
fn new(result: Result<Decoded, OsStatus>) -> Self {
|
||||
Self::with_tiles(result, None)
|
||||
}
|
||||
|
||||
/// A session on a backend whose decoders decode `tiles`.
|
||||
fn with_tiles(result: Result<Decoded, OsStatus>, tiles: Option<TileLimits>) -> Self {
|
||||
let calls = Calls::default();
|
||||
let regions = Regions::default();
|
||||
let backend = Arc::new(FakeBackend {
|
||||
calls: Arc::clone(&calls),
|
||||
regions: Arc::clone(®ions),
|
||||
result,
|
||||
tiles,
|
||||
});
|
||||
let decoders = vec![Decoder {
|
||||
codec: Codec::H264,
|
||||
@@ -119,6 +155,7 @@ impl Guest {
|
||||
sent,
|
||||
uuid: GuestUuid([0x5a; 16]),
|
||||
calls,
|
||||
regions,
|
||||
};
|
||||
let answer = guest.send(
|
||||
b"+dec",
|
||||
@@ -211,6 +248,68 @@ impl Guest {
|
||||
);
|
||||
}
|
||||
|
||||
/// Starts a tile session on a 64x48 description of `record`.
|
||||
fn start_tiles(&self, record: &[u8]) {
|
||||
let description = hand_written(b"avc1", 64, 48, record);
|
||||
self.send(
|
||||
b"dsts",
|
||||
MessageFlags::GUEST_EXPECTS_REPLY,
|
||||
3,
|
||||
Vec::new(),
|
||||
|m| {
|
||||
m.image_description(names::FORMAT_DESCRIPTION, &description);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Sends tile `tile`, its sample `sample`, landing the `size` columns and rows from `origin`
|
||||
/// at `at` of the surface `surface` it lends, the buffer `buffer`.
|
||||
fn tile(
|
||||
&self,
|
||||
tile: i64,
|
||||
(origin, size, at): ((i32, i32), (i32, i32), (i32, i32)),
|
||||
buffer: GuestUuid,
|
||||
surface: u64,
|
||||
sample: &[u8],
|
||||
) {
|
||||
self.send(
|
||||
b"dtil",
|
||||
MessageFlags::GUEST_EXPECTS_REPLY,
|
||||
200 + tile as u64,
|
||||
vec![Arc::new(Surface(surface))],
|
||||
|m| {
|
||||
m.s64(names::TILE, tile);
|
||||
m.i32_pair(names::TILE_SOURCE_ORIGIN, ValueType::Point, origin);
|
||||
m.i32_pair(names::TILE_SOURCE_SIZE, ValueType::Size, size);
|
||||
m.uuid(names::TILE_BUFFER_UUID, buffer);
|
||||
m.i32_pair(names::TILE_OUTPUT_POINT, ValueType::Point, at);
|
||||
m.u32(names::DECODE_FLAGS, 1);
|
||||
m.sample_buffer_with_limit(names::SAMPLE_BUFFER, usize::MAX, sample);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Checks the host's `TDem` of tile `tile` with `status` and `buffer`, answers it, and checks
|
||||
/// that `surface` goes back and the `dtil` is answered noErr.
|
||||
fn tile_emitted(&self, tile: i64, status: OsStatus, buffer: GuestUuid, surface: u64) {
|
||||
let (tdem, emitted) = self.next_of(b"TDem");
|
||||
assert!(tdem.flags.contains(MessageFlags::HOST_EXPECTS_REPLY));
|
||||
let message = Message::parse(&emitted).unwrap();
|
||||
assert_eq!(message.s64(names::TILE).unwrap(), Some(tile));
|
||||
assert_eq!(status_of(&emitted), Some(status));
|
||||
assert_eq!(info_of(&emitted), Some(0));
|
||||
assert_eq!(message.uuid(names::TILE_BUFFER_UUID).unwrap(), Some(buffer));
|
||||
self.answer(&tdem, 0, None);
|
||||
let (header, reply) = self.next_of(b"dtil");
|
||||
assert_eq!(header.reply_id, 200 + tile as u64);
|
||||
assert_eq!((status_of(&reply), info_of(&reply)), (Some(0), Some(0)));
|
||||
assert_eq!(
|
||||
self.next(),
|
||||
surface_release(&[surface]),
|
||||
"the surface goes back"
|
||||
);
|
||||
}
|
||||
|
||||
/// Sends frame `frame` with `flags`, its sample `sample`.
|
||||
fn frame(&self, frame: i64, flags: u32, sample: &[u8]) {
|
||||
self.send(
|
||||
@@ -682,3 +781,172 @@ fn a_create_of_a_codec_the_list_lacks_is_refused() {
|
||||
Some(status::COULD_NOT_FIND_VIDEO_DECODER)
|
||||
);
|
||||
}
|
||||
|
||||
/// The tiles the fake backend's decoders decode, where a test lets them.
|
||||
const TILES: TileLimits = TileLimits {
|
||||
max_width: 8192,
|
||||
max_height: 4352,
|
||||
min_width: 64,
|
||||
min_height: 64,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn a_tile_session_sends_its_requirements_then_its_reply() {
|
||||
let guest = Guest::with_tiles(Ok(Decoded::Landed), Some(TILES));
|
||||
guest.start_tiles(&avcc(&SPS, 4));
|
||||
let (tdrs, requirements) = guest.next_of(b"TDrs");
|
||||
assert!(!tdrs.flags.contains(MessageFlags::HOST_EXPECTS_REPLY));
|
||||
let attributes = plist_of(&requirements, names::TILE_BUFFER_ATTRIBUTES);
|
||||
assert_eq!(
|
||||
attributes.get("PixelFormatType"),
|
||||
Some(&Value::Array(vec![Value::Integer(0x3432_3076)])),
|
||||
"420v"
|
||||
);
|
||||
assert_eq!(attributes.get("Width"), None, "the guest sizes its buffers");
|
||||
let tiles = plist_of(&requirements, names::TILE_REQUIREMENTS);
|
||||
for (key, value) in [
|
||||
("MaximumTileWidth", 8192),
|
||||
("MaximumTileHeight", 4352),
|
||||
("MinimumTileWidth", 64),
|
||||
("MinimumTileHeight", 64),
|
||||
("MinimumDecodableWidth", 64),
|
||||
("MinimumDecodableHeight", 64),
|
||||
("TileWidthPixelAlignment", 8),
|
||||
("TileHeightPixelAlignment", 8),
|
||||
("TileByteAlignment", 64),
|
||||
("MaximumCanvasRowBytes", 16384),
|
||||
] {
|
||||
assert_eq!(tiles.get(key), Some(&Value::Integer(value)), "{key}");
|
||||
}
|
||||
let (header, reply) = guest.next_of(b"dsts");
|
||||
assert!(header.flags.contains(MessageFlags::REPLY_TO_GUEST));
|
||||
assert_eq!(status_of(&reply), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tile_session_on_a_backend_that_decodes_no_tiles_is_refused_unimplemented() {
|
||||
let guest = Guest::new(Ok(Decoded::Landed));
|
||||
guest.start_tiles(&avcc(&SPS, 4));
|
||||
let (_, reply) = guest.next_of(b"dsts");
|
||||
assert_eq!(
|
||||
status_of(&reply),
|
||||
Some(status::UNIMPLEMENTED),
|
||||
"no TDrs first"
|
||||
);
|
||||
let buffer = GuestUuid([0xc0; 16]);
|
||||
guest.tile(
|
||||
0,
|
||||
((0, 0), (64, 48), (0, 0)),
|
||||
buffer,
|
||||
30,
|
||||
&one_sample(&SAMPLE, None, false),
|
||||
);
|
||||
guest.tile_emitted(0, NO_DECODER, buffer, 30);
|
||||
assert!(guest.calls.lock().is_empty());
|
||||
assert!(guest.quiet());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tile_lands_its_region_in_the_surface_it_lends_then_is_emitted_and_let_go() {
|
||||
let guest = Guest::with_tiles(Ok(Decoded::Landed), Some(TILES));
|
||||
guest.start_tiles(&avcc(&SPS, 4));
|
||||
guest.next_of(b"TDrs");
|
||||
guest.next_of(b"dsts");
|
||||
let buffer = GuestUuid([0xc1; 16]);
|
||||
guest.tile(
|
||||
0,
|
||||
((0, 0), (64, 48), (0, 0)),
|
||||
buffer,
|
||||
31,
|
||||
&one_sample(&SAMPLE, None, false),
|
||||
);
|
||||
guest.tile_emitted(0, 0, buffer, 31);
|
||||
guest.tile(
|
||||
1,
|
||||
((16, 8), (47, 39), (64, 48)),
|
||||
buffer,
|
||||
32,
|
||||
&one_sample(&SAMPLE, None, false),
|
||||
);
|
||||
guest.tile_emitted(1, 0, buffer, 32);
|
||||
let mut au = START_CODE.to_vec();
|
||||
au.extend_from_slice(&[0x65, 0x88]);
|
||||
assert_eq!(
|
||||
*guest.calls.lock(),
|
||||
vec![(annex_b_sets(), au.clone(), 31), (Vec::new(), au, 32)],
|
||||
"the record's sets go first, once"
|
||||
);
|
||||
assert_eq!(
|
||||
*guest.regions.lock(),
|
||||
vec![
|
||||
TileRegion {
|
||||
source_x: 0,
|
||||
source_y: 0,
|
||||
width: 64,
|
||||
height: 48,
|
||||
x: 0,
|
||||
y: 0,
|
||||
},
|
||||
TileRegion {
|
||||
source_x: 16,
|
||||
source_y: 8,
|
||||
width: 47,
|
||||
height: 39,
|
||||
x: 64,
|
||||
y: 48,
|
||||
},
|
||||
],
|
||||
"an odd width and height at the image's edge"
|
||||
);
|
||||
guest.send(
|
||||
b"dtfi",
|
||||
MessageFlags::GUEST_EXPECTS_REPLY,
|
||||
4,
|
||||
Vec::new(),
|
||||
|_| {},
|
||||
);
|
||||
let (_, finished) = guest.next_of(b"dtfi");
|
||||
assert_eq!(status_of(&finished), Some(0), "no tile left to finish");
|
||||
assert!(guest.quiet());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tile_the_host_cannot_place_is_emitted_with_a_parameter_error_undecoded() {
|
||||
let guest = Guest::with_tiles(Ok(Decoded::Landed), Some(TILES));
|
||||
guest.start_tiles(&avcc(&SPS, 4));
|
||||
guest.next_of(b"TDrs");
|
||||
guest.next_of(b"dsts");
|
||||
let buffer = GuestUuid([0xc2; 16]);
|
||||
for (tile, region) in [
|
||||
(0, ((0, 0), (64, 48), (4, 0))),
|
||||
(1, ((1, 0), (62, 48), (0, 0))),
|
||||
(2, ((0, 0), (0, 48), (0, 0))),
|
||||
(3, ((0, -2), (64, 48), (0, 0))),
|
||||
] {
|
||||
guest.tile(tile, region, buffer, 33, &one_sample(&SAMPLE, None, false));
|
||||
guest.tile_emitted(tile, status::PARAMETER, buffer, 33);
|
||||
}
|
||||
assert!(guest.calls.lock().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tile_that_does_not_decode_is_emitted_with_its_status_and_the_next_gets_the_sets() {
|
||||
let guest = Guest::with_tiles(Err(status::VIDEO_DECODER_BAD_DATA), Some(TILES));
|
||||
guest.start_tiles(&avcc(&SPS, 4));
|
||||
guest.next_of(b"TDrs");
|
||||
guest.next_of(b"dsts");
|
||||
let buffer = GuestUuid([0xc3; 16]);
|
||||
for tile in 0..2 {
|
||||
guest.tile(
|
||||
tile,
|
||||
((0, 0), (64, 48), (0, 0)),
|
||||
buffer,
|
||||
34,
|
||||
&one_sample(&SAMPLE, None, false),
|
||||
);
|
||||
guest.tile_emitted(tile, status::VIDEO_DECODER_BAD_DATA, buffer, 34);
|
||||
}
|
||||
let calls = guest.calls.lock();
|
||||
assert_eq!(calls.len(), 2);
|
||||
assert!(calls.iter().all(|(sets, _, _)| *sets == annex_b_sets()));
|
||||
}
|
||||
@@ -79,6 +79,25 @@ pub(crate) const CREATE_PIXEL_BUFFER: FourCc = FourCc::new(*b"Dbuf");
|
||||
pub(crate) const EMIT_DECODED_FRAME: FourCc = FourCc::new(*b"Demt");
|
||||
/// `Dfub`: output buffers let go of unemitted.
|
||||
pub(crate) const FREE_UNUSED_PIXEL_BUFFERS: FourCc = FourCc::new(*b"Dfub");
|
||||
/// `TDrs`: what a tile session's output buffers are to have, and the tiles it decodes.
|
||||
pub(crate) const SET_TILE_DECODE_REQUIREMENTS: FourCc = FourCc::new(*b"TDrs");
|
||||
/// `TDem`: emit a decoded tile.
|
||||
pub(crate) const EMIT_DECODED_TILE: FourCc = FourCc::new(*b"TDem");
|
||||
|
||||
/// `,til`: a tile's identifier, `=s64`.
|
||||
pub(crate) const TILE: FourCc = FourCc::new(*b",til");
|
||||
/// `,tco`: the first column and row of the tile's picture that land, `=32p`.
|
||||
pub(crate) const TILE_SOURCE_ORIGIN: FourCc = FourCc::new(*b",tco");
|
||||
/// `,tcd`: the columns and rows of the tile's picture that land, `=32s`.
|
||||
pub(crate) const TILE_SOURCE_SIZE: FourCc = FourCc::new(*b",tcd");
|
||||
/// `,obp`: where in the output buffer they land, `=32p`.
|
||||
pub(crate) const TILE_OUTPUT_POINT: FourCc = FourCc::new(*b",obp");
|
||||
/// `,uiu`: a tile's output buffer's UUID, `=uui`.
|
||||
pub(crate) const TILE_BUFFER_UUID: FourCc = FourCc::new(*b",uiu");
|
||||
/// `,cba`: a tile session's output buffer attributes, `=pls`.
|
||||
pub(crate) const TILE_BUFFER_ATTRIBUTES: FourCc = FourCc::new(*b",cba");
|
||||
/// `,trd`: a tile session's tile requirements, `=pls`.
|
||||
pub(crate) const TILE_REQUIREMENTS: FourCc = FourCc::new(*b",trd");
|
||||
|
||||
/// `,fds`: a format description, `=fds`.
|
||||
pub(crate) const FORMAT_DESCRIPTION: FourCc = FourCc::new(*b",fds");
|
||||
|
||||
@@ -73,6 +73,20 @@ impl Frame {
|
||||
(self.rect.x, self.rect.y)
|
||||
}
|
||||
|
||||
/// Narrows the crop to the `width` by `height` samples from (`x`, `y`) of it: what its writes
|
||||
/// and copies take from then on, as they take an odd crop. `x` and `y` are even, as 4:2:0's
|
||||
/// crops start, and the rect lies inside the crop; [`Error::Unsupported`] otherwise, the crop
|
||||
/// left as it was.
|
||||
pub fn crop_within(&mut self, x: u32, y: u32, width: u32, height: u32) -> Result<(), Error> {
|
||||
self.rect = narrowed(self.rect, x, y, width, height).ok_or_else(|| {
|
||||
Error::Unsupported(format!(
|
||||
"a crop of {width}x{height} at ({x}, {y}) of a frame of {}x{}",
|
||||
self.rect.width, self.rect.height
|
||||
))
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The frame's surface as dma-bufs, for another device to read its planes
|
||||
/// (`super::export`): its pool's export of the surface, made at the surface's first ask.
|
||||
/// It reads the decode only once [`Frame::sync`] returned.
|
||||
@@ -352,3 +366,68 @@ impl Frame {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `rect`'s `width` by `height` samples from (`x`, `y`) of it, where `x` and `y` are even and the
|
||||
/// rect lies inside `rect` and holds a sample; `None` otherwise.
|
||||
fn narrowed(rect: Rect, x: u32, y: u32, width: u32, height: u32) -> Option<Rect> {
|
||||
let even = (x | y) & 1 == 0;
|
||||
let inside = (x.checked_add(width)).is_some_and(|end| end <= rect.width)
|
||||
&& (y.checked_add(height)).is_some_and(|end| end <= rect.height);
|
||||
(even && inside && width != 0 && height != 0).then(|| Rect {
|
||||
x: rect.x + x,
|
||||
y: rect.y + y,
|
||||
width,
|
||||
height,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn rect(x: u32, y: u32, width: u32, height: u32) -> Rect {
|
||||
Rect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
|
||||
fn parts(rect: Option<Rect>) -> Option<(u32, u32, u32, u32)> {
|
||||
rect.map(|r| (r.x, r.y, r.width, r.height))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crop_within_a_crop_starts_from_the_crops_origin() {
|
||||
let crop = rect(0, 8, 1024, 1016);
|
||||
assert_eq!(
|
||||
parts(narrowed(crop, 0, 0, 1024, 1016)),
|
||||
Some((0, 8, 1024, 1016))
|
||||
);
|
||||
assert_eq!(
|
||||
parts(narrowed(crop, 128, 64, 896, 952)),
|
||||
Some((128, 72, 896, 952))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crop_may_end_on_an_odd_column_or_row() {
|
||||
let crop = rect(0, 0, 1024, 1024);
|
||||
assert_eq!(
|
||||
parts(narrowed(crop, 512, 0, 511, 1023)),
|
||||
Some((512, 0, 511, 1023))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crop_past_the_frame_from_an_odd_sample_or_empty_is_refused() {
|
||||
let crop = rect(0, 0, 1024, 1024);
|
||||
assert_eq!(parts(narrowed(crop, 0, 0, 1026, 1024)), None);
|
||||
assert_eq!(parts(narrowed(crop, 2, 0, 1024, 1024)), None);
|
||||
assert_eq!(parts(narrowed(crop, 1, 0, 512, 512)), None);
|
||||
assert_eq!(parts(narrowed(crop, 0, 3, 512, 512)), None);
|
||||
assert_eq!(parts(narrowed(crop, 0, 0, 0, 512)), None);
|
||||
assert_eq!(parts(narrowed(crop, u32::MAX - 1, 0, 2, 2)), None);
|
||||
}
|
||||
}
|
||||
@@ -144,6 +144,28 @@ pub trait GuestDecoder: Send {
|
||||
au: &[u8],
|
||||
output: &GuestOutput<'_>,
|
||||
) -> Result<bool, reims_vgpu_video::core::backend::BackendError>;
|
||||
|
||||
/// Whether it lands a part of a picture ([`GuestDecoder::decode_region`]): false, the
|
||||
/// default, where it lands only whole pictures.
|
||||
fn decodes_regions(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Decodes `au` as [`GuestDecoder::decode`] does, and lands the `width` by `height` samples
|
||||
/// of its picture from (`x`, `y`), `region` in that order, at `output`'s top left, `output`
|
||||
/// laid out that size; [`VideoError::Unsupported`], the default, where it lands no parts.
|
||||
fn decode_region(
|
||||
&mut self,
|
||||
parameter_sets: &[u8],
|
||||
au: &[u8],
|
||||
output: &GuestOutput<'_>,
|
||||
region: [u32; 4],
|
||||
) -> Result<bool, VideoError> {
|
||||
let _ = (parameter_sets, au, output, region);
|
||||
Err(VideoError::Unsupported(
|
||||
"the arm lands no part of a picture".to_owned(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// An encoder of one codec whose source frames come in surfaces the guest lent: VideoToolbox's
|
||||
|
||||
@@ -1023,6 +1023,36 @@ impl GuestDecoder for VaGuestDecoder {
|
||||
parameter_sets: &[u8],
|
||||
au: &[u8],
|
||||
output: &GuestOutput<'_>,
|
||||
) -> Result<bool, VideoError> {
|
||||
self.land(parameter_sets, au, output, None)
|
||||
}
|
||||
|
||||
/// The crop narrows to the region, which then lands as a whole picture does, by the driver's
|
||||
/// video processing in place or the CPU's copy.
|
||||
fn decodes_regions(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn decode_region(
|
||||
&mut self,
|
||||
parameter_sets: &[u8],
|
||||
au: &[u8],
|
||||
output: &GuestOutput<'_>,
|
||||
region: [u32; 4],
|
||||
) -> Result<bool, VideoError> {
|
||||
self.land(parameter_sets, au, output, Some(region))
|
||||
}
|
||||
}
|
||||
|
||||
impl VaGuestDecoder {
|
||||
/// Decodes `au` after `parameter_sets`, and lands its picture, or `region` of it (`x`, `y`,
|
||||
/// `width`, `height`), in `output`.
|
||||
fn land(
|
||||
&mut self,
|
||||
parameter_sets: &[u8],
|
||||
au: &[u8],
|
||||
output: &GuestOutput<'_>,
|
||||
region: Option<[u32; 4]>,
|
||||
) -> Result<bool, VideoError> {
|
||||
if !parameter_sets.is_empty() {
|
||||
let n = self.frames(parameter_sets)?.len();
|
||||
@@ -1033,7 +1063,7 @@ impl GuestDecoder for VaGuestDecoder {
|
||||
}
|
||||
}
|
||||
let mut frames = self.frames(au)?;
|
||||
let frame = match (frames.pop(), frames.len()) {
|
||||
let mut frame = match (frames.pop(), frames.len()) {
|
||||
(None, _) => return Ok(false),
|
||||
(Some(frame), 0) => frame,
|
||||
(Some(_), n) => {
|
||||
@@ -1043,6 +1073,11 @@ impl GuestDecoder for VaGuestDecoder {
|
||||
)));
|
||||
}
|
||||
};
|
||||
if let Some([x, y, width, height]) = region {
|
||||
frame
|
||||
.crop_within(x, y, width, height)
|
||||
.map_err(video_error)?;
|
||||
}
|
||||
let declined = match GuestTarget::new(&output.layout, output.memory) {
|
||||
Ok(target) => match frame.write_to_guest(&target, &self.imports) {
|
||||
Ok(DeviceWrite::Written) => return Ok(true),
|
||||
|
||||
@@ -23,7 +23,8 @@ use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_graphics::wire::{
|
||||
RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC, RGFX_VT_SURFACE_PLANES, RgfxVtSurface,
|
||||
RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_DECODE, RGFX_VT_SURFACE_PLANES,
|
||||
RgfxVtSurface,
|
||||
};
|
||||
use reims_vgpu_video::codec::encode::{Coded, FailedSample};
|
||||
use reims_vgpu_video::core::backend::BackendError as VideoError;
|
||||
@@ -32,7 +33,7 @@ use reims_vgpu_video::core::surfaces::{PlaneLayout, SurfaceLayout};
|
||||
use reims_vgpu_video::paravirt::status::{self, OsStatus};
|
||||
use reims_vgpu_video::paravirt::{
|
||||
Backend, BackendDecoder, BackendEncoder, Codec, Decoded, DecoderConfig, EncoderBackend,
|
||||
EncoderConfig, LentSurface, SourceFrame,
|
||||
EncoderConfig, LentSurface, SourceFrame, TileLimits, TileRegion,
|
||||
};
|
||||
use reims_vgpu_vulkan::core::num::ToUsize as _;
|
||||
use reims_vgpu_vulkan::core::platform::{Handle as _, Platform};
|
||||
@@ -66,11 +67,25 @@ impl<P: Platform> Backend for VtBackend<P> {
|
||||
};
|
||||
let decoder =
|
||||
(self.video.guest_decoder(codec)).ok_or(status::COULD_NOT_FIND_VIDEO_DECODER)?;
|
||||
// Tiles as large and small as the arm decodes pictures of the codec, where it lands parts.
|
||||
let tiles = (decoder.decodes_regions())
|
||||
.then(|| self.video.caps())
|
||||
.and_then(|caps| {
|
||||
let entry =
|
||||
(caps.iter()).find(|c| c.codec == codec && c.direction == RGFX_VIDEO_DECODE)?;
|
||||
Some(TileLimits {
|
||||
max_width: entry.max_size[0],
|
||||
max_height: entry.max_size[1],
|
||||
min_width: entry.min_size[0],
|
||||
min_height: entry.min_size[1],
|
||||
})
|
||||
});
|
||||
Ok(Box::new(VtDecoder {
|
||||
decoder,
|
||||
views: self.views.clone(),
|
||||
kept: VecDeque::new(),
|
||||
said: Vec::new(),
|
||||
tiles,
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -82,6 +97,8 @@ struct VtDecoder<P: Platform> {
|
||||
kept: Kept<()>,
|
||||
/// The reasons a decode failed, each logged once.
|
||||
said: Vec<String>,
|
||||
/// The tiles it decodes into regions of an output, where the arm lands parts of pictures.
|
||||
tiles: Option<TileLimits>,
|
||||
}
|
||||
|
||||
/// The views a decoder or encoder keeps, by their runs and bytes, the newest last, each with
|
||||
@@ -132,6 +149,37 @@ impl<P: Platform> BackendDecoder for VtDecoder<P> {
|
||||
parameter_sets: &[u8],
|
||||
access_unit: &[u8],
|
||||
output: &dyn LentSurface,
|
||||
) -> Result<Decoded, OsStatus> {
|
||||
self.land(parameter_sets, access_unit, output, None)
|
||||
}
|
||||
|
||||
fn tile_limits(&self) -> Option<TileLimits> {
|
||||
self.tiles
|
||||
}
|
||||
|
||||
fn decode_tile(
|
||||
&mut self,
|
||||
parameter_sets: &[u8],
|
||||
access_unit: &[u8],
|
||||
output: &dyn LentSurface,
|
||||
region: TileRegion,
|
||||
) -> Result<Decoded, OsStatus> {
|
||||
if self.tiles.is_none() {
|
||||
return Err(status::UNIMPLEMENTED);
|
||||
}
|
||||
self.land(parameter_sets, access_unit, output, Some(region))
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> VtDecoder<P> {
|
||||
/// Decodes `access_unit` after `parameter_sets` into `output`: its picture into the whole
|
||||
/// surface, or `region` of it at the region's place.
|
||||
fn land(
|
||||
&mut self,
|
||||
parameter_sets: &[u8],
|
||||
access_unit: &[u8],
|
||||
output: &dyn LentSurface,
|
||||
region: Option<TileRegion>,
|
||||
) -> Result<Decoded, OsStatus> {
|
||||
let Some(GuestSurface(surface)) = output.as_any().downcast_ref::<GuestSurface>() else {
|
||||
return Err(self.failed(status::PARAMETER, "an output no guest lent".to_owned()));
|
||||
@@ -142,6 +190,11 @@ impl<P: Platform> BackendDecoder for VtDecoder<P> {
|
||||
return Err(self.failed(status::VIDEO_DECODER_UNSUPPORTED_DATA_FORMAT, why));
|
||||
}
|
||||
};
|
||||
let layout = match region.map(|region| region_layout(&layout, region)) {
|
||||
None => layout,
|
||||
Some(Ok(layout)) => layout,
|
||||
Some(Err(why)) => return Err(self.failed(status::PARAMETER, why)),
|
||||
};
|
||||
let view = match view_of(
|
||||
&mut self.kept,
|
||||
&self.views,
|
||||
@@ -155,7 +208,15 @@ impl<P: Platform> BackendDecoder for VtDecoder<P> {
|
||||
layout,
|
||||
memory: &**view.memory(),
|
||||
};
|
||||
let decoded = self.decoder.decode(parameter_sets, access_unit, &output);
|
||||
let decoded = match region {
|
||||
None => self.decoder.decode(parameter_sets, access_unit, &output),
|
||||
Some(r) => self.decoder.decode_region(
|
||||
parameter_sets,
|
||||
access_unit,
|
||||
&output,
|
||||
[r.source_x, r.source_y, r.width, r.height],
|
||||
),
|
||||
};
|
||||
match decoded {
|
||||
Ok(true) => Ok(Decoded::Landed),
|
||||
Ok(false) | Err(VideoError::SkippedLeadingPicture(_)) => Ok(Decoded::Skipped),
|
||||
@@ -364,6 +425,57 @@ pub(super) fn layout_of(record: &RgfxVtSurface) -> Result<SurfaceLayout, String>
|
||||
})
|
||||
}
|
||||
|
||||
/// The part of a surface laid out as `layout` that a tile's `region` lands in: each plane from the
|
||||
/// region's first row and column, `region.width` by `region.height` luma samples (half, rounded
|
||||
/// up, of a 4:2:0 chroma plane's, of pairs), with the surface's rows. A region past the surface,
|
||||
/// or one from an odd column or row, is refused.
|
||||
fn region_layout(layout: &SurfaceLayout, region: TileRegion) -> Result<SurfaceLayout, String> {
|
||||
let format = layout.pixel_format;
|
||||
let sample = if [*b"420v", *b"420f"].map(FourCc::new).contains(&format) {
|
||||
1
|
||||
} else if [*b"x420", *b"xf20"].map(FourCc::new).contains(&format) {
|
||||
2
|
||||
} else {
|
||||
return Err(format!("tiles in '{format}'"));
|
||||
};
|
||||
let fits = (region.x.checked_add(region.width)).is_some_and(|end| end <= layout.width)
|
||||
&& (region.y.checked_add(region.height)).is_some_and(|end| end <= layout.height);
|
||||
if !fits || (region.x | region.y) & 1 != 0 {
|
||||
return Err(format!(
|
||||
"a tile of {}x{} at ({}, {}) of a surface of {}x{}",
|
||||
region.width, region.height, region.x, region.y, layout.width, layout.height
|
||||
));
|
||||
}
|
||||
let [luma, chroma] = layout.planes[..] else {
|
||||
return Err(format!("a surface of {} planes", layout.planes.len()));
|
||||
};
|
||||
// A 4:2:0 chroma row holds a Cb/Cr pair for every two columns, and stands for two rows.
|
||||
let moved = |plane: PlaneLayout, rows: u32, width: u32, height: u32| -> Option<PlaneLayout> {
|
||||
let down = plane.bytes_per_row.checked_mul(rows.to_usize())?;
|
||||
let across = region.x.to_usize().checked_mul(sample)?;
|
||||
Some(PlaneLayout {
|
||||
offset: plane.offset.checked_add(down)?.checked_add(across)?,
|
||||
width,
|
||||
height,
|
||||
..plane
|
||||
})
|
||||
};
|
||||
let (half_width, half_height) = (region.width.div_ceil(2), region.height.div_ceil(2));
|
||||
let planes = [
|
||||
moved(luma, region.y, region.width, region.height),
|
||||
moved(chroma, region.y / 2, half_width, half_height),
|
||||
];
|
||||
let [Some(luma), Some(chroma)] = planes else {
|
||||
return Err("a tile past 2^64 bytes".to_owned());
|
||||
};
|
||||
Ok(SurfaceLayout {
|
||||
width: region.width,
|
||||
height: region.height,
|
||||
planes: vec![luma, chroma],
|
||||
..layout.clone()
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -423,6 +535,80 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A tile's region of [`nv12`]: luma from its row and column, chroma from half its row, of
|
||||
/// half its columns and rows rounded up.
|
||||
#[test]
|
||||
fn a_tiles_region_moves_each_plane_to_its_place() {
|
||||
let layout = layout_of(&nv12()).unwrap();
|
||||
let region = TileRegion {
|
||||
source_x: 0,
|
||||
source_y: 0,
|
||||
width: 23,
|
||||
height: 15,
|
||||
x: 40,
|
||||
y: 32,
|
||||
};
|
||||
let part = region_layout(&layout, region).unwrap();
|
||||
assert_eq!((part.width, part.height), (23, 15));
|
||||
assert_eq!(
|
||||
part.planes,
|
||||
vec![
|
||||
PlaneLayout {
|
||||
offset: 0x400 + 32 * 64 + 40,
|
||||
bytes_per_row: 64,
|
||||
width: 23,
|
||||
height: 15,
|
||||
},
|
||||
PlaneLayout {
|
||||
offset: 0x1000 + 16 * 64 + 40,
|
||||
bytes_per_row: 64,
|
||||
width: 12,
|
||||
height: 8,
|
||||
},
|
||||
]
|
||||
);
|
||||
let whole = TileRegion {
|
||||
width: 64,
|
||||
height: 48,
|
||||
x: 0,
|
||||
y: 0,
|
||||
..region
|
||||
};
|
||||
assert_eq!(region_layout(&layout, whole).unwrap().planes, layout.planes);
|
||||
}
|
||||
|
||||
/// A 10-bit surface's samples are two bytes each; a region past the surface, or at an odd
|
||||
/// column or row, is refused.
|
||||
#[test]
|
||||
fn a_tiles_region_past_its_surface_or_off_its_pairs_is_refused() {
|
||||
let mut ten = nv12();
|
||||
ten.pixel_format = u32::from_be_bytes(*b"x420");
|
||||
let layout = layout_of(&ten).unwrap();
|
||||
let region = TileRegion {
|
||||
source_x: 0,
|
||||
source_y: 0,
|
||||
width: 16,
|
||||
height: 16,
|
||||
x: 8,
|
||||
y: 8,
|
||||
};
|
||||
let part = region_layout(&layout, region).unwrap();
|
||||
assert_eq!(part.planes[0].offset, 0x400 + 8 * 64 + 16);
|
||||
assert_eq!(part.planes[1].offset, 0x1000 + 4 * 64 + 16);
|
||||
for (x, y, width) in [(50, 8, 16), (8, 40, 16), (7, 8, 16), (8, 9, 16), (0, 0, 65)] {
|
||||
let off = TileRegion {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
..region
|
||||
};
|
||||
assert!(region_layout(&layout, off).is_err(), "{x}, {y}, {width}");
|
||||
}
|
||||
let mut odd = nv12();
|
||||
odd.pixel_format = u32::from_be_bytes(*b"BGRA");
|
||||
assert!(region_layout(&layout_of(&odd).unwrap(), region).is_err());
|
||||
}
|
||||
|
||||
/// An encode the arm refuses for its source or settings is a parameter error to the guest,
|
||||
/// any other failure the encoder's malfunction.
|
||||
#[test]
|
||||
|
||||
@@ -1739,7 +1739,18 @@ Stages:
|
||||
the surface the guest lent for each (`crates/reims-vgpu/src/graphics/vt.rs`;
|
||||
on VA-API, written there by the driver's video processing where it
|
||||
takes the surface's layout, on NVDEC by the GPU into the surface's
|
||||
pages registered with CUDA, else copied by the CPU). `encs` lists one
|
||||
pages registered with CUDA, else copied by the CPU). A decoder
|
||||
session also starts a tile session (`dsts`), as CMPhoto's
|
||||
`VTTileDecompressionSession` asks of a HEIC image's grid, where the arm
|
||||
lands a part of a picture (on VA-API: the frame's crop narrowed to the
|
||||
tile's region, written as a whole picture is): each tile (`dtil`)
|
||||
lands in the surface it lends, emitted (`TDem`) before its reply.
|
||||
Elsewhere, on NVDEC today, the session answers `kVTUnimplementedErr`,
|
||||
and VideoToolbox decodes the image in software. Measured on an M3 Max
|
||||
on macOS 27.0.1 (oracle job m3-max-39549): CMPhoto decodes Mac Blue,
|
||||
6016x6016, as 36 tiles of 1024x1024, each whole into a 1024x1024
|
||||
`420f` buffer of its own, asynchronous, and Apple's hardware decoder
|
||||
answers each synchronously. `encs` lists one
|
||||
encoder for each codec the arm encodes the guest's frames of (on
|
||||
VA-API and on NVENC, each codec it encodes a profile of), by the ID of Apple's
|
||||
hardware encoder of the codec (`com.apple.videotoolbox.videoencoder.ave.avc`,
|
||||
|
||||
Reference in new issue
Block a user