use std::collections::{BTreeSet, VecDeque};
use alpha2_ffmpeg_bridge::DecodedFrame;
use alpha2_media::DecodeError;
use rsmpeg::avcodec::{AVCodec, AVCodecContext, AVPacket};
use rsmpeg::avutil::{AVFrame, AVRational};
use rsmpeg::error::RsmpegError;
use rsmpeg::ffi;
use crate::convert::{adapter_error, reject_unused_decode_options, video_decoder_options};
use crate::recovery::{FfmpegRecovery, Recovery};
const ALPHA_BLOCK_ADDITION: u64 = 1;
#[derive(Debug)]
pub(crate) struct RawFrame {
picture: DecodedFrame,
alpha: Option<DecodedFrame>,
}
impl RawFrame {
pub(crate) const fn opaque(picture: DecodedFrame) -> Self {
Self {
picture,
alpha: None,
}
}
pub(crate) const fn alpha(&self) -> Option<&DecodedFrame> {
self.alpha.as_ref()
}
#[cfg(all(
any(target_os = "linux", target_os = "macos", target_os = "windows"),
feature = "hwdecode"
))]
pub(crate) fn into_parts(self) -> (DecodedFrame, Option<DecodedFrame>) {
(self.picture, self.alpha)
}
}
impl std::ops::Deref for RawFrame {
type Target = DecodedFrame;
fn deref(&self) -> &DecodedFrame {
&self.picture
}
}
#[derive(Clone, Copy)]
pub(crate) enum FrameAlpha<'a> {
Decoded(&'a DecodedFrame),
AtLumaLayout(&'a alpha2_media::Plane),
}
impl FrameAlpha<'_> {
pub(crate) fn plane(
self,
(width, height): (u32, u32),
depth: u8,
msb_aligned: bool,
) -> Result<alpha2_media::Plane, DecodeError> {
let plane = match self {
Self::Decoded(frame) => alpha_plane(frame, depth, msb_aligned)?,
Self::AtLumaLayout(plane) => plane.clone(),
};
if (plane.width, plane.height) == (width, height) {
Ok(plane)
} else {
Err(DecodeError::Adapter(format!(
"a {}x{} alpha plane does not fit a {width}x{height} picture",
plane.width, plane.height
)))
}
}
}
pub(crate) fn carries_alpha_stream(packet: &AVPacket) -> bool {
alpha2_ffmpeg_bridge::packet_block_addition(packet, ALPHA_BLOCK_ADDITION).is_some()
}
fn pairing_pts(frame: &AVFrame) -> i64 {
if frame.pts == ffi::AV_NOPTS_VALUE {
frame.best_effort_timestamp
} else {
frame.pts
}
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum StreamEnd {
Open,
Signalled,
Drained,
}
pub(crate) struct AlphaCompanion {
decoder: AVCodecContext,
pictures: VecDeque<DecodedFrame>,
alphas: VecDeque<DecodedFrame>,
pictures_dropped_unreported: BTreeSet<i64>,
awaiting_keyframe: bool,
from_stream_start: bool,
end: StreamEnd,
pictures_taken: u64,
alphas_received: u64,
}
impl AlphaCompanion {
pub(crate) fn open(threads: i64, time_base: AVRational) -> Result<Self, DecodeError> {
let codec = AVCodec::find_decoder_by_name(c"vp9").ok_or_else(|| {
DecodeError::Unsupported("this FFmpeg runtime has no vp9 decoder".into())
})?;
crate::decode::allowed_decoder(&codec)?;
let mut decoder = AVCodecContext::new(&codec);
decoder.set_pkt_timebase(time_base);
let unused =
alpha2_ffmpeg_bridge::open_codec_context(&mut decoder, video_decoder_options(threads))
.map_err(adapter_error)?;
reject_unused_decode_options(unused)?;
Ok(Self {
decoder,
pictures: VecDeque::new(),
alphas: VecDeque::new(),
pictures_dropped_unreported: BTreeSet::new(),
awaiting_keyframe: true,
from_stream_start: true,
end: StreamEnd::Open,
pictures_taken: 0,
alphas_received: 0,
})
}
pub(crate) fn flush(&mut self) {
self.decoder.flush_buffers();
self.pictures.clear();
self.alphas.clear();
self.pictures_dropped_unreported.clear();
self.awaiting_keyframe = true;
self.from_stream_start = false;
self.end = StreamEnd::Open;
}
pub(crate) const fn restarted_from_stream_start(&mut self, from_start: bool) {
self.from_stream_start = from_start;
}
pub(crate) const fn pictures_taken(&self) -> u64 {
self.pictures_taken
}
pub(crate) fn hold_picture(&mut self, picture: DecodedFrame) {
self.pictures_taken = self.pictures_taken.wrapping_add(1);
self.pictures.push_back(picture);
}
pub(crate) fn send(
&mut self,
packet: &AVPacket,
recovery: &mut Recovery,
) -> Result<(), DecodeError> {
let pts = packet.pts;
let Some(payload) =
alpha2_ffmpeg_bridge::packet_block_addition(packet, ALPHA_BLOCK_ADDITION)
else {
return self.damaged(pts, "the block carries no alpha data", recovery);
};
if self.awaiting_keyframe {
if !alpha2_ffmpeg_bridge::vp9_frame_is_keyframe(payload) {
if self.from_stream_start {
return self.damaged(
pts,
"the alpha stream starts without a key frame",
recovery,
);
}
self.pictures_dropped_unreported.insert(pts);
return Ok(());
}
self.awaiting_keyframe = false;
}
let mut alpha = alpha2_ffmpeg_bridge::packet_from_bytes(payload).map_err(adapter_error)?;
alpha.set_pts(packet.pts);
alpha.set_dts(packet.dts);
alpha.set_duration(packet.duration);
for _ in 0..64 {
match self.decoder.send_packet(Some(&alpha)) {
Ok(()) => return Ok(()),
Err(RsmpegError::DecoderFullError) => {
let received = self.alphas_received;
self.receive_ready_alphas(recovery)?;
if self.alphas_received == received {
return Err(DecodeError::Adapter(
"the alpha decoder takes no packet and returns no frame".into(),
));
}
}
Err(error) => {
recovery.unless_damage(error)?;
return Ok(());
}
}
}
Err(DecodeError::Adapter(
"alpha packet retry budget exceeded".into(),
))
}
pub(crate) fn send_end(&mut self, recovery: &mut Recovery) -> Result<(), DecodeError> {
if self.end != StreamEnd::Open {
return Ok(());
}
loop {
match self.decoder.send_packet(None) {
Ok(()) | Err(RsmpegError::DecoderFlushedError) => break,
Err(RsmpegError::DecoderFullError) => {
let received = self.alphas_received;
self.receive_ready_alphas(recovery)?;
if self.alphas_received == received {
break;
}
}
Err(error) => {
recovery.error(error, "video alpha flush", None)?;
break;
}
}
}
self.end = StreamEnd::Signalled;
Ok(())
}
fn damaged(
&mut self,
pts: i64,
detail: &str,
recovery: &mut Recovery,
) -> Result<(), DecodeError> {
self.pictures_dropped_unreported.insert(pts);
report_damage(pts, detail, recovery)
}
fn receive_ready_alphas(&mut self, recovery: &mut Recovery) -> Result<(), DecodeError> {
loop {
match DecodedFrame::receive(&mut self.decoder) {
Ok(frame) => {
self.alphas_received = self.alphas_received.wrapping_add(1);
if frame.flags
& i32::try_from(ffi::AV_FRAME_FLAG_CORRUPT).expect("flag fits i32")
!= 0
|| frame.decode_error_flags != 0
{
let pts = pairing_pts(&frame);
self.damaged(pts, "the alpha frame is corrupt", recovery)?;
continue;
}
self.alphas.push_back(frame);
}
Err(RsmpegError::DecoderDrainError) => return Ok(()),
Err(RsmpegError::DecoderFlushedError) => {
self.end = StreamEnd::Drained;
return Ok(());
}
Err(error) => recovery.unless_damage(error)?,
}
}
}
pub(crate) fn next_pair(
&mut self,
recovery: &mut Recovery,
) -> Result<Option<RawFrame>, DecodeError> {
self.receive_ready_alphas(recovery)?;
while let Some(picture) = self.pictures.front() {
let pts = pairing_pts(picture);
self.pictures_dropped_unreported = self.pictures_dropped_unreported.split_off(&pts);
while self
.alphas
.front()
.is_some_and(|alpha| pairing_pts(alpha) < pts)
{
self.alphas.pop_front();
}
let dropped = self.pictures_dropped_unreported.remove(&pts);
let matched = self
.alphas
.front()
.is_some_and(|alpha| pairing_pts(alpha) == pts);
if !matched && !dropped && self.alphas.is_empty() && self.end != StreamEnd::Drained {
return Ok(None);
}
let picture = self.pictures.pop_front().expect("a picture waits");
let alpha = matched.then(|| self.alphas.pop_front().expect("a matched alpha frame"));
if dropped {
continue;
}
let Some(alpha) = alpha else {
report_damage(pts, "the alpha frame is missing", recovery)?;
continue;
};
if let Err(detail) = alpha_fits(&picture, &alpha) {
report_damage(pts, &detail, recovery)?;
continue;
}
return Ok(Some(RawFrame {
picture,
alpha: Some(alpha),
}));
}
Ok(None)
}
}
fn report_damage(pts: i64, detail: &str, recovery: &mut Recovery) -> Result<(), DecodeError> {
recovery.corrupt_with_detail(
"video alpha",
crate::recovery::pts(pts),
Some(detail.to_owned()),
)
}
fn alpha_fits(picture: &AVFrame, alpha: &AVFrame) -> Result<(), String> {
if (alpha.width, alpha.height) != (picture.width, picture.height) {
return Err(format!(
"the alpha frame is {}x{}, the picture {}x{}",
alpha.width, alpha.height, picture.width, picture.height
));
}
let depth = |format| alpha2_ffmpeg_bridge::yuv_layout(format).map(|layout| layout.bit_depth);
let picture_depth =
alpha2_ffmpeg_bridge::sample_profile(picture.format).map(|profile| profile.bit_depth);
match (depth(alpha.format), picture_depth) {
(Some(8), _) => Ok(()),
(Some(alpha), Some(picture)) if u32::from(alpha) == u32::from(picture) => Ok(()),
(alpha, picture) => Err(format!(
"the alpha frame's depth {alpha:?} does not fit the picture's {picture:?}"
)),
}
}
fn alpha_plane(
alpha: &DecodedFrame,
depth: u8,
msb_aligned: bool,
) -> Result<alpha2_media::Plane, DecodeError> {
let planes = alpha
.yuv_planes()
.map_err(adapter_error)?
.ok_or_else(|| DecodeError::Unsupported("the alpha frame has no luma plane".into()))?;
let source_depth = planes.layout.bit_depth;
let luma = planes.planes.into_iter().next().expect("a luma plane");
if source_depth == depth && planes.layout.msb_aligned == msb_aligned {
return Ok(alpha2_media::Plane {
bytes: luma.bytes,
stride: luma.stride,
width: luma.width,
height: luma.height,
});
}
let rescale = match source_depth {
8 => Rescale::Widen(Box::new(widened_alpha(depth, msb_aligned))),
_ if source_depth == depth && msb_aligned && !planes.layout.msb_aligned => {
Rescale::ToHighBits(16 - u32::from(depth))
}
_ => {
return Err(DecodeError::Unsupported(format!(
"a {source_depth}-bit alpha plane cannot go with {depth}-bit colour"
)));
}
};
let sample_bytes = usize::from(source_depth.div_ceil(8));
let width = usize::try_from(luma.width).map_err(|_| DecodeError::OutOfRange)?;
let stride = usize::try_from(luma.stride).map_err(|_| DecodeError::OutOfRange)?;
let rows = usize::try_from(luma.height).map_err(|_| DecodeError::OutOfRange)?;
let mut bytes = Vec::with_capacity(width * 2 * rows);
for row in luma.bytes.chunks(stride).take(rows) {
for sample in row[..width * sample_bytes].chunks(sample_bytes) {
bytes.extend_from_slice(&rescale.sample(sample).to_le_bytes());
}
}
Ok(alpha2_media::Plane {
bytes: bytes.into(),
stride: luma.width * 2,
width: luma.width,
height: luma.height,
})
}
enum Rescale {
Widen(Box<[u16; 256]>),
ToHighBits(u32),
}
impl Rescale {
fn sample(&self, bytes: &[u8]) -> u16 {
match self {
Self::Widen(table) => table[usize::from(bytes[0])],
Self::ToHighBits(shift) => u16::from_le_bytes([bytes[0], bytes[1]]) << shift,
}
}
}
fn widened_alpha(depth: u8, msb_aligned: bool) -> [u16; 256] {
let maximum = (1_u32 << depth) - 1;
let shift = if msb_aligned {
16 - u32::from(depth)
} else {
0
};
std::array::from_fn(|value| {
let value = u32::try_from(value).expect("an index below 256");
let widened = (value * maximum + 127) / 255;
u16::try_from(widened << shift).expect("a sample fits 16 bits")
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn alpha_widens_from_eight_bits_keeping_its_ends() {
let ten = widened_alpha(10, false);
assert_eq!((ten[0], ten[128], ten[255]), (0, 514, 1023));
let p010 = widened_alpha(10, true);
assert_eq!((p010[0], p010[255]), (0, 1023 << 6));
let sixteen = widened_alpha(16, false);
assert_eq!((sixteen[1], sixteen[255]), (257, 65535));
assert_eq!(widened_alpha(8, false)[200], 200);
}
}