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;
7 /// A list specifying general decoding errors.
8 #[derive(Debug,Clone,Copy,PartialEq)]
10 pub enum DecoderError {
11 /// No frame was provided.
13 /// Allocation failed.
15 /// Operation requires repeating.
17 /// Invalid input data was provided.
19 /// Provided input turned out to be incomplete.
21 /// Decoder could not decode provided frame because it references some missing previous frame.
23 /// Feature is not implemented.
25 /// Some bug in decoder. It should not happen yet it might.
29 /// A specialised `Result` type for decoding operations.
30 pub type DecoderResult<T> = Result<T, DecoderError>;
32 impl From<ByteIOError> for DecoderError {
33 fn from(_: ByteIOError) -> Self { DecoderError::ShortData }
36 impl From<BitReaderError> for DecoderError {
37 fn from(e: BitReaderError) -> Self {
39 BitReaderError::BitstreamEnd => DecoderError::ShortData,
40 _ => DecoderError::InvalidData,
45 impl From<CodebookError> for DecoderError {
46 fn from(_: CodebookError) -> Self { DecoderError::InvalidData }
49 impl From<AllocatorError> for DecoderError {
50 fn from(_: AllocatorError) -> Self { DecoderError::AllocError }
53 /// Auxiliary structure for storing data used by decoder but also controlled by the caller.
54 pub struct NADecoderSupport {
55 /// Frame buffer pool for 8-bit or packed video frames.
56 pub pool_u8: NAVideoBufferPool<u8>,
57 /// Frame buffer pool for 16-bit video frames.
58 pub pool_u16: NAVideoBufferPool<u16>,
59 /// Frame buffer pool for 32-bit video frames.
60 pub pool_u32: NAVideoBufferPool<u32>,
63 impl NADecoderSupport {
64 /// Constructs a new instance of `NADecoderSupport`.
65 pub fn new() -> Self {
67 pool_u8: NAVideoBufferPool::new(0),
68 pool_u16: NAVideoBufferPool::new(0),
69 pool_u32: NAVideoBufferPool::new(0),
74 impl Default for NADecoderSupport {
75 fn default() -> Self { Self::new() }
80 /// Initialises the decoder.
82 /// It takes [`NADecoderSupport`] allocated by the caller and `NACodecInfoRef` provided by demuxer.
84 /// [`NADecoderSupport`]: ./struct.NADecoderSupport.html
85 fn init(&mut self, supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()>;
86 /// Decodes a single frame.
87 fn decode(&mut self, supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef>;
88 /// Tells decoder to clear internal state (e.g. after error or seeking).
92 /// Decoder information used during creating a decoder for requested codec.
94 pub struct DecoderInfo {
95 /// Short decoder name.
96 pub name: &'static str,
97 /// The function that creates a decoder instance.
98 pub get_decoder: fn () -> Box<dyn NADecoder + Send>,
101 /// Structure for registering known decoders.
103 /// 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.
105 pub struct RegisteredDecoders {
106 decs: Vec<DecoderInfo>,
109 impl RegisteredDecoders {
110 /// Constructs a new instance of `RegisteredDecoders`.
111 pub fn new() -> Self {
112 Self { decs: Vec::new() }
114 /// Adds another decoder to the registry.
115 pub fn add_decoder(&mut self, dec: DecoderInfo) {
118 /// Searches for the decoder for the provided name and returns a function for creating it on success.
119 pub fn find_decoder(&self, name: &str) -> Option<fn () -> Box<dyn NADecoder + Send>> {
120 for &dec in self.decs.iter() {
121 if dec.name == name {
122 return Some(dec.get_decoder);
127 /// Provides an iterator over currently registered decoders.
128 pub fn iter(&self) -> std::slice::Iter<DecoderInfo> {
133 /// A list specifying general encoding errors.
134 #[derive(Debug,Clone,Copy,PartialEq)]
136 pub enum EncoderError {
137 /// No frame was provided.
139 /// Allocation failed.
141 /// Operation requires repeating.
143 /// Input format is not supported by codec.
145 /// Invalid input parameters were provided.
147 /// Feature is not implemented.
149 /// Some bug in encoder. It should not happen yet it might.
153 /// A specialised `Result` type for decoding operations.
154 pub type EncoderResult<T> = Result<T, EncoderError>;
156 impl From<ByteIOError> for EncoderError {
157 fn from(_: ByteIOError) -> Self { EncoderError::Bug }
160 /// Encoding parameter flag to force constant bitrate mode.
161 pub const ENC_MODE_CBR: u64 = 1 << 0;
162 /// Encoding parameter flag to force constant framerate mode.
163 pub const ENC_MODE_CFR: u64 = 1 << 1;
165 /// Encoding parameters.
166 #[derive(Clone,Copy,PartialEq)]
167 pub struct EncodeParameters {
169 pub format: NACodecTypeInfo,
170 /// Time base numerator. Ignored for audio.
172 /// Time base denominator. Ignored for audio.
174 /// Bitrate in kilobits per second.
176 /// A collection of various boolean encoder settings like CBR mode.
178 /// See `ENC_MODE_*` constants for available options.
180 /// Encoding quality.
184 impl Default for EncodeParameters {
185 fn default() -> EncodeParameters {
187 format: NACodecTypeInfo::None,
199 /// Overall encoding is more complex than decoding.
200 /// There are at least two issues that should be addressed: input format and the need for lookahead.
202 /// Some formats (like MPEG-1 ones) have fixed picture dimensions and framerate, or sampling rate.
203 /// Some formats accept only pictures with dimensions being multiple of eight or sixteen.
204 /// Some audio formats work only with monaural sound.
205 /// 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.
206 /// That is why `NAEncoder` has [`negotiate_format`] function that performs such check and returns what encoder can handle.
208 /// 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.
209 /// That is why encoder has two functions, one for queueing frames for encoding and one for obtaining encoded packets when they are available.
210 /// 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.
212 /// Overall encoding loop should look like this:
214 /// let encoder = ...; // create encoder
215 /// let enc_params = encoder.negotiate_format(input_enc_params)?; // negotiate format
216 /// let output_stream = encoder.init(stream_no, enc_params)?;
217 /// while let Some(frame) = queue.get_frame() {
218 /// // convert to the format encoder expects if required
219 /// encoder.encode(frame)?;
220 /// while let Some(enc_pkt) = encoder.get_packet()? {
221 /// // send encoded packet to a muxer for example
224 /// // retrieve the rest of encoded packets
225 /// encoder.flush()?;
226 /// while let Ok(enc_pkt) = encoder.get_packet()? {
227 /// // send encoded packet to a muxer for example
231 /// [`negotiate_format`]: ./trait.NAEncoder.html#tymethod.negotiate_format
232 /// [`encode`]: ./trait.NAEncoder.html#tymethod.encode
233 /// [`get_packet`]: ./trait.NAEncoder.html#tymethod.get_packet
234 pub trait NAEncoder {
235 /// Tries to negotiate input format.
237 /// This function takes input encoding parameters and returns adjusted encoding parameters if input ones make sense.
238 /// If input parameters are empty then the default parameters are returned.
242 /// let enc_params = [ EncodeParameters {...}, ..., EncodeParameters::default() ];
243 /// let mut target_params = EncodeParameters::default();
244 /// for params in enc_params.iter() {
245 /// if let Ok(dparams) = encoder.negotiate_format(params) {
246 /// target_params = dparams;
250 /// // since negotiate_format(EncodeParameters::default()) will return a valid format, target_params should be valid here
251 /// let stream = encoder.init(stream_id, target_params)?;
252 /// // convert input into format defined in target_params, feed to the encoder, ...
254 fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters>;
255 /// Initialises the encoder.
256 fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef>;
257 /// Takes a single frame for encoding.
258 fn encode(&mut self, frm: &NAFrame) -> EncoderResult<()>;
259 /// Returns encoded packet if available.
260 fn get_packet(&mut self) -> EncoderResult<Option<NAPacket>>;
261 /// Tells encoder to encode all data it currently has.
262 fn flush(&mut self) -> EncoderResult<()>;
265 /// Encoder information used during creating an encoder for requested codec.
266 #[derive(Clone,Copy)]
267 pub struct EncoderInfo {
268 /// Short encoder name.
269 pub name: &'static str,
270 /// The function that creates an encoder instance.
271 pub get_encoder: fn () -> Box<dyn NAEncoder + Send>,
274 /// Structure for registering known encoders.
276 /// 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.
278 pub struct RegisteredEncoders {
279 encs: Vec<EncoderInfo>,
282 impl RegisteredEncoders {
283 /// Constructs a new instance of `RegisteredEncoders`.
284 pub fn new() -> Self {
285 Self { encs: Vec::new() }
287 /// Adds another encoder to the registry.
288 pub fn add_encoder(&mut self, enc: EncoderInfo) {
291 /// Searches for the encoder for the provided name and returns a function for creating it on success.
292 pub fn find_encoder(&self, name: &str) -> Option<fn () -> Box<dyn NAEncoder + Send>> {
293 for &enc in self.encs.iter() {
294 if enc.name == name {
295 return Some(enc.get_encoder);
300 /// Provides an iterator over currently registered encoders.
301 pub fn iter(&self) -> std::slice::Iter<EncoderInfo> {