use std::sync::Arc;
use alpha2_container::{ContainerReader, Packet, TrackInfo, TrackKind, VideoCodec};
use alpha2_media::{
CancelToken, ChromaLocation, ColorMetadata, DecodeError, DecodeEvent, DecodeRequest,
DecodeResult, DecodedVideoFrame, Decoder, Orientation, PixelFormat, Plane, Rect,
SampleAspectRatio, SourceAlpha, StreamInfo, StreamKind, YuvFormat,
};
use alpha2_time::{MediaTime, TICKS_PER_SECOND};
use crate::parameter_sets::{CropWindow, ParameterSetCodec, Vui, sequence_facts};
use crate::recovery::{DecodeFailure, DecodePolicy, Recovery, WorkBudget};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BackendKind {
Hardware,
Software,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BackendError {
SessionLost(String),
Unsupported(String),
Corrupt(String),
HardwarePicture(String),
Failed(String),
}
impl std::fmt::Display for BackendError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SessionLost(reason) => write!(formatter, "decoder session lost: {reason}"),
Self::Unsupported(reason)
| Self::Corrupt(reason)
| Self::HardwarePicture(reason)
| Self::Failed(reason) => write!(formatter, "{reason}"),
}
}
}
impl From<BackendError> for DecodeError {
fn from(error: BackendError) -> Self {
match error {
BackendError::Unsupported(reason) => Self::Unsupported(reason),
error => Self::Adapter(error.to_string()),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Submit {
Accepted,
Busy,
}
pub trait SurfaceLease: std::fmt::Debug + Send + Sync + 'static {
fn retained_bytes(&self) -> u64;
fn as_any(&self) -> &dyn std::any::Any;
}
#[derive(Clone, Debug)]
pub enum BackendImage {
Cpu {
format: YuvFormat,
planes: Vec<Plane>,
},
Surface(Arc<dyn SurfaceLease>),
}
#[derive(Clone, Debug)]
pub struct BackendFrame {
pub pts: i64,
pub image: BackendImage,
pub coded: (u32, u32),
pub visible: Option<Rect>,
pub sample_aspect_ratio: Option<SampleAspectRatio>,
pub color: Option<ColorMetadata>,
pub chroma_location: Option<ChromaLocation>,
}
#[derive(Debug)]
pub enum Poll {
Frame(BackendFrame),
Pending,
Drained,
}
pub trait VideoDecodeBackend: Send {
fn kind(&self) -> BackendKind;
fn submit(&mut self, packet: &Packet) -> Result<Submit, BackendError>;
fn receive(&mut self, wait: bool) -> Result<Poll, BackendError>;
fn presentation_order(&self) -> bool {
false
}
fn finish_input(&mut self) -> Result<(), BackendError>;
fn flush(&mut self) -> Result<(), BackendError>;
}
pub trait VideoBackends: Send + Sync {
fn open(
&self,
track: &TrackInfo,
kind: BackendKind,
) -> Result<Box<dyn VideoDecodeBackend>, BackendError>;
}
#[derive(Clone, Copy, Debug, Default)]
struct Bitstream {
vui: Vui,
chroma_location: Option<ChromaLocation>,
}
fn av1_chroma_location(record: &[u8]) -> Option<ChromaLocation> {
match record.get(2)? & 3 {
1 => Some(ChromaLocation::Left),
2 => Some(ChromaLocation::TopLeft),
_ => None,
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum DecodePreference {
#[default]
Auto,
Hardware,
Software,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct StreamOptions {
pub preference: DecodePreference,
pub policy: DecodePolicy,
pub declared_color: Option<ColorMetadata>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FrameFacts {
pub pts: MediaTime,
pub visible_rect: Rect,
pub orientation: Orientation,
pub sample_aspect_ratio: SampleAspectRatio,
pub chroma_location: ChromaLocation,
pub color: Option<ColorMetadata>,
}
#[derive(Clone, Debug)]
pub struct StreamFrame {
pub facts: FrameFacts,
pub image: BackendImage,
}
impl StreamFrame {
#[must_use]
pub fn retained_bytes(&self) -> u64 {
match &self.image {
BackendImage::Cpu { planes, .. } => {
planes.iter().map(|plane| plane.bytes.len() as u64).sum()
}
BackendImage::Surface(lease) => lease.retained_bytes(),
}
}
#[must_use]
pub fn to_cpu(&self) -> Option<DecodedVideoFrame> {
let BackendImage::Cpu { format, planes } = &self.image else {
return None;
};
Some(DecodedVideoFrame {
pts: self.facts.pts,
dts: None,
duration: None,
visible_rect: self.facts.visible_rect,
sample_aspect_ratio: self.facts.sample_aspect_ratio,
orientation: self.facts.orientation,
pixel_format: PixelFormat::Yuv(*format),
chroma_location: self.facts.chroma_location,
color: self.facts.color,
planes: planes.clone(),
})
}
}
#[derive(Debug, Default)]
pub struct ReorderBuffer {
depth: Option<usize>,
arriving: Vec<BackendFrame>,
ready: std::collections::VecDeque<BackendFrame>,
}
impl ReorderBuffer {
#[must_use]
pub fn new(depth: Option<usize>) -> Self {
Self {
depth,
..Self::default()
}
}
pub fn arrive(&mut self, frame: BackendFrame) {
if self.depth.is_none()
&& self
.arriving
.last()
.is_some_and(|latest| frame.pts >= latest.pts)
{
self.ready.extend(self.arriving.drain(..));
}
let at = self
.arriving
.iter()
.position(|held| held.pts > frame.pts)
.unwrap_or(self.arriving.len());
self.arriving.insert(at, frame);
if let Some(depth) = self.depth {
let excess = self.arriving.len().saturating_sub(depth);
self.ready.extend(self.arriving.drain(..excess));
}
}
pub fn drain(&mut self) {
self.ready.extend(self.arriving.drain(..));
}
pub fn take(&mut self) -> Option<BackendFrame> {
self.ready.pop_front()
}
pub fn clear(&mut self) {
self.arriving.clear();
self.ready.clear();
}
#[must_use]
pub fn len(&self) -> usize {
self.arriving.len() + self.ready.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
const MAX_SESSION_REOPENS: u32 = 3;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Input {
Open,
Full,
Ended,
Drained,
}
enum Interrupt {
Backend(BackendError),
Decode(DecodeError),
}
impl From<DecodeError> for Interrupt {
fn from(error: DecodeError) -> Self {
Self::Decode(error)
}
}
impl From<alpha2_container::DemuxError> for Interrupt {
fn from(error: alpha2_container::DemuxError) -> Self {
Self::Decode(error.into())
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DroppedLayer {
pub code: &'static str,
pub reason: String,
}
fn dropped_alpha(video: &alpha2_container::VideoTrack) -> Option<(SourceAlpha, DroppedLayer)> {
if !video.alpha {
return None;
}
let (alpha, reason) = match video.codec {
VideoCodec::Vp9 => (
SourceAlpha::Vp9SideData,
"VP9 alpha in block additions is not decoded on this platform",
),
VideoCodec::Hevc => (
SourceAlpha::HevcAuxiliaryLayer,
"alpha in an HEVC auxiliary layer is not decoded",
),
_ => (
SourceAlpha::Planar,
"the alpha plane is not decoded on this platform",
),
};
let dropped = DroppedLayer {
code: "alpha-dropped",
reason: reason.into(),
};
Some((alpha, dropped))
}
pub struct VideoStream {
reader: Box<dyn ContainerReader>,
track: TrackInfo,
backends: Arc<dyn VideoBackends>,
backend: Box<dyn VideoDecodeBackend>,
options: StreamOptions,
software_fallback_used: bool,
reopens: u32,
recovery: Recovery,
reorder: ReorderBuffer,
lookahead: Option<StreamFrame>,
pending: Option<Packet>,
input: Input,
last_returned: Option<i64>,
resume_after: Option<i64>,
first_keyframe: Option<i64>,
slack: MediaTime,
crop: Option<CropWindow>,
bitstream: Bitstream,
info: Vec<StreamInfo>,
dropped: Option<DroppedLayer>,
}
impl std::fmt::Debug for VideoStream {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("VideoStream")
.field("track", &self.track.id)
.field("backend", &self.backend.kind())
.finish_non_exhaustive()
}
}
impl VideoStream {
pub fn open(
mut reader: Box<dyn ContainerReader>,
index: usize,
backends: Arc<dyn VideoBackends>,
options: StreamOptions,
) -> Result<Self, DecodeError> {
let track =
reader.tracks().get(index).cloned().ok_or_else(|| {
DecodeError::Unsupported(format!("the file has no track {index}"))
})?;
let Some(video) = track.video.clone() else {
return Err(DecodeError::Unsupported(format!(
"track {} is not video",
track.id.0
)));
};
let sequence = match video.codec {
VideoCodec::H264 => sequence_facts(ParameterSetCodec::H264, &video.codec_private),
VideoCodec::Hevc => sequence_facts(ParameterSetCodec::Hevc, &video.codec_private),
_ => None,
};
let crop = sequence.map(|facts| facts.crop);
let bitstream = Bitstream {
vui: sequence.map(|facts| facts.vui).unwrap_or_default(),
chroma_location: match video.codec {
VideoCodec::Av1 => av1_chroma_location(&video.codec_private),
_ => sequence.and_then(|facts| facts.chroma_location()),
},
};
let first = match options.preference {
DecodePreference::Software => BackendKind::Software,
DecodePreference::Auto | DecodePreference::Hardware => BackendKind::Hardware,
};
let (backend, software_fallback_used) = match backends.open(&track, first) {
Ok(backend) => (backend, false),
Err(hardware) if options.preference == DecodePreference::Auto => {
let software = backends.open(&track, BackendKind::Software).map_err(|software| {
DecodeError::Unsupported(format!(
"no decoder here reads this stream (hardware: {hardware}; software: {software})"
))
})?;
(software, true)
}
Err(error) => return Err(error.into()),
};
let first_keyframe = reader.seek(track.id, i64::MIN)?;
let timescale = i64::from(track.timescale.max(1));
let slack = scan_slack(reader.as_mut(), &track)?;
let mut recovery = Recovery::new((1, i32::try_from(timescale).unwrap_or(i32::MAX)));
recovery.policy = options.policy;
recovery.set_hardware(backend.kind() == BackendKind::Hardware);
let dimensions = crop
.and_then(|crop| crop.visible())
.map_or((video.width, video.height), |rect| {
(rect.width, rect.height)
});
let reorder = ReorderBuffer::new(reorder_depth(backend.as_ref(), &track));
let (alpha, dropped) = dropped_alpha(&video).unzip();
let info = vec![StreamInfo {
index,
kind: StreamKind::Video,
codec: codec_name(video.codec),
duration: track
.duration
.map(|duration| to_media_time(duration, track.timescale)),
dimensions: Some(dimensions),
frame_rate: video.frame_rate,
sample_rate: None,
channels: None,
orientation: video.orientation,
sample_aspect_ratio: video
.sample_aspect_ratio
.or(bitstream.vui.sample_aspect_ratio)
.unwrap_or(SampleAspectRatio { num: 1, den: 1 }),
color: options
.declared_color
.or(video.color)
.or(bitstream.vui.color),
frame_bytes: None,
alpha,
language: track.language.clone(),
title: track.title.clone(),
}];
Ok(Self {
reader,
backends,
backend,
options,
software_fallback_used,
reopens: 0,
recovery,
reorder,
lookahead: None,
pending: None,
input: Input::Open,
last_returned: None,
resume_after: None,
first_keyframe,
slack,
crop,
bitstream,
info,
dropped,
track,
})
}
pub fn open_file(
path: &std::path::Path,
backends: Arc<dyn VideoBackends>,
options: StreamOptions,
) -> Result<Self, DecodeError> {
let reader = alpha2_container::open(path)?;
let index = alpha2_container::default_track(reader.tracks(), TrackKind::Video)
.ok_or_else(|| DecodeError::Unsupported("the file has no video track".into()))?;
Self::open(reader, index, backends, options)
}
#[must_use]
pub const fn track(&self) -> &TrackInfo {
&self.track
}
#[must_use]
pub const fn dropped_layer(&self) -> Option<&DroppedLayer> {
self.dropped.as_ref()
}
#[must_use]
pub fn lookahead_bytes(&self) -> u64 {
self.lookahead
.as_ref()
.map_or(0, StreamFrame::retained_bytes)
}
#[must_use]
pub const fn presentation_slack(&self) -> MediaTime {
self.slack
}
#[must_use]
pub fn on_hardware(&self) -> bool {
self.backend.kind() == BackendKind::Hardware
}
#[must_use]
pub const fn recovery(&self) -> &Recovery {
&self.recovery
}
pub fn next(&mut self, cancel: &CancelToken) -> Result<Option<StreamFrame>, DecodeError> {
let frame = match self.lookahead.take() {
Some(frame) => Some(frame),
None => self.decode_next(cancel)?,
};
if let Some(frame) = &frame {
self.last_returned = Some(self.track_units(frame.facts.pts));
}
Ok(frame)
}
pub fn peek_pts(&mut self, cancel: &CancelToken) -> Result<Option<MediaTime>, DecodeError> {
if self.lookahead.is_none() {
self.lookahead = self.decode_next(cancel)?;
}
Ok(self.lookahead.as_ref().map(|frame| frame.facts.pts))
}
pub fn seek(
&mut self,
time: MediaTime,
cancel: &CancelToken,
) -> Result<StreamFrame, DecodeError> {
loop {
match self.seek_once(time, cancel) {
Ok(frame) => {
self.last_returned = Some(self.track_units(frame.facts.pts));
return Ok(frame);
}
Err(Interrupt::Decode(error)) => return Err(error),
Err(Interrupt::Backend(error)) => self.replace_session(error)?,
}
}
}
fn seek_once(
&mut self,
time: MediaTime,
cancel: &CancelToken,
) -> Result<StreamFrame, Interrupt> {
self.resume_after = None;
let deadline = time.presentation_deadline(self.slack);
let mut target = self.track_units_floor(deadline);
let mut keyframe = self.reader.seek(self.track.id, target)?;
let first = loop {
self.reset(None)?;
let Some(first) = self.decode_raw(cancel)? else {
return Err(DecodeError::OutOfRange.into());
};
let at_start = keyframe.is_none() || keyframe <= self.first_keyframe;
if first.facts.pts <= deadline || at_start {
break first;
}
let landed = keyframe;
let mut step = 1_i64;
while keyframe == landed && target > i64::MIN {
target = target.min(landed.unwrap_or(target)).saturating_sub(step);
keyframe = self.reader.seek(self.track.id, target)?;
step = step.saturating_mul(2);
}
};
let mut shown = first;
loop {
match self.decode_raw(cancel)? {
Some(frame) if frame.facts.pts <= deadline => shown = frame,
Some(frame) => {
self.lookahead = Some(frame);
break;
}
None => break,
}
}
Ok(shown)
}
fn decode_next(&mut self, cancel: &CancelToken) -> Result<Option<StreamFrame>, DecodeError> {
loop {
match self.decode_raw(cancel) {
Ok(frame) => return Ok(frame),
Err(Interrupt::Decode(error)) => return Err(error),
Err(Interrupt::Backend(error)) => {
self.replace_session(error)?;
self.resume().map_err(|interrupt| match interrupt {
Interrupt::Decode(error) => error,
Interrupt::Backend(error) => error.into(),
})?;
}
}
}
}
fn decode_raw(&mut self, cancel: &CancelToken) -> Result<Option<StreamFrame>, Interrupt> {
let mut budget = WorkBudget::new();
loop {
if let Some(picture) = self.reorder.take() {
let frame = self.facts(picture);
let pts = self.track_units(frame.facts.pts);
budget.progressed();
if self.resume_after.is_some_and(|after| pts <= after) {
continue;
}
self.resume_after = None;
self.reopens = 0;
self.recovery.progress(Some(pts))?;
return Ok(Some(frame));
}
if self.input == Input::Drained {
if self.recovery.diagnostics.corrupt_packets.is_empty() {
return Ok(None);
}
self.recovery.video_eof()?;
return Ok(None);
}
budget.step(cancel)?;
if self.step()? {
budget.advanced();
}
}
}
fn step(&mut self) -> Result<bool, Interrupt> {
match self.backend.receive(self.input != Input::Open) {
Ok(Poll::Frame(picture)) => {
if self.input == Input::Full {
self.input = Input::Open;
}
self.reorder.arrive(picture);
return Ok(false);
}
Ok(Poll::Drained) => {
self.reorder.drain();
self.input = Input::Drained;
return Ok(false);
}
Ok(Poll::Pending) => {}
Err(BackendError::HardwarePicture(reason))
if self
.recovery
.counts_as_damage(DecodeFailure::HardwarePicture) =>
{
self.recovery
.corrupt_with_detail("video receive", None, Some(reason))?;
return Ok(false);
}
Err(error) => return Err(Interrupt::Backend(error)),
}
if matches!(self.input, Input::Ended | Input::Drained) {
return Ok(false);
}
let mut advanced = false;
if self.pending.is_none() {
if let Some(packet) = self.reader.next_packet(self.track.id)? {
self.pending = Some(packet);
advanced = true;
} else {
self.backend.finish_input().map_err(Interrupt::Backend)?;
self.input = Input::Ended;
return Ok(false);
}
}
let Some(packet) = self.pending.as_ref() else {
return Ok(advanced);
};
match self.backend.submit(packet) {
Ok(Submit::Accepted) => {
self.pending = None;
self.input = Input::Open;
advanced = true;
}
Ok(Submit::Busy) => self.input = Input::Full,
Err(BackendError::Corrupt(reason))
if self.recovery.counts_as_damage(DecodeFailure::InvalidData) =>
{
let pts = packet.pts;
self.pending = None;
self.recovery
.corrupt_with_detail("video send", Some(pts), Some(reason))?;
}
Err(error) => return Err(Interrupt::Backend(error)),
}
Ok(advanced)
}
fn reset(&mut self, lookahead: Option<StreamFrame>) -> Result<(), Interrupt> {
self.reorder.clear();
self.lookahead = lookahead;
self.pending = None;
self.input = Input::Open;
self.recovery.reset_progress();
self.backend.flush().map_err(Interrupt::Backend)
}
fn replace_session(&mut self, error: BackendError) -> Result<(), DecodeError> {
let kind = match &error {
BackendError::SessionLost(_) if self.reopens < MAX_SESSION_REOPENS => {
self.reopens += 1;
self.backend.kind()
}
BackendError::Unsupported(_)
| BackendError::Failed(_)
| BackendError::Corrupt(_)
| BackendError::HardwarePicture(_)
if self.backend.kind() == BackendKind::Hardware
&& self.options.preference == DecodePreference::Auto
&& !self.software_fallback_used =>
{
self.software_fallback_used = true;
BackendKind::Software
}
_ => return Err(error.into()),
};
self.backend = self.backends.open(&self.track, kind).map_err(|reopen| {
DecodeError::Adapter(format!("{error}; no session replaces it: {reopen}"))
})?;
self.reorder = ReorderBuffer::new(reorder_depth(self.backend.as_ref(), &self.track));
self.recovery
.set_hardware(self.backend.kind() == BackendKind::Hardware);
Ok(())
}
fn resume(&mut self) -> Result<(), Interrupt> {
let lookahead = self.lookahead.take();
let after = lookahead
.as_ref()
.map(|frame| self.track_units(frame.facts.pts))
.or(self.last_returned);
self.reader.seek(self.track.id, after.unwrap_or(i64::MIN))?;
self.reset(lookahead)?;
self.resume_after = after;
Ok(())
}
fn facts(&self, picture: BackendFrame) -> StreamFrame {
let video = self.track.video.as_ref();
let whole = Rect {
x: 0,
y: 0,
width: picture.coded.0,
height: picture.coded.1,
};
let window = self.crop.and_then(|crop| {
let visible = crop.visible()?;
if picture.coded == (crop.coded_width, crop.coded_height) {
Some(visible)
} else if picture.coded == (visible.width, visible.height) {
Some(whole)
} else {
None
}
});
let visible = window.or(picture.visible).unwrap_or(whole);
let chroma_location = picture
.chroma_location
.or(self.bitstream.chroma_location)
.unwrap_or(ChromaLocation::Unspecified);
StreamFrame {
facts: FrameFacts {
pts: to_media_time(picture.pts, self.track.timescale),
visible_rect: visible,
orientation: video.map(|video| video.orientation).unwrap_or_default(),
sample_aspect_ratio: video
.and_then(|video| video.sample_aspect_ratio)
.or(self.bitstream.vui.sample_aspect_ratio)
.or(picture.sample_aspect_ratio)
.unwrap_or(SampleAspectRatio { num: 1, den: 1 }),
chroma_location,
color: self
.options
.declared_color
.or_else(|| video.and_then(|video| video.color))
.or(self.bitstream.vui.color)
.or(picture.color),
},
image: picture.image,
}
}
fn track_units(&self, time: MediaTime) -> i64 {
rescale(
time.ticks(),
i64::from(self.track.timescale.max(1)),
TICKS_PER_SECOND,
false,
)
}
fn track_units_floor(&self, time: MediaTime) -> i64 {
rescale(
time.ticks(),
i64::from(self.track.timescale.max(1)),
TICKS_PER_SECOND,
true,
)
}
}
fn reorder_depth(backend: &dyn VideoDecodeBackend, track: &TrackInfo) -> Option<usize> {
if backend.presentation_order() {
return Some(0);
}
track.video.as_ref().and_then(|video| video.reorder_depth)
}
fn scan_slack(
reader: &mut dyn ContainerReader,
track: &TrackInfo,
) -> Result<MediaTime, DecodeError> {
let timestamps = first_timestamps(reader, track)?;
reader.seek(track.id, i64::MIN)?;
Ok(alpha2_time::presentation_slack(
1,
i64::from(track.timescale.max(1)),
alpha2_time::rounding_quantum(×tamps),
))
}
pub(crate) fn first_timestamps(
reader: &mut dyn ContainerReader,
track: &TrackInfo,
) -> Result<Vec<i64>, DecodeError> {
let mut timestamps = Vec::with_capacity(alpha2_time::ROUNDING_SCAN_FRAMES);
let mut bytes = 0_u64;
while timestamps.len() < alpha2_time::ROUNDING_SCAN_FRAMES
&& bytes < alpha2_time::ROUNDING_SCAN_BYTES
{
let Some(packet) = reader.next_packet(track.id)? else {
break;
};
bytes = bytes.saturating_add(packet.data.len() as u64);
timestamps.push(packet.pts);
}
Ok(timestamps)
}
#[must_use]
pub fn to_media_time(units: i64, timescale: u32) -> MediaTime {
MediaTime::from_ticks(rescale(
units,
TICKS_PER_SECOND,
i64::from(timescale.max(1)),
false,
))
}
fn rescale(value: i64, numerator: i64, denominator: i64, floor: bool) -> i64 {
let product = i128::from(value) * i128::from(numerator);
let denominator = i128::from(denominator);
let scaled = if floor {
product.div_euclid(denominator)
} else {
let half = denominator / 2;
if product >= 0 {
(product + half) / denominator
} else {
(product - half) / denominator
}
};
i64::try_from(scaled).unwrap_or(if scaled < 0 { i64::MIN } else { i64::MAX })
}
fn codec_name(codec: VideoCodec) -> String {
match codec {
VideoCodec::H264 => "h264".into(),
VideoCodec::Hevc => "hevc".into(),
VideoCodec::Vp8 => "vp8".into(),
VideoCodec::Vp9 => "vp9".into(),
VideoCodec::Av1 => "av1".into(),
VideoCodec::Mpeg4Part2 => "mpeg4".into(),
VideoCodec::ProRes(_) => "prores".into(),
VideoCodec::Other(fourcc) => fourcc.to_string(),
}
}
impl Decoder for VideoStream {
fn streams(&self) -> &[StreamInfo] {
&self.info
}
fn flush(&mut self) -> Result<(), DecodeError> {
let after = self.last_returned;
self.reader.seek(self.track.id, after.unwrap_or(i64::MIN))?;
match self.reset(None) {
Ok(()) => {}
Err(Interrupt::Decode(error)) => return Err(error),
Err(Interrupt::Backend(error)) => self.replace_session(error)?,
}
self.resume_after = after;
Ok(())
}
fn seek(
&mut self,
request: DecodeRequest,
cancel: &CancelToken,
) -> Result<DecodeResult, DecodeError> {
let frame = VideoStream::seek(self, request.time, cancel)?;
Ok(DecodeResult {
request,
event: DecodeEvent::Video(cpu_frame(&frame)?),
})
}
fn decode_next(&mut self, cancel: &CancelToken) -> Result<DecodeEvent, DecodeError> {
Ok(match self.next(cancel)? {
Some(frame) => DecodeEvent::Video(cpu_frame(&frame)?),
None => DecodeEvent::EndOfStream,
})
}
}
fn cpu_frame(frame: &StreamFrame) -> Result<DecodedVideoFrame, DecodeError> {
frame.to_cpu().ok_or_else(|| {
DecodeError::Unsupported(
"the decoder produced a surface where CPU planes were asked".into(),
)
})
}
#[cfg(test)]
#[path = "video_stream_tests.rs"]
mod tests;