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