Skip to content

decoders: Add stateful decoder API #62

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 27 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ libva = { git = "https://github.com/chromeos/cros-libva", rev = "905041a9", pack
log = { version = "0", features = ["release_max_level_debug"] }
thiserror = "1.0.31"
crc32fast = "1.3.2"
zerocopy = { version = "0.7", features = ["derive"] }

[dev-dependencies]
argh = "0.1"
Expand Down
1 change: 1 addition & 0 deletions src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//!
//! At the moment, only a [stateless] decoder interface is provided.

pub mod stateful;
pub mod stateless;

use std::collections::VecDeque;
Expand Down
169 changes: 169 additions & 0 deletions src/decoder/stateful.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
// Copyright 2023 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use thiserror::Error;
use zerocopy::AsBytes;

use crate::decoder::DecodedHandle;
use crate::decoder::StreamInfo;
use crate::DecodedFormat;
use crate::Resolution;

use std::sync::Arc;

pub enum DecodeError {
InvalidState,
InvalidData,
}

pub enum ConfigError {
InvalidState,
NotSupported,
InvalidConfig,
}

/// Error returned by stateful backend methods.
#[derive(Error, Debug)]
pub enum StatefulBackendError {
#[error("not enough resources to proceed with the operation now")]
OutOfResources,
#[error("this format is not supported")]
UnsupportedFormat,
#[error(transparent)]
Other(#[from] anyhow::Error),
}

#[derive(Copy, Clone, Debug)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since ccdec has a similar enum, we should probably have a single declaration in lib.rs since we already have DecodedFormat there.

pub enum EncodedFormat {
AV1,
H264,
H265,
VP8,
VP9,
}

/// Common trait shared by all stateful video decoder backends, providing codec-independent
/// methods.
pub trait StatefulDecoderBackend<Codec: StatefulCodec> {
/// The type that the backend returns as a result of a decode operation.
/// This will usually be some backend-specific type with a resource and a
/// resource pool so that said buffer can be reused for another decode
/// operation when it goes out of scope.
type Handle: DecodedHandle;

/// Returns the current decoding parameters, as parsed from the stream.
fn stream_info(&self) -> Option<&StreamInfo>;
}

pub trait StatefulCodec {
/// State that needs to be kept during a decoding operation, typed by backend.
type DecoderState<B: StatefulDecoderBackend<Self>>;
}

#[derive(Copy, Clone, Debug)]

pub enum ColorGamut {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now we don't have any way to manage color properties, even for stateless decoders. Let's drop this for now as it is not needed for basic decoding.

Bt709,
Bt470bg,
Smpte170m,
}

#[derive(Copy, Clone, Debug)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here.

pub enum ColorTransfer {
Bt709,
Smpte170m,
Iec61966_2_1,
}

#[derive(Copy, Clone, Debug)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here.

pub enum ColorMatrix {
Rgb,
Bt709,
Bt470bg,
Smpte170m,
}

#[derive(Copy, Clone, Debug)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here.

pub struct VideoColorSpace {
primaries: ColorGamut,
transfer: ColorTransfer,
matrix: ColorMatrix,
}

#[derive(Clone, Debug)]
pub struct EncodedVideoChunk {
data: Arc<Vec<u8>>,
}

pub struct VideoFrame {
format: DecodedFormat,
coded_resolution: Resolution,
display_resolution: Resolution,
duration: usize,
timestamp: usize,
color_space: VideoColorSpace,
buffer: Option<Box<dyn AsBytes>>,
}

pub enum StatefulDecoderEvent {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect you can reuse DecoderEvent (and the DecodedHandle trait) as-is for the stateful decoder. It will align the interfaces and make the code simpler somehow.

/// The next frame has been decoded.
FrameReady(VideoFrame),
/// The format of the stream has changed and action is required. A VideoFrame
/// with no buffer is returned.
FormatChanged(VideoFrame),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to return a videoframe here?

}

pub trait StatefulVideoDecoder<M> {
/// Add a new chunk of video to decoding queue, this is a non-blocking method
fn decode(&mut self, chunk: EncodedVideoChunk) -> Result<(), DecodeError>;

/// Return information about the currently decoded stream
fn stream_info(&self) -> Option<&StreamInfo>;

/// Close the decoder and prevent it from future use
fn close(&mut self);

/// Finish processing all pending decode requests
fn flush(&mut self) -> Result<(), DecodeError>;

/// Returns the next event, if there is any pending.
fn next_event(&mut self) -> Option<StatefulDecoderEvent>;
}

#[derive(Copy, Clone, Debug, Default)]
pub enum StatefulDecoderState {
#[default]
Unconfigured,
Configured,
Closed,
}

pub struct StatefulDecoder<C, B>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The first use of the stateful decoder interface should be as a stateful wrapper to any stateless decoder, i.e. an adapter that turns a stateless decoder into a stateful one. That adapter maybe be implemented as a StatefulDecoderBackend, but for simplicity I'd recommend writing it as an implementation of StatefulDecoder first and see what parts we can share with other stateful decoder implementations.

So I'd suggest starting with the design of this wrapper first to guide the interface. Starting from any stateless decoder, the stateful wrapper should

  • Accept input buffers and queue them until they can be processed,
  • Try to submit work to the stateless decoder, hold if the work cannot be submitted to retry later, and process the events of the stateless decoder, forwarding them to the caller if needed (e.g. decoded frames),

... and I think that's mostly it. The simple_playback_loop should give a good example of how things should work, as its purpose is to provide some stateful-ish behavior to our stateless decoders. I will be replaced it by the stateful decoder once it is available.

where
C: StatefulCodec,
B: StatefulDecoderBackend<C>,
{
decoding_state: StatefulDecoderState,

/// The backend used for hardware acceleration.
backend: B,

/// Codec-specific state.
codec_state: C::DecoderState<B>,
}

impl<C, B> StatefulDecoder<C, B>
where
C: StatefulCodec,
B: StatefulDecoderBackend<C>,
C::DecoderState<B>: Default,
{
pub fn new(backend: B) -> Self {
Self {
backend,
decoding_state: Default::default(),
codec_state: Default::default(),
}
}
}