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() }
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 /// Encoding parameter flag to force constant bitrate mode.
162 pub const ENC_MODE_CBR: u64 = 1 << 0;
163 /// Encoding parameter flag to force constant framerate mode.
164 pub const ENC_MODE_CFR: u64 = 1 << 1;
166 /// Encoding parameters.
167 #[derive(Clone,Copy,PartialEq)]
168 pub struct EncodeParameters {
170 pub format: NACodecTypeInfo,
171 /// Time base numerator. Ignored for audio.
173 /// Time base denominator. Ignored for audio.
175 /// Bitrate in kilobits per second.
177 /// A collection of various boolean encoder settings like CBR mode.
179 /// See `ENC_MODE_*` constants for available options.
181 /// Encoding quality.
185 impl Default for EncodeParameters {
186 fn default() -> EncodeParameters {
188 format: NACodecTypeInfo::None,
200 /// Overall encoding is more complex than decoding.
201 /// There are at least two issues that should be addressed: input format and the need for lookahead.
203 /// Some formats (like MPEG-1 ones) have fixed picture dimensions and framerate, or sampling rate.
204 /// Some formats accept only pictures with dimensions being multiple of eight or sixteen.
205 /// Some audio formats work only with monaural sound.
206 /// 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.
207 /// That is why `NAEncoder` has [`negotiate_format`] function that performs such check and returns what encoder can handle.
209 /// 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.
210 /// That is why encoder has two functions, one for queueing frames for encoding and one for obtaining encoded packets when they are available.
211 /// 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.
213 /// Overall encoding loop should look like this:
215 /// let encoder = ...; // create encoder
216 /// let enc_params = encoder.negotiate_format(input_enc_params)?; // negotiate format
217 /// let output_stream = encoder.init(stream_no, enc_params)?;
218 /// while let Some(frame) = queue.get_frame() {
219 /// // convert to the format encoder expects if required
220 /// encoder.encode(frame)?;
221 /// while let Some(enc_pkt) = encoder.get_packet()? {
222 /// // send encoded packet to a muxer for example
225 /// // retrieve the rest of encoded packets
226 /// encoder.flush()?;
227 /// while let Ok(enc_pkt) = encoder.get_packet()? {
228 /// // send encoded packet to a muxer for example
232 /// [`negotiate_format`]: ./trait.NAEncoder.html#tymethod.negotiate_format
233 /// [`encode`]: ./trait.NAEncoder.html#tymethod.encode
234 /// [`get_packet`]: ./trait.NAEncoder.html#tymethod.get_packet
235 pub trait NAEncoder: NAOptionHandler {
236 /// Tries to negotiate input format.
238 /// This function takes input encoding parameters and returns adjusted encoding parameters if input ones make sense.
239 /// If input parameters are empty then the default parameters are returned.
243 /// let enc_params = [ EncodeParameters {...}, ..., EncodeParameters::default() ];
244 /// let mut target_params = EncodeParameters::default();
245 /// for params in enc_params.iter() {
246 /// if let Ok(dparams) = encoder.negotiate_format(params) {
247 /// target_params = dparams;
251 /// // since negotiate_format(EncodeParameters::default()) will return a valid format, target_params should be valid here
252 /// let stream = encoder.init(stream_id, target_params)?;
253 /// // convert input into format defined in target_params, feed to the encoder, ...
255 fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters>;
256 /// Initialises the encoder.
257 fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef>;
258 /// Takes a single frame for encoding.
259 fn encode(&mut self, frm: &NAFrame) -> EncoderResult<()>;
260 /// Returns encoded packet if available.
261 fn get_packet(&mut self) -> EncoderResult<Option<NAPacket>>;
262 /// Tells encoder to encode all data it currently has.
263 fn flush(&mut self) -> EncoderResult<()>;
266 /// Encoder information used during creating an encoder for requested codec.
267 #[derive(Clone,Copy)]
268 pub struct EncoderInfo {
269 /// Short encoder name.
270 pub name: &'static str,
271 /// The function that creates an encoder instance.
272 pub get_encoder: fn () -> Box<dyn NAEncoder + Send>,
275 /// Structure for registering known encoders.
277 /// 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.
279 pub struct RegisteredEncoders {
280 encs: Vec<EncoderInfo>,
283 impl RegisteredEncoders {
284 /// Constructs a new instance of `RegisteredEncoders`.
285 pub fn new() -> Self {
286 Self { encs: Vec::new() }
288 /// Adds another encoder to the registry.
289 pub fn add_encoder(&mut self, enc: EncoderInfo) {
292 /// Searches for the encoder for the provided name and returns a function for creating it on success.
293 pub fn find_encoder(&self, name: &str) -> Option<fn () -> Box<dyn NAEncoder + Send>> {
294 for &enc in self.encs.iter() {
295 if enc.name == name {
296 return Some(enc.get_encoder);
301 /// Provides an iterator over currently registered encoders.
302 pub fn iter(&self) -> std::slice::Iter<EncoderInfo> {