introduce option handling for demuxers
[nihav.git] / nihav-core / src / codecs / mod.rs
CommitLineData
3ba71779 1//! Decoder interface definitions.
4e8b4f31 2pub use crate::frame::*;
aca89041
KS
3use crate::io::byteio::ByteIOError;
4use crate::io::bitreader::BitReaderError;
5use crate::io::codebook::CodebookError;
77d06de2 6
3ba71779 7/// A list specifying general decoding errors.
77d06de2
KS
8#[derive(Debug,Clone,Copy,PartialEq)]
9#[allow(dead_code)]
10pub enum DecoderError {
3ba71779 11 /// No frame was provided.
6d3bb0b2 12 NoFrame,
3ba71779 13 /// Allocation failed.
e35062e7 14 AllocError,
3ba71779 15 /// Operation requires repeating.
503374e7 16 TryAgain,
3ba71779 17 /// Invalid input data was provided.
77d06de2 18 InvalidData,
3ba71779 19 /// Provided input turned out to be incomplete.
77d06de2 20 ShortData,
3ba71779 21 /// Decoder could not decode provided frame because it references some missing previous frame.
77d06de2 22 MissingReference,
3ba71779 23 /// Feature is not implemented.
77d06de2 24 NotImplemented,
3ba71779 25 /// Some bug in decoder. It should not happen yet it might.
77d06de2
KS
26 Bug,
27}
28
3ba71779 29/// A specialised `Result` type for decoding operations.
cf64af13 30pub type DecoderResult<T> = Result<T, DecoderError>;
77d06de2
KS
31
32impl From<ByteIOError> for DecoderError {
33 fn from(_: ByteIOError) -> Self { DecoderError::ShortData }
34}
35
36impl From<BitReaderError> for DecoderError {
37 fn from(e: BitReaderError) -> Self {
38 match e {
39 BitReaderError::BitstreamEnd => DecoderError::ShortData,
40 _ => DecoderError::InvalidData,
41 }
42 }
43}
44
45impl From<CodebookError> for DecoderError {
46 fn from(_: CodebookError) -> Self { DecoderError::InvalidData }
47}
48
e35062e7
KS
49impl From<AllocatorError> for DecoderError {
50 fn from(_: AllocatorError) -> Self { DecoderError::AllocError }
51}
52
3ba71779 53/// Auxiliary structure for storing data used by decoder but also controlled by the caller.
01613464 54pub struct NADecoderSupport {
3ba71779 55 /// Frame buffer pool for 8-bit or packed video frames.
01613464 56 pub pool_u8: NAVideoBufferPool<u8>,
3ba71779 57 /// Frame buffer pool for 16-bit video frames.
01613464 58 pub pool_u16: NAVideoBufferPool<u16>,
3ba71779 59 /// Frame buffer pool for 32-bit video frames.
01613464
KS
60 pub pool_u32: NAVideoBufferPool<u32>,
61}
62
63impl NADecoderSupport {
3ba71779 64 /// Constructs a new instance of `NADecoderSupport`.
01613464
KS
65 pub fn new() -> Self {
66 Self {
67 pool_u8: NAVideoBufferPool::new(0),
68 pool_u16: NAVideoBufferPool::new(0),
69 pool_u32: NAVideoBufferPool::new(0),
70 }
71 }
72}
73
e243ceb4
KS
74impl Default for NADecoderSupport {
75 fn default() -> Self { Self::new() }
76}
77
3ba71779 78/// Decoder trait.
77d06de2 79pub trait NADecoder {
3ba71779
KS
80 /// Initialises the decoder.
81 ///
82 /// It takes [`NADecoderSupport`] allocated by the caller and `NACodecInfoRef` provided by demuxer.
83 ///
84 /// [`NADecoderSupport`]: ./struct.NADecoderSupport.html
01613464 85 fn init(&mut self, supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()>;
3ba71779 86 /// Decodes a single frame.
01613464 87 fn decode(&mut self, supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef>;
3ba71779 88 /// Tells decoder to clear internal state (e.g. after error or seeking).
f9be4e75 89 fn flush(&mut self);
77d06de2
KS
90}
91
377400a1 92/// Decoder information used during creating a decoder for requested codec.
70259941 93#[derive(Clone,Copy)]
2a4130ba 94pub struct DecoderInfo {
3ba71779 95 /// Short decoder name.
5641dccf 96 pub name: &'static str,
3ba71779 97 /// The function that creates a decoder instance.
08a1fab7 98 pub get_decoder: fn () -> Box<dyn NADecoder + Send>,
70259941
KS
99}
100
3ba71779
KS
101/// Structure for registering known decoders.
102///
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.
e243ceb4 104#[derive(Default)]
5641dccf
KS
105pub struct RegisteredDecoders {
106 decs: Vec<DecoderInfo>,
107}
108
109impl RegisteredDecoders {
3ba71779 110 /// Constructs a new instance of `RegisteredDecoders`.
5641dccf
KS
111 pub fn new() -> Self {
112 Self { decs: Vec::new() }
113 }
3ba71779 114 /// Adds another decoder to the registry.
5641dccf
KS
115 pub fn add_decoder(&mut self, dec: DecoderInfo) {
116 self.decs.push(dec);
117 }
3ba71779 118 /// Searches for the decoder for the provided name and returns a function for creating it on success.
08a1fab7 119 pub fn find_decoder(&self, name: &str) -> Option<fn () -> Box<dyn NADecoder + Send>> {
5641dccf
KS
120 for &dec in self.decs.iter() {
121 if dec.name == name {
122 return Some(dec.get_decoder);
123 }
70259941 124 }
5641dccf 125 None
70259941 126 }
3ba71779 127 /// Provides an iterator over currently registered decoders.
d10c9311
KS
128 pub fn iter(&self) -> std::slice::Iter<DecoderInfo> {
129 self.decs.iter()
130 }
70259941 131}
0b257d9f
KS
132
133/// A list specifying general encoding errors.
134#[derive(Debug,Clone,Copy,PartialEq)]
135#[allow(dead_code)]
136pub enum EncoderError {
137 /// No frame was provided.
138 NoFrame,
139 /// Allocation failed.
140 AllocError,
141 /// Operation requires repeating.
142 TryAgain,
143 /// Input format is not supported by codec.
144 FormatError,
145 /// Invalid input parameters were provided.
146 InvalidParameters,
147 /// Feature is not implemented.
148 NotImplemented,
149 /// Some bug in encoder. It should not happen yet it might.
150 Bug,
151}
152
153/// A specialised `Result` type for decoding operations.
154pub type EncoderResult<T> = Result<T, EncoderError>;
155
156impl From<ByteIOError> for EncoderError {
157 fn from(_: ByteIOError) -> Self { EncoderError::Bug }
158}
159
160/// Encoding parameter flag to force constant bitrate mode.
161pub const ENC_MODE_CBR: u64 = 1 << 0;
162/// Encoding parameter flag to force constant framerate mode.
163pub const ENC_MODE_CFR: u64 = 1 << 1;
164
165/// Encoding parameters.
166#[derive(Clone,Copy,PartialEq)]
167pub struct EncodeParameters {
168 /// Input format.
169 pub format: NACodecTypeInfo,
170 /// Time base numerator. Ignored for audio.
171 pub tb_num: u32,
172 /// Time base denominator. Ignored for audio.
173 pub tb_den: u32,
174 /// Bitrate in kilobits per second.
175 pub bitrate: u32,
176 /// A collection of various boolean encoder settings like CBR mode.
177 ///
178 /// See `ENC_MODE_*` constants for available options.
179 pub flags: u64,
180 /// Encoding quality.
181 pub quality: u8,
182}
183
184impl Default for EncodeParameters {
185 fn default() -> EncodeParameters {
186 EncodeParameters {
187 format: NACodecTypeInfo::None,
188 tb_num: 0,
189 tb_den: 0,
190 bitrate: 0,
191 flags: 0,
192 quality: 0,
193 }
194 }
195}
196
197/// Encoder trait.
198///
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.
201///
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.
207///
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.
211///
212/// Overall encoding loop should look like this:
213/// ```ignore
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
222/// }
223/// }
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
228/// }
229/// ```
230///
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
234pub trait NAEncoder {
235 /// Tries to negotiate input format.
236 ///
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.
239 ///
240 /// # Example
241 /// ```ignore
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;
247 /// break;
248 /// }
249 /// }
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, ...
253 /// ```
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<()>;
263}
264
265/// Encoder information used during creating an encoder for requested codec.
266#[derive(Clone,Copy)]
267pub 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>,
272}
273
274/// Structure for registering known encoders.
275///
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.
277#[derive(Default)]
278pub struct RegisteredEncoders {
279 encs: Vec<EncoderInfo>,
280}
281
282impl RegisteredEncoders {
283 /// Constructs a new instance of `RegisteredEncoders`.
284 pub fn new() -> Self {
285 Self { encs: Vec::new() }
286 }
287 /// Adds another encoder to the registry.
288 pub fn add_encoder(&mut self, enc: EncoderInfo) {
289 self.encs.push(enc);
290 }
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);
296 }
297 }
298 None
299 }
300 /// Provides an iterator over currently registered encoders.
301 pub fn iter(&self) -> std::slice::Iter<EncoderInfo> {
302 self.encs.iter()
303 }
304}
305