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 /// Checksum verification failed.
23 /// Provided input turned out to be incomplete.
25 /// Decoder could not decode provided frame because it references some missing previous frame.
27 /// Feature is not implemented.
29 /// Some bug in decoder. It should not happen yet it might.
33 /// A specialised `Result` type for decoding operations.
34 pub type DecoderResult<T> = Result<T, DecoderError>;
36 impl From<ByteIOError> for DecoderError {
37 fn from(_: ByteIOError) -> Self { DecoderError::ShortData }
40 impl From<BitReaderError> for DecoderError {
41 fn from(e: BitReaderError) -> Self {
43 BitReaderError::BitstreamEnd => DecoderError::ShortData,
44 _ => DecoderError::InvalidData,
49 impl From<CodebookError> for DecoderError {
50 fn from(_: CodebookError) -> Self { DecoderError::InvalidData }
53 impl From<AllocatorError> for DecoderError {
54 fn from(_: AllocatorError) -> Self { DecoderError::AllocError }
57 /// Auxiliary structure for storing data used by decoder but also controlled by the caller.
58 pub struct NADecoderSupport {
59 /// Frame buffer pool for 8-bit or packed video frames.
60 pub pool_u8: NAVideoBufferPool<u8>,
61 /// Frame buffer pool for 16-bit video frames.
62 pub pool_u16: NAVideoBufferPool<u16>,
63 /// Frame buffer pool for 32-bit video frames.
64 pub pool_u32: NAVideoBufferPool<u32>,
67 impl NADecoderSupport {
68 /// Constructs a new instance of `NADecoderSupport`.
69 pub fn new() -> Self {
71 pool_u8: NAVideoBufferPool::new(0),
72 pool_u16: NAVideoBufferPool::new(0),
73 pool_u32: NAVideoBufferPool::new(0),
78 impl Default for NADecoderSupport {
79 fn default() -> Self { Self::new() }
83 pub trait NADecoder: NAOptionHandler {
84 /// Initialises the decoder.
86 /// It takes [`NADecoderSupport`] allocated by the caller and `NACodecInfoRef` provided by demuxer.
88 /// [`NADecoderSupport`]: ./struct.NADecoderSupport.html
89 fn init(&mut self, supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()>;
90 /// Decodes a single frame.
91 fn decode(&mut self, supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef>;
92 /// Tells decoder to clear internal state (e.g. after error or seeking).
96 /// Decoder information used during creating a decoder for requested codec.
98 pub struct DecoderInfo {
99 /// Short decoder name.
100 pub name: &'static str,
101 /// The function that creates a decoder instance.
102 pub get_decoder: fn () -> Box<dyn NADecoder + Send>,
105 /// Structure for registering known decoders.
107 /// 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.
109 pub struct RegisteredDecoders {
110 decs: Vec<DecoderInfo>,
113 impl RegisteredDecoders {
114 /// Constructs a new instance of `RegisteredDecoders`.
115 pub fn new() -> Self {
116 Self { decs: Vec::new() }
118 /// Adds another decoder to the registry.
119 pub fn add_decoder(&mut self, dec: DecoderInfo) {
122 /// Searches for the decoder for the provided name and returns a function for creating it on success.
123 pub fn find_decoder(&self, name: &str) -> Option<fn () -> Box<dyn NADecoder + Send>> {
124 for &dec in self.decs.iter() {
125 if dec.name == name {
126 return Some(dec.get_decoder);
131 /// Provides an iterator over currently registered decoders.
132 pub fn iter(&self) -> std::slice::Iter<DecoderInfo> {
137 /// Frame skipping mode for decoders.
138 #[derive(Clone,Copy,PartialEq,Debug)]
139 pub enum FrameSkipMode {
140 /// Decode all frames.
142 /// Decode all key frames.
144 /// Decode only intra frames.
148 impl Default for FrameSkipMode {
149 fn default() -> Self {
154 impl FromStr for FrameSkipMode {
155 type Err = DecoderError;
157 fn from_str(s: &str) -> Result<Self, Self::Err> {
159 FRAME_SKIP_OPTION_VAL_NONE => Ok(FrameSkipMode::None),
160 FRAME_SKIP_OPTION_VAL_KEYFRAME => Ok(FrameSkipMode::KeyframesOnly),
161 FRAME_SKIP_OPTION_VAL_INTRA => Ok(FrameSkipMode::IntraOnly),
162 _ => Err(DecoderError::InvalidData),
167 impl ToString for FrameSkipMode {
168 fn to_string(&self) -> String {
170 FrameSkipMode::None => FRAME_SKIP_OPTION_VAL_NONE.to_string(),
171 FrameSkipMode::KeyframesOnly => FRAME_SKIP_OPTION_VAL_KEYFRAME.to_string(),
172 FrameSkipMode::IntraOnly => FRAME_SKIP_OPTION_VAL_INTRA.to_string(),
177 /// A list specifying general encoding errors.
178 #[derive(Debug,Clone,Copy,PartialEq)]
180 pub enum EncoderError {
181 /// No frame was provided.
183 /// Allocation failed.
185 /// Operation requires repeating.
187 /// Input format is not supported by codec.
189 /// Invalid input parameters were provided.
191 /// Feature is not implemented.
193 /// Some bug in encoder. It should not happen yet it might.
197 /// A specialised `Result` type for decoding operations.
198 pub type EncoderResult<T> = Result<T, EncoderError>;
200 impl From<ByteIOError> for EncoderError {
201 fn from(_: ByteIOError) -> Self { EncoderError::Bug }
204 impl From<AllocatorError> for EncoderError {
205 fn from(_: AllocatorError) -> Self { EncoderError::AllocError }
208 /// Encoding parameter flag to force constant bitrate mode.
209 pub const ENC_MODE_CBR: u64 = 1 << 0;
210 /// Encoding parameter flag to force constant framerate mode.
211 pub const ENC_MODE_CFR: u64 = 1 << 1;
213 /// Encoder supports constant bitrate mode.
214 pub const ENC_CAPS_CBR: u64 = 1 << 0;
215 /// Encoder supports skip frames.
216 pub const ENC_CAPS_SKIPFRAME: u64 = 1 << 1;
217 /// Encoder supports mid-stream parameters change.
218 pub const ENC_CAPS_PARAMCHANGE: u64 = 1 << 2;
220 /// Encoding parameters.
221 #[derive(Clone,Copy,PartialEq)]
222 pub struct EncodeParameters {
224 pub format: NACodecTypeInfo,
225 /// Time base numerator. Ignored for audio.
227 /// Time base denominator. Ignored for audio.
229 /// Bitrate in bits per second.
231 /// A collection of various boolean encoder settings like CBR mode.
233 /// See `ENC_MODE_*` constants for available options.
235 /// Encoding quality.
239 impl Default for EncodeParameters {
240 fn default() -> EncodeParameters {
242 format: NACodecTypeInfo::None,
254 /// Overall encoding is more complex than decoding.
255 /// There are at least two issues that should be addressed: input format and the need for lookahead.
257 /// Some formats (like MPEG-1 ones) have fixed picture dimensions and framerate, or sampling rate.
258 /// Some formats accept only pictures with dimensions being multiple of eight or sixteen.
259 /// Some audio formats work only with monaural sound.
260 /// 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.
261 /// That is why `NAEncoder` has [`negotiate_format`] function that performs such check and returns what encoder can handle.
263 /// 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.
264 /// That is why encoder has two functions, one for queueing frames for encoding and one for obtaining encoded packets when they are available.
265 /// 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.
267 /// Overall encoding loop should look like this:
269 /// let encoder = ...; // create encoder
270 /// let enc_params = encoder.negotiate_format(input_enc_params)?; // negotiate format
271 /// let output_stream = encoder.init(stream_no, enc_params)?;
272 /// while let Some(frame) = queue.get_frame() {
273 /// // convert to the format encoder expects if required
274 /// encoder.encode(frame)?;
275 /// while let Ok(enc_pkt) = encoder.get_packet()? {
276 /// // send encoded packet to a muxer for example
279 /// // retrieve the rest of encoded packets
280 /// encoder.flush()?;
281 /// while let Ok(enc_pkt) = encoder.get_packet()? {
282 /// // send encoded packet to a muxer for example
286 /// [`negotiate_format`]: ./trait.NAEncoder.html#tymethod.negotiate_format
287 /// [`encode`]: ./trait.NAEncoder.html#tymethod.encode
288 /// [`get_packet`]: ./trait.NAEncoder.html#tymethod.get_packet
289 pub trait NAEncoder: NAOptionHandler {
290 /// Tries to negotiate input format.
292 /// This function takes input encoding parameters and returns adjusted encoding parameters if input ones make sense.
293 /// If input parameters are empty then the default parameters are returned.
297 /// let enc_params = [ EncodeParameters {...}, ..., EncodeParameters::default() ];
298 /// let mut target_params = EncodeParameters::default();
299 /// for params in enc_params.iter() {
300 /// if let Ok(dparams) = encoder.negotiate_format(params) {
301 /// target_params = dparams;
305 /// // since negotiate_format(EncodeParameters::default()) will return a valid format, target_params should be valid here
306 /// let stream = encoder.init(stream_id, target_params)?;
307 /// // convert input into format defined in target_params, feed to the encoder, ...
309 fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters>;
310 /// Queries encoder capabilities.
312 /// See `ENC_CAPS_*` for examples.
313 fn get_capabilities(&self) -> u64;
314 /// Initialises the encoder.
315 fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef>;
316 /// Takes a single frame for encoding.
317 fn encode(&mut self, frm: &NAFrame) -> EncoderResult<()>;
318 /// Returns encoded packet if available.
319 fn get_packet(&mut self) -> EncoderResult<Option<NAPacket>>;
320 /// Tells encoder to encode all data it currently has.
321 fn flush(&mut self) -> EncoderResult<()>;
324 /// Encoder information used during creating an encoder for requested codec.
325 #[derive(Clone,Copy)]
326 pub struct EncoderInfo {
327 /// Short encoder name.
328 pub name: &'static str,
329 /// The function that creates an encoder instance.
330 pub get_encoder: fn () -> Box<dyn NAEncoder + Send>,
333 /// Structure for registering known encoders.
335 /// 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.
337 pub struct RegisteredEncoders {
338 encs: Vec<EncoderInfo>,
341 impl RegisteredEncoders {
342 /// Constructs a new instance of `RegisteredEncoders`.
343 pub fn new() -> Self {
344 Self { encs: Vec::new() }
346 /// Adds another encoder to the registry.
347 pub fn add_encoder(&mut self, enc: EncoderInfo) {
350 /// Searches for the encoder for the provided name and returns a function for creating it on success.
351 pub fn find_encoder(&self, name: &str) -> Option<fn () -> Box<dyn NAEncoder + Send>> {
352 for &enc in self.encs.iter() {
353 if enc.name == name {
354 return Some(enc.get_encoder);
359 /// Provides an iterator over currently registered encoders.
360 pub fn iter(&self) -> std::slice::Iter<EncoderInfo> {
365 /// Trait for packetisers (objects that form full packets from raw stream data).
366 pub trait NAPacketiser {
367 /// Queues new raw stream data for parsing.
369 /// Returns false is the internal buffer grows too large.
370 fn add_data(&mut self, src: &[u8]) -> bool;
371 /// Tries to retrieve stream information from the data.
373 /// Returns [`NAStream`] reference on success (with stream ID set to `id`), [`ShortData`] when there is not enough data to parse the headers and other errors in case there was an error parsing the data.
375 /// [`NAStream`]: ../frame/struct.NAStream.html
376 /// [`ShortData`]: ./enum.DecoderError.html#variant.ShortData
377 fn parse_stream(&mut self, id: u32) -> DecoderResult<NAStreamRef>;
378 /// Tries to discard junk data until the first possible packet header.
380 /// Returns the number of bytes skipped.
381 fn skip_junk(&mut self) -> DecoderResult<usize>;
382 /// Tries to form full packet from the already queued data.
384 /// The function should be called repeatedly until it returns nothing or an error.
385 fn get_packet(&mut self, stream: NAStreamRef) -> DecoderResult<Option<NAPacket>>;
386 /// Resets the internal buffer.
388 /// Tells how much data is left in the internal buffer.
389 fn bytes_left(&self) -> usize;
392 /// Decoder information used during creating a packetiser for requested codec.
393 #[derive(Clone,Copy)]
394 pub struct PacketiserInfo {
395 /// Short packetiser name.
396 pub name: &'static str,
397 /// The function that creates a packetiser instance.
398 pub get_packetiser: fn () -> Box<dyn NAPacketiser + Send>,
401 /// Structure for registering known packetisers.
403 /// It is supposed to be filled using `register_all_packetisers()` from some decoders crate and then it can be used to create packetisers for the requested codecs.
405 pub struct RegisteredPacketisers {
406 packs: Vec<PacketiserInfo>,
409 impl RegisteredPacketisers {
410 /// Constructs a new instance of `RegisteredPacketisers`.
411 pub fn new() -> Self {
412 Self { packs: Vec::new() }
414 /// Adds another packetiser to the registry.
415 pub fn add_packetiser(&mut self, pack: PacketiserInfo) {
416 self.packs.push(pack);
418 /// Searches for the packetiser for the provided name and returns a function for creating it on success.
419 pub fn find_packetiser(&self, name: &str) -> Option<fn () -> Box<dyn NAPacketiser + Send>> {
420 for &pack in self.packs.iter() {
421 if pack.name == name {
422 return Some(pack.get_packetiser);
427 /// Provides an iterator over currently registered packetiser.
428 pub fn iter(&self) -> std::slice::Iter<PacketiserInfo> {