#[cfg(test)]
mod svc_mode_test;
#[cfg(test)]
mod svc_pattern_test;
use std::fmt;
use std::str::FromStr;
use shared::error::{Error, Result};
use crate::codec::dependency_descriptor::{
DecodeTargetIndication, FrameDependencyStructure, FrameDependencyTemplate, RenderResolution,
};
use crate::codec::vp8::{Vp8FrameInfo, Vp8TemporalLayer};
use crate::codec::vp9::{Vp9FrameInfo, Vp9PictureGroupEntry, Vp9ScalabilityStructure};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum InterLayerPrediction {
Full,
KeyPicture,
None,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ResolutionRatio {
TwoToOne,
OneAndAHalfToOne,
}
macro_rules! scalability_modes {
($(($variant:ident, $name:literal, $spatial:literal, $temporal:literal, $prediction:ident, $ratio:ident, $shift:literal)),* $(,)?) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(non_camel_case_types)]
#[non_exhaustive]
pub enum ScalabilityMode {
$(
#[doc = concat!("`\"", $name, "\"`.")]
$variant,
)*
}
impl ScalabilityMode {
pub const ALL: &'static [ScalabilityMode] = &[$(ScalabilityMode::$variant,)*];
pub fn as_str(&self) -> &'static str {
match self {
$(ScalabilityMode::$variant => $name,)*
}
}
fn properties(&self) -> (u8, u8, InterLayerPrediction, ResolutionRatio, bool) {
match self {
$(ScalabilityMode::$variant => (
$spatial,
$temporal,
InterLayerPrediction::$prediction,
ResolutionRatio::$ratio,
$shift,
),)*
}
}
}
};
}
scalability_modes![
(L1T1, "L1T1", 1, 1, Full, TwoToOne, false),
(L1T2, "L1T2", 1, 2, Full, TwoToOne, false),
(L1T3, "L1T3", 1, 3, Full, TwoToOne, false),
(L2T1, "L2T1", 2, 1, Full, TwoToOne, false),
(L2T2, "L2T2", 2, 2, Full, TwoToOne, false),
(L2T3, "L2T3", 2, 3, Full, TwoToOne, false),
(L3T1, "L3T1", 3, 1, Full, TwoToOne, false),
(L3T2, "L3T2", 3, 2, Full, TwoToOne, false),
(L3T3, "L3T3", 3, 3, Full, TwoToOne, false),
(L2T1h, "L2T1h", 2, 1, Full, OneAndAHalfToOne, false),
(L2T2h, "L2T2h", 2, 2, Full, OneAndAHalfToOne, false),
(L2T3h, "L2T3h", 2, 3, Full, OneAndAHalfToOne, false),
(L3T1h, "L3T1h", 3, 1, Full, OneAndAHalfToOne, false),
(L3T2h, "L3T2h", 3, 2, Full, OneAndAHalfToOne, false),
(L3T3h, "L3T3h", 3, 3, Full, OneAndAHalfToOne, false),
(S2T1, "S2T1", 2, 1, None, TwoToOne, false),
(S2T2, "S2T2", 2, 2, None, TwoToOne, false),
(S2T3, "S2T3", 2, 3, None, TwoToOne, false),
(S2T1h, "S2T1h", 2, 1, None, OneAndAHalfToOne, false),
(S2T2h, "S2T2h", 2, 2, None, OneAndAHalfToOne, false),
(S2T3h, "S2T3h", 2, 3, None, OneAndAHalfToOne, false),
(S3T1, "S3T1", 3, 1, None, TwoToOne, false),
(S3T2, "S3T2", 3, 2, None, TwoToOne, false),
(S3T3, "S3T3", 3, 3, None, TwoToOne, false),
(S3T1h, "S3T1h", 3, 1, None, OneAndAHalfToOne, false),
(S3T2h, "S3T2h", 3, 2, None, OneAndAHalfToOne, false),
(S3T3h, "S3T3h", 3, 3, None, OneAndAHalfToOne, false),
(L2T2_KEY, "L2T2_KEY", 2, 2, KeyPicture, TwoToOne, false),
(
L2T2_KEY_SHIFT,
"L2T2_KEY_SHIFT",
2,
2,
KeyPicture,
TwoToOne,
true
),
(L2T3_KEY, "L2T3_KEY", 2, 3, KeyPicture, TwoToOne, false),
(
L2T3_KEY_SHIFT,
"L2T3_KEY_SHIFT",
2,
3,
KeyPicture,
TwoToOne,
true
),
(L3T1_KEY, "L3T1_KEY", 3, 1, KeyPicture, TwoToOne, false),
(L3T2_KEY, "L3T2_KEY", 3, 2, KeyPicture, TwoToOne, false),
(
L3T2_KEY_SHIFT,
"L3T2_KEY_SHIFT",
3,
2,
KeyPicture,
TwoToOne,
true
),
(L3T3_KEY, "L3T3_KEY", 3, 3, KeyPicture, TwoToOne, false),
(
L3T3_KEY_SHIFT,
"L3T3_KEY_SHIFT",
3,
3,
KeyPicture,
TwoToOne,
true
),
];
impl ScalabilityMode {
pub fn spatial_layers(&self) -> u8 {
self.properties().0
}
pub fn temporal_layers(&self) -> u8 {
self.properties().1
}
pub fn inter_layer_prediction(&self) -> InterLayerPrediction {
self.properties().2
}
pub fn resolution_ratio(&self) -> Option<ResolutionRatio> {
(self.spatial_layers() > 1).then_some(self.properties().3)
}
pub fn has_temporal_shift(&self) -> bool {
self.properties().4
}
pub fn is_simulcast(&self) -> bool {
self.inter_layer_prediction() == InterLayerPrediction::None
}
pub fn is_single_layer(&self) -> bool {
self.spatial_layers() == 1 && self.temporal_layers() == 1
}
pub fn supported_by(&self, mime_type: &str) -> bool {
let codec = mime_type.to_ascii_lowercase();
match codec.as_str() {
"video/av1" | "video/vp9" => true,
"video/vp8" | "video/h264" | "video/h265" => self.spatial_layers() == 1,
other => other.starts_with("video/") && self.is_single_layer(),
}
}
pub fn supported_modes(mime_type: &str) -> Vec<ScalabilityMode> {
Self::ALL
.iter()
.copied()
.filter(|mode| mode.supported_by(mime_type))
.collect()
}
pub fn layer_resolution(&self, spatial_id: u8, width: u32, height: u32) -> (u32, u32) {
let steps = (self.spatial_layers() - 1).saturating_sub(spatial_id) as u32;
let (numerator, denominator) = match self.properties().3 {
ResolutionRatio::TwoToOne => (1u64, 2u64.pow(steps)),
ResolutionRatio::OneAndAHalfToOne => (2u64.pow(steps), 3u64.pow(steps)),
};
let scale = |v: u32| ((v as u64 * numerator / denominator).max(1)) as u32;
(scale(width), scale(height))
}
}
impl fmt::Display for ScalabilityMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for ScalabilityMode {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
Self::ALL
.iter()
.copied()
.find(|mode| mode.as_str() == s)
.ok_or_else(|| Error::Other(format!("\"{s}\" is not a scalability mode")))
}
}
const MAX_SPATIAL: usize = 3;
const MAX_TEMPORAL: usize = 3;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LayerFrame {
pub spatial_id: u8,
pub temporal_id: u8,
pub key_picture: bool,
pub key_frame: bool,
pub temporal_reference: Option<u8>,
pub inter_layer_dependency: bool,
pub referenced_by_upper_layers: bool,
pub discardable: bool,
pub layer_sync: bool,
pub fdiffs: Vec<u16>,
pub dtis: Vec<DecodeTargetIndication>,
pub chain_fdiffs: Vec<u8>,
pub end_of_picture: bool,
}
impl LayerFrame {
pub fn starts_coded_video_sequence(&self) -> bool {
self.key_picture && self.spatial_id == 0
}
pub fn dependencies(&self) -> FrameDependencyTemplate {
FrameDependencyTemplate {
spatial_id: self.spatial_id,
temporal_id: self.temporal_id,
dtis: self.dtis.clone(),
fdiffs: self.fdiffs.clone(),
chain_fdiffs: self.chain_fdiffs.clone(),
}
}
pub fn vp8_info(&self, mode: ScalabilityMode) -> Vp8FrameInfo {
Vp8FrameInfo {
non_reference: self.discardable,
temporal: (mode.temporal_layers() > 1).then_some(Vp8TemporalLayer {
tid: self.temporal_id,
layer_sync: self.layer_sync,
}),
key_idx: None,
}
}
pub fn vp9_info(&self) -> Vp9FrameInfo {
Vp9FrameInfo {
temporal_id: self.temporal_id,
spatial_id: self.spatial_id,
switching_up_point: true,
inter_layer_dependency: self.inter_layer_dependency,
not_reference_for_upper_layers: !self.referenced_by_upper_layers,
end_of_picture: self.end_of_picture,
key_frame: Some(self.key_frame),
inter_picture_predicted: Some(self.temporal_reference.is_some()),
reference_diffs: self.temporal_reference.into_iter().collect(),
}
}
}
#[derive(Debug, Clone)]
pub struct ScalabilityPattern {
mode: ScalabilityMode,
picture: Option<u64>,
frames: u64,
latest: [[Option<(u64, u64)>; MAX_TEMPORAL]; MAX_SPATIAL],
chain_latest: [Option<u64>; MAX_SPATIAL],
}
impl ScalabilityPattern {
pub fn new(mode: ScalabilityMode) -> Self {
Self {
mode,
picture: None,
frames: 0,
latest: [[None; MAX_TEMPORAL]; MAX_SPATIAL],
chain_latest: [None; MAX_SPATIAL],
}
}
pub fn mode(&self) -> ScalabilityMode {
self.mode
}
pub fn decode_target_layers(&self) -> Vec<(u8, u8)> {
let (spatial, temporal) = (self.mode.spatial_layers(), self.mode.temporal_layers());
(0..spatial)
.rev()
.flat_map(|s| (0..temporal).rev().map(move |t| (s, t)))
.collect()
}
fn temporal_id(&self, s: u8, picture: u64) -> u8 {
if picture == 0 {
return 0;
}
let sequence: &[u8] = match self.mode.temporal_layers() {
1 => &[0],
2 => &[0, 1],
_ => &[0, 2, 1, 2],
};
let shift = if self.mode.has_temporal_shift() {
((s + 1) % self.mode.spatial_layers()) as i64
} else {
0
};
sequence[(picture as i64 - shift).rem_euclid(sequence.len() as i64) as usize]
}
pub fn next_picture(&mut self, key_picture: bool) -> Vec<LayerFrame> {
let picture = match self.picture {
Some(picture) if !key_picture => picture + 1,
_ => {
self.latest = [[None; MAX_TEMPORAL]; MAX_SPATIAL];
self.chain_latest = [None; MAX_SPATIAL];
0
}
};
self.picture = Some(picture);
let key_picture = picture == 0;
let mode = self.mode;
let prediction = mode.inter_layer_prediction();
let (spatial, temporal) = (mode.spatial_layers(), mode.temporal_layers());
let mut frames = Vec::with_capacity(spatial as usize);
for s in 0..spatial {
let t = self.temporal_id(s, picture);
let number = self.frames;
let candidates = if t == 0 { 0..1 } else { 0..t as usize };
let temporal_reference = self.latest[s as usize][candidates]
.iter()
.flatten()
.max_by_key(|(_, picture)| *picture)
.copied();
let inter_layer_dependency = s > 0
&& match prediction {
InterLayerPrediction::Full => true,
InterLayerPrediction::KeyPicture => key_picture,
InterLayerPrediction::None => false,
};
let mut fdiffs = vec![];
if let Some((reference, _)) = temporal_reference {
fdiffs.push((number - reference) as u16);
}
if inter_layer_dependency {
fdiffs.push(1);
}
let referenced_by_upper_layers = s + 1 < spatial
&& match prediction {
InterLayerPrediction::Full => true,
InterLayerPrediction::KeyPicture => key_picture,
InterLayerPrediction::None => false,
};
let discardable = temporal > 1 && t == temporal - 1 && !referenced_by_upper_layers;
let layer_sync = t > 0
&& temporal_reference.is_some_and(|(reference, _)| {
self.latest[s as usize][0].is_some_and(|(base, _)| base == reference)
});
let dtis = self
.decode_target_layers()
.into_iter()
.map(|(ds, dt)| {
let own_layer = if t > dt {
DecodeTargetIndication::NotPresent
} else if t == dt && t > 0 {
DecodeTargetIndication::Discardable
} else {
DecodeTargetIndication::Switch
};
match prediction {
InterLayerPrediction::Full if s > ds || t > dt => {
DecodeTargetIndication::NotPresent
}
InterLayerPrediction::Full if s == ds => own_layer,
InterLayerPrediction::Full if key_picture => DecodeTargetIndication::Switch,
InterLayerPrediction::Full => DecodeTargetIndication::Required,
InterLayerPrediction::KeyPicture if key_picture => {
if s <= ds {
DecodeTargetIndication::Switch
} else {
DecodeTargetIndication::NotPresent
}
}
InterLayerPrediction::KeyPicture | InterLayerPrediction::None => {
if s == ds {
own_layer
} else {
DecodeTargetIndication::NotPresent
}
}
}
})
.collect();
let mut chain_fdiffs = Vec::with_capacity(spatial as usize);
for chain in 0..spatial {
chain_fdiffs.push(
self.chain_latest[chain as usize]
.map_or(0, |latest| (number - latest).min(u8::MAX as u64) as u8),
);
let in_chain = match prediction {
InterLayerPrediction::Full => t == 0 && s <= chain,
InterLayerPrediction::KeyPicture if key_picture => s <= chain,
InterLayerPrediction::KeyPicture | InterLayerPrediction::None => {
t == 0 && s == chain
}
};
if in_chain {
self.chain_latest[chain as usize] = Some(number);
}
}
frames.push(LayerFrame {
spatial_id: s,
temporal_id: t,
key_picture,
key_frame: fdiffs.is_empty(),
temporal_reference: temporal_reference
.map(|(_, reference_picture)| (picture - reference_picture) as u8),
inter_layer_dependency,
referenced_by_upper_layers,
discardable,
layer_sync,
fdiffs,
dtis,
chain_fdiffs,
end_of_picture: s + 1 == spatial,
});
self.latest[s as usize][t as usize] = Some((number, picture));
self.frames += 1;
}
frames
}
pub fn dependency_structure(
mode: ScalabilityMode,
resolution: Option<(u32, u32)>,
) -> FrameDependencyStructure {
let mut pattern = Self::new(mode);
let mut templates: Vec<FrameDependencyTemplate> = vec![];
for _ in 0..=4 * 4 {
for frame in pattern.next_picture(false) {
let template = frame.dependencies();
if !templates.contains(&template) {
templates.push(template);
}
}
}
templates.sort_by_key(|t| (t.spatial_id, t.temporal_id));
let spatial = mode.spatial_layers();
FrameDependencyStructure {
template_id_offset: 0,
num_decode_targets: spatial as usize * mode.temporal_layers() as usize,
num_chains: spatial as usize,
decode_target_protected_by: pattern
.decode_target_layers()
.into_iter()
.map(|(s, _)| s)
.collect(),
resolutions: resolution
.map(|(width, height)| {
(0..spatial)
.map(|s| {
let (width, height) = mode.layer_resolution(s, width, height);
RenderResolution { width, height }
})
.collect()
})
.unwrap_or_default(),
templates,
}
}
pub fn vp9_scalability_structure(
mode: ScalabilityMode,
resolution: Option<(u32, u32)>,
flexible_mode: bool,
) -> Result<Vp9ScalabilityStructure> {
let mut resolutions = vec![];
if let Some((width, height)) = resolution {
for s in 0..mode.spatial_layers() {
let (width, height) = mode.layer_resolution(s, width, height);
match (u16::try_from(width), u16::try_from(height)) {
(Ok(width), Ok(height)) => resolutions.push((width, height)),
_ => {
return Err(Error::Other(format!(
"VP9 scalability structure: {width}x{height} does not fit 16 bits"
)));
}
}
}
}
let mut picture_group = vec![];
if !flexible_mode {
if mode.has_temporal_shift() {
return Err(Error::Other(format!(
"VP9 non-flexible mode cannot carry {mode}: its spatial layers have different temporal structures"
)));
}
let group: &[(u8, u8)] = match mode.temporal_layers() {
1 => &[(0, 1)],
2 => &[(0, 2), (1, 1)],
_ => &[(0, 4), (2, 1), (1, 2), (2, 1)],
};
picture_group = group
.iter()
.map(|(temporal_id, reference_diff)| Vp9PictureGroupEntry {
temporal_id: *temporal_id,
switching_up_point: true,
reference_diffs: vec![*reference_diff],
})
.collect();
}
Ok(Vp9ScalabilityStructure {
spatial_layers: mode.spatial_layers(),
resolutions,
picture_group,
})
}
}