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::*;
8 /// A list specifying general decoding errors.
9 #[derive(Debug,Clone,Copy,PartialEq)]
11 pub enum DecoderError {
12 /// No frame was provided.
14 /// Allocation failed.
16 /// Operation requires repeating.
18 /// Invalid input data was provided.
20 /// Provided input turned out to be incomplete.
22 /// Decoder could not decode provided frame because it references some missing previous frame.
24 /// Feature is not implemented.
26 /// Some bug in decoder. It should not happen yet it might.
30 /// A specialised `Result` type for decoding operations.
31 pub type DecoderResult<T> = Result<T, DecoderError>;
33 impl From<ByteIOError> for DecoderError {
34 fn from(_: ByteIOError) -> Self { DecoderError::ShortData }
37 impl From<BitReaderError> for DecoderError {
38 fn from(e: BitReaderError) -> Self {
40 BitReaderError::BitstreamEnd => DecoderError::ShortData,
41 _ => DecoderError::InvalidData,
46 impl From<CodebookError> for DecoderError {
47 fn from(_: CodebookError) -> Self { DecoderError::InvalidData }
50 impl From<AllocatorError> for DecoderError {
51 fn from(_: AllocatorError) -> Self { DecoderError::AllocError }
54 /// Auxiliary structure for storing data used by decoder but also controlled by the caller.
55 pub struct NADecoderSupport {
56 /// Frame buffer pool for 8-bit or packed video frames.
57 pub pool_u8: NAVideoBufferPool<u8>,
58 /// Frame buffer pool for 16-bit video frames.
59 pub pool_u16: NAVideoBufferPool<u16>,
60 /// Frame buffer pool for 32-bit video frames.
61 pub pool_u32: NAVideoBufferPool<u32>,
64 impl NADecoderSupport {
65 /// Constructs a new instance of `NADecoderSupport`.
66 pub fn new() -> Self {
68 pool_u8: NAVideoBufferPool::new(0),
69 pool_u16: NAVideoBufferPool::new(0),
70 pool_u32: NAVideoBufferPool::new(0),
75 impl Default for NADecoderSupport {
76 fn default() -> Self { Self::new() }
80 pub trait NADecoder: NAOptionHandler {
81 /// Initialises the decoder.
83 /// It takes [`NADecoderSupport`] allocated by the caller and `NACodecInfoRef` provided by demuxer.
85 /// [`NADecoderSupport`]: ./struct.NADecoderSupport.html
86 fn init(&mut self, supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()>;
87 /// Decodes a single frame.
88 fn decode(&mut self, supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef>;
89 /// Tells decoder to clear internal state (e.g. after error or seeking).
93 /// Decoder information used during creating a decoder for requested codec.
95 pub struct DecoderInfo {
96 /// Short decoder name.
97 pub name: &'static str,
98 /// The function that creates a decoder instance.
99 pub get_decoder: fn () -> Box<dyn NADecoder + Send>,
102 /// Structure for registering known decoders.
104 /// It is supposed to be filled using `register_all_codecs()` from some decoders crate and then it can be used to create decoders for the requested codecs.
106 pub struct RegisteredDecoders {
107 decs: Vec<DecoderInfo>,
110 impl RegisteredDecoders {
111 /// Constructs a new instance of `RegisteredDecoders`.
112 pub fn new() -> Self {
113 Self { decs: Vec::new() }
115 /// Adds another decoder to the registry.
116 pub fn add_decoder(&mut self, dec: DecoderInfo) {
119 /// Searches for the decoder for the provided name and returns a function for creating it on success.
120 pub fn find_decoder(&self, name: &str) -> Option<fn () -> Box<dyn NADecoder + Send>> {
121 for &dec in self.decs.iter() {
122 if dec.name == name {
123 return Some(dec.get_decoder);
128 /// Provides an iterator over currently registered decoders.
129 pub fn iter(&self) -> std::slice::Iter<DecoderInfo> {
134 /// A list specifying general encoding errors.
135 #[derive(Debug,Clone,Copy,PartialEq)]
137 pub enum EncoderError {
138 /// No frame was provided.
140 /// Allocation failed.
142 /// Operation requires repeating.
144 /// Input format is not supported by codec.
146 /// Invalid input parameters were provided.
148 /// Feature is not implemented.
150 /// Some bug in encoder. It should not happen yet it might.
154 /// A specialised `Result` type for decoding operations.
155 pub type EncoderResult<T> = Result<T, EncoderError>;
157 impl From<ByteIOError> for EncoderError {
158 fn from(_: ByteIOError) -> Self { EncoderError::Bug }
161 impl From<AllocatorError> for EncoderError {
162 fn from(_: AllocatorError) -> Self { EncoderError::AllocError }
165 /// Encoding parameter flag to force constant bitrate mode.
166 pub const ENC_MODE_CBR: u64 = 1 << 0;
167 /// Encoding parameter flag to force constant framerate mode.
168 pub const ENC_MODE_CFR: u64 = 1 << 1;
170 /// Encoding parameters.
171 #[derive(Clone,Copy,PartialEq)]
172 pub struct EncodeParameters {
174 pub format: NACodecTypeInfo,
175 /// Time base numerator. Ignored for audio.
177 /// Time base denominator. Ignored for audio.
179 /// Bitrate in kilobits per second.
181 /// A collection of various boolean encoder settings like CBR mode.
183 /// See `ENC_MODE_*` constants for available options.
185 /// Encoding quality.
189 impl Default for EncodeParameters {
190 fn default() -> EncodeParameters {
192 format: NACodecTypeInfo::None,
204 /// Overall encoding is more complex than decoding.
205 /// There are at least two issues that should be addressed: input format and the need for lookahead.
207 /// Some formats (like MPEG-1 ones) have fixed picture dimensions and framerate, or sampling rate.
208 /// Some formats accept only pictures with dimensions being multiple of eight or sixteen.
209 /// Some audio formats work only with monaural sound.
210 /// 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.
211 /// That is why `NAEncoder` has [`negotiate_format`] function that performs such check and returns what encoder can handle.
213 /// 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.
214 /// That is why encoder has two functions, one for queueing frames for encoding and one for obtaining encoded packets when they are available.
215 /// 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.
217 /// Overall encoding loop should look like this:
219 /// let encoder = ...; // create encoder
220 /// let enc_params = encoder.negotiate_format(input_enc_params)?; // negotiate format
221 /// let output_stream = encoder.init(stream_no, enc_params)?;
222 /// while let Some(frame) = queue.get_frame() {
223 /// // convert to the format encoder expects if required
224 /// encoder.encode(frame)?;
225 /// while let Some(enc_pkt) = encoder.get_packet()? {
226 /// // send encoded packet to a muxer for example
229 /// // retrieve the rest of encoded packets
230 /// encoder.flush()?;
231 /// while let Ok(enc_pkt) = encoder.get_packet()? {
232 /// // send encoded packet to a muxer for example
236 /// [`negotiate_format`]: ./trait.NAEncoder.html#tymethod.negotiate_format
237 /// [`encode`]: ./trait.NAEncoder.html#tymethod.encode
238 /// [`get_packet`]: ./trait.NAEncoder.html#tymethod.get_packet
239 pub trait NAEncoder: NAOptionHandler {
240 /// Tries to negotiate input format.
242 /// This function takes input encoding parameters and returns adjusted encoding parameters if input ones make sense.
243 /// If input parameters are empty then the default parameters are returned.
247 /// let enc_params = [ EncodeParameters {...}, ..., EncodeParameters::default() ];
248 /// let mut target_params = EncodeParameters::default();
249 /// for params in enc_params.iter() {
250 /// if let Ok(dparams) = encoder.negotiate_format(params) {
251 /// target_params = dparams;
255 /// // since negotiate_format(EncodeParameters::default()) will return a valid format, target_params should be valid here
256 /// let stream = encoder.init(stream_id, target_params)?;
257 /// // convert input into format defined in target_params, feed to the encoder, ...
259 fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters>;
260 /// Initialises the encoder.
261 fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef>;
262 /// Takes a single frame for encoding.
263 fn encode(&mut self, frm: &NAFrame) -> EncoderResult<()>;
264 /// Returns encoded packet if available.
265 fn get_packet(&mut self) -> EncoderResult<Option<NAPacket>>;
266 /// Tells encoder to encode all data it currently has.
267 fn flush(&mut self) -> EncoderResult<()>;
270 /// Encoder information used during creating an encoder for requested codec.
271 #[derive(Clone,Copy)]
272 pub struct EncoderInfo {
273 /// Short encoder name.
274 pub name: &'static str,
275 /// The function that creates an encoder instance.
276 pub get_encoder: fn () -> Box<dyn NAEncoder + Send>,
279 /// Structure for registering known encoders.
281 /// It is supposed to be filled using `register_all_codecs()` from some encoders crate and then it can be used to create encoders for the requested codecs.
283 pub struct RegisteredEncoders {
284 encs: Vec<EncoderInfo>,
287 impl RegisteredEncoders {
288 /// Constructs a new instance of `RegisteredEncoders`.
289 pub fn new() -> Self {
290 Self { encs: Vec::new() }
292 /// Adds another encoder to the registry.
293 pub fn add_encoder(&mut self, enc: EncoderInfo) {
296 /// Searches for the encoder for the provided name and returns a function for creating it on success.
297 pub fn find_encoder(&self, name: &str) -> Option<fn () -> Box<dyn NAEncoder + Send>> {
298 for &enc in self.encs.iter() {
299 if enc.name == name {
300 return Some(enc.get_encoder);
305 /// Provides an iterator over currently registered encoders.
306 pub fn iter(&self) -> std::slice::Iter<EncoderInfo> {