1 //! Decoder interface definitions.
2 pub use crate::frame::*;
3 use crate::io::byteio::ByteIOError;
4 use crate::io::bitreader::BitReaderError;
5 use crate::io::codebook::CodebookError;
6 pub use crate::options::*;
7 pub use std::str::FromStr;
9 /// A list specifying general decoding errors.
10 #[derive(Debug,Clone,Copy,PartialEq)]
12 pub enum DecoderError {
13 /// No frame was provided.
15 /// Allocation failed.
17 /// Operation requires repeating.
19 /// Invalid input data was provided.
21 /// Provided input turned out to be incomplete.
23 /// Decoder could not decode provided frame because it references some missing previous frame.
25 /// Feature is not implemented.
27 /// Some bug in decoder. It should not happen yet it might.
31 /// A specialised `Result` type for decoding operations.
32 pub type DecoderResult<T> = Result<T, DecoderError>;
34 impl From<ByteIOError> for DecoderError {
35 fn from(_: ByteIOError) -> Self { DecoderError::ShortData }
38 impl From<BitReaderError> for DecoderError {
39 fn from(e: BitReaderError) -> Self {
41 BitReaderError::BitstreamEnd => DecoderError::ShortData,
42 _ => DecoderError::InvalidData,
47 impl From<CodebookError> for DecoderError {
48 fn from(_: CodebookError) -> Self { DecoderError::InvalidData }
51 impl From<AllocatorError> for DecoderError {
52 fn from(_: AllocatorError) -> Self { DecoderError::AllocError }
55 /// Auxiliary structure for storing data used by decoder but also controlled by the caller.
56 pub struct NADecoderSupport {
57 /// Frame buffer pool for 8-bit or packed video frames.
58 pub pool_u8: NAVideoBufferPool<u8>,
59 /// Frame buffer pool for 16-bit video frames.
60 pub pool_u16: NAVideoBufferPool<u16>,
61 /// Frame buffer pool for 32-bit video frames.
62 pub pool_u32: NAVideoBufferPool<u32>,
65 impl NADecoderSupport {
66 /// Constructs a new instance of `NADecoderSupport`.
67 pub fn new() -> Self {
69 pool_u8: NAVideoBufferPool::new(0),
70 pool_u16: NAVideoBufferPool::new(0),
71 pool_u32: NAVideoBufferPool::new(0),
76 impl Default for NADecoderSupport {
77 fn default() -> Self { Self::new() }
81 pub trait NADecoder: NAOptionHandler {
82 /// Initialises the decoder.
84 /// It takes [`NADecoderSupport`] allocated by the caller and `NACodecInfoRef` provided by demuxer.
86 /// [`NADecoderSupport`]: ./struct.NADecoderSupport.html
87 fn init(&mut self, supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()>;
88 /// Decodes a single frame.
89 fn decode(&mut self, supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef>;
90 /// Tells decoder to clear internal state (e.g. after error or seeking).
94 /// Decoder information used during creating a decoder for requested codec.
96 pub struct DecoderInfo {
97 /// Short decoder name.
98 pub name: &'static str,
99 /// The function that creates a decoder instance.
100 pub get_decoder: fn () -> Box<dyn NADecoder + Send>,
103 /// Structure for registering known decoders.
105 /// It is supposed to be filled using `register_all_decoders()` from some decoders crate and then it can be used to create decoders for the requested codecs.
107 pub struct RegisteredDecoders {
108 decs: Vec<DecoderInfo>,
111 impl RegisteredDecoders {
112 /// Constructs a new instance of `RegisteredDecoders`.
113 pub fn new() -> Self {
114 Self { decs: Vec::new() }
116 /// Adds another decoder to the registry.
117 pub fn add_decoder(&mut self, dec: DecoderInfo) {
120 /// Searches for the decoder for the provided name and returns a function for creating it on success.
121 pub fn find_decoder(&self, name: &str) -> Option<fn () -> Box<dyn NADecoder + Send>> {
122 for &dec in self.decs.iter() {
123 if dec.name == name {
124 return Some(dec.get_decoder);
129 /// Provides an iterator over currently registered decoders.
130 pub fn iter(&self) -> std::slice::Iter<DecoderInfo> {
135 /// Frame skipping mode for decoders.
136 #[derive(Clone,Copy,PartialEq,Debug)]
137 pub enum FrameSkipMode {
138 /// Decode all frames.
140 /// Decode all key frames.
142 /// Decode only intra frames.
146 impl Default for FrameSkipMode {
147 fn default() -> Self {
152 impl FromStr for FrameSkipMode {
153 type Err = DecoderError;
155 fn from_str(s: &str) -> Result<Self, Self::Err> {
157 FRAME_SKIP_OPTION_VAL_NONE => Ok(FrameSkipMode::None),
158 FRAME_SKIP_OPTION_VAL_KEYFRAME => Ok(FrameSkipMode::KeyframesOnly),
159 FRAME_SKIP_OPTION_VAL_INTRA => Ok(FrameSkipMode::IntraOnly),
160 _ => Err(DecoderError::InvalidData),
165 impl ToString for FrameSkipMode {
166 fn to_string(&self) -> String {
168 FrameSkipMode::None => FRAME_SKIP_OPTION_VAL_NONE.to_string(),
169 FrameSkipMode::KeyframesOnly => FRAME_SKIP_OPTION_VAL_KEYFRAME.to_string(),
170 FrameSkipMode::IntraOnly => FRAME_SKIP_OPTION_VAL_INTRA.to_string(),
175 /// A list specifying general encoding errors.
176 #[derive(Debug,Clone,Copy,PartialEq)]
178 pub enum EncoderError {
179 /// No frame was provided.
181 /// Allocation failed.
183 /// Operation requires repeating.
185 /// Input format is not supported by codec.
187 /// Invalid input parameters were provided.
189 /// Feature is not implemented.
191 /// Some bug in encoder. It should not happen yet it might.
195 /// A specialised `Result` type for decoding operations.
196 pub type EncoderResult<T> = Result<T, EncoderError>;
198 impl From<ByteIOError> for EncoderError {
199 fn from(_: ByteIOError) -> Self { EncoderError::Bug }
202 impl From<AllocatorError> for EncoderError {
203 fn from(_: AllocatorError) -> Self { EncoderError::AllocError }
206 /// Encoding parameter flag to force constant bitrate mode.
207 pub const ENC_MODE_CBR: u64 = 1 << 0;
208 /// Encoding parameter flag to force constant framerate mode.
209 pub const ENC_MODE_CFR: u64 = 1 << 1;
211 /// Encoding parameters.
212 #[derive(Clone,Copy,PartialEq)]
213 pub struct EncodeParameters {
215 pub format: NACodecTypeInfo,
216 /// Time base numerator. Ignored for audio.
218 /// Time base denominator. Ignored for audio.
220 /// Bitrate in kilobits per second.
222 /// A collection of various boolean encoder settings like CBR mode.
224 /// See `ENC_MODE_*` constants for available options.
226 /// Encoding quality.
230 impl Default for EncodeParameters {
231 fn default() -> EncodeParameters {
233 format: NACodecTypeInfo::None,
245 /// Overall encoding is more complex than decoding.
246 /// There are at least two issues that should be addressed: input format and the need for lookahead.
248 /// Some formats (like MPEG-1 ones) have fixed picture dimensions and framerate, or sampling rate.
249 /// Some formats accept only pictures with dimensions being multiple of eight or sixteen.
250 /// Some audio formats work only with monaural sound.
251 /// In order to account for all this user first needs to check whether encoder can handle provided input format as is or some conversion is required.
252 /// That is why `NAEncoder` has [`negotiate_format`] function that performs such check and returns what encoder can handle.
254 /// Additionally, encoders for complex formats often need several frames lookahead to encode data efficiently, actual frame encoding may take place only when some frames are accumulated.
255 /// That is why encoder has two functions, one for queueing frames for encoding and one for obtaining encoded packets when they are available.
256 /// In result encoder should first queue a frame for encoding with [`encode`] and then retrieve zero or more encoded packets with [`get_packet`] in a loop.
258 /// Overall encoding loop should look like this:
260 /// let encoder = ...; // create encoder
261 /// let enc_params = encoder.negotiate_format(input_enc_params)?; // negotiate format
262 /// let output_stream = encoder.init(stream_no, enc_params)?;
263 /// while let Some(frame) = queue.get_frame() {
264 /// // convert to the format encoder expects if required
265 /// encoder.encode(frame)?;
266 /// while let Ok(enc_pkt) = encoder.get_packet()? {
267 /// // send encoded packet to a muxer for example
270 /// // retrieve the rest of encoded packets
271 /// encoder.flush()?;
272 /// while let Ok(enc_pkt) = encoder.get_packet()? {
273 /// // send encoded packet to a muxer for example
277 /// [`negotiate_format`]: ./trait.NAEncoder.html#tymethod.negotiate_format
278 /// [`encode`]: ./trait.NAEncoder.html#tymethod.encode
279 /// [`get_packet`]: ./trait.NAEncoder.html#tymethod.get_packet
280 pub trait NAEncoder: NAOptionHandler {
281 /// Tries to negotiate input format.
283 /// This function takes input encoding parameters and returns adjusted encoding parameters if input ones make sense.
284 /// If input parameters are empty then the default parameters are returned.
288 /// let enc_params = [ EncodeParameters {...}, ..., EncodeParameters::default() ];
289 /// let mut target_params = EncodeParameters::default();
290 /// for params in enc_params.iter() {
291 /// if let Ok(dparams) = encoder.negotiate_format(params) {
292 /// target_params = dparams;
296 /// // since negotiate_format(EncodeParameters::default()) will return a valid format, target_params should be valid here
297 /// let stream = encoder.init(stream_id, target_params)?;
298 /// // convert input into format defined in target_params, feed to the encoder, ...
300 fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters>;
301 /// Initialises the encoder.
302 fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef>;
303 /// Takes a single frame for encoding.
304 fn encode(&mut self, frm: &NAFrame) -> EncoderResult<()>;
305 /// Returns encoded packet if available.
306 fn get_packet(&mut self) -> EncoderResult<Option<NAPacket>>;
307 /// Tells encoder to encode all data it currently has.
308 fn flush(&mut self) -> EncoderResult<()>;
311 /// Encoder information used during creating an encoder for requested codec.
312 #[derive(Clone,Copy)]
313 pub struct EncoderInfo {
314 /// Short encoder name.
315 pub name: &'static str,
316 /// The function that creates an encoder instance.
317 pub get_encoder: fn () -> Box<dyn NAEncoder + Send>,
320 /// Structure for registering known encoders.
322 /// It is supposed to be filled using `register_all_decoders()` from some encoders crate and then it can be used to create encoders for the requested codecs.
324 pub struct RegisteredEncoders {
325 encs: Vec<EncoderInfo>,
328 impl RegisteredEncoders {
329 /// Constructs a new instance of `RegisteredEncoders`.
330 pub fn new() -> Self {
331 Self { encs: Vec::new() }
333 /// Adds another encoder to the registry.
334 pub fn add_encoder(&mut self, enc: EncoderInfo) {
337 /// Searches for the encoder for the provided name and returns a function for creating it on success.
338 pub fn find_encoder(&self, name: &str) -> Option<fn () -> Box<dyn NAEncoder + Send>> {
339 for &enc in self.encs.iter() {
340 if enc.name == name {
341 return Some(enc.get_encoder);
346 /// Provides an iterator over currently registered encoders.
347 pub fn iter(&self) -> std::slice::Iter<EncoderInfo> {