mod bits;
#[cfg(test)]
pub(crate) mod dependency_descriptor_test;
mod selector;
#[cfg(test)]
mod selector_test;
mod writer;
#[cfg(test)]
mod writer_test;
pub use selector::DecodeTargetSelector;
pub use writer::{DependencyDescriptorWriter, FrameDescriptor};
use bits::{BitReader, BitWriter};
use bytes::Bytes;
use shared::error::{Error, Result};
pub const DEPENDENCY_DESCRIPTOR_URI: &str =
"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";
pub const MAX_DECODE_TARGETS: usize = 32;
pub const MAX_TEMPLATES: usize = 64;
pub const MAX_FRAME_DIFF: u16 = 4096;
pub const MAX_TEMPLATE_FRAME_DIFF: u16 = 16;
pub const MAX_TEMPLATE_CHAIN_DIFF: u8 = 15;
fn invalid<T>(what: &str) -> Result<T> {
Err(Error::Other(format!("dependency descriptor: {what}")))
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum DecodeTargetIndication {
#[default]
NotPresent = 0,
Discardable = 1,
Switch = 2,
Required = 3,
}
impl DecodeTargetIndication {
fn from_bits(bits: u32) -> Self {
match bits & 0x3 {
0 => Self::NotPresent,
1 => Self::Discardable,
2 => Self::Switch,
_ => Self::Required,
}
}
pub fn symbol(self) -> char {
match self {
Self::NotPresent => '-',
Self::Discardable => 'D',
Self::Switch => 'S',
Self::Required => 'R',
}
}
pub fn from_symbols(symbols: &str) -> Option<Vec<Self>> {
symbols
.chars()
.map(|c| match c {
'-' => Some(Self::NotPresent),
'D' => Some(Self::Discardable),
'S' => Some(Self::Switch),
'R' => Some(Self::Required),
_ => None,
})
.collect()
}
pub fn is_present(self) -> bool {
self != Self::NotPresent
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct FrameDependencyTemplate {
pub spatial_id: u8,
pub temporal_id: u8,
pub dtis: Vec<DecodeTargetIndication>,
pub fdiffs: Vec<u16>,
pub chain_fdiffs: Vec<u8>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RenderResolution {
pub width: u32,
pub height: u32,
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct FrameDependencyStructure {
pub template_id_offset: u8,
pub num_decode_targets: usize,
pub num_chains: usize,
pub decode_target_protected_by: Vec<u8>,
pub resolutions: Vec<RenderResolution>,
pub templates: Vec<FrameDependencyTemplate>,
}
impl FrameDependencyStructure {
pub fn validate(&self) -> Result<()> {
if self.template_id_offset as usize >= MAX_TEMPLATES {
return invalid("template_id_offset is six bits");
}
if self.num_decode_targets == 0 || self.num_decode_targets > MAX_DECODE_TARGETS {
return invalid("1 to 32 decode targets");
}
if self.templates.is_empty() || self.templates.len() > MAX_TEMPLATES {
return invalid("1 to 64 templates");
}
if self.num_chains > self.num_decode_targets {
return invalid("no more chains than decode targets");
}
if self.num_chains == 0 {
if !self.decode_target_protected_by.is_empty() {
return invalid("decode_target_protected_by without chains");
}
} else if self.decode_target_protected_by.len() != self.num_decode_targets
|| self
.decode_target_protected_by
.iter()
.any(|c| *c as usize >= self.num_chains)
{
return invalid("each decode target is protected by one of the chains");
}
let mut previous = (0u8, 0u8);
for (i, template) in self.templates.iter().enumerate() {
let layer = (template.spatial_id, template.temporal_id);
let reachable = if i == 0 {
layer == (0, 0)
} else {
layer == previous
|| layer == (previous.0, previous.1.wrapping_add(1))
|| (template.spatial_id == previous.0.wrapping_add(1)
&& template.temporal_id == 0)
};
if !reachable {
return invalid(
"templates are ordered by spatial then temporal layer, without gaps",
);
}
previous = layer;
if template.dtis.len() != self.num_decode_targets {
return invalid("one decode target indication per decode target");
}
if template
.fdiffs
.iter()
.any(|d| *d == 0 || *d > MAX_TEMPLATE_FRAME_DIFF)
{
return invalid("a template's frame differences are 1 to 16");
}
if template.chain_fdiffs.len() != self.num_chains
|| template
.chain_fdiffs
.iter()
.any(|d| *d > MAX_TEMPLATE_CHAIN_DIFF)
{
return invalid("a template has one chain difference per chain, 0 to 15");
}
}
if !self.resolutions.is_empty() {
if self.resolutions.len() != self.max_spatial_id() as usize + 1 {
return invalid("one resolution per spatial layer, or none");
}
if self
.resolutions
.iter()
.any(|r| r.width == 0 || r.width > 65536 || r.height == 0 || r.height > 65536)
{
return invalid("a resolution is 1 to 65536 in each dimension");
}
}
Ok(())
}
pub fn max_spatial_id(&self) -> u8 {
self.templates.last().map_or(0, |t| t.spatial_id)
}
pub fn max_temporal_id(&self) -> u8 {
self.templates
.iter()
.map(|t| t.temporal_id)
.max()
.unwrap_or(0)
}
pub fn decode_target_layers(&self) -> Vec<(u8, u8)> {
(0..self.num_decode_targets.min(MAX_DECODE_TARGETS))
.map(|dt| {
let mut spatial_id = 0;
let mut temporal_id = 0;
for template in &self.templates {
if template.dtis.get(dt).is_some_and(|dti| dti.is_present()) {
spatial_id = spatial_id.max(template.spatial_id);
temporal_id = temporal_id.max(template.temporal_id);
}
}
(spatial_id, temporal_id)
})
.collect()
}
pub fn decode_target_for(&self, spatial_id: u8, temporal_id: u8) -> Option<usize> {
self.decode_target_layers()
.into_iter()
.enumerate()
.filter(|(_, (s, t))| *s <= spatial_id && *t <= temporal_id)
.max_by_key(|(dt, (s, t))| (*s, *t, std::cmp::Reverse(*dt)))
.map(|(dt, _)| dt)
}
pub fn template_index(&self, template_id: u8) -> Option<usize> {
let index = (template_id as usize + MAX_TEMPLATES - self.template_id_offset as usize)
% MAX_TEMPLATES;
(index < self.templates.len()).then_some(index)
}
pub fn template_id(&self, index: usize) -> u8 {
((self.template_id_offset as usize + index) % MAX_TEMPLATES) as u8
}
pub fn all_decode_targets(&self) -> u32 {
if self.num_decode_targets >= 32 {
u32::MAX
} else {
(1u32 << self.num_decode_targets) - 1
}
}
pub fn next_template_id_offset(&self) -> u8 {
self.template_id(self.templates.len())
}
fn write(&self, w: &mut BitWriter) {
w.f(6, self.template_id_offset as u32);
w.f(5, self.num_decode_targets as u32 - 1);
for (i, template) in self.templates.iter().enumerate() {
let next_layer_idc = match self.templates.get(i + 1) {
None => 3,
Some(next) if next.spatial_id != template.spatial_id => 2,
Some(next) if next.temporal_id != template.temporal_id => 1,
Some(_) => 0,
};
w.f(2, next_layer_idc);
}
for template in &self.templates {
for dti in &template.dtis {
w.f(2, *dti as u32);
}
}
for template in &self.templates {
for fdiff in &template.fdiffs {
w.flag(true); w.f(4, *fdiff as u32 - 1);
}
w.flag(false);
}
w.ns(self.num_decode_targets as u32 + 1, self.num_chains as u32);
if self.num_chains > 0 {
for chain in &self.decode_target_protected_by {
w.ns(self.num_chains as u32, *chain as u32);
}
for template in &self.templates {
for chain_fdiff in &template.chain_fdiffs {
w.f(4, *chain_fdiff as u32);
}
}
}
w.flag(!self.resolutions.is_empty());
for resolution in &self.resolutions {
w.f(16, resolution.width - 1);
w.f(16, resolution.height - 1);
}
}
fn read(r: &mut BitReader<'_>) -> Result<Self> {
let template_id_offset = r.f(6)? as u8;
let num_decode_targets = r.f(5)? as usize + 1;
let mut templates: Vec<FrameDependencyTemplate> = vec![];
let (mut spatial_id, mut temporal_id) = (0u8, 0u8);
loop {
if templates.len() == MAX_TEMPLATES {
return invalid("more than 64 templates");
}
templates.push(FrameDependencyTemplate {
spatial_id,
temporal_id,
..Default::default()
});
match r.f(2)? {
0 => {}
1 => temporal_id += 1,
2 => {
temporal_id = 0;
spatial_id += 1;
}
_ => break,
}
}
for template in &mut templates {
template.dtis.reserve_exact(num_decode_targets);
for _ in 0..num_decode_targets {
template
.dtis
.push(DecodeTargetIndication::from_bits(r.f(2)?));
}
}
for template in &mut templates {
while r.flag()? {
template.fdiffs.push(r.f(4)? as u16 + 1);
}
}
let num_chains = r.ns(num_decode_targets as u32 + 1)? as usize;
let mut decode_target_protected_by = vec![];
if num_chains > 0 {
for _ in 0..num_decode_targets {
decode_target_protected_by.push(r.ns(num_chains as u32)? as u8);
}
for template in &mut templates {
for _ in 0..num_chains {
template.chain_fdiffs.push(r.f(4)? as u8);
}
}
}
let mut resolutions = vec![];
if r.flag()? {
for _ in 0..=spatial_id {
resolutions.push(RenderResolution {
width: r.f(16)? + 1,
height: r.f(16)? + 1,
});
}
}
Ok(Self {
template_id_offset,
num_decode_targets,
num_chains,
decode_target_protected_by,
resolutions,
templates,
})
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct DependencyDescriptor {
pub start_of_frame: bool,
pub end_of_frame: bool,
pub frame_number: u16,
pub template_id: u8,
pub attached_structure: Option<FrameDependencyStructure>,
pub active_decode_targets_bitmask: Option<u32>,
pub spatial_id: u8,
pub temporal_id: u8,
pub dtis: Vec<DecodeTargetIndication>,
pub fdiffs: Vec<u16>,
pub chain_fdiffs: Vec<u8>,
pub resolution: Option<RenderResolution>,
}
impl DependencyDescriptor {
pub fn from_template(
structure: &FrameDependencyStructure,
template_index: usize,
frame_number: u16,
) -> Option<Self> {
let template = structure.templates.get(template_index)?;
Some(Self {
frame_number,
template_id: structure.template_id(template_index),
spatial_id: template.spatial_id,
temporal_id: template.temporal_id,
dtis: template.dtis.clone(),
fdiffs: template.fdiffs.clone(),
chain_fdiffs: template.chain_fdiffs.clone(),
resolution: structure
.resolutions
.get(template.spatial_id as usize)
.copied(),
..Default::default()
})
}
pub fn referred_frame_number(&self, fdiff: u16) -> u16 {
self.frame_number.wrapping_sub(fdiff)
}
pub fn marshal(&self, structure: &FrameDependencyStructure) -> Result<Bytes> {
if let Some(attached) = &self.attached_structure {
if attached != structure {
return invalid("the attached structure is not the one in force");
}
attached.validate()?;
}
if structure.num_decode_targets == 0 || structure.num_decode_targets > MAX_DECODE_TARGETS {
return invalid("1 to 32 decode targets");
}
let Some(template_index) = structure.template_index(self.template_id) else {
return invalid("frame_dependency_template_id is not one of the structure's");
};
let template = &structure.templates[template_index];
if (template.spatial_id, template.temporal_id) != (self.spatial_id, self.temporal_id) {
return invalid("the frame's layer is not its template's");
}
if self.dtis.len() != structure.num_decode_targets {
return invalid("one decode target indication per decode target");
}
if self.chain_fdiffs.len() != structure.num_chains {
return invalid("one chain difference per chain");
}
if self.fdiffs.iter().any(|d| *d == 0 || *d > MAX_FRAME_DIFF) {
return invalid("a frame difference is 1 to 4096");
}
let all_active = structure.all_decode_targets();
if let Some(bitmask) = self.active_decode_targets_bitmask
&& bitmask & !all_active != 0
{
return invalid("the bitmask names decode targets the structure does not have");
}
let custom_dtis = self.dtis != template.dtis;
let custom_fdiffs = self.fdiffs != template.fdiffs;
let custom_chains = self.chain_fdiffs != template.chain_fdiffs;
let active_decode_targets = self
.active_decode_targets_bitmask
.filter(|bitmask| self.attached_structure.is_none() || *bitmask != all_active);
let mut w = BitWriter::default();
w.flag(self.start_of_frame);
w.flag(self.end_of_frame);
w.f(6, self.template_id as u32);
w.f(16, self.frame_number as u32);
let extended = self.attached_structure.is_some()
|| active_decode_targets.is_some()
|| custom_dtis
|| custom_fdiffs
|| custom_chains;
if extended {
w.flag(self.attached_structure.is_some());
w.flag(active_decode_targets.is_some());
w.flag(custom_dtis);
w.flag(custom_fdiffs);
w.flag(custom_chains);
if let Some(attached) = &self.attached_structure {
attached.write(&mut w);
}
if let Some(bitmask) = active_decode_targets {
w.f(structure.num_decode_targets, bitmask);
}
if custom_dtis {
for dti in &self.dtis {
w.f(2, *dti as u32);
}
}
if custom_fdiffs {
for fdiff in &self.fdiffs {
let fdiff_minus_one = *fdiff as u32 - 1;
let next_fdiff_size = match fdiff_minus_one {
0..=0xF => 1,
0x10..=0xFF => 2,
_ => 3,
};
w.f(2, next_fdiff_size);
w.f(4 * next_fdiff_size as usize, fdiff_minus_one);
}
w.f(2, 0);
}
if custom_chains {
for chain_fdiff in &self.chain_fdiffs {
w.f(8, *chain_fdiff as u32);
}
}
}
Ok(Bytes::from(w.finish()))
}
pub fn unmarshal_mandatory(data: &[u8]) -> Result<(bool, bool, u8, u16)> {
let mut r = BitReader::new(data);
Ok((r.flag()?, r.flag()?, r.f(6)? as u8, r.f(16)? as u16))
}
pub fn unmarshal(
data: &[u8],
structure: Option<&FrameDependencyStructure>,
) -> Result<Option<Self>> {
let mut r = BitReader::new(data);
let mut descriptor = Self {
start_of_frame: r.flag()?,
end_of_frame: r.flag()?,
template_id: r.f(6)? as u8,
frame_number: r.f(16)? as u16,
..Default::default()
};
let mut custom_dtis = false;
let mut custom_fdiffs = false;
let mut custom_chains = false;
let mut active_decode_targets_present = false;
if data.len() > 3 {
let structure_present = r.flag()?;
active_decode_targets_present = r.flag()?;
custom_dtis = r.flag()?;
custom_fdiffs = r.flag()?;
custom_chains = r.flag()?;
if structure_present {
descriptor.attached_structure = Some(FrameDependencyStructure::read(&mut r)?);
}
}
let Some(structure) = descriptor.attached_structure.as_ref().or(structure) else {
return Ok(None);
};
if active_decode_targets_present {
descriptor.active_decode_targets_bitmask = Some(r.f(structure.num_decode_targets)?);
}
let Some(template_index) = structure.template_index(descriptor.template_id) else {
return Ok(None);
};
let template = &structure.templates[template_index];
descriptor.spatial_id = template.spatial_id;
descriptor.temporal_id = template.temporal_id;
if custom_dtis {
for _ in 0..structure.num_decode_targets {
descriptor
.dtis
.push(DecodeTargetIndication::from_bits(r.f(2)?));
}
} else {
descriptor.dtis = template.dtis.clone();
}
if custom_fdiffs {
loop {
let next_fdiff_size = r.f(2)? as usize;
if next_fdiff_size == 0 {
break;
}
descriptor.fdiffs.push(r.f(4 * next_fdiff_size)? as u16 + 1);
}
} else {
descriptor.fdiffs = template.fdiffs.clone();
}
if custom_chains {
for _ in 0..structure.num_chains {
descriptor.chain_fdiffs.push(r.f(8)? as u8);
}
} else {
descriptor.chain_fdiffs = template.chain_fdiffs.clone();
}
descriptor.resolution = structure
.resolutions
.get(descriptor.spatial_id as usize)
.copied();
Ok(Some(descriptor))
}
}
#[derive(Debug, Default, Clone)]
pub struct DependencyDescriptorReader {
structure: Option<FrameDependencyStructure>,
active_decode_targets: u32,
}
impl DependencyDescriptorReader {
pub fn new() -> Self {
Self::default()
}
pub fn read(&mut self, data: &[u8]) -> Result<Option<DependencyDescriptor>> {
let Some(descriptor) = DependencyDescriptor::unmarshal(data, self.structure.as_ref())?
else {
return Ok(None);
};
if let Some(structure) = &descriptor.attached_structure {
self.active_decode_targets = structure.all_decode_targets();
self.structure = Some(structure.clone());
}
if let Some(bitmask) = descriptor.active_decode_targets_bitmask {
self.active_decode_targets = bitmask;
}
Ok(Some(descriptor))
}
pub fn structure(&self) -> Option<&FrameDependencyStructure> {
self.structure.as_ref()
}
pub fn active_decode_targets(&self) -> u32 {
self.active_decode_targets
}
pub fn chain_has_active_decode_target(&self, chain: usize) -> bool {
chain_has_active_decode_target(self.structure.as_ref(), self.active_decode_targets, chain)
}
pub fn part_of_active_chain(&self, descriptor: &DependencyDescriptor, chain: usize) -> bool {
let Some(structure) = &self.structure else {
return false;
};
if !self.chain_has_active_decode_target(chain) {
return false;
}
structure
.decode_target_protected_by
.iter()
.enumerate()
.filter(|(_, protected_by)| **protected_by as usize == chain)
.all(|(dt, _)| {
!matches!(
descriptor.dtis.get(dt),
None | Some(
DecodeTargetIndication::NotPresent | DecodeTargetIndication::Discardable
)
)
})
}
}
fn chain_has_active_decode_target(
structure: Option<&FrameDependencyStructure>,
active_decode_targets: u32,
chain: usize,
) -> bool {
structure.is_some_and(|structure| {
structure
.decode_target_protected_by
.iter()
.enumerate()
.any(|(dt, protected_by)| {
*protected_by as usize == chain
&& active_decode_targets.checked_shr(dt as u32).unwrap_or(0) & 1 == 1
})
})
}