86441e6031ef20dfe118cff8069e98ca8159b11f
[nihav.git] / nihav-core / src / codecs / mod.rs
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::*;
7
8 /// A list specifying general decoding errors.
9 #[derive(Debug,Clone,Copy,PartialEq)]
10 #[allow(dead_code)]
11 pub enum DecoderError {
12 /// No frame was provided.
13 NoFrame,
14 /// Allocation failed.
15 AllocError,
16 /// Operation requires repeating.
17 TryAgain,
18 /// Invalid input data was provided.
19 InvalidData,
20 /// Provided input turned out to be incomplete.
21 ShortData,
22 /// Decoder could not decode provided frame because it references some missing previous frame.
23 MissingReference,
24 /// Feature is not implemented.
25 NotImplemented,
26 /// Some bug in decoder. It should not happen yet it might.
27 Bug,
28 }
29
30 /// A specialised `Result` type for decoding operations.
31 pub type DecoderResult<T> = Result<T, DecoderError>;
32
33 impl From<ByteIOError> for DecoderError {
34 fn from(_: ByteIOError) -> Self { DecoderError::ShortData }
35 }
36
37 impl 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
46 impl From<CodebookError> for DecoderError {
47 fn from(_: CodebookError) -> Self { DecoderError::InvalidData }
48 }
49
50 impl From<AllocatorError> for DecoderError {
51 fn from(_: AllocatorError) -> Self { DecoderError::AllocError }
52 }
53
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>,
62 }
63
64 impl NADecoderSupport {
65 /// Constructs a new instance of `NADecoderSupport`.
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
75 impl Default for NADecoderSupport {
76 fn default() -> Self { Self::new() }
77 }
78
79 /// Decoder trait.
80 pub trait NADecoder {
81 /// Initialises the decoder.
82 ///
83 /// It takes [`NADecoderSupport`] allocated by the caller and `NACodecInfoRef` provided by demuxer.
84 ///
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).
90 fn flush(&mut self);
91 }
92
93 /// Decoder information used during creating a decoder for requested codec.
94 #[derive(Clone,Copy)]
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>,
100 }
101
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.
105 #[derive(Default)]
106 pub struct RegisteredDecoders {
107 decs: Vec<DecoderInfo>,
108 }
109
110 impl RegisteredDecoders {
111 /// Constructs a new instance of `RegisteredDecoders`.
112 pub fn new() -> Self {
113 Self { decs: Vec::new() }
114 }
115 /// Adds another decoder to the registry.
116 pub fn add_decoder(&mut self, dec: DecoderInfo) {
117 self.decs.push(dec);
118 }
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);
124 }
125 }
126 None
127 }
128 /// Provides an iterator over currently registered decoders.
129 pub fn iter(&self) -> std::slice::Iter<DecoderInfo> {
130 self.decs.iter()
131 }
132 }
133
134 /// A list specifying general encoding errors.
135 #[derive(Debug,Clone,Copy,PartialEq)]
136 #[allow(dead_code)]
137 pub 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.
155 pub type EncoderResult<T> = Result<T, EncoderError>;
156
157 impl From<ByteIOError> for EncoderError {
158 fn from(_: ByteIOError) -> Self { EncoderError::Bug }
159 }
160
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;
165
166 /// Encoding parameters.
167 #[derive(Clone,Copy,PartialEq)]
168 pub 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
185 impl 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
235 pub trait NAEncoder: NAOptionHandler {
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)]
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>,
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)]
279 pub struct RegisteredEncoders {
280 encs: Vec<EncoderInfo>,
281 }
282
283 impl 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