#[cfg(test)]
mod vp9_depacketizer_fields_test;
#[cfg(test)]
mod vp9_descriptor_test;
#[cfg(test)]
mod vp9_layers_test;
#[cfg(test)]
mod vp9_test;
mod superframe;
pub use superframe::{VP9_MAX_SUPERFRAME_FRAMES, join_superframe, split_superframe};
use crate::packetizer::{Depacketizer, Payloader};
use shared::error::{Error, Result};
use bytes::{Buf, BufMut, Bytes, BytesMut};
use std::fmt;
use std::sync::Arc;
const VP9HEADER_SIZE: usize = 3;
const MAX_VP9REF_PICS: usize = 3;
const VP9_REF_SLOTS: usize = 8;
pub const VP9_MAX_SPATIAL_ID: u8 = 7;
pub const VP9_MAX_TEMPORAL_ID: u8 = 7;
pub const VP9_MAX_P_DIFF: u8 = 127;
pub type InitialPictureIDFn = Arc<dyn (Fn() -> u16) + Send + Sync>;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Vp9PictureGroupEntry {
pub temporal_id: u8,
pub switching_up_point: bool,
pub reference_diffs: Vec<u8>,
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Vp9ScalabilityStructure {
pub spatial_layers: u8,
pub resolutions: Vec<(u16, u16)>,
pub picture_group: Vec<Vp9PictureGroupEntry>,
}
impl Vp9ScalabilityStructure {
pub fn validate(&self) -> Result<()> {
let fail = |what: &str| Err(Error::Other(format!("VP9 scalability structure: {what}")));
if self.spatial_layers == 0 || self.spatial_layers > VP9_MAX_SPATIAL_ID + 1 {
return fail("1 to 8 spatial layers");
}
if !self.resolutions.is_empty() && self.resolutions.len() != self.spatial_layers as usize {
return fail("one resolution per spatial layer, or none");
}
if self.picture_group.len() > 255 {
return fail("at most 255 pictures in a picture group");
}
for entry in &self.picture_group {
if entry.temporal_id > VP9_MAX_TEMPORAL_ID {
return fail("TID is three bits");
}
if entry.reference_diffs.len() > MAX_VP9REF_PICS {
return fail("at most three reference indices per picture");
}
}
if self
.picture_group
.first()
.is_some_and(|e| e.temporal_id != 0)
{
return fail("the first picture of the group has TID 0");
}
Ok(())
}
pub fn marshal_size(&self) -> usize {
let mut size = 1 + 4 * self.resolutions.len();
if !self.picture_group.is_empty() {
size += 1;
for entry in &self.picture_group {
size += 1 + entry.reference_diffs.len();
}
}
size
}
pub fn marshal_to(&self, out: &mut BytesMut) -> Result<()> {
self.validate()?;
let mut b = (self.spatial_layers - 1) << 5;
if !self.resolutions.is_empty() {
b |= 0x10; }
if !self.picture_group.is_empty() {
b |= 0x08; }
out.put_u8(b);
for (width, height) in &self.resolutions {
out.put_u16(*width);
out.put_u16(*height);
}
if !self.picture_group.is_empty() {
out.put_u8(self.picture_group.len() as u8); for entry in &self.picture_group {
let mut b = entry.temporal_id << 5;
if entry.switching_up_point {
b |= 0x10;
}
b |= (entry.reference_diffs.len() as u8) << 2;
out.put_u8(b);
for diff in &entry.reference_diffs {
out.put_u8(*diff);
}
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Vp9FrameInfo {
pub temporal_id: u8,
pub spatial_id: u8,
pub switching_up_point: bool,
pub inter_layer_dependency: bool,
pub not_reference_for_upper_layers: bool,
pub end_of_picture: bool,
pub key_frame: Option<bool>,
pub inter_picture_predicted: Option<bool>,
pub reference_diffs: Vec<u8>,
}
impl Default for Vp9FrameInfo {
fn default() -> Self {
Self {
temporal_id: 0,
spatial_id: 0,
switching_up_point: false,
inter_layer_dependency: false,
not_reference_for_upper_layers: false,
end_of_picture: true,
key_frame: None,
inter_picture_predicted: None,
reference_diffs: vec![],
}
}
}
#[derive(Default, Clone)]
pub struct Vp9Payloader {
picture_id: u16,
initialized: bool,
pub initial_picture_id_fn: Option<InitialPictureIDFn>,
pub flexible_mode: bool,
pub initial_tl0_pic_idx: Option<u8>,
scalability_structure: Option<Vp9ScalabilityStructure>,
mode: Option<bool>,
picture_number: u64,
key_picture_number: u64,
picture_group_tids: Vec<u8>,
tl0_pic_idx: u8,
slots: [Option<u64>; VP9_REF_SLOTS],
open_picture_sid: Option<u8>,
next_frame_info: Option<Vp9FrameInfo>,
started: bool,
}
impl fmt::Debug for Vp9Payloader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Vp9Payloader")
.field("picture_id", &self.picture_id)
.field("initialized", &self.initialized)
.field("flexible_mode", &self.flexible_mode)
.field("mode", &self.mode)
.field("scalability_structure", &self.scalability_structure)
.field("tl0_pic_idx", &self.tl0_pic_idx)
.finish()
}
}
impl Payloader for Vp9Payloader {
fn payload(&mut self, mtu: usize, payload: &Bytes) -> Result<Vec<Bytes>> {
let info = self.next_frame_info.take();
self.payload_frame(mtu, payload, info.as_ref())
}
fn marker_rule(&self) -> crate::packetizer::MarkerRule {
if self.open_picture_sid.is_some() {
crate::packetizer::MarkerRule::Never
} else {
crate::packetizer::MarkerRule::LastPacketOfFrame
}
}
fn set_next_frame_info(&mut self, info: &dyn std::any::Any) {
if let Some(info) = info.downcast_ref::<Vp9FrameInfo>() {
self.next_frame_info = Some(info.clone());
}
}
fn clone_to(&self) -> Box<dyn Payloader> {
Box::new(self.clone())
}
}
impl Vp9Payloader {
pub fn set_scalability_structure(
&mut self,
structure: Option<Vp9ScalabilityStructure>,
) -> Result<()> {
if let Some(structure) = &structure {
structure.validate()?;
}
self.scalability_structure = structure;
Ok(())
}
pub fn picture_id(&self) -> u16 {
self.picture_id
}
pub fn payload_layer_frame(
&mut self,
mtu: usize,
frame: &Bytes,
info: &Vp9FrameInfo,
) -> Result<Vec<Bytes>> {
self.payload_frame(mtu, frame, Some(info))
}
fn payload_frame(
&mut self,
mtu: usize,
frame: &Bytes,
info: Option<&Vp9FrameInfo>,
) -> Result<Vec<Bytes>> {
let fail = |what: String| Err(Error::Other(format!("VP9 payloader: {what}")));
if let Some(info) = info {
if info.temporal_id > VP9_MAX_TEMPORAL_ID || info.spatial_id > VP9_MAX_SPATIAL_ID {
return fail(format!(
"TID {} / SID {} do not fit three bits",
info.temporal_id, info.spatial_id
));
}
if info.inter_layer_dependency && info.spatial_id == 0 {
return fail("D must be 0 on spatial layer 0".to_owned());
}
if info.reference_diffs.len() > MAX_VP9REF_PICS
|| info
.reference_diffs
.iter()
.any(|d| *d == 0 || *d > VP9_MAX_P_DIFF)
{
return fail("at most three reference indices, each 1 to 127".to_owned());
}
if let Some(open_sid) = self.open_picture_sid
&& info.spatial_id <= open_sid
{
return fail(format!(
"SID {} after SID {open_sid} in one picture",
info.spatial_id
));
}
}
if frame.is_empty() || mtu == 0 {
return Ok(vec![]);
}
if !self.initialized {
if self.initial_picture_id_fn.is_none() {
self.initial_picture_id_fn =
Some(Arc::new(|| -> u16 { rand::random::<u16>() & 0x7FFF }));
}
self.picture_id = if let Some(f) = &self.initial_picture_id_fn {
f() & 0x7FFF
} else {
0
};
self.tl0_pic_idx = self
.initial_tl0_pic_idx
.unwrap_or_else(rand::random::<u8>)
.wrapping_sub(1);
self.initialized = true;
}
let header = Vp9FrameHeader::parse(frame);
let first_of_picture = self.open_picture_sid.is_none();
let spatial_id = info.map_or(0, |i| i.spatial_id);
let temporal_id = info.map_or(0, |i| i.temporal_id);
let key_frame = info
.and_then(|i| i.key_frame)
.unwrap_or_else(|| header.is_some_and(|h| h.key_frame));
let key_picture_start = key_frame && first_of_picture && spatial_id == 0;
let flexible = match self.mode {
Some(mode) if !key_picture_start => mode,
_ => {
self.flexible_mode
|| (header.is_none() && info.is_none_or(|i| i.key_frame.is_none()))
}
};
let derived = self.references(header.as_ref(), key_frame);
let predicted = info
.and_then(|i| i.inter_picture_predicted)
.unwrap_or(derived.0);
let mut reference_diffs: Vec<u8> = vec![];
if predicted && flexible {
reference_diffs = match info {
Some(info) if !info.reference_diffs.is_empty() => info.reference_diffs.clone(),
_ => derived.1,
};
if reference_diffs.is_empty() {
reference_diffs.push(1);
}
}
if !predicted && temporal_id != 0 {
return fail(format!(
"a frame without inter-picture prediction has TID {temporal_id}"
));
}
let picture_group_tids = if key_picture_start {
self.key_picture_structure(flexible, header.as_ref())
.map(|s| s.picture_group.iter().map(|e| e.temporal_id).collect())
.unwrap_or_default()
} else {
self.picture_group_tids.clone()
};
if !flexible && info.is_some() && !picture_group_tids.is_empty() {
let since_key = if key_picture_start {
0
} else {
self.picture_number.wrapping_sub(self.key_picture_number)
};
let expected =
picture_group_tids[(since_key % picture_group_tids.len() as u64) as usize];
if expected != temporal_id {
return fail(format!(
"TID {temporal_id} where the picture group has TID {expected}"
));
}
}
let mut ss = BytesMut::new();
if key_picture_start
&& let Some(structure) = self.key_picture_structure(flexible, header.as_ref())
{
structure.marshal_to(&mut ss)?;
}
let tl0_pic_idx = if !flexible && info.is_some() && first_of_picture && temporal_id == 0 {
self.tl0_pic_idx.wrapping_add(1)
} else {
self.tl0_pic_idx
};
let mut descriptor = BytesMut::with_capacity(8);
descriptor.put_u8((self.picture_id >> 8) as u8 | 0x80);
descriptor.put_u8((self.picture_id & 0xFF) as u8);
let mut b0 = 0x80; if predicted {
b0 |= 0x40; }
if flexible {
b0 |= 0x10; }
match info {
Some(info) => {
b0 |= 0x20; let mut layer = (info.temporal_id << 5) | (info.spatial_id << 1);
if info.switching_up_point {
layer |= 0x10; }
if info.inter_layer_dependency {
layer |= 0x01; }
descriptor.put_u8(layer);
if !flexible {
descriptor.put_u8(tl0_pic_idx);
}
if info.not_reference_for_upper_layers {
b0 |= 0x01; }
}
None if !flexible => b0 |= 0x01,
None => {}
}
for (i, diff) in reference_diffs.iter().enumerate() {
let more = i + 1 < reference_diffs.len();
descriptor.put_u8((diff << 1) | more as u8);
}
let header_size = 1 + descriptor.len();
if mtu <= header_size + ss.len() {
return match info {
Some(_) => fail(format!(
"an MTU of {mtu} has no room for a descriptor of {} octets",
header_size + ss.len()
)),
None => Ok(vec![]),
};
}
let mut payloads = vec![];
let mut index = 0;
while index < frame.len() {
let with_ss = index == 0 && !ss.is_empty();
let room = mtu - header_size - if with_ss { ss.len() } else { 0 };
let fragment = std::cmp::min(room, frame.len() - index);
let mut out = BytesMut::with_capacity(mtu.min(header_size + ss.len() + fragment));
let mut b = b0;
if index == 0 {
b |= 0x08; }
if index + fragment == frame.len() {
b |= 0x04; }
if with_ss {
b |= 0x02; }
out.put_u8(b);
out.put(&descriptor[..]);
if with_ss {
out.put(&ss[..]);
}
out.put(&frame[index..index + fragment]);
payloads.push(out.freeze());
index += fragment;
}
self.started = true;
self.mode = Some(flexible);
self.tl0_pic_idx = tl0_pic_idx;
if key_picture_start {
self.key_picture_number = self.picture_number;
self.picture_group_tids = picture_group_tids;
}
if key_frame {
self.slots = [Some(self.picture_number); VP9_REF_SLOTS];
} else if let Some(refresh) = header.and_then(|h| h.refresh_frame_flags) {
for (i, slot) in self.slots.iter_mut().enumerate() {
if refresh & (1 << i) != 0 {
*slot = Some(self.picture_number);
}
}
}
if info.is_none_or(|i| i.end_of_picture) {
self.open_picture_sid = None;
self.picture_number += 1;
self.picture_id = (self.picture_id + 1) & 0x7FFF;
} else {
self.open_picture_sid = Some(spatial_id);
}
Ok(payloads)
}
fn references(&self, header: Option<&Vp9FrameHeader>, key_frame: bool) -> (bool, Vec<u8>) {
if key_frame {
return (false, vec![]);
}
let Some(header) = header else {
return (self.started, vec![]);
};
if header.intra_only {
return (false, vec![]);
}
let slots: Vec<u8> = match (header.show_existing, header.ref_frame_idx) {
(Some(slot), _) => vec![slot],
(None, Some(refs)) => refs.to_vec(),
(None, None) => return (true, vec![]),
};
let mut diffs: Vec<u8> = vec![];
let mut predicted = false;
for slot in slots {
match self.slots[slot as usize] {
Some(picture) if picture == self.picture_number => {}
Some(picture) => {
predicted = true;
let diff = (self.picture_number - picture).min(VP9_MAX_P_DIFF as u64) as u8;
if !diffs.contains(&diff) {
diffs.push(diff);
}
}
None => predicted = true,
}
}
(predicted, diffs)
}
fn key_picture_structure(
&self,
flexible: bool,
header: Option<&Vp9FrameHeader>,
) -> Option<Vp9ScalabilityStructure> {
if let Some(structure) = &self.scalability_structure {
return Some(structure.clone());
}
if flexible {
return None;
}
let resolutions = match header.and_then(|h| h.size) {
Some((width, height)) if width <= 0xFFFF && height <= 0xFFFF => {
vec![(width as u16, height as u16)]
}
_ => vec![],
};
Some(Vp9ScalabilityStructure {
spatial_layers: 1,
resolutions,
picture_group: vec![Vp9PictureGroupEntry {
temporal_id: 0,
switching_up_point: true,
reference_diffs: vec![1],
}],
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct Vp9FrameHeader {
pub(crate) key_frame: bool,
pub(crate) intra_only: bool,
pub(crate) show_existing: Option<u8>,
pub(crate) size: Option<(u32, u32)>,
pub(crate) refresh_frame_flags: Option<u8>,
pub(crate) ref_frame_idx: Option<[u8; 3]>,
}
struct BitReader<'a> {
data: &'a [u8],
pos: usize,
}
impl BitReader<'_> {
fn bits(&mut self, n: usize) -> Option<u32> {
let mut v = 0u32;
for _ in 0..n {
let byte = *self.data.get(self.pos / 8)?;
v = (v << 1) | ((byte >> (7 - (self.pos % 8))) & 1) as u32;
self.pos += 1;
}
Some(v)
}
}
impl Vp9FrameHeader {
pub(crate) fn parse(frame: &[u8]) -> Option<Self> {
let mut r = BitReader {
data: frame,
pos: 0,
};
if r.bits(2)? != 2 {
return None; }
let low = r.bits(1)?;
let high = r.bits(1)?;
let profile = (high << 1) | low;
if profile == 3 {
r.bits(1)?; }
if r.bits(1)? == 1 {
return Some(Self {
show_existing: Some(r.bits(3)? as u8),
..Default::default()
});
}
let key_frame = r.bits(1)? == 0;
let show_frame = r.bits(1)? == 1;
let error_resilient_mode = r.bits(1)? == 1;
if key_frame {
if r.bits(24)? != 0x49_83_42 {
return None; }
Self::color_config(&mut r, profile)?;
let width = r.bits(16)? + 1;
let height = r.bits(16)? + 1;
return Some(Self {
key_frame,
size: Some((width, height)),
..Default::default()
});
}
let mut header = Self::default();
let rest = (|| -> Option<()> {
header.intra_only = !show_frame && r.bits(1)? == 1;
if !error_resilient_mode {
r.bits(2)?; }
if header.intra_only {
if r.bits(24)? != 0x49_83_42 {
return None; }
if profile > 0 {
Self::color_config(&mut r, profile)?;
}
header.refresh_frame_flags = Some(r.bits(8)? as u8);
} else {
header.refresh_frame_flags = Some(r.bits(8)? as u8);
let mut refs = [0u8; 3];
for slot in &mut refs {
*slot = r.bits(3)? as u8;
r.bits(1)?; }
header.ref_frame_idx = Some(refs);
}
Some(())
})();
let _ = rest;
Some(header)
}
fn color_config(r: &mut BitReader<'_>, profile: u32) -> Option<()> {
if profile >= 2 {
r.bits(1)?; }
let color_space = r.bits(3)?;
if color_space != 7 {
r.bits(1)?; if profile == 1 || profile == 3 {
r.bits(3)?; }
} else if profile == 1 || profile == 3 {
r.bits(1)?; }
Some(())
}
}
#[derive(PartialEq, Eq, Debug, Default, Clone)]
pub struct Vp9Packet {
pub i: bool,
pub p: bool,
pub l: bool,
pub f: bool,
pub b: bool,
pub e: bool,
pub v: bool,
pub z: bool,
pub picture_id: u16,
pub picture_id_15_bits: bool,
pub tid: u8,
pub u: bool,
pub sid: u8,
pub d: bool,
pub pdiff: Vec<u8>,
pub tl0picidx: u8,
pub ns: u8,
pub y: bool,
pub g: bool,
pub ng: u8,
pub width: Vec<u16>,
pub height: Vec<u16>,
pub pgtid: Vec<u8>,
pub pgu: Vec<bool>,
pub pgpdiff: Vec<Vec<u8>>,
}
impl Depacketizer for Vp9Packet {
fn depacketize(&mut self, packet: &Bytes) -> Result<Bytes> {
if packet.is_empty() {
return Err(Error::ErrShortPacket);
}
*self = Self::default();
let reader = &mut packet.clone();
let b = reader.get_u8();
self.i = (b & 0x80) != 0;
self.p = (b & 0x40) != 0;
self.l = (b & 0x20) != 0;
self.f = (b & 0x10) != 0 && self.i;
self.b = (b & 0x08) != 0;
self.e = (b & 0x04) != 0;
self.v = (b & 0x02) != 0;
self.z = (b & 0x01) != 0;
let mut payload_index = 1;
if self.i {
payload_index = self.parse_picture_id(reader, payload_index)?;
}
if self.l {
payload_index = self.parse_layer_info(reader, payload_index)?;
}
if self.f && self.p {
payload_index = self.parse_ref_indices(reader, payload_index)?;
}
if self.v {
payload_index = self.parse_ssdata(reader, payload_index)?;
}
Ok(packet.slice(payload_index..))
}
fn is_partition_head(&self, payload: &Bytes) -> bool {
let Some(&b) = payload.first() else {
return false;
};
if b & 0x08 == 0 {
return false;
}
if b & 0x20 != 0 {
let mut index = 1;
if b & 0x80 != 0 {
index += match payload.get(1) {
Some(m) if m & 0x80 != 0 => 2,
_ => 1,
};
}
if payload.get(index).is_some_and(|layer| layer & 0x01 != 0) {
return false;
}
}
true
}
fn is_partition_tail(&self, marker: bool, _payload: &Bytes) -> bool {
marker
}
fn has_key_frames(&self) -> bool {
true
}
fn is_key_frame_start(&self, payload: &Bytes) -> bool {
let Some(&b) = payload.first() else {
return false;
};
if b & 0x40 != 0 || !self.is_partition_head(payload) {
return false;
}
if b & 0x20 != 0 {
let mut index = 1;
if b & 0x80 != 0 {
index += match payload.get(1) {
Some(m) if m & 0x80 != 0 => 2,
_ => 1,
};
}
return payload
.get(index)
.is_some_and(|layer| (layer >> 1) & 0x07 == 0);
}
true
}
}
impl Vp9Packet {
fn parse_picture_id(
&mut self,
reader: &mut dyn Buf,
mut payload_index: usize,
) -> Result<usize> {
if reader.remaining() == 0 {
return Err(Error::ErrShortPacket);
}
let b = reader.get_u8();
payload_index += 1;
if (b & 0x80) != 0 {
if reader.remaining() == 0 {
return Err(Error::ErrShortPacket);
}
self.picture_id = (((b & 0x7f) as u16) << 8) | (reader.get_u8() as u16);
self.picture_id_15_bits = true;
payload_index += 1;
} else {
self.picture_id = (b & 0x7F) as u16;
}
Ok(payload_index)
}
fn parse_layer_info(
&mut self,
reader: &mut dyn Buf,
mut payload_index: usize,
) -> Result<usize> {
payload_index = self.parse_layer_info_common(reader, payload_index)?;
if self.f {
Ok(payload_index)
} else {
self.parse_layer_info_non_flexible_mode(reader, payload_index)
}
}
fn parse_layer_info_common(
&mut self,
reader: &mut dyn Buf,
mut payload_index: usize,
) -> Result<usize> {
if reader.remaining() == 0 {
return Err(Error::ErrShortPacket);
}
let b = reader.get_u8();
payload_index += 1;
self.tid = b >> 5;
self.u = b & 0x10 != 0;
self.sid = (b >> 1) & 0x7;
self.d = b & 0x01 != 0;
Ok(payload_index)
}
fn parse_layer_info_non_flexible_mode(
&mut self,
reader: &mut dyn Buf,
mut payload_index: usize,
) -> Result<usize> {
if reader.remaining() == 0 {
return Err(Error::ErrShortPacket);
}
self.tl0picidx = reader.get_u8();
payload_index += 1;
Ok(payload_index)
}
fn parse_ref_indices(
&mut self,
reader: &mut dyn Buf,
mut payload_index: usize,
) -> Result<usize> {
let mut b = 1u8;
while (b & 0x1) != 0 {
if reader.remaining() == 0 {
return Err(Error::ErrShortPacket);
}
b = reader.get_u8();
payload_index += 1;
self.pdiff.push(b >> 1);
if self.pdiff.len() > MAX_VP9REF_PICS {
return Err(Error::ErrTooManyPDiff);
}
}
Ok(payload_index)
}
fn parse_ssdata(&mut self, reader: &mut dyn Buf, mut payload_index: usize) -> Result<usize> {
if reader.remaining() == 0 {
return Err(Error::ErrShortPacket);
}
let b = reader.get_u8();
payload_index += 1;
self.ns = b >> 5;
self.y = b & 0x10 != 0;
self.g = b & 0x08 != 0;
let ns = (self.ns + 1) as usize;
if self.y {
if reader.remaining() < 4 * ns {
return Err(Error::ErrShortPacket);
}
self.width = vec![0u16; ns];
self.height = vec![0u16; ns];
for i in 0..ns {
self.width[i] = reader.get_u16();
self.height[i] = reader.get_u16();
}
payload_index += 4 * ns;
}
if self.g {
if reader.remaining() == 0 {
return Err(Error::ErrShortPacket);
}
self.ng = reader.get_u8();
payload_index += 1;
}
for i in 0..self.ng as usize {
if reader.remaining() == 0 {
return Err(Error::ErrShortPacket);
}
let b = reader.get_u8();
payload_index += 1;
self.pgtid.push(b >> 5);
self.pgu.push(b & 0x10 != 0);
let r = ((b >> 2) & 0x3) as usize;
if reader.remaining() < r {
return Err(Error::ErrShortPacket);
}
self.pgpdiff.push(vec![]);
for _ in 0..r {
let b = reader.get_u8();
payload_index += 1;
self.pgpdiff[i].push(b);
}
}
Ok(payload_index)
}
pub fn scalability_structure(&self) -> Option<Vp9ScalabilityStructure> {
if !self.v {
return None;
}
Some(Vp9ScalabilityStructure {
spatial_layers: self.ns + 1,
resolutions: self
.width
.iter()
.copied()
.zip(self.height.iter().copied())
.collect(),
picture_group: (0..self.pgtid.len())
.map(|i| Vp9PictureGroupEntry {
temporal_id: self.pgtid[i],
switching_up_point: self.pgu[i],
reference_diffs: self.pgpdiff[i].clone(),
})
.collect(),
})
}
pub fn referenced_picture_id(&self, reference_diff: u8) -> u16 {
let mask = if self.picture_id_15_bits {
0x7FFF
} else {
0x7F
};
self.picture_id.wrapping_sub(reference_diff as u16) & mask
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Vp9Forward {
pub forward: bool,
pub marker: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Vp9LayerFilter {
target_sid: u8,
target_tid: u8,
current_sid: u8,
current_tid: u8,
decodable: [bool; 8],
picture: Option<(Option<u16>, u8)>,
picture_closed: bool,
frame: Option<(u8, bool)>,
}
impl Vp9LayerFilter {
pub fn new(target_sid: u8, target_tid: u8) -> Self {
Self {
target_sid: target_sid.min(VP9_MAX_SPATIAL_ID),
target_tid: target_tid.min(VP9_MAX_TEMPORAL_ID),
current_sid: 0,
current_tid: 0,
decodable: [false; 8],
picture: None,
picture_closed: false,
frame: None,
}
}
pub fn set_target(&mut self, target_sid: u8, target_tid: u8) {
self.target_sid = target_sid.min(VP9_MAX_SPATIAL_ID);
self.target_tid = target_tid.min(VP9_MAX_TEMPORAL_ID);
self.current_tid = self.current_tid.min(self.target_tid);
}
pub fn target(&self) -> (u8, u8) {
(self.target_sid, self.target_tid)
}
pub fn current(&self) -> (u8, u8) {
(self.current_sid, self.current_tid)
}
pub fn needs_key_frame(&self) -> bool {
!self.decodable[self.current_sid as usize]
|| (self.target_sid < self.current_sid && !self.decodable[self.target_sid as usize])
}
pub fn forward(&mut self, descriptor: &Vp9Packet, marker: bool) -> Vp9Forward {
if !descriptor.l {
return Vp9Forward {
forward: true,
marker,
};
}
let sid = descriptor.sid;
let picture_id = descriptor.i.then_some(descriptor.picture_id);
let new_picture = match (self.picture, self.frame) {
(Some((id, _)), Some((last_sid, _))) => {
id != picture_id || (picture_id.is_none() && descriptor.b && sid <= last_sid)
}
_ => true,
};
if new_picture {
self.picture = Some((picture_id, 0));
self.picture_closed = false;
self.frame = None;
}
let decided = match self.frame {
Some((frame_sid, forward)) if frame_sid == sid && !descriptor.b => Some(forward),
_ => None,
};
let forward = decided.unwrap_or_else(|| self.decide(descriptor));
self.frame = Some((sid, forward));
let ends_here = forward
&& descriptor.e
&& sid == self.current_sid
&& (self.current_sid >= self.target_sid || descriptor.p);
let marker = forward && (marker || ends_here);
self.picture_closed |= marker;
Vp9Forward { forward, marker }
}
fn decide(&mut self, d: &Vp9Packet) -> bool {
let sid = d.sid;
let s = sid as usize;
let forwarded_sids = self.picture.map_or(0, |(_, mask)| mask);
let lower_ok = !d.d || (sid > 0 && forwarded_sids & (1 << (sid - 1)) != 0);
let decodable = (!d.p || self.decodable[s]) && lower_ok;
if d.tid > self.current_tid {
return false;
}
let wanted = if sid == self.current_sid {
true
} else if sid < self.current_sid {
!d.z || sid == self.target_sid
} else {
sid <= self.target_sid && !d.p && !self.picture_closed
};
let forward = wanted && decodable;
if forward {
self.decodable[s] = true;
if let Some((_, mask)) = &mut self.picture {
*mask |= 1 << sid;
}
if sid > self.current_sid || (sid == self.target_sid && sid < self.current_sid) {
self.current_sid = sid;
}
if d.u || (d.v && !d.p) {
self.current_tid = self.target_tid;
}
} else {
self.decodable[s] = false;
}
forward
}
}