#[cfg(test)]
mod vp8_descriptor_test;
#[cfg(test)]
mod vp8_layers_test;
#[cfg(test)]
mod vp8_partitions_test;
#[cfg(test)]
mod vp8_test;
mod partitions;
use crate::packetizer::{Depacketizer, Payloader};
use shared::error::{Error, Result};
use bytes::{BufMut, Bytes, BytesMut};
pub const VP8_HEADER_SIZE: usize = 1;
pub const VP8_MAX_TEMPORAL_ID: u8 = 3;
pub const VP8_MAX_KEY_IDX: u8 = 31;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Vp8TemporalLayer {
pub tid: u8,
pub layer_sync: bool,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Vp8FrameInfo {
pub non_reference: bool,
pub temporal: Option<Vp8TemporalLayer>,
pub key_idx: Option<u8>,
}
#[derive(Default, Debug, Copy, Clone)]
pub struct Vp8Payloader {
pub enable_picture_id: bool,
pub ignore_partitions: bool,
picture_id: u16,
tl0_pic_idx: u8,
}
impl Vp8Payloader {
pub fn set_initial_picture_id(&mut self, picture_id: u16) {
self.picture_id = picture_id & 0x7FFF;
}
pub fn set_initial_tl0_pic_idx(&mut self, tl0_pic_idx: u8) {
self.tl0_pic_idx = tl0_pic_idx.wrapping_sub(1);
}
pub fn picture_id(&self) -> u16 {
self.picture_id
}
pub fn payload_frame(
&mut self,
mtu: usize,
payload: &Bytes,
info: &Vp8FrameInfo,
) -> Result<Vec<Bytes>> {
if let Some(temporal) = &info.temporal
&& temporal.tid > VP8_MAX_TEMPORAL_ID
{
return Err(Error::Other(format!(
"VP8 TID {} does not fit two bits",
temporal.tid
)));
}
if let Some(key_idx) = info.key_idx
&& key_idx > VP8_MAX_KEY_IDX
{
return Err(Error::Other(format!(
"VP8 KEYIDX {key_idx} does not fit five bits"
)));
}
if payload.is_empty() || mtu == 0 {
return Ok(vec![]);
}
let mut extension = [0u8; 5];
let mut extension_len = 0;
let has_extension =
self.enable_picture_id || info.temporal.is_some() || info.key_idx.is_some();
let tl0_pic_idx = match &info.temporal {
Some(temporal) if temporal.tid == 0 => self.tl0_pic_idx.wrapping_add(1),
_ => self.tl0_pic_idx,
};
if has_extension {
let mut flags = 0u8;
extension_len = 1;
if self.enable_picture_id {
flags |= 0x80; if self.picture_id < 128 {
extension[extension_len] = self.picture_id as u8;
extension_len += 1;
} else {
extension[extension_len] = 0x80 | (self.picture_id >> 8) as u8; extension[extension_len + 1] = (self.picture_id & 0xFF) as u8;
extension_len += 2;
}
}
if info.temporal.is_some() {
flags |= 0x40 | 0x20;
extension[extension_len] = tl0_pic_idx;
extension_len += 1;
}
if info.temporal.is_some() || info.key_idx.is_some() {
let mut b = 0u8;
if let Some(temporal) = &info.temporal {
b |= temporal.tid << 6;
if temporal.layer_sync {
b |= 0x20;
}
}
if let Some(key_idx) = info.key_idx {
flags |= 0x10; b |= key_idx;
}
extension[extension_len] = b;
extension_len += 1;
}
extension[0] = flags;
}
let using_header_size = VP8_HEADER_SIZE + extension_len;
if mtu <= using_header_size {
return Ok(vec![]);
}
let max_fragment_size = mtu - using_header_size;
let mut regions: Vec<(std::ops::Range<usize>, u8)> = Vec::new();
match (!self.ignore_partitions)
.then(|| partitions::vp8_partitions(payload))
.flatten()
{
Some(parts) => {
for (index, part) in parts.into_iter().enumerate() {
let pid = index.min(7) as u8;
match regions.last_mut() {
Some((last, last_pid)) if *last_pid == pid => last.end = part.end,
_ if part.is_empty() => {}
_ => regions.push((part, pid)),
}
}
}
None => regions.push((0..payload.len(), 0)),
}
let mut payloads = Vec::with_capacity(
regions
.iter()
.map(|(r, _)| r.len().div_ceil(max_fragment_size))
.sum(),
);
for (region, pid) in regions {
let mut payload_data_index = region.start;
while payload_data_index < region.end {
let current_fragment_size =
std::cmp::min(max_fragment_size, region.end - payload_data_index);
let mut out = BytesMut::with_capacity(using_header_size + current_fragment_size);
let mut first = pid;
if has_extension {
first |= 0x80; }
if info.non_reference {
first |= 0x20; }
if payload_data_index == region.start {
first |= 0x10; }
out.put_u8(first);
out.put(&extension[..extension_len]);
out.put(
&*payload.slice(payload_data_index..payload_data_index + current_fragment_size),
);
payloads.push(out.freeze());
payload_data_index += current_fragment_size;
}
}
self.picture_id += 1;
self.picture_id &= 0x7FFF;
self.tl0_pic_idx = tl0_pic_idx;
Ok(payloads)
}
}
impl Payloader for Vp8Payloader {
fn payload(&mut self, mtu: usize, payload: &Bytes) -> Result<Vec<Bytes>> {
self.payload_frame(mtu, payload, &Vp8FrameInfo::default())
}
fn clone_to(&self) -> Box<dyn Payloader> {
Box::new(*self)
}
}
#[derive(PartialEq, Eq, Debug, Default, Clone)]
pub struct Vp8Packet {
pub x: u8,
pub n: u8,
pub s: u8,
pub pid: u8,
pub i: u8,
pub l: u8,
pub t: u8,
pub k: u8,
pub picture_id: u16,
pub picture_id_15_bits: bool,
pub tl0_pic_idx: u8,
pub tid: u8,
pub y: u8,
pub key_idx: u8,
}
impl Vp8Packet {
fn parse_descriptor(&mut self, packet: &[u8]) -> Result<usize> {
*self = Self::default();
let mut index = 0;
let mut next = || -> Result<u8> {
let b = *packet.get(index).ok_or(Error::ErrShortPacket)?;
index += 1;
Ok(b)
};
let b = next()?;
self.x = (b & 0x80) >> 7;
self.n = (b & 0x20) >> 5;
self.s = (b & 0x10) >> 4;
self.pid = b & 0x07;
if self.x == 1 {
let b = next()?;
self.i = (b & 0x80) >> 7;
self.l = (b & 0x40) >> 6;
self.t = (b & 0x20) >> 5;
self.k = (b & 0x10) >> 4;
}
if self.i == 1 {
let b = next()?;
if b & 0x80 > 0 {
self.picture_id = (((b & 0x7f) as u16) << 8) | (next()? as u16);
self.picture_id_15_bits = true;
} else {
self.picture_id = b as u16;
}
}
if self.l == 1 {
self.tl0_pic_idx = next()?;
}
if self.t == 1 || self.k == 1 {
let b = next()?;
if self.t == 1 {
self.tid = b >> 6;
self.y = (b >> 5) & 0x1;
}
if self.k == 1 {
self.key_idx = b & 0x1F;
}
}
Ok(index)
}
pub fn is_frame_start(&self) -> bool {
self.s == 1 && self.pid == 0
}
}
impl Depacketizer for Vp8Packet {
fn depacketize(&mut self, packet: &Bytes) -> Result<Bytes> {
let descriptor_len = self.parse_descriptor(packet)?;
if descriptor_len >= packet.len() {
return Err(Error::ErrShortPacket);
}
Ok(packet.slice(descriptor_len..))
}
fn is_partition_head(&self, payload: &Bytes) -> bool {
if payload.is_empty() {
false
} else {
(payload[0] & 0x10) != 0 && (payload[0] & 0x07) == 0
}
}
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 {
if !self.is_partition_head(payload) {
return false;
}
let mut index = 1;
if payload[0] & 0x80 != 0 {
let Some(&extension) = payload.get(1) else {
return false;
};
index += 1;
if extension & 0x80 != 0 {
index += match payload.get(index) {
Some(m) if m & 0x80 != 0 => 2,
Some(_) => 1,
None => return false,
};
}
if extension & 0x40 != 0 {
index += 1;
}
if extension & 0x30 != 0 {
index += 1;
}
}
payload.get(index).is_some_and(|header| header & 0x01 == 0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Vp8TemporalLayerFilter {
target_tid: u8,
current_tid: u8,
withheld_tid: Option<u8>,
}
impl Default for Vp8TemporalLayerFilter {
fn default() -> Self {
Self::new(VP8_MAX_TEMPORAL_ID)
}
}
impl Vp8TemporalLayerFilter {
pub fn new(target_tid: u8) -> Self {
Self {
target_tid: target_tid.min(VP8_MAX_TEMPORAL_ID),
current_tid: 0,
withheld_tid: None,
}
}
pub fn set_target(&mut self, target_tid: u8) {
self.target_tid = target_tid.min(VP8_MAX_TEMPORAL_ID);
self.current_tid = self.current_tid.min(self.target_tid);
}
pub fn target(&self) -> u8 {
self.target_tid
}
pub fn current(&self) -> u8 {
self.current_tid
}
pub fn forward(&mut self, descriptor: &Vp8Packet, vp8_data: &[u8]) -> bool {
if descriptor.t == 0 {
return true;
}
let tid = descriptor.tid;
if descriptor.is_frame_start() {
if vp8_data.first().is_some_and(|b| b & 0x01 == 0) {
self.current_tid = self.target_tid;
self.withheld_tid = None;
} else if tid == 0 {
self.withheld_tid = None;
}
}
if tid > self.target_tid {
return false;
}
if tid <= self.current_tid {
return true;
}
if descriptor.y == 1 && descriptor.is_frame_start() {
let open = match self.withheld_tid {
Some(withheld) => withheld.saturating_sub(1).min(self.target_tid),
None => self.target_tid,
};
if tid <= open {
self.current_tid = open;
return true;
}
}
self.withheld_tid = Some(self.withheld_tid.map_or(tid, |w| w.min(tid)));
false
}
}